diff --git a/.gitattributes b/.gitattributes index 6b6ad6f..709d29f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,2 @@ +* text=auto eol=lf *.h linguist-language=C++ -*.c linguist-language=C++ \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..dadcdef --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,262 @@ +name: CI + +on: + push: + branches: [master, v3] + pull_request: + workflow_call: + workflow_dispatch: + inputs: + jobs: + description: Jobs to run + type: choice + options: [all, linux, windows] + default: all + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +# The vcpkg packages are cached under a new key per run, and saved right after +# they are built, even when a later step fails: a fix cycle never rebuilds +# OpenSSL, curl or libpq. A run saves only when it built new packages. + +jobs: + linux: + name: Linux x64 (manylinux_2_28) + if: github.event_name != 'workflow_dispatch' || inputs.jobs != 'windows' + runs-on: ubuntu-24.04 + timeout-minutes: 90 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ci + file: ci/manylinux.Dockerfile + tags: vcmp-lua-build + load: true + cache-from: type=gha,scope=manylinux + cache-to: type=gha,mode=max,scope=manylinux + + - name: vcpkg cache key + id: key + run: echo "key=vcpkg-linux-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'cmake/triplets/x64-linux-plugin.cmake', 'ci/manylinux.Dockerfile') }}" >> "$GITHUB_OUTPUT" + + - name: Restore vcpkg packages + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/vcpkg-archives + key: ${{ steps.key.outputs.key }}-${{ github.run_id }} + restore-keys: | + ${{ steps.key.outputs.key }}- + vcpkg-linux- + + - name: Count vcpkg packages + id: before + run: echo "count=$(find .cache/vcpkg-archives -type f 2>/dev/null | wc -l)" >> "$GITHUB_OUTPUT" + + - name: Build, test and check the binary + id: build + run: docker run --rm -v "$PWD:/src" -w /src vcmp-lua-build ci/build-linux.sh + + - name: Look for new vcpkg packages + id: after + if: always() && steps.before.outcome == 'success' + run: | + count="$(find .cache/vcpkg-archives -type f 2>/dev/null | wc -l)" + if [ "$count" != "${{ steps.before.outputs.count }}" ]; then + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Save vcpkg packages + if: always() && steps.after.outputs.changed == 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/vcpkg-archives + key: ${{ steps.key.outputs.key }}-${{ github.run_id }} + + - name: MySQL gate + if: steps.build.outcome == 'success' + run: docker compose -f tests/integration/compose.yml --profile gate run --rm mysql-gate + + - name: Stop the MySQL gate services + if: always() + run: docker compose -f tests/integration/compose.yml --profile gate down --volumes + + # The real VC:MP server is not redistributable from this repository: the + # owner sets the repository variables VCMP_SERVER_URL (the Linux x64 + # server zip) and VCMP_SERVER_SHA256. The test itself uses no network + # beyond the compose services. + - name: Integration smoke test (real VC:MP server) + if: steps.build.outcome == 'success' && vars.VCMP_SERVER_URL != '' + env: + VCMP_SERVER_URL: ${{ vars.VCMP_SERVER_URL }} + VCMP_SERVER_SHA256: ${{ vars.VCMP_SERVER_SHA256 }} + run: | + curl -fsSL -o "$RUNNER_TEMP/vcmp-server.zip" "$VCMP_SERVER_URL" + echo "$VCMP_SERVER_SHA256 $RUNNER_TEMP/vcmp-server.zip" | sha256sum -c - + tests/integration/run.sh "$RUNNER_TEMP/vcmp-server.zip" + + - name: Upload logs + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: linux-logs + path: | + .cache/vcpkg/buildtrees/**/*.log + build/linux-release/vcpkg-manifest-install.log + build/linux-release/CMakeFiles/CMakeConfigureLog.yaml + build/linux-release/Testing/Temporary/LastTest.log + if-no-files-found: ignore + + - name: Upload plugin + if: steps.build.outcome == 'success' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: LuaPlugin_x64-linux + path: build/linux-release/bin/LuaPlugin_x64.so + if-no-files-found: error + + linux-asan: + name: Linux x64 unit tests (ASan + UBSan) + # After the release job, so a cold cache is built once and shared. + needs: linux + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ci + file: ci/manylinux.Dockerfile + tags: vcmp-lua-build + load: true + cache-from: type=gha,scope=manylinux + + - name: vcpkg cache key + id: key + run: echo "key=vcpkg-linux-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'cmake/triplets/x64-linux-plugin.cmake', 'ci/manylinux.Dockerfile') }}" >> "$GITHUB_OUTPUT" + + - name: Restore vcpkg packages + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/vcpkg-archives + key: ${{ steps.key.outputs.key }}-${{ github.run_id }} + restore-keys: | + ${{ steps.key.outputs.key }}- + vcpkg-linux- + + - name: Build and run the unit tests under ASan + UBSan + run: docker run --rm -v "$PWD:/src" -w /src vcmp-lua-build ci/test-asan.sh + + - name: Upload logs + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: linux-asan-logs + path: | + build/linux-asan/CMakeFiles/CMakeConfigureLog.yaml + build/linux-asan/Testing/Temporary/LastTest.log + if-no-files-found: ignore + + windows: + name: Windows x64 (MSVC) + if: github.event_name != 'workflow_dispatch' || inputs.jobs != 'linux' + runs-on: windows-2022 + timeout-minutes: 120 + defaults: + run: + shell: pwsh + env: + VCPKG_ROOT: ${{ github.workspace }}\.cache\vcpkg + VCPKG_DEFAULT_BINARY_CACHE: ${{ github.workspace }}\.cache\vcpkg-archives + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: vcpkg cache key + id: key + run: | + "key=vcpkg-windows-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'cmake/triplets/x64-windows-static-plugin.cmake') }}" >> $env:GITHUB_OUTPUT + + - name: Restore vcpkg packages + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/vcpkg-archives + key: ${{ steps.key.outputs.key }}-${{ github.run_id }} + restore-keys: | + ${{ steps.key.outputs.key }}- + vcpkg-windows- + + - name: Bootstrap vcpkg + id: bootstrap + run: | + New-Item -ItemType Directory -Force $env:VCPKG_DEFAULT_BINARY_CACHE | Out-Null + "count=$((Get-ChildItem -Recurse -File $env:VCPKG_DEFAULT_BINARY_CACHE).Count)" >> $env:GITHUB_OUTPUT + ci/bootstrap-vcpkg.ps1 $env:VCPKG_ROOT + + - name: Configure (builds the vcpkg packages) + id: configure + run: cmake --preset windows-release + + - name: Look for new vcpkg packages + id: after + if: always() && steps.bootstrap.outcome == 'success' + run: | + $count = (Get-ChildItem -Recurse -File $env:VCPKG_DEFAULT_BINARY_CACHE).Count + if ($count -ne ${{ steps.bootstrap.outputs.count }}) { "changed=true" >> $env:GITHUB_OUTPUT } + + - name: Save vcpkg packages + if: always() && steps.after.outputs.changed == 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/vcpkg-archives + key: ${{ steps.key.outputs.key }}-${{ github.run_id }} + + - name: Show vcpkg build logs + if: failure() && steps.configure.outcome == 'failure' + run: | + Get-ChildItem .cache/vcpkg/buildtrees -Recurse -Include *-err.log, *-out.log -ErrorAction SilentlyContinue | + ForEach-Object { "==== $($_.FullName)"; Get-Content $_.FullName -Tail 80 } + + - name: Build + id: build + run: cmake --build --preset windows-release + + - name: Test + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + run: ctest --preset windows-release + + - name: Check the binary + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + run: ci/check-binary.ps1 build/windows-release/bin/LuaPlugin_x64.dll + + - name: Upload logs + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: windows-logs + path: | + .cache/vcpkg/buildtrees/**/*.log + build/windows-release/vcpkg-manifest-install.log + build/windows-release/CMakeFiles/CMakeConfigureLog.yaml + build/windows-release/Testing/Temporary/LastTest.log + if-no-files-found: ignore + + - name: Upload plugin + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: LuaPlugin_x64-windows + path: build/windows-release/bin/LuaPlugin_x64.dll + if-no-files-found: error diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index a2d0b7f..0000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1,106 +0,0 @@ -# This is a basic workflow to help you get started with Actions - -name: CI - -# Controls when the workflow will run -on: - # Triggers the workflow on push or pull request events but only for the master branch - push: - branches: [master] - pull_request: - branches: [master] - - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - # This workflow contains a single job called "build" - build-ubuntu: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - uses: actions/checkout@v3 - with: - submodules: recursive - - - name: Setup premake - uses: abel0b/setup-premake@v2.2 - with: - version: "5.0.0-beta1" - - # Runs a set of commands using the runners shell - - name: Run a multi-line script - run: | - premake5 gmake - make config=release - - - uses: actions/upload-artifact@v4 - with: - name: LinuxPlugin-ubuntu-x64 - path: | - **/LuaPlugin*.so - -# build-debian: -# # The type of runner that the job will run on -# runs-on: debian-latest - -# # Steps represent a sequence of tasks that will be executed as part of the job -# steps: -# # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it -# - uses: actions/checkout@v3 -# with: -# submodules: recursive - -# - name: Setup premake -# uses: abel0b/setup-premake@v2.1 -# with: -# version: "5.0.0-beta1" - -# # Runs a set of commands using the runners shell -# - name: Run a multi-line script -# run: | -# premake5 gmake -# make config=release - -# - uses: actions/upload-artifact@v4 -# with: -# name: LinuxPluginx-debian-64 -# path: | -# **/LuaPlugin*.so - - build-windows: - # The type of runner that the job will run on - runs-on: windows-latest - - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - uses: actions/checkout@v3 - with: - submodules: recursive - - - name: Add MSBuild to PATH - uses: microsoft/setup-msbuild@v1.1 - with: - msbuild-architecture: x64 - - - name: Setup premake - uses: abel0b/setup-premake@v2.2 - with: - version: "5.0.0-beta1" - - # Runs a set of commands using the runners shell - - name: Run a multi-line script - run: | - premake5 vs2022 - msbuild.exe VCMPLua.sln -p:Configuration=Release -p:Platform=x64 - - - uses: actions/upload-artifact@v4 - with: - name: WindowsPluginx64 - path: | - **/LuaPlugin*.dll diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..4ab4171 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,78 @@ +name: Release + +on: + push: + tags: ['v*'] + +permissions: + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + version: + name: Check the tag + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.check.outputs.version }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Tag matches the project version + id: check + run: | + version="$(sed -n 's/^ *VERSION \([0-9][0-9.]*\)$/\1/p' CMakeLists.txt | head -n 1)" + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "::error::tag $GITHUB_REF_NAME does not match the version in CMakeLists.txt ($version)" + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + + build: + name: Build and test + needs: version + uses: ./.github/workflows/ci.yml + + release: + name: Draft the release + needs: [version, build] + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + path: artifacts + + - name: Package + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + mkdir dist + package() { + local os="$1" binary="$2" + local stage="stage/VCMP-Lua-$VERSION-$os-x64" + mkdir -p "$stage" + cp "$binary" LICENSE THIRD_PARTY_NOTICES.md THIRD_PARTY_LICENSES.txt examples/luaconfig.lua "$stage/" + (cd stage && zip -r -9 "../dist/VCMP-Lua-$VERSION-$os-x64.zip" "VCMP-Lua-$VERSION-$os-x64") + } + package linux artifacts/LuaPlugin_x64-linux/LuaPlugin_x64.so + package windows artifacts/LuaPlugin_x64-windows/LuaPlugin_x64.dll + (cd dist && sha256sum -- *.zip > SHA256SUMS) + cat dist/SHA256SUMS + + # A draft: the owner checks the plugin on a Windows server, then + # publishes it. + - name: Create the draft release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.version.outputs.version }} + run: | + gh release create "$GITHUB_REF_NAME" dist/* \ + --draft --verify-tag \ + --title "VCMP-Lua $VERSION" \ + --notes "Lua 5.4 scripting plugin for the VC:MP 0.4 server. Upgrading from 2.x: see [docs/MIGRATION-v3.md](https://github.com/${{ github.repository }}/blob/$GITHUB_REF_NAME/docs/MIGRATION-v3.md). Verify downloads with \`sha256sum -c SHA256SUMS\`." diff --git a/.gitignore b/.gitignore index 8f81d1a..6aa8c15 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,23 @@ -.vs/* -backup/* -bin/* -*.vcxproj** -*.sln +# Build trees and local caches +/build/ +/out/ +/.cache/ +/CMakeUserPresets.json + +# IDE files +.vs/ +.vscode/ +.idea/ +*.swp +.DS_Store + +# Never commit binaries +*.so +*.dll +*.exe +*.pdb +*.lib +*.exp +*.a +*.o +*.obj diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index e3ae298..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "VCMP-LUA/vendor/lanes"] - path = VCMP-LUA/vendor/lanes - url = git@github.com:LuaLanes/lanes.git diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..27cf865 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,81 @@ +cmake_minimum_required(VERSION 3.25) + +project(vcmp_lua + VERSION 3.0.0 + DESCRIPTION "Lua 5.4 scripting plugin for the VC:MP 0.4 server" + HOMEPAGE_URL "https://github.com/rasikhq/VCMP-Lua" + LANGUAGES C CXX) + +if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) + message(FATAL_ERROR "VCMP-Lua builds for x64 only.") +endif() + +option(VCMP_LUA_BUILD_TESTS "Build the tests" ON) +option(VCMP_LUA_SANITIZE "Build with AddressSanitizer and UndefinedBehaviorSanitizer (GCC/Clang)" OFF) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) +set(CMAKE_C_VISIBILITY_PRESET hidden) +set(CMAKE_CXX_VISIBILITY_PRESET hidden) +set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) +# Static CRT (/MT), as in the x64-windows-static-plugin triplet. +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") +if(MSVC) + # /EHs, not /EHsc: Lua is compiled as C, and the panic handler throws a + # C++ exception through its frames, so extern "C" calls may throw. + string(REPLACE "/EHsc" "/EHs" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") +endif() + +# Everything compiled here, third-party Lua modules included. The vcpkg +# libraries are not instrumented. Any finding fails the test (no recovery). +if(VCMP_LUA_SANITIZE) + if(MSVC) + message(FATAL_ERROR "VCMP_LUA_SANITIZE is for GCC and Clang") + endif() + add_compile_options(-fsanitize=address,undefined -fno-sanitize-recover=all + -fno-omit-frame-pointer) + add_link_options(-fsanitize=address,undefined) +endif() + +list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake") +include(Hardening) +include(EmbedLua) +include(EmbedFile) + +# Native libraries (vcpkg.json). +find_package(unofficial-lua CONFIG REQUIRED) +if(NOT TARGET lua) + message(FATAL_ERROR "The vcpkg lua port no longer defines the imported target 'lua'.") +endif() +find_package(sol2 CONFIG REQUIRED) +find_package(fmt CONFIG REQUIRED) +find_package(spdlog CONFIG REQUIRED) +find_package(ZLIB REQUIRED) +find_package(OpenSSL REQUIRED) +find_package(CURL REQUIRED) +find_package(unofficial-sqlite3 CONFIG REQUIRED) +find_package(PostgreSQL REQUIRED) +find_package(unofficial-libmariadb CONFIG REQUIRED) + +# Lua modules and header-only libraries from pinned tarballs (cmake/deps). +include(deps/common) +include(deps/luafilesystem) +include(deps/lua-cjson) +include(deps/luasocket) +include(deps/luasql) +include(deps/copas) +include(deps/inspect) +include(deps/digestpp) +if(NOT WIN32) + include(deps/cacert) +endif() + +add_subdirectory(src) + +if(VCMP_LUA_BUILD_TESTS) + enable_testing() + add_subdirectory(tests/unit) + add_subdirectory(tests/host) +endif() diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..785f3dc --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,115 @@ +{ + "version": 6, + "cmakeMinimumRequired": { + "major": 3, + "minor": 25, + "patch": 0 + }, + "configurePresets": [ + { + "name": "vcpkg", + "hidden": true, + "binaryDir": "${sourceDir}/build/${presetName}", + "toolchainFile": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake", + "cacheVariables": { + "VCPKG_MANIFEST_FEATURES": "tests", + "VCPKG_INSTALL_OPTIONS": "--clean-after-build" + } + }, + { + "name": "linux-release", + "displayName": "Linux x64 release (inside ci/manylinux.Dockerfile)", + "inherits": "vcpkg", + "generator": "Ninja", + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Linux" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "VCPKG_TARGET_TRIPLET": "x64-linux-plugin", + "VCPKG_HOST_TRIPLET": "x64-linux-plugin" + } + }, + { + "name": "linux-asan", + "displayName": "Linux x64 unit tests with ASan + UBSan (inside ci/manylinux.Dockerfile)", + "inherits": "linux-release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "VCMP_LUA_SANITIZE": "ON" + } + }, + { + "name": "windows-release", + "displayName": "Windows x64 release (MSVC, static CRT)", + "inherits": "vcpkg", + "generator": "Visual Studio 17 2022", + "architecture": { + "value": "x64", + "strategy": "set" + }, + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Windows" + }, + "cacheVariables": { + "VCPKG_TARGET_TRIPLET": "x64-windows-static-plugin", + "VCPKG_HOST_TRIPLET": "x64-windows-static-plugin" + } + } + ], + "buildPresets": [ + { + "name": "linux-release", + "configurePreset": "linux-release" + }, + { + "name": "linux-asan", + "configurePreset": "linux-asan", + "targets": [ + "vcmp_lua_unit_tests" + ] + }, + { + "name": "windows-release", + "configurePreset": "windows-release", + "configuration": "Release" + } + ], + "testPresets": [ + { + "name": "linux-release", + "configurePreset": "linux-release", + "output": { + "outputOnFailure": true + } + }, + { + "name": "linux-asan", + "configurePreset": "linux-asan", + "output": { + "outputOnFailure": true + }, + "filter": { + "include": { + "label": "unit" + } + }, + "environment": { + "ASAN_OPTIONS": "detect_leaks=1:abort_on_error=1:detect_stack_use_after_return=1:strict_init_order=1", + "UBSAN_OPTIONS": "print_stacktrace=1:halt_on_error=1" + } + }, + { + "name": "windows-release", + "configurePreset": "windows-release", + "configuration": "Release", + "output": { + "outputOnFailure": true + } + } + ] +} diff --git a/VCMP-LUA/vendor/asyncplusplus/LICENSE b/LICENSE similarity index 85% rename from VCMP-LUA/vendor/asyncplusplus/LICENSE rename to LICENSE index f6c080d..762b7be 100644 --- a/VCMP-LUA/vendor/asyncplusplus/LICENSE +++ b/LICENSE @@ -1,4 +1,6 @@ -Copyright (c) 2015 Amanieu d'Antras +MIT License + +Copyright (c) 2020-2026 DizzasTeR and VCMP-Lua contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -7,13 +9,13 @@ 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 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. +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index c100fde..b234059 100644 --- a/README.md +++ b/README.md @@ -1,55 +1,119 @@ -# VCMP Lua Plugin +# VCMP-Lua + +A Lua 5.4 scripting plugin for the Vice City: Multiplayer (VC:MP) 0.4 server. + +- **One file, nothing to install.** `LuaPlugin_x64.dll` (Windows) or + `LuaPlugin_x64.so` (Linux, glibc 2.28 or newer). No runtime libraries, + no DLLs next to it. +- **Batteries included.** SQLite, PostgreSQL and MySQL/MariaDB through + LuaSQL, JSON through lua-cjson, LuaSocket, Copas, LuaFileSystem and + inspect.lua are built in and load with `require`. The plugin adds a + non-blocking HTTPS client (`http`), password hashing (`Hash`) and safe + SQL values (`sql`). +- **Scripts cannot crash the server.** Every handle is checked before use, + arguments are checked, errors are logged with a traceback, and the server + owns entity lifetimes. + +```lua +Event.bind("onPlayerCommand", function(player, command, args) + if command == "car" then + local pos = player.position + local vehicle = Vehicle.create(tonumber(args and args[1]) or 191, player.world, + pos[1] + 3, pos[2], pos[3], player.angle) + player:msg("Your vehicle: " .. vehicle.id) + end +end) +``` -As the name suggests, this plugin provides a scripting API for VCMP in Lua (yay!). Please check out the [WIKI](https://github.com/DizzasTeR/VCMP-Lua/wiki) to learn -about the structure of the plugin (its quite easy!) +## Install + +1. Download the zip for your server's platform from + [Releases](https://github.com/rasikhq/VCMP-Lua/releases) and check it + against `SHA256SUMS`. +2. Copy `LuaPlugin_x64.dll` or `LuaPlugin_x64.so` to the server's + `plugins` directory, and add `LuaPlugin_x64` to the `plugins` line of + `server.cfg`. +3. Copy `luaconfig.lua` to the server directory and list your scripts in + it: + +```lua +return { + scripts = { "lua/main.lua" }, + package_path = "lua/?.lua;lua/?/init.lua", + log = { level = "info" }, +} +``` -## Purpose of this project +## Documentation -The purpose of this project is mainly that I love Lua, and I also love C++, therefore to keep my practice in C++ I decided to work on this plugin with one of my -favorite scripting languages (Lua). +- [API reference](docs/api/README.md) +- [Configuration](docs/configuration.md) +- [Examples](examples/): commands, accounts with hashed passwords in + SQLite, and a JSON webhook over HTTPS +- [Migrating from 2.x](docs/MIGRATION-v3.md) +- [Internals](docs/internals.md): how the server behaves, measured -# The Lua config file +## Building -In your server directory you should place a **luaconfig.ini** file which will allow you to specify some settings the plugin can use. Some of these settings are -optional while some (like specifying atleast 1 script file) is compulsory. +The dependencies come from [vcpkg](https://vcpkg.io) (pinned in +`vcpkg-configuration.json`) and from release tarballs pinned by SHA256 +(`cmake/deps/`). -The file structure is as of right now very simple: +### Linux -```ini -[config] -# Sets experimental mode ON (1) or OFF (0) | Intended for beta-testing and development only. Do not rely for stability -#experimental=1 -# Sets the log level, See the Logger page on Wiki for more information -loglevel=0 -# Sets the log file. This log file will be used to create daily logs and it will log everything logged by Logger class, regardless of level -logfile=DailyLogs.logs +The Linux plugin is built in a pinned manylinux_2_28 image, so it loads on +older distributions too. With Docker: -[modules] -# This is the modules section, here you can opt in to use external modules that the plugin provides. They can be listed and toggled by setting them to a boolean +```bash +docker build --platform linux/amd64 -t vcmp-lua-build -f ci/manylinux.Dockerfile ci +``` + +```bash +docker run --rm --platform linux/amd64 -v "$PWD:/src" -w /src vcmp-lua-build ci/build-linux.sh +``` -#moduleName=[true/false] -lanes=false +The plugin is written to `build/linux-release/bin/LuaPlugin_x64.so`. -[scripts] -# This is the scripts section, here you can specify all your script files that you want to run. +### Windows -# script=path/to/file.lua -script=lua/script.lua +With Visual Studio 2022 (C++ workload) and Git: + +```powershell +ci/bootstrap-vcpkg.ps1 .cache/vcpkg +$env:VCPKG_ROOT = "$PWD/.cache/vcpkg" +cmake --preset windows-release +cmake --build --preset windows-release +ctest --preset windows-release ``` -# Building the plugin +The plugin is written to `build/windows-release/bin/LuaPlugin_x64.dll`. + +## Tests -## Windows +`ctest` runs the unit tests and loads the built plugin into a fake server +(`tests/host`). `ci/test-asan.sh` runs the unit tests under AddressSanitizer +and UndefinedBehaviorSanitizer. The integration smoke test runs the plugin +in the real VC:MP 0.4 Linux server against Postgres 17, MySQL 8.4, +MariaDB 11 and a local TLS server, with Docker; pass it the server +download: + +```bash +tests/integration/run.sh /path/to/VCMP04_server_v46_linux64.zip +``` -To build on Windows, just download the repository and run the win-build.bat file in the premake folder. You should be getting a Visual Studio 2019 solution file +`tests/integration/bindings/run.sh` and `tests/integration/examples/run.sh` +take the same argument and run every binding, and the examples, in the real +server. -**NOTE: You can only build x64 of Lua plugin on Windows for now. Why? Cuz I'm too lazy to setup my environment to compile mariadb for x32 :D** +## Releases -## Linux +Pushing a `v*` tag that matches the version in `CMakeLists.txt` builds and +tests both plugins, and drafts a GitHub release with one zip per platform +(plugin, `luaconfig.lua`, `LICENSE` and the third-party notices and +license texts) and `SHA256SUMS`. -To build on Linux: +## License -- Download/Clone the repository -- Download premake and build it -- Inside the repository, call premake: `path/to/premake5 gmake` -- Now use `make` with your desired `config`: `make config=release` OR `make config=release32` +MIT, see [LICENSE](LICENSE). The bundled libraries are listed in +[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md), with their license texts in +[THIRD_PARTY_LICENSES.txt](THIRD_PARTY_LICENSES.txt). diff --git a/THIRD_PARTY_LICENSES.txt b/THIRD_PARTY_LICENSES.txt new file mode 100644 index 0000000..3e3cdfd --- /dev/null +++ b/THIRD_PARTY_LICENSES.txt @@ -0,0 +1,1144 @@ +License texts of the third-party software in the VCMP-Lua plugin. +See THIRD_PARTY_NOTICES.md for versions and sources. + +=============================================================================== +Lua 5.4 +=============================================================================== + +Copyright © 1994–2016 Lua.org, PUC-Rio. +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. + +=============================================================================== +sol2 +=============================================================================== + +The MIT License (MIT) + +Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors + +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. + +=============================================================================== +spdlog +=============================================================================== + +The MIT License (MIT) + +Copyright (c) 2016 - present, Gabi Melman and spdlog contributors. + +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. + +-- NOTE: Third party dependency used by this software -- +This software depends on the fmt lib (MIT License), +and users must comply to its license: https://raw.githubusercontent.com/fmtlib/fmt/master/LICENSE + +=============================================================================== +{fmt} +=============================================================================== + +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +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. + +=============================================================================== +SQLite +=============================================================================== + +SQLite is in the Public Domain. +http://www.sqlite.org/copyright.html + +=============================================================================== +OpenSSL +=============================================================================== + + + Apache License + Version 2.0, January 2004 + https://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 + +=============================================================================== +libpq (PostgreSQL) +=============================================================================== + +PostgreSQL Database Management System +(also known as Postgres, formerly known as Postgres95) + +Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group + +Portions Copyright (c) 1994, The Regents of the University of California + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose, without fee, and without a written agreement +is hereby granted, provided that the above copyright notice and this +paragraph and the following two paragraphs appear in all copies. + +IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING +LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS +DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + +=============================================================================== +MariaDB Connector/C +=============================================================================== + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + +=============================================================================== +libcurl +=============================================================================== + +COPYING: + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2026, Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +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 OF THIRD PARTY RIGHTS. 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. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. + + +inet_ntop.c and inet_pton.c Notice: + +/* + * Copyright (C) 1996-2022 Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM + * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL + * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING + * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * SPDX-License-Identifier: ISC + */ + +=============================================================================== +zlib +=============================================================================== + +Copyright notice: + + (C) 1995-2026 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +=============================================================================== +LuaFileSystem +=============================================================================== + +Copyright © 2003-2010 Kepler Project. +Copyright © 2010-2022 The LuaFileSystem authors. + +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. + +=============================================================================== +lua-cjson (OpenResty) +=============================================================================== + +Copyright (c) 2010-2012 Mark Pulford + +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. + +=============================================================================== +LuaSocket +=============================================================================== + +Copyright (C) 2004-2022 Diego Nehab + +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. + +=============================================================================== +LuaSQL +=============================================================================== + +Copyright © 2003-2026 The Kepler Project. + +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. + +=============================================================================== +Copas +=============================================================================== + +Copyright © 2005-2013 Kepler Project, 2015-2026 Thijs Schreijer. + +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. + +=============================================================================== +binaryheap.lua +=============================================================================== + +binaryheap.lua by Thijs Schreijer, MIT/X11 license. + +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. + +=============================================================================== +timerwheel.lua +=============================================================================== + +MIT License Terms +================= + +Copyright (c) 2018-2022 Thijs Schreijer. + +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. + +=============================================================================== +inspect.lua +=============================================================================== + +Copyright (c) 2013 Enrique García Cota + +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. + +=============================================================================== +digestpp +=============================================================================== + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to + +=============================================================================== +Mozilla CA certificates (Linux build only) +=============================================================================== + +The built-in CA bundle is Mozilla's root certificate list as extracted by the +curl project (https://curl.se/docs/caextract.html). It is subject to the +Mozilla Public License, version 2.0 (https://mozilla.org/MPL/2.0/). Its +source form is available at https://curl.se/docs/caextract.html. + +=============================================================================== +VC:MP plugin SDK header +=============================================================================== + +Copyright 2011-2019 Ago Allikmaa (maxorator) + +The header is licensed under the Apache License, Version 2.0; +the full text is in the OpenSSL section above. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..ffad6b7 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,40 @@ +# Third-party notices + +The VCMP-Lua plugin binary contains the following software, linked statically. +Versions are pinned in `vcpkg.json`, `vcpkg-configuration.json` and +`cmake/deps/`. + +| Component | Version | License | Source | +|---|---|---|---| +| Lua | 5.4.8 | MIT | https://www.lua.org | +| sol2 | 3.5.0 | MIT | https://github.com/ThePhD/sol2 | +| spdlog | 1.17.0 | MIT | https://github.com/gabime/spdlog | +| {fmt} | 12.2.0 | MIT | https://github.com/fmtlib/fmt | +| SQLite | 3.53.4 | Public domain | https://sqlite.org | +| OpenSSL | 3.6.5 | Apache-2.0 | https://www.openssl.org | +| libpq (PostgreSQL) | 18.4 | PostgreSQL License | https://www.postgresql.org | +| MariaDB Connector/C | 3.4.11 | LGPL-2.1-or-later | https://github.com/mariadb-corporation/mariadb-connector-c | +| libcurl | 8.22.0 | curl License | https://curl.se | +| zlib | 1.3.2 | zlib License | https://zlib.net | +| LuaFileSystem | 1.9.0 | MIT | https://github.com/lunarmodules/luafilesystem | +| lua-cjson (OpenResty) | 2.1.0.19 | MIT | https://github.com/openresty/lua-cjson | +| LuaSocket | 3.1.0 | MIT | https://github.com/lunarmodules/luasocket | +| LuaSQL | 2.8.1 | MIT | https://github.com/lunarmodules/luasql | +| Copas | 4.12.0 | MIT | https://github.com/lunarmodules/copas | +| binaryheap.lua | 0.4 | MIT | https://github.com/Tieske/binaryheap.lua | +| timerwheel.lua | 1.0.2 | MIT | https://github.com/Tieske/timerwheel.lua | +| inspect.lua | 3.1.3 | MIT | https://github.com/kikito/inspect.lua | +| digestpp | 4beae75 | Unlicense (public domain) | https://github.com/kerukuro/digestpp | +| Mozilla CA certificates, as extracted by the curl project (Linux build only) | 2026-09-25 | MPL-2.0 | https://curl.se/docs/caextract.html | +| VC:MP 0.4 plugin SDK header (API 2.1, from SqMod's `module/VCMP/vcmp21.h` at 4a6bfc0) | 0.4 | Apache-2.0 | `third_party/vcmp/vcmp.h` | + +MariaDB Connector/C is licensed under the LGPL. VCMP-Lua links it statically; +the complete source of VCMP-Lua and the build scripts that produce the binary +are public in this repository, so the plugin can be rebuilt against a +modified copy of the library. + +VCMP-Lua patches some of these components at build time; the patches are in +`cmake/deps/patches/`. + +The full license texts are in `THIRD_PARTY_LICENSES.txt`, which +`ci/collect-licenses.py` writes from a configured build tree. diff --git a/VCMP-LUA/Core.cpp b/VCMP-LUA/Core.cpp deleted file mode 100644 index 57a188b..0000000 --- a/VCMP-LUA/Core.cpp +++ /dev/null @@ -1,179 +0,0 @@ -#include "pch.h" -#include "include/utility.h" -#include "vcmpWrap/globalTables.h" -#include "vcmpWrap/vcmpCallbacks.h" - -PluginFuncs* g_Funcs; -PluginCallbacks* g_Calls; -PluginInfo* g_Info; - -sol::state Lua; - -static std::vector s_ScriptFiles; - -void reload_scripts(); -void LoadLuaModule(std::string); - -int my_exception_handler(lua_State* L, sol::optional maybe_exception, sol::string_view description) { - std::cout << "An exception occurred in a function "; - if (maybe_exception) { - std::cout << "(straight from the exception): "; - const std::exception& ex = *maybe_exception; - std::cout << ex.what() << std::endl; - } - else { - std::cout << "(from the description parameter): "; - std::cout.write(description.data(), description.size()); - std::cout << std::endl; - } - return sol::stack::push(L, description); -} - -extern "C" EXPORT unsigned int VcmpPluginInit(PluginFuncs* pluginFuncs, PluginCallbacks* pluginCalls, PluginInfo* pluginInfo) { - g_Funcs = pluginFuncs; - g_Calls = pluginCalls; - g_Info = pluginInfo; - - pluginInfo->pluginVersion = 0x2600; - pluginInfo->apiMajorVersion = PLUGIN_API_MAJOR; - pluginInfo->apiMinorVersion = PLUGIN_API_MINOR; - - CSimpleIni conf(false, true, false); - SI_Error ini_ret = conf.LoadFile("luaconfig.ini"); - - if (ini_ret < 0) { - switch (ini_ret) { - case SI_FAIL: - spdlog::error("Failed to load LUA config file"); - break; - - case SI_NOMEM: - spdlog::error("Failed to load LUA config file (No memory)"); - break; - - case SI_FILE: - spdlog::error("Failed to load LUA config file: {}", std::strerror(errno)); - break; - - default: spdlog::error("Failed to load LUA config file (unknown)"); - } - return false; - } - - Lua.open_libraries(); - - Logger::Init(&Lua, spdlog::level::info); // Set level to info to avoid debug messages or trace to get internal debug messages - - //luaopen_lanes_embedded(Lua.lua_state(), NULL); - - //Lua.set_exception_handler(&my_exception_handler); - - bool experimental_mode = false; - - // Load Configuration - { - std::list configOptions; - if (conf.GetAllKeys("config", configOptions) && configOptions.size() > 0) { - for (const auto& setting : configOptions) { - if (strcmp(setting.pItem, "loglevel") == 0) { - const auto value = conf.GetValue("config", setting.pItem); - try { - unsigned short loglevel = std::stoi(value); - spdlog::info("Reading logging level as: {}", loglevel); - Logger::setLevel(loglevel); - } - catch (const std::exception e) { spdlog::error("Invalid logging level!"); } - } - else if (strcmp(setting.pItem, "logfile") == 0) { - Logger::setFile(conf.GetValue("config", setting.pItem), 0, 0); - } - else if (strcmp(setting.pItem, "experimental") == 0) { - experimental_mode = static_cast(conf.GetValue("config", setting.pItem)); - } - } - } - else spdlog::warn("No configuration settings supplied, using defaults"); - } - - if (experimental_mode) { - Lua["__experimental__"] = true; - spdlog::warn("Experimental features may be really unstable, be very careful when using them."); - Lua["__reload_scripts"] = &reload_scripts; - } - - RegisterClasses(&Lua); - RegisterVCMPCallbacks(); - - // Load Modules - { - std::list modules; - if(conf.GetAllKeys("modules", modules) && modules.size() > 0) { - for(const auto& module : modules) - if(std::string(conf.GetValue("modules", module.pItem)) == "true") - LoadLuaModule(module.pItem); - } - else spdlog::info("No lua modules defined"); - } - - // Load Scripts - { - std::list scripts; - if (conf.GetAllValues("scripts", "script", scripts) && scripts.size() > 0) { - for (auto it = scripts.begin(); it != scripts.end(); it++) { - auto result = Lua.safe_script_file(it->pItem, sol::script_pass_on_error); - s_ScriptFiles.emplace_back(it->pItem); - if (!result.valid()) { - sol::error e = result; - spdlog::error("Failed to load script: {}", e.what()); - } - } - } - else spdlog::error("No Lua scripts specified to load"); - } - - return 1; -} - -void reload_scripts() -{ - spdlog::warn("Reloading scripts..."); - - // Re-trigger some crucial events which simulate a 'restart' - EventManager::Trigger("onServerShutdown"); - // Reset the event handlers to avoid duplication - EventManager::Reset(); - - for (const auto& scriptFile : s_ScriptFiles) - { - spdlog::info("Parsing script: {}", scriptFile); - auto result = Lua.safe_script_file(scriptFile, sol::script_pass_on_error); - if (!result.valid()) { - sol::error e = result; - spdlog::error("Failed to load script: {}", e.what()); - } - } - - // Re-trigger some crucial events which simulate a 'restart' - EventManager::Trigger("onServerInit"); -} - -enum LuaModules { - Invalid = 0, - Lanes -}; - -static std::unordered_map s_LuaModules = { - {"lanes", LuaModules::Lanes} -}; - -void LoadLuaModule(std::string name) { - LuaModules module = s_LuaModules.find(name) != s_LuaModules.end() ? s_LuaModules[name] : LuaModules::Invalid; - - spdlog::info("Loading Lua module: {}", name); - - switch(module) { - case Lanes: - luaopen_lanes_embedded(Lua.lua_state(), NULL); - break; - } -} \ No newline at end of file diff --git a/VCMP-LUA/Makefile b/VCMP-LUA/Makefile deleted file mode 100644 index 9e3b144..0000000 --- a/VCMP-LUA/Makefile +++ /dev/null @@ -1,270 +0,0 @@ -# GNU Make project makefile autogenerated by Premake - -ifndef config - config=release32 -endif - -ifndef verbose - SILENT = @ -endif - -.PHONY: clean prebuild prelink - -ifeq ($(config),release32) - RESCOMP = windres - TARGETDIR = ../bin/Release32-windows-x86/LuaPlugin - TARGET = $(TARGETDIR)/LuaPlugin_x86.dll - OBJDIR = ../bin/interm/Release32-windows-x86/LuaPlugin - DEFINES += -D_x32 -DLIBASYNC_STATIC -DWIN32 - INCLUDES += -I. -Iinclude -IvcmpWrap -Ivendor -Ivendor/Lua -Ivendor/sol -Ivendor/spdlog/include -Ivendor/asyncplusplus/include -Imodules/sqlite3/sqliteCpp/include -Imodules/requests/cpr/include -Imodules/mariadb/include -Imodules/mariadb/include/mysql - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += ../bin/Release32-windows-x86/spdlog/spdlog_x86.lib ../bin/Release32-windows-x86/Lua/Lua_x86.lib ../bin/Release32-windows-x86/asyncplusplus/asyncplusplus_x86.lib ../bin/Release32-windows-x86/module-crypto/module-crypto_x86.lib ../bin/Release32-windows-x86/module-sqliteCpp/module-sqliteCpp_x86.lib ../bin/Release32-windows-x86/module-cpr/module-cpr_x86.lib - LDDEPS += ../bin/Release32-windows-x86/spdlog/spdlog_x86.lib ../bin/Release32-windows-x86/Lua/Lua_x86.lib ../bin/Release32-windows-x86/asyncplusplus/asyncplusplus_x86.lib ../bin/Release32-windows-x86/module-crypto/module-crypto_x86.lib ../bin/Release32-windows-x86/module-sqliteCpp/module-sqliteCpp_x86.lib ../bin/Release32-windows-x86/module-cpr/module-cpr_x86.lib - ALL_LDFLAGS += $(LDFLAGS) -Lmodules/mariadb/lib -L/usr/lib32 -m32 -shared -Wl,--out-implib="../bin/Release32-windows-x86/LuaPlugin/LuaPlugin_x86.lib" -s - LINKCMD = $(CXX) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -ifeq ($(config),release) - RESCOMP = windres - TARGETDIR = ../bin/Release-windows-x86_64/LuaPlugin - TARGET = $(TARGETDIR)/LuaPlugin_x64.dll - OBJDIR = ../bin/interm/Release-windows-x86_64/LuaPlugin - DEFINES += -DLIBASYNC_STATIC -DWIN32 -D_RELEASE - INCLUDES += -I. -Iinclude -IvcmpWrap -Ivendor -Ivendor/Lua -Ivendor/sol -Ivendor/spdlog/include -Ivendor/asyncplusplus/include -Imodules/sqlite3/sqliteCpp/include -Imodules/requests/cpr/include -Imodules/mariadb/include -Imodules/mariadb/include/mysql - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += ../bin/Release-windows-x86_64/spdlog/spdlog_x64.lib ../bin/Release-windows-x86_64/Lua/Lua_x64.lib ../bin/Release-windows-x86_64/asyncplusplus/asyncplusplus_x64.lib ../bin/Release-windows-x86_64/module-crypto/module-crypto_x64.lib ../bin/Release-windows-x86_64/module-sqliteCpp/module-sqliteCpp_x64.lib ../bin/Release-windows-x86_64/module-cpr/module-cpr_x64.lib -lmysqlclient.lib - LDDEPS += ../bin/Release-windows-x86_64/spdlog/spdlog_x64.lib ../bin/Release-windows-x86_64/Lua/Lua_x64.lib ../bin/Release-windows-x86_64/asyncplusplus/asyncplusplus_x64.lib ../bin/Release-windows-x86_64/module-crypto/module-crypto_x64.lib ../bin/Release-windows-x86_64/module-sqliteCpp/module-sqliteCpp_x64.lib ../bin/Release-windows-x86_64/module-cpr/module-cpr_x64.lib - ALL_LDFLAGS += $(LDFLAGS) -Lmodules/mariadb/lib -L/usr/lib64 -m64 -shared -Wl,--out-implib="../bin/Release-windows-x86_64/LuaPlugin/LuaPlugin_x64.lib" -s - LINKCMD = $(CXX) -o "$@" $(OBJECTS) $(RESOURCES) $(ALL_LDFLAGS) $(LIBS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -OBJECTS := \ - $(OBJDIR)/Core.o \ - $(OBJDIR)/ConvertUTF.o \ - $(OBJDIR)/account.o \ - $(OBJDIR)/bind.o \ - $(OBJDIR)/concurrency.o \ - $(OBJDIR)/connection.o \ - $(OBJDIR)/date_time.o \ - $(OBJDIR)/exceptions.o \ - $(OBJDIR)/last_error.o \ - $(OBJDIR)/result_set.o \ - $(OBJDIR)/save_point.o \ - $(OBJDIR)/statement.o \ - $(OBJDIR)/time.o \ - $(OBJDIR)/time_span.o \ - $(OBJDIR)/transaction.o \ - $(OBJDIR)/worker.o \ - $(OBJDIR)/pch.o \ - $(OBJDIR)/Bind1.o \ - $(OBJDIR)/Checkpoint.o \ - $(OBJDIR)/Object.o \ - $(OBJDIR)/Pickup.o \ - $(OBJDIR)/Player.o \ - $(OBJDIR)/Server.o \ - $(OBJDIR)/Stream.o \ - $(OBJDIR)/Vehicle.o \ - $(OBJDIR)/EventManager.o \ - $(OBJDIR)/Remote.o \ - $(OBJDIR)/Hash.o \ - $(OBJDIR)/MySQL.o \ - $(OBJDIR)/MySQLAccount.o \ - $(OBJDIR)/MySQLConnection.o \ - $(OBJDIR)/SqLite.o \ - $(OBJDIR)/Thread.o \ - $(OBJDIR)/TimerManager.o \ - $(OBJDIR)/vcmpTimer.o \ - -RESOURCES := \ - -CUSTOMFILES := \ - -SHELLTYPE := posix -ifeq (.exe,$(findstring .exe,$(ComSpec))) - SHELLTYPE := msdos -endif - -$(TARGET): $(GCH) ${CUSTOMFILES} $(OBJECTS) $(LDDEPS) $(RESOURCES) | $(TARGETDIR) - @echo Linking LuaPlugin - $(SILENT) $(LINKCMD) - $(POSTBUILDCMDS) - -$(CUSTOMFILES): | $(OBJDIR) - -$(TARGETDIR): - @echo Creating $(TARGETDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(TARGETDIR) -else - $(SILENT) mkdir $(subst /,\\,$(TARGETDIR)) -endif - -$(OBJDIR): - @echo Creating $(OBJDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(OBJDIR) -else - $(SILENT) mkdir $(subst /,\\,$(OBJDIR)) -endif - -clean: - @echo Cleaning LuaPlugin -ifeq (posix,$(SHELLTYPE)) - $(SILENT) rm -f $(TARGET) - $(SILENT) rm -rf $(OBJDIR) -else - $(SILENT) if exist $(subst /,\\,$(TARGET)) del $(subst /,\\,$(TARGET)) - $(SILENT) if exist $(subst /,\\,$(OBJDIR)) rmdir /s /q $(subst /,\\,$(OBJDIR)) -endif - -prebuild: - $(PREBUILDCMDS) - -prelink: - $(PRELINKCMDS) - -ifneq (,$(PCH)) -$(OBJECTS): $(GCH) $(PCH) | $(OBJDIR) -$(GCH): $(PCH) | $(OBJDIR) - @echo $(notdir $<) - $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" -else -$(OBJECTS): | $(OBJDIR) -endif - -$(OBJDIR)/Core.o: Core.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/ConvertUTF.o: include/ConvertUTF.c - @echo $(notdir $<) - $(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/account.o: modules/mariadb/src/account.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/bind.o: modules/mariadb/src/bind.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/concurrency.o: modules/mariadb/src/concurrency.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/connection.o: modules/mariadb/src/connection.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/date_time.o: modules/mariadb/src/date_time.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/exceptions.o: modules/mariadb/src/exceptions.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/last_error.o: modules/mariadb/src/last_error.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/result_set.o: modules/mariadb/src/result_set.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/save_point.o: modules/mariadb/src/save_point.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/statement.o: modules/mariadb/src/statement.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/time.o: modules/mariadb/src/time.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/time_span.o: modules/mariadb/src/time_span.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/transaction.o: modules/mariadb/src/transaction.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/worker.o: modules/mariadb/src/worker.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/pch.o: pch.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Bind1.o: vcmpWrap/Classes/Bind.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Checkpoint.o: vcmpWrap/Classes/Checkpoint.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Object.o: vcmpWrap/Classes/Object.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Pickup.o: vcmpWrap/Classes/Pickup.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Player.o: vcmpWrap/Classes/Player.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Server.o: vcmpWrap/Classes/Server.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Stream.o: vcmpWrap/Classes/Stream.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Vehicle.o: vcmpWrap/Classes/Vehicle.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/EventManager.o: vcmpWrap/EventManager/EventManager.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Remote.o: vcmpWrap/Modules/CPR/Remote.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Hash.o: vcmpWrap/Modules/Crypto/Hash.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/MySQL.o: vcmpWrap/Modules/MariaDB/MySQL.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/MySQLAccount.o: vcmpWrap/Modules/MariaDB/MySQLAccount.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/MySQLConnection.o: vcmpWrap/Modules/MariaDB/MySQLConnection.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/SqLite.o: vcmpWrap/Modules/SqLite3/SqLite.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Thread.o: vcmpWrap/Modules/Thread/Thread.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/TimerManager.o: vcmpWrap/Timer/TimerManager.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/vcmpTimer.o: vcmpWrap/Timer/vcmpTimer.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" - --include $(OBJECTS:%.o=%.d) -ifneq (,$(PCH)) - -include $(OBJDIR)/$(notdir $(PCH)).d -endif \ No newline at end of file diff --git a/VCMP-LUA/include/ConvertUTF.c b/VCMP-LUA/include/ConvertUTF.c deleted file mode 100644 index 0575759..0000000 --- a/VCMP-LUA/include/ConvertUTF.c +++ /dev/null @@ -1,539 +0,0 @@ -/* - * Copyright 2001-2004 Unicode, Inc. - * - * Disclaimer - * - * This source code is provided as is by Unicode, Inc. No claims are - * made as to fitness for any particular purpose. No warranties of any - * kind are expressed or implied. The recipient agrees to determine - * applicability of information provided. If this file has been - * purchased on magnetic or optical media from Unicode, Inc., the - * sole remedy for any claim will be exchange of defective media - * within 90 days of receipt. - * - * Limitations on Rights to Redistribute This Code - * - * Unicode, Inc. hereby grants the right to freely use the information - * supplied in this file in the creation of products supporting the - * Unicode Standard, and to make copies of this file in any form - * for internal or external distribution as long as this notice - * remains attached. - */ - -/* --------------------------------------------------------------------- - - Conversions between UTF32, UTF-16, and UTF-8. Source code file. - Author: Mark E. Davis, 1994. - Rev History: Rick McGowan, fixes & updates May 2001. - Sept 2001: fixed const & error conditions per - mods suggested by S. Parent & A. Lillich. - June 2002: Tim Dodd added detection and handling of incomplete - source sequences, enhanced error detection, added casts - to eliminate compiler warnings. - July 2003: slight mods to back out aggressive FFFE detection. - Jan 2004: updated switches in from-UTF8 conversions. - Oct 2004: updated to use UNI_MAX_LEGAL_UTF32 in UTF-32 conversions. - - See the header file "ConvertUTF.h" for complete documentation. - ------------------------------------------------------------------------- */ - - -#include "ConvertUTF.h" -#ifdef CVTUTF_DEBUG -#include -#endif - -static const int halfShift = 10; /* used for shifting by 10 bits */ - -static const UTF32 halfBase = 0x0010000UL; -static const UTF32 halfMask = 0x3FFUL; - -#define UNI_SUR_HIGH_START (UTF32)0xD800 -#define UNI_SUR_HIGH_END (UTF32)0xDBFF -#define UNI_SUR_LOW_START (UTF32)0xDC00 -#define UNI_SUR_LOW_END (UTF32)0xDFFF -#define false 0 -#define true 1 - -/* --------------------------------------------------------------------- */ - -ConversionResult ConvertUTF32toUTF16 ( - const UTF32** sourceStart, const UTF32* sourceEnd, - UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { - ConversionResult result = conversionOK; - const UTF32* source = *sourceStart; - UTF16* target = *targetStart; - while (source < sourceEnd) { - UTF32 ch; - if (target >= targetEnd) { - result = targetExhausted; break; - } - ch = *source++; - if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ - /* UTF-16 surrogate values are illegal in UTF-32; 0xffff or 0xfffe are both reserved values */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - if (flags == strictConversion) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - *target++ = (UTF16)ch; /* normal case */ - } - } else if (ch > UNI_MAX_LEGAL_UTF32) { - if (flags == strictConversion) { - result = sourceIllegal; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - /* target is a character in range 0xFFFF - 0x10FFFF. */ - if (target + 1 >= targetEnd) { - --source; /* Back up source pointer! */ - result = targetExhausted; break; - } - ch -= halfBase; - *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); - *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); - } - } - *sourceStart = source; - *targetStart = target; - return result; -} - -/* --------------------------------------------------------------------- */ - -ConversionResult ConvertUTF16toUTF32 ( - const UTF16** sourceStart, const UTF16* sourceEnd, - UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { - ConversionResult result = conversionOK; - const UTF16* source = *sourceStart; - UTF32* target = *targetStart; - UTF32 ch, ch2; - while (source < sourceEnd) { - const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ - ch = *source++; - /* If we have a surrogate pair, convert to UTF32 first. */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { - /* If the 16 bits following the high surrogate are in the source buffer... */ - if (source < sourceEnd) { - ch2 = *source; - /* If it's a low surrogate, convert to UTF32. */ - if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { - ch = ((ch - UNI_SUR_HIGH_START) << halfShift) - + (ch2 - UNI_SUR_LOW_START) + halfBase; - ++source; - } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } else { /* We don't have the 16 bits following the high surrogate. */ - --source; /* return to the high surrogate */ - result = sourceExhausted; - break; - } - } else if (flags == strictConversion) { - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } - if (target >= targetEnd) { - source = oldSource; /* Back up source pointer! */ - result = targetExhausted; break; - } - *target++ = ch; - } - *sourceStart = source; - *targetStart = target; -#ifdef CVTUTF_DEBUG -if (result == sourceIllegal) { - fprintf(stderr, "ConvertUTF16toUTF32 illegal seq 0x%04x,%04x\n", ch, ch2); - fflush(stderr); -} -#endif - return result; -} - -/* --------------------------------------------------------------------- */ - -/* - * Index into the table below with the first byte of a UTF-8 sequence to - * get the number of trailing bytes that are supposed to follow it. - * Note that *legal* UTF-8 values can't have 4 or 5-bytes. The table is - * left as-is for anyone who may want to do such conversion, which was - * allowed in earlier algorithms. - */ -static const char trailingBytesForUTF8[256] = { - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 -}; - -/* - * Magic values subtracted from a buffer value during UTF8 conversion. - * This table contains as many values as there might be trailing bytes - * in a UTF-8 sequence. - */ -static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, - 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; - -/* - * Once the bits are split out into bytes of UTF-8, this is a mask OR-ed - * into the first byte, depending on how many bytes follow. There are - * as many entries in this table as there are UTF-8 sequence types. - * (I.e., one byte sequence, two byte... etc.). Remember that sequencs - * for *legal* UTF-8 will be 4 or fewer bytes total. - */ -static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - -/* --------------------------------------------------------------------- */ - -/* The interface converts a whole buffer to avoid function-call overhead. - * Constants have been gathered. Loops & conditionals have been removed as - * much as possible for efficiency, in favor of drop-through switches. - * (See "Note A" at the bottom of the file for equivalent code.) - * If your compiler supports it, the "isLegalUTF8" call can be turned - * into an inline function. - */ - -/* --------------------------------------------------------------------- */ - -ConversionResult ConvertUTF16toUTF8 ( - const UTF16** sourceStart, const UTF16* sourceEnd, - UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { - ConversionResult result = conversionOK; - const UTF16* source = *sourceStart; - UTF8* target = *targetStart; - while (source < sourceEnd) { - UTF32 ch; - unsigned short bytesToWrite = 0; - const UTF32 byteMask = 0xBF; - const UTF32 byteMark = 0x80; - const UTF16* oldSource = source; /* In case we have to back up because of target overflow. */ - ch = *source++; - /* If we have a surrogate pair, convert to UTF32 first. */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_HIGH_END) { - /* If the 16 bits following the high surrogate are in the source buffer... */ - if (source < sourceEnd) { - UTF32 ch2 = *source; - /* If it's a low surrogate, convert to UTF32. */ - if (ch2 >= UNI_SUR_LOW_START && ch2 <= UNI_SUR_LOW_END) { - ch = ((ch - UNI_SUR_HIGH_START) << halfShift) - + (ch2 - UNI_SUR_LOW_START) + halfBase; - ++source; - } else if (flags == strictConversion) { /* it's an unpaired high surrogate */ - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } else { /* We don't have the 16 bits following the high surrogate. */ - --source; /* return to the high surrogate */ - result = sourceExhausted; - break; - } - } else if (flags == strictConversion) { - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_LOW_START && ch <= UNI_SUR_LOW_END) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } - /* Figure out how many bytes the result will require */ - if (ch < (UTF32)0x80) { bytesToWrite = 1; - } else if (ch < (UTF32)0x800) { bytesToWrite = 2; - } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; - } else if (ch < (UTF32)0x110000) { bytesToWrite = 4; - } else { bytesToWrite = 3; - ch = UNI_REPLACEMENT_CHAR; - } - - target += bytesToWrite; - if (target > targetEnd) { - source = oldSource; /* Back up source pointer! */ - target -= bytesToWrite; result = targetExhausted; break; - } - switch (bytesToWrite) { /* note: everything falls through. */ - case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 1: *--target = (UTF8)(ch | firstByteMark[bytesToWrite]); - } - target += bytesToWrite; - } - *sourceStart = source; - *targetStart = target; - return result; -} - -/* --------------------------------------------------------------------- */ - -/* - * Utility routine to tell whether a sequence of bytes is legal UTF-8. - * This must be called with the length pre-determined by the first byte. - * If not calling this from ConvertUTF8to*, then the length can be set by: - * length = trailingBytesForUTF8[*source]+1; - * and the sequence is illegal right away if there aren't that many bytes - * available. - * If presented with a length > 4, this returns false. The Unicode - * definition of UTF-8 goes up to 4-byte sequences. - */ - -static Boolean isLegalUTF8(const UTF8 *source, int length) { - UTF8 a; - const UTF8 *srcptr = source+length; - switch (length) { - default: return false; - /* Everything else falls through when "true"... */ - case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; - case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; - case 2: if ((a = (*--srcptr)) > 0xBF) return false; - - switch (*source) { - /* no fall-through in this inner switch */ - case 0xE0: if (a < 0xA0) return false; break; - case 0xED: if (a > 0x9F) return false; break; - case 0xF0: if (a < 0x90) return false; break; - case 0xF4: if (a > 0x8F) return false; break; - default: if (a < 0x80) return false; - } - - case 1: if (*source >= 0x80 && *source < 0xC2) return false; - } - if (*source > 0xF4) return false; - return true; -} - -/* --------------------------------------------------------------------- */ - -/* - * Exported function to return whether a UTF-8 sequence is legal or not. - * This is not used here; it's just exported. - */ -Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) { - int length = trailingBytesForUTF8[*source]+1; - if (source+length > sourceEnd) { - return false; - } - return isLegalUTF8(source, length); -} - -/* --------------------------------------------------------------------- */ - -ConversionResult ConvertUTF8toUTF16 ( - const UTF8** sourceStart, const UTF8* sourceEnd, - UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) { - ConversionResult result = conversionOK; - const UTF8* source = *sourceStart; - UTF16* target = *targetStart; - while (source < sourceEnd) { - UTF32 ch = 0; - unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; - if (source + extraBytesToRead >= sourceEnd) { - result = sourceExhausted; break; - } - /* Do this check whether lenient or strict */ - if (! isLegalUTF8(source, extraBytesToRead+1)) { - result = sourceIllegal; - break; - } - /* - * The cases all fall through. See "Note A" below. - */ - switch (extraBytesToRead) { - case 5: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ - case 4: ch += *source++; ch <<= 6; /* remember, illegal UTF-8 */ - case 3: ch += *source++; ch <<= 6; - case 2: ch += *source++; ch <<= 6; - case 1: ch += *source++; ch <<= 6; - case 0: ch += *source++; - } - ch -= offsetsFromUTF8[extraBytesToRead]; - - if (target >= targetEnd) { - source -= (extraBytesToRead+1); /* Back up source pointer! */ - result = targetExhausted; break; - } - if (ch <= UNI_MAX_BMP) { /* Target is a character <= 0xFFFF */ - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - if (flags == strictConversion) { - source -= (extraBytesToRead+1); /* return to the illegal value itself */ - result = sourceIllegal; - break; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - *target++ = (UTF16)ch; /* normal case */ - } - } else if (ch > UNI_MAX_UTF16) { - if (flags == strictConversion) { - result = sourceIllegal; - source -= (extraBytesToRead+1); /* return to the start */ - break; /* Bail out; shouldn't continue */ - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - /* target is a character in range 0xFFFF - 0x10FFFF. */ - if (target + 1 >= targetEnd) { - source -= (extraBytesToRead+1); /* Back up source pointer! */ - result = targetExhausted; break; - } - ch -= halfBase; - *target++ = (UTF16)((ch >> halfShift) + UNI_SUR_HIGH_START); - *target++ = (UTF16)((ch & halfMask) + UNI_SUR_LOW_START); - } - } - *sourceStart = source; - *targetStart = target; - return result; -} - -/* --------------------------------------------------------------------- */ - -ConversionResult ConvertUTF32toUTF8 ( - const UTF32** sourceStart, const UTF32* sourceEnd, - UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags) { - ConversionResult result = conversionOK; - const UTF32* source = *sourceStart; - UTF8* target = *targetStart; - while (source < sourceEnd) { - UTF32 ch; - unsigned short bytesToWrite = 0; - const UTF32 byteMask = 0xBF; - const UTF32 byteMark = 0x80; - ch = *source++; - if (flags == strictConversion ) { - /* UTF-16 surrogate values are illegal in UTF-32 */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - --source; /* return to the illegal value itself */ - result = sourceIllegal; - break; - } - } - /* - * Figure out how many bytes the result will require. Turn any - * illegally large UTF32 things (> Plane 17) into replacement chars. - */ - if (ch < (UTF32)0x80) { bytesToWrite = 1; - } else if (ch < (UTF32)0x800) { bytesToWrite = 2; - } else if (ch < (UTF32)0x10000) { bytesToWrite = 3; - } else if (ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; - } else { bytesToWrite = 3; - ch = UNI_REPLACEMENT_CHAR; - result = sourceIllegal; - } - - target += bytesToWrite; - if (target > targetEnd) { - --source; /* Back up source pointer! */ - target -= bytesToWrite; result = targetExhausted; break; - } - switch (bytesToWrite) { /* note: everything falls through. */ - case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; - case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); - } - target += bytesToWrite; - } - *sourceStart = source; - *targetStart = target; - return result; -} - -/* --------------------------------------------------------------------- */ - -ConversionResult ConvertUTF8toUTF32 ( - const UTF8** sourceStart, const UTF8* sourceEnd, - UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) { - ConversionResult result = conversionOK; - const UTF8* source = *sourceStart; - UTF32* target = *targetStart; - while (source < sourceEnd) { - UTF32 ch = 0; - unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; - if (source + extraBytesToRead >= sourceEnd) { - result = sourceExhausted; break; - } - /* Do this check whether lenient or strict */ - if (! isLegalUTF8(source, extraBytesToRead+1)) { - result = sourceIllegal; - break; - } - /* - * The cases all fall through. See "Note A" below. - */ - switch (extraBytesToRead) { - case 5: ch += *source++; ch <<= 6; - case 4: ch += *source++; ch <<= 6; - case 3: ch += *source++; ch <<= 6; - case 2: ch += *source++; ch <<= 6; - case 1: ch += *source++; ch <<= 6; - case 0: ch += *source++; - } - ch -= offsetsFromUTF8[extraBytesToRead]; - - if (target >= targetEnd) { - source -= (extraBytesToRead+1); /* Back up the source pointer! */ - result = targetExhausted; break; - } - if (ch <= UNI_MAX_LEGAL_UTF32) { - /* - * UTF-16 surrogate values are illegal in UTF-32, and anything - * over Plane 17 (> 0x10FFFF) is illegal. - */ - if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) { - if (flags == strictConversion) { - source -= (extraBytesToRead+1); /* return to the illegal value itself */ - result = sourceIllegal; - break; - } else { - *target++ = UNI_REPLACEMENT_CHAR; - } - } else { - *target++ = ch; - } - } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */ - result = sourceIllegal; - *target++ = UNI_REPLACEMENT_CHAR; - } - } - *sourceStart = source; - *targetStart = target; - return result; -} - -/* --------------------------------------------------------------------- - - Note A. - The fall-through switches in UTF-8 reading code save a - temp variable, some decrements & conditionals. The switches - are equivalent to the following loop: - { - int tmpBytesToRead = extraBytesToRead+1; - do { - ch += *source++; - --tmpBytesToRead; - if (tmpBytesToRead) ch <<= 6; - } while (tmpBytesToRead > 0); - } - In UTF-8 writing code, the switches on "bytesToWrite" are - similarly unrolled loops. - - --------------------------------------------------------------------- */ \ No newline at end of file diff --git a/VCMP-LUA/include/ConvertUTF.h b/VCMP-LUA/include/ConvertUTF.h deleted file mode 100644 index 2ee5cf9..0000000 --- a/VCMP-LUA/include/ConvertUTF.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2001-2004 Unicode, Inc. - * - * Disclaimer - * - * This source code is provided as is by Unicode, Inc. No claims are - * made as to fitness for any particular purpose. No warranties of any - * kind are expressed or implied. The recipient agrees to determine - * applicability of information provided. If this file has been - * purchased on magnetic or optical media from Unicode, Inc., the - * sole remedy for any claim will be exchange of defective media - * within 90 days of receipt. - * - * Limitations on Rights to Redistribute This Code - * - * Unicode, Inc. hereby grants the right to freely use the information - * supplied in this file in the creation of products supporting the - * Unicode Standard, and to make copies of this file in any form - * for internal or external distribution as long as this notice - * remains attached. - */ - -/* --------------------------------------------------------------------- - - Conversions between UTF32, UTF-16, and UTF-8. Header file. - - Several funtions are included here, forming a complete set of - conversions between the three formats. UTF-7 is not included - here, but is handled in a separate source file. - - Each of these routines takes pointers to input buffers and output - buffers. The input buffers are const. - - Each routine converts the text between *sourceStart and sourceEnd, - putting the result into the buffer between *targetStart and - targetEnd. Note: the end pointers are *after* the last item: e.g. - *(sourceEnd - 1) is the last item. - - The return result indicates whether the conversion was successful, - and if not, whether the problem was in the source or target buffers. - (Only the first encountered problem is indicated.) - - After the conversion, *sourceStart and *targetStart are both - updated to point to the end of last text successfully converted in - the respective buffers. - - Input parameters: - sourceStart - pointer to a pointer to the source buffer. - The contents of this are modified on return so that - it points at the next thing to be converted. - targetStart - similarly, pointer to pointer to the target buffer. - sourceEnd, targetEnd - respectively pointers to the ends of the - two buffers, for overflow checking only. - - These conversion functions take a ConversionFlags argument. When this - flag is set to strict, both irregular sequences and isolated surrogates - will cause an error. When the flag is set to lenient, both irregular - sequences and isolated surrogates are converted. - - Whether the flag is strict or lenient, all illegal sequences will cause - an error return. This includes sequences such as: , , - or in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code - must check for illegal sequences. - - When the flag is set to lenient, characters over 0x10FFFF are converted - to the replacement character; otherwise (when the flag is set to strict) - they constitute an error. - - Output parameters: - The value "sourceIllegal" is returned from some routines if the input - sequence is malformed. When "sourceIllegal" is returned, the source - value will point to the illegal value that caused the problem. E.g., - in UTF-8 when a sequence is malformed, it points to the start of the - malformed sequence. - - Author: Mark E. Davis, 1994. - Rev History: Rick McGowan, fixes & updates May 2001. - Fixes & updates, Sept 2001. - ------------------------------------------------------------------------- */ - -/* --------------------------------------------------------------------- - The following 4 definitions are compiler-specific. - The C standard does not guarantee that wchar_t has at least - 16 bits, so wchar_t is no less portable than unsigned short! - All should be unsigned values to avoid sign extension during - bit mask & shift operations. ------------------------------------------------------------------------- */ - -typedef unsigned int UTF32; /* at least 32 bits */ -typedef unsigned short UTF16; /* at least 16 bits */ -typedef unsigned char UTF8; /* typically 8 bits */ -typedef unsigned char Boolean; /* 0 or 1 */ - -/* Some fundamental constants */ -#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD -#define UNI_MAX_BMP (UTF32)0x0000FFFF -#define UNI_MAX_UTF16 (UTF32)0x0010FFFF -#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF -#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF - -typedef enum { - conversionOK, /* conversion successful */ - sourceExhausted, /* partial character in source, but hit end */ - targetExhausted, /* insuff. room in target for conversion */ - sourceIllegal /* source sequence is illegal/malformed */ -} ConversionResult; - -typedef enum { - strictConversion = 0, - lenientConversion -} ConversionFlags; - -/* This is for C++ and does no harm in C */ -#ifdef __cplusplus -extern "C" { -#endif - -ConversionResult ConvertUTF8toUTF16 ( - const UTF8** sourceStart, const UTF8* sourceEnd, - UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); - -ConversionResult ConvertUTF16toUTF8 ( - const UTF16** sourceStart, const UTF16* sourceEnd, - UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); - -ConversionResult ConvertUTF8toUTF32 ( - const UTF8** sourceStart, const UTF8* sourceEnd, - UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); - -ConversionResult ConvertUTF32toUTF8 ( - const UTF32** sourceStart, const UTF32* sourceEnd, - UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); - -ConversionResult ConvertUTF16toUTF32 ( - const UTF16** sourceStart, const UTF16* sourceEnd, - UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); - -ConversionResult ConvertUTF32toUTF16 ( - const UTF32** sourceStart, const UTF32* sourceEnd, - UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); - -Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd); - -#ifdef __cplusplus -} -#endif - -/* --------------------------------------------------------------------- */ \ No newline at end of file diff --git a/VCMP-LUA/include/SimpleIni.h b/VCMP-LUA/include/SimpleIni.h deleted file mode 100644 index 047c809..0000000 --- a/VCMP-LUA/include/SimpleIni.h +++ /dev/null @@ -1,3442 +0,0 @@ -/** @mainpage - - -
Library SimpleIni -
File SimpleIni.h -
Author Brodie Thiesfield [code at jellycan dot com] -
Source https://github.com/brofield/simpleini -
Version 4.17 -
- - Jump to the @link CSimpleIniTempl CSimpleIni @endlink interface documentation. - - @section intro INTRODUCTION - - This component allows an INI-style configuration file to be used on both - Windows and Linux/Unix. It is fast, simple and source code using this - component will compile unchanged on either OS. - - - @section features FEATURES - - - MIT Licence allows free use in all software (including GPL and commercial) - - multi-platform (Windows CE/9x/NT..10/etc, Linux, MacOSX, Unix) - - loading and saving of INI-style configuration files - - configuration files can have any newline format on all platforms - - liberal acceptance of file format - - key/values with no section - - removal of whitespace around sections, keys and values - - support for multi-line values (values with embedded newline characters) - - optional support for multiple keys with the same name - - optional case-insensitive sections and keys (for ASCII characters only) - - saves files with sections and keys in the same order as they were loaded - - preserves comments on the file, section and keys where possible. - - supports both char or wchar_t programming interfaces - - supports both MBCS (system locale) and UTF-8 file encodings - - system locale does not need to be UTF-8 on Linux/Unix to load UTF-8 file - - support for non-ASCII characters in section, keys, values and comments - - support for non-standard character types or file encodings - via user-written converter classes - - support for adding/modifying values programmatically - - compiles cleanly in the following compilers: - - Windows/VC6 (warning level 3) - - Windows/VC.NET 2003 (warning level 4) - - Windows/VC 2005 (warning level 4) - - Linux/gcc (-Wall) - - - @section usage USAGE SUMMARY - - -# Define the appropriate symbol for the converter you wish to use and - include the SimpleIni.h header file. If no specific converter is defined - then the default converter is used. The default conversion mode uses - SI_CONVERT_WIN32 on Windows and SI_CONVERT_GENERIC on all other - platforms. If you are using ICU then SI_CONVERT_ICU is supported on all - platforms. - -# Declare an instance the appropriate class. Note that the following - definitions are just shortcuts for commonly used types. Other types - (PRUnichar, unsigned short, unsigned char) are also possible. - -
Interface Case-sensitive Load UTF-8 Load MBCS Typedef -
SI_CONVERT_GENERIC -
char No Yes Yes #1 CSimpleIniA -
char Yes Yes Yes CSimpleIniCaseA -
wchar_t No Yes Yes CSimpleIniW -
wchar_t Yes Yes Yes CSimpleIniCaseW -
SI_CONVERT_WIN32 -
char No No #2 Yes CSimpleIniA -
char Yes Yes Yes CSimpleIniCaseA -
wchar_t No Yes Yes CSimpleIniW -
wchar_t Yes Yes Yes CSimpleIniCaseW -
SI_CONVERT_ICU -
char No Yes Yes CSimpleIniA -
char Yes Yes Yes CSimpleIniCaseA -
UChar No Yes Yes CSimpleIniW -
UChar Yes Yes Yes CSimpleIniCaseW -
- #1 On Windows you are better to use CSimpleIniA with SI_CONVERT_WIN32.
- #2 Only affects Windows. On Windows this uses MBCS functions and - so may fold case incorrectly leading to uncertain results. - -# Call LoadData() or LoadFile() to load and parse the INI configuration file - -# Access and modify the data of the file using the following functions - -
GetAllSections Return all section names -
GetAllKeys Return all key names within a section -
GetAllValues Return all values within a section & key -
GetSection Return all key names and values in a section -
GetSectionSize Return the number of keys in a section -
GetValue Return a value for a section & key -
SetValue Add or update a value for a section & key -
Delete Remove a section, or a key from a section -
- -# Call Save() or SaveFile() to save the INI configuration data - - @section iostreams IO STREAMS - - SimpleIni supports reading from and writing to STL IO streams. Enable this - by defining SI_SUPPORT_IOSTREAMS before including the SimpleIni.h header - file. Ensure that if the streams are backed by a file (e.g. ifstream or - ofstream) then the flag ios_base::binary has been used when the file was - opened. - - @section multiline MULTI-LINE VALUES - - Values that span multiple lines are created using the following format. - -
-        key = <<
-
-    Note the following:
-    - The text used for ENDTAG can be anything and is used to find
-      where the multi-line text ends.
-    - The newline after ENDTAG in the start tag, and the newline
-      before ENDTAG in the end tag is not included in the data value.
-    - The ending tag must be on it's own line with no whitespace before
-      or after it.
-    - The multi-line value is modified at load so that each line in the value
-      is delimited by a single '\\n' character on all platforms. At save time
-      it will be converted into the newline format used by the current
-      platform.
-
-    @section comments COMMENTS
-
-    Comments are preserved in the file within the following restrictions:
-    - Every file may have a single "file comment". It must start with the
-      first character in the file, and will end with the first non-comment
-      line in the file.
-    - Every section may have a single "section comment". It will start
-      with the first comment line following the file comment, or the last
-      data entry. It ends at the beginning of the section.
-    - Every key may have a single "key comment". This comment will start
-      with the first comment line following the section start, or the file
-      comment if there is no section name.
-    - Comments are set at the time that the file, section or key is first
-      created. The only way to modify a comment on a section or a key is to
-      delete that entry and recreate it with the new comment. There is no
-      way to change the file comment.
-
-    @section save SAVE ORDER
-
-    The sections and keys are written out in the same order as they were
-    read in from the file. Sections and keys added to the data after the
-    file has been loaded will be added to the end of the file when it is
-    written. There is no way to specify the location of a section or key
-    other than in first-created, first-saved order.
-
-    @section notes NOTES
-
-    - To load UTF-8 data on Windows 95, you need to use Microsoft Layer for
-      Unicode, or SI_CONVERT_GENERIC, or SI_CONVERT_ICU.
-    - When using SI_CONVERT_GENERIC, ConvertUTF.c must be compiled and linked.
-    - When using SI_CONVERT_ICU, ICU header files must be on the include
-      path and icuuc.lib must be linked in.
-    - To load a UTF-8 file on Windows AND expose it with SI_CHAR == char,
-      you should use SI_CONVERT_GENERIC.
-    - The collation (sorting) order used for sections and keys returned from
-      iterators is NOT DEFINED. If collation order of the text is important
-      then it should be done yourself by either supplying a replacement
-      SI_STRLESS class, or by sorting the strings external to this library.
-    - Usage of the  header on Windows can be disabled by defining
-      SI_NO_MBCS. This is defined automatically on Windows CE platforms.
-    - Not thread-safe so manage your own locking
-
-    @section contrib CONTRIBUTIONS
-    
-    - 2010/05/03: Tobias Gehrig: added GetDoubleValue()
-
-    @section licence MIT LICENCE
-
-    The licence text below is the boilerplate "MIT Licence" used from:
-    http://www.opensource.org/licenses/mit-license.php
-
-    Copyright (c) 2006-2012, Brodie Thiesfield
-
-    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.
-*/
-
-#ifndef INCLUDED_SimpleIni_h
-#define INCLUDED_SimpleIni_h
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-# pragma once
-#endif
-
-// Disable these warnings in MSVC:
-//  4127 "conditional expression is constant" as the conversion classes trigger
-//  it with the statement if (sizeof(SI_CHAR) == sizeof(char)). This test will
-//  be optimized away in a release build.
-//  4503 'insert' : decorated name length exceeded, name was truncated
-//  4702 "unreachable code" as the MS STL header causes it in release mode.
-//  Again, the code causing the warning will be cleaned up by the compiler.
-//  4786 "identifier truncated to 256 characters" as this is thrown hundreds
-//  of times VC6 as soon as STL is used.
-#ifdef _MSC_VER
-# pragma warning (push)
-# pragma warning (disable: 4127 4503 4702 4786)
-#endif
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#ifdef SI_SUPPORT_IOSTREAMS
-# include 
-#endif // SI_SUPPORT_IOSTREAMS
-
-#ifdef _DEBUG
-# ifndef assert
-#  include 
-# endif
-# define SI_ASSERT(x)   assert(x)
-#else
-# define SI_ASSERT(x)
-#endif
-
-enum SI_Error {
-    SI_OK       =  0,   //!< No error
-    SI_UPDATED  =  1,   //!< An existing value was updated
-    SI_INSERTED =  2,   //!< A new value was inserted
-
-    // note: test for any error with (retval < 0)
-    SI_FAIL     = -1,   //!< Generic failure
-    SI_NOMEM    = -2,   //!< Out of memory error
-    SI_FILE     = -3    //!< File error (see errno for detail error)
-};
-
-#define SI_UTF8_SIGNATURE     "\xEF\xBB\xBF"
-
-#ifdef _WIN32
-# define SI_NEWLINE_A   "\r\n"
-# define SI_NEWLINE_W   L"\r\n"
-#else // !_WIN32
-# define SI_NEWLINE_A   "\n"
-# define SI_NEWLINE_W   L"\n"
-#endif // _WIN32
-
-#if defined(SI_CONVERT_ICU)
-# include 
-#endif
-
-#if defined(_WIN32)
-# define SI_HAS_WIDE_FILE
-# define SI_WCHAR_T     wchar_t
-#elif defined(SI_CONVERT_ICU)
-# define SI_HAS_WIDE_FILE
-# define SI_WCHAR_T     UChar
-#endif
-
-
-// ---------------------------------------------------------------------------
-//                              MAIN TEMPLATE CLASS
-// ---------------------------------------------------------------------------
-
-/** Simple INI file reader.
-
-    This can be instantiated with the choice of unicode or native characterset,
-    and case sensitive or insensitive comparisons of section and key names.
-    The supported combinations are pre-defined with the following typedefs:
-
-    
-        
Interface Case-sensitive Typedef -
char No CSimpleIniA -
char Yes CSimpleIniCaseA -
wchar_t No CSimpleIniW -
wchar_t Yes CSimpleIniCaseW -
- - Note that using other types for the SI_CHAR is supported. For instance, - unsigned char, unsigned short, etc. Note that where the alternative type - is a different size to char/wchar_t you may need to supply new helper - classes for SI_STRLESS and SI_CONVERTER. - */ -template -class CSimpleIniTempl -{ -public: - typedef SI_CHAR SI_CHAR_T; - - /** key entry */ - struct Entry { - const SI_CHAR * pItem; - const SI_CHAR * pComment; - int nOrder; - - Entry(const SI_CHAR * a_pszItem = NULL, int a_nOrder = 0) - : pItem(a_pszItem) - , pComment(NULL) - , nOrder(a_nOrder) - { } - Entry(const SI_CHAR * a_pszItem, const SI_CHAR * a_pszComment, int a_nOrder) - : pItem(a_pszItem) - , pComment(a_pszComment) - , nOrder(a_nOrder) - { } - Entry(const Entry & rhs) { operator=(rhs); } - Entry & operator=(const Entry & rhs) { - pItem = rhs.pItem; - pComment = rhs.pComment; - nOrder = rhs.nOrder; - return *this; - } - -#if defined(_MSC_VER) && _MSC_VER <= 1200 - /** STL of VC6 doesn't allow me to specify my own comparator for list::sort() */ - bool operator<(const Entry & rhs) const { return LoadOrder()(*this, rhs); } - bool operator>(const Entry & rhs) const { return LoadOrder()(rhs, *this); } -#endif - - /** Strict less ordering by name of key only */ - struct KeyOrder { - bool operator()(const Entry & lhs, const Entry & rhs) const { - const static SI_STRLESS isLess = SI_STRLESS(); - return isLess(lhs.pItem, rhs.pItem); - } - }; - - /** Strict less ordering by order, and then name of key */ - struct LoadOrder { - bool operator()(const Entry & lhs, const Entry & rhs) const { - if (lhs.nOrder != rhs.nOrder) { - return lhs.nOrder < rhs.nOrder; - } - return KeyOrder()(lhs.pItem, rhs.pItem); - } - }; - }; - - /** map keys to values */ - typedef std::multimap TKeyVal; - - /** map sections to key/value map */ - typedef std::map TSection; - - /** set of dependent string pointers. Note that these pointers are - dependent on memory owned by CSimpleIni. - */ - typedef std::list TNamesDepend; - - /** interface definition for the OutputWriter object to pass to Save() - in order to output the INI file data. - */ - class OutputWriter { - public: - OutputWriter() { } - virtual ~OutputWriter() { } - virtual void Write(const char * a_pBuf) = 0; - private: - OutputWriter(const OutputWriter &); // disable - OutputWriter & operator=(const OutputWriter &); // disable - }; - - /** OutputWriter class to write the INI data to a file */ - class FileWriter : public OutputWriter { - FILE * m_file; - public: - FileWriter(FILE * a_file) : m_file(a_file) { } - void Write(const char * a_pBuf) { - fputs(a_pBuf, m_file); - } - private: - FileWriter(const FileWriter &); // disable - FileWriter & operator=(const FileWriter &); // disable - }; - - /** OutputWriter class to write the INI data to a string */ - class StringWriter : public OutputWriter { - std::string & m_string; - public: - StringWriter(std::string & a_string) : m_string(a_string) { } - void Write(const char * a_pBuf) { - m_string.append(a_pBuf); - } - private: - StringWriter(const StringWriter &); // disable - StringWriter & operator=(const StringWriter &); // disable - }; - -#ifdef SI_SUPPORT_IOSTREAMS - /** OutputWriter class to write the INI data to an ostream */ - class StreamWriter : public OutputWriter { - std::ostream & m_ostream; - public: - StreamWriter(std::ostream & a_ostream) : m_ostream(a_ostream) { } - void Write(const char * a_pBuf) { - m_ostream << a_pBuf; - } - private: - StreamWriter(const StreamWriter &); // disable - StreamWriter & operator=(const StreamWriter &); // disable - }; -#endif // SI_SUPPORT_IOSTREAMS - - /** Characterset conversion utility class to convert strings to the - same format as is used for the storage. - */ - class Converter : private SI_CONVERTER { - public: - Converter(bool a_bStoreIsUtf8) : SI_CONVERTER(a_bStoreIsUtf8) { - m_scratch.resize(1024); - } - Converter(const Converter & rhs) { operator=(rhs); } - Converter & operator=(const Converter & rhs) { - m_scratch = rhs.m_scratch; - return *this; - } - bool ConvertToStore(const SI_CHAR * a_pszString) { - size_t uLen = SI_CONVERTER::SizeToStore(a_pszString); - if (uLen == (size_t)(-1)) { - return false; - } - while (uLen > m_scratch.size()) { - m_scratch.resize(m_scratch.size() * 2); - } - return SI_CONVERTER::ConvertToStore( - a_pszString, - const_cast(m_scratch.data()), - m_scratch.size()); - } - const char * Data() { return m_scratch.data(); } - private: - std::string m_scratch; - }; - -public: - /*-----------------------------------------------------------------------*/ - - /** Default constructor. - - @param a_bIsUtf8 See the method SetUnicode() for details. - @param a_bMultiKey See the method SetMultiKey() for details. - @param a_bMultiLine See the method SetMultiLine() for details. - */ - CSimpleIniTempl( - bool a_bIsUtf8 = false, - bool a_bMultiKey = false, - bool a_bMultiLine = false - ); - - /** Destructor */ - ~CSimpleIniTempl(); - - /** Deallocate all memory stored by this object */ - void Reset(); - - /** Has any data been loaded */ - bool IsEmpty() const { return m_data.empty(); } - - /*-----------------------------------------------------------------------*/ - /** @{ @name Settings */ - - /** Set the storage format of the INI data. This affects both the loading - and saving of the INI data using all of the Load/Save API functions. - This value cannot be changed after any INI data has been loaded. - - If the file is not set to Unicode (UTF-8), then the data encoding is - assumed to be the OS native encoding. This encoding is the system - locale on Linux/Unix and the legacy MBCS encoding on Windows NT/2K/XP. - If the storage format is set to Unicode then the file will be loaded - as UTF-8 encoded data regardless of the native file encoding. If - SI_CHAR == char then all of the char* parameters take and return UTF-8 - encoded data regardless of the system locale. - - \param a_bIsUtf8 Assume UTF-8 encoding for the source? - */ - void SetUnicode(bool a_bIsUtf8 = true) { - if (!m_pData) m_bStoreIsUtf8 = a_bIsUtf8; - } - - /** Get the storage format of the INI data. */ - bool IsUnicode() const { return m_bStoreIsUtf8; } - - /** Should multiple identical keys be permitted in the file. If set to false - then the last value encountered will be used as the value of the key. - If set to true, then all values will be available to be queried. For - example, with the following input: - -
-        [section]
-        test=value1
-        test=value2
-        
- - Then with SetMultiKey(true), both of the values "value1" and "value2" - will be returned for the key test. If SetMultiKey(false) is used, then - the value for "test" will only be "value2". This value may be changed - at any time. - - \param a_bAllowMultiKey Allow multi-keys in the source? - */ - void SetMultiKey(bool a_bAllowMultiKey = true) { - m_bAllowMultiKey = a_bAllowMultiKey; - } - - /** Get the storage format of the INI data. */ - bool IsMultiKey() const { return m_bAllowMultiKey; } - - /** Should data values be permitted to span multiple lines in the file. If - set to false then the multi-line construct << - SI_CHAR FORMAT - char same format as when loaded (MBCS or UTF-8) - wchar_t UTF-8 - other UTF-8 - - - Note that comments from the original data is preserved as per the - documentation on comments. The order of the sections and values - from the original file will be preserved. - - Any data prepended or appended to the output device must use the the - same format (MBCS or UTF-8). You may use the GetConverter() method to - convert text to the correct format regardless of the output format - being used by SimpleIni. - - To add a BOM to UTF-8 data, write it out manually at the very beginning - like is done in SaveFile when a_bUseBOM is true. - - @param a_oOutput Output writer to write the data to. - - @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in - UTF-8 format. If it is not UTF-8 then this value is - ignored. Do not set this to true if anything has - already been written to the OutputWriter. - - @return SI_Error See error definitions - */ - SI_Error Save( - OutputWriter & a_oOutput, - bool a_bAddSignature = false - ) const; - -#ifdef SI_SUPPORT_IOSTREAMS - /** Save the INI data to an ostream. See Save() for details. - - @param a_ostream String to have the INI data appended to. - - @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in - UTF-8 format. If it is not UTF-8 then this value is - ignored. Do not set this to true if anything has - already been written to the stream. - - @return SI_Error See error definitions - */ - SI_Error Save( - std::ostream & a_ostream, - bool a_bAddSignature = false - ) const - { - StreamWriter writer(a_ostream); - return Save(writer, a_bAddSignature); - } -#endif // SI_SUPPORT_IOSTREAMS - - /** Append the INI data to a string. See Save() for details. - - @param a_sBuffer String to have the INI data appended to. - - @param a_bAddSignature Prepend the UTF-8 BOM if the output data is in - UTF-8 format. If it is not UTF-8 then this value is - ignored. Do not set this to true if anything has - already been written to the string. - - @return SI_Error See error definitions - */ - SI_Error Save( - std::string & a_sBuffer, - bool a_bAddSignature = false - ) const - { - StringWriter writer(a_sBuffer); - return Save(writer, a_bAddSignature); - } - - /*-----------------------------------------------------------------------*/ - /** @} - @{ @name Accessing INI Data */ - - /** Retrieve all section names. The list is returned as an STL vector of - names and can be iterated or searched as necessary. Note that the - sort order of the returned strings is NOT DEFINED. You can sort - the names into the load order if desired. Search this file for ".sort" - for an example. - - NOTE! This structure contains only pointers to strings. The actual - string data is stored in memory owned by CSimpleIni. Ensure that the - CSimpleIni object is not destroyed or Reset() while these pointers - are in use! - - @param a_names Vector that will receive all of the section - names. See note above! - */ - void GetAllSections( - TNamesDepend & a_names - ) const; - - /** Retrieve all unique key names in a section. The sort order of the - returned strings is NOT DEFINED. You can sort the names into the load - order if desired. Search this file for ".sort" for an example. Only - unique key names are returned. - - NOTE! This structure contains only pointers to strings. The actual - string data is stored in memory owned by CSimpleIni. Ensure that the - CSimpleIni object is not destroyed or Reset() while these strings - are in use! - - @param a_pSection Section to request data for - @param a_names List that will receive all of the key - names. See note above! - - @return true Section was found. - @return false Matching section was not found. - */ - bool GetAllKeys( - const SI_CHAR * a_pSection, - TNamesDepend & a_names - ) const; - - /** Retrieve all values for a specific key. This method can be used when - multiple keys are both enabled and disabled. Note that the sort order - of the returned strings is NOT DEFINED. You can sort the names into - the load order if desired. Search this file for ".sort" for an example. - - NOTE! The returned values are pointers to string data stored in memory - owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed - or Reset while you are using this pointer! - - @param a_pSection Section to search - @param a_pKey Key to search for - @param a_values List to return if the key is not found - - @return true Key was found. - @return false Matching section/key was not found. - */ - bool GetAllValues( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - TNamesDepend & a_values - ) const; - - /** Query the number of keys in a specific section. Note that if multiple - keys are enabled, then this value may be different to the number of - keys returned by GetAllKeys. - - @param a_pSection Section to request data for - - @return -1 Section does not exist in the file - @return >=0 Number of keys in the section - */ - int GetSectionSize( - const SI_CHAR * a_pSection - ) const; - - /** Retrieve all key and value pairs for a section. The data is returned - as a pointer to an STL map and can be iterated or searched as - desired. Note that multiple entries for the same key may exist when - multiple keys have been enabled. - - NOTE! This structure contains only pointers to strings. The actual - string data is stored in memory owned by CSimpleIni. Ensure that the - CSimpleIni object is not destroyed or Reset() while these strings - are in use! - - @param a_pSection Name of the section to return - @return boolean Was a section matching the supplied - name found. - */ - const TKeyVal * GetSection( - const SI_CHAR * a_pSection - ) const; - - /** Retrieve the value for a specific key. If multiple keys are enabled - (see SetMultiKey) then only the first value associated with that key - will be returned, see GetAllValues for getting all values with multikey. - - NOTE! The returned value is a pointer to string data stored in memory - owned by CSimpleIni. Ensure that the CSimpleIni object is not destroyed - or Reset while you are using this pointer! - - @param a_pSection Section to search - @param a_pKey Key to search for - @param a_pDefault Value to return if the key is not found - @param a_pHasMultiple Optionally receive notification of if there are - multiple entries for this key. - - @return a_pDefault Key was not found in the section - @return other Value of the key - */ - const SI_CHAR * GetValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - const SI_CHAR * a_pDefault = NULL, - bool * a_pHasMultiple = NULL - ) const; - - /** Retrieve a numeric value for a specific key. If multiple keys are enabled - (see SetMultiKey) then only the first value associated with that key - will be returned, see GetAllValues for getting all values with multikey. - - @param a_pSection Section to search - @param a_pKey Key to search for - @param a_nDefault Value to return if the key is not found - @param a_pHasMultiple Optionally receive notification of if there are - multiple entries for this key. - - @return a_nDefault Key was not found in the section - @return other Value of the key - */ - long GetLongValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - long a_nDefault = 0, - bool * a_pHasMultiple = NULL - ) const; - - /** Retrieve a numeric value for a specific key. If multiple keys are enabled - (see SetMultiKey) then only the first value associated with that key - will be returned, see GetAllValues for getting all values with multikey. - - @param a_pSection Section to search - @param a_pKey Key to search for - @param a_nDefault Value to return if the key is not found - @param a_pHasMultiple Optionally receive notification of if there are - multiple entries for this key. - - @return a_nDefault Key was not found in the section - @return other Value of the key - */ - double GetDoubleValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - double a_nDefault = 0, - bool * a_pHasMultiple = NULL - ) const; - - /** Retrieve a boolean value for a specific key. If multiple keys are enabled - (see SetMultiKey) then only the first value associated with that key - will be returned, see GetAllValues for getting all values with multikey. - - Strings starting with "t", "y", "on" or "1" are returned as logically true. - Strings starting with "f", "n", "of" or "0" are returned as logically false. - For all other values the default is returned. Character comparisons are - case-insensitive. - - @param a_pSection Section to search - @param a_pKey Key to search for - @param a_bDefault Value to return if the key is not found - @param a_pHasMultiple Optionally receive notification of if there are - multiple entries for this key. - - @return a_nDefault Key was not found in the section - @return other Value of the key - */ - bool GetBoolValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - bool a_bDefault = false, - bool * a_pHasMultiple = NULL - ) const; - - /** Add or update a section or value. This will always insert - when multiple keys are enabled. - - @param a_pSection Section to add or update - @param a_pKey Key to add or update. Set to NULL to - create an empty section. - @param a_pValue Value to set. Set to NULL to create an - empty section. - @param a_pComment Comment to be associated with the section or the - key. If a_pKey is NULL then it will be associated - with the section, otherwise the key. Note that a - comment may be set ONLY when the section or key is - first created (i.e. when this function returns the - value SI_INSERTED). If you wish to create a section - with a comment then you need to create the section - separately to the key. The comment string must be - in full comment form already (have a comment - character starting every line). - @param a_bForceReplace Should all existing values in a multi-key INI - file be replaced with this entry. This option has - no effect if not using multi-key files. The - difference between Delete/SetValue and SetValue - with a_bForceReplace = true, is that the load - order and comment will be preserved this way. - - @return SI_Error See error definitions - @return SI_UPDATED Value was updated - @return SI_INSERTED Value was inserted - */ - SI_Error SetValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - const SI_CHAR * a_pValue, - const SI_CHAR * a_pComment = NULL, - bool a_bForceReplace = false - ) - { - return AddEntry(a_pSection, a_pKey, a_pValue, a_pComment, a_bForceReplace, true); - } - - /** Add or update a numeric value. This will always insert - when multiple keys are enabled. - - @param a_pSection Section to add or update - @param a_pKey Key to add or update. - @param a_nValue Value to set. - @param a_pComment Comment to be associated with the key. See the - notes on SetValue() for comments. - @param a_bUseHex By default the value will be written to the file - in decimal format. Set this to true to write it - as hexadecimal. - @param a_bForceReplace Should all existing values in a multi-key INI - file be replaced with this entry. This option has - no effect if not using multi-key files. The - difference between Delete/SetLongValue and - SetLongValue with a_bForceReplace = true, is that - the load order and comment will be preserved this - way. - - @return SI_Error See error definitions - @return SI_UPDATED Value was updated - @return SI_INSERTED Value was inserted - */ - SI_Error SetLongValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - long a_nValue, - const SI_CHAR * a_pComment = NULL, - bool a_bUseHex = false, - bool a_bForceReplace = false - ); - - /** Add or update a double value. This will always insert - when multiple keys are enabled. - - @param a_pSection Section to add or update - @param a_pKey Key to add or update. - @param a_nValue Value to set. - @param a_pComment Comment to be associated with the key. See the - notes on SetValue() for comments. - @param a_bForceReplace Should all existing values in a multi-key INI - file be replaced with this entry. This option has - no effect if not using multi-key files. The - difference between Delete/SetDoubleValue and - SetDoubleValue with a_bForceReplace = true, is that - the load order and comment will be preserved this - way. - - @return SI_Error See error definitions - @return SI_UPDATED Value was updated - @return SI_INSERTED Value was inserted - */ - SI_Error SetDoubleValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - double a_nValue, - const SI_CHAR * a_pComment = NULL, - bool a_bForceReplace = false - ); - - /** Add or update a boolean value. This will always insert - when multiple keys are enabled. - - @param a_pSection Section to add or update - @param a_pKey Key to add or update. - @param a_bValue Value to set. - @param a_pComment Comment to be associated with the key. See the - notes on SetValue() for comments. - @param a_bForceReplace Should all existing values in a multi-key INI - file be replaced with this entry. This option has - no effect if not using multi-key files. The - difference between Delete/SetBoolValue and - SetBoolValue with a_bForceReplace = true, is that - the load order and comment will be preserved this - way. - - @return SI_Error See error definitions - @return SI_UPDATED Value was updated - @return SI_INSERTED Value was inserted - */ - SI_Error SetBoolValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - bool a_bValue, - const SI_CHAR * a_pComment = NULL, - bool a_bForceReplace = false - ); - - /** Delete an entire section, or a key from a section. Note that the - data returned by GetSection is invalid and must not be used after - anything has been deleted from that section using this method. - Note when multiple keys is enabled, this will delete all keys with - that name; to selectively delete individual key/values, use - DeleteValue. - - @param a_pSection Section to delete key from, or if - a_pKey is NULL, the section to remove. - @param a_pKey Key to remove from the section. Set to - NULL to remove the entire section. - @param a_bRemoveEmpty If the section is empty after this key has - been deleted, should the empty section be - removed? - - @return true Key or section was deleted. - @return false Key or section was not found. - */ - bool Delete( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - bool a_bRemoveEmpty = false - ); - - /** Delete an entire section, or a key from a section. If value is - provided, only remove keys with the value. Note that the data - returned by GetSection is invalid and must not be used after - anything has been deleted from that section using this method. - Note when multiple keys is enabled, all keys with the value will - be deleted. - - @param a_pSection Section to delete key from, or if - a_pKey is NULL, the section to remove. - @param a_pKey Key to remove from the section. Set to - NULL to remove the entire section. - @param a_pValue Value of key to remove from the section. - Set to NULL to remove all keys. - @param a_bRemoveEmpty If the section is empty after this key has - been deleted, should the empty section be - removed? - - @return true Key/value or section was deleted. - @return false Key/value or section was not found. - */ - bool DeleteValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - const SI_CHAR * a_pValue, - bool a_bRemoveEmpty = false - ); - - /*-----------------------------------------------------------------------*/ - /** @} - @{ @name Converter */ - - /** Return a conversion object to convert text to the same encoding - as is used by the Save(), SaveFile() and SaveString() functions. - Use this to prepare the strings that you wish to append or prepend - to the output INI data. - */ - Converter GetConverter() const { - return Converter(m_bStoreIsUtf8); - } - - /*-----------------------------------------------------------------------*/ - /** @} */ - -private: - // copying is not permitted - CSimpleIniTempl(const CSimpleIniTempl &); // disabled - CSimpleIniTempl & operator=(const CSimpleIniTempl &); // disabled - - /** Parse the data looking for a file comment and store it if found. - */ - SI_Error FindFileComment( - SI_CHAR *& a_pData, - bool a_bCopyStrings - ); - - /** Parse the data looking for the next valid entry. The memory pointed to - by a_pData is modified by inserting NULL characters. The pointer is - updated to the current location in the block of text. - */ - bool FindEntry( - SI_CHAR *& a_pData, - const SI_CHAR *& a_pSection, - const SI_CHAR *& a_pKey, - const SI_CHAR *& a_pVal, - const SI_CHAR *& a_pComment - ) const; - - /** Add the section/key/value to our data. - - @param a_pSection Section name. Sections will be created if they - don't already exist. - @param a_pKey Key name. May be NULL to create an empty section. - Existing entries will be updated. New entries will - be created. - @param a_pValue Value for the key. - @param a_pComment Comment to be associated with the section or the - key. If a_pKey is NULL then it will be associated - with the section, otherwise the key. This must be - a string in full comment form already (have a - comment character starting every line). - @param a_bForceReplace Should all existing values in a multi-key INI - file be replaced with this entry. This option has - no effect if not using multi-key files. The - difference between Delete/AddEntry and AddEntry - with a_bForceReplace = true, is that the load - order and comment will be preserved this way. - @param a_bCopyStrings Should copies of the strings be made or not. - If false then the pointers will be used as is. - */ - SI_Error AddEntry( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - const SI_CHAR * a_pValue, - const SI_CHAR * a_pComment, - bool a_bForceReplace, - bool a_bCopyStrings - ); - - /** Is the supplied character a whitespace character? */ - inline bool IsSpace(SI_CHAR ch) const { - return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'); - } - - /** Does the supplied character start a comment line? */ - inline bool IsComment(SI_CHAR ch) const { - return (ch == ';' || ch == '#'); - } - - - /** Skip over a newline character (or characters) for either DOS or UNIX */ - inline void SkipNewLine(SI_CHAR *& a_pData) const { - a_pData += (*a_pData == '\r' && *(a_pData+1) == '\n') ? 2 : 1; - } - - /** Make a copy of the supplied string, replacing the original pointer */ - SI_Error CopyString(const SI_CHAR *& a_pString); - - /** Delete a string from the copied strings buffer if necessary */ - void DeleteString(const SI_CHAR * a_pString); - - /** Internal use of our string comparison function */ - bool IsLess(const SI_CHAR * a_pLeft, const SI_CHAR * a_pRight) const { - const static SI_STRLESS isLess = SI_STRLESS(); - return isLess(a_pLeft, a_pRight); - } - - bool IsMultiLineTag(const SI_CHAR * a_pData) const; - bool IsMultiLineData(const SI_CHAR * a_pData) const; - bool LoadMultiLineText( - SI_CHAR *& a_pData, - const SI_CHAR *& a_pVal, - const SI_CHAR * a_pTagName, - bool a_bAllowBlankLinesInComment = false - ) const; - bool IsNewLineChar(SI_CHAR a_c) const; - - bool OutputMultiLineText( - OutputWriter & a_oOutput, - Converter & a_oConverter, - const SI_CHAR * a_pText - ) const; - -private: - /** Copy of the INI file data in our character format. This will be - modified when parsed to have NULL characters added after all - interesting string entries. All of the string pointers to sections, - keys and values point into this block of memory. - */ - SI_CHAR * m_pData; - - /** Length of the data that we have stored. Used when deleting strings - to determine if the string is stored here or in the allocated string - buffer. - */ - size_t m_uDataLen; - - /** File comment for this data, if one exists. */ - const SI_CHAR * m_pFileComment; - - /** Parsed INI data. Section -> (Key -> Value). */ - TSection m_data; - - /** This vector stores allocated memory for copies of strings that have - been supplied after the file load. It will be empty unless SetValue() - has been called. - */ - TNamesDepend m_strings; - - /** Is the format of our datafile UTF-8 or MBCS? */ - bool m_bStoreIsUtf8; - - /** Are multiple values permitted for the same key? */ - bool m_bAllowMultiKey; - - /** Are data values permitted to span multiple lines? */ - bool m_bAllowMultiLine; - - /** Should spaces be written out surrounding the equals sign? */ - bool m_bSpaces; - - /** Next order value, used to ensure sections and keys are output in the - same order that they are loaded/added. - */ - int m_nOrder; -}; - -// --------------------------------------------------------------------------- -// IMPLEMENTATION -// --------------------------------------------------------------------------- - -template -CSimpleIniTempl::CSimpleIniTempl( - bool a_bIsUtf8, - bool a_bAllowMultiKey, - bool a_bAllowMultiLine - ) - : m_pData(0) - , m_uDataLen(0) - , m_pFileComment(NULL) - , m_bStoreIsUtf8(a_bIsUtf8) - , m_bAllowMultiKey(a_bAllowMultiKey) - , m_bAllowMultiLine(a_bAllowMultiLine) - , m_bSpaces(true) - , m_nOrder(0) -{ } - -template -CSimpleIniTempl::~CSimpleIniTempl() -{ - Reset(); -} - -template -void -CSimpleIniTempl::Reset() -{ - // remove all data - delete[] m_pData; - m_pData = NULL; - m_uDataLen = 0; - m_pFileComment = NULL; - if (!m_data.empty()) { - m_data.erase(m_data.begin(), m_data.end()); - } - - // remove all strings - if (!m_strings.empty()) { - typename TNamesDepend::iterator i = m_strings.begin(); - for (; i != m_strings.end(); ++i) { - delete[] const_cast(i->pItem); - } - m_strings.erase(m_strings.begin(), m_strings.end()); - } -} - -template -SI_Error -CSimpleIniTempl::LoadFile( - const char * a_pszFile - ) -{ - FILE * fp = NULL; -#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE - fopen_s(&fp, a_pszFile, "rb"); -#else // !__STDC_WANT_SECURE_LIB__ - fp = fopen(a_pszFile, "rb"); -#endif // __STDC_WANT_SECURE_LIB__ - if (!fp) { - return SI_FILE; - } - SI_Error rc = LoadFile(fp); - fclose(fp); - return rc; -} - -#ifdef SI_HAS_WIDE_FILE -template -SI_Error -CSimpleIniTempl::LoadFile( - const SI_WCHAR_T * a_pwszFile - ) -{ -#ifdef _WIN32 - FILE * fp = NULL; -#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE - _wfopen_s(&fp, a_pwszFile, L"rb"); -#else // !__STDC_WANT_SECURE_LIB__ - fp = _wfopen(a_pwszFile, L"rb"); -#endif // __STDC_WANT_SECURE_LIB__ - if (!fp) return SI_FILE; - SI_Error rc = LoadFile(fp); - fclose(fp); - return rc; -#else // !_WIN32 (therefore SI_CONVERT_ICU) - char szFile[256]; - u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); - return LoadFile(szFile); -#endif // _WIN32 -} -#endif // SI_HAS_WIDE_FILE - -template -SI_Error -CSimpleIniTempl::LoadFile( - FILE * a_fpFile - ) -{ - // load the raw file data - int retval = fseek(a_fpFile, 0, SEEK_END); - if (retval != 0) { - return SI_FILE; - } - long lSize = ftell(a_fpFile); - if (lSize < 0) { - return SI_FILE; - } - if (lSize == 0) { - return SI_OK; - } - - // allocate and ensure NULL terminated - char * pData = new(std::nothrow) char[lSize+1]; - if (!pData) { - return SI_NOMEM; - } - pData[lSize] = 0; - - // load data into buffer - fseek(a_fpFile, 0, SEEK_SET); - size_t uRead = fread(pData, sizeof(char), lSize, a_fpFile); - if (uRead != (size_t) lSize) { - delete[] pData; - return SI_FILE; - } - - // convert the raw data to unicode - SI_Error rc = LoadData(pData, uRead); - delete[] pData; - return rc; -} - -template -SI_Error -CSimpleIniTempl::LoadData( - const char * a_pData, - size_t a_uDataLen - ) -{ - if (!a_pData) { - return SI_OK; - } - - // if the UTF-8 BOM exists, consume it and set mode to unicode, if we have - // already loaded data and try to change mode half-way through then this will - // be ignored and we will assert in debug versions - if (a_uDataLen >= 3 && memcmp(a_pData, SI_UTF8_SIGNATURE, 3) == 0) { - a_pData += 3; - a_uDataLen -= 3; - SI_ASSERT(m_bStoreIsUtf8 || !m_pData); // we don't expect mixed mode data - SetUnicode(); - } - - if (a_uDataLen == 0) { - return SI_OK; - } - - // determine the length of the converted data - SI_CONVERTER converter(m_bStoreIsUtf8); - size_t uLen = converter.SizeFromStore(a_pData, a_uDataLen); - if (uLen == (size_t)(-1)) { - return SI_FAIL; - } - - // allocate memory for the data, ensure that there is a NULL - // terminator wherever the converted data ends - SI_CHAR * pData = new(std::nothrow) SI_CHAR[uLen+1]; - if (!pData) { - return SI_NOMEM; - } - memset(pData, 0, sizeof(SI_CHAR)*(uLen+1)); - - // convert the data - if (!converter.ConvertFromStore(a_pData, a_uDataLen, pData, uLen)) { - delete[] pData; - return SI_FAIL; - } - - // parse it - const static SI_CHAR empty = 0; - SI_CHAR * pWork = pData; - const SI_CHAR * pSection = ∅ - const SI_CHAR * pItem = NULL; - const SI_CHAR * pVal = NULL; - const SI_CHAR * pComment = NULL; - - // We copy the strings if we are loading data into this class when we - // already have stored some. - bool bCopyStrings = (m_pData != NULL); - - // find a file comment if it exists, this is a comment that starts at the - // beginning of the file and continues until the first blank line. - SI_Error rc = FindFileComment(pWork, bCopyStrings); - if (rc < 0) return rc; - - // add every entry in the file to the data table - while (FindEntry(pWork, pSection, pItem, pVal, pComment)) { - rc = AddEntry(pSection, pItem, pVal, pComment, false, bCopyStrings); - if (rc < 0) return rc; - } - - // store these strings if we didn't copy them - if (bCopyStrings) { - delete[] pData; - } - else { - m_pData = pData; - m_uDataLen = uLen+1; - } - - return SI_OK; -} - -#ifdef SI_SUPPORT_IOSTREAMS -template -SI_Error -CSimpleIniTempl::LoadData( - std::istream & a_istream - ) -{ - std::string strData; - char szBuf[512]; - do { - a_istream.get(szBuf, sizeof(szBuf), '\0'); - strData.append(szBuf); - } - while (a_istream.good()); - return LoadData(strData); -} -#endif // SI_SUPPORT_IOSTREAMS - -template -SI_Error -CSimpleIniTempl::FindFileComment( - SI_CHAR *& a_pData, - bool a_bCopyStrings - ) -{ - // there can only be a single file comment - if (m_pFileComment) { - return SI_OK; - } - - // Load the file comment as multi-line text, this will modify all of - // the newline characters to be single \n chars - if (!LoadMultiLineText(a_pData, m_pFileComment, NULL, false)) { - return SI_OK; - } - - // copy the string if necessary - if (a_bCopyStrings) { - SI_Error rc = CopyString(m_pFileComment); - if (rc < 0) return rc; - } - - return SI_OK; -} - -template -bool -CSimpleIniTempl::FindEntry( - SI_CHAR *& a_pData, - const SI_CHAR *& a_pSection, - const SI_CHAR *& a_pKey, - const SI_CHAR *& a_pVal, - const SI_CHAR *& a_pComment - ) const -{ - a_pComment = NULL; - - SI_CHAR * pTrail = NULL; - while (*a_pData) { - // skip spaces and empty lines - while (*a_pData && IsSpace(*a_pData)) { - ++a_pData; - } - if (!*a_pData) { - break; - } - - // skip processing of comment lines but keep a pointer to - // the start of the comment. - if (IsComment(*a_pData)) { - LoadMultiLineText(a_pData, a_pComment, NULL, true); - continue; - } - - // process section names - if (*a_pData == '[') { - // skip leading spaces - ++a_pData; - while (*a_pData && IsSpace(*a_pData)) { - ++a_pData; - } - - // find the end of the section name (it may contain spaces) - // and convert it to lowercase as necessary - a_pSection = a_pData; - while (*a_pData && *a_pData != ']' && !IsNewLineChar(*a_pData)) { - ++a_pData; - } - - // if it's an invalid line, just skip it - if (*a_pData != ']') { - continue; - } - - // remove trailing spaces from the section - pTrail = a_pData - 1; - while (pTrail >= a_pSection && IsSpace(*pTrail)) { - --pTrail; - } - ++pTrail; - *pTrail = 0; - - // skip to the end of the line - ++a_pData; // safe as checked that it == ']' above - while (*a_pData && !IsNewLineChar(*a_pData)) { - ++a_pData; - } - - a_pKey = NULL; - a_pVal = NULL; - return true; - } - - // find the end of the key name (it may contain spaces) - // and convert it to lowercase as necessary - a_pKey = a_pData; - while (*a_pData && *a_pData != '=' && !IsNewLineChar(*a_pData)) { - ++a_pData; - } - - // if it's an invalid line, just skip it - if (*a_pData != '=') { - continue; - } - - // empty keys are invalid - if (a_pKey == a_pData) { - while (*a_pData && !IsNewLineChar(*a_pData)) { - ++a_pData; - } - continue; - } - - // remove trailing spaces from the key - pTrail = a_pData - 1; - while (pTrail >= a_pKey && IsSpace(*pTrail)) { - --pTrail; - } - ++pTrail; - *pTrail = 0; - - // skip leading whitespace on the value - ++a_pData; // safe as checked that it == '=' above - while (*a_pData && !IsNewLineChar(*a_pData) && IsSpace(*a_pData)) { - ++a_pData; - } - - // find the end of the value which is the end of this line - a_pVal = a_pData; - while (*a_pData && !IsNewLineChar(*a_pData)) { - ++a_pData; - } - - // remove trailing spaces from the value - pTrail = a_pData - 1; - if (*a_pData) { // prepare for the next round - SkipNewLine(a_pData); - } - while (pTrail >= a_pVal && IsSpace(*pTrail)) { - --pTrail; - } - ++pTrail; - *pTrail = 0; - - // check for multi-line entries - if (m_bAllowMultiLine && IsMultiLineTag(a_pVal)) { - // skip the "<<<" to get the tag that will end the multiline - const SI_CHAR * pTagName = a_pVal + 3; - return LoadMultiLineText(a_pData, a_pVal, pTagName); - } - - // return the standard entry - return true; - } - - return false; -} - -template -bool -CSimpleIniTempl::IsMultiLineTag( - const SI_CHAR * a_pVal - ) const -{ - // check for the "<<<" prefix for a multi-line entry - if (*a_pVal++ != '<') return false; - if (*a_pVal++ != '<') return false; - if (*a_pVal++ != '<') return false; - return true; -} - -template -bool -CSimpleIniTempl::IsMultiLineData( - const SI_CHAR * a_pData - ) const -{ - // data is multi-line if it has any of the following features: - // * whitespace prefix - // * embedded newlines - // * whitespace suffix - - // empty string - if (!*a_pData) { - return false; - } - - // check for prefix - if (IsSpace(*a_pData)) { - return true; - } - - // embedded newlines - while (*a_pData) { - if (IsNewLineChar(*a_pData)) { - return true; - } - ++a_pData; - } - - // check for suffix - if (IsSpace(*--a_pData)) { - return true; - } - - return false; -} - -template -bool -CSimpleIniTempl::IsNewLineChar( - SI_CHAR a_c - ) const -{ - return (a_c == '\n' || a_c == '\r'); -} - -template -bool -CSimpleIniTempl::LoadMultiLineText( - SI_CHAR *& a_pData, - const SI_CHAR *& a_pVal, - const SI_CHAR * a_pTagName, - bool a_bAllowBlankLinesInComment - ) const -{ - // we modify this data to strip all newlines down to a single '\n' - // character. This means that on Windows we need to strip out some - // characters which will make the data shorter. - // i.e. LINE1-LINE1\r\nLINE2-LINE2\0 will become - // LINE1-LINE1\nLINE2-LINE2\0 - // The pDataLine entry is the pointer to the location in memory that - // the current line needs to start to run following the existing one. - // This may be the same as pCurrLine in which case no move is needed. - SI_CHAR * pDataLine = a_pData; - SI_CHAR * pCurrLine; - - // value starts at the current line - a_pVal = a_pData; - - // find the end tag. This tag must start in column 1 and be - // followed by a newline. No whitespace removal is done while - // searching for this tag. - SI_CHAR cEndOfLineChar = *a_pData; - for(;;) { - // if we are loading comments then we need a comment character as - // the first character on every line - if (!a_pTagName && !IsComment(*a_pData)) { - // if we aren't allowing blank lines then we're done - if (!a_bAllowBlankLinesInComment) { - break; - } - - // if we are allowing blank lines then we only include them - // in this comment if another comment follows, so read ahead - // to find out. - SI_CHAR * pCurr = a_pData; - int nNewLines = 0; - while (IsSpace(*pCurr)) { - if (IsNewLineChar(*pCurr)) { - ++nNewLines; - SkipNewLine(pCurr); - } - else { - ++pCurr; - } - } - - // we have a comment, add the blank lines to the output - // and continue processing from here - if (IsComment(*pCurr)) { - for (; nNewLines > 0; --nNewLines) *pDataLine++ = '\n'; - a_pData = pCurr; - continue; - } - - // the comment ends here - break; - } - - // find the end of this line - pCurrLine = a_pData; - while (*a_pData && !IsNewLineChar(*a_pData)) ++a_pData; - - // move this line down to the location that it should be if necessary - if (pDataLine < pCurrLine) { - size_t nLen = (size_t) (a_pData - pCurrLine); - memmove(pDataLine, pCurrLine, nLen * sizeof(SI_CHAR)); - pDataLine[nLen] = '\0'; - } - - // end the line with a NULL - cEndOfLineChar = *a_pData; - *a_pData = 0; - - // if are looking for a tag then do the check now. This is done before - // checking for end of the data, so that if we have the tag at the end - // of the data then the tag is removed correctly. - if (a_pTagName && - (!IsLess(pDataLine, a_pTagName) && !IsLess(a_pTagName, pDataLine))) - { - break; - } - - // if we are at the end of the data then we just automatically end - // this entry and return the current data. - if (!cEndOfLineChar) { - return true; - } - - // otherwise we need to process this newline to ensure that it consists - // of just a single \n character. - pDataLine += (a_pData - pCurrLine); - *a_pData = cEndOfLineChar; - SkipNewLine(a_pData); - *pDataLine++ = '\n'; - } - - // if we didn't find a comment at all then return false - if (a_pVal == a_pData) { - a_pVal = NULL; - return false; - } - - // the data (which ends at the end of the last line) needs to be - // null-terminated BEFORE before the newline character(s). If the - // user wants a new line in the multi-line data then they need to - // add an empty line before the tag. - *--pDataLine = '\0'; - - // if looking for a tag and if we aren't at the end of the data, - // then move a_pData to the start of the next line. - if (a_pTagName && cEndOfLineChar) { - SI_ASSERT(IsNewLineChar(cEndOfLineChar)); - *a_pData = cEndOfLineChar; - SkipNewLine(a_pData); - } - - return true; -} - -template -SI_Error -CSimpleIniTempl::CopyString( - const SI_CHAR *& a_pString - ) -{ - size_t uLen = 0; - if (sizeof(SI_CHAR) == sizeof(char)) { - uLen = strlen((const char *)a_pString); - } - else if (sizeof(SI_CHAR) == sizeof(wchar_t)) { - uLen = wcslen((const wchar_t *)a_pString); - } - else { - for ( ; a_pString[uLen]; ++uLen) /*loop*/ ; - } - ++uLen; // NULL character - SI_CHAR * pCopy = new(std::nothrow) SI_CHAR[uLen]; - if (!pCopy) { - return SI_NOMEM; - } - memcpy(pCopy, a_pString, sizeof(SI_CHAR)*uLen); - m_strings.push_back(pCopy); - a_pString = pCopy; - return SI_OK; -} - -template -SI_Error -CSimpleIniTempl::AddEntry( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - const SI_CHAR * a_pValue, - const SI_CHAR * a_pComment, - bool a_bForceReplace, - bool a_bCopyStrings - ) -{ - SI_Error rc; - bool bInserted = false; - - SI_ASSERT(!a_pComment || IsComment(*a_pComment)); - - // if we are copying strings then make a copy of the comment now - // because we will need it when we add the entry. - if (a_bCopyStrings && a_pComment) { - rc = CopyString(a_pComment); - if (rc < 0) return rc; - } - - // create the section entry if necessary - typename TSection::iterator iSection = m_data.find(a_pSection); - if (iSection == m_data.end()) { - // if the section doesn't exist then we need a copy as the - // string needs to last beyond the end of this function - if (a_bCopyStrings) { - rc = CopyString(a_pSection); - if (rc < 0) return rc; - } - - // only set the comment if this is a section only entry - Entry oSection(a_pSection, ++m_nOrder); - if (a_pComment && (!a_pKey || !a_pValue)) { - oSection.pComment = a_pComment; - } - - typename TSection::value_type oEntry(oSection, TKeyVal()); - typedef typename TSection::iterator SectionIterator; - std::pair i = m_data.insert(oEntry); - iSection = i.first; - bInserted = true; - } - if (!a_pKey || !a_pValue) { - // section only entries are specified with pItem and pVal as NULL - return bInserted ? SI_INSERTED : SI_UPDATED; - } - - // check for existence of the key - TKeyVal & keyval = iSection->second; - typename TKeyVal::iterator iKey = keyval.find(a_pKey); - - // remove all existing entries but save the load order and - // comment of the first entry - int nLoadOrder = ++m_nOrder; - if (iKey != keyval.end() && m_bAllowMultiKey && a_bForceReplace) { - const SI_CHAR * pComment = NULL; - while (iKey != keyval.end() && !IsLess(a_pKey, iKey->first.pItem)) { - if (iKey->first.nOrder < nLoadOrder) { - nLoadOrder = iKey->first.nOrder; - pComment = iKey->first.pComment; - } - ++iKey; - } - if (pComment) { - DeleteString(a_pComment); - a_pComment = pComment; - CopyString(a_pComment); - } - Delete(a_pSection, a_pKey); - iKey = keyval.end(); - } - - // make string copies if necessary - bool bForceCreateNewKey = m_bAllowMultiKey && !a_bForceReplace; - if (a_bCopyStrings) { - if (bForceCreateNewKey || iKey == keyval.end()) { - // if the key doesn't exist then we need a copy as the - // string needs to last beyond the end of this function - // because we will be inserting the key next - rc = CopyString(a_pKey); - if (rc < 0) return rc; - } - - // we always need a copy of the value - rc = CopyString(a_pValue); - if (rc < 0) return rc; - } - - // create the key entry - if (iKey == keyval.end() || bForceCreateNewKey) { - Entry oKey(a_pKey, nLoadOrder); - if (a_pComment) { - oKey.pComment = a_pComment; - } - typename TKeyVal::value_type oEntry(oKey, static_cast(NULL)); - iKey = keyval.insert(oEntry); - bInserted = true; - } - iKey->second = a_pValue; - return bInserted ? SI_INSERTED : SI_UPDATED; -} - -template -const SI_CHAR * -CSimpleIniTempl::GetValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - const SI_CHAR * a_pDefault, - bool * a_pHasMultiple - ) const -{ - if (a_pHasMultiple) { - *a_pHasMultiple = false; - } - if (!a_pSection || !a_pKey) { - return a_pDefault; - } - typename TSection::const_iterator iSection = m_data.find(a_pSection); - if (iSection == m_data.end()) { - return a_pDefault; - } - typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); - if (iKeyVal == iSection->second.end()) { - return a_pDefault; - } - - // check for multiple entries with the same key - if (m_bAllowMultiKey && a_pHasMultiple) { - typename TKeyVal::const_iterator iTemp = iKeyVal; - if (++iTemp != iSection->second.end()) { - if (!IsLess(a_pKey, iTemp->first.pItem)) { - *a_pHasMultiple = true; - } - } - } - - return iKeyVal->second; -} - -template -long -CSimpleIniTempl::GetLongValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - long a_nDefault, - bool * a_pHasMultiple - ) const -{ - // return the default if we don't have a value - const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); - if (!pszValue || !*pszValue) return a_nDefault; - - // convert to UTF-8/MBCS which for a numeric value will be the same as ASCII - char szValue[64] = { 0 }; - SI_CONVERTER c(m_bStoreIsUtf8); - if (!c.ConvertToStore(pszValue, szValue, sizeof(szValue))) { - return a_nDefault; - } - - // handle the value as hex if prefaced with "0x" - long nValue = a_nDefault; - char * pszSuffix = szValue; - if (szValue[0] == '0' && (szValue[1] == 'x' || szValue[1] == 'X')) { - if (!szValue[2]) return a_nDefault; - nValue = strtol(&szValue[2], &pszSuffix, 16); - } - else { - nValue = strtol(szValue, &pszSuffix, 10); - } - - // any invalid strings will return the default value - if (*pszSuffix) { - return a_nDefault; - } - - return nValue; -} - -template -SI_Error -CSimpleIniTempl::SetLongValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - long a_nValue, - const SI_CHAR * a_pComment, - bool a_bUseHex, - bool a_bForceReplace - ) -{ - // use SetValue to create sections - if (!a_pSection || !a_pKey) return SI_FAIL; - - // convert to an ASCII string - char szInput[64]; -#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE - sprintf_s(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); -#else // !__STDC_WANT_SECURE_LIB__ - sprintf(szInput, a_bUseHex ? "0x%lx" : "%ld", a_nValue); -#endif // __STDC_WANT_SECURE_LIB__ - - // convert to output text - SI_CHAR szOutput[64]; - SI_CONVERTER c(m_bStoreIsUtf8); - c.ConvertFromStore(szInput, strlen(szInput) + 1, - szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); - - // actually add it - return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); -} - -template -double -CSimpleIniTempl::GetDoubleValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - double a_nDefault, - bool * a_pHasMultiple - ) const -{ - // return the default if we don't have a value - const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); - if (!pszValue || !*pszValue) return a_nDefault; - - // convert to UTF-8/MBCS which for a numeric value will be the same as ASCII - char szValue[64] = { 0 }; - SI_CONVERTER c(m_bStoreIsUtf8); - if (!c.ConvertToStore(pszValue, szValue, sizeof(szValue))) { - return a_nDefault; - } - - char * pszSuffix = NULL; - double nValue = strtod(szValue, &pszSuffix); - - // any invalid strings will return the default value - if (!pszSuffix || *pszSuffix) { - return a_nDefault; - } - - return nValue; -} - -template -SI_Error -CSimpleIniTempl::SetDoubleValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - double a_nValue, - const SI_CHAR * a_pComment, - bool a_bForceReplace - ) -{ - // use SetValue to create sections - if (!a_pSection || !a_pKey) return SI_FAIL; - - // convert to an ASCII string - char szInput[64]; -#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE - sprintf_s(szInput, "%f", a_nValue); -#else // !__STDC_WANT_SECURE_LIB__ - sprintf(szInput, "%f", a_nValue); -#endif // __STDC_WANT_SECURE_LIB__ - - // convert to output text - SI_CHAR szOutput[64]; - SI_CONVERTER c(m_bStoreIsUtf8); - c.ConvertFromStore(szInput, strlen(szInput) + 1, - szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); - - // actually add it - return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); -} - -template -bool -CSimpleIniTempl::GetBoolValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - bool a_bDefault, - bool * a_pHasMultiple - ) const -{ - // return the default if we don't have a value - const SI_CHAR * pszValue = GetValue(a_pSection, a_pKey, NULL, a_pHasMultiple); - if (!pszValue || !*pszValue) return a_bDefault; - - // we only look at the minimum number of characters - switch (pszValue[0]) { - case 't': case 'T': // true - case 'y': case 'Y': // yes - case '1': // 1 (one) - return true; - - case 'f': case 'F': // false - case 'n': case 'N': // no - case '0': // 0 (zero) - return false; - - case 'o': case 'O': - if (pszValue[1] == 'n' || pszValue[1] == 'N') return true; // on - if (pszValue[1] == 'f' || pszValue[1] == 'F') return false; // off - break; - } - - // no recognized value, return the default - return a_bDefault; -} - -template -SI_Error -CSimpleIniTempl::SetBoolValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - bool a_bValue, - const SI_CHAR * a_pComment, - bool a_bForceReplace - ) -{ - // use SetValue to create sections - if (!a_pSection || !a_pKey) return SI_FAIL; - - // convert to an ASCII string - const char * pszInput = a_bValue ? "true" : "false"; - - // convert to output text - SI_CHAR szOutput[64]; - SI_CONVERTER c(m_bStoreIsUtf8); - c.ConvertFromStore(pszInput, strlen(pszInput) + 1, - szOutput, sizeof(szOutput) / sizeof(SI_CHAR)); - - // actually add it - return AddEntry(a_pSection, a_pKey, szOutput, a_pComment, a_bForceReplace, true); -} - -template -bool -CSimpleIniTempl::GetAllValues( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - TNamesDepend & a_values - ) const -{ - a_values.clear(); - - if (!a_pSection || !a_pKey) { - return false; - } - typename TSection::const_iterator iSection = m_data.find(a_pSection); - if (iSection == m_data.end()) { - return false; - } - typename TKeyVal::const_iterator iKeyVal = iSection->second.find(a_pKey); - if (iKeyVal == iSection->second.end()) { - return false; - } - - // insert all values for this key - a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); - if (m_bAllowMultiKey) { - ++iKeyVal; - while (iKeyVal != iSection->second.end() && !IsLess(a_pKey, iKeyVal->first.pItem)) { - a_values.push_back(Entry(iKeyVal->second, iKeyVal->first.pComment, iKeyVal->first.nOrder)); - ++iKeyVal; - } - } - - return true; -} - -template -int -CSimpleIniTempl::GetSectionSize( - const SI_CHAR * a_pSection - ) const -{ - if (!a_pSection) { - return -1; - } - - typename TSection::const_iterator iSection = m_data.find(a_pSection); - if (iSection == m_data.end()) { - return -1; - } - const TKeyVal & section = iSection->second; - - // if multi-key isn't permitted then the section size is - // the number of keys that we have. - if (!m_bAllowMultiKey || section.empty()) { - return (int) section.size(); - } - - // otherwise we need to count them - int nCount = 0; - const SI_CHAR * pLastKey = NULL; - typename TKeyVal::const_iterator iKeyVal = section.begin(); - for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n) { - if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { - ++nCount; - pLastKey = iKeyVal->first.pItem; - } - } - return nCount; -} - -template -const typename CSimpleIniTempl::TKeyVal * -CSimpleIniTempl::GetSection( - const SI_CHAR * a_pSection - ) const -{ - if (a_pSection) { - typename TSection::const_iterator i = m_data.find(a_pSection); - if (i != m_data.end()) { - return &(i->second); - } - } - return 0; -} - -template -void -CSimpleIniTempl::GetAllSections( - TNamesDepend & a_names - ) const -{ - a_names.clear(); - typename TSection::const_iterator i = m_data.begin(); - for (int n = 0; i != m_data.end(); ++i, ++n ) { - a_names.push_back(i->first); - } -} - -template -bool -CSimpleIniTempl::GetAllKeys( - const SI_CHAR * a_pSection, - TNamesDepend & a_names - ) const -{ - a_names.clear(); - - if (!a_pSection) { - return false; - } - - typename TSection::const_iterator iSection = m_data.find(a_pSection); - if (iSection == m_data.end()) { - return false; - } - - const TKeyVal & section = iSection->second; - const SI_CHAR * pLastKey = NULL; - typename TKeyVal::const_iterator iKeyVal = section.begin(); - for (int n = 0; iKeyVal != section.end(); ++iKeyVal, ++n ) { - if (!pLastKey || IsLess(pLastKey, iKeyVal->first.pItem)) { - a_names.push_back(iKeyVal->first); - pLastKey = iKeyVal->first.pItem; - } - } - - return true; -} - -template -SI_Error -CSimpleIniTempl::SaveFile( - const char * a_pszFile, - bool a_bAddSignature - ) const -{ - FILE * fp = NULL; -#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE - fopen_s(&fp, a_pszFile, "wb"); -#else // !__STDC_WANT_SECURE_LIB__ - fp = fopen(a_pszFile, "wb"); -#endif // __STDC_WANT_SECURE_LIB__ - if (!fp) return SI_FILE; - SI_Error rc = SaveFile(fp, a_bAddSignature); - fclose(fp); - return rc; -} - -#ifdef SI_HAS_WIDE_FILE -template -SI_Error -CSimpleIniTempl::SaveFile( - const SI_WCHAR_T * a_pwszFile, - bool a_bAddSignature - ) const -{ -#ifdef _WIN32 - FILE * fp = NULL; -#if __STDC_WANT_SECURE_LIB__ && !_WIN32_WCE - _wfopen_s(&fp, a_pwszFile, L"wb"); -#else // !__STDC_WANT_SECURE_LIB__ - fp = _wfopen(a_pwszFile, L"wb"); -#endif // __STDC_WANT_SECURE_LIB__ - if (!fp) return SI_FILE; - SI_Error rc = SaveFile(fp, a_bAddSignature); - fclose(fp); - return rc; -#else // !_WIN32 (therefore SI_CONVERT_ICU) - char szFile[256]; - u_austrncpy(szFile, a_pwszFile, sizeof(szFile)); - return SaveFile(szFile, a_bAddSignature); -#endif // _WIN32 -} -#endif // SI_HAS_WIDE_FILE - -template -SI_Error -CSimpleIniTempl::SaveFile( - FILE * a_pFile, - bool a_bAddSignature - ) const -{ - FileWriter writer(a_pFile); - return Save(writer, a_bAddSignature); -} - -template -SI_Error -CSimpleIniTempl::Save( - OutputWriter & a_oOutput, - bool a_bAddSignature - ) const -{ - Converter convert(m_bStoreIsUtf8); - - // add the UTF-8 signature if it is desired - if (m_bStoreIsUtf8 && a_bAddSignature) { - a_oOutput.Write(SI_UTF8_SIGNATURE); - } - - // get all of the sections sorted in load order - TNamesDepend oSections; - GetAllSections(oSections); -#if defined(_MSC_VER) && _MSC_VER <= 1200 - oSections.sort(); -#elif defined(__BORLANDC__) - oSections.sort(Entry::LoadOrder()); -#else - oSections.sort(typename Entry::LoadOrder()); -#endif - - // write the file comment if we have one - bool bNeedNewLine = false; - if (m_pFileComment) { - if (!OutputMultiLineText(a_oOutput, convert, m_pFileComment)) { - return SI_FAIL; - } - bNeedNewLine = true; - } - - // iterate through our sections and output the data - typename TNamesDepend::const_iterator iSection = oSections.begin(); - for ( ; iSection != oSections.end(); ++iSection ) { - // write out the comment if there is one - if (iSection->pComment) { - if (bNeedNewLine) { - a_oOutput.Write(SI_NEWLINE_A); - a_oOutput.Write(SI_NEWLINE_A); - } - if (!OutputMultiLineText(a_oOutput, convert, iSection->pComment)) { - return SI_FAIL; - } - bNeedNewLine = false; - } - - if (bNeedNewLine) { - a_oOutput.Write(SI_NEWLINE_A); - a_oOutput.Write(SI_NEWLINE_A); - bNeedNewLine = false; - } - - // write the section (unless there is no section name) - if (*iSection->pItem) { - if (!convert.ConvertToStore(iSection->pItem)) { - return SI_FAIL; - } - a_oOutput.Write("["); - a_oOutput.Write(convert.Data()); - a_oOutput.Write("]"); - a_oOutput.Write(SI_NEWLINE_A); - } - - // get all of the keys sorted in load order - TNamesDepend oKeys; - GetAllKeys(iSection->pItem, oKeys); -#if defined(_MSC_VER) && _MSC_VER <= 1200 - oKeys.sort(); -#elif defined(__BORLANDC__) - oKeys.sort(Entry::LoadOrder()); -#else - oKeys.sort(typename Entry::LoadOrder()); -#endif - - // write all keys and values - typename TNamesDepend::const_iterator iKey = oKeys.begin(); - for ( ; iKey != oKeys.end(); ++iKey) { - // get all values for this key - TNamesDepend oValues; - GetAllValues(iSection->pItem, iKey->pItem, oValues); - - typename TNamesDepend::const_iterator iValue = oValues.begin(); - for ( ; iValue != oValues.end(); ++iValue) { - // write out the comment if there is one - if (iValue->pComment) { - a_oOutput.Write(SI_NEWLINE_A); - if (!OutputMultiLineText(a_oOutput, convert, iValue->pComment)) { - return SI_FAIL; - } - } - - // write the key - if (!convert.ConvertToStore(iKey->pItem)) { - return SI_FAIL; - } - a_oOutput.Write(convert.Data()); - - // write the value - if (!convert.ConvertToStore(iValue->pItem)) { - return SI_FAIL; - } - a_oOutput.Write(m_bSpaces ? " = " : "="); - if (m_bAllowMultiLine && IsMultiLineData(iValue->pItem)) { - // multi-line data needs to be processed specially to ensure - // that we use the correct newline format for the current system - a_oOutput.Write("<<pItem)) { - return SI_FAIL; - } - a_oOutput.Write("END_OF_TEXT"); - } - else { - a_oOutput.Write(convert.Data()); - } - a_oOutput.Write(SI_NEWLINE_A); - } - } - - bNeedNewLine = true; - } - - return SI_OK; -} - -template -bool -CSimpleIniTempl::OutputMultiLineText( - OutputWriter & a_oOutput, - Converter & a_oConverter, - const SI_CHAR * a_pText - ) const -{ - const SI_CHAR * pEndOfLine; - SI_CHAR cEndOfLineChar = *a_pText; - while (cEndOfLineChar) { - // find the end of this line - pEndOfLine = a_pText; - for (; *pEndOfLine && *pEndOfLine != '\n'; ++pEndOfLine) /*loop*/ ; - cEndOfLineChar = *pEndOfLine; - - // temporarily null terminate, convert and output the line - *const_cast(pEndOfLine) = 0; - if (!a_oConverter.ConvertToStore(a_pText)) { - return false; - } - *const_cast(pEndOfLine) = cEndOfLineChar; - a_pText += (pEndOfLine - a_pText) + 1; - a_oOutput.Write(a_oConverter.Data()); - a_oOutput.Write(SI_NEWLINE_A); - } - return true; -} - -template -bool -CSimpleIniTempl::Delete( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - bool a_bRemoveEmpty - ) -{ - return DeleteValue(a_pSection, a_pKey, NULL, a_bRemoveEmpty); -} - -template -bool -CSimpleIniTempl::DeleteValue( - const SI_CHAR * a_pSection, - const SI_CHAR * a_pKey, - const SI_CHAR * a_pValue, - bool a_bRemoveEmpty - ) -{ - if (!a_pSection) { - return false; - } - - typename TSection::iterator iSection = m_data.find(a_pSection); - if (iSection == m_data.end()) { - return false; - } - - // remove a single key if we have a keyname - if (a_pKey) { - typename TKeyVal::iterator iKeyVal = iSection->second.find(a_pKey); - if (iKeyVal == iSection->second.end()) { - return false; - } - - const static SI_STRLESS isLess = SI_STRLESS(); - - // remove any copied strings and then the key - typename TKeyVal::iterator iDelete; - bool bDeleted = false; - do { - iDelete = iKeyVal++; - - if(a_pValue == NULL || - (isLess(a_pValue, iDelete->second) == false && - isLess(iDelete->second, a_pValue) == false)) { - DeleteString(iDelete->first.pItem); - DeleteString(iDelete->second); - iSection->second.erase(iDelete); - bDeleted = true; - } - } - while (iKeyVal != iSection->second.end() - && !IsLess(a_pKey, iKeyVal->first.pItem)); - - if(!bDeleted) { - return false; - } - - // done now if the section is not empty or we are not pruning away - // the empty sections. Otherwise let it fall through into the section - // deletion code - if (!a_bRemoveEmpty || !iSection->second.empty()) { - return true; - } - } - else { - // delete all copied strings from this section. The actual - // entries will be removed when the section is removed. - typename TKeyVal::iterator iKeyVal = iSection->second.begin(); - for ( ; iKeyVal != iSection->second.end(); ++iKeyVal) { - DeleteString(iKeyVal->first.pItem); - DeleteString(iKeyVal->second); - } - } - - // delete the section itself - DeleteString(iSection->first.pItem); - m_data.erase(iSection); - - return true; -} - -template -void -CSimpleIniTempl::DeleteString( - const SI_CHAR * a_pString - ) -{ - // strings may exist either inside the data block, or they will be - // individually allocated and stored in m_strings. We only physically - // delete those stored in m_strings. - if (a_pString < m_pData || a_pString >= m_pData + m_uDataLen) { - typename TNamesDepend::iterator i = m_strings.begin(); - for (;i != m_strings.end(); ++i) { - if (a_pString == i->pItem) { - delete[] const_cast(i->pItem); - m_strings.erase(i); - break; - } - } - } -} - -// --------------------------------------------------------------------------- -// CONVERSION FUNCTIONS -// --------------------------------------------------------------------------- - -// Defines the conversion classes for different libraries. Before including -// SimpleIni.h, set the converter that you wish you use by defining one of the -// following symbols. -// -// SI_CONVERT_GENERIC Use the Unicode reference conversion library in -// the accompanying files ConvertUTF.h/c -// SI_CONVERT_ICU Use the IBM ICU conversion library. Requires -// ICU headers on include path and icuuc.lib -// SI_CONVERT_WIN32 Use the Win32 API functions for conversion. - -#if !defined(SI_CONVERT_GENERIC) && !defined(SI_CONVERT_WIN32) && !defined(SI_CONVERT_ICU) -# ifdef _WIN32 -# define SI_CONVERT_WIN32 -# else -# define SI_CONVERT_GENERIC -# endif -#endif - -/** - * Generic case-sensitive less than comparison. This class returns numerically - * ordered ASCII case-sensitive text for all possible sizes and types of - * SI_CHAR. - */ -template -struct SI_GenericCase { - bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { - long cmp; - for ( ;*pLeft && *pRight; ++pLeft, ++pRight) { - cmp = (long) *pLeft - (long) *pRight; - if (cmp != 0) { - return cmp < 0; - } - } - return *pRight != 0; - } -}; - -/** - * Generic ASCII case-insensitive less than comparison. This class returns - * numerically ordered ASCII case-insensitive text for all possible sizes - * and types of SI_CHAR. It is not safe for MBCS text comparison where - * ASCII A-Z characters are used in the encoding of multi-byte characters. - */ -template -struct SI_GenericNoCase { - inline SI_CHAR locase(SI_CHAR ch) const { - return (ch < 'A' || ch > 'Z') ? ch : (ch - 'A' + 'a'); - } - bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { - long cmp; - for ( ;*pLeft && *pRight; ++pLeft, ++pRight) { - cmp = (long) locase(*pLeft) - (long) locase(*pRight); - if (cmp != 0) { - return cmp < 0; - } - } - return *pRight != 0; - } -}; - -/** - * Null conversion class for MBCS/UTF-8 to char (or equivalent). - */ -template -class SI_ConvertA { - bool m_bStoreIsUtf8; -protected: - SI_ConvertA() { } -public: - SI_ConvertA(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) { } - - /* copy and assignment */ - SI_ConvertA(const SI_ConvertA & rhs) { operator=(rhs); } - SI_ConvertA & operator=(const SI_ConvertA & rhs) { - m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; - return *this; - } - - /** Calculate the number of SI_CHAR required for converting the input - * from the storage format. The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to SI_CHAR. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @return Number of SI_CHAR required by the string when - * converted. If there are embedded NULL bytes in the - * input data, only the string up and not including - * the NULL byte will be converted. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeFromStore( - const char * a_pInputData, - size_t a_uInputDataLen) - { - (void)a_pInputData; - SI_ASSERT(a_uInputDataLen != (size_t) -1); - - // ASCII/MBCS/UTF-8 needs no conversion - return a_uInputDataLen; - } - - /** Convert the input string from the storage format to SI_CHAR. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to SI_CHAR. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @param a_pOutputData Pointer to the output buffer to received the - * converted data. - * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. - * @return true if all of the input data was successfully - * converted. - */ - bool ConvertFromStore( - const char * a_pInputData, - size_t a_uInputDataLen, - SI_CHAR * a_pOutputData, - size_t a_uOutputDataSize) - { - // ASCII/MBCS/UTF-8 needs no conversion - if (a_uInputDataLen > a_uOutputDataSize) { - return false; - } - memcpy(a_pOutputData, a_pInputData, a_uInputDataLen); - return true; - } - - /** Calculate the number of char required by the storage format of this - * data. The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData NULL terminated string to calculate the number of - * bytes required to be converted to storage format. - * @return Number of bytes required by the string when - * converted to storage format. This size always - * includes space for the terminating NULL character. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeToStore( - const SI_CHAR * a_pInputData) - { - // ASCII/MBCS/UTF-8 needs no conversion - return strlen((const char *)a_pInputData) + 1; - } - - /** Convert the input string to the storage format of this data. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData NULL terminated source string to convert. All of - * the data will be converted including the - * terminating NULL character. - * @param a_pOutputData Pointer to the buffer to receive the converted - * string. - * @param a_uOutputDataSize Size of the output buffer in char. - * @return true if all of the input data, including the - * terminating NULL character was successfully - * converted. - */ - bool ConvertToStore( - const SI_CHAR * a_pInputData, - char * a_pOutputData, - size_t a_uOutputDataSize) - { - // calc input string length (SI_CHAR type and size independent) - size_t uInputLen = strlen((const char *)a_pInputData) + 1; - if (uInputLen > a_uOutputDataSize) { - return false; - } - - // ascii/UTF-8 needs no conversion - memcpy(a_pOutputData, a_pInputData, uInputLen); - return true; - } -}; - - -// --------------------------------------------------------------------------- -// SI_CONVERT_GENERIC -// --------------------------------------------------------------------------- -#ifdef SI_CONVERT_GENERIC - -#define SI_Case SI_GenericCase -#define SI_NoCase SI_GenericNoCase - -#include -#include "ConvertUTF.h" - -/** - * Converts UTF-8 to a wchar_t (or equivalent) using the Unicode reference - * library functions. This can be used on all platforms. - */ -template -class SI_ConvertW { - bool m_bStoreIsUtf8; -protected: - SI_ConvertW() { } -public: - SI_ConvertW(bool a_bStoreIsUtf8) : m_bStoreIsUtf8(a_bStoreIsUtf8) { } - - /* copy and assignment */ - SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } - SI_ConvertW & operator=(const SI_ConvertW & rhs) { - m_bStoreIsUtf8 = rhs.m_bStoreIsUtf8; - return *this; - } - - /** Calculate the number of SI_CHAR required for converting the input - * from the storage format. The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to SI_CHAR. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @return Number of SI_CHAR required by the string when - * converted. If there are embedded NULL bytes in the - * input data, only the string up and not including - * the NULL byte will be converted. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeFromStore( - const char * a_pInputData, - size_t a_uInputDataLen) - { - SI_ASSERT(a_uInputDataLen != (size_t) -1); - - if (m_bStoreIsUtf8) { - // worst case scenario for UTF-8 to wchar_t is 1 char -> 1 wchar_t - // so we just return the same number of characters required as for - // the source text. - return a_uInputDataLen; - } - -#if defined(SI_NO_MBSTOWCS_NULL) || (!defined(_MSC_VER) && !defined(_linux)) - // fall back processing for platforms that don't support a NULL dest to mbstowcs - // worst case scenario is 1:1, this will be a sufficient buffer size - (void)a_pInputData; - return a_uInputDataLen; -#else - // get the actual required buffer size - return mbstowcs(NULL, a_pInputData, a_uInputDataLen); -#endif - } - - /** Convert the input string from the storage format to SI_CHAR. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to SI_CHAR. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @param a_pOutputData Pointer to the output buffer to received the - * converted data. - * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. - * @return true if all of the input data was successfully - * converted. - */ - bool ConvertFromStore( - const char * a_pInputData, - size_t a_uInputDataLen, - SI_CHAR * a_pOutputData, - size_t a_uOutputDataSize) - { - if (m_bStoreIsUtf8) { - // This uses the Unicode reference implementation to do the - // conversion from UTF-8 to wchar_t. The required files are - // ConvertUTF.h and ConvertUTF.c which should be included in - // the distribution but are publically available from unicode.org - // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ - ConversionResult retval; - const UTF8 * pUtf8 = (const UTF8 *) a_pInputData; - if (sizeof(wchar_t) == sizeof(UTF32)) { - UTF32 * pUtf32 = (UTF32 *) a_pOutputData; - retval = ConvertUTF8toUTF32( - &pUtf8, pUtf8 + a_uInputDataLen, - &pUtf32, pUtf32 + a_uOutputDataSize, - lenientConversion); - } - else if (sizeof(wchar_t) == sizeof(UTF16)) { - UTF16 * pUtf16 = (UTF16 *) a_pOutputData; - retval = ConvertUTF8toUTF16( - &pUtf8, pUtf8 + a_uInputDataLen, - &pUtf16, pUtf16 + a_uOutputDataSize, - lenientConversion); - } - return retval == conversionOK; - } - - // convert to wchar_t - size_t retval = mbstowcs(a_pOutputData, - a_pInputData, a_uOutputDataSize); - return retval != (size_t)(-1); - } - - /** Calculate the number of char required by the storage format of this - * data. The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData NULL terminated string to calculate the number of - * bytes required to be converted to storage format. - * @return Number of bytes required by the string when - * converted to storage format. This size always - * includes space for the terminating NULL character. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeToStore( - const SI_CHAR * a_pInputData) - { - if (m_bStoreIsUtf8) { - // worst case scenario for wchar_t to UTF-8 is 1 wchar_t -> 6 char - size_t uLen = 0; - while (a_pInputData[uLen]) { - ++uLen; - } - return (6 * uLen) + 1; - } - else { - size_t uLen = wcstombs(NULL, a_pInputData, 0); - if (uLen == (size_t)(-1)) { - return uLen; - } - return uLen + 1; // include NULL terminator - } - } - - /** Convert the input string to the storage format of this data. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData NULL terminated source string to convert. All of - * the data will be converted including the - * terminating NULL character. - * @param a_pOutputData Pointer to the buffer to receive the converted - * string. - * @param a_uOutputDataSize Size of the output buffer in char. - * @return true if all of the input data, including the - * terminating NULL character was successfully - * converted. - */ - bool ConvertToStore( - const SI_CHAR * a_pInputData, - char * a_pOutputData, - size_t a_uOutputDataSize - ) - { - if (m_bStoreIsUtf8) { - // calc input string length (SI_CHAR type and size independent) - size_t uInputLen = 0; - while (a_pInputData[uInputLen]) { - ++uInputLen; - } - ++uInputLen; // include the NULL char - - // This uses the Unicode reference implementation to do the - // conversion from wchar_t to UTF-8. The required files are - // ConvertUTF.h and ConvertUTF.c which should be included in - // the distribution but are publically available from unicode.org - // at http://www.unicode.org/Public/PROGRAMS/CVTUTF/ - ConversionResult retval; - UTF8 * pUtf8 = (UTF8 *) a_pOutputData; - if (sizeof(wchar_t) == sizeof(UTF32)) { - const UTF32 * pUtf32 = (const UTF32 *) a_pInputData; - retval = ConvertUTF32toUTF8( - &pUtf32, pUtf32 + uInputLen, - &pUtf8, pUtf8 + a_uOutputDataSize, - lenientConversion); - } - else if (sizeof(wchar_t) == sizeof(UTF16)) { - const UTF16 * pUtf16 = (const UTF16 *) a_pInputData; - retval = ConvertUTF16toUTF8( - &pUtf16, pUtf16 + uInputLen, - &pUtf8, pUtf8 + a_uOutputDataSize, - lenientConversion); - } - return retval == conversionOK; - } - else { - size_t retval = wcstombs(a_pOutputData, - a_pInputData, a_uOutputDataSize); - return retval != (size_t) -1; - } - } -}; - -#endif // SI_CONVERT_GENERIC - - -// --------------------------------------------------------------------------- -// SI_CONVERT_ICU -// --------------------------------------------------------------------------- -#ifdef SI_CONVERT_ICU - -#define SI_Case SI_GenericCase -#define SI_NoCase SI_GenericNoCase - -#include - -/** - * Converts MBCS/UTF-8 to UChar using ICU. This can be used on all platforms. - */ -template -class SI_ConvertW { - const char * m_pEncoding; - UConverter * m_pConverter; -protected: - SI_ConvertW() : m_pEncoding(NULL), m_pConverter(NULL) { } -public: - SI_ConvertW(bool a_bStoreIsUtf8) : m_pConverter(NULL) { - m_pEncoding = a_bStoreIsUtf8 ? "UTF-8" : NULL; - } - - /* copy and assignment */ - SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } - SI_ConvertW & operator=(const SI_ConvertW & rhs) { - m_pEncoding = rhs.m_pEncoding; - m_pConverter = NULL; - return *this; - } - ~SI_ConvertW() { if (m_pConverter) ucnv_close(m_pConverter); } - - /** Calculate the number of UChar required for converting the input - * from the storage format. The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to UChar. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @return Number of UChar required by the string when - * converted. If there are embedded NULL bytes in the - * input data, only the string up and not including - * the NULL byte will be converted. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeFromStore( - const char * a_pInputData, - size_t a_uInputDataLen) - { - SI_ASSERT(a_uInputDataLen != (size_t) -1); - - UErrorCode nError; - - if (!m_pConverter) { - nError = U_ZERO_ERROR; - m_pConverter = ucnv_open(m_pEncoding, &nError); - if (U_FAILURE(nError)) { - return (size_t) -1; - } - } - - nError = U_ZERO_ERROR; - int32_t nLen = ucnv_toUChars(m_pConverter, NULL, 0, - a_pInputData, (int32_t) a_uInputDataLen, &nError); - if (U_FAILURE(nError) && nError != U_BUFFER_OVERFLOW_ERROR) { - return (size_t) -1; - } - - return (size_t) nLen; - } - - /** Convert the input string from the storage format to UChar. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to UChar. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @param a_pOutputData Pointer to the output buffer to received the - * converted data. - * @param a_uOutputDataSize Size of the output buffer in UChar. - * @return true if all of the input data was successfully - * converted. - */ - bool ConvertFromStore( - const char * a_pInputData, - size_t a_uInputDataLen, - UChar * a_pOutputData, - size_t a_uOutputDataSize) - { - UErrorCode nError; - - if (!m_pConverter) { - nError = U_ZERO_ERROR; - m_pConverter = ucnv_open(m_pEncoding, &nError); - if (U_FAILURE(nError)) { - return false; - } - } - - nError = U_ZERO_ERROR; - ucnv_toUChars(m_pConverter, - a_pOutputData, (int32_t) a_uOutputDataSize, - a_pInputData, (int32_t) a_uInputDataLen, &nError); - if (U_FAILURE(nError)) { - return false; - } - - return true; - } - - /** Calculate the number of char required by the storage format of this - * data. The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData NULL terminated string to calculate the number of - * bytes required to be converted to storage format. - * @return Number of bytes required by the string when - * converted to storage format. This size always - * includes space for the terminating NULL character. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeToStore( - const UChar * a_pInputData) - { - UErrorCode nError; - - if (!m_pConverter) { - nError = U_ZERO_ERROR; - m_pConverter = ucnv_open(m_pEncoding, &nError); - if (U_FAILURE(nError)) { - return (size_t) -1; - } - } - - nError = U_ZERO_ERROR; - int32_t nLen = ucnv_fromUChars(m_pConverter, NULL, 0, - a_pInputData, -1, &nError); - if (U_FAILURE(nError) && nError != U_BUFFER_OVERFLOW_ERROR) { - return (size_t) -1; - } - - return (size_t) nLen + 1; - } - - /** Convert the input string to the storage format of this data. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData NULL terminated source string to convert. All of - * the data will be converted including the - * terminating NULL character. - * @param a_pOutputData Pointer to the buffer to receive the converted - * string. - * @param a_pOutputDataSize Size of the output buffer in char. - * @return true if all of the input data, including the - * terminating NULL character was successfully - * converted. - */ - bool ConvertToStore( - const UChar * a_pInputData, - char * a_pOutputData, - size_t a_uOutputDataSize) - { - UErrorCode nError; - - if (!m_pConverter) { - nError = U_ZERO_ERROR; - m_pConverter = ucnv_open(m_pEncoding, &nError); - if (U_FAILURE(nError)) { - return false; - } - } - - nError = U_ZERO_ERROR; - ucnv_fromUChars(m_pConverter, - a_pOutputData, (int32_t) a_uOutputDataSize, - a_pInputData, -1, &nError); - if (U_FAILURE(nError)) { - return false; - } - - return true; - } -}; - -#endif // SI_CONVERT_ICU - - -// --------------------------------------------------------------------------- -// SI_CONVERT_WIN32 -// --------------------------------------------------------------------------- -#ifdef SI_CONVERT_WIN32 - -#define SI_Case SI_GenericCase - -// Windows CE doesn't have errno or MBCS libraries -#ifdef _WIN32_WCE -# ifndef SI_NO_MBCS -# define SI_NO_MBCS -# endif -#endif - -#include -#ifdef SI_NO_MBCS -# define SI_NoCase SI_GenericNoCase -#else // !SI_NO_MBCS -/** - * Case-insensitive comparison class using Win32 MBCS functions. This class - * returns a case-insensitive semi-collation order for MBCS text. It may not - * be safe for UTF-8 text returned in char format as we don't know what - * characters will be folded by the function! Therefore, if you are using - * SI_CHAR == char and SetUnicode(true), then you need to use the generic - * SI_NoCase class instead. - */ -#include -template -struct SI_NoCase { - bool operator()(const SI_CHAR * pLeft, const SI_CHAR * pRight) const { - if (sizeof(SI_CHAR) == sizeof(char)) { - return _mbsicmp((const unsigned char *)pLeft, - (const unsigned char *)pRight) < 0; - } - if (sizeof(SI_CHAR) == sizeof(wchar_t)) { - return _wcsicmp((const wchar_t *)pLeft, - (const wchar_t *)pRight) < 0; - } - return SI_GenericNoCase()(pLeft, pRight); - } -}; -#endif // SI_NO_MBCS - -/** - * Converts MBCS and UTF-8 to a wchar_t (or equivalent) on Windows. This uses - * only the Win32 functions and doesn't require the external Unicode UTF-8 - * conversion library. It will not work on Windows 95 without using Microsoft - * Layer for Unicode in your application. - */ -template -class SI_ConvertW { - UINT m_uCodePage; -protected: - SI_ConvertW() { } -public: - SI_ConvertW(bool a_bStoreIsUtf8) { - m_uCodePage = a_bStoreIsUtf8 ? CP_UTF8 : CP_ACP; - } - - /* copy and assignment */ - SI_ConvertW(const SI_ConvertW & rhs) { operator=(rhs); } - SI_ConvertW & operator=(const SI_ConvertW & rhs) { - m_uCodePage = rhs.m_uCodePage; - return *this; - } - - /** Calculate the number of SI_CHAR required for converting the input - * from the storage format. The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to SI_CHAR. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @return Number of SI_CHAR required by the string when - * converted. If there are embedded NULL bytes in the - * input data, only the string up and not including - * the NULL byte will be converted. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeFromStore( - const char * a_pInputData, - size_t a_uInputDataLen) - { - SI_ASSERT(a_uInputDataLen != (size_t) -1); - - int retval = MultiByteToWideChar( - m_uCodePage, 0, - a_pInputData, (int) a_uInputDataLen, - 0, 0); - return (size_t)(retval > 0 ? retval : -1); - } - - /** Convert the input string from the storage format to SI_CHAR. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData Data in storage format to be converted to SI_CHAR. - * @param a_uInputDataLen Length of storage format data in bytes. This - * must be the actual length of the data, including - * NULL byte if NULL terminated string is required. - * @param a_pOutputData Pointer to the output buffer to received the - * converted data. - * @param a_uOutputDataSize Size of the output buffer in SI_CHAR. - * @return true if all of the input data was successfully - * converted. - */ - bool ConvertFromStore( - const char * a_pInputData, - size_t a_uInputDataLen, - SI_CHAR * a_pOutputData, - size_t a_uOutputDataSize) - { - int nSize = MultiByteToWideChar( - m_uCodePage, 0, - a_pInputData, (int) a_uInputDataLen, - (wchar_t *) a_pOutputData, (int) a_uOutputDataSize); - return (nSize > 0); - } - - /** Calculate the number of char required by the storage format of this - * data. The storage format is always UTF-8. - * - * @param a_pInputData NULL terminated string to calculate the number of - * bytes required to be converted to storage format. - * @return Number of bytes required by the string when - * converted to storage format. This size always - * includes space for the terminating NULL character. - * @return -1 cast to size_t on a conversion error. - */ - size_t SizeToStore( - const SI_CHAR * a_pInputData) - { - int retval = WideCharToMultiByte( - m_uCodePage, 0, - (const wchar_t *) a_pInputData, -1, - 0, 0, 0, 0); - return (size_t) (retval > 0 ? retval : -1); - } - - /** Convert the input string to the storage format of this data. - * The storage format is always UTF-8 or MBCS. - * - * @param a_pInputData NULL terminated source string to convert. All of - * the data will be converted including the - * terminating NULL character. - * @param a_pOutputData Pointer to the buffer to receive the converted - * string. - * @param a_pOutputDataSize Size of the output buffer in char. - * @return true if all of the input data, including the - * terminating NULL character was successfully - * converted. - */ - bool ConvertToStore( - const SI_CHAR * a_pInputData, - char * a_pOutputData, - size_t a_uOutputDataSize) - { - int retval = WideCharToMultiByte( - m_uCodePage, 0, - (const wchar_t *) a_pInputData, -1, - a_pOutputData, (int) a_uOutputDataSize, 0, 0); - return retval > 0; - } -}; - -#endif // SI_CONVERT_WIN32 - - -// --------------------------------------------------------------------------- -// TYPE DEFINITIONS -// --------------------------------------------------------------------------- - -typedef CSimpleIniTempl,SI_ConvertA > CSimpleIniA; -typedef CSimpleIniTempl,SI_ConvertA > CSimpleIniCaseA; - -#if defined(SI_CONVERT_ICU) -typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniW; -typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniCaseW; -#else -typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniW; -typedef CSimpleIniTempl,SI_ConvertW > CSimpleIniCaseW; -#endif - -#ifdef _UNICODE -# define CSimpleIni CSimpleIniW -# define CSimpleIniCase CSimpleIniCaseW -# define SI_NEWLINE SI_NEWLINE_W -#else // !_UNICODE -# define CSimpleIni CSimpleIniA -# define CSimpleIniCase CSimpleIniCaseA -# define SI_NEWLINE SI_NEWLINE_A -#endif // _UNICODE - -#ifdef _MSC_VER -# pragma warning (pop) -#endif - -#endif // INCLUDED_SimpleIni_h - diff --git a/VCMP-LUA/include/utility.h b/VCMP-LUA/include/utility.h deleted file mode 100644 index b286051..0000000 --- a/VCMP-LUA/include/utility.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once -#include "pch.h" -#include - -static inline void raw_split(const std::string& s, char delim, std::vector& elems) -{ - std::stringstream ss(s); - std::string item; - while (getline(ss, item, delim)) { - if (!item.empty()) - elems.push_back(item); - } -} - -namespace std { - - static inline std::vector split(const std::string& s, char delim) - { - std::vector elems; - raw_split(s, delim, elems); - return elems; - } - -} - -#if defined(_WIN32) || defined(WIN32) -static inline LARGE_INTEGER GetFrequency() -{ - LARGE_INTEGER frequency; - QueryPerformanceFrequency(&frequency); - return frequency; -} - -static uint32_t GetCurrentSysTime() -{ - HANDLE current_thread = GetCurrentThread(); - DWORD_PTR previous_mask = SetThreadAffinityMask(current_thread, 1); - - static const LARGE_INTEGER frequency = GetFrequency(); - - // Get the current time - LARGE_INTEGER time; - QueryPerformanceCounter(&time); - - // Restore the thread affinity - SetThreadAffinityMask(current_thread, previous_mask); - - // Return the current time as miliseconds - return static_cast(1000000LL * time.QuadPart / frequency.QuadPart); -} -#else -static uint32_t GetCurrentSysTime() -{ - // POSIX implementation - timespec time; - clock_gettime(CLOCK_MONOTONIC, &time); - return static_cast(uint64_t(time.tv_sec) * 1000000 + time.tv_nsec / 1000); -} -#endif diff --git a/VCMP-LUA/include/vcmp.h b/VCMP-LUA/include/vcmp.h deleted file mode 100644 index c01106f..0000000 --- a/VCMP-LUA/include/vcmp.h +++ /dev/null @@ -1,1010 +0,0 @@ -/* - Project: Vice City Multiplayer 0.4 Server / Plugin Kit - File: plugin.h - - Copyright 2011-2016 Ago Allikmaa (maxorator) - - 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. -*/ - -#pragma once - -#include -#include - -#ifdef WIN32 -#define EXPORT __declspec(dllexport) -#else -#define EXPORT -#endif - -#define PLUGIN_API_MAJOR 2 -#define PLUGIN_API_MINOR 0 - -typedef struct { - uint32_t structSize; - char serverName[128]; - uint32_t maxPlayers; - uint32_t port; - uint32_t flags; -} ServerSettings; - -typedef struct { - uint32_t structSize; - uint32_t pluginId; - char name[32]; - uint32_t pluginVersion; - uint16_t apiMajorVersion; - uint16_t apiMinorVersion; -} PluginInfo; - -typedef enum { - vcmpErrorNone = 0, - vcmpErrorNoSuchEntity = 1, - vcmpErrorBufferTooSmall = 2, - vcmpErrorTooLargeInput = 3, - vcmpErrorArgumentOutOfBounds = 4, - vcmpErrorNullArgument = 5, - vcmpErrorPoolExhausted = 6, - vcmpErrorInvalidName = 7, - vcmpErrorRequestDenied = 8, - forceSizeVcmpError = INT32_MAX -} vcmpError; - -typedef enum { - vcmpEntityPoolVehicle = 1, - vcmpEntityPoolObject = 2, - vcmpEntityPoolPickup = 3, - vcmpEntityPoolRadio = 4, - vcmpEntityPoolBlip = 7, - vcmpEntityPoolCheckPoint = 8, - forceSizeVcmpEntityPool = INT32_MAX -} vcmpEntityPool; - -typedef enum { - vcmpDisconnectReasonTimeout = 0, - vcmpDisconnectReasonQuit = 1, - vcmpDisconnectReasonKick = 2, - vcmpDisconnectReasonCrash = 3, - vcmpDisconnectReasonAntiCheat = 4, - forceSizeVcmpDisconnectReason = INT32_MAX -} vcmpDisconnectReason; - -typedef enum { - vcmpBodyPartBody = 0, - vcmpBodyPartTorso = 1, - vcmpBodyPartLeftArm = 2, - vcmpBodyPartRightArm = 3, - vcmpBodyPartLeftLeg = 4, - vcmpBodyPartRightLeg = 5, - vcmpBodyPartHead = 6, - vcmpBodyPartInVehicle = 7, - forceSizeVcmpBodyPart = INT32_MAX -} vcmpBodyPart; - -typedef enum { - vcmpPlayerStateNone = 0, - vcmpPlayerStateNormal = 1, - vcmpPlayerStateAim = 2, - vcmpPlayerStateDriver = 3, - vcmpPlayerStatePassenger = 4, - vcmpPlayerStateEnterDriver = 5, - vcmpPlayerStateEnterPassenger = 6, - vcmpPlayerStateExit = 7, - vcmpPlayerStateUnspawned = 8, - forceSizeVcmpPlayerState = INT32_MAX -} vcmpPlayerState; - -typedef enum { - vcmpPlayerUpdateNormal = 0, - vcmpPlayerUpdateAiming = 1, - vcmpPlayerUpdateDriver = 2, - vcmpPlayerUpdatePassenger = 3, - forceSizeVcmpPlayerUpdate = INT32_MAX -} vcmpPlayerUpdate; - -typedef enum { - vcmpPlayerVehicleOut = 0, - vcmpPlayerVehicleEntering = 1, - vcmpPlayerVehicleExiting = 2, - vcmpPlayerVehicleIn = 3, - forceSizeVcmpPlayerVehicle = INT32_MAX -} vcmpPlayerVehicle; - -typedef enum { - vcmpVehicleSyncNone = 0, - vcmpVehicleSyncDriver = 1, - vcmpVehicleSyncPassenger = 3, - vcmpVehicleSyncNear = 4, - forceSizeVcmpVehicleSync = INT32_MAX -} vcmpVehicleSync; - -typedef enum { - vcmpVehicleUpdateDriverSync = 0, - vcmpVehicleUpdateOtherSync = 1, - vcmpVehicleUpdatePosition = 2, - vcmpVehicleUpdateHealth = 4, - vcmpVehicleUpdateColour = 5, - vcmpVehicleUpdateRotation = 6, - forceSizeVcmpVehicleUpdate = INT32_MAX -} vcmpVehicleUpdate; - -typedef enum { - vcmpServerOptionSyncFrameLimiter = 0, - vcmpServerOptionFrameLimiter = 1, - vcmpServerOptionTaxiBoostJump = 2, - vcmpServerOptionDriveOnWater = 3, - vcmpServerOptionFastSwitch = 4, - vcmpServerOptionFriendlyFire = 5, - vcmpServerOptionDisableDriveBy = 6, - vcmpServerOptionPerfectHandling = 7, - vcmpServerOptionFlyingCars = 8, - vcmpServerOptionJumpSwitch = 9, - vcmpServerOptionShowMarkers = 10, - vcmpServerOptionOnlyShowTeamMarkers = 11, - vcmpServerOptionStuntBike = 12, - vcmpServerOptionShootInAir = 13, - vcmpServerOptionShowNameTags = 14, - vcmpServerOptionJoinMessages = 15, - vcmpServerOptionDeathMessages = 16, - vcmpServerOptionChatTagsEnabled = 17, - vcmpServerOptionUseClasses = 18, - vcmpServerOptionWallGlitch = 19, - vcmpServerOptionDisableBackfaceCulling = 20, - vcmpServerOptionDisableHeliBladeDamage = 21, - vcmpServerOptionDisableCrouch = 22, - forceSizeVcmpServerOption = INT32_MAX -} vcmpServerOption; - -typedef enum { - vcmpPlayerOptionControllable = 0, - vcmpPlayerOptionDriveBy = 1, - vcmpPlayerOptionWhiteScanlines = 2, - vcmpPlayerOptionGreenScanlines = 3, - vcmpPlayerOptionWidescreen = 4, - vcmpPlayerOptionShowMarkers = 5, - vcmpPlayerOptionCanAttack = 6, - vcmpPlayerOptionHasMarker = 7, - vcmpPlayerOptionChatTagsEnabled = 8, - vcmpPlayerOptionDrunkEffectsDeprecated = 9, - vcmpPlayerOptionBleeding = 10, - forceSizeVcmpPlayerOption = INT32_MAX -} vcmpPlayerOption; - -typedef enum { - vcmpVehicleOptionDoorsLocked = 0, - vcmpVehicleOptionAlarm = 1, - vcmpVehicleOptionLights = 2, - vcmpVehicleOptionRadioLocked = 3, - vcmpVehicleOptionGhost = 4, - vcmpVehicleOptionSiren = 5, - vcmpVehicleOptionSingleUse = 6, - vcmpVehicleOptionEngineDisabled = 7, - vcmpVehicleOptionBootOpen = 8, - vcmpVehicleOptionBonnetOpen = 9, - forceSizeVcmpVehicleOption = INT32_MAX -} vcmpVehicleOption; - -typedef enum { - vcmpPickupOptionSingleUse = 0, - forceSizeVcmpPickupOption = INT32_MAX -} vcmpPickupOption; - -typedef struct { - uint32_t structSize; - - /** - * Plugin system - */ - - /* success */ - uint32_t(*GetServerVersion) (void); - /* vcmpErrorNullArgument */ - vcmpError(*GetServerSettings) (ServerSettings* settings); - /* vcmpErrorNoSuchEntity */ - vcmpError(*ExportFunctions) (int32_t pluginId, const void** functionList, size_t size); - /* success */ - uint32_t(*GetNumberOfPlugins) (void); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument */ - vcmpError(*GetPluginInfo) (int32_t pluginId, PluginInfo* pluginInfo); - /* -1 == vcmpEntityNone */ - int32_t(*FindPlugin) (const char* pluginName); - /* GetLastError: vcmpErrorNoSuchEntity */ - const void** (*GetPluginExports) (int32_t pluginId, size_t* exportCount); - /* vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*SendPluginCommand) (uint32_t commandIdentifier, const char* format, ...); - /* success */ - uint64_t(*GetTime) (void); - /* vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*LogMessage) (const char* format, ...); - /* success */ - vcmpError(*GetLastError) (void); - - /** - * Client messages - */ - - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*SendClientScriptData) (int32_t playerId, const void* data, size_t size); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*SendClientMessage) (int32_t playerId, uint32_t colour, const char* format, ...); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds, vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*SendGameMessage) (int32_t playerId, int32_t type, const char* format, ...); - - /* - * Server settings - */ - - /* vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*SetServerName) (const char* text); - /* vcmpErrorNullArgument, vcmpErrorBufferTooSmall */ - vcmpError(*GetServerName) (char* buffer, size_t size); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetMaxPlayers) (uint32_t maxPlayers); - /* success */ - uint32_t(*GetMaxPlayers) (void); - /* vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*SetServerPassword) (const char* password); - /* vcmpErrorNullArgument, vcmpErrorBufferTooSmall */ - vcmpError(*GetServerPassword) (char* buffer, size_t size); - /* vcmpErrorNullArgument, vcmpErrorTooLargeInput */ - vcmpError(*SetGameModeText) (const char* gameMode); - /* vcmpErrorNullArgument, vcmpErrorBufferTooSmall */ - vcmpError(*GetGameModeText) (char* buffer, size_t size); - /* success */ - void(*ShutdownServer) (void); - - /* - * Game environment settings - */ - - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetServerOption) (vcmpServerOption option, uint8_t toggle); - /* GetLastError: vcmpErrorArgumentOutOfBounds */ - uint8_t(*GetServerOption) (vcmpServerOption option); - /* success */ - void(*SetWorldBounds) (float maxX, float minX, float maxY, float minY); - /* success */ - void(*GetWorldBounds) (float* maxXOut, float* minXOut, float* maxYOut, float* minYOut); - /* success */ - void(*SetWastedSettings) (uint32_t deathTimer, uint32_t fadeTimer, float fadeInSpeed, float fadeOutSpeed, uint32_t fadeColour, uint32_t corpseFadeStart, uint32_t corpseFadeTime); - /* success */ - void(*GetWastedSettings) (uint32_t* deathTimerOut, uint32_t* fadeTimerOut, float* fadeInSpeedOut, float* fadeOutSpeedOut, uint32_t* fadeColourOut, uint32_t* corpseFadeStartOut, uint32_t* corpseFadeTimeOut); - /* success */ - void(*SetTimeRate) (int32_t timeRate); - /* success */ - int32_t(*GetTimeRate) (void); - /* success */ - void(*SetHour) (int32_t hour); - /* success */ - int32_t(*GetHour) (void); - /* success */ - void(*SetMinute) (int32_t minute); - /* success */ - int32_t(*GetMinute) (void); - /* success */ - void(*SetWeather) (int32_t weather); - /* success */ - int32_t(*GetWeather) (void); - /* success */ - void(*SetGravity) (float gravity); - /* success */ - float(*GetGravity) (void); - /* success */ - void(*SetGameSpeed) (float gameSpeed); - /* success */ - float(*GetGameSpeed) (void); - /* success */ - void(*SetWaterLevel) (float waterLevel); - /* success */ - float(*GetWaterLevel) (void); - /* success */ - void(*SetMaximumFlightAltitude) (float height); - /* success */ - float(*GetMaximumFlightAltitude) (void); - /* success */ - void(*SetKillCommandDelay) (int32_t delay); - /* success */ - int32_t(*GetKillCommandDelay) (void); - /* success */ - void(*SetVehiclesForcedRespawnHeight) (float height); - /* success */ - float(*GetVehiclesForcedRespawnHeight) (void); - - /* - * Miscellaneous things - */ - - /* vcmpErrorArgumentOutOfBounds, vcmpErrorNoSuchEntity */ - vcmpError(*CreateExplosion) (int32_t worldId, int32_t type, float x, float y, float z, int32_t responsiblePlayerId, uint8_t atGroundLevel); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*PlaySound) (int32_t worldId, int32_t soundId, float x, float y, float z); - /* success */ - void(*HideMapObject) (int32_t modelId, int16_t tenthX, int16_t tenthY, int16_t tenthZ); - /* success */ - void(*ShowMapObject) (int32_t modelId, int16_t tenthX, int16_t tenthY, int16_t tenthZ); - /* success */ - void(*ShowAllMapObjects) (void); - - /* - * Weapon settings - */ - - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetWeaponDataValue) (int32_t weaponId, int32_t fieldId, double value); - /* GetLastError: vcmpErrorArgumentOutOfBounds */ - double(*GetWeaponDataValue) (int32_t weaponId, int32_t fieldId); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*ResetWeaponDataValue) (int32_t weaponId, int32_t fieldId); - /* GetLastError: vcmpErrorArgumentOutOfBounds */ - uint8_t(*IsWeaponDataValueModified) (int32_t weaponId, int32_t fieldId); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*ResetWeaponData) (int32_t weaponId); - /* success */ - void(*ResetAllWeaponData) (void); - - /* - * Key binds - */ - - /* -1 == vcmpEntityNone */ - int32_t(*GetKeyBindUnusedSlot) (void); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetKeyBindData) (int32_t bindId, uint8_t* isCalledOnReleaseOut, int32_t* keyOneOut, int32_t* keyTwoOut, int32_t* keyThreeOut); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*RegisterKeyBind) (int32_t bindId, uint8_t isCalledOnRelease, int32_t keyOne, int32_t keyTwo, int32_t keyThree); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RemoveKeyBind) (int32_t bindId); - /* success */ - void(*RemoveAllKeyBinds) (void); - - /* - * Coordinate blips - */ - - /* GetLastError: vcmpErrorPoolExhausted */ - int32_t(*CreateCoordBlip) (int32_t index, int32_t world, float x, float y, float z, int32_t scale, uint32_t colour, int32_t sprite); - /* vcmpErrorNoSuchEntity */ - vcmpError(*DestroyCoordBlip) (int32_t index); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetCoordBlipInfo) (int32_t index, int32_t* worldOut, float* xOut, float* yOUt, float* zOut, int32_t* scaleOut, uint32_t* colourOut, int32_t* spriteOut); - - /* - * Radios - */ - - /* vcmpErrorArgumentOutOfBounds, vcmpErrorNullArgument */ - vcmpError(*AddRadioStream) (int32_t radioId, const char* radioName, const char* radioUrl, uint8_t isListed); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RemoveRadioStream) (int32_t radioId); - - /* - * Spawning and classes - */ - - /* GetLastError: vcmpErrorArgumentOutOfBounds, vcmpErrorPoolExhausted */ - int32_t(*AddPlayerClass) (int32_t teamId, uint32_t colour, int32_t modelIndex, float x, float y, float z, float angle, int32_t weaponOne, int32_t weaponOneAmmo, int32_t weaponTwo, int32_t weaponTwoAmmo, int32_t weaponThree, int32_t weaponThreeAmmo); - /* success */ - void(*SetSpawnPlayerPosition) (float x, float y, float z); - /* success */ - void(*SetSpawnCameraPosition) (float x, float y, float z); - /* success */ - void(*SetSpawnCameraLookAt) (float x, float y, float z); - - /* - * Administration - */ - - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerAdmin) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerAdmin) (int32_t playerId, uint8_t toggle); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument, vcmpErrorBufferTooSmall */ - vcmpError(*GetPlayerIP) (int32_t playerId, char* buffer, size_t size); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument, vcmpErrorBufferTooSmall */ - vcmpError(*GetPlayerUID) (int32_t playerId, char* buffer, size_t size); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument, vcmpErrorBufferTooSmall */ - vcmpError(*GetPlayerUID2) (int32_t playerId, char* buffer, size_t size); - /* vcmpErrorNoSuchEntity */ - vcmpError(*KickPlayer) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*BanPlayer) (int32_t playerId); - /* success */ - void(*BanIP) (char* ipAddress); - /* success */ - uint8_t(*UnbanIP) (char* ipAddress); - /* success */ - uint8_t(*IsIPBanned) (char* ipAddress); - - /* - * Player access and basic info - */ - - /* -1 == vcmpEntityNone */ - int32_t(*GetPlayerIdFromName) (const char* name); - /* success */ - uint8_t(*IsPlayerConnected) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerStreamedForPlayer) (int32_t checkedPlayerId, int32_t playerId); - /* vcmpErrorNoSuchEntity */ - uint32_t(*GetPlayerKey) (int32_t playerId); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument, vcmpErrorBufferTooSmall */ - vcmpError(*GetPlayerName) (int32_t playerId, char* buffer, size_t size); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument, vcmpErrorInvalidName, vcmpErrorTooLargeInput */ - vcmpError(*SetPlayerName) (int32_t playerId, const char* name); - /* GetLastError: vcmpErrorNoSuchEntity */ - vcmpPlayerState(*GetPlayerState) (int32_t playerId); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetPlayerOption) (int32_t playerId, vcmpPlayerOption option, uint8_t toggle); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - uint8_t(*GetPlayerOption) (int32_t playerId, vcmpPlayerOption option); - - /* - * Player world - */ - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerWorld) (int32_t playerId, int32_t world); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerWorld) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerSecondaryWorld) (int32_t playerId, int32_t secondaryWorld); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerSecondaryWorld) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerUniqueWorld) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerWorldCompatible) (int32_t playerId, int32_t world); - - /* - * Player class, team, skin, colour - */ - - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerClass) (int32_t playerId); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetPlayerTeam) (int32_t playerId, int32_t teamId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerTeam) (int32_t playerId); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetPlayerSkin) (int32_t playerId, int32_t skinId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerSkin) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerColour) (int32_t playerId, uint32_t colour); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetPlayerColour) (int32_t playerId); - - /* - * Player spawn cycle - */ - - /* vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerSpawned) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*ForcePlayerSpawn) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*ForcePlayerSelect) (int32_t playerId); - /* success */ - void(*ForceAllSelect) (void); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerTyping) (int32_t playerId); - - /* - * Player money, score, wanted level - */ - - /* vcmpErrorNoSuchEntity */ - vcmpError(*GivePlayerMoney) (int32_t playerId, int32_t amount); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerMoney) (int32_t playerId, int32_t amount); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerMoney) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerScore) (int32_t playerId, int32_t score); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerScore) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerWantedLevel) (int32_t playerId, int32_t level); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerWantedLevel) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerPing) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - double(*GetPlayerFPS) (int32_t playerId); - - /* - * Player health and immunity - */ - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerHealth) (int32_t playerId, float health); - /* GetLastError: vcmpErrorNoSuchEntity */ - float(*GetPlayerHealth) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerArmour) (int32_t playerId, float armour); - /* GetLastError: vcmpErrorNoSuchEntity */ - float(*GetPlayerArmour) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerImmunityFlags) (int32_t playerId, uint32_t flags); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetPlayerImmunityFlags) (int32_t playerId); - - /* - * Player position and rotation - */ - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerPosition) (int32_t playerId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetPlayerPosition) (int32_t playerId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerSpeed) (int32_t playerId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetPlayerSpeed) (int32_t playerId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*AddPlayerSpeed) (int32_t playerId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerHeading) (int32_t playerId, float angle); - /* GetLastError: vcmpErrorNoSuchEntity */ - float(*GetPlayerHeading) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerAlpha) (int32_t playerId, int32_t alpha, uint32_t fadeTime); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerAlpha) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetPlayerAimPosition) (int32_t playerId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetPlayerAimDirection) (int32_t playerId, float* xOut, float* yOut, float* zOut); - - /* - * Player actions and keys - */ - - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerOnFire) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerCrouching) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerAction) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetPlayerGameKeys) (int32_t playerId); - - /* - * Player vehicle - */ - - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds, vcmpErrorRequestDenied */ - vcmpError(*PutPlayerInVehicle) (int32_t playerId, int32_t vehicleId, int32_t slotIndex, uint8_t makeRoom, uint8_t warp); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RemovePlayerFromVehicle) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - vcmpPlayerVehicle(*GetPlayerInVehicleStatus) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerInVehicleSlot) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerVehicleId) (int32_t playerId); - - /* - * Player weapons - */ - - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*GivePlayerWeapon) (int32_t playerId, int32_t weaponId, int32_t ammo); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetPlayerWeapon) (int32_t playerId, int32_t weaponId, int32_t ammo); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerWeapon) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerWeaponAmmo) (int32_t playerId); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetPlayerWeaponSlot) (int32_t playerId, int32_t slot); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerWeaponSlot) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - int32_t(*GetPlayerWeaponAtSlot) (int32_t playerId, int32_t slot); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - int32_t(*GetPlayerAmmoAtSlot) (int32_t playerId, int32_t slot); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RemovePlayerWeapon) (int32_t playerId, int32_t weaponId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RemoveAllWeapons) (int32_t playerId); - - /* - * Player camera - */ - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetCameraPosition) (int32_t playerId, float posX, float posY, float posZ, float lookX, float lookY, float lookZ); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RestoreCamera) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsCameraLocked) (int32_t playerId); - - /* - * Player miscellaneous stuff - */ - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerAnimation) (int32_t playerId, int32_t groupId, int32_t animationId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerStandingOnVehicle) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerStandingOnObject) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPlayerAway) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - int32_t(*GetPlayerSpectateTarget) (int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerSpectateTarget) (int32_t playerId, int32_t targetId); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument */ - vcmpError(*RedirectPlayerToServer) (int32_t playerId, const char* ip, uint32_t port, const char* nick, const char* serverPassword, const char* userPassword); - - /* - * All entities - */ - - /* GetLastError: vcmpArgumentOutOfBounds */ - uint8_t(*CheckEntityExists) (vcmpEntityPool entityPool, int32_t index); - - /* - * Vehicles - */ - - /* GetLastError: vcmpErrorArgumentOutOfBounds, vcmpErrorPoolExhausted */ - int32_t(*CreateVehicle) (int32_t modelIndex, int32_t world, float x, float y, float z, float angle, int32_t primaryColour, int32_t secondaryColour); - /* vcmpErrorNoSuchEntity */ - vcmpError(*DeleteVehicle) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetVehicleOption) (int32_t vehicleId, vcmpVehicleOption option, uint8_t toggle); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - uint8_t(*GetVehicleOption) (int32_t vehicleId, vcmpVehicleOption option); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetVehicleSyncSource) (int32_t vehicleId); - /* GetLastError: vcmpErrorNoSuchEntity */ - vcmpVehicleSync(*GetVehicleSyncType) (int32_t vehicleId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsVehicleStreamedForPlayer) (int32_t vehicleId, int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleWorld) (int32_t vehicleId, int32_t world); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetVehicleWorld) (int32_t vehicleId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetVehicleModel) (int32_t vehicleId); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - int32_t(*GetVehicleOccupant) (int32_t vehicleId, int32_t slotIndex); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RespawnVehicle) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleImmunityFlags) (int32_t vehicleId, uint32_t immunityFlags); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetVehicleImmunityFlags) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*ExplodeVehicle) (int32_t vehicleId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsVehicleWrecked) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehiclePosition) (int32_t vehicleId, float x, float y, float z, uint8_t removeOccupants); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehiclePosition) (int32_t vehicleId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleRotation) (int32_t vehicleId, float x, float y, float z, float w); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleRotationEuler) (int32_t vehicleId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleRotation) (int32_t vehicleId, float* xOut, float* yOut, float* zOut, float* wOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleRotationEuler) (int32_t vehicleId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleSpeed) (int32_t vehicleId, float x, float y, float z, uint8_t add, uint8_t relative); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleSpeed) (int32_t vehicleId, float* xOut, float* yOut, float* zOut, uint8_t relative); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleTurnSpeed) (int32_t vehicleId, float x, float y, float z, uint8_t add, uint8_t relative); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleTurnSpeed) (int32_t vehicleId, float* xOut, float* yOut, float* zOut, uint8_t relative); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleSpawnPosition) (int32_t vehicleId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleSpawnPosition) (int32_t vehicleId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleSpawnRotation) (int32_t vehicleId, float x, float y, float z, float w); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleSpawnRotationEuler) (int32_t vehicleId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleSpawnRotation) (int32_t vehicleId, float* xOut, float* yOut, float* zOut, float* wOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleSpawnRotationEuler) (int32_t vehicleId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleIdleRespawnTimer) (int32_t vehicleId, uint32_t millis); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetVehicleIdleRespawnTimer) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleHealth) (int32_t vehicleId, float health); - /* GetLastError: vcmpErrorNoSuchEntity */ - float(*GetVehicleHealth) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleColour) (int32_t vehicleId, int32_t primaryColour, int32_t secondaryColour); - /* vcmpErrorNoSuchEntity, vcmpErrorNullArgument */ - vcmpError(*GetVehicleColour) (int32_t vehicleId, int32_t* primaryColourOut, int32_t* secondaryColourOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehiclePartStatus) (int32_t vehicleId, int32_t partId, int32_t status); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetVehiclePartStatus) (int32_t vehicleId, int32_t partId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleTyreStatus) (int32_t vehicleId, int32_t tyreId, int32_t status); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetVehicleTyreStatus) (int32_t vehicleId, int32_t tyreId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleDamageData) (int32_t vehicleId, uint32_t damageData); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetVehicleDamageData) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleRadio) (int32_t vehicleId, int32_t radioId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetVehicleRadio) (int32_t vehicleId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetVehicleTurretRotation) (int32_t vehicleId, float* horizontalOut, float* verticalOut); - - /* - * Vehicle handling - */ - - /* success */ - void(*ResetAllVehicleHandlings) (void); - /* vcmpErrorArgumentOutOfBounds */ - uint8_t(*ExistsHandlingRule) (int32_t modelIndex, int32_t ruleIndex); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetHandlingRule) (int32_t modelIndex, int32_t ruleIndex, double value); - /* GetLastError: vcmpErrorArgumentOutOfBounds */ - double(*GetHandlingRule) (int32_t modelIndex, int32_t ruleIndex); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*ResetHandlingRule) (int32_t modelIndex, int32_t ruleIndex); - /* vcmpErrorArgumentOutOfBounds */ - vcmpError(*ResetHandling) (int32_t modelIndex); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - uint8_t(*ExistsInstHandlingRule) (int32_t vehicleId, int32_t ruleIndex); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetInstHandlingRule) (int32_t vehicleId, int32_t ruleIndex, double value); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - double(*GetInstHandlingRule) (int32_t vehicleId, int32_t ruleIndex); - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*ResetInstHandlingRule) (int32_t vehicleId, int32_t ruleIndex); - /* vcmpErrorNoSuchEntity */ - vcmpError(*ResetInstHandling) (int32_t vehicleId); - - /* - * Pickups - */ - - /* vcmpErrorPoolExhausted */ - int32_t(*CreatePickup) (int32_t modelIndex, int32_t world, int32_t quantity, float x, float y, float z, int32_t alpha, uint8_t isAutomatic); - /* vcmpErrorNoSuchEntity */ - vcmpError(*DeletePickup) (int32_t pickupId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPickupStreamedForPlayer) (int32_t pickupId, int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPickupWorld) (int32_t pickupId, int32_t world); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPickupWorld) (int32_t pickupId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPickupAlpha) (int32_t pickupId, int32_t alpha); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPickupAlpha) (int32_t pickupId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPickupIsAutomatic) (int32_t pickupId, uint8_t toggle); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsPickupAutomatic) (int32_t pickupId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPickupAutoTimer) (int32_t pickupId, uint32_t durationMillis); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetPickupAutoTimer) (int32_t pickupId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RefreshPickup) (int32_t pickupId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPickupPosition) (int32_t pickupId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetPickupPosition) (int32_t pickupId, float* xOut, float* yOut, float* zOut); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPickupModel) (int32_t pickupId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetPickupQuantity) (int32_t pickupId); - - /* - * Checkpoints - */ - - /* vcmpErrorPoolExhausted, vcmpErrorNoSuchEntity */ - int32_t(*CreateCheckPoint) (int32_t playerId, int32_t world, uint8_t isSphere, float x, float y, float z, int32_t red, int32_t green, int32_t blue, int32_t alpha, float radius); - /* vcmpErrorNoSuchEntity */ - vcmpError(*DeleteCheckPoint) (int32_t checkPointId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsCheckPointStreamedForPlayer) (int32_t checkPointId, int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsCheckPointSphere) (int32_t checkPointId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetCheckPointWorld) (int32_t checkPointId, int32_t world); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetCheckPointWorld) (int32_t checkPointId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetCheckPointColour) (int32_t checkPointId, int32_t red, int32_t green, int32_t blue, int32_t alpha); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetCheckPointColour) (int32_t checkPointId, int32_t* redOut, int32_t* greenOut, int32_t* blueOut, int32_t* alphaOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetCheckPointPosition) (int32_t checkPointId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetCheckPointPosition) (int32_t checkPointId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetCheckPointRadius) (int32_t checkPointId, float radius); - /* GetLastError: vcmpErrorNoSuchEntity */ - float(*GetCheckPointRadius) (int32_t checkPointId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetCheckPointOwner) (int32_t checkPointId); - - /* - * Objects - */ - - /* GetLastError: vcmpErrorPoolExhausted */ - int32_t(*CreateObject) (int32_t modelIndex, int32_t world, float x, float y, float z, int32_t alpha); - /* vcmpErrorNoSuchEntity */ - vcmpError(*DeleteObject) (int32_t objectId); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsObjectStreamedForPlayer) (int32_t objectId, int32_t playerId); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetObjectModel) (int32_t objectId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetObjectWorld) (int32_t objectId, int32_t world); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetObjectWorld) (int32_t objectId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetObjectAlpha) (int32_t objectId, int32_t alpha, uint32_t duration); - /* GetLastError: vcmpErrorNoSuchEntity */ - int32_t(*GetObjectAlpha) (int32_t objectId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*MoveObjectTo) (int32_t objectId, float x, float y, float z, uint32_t duration); - /* vcmpErrorNoSuchEntity */ - vcmpError(*MoveObjectBy) (int32_t objectId, float x, float y, float z, uint32_t duration); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetObjectPosition) (int32_t objectId, float x, float y, float z); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetObjectPosition) (int32_t objectId, float* xOut, float* yOut, float* zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RotateObjectTo) (int32_t objectId, float x, float y, float z, float w, uint32_t duration); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RotateObjectToEuler) (int32_t objectId, float x, float y, float z, uint32_t duration); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RotateObjectBy) (int32_t objectId, float x, float y, float z, float w, uint32_t duration); - /* vcmpErrorNoSuchEntity */ - vcmpError(*RotateObjectByEuler) (int32_t objectId, float x, float y, float z, uint32_t duration); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetObjectRotation) (int32_t objectId, float* xOut, float* yOut, float *zOut, float *wOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*GetObjectRotationEuler) (int32_t objectId, float* xOut, float* yOut, float *zOut); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetObjectShotReportEnabled) (int32_t objectId, uint8_t toggle); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsObjectShotReportEnabled) (int32_t objectId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetObjectTouchedReportEnabled) (int32_t objectId, uint8_t toggle); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*IsObjectTouchedReportEnabled) (int32_t objectId); - - // TODO: MOVE LATER - vcmpError(*GetPlayerModuleList) (int32_t playerId); - - /* vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - vcmpError(*SetPickupOption) (int32_t pickupId, vcmpPickupOption option, uint8_t toggle); - /* GetLastError: vcmpErrorNoSuchEntity, vcmpErrorArgumentOutOfBounds */ - uint8_t(*GetPickupOption) (int32_t pickupId, vcmpPickupOption option); - - /* success */ - void(*SetFallTimer) (uint16_t timeRate); - /* success */ - uint16_t(*GetFallTimer) (void); - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicleLightsData) (int32_t vehicleId, uint32_t lightsData); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetVehicleLightsData) (int32_t vehicleId); - - /* vcmpErrorNoSuchEntity */ - vcmpError(*KillPlayer) (int32_t playerId); - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetVehicle3DArrowForPlayer) (int32_t nVehicleId, int32_t nTargetPlayerId, uint8_t bEnabled); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*GetVehicle3DArrowForPlayer) (int32_t nVehicleId, int32_t nTargetPlayerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayer3DArrowForPlayer) (int32_t nPlayerId, int32_t nTargetPlayerId, uint8_t bEnabled); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*GetPlayer3DArrowForPlayer) (int32_t nVehicleId, int32_t nTargetPlayerId); - - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerDrunkHandling) (int32_t playerId, uint32_t drunkLevel); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint32_t(*GetPlayerDrunkHandling) (int32_t playerId); - /* vcmpErrorNoSuchEntity */ - vcmpError(*SetPlayerDrunkVisuals) (int32_t playerId, uint8_t drunkLevel); - /* GetLastError: vcmpErrorNoSuchEntity */ - uint8_t(*GetPlayerDrunkVisuals) (int32_t playerId); - - /* vcmpErrorNoSuchEntity, vcmpErrorRequestDenied */ - vcmpError(*InterpolateCameraLookAt) (int32_t playerId, float lookX, float lookY, float lookZ, uint32_t interpTimeMS); - -} PluginFuncs; - -typedef struct { - uint32_t structSize; - - uint8_t(*OnServerInitialise) (void); - void(*OnServerShutdown) (void); - void(*OnServerFrame) (float elapsedTime); - - uint8_t(*OnPluginCommand) (uint32_t commandIdentifier, const char* message); - uint8_t(*OnIncomingConnection) (char* playerName, size_t nameBufferSize, const char* userPassword, const char* ipAddress); - void(*OnClientScriptData) (int32_t playerId, const uint8_t* data, size_t size); - - void(*OnPlayerConnect) (int32_t playerId); - void(*OnPlayerDisconnect) (int32_t playerId, vcmpDisconnectReason reason); - - uint8_t(*OnPlayerRequestClass) (int32_t playerId, int32_t offset); - uint8_t(*OnPlayerRequestSpawn) (int32_t playerId); - void(*OnPlayerSpawn) (int32_t playerId); - void(*OnPlayerDeath) (int32_t playerId, int32_t killerId, int32_t reason, vcmpBodyPart bodyPart); - void(*OnPlayerUpdate) (int32_t playerId, vcmpPlayerUpdate updateType); - - uint8_t(*OnPlayerRequestEnterVehicle) (int32_t playerId, int32_t vehicleId, int32_t slotIndex); - void(*OnPlayerEnterVehicle) (int32_t playerId, int32_t vehicleId, int32_t slotIndex); - void(*OnPlayerExitVehicle) (int32_t playerId, int32_t vehicleId); - - void(*OnPlayerNameChange) (int32_t playerId, const char* oldName, const char* newName); - void(*OnPlayerStateChange) (int32_t playerId, vcmpPlayerState oldState, vcmpPlayerState newState); - void(*OnPlayerActionChange) (int32_t playerId, int32_t oldAction, int32_t newAction); - void(*OnPlayerOnFireChange) (int32_t playerId, uint8_t isOnFire); - void(*OnPlayerCrouchChange) (int32_t playerId, uint8_t isCrouching); - void(*OnPlayerGameKeysChange) (int32_t playerId, uint32_t oldKeys, uint32_t newKeys); - void(*OnPlayerBeginTyping) (int32_t playerId); - void(*OnPlayerEndTyping) (int32_t playerId); - void(*OnPlayerAwayChange) (int32_t playerId, uint8_t isAway); - - uint8_t(*OnPlayerMessage) (int32_t playerId, const char* message); - uint8_t(*OnPlayerCommand) (int32_t playerId, const char* message); - uint8_t(*OnPlayerPrivateMessage) (int32_t playerId, int32_t targetPlayerId, const char* message); - - void(*OnPlayerKeyBindDown) (int32_t playerId, int32_t bindId); - void(*OnPlayerKeyBindUp) (int32_t playerId, int32_t bindId); - void(*OnPlayerSpectate) (int32_t playerId, int32_t targetPlayerId); - void(*OnPlayerCrashReport) (int32_t playerId, const char* report); - - void(*OnVehicleUpdate) (int32_t vehicleId, vcmpVehicleUpdate updateType); - void(*OnVehicleExplode) (int32_t vehicleId); - void(*OnVehicleRespawn) (int32_t vehicleId); - - void(*OnObjectShot) (int32_t objectId, int32_t playerId, int32_t weaponId); - void(*OnObjectTouched) (int32_t objectId, int32_t playerId); - - uint8_t(*OnPickupPickAttempt) (int32_t pickupId, int32_t playerId); - void(*OnPickupPicked) (int32_t pickupId, int32_t playerId); - void(*OnPickupRespawn) (int32_t pickupId); - - void(*OnCheckpointEntered) (int32_t checkPointId, int32_t playerId); - void(*OnCheckpointExited) (int32_t checkPointId, int32_t playerId); - - void(*OnEntityPoolChange) (vcmpEntityPool entityType, int32_t entityId, uint8_t isDeleted); - void(*OnServerPerformanceReport) (size_t entryCount, const char** descriptions, uint64_t* times); - - // TODO: MOVE LATER - void(*OnPlayerModuleList) (int32_t playerId, const char* list); - -} PluginCallbacks; diff --git a/VCMP-LUA/modules/crypto/Makefile b/VCMP-LUA/modules/crypto/Makefile deleted file mode 100644 index 783617e..0000000 --- a/VCMP-LUA/modules/crypto/Makefile +++ /dev/null @@ -1,134 +0,0 @@ -# GNU Make project makefile autogenerated by Premake - -ifndef config - config=release32 -endif - -ifndef verbose - SILENT = @ -endif - -.PHONY: clean prebuild prelink - -ifeq ($(config),release32) - RESCOMP = windres - TARGETDIR = ../../../bin/Release32-windows-x86/module-crypto - TARGET = $(TARGETDIR)/module-crypto_x86.lib - OBJDIR = ../../../bin/interm/Release32-windows-x86/module-crypto - DEFINES += -D_x32 - INCLUDES += -Iinclude - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += - LDDEPS += - ALL_LDFLAGS += $(LDFLAGS) -L/usr/lib32 -m32 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -ifeq ($(config),release) - RESCOMP = windres - TARGETDIR = ../../../bin/Release-windows-x86_64/module-crypto - TARGET = $(TARGETDIR)/module-crypto_x64.lib - OBJDIR = ../../../bin/interm/Release-windows-x86_64/module-crypto - DEFINES += - INCLUDES += -Iinclude - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += - LDDEPS += - ALL_LDFLAGS += $(LDFLAGS) -L/usr/lib64 -m64 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -OBJECTS := \ - $(OBJDIR)/src.o \ - -RESOURCES := \ - -CUSTOMFILES := \ - -SHELLTYPE := posix -ifeq (.exe,$(findstring .exe,$(ComSpec))) - SHELLTYPE := msdos -endif - -$(TARGET): $(GCH) ${CUSTOMFILES} $(OBJECTS) $(LDDEPS) $(RESOURCES) | $(TARGETDIR) - @echo Linking module-crypto - $(SILENT) $(LINKCMD) - $(POSTBUILDCMDS) - -$(CUSTOMFILES): | $(OBJDIR) - -$(TARGETDIR): - @echo Creating $(TARGETDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(TARGETDIR) -else - $(SILENT) mkdir $(subst /,\\,$(TARGETDIR)) -endif - -$(OBJDIR): - @echo Creating $(OBJDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(OBJDIR) -else - $(SILENT) mkdir $(subst /,\\,$(OBJDIR)) -endif - -clean: - @echo Cleaning module-crypto -ifeq (posix,$(SHELLTYPE)) - $(SILENT) rm -f $(TARGET) - $(SILENT) rm -rf $(OBJDIR) -else - $(SILENT) if exist $(subst /,\\,$(TARGET)) del $(subst /,\\,$(TARGET)) - $(SILENT) if exist $(subst /,\\,$(OBJDIR)) rmdir /s /q $(subst /,\\,$(OBJDIR)) -endif - -prebuild: - $(PREBUILDCMDS) - -prelink: - $(PRELINKCMDS) - -ifneq (,$(PCH)) -$(OBJECTS): $(GCH) $(PCH) | $(OBJDIR) -$(GCH): $(PCH) | $(OBJDIR) - @echo $(notdir $<) - $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" -else -$(OBJECTS): | $(OBJDIR) -endif - -$(OBJDIR)/src.o: src/src.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" - --include $(OBJECTS:%.o=%.d) -ifneq (,$(PCH)) - -include $(OBJDIR)/$(notdir $(PCH)).d -endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/blake.hpp b/VCMP-LUA/modules/crypto/include/algorithm/blake.hpp deleted file mode 100644 index 74c7ce3..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/blake.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_BLAKE_HPP -#define DIGESTPP_ALGORITHM_BLAKE_HPP - -#include "../hasher.hpp" -#include "detail/blake_provider.hpp" -#include "mixin/blake_mixin.hpp" - -namespace digestpp -{ - -/** - * @brief BLAKE hash function (SHA-3 finalist) - * - * @hash - * - * @outputsize 224 / 256 / 384 / 512 bits - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not supported - * - * @mixinparams salt - * - * @mixin{mixin::blake_mixin} - * - * @par Example:\n - * @code // Output a 256-bit BLAKE digest of a string - * digestpp::blake hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 7576698ee9cad30173080678e5965916adbb11cb5245d386bf1ffda1cb26c9d7 - * @endcode - * - * @sa hasher, mixin::blake_mixin - */ -typedef hasher blake; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_BLAKE_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/blake2.hpp b/VCMP-LUA/modules/crypto/include/algorithm/blake2.hpp deleted file mode 100644 index 2639800..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/blake2.hpp +++ /dev/null @@ -1,196 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_BLAKE2_HPP -#define DIGESTPP_ALGORITHM_BLAKE2_HPP - -#include "../hasher.hpp" -#include "detail/blake2_provider.hpp" -#include "mixin/blake2_mixin.hpp" - -/// digestpp namespace -namespace digestpp -{ - -/** - * @brief BLAKE2b hash function - * - * @hash - * - * @outputsize 8 - 512 bits - * - * @defaultsize 512 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes), - * or is not within the supported range - * - * @mixinparams salt, personalization, key - * - * @mixin{mixin::blake2_mixin} - * - * @par Example:\n - * @code // Output a 256-bit BLAKE2b digest of a string - * digestpp::blake2b hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 01718cec35cd3d796dd00020e0bfecb473ad23457d063b75eff29c0ffa2e58a9 - * @endcode - * - * @sa hasher, mixin::blake2_mixin - */ -typedef hasher, mixin::blake2_mixin> blake2b; - -/** - * @brief BLAKE2s hash function - * - * @hash - * - * @outputsize 8 - 256 bits - * - * @defaultsize 256 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes), - * or is not within the supported range - * - * @mixinparams salt, personalization, key - * - * @mixin{mixin::blake2_mixin} - * - * @par Example:\n - * @code // Output a 256-bit BLAKE2s digest of a string - * digestpp::blake2s hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 606beeec743ccbeff6cbcdf5d5302aa855c256c29b88c8ed331ea1a6bf3c8812 - * @endcode - * - * @sa hasher, mixin::blake2_mixin - */ -typedef hasher, mixin::blake2_mixin> blake2s; - -/** - * @brief BLAKE2xb hash function - * - * Use this variant when the required hash size is known in advance. Otherwise, use \ref blake2xb_xof - * - * @hash - * - * @outputsize arbitrary - * - * @defaultsize 512 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes) - * - * @mixinparams salt, personalization, key - * - * @mixin{mixin::blake2_mixin} - * - * @par Example:\n - * @code // Output a 256-bit BLAKE2xb digest of a string - * digestpp::blake2xb hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code ca7a0c9c54b4b93c0bee0aa3a4d63e4f7fb87e3e0a9050522377fde76f0b6c01 - * @endcode - * - * @sa hasher, mixin::blake2_mixin - */ -typedef hasher, mixin::blake2_mixin> blake2xb; - -/** - * @brief BLAKE2xs hash function - * - * Use this variant when the required hash size is known in advance. Otherwise, use \ref blake2xs_xof - * - * @hash - * - * @outputsize arbitrary - * - * @defaultsize 256 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes) - * - * @mixinparams salt, personalization, key - * - * @mixin{mixin::blake2_mixin} - * - * @par Example:\n - * @code // Output a 512-bit BLAKE2xs digest of a string - * digestpp::blake2xs hasher(512); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code e709f8377d21507c166e5dd2279a1f58b290792d65dafcc5647b6e439a974227503c341341572725709b874e95f13a438677aa6f9648467fd341e0f3e5421840 - * @endcode - * - * @sa hasher, mixin::blake2_mixin - */ -typedef hasher, mixin::blake2_mixin> blake2xs; - -/** - * @brief BLAKE2xb in XOF mode - * - * Use this variant when the required hash size is not known in advance. Otherwise, use \ref blake2xb - * - * @xof - * - * @mixinparams salt, personalization, key - * - * @mixin{mixin::blake2_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::blake2xb_xof hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 364e84ca4c103df292306c93ebba6f6633d5e9cc8a95e040498e9a012d5ca534 - * @endcode - * - * @sa hasher, mixin::blake2_mixin - */ -typedef hasher, mixin::blake2_mixin> blake2xb_xof; - -/** - * @brief BLAKE2xs in XOF mode - * - * Use this variant when the required hash size is not known in advance. Otherwise, use \ref blake2xs - * - * @xof - * - * @mixinparams salt, personalization, key - * - * @mixin{mixin::blake2_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::blake2xs_xof hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 0650cde4df888a06eada0f0fecb3c17594304b4a03fdd678182f27db1238b1747e33c34ae539fe2179a7594442b5cc9a7a0f398bb15ac3095a397de6a60061d6 - * @endcode - * - * @sa hasher, mixin::blake2_mixin - */ -typedef hasher, mixin::blake2_mixin> blake2xs_xof; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_BLAKE2_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/blake2_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/blake2_provider.hpp deleted file mode 100644 index e817110..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/blake2_provider.hpp +++ /dev/null @@ -1,341 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_BLAKE2_HPP -#define DIGESTPP_PROVIDERS_BLAKE2_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/blake2_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace blake2_functions -{ - static inline void G(int r, int i, uint64_t& a, uint64_t& b, uint64_t& c, uint64_t& d, uint64_t* M) - { - a = a + b + M[blake2_constants::S[r][2 * i]]; - d = rotate_right(d ^ a, 32); - c = c + d; - b = rotate_right(b ^ c, 24); - a = a + b + M[blake2_constants::S[r][2 * i + 1]]; - d = rotate_right(d ^ a, 16); - c = c + d; - b = rotate_right(b ^ c, 63); - } - - static inline void G(int r, int i, uint32_t& a, uint32_t& b, uint32_t& c, uint32_t& d, uint32_t* M) - { - a = a + b + M[blake2_constants::S[r][2 * i]]; - d = rotate_right(d ^ a, 16); - c = c + d; - b = rotate_right(b ^ c, 12); - a = a + b + M[blake2_constants::S[r][2 * i + 1]]; - d = rotate_right(d ^ a, 8); - c = c + d; - b = rotate_right(b ^ c, 7); - } - - template - static inline void round(int r, T* M, T* v) - { - G(r, 0, v[0], v[4], v[8], v[12], M); - G(r, 1, v[1], v[5], v[9], v[13], M); - G(r, 2, v[2], v[6], v[10], v[14], M); - G(r, 3, v[3], v[7], v[11], v[15], M); - G(r, 4, v[0], v[5], v[10], v[15], M); - G(r, 5, v[1], v[6], v[11], v[12], M); - G(r, 6, v[2], v[7], v[8], v[13], M); - G(r, 7, v[3], v[4], v[9], v[14], M); - } - - template - inline T IV(int t); - - template<> - inline uint32_t IV(int t) - { - return blake2s_constants::IV[t]; - } - - template<> - inline uint64_t IV(int t) - { - return blake2b_constants::IV[t]; - } - - inline void initH(std::array& H) - { - memcpy(&H[0], blake2s_constants::IV, 32); - H[0] ^= 0x01010000ULL; - } - - inline void initH(std::array& H) - { - memcpy(&H[0], blake2b_constants::IV, 64); - H[0] ^= 0x0000000001010000ULL; - } - - inline void initX(std::array& H, size_t hs, size_t processed, size_t xoffset, uint32_t rhs) - { - memcpy(&H[0], blake2s_constants::IV, 32); - H[0] ^= std::min(hs - processed, static_cast(32)); - H[1] ^= 0x00000020; - H[2] ^= xoffset; - H[3] ^= 0x20000000; - H[3] ^= static_cast(rhs); - } - - inline void initX(std::array& H, size_t hs, size_t processed, size_t xoffset, uint64_t rhs) - { - memcpy(&H[0], blake2b_constants::IV, 64); - H[0] ^= std::min(hs - processed, static_cast(64)); - H[0] ^= 0x0000004000000000ULL; - H[1] ^= xoffset; - H[1] ^= rhs << 32; - H[2] ^= 0x0000000000004000ULL; - } - -} - -template -class blake2_provider -{ -public: - static const bool is_xof = type == blake2_type::xof; - - blake2_provider(size_t hashsize = N) - : hs(hashsize), squeezing(false) - { - static_assert(sizeof(T) == 8 || sizeof(T) == 4, "Invalid T size"); - - if (type == blake2_type::hash) - detail::validate_hash_size(hashsize, N); - else if (type == blake2_type::x_hash) - detail::validate_hash_size(hashsize, N * sizeof(T) * 4 - 16); - - zero_memory(s); - zero_memory(p); - } - - ~blake2_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - xoffset = 0; - squeezing = false; - - blake2_functions::initH(H); - - if (type == blake2_type::hash) - H[0] ^= hash_size()/8; - else - { - H[0] ^= N / 8; - T rhs = type == blake2_type::x_hash ? static_cast(hs/8) : (static_cast(-1) >> (sizeof(T) * 4)); - if (N == 512) - H[1] ^= (rhs << (N / 16)); - else - H[3] ^= rhs; - } - H[0] ^= (k.size() << 8); - H[4] ^= s[0]; - H[5] ^= s[1]; - H[6] ^= p[0]; - H[7] ^= p[1]; - absorb_key(); - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, N / 4, N / 4 + 1, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len, false); }); - } - - inline void set_key(const std::string& key) - { - if (key.length() > N / 8) - throw std::runtime_error("invalid key length"); - - k = key; - } - - inline void set_salt(const unsigned char* salt, size_t salt_len) - { - if (salt_len && salt_len != N / 32) - throw std::runtime_error("invalid salt length"); - - memcpy(&s[0], salt, salt_len); - } - - inline void set_personalization(const unsigned char* personalization, size_t personalization_len) - { - if (personalization_len && personalization_len != N / 32) - throw std::runtime_error("invalid personalization length"); - - memcpy(&p[0], personalization, personalization_len); - } - - inline void squeeze(unsigned char* hash, size_t hs) - { - size_t processed = 0; - if (!squeezing) - { - if (type == blake2_type::xof) - total += pos * 8; - squeezing = true; - xoffset = 0; - if (N / 4 != pos) - memset(&m[pos], 0, N / 4 - pos); - transform(m.data(), 1, true); - memcpy(&m[0], H.data(), N / 8); - } - else if (pos < N / 8) - { - size_t to_copy = std::min(hs, N / 8 - pos); - memcpy(hash, reinterpret_cast(H.data()) + pos, to_copy); - processed += to_copy; - pos += to_copy; - } - while (processed < hs) - { - blake2_functions::initX(H, hs, processed, xoffset++, type == blake2_type::xof ? static_cast(-1) : static_cast(hs)); - H[4] ^= s[0]; - H[5] ^= s[1]; - H[6] ^= p[0]; - H[7] ^= p[1]; - total = N; - memset(&m[N / 8], 0, m.size() - N / 8); - transform(m.data(), 1, true); - pos = std::min(hs - processed, N / 8); - memcpy(hash + processed, H.data(), pos); - processed += pos; - } - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - if (type == blake2_type::hash) - { - if (N / 4 != pos) - memset(&m[pos], 0, N / 4 - pos); - transform(m.data(), 1, true); - memcpy(hash, H.data(), hash_size() / 8); - } - else - squeeze(hash, hs / 8); - } - - inline void clear() - { - zero_memory(H); - zero_memory(m); - zero_memory(s); - zero_memory(p); - zero_memory(k); - k.clear(); - } - - inline size_t hash_size() const { return hs; } - -private: - inline void absorb_key() - { - if (k.empty()) - return; - - unsigned char key[N / 4]; - memcpy(key, k.data(), k.length()); - if (k.length() != N / 4) - memset(key + k.length(), 0, N / 4 - k.length()); - update(key, sizeof(key)); - } - - inline void transform(const unsigned char* data, size_t num_blks, bool padding) - { - for (size_t blk = 0; blk < num_blks; blk++) - { - T M[16]; - for (int i = 0; i < 16; i++) - M[i] = reinterpret_cast(data)[blk * 16 + i]; - uint64_t totalbytes = total / 8 + (padding ? 0 : (blk + 1) * N) / 4; - T t0 = static_cast(totalbytes); - T t1 = N == 512 ? 0 : static_cast(totalbytes >> 32); - T f0 = 0; - T f1 = 0; - if (padding) - { - f0 = static_cast(-1); - f1 = 0; - } - - T v[16]; - memcpy(v, H.data(), sizeof(T) * 8); - v[8 + 0] = blake2_functions::IV(0); - v[8 + 1] = blake2_functions::IV(1); - v[8 + 2] = blake2_functions::IV(2); - v[8 + 3] = blake2_functions::IV(3); - v[12] = t0 ^ blake2_functions::IV(4); - v[13] = t1 ^ blake2_functions::IV(5); - v[14] = f0 ^ blake2_functions::IV(6); - v[15] = f1 ^ blake2_functions::IV(7); - - blake2_functions::round(0, M, v); - blake2_functions::round(1, M, v); - blake2_functions::round(2, M, v); - blake2_functions::round(3, M, v); - blake2_functions::round(4, M, v); - blake2_functions::round(5, M, v); - blake2_functions::round(6, M, v); - blake2_functions::round(7, M, v); - blake2_functions::round(8, M, v); - blake2_functions::round(9, M, v); - if (N == 512) - { - blake2_functions::round(10, M, v); - blake2_functions::round(11, M, v); - } - - H[0] = H[0] ^ v[0] ^ v[0 + 8]; - H[0 + 4] = H[0 + 4] ^ v[0 + 4] ^ v[0 + 8 + 4]; - H[1] = H[1] ^ v[1] ^ v[1 + 8]; - H[1 + 4] = H[1 + 4] ^ v[1 + 4] ^ v[1 + 8 + 4]; - H[2] = H[2] ^ v[2] ^ v[2 + 8]; - H[2 + 4] = H[2 + 4] ^ v[2 + 4] ^ v[2 + 8 + 4]; - H[3] = H[3] ^ v[3] ^ v[3 + 8]; - H[3 + 4] = H[3 + 4] ^ v[3 + 4] ^ v[3 + 8 + 4]; - } - - } - - constexpr static size_t N = sizeof(T) == 8 ? 512 : 256; - std::array H; - std::array s; - std::array p; - std::string k; - std::array m; - size_t pos; - uint64_t total; - size_t hs; - size_t xoffset; - bool squeezing; -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/blake_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/blake_provider.hpp deleted file mode 100644 index e2839a2..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/blake_provider.hpp +++ /dev/null @@ -1,301 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_BLAKE_HPP -#define DIGESTPP_PROVIDERS_BLAKE_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/blake_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace blake_functions -{ - static inline void G(int r, int i, uint32_t& a, uint32_t& b, uint32_t& c, uint32_t& d, uint32_t* M) - { - a = a + b + (M[blake_constants::S[r % 10][2 * i]] - ^ blake_constants::c[blake_constants::S[r % 10][2 * i + 1]]); - d = rotate_right(d ^ a, 16); - c = c + d; - b = rotate_right(b ^ c, 12); - a = a + b + (M[blake_constants::S[r % 10][2 * i + 1]] - ^ blake_constants::c[blake_constants::S[r % 10][2 * i]]); - d = rotate_right(d ^ a, 8); - c = c + d; - b = rotate_right(b ^ c, 7); - } - - static inline void G(int r, int i, uint64_t& a, uint64_t& b, uint64_t& c, uint64_t& d, uint64_t* M) - { - a = a + b + (M[blake_constants::S[r % 10][2 * i]] - ^ blake_constants::c512[blake_constants::S[r % 10][2 * i + 1]]); - d = rotate_right(d ^ a, 32); - c = c + d; - b = rotate_right(b ^ c, 25); - a = a + b + (M[blake_constants::S[r % 10][2 * i + 1]] - ^ blake_constants::c512[blake_constants::S[r % 10][2 * i]]); - d = rotate_right(d ^ a, 16); - c = c + d; - b = rotate_right(b ^ c, 11); - } - - template - static inline void round(int r, T* M, T* v) - { - G(r, 0, v[0], v[4], v[8], v[12], M); - G(r, 1, v[1], v[5], v[9], v[13], M); - G(r, 2, v[2], v[6], v[10], v[14], M); - G(r, 3, v[3], v[7], v[11], v[15], M); - G(r, 4, v[0], v[5], v[10], v[15], M); - G(r, 5, v[1], v[6], v[11], v[12], M); - G(r, 6, v[2], v[7], v[8], v[13], M); - G(r, 7, v[3], v[4], v[9], v[14], M); - } - - template - inline T C(int t); - - template<> - inline uint32_t C(int t) - { - return blake_constants::c[t]; - } - - template<> - inline uint64_t C(int t) - { - return blake_constants::c512[t]; - } - - template - inline void transform(const unsigned char* data, size_t num_blks, bool padding, std::array& H, uint64_t total, bool final) - { - for (size_t blk = 0; blk < num_blks; blk++) - { - T M[16]; - for (int i = 0; i < 16; i++) - M[i] = byteswap(reinterpret_cast(data)[blk * 16 + i]); - - uint64_t totalbytes = total + (!final ? (blk + 1) * sizeof(M) * 8 : 0); - T t0 = static_cast(totalbytes); - T t1 = sizeof(T) == 8 ? 0 : static_cast(totalbytes >> 32); - if (padding) - t0 = t1 = 0; - - T v[16]; - memcpy(v, H.data(), sizeof(T) * 8); - v[8 + 0] = H[8] ^ C(0); - v[8 + 1] = H[9] ^ C(1); - v[8 + 2] = H[10] ^ C(2); - v[8 + 3] = H[11] ^ C(3); - v[12] = t0 ^ C(4); - v[13] = t0 ^ C(5); - v[14] = t1 ^ C(6); - v[15] = t1 ^ C(7); - - // The loop is fully unrolled for performance reasons - round(0, M, v); - round(1, M, v); - round(2, M, v); - round(3, M, v); - round(4, M, v); - round(5, M, v); - round(6, M, v); - round(7, M, v); - round(8, M, v); - round(9, M, v); - round(10, M, v); - round(11, M, v); - round(12, M, v); - round(13, M, v); - if (sizeof(T) == 8) - { - round(14, M, v); - round(15, M, v); - } - - H[0] = H[0] ^ H[8] ^ v[0] ^ v[0 + 8]; - H[0 + 4] = H[0 + 4] ^ H[8] ^ v[0 + 4] ^ v[0 + 8 + 4]; - H[1] = H[1] ^ H[9] ^ v[1] ^ v[1 + 8]; - H[1 + 4] = H[1 + 4] ^ H[9] ^ v[1 + 4] ^ v[1 + 8 + 4]; - H[2] = H[2] ^ H[10] ^ v[2] ^ v[2 + 8]; - H[2 + 4] = H[2 + 4] ^ H[10] ^ v[2 + 4] ^ v[2 + 8 + 4]; - H[3] = H[3] ^ H[11] ^ v[3] ^ v[3 + 8]; - H[3 + 4] = H[3 + 4] ^ H[11] ^ v[3 + 4] ^ v[3 + 8 + 4]; - } - } - - template - inline void set_salt(std::array& H, const unsigned char* salt, size_t saltlen) - { - if (saltlen) - for (int i = 0; i < 4; i++) - H[8 + i] = byteswap(reinterpret_cast(salt)[i]); - else - H[8] = H[9] = H[10] = H[11] = 0; - } -} - -class blake_provider -{ -public: - static const bool is_xof = false; - - blake_provider(size_t hashsize) - : hs(hashsize) - { - validate_hash_size(hashsize, {224, 256, 384, 512}); - zero_memory(u.H512); - } - - ~blake_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - - switch(hs) - { - case 512: - u.H512[0] = 0x6A09E667F3BCC908ull; - u.H512[1] = 0xBB67AE8584CAA73Bull; - u.H512[2] = 0x3C6EF372FE94F82Bull; - u.H512[3] = 0xA54FF53A5F1D36F1ull; - u.H512[4] = 0x510E527FADE682D1ull; - u.H512[5] = 0x9B05688C2B3E6C1Full; - u.H512[6] = 0x1F83D9ABFB41BD6Bull; - u.H512[7] = 0x5BE0CD19137E2179ull; - break; - case 384: - u.H512[0] = 0xcbbb9d5dc1059ed8ull; - u.H512[1] = 0x629a292a367cd507ull; - u.H512[2] = 0x9159015a3070dd17ull; - u.H512[3] = 0x152fecd8f70e5939ull; - u.H512[4] = 0x67332667ffc00b31ull; - u.H512[5] = 0x8eb44a8768581511ull; - u.H512[6] = 0xdb0c2e0d64f98fa7ull; - u.H512[7] = 0x47b5481dbefa4fa4ull; - break; - case 256: - u.H256[0] = 0x6a09e667; - u.H256[1] = 0xbb67ae85; - u.H256[2] = 0x3c6ef372; - u.H256[3] = 0xa54ff53a; - u.H256[4] = 0x510e527f; - u.H256[5] = 0x9b05688c; - u.H256[6] = 0x1f83d9ab; - u.H256[7] = 0x5be0cd19; - break; - case 224: - u.H256[0] = 0xC1059ED8; - u.H256[1] = 0x367CD507; - u.H256[2] = 0x3070DD17; - u.H256[3] = 0xF70E5939; - u.H256[4] = 0xFFC00B31; - u.H256[5] = 0x68581511; - u.H256[6] = 0x64F98FA7; - u.H256[7] = 0xBEFA4FA4; - break; - } - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, block_bytes(), block_bytes(), m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len, false, false); }); - } - - inline void set_salt(const unsigned char* salt, size_t salt_len) - { - if (salt_len && ((hs > 256 && salt_len != 32) || (hs <= 256 && salt_len != 16))) - throw std::runtime_error("invalid salt length"); - - if (hs > 256) - blake_functions::set_salt(u.H512, salt, salt_len); - else - blake_functions::set_salt(u.H256, salt, salt_len); - } - - inline void final(unsigned char* hash) - { - size_t messageend = hs > 256 ? 111 : 55; - bool truncated = hs != 512 && hs != 256; - bool padding = !pos; - total += 8 * pos; - m[pos] = pos == messageend && !truncated ? 0x81 : 0x80; - if (pos++ > messageend) - { - if (block_bytes() != pos) - memset(&m[pos], 0, block_bytes() - pos); - transform(m.data(), 1, false, true); - pos = 0; - padding = true; - } - if (pos <= messageend) - { - memset(&m[pos], 0, messageend - pos); - m[messageend] = truncated ? 0x00 : 0x01; - } - uint64_t mlen = byteswap(total); - if (block_bytes() == 128) - memset(&m[128 - 16], 0, sizeof(uint64_t)); - memcpy(&m[block_bytes() - 8], &mlen, sizeof(uint64_t)); - transform(m.data(), 1, padding, true); - if (hs > 256) - { - for (int i = 0; i < 8; i++) - u.H512[i] = byteswap(u.H512[i]); - memcpy(hash, u.H512.data(), hash_size()/8); - } - else - { - for (int i = 0; i < 8; i++) - u.H256[i] = byteswap(u.H256[i]); - memcpy(hash, u.H256.data(), hash_size()/8); - } - } - - inline void clear() - { - zero_memory(u.H512); - zero_memory(m); - } - - inline size_t hash_size() const { return hs; } - -private: - inline size_t block_bytes() const { return hs > 256 ? 128 : 64; } - - inline void transform(const unsigned char* mp, size_t num_blks, bool padding, bool final) - { - if (hs > 256) - blake_functions::transform(mp, num_blks, padding, u.H512, total, final); - else - blake_functions::transform(mp, num_blks, padding, u.H256, total, final); - } - - union { std::array H512; std::array H256; } u; - std::array m; - size_t hs; - size_t pos; - uint64_t total; - -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/blake2_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/blake2_constants.hpp deleted file mode 100644 index 955ff9b..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/blake2_constants.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_BLAKE2_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_BLAKE2_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct blake2b_constants -{ - const static uint64_t IV[8]; -}; - -template -const uint64_t blake2b_constants::IV[8] = { - 0x6A09E667F3BCC908ull, 0xBB67AE8584CAA73Bull, 0x3C6EF372FE94F82Bull, 0xA54FF53A5F1D36F1ull, - 0x510E527FADE682D1ull, 0x9B05688C2B3E6C1Full, 0x1F83D9ABFB41BD6Bull, 0x5BE0CD19137E2179ull -}; - -template -struct blake2s_constants -{ - const static uint32_t IV[8]; -}; - -template -const uint32_t blake2s_constants::IV[8] = { - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 -}; - -template -struct blake2_constants -{ - static const uint32_t S[12][16]; - -}; - -template -const uint32_t blake2_constants::S[12][16] = { - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } -}; - -enum class blake2_type -{ - hash, - x_hash, - xof -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/blake_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/blake_constants.hpp deleted file mode 100644 index 090c261..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/blake_constants.hpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_BLAKE_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_BLAKE_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct blake_constants -{ - static const uint32_t c[16]; - static const uint64_t c512[16]; - static const uint32_t S[10][16]; - -}; - -template -const uint32_t blake_constants::c[16] = { - 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89, - 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917 -}; - -template -const uint64_t blake_constants::c512[16] = { - 0x243F6A8885A308D3ull, 0x13198A2E03707344ull, 0xA4093822299F31D0ull, 0x082EFA98EC4E6C89ull, - 0x452821E638D01377ull, 0xBE5466CF34E90C6Cull, 0xC0AC29B7C97C50DDull, 0x3F84D5B5B5470917ull, - 0x9216D5D98979FB1Bull, 0xD1310BA698DFB5ACull, 0x2FFD72DBD01ADFB7ull, 0xB8E1AFED6A267E96ull, - 0xBA7C9045F12C7F99ull, 0x24A19947B3916CF7ull, 0x0801F2E2858EFC16ull, 0x636920D871574E69ull -}; - -template -const uint32_t blake_constants::S[10][16] = { - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 } -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/groestl_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/groestl_constants.hpp deleted file mode 100644 index 8e7eff7..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/groestl_constants.hpp +++ /dev/null @@ -1,557 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_GROESTL_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_GROESTL_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct groestl_constants -{ - static const uint64_t T[8][256]; - -}; - -template -const uint64_t groestl_constants::T[8][256] = { - { - 0xc6a597f4a5f432c6ull, 0xf884eb9784976ff8ull, 0xee99c7b099b05eeeull, 0xf68df78c8d8c7af6ull, - 0xff0de5170d17e8ffull, 0xd6bdb7dcbddc0ad6ull, 0xdeb1a7c8b1c816deull, 0x915439fc54fc6d91ull, - 0x6050c0f050f09060ull, 0x0203040503050702ull, 0xcea987e0a9e02eceull, 0x567dac877d87d156ull, - 0xe719d52b192bcce7ull, 0xb56271a662a613b5ull, 0x4de69a31e6317c4dull, 0xec9ac3b59ab559ecull, - 0x8f4505cf45cf408full, 0x1f9d3ebc9dbca31full, 0x894009c040c04989ull, 0xfa87ef92879268faull, - 0xef15c53f153fd0efull, 0xb2eb7f26eb2694b2ull, 0x8ec90740c940ce8eull, 0xfb0bed1d0b1de6fbull, - 0x41ec822fec2f6e41ull, 0xb3677da967a91ab3ull, 0x5ffdbe1cfd1c435full, 0x45ea8a25ea256045ull, - 0x23bf46dabfdaf923ull, 0x53f7a602f7025153ull, 0xe496d3a196a145e4ull, 0x9b5b2ded5bed769bull, - 0x75c2ea5dc25d2875ull, 0xe11cd9241c24c5e1ull, 0x3dae7ae9aee9d43dull, 0x4c6a98be6abef24cull, - 0x6c5ad8ee5aee826cull, 0x7e41fcc341c3bd7eull, 0xf502f1060206f3f5ull, 0x834f1dd14fd15283ull, - 0x685cd0e45ce48c68ull, 0x51f4a207f4075651ull, 0xd134b95c345c8dd1ull, 0xf908e9180818e1f9ull, - 0xe293dfae93ae4ce2ull, 0xab734d9573953eabull, 0x6253c4f553f59762ull, 0x2a3f54413f416b2aull, - 0x080c10140c141c08ull, 0x955231f652f66395ull, 0x46658caf65afe946ull, 0x9d5e21e25ee27f9dull, - 0x3028607828784830ull, 0x37a16ef8a1f8cf37ull, 0x0a0f14110f111b0aull, 0x2fb55ec4b5c4eb2full, - 0x0e091c1b091b150eull, 0x2436485a365a7e24ull, 0x1b9b36b69bb6ad1bull, 0xdf3da5473d4798dfull, - 0xcd26816a266aa7cdull, 0x4e699cbb69bbf54eull, 0x7fcdfe4ccd4c337full, 0xea9fcfba9fba50eaull, - 0x121b242d1b2d3f12ull, 0x1d9e3ab99eb9a41dull, 0x5874b09c749cc458ull, 0x342e68722e724634ull, - 0x362d6c772d774136ull, 0xdcb2a3cdb2cd11dcull, 0xb4ee7329ee299db4ull, 0x5bfbb616fb164d5bull, - 0xa4f65301f601a5a4ull, 0x764decd74dd7a176ull, 0xb76175a361a314b7ull, 0x7dcefa49ce49347dull, - 0x527ba48d7b8ddf52ull, 0xdd3ea1423e429fddull, 0x5e71bc937193cd5eull, 0x139726a297a2b113ull, - 0xa6f55704f504a2a6ull, 0xb96869b868b801b9ull, 0x0000000000000000ull, 0xc12c99742c74b5c1ull, - 0x406080a060a0e040ull, 0xe31fdd211f21c2e3ull, 0x79c8f243c8433a79ull, 0xb6ed772ced2c9ab6ull, - 0xd4beb3d9bed90dd4ull, 0x8d4601ca46ca478dull, 0x67d9ce70d9701767ull, 0x724be4dd4bddaf72ull, - 0x94de3379de79ed94ull, 0x98d42b67d467ff98ull, 0xb0e87b23e82393b0ull, 0x854a11de4ade5b85ull, - 0xbb6b6dbd6bbd06bbull, 0xc52a917e2a7ebbc5ull, 0x4fe59e34e5347b4full, 0xed16c13a163ad7edull, - 0x86c51754c554d286ull, 0x9ad72f62d762f89aull, 0x6655ccff55ff9966ull, 0x119422a794a7b611ull, - 0x8acf0f4acf4ac08aull, 0xe910c9301030d9e9ull, 0x0406080a060a0e04ull, 0xfe81e798819866feull, - 0xa0f05b0bf00baba0ull, 0x7844f0cc44ccb478ull, 0x25ba4ad5bad5f025ull, 0x4be3963ee33e754bull, - 0xa2f35f0ef30eaca2ull, 0x5dfeba19fe19445dull, 0x80c01b5bc05bdb80ull, 0x058a0a858a858005ull, - 0x3fad7eecadecd33full, 0x21bc42dfbcdffe21ull, 0x7048e0d848d8a870ull, 0xf104f90c040cfdf1ull, - 0x63dfc67adf7a1963ull, 0x77c1ee58c1582f77ull, 0xaf75459f759f30afull, 0x426384a563a5e742ull, - 0x2030405030507020ull, 0xe51ad12e1a2ecbe5ull, 0xfd0ee1120e12effdull, 0xbf6d65b76db708bfull, - 0x814c19d44cd45581ull, 0x1814303c143c2418ull, 0x26354c5f355f7926ull, 0xc32f9d712f71b2c3ull, - 0xbee16738e13886beull, 0x35a26afda2fdc835ull, 0x88cc0b4fcc4fc788ull, 0x2e395c4b394b652eull, - 0x93573df957f96a93ull, 0x55f2aa0df20d5855ull, 0xfc82e39d829d61fcull, 0x7a47f4c947c9b37aull, - 0xc8ac8befacef27c8ull, 0xbae76f32e73288baull, 0x322b647d2b7d4f32ull, 0xe695d7a495a442e6ull, - 0xc0a09bfba0fb3bc0ull, 0x199832b398b3aa19ull, 0x9ed12768d168f69eull, 0xa37f5d817f8122a3ull, - 0x446688aa66aaee44ull, 0x547ea8827e82d654ull, 0x3bab76e6abe6dd3bull, 0x0b83169e839e950bull, - 0x8cca0345ca45c98cull, 0xc729957b297bbcc7ull, 0x6bd3d66ed36e056bull, 0x283c50443c446c28ull, - 0xa779558b798b2ca7ull, 0xbce2633de23d81bcull, 0x161d2c271d273116ull, 0xad76419a769a37adull, - 0xdb3bad4d3b4d96dbull, 0x6456c8fa56fa9e64ull, 0x744ee8d24ed2a674ull, 0x141e28221e223614ull, - 0x92db3f76db76e492ull, 0x0c0a181e0a1e120cull, 0x486c90b46cb4fc48ull, 0xb8e46b37e4378fb8ull, - 0x9f5d25e75de7789full, 0xbd6e61b26eb20fbdull, 0x43ef862aef2a6943ull, 0xc4a693f1a6f135c4ull, - 0x39a872e3a8e3da39ull, 0x31a462f7a4f7c631ull, 0xd337bd5937598ad3ull, 0xf28bff868b8674f2ull, - 0xd532b156325683d5ull, 0x8b430dc543c54e8bull, 0x6e59dceb59eb856eull, 0xdab7afc2b7c218daull, - 0x018c028f8c8f8e01ull, 0xb16479ac64ac1db1ull, 0x9cd2236dd26df19cull, 0x49e0923be03b7249ull, - 0xd8b4abc7b4c71fd8ull, 0xacfa4315fa15b9acull, 0xf307fd090709faf3ull, 0xcf25856f256fa0cfull, - 0xcaaf8feaafea20caull, 0xf48ef3898e897df4ull, 0x47e98e20e9206747ull, 0x1018202818283810ull, - 0x6fd5de64d5640b6full, 0xf088fb83888373f0ull, 0x4a6f94b16fb1fb4aull, 0x5c72b8967296ca5cull, - 0x3824706c246c5438ull, 0x57f1ae08f1085f57ull, 0x73c7e652c7522173ull, 0x975135f351f36497ull, - 0xcb238d652365aecbull, 0xa17c59847c8425a1ull, 0xe89ccbbf9cbf57e8ull, 0x3e217c6321635d3eull, - 0x96dd377cdd7cea96ull, 0x61dcc27fdc7f1e61ull, 0x0d861a9186919c0dull, 0x0f851e9485949b0full, - 0xe090dbab90ab4be0ull, 0x7c42f8c642c6ba7cull, 0x71c4e257c4572671ull, 0xccaa83e5aae529ccull, - 0x90d83b73d873e390ull, 0x06050c0f050f0906ull, 0xf701f5030103f4f7ull, 0x1c12383612362a1cull, - 0xc2a39ffea3fe3cc2ull, 0x6a5fd4e15fe18b6aull, 0xaef94710f910beaeull, 0x69d0d26bd06b0269ull, - 0x17912ea891a8bf17ull, 0x995829e858e87199ull, 0x3a2774692769533aull, 0x27b94ed0b9d0f727ull, - 0xd938a948384891d9ull, 0xeb13cd351335deebull, 0x2bb356ceb3cee52bull, 0x2233445533557722ull, - 0xd2bbbfd6bbd604d2ull, 0xa9704990709039a9ull, 0x07890e8089808707ull, 0x33a766f2a7f2c133ull, - 0x2db65ac1b6c1ec2dull, 0x3c22786622665a3cull, 0x15922aad92adb815ull, 0xc92089602060a9c9ull, - 0x874915db49db5c87ull, 0xaaff4f1aff1ab0aaull, 0x5078a0887888d850ull, 0xa57a518e7a8e2ba5ull, - 0x038f068a8f8a8903ull, 0x59f8b213f8134a59ull, 0x0980129b809b9209ull, 0x1a1734391739231aull, - 0x65daca75da751065ull, 0xd731b553315384d7ull, 0x84c61351c651d584ull, 0xd0b8bbd3b8d303d0ull, - 0x82c31f5ec35edc82ull, 0x29b052cbb0cbe229ull, 0x5a77b4997799c35aull, 0x1e113c3311332d1eull, - 0x7bcbf646cb463d7bull, 0xa8fc4b1ffc1fb7a8ull, 0x6dd6da61d6610c6dull, 0x2c3a584e3a4e622cull - }, - { - 0xa597f4a5f432c6c6ull, 0x84eb9784976ff8f8ull, 0x99c7b099b05eeeeeull, 0x8df78c8d8c7af6f6ull, - 0x0de5170d17e8ffffull, 0xbdb7dcbddc0ad6d6ull, 0xb1a7c8b1c816dedeull, 0x5439fc54fc6d9191ull, - 0x50c0f050f0906060ull, 0x0304050305070202ull, 0xa987e0a9e02ececeull, 0x7dac877d87d15656ull, - 0x19d52b192bcce7e7ull, 0x6271a662a613b5b5ull, 0xe69a31e6317c4d4dull, 0x9ac3b59ab559ececull, - 0x4505cf45cf408f8full, 0x9d3ebc9dbca31f1full, 0x4009c040c0498989ull, 0x87ef92879268fafaull, - 0x15c53f153fd0efefull, 0xeb7f26eb2694b2b2ull, 0xc90740c940ce8e8eull, 0x0bed1d0b1de6fbfbull, - 0xec822fec2f6e4141ull, 0x677da967a91ab3b3ull, 0xfdbe1cfd1c435f5full, 0xea8a25ea25604545ull, - 0xbf46dabfdaf92323ull, 0xf7a602f702515353ull, 0x96d3a196a145e4e4ull, 0x5b2ded5bed769b9bull, - 0xc2ea5dc25d287575ull, 0x1cd9241c24c5e1e1ull, 0xae7ae9aee9d43d3dull, 0x6a98be6abef24c4cull, - 0x5ad8ee5aee826c6cull, 0x41fcc341c3bd7e7eull, 0x02f1060206f3f5f5ull, 0x4f1dd14fd1528383ull, - 0x5cd0e45ce48c6868ull, 0xf4a207f407565151ull, 0x34b95c345c8dd1d1ull, 0x08e9180818e1f9f9ull, - 0x93dfae93ae4ce2e2ull, 0x734d9573953eababull, 0x53c4f553f5976262ull, 0x3f54413f416b2a2aull, - 0x0c10140c141c0808ull, 0x5231f652f6639595ull, 0x658caf65afe94646ull, 0x5e21e25ee27f9d9dull, - 0x2860782878483030ull, 0xa16ef8a1f8cf3737ull, 0x0f14110f111b0a0aull, 0xb55ec4b5c4eb2f2full, - 0x091c1b091b150e0eull, 0x36485a365a7e2424ull, 0x9b36b69bb6ad1b1bull, 0x3da5473d4798dfdfull, - 0x26816a266aa7cdcdull, 0x699cbb69bbf54e4eull, 0xcdfe4ccd4c337f7full, 0x9fcfba9fba50eaeaull, - 0x1b242d1b2d3f1212ull, 0x9e3ab99eb9a41d1dull, 0x74b09c749cc45858ull, 0x2e68722e72463434ull, - 0x2d6c772d77413636ull, 0xb2a3cdb2cd11dcdcull, 0xee7329ee299db4b4ull, 0xfbb616fb164d5b5bull, - 0xf65301f601a5a4a4ull, 0x4decd74dd7a17676ull, 0x6175a361a314b7b7ull, 0xcefa49ce49347d7dull, - 0x7ba48d7b8ddf5252ull, 0x3ea1423e429fddddull, 0x71bc937193cd5e5eull, 0x9726a297a2b11313ull, - 0xf55704f504a2a6a6ull, 0x6869b868b801b9b9ull, 0x0000000000000000ull, 0x2c99742c74b5c1c1ull, - 0x6080a060a0e04040ull, 0x1fdd211f21c2e3e3ull, 0xc8f243c8433a7979ull, 0xed772ced2c9ab6b6ull, - 0xbeb3d9bed90dd4d4ull, 0x4601ca46ca478d8dull, 0xd9ce70d970176767ull, 0x4be4dd4bddaf7272ull, - 0xde3379de79ed9494ull, 0xd42b67d467ff9898ull, 0xe87b23e82393b0b0ull, 0x4a11de4ade5b8585ull, - 0x6b6dbd6bbd06bbbbull, 0x2a917e2a7ebbc5c5ull, 0xe59e34e5347b4f4full, 0x16c13a163ad7ededull, - 0xc51754c554d28686ull, 0xd72f62d762f89a9aull, 0x55ccff55ff996666ull, 0x9422a794a7b61111ull, - 0xcf0f4acf4ac08a8aull, 0x10c9301030d9e9e9ull, 0x06080a060a0e0404ull, 0x81e798819866fefeull, - 0xf05b0bf00baba0a0ull, 0x44f0cc44ccb47878ull, 0xba4ad5bad5f02525ull, 0xe3963ee33e754b4bull, - 0xf35f0ef30eaca2a2ull, 0xfeba19fe19445d5dull, 0xc01b5bc05bdb8080ull, 0x8a0a858a85800505ull, - 0xad7eecadecd33f3full, 0xbc42dfbcdffe2121ull, 0x48e0d848d8a87070ull, 0x04f90c040cfdf1f1ull, - 0xdfc67adf7a196363ull, 0xc1ee58c1582f7777ull, 0x75459f759f30afafull, 0x6384a563a5e74242ull, - 0x3040503050702020ull, 0x1ad12e1a2ecbe5e5ull, 0x0ee1120e12effdfdull, 0x6d65b76db708bfbfull, - 0x4c19d44cd4558181ull, 0x14303c143c241818ull, 0x354c5f355f792626ull, 0x2f9d712f71b2c3c3ull, - 0xe16738e13886bebeull, 0xa26afda2fdc83535ull, 0xcc0b4fcc4fc78888ull, 0x395c4b394b652e2eull, - 0x573df957f96a9393ull, 0xf2aa0df20d585555ull, 0x82e39d829d61fcfcull, 0x47f4c947c9b37a7aull, - 0xac8befacef27c8c8ull, 0xe76f32e73288babaull, 0x2b647d2b7d4f3232ull, 0x95d7a495a442e6e6ull, - 0xa09bfba0fb3bc0c0ull, 0x9832b398b3aa1919ull, 0xd12768d168f69e9eull, 0x7f5d817f8122a3a3ull, - 0x6688aa66aaee4444ull, 0x7ea8827e82d65454ull, 0xab76e6abe6dd3b3bull, 0x83169e839e950b0bull, - 0xca0345ca45c98c8cull, 0x29957b297bbcc7c7ull, 0xd3d66ed36e056b6bull, 0x3c50443c446c2828ull, - 0x79558b798b2ca7a7ull, 0xe2633de23d81bcbcull, 0x1d2c271d27311616ull, 0x76419a769a37adadull, - 0x3bad4d3b4d96dbdbull, 0x56c8fa56fa9e6464ull, 0x4ee8d24ed2a67474ull, 0x1e28221e22361414ull, - 0xdb3f76db76e49292ull, 0x0a181e0a1e120c0cull, 0x6c90b46cb4fc4848ull, 0xe46b37e4378fb8b8ull, - 0x5d25e75de7789f9full, 0x6e61b26eb20fbdbdull, 0xef862aef2a694343ull, 0xa693f1a6f135c4c4ull, - 0xa872e3a8e3da3939ull, 0xa462f7a4f7c63131ull, 0x37bd5937598ad3d3ull, 0x8bff868b8674f2f2ull, - 0x32b156325683d5d5ull, 0x430dc543c54e8b8bull, 0x59dceb59eb856e6eull, 0xb7afc2b7c218dadaull, - 0x8c028f8c8f8e0101ull, 0x6479ac64ac1db1b1ull, 0xd2236dd26df19c9cull, 0xe0923be03b724949ull, - 0xb4abc7b4c71fd8d8ull, 0xfa4315fa15b9acacull, 0x07fd090709faf3f3ull, 0x25856f256fa0cfcfull, - 0xaf8feaafea20cacaull, 0x8ef3898e897df4f4ull, 0xe98e20e920674747ull, 0x1820281828381010ull, - 0xd5de64d5640b6f6full, 0x88fb83888373f0f0ull, 0x6f94b16fb1fb4a4aull, 0x72b8967296ca5c5cull, - 0x24706c246c543838ull, 0xf1ae08f1085f5757ull, 0xc7e652c752217373ull, 0x5135f351f3649797ull, - 0x238d652365aecbcbull, 0x7c59847c8425a1a1ull, 0x9ccbbf9cbf57e8e8ull, 0x217c6321635d3e3eull, - 0xdd377cdd7cea9696ull, 0xdcc27fdc7f1e6161ull, 0x861a9186919c0d0dull, 0x851e9485949b0f0full, - 0x90dbab90ab4be0e0ull, 0x42f8c642c6ba7c7cull, 0xc4e257c457267171ull, 0xaa83e5aae529ccccull, - 0xd83b73d873e39090ull, 0x050c0f050f090606ull, 0x01f5030103f4f7f7ull, 0x12383612362a1c1cull, - 0xa39ffea3fe3cc2c2ull, 0x5fd4e15fe18b6a6aull, 0xf94710f910beaeaeull, 0xd0d26bd06b026969ull, - 0x912ea891a8bf1717ull, 0x5829e858e8719999ull, 0x2774692769533a3aull, 0xb94ed0b9d0f72727ull, - 0x38a948384891d9d9ull, 0x13cd351335deebebull, 0xb356ceb3cee52b2bull, 0x3344553355772222ull, - 0xbbbfd6bbd604d2d2ull, 0x704990709039a9a9ull, 0x890e808980870707ull, 0xa766f2a7f2c13333ull, - 0xb65ac1b6c1ec2d2dull, 0x22786622665a3c3cull, 0x922aad92adb81515ull, 0x2089602060a9c9c9ull, - 0x4915db49db5c8787ull, 0xff4f1aff1ab0aaaaull, 0x78a0887888d85050ull, 0x7a518e7a8e2ba5a5ull, - 0x8f068a8f8a890303ull, 0xf8b213f8134a5959ull, 0x80129b809b920909ull, 0x1734391739231a1aull, - 0xdaca75da75106565ull, 0x31b553315384d7d7ull, 0xc61351c651d58484ull, 0xb8bbd3b8d303d0d0ull, - 0xc31f5ec35edc8282ull, 0xb052cbb0cbe22929ull, 0x77b4997799c35a5aull, 0x113c3311332d1e1eull, - 0xcbf646cb463d7b7bull, 0xfc4b1ffc1fb7a8a8ull, 0xd6da61d6610c6d6dull, 0x3a584e3a4e622c2cull - }, - { - 0x97f4a5f432c6c6a5ull, 0xeb9784976ff8f884ull, 0xc7b099b05eeeee99ull, 0xf78c8d8c7af6f68dull, - 0xe5170d17e8ffff0dull, 0xb7dcbddc0ad6d6bdull, 0xa7c8b1c816dedeb1ull, 0x39fc54fc6d919154ull, - 0xc0f050f090606050ull, 0x0405030507020203ull, 0x87e0a9e02ececea9ull, 0xac877d87d156567dull, - 0xd52b192bcce7e719ull, 0x71a662a613b5b562ull, 0x9a31e6317c4d4de6ull, 0xc3b59ab559ecec9aull, - 0x05cf45cf408f8f45ull, 0x3ebc9dbca31f1f9dull, 0x09c040c049898940ull, 0xef92879268fafa87ull, - 0xc53f153fd0efef15ull, 0x7f26eb2694b2b2ebull, 0x0740c940ce8e8ec9ull, 0xed1d0b1de6fbfb0bull, - 0x822fec2f6e4141ecull, 0x7da967a91ab3b367ull, 0xbe1cfd1c435f5ffdull, 0x8a25ea25604545eaull, - 0x46dabfdaf92323bfull, 0xa602f702515353f7ull, 0xd3a196a145e4e496ull, 0x2ded5bed769b9b5bull, - 0xea5dc25d287575c2ull, 0xd9241c24c5e1e11cull, 0x7ae9aee9d43d3daeull, 0x98be6abef24c4c6aull, - 0xd8ee5aee826c6c5aull, 0xfcc341c3bd7e7e41ull, 0xf1060206f3f5f502ull, 0x1dd14fd15283834full, - 0xd0e45ce48c68685cull, 0xa207f407565151f4ull, 0xb95c345c8dd1d134ull, 0xe9180818e1f9f908ull, - 0xdfae93ae4ce2e293ull, 0x4d9573953eabab73ull, 0xc4f553f597626253ull, 0x54413f416b2a2a3full, - 0x10140c141c08080cull, 0x31f652f663959552ull, 0x8caf65afe9464665ull, 0x21e25ee27f9d9d5eull, - 0x6078287848303028ull, 0x6ef8a1f8cf3737a1ull, 0x14110f111b0a0a0full, 0x5ec4b5c4eb2f2fb5ull, - 0x1c1b091b150e0e09ull, 0x485a365a7e242436ull, 0x36b69bb6ad1b1b9bull, 0xa5473d4798dfdf3dull, - 0x816a266aa7cdcd26ull, 0x9cbb69bbf54e4e69ull, 0xfe4ccd4c337f7fcdull, 0xcfba9fba50eaea9full, - 0x242d1b2d3f12121bull, 0x3ab99eb9a41d1d9eull, 0xb09c749cc4585874ull, 0x68722e724634342eull, - 0x6c772d774136362dull, 0xa3cdb2cd11dcdcb2ull, 0x7329ee299db4b4eeull, 0xb616fb164d5b5bfbull, - 0x5301f601a5a4a4f6ull, 0xecd74dd7a176764dull, 0x75a361a314b7b761ull, 0xfa49ce49347d7dceull, - 0xa48d7b8ddf52527bull, 0xa1423e429fdddd3eull, 0xbc937193cd5e5e71ull, 0x26a297a2b1131397ull, - 0x5704f504a2a6a6f5ull, 0x69b868b801b9b968ull, 0x0000000000000000ull, 0x99742c74b5c1c12cull, - 0x80a060a0e0404060ull, 0xdd211f21c2e3e31full, 0xf243c8433a7979c8ull, 0x772ced2c9ab6b6edull, - 0xb3d9bed90dd4d4beull, 0x01ca46ca478d8d46ull, 0xce70d970176767d9ull, 0xe4dd4bddaf72724bull, - 0x3379de79ed9494deull, 0x2b67d467ff9898d4ull, 0x7b23e82393b0b0e8ull, 0x11de4ade5b85854aull, - 0x6dbd6bbd06bbbb6bull, 0x917e2a7ebbc5c52aull, 0x9e34e5347b4f4fe5ull, 0xc13a163ad7eded16ull, - 0x1754c554d28686c5ull, 0x2f62d762f89a9ad7ull, 0xccff55ff99666655ull, 0x22a794a7b6111194ull, - 0x0f4acf4ac08a8acfull, 0xc9301030d9e9e910ull, 0x080a060a0e040406ull, 0xe798819866fefe81ull, - 0x5b0bf00baba0a0f0ull, 0xf0cc44ccb4787844ull, 0x4ad5bad5f02525baull, 0x963ee33e754b4be3ull, - 0x5f0ef30eaca2a2f3ull, 0xba19fe19445d5dfeull, 0x1b5bc05bdb8080c0ull, 0x0a858a858005058aull, - 0x7eecadecd33f3fadull, 0x42dfbcdffe2121bcull, 0xe0d848d8a8707048ull, 0xf90c040cfdf1f104ull, - 0xc67adf7a196363dfull, 0xee58c1582f7777c1ull, 0x459f759f30afaf75ull, 0x84a563a5e7424263ull, - 0x4050305070202030ull, 0xd12e1a2ecbe5e51aull, 0xe1120e12effdfd0eull, 0x65b76db708bfbf6dull, - 0x19d44cd45581814cull, 0x303c143c24181814ull, 0x4c5f355f79262635ull, 0x9d712f71b2c3c32full, - 0x6738e13886bebee1ull, 0x6afda2fdc83535a2ull, 0x0b4fcc4fc78888ccull, 0x5c4b394b652e2e39ull, - 0x3df957f96a939357ull, 0xaa0df20d585555f2ull, 0xe39d829d61fcfc82ull, 0xf4c947c9b37a7a47ull, - 0x8befacef27c8c8acull, 0x6f32e73288babae7ull, 0x647d2b7d4f32322bull, 0xd7a495a442e6e695ull, - 0x9bfba0fb3bc0c0a0ull, 0x32b398b3aa191998ull, 0x2768d168f69e9ed1ull, 0x5d817f8122a3a37full, - 0x88aa66aaee444466ull, 0xa8827e82d654547eull, 0x76e6abe6dd3b3babull, 0x169e839e950b0b83ull, - 0x0345ca45c98c8ccaull, 0x957b297bbcc7c729ull, 0xd66ed36e056b6bd3ull, 0x50443c446c28283cull, - 0x558b798b2ca7a779ull, 0x633de23d81bcbce2ull, 0x2c271d273116161dull, 0x419a769a37adad76ull, - 0xad4d3b4d96dbdb3bull, 0xc8fa56fa9e646456ull, 0xe8d24ed2a674744eull, 0x28221e223614141eull, - 0x3f76db76e49292dbull, 0x181e0a1e120c0c0aull, 0x90b46cb4fc48486cull, 0x6b37e4378fb8b8e4ull, - 0x25e75de7789f9f5dull, 0x61b26eb20fbdbd6eull, 0x862aef2a694343efull, 0x93f1a6f135c4c4a6ull, - 0x72e3a8e3da3939a8ull, 0x62f7a4f7c63131a4ull, 0xbd5937598ad3d337ull, 0xff868b8674f2f28bull, - 0xb156325683d5d532ull, 0x0dc543c54e8b8b43ull, 0xdceb59eb856e6e59ull, 0xafc2b7c218dadab7ull, - 0x028f8c8f8e01018cull, 0x79ac64ac1db1b164ull, 0x236dd26df19c9cd2ull, 0x923be03b724949e0ull, - 0xabc7b4c71fd8d8b4ull, 0x4315fa15b9acacfaull, 0xfd090709faf3f307ull, 0x856f256fa0cfcf25ull, - 0x8feaafea20cacaafull, 0xf3898e897df4f48eull, 0x8e20e920674747e9ull, 0x2028182838101018ull, - 0xde64d5640b6f6fd5ull, 0xfb83888373f0f088ull, 0x94b16fb1fb4a4a6full, 0xb8967296ca5c5c72ull, - 0x706c246c54383824ull, 0xae08f1085f5757f1ull, 0xe652c752217373c7ull, 0x35f351f364979751ull, - 0x8d652365aecbcb23ull, 0x59847c8425a1a17cull, 0xcbbf9cbf57e8e89cull, 0x7c6321635d3e3e21ull, - 0x377cdd7cea9696ddull, 0xc27fdc7f1e6161dcull, 0x1a9186919c0d0d86ull, 0x1e9485949b0f0f85ull, - 0xdbab90ab4be0e090ull, 0xf8c642c6ba7c7c42ull, 0xe257c457267171c4ull, 0x83e5aae529ccccaaull, - 0x3b73d873e39090d8ull, 0x0c0f050f09060605ull, 0xf5030103f4f7f701ull, 0x383612362a1c1c12ull, - 0x9ffea3fe3cc2c2a3ull, 0xd4e15fe18b6a6a5full, 0x4710f910beaeaef9ull, 0xd26bd06b026969d0ull, - 0x2ea891a8bf171791ull, 0x29e858e871999958ull, 0x74692769533a3a27ull, 0x4ed0b9d0f72727b9ull, - 0xa948384891d9d938ull, 0xcd351335deebeb13ull, 0x56ceb3cee52b2bb3ull, 0x4455335577222233ull, - 0xbfd6bbd604d2d2bbull, 0x4990709039a9a970ull, 0x0e80898087070789ull, 0x66f2a7f2c13333a7ull, - 0x5ac1b6c1ec2d2db6ull, 0x786622665a3c3c22ull, 0x2aad92adb8151592ull, 0x89602060a9c9c920ull, - 0x15db49db5c878749ull, 0x4f1aff1ab0aaaaffull, 0xa0887888d8505078ull, 0x518e7a8e2ba5a57aull, - 0x068a8f8a8903038full, 0xb213f8134a5959f8ull, 0x129b809b92090980ull, 0x34391739231a1a17ull, - 0xca75da75106565daull, 0xb553315384d7d731ull, 0x1351c651d58484c6ull, 0xbbd3b8d303d0d0b8ull, - 0x1f5ec35edc8282c3ull, 0x52cbb0cbe22929b0ull, 0xb4997799c35a5a77ull, 0x3c3311332d1e1e11ull, - 0xf646cb463d7b7bcbull, 0x4b1ffc1fb7a8a8fcull, 0xda61d6610c6d6dd6ull, 0x584e3a4e622c2c3aull - }, - { - 0xf4a5f432c6c6a597ull, 0x9784976ff8f884ebull, 0xb099b05eeeee99c7ull, 0x8c8d8c7af6f68df7ull, - 0x170d17e8ffff0de5ull, 0xdcbddc0ad6d6bdb7ull, 0xc8b1c816dedeb1a7ull, 0xfc54fc6d91915439ull, - 0xf050f090606050c0ull, 0x0503050702020304ull, 0xe0a9e02ececea987ull, 0x877d87d156567dacull, - 0x2b192bcce7e719d5ull, 0xa662a613b5b56271ull, 0x31e6317c4d4de69aull, 0xb59ab559ecec9ac3ull, - 0xcf45cf408f8f4505ull, 0xbc9dbca31f1f9d3eull, 0xc040c04989894009ull, 0x92879268fafa87efull, - 0x3f153fd0efef15c5ull, 0x26eb2694b2b2eb7full, 0x40c940ce8e8ec907ull, 0x1d0b1de6fbfb0bedull, - 0x2fec2f6e4141ec82ull, 0xa967a91ab3b3677dull, 0x1cfd1c435f5ffdbeull, 0x25ea25604545ea8aull, - 0xdabfdaf92323bf46ull, 0x02f702515353f7a6ull, 0xa196a145e4e496d3ull, 0xed5bed769b9b5b2dull, - 0x5dc25d287575c2eaull, 0x241c24c5e1e11cd9ull, 0xe9aee9d43d3dae7aull, 0xbe6abef24c4c6a98ull, - 0xee5aee826c6c5ad8ull, 0xc341c3bd7e7e41fcull, 0x060206f3f5f502f1ull, 0xd14fd15283834f1dull, - 0xe45ce48c68685cd0ull, 0x07f407565151f4a2ull, 0x5c345c8dd1d134b9ull, 0x180818e1f9f908e9ull, - 0xae93ae4ce2e293dfull, 0x9573953eabab734dull, 0xf553f597626253c4ull, 0x413f416b2a2a3f54ull, - 0x140c141c08080c10ull, 0xf652f66395955231ull, 0xaf65afe94646658cull, 0xe25ee27f9d9d5e21ull, - 0x7828784830302860ull, 0xf8a1f8cf3737a16eull, 0x110f111b0a0a0f14ull, 0xc4b5c4eb2f2fb55eull, - 0x1b091b150e0e091cull, 0x5a365a7e24243648ull, 0xb69bb6ad1b1b9b36ull, 0x473d4798dfdf3da5ull, - 0x6a266aa7cdcd2681ull, 0xbb69bbf54e4e699cull, 0x4ccd4c337f7fcdfeull, 0xba9fba50eaea9fcfull, - 0x2d1b2d3f12121b24ull, 0xb99eb9a41d1d9e3aull, 0x9c749cc4585874b0ull, 0x722e724634342e68ull, - 0x772d774136362d6cull, 0xcdb2cd11dcdcb2a3ull, 0x29ee299db4b4ee73ull, 0x16fb164d5b5bfbb6ull, - 0x01f601a5a4a4f653ull, 0xd74dd7a176764decull, 0xa361a314b7b76175ull, 0x49ce49347d7dcefaull, - 0x8d7b8ddf52527ba4ull, 0x423e429fdddd3ea1ull, 0x937193cd5e5e71bcull, 0xa297a2b113139726ull, - 0x04f504a2a6a6f557ull, 0xb868b801b9b96869ull, 0x0000000000000000ull, 0x742c74b5c1c12c99ull, - 0xa060a0e040406080ull, 0x211f21c2e3e31fddull, 0x43c8433a7979c8f2ull, 0x2ced2c9ab6b6ed77ull, - 0xd9bed90dd4d4beb3ull, 0xca46ca478d8d4601ull, 0x70d970176767d9ceull, 0xdd4bddaf72724be4ull, - 0x79de79ed9494de33ull, 0x67d467ff9898d42bull, 0x23e82393b0b0e87bull, 0xde4ade5b85854a11ull, - 0xbd6bbd06bbbb6b6dull, 0x7e2a7ebbc5c52a91ull, 0x34e5347b4f4fe59eull, 0x3a163ad7eded16c1ull, - 0x54c554d28686c517ull, 0x62d762f89a9ad72full, 0xff55ff99666655ccull, 0xa794a7b611119422ull, - 0x4acf4ac08a8acf0full, 0x301030d9e9e910c9ull, 0x0a060a0e04040608ull, 0x98819866fefe81e7ull, - 0x0bf00baba0a0f05bull, 0xcc44ccb4787844f0ull, 0xd5bad5f02525ba4aull, 0x3ee33e754b4be396ull, - 0x0ef30eaca2a2f35full, 0x19fe19445d5dfebaull, 0x5bc05bdb8080c01bull, 0x858a858005058a0aull, - 0xecadecd33f3fad7eull, 0xdfbcdffe2121bc42ull, 0xd848d8a8707048e0ull, 0x0c040cfdf1f104f9ull, - 0x7adf7a196363dfc6ull, 0x58c1582f7777c1eeull, 0x9f759f30afaf7545ull, 0xa563a5e742426384ull, - 0x5030507020203040ull, 0x2e1a2ecbe5e51ad1ull, 0x120e12effdfd0ee1ull, 0xb76db708bfbf6d65ull, - 0xd44cd45581814c19ull, 0x3c143c2418181430ull, 0x5f355f792626354cull, 0x712f71b2c3c32f9dull, - 0x38e13886bebee167ull, 0xfda2fdc83535a26aull, 0x4fcc4fc78888cc0bull, 0x4b394b652e2e395cull, - 0xf957f96a9393573dull, 0x0df20d585555f2aaull, 0x9d829d61fcfc82e3ull, 0xc947c9b37a7a47f4ull, - 0xefacef27c8c8ac8bull, 0x32e73288babae76full, 0x7d2b7d4f32322b64ull, 0xa495a442e6e695d7ull, - 0xfba0fb3bc0c0a09bull, 0xb398b3aa19199832ull, 0x68d168f69e9ed127ull, 0x817f8122a3a37f5dull, - 0xaa66aaee44446688ull, 0x827e82d654547ea8ull, 0xe6abe6dd3b3bab76ull, 0x9e839e950b0b8316ull, - 0x45ca45c98c8cca03ull, 0x7b297bbcc7c72995ull, 0x6ed36e056b6bd3d6ull, 0x443c446c28283c50ull, - 0x8b798b2ca7a77955ull, 0x3de23d81bcbce263ull, 0x271d273116161d2cull, 0x9a769a37adad7641ull, - 0x4d3b4d96dbdb3badull, 0xfa56fa9e646456c8ull, 0xd24ed2a674744ee8ull, 0x221e223614141e28ull, - 0x76db76e49292db3full, 0x1e0a1e120c0c0a18ull, 0xb46cb4fc48486c90ull, 0x37e4378fb8b8e46bull, - 0xe75de7789f9f5d25ull, 0xb26eb20fbdbd6e61ull, 0x2aef2a694343ef86ull, 0xf1a6f135c4c4a693ull, - 0xe3a8e3da3939a872ull, 0xf7a4f7c63131a462ull, 0x5937598ad3d337bdull, 0x868b8674f2f28bffull, - 0x56325683d5d532b1ull, 0xc543c54e8b8b430dull, 0xeb59eb856e6e59dcull, 0xc2b7c218dadab7afull, - 0x8f8c8f8e01018c02ull, 0xac64ac1db1b16479ull, 0x6dd26df19c9cd223ull, 0x3be03b724949e092ull, - 0xc7b4c71fd8d8b4abull, 0x15fa15b9acacfa43ull, 0x090709faf3f307fdull, 0x6f256fa0cfcf2585ull, - 0xeaafea20cacaaf8full, 0x898e897df4f48ef3ull, 0x20e920674747e98eull, 0x2818283810101820ull, - 0x64d5640b6f6fd5deull, 0x83888373f0f088fbull, 0xb16fb1fb4a4a6f94ull, 0x967296ca5c5c72b8ull, - 0x6c246c5438382470ull, 0x08f1085f5757f1aeull, 0x52c752217373c7e6ull, 0xf351f36497975135ull, - 0x652365aecbcb238dull, 0x847c8425a1a17c59ull, 0xbf9cbf57e8e89ccbull, 0x6321635d3e3e217cull, - 0x7cdd7cea9696dd37ull, 0x7fdc7f1e6161dcc2ull, 0x9186919c0d0d861aull, 0x9485949b0f0f851eull, - 0xab90ab4be0e090dbull, 0xc642c6ba7c7c42f8ull, 0x57c457267171c4e2ull, 0xe5aae529ccccaa83ull, - 0x73d873e39090d83bull, 0x0f050f090606050cull, 0x030103f4f7f701f5ull, 0x3612362a1c1c1238ull, - 0xfea3fe3cc2c2a39full, 0xe15fe18b6a6a5fd4ull, 0x10f910beaeaef947ull, 0x6bd06b026969d0d2ull, - 0xa891a8bf1717912eull, 0xe858e87199995829ull, 0x692769533a3a2774ull, 0xd0b9d0f72727b94eull, - 0x48384891d9d938a9ull, 0x351335deebeb13cdull, 0xceb3cee52b2bb356ull, 0x5533557722223344ull, - 0xd6bbd604d2d2bbbfull, 0x90709039a9a97049ull, 0x808980870707890eull, 0xf2a7f2c13333a766ull, - 0xc1b6c1ec2d2db65aull, 0x6622665a3c3c2278ull, 0xad92adb81515922aull, 0x602060a9c9c92089ull, - 0xdb49db5c87874915ull, 0x1aff1ab0aaaaff4full, 0x887888d8505078a0ull, 0x8e7a8e2ba5a57a51ull, - 0x8a8f8a8903038f06ull, 0x13f8134a5959f8b2ull, 0x9b809b9209098012ull, 0x391739231a1a1734ull, - 0x75da75106565dacaull, 0x53315384d7d731b5ull, 0x51c651d58484c613ull, 0xd3b8d303d0d0b8bbull, - 0x5ec35edc8282c31full, 0xcbb0cbe22929b052ull, 0x997799c35a5a77b4ull, 0x3311332d1e1e113cull, - 0x46cb463d7b7bcbf6ull, 0x1ffc1fb7a8a8fc4bull, 0x61d6610c6d6dd6daull, 0x4e3a4e622c2c3a58ull - }, - { - 0xa5f432c6c6a597f4ull, 0x84976ff8f884eb97ull, 0x99b05eeeee99c7b0ull, 0x8d8c7af6f68df78cull, - 0x0d17e8ffff0de517ull, 0xbddc0ad6d6bdb7dcull, 0xb1c816dedeb1a7c8ull, 0x54fc6d91915439fcull, - 0x50f090606050c0f0ull, 0x0305070202030405ull, 0xa9e02ececea987e0ull, 0x7d87d156567dac87ull, - 0x192bcce7e719d52bull, 0x62a613b5b56271a6ull, 0xe6317c4d4de69a31ull, 0x9ab559ecec9ac3b5ull, - 0x45cf408f8f4505cfull, 0x9dbca31f1f9d3ebcull, 0x40c04989894009c0ull, 0x879268fafa87ef92ull, - 0x153fd0efef15c53full, 0xeb2694b2b2eb7f26ull, 0xc940ce8e8ec90740ull, 0x0b1de6fbfb0bed1dull, - 0xec2f6e4141ec822full, 0x67a91ab3b3677da9ull, 0xfd1c435f5ffdbe1cull, 0xea25604545ea8a25ull, - 0xbfdaf92323bf46daull, 0xf702515353f7a602ull, 0x96a145e4e496d3a1ull, 0x5bed769b9b5b2dedull, - 0xc25d287575c2ea5dull, 0x1c24c5e1e11cd924ull, 0xaee9d43d3dae7ae9ull, 0x6abef24c4c6a98beull, - 0x5aee826c6c5ad8eeull, 0x41c3bd7e7e41fcc3ull, 0x0206f3f5f502f106ull, 0x4fd15283834f1dd1ull, - 0x5ce48c68685cd0e4ull, 0xf407565151f4a207ull, 0x345c8dd1d134b95cull, 0x0818e1f9f908e918ull, - 0x93ae4ce2e293dfaeull, 0x73953eabab734d95ull, 0x53f597626253c4f5ull, 0x3f416b2a2a3f5441ull, - 0x0c141c08080c1014ull, 0x52f66395955231f6ull, 0x65afe94646658cafull, 0x5ee27f9d9d5e21e2ull, - 0x2878483030286078ull, 0xa1f8cf3737a16ef8ull, 0x0f111b0a0a0f1411ull, 0xb5c4eb2f2fb55ec4ull, - 0x091b150e0e091c1bull, 0x365a7e242436485aull, 0x9bb6ad1b1b9b36b6ull, 0x3d4798dfdf3da547ull, - 0x266aa7cdcd26816aull, 0x69bbf54e4e699cbbull, 0xcd4c337f7fcdfe4cull, 0x9fba50eaea9fcfbaull, - 0x1b2d3f12121b242dull, 0x9eb9a41d1d9e3ab9ull, 0x749cc4585874b09cull, 0x2e724634342e6872ull, - 0x2d774136362d6c77ull, 0xb2cd11dcdcb2a3cdull, 0xee299db4b4ee7329ull, 0xfb164d5b5bfbb616ull, - 0xf601a5a4a4f65301ull, 0x4dd7a176764decd7ull, 0x61a314b7b76175a3ull, 0xce49347d7dcefa49ull, - 0x7b8ddf52527ba48dull, 0x3e429fdddd3ea142ull, 0x7193cd5e5e71bc93ull, 0x97a2b113139726a2ull, - 0xf504a2a6a6f55704ull, 0x68b801b9b96869b8ull, 0x0000000000000000ull, 0x2c74b5c1c12c9974ull, - 0x60a0e040406080a0ull, 0x1f21c2e3e31fdd21ull, 0xc8433a7979c8f243ull, 0xed2c9ab6b6ed772cull, - 0xbed90dd4d4beb3d9ull, 0x46ca478d8d4601caull, 0xd970176767d9ce70ull, 0x4bddaf72724be4ddull, - 0xde79ed9494de3379ull, 0xd467ff9898d42b67ull, 0xe82393b0b0e87b23ull, 0x4ade5b85854a11deull, - 0x6bbd06bbbb6b6dbdull, 0x2a7ebbc5c52a917eull, 0xe5347b4f4fe59e34ull, 0x163ad7eded16c13aull, - 0xc554d28686c51754ull, 0xd762f89a9ad72f62ull, 0x55ff99666655ccffull, 0x94a7b611119422a7ull, - 0xcf4ac08a8acf0f4aull, 0x1030d9e9e910c930ull, 0x060a0e040406080aull, 0x819866fefe81e798ull, - 0xf00baba0a0f05b0bull, 0x44ccb4787844f0ccull, 0xbad5f02525ba4ad5ull, 0xe33e754b4be3963eull, - 0xf30eaca2a2f35f0eull, 0xfe19445d5dfeba19ull, 0xc05bdb8080c01b5bull, 0x8a858005058a0a85ull, - 0xadecd33f3fad7eecull, 0xbcdffe2121bc42dfull, 0x48d8a8707048e0d8ull, 0x040cfdf1f104f90cull, - 0xdf7a196363dfc67aull, 0xc1582f7777c1ee58ull, 0x759f30afaf75459full, 0x63a5e742426384a5ull, - 0x3050702020304050ull, 0x1a2ecbe5e51ad12eull, 0x0e12effdfd0ee112ull, 0x6db708bfbf6d65b7ull, - 0x4cd45581814c19d4ull, 0x143c24181814303cull, 0x355f792626354c5full, 0x2f71b2c3c32f9d71ull, - 0xe13886bebee16738ull, 0xa2fdc83535a26afdull, 0xcc4fc78888cc0b4full, 0x394b652e2e395c4bull, - 0x57f96a9393573df9ull, 0xf20d585555f2aa0dull, 0x829d61fcfc82e39dull, 0x47c9b37a7a47f4c9ull, - 0xacef27c8c8ac8befull, 0xe73288babae76f32ull, 0x2b7d4f32322b647dull, 0x95a442e6e695d7a4ull, - 0xa0fb3bc0c0a09bfbull, 0x98b3aa19199832b3ull, 0xd168f69e9ed12768ull, 0x7f8122a3a37f5d81ull, - 0x66aaee44446688aaull, 0x7e82d654547ea882ull, 0xabe6dd3b3bab76e6ull, 0x839e950b0b83169eull, - 0xca45c98c8cca0345ull, 0x297bbcc7c729957bull, 0xd36e056b6bd3d66eull, 0x3c446c28283c5044ull, - 0x798b2ca7a779558bull, 0xe23d81bcbce2633dull, 0x1d273116161d2c27ull, 0x769a37adad76419aull, - 0x3b4d96dbdb3bad4dull, 0x56fa9e646456c8faull, 0x4ed2a674744ee8d2ull, 0x1e223614141e2822ull, - 0xdb76e49292db3f76ull, 0x0a1e120c0c0a181eull, 0x6cb4fc48486c90b4ull, 0xe4378fb8b8e46b37ull, - 0x5de7789f9f5d25e7ull, 0x6eb20fbdbd6e61b2ull, 0xef2a694343ef862aull, 0xa6f135c4c4a693f1ull, - 0xa8e3da3939a872e3ull, 0xa4f7c63131a462f7ull, 0x37598ad3d337bd59ull, 0x8b8674f2f28bff86ull, - 0x325683d5d532b156ull, 0x43c54e8b8b430dc5ull, 0x59eb856e6e59dcebull, 0xb7c218dadab7afc2ull, - 0x8c8f8e01018c028full, 0x64ac1db1b16479acull, 0xd26df19c9cd2236dull, 0xe03b724949e0923bull, - 0xb4c71fd8d8b4abc7ull, 0xfa15b9acacfa4315ull, 0x0709faf3f307fd09ull, 0x256fa0cfcf25856full, - 0xafea20cacaaf8feaull, 0x8e897df4f48ef389ull, 0xe920674747e98e20ull, 0x1828381010182028ull, - 0xd5640b6f6fd5de64ull, 0x888373f0f088fb83ull, 0x6fb1fb4a4a6f94b1ull, 0x7296ca5c5c72b896ull, - 0x246c54383824706cull, 0xf1085f5757f1ae08ull, 0xc752217373c7e652ull, 0x51f36497975135f3ull, - 0x2365aecbcb238d65ull, 0x7c8425a1a17c5984ull, 0x9cbf57e8e89ccbbfull, 0x21635d3e3e217c63ull, - 0xdd7cea9696dd377cull, 0xdc7f1e6161dcc27full, 0x86919c0d0d861a91ull, 0x85949b0f0f851e94ull, - 0x90ab4be0e090dbabull, 0x42c6ba7c7c42f8c6ull, 0xc457267171c4e257ull, 0xaae529ccccaa83e5ull, - 0xd873e39090d83b73ull, 0x050f090606050c0full, 0x0103f4f7f701f503ull, 0x12362a1c1c123836ull, - 0xa3fe3cc2c2a39ffeull, 0x5fe18b6a6a5fd4e1ull, 0xf910beaeaef94710ull, 0xd06b026969d0d26bull, - 0x91a8bf1717912ea8ull, 0x58e87199995829e8ull, 0x2769533a3a277469ull, 0xb9d0f72727b94ed0ull, - 0x384891d9d938a948ull, 0x1335deebeb13cd35ull, 0xb3cee52b2bb356ceull, 0x3355772222334455ull, - 0xbbd604d2d2bbbfd6ull, 0x709039a9a9704990ull, 0x8980870707890e80ull, 0xa7f2c13333a766f2ull, - 0xb6c1ec2d2db65ac1ull, 0x22665a3c3c227866ull, 0x92adb81515922aadull, 0x2060a9c9c9208960ull, - 0x49db5c87874915dbull, 0xff1ab0aaaaff4f1aull, 0x7888d8505078a088ull, 0x7a8e2ba5a57a518eull, - 0x8f8a8903038f068aull, 0xf8134a5959f8b213ull, 0x809b92090980129bull, 0x1739231a1a173439ull, - 0xda75106565daca75ull, 0x315384d7d731b553ull, 0xc651d58484c61351ull, 0xb8d303d0d0b8bbd3ull, - 0xc35edc8282c31f5eull, 0xb0cbe22929b052cbull, 0x7799c35a5a77b499ull, 0x11332d1e1e113c33ull, - 0xcb463d7b7bcbf646ull, 0xfc1fb7a8a8fc4b1full, 0xd6610c6d6dd6da61ull, 0x3a4e622c2c3a584eull - }, - { - 0xf432c6c6a597f4a5ull, 0x976ff8f884eb9784ull, 0xb05eeeee99c7b099ull, 0x8c7af6f68df78c8dull, - 0x17e8ffff0de5170dull, 0xdc0ad6d6bdb7dcbdull, 0xc816dedeb1a7c8b1ull, 0xfc6d91915439fc54ull, - 0xf090606050c0f050ull, 0x0507020203040503ull, 0xe02ececea987e0a9ull, 0x87d156567dac877dull, - 0x2bcce7e719d52b19ull, 0xa613b5b56271a662ull, 0x317c4d4de69a31e6ull, 0xb559ecec9ac3b59aull, - 0xcf408f8f4505cf45ull, 0xbca31f1f9d3ebc9dull, 0xc04989894009c040ull, 0x9268fafa87ef9287ull, - 0x3fd0efef15c53f15ull, 0x2694b2b2eb7f26ebull, 0x40ce8e8ec90740c9ull, 0x1de6fbfb0bed1d0bull, - 0x2f6e4141ec822fecull, 0xa91ab3b3677da967ull, 0x1c435f5ffdbe1cfdull, 0x25604545ea8a25eaull, - 0xdaf92323bf46dabfull, 0x02515353f7a602f7ull, 0xa145e4e496d3a196ull, 0xed769b9b5b2ded5bull, - 0x5d287575c2ea5dc2ull, 0x24c5e1e11cd9241cull, 0xe9d43d3dae7ae9aeull, 0xbef24c4c6a98be6aull, - 0xee826c6c5ad8ee5aull, 0xc3bd7e7e41fcc341ull, 0x06f3f5f502f10602ull, 0xd15283834f1dd14full, - 0xe48c68685cd0e45cull, 0x07565151f4a207f4ull, 0x5c8dd1d134b95c34ull, 0x18e1f9f908e91808ull, - 0xae4ce2e293dfae93ull, 0x953eabab734d9573ull, 0xf597626253c4f553ull, 0x416b2a2a3f54413full, - 0x141c08080c10140cull, 0xf66395955231f652ull, 0xafe94646658caf65ull, 0xe27f9d9d5e21e25eull, - 0x7848303028607828ull, 0xf8cf3737a16ef8a1ull, 0x111b0a0a0f14110full, 0xc4eb2f2fb55ec4b5ull, - 0x1b150e0e091c1b09ull, 0x5a7e242436485a36ull, 0xb6ad1b1b9b36b69bull, 0x4798dfdf3da5473dull, - 0x6aa7cdcd26816a26ull, 0xbbf54e4e699cbb69ull, 0x4c337f7fcdfe4ccdull, 0xba50eaea9fcfba9full, - 0x2d3f12121b242d1bull, 0xb9a41d1d9e3ab99eull, 0x9cc4585874b09c74ull, 0x724634342e68722eull, - 0x774136362d6c772dull, 0xcd11dcdcb2a3cdb2ull, 0x299db4b4ee7329eeull, 0x164d5b5bfbb616fbull, - 0x01a5a4a4f65301f6ull, 0xd7a176764decd74dull, 0xa314b7b76175a361ull, 0x49347d7dcefa49ceull, - 0x8ddf52527ba48d7bull, 0x429fdddd3ea1423eull, 0x93cd5e5e71bc9371ull, 0xa2b113139726a297ull, - 0x04a2a6a6f55704f5ull, 0xb801b9b96869b868ull, 0x0000000000000000ull, 0x74b5c1c12c99742cull, - 0xa0e040406080a060ull, 0x21c2e3e31fdd211full, 0x433a7979c8f243c8ull, 0x2c9ab6b6ed772cedull, - 0xd90dd4d4beb3d9beull, 0xca478d8d4601ca46ull, 0x70176767d9ce70d9ull, 0xddaf72724be4dd4bull, - 0x79ed9494de3379deull, 0x67ff9898d42b67d4ull, 0x2393b0b0e87b23e8ull, 0xde5b85854a11de4aull, - 0xbd06bbbb6b6dbd6bull, 0x7ebbc5c52a917e2aull, 0x347b4f4fe59e34e5ull, 0x3ad7eded16c13a16ull, - 0x54d28686c51754c5ull, 0x62f89a9ad72f62d7ull, 0xff99666655ccff55ull, 0xa7b611119422a794ull, - 0x4ac08a8acf0f4acfull, 0x30d9e9e910c93010ull, 0x0a0e040406080a06ull, 0x9866fefe81e79881ull, - 0x0baba0a0f05b0bf0ull, 0xccb4787844f0cc44ull, 0xd5f02525ba4ad5baull, 0x3e754b4be3963ee3ull, - 0x0eaca2a2f35f0ef3ull, 0x19445d5dfeba19feull, 0x5bdb8080c01b5bc0ull, 0x858005058a0a858aull, - 0xecd33f3fad7eecadull, 0xdffe2121bc42dfbcull, 0xd8a8707048e0d848ull, 0x0cfdf1f104f90c04ull, - 0x7a196363dfc67adfull, 0x582f7777c1ee58c1ull, 0x9f30afaf75459f75ull, 0xa5e742426384a563ull, - 0x5070202030405030ull, 0x2ecbe5e51ad12e1aull, 0x12effdfd0ee1120eull, 0xb708bfbf6d65b76dull, - 0xd45581814c19d44cull, 0x3c24181814303c14ull, 0x5f792626354c5f35ull, 0x71b2c3c32f9d712full, - 0x3886bebee16738e1ull, 0xfdc83535a26afda2ull, 0x4fc78888cc0b4fccull, 0x4b652e2e395c4b39ull, - 0xf96a9393573df957ull, 0x0d585555f2aa0df2ull, 0x9d61fcfc82e39d82ull, 0xc9b37a7a47f4c947ull, - 0xef27c8c8ac8befacull, 0x3288babae76f32e7ull, 0x7d4f32322b647d2bull, 0xa442e6e695d7a495ull, - 0xfb3bc0c0a09bfba0ull, 0xb3aa19199832b398ull, 0x68f69e9ed12768d1ull, 0x8122a3a37f5d817full, - 0xaaee44446688aa66ull, 0x82d654547ea8827eull, 0xe6dd3b3bab76e6abull, 0x9e950b0b83169e83ull, - 0x45c98c8cca0345caull, 0x7bbcc7c729957b29ull, 0x6e056b6bd3d66ed3ull, 0x446c28283c50443cull, - 0x8b2ca7a779558b79ull, 0x3d81bcbce2633de2ull, 0x273116161d2c271dull, 0x9a37adad76419a76ull, - 0x4d96dbdb3bad4d3bull, 0xfa9e646456c8fa56ull, 0xd2a674744ee8d24eull, 0x223614141e28221eull, - 0x76e49292db3f76dbull, 0x1e120c0c0a181e0aull, 0xb4fc48486c90b46cull, 0x378fb8b8e46b37e4ull, - 0xe7789f9f5d25e75dull, 0xb20fbdbd6e61b26eull, 0x2a694343ef862aefull, 0xf135c4c4a693f1a6ull, - 0xe3da3939a872e3a8ull, 0xf7c63131a462f7a4ull, 0x598ad3d337bd5937ull, 0x8674f2f28bff868bull, - 0x5683d5d532b15632ull, 0xc54e8b8b430dc543ull, 0xeb856e6e59dceb59ull, 0xc218dadab7afc2b7ull, - 0x8f8e01018c028f8cull, 0xac1db1b16479ac64ull, 0x6df19c9cd2236dd2ull, 0x3b724949e0923be0ull, - 0xc71fd8d8b4abc7b4ull, 0x15b9acacfa4315faull, 0x09faf3f307fd0907ull, 0x6fa0cfcf25856f25ull, - 0xea20cacaaf8feaafull, 0x897df4f48ef3898eull, 0x20674747e98e20e9ull, 0x2838101018202818ull, - 0x640b6f6fd5de64d5ull, 0x8373f0f088fb8388ull, 0xb1fb4a4a6f94b16full, 0x96ca5c5c72b89672ull, - 0x6c54383824706c24ull, 0x085f5757f1ae08f1ull, 0x52217373c7e652c7ull, 0xf36497975135f351ull, - 0x65aecbcb238d6523ull, 0x8425a1a17c59847cull, 0xbf57e8e89ccbbf9cull, 0x635d3e3e217c6321ull, - 0x7cea9696dd377cddull, 0x7f1e6161dcc27fdcull, 0x919c0d0d861a9186ull, 0x949b0f0f851e9485ull, - 0xab4be0e090dbab90ull, 0xc6ba7c7c42f8c642ull, 0x57267171c4e257c4ull, 0xe529ccccaa83e5aaull, - 0x73e39090d83b73d8ull, 0x0f090606050c0f05ull, 0x03f4f7f701f50301ull, 0x362a1c1c12383612ull, - 0xfe3cc2c2a39ffea3ull, 0xe18b6a6a5fd4e15full, 0x10beaeaef94710f9ull, 0x6b026969d0d26bd0ull, - 0xa8bf1717912ea891ull, 0xe87199995829e858ull, 0x69533a3a27746927ull, 0xd0f72727b94ed0b9ull, - 0x4891d9d938a94838ull, 0x35deebeb13cd3513ull, 0xcee52b2bb356ceb3ull, 0x5577222233445533ull, - 0xd604d2d2bbbfd6bbull, 0x9039a9a970499070ull, 0x80870707890e8089ull, 0xf2c13333a766f2a7ull, - 0xc1ec2d2db65ac1b6ull, 0x665a3c3c22786622ull, 0xadb81515922aad92ull, 0x60a9c9c920896020ull, - 0xdb5c87874915db49ull, 0x1ab0aaaaff4f1affull, 0x88d8505078a08878ull, 0x8e2ba5a57a518e7aull, - 0x8a8903038f068a8full, 0x134a5959f8b213f8ull, 0x9b92090980129b80ull, 0x39231a1a17343917ull, - 0x75106565daca75daull, 0x5384d7d731b55331ull, 0x51d58484c61351c6ull, 0xd303d0d0b8bbd3b8ull, - 0x5edc8282c31f5ec3ull, 0xcbe22929b052cbb0ull, 0x99c35a5a77b49977ull, 0x332d1e1e113c3311ull, - 0x463d7b7bcbf646cbull, 0x1fb7a8a8fc4b1ffcull, 0x610c6d6dd6da61d6ull, 0x4e622c2c3a584e3aull - }, - { - 0x32c6c6a597f4a5f4ull, 0x6ff8f884eb978497ull, 0x5eeeee99c7b099b0ull, 0x7af6f68df78c8d8cull, - 0xe8ffff0de5170d17ull, 0x0ad6d6bdb7dcbddcull, 0x16dedeb1a7c8b1c8ull, 0x6d91915439fc54fcull, - 0x90606050c0f050f0ull, 0x0702020304050305ull, 0x2ececea987e0a9e0ull, 0xd156567dac877d87ull, - 0xcce7e719d52b192bull, 0x13b5b56271a662a6ull, 0x7c4d4de69a31e631ull, 0x59ecec9ac3b59ab5ull, - 0x408f8f4505cf45cfull, 0xa31f1f9d3ebc9dbcull, 0x4989894009c040c0ull, 0x68fafa87ef928792ull, - 0xd0efef15c53f153full, 0x94b2b2eb7f26eb26ull, 0xce8e8ec90740c940ull, 0xe6fbfb0bed1d0b1dull, - 0x6e4141ec822fec2full, 0x1ab3b3677da967a9ull, 0x435f5ffdbe1cfd1cull, 0x604545ea8a25ea25ull, - 0xf92323bf46dabfdaull, 0x515353f7a602f702ull, 0x45e4e496d3a196a1ull, 0x769b9b5b2ded5bedull, - 0x287575c2ea5dc25dull, 0xc5e1e11cd9241c24ull, 0xd43d3dae7ae9aee9ull, 0xf24c4c6a98be6abeull, - 0x826c6c5ad8ee5aeeull, 0xbd7e7e41fcc341c3ull, 0xf3f5f502f1060206ull, 0x5283834f1dd14fd1ull, - 0x8c68685cd0e45ce4ull, 0x565151f4a207f407ull, 0x8dd1d134b95c345cull, 0xe1f9f908e9180818ull, - 0x4ce2e293dfae93aeull, 0x3eabab734d957395ull, 0x97626253c4f553f5ull, 0x6b2a2a3f54413f41ull, - 0x1c08080c10140c14ull, 0x6395955231f652f6ull, 0xe94646658caf65afull, 0x7f9d9d5e21e25ee2ull, - 0x4830302860782878ull, 0xcf3737a16ef8a1f8ull, 0x1b0a0a0f14110f11ull, 0xeb2f2fb55ec4b5c4ull, - 0x150e0e091c1b091bull, 0x7e242436485a365aull, 0xad1b1b9b36b69bb6ull, 0x98dfdf3da5473d47ull, - 0xa7cdcd26816a266aull, 0xf54e4e699cbb69bbull, 0x337f7fcdfe4ccd4cull, 0x50eaea9fcfba9fbaull, - 0x3f12121b242d1b2dull, 0xa41d1d9e3ab99eb9ull, 0xc4585874b09c749cull, 0x4634342e68722e72ull, - 0x4136362d6c772d77ull, 0x11dcdcb2a3cdb2cdull, 0x9db4b4ee7329ee29ull, 0x4d5b5bfbb616fb16ull, - 0xa5a4a4f65301f601ull, 0xa176764decd74dd7ull, 0x14b7b76175a361a3ull, 0x347d7dcefa49ce49ull, - 0xdf52527ba48d7b8dull, 0x9fdddd3ea1423e42ull, 0xcd5e5e71bc937193ull, 0xb113139726a297a2ull, - 0xa2a6a6f55704f504ull, 0x01b9b96869b868b8ull, 0x0000000000000000ull, 0xb5c1c12c99742c74ull, - 0xe040406080a060a0ull, 0xc2e3e31fdd211f21ull, 0x3a7979c8f243c843ull, 0x9ab6b6ed772ced2cull, - 0x0dd4d4beb3d9bed9ull, 0x478d8d4601ca46caull, 0x176767d9ce70d970ull, 0xaf72724be4dd4bddull, - 0xed9494de3379de79ull, 0xff9898d42b67d467ull, 0x93b0b0e87b23e823ull, 0x5b85854a11de4adeull, - 0x06bbbb6b6dbd6bbdull, 0xbbc5c52a917e2a7eull, 0x7b4f4fe59e34e534ull, 0xd7eded16c13a163aull, - 0xd28686c51754c554ull, 0xf89a9ad72f62d762ull, 0x99666655ccff55ffull, 0xb611119422a794a7ull, - 0xc08a8acf0f4acf4aull, 0xd9e9e910c9301030ull, 0x0e040406080a060aull, 0x66fefe81e7988198ull, - 0xaba0a0f05b0bf00bull, 0xb4787844f0cc44ccull, 0xf02525ba4ad5bad5ull, 0x754b4be3963ee33eull, - 0xaca2a2f35f0ef30eull, 0x445d5dfeba19fe19ull, 0xdb8080c01b5bc05bull, 0x8005058a0a858a85ull, - 0xd33f3fad7eecadecull, 0xfe2121bc42dfbcdfull, 0xa8707048e0d848d8ull, 0xfdf1f104f90c040cull, - 0x196363dfc67adf7aull, 0x2f7777c1ee58c158ull, 0x30afaf75459f759full, 0xe742426384a563a5ull, - 0x7020203040503050ull, 0xcbe5e51ad12e1a2eull, 0xeffdfd0ee1120e12ull, 0x08bfbf6d65b76db7ull, - 0x5581814c19d44cd4ull, 0x24181814303c143cull, 0x792626354c5f355full, 0xb2c3c32f9d712f71ull, - 0x86bebee16738e138ull, 0xc83535a26afda2fdull, 0xc78888cc0b4fcc4full, 0x652e2e395c4b394bull, - 0x6a9393573df957f9ull, 0x585555f2aa0df20dull, 0x61fcfc82e39d829dull, 0xb37a7a47f4c947c9ull, - 0x27c8c8ac8befacefull, 0x88babae76f32e732ull, 0x4f32322b647d2b7dull, 0x42e6e695d7a495a4ull, - 0x3bc0c0a09bfba0fbull, 0xaa19199832b398b3ull, 0xf69e9ed12768d168ull, 0x22a3a37f5d817f81ull, - 0xee44446688aa66aaull, 0xd654547ea8827e82ull, 0xdd3b3bab76e6abe6ull, 0x950b0b83169e839eull, - 0xc98c8cca0345ca45ull, 0xbcc7c729957b297bull, 0x056b6bd3d66ed36eull, 0x6c28283c50443c44ull, - 0x2ca7a779558b798bull, 0x81bcbce2633de23dull, 0x3116161d2c271d27ull, 0x37adad76419a769aull, - 0x96dbdb3bad4d3b4dull, 0x9e646456c8fa56faull, 0xa674744ee8d24ed2ull, 0x3614141e28221e22ull, - 0xe49292db3f76db76ull, 0x120c0c0a181e0a1eull, 0xfc48486c90b46cb4ull, 0x8fb8b8e46b37e437ull, - 0x789f9f5d25e75de7ull, 0x0fbdbd6e61b26eb2ull, 0x694343ef862aef2aull, 0x35c4c4a693f1a6f1ull, - 0xda3939a872e3a8e3ull, 0xc63131a462f7a4f7ull, 0x8ad3d337bd593759ull, 0x74f2f28bff868b86ull, - 0x83d5d532b1563256ull, 0x4e8b8b430dc543c5ull, 0x856e6e59dceb59ebull, 0x18dadab7afc2b7c2ull, - 0x8e01018c028f8c8full, 0x1db1b16479ac64acull, 0xf19c9cd2236dd26dull, 0x724949e0923be03bull, - 0x1fd8d8b4abc7b4c7ull, 0xb9acacfa4315fa15ull, 0xfaf3f307fd090709ull, 0xa0cfcf25856f256full, - 0x20cacaaf8feaafeaull, 0x7df4f48ef3898e89ull, 0x674747e98e20e920ull, 0x3810101820281828ull, - 0x0b6f6fd5de64d564ull, 0x73f0f088fb838883ull, 0xfb4a4a6f94b16fb1ull, 0xca5c5c72b8967296ull, - 0x54383824706c246cull, 0x5f5757f1ae08f108ull, 0x217373c7e652c752ull, 0x6497975135f351f3ull, - 0xaecbcb238d652365ull, 0x25a1a17c59847c84ull, 0x57e8e89ccbbf9cbfull, 0x5d3e3e217c632163ull, - 0xea9696dd377cdd7cull, 0x1e6161dcc27fdc7full, 0x9c0d0d861a918691ull, 0x9b0f0f851e948594ull, - 0x4be0e090dbab90abull, 0xba7c7c42f8c642c6ull, 0x267171c4e257c457ull, 0x29ccccaa83e5aae5ull, - 0xe39090d83b73d873ull, 0x090606050c0f050full, 0xf4f7f701f5030103ull, 0x2a1c1c1238361236ull, - 0x3cc2c2a39ffea3feull, 0x8b6a6a5fd4e15fe1ull, 0xbeaeaef94710f910ull, 0x026969d0d26bd06bull, - 0xbf1717912ea891a8ull, 0x7199995829e858e8ull, 0x533a3a2774692769ull, 0xf72727b94ed0b9d0ull, - 0x91d9d938a9483848ull, 0xdeebeb13cd351335ull, 0xe52b2bb356ceb3ceull, 0x7722223344553355ull, - 0x04d2d2bbbfd6bbd6ull, 0x39a9a97049907090ull, 0x870707890e808980ull, 0xc13333a766f2a7f2ull, - 0xec2d2db65ac1b6c1ull, 0x5a3c3c2278662266ull, 0xb81515922aad92adull, 0xa9c9c92089602060ull, - 0x5c87874915db49dbull, 0xb0aaaaff4f1aff1aull, 0xd8505078a0887888ull, 0x2ba5a57a518e7a8eull, - 0x8903038f068a8f8aull, 0x4a5959f8b213f813ull, 0x92090980129b809bull, 0x231a1a1734391739ull, - 0x106565daca75da75ull, 0x84d7d731b5533153ull, 0xd58484c61351c651ull, 0x03d0d0b8bbd3b8d3ull, - 0xdc8282c31f5ec35eull, 0xe22929b052cbb0cbull, 0xc35a5a77b4997799ull, 0x2d1e1e113c331133ull, - 0x3d7b7bcbf646cb46ull, 0xb7a8a8fc4b1ffc1full, 0x0c6d6dd6da61d661ull, 0x622c2c3a584e3a4eull - }, - { - 0xc6c6a597f4a5f432ull, 0xf8f884eb9784976full, 0xeeee99c7b099b05eull, 0xf6f68df78c8d8c7aull, - 0xffff0de5170d17e8ull, 0xd6d6bdb7dcbddc0aull, 0xdedeb1a7c8b1c816ull, 0x91915439fc54fc6dull, - 0x606050c0f050f090ull, 0x0202030405030507ull, 0xcecea987e0a9e02eull, 0x56567dac877d87d1ull, - 0xe7e719d52b192bccull, 0xb5b56271a662a613ull, 0x4d4de69a31e6317cull, 0xecec9ac3b59ab559ull, - 0x8f8f4505cf45cf40ull, 0x1f1f9d3ebc9dbca3ull, 0x89894009c040c049ull, 0xfafa87ef92879268ull, - 0xefef15c53f153fd0ull, 0xb2b2eb7f26eb2694ull, 0x8e8ec90740c940ceull, 0xfbfb0bed1d0b1de6ull, - 0x4141ec822fec2f6eull, 0xb3b3677da967a91aull, 0x5f5ffdbe1cfd1c43ull, 0x4545ea8a25ea2560ull, - 0x2323bf46dabfdaf9ull, 0x5353f7a602f70251ull, 0xe4e496d3a196a145ull, 0x9b9b5b2ded5bed76ull, - 0x7575c2ea5dc25d28ull, 0xe1e11cd9241c24c5ull, 0x3d3dae7ae9aee9d4ull, 0x4c4c6a98be6abef2ull, - 0x6c6c5ad8ee5aee82ull, 0x7e7e41fcc341c3bdull, 0xf5f502f1060206f3ull, 0x83834f1dd14fd152ull, - 0x68685cd0e45ce48cull, 0x5151f4a207f40756ull, 0xd1d134b95c345c8dull, 0xf9f908e9180818e1ull, - 0xe2e293dfae93ae4cull, 0xabab734d9573953eull, 0x626253c4f553f597ull, 0x2a2a3f54413f416bull, - 0x08080c10140c141cull, 0x95955231f652f663ull, 0x4646658caf65afe9ull, 0x9d9d5e21e25ee27full, - 0x3030286078287848ull, 0x3737a16ef8a1f8cfull, 0x0a0a0f14110f111bull, 0x2f2fb55ec4b5c4ebull, - 0x0e0e091c1b091b15ull, 0x242436485a365a7eull, 0x1b1b9b36b69bb6adull, 0xdfdf3da5473d4798ull, - 0xcdcd26816a266aa7ull, 0x4e4e699cbb69bbf5ull, 0x7f7fcdfe4ccd4c33ull, 0xeaea9fcfba9fba50ull, - 0x12121b242d1b2d3full, 0x1d1d9e3ab99eb9a4ull, 0x585874b09c749cc4ull, 0x34342e68722e7246ull, - 0x36362d6c772d7741ull, 0xdcdcb2a3cdb2cd11ull, 0xb4b4ee7329ee299dull, 0x5b5bfbb616fb164dull, - 0xa4a4f65301f601a5ull, 0x76764decd74dd7a1ull, 0xb7b76175a361a314ull, 0x7d7dcefa49ce4934ull, - 0x52527ba48d7b8ddfull, 0xdddd3ea1423e429full, 0x5e5e71bc937193cdull, 0x13139726a297a2b1ull, - 0xa6a6f55704f504a2ull, 0xb9b96869b868b801ull, 0x0000000000000000ull, 0xc1c12c99742c74b5ull, - 0x40406080a060a0e0ull, 0xe3e31fdd211f21c2ull, 0x7979c8f243c8433aull, 0xb6b6ed772ced2c9aull, - 0xd4d4beb3d9bed90dull, 0x8d8d4601ca46ca47ull, 0x6767d9ce70d97017ull, 0x72724be4dd4bddafull, - 0x9494de3379de79edull, 0x9898d42b67d467ffull, 0xb0b0e87b23e82393ull, 0x85854a11de4ade5bull, - 0xbbbb6b6dbd6bbd06ull, 0xc5c52a917e2a7ebbull, 0x4f4fe59e34e5347bull, 0xeded16c13a163ad7ull, - 0x8686c51754c554d2ull, 0x9a9ad72f62d762f8ull, 0x666655ccff55ff99ull, 0x11119422a794a7b6ull, - 0x8a8acf0f4acf4ac0ull, 0xe9e910c9301030d9ull, 0x040406080a060a0eull, 0xfefe81e798819866ull, - 0xa0a0f05b0bf00babull, 0x787844f0cc44ccb4ull, 0x2525ba4ad5bad5f0ull, 0x4b4be3963ee33e75ull, - 0xa2a2f35f0ef30eacull, 0x5d5dfeba19fe1944ull, 0x8080c01b5bc05bdbull, 0x05058a0a858a8580ull, - 0x3f3fad7eecadecd3ull, 0x2121bc42dfbcdffeull, 0x707048e0d848d8a8ull, 0xf1f104f90c040cfdull, - 0x6363dfc67adf7a19ull, 0x7777c1ee58c1582full, 0xafaf75459f759f30ull, 0x42426384a563a5e7ull, - 0x2020304050305070ull, 0xe5e51ad12e1a2ecbull, 0xfdfd0ee1120e12efull, 0xbfbf6d65b76db708ull, - 0x81814c19d44cd455ull, 0x181814303c143c24ull, 0x2626354c5f355f79ull, 0xc3c32f9d712f71b2ull, - 0xbebee16738e13886ull, 0x3535a26afda2fdc8ull, 0x8888cc0b4fcc4fc7ull, 0x2e2e395c4b394b65ull, - 0x9393573df957f96aull, 0x5555f2aa0df20d58ull, 0xfcfc82e39d829d61ull, 0x7a7a47f4c947c9b3ull, - 0xc8c8ac8befacef27ull, 0xbabae76f32e73288ull, 0x32322b647d2b7d4full, 0xe6e695d7a495a442ull, - 0xc0c0a09bfba0fb3bull, 0x19199832b398b3aaull, 0x9e9ed12768d168f6ull, 0xa3a37f5d817f8122ull, - 0x44446688aa66aaeeull, 0x54547ea8827e82d6ull, 0x3b3bab76e6abe6ddull, 0x0b0b83169e839e95ull, - 0x8c8cca0345ca45c9ull, 0xc7c729957b297bbcull, 0x6b6bd3d66ed36e05ull, 0x28283c50443c446cull, - 0xa7a779558b798b2cull, 0xbcbce2633de23d81ull, 0x16161d2c271d2731ull, 0xadad76419a769a37ull, - 0xdbdb3bad4d3b4d96ull, 0x646456c8fa56fa9eull, 0x74744ee8d24ed2a6ull, 0x14141e28221e2236ull, - 0x9292db3f76db76e4ull, 0x0c0c0a181e0a1e12ull, 0x48486c90b46cb4fcull, 0xb8b8e46b37e4378full, - 0x9f9f5d25e75de778ull, 0xbdbd6e61b26eb20full, 0x4343ef862aef2a69ull, 0xc4c4a693f1a6f135ull, - 0x3939a872e3a8e3daull, 0x3131a462f7a4f7c6ull, 0xd3d337bd5937598aull, 0xf2f28bff868b8674ull, - 0xd5d532b156325683ull, 0x8b8b430dc543c54eull, 0x6e6e59dceb59eb85ull, 0xdadab7afc2b7c218ull, - 0x01018c028f8c8f8eull, 0xb1b16479ac64ac1dull, 0x9c9cd2236dd26df1ull, 0x4949e0923be03b72ull, - 0xd8d8b4abc7b4c71full, 0xacacfa4315fa15b9ull, 0xf3f307fd090709faull, 0xcfcf25856f256fa0ull, - 0xcacaaf8feaafea20ull, 0xf4f48ef3898e897dull, 0x4747e98e20e92067ull, 0x1010182028182838ull, - 0x6f6fd5de64d5640bull, 0xf0f088fb83888373ull, 0x4a4a6f94b16fb1fbull, 0x5c5c72b8967296caull, - 0x383824706c246c54ull, 0x5757f1ae08f1085full, 0x7373c7e652c75221ull, 0x97975135f351f364ull, - 0xcbcb238d652365aeull, 0xa1a17c59847c8425ull, 0xe8e89ccbbf9cbf57ull, 0x3e3e217c6321635dull, - 0x9696dd377cdd7ceaull, 0x6161dcc27fdc7f1eull, 0x0d0d861a9186919cull, 0x0f0f851e9485949bull, - 0xe0e090dbab90ab4bull, 0x7c7c42f8c642c6baull, 0x7171c4e257c45726ull, 0xccccaa83e5aae529ull, - 0x9090d83b73d873e3ull, 0x0606050c0f050f09ull, 0xf7f701f5030103f4ull, 0x1c1c12383612362aull, - 0xc2c2a39ffea3fe3cull, 0x6a6a5fd4e15fe18bull, 0xaeaef94710f910beull, 0x6969d0d26bd06b02ull, - 0x1717912ea891a8bfull, 0x99995829e858e871ull, 0x3a3a277469276953ull, 0x2727b94ed0b9d0f7ull, - 0xd9d938a948384891ull, 0xebeb13cd351335deull, 0x2b2bb356ceb3cee5ull, 0x2222334455335577ull, - 0xd2d2bbbfd6bbd604ull, 0xa9a9704990709039ull, 0x0707890e80898087ull, 0x3333a766f2a7f2c1ull, - 0x2d2db65ac1b6c1ecull, 0x3c3c22786622665aull, 0x1515922aad92adb8ull, 0xc9c92089602060a9ull, - 0x87874915db49db5cull, 0xaaaaff4f1aff1ab0ull, 0x505078a0887888d8ull, 0xa5a57a518e7a8e2bull, - 0x03038f068a8f8a89ull, 0x5959f8b213f8134aull, 0x090980129b809b92ull, 0x1a1a173439173923ull, - 0x6565daca75da7510ull, 0xd7d731b553315384ull, 0x8484c61351c651d5ull, 0xd0d0b8bbd3b8d303ull, - 0x8282c31f5ec35edcull, 0x2929b052cbb0cbe2ull, 0x5a5a77b4997799c3ull, 0x1e1e113c3311332dull, - 0x7b7bcbf646cb463dull, 0xa8a8fc4b1ffc1fb7ull, 0x6d6dd6da61d6610cull, 0x2c2c3a584e3a4e62ull - } -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/jh_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/jh_constants.hpp deleted file mode 100644 index 9d8d563..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/jh_constants.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_JH_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_JH_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct jh_constants -{ - static const uint64_t C[168]; - -}; - -template -const uint64_t jh_constants::C[168] = { - 0x67f815dfa2ded572ull, 0x571523b70a15847bull, 0xf6875a4d90d6ab81ull, 0x402bd1c3c54f9f4eull, - 0x9cfa455ce03a98eaull, 0x9a99b26699d2c503ull, 0x8a53bbf2b4960266ull, 0x31a2db881a1456b5ull, - 0xdb0e199a5c5aa303ull, 0x1044c1870ab23f40ull, 0x1d959e848019051cull, 0xdccde75eadeb336full, - 0x416bbf029213ba10ull, 0xd027bbf7156578dcull, 0x5078aa3739812c0aull, 0xd3910041d2bf1a3full, - 0x907eccf60d5a2d42ull, 0xce97c0929c9f62ddull, 0xac442bc70ba75c18ull, 0x23fcc663d665dfd1ull, - 0x1ab8e09e036c6e97ull, 0xa8ec6c447e450521ull, 0xfa618e5dbb03f1eeull, 0x97818394b29796fdull, - 0x2f3003db37858e4aull, 0x956a9ffb2d8d672aull, 0x6c69b8f88173fe8aull, 0x14427fc04672c78aull, - 0xc45ec7bd8f15f4c5ull, 0x80bb118fa76f4475ull, 0xbc88e4aeb775de52ull, 0xf4a3a6981e00b882ull, - 0x1563a3a9338ff48eull, 0x89f9b7d524565faaull, 0xfde05a7c20edf1b6ull, 0x362c42065ae9ca36ull, - 0x3d98fe4e433529ceull, 0xa74b9a7374f93a53ull, 0x86814e6f591ff5d0ull, 0x9f5ad8af81ad9d0eull, - 0x6a6234ee670605a7ull, 0x2717b96ebe280b8bull, 0x3f1080c626077447ull, 0x7b487ec66f7ea0e0ull, - 0xc0a4f84aa50a550dull, 0x9ef18e979fe7e391ull, 0xd48d605081727686ull, 0x62b0e5f3415a9e7eull, - 0x7a205440ec1f9ffcull, 0x84c9f4ce001ae4e3ull, 0xd895fa9df594d74full, 0xa554c324117e2e55ull, - 0x286efebd2872df5bull, 0xb2c4a50fe27ff578ull, 0x2ed349eeef7c8905ull, 0x7f5928eb85937e44ull, - 0x4a3124b337695f70ull, 0x65e4d61df128865eull, 0xe720b95104771bc7ull, 0x8a87d423e843fe74ull, - 0xf2947692a3e8297dull, 0xc1d9309b097acbddull, 0xe01bdc5bfb301b1dull, 0xbf829cf24f4924daull, - 0xffbf70b431bae7a4ull, 0x48bcf8de0544320dull, 0x39d3bb5332fcae3bull, 0xa08b29e0c1c39f45ull, - 0x0f09aef7fd05c9e5ull, 0x34f1904212347094ull, 0x95ed44e301b771a2ull, 0x4a982f4f368e3be9ull, - 0x15f66ca0631d4088ull, 0xffaf52874b44c147ull, 0x30c60ae2f14abb7eull, 0xe68c6eccc5b67046ull, - 0x00ca4fbd56a4d5a4ull, 0xae183ec84b849ddaull, 0xadd1643045ce5773ull, 0x67255c1468cea6e8ull, - 0x16e10ecbf28cdaa3ull, 0x9a99949a5806e933ull, 0x7b846fc220b2601full, 0x1885d1a07facced1ull, - 0xd319dd8da15b5932ull, 0x46b4a5aac01c9a50ull, 0xba6b04e467633d9full, 0x7eee560bab19caf6ull, - 0x742128a9ea79b11full, 0xee51363b35f7bde9ull, 0x76d350755aac571dull, 0x01707da3fec2463aull, - 0x42d8a498afc135f7ull, 0x79676b9e20eced78ull, 0xa8db3aea15638341ull, 0x832c83324d3bc3faull, - 0xf347271c1f3b40a7ull, 0x9a762db734f04059ull, 0xfd4f21d26c4e3ee7ull, 0xef5957dc398dfdb8ull, - 0xdaeb492b490c9b8dull, 0x0d70f36849d7a25bull, 0x84558d7ad0ae3b7dull, 0x658ef8e4f0e9a5f5ull, - 0x533b1036f4a2b8a0ull, 0x5aec3e759e07a80cull, 0x4f88e85692946891ull, 0x4cbcbaf8555cb05bull, - 0x7b9487f3993bbbe3ull, 0x5d1c6b72d6f4da75ull, 0x6db334dc28acae64ull, 0x71db28b850a5346cull, - 0x2a518d10f2e261f8ull, 0xfc75dd593364dbe3ull, 0xa23fce43f1bcac1cull, 0xb043e8023cd1bb67ull, - 0x75a12988ca5b0a33ull, 0x5c5316b44d19347full, 0x1e4d790ec3943b92ull, 0x3fafeeb6d7757479ull, - 0x21391abef7d4a8eaull, 0x5127234c097ef45cull, 0xd23c32ba5324a326ull, 0xadd5a66d4a17a344ull, - 0x08c9f2afa63e1db5ull, 0x563c6b91983d5983ull, 0x4d608672a17cf84cull, 0xf6c76e08cc3ee246ull, - 0x5e76bcb1b333982full, 0x2ae6c4efa566d62bull, 0x36d4c1bee8b6f406ull, 0x6321efbc1582ee74ull, - 0x69c953f40d4ec1fdull, 0x26585806c45a7da7ull, 0x16fae0061614c17eull, 0x3f9d63283daf907eull, - 0x0cd29b00e3f2c9d2ull, 0x300cd4b730ceaa5full, 0x9832e0f216512a74ull, 0x9af8cee3d830eb0dull, - 0x9279f1b57b9ec54bull, 0xd36886046ee651ffull, 0x316796e6574d239bull, 0x05750a17f3a6e6ccull, - 0xce6c3213d98176b1ull, 0x62a205f88452173cull, 0x47154778b3cb2bf4ull, 0x486a9323825446ffull, - 0x65655e4e0758df38ull, 0x8e5086fc897cfcf2ull, 0x86ca0bd0442e7031ull, 0x4e477830a20940f0ull, - 0x8338f7d139eea065ull, 0xbd3a2ce437e95ef7ull, 0x6ff8130126b29721ull, 0xe7de9fefd1ed44a3ull, - 0xd992257615dfa08bull, 0xbe42dc12f6f7853cull, 0x7eb027ab7ceca7d8ull, 0xdea83eaada7d8d53ull, - 0xd86902bd93ce25aaull, 0xf908731afd43f65aull, 0xa5194a17daef5fc0ull, 0x6a21fd4c33664d97ull, - 0x701541db3198b435ull, 0x9b54cdedbb0f1eeaull, 0x72409751a163d09aull, 0xe26f4791bf9d75f6ull -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/kupyna_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/kupyna_constants.hpp deleted file mode 100644 index e16b06b..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/kupyna_constants.hpp +++ /dev/null @@ -1,557 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_KUPYNA_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_KUPYNA_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct kupyna_constants -{ - static const uint64_t T[8][256]; - -}; - -template -const uint64_t kupyna_constants::T[8][256] = { - { - 0xa832a829d77f9aa8ull, 0x4352432297d41143ull, 0x5f3e5fc2df80615full, 0x061e063014121806ull, - 0x6bda6b7f670cb16bull, 0x75bc758f2356c975ull, 0x6cc16c477519ad6cull, 0x592059f2cb927959ull, - 0x71a871af3b4ad971ull, 0xdf84dfb6f8275bdfull, 0x87a1874c35b22687ull, 0x95fb95dc59cc6e95ull, - 0x174b17b872655c17ull, 0xf017f0d31aeae7f0ull, 0xd89fd88eea3247d8ull, 0x092d0948363f2409ull, - 0x6dc46d4f731ea96dull, 0xf318f3cb10e3ebf3ull, 0x1d691de84e53741dull, 0xcbc0cb16804b0bcbull, - 0xc9cac9068c4503c9ull, 0x4d644d52b3fe294dull, 0x2c9c2c7de8c4b02cull, 0xaf29af11c56a86afull, - 0x798079ef0b72f979ull, 0xe047e0537a9aa7e0ull, 0x97f197cc55c26697ull, 0xfd2efdbb34c9d3fdull, - 0x6fce6f5f7f10a16full, 0x4b7a4b62a7ec314bull, 0x454c451283c60945ull, 0x39dd39d596afe439ull, - 0x3ec63eed84baf83eull, 0xdd8edda6f42953ddull, 0xa315a371ed4eb6a3ull, 0x4f6e4f42bff0214full, - 0xb45eb4c99f2beab4ull, 0xb654b6d99325e2b6ull, 0x9ac89aa47be1529aull, 0x0e360e70242a380eull, - 0x1f631ff8425d7c1full, 0xbf79bf91a51ac6bfull, 0x154115a87e6b5415ull, 0xe142e15b7c9da3e1ull, - 0x49704972abe23949ull, 0xd2bdd2ded6046fd2ull, 0x93e593ec4dde7693ull, 0xc6f9c67eae683fc6ull, - 0x92e092e44bd97292ull, 0x72a772b73143d572ull, 0x9edc9e8463fd429eull, 0x61f8612f5b3a9961ull, - 0xd1b2d1c6dc0d63d1ull, 0x63f2633f57349163ull, 0xfa35fa8326dccffaull, 0xee71ee235eb09feeull, - 0xf403f4f302f6f7f4ull, 0x197d19c8564f6419ull, 0xd5a6d5e6c41173d5ull, 0xad23ad01c9648eadull, - 0x582558facd957d58ull, 0xa40ea449ff5baaa4ull, 0xbb6dbbb1bd06d6bbull, 0xa11fa161e140bea1ull, - 0xdc8bdcaef22e57dcull, 0xf21df2c316e4eff2ull, 0x83b5836c2dae3683ull, 0x37eb37a5b285dc37ull, - 0x4257422a91d31542ull, 0xe453e4736286b7e4ull, 0x7a8f7af7017bf57aull, 0x32fa328dac9ec832ull, - 0x9cd69c946ff34a9cull, 0xccdbcc2e925e17ccull, 0xab3dab31dd7696abull, 0x4a7f4a6aa1eb354aull, - 0x8f898f0c058a068full, 0x6ecb6e577917a56eull, 0x04140420181c1004ull, 0x27bb2725d2f59c27ull, - 0x2e962e6de4cab82eull, 0xe75ce76b688fbbe7ull, 0xe24de2437694afe2ull, 0x5a2f5aeac19b755aull, - 0x96f496c453c56296ull, 0x164e16b074625816ull, 0x23af2305cae98c23ull, 0x2b872b45fad1ac2bull, - 0xc2edc25eb6742fc2ull, 0x65ec650f43268965ull, 0x66e36617492f8566ull, 0x0f330f78222d3c0full, - 0xbc76bc89af13cabcull, 0xa937a921d1789ea9ull, 0x474647028fc80147ull, 0x415841329bda1941ull, - 0x34e434bdb88cd034ull, 0x4875487aade53d48ull, 0xfc2bfcb332ced7fcull, 0xb751b7d19522e6b7ull, - 0x6adf6a77610bb56aull, 0x88928834179f1a88ull, 0xa50ba541f95caea5ull, 0x530253a2f7a45153ull, - 0x86a4864433b52286ull, 0xf93af99b2cd5c3f9ull, 0x5b2a5be2c79c715bull, 0xdb90db96e03b4bdbull, - 0x38d838dd90a8e038ull, 0x7b8a7bff077cf17bull, 0xc3e8c356b0732bc3ull, 0x1e661ef0445a781eull, - 0x22aa220dccee8822ull, 0x33ff3385aa99cc33ull, 0x24b4243dd8fc9024ull, 0x2888285df0d8a028ull, - 0x36ee36adb482d836ull, 0xc7fcc776a86f3bc7ull, 0xb240b2f98b39f2b2ull, 0x3bd73bc59aa1ec3bull, - 0x8e8c8e04038d028eull, 0x77b6779f2f58c177ull, 0xba68bab9bb01d2baull, 0xf506f5fb04f1f3f5ull, - 0x144414a0786c5014ull, 0x9fd99f8c65fa469full, 0x0828084030382008ull, 0x551c5592e3b64955ull, - 0x9bcd9bac7de6569bull, 0x4c614c5ab5f92d4cull, 0xfe21fea33ec0dffeull, 0x60fd60275d3d9d60ull, - 0x5c315cdad5896d5cull, 0xda95da9ee63c4fdaull, 0x187818c050486018ull, 0x4643460a89cf0546ull, - 0xcddecd26945913cdull, 0x7d947dcf136ee97dull, 0x21a52115c6e78421ull, 0xb04ab0e98737fab0ull, - 0x3fc33fe582bdfc3full, 0x1b771bd85a416c1bull, 0x8997893c11981e89ull, 0xff24ffab38c7dbffull, - 0xeb60eb0b40ab8bebull, 0x84ae84543fbb2a84ull, 0x69d0696f6b02b969ull, 0x3ad23acd9ca6e83aull, - 0x9dd39d9c69f44e9dull, 0xd7acd7f6c81f7bd7ull, 0xd3b8d3d6d0036bd3ull, 0x70ad70a73d4ddd70ull, - 0x67e6671f4f288167ull, 0x405d403a9ddd1d40ull, 0xb55bb5c1992ceeb5ull, 0xde81debefe205fdeull, - 0x5d345dd2d38e695dull, 0x30f0309da090c030ull, 0x91ef91fc41d07e91ull, 0xb14fb1e18130feb1ull, - 0x788578e70d75fd78ull, 0x1155118866774411ull, 0x0105010806070401ull, 0xe556e57b6481b3e5ull, - 0x0000000000000000ull, 0x68d568676d05bd68ull, 0x98c298b477ef5a98ull, 0xa01aa069e747baa0ull, - 0xc5f6c566a46133c5ull, 0x020a02100c0e0802ull, 0xa604a659f355a2a6ull, 0x74b974872551cd74ull, - 0x2d992d75eec3b42dull, 0x0b270b583a312c0bull, 0xa210a279eb49b2a2ull, 0x76b37697295fc576ull, - 0xb345b3f18d3ef6b3ull, 0xbe7cbe99a31dc2beull, 0xced1ce3e9e501fceull, 0xbd73bd81a914cebdull, - 0xae2cae19c36d82aeull, 0xe96ae91b4ca583e9ull, 0x8a988a241b91128aull, 0x31f53195a697c431ull, - 0x1c6c1ce04854701cull, 0xec7bec3352be97ecull, 0xf112f1db1cede3f1ull, 0x99c799bc71e85e99ull, - 0x94fe94d45fcb6a94ull, 0xaa38aa39db7192aaull, 0xf609f6e30ef8fff6ull, 0x26be262dd4f29826ull, - 0x2f932f65e2cdbc2full, 0xef74ef2b58b79befull, 0xe86fe8134aa287e8ull, 0x8c868c140f830a8cull, - 0x35e135b5be8bd435ull, 0x030f03180a090c03ull, 0xd4a3d4eec21677d4ull, 0x7f9e7fdf1f60e17full, - 0xfb30fb8b20dbcbfbull, 0x051105281e1b1405ull, 0xc1e2c146bc7d23c1ull, 0x5e3b5ecad987655eull, - 0x90ea90f447d77a90ull, 0x20a0201dc0e08020ull, 0x3dc93df58eb3f43dull, 0x82b082642ba93282ull, - 0xf70cf7eb08fffbf7ull, 0xea65ea0346ac8feaull, 0x0a220a503c36280aull, 0x0d390d682e23340dull, - 0x7e9b7ed71967e57eull, 0xf83ff8932ad2c7f8ull, 0x500d50bafdad5d50ull, 0x1a721ad05c46681aull, - 0xc4f3c46ea26637c4ull, 0x071b073812151c07ull, 0x57165782efb84157ull, 0xb862b8a9b70fdab8ull, - 0x3ccc3cfd88b4f03cull, 0x62f7623751339562ull, 0xe348e34b7093abe3ull, 0xc8cfc80e8a4207c8ull, - 0xac26ac09cf638aacull, 0x520752aaf1a35552ull, 0x64e9640745218d64ull, 0x1050108060704010ull, - 0xd0b7d0ceda0a67d0ull, 0xd99ad986ec3543d9ull, 0x135f13986a794c13ull, 0x0c3c0c602824300cull, - 0x125a12906c7e4812ull, 0x298d2955f6dfa429ull, 0x510851b2fbaa5951ull, 0xb967b9a1b108deb9ull, - 0xcfd4cf3698571bcfull, 0xd6a9d6fece187fd6ull, 0x73a273bf3744d173ull, 0x8d838d1c09840e8dull, - 0x81bf817c21a03e81ull, 0x5419549ae5b14d54ull, 0xc0e7c04eba7a27c0ull, 0xed7eed3b54b993edull, - 0x4e6b4e4ab9f7254eull, 0x4449441a85c10d44ull, 0xa701a751f552a6a7ull, 0x2a822a4dfcd6a82aull, - 0x85ab855c39bc2e85ull, 0x25b12535defb9425ull, 0xe659e6636e88bfe6ull, 0xcac5ca1e864c0fcaull, - 0x7c917cc71569ed7cull, 0x8b9d8b2c1d96168bull, 0x5613568ae9bf4556ull, 0x80ba807427a73a80ull - }, - { - 0xd1ce3e9e501fceceull, 0x6dbbb1bd06d6bbbbull, 0x60eb0b40ab8bebebull, 0xe092e44bd9729292ull, - 0x65ea0346ac8feaeaull, 0xc0cb16804b0bcbcbull, 0x5f13986a794c1313ull, 0xe2c146bc7d23c1c1ull, - 0x6ae91b4ca583e9e9ull, 0xd23acd9ca6e83a3aull, 0xa9d6fece187fd6d6ull, 0x40b2f98b39f2b2b2ull, - 0xbdd2ded6046fd2d2ull, 0xea90f447d77a9090ull, 0x4b17b872655c1717ull, 0x3ff8932ad2c7f8f8ull, - 0x57422a91d3154242ull, 0x4115a87e6b541515ull, 0x13568ae9bf455656ull, 0x5eb4c99f2beab4b4ull, - 0xec650f4326896565ull, 0x6c1ce04854701c1cull, 0x928834179f1a8888ull, 0x52432297d4114343ull, - 0xf6c566a46133c5c5ull, 0x315cdad5896d5c5cull, 0xee36adb482d83636ull, 0x68bab9bb01d2babaull, - 0x06f5fb04f1f3f5f5ull, 0x165782efb8415757ull, 0xe6671f4f28816767ull, 0x838d1c09840e8d8dull, - 0xf53195a697c43131ull, 0x09f6e30ef8fff6f6ull, 0xe9640745218d6464ull, 0x2558facd957d5858ull, - 0xdc9e8463fd429e9eull, 0x03f4f302f6f7f4f4ull, 0xaa220dccee882222ull, 0x38aa39db7192aaaaull, - 0xbc758f2356c97575ull, 0x330f78222d3c0f0full, 0x0a02100c0e080202ull, 0x4fb1e18130feb1b1ull, - 0x84dfb6f8275bdfdfull, 0xc46d4f731ea96d6dull, 0xa273bf3744d17373ull, 0x644d52b3fe294d4dull, - 0x917cc71569ed7c7cull, 0xbe262dd4f2982626ull, 0x962e6de4cab82e2eull, 0x0cf7eb08fffbf7f7ull, - 0x2808403038200808ull, 0x345dd2d38e695d5dull, 0x49441a85c10d4444ull, 0xc63eed84baf83e3eull, - 0xd99f8c65fa469f9full, 0x4414a0786c501414ull, 0xcfc80e8a4207c8c8ull, 0x2cae19c36d82aeaeull, - 0x19549ae5b14d5454ull, 0x5010806070401010ull, 0x9fd88eea3247d8d8ull, 0x76bc89af13cabcbcull, - 0x721ad05c46681a1aull, 0xda6b7f670cb16b6bull, 0xd0696f6b02b96969ull, 0x18f3cb10e3ebf3f3ull, - 0x73bd81a914cebdbdull, 0xff3385aa99cc3333ull, 0x3dab31dd7696ababull, 0x35fa8326dccffafaull, - 0xb2d1c6dc0d63d1d1ull, 0xcd9bac7de6569b9bull, 0xd568676d05bd6868ull, 0x6b4e4ab9f7254e4eull, - 0x4e16b07462581616ull, 0xfb95dc59cc6e9595ull, 0xef91fc41d07e9191ull, 0x71ee235eb09feeeeull, - 0x614c5ab5f92d4c4cull, 0xf2633f5734916363ull, 0x8c8e04038d028e8eull, 0x2a5be2c79c715b5bull, - 0xdbcc2e925e17ccccull, 0xcc3cfd88b4f03c3cull, 0x7d19c8564f641919ull, 0x1fa161e140bea1a1ull, - 0xbf817c21a03e8181ull, 0x704972abe2394949ull, 0x8a7bff077cf17b7bull, 0x9ad986ec3543d9d9ull, - 0xce6f5f7f10a16f6full, 0xeb37a5b285dc3737ull, 0xfd60275d3d9d6060ull, 0xc5ca1e864c0fcacaull, - 0x5ce76b688fbbe7e7ull, 0x872b45fad1ac2b2bull, 0x75487aade53d4848ull, 0x2efdbb34c9d3fdfdull, - 0xf496c453c5629696ull, 0x4c451283c6094545ull, 0x2bfcb332ced7fcfcull, 0x5841329bda194141ull, - 0x5a12906c7e481212ull, 0x390d682e23340d0dull, 0x8079ef0b72f97979ull, 0x56e57b6481b3e5e5ull, - 0x97893c11981e8989ull, 0x868c140f830a8c8cull, 0x48e34b7093abe3e3ull, 0xa0201dc0e0802020ull, - 0xf0309da090c03030ull, 0x8bdcaef22e57dcdcull, 0x51b7d19522e6b7b7ull, 0xc16c477519ad6c6cull, - 0x7f4a6aa1eb354a4aull, 0x5bb5c1992ceeb5b5ull, 0xc33fe582bdfc3f3full, 0xf197cc55c2669797ull, - 0xa3d4eec21677d4d4ull, 0xf762375133956262ull, 0x992d75eec3b42d2dull, 0x1e06301412180606ull, - 0x0ea449ff5baaa4a4ull, 0x0ba541f95caea5a5ull, 0xb5836c2dae368383ull, 0x3e5fc2df80615f5full, - 0x822a4dfcd6a82a2aull, 0x95da9ee63c4fdadaull, 0xcac9068c4503c9c9ull, 0x0000000000000000ull, - 0x9b7ed71967e57e7eull, 0x10a279eb49b2a2a2ull, 0x1c5592e3b6495555ull, 0x79bf91a51ac6bfbfull, - 0x5511886677441111ull, 0xa6d5e6c41173d5d5ull, 0xd69c946ff34a9c9cull, 0xd4cf3698571bcfcfull, - 0x360e70242a380e0eull, 0x220a503c36280a0aull, 0xc93df58eb3f43d3dull, 0x0851b2fbaa595151ull, - 0x947dcf136ee97d7dull, 0xe593ec4dde769393ull, 0x771bd85a416c1b1bull, 0x21fea33ec0dffefeull, - 0xf3c46ea26637c4c4ull, 0x4647028fc8014747ull, 0x2d0948363f240909ull, 0xa4864433b5228686ull, - 0x270b583a312c0b0bull, 0x898f0c058a068f8full, 0xd39d9c69f44e9d9dull, 0xdf6a77610bb56a6aull, - 0x1b073812151c0707ull, 0x67b9a1b108deb9b9ull, 0x4ab0e98737fab0b0ull, 0xc298b477ef5a9898ull, - 0x7818c05048601818ull, 0xfa328dac9ec83232ull, 0xa871af3b4ad97171ull, 0x7a4b62a7ec314b4bull, - 0x74ef2b58b79befefull, 0xd73bc59aa1ec3b3bull, 0xad70a73d4ddd7070ull, 0x1aa069e747baa0a0ull, - 0x53e4736286b7e4e4ull, 0x5d403a9ddd1d4040ull, 0x24ffab38c7dbffffull, 0xe8c356b0732bc3c3ull, - 0x37a921d1789ea9a9ull, 0x59e6636e88bfe6e6ull, 0x8578e70d75fd7878ull, 0x3af99b2cd5c3f9f9ull, - 0x9d8b2c1d96168b8bull, 0x43460a89cf054646ull, 0xba807427a73a8080ull, 0x661ef0445a781e1eull, - 0xd838dd90a8e03838ull, 0x42e15b7c9da3e1e1ull, 0x62b8a9b70fdab8b8ull, 0x32a829d77f9aa8a8ull, - 0x47e0537a9aa7e0e0ull, 0x3c0c602824300c0cull, 0xaf2305cae98c2323ull, 0xb37697295fc57676ull, - 0x691de84e53741d1dull, 0xb12535defb942525ull, 0xb4243dd8fc902424ull, 0x1105281e1b140505ull, - 0x12f1db1cede3f1f1ull, 0xcb6e577917a56e6eull, 0xfe94d45fcb6a9494ull, 0x88285df0d8a02828ull, - 0xc89aa47be1529a9aull, 0xae84543fbb2a8484ull, 0x6fe8134aa287e8e8ull, 0x15a371ed4eb6a3a3ull, - 0x6e4f42bff0214f4full, 0xb6779f2f58c17777ull, 0xb8d3d6d0036bd3d3ull, 0xab855c39bc2e8585ull, - 0x4de2437694afe2e2ull, 0x0752aaf1a3555252ull, 0x1df2c316e4eff2f2ull, 0xb082642ba9328282ull, - 0x0d50bafdad5d5050ull, 0x8f7af7017bf57a7aull, 0x932f65e2cdbc2f2full, 0xb974872551cd7474ull, - 0x0253a2f7a4515353ull, 0x45b3f18d3ef6b3b3ull, 0xf8612f5b3a996161ull, 0x29af11c56a86afafull, - 0xdd39d596afe43939ull, 0xe135b5be8bd43535ull, 0x81debefe205fdedeull, 0xdecd26945913cdcdull, - 0x631ff8425d7c1f1full, 0xc799bc71e85e9999ull, 0x26ac09cf638aacacull, 0x23ad01c9648eadadull, - 0xa772b73143d57272ull, 0x9c2c7de8c4b02c2cull, 0x8edda6f42953ddddull, 0xb7d0ceda0a67d0d0ull, - 0xa1874c35b2268787ull, 0x7cbe99a31dc2bebeull, 0x3b5ecad987655e5eull, 0x04a659f355a2a6a6ull, - 0x7bec3352be97ececull, 0x140420181c100404ull, 0xf9c67eae683fc6c6ull, 0x0f03180a090c0303ull, - 0xe434bdb88cd03434ull, 0x30fb8b20dbcbfbfbull, 0x90db96e03b4bdbdbull, 0x2059f2cb92795959ull, - 0x54b6d99325e2b6b6ull, 0xedc25eb6742fc2c2ull, 0x0501080607040101ull, 0x17f0d31aeae7f0f0ull, - 0x2f5aeac19b755a5aull, 0x7eed3b54b993ededull, 0x01a751f552a6a7a7ull, 0xe36617492f856666ull, - 0xa52115c6e7842121ull, 0x9e7fdf1f60e17f7full, 0x988a241b91128a8aull, 0xbb2725d2f59c2727ull, - 0xfcc776a86f3bc7c7ull, 0xe7c04eba7a27c0c0ull, 0x8d2955f6dfa42929ull, 0xacd7f6c81f7bd7d7ull - }, - { - 0x93ec4dde769393e5ull, 0xd986ec3543d9d99aull, 0x9aa47be1529a9ac8ull, 0xb5c1992ceeb5b55bull, - 0x98b477ef5a9898c2ull, 0x220dccee882222aaull, 0x451283c60945454cull, 0xfcb332ced7fcfc2bull, - 0xbab9bb01d2baba68ull, 0x6a77610bb56a6adfull, 0xdfb6f8275bdfdf84ull, 0x02100c0e0802020aull, - 0x9f8c65fa469f9fd9ull, 0xdcaef22e57dcdc8bull, 0x51b2fbaa59515108ull, 0x59f2cb9279595920ull, - 0x4a6aa1eb354a4a7full, 0x17b872655c17174bull, 0x2b45fad1ac2b2b87ull, 0xc25eb6742fc2c2edull, - 0x94d45fcb6a9494feull, 0xf4f302f6f7f4f403ull, 0xbbb1bd06d6bbbb6dull, 0xa371ed4eb6a3a315ull, - 0x62375133956262f7ull, 0xe4736286b7e4e453ull, 0x71af3b4ad97171a8ull, 0xd4eec21677d4d4a3ull, - 0xcd26945913cdcddeull, 0x70a73d4ddd7070adull, 0x16b074625816164eull, 0xe15b7c9da3e1e142ull, - 0x4972abe239494970ull, 0x3cfd88b4f03c3cccull, 0xc04eba7a27c0c0e7ull, 0xd88eea3247d8d89full, - 0x5cdad5896d5c5c31ull, 0x9bac7de6569b9bcdull, 0xad01c9648eadad23ull, 0x855c39bc2e8585abull, - 0x53a2f7a451535302ull, 0xa161e140bea1a11full, 0x7af7017bf57a7a8full, 0xc80e8a4207c8c8cfull, - 0x2d75eec3b42d2d99ull, 0xe0537a9aa7e0e047ull, 0xd1c6dc0d63d1d1b2ull, 0x72b73143d57272a7ull, - 0xa659f355a2a6a604ull, 0x2c7de8c4b02c2c9cull, 0xc46ea26637c4c4f3ull, 0xe34b7093abe3e348ull, - 0x7697295fc57676b3ull, 0x78e70d75fd787885ull, 0xb7d19522e6b7b751ull, 0xb4c99f2beab4b45eull, - 0x0948363f2409092dull, 0x3bc59aa1ec3b3bd7ull, 0x0e70242a380e0e36ull, 0x41329bda19414158ull, - 0x4c5ab5f92d4c4c61ull, 0xdebefe205fdede81ull, 0xb2f98b39f2b2b240ull, 0x90f447d77a9090eaull, - 0x2535defb942525b1ull, 0xa541f95caea5a50bull, 0xd7f6c81f7bd7d7acull, 0x03180a090c03030full, - 0x1188667744111155ull, 0x0000000000000000ull, 0xc356b0732bc3c3e8ull, 0x2e6de4cab82e2e96ull, - 0x92e44bd9729292e0ull, 0xef2b58b79befef74ull, 0x4e4ab9f7254e4e6bull, 0x12906c7e4812125aull, - 0x9d9c69f44e9d9dd3ull, 0x7dcf136ee97d7d94ull, 0xcb16804b0bcbcbc0ull, 0x35b5be8bd43535e1ull, - 0x1080607040101050ull, 0xd5e6c41173d5d5a6ull, 0x4f42bff0214f4f6eull, 0x9e8463fd429e9edcull, - 0x4d52b3fe294d4d64ull, 0xa921d1789ea9a937ull, 0x5592e3b64955551cull, 0xc67eae683fc6c6f9ull, - 0xd0ceda0a67d0d0b7ull, 0x7bff077cf17b7b8aull, 0x18c0504860181878ull, 0x97cc55c2669797f1ull, - 0xd3d6d0036bd3d3b8ull, 0x36adb482d83636eeull, 0xe6636e88bfe6e659ull, 0x487aade53d484875ull, - 0x568ae9bf45565613ull, 0x817c21a03e8181bfull, 0x8f0c058a068f8f89ull, 0x779f2f58c17777b6ull, - 0xcc2e925e17ccccdbull, 0x9c946ff34a9c9cd6ull, 0xb9a1b108deb9b967ull, 0xe2437694afe2e24dull, - 0xac09cf638aacac26ull, 0xb8a9b70fdab8b862ull, 0x2f65e2cdbc2f2f93ull, 0x15a87e6b54151541ull, - 0xa449ff5baaa4a40eull, 0x7cc71569ed7c7c91ull, 0xda9ee63c4fdada95ull, 0x38dd90a8e03838d8ull, - 0x1ef0445a781e1e66ull, 0x0b583a312c0b0b27ull, 0x05281e1b14050511ull, 0xd6fece187fd6d6a9ull, - 0x14a0786c50141444ull, 0x6e577917a56e6ecbull, 0x6c477519ad6c6cc1ull, 0x7ed71967e57e7e9bull, - 0x6617492f856666e3ull, 0xfdbb34c9d3fdfd2eull, 0xb1e18130feb1b14full, 0xe57b6481b3e5e556ull, - 0x60275d3d9d6060fdull, 0xaf11c56a86afaf29ull, 0x5ecad987655e5e3bull, 0x3385aa99cc3333ffull, - 0x874c35b2268787a1ull, 0xc9068c4503c9c9caull, 0xf0d31aeae7f0f017ull, 0x5dd2d38e695d5d34ull, - 0x6d4f731ea96d6dc4ull, 0x3fe582bdfc3f3fc3ull, 0x8834179f1a888892ull, 0x8d1c09840e8d8d83ull, - 0xc776a86f3bc7c7fcull, 0xf7eb08fffbf7f70cull, 0x1de84e53741d1d69ull, 0xe91b4ca583e9e96aull, - 0xec3352be97ecec7bull, 0xed3b54b993eded7eull, 0x807427a73a8080baull, 0x2955f6dfa429298dull, - 0x2725d2f59c2727bbull, 0xcf3698571bcfcfd4ull, 0x99bc71e85e9999c7ull, 0xa829d77f9aa8a832ull, - 0x50bafdad5d50500dull, 0x0f78222d3c0f0f33ull, 0x37a5b285dc3737ebull, 0x243dd8fc902424b4ull, - 0x285df0d8a0282888ull, 0x309da090c03030f0ull, 0x95dc59cc6e9595fbull, 0xd2ded6046fd2d2bdull, - 0x3eed84baf83e3ec6ull, 0x5be2c79c715b5b2aull, 0x403a9ddd1d40405dull, 0x836c2dae368383b5ull, - 0xb3f18d3ef6b3b345ull, 0x696f6b02b96969d0ull, 0x5782efb841575716ull, 0x1ff8425d7c1f1f63ull, - 0x073812151c07071bull, 0x1ce04854701c1c6cull, 0x8a241b91128a8a98ull, 0xbc89af13cabcbc76ull, - 0x201dc0e0802020a0ull, 0xeb0b40ab8bebeb60ull, 0xce3e9e501fceced1ull, 0x8e04038d028e8e8cull, - 0xab31dd7696abab3dull, 0xee235eb09feeee71ull, 0x3195a697c43131f5ull, 0xa279eb49b2a2a210ull, - 0x73bf3744d17373a2ull, 0xf99b2cd5c3f9f93aull, 0xca1e864c0fcacac5ull, 0x3acd9ca6e83a3ad2ull, - 0x1ad05c46681a1a72ull, 0xfb8b20dbcbfbfb30ull, 0x0d682e23340d0d39ull, 0xc146bc7d23c1c1e2ull, - 0xfea33ec0dffefe21ull, 0xfa8326dccffafa35ull, 0xf2c316e4eff2f21dull, 0x6f5f7f10a16f6fceull, - 0xbd81a914cebdbd73ull, 0x96c453c5629696f4ull, 0xdda6f42953dddd8eull, 0x432297d411434352ull, - 0x52aaf1a355525207ull, 0xb6d99325e2b6b654ull, 0x0840303820080828ull, 0xf3cb10e3ebf3f318ull, - 0xae19c36d82aeae2cull, 0xbe99a31dc2bebe7cull, 0x19c8564f6419197dull, 0x893c11981e898997ull, - 0x328dac9ec83232faull, 0x262dd4f2982626beull, 0xb0e98737fab0b04aull, 0xea0346ac8feaea65ull, - 0x4b62a7ec314b4b7aull, 0x640745218d6464e9ull, 0x84543fbb2a8484aeull, 0x82642ba9328282b0ull, - 0x6b7f670cb16b6bdaull, 0xf5fb04f1f3f5f506ull, 0x79ef0b72f9797980ull, 0xbf91a51ac6bfbf79ull, - 0x0108060704010105ull, 0x5fc2df80615f5f3eull, 0x758f2356c97575bcull, 0x633f5734916363f2ull, - 0x1bd85a416c1b1b77ull, 0x2305cae98c2323afull, 0x3df58eb3f43d3dc9ull, 0x68676d05bd6868d5ull, - 0x2a4dfcd6a82a2a82ull, 0x650f4326896565ecull, 0xe8134aa287e8e86full, 0x91fc41d07e9191efull, - 0xf6e30ef8fff6f609ull, 0xffab38c7dbffff24ull, 0x13986a794c13135full, 0x58facd957d585825ull, - 0xf1db1cede3f1f112ull, 0x47028fc801474746ull, 0x0a503c36280a0a22ull, 0x7fdf1f60e17f7f9eull, - 0xc566a46133c5c5f6ull, 0xa751f552a6a7a701ull, 0xe76b688fbbe7e75cull, 0x612f5b3a996161f8ull, - 0x5aeac19b755a5a2full, 0x063014121806061eull, 0x460a89cf05464643ull, 0x441a85c10d444449ull, - 0x422a91d315424257ull, 0x0420181c10040414ull, 0xa069e747baa0a01aull, 0xdb96e03b4bdbdb90ull, - 0x39d596afe43939ddull, 0x864433b5228686a4ull, 0x549ae5b14d545419ull, 0xaa39db7192aaaa38ull, - 0x8c140f830a8c8c86ull, 0x34bdb88cd03434e4ull, 0x2115c6e7842121a5ull, 0x8b2c1d96168b8b9dull, - 0xf8932ad2c7f8f83full, 0x0c602824300c0c3cull, 0x74872551cd7474b9ull, 0x671f4f28816767e6ull - }, - { - 0x676d05bd6868d568ull, 0x1c09840e8d8d838dull, 0x1e864c0fcacac5caull, 0x52b3fe294d4d644dull, - 0xbf3744d17373a273ull, 0x62a7ec314b4b7a4bull, 0x4ab9f7254e4e6b4eull, 0x4dfcd6a82a2a822aull, - 0xeec21677d4d4a3d4ull, 0xaaf1a35552520752ull, 0x2dd4f2982626be26ull, 0xf18d3ef6b3b345b3ull, - 0x9ae5b14d54541954ull, 0xf0445a781e1e661eull, 0xc8564f6419197d19ull, 0xf8425d7c1f1f631full, - 0x0dccee882222aa22ull, 0x180a090c03030f03ull, 0x0a89cf0546464346ull, 0xf58eb3f43d3dc93dull, - 0x75eec3b42d2d992dull, 0x6aa1eb354a4a7f4aull, 0xa2f7a45153530253ull, 0x6c2dae368383b583ull, - 0x986a794c13135f13ull, 0x241b91128a8a988aull, 0xd19522e6b7b751b7ull, 0xe6c41173d5d5a6d5ull, - 0x35defb942525b125ull, 0xef0b72f979798079ull, 0xfb04f1f3f5f506f5ull, 0x81a914cebdbd73bdull, - 0xfacd957d58582558ull, 0x65e2cdbc2f2f932full, 0x682e23340d0d390dull, 0x100c0e0802020a02ull, - 0x3b54b993eded7eedull, 0xb2fbaa5951510851ull, 0x8463fd429e9edc9eull, 0x8866774411115511ull, - 0xc316e4eff2f21df2ull, 0xed84baf83e3ec63eull, 0x92e3b64955551c55ull, 0xcad987655e5e3b5eull, - 0xc6dc0d63d1d1b2d1ull, 0xb074625816164e16ull, 0xfd88b4f03c3ccc3cull, 0x17492f856666e366ull, - 0xa73d4ddd7070ad70ull, 0xd2d38e695d5d345dull, 0xcb10e3ebf3f318f3ull, 0x1283c60945454c45ull, - 0x3a9ddd1d40405d40ull, 0x2e925e17ccccdbccull, 0x134aa287e8e86fe8ull, 0xd45fcb6a9494fe94ull, - 0x8ae9bf4556561356ull, 0x4030382008082808ull, 0x3e9e501fceced1ceull, 0xd05c46681a1a721aull, - 0xcd9ca6e83a3ad23aull, 0xded6046fd2d2bdd2ull, 0x5b7c9da3e1e142e1ull, 0xb6f8275bdfdf84dfull, - 0xc1992ceeb5b55bb5ull, 0xdd90a8e03838d838ull, 0x577917a56e6ecb6eull, 0x70242a380e0e360eull, - 0x7b6481b3e5e556e5ull, 0xf302f6f7f4f403f4ull, 0x9b2cd5c3f9f93af9ull, 0x4433b5228686a486ull, - 0x1b4ca583e9e96ae9ull, 0x42bff0214f4f6e4full, 0xfece187fd6d6a9d6ull, 0x5c39bc2e8585ab85ull, - 0x05cae98c2323af23ull, 0x3698571bcfcfd4cfull, 0x8dac9ec83232fa32ull, 0xbc71e85e9999c799ull, - 0x95a697c43131f531ull, 0xa0786c5014144414ull, 0x19c36d82aeae2caeull, 0x235eb09feeee71eeull, - 0x0e8a4207c8c8cfc8ull, 0x7aade53d48487548ull, 0xd6d0036bd3d3b8d3ull, 0x9da090c03030f030ull, - 0x61e140bea1a11fa1ull, 0xe44bd9729292e092ull, 0x329bda1941415841ull, 0xe18130feb1b14fb1ull, - 0xc050486018187818ull, 0x6ea26637c4c4f3c4ull, 0x7de8c4b02c2c9c2cull, 0xaf3b4ad97171a871ull, - 0xb73143d57272a772ull, 0x1a85c10d44444944ull, 0xa87e6b5415154115ull, 0xbb34c9d3fdfd2efdull, - 0xa5b285dc3737eb37ull, 0x99a31dc2bebe7cbeull, 0xc2df80615f5f3e5full, 0x39db7192aaaa38aaull, - 0xac7de6569b9bcd9bull, 0x34179f1a88889288ull, 0x8eea3247d8d89fd8ull, 0x31dd7696abab3dabull, - 0x3c11981e89899789ull, 0x946ff34a9c9cd69cull, 0x8326dccffafa35faull, 0x275d3d9d6060fd60ull, - 0x0346ac8feaea65eaull, 0x89af13cabcbc76bcull, 0x375133956262f762ull, 0x602824300c0c3c0cull, - 0x3dd8fc902424b424ull, 0x59f355a2a6a604a6ull, 0x29d77f9aa8a832a8ull, 0x3352be97ecec7becull, - 0x1f4f28816767e667ull, 0x1dc0e0802020a020ull, 0x96e03b4bdbdb90dbull, 0xc71569ed7c7c917cull, - 0x5df0d8a028288828ull, 0xa6f42953dddd8eddull, 0x09cf638aacac26acull, 0xe2c79c715b5b2a5bull, - 0xbdb88cd03434e434ull, 0xd71967e57e7e9b7eull, 0x8060704010105010ull, 0xdb1cede3f1f112f1ull, - 0xff077cf17b7b8a7bull, 0x0c058a068f8f898full, 0x3f5734916363f263ull, 0x69e747baa0a01aa0ull, - 0x281e1b1405051105ull, 0xa47be1529a9ac89aull, 0x2297d41143435243ull, 0x9f2f58c17777b677ull, - 0x15c6e7842121a521ull, 0x91a51ac6bfbf79bfull, 0x25d2f59c2727bb27ull, 0x48363f2409092d09ull, - 0x56b0732bc3c3e8c3ull, 0x8c65fa469f9fd99full, 0xd99325e2b6b654b6ull, 0xf6c81f7bd7d7acd7ull, - 0x55f6dfa429298d29ull, 0x5eb6742fc2c2edc2ull, 0x0b40ab8bebeb60ebull, 0x4eba7a27c0c0e7c0ull, - 0x49ff5baaa4a40ea4ull, 0x2c1d96168b8b9d8bull, 0x140f830a8c8c868cull, 0xe84e53741d1d691dull, - 0x8b20dbcbfbfb30fbull, 0xab38c7dbffff24ffull, 0x46bc7d23c1c1e2c1ull, 0xf98b39f2b2b240b2ull, - 0xcc55c2669797f197ull, 0x6de4cab82e2e962eull, 0x932ad2c7f8f83ff8ull, 0x0f4326896565ec65ull, - 0xe30ef8fff6f609f6ull, 0x8f2356c97575bc75ull, 0x3812151c07071b07ull, 0x20181c1004041404ull, - 0x72abe23949497049ull, 0x85aa99cc3333ff33ull, 0x736286b7e4e453e4ull, 0x86ec3543d9d99ad9ull, - 0xa1b108deb9b967b9ull, 0xceda0a67d0d0b7d0ull, 0x2a91d31542425742ull, 0x76a86f3bc7c7fcc7ull, - 0x477519ad6c6cc16cull, 0xf447d77a9090ea90ull, 0x0000000000000000ull, 0x04038d028e8e8c8eull, - 0x5f7f10a16f6fce6full, 0xbafdad5d50500d50ull, 0x0806070401010501ull, 0x66a46133c5c5f6c5ull, - 0x9ee63c4fdada95daull, 0x028fc80147474647ull, 0xe582bdfc3f3fc33full, 0x26945913cdcddecdull, - 0x6f6b02b96969d069ull, 0x79eb49b2a2a210a2ull, 0x437694afe2e24de2ull, 0xf7017bf57a7a8f7aull, - 0x51f552a6a7a701a7ull, 0x7eae683fc6c6f9c6ull, 0xec4dde769393e593ull, 0x78222d3c0f0f330full, - 0x503c36280a0a220aull, 0x3014121806061e06ull, 0x636e88bfe6e659e6ull, 0x45fad1ac2b2b872bull, - 0xc453c5629696f496ull, 0x71ed4eb6a3a315a3ull, 0xe04854701c1c6c1cull, 0x11c56a86afaf29afull, - 0x77610bb56a6adf6aull, 0x906c7e4812125a12ull, 0x543fbb2a8484ae84ull, 0xd596afe43939dd39ull, - 0x6b688fbbe7e75ce7ull, 0xe98737fab0b04ab0ull, 0x642ba9328282b082ull, 0xeb08fffbf7f70cf7ull, - 0xa33ec0dffefe21feull, 0x9c69f44e9d9dd39dull, 0x4c35b2268787a187ull, 0xdad5896d5c5c315cull, - 0x7c21a03e8181bf81ull, 0xb5be8bd43535e135ull, 0xbefe205fdede81deull, 0xc99f2beab4b45eb4ull, - 0x41f95caea5a50ba5ull, 0xb332ced7fcfc2bfcull, 0x7427a73a8080ba80ull, 0x2b58b79befef74efull, - 0x16804b0bcbcbc0cbull, 0xb1bd06d6bbbb6dbbull, 0x7f670cb16b6bda6bull, 0x97295fc57676b376ull, - 0xb9bb01d2baba68baull, 0xeac19b755a5a2f5aull, 0xcf136ee97d7d947dull, 0xe70d75fd78788578ull, - 0x583a312c0b0b270bull, 0xdc59cc6e9595fb95ull, 0x4b7093abe3e348e3ull, 0x01c9648eadad23adull, - 0x872551cd7474b974ull, 0xb477ef5a9898c298ull, 0xc59aa1ec3b3bd73bull, 0xadb482d83636ee36ull, - 0x0745218d6464e964ull, 0x4f731ea96d6dc46dull, 0xaef22e57dcdc8bdcull, 0xd31aeae7f0f017f0ull, - 0xf2cb927959592059ull, 0x21d1789ea9a937a9ull, 0x5ab5f92d4c4c614cull, 0xb872655c17174b17ull, - 0xdf1f60e17f7f9e7full, 0xfc41d07e9191ef91ull, 0xa9b70fdab8b862b8ull, 0x068c4503c9c9cac9ull, - 0x82efb84157571657ull, 0xd85a416c1b1b771bull, 0x537a9aa7e0e047e0ull, 0x2f5b3a996161f861ull - }, - { - 0xd77f9aa8a832a829ull, 0x97d4114343524322ull, 0xdf80615f5f3e5fc2ull, 0x14121806061e0630ull, - 0x670cb16b6bda6b7full, 0x2356c97575bc758full, 0x7519ad6c6cc16c47ull, 0xcb927959592059f2ull, - 0x3b4ad97171a871afull, 0xf8275bdfdf84dfb6ull, 0x35b2268787a1874cull, 0x59cc6e9595fb95dcull, - 0x72655c17174b17b8ull, 0x1aeae7f0f017f0d3ull, 0xea3247d8d89fd88eull, 0x363f2409092d0948ull, - 0x731ea96d6dc46d4full, 0x10e3ebf3f318f3cbull, 0x4e53741d1d691de8ull, 0x804b0bcbcbc0cb16ull, - 0x8c4503c9c9cac906ull, 0xb3fe294d4d644d52ull, 0xe8c4b02c2c9c2c7dull, 0xc56a86afaf29af11ull, - 0x0b72f979798079efull, 0x7a9aa7e0e047e053ull, 0x55c2669797f197ccull, 0x34c9d3fdfd2efdbbull, - 0x7f10a16f6fce6f5full, 0xa7ec314b4b7a4b62ull, 0x83c60945454c4512ull, 0x96afe43939dd39d5ull, - 0x84baf83e3ec63eedull, 0xf42953dddd8edda6ull, 0xed4eb6a3a315a371ull, 0xbff0214f4f6e4f42ull, - 0x9f2beab4b45eb4c9ull, 0x9325e2b6b654b6d9ull, 0x7be1529a9ac89aa4ull, 0x242a380e0e360e70ull, - 0x425d7c1f1f631ff8ull, 0xa51ac6bfbf79bf91ull, 0x7e6b5415154115a8ull, 0x7c9da3e1e142e15bull, - 0xabe2394949704972ull, 0xd6046fd2d2bdd2deull, 0x4dde769393e593ecull, 0xae683fc6c6f9c67eull, - 0x4bd9729292e092e4ull, 0x3143d57272a772b7ull, 0x63fd429e9edc9e84ull, 0x5b3a996161f8612full, - 0xdc0d63d1d1b2d1c6ull, 0x5734916363f2633full, 0x26dccffafa35fa83ull, 0x5eb09feeee71ee23ull, - 0x02f6f7f4f403f4f3ull, 0x564f6419197d19c8ull, 0xc41173d5d5a6d5e6ull, 0xc9648eadad23ad01ull, - 0xcd957d58582558faull, 0xff5baaa4a40ea449ull, 0xbd06d6bbbb6dbbb1ull, 0xe140bea1a11fa161ull, - 0xf22e57dcdc8bdcaeull, 0x16e4eff2f21df2c3ull, 0x2dae368383b5836cull, 0xb285dc3737eb37a5ull, - 0x91d315424257422aull, 0x6286b7e4e453e473ull, 0x017bf57a7a8f7af7ull, 0xac9ec83232fa328dull, - 0x6ff34a9c9cd69c94ull, 0x925e17ccccdbcc2eull, 0xdd7696abab3dab31ull, 0xa1eb354a4a7f4a6aull, - 0x058a068f8f898f0cull, 0x7917a56e6ecb6e57ull, 0x181c100404140420ull, 0xd2f59c2727bb2725ull, - 0xe4cab82e2e962e6dull, 0x688fbbe7e75ce76bull, 0x7694afe2e24de243ull, 0xc19b755a5a2f5aeaull, - 0x53c5629696f496c4ull, 0x74625816164e16b0ull, 0xcae98c2323af2305ull, 0xfad1ac2b2b872b45ull, - 0xb6742fc2c2edc25eull, 0x4326896565ec650full, 0x492f856666e36617ull, 0x222d3c0f0f330f78ull, - 0xaf13cabcbc76bc89ull, 0xd1789ea9a937a921ull, 0x8fc8014747464702ull, 0x9bda194141584132ull, - 0xb88cd03434e434bdull, 0xade53d484875487aull, 0x32ced7fcfc2bfcb3ull, 0x9522e6b7b751b7d1ull, - 0x610bb56a6adf6a77ull, 0x179f1a8888928834ull, 0xf95caea5a50ba541ull, 0xf7a45153530253a2ull, - 0x33b5228686a48644ull, 0x2cd5c3f9f93af99bull, 0xc79c715b5b2a5be2ull, 0xe03b4bdbdb90db96ull, - 0x90a8e03838d838ddull, 0x077cf17b7b8a7bffull, 0xb0732bc3c3e8c356ull, 0x445a781e1e661ef0ull, - 0xccee882222aa220dull, 0xaa99cc3333ff3385ull, 0xd8fc902424b4243dull, 0xf0d8a0282888285dull, - 0xb482d83636ee36adull, 0xa86f3bc7c7fcc776ull, 0x8b39f2b2b240b2f9ull, 0x9aa1ec3b3bd73bc5ull, - 0x038d028e8e8c8e04ull, 0x2f58c17777b6779full, 0xbb01d2baba68bab9ull, 0x04f1f3f5f506f5fbull, - 0x786c5014144414a0ull, 0x65fa469f9fd99f8cull, 0x3038200808280840ull, 0xe3b64955551c5592ull, - 0x7de6569b9bcd9bacull, 0xb5f92d4c4c614c5aull, 0x3ec0dffefe21fea3ull, 0x5d3d9d6060fd6027ull, - 0xd5896d5c5c315cdaull, 0xe63c4fdada95da9eull, 0x50486018187818c0ull, 0x89cf05464643460aull, - 0x945913cdcddecd26ull, 0x136ee97d7d947dcfull, 0xc6e7842121a52115ull, 0x8737fab0b04ab0e9ull, - 0x82bdfc3f3fc33fe5ull, 0x5a416c1b1b771bd8ull, 0x11981e898997893cull, 0x38c7dbffff24ffabull, - 0x40ab8bebeb60eb0bull, 0x3fbb2a8484ae8454ull, 0x6b02b96969d0696full, 0x9ca6e83a3ad23acdull, - 0x69f44e9d9dd39d9cull, 0xc81f7bd7d7acd7f6ull, 0xd0036bd3d3b8d3d6ull, 0x3d4ddd7070ad70a7ull, - 0x4f28816767e6671full, 0x9ddd1d40405d403aull, 0x992ceeb5b55bb5c1ull, 0xfe205fdede81debeull, - 0xd38e695d5d345dd2ull, 0xa090c03030f0309dull, 0x41d07e9191ef91fcull, 0x8130feb1b14fb1e1ull, - 0x0d75fd78788578e7ull, 0x6677441111551188ull, 0x0607040101050108ull, 0x6481b3e5e556e57bull, - 0x0000000000000000ull, 0x6d05bd6868d56867ull, 0x77ef5a9898c298b4ull, 0xe747baa0a01aa069ull, - 0xa46133c5c5f6c566ull, 0x0c0e0802020a0210ull, 0xf355a2a6a604a659ull, 0x2551cd7474b97487ull, - 0xeec3b42d2d992d75ull, 0x3a312c0b0b270b58ull, 0xeb49b2a2a210a279ull, 0x295fc57676b37697ull, - 0x8d3ef6b3b345b3f1ull, 0xa31dc2bebe7cbe99ull, 0x9e501fceced1ce3eull, 0xa914cebdbd73bd81ull, - 0xc36d82aeae2cae19ull, 0x4ca583e9e96ae91bull, 0x1b91128a8a988a24ull, 0xa697c43131f53195ull, - 0x4854701c1c6c1ce0ull, 0x52be97ecec7bec33ull, 0x1cede3f1f112f1dbull, 0x71e85e9999c799bcull, - 0x5fcb6a9494fe94d4ull, 0xdb7192aaaa38aa39ull, 0x0ef8fff6f609f6e3ull, 0xd4f2982626be262dull, - 0xe2cdbc2f2f932f65ull, 0x58b79befef74ef2bull, 0x4aa287e8e86fe813ull, 0x0f830a8c8c868c14ull, - 0xbe8bd43535e135b5ull, 0x0a090c03030f0318ull, 0xc21677d4d4a3d4eeull, 0x1f60e17f7f9e7fdfull, - 0x20dbcbfbfb30fb8bull, 0x1e1b140505110528ull, 0xbc7d23c1c1e2c146ull, 0xd987655e5e3b5ecaull, - 0x47d77a9090ea90f4ull, 0xc0e0802020a0201dull, 0x8eb3f43d3dc93df5ull, 0x2ba9328282b08264ull, - 0x08fffbf7f70cf7ebull, 0x46ac8feaea65ea03ull, 0x3c36280a0a220a50ull, 0x2e23340d0d390d68ull, - 0x1967e57e7e9b7ed7ull, 0x2ad2c7f8f83ff893ull, 0xfdad5d50500d50baull, 0x5c46681a1a721ad0ull, - 0xa26637c4c4f3c46eull, 0x12151c07071b0738ull, 0xefb8415757165782ull, 0xb70fdab8b862b8a9ull, - 0x88b4f03c3ccc3cfdull, 0x5133956262f76237ull, 0x7093abe3e348e34bull, 0x8a4207c8c8cfc80eull, - 0xcf638aacac26ac09ull, 0xf1a35552520752aaull, 0x45218d6464e96407ull, 0x6070401010501080ull, - 0xda0a67d0d0b7d0ceull, 0xec3543d9d99ad986ull, 0x6a794c13135f1398ull, 0x2824300c0c3c0c60ull, - 0x6c7e4812125a1290ull, 0xf6dfa429298d2955ull, 0xfbaa5951510851b2ull, 0xb108deb9b967b9a1ull, - 0x98571bcfcfd4cf36ull, 0xce187fd6d6a9d6feull, 0x3744d17373a273bfull, 0x09840e8d8d838d1cull, - 0x21a03e8181bf817cull, 0xe5b14d545419549aull, 0xba7a27c0c0e7c04eull, 0x54b993eded7eed3bull, - 0xb9f7254e4e6b4e4aull, 0x85c10d444449441aull, 0xf552a6a7a701a751ull, 0xfcd6a82a2a822a4dull, - 0x39bc2e8585ab855cull, 0xdefb942525b12535ull, 0x6e88bfe6e659e663ull, 0x864c0fcacac5ca1eull, - 0x1569ed7c7c917cc7ull, 0x1d96168b8b9d8b2cull, 0xe9bf45565613568aull, 0x27a73a8080ba8074ull - }, - { - 0x501fceced1ce3e9eull, 0x06d6bbbb6dbbb1bdull, 0xab8bebeb60eb0b40ull, 0xd9729292e092e44bull, - 0xac8feaea65ea0346ull, 0x4b0bcbcbc0cb1680ull, 0x794c13135f13986aull, 0x7d23c1c1e2c146bcull, - 0xa583e9e96ae91b4cull, 0xa6e83a3ad23acd9cull, 0x187fd6d6a9d6feceull, 0x39f2b2b240b2f98bull, - 0x046fd2d2bdd2ded6ull, 0xd77a9090ea90f447ull, 0x655c17174b17b872ull, 0xd2c7f8f83ff8932aull, - 0xd315424257422a91ull, 0x6b5415154115a87eull, 0xbf45565613568ae9ull, 0x2beab4b45eb4c99full, - 0x26896565ec650f43ull, 0x54701c1c6c1ce048ull, 0x9f1a888892883417ull, 0xd411434352432297ull, - 0x6133c5c5f6c566a4ull, 0x896d5c5c315cdad5ull, 0x82d83636ee36adb4ull, 0x01d2baba68bab9bbull, - 0xf1f3f5f506f5fb04ull, 0xb8415757165782efull, 0x28816767e6671f4full, 0x840e8d8d838d1c09ull, - 0x97c43131f53195a6ull, 0xf8fff6f609f6e30eull, 0x218d6464e9640745ull, 0x957d58582558facdull, - 0xfd429e9edc9e8463ull, 0xf6f7f4f403f4f302ull, 0xee882222aa220dccull, 0x7192aaaa38aa39dbull, - 0x56c97575bc758f23ull, 0x2d3c0f0f330f7822ull, 0x0e0802020a02100cull, 0x30feb1b14fb1e181ull, - 0x275bdfdf84dfb6f8ull, 0x1ea96d6dc46d4f73ull, 0x44d17373a273bf37ull, 0xfe294d4d644d52b3ull, - 0x69ed7c7c917cc715ull, 0xf2982626be262dd4ull, 0xcab82e2e962e6de4ull, 0xfffbf7f70cf7eb08ull, - 0x3820080828084030ull, 0x8e695d5d345dd2d3ull, 0xc10d444449441a85ull, 0xbaf83e3ec63eed84ull, - 0xfa469f9fd99f8c65ull, 0x6c5014144414a078ull, 0x4207c8c8cfc80e8aull, 0x6d82aeae2cae19c3ull, - 0xb14d545419549ae5ull, 0x7040101050108060ull, 0x3247d8d89fd88eeaull, 0x13cabcbc76bc89afull, - 0x46681a1a721ad05cull, 0x0cb16b6bda6b7f67ull, 0x02b96969d0696f6bull, 0xe3ebf3f318f3cb10ull, - 0x14cebdbd73bd81a9ull, 0x99cc3333ff3385aaull, 0x7696abab3dab31ddull, 0xdccffafa35fa8326ull, - 0x0d63d1d1b2d1c6dcull, 0xe6569b9bcd9bac7dull, 0x05bd6868d568676dull, 0xf7254e4e6b4e4ab9ull, - 0x625816164e16b074ull, 0xcc6e9595fb95dc59ull, 0xd07e9191ef91fc41ull, 0xb09feeee71ee235eull, - 0xf92d4c4c614c5ab5ull, 0x34916363f2633f57ull, 0x8d028e8e8c8e0403ull, 0x9c715b5b2a5be2c7ull, - 0x5e17ccccdbcc2e92ull, 0xb4f03c3ccc3cfd88ull, 0x4f6419197d19c856ull, 0x40bea1a11fa161e1ull, - 0xa03e8181bf817c21ull, 0xe2394949704972abull, 0x7cf17b7b8a7bff07ull, 0x3543d9d99ad986ecull, - 0x10a16f6fce6f5f7full, 0x85dc3737eb37a5b2ull, 0x3d9d6060fd60275dull, 0x4c0fcacac5ca1e86ull, - 0x8fbbe7e75ce76b68ull, 0xd1ac2b2b872b45faull, 0xe53d484875487aadull, 0xc9d3fdfd2efdbb34ull, - 0xc5629696f496c453ull, 0xc60945454c451283ull, 0xced7fcfc2bfcb332ull, 0xda1941415841329bull, - 0x7e4812125a12906cull, 0x23340d0d390d682eull, 0x72f979798079ef0bull, 0x81b3e5e556e57b64ull, - 0x981e898997893c11ull, 0x830a8c8c868c140full, 0x93abe3e348e34b70ull, 0xe0802020a0201dc0ull, - 0x90c03030f0309da0ull, 0x2e57dcdc8bdcaef2ull, 0x22e6b7b751b7d195ull, 0x19ad6c6cc16c4775ull, - 0xeb354a4a7f4a6aa1ull, 0x2ceeb5b55bb5c199ull, 0xbdfc3f3fc33fe582ull, 0xc2669797f197cc55ull, - 0x1677d4d4a3d4eec2ull, 0x33956262f7623751ull, 0xc3b42d2d992d75eeull, 0x121806061e063014ull, - 0x5baaa4a40ea449ffull, 0x5caea5a50ba541f9ull, 0xae368383b5836c2dull, 0x80615f5f3e5fc2dfull, - 0xd6a82a2a822a4dfcull, 0x3c4fdada95da9ee6ull, 0x4503c9c9cac9068cull, 0x0000000000000000ull, - 0x67e57e7e9b7ed719ull, 0x49b2a2a210a279ebull, 0xb64955551c5592e3ull, 0x1ac6bfbf79bf91a5ull, - 0x7744111155118866ull, 0x1173d5d5a6d5e6c4ull, 0xf34a9c9cd69c946full, 0x571bcfcfd4cf3698ull, - 0x2a380e0e360e7024ull, 0x36280a0a220a503cull, 0xb3f43d3dc93df58eull, 0xaa5951510851b2fbull, - 0x6ee97d7d947dcf13ull, 0xde769393e593ec4dull, 0x416c1b1b771bd85aull, 0xc0dffefe21fea33eull, - 0x6637c4c4f3c46ea2ull, 0xc80147474647028full, 0x3f2409092d094836ull, 0xb5228686a4864433ull, - 0x312c0b0b270b583aull, 0x8a068f8f898f0c05ull, 0xf44e9d9dd39d9c69ull, 0x0bb56a6adf6a7761ull, - 0x151c07071b073812ull, 0x08deb9b967b9a1b1ull, 0x37fab0b04ab0e987ull, 0xef5a9898c298b477ull, - 0x486018187818c050ull, 0x9ec83232fa328dacull, 0x4ad97171a871af3bull, 0xec314b4b7a4b62a7ull, - 0xb79befef74ef2b58ull, 0xa1ec3b3bd73bc59aull, 0x4ddd7070ad70a73dull, 0x47baa0a01aa069e7ull, - 0x86b7e4e453e47362ull, 0xdd1d40405d403a9dull, 0xc7dbffff24ffab38ull, 0x732bc3c3e8c356b0ull, - 0x789ea9a937a921d1ull, 0x88bfe6e659e6636eull, 0x75fd78788578e70dull, 0xd5c3f9f93af99b2cull, - 0x96168b8b9d8b2c1dull, 0xcf05464643460a89ull, 0xa73a8080ba807427ull, 0x5a781e1e661ef044ull, - 0xa8e03838d838dd90ull, 0x9da3e1e142e15b7cull, 0x0fdab8b862b8a9b7ull, 0x7f9aa8a832a829d7ull, - 0x9aa7e0e047e0537aull, 0x24300c0c3c0c6028ull, 0xe98c2323af2305caull, 0x5fc57676b3769729ull, - 0x53741d1d691de84eull, 0xfb942525b12535deull, 0xfc902424b4243dd8ull, 0x1b1405051105281eull, - 0xede3f1f112f1db1cull, 0x17a56e6ecb6e5779ull, 0xcb6a9494fe94d45full, 0xd8a0282888285df0ull, - 0xe1529a9ac89aa47bull, 0xbb2a8484ae84543full, 0xa287e8e86fe8134aull, 0x4eb6a3a315a371edull, - 0xf0214f4f6e4f42bfull, 0x58c17777b6779f2full, 0x036bd3d3b8d3d6d0ull, 0xbc2e8585ab855c39ull, - 0x94afe2e24de24376ull, 0xa35552520752aaf1ull, 0xe4eff2f21df2c316ull, 0xa9328282b082642bull, - 0xad5d50500d50bafdull, 0x7bf57a7a8f7af701ull, 0xcdbc2f2f932f65e2ull, 0x51cd7474b9748725ull, - 0xa45153530253a2f7ull, 0x3ef6b3b345b3f18dull, 0x3a996161f8612f5bull, 0x6a86afaf29af11c5ull, - 0xafe43939dd39d596ull, 0x8bd43535e135b5beull, 0x205fdede81debefeull, 0x5913cdcddecd2694ull, - 0x5d7c1f1f631ff842ull, 0xe85e9999c799bc71ull, 0x638aacac26ac09cfull, 0x648eadad23ad01c9ull, - 0x43d57272a772b731ull, 0xc4b02c2c9c2c7de8ull, 0x2953dddd8edda6f4ull, 0x0a67d0d0b7d0cedaull, - 0xb2268787a1874c35ull, 0x1dc2bebe7cbe99a3ull, 0x87655e5e3b5ecad9ull, 0x55a2a6a604a659f3ull, - 0xbe97ecec7bec3352ull, 0x1c10040414042018ull, 0x683fc6c6f9c67eaeull, 0x090c03030f03180aull, - 0x8cd03434e434bdb8ull, 0xdbcbfbfb30fb8b20ull, 0x3b4bdbdb90db96e0ull, 0x927959592059f2cbull, - 0x25e2b6b654b6d993ull, 0x742fc2c2edc25eb6ull, 0x0704010105010806ull, 0xeae7f0f017f0d31aull, - 0x9b755a5a2f5aeac1ull, 0xb993eded7eed3b54ull, 0x52a6a7a701a751f5ull, 0x2f856666e3661749ull, - 0xe7842121a52115c6ull, 0x60e17f7f9e7fdf1full, 0x91128a8a988a241bull, 0xf59c2727bb2725d2ull, - 0x6f3bc7c7fcc776a8ull, 0x7a27c0c0e7c04ebaull, 0xdfa429298d2955f6ull, 0x1f7bd7d7acd7f6c8ull - }, - { - 0x769393e593ec4ddeull, 0x43d9d99ad986ec35ull, 0x529a9ac89aa47be1ull, 0xeeb5b55bb5c1992cull, - 0x5a9898c298b477efull, 0x882222aa220dcceeull, 0x0945454c451283c6ull, 0xd7fcfc2bfcb332ceull, - 0xd2baba68bab9bb01ull, 0xb56a6adf6a77610bull, 0x5bdfdf84dfb6f827ull, 0x0802020a02100c0eull, - 0x469f9fd99f8c65faull, 0x57dcdc8bdcaef22eull, 0x5951510851b2fbaaull, 0x7959592059f2cb92ull, - 0x354a4a7f4a6aa1ebull, 0x5c17174b17b87265ull, 0xac2b2b872b45fad1ull, 0x2fc2c2edc25eb674ull, - 0x6a9494fe94d45fcbull, 0xf7f4f403f4f302f6ull, 0xd6bbbb6dbbb1bd06ull, 0xb6a3a315a371ed4eull, - 0x956262f762375133ull, 0xb7e4e453e4736286ull, 0xd97171a871af3b4aull, 0x77d4d4a3d4eec216ull, - 0x13cdcddecd269459ull, 0xdd7070ad70a73d4dull, 0x5816164e16b07462ull, 0xa3e1e142e15b7c9dull, - 0x394949704972abe2ull, 0xf03c3ccc3cfd88b4ull, 0x27c0c0e7c04eba7aull, 0x47d8d89fd88eea32ull, - 0x6d5c5c315cdad589ull, 0x569b9bcd9bac7de6ull, 0x8eadad23ad01c964ull, 0x2e8585ab855c39bcull, - 0x5153530253a2f7a4ull, 0xbea1a11fa161e140ull, 0xf57a7a8f7af7017bull, 0x07c8c8cfc80e8a42ull, - 0xb42d2d992d75eec3ull, 0xa7e0e047e0537a9aull, 0x63d1d1b2d1c6dc0dull, 0xd57272a772b73143ull, - 0xa2a6a604a659f355ull, 0xb02c2c9c2c7de8c4ull, 0x37c4c4f3c46ea266ull, 0xabe3e348e34b7093ull, - 0xc57676b37697295full, 0xfd78788578e70d75ull, 0xe6b7b751b7d19522ull, 0xeab4b45eb4c99f2bull, - 0x2409092d0948363full, 0xec3b3bd73bc59aa1ull, 0x380e0e360e70242aull, 0x1941415841329bdaull, - 0x2d4c4c614c5ab5f9ull, 0x5fdede81debefe20ull, 0xf2b2b240b2f98b39ull, 0x7a9090ea90f447d7ull, - 0x942525b12535defbull, 0xaea5a50ba541f95cull, 0x7bd7d7acd7f6c81full, 0x0c03030f03180a09ull, - 0x4411115511886677ull, 0x0000000000000000ull, 0x2bc3c3e8c356b073ull, 0xb82e2e962e6de4caull, - 0x729292e092e44bd9ull, 0x9befef74ef2b58b7ull, 0x254e4e6b4e4ab9f7ull, 0x4812125a12906c7eull, - 0x4e9d9dd39d9c69f4ull, 0xe97d7d947dcf136eull, 0x0bcbcbc0cb16804bull, 0xd43535e135b5be8bull, - 0x4010105010806070ull, 0x73d5d5a6d5e6c411ull, 0x214f4f6e4f42bff0ull, 0x429e9edc9e8463fdull, - 0x294d4d644d52b3feull, 0x9ea9a937a921d178ull, 0x4955551c5592e3b6ull, 0x3fc6c6f9c67eae68ull, - 0x67d0d0b7d0ceda0aull, 0xf17b7b8a7bff077cull, 0x6018187818c05048ull, 0x669797f197cc55c2ull, - 0x6bd3d3b8d3d6d003ull, 0xd83636ee36adb482ull, 0xbfe6e659e6636e88ull, 0x3d484875487aade5ull, - 0x45565613568ae9bfull, 0x3e8181bf817c21a0ull, 0x068f8f898f0c058aull, 0xc17777b6779f2f58ull, - 0x17ccccdbcc2e925eull, 0x4a9c9cd69c946ff3ull, 0xdeb9b967b9a1b108ull, 0xafe2e24de2437694ull, - 0x8aacac26ac09cf63ull, 0xdab8b862b8a9b70full, 0xbc2f2f932f65e2cdull, 0x5415154115a87e6bull, - 0xaaa4a40ea449ff5bull, 0xed7c7c917cc71569ull, 0x4fdada95da9ee63cull, 0xe03838d838dd90a8ull, - 0x781e1e661ef0445aull, 0x2c0b0b270b583a31ull, 0x1405051105281e1bull, 0x7fd6d6a9d6fece18ull, - 0x5014144414a0786cull, 0xa56e6ecb6e577917ull, 0xad6c6cc16c477519ull, 0xe57e7e9b7ed71967ull, - 0x856666e36617492full, 0xd3fdfd2efdbb34c9ull, 0xfeb1b14fb1e18130ull, 0xb3e5e556e57b6481ull, - 0x9d6060fd60275d3dull, 0x86afaf29af11c56aull, 0x655e5e3b5ecad987ull, 0xcc3333ff3385aa99ull, - 0x268787a1874c35b2ull, 0x03c9c9cac9068c45ull, 0xe7f0f017f0d31aeaull, 0x695d5d345dd2d38eull, - 0xa96d6dc46d4f731eull, 0xfc3f3fc33fe582bdull, 0x1a8888928834179full, 0x0e8d8d838d1c0984ull, - 0x3bc7c7fcc776a86full, 0xfbf7f70cf7eb08ffull, 0x741d1d691de84e53ull, 0x83e9e96ae91b4ca5ull, - 0x97ecec7bec3352beull, 0x93eded7eed3b54b9ull, 0x3a8080ba807427a7ull, 0xa429298d2955f6dfull, - 0x9c2727bb2725d2f5ull, 0x1bcfcfd4cf369857ull, 0x5e9999c799bc71e8ull, 0x9aa8a832a829d77full, - 0x5d50500d50bafdadull, 0x3c0f0f330f78222dull, 0xdc3737eb37a5b285ull, 0x902424b4243dd8fcull, - 0xa0282888285df0d8ull, 0xc03030f0309da090ull, 0x6e9595fb95dc59ccull, 0x6fd2d2bdd2ded604ull, - 0xf83e3ec63eed84baull, 0x715b5b2a5be2c79cull, 0x1d40405d403a9dddull, 0x368383b5836c2daeull, - 0xf6b3b345b3f18d3eull, 0xb96969d0696f6b02ull, 0x415757165782efb8ull, 0x7c1f1f631ff8425dull, - 0x1c07071b07381215ull, 0x701c1c6c1ce04854ull, 0x128a8a988a241b91ull, 0xcabcbc76bc89af13ull, - 0x802020a0201dc0e0ull, 0x8bebeb60eb0b40abull, 0x1fceced1ce3e9e50ull, 0x028e8e8c8e04038dull, - 0x96abab3dab31dd76ull, 0x9feeee71ee235eb0ull, 0xc43131f53195a697ull, 0xb2a2a210a279eb49ull, - 0xd17373a273bf3744ull, 0xc3f9f93af99b2cd5ull, 0x0fcacac5ca1e864cull, 0xe83a3ad23acd9ca6ull, - 0x681a1a721ad05c46ull, 0xcbfbfb30fb8b20dbull, 0x340d0d390d682e23ull, 0x23c1c1e2c146bc7dull, - 0xdffefe21fea33ec0ull, 0xcffafa35fa8326dcull, 0xeff2f21df2c316e4ull, 0xa16f6fce6f5f7f10ull, - 0xcebdbd73bd81a914ull, 0x629696f496c453c5ull, 0x53dddd8edda6f429ull, 0x11434352432297d4ull, - 0x5552520752aaf1a3ull, 0xe2b6b654b6d99325ull, 0x2008082808403038ull, 0xebf3f318f3cb10e3ull, - 0x82aeae2cae19c36dull, 0xc2bebe7cbe99a31dull, 0x6419197d19c8564full, 0x1e898997893c1198ull, - 0xc83232fa328dac9eull, 0x982626be262dd4f2ull, 0xfab0b04ab0e98737ull, 0x8feaea65ea0346acull, - 0x314b4b7a4b62a7ecull, 0x8d6464e964074521ull, 0x2a8484ae84543fbbull, 0x328282b082642ba9ull, - 0xb16b6bda6b7f670cull, 0xf3f5f506f5fb04f1ull, 0xf979798079ef0b72ull, 0xc6bfbf79bf91a51aull, - 0x0401010501080607ull, 0x615f5f3e5fc2df80ull, 0xc97575bc758f2356ull, 0x916363f2633f5734ull, - 0x6c1b1b771bd85a41ull, 0x8c2323af2305cae9ull, 0xf43d3dc93df58eb3ull, 0xbd6868d568676d05ull, - 0xa82a2a822a4dfcd6ull, 0x896565ec650f4326ull, 0x87e8e86fe8134aa2ull, 0x7e9191ef91fc41d0ull, - 0xfff6f609f6e30ef8ull, 0xdbffff24ffab38c7ull, 0x4c13135f13986a79ull, 0x7d58582558facd95ull, - 0xe3f1f112f1db1cedull, 0x0147474647028fc8ull, 0x280a0a220a503c36ull, 0xe17f7f9e7fdf1f60ull, - 0x33c5c5f6c566a461ull, 0xa6a7a701a751f552ull, 0xbbe7e75ce76b688full, 0x996161f8612f5b3aull, - 0x755a5a2f5aeac19bull, 0x1806061e06301412ull, 0x05464643460a89cfull, 0x0d444449441a85c1ull, - 0x15424257422a91d3ull, 0x100404140420181cull, 0xbaa0a01aa069e747ull, 0x4bdbdb90db96e03bull, - 0xe43939dd39d596afull, 0x228686a4864433b5ull, 0x4d545419549ae5b1ull, 0x92aaaa38aa39db71ull, - 0x0a8c8c868c140f83ull, 0xd03434e434bdb88cull, 0x842121a52115c6e7ull, 0x168b8b9d8b2c1d96ull, - 0xc7f8f83ff8932ad2ull, 0x300c0c3c0c602824ull, 0xcd7474b974872551ull, 0x816767e6671f4f28ull - }, - { - 0x6868d568676d05bdull, 0x8d8d838d1c09840eull, 0xcacac5ca1e864c0full, 0x4d4d644d52b3fe29ull, - 0x7373a273bf3744d1ull, 0x4b4b7a4b62a7ec31ull, 0x4e4e6b4e4ab9f725ull, 0x2a2a822a4dfcd6a8ull, - 0xd4d4a3d4eec21677ull, 0x52520752aaf1a355ull, 0x2626be262dd4f298ull, 0xb3b345b3f18d3ef6ull, - 0x545419549ae5b14dull, 0x1e1e661ef0445a78ull, 0x19197d19c8564f64ull, 0x1f1f631ff8425d7cull, - 0x2222aa220dccee88ull, 0x03030f03180a090cull, 0x464643460a89cf05ull, 0x3d3dc93df58eb3f4ull, - 0x2d2d992d75eec3b4ull, 0x4a4a7f4a6aa1eb35ull, 0x53530253a2f7a451ull, 0x8383b5836c2dae36ull, - 0x13135f13986a794cull, 0x8a8a988a241b9112ull, 0xb7b751b7d19522e6ull, 0xd5d5a6d5e6c41173ull, - 0x2525b12535defb94ull, 0x79798079ef0b72f9ull, 0xf5f506f5fb04f1f3ull, 0xbdbd73bd81a914ceull, - 0x58582558facd957dull, 0x2f2f932f65e2cdbcull, 0x0d0d390d682e2334ull, 0x02020a02100c0e08ull, - 0xeded7eed3b54b993ull, 0x51510851b2fbaa59ull, 0x9e9edc9e8463fd42ull, 0x1111551188667744ull, - 0xf2f21df2c316e4efull, 0x3e3ec63eed84baf8ull, 0x55551c5592e3b649ull, 0x5e5e3b5ecad98765ull, - 0xd1d1b2d1c6dc0d63ull, 0x16164e16b0746258ull, 0x3c3ccc3cfd88b4f0ull, 0x6666e36617492f85ull, - 0x7070ad70a73d4dddull, 0x5d5d345dd2d38e69ull, 0xf3f318f3cb10e3ebull, 0x45454c451283c609ull, - 0x40405d403a9ddd1dull, 0xccccdbcc2e925e17ull, 0xe8e86fe8134aa287ull, 0x9494fe94d45fcb6aull, - 0x565613568ae9bf45ull, 0x0808280840303820ull, 0xceced1ce3e9e501full, 0x1a1a721ad05c4668ull, - 0x3a3ad23acd9ca6e8ull, 0xd2d2bdd2ded6046full, 0xe1e142e15b7c9da3ull, 0xdfdf84dfb6f8275bull, - 0xb5b55bb5c1992ceeull, 0x3838d838dd90a8e0ull, 0x6e6ecb6e577917a5ull, 0x0e0e360e70242a38ull, - 0xe5e556e57b6481b3ull, 0xf4f403f4f302f6f7ull, 0xf9f93af99b2cd5c3ull, 0x8686a4864433b522ull, - 0xe9e96ae91b4ca583ull, 0x4f4f6e4f42bff021ull, 0xd6d6a9d6fece187full, 0x8585ab855c39bc2eull, - 0x2323af2305cae98cull, 0xcfcfd4cf3698571bull, 0x3232fa328dac9ec8ull, 0x9999c799bc71e85eull, - 0x3131f53195a697c4ull, 0x14144414a0786c50ull, 0xaeae2cae19c36d82ull, 0xeeee71ee235eb09full, - 0xc8c8cfc80e8a4207ull, 0x484875487aade53dull, 0xd3d3b8d3d6d0036bull, 0x3030f0309da090c0ull, - 0xa1a11fa161e140beull, 0x9292e092e44bd972ull, 0x41415841329bda19ull, 0xb1b14fb1e18130feull, - 0x18187818c0504860ull, 0xc4c4f3c46ea26637ull, 0x2c2c9c2c7de8c4b0ull, 0x7171a871af3b4ad9ull, - 0x7272a772b73143d5ull, 0x444449441a85c10dull, 0x15154115a87e6b54ull, 0xfdfd2efdbb34c9d3ull, - 0x3737eb37a5b285dcull, 0xbebe7cbe99a31dc2ull, 0x5f5f3e5fc2df8061ull, 0xaaaa38aa39db7192ull, - 0x9b9bcd9bac7de656ull, 0x8888928834179f1aull, 0xd8d89fd88eea3247ull, 0xabab3dab31dd7696ull, - 0x898997893c11981eull, 0x9c9cd69c946ff34aull, 0xfafa35fa8326dccfull, 0x6060fd60275d3d9dull, - 0xeaea65ea0346ac8full, 0xbcbc76bc89af13caull, 0x6262f76237513395ull, 0x0c0c3c0c60282430ull, - 0x2424b4243dd8fc90ull, 0xa6a604a659f355a2ull, 0xa8a832a829d77f9aull, 0xecec7bec3352be97ull, - 0x6767e6671f4f2881ull, 0x2020a0201dc0e080ull, 0xdbdb90db96e03b4bull, 0x7c7c917cc71569edull, - 0x282888285df0d8a0ull, 0xdddd8edda6f42953ull, 0xacac26ac09cf638aull, 0x5b5b2a5be2c79c71ull, - 0x3434e434bdb88cd0ull, 0x7e7e9b7ed71967e5ull, 0x1010501080607040ull, 0xf1f112f1db1cede3ull, - 0x7b7b8a7bff077cf1ull, 0x8f8f898f0c058a06ull, 0x6363f2633f573491ull, 0xa0a01aa069e747baull, - 0x05051105281e1b14ull, 0x9a9ac89aa47be152ull, 0x434352432297d411ull, 0x7777b6779f2f58c1ull, - 0x2121a52115c6e784ull, 0xbfbf79bf91a51ac6ull, 0x2727bb2725d2f59cull, 0x09092d0948363f24ull, - 0xc3c3e8c356b0732bull, 0x9f9fd99f8c65fa46ull, 0xb6b654b6d99325e2ull, 0xd7d7acd7f6c81f7bull, - 0x29298d2955f6dfa4ull, 0xc2c2edc25eb6742full, 0xebeb60eb0b40ab8bull, 0xc0c0e7c04eba7a27ull, - 0xa4a40ea449ff5baaull, 0x8b8b9d8b2c1d9616ull, 0x8c8c868c140f830aull, 0x1d1d691de84e5374ull, - 0xfbfb30fb8b20dbcbull, 0xffff24ffab38c7dbull, 0xc1c1e2c146bc7d23ull, 0xb2b240b2f98b39f2ull, - 0x9797f197cc55c266ull, 0x2e2e962e6de4cab8ull, 0xf8f83ff8932ad2c7ull, 0x6565ec650f432689ull, - 0xf6f609f6e30ef8ffull, 0x7575bc758f2356c9ull, 0x07071b073812151cull, 0x0404140420181c10ull, - 0x4949704972abe239ull, 0x3333ff3385aa99ccull, 0xe4e453e4736286b7ull, 0xd9d99ad986ec3543ull, - 0xb9b967b9a1b108deull, 0xd0d0b7d0ceda0a67ull, 0x424257422a91d315ull, 0xc7c7fcc776a86f3bull, - 0x6c6cc16c477519adull, 0x9090ea90f447d77aull, 0x0000000000000000ull, 0x8e8e8c8e04038d02ull, - 0x6f6fce6f5f7f10a1ull, 0x50500d50bafdad5dull, 0x0101050108060704ull, 0xc5c5f6c566a46133ull, - 0xdada95da9ee63c4full, 0x47474647028fc801ull, 0x3f3fc33fe582bdfcull, 0xcdcddecd26945913ull, - 0x6969d0696f6b02b9ull, 0xa2a210a279eb49b2ull, 0xe2e24de2437694afull, 0x7a7a8f7af7017bf5ull, - 0xa7a701a751f552a6ull, 0xc6c6f9c67eae683full, 0x9393e593ec4dde76ull, 0x0f0f330f78222d3cull, - 0x0a0a220a503c3628ull, 0x06061e0630141218ull, 0xe6e659e6636e88bfull, 0x2b2b872b45fad1acull, - 0x9696f496c453c562ull, 0xa3a315a371ed4eb6ull, 0x1c1c6c1ce0485470ull, 0xafaf29af11c56a86ull, - 0x6a6adf6a77610bb5ull, 0x12125a12906c7e48ull, 0x8484ae84543fbb2aull, 0x3939dd39d596afe4ull, - 0xe7e75ce76b688fbbull, 0xb0b04ab0e98737faull, 0x8282b082642ba932ull, 0xf7f70cf7eb08fffbull, - 0xfefe21fea33ec0dfull, 0x9d9dd39d9c69f44eull, 0x8787a1874c35b226ull, 0x5c5c315cdad5896dull, - 0x8181bf817c21a03eull, 0x3535e135b5be8bd4ull, 0xdede81debefe205full, 0xb4b45eb4c99f2beaull, - 0xa5a50ba541f95caeull, 0xfcfc2bfcb332ced7ull, 0x8080ba807427a73aull, 0xefef74ef2b58b79bull, - 0xcbcbc0cb16804b0bull, 0xbbbb6dbbb1bd06d6ull, 0x6b6bda6b7f670cb1ull, 0x7676b37697295fc5ull, - 0xbaba68bab9bb01d2ull, 0x5a5a2f5aeac19b75ull, 0x7d7d947dcf136ee9ull, 0x78788578e70d75fdull, - 0x0b0b270b583a312cull, 0x9595fb95dc59cc6eull, 0xe3e348e34b7093abull, 0xadad23ad01c9648eull, - 0x7474b974872551cdull, 0x9898c298b477ef5aull, 0x3b3bd73bc59aa1ecull, 0x3636ee36adb482d8ull, - 0x6464e9640745218dull, 0x6d6dc46d4f731ea9ull, 0xdcdc8bdcaef22e57ull, 0xf0f017f0d31aeae7ull, - 0x59592059f2cb9279ull, 0xa9a937a921d1789eull, 0x4c4c614c5ab5f92dull, 0x17174b17b872655cull, - 0x7f7f9e7fdf1f60e1ull, 0x9191ef91fc41d07eull, 0xb8b862b8a9b70fdaull, 0xc9c9cac9068c4503ull, - 0x5757165782efb841ull, 0x1b1b771bd85a416cull, 0xe0e047e0537a9aa7ull, 0x6161f8612f5b3a99ull - } -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/md5_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/md5_constants.hpp deleted file mode 100644 index 0a9d3d1..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/md5_constants.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_MD5_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_MD5_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct md5_constants -{ - const static uint32_t K[64]; - const static unsigned char S[64]; -}; - -template -const uint32_t md5_constants::K[64] = { - 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, - 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, - 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, - 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, - 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, - 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, - 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, - 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 -}; - -template -const unsigned char md5_constants::S[64] = { - 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, - 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha1_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha1_constants.hpp deleted file mode 100644 index 3a273a1..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha1_constants.hpp +++ /dev/null @@ -1,29 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SHA1_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_SHA1_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct sha1_constants -{ - const static uint32_t K[4]; -}; - -template -const uint32_t sha1_constants::K[4] = { - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha2_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha2_constants.hpp deleted file mode 100644 index 8d826cb..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha2_constants.hpp +++ /dev/null @@ -1,66 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SHA2_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_SHA2_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct sha512_constants -{ - const static uint64_t K[80]; -}; - -template -const uint64_t sha512_constants::K[80] = { - 0x428a2f98d728ae22ull, 0x7137449123ef65cdull, 0xb5c0fbcfec4d3b2full, 0xe9b5dba58189dbbcull, - 0x3956c25bf348b538ull, 0x59f111f1b605d019ull, 0x923f82a4af194f9bull, 0xab1c5ed5da6d8118ull, - 0xd807aa98a3030242ull, 0x12835b0145706fbeull, 0x243185be4ee4b28cull, 0x550c7dc3d5ffb4e2ull, - 0x72be5d74f27b896full, 0x80deb1fe3b1696b1ull, 0x9bdc06a725c71235ull, 0xc19bf174cf692694ull, - 0xe49b69c19ef14ad2ull, 0xefbe4786384f25e3ull, 0x0fc19dc68b8cd5b5ull, 0x240ca1cc77ac9c65ull, - 0x2de92c6f592b0275ull, 0x4a7484aa6ea6e483ull, 0x5cb0a9dcbd41fbd4ull, 0x76f988da831153b5ull, - 0x983e5152ee66dfabull, 0xa831c66d2db43210ull, 0xb00327c898fb213full, 0xbf597fc7beef0ee4ull, - 0xc6e00bf33da88fc2ull, 0xd5a79147930aa725ull, 0x06ca6351e003826full, 0x142929670a0e6e70ull, - 0x27b70a8546d22ffcull, 0x2e1b21385c26c926ull, 0x4d2c6dfc5ac42aedull, 0x53380d139d95b3dfull, - 0x650a73548baf63deull, 0x766a0abb3c77b2a8ull, 0x81c2c92e47edaee6ull, 0x92722c851482353bull, - 0xa2bfe8a14cf10364ull, 0xa81a664bbc423001ull, 0xc24b8b70d0f89791ull, 0xc76c51a30654be30ull, - 0xd192e819d6ef5218ull, 0xd69906245565a910ull, 0xf40e35855771202aull, 0x106aa07032bbd1b8ull, - 0x19a4c116b8d2d0c8ull, 0x1e376c085141ab53ull, 0x2748774cdf8eeb99ull, 0x34b0bcb5e19b48a8ull, - 0x391c0cb3c5c95a63ull, 0x4ed8aa4ae3418acbull, 0x5b9cca4f7763e373ull, 0x682e6ff3d6b2b8a3ull, - 0x748f82ee5defb2fcull, 0x78a5636f43172f60ull, 0x84c87814a1f0ab72ull, 0x8cc702081a6439ecull, - 0x90befffa23631e28ull, 0xa4506cebde82bde9ull, 0xbef9a3f7b2c67915ull, 0xc67178f2e372532bull, - 0xca273eceea26619cull, 0xd186b8c721c0c207ull, 0xeada7dd6cde0eb1eull, 0xf57d4f7fee6ed178ull, - 0x06f067aa72176fbaull, 0x0a637dc5a2c898a6ull, 0x113f9804bef90daeull, 0x1b710b35131c471bull, - 0x28db77f523047d84ull, 0x32caab7b40c72493ull, 0x3c9ebe0a15c9bebcull, 0x431d67c49c100d4cull, - 0x4cc5d4becb3e42b6ull, 0x597f299cfc657e2aull, 0x5fcb6fab3ad6faecull, 0x6c44198c4a475817ull -}; - -template -struct sha256_constants -{ - const static uint32_t K[64]; -}; - -template -const uint32_t sha256_constants::K[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha3_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha3_constants.hpp deleted file mode 100644 index ff4c838..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/sha3_constants.hpp +++ /dev/null @@ -1,35 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SHA3_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_SHA3_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct sha3_constants -{ - const static uint64_t RC[24]; -}; - -template -const uint64_t sha3_constants::RC[24] = { - 0x0000000000000001ull, 0x0000000000008082ull, 0x800000000000808Aull, 0x8000000080008000ull, - 0x000000000000808Bull, 0x0000000080000001ull, 0x8000000080008081ull, 0x8000000000008009ull, - 0x000000000000008Aull, 0x0000000000000088ull, 0x0000000080008009ull, 0x000000008000000Aull, - 0x000000008000808Bull, 0x800000000000008Bull, 0x8000000000008089ull, 0x8000000000008003ull, - 0x8000000000008002ull, 0x8000000000000080ull, 0x000000000000800Aull, 0x800000008000000Aull, - 0x8000000080008081ull, 0x8000000000008080ull, 0x0000000080000001ull, 0x8000000080008008ull -}; - - -} // namespace detail - -} // namespace digestpp - -#endif // DIGESTPP_PROVIDERS_SHA3_CONSTANTS_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/skein_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/skein_constants.hpp deleted file mode 100644 index 223ccf1..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/skein_constants.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SKEIN_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_SKEIN_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct skein_constants -{ - const static unsigned C4[8][2]; - const static unsigned C8[8][4]; - const static unsigned C16[8][8]; - const static unsigned I4[8][4]; - const static unsigned I8[8][8]; - const static unsigned I16[8][16]; -}; - -template -const unsigned skein_constants::C4[8][2] = { - { 14, 16 }, { 52, 57 }, { 23, 40 }, { 5, 37 }, { 25, 33 }, { 46, 12 }, { 58, 22 }, { 32, 32 } -}; - -template -const unsigned skein_constants::C8[8][4] = { - { 46, 36, 19, 37 }, { 33, 27, 14, 42 }, { 17, 49, 36, 39 }, { 44, 9, 54, 56 }, - { 39, 30, 34, 24 }, { 13, 50, 10, 17 }, { 25, 29, 39, 43 }, { 8, 35, 56, 22 } -}; - -template -const unsigned skein_constants::C16[8][8]= { - { 24, 13, 8, 47, 8, 17, 22, 37 }, { 38, 19, 10, 55, 49, 18, 23, 52 }, - { 33, 4, 51, 13, 34, 41, 59, 17 }, { 5, 20, 48, 41, 47, 28, 16, 25 }, - { 41, 9, 37, 31, 12, 47, 44, 30 }, { 16, 34, 56, 51, 4, 53, 42, 41 }, - { 31, 44, 47, 46, 19, 42, 44, 25 }, { 9, 48, 35, 52, 23, 31, 37, 20 } - -}; - -template -const unsigned skein_constants::I4[8][4]= { - { 0, 1, 2, 3 }, { 0, 3, 2, 1 }, { 0, 1, 2, 3 }, { 0, 3, 2, 1 }, - { 0, 1, 2, 3 }, { 0, 3, 2, 1 }, { 0, 1, 2, 3 }, { 0, 3, 2, 1 } -}; - -template -const unsigned skein_constants::I8[8][8]= { - { 0, 1, 2, 3, 4, 5, 6, 7 }, { 2, 1, 4, 7, 6, 5, 0, 3 }, - { 4, 1, 6, 3, 0, 5, 2, 7 }, { 6, 1, 0, 7, 2, 5, 4, 3 }, - { 0, 1, 2, 3, 4, 5, 6, 7 }, { 2, 1, 4, 7, 6, 5, 0, 3 }, - { 4, 1, 6, 3, 0, 5, 2, 7 }, { 6, 1, 0, 7, 2, 5, 4, 3 } -}; - -template -const unsigned skein_constants::I16[8][16] = { - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - { 0, 9, 2, 13, 6, 11, 4, 15, 10, 7, 12, 3, 14, 5, 8, 1 }, - { 0, 7, 2, 5, 4, 3, 6, 1, 12, 15, 14, 13, 8, 11, 10, 9 }, - { 0, 15, 2, 11, 6, 13, 4, 9, 14, 1, 8, 5, 10, 3, 12, 7 }, - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - { 0, 9, 2, 13, 6, 11, 4, 15, 10, 7, 12, 3, 14, 5, 8, 1 }, - { 0, 7, 2, 5, 4, 3, 6, 1, 12, 15, 14, 13, 8, 11, 10, 9 }, - { 0, 15, 2, 11, 6, 13, 4, 9, 14, 1, 8, 5, 10, 3, 12, 7 } -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/streebog_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/streebog_constants.hpp deleted file mode 100644 index 09eddee..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/streebog_constants.hpp +++ /dev/null @@ -1,586 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_STREEBOG_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_STREEBOG_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct streebog_constants -{ - static const uint64_t T[8][256]; - static const uint64_t RC[12][8]; -}; - -template -const uint64_t streebog_constants::T[8][256] = { - { - 0xd01f715b5c7ef8e6ull, 0x16fa240980778325ull, 0xa8a42e857ee049c8ull, 0x6ac1068fa186465bull, - 0x6e417bd7a2e9320bull, 0x665c8167a437daabull, 0x7666681aa89617f6ull, 0x4b959163700bdcf5ull, - 0xf14be6b78df36248ull, 0xc585bd689a625cffull, 0x9557d7fca67d82cbull, 0x89f0b969af6dd366ull, - 0xb0833d48749f6c35ull, 0xa1998c23b1ecbc7cull, 0x8d70c431ac02a736ull, 0xd6dfbc2fd0a8b69eull, - 0x37aeb3e551fa198bull, 0x0b7d128a40b5cf9cull, 0x5a8f2008b5780cbcull, 0xedec882284e333e5ull, - 0xd25fc177d3c7c2ceull, 0x5e0f5d50b61778ecull, 0x1d873683c0c24cb9ull, 0xad040bcbb45d208cull, - 0x2f89a0285b853c76ull, 0x5732fff6791b8d58ull, 0x3e9311439ef6ec3full, 0xc9183a809fd3c00full, - 0x83adf3f5260a01eeull, 0xa6791941f4e8ef10ull, 0x103ae97d0ca1cd5dull, 0x2ce948121dee1b4aull, - 0x39738421dbf2bf53ull, 0x093da2a6cf0cf5b4ull, 0xcd9847d89cbcb45full, 0xf9561c078b2d8ae8ull, - 0x9c6a755a6971777full, 0xbc1ebaa0712ef0c5ull, 0x72e61542abf963a6ull, 0x78bb5fde229eb12eull, - 0x14ba94250fceb90dull, 0x844d6697630e5282ull, 0x98ea08026a1e032full, 0xf06bbea144217f5cull, - 0xdb6263d11ccb377aull, 0x641c314b2b8ee083ull, 0x320e96ab9b4770cfull, 0x1ee7deb986a96b85ull, - 0xe96cf57a878c47b5ull, 0xfdd6615f8842feb8ull, 0xc83862965601dd1bull, 0x2ea9f83e92572162ull, - 0xf876441142ff97fcull, 0xeb2c455608357d9dull, 0x5612a7e0b0c9904cull, 0x6c01cbfb2d500823ull, - 0x4548a6a7fa037a2dull, 0xabc4c6bf388b6ef4ull, 0xbade77d4fdf8bebdull, 0x799b07c8eb4cac3aull, - 0x0c9d87e805b19cf0ull, 0xcb588aac106afa27ull, 0xea0c1d40c1e76089ull, 0x2869354a1e816f1aull, - 0xff96d17307fbc490ull, 0x9f0a9d602f1a5043ull, 0x96373fc6e016a5f7ull, 0x5292dab8b3a6e41cull, - 0x9b8ae0382c752413ull, 0x4f15ec3b7364a8a5ull, 0x3fb349555724f12bull, 0xc7c50d4415db66d7ull, - 0x92b7429ee379d1a7ull, 0xd37f99611a15dfdaull, 0x231427c05e34a086ull, 0xa439a96d7b51d538ull, - 0xb403401077f01865ull, 0xdda2aea5901d7902ull, 0x0a5d4a9c8967d288ull, 0xc265280adf660f93ull, - 0x8bb0094520d4e94eull, 0x2a29856691385532ull, 0x42a833c5bf072941ull, 0x73c64d54622b7eb2ull, - 0x07e095624504536cull, 0x8a905153e906f45aull, 0x6f6123c16b3b2f1full, 0xc6e55552dc097bc3ull, - 0x4468feb133d16739ull, 0xe211e7f0c7398829ull, 0xa2f96419f7879b40ull, 0x19074bdbc3ad38e9ull, - 0xf4ebc3f9474e0b0cull, 0x43886bd376d53455ull, 0xd8028beb5aa01046ull, 0x51f23282f5cdc320ull, - 0xe7b1c2be0d84e16dull, 0x081dfab006dee8a0ull, 0x3b33340d544b857bull, 0x7f5bcabc679ae242ull, - 0x0edd37c48a08a6d8ull, 0x81ed43d9a9b33bc6ull, 0xb1a3655ebd4d7121ull, 0x69a1eeb5e7ed6167ull, - 0xf6ab73d5c8f73124ull, 0x1a67a3e185c61fd5ull, 0x2dc91004d43c065eull, 0x0240b02c8fb93a28ull, - 0x90f7f2b26cc0eb8full, 0x3cd3a16f114fd617ull, 0xaae49ea9f15973e0ull, 0x06c0cd748cd64e78ull, - 0xda423bc7d5192a6eull, 0xc345701c16b41287ull, 0x6d2193ede4821537ull, 0xfcf639494190e3acull, - 0x7c3b228621f1c57eull, 0xfb16ac2b0494b0c0ull, 0xbf7e529a3745d7f9ull, 0x6881b6a32e3f7c73ull, - 0xca78d2bad9b8e733ull, 0xbbfe2fc2342aa3a9ull, 0x0dbddffecc6381e4ull, 0x70a6a56e2440598eull, - 0xe4d12a844befc651ull, 0x8c509c2765d0ba22ull, 0xee8c6018c28814d9ull, 0x17da7c1f49a59e31ull, - 0x609c4c1328e194d3ull, 0xb3e3d57232f44b09ull, 0x91d7aaa4a512f69bull, 0x0ffd6fd243dabbccull, - 0x50d26a943c1fde34ull, 0x6be15e9968545b4full, 0x94778fea6faf9fdfull, 0x2b09dd7058ea4826ull, - 0x677cd9716de5c7bfull, 0x49d5214fffb2e6ddull, 0x0360e83a466b273cull, 0x1fc786af4f7b7691ull, - 0xa0b9d435783ea168ull, 0xd49f0c035f118cb6ull, 0x01205816c9d21d14ull, 0xac2453dd7d8f3d98ull, - 0x545217cc3f70aa64ull, 0x26b4028e9489c9c2ull, 0xdec2469fd6765e3eull, 0x04807d58036f7450ull, - 0xe5f17292823ddb45ull, 0xf30b569b024a5860ull, 0x62dcfc3fa758aefbull, 0xe84cad6c4e5e5aa1ull, - 0xccb81fce556ea94bull, 0x53b282ae7a74f908ull, 0x1b47fbf74c1402c1ull, 0x368eebf39828049full, - 0x7afbeff2ad278b06ull, 0xbe5e0a8cfe97caedull, 0xcfd8f7f413058e77ull, 0xf78b2bc301252c30ull, - 0x4d555c17fcdd928dull, 0x5f2f05467fc565f8ull, 0x24f4b2a21b30f3eaull, 0x860dd6bbecb768aaull, - 0x4c750401350f8f99ull, 0x0000000000000000ull, 0xecccd0344d312ef1ull, 0xb5231806be220571ull, - 0xc105c030990d28afull, 0x653c695de25cfd97ull, 0x159acc33c61ca419ull, 0xb89ec7f872418495ull, - 0xa9847693b73254dcull, 0x58cf90243ac13694ull, 0x59efc832f3132b80ull, 0x5c4fed7c39ae42c4ull, - 0x828dabe3efd81cfaull, 0xd13f294d95ace5f2ull, 0x7d1b7a90e823d86aull, 0xb643f03cf849224dull, - 0x3df3f979d89dcb03ull, 0x7426d836272f2ddeull, 0xdfe21e891fa4432aull, 0x3a136c1b9d99986full, - 0xfa36f43dcd46add4ull, 0xc025982650df35bbull, 0x856d3e81aadc4f96ull, 0xc4a5e57e53b041ebull, - 0x4708168b75ba4005ull, 0xaf44bbe73be41aa4ull, 0x971767d029c4b8e3ull, 0xb9be9feebb939981ull, - 0x215497ecd18d9aaeull, 0x316e7e91dd2c57f3ull, 0xcef8afe2dad79363ull, 0x3853dc371220a247ull, - 0x35ee03c9de4323a3ull, 0xe6919aa8c456fc79ull, 0xe05157dc4880b201ull, 0x7bdbb7e464f59612ull, - 0x127a59518318f775ull, 0x332ecebd52956ddbull, 0x8f30741d23bb9d1eull, 0xd922d3fd93720d52ull, - 0x7746300c61440ae2ull, 0x25d4eab4d2e2eefeull, 0x75068020eefd30caull, 0x135a01474acaea61ull, - 0x304e268714fe4ae7ull, 0xa519f17bb283c82cull, 0xdc82f6b359cf6416ull, 0x5baf781e7caa11a8ull, - 0xb2c38d64fb26561dull, 0x34ce5bdf17913eb7ull, 0x5d6fb56af07c5fd0ull, 0x182713cd0a7f25fdull, - 0x9e2ac576e6c84d57ull, 0x9aaab82ee5a73907ull, 0xa3d93c0f3e558654ull, 0x7e7b92aaae48ff56ull, - 0x872d8ead256575beull, 0x41c8dbfff96c0e7dull, 0x99ca5014a3cc1e3bull, 0x40e883e930be1369ull, - 0x1ca76e95091051adull, 0x4e35b42dbab6b5b1ull, 0x05a0254ecabd6944ull, 0xe1710fca8152af15ull, - 0xf22b0e8dcb984574ull, 0xb763a82a319b3f59ull, 0x63fca4296e8ab3efull, 0x9d4a2d4ca0a36a6bull, - 0xe331bfe60eeb953dull, 0xd5bf541596c391a2ull, 0xf5cb9bef8e9c1618ull, 0x46284e9dbc685d11ull, - 0x2074cffa185f87baull, 0xbd3ee2b6b8fcedd1ull, 0xae64e3f1f23607b0ull, 0xfeb68965ce29d984ull, - 0x55724fdaf6a2b770ull, 0x29496d5cd753720eull, 0xa75941573d3af204ull, 0x8e102c0bea69800aull, - 0x111ab16bc573d049ull, 0xd7ffe439197aab8aull, 0xefac380e0b5a09cdull, 0x48f579593660fbc9ull, - 0x22347fd697e6bd92ull, 0x61bc1405e13389c7ull, 0x4ab5c975b9d9c1e1ull, 0x80cd1bcf606126d2ull, - 0x7186fd78ed92449aull, 0x93971a882aabccb3ull, 0x88d0e17f66bfce72ull, 0x27945a985d5bd4d6ull - }, - { - 0xde553f8c05a811c8ull, 0x1906b59631b4f565ull, 0x436e70d6b1964ff7ull, 0x36d343cb8b1e9d85ull, - 0x843dfacc858aab5aull, 0xfdfc95c299bfc7f9ull, 0x0f634bdea1d51fa2ull, 0x6d458b3b76efb3cdull, - 0x85c3f77cf8593f80ull, 0x3c91315fbe737cb2ull, 0x2148b03366ace398ull, 0x18f8b8264c6761bfull, - 0xc830c1c495c9fb0full, 0x981a76102086a0aaull, 0xaa16012142f35760ull, 0x35cc54060c763cf6ull, - 0x42907d66cc45db2dull, 0x8203d44b965af4bcull, 0x3d6f3cefc3a0e868ull, 0xbc73ff69d292bda7ull, - 0x8722ed0102e20a29ull, 0x8f8185e8cd34deb7ull, 0x9b0561dda7ee01d9ull, 0x5335a0193227fad6ull, - 0xc9cecc74e81a6fd5ull, 0x54f5832e5c2431eaull, 0x99e47ba05d553470ull, 0xf7bee756acd226ceull, - 0x384e05a5571816fdull, 0xd1367452a47d0e6aull, 0xf29fde1c386ad85bull, 0x320c77316275f7caull, - 0xd0c879e2d9ae9ab0ull, 0xdb7406c69110ef5dull, 0x45505e51a2461011ull, 0xfc029872e46c5323ull, - 0xfa3cb6f5f7bc0cc5ull, 0x031f17cd8768a173ull, 0xbd8df2d9af41297dull, 0x9d3b4f5ab43e5e3full, - 0x4071671b36feee84ull, 0x716207e7d3e3b83dull, 0x48d20ff2f9283a1aull, 0x27769eb4757cbc7eull, - 0x5c56ebc793f2e574ull, 0xa48b474f9ef5dc18ull, 0x52cbada94ff46e0cull, 0x60c7da982d8199c6ull, - 0x0e9d466edc068b78ull, 0x4eec2175eaf865fcull, 0x550b8e9e21f7a530ull, 0x6b7ba5bc653fec2bull, - 0x5eb7f1ba6949d0ddull, 0x57ea94e3db4c9099ull, 0xf640eae6d101b214ull, 0xdd4a284182c0b0bbull, - 0xff1d8fbf6304f250ull, 0xb8accb933bf9d7e8ull, 0xe8867c478eb68c4dull, 0x3f8e2692391bddc1ull, - 0xcb2fd60912a15a7cull, 0xaec935dbab983d2full, 0xf55ffd2b56691367ull, 0x80e2ce366ce1c115ull, - 0x179bf3f8edb27e1dull, 0x01fe0db07dd394daull, 0xda8a0b76ecc37b87ull, 0x44ae53e1df9584cbull, - 0xb310b4b77347a205ull, 0xdfab323c787b8512ull, 0x3b511268d070b78eull, 0x65e6e3d2b9396753ull, - 0x6864b271e2574d58ull, 0x259784c98fc789d7ull, 0x02e11a7dfabb35a9ull, 0x8841a6dfa337158bull, - 0x7ade78c39b5dcdd0ull, 0xb7cf804d9a2cc84aull, 0x20b6bd831b7f7742ull, 0x75bd331d3a88d272ull, - 0x418f6aab4b2d7a5eull, 0xd9951cbb6babdaf4ull, 0xb6318dfde7ff5c90ull, 0x1f389b112264aa83ull, - 0x492c024284fbaec0ull, 0xe33a0363c608f9a0ull, 0x2688930408af28a4ull, 0xc7538a1a341ce4adull, - 0x5da8e677ee2171aeull, 0x8c9e92254a5c7fc4ull, 0x63d8cd55aae938b5ull, 0x29ebd8daa97a3706ull, - 0x959827b37be88aa1ull, 0x1484e4356adadf6eull, 0xa7945082199d7d6bull, 0xbf6ce8a455fa1cd4ull, - 0x9cc542eac9edcae5ull, 0x79c16f0e1c356ca3ull, 0x89bfab6fdee48151ull, 0xd4174d1830c5f0ffull, - 0x9258048415eb419dull, 0x6139d72850520d1cull, 0x6a85a80c18ec78f1ull, 0xcd11f88e0171059aull, - 0xcceff53e7ca29140ull, 0xd229639f2315af19ull, 0x90b91ef9ef507434ull, 0x5977d28d074a1be1ull, - 0x311360fce51d56b9ull, 0xc093a92d5a1f2f91ull, 0x1a19a25bb6dc5416ull, 0xeb996b8a09de2d3eull, - 0xfee3820f1ed7668aull, 0xd7085ad5b7ad518cull, 0x7fff41890fe53345ull, 0xec5948bd67dde602ull, - 0x2fd5f65dbaaa68e0ull, 0xa5754affe32648c2ull, 0xf8ddac880d07396cull, 0x6fa491468c548664ull, - 0x0c7c5c1326bdbed1ull, 0x4a33158f03930fb3ull, 0x699abfc19f84d982ull, 0xe4fa2054a80b329cull, - 0x6707f9af438252faull, 0x08a368e9cfd6d49eull, 0x47b1442c58fd25b8ull, 0xbbb3dc5ebc91769bull, - 0x1665fe489061eac7ull, 0x33f27a811fa66310ull, 0x93a609346838d547ull, 0x30ed6d4c98cec263ull, - 0x1dd9816cd8df9f2aull, 0x94662a03063b1e7bull, 0x83fdd9fbeb896066ull, 0x7b207573e68e590aull, - 0x5f49fc0a149a4407ull, 0x343259b671a5a82cull, 0xfbc2bb458a6f981full, 0xc272b350a0a41a38ull, - 0x3aaf1fd8ada32354ull, 0x6cbb868b0b3c2717ull, 0xa2b569c88d2583feull, 0xf180c9d1bf027928ull, - 0xaf37386bd64ba9f5ull, 0x12bacab2790a8088ull, 0x4c0d3b0810435055ull, 0xb2eeb9070e9436dfull, - 0xc5b29067cea7d104ull, 0xdcb425f1ff132461ull, 0x4f122cc5972bf126ull, 0xac282fa651230886ull, - 0xe7e537992f6393efull, 0xe61b3a2952b00735ull, 0x709c0a57ae302ce7ull, 0xe02514ae416058d3ull, - 0xc44c9dd7b37445deull, 0x5a68c5408022ba92ull, 0x1c278cdca50c0bf0ull, 0x6e5a9cf6f18712beull, - 0x86dce0b17f319ef3ull, 0x2d34ec2040115d49ull, 0x4bcd183f7e409b69ull, 0x2815d56ad4a9a3dcull, - 0x24698979f2141d0dull, 0x0000000000000000ull, 0x1ec696a15fb73e59ull, 0xd86b110b16784e2eull, - 0x8e7f8858b0e74a6dull, 0x063e2e8713d05fe6ull, 0xe2c40ed3bbdb6d7aull, 0xb1f1aeca89fc97acull, - 0xe1db191e3cb3cc09ull, 0x6418ee62c4eaf389ull, 0xc6ad87aa49cf7077ull, 0xd6f65765ca7ec556ull, - 0x9afb6c6dda3d9503ull, 0x7ce05644888d9236ull, 0x8d609f95378feb1eull, 0x23a9aa4e9c17d631ull, - 0x6226c0e5d73aac6full, 0x56149953a69f0443ull, 0xeeb852c09d66d3abull, 0x2b0ac2a753c102afull, - 0x07c023376e03cb3cull, 0x2ccae1903dc2c993ull, 0xd3d76e2f5ec63bc3ull, 0x9e2458973356ff4cull, - 0xa66a5d32644ee9b1ull, 0x0a427294356de137ull, 0x783f62be61e6f879ull, 0x1344c70204d91452ull, - 0x5b96c8f0fdf12e48ull, 0xa90916ecc59bf613ull, 0xbe92e5142829880eull, 0x727d102a548b194eull, - 0x1be7afebcb0fc0ccull, 0x3e702b2244c8491bull, 0xd5e940a84d166425ull, 0x66f9f41f3e51c620ull, - 0xabe80c913f20c3baull, 0xf07ec461c2d1edf2ull, 0xf361d3ac45b94c81ull, 0x0521394a94b8fe95ull, - 0xadd622162cf09c5cull, 0xe97871f7f3651897ull, 0xf4a1f09b2bba87bdull, 0x095d6559b2054044ull, - 0x0bbc7f2448be75edull, 0x2af4cf172e129675ull, 0x157ae98517094bb4ull, 0x9fda55274e856b96ull, - 0x914713499283e0eeull, 0xb952c623462a4332ull, 0x74433ead475b46a8ull, 0x8b5eb112245fb4f8ull, - 0xa34b6478f0f61724ull, 0x11a5dd7ffe6221fbull, 0xc16da49d27ccbb4bull, 0x76a224d0bde07301ull, - 0x8aa0bca2598c2022ull, 0x4df336b86d90c48full, 0xea67663a740db9e4ull, 0xef465f70e0b54771ull, - 0x39b008152acb8227ull, 0x7d1e5bf4f55e06ecull, 0x105bd0cf83b1b521ull, 0x775c2960c033e7dbull, - 0x7e014c397236a79full, 0x811cc386113255cfull, 0xeda7450d1a0e72d8ull, 0x5889df3d7a998f3bull, - 0x2e2bfbedc779fc3aull, 0xce0eef438619a4e9ull, 0x372d4e7bf6cd095full, 0x04df34fae96b6a4full, - 0xf923a13870d4adb6ull, 0xa1aa7e050a4d228dull, 0xa8f71b5cb84862c9ull, 0xb52e9a306097fde3ull, - 0x0d8251a35b6e2a0bull, 0x2257a7fee1c442ebull, 0x73831d9a29588d94ull, 0x51d4ba64c89ccf7full, - 0x502ab7d4b54f5ba5ull, 0x97793dce8153bf08ull, 0xe5042de4d5d8a646ull, 0x9687307efc802bd2ull, - 0xa05473b5779eb657ull, 0xb4d097801d446939ull, 0xcff0e2f3fbca3033ull, 0xc38cbee0dd778ee2ull, - 0x464f499c252eb162ull, 0xcad1dbb96f72cea6ull, 0xba4dd1eec142e241ull, 0xb00fa37af42f0376ull - }, - { - 0xcce4cd3aa968b245ull, 0x089d5484e80b7fafull, 0x638246c1b3548304ull, 0xd2fe0ec8c2355492ull, - 0xa7fbdf7ff2374eeeull, 0x4df1600c92337a16ull, 0x84e503ea523b12fbull, 0x0790bbfd53ab0c4aull, - 0x198a780f38f6ea9dull, 0x2ab30c8f55ec48cbull, 0xe0f7fed6b2c49db5ull, 0xb6ecf3f422cadbdcull, - 0x409c9a541358df11ull, 0xd3ce8a56dfde3fe3ull, 0xc3e9224312c8c1a0ull, 0x0d6dfa58816ba507ull, - 0xddf3e1b179952777ull, 0x04c02a42748bb1d9ull, 0x94c2abff9f2decb8ull, 0x4f91752da8f8acf4ull, - 0x78682befb169bf7bull, 0xe1c77a48af2ff6c4ull, 0x0c5d7ec69c80ce76ull, 0x4cc1e4928fd81167ull, - 0xfeed3d24d9997b62ull, 0x518bb6dfc3a54a23ull, 0x6dbf2d26151f9b90ull, 0xb5bc624b05ea664full, - 0xe86aaa525acfe21aull, 0x4801ced0fb53a0beull, 0xc91463e6c00868edull, 0x1027a815cd16fe43ull, - 0xf67069a0319204cdull, 0xb04ccc976c8abce7ull, 0xc0b9b3fc35e87c33ull, 0xf380c77c58f2de65ull, - 0x50bb3241de4e2152ull, 0xdf93f490435ef195ull, 0xf1e0d25d62390887ull, 0xaf668bfb1a3c3141ull, - 0xbc11b251f00a7291ull, 0x73a5eed47e427d47ull, 0x25bee3f6ee4c3b2eull, 0x43cc0beb34786282ull, - 0xc824e778dde3039cull, 0xf97d86d98a327728ull, 0xf2b043e24519b514ull, 0xe297ebf7880f4b57ull, - 0x3a94a49a98fab688ull, 0x868516cb68f0c419ull, 0xeffa11af0964ee50ull, 0xa4ab4ec0d517f37dull, - 0xa9c6b498547c567aull, 0x8e18424f80fbbbb6ull, 0x0bcdc53bcf2bc23cull, 0x137739aaea3643d0ull, - 0x2c1333ec1bac2ff0ull, 0x8d48d3f0a7db0625ull, 0x1e1ac3f26b5de6d7ull, 0xf520f81f16b2b95eull, - 0x9f0f6ec450062e84ull, 0x0130849e1deb6b71ull, 0xd45e31ab8c7533a9ull, 0x652279a2fd14e43full, - 0x3209f01e70f1c927ull, 0xbe71a770cac1a473ull, 0x0e3d6be7a64b1894ull, 0x7ec8148cff29d840ull, - 0xcb7476c7fac3be0full, 0x72956a4a63a91636ull, 0x37f95ec21991138full, 0x9e3fea5a4ded45f5ull, - 0x7b38ba50964902e8ull, 0x222e580bbde73764ull, 0x61e253e0899f55e6ull, 0xfc8d2805e352ad80ull, - 0x35994be3235ac56dull, 0x09add01af5e014deull, 0x5e8659a6780539c6ull, 0xb17c48097161d796ull, - 0x026015213acbd6e2ull, 0xd1ae9f77e515e901ull, 0xb7dc776a3f21b0adull, 0xaba6a1b96eb78098ull, - 0x9bcf4486248d9f5dull, 0x582666c536455efdull, 0xfdbdac9bfeb9c6f1ull, 0xc47999be4163cdeaull, - 0x765540081722a7efull, 0x3e548ed8ec710751ull, 0x3d041f67cb51bac2ull, 0x7958af71ac82d40aull, - 0x36c9da5c047a78feull, 0xed9a048e33af38b2ull, 0x26ee7249c96c86bdull, 0x900281bdeba65d61ull, - 0x11172c8bd0fd9532ull, 0xea0abf73600434f8ull, 0x42fc8f75299309f3ull, 0x34a9cf7d3eb1ae1cull, - 0x2b838811480723baull, 0x5ce64c8742ceef24ull, 0x1adae9b01fd6570eull, 0x3c349bf9d6bad1b3ull, - 0x82453c891c7b75c0ull, 0x97923a40b80d512bull, 0x4a61dbf1c198765cull, 0xb48ce6d518010d3eull, - 0xcfb45c858e480fd6ull, 0xd933cbf30d1e96aeull, 0xd70ea014ab558e3aull, 0xc189376228031742ull, - 0x9262949cd16d8b83ull, 0xeb3a3bed7def5f89ull, 0x49314a4ee6b8cbcfull, 0xdcc3652f647e4c06ull, - 0xda635a4c2a3e2b3dull, 0x470c21a940f3d35bull, 0x315961a157d174b4ull, 0x6672e81dda3459acull, - 0x5b76f77a1165e36eull, 0x445cb01667d36ec8ull, 0xc5491d205c88a69bull, 0x456c34887a3805b9ull, - 0xffddb9bac4721013ull, 0x99af51a71e4649bfull, 0xa15be01cbc7729d5ull, 0x52db2760e485f7b0ull, - 0x8c78576eba306d54ull, 0xae560f6507d75a30ull, 0x95f22f6182c687c9ull, 0x71c5fbf54489aba5ull, - 0xca44f259e728d57eull, 0x88b87d2ccebbdc8dull, 0xbab18d32be4a15aaull, 0x8be8ec93e99b611eull, - 0x17b713e89ebdf209ull, 0xb31c5d284baa0174ull, 0xeeca9531148f8521ull, 0xb8d198138481c348ull, - 0x8988f9b2d350b7fcull, 0xb9e11c8d996aa839ull, 0x5a4673e40c8e881full, 0x1687977683569978ull, - 0xbf4123eed72acf02ull, 0x4ea1f1b3b513c785ull, 0xe767452be16f91ffull, 0x7505d1b730021a7cull, - 0xa59bca5ec8fc980cull, 0xad069eda20f7e7a3ull, 0x38f4b1bba231606aull, 0x60d2d77e94743e97ull, - 0x9affc0183966f42cull, 0x248e6768f3a7505full, 0xcdd449a4b483d934ull, 0x87b59255751baf68ull, - 0x1bea6d2e023d3c7full, 0x6b1f12455b5ffcabull, 0x743555292de9710dull, 0xd8034f6d10f5fddfull, - 0xc6198c9f7ba81b08ull, 0xbb8109aca3a17edbull, 0xfa2d1766ad12cabbull, 0xc729080166437079ull, - 0x9c5fff7b77269317ull, 0x0000000000000000ull, 0x15d706c9a47624ebull, 0x6fdf38072fd44d72ull, - 0x5fb6dd3865ee52b7ull, 0xa33bf53d86bcff37ull, 0xe657c1b5fc84fa8eull, 0xaa962527735cebe9ull, - 0x39c43525bfda0b1bull, 0x204e4d2a872ce186ull, 0x7a083ece8ba26999ull, 0x554b9c9db72efbfaull, - 0xb22cd9b656416a05ull, 0x96a2bedea5e63a5aull, 0x802529a826b0a322ull, 0x8115ad363b5bc853ull, - 0x8375b81701901eb1ull, 0x3069e53f4a3a1fc5ull, 0xbd2136cfede119e0ull, 0x18bafc91251d81ecull, - 0x1d4a524d4c7d5b44ull, 0x05f0aedc6960daa8ull, 0x29e39d3072ccf558ull, 0x70f57f6b5962c0d4ull, - 0x989fd53903ad22ceull, 0xf84d024797d91c59ull, 0x547b1803aac5908bull, 0xf0d056c37fd263f6ull, - 0xd56eb535919e58d8ull, 0x1c7ad6d351963035ull, 0x2e7326cd2167f912ull, 0xac361a443d1c8cd2ull, - 0x697f076461942a49ull, 0x4b515f6fdc731d2dull, 0x8ad8680df4700a6full, 0x41ac1eca0eb3b460ull, - 0x7d988533d80965d3ull, 0xa8f6300649973d0bull, 0x7765c4960ac9cc9eull, 0x7ca801adc5e20ea2ull, - 0xdea3700e5eb59ae4ull, 0xa06b6482a19c42a4ull, 0x6a2f96db46b497daull, 0x27def6d7d487edccull, - 0x463ca5375d18b82aull, 0xa6cb5be1efdc259full, 0x53eba3fef96e9cc1ull, 0xce84d81b93a364a7ull, - 0xf4107c810b59d22full, 0x333974806d1aa256ull, 0x0f0def79bba073e5ull, 0x231edc95a00c5c15ull, - 0xe437d494c64f2c6cull, 0x91320523f64d3610ull, 0x67426c83c7df32ddull, 0x6eefbc99323f2603ull, - 0x9d6f7be56acdf866ull, 0x5916e25b2bae358cull, 0x7ff89012e2c2b331ull, 0x035091bf2720bd93ull, - 0x561b0d22900e4669ull, 0x28d319ae6f279e29ull, 0x2f43a2533c8c9263ull, 0xd09e1be9f8fe8270ull, - 0xf740ed3e2c796fbcull, 0xdb53ded237d5404cull, 0x62b2c25faebfe875ull, 0x0afd41a5d2c0a94dull, - 0x6412fd3ce0ff8f4eull, 0xe3a76f6995e42026ull, 0x6c8fa9b808f4f0e1ull, 0xc2d9a6dd0f23aad1ull, - 0x8f28c6d19d10d0c7ull, 0x85d587744fd0798aull, 0xa20b71a39b579446ull, 0x684f83fa7c7f4138ull, - 0xe507500adba4471dull, 0x3f640a46f19a6c20ull, 0x1247bd34f7dd28a1ull, 0x2d23b77206474481ull, - 0x93521002cc86e0f2ull, 0x572b89bc8de52d18ull, 0xfb1d93f8b0f9a1caull, 0xe95a2ecc4724896bull, - 0x3ba420048511ddf9ull, 0xd63e248ab6bee54bull, 0x5dd6c8195f258455ull, 0x06a03f634e40673bull, - 0x1f2a476c76b68da6ull, 0x217ec9b49ac78af7ull, 0xecaa80102e4453c3ull, 0x14e78257b99d4f9aull - }, - { - 0x20329b2cc87bba05ull, 0x4f5eb6f86546a531ull, 0xd4f44775f751b6b1ull, 0x8266a47b850dfa8bull, - 0xbb986aa15a6ca985ull, 0xc979eb08f9ae0f99ull, 0x2da6f447a2375ea1ull, 0x1e74275dcd7d8576ull, - 0xbc20180a800bc5f8ull, 0xb4a2f701b2dc65beull, 0xe726946f981b6d66ull, 0x48e6c453bf21c94cull, - 0x42cad9930f0a4195ull, 0xefa47b64aacccd20ull, 0x71180a8960409a42ull, 0x8bb3329bf6a44e0cull, - 0xd34c35de2d36daccull, 0xa92f5b7cbc23dc96ull, 0xb31a85aa68bb09c3ull, 0x13e04836a73161d2ull, - 0xb24dfc4129c51d02ull, 0x8ae44b70b7da5acdull, 0xe671ed84d96579a7ull, 0xa4bb3417d66f3832ull, - 0x4572ab38d56d2de8ull, 0xb1b47761ea47215cull, 0xe81c09cf70aba15dull, 0xffbdb872ce7f90acull, - 0xa8782297fd5dc857ull, 0x0d946f6b6a4ce4a4ull, 0xe4df1f4f5b995138ull, 0x9ebc71edca8c5762ull, - 0x0a2c1dc0b02b88d9ull, 0x3b503c115d9d7b91ull, 0xc64376a8111ec3a2ull, 0xcec199a323c963e4ull, - 0xdc76a87ec58616f7ull, 0x09d596e073a9b487ull, 0x14583a9d7d560dafull, 0xf4c6dc593f2a0cb4ull, - 0xdd21d19584f80236ull, 0x4a4836983ddde1d3ull, 0xe58866a41ae745f9ull, 0xf591a5b27e541875ull, - 0x891dc05074586693ull, 0x5b068c651810a89eull, 0xa30346bc0c08544full, 0x3dbf3751c684032dull, - 0x2a1e86ec785032dcull, 0xf73f5779fca830eaull, 0xb60c05ca30204d21ull, 0x0cc316802b32f065ull, - 0x8770241bdd96be69ull, 0xb861e18199ee95dbull, 0xf805cad91418fcd1ull, 0x29e70dccbbd20e82ull, - 0xc7140f435060d763ull, 0x0f3a9da0e8b0cc3bull, 0xa2543f574d76408eull, 0xbd7761e1c175d139ull, - 0x4b1f4f737ca3f512ull, 0x6dc2df1f2fc137abull, 0xf1d05c3967b14856ull, 0xa742bf3715ed046cull, - 0x654030141d1697edull, 0x07b872abda676c7dull, 0x3ce84eba87fa17ecull, 0xc1fb0403cb79afdfull, - 0x3e46bc7105063f73ull, 0x278ae987121cd678ull, 0xa1adb4778ef47cd0ull, 0x26dd906c5362c2b9ull, - 0x05168060589b44e2ull, 0xfbfc41f9d79ac08full, 0x0e6de44ba9ced8faull, 0x9feb08068bf243a3ull, - 0x7b341749d06b129bull, 0x229c69e74a87929aull, 0xe09ee6c4427c011bull, 0x5692e30e725c4c3aull, - 0xda99a33e5e9f6e4bull, 0x353dd85af453a36bull, 0x25241b4c90e0fee7ull, 0x5de987258309d022ull, - 0xe230140fc0802984ull, 0x93281e86a0c0b3c6ull, 0xf229d719a4337408ull, 0x6f6c2dd4ad3d1f34ull, - 0x8ea5b2fbae3f0aeeull, 0x8331dd90c473ee4aull, 0x346aa1b1b52db7aaull, 0xdf8f235e06042aa9ull, - 0xcc6f6b68a1354b7bull, 0x6c95a6f46ebf236aull, 0x52d31a856bb91c19ull, 0x1a35ded6d498d555ull, - 0xf37eaef2e54d60c9ull, 0x72e181a9a3c2a61cull, 0x98537aad51952fdeull, 0x16f6c856ffaa2530ull, - 0xd960281e9d1d5215ull, 0x3a0745fa1ce36f50ull, 0x0b7b642bf1559c18ull, 0x59a87eae9aec8001ull, - 0x5e100c05408bec7cull, 0x0441f98b19e55023ull, 0xd70dcc5534d38aefull, 0x927f676de1bea707ull, - 0x9769e70db925e3e5ull, 0x7a636ea29115065aull, 0x468b201816ef11b6ull, 0xab81a9b73edff409ull, - 0xc0ac7de88a07bb1eull, 0x1f235eb68c0391b7ull, 0x6056b074458dd30full, 0xbe8eeac102f7ed67ull, - 0xcd381283e04b5fbaull, 0x5cbefecec277c4e3ull, 0xd21b4c356c48ce0dull, 0x1019c31664b35d8cull, - 0x247362a7d19eea26ull, 0xebe582efb3299d03ull, 0x02aef2cb82fc289full, 0x86275df09ce8aaa8ull, - 0x28b07427faac1a43ull, 0x38a9b7319e1f47cfull, 0xc82e92e3b8d01b58ull, 0x06ef0b409b1978bcull, - 0x62f842bfc771fb90ull, 0x9904034610eb3b1full, 0xded85ab5477a3e68ull, 0x90d195a663428f98ull, - 0x5384636e2ac708d8ull, 0xcbd719c37b522706ull, 0xae9729d76644b0ebull, 0x7c8c65e20a0c7ee6ull, - 0x80c856b007f1d214ull, 0x8c0b40302cc32271ull, 0xdbcedad51fe17a8aull, 0x740e8ae938dbdea0ull, - 0xa615c6dc549310adull, 0x19cc55f6171ae90bull, 0x49b1bdb8fe5fdd8dull, 0xed0a89af2830e5bfull, - 0x6a7aadb4f5a65bd6ull, 0x7e22972988f05679ull, 0xf952b3325566e810ull, 0x39fecedadf61530eull, - 0x6101c99f04f3c7ceull, 0x2e5f7f6761b562ffull, 0xf08725d226cf5c97ull, 0x63af3b54860fef51ull, - 0x8ff2cb10ef411e2full, 0x884ab9bb35267252ull, 0x4df04433e7ba8daeull, 0x9afd8866d3690741ull, - 0x66b9bb34de94abb3ull, 0x9baaf18d92171380ull, 0x543c11c5f0a064a5ull, 0x17a1b1bdbed431f1ull, - 0xb5f58eeaf3a2717full, 0xc355f6c849858740ull, 0xec5df044694ef17eull, 0xd83751f5dc6346d4ull, - 0xfc4433520dfdacf2ull, 0x0000000000000000ull, 0x5a51f58e596ebc5full, 0x3285aaf12e34cf16ull, - 0x8d5c39db6dbd36b0ull, 0x12b731dde64f7513ull, 0x94906c2d7aa7dfbbull, 0x302b583aacc8e789ull, - 0x9d45facd090e6b3cull, 0x2165e2c78905aec4ull, 0x68d45f7f775a7349ull, 0x189b2c1d5664fdcaull, - 0xe1c99f2f030215daull, 0x6983269436246788ull, 0x8489af3b1e148237ull, 0xe94b702431d5b59cull, - 0x33d2d31a6f4adbd7ull, 0xbfd9932a4389f9a6ull, 0xb0e30e8aab39359dull, 0xd1e2c715afcaf253ull, - 0x150f43763c28196eull, 0xc4ed846393e2eb3dull, 0x03f98b20c3823c5eull, 0xfd134ab94c83b833ull, - 0x556b682eb1de7064ull, 0x36c4537a37d19f35ull, 0x7559f30279a5ca61ull, 0x799ae58252973a04ull, - 0x9c12832648707ffdull, 0x78cd9c6913e92ec5ull, 0x1d8dac7d0effb928ull, 0x439da0784e745554ull, - 0x413352b3cc887dcbull, 0xbacf134a1b12bd44ull, 0x114ebafd25cd494dull, 0x2f08068c20cb763eull, - 0x76a07822ba27f63full, 0xeab2fb04f25789c2ull, 0xe3676de481fe3d45ull, 0x1b62a73d95e6c194ull, - 0x641749ff5c68832cull, 0xa5ec4dfc97112cf3ull, 0xf6682e92bdd6242bull, 0x3f11c59a44782bb2ull, - 0x317c21d1edb6f348ull, 0xd65ab5be75ad9e2eull, 0x6b2dd45fb4d84f17ull, 0xfaab381296e4d44eull, - 0xd0b5befeeeb4e692ull, 0x0882ef0b32d7a046ull, 0x512a91a5a83b2047ull, 0x963e9ee6f85bf724ull, - 0x4e09cf132438b1f0ull, 0x77f701c9fb59e2feull, 0x7ddb1c094b726a27ull, 0x5f4775ee01f5f8bdull, - 0x9186ec4d223c9b59ull, 0xfeeac1998f01846dull, 0xac39db1ce4b89874ull, 0xb75b7c21715e59e0ull, - 0xafc0503c273aa42aull, 0x6e3b543fec430bf5ull, 0x704f7362213e8e83ull, 0x58ff0745db9294c0ull, - 0x67eec2df9feabf72ull, 0xa0facd9ccf8a6811ull, 0xb936986ad890811aull, 0x95c715c63bd9cb7aull, - 0xca8060283a2c33c7ull, 0x507de84ee9453486ull, 0x85ded6d05f6a96f6ull, 0x1cdad5964f81ade9ull, - 0xd5a33e9eb62fa270ull, 0x40642b588df6690aull, 0x7f75eec2c98e42b8ull, 0x2cf18dace3494a60ull, - 0x23cb100c0bf9865bull, 0xeef3028febb2d9e1ull, 0x4425d2d394133929ull, 0xaad6d05c7fa1e0c8ull, - 0xad6ea2f7a5c68cb5ull, 0xc2028f2308fb9381ull, 0x819f2f5b468fc6d5ull, 0xc5bafd88d29cfffcull, - 0x47dc59f357910577ull, 0x2b49ff07392e261dull, 0x57c59ae5332258fbull, 0x73b6f842e2bcb2ddull, - 0xcf96e04862b77725ull, 0x4ca73dd8a6c4996full, 0x015779eb417e14c1ull, 0x37932a9176af8bf4ull - }, - { - 0x190a2c9b249df23eull, 0x2f62f8b62263e1e9ull, 0x7a7f754740993655ull, 0x330b7ba4d5564d9full, - 0x4c17a16a46672582ull, 0xb22f08eb7d05f5b8ull, 0x535f47f40bc148ccull, 0x3aec5d27d4883037ull, - 0x10ed0a1825438f96ull, 0x516101f72c233d17ull, 0x13cc6f949fd04eaeull, 0x739853c441474bfdull, - 0x653793d90d3f5b1bull, 0x5240647b96b0fc2full, 0x0c84890ad27623e0ull, 0xd7189b32703aaea3ull, - 0x2685de3523bd9c41ull, 0x99317c5b11bffefaull, 0x0d9baa854f079703ull, 0x70b93648fbd48ac5ull, - 0xa80441fce30bc6beull, 0x7287704bdc36ff1eull, 0xb65384ed33dc1f13ull, 0xd36417343ee34408ull, - 0x39cd38ab6e1bf10full, 0x5ab861770a1f3564ull, 0x0ebacf09f594563bull, 0xd04572b884708530ull, - 0x3cae9722bdb3af47ull, 0x4a556b6f2f5cbaf2ull, 0xe1704f1f76c4bd74ull, 0x5ec4ed7144c6dfcfull, - 0x16afc01d4c7810e6ull, 0x283f113cd629ca7aull, 0xaf59a8761741ed2dull, 0xeed5a3991e215facull, - 0x3bf37ea849f984d4ull, 0xe413e096a56ce33cull, 0x2c439d3a98f020d1ull, 0x637559dc6404c46bull, - 0x9e6c95d1e5f5d569ull, 0x24bb9836045fe99aull, 0x44efa466dac8ecc9ull, 0xc6eab2a5c80895d6ull, - 0x803b50c035220cc4ull, 0x0321658cba93c138ull, 0x8f9ebc465dc7ee1cull, 0xd15a5137190131d3ull, - 0x0fa5ec8668e5e2d8ull, 0x91c979578d1037b1ull, 0x0642ca05693b9f70ull, 0xefca80168350eb4full, - 0x38d21b24f36a45ecull, 0xbeab81e1af73d658ull, 0x8cbfd9cae7542f24ull, 0xfd19cc0d81f11102ull, - 0x0ac6430fbb4dbc90ull, 0x1d76a09d6a441895ull, 0x2a01573ff1cbbfa1ull, 0xb572e161894fde2bull, - 0x8124734fa853b827ull, 0x614b1fdf43e6b1b0ull, 0x68ac395c4238cc18ull, 0x21d837bfd7f7b7d2ull, - 0x20c714304a860331ull, 0x5cfaab726324aa14ull, 0x74c5ba4eb50d606eull, 0xf3a3030474654739ull, - 0x23e671bcf015c209ull, 0x45f087e947b9582aull, 0xd8bd77b418df4c7bull, 0xe06f6c90ebb50997ull, - 0x0bd96080263c0873ull, 0x7e03f9410e40dcfeull, 0xb8e94be4c6484928ull, 0xfb5b0608e8ca8e72ull, - 0x1a2b49179e0e3306ull, 0x4e29e76961855059ull, 0x4f36c4e6fcf4e4baull, 0x49740ee395cf7bcaull, - 0xc2963ea386d17f7dull, 0x90d65ad810618352ull, 0x12d34c1b02a1fa4dull, 0xfa44258775bb3a91ull, - 0x18150f14b9ec46ddull, 0x1491861e6b9a653dull, 0x9a1019d7ab2c3fc2ull, 0x3668d42d06fe13d7ull, - 0xdcc1fbb25606a6d0ull, 0x969490dd795a1c22ull, 0x3549b1a1bc6dd2efull, 0xc94f5e23a0ed770eull, - 0xb9f6686b5b39fdcbull, 0xc4d4f4a6efeae00dull, 0xe732851a1fff2204ull, 0x94aad6de5eb869f9ull, - 0x3f8ff2ae07206e7full, 0xfe38a9813b62d03aull, 0xa7a1ad7a8bee2466ull, 0x7b6056c8dde882b6ull, - 0x302a1e286fc58ca7ull, 0x8da0fa457a259bc7ull, 0xb3302b64e074415bull, 0x5402ae7eff8b635full, - 0x08f8050c9cafc94bull, 0xae468bf98a3059ceull, 0x88c355cca98dc58full, 0xb10e6d67c7963480ull, - 0xbad70de7e1aa3cf3ull, 0xbfb4a26e320262bbull, 0xcb711820870f02d5ull, 0xce12b7a954a75c9dull, - 0x563ce87dd8691684ull, 0x9f73b65e7884618aull, 0x2b1e74b06cba0b42ull, 0x47cec1ea605b2df1ull, - 0x1c698312f735ac76ull, 0x5fdbcefed9b76b2cull, 0x831a354c8fb1cdfcull, 0x820516c312c0791full, - 0xb74ca762aeadabf0ull, 0xfc06ef821c80a5e1ull, 0x5723cbf24518a267ull, 0x9d4df05d5f661451ull, - 0x588627742dfd40bfull, 0xda8331b73f3d39a0ull, 0x17b0e392d109a405ull, 0xf965400bcf28fba9ull, - 0x7c3dbf4229a2a925ull, 0x023e460327e275dbull, 0x6cd0b55a0ce126b3ull, 0xe62da695828e96e7ull, - 0x42ad6e63b3f373b9ull, 0xe50cc319381d57dfull, 0xc5cbd729729b54eeull, 0x46d1e265fd2a9912ull, - 0x6428b056904eeff8ull, 0x8be23040131e04b7ull, 0x6709d5da2add2ec0ull, 0x075de98af44a2b93ull, - 0x8447dcc67bfbe66full, 0x6616f655b7ac9a23ull, 0xd607b8bded4b1a40ull, 0x0563af89d3a85e48ull, - 0x3db1b4ad20c21ba4ull, 0x11f22997b8323b75ull, 0x292032b34b587e99ull, 0x7f1cdace9331681dull, - 0x8e819fc9c0b65affull, 0xa1e3677fe2d5bb16ull, 0xcd33d225ee349da5ull, 0xd9a2543b85aef898ull, - 0x795e10cbfa0af76dull, 0x25a4bbb9992e5d79ull, 0x78413344677b438eull, 0xf0826688cef68601ull, - 0xd27b34bba392f0ebull, 0x551d8df162fad7bcull, 0x1e57c511d0d7d9adull, 0xdeffbdb171e4d30bull, - 0xf4feea8e802f6caaull, 0xa480c8f6317de55eull, 0xa0fc44f07fa40ff5ull, 0x95b5f551c3c9dd1aull, - 0x22f952336d6476eaull, 0x0000000000000000ull, 0xa6be8ef5169f9085ull, 0xcc2cf1aa73452946ull, - 0x2e7ddb39bf12550aull, 0xd526dd3157d8db78ull, 0x486b2d6c08becf29ull, 0x9b0f3a58365d8b21ull, - 0xac78cdfaadd22c15ull, 0xbc95c7e28891a383ull, 0x6a927f5f65dab9c3ull, 0xc3891d2c1ba0cb9eull, - 0xeaa92f9f50f8b507ull, 0xcf0d9426c9d6e87eull, 0xca6e3baf1a7eb636ull, 0xab25247059980786ull, - 0x69b31ad3df4978fbull, 0xe2512a93cc577c4cull, 0xff278a0ea61364d9ull, 0x71a615c766a53e26ull, - 0x89dc764334fc716cull, 0xf87a638452594f4aull, 0xf2bc208be914f3daull, 0x8766b94ac1682757ull, - 0xbbc82e687cdb8810ull, 0x626a7a53f9757088ull, 0xa2c202f358467a2eull, 0x4d0882e5db169161ull, - 0x09e7268301de7da8ull, 0xe897699c771ac0dcull, 0xc8507dac3d9cc3edull, 0xc0a878a0a1330aa6ull, - 0x978bb352e42ba8c1ull, 0xe9884a13ea6b743full, 0x279afdbabecc28a2ull, 0x047c8c064ed9eaabull, - 0x507e2278b15289f4ull, 0x599904fbb08cf45cull, 0xbd8ae46d15e01760ull, 0x31353da7f2b43844ull, - 0x8558ff49e68a528cull, 0x76fbfc4d92ef15b5ull, 0x3456922e211c660cull, 0x86799ac55c1993b4ull, - 0x3e90d1219a51da9cull, 0x2d5cbeb505819432ull, 0x982e5fd48cce4a19ull, 0xdb9c1238a24c8d43ull, - 0xd439febecaa96f9bull, 0x418c0bef0960b281ull, 0x158ea591f6ebd1deull, 0x1f48e69e4da66d4eull, - 0x8afd13cf8e6fb054ull, 0xf5e1c9011d5ed849ull, 0xe34e091c5126c8afull, 0xad67ee7530a398f6ull, - 0x43b24dec2e82c75aull, 0x75da99c1287cd48dull, 0x92e81cdb3783f689ull, 0xa3dd217cc537cecdull, - 0x60543c50de970553ull, 0x93f73f54aaf2426aull, 0xa91b62737e7a725dull, 0xf19d4507538732e2ull, - 0x77e4dfc20f9ea156ull, 0x7d229ccdb4d31dc6ull, 0x1b346a98037f87e5ull, 0xedf4c615a4b29e94ull, - 0x4093286094110662ull, 0xb0114ee85ae78063ull, 0x6ff1d0d6b672e78bull, 0x6dcf96d591909250ull, - 0xdfe09e3eec9567e8ull, 0x3214582b4827f97cull, 0xb46dc2ee143e6ac8ull, 0xf6c0ac8da7cd1971ull, - 0xebb60c10cd8901e4ull, 0xf7df8f023abcad92ull, 0x9c52d3d2c217a0b2ull, 0x6b8d5cd0f8ab0d20ull, - 0x3777f7a29b8fa734ull, 0x011f238f9d71b4e3ull, 0xc1b75b2f3c42be45ull, 0x5de588fdfe551ef7ull, - 0x6eeef3592b035368ull, 0xaa3a07ffc4e9b365ull, 0xecebe59a39c32a77ull, 0x5ba742f8976e8187ull, - 0x4b4a48e0b22d0e11ull, 0xddded83dcb771233ull, 0xa59feb79ac0c51bdull, 0xc7f5912a55792135ull - }, - { - 0x6d6ae04668a9b08aull, 0x3ab3f04b0be8c743ull, 0xe51e166b54b3c908ull, 0xbe90a9eb35c2f139ull, - 0xb2c7066637f2bec1ull, 0xaa6945613392202cull, 0x9a28c36f3b5201ebull, 0xddce5a93ab536994ull, - 0x0e34133ef6382827ull, 0x52a02ba1ec55048bull, 0xa2f88f97c4b2a177ull, 0x8640e513ca2251a5ull, - 0xcdf1d36258137622ull, 0xfe6cb708dedf8ddbull, 0x8a174a9ec8121e5dull, 0x679896036b81560eull, - 0x59ed033395795feeull, 0x1dd778ab8b74edafull, 0xee533ef92d9f926dull, 0x2a8c79baf8a8d8f5ull, - 0x6bcf398e69b119f6ull, 0xe20491742fafdd95ull, 0x276488e0809c2aecull, 0xea955b82d88f5cceull, - 0x7102c63a99d9e0c4ull, 0xf9763017a5c39946ull, 0x429fa2501f151b3dull, 0x4659c72bea05d59eull, - 0x984b7fdccf5a6634ull, 0xf742232953fbb161ull, 0x3041860e08c021c7ull, 0x747bfd9616cd9386ull, - 0x4bb1367192312787ull, 0x1b72a1638a6c44d3ull, 0x4a0e68a6e8359a66ull, 0x169a5039f258b6caull, - 0xb98a2ef44edee5a4ull, 0xd9083fe85e43a737ull, 0x967f6ce239624e13ull, 0x8874f62d3c1a7982ull, - 0x3c1629830af06e3full, 0x9165ebfd427e5a8eull, 0xb5dd81794ceeaa5cull, 0x0de8f15a7834f219ull, - 0x70bd98ede3dd5d25ull, 0xaccc9ca9328a8950ull, 0x56664eda1945ca28ull, 0x221db34c0f8859aeull, - 0x26dbd637fa98970dull, 0x1acdffb4f068f932ull, 0x4585254f64090fa0ull, 0x72de245e17d53afaull, - 0x1546b25d7c546cf4ull, 0x207e0ffffb803e71ull, 0xfaaad2732bcf4378ull, 0xb462dfae36ea17bdull, - 0xcf926fd1ac1b11fdull, 0xe0672dc7dba7ba4aull, 0xd3fa49ad5d6b41b3ull, 0x8ba81449b216a3bcull, - 0x14f9ec8a0650d115ull, 0x40fc1ee3eb1d7ce2ull, 0x23a2ed9b758ce44full, 0x782c521b14fddc7eull, - 0x1c68267cf170504eull, 0xbcf31558c1ca96e6ull, 0xa781b43b4ba6d235ull, 0xf6fd7dfe29ff0c80ull, - 0xb0a4bad5c3fad91eull, 0xd199f51ea963266cull, 0x414340349119c103ull, 0x5405f269ed4dadf7ull, - 0xabd61bb649969dcdull, 0x6813dbeae7bdc3c8ull, 0x65fb2ab09f8931d1ull, 0xf1e7fae152e3181dull, - 0xc1a67cef5a2339daull, 0x7a4feea8e0f5bba1ull, 0x1e0b9acf05783791ull, 0x5b8ebf8061713831ull, - 0x80e53cdbcb3af8d9ull, 0x7e898bd315e57502ull, 0xc6bcfbf0213f2d47ull, 0x95a38e86b76e942dull, - 0x092e94218d243cbaull, 0x8339debf453622e7ull, 0xb11be402b9fe64ffull, 0x57d9100d634177c9ull, - 0xcc4e8db52217cbc3ull, 0x3b0cae9c71ec7aa2ull, 0xfb158ca451cbfe99ull, 0x2b33276d82ac6514ull, - 0x01bf5ed77a04bde1ull, 0xc5601994af33f779ull, 0x75c4a3416cc92e67ull, 0xf3844652a6eb7fc2ull, - 0x3487e375fdd0ef64ull, 0x18ae430704609eedull, 0x4d14efb993298efbull, 0x815a620cb13e4538ull, - 0x125c354207487869ull, 0x9eeea614ce42cf48ull, 0xce2d3106d61fac1cull, 0xbbe99247bad6827bull, - 0x071a871f7b1c149dull, 0x2e4a1cc10db81656ull, 0x77a71ff298c149b8ull, 0x06a5d9c80118a97cull, - 0xad73c27e488e34b1ull, 0x443a7b981e0db241ull, 0xe3bbcfa355ab6074ull, 0x0af276450328e684ull, - 0x73617a896dd1871bull, 0x58525de4ef7de20full, 0xb7be3dcab8e6cd83ull, 0x19111dd07e64230cull, - 0x842359a03e2a367aull, 0x103f89f1f3401fb6ull, 0xdc710444d157d475ull, 0xb835702334da5845ull, - 0x4320fc876511a6dcull, 0xd026abc9d3679b8dull, 0x17250eee885c0b2bull, 0x90dab52a387ae76full, - 0x31fed8d972c49c26ull, 0x89cba8fa461ec463ull, 0x2ff5421677bcabb7ull, 0x396f122f85e41d7dull, - 0xa09b332430bac6a8ull, 0xc888e8ced7070560ull, 0xaeaf201ac682ee8full, 0x1180d7268944a257ull, - 0xf058a43628e7a5fcull, 0xbd4c4b8fbbce2b07ull, 0xa1246df34abe7b49ull, 0x7d5569b79be9af3cull, - 0xa9b5a705bd9efa12ull, 0xdb6b835baa4bc0e8ull, 0x05793bac8f147342ull, 0x21c1512881848390ull, - 0xfdb0556c50d357e5ull, 0x613d4fcb6a99ff72ull, 0x03dce2648e0cda3eull, 0xe949b9e6568386f0ull, - 0xfc0f0bbb2ad7ea04ull, 0x6a70675913b5a417ull, 0x7f36d5046fe1c8e3ull, 0x0c57af8d02304ff8ull, - 0x32223abdfcc84618ull, 0x0891caf6f720815bull, 0xa63eeaec31a26fd4ull, 0x2507345374944d33ull, - 0x49d28ac266394058ull, 0xf5219f9aa7f3d6beull, 0x2d96fea583b4cc68ull, 0x5a31e1571b7585d0ull, - 0x8ed12fe53d02d0feull, 0xdfade6205f5b0e4bull, 0x4cabb16ee92d331aull, 0x04c6657bf510cea3ull, - 0xd73c2cd6a87b8f10ull, 0xe1d87310a1a307abull, 0x6cd5be9112ad0d6bull, 0x97c032354366f3f2ull, - 0xd4e0ceb22677552eull, 0x0000000000000000ull, 0x29509bde76a402cbull, 0xc27a9e8bd42fe3e4ull, - 0x5ef7842cee654b73ull, 0xaf107ecdbc86536eull, 0x3fcacbe784fcb401ull, 0xd55f90655c73e8cfull, - 0xe6c2f40fdabf1336ull, 0xe8f6e7312c873b11ull, 0xeb2a0555a28be12full, 0xe4a148bc2eb774e9ull, - 0x9b979db84156bc0aull, 0x6eb60222e6a56ab4ull, 0x87ffbbc4b026ec44ull, 0xc703a5275b3b90a6ull, - 0x47e699fc9001687full, 0x9c8d1aa73a4aa897ull, 0x7cea3760e1ed12ddull, 0x4ec80ddd1d2554c5ull, - 0x13e36b957d4cc588ull, 0x5d2b66486069914dull, 0x92b90999cc7280b0ull, 0x517cc9c56259deb5ull, - 0xc937b619ad03b881ull, 0xec30824ad997f5b2ull, 0xa45d565fc5aa080bull, 0xd6837201d27f32f1ull, - 0x635ef3789e9198adull, 0x531f75769651b96aull, 0x4f77530a6721e924ull, 0x486dd4151c3dfdb9ull, - 0x5f48dafb9461f692ull, 0x375b011173dc355aull, 0x3da9775470f4d3deull, 0x8d0dcd81b30e0ac0ull, - 0x36e45fc609d888bbull, 0x55baacbe97491016ull, 0x8cb29356c90ab721ull, 0x76184125e2c5f459ull, - 0x99f4210bb55edbd5ull, 0x6f095cf59ca1d755ull, 0x9f51f8c3b44672a9ull, 0x3538bda287d45285ull, - 0x50c39712185d6354ull, 0xf23b1885dcefc223ull, 0x79930ccc6ef9619full, 0xed8fdc9da3934853ull, - 0xcb540aaa590bdf5eull, 0x5c94389f1a6d2cacull, 0xe77daad8a0bbaed7ull, 0x28efc5090ca0bf2aull, - 0xbf2ff73c4fc64cd8ull, 0xb37858b14df60320ull, 0xf8c96ec0dfc724a7ull, 0x828680683f329f06ull, - 0x941cd051cd6a29ccull, 0xc3c5c05cae2b5e05ull, 0xb601631dc2e27062ull, 0xc01922382027843bull, - 0x24b86a840e90f0d2ull, 0xd245177a276ffc52ull, 0x0f8b4de98c3c95c6ull, 0x3e759530fef809e0ull, - 0x0b4d2892792c5b65ull, 0xc4df4743d5374a98ull, 0xa5e20888bfaeb5eaull, 0xba56cc90c0d23f9aull, - 0x38d04cf8ffe0a09cull, 0x62e1adafe495254cull, 0x0263bcb3f40867dfull, 0xcaeb547d230f62bfull, - 0x6082111c109d4293ull, 0xdad4dd8cd04f7d09ull, 0xefec602e579b2f8cull, 0x1fb4c4187f7c8a70ull, - 0xffd3e9dfa4db303aull, 0x7bf0b07f9af10640ull, 0xf49ec14dddf76b5full, 0x8f6e713247066d1full, - 0x339d646a86ccfbf9ull, 0x64447467e58d8c30ull, 0x2c29a072f9b07189ull, 0xd8b7613f24471ad6ull, - 0x6627c8d41185ebefull, 0xa347d140beb61c96ull, 0xde12b8f7255fb3aaull, 0x9d324470404e1576ull, - 0x9306574eb6763d51ull, 0xa80af9d2c79a47f3ull, 0x859c0777442e8b9bull, 0x69ac853d9db97e29ull - }, - { - 0xc3407dfc2de6377eull, 0x5b9e93eea4256f77ull, 0xadb58fdd50c845e0ull, 0x5219ff11a75bed86ull, - 0x356b61cfd90b1de9ull, 0xfb8f406e25abe037ull, 0x7a5a0231c0f60796ull, 0x9d3cd216e1f5020bull, - 0x0c6550fb6b48d8f3ull, 0xf57508c427ff1c62ull, 0x4ad35ffa71cb407dull, 0x6290a2da1666aa6dull, - 0xe284ec2349355f9full, 0xb3c307c53d7c84ecull, 0x05e23c0468365a02ull, 0x190bac4d6c9ebfa8ull, - 0x94bbbee9e28b80faull, 0xa34fc777529cb9b5ull, 0xcc7b39f095bcd978ull, 0x2426addb0ce532e3ull, - 0x7e79329312ce4fc7ull, 0xab09a72eebec2917ull, 0xf8d15499f6b9d6c2ull, 0x1a55b8babf8c895dull, - 0xdb8add17fb769a85ull, 0xb57f2f368658e81bull, 0x8acd36f18f3f41f6ull, 0x5ce3b7bba50f11d3ull, - 0x114dcc14d5ee2f0aull, 0xb91a7fcded1030e8ull, 0x81d5425fe55de7a1ull, 0xb6213bc1554adeeeull, - 0x80144ef95f53f5f2ull, 0x1e7688186db4c10cull, 0x3b912965db5fe1bcull, 0xc281715a97e8252dull, - 0x54a5d7e21c7f8171ull, 0x4b12535ccbc5522eull, 0x1d289cefbea6f7f9ull, 0x6ef5f2217d2e729eull, - 0xe6a7dc819b0d17ceull, 0x1b94b41c05829b0eull, 0x33d7493c622f711eull, 0xdcf7f942fa5ce421ull, - 0x600fba8b7f7a8ecbull, 0x46b60f011a83988eull, 0x235b898e0dcf4c47ull, 0x957ab24f588592a9ull, - 0x4354330572b5c28cull, 0xa5f3ef84e9b8d542ull, 0x8c711e02341b2d01ull, 0x0b1874ae6a62a657ull, - 0x1213d8e306fc19ffull, 0xfe6d7c6a4d9dba35ull, 0x65ed868f174cd4c9ull, 0x88522ea0e6236550ull, - 0x899322065c2d7703ull, 0xc01e690bfef4018bull, 0x915982ed8abddaf8ull, 0xbe675b98ec3a4e4cull, - 0xa996bf7f82f00db1ull, 0xe1daf8d49a27696aull, 0x2effd5d3dc8986e7ull, 0xd153a51f2b1a2e81ull, - 0x18caa0ebd690adfbull, 0x390e3134b243c51aull, 0x2778b92cdff70416ull, 0x029f1851691c24a6ull, - 0x5e7cafeacc133575ull, 0xfa4e4cc89fa5f264ull, 0x5a5f9f481e2b7d24ull, 0x484c47ab18d764dbull, - 0x400a27f2a1a7f479ull, 0xaeeb9b2a83da7315ull, 0x721c626879869734ull, 0x042330a2d2384851ull, - 0x85f672fd3765aff0ull, 0xba446b3a3e02061dull, 0x73dd6ecec3888567ull, 0xffac70ccf793a866ull, - 0xdfa9edb5294ed2d4ull, 0x6c6aea7014325638ull, 0x834a5a0e8c41c307ull, 0xcdba35562fb2cb2bull, - 0x0ad97808d06cb404ull, 0x0f3b440cb85aee06ull, 0xe5f9c876481f213bull, 0x98deee1289c35809ull, - 0x59018bbfcd394bd1ull, 0xe01bf47220297b39ull, 0xde68e1139340c087ull, 0x9fa3ca4788e926adull, - 0xbb85679c840c144eull, 0x53d8f3b71d55ffd5ull, 0x0da45c5dd146caa0ull, 0x6f34fe87c72060cdull, - 0x57fbc315cf6db784ull, 0xcee421a1fca0fddeull, 0x3d2d0196607b8d4bull, 0x642c8a29ad42c69aull, - 0x14aff010bdd87508ull, 0xac74837beac657b3ull, 0x3216459ad821634dull, 0x3fb219c70967a9edull, - 0x06bc28f3bb246cf7ull, 0xf2082c9126d562c6ull, 0x66b39278c45ee23cull, 0xbd394f6f3f2878b9ull, - 0xfd33689d9e8f8cc0ull, 0x37f4799eb017394full, 0x108cc0b26fe03d59ull, 0xda4bd1b1417888d6ull, - 0xb09d1332ee6eb219ull, 0x2f3ed975668794b4ull, 0x58c0871977375982ull, 0x7561463d78ace990ull, - 0x09876cff037e82f1ull, 0x7fb83e35a8c05d94ull, 0x26b9b58a65f91645ull, 0xef20b07e9873953full, - 0x3148516d0b3355b8ull, 0x41cb2b541ba9e62aull, 0x790416c613e43163ull, 0xa011d380818e8f40ull, - 0x3a5025c36151f3efull, 0xd57095bdf92266d0ull, 0x498d4b0da2d97688ull, 0x8b0c3a57353153a5ull, - 0x21c491df64d368e1ull, 0x8f2f0af5e7091bf4ull, 0x2da1c1240f9bb012ull, 0xc43d59a92ccc49daull, - 0xbfa6573e56345c1full, 0x828b56a8364fd154ull, 0x9a41f643e0df7cafull, 0xbcf843c985266aeaull, - 0x2b1de9d7b4bfdce5ull, 0x20059d79dedd7ab2ull, 0x6dabe6d6ae3c446bull, 0x45e81bf6c991ae7bull, - 0x6351ae7cac68b83eull, 0xa432e32253b6c711ull, 0xd092a9b991143cd2ull, 0xcac711032e98b58full, - 0xd8d4c9e02864ac70ull, 0xc5fc550f96c25b89ull, 0xd7ef8dec903e4276ull, 0x67729ede7e50f06full, - 0xeac28c7af045cf3dull, 0xb15c1f945460a04aull, 0x9cfddeb05bfb1058ull, 0x93c69abce3a1fe5eull, - 0xeb0380dc4a4bdd6eull, 0xd20db1e8f8081874ull, 0x229a8528b7c15e14ull, 0x44291750739fbc28ull, - 0xd3ccbd4e42060a27ull, 0xf62b1c33f4ed2a97ull, 0x86a8660ae4779905ull, 0xd62e814a2a305025ull, - 0x477703a7a08d8addull, 0x7b9b0e977af815c5ull, 0x78c51a60a9ea2330ull, 0xa6adfb733aaae3b7ull, - 0x97e5aa1e3199b60full, 0x0000000000000000ull, 0xf4b404629df10e31ull, 0x5564db44a6719322ull, - 0x9207961a59afec0dull, 0x9624a6b88b97a45cull, 0x363575380a192b1cull, 0x2c60cd82b595a241ull, - 0x7d272664c1dc7932ull, 0x7142769faa94a1c1ull, 0xa1d0df263b809d13ull, 0x1630e841d4c451aeull, - 0xc1df65ad44fa13d8ull, 0x13d2d445bcf20bacull, 0xd915c546926abe23ull, 0x38cf3d92084dd749ull, - 0xe766d0272103059dull, 0xc7634d5effde7f2full, 0x077d2455012a7ea4ull, 0xedbfa82ff16fb199ull, - 0xaf2a978c39d46146ull, 0x42953fa3c8bbd0dfull, 0xcb061da59496a7dcull, 0x25e7a17db6eb20b0ull, - 0x34aa6d6963050fbaull, 0xa76cf7d580a4f1e4ull, 0xf7ea10954ee338c4ull, 0xfcf2643b24819e93ull, - 0xcf252d0746aeef8dull, 0x4ef06f58a3f3082cull, 0x563acfb37563a5d7ull, 0x5086e740ce47c920ull, - 0x2982f186dda3f843ull, 0x87696aac5e798b56ull, 0x5d22bb1d1f010380ull, 0x035e14f7d31236f5ull, - 0x3cec0d30da759f18ull, 0xf3c920379cdb7095ull, 0xb8db736b571e22bbull, 0xdd36f5e44052f672ull, - 0xaac8ab8851e23b44ull, 0xa857b3d938fe1fe2ull, 0x17f1e4e76eca43fdull, 0xec7ea4894b61a3caull, - 0x9e62c6e132e734feull, 0xd4b1991b432c7483ull, 0x6ad6c283af163acfull, 0x1ce9904904a8e5aaull, - 0x5fbda34c761d2726ull, 0xf910583f4cb7c491ull, 0xc6a241f845d06d7cull, 0x4f3163fe19fd1a7full, - 0xe99c988d2357f9c8ull, 0x8eee06535d0709a7ull, 0x0efa48aa0254fc55ull, 0xb4be23903c56fa48ull, - 0x763f52caabbedf65ull, 0xeee1bcd8227d876cull, 0xe345e085f33b4dccull, 0x3e731561b369bbbeull, - 0x2843fd2067adea10ull, 0x2adce5710eb1ceb6ull, 0xb7e03767ef44ccbdull, 0x8db012a48e153f52ull, - 0x61ceb62dc5749c98ull, 0xe85d942b9959eb9bull, 0x4c6f7709caef2c8aull, 0x84377e5b8d6bbda3ull, - 0x30895dcbb13d47ebull, 0x74a04a9bc2a2fbc3ull, 0x6b17ce251518289cull, 0xe438c4d0f2113368ull, - 0x1fb784bed7bad35full, 0x9b80fae55ad16efcull, 0x77fe5e6c11b0cd36ull, 0xc858095247849129ull, - 0x08466059b97090a2ull, 0x01c10ca6ba0e1253ull, 0x6988d6747c040c3aull, 0x6849dad2c60a1e69ull, - 0x5147ebe67449db73ull, 0xc99905f4fd8a837aull, 0x991fe2b433cd4a5aull, 0xf09734c04fc94660ull, - 0xa28ecbd1e892abe6ull, 0xf1563866f5c75433ull, 0x4dae7baf70e13ed9ull, 0x7ce62ac27bd26b61ull, - 0x70837a39109ab392ull, 0x90988e4b30b3c8abull, 0xb2020b63877296bfull, 0x156efcb607d6675bull - }, - { - 0xe63f55ce97c331d0ull, 0x25b506b0015bba16ull, 0xc8706e29e6ad9ba8ull, 0x5b43d3775d521f6aull, - 0x0bfa3d577035106eull, 0xab95fc172afb0e66ull, 0xf64b63979e7a3276ull, 0xf58b4562649dad4bull, - 0x48f7c3dbae0c83f1ull, 0xff31916642f5c8c5ull, 0xcbb048dc1c4a0495ull, 0x66b8f83cdf622989ull, - 0x35c130e908e2b9b0ull, 0x7c761a61f0b34fa1ull, 0x3601161cf205268dull, 0x9e54ccfe2219b7d6ull, - 0x8b7d90a538940837ull, 0x9cd403588ea35d0bull, 0xbc3c6fea9ccc5b5aull, 0xe5ff733b6d24aeedull, - 0xceed22de0f7eb8d2ull, 0xec8581cab1ab545eull, 0xb96105e88ff8e71dull, 0x8ca03501871a5eadull, - 0x76ccce65d6db2a2full, 0x5883f582a7b58057ull, 0x3f7be4ed2e8adc3eull, 0x0fe7be06355cd9c9ull, - 0xee054e6c1d11be83ull, 0x1074365909b903a6ull, 0x5dde9f80b4813c10ull, 0x4a770c7d02b6692cull, - 0x5379c8d5d7809039ull, 0xb4067448161ed409ull, 0x5f5e5026183bd6cdull, 0xe898029bf4c29df9ull, - 0x7fb63c940a54d09cull, 0xc5171f897f4ba8bcull, 0xa6f28db7b31d3d72ull, 0x2e4f3be7716eaa78ull, - 0x0d6771a099e63314ull, 0x82076254e41bf284ull, 0x2f0fd2b42733df98ull, 0x5c9e76d3e2dc49f0ull, - 0x7aeb569619606cdbull, 0x83478b07b2468764ull, 0xcfadcb8d5923cd32ull, 0x85dac7f05b95a41eull, - 0xb5469d1b4043a1e9ull, 0xb821ecbbd9a592fdull, 0x1b8e0b0e798c13c8ull, 0x62a57b6d9a0be02eull, - 0xfcf1b793b81257f8ull, 0x9d94ea0bd8fe28ebull, 0x4cea408aeb654a56ull, 0x23284a47e888996cull, - 0x2d8f1d128b893545ull, 0xf4cbac3132c0d8abull, 0xbd7c86b9ca912ebaull, 0x3a268eef3dbe6079ull, - 0xf0d62f6077a9110cull, 0x2735c916ade150cbull, 0x89fd5f03942ee2eaull, 0x1acee25d2fd16628ull, - 0x90f39bab41181bffull, 0x430dfe8cde39939full, 0xf70b8ac4c8274796ull, 0x1c53aeaac6024552ull, - 0x13b410acf35e9c9bull, 0xa532ab4249faa24full, 0x2b1251e5625a163full, 0xd7e3e676da4841c7ull, - 0xa7b264e4e5404892ull, 0xda8497d643ae72d3ull, 0x861ae105a1723b23ull, 0x38a6414991048aa4ull, - 0x6578dec92585b6b4ull, 0x0280cfa6acbaeaddull, 0x88bdb650c273970aull, 0x9333bd5ebbff84c2ull, - 0x4e6a8f2c47dfa08bull, 0x321c954db76cef2aull, 0x418d312a72837942ull, 0xb29b38bfffcdf773ull, - 0x6c022c38f90a4c07ull, 0x5a033a240b0f6a8aull, 0x1f93885f3ce5da6full, 0xc38a537e96988bc6ull, - 0x39e6a81ac759ff44ull, 0x29929e43cee0fce2ull, 0x40cdd87924de0ca2ull, 0xe9d8ebc8a29fe819ull, - 0x0c2798f3cfbb46f4ull, 0x55e484223e53b343ull, 0x4650948ecd0d2fd8ull, 0x20e86cb2126f0651ull, - 0x6d42c56baf5739e7ull, 0xa06fc1405ace1e08ull, 0x7babbfc54f3d193bull, 0x424d17df8864e67full, - 0xd8045870ef14980eull, 0xc6d7397c85ac3781ull, 0x21a885e1443273b1ull, 0x67f8116f893f5c69ull, - 0x24f5efe35706cff6ull, 0xd56329d076f2ab1aull, 0x5e1eb9754e66a32dull, 0x28d2771098bd8902ull, - 0x8f6013f47dfdc190ull, 0x17a993fdb637553cull, 0xe0a219397e1012aaull, 0x786b9930b5da8606ull, - 0x6e82e39e55b0a6daull, 0x875a0856f72f4ec3ull, 0x3741ff4fa458536dull, 0xac4859b3957558fcull, - 0x7ef6d5c75c09a57cull, 0xc04a758b6c7f14fbull, 0xf9acdd91ab26ebbfull, 0x7391a467c5ef9668ull, - 0x335c7c1ee1319acaull, 0xa91533b18641e4bbull, 0xe4bf9a683b79db0dull, 0x8e20faa72ba0b470ull, - 0x51f907737b3a7ae4ull, 0x2268a314bed5ec8cull, 0xd944b123b949edeeull, 0x31dcb3b84d8b7017ull, - 0xd3fe65279f218860ull, 0x097af2f1dc8ffab3ull, 0x9b09a6fc312d0b91ull, 0xcc6ded78a3c4520full, - 0x3481d9ba5ebfcc50ull, 0x4f2a667f1182d56bull, 0xdfd9fdd4509ace94ull, 0x26752045fbbc252bull, - 0xbffc491f662bc467ull, 0xdd593272fc202449ull, 0x3cbbc218d46d4303ull, 0x91b372f817456e1full, - 0x681faf69bc6385a0ull, 0xb686bbeebaa43ed4ull, 0x1469b5084cd0ca01ull, 0x98c98009cbca94acull, - 0x6438379a73d8c354ull, 0xc2caba2dc0c5fe26ull, 0x3e3b0dbe78d7a9deull, 0x50b9ee202d670f04ull, - 0x4590b27b37eab0e5ull, 0x6025b4cb36b10af3ull, 0xfb2c1237079c0162ull, 0xa12f28130c936be8ull, - 0x4b37e52e54eb1cccull, 0x083a1ba28ad28f53ull, 0xc10a9cd83a22611bull, 0x9f1425ad7444c236ull, - 0x069d4cf7e9d3237aull, 0xedc56899e7f621beull, 0x778c273680865fcfull, 0x309c5aeb1bd605f7ull, - 0x8de0dc52d1472b4dull, 0xf8ec34c2fd7b9e5full, 0xea18cd3d58787724ull, 0xaad515447ca67b86ull, - 0x9989695a9d97e14cull, 0x0000000000000000ull, 0xf196c63321f464ecull, 0x71116bc169557cb5ull, - 0xaf887f466f92c7c1ull, 0x972e3e0ffe964d65ull, 0x190ec4a8d536f915ull, 0x95aef1a9522ca7b8ull, - 0xdc19db21aa7d51a9ull, 0x94ee18fa0471d258ull, 0x8087adf248a11859ull, 0xc457f6da2916dd5cull, - 0xfa6cfb6451c17482ull, 0xf256e0c6db13fbd1ull, 0x6a9f60cf10d96f7dull, 0x4daaa9d9bd383fb6ull, - 0x03c026f5fae79f3dull, 0xde99148706c7bb74ull, 0x2a52b8b6340763dfull, 0x6fc20acd03edd33aull, - 0xd423c08320afdefaull, 0xbbe1ca4e23420dc0ull, 0x966ed75ca8cb3885ull, 0xeb58246e0e2502c4ull, - 0x055d6a021334bc47ull, 0xa47242111fa7d7afull, 0xe3623fcc84f78d97ull, 0x81c744a11efc6db9ull, - 0xaec8961539cfb221ull, 0xf31609958d4e8e31ull, 0x63e5923ecc5695ceull, 0x47107ddd9b505a38ull, - 0xa3afe7b5a0298135ull, 0x792b7063e387f3e6ull, 0x0140e953565d75e0ull, 0x12f4f9ffa503e97bull, - 0x750ce8902c3cb512ull, 0xdbc47e8515f30733ull, 0x1ed3610c6ab8af8full, 0x5239218681dde5d9ull, - 0xe222d69fd2aaf877ull, 0xfe71783514a8bd25ull, 0xcaf0a18f4a177175ull, 0x61655d9860ec7f13ull, - 0xe77fbc9dc19e4430ull, 0x2ccff441ddd440a5ull, 0x16e97aaee06a20dcull, 0xa855dae2d01c915bull, - 0x1d1347f9905f30b2ull, 0xb7c652bdecf94b34ull, 0xd03e43d265c6175dull, 0xfdb15ec0ee4f2218ull, - 0x57644b8492e9599eull, 0x07dda5a4bf8e569aull, 0x54a46d71680ec6a3ull, 0x5624a2d7c4b42c7eull, - 0xbebca04c3076b187ull, 0x7d36f332a6ee3a41ull, 0x3b6667bc6be31599ull, 0x695f463aea3ef040ull, - 0xad08b0e0c3282d1cull, 0xb15b1e4a052a684eull, 0x44d05b2861b7c505ull, 0x15295c5b1a8dbfe1ull, - 0x744c01c37a61c0f2ull, 0x59c31cd1f1e8f5b7ull, 0xef45a73f4b4ccb63ull, 0x6bdf899c46841a9dull, - 0x3dfb2b4b823036e3ull, 0xa2ef0ee6f674f4d5ull, 0x184e2dfb836b8cf5ull, 0x1134df0a5fe47646ull, - 0xbaa1231d751f7820ull, 0xd17eaa81339b62bdull, 0xb01bf71953771daeull, 0x849a2ea30dc8d1feull, - 0x705182923f080955ull, 0x0ea757556301ac29ull, 0x041d83514569c9a7ull, 0x0abad4042668658eull, - 0x49b72a88f851f611ull, 0x8a3d79f66ec97dd7ull, 0xcd2d042bf59927efull, 0xc930877ab0f0ee48ull, - 0x9273540deda2f122ull, 0xc797d02fd3f14261ull, 0xe1e2f06a284d674aull, 0xd2be8c74c97cfd80ull, - 0x9a494faf67707e71ull, 0xb3dbd1eca9908293ull, 0x72d14d3493b2e388ull, 0xd6a30f258c153427ull - } -}; - -template -const uint64_t streebog_constants::RC[12][8] = { - { 0xdd806559f2a64507ull, 0x05767436cc744d23ull, 0xa2422a08a460d315ull, 0x4b7ce09192676901ull, - 0x714eb88d7585c4fcull, 0x2f6a76432e45d016ull, 0xebcb2f81c0657c1full, 0xb1085bda1ecadae9ull }, - { 0xe679047021b19bb7ull, 0x55dda21bd7cbcd56ull, 0x5cb561c2db0aa7caull, 0x9ab5176b12d69958ull, - 0x61d55e0f16b50131ull, 0xf3feea720a232b98ull, 0x4fe39d460f70b5d7ull, 0x6fa3b58aa99d2f1aull }, - { 0x991e96f50aba0ab2ull, 0xc2b6f443867adb31ull, 0xc1c93a376062db09ull, 0xd3e20fe490359eb1ull, - 0xf2ea7514b1297b7bull, 0x06f15e5f529c1f8bull, 0x0a39fc286a3d8435ull, 0xf574dcac2bce2fc7ull }, - { 0x220cbebc84e3d12eull, 0x3453eaa193e837f1ull, 0xd8b71333935203beull, 0xa9d72c82ed03d675ull, - 0x9d721cad685e353full, 0x488e857e335c3c7dull, 0xf948e1a05d71e4ddull, 0xef1fdfb3e81566d2ull }, - { 0x601758fd7c6cfe57ull, 0x7a56a27ea9ea63f5ull, 0xdfff00b723271a16ull, 0xbfcd1747253af5a3ull, - 0x359e35d7800fffbdull, 0x7f151c1f1686104aull, 0x9a3f410c6ca92363ull, 0x4bea6bacad474799ull }, - { 0xfa68407a46647d6eull, 0xbf71c57236904f35ull, 0x0af21f66c2bec6b6ull, 0xcffaa6b71c9ab7b4ull, - 0x187f9ab49af08ec6ull, 0x2d66c4f95142a46cull, 0x6fa4c33b7a3039c0ull, 0xae4faeae1d3ad3d9ull }, - { 0x8886564d3a14d493ull, 0x3517454ca23c4af3ull, 0x06476983284a0504ull, 0x0992abc52d822c37ull, - 0xd3473e33197a93c9ull, 0x399ec6c7e6bf87c9ull, 0x51ac86febf240954ull, 0xf4c70e16eeaac5ecull }, - { 0xa47f0dd4bf02e71eull, 0x36acc2355951a8d9ull, 0x69d18d2bd1a5c42full, 0xf4892bcb929b0690ull, - 0x89b4443b4ddbc49aull, 0x4eb7f8719c36de1eull, 0x03e7aa020c6e4141ull, 0x9b1f5b424d93c9a7ull }, - { 0x7261445183235adbull, 0x0e38dc92cb1f2a60ull, 0x7b2b8a9aa6079c54ull, 0x800a440bdbb2ceb1ull, - 0x3cd955b7e00d0984ull, 0x3a7d3a1b25894224ull, 0x944c9ad8ec165fdeull, 0x378f5a541631229bull }, - { 0x74b4c7fb98459cedull, 0x3698fad1153bb6c3ull, 0x7a1e6c303b7652f4ull, 0x9fe76702af69334bull, - 0x1fffe18a1b336103ull, 0x8941e71cff8a78dbull, 0x382ae548b2e4f3f3ull, 0xabbedea680056f52ull }, - { 0x6bcaa4cd81f32d1bull, 0xdea2594ac06fd85dull, 0xefbacd1d7d476e98ull, 0x8a1d71efea48b9caull, - 0x2001802114846679ull, 0xd8fa6bbbebab0761ull, 0x3002c6cd635afe94ull, 0x7bcd9ed0efc889fbull }, - { 0x48bc924af11bd720ull, 0xfaf417d5d9b21b99ull, 0xe71da4aa88e12852ull, 0x5d80ef9d1891cc86ull, - 0xf82012d430219f9bull, 0xcda43c32bcdf1d77ull, 0xd21380b00449b17aull, 0x378ee767f11631baull } -}; - - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/whirlpool_constants.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/whirlpool_constants.hpp deleted file mode 100644 index 87e9e09..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/constants/whirlpool_constants.hpp +++ /dev/null @@ -1,571 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_WHIRLPOOL_CONSTANTS_HPP -#define DIGESTPP_PROVIDERS_WHIRLPOOL_CONSTANTS_HPP - -namespace digestpp -{ - -namespace detail -{ - -template -struct whirlpool_constants -{ - static const uint64_t RC[10]; - static const uint64_t T[8][256]; -}; - -template -const uint64_t whirlpool_constants::RC[10] = { - 0x4f01b887e8c62318ull, - 0x52916f79f5d2a636ull, - 0x357b0ca38e9bbc60ull, - 0x57fe4b2ec2d7e01dull, - 0xda4af09fe5377715ull, - 0x856ba0b10a29c958ull, - 0x67053ecbf4105dbdull, - 0xd8957da78b4127e4ull, - 0x9e4717dd667ceefbull, - 0x33835aad07bf2dcaull -}; - -template -const uint64_t whirlpool_constants::T[8][256] = { - { - 0xd83078c018601818ull, 0x2646af05238c2323ull, 0xb891f97ec63fc6c6ull, 0xfbcd6f13e887e8e8ull, - 0xcb13a14c87268787ull, 0x116d62a9b8dab8b8ull, 0x0902050801040101ull, 0x0d9e6e424f214f4full, - 0x9b6ceead36d83636ull, 0xff510459a6a2a6a6ull, 0x0cb9bdded26fd2d2ull, 0x0ef706fbf5f3f5f5ull, - 0x96f280ef79f97979ull, 0x30dece5f6fa16f6full, 0x6d3feffc917e9191ull, 0xf8a407aa52555252ull, - 0x47c0fd27609d6060ull, 0x35657689bccabcbcull, 0x372bcdac9b569b9bull, 0x8a018c048e028e8eull, - 0xd25b1571a3b6a3a3ull, 0x6c183c600c300c0cull, 0x84f68aff7bf17b7bull, 0x806ae1b535d43535ull, - 0xf53a69e81d741d1dull, 0xb3dd4753e0a7e0e0ull, 0x21b3acf6d77bd7d7ull, 0x9c99ed5ec22fc2c2ull, - 0x435c966d2eb82e2eull, 0x29967a624b314b4bull, 0x5de121a3fedffefeull, 0xd5ae168257415757ull, - 0xbd2a41a815541515ull, 0xe8eeb69f77c17777ull, 0x926eeba537dc3737ull, 0x9ed7567be5b3e5e5ull, - 0x1323d98c9f469f9full, 0x23fd17d3f0e7f0f0ull, 0x20947f6a4a354a4aull, 0x44a9959eda4fdadaull, - 0xa2b025fa587d5858ull, 0xcf8fca06c903c9c9ull, 0x7c528d5529a42929ull, 0x5a1422500a280a0aull, - 0x507f4fe1b1feb1b1ull, 0xc95d1a69a0baa0a0ull, 0x14d6da7f6bb16b6bull, 0xd917ab5c852e8585ull, - 0x3c677381bdcebdbdull, 0x8fba34d25d695d5dull, 0x9020508010401010ull, 0x07f503f3f4f7f4f4ull, - 0xdd8bc016cb0bcbcbull, 0xd37cc6ed3ef83e3eull, 0x2d0a112805140505ull, 0x78cee61f67816767ull, - 0x97d55373e4b7e4e4ull, 0x024ebb25279c2727ull, 0x7382583241194141ull, 0xa70b9d2c8b168b8bull, - 0xf6530151a7a6a7a7ull, 0xb2fa94cf7de97d7dull, 0x4937fbdc956e9595ull, 0x56ad9f8ed847d8d8ull, - 0x70eb308bfbcbfbfbull, 0xcdc17123ee9feeeeull, 0xbbf891c77ced7c7cull, 0x71cce31766856666ull, - 0x7ba78ea6dd53ddddull, 0xaf2e4bb8175c1717ull, 0x458e460247014747ull, 0x1a21dc849e429e9eull, - 0xd489c51eca0fcacaull, 0x585a99752db42d2dull, 0x2e637991bfc6bfbfull, 0x3f0e1b38071c0707ull, - 0xac472301ad8eadadull, 0xb0b42fea5a755a5aull, 0xef1bb56c83368383ull, 0xb666ff8533cc3333ull, - 0x5cc6f23f63916363ull, 0x12040a1002080202ull, 0x93493839aa92aaaaull, 0xdee2a8af71d97171ull, - 0xc68dcf0ec807c8c8ull, 0xd1327dc819641919ull, 0x3b92707249394949ull, 0x5faf9a86d943d9d9ull, - 0x31f91dc3f2eff2f2ull, 0xa8db484be3abe3e3ull, 0xb9b62ae25b715b5bull, 0xbc0d9234881a8888ull, - 0x3e29c8a49a529a9aull, 0x0b4cbe2d26982626ull, 0xbf64fa8d32c83232ull, 0x597d4ae9b0fab0b0ull, - 0xf2cf6a1be983e9e9ull, 0x771e33780f3c0f0full, 0x33b7a6e6d573d5d5ull, 0xf41dba74803a8080ull, - 0x27617c99bec2bebeull, 0xeb87de26cd13cdcdull, 0x8968e4bd34d03434ull, 0x3290757a483d4848ull, - 0x54e324abffdbffffull, 0x8df48ff77af57a7aull, 0x643deaf4907a9090ull, 0x9dbe3ec25f615f5full, - 0x3d40a01d20802020ull, 0x0fd0d56768bd6868ull, 0xca3472d01a681a1aull, 0xb7412c19ae82aeaeull, - 0x7d755ec9b4eab4b4ull, 0xcea8199a544d5454ull, 0x7f3be5ec93769393ull, 0x2f44aa0d22882222ull, - 0x63c8e907648d6464ull, 0x2aff12dbf1e3f1f1ull, 0xcce6a2bf73d17373ull, 0x82245a9012481212ull, - 0x7a805d3a401d4040ull, 0x4810284008200808ull, 0x959be856c32bc3c3ull, 0xdfc57b33ec97ececull, - 0x4dab9096db4bdbdbull, 0xc05f1f61a1bea1a1ull, 0x9107831c8d0e8d8dull, 0xc87ac9f53df43d3dull, - 0x5b33f1cc97669797ull, 0x0000000000000000ull, 0xf983d436cf1bcfcfull, 0x6e5687452bac2b2bull, - 0xe1ecb39776c57676ull, 0xe619b06482328282ull, 0x28b1a9fed67fd6d6ull, 0xc33677d81b6c1b1bull, - 0x74775bc1b5eeb5b5ull, 0xbe432911af86afafull, 0x1dd4df776ab56a6aull, 0xeaa00dba505d5050ull, - 0x578a4c1245094545ull, 0x38fb18cbf3ebf3f3ull, 0xad60f09d30c03030ull, 0xc4c3742bef9befefull, - 0xda7ec3e53ffc3f3full, 0xc7aa1c9255495555ull, 0xdb591079a2b2a2a2ull, 0xe9c96503ea8feaeaull, - 0x6acaec0f65896565ull, 0x036968b9bad2babaull, 0x4a5e93652fbc2f2full, 0x8e9de74ec027c0c0ull, - 0x60a181bede5fdedeull, 0xfc386ce01c701c1cull, 0x46e72ebbfdd3fdfdull, 0x1f9a64524d294d4dull, - 0x7639e0e492729292ull, 0xfaeabc8f75c97575ull, 0x360c1e3006180606ull, 0xae0998248a128a8aull, - 0x4b7940f9b2f2b2b2ull, 0x85d15963e6bfe6e6ull, 0x7e1c36700e380e0eull, 0xe73e63f81f7c1f1full, - 0x55c4f73762956262ull, 0x3ab5a3eed477d4d4ull, 0x814d3229a89aa8a8ull, 0x5231f4c496629696ull, - 0x62ef3a9bf9c3f9f9ull, 0xa397f666c533c5c5ull, 0x104ab13525942525ull, 0xabb220f259795959ull, - 0xd015ae54842a8484ull, 0xc5e4a7b772d57272ull, 0xec72ddd539e43939ull, 0x1698615a4c2d4c4cull, - 0x94bc3bca5e655e5eull, 0x9ff085e778fd7878ull, 0xe570d8dd38e03838ull, 0x980586148c0a8c8cull, - 0x17bfb2c6d163d1d1ull, 0xe4570b41a5aea5a5ull, 0xa1d94d43e2afe2e2ull, 0x4ec2f82f61996161ull, - 0x427b45f1b3f6b3b3ull, 0x3442a51521842121ull, 0x0825d6949c4a9c9cull, 0xee3c66f01e781e1eull, - 0x6186522243114343ull, 0xb193fc76c73bc7c7ull, 0x4fe52bb3fcd7fcfcull, 0x2408142004100404ull, - 0xe3a208b251595151ull, 0x252fc7bc995e9999ull, 0x22dac44f6da96d6dull, 0x651a39680d340d0dull, - 0x79e93583facffafaull, 0x69a384b6df5bdfdfull, 0xa9fc9bd77ee57e7eull, 0x1948b43d24902424ull, - 0xfe76d7c53bec3b3bull, 0x9a4b3d31ab96ababull, 0xf081d13ece1fceceull, 0x9922558811441111ull, - 0x8303890c8f068f8full, 0x049c6b4a4e254e4eull, 0x667351d1b7e6b7b7ull, 0xe0cb600beb8bebebull, - 0xc178ccfd3cf03c3cull, 0xfd1fbf7c813e8181ull, 0x4035fed4946a9494ull, 0x1cf30cebf7fbf7f7ull, - 0x186f67a1b9deb9b9ull, 0x8b265f98134c1313ull, 0x51589c7d2cb02c2cull, 0x05bbb8d6d36bd3d3ull, - 0x8cd35c6be7bbe7e7ull, 0x39dccb576ea56e6eull, 0xaa95f36ec437c4c4ull, 0x1b060f18030c0303ull, - 0xdcac138a56455656ull, 0x5e88491a440d4444ull, 0xa0fe9edf7fe17f7full, 0x884f3721a99ea9a9ull, - 0x6754824d2aa82a2aull, 0x0a6b6db1bbd6bbbbull, 0x879fe246c123c1c1ull, 0xf1a602a253515353ull, - 0x72a58baedc57dcdcull, 0x531627580b2c0b0bull, 0x0127d39c9d4e9d9dull, 0x2bd8c1476cad6c6cull, - 0xa462f59531c43131ull, 0xf3e8b98774cd7474ull, 0x15f109e3f6fff6f6ull, 0x4c8c430a46054646ull, - 0xa5452609ac8aacacull, 0xb50f973c891e8989ull, 0xb42844a014501414ull, 0xbadf425be1a3e1e1ull, - 0xa62c4eb016581616ull, 0xf774d2cd3ae83a3aull, 0x06d2d06f69b96969ull, 0x41122d4809240909ull, - 0xd7e0ada770dd7070ull, 0x6f7154d9b6e2b6b6ull, 0x1ebdb7ced067d0d0ull, 0xd6c77e3bed93ededull, - 0xe285db2ecc17ccccull, 0x6884572a42154242ull, 0x2c2dc2b4985a9898ull, 0xed550e49a4aaa4a4ull, - 0x7550885d28a02828ull, 0x86b831da5c6d5c5cull, 0x6bed3f93f8c7f8f8ull, 0xc211a44486228686ull - }, - { - 0x3078c018601818d8ull, 0x46af05238c232326ull, 0x91f97ec63fc6c6b8ull, 0xcd6f13e887e8e8fbull, - 0x13a14c87268787cbull, 0x6d62a9b8dab8b811ull, 0x0205080104010109ull, 0x9e6e424f214f4f0dull, - 0x6ceead36d836369bull, 0x510459a6a2a6a6ffull, 0xb9bdded26fd2d20cull, 0xf706fbf5f3f5f50eull, - 0xf280ef79f9797996ull, 0xdece5f6fa16f6f30ull, 0x3feffc917e91916dull, 0xa407aa52555252f8ull, - 0xc0fd27609d606047ull, 0x657689bccabcbc35ull, 0x2bcdac9b569b9b37ull, 0x018c048e028e8e8aull, - 0x5b1571a3b6a3a3d2ull, 0x183c600c300c0c6cull, 0xf68aff7bf17b7b84ull, 0x6ae1b535d4353580ull, - 0x3a69e81d741d1df5ull, 0xdd4753e0a7e0e0b3ull, 0xb3acf6d77bd7d721ull, 0x99ed5ec22fc2c29cull, - 0x5c966d2eb82e2e43ull, 0x967a624b314b4b29ull, 0xe121a3fedffefe5dull, 0xae168257415757d5ull, - 0x2a41a815541515bdull, 0xeeb69f77c17777e8ull, 0x6eeba537dc373792ull, 0xd7567be5b3e5e59eull, - 0x23d98c9f469f9f13ull, 0xfd17d3f0e7f0f023ull, 0x947f6a4a354a4a20ull, 0xa9959eda4fdada44ull, - 0xb025fa587d5858a2ull, 0x8fca06c903c9c9cfull, 0x528d5529a429297cull, 0x1422500a280a0a5aull, - 0x7f4fe1b1feb1b150ull, 0x5d1a69a0baa0a0c9ull, 0xd6da7f6bb16b6b14ull, 0x17ab5c852e8585d9ull, - 0x677381bdcebdbd3cull, 0xba34d25d695d5d8full, 0x2050801040101090ull, 0xf503f3f4f7f4f407ull, - 0x8bc016cb0bcbcbddull, 0x7cc6ed3ef83e3ed3ull, 0x0a1128051405052dull, 0xcee61f6781676778ull, - 0xd55373e4b7e4e497ull, 0x4ebb25279c272702ull, 0x8258324119414173ull, 0x0b9d2c8b168b8ba7ull, - 0x530151a7a6a7a7f6ull, 0xfa94cf7de97d7db2ull, 0x37fbdc956e959549ull, 0xad9f8ed847d8d856ull, - 0xeb308bfbcbfbfb70ull, 0xc17123ee9feeeecdull, 0xf891c77ced7c7cbbull, 0xcce3176685666671ull, - 0xa78ea6dd53dddd7bull, 0x2e4bb8175c1717afull, 0x8e46024701474745ull, 0x21dc849e429e9e1aull, - 0x89c51eca0fcacad4ull, 0x5a99752db42d2d58ull, 0x637991bfc6bfbf2eull, 0x0e1b38071c07073full, - 0x472301ad8eadadacull, 0xb42fea5a755a5ab0ull, 0x1bb56c83368383efull, 0x66ff8533cc3333b6ull, - 0xc6f23f639163635cull, 0x040a100208020212ull, 0x493839aa92aaaa93ull, 0xe2a8af71d97171deull, - 0x8dcf0ec807c8c8c6ull, 0x327dc819641919d1ull, 0x927072493949493bull, 0xaf9a86d943d9d95full, - 0xf91dc3f2eff2f231ull, 0xdb484be3abe3e3a8ull, 0xb62ae25b715b5bb9ull, 0x0d9234881a8888bcull, - 0x29c8a49a529a9a3eull, 0x4cbe2d269826260bull, 0x64fa8d32c83232bfull, 0x7d4ae9b0fab0b059ull, - 0xcf6a1be983e9e9f2ull, 0x1e33780f3c0f0f77ull, 0xb7a6e6d573d5d533ull, 0x1dba74803a8080f4ull, - 0x617c99bec2bebe27ull, 0x87de26cd13cdcdebull, 0x68e4bd34d0343489ull, 0x90757a483d484832ull, - 0xe324abffdbffff54ull, 0xf48ff77af57a7a8dull, 0x3deaf4907a909064ull, 0xbe3ec25f615f5f9dull, - 0x40a01d208020203dull, 0xd0d56768bd68680full, 0x3472d01a681a1acaull, 0x412c19ae82aeaeb7ull, - 0x755ec9b4eab4b47dull, 0xa8199a544d5454ceull, 0x3be5ec937693937full, 0x44aa0d228822222full, - 0xc8e907648d646463ull, 0xff12dbf1e3f1f12aull, 0xe6a2bf73d17373ccull, 0x245a901248121282ull, - 0x805d3a401d40407aull, 0x1028400820080848ull, 0x9be856c32bc3c395ull, 0xc57b33ec97ececdfull, - 0xab9096db4bdbdb4dull, 0x5f1f61a1bea1a1c0ull, 0x07831c8d0e8d8d91ull, 0x7ac9f53df43d3dc8ull, - 0x33f1cc976697975bull, 0x0000000000000000ull, 0x83d436cf1bcfcff9ull, 0x5687452bac2b2b6eull, - 0xecb39776c57676e1ull, 0x19b06482328282e6ull, 0xb1a9fed67fd6d628ull, 0x3677d81b6c1b1bc3ull, - 0x775bc1b5eeb5b574ull, 0x432911af86afafbeull, 0xd4df776ab56a6a1dull, 0xa00dba505d5050eaull, - 0x8a4c124509454557ull, 0xfb18cbf3ebf3f338ull, 0x60f09d30c03030adull, 0xc3742bef9befefc4ull, - 0x7ec3e53ffc3f3fdaull, 0xaa1c9255495555c7ull, 0x591079a2b2a2a2dbull, 0xc96503ea8feaeae9ull, - 0xcaec0f658965656aull, 0x6968b9bad2baba03ull, 0x5e93652fbc2f2f4aull, 0x9de74ec027c0c08eull, - 0xa181bede5fdede60ull, 0x386ce01c701c1cfcull, 0xe72ebbfdd3fdfd46ull, 0x9a64524d294d4d1full, - 0x39e0e49272929276ull, 0xeabc8f75c97575faull, 0x0c1e300618060636ull, 0x0998248a128a8aaeull, - 0x7940f9b2f2b2b24bull, 0xd15963e6bfe6e685ull, 0x1c36700e380e0e7eull, 0x3e63f81f7c1f1fe7ull, - 0xc4f7376295626255ull, 0xb5a3eed477d4d43aull, 0x4d3229a89aa8a881ull, 0x31f4c49662969652ull, - 0xef3a9bf9c3f9f962ull, 0x97f666c533c5c5a3ull, 0x4ab1352594252510ull, 0xb220f259795959abull, - 0x15ae54842a8484d0ull, 0xe4a7b772d57272c5ull, 0x72ddd539e43939ecull, 0x98615a4c2d4c4c16ull, - 0xbc3bca5e655e5e94ull, 0xf085e778fd78789full, 0x70d8dd38e03838e5ull, 0x0586148c0a8c8c98ull, - 0xbfb2c6d163d1d117ull, 0x570b41a5aea5a5e4ull, 0xd94d43e2afe2e2a1ull, 0xc2f82f619961614eull, - 0x7b45f1b3f6b3b342ull, 0x42a5152184212134ull, 0x25d6949c4a9c9c08ull, 0x3c66f01e781e1eeeull, - 0x8652224311434361ull, 0x93fc76c73bc7c7b1ull, 0xe52bb3fcd7fcfc4full, 0x0814200410040424ull, - 0xa208b251595151e3ull, 0x2fc7bc995e999925ull, 0xdac44f6da96d6d22ull, 0x1a39680d340d0d65ull, - 0xe93583facffafa79ull, 0xa384b6df5bdfdf69ull, 0xfc9bd77ee57e7ea9ull, 0x48b43d2490242419ull, - 0x76d7c53bec3b3bfeull, 0x4b3d31ab96abab9aull, 0x81d13ece1fcecef0ull, 0x2255881144111199ull, - 0x03890c8f068f8f83ull, 0x9c6b4a4e254e4e04ull, 0x7351d1b7e6b7b766ull, 0xcb600beb8bebebe0ull, - 0x78ccfd3cf03c3cc1ull, 0x1fbf7c813e8181fdull, 0x35fed4946a949440ull, 0xf30cebf7fbf7f71cull, - 0x6f67a1b9deb9b918ull, 0x265f98134c13138bull, 0x589c7d2cb02c2c51ull, 0xbbb8d6d36bd3d305ull, - 0xd35c6be7bbe7e78cull, 0xdccb576ea56e6e39ull, 0x95f36ec437c4c4aaull, 0x060f18030c03031bull, - 0xac138a56455656dcull, 0x88491a440d44445eull, 0xfe9edf7fe17f7fa0ull, 0x4f3721a99ea9a988ull, - 0x54824d2aa82a2a67ull, 0x6b6db1bbd6bbbb0aull, 0x9fe246c123c1c187ull, 0xa602a253515353f1ull, - 0xa58baedc57dcdc72ull, 0x1627580b2c0b0b53ull, 0x27d39c9d4e9d9d01ull, 0xd8c1476cad6c6c2bull, - 0x62f59531c43131a4ull, 0xe8b98774cd7474f3ull, 0xf109e3f6fff6f615ull, 0x8c430a460546464cull, - 0x452609ac8aacaca5ull, 0x0f973c891e8989b5ull, 0x2844a014501414b4ull, 0xdf425be1a3e1e1baull, - 0x2c4eb016581616a6ull, 0x74d2cd3ae83a3af7ull, 0xd2d06f69b9696906ull, 0x122d480924090941ull, - 0xe0ada770dd7070d7ull, 0x7154d9b6e2b6b66full, 0xbdb7ced067d0d01eull, 0xc77e3bed93ededd6ull, - 0x85db2ecc17cccce2ull, 0x84572a4215424268ull, 0x2dc2b4985a98982cull, 0x550e49a4aaa4a4edull, - 0x50885d28a0282875ull, 0xb831da5c6d5c5c86ull, 0xed3f93f8c7f8f86bull, 0x11a44486228686c2ull - }, - { - 0x78c018601818d830ull, 0xaf05238c23232646ull, 0xf97ec63fc6c6b891ull, 0x6f13e887e8e8fbcdull, - 0xa14c87268787cb13ull, 0x62a9b8dab8b8116dull, 0x0508010401010902ull, 0x6e424f214f4f0d9eull, - 0xeead36d836369b6cull, 0x0459a6a2a6a6ff51ull, 0xbdded26fd2d20cb9ull, 0x06fbf5f3f5f50ef7ull, - 0x80ef79f9797996f2ull, 0xce5f6fa16f6f30deull, 0xeffc917e91916d3full, 0x07aa52555252f8a4ull, - 0xfd27609d606047c0ull, 0x7689bccabcbc3565ull, 0xcdac9b569b9b372bull, 0x8c048e028e8e8a01ull, - 0x1571a3b6a3a3d25bull, 0x3c600c300c0c6c18ull, 0x8aff7bf17b7b84f6ull, 0xe1b535d43535806aull, - 0x69e81d741d1df53aull, 0x4753e0a7e0e0b3ddull, 0xacf6d77bd7d721b3ull, 0xed5ec22fc2c29c99ull, - 0x966d2eb82e2e435cull, 0x7a624b314b4b2996ull, 0x21a3fedffefe5de1ull, 0x168257415757d5aeull, - 0x41a815541515bd2aull, 0xb69f77c17777e8eeull, 0xeba537dc3737926eull, 0x567be5b3e5e59ed7ull, - 0xd98c9f469f9f1323ull, 0x17d3f0e7f0f023fdull, 0x7f6a4a354a4a2094ull, 0x959eda4fdada44a9ull, - 0x25fa587d5858a2b0ull, 0xca06c903c9c9cf8full, 0x8d5529a429297c52ull, 0x22500a280a0a5a14ull, - 0x4fe1b1feb1b1507full, 0x1a69a0baa0a0c95dull, 0xda7f6bb16b6b14d6ull, 0xab5c852e8585d917ull, - 0x7381bdcebdbd3c67ull, 0x34d25d695d5d8fbaull, 0x5080104010109020ull, 0x03f3f4f7f4f407f5ull, - 0xc016cb0bcbcbdd8bull, 0xc6ed3ef83e3ed37cull, 0x1128051405052d0aull, 0xe61f6781676778ceull, - 0x5373e4b7e4e497d5ull, 0xbb25279c2727024eull, 0x5832411941417382ull, 0x9d2c8b168b8ba70bull, - 0x0151a7a6a7a7f653ull, 0x94cf7de97d7db2faull, 0xfbdc956e95954937ull, 0x9f8ed847d8d856adull, - 0x308bfbcbfbfb70ebull, 0x7123ee9feeeecdc1ull, 0x91c77ced7c7cbbf8ull, 0xe3176685666671ccull, - 0x8ea6dd53dddd7ba7ull, 0x4bb8175c1717af2eull, 0x460247014747458eull, 0xdc849e429e9e1a21ull, - 0xc51eca0fcacad489ull, 0x99752db42d2d585aull, 0x7991bfc6bfbf2e63ull, 0x1b38071c07073f0eull, - 0x2301ad8eadadac47ull, 0x2fea5a755a5ab0b4ull, 0xb56c83368383ef1bull, 0xff8533cc3333b666ull, - 0xf23f639163635cc6ull, 0x0a10020802021204ull, 0x3839aa92aaaa9349ull, 0xa8af71d97171dee2ull, - 0xcf0ec807c8c8c68dull, 0x7dc819641919d132ull, 0x7072493949493b92ull, 0x9a86d943d9d95fafull, - 0x1dc3f2eff2f231f9ull, 0x484be3abe3e3a8dbull, 0x2ae25b715b5bb9b6ull, 0x9234881a8888bc0dull, - 0xc8a49a529a9a3e29ull, 0xbe2d269826260b4cull, 0xfa8d32c83232bf64ull, 0x4ae9b0fab0b0597dull, - 0x6a1be983e9e9f2cfull, 0x33780f3c0f0f771eull, 0xa6e6d573d5d533b7ull, 0xba74803a8080f41dull, - 0x7c99bec2bebe2761ull, 0xde26cd13cdcdeb87ull, 0xe4bd34d034348968ull, 0x757a483d48483290ull, - 0x24abffdbffff54e3ull, 0x8ff77af57a7a8df4ull, 0xeaf4907a9090643dull, 0x3ec25f615f5f9dbeull, - 0xa01d208020203d40ull, 0xd56768bd68680fd0ull, 0x72d01a681a1aca34ull, 0x2c19ae82aeaeb741ull, - 0x5ec9b4eab4b47d75ull, 0x199a544d5454cea8ull, 0xe5ec937693937f3bull, 0xaa0d228822222f44ull, - 0xe907648d646463c8ull, 0x12dbf1e3f1f12affull, 0xa2bf73d17373cce6ull, 0x5a90124812128224ull, - 0x5d3a401d40407a80ull, 0x2840082008084810ull, 0xe856c32bc3c3959bull, 0x7b33ec97ececdfc5ull, - 0x9096db4bdbdb4dabull, 0x1f61a1bea1a1c05full, 0x831c8d0e8d8d9107ull, 0xc9f53df43d3dc87aull, - 0xf1cc976697975b33ull, 0x0000000000000000ull, 0xd436cf1bcfcff983ull, 0x87452bac2b2b6e56ull, - 0xb39776c57676e1ecull, 0xb06482328282e619ull, 0xa9fed67fd6d628b1ull, 0x77d81b6c1b1bc336ull, - 0x5bc1b5eeb5b57477ull, 0x2911af86afafbe43ull, 0xdf776ab56a6a1dd4ull, 0x0dba505d5050eaa0ull, - 0x4c1245094545578aull, 0x18cbf3ebf3f338fbull, 0xf09d30c03030ad60ull, 0x742bef9befefc4c3ull, - 0xc3e53ffc3f3fda7eull, 0x1c9255495555c7aaull, 0x1079a2b2a2a2db59ull, 0x6503ea8feaeae9c9ull, - 0xec0f658965656acaull, 0x68b9bad2baba0369ull, 0x93652fbc2f2f4a5eull, 0xe74ec027c0c08e9dull, - 0x81bede5fdede60a1ull, 0x6ce01c701c1cfc38ull, 0x2ebbfdd3fdfd46e7ull, 0x64524d294d4d1f9aull, - 0xe0e4927292927639ull, 0xbc8f75c97575faeaull, 0x1e3006180606360cull, 0x98248a128a8aae09ull, - 0x40f9b2f2b2b24b79ull, 0x5963e6bfe6e685d1ull, 0x36700e380e0e7e1cull, 0x63f81f7c1f1fe73eull, - 0xf7376295626255c4ull, 0xa3eed477d4d43ab5ull, 0x3229a89aa8a8814dull, 0xf4c4966296965231ull, - 0x3a9bf9c3f9f962efull, 0xf666c533c5c5a397ull, 0xb13525942525104aull, 0x20f259795959abb2ull, - 0xae54842a8484d015ull, 0xa7b772d57272c5e4ull, 0xddd539e43939ec72ull, 0x615a4c2d4c4c1698ull, - 0x3bca5e655e5e94bcull, 0x85e778fd78789ff0ull, 0xd8dd38e03838e570ull, 0x86148c0a8c8c9805ull, - 0xb2c6d163d1d117bfull, 0x0b41a5aea5a5e457ull, 0x4d43e2afe2e2a1d9ull, 0xf82f619961614ec2ull, - 0x45f1b3f6b3b3427bull, 0xa515218421213442ull, 0xd6949c4a9c9c0825ull, 0x66f01e781e1eee3cull, - 0x5222431143436186ull, 0xfc76c73bc7c7b193ull, 0x2bb3fcd7fcfc4fe5ull, 0x1420041004042408ull, - 0x08b251595151e3a2ull, 0xc7bc995e9999252full, 0xc44f6da96d6d22daull, 0x39680d340d0d651aull, - 0x3583facffafa79e9ull, 0x84b6df5bdfdf69a3ull, 0x9bd77ee57e7ea9fcull, 0xb43d249024241948ull, - 0xd7c53bec3b3bfe76ull, 0x3d31ab96abab9a4bull, 0xd13ece1fcecef081ull, 0x5588114411119922ull, - 0x890c8f068f8f8303ull, 0x6b4a4e254e4e049cull, 0x51d1b7e6b7b76673ull, 0x600beb8bebebe0cbull, - 0xccfd3cf03c3cc178ull, 0xbf7c813e8181fd1full, 0xfed4946a94944035ull, 0x0cebf7fbf7f71cf3ull, - 0x67a1b9deb9b9186full, 0x5f98134c13138b26ull, 0x9c7d2cb02c2c5158ull, 0xb8d6d36bd3d305bbull, - 0x5c6be7bbe7e78cd3ull, 0xcb576ea56e6e39dcull, 0xf36ec437c4c4aa95ull, 0x0f18030c03031b06ull, - 0x138a56455656dcacull, 0x491a440d44445e88ull, 0x9edf7fe17f7fa0feull, 0x3721a99ea9a9884full, - 0x824d2aa82a2a6754ull, 0x6db1bbd6bbbb0a6bull, 0xe246c123c1c1879full, 0x02a253515353f1a6ull, - 0x8baedc57dcdc72a5ull, 0x27580b2c0b0b5316ull, 0xd39c9d4e9d9d0127ull, 0xc1476cad6c6c2bd8ull, - 0xf59531c43131a462ull, 0xb98774cd7474f3e8ull, 0x09e3f6fff6f615f1ull, 0x430a460546464c8cull, - 0x2609ac8aacaca545ull, 0x973c891e8989b50full, 0x44a014501414b428ull, 0x425be1a3e1e1badfull, - 0x4eb016581616a62cull, 0xd2cd3ae83a3af774ull, 0xd06f69b9696906d2ull, 0x2d48092409094112ull, - 0xada770dd7070d7e0ull, 0x54d9b6e2b6b66f71ull, 0xb7ced067d0d01ebdull, 0x7e3bed93ededd6c7ull, - 0xdb2ecc17cccce285ull, 0x572a421542426884ull, 0xc2b4985a98982c2dull, 0x0e49a4aaa4a4ed55ull, - 0x885d28a028287550ull, 0x31da5c6d5c5c86b8ull, 0x3f93f8c7f8f86bedull, 0xa44486228686c211ull - }, - { - 0xc018601818d83078ull, 0x05238c23232646afull, 0x7ec63fc6c6b891f9ull, 0x13e887e8e8fbcd6full, - 0x4c87268787cb13a1ull, 0xa9b8dab8b8116d62ull, 0x0801040101090205ull, 0x424f214f4f0d9e6eull, - 0xad36d836369b6ceeull, 0x59a6a2a6a6ff5104ull, 0xded26fd2d20cb9bdull, 0xfbf5f3f5f50ef706ull, - 0xef79f9797996f280ull, 0x5f6fa16f6f30deceull, 0xfc917e91916d3fefull, 0xaa52555252f8a407ull, - 0x27609d606047c0fdull, 0x89bccabcbc356576ull, 0xac9b569b9b372bcdull, 0x048e028e8e8a018cull, - 0x71a3b6a3a3d25b15ull, 0x600c300c0c6c183cull, 0xff7bf17b7b84f68aull, 0xb535d43535806ae1ull, - 0xe81d741d1df53a69ull, 0x53e0a7e0e0b3dd47ull, 0xf6d77bd7d721b3acull, 0x5ec22fc2c29c99edull, - 0x6d2eb82e2e435c96ull, 0x624b314b4b29967aull, 0xa3fedffefe5de121ull, 0x8257415757d5ae16ull, - 0xa815541515bd2a41ull, 0x9f77c17777e8eeb6ull, 0xa537dc3737926eebull, 0x7be5b3e5e59ed756ull, - 0x8c9f469f9f1323d9ull, 0xd3f0e7f0f023fd17ull, 0x6a4a354a4a20947full, 0x9eda4fdada44a995ull, - 0xfa587d5858a2b025ull, 0x06c903c9c9cf8fcaull, 0x5529a429297c528dull, 0x500a280a0a5a1422ull, - 0xe1b1feb1b1507f4full, 0x69a0baa0a0c95d1aull, 0x7f6bb16b6b14d6daull, 0x5c852e8585d917abull, - 0x81bdcebdbd3c6773ull, 0xd25d695d5d8fba34ull, 0x8010401010902050ull, 0xf3f4f7f4f407f503ull, - 0x16cb0bcbcbdd8bc0ull, 0xed3ef83e3ed37cc6ull, 0x28051405052d0a11ull, 0x1f6781676778cee6ull, - 0x73e4b7e4e497d553ull, 0x25279c2727024ebbull, 0x3241194141738258ull, 0x2c8b168b8ba70b9dull, - 0x51a7a6a7a7f65301ull, 0xcf7de97d7db2fa94ull, 0xdc956e95954937fbull, 0x8ed847d8d856ad9full, - 0x8bfbcbfbfb70eb30ull, 0x23ee9feeeecdc171ull, 0xc77ced7c7cbbf891ull, 0x176685666671cce3ull, - 0xa6dd53dddd7ba78eull, 0xb8175c1717af2e4bull, 0x0247014747458e46ull, 0x849e429e9e1a21dcull, - 0x1eca0fcacad489c5ull, 0x752db42d2d585a99ull, 0x91bfc6bfbf2e6379ull, 0x38071c07073f0e1bull, - 0x01ad8eadadac4723ull, 0xea5a755a5ab0b42full, 0x6c83368383ef1bb5ull, 0x8533cc3333b666ffull, - 0x3f639163635cc6f2ull, 0x100208020212040aull, 0x39aa92aaaa934938ull, 0xaf71d97171dee2a8ull, - 0x0ec807c8c8c68dcfull, 0xc819641919d1327dull, 0x72493949493b9270ull, 0x86d943d9d95faf9aull, - 0xc3f2eff2f231f91dull, 0x4be3abe3e3a8db48ull, 0xe25b715b5bb9b62aull, 0x34881a8888bc0d92ull, - 0xa49a529a9a3e29c8ull, 0x2d269826260b4cbeull, 0x8d32c83232bf64faull, 0xe9b0fab0b0597d4aull, - 0x1be983e9e9f2cf6aull, 0x780f3c0f0f771e33ull, 0xe6d573d5d533b7a6ull, 0x74803a8080f41dbaull, - 0x99bec2bebe27617cull, 0x26cd13cdcdeb87deull, 0xbd34d034348968e4ull, 0x7a483d4848329075ull, - 0xabffdbffff54e324ull, 0xf77af57a7a8df48full, 0xf4907a9090643deaull, 0xc25f615f5f9dbe3eull, - 0x1d208020203d40a0ull, 0x6768bd68680fd0d5ull, 0xd01a681a1aca3472ull, 0x19ae82aeaeb7412cull, - 0xc9b4eab4b47d755eull, 0x9a544d5454cea819ull, 0xec937693937f3be5ull, 0x0d228822222f44aaull, - 0x07648d646463c8e9ull, 0xdbf1e3f1f12aff12ull, 0xbf73d17373cce6a2ull, 0x901248121282245aull, - 0x3a401d40407a805dull, 0x4008200808481028ull, 0x56c32bc3c3959be8ull, 0x33ec97ececdfc57bull, - 0x96db4bdbdb4dab90ull, 0x61a1bea1a1c05f1full, 0x1c8d0e8d8d910783ull, 0xf53df43d3dc87ac9ull, - 0xcc976697975b33f1ull, 0x0000000000000000ull, 0x36cf1bcfcff983d4ull, 0x452bac2b2b6e5687ull, - 0x9776c57676e1ecb3ull, 0x6482328282e619b0ull, 0xfed67fd6d628b1a9ull, 0xd81b6c1b1bc33677ull, - 0xc1b5eeb5b574775bull, 0x11af86afafbe4329ull, 0x776ab56a6a1dd4dfull, 0xba505d5050eaa00dull, - 0x1245094545578a4cull, 0xcbf3ebf3f338fb18ull, 0x9d30c03030ad60f0ull, 0x2bef9befefc4c374ull, - 0xe53ffc3f3fda7ec3ull, 0x9255495555c7aa1cull, 0x79a2b2a2a2db5910ull, 0x03ea8feaeae9c965ull, - 0x0f658965656acaecull, 0xb9bad2baba036968ull, 0x652fbc2f2f4a5e93ull, 0x4ec027c0c08e9de7ull, - 0xbede5fdede60a181ull, 0xe01c701c1cfc386cull, 0xbbfdd3fdfd46e72eull, 0x524d294d4d1f9a64ull, - 0xe4927292927639e0ull, 0x8f75c97575faeabcull, 0x3006180606360c1eull, 0x248a128a8aae0998ull, - 0xf9b2f2b2b24b7940ull, 0x63e6bfe6e685d159ull, 0x700e380e0e7e1c36ull, 0xf81f7c1f1fe73e63ull, - 0x376295626255c4f7ull, 0xeed477d4d43ab5a3ull, 0x29a89aa8a8814d32ull, 0xc4966296965231f4ull, - 0x9bf9c3f9f962ef3aull, 0x66c533c5c5a397f6ull, 0x3525942525104ab1ull, 0xf259795959abb220ull, - 0x54842a8484d015aeull, 0xb772d57272c5e4a7ull, 0xd539e43939ec72ddull, 0x5a4c2d4c4c169861ull, - 0xca5e655e5e94bc3bull, 0xe778fd78789ff085ull, 0xdd38e03838e570d8ull, 0x148c0a8c8c980586ull, - 0xc6d163d1d117bfb2ull, 0x41a5aea5a5e4570bull, 0x43e2afe2e2a1d94dull, 0x2f619961614ec2f8ull, - 0xf1b3f6b3b3427b45ull, 0x15218421213442a5ull, 0x949c4a9c9c0825d6ull, 0xf01e781e1eee3c66ull, - 0x2243114343618652ull, 0x76c73bc7c7b193fcull, 0xb3fcd7fcfc4fe52bull, 0x2004100404240814ull, - 0xb251595151e3a208ull, 0xbc995e9999252fc7ull, 0x4f6da96d6d22dac4ull, 0x680d340d0d651a39ull, - 0x83facffafa79e935ull, 0xb6df5bdfdf69a384ull, 0xd77ee57e7ea9fc9bull, 0x3d249024241948b4ull, - 0xc53bec3b3bfe76d7ull, 0x31ab96abab9a4b3dull, 0x3ece1fcecef081d1ull, 0x8811441111992255ull, - 0x0c8f068f8f830389ull, 0x4a4e254e4e049c6bull, 0xd1b7e6b7b7667351ull, 0x0beb8bebebe0cb60ull, - 0xfd3cf03c3cc178ccull, 0x7c813e8181fd1fbfull, 0xd4946a94944035feull, 0xebf7fbf7f71cf30cull, - 0xa1b9deb9b9186f67ull, 0x98134c13138b265full, 0x7d2cb02c2c51589cull, 0xd6d36bd3d305bbb8ull, - 0x6be7bbe7e78cd35cull, 0x576ea56e6e39dccbull, 0x6ec437c4c4aa95f3ull, 0x18030c03031b060full, - 0x8a56455656dcac13ull, 0x1a440d44445e8849ull, 0xdf7fe17f7fa0fe9eull, 0x21a99ea9a9884f37ull, - 0x4d2aa82a2a675482ull, 0xb1bbd6bbbb0a6b6dull, 0x46c123c1c1879fe2ull, 0xa253515353f1a602ull, - 0xaedc57dcdc72a58bull, 0x580b2c0b0b531627ull, 0x9c9d4e9d9d0127d3ull, 0x476cad6c6c2bd8c1ull, - 0x9531c43131a462f5ull, 0x8774cd7474f3e8b9ull, 0xe3f6fff6f615f109ull, 0x0a460546464c8c43ull, - 0x09ac8aacaca54526ull, 0x3c891e8989b50f97ull, 0xa014501414b42844ull, 0x5be1a3e1e1badf42ull, - 0xb016581616a62c4eull, 0xcd3ae83a3af774d2ull, 0x6f69b9696906d2d0ull, 0x480924090941122dull, - 0xa770dd7070d7e0adull, 0xd9b6e2b6b66f7154ull, 0xced067d0d01ebdb7ull, 0x3bed93ededd6c77eull, - 0x2ecc17cccce285dbull, 0x2a42154242688457ull, 0xb4985a98982c2dc2ull, 0x49a4aaa4a4ed550eull, - 0x5d28a02828755088ull, 0xda5c6d5c5c86b831ull, 0x93f8c7f8f86bed3full, 0x4486228686c211a4ull - }, - { - 0x18601818d83078c0ull, 0x238c23232646af05ull, 0xc63fc6c6b891f97eull, 0xe887e8e8fbcd6f13ull, - 0x87268787cb13a14cull, 0xb8dab8b8116d62a9ull, 0x0104010109020508ull, 0x4f214f4f0d9e6e42ull, - 0x36d836369b6ceeadull, 0xa6a2a6a6ff510459ull, 0xd26fd2d20cb9bddeull, 0xf5f3f5f50ef706fbull, - 0x79f9797996f280efull, 0x6fa16f6f30dece5full, 0x917e91916d3feffcull, 0x52555252f8a407aaull, - 0x609d606047c0fd27ull, 0xbccabcbc35657689ull, 0x9b569b9b372bcdacull, 0x8e028e8e8a018c04ull, - 0xa3b6a3a3d25b1571ull, 0x0c300c0c6c183c60ull, 0x7bf17b7b84f68affull, 0x35d43535806ae1b5ull, - 0x1d741d1df53a69e8ull, 0xe0a7e0e0b3dd4753ull, 0xd77bd7d721b3acf6ull, 0xc22fc2c29c99ed5eull, - 0x2eb82e2e435c966dull, 0x4b314b4b29967a62ull, 0xfedffefe5de121a3ull, 0x57415757d5ae1682ull, - 0x15541515bd2a41a8ull, 0x77c17777e8eeb69full, 0x37dc3737926eeba5ull, 0xe5b3e5e59ed7567bull, - 0x9f469f9f1323d98cull, 0xf0e7f0f023fd17d3ull, 0x4a354a4a20947f6aull, 0xda4fdada44a9959eull, - 0x587d5858a2b025faull, 0xc903c9c9cf8fca06ull, 0x29a429297c528d55ull, 0x0a280a0a5a142250ull, - 0xb1feb1b1507f4fe1ull, 0xa0baa0a0c95d1a69ull, 0x6bb16b6b14d6da7full, 0x852e8585d917ab5cull, - 0xbdcebdbd3c677381ull, 0x5d695d5d8fba34d2ull, 0x1040101090205080ull, 0xf4f7f4f407f503f3ull, - 0xcb0bcbcbdd8bc016ull, 0x3ef83e3ed37cc6edull, 0x051405052d0a1128ull, 0x6781676778cee61full, - 0xe4b7e4e497d55373ull, 0x279c2727024ebb25ull, 0x4119414173825832ull, 0x8b168b8ba70b9d2cull, - 0xa7a6a7a7f6530151ull, 0x7de97d7db2fa94cfull, 0x956e95954937fbdcull, 0xd847d8d856ad9f8eull, - 0xfbcbfbfb70eb308bull, 0xee9feeeecdc17123ull, 0x7ced7c7cbbf891c7ull, 0x6685666671cce317ull, - 0xdd53dddd7ba78ea6ull, 0x175c1717af2e4bb8ull, 0x47014747458e4602ull, 0x9e429e9e1a21dc84ull, - 0xca0fcacad489c51eull, 0x2db42d2d585a9975ull, 0xbfc6bfbf2e637991ull, 0x071c07073f0e1b38ull, - 0xad8eadadac472301ull, 0x5a755a5ab0b42feaull, 0x83368383ef1bb56cull, 0x33cc3333b666ff85ull, - 0x639163635cc6f23full, 0x0208020212040a10ull, 0xaa92aaaa93493839ull, 0x71d97171dee2a8afull, - 0xc807c8c8c68dcf0eull, 0x19641919d1327dc8ull, 0x493949493b927072ull, 0xd943d9d95faf9a86ull, - 0xf2eff2f231f91dc3ull, 0xe3abe3e3a8db484bull, 0x5b715b5bb9b62ae2ull, 0x881a8888bc0d9234ull, - 0x9a529a9a3e29c8a4ull, 0x269826260b4cbe2dull, 0x32c83232bf64fa8dull, 0xb0fab0b0597d4ae9ull, - 0xe983e9e9f2cf6a1bull, 0x0f3c0f0f771e3378ull, 0xd573d5d533b7a6e6ull, 0x803a8080f41dba74ull, - 0xbec2bebe27617c99ull, 0xcd13cdcdeb87de26ull, 0x34d034348968e4bdull, 0x483d48483290757aull, - 0xffdbffff54e324abull, 0x7af57a7a8df48ff7ull, 0x907a9090643deaf4ull, 0x5f615f5f9dbe3ec2ull, - 0x208020203d40a01dull, 0x68bd68680fd0d567ull, 0x1a681a1aca3472d0ull, 0xae82aeaeb7412c19ull, - 0xb4eab4b47d755ec9ull, 0x544d5454cea8199aull, 0x937693937f3be5ecull, 0x228822222f44aa0dull, - 0x648d646463c8e907ull, 0xf1e3f1f12aff12dbull, 0x73d17373cce6a2bfull, 0x1248121282245a90ull, - 0x401d40407a805d3aull, 0x0820080848102840ull, 0xc32bc3c3959be856ull, 0xec97ececdfc57b33ull, - 0xdb4bdbdb4dab9096ull, 0xa1bea1a1c05f1f61ull, 0x8d0e8d8d9107831cull, 0x3df43d3dc87ac9f5ull, - 0x976697975b33f1ccull, 0x0000000000000000ull, 0xcf1bcfcff983d436ull, 0x2bac2b2b6e568745ull, - 0x76c57676e1ecb397ull, 0x82328282e619b064ull, 0xd67fd6d628b1a9feull, 0x1b6c1b1bc33677d8ull, - 0xb5eeb5b574775bc1ull, 0xaf86afafbe432911ull, 0x6ab56a6a1dd4df77ull, 0x505d5050eaa00dbaull, - 0x45094545578a4c12ull, 0xf3ebf3f338fb18cbull, 0x30c03030ad60f09dull, 0xef9befefc4c3742bull, - 0x3ffc3f3fda7ec3e5ull, 0x55495555c7aa1c92ull, 0xa2b2a2a2db591079ull, 0xea8feaeae9c96503ull, - 0x658965656acaec0full, 0xbad2baba036968b9ull, 0x2fbc2f2f4a5e9365ull, 0xc027c0c08e9de74eull, - 0xde5fdede60a181beull, 0x1c701c1cfc386ce0ull, 0xfdd3fdfd46e72ebbull, 0x4d294d4d1f9a6452ull, - 0x927292927639e0e4ull, 0x75c97575faeabc8full, 0x06180606360c1e30ull, 0x8a128a8aae099824ull, - 0xb2f2b2b24b7940f9ull, 0xe6bfe6e685d15963ull, 0x0e380e0e7e1c3670ull, 0x1f7c1f1fe73e63f8ull, - 0x6295626255c4f737ull, 0xd477d4d43ab5a3eeull, 0xa89aa8a8814d3229ull, 0x966296965231f4c4ull, - 0xf9c3f9f962ef3a9bull, 0xc533c5c5a397f666ull, 0x25942525104ab135ull, 0x59795959abb220f2ull, - 0x842a8484d015ae54ull, 0x72d57272c5e4a7b7ull, 0x39e43939ec72ddd5ull, 0x4c2d4c4c1698615aull, - 0x5e655e5e94bc3bcaull, 0x78fd78789ff085e7ull, 0x38e03838e570d8ddull, 0x8c0a8c8c98058614ull, - 0xd163d1d117bfb2c6ull, 0xa5aea5a5e4570b41ull, 0xe2afe2e2a1d94d43ull, 0x619961614ec2f82full, - 0xb3f6b3b3427b45f1ull, 0x218421213442a515ull, 0x9c4a9c9c0825d694ull, 0x1e781e1eee3c66f0ull, - 0x4311434361865222ull, 0xc73bc7c7b193fc76ull, 0xfcd7fcfc4fe52bb3ull, 0x0410040424081420ull, - 0x51595151e3a208b2ull, 0x995e9999252fc7bcull, 0x6da96d6d22dac44full, 0x0d340d0d651a3968ull, - 0xfacffafa79e93583ull, 0xdf5bdfdf69a384b6ull, 0x7ee57e7ea9fc9bd7ull, 0x249024241948b43dull, - 0x3bec3b3bfe76d7c5ull, 0xab96abab9a4b3d31ull, 0xce1fcecef081d13eull, 0x1144111199225588ull, - 0x8f068f8f8303890cull, 0x4e254e4e049c6b4aull, 0xb7e6b7b7667351d1ull, 0xeb8bebebe0cb600bull, - 0x3cf03c3cc178ccfdull, 0x813e8181fd1fbf7cull, 0x946a94944035fed4ull, 0xf7fbf7f71cf30cebull, - 0xb9deb9b9186f67a1ull, 0x134c13138b265f98ull, 0x2cb02c2c51589c7dull, 0xd36bd3d305bbb8d6ull, - 0xe7bbe7e78cd35c6bull, 0x6ea56e6e39dccb57ull, 0xc437c4c4aa95f36eull, 0x030c03031b060f18ull, - 0x56455656dcac138aull, 0x440d44445e88491aull, 0x7fe17f7fa0fe9edfull, 0xa99ea9a9884f3721ull, - 0x2aa82a2a6754824dull, 0xbbd6bbbb0a6b6db1ull, 0xc123c1c1879fe246ull, 0x53515353f1a602a2ull, - 0xdc57dcdc72a58baeull, 0x0b2c0b0b53162758ull, 0x9d4e9d9d0127d39cull, 0x6cad6c6c2bd8c147ull, - 0x31c43131a462f595ull, 0x74cd7474f3e8b987ull, 0xf6fff6f615f109e3ull, 0x460546464c8c430aull, - 0xac8aacaca5452609ull, 0x891e8989b50f973cull, 0x14501414b42844a0ull, 0xe1a3e1e1badf425bull, - 0x16581616a62c4eb0ull, 0x3ae83a3af774d2cdull, 0x69b9696906d2d06full, 0x0924090941122d48ull, - 0x70dd7070d7e0ada7ull, 0xb6e2b6b66f7154d9ull, 0xd067d0d01ebdb7ceull, 0xed93ededd6c77e3bull, - 0xcc17cccce285db2eull, 0x421542426884572aull, 0x985a98982c2dc2b4ull, 0xa4aaa4a4ed550e49ull, - 0x28a028287550885dull, 0x5c6d5c5c86b831daull, 0xf8c7f8f86bed3f93ull, 0x86228686c211a444ull - }, - { - 0x601818d83078c018ull, 0x8c23232646af0523ull, 0x3fc6c6b891f97ec6ull, 0x87e8e8fbcd6f13e8ull, - 0x268787cb13a14c87ull, 0xdab8b8116d62a9b8ull, 0x0401010902050801ull, 0x214f4f0d9e6e424full, - 0xd836369b6ceead36ull, 0xa2a6a6ff510459a6ull, 0x6fd2d20cb9bdded2ull, 0xf3f5f50ef706fbf5ull, - 0xf9797996f280ef79ull, 0xa16f6f30dece5f6full, 0x7e91916d3feffc91ull, 0x555252f8a407aa52ull, - 0x9d606047c0fd2760ull, 0xcabcbc35657689bcull, 0x569b9b372bcdac9bull, 0x028e8e8a018c048eull, - 0xb6a3a3d25b1571a3ull, 0x300c0c6c183c600cull, 0xf17b7b84f68aff7bull, 0xd43535806ae1b535ull, - 0x741d1df53a69e81dull, 0xa7e0e0b3dd4753e0ull, 0x7bd7d721b3acf6d7ull, 0x2fc2c29c99ed5ec2ull, - 0xb82e2e435c966d2eull, 0x314b4b29967a624bull, 0xdffefe5de121a3feull, 0x415757d5ae168257ull, - 0x541515bd2a41a815ull, 0xc17777e8eeb69f77ull, 0xdc3737926eeba537ull, 0xb3e5e59ed7567be5ull, - 0x469f9f1323d98c9full, 0xe7f0f023fd17d3f0ull, 0x354a4a20947f6a4aull, 0x4fdada44a9959edaull, - 0x7d5858a2b025fa58ull, 0x03c9c9cf8fca06c9ull, 0xa429297c528d5529ull, 0x280a0a5a1422500aull, - 0xfeb1b1507f4fe1b1ull, 0xbaa0a0c95d1a69a0ull, 0xb16b6b14d6da7f6bull, 0x2e8585d917ab5c85ull, - 0xcebdbd3c677381bdull, 0x695d5d8fba34d25dull, 0x4010109020508010ull, 0xf7f4f407f503f3f4ull, - 0x0bcbcbdd8bc016cbull, 0xf83e3ed37cc6ed3eull, 0x1405052d0a112805ull, 0x81676778cee61f67ull, - 0xb7e4e497d55373e4ull, 0x9c2727024ebb2527ull, 0x1941417382583241ull, 0x168b8ba70b9d2c8bull, - 0xa6a7a7f6530151a7ull, 0xe97d7db2fa94cf7dull, 0x6e95954937fbdc95ull, 0x47d8d856ad9f8ed8ull, - 0xcbfbfb70eb308bfbull, 0x9feeeecdc17123eeull, 0xed7c7cbbf891c77cull, 0x85666671cce31766ull, - 0x53dddd7ba78ea6ddull, 0x5c1717af2e4bb817ull, 0x014747458e460247ull, 0x429e9e1a21dc849eull, - 0x0fcacad489c51ecaull, 0xb42d2d585a99752dull, 0xc6bfbf2e637991bfull, 0x1c07073f0e1b3807ull, - 0x8eadadac472301adull, 0x755a5ab0b42fea5aull, 0x368383ef1bb56c83ull, 0xcc3333b666ff8533ull, - 0x9163635cc6f23f63ull, 0x08020212040a1002ull, 0x92aaaa93493839aaull, 0xd97171dee2a8af71ull, - 0x07c8c8c68dcf0ec8ull, 0x641919d1327dc819ull, 0x3949493b92707249ull, 0x43d9d95faf9a86d9ull, - 0xeff2f231f91dc3f2ull, 0xabe3e3a8db484be3ull, 0x715b5bb9b62ae25bull, 0x1a8888bc0d923488ull, - 0x529a9a3e29c8a49aull, 0x9826260b4cbe2d26ull, 0xc83232bf64fa8d32ull, 0xfab0b0597d4ae9b0ull, - 0x83e9e9f2cf6a1be9ull, 0x3c0f0f771e33780full, 0x73d5d533b7a6e6d5ull, 0x3a8080f41dba7480ull, - 0xc2bebe27617c99beull, 0x13cdcdeb87de26cdull, 0xd034348968e4bd34ull, 0x3d48483290757a48ull, - 0xdbffff54e324abffull, 0xf57a7a8df48ff77aull, 0x7a9090643deaf490ull, 0x615f5f9dbe3ec25full, - 0x8020203d40a01d20ull, 0xbd68680fd0d56768ull, 0x681a1aca3472d01aull, 0x82aeaeb7412c19aeull, - 0xeab4b47d755ec9b4ull, 0x4d5454cea8199a54ull, 0x7693937f3be5ec93ull, 0x8822222f44aa0d22ull, - 0x8d646463c8e90764ull, 0xe3f1f12aff12dbf1ull, 0xd17373cce6a2bf73ull, 0x48121282245a9012ull, - 0x1d40407a805d3a40ull, 0x2008084810284008ull, 0x2bc3c3959be856c3ull, 0x97ececdfc57b33ecull, - 0x4bdbdb4dab9096dbull, 0xbea1a1c05f1f61a1ull, 0x0e8d8d9107831c8dull, 0xf43d3dc87ac9f53dull, - 0x6697975b33f1cc97ull, 0x0000000000000000ull, 0x1bcfcff983d436cfull, 0xac2b2b6e5687452bull, - 0xc57676e1ecb39776ull, 0x328282e619b06482ull, 0x7fd6d628b1a9fed6ull, 0x6c1b1bc33677d81bull, - 0xeeb5b574775bc1b5ull, 0x86afafbe432911afull, 0xb56a6a1dd4df776aull, 0x5d5050eaa00dba50ull, - 0x094545578a4c1245ull, 0xebf3f338fb18cbf3ull, 0xc03030ad60f09d30ull, 0x9befefc4c3742befull, - 0xfc3f3fda7ec3e53full, 0x495555c7aa1c9255ull, 0xb2a2a2db591079a2ull, 0x8feaeae9c96503eaull, - 0x8965656acaec0f65ull, 0xd2baba036968b9baull, 0xbc2f2f4a5e93652full, 0x27c0c08e9de74ec0ull, - 0x5fdede60a181bedeull, 0x701c1cfc386ce01cull, 0xd3fdfd46e72ebbfdull, 0x294d4d1f9a64524dull, - 0x7292927639e0e492ull, 0xc97575faeabc8f75ull, 0x180606360c1e3006ull, 0x128a8aae0998248aull, - 0xf2b2b24b7940f9b2ull, 0xbfe6e685d15963e6ull, 0x380e0e7e1c36700eull, 0x7c1f1fe73e63f81full, - 0x95626255c4f73762ull, 0x77d4d43ab5a3eed4ull, 0x9aa8a8814d3229a8ull, 0x6296965231f4c496ull, - 0xc3f9f962ef3a9bf9ull, 0x33c5c5a397f666c5ull, 0x942525104ab13525ull, 0x795959abb220f259ull, - 0x2a8484d015ae5484ull, 0xd57272c5e4a7b772ull, 0xe43939ec72ddd539ull, 0x2d4c4c1698615a4cull, - 0x655e5e94bc3bca5eull, 0xfd78789ff085e778ull, 0xe03838e570d8dd38ull, 0x0a8c8c980586148cull, - 0x63d1d117bfb2c6d1ull, 0xaea5a5e4570b41a5ull, 0xafe2e2a1d94d43e2ull, 0x9961614ec2f82f61ull, - 0xf6b3b3427b45f1b3ull, 0x8421213442a51521ull, 0x4a9c9c0825d6949cull, 0x781e1eee3c66f01eull, - 0x1143436186522243ull, 0x3bc7c7b193fc76c7ull, 0xd7fcfc4fe52bb3fcull, 0x1004042408142004ull, - 0x595151e3a208b251ull, 0x5e9999252fc7bc99ull, 0xa96d6d22dac44f6dull, 0x340d0d651a39680dull, - 0xcffafa79e93583faull, 0x5bdfdf69a384b6dfull, 0xe57e7ea9fc9bd77eull, 0x9024241948b43d24ull, - 0xec3b3bfe76d7c53bull, 0x96abab9a4b3d31abull, 0x1fcecef081d13eceull, 0x4411119922558811ull, - 0x068f8f8303890c8full, 0x254e4e049c6b4a4eull, 0xe6b7b7667351d1b7ull, 0x8bebebe0cb600bebull, - 0xf03c3cc178ccfd3cull, 0x3e8181fd1fbf7c81ull, 0x6a94944035fed494ull, 0xfbf7f71cf30cebf7ull, - 0xdeb9b9186f67a1b9ull, 0x4c13138b265f9813ull, 0xb02c2c51589c7d2cull, 0x6bd3d305bbb8d6d3ull, - 0xbbe7e78cd35c6be7ull, 0xa56e6e39dccb576eull, 0x37c4c4aa95f36ec4ull, 0x0c03031b060f1803ull, - 0x455656dcac138a56ull, 0x0d44445e88491a44ull, 0xe17f7fa0fe9edf7full, 0x9ea9a9884f3721a9ull, - 0xa82a2a6754824d2aull, 0xd6bbbb0a6b6db1bbull, 0x23c1c1879fe246c1ull, 0x515353f1a602a253ull, - 0x57dcdc72a58baedcull, 0x2c0b0b531627580bull, 0x4e9d9d0127d39c9dull, 0xad6c6c2bd8c1476cull, - 0xc43131a462f59531ull, 0xcd7474f3e8b98774ull, 0xfff6f615f109e3f6ull, 0x0546464c8c430a46ull, - 0x8aacaca5452609acull, 0x1e8989b50f973c89ull, 0x501414b42844a014ull, 0xa3e1e1badf425be1ull, - 0x581616a62c4eb016ull, 0xe83a3af774d2cd3aull, 0xb9696906d2d06f69ull, 0x24090941122d4809ull, - 0xdd7070d7e0ada770ull, 0xe2b6b66f7154d9b6ull, 0x67d0d01ebdb7ced0ull, 0x93ededd6c77e3bedull, - 0x17cccce285db2eccull, 0x1542426884572a42ull, 0x5a98982c2dc2b498ull, 0xaaa4a4ed550e49a4ull, - 0xa028287550885d28ull, 0x6d5c5c86b831da5cull, 0xc7f8f86bed3f93f8ull, 0x228686c211a44486ull - }, - { - 0x1818d83078c01860ull, 0x23232646af05238cull, 0xc6c6b891f97ec63full, 0xe8e8fbcd6f13e887ull, - 0x8787cb13a14c8726ull, 0xb8b8116d62a9b8daull, 0x0101090205080104ull, 0x4f4f0d9e6e424f21ull, - 0x36369b6ceead36d8ull, 0xa6a6ff510459a6a2ull, 0xd2d20cb9bdded26full, 0xf5f50ef706fbf5f3ull, - 0x797996f280ef79f9ull, 0x6f6f30dece5f6fa1ull, 0x91916d3feffc917eull, 0x5252f8a407aa5255ull, - 0x606047c0fd27609dull, 0xbcbc35657689bccaull, 0x9b9b372bcdac9b56ull, 0x8e8e8a018c048e02ull, - 0xa3a3d25b1571a3b6ull, 0x0c0c6c183c600c30ull, 0x7b7b84f68aff7bf1ull, 0x3535806ae1b535d4ull, - 0x1d1df53a69e81d74ull, 0xe0e0b3dd4753e0a7ull, 0xd7d721b3acf6d77bull, 0xc2c29c99ed5ec22full, - 0x2e2e435c966d2eb8ull, 0x4b4b29967a624b31ull, 0xfefe5de121a3fedfull, 0x5757d5ae16825741ull, - 0x1515bd2a41a81554ull, 0x7777e8eeb69f77c1ull, 0x3737926eeba537dcull, 0xe5e59ed7567be5b3ull, - 0x9f9f1323d98c9f46ull, 0xf0f023fd17d3f0e7ull, 0x4a4a20947f6a4a35ull, 0xdada44a9959eda4full, - 0x5858a2b025fa587dull, 0xc9c9cf8fca06c903ull, 0x29297c528d5529a4ull, 0x0a0a5a1422500a28ull, - 0xb1b1507f4fe1b1feull, 0xa0a0c95d1a69a0baull, 0x6b6b14d6da7f6bb1ull, 0x8585d917ab5c852eull, - 0xbdbd3c677381bdceull, 0x5d5d8fba34d25d69ull, 0x1010902050801040ull, 0xf4f407f503f3f4f7ull, - 0xcbcbdd8bc016cb0bull, 0x3e3ed37cc6ed3ef8ull, 0x05052d0a11280514ull, 0x676778cee61f6781ull, - 0xe4e497d55373e4b7ull, 0x2727024ebb25279cull, 0x4141738258324119ull, 0x8b8ba70b9d2c8b16ull, - 0xa7a7f6530151a7a6ull, 0x7d7db2fa94cf7de9ull, 0x95954937fbdc956eull, 0xd8d856ad9f8ed847ull, - 0xfbfb70eb308bfbcbull, 0xeeeecdc17123ee9full, 0x7c7cbbf891c77cedull, 0x666671cce3176685ull, - 0xdddd7ba78ea6dd53ull, 0x1717af2e4bb8175cull, 0x4747458e46024701ull, 0x9e9e1a21dc849e42ull, - 0xcacad489c51eca0full, 0x2d2d585a99752db4ull, 0xbfbf2e637991bfc6ull, 0x07073f0e1b38071cull, - 0xadadac472301ad8eull, 0x5a5ab0b42fea5a75ull, 0x8383ef1bb56c8336ull, 0x3333b666ff8533ccull, - 0x63635cc6f23f6391ull, 0x020212040a100208ull, 0xaaaa93493839aa92ull, 0x7171dee2a8af71d9ull, - 0xc8c8c68dcf0ec807ull, 0x1919d1327dc81964ull, 0x49493b9270724939ull, 0xd9d95faf9a86d943ull, - 0xf2f231f91dc3f2efull, 0xe3e3a8db484be3abull, 0x5b5bb9b62ae25b71ull, 0x8888bc0d9234881aull, - 0x9a9a3e29c8a49a52ull, 0x26260b4cbe2d2698ull, 0x3232bf64fa8d32c8ull, 0xb0b0597d4ae9b0faull, - 0xe9e9f2cf6a1be983ull, 0x0f0f771e33780f3cull, 0xd5d533b7a6e6d573ull, 0x8080f41dba74803aull, - 0xbebe27617c99bec2ull, 0xcdcdeb87de26cd13ull, 0x34348968e4bd34d0ull, 0x48483290757a483dull, - 0xffff54e324abffdbull, 0x7a7a8df48ff77af5ull, 0x9090643deaf4907aull, 0x5f5f9dbe3ec25f61ull, - 0x20203d40a01d2080ull, 0x68680fd0d56768bdull, 0x1a1aca3472d01a68ull, 0xaeaeb7412c19ae82ull, - 0xb4b47d755ec9b4eaull, 0x5454cea8199a544dull, 0x93937f3be5ec9376ull, 0x22222f44aa0d2288ull, - 0x646463c8e907648dull, 0xf1f12aff12dbf1e3ull, 0x7373cce6a2bf73d1ull, 0x121282245a901248ull, - 0x40407a805d3a401dull, 0x0808481028400820ull, 0xc3c3959be856c32bull, 0xececdfc57b33ec97ull, - 0xdbdb4dab9096db4bull, 0xa1a1c05f1f61a1beull, 0x8d8d9107831c8d0eull, 0x3d3dc87ac9f53df4ull, - 0x97975b33f1cc9766ull, 0x0000000000000000ull, 0xcfcff983d436cf1bull, 0x2b2b6e5687452bacull, - 0x7676e1ecb39776c5ull, 0x8282e619b0648232ull, 0xd6d628b1a9fed67full, 0x1b1bc33677d81b6cull, - 0xb5b574775bc1b5eeull, 0xafafbe432911af86ull, 0x6a6a1dd4df776ab5ull, 0x5050eaa00dba505dull, - 0x4545578a4c124509ull, 0xf3f338fb18cbf3ebull, 0x3030ad60f09d30c0ull, 0xefefc4c3742bef9bull, - 0x3f3fda7ec3e53ffcull, 0x5555c7aa1c925549ull, 0xa2a2db591079a2b2ull, 0xeaeae9c96503ea8full, - 0x65656acaec0f6589ull, 0xbaba036968b9bad2ull, 0x2f2f4a5e93652fbcull, 0xc0c08e9de74ec027ull, - 0xdede60a181bede5full, 0x1c1cfc386ce01c70ull, 0xfdfd46e72ebbfdd3ull, 0x4d4d1f9a64524d29ull, - 0x92927639e0e49272ull, 0x7575faeabc8f75c9ull, 0x0606360c1e300618ull, 0x8a8aae0998248a12ull, - 0xb2b24b7940f9b2f2ull, 0xe6e685d15963e6bfull, 0x0e0e7e1c36700e38ull, 0x1f1fe73e63f81f7cull, - 0x626255c4f7376295ull, 0xd4d43ab5a3eed477ull, 0xa8a8814d3229a89aull, 0x96965231f4c49662ull, - 0xf9f962ef3a9bf9c3ull, 0xc5c5a397f666c533ull, 0x2525104ab1352594ull, 0x5959abb220f25979ull, - 0x8484d015ae54842aull, 0x7272c5e4a7b772d5ull, 0x3939ec72ddd539e4ull, 0x4c4c1698615a4c2dull, - 0x5e5e94bc3bca5e65ull, 0x78789ff085e778fdull, 0x3838e570d8dd38e0ull, 0x8c8c980586148c0aull, - 0xd1d117bfb2c6d163ull, 0xa5a5e4570b41a5aeull, 0xe2e2a1d94d43e2afull, 0x61614ec2f82f6199ull, - 0xb3b3427b45f1b3f6ull, 0x21213442a5152184ull, 0x9c9c0825d6949c4aull, 0x1e1eee3c66f01e78ull, - 0x4343618652224311ull, 0xc7c7b193fc76c73bull, 0xfcfc4fe52bb3fcd7ull, 0x0404240814200410ull, - 0x5151e3a208b25159ull, 0x9999252fc7bc995eull, 0x6d6d22dac44f6da9ull, 0x0d0d651a39680d34ull, - 0xfafa79e93583facfull, 0xdfdf69a384b6df5bull, 0x7e7ea9fc9bd77ee5ull, 0x24241948b43d2490ull, - 0x3b3bfe76d7c53becull, 0xabab9a4b3d31ab96ull, 0xcecef081d13ece1full, 0x1111992255881144ull, - 0x8f8f8303890c8f06ull, 0x4e4e049c6b4a4e25ull, 0xb7b7667351d1b7e6ull, 0xebebe0cb600beb8bull, - 0x3c3cc178ccfd3cf0ull, 0x8181fd1fbf7c813eull, 0x94944035fed4946aull, 0xf7f71cf30cebf7fbull, - 0xb9b9186f67a1b9deull, 0x13138b265f98134cull, 0x2c2c51589c7d2cb0ull, 0xd3d305bbb8d6d36bull, - 0xe7e78cd35c6be7bbull, 0x6e6e39dccb576ea5ull, 0xc4c4aa95f36ec437ull, 0x03031b060f18030cull, - 0x5656dcac138a5645ull, 0x44445e88491a440dull, 0x7f7fa0fe9edf7fe1ull, 0xa9a9884f3721a99eull, - 0x2a2a6754824d2aa8ull, 0xbbbb0a6b6db1bbd6ull, 0xc1c1879fe246c123ull, 0x5353f1a602a25351ull, - 0xdcdc72a58baedc57ull, 0x0b0b531627580b2cull, 0x9d9d0127d39c9d4eull, 0x6c6c2bd8c1476cadull, - 0x3131a462f59531c4ull, 0x7474f3e8b98774cdull, 0xf6f615f109e3f6ffull, 0x46464c8c430a4605ull, - 0xacaca5452609ac8aull, 0x8989b50f973c891eull, 0x1414b42844a01450ull, 0xe1e1badf425be1a3ull, - 0x1616a62c4eb01658ull, 0x3a3af774d2cd3ae8ull, 0x696906d2d06f69b9ull, 0x090941122d480924ull, - 0x7070d7e0ada770ddull, 0xb6b66f7154d9b6e2ull, 0xd0d01ebdb7ced067ull, 0xededd6c77e3bed93ull, - 0xcccce285db2ecc17ull, 0x42426884572a4215ull, 0x98982c2dc2b4985aull, 0xa4a4ed550e49a4aaull, - 0x28287550885d28a0ull, 0x5c5c86b831da5c6dull, 0xf8f86bed3f93f8c7ull, 0x8686c211a4448622ull - }, - { - 0x18d83078c0186018ull, 0x232646af05238c23ull, 0xc6b891f97ec63fc6ull, 0xe8fbcd6f13e887e8ull, - 0x87cb13a14c872687ull, 0xb8116d62a9b8dab8ull, 0x0109020508010401ull, 0x4f0d9e6e424f214full, - 0x369b6ceead36d836ull, 0xa6ff510459a6a2a6ull, 0xd20cb9bdded26fd2ull, 0xf50ef706fbf5f3f5ull, - 0x7996f280ef79f979ull, 0x6f30dece5f6fa16full, 0x916d3feffc917e91ull, 0x52f8a407aa525552ull, - 0x6047c0fd27609d60ull, 0xbc35657689bccabcull, 0x9b372bcdac9b569bull, 0x8e8a018c048e028eull, - 0xa3d25b1571a3b6a3ull, 0x0c6c183c600c300cull, 0x7b84f68aff7bf17bull, 0x35806ae1b535d435ull, - 0x1df53a69e81d741dull, 0xe0b3dd4753e0a7e0ull, 0xd721b3acf6d77bd7ull, 0xc29c99ed5ec22fc2ull, - 0x2e435c966d2eb82eull, 0x4b29967a624b314bull, 0xfe5de121a3fedffeull, 0x57d5ae1682574157ull, - 0x15bd2a41a8155415ull, 0x77e8eeb69f77c177ull, 0x37926eeba537dc37ull, 0xe59ed7567be5b3e5ull, - 0x9f1323d98c9f469full, 0xf023fd17d3f0e7f0ull, 0x4a20947f6a4a354aull, 0xda44a9959eda4fdaull, - 0x58a2b025fa587d58ull, 0xc9cf8fca06c903c9ull, 0x297c528d5529a429ull, 0x0a5a1422500a280aull, - 0xb1507f4fe1b1feb1ull, 0xa0c95d1a69a0baa0ull, 0x6b14d6da7f6bb16bull, 0x85d917ab5c852e85ull, - 0xbd3c677381bdcebdull, 0x5d8fba34d25d695dull, 0x1090205080104010ull, 0xf407f503f3f4f7f4ull, - 0xcbdd8bc016cb0bcbull, 0x3ed37cc6ed3ef83eull, 0x052d0a1128051405ull, 0x6778cee61f678167ull, - 0xe497d55373e4b7e4ull, 0x27024ebb25279c27ull, 0x4173825832411941ull, 0x8ba70b9d2c8b168bull, - 0xa7f6530151a7a6a7ull, 0x7db2fa94cf7de97dull, 0x954937fbdc956e95ull, 0xd856ad9f8ed847d8ull, - 0xfb70eb308bfbcbfbull, 0xeecdc17123ee9feeull, 0x7cbbf891c77ced7cull, 0x6671cce317668566ull, - 0xdd7ba78ea6dd53ddull, 0x17af2e4bb8175c17ull, 0x47458e4602470147ull, 0x9e1a21dc849e429eull, - 0xcad489c51eca0fcaull, 0x2d585a99752db42dull, 0xbf2e637991bfc6bfull, 0x073f0e1b38071c07ull, - 0xadac472301ad8eadull, 0x5ab0b42fea5a755aull, 0x83ef1bb56c833683ull, 0x33b666ff8533cc33ull, - 0x635cc6f23f639163ull, 0x0212040a10020802ull, 0xaa93493839aa92aaull, 0x71dee2a8af71d971ull, - 0xc8c68dcf0ec807c8ull, 0x19d1327dc8196419ull, 0x493b927072493949ull, 0xd95faf9a86d943d9ull, - 0xf231f91dc3f2eff2ull, 0xe3a8db484be3abe3ull, 0x5bb9b62ae25b715bull, 0x88bc0d9234881a88ull, - 0x9a3e29c8a49a529aull, 0x260b4cbe2d269826ull, 0x32bf64fa8d32c832ull, 0xb0597d4ae9b0fab0ull, - 0xe9f2cf6a1be983e9ull, 0x0f771e33780f3c0full, 0xd533b7a6e6d573d5ull, 0x80f41dba74803a80ull, - 0xbe27617c99bec2beull, 0xcdeb87de26cd13cdull, 0x348968e4bd34d034ull, 0x483290757a483d48ull, - 0xff54e324abffdbffull, 0x7a8df48ff77af57aull, 0x90643deaf4907a90ull, 0x5f9dbe3ec25f615full, - 0x203d40a01d208020ull, 0x680fd0d56768bd68ull, 0x1aca3472d01a681aull, 0xaeb7412c19ae82aeull, - 0xb47d755ec9b4eab4ull, 0x54cea8199a544d54ull, 0x937f3be5ec937693ull, 0x222f44aa0d228822ull, - 0x6463c8e907648d64ull, 0xf12aff12dbf1e3f1ull, 0x73cce6a2bf73d173ull, 0x1282245a90124812ull, - 0x407a805d3a401d40ull, 0x0848102840082008ull, 0xc3959be856c32bc3ull, 0xecdfc57b33ec97ecull, - 0xdb4dab9096db4bdbull, 0xa1c05f1f61a1bea1ull, 0x8d9107831c8d0e8dull, 0x3dc87ac9f53df43dull, - 0x975b33f1cc976697ull, 0x0000000000000000ull, 0xcff983d436cf1bcfull, 0x2b6e5687452bac2bull, - 0x76e1ecb39776c576ull, 0x82e619b064823282ull, 0xd628b1a9fed67fd6ull, 0x1bc33677d81b6c1bull, - 0xb574775bc1b5eeb5ull, 0xafbe432911af86afull, 0x6a1dd4df776ab56aull, 0x50eaa00dba505d50ull, - 0x45578a4c12450945ull, 0xf338fb18cbf3ebf3ull, 0x30ad60f09d30c030ull, 0xefc4c3742bef9befull, - 0x3fda7ec3e53ffc3full, 0x55c7aa1c92554955ull, 0xa2db591079a2b2a2ull, 0xeae9c96503ea8feaull, - 0x656acaec0f658965ull, 0xba036968b9bad2baull, 0x2f4a5e93652fbc2full, 0xc08e9de74ec027c0ull, - 0xde60a181bede5fdeull, 0x1cfc386ce01c701cull, 0xfd46e72ebbfdd3fdull, 0x4d1f9a64524d294dull, - 0x927639e0e4927292ull, 0x75faeabc8f75c975ull, 0x06360c1e30061806ull, 0x8aae0998248a128aull, - 0xb24b7940f9b2f2b2ull, 0xe685d15963e6bfe6ull, 0x0e7e1c36700e380eull, 0x1fe73e63f81f7c1full, - 0x6255c4f737629562ull, 0xd43ab5a3eed477d4ull, 0xa8814d3229a89aa8ull, 0x965231f4c4966296ull, - 0xf962ef3a9bf9c3f9ull, 0xc5a397f666c533c5ull, 0x25104ab135259425ull, 0x59abb220f2597959ull, - 0x84d015ae54842a84ull, 0x72c5e4a7b772d572ull, 0x39ec72ddd539e439ull, 0x4c1698615a4c2d4cull, - 0x5e94bc3bca5e655eull, 0x789ff085e778fd78ull, 0x38e570d8dd38e038ull, 0x8c980586148c0a8cull, - 0xd117bfb2c6d163d1ull, 0xa5e4570b41a5aea5ull, 0xe2a1d94d43e2afe2ull, 0x614ec2f82f619961ull, - 0xb3427b45f1b3f6b3ull, 0x213442a515218421ull, 0x9c0825d6949c4a9cull, 0x1eee3c66f01e781eull, - 0x4361865222431143ull, 0xc7b193fc76c73bc7ull, 0xfc4fe52bb3fcd7fcull, 0x0424081420041004ull, - 0x51e3a208b2515951ull, 0x99252fc7bc995e99ull, 0x6d22dac44f6da96dull, 0x0d651a39680d340dull, - 0xfa79e93583facffaull, 0xdf69a384b6df5bdfull, 0x7ea9fc9bd77ee57eull, 0x241948b43d249024ull, - 0x3bfe76d7c53bec3bull, 0xab9a4b3d31ab96abull, 0xcef081d13ece1fceull, 0x1199225588114411ull, - 0x8f8303890c8f068full, 0x4e049c6b4a4e254eull, 0xb7667351d1b7e6b7ull, 0xebe0cb600beb8bebull, - 0x3cc178ccfd3cf03cull, 0x81fd1fbf7c813e81ull, 0x944035fed4946a94ull, 0xf71cf30cebf7fbf7ull, - 0xb9186f67a1b9deb9ull, 0x138b265f98134c13ull, 0x2c51589c7d2cb02cull, 0xd305bbb8d6d36bd3ull, - 0xe78cd35c6be7bbe7ull, 0x6e39dccb576ea56eull, 0xc4aa95f36ec437c4ull, 0x031b060f18030c03ull, - 0x56dcac138a564556ull, 0x445e88491a440d44ull, 0x7fa0fe9edf7fe17full, 0xa9884f3721a99ea9ull, - 0x2a6754824d2aa82aull, 0xbb0a6b6db1bbd6bbull, 0xc1879fe246c123c1ull, 0x53f1a602a2535153ull, - 0xdc72a58baedc57dcull, 0x0b531627580b2c0bull, 0x9d0127d39c9d4e9dull, 0x6c2bd8c1476cad6cull, - 0x31a462f59531c431ull, 0x74f3e8b98774cd74ull, 0xf615f109e3f6fff6ull, 0x464c8c430a460546ull, - 0xaca5452609ac8aacull, 0x89b50f973c891e89ull, 0x14b42844a0145014ull, 0xe1badf425be1a3e1ull, - 0x16a62c4eb0165816ull, 0x3af774d2cd3ae83aull, 0x6906d2d06f69b969ull, 0x0941122d48092409ull, - 0x70d7e0ada770dd70ull, 0xb66f7154d9b6e2b6ull, 0xd01ebdb7ced067d0ull, 0xedd6c77e3bed93edull, - 0xcce285db2ecc17ccull, 0x426884572a421542ull, 0x982c2dc2b4985a98ull, 0xa4ed550e49a4aaa4ull, - 0x287550885d28a028ull, 0x5c86b831da5c6d5cull, 0xf86bed3f93f8c7f8ull, 0x86c211a444862286ull - } -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/groestl_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/groestl_provider.hpp deleted file mode 100644 index 0aae4ff..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/groestl_provider.hpp +++ /dev/null @@ -1,202 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_GROESTL_HPP -#define DIGESTPP_PROVIDERS_GROESTL_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/groestl_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace groestl_functions -{ - template - static inline void roundP(uint64_t* x, uint64_t* y, uint64_t i) - { - for (int idx = 0; idx < R; idx++) - x[idx] ^= (static_cast(idx) << 4) ^ i; - - for (int c = R - 1; c >= 0; c--) - y[c] = groestl_constants::T[0][static_cast(x[(c + 0) % R])] - ^ groestl_constants::T[1][static_cast(x[(c + 1) % R] >> 8)] - ^ groestl_constants::T[2][static_cast(x[(c + 2) % R] >> 16)] - ^ groestl_constants::T[3][static_cast(x[(c + 3) % R] >> 24)] - ^ groestl_constants::T[4][static_cast(x[(c + 4) % R] >> 32)] - ^ groestl_constants::T[5][static_cast(x[(c + 5) % R] >> 40)] - ^ groestl_constants::T[6][static_cast(x[(c + 6) % R] >> 48)] - ^ groestl_constants::T[7][static_cast(x[(c + (R == 16 ? 11 : 7)) % R] >> 56)]; - } - - template - static inline void roundQ(uint64_t* x, uint64_t* y, uint64_t i) - { - for (int idx = 0; idx < R; idx++) - x[idx] ^= (0xffffffffffffffffull - (static_cast(idx) << 60)) ^ i; - - for (int c = R - 1; c >= 0; c--) - y[c] = groestl_constants::T[0][static_cast(x[(c + 1) % R])] - ^ groestl_constants::T[1][static_cast(x[(c + 3) % R] >> 8)] - ^ groestl_constants::T[2][static_cast(x[(c + 5) % R] >> 16)] - ^ groestl_constants::T[3][static_cast(x[(c + (R == 16 ? 11 : 7)) % R] >> 24)] - ^ groestl_constants::T[4][static_cast(x[(c + 0) % R] >> 32)] - ^ groestl_constants::T[5][static_cast(x[(c + 2) % R] >> 40)] - ^ groestl_constants::T[6][static_cast(x[(c + 4) % R] >> 48)] - ^ groestl_constants::T[7][static_cast(x[(c + 6) % R] >> 56)]; - } - - template - static inline void transform(uint64_t* h, const uint64_t* m) - { - uint64_t AQ1[R], AQ2[R], AP1[R], AP2[R]; - - for (int column = 0; column < R; column++) - { - AP1[column] = h[column] ^ m[column]; - AQ1[column] = m[column]; - } - - for (uint64_t r = 0; r < (R == 16 ? 14 : 10); r += 2) - { - roundP(AP1, AP2, r); - roundP(AP2, AP1, r + 1); - roundQ(AQ1, AQ2, r << 56); - roundQ(AQ2, AQ1, (r + 1ull) << 56); - } - - for (int column = 0; column < R; column++) - { - h[column] = AP1[column] ^ AQ1[column] ^ h[column]; - } - } - - template - static inline void outputTransform(uint64_t* h) - { - uint64_t t1[R]; - uint64_t t2[R]; - - for (int column = 0; column < R; column++) { - t1[column] = h[column]; - } - - for (uint64_t r = 0; r < (R == 16 ? 14 : 10); r += 2) { - roundP(t1, t2, r); - roundP(t2, t1, r+1); - } - - for (int column = 0; column < R; column++) { - h[column] ^= t1[column]; - } - } - -} - -class groestl_provider -{ -public: - static const bool is_xof = false; - - groestl_provider(size_t hashsize) - : hs(hashsize) - { - validate_hash_size(hashsize, 512); - } - - ~groestl_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - memset(&h[0], 0, sizeof(uint64_t)*16); - uint64_t hs = hash_size(); - h[hs > 256 ? 15 : 7] = byteswap(hs); - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, block_bytes(), block_bytes(), m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - m[pos++] = 0x80; - total += pos * 8; - size_t limit = block_bytes(); - if (pos > limit - 8) - { - if (limit != pos) - memset(&m[pos], 0, limit - pos); - transform(m.data(), 1); - total += (block_bytes() - pos) * 8; - pos = 0; - } - memset(&m[pos], 0, limit - 8 - pos); - total += (block_bytes() - pos) * 8; - uint64_t mlen = byteswap(total / 8 / block_bytes()); - memcpy(&m[limit - 8], &mlen, 64 / 8); - transform(m.data(), 1); - outputTransform(); - - const unsigned char* s = reinterpret_cast(h.data()); - for (size_t i = limit - hash_size() / 8, j = 0; i < limit; i++, j++) { - hash[j] = s[i]; - } - } - - inline void clear() - { - zero_memory(h); - zero_memory(m); - } - - inline size_t hash_size() const { return hs; } - -private: - inline size_t block_bytes() const { return hs > 256 ? 128 : 64; } - - inline void outputTransform() - { - if (hs > 256) - groestl_functions::outputTransform<16>(&h[0]); - else - groestl_functions::outputTransform<8>(&h[0]); - } - - inline void transform(const unsigned char* mp, size_t num_blks) - { - for (size_t blk = 0; blk < num_blks; blk++) - { - if (hs > 256) - groestl_functions::transform<16>(&h[0], reinterpret_cast(mp + block_bytes() * blk)); - else - groestl_functions::transform<8>(&h[0], reinterpret_cast(mp + block_bytes() * blk)); - } - } - - std::array h; - std::array m; - size_t hs; - size_t pos; - uint64_t total; - -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/jh_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/jh_provider.hpp deleted file mode 100644 index 599c2b8..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/jh_provider.hpp +++ /dev/null @@ -1,214 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_JH_HPP -#define DIGESTPP_PROVIDERS_JH_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/jh_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace jh_functions -{ - static inline void bitswap(uint64_t& x, uint64_t mask, int shift) - { - x = ((x & mask) << shift) | ((x & ~mask) >> shift); - } - - static inline void bitswap(std::array& H, uint64_t mask, int shift) - { - bitswap(H[2], mask, shift); - bitswap(H[3], mask, shift); - bitswap(H[6], mask, shift); - bitswap(H[7], mask, shift); - bitswap(H[10], mask, shift); - bitswap(H[11], mask, shift); - bitswap(H[14], mask, shift); - bitswap(H[15], mask, shift); - } - - static inline void Sbitsli(uint64_t& x0a, uint64_t& x0b, uint64_t& x1a, uint64_t& x1b, uint64_t& x2a, uint64_t& x2b, - uint64_t& x3a, uint64_t& x3b, uint64_t ca, uint64_t cb) - { - x3a = ~x3a; - x3b = ~x3b; - x0a ^= (ca & ~x2a); - x0b ^= (cb & ~x2b); - uint64_t ta = ca ^ (x0a & x1a); - uint64_t tb = cb ^ (x0b & x1b); - x0a ^= (x2a & x3a); - x0b ^= (x2b & x3b); - x3a ^= (~x1a & x2a); - x3b ^= (~x1b & x2b); - x1a ^= (x0a & x2a); - x1b ^= (x0b & x2b); - x2a ^= (x0a & ~x3a); - x2b ^= (x0b & ~x3b); - x0a ^= (x1a | x3a); - x0b ^= (x1b | x3b); - x3a ^= (x1a & x2a); - x3b ^= (x1b & x2b); - x1a ^= (ta & x0a); - x1b ^= (tb & x0b); - x2a ^= ta; - x2b ^= tb; - } - - static inline void Lbitsli(std::array& H) - { - H[2] ^= H[4]; - H[3] ^= H[5]; - H[6] ^= H[8]; - H[7] ^= H[9]; - H[10] ^= H[12] ^ H[0]; - H[11] ^= H[13] ^ H[1]; - H[14] ^= H[0]; - H[15] ^= H[1]; - H[0] ^= H[6]; - H[1] ^= H[7]; - H[4] ^= H[10]; - H[5] ^= H[11]; - H[8] ^= H[14] ^ H[2]; - H[9] ^= H[15] ^ H[3]; - H[12] ^= H[2]; - H[13] ^= H[3]; - } - - static inline void round(std::array& H, int r, uint64_t mask, int shift) - { - jh_functions::Sbitsli(H[0], H[1], H[4], H[5], H[8], H[9], H[12], H[13], - jh_constants::C[r * 4 + 0], jh_constants::C[r * 4 + 1]); - jh_functions::Sbitsli(H[2], H[3], H[6], H[7], H[10], H[11], H[14], H[15], - jh_constants::C[r * 4 + 2], jh_constants::C[r * 4 + 3]); - jh_functions::Lbitsli(H); - if (shift) - jh_functions::bitswap(H, mask, shift); - } -} - -class jh_provider -{ -public: - static const bool is_xof = false; - - jh_provider(size_t hashsize = 512) - : hs(hashsize) - { - validate_hash_size(hashsize, 512); - } - - ~jh_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - - zero_memory(H); - H[0] = byteswap(static_cast(hs)); - - unsigned char msg[64]; - memset(msg, 0, sizeof(msg)); - transform(msg, 1); - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, 64, 64, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - m[pos++] = 0x80; - if (pos > 1) - { - if (pos != 64) - memset(&m[pos], 0, 64 - pos); - transform(&m[0], 1); - pos = 0; - } - memset(&m[0] + pos, 0, 56 - pos); - uint64_t mlen = byteswap(total); - memcpy(&m[0] + (64 - 8), &mlen, 64 / 8); - transform(&m[0], 1); - - memcpy(hash, reinterpret_cast(H.data()) + 128 - hash_size() / 8, hash_size() / 8); - } - - inline void clear() - { - zero_memory(H); - zero_memory(m); - } - - inline size_t hash_size() const { return hs; } - -private: - inline void transform(const unsigned char* mp, size_t num_blks) - { - for (uint64_t blk = 0; blk < num_blks; blk++) - { - const uint64_t* M = (const uint64_t*)(((const unsigned char*)mp) + blk * 64); - H[0] ^= M[0]; - H[1] ^= M[1]; - H[2] ^= M[2]; - H[3] ^= M[3]; - H[4] ^= M[4]; - H[5] ^= M[5]; - H[6] ^= M[6]; - H[7] ^= M[7]; - - // partially unroll - for (int r = 0; r < 42; r += 7) - { - jh_functions::round(H, r, 0x5555555555555555ULL, 1); - jh_functions::round(H, r + 1, 0x3333333333333333ULL, 2); - jh_functions::round(H, r + 2, 0x0f0f0f0f0f0f0f0fULL, 4); - jh_functions::round(H, r + 3, 0x00ff00ff00ff00ffULL, 8); - jh_functions::round(H, r + 4, 0x0000ffff0000ffffULL, 16); - jh_functions::round(H, r + 5, 0x00000000ffffffffULL, 32); - jh_functions::round(H, r + 6, 0, 0); - - std::swap(H[2], H[3]); - std::swap(H[6], H[7]); - std::swap(H[10], H[11]); - std::swap(H[14], H[15]); - } - - H[8] ^= M[0]; - H[9] ^= M[1]; - H[10] ^= M[2]; - H[11] ^= M[3]; - H[12] ^= M[4]; - H[13] ^= M[5]; - H[14] ^= M[6]; - H[15] ^= M[7]; - } - } - - std::array H; - std::array m; - size_t hs; - size_t pos; - uint64_t total; -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/k12m14_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/k12m14_provider.hpp deleted file mode 100644 index 6aefa09..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/k12m14_provider.hpp +++ /dev/null @@ -1,139 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_K12M14_HPP -#define DIGESTPP_PROVIDERS_K12M14_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "shake_provider.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -template -class k12m14_provider -{ -public: - static const bool is_xof = true; - - k12m14_provider() - { - static_assert(B == 128 || B == 256, "K12M14 only supports 128 and 256 bits"); - } - - ~k12m14_provider() - { - clear(); - } - - inline void set_customization(const std::string& customization) - { - S = customization; - } - - inline void init() - { - main.init(); - pos = 0; - total = 0; - chunk = 0; - squeezing = false; - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, m.size(), m.size(), m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len, len * 8192); }); - } - - inline void squeeze(unsigned char* hash, size_t hs) - { - if (!squeezing) - { - unsigned char buf[B / 4]; - size_t len = shake_functions::right_encode(S.length(), buf, true); - if (!S.empty()) - update(reinterpret_cast(S.data()), S.length()); - update(buf, len); - if (pos) - { - if (!chunk) - { - main.update(m.data(), pos); - main.set_suffix(0x07); - } - else - { - child.update(m.data(), pos); - child.squeeze(buf, B / 4); - main.update(buf, B / 4); - main.set_suffix(0x06); - len = shake_functions::right_encode(chunk, buf, true); - main.update(buf, len); - main.update(reinterpret_cast("\xFF\xFF"), 2); - } - } - squeezing = true; - } - main.squeeze(hash, hs); - } - - inline void transform(const unsigned char* data, uint64_t num_blks, size_t reallen) - { - (void)reallen; - - for (uint64_t blk = 0; blk < num_blks; blk++) - { - if (!chunk) - { - main.update(data, 8192); - main.update(reinterpret_cast("\x03\x00\x00\x00\x00\x00\x00\x00"), 8); - } - else - { - child.update(data, 8192); - unsigned char buf[B / 4]; - child.squeeze(buf, B / 4); - main.update(buf, B / 4); - } - - child.init(); - child.set_suffix(0x0b); - ++chunk; - data += 8192; - } - } - - - inline void clear() - { - main.clear(); - child.clear(); - zero_memory(m); - zero_memory(S); - S.clear(); - } - -private: - constexpr static size_t R = B == 128 ? 12 : 14; - shake_provider main; - shake_provider child; - std::array m; - std::string S; - size_t pos; - size_t total; - size_t chunk; - bool squeezing; -}; - -} // namespace detail - -} // namespace digestpp - -#endif // DIGESTPP_PROVIDERS_K12M14_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/kmac_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/kmac_provider.hpp deleted file mode 100644 index 896544b..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/kmac_provider.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_KMAC_HPP -#define DIGESTPP_PROVIDERS_KMAC_HPP - -#include "shake_provider.hpp" - -namespace digestpp -{ - -namespace detail -{ - -namespace kmac_functions -{ - template - inline std::string bytepad(const std::string& str) - { - const size_t pad = B == 128 ? 168 : 136; - unsigned char buf[32]; - size_t len = shake_functions::left_encode(pad, buf); - std::string res(reinterpret_cast(buf), len); - len = shake_functions::left_encode(str.length() * 8, buf); - res.append(reinterpret_cast(buf), len); - res.append(str); - size_t delta = pad - res.size() % pad; - if (delta && delta != pad) - res.append(delta, '\x00'); - return res; - } - -} // namespace kmac_functions - - -template -class kmac_provider -{ -public: - static const bool is_xof = XOF; - - template::type* = nullptr> - kmac_provider(size_t hashsize) : hs(hashsize) - { - static_assert(B == 128 || B == 256, "KMAC only supports 128 and 256 bits"); - validate_hash_size(hashsize, SIZE_MAX); - set_key(""); - } - - template::type* = nullptr> - kmac_provider() : hs(0) - { - static_assert(B == 128 || B == 256, "KMAC only supports 128 and 256 bits"); - set_key(""); - } - - ~kmac_provider() - { - clear(); - } - - inline void set_key(const std::string& key) - { - K = kmac_functions::bytepad(key); - } - - inline void set_customization(const std::string& customization) - { - shake.set_customization(customization); - } - - inline void init() - { - squeezing = false; - shake.set_function_name("KMAC"); - shake.init(); - update(reinterpret_cast(K.data()), K.length()); - } - - inline void update(const unsigned char* data, size_t len) - { - shake.update(data, len); - } - - inline void squeeze(unsigned char* hash, size_t hs) - { - if (!squeezing) - { - unsigned char buf[32]; - size_t len = shake_functions::right_encode(!XOF ? hs * 8 : 0, buf, false); - update(buf, len); - squeezing = true; - } - shake.squeeze(hash, hs); - } - - inline void final(unsigned char* hash) - { - squeeze(hash, hs / 8); - } - - inline void clear() - { - shake.clear(); - zero_memory(K); - set_key(""); - } - - inline size_t hash_size() const - { - return hs; - } - -private: - std::string K; - size_t hs; - bool squeezing; - shake_provider shake; -}; - -} // namespace detail - -} // namespace digestpp - -#endif // DIGESTPP_PROVIDERS_KMAC_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/kupyna_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/kupyna_provider.hpp deleted file mode 100644 index cec5eb0..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/kupyna_provider.hpp +++ /dev/null @@ -1,196 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_KUPYNA_HPP -#define DIGESTPP_PROVIDERS_KUPYNA_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/kupyna_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace kupyna_functions -{ - template - static inline void G(uint64_t* x, uint64_t* y) - { - for (int c = 0; c != R; ++c) - y[c] = kupyna_constants::T[0][static_cast(x[(c + R) % R])] - ^ kupyna_constants::T[1][static_cast(x[(c + R - 1) % R] >> 8)] - ^ kupyna_constants::T[2][static_cast(x[(c + R - 2) % R] >> 16)] - ^ kupyna_constants::T[3][static_cast(x[(c + R - 3) % R] >> 24)] - ^ kupyna_constants::T[4][static_cast(x[(c + R - 4) % R] >> 32)] - ^ kupyna_constants::T[5][static_cast(x[(c + R - 5) % R] >> 40)] - ^ kupyna_constants::T[6][static_cast(x[(c + R - 6) % R] >> 48)] - ^ kupyna_constants::T[7][static_cast(x[(c + R - (R == 16 ? 11 : 7)) % R] >> 56)]; - } - - template - static inline void roundP(uint64_t* x, uint64_t* y, uint64_t i) - { - for (int idx = 0; idx < R; idx++) - x[idx] ^= (static_cast(idx) << 4) ^ i; - - G(x, y); - } - - template - static inline void roundQ(uint64_t* x, uint64_t* y, uint64_t i) - { - for (int j = 0; j < R; ++j) - x[j] += (0x00F0F0F0F0F0F0F3ULL - ^ ((static_cast(((R - 1 - j) * 0x10) ^ static_cast(i))) << 56)); - - G(x, y); - } - - template - static inline void transform(uint64_t* h, const uint64_t* m) - { - uint64_t AQ1[R], AQ2[R], AP1[R], AP2[R]; - - for (int column = 0; column < R; column++) - { - AP1[column] = h[column] ^ m[column]; - AQ1[column] = m[column]; - } - - for (uint64_t r = 0; r < (R == 16 ? 14 : 10); r += 2) - { - roundP(AP1, AP2, r); - roundP(AP2, AP1, r + 1); - roundQ(AQ1, AQ2, r); - roundQ(AQ2, AQ1, r + 1); - } - - for (int column = 0; column < R; column++) - { - h[column] = AP1[column] ^ AQ1[column] ^ h[column]; - } - } - - template - static inline void outputTransform(uint64_t* h) - { - uint64_t t1[R]; - uint64_t t2[R]; - - for (int column = 0; column < R; column++) { - t1[column] = h[column]; - } - - for (uint64_t r = 0; r < (R == 16 ? 14 : 10); r += 2) { - roundP(t1, t2, r); - roundP(t2, t1, r+1); - } - - for (int column = 0; column < R; column++) { - h[column] ^= t1[column]; - } - } - -} - -class kupyna_provider -{ -public: - static const bool is_xof = false; - - kupyna_provider(size_t hashsize) - : hs(hashsize) - { - validate_hash_size(hashsize, { 256, 512 }); - } - - ~kupyna_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - memset(&h[0], 0, sizeof(uint64_t)*16); - h[0] = block_bytes(); // state in bytes - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, block_bytes(), block_bytes(), m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - m[pos++] = 0x80; - size_t limit = block_bytes(); - if (pos > limit - 12) - { - if (limit != pos) - memset(&m[pos], 0, limit - pos); - transform(m.data(), 1); - pos = 0; - } - memset(&m[pos], 0, limit - pos); - memcpy(&m[limit - 12], &total, sizeof(uint64_t)); - memset(&m[limit - 4], 0, 4); - - transform(m.data(), 1); - outputTransform(); - - memcpy(hash, reinterpret_cast(h.data()) + limit - hash_size() / 8, hash_size() / 8); - } - - inline void clear() - { - zero_memory(h); - zero_memory(m); - } - - inline size_t hash_size() const { return hs; } - -private: - inline size_t block_bytes() const { return hs > 256 ? 128 : 64; } - - inline void outputTransform() - { - if (hs > 256) - kupyna_functions::outputTransform<16>(&h[0]); - else - kupyna_functions::outputTransform<8>(&h[0]); - } - - inline void transform(const unsigned char* mp, size_t num_blks) - { - for (size_t blk = 0; blk < num_blks; blk++) - { - if (hs > 256) - kupyna_functions::transform<16>(&h[0], reinterpret_cast(mp + block_bytes() * blk)); - else - kupyna_functions::transform<8>(&h[0], reinterpret_cast(mp + block_bytes() * blk)); - } - } - - std::array h; - std::array m; - size_t hs; - size_t pos; - uint64_t total; - -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/md5_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/md5_provider.hpp deleted file mode 100644 index d429b0c..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/md5_provider.hpp +++ /dev/null @@ -1,198 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_MD5_HPP -#define DIGESTPP_PROVIDERS_MD5_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "constants/md5_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace md5_functions -{ - static inline void roundf(int round, uint32_t& a, uint32_t& b, uint32_t& c, uint32_t& d, const uint32_t* M) - { - a = b + rotate_left(a + (d ^ (b & (c ^ d))) + md5_constants::K[round] + M[round], - md5_constants::S[round]); - } - - static inline void roundg(int round, uint32_t& a, uint32_t& b, uint32_t& c, uint32_t& d, const uint32_t* M) - { - a = b + rotate_left(a + (c ^ (d & (b ^ c))) + md5_constants::K[round] + M[(5 * round + 1) % 16], - md5_constants::S[round]); - } - - static inline void roundh(int round, uint32_t& a, uint32_t& b, uint32_t& c, uint32_t& d, const uint32_t* M) - { - a = b + rotate_left(a + (b ^ c ^ d) + md5_constants::K[round] + M[(3 * round + 5) % 16], - md5_constants::S[round]); - } - - static inline void roundi(int round, uint32_t& a, uint32_t& b, uint32_t& c, uint32_t& d, const uint32_t* M) - { - a = b + rotate_left(a + (c ^ (b | ~d)) + md5_constants::K[round] + M[(7 * round) % 16], - md5_constants::S[round]); - } - -} - -class md5_provider -{ -public: - static const bool is_xof = false; - - md5_provider() - { - } - - ~md5_provider() - { - clear(); - } - - inline void init() - { - H[0] = 0x67452301; - H[1] = 0xefcdab89; - H[2] = 0x98badcfe; - H[3] = 0x10325476; - pos = 0; - total = 0; - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, 64, 64, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - m[pos++] = 0x80; - if (pos > 56) - { - if (pos != 64) - memset(&m[pos], 0, 64 - pos); - transform(&m[0], 1); - pos = 0; - } - memset(&m[0] + pos, 0, 56 - pos); - memcpy(&m[0] + (64 - 8), &total, 64 / 8); - transform(&m[0], 1); - memcpy(hash, H.data(), 16); - } - - inline void clear() - { - zero_memory(H); - zero_memory(m); - } - - inline size_t hash_size() const { return 128; } - -private: - inline void transform(const unsigned char* data, size_t num_blks) - { - const uint32_t* M = reinterpret_cast(data); - for (uint64_t blk = 0; blk < num_blks; blk++, M += 16) - { - uint32_t a = H[0]; - uint32_t b = H[1]; - uint32_t c = H[2]; - uint32_t d = H[3]; - - md5_functions::roundf(0, a, b, c, d, M); - md5_functions::roundf(1, d, a, b, c, M); - md5_functions::roundf(2, c, d, a, b, M); - md5_functions::roundf(3, b, c, d, a, M); - md5_functions::roundf(4, a, b, c, d, M); - md5_functions::roundf(5, d, a, b, c, M); - md5_functions::roundf(6, c, d, a, b, M); - md5_functions::roundf(7, b, c, d, a, M); - md5_functions::roundf(8, a, b, c, d, M); - md5_functions::roundf(9, d, a, b, c, M); - md5_functions::roundf(10, c, d, a, b, M); - md5_functions::roundf(11, b, c, d, a, M); - md5_functions::roundf(12, a, b, c, d, M); - md5_functions::roundf(13, d, a, b, c, M); - md5_functions::roundf(14, c, d, a, b, M); - md5_functions::roundf(15, b, c, d, a, M); - - md5_functions::roundg(16, a, b, c, d, M); - md5_functions::roundg(17, d, a, b, c, M); - md5_functions::roundg(18, c, d, a, b, M); - md5_functions::roundg(19, b, c, d, a, M); - md5_functions::roundg(20, a, b, c, d, M); - md5_functions::roundg(21, d, a, b, c, M); - md5_functions::roundg(22, c, d, a, b, M); - md5_functions::roundg(23, b, c, d, a, M); - md5_functions::roundg(24, a, b, c, d, M); - md5_functions::roundg(25, d, a, b, c, M); - md5_functions::roundg(26, c, d, a, b, M); - md5_functions::roundg(27, b, c, d, a, M); - md5_functions::roundg(28, a, b, c, d, M); - md5_functions::roundg(29, d, a, b, c, M); - md5_functions::roundg(30, c, d, a, b, M); - md5_functions::roundg(31, b, c, d, a, M); - - md5_functions::roundh(32, a, b, c, d, M); - md5_functions::roundh(33, d, a, b, c, M); - md5_functions::roundh(34, c, d, a, b, M); - md5_functions::roundh(35, b, c, d, a, M); - md5_functions::roundh(36, a, b, c, d, M); - md5_functions::roundh(37, d, a, b, c, M); - md5_functions::roundh(38, c, d, a, b, M); - md5_functions::roundh(39, b, c, d, a, M); - md5_functions::roundh(40, a, b, c, d, M); - md5_functions::roundh(41, d, a, b, c, M); - md5_functions::roundh(42, c, d, a, b, M); - md5_functions::roundh(43, b, c, d, a, M); - md5_functions::roundh(44, a, b, c, d, M); - md5_functions::roundh(45, d, a, b, c, M); - md5_functions::roundh(46, c, d, a, b, M); - md5_functions::roundh(47, b, c, d, a, M); - - md5_functions::roundi(48, a, b, c, d, M); - md5_functions::roundi(49, d, a, b, c, M); - md5_functions::roundi(50, c, d, a, b, M); - md5_functions::roundi(51, b, c, d, a, M); - md5_functions::roundi(52, a, b, c, d, M); - md5_functions::roundi(53, d, a, b, c, M); - md5_functions::roundi(54, c, d, a, b, M); - md5_functions::roundi(55, b, c, d, a, M); - md5_functions::roundi(56, a, b, c, d, M); - md5_functions::roundi(57, d, a, b, c, M); - md5_functions::roundi(58, c, d, a, b, M); - md5_functions::roundi(59, b, c, d, a, M); - md5_functions::roundi(60, a, b, c, d, M); - md5_functions::roundi(61, d, a, b, c, M); - md5_functions::roundi(62, c, d, a, b, M); - md5_functions::roundi(63, b, c, d, a, M); - - H[0] += a; - H[1] += b; - H[2] += c; - H[3] += d; - } - } - - std::array H; - std::array m; - size_t pos; - uint64_t total; -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/sha1_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/sha1_provider.hpp deleted file mode 100644 index a5bb248..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/sha1_provider.hpp +++ /dev/null @@ -1,162 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SHA1_HPP -#define DIGESTPP_PROVIDERS_SHA1_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "constants/sha1_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace sha1_functions -{ - static inline uint32_t Ch(uint32_t x, uint32_t y, uint32_t z) - { - return (x & y) ^ (~x & z); - } - - static inline uint32_t Parity(uint32_t x, uint32_t y, uint32_t z) - { - return x ^ y ^ z; - } - - static inline uint32_t Maj(uint32_t x, uint32_t y, uint32_t z) - { - return (x & y) ^ (x & z) ^ (y & z); - } -} - -class sha1_provider -{ -public: - static const bool is_xof = false; - - sha1_provider() - { - } - - ~sha1_provider() - { - clear(); - } - - inline void init() - { - H[0] = 0x67452301; - H[1] = 0xefcdab89; - H[2] = 0x98badcfe; - H[3] = 0x10325476; - H[4] = 0xc3d2e1f0; - pos = 0; - total = 0; - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, 64, 64, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - m[pos++] = 0x80; - if (pos > 56) { - if (pos != 64) - memset(&m[pos], 0, 64 - pos); - transform(&m[0], 1); - pos = 0; - } - memset(&m[0] + pos, 0, 56 - pos); - uint64_t mlen = byteswap(total); - memcpy(&m[0] + (64 - 8), &mlen, 64 / 8); - transform(&m[0], 1); - for (int i = 0; i < 5; i++) - H[i] = byteswap(H[i]); - memcpy(hash, H.data(), 160/8); - } - - inline void clear() - { - zero_memory(H); - zero_memory(m); - } - - inline size_t hash_size() const { return 160; } - -private: - inline void transform(const unsigned char* data, size_t num_blks) - { - for (uint64_t blk = 0; blk < num_blks; blk++) - { - uint32_t M[16]; - for (uint32_t i = 0; i < 64 / 4; i++) - M[i] = byteswap((reinterpret_cast(data)[blk * 16 + i])); - - uint32_t W[80]; - for (int t = 0; t <= 15; t++) - W[t] = M[t]; - for (int t = 16; t <= 79; t++) - W[t] = rotate_left(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); - - uint32_t a = H[0]; - uint32_t b = H[1]; - uint32_t c = H[2]; - uint32_t d = H[3]; - uint32_t e = H[4]; - - uint32_t K = sha1_constants::K[0]; - auto f = sha1_functions::Ch; - for (int t = 0; t <= 79; t++) - { - uint32_t T = rotate_left(a, 5) + f(b, c, d) + e + K + W[t]; - e = d; - d = c; - c = rotate_left(b, 30); - b = a; - a = T; - - if (t == 19) - { - f = sha1_functions::Parity; - K = sha1_constants::K[1]; - } - else if (t == 39) - { - f = sha1_functions::Maj; - K = sha1_constants::K[2]; - } - else if (t == 59) - { - f = sha1_functions::Parity; - K = sha1_constants::K[3]; - } - - } - H[0] += a; - H[1] += b; - H[2] += c; - H[3] += d; - H[4] += e; - } - } - - std::array H; - std::array m; - size_t pos; - uint64_t total; -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/sha2_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/sha2_provider.hpp deleted file mode 100644 index e47008a..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/sha2_provider.hpp +++ /dev/null @@ -1,318 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SHA2_HPP -#define DIGESTPP_PROVIDERS_SHA2_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/sha2_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace sha2_functions -{ - template - static inline T Ch(T x, T y, T z) - { - return (x & y) ^ (~x & z); - } - - template - static inline T Maj(T x, T y, T z) - { - return (x & y) ^ (x & z) ^ (y & z); - } - - static inline uint64_t sum0(uint64_t x) - { - return rotate_right(x, 28) ^ rotate_right(x, 34) ^ rotate_right(x, 39); - } - - static inline uint64_t sum1(uint64_t x) - { - return rotate_right(x, 14) ^ rotate_right(x, 18) ^ rotate_right(x, 41); - } - - static inline uint64_t sigma0(uint64_t x) - { - return rotate_right(x, 1) ^ rotate_right(x, 8) ^ (x >> 7); - } - - static inline uint64_t sigma1(uint64_t x) - { - return rotate_right(x, 19) ^ rotate_right(x, 61) ^ (x >> 6); - } - - static inline uint32_t sum0(uint32_t x) - { - return rotate_right(x, 2) ^ rotate_right(x, 13) ^ rotate_right(x, 22); - } - - static inline uint32_t sum1(uint32_t x) - { - return rotate_right(x, 6) ^ rotate_right(x, 11) ^ rotate_right(x, 25); - } - - static inline uint32_t sigma0(uint32_t x) - { - return rotate_right(x, 7) ^ rotate_right(x, 18) ^ (x >> 3); - } - - static inline uint32_t sigma1(uint32_t x) - { - return rotate_right(x, 17) ^ rotate_right(x, 19) ^ (x >> 10); - } -} - -// SHA-224, SHA-256, SHA-384, SHA-512/t algorithm -// SHA-512/t supports any output size up to 512 bits; in this case O must be 0 and output size provided to the constructor -template -class sha2_provider -{ -public: - static const bool is_xof = false; - - template::type* = nullptr> - sha2_provider() - : hs(O) - { - } - - template::type* = nullptr> - sha2_provider(size_t hashsize = N) - : hs(hashsize) - { - detail::validate_hash_size(hashsize, N); - } - - ~sha2_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - - // precalculated initial values for most common output sizes - switch(hs) - { - case 224: - H[0] = 0x8C3D37C819544DA2ull; - H[1] = 0x73E1996689DCD4D6ull; - H[2] = 0x1DFAB7AE32FF9C82ull; - H[3] = 0x679DD514582F9FCFull; - H[4] = 0x0F6D2B697BD44DA8ull; - H[5] = 0x77E36F7304C48942ull; - H[6] = 0x3F9D85A86A1D36C8ull; - H[7] = 0x1112E6AD91D692A1ull; - return; - case 256: - H[0] = 0x22312194FC2BF72Cull; - H[1] = 0x9F555FA3C84C64C2ull; - H[2] = 0x2393B86B6F53B151ull; - H[3] = 0x963877195940EABDull; - H[4] = 0x96283EE2A88EFFE3ull; - H[5] = 0xBE5E1E2553863992ull; - H[6] = 0x2B0199FC2C85B8AAull; - H[7] = 0x0EB72DDC81C52CA2ull; - return; - case 384: - H[0] = 0xcbbb9d5dc1059ed8ull; - H[1] = 0x629a292a367cd507ull; - H[2] = 0x9159015a3070dd17ull; - H[3] = 0x152fecd8f70e5939ull; - H[4] = 0x67332667ffc00b31ull; - H[5] = 0x8eb44a8768581511ull; - H[6] = 0xdb0c2e0d64f98fa7ull; - H[7] = 0x47b5481dbefa4fa4ull; - return; - default: - H[0] = 0x6a09e667f3bcc908ull; - H[1] = 0xbb67ae8584caa73bull; - H[2] = 0x3c6ef372fe94f82bull; - H[3] = 0xa54ff53a5f1d36f1ull; - H[4] = 0x510e527fade682d1ull; - H[5] = 0x9b05688c2b3e6c1full; - H[6] = 0x1f83d9abfb41bd6bull; - H[7] = 0x5be0cd19137e2179ull; - } - if (hs == 512) - return; - - // calculate initial values for SHA-512/t with a different output size - for (int i = 0; i < 8; i++) - H[i] ^= 0xa5a5a5a5a5a5a5a5ull; - std::string tmp = "SHA-512/" + std::to_string(hs); - - update(reinterpret_cast(&tmp[0]), tmp.length()); - unsigned char buf[512 / 8]; - final(buf); - for (int i = 0; i < 8; i++) - H[i] = byteswap(H[i]); - pos = 0; - total = 0; - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, N / 4, N / 4, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - m[pos++] = 0x80; - if (pos > N / 4 - sizeof(T) * 2) { - if (pos != N / 4) - memset(&m[pos], 0, N / 4 - pos); - transform(m.data(), 1); - pos = 0; - } - memset(&m[pos], 0, N / 4 - pos); - uint64_t mlen = byteswap(total); - memcpy(&m[N / 4 - 8], &mlen, 64 / 8); - transform(m.data(), 1); - for (int i = 0; i < 8; i++) - H[i] = byteswap(H[i]); - memcpy(hash, &H[0], hs/8); - } - - inline void clear() - { - zero_memory(H); - zero_memory(m); - } - - inline size_t hash_size() const { return hs; } - - inline T getK(int t) const; - -private: - inline void transform(const unsigned char* data, size_t num_blks) - { - for (size_t blk = 0; blk < num_blks; blk++) - { - T M[16]; - for (int i = 0; i < 16; i++) - M[i] = byteswap(reinterpret_cast(data)[blk * 16 + i]); - - const int rounds = N == 512 ? 80 : 64; - T W[rounds]; - for (int t = 0; t <= 15; t++) - W[t] = M[t]; - for (int t = 16; t < rounds; t++) - W[t] = sha2_functions::sigma1(W[t - 2]) + W[t - 7] + sha2_functions::sigma0(W[t - 15]) + W[t - 16]; - - T a = H[0]; - T b = H[1]; - T c = H[2]; - T d = H[3]; - T e = H[4]; - T f = H[5]; - T g = H[6]; - T h = H[7]; - - for (int t = 0; t < rounds; t++) - { - T T1 = h + sha2_functions::sum1(e) + sha2_functions::Ch(e, f, g) + getK(t) + W[t]; - T T2 = sha2_functions::sum0(a) + sha2_functions::Maj(a, b, c); - h = g; - g = f; - f = e; - e = d + T1; - d = c; - c = b; - b = a; - a = T1 + T2; - - } - H[0] += a; - H[1] += b; - H[2] += c; - H[3] += d; - H[4] += e; - H[5] += f; - H[6] += g; - H[7] += h; - } - - } - - constexpr static size_t N = sizeof(T) == 8 ? 512 : 256; - std::array H; - std::array m; - size_t pos; - uint64_t total; - size_t hs; -}; - -template<> -inline uint32_t sha2_provider::getK(int t) const -{ - return sha256_constants::K[t]; -} - -template<> -inline uint32_t sha2_provider::getK(int t) const -{ - return sha256_constants::K[t]; -} - -template<> -inline uint64_t sha2_provider::getK(int t) const -{ - return sha512_constants::K[t]; -} - -template<> -inline uint64_t sha2_provider::getK(int t) const -{ - return sha512_constants::K[t]; -} - -template<> -inline void sha2_provider::init() -{ - pos = 0; - total = 0; - H[0] = 0xc1059ed8; - H[1] = 0x367cd507; - H[2] = 0x3070dd17; - H[3] = 0xf70e5939; - H[4] = 0xffc00b31; - H[5] = 0x68581511; - H[6] = 0x64f98fa7; - H[7] = 0xbefa4fa4; -} - -template<> -inline void sha2_provider::init() -{ - pos = 0; - total = 0; - H[0] = 0x6a09e667; - H[1] = 0xbb67ae85; - H[2] = 0x3c6ef372; - H[3] = 0xa54ff53a; - H[4] = 0x510e527f; - H[5] = 0x9b05688c; - H[6] = 0x1f83d9ab; - H[7] = 0x5be0cd19; -} - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/sha3_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/sha3_provider.hpp deleted file mode 100644 index b09126b..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/sha3_provider.hpp +++ /dev/null @@ -1,186 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SHA3_HPP -#define DIGESTPP_PROVIDERS_SHA3_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/sha3_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace sha3_functions -{ - template - static inline void transform(uint64_t* A) - { - for (int round = 24 - R; round < 24; round++) - { - uint64_t C[5], D[5]; - C[0] = A[0 * 5 + 0] ^ A[1 * 5 + 0] ^ A[2 * 5 + 0] ^ A[3 * 5 + 0] ^ A[4 * 5 + 0]; - C[1] = A[0 * 5 + 1] ^ A[1 * 5 + 1] ^ A[2 * 5 + 1] ^ A[3 * 5 + 1] ^ A[4 * 5 + 1]; - C[2] = A[0 * 5 + 2] ^ A[1 * 5 + 2] ^ A[2 * 5 + 2] ^ A[3 * 5 + 2] ^ A[4 * 5 + 2]; - C[3] = A[0 * 5 + 3] ^ A[1 * 5 + 3] ^ A[2 * 5 + 3] ^ A[3 * 5 + 3] ^ A[4 * 5 + 3]; - C[4] = A[0 * 5 + 4] ^ A[1 * 5 + 4] ^ A[2 * 5 + 4] ^ A[3 * 5 + 4] ^ A[4 * 5 + 4]; - - D[0] = C[4] ^ rotate_left(C[1], 1); - D[1] = C[0] ^ rotate_left(C[2], 1); - D[2] = C[1] ^ rotate_left(C[3], 1); - D[3] = C[2] ^ rotate_left(C[4], 1); - D[4] = C[3] ^ rotate_left(C[0], 1); - - uint64_t B00 = A[0 * 5 + 0] ^ D[0]; - uint64_t B10 = rotate_left(A[0 * 5 + 1] ^ D[1], 1); - uint64_t B20 = rotate_left(A[0 * 5 + 2] ^ D[2], 62); - uint64_t B5 = rotate_left(A[0 * 5 + 3] ^ D[3], 28); - uint64_t B15 = rotate_left(A[0 * 5 + 4] ^ D[4], 27); - - uint64_t B16 = rotate_left(A[1 * 5 + 0] ^ D[0], 36); - uint64_t B1 = rotate_left(A[1 * 5 + 1] ^ D[1], 44); - uint64_t B11 = rotate_left(A[1 * 5 + 2] ^ D[2], 6); - uint64_t B21 = rotate_left(A[1 * 5 + 3] ^ D[3], 55); - uint64_t B6 = rotate_left(A[1 * 5 + 4] ^ D[4], 20); - - uint64_t B7 = rotate_left(A[2 * 5 + 0] ^ D[0], 3); - uint64_t B17 = rotate_left(A[2 * 5 + 1] ^ D[1], 10); - uint64_t B2 = rotate_left(A[2 * 5 + 2] ^ D[2], 43); - uint64_t B12 = rotate_left(A[2 * 5 + 3] ^ D[3], 25); - uint64_t B22 = rotate_left(A[2 * 5 + 4] ^ D[4], 39); - - uint64_t B23 = rotate_left(A[3 * 5 + 0] ^ D[0], 41); - uint64_t B8 = rotate_left(A[3 * 5 + 1] ^ D[1], 45); - uint64_t B18 = rotate_left(A[3 * 5 + 2] ^ D[2], 15); - uint64_t B3 = rotate_left(A[3 * 5 + 3] ^ D[3], 21); - uint64_t B13 = rotate_left(A[3 * 5 + 4] ^ D[4], 8); - - uint64_t B14 = rotate_left(A[4 * 5 + 0] ^ D[0], 18); - uint64_t B24 = rotate_left(A[4 * 5 + 1] ^ D[1], 2); - uint64_t B9 = rotate_left(A[4 * 5 + 2] ^ D[2], 61); - uint64_t B19 = rotate_left(A[4 * 5 + 3] ^ D[3], 56); - uint64_t B4 = rotate_left(A[4 * 5 + 4] ^ D[4], 14); - - A[0 * 5 + 0] = B00 ^ ((~B1) & B2); - A[0 * 5 + 1] = B1 ^ ((~B2) & B3); - A[0 * 5 + 2] = B2 ^ ((~B3) & B4); - A[0 * 5 + 3] = B3 ^ ((~B4) & B00); - A[0 * 5 + 4] = B4 ^ ((~B00) & B1); - - A[1 * 5 + 0] = B5 ^ ((~B6) & B7); - A[1 * 5 + 1] = B6 ^ ((~B7) & B8); - A[1 * 5 + 2] = B7 ^ ((~B8) & B9); - A[1 * 5 + 3] = B8 ^ ((~B9) & B5); - A[1 * 5 + 4] = B9 ^ ((~B5) & B6); - - A[2 * 5 + 0] = B10 ^ ((~B11) & B12); - A[2 * 5 + 1] = B11 ^ ((~B12) & B13); - A[2 * 5 + 2] = B12 ^ ((~B13) & B14); - A[2 * 5 + 3] = B13 ^ ((~B14) & B10); - A[2 * 5 + 4] = B14 ^ ((~B10) & B11); - - A[3 * 5 + 0] = B15 ^ ((~B16) & B17); - A[3 * 5 + 1] = B16 ^ ((~B17) & B18); - A[3 * 5 + 2] = B17 ^ ((~B18) & B19); - A[3 * 5 + 3] = B18 ^ ((~B19) & B15); - A[3 * 5 + 4] = B19 ^ ((~B15) & B16); - - A[4 * 5 + 0] = B20 ^ ((~B21) & B22); - A[4 * 5 + 1] = B21 ^ ((~B22) & B23); - A[4 * 5 + 2] = B22 ^ ((~B23) & B24); - A[4 * 5 + 3] = B23 ^ ((~B24) & B20); - A[4 * 5 + 4] = B24 ^ ((~B20) & B21); - - A[0] ^= sha3_constants::RC[round]; - } - } - - template - static inline void transform(const unsigned char* data, uint64_t num_blks, uint64_t* A, size_t rate) - { - size_t r = rate / 8; - size_t r64 = rate / 64; - for (uint64_t blk = 0; blk < num_blks; blk++) - { - for (size_t i = 0; i < r64; i++) - A[i] ^= reinterpret_cast(data+blk*r)[i]; - - transform(A); - } - } - -} // namespace sha3_functions - - -class sha3_provider -{ -public: - static const bool is_xof = false; - - sha3_provider(size_t hashsize) - : hs(hashsize) - { - validate_hash_size(hashsize, {224, 256, 384, 512}); - rate = 1600U - hs * 2; - } - - ~sha3_provider() - { - clear(); - } - - inline void init() - { - zero_memory(A); - pos = 0; - total = 0; - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, rate / 8, rate / 8, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { sha3_functions::transform<24>(data, len, A.data(), rate); }); - } - - inline void final(unsigned char* hash) - { - size_t r = rate / 8; - m[pos++] = 0x06; - if (r != pos) - memset(&m[pos], 0, r - pos); - m[r - 1] |= 0x80; - sha3_functions::transform<24>(m.data(), 1, A.data(), rate); - memcpy(hash, A.data(), hash_size() / 8); - } - - inline size_t hash_size() const - { - return hs; - } - - inline void clear() - { - zero_memory(A); - zero_memory(m); - } - -private: - std::array A; - std::array m; - size_t pos; - size_t hs; - size_t rate; - uint64_t total; -}; - -} // namespace detail - -} // namespace digestpp - -#endif // DIGESTPP_PROVIDERS_SHA3_HPP diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/shake_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/shake_provider.hpp deleted file mode 100644 index 6e97b65..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/shake_provider.hpp +++ /dev/null @@ -1,180 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SHAKE_HPP -#define DIGESTPP_PROVIDERS_SHAKE_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "sha3_provider.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace shake_functions -{ - static inline size_t left_encode(size_t num, unsigned char* buf) - { - // first, calculate length - unsigned char n = 1; - size_t tmp = num; - while (tmp >>= 8) - ++n; - buf[0] = n; - size_t result = n + 1; - size_t i = 0; - while (n) - buf[n--] = static_cast(num >> (8*i++)); - return result; - } - - static inline size_t right_encode(size_t num, unsigned char* buf, bool k12) - { - // first, calculate length - unsigned char n = k12 ? num ? 1 : 0 : 1; - size_t tmp = num; - while (tmp >>= 8) - ++n; - buf[n] = n; - size_t result = n + 1; - size_t i = 0; - while (n--) - buf[n] = static_cast(num >> (8*i++)); - return result; - } - -} // namespace shake_functions - - -template -class shake_provider -{ -public: - static const bool is_xof = true; - - shake_provider() - { - static_assert(B == 128 || B == 256, "SHAKE only supports 128 and 256 bits"); - } - - ~shake_provider() - { - clear(); - } - - inline void set_function_name(const std::string& function_name) - { - N = function_name; - } - - inline void set_customization(const std::string& customization) - { - S = customization; - } - - inline void init() - { - zero_memory(A); - pos = 0; - total = 0; - squeezing = false; - suffix = 0; - - if (!N.empty() || !S.empty()) - { - unsigned char buf[1024]; - size_t r = rate / 8; - size_t len = shake_functions::left_encode(r, buf); - size_t total = len; - update(buf, len); - len = shake_functions::left_encode(N.length() * 8, buf); - total += len; - update(buf, len); - if (!N.empty()) - update(reinterpret_cast(N.data()), N.length()); - len = shake_functions::left_encode(S.length() * 8, buf); - update(buf, len); - total += len; - if (!S.empty()) - update(reinterpret_cast(S.data()), S.length()); - total += S.length() + N.length(); - - len = r - (total % r); - memset(buf, 0, len); - update(buf, len); - } - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, rate / 8, rate / 8, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { sha3_functions::transform(data, len, A.data(), rate); }); - } - - inline void set_suffix(unsigned char s) - { - suffix = s; - } - - inline void squeeze(unsigned char* hash, size_t hs) - { - size_t r = rate / 8; - size_t processed = 0; - if (!squeezing) - { - m[pos++] = suffix ? suffix : N.empty() && S.empty() ? 0x1F : 0x04; - if (r != pos) - memset(&m[pos], 0, r - pos); - m[r - 1] |= 0x80; - sha3_functions::transform(m.data(), 1, A.data(), rate); - squeezing = true; - } - else if (pos < r) - { - size_t to_copy = std::min(hs, r - pos); - memcpy(hash, reinterpret_cast(A.data()) + pos, to_copy); - processed += to_copy; - pos += to_copy; - } - while (processed < hs) - { - if (processed) - sha3_functions::transform(A.data()); - pos = std::min(hs - processed, r); - memcpy(hash + processed, A.data(), pos); - processed += pos; - } - } - - inline void clear() - { - zero_memory(A); - zero_memory(m); - zero_memory(N); - zero_memory(S); - N.clear(); - S.clear(); - } - -private: - std::array A; - std::array m; - std::string N; - std::string S; - const size_t rate = B == 128 ? 1344 : 1088; - size_t pos; - size_t total; - bool squeezing; - unsigned char suffix; -}; - -} // namespace detail - -} // namespace digestpp - -#endif // DIGESTPP_PROVIDERS_SHAKE_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/skein_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/skein_provider.hpp deleted file mode 100644 index 7b03cc3..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/skein_provider.hpp +++ /dev/null @@ -1,387 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SKEIN_HPP -#define DIGESTPP_PROVIDERS_SKEIN_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/skein_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -template -struct skein_functions -{ -}; - -template<> -struct skein_functions<4> -{ - template static inline void GTv4(uint64_t* G) - { - G[skein_constants::I4[r][0]] += G[skein_constants::I4[r][1]]; - G[skein_constants::I4[r][1]] = rotate_left(G[skein_constants::I4[r][1]], - skein_constants::C4[r][0]) ^ G[skein_constants::I4[r][0]]; - G[skein_constants::I4[r][2]] += G[skein_constants::I4[r][3]]; - G[skein_constants::I4[r][3]] = rotate_left(G[skein_constants::I4[r][3]], - skein_constants::C4[r][1]) ^ G[skein_constants::I4[r][2]]; - } - - template - static inline void KStRv4(uint64_t* G, uint64_t* keys, uint64_t* tweaks) - { - G[0] += keys[(r + 0 + 1) % 5]; - G[1] += keys[(r + 1 + 1) % 5] + tweaks[(r + 1) % 3]; - G[2] += keys[(r + 2 + 1) % 5] + tweaks[(r + 2) % 3]; - G[3] += keys[(r + 3 + 1) % 5] + r + 1; - } - - template - static inline void G8(uint64_t* G, uint64_t* keys, uint64_t* tweaks) - { - GTv4<0>(G); - GTv4<1>(G); - GTv4<2>(G); - GTv4<3>(G); - KStRv4(G, keys, tweaks); - GTv4<4>(G); - GTv4<5>(G); - GTv4<6>(G); - GTv4<7>(G); - KStRv4(G, keys, tweaks); - } -}; - -template<> -struct skein_functions<8> -{ - template static inline void GTv4(uint64_t* G) - { - G[skein_constants::I8[r][0]] += G[skein_constants::I8[r][1]]; - G[skein_constants::I8[r][1]] = rotate_left(G[skein_constants::I8[r][1]], - skein_constants::C8[r][0]) ^ G[skein_constants::I8[r][0]]; - G[skein_constants::I8[r][2]] += G[skein_constants::I8[r][3]]; - G[skein_constants::I8[r][3]] = rotate_left(G[skein_constants::I8[r][3]], - skein_constants::C8[r][1]) ^ G[skein_constants::I8[r][2]]; - G[skein_constants::I8[r][4]] += G[skein_constants::I8[r][5]]; - G[skein_constants::I8[r][5]] = rotate_left(G[skein_constants::I8[r][5]], - skein_constants::C8[r][2]) ^ G[skein_constants::I8[r][4]]; - G[skein_constants::I8[r][6]] += G[skein_constants::I8[r][7]]; - G[skein_constants::I8[r][7]] = rotate_left(G[skein_constants::I8[r][7]], - skein_constants::C8[r][3]) ^ G[skein_constants::I8[r][6]]; - } - - template - static inline void KStRv4(uint64_t* G, uint64_t* keys, uint64_t* tweaks) - { - G[0] += keys[(r + 0 + 1) % 9]; - G[1] += keys[(r + 1 + 1) % 9]; - G[2] += keys[(r + 2 + 1) % 9]; - G[3] += keys[(r + 3 + 1) % 9]; - G[4] += keys[(r + 4 + 1) % 9]; - G[5] += keys[(r + 5 + 1) % 9] + tweaks[(r + 1) % 3]; - G[6] += keys[(r + 6 + 1) % 9] + tweaks[(r + 2) % 3]; - G[7] += keys[(r + 7 + 1) % 9] + r + 1; - } - - template - static inline void G8(uint64_t* G, uint64_t* keys, uint64_t* tweaks) - { - GTv4<0>(G); - GTv4<1>(G); - GTv4<2>(G); - GTv4<3>(G); - KStRv4(G, keys, tweaks); - GTv4<4>(G); - GTv4<5>(G); - GTv4<6>(G); - GTv4<7>(G); - KStRv4(G, keys, tweaks); - } -}; - -template<> -struct skein_functions<16> -{ - - template static inline void GTv4(uint64_t* G) - { - G[skein_constants::I16[r][0]] += G[skein_constants::I16[r][1]]; - G[skein_constants::I16[r][1]] = rotate_left(G[skein_constants::I16[r][1]], - skein_constants::C16[r][0]) ^ G[skein_constants::I16[r][0]]; - G[skein_constants::I16[r][2]] += G[skein_constants::I16[r][3]]; - G[skein_constants::I16[r][3]] = rotate_left(G[skein_constants::I16[r][3]], - skein_constants::C16[r][1]) ^ G[skein_constants::I16[r][2]]; - G[skein_constants::I16[r][4]] += G[skein_constants::I16[r][5]]; - G[skein_constants::I16[r][5]] = rotate_left(G[skein_constants::I16[r][5]], - skein_constants::C16[r][2]) ^ G[skein_constants::I16[r][4]]; - G[skein_constants::I16[r][6]] += G[skein_constants::I16[r][7]]; - G[skein_constants::I16[r][7]] = rotate_left(G[skein_constants::I16[r][7]], - skein_constants::C16[r][3]) ^ G[skein_constants::I16[r][6]]; - G[skein_constants::I16[r][8]] += G[skein_constants::I16[r][9]]; - G[skein_constants::I16[r][9]] = rotate_left(G[skein_constants::I16[r][9]], - skein_constants::C16[r][4]) ^ G[skein_constants::I16[r][8]]; - G[skein_constants::I16[r][10]] += G[skein_constants::I16[r][11]]; - G[skein_constants::I16[r][11]] = rotate_left(G[skein_constants::I16[r][11]], - skein_constants::C16[r][5]) ^ G[skein_constants::I16[r][10]]; - G[skein_constants::I16[r][12]] += G[skein_constants::I16[r][13]]; - G[skein_constants::I16[r][13]] = rotate_left(G[skein_constants::I16[r][13]], - skein_constants::C16[r][6]) ^ G[skein_constants::I16[r][12]]; - G[skein_constants::I16[r][14]] += G[skein_constants::I16[r][15]]; - G[skein_constants::I16[r][15]] = rotate_left(G[skein_constants::I16[r][15]], - skein_constants::C16[r][7]) ^ G[skein_constants::I16[r][14]]; - } - - template - static inline void KStRv4(uint64_t* G, uint64_t* keys, uint64_t* tweaks) - { - G[0] += keys[(r + 0 + 1) % 17]; - G[1] += keys[(r + 1 + 1) % 17]; - G[2] += keys[(r + 2 + 1) % 17]; - G[3] += keys[(r + 3 + 1) % 17]; - G[4] += keys[(r + 4 + 1) % 17]; - G[5] += keys[(r + 5 + 1) % 17]; - G[6] += keys[(r + 6 + 1) % 17]; - G[7] += keys[(r + 7 + 1) % 17]; - G[8] += keys[(r + 8 + 1) % 17]; - G[9] += keys[(r + 9 + 1) % 17]; - G[10] += keys[(r + 10 + 1) % 17]; - G[11] += keys[(r + 11 + 1) % 17]; - G[12] += keys[(r + 12 + 1) % 17]; - G[13] += keys[(r + 13 + 1) % 17] + tweaks[(r + 1) % 3]; - G[14] += keys[(r + 14 + 1) % 17] + tweaks[(r + 2) % 3]; - G[15] += keys[(r + 15 + 1) % 17] + r + 1; - } - - template - static inline void G8(uint64_t* G, uint64_t* keys, uint64_t* tweaks) - { - GTv4<0>(G); - GTv4<1>(G); - GTv4<2>(G); - GTv4<3>(G); - KStRv4(G, keys, tweaks); - GTv4<4>(G); - GTv4<5>(G); - GTv4<6>(G); - GTv4<7>(G); - KStRv4(G, keys, tweaks); - } -}; - -template -class skein_provider -{ -public: - static const bool is_xof = XOF; - - skein_provider(size_t hashsize = N) - : hs(hashsize) - { - validate_hash_size(hashsize, SIZE_MAX); - } - - ~skein_provider() - { - clear(); - } - - inline void set_personalization(const std::string& personalization) - { - p = personalization; - } - - inline void set_nonce(const std::string& nonce) - { - n = nonce; - } - - inline void set_key(const std::string& key) - { - k = key; - } - - inline void init() - { - squeezing = false; - tweak[0] = 0ULL; - pos = 0; - total = 0; - zero_memory(H); - inject_parameter(k, 0ULL); - tweak[1] = (1ULL << 62) | (4ULL << 56) | (1ULL << 63); - zero_memory(m); - m[0] = 0x53; - m[1] = 0x48; - m[2] = 0x41; - m[3] = 0x33; - m[4] = 0x01; - uint64_t size64 = XOF ? static_cast(-1) : hs; - memcpy(&m[8], &size64, 8); - transform(m.data(), 1, 32); - pos = 0; - total = 0; - tweak[0] = 0ULL; - tweak[1] = (1ULL << 62) | (48ULL << 56); - inject_parameter(p, 8ULL); - inject_parameter(n, 20ULL); - - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, N / 8, N / 8 + 1, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len, N / 8); }); - } - - inline void squeeze(unsigned char* hash, size_t hs) - { - size_t processed = 0; - if (!squeezing) - { - squeezing = true; - tweak[1] |= 1ull << 63; // last block - if (pos < N / 8) - memset(&m[pos], 0, N / 8 - pos); - - transform(m.data(), 1, pos); - memset(&m[0], 0, N / 8); - memcpy(&hbk[0], H.data(), N / 8); - pos = 0; - total = 0; - } - else if (pos < N / 8) - { - size_t to_copy = std::min(hs, N / 8 - pos); - memcpy(hash, reinterpret_cast(H.data()) + pos, to_copy); - processed += to_copy; - pos += to_copy; - } - while (processed < hs) - { - pos = std::min(hs - processed, N / 8); - tweak[0] = 0; - tweak[1] = 255ULL << 56; - memcpy(&m[0], &total, 8); - memcpy(&H[0], hbk.data(), N / 8); - transform(m.data(), 1, 8); - memcpy(hash + processed, H.data(), pos); - processed += pos; - ++total; - } - } - - inline void final(unsigned char* hash) - { - return squeeze(hash, hs / 8); - } - - inline size_t hash_size() const - { - return hs; - } - - inline void clear() - { - zero_memory(H); - zero_memory(hbk); - zero_memory(m); - zero_memory(tweak); - zero_memory(p); - zero_memory(n); - zero_memory(k); - p.clear(); - n.clear(); - k.clear(); - } - -private: - inline void transform(const unsigned char* mp, uint64_t num_blks, size_t reallen) - { - uint64_t keys[N / 64 + 1]; - uint64_t tweaks[3]; - - for (uint64_t b = 0; b < num_blks; b++) - { - uint64_t M[N / 64]; - uint64_t G[N / 64]; - for (uint64_t i = 0; i < N / 64; i++) - { - M[i] = (reinterpret_cast(mp)[b * N / 64 + i]); - } - memcpy(keys, H.data(), sizeof(uint64_t) * N / 64); - memcpy(tweaks, tweak.data(), sizeof(uint64_t) * 2); - tweaks[0] += reallen; - tweaks[2] = tweaks[0] ^ tweaks[1]; - keys[N / 64] = 0x1BD11BDAA9FC1A22ULL; - for (int i = 0; i < N / 64; i++) - { - keys[N / 64] ^= keys[i]; - G[i] = M[i] + keys[i]; - } - G[N / 64 - 3] += tweaks[0]; - G[N / 64 - 2] += tweaks[1]; - - skein_functions::template G8<0>(G, keys, tweaks); - skein_functions::template G8<2>(G, keys, tweaks); - skein_functions::template G8<4>(G, keys, tweaks); - skein_functions::template G8<6>(G, keys, tweaks); - skein_functions::template G8<8>(G, keys, tweaks); - skein_functions::template G8<10>(G, keys, tweaks); - skein_functions::template G8<12>(G, keys, tweaks); - skein_functions::template G8<14>(G, keys, tweaks); - skein_functions::template G8<16>(G, keys, tweaks); - if (N == 1024) - skein_functions::template G8<18>(G, keys, tweaks); - - tweaks[1] &= ~(64ULL << 56); - tweak[0] = tweaks[0]; - tweak[1] = tweaks[1]; - - for (int i = 0; i < N / 64; i++) - H[i] = G[i] ^ M[i]; - } - } - - inline void inject_parameter(const std::string& p, uint64_t code) - { - if (p.empty()) - return; - - tweak[1] = (1ULL << 62) | (code << 56); - update(reinterpret_cast(p.data()), p.length()); - tweak[1] |= 1ull << 63; // last block - if (pos < N / 8) - memset(&m[pos], 0, N / 8 - pos); - transform(m.data(), 1, pos); - squeezing = false; - pos = 0; - total = 0; - tweak[0] = 0ULL; - tweak[1] = (1ULL << 62) | (48ULL << 56); - } - - std::array H, hbk; - std::array m; - size_t pos; - uint64_t total; - std::array tweak; - size_t hs; - bool squeezing; - std::string p, n, k; -}; - - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/sm3_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/sm3_provider.hpp deleted file mode 100644 index 9a2dcd0..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/sm3_provider.hpp +++ /dev/null @@ -1,188 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_SM3_HPP -#define DIGESTPP_PROVIDERS_SM3_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace sm3_functions -{ - static inline uint32_t xorf(uint32_t x, uint32_t y, uint32_t z) - { - return x ^ y ^ z; - } - - static inline uint32_t ff1(uint32_t x, uint32_t y, uint32_t z) - { - return (x & y) ^ (x & z) ^ (y & z); - } - - static inline uint32_t gg1(uint32_t x, uint32_t y, uint32_t z) - { - return (x & y) ^ (~x & z); - } - - static inline uint32_t p0(uint32_t x) - { - return x ^ rotate_left(x, 9) ^ rotate_left(x, 17); - } - - static inline uint32_t p1(uint32_t x) - { - return x ^ rotate_left(x, 15) ^ rotate_left(x, 23); - } -} - -class sm3_provider -{ -public: - static const bool is_xof = false; - - sm3_provider() - { - } - - ~sm3_provider() - { - clear(); - } - - inline void init() - { - H[0] = 0x7380166f; - H[1] = 0x4914b2b9; - H[2] = 0x172442d7; - H[3] = 0xda8a0600; - H[4] = 0xa96f30bc; - H[5] = 0x163138aa; - H[6] = 0xe38dee4d; - H[7] = 0xb0fb0e4e; - pos = 0; - total = 0; - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, 64, 64, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - m[pos++] = 0x80; - if (pos > 56) - { - if (pos != 64) - memset(&m[pos], 0, 64 - pos); - transform(m.data(), 1); - pos = 0; - } - memset(&m[pos], 0, 56 - pos); - uint64_t mlen = byteswap(total); - memcpy(&m[64 - 8], &mlen, 64 / 8); - transform(m.data(), 1); - for (int i = 0; i < 8; i++) - H[i] = byteswap(H[i]); - memcpy(hash, H.data(), 32); - } - - inline void clear() - { - zero_memory(H); - zero_memory(m); - } - - inline size_t hash_size() const { return 256; } - -private: - inline void transform(const unsigned char* data, size_t num_blks) - { - for (uint64_t blk = 0; blk < num_blks; blk++) - { - uint32_t M[16]; - for (uint32_t i = 0; i < 64 / 4; i++) - M[i] = byteswap(reinterpret_cast(data)[blk * 16 + i]); - - uint32_t W[68]; - uint32_t W2[64]; - for (int t = 0; t <= 15; t++) - W[t] = M[t]; - for (int t = 16; t <= 67; t++) - W[t] = sm3_functions::p1(W[t - 16] ^ W[t - 9] ^ rotate_left(W[t - 3], 15)) ^ rotate_left(W[t - 13], 7) ^ W[t - 6]; - for (int t = 0; t <= 63; t++) - W2[t] = W[t] ^ W[t + 4]; - - uint32_t a = H[0]; - uint32_t b = H[1]; - uint32_t c = H[2]; - uint32_t d = H[3]; - uint32_t e = H[4]; - uint32_t f = H[5]; - uint32_t g = H[6]; - uint32_t h = H[7]; - - for (int t = 0; t <= 15; t++) - { - uint32_t ss1 = rotate_left((rotate_left(a, 12) + e + rotate_left(0x79cc4519U, t)), 7); - uint32_t ss2 = ss1 ^ rotate_left(a, 12); - uint32_t tt1 = sm3_functions::xorf(a, b, c) + d + ss2 + W2[t]; - uint32_t tt2 = sm3_functions::xorf(e, f, g) + h + ss1 + W[t]; - d = c; - c = rotate_left(b, 9); - b = a; - a = tt1; - h = g; - g = rotate_left(f, 19); - f = e; - e = sm3_functions::p0(tt2); - } - - for (int t = 16; t <= 63; t++) - { - uint32_t ss1 = rotate_left((rotate_left(a, 12) + e + rotate_left(0x7a879d8aU, t)), 7); - uint32_t ss2 = ss1 ^ rotate_left(a, 12); - uint32_t tt1 = sm3_functions::ff1(a, b, c) + d + ss2 + W2[t]; - uint32_t tt2 = sm3_functions::gg1(e, f, g) + h + ss1 + W[t]; - d = c; - c = rotate_left(b, 9); - b = a; - a = tt1; - h = g; - g = rotate_left(f, 19); - f = e; - e = sm3_functions::p0(tt2); - } - - H[0] ^= a; - H[1] ^= b; - H[2] ^= c; - H[3] ^= d; - H[4] ^= e; - H[5] ^= f; - H[6] ^= g; - H[7] ^= h; - } - } - - std::array H; - std::array m; - size_t pos; - uint64_t total; -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/streebog_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/streebog_provider.hpp deleted file mode 100644 index 220ef0c..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/streebog_provider.hpp +++ /dev/null @@ -1,182 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_STREEBOG_HPP -#define DIGESTPP_PROVIDERS_STREEBOG_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "../../detail/validate_hash_size.hpp" -#include "constants/streebog_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace streebog_functions -{ - template - static inline uint64_t lps(unsigned char* ch) - { - return streebog_constants::T[0][(ch[I])] - ^ streebog_constants::T[1][(ch[8 + I])] - ^ streebog_constants::T[2][(ch[16 + I])] - ^ streebog_constants::T[3][(ch[24 + I])] - ^ streebog_constants::T[4][(ch[32 + I])] - ^ streebog_constants::T[5][(ch[40 + I])] - ^ streebog_constants::T[6][(ch[48 + I])] - ^ streebog_constants::T[7][(ch[56 + I])]; - } - - static inline void lps_block(uint64_t* block) - { - unsigned char ch[64]; - memcpy(ch, block, 64); - - block[0] = lps<0>(ch); - block[1] = lps<1>(ch); - block[2] = lps<2>(ch); - block[3] = lps<3>(ch); - block[4] = lps<4>(ch); - block[5] = lps<5>(ch); - block[6] = lps<6>(ch); - block[7] = lps<7>(ch); - } - - static inline void xor_blocks(uint64_t* block, const uint64_t* toxor) - { - block[0] ^= toxor[0]; - block[1] ^= toxor[1]; - block[2] ^= toxor[2]; - block[3] ^= toxor[3]; - block[4] ^= toxor[4]; - block[5] ^= toxor[5]; - block[6] ^= toxor[6]; - block[7] ^= toxor[7]; - } - - static inline void e(uint64_t* K, const unsigned char* m) - { - uint64_t tmp[8]; - memcpy(tmp, K, 64); - xor_blocks(K, reinterpret_cast(m)); - for (int i = 0; i < 12; i++) - { - lps_block(K); - xor_blocks(tmp, &streebog_constants::RC[i][0]); - lps_block(tmp); - xor_blocks(K, tmp); - } - } - - static inline void gN(uint64_t* h, const unsigned char* m, uint64_t N) - { - uint64_t hN[8]; - memcpy(hN, h, 64); - hN[0] ^= N; - lps_block(hN); - e(hN, m); - xor_blocks(h, hN); - xor_blocks(h, reinterpret_cast(m)); - } - - static inline void addm(const unsigned char* m, uint64_t* h) - { - const uint64_t* m64 = reinterpret_cast(m); - bool carry = false, overflow = false; - for (int i = 0; i < 8; i++) - { - uint64_t t = h[i] + m64[i]; - overflow = t < h[i] || t < m64[i]; - h[i] = t + carry; - carry = overflow; - } - } - -} - -class streebog_provider -{ -public: - static const bool is_xof = false; - - streebog_provider(size_t hashsize) - : hs(hashsize) - { - validate_hash_size(hashsize, { 256, 512 }); - } - - ~streebog_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - memset(&h[0], hs == 512 ? 0 : 1, sizeof(uint64_t) * 8); - memset(&S[0], 0, sizeof(uint64_t) * 8); - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, 64, 64, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len, false); }); - } - - inline void final(unsigned char* hash) - { - m[pos++] = 0x01; - if (pos != 64) - memset(&m[pos], 0, 64 - pos); - transform(&m[0], 1, false); - total += (pos - 1) * 8; - - memcpy(&m[0], &total, sizeof(total)); - memset(&m[sizeof(total)], 0, 64 - sizeof(total)); - transform(&m[0], 1, true); - transform(reinterpret_cast(&S[0]), 1, true); - - memcpy(hash, &h[8 - hash_size()/64], hash_size() / 8); - } - - inline void clear() - { - zero_memory(h); - zero_memory(S); - zero_memory(m); - } - - inline size_t hash_size() const { return hs; } - -private: - inline void transform(const unsigned char* mp, size_t num_blks, bool final) - { - for (size_t blk = 0; blk < num_blks; blk++) - { - streebog_functions::gN(&h[0], mp + blk * 64, final ? 0ULL : total + blk * 512); - - if (!final) - streebog_functions::addm(mp + blk * 64, &S[0]); - } - } - - std::array h; - std::array S; - std::array m; - size_t hs; - size_t pos; - uint64_t total; - -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/detail/whirlpool_provider.hpp b/VCMP-LUA/modules/crypto/include/algorithm/detail/whirlpool_provider.hpp deleted file mode 100644 index d97113a..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/detail/whirlpool_provider.hpp +++ /dev/null @@ -1,143 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_PROVIDERS_WHIRLPOOL_HPP -#define DIGESTPP_PROVIDERS_WHIRLPOOL_HPP - -#include "../../detail/functions.hpp" -#include "../../detail/absorb_data.hpp" -#include "constants/whirlpool_constants.hpp" -#include - -namespace digestpp -{ - -namespace detail -{ - -namespace whirlpool_functions -{ - template - static inline uint64_t G(const uint64_t* ll) - { - return whirlpool_constants::T[0][static_cast(ll[a % 8])] - ^ whirlpool_constants::T[1][static_cast(ll[(a - 1) % 8] >> 8)] - ^ whirlpool_constants::T[2][static_cast(ll[(a - 2) % 8] >> 16)] - ^ whirlpool_constants::T[3][static_cast(ll[(a - 3) % 8] >> 24)] - ^ whirlpool_constants::T[4][static_cast(ll[(a - 4) % 8] >> 32)] - ^ whirlpool_constants::T[5][static_cast(ll[(a - 5) % 8] >> 40)] - ^ whirlpool_constants::T[6][static_cast(ll[(a - 6) % 8] >> 48)] - ^ whirlpool_constants::T[7][static_cast(ll[(a - 7) % 8] >> 56)]; - } -} - -class whirlpool_provider -{ -public: - static const bool is_xof = false; - - whirlpool_provider() - { - } - - ~whirlpool_provider() - { - clear(); - } - - inline void init() - { - pos = 0; - total = 0; - memset(&h[0], 0, sizeof(uint64_t)*8); - } - - inline void update(const unsigned char* data, size_t len) - { - detail::absorb_bytes(data, len, 64, 64, m.data(), pos, total, - [this](const unsigned char* data, size_t len) { transform(data, len); }); - } - - inline void final(unsigned char* hash) - { - total += pos * 8; - uint64_t mlen = byteswap(total); - m[pos++] = 0x80; - if (pos > 32) - { - if (pos != 64) - memset(&m[pos], 0, 64 - pos); - transform(m.data(), 1); - pos = 0; - } - memset(&m[pos], 0, 56 - pos); - memcpy(&m[64 - 8], &mlen, 64 / 8); - transform(m.data(), 1); - memcpy(hash, h.data(), hash_size() / 8); - } - - inline void clear() - { - zero_memory(h); - zero_memory(m); - } - - inline size_t hash_size() const { return 512; } - -private: - inline void transform(const unsigned char* mp, size_t num_blks) - { - for (uint64_t b = 0; b < num_blks; b++) - { - uint64_t K[8], state[8]; - - memcpy(K, h.data(), sizeof(K)); - for (int i = 0; i < 8; ++i) - state[i] = h[i] ^ (reinterpret_cast(mp)[i]); - - for (int r = 0; r < 10; ++r) - { - uint64_t L[8]; - - L[0] = whirlpool_functions::G<0 + 8>(K) ^ whirlpool_constants::RC[r]; - L[1] = whirlpool_functions::G<1 + 8>(K); - L[2] = whirlpool_functions::G<2 + 8>(K); - L[3] = whirlpool_functions::G<3 + 8>(K); - L[4] = whirlpool_functions::G<4 + 8>(K); - L[5] = whirlpool_functions::G<5 + 8>(K); - L[6] = whirlpool_functions::G<6 + 8>(K); - L[7] = whirlpool_functions::G<7 + 8>(K); - - memcpy(K, L, sizeof(L)); - - L[0] ^= whirlpool_functions::G<0 + 8>(state); - L[1] ^= whirlpool_functions::G<1 + 8>(state); - L[2] ^= whirlpool_functions::G<2 + 8>(state); - L[3] ^= whirlpool_functions::G<3 + 8>(state); - L[4] ^= whirlpool_functions::G<4 + 8>(state); - L[5] ^= whirlpool_functions::G<5 + 8>(state); - L[6] ^= whirlpool_functions::G<6 + 8>(state); - L[7] ^= whirlpool_functions::G<7 + 8>(state); - - memcpy(state, L, sizeof(L)); - } - - for (int i = 0; i < 8; ++i) - h[i] ^= state[i] ^ reinterpret_cast(mp)[i]; - mp += 64; - } - } - - std::array h; - std::array m; - size_t pos; - uint64_t total; - -}; - -} // namespace detail - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/groestl.hpp b/VCMP-LUA/modules/crypto/include/algorithm/groestl.hpp deleted file mode 100644 index 508a733..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/groestl.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_GROESTL_HPP -#define DIGESTPP_ALGORITHM_GROESTL_HPP - -#include "../hasher.hpp" -#include "detail/groestl_provider.hpp" - -namespace digestpp -{ - -/** - * @brief Grøstl hash function - * - * @hash - * - * @outputsize 8 - 512 bits - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes), - * or is not within the supported range - * - * @par Example:\n - * @code // Output a 256-bit Grøstl digest of a string - * digestpp::groestl hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 8c7ad62eb26a21297bc39c2d7293b4bd4d3399fa8afab29e970471739e28b301 - * @endcode - * - * @sa hasher - */ -typedef hasher groestl; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_GROESTL_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/jh.hpp b/VCMP-LUA/modules/crypto/include/algorithm/jh.hpp deleted file mode 100644 index 98624e9..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/jh.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_JG_HPP -#define DIGESTPP_ALGORITHM_JG_HPP - -#include "../hasher.hpp" -#include "detail/jh_provider.hpp" - -namespace digestpp -{ - -/** - * @brief JH hash function - * - * @hash - * - * @outputsize 8 - 512 bits - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes), - * or is not within the supported range - * - * @par Example:\n - * @code // Output a 256-bit JH digest of a string - * digestpp::jh hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 6a049fed5fc6874acfdc4a08b568a4f8cbac27de933496f031015b38961608a0 - * @endcode - * - * @sa hasher - */ -typedef hasher jh; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_JG_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/k12m14.hpp b/VCMP-LUA/modules/crypto/include/algorithm/k12m14.hpp deleted file mode 100644 index df92869..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/k12m14.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_K12M14_HPP -#define DIGESTPP_ALGORITHM_K12M14_HPP - -#include "../hasher.hpp" -#include "detail/k12m14_provider.hpp" -#include "mixin/k12m14_mixin.hpp" - -namespace digestpp -{ - -/** - * @brief KangarooTwelve function - * - * Extendable output function similar to SHAKE128 but with reduced number of round. - * - * @xof - * - * @mixinparams customization - * - * @mixin{mixin::k12m14_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::k12 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code b4f249b4f77c58df170aa4d1723db1127d82f1d98d25ddda561ada459cd11a48 - * @endcode - * - * @sa hasher, mixin::k12m14_mixin - */ -typedef hasher, mixin::k12m14_mixin> k12; - -/** - * @brief MarsupilamiFourteen function - * - * Extendable output function similar to KangarooTwelve, but providing 256-bit security. - * - * @xof - * - * @mixinparams customization - * - * @mixin{mixin::k12m14_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::m14 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 3611bcaa666347770dbffd4562f137c5adfe2e09f3c4268ef7c7d7c0e6c5d59c - * @endcode - * - * @sa hasher, mixin::k12m14_mixin - */ -typedef hasher, mixin::k12m14_mixin> m14; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_K12M14_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/kmac.hpp b/VCMP-LUA/modules/crypto/include/algorithm/kmac.hpp deleted file mode 100644 index c6ac8d3..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/kmac.hpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_KMAC_HPP -#define DIGESTPP_ALGORITHM_KMAC_HPP - -#include "../hasher.hpp" -#include "detail/kmac_provider.hpp" -#include "mixin/kmac_mixin.hpp" - -namespace digestpp -{ - -/** - * @brief KMAC128 in hash mode - * - * Use this variant when the required hash size is known in advance. Otherwise, use \ref kmac128_xof. - * While primary usage of KMAC is message authentication, it can also be used without a key as a regular hash function. - * - * @hash - * - * @outputsize arbitrary - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes) - * - * @mixinparams customization, key - * - * @mixin{mixin::kmac_mixin} - * - * @par Example:\n - * @code // Set key and output a 256-bit KMAC128 of a string - * digestpp::kmac128 hasher(256); - * hasher.set_key(R"(@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_)"); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code bbd4ebf20aacc8e4dfd2cc91f2b6cbf33e2a45d805996b48a17b8d3e42b4b010 - * @endcode - * - * @sa hasher, kmac128_xof, mixin::kmac_mixin - */ -typedef hasher, mixin::kmac_mixin> kmac128; - -/** - * @brief KMAC256 in hash mode - * - * Use this variant when the required hash size is known in advance. Otherwise, use \ref kmac256_xof. - * While primary usage of KMAC is message authentication, it can also be used without a key as a regular hash function. - * - * @hash - * - * @outputsize arbitrary - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes) - * - * @mixinparams customization, key - * - * @mixin{mixin::kmac_mixin} - * - * @par Example:\n - * @code // Set key and output a 256-bit KMAC256 of a string - * digestpp::kmac256 hasher(256); - * hasher.set_key(R("@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_")); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code bbe7d65fe0e7574254a13e0f3f79482275b96887287fc8b620a92ed5e5de3bce - * @endcode - * - * @sa hasher, kmac256_xof, mixin::kmac_mixin - */ -typedef hasher, mixin::kmac_mixin> kmac256; - -/** - * @brief KMAC128 in XOF mode (KMACXOF128) - * - * Use this variant when the required hash size is not known in advance. Otherwise, use \ref kmac128. - * This hasher can also be used without a key, but there are no advantages over \ref cshake128 in this case. - * - * @xof - * - * @mixinparams customization, key - * - * @mixin{mixin::kmac_mixin} - * - * @par Example:\n - * @code // Set key, absorb a string and squeeze 32 bytes of output - * digestpp::kmac128_xof hasher; - * hasher.set_key(R"(@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_)"); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code a5dd2e2c92e4fe5d203ab7cc4e05df888b021390ba08a00dcb39a94ed07bd364 - * @endcode - * - * @sa hasher, kmac128, mixin::kmac_mixin - */ -typedef hasher, mixin::kmac_mixin> kmac128_xof; - -/** - * @brief KMAC256 in XOF mode (KMACXOF256) - * - * Use this variant when the required hash size is not known in advance. Otherwise, use \ref kmac256. - * This hasher can also be used without a key, but there are no advantages over \ref cshake256 in this case. - * - * @xof - * - * @mixinparams customization, key - * - * @mixin{mixin::kmac_mixin} - * - * @par Example:\n - * @code // Set key, absorb a string and squeeze 32 bytes of output - * digestpp::kmac256_xof hasher; - * hasher.set_key(R"(@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_)"); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 81ce507692e27fb404e4a765c3be3450ce5c090a61b8311f93eb4e35604877ad - * @endcode - * - * @sa hasher, kmac256, mixin::kmac_mixin - */ -typedef hasher, mixin::kmac_mixin> kmac256_xof; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_KMAC_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/kupyna.hpp b/VCMP-LUA/modules/crypto/include/algorithm/kupyna.hpp deleted file mode 100644 index 88377ef..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/kupyna.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_KUPYNA_HPP -#define DIGESTPP_ALGORITHM_KUPYNA_HPP - -#include "../hasher.hpp" -#include "detail/kupyna_provider.hpp" - -namespace digestpp -{ - -/** - * @brief Kupyna hash function - * - * @hash - * - * @outputsize 256 / 512 bits - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not supported - * - * @par Example:\n - * @code // Output a 256-bit Kupyna digest of a string - * digestpp::kupyna hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 996899f2d7422ceaf552475036b2dc120607eff538abf2b8dff471a98a4740c6 - * @endcode - * - * @sa hasher - */ - -typedef hasher kupyna; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_KUPYNA_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/md5.hpp b/VCMP-LUA/modules/crypto/include/algorithm/md5.hpp deleted file mode 100644 index 636e74b..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/md5.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_MD5_HPP -#define DIGESTPP_ALGORITHM_MD5_HPP - -#include "../hasher.hpp" -#include "detail/md5_provider.hpp" - -namespace digestpp -{ - -/** - * @brief MD5 hash function - * - * Note that MD5 hash function is considered insecure and is not recommended for new applications. - * - * @hash - * - * @outputsize 128 bits - * - * @defaultsize 128 bits - * - * @par Example:\n - * @code // Output an MD5 digest of a string - * digestpp::md5 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 9e107d9d372bb6826bd81d3542a419d6 - * @endcode - * - * @sa hasher - */ -typedef hasher md5; - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/mixin/blake2_mixin.hpp b/VCMP-LUA/modules/crypto/include/algorithm/mixin/blake2_mixin.hpp deleted file mode 100644 index 66e6ea2..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/mixin/blake2_mixin.hpp +++ /dev/null @@ -1,127 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_MIXINS_BLAKE2_HPP -#define DIGESTPP_MIXINS_BLAKE2_HPP - -namespace digestpp -{ - -namespace mixin -{ - -/** - * \brief Defines additional public functions for BLAKE2 family of algorithms. - * \sa hasher, blake2s, blake2b, blake2sx, blake2bx, blake2sx_xof, blake2bx_xof - */ -template -class blake2_mixin -{ -public: - /** - * \brief Set salt from std::string - * - * Supported salt size is 8 bytes for BLAKE2s and 16 bytes for BLAKE2b. - * - * \param[in] salt String with salt - * \throw std::runtime_error if salt size is not supported. - * \return Reference to hasher - */ - inline hasher& set_salt(const std::string& salt) - { - return set_salt(salt.c_str(), salt.size()); - } - - /** - * \brief Set salt from raw buffer - * - * Supported salt size is 8 bytes for BLAKE2s and 16 bytes for BLAKE2b. - * - * \param[in] salt Pointer to salt bytes - * \param[in] salt_len Salt length (in bytes) - * \throw std::runtime_error if salt size is not supported. - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_salt(const C* salt, size_t salt_len) - { - auto& blake = static_cast&>(*this); - blake.provider.set_salt(reinterpret_cast(salt), salt_len); - blake.provider.init(); - return blake; - } - - /** - * \brief Set personalization from std::string - * - * Supported personalization size is 8 bytes for BLAKE2s and 16 bytes for BLAKE2b. - * - * \param[in] personalization String with personalization - * \throw std::runtime_error if personalization size is not supported. - * \return Reference to hasher - */ - inline hasher& set_personalization(const std::string& personalization) - { - return set_personalization(personalization.c_str(), personalization.size()); - } - - /** - * \brief Set personalization from raw buffer - * - * Supported personalization size is 8 bytes for BLAKE2s and 16 bytes for BLAKE2b. - * - * \param[in] personalization Pointer to personalization bytes - * \param[in] personalization_len Personalization length (in bytes) - * \throw std::runtime_error if personalization size is not supported. - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_personalization(const C* personalization, size_t personalization_len) - { - auto& blake = static_cast&>(*this); - blake.provider.set_personalization(reinterpret_cast(personalization), personalization_len); - blake.provider.init(); - return blake; - } - - /** - * \brief Set key from std::string - * - * Maximum key size is 32 bytes for BLAKE2s and 64 bytes for BLAKE2b. - * - * \param[in] key String with key - * \throw std::runtime_error if key size is not supported. - * \return Reference to hasher - */ - inline hasher& set_key(const std::string& key) - { - auto& blake = static_cast&>(*this); - blake.provider.set_key(key); - blake.provider.init(); - return blake; - } - - /** - * \brief Set key from raw buffer - * - * Maximum key size is 32 bytes for BLAKE2s and 64 bytes for BLAKE2b. - * - * \param[in] key Pointer to key bytes - * \param[in] key_len Key length (in bytes) - * \throw std::runtime_error if key size is not supported. - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_key(const C* key, size_t key_len) - { - return set_key(std::string(reinterpret_cast(key), key_len)); - } -}; - - -} // namespace mixin - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/mixin/blake_mixin.hpp b/VCMP-LUA/modules/crypto/include/algorithm/mixin/blake_mixin.hpp deleted file mode 100644 index a954d96..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/mixin/blake_mixin.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_MIXINS_BLAKE_HPP -#define DIGESTPP_MIXINS_BLAKE_HPP - -namespace digestpp -{ - -namespace mixin -{ - -/** - * \brief Defines additional public functions for BLAKE algorithm. - * \sa hasher, blake - */ -template -class blake_mixin -{ -public: - - /** - * \brief Set salt from std::string - * - * Supported salt size is 16 bytes for BLAKE-224, BLAKE-256 and 32 bytes for BLAKE-384, BLAKE-512. - * - * \param[in] salt String with salt - * \throw std::runtime_error if salt size is not supported. - * \return Reference to hasher - */ - inline hasher& set_salt(const std::string& salt) - { - return set_salt(salt.c_str(), salt.size()); - } - - /** - * \brief Set salt from raw buffer - * - * Supported salt size is 16 bytes for BLAKE-224, BLAKE-256 and 32 bytes for BLAKE-384, BLAKE-512. - * - * \param[in] salt Pointer to salt bytes - * \param[in] salt_len Salt length (in bytes) - * \throw std::runtime_error if salt size is not supported. - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_salt(const C* salt, size_t salt_len) - { - auto& blake = static_cast&>(*this); - blake.provider.set_salt(reinterpret_cast(salt), salt_len); - blake.provider.init(); - return blake; - } -}; - -} // namespace mixin - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/mixin/cshake_mixin.hpp b/VCMP-LUA/modules/crypto/include/algorithm/mixin/cshake_mixin.hpp deleted file mode 100644 index b26d83f..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/mixin/cshake_mixin.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_MIXIN_SHAKE_HPP -#define DIGESTPP_MIXIN_SHAKE_HPP - -namespace digestpp -{ - -namespace mixin -{ - -/** - * \brief Defines additional public functions for cSHAKE128 and cSHAKE256. - * \sa hasher, cshake128, cshake256 - */ -template -class cshake_mixin -{ -public: - /** - * \brief Set NIST function name from std::string - * - * \param[in] function_name NIST function name string - * \return Reference to hasher - */ - inline hasher& set_function_name(const std::string& function_name) - { - auto& shake = static_cast&>(*this); - shake.provider.set_function_name(function_name); - shake.provider.init(); - return shake; - } - - /** - * \brief Set NIST function name from raw buffer - * - * \param[in] function_name Pointer to NIST function name bytes - * \param[in] function_name_len NIST function name length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_function_name(const C* function_name, size_t function_name_len) - { - return set_function_name(std::string(reinterpret_cast(function_name), function_name_len)); - } - - /** - * \brief Set customization from std::string - * - * \param[in] customization Customization string - * \return Reference to hasher - */ - inline hasher& set_customization(const std::string& customization) - { - auto& shake = static_cast&>(*this); - shake.provider.set_customization(customization); - shake.provider.init(); - return shake; - } - - /** - * \brief Set customization from raw buffer - * - * \param[in] customization Pointer to customization bytes - * \param[in] customization_len Customization length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_customization(const C* customization, size_t customization_len) - { - return set_customization(std::string(reinterpret_cast(customization), customization_len)); - } -}; - -} // namespace mixin - -} // namespace digestpp - -#endif // DIGESTPP_MIXIN_SHAKE_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/mixin/k12m14_mixin.hpp b/VCMP-LUA/modules/crypto/include/algorithm/mixin/k12m14_mixin.hpp deleted file mode 100644 index 3b00f15..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/mixin/k12m14_mixin.hpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_MIXINS_K12M14_HPP -#define DIGESTPP_MIXINS_K12M14_HPP - -namespace digestpp -{ - -namespace mixin -{ - -/** - * \brief Defines additional public functions for KangarooTwelve and MarsupilamiFourteen. - * \sa hasher, k12, m14 - */ -template -class k12m14_mixin -{ -public: - - /** - * \brief Set customization from std::string - * - * \param[in] customization Customization string - * \return Reference to hasher - */ - inline hasher& set_customization(const std::string& customization) - { - auto& k12m14 = static_cast&>(*this); - k12m14.provider.set_customization(customization); - k12m14.provider.init(); - return k12m14; - } - - /** - * \brief Set customization from raw buffer - * - * \param[in] customization Pointer to customization bytes - * \param[in] customization_len Customization length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_customization(const C* customization, size_t customization_len) - { - return set_customization(std::string(reinterpret_cast(customization), customization_len)); - } -}; - -} // namespace mixin - -} // namespace digestpp - -#endif // DIGESTPP_MIXINS_K12M14_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/mixin/kmac_mixin.hpp b/VCMP-LUA/modules/crypto/include/algorithm/mixin/kmac_mixin.hpp deleted file mode 100644 index 7e4b2eb..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/mixin/kmac_mixin.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_MIXINS_KMAC_HPP -#define DIGESTPP_MIXINS_KMAC_HPP - -namespace digestpp -{ - -namespace mixin -{ - -/** - * \brief Defines additional public functions for KMAC family of algorithms. - * \sa hasher, kmac128, kmac256, kmac128_xof, kmac256_xof - */ -template -class kmac_mixin -{ -public: - /** - * \brief Set key from std::string - * - * \param[in] key Key string - * \return Reference to hasher - */ - inline hasher& set_key(const std::string& key) - { - auto& kmac = static_cast&>(*this); - kmac.provider.set_key(key); - kmac.provider.init(); - return kmac; - } - - /** - * \brief Set key from raw buffer - * - * \param[in] key Pointer to key bytes - * \param[in] key_len Key length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_key(const C* key, size_t key_len) - { - return set_key(std::string(reinterpret_cast(key), key_len)); - } - - /** - * \brief Set customization from std::string - * - * \param[in] customization Customization string - * \return Reference to hasher - */ - inline hasher& set_customization(const std::string& customization) - { - auto& kmac = static_cast&>(*this); - kmac.provider.set_customization(customization); - kmac.provider.init(); - return kmac; - } - - /** - * \brief Set customization from raw buffer - * - * \param[in] customization Pointer to customization bytes - * \param[in] customization_len Customization length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_customization(const C* customization, size_t customization_len) - { - return set_customization(std::string(reinterpret_cast(customization), customization_len)); - } -}; - -} // namespace mixin - -} // namespace digestpp - -#endif // DIGESTPP_MIXINS_KMAC_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/mixin/null_mixin.hpp b/VCMP-LUA/modules/crypto/include/algorithm/mixin/null_mixin.hpp deleted file mode 100644 index 390aaa7..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/mixin/null_mixin.hpp +++ /dev/null @@ -1,25 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_MIXINS_NULL_HPP -#define DIGESTPP_MIXINS_NULL_HPP - -namespace digestpp -{ -namespace mixin -{ - -/** - * \brief Empty mixin that does not have any additional fuctions. - * \sa hasher - */ -template -struct null_mixin -{ -}; - -} // namespace mixin -} // namespace digestpp - -#endif // DIGESTPP_MIXINS_NULL_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/mixin/skein_mixin.hpp b/VCMP-LUA/modules/crypto/include/algorithm/mixin/skein_mixin.hpp deleted file mode 100644 index a013a92..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/mixin/skein_mixin.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_MIXINS_SKEIN_HPP -#define DIGESTPP_MIXINS_SKEIN_HPP - -namespace digestpp -{ - -namespace mixin -{ - -/** - * \brief Defines additional public functions for Skein family of algorithms. - * \sa hasher, skein256, skein512, skein1024, skein256_xof, skein512_xof, skein1024_xof - */ -template -class skein_mixin -{ -public: - /** - * \brief Set personalization from std::string - * - * \param[in] personalization Personalization string - * \return Reference to hasher - */ - inline hasher& set_personalization(const std::string& personalization) - { - auto& skein = static_cast&>(*this); - skein.provider.set_personalization(personalization); - skein.provider.init(); - return skein; - } - - /** - * \brief Set personalization from raw buffer - * - * \param[in] personalization Pointer to personalization bytes - * \param[in] personalization_len Personalization length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_personalization(const C* personalization, size_t personalization_len) - { - return set_personalization(std::string(reinterpret_cast(personalization), personalization_len)); - } - - /** - * \brief Set key from std::string - * - * \param[in] key Key string - * \return Reference to hasher - */ - inline hasher& set_key(const std::string& key) - { - auto& skein = static_cast&>(*this); - skein.provider.set_key(key); - skein.provider.init(); - return skein; - } - - /** - * \brief Set key from raw buffer - * - * \param[in] key Pointer to key bytes - * \param[in] key_len Key length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_key(const C* key, size_t key_len) - { - return set_key(std::string(reinterpret_cast(key), key_len)); - } - - /** - * \brief Set nonce from std::string - * - * \param[in] nonce Nonce string - * \return Reference to hasher - */ - inline hasher& set_nonce(const std::string& nonce) - { - auto& skein = static_cast&>(*this); - skein.provider.set_nonce(nonce); - skein.provider.init(); - return skein; - } - - /** - * \brief Set nonce from raw buffer - * - * \param[in] nonce Pointer to nonce bytes - * \param[in] nonce_len Nonce length (in bytes) - * \return Reference to hasher - */ - template::value>::type* = nullptr> - inline hasher& set_nonce(const C* nonce, size_t nonce_len) - { - return set_nonce(std::string(reinterpret_cast(nonce), nonce_len)); - } -}; - -} // namespace mixin - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/sha1.hpp b/VCMP-LUA/modules/crypto/include/algorithm/sha1.hpp deleted file mode 100644 index 536b623..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/sha1.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_SHA1_HPP -#define DIGESTPP_ALGORITHM_SHA1_HPP - -#include "../hasher.hpp" -#include "detail/sha1_provider.hpp" - -namespace digestpp -{ - -/** - * @brief SHA-1 hash function - * - * Note that SHA-1 hash function is considered insecure and is not recommended for new applications. - * - * @hash - * - * @outputsize 160 bits - * - * @defaultsize 160 bits - * - * @par Example:\n - * @code // Output a SHA1 digest of a string - * digestpp::sha1 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 - * @endcode - * - * @sa hasher - */ -typedef hasher sha1; - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/sha2.hpp b/VCMP-LUA/modules/crypto/include/algorithm/sha2.hpp deleted file mode 100644 index dee9c81..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/sha2.hpp +++ /dev/null @@ -1,118 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_SHA2_HPP -#define DIGESTPP_ALGORITHM_SHA2_HPP - -#include "../hasher.hpp" -#include "detail/sha2_provider.hpp" - -namespace digestpp -{ - -/** - * @brief SHA-512 hash function - * - * @hash - * - * @outputsize 8 - 512 bits - * - * @defaultsize 512 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes), - * or is not within the supported range - * - * @par Example:\n - * @code // Output a SHA-512/256 digest of a string - * digestpp::sha512 hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code dd9d67b371519c339ed8dbd25af90e976a1eeefd4ad3d889005e532fc5bef04d - * @endcode - * - * @sa hasher - */ -typedef hasher> sha512; - -/** - * @brief SHA-384 hash function - * - * @hash - * - * @outputsize 384 bits - * - * @defaultsize 384 bits - * - * @par Example:\n - * @code // Output a SHA-384 digest of a string - * digestpp::sha384 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1 - * @endcode - * - * @sa hasher - */ -typedef hasher> sha384; - -/** - * @brief SHA-256 hash function - * - * Note that this function is slower than SHA-512/256 on 64-bit systems. - * - * @hash - * - * @outputsize 256 bits - * - * @defaultsize 256 bits - * - * @par Example:\n - * @code // Output a SHA-256 digest of a string - * digestpp::sha256 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 - * @endcode - * - * @sa hasher - */ -typedef hasher> sha256; - -/** - * @brief SHA-224 hash function - * - * @hash - * - * @outputsize 224 bits - * - * @defaultsize 224 bits - * - * @par Example:\n - * @code // Output a SHA-224 digest of a string - * digestpp::sha224 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525 - * @endcode - * - * @sa hasher - */ -typedef hasher> sha224; - - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/sha3.hpp b/VCMP-LUA/modules/crypto/include/algorithm/sha3.hpp deleted file mode 100644 index 8d5dff7..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/sha3.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_SHA3_HPP -#define DIGESTPP_ALGORITHM_SHA3_HPP - -#include "../hasher.hpp" -#include "detail/sha3_provider.hpp" - -namespace digestpp -{ - -/** - * @brief SHA-3 hash function - * - * @hash - * - * @outputsize 224 / 256 / 384 / 512 bits - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not supported - * - * @par Example:\n - * @code // Output a 256-bit SHA-3 digest of a string - * digestpp::sha3 hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 69070dda01975c8c120c3aada1b282394e7f032fa9cf32f4cb2259a0897dfc04 - * @endcode - * - * @sa hasher - */ -typedef hasher sha3; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_SHA3_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/shake.hpp b/VCMP-LUA/modules/crypto/include/algorithm/shake.hpp deleted file mode 100644 index c3efcab..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/shake.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_SHAKE_HPP -#define DIGESTPP_ALGORITHM_SHAKE_HPP - -#include "../hasher.hpp" -#include "detail/shake_provider.hpp" -#include "mixin/cshake_mixin.hpp" - -namespace digestpp -{ - -/** - * @brief SHAKE128 function - * - * @xof - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::shake128 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code f4202e3c5852f9182a0430fd8144f0a74b95e7417ecae17db0f8cfeed0e3e66e - * @endcode - * - * @sa hasher, cshake128 - */ -typedef hasher> shake128; - -/** - * @brief SHAKE256 function - * - * @xof - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::shake256 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 2f671343d9b2e1604dc9dcf0753e5fe15c7c64a0d283cbbf722d411a0e36f6ca - * @endcode - * - * @sa hasher, cshake256 - */ -typedef hasher> shake256; - -/** - * @brief Customizable cSHAKE128 function - * - * Extendable output function similar to SHAKE128 but with possibility to use a customization string. - * When used without a customization string, the output is identical to \ref shake128. - * - * @xof - * - * @mixinparams function name, customization - * - * @mixin{mixin::cshake_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::cshake128 hasher; - * hasher.set_customization("My Custom SHAKE"); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 5b831bfe752f7f05d81f18f0e83a92eb48b9e3d460c10022ecb4852aa8b1f9d4 - * @endcode - * - * @sa hasher, mixin::cshake_mixin - */ -typedef hasher, mixin::cshake_mixin> cshake128; - -/** - * @brief Customizable cSHAKE256 function - * - * Extendable output function similar to SHAKE256 but with possibility to use a customization string. - * When used without a customization string, the output is identical to \ref shake256. - * - * @xof - * - * @mixinparams function name, customization - * - * @mixin{mixin::cshake_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::cshake256 hasher; - * hasher.set_customization("My Custom SHAKE"); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code bcebde2c2e18f6efd99ee9e0def1383e86595d72e49b4754f7f727a962c3cd3d - * @endcode - * - * @sa hasher, mixin::cshake_mixin - */ -typedef hasher, mixin::cshake_mixin> cshake256; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_SHAKE_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/skein.hpp b/VCMP-LUA/modules/crypto/include/algorithm/skein.hpp deleted file mode 100644 index a2d5396..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/skein.hpp +++ /dev/null @@ -1,191 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_SKEIN_HPP -#define DIGESTPP_ALGORITHM_SKEIN_HPP - -#include "../hasher.hpp" -#include "detail/skein_provider.hpp" -#include "mixin/skein_mixin.hpp" - -namespace digestpp -{ - -/** - * @brief Skein1024 hash function - * - * Use this variant when the required hash size is known in advance. Otherwise, use \ref skein1024_xof - * - * @hash - * - * @outputsize arbitrary - * - * @defaultsize 1024 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes) - * - * @mixinparams personalization, nonce, key - * - * @mixin{mixin::skein_mixin} - * - * @par Example:\n - * @code // Output a 256-bit Skein1024 digest of a string - * digestpp::skein1024 hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 054922d4393e36af62143986221555bee407671f6e57631bd7273e215a714833 - * @endcode - * - * @sa hasher, mixin::skein_mixin, skein1024_xof - */ -typedef hasher, mixin::skein_mixin> skein1024; - -/** - * @brief Skein512 hash function - * - * Use this variant when the required hash size is known in advance. Otherwise, use \ref skein512_xof - * - * @hash - * - * @outputsize arbitrary - * - * @defaultsize 512 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes) - * - * @mixinparams personalization, nonce, key - * - * @mixin{mixin::skein_mixin} - * - * @par Example:\n - * @code // Output a 256-bit Skein512 digest of a string - * digestpp::skein512 hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code b3250457e05d3060b1a4bbc1428bc75a3f525ca389aeab96cfa34638d96e492a - * @endcode - * - * @sa hasher, mixin::skein_mixin, skein512_xof - */ -typedef hasher, mixin::skein_mixin> skein512; - -/** - * @brief Skein256 hash function - * - * Use this variant when the required hash size is known in advance. Otherwise, use \ref skein256_xof - * - * @hash - * - * @outputsize arbitrary - * - * @defaultsize 256 bits - * - * @throw std::runtime_error if the requested digest size is not divisible by 8 (full bytes) - * - * @mixinparams personalization, nonce, key - * - * @mixin{mixin::skein_mixin} - * - * @par Example:\n - * @code // Output a 512-bit Skein256 digest of a string - * digestpp::skein256 hasher(512); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code f8138e72cdd9e11cf09e4be198c234acb0d21a9f75f936e989cf532f1fa9f4fb21d255811f0f1592fb3617d04704add875ae7bd16ddbbeaed4eca6eb9675d2c6 - * @endcode - * - * @sa hasher, mixin::skein_mixin, skein256_xof - */ -typedef hasher, mixin::skein_mixin> skein256; - -/** - * @brief Skein1024 in XOF mode - * - * Use this variant when the required hash size is not known in advance. Otherwise, use \ref skein1024 - * - * @xof - * - * @mixinparams personalization, nonce, key - * - * @mixin{mixin::skein_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::skein1024_xof hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 20cd7366b0a3713037fdbf8c635ea190943261455689792a327d93a9fd74dedf - * @endcode - * - * @sa hasher, mixin::skein_mixin, skein1024 - */ -typedef hasher, mixin::skein_mixin> skein1024_xof; - -/** - * @brief Skein512 in XOF mode - * - * Use this variant when the required hash size is not known in advance. Otherwise, use \ref skein512 - * - * @xof - * - * @mixinparams personalization, nonce, key - * - * @mixin{mixin::skein_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::skein512_xof hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code cd7447a48e387ca4461e75ede8424566f7ed816a80bfac5bed291ac107f96170 - * @endcode - * - * @sa hasher, mixin::skein_mixin, skein512 - */ -typedef hasher, mixin::skein_mixin> skein512_xof; - -/** - * @brief Skein256 in XOF mode - * - * Use this variant when the required hash size is not known in advance. Otherwise, use \ref skein256 - * - * @xof - * - * @mixinparams personalization, nonce, key - * - * @mixin{mixin::skein_mixin} - * - * @par Example:\n - * @code // Absorb a string and squeeze 32 bytes of output - * digestpp::skein256_xof hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexsqueeze(32) << '\n'; - * @endcode - * - * @par Example output:\n - * @code 217021fbabe331c5753024fe4c17a005a698b037859ca8f4f0fb9112dce5605c - * @endcode - * - * @sa hasher, mixin::skein_mixin, skein256 - */ -typedef hasher, mixin::skein_mixin> skein256_xof; - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/sm3.hpp b/VCMP-LUA/modules/crypto/include/algorithm/sm3.hpp deleted file mode 100644 index 69ded58..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/sm3.hpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_SM3_HPP -#define DIGESTPP_ALGORITHM_SM3_HPP - -#include "../hasher.hpp" -#include "detail/sm3_provider.hpp" - -namespace digestpp -{ - -/** - * @brief SM3 hash function - * - * @hash - * - * @outputsize 256 bits - * - * @defaultsize 256 bits - * - * @par Example:\n - * @code // Output a SM3 digest of a string - * digestpp::sm3 hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 5fdfe814b8573ca021983970fc79b2218c9570369b4859684e2e4c3fc76cb8ea - * @endcode - * - * @sa hasher - */ -typedef hasher sm3; - -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/streebog.hpp b/VCMP-LUA/modules/crypto/include/algorithm/streebog.hpp deleted file mode 100644 index bc9e1c8..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/streebog.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_STREEBOG_HPP -#define DIGESTPP_ALGORITHM_STREEBOG_HPP - -#include "../hasher.hpp" -#include "detail/streebog_provider.hpp" - -namespace digestpp -{ - -/** @brief Streebog hash function - * - * @hash - * - * @outputsize 256 / 512 bits - * - * @defaultsize none - * - * @throw std::runtime_error if the requested digest size is not supported - * - * @par Example:\n - * @code // Output a 256-bit Streebog digest of a string - * digestpp::streebog hasher(256); - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code 3e7dea7f2384b6c5a3d0e24aaa29c05e89ddd762145030ec22c71a6db8b2c1f4 - * @endcode - * - * @sa hasher - */ -typedef hasher streebog; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_STREEBOG_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/algorithm/whirlpool.hpp b/VCMP-LUA/modules/crypto/include/algorithm/whirlpool.hpp deleted file mode 100644 index cc6538f..0000000 --- a/VCMP-LUA/modules/crypto/include/algorithm/whirlpool.hpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_ALGORITHM_WHIRLPOOL_HPP -#define DIGESTPP_ALGORITHM_WHIRLPOOL_HPP - -#include "../hasher.hpp" -#include "detail/whirlpool_provider.hpp" - -namespace digestpp -{ - -/** - * @brief Whirlpool hash function - * - * @hash - * - * @outputsize 512 bits - * - * @defaultsize 512 bits - * - * @par Example:\n - * @code // Output a Whirlpool digest of a string - * digestpp::whirlpool hasher; - * hasher.absorb("The quick brown fox jumps over the lazy dog"); - * std::cout << hasher.hexdigest() << '\n'; - * @endcode - * - * @par Example output:\n - * @code b97de512e91e3828b40d2b0fdce9ceb3c4a71f9bea8d88e75c4fa854df36725fd2b52eb6544edcacd6f8beddfea403cb55ae31f03ad62a5ef54e42ee82c3fb35 - * @endcode - * - * @sa hasher - */ -typedef hasher whirlpool; - -} // namespace digestpp - -#endif // DIGESTPP_ALGORITHM_WHIRLPOOL_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/detail/absorb_data.hpp b/VCMP-LUA/modules/crypto/include/detail/absorb_data.hpp deleted file mode 100644 index d697229..0000000 --- a/VCMP-LUA/modules/crypto/include/detail/absorb_data.hpp +++ /dev/null @@ -1,46 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_DETAIL_ABSORB_DATA_HPP -#define DIGESTPP_DETAIL_ABSORB_DATA_HPP - -namespace digestpp -{ - -namespace detail -{ - -// Accumulate data and call the transformation function for full blocks. -template -inline void absorb_bytes(const unsigned char* data, size_t len, size_t bs, size_t bschk, - unsigned char* m, size_t& pos, T& total, TF transform) -{ - if (pos && pos + len >= bschk) - { - memcpy(m + pos, data, bs - pos); - transform(m, 1); - len -= bs - pos; - data += bs - pos; - total += bs * 8; - pos = 0; - } - if (len >= bschk) - { - size_t blocks = (len + bs - bschk) / bs; - size_t bytes = blocks * bs; - transform(data, blocks); - len -= bytes; - data += bytes; - total += (bytes)* 8; - } - memcpy(m + pos, data, len); - pos += len; -} - - -} // namespace detail - -} // namespace digestpp - -#endif // DIGESTPP_DETAIL_ABSORB_DATA_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/detail/functions.hpp b/VCMP-LUA/modules/crypto/include/detail/functions.hpp deleted file mode 100644 index b48ffd4..0000000 --- a/VCMP-LUA/modules/crypto/include/detail/functions.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_DETAIL_FUNCTIONS_HPP -#define DIGESTPP_DETAIL_FUNCTIONS_HPP - -#include -#include -#include - -namespace digestpp -{ -namespace detail -{ - -// Byte-swap a 16-bit unsigned integer. -inline uint16_t byteswap(uint16_t val) -{ - return ((val & 0xff) << 8) | ((val & 0xff00) >> 8); -} - -// Byte-swap a 32-bit unsigned integer. -inline uint32_t byteswap(uint32_t val) -{ - return (((val & 0xff000000) >> 24) | - ((val & 0x00ff0000) >> 8) | - ((val & 0x0000ff00) << 8) | - ((val & 0x000000ff) << 24)); -} - -// Byte-swap a 64-bit unsigned integer. -inline uint64_t byteswap(uint64_t val) -{ - return (((val & 0xff00000000000000ull) >> 56) | - ((val & 0x00ff000000000000ull) >> 40) | - ((val & 0x0000ff0000000000ull) >> 24) | - ((val & 0x000000ff00000000ull) >> 8) | - ((val & 0x00000000ff000000ull) << 8) | - ((val & 0x0000000000ff0000ull) << 24) | - ((val & 0x000000000000ff00ull) << 40) | - ((val & 0x00000000000000ffull) << 56)); -} - -#ifdef __APPLE__ -inline size_t byteswap(size_t val) -{ - switch(sizeof(size_t)) - { - case sizeof(uint16_t): - return (size_t)byteswap((uint16_t)val); - - case sizeof(uint32_t): - return (size_t)byteswap((uint32_t)val); - - case sizeof(uint64_t): - return (size_t)byteswap((uint64_t)val); - } -} -#endif - -// Rotate 32-bit unsigned integer to the right. -inline uint32_t rotate_right(uint32_t x, unsigned n) -{ - return (x >> n) | (x << (32 - n)); -} - -// Rotate 32-bit unsigned integer to the left. -inline uint32_t rotate_left(uint32_t x, unsigned n) -{ - return (x << n) | (x >> (32 - n)); -} - -// Rotate 64-bit unsigned integer to the right. -inline uint64_t rotate_right(uint64_t x, unsigned n) -{ - return (x >> n) | (x << (64 - n)); -} - -// Rotate 64-bit unsigned integer to the left. -inline uint64_t rotate_left(uint64_t x, unsigned n) -{ - return (x << n) | (x >> (64 - n)); -} - -// Clear memory, suppressing compiler optimizations. -inline void zero_memory(void *v, size_t n) { - volatile unsigned char *p = static_cast(v); - while (n--) { - *p++ = 0; - } -} - -// Clear memory occupied by an array, suppressing compiler optimizations. -template -inline void zero_memory(std::array& ar) -{ - zero_memory(ar.data(), ar.size() * sizeof(T)); -} - -// Clear memory occupied by std::string -inline void zero_memory(std::string& s) -{ - if (!s.empty()) - zero_memory(&s[0], s.size()); -} - - -} // namespace detail -} // namespace digestpp - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/detail/stream_width_fixer.hpp b/VCMP-LUA/modules/crypto/include/detail/stream_width_fixer.hpp deleted file mode 100644 index 5e0c606..0000000 --- a/VCMP-LUA/modules/crypto/include/detail/stream_width_fixer.hpp +++ /dev/null @@ -1,30 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_DETAIL_WIDTH_FIXER_HPP -#define DIGESTPP_DETAIL_WIDTH_FIXER_HPP - -namespace digestpp -{ -namespace detail -{ - -template -struct stream_width_fixer -{ - stream_width_fixer(T value) : v(value) {} - T v; -}; - -template -std::ostream& operator<<(std::ostream& ostr, const stream_width_fixer& value) -{ - return ostr << std::setw(N) << value.v; -} - - -} // namespace detail -} // namespace digestpp - -#endif // DIGESTPP_DETAIL_WIDTH_FIXER_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/detail/traits.hpp b/VCMP-LUA/modules/crypto/include/detail/traits.hpp deleted file mode 100644 index 34bbd69..0000000 --- a/VCMP-LUA/modules/crypto/include/detail/traits.hpp +++ /dev/null @@ -1,35 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_DETAIL_TRAITS_HPP -#define DIGESTPP_DETAIL_TRAITS_HPP - -#include // needed for testing std::byte - -namespace digestpp -{ -namespace detail -{ - -template -struct is_xof -{ - static const bool value = T::is_xof; -}; - -template -struct is_byte -{ - static const bool value = std::is_same::value || - std::is_same::value || -#if (defined(_HAS_STD_BYTE) && _HAS_STD_BYTE) || (defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603) - std::is_same::value || -#endif - std::is_same::value; -}; - -} // namespace detail -} // namespace digestpp - -#endif // DIGESTPP_DETAIL_TRAITS_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/detail/validate_hash_size.hpp b/VCMP-LUA/modules/crypto/include/detail/validate_hash_size.hpp deleted file mode 100644 index 51bbbde..0000000 --- a/VCMP-LUA/modules/crypto/include/detail/validate_hash_size.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_DETAIL_VALIDATE_HASH_SIZE_HPP -#define DIGESTPP_DETAIL_VALIDATE_HASH_SIZE_HPP - -namespace digestpp -{ -namespace detail -{ - -// Validate that variable hash is within the list of allowed sizes -inline void validate_hash_size(size_t hs, std::initializer_list set) -{ - if (!hs) - throw std::runtime_error("hash size can't be zero"); - - if (std::find(set.begin(), set.end(), hs)) - return; - - throw std::runtime_error("invalid hash size"); -} - -// Validate variable hash size up to max bits -inline void validate_hash_size(size_t hs, size_t max) -{ - if (!hs) - throw std::runtime_error("hash size can't be zero"); - - if (hs % 8) - throw std::runtime_error("non-byte hash sizes are not supported"); - - if (hs > max) - throw std::runtime_error("invalid hash size"); -} - -} // namespace detail -} // namespace digestpp - -#endif // DIGESTPP_DETAIL_VALIDATE_HASH_SIZE_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/digestpp.hpp b/VCMP-LUA/modules/crypto/include/digestpp.hpp deleted file mode 100644 index ce64323..0000000 --- a/VCMP-LUA/modules/crypto/include/digestpp.hpp +++ /dev/null @@ -1,21 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#include "hasher.hpp" -#include "algorithm/sha2.hpp" -#include "algorithm/sha3.hpp" -#include "algorithm/shake.hpp" -#include "algorithm/skein.hpp" -#include "algorithm/blake.hpp" -#include "algorithm/blake2.hpp" -#include "algorithm/groestl.hpp" -#include "algorithm/jh.hpp" -#include "algorithm/md5.hpp" -#include "algorithm/sha1.hpp" -#include "algorithm/sm3.hpp" -#include "algorithm/streebog.hpp" -#include "algorithm/whirlpool.hpp" -#include "algorithm/k12m14.hpp" -#include "algorithm/kupyna.hpp" -#include "algorithm/kmac.hpp" \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/include/hasher.hpp b/VCMP-LUA/modules/crypto/include/hasher.hpp deleted file mode 100644 index 3ffbf58..0000000 --- a/VCMP-LUA/modules/crypto/include/hasher.hpp +++ /dev/null @@ -1,347 +0,0 @@ -/* -This code is written by kerukuro and released into public domain. -*/ - -#ifndef DIGESTPP_HASHER_HPP -#define DIGESTPP_HASHER_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "detail/traits.hpp" -#include "detail/stream_width_fixer.hpp" -#include "algorithm/mixin/null_mixin.hpp" - -namespace digestpp -{ - -/** - * \brief Main class template implementing the public API for hashing - * - * Individual hash functions are defined by typedefs. - * See \ref digestpp namespace description for description of supported hash functions with usage examples. - * - * \param HashProvider A class implementing the algorithm via traditional init/update/final interface. - * \param Mixin A class template which can be used to inject additional functions to the public API of the hasher. - * - * \sa digestpp - */ -template class Mixin = mixin::null_mixin> -class hasher : public Mixin -{ - public: - - /** - * \brief Default constructor - * - * \available_if * HashProvider is a hash function with fixed output size, OR - * * HashProvider is a hash function with sensible default output size, OR - * * HashProvider is an extendable output function (XOF) - */ - template::value>::type* = nullptr> - hasher() - { - provider.init(); - } - - /** - * \brief Constructor with hash size parameter - * - * Supported output sizes for each algorithm are listed in the description of corresponding typedef. - * - * \available_if * HashProvider supports multiple output sizes, AND - * * HashProvider is not an extendable output function (XOF) - * - * \param[in] hashsize Desired output digest size (in bits). - * \throw std::runtime_error if the requested output size is not supported by the algorithm. - */ - template::value>::type* = nullptr> - hasher(size_t hashsize) : provider(hashsize) - { - provider.init(); - } - - /** - * \brief Absorbs bytes from a C-style pointer to character buffer - * \param[in] data Pointer to data to absorb - * \param[in] len Size of data to absorb (in bytes) - * \return Reference to *this - * - * @par Example:\n - * @code // Calculate SHA-512/256 digest of a C array and output it in hex format - * unsigned char c[32]; - * std::iota(c, c + sizeof(c), 0); - * cout << digestpp::sha512(256).absorb(c, sizeof(c)).hexdigest() << std::endl; - * @endcode - */ - template::value>::type* = nullptr> - inline hasher& absorb(const T* data, size_t len) - { - provider.update(reinterpret_cast(data), len); - return *this; - } - - /** - * \brief Absorbs bytes from std::basic_string - * \param[in] str String to absorb - * \return Reference to *this - */ - template::value && !std::is_same::value>::type* = nullptr> - inline hasher& absorb(const std::basic_string& str) - { - if (!str.empty()) - provider.update(reinterpret_cast(&str[0]), str.size()); - return *this; - } - - /** - * \brief Absorbs bytes from std::string - * \param[in] str String to absorb - * \return Reference to *this - * @par Example:\n - * @code // Calculate BLAKE2b-256 digest from an std::string and output it in hex format - * std::string str = "The quick brown fox jumps over the lazy dog"; - * std::cout << digestpp::blake2b(256).absorb(str).hexdigest() << std::endl; - * @endcode - */ - inline hasher& absorb(const std::string& str) - { - if (!str.empty()) - provider.update(reinterpret_cast(&str[0]), str.size()); - return *this; - } - - /** - * \brief Absorbs bytes from std::istream - * \param[in] istr Stream to absorb - * \return Reference to *this - * @par Example:\n - * @code // Calculate SHA-256 digest of a file and output it in hex format - * std::ifstream file("filename", std::ios_base::in|std::ios_base::binary); - * std::cout << digestpp::sha256().absorb(file).hexdigest() << std::endl; - * @endcode - */ - template::value>::type* = nullptr> - inline hasher& absorb(std::basic_istream& istr) - { - const int tmp_buffer_size = 10000; - unsigned char buffer[tmp_buffer_size]; - size_t len = 0; - while (istr.read(reinterpret_cast(buffer), sizeof(buffer))) - { - provider.update(buffer, sizeof(buffer)); - len += sizeof(buffer); - } - size_t gcount = istr.gcount(); - if (gcount) - { - provider.update(buffer, gcount); - len += gcount; - } - return *this; - } - - /** - * \brief Absorbs bytes from an iterator sequence - * \param[in] begin Begin iterator - * \param[in] end End iterator - * \return Reference to *this - * - * @par Example:\n - * @code // Calculate SHA-512 digest of a vector and output it in hex format - * std::vector v(100); - * std::iota(v.begin(), v.end(), 0); - * std::cout << digestpp::sha512().absorb(v.begin(), v.end()).hexdigest() << std::endl; - * @endcode - */ - template - inline hasher& absorb(IT begin, IT end) - { - while (begin != end) - { - unsigned char byte = *begin++; - provider.update(&byte, 1); - } - return *this; - } - - /** - * \brief Squeeze bytes into user-provided preallocated buffer. - * - * After each invocation of this function the internal state of the hasher changes - * so that the next call will generate different (additional) output bytes. - * To reset the state and start new digest calculation, use \ref reset function. - * - * \available_if HashProvider is an extendable output function (XOF) - * - * \param[out] buf Buffer to squeeze data to; must be of byte type (char, unsigned char or signed char) - * \param[in] len Size of data to squeeze (in bytes) - */ - template::value && detail::is_xof::value>::type* = nullptr> - inline void squeeze(T* buf, size_t len) - { - provider.squeeze(reinterpret_cast(buf), len); - } - - /** - * \brief Squeeze bytes into an output iterator. - * - * After each invocation of this function the internal state of the hasher changes - * so that the next call will generate different (additional) output bytes. - * To reset the state and start new digest calculation, use \ref reset function. - * - * \available_if HashProvider is an extendable output function (XOF) - * - * \param[in] len Size of data to squeeze (in bytes) - * \param[out] it output iterator to a byte container - * @par Example:\n - * @code // Generate long output using SHAKE-256 extendable output function using multiple calls to squeeze() - * std::vector v; - * digestpp::shake256 xof; - * xof.absorb("The quick brown fox jumps over the lazy dog"); - * xof.squeeze(1000, back_inserter(v)); - * xof.squeeze(1000, back_inserter(v)); - * xof.squeeze(1000, back_inserter(v)); - * std::cout << "Squeezed " << v.size() << " bytes." << std::endl; - * @endcode - */ - template::value>::type* = nullptr> - inline void squeeze(size_t len, OI it) - { - std::vector hash(len); - provider.squeeze(&hash[0], len); - std::copy(hash.begin(), hash.end(), it); - } - - /** - * \brief Squeeze bytes and return them as a hex string. - * - * After each invocation of this function the internal state of the hasher changes - * so that the next call will generate different (additional) output bytes. - * To reset the state and start new digest calculation, use \ref reset function. - * - * \available_if HashProvider is an extendable output function (XOF) - * - * \param[in] len Size of data to squeeze (in bytes) - * \return Calculated digest as a hexademical string - * @par Example:\n - * @code // Generate 64-byte digest using customizable cSHAKE-256 algorithm and print it in hex format - * digestpp::cshake256 xof; - * xof.set_customization("My Customization"); - * std::cout << xof.absorb("The quick brown fox jumps over the lazy dog").hexsqueeze(64) << std::endl; - * @endcode - */ - template::value>::type* = nullptr> - inline std::string hexsqueeze(size_t len) - { - std::ostringstream res; - res << std::setfill('0') << std::hex; - squeeze(len, std::ostream_iterator>(res, "")); - return res.str(); - } - - /** - * \brief Output binary digest into user-provided preallocated buffer. - * - * This function does not change the state of the hasher and can be called multiple times, producing the same result. - * To reset the state and start new digest calculation, use \ref reset function. - * - * \available_if HashProvider is a hash function (not XOF) - * - * \param[out] buf Buffer to squeeze data to; must be of byte type (char, unsigned char or signed char) - * \param[in] len Size of the buffer - * \throw std::runtime_error if the buffer size is not enough to fit the calculated digest - * (fixed by the algorithm or specified in the hasher constructor). - * @par Example:\n - * @code // Output binary digest to a raw C array - * unsigned char buf[32]; - * digestpp::sha3(256).absorb("The quick brown fox jumps over the lazy dog").digest(buf, sizeof(buf)); - * @endcode - */ - template::value && !detail::is_xof::value>::type* = nullptr> - inline void digest(T* buf, size_t len) const - { - if (len < provider.hash_size() / 8) - throw std::runtime_error("Invalid buffer size"); - - HashProvider copy(provider); - copy.final(buf); - } - - /** - * \brief Write binary digest into an output iterator. - * - * This function does not change the state of the hasher and can be called multiple times, producing the same result. - * To reset the state and start new digest calculation, use \ref reset function. - * - * \available_if HashProvider is a hash function (not XOF) - * - * \param[out] it Output iterator to a byte container. - * @par Example:\n - * @code // Output binary SHA3-256 digest to a vector - * vector v; - * digestpp::sha3(256).absorb("The quick brown fox jumps over the lazy dog").digest(back_inserter(v)); - * @endcode - */ - template::value>::type* = nullptr> - inline void digest(OI it) const - { - HashProvider copy(provider); - std::vector hash(provider.hash_size() / 8); - copy.final(&hash[0]); - std::copy(hash.begin(), hash.end(), it); - } - - /** - * \brief Return hex digest of absorbed data. - * - * This function does not change the state of the hasher and can be called multiple times, producing the same result. - * To reset the state and start new digest calculation, use \ref reset function. - * - * \available_if HashProvider is a hash function (not XOF) - * - * \return Calculated digest as a hexademical string - * @par Example:\n - * @code // Calculate BLAKE2b digest from a double quoted string and output it in hex format - * std::cout << digestpp::blake2b().absorb("The quick brown fox jumps over the lazy dog").hexdigest() << std::endl; - * @endcode - */ - template::value>::type* = nullptr> - inline std::string hexdigest() const - { - std::ostringstream res; - res << std::setfill('0') << std::hex; - digest(std::ostream_iterator>(res, "")); - return res.str(); - } - - /** - * \brief Reset the hasher state to start new digest computation. - * - * \param[in] resetParameters if true, also clear optional parameters (personalization, salt, etc) - */ - inline void reset(bool resetParameters = false) - { - if (resetParameters) - provider.clear(); - provider.init(); - } - -private: - friend Mixin; - HashProvider provider; -}; - - -} // namespace digestpp - -#endif // DIGESTPP_HASHER_HPP \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/premake5.lua b/VCMP-LUA/modules/crypto/premake5.lua deleted file mode 100644 index a7bbb79..0000000 --- a/VCMP-LUA/modules/crypto/premake5.lua +++ /dev/null @@ -1,21 +0,0 @@ -project "module-crypto" - kind "StaticLib" - language "C++" - cppdialect "C++17" - - targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") - objdir ("%{wks.location}/bin/interm/" .. outputdir .. "/%{prj.name}") - - files - { - "include/**.hpp", - "src/**.cpp", - } - - includedirs - { - "include", - } - - filter "system:linux" - buildoptions { "-g2", "-O2" } \ No newline at end of file diff --git a/VCMP-LUA/modules/crypto/src/src.cpp b/VCMP-LUA/modules/crypto/src/src.cpp deleted file mode 100644 index b219599..0000000 --- a/VCMP-LUA/modules/crypto/src/src.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "../include/digestpp.hpp" \ No newline at end of file diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/account.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/account.hpp deleted file mode 100644 index 0088676..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/account.hpp +++ /dev/null @@ -1,239 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_ACCOUNT_HPP_ -#define _MARIADB_ACCOUNT_HPP_ - -#include -#include -#include -#include - -namespace mariadb { -class account; -typedef std::shared_ptr account_ref; - -class option_arg { - public: - virtual ~option_arg() = default; - virtual const void *value() = 0; -}; - -#define MAKE_OPTION_ARG(name, type, return_value) \ -class option_arg_##name : public option_arg { \ - public: \ - explicit option_arg_##name(const type &arg) : m_value(arg) { } \ - const void *value() override { return return_value; } \ - protected: \ - type m_value; \ -} - -MAKE_OPTION_ARG(bool, bool, &m_value); -MAKE_OPTION_ARG(int, int, &m_value); -MAKE_OPTION_ARG(string, std::string, m_value.c_str()); - -/** - * Class used to store account and connection information used by mariadb::connection when - * connecting. - * Note that modifying an account after the connection was established is useless. - */ -class account { - public: - typedef std::map map_options_t; - typedef std::map> map_connect_options_t; - - public: - /** - * Destructs the account - */ - virtual ~account() {} - - /** - * Gets the name of the host to connect to - */ - const std::string &host_name() const; - - /** - * Gets the username to log in with - */ - const std::string &user_name() const; - - /** - * Gets the password of the user to log in with - */ - const std::string &password() const; - - /** - * Gets the unix socket path to connect to. - * If this option is set, host and port will be ignored - */ - const std::string &unix_socket() const; - - /** - * Gets the path to the key file - */ - const std::string &ssl_key() const; - - /** - * Gets the path to the certificate file - */ - const std::string &ssl_certificate() const; - - /** - * Gets the path to the certificate authority file - */ - const std::string &ssl_ca() const; - - /** - * Gets the path to the directory containing CA files - */ - const std::string &ssl_ca_path() const; - - /** - * Gets the list of allowed SSL ciphers - */ - const std::string &ssl_cipher() const; - - /** - * Gets the port to connect to - */ - u32 port() const; - - /** - * Gets the name of the database to open on connect - */ - const std::string &schema() const; - - /** - * Sets the name of the database to open on connect - */ - void set_schema(const std::string &schema); - - /** - * Set SSL options. All files should be PEM format - * - * @param key Path to the key file - * @param certificate Path to the certificate file - * @param ca Path to the certificate authority file - * @param ca_path Path to a directory containing CA files - * @param cipher List of allowed SSL ciphers. See MariaDB manual for possible values - */ - void set_ssl(const std::string &key, const std::string &certificate, const std::string &ca, - const std::string &ca_path, const std::string &cipher); - - /** - * Gets the current state of the auto_commit option. This option is turned on by default. - */ - bool auto_commit() const; - - /** - * Sets the state of the auto_commit option. - */ - void set_auto_commit(bool auto_commit); - - /** - * Gets the current state of the store_result option. When set, the connection uses buffered store - * (mysql_store_result) instead of unbuffered store (mysql_use_result). This option is turned on by default. - * - * Note: Unbuffered store has some restrictions and might lead to unexpected behavior. See the documentation - * (https://mariadb.com/kb/en/library/mysql_use_result/) for more information. - */ - bool store_result() const; - - /** - * Sets the state of the store_result option. - */ - void set_store_result(bool store_result); - - /** - * Gets the current value of any named option that was previously set - * - * @return Value of the found option or empty string if not found - */ - const std::string option(const std::string &name) const; - - /** - * Gets a map of all option key/value pairs previously set - */ - const map_options_t &options() const; - - /** - * Sets a named option key/value pair - */ - void set_option(const std::string &name, const std::string &value); - - /** - * Deletes all stored key/value pairs of named options - */ - void clear_options(); - - /** - * Gets a map of all connect option key/value pairs previously set - */ - const map_connect_options_t &connect_options() const; - - /** - * Sets a connect option key/value pair with bool argument - */ - void set_connect_option(mysql_option option, bool arg); - /** - * Sets a connect option key/value pair with int argument - */ - void set_connect_option(mysql_option option, int arg); - /** - * Sets a connect option key/value pair with string argument - */ - void set_connect_option(mysql_option option, const std::string &arg); - - /** - * Deletes all stored key/value pairs of named options - */ - void clear_connect_options(); - - /** - * Create an account - * - * @param host_name Hostname to connect to - * @param user_name Username to log in with - * @param password Password for the user to log in with (may be empty) - * @param schema Database name to select on connect. Can also be set after connecting - * @param port Port of host to connect to (defaults to 3306) - * @param unix_sock Path of unix socket to connect to. If specified, host and port will be - * ignored - */ - static account_ref create(const std::string &host_name, const std::string &user_name, - const std::string &password, const std::string &schema = "", - u32 port = 3306, const std::string &unix_socket = ""); - - private: - /** - * Private account constructor - */ - account(const std::string &host_name, const std::string &user_name, const std::string &password, - const std::string &schema, u32 port, const std::string &unix_sock); - - bool m_auto_commit = true; - bool m_store_result = true; - u32 m_port; - std::string m_host_name; - std::string m_user_name; - std::string m_password; - std::string m_schema; - std::string m_unix_socket; - std::string m_ssl_key; - std::string m_ssl_certificate; - std::string m_ssl_ca; - std::string m_ssl_ca_path; - std::string m_ssl_cipher; - map_options_t m_options; - map_connect_options_t m_connect_options; -}; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/bind.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/bind.hpp deleted file mode 100644 index 58f8937..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/bind.hpp +++ /dev/null @@ -1,74 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_BIND_HPP_ -#define _MARIADB_BIND_HPP_ - -#include -#include -#include - -namespace mariadb { -class statement; -class result_set; -class bind { - friend class statement; - friend class result_set; - - public: - /** - * Construct a parameter bind - */ - explicit bind(MYSQL_BIND *mysql_bind); - - /** - * Construct a result bind for given field type - */ - bind(MYSQL_BIND *mysql_bind, MYSQL_FIELD *mysql_field); - - /* - * Disallow copying and moving of a bind: - * As the bind can set its union as the bind "buffer", copying the bind would change the address of the union - */ - bind(const bind &) = delete; - bind(bind &&) = delete; - bind &operator=(const bind &) = delete; - bind &operator=(bind &&) = delete; - - char* buffer() const; - - long unsigned int length() const; - - bool is_null() const; - - void set(enum_field_types type, const char* buffer = nullptr, unsigned long length = 0, bool us = false); - - private: - MYSQL_BIND* m_bind; - MYSQL_TIME m_time; - - my_bool m_is_null; - my_bool m_error; - - data_ref m_data; - - union { - u64 m_unsigned64; - s64 m_signed64; - s32 m_signed32[2]; - f64 m_double64; - f32 m_float32[2]; - u8 m_uchar8[4]; - }; -}; - - using bind_ref = std::unique_ptr; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/concurrency.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/concurrency.hpp deleted file mode 100644 index a928855..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/concurrency.hpp +++ /dev/null @@ -1,84 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_CONCURRENCY_HPP_ -#define _MARIADB_CONCURRENCY_HPP_ - -#include -#include -#include - -namespace mariadb { -namespace concurrency { - namespace status { - enum type { waiting, executing, succeed, failed, removed }; - } - - // - // Set account for connection - // - extern void set_account(account_ref& account); - - // - // Query status - // - extern status::type worker_status(handle h); - - // - // Execute a query - // Note: the void overloads are needed because it was too easy to "forget" passing keep_handle - // and getting an invalid handle, instead we now return void when no handle is needed - // - extern handle execute(const std::string& query, bool keep_handle); - inline void execute(const std::string& squery) { execute(squery, false); } - - extern handle insert(const std::string& query, bool keep_handle); - inline void insert(const std::string& squery) { insert(squery, false); } - - extern handle query(const std::string& query, bool keep_handle); - inline void query(const std::string& squery) { query(squery, false); } - - // - // Execute a query using a statement - // Note: the void overloads are needed because it was too easy to "forget" passing keep_handle - // and getting an invalid handle, instead we now return void when no handle is needed - // - extern statement_ref create_statement(const std::string& query); - extern handle execute(statement_ref& statement, bool keep_handle); - inline void execute(statement_ref& statement) { execute(statement, false); } - - extern handle insert(statement_ref& statement, bool keep_handle); - inline void insert(statement_ref& statement) { insert(statement, false); } - - extern handle query(statement_ref& statement, bool keep_handle); - inline void query(statement_ref& statement) { query(statement, false); } - - // - // Query executed, result ready to be used - // - extern u64 get_execute_result(handle h); - extern u64 get_insert_result(handle h); - extern result_set_ref get_query_result(handle h); - - // - // Remove a query - // - // Please note, if a result_set is used, it must be done after the result_set is used... - // - extern void release_handle(handle h); - - // - // Wait for a handle to signal - // - extern bool wait_handle(handle h, u64 wait_time_ms = 100); -} -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/connection.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/connection.hpp deleted file mode 100644 index 0de839e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/connection.hpp +++ /dev/null @@ -1,204 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_CONNECTION_HPP_ -#define _MARIADB_CONNECTION_HPP_ - -#include -#include -#include -#include -#include -#include - -#include - -namespace mariadb { -/** - * Wraps a Database connection. - */ -class connection : public last_error { - friend class result_set; - friend class statement; - friend class transaction; - friend class save_point; - - public: - /** - * Destroys connection and automatically disconnects - */ - virtual ~connection(); - - /** - * Actually connects to the database using given account, sets SSL and additional options as - * well as auto commit - * - * @return True on success - */ - bool connect(); - - /** - * Disconnects from the database - */ - void disconnect(); - - /** - * Indicates whether the connection is active. Also detects stale connections - * - * @return True on active connection - */ - bool connected() const; - - /** - * Gets the account associated with this connection - * - * @return Reference to the account - */ - account_ref account() const; - - /** - * Gets the schema (database name) - * - * @return String containing the schema - */ - const std::string& schema() const; - - /** - * Sets the schema (database name). - * The connection needs to be already established - * - * @param schema The new schema name - * @return True on success - */ - bool set_schema(const std::string& schema); - - /** - * Gets the charset associated with this connection - * - * @return String containg the charset (see documentation of MariaDB for possible values) - */ - const std::string& charset() const; - - /** - * Sets the charset. - * The connection needs to be already established - * - * @param value The new charset - * @return True on success - */ - bool set_charset(const std::string& value); - - /** - * Execute a query without interest in a result. - * The connection needs to be established. - * - * @param query SQL query to execute - * @return The number of actually affected rows. 0 on error - */ - u64 execute(const std::string& query); - - /** - * Execute a query (usually, but not limited to INSERT) with interest for the last row id. - * The connection needs to be established. - * - * @param query SQL query to execute - * @return Last row id of the inserted row. 0 on error - */ - u64 insert(const std::string& query); - - /** - * Execute a query with an result (if no result is returned, the result_set will be empty). - * The connection needs to be established. - * Note: The result is only valid as long as the connection is valid. - * - * @param query SQL query to execute - * @return Result of the query as result_set. - */ - result_set_ref query(const std::string& query); - - /** - * Gets the status of the auto_commit setting. - * - * @return True if auto_commit is enabled - */ - bool auto_commit() const; - - /** - * Sets the auto_commit setting. Default MariaDB setting is TRUE. - * The connection needs to be established. - * This setting controls the default behavior of holding all changes back until a COMMIT is - * issued. - * See MariaDB documentation for further information on this setting. - * - * @return True on success - */ - bool set_auto_commit(bool auto_commit); - - /** - * Create a prepared statement. Use "?" to issue bindings in the query which can then be filled - * in. - * For information on how to properly use prepared statements please refer to the MariaDB - * manual. - * The connection needs to be established. - * Note that "?" bindings can only be established at certain locations in a SQL statement. - * A misplaced "?" will result in an error when executing the statement. - * The statement is only valid as long as the connection is valid. - * - * @return Reference to the created statement. - */ - statement_ref create_statement(const std::string& query); - - /** - * Create a transaction. Any change to the database will be held back until you COMMIT the - * transaction. - * A not committed transaction automatically rolls all changes back on destruction. - * Note: the transaction is only valid as long as this connection is valid. - * - * @param level The level of isolation to set while using this transaction. Defaults to - * repeatable read - * @param consistent_snapshot Indicates whether to require a consistent snapshot before entering - * the transaction. - * Note: refer to MariaDB manual for further information - * - * @return Reference to the created transaction. - */ - transaction_ref create_transaction(isolation::level level = isolation::repeatable_read, - bool consistent_snapshot = true); - - /** - * Creates a new connection using the given account - * - * @param account The account used to provide the connection information - * @return Reference to the newly created connection - */ - static connection_ref create(const account_ref& account); - - private: - /** - * Private constructor used to create a connection with the given account - */ - connection(const account_ref& account); - - private: - // internal database connection pointer - MYSQL* m_mysql; - - // state of auto_commit setting - bool m_auto_commit; - // name of current schema - std::string m_schema; - // current charset - std::string m_charset; - // currently used account - account_ref m_account; -}; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/conversion_helper.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/conversion_helper.hpp deleted file mode 100644 index 03342bf..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/conversion_helper.hpp +++ /dev/null @@ -1,104 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef MARIADBCLIENTPP_CONVERSION_HELPER_H -#define MARIADBCLIENTPP_CONVERSION_HELPER_H - -#include -#include - -#ifdef WIN32 -#undef max -#undef min -#endif - -template -inline T checked_cast(K value) { - if (value < std::numeric_limits::lowest() || value > std::numeric_limits::max()) return T(); - - return static_cast(value); -} - -template -inline T string_cast(const std::string &str) { - size_t endPos; - int parsedNumber = std::stoi(str, &endPos); - - if (endPos != str.size()) return T(); - - return checked_cast(parsedNumber); -} - -template <> -inline unsigned long string_cast(const std::string &str) { - size_t endPos; - unsigned long parsedNumber = std::stoul(str, &endPos); - - if (endPos != str.size()) return 0; - - return parsedNumber; -} - -template <> -inline unsigned int string_cast(const std::string &str) { - unsigned long parsedNumber = string_cast(str); - - return checked_cast(parsedNumber); -} - -template <> -inline unsigned long long string_cast(const std::string &str) { - size_t endPos; - unsigned long long parsedNumber = std::stoull(str, &endPos); - - if (endPos != str.size()) return 0; - - return parsedNumber; -} - -template <> -inline long long string_cast(const std::string &str) { - size_t endPos; - long long parsedNumber = std::stoll(str, &endPos); - - if (endPos != str.size()) return 0; - - return parsedNumber; -} - -template <> -inline double string_cast(const std::string &str) { - size_t endPos; - try { - double parsedNumber = std::stod(str, &endPos); - - if (endPos != str.size()) return 0; - - return parsedNumber; - } catch (std::out_of_range &) { - // Not a Number double - return std::numeric_limits::quiet_NaN(); - } -} - -template <> -inline float string_cast(const std::string &str) { - size_t endPos; - try { - float parsedNumber = std::stof(str, &endPos); - - if (endPos != str.size()) return 0; - - return parsedNumber; - } catch (std::out_of_range &) { - // Not a Number float - return std::numeric_limits::quiet_NaN(); - } -} - -#endif // MARIADBCLIENTPP_CONVERSION_HELPER_H diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/data.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/data.hpp deleted file mode 100644 index f9848ff..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/data.hpp +++ /dev/null @@ -1,174 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_DATA_HPP_ -#define _MARIADB_DATA_HPP_ - -#include -#include -#include - -namespace mariadb { -template -class data { - public: - typedef Type char_type; - - // - // Constructor - // - data() : m_count(0), m_size(0), m_data(0) {} - - data(u32 count) : m_count(0), m_size(0), m_data(0) { create(count); } - - data(const Type* data, size_t count) : m_count(0), m_size(0), m_data(0) { - create(data, static_cast(count)); - } - - // - // Destructor - // - virtual ~data() { destroy(); } - - // - // Create the data - // - bool create(u32 count) { - if (m_data) destroy(); - - m_data = new Type[count]; - - if (m_data == 0) return false; - - m_count = count; - m_size = sizeof(Type) * count; - m_position = 0; - - return true; - } - - bool create(const Type* data, u32 count) { - if (create(count)) { - memcpy(m_data, data, m_size); - return true; - } - - return false; - } - - bool resize(u32 count) { - if (count > m_count) { - Type* data = new Type[count]; - - if (data == 0) return false; - - memcpy(data, m_data, m_size); - delete[] m_data; - m_data = data; - } - - m_count = count; - m_size = sizeof(Type) * count; - - return true; - } - - // - // Destroy - // - void destroy() { - if (m_data) delete[] m_data; - - m_data = NULL; - m_size = 0; - m_count = 0; - m_position = 0; - } - - // - // Convert data to a valid string - // - std::string string() const { - std::string str; - if (m_size) str.append(reinterpret_cast(m_data), m_size); - return str; - } - - // - // Get data / size - // - inline u32 size() const { return m_size; } - inline Type* get() const { return m_data; } - - // - // Operator to access the base directly - // - inline operator Type*() { return m_data; } - inline operator Type*() const { return m_data; } - - // - // Stream methods - // - std::streamsize read(char_type* buffer, std::streamsize size) { - const std::streamsize amount = static_cast(m_size - m_position); - const std::streamsize result = std::min(size, amount); - - if (result != 0) { - std::copy(m_data + m_position, m_data + m_position + result, buffer); - m_position += result; - return result; - } - - return size ? -1 : 0; - } - - std::streamsize write(char_type* buffer, std::streamsize size) { - const std::streamsize amount = static_cast(m_size - m_position); - const std::streamsize result = std::min(size, amount); - - if (result != 0) { - std::copy(buffer, buffer + result, m_data + m_position); - m_position += result; - return result; - } - - return size ? -1 : 0; - } - - std::streampos seek(std::streampos offset, std::ios_base::seekdir seekdir) { - std::streampos pos; - - if (seekdir == std::ios_base::beg) - pos = offset; - else if (seekdir == std::ios_base::cur) - pos = m_position + offset; - else if (seekdir == std::ios_base::end) - pos = m_size + offset; - else - throw std::ios_base::failure("Bad seek direction"); - - if (pos < 0 || pos > m_size) throw std::ios_base::failure("Bad seek offset"); - - m_position = static_cast(pos); - return pos; - } - - protected: - u32 m_count; - u32 m_size; - u32 m_position; - Type* m_data; -}; - -typedef std::shared_ptr< ::mariadb::data > data_ref; -typedef std::basic_iostream< ::mariadb::data > data_stream; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/date_time.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/date_time.hpp deleted file mode 100644 index dad8ba6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/date_time.hpp +++ /dev/null @@ -1,410 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2020. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_DATE_TIME_HPP_ -#define _MARIADB_DATE_TIME_HPP_ - -#include -#include - -namespace mariadb { -/** - * Class used to represent SQL date_time - */ -class date_time : public time { - public: - /** - * Construct date_time from given data. An exception will be thrown on invalid data. - * - * @param year The year to set. - * @param month The month to set. [1-12] - * @param day The day to set. Make sure it exists in the month. [1-28/39/30/31] - * @param hour The hour to set. [0-23} - * @param minute The minute to set. [0-59] - * @param second The second to set. [0-60] - * @param millisecond The millisecond to set. [0-999] - */ - date_time(u16 year = 1970, u8 month = 1, u8 day = 1, u8 hour = 0, u8 minute = 0, u8 second = 0, - u16 millisecond = 0); - - /** - * Copy constructor - * - * @param dt Datetime to copy from - */ - date_time(const date_time& dt); - - /** - * Construct date_time with given time. Sets the date to Jan, 1st of 1900 - * - * @param t Time to copy from - */ - date_time(const time& t); - - /** - * Construct date_time from tm struct. Since tm cannot represent milliseconds, none will be set. - * - * @param time_struct Struct to copy from - */ - date_time(const tm& time_struct); - - /** - * Construct date_time from given time_t. Converts the time to local timezone before setting it. - * Note that no milliseconds will be set. - * - * @param time Timetype to set. - */ - date_time(const time_t& time); - - /** - * Construct date_time from MYSQL_TIME. No milliseconds will be set. - * - * @param time MYSQL_TIME to copy from. - */ - date_time(const MYSQL_TIME& time); - - /** - * Construct date_time from ISO yyyy-mm-dd hh:mm:ss.nnn date format. Throws an exception on - * invalid input - * - * @param dt String containing ISO date - */ - date_time(const std::string& dt); - - // - // Operators - // - int compare(const date_time& dt) const; - date_time& operator=(const date_time& dt); - bool operator==(const date_time& dt) const; - bool operator!=(const date_time& dt) const; - bool operator<(const date_time& dt) const; - bool operator<=(const date_time& dt) const; - bool operator>(const date_time& dt) const; - bool operator>=(const date_time& dt) const; - - /** - * Get currently set year - * - * @return Current year - */ - u16 year() const; - - /** - * Set current year. If date becomes invalid, month and day will be reset to 1-1 - * - * @param year Year to set - * @return Newly set year - */ - u16 year(u16 year); - - /** - * Get currently set month - * - * @return Current month - */ - u8 month() const; - - /** - * Set current month. If date becomes invalid, day will be reset to 1 - * - * @param month Month to set - * @return Newly set month - */ - u8 month(u8 month); - - /** - * Get currently set day of month - * - * @return Current day - */ - u8 day() const; - - /** - * Set current day. If date becomes invalid, an exception will be thrown - * - * @param day Day to set - * @return Newly set day - */ - u8 day(u8 day); - - /** - * Calculates the day of year from current date. - * - * @return Day of year - */ - u16 day_of_year() const; - - /** - * Sets the date by calculating which date the day_of_year corresponds to. - * - * @return Day of year that was set - */ - u16 day_of_year(u16 day_of_year); - - /** - * Set only date part. Invalid dates will throw an exception - * - * @param year Year to set. - * @param month Month to set. [1-12] - * @param day Day to set. [1-28/29/30/31] - * @return True on success - */ - bool set(u16 year, u8 month, u8 day); - - /** - * Set date and time part. Invalid dates will throw an exception - * - * @param year Year to set. - * @param month Month to set. [1-12] - * @param day Day to set. [1-28/29/30/31] - * @param hour The hour to set. [0-23} - * @param minute The minute to set. [0-59] - * @param second The second to set. [0-60] - * @param millisecond The millisecond to set. [0-999] - * @return True on success - */ - bool set(u16 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond); - - /** - * Set date and time to ISO yyyy-mm-dd hh:mm:ss.nnn date format. - * Throws an exception on invalid input - * - * @param dt String containing ISO date - * @return True on success - */ - bool set(const std::string& dt) override; - - /** - * Add years to current date. - * - * @param years Number of years to add - * @return Newly created date_time containing result - */ - date_time add_years(s32 years) const; - - /** - * Add months to current date with year wrapping. - * - * @param months Number of months to add - * @return Newly created date_time containing result - */ - date_time add_months(s32 months) const; - - /** - * Add days to current date with month wrapping. - * - * @param days Number of days to add - * @return Newly created date_time containing result - */ - date_time add_days(s32 days) const; - - /** - * Add hours to current date with day wrapping. - * - * @param hours Number of hours to add - * @return Newly created date_time containing result - */ - date_time add_hours(s32 hours) const; - - /** - * Add minutes to current date with hour wrapping. - * - * @param minutes Number of minutes to add - * @return Newly created date_time containing result - */ - date_time add_minutes(s32 minutes) const; - - /** - * Add seconds to current date with minute wrapping. - * - * @param seconds Number of seconds to add - * @return Newly created date_time containing result - */ - date_time add_seconds(s32 seconds) const; - - /** - * Add milliseconds to current date with second wrapping. - * - * @param milliseconds Number of milliseconds to add - * @return Newly created date_time containing result - */ - date_time add_milliseconds(s32 milliseconds) const; - - /** - * Adds a timespan to the date_time. - * - * @param dur The duration to add - * @return Newly created date_time containing result - */ - date_time add(const time_span& dur) const; - - /** - * Subtracts a timespan from the date_time. - * - * @param dur The duration to subtract - * @return Newly created date_time containing result - */ - date_time subtract(const time_span& dur) const; - - /** - * Adds a mariadb::time to the date_time. - * - * @param t Time to add - * @return Newly created date_time containing result - */ - date_time add(const time& t) const; - - /** - * Substract a mariadb::time from the date_time. - * - * @param t Time to subtract - * @return Newly created date_time containing result - */ - date_time substract(const time& t) const; - - /** - * Calculates the time_span between this date_time and dt. If dt > this the time_span will be - * negative - * - * @param dt Datetime to calculate the timespan to - * @return Timespan representing the time between this and dt - */ - time_span time_between(const date_time& dt) const; - - /** - * Indicates whether this date is considered valid - * - * @return True if date is valid - */ - bool is_valid() const override; - - /** - * Indicates whether a given year is leap according to gregorian calendar - * - * @param year The year to check - * @return True if year is leap - */ - static bool is_leap_year(u16 year); - - /** - * Indicates whether a given date is valid in terms of existing month and day in month. Accounts - * for leap years - * - * @param year Year to check - * @param month Month to check - * @param day Day to check - * @return True if date is valid - */ - static bool valid_date(u16 year, u8 month, u8 day); - - /** - * Gets the number of days in a given year. Accounts for leap years - * - * @param year Year to check - * @return Number of days in year - */ - static u16 days_in_year(u16 year); - - /** - * Gets the number of days in a given month of a given year. Accounts for leap years - * - * @param year Year to check - * @param month Month to check - * @return Number of days in month of year - */ - static u8 days_in_month(u16 year, u8 month); - - /** - * Gets the day of year for given date. Accounts for leap years - * - * @param year Year of date - * @param month Month of date - * @param day Day of date - * @return Day of year of given date - */ - static u16 day_of_year(u16 year, u8 month, u8 day); - - /** - * Gets the date from given year and day of year - * - * @param year Year in which to position day_of_year - * @param day_of_year Position of day within the year - * @return Datetime representing the exact date - */ - static date_time reverse_day_of_year(u16 year, u16 day_of_year); - - /** - * Convert the date_time to a time_t. Precision is limited to seconds - * - * @return Timetype representing the date_time - */ - time_t mktime() const; - - /** - * Uses ::difftime to calculate number of seconds between two dates - * - * @param dt Datetime to calculate difference to - * @return Number of seconds with fractions between the two dates - */ - double diff_time(const date_time& dt) const; - - /** - * Gets only the date part of this date_time - * - * @return Datetime representing only the date part - */ - date_time date() const; - - /** - * Converts the date_time to a MYSQL_TIME. Precision is limited to seconds - * - * @return MYSQL_TIME representing this date_time - */ - MYSQL_TIME mysql_time() const; - - /** - * Gets the current date and time as date_time. Does not set milliseconds - * - * @return Current date and time in local timezone - */ - static date_time now(); - - /** - * Gets the current date and time as date_time. Does not set milliseconds - * - * @return Current date and time in UTC - */ - static date_time now_utc(); - - /** - * Converts the date and time to ISO 8601 string yyyy-mm-dd hh:mm:ss[.nnn] - * - * @param with_millisecond Controls whether or not to print optional .nnn part - * @return String containing ISO date and time - */ - const std::string str(bool with_millisecond = false) const; - - /** - * Converts only the date part of this date_time to ISO 8601 date string yyyy-mm-dd - * - * @return String containing ISO date - */ - const std::string str_date() const; - - private: - u16 m_year; - u8 m_month; - u8 m_day; -}; - -std::ostream& operator<<(std::ostream& os, const date_time& ddt); -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/decimal.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/decimal.hpp deleted file mode 100644 index e7b753f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/decimal.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_DECIMAL_HPP_ -#define _MARIADB_DECIMAL_HPP_ - -#include -#include -#include - -namespace mariadb { -class decimal { -public: - explicit decimal(std::string str = "") : mStr(std::move(str)) { } - - std::string str() const { - return mStr; - } - - f32 float32() const { - return string_cast(mStr); - } - - f64 double64() const { - return string_cast(mStr); - } - -private: - std::string mStr; -}; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/exceptions.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/exceptions.hpp deleted file mode 100644 index 81c76f1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/exceptions.hpp +++ /dev/null @@ -1,74 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_EXCEPTIONS_HPP_ -#define _MARIADB_EXCEPTIONS_HPP_ - -#include -#include - -namespace mariadb { -namespace exception { -class base : public std::exception { - public: - // - // Constructor - // - base() throw() : std::exception(), m_error_id(0), m_error("Exception not defined") {} - - base(u32 error_id, const std::string& error) throw() - : std::exception(), m_error_id(error_id), m_error(error) {} - - base(const std::string& error) throw() : std::exception(), m_error_id(0), m_error(error) {} - - // - // Destructor - // - virtual ~base() throw() {} - - // - // Methods - // - virtual const char* what() const throw() { return m_error.c_str(); } - - u32 error_id() const throw() { return m_error_id; } - - protected: - u32 m_error_id; - std::string m_error; -}; - -class date_time : public base { - public: - // - // Constructors - // - date_time(u16 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond) throw(); -}; - -class time : public base { - public: - // - // Constructors - // - time(u8 hour, u8 minute, u8 second, u16 millisecond) throw(); -}; - -class connection : public base { - public: - // - // Constructor - // - connection(u32 error_id, const std::string& error) throw() : base(error_id, error) {} -}; -} -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/last_error.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/last_error.hpp deleted file mode 100644 index fe81b79..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/last_error.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_LAST_ERROR_HPP_ -#define _MARIADB_LAST_ERROR_HPP_ - -#include -#include "types.hpp" - -namespace mariadb { -class last_error { - public: - // - // Constructor - // - last_error(); - - // - // Get last error - // - u32 error_no() const; - const std::string& error() const; - - protected: - u32 m_last_error_no; - std::string m_last_error; -}; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/result_set.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/result_set.hpp deleted file mode 100644 index d3baf70..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/result_set.hpp +++ /dev/null @@ -1,222 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_RESULT_SET_HPP_ -#define _MARIADB_RESULT_SET_HPP_ - -#include -#include -#include -#include -#include -#include -#include - -#define MAKE_GETTER_SIG_STR(nm, rtype, fq) rtype fq get_##nm(const std::string& name) const -#define MAKE_GETTER_SIG_INT(nm, rtype, fq) rtype fq get_##nm(u32 index) const - -#define MAKE_GETTER_DECL(nm, rtype) \ - MAKE_GETTER_SIG_STR(nm, rtype, ); \ - MAKE_GETTER_SIG_INT(nm, rtype, ) - -#define MAKE_GETTER(nm, rtype, vtype) \ - MAKE_GETTER_SIG_STR(nm, rtype, result_set::) { return get_##nm(column_index(name)); } \ - MAKE_GETTER_SIG_INT(nm, rtype, result_set::) { \ - check_row_fetched(); \ - check_type(index, vtype); \ - \ - if (index >= m_field_count) throw std::out_of_range("Column index out of range"); - -namespace mariadb { -class connection; -class statement; - -/* - * This data is shared between a statement and its result_set, - * therefore it needs to be destroyed only when - * - the statement is freed - * - all of the result_sets are freed - * - * A shared_ptr is used to keep the data alive in the statement and the result_set. - */ -struct statement_data { - explicit statement_data(MYSQL_STMT* stmt) : m_statement(stmt) {} - - ~statement_data(); - - // number of binds in this query - unsigned long m_bind_count = 0; - // pointer to underlying statement - MYSQL_STMT* m_statement; - // pointer to raw binds - MYSQL_BIND* m_raw_binds = nullptr; - // pointer to managed binds - std::vector m_binds; -}; - -typedef std::shared_ptr statement_data_ref; - -/** - * Class used to store query and statement results - */ -class result_set : public last_error { - friend class connection; - friend class statement; - - typedef std::map map_indexes_t; - - public: - /** - * Destructs the result_set and frees all result data - */ - virtual ~result_set(); - - /** - * Get the count of columns contained in this result_set - * - * @return Count of columns - */ - u32 column_count() const; - - /** - * Get the index of a column by column-name (case sensitive) - * - * @param name Name of column to look up - * @return Index of column if found, maximum uint32 if not found - */ - u32 column_index(const std::string& name) const; - - /** - * Gets the type of a column by index - * - * @param index Index of the column to examine - * @return Type enum indicating column type - */ - value::type column_type(u32 index) const; - - /** - * Gets the name of a column by index - * - * @param index Index of the column to get the name for - * @return String representing column name - */ - const std::string column_name(u32 index); - - /** - * Gets the size of the data contained in the column at index - * - * @param index Index of the column to get the size for - * @return Size of the column contents for the currently active row - */ - unsigned long column_size(u32 index) const; - - /** - * Gets the row index of the currently selected row - * - * @return Index of current row - */ - u64 row_index() const; - - /** - * Gets the number of rows in this result - * - * @return Number of rows in result_set - */ - u64 row_count() const; - - /** - * Fetch next row from result_set - * - * @return True if next row exists - */ - bool next(); - - /** - * Set the current row index in result_set (seek to result). - * Also immediately fetches the selected row. - * - * @param index Index of row to select - * @return True if row could be seeked to and fetched. - */ - bool set_row_index(u64 index); - - // declare all getters - MAKE_GETTER_DECL(blob, stream_ref); - MAKE_GETTER_DECL(data, data_ref); - MAKE_GETTER_DECL(date, date_time); - MAKE_GETTER_DECL(date_time, date_time); - MAKE_GETTER_DECL(time, time); - MAKE_GETTER_DECL(decimal, decimal); - MAKE_GETTER_DECL(string, std::string); - MAKE_GETTER_DECL(boolean, bool); - MAKE_GETTER_DECL(unsigned8, u8); - MAKE_GETTER_DECL(signed8, s8); - MAKE_GETTER_DECL(unsigned16, u16); - MAKE_GETTER_DECL(signed16, s16); - MAKE_GETTER_DECL(unsigned32, u32); - MAKE_GETTER_DECL(signed32, s32); - MAKE_GETTER_DECL(unsigned64, u64); - MAKE_GETTER_DECL(signed64, s64); - MAKE_GETTER_DECL(float, f32); - MAKE_GETTER_DECL(double, f64); - MAKE_GETTER_DECL(is_null, bool); - - private: - /** - * Create result_set from connection - */ - explicit result_set(connection* conn); - - /** - * Create result_set from statement - */ - explicit result_set(connection* conn, const statement_data_ref& stmt); - - /** - * Throws if the result set was created, but no row was ever fetched (using next()) - */ - void check_row_fetched() const; - - /** - * Throws if the actual type of column at index cannot be converted to the requested type - * - * @param index Index of column to check - * @param requested Requested type - */ - void check_type(u32 index, value::type requested) const; - - // pointer to result set - MYSQL_RES* m_result_set; - // pointer to array of fields - MYSQL_FIELD* m_fields; - // pointer to current row - MYSQL_ROW m_row; - // pointer to raw binds - MYSQL_BIND* m_raw_binds; - - // vector of managed binds - std::vector m_binds; - // optional pointer to statement - statement_data_ref m_stmt_data; - // map caching column name by index - map_indexes_t m_indexes; - // array of content lengths for the columns of current row - long unsigned int* m_lengths; - - // count of fields per row - u32 m_field_count; - // indicates if a row was fetched using next() - bool m_was_fetched; -}; - -typedef std::shared_ptr result_set_ref; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/save_point.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/save_point.hpp deleted file mode 100644 index 9c0be61..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/save_point.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_SAVE_POINT_HPP_ -#define _MARIADB_SAVE_POINT_HPP_ - -#include - -namespace mariadb { -class connection; -class transaction; - -/** - * Class used to represent a MariaDB savepoint having automatic rollback functionality - */ -class save_point { - friend class connection; - friend class transaction; - - public: - /** - * Destructor initiates automatic rollback if changes were not committed - */ - virtual ~save_point(); - - /** - * Commits the changes and releases savepoint - */ - void commit(); - - private: - /** - * Create save_point with given transaction - */ - save_point(transaction* trans); - - private: - // internal transaction pointer - transaction* m_transaction; - // distinct name of the current save_pointS - std::string m_name; -}; - -typedef std::shared_ptr save_point_ref; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/statement.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/statement.hpp deleted file mode 100644 index 09f421f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/statement.hpp +++ /dev/null @@ -1,112 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_STATEMENT_HPP_ -#define _MARIADB_STATEMENT_HPP_ - -#include -#include - -#define MAKE_SETTER_SIG(nm, type, fq) void fq set_##nm(u32 index, type value) - -#define MAKE_SETTER_DECL(nm, type) MAKE_SETTER_SIG(nm, type, ) - -#define MAKE_SETTER_BODY \ - if (index >= m_data->m_bind_count) throw std::out_of_range("Field index out of range"); \ - \ - bind& bind = *m_data->m_binds.at(index); - -#define MAKE_SETTER(nm, type) \ - MAKE_SETTER_SIG(nm, type, statement::) { \ - MAKE_SETTER_BODY - -namespace mariadb { -class connection; -class worker; -class result_set; -typedef std::shared_ptr connection_ref; - -/** - * Class representing a prepared statement with binding functionality - */ -class statement : public last_error { - friend class connection; - friend class result_set; - friend class worker; - - public: - statement() = delete; - - /** - * Execute the query and return the number of rows affected - * - * @return Number of rows affected or zero on error - */ - u64 execute(); - - /** - * Execute the query and return the last insert id - * - * @return Last insert ID or zero on error - */ - u64 insert(); - - /** - * Execute the query and return a result set - * - * @return Result set containing a result or an empty set on error - */ - result_set_ref query(); - - /** - * Set connection ref, used by concurrency - */ - void set_connection(connection_ref& connection); - - // declare all setters - MAKE_SETTER_DECL(blob, stream_ref); - MAKE_SETTER_DECL(date_time, const date_time&); - MAKE_SETTER_DECL(date, const date_time&); - MAKE_SETTER_DECL(time, const time&); - MAKE_SETTER_DECL(data, const data_ref&); - MAKE_SETTER_DECL(decimal, const decimal&); - MAKE_SETTER_DECL(string, const std::string&); - MAKE_SETTER_DECL(boolean, bool); - MAKE_SETTER_DECL(unsigned8, u8); - MAKE_SETTER_DECL(signed8, s8); - MAKE_SETTER_DECL(unsigned16, u16); - MAKE_SETTER_DECL(signed16, s16); - MAKE_SETTER_DECL(unsigned32, u32); - MAKE_SETTER_DECL(signed32, s32); - MAKE_SETTER_DECL(unsigned64, u64); - MAKE_SETTER_DECL(signed64, s64); - MAKE_SETTER_DECL(float, f32); - MAKE_SETTER_DECL(double, f64); - void set_null(u32 index); - - private: - /** - * Private constructor used by connection - */ - statement(connection* conn, const std::string& query); - - private: - // reference to parent connection - connection_ref m_connection; - // non-owning pointer to parent connection - connection *m_parent; - // reference to internal data, shared with all results - statement_data_ref m_data; -}; - -typedef std::shared_ptr statement_ref; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/time.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/time.hpp deleted file mode 100644 index c0f83e1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/time.hpp +++ /dev/null @@ -1,316 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2020. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_TIME_HPP_ -#define _MARIADB_TIME_HPP_ - -#include -#include - -#include - -namespace mariadb { -/** - * Class representing SQL time - */ -class time { - public: - /** - * Construct time using given values - * - * @param hour Hours 0-23 - * @param minute Minutes 0-59 - * @param second Seconds 0-61 (for leap seconds) - * @param millisecond Milliseconds 0-999 - */ - time(u8 hour = 0, u8 minute = 0, u8 second = 0, u16 millisecond = 0); - - /** - * Copy constructor - * - * @param t Time to copy from - */ - time(const time& t); - - /** - * Construct time from time.h functions - * - * @param time_struct Timestruct to copy from - */ - time(const tm& time_struct); - - /** - * Construct time from time.h functions - * - * @param time Timestruct to copy from - */ - time(const time_t& time); - - /** - * Construct time from SQL time - * - * @param time SQL time to copy from - */ - time(const MYSQL_TIME& time); - - /** - * Construct time from string - * The format needs to be hh[:mm][:ss][:nnn] - * where less digits are possible and the delimiter may be any non digit - * - * @param t String containing time representation - */ - time(const std::string& t); - - /** - * Allow proper destruction in derived classes - */ - virtual ~time() = default; - - /** - * Compare this instance to given instance - * - * @param t Time to compare to - * @return 1 if this instance is greater, -1 if t is greater, 0 on equality - */ - int compare(const time& t) const; - - /** - * Assigns a value to this instance - */ - time& operator=(const time& t); - - /** - * Checks for equality - */ - bool operator==(const time& t) const; - - /** - * Checks for unequality - */ - bool operator!=(const time& t) const; - - /** - * Checks if this instance is lesser than t - */ - bool operator<(const time& t) const; - - /** - * Checks if this instance is lesser or equal to t - */ - bool operator<=(const time& t) const; - - /** - * Checks if this instance is greater than t - */ - bool operator>(const time& t) const; - - /** - * Checks if this instance is greater or equal to t - */ - bool operator>=(const time& t) const; - - /** - * Get the current hour 0-23 - */ - u8 hour() const; - - /** - * Set the current hour 0-23 - */ - u8 hour(u8 hour); - - /** - * Get the current minute 0-59 - */ - u8 minute() const; - - /** - * Set the current minute 0-59 - */ - u8 minute(u8 minute); - - /** - * Get the current second 0-61 (leap second possible) - */ - u8 second() const; - - /** - * Set the current second 0-61 (leap second possible) - */ - u8 second(u8 second); - - /** - * Get the current millisecond 0-999 - */ - u16 millisecond() const; - - /** - * Set the current millisecond 0-999 - */ - u16 millisecond(u16 millisecond); - - /** - * Set the time from string - * The format needs to be hh[:mm][:ss][.nnn] - * where less digits are possible and the delimiter may be any non digit - * - * Examples: - * h - * h:mm.s?n - * hh,mm!ss-n - * - * @return True on success - */ - virtual bool set(const std::string& t); - - /** - * Set the time from given values - * - * @param hour Hour to set - * @param minute Minute to set - * @param second Second to set - * @param millisecond Milliseconds to set - * @return True on success - */ - bool set(u8 hour, u8 minute, u8 second, u16 millisecond); - - /** - * Adds a certain amount of hours to the current time. Negative values subtract hours - * - * @param hours Number of hours to add - * @return Time containing sum - */ - time add_hours(s32 hours) const; - - /** - * Adds a certain amount of minutes to the current time. Negative values subtract minutes - * - * @param minutes Number of minutes to add - * @return Time containing sum - */ - time add_minutes(s32 minutes) const; - - /** - * Adds a certain amount of seconds to the current time. Negative values subtract seconds - * - * @param minutes Number of seconds to add - * @return Time containing sum - */ - time add_seconds(s32 seconds) const; - - /** - * Adds a certain amount of milliseconds to the current time. Negative values subtract - * milliseconds - * - * @param minutes Number of milliseconds to add - * @return Time containing sum - */ - time add_milliseconds(s32 milliseconds) const; - - /** - * Subtracts the given timespan from the current time - * - * @param dur A duration to subtract - * @return Time containing result - */ - time subtract(const time_span& dur) const; - - /** - * Adds the given timespan to the current time - * - * @param dur A duration to add - * @return Time containing sum - */ - time add(const time_span& dur) const; - - /** - * Calculates the timespan between the current time instance and given instance t - * - * @param t Time to calculate the duration between - * @return Timespan containing the duration - */ - time_span time_between(const time& t) const; - - /** - * Converts the time to time_t (time.h representation) - * - * @return Time as time.h time_t - */ - time_t mktime() const; - - /** - * Calculates the time difference using ::difftime. - * Calculates (this - t) - * - * @return Difference in seconds as double - */ - double diff_time(const time& t) const; - - /** - * Indicates whether this time is considered valid - * - * @return True if time is valid - */ - virtual bool is_valid() const; - - /** - * Indicates whether a given time is valid in terms of limits. Accounts for leap seconds - * - * @param hour Hour to check - * @param minute Minute to check - * @param second Second to check - * @param millisecond Milliseconds to check - * @return True if valid - */ - static bool valid_time(u8 hour, u8 minute, u8 second, u16 millisecond); - - /** - * Converts the time to MySQL time representation. Note that MySQL time does not support - * milliseconds - * - * @return Time as MYSQL_TIME with no milliseconds - */ - MYSQL_TIME mysql_time() const; - - /** - * Converts the time to a string with the format hh:mm:ss[.nnn] - * - * @param with_millisecond Indicates if milliseconds should be printed or not. - * - * @return String representing time with optional milliseconds - */ - const std::string str_time(bool with_millisecond = false) const; - - /** - * Uses time.h to determine the current time in the local timezone. - * - * @return Time representing now - */ - static time now(); - - /** - * Uses time.h to determine the current time in UTC timezone. - * - * @return Time representing now in UTC - */ - static time now_utc(); - - protected: - u8 m_hour; - u8 m_minute; - u8 m_second; - u16 m_millisecond; -}; - -std::ostream& operator<<(std::ostream& os, const time& t); -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/time_span.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/time_span.hpp deleted file mode 100644 index bbbb5f1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/time_span.hpp +++ /dev/null @@ -1,204 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_TIME_SPAN_HPP_ -#define _MARIADB_TIME_SPAN_HPP_ - -#include -#include - -namespace mariadb { -class time_span { - public: - /** - * Construct time_span from given data. Note that a time_span can span one day at most. - * - * @param hours Number of hours 0-23 - * @param minutes Number of minutes 0-59 - * @param seconds Number of seconds 0-59 - * @param milliseconds Number of milliseconds 0-999 - * @param negative Indicates negative timespan - */ - time_span(u32 days = 0, u8 hours = 0, u8 minutes = 0, u8 seconds = 0, u16 milliseconds = 0, - bool negative = false); - - /** - * Copy constructor - * - * @param dur Timespan to copy from - */ - time_span(const time_span& dur); - - /** - * Compares this timespan with the given timespan. - * - * @param rhs Timespan to compare this to - * @return 1 if this is greater, 0 if equal, -1 if this is smaller - */ - int compare(const time_span& rhs) const; - - time_span& operator=(const time_span& rhs); - bool operator==(const time_span& rhs) const; - bool operator!=(const time_span& rhs) const; - bool operator<(const time_span& rhs) const; - bool operator<=(const time_span& rhs) const; - bool operator>(const time_span& rhs) const; - bool operator>=(const time_span& rhs) const; - - /** - * Set the value of this time_span to given values - * - * @param days Any number of days - * @param hours Number of hours 0-23 - * @param minutes Number of minutes 0-59 - * @param seconds Number of seconds 0-59 - * @param milliseconds Number of milliseconds 0-999 - * @param negative Indicates negative timespan - */ - void set(u32 days = 0, u8 hours = 0, u8 minutes = 0, u8 seconds = 0, u16 milliseconds = 0, - bool negative = false); - - /** - * Indicates whether this time_span is zero. That is only true if all components are zero - * - * @return True if zero - */ - bool zero() const; - - /** - * Indicates whether this time_span is negative. - * - * @return True if negative - */ - bool negative() const; - - /** - * Sets negative flag on this time_span - * - * @param negative Value to set - * @return Newly set value - */ - bool negative(bool negative); - - /** - * Get number of days - * - * @return Number of days - */ - u32 days() const; - - /** - * Sets the number of days - * - * @param hour Number of days to set - * @return Newly set value - */ - u32 days(u32 day); - - /** - * Get number of hours - * - * @return Number of hours - */ - u8 hours() const; - - /** - * Sets the number of hours - * - * @param hour Number of hours to set - * @return Newly set value - */ - u8 hours(u8 hour); - - /** - * Get number of hours - * - * @return Number of hours - */ - u8 minutes() const; - - /** - * Sets the number of minutes - * - * @param minute Number of minutes to set - * @return Newly set value - */ - u8 minutes(u8 minute); - - /** - * Get number of seconds - * - * @return Number of seconds - */ - u8 seconds() const; - - /** - * Sets the number of seconds - * - * @param second Number of seconds to set - * @return Newly set value - */ - u8 seconds(u8 second); - - /** - * Get number of milliseconds - * - * @return Number of milliseconds - */ - u16 milliseconds() const; - - /** - * Sets the number of milliseconds - * - * @param millisecond Number of milliseconds to set - * @return Newly set value - */ - u16 milliseconds(u16 millisecond); - - /** - * Converts the time_span to minutes - * - * @return Total number of minutes in this time_span - */ - u64 total_hours() const; - - /** - * Converts the time_span to minutes - * - * @return Total number of minutes in this time_span - */ - u64 total_minutes() const; - - /** - * Converts the time_span to seconds - * - * @return Total number of seconds in this time_span - */ - u64 total_seconds() const; - - /** - * Converts the time_span to milliseconds - * - * @return Total number of milliseconds in this time_span - */ - u64 total_milliseconds() const; - - private: - bool m_negative = false; - u32 m_days = 0; - u8 m_hours = 0; - u8 m_minutes = 0; - u8 m_seconds = 0; - u16 m_milliseconds = 0; -}; - -std::ostream& operator<<(std::ostream& os, const time_span& ts); -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/transaction.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/transaction.hpp deleted file mode 100644 index f44b875..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/transaction.hpp +++ /dev/null @@ -1,81 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_TRANSACTION_HPP_ -#define _MARIADB_TRANSACTION_HPP_ - -#include -#include -#include -#include - -namespace mariadb { -class connection; -class save_point; - -/** - * Class representing a SQL transaction having automatic rollback functionality - */ -class transaction { - friend class connection; - friend class save_point; - - public: - /** - * Destructor initiates automatic rollback if changes were not committed - */ - virtual ~transaction(); - - /** - * Commits the changes, releases all savepoints - */ - void commit(); - - /** - * Create named savepoint - * Note: only valid until the transaction is destroyed or committed - * - * @return Reference to a unique new savepoint - */ - save_point_ref create_save_point(); - - private: - /** - * Create a transaction with given isolation level and snapshot setting - * - * @param conn Connection to start transaction on - * @param level Level of database isolation to use - * @param consistent_snapshot Controls whether the transaction needs a consistent snapshot on - * creation - */ - transaction(connection* conn, isolation::level level, bool consistent_snapshot); - - /** - * Removes a savepoint from the list of savepoints - * - * @param sv_point savepoint to remove - */ - void remove_save_point(save_point* sv_point); - - /** - * Cleans up the transaction, releases all savepoints - */ - void cleanup(); - - private: - // parent connection pointer - connection* m_connection; - // list of created savepoints for this transaction - std::vector m_save_points; -}; - -typedef std::shared_ptr transaction_ref; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mariadb++/types.hpp b/VCMP-LUA/modules/mariadb/include/mariadb++/types.hpp deleted file mode 100644 index 2abe393..0000000 --- a/VCMP-LUA/modules/mariadb/include/mariadb++/types.hpp +++ /dev/null @@ -1,86 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_TYPES_HPP_ -#define _MARIADB_TYPES_HPP_ - -#include -#include - -namespace mariadb { - // - // Default types - // - typedef unsigned char u8; - typedef unsigned short u16; - typedef unsigned int u32; - typedef signed char s8; - typedef signed short s16; - typedef signed int s32; - typedef float f32; - typedef double f64; - typedef long double f128; - - #if defined(_MSC_VER) || defined(__BORLANDC__) - typedef unsigned __int64 u64; - typedef signed __int64 s64; - #else - typedef unsigned long long u64; - typedef signed long long s64; - #endif - - typedef u64 handle; - - // - // Value type - // - namespace value { - enum type { - null = 0, - blob, - data, - date, - date_time, - time, - string, - boolean, - decimal, - unsigned8, - signed8, - unsigned16, - signed16, - unsigned32, - signed32, - unsigned64, - signed64, - float32, - double64, - enumeration - }; - } - - // - // Isolation level - // - namespace isolation { - enum level { repeatable_read = 0, read_committed, read_uncommitted, serializable }; - } - - // - // Stream - // - typedef std::shared_ptr stream_ref; -} - -#if !defined(MARIADB_BASE_VERSION) && MYSQL_VERSION_ID > 80000 -// Assume MySQL Community 8.0+ -typedef bool my_bool; -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/errmsg.h b/VCMP-LUA/modules/mariadb/include/mysql/errmsg.h deleted file mode 100644 index 7ca3238..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/errmsg.h +++ /dev/null @@ -1,107 +0,0 @@ -/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB - 2012-2016 SkySQL AB, MariaDB Corporation AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ - -/* Error messages for mysql clients */ -/* error messages for the demon is in share/language/errmsg.sys */ -#ifndef _errmsg_h_ -#define _errmsg_h_ - -#ifdef __cplusplus -extern "C" { -#endif -void init_client_errs(void); -extern const char *client_errors[]; /* Error messages */ -extern const char *mariadb_client_errors[]; /* Error messages */ -#ifdef __cplusplus -} -#endif - - - -#define CR_MIN_ERROR 2000 /* For easier client code */ -#define CR_MAX_ERROR 2999 -#define CER_MIN_ERROR 5000 -#define CER_MAX_ERROR 5999 -#define CER(X) mariadb_client_errors[(X)-CER_MIN_ERROR] -#define ER(X) client_errors[(X)-CR_MIN_ERROR] -#define CLIENT_ERRMAP 2 /* Errormap used by ma_error() */ - -#define CR_UNKNOWN_ERROR 2000 -#define CR_SOCKET_CREATE_ERROR 2001 -#define CR_CONNECTION_ERROR 2002 -#define CR_CONN_HOST_ERROR 2003 /* never sent to a client, message only */ -#define CR_IPSOCK_ERROR 2004 -#define CR_UNKNOWN_HOST 2005 -#define CR_SERVER_GONE_ERROR 2006 /* disappeared _between_ queries */ -#define CR_VERSION_ERROR 2007 -#define CR_OUT_OF_MEMORY 2008 -#define CR_WRONG_HOST_INFO 2009 -#define CR_LOCALHOST_CONNECTION 2010 -#define CR_TCP_CONNECTION 2011 -#define CR_SERVER_HANDSHAKE_ERR 2012 -#define CR_SERVER_LOST 2013 /* disappeared _during_ a query */ -#define CR_COMMANDS_OUT_OF_SYNC 2014 -#define CR_NAMEDPIPE_CONNECTION 2015 -#define CR_NAMEDPIPEWAIT_ERROR 2016 -#define CR_NAMEDPIPEOPEN_ERROR 2017 -#define CR_NAMEDPIPESETSTATE_ERROR 2018 -#define CR_CANT_READ_CHARSET 2019 -#define CR_NET_PACKET_TOO_LARGE 2020 -#define CR_SSL_CONNECTION_ERROR 2026 -#define CR_MALFORMED_PACKET 2027 -#define CR_NO_PREPARE_STMT 2030 -#define CR_PARAMS_NOT_BOUND 2031 -#define CR_INVALID_PARAMETER_NO 2034 -#define CR_INVALID_BUFFER_USE 2035 -#define CR_UNSUPPORTED_PARAM_TYPE 2036 - -#define CR_SHARED_MEMORY_CONNECTION 2037 -#define CR_SHARED_MEMORY_CONNECT_ERROR 2038 - -#define CR_CONN_UNKNOWN_PROTOCOL 2047 -#define CR_SECURE_AUTH 2049 -#define CR_NO_DATA 2051 -#define CR_NO_STMT_METADATA 2052 -#define CR_NOT_IMPLEMENTED 2054 -#define CR_SERVER_LOST_EXTENDED 2055 /* never sent to a client, message only */ -#define CR_STMT_CLOSED 2056 -#define CR_NEW_STMT_METADATA 2057 -#define CR_ALREADY_CONNECTED 2058 -#define CR_AUTH_PLUGIN_CANNOT_LOAD 2059 -#define CR_DUPLICATE_CONNECTION_ATTR 2060 -#define CR_AUTH_PLUGIN_ERR 2061 -/* Always last, if you add new error codes please update the - value for CR_MYSQL_LAST_ERROR */ -#define CR_MYSQL_LAST_ERROR CR_AUTH_PLUGIN_ERR - -/* - * MariaDB Connector/C errors: - */ -#define CR_EVENT_CREATE_FAILED 5000 -#define CR_BIND_ADDR_FAILED 5001 -#define CR_ASYNC_NOT_SUPPORTED 5002 -#define CR_FUNCTION_NOT_SUPPORTED 5003 -#define CR_FILE_NOT_FOUND 5004 -#define CR_FILE_READ 5005 -#define CR_BULK_WITHOUT_PARAMETERS 5006 -#define CR_INVALID_STMT 5007 -#define CR_VERSION_MISMATCH 5008 -/* Always last, if you add new error codes please update the - value for CR_MARIADB_LAST_ERROR */ -#define CR_MARIADB_LAST_ERROR CR_VERSION_MISMATCH -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/ma_list.h b/VCMP-LUA/modules/mariadb/include/mysql/ma_list.h deleted file mode 100644 index ccd2bbd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/ma_list.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ - -#ifndef _list_h_ -#define _list_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct st_list { - struct st_list *prev,*next; - void *data; -} LIST; - -typedef int (*list_walk_action)(void *,void *); - -extern LIST *list_add(LIST *root,LIST *element); -extern LIST *list_delete(LIST *root,LIST *element); -extern LIST *list_cons(void *data,LIST *root); -extern LIST *list_reverse(LIST *root); -extern void list_free(LIST *root,unsigned int free_data); -extern unsigned int list_length(LIST *list); -extern int list_walk(LIST *list,list_walk_action action,char * argument); - -#define list_rest(a) ((a)->next) -#define list_push(a,b) (a)=list_cons((b),(a)) -#define list_pop(A) do {LIST *old=(A); (A)=list_delete(old,old) ; ma_free((char *) old,MYF(MY_FAE)); } while(0) - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/ma_pvio.h b/VCMP-LUA/modules/mariadb/include/mysql/ma_pvio.h deleted file mode 100644 index 05a0748..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/ma_pvio.h +++ /dev/null @@ -1,139 +0,0 @@ -#ifndef _ma_pvio_h_ -#define _ma_pvio_h_ -#define cio_defined - -#ifdef HAVE_TLS -#include -#else -#define MARIADB_TLS void -#endif - -/* CONC-492: Allow to buuld plugins outside of MariaDB Connector/C - source tree wnen ma_global.h was not included. */ -#if !defined(_global_h) && !defined(MY_GLOBAL_INCLUDED) -typedef unsigned char uchar; -#endif - -#define PVIO_SET_ERROR if (pvio->set_error) \ - pvio->set_error - -#define PVIO_READ_AHEAD_CACHE_SIZE 16384 -#define PVIO_READ_AHEAD_CACHE_MIN_SIZE 2048 -#define PVIO_EINTR_TRIES 2 - -struct st_ma_pvio_methods; -typedef struct st_ma_pvio_methods PVIO_METHODS; - -#define IS_PVIO_ASYNC(a) \ - ((a)->mysql && (a)->mysql->options.extension && (a)->mysql->options.extension->async_context) - -#define IS_PVIO_ASYNC_ACTIVE(a) \ - (IS_PVIO_ASYNC(a)&& (a)->mysql->options.extension->async_context->active) - -#define IS_MYSQL_ASYNC(a) \ - ((a)->options.extension && (a)->options.extension->async_context) - -#define IS_MYSQL_ASYNC_ACTIVE(a) \ - (IS_MYSQL_ASYNC(a)&& (a)->options.extension->async_context->active) - -enum enum_pvio_timeout { - PVIO_CONNECT_TIMEOUT= 0, - PVIO_READ_TIMEOUT, - PVIO_WRITE_TIMEOUT -}; - -enum enum_pvio_io_event -{ - VIO_IO_EVENT_READ, - VIO_IO_EVENT_WRITE, - VIO_IO_EVENT_CONNECT -}; - -enum enum_pvio_type { - PVIO_TYPE_UNIXSOCKET= 0, - PVIO_TYPE_SOCKET, - PVIO_TYPE_NAMEDPIPE, - PVIO_TYPE_SHAREDMEM, -}; - -enum enum_pvio_operation { - PVIO_READ= 0, - PVIO_WRITE=1 -}; - -#define SHM_DEFAULT_NAME "MYSQL" - -struct st_pvio_callback; - -typedef struct st_pvio_callback { - void (*callback)(MYSQL *mysql, uchar *buffer, size_t size); - struct st_pvio_callback *next; -} PVIO_CALLBACK; - -struct st_ma_pvio { - void *data; - /* read ahead cache */ - uchar *cache; - uchar *cache_pos; - size_t cache_size; - enum enum_pvio_type type; - int timeout[3]; - int ssl_type; /* todo: change to enum (ssl plugins) */ - MARIADB_TLS *ctls; - MYSQL *mysql; - PVIO_METHODS *methods; - void (*set_error)(MYSQL *mysql, unsigned int error_nr, const char *sqlstate, const char *format, ...); - void (*callback)(MARIADB_PVIO *pvio, my_bool is_read, const uchar *buffer, size_t length); -}; - -typedef struct st_ma_pvio_cinfo -{ - const char *host; - const char *unix_socket; - int port; - enum enum_pvio_type type; - MYSQL *mysql; -} MA_PVIO_CINFO; - -struct st_ma_pvio_methods -{ - my_bool (*set_timeout)(MARIADB_PVIO *pvio, enum enum_pvio_timeout type, int timeout); - int (*get_timeout)(MARIADB_PVIO *pvio, enum enum_pvio_timeout type); - ssize_t (*read)(MARIADB_PVIO *pvio, uchar *buffer, size_t length); - ssize_t (*async_read)(MARIADB_PVIO *pvio, uchar *buffer, size_t length); - ssize_t (*write)(MARIADB_PVIO *pvio, const uchar *buffer, size_t length); - ssize_t (*async_write)(MARIADB_PVIO *pvio, const uchar *buffer, size_t length); - int (*wait_io_or_timeout)(MARIADB_PVIO *pvio, my_bool is_read, int timeout); - int (*blocking)(MARIADB_PVIO *pvio, my_bool value, my_bool *old_value); - my_bool (*connect)(MARIADB_PVIO *pvio, MA_PVIO_CINFO *cinfo); - my_bool (*close)(MARIADB_PVIO *pvio); - int (*fast_send)(MARIADB_PVIO *pvio); - int (*keepalive)(MARIADB_PVIO *pvio); - my_bool (*get_handle)(MARIADB_PVIO *pvio, void *handle); - my_bool (*is_blocking)(MARIADB_PVIO *pvio); - my_bool (*is_alive)(MARIADB_PVIO *pvio); - my_bool (*has_data)(MARIADB_PVIO *pvio, ssize_t *data_len); - int(*shutdown)(MARIADB_PVIO *pvio); -}; - -/* Function prototypes */ -MARIADB_PVIO *ma_pvio_init(MA_PVIO_CINFO *cinfo); -void ma_pvio_close(MARIADB_PVIO *pvio); -ssize_t ma_pvio_cache_read(MARIADB_PVIO *pvio, uchar *buffer, size_t length); -ssize_t ma_pvio_read(MARIADB_PVIO *pvio, uchar *buffer, size_t length); -ssize_t ma_pvio_write(MARIADB_PVIO *pvio, const uchar *buffer, size_t length); -int ma_pvio_get_timeout(MARIADB_PVIO *pvio, enum enum_pvio_timeout type); -my_bool ma_pvio_set_timeout(MARIADB_PVIO *pvio, enum enum_pvio_timeout type, int timeout); -int ma_pvio_fast_send(MARIADB_PVIO *pvio); -int ma_pvio_keepalive(MARIADB_PVIO *pvio); -my_socket ma_pvio_get_socket(MARIADB_PVIO *pvio); -my_bool ma_pvio_is_blocking(MARIADB_PVIO *pvio); -my_bool ma_pvio_blocking(MARIADB_PVIO *pvio, my_bool block, my_bool *previous_mode); -my_bool ma_pvio_is_blocking(MARIADB_PVIO *pvio); -int ma_pvio_wait_io_or_timeout(MARIADB_PVIO *pvio, my_bool is_read, int timeout); -my_bool ma_pvio_connect(MARIADB_PVIO *pvio, MA_PVIO_CINFO *cinfo); -my_bool ma_pvio_is_alive(MARIADB_PVIO *pvio); -my_bool ma_pvio_get_handle(MARIADB_PVIO *pvio, void *handle); -my_bool ma_pvio_has_data(MARIADB_PVIO *pvio, ssize_t *length); - -#endif /* _ma_pvio_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/ma_tls.h b/VCMP-LUA/modules/mariadb/include/mysql/ma_tls.h deleted file mode 100644 index 9ce49e7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/ma_tls.h +++ /dev/null @@ -1,161 +0,0 @@ -#ifndef _ma_tls_h_ -#define _ma_tls_h_ - -enum enum_pvio_tls_type { - SSL_TYPE_DEFAULT=0, -#ifdef _WIN32 - SSL_TYPE_SCHANNEL, -#endif - SSL_TYPE_OPENSSL, - SSL_TYPE_GNUTLS -}; - -#define PROTOCOL_SSLV3 0 -#define PROTOCOL_TLS_1_0 1 -#define PROTOCOL_TLS_1_1 2 -#define PROTOCOL_TLS_1_2 3 -#define PROTOCOL_TLS_1_3 4 -#define PROTOCOL_UNKNOWN 5 -#define PROTOCOL_MAX PROTOCOL_TLS_1_3 - -#define TLS_VERSION_LENGTH 64 -extern char tls_library_version[TLS_VERSION_LENGTH]; - -typedef struct st_ma_pvio_tls { - void *data; - MARIADB_PVIO *pvio; - void *ssl; -} MARIADB_TLS; - -/* Function prototypes */ - -/* ma_tls_start - initializes the ssl library - Parameter: - errmsg pointer to error message buffer - errmsg_len length of error message buffer - Returns: - 0 success - 1 if an error occurred - Notes: - On success the global variable ma_tls_initialized will be set to 1 -*/ -int ma_tls_start(char *errmsg, size_t errmsg_len); - -/* ma_tls_end - unloads/deinitializes ssl library and unsets global variable - ma_tls_initialized -*/ -void ma_tls_end(void); - -/* ma_tls_init - creates a new SSL structure for a SSL connection and loads - client certificates - - Parameters: - MYSQL a mysql structure - Returns: - void * a pointer to internal SSL structure -*/ -void * ma_tls_init(MYSQL *mysql); - -/* ma_tls_connect - performs SSL handshake - Parameters: - MARIADB_TLS MariaDB SSL container - Returns: - 0 success - 1 error -*/ -my_bool ma_tls_connect(MARIADB_TLS *ctls); - -/* ma_tls_read - reads up to length bytes from socket - Parameters: - ctls MariaDB SSL container - buffer read buffer - length buffer length - Returns: - 0-n bytes read - -1 if an error occurred -*/ -ssize_t ma_tls_read(MARIADB_TLS *ctls, const uchar* buffer, size_t length); - -/* ma_tls_write - write buffer to socket - Parameters: - ctls MariaDB SSL container - buffer write buffer - length buffer length - Returns: - 0-n bytes written - -1 if an error occurred -*/ -ssize_t ma_tls_write(MARIADB_TLS *ctls, const uchar* buffer, size_t length); - -/* ma_tls_close - closes SSL connection and frees SSL structure which was previously - created by ma_tls_init call - Parameters: - MARIADB_TLS MariaDB SSL container - Returns: - 0 success - 1 error -*/ -my_bool ma_tls_close(MARIADB_TLS *ctls); - -/* ma_tls_verify_server_cert - validation check of server certificate - Parameter: - MARIADB_TLS MariaDB SSL container - Returns: - ß success - 1 error -*/ -int ma_tls_verify_server_cert(MARIADB_TLS *ctls); - -/* ma_tls_get_cipher - returns cipher for current ssl connection - Parameter: - MARIADB_TLS MariaDB SSL container - Returns: - cipher in use or - NULL on error -*/ -const char *ma_tls_get_cipher(MARIADB_TLS *ssl); - -/* ma_tls_get_finger_print - returns SHA1 finger print of server certificate - Parameter: - MARIADB_TLS MariaDB SSL container - fp buffer for fingerprint - fp_len buffer length - Returns: - actual size of finger print -*/ -unsigned int ma_tls_get_finger_print(MARIADB_TLS *ctls, char *fp, unsigned int fp_len); - -/* ma_tls_get_protocol_version - returns protocol version number in use - Parameter: - MARIADB_TLS MariaDB SSL container - Returns: - protocol number -*/ -int ma_tls_get_protocol_version(MARIADB_TLS *ctls); -const char *ma_pvio_tls_get_protocol_version(MARIADB_TLS *ctls); -int ma_pvio_tls_get_protocol_version_id(MARIADB_TLS *ctls); - -/* Function prototypes */ -MARIADB_TLS *ma_pvio_tls_init(MYSQL *mysql); -my_bool ma_pvio_tls_connect(MARIADB_TLS *ctls); -ssize_t ma_pvio_tls_read(MARIADB_TLS *ctls, const uchar *buffer, size_t length); -ssize_t ma_pvio_tls_write(MARIADB_TLS *ctls, const uchar *buffer, size_t length); -my_bool ma_pvio_tls_close(MARIADB_TLS *ctls); -int ma_pvio_tls_verify_server_cert(MARIADB_TLS *ctls); -const char *ma_pvio_tls_cipher(MARIADB_TLS *ctls); -my_bool ma_pvio_tls_check_fp(MARIADB_TLS *ctls, const char *fp, const char *fp_list); -my_bool ma_pvio_start_ssl(MARIADB_PVIO *pvio); -void ma_pvio_tls_end(); - -#endif /* _ma_tls_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mariadb/ma_io.h b/VCMP-LUA/modules/mariadb/include/mysql/mariadb/ma_io.h deleted file mode 100644 index d39fc06..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mariadb/ma_io.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright (C) 2015 MariaDB Corporation AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ - -#ifndef _ma_io_h_ -#define _ma_io_h_ - - -#ifdef HAVE_REMOTEIO -#include -#endif - -enum enum_file_type { - MA_FILE_NONE=0, - MA_FILE_LOCAL=1, - MA_FILE_REMOTE=2 -}; - -typedef struct -{ - enum enum_file_type type; - void *ptr; -} MA_FILE; - -#ifdef HAVE_REMOTEIO -struct st_rio_methods { - MA_FILE *(*mopen)(const char *url, const char *mode); - int (*mclose)(MA_FILE *ptr); - int (*mfeof)(MA_FILE *file); - size_t (*mread)(void *ptr, size_t size, size_t nmemb, MA_FILE *file); - char * (*mgets)(char *ptr, size_t size, MA_FILE *file); -}; -#endif - -/* function prototypes */ -MA_FILE *ma_open(const char *location, const char *mode, MYSQL *mysql); -int ma_close(MA_FILE *file); -int ma_feof(MA_FILE *file); -size_t ma_read(void *ptr, size_t size, size_t nmemb, MA_FILE *file); -char *ma_gets(char *ptr, size_t size, MA_FILE *file); - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_com.h b/VCMP-LUA/modules/mariadb/include/mysql/mariadb_com.h deleted file mode 100644 index a1b99a8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_com.h +++ /dev/null @@ -1,466 +0,0 @@ -/************************************************************************************ - Copyright (C) 2000, 2012 MySQL AB & MySQL Finland AB & TCX DataKonsult AB, - Monty Program AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not see - or write to the Free Software Foundation, Inc., - 51 Franklin St., Fifth Floor, Boston, MA 02110, USA - - Part of this code includes code from the PHP project which - is freely available from http://www.php.net -*************************************************************************************/ - -/* -** Common definition between mysql server & client -*/ - -#ifndef _mysql_com_h -#define _mysql_com_h - - -#define NAME_CHAR_LEN 64 -#define NAME_LEN 256 /* Field/table name length */ -#define HOSTNAME_LENGTH 60 -#define SYSTEM_MB_MAX_CHAR_LENGTH 4 -#define USERNAME_CHAR_LENGTH 128 -#define USERNAME_LENGTH (USERNAME_CHAR_LENGTH * SYSTEM_MB_MAX_CHAR_LENGTH) -#define SERVER_VERSION_LENGTH 60 -#define SQLSTATE_LENGTH 5 -#define SCRAMBLE_LENGTH 20 -#define SCRAMBLE_LENGTH_323 8 - -#define LOCAL_HOST "localhost" -#define LOCAL_HOST_NAMEDPIPE "." - -#if defined(_WIN32) && !defined( _CUSTOMCONFIG_) -#define MARIADB_NAMEDPIPE "MySQL" -#define MYSQL_SERVICENAME "MySql" -#endif /* _WIN32 */ - -/* for use in mysql client tools only */ -#define MYSQL_AUTODETECT_CHARSET_NAME "auto" -#define BINCMP_FLAG 131072 - -enum mysql_enum_shutdown_level -{ - SHUTDOWN_DEFAULT = 0, - KILL_QUERY= 254, - KILL_CONNECTION= 255 -}; - -enum enum_server_command -{ - COM_SLEEP = 0, - COM_QUIT, - COM_INIT_DB, - COM_QUERY, - COM_FIELD_LIST, - COM_CREATE_DB, - COM_DROP_DB, - COM_REFRESH, - COM_SHUTDOWN, - COM_STATISTICS, - COM_PROCESS_INFO, - COM_CONNECT, - COM_PROCESS_KILL, - COM_DEBUG, - COM_PING, - COM_TIME = 15, - COM_DELAYED_INSERT, - COM_CHANGE_USER, - COM_BINLOG_DUMP, - COM_TABLE_DUMP, - COM_CONNECT_OUT = 20, - COM_REGISTER_SLAVE, - COM_STMT_PREPARE = 22, - COM_STMT_EXECUTE = 23, - COM_STMT_SEND_LONG_DATA = 24, - COM_STMT_CLOSE = 25, - COM_STMT_RESET = 26, - COM_SET_OPTION = 27, - COM_STMT_FETCH = 28, - COM_DAEMON= 29, - COM_UNSUPPORTED= 30, - COM_RESET_CONNECTION = 31, - COM_STMT_BULK_EXECUTE = 250, - COM_RESERVED_1 = 254, /* former COM_MULTI, now removed */ - COM_END -}; - - -#define NOT_NULL_FLAG 1 /* Field can't be NULL */ -#define PRI_KEY_FLAG 2 /* Field is part of a primary key */ -#define UNIQUE_KEY_FLAG 4 /* Field is part of a unique key */ -#define MULTIPLE_KEY_FLAG 8 /* Field is part of a key */ -#define BLOB_FLAG 16 /* Field is a blob */ -#define UNSIGNED_FLAG 32 /* Field is unsigned */ -#define ZEROFILL_FLAG 64 /* Field is zerofill */ -#define BINARY_FLAG 128 -/* The following are only sent to new clients */ -#define ENUM_FLAG 256 /* field is an enum */ -#define AUTO_INCREMENT_FLAG 512 /* field is a autoincrement field */ -#define TIMESTAMP_FLAG 1024 /* Field is a timestamp */ -#define SET_FLAG 2048 /* field is a set */ -/* new since 3.23.58 */ -#define NO_DEFAULT_VALUE_FLAG 4096 /* Field doesn't have default value */ -#define ON_UPDATE_NOW_FLAG 8192 /* Field is set to NOW on UPDATE */ -/* end new */ -#define NUM_FLAG 32768 /* Field is num (for clients) */ -#define PART_KEY_FLAG 16384 /* Intern; Part of some key */ -#define GROUP_FLAG 32768 /* Intern: Group field */ -#define UNIQUE_FLAG 65536 /* Intern: Used by sql_yacc */ - -#define REFRESH_GRANT 1 /* Refresh grant tables */ -#define REFRESH_LOG 2 /* Start on new log file */ -#define REFRESH_TABLES 4 /* close all tables */ -#define REFRESH_HOSTS 8 /* Flush host cache */ -#define REFRESH_STATUS 16 /* Flush status variables */ -#define REFRESH_THREADS 32 /* Flush thread cache */ -#define REFRESH_SLAVE 64 /* Reset master info and restart slave - thread */ -#define REFRESH_MASTER 128 /* Remove all bin logs in the index - and truncate the index */ - -/* The following can't be set with mysql_refresh() */ -#define REFRESH_READ_LOCK 16384 /* Lock tables for read */ -#define REFRESH_FAST 32768 /* Intern flag */ - -#define CLIENT_MYSQL 1 -#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */ -#define CLIENT_LONG_FLAG 4 /* Get all column flags */ -#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */ -#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */ -#define CLIENT_COMPRESS 32 /* Can use compression protocol */ -#define CLIENT_ODBC 64 /* Odbc client */ -#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */ -#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */ -#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */ -#define CLIENT_SSL 2048 /* Switch to SSL after handshake */ -#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */ -#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */ -/* added in 4.x */ -#define CLIENT_PROTOCOL_41 512 -#define CLIENT_RESERVED 16384 -#define CLIENT_SECURE_CONNECTION 32768 -#define CLIENT_MULTI_STATEMENTS (1UL << 16) -#define CLIENT_MULTI_RESULTS (1UL << 17) -#define CLIENT_PS_MULTI_RESULTS (1UL << 18) -#define CLIENT_PLUGIN_AUTH (1UL << 19) -#define CLIENT_CONNECT_ATTRS (1UL << 20) -#define CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA (1UL << 21) -#define CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS (1UL << 22) -#define CLIENT_SESSION_TRACKING (1UL << 23) -#define CLIENT_PROGRESS (1UL << 29) /* client supports progress indicator */ -#define CLIENT_PROGRESS_OBSOLETE CLIENT_PROGRESS -#define CLIENT_SSL_VERIFY_SERVER_CERT (1UL << 30) -#define CLIENT_REMEMBER_OPTIONS (1UL << 31) - -/* MariaDB specific capabilities */ -#define MARIADB_CLIENT_FLAGS 0xFFFFFFFF00000000ULL -#define MARIADB_CLIENT_PROGRESS (1ULL << 32) -#define MARIADB_CLIENT_RESERVED_1 (1ULL << 33) /* Former COM_MULTI, don't use */ -#define MARIADB_CLIENT_STMT_BULK_OPERATIONS (1ULL << 34) -/* support of extended data type/format information, since 10.5.0 */ -#define MARIADB_CLIENT_EXTENDED_METADATA (1ULL << 35) - -#define IS_MARIADB_EXTENDED_SERVER(mysql)\ - (!(mysql->server_capabilities & CLIENT_MYSQL)) - -#define MARIADB_CLIENT_SUPPORTED_FLAGS (MARIADB_CLIENT_PROGRESS |\ - MARIADB_CLIENT_STMT_BULK_OPERATIONS|\ - MARIADB_CLIENT_EXTENDED_METADATA) - -#define CLIENT_SUPPORTED_FLAGS (CLIENT_MYSQL |\ - CLIENT_FOUND_ROWS |\ - CLIENT_LONG_FLAG |\ - CLIENT_CONNECT_WITH_DB |\ - CLIENT_NO_SCHEMA |\ - CLIENT_COMPRESS |\ - CLIENT_ODBC |\ - CLIENT_LOCAL_FILES |\ - CLIENT_IGNORE_SPACE |\ - CLIENT_INTERACTIVE |\ - CLIENT_SSL |\ - CLIENT_IGNORE_SIGPIPE |\ - CLIENT_TRANSACTIONS |\ - CLIENT_PROTOCOL_41 |\ - CLIENT_RESERVED |\ - CLIENT_SECURE_CONNECTION |\ - CLIENT_MULTI_STATEMENTS |\ - CLIENT_MULTI_RESULTS |\ - CLIENT_PROGRESS |\ - CLIENT_SSL_VERIFY_SERVER_CERT |\ - CLIENT_REMEMBER_OPTIONS |\ - CLIENT_PLUGIN_AUTH |\ - CLIENT_SESSION_TRACKING |\ - CLIENT_CONNECT_ATTRS) -#define CLIENT_CAPABILITIES (CLIENT_MYSQL | \ - CLIENT_LONG_FLAG |\ - CLIENT_TRANSACTIONS |\ - CLIENT_SECURE_CONNECTION |\ - CLIENT_MULTI_RESULTS | \ - CLIENT_PS_MULTI_RESULTS |\ - CLIENT_PROTOCOL_41 |\ - CLIENT_PLUGIN_AUTH |\ - CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | \ - CLIENT_SESSION_TRACKING |\ - CLIENT_CONNECT_ATTRS) - -#define CLIENT_DEFAULT_FLAGS ((CLIENT_SUPPORTED_FLAGS & ~CLIENT_COMPRESS)\ - & ~CLIENT_SSL) - -#define SERVER_STATUS_IN_TRANS 1 /* Transaction has started */ -#define SERVER_STATUS_AUTOCOMMIT 2 /* Server in auto_commit mode */ -#define SERVER_MORE_RESULTS_EXIST 8 -#define SERVER_QUERY_NO_GOOD_INDEX_USED 16 -#define SERVER_QUERY_NO_INDEX_USED 32 -#define SERVER_STATUS_CURSOR_EXISTS 64 -#define SERVER_STATUS_LAST_ROW_SENT 128 -#define SERVER_STATUS_DB_DROPPED 256 -#define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512 -#define SERVER_STATUS_METADATA_CHANGED 1024 -#define SERVER_QUERY_WAS_SLOW 2048 -#define SERVER_PS_OUT_PARAMS 4096 -#define SERVER_STATUS_IN_TRANS_READONLY 8192 -#define SERVER_SESSION_STATE_CHANGED 16384 -#define SERVER_STATUS_ANSI_QUOTES 32768 - -#define MYSQL_ERRMSG_SIZE 512 -#define NET_READ_TIMEOUT 30 /* Timeout on read */ -#define NET_WRITE_TIMEOUT 60 /* Timeout on write */ -#define NET_WAIT_TIMEOUT (8*60*60) /* Wait for new query */ - -/* for server integration (mysqlbinlog) */ -#define LIST_PROCESS_HOST_LEN 64 -#define MYSQL50_TABLE_NAME_PREFIX "#mysql50#" -#define MYSQL50_TABLE_NAME_PREFIX_LENGTH (sizeof(MYSQL50_TABLE_NAME_PREFIX)-1) -#define SAFE_NAME_LEN (NAME_LEN + MYSQL50_TABLE_NAME_PREFIX_LENGTH) - -struct st_ma_pvio; -typedef struct st_ma_pvio MARIADB_PVIO; - -#define MAX_CHAR_WIDTH 255 /* Max length for a CHAR column */ -#define MAX_BLOB_WIDTH 8192 /* Default width for blob */ - -/* the following defines were added for PHP's mysqli and pdo extensions: - see: CONC-56 -*/ -#define MAX_TINYINT_WIDTH 3 -#define MAX_SMALLINT_WIDTH 5 -#define MAX_MEDIUMINT_WIDTH 8 -#define MAX_INT_WIDTH 10 -#define MAX_BIGINT_WIDTH 20 - -struct st_ma_connection_plugin; - - -typedef struct st_net { - MARIADB_PVIO *pvio; - unsigned char *buff; - unsigned char *buff_end,*write_pos,*read_pos; - my_socket fd; /* For Perl DBI/dbd */ - unsigned long remain_in_buf,length; - unsigned long buf_length, where_b; - unsigned long max_packet, max_packet_size; - unsigned int pkt_nr, compress_pkt_nr; - unsigned int write_timeout, read_timeout, retry_count; - int fcntl; - unsigned int *return_status; - unsigned char reading_or_writing; - char save_char; - char unused_1; - my_bool unused_2; - my_bool compress; - my_bool unused_3; - void *unused_4; - unsigned int last_errno; - unsigned char error; - my_bool unused_5; - my_bool unused_6; - char last_error[MYSQL_ERRMSG_SIZE]; - char sqlstate[SQLSTATE_LENGTH+1]; - struct st_mariadb_net_extension *extension; -} NET; - -#define packet_error ((unsigned int) -1) - -/* used by mysql_set_server_option */ -enum enum_mysql_set_option -{ - MYSQL_OPTION_MULTI_STATEMENTS_ON, - MYSQL_OPTION_MULTI_STATEMENTS_OFF -}; - -enum enum_session_state_type -{ - SESSION_TRACK_SYSTEM_VARIABLES= 0, - SESSION_TRACK_SCHEMA, - SESSION_TRACK_STATE_CHANGE, - /* currently not supported by MariaDB Server */ - SESSION_TRACK_GTIDS, - SESSION_TRACK_TRANSACTION_CHARACTERISTICS, - SESSION_TRACK_TRANSACTION_STATE /* make sure that SESSION_TRACK_END always points - to last element of enum !! */ -}; - -#define SESSION_TRACK_BEGIN 0 -#define SESSION_TRACK_END SESSION_TRACK_TRANSACTION_STATE -#define SESSION_TRACK_TYPES (SESSION_TRACK_END + 1) - -/* SESSION_TRACK_TRANSACTION_TYPE was renamed to SESSION_TRACK_TRANSACTION_STATE - in 3e699a1738cdfb0a2c5b8eabfa8301b8d11cf711. - This is a workaround to prevent breaking of travis and buildbot tests. - TODO: Remove this after server fixes */ -#define SESSION_TRACK_TRANSACTION_TYPE SESSION_TRACK_TRANSACTION_STATE - -enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY, - MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, - MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE, - MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP, - MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24, - MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, - MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, - MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR, - MYSQL_TYPE_BIT, - /* - the following types are not used by client, - only for mysqlbinlog!! - */ - MYSQL_TYPE_TIMESTAMP2, - MYSQL_TYPE_DATETIME2, - MYSQL_TYPE_TIME2, - /* --------------------------------------------- */ - MYSQL_TYPE_JSON=245, - MYSQL_TYPE_NEWDECIMAL=246, - MYSQL_TYPE_ENUM=247, - MYSQL_TYPE_SET=248, - MYSQL_TYPE_TINY_BLOB=249, - MYSQL_TYPE_MEDIUM_BLOB=250, - MYSQL_TYPE_LONG_BLOB=251, - MYSQL_TYPE_BLOB=252, - MYSQL_TYPE_VAR_STRING=253, - MYSQL_TYPE_STRING=254, - MYSQL_TYPE_GEOMETRY=255, - MAX_NO_FIELD_TYPES }; - -#define FIELD_TYPE_CHAR FIELD_TYPE_TINY /* For compatibility */ -#define FIELD_TYPE_INTERVAL FIELD_TYPE_ENUM /* For compatibility */ -#define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL -#define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL -#define FIELD_TYPE_TINY MYSQL_TYPE_TINY -#define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT -#define FIELD_TYPE_LONG MYSQL_TYPE_LONG -#define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT -#define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE -#define FIELD_TYPE_NULL MYSQL_TYPE_NULL -#define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP -#define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG -#define FIELD_TYPE_INT24 MYSQL_TYPE_INT24 -#define FIELD_TYPE_DATE MYSQL_TYPE_DATE -#define FIELD_TYPE_TIME MYSQL_TYPE_TIME -#define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME -#define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR -#define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE -#define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM -#define FIELD_TYPE_SET MYSQL_TYPE_SET -#define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB -#define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB -#define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB -#define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB -#define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING -#define FIELD_TYPE_STRING MYSQL_TYPE_STRING -#define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY -#define FIELD_TYPE_BIT MYSQL_TYPE_BIT - -extern unsigned long max_allowed_packet; -extern unsigned long net_buffer_length; - -#define net_new_transaction(net) ((net)->pkt_nr=0) - -int ma_net_init(NET *net, MARIADB_PVIO *pvio); -void ma_net_end(NET *net); -void ma_net_clear(NET *net); -int ma_net_flush(NET *net); -int ma_net_write(NET *net,const unsigned char *packet, size_t len); -int ma_net_write_command(NET *net,unsigned char command,const char *packet, - size_t len, my_bool disable_flush); -int ma_net_real_write(NET *net,const char *packet, size_t len); -extern unsigned long ma_net_read(NET *net); - -struct rand_struct { - unsigned long seed1,seed2,max_value; - double max_value_dbl; -}; - - /* The following is for user defined functions */ - -enum Item_result {STRING_RESULT,REAL_RESULT,INT_RESULT,ROW_RESULT,DECIMAL_RESULT}; - -typedef struct st_udf_args -{ - unsigned int arg_count; /* Number of arguments */ - enum Item_result *arg_type; /* Pointer to item_results */ - char **args; /* Pointer to argument */ - unsigned long *lengths; /* Length of string arguments */ - char *maybe_null; /* Set to 1 for all maybe_null args */ -} UDF_ARGS; - - /* This holds information about the result */ - -typedef struct st_udf_init -{ - my_bool maybe_null; /* 1 if function can return NULL */ - unsigned int decimals; /* for real functions */ - unsigned int max_length; /* For string functions */ - char *ptr; /* free pointer for function data */ - my_bool const_item; /* 0 if result is independent of arguments */ -} UDF_INIT; - -/* Connection types */ -#define MARIADB_CONNECTION_UNIXSOCKET 0 -#define MARIADB_CONNECTION_TCP 1 -#define MARIADB_CONNECTION_NAMEDPIPE 2 -#define MARIADB_CONNECTION_SHAREDMEM 3 - - /* Constants when using compression */ -#define NET_HEADER_SIZE 4 /* standard header size */ -#define COMP_HEADER_SIZE 3 /* compression header extra size */ - - /* Prototypes to password functions */ -#define native_password_plugin_name "mysql_native_password" -#define old_password_plugin_name "mysql_old_password" - -#ifdef __cplusplus -extern "C" { -#endif - -char *ma_scramble_323(char *to,const char *message,const char *password); -void ma_scramble_41(const unsigned char *buffer, const char *scramble, const char *password); -void ma_hash_password(unsigned long *result, const char *password, size_t len); -void ma_make_scrambled_password(char *to,const char *password); - -/* Some other useful functions */ - -void mariadb_load_defaults(const char *conf_file, const char **groups, - int *argc, char ***argv); -my_bool ma_thread_init(void); -void ma_thread_end(void); - -#ifdef __cplusplus -} -#endif - -#define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */ - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_ctype.h b/VCMP-LUA/modules/mariadb/include/mysql/mariadb_ctype.h deleted file mode 100644 index bc65fcd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_ctype.h +++ /dev/null @@ -1,76 +0,0 @@ -/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ - -/* - A better inplementation of the UNIX ctype(3) library. - Notes: my_global.h should be included before ctype.h -*/ - -#ifndef _mariadb_ctype_h -#define _mariadb_ctype_h - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define CHARSET_DIR "charsets/" -#define MY_CS_NAME_SIZE 32 - -#define MADB_DEFAULT_CHARSET_NAME "latin1" -#define MADB_DEFAULT_COLLATION_NAME "latin1_swedish_ci" -#define MADB_AUTODETECT_CHARSET_NAME "auto" - -/* we use the mysqlnd implementation */ -typedef struct ma_charset_info_st -{ - unsigned int nr; /* so far only 1 byte for charset */ - unsigned int state; - const char *csname; - const char *name; - const char *dir; - unsigned int codepage; - const char *encoding; - unsigned int char_minlen; - unsigned int char_maxlen; - unsigned int (*mb_charlen)(unsigned int c); - unsigned int (*mb_valid)(const char *start, const char *end); -} MARIADB_CHARSET_INFO; - -extern const MARIADB_CHARSET_INFO mariadb_compiled_charsets[]; -extern MARIADB_CHARSET_INFO *ma_default_charset_info; -extern MARIADB_CHARSET_INFO *ma_charset_bin; -extern MARIADB_CHARSET_INFO *ma_charset_latin1; -extern MARIADB_CHARSET_INFO *ma_charset_utf8_general_ci; -extern MARIADB_CHARSET_INFO *ma_charset_utf16le_general_ci; - -MARIADB_CHARSET_INFO *find_compiled_charset(unsigned int cs_number); -MARIADB_CHARSET_INFO *find_compiled_charset_by_name(const char *name); - -size_t mysql_cset_escape_quotes(const MARIADB_CHARSET_INFO *cset, char *newstr, const char *escapestr, size_t escapestr_len); -size_t mysql_cset_escape_slashes(const MARIADB_CHARSET_INFO *cset, char *newstr, const char *escapestr, size_t escapestr_len); -const char* madb_get_os_character_set(void); -#ifdef _WIN32 -int madb_get_windows_cp(const char *charset); -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_dyncol.h b/VCMP-LUA/modules/mariadb/include/mysql/mariadb_dyncol.h deleted file mode 100644 index 216431a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_dyncol.h +++ /dev/null @@ -1,259 +0,0 @@ -/* Copyright (c) 2011, Monty Program Ab - Copyright (c) 2011, Oleksandr Byelkin - - 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 the following disclaimer in - the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY ``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 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. -*/ - -#ifndef ma_dyncol_h -#define ma_dyncol_h - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef LIBMARIADB -#include -#include -#endif -#include - -#ifndef longlong_defined -#if defined(HAVE_LONG_LONG) && SIZEOF_LONG != 8 -typedef unsigned long long int ulonglong; /* ulong or unsigned long long */ -typedef long long int longlong; -#else -typedef unsigned long ulonglong; /* ulong or unsigned long long */ -typedef long longlong; -#endif -#define longlong_defined -#endif - - -#ifndef _my_sys_h -typedef struct st_dynamic_string -{ - char *str; - size_t length,max_length,alloc_increment; -} DYNAMIC_STRING; -#endif - -struct st_mysql_lex_string -{ - char *str; - size_t length; -}; -typedef struct st_mysql_lex_string MYSQL_LEX_STRING; -typedef struct st_mysql_lex_string LEX_STRING; -/* - Limits of implementation -*/ -#define MAX_TOTAL_NAME_LENGTH 65535 -#define MAX_NAME_LENGTH (MAX_TOTAL_NAME_LENGTH/4) - -/* NO and OK is the same used just to show semantics */ -#define ER_DYNCOL_NO ER_DYNCOL_OK - -enum enum_dyncol_func_result -{ - ER_DYNCOL_OK= 0, - ER_DYNCOL_YES= 1, /* For functions returning 0/1 */ - ER_DYNCOL_FORMAT= -1, /* Wrong format of the encoded string */ - ER_DYNCOL_LIMIT= -2, /* Some limit reached */ - ER_DYNCOL_RESOURCE= -3, /* Out of resourses */ - ER_DYNCOL_DATA= -4, /* Incorrect input data */ - ER_DYNCOL_UNKNOWN_CHARSET= -5, /* Unknown character set */ - ER_DYNCOL_TRUNCATED= 2 /* OK, but data was truncated */ -}; - -typedef DYNAMIC_STRING DYNAMIC_COLUMN; - -enum enum_dynamic_column_type -{ - DYN_COL_NULL= 0, - DYN_COL_INT, - DYN_COL_UINT, - DYN_COL_DOUBLE, - DYN_COL_STRING, - DYN_COL_DECIMAL, - DYN_COL_DATETIME, - DYN_COL_DATE, - DYN_COL_TIME, - DYN_COL_DYNCOL -}; - -typedef enum enum_dynamic_column_type DYNAMIC_COLUMN_TYPE; - -struct st_dynamic_column_value -{ - DYNAMIC_COLUMN_TYPE type; - union - { - long long long_value; - unsigned long long ulong_value; - double double_value; - struct { - MYSQL_LEX_STRING value; - MARIADB_CHARSET_INFO *charset; - } string; -#ifndef LIBMARIADB - struct { - decimal_digit_t buffer[DECIMAL_BUFF_LENGTH]; - decimal_t value; - } decimal; -#endif - MYSQL_TIME time_value; - } x; -}; - -typedef struct st_dynamic_column_value DYNAMIC_COLUMN_VALUE; - -#ifdef MADYNCOL_DEPRECATED -enum enum_dyncol_func_result -dynamic_column_create(DYNAMIC_COLUMN *str, - uint column_nr, DYNAMIC_COLUMN_VALUE *value); - -enum enum_dyncol_func_result -dynamic_column_create_many(DYNAMIC_COLUMN *str, - uint column_count, - uint *column_numbers, - DYNAMIC_COLUMN_VALUE *values); -enum enum_dyncol_func_result -dynamic_column_update(DYNAMIC_COLUMN *org, uint column_nr, - DYNAMIC_COLUMN_VALUE *value); -enum enum_dyncol_func_result -dynamic_column_update_many(DYNAMIC_COLUMN *str, - uint add_column_count, - uint *column_numbers, - DYNAMIC_COLUMN_VALUE *values); - -enum enum_dyncol_func_result -dynamic_column_exists(DYNAMIC_COLUMN *org, uint column_nr); - -enum enum_dyncol_func_result -dynamic_column_list(DYNAMIC_COLUMN *org, DYNAMIC_ARRAY *array_of_uint); - -enum enum_dyncol_func_result -dynamic_column_get(DYNAMIC_COLUMN *org, uint column_nr, - DYNAMIC_COLUMN_VALUE *store_it_here); -#endif - -/* new functions */ -enum enum_dyncol_func_result -mariadb_dyncol_create_many_num(DYNAMIC_COLUMN *str, - uint column_count, - uint *column_numbers, - DYNAMIC_COLUMN_VALUE *values, - my_bool new_string); -enum enum_dyncol_func_result -mariadb_dyncol_create_many_named(DYNAMIC_COLUMN *str, - uint column_count, - MYSQL_LEX_STRING *column_keys, - DYNAMIC_COLUMN_VALUE *values, - my_bool new_string); - - -enum enum_dyncol_func_result -mariadb_dyncol_update_many_num(DYNAMIC_COLUMN *str, - uint add_column_count, - uint *column_keys, - DYNAMIC_COLUMN_VALUE *values); -enum enum_dyncol_func_result -mariadb_dyncol_update_many_named(DYNAMIC_COLUMN *str, - uint add_column_count, - MYSQL_LEX_STRING *column_keys, - DYNAMIC_COLUMN_VALUE *values); - - -enum enum_dyncol_func_result -mariadb_dyncol_exists_num(DYNAMIC_COLUMN *org, uint column_nr); -enum enum_dyncol_func_result -mariadb_dyncol_exists_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name); - -/* List of not NULL columns */ -enum enum_dyncol_func_result -mariadb_dyncol_list_num(DYNAMIC_COLUMN *str, uint *count, uint **nums); -enum enum_dyncol_func_result -mariadb_dyncol_list_named(DYNAMIC_COLUMN *str, uint *count, - MYSQL_LEX_STRING **names); - -/* - if the column do not exists it is NULL -*/ -enum enum_dyncol_func_result -mariadb_dyncol_get_num(DYNAMIC_COLUMN *org, uint column_nr, - DYNAMIC_COLUMN_VALUE *store_it_here); -enum enum_dyncol_func_result -mariadb_dyncol_get_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name, - DYNAMIC_COLUMN_VALUE *store_it_here); - -my_bool mariadb_dyncol_has_names(DYNAMIC_COLUMN *str); - -enum enum_dyncol_func_result -mariadb_dyncol_check(DYNAMIC_COLUMN *str); - -enum enum_dyncol_func_result -mariadb_dyncol_json(DYNAMIC_COLUMN *str, DYNAMIC_STRING *json); - -void mariadb_dyncol_free(DYNAMIC_COLUMN *str); - -#define mariadb_dyncol_init(A) memset((A), 0, sizeof(DYNAMIC_COLUMN)) -#define dynamic_column_initialize(A) mariadb_dyncol_init((A)) -#define dynamic_column_column_free(A) mariadb_dyncol_free((A)) - -/* conversion of values to 3 base types */ -enum enum_dyncol_func_result -mariadb_dyncol_val_str(DYNAMIC_STRING *str, DYNAMIC_COLUMN_VALUE *val, - MARIADB_CHARSET_INFO *cs, char quote); -enum enum_dyncol_func_result -mariadb_dyncol_val_long(longlong *ll, DYNAMIC_COLUMN_VALUE *val); -enum enum_dyncol_func_result -mariadb_dyncol_val_double(double *dbl, DYNAMIC_COLUMN_VALUE *val); - -enum enum_dyncol_func_result -mariadb_dyncol_unpack(DYNAMIC_COLUMN *str, - uint *count, - MYSQL_LEX_STRING **names, DYNAMIC_COLUMN_VALUE **vals); - -int mariadb_dyncol_column_cmp_named(const MYSQL_LEX_STRING *s1, - const MYSQL_LEX_STRING *s2); - -enum enum_dyncol_func_result -mariadb_dyncol_column_count(DYNAMIC_COLUMN *str, uint *column_count); - -#define mariadb_dyncol_value_init(V) \ -do {\ - (V)->type= DYN_COL_NULL;\ -} while(0) - -/* - Prepare value for using as decimal -*/ -void mariadb_dyncol_prepare_decimal(DYNAMIC_COLUMN_VALUE *value); - - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_rpl.h b/VCMP-LUA/modules/mariadb/include/mysql/mariadb_rpl.h deleted file mode 100644 index 315543f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_rpl.h +++ /dev/null @@ -1,305 +0,0 @@ -/* Copyright (C) 2018 MariaDB Corporation AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ -#ifndef _mariadb_rpl_h_ -#define _mariadb_rpl_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#define MARIADB_RPL_VERSION 0x0001 -#define MARIADB_RPL_REQUIRED_VERSION 0x0001 - -/* Protocol flags */ -#define MARIADB_RPL_BINLOG_DUMP_NON_BLOCK 1 -#define MARIADB_RPL_BINLOG_SEND_ANNOTATE_ROWS 2 -#define MARIADB_RPL_IGNORE_HEARTBEAT (1 << 17) - -#define EVENT_HEADER_OFS 20 - -#define FL_GROUP_COMMIT_ID 2 -#define FL_STMT_END 1 - -#define LOG_EVENT_ARTIFICIAL_F 0x20 - - -/* Options */ -enum mariadb_rpl_option { - MARIADB_RPL_FILENAME, /* Filename and length */ - MARIADB_RPL_START, /* Start position */ - MARIADB_RPL_SERVER_ID, /* Server ID */ - MARIADB_RPL_FLAGS, /* Protocol flags */ - MARIADB_RPL_GTID_CALLBACK, /* GTID callback function */ - MARIADB_RPL_GTID_DATA, /* GTID data */ - MARIADB_RPL_BUFFER -}; - -/* Event types: From MariaDB Server sql/log_event.h */ -enum mariadb_rpl_event { - UNKNOWN_EVENT= 0, - START_EVENT_V3= 1, - QUERY_EVENT= 2, - STOP_EVENT= 3, - ROTATE_EVENT= 4, - INTVAR_EVENT= 5, - LOAD_EVENT= 6, - SLAVE_EVENT= 7, - CREATE_FILE_EVENT= 8, - APPEND_BLOCK_EVENT= 9, - EXEC_LOAD_EVENT= 10, - DELETE_FILE_EVENT= 11, - NEW_LOAD_EVENT= 12, - RAND_EVENT= 13, - USER_VAR_EVENT= 14, - FORMAT_DESCRIPTION_EVENT= 15, - XID_EVENT= 16, - BEGIN_LOAD_QUERY_EVENT= 17, - EXECUTE_LOAD_QUERY_EVENT= 18, - TABLE_MAP_EVENT = 19, - - PRE_GA_WRITE_ROWS_EVENT = 20, /* deprecated */ - PRE_GA_UPDATE_ROWS_EVENT = 21, /* deprecated */ - PRE_GA_DELETE_ROWS_EVENT = 22, /* deprecated */ - - WRITE_ROWS_EVENT_V1 = 23, - UPDATE_ROWS_EVENT_V1 = 24, - DELETE_ROWS_EVENT_V1 = 25, - INCIDENT_EVENT= 26, - HEARTBEAT_LOG_EVENT= 27, - IGNORABLE_LOG_EVENT= 28, - ROWS_QUERY_LOG_EVENT= 29, - WRITE_ROWS_EVENT = 30, - UPDATE_ROWS_EVENT = 31, - DELETE_ROWS_EVENT = 32, - GTID_LOG_EVENT= 33, - ANONYMOUS_GTID_LOG_EVENT= 34, - PREVIOUS_GTIDS_LOG_EVENT= 35, - TRANSACTION_CONTEXT_EVENT= 36, - VIEW_CHANGE_EVENT= 37, - XA_PREPARE_LOG_EVENT= 38, - - /* - Add new events here - right above this comment! - Existing events (except ENUM_END_EVENT) should never change their numbers - */ - - /* New MySQL/Sun events are to be added right above this comment */ - MYSQL_EVENTS_END, - - MARIA_EVENTS_BEGIN= 160, - ANNOTATE_ROWS_EVENT= 160, - BINLOG_CHECKPOINT_EVENT= 161, - GTID_EVENT= 162, - GTID_LIST_EVENT= 163, - START_ENCRYPTION_EVENT= 164, - QUERY_COMPRESSED_EVENT = 165, - WRITE_ROWS_COMPRESSED_EVENT_V1 = 166, - UPDATE_ROWS_COMPRESSED_EVENT_V1 = 167, - DELETE_ROWS_COMPRESSED_EVENT_V1 = 168, - WRITE_ROWS_COMPRESSED_EVENT = 169, - UPDATE_ROWS_COMPRESSED_EVENT = 170, - DELETE_ROWS_COMPRESSED_EVENT = 171, - - /* Add new MariaDB events here - right above this comment! */ - - ENUM_END_EVENT /* end marker */ -}; - -typedef struct { - char *str; - size_t length; -} MARIADB_STRING; - -enum mariadb_row_event_type { - WRITE_ROWS= 0, - UPDATE_ROWS= 1, - DELETE_ROWS= 2 -}; - -/* Global transaction id */ -typedef struct st_mariadb_gtid { - unsigned int domain_id; - unsigned int server_id; - unsigned long long sequence_nr; -} MARIADB_GTID; - -/* Generic replication handle */ -typedef struct st_mariadb_rpl { - unsigned int version; - MYSQL *mysql; - char *filename; - uint32_t filename_length; - unsigned char *buffer; - unsigned long buffer_size; - uint32_t server_id; - unsigned long start_position; - uint32_t flags; - uint8_t fd_header_len; /* header len from last format description event */ - uint8_t use_checksum; -} MARIADB_RPL; - -/* Event header */ -struct st_mariadb_rpl_rotate_event { - unsigned long long position; - MARIADB_STRING filename; -}; - -struct st_mariadb_rpl_query_event { - uint32_t thread_id; - uint32_t seconds; - MARIADB_STRING database; - uint32_t errornr; - MARIADB_STRING status; - MARIADB_STRING statement; -}; - -struct st_mariadb_rpl_gtid_list_event { - uint32_t gtid_cnt; - MARIADB_GTID *gtid; -}; - -struct st_mariadb_rpl_format_description_event -{ - uint16_t format; - char *server_version; - uint32_t timestamp; - uint8_t header_len; -}; - -struct st_mariadb_rpl_checkpoint_event { - MARIADB_STRING filename; -}; - -struct st_mariadb_rpl_xid_event { - uint64_t transaction_nr; -}; - -struct st_mariadb_rpl_gtid_event { - uint64_t sequence_nr; - uint32_t domain_id; - uint8_t flags; - uint64_t commit_id; -}; - -struct st_mariadb_rpl_annotate_rows_event { - MARIADB_STRING statement; -}; - -struct st_mariadb_rpl_table_map_event { - unsigned long long table_id; - MARIADB_STRING database; - MARIADB_STRING table; - unsigned int column_count; - MARIADB_STRING column_types; - MARIADB_STRING metadata; - char *null_indicator; -}; - -struct st_mariadb_rpl_rand_event { - unsigned long long first_seed; - unsigned long long second_seed; -}; - -struct st_mariadb_rpl_encryption_event { - char scheme; - unsigned int key_version; - char *nonce; -}; - -struct st_mariadb_rpl_intvar_event { - char type; - unsigned long long value; -}; - -struct st_mariadb_rpl_uservar_event { - MARIADB_STRING name; - uint8_t is_null; - uint8_t type; - uint32_t charset_nr; - MARIADB_STRING value; - uint8_t flags; -}; - -struct st_mariadb_rpl_rows_event { - enum mariadb_row_event_type type; - uint64_t table_id; - uint16_t flags; - uint32_t column_count; - char *column_bitmap; - char *column_update_bitmap; - size_t row_data_size; - void *row_data; -}; - -struct st_mariadb_rpl_heartbeat_event { - uint32_t timestamp; - uint32_t next_position; - uint8_t type; - uint16_t flags; -}; - -typedef struct st_mariadb_rpl_event -{ - /* common header */ - MA_MEM_ROOT memroot; - unsigned int checksum; - char ok; - enum mariadb_rpl_event event_type; - unsigned int timestamp; - unsigned int server_id; - unsigned int event_length; - unsigned int next_event_pos; - unsigned short flags; - /****************/ - union { - struct st_mariadb_rpl_rotate_event rotate; - struct st_mariadb_rpl_query_event query; - struct st_mariadb_rpl_format_description_event format_description; - struct st_mariadb_rpl_gtid_list_event gtid_list; - struct st_mariadb_rpl_checkpoint_event checkpoint; - struct st_mariadb_rpl_xid_event xid; - struct st_mariadb_rpl_gtid_event gtid; - struct st_mariadb_rpl_annotate_rows_event annotate_rows; - struct st_mariadb_rpl_table_map_event table_map; - struct st_mariadb_rpl_rand_event rand; - struct st_mariadb_rpl_encryption_event encryption; - struct st_mariadb_rpl_intvar_event intvar; - struct st_mariadb_rpl_uservar_event uservar; - struct st_mariadb_rpl_rows_event rows; - struct st_mariadb_rpl_heartbeat_event heartbeat; - } event; -} MARIADB_RPL_EVENT; - -#define mariadb_rpl_init(a) mariadb_rpl_init_ex((a), MARIADB_RPL_VERSION) - -/* Function prototypes */ -MARIADB_RPL * STDCALL mariadb_rpl_init_ex(MYSQL *mysql, unsigned int version); - -int mariadb_rpl_optionsv(MARIADB_RPL *rpl, enum mariadb_rpl_option, ...); -int mariadb_rpl_get_optionsv(MARIADB_RPL *rpl, enum mariadb_rpl_option, ...); - -int STDCALL mariadb_rpl_open(MARIADB_RPL *rpl); -void STDCALL mariadb_rpl_close(MARIADB_RPL *rpl); -MARIADB_RPL_EVENT * STDCALL mariadb_rpl_fetch(MARIADB_RPL *rpl, MARIADB_RPL_EVENT *event); -void STDCALL mariadb_free_rpl_event(MARIADB_RPL_EVENT *event); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_stmt.h b/VCMP-LUA/modules/mariadb/include/mysql/mariadb_stmt.h deleted file mode 100644 index d07540e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_stmt.h +++ /dev/null @@ -1,298 +0,0 @@ -/************************************************************************ - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA - - Part of this code includes code from PHP's mysqlnd extension - (written by Andrey Hristov, Georg Richter and Ulf Wendel), freely - available from http://www.php.net/software - -*************************************************************************/ - -#define MYSQL_NO_DATA 100 -#define MYSQL_DATA_TRUNCATED 101 -#define MYSQL_DEFAULT_PREFETCH_ROWS (unsigned long) 1 - -/* Bind flags */ -#define MADB_BIND_DUMMY 1 - -#define MARIADB_STMT_BULK_SUPPORTED(stmt)\ - ((stmt)->mysql && \ - (!((stmt)->mysql->server_capabilities & CLIENT_MYSQL) &&\ - ((stmt)->mysql->extension->mariadb_server_capabilities & \ - (MARIADB_CLIENT_STMT_BULK_OPERATIONS >> 32)))) - -#define SET_CLIENT_STMT_ERROR(a, b, c, d) \ -do { \ - (a)->last_errno= (b);\ - strncpy((a)->sqlstate, (c), SQLSTATE_LENGTH);\ - (a)->sqlstate[SQLSTATE_LENGTH]= 0;\ - strncpy((a)->last_error, (d) ? (d) : ER((b)), MYSQL_ERRMSG_SIZE);\ - (a)->last_error[MYSQL_ERRMSG_SIZE - 1]= 0;\ -} while (0) - -#define CLEAR_CLIENT_STMT_ERROR(a) \ -do { \ - (a)->last_errno= 0;\ - strcpy((a)->sqlstate, "00000");\ - (a)->last_error[0]= 0;\ -} while (0) - -#define MYSQL_PS_SKIP_RESULT_W_LEN -1 -#define MYSQL_PS_SKIP_RESULT_STR -2 -#define STMT_ID_LENGTH 4 - - -typedef struct st_mysql_stmt MYSQL_STMT; - -typedef MYSQL_RES* (*mysql_stmt_use_or_store_func)(MYSQL_STMT *); - -enum enum_stmt_attr_type -{ - STMT_ATTR_UPDATE_MAX_LENGTH, - STMT_ATTR_CURSOR_TYPE, - STMT_ATTR_PREFETCH_ROWS, - - /* MariaDB only */ - STMT_ATTR_PREBIND_PARAMS=200, - STMT_ATTR_ARRAY_SIZE, - STMT_ATTR_ROW_SIZE, - STMT_ATTR_STATE, - STMT_ATTR_CB_USER_DATA, - STMT_ATTR_CB_PARAM, - STMT_ATTR_CB_RESULT -}; - -enum enum_cursor_type -{ - CURSOR_TYPE_NO_CURSOR= 0, - CURSOR_TYPE_READ_ONLY= 1, - CURSOR_TYPE_FOR_UPDATE= 2, - CURSOR_TYPE_SCROLLABLE= 4 -}; - -enum enum_indicator_type -{ - STMT_INDICATOR_NTS=-1, - STMT_INDICATOR_NONE=0, - STMT_INDICATOR_NULL=1, - STMT_INDICATOR_DEFAULT=2, - STMT_INDICATOR_IGNORE=3, - STMT_INDICATOR_IGNORE_ROW=4 -}; - -/* - bulk PS flags -*/ -#define STMT_BULK_FLAG_CLIENT_SEND_TYPES 128 -#define STMT_BULK_FLAG_INSERT_ID_REQUEST 64 - -typedef enum mysql_stmt_state -{ - MYSQL_STMT_INITTED = 0, - MYSQL_STMT_PREPARED, - MYSQL_STMT_EXECUTED, - MYSQL_STMT_WAITING_USE_OR_STORE, - MYSQL_STMT_USE_OR_STORE_CALLED, - MYSQL_STMT_USER_FETCHING, /* fetch_row_buff or fetch_row_unbuf */ - MYSQL_STMT_FETCH_DONE -} enum_mysqlnd_stmt_state; - -typedef struct st_mysql_bind -{ - unsigned long *length; /* output length pointer */ - my_bool *is_null; /* Pointer to null indicator */ - void *buffer; /* buffer to get/put data */ - /* set this if you want to track data truncations happened during fetch */ - my_bool *error; - union { - unsigned char *row_ptr; /* for the current data position */ - char *indicator; /* indicator variable */ - } u; - void (*store_param_func)(NET *net, struct st_mysql_bind *param); - void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *, - unsigned char **row); - void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *, - unsigned char **row); - /* output buffer length, must be set when fetching str/binary */ - unsigned long buffer_length; - unsigned long offset; /* offset position for char/binary fetch */ - unsigned long length_value; /* Used if length is 0 */ - unsigned int flags; /* special flags, e.g. for dummy bind */ - unsigned int pack_length; /* Internal length for packed data */ - enum enum_field_types buffer_type; /* buffer type */ - my_bool error_value; /* used if error is 0 */ - my_bool is_unsigned; /* set if integer type is unsigned */ - my_bool long_data_used; /* If used with mysql_send_long_data */ - my_bool is_null_value; /* Used if is_null is 0 */ - void *extension; -} MYSQL_BIND; - -typedef struct st_mysqlnd_upsert_result -{ - unsigned int warning_count; - unsigned int server_status; - unsigned long long affected_rows; - unsigned long long last_insert_id; -} mysql_upsert_status; - -typedef struct st_mysql_cmd_buffer -{ - unsigned char *buffer; - size_t length; -} MYSQL_CMD_BUFFER; - -typedef struct st_mysql_error_info -{ - unsigned int error_no; - char error[MYSQL_ERRMSG_SIZE+1]; - char sqlstate[SQLSTATE_LENGTH + 1]; -} mysql_error_info; - - -struct st_mysqlnd_stmt_methods -{ - my_bool (*prepare)(const MYSQL_STMT * stmt, const char * const query, size_t query_len); - my_bool (*execute)(const MYSQL_STMT * stmt); - MYSQL_RES * (*use_result)(const MYSQL_STMT * stmt); - MYSQL_RES * (*store_result)(const MYSQL_STMT * stmt); - MYSQL_RES * (*get_result)(const MYSQL_STMT * stmt); - my_bool (*free_result)(const MYSQL_STMT * stmt); - my_bool (*seek_data)(const MYSQL_STMT * stmt, unsigned long long row); - my_bool (*reset)(const MYSQL_STMT * stmt); - my_bool (*close)(const MYSQL_STMT * stmt); /* private */ - my_bool (*dtor)(const MYSQL_STMT * stmt); /* use this for mysqlnd_stmt_close */ - - my_bool (*fetch)(const MYSQL_STMT * stmt, my_bool * const fetched_anything); - - my_bool (*bind_param)(const MYSQL_STMT * stmt, const MYSQL_BIND bind); - my_bool (*refresh_bind_param)(const MYSQL_STMT * stmt); - my_bool (*bind_result)(const MYSQL_STMT * stmt, const MYSQL_BIND *bind); - my_bool (*send_long_data)(const MYSQL_STMT * stmt, unsigned int param_num, - const char * const data, size_t length); - MYSQL_RES *(*get_parameter_metadata)(const MYSQL_STMT * stmt); - MYSQL_RES *(*get_result_metadata)(const MYSQL_STMT * stmt); - unsigned long long (*get_last_insert_id)(const MYSQL_STMT * stmt); - unsigned long long (*get_affected_rows)(const MYSQL_STMT * stmt); - unsigned long long (*get_num_rows)(const MYSQL_STMT * stmt); - - unsigned int (*get_param_count)(const MYSQL_STMT * stmt); - unsigned int (*get_field_count)(const MYSQL_STMT * stmt); - unsigned int (*get_warning_count)(const MYSQL_STMT * stmt); - - unsigned int (*get_error_no)(const MYSQL_STMT * stmt); - const char * (*get_error_str)(const MYSQL_STMT * stmt); - const char * (*get_sqlstate)(const MYSQL_STMT * stmt); - - my_bool (*get_attribute)(const MYSQL_STMT * stmt, enum enum_stmt_attr_type attr_type, const void * value); - my_bool (*set_attribute)(const MYSQL_STMT * stmt, enum enum_stmt_attr_type attr_type, const void * value); - void (*set_error)(MYSQL_STMT *stmt, unsigned int error_nr, const char *sqlstate, const char *format, ...); -}; - -typedef int (*mysql_stmt_fetch_row_func)(MYSQL_STMT *stmt, unsigned char **row); -typedef void (*ps_result_callback)(void *data, unsigned int column, unsigned char **row); -typedef my_bool *(*ps_param_callback)(void *data, MYSQL_BIND *bind, unsigned int row_nr); - -struct st_mysql_stmt -{ - MA_MEM_ROOT mem_root; - MYSQL *mysql; - unsigned long stmt_id; - unsigned long flags;/* cursor is set here */ - enum_mysqlnd_stmt_state state; - MYSQL_FIELD *fields; - unsigned int field_count; - unsigned int param_count; - unsigned char send_types_to_server; - MYSQL_BIND *params; - MYSQL_BIND *bind; - MYSQL_DATA result; /* we don't use mysqlnd's result set logic */ - MYSQL_ROWS *result_cursor; - my_bool bind_result_done; - my_bool bind_param_done; - - mysql_upsert_status upsert_status; - - unsigned int last_errno; - char last_error[MYSQL_ERRMSG_SIZE+1]; - char sqlstate[SQLSTATE_LENGTH + 1]; - - my_bool update_max_length; - unsigned long prefetch_rows; - LIST list; - - my_bool cursor_exists; - - void *extension; - mysql_stmt_fetch_row_func fetch_row_func; - unsigned int execute_count;/* count how many times the stmt was executed */ - mysql_stmt_use_or_store_func default_rset_handler; - struct st_mysqlnd_stmt_methods *m; - unsigned int array_size; - size_t row_size; - unsigned int prebind_params; - void *user_data; - ps_result_callback result_callback; - ps_param_callback param_callback; -}; - -typedef void (*ps_field_fetch_func)(MYSQL_BIND *r_param, const MYSQL_FIELD * field, unsigned char **row); -typedef struct st_mysql_perm_bind { - ps_field_fetch_func func; - /* should be signed int */ - int pack_len; - unsigned long max_len; -} MYSQL_PS_CONVERSION; - -extern MYSQL_PS_CONVERSION mysql_ps_fetch_functions[MYSQL_TYPE_GEOMETRY + 1]; -unsigned long ma_net_safe_read(MYSQL *mysql); -void mysql_init_ps_subsystem(void); -unsigned long net_field_length(unsigned char **packet); -int ma_simple_command(MYSQL *mysql,enum enum_server_command command, const char *arg, - size_t length, my_bool skipp_check, void *opt_arg); -/* - * function prototypes - */ -MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql); -int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, unsigned long length); -int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg, unsigned int column, unsigned long offset); -int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt); -unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt); -my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, const void *attr); -my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, void *attr); -my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd); -my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd); -my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt); -my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt); -my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt); -my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt, unsigned int param_number, const char *data, unsigned long length); -MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt); -MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt); -unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt); -const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt); -const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt); -MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET offset); -MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt); -void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, unsigned long long offset); -unsigned long long STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt); -unsigned long long STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt); -unsigned long long STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt); -unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_next_result(MYSQL_STMT *stmt); -my_bool STDCALL mysql_stmt_more_results(MYSQL_STMT *stmt); -int STDCALL mariadb_stmt_execute_direct(MYSQL_STMT *stmt, const char *stmt_str, size_t length); -MYSQL_FIELD * STDCALL mariadb_stmt_fetch_fields(MYSQL_STMT *stmt); diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_version.h b/VCMP-LUA/modules/mariadb/include/mysql/mariadb_version.h deleted file mode 100644 index f6843de..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mariadb_version.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright Abandoned 1996, 1999, 2001 MySQL AB - This file is public domain and comes with NO WARRANTY of any kind */ - -/* Version numbers for protocol & mysqld */ - -#ifndef _mariadb_version_h_ -#define _mariadb_version_h_ - -#ifdef _CUSTOMCONFIG_ -#include -#else -#define PROTOCOL_VERSION 10 -#define MARIADB_CLIENT_VERSION_STR "10.5.7" -#define MARIADB_BASE_VERSION "mariadb-10.5" -#define MARIADB_VERSION_ID 100507 -#define MARIADB_PORT 3306 -#define MARIADB_UNIX_ADDR "/tmp/mysql.sock" -#ifndef MYSQL_UNIX_ADDR -#define MYSQL_UNIX_ADDR MARIADB_UNIX_ADDR -#endif -#ifndef MYSQL_PORT -#define MYSQL_PORT MARIADB_PORT -#endif - -#define MYSQL_CONFIG_NAME "my" -#define MYSQL_VERSION_ID 100507 -#define MYSQL_SERVER_VERSION "10.5.7-MariaDB" - -#define MARIADB_PACKAGE_VERSION "3.1.11" -#define MARIADB_PACKAGE_VERSION_ID 30111 -#define MARIADB_SYSTEM_TYPE "Windows" -#define MARIADB_MACHINE_TYPE "AMD64" -#define MARIADB_PLUGINDIR "C:/Program Files (x86)/MySQL/lib/plugin" - -/* mysqld compile time options */ -#ifndef MYSQL_CHARSET -#define MYSQL_CHARSET "" -#endif -#endif - -/* Source information */ -#define CC_SOURCE_REVISION "" - -#endif /* _mariadb_version_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/my_config.h b/VCMP-LUA/modules/mariadb/include/mysql/my_config.h deleted file mode 100644 index fc62b0b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/my_config.h +++ /dev/null @@ -1,4 +0,0 @@ -/* Do not edit this file directly, it was auto-generated by cmake */ - -#warning This file should not be included by clients, include only - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/my_global.h b/VCMP-LUA/modules/mariadb/include/mysql/my_global.h deleted file mode 100644 index fc62b0b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/my_global.h +++ /dev/null @@ -1,4 +0,0 @@ -/* Do not edit this file directly, it was auto-generated by cmake */ - -#warning This file should not be included by clients, include only - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/my_sys.h b/VCMP-LUA/modules/mariadb/include/mysql/my_sys.h deleted file mode 100644 index fc62b0b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/my_sys.h +++ /dev/null @@ -1,4 +0,0 @@ -/* Do not edit this file directly, it was auto-generated by cmake */ - -#warning This file should not be included by clients, include only - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mysql.h b/VCMP-LUA/modules/mariadb/include/mysql/mysql.h deleted file mode 100644 index 5174e07..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mysql.h +++ /dev/null @@ -1,891 +0,0 @@ -/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB - 2012 by MontyProgram AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ - -/* defines for the libmariadb library */ - -#ifndef _mysql_h -#define _mysql_h - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef LIBMARIADB -#define LIBMARIADB -#endif -#ifndef MYSQL_CLIENT -#define MYSQL_CLIENT -#endif - -#include - -#if !defined (_global_h) && !defined (MY_GLOBAL_INCLUDED) /* If not standard header */ -#include -typedef char my_bool; -typedef unsigned long long my_ulonglong; - -#if !defined(_WIN32) -#define STDCALL -#else -#define STDCALL __stdcall -#endif - -#ifndef my_socket_defined -#define my_socket_defined -#if defined(_WIN64) -#define my_socket unsigned long long -#elif defined(_WIN32) -#define my_socket unsigned int -#else -typedef int my_socket; -#endif -#endif -#endif -#include "mariadb_com.h" -#include "mariadb_version.h" -#include "ma_list.h" -#include "mariadb_ctype.h" - - -typedef struct st_ma_const_string -{ - const char *str; - size_t length; -} MARIADB_CONST_STRING; - - -#ifndef ST_MA_USED_MEM_DEFINED -#define ST_MA_USED_MEM_DEFINED - typedef struct st_ma_used_mem { /* struct for once_alloc */ - struct st_ma_used_mem *next; /* Next block in use */ - size_t left; /* memory left in block */ - size_t size; /* Size of block */ - } MA_USED_MEM; - - typedef struct st_ma_mem_root { - MA_USED_MEM *free; - MA_USED_MEM *used; - MA_USED_MEM *pre_alloc; - size_t min_malloc; - size_t block_size; - unsigned int block_num; - unsigned int first_block_usage; - void (*error_handler)(void); - } MA_MEM_ROOT; -#endif - -extern unsigned int mysql_port; -extern char *mysql_unix_port; -extern unsigned int mariadb_deinitialize_ssl; - -#define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG) -#define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG) -#define IS_BLOB(n) ((n) & BLOB_FLAG) -#define IS_NUM(t) (((t) <= MYSQL_TYPE_INT24 && (t) != MYSQL_TYPE_TIMESTAMP) || (t) == MYSQL_TYPE_YEAR || (t) == MYSQL_TYPE_NEWDECIMAL) -#define IS_NUM_FIELD(f) ((f)->flags & NUM_FLAG) -#define INTERNAL_NUM_FIELD(f) (((f)->type <= MYSQL_TYPE_INT24 && ((f)->type != MYSQL_TYPE_TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == MYSQL_TYPE_YEAR || (f)->type == MYSQL_TYPE_NEWDECIMAL || (f)->type == MYSQL_TYPE_DECIMAL) - - typedef struct st_mysql_field { - char *name; /* Name of column */ - char *org_name; /* Name of original column (added after 3.23.58) */ - char *table; /* Table of column if column was a field */ - char *org_table; /* Name of original table (added after 3.23.58 */ - char *db; /* table schema (added after 3.23.58) */ - char *catalog; /* table catalog (added after 3.23.58) */ - char *def; /* Default value (set by mysql_list_fields) */ - unsigned long length; /* Width of column */ - unsigned long max_length; /* Max width of selected set */ - /* added after 3.23.58 */ - unsigned int name_length; - unsigned int org_name_length; - unsigned int table_length; - unsigned int org_table_length; - unsigned int db_length; - unsigned int catalog_length; - unsigned int def_length; - /***********************/ - unsigned int flags; /* Div flags */ - unsigned int decimals; /* Number of decimals in field */ - unsigned int charsetnr; /* char set number (added in 4.1) */ - enum enum_field_types type; /* Type of field. Se mysql_com.h for types */ - void *extension; /* added in 4.1 */ - } MYSQL_FIELD; - - typedef char **MYSQL_ROW; /* return data as array of strings */ - typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */ - -#define SET_CLIENT_ERROR(a, b, c, d) \ - do { \ - (a)->net.last_errno= (b);\ - strncpy((a)->net.sqlstate, (c), SQLSTATE_LENGTH);\ - (a)->net.sqlstate[SQLSTATE_LENGTH]= 0;\ - strncpy((a)->net.last_error, (d) ? (d) : ER((b)), MYSQL_ERRMSG_SIZE - 1);\ - (a)->net.last_error[MYSQL_ERRMSG_SIZE - 1]= 0;\ - } while(0) - -/* For mysql_async.c */ -#define set_mariadb_error(A,B,C) SET_CLIENT_ERROR((A),(B),(C),0) -extern const char *SQLSTATE_UNKNOWN; -#define unknown_sqlstate SQLSTATE_UNKNOWN - -#define CLEAR_CLIENT_ERROR(a) \ - do { \ - (a)->net.last_errno= 0;\ - strcpy((a)->net.sqlstate, "00000");\ - (a)->net.last_error[0]= '\0';\ - if ((a)->net.extension)\ - (a)->net.extension->extended_errno= 0;\ - } while (0) - -#define MYSQL_COUNT_ERROR (~(unsigned long long) 0) - - - typedef struct st_mysql_rows { - struct st_mysql_rows *next; /* list of rows */ - MYSQL_ROW data; - unsigned long length; - } MYSQL_ROWS; - - typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */ - - typedef struct st_mysql_data { - MYSQL_ROWS *data; - void *embedded_info; - MA_MEM_ROOT alloc; - unsigned long long rows; - unsigned int fields; - void *extension; - } MYSQL_DATA; - - enum mysql_option - { - MYSQL_OPT_CONNECT_TIMEOUT, - MYSQL_OPT_COMPRESS, - MYSQL_OPT_NAMED_PIPE, - MYSQL_INIT_COMMAND, - MYSQL_READ_DEFAULT_FILE, - MYSQL_READ_DEFAULT_GROUP, - MYSQL_SET_CHARSET_DIR, - MYSQL_SET_CHARSET_NAME, - MYSQL_OPT_LOCAL_INFILE, - MYSQL_OPT_PROTOCOL, - MYSQL_SHARED_MEMORY_BASE_NAME, - MYSQL_OPT_READ_TIMEOUT, - MYSQL_OPT_WRITE_TIMEOUT, - MYSQL_OPT_USE_RESULT, - MYSQL_OPT_USE_REMOTE_CONNECTION, - MYSQL_OPT_USE_EMBEDDED_CONNECTION, - MYSQL_OPT_GUESS_CONNECTION, - MYSQL_SET_CLIENT_IP, - MYSQL_SECURE_AUTH, - MYSQL_REPORT_DATA_TRUNCATION, - MYSQL_OPT_RECONNECT, - MYSQL_OPT_SSL_VERIFY_SERVER_CERT, - MYSQL_PLUGIN_DIR, - MYSQL_DEFAULT_AUTH, - MYSQL_OPT_BIND, - MYSQL_OPT_SSL_KEY, - MYSQL_OPT_SSL_CERT, - MYSQL_OPT_SSL_CA, - MYSQL_OPT_SSL_CAPATH, - MYSQL_OPT_SSL_CIPHER, - MYSQL_OPT_SSL_CRL, - MYSQL_OPT_SSL_CRLPATH, - /* Connection attribute options */ - MYSQL_OPT_CONNECT_ATTR_RESET, - MYSQL_OPT_CONNECT_ATTR_ADD, - MYSQL_OPT_CONNECT_ATTR_DELETE, - MYSQL_SERVER_PUBLIC_KEY, - MYSQL_ENABLE_CLEARTEXT_PLUGIN, - MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, - MYSQL_OPT_SSL_ENFORCE, - MYSQL_OPT_MAX_ALLOWED_PACKET, - MYSQL_OPT_NET_BUFFER_LENGTH, - MYSQL_OPT_TLS_VERSION, - - /* MariaDB specific */ - MYSQL_PROGRESS_CALLBACK=5999, - MYSQL_OPT_NONBLOCK, - /* MariaDB Connector/C specific */ - MYSQL_DATABASE_DRIVER=7000, - MARIADB_OPT_SSL_FP, /* deprecated, use MARIADB_OPT_TLS_PEER_FP instead */ - MARIADB_OPT_SSL_FP_LIST, /* deprecated, use MARIADB_OPT_TLS_PEER_FP_LIST instead */ - MARIADB_OPT_TLS_PASSPHRASE, /* passphrase for encrypted certificates */ - MARIADB_OPT_TLS_CIPHER_STRENGTH, - MARIADB_OPT_TLS_VERSION, - MARIADB_OPT_TLS_PEER_FP, /* single finger print for server certificate verification */ - MARIADB_OPT_TLS_PEER_FP_LIST, /* finger print white list for server certificate verification */ - MARIADB_OPT_CONNECTION_READ_ONLY, - MYSQL_OPT_CONNECT_ATTRS, /* for mysql_get_optionv */ - MARIADB_OPT_USERDATA, - MARIADB_OPT_CONNECTION_HANDLER, - MARIADB_OPT_PORT, - MARIADB_OPT_UNIXSOCKET, - MARIADB_OPT_PASSWORD, - MARIADB_OPT_HOST, - MARIADB_OPT_USER, - MARIADB_OPT_SCHEMA, - MARIADB_OPT_DEBUG, - MARIADB_OPT_FOUND_ROWS, - MARIADB_OPT_MULTI_RESULTS, - MARIADB_OPT_MULTI_STATEMENTS, - MARIADB_OPT_INTERACTIVE, - MARIADB_OPT_PROXY_HEADER, - MARIADB_OPT_IO_WAIT - }; - - enum mariadb_value { - MARIADB_CHARSET_ID, - MARIADB_CHARSET_NAME, - MARIADB_CLIENT_ERRORS, - MARIADB_CLIENT_VERSION, - MARIADB_CLIENT_VERSION_ID, - MARIADB_CONNECTION_ASYNC_TIMEOUT, - MARIADB_CONNECTION_ASYNC_TIMEOUT_MS, - MARIADB_CONNECTION_MARIADB_CHARSET_INFO, - MARIADB_CONNECTION_ERROR, - MARIADB_CONNECTION_ERROR_ID, - MARIADB_CONNECTION_HOST, - MARIADB_CONNECTION_INFO, - MARIADB_CONNECTION_PORT, - MARIADB_CONNECTION_PROTOCOL_VERSION_ID, - MARIADB_CONNECTION_PVIO_TYPE, - MARIADB_CONNECTION_SCHEMA, - MARIADB_CONNECTION_SERVER_TYPE, - MARIADB_CONNECTION_SERVER_VERSION, - MARIADB_CONNECTION_SERVER_VERSION_ID, - MARIADB_CONNECTION_SOCKET, - MARIADB_CONNECTION_SQLSTATE, - MARIADB_CONNECTION_SSL_CIPHER, - MARIADB_TLS_LIBRARY, - MARIADB_CONNECTION_TLS_VERSION, - MARIADB_CONNECTION_TLS_VERSION_ID, - MARIADB_CONNECTION_TYPE, - MARIADB_CONNECTION_UNIX_SOCKET, - MARIADB_CONNECTION_USER, - MARIADB_MAX_ALLOWED_PACKET, - MARIADB_NET_BUFFER_LENGTH, - MARIADB_CONNECTION_SERVER_STATUS, - MARIADB_CONNECTION_SERVER_CAPABILITIES, - MARIADB_CONNECTION_EXTENDED_SERVER_CAPABILITIES, - MARIADB_CONNECTION_CLIENT_CAPABILITIES - }; - - enum mysql_status { MYSQL_STATUS_READY, - MYSQL_STATUS_GET_RESULT, - MYSQL_STATUS_USE_RESULT, - MYSQL_STATUS_QUERY_SENT, - MYSQL_STATUS_SENDING_LOAD_DATA, - MYSQL_STATUS_FETCHING_DATA, - MYSQL_STATUS_NEXT_RESULT_PENDING, - MYSQL_STATUS_QUIT_SENT, /* object is "destroyed" at this stage */ - MYSQL_STATUS_STMT_RESULT - }; - - enum mysql_protocol_type - { - MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET, - MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY - }; - -struct st_mysql_options { - unsigned int connect_timeout, read_timeout, write_timeout; - unsigned int port, protocol; - unsigned long client_flag; - char *host,*user,*password,*unix_socket,*db; - struct st_dynamic_array *init_command; - char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name; - char *ssl_key; /* PEM key file */ - char *ssl_cert; /* PEM cert file */ - char *ssl_ca; /* PEM CA file */ - char *ssl_capath; /* PEM directory of CA-s? */ - char *ssl_cipher; - char *shared_memory_base_name; - unsigned long max_allowed_packet; - my_bool use_ssl; /* if to use SSL or not */ - my_bool compress,named_pipe; - my_bool reconnect, unused_1, unused_2, unused_3; - enum mysql_option methods_to_use; - char *bind_address; - my_bool secure_auth; - my_bool report_data_truncation; - /* function pointers for local infile support */ - int (*local_infile_init)(void **, const char *, void *); - int (*local_infile_read)(void *, char *, unsigned int); - void (*local_infile_end)(void *); - int (*local_infile_error)(void *, char *, unsigned int); - void *local_infile_userdata; - struct st_mysql_options_extension *extension; -}; - - typedef struct st_mysql { - NET net; /* Communication parameters */ - void *unused_0; - char *host,*user,*passwd,*unix_socket,*server_version,*host_info; - char *info,*db; - const struct ma_charset_info_st *charset; /* character set */ - MYSQL_FIELD *fields; - MA_MEM_ROOT field_alloc; - unsigned long long affected_rows; - unsigned long long insert_id; /* id if insert on table with NEXTNR */ - unsigned long long extra_info; /* Used by mysqlshow */ - unsigned long thread_id; /* Id for connection in server */ - unsigned long packet_length; - unsigned int port; - unsigned long client_flag; - unsigned long server_capabilities; - unsigned int protocol_version; - unsigned int field_count; - unsigned int server_status; - unsigned int server_language; - unsigned int warning_count; /* warning count, added in 4.1 protocol */ - struct st_mysql_options options; - enum mysql_status status; - my_bool free_me; /* If free in mysql_close */ - my_bool unused_1; - char scramble_buff[20+ 1]; - /* madded after 3.23.58 */ - my_bool unused_2; - void *unused_3, *unused_4, *unused_5, *unused_6; - LIST *stmts; - const struct st_mariadb_methods *methods; - void *thd; - my_bool *unbuffered_fetch_owner; - char *info_buffer; - struct st_mariadb_extension *extension; -} MYSQL; - -typedef struct st_mysql_res { - unsigned long long row_count; - unsigned int field_count, current_field; - MYSQL_FIELD *fields; - MYSQL_DATA *data; - MYSQL_ROWS *data_cursor; - MA_MEM_ROOT field_alloc; - MYSQL_ROW row; /* If unbuffered read */ - MYSQL_ROW current_row; /* buffer to current row */ - unsigned long *lengths; /* column lengths of current row */ - MYSQL *handle; /* for unbuffered reads */ - my_bool eof; /* Used my mysql_fetch_row */ - my_bool is_ps; -} MYSQL_RES; - -typedef struct -{ - unsigned long *p_max_allowed_packet; - unsigned long *p_net_buffer_length; - void *extension; -} MYSQL_PARAMETERS; - - -enum mariadb_field_attr_t -{ - MARIADB_FIELD_ATTR_DATA_TYPE_NAME= 0, - MARIADB_FIELD_ATTR_FORMAT_NAME= 1 -}; - -#define MARIADB_FIELD_ATTR_LAST MARIADB_FIELD_ATTR_FORMAT_NAME - - -int STDCALL mariadb_field_attr(MARIADB_CONST_STRING *attr, - const MYSQL_FIELD *field, - enum mariadb_field_attr_t type); - -#ifndef _mysql_time_h_ -enum enum_mysql_timestamp_type -{ - MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1, - MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2 -}; - -typedef struct st_mysql_time -{ - unsigned int year, month, day, hour, minute, second; - unsigned long second_part; - my_bool neg; - enum enum_mysql_timestamp_type time_type; -} MYSQL_TIME; -#define AUTO_SEC_PART_DIGITS 39 -#endif - -#define SEC_PART_DIGITS 6 -#define MARIADB_INVALID_SOCKET -1 - -/* Ansynchronous API constants */ -#define MYSQL_WAIT_READ 1 -#define MYSQL_WAIT_WRITE 2 -#define MYSQL_WAIT_EXCEPT 4 -#define MYSQL_WAIT_TIMEOUT 8 - -typedef struct character_set -{ - unsigned int number; /* character set number */ - unsigned int state; /* character set state */ - const char *csname; /* character set name */ - const char *name; /* collation name */ - const char *comment; /* comment */ - const char *dir; /* character set directory */ - unsigned int mbminlen; /* min. length for multibyte strings */ - unsigned int mbmaxlen; /* max. length for multibyte strings */ -} MY_CHARSET_INFO; - -/* Local infile support functions */ -#define LOCAL_INFILE_ERROR_LEN 512 - -#include "mariadb_stmt.h" - -#ifndef MYSQL_CLIENT_PLUGIN_HEADER -#define MYSQL_CLIENT_PLUGIN_HEADER \ - int type; \ - unsigned int interface_version; \ - const char *name; \ - const char *author; \ - const char *desc; \ - unsigned int version[3]; \ - const char *license; \ - void *mysql_api; \ - int (*init)(char *, size_t, int, va_list); \ - int (*deinit)(void); \ - int (*options)(const char *option, const void *); -struct st_mysql_client_plugin -{ - MYSQL_CLIENT_PLUGIN_HEADER -}; - -struct st_mysql_client_plugin * -mysql_load_plugin(struct st_mysql *mysql, const char *name, int type, - int argc, ...); -struct st_mysql_client_plugin * STDCALL -mysql_load_plugin_v(struct st_mysql *mysql, const char *name, int type, - int argc, va_list args); -struct st_mysql_client_plugin * STDCALL -mysql_client_find_plugin(struct st_mysql *mysql, const char *name, int type); -struct st_mysql_client_plugin * STDCALL -mysql_client_register_plugin(struct st_mysql *mysql, - struct st_mysql_client_plugin *plugin); -#endif - - -void STDCALL mysql_set_local_infile_handler(MYSQL *mysql, - int (*local_infile_init)(void **, const char *, void *), - int (*local_infile_read)(void *, char *, unsigned int), - void (*local_infile_end)(void *), - int (*local_infile_error)(void *, char*, unsigned int), - void *); - -void mysql_set_local_infile_default(MYSQL *mysql); - -void my_set_error(MYSQL *mysql, unsigned int error_nr, - const char *sqlstate, const char *format, ...); -/* Functions to get information from the MYSQL and MYSQL_RES structures */ -/* Should definitely be used if one uses shared libraries */ - -my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res); -unsigned int STDCALL mysql_num_fields(MYSQL_RES *res); -my_bool STDCALL mysql_eof(MYSQL_RES *res); -MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res, - unsigned int fieldnr); -MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res); -MYSQL_ROWS * STDCALL mysql_row_tell(MYSQL_RES *res); -unsigned int STDCALL mysql_field_tell(MYSQL_RES *res); - -unsigned int STDCALL mysql_field_count(MYSQL *mysql); -my_bool STDCALL mysql_more_results(MYSQL *mysql); -int STDCALL mysql_next_result(MYSQL *mysql); -my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql); -my_bool STDCALL mysql_autocommit(MYSQL *mysql, my_bool mode); -my_bool STDCALL mysql_commit(MYSQL *mysql); -my_bool STDCALL mysql_rollback(MYSQL *mysql); -my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql); -unsigned int STDCALL mysql_errno(MYSQL *mysql); -const char * STDCALL mysql_error(MYSQL *mysql); -const char * STDCALL mysql_info(MYSQL *mysql); -unsigned long STDCALL mysql_thread_id(MYSQL *mysql); -const char * STDCALL mysql_character_set_name(MYSQL *mysql); -void STDCALL mysql_get_character_set_info(MYSQL *mysql, MY_CHARSET_INFO *cs); -int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname); - -my_bool mariadb_get_infov(MYSQL *mysql, enum mariadb_value value, void *arg, ...); -my_bool STDCALL mariadb_get_info(MYSQL *mysql, enum mariadb_value value, void *arg); -MYSQL * STDCALL mysql_init(MYSQL *mysql); -int STDCALL mysql_ssl_set(MYSQL *mysql, const char *key, - const char *cert, const char *ca, - const char *capath, const char *cipher); -const char * STDCALL mysql_get_ssl_cipher(MYSQL *mysql); -my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user, - const char *passwd, const char *db); -MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host, - const char *user, - const char *passwd, - const char *db, - unsigned int port, - const char *unix_socket, - unsigned long clientflag); -void STDCALL mysql_close(MYSQL *sock); -int STDCALL mysql_select_db(MYSQL *mysql, const char *db); -int STDCALL mysql_query(MYSQL *mysql, const char *q); -int STDCALL mysql_send_query(MYSQL *mysql, const char *q, - unsigned long length); -my_bool STDCALL mysql_read_query_result(MYSQL *mysql); -int STDCALL mysql_real_query(MYSQL *mysql, const char *q, - unsigned long length); -int STDCALL mysql_shutdown(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level); -int STDCALL mysql_dump_debug_info(MYSQL *mysql); -int STDCALL mysql_refresh(MYSQL *mysql, - unsigned int refresh_options); -int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid); -int STDCALL mysql_ping(MYSQL *mysql); -char * STDCALL mysql_stat(MYSQL *mysql); -char * STDCALL mysql_get_server_info(MYSQL *mysql); -unsigned long STDCALL mysql_get_server_version(MYSQL *mysql); -char * STDCALL mysql_get_host_info(MYSQL *mysql); -unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql); -MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild); -MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild); -MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table, - const char *wild); -MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql); -MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql); -MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql); -int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option, - const void *arg); -int STDCALL mysql_options4(MYSQL *mysql,enum mysql_option option, - const void *arg1, const void *arg2); -void STDCALL mysql_free_result(MYSQL_RES *result); -void STDCALL mysql_data_seek(MYSQL_RES *result, - unsigned long long offset); -MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET); -MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result, - MYSQL_FIELD_OFFSET offset); -MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); -unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result); -MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result); -unsigned long STDCALL mysql_escape_string(char *to,const char *from, - unsigned long from_length); -unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql, - char *to,const char *from, - unsigned long length); -unsigned int STDCALL mysql_thread_safe(void); -unsigned int STDCALL mysql_warning_count(MYSQL *mysql); -const char * STDCALL mysql_sqlstate(MYSQL *mysql); -int STDCALL mysql_server_init(int argc, char **argv, char **groups); -void STDCALL mysql_server_end(void); -void STDCALL mysql_thread_end(void); -my_bool STDCALL mysql_thread_init(void); -int STDCALL mysql_set_server_option(MYSQL *mysql, - enum enum_mysql_set_option option); -const char * STDCALL mysql_get_client_info(void); -unsigned long STDCALL mysql_get_client_version(void); -my_bool STDCALL mariadb_connection(MYSQL *mysql); -const char * STDCALL mysql_get_server_name(MYSQL *mysql); -MARIADB_CHARSET_INFO * STDCALL mariadb_get_charset_by_name(const char *csname); -MARIADB_CHARSET_INFO * STDCALL mariadb_get_charset_by_nr(unsigned int csnr); -size_t STDCALL mariadb_convert_string(const char *from, size_t *from_len, MARIADB_CHARSET_INFO *from_cs, - char *to, size_t *to_len, MARIADB_CHARSET_INFO *to_cs, int *errorcode); -int mysql_optionsv(MYSQL *mysql,enum mysql_option option, ...); -int mysql_get_optionv(MYSQL *mysql, enum mysql_option option, void *arg, ...); -int STDCALL mysql_get_option(MYSQL *mysql, enum mysql_option option, void *arg); -unsigned long STDCALL mysql_hex_string(char *to, const char *from, unsigned long len); -my_socket STDCALL mysql_get_socket(MYSQL *mysql); -unsigned int STDCALL mysql_get_timeout_value(const MYSQL *mysql); -unsigned int STDCALL mysql_get_timeout_value_ms(const MYSQL *mysql); -my_bool STDCALL mariadb_reconnect(MYSQL *mysql); -int STDCALL mariadb_cancel(MYSQL *mysql); -void STDCALL mysql_debug(const char *debug); -unsigned long STDCALL mysql_net_read_packet(MYSQL *mysql); -unsigned long STDCALL mysql_net_field_length(unsigned char **packet); -my_bool STDCALL mysql_embedded(void); -MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void); - -/* Async API */ -int STDCALL mysql_close_start(MYSQL *sock); -int STDCALL mysql_close_cont(MYSQL *sock, int status); -int STDCALL mysql_commit_start(my_bool *ret, MYSQL * mysql); -int STDCALL mysql_commit_cont(my_bool *ret, MYSQL * mysql, int status); -int STDCALL mysql_dump_debug_info_cont(int *ret, MYSQL *mysql, int ready_status); -int STDCALL mysql_dump_debug_info_start(int *ret, MYSQL *mysql); -int STDCALL mysql_rollback_start(my_bool *ret, MYSQL * mysql); -int STDCALL mysql_rollback_cont(my_bool *ret, MYSQL * mysql, int status); -int STDCALL mysql_autocommit_start(my_bool *ret, MYSQL * mysql, - my_bool auto_mode); -int STDCALL mysql_list_fields_cont(MYSQL_RES **ret, MYSQL *mysql, int ready_status); -int STDCALL mysql_list_fields_start(MYSQL_RES **ret, MYSQL *mysql, const char *table, - const char *wild); -int STDCALL mysql_autocommit_cont(my_bool *ret, MYSQL * mysql, int status); -int STDCALL mysql_next_result_start(int *ret, MYSQL *mysql); -int STDCALL mysql_next_result_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_select_db_start(int *ret, MYSQL *mysql, const char *db); -int STDCALL mysql_select_db_cont(int *ret, MYSQL *mysql, int ready_status); -int STDCALL mysql_stmt_warning_count(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_next_result_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_next_result_cont(int *ret, MYSQL_STMT *stmt, int status); - -int STDCALL mysql_set_character_set_start(int *ret, MYSQL *mysql, - const char *csname); -int STDCALL mysql_set_character_set_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_change_user_start(my_bool *ret, MYSQL *mysql, - const char *user, - const char *passwd, - const char *db); -int STDCALL mysql_change_user_cont(my_bool *ret, MYSQL *mysql, - int status); -int STDCALL mysql_real_connect_start(MYSQL **ret, MYSQL *mysql, - const char *host, - const char *user, - const char *passwd, - const char *db, - unsigned int port, - const char *unix_socket, - unsigned long clientflag); -int STDCALL mysql_real_connect_cont(MYSQL **ret, MYSQL *mysql, - int status); -int STDCALL mysql_query_start(int *ret, MYSQL *mysql, - const char *q); -int STDCALL mysql_query_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_send_query_start(int *ret, MYSQL *mysql, - const char *q, - unsigned long length); -int STDCALL mysql_send_query_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_real_query_start(int *ret, MYSQL *mysql, - const char *q, - unsigned long length); -int STDCALL mysql_real_query_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_store_result_start(MYSQL_RES **ret, MYSQL *mysql); -int STDCALL mysql_store_result_cont(MYSQL_RES **ret, MYSQL *mysql, - int status); -int STDCALL mysql_shutdown_start(int *ret, MYSQL *mysql, - enum mysql_enum_shutdown_level - shutdown_level); -int STDCALL mysql_shutdown_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_refresh_start(int *ret, MYSQL *mysql, - unsigned int refresh_options); -int STDCALL mysql_refresh_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_kill_start(int *ret, MYSQL *mysql, - unsigned long pid); -int STDCALL mysql_kill_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_set_server_option_start(int *ret, MYSQL *mysql, - enum enum_mysql_set_option - option); -int STDCALL mysql_set_server_option_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_ping_start(int *ret, MYSQL *mysql); -int STDCALL mysql_ping_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_stat_start(const char **ret, MYSQL *mysql); -int STDCALL mysql_stat_cont(const char **ret, MYSQL *mysql, - int status); -int STDCALL mysql_free_result_start(MYSQL_RES *result); -int STDCALL mysql_free_result_cont(MYSQL_RES *result, int status); -int STDCALL mysql_fetch_row_start(MYSQL_ROW *ret, - MYSQL_RES *result); -int STDCALL mysql_fetch_row_cont(MYSQL_ROW *ret, MYSQL_RES *result, - int status); -int STDCALL mysql_read_query_result_start(my_bool *ret, - MYSQL *mysql); -int STDCALL mysql_read_query_result_cont(my_bool *ret, - MYSQL *mysql, int status); -int STDCALL mysql_reset_connection_start(int *ret, MYSQL *mysql); -int STDCALL mysql_reset_connection_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_session_track_get_next(MYSQL *mysql, enum enum_session_state_type type, const char **data, size_t *length); -int STDCALL mysql_session_track_get_first(MYSQL *mysql, enum enum_session_state_type type, const char **data, size_t *length); -int STDCALL mysql_stmt_prepare_start(int *ret, MYSQL_STMT *stmt,const char *query, unsigned long length); -int STDCALL mysql_stmt_prepare_cont(int *ret, MYSQL_STMT *stmt, int status); -int STDCALL mysql_stmt_execute_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_execute_cont(int *ret, MYSQL_STMT *stmt, int status); -int STDCALL mysql_stmt_fetch_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_fetch_cont(int *ret, MYSQL_STMT *stmt, int status); -int STDCALL mysql_stmt_store_result_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_store_result_cont(int *ret, MYSQL_STMT *stmt,int status); -int STDCALL mysql_stmt_close_start(my_bool *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_close_cont(my_bool *ret, MYSQL_STMT * stmt, int status); -int STDCALL mysql_stmt_reset_start(my_bool *ret, MYSQL_STMT * stmt); -int STDCALL mysql_stmt_reset_cont(my_bool *ret, MYSQL_STMT *stmt, int status); -int STDCALL mysql_stmt_free_result_start(my_bool *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_free_result_cont(my_bool *ret, MYSQL_STMT *stmt, - int status); -int STDCALL mysql_stmt_send_long_data_start(my_bool *ret, MYSQL_STMT *stmt, - unsigned int param_number, - const char *data, - unsigned long len); -int STDCALL mysql_stmt_send_long_data_cont(my_bool *ret, MYSQL_STMT *stmt, - int status); -int STDCALL mysql_reset_connection(MYSQL *mysql); - -/* API function calls (used by dynmic plugins) */ -struct st_mariadb_api { - unsigned long long (STDCALL *mysql_num_rows)(MYSQL_RES *res); - unsigned int (STDCALL *mysql_num_fields)(MYSQL_RES *res); - my_bool (STDCALL *mysql_eof)(MYSQL_RES *res); - MYSQL_FIELD *(STDCALL *mysql_fetch_field_direct)(MYSQL_RES *res, unsigned int fieldnr); - MYSQL_FIELD * (STDCALL *mysql_fetch_fields)(MYSQL_RES *res); - MYSQL_ROWS * (STDCALL *mysql_row_tell)(MYSQL_RES *res); - unsigned int (STDCALL *mysql_field_tell)(MYSQL_RES *res); - unsigned int (STDCALL *mysql_field_count)(MYSQL *mysql); - my_bool (STDCALL *mysql_more_results)(MYSQL *mysql); - int (STDCALL *mysql_next_result)(MYSQL *mysql); - unsigned long long (STDCALL *mysql_affected_rows)(MYSQL *mysql); - my_bool (STDCALL *mysql_autocommit)(MYSQL *mysql, my_bool mode); - my_bool (STDCALL *mysql_commit)(MYSQL *mysql); - my_bool (STDCALL *mysql_rollback)(MYSQL *mysql); - unsigned long long (STDCALL *mysql_insert_id)(MYSQL *mysql); - unsigned int (STDCALL *mysql_errno)(MYSQL *mysql); - const char * (STDCALL *mysql_error)(MYSQL *mysql); - const char * (STDCALL *mysql_info)(MYSQL *mysql); - unsigned long (STDCALL *mysql_thread_id)(MYSQL *mysql); - const char * (STDCALL *mysql_character_set_name)(MYSQL *mysql); - void (STDCALL *mysql_get_character_set_info)(MYSQL *mysql, MY_CHARSET_INFO *cs); - int (STDCALL *mysql_set_character_set)(MYSQL *mysql, const char *csname); - my_bool (*mariadb_get_infov)(MYSQL *mysql, enum mariadb_value value, void *arg, ...); - my_bool (STDCALL *mariadb_get_info)(MYSQL *mysql, enum mariadb_value value, void *arg); - MYSQL * (STDCALL *mysql_init)(MYSQL *mysql); - int (STDCALL *mysql_ssl_set)(MYSQL *mysql, const char *key, const char *cert, const char *ca, const char *capath, const char *cipher); - const char * (STDCALL *mysql_get_ssl_cipher)(MYSQL *mysql); - my_bool (STDCALL *mysql_change_user)(MYSQL *mysql, const char *user, const char *passwd, const char *db); - MYSQL * (STDCALL *mysql_real_connect)(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); - void (STDCALL *mysql_close)(MYSQL *sock); - int (STDCALL *mysql_select_db)(MYSQL *mysql, const char *db); - int (STDCALL *mysql_query)(MYSQL *mysql, const char *q); - int (STDCALL *mysql_send_query)(MYSQL *mysql, const char *q, unsigned long length); - my_bool (STDCALL *mysql_read_query_result)(MYSQL *mysql); - int (STDCALL *mysql_real_query)(MYSQL *mysql, const char *q, unsigned long length); - int (STDCALL *mysql_shutdown)(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level); - int (STDCALL *mysql_dump_debug_info)(MYSQL *mysql); - int (STDCALL *mysql_refresh)(MYSQL *mysql, unsigned int refresh_options); - int (STDCALL *mysql_kill)(MYSQL *mysql,unsigned long pid); - int (STDCALL *mysql_ping)(MYSQL *mysql); - char * (STDCALL *mysql_stat)(MYSQL *mysql); - char * (STDCALL *mysql_get_server_info)(MYSQL *mysql); - unsigned long (STDCALL *mysql_get_server_version)(MYSQL *mysql); - char * (STDCALL *mysql_get_host_info)(MYSQL *mysql); - unsigned int (STDCALL *mysql_get_proto_info)(MYSQL *mysql); - MYSQL_RES * (STDCALL *mysql_list_dbs)(MYSQL *mysql,const char *wild); - MYSQL_RES * (STDCALL *mysql_list_tables)(MYSQL *mysql,const char *wild); - MYSQL_RES * (STDCALL *mysql_list_fields)(MYSQL *mysql, const char *table, const char *wild); - MYSQL_RES * (STDCALL *mysql_list_processes)(MYSQL *mysql); - MYSQL_RES * (STDCALL *mysql_store_result)(MYSQL *mysql); - MYSQL_RES * (STDCALL *mysql_use_result)(MYSQL *mysql); - int (STDCALL *mysql_options)(MYSQL *mysql,enum mysql_option option, const void *arg); - void (STDCALL *mysql_free_result)(MYSQL_RES *result); - void (STDCALL *mysql_data_seek)(MYSQL_RES *result, unsigned long long offset); - MYSQL_ROW_OFFSET (STDCALL *mysql_row_seek)(MYSQL_RES *result, MYSQL_ROW_OFFSET); - MYSQL_FIELD_OFFSET (STDCALL *mysql_field_seek)(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset); - MYSQL_ROW (STDCALL *mysql_fetch_row)(MYSQL_RES *result); - unsigned long * (STDCALL *mysql_fetch_lengths)(MYSQL_RES *result); - MYSQL_FIELD * (STDCALL *mysql_fetch_field)(MYSQL_RES *result); - unsigned long (STDCALL *mysql_escape_string)(char *to,const char *from, unsigned long from_length); - unsigned long (STDCALL *mysql_real_escape_string)(MYSQL *mysql, char *to,const char *from, unsigned long length); - unsigned int (STDCALL *mysql_thread_safe)(void); - unsigned int (STDCALL *mysql_warning_count)(MYSQL *mysql); - const char * (STDCALL *mysql_sqlstate)(MYSQL *mysql); - int (STDCALL *mysql_server_init)(int argc, char **argv, char **groups); - void (STDCALL *mysql_server_end)(void); - void (STDCALL *mysql_thread_end)(void); - my_bool (STDCALL *mysql_thread_init)(void); - int (STDCALL *mysql_set_server_option)(MYSQL *mysql, enum enum_mysql_set_option option); - const char * (STDCALL *mysql_get_client_info)(void); - unsigned long (STDCALL *mysql_get_client_version)(void); - my_bool (STDCALL *mariadb_connection)(MYSQL *mysql); - const char * (STDCALL *mysql_get_server_name)(MYSQL *mysql); - MARIADB_CHARSET_INFO * (STDCALL *mariadb_get_charset_by_name)(const char *csname); - MARIADB_CHARSET_INFO * (STDCALL *mariadb_get_charset_by_nr)(unsigned int csnr); - size_t (STDCALL *mariadb_convert_string)(const char *from, size_t *from_len, MARIADB_CHARSET_INFO *from_cs, char *to, size_t *to_len, MARIADB_CHARSET_INFO *to_cs, int *errorcode); - int (*mysql_optionsv)(MYSQL *mysql,enum mysql_option option, ...); - int (*mysql_get_optionv)(MYSQL *mysql, enum mysql_option option, void *arg, ...); - int (STDCALL *mysql_get_option)(MYSQL *mysql, enum mysql_option option, void *arg); - unsigned long (STDCALL *mysql_hex_string)(char *to, const char *from, unsigned long len); - my_socket (STDCALL *mysql_get_socket)(MYSQL *mysql); - unsigned int (STDCALL *mysql_get_timeout_value)(const MYSQL *mysql); - unsigned int (STDCALL *mysql_get_timeout_value_ms)(const MYSQL *mysql); - my_bool (STDCALL *mariadb_reconnect)(MYSQL *mysql); - MYSQL_STMT * (STDCALL *mysql_stmt_init)(MYSQL *mysql); - int (STDCALL *mysql_stmt_prepare)(MYSQL_STMT *stmt, const char *query, unsigned long length); - int (STDCALL *mysql_stmt_execute)(MYSQL_STMT *stmt); - int (STDCALL *mysql_stmt_fetch)(MYSQL_STMT *stmt); - int (STDCALL *mysql_stmt_fetch_column)(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg, unsigned int column, unsigned long offset); - int (STDCALL *mysql_stmt_store_result)(MYSQL_STMT *stmt); - unsigned long (STDCALL *mysql_stmt_param_count)(MYSQL_STMT * stmt); - my_bool (STDCALL *mysql_stmt_attr_set)(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, const void *attr); - my_bool (STDCALL *mysql_stmt_attr_get)(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, void *attr); - my_bool (STDCALL *mysql_stmt_bind_param)(MYSQL_STMT * stmt, MYSQL_BIND * bnd); - my_bool (STDCALL *mysql_stmt_bind_result)(MYSQL_STMT * stmt, MYSQL_BIND * bnd); - my_bool (STDCALL *mysql_stmt_close)(MYSQL_STMT * stmt); - my_bool (STDCALL *mysql_stmt_reset)(MYSQL_STMT * stmt); - my_bool (STDCALL *mysql_stmt_free_result)(MYSQL_STMT *stmt); - my_bool (STDCALL *mysql_stmt_send_long_data)(MYSQL_STMT *stmt, unsigned int param_number, const char *data, unsigned long length); - MYSQL_RES *(STDCALL *mysql_stmt_result_metadata)(MYSQL_STMT *stmt); - MYSQL_RES *(STDCALL *mysql_stmt_param_metadata)(MYSQL_STMT *stmt); - unsigned int (STDCALL *mysql_stmt_errno)(MYSQL_STMT * stmt); - const char *(STDCALL *mysql_stmt_error)(MYSQL_STMT * stmt); - const char *(STDCALL *mysql_stmt_sqlstate)(MYSQL_STMT * stmt); - MYSQL_ROW_OFFSET (STDCALL *mysql_stmt_row_seek)(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET offset); - MYSQL_ROW_OFFSET (STDCALL *mysql_stmt_row_tell)(MYSQL_STMT *stmt); - void (STDCALL *mysql_stmt_data_seek)(MYSQL_STMT *stmt, unsigned long long offset); - unsigned long long (STDCALL *mysql_stmt_num_rows)(MYSQL_STMT *stmt); - unsigned long long (STDCALL *mysql_stmt_affected_rows)(MYSQL_STMT *stmt); - unsigned long long (STDCALL *mysql_stmt_insert_id)(MYSQL_STMT *stmt); - unsigned int (STDCALL *mysql_stmt_field_count)(MYSQL_STMT *stmt); - int (STDCALL *mysql_stmt_next_result)(MYSQL_STMT *stmt); - my_bool (STDCALL *mysql_stmt_more_results)(MYSQL_STMT *stmt); - int (STDCALL *mariadb_stmt_execute_direct)(MYSQL_STMT *stmt, const char *stmtstr, size_t length); - int (STDCALL *mysql_reset_connection)(MYSQL *mysql); -}; - -/* these methods can be overwritten by db plugins */ -struct st_mariadb_methods { - MYSQL *(*db_connect)(MYSQL *mysql, const char *host, const char *user, const char *passwd, - const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); - void (*db_close)(MYSQL *mysql); - int (*db_command)(MYSQL *mysql,enum enum_server_command command, const char *arg, - size_t length, my_bool skipp_check, void *opt_arg); - void (*db_skip_result)(MYSQL *mysql); - int (*db_read_query_result)(MYSQL *mysql); - MYSQL_DATA *(*db_read_rows)(MYSQL *mysql,MYSQL_FIELD *fields, unsigned int field_count); - int (*db_read_one_row)(MYSQL *mysql,unsigned int fields,MYSQL_ROW row, unsigned long *lengths); - /* prepared statements */ - my_bool (*db_supported_buffer_type)(enum enum_field_types type); - my_bool (*db_read_prepare_response)(MYSQL_STMT *stmt); - int (*db_read_stmt_result)(MYSQL *mysql); - my_bool (*db_stmt_get_result_metadata)(MYSQL_STMT *stmt); - my_bool (*db_stmt_get_param_metadata)(MYSQL_STMT *stmt); - int (*db_stmt_read_all_rows)(MYSQL_STMT *stmt); - int (*db_stmt_fetch)(MYSQL_STMT *stmt, unsigned char **row); - int (*db_stmt_fetch_to_bind)(MYSQL_STMT *stmt, unsigned char *row); - void (*db_stmt_flush_unbuffered)(MYSQL_STMT *stmt); - void (*set_error)(MYSQL *mysql, unsigned int error_nr, const char *sqlstate, const char *format, ...); - void (*invalidate_stmts)(MYSQL *mysql, const char *function_name); - struct st_mariadb_api *api; -}; - -/* synonyms/aliases functions */ -#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT) -#define mysql_library_init mysql_server_init -#define mysql_library_end mysql_server_end - -/* new api functions */ - -#define HAVE_MYSQL_REAL_CONNECT - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mysql/client_plugin.h b/VCMP-LUA/modules/mariadb/include/mysql/mysql/client_plugin.h deleted file mode 100644 index 72939d2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mysql/client_plugin.h +++ /dev/null @@ -1,244 +0,0 @@ -/* Copyright (C) 2010 - 2012 Sergei Golubchik and Monty Program Ab - 2014 MariaDB Corporation AB - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not see - or write to the Free Software Foundation, Inc., - 51 Franklin St., Fifth Floor, Boston, MA 02110, USA */ - -/** - @file - - MySQL Client Plugin API - - This file defines the API for plugins that work on the client side -*/ -#ifndef MYSQL_CLIENT_PLUGIN_INCLUDED -#define MYSQL_CLIENT_PLUGIN_INCLUDED - -#ifndef MYSQL_ABI_CHECK -#include -#include -#endif - - -#ifndef PLUGINDIR -#define PLUGINDIR "lib/plugin" -#endif - -#define plugin_declarations_sym "_mysql_client_plugin_declaration_" - -/* known plugin types */ -#define MYSQL_CLIENT_PLUGIN_RESERVED 0 -#define MYSQL_CLIENT_PLUGIN_RESERVED2 1 -#define MYSQL_CLIENT_AUTHENTICATION_PLUGIN 2 /* authentication */ - -#define MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION 0x0100 -#define MYSQL_CLIENT_MAX_PLUGINS 3 - -/* Connector/C specific plugin types */ -#define MARIADB_CLIENT_REMOTEIO_PLUGIN 100 /* communication IO */ -#define MARIADB_CLIENT_PVIO_PLUGIN 101 -#define MARIADB_CLIENT_TRACE_PLUGIN 102 -#define MARIADB_CLIENT_CONNECTION_PLUGIN 103 - -#define MARIADB_CLIENT_REMOTEIO_PLUGIN_INTERFACE_VERSION 0x0100 -#define MARIADB_CLIENT_PVIO_PLUGIN_INTERFACE_VERSION 0x0100 -#define MARIADB_CLIENT_TRACE_PLUGIN_INTERFACE_VERSION 0x0100 -#define MARIADB_CLIENT_CONNECTION_PLUGIN_INTERFACE_VERSION 0x0100 - -#define MARIADB_CLIENT_MAX_PLUGINS 4 - -#define mysql_declare_client_plugin(X) \ - struct st_mysql_client_plugin_ ## X \ - _mysql_client_plugin_declaration_ = { \ - MYSQL_CLIENT_ ## X ## _PLUGIN, \ - MYSQL_CLIENT_ ## X ## _PLUGIN_INTERFACE_VERSION, -#define mysql_end_client_plugin } - -/* generic plugin header structure */ -#ifndef MYSQL_CLIENT_PLUGIN_HEADER -#define MYSQL_CLIENT_PLUGIN_HEADER \ - int type; \ - unsigned int interface_version; \ - const char *name; \ - const char *author; \ - const char *desc; \ - unsigned int version[3]; \ - const char *license; \ - void *mysql_api; \ - int (*init)(char *, size_t, int, va_list); \ - int (*deinit)(void); \ - int (*options)(const char *option, const void *); -struct st_mysql_client_plugin -{ - MYSQL_CLIENT_PLUGIN_HEADER -}; -#endif - -struct st_mysql; - -/********* connection handler plugin specific declarations **********/ - -typedef struct st_ma_connection_plugin -{ - MYSQL_CLIENT_PLUGIN_HEADER - /* functions */ - MYSQL *(*connect)(MYSQL *mysql, const char *host, - const char *user, const char *passwd, - const char *db, unsigned int port, - const char *unix_socket, unsigned long clientflag); - void (*close)(MYSQL *mysql); - int (*set_optionsv)(MYSQL *mysql, unsigned int option, ...); - int (*set_connection)(MYSQL *mysql,enum enum_server_command command, - const char *arg, - size_t length, my_bool skipp_check, void *opt_arg); - my_bool (*reconnect)(MYSQL *mysql); - int (*reset)(MYSQL *mysql); -} MARIADB_CONNECTION_PLUGIN; - -#define MARIADB_DB_DRIVER(a) ((a)->ext_db) - -/******************* Communication IO plugin *****************/ -#include - -typedef struct st_mariadb_client_plugin_PVIO -{ - MYSQL_CLIENT_PLUGIN_HEADER - struct st_ma_pvio_methods *methods; -} MARIADB_PVIO_PLUGIN; - -/******** authentication plugin specific declarations *********/ -#include - -struct st_mysql_client_plugin_AUTHENTICATION -{ - MYSQL_CLIENT_PLUGIN_HEADER - int (*authenticate_user)(MYSQL_PLUGIN_VIO *vio, struct st_mysql *mysql); -}; - -/******** trace plugin *******/ -struct st_mysql_client_plugin_TRACE -{ - MYSQL_CLIENT_PLUGIN_HEADER -}; - -/** - type of the mysql_authentication_dialog_ask function - - @param mysql mysql - @param type type of the input - 1 - ordinary string input - 2 - password string - @param prompt prompt - @param buf a buffer to store the use input - @param buf_len the length of the buffer - - @retval a pointer to the user input string. - It may be equal to 'buf' or to 'mysql->password'. - In all other cases it is assumed to be an allocated - string, and the "dialog" plugin will free() it. -*/ -typedef char *(*mysql_authentication_dialog_ask_t)(struct st_mysql *mysql, - int type, const char *prompt, char *buf, int buf_len); - -/********************** remote IO plugin **********************/ -#ifdef HAVE_REMOTEIO -#include - -/* Remote IO plugin */ -typedef struct st_mysql_client_plugin_REMOTEIO -{ - MYSQL_CLIENT_PLUGIN_HEADER - struct st_rio_methods *methods; -} MARIADB_REMOTEIO_PLUGIN; -#endif - -/******** using plugins ************/ - -/** - loads a plugin and initializes it - - @param mysql MYSQL structure. only MYSQL_PLUGIN_DIR option value is used, - and last_errno/last_error, for error reporting - @param name a name of the plugin to load - @param type type of plugin that should be loaded, -1 to disable type check - @param argc number of arguments to pass to the plugin initialization - function - @param ... arguments for the plugin initialization function - - @retval - a pointer to the loaded plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * -mysql_load_plugin(struct st_mysql *mysql, const char *name, int type, - int argc, ...); - -/** - loads a plugin and initializes it, taking va_list as an argument - - This is the same as mysql_load_plugin, but take va_list instead of - a list of arguments. - - @param mysql MYSQL structure. only MYSQL_PLUGIN_DIR option value is used, - and last_errno/last_error, for error reporting - @param name a name of the plugin to load - @param type type of plugin that should be loaded, -1 to disable type check - @param argc number of arguments to pass to the plugin initialization - function - @param args arguments for the plugin initialization function - - @retval - a pointer to the loaded plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * STDCALL -mysql_load_plugin_v(struct st_mysql *mysql, const char *name, int type, - int argc, va_list args); - -/** - finds an already loaded plugin by name, or loads it, if necessary - - @param mysql MYSQL structure. only MYSQL_PLUGIN_DIR option value is used, - and last_errno/last_error, for error reporting - @param name a name of the plugin to load - @param type type of plugin that should be loaded - - @retval - a pointer to the plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * STDCALL -mysql_client_find_plugin(struct st_mysql *mysql, const char *name, int type); - -/** - adds a plugin structure to the list of loaded plugins - - This is useful if an application has the necessary functionality - (for example, a special load data handler) statically linked into - the application binary. It can use this function to register the plugin - directly, avoiding the need to factor it out into a shared object. - - @param mysql MYSQL structure. It is only used for error reporting - @param plugin an st_mysql_client_plugin structure to register - - @retval - a pointer to the plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * STDCALL -mysql_client_register_plugin(struct st_mysql *mysql, - struct st_mysql_client_plugin *plugin); - -extern struct st_mysql_client_plugin *mysql_client_builtins[]; - -#endif - - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mysql/plugin_auth.h b/VCMP-LUA/modules/mariadb/include/mysql/mysql/plugin_auth.h deleted file mode 100644 index 2be64a6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mysql/plugin_auth.h +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef MYSQL_PLUGIN_AUTH_COMMON_INCLUDED -/* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ - -/** - @file - - This file defines constants and data structures that are the same for - both client- and server-side authentication plugins. -*/ -#define MYSQL_PLUGIN_AUTH_COMMON_INCLUDED - -/** the max allowed length for a user name */ -#define MYSQL_USERNAME_LENGTH 512 - -/** - return values of the plugin authenticate_user() method. -*/ - -/** - Authentication failed. Additionally, all other CR_xxx values - (libmariadb error code) can be used too. - - The client plugin may set the error code and the error message directly - in the MYSQL structure and return CR_ERROR. If a CR_xxx specific error - code was returned, an error message in the MYSQL structure will be - overwritten. If CR_ERROR is returned without setting the error in MYSQL, - CR_UNKNOWN_ERROR will be user. -*/ -#define CR_ERROR 0 -/** - Authentication (client part) was successful. It does not mean that the - authentication as a whole was successful, usually it only means - that the client was able to send the user name and the password to the - server. If CR_OK is returned, the libmariadb reads the next packet expecting - it to be one of OK, ERROR, or CHANGE_PLUGIN packets. -*/ -#define CR_OK -1 -/** - Authentication was successful. - It means that the client has done its part successfully and also that - a plugin has read the last packet (one of OK, ERROR, CHANGE_PLUGIN). - In this case, libmariadb will not read a packet from the server, - but it will use the data at mysql->net.read_pos. - - A plugin may return this value if the number of roundtrips in the - authentication protocol is not known in advance, and the client plugin - needs to read one packet more to determine if the authentication is finished - or not. -*/ -#define CR_OK_HANDSHAKE_COMPLETE -2 - -typedef struct st_plugin_vio_info -{ - enum { MYSQL_VIO_INVALID, MYSQL_VIO_TCP, MYSQL_VIO_SOCKET, - MYSQL_VIO_PIPE, MYSQL_VIO_MEMORY } protocol; - int socket; /**< it's set, if the protocol is SOCKET or TCP */ -#ifdef _WIN32 - HANDLE handle; /**< it's set, if the protocol is PIPE or MEMORY */ -#endif -} MYSQL_PLUGIN_VIO_INFO; - -/** - Provides plugin access to communication channel -*/ -typedef struct st_plugin_vio -{ - /** - Plugin provides a pointer reference and this function sets it to the - contents of any incoming packet. Returns the packet length, or -1 if - the plugin should terminate. - */ - int (*read_packet)(struct st_plugin_vio *vio, - unsigned char **buf); - - /** - Plugin provides a buffer with data and the length and this - function sends it as a packet. Returns 0 on success, 1 on failure. - */ - int (*write_packet)(struct st_plugin_vio *vio, - const unsigned char *packet, - int packet_len); - - /** - Fills in a st_plugin_vio_info structure, providing the information - about the connection. - */ - void (*info)(struct st_plugin_vio *vio, struct st_plugin_vio_info *info); - -} MYSQL_PLUGIN_VIO; - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mysql/plugin_auth_common.h b/VCMP-LUA/modules/mariadb/include/mysql/mysql/plugin_auth_common.h deleted file mode 100644 index ee4b8b9..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mysql/plugin_auth_common.h +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - MA 02111-1301, USA */ - - -#ifndef MYSQL_PLUGIN_AUTH_COMMON_INCLUDED -/** - @file - - This file defines constants and data structures that are the same for - both client- and server-side authentication plugins. -*/ -#define MYSQL_PLUGIN_AUTH_COMMON_INCLUDED - -/** the max allowed length for a user name */ -#define MYSQL_USERNAME_LENGTH 512 - -/** - return values of the plugin authenticate_user() method. -*/ - -/** - Authentication failed. Additionally, all other CR_xxx values - (libmariadb error code) can be used too. - - The client plugin may set the error code and the error message directly - in the MYSQL structure and return CR_ERROR. If a CR_xxx specific error - code was returned, an error message in the MYSQL structure will be - overwritten. If CR_ERROR is returned without setting the error in MYSQL, - CR_UNKNOWN_ERROR will be user. -*/ -#define CR_ERROR 0 -/** - Authentication (client part) was successful. It does not mean that the - authentication as a whole was successful, usually it only means - that the client was able to send the user name and the password to the - server. If CR_OK is returned, the libmariadb reads the next packet expecting - it to be one of OK, ERROR, or CHANGE_PLUGIN packets. -*/ -#define CR_OK -1 -/** - Authentication was successful. - It means that the client has done its part successfully and also that - a plugin has read the last packet (one of OK, ERROR, CHANGE_PLUGIN). - In this case, libmariadb will not read a packet from the server, - but it will use the data at mysql->net.read_pos. - - A plugin may return this value if the number of roundtrips in the - authentication protocol is not known in advance, and the client plugin - needs to read one packet more to determine if the authentication is finished - or not. -*/ -#define CR_OK_HANDSHAKE_COMPLETE -2 - -typedef struct st_plugin_vio_info -{ - enum { MYSQL_VIO_INVALID, MYSQL_VIO_TCP, MYSQL_VIO_SOCKET, - MYSQL_VIO_PIPE, MYSQL_VIO_MEMORY } protocol; -#ifndef _WIN32 - int socket; /**< it's set, if the protocol is SOCKET or TCP */ -#else - SOCKET socket; /**< it's set, if the protocol is SOCKET or TCP */ - HANDLE handle; /**< it's set, if the protocol is PIPE or MEMORY */ -#endif -} MYSQL_PLUGIN_VIO_INFO; - -/** - Provides plugin access to communication channel -*/ -typedef struct st_plugin_vio -{ - /** - Plugin provides a pointer reference and this function sets it to the - contents of any incoming packet. Returns the packet length, or -1 if - the plugin should terminate. - */ - int (*read_packet)(struct st_plugin_vio *vio, - unsigned char **buf); - - /** - Plugin provides a buffer with data and the length and this - function sends it as a packet. Returns 0 on success, 1 on failure. - */ - int (*write_packet)(struct st_plugin_vio *vio, - const unsigned char *packet, - int packet_len); - - /** - Fills in a st_plugin_vio_info structure, providing the information - about the connection. - */ - void (*info)(struct st_plugin_vio *vio, struct st_plugin_vio_info *info); - -} MYSQL_PLUGIN_VIO; - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mysql_com.h b/VCMP-LUA/modules/mariadb/include/mysql/mysql_com.h deleted file mode 100644 index 09ed396..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mysql_com.h +++ /dev/null @@ -1,6 +0,0 @@ -/* Do not edit this file directly, it was auto-generated by cmake */ - -#warning This file should not be included by clients, include only - -#include - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mysql_version.h b/VCMP-LUA/modules/mariadb/include/mysql/mysql_version.h deleted file mode 100644 index ada3c0d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mysql_version.h +++ /dev/null @@ -1,7 +0,0 @@ -/* Do not edit this file directly, it was auto-generated by cmake */ - -#warning This file should not be included by clients, include only - -#include -#define LIBMYSQL_VERSION MARIADB_CLIENT_VERSION_STR - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/mysqld_error.h b/VCMP-LUA/modules/mariadb/include/mysql/mysqld_error.h deleted file mode 100644 index 04ec2da..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/mysqld_error.h +++ /dev/null @@ -1,1225 +0,0 @@ -/* Autogenerated file, please don't edit */ - -#ifndef ER_ERROR_FIRST -#define ER_ERROR_FIRST 1000 -#define ER_HASHCHK 1000 -#define ER_NISAMCHK 1001 -#define ER_NO 1002 -#define ER_YES 1003 -#define ER_CANT_CREATE_FILE 1004 -#define ER_CANT_CREATE_TABLE 1005 -#define ER_CANT_CREATE_DB 1006 -#define ER_DB_CREATE_EXISTS 1007 -#define ER_DB_DROP_EXISTS 1008 -#define ER_DB_DROP_DELETE 1009 -#define ER_DB_DROP_RMDIR 1010 -#define ER_CANT_DELETE_FILE 1011 -#define ER_CANT_FIND_SYSTEM_REC 1012 -#define ER_CANT_GET_STAT 1013 -#define ER_CANT_GET_WD 1014 -#define ER_CANT_LOCK 1015 -#define ER_CANT_OPEN_FILE 1016 -#define ER_FILE_NOT_FOUND 1017 -#define ER_CANT_READ_DIR 1018 -#define ER_CANT_SET_WD 1019 -#define ER_CHECKREAD 1020 -#define ER_DISK_FULL 1021 -#define ER_DUP_KEY 1022 -#define ER_ERROR_ON_CLOSE 1023 -#define ER_ERROR_ON_READ 1024 -#define ER_ERROR_ON_RENAME 1025 -#define ER_ERROR_ON_WRITE 1026 -#define ER_FILE_USED 1027 -#define ER_FILSORT_ABORT 1028 -#define ER_FORM_NOT_FOUND 1029 -#define ER_GET_ERRNO 1030 -#define ER_ILLEGAL_HA 1031 -#define ER_KEY_NOT_FOUND 1032 -#define ER_NOT_FORM_FILE 1033 -#define ER_NOT_KEYFILE 1034 -#define ER_OLD_KEYFILE 1035 -#define ER_OPEN_AS_READONLY 1036 -#define ER_OUTOFMEMORY 1037 -#define ER_OUT_OF_SORTMEMORY 1038 -#define ER_UNEXPECTED_EOF 1039 -#define ER_CON_COUNT_ERROR 1040 -#define ER_OUT_OF_RESOURCES 1041 -#define ER_BAD_HOST_ERROR 1042 -#define ER_HANDSHAKE_ERROR 1043 -#define ER_DBACCESS_DENIED_ERROR 1044 -#define ER_ACCESS_DENIED_ERROR 1045 -#define ER_NO_DB_ERROR 1046 -#define ER_UNKNOWN_COM_ERROR 1047 -#define ER_BAD_NULL_ERROR 1048 -#define ER_BAD_DB_ERROR 1049 -#define ER_TABLE_EXISTS_ERROR 1050 -#define ER_BAD_TABLE_ERROR 1051 -#define ER_NON_UNIQ_ERROR 1052 -#define ER_SERVER_SHUTDOWN 1053 -#define ER_BAD_FIELD_ERROR 1054 -#define ER_WRONG_FIELD_WITH_GROUP 1055 -#define ER_WRONG_GROUP_FIELD 1056 -#define ER_WRONG_SUM_SELECT 1057 -#define ER_WRONG_VALUE_COUNT 1058 -#define ER_TOO_LONG_IDENT 1059 -#define ER_DUP_FIELDNAME 1060 -#define ER_DUP_KEYNAME 1061 -#define ER_DUP_ENTRY 1062 -#define ER_WRONG_FIELD_SPEC 1063 -#define ER_PARSE_ERROR 1064 -#define ER_EMPTY_QUERY 1065 -#define ER_NONUNIQ_TABLE 1066 -#define ER_INVALID_DEFAULT 1067 -#define ER_MULTIPLE_PRI_KEY 1068 -#define ER_TOO_MANY_KEYS 1069 -#define ER_TOO_MANY_KEY_PARTS 1070 -#define ER_TOO_LONG_KEY 1071 -#define ER_KEY_COLUMN_DOES_NOT_EXITS 1072 -#define ER_BLOB_USED_AS_KEY 1073 -#define ER_TOO_BIG_FIELDLENGTH 1074 -#define ER_WRONG_AUTO_KEY 1075 -#define ER_BINLOG_CANT_DELETE_GTID_DOMAIN 1076 -#define ER_NORMAL_SHUTDOWN 1077 -#define ER_GOT_SIGNAL 1078 -#define ER_SHUTDOWN_COMPLETE 1079 -#define ER_FORCING_CLOSE 1080 -#define ER_IPSOCK_ERROR 1081 -#define ER_NO_SUCH_INDEX 1082 -#define ER_WRONG_FIELD_TERMINATORS 1083 -#define ER_BLOBS_AND_NO_TERMINATED 1084 -#define ER_TEXTFILE_NOT_READABLE 1085 -#define ER_FILE_EXISTS_ERROR 1086 -#define ER_LOAD_INFO 1087 -#define ER_ALTER_INFO 1088 -#define ER_WRONG_SUB_KEY 1089 -#define ER_CANT_REMOVE_ALL_FIELDS 1090 -#define ER_CANT_DROP_FIELD_OR_KEY 1091 -#define ER_INSERT_INFO 1092 -#define ER_UPDATE_TABLE_USED 1093 -#define ER_NO_SUCH_THREAD 1094 -#define ER_KILL_DENIED_ERROR 1095 -#define ER_NO_TABLES_USED 1096 -#define ER_TOO_BIG_SET 1097 -#define ER_NO_UNIQUE_LOGFILE 1098 -#define ER_TABLE_NOT_LOCKED_FOR_WRITE 1099 -#define ER_TABLE_NOT_LOCKED 1100 -#define ER_UNUSED_17 1101 -#define ER_WRONG_DB_NAME 1102 -#define ER_WRONG_TABLE_NAME 1103 -#define ER_TOO_BIG_SELECT 1104 -#define ER_UNKNOWN_ERROR 1105 -#define ER_UNKNOWN_PROCEDURE 1106 -#define ER_WRONG_PARAMCOUNT_TO_PROCEDURE 1107 -#define ER_WRONG_PARAMETERS_TO_PROCEDURE 1108 -#define ER_UNKNOWN_TABLE 1109 -#define ER_FIELD_SPECIFIED_TWICE 1110 -#define ER_INVALID_GROUP_FUNC_USE 1111 -#define ER_UNSUPPORTED_EXTENSION 1112 -#define ER_TABLE_MUST_HAVE_COLUMNS 1113 -#define ER_RECORD_FILE_FULL 1114 -#define ER_UNKNOWN_CHARACTER_SET 1115 -#define ER_TOO_MANY_TABLES 1116 -#define ER_TOO_MANY_FIELDS 1117 -#define ER_TOO_BIG_ROWSIZE 1118 -#define ER_STACK_OVERRUN 1119 -#define ER_WRONG_OUTER_JOIN 1120 -#define ER_NULL_COLUMN_IN_INDEX 1121 -#define ER_CANT_FIND_UDF 1122 -#define ER_CANT_INITIALIZE_UDF 1123 -#define ER_UDF_NO_PATHS 1124 -#define ER_UDF_EXISTS 1125 -#define ER_CANT_OPEN_LIBRARY 1126 -#define ER_CANT_FIND_DL_ENTRY 1127 -#define ER_FUNCTION_NOT_DEFINED 1128 -#define ER_HOST_IS_BLOCKED 1129 -#define ER_HOST_NOT_PRIVILEGED 1130 -#define ER_PASSWORD_ANONYMOUS_USER 1131 -#define ER_PASSWORD_NOT_ALLOWED 1132 -#define ER_PASSWORD_NO_MATCH 1133 -#define ER_UPDATE_INFO 1134 -#define ER_CANT_CREATE_THREAD 1135 -#define ER_WRONG_VALUE_COUNT_ON_ROW 1136 -#define ER_CANT_REOPEN_TABLE 1137 -#define ER_INVALID_USE_OF_NULL 1138 -#define ER_REGEXP_ERROR 1139 -#define ER_MIX_OF_GROUP_FUNC_AND_FIELDS 1140 -#define ER_NONEXISTING_GRANT 1141 -#define ER_TABLEACCESS_DENIED_ERROR 1142 -#define ER_COLUMNACCESS_DENIED_ERROR 1143 -#define ER_ILLEGAL_GRANT_FOR_TABLE 1144 -#define ER_GRANT_WRONG_HOST_OR_USER 1145 -#define ER_NO_SUCH_TABLE 1146 -#define ER_NONEXISTING_TABLE_GRANT 1147 -#define ER_NOT_ALLOWED_COMMAND 1148 -#define ER_SYNTAX_ERROR 1149 -#define ER_DELAYED_CANT_CHANGE_LOCK 1150 -#define ER_TOO_MANY_DELAYED_THREADS 1151 -#define ER_ABORTING_CONNECTION 1152 -#define ER_NET_PACKET_TOO_LARGE 1153 -#define ER_NET_READ_ERROR_FROM_PIPE 1154 -#define ER_NET_FCNTL_ERROR 1155 -#define ER_NET_PACKETS_OUT_OF_ORDER 1156 -#define ER_NET_UNCOMPRESS_ERROR 1157 -#define ER_NET_READ_ERROR 1158 -#define ER_NET_READ_INTERRUPTED 1159 -#define ER_NET_ERROR_ON_WRITE 1160 -#define ER_NET_WRITE_INTERRUPTED 1161 -#define ER_TOO_LONG_STRING 1162 -#define ER_TABLE_CANT_HANDLE_BLOB 1163 -#define ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 1164 -#define ER_DELAYED_INSERT_TABLE_LOCKED 1165 -#define ER_WRONG_COLUMN_NAME 1166 -#define ER_WRONG_KEY_COLUMN 1167 -#define ER_WRONG_MRG_TABLE 1168 -#define ER_DUP_UNIQUE 1169 -#define ER_BLOB_KEY_WITHOUT_LENGTH 1170 -#define ER_PRIMARY_CANT_HAVE_NULL 1171 -#define ER_TOO_MANY_ROWS 1172 -#define ER_REQUIRES_PRIMARY_KEY 1173 -#define ER_NO_RAID_COMPILED 1174 -#define ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE 1175 -#define ER_KEY_DOES_NOT_EXISTS 1176 -#define ER_CHECK_NO_SUCH_TABLE 1177 -#define ER_CHECK_NOT_IMPLEMENTED 1178 -#define ER_CANT_DO_THIS_DURING_AN_TRANSACTION 1179 -#define ER_ERROR_DURING_COMMIT 1180 -#define ER_ERROR_DURING_ROLLBACK 1181 -#define ER_ERROR_DURING_FLUSH_LOGS 1182 -#define ER_ERROR_DURING_CHECKPOINT 1183 -#define ER_NEW_ABORTING_CONNECTION 1184 -#define ER_UNUSED_10 1185 -#define ER_FLUSH_MASTER_BINLOG_CLOSED 1186 -#define ER_INDEX_REBUILD 1187 -#define ER_MASTER 1188 -#define ER_MASTER_NET_READ 1189 -#define ER_MASTER_NET_WRITE 1190 -#define ER_FT_MATCHING_KEY_NOT_FOUND 1191 -#define ER_LOCK_OR_ACTIVE_TRANSACTION 1192 -#define ER_UNKNOWN_SYSTEM_VARIABLE 1193 -#define ER_CRASHED_ON_USAGE 1194 -#define ER_CRASHED_ON_REPAIR 1195 -#define ER_WARNING_NOT_COMPLETE_ROLLBACK 1196 -#define ER_TRANS_CACHE_FULL 1197 -#define ER_SLAVE_MUST_STOP 1198 -#define ER_SLAVE_NOT_RUNNING 1199 -#define ER_BAD_SLAVE 1200 -#define ER_MASTER_INFO 1201 -#define ER_SLAVE_THREAD 1202 -#define ER_TOO_MANY_USER_CONNECTIONS 1203 -#define ER_SET_CONSTANTS_ONLY 1204 -#define ER_LOCK_WAIT_TIMEOUT 1205 -#define ER_LOCK_TABLE_FULL 1206 -#define ER_READ_ONLY_TRANSACTION 1207 -#define ER_DROP_DB_WITH_READ_LOCK 1208 -#define ER_CREATE_DB_WITH_READ_LOCK 1209 -#define ER_WRONG_ARGUMENTS 1210 -#define ER_NO_PERMISSION_TO_CREATE_USER 1211 -#define ER_UNION_TABLES_IN_DIFFERENT_DIR 1212 -#define ER_LOCK_DEADLOCK 1213 -#define ER_TABLE_CANT_HANDLE_FT 1214 -#define ER_CANNOT_ADD_FOREIGN 1215 -#define ER_NO_REFERENCED_ROW 1216 -#define ER_ROW_IS_REFERENCED 1217 -#define ER_CONNECT_TO_MASTER 1218 -#define ER_QUERY_ON_MASTER 1219 -#define ER_ERROR_WHEN_EXECUTING_COMMAND 1220 -#define ER_WRONG_USAGE 1221 -#define ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT 1222 -#define ER_CANT_UPDATE_WITH_READLOCK 1223 -#define ER_MIXING_NOT_ALLOWED 1224 -#define ER_DUP_ARGUMENT 1225 -#define ER_USER_LIMIT_REACHED 1226 -#define ER_SPECIFIC_ACCESS_DENIED_ERROR 1227 -#define ER_LOCAL_VARIABLE 1228 -#define ER_GLOBAL_VARIABLE 1229 -#define ER_NO_DEFAULT 1230 -#define ER_WRONG_VALUE_FOR_VAR 1231 -#define ER_WRONG_TYPE_FOR_VAR 1232 -#define ER_VAR_CANT_BE_READ 1233 -#define ER_CANT_USE_OPTION_HERE 1234 -#define ER_NOT_SUPPORTED_YET 1235 -#define ER_MASTER_FATAL_ERROR_READING_BINLOG 1236 -#define ER_SLAVE_IGNORED_TABLE 1237 -#define ER_INCORRECT_GLOBAL_LOCAL_VAR 1238 -#define ER_WRONG_FK_DEF 1239 -#define ER_KEY_REF_DO_NOT_MATCH_TABLE_REF 1240 -#define ER_OPERAND_COLUMNS 1241 -#define ER_SUBQUERY_NO_1_ROW 1242 -#define ER_UNKNOWN_STMT_HANDLER 1243 -#define ER_CORRUPT_HELP_DB 1244 -#define ER_CYCLIC_REFERENCE 1245 -#define ER_AUTO_CONVERT 1246 -#define ER_ILLEGAL_REFERENCE 1247 -#define ER_DERIVED_MUST_HAVE_ALIAS 1248 -#define ER_SELECT_REDUCED 1249 -#define ER_TABLENAME_NOT_ALLOWED_HERE 1250 -#define ER_NOT_SUPPORTED_AUTH_MODE 1251 -#define ER_SPATIAL_CANT_HAVE_NULL 1252 -#define ER_COLLATION_CHARSET_MISMATCH 1253 -#define ER_SLAVE_WAS_RUNNING 1254 -#define ER_SLAVE_WAS_NOT_RUNNING 1255 -#define ER_TOO_BIG_FOR_UNCOMPRESS 1256 -#define ER_ZLIB_Z_MEM_ERROR 1257 -#define ER_ZLIB_Z_BUF_ERROR 1258 -#define ER_ZLIB_Z_DATA_ERROR 1259 -#define ER_CUT_VALUE_GROUP_CONCAT 1260 -#define ER_WARN_TOO_FEW_RECORDS 1261 -#define ER_WARN_TOO_MANY_RECORDS 1262 -#define ER_WARN_NULL_TO_NOTNULL 1263 -#define ER_WARN_DATA_OUT_OF_RANGE 1264 -#define WARN_DATA_TRUNCATED 1265 -#define ER_WARN_USING_OTHER_HANDLER 1266 -#define ER_CANT_AGGREGATE_2COLLATIONS 1267 -#define ER_DROP_USER 1268 -#define ER_REVOKE_GRANTS 1269 -#define ER_CANT_AGGREGATE_3COLLATIONS 1270 -#define ER_CANT_AGGREGATE_NCOLLATIONS 1271 -#define ER_VARIABLE_IS_NOT_STRUCT 1272 -#define ER_UNKNOWN_COLLATION 1273 -#define ER_SLAVE_IGNORED_SSL_PARAMS 1274 -#define ER_SERVER_IS_IN_SECURE_AUTH_MODE 1275 -#define ER_WARN_FIELD_RESOLVED 1276 -#define ER_BAD_SLAVE_UNTIL_COND 1277 -#define ER_MISSING_SKIP_SLAVE 1278 -#define ER_UNTIL_COND_IGNORED 1279 -#define ER_WRONG_NAME_FOR_INDEX 1280 -#define ER_WRONG_NAME_FOR_CATALOG 1281 -#define ER_WARN_QC_RESIZE 1282 -#define ER_BAD_FT_COLUMN 1283 -#define ER_UNKNOWN_KEY_CACHE 1284 -#define ER_WARN_HOSTNAME_WONT_WORK 1285 -#define ER_UNKNOWN_STORAGE_ENGINE 1286 -#define ER_WARN_DEPRECATED_SYNTAX 1287 -#define ER_NON_UPDATABLE_TABLE 1288 -#define ER_FEATURE_DISABLED 1289 -#define ER_OPTION_PREVENTS_STATEMENT 1290 -#define ER_DUPLICATED_VALUE_IN_TYPE 1291 -#define ER_TRUNCATED_WRONG_VALUE 1292 -#define ER_TOO_MUCH_AUTO_TIMESTAMP_COLS 1293 -#define ER_INVALID_ON_UPDATE 1294 -#define ER_UNSUPPORTED_PS 1295 -#define ER_GET_ERRMSG 1296 -#define ER_GET_TEMPORARY_ERRMSG 1297 -#define ER_UNKNOWN_TIME_ZONE 1298 -#define ER_WARN_INVALID_TIMESTAMP 1299 -#define ER_INVALID_CHARACTER_STRING 1300 -#define ER_WARN_ALLOWED_PACKET_OVERFLOWED 1301 -#define ER_CONFLICTING_DECLARATIONS 1302 -#define ER_SP_NO_RECURSIVE_CREATE 1303 -#define ER_SP_ALREADY_EXISTS 1304 -#define ER_SP_DOES_NOT_EXIST 1305 -#define ER_SP_DROP_FAILED 1306 -#define ER_SP_STORE_FAILED 1307 -#define ER_SP_LILABEL_MISMATCH 1308 -#define ER_SP_LABEL_REDEFINE 1309 -#define ER_SP_LABEL_MISMATCH 1310 -#define ER_SP_UNINIT_VAR 1311 -#define ER_SP_BADSELECT 1312 -#define ER_SP_BADRETURN 1313 -#define ER_SP_BADSTATEMENT 1314 -#define ER_UPDATE_LOG_DEPRECATED_IGNORED 1315 -#define ER_UPDATE_LOG_DEPRECATED_TRANSLATED 1316 -#define ER_QUERY_INTERRUPTED 1317 -#define ER_SP_WRONG_NO_OF_ARGS 1318 -#define ER_SP_COND_MISMATCH 1319 -#define ER_SP_NORETURN 1320 -#define ER_SP_NORETURNEND 1321 -#define ER_SP_BAD_CURSOR_QUERY 1322 -#define ER_SP_BAD_CURSOR_SELECT 1323 -#define ER_SP_CURSOR_MISMATCH 1324 -#define ER_SP_CURSOR_ALREADY_OPEN 1325 -#define ER_SP_CURSOR_NOT_OPEN 1326 -#define ER_SP_UNDECLARED_VAR 1327 -#define ER_SP_WRONG_NO_OF_FETCH_ARGS 1328 -#define ER_SP_FETCH_NO_DATA 1329 -#define ER_SP_DUP_PARAM 1330 -#define ER_SP_DUP_VAR 1331 -#define ER_SP_DUP_COND 1332 -#define ER_SP_DUP_CURS 1333 -#define ER_SP_CANT_ALTER 1334 -#define ER_SP_SUBSELECT_NYI 1335 -#define ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG 1336 -#define ER_SP_VARCOND_AFTER_CURSHNDLR 1337 -#define ER_SP_CURSOR_AFTER_HANDLER 1338 -#define ER_SP_CASE_NOT_FOUND 1339 -#define ER_FPARSER_TOO_BIG_FILE 1340 -#define ER_FPARSER_BAD_HEADER 1341 -#define ER_FPARSER_EOF_IN_COMMENT 1342 -#define ER_FPARSER_ERROR_IN_PARAMETER 1343 -#define ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER 1344 -#define ER_VIEW_NO_EXPLAIN 1345 -#define ER_FRM_UNKNOWN_TYPE 1346 -#define ER_WRONG_OBJECT 1347 -#define ER_NONUPDATEABLE_COLUMN 1348 -#define ER_VIEW_SELECT_DERIVED 1349 -#define ER_VIEW_SELECT_CLAUSE 1350 -#define ER_VIEW_SELECT_VARIABLE 1351 -#define ER_VIEW_SELECT_TMPTABLE 1352 -#define ER_VIEW_WRONG_LIST 1353 -#define ER_WARN_VIEW_MERGE 1354 -#define ER_WARN_VIEW_WITHOUT_KEY 1355 -#define ER_VIEW_INVALID 1356 -#define ER_SP_NO_DROP_SP 1357 -#define ER_SP_GOTO_IN_HNDLR 1358 -#define ER_TRG_ALREADY_EXISTS 1359 -#define ER_TRG_DOES_NOT_EXIST 1360 -#define ER_TRG_ON_VIEW_OR_TEMP_TABLE 1361 -#define ER_TRG_CANT_CHANGE_ROW 1362 -#define ER_TRG_NO_SUCH_ROW_IN_TRG 1363 -#define ER_NO_DEFAULT_FOR_FIELD 1364 -#define ER_DIVISION_BY_ZERO 1365 -#define ER_TRUNCATED_WRONG_VALUE_FOR_FIELD 1366 -#define ER_ILLEGAL_VALUE_FOR_TYPE 1367 -#define ER_VIEW_NONUPD_CHECK 1368 -#define ER_VIEW_CHECK_FAILED 1369 -#define ER_PROCACCESS_DENIED_ERROR 1370 -#define ER_RELAY_LOG_FAIL 1371 -#define ER_PASSWD_LENGTH 1372 -#define ER_UNKNOWN_TARGET_BINLOG 1373 -#define ER_IO_ERR_LOG_INDEX_READ 1374 -#define ER_BINLOG_PURGE_PROHIBITED 1375 -#define ER_FSEEK_FAIL 1376 -#define ER_BINLOG_PURGE_FATAL_ERR 1377 -#define ER_LOG_IN_USE 1378 -#define ER_LOG_PURGE_UNKNOWN_ERR 1379 -#define ER_RELAY_LOG_INIT 1380 -#define ER_NO_BINARY_LOGGING 1381 -#define ER_RESERVED_SYNTAX 1382 -#define ER_WSAS_FAILED 1383 -#define ER_DIFF_GROUPS_PROC 1384 -#define ER_NO_GROUP_FOR_PROC 1385 -#define ER_ORDER_WITH_PROC 1386 -#define ER_LOGGING_PROHIBIT_CHANGING_OF 1387 -#define ER_NO_FILE_MAPPING 1388 -#define ER_WRONG_MAGIC 1389 -#define ER_PS_MANY_PARAM 1390 -#define ER_KEY_PART_0 1391 -#define ER_VIEW_CHECKSUM 1392 -#define ER_VIEW_MULTIUPDATE 1393 -#define ER_VIEW_NO_INSERT_FIELD_LIST 1394 -#define ER_VIEW_DELETE_MERGE_VIEW 1395 -#define ER_CANNOT_USER 1396 -#define ER_XAER_NOTA 1397 -#define ER_XAER_INVAL 1398 -#define ER_XAER_RMFAIL 1399 -#define ER_XAER_OUTSIDE 1400 -#define ER_XAER_RMERR 1401 -#define ER_XA_RBROLLBACK 1402 -#define ER_NONEXISTING_PROC_GRANT 1403 -#define ER_PROC_AUTO_GRANT_FAIL 1404 -#define ER_PROC_AUTO_REVOKE_FAIL 1405 -#define ER_DATA_TOO_LONG 1406 -#define ER_SP_BAD_SQLSTATE 1407 -#define ER_STARTUP 1408 -#define ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR 1409 -#define ER_CANT_CREATE_USER_WITH_GRANT 1410 -#define ER_WRONG_VALUE_FOR_TYPE 1411 -#define ER_TABLE_DEF_CHANGED 1412 -#define ER_SP_DUP_HANDLER 1413 -#define ER_SP_NOT_VAR_ARG 1414 -#define ER_SP_NO_RETSET 1415 -#define ER_CANT_CREATE_GEOMETRY_OBJECT 1416 -#define ER_FAILED_ROUTINE_BREAK_BINLOG 1417 -#define ER_BINLOG_UNSAFE_ROUTINE 1418 -#define ER_BINLOG_CREATE_ROUTINE_NEED_SUPER 1419 -#define ER_EXEC_STMT_WITH_OPEN_CURSOR 1420 -#define ER_STMT_HAS_NO_OPEN_CURSOR 1421 -#define ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG 1422 -#define ER_NO_DEFAULT_FOR_VIEW_FIELD 1423 -#define ER_SP_NO_RECURSION 1424 -#define ER_TOO_BIG_SCALE 1425 -#define ER_TOO_BIG_PRECISION 1426 -#define ER_M_BIGGER_THAN_D 1427 -#define ER_WRONG_LOCK_OF_SYSTEM_TABLE 1428 -#define ER_CONNECT_TO_FOREIGN_DATA_SOURCE 1429 -#define ER_QUERY_ON_FOREIGN_DATA_SOURCE 1430 -#define ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST 1431 -#define ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE 1432 -#define ER_FOREIGN_DATA_STRING_INVALID 1433 -#define ER_CANT_CREATE_FEDERATED_TABLE 1434 -#define ER_TRG_IN_WRONG_SCHEMA 1435 -#define ER_STACK_OVERRUN_NEED_MORE 1436 -#define ER_TOO_LONG_BODY 1437 -#define ER_WARN_CANT_DROP_DEFAULT_KEYCACHE 1438 -#define ER_TOO_BIG_DISPLAYWIDTH 1439 -#define ER_XAER_DUPID 1440 -#define ER_DATETIME_FUNCTION_OVERFLOW 1441 -#define ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG 1442 -#define ER_VIEW_PREVENT_UPDATE 1443 -#define ER_PS_NO_RECURSION 1444 -#define ER_SP_CANT_SET_AUTOCOMMIT 1445 -#define ER_MALFORMED_DEFINER 1446 -#define ER_VIEW_FRM_NO_USER 1447 -#define ER_VIEW_OTHER_USER 1448 -#define ER_NO_SUCH_USER 1449 -#define ER_FORBID_SCHEMA_CHANGE 1450 -#define ER_ROW_IS_REFERENCED_2 1451 -#define ER_NO_REFERENCED_ROW_2 1452 -#define ER_SP_BAD_VAR_SHADOW 1453 -#define ER_TRG_NO_DEFINER 1454 -#define ER_OLD_FILE_FORMAT 1455 -#define ER_SP_RECURSION_LIMIT 1456 -#define ER_SP_PROC_TABLE_CORRUPT 1457 -#define ER_SP_WRONG_NAME 1458 -#define ER_TABLE_NEEDS_UPGRADE 1459 -#define ER_SP_NO_AGGREGATE 1460 -#define ER_MAX_PREPARED_STMT_COUNT_REACHED 1461 -#define ER_VIEW_RECURSIVE 1462 -#define ER_NON_GROUPING_FIELD_USED 1463 -#define ER_TABLE_CANT_HANDLE_SPKEYS 1464 -#define ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA 1465 -#define ER_REMOVED_SPACES 1466 -#define ER_AUTOINC_READ_FAILED 1467 -#define ER_USERNAME 1468 -#define ER_HOSTNAME 1469 -#define ER_WRONG_STRING_LENGTH 1470 -#define ER_NON_INSERTABLE_TABLE 1471 -#define ER_ADMIN_WRONG_MRG_TABLE 1472 -#define ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT 1473 -#define ER_NAME_BECOMES_EMPTY 1474 -#define ER_AMBIGUOUS_FIELD_TERM 1475 -#define ER_FOREIGN_SERVER_EXISTS 1476 -#define ER_FOREIGN_SERVER_DOESNT_EXIST 1477 -#define ER_ILLEGAL_HA_CREATE_OPTION 1478 -#define ER_PARTITION_REQUIRES_VALUES_ERROR 1479 -#define ER_PARTITION_WRONG_VALUES_ERROR 1480 -#define ER_PARTITION_MAXVALUE_ERROR 1481 -#define ER_PARTITION_SUBPARTITION_ERROR 1482 -#define ER_PARTITION_SUBPART_MIX_ERROR 1483 -#define ER_PARTITION_WRONG_NO_PART_ERROR 1484 -#define ER_PARTITION_WRONG_NO_SUBPART_ERROR 1485 -#define ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR 1486 -#define ER_NOT_CONSTANT_EXPRESSION 1487 -#define ER_FIELD_NOT_FOUND_PART_ERROR 1488 -#define ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR 1489 -#define ER_INCONSISTENT_PARTITION_INFO_ERROR 1490 -#define ER_PARTITION_FUNC_NOT_ALLOWED_ERROR 1491 -#define ER_PARTITIONS_MUST_BE_DEFINED_ERROR 1492 -#define ER_RANGE_NOT_INCREASING_ERROR 1493 -#define ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR 1494 -#define ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR 1495 -#define ER_PARTITION_ENTRY_ERROR 1496 -#define ER_MIX_HANDLER_ERROR 1497 -#define ER_PARTITION_NOT_DEFINED_ERROR 1498 -#define ER_TOO_MANY_PARTITIONS_ERROR 1499 -#define ER_SUBPARTITION_ERROR 1500 -#define ER_CANT_CREATE_HANDLER_FILE 1501 -#define ER_BLOB_FIELD_IN_PART_FUNC_ERROR 1502 -#define ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF 1503 -#define ER_NO_PARTS_ERROR 1504 -#define ER_PARTITION_MGMT_ON_NONPARTITIONED 1505 -#define ER_FEATURE_NOT_SUPPORTED_WITH_PARTITIONING 1506 -#define ER_DROP_PARTITION_NON_EXISTENT 1507 -#define ER_DROP_LAST_PARTITION 1508 -#define ER_COALESCE_ONLY_ON_HASH_PARTITION 1509 -#define ER_REORG_HASH_ONLY_ON_SAME_NO 1510 -#define ER_REORG_NO_PARAM_ERROR 1511 -#define ER_ONLY_ON_RANGE_LIST_PARTITION 1512 -#define ER_ADD_PARTITION_SUBPART_ERROR 1513 -#define ER_ADD_PARTITION_NO_NEW_PARTITION 1514 -#define ER_COALESCE_PARTITION_NO_PARTITION 1515 -#define ER_REORG_PARTITION_NOT_EXIST 1516 -#define ER_SAME_NAME_PARTITION 1517 -#define ER_NO_BINLOG_ERROR 1518 -#define ER_CONSECUTIVE_REORG_PARTITIONS 1519 -#define ER_REORG_OUTSIDE_RANGE 1520 -#define ER_PARTITION_FUNCTION_FAILURE 1521 -#define ER_PART_STATE_ERROR 1522 -#define ER_LIMITED_PART_RANGE 1523 -#define ER_PLUGIN_IS_NOT_LOADED 1524 -#define ER_WRONG_VALUE 1525 -#define ER_NO_PARTITION_FOR_GIVEN_VALUE 1526 -#define ER_FILEGROUP_OPTION_ONLY_ONCE 1527 -#define ER_CREATE_FILEGROUP_FAILED 1528 -#define ER_DROP_FILEGROUP_FAILED 1529 -#define ER_TABLESPACE_AUTO_EXTEND_ERROR 1530 -#define ER_WRONG_SIZE_NUMBER 1531 -#define ER_SIZE_OVERFLOW_ERROR 1532 -#define ER_ALTER_FILEGROUP_FAILED 1533 -#define ER_BINLOG_ROW_LOGGING_FAILED 1534 -#define ER_BINLOG_ROW_WRONG_TABLE_DEF 1535 -#define ER_BINLOG_ROW_RBR_TO_SBR 1536 -#define ER_EVENT_ALREADY_EXISTS 1537 -#define ER_EVENT_STORE_FAILED 1538 -#define ER_EVENT_DOES_NOT_EXIST 1539 -#define ER_EVENT_CANT_ALTER 1540 -#define ER_EVENT_DROP_FAILED 1541 -#define ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG 1542 -#define ER_EVENT_ENDS_BEFORE_STARTS 1543 -#define ER_EVENT_EXEC_TIME_IN_THE_PAST 1544 -#define ER_EVENT_OPEN_TABLE_FAILED 1545 -#define ER_EVENT_NEITHER_M_EXPR_NOR_M_AT 1546 -#define ER_UNUSED_2 1547 -#define ER_UNUSED_3 1548 -#define ER_EVENT_CANNOT_DELETE 1549 -#define ER_EVENT_COMPILE_ERROR 1550 -#define ER_EVENT_SAME_NAME 1551 -#define ER_EVENT_DATA_TOO_LONG 1552 -#define ER_DROP_INDEX_FK 1553 -#define ER_WARN_DEPRECATED_SYNTAX_WITH_VER 1554 -#define ER_CANT_WRITE_LOCK_LOG_TABLE 1555 -#define ER_CANT_LOCK_LOG_TABLE 1556 -#define ER_UNUSED_4 1557 -#define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE 1558 -#define ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR 1559 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT 1560 -#define ER_UNUSED_13 1561 -#define ER_PARTITION_NO_TEMPORARY 1562 -#define ER_PARTITION_CONST_DOMAIN_ERROR 1563 -#define ER_PARTITION_FUNCTION_IS_NOT_ALLOWED 1564 -#define ER_DDL_LOG_ERROR 1565 -#define ER_NULL_IN_VALUES_LESS_THAN 1566 -#define ER_WRONG_PARTITION_NAME 1567 -#define ER_CANT_CHANGE_TX_CHARACTERISTICS 1568 -#define ER_DUP_ENTRY_AUTOINCREMENT_CASE 1569 -#define ER_EVENT_MODIFY_QUEUE_ERROR 1570 -#define ER_EVENT_SET_VAR_ERROR 1571 -#define ER_PARTITION_MERGE_ERROR 1572 -#define ER_CANT_ACTIVATE_LOG 1573 -#define ER_RBR_NOT_AVAILABLE 1574 -#define ER_BASE64_DECODE_ERROR 1575 -#define ER_EVENT_RECURSION_FORBIDDEN 1576 -#define ER_EVENTS_DB_ERROR 1577 -#define ER_ONLY_INTEGERS_ALLOWED 1578 -#define ER_UNSUPORTED_LOG_ENGINE 1579 -#define ER_BAD_LOG_STATEMENT 1580 -#define ER_CANT_RENAME_LOG_TABLE 1581 -#define ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT 1582 -#define ER_WRONG_PARAMETERS_TO_NATIVE_FCT 1583 -#define ER_WRONG_PARAMETERS_TO_STORED_FCT 1584 -#define ER_NATIVE_FCT_NAME_COLLISION 1585 -#define ER_DUP_ENTRY_WITH_KEY_NAME 1586 -#define ER_BINLOG_PURGE_EMFILE 1587 -#define ER_EVENT_CANNOT_CREATE_IN_THE_PAST 1588 -#define ER_EVENT_CANNOT_ALTER_IN_THE_PAST 1589 -#define ER_SLAVE_INCIDENT 1590 -#define ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT 1591 -#define ER_BINLOG_UNSAFE_STATEMENT 1592 -#define ER_SLAVE_FATAL_ERROR 1593 -#define ER_SLAVE_RELAY_LOG_READ_FAILURE 1594 -#define ER_SLAVE_RELAY_LOG_WRITE_FAILURE 1595 -#define ER_SLAVE_CREATE_EVENT_FAILURE 1596 -#define ER_SLAVE_MASTER_COM_FAILURE 1597 -#define ER_BINLOG_LOGGING_IMPOSSIBLE 1598 -#define ER_VIEW_NO_CREATION_CTX 1599 -#define ER_VIEW_INVALID_CREATION_CTX 1600 -#define ER_SR_INVALID_CREATION_CTX 1601 -#define ER_TRG_CORRUPTED_FILE 1602 -#define ER_TRG_NO_CREATION_CTX 1603 -#define ER_TRG_INVALID_CREATION_CTX 1604 -#define ER_EVENT_INVALID_CREATION_CTX 1605 -#define ER_TRG_CANT_OPEN_TABLE 1606 -#define ER_CANT_CREATE_SROUTINE 1607 -#define ER_UNUSED_11 1608 -#define ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT 1609 -#define ER_SLAVE_CORRUPT_EVENT 1610 -#define ER_LOAD_DATA_INVALID_COLUMN 1611 -#define ER_LOG_PURGE_NO_FILE 1612 -#define ER_XA_RBTIMEOUT 1613 -#define ER_XA_RBDEADLOCK 1614 -#define ER_NEED_REPREPARE 1615 -#define ER_DELAYED_NOT_SUPPORTED 1616 -#define WARN_NO_MASTER_INFO 1617 -#define WARN_OPTION_IGNORED 1618 -#define ER_PLUGIN_DELETE_BUILTIN 1619 -#define WARN_PLUGIN_BUSY 1620 -#define ER_VARIABLE_IS_READONLY 1621 -#define ER_WARN_ENGINE_TRANSACTION_ROLLBACK 1622 -#define ER_SLAVE_HEARTBEAT_FAILURE 1623 -#define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE 1624 -#define ER_UNUSED_14 1625 -#define ER_CONFLICT_FN_PARSE_ERROR 1626 -#define ER_EXCEPTIONS_WRITE_ERROR 1627 -#define ER_TOO_LONG_TABLE_COMMENT 1628 -#define ER_TOO_LONG_FIELD_COMMENT 1629 -#define ER_FUNC_INEXISTENT_NAME_COLLISION 1630 -#define ER_DATABASE_NAME 1631 -#define ER_TABLE_NAME 1632 -#define ER_PARTITION_NAME 1633 -#define ER_SUBPARTITION_NAME 1634 -#define ER_TEMPORARY_NAME 1635 -#define ER_RENAMED_NAME 1636 -#define ER_TOO_MANY_CONCURRENT_TRXS 1637 -#define WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED 1638 -#define ER_DEBUG_SYNC_TIMEOUT 1639 -#define ER_DEBUG_SYNC_HIT_LIMIT 1640 -#define ER_DUP_SIGNAL_SET 1641 -#define ER_SIGNAL_WARN 1642 -#define ER_SIGNAL_NOT_FOUND 1643 -#define ER_SIGNAL_EXCEPTION 1644 -#define ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER 1645 -#define ER_SIGNAL_BAD_CONDITION_TYPE 1646 -#define WARN_COND_ITEM_TRUNCATED 1647 -#define ER_COND_ITEM_TOO_LONG 1648 -#define ER_UNKNOWN_LOCALE 1649 -#define ER_SLAVE_IGNORE_SERVER_IDS 1650 -#define ER_QUERY_CACHE_DISABLED 1651 -#define ER_SAME_NAME_PARTITION_FIELD 1652 -#define ER_PARTITION_COLUMN_LIST_ERROR 1653 -#define ER_WRONG_TYPE_COLUMN_VALUE_ERROR 1654 -#define ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR 1655 -#define ER_MAXVALUE_IN_VALUES_IN 1656 -#define ER_TOO_MANY_VALUES_ERROR 1657 -#define ER_ROW_SINGLE_PARTITION_FIELD_ERROR 1658 -#define ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD 1659 -#define ER_PARTITION_FIELDS_TOO_LONG 1660 -#define ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE 1661 -#define ER_BINLOG_ROW_MODE_AND_STMT_ENGINE 1662 -#define ER_BINLOG_UNSAFE_AND_STMT_ENGINE 1663 -#define ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE 1664 -#define ER_BINLOG_STMT_MODE_AND_ROW_ENGINE 1665 -#define ER_BINLOG_ROW_INJECTION_AND_STMT_MODE 1666 -#define ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1667 -#define ER_BINLOG_UNSAFE_LIMIT 1668 -#define ER_BINLOG_UNSAFE_INSERT_DELAYED 1669 -#define ER_BINLOG_UNSAFE_SYSTEM_TABLE 1670 -#define ER_BINLOG_UNSAFE_AUTOINC_COLUMNS 1671 -#define ER_BINLOG_UNSAFE_UDF 1672 -#define ER_BINLOG_UNSAFE_SYSTEM_VARIABLE 1673 -#define ER_BINLOG_UNSAFE_SYSTEM_FUNCTION 1674 -#define ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS 1675 -#define ER_MESSAGE_AND_STATEMENT 1676 -#define ER_SLAVE_CONVERSION_FAILED 1677 -#define ER_SLAVE_CANT_CREATE_CONVERSION 1678 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT 1679 -#define ER_PATH_LENGTH 1680 -#define ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT 1681 -#define ER_WRONG_NATIVE_TABLE_STRUCTURE 1682 -#define ER_WRONG_PERFSCHEMA_USAGE 1683 -#define ER_WARN_I_S_SKIPPED_TABLE 1684 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT 1685 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT 1686 -#define ER_SPATIAL_MUST_HAVE_GEOM_COL 1687 -#define ER_TOO_LONG_INDEX_COMMENT 1688 -#define ER_LOCK_ABORTED 1689 -#define ER_DATA_OUT_OF_RANGE 1690 -#define ER_WRONG_SPVAR_TYPE_IN_LIMIT 1691 -#define ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1692 -#define ER_BINLOG_UNSAFE_MIXED_STATEMENT 1693 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN 1694 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN 1695 -#define ER_FAILED_READ_FROM_PAR_FILE 1696 -#define ER_VALUES_IS_NOT_INT_TYPE_ERROR 1697 -#define ER_ACCESS_DENIED_NO_PASSWORD_ERROR 1698 -#define ER_SET_PASSWORD_AUTH_PLUGIN 1699 -#define ER_GRANT_PLUGIN_USER_EXISTS 1700 -#define ER_TRUNCATE_ILLEGAL_FK 1701 -#define ER_PLUGIN_IS_PERMANENT 1702 -#define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN 1703 -#define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX 1704 -#define ER_STMT_CACHE_FULL 1705 -#define ER_MULTI_UPDATE_KEY_CONFLICT 1706 -#define ER_TABLE_NEEDS_REBUILD 1707 -#define WARN_OPTION_BELOW_LIMIT 1708 -#define ER_INDEX_COLUMN_TOO_LONG 1709 -#define ER_ERROR_IN_TRIGGER_BODY 1710 -#define ER_ERROR_IN_UNKNOWN_TRIGGER_BODY 1711 -#define ER_INDEX_CORRUPT 1712 -#define ER_UNDO_RECORD_TOO_BIG 1713 -#define ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT 1714 -#define ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE 1715 -#define ER_BINLOG_UNSAFE_REPLACE_SELECT 1716 -#define ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT 1717 -#define ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT 1718 -#define ER_BINLOG_UNSAFE_UPDATE_IGNORE 1719 -#define ER_UNUSED_15 1720 -#define ER_UNUSED_16 1721 -#define ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT 1722 -#define ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC 1723 -#define ER_BINLOG_UNSAFE_INSERT_TWO_KEYS 1724 -#define ER_TABLE_IN_FK_CHECK 1725 -#define ER_UNUSED_1 1726 -#define ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST 1727 -#define ER_CANNOT_LOAD_FROM_TABLE_V2 1728 -#define ER_MASTER_DELAY_VALUE_OUT_OF_RANGE 1729 -#define ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT 1730 -#define ER_PARTITION_EXCHANGE_DIFFERENT_OPTION 1731 -#define ER_PARTITION_EXCHANGE_PART_TABLE 1732 -#define ER_PARTITION_EXCHANGE_TEMP_TABLE 1733 -#define ER_PARTITION_INSTEAD_OF_SUBPARTITION 1734 -#define ER_UNKNOWN_PARTITION 1735 -#define ER_TABLES_DIFFERENT_METADATA 1736 -#define ER_ROW_DOES_NOT_MATCH_PARTITION 1737 -#define ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX 1738 -#define ER_WARN_INDEX_NOT_APPLICABLE 1739 -#define ER_PARTITION_EXCHANGE_FOREIGN_KEY 1740 -#define ER_NO_SUCH_KEY_VALUE 1741 -#define ER_VALUE_TOO_LONG 1742 -#define ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE 1743 -#define ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE 1744 -#define ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX 1745 -#define ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT 1746 -#define ER_PARTITION_CLAUSE_ON_NONPARTITIONED 1747 -#define ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET 1748 -#define ER_UNUSED_5 1749 -#define ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE 1750 -#define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE 1751 -#define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE 1752 -#define ER_MTS_FEATURE_IS_NOT_SUPPORTED 1753 -#define ER_MTS_UPDATED_DBS_GREATER_MAX 1754 -#define ER_MTS_CANT_PARALLEL 1755 -#define ER_MTS_INCONSISTENT_DATA 1756 -#define ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING 1757 -#define ER_DA_INVALID_CONDITION_NUMBER 1758 -#define ER_INSECURE_PLAIN_TEXT 1759 -#define ER_INSECURE_CHANGE_MASTER 1760 -#define ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO 1761 -#define ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO 1762 -#define ER_SQLTHREAD_WITH_SECURE_SLAVE 1763 -#define ER_TABLE_HAS_NO_FT 1764 -#define ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER 1765 -#define ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION 1766 -#define ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST 1767 -#define ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL 1768 -#define ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION 1769 -#define ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL 1770 -#define ER_SKIPPING_LOGGED_TRANSACTION 1771 -#define ER_MALFORMED_GTID_SET_SPECIFICATION 1772 -#define ER_MALFORMED_GTID_SET_ENCODING 1773 -#define ER_MALFORMED_GTID_SPECIFICATION 1774 -#define ER_GNO_EXHAUSTED 1775 -#define ER_BAD_SLAVE_AUTO_POSITION 1776 -#define ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON 1777 -#define ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET 1778 -#define ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON 1779 -#define ER_GTID_MODE_REQUIRES_BINLOG 1780 -#define ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF 1781 -#define ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON 1782 -#define ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF 1783 -#define ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF 1784 -#define ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE 1785 -#define ER_GTID_UNSAFE_CREATE_SELECT 1786 -#define ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION 1787 -#define ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME 1788 -#define ER_MASTER_HAS_PURGED_REQUIRED_GTIDS 1789 -#define ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID 1790 -#define ER_UNKNOWN_EXPLAIN_FORMAT 1791 -#define ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION 1792 -#define ER_TOO_LONG_TABLE_PARTITION_COMMENT 1793 -#define ER_SLAVE_CONFIGURATION 1794 -#define ER_INNODB_FT_LIMIT 1795 -#define ER_INNODB_NO_FT_TEMP_TABLE 1796 -#define ER_INNODB_FT_WRONG_DOCID_COLUMN 1797 -#define ER_INNODB_FT_WRONG_DOCID_INDEX 1798 -#define ER_INNODB_ONLINE_LOG_TOO_BIG 1799 -#define ER_UNKNOWN_ALTER_ALGORITHM 1800 -#define ER_UNKNOWN_ALTER_LOCK 1801 -#define ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS 1802 -#define ER_MTS_RECOVERY_FAILURE 1803 -#define ER_MTS_RESET_WORKERS 1804 -#define ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2 1805 -#define ER_SLAVE_SILENT_RETRY_TRANSACTION 1806 -#define ER_UNUSED_22 1807 -#define ER_TABLE_SCHEMA_MISMATCH 1808 -#define ER_TABLE_IN_SYSTEM_TABLESPACE 1809 -#define ER_IO_READ_ERROR 1810 -#define ER_IO_WRITE_ERROR 1811 -#define ER_TABLESPACE_MISSING 1812 -#define ER_TABLESPACE_EXISTS 1813 -#define ER_TABLESPACE_DISCARDED 1814 -#define ER_INTERNAL_ERROR 1815 -#define ER_INNODB_IMPORT_ERROR 1816 -#define ER_INNODB_INDEX_CORRUPT 1817 -#define ER_INVALID_YEAR_COLUMN_LENGTH 1818 -#define ER_NOT_VALID_PASSWORD 1819 -#define ER_MUST_CHANGE_PASSWORD 1820 -#define ER_FK_NO_INDEX_CHILD 1821 -#define ER_FK_NO_INDEX_PARENT 1822 -#define ER_FK_FAIL_ADD_SYSTEM 1823 -#define ER_FK_CANNOT_OPEN_PARENT 1824 -#define ER_FK_INCORRECT_OPTION 1825 -#define ER_DUP_CONSTRAINT_NAME 1826 -#define ER_PASSWORD_FORMAT 1827 -#define ER_FK_COLUMN_CANNOT_DROP 1828 -#define ER_FK_COLUMN_CANNOT_DROP_CHILD 1829 -#define ER_FK_COLUMN_NOT_NULL 1830 -#define ER_DUP_INDEX 1831 -#define ER_FK_COLUMN_CANNOT_CHANGE 1832 -#define ER_FK_COLUMN_CANNOT_CHANGE_CHILD 1833 -#define ER_FK_CANNOT_DELETE_PARENT 1834 -#define ER_MALFORMED_PACKET 1835 -#define ER_READ_ONLY_MODE 1836 -#define ER_GTID_NEXT_TYPE_UNDEFINED_GROUP 1837 -#define ER_VARIABLE_NOT_SETTABLE_IN_SP 1838 -#define ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF 1839 -#define ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY 1840 -#define ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY 1841 -#define ER_GTID_PURGED_WAS_CHANGED 1842 -#define ER_GTID_EXECUTED_WAS_CHANGED 1843 -#define ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES 1844 -#define ER_ALTER_OPERATION_NOT_SUPPORTED 1845 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON 1846 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY 1847 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION 1848 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME 1849 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE 1850 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK 1851 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE 1852 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK 1853 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC 1854 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS 1855 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS 1856 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS 1857 -#define ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE 1858 -#define ER_DUP_UNKNOWN_IN_INDEX 1859 -#define ER_IDENT_CAUSES_TOO_LONG_PATH 1860 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL 1861 -#define ER_MUST_CHANGE_PASSWORD_LOGIN 1862 -#define ER_ROW_IN_WRONG_PARTITION 1863 -#define ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX 1864 -#define ER_INNODB_NO_FT_USES_PARSER 1865 -#define ER_BINLOG_LOGICAL_CORRUPTION 1866 -#define ER_WARN_PURGE_LOG_IN_USE 1867 -#define ER_WARN_PURGE_LOG_IS_ACTIVE 1868 -#define ER_AUTO_INCREMENT_CONFLICT 1869 -#define WARN_ON_BLOCKHOLE_IN_RBR 1870 -#define ER_SLAVE_MI_INIT_REPOSITORY 1871 -#define ER_SLAVE_RLI_INIT_REPOSITORY 1872 -#define ER_ACCESS_DENIED_CHANGE_USER_ERROR 1873 -#define ER_INNODB_READ_ONLY 1874 -#define ER_STOP_SLAVE_SQL_THREAD_TIMEOUT 1875 -#define ER_STOP_SLAVE_IO_THREAD_TIMEOUT 1876 -#define ER_TABLE_CORRUPT 1877 -#define ER_TEMP_FILE_WRITE_FAILURE 1878 -#define ER_INNODB_FT_AUX_NOT_HEX_ID 1879 -#define ER_LAST_MYSQL_ERROR_MESSAGE 1880 -#define ER_ERROR_LAST_SECTION_1 1880 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_2 1900 -#define ER_UNUSED_18 1900 -#define ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED 1901 -#define ER_UNUSED_19 1902 -#define ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN 1903 -#define ER_KEY_BASED_ON_GENERATED_VIRTUAL_COLUMN 1904 -#define ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN 1905 -#define ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN 1906 -#define ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN 1907 -#define ER_UNUSED_20 1908 -#define ER_UNUSED_21 1909 -#define ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS 1910 -#define ER_UNKNOWN_OPTION 1911 -#define ER_BAD_OPTION_VALUE 1912 -#define ER_UNUSED_6 1913 -#define ER_UNUSED_7 1914 -#define ER_UNUSED_8 1915 -#define ER_DATA_OVERFLOW 1916 -#define ER_DATA_TRUNCATED 1917 -#define ER_BAD_DATA 1918 -#define ER_DYN_COL_WRONG_FORMAT 1919 -#define ER_DYN_COL_IMPLEMENTATION_LIMIT 1920 -#define ER_DYN_COL_DATA 1921 -#define ER_DYN_COL_WRONG_CHARSET 1922 -#define ER_ILLEGAL_SUBQUERY_OPTIMIZER_SWITCHES 1923 -#define ER_QUERY_CACHE_IS_DISABLED 1924 -#define ER_QUERY_CACHE_IS_GLOBALY_DISABLED 1925 -#define ER_VIEW_ORDERBY_IGNORED 1926 -#define ER_CONNECTION_KILLED 1927 -#define ER_UNUSED_12 1928 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SKIP_REPLICATION 1929 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_SKIP_REPLICATION 1930 -#define ER_QUERY_EXCEEDED_ROWS_EXAMINED_LIMIT 1931 -#define ER_NO_SUCH_TABLE_IN_ENGINE 1932 -#define ER_TARGET_NOT_EXPLAINABLE 1933 -#define ER_CONNECTION_ALREADY_EXISTS 1934 -#define ER_MASTER_LOG_PREFIX 1935 -#define ER_CANT_START_STOP_SLAVE 1936 -#define ER_SLAVE_STARTED 1937 -#define ER_SLAVE_STOPPED 1938 -#define ER_SQL_DISCOVER_ERROR 1939 -#define ER_FAILED_GTID_STATE_INIT 1940 -#define ER_INCORRECT_GTID_STATE 1941 -#define ER_CANNOT_UPDATE_GTID_STATE 1942 -#define ER_DUPLICATE_GTID_DOMAIN 1943 -#define ER_GTID_OPEN_TABLE_FAILED 1944 -#define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG 1945 -#define ER_CANNOT_LOAD_SLAVE_GTID_STATE 1946 -#define ER_MASTER_GTID_POS_CONFLICTS_WITH_BINLOG 1947 -#define ER_MASTER_GTID_POS_MISSING_DOMAIN 1948 -#define ER_UNTIL_REQUIRES_USING_GTID 1949 -#define ER_GTID_STRICT_OUT_OF_ORDER 1950 -#define ER_GTID_START_FROM_BINLOG_HOLE 1951 -#define ER_SLAVE_UNEXPECTED_MASTER_SWITCH 1952 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1953 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1954 -#define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG2 1955 -#define ER_BINLOG_MUST_BE_EMPTY 1956 -#define ER_NO_SUCH_QUERY 1957 -#define ER_BAD_BASE64_DATA 1958 -#define ER_INVALID_ROLE 1959 -#define ER_INVALID_CURRENT_USER 1960 -#define ER_CANNOT_GRANT_ROLE 1961 -#define ER_CANNOT_REVOKE_ROLE 1962 -#define ER_CHANGE_SLAVE_PARALLEL_THREADS_ACTIVE 1963 -#define ER_PRIOR_COMMIT_FAILED 1964 -#define ER_IT_IS_A_VIEW 1965 -#define ER_SLAVE_SKIP_NOT_IN_GTID 1966 -#define ER_TABLE_DEFINITION_TOO_BIG 1967 -#define ER_PLUGIN_INSTALLED 1968 -#define ER_STATEMENT_TIMEOUT 1969 -#define ER_SUBQUERIES_NOT_SUPPORTED 1970 -#define ER_SET_STATEMENT_NOT_SUPPORTED 1971 -#define ER_UNUSED_9 1972 -#define ER_USER_CREATE_EXISTS 1973 -#define ER_USER_DROP_EXISTS 1974 -#define ER_ROLE_CREATE_EXISTS 1975 -#define ER_ROLE_DROP_EXISTS 1976 -#define ER_CANNOT_CONVERT_CHARACTER 1977 -#define ER_INVALID_DEFAULT_VALUE_FOR_FIELD 1978 -#define ER_KILL_QUERY_DENIED_ERROR 1979 -#define ER_NO_EIS_FOR_FIELD 1980 -#define ER_WARN_AGGFUNC_DEPENDENCE 1981 -#define WARN_INNODB_PARTITION_OPTION_IGNORED 1982 -#define ER_ERROR_LAST_SECTION_2 1982 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_3 2000 -#define ER_ERROR_LAST_SECTION_3 2000 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_4 3000 -#define ER_FILE_CORRUPT 3000 -#define ER_ERROR_ON_MASTER 3001 -#define ER_INCONSISTENT_ERROR 3002 -#define ER_STORAGE_ENGINE_NOT_LOADED 3003 -#define ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER 3004 -#define ER_WARN_LEGACY_SYNTAX_CONVERTED 3005 -#define ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN 3006 -#define ER_CANNOT_DISCARD_TEMPORARY_TABLE 3007 -#define ER_FK_DEPTH_EXCEEDED 3008 -#define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2 3009 -#define ER_WARN_TRIGGER_DOESNT_HAVE_CREATED 3010 -#define ER_REFERENCED_TRG_DOES_NOT_EXIST_MYSQL 3011 -#define ER_EXPLAIN_NOT_SUPPORTED 3012 -#define ER_INVALID_FIELD_SIZE 3013 -#define ER_MISSING_HA_CREATE_OPTION 3014 -#define ER_ENGINE_OUT_OF_MEMORY 3015 -#define ER_PASSWORD_EXPIRE_ANONYMOUS_USER 3016 -#define ER_SLAVE_SQL_THREAD_MUST_STOP 3017 -#define ER_NO_FT_MATERIALIZED_SUBQUERY 3018 -#define ER_INNODB_UNDO_LOG_FULL 3019 -#define ER_INVALID_ARGUMENT_FOR_LOGARITHM 3020 -#define ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP 3021 -#define ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO 3022 -#define ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS 3023 -#define ER_QUERY_TIMEOUT 3024 -#define ER_NON_RO_SELECT_DISABLE_TIMER 3025 -#define ER_DUP_LIST_ENTRY 3026 -#define ER_SQL_MODE_NO_EFFECT 3027 -#define ER_AGGREGATE_ORDER_FOR_UNION 3028 -#define ER_AGGREGATE_ORDER_NON_AGG_QUERY 3029 -#define ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR 3030 -#define ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER 3031 -#define ER_SERVER_OFFLINE_MODE 3032 -#define ER_GIS_DIFFERENT_SRIDS 3033 -#define ER_GIS_UNSUPPORTED_ARGUMENT 3034 -#define ER_GIS_UNKNOWN_ERROR 3035 -#define ER_GIS_UNKNOWN_EXCEPTION 3036 -#define ER_GIS_INVALID_DATA 3037 -#define ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION 3038 -#define ER_BOOST_GEOMETRY_CENTROID_EXCEPTION 3039 -#define ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION 3040 -#define ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION 3041 -#define ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION 3042 -#define ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION 3043 -#define ER_STD_BAD_ALLOC_ERROR 3044 -#define ER_STD_DOMAIN_ERROR 3045 -#define ER_STD_LENGTH_ERROR 3046 -#define ER_STD_INVALID_ARGUMENT 3047 -#define ER_STD_OUT_OF_RANGE_ERROR 3048 -#define ER_STD_OVERFLOW_ERROR 3049 -#define ER_STD_RANGE_ERROR 3050 -#define ER_STD_UNDERFLOW_ERROR 3051 -#define ER_STD_LOGIC_ERROR 3052 -#define ER_STD_RUNTIME_ERROR 3053 -#define ER_STD_UNKNOWN_EXCEPTION 3054 -#define ER_GIS_DATA_WRONG_ENDIANESS 3055 -#define ER_CHANGE_MASTER_PASSWORD_LENGTH 3056 -#define ER_USER_LOCK_WRONG_NAME 3057 -#define ER_USER_LOCK_DEADLOCK 3058 -#define ER_REPLACE_INACCESSIBLE_ROWS 3059 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS 3060 -#define ER_ERROR_LAST_SECTION_4 3060 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_5 4000 -#define ER_COMMULTI_BADCONTEXT 4000 -#define ER_BAD_COMMAND_IN_MULTI 4001 -#define ER_WITH_COL_WRONG_LIST 4002 -#define ER_TOO_MANY_DEFINITIONS_IN_WITH_CLAUSE 4003 -#define ER_DUP_QUERY_NAME 4004 -#define ER_RECURSIVE_WITHOUT_ANCHORS 4005 -#define ER_UNACCEPTABLE_MUTUAL_RECURSION 4006 -#define ER_REF_TO_RECURSIVE_WITH_TABLE_IN_DERIVED 4007 -#define ER_NOT_STANDARD_COMPLIANT_RECURSIVE 4008 -#define ER_WRONG_WINDOW_SPEC_NAME 4009 -#define ER_DUP_WINDOW_NAME 4010 -#define ER_PARTITION_LIST_IN_REFERENCING_WINDOW_SPEC 4011 -#define ER_ORDER_LIST_IN_REFERENCING_WINDOW_SPEC 4012 -#define ER_WINDOW_FRAME_IN_REFERENCED_WINDOW_SPEC 4013 -#define ER_BAD_COMBINATION_OF_WINDOW_FRAME_BOUND_SPECS 4014 -#define ER_WRONG_PLACEMENT_OF_WINDOW_FUNCTION 4015 -#define ER_WINDOW_FUNCTION_IN_WINDOW_SPEC 4016 -#define ER_NOT_ALLOWED_WINDOW_FRAME 4017 -#define ER_NO_ORDER_LIST_IN_WINDOW_SPEC 4018 -#define ER_RANGE_FRAME_NEEDS_SIMPLE_ORDERBY 4019 -#define ER_WRONG_TYPE_FOR_ROWS_FRAME 4020 -#define ER_WRONG_TYPE_FOR_RANGE_FRAME 4021 -#define ER_FRAME_EXCLUSION_NOT_SUPPORTED 4022 -#define ER_WINDOW_FUNCTION_DONT_HAVE_FRAME 4023 -#define ER_INVALID_NTILE_ARGUMENT 4024 -#define ER_CONSTRAINT_FAILED 4025 -#define ER_EXPRESSION_IS_TOO_BIG 4026 -#define ER_ERROR_EVALUATING_EXPRESSION 4027 -#define ER_CALCULATING_DEFAULT_VALUE 4028 -#define ER_EXPRESSION_REFERS_TO_UNINIT_FIELD 4029 -#define ER_PARTITION_DEFAULT_ERROR 4030 -#define ER_REFERENCED_TRG_DOES_NOT_EXIST 4031 -#define ER_INVALID_DEFAULT_PARAM 4032 -#define ER_BINLOG_NON_SUPPORTED_BULK 4033 -#define ER_BINLOG_UNCOMPRESS_ERROR 4034 -#define ER_JSON_BAD_CHR 4035 -#define ER_JSON_NOT_JSON_CHR 4036 -#define ER_JSON_EOS 4037 -#define ER_JSON_SYNTAX 4038 -#define ER_JSON_ESCAPING 4039 -#define ER_JSON_DEPTH 4040 -#define ER_JSON_PATH_EOS 4041 -#define ER_JSON_PATH_SYNTAX 4042 -#define ER_JSON_PATH_DEPTH 4043 -#define ER_JSON_PATH_NO_WILDCARD 4044 -#define ER_JSON_PATH_ARRAY 4045 -#define ER_JSON_ONE_OR_ALL 4046 -#define ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE 4047 -#define ER_GEOJSON_INCORRECT 4048 -#define ER_GEOJSON_TOO_FEW_POINTS 4049 -#define ER_GEOJSON_NOT_CLOSED 4050 -#define ER_JSON_PATH_EMPTY 4051 -#define ER_SLAVE_SAME_ID 4052 -#define ER_FLASHBACK_NOT_SUPPORTED 4053 -#define ER_KEYS_OUT_OF_ORDER 4054 -#define ER_OVERLAPPING_KEYS 4055 -#define ER_REQUIRE_ROW_BINLOG_FORMAT 4056 -#define ER_ISOLATION_MODE_NOT_SUPPORTED 4057 -#define ER_ON_DUPLICATE_DISABLED 4058 -#define ER_UPDATES_WITH_CONSISTENT_SNAPSHOT 4059 -#define ER_ROLLBACK_ONLY 4060 -#define ER_ROLLBACK_TO_SAVEPOINT 4061 -#define ER_ISOLATION_LEVEL_WITH_CONSISTENT_SNAPSHOT 4062 -#define ER_UNSUPPORTED_COLLATION 4063 -#define ER_METADATA_INCONSISTENCY 4064 -#define ER_CF_DIFFERENT 4065 -#define ER_RDB_TTL_DURATION_FORMAT 4066 -#define ER_RDB_STATUS_GENERAL 4067 -#define ER_RDB_STATUS_MSG 4068 -#define ER_RDB_TTL_UNSUPPORTED 4069 -#define ER_RDB_TTL_COL_FORMAT 4070 -#define ER_PER_INDEX_CF_DEPRECATED 4071 -#define ER_KEY_CREATE_DURING_ALTER 4072 -#define ER_SK_POPULATE_DURING_ALTER 4073 -#define ER_SUM_FUNC_WITH_WINDOW_FUNC_AS_ARG 4074 -#define ER_NET_OK_PACKET_TOO_LARGE 4075 -#define ER_GEOJSON_EMPTY_COORDINATES 4076 -#define ER_MYROCKS_CANT_NOPAD_COLLATION 4077 -#define ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION 4078 -#define ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION 4079 -#define ER_WRONG_PARAMCOUNT_TO_CURSOR 4080 -#define ER_UNKNOWN_STRUCTURED_VARIABLE 4081 -#define ER_ROW_VARIABLE_DOES_NOT_HAVE_FIELD 4082 -#define ER_END_IDENTIFIER_DOES_NOT_MATCH 4083 -#define ER_SEQUENCE_RUN_OUT 4084 -#define ER_SEQUENCE_INVALID_DATA 4085 -#define ER_SEQUENCE_INVALID_TABLE_STRUCTURE 4086 -#define ER_SEQUENCE_ACCESS_ERROR 4087 -#define ER_SEQUENCE_BINLOG_FORMAT 4088 -#define ER_NOT_SEQUENCE 4089 -#define ER_NOT_SEQUENCE2 4090 -#define ER_UNKNOWN_SEQUENCES 4091 -#define ER_UNKNOWN_VIEW 4092 -#define ER_WRONG_INSERT_INTO_SEQUENCE 4093 -#define ER_SP_STACK_TRACE 4094 -#define ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY 4095 -#define ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED 4096 -#define ER_COMPRESSED_COLUMN_USED_AS_KEY 4097 -#define ER_UNKNOWN_COMPRESSION_METHOD 4098 -#define ER_WRONG_NUMBER_OF_VALUES_IN_TVC 4099 -#define ER_FIELD_REFERENCE_IN_TVC 4100 -#define ER_WRONG_TYPE_FOR_PERCENTILE_FUNC 4101 -#define ER_ARGUMENT_NOT_CONSTANT 4102 -#define ER_ARGUMENT_OUT_OF_RANGE 4103 -#define ER_WRONG_TYPE_OF_ARGUMENT 4104 -#define ER_NOT_AGGREGATE_FUNCTION 4105 -#define ER_INVALID_AGGREGATE_FUNCTION 4106 -#define ER_INVALID_VALUE_TO_LIMIT 4107 -#define ER_INVISIBLE_NOT_NULL_WITHOUT_DEFAULT 4108 -#define ER_UPDATE_INFO_WITH_SYSTEM_VERSIONING 4109 -#define ER_VERS_FIELD_WRONG_TYPE 4110 -#define ER_VERS_ENGINE_UNSUPPORTED 4111 -#define ER_UNUSED_23 4112 -#define ER_PARTITION_WRONG_TYPE 4113 -#define WARN_VERS_PART_FULL 4114 -#define WARN_VERS_PARAMETERS 4115 -#define ER_VERS_DROP_PARTITION_INTERVAL 4116 -#define ER_UNUSED_25 4117 -#define WARN_VERS_PART_NON_HISTORICAL 4118 -#define ER_VERS_ALTER_NOT_ALLOWED 4119 -#define ER_VERS_ALTER_ENGINE_PROHIBITED 4120 -#define ER_VERS_RANGE_PROHIBITED 4121 -#define ER_CONFLICTING_FOR_SYSTEM_TIME 4122 -#define ER_VERS_TABLE_MUST_HAVE_COLUMNS 4123 -#define ER_VERS_NOT_VERSIONED 4124 -#define ER_MISSING 4125 -#define ER_VERS_PERIOD_COLUMNS 4126 -#define ER_PART_WRONG_VALUE 4127 -#define ER_VERS_WRONG_PARTS 4128 -#define ER_VERS_NO_TRX_ID 4129 -#define ER_VERS_ALTER_SYSTEM_FIELD 4130 -#define ER_DROP_VERSIONING_SYSTEM_TIME_PARTITION 4131 -#define ER_VERS_DB_NOT_SUPPORTED 4132 -#define ER_VERS_TRT_IS_DISABLED 4133 -#define ER_VERS_DUPLICATE_ROW_START_END 4134 -#define ER_VERS_ALREADY_VERSIONED 4135 -#define ER_UNUSED_24 4136 -#define ER_VERS_NOT_SUPPORTED 4137 -#define ER_VERS_TRX_PART_HISTORIC_ROW_NOT_SUPPORTED 4138 -#define ER_INDEX_FILE_FULL 4139 -#define ER_UPDATED_COLUMN_ONLY_ONCE 4140 -#define ER_EMPTY_ROW_IN_TVC 4141 -#define ER_VERS_QUERY_IN_PARTITION 4142 -#define ER_KEY_DOESNT_SUPPORT 4143 -#define ER_ALTER_OPERATION_TABLE_OPTIONS_NEED_REBUILD 4144 -#define ER_BACKUP_LOCK_IS_ACTIVE 4145 -#define ER_BACKUP_NOT_RUNNING 4146 -#define ER_BACKUP_WRONG_STAGE 4147 -#define ER_BACKUP_STAGE_FAILED 4148 -#define ER_BACKUP_UNKNOWN_STAGE 4149 -#define ER_USER_IS_BLOCKED 4150 -#define ER_ACCOUNT_HAS_BEEN_LOCKED 4151 -#define ER_PERIOD_TEMPORARY_NOT_ALLOWED 4152 -#define ER_PERIOD_TYPES_MISMATCH 4153 -#define ER_MORE_THAN_ONE_PERIOD 4154 -#define ER_PERIOD_FIELD_WRONG_ATTRIBUTES 4155 -#define ER_PERIOD_NOT_FOUND 4156 -#define ER_PERIOD_COLUMNS_UPDATED 4157 -#define ER_PERIOD_CONSTRAINT_DROP 4158 -#define ER_TOO_LONG_KEYPART 4159 -#define ER_TOO_LONG_DATABASE_COMMENT 4160 -#define ER_UNKNOWN_DATA_TYPE 4161 -#define ER_UNKNOWN_OPERATOR 4162 -#define ER_WARN_HISTORY_ROW_START_TIME 4163 -#define ER_PART_STARTS_BEYOND_INTERVAL 4164 -#define ER_GALERA_REPLICATION_NOT_SUPPORTED 4165 -#define ER_LOAD_INFILE_CAPABILITY_DISABLED 4166 -#define ER_NO_SECURE_TRANSPORTS_CONFIGURED 4167 -#define ER_SLAVE_IGNORED_SHARED_TABLE 4168 -#define ER_NO_AUTOINCREMENT_WITH_UNIQUE 4169 -#define ER_KEY_CONTAINS_PERIOD_FIELDS 4170 -#define ER_KEY_CANT_HAVE_WITHOUT_OVERLAPS 4171 -#define ER_NOT_ALLOWED_IN_THIS_CONTEXT 4172 -#define ER_DATA_WAS_COMMITED_UNDER_ROLLBACK 4173 -#define ER_ERROR_LAST 4173 -#endif /* ER_ERROR_FIRST */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/big_endian.h b/VCMP-LUA/modules/mariadb/include/mysql/server/big_endian.h deleted file mode 100644 index 6487f82..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/big_endian.h +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Data in big-endian format. -*/ -#define float4store(T,A) do { *(T)= ((uchar *) &A)[3];\ - *((T)+1)=(char) ((uchar *) &A)[2];\ - *((T)+2)=(char) ((uchar *) &A)[1];\ - *((T)+3)=(char) ((uchar *) &A)[0]; } while(0) - -#define float4get(V,M) do { float def_temp;\ - ((uchar*) &def_temp)[0]=(M)[3];\ - ((uchar*) &def_temp)[1]=(M)[2];\ - ((uchar*) &def_temp)[2]=(M)[1];\ - ((uchar*) &def_temp)[3]=(M)[0];\ - (V)=def_temp; } while(0) - -#define float8store(T,V) do { *(T)= ((uchar *) &V)[7];\ - *((T)+1)=(char) ((uchar *) &V)[6];\ - *((T)+2)=(char) ((uchar *) &V)[5];\ - *((T)+3)=(char) ((uchar *) &V)[4];\ - *((T)+4)=(char) ((uchar *) &V)[3];\ - *((T)+5)=(char) ((uchar *) &V)[2];\ - *((T)+6)=(char) ((uchar *) &V)[1];\ - *((T)+7)=(char) ((uchar *) &V)[0]; } while(0) - -#define float8get(V,M) do { double def_temp;\ - ((uchar*) &def_temp)[0]=(M)[7];\ - ((uchar*) &def_temp)[1]=(M)[6];\ - ((uchar*) &def_temp)[2]=(M)[5];\ - ((uchar*) &def_temp)[3]=(M)[4];\ - ((uchar*) &def_temp)[4]=(M)[3];\ - ((uchar*) &def_temp)[5]=(M)[2];\ - ((uchar*) &def_temp)[6]=(M)[1];\ - ((uchar*) &def_temp)[7]=(M)[0];\ - (V) = def_temp; } while(0) - -#define ushortget(V,M) do { V = (uint16) (((uint16) ((uchar) (M)[1]))+\ - ((uint16) ((uint16) (M)[0]) << 8)); } while(0) -#define shortget(V,M) do { V = (short) (((short) ((uchar) (M)[1]))+\ - ((short) ((short) (M)[0]) << 8)); } while(0) -#define longget(V,M) do { int32 def_temp;\ - ((uchar*) &def_temp)[0]=(M)[0];\ - ((uchar*) &def_temp)[1]=(M)[1];\ - ((uchar*) &def_temp)[2]=(M)[2];\ - ((uchar*) &def_temp)[3]=(M)[3];\ - (V)=def_temp; } while(0) -#define ulongget(V,M) do { uint32 def_temp;\ - ((uchar*) &def_temp)[0]=(M)[0];\ - ((uchar*) &def_temp)[1]=(M)[1];\ - ((uchar*) &def_temp)[2]=(M)[2];\ - ((uchar*) &def_temp)[3]=(M)[3];\ - (V)=def_temp; } while(0) -#define shortstore(T,A) do { uint def_temp=(uint) (A) ;\ - *(((char*)T)+1)=(char)(def_temp); \ - *(((char*)T)+0)=(char)(def_temp >> 8); } while(0) -#define longstore(T,A) do { *(((char*)T)+3)=((A));\ - *(((char*)T)+2)=(((A) >> 8));\ - *(((char*)T)+1)=(((A) >> 16));\ - *(((char*)T)+0)=(((A) >> 24)); } while(0) - -#define floatget(V,M) memcpy(&V, (M), sizeof(float)) -/* Cast away type qualifiers (necessary as macro takes argument by value). */ -#define floatstore(T,V) memcpy((T), (void*) (&V), sizeof(float)) -#define doubleget(V,M) memcpy(&V, (M), sizeof(double)) -/* Cast away type qualifiers (necessary as macro takes argument by value). */ -#define doublestore(T,V) memcpy((T), (void*) &V, sizeof(double)) -#define longlongget(V,M) memcpy(&V, (M), sizeof(ulonglong)) -#define longlongstore(T,V) memcpy((T), &V, sizeof(ulonglong)) diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic.h b/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic.h deleted file mode 100644 index 8381941..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic.h +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Endianness-independent definitions for architectures other - than the x86 architecture. -*/ -#define sint2korr(A) (int16) (((int16) ((uchar) (A)[0])) |\ - ((int16) ((int16) (A)[1]) << 8)) -#define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ - (((uint32) 255L << 24) | \ - (((uint32) (uchar) (A)[2]) << 16) |\ - (((uint32) (uchar) (A)[1]) << 8) | \ - ((uint32) (uchar) (A)[0])) : \ - (((uint32) (uchar) (A)[2]) << 16) |\ - (((uint32) (uchar) (A)[1]) << 8) | \ - ((uint32) (uchar) (A)[0]))) -#define sint4korr(A) (int32) (((int32) ((uchar) (A)[0])) |\ - (((int32) ((uchar) (A)[1]) << 8)) |\ - (((int32) ((uchar) (A)[2]) << 16)) |\ - (((int32) ((int16) (A)[3]) << 24))) -#define sint8korr(A) (longlong) uint8korr(A) -#define uint2korr(A) (uint16) (((uint16) ((uchar) (A)[0])) |\ - ((uint16) ((uchar) (A)[1]) << 8)) -#define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ - (((uint32) ((uchar) (A)[1])) << 8) |\ - (((uint32) ((uchar) (A)[2])) << 16)) -#define uint4korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ - (((uint32) ((uchar) (A)[1])) << 8) |\ - (((uint32) ((uchar) (A)[2])) << 16) |\ - (((uint32) ((uchar) (A)[3])) << 24)) -#define uint5korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) |\ - (((uint32) ((uchar) (A)[1])) << 8) |\ - (((uint32) ((uchar) (A)[2])) << 16) |\ - (((uint32) ((uchar) (A)[3])) << 24)) |\ - (((ulonglong) ((uchar) (A)[4])) << 32)) -#define uint6korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) | \ - (((uint32) ((uchar) (A)[1])) << 8) | \ - (((uint32) ((uchar) (A)[2])) << 16) | \ - (((uint32) ((uchar) (A)[3])) << 24)) | \ - (((ulonglong) ((uchar) (A)[4])) << 32) | \ - (((ulonglong) ((uchar) (A)[5])) << 40)) -#define uint8korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) |\ - (((uint32) ((uchar) (A)[1])) << 8) |\ - (((uint32) ((uchar) (A)[2])) << 16) |\ - (((uint32) ((uchar) (A)[3])) << 24)) |\ - (((ulonglong) (((uint32) ((uchar) (A)[4])) |\ - (((uint32) ((uchar) (A)[5])) << 8) |\ - (((uint32) ((uchar) (A)[6])) << 16) |\ - (((uint32) ((uchar) (A)[7])) << 24))) <<\ - 32)) -#define int2store(T,A) do { uint def_temp= (uint) (A) ;\ - *((uchar*) (T))= (uchar)(def_temp); \ - *((uchar*) (T)+1)=(uchar)((def_temp >> 8)); \ - } while(0) -#define int3store(T,A) do { /*lint -save -e734 */\ - *((uchar*)(T))=(uchar) ((A));\ - *((uchar*) (T)+1)=(uchar) (((A) >> 8));\ - *((uchar*)(T)+2)=(uchar) (((A) >> 16)); \ - /*lint -restore */} while(0) -#define int4store(T,A) do { *((char *)(T))=(char) ((A));\ - *(((char *)(T))+1)=(char) (((A) >> 8));\ - *(((char *)(T))+2)=(char) (((A) >> 16));\ - *(((char *)(T))+3)=(char) (((A) >> 24));\ - } while(0) -#define int5store(T,A) do { *((char *)(T))= (char)((A)); \ - *(((char *)(T))+1)= (char)(((A) >> 8)); \ - *(((char *)(T))+2)= (char)(((A) >> 16)); \ - *(((char *)(T))+3)= (char)(((A) >> 24)); \ - *(((char *)(T))+4)= (char)(((A) >> 32)); \ - } while(0) -#define int6store(T,A) do { *((char *)(T))= (char)((A)); \ - *(((char *)(T))+1)= (char)(((A) >> 8)); \ - *(((char *)(T))+2)= (char)(((A) >> 16)); \ - *(((char *)(T))+3)= (char)(((A) >> 24)); \ - *(((char *)(T))+4)= (char)(((A) >> 32)); \ - *(((char *)(T))+5)= (char)(((A) >> 40)); \ - } while(0) -#define int8store(T,A) do { uint def_temp= (uint) (A), \ - def_temp2= (uint) ((A) >> 32); \ - int4store((T),def_temp); \ - int4store((T+4),def_temp2);\ - } while(0) diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic_x86.h b/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic_x86.h deleted file mode 100644 index 72e00be..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic_x86.h +++ /dev/null @@ -1,88 +0,0 @@ -/* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Optimized function-like macros for the x86 architecture (_WIN32 included). -*/ -#define sint2korr(A) (*((const int16 *) (A))) -#define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ - (((uint32) 255L << 24) | \ - (((uint32) (uchar) (A)[2]) << 16) |\ - (((uint32) (uchar) (A)[1]) << 8) | \ - ((uint32) (uchar) (A)[0])) : \ - (((uint32) (uchar) (A)[2]) << 16) |\ - (((uint32) (uchar) (A)[1]) << 8) | \ - ((uint32) (uchar) (A)[0]))) -#define sint4korr(A) (*((const long *) (A))) -#define uint2korr(A) (*((const uint16 *) (A))) -#define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ - (((uint32) ((uchar) (A)[1])) << 8) |\ - (((uint32) ((uchar) (A)[2])) << 16)) -#define uint4korr(A) (*((const uint32 *) (A))) -#define uint5korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) |\ - (((uint32) ((uchar) (A)[1])) << 8) |\ - (((uint32) ((uchar) (A)[2])) << 16) |\ - (((uint32) ((uchar) (A)[3])) << 24)) |\ - (((ulonglong) ((uchar) (A)[4])) << 32)) -#define uint6korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) | \ - (((uint32) ((uchar) (A)[1])) << 8) | \ - (((uint32) ((uchar) (A)[2])) << 16) | \ - (((uint32) ((uchar) (A)[3])) << 24)) | \ - (((ulonglong) ((uchar) (A)[4])) << 32) | \ - (((ulonglong) ((uchar) (A)[5])) << 40)) -#define uint8korr(A) (*((const ulonglong *) (A))) -#define sint8korr(A) (*((const longlong *) (A))) - -#define int2store(T,A) *((uint16*) (T))= (uint16) (A) -#define int3store(T,A) do { *(T)= (uchar) ((A));\ - *(T+1)=(uchar) (((uint) (A) >> 8));\ - *(T+2)=(uchar) (((A) >> 16));\ - } while (0) -#define int4store(T,A) *((long *) (T))= (long) (A) -#define int5store(T,A) do { *(T)= (uchar)((A));\ - *((T)+1)=(uchar) (((A) >> 8));\ - *((T)+2)=(uchar) (((A) >> 16));\ - *((T)+3)=(uchar) (((A) >> 24));\ - *((T)+4)=(uchar) (((A) >> 32));\ - } while(0) -#define int6store(T,A) do { *(T)= (uchar)((A)); \ - *((T)+1)=(uchar) (((A) >> 8)); \ - *((T)+2)=(uchar) (((A) >> 16)); \ - *((T)+3)=(uchar) (((A) >> 24)); \ - *((T)+4)=(uchar) (((A) >> 32)); \ - *((T)+5)=(uchar) (((A) >> 40)); \ - } while(0) -#define int8store(T,A) *((ulonglong *) (T))= (ulonglong) (A) -typedef union { - double v; - long m[2]; -} doubleget_union; -#define doubleget(V,M) \ -do { doubleget_union _tmp; \ - _tmp.m[0] = *((const long*)(M)); \ - _tmp.m[1] = *(((const long*) (M))+1); \ - (V) = _tmp.v; } while(0) -#define doublestore(T,V) \ -do { *((long *) T) = ((const doubleget_union *)&V)->m[0]; \ - *(((long *) T)+1) = ((const doubleget_union *)&V)->m[1]; \ - } while (0) -#define float4get(V,M) \ -do { *((float *) &(V)) = *((const float*) (M)); } while(0) -#define float8get(V,M) doubleget((V),(M)) -#define float4store(V,M) memcpy((uchar*)(V), (uchar*)(&M), sizeof(float)) -#define floatstore(T,V) memcpy((uchar*)(T), (uchar*)(&V), sizeof(float)) -#define floatget(V,M) memcpy((uchar*)(&V),(uchar*) (M), sizeof(float)) -#define float8store(V,M) doublestore((V),(M)) diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic_x86_64.h b/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic_x86_64.h deleted file mode 100644 index a25e6a2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/byte_order_generic_x86_64.h +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Optimized function-like macros for the x86 architecture (_WIN32 included). -*/ - -#define sint2korr(A) (int16) (*((int16 *) (A))) -#define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ - (((uint32) 255L << 24) | \ - (((uint32) (uchar) (A)[2]) << 16) |\ - (((uint32) (uchar) (A)[1]) << 8) | \ - ((uint32) (uchar) (A)[0])) : \ - (((uint32) (uchar) (A)[2]) << 16) |\ - (((uint32) (uchar) (A)[1]) << 8) | \ - ((uint32) (uchar) (A)[0]))) -#define sint4korr(A) (int32) (*((int32 *) (A))) -#define uint2korr(A) (uint16) (*((uint16 *) (A))) -#define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ - (((uint32) ((uchar) (A)[1])) << 8) |\ - (((uint32) ((uchar) (A)[2])) << 16)) -#define uint4korr(A) (uint32) (*((uint32 *) (A))) - - -static inline ulonglong uint5korr(const void *p) -{ - ulonglong a= *(uint32 *) p; - ulonglong b= *(4 + (uchar *) p); - return a | (b << 32); -} -static inline ulonglong uint6korr(const void *p) -{ - ulonglong a= *(uint32 *) p; - ulonglong b= *(uint16 *) (4 + (char *) p); - return a | (b << 32); -} - -#define uint8korr(A) (ulonglong) (*((ulonglong *) (A))) -#define sint8korr(A) (longlong) (*((longlong *) (A))) - -#define int2store(T,A) do { uchar *pT= (uchar*)(T);\ - *((uint16*)(pT))= (uint16) (A);\ - } while (0) - -#define int3store(T,A) do { *(T)= (uchar) ((A));\ - *(T+1)=(uchar) (((uint) (A) >> 8));\ - *(T+2)=(uchar) (((A) >> 16));\ - } while (0) - -#define int4store(T,A) do { uchar *pT= (uchar*)(T);\ - *((uint32 *) (pT))= (uint32) (A); \ - } while (0) - -#define int5store(T,A) do { uchar *pT= (uchar*)(T);\ - *((uint32 *) (pT))= (uint32) (A); \ - *((pT)+4)=(uchar) (((A) >> 32));\ - } while (0) - -#define int6store(T,A) do { uchar *pT= (uchar*)(T);\ - *((uint32 *) (pT))= (uint32) (A); \ - *((uint16*)(pT+4))= (uint16) (A >> 32);\ - } while (0) - -#define int8store(T,A) do { uchar *pT= (uchar*)(T);\ - *((ulonglong *) (pT))= (ulonglong) (A);\ - } while(0) - -#if defined(__GNUC__) - -#define HAVE_mi_uint5korr -#define HAVE_mi_uint6korr -#define HAVE_mi_uint7korr -#define HAVE_mi_uint78orr - -/* Read numbers stored in high-bytes-first order */ - -static inline ulonglong mi_uint5korr(const void *p) -{ - ulonglong a= *(uint32 *) p; - ulonglong b= *(4 + (uchar *) p); - ulonglong v= (a | (b << 32)) << 24; - asm ("bswapq %0" : "=r" (v) : "0" (v)); - return v; -} - -static inline ulonglong mi_uint6korr(const void *p) -{ - ulonglong a= *(uint32 *) p; - ulonglong b= *(uint16 *) (4 + (char *) p); - ulonglong v= (a | (b << 32)) << 16; - asm ("bswapq %0" : "=r" (v) : "0" (v)); - return v; -} - -static inline ulonglong mi_uint7korr(const void *p) -{ - ulonglong a= *(uint32 *) p; - ulonglong b= *(uint16 *) (4 + (char *) p); - ulonglong c= *(6 + (uchar *) p); - ulonglong v= (a | (b << 32) | (c << 48)) << 8; - asm ("bswapq %0" : "=r" (v) : "0" (v)); - return v; -} - -static inline ulonglong mi_uint8korr(const void *p) -{ - ulonglong v= *(ulonglong *) p; - asm ("bswapq %0" : "=r" (v) : "0" (v)); - return v; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/decimal.h b/VCMP-LUA/modules/mariadb/include/mysql/server/decimal.h deleted file mode 100644 index cab18f9..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/decimal.h +++ /dev/null @@ -1,124 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _decimal_h -#define _decimal_h - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum -{TRUNCATE=0, HALF_EVEN, HALF_UP, CEILING, FLOOR} - decimal_round_mode; -typedef int32 decimal_digit_t; - -/** - intg is the number of *decimal* digits (NOT number of decimal_digit_t's !) - before the point - frac is the number of decimal digits after the point - len is the length of buf (length of allocated space) in decimal_digit_t's, - not in bytes - sign false means positive, true means negative - buf is an array of decimal_digit_t's - */ -typedef struct st_decimal_t { - int intg, frac, len; - my_bool sign; - decimal_digit_t *buf; -} decimal_t; - -int internal_str2dec(const char *from, decimal_t *to, char **end, - my_bool fixed); -int decimal2string(const decimal_t *from, char *to, int *to_len, - int fixed_precision, int fixed_decimals, - char filler); -int decimal2ulonglong(const decimal_t *from, ulonglong *to); -int ulonglong2decimal(ulonglong from, decimal_t *to); -int decimal2longlong(const decimal_t *from, longlong *to); -int longlong2decimal(longlong from, decimal_t *to); -int decimal2double(const decimal_t *from, double *to); -int double2decimal(double from, decimal_t *to); -int decimal_actual_fraction(const decimal_t *from); -int decimal2bin(const decimal_t *from, uchar *to, int precision, int scale); -int bin2decimal(const uchar *from, decimal_t *to, int precision, int scale); - -int decimal_size(int precision, int scale); -int decimal_bin_size(int precision, int scale); -int decimal_result_size(decimal_t *from1, decimal_t *from2, char op, - int param); - -int decimal_intg(const decimal_t *from); -int decimal_add(const decimal_t *from1, const decimal_t *from2, decimal_t *to); -int decimal_sub(const decimal_t *from1, const decimal_t *from2, decimal_t *to); -int decimal_cmp(const decimal_t *from1, const decimal_t *from2); -int decimal_mul(const decimal_t *from1, const decimal_t *from2, decimal_t *to); -int decimal_div(const decimal_t *from1, const decimal_t *from2, decimal_t *to, - int scale_incr); -int decimal_mod(const decimal_t *from1, const decimal_t *from2, decimal_t *to); -int decimal_round(const decimal_t *from, decimal_t *to, int new_scale, - decimal_round_mode mode); -int decimal_is_zero(const decimal_t *from); -void max_decimal(int precision, int frac, decimal_t *to); - -#define string2decimal(A,B,C) internal_str2dec((A), (B), (C), 0) -#define string2decimal_fixed(A,B,C) internal_str2dec((A), (B), (C), 1) - -/* set a decimal_t to zero */ - -#define decimal_make_zero(dec) do { \ - (dec)->buf[0]=0; \ - (dec)->intg=1; \ - (dec)->frac=0; \ - (dec)->sign=0; \ - } while(0) - -/* - returns the length of the buffer to hold string representation - of the decimal (including decimal dot, possible sign and \0) -*/ - -#define decimal_string_size(dec) (((dec)->intg ? (dec)->intg : 1) + \ - (dec)->frac + ((dec)->frac > 0) + 2) - -/* negate a decimal */ -#define decimal_neg(dec) do { (dec)->sign^=1; } while(0) - -/* - conventions: - - decimal_smth() == 0 -- everything's ok - decimal_smth() <= 1 -- result is usable, but precision loss is possible - decimal_smth() <= 2 -- result can be unusable, most significant digits - could've been lost - decimal_smth() > 2 -- no result was generated -*/ - -#define E_DEC_OK 0 -#define E_DEC_TRUNCATED 1 -#define E_DEC_OVERFLOW 2 -#define E_DEC_DIV_ZERO 4 -#define E_DEC_BAD_NUM 8 -#define E_DEC_OOM 16 - -#define E_DEC_ERROR 31 -#define E_DEC_FATAL_ERROR 30 - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/errmsg.h b/VCMP-LUA/modules/mariadb/include/mysql/server/errmsg.h deleted file mode 100644 index c0c4cfc..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/errmsg.h +++ /dev/null @@ -1,116 +0,0 @@ -#ifndef ERRMSG_INCLUDED -#define ERRMSG_INCLUDED - -/* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Error messages numbers for MySQL clients. - The error messages itself are in libmysql/errmsg.c - - Error messages for the mysqld daemon are in sql/share/errmsg.txt -*/ - -#ifdef __cplusplus -extern "C" { -#endif -void init_client_errs(void); -void finish_client_errs(void); -extern const char *client_errors[]; /* Error messages */ -#ifdef __cplusplus -} -#endif - -#define CR_MIN_ERROR 2000 /* For easier client code */ -#define CR_MAX_ERROR 2999 -#if !defined(ER) -#define ER(X) (((X) >= CR_ERROR_FIRST && (X) <= CR_ERROR_LAST)? \ - client_errors[(X)-CR_ERROR_FIRST]: client_errors[CR_UNKNOWN_ERROR]) - -#endif -#define CLIENT_ERRMAP 2 /* Errormap used by my_error() */ - -/* Do not add error numbers before CR_ERROR_FIRST. */ -/* If necessary to add lower numbers, change CR_ERROR_FIRST accordingly. */ -#define CR_ERROR_FIRST 2000 /*Copy first error nr.*/ -#define CR_UNKNOWN_ERROR 2000 -#define CR_SOCKET_CREATE_ERROR 2001 -#define CR_CONNECTION_ERROR 2002 -#define CR_CONN_HOST_ERROR 2003 -#define CR_IPSOCK_ERROR 2004 -#define CR_UNKNOWN_HOST 2005 -#define CR_SERVER_GONE_ERROR 2006 -#define CR_VERSION_ERROR 2007 -#define CR_OUT_OF_MEMORY 2008 -#define CR_WRONG_HOST_INFO 2009 -#define CR_LOCALHOST_CONNECTION 2010 -#define CR_TCP_CONNECTION 2011 -#define CR_SERVER_HANDSHAKE_ERR 2012 -#define CR_SERVER_LOST 2013 -#define CR_COMMANDS_OUT_OF_SYNC 2014 -#define CR_NAMEDPIPE_CONNECTION 2015 -#define CR_NAMEDPIPEWAIT_ERROR 2016 -#define CR_NAMEDPIPEOPEN_ERROR 2017 -#define CR_NAMEDPIPESETSTATE_ERROR 2018 -#define CR_CANT_READ_CHARSET 2019 -#define CR_NET_PACKET_TOO_LARGE 2020 -#define CR_EMBEDDED_CONNECTION 2021 -#define CR_PROBE_SLAVE_STATUS 2022 -#define CR_PROBE_SLAVE_HOSTS 2023 -#define CR_PROBE_SLAVE_CONNECT 2024 -#define CR_PROBE_MASTER_CONNECT 2025 -#define CR_SSL_CONNECTION_ERROR 2026 -#define CR_MALFORMED_PACKET 2027 -#define CR_WRONG_LICENSE 2028 - -/* new 4.1 error codes */ -#define CR_NULL_POINTER 2029 -#define CR_NO_PREPARE_STMT 2030 -#define CR_PARAMS_NOT_BOUND 2031 -#define CR_DATA_TRUNCATED 2032 -#define CR_NO_PARAMETERS_EXISTS 2033 -#define CR_INVALID_PARAMETER_NO 2034 -#define CR_INVALID_BUFFER_USE 2035 -#define CR_UNSUPPORTED_PARAM_TYPE 2036 - -#define CR_SHARED_MEMORY_CONNECTION 2037 -#define CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR 2038 -#define CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR 2039 -#define CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR 2040 -#define CR_SHARED_MEMORY_CONNECT_MAP_ERROR 2041 -#define CR_SHARED_MEMORY_FILE_MAP_ERROR 2042 -#define CR_SHARED_MEMORY_MAP_ERROR 2043 -#define CR_SHARED_MEMORY_EVENT_ERROR 2044 -#define CR_SHARED_MEMORY_CONNECT_ABANDONED_ERROR 2045 -#define CR_SHARED_MEMORY_CONNECT_SET_ERROR 2046 -#define CR_CONN_UNKNOW_PROTOCOL 2047 -#define CR_INVALID_CONN_HANDLE 2048 -#define CR_SECURE_AUTH 2049 -#define CR_FETCH_CANCELED 2050 -#define CR_NO_DATA 2051 -#define CR_NO_STMT_METADATA 2052 -#define CR_NO_RESULT_SET 2053 -#define CR_NOT_IMPLEMENTED 2054 -#define CR_SERVER_LOST_EXTENDED 2055 -#define CR_STMT_CLOSED 2056 -#define CR_NEW_STMT_METADATA 2057 -#define CR_ALREADY_CONNECTED 2058 -#define CR_AUTH_PLUGIN_CANNOT_LOAD 2059 -#define CR_DUPLICATE_CONNECTION_ATTR 2060 -#define CR_AUTH_PLUGIN_ERR 2061 -#define CR_ERROR_LAST /*Copy last error nr:*/ 2061 -/* Add error numbers before CR_ERROR_LAST and change it accordingly. */ - -#endif /* ERRMSG_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/handler_ername.h b/VCMP-LUA/modules/mariadb/include/mysql/server/handler_ername.h deleted file mode 100644 index fe55062..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/handler_ername.h +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright (c) 2013 SkySQL Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Names of all handler error numbers. Used by mysqltest */ - -{ "HA_ERR_KEY_NOT_FOUND", HA_ERR_KEY_NOT_FOUND, "" }, -{ "HA_ERR_FOUND_DUPP_KEY", HA_ERR_FOUND_DUPP_KEY, "" }, -{ "HA_ERR_INTERNAL_ERROR", HA_ERR_INTERNAL_ERROR, "" }, -{ "HA_ERR_RECORD_CHANGED", HA_ERR_RECORD_CHANGED, "" }, -{ "HA_ERR_WRONG_INDEX", HA_ERR_WRONG_INDEX, "" }, -{ "HA_ERR_CRASHED", HA_ERR_CRASHED, "" }, -{ "HA_ERR_WRONG_IN_RECORD", HA_ERR_WRONG_IN_RECORD, "" }, -{ "HA_ERR_OUT_OF_MEM", HA_ERR_OUT_OF_MEM, "" }, -{ "HA_ERR_NOT_A_TABLE", HA_ERR_NOT_A_TABLE, "" }, -{ "HA_ERR_WRONG_COMMAND", HA_ERR_WRONG_COMMAND, "" }, -{ "HA_ERR_OLD_FILE", HA_ERR_OLD_FILE, "" }, -{ "HA_ERR_NO_ACTIVE_RECORD", HA_ERR_NO_ACTIVE_RECORD, "" }, -{ "HA_ERR_RECORD_DELETED", HA_ERR_RECORD_DELETED, "" }, -{ "HA_ERR_RECORD_FILE_FULL", HA_ERR_RECORD_FILE_FULL, "" }, -{ "HA_ERR_INDEX_FILE_FULL", HA_ERR_INDEX_FILE_FULL, "" }, -{ "HA_ERR_END_OF_FILE", HA_ERR_END_OF_FILE, "" }, -{ "HA_ERR_UNSUPPORTED", HA_ERR_UNSUPPORTED, "" }, -{ "HA_ERR_TO_BIG_ROW", HA_ERR_TO_BIG_ROW, "" }, -{ "HA_WRONG_CREATE_OPTION", HA_WRONG_CREATE_OPTION, "" }, -{ "HA_ERR_FOUND_DUPP_UNIQUE", HA_ERR_FOUND_DUPP_UNIQUE, "" }, -{ "HA_ERR_UNKNOWN_CHARSET", HA_ERR_UNKNOWN_CHARSET, "" }, -{ "HA_ERR_WRONG_MRG_TABLE_DEF", HA_ERR_WRONG_MRG_TABLE_DEF, "" }, -{ "HA_ERR_CRASHED_ON_REPAIR", HA_ERR_CRASHED_ON_REPAIR, "" }, -{ "HA_ERR_CRASHED_ON_USAGE", HA_ERR_CRASHED_ON_USAGE, "" }, -{ "HA_ERR_LOCK_WAIT_TIMEOUT", HA_ERR_LOCK_WAIT_TIMEOUT, "" }, -{ "HA_ERR_LOCK_TABLE_FULL", HA_ERR_LOCK_TABLE_FULL, "" }, -{ "HA_ERR_READ_ONLY_TRANSACTION", HA_ERR_READ_ONLY_TRANSACTION, "" }, -{ "HA_ERR_LOCK_DEADLOCK", HA_ERR_LOCK_DEADLOCK, "" }, -{ "HA_ERR_CANNOT_ADD_FOREIGN", HA_ERR_CANNOT_ADD_FOREIGN, "" }, -{ "HA_ERR_NO_REFERENCED_ROW", HA_ERR_NO_REFERENCED_ROW, "" }, -{ "HA_ERR_ROW_IS_REFERENCED", HA_ERR_ROW_IS_REFERENCED, "" }, -{ "HA_ERR_NO_SAVEPOINT", HA_ERR_NO_SAVEPOINT, "" }, -{ "HA_ERR_NON_UNIQUE_BLOCK_SIZE", HA_ERR_NON_UNIQUE_BLOCK_SIZE, "" }, -{ "HA_ERR_NO_SUCH_TABLE", HA_ERR_NO_SUCH_TABLE, "" }, -{ "HA_ERR_TABLE_EXIST", HA_ERR_TABLE_EXIST, "" }, -{ "HA_ERR_NO_CONNECTION", HA_ERR_NO_CONNECTION, "" }, -{ "HA_ERR_NULL_IN_SPATIAL", HA_ERR_NULL_IN_SPATIAL, "" }, -{ "HA_ERR_TABLE_DEF_CHANGED", HA_ERR_TABLE_DEF_CHANGED, "" }, -{ "HA_ERR_NO_PARTITION_FOUND", HA_ERR_NO_PARTITION_FOUND, "" }, -{ "HA_ERR_RBR_LOGGING_FAILED", HA_ERR_RBR_LOGGING_FAILED, "" }, -{ "HA_ERR_DROP_INDEX_FK", HA_ERR_DROP_INDEX_FK, "" }, -{ "HA_ERR_FOREIGN_DUPLICATE_KEY", HA_ERR_FOREIGN_DUPLICATE_KEY, "" }, -{ "HA_ERR_TABLE_NEEDS_UPGRADE", HA_ERR_TABLE_NEEDS_UPGRADE, "" }, -{ "HA_ERR_TABLE_READONLY", HA_ERR_TABLE_READONLY, "" }, -{ "HA_ERR_AUTOINC_READ_FAILED", HA_ERR_AUTOINC_READ_FAILED, "" }, -{ "HA_ERR_AUTOINC_ERANGE", HA_ERR_AUTOINC_ERANGE, "" }, -{ "HA_ERR_GENERIC", HA_ERR_GENERIC, "" }, -{ "HA_ERR_RECORD_IS_THE_SAME", HA_ERR_RECORD_IS_THE_SAME, "" }, -{ "HA_ERR_LOGGING_IMPOSSIBLE", HA_ERR_LOGGING_IMPOSSIBLE, "" }, -{ "HA_ERR_CORRUPT_EVENT", HA_ERR_CORRUPT_EVENT, "" }, -{ "HA_ERR_NEW_FILE", HA_ERR_NEW_FILE, "" }, -{ "HA_ERR_ROWS_EVENT_APPLY", HA_ERR_ROWS_EVENT_APPLY, "" }, -{ "HA_ERR_INITIALIZATION", HA_ERR_INITIALIZATION, "" }, -{ "HA_ERR_FILE_TOO_SHORT", HA_ERR_FILE_TOO_SHORT, "" }, -{ "HA_ERR_WRONG_CRC", HA_ERR_WRONG_CRC, "" }, -{ "HA_ERR_TOO_MANY_CONCURRENT_TRXS", HA_ERR_TOO_MANY_CONCURRENT_TRXS, "" }, -{ "HA_ERR_INDEX_COL_TOO_LONG", HA_ERR_INDEX_COL_TOO_LONG, "" }, -{ "HA_ERR_INDEX_CORRUPT", HA_ERR_INDEX_CORRUPT, "" }, -{ "HA_ERR_UNDO_REC_TOO_BIG", HA_ERR_UNDO_REC_TOO_BIG, "" }, -{ "HA_ERR_TABLE_IN_FK_CHECK", HA_ERR_TABLE_IN_FK_CHECK, "" }, -{ "HA_ERR_ROW_NOT_VISIBLE", HA_ERR_ROW_NOT_VISIBLE, "" }, -{ "HA_ERR_ABORTED_BY_USER", HA_ERR_ABORTED_BY_USER, "" }, -{ "HA_ERR_DISK_FULL", HA_ERR_DISK_FULL, "" }, -{ "HA_ERR_INCOMPATIBLE_DEFINITION", HA_ERR_INCOMPATIBLE_DEFINITION, "" }, diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/handler_state.h b/VCMP-LUA/modules/mariadb/include/mysql/server/handler_state.h deleted file mode 100644 index 65604a6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/handler_state.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - Map handler error message to sql states. Note that this list MUST be in - increasing order! - See sql_state.c for usage -*/ - -{ HA_ERR_KEY_NOT_FOUND, "02000", "" }, -{ HA_ERR_FOUND_DUPP_KEY, "23000", "" }, -{ HA_ERR_WRONG_COMMAND, "0A000", "" }, -{ HA_ERR_UNSUPPORTED, "0A000", "" }, -{ HA_WRONG_CREATE_OPTION, "0A000", "" }, -{ HA_ERR_FOUND_DUPP_UNIQUE, "23000", "" }, -{ HA_ERR_UNKNOWN_CHARSET, "0A000", "" }, -{ HA_ERR_READ_ONLY_TRANSACTION, "25000", "" }, -{ HA_ERR_LOCK_DEADLOCK, "40001", "" }, -{ HA_ERR_NO_REFERENCED_ROW, "23000", "" }, -{ HA_ERR_ROW_IS_REFERENCED, "23000", "" }, -{ HA_ERR_TABLE_EXIST, "42S01", "" }, -{ HA_ERR_FOREIGN_DUPLICATE_KEY, "23000", "" }, -{ HA_ERR_TABLE_READONLY, "25000", "" }, -{ HA_ERR_AUTOINC_ERANGE, "22003", "" }, diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/json_lib.h b/VCMP-LUA/modules/mariadb/include/mysql/server/json_lib.h deleted file mode 100644 index b6add6d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/json_lib.h +++ /dev/null @@ -1,437 +0,0 @@ -#ifndef JSON_LIB_INCLUDED -#define JSON_LIB_INCLUDED - -#ifdef __cplusplus -extern "C" { -#endif - -#define JSON_DEPTH_LIMIT 32 - -/* - When error happens, the c_next of the JSON engine contains the - character that caused the error, and the c_str is the position - in string where the error occurs. -*/ -enum json_errors { - JE_BAD_CHR= -1, /* Invalid character, charset handler cannot read it. */ - - JE_NOT_JSON_CHR= -2, /* Character met not used in JSON. */ - /* ASCII 00-08 for instance. */ - - JE_EOS= -3, /* Unexpected end of string. */ - - JE_SYN= -4, /* The next character breaks the JSON syntax. */ - - JE_STRING_CONST= -5, /* Character disallowed in string constant. */ - - JE_ESCAPING= -6, /* Error in the escaping. */ - - JE_DEPTH= -7, /* The limit on the JSON depth was overrun. */ -}; - - -typedef struct st_json_string_t -{ - const uchar *c_str; /* Current position in JSON string */ - const uchar *str_end; /* The end on the string. */ - my_wc_t c_next; /* UNICODE of the last read character */ - int error; /* error code. */ - - CHARSET_INFO *cs; /* Character set of the JSON string. */ - - my_charset_conv_mb_wc wc; /* UNICODE conversion function. */ - /* It's taken out of the cs just to speed calls. */ -} json_string_t; - - -void json_string_set_cs(json_string_t *s, CHARSET_INFO *i_cs); -void json_string_set_str(json_string_t *s, - const uchar *str, const uchar *end); -#define json_next_char(j) \ - (j)->wc((j)->cs, &(j)->c_next, (j)->c_str, (j)->str_end) -#define json_eos(j) ((j)->c_str >= (j)->str_end) -/* - read_string_const_chr() reads the next character of the string constant - and saves it to the js->c_next. - It takes into account possible escapings, so if for instance - the string is '\b', the read_string_const_chr() sets 8. -*/ -int json_read_string_const_chr(json_string_t *js); - - -/* - Various JSON-related operations expect JSON path as a parameter. - The path is a string like this "$.keyA[2].*" - The path itself is a number of steps specifying either a key or a position - in an array. Some of them can be wildcards. - So the representation of the JSON path is the json_path_t class - containing an array of json_path_step_t objects. -*/ - - -/* Path step types - actually bitmasks to let '&' or '|' operations. */ -enum json_path_step_types -{ - JSON_PATH_KEY_NULL=0, - JSON_PATH_KEY=1, /* Must be equal to JSON_VALUE_OBJECT. */ - JSON_PATH_ARRAY=2, /* Must be equal to JSON_VALUE_ARRAY. */ - JSON_PATH_KEY_OR_ARRAY=3, - JSON_PATH_WILD=4, /* Step like .* or [*] */ - JSON_PATH_DOUBLE_WILD=8, /* Step like **.k or **[1] */ - JSON_PATH_KEY_WILD= 1+4, - JSON_PATH_KEY_DOUBLEWILD= 1+8, - JSON_PATH_ARRAY_WILD= 2+4, - JSON_PATH_ARRAY_DOUBLEWILD= 2+8 -}; - - -typedef struct st_json_path_step_t -{ - enum json_path_step_types type; /* The type of the step - */ - /* see json_path_step_types */ - const uchar *key; /* Pointer to the beginning of the key. */ - const uchar *key_end; /* Pointer to the end of the key. */ - uint n_item; /* Item number in an array. No meaning for the key step. */ -} json_path_step_t; - - -typedef struct st_json_path_t -{ - json_string_t s; /* The string to be parsed. */ - json_path_step_t steps[JSON_DEPTH_LIMIT]; /* Steps of the path. */ - json_path_step_t *last_step; /* Points to the last step. */ - - int mode_strict; /* TRUE if the path specified as 'strict' */ - enum json_path_step_types types_used; /* The '|' of all step's 'type'-s */ -} json_path_t; - - -int json_path_setup(json_path_t *p, - CHARSET_INFO *i_cs, const uchar *str, const uchar *end); - - -/* - The set of functions and structures below provides interface - to the JSON text parser. - Running the parser normally goes like this: - - json_engine_t j_eng; // structure keeps parser's data - json_scan_start(j_eng) // begin the parsing - - do - { - // The parser has read next piece of JSON - // and set fields of j_eng structure accordingly. - // So let's see what we have: - switch (j_eng.state) - { - case JST_KEY: - // Handle key name. See the json_read_keyname_chr() - // Probably compare it with the keyname we're looking for - case JST_VALUE: - // Handle value. It is either value of the key or an array item. - // see the json_read_value() - case JST_OBJ_START: - // parser found an object (the '{' in JSON) - case JST_OBJ_END: - // parser found the end of the object (the '}' in JSON) - case JST_ARRAY_START: - // parser found an array (the '[' in JSON) - case JST_ARRAY_END: - // parser found the end of the array (the ']' in JSON) - - }; - } while (json_scan_next() == 0); // parse next structure - - - if (j_eng.s.error) // we need to check why the loop ended. - // Did we get to the end of JSON, or came upon error. - { - signal_error_in_JSON() - } - - - Parts of JSON can be quickly skipped. If we are not interested - in a particular key, we can just skip it with json_skip_key() call. - Similarly json_skip_level() goes right to the end of an object - or an array. -*/ - - -/* These are JSON parser states that user can expect and handle. */ -enum json_states { - JST_VALUE, /* value found */ - JST_KEY, /* key found */ - JST_OBJ_START, /* object */ - JST_OBJ_END, /* object ended */ - JST_ARRAY_START, /* array */ - JST_ARRAY_END, /* array ended */ - NR_JSON_USER_STATES -}; - - -enum json_value_types -{ - JSON_VALUE_OBJECT=1, - JSON_VALUE_ARRAY=2, - JSON_VALUE_STRING=3, - JSON_VALUE_NUMBER=4, - JSON_VALUE_TRUE=5, - JSON_VALUE_FALSE=6, - JSON_VALUE_NULL=7 -}; - - -enum json_num_flags -{ - JSON_NUM_NEG=1, /* Number is negative. */ - JSON_NUM_FRAC_PART=2, /* The fractional part is not empty. */ - JSON_NUM_EXP=4, /* The number has the 'e' part. */ -}; - - -typedef struct st_json_engine_t -{ - json_string_t s; /* String to parse. */ - int sav_c_len; /* Length of the current character. - Can be more than 1 for multibyte charsets */ - - int state; /* The state of the parser. One of 'enum json_states'. - It tells us what construction of JSON we've just read. */ - - /* These values are only set after the json_read_value() call. */ - enum json_value_types value_type; /* type of the value.*/ - const uchar *value; /* Points to the value. */ - const uchar *value_begin;/* Points to where the value starts in the JSON. */ - int value_escaped; /* Flag telling if the string value has escaping.*/ - uint num_flags; /* the details of the JSON_VALUE_NUMBER, is it negative, - or if it has the fractional part. - See the enum json_num_flags. */ - - /* - In most cases the 'value' and 'value_begin' are equal. - They only differ if the value is a string constants. Then 'value_begin' - points to the starting quotation mark, while the 'value' - to - the first character of the string. - */ - - const uchar *value_end; /* Points to the next character after the value. */ - int value_len; /* The length of the value. Does not count quotations for */ - /* string constants. */ - - int stack[JSON_DEPTH_LIMIT]; /* Keeps the stack of nested JSON structures. */ - int stack_p; /* The 'stack' pointer. */ -} json_engine_t; - - -int json_scan_start(json_engine_t *je, - CHARSET_INFO *i_cs, const uchar *str, const uchar *end); -int json_scan_next(json_engine_t *j); - - -/* - json_read_keyname_chr() function assists parsing the name of an JSON key. - It only can be called when the json_engine is in JST_KEY. - The json_read_keyname_chr() reads one character of the name of the key, - and puts it in j_eng.s.next_c. - Typical usage is like this: - - if (j_eng.state == JST_KEY) - { - while (json_read_keyname_chr(&j) == 0) - { - //handle next character i.e. match it against the pattern - } - } -*/ - -int json_read_keyname_chr(json_engine_t *j); - - -/* - Check if the name of the current JSON key matches - the step of the path. -*/ -int json_key_matches(json_engine_t *je, json_string_t *k); - - -/* - json_read_value() function parses the JSON value syntax, - so that we can handle the value of a key or an array item. - It only returns meaningful result when the engine is in - the JST_VALUE state. - - Typical usage is like this: - - if (j_eng.state == JST_VALUE) - { - json_read_value(&j_eng); - switch(j_eng.value_type) - { - case JSON_VALUE_STRING: - // get the string - str= j_eng.value; - str_length= j_eng.value_len; - case JSON_VALUE_NUMBER: - // get the number - ... etc - } -*/ -int json_read_value(json_engine_t *j); - - -/* - json_skip_key() makes parser skip the content of the current - JSON key quickly. - It can be called only when the json_engine state is JST_KEY. - Typical usage is: - - if (j_eng.state == JST_KEY) - { - if (key_does_not_match(j_eng)) - json_skip_key(j_eng); - } -*/ - -int json_skip_key(json_engine_t *j); - - -typedef const int *json_level_t; - -/* - json_skip_to_level() makes parser quickly get out of nested - loops and arrays. It is used when we're not interested in what is - there in the rest of these structures. - The 'level' should be remembered in advance. - json_level_t level= json_get_level(j); - .... // getting into the nested JSON structures - json_skip_to_level(j, level); -*/ -#define json_get_level(j) (j->stack_p) - -int json_skip_to_level(json_engine_t *j, int level); - -/* - json_skip_level() works as above with just current structure. - So it gets to the end of the current JSON array or object. -*/ -#define json_skip_level(json_engine) \ - json_skip_to_level((json_engine), (json_engine)->stack_p) - - -/* - works as json_skip_level() but also counts items on the current - level skipped. -*/ -int json_skip_level_and_count(json_engine_t *j, int *n_items_skipped); - -#define json_skip_array_item json_skip_key - -/* - Checks if the current value is of scalar type - - not an OBJECT nor ARRAY. -*/ -#define json_value_scalar(je) ((je)->value_type > JSON_VALUE_ARRAY) - - -/* - Look for the JSON PATH in the json string. - Function can be called several times with same JSON/PATH to - find multiple matches. - On the first call, the json_engine_t parameter should be - initialized with the JSON string, and the json_path_t with the JSON path - appropriately. The 'p_cur_step' should point at the first - step of the path. - The 'array_counters' is the array of JSON_DEPTH_LIMIT size. - It stores the array counters of the parsed JSON. - If function returns 0, it means it found the match. The position of - the match is je->s.c_str. Then we can call the json_find_path() - with same engine/path/p_cur_step to get the next match. - Non-zero return means no matches found. - Check je->s.error to see if there was an error in JSON. -*/ -int json_find_path(json_engine_t *je, - json_path_t *p, json_path_step_t **p_cur_step, - uint *array_counters); - - -typedef struct st_json_find_paths_t -{ - uint n_paths; - json_path_t *paths; - uint cur_depth; - uint *path_depths; - uint array_counters[JSON_DEPTH_LIMIT]; -} json_find_paths_t; - - -int json_find_paths_first(json_engine_t *je, json_find_paths_t *state, - uint n_paths, json_path_t *paths, uint *path_depths); -int json_find_paths_next(json_engine_t *je, json_find_paths_t *state); - - -/* - Converst JSON string constant into ordinary string constant - which can involve unpacking json escapes and changing character set. - Returns negative integer in the case of an error, - the length of the result otherwise. -*/ -int json_unescape(CHARSET_INFO *json_cs, - const uchar *json_str, const uchar *json_end, - CHARSET_INFO *res_cs, - uchar *res, uchar *res_end); - -/* - Converst ordinary string constant into JSON string constant. - which can involve appropriate escaping and changing character set. - Returns negative integer in the case of an error, - the length of the result otherwise. -*/ -int json_escape(CHARSET_INFO *str_cs, const uchar *str, const uchar *str_end, - CHARSET_INFO *json_cs, uchar *json, uchar *json_end); - - -/* - Appends the ASCII string to the json with the charset conversion. -*/ -int json_append_ascii(CHARSET_INFO *json_cs, - uchar *json, uchar *json_end, - const uchar *ascii, const uchar *ascii_end); - - -/* - Scan the JSON and return paths met one-by-one. - json_get_path_start(&p) - while (json_get_path_next(&p)) - { - handle_the_next_path(); - } -*/ - -int json_get_path_start(json_engine_t *je, CHARSET_INFO *i_cs, - const uchar *str, const uchar *end, - json_path_t *p); - - -int json_get_path_next(json_engine_t *je, json_path_t *p); - - -int json_path_parts_compare( - const json_path_step_t *a, const json_path_step_t *a_end, - const json_path_step_t *b, const json_path_step_t *b_end, - enum json_value_types vt); -int json_path_compare(const json_path_t *a, const json_path_t *b, - enum json_value_types vt); - -int json_valid(const char *js, size_t js_len, CHARSET_INFO *cs); - -int json_locate_key(const char *js, const char *js_end, - const char *kname, - const char **key_start, const char **key_end, - int *comma_pos); - -#ifdef __cplusplus -} -#endif - -#endif /* JSON_LIB_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/keycache.h b/VCMP-LUA/modules/mariadb/include/mysql/server/keycache.h deleted file mode 100644 index 14fd9c8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/keycache.h +++ /dev/null @@ -1,212 +0,0 @@ -/* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Key cache variable structures */ - -#ifndef _keycache_h -#define _keycache_h - -#include "my_sys.h" /* flush_type */ - -C_MODE_START - -/* - Currently the default key cache is created as non-partitioned at - the start of the server unless the server is started with the parameter - --key-cache-partitions that is greater than 0 -*/ - -#define DEFAULT_KEY_CACHE_PARTITIONS 0 - -/* - MAX_KEY_CACHE_PARTITIONS cannot be greater than - sizeof(MYISAM_SHARE::dirty_part_map) - Currently sizeof(MYISAM_SHARE::dirty_part_map)=sizeof(ulonglong) -*/ - -#define MAX_KEY_CACHE_PARTITIONS 64 - -/* The structure to get statistical data about a key cache */ - -typedef struct st_key_cache_statistics -{ - ulonglong mem_size; /* memory for cache buffers/auxiliary structures */ - ulonglong block_size; /* size of the each buffers in the key cache */ - ulonglong blocks_used; /* maximum number of used blocks/buffers */ - ulonglong blocks_unused; /* number of currently unused blocks */ - ulonglong blocks_changed; /* number of currently dirty blocks */ - ulonglong blocks_warm; /* number of blocks in warm sub-chain */ - ulonglong read_requests; /* number of read requests (read hits) */ - ulonglong reads; /* number of actual reads from files into buffers */ - ulonglong write_requests; /* number of write requests (write hits) */ - ulonglong writes; /* number of actual writes from buffers into files */ -} KEY_CACHE_STATISTICS; - -#define NUM_LONG_KEY_CACHE_STAT_VARIABLES 3 - -/* The type of a key cache object */ -typedef enum key_cache_type -{ - SIMPLE_KEY_CACHE, - PARTITIONED_KEY_CACHE -} KEY_CACHE_TYPE; - - -typedef - int (*INIT_KEY_CACHE) - (void *, uint key_cache_block_size, - size_t use_mem, uint division_limit, uint age_threshold, - uint changed_blocks_hash_size); -typedef - int (*RESIZE_KEY_CACHE) - (void *, uint key_cache_block_size, - size_t use_mem, uint division_limit, uint age_threshold, - uint changed_blocks_hash_size); -typedef - void (*CHANGE_KEY_CACHE_PARAM) - (void *keycache_cb, - uint division_limit, uint age_threshold); -typedef - uchar* (*KEY_CACHE_READ) - (void *keycache_cb, - File file, my_off_t filepos, int level, - uchar *buff, uint length, - uint block_length, int return_buffer); -typedef - int (*KEY_CACHE_INSERT) - (void *keycache_cb, - File file, my_off_t filepos, int level, - uchar *buff, uint length); -typedef - int (*KEY_CACHE_WRITE) - (void *keycache_cb, - File file, void *file_extra, - my_off_t filepos, int level, - uchar *buff, uint length, - uint block_length, int force_write); -typedef - int (*FLUSH_KEY_BLOCKS) - (void *keycache_cb, - int file, void *file_extra, - enum flush_type type); -typedef - int (*RESET_KEY_CACHE_COUNTERS) - (const char *name, void *keycache_cb); -typedef - void (*END_KEY_CACHE) - (void *keycache_cb, my_bool cleanup); -typedef - void (*GET_KEY_CACHE_STATISTICS) - (void *keycache_cb, uint partition_no, - KEY_CACHE_STATISTICS *key_cache_stats); - -/* - An object of the type KEY_CACHE_FUNCS contains pointers to all functions - from the key cache interface. - Currently a key cache can be of two types: simple and partitioned. - For each of them its own static structure of the type KEY_CACHE_FUNCS is - defined . The structures contain the pointers to the implementations of - the interface functions used by simple key caches and partitioned key - caches respectively. Pointers to these structures are assigned to key cache - objects at the time of their creation. -*/ - -typedef struct st_key_cache_funcs -{ - INIT_KEY_CACHE init; - RESIZE_KEY_CACHE resize; - CHANGE_KEY_CACHE_PARAM change_param; - KEY_CACHE_READ read; - KEY_CACHE_INSERT insert; - KEY_CACHE_WRITE write; - FLUSH_KEY_BLOCKS flush; - RESET_KEY_CACHE_COUNTERS reset_counters; - END_KEY_CACHE end; - GET_KEY_CACHE_STATISTICS get_stats; -} KEY_CACHE_FUNCS; - - -typedef struct st_key_cache -{ - KEY_CACHE_TYPE key_cache_type; /* type of the key cache used for debugging */ - void *keycache_cb; /* control block of the used key cache */ - KEY_CACHE_FUNCS *interface_funcs; /* interface functions of the key cache */ - ulonglong param_buff_size; /* size the memory allocated for the cache */ - ulonglong param_block_size; /* size of the blocks in the key cache */ - ulonglong param_division_limit;/* min. percentage of warm blocks */ - ulonglong param_age_threshold; /* determines when hot block is downgraded */ - ulonglong param_partitions; /* number of the key cache partitions */ - ulonglong changed_blocks_hash_size; /* number of hash buckets for changed files */ - my_bool key_cache_inited; /* <=> key cache has been created */ - my_bool can_be_used; /* usage of cache for read/write is allowed */ - my_bool in_init; /* set to 1 in MySQL during init/resize */ - uint partitions; /* actual number of partitions */ - size_t key_cache_mem_size; /* specified size of the cache memory */ - pthread_mutex_t op_lock; /* to serialize operations like 'resize' */ -} KEY_CACHE; - - -/* The default key cache */ -extern KEY_CACHE dflt_key_cache_var, *dflt_key_cache; - -extern int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size, - size_t use_mem, uint division_limit, - uint age_threshold, uint changed_blocks_hash_size, - uint partitions); -extern int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size, - size_t use_mem, uint division_limit, - uint age_threshold, uint changed_blocks_hash_size); -extern void change_key_cache_param(KEY_CACHE *keycache, uint division_limit, - uint age_threshold); -extern uchar *key_cache_read(KEY_CACHE *keycache, - File file, my_off_t filepos, int level, - uchar *buff, uint length, - uint block_length,int return_buffer); -extern int key_cache_insert(KEY_CACHE *keycache, - File file, my_off_t filepos, int level, - uchar *buff, uint length); -extern int key_cache_write(KEY_CACHE *keycache, - File file, void *file_extra, - my_off_t filepos, int level, - uchar *buff, uint length, - uint block_length, int force_write); -extern int flush_key_blocks(KEY_CACHE *keycache, - int file, void *file_extra, - enum flush_type type); -extern void end_key_cache(KEY_CACHE *keycache, my_bool cleanup); -extern void get_key_cache_statistics(KEY_CACHE *keycache, - uint partition_no, - KEY_CACHE_STATISTICS *key_cache_stats); - -/* Functions to handle multiple key caches */ -extern my_bool multi_keycache_init(void); -extern void multi_keycache_free(void); -extern KEY_CACHE *multi_key_cache_search(uchar *key, uint length, - KEY_CACHE *def); -extern my_bool multi_key_cache_set(const uchar *key, uint length, - KEY_CACHE *key_cache); -extern void multi_key_cache_change(KEY_CACHE *old_data, - KEY_CACHE *new_data); -extern int reset_key_cache_counters(const char *name, - KEY_CACHE *key_cache, void *); -extern int repartition_key_cache(KEY_CACHE *keycache, - uint key_cache_block_size, - size_t use_mem, - uint division_limit, - uint age_threshold, - uint changed_blocks_hash_size, - uint partitions); -C_MODE_END -#endif /* _keycache_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/little_endian.h b/VCMP-LUA/modules/mariadb/include/mysql/server/little_endian.h deleted file mode 100644 index dcddbdd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/little_endian.h +++ /dev/null @@ -1,75 +0,0 @@ -/* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Data in little-endian format. -*/ - -#ifndef MY_BYTE_ORDER_ARCH_OPTIMIZED -#define float4get(V,M) memcpy(&V, (M), sizeof(float)) -#define float4store(V,M) memcpy(V, (&M), sizeof(float)) -#define float8get(V,M) doubleget((V),(M)) -#define float8store(V,M) doublestore((V),(M)) - -/* Bi-endian hardware.... */ -#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) -#define doublestore(T,V) do { *(((char*)T)+0)=(char) ((uchar *) &V)[4];\ - *(((char*)T)+1)=(char) ((uchar *) &V)[5];\ - *(((char*)T)+2)=(char) ((uchar *) &V)[6];\ - *(((char*)T)+3)=(char) ((uchar *) &V)[7];\ - *(((char*)T)+4)=(char) ((uchar *) &V)[0];\ - *(((char*)T)+5)=(char) ((uchar *) &V)[1];\ - *(((char*)T)+6)=(char) ((uchar *) &V)[2];\ - *(((char*)T)+7)=(char) ((uchar *) &V)[3]; }\ - while(0) -#define doubleget(V,M) do { double def_temp;\ - ((uchar*) &def_temp)[0]=(M)[4];\ - ((uchar*) &def_temp)[1]=(M)[5];\ - ((uchar*) &def_temp)[2]=(M)[6];\ - ((uchar*) &def_temp)[3]=(M)[7];\ - ((uchar*) &def_temp)[4]=(M)[0];\ - ((uchar*) &def_temp)[5]=(M)[1];\ - ((uchar*) &def_temp)[6]=(M)[2];\ - ((uchar*) &def_temp)[7]=(M)[3];\ - (V) = def_temp; } while(0) -#else /* Bi-endian hardware.... */ - -/* Cast away type qualifiers (necessary as macro takes argument by value). */ -#define doublestore(T,V) memcpy((T), (void*) &V, sizeof(double)) -#define doubleget(V,M) memcpy(&V, (M), sizeof(double)) - -#endif /* Bi-endian hardware.... */ - -#endif /* !MY_BYTE_ORDER_ARCH_OPTIMIZED */ - -#define ushortget(V,M) do { uchar *pM= (uchar*)(M);V = uint2korr(pM);} while(0) -#define shortget(V,M) do { uchar *pM= (uchar*)(M);V = sint2korr(pM);} while(0) -#define longget(V,M) do { uchar *pM= (uchar*)(M);V = sint4korr(pM);} while(0) -#define ulongget(V,M) do { uchar *pM= (uchar*)(M);V = uint4korr(pM);} while(0) -#define shortstore(T,V) int2store(T,V) -#define longstore(T,V) int4store(T,V) - -#ifndef floatstore -/* Cast away type qualifiers (necessary as macro takes argument by value). */ -#define floatstore(T,V) memcpy((T), (void*) (&V), sizeof(float)) -#define floatget(V,M) memcpy(&V, (M), sizeof(float)) -#endif -#ifndef doubleget -#define doubleget(V,M) memcpy(&V, (M), sizeof(double)) -#define doublestore(T,V) memcpy((T), (void *) &V, sizeof(double)) -#endif /* doubleget */ - -#define longlongget(V,M) memcpy(&V, (M), sizeof(ulonglong)) -#define longlongstore(T,V) memcpy((T), &V, sizeof(ulonglong)) diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/m_ctype.h b/VCMP-LUA/modules/mariadb/include/mysql/server/m_ctype.h deleted file mode 100644 index 5fa8f28..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/m_ctype.h +++ /dev/null @@ -1,1602 +0,0 @@ -/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - A better inplementation of the UNIX ctype(3) library. -*/ - -#ifndef _m_ctype_h -#define _m_ctype_h - -#include - -enum loglevel { - ERROR_LEVEL= 0, - WARNING_LEVEL= 1, - INFORMATION_LEVEL= 2 -}; - -#ifdef __cplusplus -extern "C" { -#endif - -#define MY_CS_NAME_SIZE 32 -#define MY_CS_CTYPE_TABLE_SIZE 257 -#define MY_CS_TO_LOWER_TABLE_SIZE 256 -#define MY_CS_TO_UPPER_TABLE_SIZE 256 -#define MY_CS_SORT_ORDER_TABLE_SIZE 256 -#define MY_CS_TO_UNI_TABLE_SIZE 256 - -#define CHARSET_DIR "charsets/" - -#define my_wc_t ulong - -#define MY_CS_REPLACEMENT_CHARACTER 0xFFFD - -/** - Maximum character length of a string produced by wc_to_printable(). - Note, wc_to_printable() is currently limited to BMP. - One non-printable or non-convertable character can produce a string - with at most 5 characters: \hhhh. - If we ever modify wc_to_printable() to support supplementary characters, - e.g. \+hhhhhh, this constant should be changed to 8. - Note, maximum octet length of a wc_to_printable() result can be calculated - as: (MY_CS_PRINTABLE_CHAR_LENGTH*cs->mbminlen). -*/ -#define MY_CS_PRINTABLE_CHAR_LENGTH 5 - - -/* - On i386 we store Unicode->CS conversion tables for - some character sets using Big-endian order, - to copy two bytes at once. - This gives some performance improvement. -*/ -#ifdef __i386__ -#define MB2(x) (((x) >> 8) + (((x) & 0xFF) << 8)) -#define MY_PUT_MB2(s, code) { *((uint16*)(s))= (code); } -#else -#define MB2(x) (x) -#define MY_PUT_MB2(s, code) { (s)[0]= code >> 8; (s)[1]= code & 0xFF; } -#endif - -typedef const struct my_charset_handler_st MY_CHARSET_HANDLER; -typedef const struct my_collation_handler_st MY_COLLATION_HANDLER; - -typedef const struct unicase_info_st MY_UNICASE_INFO; -typedef const struct uni_ctype_st MY_UNI_CTYPE; -typedef const struct my_uni_idx_st MY_UNI_IDX; - -typedef struct unicase_info_char_st -{ - uint32 toupper; - uint32 tolower; - uint32 sort; -} MY_UNICASE_CHARACTER; - - -struct unicase_info_st -{ - my_wc_t maxchar; - MY_UNICASE_CHARACTER **page; -}; - - -extern MY_UNICASE_INFO my_unicase_default; -extern MY_UNICASE_INFO my_unicase_turkish; -extern MY_UNICASE_INFO my_unicase_mysql500; -extern MY_UNICASE_INFO my_unicase_unicode520; - -#define MY_UCA_MAX_CONTRACTION 6 -/* - The DUCET tables in ctype-uca.c are dumped with a limit of 8 weights - per character. cs->strxfrm_multiply is set to 8 for all UCA based collations. - - In language-specific UCA collations (with tailorings) we also do not allow - a single character to have more than 8 weights to stay with the same - strxfrm_multiply limit. Note, contractions are allowed to have twice longer - weight strings (up to 16 weights). As a contraction consists of at - least 2 characters, this makes sure that strxfrm_multiply ratio of 8 - is respected. -*/ -#define MY_UCA_MAX_WEIGHT_SIZE (8+1) /* Including 0 terminator */ -#define MY_UCA_CONTRACTION_MAX_WEIGHT_SIZE (2*8+1) /* Including 0 terminator */ -#define MY_UCA_WEIGHT_LEVELS 2 - -typedef struct my_contraction_t -{ - my_wc_t ch[MY_UCA_MAX_CONTRACTION]; /* Character sequence */ - uint16 weight[MY_UCA_CONTRACTION_MAX_WEIGHT_SIZE];/* Its weight string, 0-terminated */ - my_bool with_context; -} MY_CONTRACTION; - - -typedef struct my_contraction_list_t -{ - size_t nitems; /* Number of items in the list */ - MY_CONTRACTION *item; /* List of contractions */ - char *flags; /* Character flags, e.g. "is contraction head") */ -} MY_CONTRACTIONS; - -my_bool my_uca_can_be_contraction_head(const MY_CONTRACTIONS *c, my_wc_t wc); -my_bool my_uca_can_be_contraction_tail(const MY_CONTRACTIONS *c, my_wc_t wc); -uint16 *my_uca_contraction2_weight(const MY_CONTRACTIONS *c, - my_wc_t wc1, my_wc_t wc2); - - -/* Collation weights on a single level (e.g. primary, secondary, tertiarty) */ -typedef struct my_uca_level_info_st -{ - my_wc_t maxchar; - uchar *lengths; - uint16 **weights; - MY_CONTRACTIONS contractions; - uint levelno; -} MY_UCA_WEIGHT_LEVEL; - - -typedef struct uca_info_st -{ - MY_UCA_WEIGHT_LEVEL level[MY_UCA_WEIGHT_LEVELS]; - - /* Logical positions */ - my_wc_t first_non_ignorable; - my_wc_t last_non_ignorable; - my_wc_t first_primary_ignorable; - my_wc_t last_primary_ignorable; - my_wc_t first_secondary_ignorable; - my_wc_t last_secondary_ignorable; - my_wc_t first_tertiary_ignorable; - my_wc_t last_tertiary_ignorable; - my_wc_t first_trailing; - my_wc_t last_trailing; - my_wc_t first_variable; - my_wc_t last_variable; - -} MY_UCA_INFO; - - - -extern MY_UCA_INFO my_uca_v400; - - -struct uni_ctype_st -{ - uchar pctype; - const uchar *ctype; -}; - -extern MY_UNI_CTYPE my_uni_ctype[256]; - -/* wm_wc and wc_mb return codes */ -#define MY_CS_ILSEQ 0 /* Wrong by sequence: wb_wc */ -#define MY_CS_ILUNI 0 /* Cannot encode Unicode to charset: wc_mb */ -#define MY_CS_TOOSMALL -101 /* Need at least one byte: wc_mb and mb_wc */ -#define MY_CS_TOOSMALL2 -102 /* Need at least two bytes: wc_mb and mb_wc */ -#define MY_CS_TOOSMALL3 -103 /* Need at least three bytes: wc_mb and mb_wc */ -/* These following three are currently not really used */ -#define MY_CS_TOOSMALL4 -104 /* Need at least 4 bytes: wc_mb and mb_wc */ -#define MY_CS_TOOSMALL5 -105 /* Need at least 5 bytes: wc_mb and mb_wc */ -#define MY_CS_TOOSMALL6 -106 /* Need at least 6 bytes: wc_mb and mb_wc */ -/* A helper macros for "need at least n bytes" */ -#define MY_CS_TOOSMALLN(n) (-100-(n)) - -#define MY_CS_MBMAXLEN 6 /* Maximum supported mbmaxlen */ -#define MY_CS_IS_TOOSMALL(rc) ((rc) >= MY_CS_TOOSMALL6 && (rc) <= MY_CS_TOOSMALL) - -#define MY_SEQ_INTTAIL 1 -#define MY_SEQ_SPACES 2 -#define MY_SEQ_NONSPACES 3 /* Skip non-space characters, including bad bytes */ - - /* My charsets_list flags */ -#define MY_CS_COMPILED 1 /* compiled-in sets */ -#define MY_CS_CONFIG 2 /* sets that have a *.conf file */ -#define MY_CS_INDEX 4 /* sets listed in the Index file */ -#define MY_CS_LOADED 8 /* sets that are currently loaded */ -#define MY_CS_BINSORT 16 /* if binary sort order */ -#define MY_CS_PRIMARY 32 /* if primary collation */ -#define MY_CS_STRNXFRM 64 /* if strnxfrm is used for sort */ -#define MY_CS_UNICODE 128 /* is a charset is BMP Unicode */ -#define MY_CS_READY 256 /* if a charset is initialized */ -#define MY_CS_AVAILABLE 512 /* If either compiled-in or loaded*/ -#define MY_CS_CSSORT 1024 /* if case sensitive sort order */ -#define MY_CS_HIDDEN 2048 /* don't display in SHOW */ -#define MY_CS_PUREASCII 4096 /* if a charset is pure ascii */ -#define MY_CS_NONASCII 8192 /* if not ASCII-compatible */ -#define MY_CS_UNICODE_SUPPLEMENT 16384 /* Non-BMP Unicode characters */ -#define MY_CS_LOWER_SORT 32768 /* If use lower case as weight */ -#define MY_CS_STRNXFRM_BAD_NWEIGHTS 0x10000 /* strnxfrm ignores "nweights" */ -#define MY_CS_NOPAD 0x20000 /* if does not ignore trailing spaces */ -#define MY_CS_NON1TO1 0x40000 /* Has a complex mapping from characters - to weights, e.g. contractions, expansions, - ignorable characters */ -#define MY_CHARSET_UNDEFINED 0 - -/* Character repertoire flags */ -typedef enum enum_repertoire_t -{ - MY_REPERTOIRE_NONE= 0, - MY_REPERTOIRE_ASCII= 1, /* Pure ASCII U+0000..U+007F */ - MY_REPERTOIRE_EXTENDED= 2, /* Extended characters: U+0080..U+FFFF */ - MY_REPERTOIRE_UNICODE30= 3 /* ASCII | EXTENDED: U+0000..U+FFFF */ -} my_repertoire_t; - - -/* Flags for strxfrm */ -#define MY_STRXFRM_LEVEL1 0x00000001 /* for primary weights */ -#define MY_STRXFRM_LEVEL2 0x00000002 /* for secondary weights */ -#define MY_STRXFRM_LEVEL3 0x00000004 /* for tertiary weights */ -#define MY_STRXFRM_LEVEL4 0x00000008 /* fourth level weights */ -#define MY_STRXFRM_LEVEL5 0x00000010 /* fifth level weights */ -#define MY_STRXFRM_LEVEL6 0x00000020 /* sixth level weights */ -#define MY_STRXFRM_LEVEL_ALL 0x0000003F /* Bit OR for the above six */ -#define MY_STRXFRM_NLEVELS 6 /* Number of possible levels*/ - -#define MY_STRXFRM_PAD_WITH_SPACE 0x00000040 /* if pad result with spaces */ -#define MY_STRXFRM_PAD_TO_MAXLEN 0x00000080 /* if pad tail(for filesort) */ - -#define MY_STRXFRM_DESC_LEVEL1 0x00000100 /* if desc order for level1 */ -#define MY_STRXFRM_DESC_LEVEL2 0x00000200 /* if desc order for level2 */ -#define MY_STRXFRM_DESC_LEVEL3 0x00000300 /* if desc order for level3 */ -#define MY_STRXFRM_DESC_LEVEL4 0x00000800 /* if desc order for level4 */ -#define MY_STRXFRM_DESC_LEVEL5 0x00001000 /* if desc order for level5 */ -#define MY_STRXFRM_DESC_LEVEL6 0x00002000 /* if desc order for level6 */ -#define MY_STRXFRM_DESC_SHIFT 8 - -#define MY_STRXFRM_UNUSED_00004000 0x00004000 /* for future extensions */ -#define MY_STRXFRM_UNUSED_00008000 0x00008000 /* for future extensions */ - -#define MY_STRXFRM_REVERSE_LEVEL1 0x00010000 /* if reverse order for level1 */ -#define MY_STRXFRM_REVERSE_LEVEL2 0x00020000 /* if reverse order for level2 */ -#define MY_STRXFRM_REVERSE_LEVEL3 0x00040000 /* if reverse order for level3 */ -#define MY_STRXFRM_REVERSE_LEVEL4 0x00080000 /* if reverse order for level4 */ -#define MY_STRXFRM_REVERSE_LEVEL5 0x00100000 /* if reverse order for level5 */ -#define MY_STRXFRM_REVERSE_LEVEL6 0x00200000 /* if reverse order for level6 */ -#define MY_STRXFRM_REVERSE_SHIFT 16 - -/* - Collation IDs for MariaDB that should not conflict with MySQL. - We reserve 256..511, because MySQL will most likely use this range - when the range 0..255 is full. - - We use the next 256 IDs starting from 512 and divide - them into 8 chunks, 32 collations each, as follows: - - 512 + (0..31) for single byte collations (e.g. latin9) - 512 + (32..63) reserved (e.g. for utf32le, or more single byte collations) - 512 + (64..95) for utf8 - 512 + (96..127) for utf8mb4 - 512 + (128..159) for ucs2 - 512 + (160..192) for utf16 - 512 + (192..223) for utf16le - 512 + (224..255) for utf32 -*/ -#define MY_PAGE2_COLLATION_ID_8BIT 0x200 -#define MY_PAGE2_COLLATION_ID_RESERVED 0x220 -#define MY_PAGE2_COLLATION_ID_UTF8 0x240 -#define MY_PAGE2_COLLATION_ID_UTF8MB4 0x260 -#define MY_PAGE2_COLLATION_ID_UCS2 0x280 -#define MY_PAGE2_COLLATION_ID_UTF16 0x2A0 -#define MY_PAGE2_COLLATION_ID_UTF16LE 0x2C0 -#define MY_PAGE2_COLLATION_ID_UTF32 0x2E0 - -struct my_uni_idx_st -{ - uint16 from; - uint16 to; - const uchar *tab; -}; - -typedef struct -{ - uint beg; - uint end; - uint mb_len; -} my_match_t; - -enum my_lex_states -{ - MY_LEX_START, MY_LEX_CHAR, MY_LEX_IDENT, - MY_LEX_IDENT_SEP, MY_LEX_IDENT_START, - MY_LEX_REAL, MY_LEX_HEX_NUMBER, MY_LEX_BIN_NUMBER, - MY_LEX_CMP_OP, MY_LEX_LONG_CMP_OP, MY_LEX_STRING, MY_LEX_COMMENT, MY_LEX_END, - MY_LEX_OPERATOR_OR_IDENT, MY_LEX_NUMBER_IDENT, MY_LEX_INT_OR_REAL, - MY_LEX_REAL_OR_POINT, MY_LEX_BOOL, MY_LEX_EOL, MY_LEX_ESCAPE, - MY_LEX_LONG_COMMENT, MY_LEX_END_LONG_COMMENT, MY_LEX_SEMICOLON, - MY_LEX_SET_VAR, MY_LEX_USER_END, MY_LEX_HOSTNAME, MY_LEX_SKIP, - MY_LEX_USER_VARIABLE_DELIMITER, MY_LEX_SYSTEM_VAR, - MY_LEX_IDENT_OR_KEYWORD, - MY_LEX_IDENT_OR_HEX, MY_LEX_IDENT_OR_BIN, MY_LEX_IDENT_OR_NCHAR, - MY_LEX_STRING_OR_DELIMITER, MY_LEX_MINUS_OR_COMMENT, MY_LEX_PLACEHOLDER, - MY_LEX_COMMA -}; - -struct charset_info_st; - -typedef struct my_charset_loader_st -{ - char error[128]; - void *(*once_alloc)(size_t); - void *(*malloc)(size_t); - void *(*realloc)(void *, size_t); - void (*free)(void *); - void (*reporter)(enum loglevel, const char *format, ...); - int (*add_collation)(struct charset_info_st *cs); -} MY_CHARSET_LOADER; - - -extern int (*my_string_stack_guard)(int); - -/* See strings/CHARSET_INFO.txt for information about this structure */ -struct my_collation_handler_st -{ - my_bool (*init)(struct charset_info_st *, MY_CHARSET_LOADER *); - /* Collation routines */ - int (*strnncoll)(CHARSET_INFO *, - const uchar *, size_t, const uchar *, size_t, my_bool); - int (*strnncollsp)(CHARSET_INFO *, - const uchar *, size_t, const uchar *, size_t); - size_t (*strnxfrm)(CHARSET_INFO *, - uchar *dst, size_t dstlen, uint nweights, - const uchar *src, size_t srclen, uint flags); - size_t (*strnxfrmlen)(CHARSET_INFO *, size_t); - my_bool (*like_range)(CHARSET_INFO *, - const char *s, size_t s_length, - pchar w_prefix, pchar w_one, pchar w_many, - size_t res_length, - char *min_str, char *max_str, - size_t *min_len, size_t *max_len); - int (*wildcmp)(CHARSET_INFO *, - const char *str,const char *str_end, - const char *wildstr,const char *wildend, - int escape,int w_one, int w_many); - - int (*strcasecmp)(CHARSET_INFO *, const char *, const char *); - - uint (*instr)(CHARSET_INFO *, - const char *b, size_t b_length, - const char *s, size_t s_length, - my_match_t *match, uint nmatch); - - /* Hash calculation */ - void (*hash_sort)(CHARSET_INFO *cs, const uchar *key, size_t len, - ulong *nr1, ulong *nr2); - my_bool (*propagate)(CHARSET_INFO *cs, const uchar *str, size_t len); -}; - -extern MY_COLLATION_HANDLER my_collation_8bit_bin_handler; -extern MY_COLLATION_HANDLER my_collation_8bit_simple_ci_handler; -extern MY_COLLATION_HANDLER my_collation_8bit_nopad_bin_handler; -extern MY_COLLATION_HANDLER my_collation_8bit_simple_nopad_ci_handler; - -/* Some typedef to make it easy for C++ to make function pointers */ -typedef int (*my_charset_conv_mb_wc)(CHARSET_INFO *, my_wc_t *, - const uchar *, const uchar *); -typedef int (*my_charset_conv_wc_mb)(CHARSET_INFO *, my_wc_t, - uchar *, uchar *); -typedef size_t (*my_charset_conv_case)(CHARSET_INFO *, - const char *, size_t, char *, size_t); - -/* - A structure to return the statistics of a native string copying, - when no Unicode conversion is involved. - - The structure is OK to be uninitialized before calling a copying routine. - A copying routine must populate the structure as follows: - - m_source_end_pos must be set by to a non-NULL value - in the range of the input string. - - m_well_formed_error_pos must be set to NULL if the string was - well formed, or to the position of the leftmost bad byte sequence. -*/ -typedef struct -{ - const char *m_source_end_pos; /* Position where reading stopped */ - const char *m_well_formed_error_pos; /* Position where a bad byte was found*/ -} MY_STRCOPY_STATUS; - - -/* - A structure to return the statistics of a Unicode string conversion. -*/ -typedef struct -{ - const char *m_cannot_convert_error_pos; -} MY_STRCONV_STATUS; - - -/* See strings/CHARSET_INFO.txt about information on this structure */ -struct my_charset_handler_st -{ - my_bool (*init)(struct charset_info_st *, MY_CHARSET_LOADER *loader); - /* Multibyte routines */ - size_t (*numchars)(CHARSET_INFO *, const char *b, const char *e); - size_t (*charpos)(CHARSET_INFO *, const char *b, const char *e, - size_t pos); - size_t (*lengthsp)(CHARSET_INFO *, const char *ptr, size_t length); - size_t (*numcells)(CHARSET_INFO *, const char *b, const char *e); - - /* Unicode conversion */ - my_charset_conv_mb_wc mb_wc; - my_charset_conv_wc_mb wc_mb; - - /* CTYPE scanner */ - int (*ctype)(CHARSET_INFO *cs, int *ctype, - const uchar *s, const uchar *e); - - /* Functions for case and sort conversion */ - size_t (*caseup_str)(CHARSET_INFO *, char *); - size_t (*casedn_str)(CHARSET_INFO *, char *); - - my_charset_conv_case caseup; - my_charset_conv_case casedn; - - /* Charset dependent snprintf() */ - size_t (*snprintf)(CHARSET_INFO *, char *to, size_t n, - const char *fmt, - ...) ATTRIBUTE_FORMAT_FPTR(printf, 4, 5); - size_t (*long10_to_str)(CHARSET_INFO *, char *to, size_t n, - int radix, long int val); - size_t (*longlong10_to_str)(CHARSET_INFO *, char *to, size_t n, - int radix, longlong val); - - void (*fill)(CHARSET_INFO *, char *to, size_t len, int fill); - - /* String-to-number conversion routines */ - long (*strntol)(CHARSET_INFO *, const char *s, size_t l, - int base, char **e, int *err); - ulong (*strntoul)(CHARSET_INFO *, const char *s, size_t l, - int base, char **e, int *err); - longlong (*strntoll)(CHARSET_INFO *, const char *s, size_t l, - int base, char **e, int *err); - ulonglong (*strntoull)(CHARSET_INFO *, const char *s, size_t l, - int base, char **e, int *err); - double (*strntod)(CHARSET_INFO *, char *s, size_t l, char **e, - int *err); - longlong (*strtoll10)(CHARSET_INFO *cs, - const char *nptr, char **endptr, int *error); - ulonglong (*strntoull10rnd)(CHARSET_INFO *cs, - const char *str, size_t length, - int unsigned_fl, - char **endptr, int *error); - size_t (*scan)(CHARSET_INFO *, const char *b, const char *e, - int sq); - - /* String copying routines and helpers for them */ - /* - charlen() - calculate length of the left-most character in bytes. - @param cs Character set - @param str The beginning of the string - @param end The end of the string - - @return MY_CS_ILSEQ if a bad byte sequence was found. - @return MY_CS_TOOSMALLN(x) if the string ended unexpectedly. - @return a positive number in the range 1..mbmaxlen, - if a valid character was found. - */ - int (*charlen)(CHARSET_INFO *cs, const uchar *str, const uchar *end); - /* - well_formed_char_length() - returns character length of a string. - - @param cs Character set - @param str The beginning of the string - @param end The end of the string - @param nchars Not more than "nchars" left-most characters are checked. - @param status[OUT] Additional statistics is returned here. - "status" can be uninitialized before the call, - and it is fully initialized after the call. - - status->m_source_end_pos is set to the position where reading stopped. - - If a bad byte sequence is found, the function returns immediately and - status->m_well_formed_error_pos is set to the position where a bad byte - sequence was found. - - status->m_well_formed_error_pos is set to NULL if no bad bytes were found. - If status->m_well_formed_error_pos is NULL after the call, that means: - - either the function reached the end of the string, - - or all "nchars" characters were read. - The caller can check status->m_source_end_pos to detect which of these two - happened. - */ - size_t (*well_formed_char_length)(CHARSET_INFO *cs, - const char *str, const char *end, - size_t nchars, - MY_STRCOPY_STATUS *status); - - /* - copy_fix() - copy a string, replace bad bytes to '?'. - Not more than "nchars" characters are copied. - - status->m_source_end_pos is set to a position in the range - between "src" and "src + src_length", where reading stopped. - - status->m_well_formed_error_pos is set to NULL if the string - in the range "src" and "status->m_source_end_pos" was well formed, - or is set to a position between "src" and "src + src_length" where - the leftmost bad byte sequence was found. - */ - size_t (*copy_fix)(CHARSET_INFO *, - char *dst, size_t dst_length, - const char *src, size_t src_length, - size_t nchars, MY_STRCOPY_STATUS *status); - /** - Write a character to the target string, using its native code. - For Unicode character sets (utf8, ucs2, utf16, utf16le, utf32, filename) - native codes are equivalent to Unicode code points. - For 8bit character sets the native code is just the byte value. - For Asian characters sets: - - MB1 native code is just the byte value (e.g. on the ASCII range) - - MB2 native code is ((b0 << 8) + b1). - - MB3 native code is ((b0 <<16) + (b1 << 8) + b2) - Note, CHARSET_INFO::min_sort_char and CHARSET_INFO::max_sort_char - are defined in native notation and should be written using - my_ci_native_to_mb() rather than my_ci_wc_mb(). - */ - my_charset_conv_wc_mb native_to_mb; - my_charset_conv_wc_mb wc_to_printable; -}; - -extern MY_CHARSET_HANDLER my_charset_8bit_handler; -extern MY_CHARSET_HANDLER my_charset_ucs2_handler; -extern MY_CHARSET_HANDLER my_charset_utf8mb3_handler; - - -/* - We define this CHARSET_INFO_DEFINED here to prevent a repeat of the - typedef in hash.c, which will cause a compiler error. -*/ -#define CHARSET_INFO_DEFINED - - -/* See strings/CHARSET_INFO.txt about information on this structure */ -struct charset_info_st -{ - uint number; - uint primary_number; - uint binary_number; - uint state; - const char *csname; - const char *name; - const char *comment; - const char *tailoring; - const uchar *m_ctype; - const uchar *to_lower; - const uchar *to_upper; - const uchar *sort_order; - MY_UCA_INFO *uca; - const uint16 *tab_to_uni; - MY_UNI_IDX *tab_from_uni; - MY_UNICASE_INFO *caseinfo; - const uchar *state_map; - const uchar *ident_map; - uint strxfrm_multiply; - uchar caseup_multiply; - uchar casedn_multiply; - uint mbminlen; - uint mbmaxlen; - my_wc_t min_sort_char; - my_wc_t max_sort_char; /* For LIKE optimization */ - uchar pad_char; - my_bool escape_with_backslash_is_dangerous; - uchar levels_for_order; - - MY_CHARSET_HANDLER *cset; - MY_COLLATION_HANDLER *coll; - -#ifdef __cplusplus - /* Character set routines */ - bool use_mb() const - { - return mbmaxlen > 1; - } - - size_t numchars(const char *b, const char *e) const - { - return (cset->numchars)(this, b, e); - } - - size_t charpos(const char *b, const char *e, size_t pos) const - { - return (cset->charpos)(this, b, e, pos); - } - size_t charpos(const uchar *b, const uchar *e, size_t pos) const - { - return (cset->charpos)(this, (const char *) b, (const char*) e, pos); - } - - size_t lengthsp(const char *str, size_t length) const - { - return (cset->lengthsp)(this, str, length); - } - - size_t numcells(const char *b, const char *e) const - { - return (cset->numcells)(this, b, e); - } - - size_t caseup(const char *src, size_t srclen, - char *dst, size_t dstlen) const - { - return (cset->caseup)(this, src, srclen, dst, dstlen); - } - - size_t casedn(const char *src, size_t srclen, - char *dst, size_t dstlen) const - { - return (cset->casedn)(this, src, srclen, dst, dstlen); - } - - size_t long10_to_str(char *dst, size_t dstlen, - int radix, long int val) const - { - return (cset->long10_to_str)(this, dst, dstlen, radix, val); - } - - size_t (longlong10_to_str)(char *dst, size_t dstlen, - int radix, longlong val) const - { - return (cset->longlong10_to_str)(this, dst, dstlen, radix, val); - } - - int mb_wc(my_wc_t *wc, const uchar *b, const uchar *e) const - { - return (cset->mb_wc)(this, wc, b, e); - } - - int wc_mb(my_wc_t wc, uchar *s, uchar *e) const - { - return (cset->wc_mb)(this, wc, s, e); - } - - int native_to_mb(my_wc_t wc, uchar *s, uchar *e) const - { - return (cset->native_to_mb)(this, wc, s, e); - } - - int wc_to_printable(my_wc_t wc, uchar *s, uchar *e) const - { - return (cset->wc_to_printable)(this, wc, s, e); - } - - int ctype(int *to, const uchar *s, const uchar *e) const - { - return (cset->ctype)(this, to, s, e); - } - - void fill(char *to, size_t len, int ch) const - { - (cset->fill)(this, to, len, ch); - } - - long strntol(const char *str, size_t length, - int base, char **endptr, int *error) const - { - return (cset->strntol)(this, str, length, base, endptr, error); - } - - ulong strntoul(const char *str, size_t length, - int base, char **endptr, int *error) const - { - return (cset->strntoul)(this, str, length, base, endptr, error); - } - - longlong strntoll(const char *str, size_t length, - int base, char **endptr, int *error) const - { - return (cset->strntoll)(this, str, length, base, endptr, error); - } - - ulonglong strntoull(const char *str, size_t length, - int base, char **endptr, int *error) const - { - return (cset->strntoull)(this, str, length, base, endptr, error); - } - - double strntod(char *str, size_t length, - char **endptr, int *error) const - { - return (cset->strntod)(this, str, length, endptr, error); - } - - longlong strtoll10(const char *str, char **endptr, int *error) const - { - return (cset->strtoll10)(this, str, endptr, error); - } - - ulonglong strntoull10rnd(const char *str, size_t length, int unsigned_fl, - char **endptr, int *error) const - { - return (cset->strntoull10rnd)(this, str, length, unsigned_fl, endptr, error); - } - - size_t scan(const char *b, const char *e, int seq) const - { - return (cset->scan)(this, b, e, seq); - } - - int charlen(const uchar *str, const uchar *end) const - { - return (cset->charlen)(this, str, end); - } - int charlen(const char *str, const char *end) const - { - return (cset->charlen)(this, (const uchar *) str, (const uchar *) end); - } - - uint charlen_fix(const uchar *str, const uchar *end) const - { - int char_length= (cset->charlen)(this, str, end); - DBUG_ASSERT(str < end); - return char_length > 0 ? (uint) char_length : (uint) 1U; - } - uint charlen_fix(const char *str, const char *end) const - { - return charlen_fix((const uchar *) str, (const uchar *) end); - } - - size_t well_formed_char_length(const char *str, const char *end, - size_t nchars, - MY_STRCOPY_STATUS *status) const - { - return (cset->well_formed_char_length)(this, str, end, nchars, status); - } - - size_t copy_fix(char *dst, size_t dst_length, - const char *src, size_t src_length, - size_t nchars, MY_STRCOPY_STATUS *status) const - { - return (cset->copy_fix)(this, dst, dst_length, src, src_length, nchars, - status); - } - - /* Collation routines */ - int strnncoll(const uchar *a, size_t alen, - const uchar *b, size_t blen, my_bool b_is_prefix= FALSE) const - { - return (coll->strnncoll)(this, a, alen, b, blen, b_is_prefix); - } - int strnncoll(const char *a, size_t alen, - const char *b, size_t blen, my_bool b_is_prefix= FALSE) const - { - return (coll->strnncoll)(this, - (const uchar *) a, alen, - (const uchar *) b, blen, b_is_prefix); - } - - int strnncollsp(const uchar *a, size_t alen, - const uchar *b, size_t blen) const - { - return (coll->strnncollsp)(this, a, alen, b, blen); - } - int strnncollsp(const char *a, size_t alen, - const char *b, size_t blen) const - { - return (coll->strnncollsp)(this, (uchar *) a, alen, (uchar *) b, blen); - } - - size_t strnxfrm(char *dst, size_t dstlen, uint nweights, - const char *src, size_t srclen, uint flags) const - { - return (coll->strnxfrm)(this, - (uchar *) dst, dstlen, nweights, - (const uchar *) src, srclen, flags); - } - size_t strnxfrm(uchar *dst, size_t dstlen, uint nweights, - const uchar *src, size_t srclen, uint flags) const - { - return (coll->strnxfrm)(this, - dst, dstlen, nweights, - src, srclen, flags); - } - size_t strnxfrm(uchar *dst, size_t dstlen, - const uchar *src, size_t srclen) const - { - return (coll->strnxfrm)(this, - dst, dstlen, (uint) dstlen, - src, srclen, MY_STRXFRM_PAD_WITH_SPACE); - } - - size_t strnxfrmlen(size_t length) const - { - return (coll->strnxfrmlen)(this, length); - } - - my_bool like_range(const char *s, size_t s_length, - pchar w_prefix, pchar w_one, pchar w_many, - size_t res_length, - char *min_str, char *max_str, - size_t *min_len, size_t *max_len) const - { - return (coll->like_range)(this, s, s_length, - w_prefix, w_one, w_many, - res_length, min_str, max_str, - min_len, max_len); - } - - int wildcmp(const char *str,const char *str_end, - const char *wildstr,const char *wildend, - int escape,int w_one, int w_many) const - { - return (coll->wildcmp)(this, str, str_end, wildstr, wildend, escape, w_one, w_many); - } - - uint instr(const char *b, size_t b_length, - const char *s, size_t s_length, - my_match_t *match, uint nmatch) const - { - return (coll->instr)(this, b, b_length, s, s_length, match, nmatch); - } - - void hash_sort(const uchar *key, size_t len, ulong *nr1, ulong *nr2) const - { - (coll->hash_sort)(this, key, len, nr1, nr2); - } - - my_bool propagate(const uchar *str, size_t len) const - { - return (coll->propagate)(this, str, len); - } - -#endif /* __cplusplus */ -}; - - -/* Character set routines */ - -static inline my_bool -my_ci_init_charset(struct charset_info_st *ci, MY_CHARSET_LOADER *loader) -{ - if (!ci->cset->init) - return FALSE; - return (ci->cset->init)(ci, loader); -} - - -static inline my_bool -my_ci_use_mb(CHARSET_INFO *ci) -{ - return ci->mbmaxlen > 1 ? TRUE : FALSE; -} - -static inline size_t -my_ci_numchars(CHARSET_INFO *cs, const char *b, const char *e) -{ - return (cs->cset->numchars)(cs, b, e); -} - -static inline size_t -my_ci_charpos(CHARSET_INFO *cs, const char *b, const char *e, size_t pos) -{ - return (cs->cset->charpos)(cs, b, e, pos); -} - -static inline size_t -my_ci_lengthsp(CHARSET_INFO *cs, const char *str, size_t length) -{ - return (cs->cset->lengthsp)(cs, str, length); -} - -static inline size_t -my_ci_numcells(CHARSET_INFO *cs, const char *b, const char *e) -{ - return (cs->cset->numcells)(cs, b, e); -} - -static inline size_t -my_ci_caseup(CHARSET_INFO *ci, - const char *src, size_t srclen, - char *dst, size_t dstlen) -{ - return (ci->cset->caseup)(ci, src, srclen, dst, dstlen); -} - -static inline size_t -my_ci_casedn(CHARSET_INFO *ci, - const char *src, size_t srclen, - char *dst, size_t dstlen) -{ - return (ci->cset->casedn)(ci, src, srclen, dst, dstlen); -} - -static inline size_t -my_ci_long10_to_str(CHARSET_INFO *cs, char *dst, size_t dstlen, - int radix, long int val) -{ - return (cs->cset->long10_to_str)(cs, dst, dstlen, radix, val); -} - -static inline size_t -my_ci_longlong10_to_str(CHARSET_INFO *cs, char *dst, size_t dstlen, - int radix, longlong val) -{ - return (cs->cset->longlong10_to_str)(cs, dst, dstlen, radix, val); -} - -#define my_ci_mb_wc(s, pwc, b, e) ((s)->cset->mb_wc)(s, pwc, b, e) -#define my_ci_wc_mb(s, wc, b, e) ((s)->cset->wc_mb)(s, wc, b, e) -#define my_ci_native_to_mb(s, wc, b, e) ((s)->cset->native_to_mb)(s, wc, b, e) -#define my_ci_ctype(s, pctype, b, e) ((s)->cset->ctype)(s, pctype, b, e) - -static inline void -my_ci_fill(CHARSET_INFO *cs, char *to, size_t len, int ch) -{ - (cs->cset->fill)(cs, to, len, ch); -} - -static inline long -my_ci_strntol(CHARSET_INFO *cs, const char *str, size_t length, - int base, char **endptr, int *error) -{ - return (cs->cset->strntol)(cs, str, length, base, endptr, error); -} - -static inline ulong -my_ci_strntoul(CHARSET_INFO *cs, const char *str, size_t length, - int base, char **endptr, int *error) -{ - return (cs->cset->strntoul)(cs, str, length, base, endptr, error); -} - -static inline longlong -my_ci_strntoll(CHARSET_INFO *cs, const char *str, size_t length, - int base, char **endptr, int *error) -{ - return (cs->cset->strntoll)(cs, str, length, base, endptr, error); -} - -static inline ulonglong -my_ci_strntoull(CHARSET_INFO *cs, const char *str, size_t length, - int base, char **endptr, int *error) -{ - return (cs->cset->strntoull)(cs, str, length, base, endptr, error); -} - -static inline double -my_ci_strntod(CHARSET_INFO *cs, char *str, size_t length, - char **endptr, int *error) -{ - return (cs->cset->strntod)(cs, str, length, endptr, error); -} - -static inline longlong -my_ci_strtoll10(CHARSET_INFO *cs, const char *str, char **endptr, int *error) -{ - return (cs->cset->strtoll10)(cs, str, endptr, error); -} - -static inline ulonglong -my_ci_strntoull10rnd(CHARSET_INFO *cs, - const char *str, size_t length, int unsigned_fl, - char **endptr, int *error) -{ - return (cs->cset->strntoull10rnd)(cs, str, length, unsigned_fl, endptr, error); -} - - -static inline size_t -my_ci_scan(CHARSET_INFO *cs, const char *b, const char *e, int seq) -{ - return (cs->cset->scan)(cs, b, e, seq); -} - - -/** - Return length of the leftmost character in a string. - @param cs - character set - @param str - the beginning of the string - @param end - the string end (the next byte after the string) - @return <=0 on errors (EOL, wrong byte sequence) - @return 1 on a single byte character - @return >1 on a multi-byte character - - Note, inlike my_ismbchar(), 1 is returned for a single byte character. -*/ - -static inline int -my_ci_charlen(CHARSET_INFO *cs, const uchar *str, const uchar *end) -{ - return (cs->cset->charlen)(cs, str, end); -} - - -static inline size_t -my_ci_well_formed_char_length(CHARSET_INFO *cs, - const char *str, const char *end, - size_t nchars, - MY_STRCOPY_STATUS *status) -{ - return (cs->cset->well_formed_char_length)(cs, str, end, nchars, status); -} - - -static inline size_t -my_ci_copy_fix(CHARSET_INFO *cs, - char *dst, size_t dst_length, - const char *src, size_t src_length, - size_t nchars, MY_STRCOPY_STATUS *status) -{ - return (cs->cset->copy_fix)(cs, dst, dst_length, src, src_length, nchars, - status); -} - - -/* Collation routines */ - -static inline my_bool -my_ci_init_collation(struct charset_info_st *ci, MY_CHARSET_LOADER *loader) -{ - if (!ci->coll->init) - return FALSE; - return (ci->coll->init)(ci, loader); -} - - -static inline int -my_ci_strnncoll(CHARSET_INFO *ci, - const uchar *a, size_t alen, - const uchar *b, size_t blen, - my_bool b_is_prefix) -{ - return (ci->coll->strnncoll)(ci, a, alen, b, blen, b_is_prefix); -} - -static inline int -my_ci_strnncollsp(CHARSET_INFO *ci, - const uchar *a, size_t alen, - const uchar *b, size_t blen) -{ - return (ci->coll->strnncollsp)(ci, a, alen, b, blen); -} - - -static inline my_bool -my_ci_like_range(CHARSET_INFO *ci, - const char *s, size_t s_length, - pchar w_prefix, pchar w_one, pchar w_many, - size_t res_length, - char *min_str, char *max_str, - size_t *min_len, size_t *max_len) -{ - return (ci->coll->like_range)(ci, s, s_length, - w_prefix, w_one, w_many, - res_length, min_str, max_str, - min_len, max_len); -} - - -static inline uint -my_ci_instr(CHARSET_INFO *ci, - const char *b, size_t b_length, - const char *s, size_t s_length, - my_match_t *match, uint nmatch) -{ - return (ci->coll->instr)(ci, b, b_length, s, s_length, match, nmatch); -} - - -static inline void -my_ci_hash_sort(CHARSET_INFO *ci, - const uchar *key, size_t len, - ulong *nr1, ulong *nr2) -{ - (ci->coll->hash_sort)(ci, key, len, nr1, nr2); -} - - -#define ILLEGAL_CHARSET_INFO_NUMBER (~0U) - -extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_bin; -extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_latin1; -extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_latin1_nopad; -extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_filename; -extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_utf8mb3_general_ci; - -extern struct charset_info_st my_charset_big5_bin; -extern struct charset_info_st my_charset_big5_chinese_ci; -extern struct charset_info_st my_charset_big5_nopad_bin; -extern struct charset_info_st my_charset_big5_chinese_nopad_ci; -extern struct charset_info_st my_charset_cp1250_czech_ci; -extern struct charset_info_st my_charset_cp932_bin; -extern struct charset_info_st my_charset_cp932_japanese_ci; -extern struct charset_info_st my_charset_cp932_nopad_bin; -extern struct charset_info_st my_charset_cp932_japanese_nopad_ci; -extern struct charset_info_st my_charset_eucjpms_bin; -extern struct charset_info_st my_charset_eucjpms_japanese_ci; -extern struct charset_info_st my_charset_eucjpms_nopad_bin; -extern struct charset_info_st my_charset_eucjpms_japanese_nopad_ci; -extern struct charset_info_st my_charset_euckr_bin; -extern struct charset_info_st my_charset_euckr_korean_ci; -extern struct charset_info_st my_charset_euckr_nopad_bin; -extern struct charset_info_st my_charset_euckr_korean_nopad_ci; -extern struct charset_info_st my_charset_gb2312_bin; -extern struct charset_info_st my_charset_gb2312_chinese_ci; -extern struct charset_info_st my_charset_gb2312_nopad_bin; -extern struct charset_info_st my_charset_gb2312_chinese_nopad_ci; -extern struct charset_info_st my_charset_gbk_bin; -extern struct charset_info_st my_charset_gbk_chinese_ci; -extern struct charset_info_st my_charset_gbk_nopad_bin; -extern struct charset_info_st my_charset_gbk_chinese_nopad_ci; -extern struct charset_info_st my_charset_latin1_bin; -extern struct charset_info_st my_charset_latin1_nopad_bin; -extern struct charset_info_st my_charset_latin1_german2_ci; -extern struct charset_info_st my_charset_latin2_czech_ci; -extern struct charset_info_st my_charset_sjis_bin; -extern struct charset_info_st my_charset_sjis_japanese_ci; -extern struct charset_info_st my_charset_sjis_nopad_bin; -extern struct charset_info_st my_charset_sjis_japanese_nopad_ci; -extern struct charset_info_st my_charset_tis620_bin; -extern struct charset_info_st my_charset_tis620_thai_ci; -extern struct charset_info_st my_charset_tis620_nopad_bin; -extern struct charset_info_st my_charset_tis620_thai_nopad_ci; -extern struct charset_info_st my_charset_ucs2_bin; -extern struct charset_info_st my_charset_ucs2_general_ci; -extern struct charset_info_st my_charset_ucs2_nopad_bin; -extern struct charset_info_st my_charset_ucs2_general_nopad_ci; -extern struct charset_info_st my_charset_ucs2_general_mysql500_ci; -extern struct charset_info_st my_charset_ucs2_unicode_ci; -extern struct charset_info_st my_charset_ucs2_unicode_nopad_ci; -extern struct charset_info_st my_charset_ucs2_general_mysql500_ci; -extern struct charset_info_st my_charset_ujis_bin; -extern struct charset_info_st my_charset_ujis_japanese_ci; -extern struct charset_info_st my_charset_ujis_nopad_bin; -extern struct charset_info_st my_charset_ujis_japanese_nopad_ci; -extern struct charset_info_st my_charset_utf16_bin; -extern struct charset_info_st my_charset_utf16_general_ci; -extern struct charset_info_st my_charset_utf16_unicode_ci; -extern struct charset_info_st my_charset_utf16_unicode_nopad_ci; -extern struct charset_info_st my_charset_utf16le_bin; -extern struct charset_info_st my_charset_utf16le_general_ci; -extern struct charset_info_st my_charset_utf16_general_nopad_ci; -extern struct charset_info_st my_charset_utf16_nopad_bin; -extern struct charset_info_st my_charset_utf16le_nopad_bin; -extern struct charset_info_st my_charset_utf16le_general_nopad_ci; -extern struct charset_info_st my_charset_utf32_bin; -extern struct charset_info_st my_charset_utf32_general_ci; -extern struct charset_info_st my_charset_utf32_unicode_ci; -extern struct charset_info_st my_charset_utf32_unicode_nopad_ci; -extern struct charset_info_st my_charset_utf32_nopad_bin; -extern struct charset_info_st my_charset_utf32_general_nopad_ci; -extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_utf8mb3_bin; -extern struct charset_info_st my_charset_utf8mb3_nopad_bin; -extern struct charset_info_st my_charset_utf8mb3_general_nopad_ci; -extern struct charset_info_st my_charset_utf8mb3_general_mysql500_ci; -extern struct charset_info_st my_charset_utf8mb3_unicode_ci; -extern struct charset_info_st my_charset_utf8mb3_unicode_nopad_ci; -extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_utf8mb4_bin; -extern struct charset_info_st my_charset_utf8mb4_general_ci; -extern struct charset_info_st my_charset_utf8mb4_nopad_bin; -extern struct charset_info_st my_charset_utf8mb4_general_nopad_ci; -extern struct charset_info_st my_charset_utf8mb4_unicode_ci; -extern struct charset_info_st my_charset_utf8mb4_unicode_nopad_ci; - -#define MY_UTF8MB3 "utf8" -#define MY_UTF8MB4 "utf8mb4" - -my_bool my_cs_have_contractions(CHARSET_INFO *cs); -my_bool my_cs_can_be_contraction_head(CHARSET_INFO *cs, my_wc_t wc); -my_bool my_cs_can_be_contraction_tail(CHARSET_INFO *cs, my_wc_t wc); -const uint16 *my_cs_contraction2_weight(CHARSET_INFO *cs, my_wc_t wc1, - my_wc_t wc2); - -/* declarations for simple charsets */ -extern size_t my_strnxfrm_simple(CHARSET_INFO *, - uchar *dst, size_t dstlen, uint nweights, - const uchar *src, size_t srclen, uint flags); -size_t my_strnxfrmlen_simple(CHARSET_INFO *, size_t); -extern int my_strnncoll_simple(CHARSET_INFO *, const uchar *, size_t, - const uchar *, size_t, my_bool); - -extern int my_strnncollsp_simple(CHARSET_INFO *, const uchar *, size_t, - const uchar *, size_t); - -extern void my_hash_sort_simple(CHARSET_INFO *cs, - const uchar *key, size_t len, - ulong *nr1, ulong *nr2); - -extern void my_hash_sort_simple_nopad(CHARSET_INFO *cs, - const uchar *key, size_t len, - ulong *nr1, ulong *nr2); - -extern void my_hash_sort_bin(CHARSET_INFO *cs, - const uchar *key, size_t len, ulong *nr1, - ulong *nr2); - -/** - Compare a string to an array of spaces, for PAD SPACE comparison. - The function iterates through the string and compares every byte to 0x20. - @param - the string - @param - its length - @return <0 - if a byte less than 0x20 was found in the string. - @return 0 - if all bytes in the string were 0x20, or if length was 0. - @return >0 - if a byte greater than 0x20 was found in the string. -*/ -extern int my_strnncollsp_padspace_bin(const uchar *str, size_t length); - -extern size_t my_lengthsp_8bit(CHARSET_INFO *cs, const char *ptr, size_t length); - -extern uint my_instr_simple(CHARSET_INFO *, - const char *b, size_t b_length, - const char *s, size_t s_length, - my_match_t *match, uint nmatch); - -size_t my_copy_8bit(CHARSET_INFO *, - char *dst, size_t dst_length, - const char *src, size_t src_length, - size_t nchars, MY_STRCOPY_STATUS *); -size_t my_copy_fix_mb(CHARSET_INFO *cs, - char *dst, size_t dst_length, - const char *src, size_t src_length, - size_t nchars, MY_STRCOPY_STATUS *); - -/* Functions for 8bit */ -extern size_t my_caseup_str_8bit(CHARSET_INFO *, char *); -extern size_t my_casedn_str_8bit(CHARSET_INFO *, char *); -extern size_t my_caseup_8bit(CHARSET_INFO *, - const char *src, size_t srclen, - char *dst, size_t dstlen); -extern size_t my_casedn_8bit(CHARSET_INFO *, - const char *src, size_t srclen, - char *dst, size_t dstlen); - -extern int my_strcasecmp_8bit(CHARSET_INFO * cs, const char *, const char *); - -int my_mb_wc_8bit(CHARSET_INFO *cs,my_wc_t *wc, const uchar *s,const uchar *e); -int my_wc_mb_8bit(CHARSET_INFO *cs,my_wc_t wc, uchar *s, uchar *e); -int my_wc_mb_bin(CHARSET_INFO *cs,my_wc_t wc, uchar *s, uchar *e); - -int my_mb_ctype_8bit(CHARSET_INFO *,int *, const uchar *,const uchar *); -int my_mb_ctype_mb(CHARSET_INFO *,int *, const uchar *,const uchar *); - -size_t my_scan_8bit(CHARSET_INFO *cs, const char *b, const char *e, int sq); - -size_t my_snprintf_8bit(CHARSET_INFO *, char *to, size_t n, - const char *fmt, ...) - ATTRIBUTE_FORMAT(printf, 4, 5); - -long my_strntol_8bit(CHARSET_INFO *, const char *s, size_t l, int base, - char **e, int *err); -ulong my_strntoul_8bit(CHARSET_INFO *, const char *s, size_t l, int base, - char **e, int *err); -longlong my_strntoll_8bit(CHARSET_INFO *, const char *s, size_t l, int base, - char **e, int *err); -ulonglong my_strntoull_8bit(CHARSET_INFO *, const char *s, size_t l, int base, - char **e, int *err); -double my_strntod_8bit(CHARSET_INFO *, char *s, size_t l,char **e, - int *err); -size_t my_long10_to_str_8bit(CHARSET_INFO *, char *to, size_t l, int radix, - long int val); -size_t my_longlong10_to_str_8bit(CHARSET_INFO *, char *to, size_t l, int radix, - longlong val); - -longlong my_strtoll10_8bit(CHARSET_INFO *cs, - const char *nptr, char **endptr, int *error); -longlong my_strtoll10_ucs2(CHARSET_INFO *cs, - const char *nptr, char **endptr, int *error); - -ulonglong my_strntoull10rnd_8bit(CHARSET_INFO *cs, - const char *str, size_t length, int - unsigned_fl, char **endptr, int *error); -ulonglong my_strntoull10rnd_ucs2(CHARSET_INFO *cs, - const char *str, size_t length, - int unsigned_fl, char **endptr, int *error); - -void my_fill_8bit(CHARSET_INFO *cs, char* to, size_t l, int fill); - -/* For 8-bit character set */ -my_bool my_like_range_simple(CHARSET_INFO *cs, - const char *ptr, size_t ptr_length, - pbool escape, pbool w_one, pbool w_many, - size_t res_length, - char *min_str, char *max_str, - size_t *min_length, size_t *max_length); - -/* For ASCII-based multi-byte character sets with mbminlen=1 */ -my_bool my_like_range_mb(CHARSET_INFO *cs, - const char *ptr, size_t ptr_length, - pbool escape, pbool w_one, pbool w_many, - size_t res_length, - char *min_str, char *max_str, - size_t *min_length, size_t *max_length); - -/* For other character sets, with arbitrary mbminlen and mbmaxlen numbers */ -my_bool my_like_range_generic(CHARSET_INFO *cs, - const char *ptr, size_t ptr_length, - pbool escape, pbool w_one, pbool w_many, - size_t res_length, - char *min_str, char *max_str, - size_t *min_length, size_t *max_length); - -int my_wildcmp_8bit(CHARSET_INFO *, - const char *str,const char *str_end, - const char *wildstr,const char *wildend, - int escape, int w_one, int w_many); - -int my_wildcmp_bin(CHARSET_INFO *, - const char *str,const char *str_end, - const char *wildstr,const char *wildend, - int escape, int w_one, int w_many); - -size_t my_numchars_8bit(CHARSET_INFO *, const char *b, const char *e); -size_t my_numcells_8bit(CHARSET_INFO *, const char *b, const char *e); -size_t my_charpos_8bit(CHARSET_INFO *, const char *b, const char *e, size_t pos); -size_t my_well_formed_char_length_8bit(CHARSET_INFO *cs, - const char *b, const char *e, - size_t nchars, - MY_STRCOPY_STATUS *status); -int my_charlen_8bit(CHARSET_INFO *, const uchar *str, const uchar *end); - - -/* Functions for multibyte charsets */ -extern size_t my_caseup_str_mb(CHARSET_INFO *, char *); -extern size_t my_casedn_str_mb(CHARSET_INFO *, char *); -extern size_t my_caseup_mb(CHARSET_INFO *, - const char *src, size_t srclen, - char *dst, size_t dstlen); -extern size_t my_casedn_mb(CHARSET_INFO *, - const char *src, size_t srclen, - char *dst, size_t dstlen); -extern size_t my_caseup_ujis(CHARSET_INFO *, - const char *src, size_t srclen, - char *dst, size_t dstlen); -extern size_t my_casedn_ujis(CHARSET_INFO *, - const char *src, size_t srclen, - char *dst, size_t dstlen); -extern int my_strcasecmp_mb(CHARSET_INFO * cs,const char *, const char *); - -int my_wildcmp_mb(CHARSET_INFO *, - const char *str,const char *str_end, - const char *wildstr,const char *wildend, - int escape, int w_one, int w_many); -size_t my_numchars_mb(CHARSET_INFO *, const char *b, const char *e); -size_t my_numcells_mb(CHARSET_INFO *, const char *b, const char *e); -size_t my_charpos_mb(CHARSET_INFO *, const char *b, const char *e, size_t pos); -uint my_instr_mb(CHARSET_INFO *, - const char *b, size_t b_length, - const char *s, size_t s_length, - my_match_t *match, uint nmatch); - -int my_wildcmp_mb_bin(CHARSET_INFO *cs, - const char *str,const char *str_end, - const char *wildstr,const char *wildend, - int escape, int w_one, int w_many); - -int my_strcasecmp_mb_bin(CHARSET_INFO * cs __attribute__((unused)), - const char *s, const char *t); - -void my_hash_sort_mb_bin(CHARSET_INFO *cs __attribute__((unused)), - const uchar *key, size_t len,ulong *nr1, ulong *nr2); - -void my_hash_sort_mb_nopad_bin(CHARSET_INFO *cs __attribute__((unused)), - const uchar *key, size_t len, - ulong *nr1, ulong *nr2); - -size_t my_strnxfrm_mb(CHARSET_INFO *, - uchar *dst, size_t dstlen, uint nweights, - const uchar *src, size_t srclen, uint flags); - -size_t my_strnxfrm_mb_nopad(CHARSET_INFO *, - uchar *dst, size_t dstlen, uint nweights, - const uchar *src, size_t srclen, uint flags); - -size_t my_strnxfrmlen_unicode(CHARSET_INFO *, size_t); - -size_t my_strnxfrm_unicode_full_bin(CHARSET_INFO *, - uchar *dst, size_t dstlen, - uint nweights, const uchar *src, - size_t srclen, uint flags); - -size_t my_strnxfrm_unicode_full_nopad_bin(CHARSET_INFO *, - uchar *dst, size_t dstlen, - uint nweights, const uchar *src, - size_t srclen, uint flags); - -size_t my_strnxfrmlen_unicode_full_bin(CHARSET_INFO *, size_t); - -int my_wildcmp_unicode(CHARSET_INFO *cs, - const char *str, const char *str_end, - const char *wildstr, const char *wildend, - int escape, int w_one, int w_many, - MY_UNICASE_INFO *weights); - -extern my_bool my_parse_charset_xml(MY_CHARSET_LOADER *loader, - const char *buf, size_t buflen); -extern char *my_strchr(CHARSET_INFO *cs, const char *str, const char *end, - pchar c); -extern size_t my_strcspn(CHARSET_INFO *cs, const char *str, const char *end, - const char *accept); - -my_bool my_propagate_simple(CHARSET_INFO *cs, const uchar *str, size_t len); -my_bool my_propagate_complex(CHARSET_INFO *cs, const uchar *str, size_t len); - - -typedef struct -{ - size_t char_length; - my_repertoire_t repertoire; -} MY_STRING_METADATA; - -void my_string_metadata_get(MY_STRING_METADATA *metadata, - CHARSET_INFO *cs, const char *str, size_t len); -my_repertoire_t my_string_repertoire(CHARSET_INFO *cs, - const char *str, size_t len); -my_bool my_charset_is_ascii_based(CHARSET_INFO *cs); -my_repertoire_t my_charset_repertoire(CHARSET_INFO *cs); - -uint my_strxfrm_flag_normalize(uint flags, uint nlevels); -void my_strxfrm_desc_and_reverse(uchar *str, uchar *strend, - uint flags, uint level); -size_t my_strxfrm_pad_desc_and_reverse(CHARSET_INFO *cs, - uchar *str, uchar *frmend, uchar *strend, - uint nweights, uint flags, uint level); -size_t my_strxfrm_pad_desc_and_reverse_nopad(CHARSET_INFO *cs, - uchar *str, uchar *frmend, - uchar *strend, uint nweights, - uint flags, uint level); - -const MY_CONTRACTIONS *my_charset_get_contractions(CHARSET_INFO *cs, - int level); - -extern size_t my_vsnprintf_ex(CHARSET_INFO *cs, char *to, size_t n, - const char* fmt, va_list ap); - -/* - Convert a string between two character sets. - Bad byte sequences as well as characters that cannot be - encoded in the destination character set are replaced to '?'. -*/ -uint32 my_convert(char *to, uint32 to_length, CHARSET_INFO *to_cs, - const char *from, uint32 from_length, - CHARSET_INFO *from_cs, uint *errors); - -/** - An extended version of my_convert(), to pass non-default mb_wc() and wc_mb(). - For example, String::copy_printable() which is used in - Protocol::store_warning() uses this to escape control - and non-convertable characters. -*/ -uint32 my_convert_using_func(char *to, size_t to_length, CHARSET_INFO *to_cs, - my_charset_conv_wc_mb mb_wc, - const char *from, size_t from_length, - CHARSET_INFO *from_cs, - my_charset_conv_mb_wc wc_mb, - uint *errors); -/* - Convert a string between two character sets. - Bad byte sequences as well as characters that cannot be - encoded in the destination character set are replaced to '?'. - Not more than "nchars" characters are copied. - Conversion statistics is returned in "status" and is set as follows: - - status->m_native_copy_status.m_source_end_pos - to the position - between (src) and (src+src_length), where the function stopped reading - the source string. - - status->m_native_copy_status.m_well_formed_error_pos - to the position - between (src) and (src+src_length), where the first badly formed byte - sequence was found, or to NULL if the string was well formed in the - given range. - - status->m_cannot_convert_error_pos - to the position - between (src) and (src+src_length), where the first character that - cannot be represented in the destination character set was found, - or to NULL if all characters in the given range were successfully - converted. - - "src" is allowed to be a NULL pointer. In this case "src_length" must - be equal to 0. All "status" members are initialized to NULL, and 0 is - returned. -*/ -size_t my_convert_fix(CHARSET_INFO *dstcs, char *dst, size_t dst_length, - CHARSET_INFO *srccs, const char *src, size_t src_length, - size_t nchars, - MY_STRCOPY_STATUS *copy_status, - MY_STRCONV_STATUS *conv_status); - -#define _MY_U 01 /* Upper case */ -#define _MY_L 02 /* Lower case */ -#define _MY_NMR 04 /* Numeral (digit) */ -#define _MY_SPC 010 /* Spacing character */ -#define _MY_PNT 020 /* Punctuation */ -#define _MY_CTR 040 /* Control character */ -#define _MY_B 0100 /* Blank */ -#define _MY_X 0200 /* heXadecimal digit */ - - -#define my_isascii(c) (!((c) & ~0177)) -#define my_toascii(c) ((c) & 0177) -#define my_tocntrl(c) ((c) & 31) -#define my_toprint(c) ((c) | 64) -#define my_toupper(s,c) (char) ((s)->to_upper[(uchar) (c)]) -#define my_tolower(s,c) (char) ((s)->to_lower[(uchar) (c)]) -#define my_isalpha(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_U | _MY_L)) -#define my_isupper(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_U) -#define my_islower(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_L) -#define my_isdigit(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_NMR) -#define my_isxdigit(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_X) -#define my_isalnum(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_U | _MY_L | _MY_NMR)) -#define my_isspace(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_SPC) -#define my_ispunct(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_PNT) -#define my_isprint(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR | _MY_B)) -#define my_isgraph(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR)) -#define my_iscntrl(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_CTR) - -/* Some macros that should be cleaned up a little */ -#define my_isvar(s,c) (my_isalnum(s,c) || (c) == '_') -#define my_isvar_start(s,c) (my_isalpha(s,c) || (c) == '_') - -#define my_binary_compare(s) ((s)->state & MY_CS_BINSORT) -#define use_strnxfrm(s) ((s)->state & MY_CS_STRNXFRM) -#define my_strnncoll(s, a, b, c, d) ((s)->coll->strnncoll((s), (a), (b), (c), (d), 0)) -#define my_strcasecmp(s, a, b) ((s)->coll->strcasecmp((s), (a), (b))) - -/** - Detect if the leftmost character in a string is a valid multi-byte character - and return its length, or return 0 otherwise. - @param cs - character set - @param str - the beginning of the string - @param end - the string end (the next byte after the string) - @return >0, for a multi-byte character - @rerurn 0, for a single byte character, broken sequence, empty string. -*/ -static inline -uint my_ismbchar(CHARSET_INFO *cs, const char *str, const char *end) -{ - int char_length= (cs->cset->charlen)(cs, (const uchar *) str, - (const uchar *) end); - return char_length > 1 ? (uint) char_length : 0U; -} - - -/** - Convert broken and incomplete byte sequences to 1 byte. -*/ -static inline -uint my_ci_charlen_fix(CHARSET_INFO *cs, const uchar *str, const uchar *end) -{ - int char_length= my_ci_charlen(cs, str, end); - DBUG_ASSERT(str < end); - return char_length > 0 ? (uint) char_length : (uint) 1U; -} - - -/* - A compatibility replacement pure C function for the former - cs->cset->well_formed_len(). - In C++ code please use Well_formed_prefix::length() instead. -*/ -static inline size_t -my_well_formed_length(CHARSET_INFO *cs, const char *b, const char *e, - size_t nchars, int *error) -{ - MY_STRCOPY_STATUS status; - (void) my_ci_well_formed_char_length(cs, b, e, nchars, &status); - *error= status.m_well_formed_error_pos == NULL ? 0 : 1; - return (size_t) (status.m_source_end_pos - b); -} - - -#define my_caseup_str(s, a) ((s)->cset->caseup_str((s), (a))) -#define my_casedn_str(s, a) ((s)->cset->casedn_str((s), (a))) - -/* XXX: still need to take care of this one */ -#ifdef MY_CHARSET_TIS620 -#error The TIS620 charset is broken at the moment. Tell tim to fix it. -#define USE_TIS620 -#include "t_ctype.h" -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _m_ctype_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/m_string.h b/VCMP-LUA/modules/mariadb/include/mysql/server/m_string.h deleted file mode 100644 index e4c11d2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/m_string.h +++ /dev/null @@ -1,240 +0,0 @@ -/* - Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* There may be problems included in all of these. Try to test in - configure which ones are needed? */ - -/* This is needed for the definitions of strchr... on solaris */ - -#ifndef _m_string_h -#define _m_string_h - -#include "my_decimal_limits.h" - -#ifndef __USE_GNU -#define __USE_GNU /* We want to use stpcpy */ -#endif -#if defined(HAVE_STRINGS_H) -#include -#endif -#if defined(HAVE_STRING_H) -#include -#endif - -/* This is needed for the definitions of memcpy... on solaris */ -#if defined(HAVE_MEMORY_H) && !defined(__cplusplus) -#include -#endif - -#if !defined(HAVE_MEMCPY) && !defined(HAVE_MEMMOVE) -# define memcpy(d, s, n) bcopy ((s), (d), (n)) -# define memset(A,C,B) bfill((A),(B),(C)) -# define memmove(d, s, n) bmove ((d), (s), (n)) -#elif defined(HAVE_MEMMOVE) -# define bmove(d, s, n) memmove((d), (s), (n)) -#endif - -/* Unixware 7 */ -#if !defined(HAVE_BFILL) -# define bfill(A,B,C) memset((A),(C),(B)) -#endif - -# define bmove_align(A,B,C) memcpy((A),(B),(C)) - -# define bcmp(A,B,C) memcmp((A),(B),(C)) - -#if !defined(bzero) -# define bzero(A,B) memset((A),0,(B)) -#endif - -#if defined(__cplusplus) -extern "C" { -#endif - -#ifdef DBUG_OFF -#if defined(HAVE_STPCPY) && MY_GNUC_PREREQ(3, 4) && !defined(__INTEL_COMPILER) -#define strmov(A,B) __builtin_stpcpy((A),(B)) -#elif defined(HAVE_STPCPY) -#define strmov(A,B) stpcpy((A),(B)) -#endif -#endif - -/* Declared in int2str() */ -extern const char _dig_vec_upper[]; -extern const char _dig_vec_lower[]; - -extern char *strmov_overlapp(char *dest, const char *src); - -#if defined(_lint) || defined(FORCE_INIT_OF_VARS) -#define LINT_INIT_STRUCT(var) bzero(&var, sizeof(var)) /* No uninitialize-warning */ -#else -#define LINT_INIT_STRUCT(var) -#endif - -/* Prototypes for string functions */ - -extern void bmove_upp(uchar *dst,const uchar *src,size_t len); -extern void bchange(uchar *dst,size_t old_len,const uchar *src, - size_t new_len,size_t tot_len); -extern void strappend(char *s,size_t len,pchar fill); -extern char *strend(const char *s); -extern char *strcend(const char *, pchar); -extern char *strfill(char * s,size_t len,pchar fill); -extern char *strmake(char *dst,const char *src,size_t length); - -#if !defined(__GNUC__) || (__GNUC__ < 4) -#define strmake_buf(D,S) strmake(D, S, sizeof(D) - 1) -#else -#define strmake_buf(D,S) ({ \ - __typeof__ (D) __x __attribute__((unused)) = { 2 }; \ - strmake(D, S, sizeof(D) - 1); \ - }) -#endif - -#ifndef strmov -extern char *strmov(char *dst,const char *src); -#endif -extern char *strnmov(char *dst, const char *src, size_t n); -extern char *strcont(const char *src, const char *set); -extern char *strxmov(char *dst, const char *src, ...); -extern char *strxnmov(char *dst, size_t len, const char *src, ...); - -/* Prototypes of normal stringfunctions (with may ours) */ -#ifndef HAVE_STRNLEN -extern size_t strnlen(const char *s, size_t n); -#endif - -extern int is_prefix(const char *, const char *); - -/* Conversion routines */ -typedef enum { - MY_GCVT_ARG_FLOAT, - MY_GCVT_ARG_DOUBLE -} my_gcvt_arg_type; - -double my_strtod(const char *str, char **end, int *error); -double my_atof(const char *nptr); -size_t my_fcvt(double x, int precision, char *to, my_bool *error); -size_t my_gcvt(double x, my_gcvt_arg_type type, int width, char *to, - my_bool *error); - -/* - The longest string my_fcvt can return is 311 + "precision" bytes. - Here we assume that we never cal my_fcvt() with - precision >= DECIMAL_NOT_SPECIFIED - (+ 1 byte for the terminating '\0'). -*/ -#define FLOATING_POINT_BUFFER (311 + DECIMAL_NOT_SPECIFIED) - -/* - We want to use the 'e' format in some cases even if we have enough space - for the 'f' one just to mimic sprintf("%.15g") behavior for large integers, - and to improve it for numbers < 10^(-4). - That is, for |x| < 1 we require |x| >= 10^(-15), and for |x| > 1 we require - it to be integer and be <= 10^DBL_DIG for the 'f' format to be used. - We don't lose precision, but make cases like "1e200" or "0.00001" look nicer. -*/ -#define MAX_DECPT_FOR_F_FORMAT DBL_DIG - -/* - The maximum possible field width for my_gcvt() conversion. - (DBL_DIG + 2) significant digits + sign + "." + ("e-NNN" or - MAX_DECPT_FOR_F_FORMAT zeros for cases when |x|<1 and the 'f' format is used). -*/ -#define MY_GCVT_MAX_FIELD_WIDTH (DBL_DIG + 4 + MY_MAX(5, MAX_DECPT_FOR_F_FORMAT)) \ - -extern char *llstr(longlong value,char *buff); -extern char *ullstr(longlong value,char *buff); -#ifndef HAVE_STRTOUL -extern long strtol(const char *str, char **ptr, int base); -extern ulong strtoul(const char *str, char **ptr, int base); -#endif - -extern char *int2str(long val, char *dst, int radix, int upcase); -extern char *int10_to_str(long val,char *dst,int radix); -extern char *str2int(const char *src,int radix,long lower,long upper, - long *val); -longlong my_strtoll10(const char *nptr, char **endptr, int *error); -#if SIZEOF_LONG == SIZEOF_LONG_LONG -#define ll2str(A,B,C,D) int2str((A),(B),(C),(D)) -#define longlong10_to_str(A,B,C) int10_to_str((A),(B),(C)) -#undef strtoll -#define strtoll(A,B,C) strtol((A),(B),(C)) -#define strtoull(A,B,C) strtoul((A),(B),(C)) -#ifndef HAVE_STRTOULL -#define HAVE_STRTOULL -#endif -#ifndef HAVE_STRTOLL -#define HAVE_STRTOLL -#endif -#else -#ifdef HAVE_LONG_LONG -extern char *ll2str(longlong val,char *dst,int radix, int upcase); -extern char *longlong10_to_str(longlong val,char *dst,int radix); -#if (!defined(HAVE_STRTOULL) || defined(NO_STRTOLL_PROTO)) -extern longlong strtoll(const char *str, char **ptr, int base); -extern ulonglong strtoull(const char *str, char **ptr, int base); -#endif -#endif -#endif -#define longlong2str(A,B,C) ll2str((A),(B),(C),1) - -#if defined(__cplusplus) -} -#endif - -#include - -#define STRING_WITH_LEN(X) (X), ((size_t) (sizeof(X) - 1)) -#define USTRING_WITH_LEN(X) ((uchar*) X), ((size_t) (sizeof(X) - 1)) -#define C_STRING_WITH_LEN(X) ((char *) (X)), ((size_t) (sizeof(X) - 1)) -#define LEX_STRING_WITH_LEN(X) (X).str, (X).length - -typedef struct st_mysql_const_lex_string LEX_CSTRING; - -/* A variant with const and unsigned */ -struct st_mysql_const_unsigned_lex_string -{ - const uchar *str; - size_t length; -}; -typedef struct st_mysql_const_unsigned_lex_string LEX_CUSTRING; - -static inline void lex_string_set(LEX_CSTRING *lex_str, const char *c_str) -{ - lex_str->str= c_str; - lex_str->length= strlen(c_str); -} -static inline void lex_string_set3(LEX_CSTRING *lex_str, const char *c_str, - size_t len) -{ - lex_str->str= c_str; - lex_str->length= len; -} - -#ifdef __cplusplus -static inline char *safe_str(char *str) -{ return str ? str : const_cast(""); } -#endif - -static inline const char *safe_str(const char *str) -{ return str ? str : ""; } - -static inline size_t safe_strlen(const char *str) -{ return str ? strlen(str) : 0; } - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/ma_dyncol.h b/VCMP-LUA/modules/mariadb/include/mysql/server/ma_dyncol.h deleted file mode 100644 index 833a25b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/ma_dyncol.h +++ /dev/null @@ -1,251 +0,0 @@ -/* Copyright (c) 2011, Monty Program Ab - Copyright (c) 2011, Oleksandr Byelkin - - 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 the following disclaimer in - the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY ``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 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. -*/ - -#ifndef ma_dyncol_h -#define ma_dyncol_h -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include - -#ifndef _my_sys_h -typedef struct st_dynamic_string -{ - char *str; - size_t length,max_length,alloc_increment; -} DYNAMIC_STRING; -#endif - -#ifndef MY_GLOBAL_INCLUDED -struct st_mysql_lex_string -{ - char *str; - size_t length; -}; -typedef struct st_mysql_lex_string MYSQL_LEX_STRING; -typedef struct st_mysql_lex_string LEX_STRING; -#endif - -/* - Limits of implementation -*/ -#define MAX_TOTAL_NAME_LENGTH 65535 -#define MAX_NAME_LENGTH (MAX_TOTAL_NAME_LENGTH/4) - -/* NO and OK is the same used just to show semantics */ -#define ER_DYNCOL_NO ER_DYNCOL_OK - -#ifdef HAVE_CHARSET_utf8mb4 -#define DYNCOL_UTF (&my_charset_utf8mb4_general_ci) -#else -#define DYNCOL_UTF (&my_charset_utf8mb3_general_ci) -#endif - -/* escape json strings */ -#define DYNCOL_JSON_ESC ((char)1) - -enum enum_dyncol_func_result -{ - ER_DYNCOL_OK= 0, - ER_DYNCOL_YES= 1, /* For functions returning 0/1 */ - ER_DYNCOL_FORMAT= -1, /* Wrong format of the encoded string */ - ER_DYNCOL_LIMIT= -2, /* Some limit reached */ - ER_DYNCOL_RESOURCE= -3, /* Out of resourses */ - ER_DYNCOL_DATA= -4, /* Incorrect input data */ - ER_DYNCOL_UNKNOWN_CHARSET= -5, /* Unknown character set */ - ER_DYNCOL_TRUNCATED= 2 /* OK, but data was truncated */ -}; - -typedef DYNAMIC_STRING DYNAMIC_COLUMN; - -enum enum_dynamic_column_type -{ - DYN_COL_NULL= 0, - DYN_COL_INT, - DYN_COL_UINT, - DYN_COL_DOUBLE, - DYN_COL_STRING, - DYN_COL_DECIMAL, - DYN_COL_DATETIME, - DYN_COL_DATE, - DYN_COL_TIME, - DYN_COL_DYNCOL -}; - -typedef enum enum_dynamic_column_type DYNAMIC_COLUMN_TYPE; - -struct st_dynamic_column_value -{ - DYNAMIC_COLUMN_TYPE type; - union - { - long long long_value; - unsigned long long ulong_value; - double double_value; - struct { - MYSQL_LEX_STRING value; - CHARSET_INFO *charset; - } string; - struct { - decimal_digit_t buffer[DECIMAL_BUFF_LENGTH]; - decimal_t value; - } decimal; - MYSQL_TIME time_value; - } x; -}; - -typedef struct st_dynamic_column_value DYNAMIC_COLUMN_VALUE; - -#ifdef MADYNCOL_DEPRECATED -enum enum_dyncol_func_result -dynamic_column_create(DYNAMIC_COLUMN *str, - uint column_nr, DYNAMIC_COLUMN_VALUE *value); - -enum enum_dyncol_func_result -dynamic_column_create_many(DYNAMIC_COLUMN *str, - uint column_count, - uint *column_numbers, - DYNAMIC_COLUMN_VALUE *values); -enum enum_dyncol_func_result -dynamic_column_update(DYNAMIC_COLUMN *org, uint column_nr, - DYNAMIC_COLUMN_VALUE *value); -enum enum_dyncol_func_result -dynamic_column_update_many(DYNAMIC_COLUMN *str, - uint add_column_count, - uint *column_numbers, - DYNAMIC_COLUMN_VALUE *values); - -enum enum_dyncol_func_result -dynamic_column_exists(DYNAMIC_COLUMN *org, uint column_nr); - -enum enum_dyncol_func_result -dynamic_column_list(DYNAMIC_COLUMN *org, DYNAMIC_ARRAY *array_of_uint); - -enum enum_dyncol_func_result -dynamic_column_get(DYNAMIC_COLUMN *org, uint column_nr, - DYNAMIC_COLUMN_VALUE *store_it_here); -#endif - -/* new functions */ -enum enum_dyncol_func_result -mariadb_dyncol_create_many_num(DYNAMIC_COLUMN *str, - uint column_count, - uint *column_numbers, - DYNAMIC_COLUMN_VALUE *values, - my_bool new_string); -enum enum_dyncol_func_result -mariadb_dyncol_create_many_named(DYNAMIC_COLUMN *str, - uint column_count, - MYSQL_LEX_STRING *column_keys, - DYNAMIC_COLUMN_VALUE *values, - my_bool new_string); - - -enum enum_dyncol_func_result -mariadb_dyncol_update_many_num(DYNAMIC_COLUMN *str, - uint add_column_count, - uint *column_keys, - DYNAMIC_COLUMN_VALUE *values); -enum enum_dyncol_func_result -mariadb_dyncol_update_many_named(DYNAMIC_COLUMN *str, - uint add_column_count, - MYSQL_LEX_STRING *column_keys, - DYNAMIC_COLUMN_VALUE *values); - - -enum enum_dyncol_func_result -mariadb_dyncol_exists_num(DYNAMIC_COLUMN *org, uint column_nr); -enum enum_dyncol_func_result -mariadb_dyncol_exists_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name); - -/* List of not NULL columns */ -enum enum_dyncol_func_result -mariadb_dyncol_list_num(DYNAMIC_COLUMN *str, uint *count, uint **nums); -enum enum_dyncol_func_result -mariadb_dyncol_list_named(DYNAMIC_COLUMN *str, uint *count, - MYSQL_LEX_STRING **names); - -/* - if the column do not exists it is NULL -*/ -enum enum_dyncol_func_result -mariadb_dyncol_get_num(DYNAMIC_COLUMN *org, uint column_nr, - DYNAMIC_COLUMN_VALUE *store_it_here); -enum enum_dyncol_func_result -mariadb_dyncol_get_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name, - DYNAMIC_COLUMN_VALUE *store_it_here); - -my_bool mariadb_dyncol_has_names(DYNAMIC_COLUMN *str); - -enum enum_dyncol_func_result -mariadb_dyncol_check(DYNAMIC_COLUMN *str); - -enum enum_dyncol_func_result -mariadb_dyncol_json(DYNAMIC_COLUMN *str, DYNAMIC_STRING *json); - -#define mariadb_dyncol_init(A) memset((A), 0, sizeof(*(A))) -void mariadb_dyncol_free(DYNAMIC_COLUMN *str); - -/* conversion of values to 3 base types */ -enum enum_dyncol_func_result -mariadb_dyncol_val_str(DYNAMIC_STRING *str, DYNAMIC_COLUMN_VALUE *val, - CHARSET_INFO *cs, my_bool quote); -enum enum_dyncol_func_result -mariadb_dyncol_val_long(longlong *ll, DYNAMIC_COLUMN_VALUE *val); -enum enum_dyncol_func_result -mariadb_dyncol_val_double(double *dbl, DYNAMIC_COLUMN_VALUE *val); - - -enum enum_dyncol_func_result -mariadb_dyncol_unpack(DYNAMIC_COLUMN *str, - uint *count, - MYSQL_LEX_STRING **names, DYNAMIC_COLUMN_VALUE **vals); - -void mariadb_dyncol_unpack_free(MYSQL_LEX_STRING *names, - DYNAMIC_COLUMN_VALUE *vals); - -int mariadb_dyncol_column_cmp_named(const MYSQL_LEX_STRING *s1, - const MYSQL_LEX_STRING *s2); - -enum enum_dyncol_func_result -mariadb_dyncol_column_count(DYNAMIC_COLUMN *str, uint *column_count); - -#define mariadb_dyncol_value_init(V) (V)->type= DYN_COL_NULL - -/* - Prepare value for using as decimal -*/ -void mariadb_dyncol_prepare_decimal(DYNAMIC_COLUMN_VALUE *value); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_alloc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_alloc.h deleted file mode 100644 index 181f637..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_alloc.h +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Data structures for mysys/my_alloc.c (root memory allocator) -*/ - -#ifndef _my_alloc_h -#define _my_alloc_h - -#include - -#define ALLOC_MAX_BLOCK_TO_DROP 4096 -#define ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP 10 - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct st_used_mem -{ /* struct for once_alloc (block) */ - struct st_used_mem *next; /* Next block in use */ - size_t left; /* memory left in block */ - size_t size; /* size of block */ -} USED_MEM; - - -typedef struct st_mem_root -{ - USED_MEM *free; /* blocks with free memory in it */ - USED_MEM *used; /* blocks almost without free memory */ - USED_MEM *pre_alloc; /* preallocated block */ - /* if block have less memory it will be put in 'used' list */ - size_t min_malloc; - size_t block_size; /* initial block size */ - unsigned int block_num; /* allocated blocks counter */ - /* - first free block in queue test counter (if it exceed - MAX_BLOCK_USAGE_BEFORE_DROP block will be dropped in 'used' list) - */ - unsigned int first_block_usage; - - void (*error_handler)(void); - - PSI_memory_key m_psi_key; -} MEM_ROOT; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_attribute.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_attribute.h deleted file mode 100644 index c8e9807..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_attribute.h +++ /dev/null @@ -1,74 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Helper macros used for setting different __attributes__ - on functions in a portable fashion -*/ - -#ifndef _my_attribute_h -#define _my_attribute_h - -#if defined(__GNUC__) -# ifndef GCC_VERSION -# define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) -# endif -#endif - -/* - Disable __attribute__() on gcc < 2.7, g++ < 3.4, and non-gcc compilers. - Some forms of __attribute__ are actually supported in earlier versions of - g++, but we just disable them all because we only use them to generate - compilation warnings. -*/ -#ifndef __attribute__ -# if !defined(__GNUC__) && !defined(__clang__) -# define __attribute__(A) -# elif defined(__GNUC__) -# ifndef GCC_VERSION -# define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) -# endif -# if GCC_VERSION < 2008 -# define __attribute__(A) -# elif defined(__cplusplus) && GCC_VERSION < 3004 -# define __attribute__(A) -# endif -# endif -#endif - -/* - __attribute__((format(...))) is only supported in gcc >= 2.8 and g++ >= 3.4 - But that's already covered by the __attribute__ tests above, so this is - just a convenience macro. -*/ -#ifndef ATTRIBUTE_FORMAT -# define ATTRIBUTE_FORMAT(style, m, n) __attribute__((format(style, m, n))) -#endif - -/* - - __attribute__((format(...))) on a function pointer is not supported - until gcc 3.1 -*/ -#ifndef ATTRIBUTE_FORMAT_FPTR -# if (GCC_VERSION >= 3001) -# define ATTRIBUTE_FORMAT_FPTR(style, m, n) ATTRIBUTE_FORMAT(style, m, n) -# else -# define ATTRIBUTE_FORMAT_FPTR(style, m, n) -# endif /* GNUC >= 3.1 */ -#endif - - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_byteorder.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_byteorder.h deleted file mode 100644 index c302781..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_byteorder.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef MY_BYTEORDER_INCLUDED -#define MY_BYTEORDER_INCLUDED - -/* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* - Macro for reading 32-bit integer from network byte order (big-endian) - from an unaligned memory location. -*/ -#define int4net(A) (int32) (((uint32) ((uchar) (A)[3])) | \ - (((uint32) ((uchar) (A)[2])) << 8) | \ - (((uint32) ((uchar) (A)[1])) << 16) | \ - (((uint32) ((uchar) (A)[0])) << 24)) - -/* - Function-like macros for reading and storing in machine independent - format (low byte first). There are 'korr' (assume 'corrector') variants - for integer types, but 'get' (assume 'getter') for floating point types. -*/ -#if defined(__i386__) || defined(_WIN32) -#define MY_BYTE_ORDER_ARCH_OPTIMIZED -#include "byte_order_generic_x86.h" -#elif defined(__x86_64__) -#include "byte_order_generic_x86_64.h" -#else -#include "byte_order_generic.h" -#endif - -/* - Function-like macros for reading and storing in machine format from/to - short/long to/from some place in memory V should be a variable (not on - a register) and M a pointer to byte. -*/ -#ifdef WORDS_BIGENDIAN -#include "big_endian.h" -#else -#include "little_endian.h" -#endif - -#endif /* MY_BYTEORDER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_compiler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_compiler.h deleted file mode 100644 index d35a910..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_compiler.h +++ /dev/null @@ -1,186 +0,0 @@ -#ifndef MY_COMPILER_INCLUDED -#define MY_COMPILER_INCLUDED - -/* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - Header for compiler-dependent features. - - Intended to contain a set of reusable wrappers for preprocessor - macros, attributes, pragmas, and any other features that are - specific to a target compiler. -*/ - -/** - Compiler-dependent internal convenience macros. -*/ - -/* C vs C++ */ -#ifdef __cplusplus -#define CONSTEXPR constexpr -#else -#define CONSTEXPR -#endif /* __cplusplus */ - - -/* GNU C/C++ */ -#if defined __GNUC__ -/* Convenience macro to test the minimum required GCC version. */ -# define MY_GNUC_PREREQ(maj, min) \ - ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) -/* Any after 2.95... */ -# define MY_ALIGN_EXT -/* Comunicate to the compiler the unreachability of the code. */ -# if MY_GNUC_PREREQ(4,5) -# define MY_ASSERT_UNREACHABLE() __builtin_unreachable() -# endif - -/* Microsoft Visual C++ */ -#elif defined _MSC_VER -# define MY_ALIGNOF(type) __alignof(type) -# define MY_ALIGNED(n) __declspec(align(n)) - -/* Oracle Solaris Studio */ -#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) -# if __SUNPRO_C >= 0x590 -# define MY_ALIGN_EXT -# endif - -/* IBM XL C/C++ */ -#elif defined __xlC__ -# if __xlC__ >= 0x0600 -# define MY_ALIGN_EXT -# endif - -/* HP aCC */ -#elif defined(__HP_aCC) || defined(__HP_cc) -# if (__HP_aCC >= 60000) || (__HP_cc >= 60000) -# define MY_ALIGN_EXT -# endif -#endif - -#ifdef MY_ALIGN_EXT -/** Specifies the minimum alignment of a type. */ -# define MY_ALIGNOF(type) __alignof__(type) -/** Determine the alignment requirement of a type. */ -# define MY_ALIGNED(n) __attribute__((__aligned__((n)))) -#endif - -/** - Generic (compiler-independent) features. -*/ - -#ifndef MY_GNUC_PREREQ -# define MY_GNUC_PREREQ(maj, min) (0) -#endif - -#ifndef MY_ALIGNOF -# ifdef __cplusplus - template struct my_alignof_helper { char m1; type m2; }; - /* Invalid for non-POD types, but most compilers give the right answer. */ -# define MY_ALIGNOF(type) offsetof(my_alignof_helper, m2) -# else -# define MY_ALIGNOF(type) offsetof(struct { char m1; type m2; }, m2) -# endif -#endif - -#ifndef MY_ASSERT_UNREACHABLE -# define MY_ASSERT_UNREACHABLE() do { assert(0); } while (0) -#endif - -/** - C++ Type Traits -*/ - -#ifdef __cplusplus - -/** - Opaque storage with a particular alignment. -*/ -# if defined(MY_ALIGNED) -/* Partial specialization used due to MSVC++. */ -template struct my_alignment_imp; -template<> struct MY_ALIGNED(1) my_alignment_imp<1> {}; -template<> struct MY_ALIGNED(2) my_alignment_imp<2> {}; -template<> struct MY_ALIGNED(4) my_alignment_imp<4> {}; -template<> struct MY_ALIGNED(8) my_alignment_imp<8> {}; -template<> struct MY_ALIGNED(16) my_alignment_imp<16> {}; -/* ... expand as necessary. */ -# else -template -struct my_alignment_imp { double m1; }; -# endif - -/** - A POD type with a given size and alignment. - - @remark If the compiler does not support a alignment attribute - (MY_ALIGN macro), the default alignment of a double is - used instead. - - @tparam size The minimum size. - @tparam alignment The desired alignment: 1, 2, 4, 8 or 16. -*/ -template -struct my_aligned_storage -{ - union - { - char data[size]; - my_alignment_imp align; - }; -}; - -#endif /* __cplusplus */ - -# ifndef MY_ALIGNED -/* - Make sure MY_ALIGNED can be used also on platforms where we don't - have a way of aligning data structures. -*/ -#define MY_ALIGNED(size) -#endif - -#ifdef __GNUC__ -# define ATTRIBUTE_NORETURN __attribute__((noreturn)) -# define ATTRIBUTE_NOINLINE __attribute__((noinline)) -# if MY_GNUC_PREREQ(4,3) -/** Starting with GCC 4.3, the "cold" attribute is used to inform the -compiler that a function is unlikely executed. The function is -optimized for size rather than speed and on many targets it is placed -into special subsection of the text section so all cold functions -appears close together improving code locality of non-cold parts of -program. The paths leading to call of cold functions within code are -marked as unlikely by the branch prediction mechanism. optimize a -rarely invoked function for size instead for speed. */ -# define ATTRIBUTE_COLD __attribute__((cold)) -# endif -#elif defined _MSC_VER -# define ATTRIBUTE_NORETURN __declspec(noreturn) -# define ATTRIBUTE_NOINLINE __declspec(noinline) -#else -# define ATTRIBUTE_NORETURN /* empty */ -# define ATTRIBUTE_NOINLINE /* empty */ -#endif - -#ifndef ATTRIBUTE_COLD -# define ATTRIBUTE_COLD /* empty */ -#endif - -#include - -#endif /* MY_COMPILER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_config.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_config.h deleted file mode 100644 index 22f5893..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_config.h +++ /dev/null @@ -1,558 +0,0 @@ -/* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MY_CONFIG_H -#define MY_CONFIG_H -#define DOT_FRM_VERSION 6 -/* Headers we may want to use. */ -#define STDC_HEADERS 1 -/* #undef _GNU_SOURCE */ -/* #undef HAVE_ALLOCA_H */ -/* #undef HAVE_ARPA_INET_H */ -/* #undef HAVE_ASM_TERMBITS_H */ -/* #undef HAVE_CRYPT_H */ -/* #undef HAVE_CURSES_H */ -/* #undef HAVE_BFD_H */ -/* #undef HAVE_NDIR_H */ -/* #undef HAVE_DIRENT_H */ -/* #undef HAVE_DLFCN_H */ -/* #undef HAVE_EXECINFO_H */ -#define HAVE_FCNTL_H 1 -/* #undef HAVE_FENV_H */ -#define HAVE_FLOAT_H 1 -/* #undef HAVE_FNMATCH_H */ -/* #undef HAVE_FPU_CONTROL_H */ -/* #undef HAVE_GRP_H */ -/* #undef HAVE_IA64INTRIN_H */ -/* #undef HAVE_IEEEFP_H */ -/* #undef HAVE_INTTYPES_H */ -/* #undef HAVE_KQUEUE */ -#define HAVE_LIMITS_H 1 -/* #undef HAVE_LINK_H */ -/* #undef HAVE_LINUX_UNISTD_H */ -#define HAVE_LOCALE_H 1 -#define HAVE_MALLOC_H 1 -#define HAVE_MEMORY_H 1 -/* #undef HAVE_NETINET_IN_H */ -/* #undef HAVE_PATHS_H */ -/* #undef HAVE_POLL_H */ -/* #undef HAVE_PWD_H */ -/* #undef HAVE_SCHED_H */ -/* #undef HAVE_SELECT_H */ -/* #undef HAVE_SOLARIS_LARGE_PAGES */ -#define HAVE_STDDEF_H 1 -#define HAVE_STDLIB_H 1 -#define HAVE_STDARG_H 1 -/* #undef HAVE_STRINGS_H */ -#define HAVE_STRING_H 1 -/* #undef HAVE_STDINT_H */ -/* #undef HAVE_SYNCH_H */ -/* #undef HAVE_SYSENT_H */ -/* #undef HAVE_SYS_DIR_H */ -/* #undef HAVE_SYS_FILE_H */ -/* #undef HAVE_SYS_FPU_H */ -/* #undef HAVE_SYS_IOCTL_H */ -/* #undef HAVE_SYS_MALLOC_H */ -/* #undef HAVE_SYS_MMAN_H */ -/* #undef HAVE_SYS_NDIR_H */ -/* #undef HAVE_SYS_PTE_H */ -/* #undef HAVE_SYS_PTEM_H */ -/* #undef HAVE_SYS_PRCTL_H */ -/* #undef HAVE_SYS_RESOURCE_H */ -/* #undef HAVE_SYS_SELECT_H */ -/* #undef HAVE_SYS_SOCKET_H */ -/* #undef HAVE_SYS_SOCKIO_H */ -/* #undef HAVE_SYS_UTSNAME_H */ -#define HAVE_SYS_STAT_H 1 -/* #undef HAVE_SYS_STREAM_H */ -/* #undef HAVE_SYS_SYSCALL_H */ -#define HAVE_SYS_TIMEB_H 1 -/* #undef HAVE_SYS_TIMES_H */ -/* #undef HAVE_SYS_TIME_H */ -#define HAVE_SYS_TYPES_H 1 -/* #undef HAVE_SYS_UN_H */ -/* #undef HAVE_SYS_VADVISE_H */ -/* #undef HAVE_SYS_STATVFS_H */ -/* #undef HAVE_UCONTEXT_H */ -/* #undef HAVE_TERM_H */ -/* #undef HAVE_TERMBITS_H */ -/* #undef HAVE_TERMIOS_H */ -/* #undef HAVE_TERMIO_H */ -/* #undef HAVE_TERMCAP_H */ -#define HAVE_TIME_H 1 -/* #undef HAVE_UNISTD_H */ -/* #undef HAVE_UTIME_H */ -#define HAVE_VARARGS_H 1 -#define HAVE_SYS_UTIME_H 1 -/* #undef HAVE_SYS_WAIT_H */ -/* #undef HAVE_SYS_PARAM_H */ - -/* Libraries */ -/* #undef HAVE_LIBWRAP */ -/* #undef HAVE_SYSTEMD */ - -/* Does "struct timespec" have a "sec" and "nsec" field? */ -/* #undef HAVE_TIMESPEC_TS_SEC */ - -/* Readline */ -/* #undef HAVE_HIST_ENTRY */ -/* #undef USE_LIBEDIT_INTERFACE */ -/* #undef USE_NEW_READLINE_INTERFACE */ - -/* #undef FIONREAD_IN_SYS_IOCTL */ -/* #undef GWINSZ_IN_SYS_IOCTL */ -/* #undef TIOCSTAT_IN_SYS_IOCTL */ -/* #undef FIONREAD_IN_SYS_FILIO */ - -/* Functions we may want to use. */ -/* #undef HAVE_ACCEPT4 */ -#define HAVE_ACCESS 1 -/* #undef HAVE_ALARM */ -#define HAVE_ALLOCA 1 -/* #undef HAVE_BFILL */ -/* #undef HAVE_INDEX */ -/* #undef HAVE_CLOCK_GETTIME */ -/* #undef HAVE_CRYPT */ -/* #undef HAVE_CUSERID */ -/* #undef HAVE_DLADDR */ -/* #undef HAVE_DLERROR */ -/* #undef HAVE_DLOPEN */ -/* #undef HAVE_FCHMOD */ -/* #undef HAVE_FCNTL */ -/* #undef HAVE_FDATASYNC */ -/* #undef HAVE_DECL_FDATASYNC */ -/* #undef HAVE_FEDISABLEEXCEPT */ -/* #undef HAVE_FESETROUND */ -/* #undef HAVE_FP_EXCEPT */ -/* #undef HAVE_FSEEKO */ -/* #undef HAVE_FSYNC */ -#define HAVE_FTIME 1 -/* #undef HAVE_GETIFADDRS */ -#define HAVE_GETCWD 1 -/* #undef HAVE_GETHOSTBYADDR_R */ -/* #undef HAVE_GETHRTIME */ -/* #undef HAVE_GETPAGESIZE */ -/* #undef HAVE_GETPAGESIZES */ -/* #undef HAVE_GETPASS */ -/* #undef HAVE_GETPASSPHRASE */ -/* #undef HAVE_GETPWNAM */ -/* #undef HAVE_GETPWUID */ -/* #undef HAVE_GETRLIMIT */ -/* #undef HAVE_GETRUSAGE */ -/* #undef HAVE_GETTIMEOFDAY */ -/* #undef HAVE_GETWD */ -#define HAVE_GMTIME_R 1 -/* #undef gmtime_r */ -/* #undef HAVE_IN_ADDR_T */ -/* #undef HAVE_INITGROUPS */ -#define HAVE_LDIV 1 -/* #undef HAVE_LRAND48 */ -#define HAVE_LOCALTIME_R 1 -/* #undef HAVE_LSTAT */ -/* #undef HAVE_MEMALIGN */ -/* #undef HAVE_MLOCK */ -/* #undef HAVE_NL_LANGINFO */ -/* #undef HAVE_MADVISE */ -/* #undef HAVE_DECL_MADVISE */ -/* #undef HAVE_DECL_MHA_MAPSIZE_VA */ -/* #undef HAVE_MALLINFO */ -#define HAVE_MEMCPY 1 -#define HAVE_MEMMOVE 1 -/* #undef HAVE_MKSTEMP */ -/* #undef HAVE_MKOSTEMP */ -/* #undef HAVE_MLOCKALL */ -/* #undef HAVE_MMAP */ -/* #undef HAVE_MMAP64 */ -#define HAVE_PERROR 1 -/* #undef HAVE_POLL */ -/* #undef HAVE_POSIX_FALLOCATE */ -/* #undef HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE */ -/* #undef HAVE_PREAD */ -/* #undef HAVE_READ_REAL_TIME */ -/* #undef HAVE_PTHREAD_ATTR_CREATE */ -/* #undef HAVE_PTHREAD_ATTR_GETGUARDSIZE */ -/* #undef HAVE_PTHREAD_ATTR_GETSTACKSIZE */ -/* #undef HAVE_PTHREAD_ATTR_SETSCOPE */ -/* #undef HAVE_PTHREAD_ATTR_SETSTACKSIZE */ -/* #undef HAVE_PTHREAD_CONDATTR_CREATE */ -/* #undef HAVE_PTHREAD_GETAFFINITY_NP */ -/* #undef HAVE_PTHREAD_KEY_DELETE */ -/* #undef HAVE_PTHREAD_KILL */ -/* #undef HAVE_PTHREAD_RWLOCK_RDLOCK */ -/* #undef HAVE_PTHREAD_SIGMASK */ -/* #undef HAVE_PTHREAD_YIELD_NP */ -/* #undef HAVE_PTHREAD_YIELD_ZERO_ARG */ -/* #undef PTHREAD_ONCE_INITIALIZER */ -#define HAVE_PUTENV 1 -/* #undef HAVE_READDIR_R */ -/* #undef HAVE_READLINK */ -/* #undef HAVE_REALPATH */ -#define HAVE_RENAME 1 -/* #undef HAVE_RWLOCK_INIT */ -/* #undef HAVE_SCHED_YIELD */ -#define HAVE_SELECT 1 -/* #undef HAVE_SETENV */ -#define HAVE_SETLOCALE 1 -/* #undef HAVE_SETUPTERM */ -/* #undef HAVE_SIGSET */ -/* #undef HAVE_SIGACTION */ -/* #undef HAVE_SIGTHREADMASK */ -/* #undef HAVE_SIGWAIT */ -/* #undef HAVE_SIGWAITINFO */ -/* #undef HAVE_SLEEP */ -#define HAVE_SNPRINTF 1 -/* #undef HAVE_STPCPY */ -#define HAVE_STRERROR 1 -#define HAVE_STRCOLL 1 -#define HAVE_STRNLEN 1 -#define HAVE_STRPBRK 1 -#define HAVE_STRTOK_R 1 -#define HAVE_STRTOLL 1 -#define HAVE_STRTOUL 1 -#define HAVE_STRTOULL 1 -#define HAVE_TELL 1 -/* #undef HAVE_THR_SETCONCURRENCY */ -/* #undef HAVE_THR_YIELD */ -#define HAVE_TIME 1 -/* #undef HAVE_TIMES */ -/* #undef HAVE_VIDATTR */ -#define HAVE_VIO_READ_BUFF 1 -/* #undef HAVE_VASPRINTF */ -#define HAVE_VSNPRINTF 1 -/* #undef HAVE_FTRUNCATE */ -#define HAVE_TZNAME 1 -/* Symbols we may use */ -/* #undef HAVE_SYS_ERRLIST */ -/* used by stacktrace functions */ -/* #undef HAVE_BACKTRACE */ -/* #undef HAVE_BACKTRACE_SYMBOLS */ -/* #undef HAVE_BACKTRACE_SYMBOLS_FD */ -/* #undef HAVE_PRINTSTACK */ -#define HAVE_IPV6 1 -/* #undef ss_family */ -/* #undef HAVE_SOCKADDR_IN_SIN_LEN */ -/* #undef HAVE_SOCKADDR_IN6_SIN6_LEN */ -#define STRUCT_TIMESPEC_HAS_TV_SEC 1 -#define STRUCT_TIMESPEC_HAS_TV_NSEC 1 - -#define USE_MB 1 -#define USE_MB_IDENT 1 - -/* this means that valgrind headers and macros are available */ -/* #undef HAVE_VALGRIND_MEMCHECK_H */ - -/* this means WITH_VALGRIND - we change some code paths for valgrind */ -/* #undef HAVE_valgrind */ - -/* Types we may use */ -#ifdef __APPLE__ - /* - Special handling required for OSX to support universal binaries that - mix 32 and 64 bit architectures. - */ - #if(__LP64__) - #define SIZEOF_LONG 8 - #else - #define SIZEOF_LONG 4 - #endif - #define SIZEOF_VOIDP SIZEOF_LONG - #define SIZEOF_CHARP SIZEOF_LONG - #define SIZEOF_SIZE_T SIZEOF_LONG -#else -/* No indentation, to fetch the lines from verification scripts */ -#define SIZEOF_LONG 4 -#define SIZEOF_VOIDP 8 -#define SIZEOF_CHARP 8 -#define SIZEOF_SIZE_T 8 -#endif - -#define HAVE_LONG 1 -#define HAVE_CHARP 1 -#define SIZEOF_INT 4 -#define HAVE_INT 1 -#define SIZEOF_LONG_LONG 8 -#define HAVE_LONG_LONG 1 -#define SIZEOF_OFF_T 4 -#define HAVE_OFF_T 1 -/* #undef SIZEOF_UCHAR */ -/* #undef HAVE_UCHAR */ -/* #undef SIZEOF_UINT */ -/* #undef HAVE_UINT */ -/* #undef SIZEOF_ULONG */ -/* #undef HAVE_ULONG */ -/* #undef SIZEOF_INT8 */ -/* #undef HAVE_INT8 */ -/* #undef SIZEOF_UINT8 */ -/* #undef HAVE_UINT8 */ -/* #undef SIZEOF_INT16 */ -/* #undef HAVE_INT16 */ -/* #undef SIZEOF_UINT16 */ -/* #undef HAVE_UINT16 */ -/* #undef SIZEOF_INT32 */ -/* #undef HAVE_INT32 */ -/* #undef SIZEOF_UINT32 */ -/* #undef HAVE_UINT32 */ -/* #undef SIZEOF_INT64 */ -/* #undef HAVE_INT64 */ -/* #undef SIZEOF_UINT64 */ -/* #undef HAVE_UINT64 */ - -#define SOCKET_SIZE_TYPE int - -/* #undef HAVE_MBSTATE_T */ - -#define MAX_INDEXES 64 - -#define QSORT_TYPE_IS_VOID 1 -#define RETQSORTTYPE void - -#define RETSIGTYPE void -#define VOID_SIGHANDLER 1 -/* #undef HAVE_SIGHANDLER_T */ -#define STRUCT_RLIMIT struct rlimit - -#ifdef __APPLE__ - #if __BIG_ENDIAN - #define WORDS_BIGENDIAN 1 - #endif -#else -/* #undef WORDS_BIGENDIAN */ -#endif - -/* Define to `__inline__' or `__inline' if that's what the C compiler calls - it, or to nothing if 'inline' is not supported under any name. */ -/* #undef C_HAS_inline */ -#if !(C_HAS_inline) -#ifndef __cplusplus -# define inline __inline -#endif -#endif - - -/* #undef TARGET_OS_LINUX */ - -#define HAVE_WCTYPE_H 1 -#define HAVE_WCHAR_H 1 -/* #undef HAVE_LANGINFO_H */ -/* #undef HAVE_MBRLEN */ -/* #undef HAVE_MBSRTOWCS */ -/* #undef HAVE_MBRTOWC */ -/* #undef HAVE_WCWIDTH */ -/* #undef HAVE_ISWLOWER */ -/* #undef HAVE_ISWUPPER */ -/* #undef HAVE_TOWLOWER */ -/* #undef HAVE_TOWUPPER */ -/* #undef HAVE_ISWCTYPE */ -/* #undef HAVE_WCHAR_T */ - - -#define HAVE_STRCASECMP 1 -/* #undef HAVE_TCGETATTR */ - -/* #undef HAVE_WEAK_SYMBOL */ -/* #undef HAVE_ABI_CXA_DEMANGLE */ -/* #undef HAVE_ATTRIBUTE_CLEANUP */ - -/* #undef HAVE_POSIX_SIGNALS */ -/* #undef HAVE_BSD_SIGNALS */ - -/* #undef HAVE_SVR3_SIGNALS */ -/* #undef HAVE_V7_SIGNALS */ -#define HAVE_ERR_remove_thread_state 1 -#define HAVE_X509_check_host 1 - -/* #undef HAVE_SOLARIS_STYLE_GETHOST */ - -/* #undef HAVE_GCC_C11_ATOMICS */ -/* #undef HAVE_SOLARIS_ATOMIC */ -#define NO_FCNTL_NONBLOCK 1 -#define NO_ALARM 1 - -/* #undef _LARGE_FILES */ -#define _LARGEFILE_SOURCE 1 -/* #undef _LARGEFILE64_SOURCE */ - -/* #undef TIME_WITH_SYS_TIME */ - -#define STACK_DIRECTION -1 - -#define SYSTEM_TYPE "Win64" -#define MACHINE_TYPE "AMD64" -#define DEFAULT_MACHINE "x64" -/* #undef HAVE_DTRACE */ - -#define SIGNAL_WITH_VIO_CLOSE 1 - -/* Windows stuff, mostly functions, that have Posix analogs but named differently */ -#define S_IROTH _S_IREAD -#define S_IFIFO _S_IFIFO -/* #undef IPPROTO_IPV6 */ -/* #undef IPV6_V6ONLY */ -#define sigset_t int -#define mode_t int -#define SIGQUIT SIGTERM -#define SIGPIPE SIGINT -#define popen _popen -#define pclose _pclose -#define ssize_t SSIZE_T -#define strcasecmp _stricmp -#define strncasecmp _strnicmp -/* #undef snprintf */ -#define strtok_r strtok_s -#define strtoll _strtoi64 -#define strtoull _strtoui64 -/* #undef vsnprintf */ -#if defined(_MSC_VER) && (_MSC_VER > 1800) -#define tzname _tzname -#define P_tmpdir "C:\\TEMP" -#endif -#if defined(_MSC_VER) && (_MSC_VER > 1310) -# define HAVE_SETENV -#define setenv(a,b,c) _putenv_s(a,b) -#endif -#define PSAPI_VERSION 1 /* for GetProcessMemoryInfo() */ - -/* We don't want the min/max macros */ -#ifdef __WIN__ -#define NOMINMAX 1 -#endif - -/* - MySQL features -*/ -#define LOCAL_INFILE_MODE_OFF 0 -#define LOCAL_INFILE_MODE_ON 1 -#define LOCAL_INFILE_MODE_AUTO 2 -#define ENABLED_LOCAL_INFILE LOCAL_INFILE_MODE_AUTO - -#define ENABLED_PROFILING 1 -/* #undef EXTRA_DEBUG */ -#define USE_SYMDIR 1 - -/* Character sets and collations */ -#define MYSQL_DEFAULT_CHARSET_NAME "latin1" -#define MYSQL_DEFAULT_COLLATION_NAME "latin1_swedish_ci" - -#define USE_MB 1 -#define USE_MB_IDENT 1 - -/* This should mean case insensitive file system */ -#define FN_NO_CASE_SENSE 1 - -#define HAVE_CHARSET_armscii8 1 -#define HAVE_CHARSET_ascii 1 -#define HAVE_CHARSET_big5 1 -#define HAVE_CHARSET_cp1250 1 -#define HAVE_CHARSET_cp1251 1 -#define HAVE_CHARSET_cp1256 1 -#define HAVE_CHARSET_cp1257 1 -#define HAVE_CHARSET_cp850 1 -#define HAVE_CHARSET_cp852 1 -#define HAVE_CHARSET_cp866 1 -#define HAVE_CHARSET_cp932 1 -#define HAVE_CHARSET_dec8 1 -#define HAVE_CHARSET_eucjpms 1 -#define HAVE_CHARSET_euckr 1 -#define HAVE_CHARSET_gb2312 1 -#define HAVE_CHARSET_gbk 1 -#define HAVE_CHARSET_geostd8 1 -#define HAVE_CHARSET_greek 1 -#define HAVE_CHARSET_hebrew 1 -#define HAVE_CHARSET_hp8 1 -#define HAVE_CHARSET_keybcs2 1 -#define HAVE_CHARSET_koi8r 1 -#define HAVE_CHARSET_koi8u 1 -#define HAVE_CHARSET_latin1 1 -#define HAVE_CHARSET_latin2 1 -#define HAVE_CHARSET_latin5 1 -#define HAVE_CHARSET_latin7 1 -#define HAVE_CHARSET_macce 1 -#define HAVE_CHARSET_macroman 1 -#define HAVE_CHARSET_sjis 1 -#define HAVE_CHARSET_swe7 1 -#define HAVE_CHARSET_tis620 1 -#define HAVE_CHARSET_ucs2 1 -#define HAVE_CHARSET_ujis 1 -#define HAVE_CHARSET_utf8mb4 1 -#define HAVE_CHARSET_utf8mb3 1 -#define HAVE_CHARSET_utf16 1 -#define HAVE_CHARSET_utf32 1 -#define HAVE_UCA_COLLATIONS 1 -#define HAVE_COMPRESS 1 -/* #undef HAVE_EncryptAes128Ctr */ -/* #undef HAVE_EncryptAes128Gcm */ - -/* - Stuff that always need to be defined (compile breaks without it) -*/ -#define HAVE_SPATIAL 1 -#define HAVE_RTREE_KEYS 1 -#define HAVE_QUERY_CACHE 1 -#define BIG_TABLES 1 - -/* - Important storage engines (those that really need define - WITH__STORAGE_ENGINE for the whole server) -*/ -#define WITH_INNOBASE_STORAGE_ENGINE 1 -#define WITH_PARTITION_STORAGE_ENGINE 1 -#define WITH_PERFSCHEMA_STORAGE_ENGINE 1 -#define WITH_ARIA_STORAGE_ENGINE 1 -#define USE_ARIA_FOR_TMP_TABLES 1 - -#define DEFAULT_MYSQL_HOME "C:/Program Files/MariaDB 10.5" -#define SHAREDIR "share" -#define DEFAULT_BASEDIR "C:/Program Files/MariaDB 10.5" -#define MYSQL_DATADIR "C:/Program Files/MariaDB 10.5/data" -#define DEFAULT_CHARSET_HOME "C:/Program Files/MariaDB 10.5" -#define PLUGINDIR "C:/Program Files/MariaDB 10.5/lib/plugin" -/* #undef DEFAULT_SYSCONFDIR */ -#define DEFAULT_TMPDIR P_tmpdir - -/* #undef SO_EXT */ - -#define MYSQL_VERSION_MAJOR 10 -#define MYSQL_VERSION_MINOR 5 -#define MYSQL_VERSION_PATCH 7 -#define MYSQL_VERSION_EXTRA "" - -#define PACKAGE "mysql" -#define PACKAGE_BUGREPORT "" -#define PACKAGE_NAME "MySQL Server" -#define PACKAGE_STRING "MySQL Server 10.5.7" -#define PACKAGE_TARNAME "mysql" -#define PACKAGE_VERSION "10.5.7" -#define VERSION "10.5.7" -#define PROTOCOL_VERSION 10 -#define PCRE2_CODE_UNIT_WIDTH 8 - -#define MALLOC_LIBRARY "system" - -/* time_t related defines */ - -#define SIZEOF_TIME_T 8 -#define TIME_T_UNSIGNED 1 - -#ifndef EMBEDDED_LIBRARY -/* #undef WSREP_INTERFACE_VERSION */ -/* #undef WITH_WSREP */ -/* #undef WSREP_PROC_INFO */ -#endif - -#if !defined(__STDC_FORMAT_MACROS) -#define __STDC_FORMAT_MACROS -#endif // !defined(__STDC_FORMAT_MACROS) - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_dbug.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_dbug.h deleted file mode 100644 index fa5b4c1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_dbug.h +++ /dev/null @@ -1,248 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. - Copyright (C) 2000, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_dbug_h -#define _my_dbug_h - -#ifndef __WIN__ -#include -#endif /* not __WIN__ */ - -#ifdef __cplusplus -extern "C" { -#endif -#if !defined(DBUG_OFF) && !defined(_lint) - -struct _db_stack_frame_ { - const char *func; /* function name of the previous stack frame */ - const char *file; /* filename of the function of previous frame */ - uint level; /* this nesting level, highest bit enables tracing */ - int line; /* line of DBUG_RETURN */ - struct _db_stack_frame_ *prev; /* pointer to the previous frame */ -}; - -struct _db_code_state_; -extern my_bool _dbug_on_; -extern my_bool _db_keyword_(struct _db_code_state_ *, const char *, int); -extern int _db_explain_(struct _db_code_state_ *cs, char *buf, size_t len); -extern int _db_explain_init_(char *buf, size_t len); -extern int _db_is_pushed_(void); -extern void _db_setjmp_(void); -extern void _db_longjmp_(void); -extern void _db_process_(const char *name); -extern void _db_push_(const char *control); -extern void _db_pop_(void); -extern void _db_set_(const char *control); -extern void _db_set_init_(const char *control); -extern void _db_enter_(const char *_func_, const char *_file_, uint _line_, - struct _db_stack_frame_ *_stack_frame_); -extern void _db_return_(struct _db_stack_frame_ *_stack_frame_); -extern int _db_pargs_(uint _line_,const char *keyword); -extern void _db_doprnt_(const char *format,...) -#ifdef WAITING_FOR_BUGFIX_TO_VSPRINTF - ATTRIBUTE_FORMAT(printf, 1, 2) -#endif - ; -extern void _db_dump_(uint _line_,const char *keyword, - const unsigned char *memory, size_t length); -extern void _db_end_(void); -extern void _db_lock_file_(void); -extern void _db_unlock_file_(void); -ATTRIBUTE_COLD -extern my_bool _db_my_assert(const char *file, int line, const char *msg); -extern FILE *_db_fp_(void); -extern void _db_flush_(void); -extern void dbug_swap_code_state(void **code_state_store); -extern void dbug_free_code_state(void **code_state_store); -extern const char* _db_get_func_(void); -extern int (*dbug_sanity)(void); - -#ifdef DBUG_TRACE -#define DBUG_LEAVE do { \ - _db_stack_frame_.line= __LINE__; \ - _db_return_ (&_db_stack_frame_); \ - _db_stack_frame_.line= 0; \ - } while(0) - -#ifdef HAVE_ATTRIBUTE_CLEANUP -#define DBUG_ENTER(a) struct _db_stack_frame_ _db_stack_frame_ __attribute__((cleanup(_db_return_))); \ - _db_enter_ (a,__FILE__,__LINE__,&_db_stack_frame_) -#define DBUG_RETURN(a1) do { _db_stack_frame_.line=__LINE__; return(a1);} while(0) -#define DBUG_VOID_RETURN do { _db_stack_frame_.line=__LINE__; return;} while(0) -#else -#define DBUG_ENTER(a) struct _db_stack_frame_ _db_stack_frame_; \ - _db_enter_ (a,__FILE__,__LINE__,&_db_stack_frame_) -#define DBUG_RETURN(a1) do {DBUG_LEAVE; return(a1);} while(0) -#define DBUG_VOID_RETURN do {DBUG_LEAVE; return;} while(0) -#endif - -#else -#define DBUG_LEAVE -#define DBUG_ENTER(a) -#define DBUG_RETURN(a1) return(a1) -#define DBUG_VOID_RETURN return -#endif - -#define DBUG_EXECUTE(keyword,a1) \ - do {if (_db_keyword_(0, (keyword), 0)) { a1 }} while(0) -#define DBUG_EXECUTE_IF(keyword,a1) \ - do {if (_db_keyword_(0, (keyword), 1)) { a1 }} while(0) -#define DBUG_EVALUATE(keyword,a1,a2) \ - (_db_keyword_(0,(keyword), 0) ? (a1) : (a2)) -#define DBUG_EVALUATE_IF(keyword,a1,a2) \ - (_db_keyword_(0,(keyword), 1) ? (a1) : (a2)) -#define DBUG_PRINT(keyword,arglist) \ - do if (_db_pargs_(__LINE__,keyword)) _db_doprnt_ arglist; while(0) - -#define DBUG_PUSH_EMPTY if (_dbug_on_) { DBUG_PUSH(""); } -#define DBUG_POP_EMPTY if (_dbug_on_) { DBUG_POP(); } -#define DBUG_PUSH(a1) _db_push_ (a1) -#define DBUG_POP() _db_pop_ () -#define DBUG_SET(a1) _db_set_ (a1) -#define DBUG_SET_INITIAL(a1) _db_set_init_ (a1) -#define DBUG_PROCESS(a1) _db_process_(a1) -#define DBUG_FILE _db_fp_() -#define DBUG_DUMP(keyword,a1,a2) _db_dump_(__LINE__,keyword,a1,a2) -#define DBUG_END() _db_end_ () -#define DBUG_LOCK_FILE _db_lock_file_() -#define DBUG_UNLOCK_FILE _db_unlock_file_() -#define DBUG_ASSERT(A) do { \ - if (unlikely(!(A)) && _db_my_assert(__FILE__, __LINE__, #A)) assert(A); \ -} while (0) -#define DBUG_SLOW_ASSERT(A) DBUG_ASSERT(A) -#define DBUG_ASSERT_EXISTS -#define DBUG_EXPLAIN(buf,len) _db_explain_(0, (buf),(len)) -#define DBUG_EXPLAIN_INITIAL(buf,len) _db_explain_init_((buf),(len)) -#define DEBUGGER_OFF do { _dbug_on_= 0; } while(0) -#define DEBUGGER_ON do { _dbug_on_= 1; } while(0) -#define IF_DBUG(A,B) A -#define IF_DBUG_ASSERT(A,B) A -#define DBUG_SWAP_CODE_STATE(arg) dbug_swap_code_state(arg) -#define DBUG_FREE_CODE_STATE(arg) dbug_free_code_state(arg) -#undef DBUG_ASSERT_AS_PRINTF - -#ifndef __WIN__ -#define DBUG_ABORT() (_db_flush_(), abort()) -#else -/* - Avoid popup with abort/retry/ignore buttons. When BUG#31745 is fixed we can - call abort() instead of _exit(3) (now it would cause a "test signal" popup). -*/ -#include -#define DBUG_ABORT() (_db_flush_(),\ - (void)_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE),\ - (void)_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR),\ - TerminateProcess(GetCurrentProcess(),3)) -#endif - -/* - Make the program fail, without creating a core file. - abort() will send SIGABRT which (most likely) generates core. - Use SIGKILL instead, which cannot be caught. - We also pause the current thread, until the signal is actually delivered. - An alternative would be to use _exit(EXIT_FAILURE), - but then valgrind would report lots of memory leaks. - */ -#ifdef __WIN__ -#define DBUG_SUICIDE() DBUG_ABORT() -#else -extern void _db_suicide_(void); -#define DBUG_SUICIDE() (_db_flush_(), _db_suicide_()) -#endif /* __WIN__ */ - -#else /* No debugger */ - -#define DBUG_ENTER(a1) -#define DBUG_VIOLATION_HELPER_LEAVE do { } while(0) -#define DBUG_LEAVE -#define DBUG_RETURN(a1) do { return(a1); } while(0) -#define DBUG_VOID_RETURN do { return; } while(0) -#define DBUG_EXECUTE(keyword,a1) do { } while(0) -#define DBUG_EXECUTE_IF(keyword,a1) do { } while(0) -#define DBUG_EVALUATE(keyword,a1,a2) (a2) -#define DBUG_EVALUATE_IF(keyword,a1,a2) (a2) -#define DBUG_PRINT(keyword,arglist) do { } while(0) -#define DBUG_PUSH_EMPTY do { } while(0) -#define DBUG_POP_EMPTY do { } while(0) -#define DBUG_PUSH(a1) do { } while(0) -#define DBUG_SET(a1) do { } while(0) -#define DBUG_SET_INITIAL(a1) do { } while(0) -#define DBUG_POP() do { } while(0) -#define DBUG_PROCESS(a1) do { } while(0) -#define DBUG_DUMP(keyword,a1,a2) do { } while(0) -#define DBUG_END() do { } while(0) -#define DBUG_SLOW_ASSERT(A) do { } while(0) -#define DBUG_LOCK_FILE do { } while(0) -#define DBUG_FILE (stderr) -#define DBUG_UNLOCK_FILE do { } while(0) -#define DBUG_EXPLAIN(buf,len) -#define DBUG_EXPLAIN_INITIAL(buf,len) -#define DEBUGGER_OFF do { } while(0) -#define DEBUGGER_ON do { } while(0) -#define IF_DBUG(A,B) B -#define DBUG_SWAP_CODE_STATE(arg) do { } while(0) -#define DBUG_FREE_CODE_STATE(arg) do { } while(0) -#define DBUG_ABORT() do { } while(0) -#define DBUG_CRASH_ENTER(func) -#define DBUG_CRASH_RETURN(val) do { return(val); } while(0) -#define DBUG_CRASH_VOID_RETURN do { return; } while(0) -#define DBUG_SUICIDE() do { } while(0) - -#ifdef DBUG_ASSERT_AS_PRINTF -extern void (*my_dbug_assert_failed)(const char *assert_expr, const char* file, unsigned long line); -#define DBUG_ASSERT(assert_expr) do { if (!(assert_expr)) { my_dbug_assert_failed(#assert_expr, __FILE__, __LINE__); }} while (0) -#define DBUG_ASSERT_EXISTS -#define IF_DBUG_ASSERT(A,B) A -#else -#define DBUG_ASSERT(A) do { } while(0) -#define IF_DBUG_ASSERT(A,B) B -#endif /* DBUG_ASSERT_AS_PRINTF */ -#endif /* !defined(DBUG_OFF) && !defined(_lint) */ - -#ifdef EXTRA_DEBUG -/** - Sync points allow us to force the server to reach a certain line of code - and block there until the client tells the server it is ok to go on. - The client tells the server to block with SELECT GET_LOCK() - and unblocks it with SELECT RELEASE_LOCK(). Used for debugging difficult - concurrency problems -*/ -#define DBUG_SYNC_POINT(lock_name,lock_timeout) \ - debug_sync_point(lock_name,lock_timeout) -void debug_sync_point(const char* lock_name, uint lock_timeout); -#else -#define DBUG_SYNC_POINT(lock_name,lock_timeout) -#endif /* EXTRA_DEBUG */ - -#ifdef __cplusplus -} -/* - DBUG_LOG() was initially intended for InnoDB. To be able to use it elsewhere - one should #include . We intentionally avoid including it here to save - compilation time. -*/ -# ifdef DBUG_OFF -# define DBUG_LOG(keyword, v) do {} while (0) -# else -# define DBUG_LOG(keyword, v) do { \ - if (_db_pargs_(__LINE__, keyword)) { \ - std::ostringstream _db_s; _db_s << v; \ - _db_doprnt_("%s", _db_s.str().c_str()); \ - }} while (0) -# endif -#endif - -#endif /* _my_dbug_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_decimal_limits.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_decimal_limits.h deleted file mode 100644 index ac1df83..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_decimal_limits.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef MY_DECIMAL_LIMITS_INCLUDED -#define MY_DECIMAL_LIMITS_INCLUDED -/* Copyright (c) 2011 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#define DECIMAL_LONGLONG_DIGITS 22 -#define DECIMAL_LONG_DIGITS 10 -#define DECIMAL_LONG3_DIGITS 8 - -/** maximum length of buffer in our big digits (uint32). */ -#define DECIMAL_BUFF_LENGTH 9 - -/* the number of digits that my_decimal can possibly contain */ -#define DECIMAL_MAX_POSSIBLE_PRECISION (DECIMAL_BUFF_LENGTH * 9) - - -/** - maximum guaranteed precision of number in decimal digits (number of our - digits * number of decimal digits in one our big digit - number of decimal - digits in one our big digit decreased by 1 (because we always put decimal - point on the border of our big digits)) - - With normal precession we can handle 65 digits. MariaDB can store in - the .frm up to 63 digits. By default we use DECIMAL_NOT_SPECIFIED digits - when converting strings to decimal, so we don't want to set this too high. - To not use up all digits for the scale we limit the number of decimals to - 38. -*/ -#define DECIMAL_MAX_PRECISION (DECIMAL_MAX_POSSIBLE_PRECISION - 8*2) -#define DECIMAL_MAX_SCALE 38 -#define DECIMAL_NOT_SPECIFIED 39 - -/** - maximum length of string representation (number of maximum decimal - digits + 1 position for sign + 1 position for decimal point, no terminator) -*/ -#define DECIMAL_MAX_STR_LENGTH (DECIMAL_MAX_POSSIBLE_PRECISION + 2) - -#endif /* MY_DECIMAL_LIMITS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_dir.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_dir.h deleted file mode 100644 index 930d54c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_dir.h +++ /dev/null @@ -1,116 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MY_DIR_H -#define MY_DIR_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - /* Defines for my_dir and my_stat */ - -#define MY_S_IFMT S_IFMT /* type of file */ -#define MY_S_IFDIR S_IFDIR /* directory */ -#define MY_S_IFCHR S_IFCHR /* character special */ -#define MY_S_IFBLK S_IFBLK /* block special */ -#define MY_S_IFREG S_IFREG /* regular */ -#define MY_S_IFIFO S_IFIFO /* fifo */ -#define MY_S_ISUID S_ISUID /* set user id on execution */ -#define MY_S_ISGID S_ISGID /* set group id on execution */ -#define MY_S_ISVTX S_ISVTX /* save swapped text even after use */ - -#ifndef S_IREAD -#define MY_S_IREAD S_IRUSR /* read permission, owner */ -#define MY_S_IWRITE S_IWUSR /* write permission, owner */ -#define MY_S_IEXEC S_IXUSR /* execute/search permission, owner */ -#else -#define MY_S_IREAD S_IREAD /* read permission, owner */ -#define MY_S_IWRITE S_IWRITE /* write permission, owner */ -#define MY_S_IEXEC S_IEXEC /* execute/search permission, owner */ -#endif - -#define MY_S_ISDIR(m) (((m) & MY_S_IFMT) == MY_S_IFDIR) -#define MY_S_ISCHR(m) (((m) & MY_S_IFMT) == MY_S_IFCHR) -#define MY_S_ISBLK(m) (((m) & MY_S_IFMT) == MY_S_IFBLK) -#define MY_S_ISREG(m) (((m) & MY_S_IFMT) == MY_S_IFREG) -#define MY_S_ISFIFO(m) (((m) & MY_S_IFMT) == MY_S_IFIFO) - -/* Ensure these doesn't clash with anything in my_sys.h */ -#define MY_WANT_SORT 8192 /* my_lib; sort files */ -#define MY_WANT_STAT 16384 /* my_lib; stat files */ -#define MY_DONT_SORT 0 - - /* typedefs for my_dir & my_stat */ - -#ifdef USE_MY_STAT_STRUCT - -typedef struct my_stat -{ - dev_t st_dev; /* major & minor device numbers */ - ino_t st_ino; /* inode number */ - ushort st_mode; /* file permissions (& suid sgid .. bits) */ - short st_nlink; /* number of links to file */ - ushort st_uid; /* user id */ - ushort st_gid; /* group id */ - dev_t st_rdev; /* more major & minor device numbers (???) */ - off_t st_size; /* size of file */ - time_t st_atime; /* time for last read */ - time_t st_mtime; /* time for last contens modify */ - time_t st_ctime; /* time for last inode or contents modify */ -} MY_STAT; - -#else - -#if defined(_MSC_VER) -#define MY_STAT struct _stati64 /* 64 bit file size */ -#else -#define MY_STAT struct stat /* Original struct has what we need */ -#endif - -#endif /* USE_MY_STAT_STRUCT */ - -/* Struct describing one file returned from my_dir */ -typedef struct fileinfo -{ - char *name; - MY_STAT *mystat; -} FILEINFO; - -typedef struct st_my_dir /* Struct returned from my_dir */ -{ - /* - These members are just copies of parts of DYNAMIC_ARRAY structure, - which is allocated right after the end of MY_DIR structure (MEM_ROOT - for storing names is also resides there). We've left them here because - we don't want to change code that uses my_dir. - */ - struct fileinfo *dir_entry; - uint number_of_files; -} MY_DIR; - -extern MY_DIR *my_dir(const char *path,myf MyFlags); -extern void my_dirend(MY_DIR *buffer); -extern MY_STAT *my_stat(const char *path, MY_STAT *stat_area, myf my_flags); -extern int my_fstat(int filenr, MY_STAT *stat_area, myf MyFlags); - -#ifdef __cplusplus -} -#endif - -#endif /* MY_DIR_H */ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_getopt.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_getopt.h deleted file mode 100644 index 642fb34..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_getopt.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - Copyright (c) 2002, 2013, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_getopt_h -#define _my_getopt_h - -#include "my_sys.h" /* loglevel */ -/* my_getopt and my_default are almost always used together */ -#include - -C_MODE_START - -#define GET_NO_ARG 1 -#define GET_BOOL 2 -#define GET_INT 3 -#define GET_UINT 4 -#define GET_LONG 5 -#define GET_ULONG 6 -#define GET_LL 7 -#define GET_ULL 8 -#define GET_STR 9 -#define GET_STR_ALLOC 10 -#define GET_DISABLED 11 -#define GET_ENUM 12 -#define GET_SET 13 -#define GET_DOUBLE 14 -#define GET_FLAGSET 15 -#define GET_BIT 16 - -#define GET_ASK_ADDR 128 -#define GET_AUTO 64 -#define GET_TYPE_MASK 63 - -/** - Enumeration of the my_option::arg_type attributes. - It should be noted that for historical reasons variables with the combination - arg_type=NO_ARG, my_option::var_type=GET_BOOL still accepts - arguments. This is someone counter intuitive and care should be taken - if the code is refactored. -*/ -enum get_opt_arg_type { NO_ARG, OPT_ARG, REQUIRED_ARG }; - -struct st_typelib; - -struct my_option -{ - const char *name; /**< Name of the option. name=NULL - marks the end of the my_option[] - array. - */ - int id; /**< For 0255 no short option - is created, but a long option still - can be identified uniquely in the - my_get_one_option() callback. - If an opton needs neither special - treatment in the my_get_one_option() - nor one-letter short equivalent - use id=0 - */ - const char *comment; /**< option comment, for autom. --help. - if it's NULL the option is not - visible in --help. - */ - void *value; /**< A pointer to the variable value */ - void *u_max_value; /**< The user def. max variable value */ - struct st_typelib *typelib; /**< Pointer to possible values */ - ulong var_type; /**< GET_BOOL, GET_ULL, etc */ - enum get_opt_arg_type arg_type; /**< e.g. REQUIRED_ARG or OPT_ARG */ - longlong def_value; /**< Default value */ - longlong min_value; /**< Min allowed value (for numbers) */ - ulonglong max_value; /**< Max allowed value (for numbers) */ - longlong sub_size; /**< Unused */ - long block_size; /**< Value should be a mult. of this (for numbers) */ - void *app_type; /**< To be used by an application */ -}; - -typedef my_bool (*my_get_one_option)(const struct my_option *, char *, const char *); - -/** - Used to retrieve a reference to the object (variable) that holds the value - for the given option. For example, if var_type is GET_UINT, the function - must return a pointer to a variable of type uint. A argument is stored in - the location pointed to by the returned pointer. -*/ -typedef void *(*my_getopt_value)(const char *, uint, const struct my_option *, - int *); - - -extern char *disabled_my_option; -extern char *autoset_my_option; -extern my_bool my_getopt_print_errors; -extern my_bool my_getopt_skip_unknown; -extern my_bool my_getopt_prefix_matching; -extern my_bool my_handle_options_init_variables; -extern my_error_reporter my_getopt_error_reporter; -extern my_getopt_value my_getopt_get_addr; - -extern int handle_options (int *argc, char ***argv, - const struct my_option *longopts, my_get_one_option) - __attribute__((nonnull)); -extern void my_cleanup_options(const struct my_option *options); -extern void my_print_help(const struct my_option *options); -extern void my_print_variables(const struct my_option *options); - -ulonglong getopt_ull_limit_value(ulonglong num, const struct my_option *optp, - my_bool *fix); -longlong getopt_ll_limit_value(longlong, const struct my_option *, - my_bool *fix); -double getopt_double_limit_value(double num, const struct my_option *optp, - my_bool *fix); - -ulonglong getopt_double2ulonglong(double); -double getopt_ulonglong2double(ulonglong); - -C_MODE_END - -#endif /* _my_getopt_h */ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_global.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_global.h deleted file mode 100644 index 86ef5f8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_global.h +++ /dev/null @@ -1,1232 +0,0 @@ -/* - Copyright (c) 2001, 2013, Oracle and/or its affiliates. - Copyright (c) 2009, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* This is the include file that should be included 'first' in every C file. */ - -#ifndef MY_GLOBAL_INCLUDED -#define MY_GLOBAL_INCLUDED - -/* Client library users on Windows need this macro defined here. */ -#if !defined(__WIN__) && defined(_WIN32) -#define __WIN__ -#endif - -/* - InnoDB depends on some MySQL internals which other plugins should not - need. This is because of InnoDB's foreign key support, "safe" binlog - truncation, and other similar legacy features. - - We define accessors for these internals unconditionally, but do not - expose them in mysql/plugin.h. They are declared in ha_innodb.h for - InnoDB's use. -*/ -#define INNODB_COMPATIBILITY_HOOKS - -#ifdef __CYGWIN__ -/* We use a Unix API, so pretend it's not Windows */ -#undef WIN -#undef WIN32 -#undef _WIN -#undef _WIN32 -#undef _WIN64 -#undef __WIN__ -#undef __WIN32__ -#define HAVE_ERRNO_AS_DEFINE -#define _POSIX_MONOTONIC_CLOCK -#define _POSIX_THREAD_CPUTIME -#endif /* __CYGWIN__ */ - -#if defined(__OpenBSD__) && (OpenBSD >= 200411) -#define HAVE_ERRNO_AS_DEFINE -#endif - -#if defined(i386) && !defined(__i386__) -#define __i386__ -#endif - -/* Macros to make switching between C and C++ mode easier */ -#ifdef __cplusplus -#define C_MODE_START extern "C" { -#define C_MODE_END } -#else -#define C_MODE_START -#define C_MODE_END -#endif - -#ifdef __cplusplus -#define CPP_UNNAMED_NS_START namespace { -#define CPP_UNNAMED_NS_END } -#endif - -#include - -#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE -#define HAVE_PSI_INTERFACE -#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */ - -/* Make it easier to add conditional code in _expressions_ */ -#ifdef __WIN__ -#define IF_WIN(A,B) A -#else -#define IF_WIN(A,B) B -#endif - -#ifdef EMBEDDED_LIBRARY -#define IF_EMBEDDED(A,B) A -#else -#define IF_EMBEDDED(A,B) B -#endif - -#ifdef WITH_PARTITION_STORAGE_ENGINE -#define IF_PARTITIONING(A,B) A -#else -#define IF_PARTITIONING(A,B) B -#endif - -#if defined (_WIN32) -/* - off_t is 32 bit long. We do not use C runtime functions - with off_t but native Win32 file IO APIs, that work with - 64 bit offsets. -*/ -#undef SIZEOF_OFF_T -#define SIZEOF_OFF_T 8 - -/* - Prevent inclusion of Windows GDI headers - they define symbol - ERROR that conflicts with mysql headers. -*/ -#ifndef NOGDI -#define NOGDI -#endif - -/* Include common headers.*/ -#include -#include /* SOCKET */ -#include /* access(), chmod() */ -#include /* getpid() */ - -#define sleep(a) Sleep((a)*1000) - -/* Define missing access() modes. */ -#define F_OK 0 -#define W_OK 2 -#define R_OK 4 /* Test for read permission. */ - -/* Define missing file locking constants. */ -#define F_RDLCK 1 -#define F_WRLCK 2 -#define F_UNLCK 3 -#define F_TO_EOF 0x3FFFFFFF - -#endif /* _WIN32*/ - - -/* Workaround for _LARGE_FILES and _LARGE_FILE_API incompatibility on AIX */ -#if defined(_AIX) && defined(_LARGE_FILE_API) -#undef _LARGE_FILE_API -#undef __GNUG__ -#endif - -/* - The macros below are used to allow build of Universal/fat binaries of - MySQL and MySQL applications under darwin. -*/ -#if defined(__APPLE__) && defined(__MACH__) -# undef SIZEOF_CHARP -# undef SIZEOF_INT -# undef SIZEOF_LONG -# undef SIZEOF_LONG_LONG -# undef SIZEOF_OFF_T -# undef WORDS_BIGENDIAN -# define SIZEOF_INT 4 -# define SIZEOF_LONG_LONG 8 -# define SIZEOF_OFF_T 8 -# if defined(__i386__) || defined(__ppc__) -# define SIZEOF_CHARP 4 -# define SIZEOF_LONG 4 -# elif defined(__x86_64__) || defined(__ppc64__) -# define SIZEOF_CHARP 8 -# define SIZEOF_LONG 8 -# else -# error Building FAT binary for an unknown architecture. -# endif -# if defined(__ppc__) || defined(__ppc64__) -# define WORDS_BIGENDIAN -# endif -#endif /* defined(__APPLE__) && defined(__MACH__) */ - - -/* - The macros below are borrowed from include/linux/compiler.h in the - Linux kernel. Use them to indicate the likelihood of the truthfulness - of a condition. This serves two purposes - newer versions of gcc will be - able to optimize for branch predication, which could yield siginficant - performance gains in frequently executed sections of the code, and the - other reason to use them is for documentation -*/ - -#if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96) -#define __builtin_expect(x, expected_value) (x) -#endif - -/* Fix problem with S_ISLNK() on Linux */ -#if defined(TARGET_OS_LINUX) || defined(__GLIBC__) -#undef _GNU_SOURCE -#define _GNU_SOURCE 1 -#endif - -/* - Temporary solution to solve bug#7156. Include "sys/types.h" before - the thread headers, else the function madvise() will not be defined -*/ -#if defined(HAVE_SYS_TYPES_H) && ( defined(sun) || defined(__sun) ) -#include -#endif - -#define __EXTENSIONS__ 1 /* We want some extension */ -#ifndef __STDC_EXT__ -#define __STDC_EXT__ 1 /* To get large file support on hpux */ -#endif - -/* - Solaris 9 include file refers to X/Open document - - System Interfaces and Headers, Issue 5 - - saying we should define _XOPEN_SOURCE=500 to get POSIX.1c prototypes, - but apparently other systems (namely FreeBSD) don't agree. - - On a newer Solaris 10, the above file recognizes also _XOPEN_SOURCE=600. - Furthermore, it tests that if a program requires older standard - (_XOPEN_SOURCE<600 or _POSIX_C_SOURCE<200112L) it cannot be - run on a new compiler (that defines _STDC_C99) and issues an #error. - It's also an #error if a program requires new standard (_XOPEN_SOURCE=600 - or _POSIX_C_SOURCE=200112L) and a compiler does not define _STDC_C99. - - To add more to this mess, Sun Studio C compiler defines _STDC_C99 while - C++ compiler does not! - - So, in a desperate attempt to get correct prototypes for both - C and C++ code, we define either _XOPEN_SOURCE=600 or _XOPEN_SOURCE=500 - depending on the compiler's announced C standard support. - - Cleaner solutions are welcome. -*/ -#ifdef __sun -#if __STDC_VERSION__ - 0 >= 199901L -#define _XOPEN_SOURCE 600 -#else -#define _XOPEN_SOURCE 500 -#endif -#endif - - -#ifdef _AIX -/* - AIX includes inttypes.h from sys/types.h - Explicitly request format macros before the first inclusion of inttypes.h -*/ -#if !defined(__STDC_FORMAT_MACROS) -#define __STDC_FORMAT_MACROS -#endif // !defined(__STDC_FORMAT_MACROS) -#endif - - -#if !defined(__WIN__) -#ifndef _POSIX_PTHREAD_SEMANTICS -#define _POSIX_PTHREAD_SEMANTICS /* We want posix threads */ -#endif - -#if !defined(SCO) -#define _REENTRANT 1 /* Some thread libraries require this */ -#endif -#if !defined(_THREAD_SAFE) && !defined(_AIX) -#define _THREAD_SAFE /* Required for OSF1 */ -#endif -#if defined(HPUX10) || defined(HPUX11) -C_MODE_START /* HPUX needs this, signal.h bug */ -#include -C_MODE_END -#else -#include /* AIX must have this included first */ -#endif -#if !defined(SCO) && !defined(_REENTRANT) -#define _REENTRANT 1 /* Threads requires reentrant code */ -#endif -#endif /* !defined(__WIN__) */ - -/* Go around some bugs in different OS and compilers */ -#ifdef _AIX /* By soren@t.dk */ -#define _H_STRINGS -#define _SYS_STREAM_H -/* #define _AIX32_CURSES */ /* XXX: this breaks AIX 4.3.3 (others?). */ -#define ulonglong2double(A) my_ulonglong2double(A) -#define my_off_t2double(A) my_ulonglong2double(A) -C_MODE_START -inline double my_ulonglong2double(unsigned long long A) { return (double)A; } -C_MODE_END -#endif /* _AIX */ - -#ifdef UNDEF_HAVE_INITGROUPS /* For AIX 4.3 */ -#undef HAVE_INITGROUPS -#endif - -/* gcc/egcs issues */ - -#if defined(__GNUC) && defined(__EXCEPTIONS) -#error "Please add -fno-exceptions to CXXFLAGS and reconfigure/recompile" -#endif - -#if defined(_lint) && !defined(lint) -#define lint -#endif -#if SIZEOF_LONG_LONG > 4 && !defined(_LONG_LONG) -#define _LONG_LONG 1 /* For AIX string library */ -#endif - -/* Workaround for _LARGE_FILES and _LARGE_FILE_API incompatibility on AIX */ -#if defined(_AIX) && defined(_LARGE_FILE_API) -#undef _LARGE_FILE_API -#undef __GNUG__ -#endif - - -#ifndef stdin -#include -#endif -#include -#ifdef HAVE_STDLIB_H -#include -#endif -#ifdef HAVE_STDDEF_H -#include -#endif - -#include -#ifdef HAVE_LIMITS_H -#include -#endif -#ifdef HAVE_FLOAT_H -#include -#endif -#ifdef HAVE_FENV_H -#include /* For fesetround() */ -#endif - -#ifdef HAVE_SYS_TYPES_H -#include -#endif - -/* Workaround for _LARGE_FILES and _LARGE_FILE_API incompatibility on AIX */ -#if defined(_AIX) && defined(_LARGE_FILE_API) -#undef _LARGE_FILE_API -#undef __GNUG__ -#endif - - -#ifdef HAVE_FCNTL_H -#include -#endif -#ifdef HAVE_SYS_STAT_H -#include -#endif -#if TIME_WITH_SYS_TIME -# include -# include -#else -# if HAVE_SYS_TIME_H -# include -# else -# include -# endif -#endif /* TIME_WITH_SYS_TIME */ -#ifdef HAVE_UNISTD_H -#include -#endif -#if defined(__cplusplus) && defined(NO_CPLUSPLUS_ALLOCA) -#undef HAVE_ALLOCA -#undef HAVE_ALLOCA_H -#endif -#ifdef HAVE_ALLOCA_H -#include -#endif - -#include /* Recommended by debian */ -/* We need the following to go around a problem with openssl on solaris */ -#if defined(HAVE_CRYPT_H) -#include -#endif - -/* Add checking if we are using likely/unlikely wrong */ -#ifdef CHECK_UNLIKELY -C_MODE_START -extern void init_my_likely(), end_my_likely(FILE *); -extern int my_likely_ok(const char *file_name, uint line); -extern int my_likely_fail(const char *file_name, uint line); -C_MODE_END - -#define likely(A) ((A) ? (my_likely_ok(__FILE__, __LINE__),1) : (my_likely_fail(__FILE__, __LINE__), 0)) -#define unlikely(A) ((A) ? (my_likely_fail(__FILE__, __LINE__),1) : (my_likely_ok(__FILE__, __LINE__), 0)) -/* - These macros should be used when the check fails often when running benchmarks but - we know for sure that the check is correct in a production environment -*/ -#define checked_likely(A) (A) -#define checked_unlikely(A) (A) -#else -/** - The semantics of builtin_expect() are that - 1) its two arguments are long - 2) it's likely that they are == - Those of our likely(x) are that x can be bool/int/longlong/pointer. -*/ - -#define likely(x) __builtin_expect(((x) != 0),1) -#define unlikely(x) __builtin_expect(((x) != 0),0) -#define checked_likely(x) likely(x) -#define checked_unlikely(x) unlikely(x) -#endif /* CHECK_UNLIKELY */ - -/* - A lot of our programs uses asserts, so better to always include it - This also fixes a problem when people uses DBUG_ASSERT without including - assert.h -*/ -#include - -/* an assert that works at compile-time. only for constant expression */ -#ifdef _some_old_compiler_that_does_not_understand_the_construct_below_ -#define compile_time_assert(X) do { } while(0) -#else -#define compile_time_assert(X) \ - do \ - { \ - typedef char compile_time_assert[(X) ? 1 : -1] __attribute__((unused)); \ - } while(0) -#endif - -/* Go around some bugs in different OS and compilers */ -#if defined (HPUX11) && defined(_LARGEFILE_SOURCE) -#ifndef _LARGEFILE64_SOURCE -#define _LARGEFILE64_SOURCE -#endif -#endif - -#if defined(_HPUX_SOURCE) && defined(HAVE_SYS_STREAM_H) -#include /* HPUX 10.20 defines ulong here. UGLY !!! */ -#define HAVE_ULONG -#endif -#if defined(HPUX10) && defined(_LARGEFILE64_SOURCE) -/* Fix bug in setrlimit */ -#undef setrlimit -#define setrlimit cma_setrlimit64 -#endif -/* Declare madvise where it is not declared for C++, like Solaris */ -#if HAVE_MADVISE && !HAVE_DECL_MADVISE && defined(__cplusplus) -extern "C" int madvise(void *addr, size_t len, int behav); -#endif -#ifdef HAVE_SYS_MMAN_H -#include -#endif -/** FreeBSD equivalent */ -#if defined(MADV_CORE) && !defined(MADV_DODUMP) -#define MADV_DODUMP MADV_CORE -#define MADV_DONTDUMP MADV_NOCORE -#define DODUMP_STR "MADV_CORE" -#define DONTDUMP_STR "MADV_NOCORE" -#else -#define DODUMP_STR "MADV_DODUMP" -#define DONTDUMP_STR "MADV_DONTDUMP" -#endif - - -#define QUOTE_ARG(x) #x /* Quote argument (before cpp) */ -#define STRINGIFY_ARG(x) QUOTE_ARG(x) /* Quote argument, after cpp */ - -/* Paranoid settings. Define I_AM_PARANOID if you are paranoid */ -#ifdef I_AM_PARANOID -#define DONT_ALLOW_USER_CHANGE 1 -#define DONT_USE_MYSQL_PWD 1 -#endif - -/* Does the system remember a signal handler after a signal ? */ -#if !defined(HAVE_BSD_SIGNALS) && !defined(HAVE_SIGACTION) -#define SIGNAL_HANDLER_RESET_ON_DELIVERY -#endif - -/* don't assume that STDERR_FILENO is 2, mysqld can freopen */ -#undef STDERR_FILENO - -#ifndef SO_EXT -#ifdef _WIN32 -#define SO_EXT ".dll" -#else -#define SO_EXT ".so" -#endif -#endif - -/* - Suppress uninitialized variable warning without generating code. -*/ -#if defined(__GNUC__) -/* GCC specific self-initialization which inhibits the warning. */ -#define UNINIT_VAR(x) x= x -#elif defined(_lint) || defined(FORCE_INIT_OF_VARS) -#define UNINIT_VAR(x) x= 0 -#else -#define UNINIT_VAR(x) x -#endif - -/* This is only to be used when resetting variables in a class constructor */ -#if defined(_lint) || defined(FORCE_INIT_OF_VARS) -#define LINT_INIT(x) x= 0 -#else -#define LINT_INIT(x) -#endif - -#if !defined(HAVE_UINT) -#undef HAVE_UINT -#define HAVE_UINT -typedef unsigned int uint; -typedef unsigned short ushort; -#endif - -#define swap_variables(t, a, b) do { t dummy; dummy= a; a= b; b= dummy; } while(0) -#define MY_TEST(a) ((a) ? 1 : 0) -#define set_if_bigger(a,b) do { if ((a) < (b)) (a)=(b); } while(0) -#define set_if_smaller(a,b) do { if ((a) > (b)) (a)=(b); } while(0) -#define set_bits(type, bit_count) (sizeof(type)*8 <= (bit_count) ? ~(type) 0 : ((((type) 1) << (bit_count)) - (type) 1)) -#define test_all_bits(a,b) (((a) & (b)) == (b)) -#define array_elements(A) ((uint) (sizeof(A)/sizeof(A[0]))) - -/* Define some general constants */ -#ifndef TRUE -#define TRUE (1) /* Logical true */ -#define FALSE (0) /* Logical false */ -#endif - -#include - -/* - Wen using the embedded library, users might run into link problems, - duplicate declaration of __cxa_pure_virtual, solved by declaring it a - weak symbol. -*/ -#if defined(USE_MYSYS_NEW) && ! defined(DONT_DECLARE_CXA_PURE_VIRTUAL) -C_MODE_START -int __cxa_pure_virtual () __attribute__ ((weak)); -C_MODE_END -#endif - -/* The DBUG_ON flag always takes precedence over default DBUG_OFF */ -#if defined(DBUG_ON) && defined(DBUG_OFF) -#undef DBUG_OFF -#endif - -/* We might be forced to turn debug off, if not turned off already */ -#if (defined(FORCE_DBUG_OFF) || defined(_lint)) && !defined(DBUG_OFF) -# define DBUG_OFF -# ifdef DBUG_ON -# undef DBUG_ON -# endif -#endif - -#ifdef DBUG_OFF -#undef EXTRA_DEBUG -#endif - -/* Some types that is different between systems */ - -typedef int File; /* File descriptor */ -#ifdef _WIN32 -typedef SOCKET my_socket; -#else -typedef int my_socket; /* File descriptor for sockets */ -#define INVALID_SOCKET -1 -#endif -/* Type for functions that handles signals */ -#define sig_handler RETSIGTYPE -#if defined(__GNUC__) && !defined(_lint) -typedef char pchar; /* Mixed prototypes can take char */ -typedef char puchar; /* Mixed prototypes can take char */ -typedef char pbool; /* Mixed prototypes can take char */ -typedef short pshort; /* Mixed prototypes can take short int */ -typedef float pfloat; /* Mixed prototypes can take float */ -#else -typedef int pchar; /* Mixed prototypes can't take char */ -typedef uint puchar; /* Mixed prototypes can't take char */ -typedef int pbool; /* Mixed prototypes can't take char */ -typedef int pshort; /* Mixed prototypes can't take short int */ -typedef double pfloat; /* Mixed prototypes can't take float */ -#endif -C_MODE_START -typedef int (*qsort_cmp)(const void *,const void *); -typedef int (*qsort_cmp2)(void*, const void *,const void *); -C_MODE_END -#define qsort_t RETQSORTTYPE /* Broken GCC can't handle typedef !!!! */ -#ifdef HAVE_SYS_SOCKET_H -#include -#endif -typedef SOCKET_SIZE_TYPE size_socket; - -#ifndef SOCKOPT_OPTLEN_TYPE -#define SOCKOPT_OPTLEN_TYPE size_socket -#endif - -/* file create flags */ - -#ifndef O_SHARE /* Probably not windows */ -#define O_SHARE 0 /* Flag to my_open for shared files */ -#ifndef O_BINARY -#define O_BINARY 0 /* Flag to my_open for binary files */ -#endif -#ifndef FILE_BINARY -#define FILE_BINARY O_BINARY /* Flag to my_fopen for binary streams */ -#endif -#ifdef HAVE_FCNTL -#define HAVE_FCNTL_LOCK -#define F_TO_EOF 0L /* Param to lockf() to lock rest of file */ -#endif -#endif /* O_SHARE */ - -#ifndef O_SEQUENTIAL -#define O_SEQUENTIAL 0 -#endif -#ifndef O_SHORT_LIVED -#define O_SHORT_LIVED 0 -#endif -#ifndef O_NOFOLLOW -#define O_NOFOLLOW 0 -#endif -#ifndef O_CLOEXEC -#define O_CLOEXEC 0 -#endif -#ifdef __GLIBC__ -#define STR_O_CLOEXEC "e" -#else -#define STR_O_CLOEXEC "" -#endif -#ifndef SOCK_CLOEXEC -#define SOCK_CLOEXEC 0 -#else -#define HAVE_SOCK_CLOEXEC -#endif - -/* additional file share flags for win32 */ -#ifdef __WIN__ -#define _SH_DENYRWD 0x110 /* deny read/write mode & delete */ -#define _SH_DENYWRD 0x120 /* deny write mode & delete */ -#define _SH_DENYRDD 0x130 /* deny read mode & delete */ -#define _SH_DENYDEL 0x140 /* deny delete only */ -#endif /* __WIN__ */ - - -/* General constants */ -#define FN_LEN 256 /* Max file name len */ -#define FN_HEADLEN 253 /* Max length of filepart of file name */ -#define FN_EXTLEN 20 /* Max length of extension (part of FN_LEN) */ -#define FN_REFLEN 512 /* Max length of full path-name */ -#define FN_EXTCHAR '.' -#define FN_HOMELIB '~' /* ~/ is used as abbrev for home dir */ -#define FN_CURLIB '.' /* ./ is used as abbrev for current dir */ -#define FN_PARENTDIR ".." /* Parent directory; Must be a string */ - -#ifdef _WIN32 -#define FN_LIBCHAR '\\' -#define FN_LIBCHAR2 '/' -#define FN_DIRSEP "/\\" /* Valid directory separators */ -#define FN_EXEEXT ".exe" -#define FN_SOEXT ".dll" -#define FN_ROOTDIR "\\" -#define FN_DEVCHAR ':' -#define FN_NETWORK_DRIVES /* Uses \\ to indicate network drives */ -#define FN_NO_CASE_SENCE /* Files are not case-sensitive */ -#else -#define FN_LIBCHAR '/' -#define FN_LIBCHAR2 '/' -#define FN_DIRSEP "/" /* Valid directory separators */ -#define FN_EXEEXT "" -#define FN_SOEXT ".so" -#define FN_ROOTDIR "/" -#endif - -/* - MY_FILE_MIN is Windows speciality and is used to quickly detect - the mismatch of CRT and mysys file IO usage on Windows at runtime. - CRT file descriptors can be in the range 0-2047, whereas descriptors returned - by my_open() will start with 2048. If a file descriptor with value less then - MY_FILE_MIN is passed to mysys IO function, chances are it stemms from - open()/fileno() and not my_open()/my_fileno. - - For Posix, mysys functions are light wrappers around libc, and MY_FILE_MIN - is logically 0. -*/ - -#ifdef _WIN32 -#define MY_FILE_MIN 2048 -#else -#define MY_FILE_MIN 0 -#endif - -/* - MY_NFILE is the default size of my_file_info array. - - It is larger on Windows, because it all file handles are stored in my_file_info - Default size is 16384 and this should be enough for most cases.If it is not - enough, --max-open-files with larger value can be used. - - For Posix , my_file_info array is only used to store filenames for - error reporting and its size is not a limitation for number of open files. -*/ -#ifdef _WIN32 -#define MY_NFILE (16384 + MY_FILE_MIN) -#else -#define MY_NFILE 64 -#endif - -#ifndef OS_FILE_LIMIT -#define OS_FILE_LIMIT UINT_MAX -#endif - -/* - Io buffer size; Must be a power of 2 and a multiple of 512. May be - smaller what the disk page size. This influences the speed of the - isam btree library. eg to big to slow. -*/ -#define IO_SIZE 4096U -/* - How much overhead does malloc have. The code often allocates - something like 1024-MALLOC_OVERHEAD bytes -*/ -#define MALLOC_OVERHEAD 8 - - /* get memory in huncs */ -#define ONCE_ALLOC_INIT (uint) 4096 - /* Typical record cache */ -#define RECORD_CACHE_SIZE (uint) (128*1024) - /* Typical key cache */ -#define KEY_CACHE_SIZE (uint) (128L*1024L*1024L) - /* Default size of a key cache block */ -#define KEY_CACHE_BLOCK_SIZE (uint) 1024 - - /* Some things that this system doesn't have */ - -#ifdef _WIN32 -#define NO_DIR_LIBRARY /* Not standard dir-library */ -#endif - -/* Some defines of functions for portability */ - -#undef remove /* Crashes MySQL on SCO 5.0.0 */ -#ifndef __WIN__ -#define closesocket(A) close(A) -#endif - -#if defined(_MSC_VER) -#if !defined(_WIN64) -inline double my_ulonglong2double(unsigned long long value) -{ - long long nr=(long long) value; - if (nr >= 0) - return (double) nr; - return (18446744073709551616.0 + (double) nr); -} -#define ulonglong2double my_ulonglong2double -#define my_off_t2double my_ulonglong2double -#endif /* _WIN64 */ -inline unsigned long long my_double2ulonglong(double d) -{ - double t= d - (double) 0x8000000000000000ULL; - - if (t >= 0) - return ((unsigned long long) t) + 0x8000000000000000ULL; - return (unsigned long long) d; -} -#define double2ulonglong my_double2ulonglong -#endif - -#ifndef ulonglong2double -#define ulonglong2double(A) ((double) (ulonglong) (A)) -#define my_off_t2double(A) ((double) (my_off_t) (A)) -#endif -#ifndef double2ulonglong -#define double2ulonglong(A) ((ulonglong) (double) (A)) -#endif - -#ifndef offsetof -#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) -#endif -#define ulong_to_double(X) ((double) (ulong) (X)) - -#ifndef STACK_DIRECTION -#error "please add -DSTACK_DIRECTION=1 or -1 to your CPPFLAGS" -#endif - -#if !defined(HAVE_STRTOK_R) -#define strtok_r(A,B,C) strtok((A),(B)) -#endif - -#if SIZEOF_LONG_LONG >= 8 -#define HAVE_LONG_LONG 1 -#else -#error WHAT? sizeof(long long) < 8 ??? -#endif - -/* - Some pre-ANSI-C99 systems like AIX 5.1 and Linux/GCC 2.95 define - ULONGLONG_MAX, LONGLONG_MIN, LONGLONG_MAX; we use them if they're defined. -*/ - -#if defined(HAVE_LONG_LONG) && !defined(LONGLONG_MIN) -#define LONGLONG_MIN ((long long) 0x8000000000000000LL) -#define LONGLONG_MAX ((long long) 0x7FFFFFFFFFFFFFFFLL) -#endif -/* Max length needed for a buffer to hold a longlong or ulonglong + end \0 */ -#define LONGLONG_BUFFER_SIZE 21 - -#if defined(HAVE_LONG_LONG) && !defined(ULONGLONG_MAX) -/* First check for ANSI C99 definition: */ -#ifdef ULLONG_MAX -#define ULONGLONG_MAX ULLONG_MAX -#else -#define ULONGLONG_MAX ((unsigned long long)(~0ULL)) -#endif -#endif /* defined (HAVE_LONG_LONG) && !defined(ULONGLONG_MAX)*/ - -#define INT_MIN64 (~0x7FFFFFFFFFFFFFFFLL) -#define INT_MAX64 0x7FFFFFFFFFFFFFFFLL -#define INT_MIN32 (~0x7FFFFFFFL) -#define INT_MAX32 0x7FFFFFFFL -#define UINT_MAX32 0xFFFFFFFFL -#define INT_MIN24 (~0x007FFFFF) -#define INT_MAX24 0x007FFFFF -#define UINT_MAX24 0x00FFFFFF -#define INT_MIN16 (~0x7FFF) -#define INT_MAX16 0x7FFF -#define UINT_MAX16 0xFFFF -#define INT_MIN8 (~0x7F) -#define INT_MAX8 0x7F -#define UINT_MAX8 0xFF - -/* From limits.h instead */ -#ifndef DBL_MIN -#define DBL_MIN 4.94065645841246544e-324 -#define FLT_MIN ((float)1.40129846432481707e-45) -#endif -#ifndef DBL_MAX -#define DBL_MAX 1.79769313486231470e+308 -#define FLT_MAX ((float)3.40282346638528860e+38) -#endif -#ifndef SIZE_T_MAX -#define SIZE_T_MAX (~((size_t) 0)) -#endif - -/* Define missing math constants. */ -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif -#ifndef M_E -#define M_E 2.7182818284590452354 -#endif -#ifndef M_LN2 -#define M_LN2 0.69314718055994530942 -#endif - -/* - Max size that must be added to a so that we know Size to make - addressable obj. -*/ -#if SIZEOF_CHARP == 4 -typedef long my_ptrdiff_t; -#else -typedef long long my_ptrdiff_t; -#endif - -#define MY_ALIGN(A,L) (((A) + (L) - 1) & ~((L) - 1)) -#define MY_ALIGN_DOWN(A,L) ((A) & ~((L) - 1)) -#define ALIGN_SIZE(A) MY_ALIGN((A),sizeof(double)) -#define ALIGN_MAX_UNIT (sizeof(double)) -/* Size to make addressable obj. */ -#define ALIGN_PTR(A, t) ((t*) MY_ALIGN((A), sizeof(double))) -#define ADD_TO_PTR(ptr,size,type) (type) ((uchar*) (ptr)+size) -#define PTR_BYTE_DIFF(A,B) (my_ptrdiff_t) ((uchar*) (A) - (uchar*) (B)) -#define PREV_BITS(type,A) ((type) (((type) 1 << (A)) -1)) - -/* - Custom version of standard offsetof() macro which can be used to get - offsets of members in class for non-POD types (according to the current - version of C++ standard offsetof() macro can't be used in such cases and - attempt to do so causes warnings to be emitted, OTOH in many cases it is - still OK to assume that all instances of the class has the same offsets - for the same members). - - This is temporary solution which should be removed once File_parser class - and related routines are refactored. -*/ - -#define my_offsetof(TYPE, MEMBER) PTR_BYTE_DIFF(&((TYPE *)0x10)->MEMBER, 0x10) - -#define NullS (char *) 0 - -#ifdef STDCALL -#undef STDCALL -#endif - -#ifdef _WIN32 -#define STDCALL __stdcall -#else -#define STDCALL -#endif - -/* Typdefs for easyier portability */ - -#ifndef HAVE_UCHAR -typedef unsigned char uchar; /* Short for unsigned char */ -#endif - -#ifndef HAVE_INT8 -typedef signed char int8; /* Signed integer >= 8 bits */ -#endif -#ifndef HAVE_UINT8 -typedef unsigned char uint8; /* Unsigned integer >= 8 bits */ -#endif -#ifndef HAVE_INT16 -typedef short int16; -#endif -#ifndef HAVE_UINT16 -typedef unsigned short uint16; -#endif -#if SIZEOF_INT == 4 -#ifndef HAVE_INT32 -typedef int int32; -#endif -#ifndef HAVE_UINT32 -typedef unsigned int uint32; -#endif -#elif SIZEOF_LONG == 4 -#ifndef HAVE_INT32 -typedef long int32; -#endif -#ifndef HAVE_UINT32 -typedef unsigned long uint32; -#endif -#else -#error Neither int or long is of 4 bytes width -#endif - -#if !defined(HAVE_ULONG) && !defined(__USE_MISC) -typedef unsigned long ulong; /* Short for unsigned long */ -#endif -#ifndef longlong_defined -/* - Using [unsigned] long long is preferable as [u]longlong because we use - [unsigned] long long unconditionally in many places, - for example in constants with [U]LL suffix. -*/ -#if defined(HAVE_LONG_LONG) && SIZEOF_LONG_LONG == 8 -typedef unsigned long long int ulonglong; /* ulong or unsigned long long */ -typedef long long int longlong; -#else -typedef unsigned long ulonglong; /* ulong or unsigned long long */ -typedef long longlong; -#endif -#endif -#ifndef HAVE_INT64 -typedef longlong int64; -#endif -#ifndef HAVE_UINT64 -typedef ulonglong uint64; -#endif - -#if defined(NO_CLIENT_LONG_LONG) -typedef unsigned long my_ulonglong; -#elif defined (__WIN__) -typedef unsigned __int64 my_ulonglong; -#else -typedef unsigned long long my_ulonglong; -#endif - -#if SIZEOF_CHARP == SIZEOF_INT -typedef unsigned int intptr; -#elif SIZEOF_CHARP == SIZEOF_LONG -typedef unsigned long intptr; -#elif SIZEOF_CHARP == SIZEOF_LONG_LONG -typedef unsigned long long intptr; -#else -#error sizeof(void *) is neither sizeof(int) nor sizeof(long) nor sizeof(long long) -#endif - -#define MY_ERRPTR ((void*)(intptr)1) - -#if defined(_WIN32) -typedef unsigned long long my_off_t; -typedef unsigned long long os_off_t; -#else -typedef off_t os_off_t; -#if SIZEOF_OFF_T > 4 -typedef ulonglong my_off_t; -#else -typedef unsigned long my_off_t; -#endif -#endif /*_WIN32*/ -#define MY_FILEPOS_ERROR (~(my_off_t) 0) - -/* - TODO Convert these to use Bitmap class. - */ -typedef ulonglong table_map; /* Used for table bits in join */ - -/* often used type names - opaque declarations */ -typedef const struct charset_info_st CHARSET_INFO; -typedef struct st_mysql_lex_string LEX_STRING; - -#if defined(__WIN__) -#define socket_errno WSAGetLastError() -#define SOCKET_EINTR WSAEINTR -#define SOCKET_ETIMEDOUT WSAETIMEDOUT -#define SOCKET_EWOULDBLOCK WSAEWOULDBLOCK -#define SOCKET_EADDRINUSE WSAEADDRINUSE -#define SOCKET_ECONNRESET WSAECONNRESET -#define SOCKET_ENFILE ENFILE -#define SOCKET_EMFILE EMFILE -#else /* Unix */ -#define socket_errno errno -#define closesocket(A) close(A) -#define SOCKET_EINTR EINTR -#define SOCKET_EAGAIN EAGAIN -#define SOCKET_EWOULDBLOCK EWOULDBLOCK -#define SOCKET_EADDRINUSE EADDRINUSE -#define SOCKET_ETIMEDOUT ETIMEDOUT -#define SOCKET_ECONNRESET ECONNRESET -#define SOCKET_ENFILE ENFILE -#define SOCKET_EMFILE EMFILE -#endif - -#include /* my_bool */ - -typedef ulong myf; /* Type of MyFlags in my_funcs */ - -#define MYF(v) (myf) (v) - -/* - Defines to make it possible to prioritize register assignments. No - longer that important with modern compilers. -*/ -#ifndef USING_X -#define reg1 register -#define reg2 register -#define reg3 register -#define reg4 register -#define reg5 register -#define reg6 register -#define reg7 register -#define reg8 register -#define reg9 register -#define reg10 register -#define reg11 register -#define reg12 register -#define reg13 register -#define reg14 register -#define reg15 register -#define reg16 register -#endif - -/* - MYSQL_PLUGIN_IMPORT macro is used to export mysqld data - (i.e variables) for usage in storage engine loadable plugins. - Outside of Windows, it is dummy. -*/ -#ifndef MYSQL_PLUGIN_IMPORT -#if (defined(_WIN32) && defined(MYSQL_DYNAMIC_PLUGIN)) -#define MYSQL_PLUGIN_IMPORT __declspec(dllimport) -#else -#define MYSQL_PLUGIN_IMPORT -#endif -#endif - -#include - -/* Some helper macros */ -#define YESNO(X) ((X) ? "yes" : "no") - -#define MY_HOW_OFTEN_TO_ALARM 2 /* How often we want info on screen */ -#define MY_HOW_OFTEN_TO_WRITE 10000 /* How often we want info on screen */ - -#include - -#ifdef HAVE_CHARSET_utf8mb4 -#define MYSQL_UNIVERSAL_CLIENT_CHARSET "utf8mb4" -#elif defined(HAVE_CHARSET_utf8mb3) -#define MYSQL_UNIVERSAL_CLIENT_CHARSET "utf8mb3" -#else -#define MYSQL_UNIVERSAL_CLIENT_CHARSET MYSQL_DEFAULT_CHARSET_NAME -#endif - -#if defined(EMBEDDED_LIBRARY) && !defined(HAVE_EMBEDDED_PRIVILEGE_CONTROL) -#define NO_EMBEDDED_ACCESS_CHECKS -#endif - -#ifdef _WIN32 -#define dlsym(lib, name) (void*)GetProcAddress((HMODULE)lib, name) -#define dlopen(libname, unused) LoadLibraryEx(libname, NULL, 0) -#define RTLD_DEFAULT GetModuleHandle(NULL) -#define dlclose(lib) FreeLibrary((HMODULE)lib) -static inline char *dlerror(void) -{ - static char win_errormsg[2048]; - FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, - 0, GetLastError(), 0, win_errormsg, 2048, NULL); - return win_errormsg; -} -#define HAVE_DLOPEN 1 -#define HAVE_DLERROR 1 -#endif - -#ifdef HAVE_DLFCN_H -#include -#endif - -#ifdef HAVE_DLOPEN -#ifndef HAVE_DLERROR -#define dlerror() "" -#endif -#ifndef HAVE_DLADDR -#define dladdr(A, B) 0 -/* Dummy definition in case we're missing dladdr() */ -typedef struct { const char *dli_fname, dli_fbase; } Dl_info; -#endif -#else -#define dlerror() "No support for dynamic loading (static build?)" -#define dlopen(A,B) 0 -#define dlsym(A,B) 0 -#define dlclose(A) 0 -#define dladdr(A, B) 0 -/* Dummy definition in case we're missing dladdr() */ -typedef struct { const char *dli_fname, dli_fbase; } Dl_info; -#endif - -/* - * Include standard definitions of operator new and delete. - */ -#ifdef __cplusplus -#include -#endif - -/* Length of decimal number represented by INT32. */ -#define MY_INT32_NUM_DECIMAL_DIGITS 11 - -/* Length of decimal number represented by INT64. */ -#define MY_INT64_NUM_DECIMAL_DIGITS 21 - -#ifdef __cplusplus -#include /* should be included before min/max macros */ -#endif - -/* Define some useful general macros (should be done after all headers). */ -#define MY_MAX(a, b) ((a) > (b) ? (a) : (b)) -#define MY_MIN(a, b) ((a) < (b) ? (a) : (b)) - -#define CMP_NUM(a,b) (((a) < (b)) ? -1 : ((a) == (b)) ? 0 : 1) - -/* - Only Linux is known to need an explicit sync of the directory to make sure a - file creation/deletion/renaming in(from,to) this directory durable. -*/ -#ifdef TARGET_OS_LINUX -#define NEED_EXPLICIT_SYNC_DIR 1 -#else -/* - On linux default rwlock scheduling policy is good enough for - waiting_threads.c, on other systems use our special implementation - (which is slower). - - QQ perhaps this should be tested in configure ? how ? -*/ -#define WT_RWLOCKS_USE_MUTEXES 1 -#endif - -#if !defined(__cplusplus) && !defined(bool) -#define bool In_C_you_should_use_my_bool_instead() -#endif - -/* Provide __func__ macro definition for platforms that miss it. */ -#if !defined (__func__) -#if defined(__STDC_VERSION__) && __STDC_VERSION__ < 199901L -# if __GNUC__ >= 2 -# define __func__ __FUNCTION__ -# else -# define __func__ "" -# endif -#elif defined(_MSC_VER) -# if _MSC_VER < 1300 -# define __func__ "" -# else -# define __func__ __FUNCTION__ -# endif -#elif defined(__BORLANDC__) -# define __func__ __FUNC__ -#else -# define __func__ "" -#endif -#endif /* !defined(__func__) */ - -/* Defines that are unique to the embedded version of MySQL */ - -#ifdef EMBEDDED_LIBRARY - -/* Things we don't need in the embedded version of MySQL */ -/* TODO HF add #undef HAVE_VIO if we don't want client in embedded library */ - -#else -#define HAVE_REPLICATION -#define HAVE_EXTERNAL_CLIENT -#endif /* EMBEDDED_LIBRARY */ - -/* Workaround for _LARGE_FILES and _LARGE_FILE_API incompatibility on AIX */ -#if defined(_AIX) && defined(_LARGE_FILE_API) -#undef _LARGE_FILE_API -#undef __GNUG__ -#endif - -/* - Provide defaults for the CPU cache line size, if it has not been detected by - CMake using getconf -*/ -#if !defined(CPU_LEVEL1_DCACHE_LINESIZE) || CPU_LEVEL1_DCACHE_LINESIZE == 0 - #if defined(CPU_LEVEL1_DCACHE_LINESIZE) && CPU_LEVEL1_DCACHE_LINESIZE == 0 - #undef CPU_LEVEL1_DCACHE_LINESIZE - #endif - - #if defined(__s390__) - #define CPU_LEVEL1_DCACHE_LINESIZE 256 - #elif defined(__powerpc__) || defined(__aarch64__) - #define CPU_LEVEL1_DCACHE_LINESIZE 128 - #else - #define CPU_LEVEL1_DCACHE_LINESIZE 64 - #endif -#endif - -#define FLOATING_POINT_DECIMALS 31 - -/* Keep client compatible with earlier versions */ -#ifdef MYSQL_SERVER -#define NOT_FIXED_DEC DECIMAL_NOT_SPECIFIED -#else -#define NOT_FIXED_DEC FLOATING_POINT_DECIMALS -#endif -#endif /* my_global_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_list.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_list.h deleted file mode 100644 index 0bb785b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_list.h +++ /dev/null @@ -1,45 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _list_h_ -#define _list_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct st_list { - struct st_list *prev,*next; - void *data; -} LIST; - -typedef int (*list_walk_action)(void *,void *); - -extern LIST *list_add(LIST *root,LIST *element); -extern LIST *list_delete(LIST *root,LIST *element); -extern LIST *list_cons(void *data,LIST *root); -extern LIST *list_reverse(LIST *root); -extern void list_free(LIST *root,unsigned int free_data); -extern unsigned int list_length(LIST *); -extern int list_walk(LIST *,list_walk_action action,unsigned char * argument); - -#define list_rest(a) ((a)->next) -#define list_push(a,b) (a)=list_cons((b),(a)) -#define list_pop(A) {LIST *old=(A); (A)=list_delete(old,old); my_free(old); } - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_net.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_net.h deleted file mode 100644 index 9a4f2f4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_net.h +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - This file is also used to make handling of sockets and ioctl() - portable across systems. - -*/ - -#ifndef _my_net_h -#define _my_net_h - -C_MODE_START - -#include -#ifdef HAVE_SYS_SOCKET_H -#include -#endif -#ifdef HAVE_NETINET_IN_H -#include -#endif -#ifdef HAVE_ARPA_INET_H -#include -#endif -#if defined(HAVE_POLL_H) -#include -#elif defined(HAVE_SYS_POLL_H) -#include -#endif /* defined(HAVE_POLL_H) */ -#ifdef HAVE_SYS_IOCTL_H -#include -#endif - -#if !defined(__WIN__) -#include -#include -#include -#if !defined(alpha_linux_port) -#include -#endif -#endif - -#if defined(__WIN__) -#define O_NONBLOCK 1 /* For emulation of fcntl() */ - -/* - SHUT_RDWR is called SD_BOTH in windows and - is defined to 2 in winsock2.h - #define SD_BOTH 0x02 -*/ -#define SHUT_RDWR 0x02 -#else -#include /* getaddrinfo() & co */ -#endif - -/* - On OSes which don't have the in_addr_t, we guess that using uint32 - is the best possible choice. We guess this from the fact that on - HP-UX64bit & FreeBSD64bit & Solaris64bit, in_addr_t is equivalent to - uint32. And on Linux32bit too. -*/ -#ifndef HAVE_IN_ADDR_T -#define in_addr_t uint32 -#endif - - -C_MODE_END -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_pthread.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_pthread.h deleted file mode 100644 index 6687603..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_pthread.h +++ /dev/null @@ -1,809 +0,0 @@ -/* Copyright (c) 2000, 2014, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Defines to make different thread packages compatible */ - -#ifndef _my_pthread_h -#define _my_pthread_h - -#ifndef ETIME -#define ETIME ETIMEDOUT /* For FreeBSD */ -#endif - -#ifdef __cplusplus -#define EXTERNC extern "C" -extern "C" { -#else -#define EXTERNC -#endif /* __cplusplus */ - -#if defined(__WIN__) -typedef CRITICAL_SECTION pthread_mutex_t; -typedef DWORD pthread_t; -typedef struct thread_attr { - DWORD dwStackSize ; - DWORD dwCreatingFlag ; -} pthread_attr_t ; - -typedef struct { int dummy; } pthread_condattr_t; - -/* Implementation of posix conditions */ - -typedef struct st_pthread_link { - DWORD thread_id; - struct st_pthread_link *next; -} pthread_link; - -/** - Implementation of Windows condition variables. - We use native conditions on Vista and later, and fallback to own - implementation on earlier OS version. -*/ -typedef CONDITION_VARIABLE pthread_cond_t; - - -typedef int pthread_mutexattr_t; -#define pthread_self() GetCurrentThreadId() -#define pthread_handler_t EXTERNC void * __cdecl -typedef void * (__cdecl *pthread_handler)(void *); - -typedef INIT_ONCE my_pthread_once_t; -#define MY_PTHREAD_ONCE_INIT INIT_ONCE_STATIC_INIT; - -#if !STRUCT_TIMESPEC_HAS_TV_SEC || !STRUCT_TIMESPEC_HAS_TV_NSEC -struct timespec { - time_t tv_sec; - long tv_nsec; -}; -#endif - -int win_pthread_mutex_trylock(pthread_mutex_t *mutex); -int pthread_create(pthread_t *, const pthread_attr_t *, pthread_handler, void *); -int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr); -int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); -int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, - const struct timespec *abstime); -int pthread_cond_signal(pthread_cond_t *cond); -int pthread_cond_broadcast(pthread_cond_t *cond); -int pthread_cond_destroy(pthread_cond_t *cond); -int pthread_attr_init(pthread_attr_t *connect_att); -int pthread_attr_setstacksize(pthread_attr_t *connect_att,size_t stack); -int pthread_attr_destroy(pthread_attr_t *connect_att); -int my_pthread_once(my_pthread_once_t *once_control,void (*init_routine)(void)); - -static inline struct tm *localtime_r(const time_t *timep, struct tm *tmp) -{ - localtime_s(tmp, timep); - return tmp; -} - -static inline struct tm *gmtime_r(const time_t *clock, struct tm *res) -{ - gmtime_s(res, clock); - return res; -} - -void pthread_exit(void *a); -int pthread_join(pthread_t thread, void **value_ptr); -int pthread_cancel(pthread_t thread); - -#ifndef ETIMEDOUT -#define ETIMEDOUT 145 /* Win32 doesn't have this */ -#endif - -#define getpid() GetCurrentThreadId() -#define HAVE_LOCALTIME_R 1 -#define _REENTRANT 1 -#define HAVE_PTHREAD_ATTR_SETSTACKSIZE 1 - -#undef SAFE_MUTEX /* This will cause conflicts */ -#define pthread_key(T,V) DWORD V -#define pthread_key_create(A,B) ((*A=TlsAlloc())==0xFFFFFFFF) -#define pthread_key_delete(A) TlsFree(A) -#define my_pthread_setspecific_ptr(T,V) (!TlsSetValue((T),(V))) -#define pthread_setspecific(A,B) (!TlsSetValue((A),(LPVOID)(B))) -#define pthread_getspecific(A) (TlsGetValue(A)) -#define my_pthread_getspecific(T,A) ((T) TlsGetValue(A)) -#define my_pthread_getspecific_ptr(T,V) ((T) TlsGetValue(V)) - -#define pthread_equal(A,B) ((A) == (B)) -#define pthread_mutex_init(A,B) (InitializeCriticalSection(A),0) -#define pthread_mutex_lock(A) (EnterCriticalSection(A),0) -#define pthread_mutex_trylock(A) win_pthread_mutex_trylock((A)) -#define pthread_mutex_unlock(A) (LeaveCriticalSection(A), 0) -#define pthread_mutex_destroy(A) (DeleteCriticalSection(A), 0) -#define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH) - - -/* Dummy defines for easier code */ -#define pthread_attr_setdetachstate(A,B) pthread_dummy(0) -#define pthread_attr_setscope(A,B) -#define pthread_detach_this_thread() -#define pthread_condattr_init(A) -#define pthread_condattr_destroy(A) -#define pthread_yield() SwitchToThread() -#define my_sigset(A,B) signal(A,B) - -#else /* Normal threads */ - -#ifdef HAVE_rts_threads -#define sigwait org_sigwait -#include -#undef sigwait -#endif -#include -#ifndef _REENTRANT -#define _REENTRANT -#endif -#ifdef HAVE_THR_SETCONCURRENCY -#include /* Probably solaris */ -#endif -#ifdef HAVE_SCHED_H -#include -#endif -#ifdef HAVE_SYNCH_H -#include -#endif - -#define pthread_key(T,V) pthread_key_t V -#define my_pthread_getspecific_ptr(T,V) my_pthread_getspecific(T,(V)) -#define my_pthread_setspecific_ptr(T,V) pthread_setspecific(T,(void*) (V)) -#define pthread_detach_this_thread() -#define pthread_handler_t EXTERNC void * -typedef void *(* pthread_handler)(void *); - -#define my_pthread_once_t pthread_once_t -#if defined(PTHREAD_ONCE_INITIALIZER) -#define MY_PTHREAD_ONCE_INIT PTHREAD_ONCE_INITIALIZER -#else -#define MY_PTHREAD_ONCE_INIT PTHREAD_ONCE_INIT -#endif -#define my_pthread_once(C,F) pthread_once(C,F) - -/* Test first for RTS or FSU threads */ - -#if defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) -#define HAVE_rts_threads -extern int my_pthread_create_detached; -#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C)) -#define PTHREAD_CREATE_DETACHED &my_pthread_create_detached -#define PTHREAD_SCOPE_SYSTEM PTHREAD_SCOPE_GLOBAL -#define PTHREAD_SCOPE_PROCESS PTHREAD_SCOPE_LOCAL -#define USE_ALARM_THREAD -#endif /* defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) */ - -#if defined(_BSDI_VERSION) && _BSDI_VERSION < 199910 -int sigwait(sigset_t *set, int *sig); -#endif - -static inline int my_sigwait(sigset_t *set, int *sig, int *code) -{ -#ifdef HAVE_SIGWAITINFO - siginfo_t siginfo; - *sig= sigwaitinfo(set, &siginfo); - *code= siginfo.si_code; - return *sig < 0 ? errno : 0; -#else -#define SI_KERNEL 128 - *code= 0; - return sigwait(set, sig); -#endif -} - -#if defined(HAVE_SIGTHREADMASK) && !defined(HAVE_PTHREAD_SIGMASK) -#define pthread_sigmask(A,B,C) sigthreadmask((A),(B),(C)) -#endif - -#if !defined(HAVE_SIGWAIT) && !defined(HAVE_rts_threads) && !defined(sigwait) && !defined(alpha_linux_port) && !defined(_AIX) -int sigwait(sigset_t *setp, int *sigp); /* Use our implementation */ -#endif - - -/* - We define my_sigset() and use that instead of the system sigset() so that - we can favor an implementation based on sigaction(). On some systems, such - as Mac OS X, sigset() results in flags such as SA_RESTART being set, and - we want to make sure that no such flags are set. -*/ -#if defined(HAVE_SIGACTION) && !defined(my_sigset) -#define my_sigset(A,B) do { struct sigaction l_s; sigset_t l_set; \ - DBUG_ASSERT((A) != 0); \ - sigemptyset(&l_set); \ - l_s.sa_handler = (B); \ - l_s.sa_mask = l_set; \ - l_s.sa_flags = 0; \ - sigaction((A), &l_s, NULL); \ - } while (0) -#elif defined(HAVE_SIGSET) && !defined(my_sigset) -#define my_sigset(A,B) sigset((A),(B)) -#elif !defined(my_sigset) -#define my_sigset(A,B) signal((A),(B)) -#endif - -#if !defined(HAVE_PTHREAD_ATTR_SETSCOPE) -#define pthread_attr_setscope(A,B) -#undef HAVE_GETHOSTBYADDR_R /* No definition */ -#endif - -#define my_pthread_getspecific(A,B) ((A) pthread_getspecific(B)) - -#ifndef HAVE_LOCALTIME_R -struct tm *localtime_r(const time_t *clock, struct tm *res); -#endif - -#ifndef HAVE_GMTIME_R -struct tm *gmtime_r(const time_t *clock, struct tm *res); -#endif - -#ifdef HAVE_PTHREAD_CONDATTR_CREATE -/* DCE threads on HPUX 10.20 */ -#define pthread_condattr_init pthread_condattr_create -#define pthread_condattr_destroy pthread_condattr_delete -#endif - -/* FSU THREADS */ -#if !defined(HAVE_PTHREAD_KEY_DELETE) && !defined(pthread_key_delete) -#define pthread_key_delete(A) pthread_dummy(0) -#endif - -#if defined(HAVE_PTHREAD_ATTR_CREATE) && !defined(HAVE_SIGWAIT) -/* This is set on AIX_3_2 and Siemens unix (and DEC OSF/1 3.2 too) */ -#define pthread_key_create(A,B) \ - pthread_keycreate(A,(B) ?\ - (pthread_destructor_t) (B) :\ - (pthread_destructor_t) pthread_dummy) -#define pthread_attr_init(A) pthread_attr_create(A) -#define pthread_attr_destroy(A) pthread_attr_delete(A) -#define pthread_attr_setdetachstate(A,B) pthread_dummy(0) -#define pthread_create(A,B,C,D) pthread_create((A),*(B),(C),(D)) -#ifndef pthread_sigmask -#define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C)) -#endif -#define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH) -#undef pthread_detach_this_thread -#define pthread_detach_this_thread() { pthread_t tmp=pthread_self() ; pthread_detach(&tmp); } -#else /* HAVE_PTHREAD_ATTR_CREATE && !HAVE_SIGWAIT */ -#define HAVE_PTHREAD_KILL 1 -#endif - -#endif /* defined(__WIN__) */ - -#if defined(HPUX10) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS) -#undef pthread_cond_timedwait -#define pthread_cond_timedwait(a,b,c) my_pthread_cond_timedwait((a),(b),(c)) -int my_pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, - struct timespec *abstime); -#endif - -#if defined(HPUX10) -#define pthread_attr_getstacksize(A,B) my_pthread_attr_getstacksize(A,B) -void my_pthread_attr_getstacksize(pthread_attr_t *attrib, size_t *size); -#endif - -#if defined(HAVE_POSIX1003_4a_MUTEX) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS) -#undef pthread_mutex_trylock -#define pthread_mutex_trylock(a) my_pthread_mutex_trylock((a)) -int my_pthread_mutex_trylock(pthread_mutex_t *mutex); -#endif - -#if !defined(HAVE_PTHREAD_YIELD_ZERO_ARG) -/* no pthread_yield() available */ -#ifdef HAVE_SCHED_YIELD -#define pthread_yield() sched_yield() -#elif defined(HAVE_PTHREAD_YIELD_NP) /* can be Mac OS X */ -#define pthread_yield() pthread_yield_np() -#elif defined(HAVE_THR_YIELD) -#define pthread_yield() thr_yield() -#endif -#endif - -size_t my_setstacksize(pthread_attr_t *attr, size_t stacksize); - -/* - The defines set_timespec and set_timespec_nsec should be used - for calculating an absolute time at which - pthread_cond_timedwait should timeout -*/ -#define set_timespec(ABSTIME,SEC) set_timespec_nsec((ABSTIME),(SEC)*1000000000ULL) - -#ifndef set_timespec_nsec -#define set_timespec_nsec(ABSTIME,NSEC) \ - set_timespec_time_nsec((ABSTIME), my_hrtime_coarse().val*1000 + (NSEC)) -#endif /* !set_timespec_nsec */ - -/* adapt for two different flavors of struct timespec */ -#ifdef HAVE_TIMESPEC_TS_SEC -#define MY_tv_sec ts_sec -#define MY_tv_nsec ts_nsec -#else -#define MY_tv_sec tv_sec -#define MY_tv_nsec tv_nsec -#endif /* HAVE_TIMESPEC_TS_SEC */ - -/** - Compare two timespec structs. - - @retval 1 If TS1 ends after TS2. - - @retval 0 If TS1 is equal to TS2. - - @retval -1 If TS1 ends before TS2. -*/ -#ifndef cmp_timespec -#define cmp_timespec(TS1, TS2) \ - ((TS1.MY_tv_sec > TS2.MY_tv_sec || \ - (TS1.MY_tv_sec == TS2.MY_tv_sec && TS1.MY_tv_nsec > TS2.MY_tv_nsec)) ? 1 : \ - ((TS1.MY_tv_sec < TS2.MY_tv_sec || \ - (TS1.MY_tv_sec == TS2.MY_tv_sec && TS1.MY_tv_nsec < TS2.MY_tv_nsec)) ? -1 : 0)) -#endif /* !cmp_timespec */ - -#ifndef set_timespec_time_nsec -#define set_timespec_time_nsec(ABSTIME,NSEC) do { \ - ulonglong _now_= (NSEC); \ - (ABSTIME).MY_tv_sec= (time_t) (_now_ / 1000000000ULL); \ - (ABSTIME).MY_tv_nsec= (ulong) (_now_ % 1000000000UL); \ -} while(0) -#endif /* !set_timespec_time_nsec */ - -#ifdef MYSQL_CLIENT -#define _current_thd() NULL -#else -MYSQL_THD _current_thd(); -#endif - -/* safe_mutex adds checking to mutex for easier debugging */ -struct st_hash; -typedef struct st_safe_mutex_t -{ - pthread_mutex_t global,mutex; - const char *file, *name; - uint line,count; - myf create_flags, active_flags; - ulong id; - pthread_t thread; - struct st_hash *locked_mutex, *used_mutex; - struct st_safe_mutex_t *prev, *next; -#ifdef SAFE_MUTEX_DETECT_DESTROY - struct st_safe_mutex_info_t *info; /* to track destroying of mutexes */ -#endif -} safe_mutex_t; - -typedef struct st_safe_mutex_deadlock_t -{ - const char *file, *name; - safe_mutex_t *mutex; - uint line; - ulong count; - ulong id; - my_bool warning_only; -} safe_mutex_deadlock_t; - -#ifdef SAFE_MUTEX_DETECT_DESTROY -/* - Used to track the destroying of mutexes. This needs to be a separate - structure because the safe_mutex_t structure could be freed before - the mutexes are destroyed. -*/ - -typedef struct st_safe_mutex_info_t -{ - struct st_safe_mutex_info_t *next; - struct st_safe_mutex_info_t *prev; - const char *init_file; - uint32 init_line; -} safe_mutex_info_t; -#endif /* SAFE_MUTEX_DETECT_DESTROY */ - -int safe_mutex_init(safe_mutex_t *mp, const pthread_mutexattr_t *attr, - const char *name, const char *file, uint line); -int safe_mutex_lock(safe_mutex_t *mp, myf my_flags, const char *file, - uint line); -int safe_mutex_unlock(safe_mutex_t *mp,const char *file, uint line); -int safe_mutex_destroy(safe_mutex_t *mp,const char *file, uint line); -int safe_cond_wait(pthread_cond_t *cond, safe_mutex_t *mp,const char *file, - uint line); -int safe_cond_timedwait(pthread_cond_t *cond, safe_mutex_t *mp, - const struct timespec *abstime, - const char *file, uint line); -void safe_mutex_global_init(void); -void safe_mutex_end(FILE *file); -void safe_mutex_free_deadlock_data(safe_mutex_t *mp); - - /* Wrappers if safe mutex is actually used */ -#define MYF_TRY_LOCK 1 -#define MYF_NO_DEADLOCK_DETECTION 2 - -#ifdef SAFE_MUTEX -#define safe_mutex_is_owner(mp) ((mp)->count > 0 && \ - pthread_equal(pthread_self(), (mp)->thread)) -#define safe_mutex_assert_owner(mp) DBUG_ASSERT(safe_mutex_is_owner(mp)) -#define safe_mutex_assert_not_owner(mp) DBUG_ASSERT(!safe_mutex_is_owner(mp)) -#define safe_mutex_setflags(mp, F) do { (mp)->create_flags|= (F); } while (0) -#define my_cond_timedwait(A,B,C) safe_cond_timedwait((A),(B),(C),__FILE__,__LINE__) -#define my_cond_wait(A,B) safe_cond_wait((A), (B), __FILE__, __LINE__) -#else - -#define safe_mutex_assert_owner(mp) do {} while (0) -#define safe_mutex_assert_not_owner(mp) do {} while (0) -#define safe_mutex_setflags(mp, F) do {} while (0) - -#define my_cond_timedwait(A,B,C) pthread_cond_timedwait((A),(B),(C)) -#define my_cond_wait(A,B) pthread_cond_wait((A), (B)) -#endif /* !SAFE_MUTEX */ - - /* READ-WRITE thread locking */ - -#if defined(USE_MUTEX_INSTEAD_OF_RW_LOCKS) -/* use these defs for simple mutex locking */ -#define rw_lock_t pthread_mutex_t -#define my_rwlock_init(A,B) pthread_mutex_init((A),(B)) -#define rw_rdlock(A) pthread_mutex_lock((A)) -#define rw_wrlock(A) pthread_mutex_lock((A)) -#define rw_tryrdlock(A) pthread_mutex_trylock((A)) -#define rw_trywrlock(A) pthread_mutex_trylock((A)) -#define rw_unlock(A) pthread_mutex_unlock((A)) -#define rwlock_destroy(A) pthread_mutex_destroy((A)) -#elif defined(HAVE_PTHREAD_RWLOCK_RDLOCK) -#define rw_lock_t pthread_rwlock_t -#define my_rwlock_init(A,B) pthread_rwlock_init((A),(B)) -#define rw_rdlock(A) pthread_rwlock_rdlock(A) -#define rw_wrlock(A) pthread_rwlock_wrlock(A) -#define rw_tryrdlock(A) pthread_rwlock_tryrdlock((A)) -#define rw_trywrlock(A) pthread_rwlock_trywrlock((A)) -#define rw_unlock(A) pthread_rwlock_unlock(A) -#define rwlock_destroy(A) pthread_rwlock_destroy(A) -#elif defined(HAVE_RWLOCK_INIT) -#ifdef HAVE_RWLOCK_T /* For example Solaris 2.6-> */ -#define rw_lock_t rwlock_t -#endif -#define my_rwlock_init(A,B) rwlock_init((A),USYNC_THREAD,0) -#else -/* Use our own version of read/write locks */ -#define NEED_MY_RW_LOCK 1 -#define rw_lock_t my_rw_lock_t -#define my_rwlock_init(A,B) my_rw_init((A)) -#define rw_rdlock(A) my_rw_rdlock((A)) -#define rw_wrlock(A) my_rw_wrlock((A)) -#define rw_tryrdlock(A) my_rw_tryrdlock((A)) -#define rw_trywrlock(A) my_rw_trywrlock((A)) -#define rw_unlock(A) my_rw_unlock((A)) -#define rwlock_destroy(A) my_rw_destroy((A)) -#define rw_lock_assert_write_owner(A) my_rw_lock_assert_write_owner((A)) -#define rw_lock_assert_not_write_owner(A) my_rw_lock_assert_not_write_owner((A)) -#endif /* USE_MUTEX_INSTEAD_OF_RW_LOCKS */ - - -/** - Portable implementation of special type of read-write locks. - - These locks have two properties which are unusual for rwlocks: - 1) They "prefer readers" in the sense that they do not allow - situations in which rwlock is rd-locked and there is a - pending rd-lock which is blocked (e.g. due to pending - request for wr-lock). - This is a stronger guarantee than one which is provided for - PTHREAD_RWLOCK_PREFER_READER_NP rwlocks in Linux. - MDL subsystem deadlock detector relies on this property for - its correctness. - 2) They are optimized for uncontended wr-lock/unlock case. - This is a scenario in which they are most often used - within MDL subsystem. Optimizing for it gives significant - performance improvements in some of the tests involving many - connections. - - Another important requirement imposed on this type of rwlock - by the MDL subsystem is that it should be OK to destroy rwlock - object which is in unlocked state even though some threads might - have not yet fully left unlock operation for it (of course there - is an external guarantee that no thread will try to lock rwlock - which is destroyed). - Putting it another way the unlock operation should not access - rwlock data after changing its state to unlocked. - - TODO/FIXME: We should consider alleviating this requirement as - it blocks us from doing certain performance optimizations. -*/ - -typedef struct st_rw_pr_lock_t { - /** - Lock which protects the structure. - Also held for the duration of wr-lock. - */ - pthread_mutex_t lock; - /** - Condition variable which is used to wake-up - writers waiting for readers to go away. - */ - pthread_cond_t no_active_readers; - /** Number of active readers. */ - uint active_readers; - /** Number of writers waiting for readers to go away. */ - uint writers_waiting_readers; - /** Indicates whether there is an active writer. */ - my_bool active_writer; -#ifdef SAFE_MUTEX - /** Thread holding wr-lock (for debug purposes only). */ - pthread_t writer_thread; -#endif -} rw_pr_lock_t; - -extern int rw_pr_init(rw_pr_lock_t *); -extern int rw_pr_rdlock(rw_pr_lock_t *); -extern int rw_pr_wrlock(rw_pr_lock_t *); -extern int rw_pr_unlock(rw_pr_lock_t *); -extern int rw_pr_destroy(rw_pr_lock_t *); -#ifdef SAFE_MUTEX -#define rw_pr_lock_assert_write_owner(A) \ - DBUG_ASSERT((A)->active_writer && pthread_equal(pthread_self(), \ - (A)->writer_thread)) -#define rw_pr_lock_assert_not_write_owner(A) \ - DBUG_ASSERT(! (A)->active_writer || ! pthread_equal(pthread_self(), \ - (A)->writer_thread)) -#else -#define rw_pr_lock_assert_write_owner(A) -#define rw_pr_lock_assert_not_write_owner(A) -#endif /* SAFE_MUTEX */ - - -#ifdef NEED_MY_RW_LOCK - -#ifdef _WIN32 - -/** - Implementation of Windows rwlock. - - We use native (slim) rwlocks on Windows, which requires Win7 - or later. -*/ -typedef struct _my_rwlock_t -{ - SRWLOCK srwlock; /* native reader writer lock */ - BOOL have_exclusive_srwlock; /* used for unlock */ -} my_rw_lock_t; - - -#else /* _WIN32 */ - -/* - On systems which don't support native read/write locks we have - to use own implementation. -*/ -typedef struct st_my_rw_lock_t { - pthread_mutex_t lock; /* lock for structure */ - pthread_cond_t readers; /* waiting readers */ - pthread_cond_t writers; /* waiting writers */ - int state; /* -1:writer,0:free,>0:readers */ - int waiters; /* number of waiting writers */ -#ifdef SAFE_MUTEX - pthread_t write_thread; -#endif -} my_rw_lock_t; - -#endif /*! _WIN32 */ - -extern int my_rw_init(my_rw_lock_t *); -extern int my_rw_destroy(my_rw_lock_t *); -extern int my_rw_rdlock(my_rw_lock_t *); -extern int my_rw_wrlock(my_rw_lock_t *); -extern int my_rw_unlock(my_rw_lock_t *); -extern int my_rw_tryrdlock(my_rw_lock_t *); -extern int my_rw_trywrlock(my_rw_lock_t *); -#ifdef SAFE_MUTEX -#define my_rw_lock_assert_write_owner(A) \ - DBUG_ASSERT((A)->state == -1 && pthread_equal(pthread_self(), \ - (A)->write_thread)) -#define my_rw_lock_assert_not_write_owner(A) \ - DBUG_ASSERT((A)->state >= 0 || ! pthread_equal(pthread_self(), \ - (A)->write_thread)) -#else -#define my_rw_lock_assert_write_owner(A) -#define my_rw_lock_assert_not_write_owner(A) -#endif -#endif /* NEED_MY_RW_LOCK */ - - -#define GETHOSTBYADDR_BUFF_SIZE 2048 - -#ifndef HAVE_THR_SETCONCURRENCY -#define thr_setconcurrency(A) pthread_dummy(0) -#endif -#if !defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && ! defined(pthread_attr_setstacksize) -#define pthread_attr_setstacksize(A,B) pthread_dummy(0) -#endif - -/* Define mutex types, see my_thr_init.c */ -#define MY_MUTEX_INIT_SLOW NULL -#ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP -extern pthread_mutexattr_t my_fast_mutexattr; -#define MY_MUTEX_INIT_FAST &my_fast_mutexattr -#else -#define MY_MUTEX_INIT_FAST NULL -#endif -#ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP -extern pthread_mutexattr_t my_errorcheck_mutexattr; -#define MY_MUTEX_INIT_ERRCHK &my_errorcheck_mutexattr -#else -#define MY_MUTEX_INIT_ERRCHK NULL -#endif - -#ifndef ESRCH -/* Define it to something */ -#define ESRCH 1 -#endif - -typedef uint64 my_thread_id; - -extern void my_threadattr_global_init(void); -extern my_bool my_thread_global_init(void); -extern void my_thread_global_reinit(void); -extern void my_thread_global_end(void); -extern my_bool my_thread_init(void); -extern void my_thread_end(void); -extern const char *my_thread_name(void); -extern my_thread_id my_thread_dbug_id(void); -extern int pthread_dummy(int); -extern void my_mutex_init(void); -extern void my_mutex_end(void); - -/* All thread specific variables are in the following struct */ - -#define THREAD_NAME_SIZE 10 -#ifndef DEFAULT_THREAD_STACK -/* - We need to have at least 256K stack to handle calls to myisamchk_init() - with the current number of keys and key parts. -*/ -#if defined(__SANITIZE_ADDRESS__) || defined(WITH_UBSAN) -#define DEFAULT_THREAD_STACK (383*1024L) /* 392192 */ -#else -#define DEFAULT_THREAD_STACK (292*1024L) /* 299008 */ -#endif -#endif - -#define MY_PTHREAD_LOCK_READ 0 -#define MY_PTHREAD_LOCK_WRITE 1 - -#include - -#define INSTRUMENT_ME 0 - -/* - Thread specific variables - - Aria key cache is using the following variables for keeping track of - state: - suspend, next, prev, keycache_link, keycache_file, suspend, lock_type - - MariaDB uses the following to - mutex, current_mutex, current_cond, abort -*/ - -struct st_my_thread_var -{ - int thr_errno; - mysql_cond_t suspend; - mysql_mutex_t mutex; - struct st_my_thread_var *next,**prev; - mysql_mutex_t * volatile current_mutex; - mysql_cond_t * volatile current_cond; - void *keycache_link; - void *keycache_file; - void *stack_ends_here; - safe_mutex_t *mutex_in_use; - pthread_t pthread_self; - my_thread_id id, dbug_id; - int volatile abort; - uint lock_type; /* used by conditional release the queue */ - my_bool init; -#ifndef DBUG_OFF - void *dbug; - char name[THREAD_NAME_SIZE+1]; -#endif -}; - -struct st_my_thread_var *_my_thread_var(void); -extern void **my_thread_var_dbug(void); -extern safe_mutex_t **my_thread_var_mutex_in_use(void); -extern uint my_thread_end_wait_time; -extern my_bool safe_mutex_deadlock_detector; -#define my_thread_var (_my_thread_var()) -#define my_errno my_thread_var->thr_errno -int set_mysys_var(struct st_my_thread_var *mysys_var); - - -/* - thread_safe_xxx functions are for critical statistic or counters. - The implementation is guaranteed to be thread safe, on all platforms. - Note that the calling code should *not* assume the counter is protected - by the mutex given, as the implementation of these helpers may change - to use my_atomic operations instead. -*/ - -#ifndef thread_safe_increment -#ifdef _WIN32 -#define thread_safe_increment(V,L) InterlockedIncrement((long*) &(V)) -#define thread_safe_decrement(V,L) InterlockedDecrement((long*) &(V)) -#else -#define thread_safe_increment(V,L) \ - (mysql_mutex_lock((L)), (V)++, mysql_mutex_unlock((L))) -#define thread_safe_decrement(V,L) \ - (mysql_mutex_lock((L)), (V)--, mysql_mutex_unlock((L))) -#endif -#endif - -#ifndef thread_safe_add -#ifdef _WIN32 -#define thread_safe_add(V,C,L) InterlockedExchangeAdd((long*) &(V),(C)) -#define thread_safe_sub(V,C,L) InterlockedExchangeAdd((long*) &(V),-(long) (C)) -#else -#define thread_safe_add(V,C,L) \ - (mysql_mutex_lock((L)), (V)+=(C), mysql_mutex_unlock((L))) -#define thread_safe_sub(V,C,L) \ - (mysql_mutex_lock((L)), (V)-=(C), mysql_mutex_unlock((L))) -#endif -#endif - - -/* - statistics_xxx functions are for non critical statistic, - maintained in global variables. - When compiling with SAFE_STATISTICS: - - race conditions can not occur. - - some locking occurs, which may cause performance degradation. - - When compiling without SAFE_STATISTICS: - - race conditions can occur, making the result slightly inaccurate. - - the lock given is not honored. -*/ -#ifdef SAFE_STATISTICS -#define statistic_increment(V,L) thread_safe_increment((V),(L)) -#define statistic_decrement(V,L) thread_safe_decrement((V),(L)) -#define statistic_add(V,C,L) thread_safe_add((V),(C),(L)) -#define statistic_sub(V,C,L) thread_safe_sub((V),(C),(L)) -#else -#define statistic_decrement(V,L) (V)-- -#define statistic_increment(V,L) (V)++ -#define statistic_add(V,C,L) (V)+=(C) -#define statistic_sub(V,C,L) (V)-=(C) -#endif /* SAFE_STATISTICS */ - -/* - No locking needed, the counter is owned by the thread -*/ -#define status_var_increment(V) (V)++ -#define status_var_decrement(V) (V)-- -#define status_var_add(V,C) (V)+=(C) -#define status_var_sub(V,C) (V)-=(C) - -#ifdef SAFE_MUTEX -#define mysql_mutex_record_order(A,B) \ - do { \ - mysql_mutex_lock(A); mysql_mutex_lock(B); \ - mysql_mutex_unlock(B); mysql_mutex_unlock(A); \ - } while(0) -#else -#define mysql_mutex_record_order(A,B) do { } while(0) -#endif - -/* At least Windows and NetBSD do not have this definition */ -#ifndef PTHREAD_STACK_MIN -#define PTHREAD_STACK_MIN 65536 -#endif - -#ifdef __cplusplus -} -#endif -#endif /* _my_ptread_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_sys.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_sys.h deleted file mode 100644 index a66bfd8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_sys.h +++ /dev/null @@ -1,1089 +0,0 @@ -/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. - Copyright (c) 2010, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_sys_h -#define _my_sys_h - -#include -#include - -C_MODE_START - - -#include -#include -#include /* for CHARSET_INFO */ -#include -#include -#ifdef _WIN32 -#include /*for alloca*/ -#endif -#include -#include - -#define MY_INIT(name) { my_progname= name; my_init(); } - -/** - Max length of an error message generated by mysys utilities. - Some mysys functions produce error messages. These mostly go - to stderr. - This constant defines the size of the buffer used to format - the message. It should be kept in sync with MYSQL_ERRMSG_SIZE, - since sometimes mysys errors are stored in the server diagnostics - area, and we would like to avoid unexpected truncation. -*/ -#define MYSYS_ERRMSG_SIZE (512) -#define MYSYS_STRERROR_SIZE (128) - -#define MY_FILE_ERROR ((size_t) -1) - - /* General bitmaps for my_func's */ -#define MY_FFNF 1U /* Fatal if file not found */ -#define MY_FNABP 2U /* Fatal if not all bytes read/written */ -#define MY_NABP 4U /* Error if not all bytes read/written */ -#define MY_FAE 8U /* Fatal if any error */ -#define MY_WME 16U /* Write message on error */ -#define MY_WAIT_IF_FULL 32U /* Wait and try again if disk full error */ -#define MY_IGNORE_BADFD 32U /* my_sync(): ignore 'bad descriptor' errors */ -#define MY_IGNORE_ENOENT 32U /* my_delete() ignores ENOENT (no such file) */ -#define MY_ENCRYPT 64U /* Encrypt IO_CACHE temporary files */ -#define MY_TEMPORARY 64U /* create_temp_file(): delete file at once */ -#define MY_NOSYMLINKS 512U /* my_open(): don't follow symlinks */ -#define MY_FULL_IO 512U /* my_read(): loop until I/O is complete */ -#define MY_DONT_CHECK_FILESIZE 128U /* Option to init_io_cache() */ -#define MY_LINK_WARNING 32U /* my_redel() gives warning if links */ -#define MY_COPYTIME 64U /* my_redel() copies time */ -#define MY_DELETE_OLD 256U /* my_create_with_symlink() */ -#define MY_RESOLVE_LINK 128U /* my_realpath(); Only resolve links */ -#define MY_HOLD_ORIGINAL_MODES 128U /* my_copy() holds to file modes */ -#define MY_REDEL_MAKE_BACKUP 256U -#define MY_SEEK_NOT_DONE 32U /* my_lock may have to do a seek */ -#define MY_SHORT_WAIT 64U /* my_lock() don't wait if can't lock */ -#define MY_FORCE_LOCK 128U /* use my_lock() even if disable_locking */ -#define MY_NO_WAIT 256U /* my_lock() don't wait at all */ -/* - init_dynamic_array() has init buffer; Internal flag, not to be used by - caller. -*/ -#define MY_INIT_BUFFER_USED 256U -#define MY_ZEROFILL 32U /* my_malloc(), fill array with zero */ -#define MY_ALLOW_ZERO_PTR 64U /* my_realloc() ; zero ptr -> malloc */ -#define MY_FREE_ON_ERROR 128U /* my_realloc() ; Free old ptr on error */ -#define MY_DONT_OVERWRITE_FILE 2048U /* my_copy: Don't overwrite file */ -#define MY_THREADSAFE 2048U /* my_seek(): lock fd mutex */ -#define MY_SYNC 4096U /* my_copy(): sync dst file */ -#define MY_SYNC_DIR 32768U /* my_create/delete/rename: sync directory */ -#define MY_SYNC_FILESIZE 65536U /* my_sync(): safe sync when file is extended */ -#define MY_THREAD_SPECIFIC 0x10000U /* my_malloc(): thread specific */ -/* Tree that should delete things automatically */ -#define MY_TREE_WITH_DELETE 0x40000U - -#define MY_CHECK_ERROR 1U /* Params to my_end; Check open-close */ -#define MY_GIVE_INFO 2U /* Give time info about process*/ -#define MY_DONT_FREE_DBUG 4U /* Do not call DBUG_END() in my_end() */ - -#define ME_BELL 4U /* Ring bell then printing message */ -#define ME_ERROR_LOG 64 /**< write the error message to error log */ -#define ME_ERROR_LOG_ONLY 128 /**< write the error message to error log only */ -#define ME_NOTE 1024 /**< not error but just info */ -#define ME_WARNING 2048 /**< not error but just warning */ -#define ME_FATAL 4096 /**< fatal statement error */ - - /* Bits in last argument to fn_format */ -#define MY_REPLACE_DIR 1U /* replace dir in name with 'dir' */ -#define MY_REPLACE_EXT 2U /* replace extension with 'ext' */ -#define MY_UNPACK_FILENAME 4U /* Unpack name (~ -> home) */ -#define MY_PACK_FILENAME 8U /* Pack name (home -> ~) */ -#define MY_RESOLVE_SYMLINKS 16U /* Resolve all symbolic links */ -#define MY_RETURN_REAL_PATH 32U /* return full path for file */ -#define MY_SAFE_PATH 64U /* Return NULL if too long path */ -#define MY_RELATIVE_PATH 128U /* name is relative to 'dir' */ -#define MY_APPEND_EXT 256U /* add 'ext' as additional extension*/ - - - /* My seek flags */ -#define MY_SEEK_SET 0 -#define MY_SEEK_CUR 1 -#define MY_SEEK_END 2 - - /* Some constants */ -#define MY_WAIT_FOR_USER_TO_FIX_PANIC 60 /* in seconds */ -#define MY_WAIT_GIVE_USER_A_MESSAGE 10 /* Every 10 times of prev */ -#define MIN_COMPRESS_LENGTH 50 /* Don't compress small bl. */ -#define DFLT_INIT_HITS 3 - - /* root_alloc flags */ -#define MY_KEEP_PREALLOC 1U -#define MY_MARK_BLOCKS_FREE 2U /* move used to free list and reuse them */ - - /* Internal error numbers (for assembler functions) */ -#define MY_ERRNO_EDOM 33 -#define MY_ERRNO_ERANGE 34 - - /* Bits for get_date timeflag */ -#define GETDATE_DATE_TIME 1U -#define GETDATE_SHORT_DATE 2U -#define GETDATE_HHMMSSTIME 4U -#define GETDATE_GMT 8U -#define GETDATE_FIXEDLENGTH 16U - -/* Extra length needed for filename if one calls my_create_backup_name */ -#define MY_BACKUP_NAME_EXTRA_LENGTH 17 - -char *guess_malloc_library(); - -/* If we have our own safemalloc (for debugging) */ -#if defined(SAFEMALLOC) -void sf_report_leaked_memory(my_thread_id id); -int sf_sanity(); -extern my_thread_id (*sf_malloc_dbug_id)(void); -#define SAFEMALLOC_REPORT_MEMORY(X) sf_report_leaked_memory(X) -#else -#define SAFEMALLOC_REPORT_MEMORY(X) do {} while(0) -#endif - -typedef void (*MALLOC_SIZE_CB) (long long size, my_bool is_thread_specific); -extern void set_malloc_size_cb(MALLOC_SIZE_CB func); - - /* defines when allocating data */ -extern void *my_malloc(PSI_memory_key key, size_t size, myf MyFlags); -extern void *my_multi_malloc(PSI_memory_key key, myf MyFlags, ...); -extern void *my_multi_malloc_large(PSI_memory_key key, myf MyFlags, ...); -extern void *my_realloc(PSI_memory_key key, void *ptr, size_t size, myf MyFlags); -extern void my_free(void *ptr); -extern void *my_memdup(PSI_memory_key key, const void *from,size_t length,myf MyFlags); -extern char *my_strdup(PSI_memory_key key, const char *from,myf MyFlags); -extern char *my_strndup(PSI_memory_key key, const char *from, size_t length, myf MyFlags); - -int my_init_large_pages(my_bool super_large_pages); -uchar *my_large_malloc(size_t *size, myf my_flags); -void my_large_free(void *ptr, size_t size); - -#ifdef _WIN32 -extern BOOL my_obtain_privilege(LPCSTR lpPrivilege); -#endif - -void my_init_atomic_write(void); -#ifdef __linux__ -my_bool my_test_if_atomic_write(File handle, int pagesize); -#else -#define my_test_if_atomic_write(A, B) 0 -#endif /* __linux__ */ -extern my_bool my_may_have_atomic_write; - -#if defined(HAVE_ALLOCA) && !defined(HAVE_valgrind) -#if defined(_AIX) && !defined(__GNUC__) && !defined(_AIX43) -#pragma alloca -#endif /* _AIX */ -#if defined(__MWERKS__) -#undef alloca -#define alloca _alloca -#endif /* __MWERKS__ */ -#if defined(__GNUC__) && !defined(HAVE_ALLOCA_H) && ! defined(alloca) -#define alloca __builtin_alloca -#endif /* GNUC */ -#define my_alloca(SZ) alloca((size_t) (SZ)) -#define my_afree(PTR) ((void)0) -#define MAX_ALLOCA_SZ 4096 -#define my_safe_alloca(size) (((size) <= MAX_ALLOCA_SZ) ? \ - my_alloca(size) : \ - my_malloc(PSI_NOT_INSTRUMENTED, (size), MYF(MY_THREAD_SPECIFIC|MY_WME))) -#define my_safe_afree(ptr, size) \ - do { if ((size) > MAX_ALLOCA_SZ) my_free(ptr); } while(0) -#else -#define my_alloca(SZ) my_malloc(PSI_NOT_INSTRUMENTED, SZ,MYF(MY_FAE)) -#define my_afree(PTR) my_free(PTR) -#define my_safe_alloca(size) my_alloca(size) -#define my_safe_afree(ptr, size) my_afree(ptr) -#endif /* HAVE_ALLOCA */ - -#ifndef errno /* did we already get it? */ -#ifdef HAVE_ERRNO_AS_DEFINE -#include /* errno is a define */ -#else -extern int errno; /* declare errno */ -#endif -#endif /* #ifndef errno */ -extern char *home_dir; /* Home directory for user */ -extern MYSQL_PLUGIN_IMPORT char *mysql_data_home; -extern const char *my_progname; /* program-name (printed in errors) */ -extern const char *my_progname_short; /* like above but without directory */ -extern char curr_dir[]; /* Current directory for user */ -extern void (*error_handler_hook)(uint my_err, const char *str,myf MyFlags); -extern void (*fatal_error_handler_hook)(uint my_err, const char *str, - myf MyFlags); -extern uint my_file_limit; -extern ulonglong my_thread_stack_size; -extern int sf_leaking_memory; /* set to 1 to disable memleak detection */ - -extern void (*proc_info_hook)(void *, const PSI_stage_info *, PSI_stage_info *, - const char *, const char *, const unsigned int); - -/* charsets */ -#define MY_ALL_CHARSETS_SIZE 2048 -extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *default_charset_info; -extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *all_charsets[MY_ALL_CHARSETS_SIZE]; -extern struct charset_info_st compiled_charsets[]; - -/* Collation properties and use statistics */ -extern my_bool my_collation_is_known_id(uint id); -extern ulonglong my_collation_statistics_get_use_count(uint id); -extern const char *my_collation_get_tailoring(uint id); - -/* statistics */ -extern ulong my_stream_opened, my_tmp_file_created; -extern ulong my_file_total_opened; -extern ulong my_sync_count; -extern uint mysys_usage_id; -extern int32 my_file_opened; -extern my_bool my_init_done, my_thr_key_mysys_exists; -extern my_bool my_assert; -extern my_bool my_assert_on_error; -extern myf my_global_flags; /* Set to MY_WME for more error messages */ - /* Point to current my_message() */ -extern void (*my_sigtstp_cleanup)(void), - /* Executed before jump to shell */ - (*my_sigtstp_restart)(void); - /* Executed when coming from shell */ -extern MYSQL_PLUGIN_IMPORT int my_umask; /* Default creation mask */ -extern int my_umask_dir, - my_recived_signals, /* Signals we have got */ - my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */ - my_dont_interrupt; /* call remember_intr when set */ -extern my_bool my_use_symdir; - -extern ulong my_default_record_cache_size; -extern my_bool my_disable_locking, my_disable_async_io, - my_disable_flush_key_blocks, my_disable_symlinks; -extern my_bool my_disable_sync, my_disable_copystat_in_redel; -extern char wild_many,wild_one,wild_prefix; -extern const char *charsets_dir; - -enum cache_type -{ - TYPE_NOT_SET= 0, READ_CACHE, WRITE_CACHE, - SEQ_READ_APPEND /* sequential read or append */, - READ_FIFO, READ_NET}; - -enum flush_type -{ - FLUSH_KEEP, /* flush block and keep it in the cache */ - FLUSH_RELEASE, /* flush block and remove it from the cache */ - FLUSH_IGNORE_CHANGED, /* remove block from the cache */ - /* - As my_disable_flush_pagecache_blocks is always 0, the following option - is strictly equivalent to FLUSH_KEEP - */ - FLUSH_FORCE_WRITE, - /** - @brief like FLUSH_KEEP but return immediately if file is already being - flushed (even partially) by another thread; only for page cache, - forbidden for key cache. - */ - FLUSH_KEEP_LAZY -}; - -typedef struct st_record_cache /* Used when caching records */ -{ - File file; - int rc_seek,error,inited; - uint rc_length,read_length,reclength; - my_off_t rc_record_pos,end_of_file; - uchar *rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos; - enum cache_type type; -} RECORD_CACHE; - -enum file_type -{ - UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE, STREAM_BY_FOPEN, STREAM_BY_FDOPEN, - FILE_BY_O_TMPFILE, FILE_BY_MKSTEMP, FILE_BY_DUP -}; - -struct st_my_file_info -{ - char *name; -#ifdef _WIN32 - HANDLE fhandle; /* win32 file handle */ - int oflag; /* open flags, e.g O_APPEND */ -#endif - enum file_type type; -}; - -extern struct st_my_file_info *my_file_info; - -/* Free function pointer */ -typedef void (*FREE_FUNC)(void *); - -typedef struct st_dynamic_array -{ - uchar *buffer; - uint elements,max_element; - uint alloc_increment; - uint size_of_element; - PSI_memory_key m_psi_key; - myf malloc_flags; -} DYNAMIC_ARRAY; - -typedef struct st_my_tmpdir -{ - DYNAMIC_ARRAY full_list; - char **list; - uint cur, max; - mysql_mutex_t mutex; -} MY_TMPDIR; - -typedef struct st_dynamic_string -{ - char *str; - size_t length,max_length,alloc_increment; -} DYNAMIC_STRING; - -struct st_io_cache; - -typedef struct st_io_cache_share -{ - mysql_mutex_t mutex; /* To sync on reads into buffer. */ - mysql_cond_t cond; /* To wait for signals. */ - mysql_cond_t cond_writer; /* For a synchronized writer. */ - /* Offset in file corresponding to the first byte of buffer. */ - my_off_t pos_in_file; - /* If a synchronized write cache is the source of the data. */ - struct st_io_cache *source_cache; - uchar *buffer; /* The read buffer. */ - uchar *read_end; /* Behind last valid byte of buffer. */ - int running_threads; /* threads not in lock. */ - int total_threads; /* threads sharing the cache. */ - int error; /* Last error. */ -#ifdef NOT_YET_IMPLEMENTED - /* whether the structure should be free'd */ - my_bool alloced; -#endif -} IO_CACHE_SHARE; - -typedef struct st_io_cache /* Used when caching files */ -{ - /* Offset in file corresponding to the first byte of uchar* buffer. */ - my_off_t pos_in_file; - /* - The offset of end of file for READ_CACHE and WRITE_CACHE. - For SEQ_READ_APPEND it the maximum of the actual end of file and - the position represented by read_end. - */ - my_off_t end_of_file; - /* Points to current read position in the buffer */ - uchar *read_pos; - /* the non-inclusive boundary in the buffer for the currently valid read */ - uchar *read_end; - uchar *buffer; /* The read buffer */ - /* Used in ASYNC_IO */ - uchar *request_pos; - - /* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */ - uchar *write_buffer; - /* - Only used in SEQ_READ_APPEND, and points to the current read position - in the write buffer. Note that reads in SEQ_READ_APPEND caches can - happen from both read buffer (uchar* buffer) and write buffer - (uchar* write_buffer). - */ - uchar *append_read_pos; - /* Points to current write position in the write buffer */ - uchar *write_pos; - /* The non-inclusive boundary of the valid write area */ - uchar *write_end; - - /* - The lock is for append buffer used in SEQ_READ_APPEND cache - need mutex copying from append buffer to read buffer. - */ - mysql_mutex_t append_buffer_lock; - /* - The following is used when several threads are reading the - same file in parallel. They are synchronized on disk - accesses reading the cached part of the file asynchronously. - It should be set to NULL to disable the feature. Only - READ_CACHE mode is supported. - */ - IO_CACHE_SHARE *share; - - /* - A caller will use my_b_read() macro to read from the cache - if the data is already in cache, it will be simply copied with - memcpy() and internal variables will be accordinging updated with - no functions invoked. However, if the data is not fully in the cache, - my_b_read() will call read_function to fetch the data. read_function - must never be invoked directly. - */ - int (*read_function)(struct st_io_cache *,uchar *,size_t); - /* - Same idea as in the case of read_function, except my_b_write() needs to - be replaced with my_b_append() for a SEQ_READ_APPEND cache - */ - int (*write_function)(struct st_io_cache *,const uchar *,size_t); - /* - Specifies the type of the cache. Depending on the type of the cache - certain operations might not be available and yield unpredicatable - results. Details to be documented later - */ - enum cache_type type; - /* - Counts the number of times, when we were forced to use disk. We use it to - increase the binlog_cache_disk_use and binlog_stmt_cache_disk_use status - variables. - */ - ulong disk_writes; - char *file_name; /* if used with 'open_cached_file' */ - const char *dir; - char prefix[3]; - File file; /* file descriptor */ - - struct st_io_cache *next_file_user; - /* - seek_not_done is set by my_b_seek() to inform the upcoming read/write - operation that a seek needs to be preformed prior to the actual I/O - error is 0 if the cache operation was successful, -1 if there was a - "hard" error, and the actual number of I/O-ed bytes if the read/write was - partial. - */ - int seek_not_done,error; - /* length of the buffer used for storing un-encrypted data */ - size_t buffer_length; - /* read_length is the same as buffer_length except when we use async io */ - size_t read_length; - myf myflags; /* Flags used to my_read/my_write */ - /* - alloced_buffer is set to the size of the buffer allocated for the IO_CACHE. - Includes the overhead(storing key to ecnrypt and decrypt) for encryption. - Set to 0 if nothing is allocated. - Currently READ_NET is the only one that will use a buffer allocated - somewhere else - */ - size_t alloced_buffer; -} IO_CACHE; - -typedef int (*qsort2_cmp)(const void *, const void *, const void *); - -typedef void (*my_error_reporter)(enum loglevel level, const char *format, ...) - ATTRIBUTE_FORMAT_FPTR(printf, 2, 3); - -extern my_error_reporter my_charset_error_reporter; - -extern PSI_file_key key_file_io_cache; - -/* inline functions for mf_iocache */ - -extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock); -extern int _my_b_get(IO_CACHE *info); -extern int _my_b_read(IO_CACHE *info,uchar *Buffer,size_t Count); -extern int _my_b_write(IO_CACHE *info,const uchar *Buffer,size_t Count); - -/* Test if buffer is inited */ -static inline void my_b_clear(IO_CACHE *info) { info->buffer= 0; } -static inline int my_b_inited(IO_CACHE *info) { return MY_TEST(info->buffer); } -#define my_b_EOF INT_MIN - -static inline int my_b_read(IO_CACHE *info, uchar *Buffer, size_t Count) -{ - if (info->read_pos + Count <= info->read_end) - { - memcpy(Buffer, info->read_pos, Count); - info->read_pos+= Count; - return 0; - } - return _my_b_read(info, Buffer, Count); -} - -static inline int my_b_write(IO_CACHE *info, const uchar *Buffer, size_t Count) -{ - MEM_CHECK_DEFINED(Buffer, Count); - if (info->write_pos + Count <= info->write_end) - { - memcpy(info->write_pos, Buffer, Count); - info->write_pos+= Count; - return 0; - } - return _my_b_write(info, Buffer, Count); -} - -static inline int my_b_get(IO_CACHE *info) -{ - if (info->read_pos != info->read_end) - { - info->read_pos++; - return info->read_pos[-1]; - } - return _my_b_get(info); -} - -static inline my_bool my_b_write_byte(IO_CACHE *info, uchar chr) -{ - MEM_CHECK_DEFINED(&chr, 1); - if (info->write_pos >= info->write_end) - if (my_b_flush_io_cache(info, 1)) - return 1; - *info->write_pos++= chr; - return 0; -} - -/** - Fill buffer of the cache. - - @note It assumes that you have already used all characters in the CACHE, - independent of the read_pos value! - - @returns - 0 On error or EOF (info->error = -1 on error) - # Number of characters -*/ -static inline size_t my_b_fill(IO_CACHE *info) -{ - info->read_pos= info->read_end; - return _my_b_read(info,0,0) ? 0 : (size_t) (info->read_end - info->read_pos); -} - -static inline my_off_t my_b_tell(const IO_CACHE *info) -{ - if (info->type == WRITE_CACHE) { - return info->pos_in_file + (my_off_t)(info->write_pos - info->request_pos); - - } - return info->pos_in_file + (my_off_t) (info->read_pos - info->request_pos); -} - -static inline my_off_t my_b_write_tell(const IO_CACHE *info) -{ - return info->pos_in_file + (my_off_t) (info->write_pos - info->write_buffer); -} - -static inline uchar* my_b_get_buffer_start(const IO_CACHE *info) -{ - return info->request_pos; -} - -static inline size_t my_b_get_bytes_in_buffer(const IO_CACHE *info) -{ - return (size_t) (info->read_end - info->request_pos); -} - -static inline my_off_t my_b_get_pos_in_file(const IO_CACHE *info) -{ - return info->pos_in_file; -} - -static inline size_t my_b_bytes_in_cache(const IO_CACHE *info) -{ - if (info->type == WRITE_CACHE) { - return (size_t) (info->write_end - info->write_pos); - } - return (size_t) (info->read_end - info->read_pos); -} - -int my_b_copy_to_file (IO_CACHE *cache, FILE *file, size_t count); -int my_b_copy_all_to_file(IO_CACHE *cache, FILE *file); - -my_off_t my_b_append_tell(IO_CACHE* info); -my_off_t my_b_safe_tell(IO_CACHE* info); /* picks the correct tell() */ -int my_b_pread(IO_CACHE *info, uchar *Buffer, size_t Count, my_off_t pos); - -typedef uint32 ha_checksum; - -extern int (*mysys_test_invalid_symlink)(const char *filename); -#include - - /* Prototypes for mysys and my_func functions */ - -extern int my_copy(const char *from,const char *to,myf MyFlags); -extern int my_delete(const char *name,myf MyFlags); -extern int my_rmtree(const char *name, myf Myflags); -extern int my_getwd(char * buf,size_t size,myf MyFlags); -extern int my_setwd(const char *dir,myf MyFlags); -extern int my_lock(File fd,int op,my_off_t start, my_off_t length,myf MyFlags); -extern void *my_once_alloc(size_t Size,myf MyFlags); -extern void my_once_free(void); -extern char *my_once_strdup(const char *src,myf myflags); -extern void *my_once_memdup(const void *src, size_t len, myf myflags); -extern File my_open(const char *FileName,int Flags,myf MyFlags); -extern File my_register_filename(File fd, const char *FileName, - enum file_type type_of_file, - uint error_message_number, myf MyFlags); -extern File my_create(const char *FileName,int CreateFlags, - int AccessFlags, myf MyFlags); -extern int my_close(File Filedes,myf MyFlags); -extern int my_mkdir(const char *dir, int Flags, myf MyFlags); -extern int my_readlink(char *to, const char *filename, myf MyFlags); -extern int my_is_symlink(const char *filename); -extern int my_realpath(char *to, const char *filename, myf MyFlags); -extern File my_create_with_symlink(const char *linkname, const char *filename, - int createflags, int access_flags, - myf MyFlags); -extern int my_rename_with_symlink(const char *from,const char *to,myf MyFlags); -extern int my_symlink(const char *content, const char *linkname, myf MyFlags); -extern int my_handler_delete_with_symlink(const char *filename, myf sync_dir); - -extern size_t my_read(File Filedes,uchar *Buffer,size_t Count,myf MyFlags); -extern size_t my_pread(File Filedes,uchar *Buffer,size_t Count,my_off_t offset, - myf MyFlags); -extern int my_rename(const char *from,const char *to,myf MyFlags); -extern my_off_t my_seek(File fd,my_off_t pos,int whence,myf MyFlags); -extern my_off_t my_tell(File fd,myf MyFlags); -extern size_t my_write(File Filedes,const uchar *Buffer,size_t Count, - myf MyFlags); -extern size_t my_pwrite(File Filedes,const uchar *Buffer,size_t Count, - my_off_t offset,myf MyFlags); -extern size_t my_fread(FILE *stream,uchar *Buffer,size_t Count,myf MyFlags); -extern size_t my_fwrite(FILE *stream,const uchar *Buffer,size_t Count, - myf MyFlags); -extern my_off_t my_fseek(FILE *stream,my_off_t pos,int whence,myf MyFlags); -extern my_off_t my_ftell(FILE *stream,myf MyFlags); - -/* implemented in my_memmem.c */ -extern void *my_memmem(const void *haystack, size_t haystacklen, - const void *needle, size_t needlelen); - - -#ifdef _WIN32 -extern int my_access(const char *path, int amode); -#define my_check_user(A,B) (NULL) -#define my_set_user(A,B,C) (0) -#else -#define my_access access -struct passwd *my_check_user(const char *user, myf MyFlags); -int my_set_user(const char *user, struct passwd *user_info, myf MyFlags); -#endif - -extern int check_if_legal_filename(const char *path); -extern int check_if_legal_tablename(const char *path); - -#ifdef _WIN32 -extern my_bool is_filename_allowed(const char *name, size_t length, - my_bool allow_current_dir); -#else /* _WIN32 */ -# define is_filename_allowed(name, length, allow_cwd) (TRUE) -#endif /* _WIN32 */ - -#ifdef _WIN32 -/* Windows-only functions (CRT equivalents)*/ -extern HANDLE my_get_osfhandle(File fd); -extern File my_win_handle2File(HANDLE hFile); -extern void my_osmaperr(unsigned long last_error); -#endif - -extern void init_glob_errs(void); -extern const char** get_global_errmsgs(int nr); -extern void wait_for_free_space(const char *filename, int errors); -extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags); -extern FILE *my_fdopen(File Filedes,const char *name, int Flags,myf MyFlags); -extern FILE *my_freopen(const char *path, const char *mode, FILE *stream); -extern int my_fclose(FILE *fd,myf MyFlags); -extern int my_vfprintf(FILE *stream, const char* format, va_list args); -extern const char* my_strerror(char *buf, size_t len, int nr); -extern int my_fprintf(FILE *stream, const char* format, ...); -extern File my_fileno(FILE *fd); -extern int my_chsize(File fd,my_off_t newlength, int filler, myf MyFlags); -extern int my_chmod(const char *name, mode_t mode, myf my_flags); -extern const char *my_basename(const char *filename); -extern void thr_set_sync_wait_callback(void (*before_sync)(void), - void (*after_sync)(void)); -extern int my_sync(File fd, myf my_flags); -extern int my_sync_dir(const char *dir_name, myf my_flags); -extern int my_sync_dir_by_file(const char *file_name, myf my_flags); -extern const char *my_get_err_msg(uint nr); -extern int my_error_register(const char** (*get_errmsgs) (int nr), - uint first, uint last); -extern my_bool my_error_unregister(uint first, uint last); -extern void my_message(uint my_err, const char *str,myf MyFlags); -extern void my_message_stderr(uint my_err, const char *str, myf MyFlags); -extern my_bool my_init(void); -extern void my_end(int infoflag); -extern int my_redel(const char *from, const char *to, time_t backup_time_stamp, - myf MyFlags); -void my_create_backup_name(char *to, const char *from, - time_t backup_time_stamp); -extern int my_copystat(const char *from, const char *to, int MyFlags); -extern char * my_filename(File fd); - -extern my_bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist); -extern char *my_tmpdir(MY_TMPDIR *tmpdir); -extern void free_tmpdir(MY_TMPDIR *tmpdir); - -extern void my_remember_signal(int signal_number,sig_handler (*func)(int)); -extern size_t dirname_part(char * to,const char *name, size_t *to_res_length); -extern size_t dirname_length(const char *name); -#define base_name(A) (A+dirname_length(A)) -extern int test_if_hard_path(const char *dir_name); -extern my_bool has_path(const char *name); -extern char *convert_dirname(char *to, const char *from, const char *from_end); -extern void to_unix_path(char * name); -extern char * fn_ext(const char *name); -extern char * fn_ext2(const char *name); -extern char * fn_same(char * toname,const char *name,int flag); -extern char * fn_format(char * to,const char *name,const char *dir, - const char *form, uint flag); -extern size_t strlength(const char *str); -extern void pack_dirname(char * to,const char *from); -extern size_t normalize_dirname(char * to, const char *from); -extern size_t unpack_dirname(char * to,const char *from); -extern size_t cleanup_dirname(char * to,const char *from); -extern size_t system_filename(char * to,const char *from); -extern size_t unpack_filename(char * to,const char *from); -extern char * intern_filename(char * to,const char *from); -extern int pack_filename(char * to, const char *name, size_t max_length); -extern char * my_path(char * to,const char *progname, - const char *own_pathname_part); -extern char * my_load_path(char * to, const char *path, - const char *own_path_prefix); -extern int wild_compare(const char *str,const char *wildstr, - pbool str_is_pattern); -extern my_bool array_append_string_unique(const char *str, - const char **array, size_t size); -extern void get_date(char * to,int timeflag,time_t use_time); -extern void soundex(CHARSET_INFO *, char * out_pntr, char * in_pntr, - pbool remove_garbage); -extern int init_record_cache(RECORD_CACHE *info,size_t cachesize,File file, - size_t reclength,enum cache_type type, - pbool use_async_io); -extern int read_cache_record(RECORD_CACHE *info,uchar *to); -extern int end_record_cache(RECORD_CACHE *info); -extern int write_cache_record(RECORD_CACHE *info,my_off_t filepos, - const uchar *record,size_t length); -extern int flush_write_cache(RECORD_CACHE *info); -extern void handle_recived_signals(void); - -extern sig_handler my_set_alarm_variable(int signo); -extern my_bool radixsort_is_appliccable(uint n_items, size_t size_of_element); -extern void my_string_ptr_sort(uchar *base,uint items,size_t size); -extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements, - size_t size_of_element,uchar *buffer[]); -extern qsort_t my_qsort(void *base_ptr, size_t total_elems, size_t size, - qsort_cmp cmp); -extern qsort_t my_qsort2(void *base_ptr, size_t total_elems, size_t size, - qsort2_cmp cmp, void *cmp_argument); -extern qsort2_cmp get_ptr_compare(size_t); -void my_store_ptr(uchar *buff, size_t pack_length, my_off_t pos); -my_off_t my_get_ptr(uchar *ptr, size_t pack_length); -extern int init_io_cache(IO_CACHE *info,File file,size_t cachesize, - enum cache_type type,my_off_t seek_offset, - my_bool use_async_io, myf cache_myflags); -extern int init_io_cache_ext(IO_CACHE *info, File file, size_t cachesize, - enum cache_type type, my_off_t seek_offset, - pbool use_async_io, myf cache_myflags, - PSI_file_key file_key); -extern my_bool reinit_io_cache(IO_CACHE *info,enum cache_type type, - my_off_t seek_offset, my_bool use_async_io, - my_bool clear_cache); -extern void init_io_cache_share(IO_CACHE *read_cache, IO_CACHE_SHARE *cshare, - IO_CACHE *write_cache, uint num_threads); - -extern int init_slave_io_cache(IO_CACHE *master, IO_CACHE *slave); -void end_slave_io_cache(IO_CACHE *cache); -void seek_io_cache(IO_CACHE *cache, my_off_t needed_offset); - -extern void remove_io_thread(IO_CACHE *info); -extern int my_b_append(IO_CACHE *info,const uchar *Buffer,size_t Count); -extern int my_b_safe_write(IO_CACHE *info,const uchar *Buffer,size_t Count); - -extern int my_block_write(IO_CACHE *info, const uchar *Buffer, - size_t Count, my_off_t pos); - -#define flush_io_cache(info) my_b_flush_io_cache((info),1) - -extern int end_io_cache(IO_CACHE *info); -extern void my_b_seek(IO_CACHE *info,my_off_t pos); -extern size_t my_b_gets(IO_CACHE *info, char *to, size_t max_length); -extern my_off_t my_b_filelength(IO_CACHE *info); -extern my_bool my_b_write_backtick_quote(IO_CACHE *info, const char *str, - size_t len); -extern my_bool my_b_printf(IO_CACHE *info, const char* fmt, ...); -extern size_t my_b_vprintf(IO_CACHE *info, const char* fmt, va_list ap); -extern my_bool open_cached_file(IO_CACHE *cache,const char *dir, - const char *prefix, size_t cache_size, - myf cache_myflags); -extern my_bool real_open_cached_file(IO_CACHE *cache); -extern void close_cached_file(IO_CACHE *cache); -File create_temp_file(char *to, const char *dir, const char *pfx, - int mode, myf MyFlags); -#define my_init_dynamic_array(A,B,C,D,E,F) init_dynamic_array2(A,B,C,NULL,D,E,F) -#define my_init_dynamic_array2(A,B,C,D,E,F,G) init_dynamic_array2(A,B,C,D,E,F,G) -extern my_bool init_dynamic_array2(PSI_memory_key psi_key, DYNAMIC_ARRAY *array, - uint element_size, void *init_buffer, - uint init_alloc, uint alloc_increment, - myf my_flags); -extern my_bool insert_dynamic(DYNAMIC_ARRAY *array, const void* element); -extern void *alloc_dynamic(DYNAMIC_ARRAY *array); -extern void *pop_dynamic(DYNAMIC_ARRAY*); -extern my_bool set_dynamic(DYNAMIC_ARRAY *array, const void *element, - uint array_index); -extern my_bool allocate_dynamic(DYNAMIC_ARRAY *array, uint max_elements); -extern void get_dynamic(DYNAMIC_ARRAY *array, void *element, uint array_index); -extern void delete_dynamic(DYNAMIC_ARRAY *array); -extern void delete_dynamic_element(DYNAMIC_ARRAY *array, uint array_index); -extern void delete_dynamic_with_callback(DYNAMIC_ARRAY *array, FREE_FUNC f); -extern void freeze_size(DYNAMIC_ARRAY *array); -extern int get_index_dynamic(DYNAMIC_ARRAY *array, void *element); -#define dynamic_array_ptr(array,array_index) ((array)->buffer+(array_index)*(array)->size_of_element) -#define dynamic_element(array,array_index,type) ((type)((array)->buffer) +(array_index)) -#define push_dynamic(A,B) insert_dynamic((A),(B)) -#define reset_dynamic(array) ((array)->elements= 0) -#define sort_dynamic(A,cmp) my_qsort((A)->buffer, (A)->elements, (A)->size_of_element, (cmp)) - -extern my_bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str, - size_t init_alloc,size_t alloc_increment); -extern my_bool dynstr_append(DYNAMIC_STRING *str, const char *append); -my_bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append, - size_t length); -extern my_bool dynstr_append_os_quoted(DYNAMIC_STRING *str, const char *append, - ...); -extern my_bool dynstr_append_quoted(DYNAMIC_STRING *str, - const char *append, size_t len, - char quote); -extern my_bool dynstr_set(DYNAMIC_STRING *str, const char *init_str); -extern my_bool dynstr_realloc(DYNAMIC_STRING *str, size_t additional_size); -extern my_bool dynstr_trunc(DYNAMIC_STRING *str, size_t n); -extern void dynstr_free(DYNAMIC_STRING *str); -extern uint32 copy_and_convert_extended(char *to, uint32 to_length, - CHARSET_INFO *to_cs, - const char *from, uint32 from_length, - CHARSET_INFO *from_cs, uint *errors); -extern void dynstr_reassociate(DYNAMIC_STRING *str, char **res, size_t *length, - size_t *alloc_length); -extern uint32 copy_and_convert_extended(char *to, uint32 to_length, - CHARSET_INFO *to_cs, - const char *from, uint32 from_length, - CHARSET_INFO *from_cs, uint *errors); -#ifdef HAVE_MLOCK -extern void *my_malloc_lock(size_t length,myf flags); -extern void my_free_lock(void *ptr); -#else -#define my_malloc_lock(A,B) my_malloc(PSI_INSTRUMENT_ME, (A),(B)) -#define my_free_lock(A) my_free((A)) -#endif -#define root_name(A) "" -#define alloc_root_inited(A) ((A)->min_malloc != 0) -#define ALLOC_ROOT_MIN_BLOCK_SIZE (MALLOC_OVERHEAD + sizeof(USED_MEM) + 8) -#define clear_alloc_root(A) do { (A)->free= (A)->used= (A)->pre_alloc= 0; (A)->min_malloc=0;} while(0) -extern void init_alloc_root(PSI_memory_key key, MEM_ROOT *mem_root, - size_t block_size, size_t pre_alloc_size, - myf my_flags); -extern void *alloc_root(MEM_ROOT *mem_root, size_t Size); -extern void *multi_alloc_root(MEM_ROOT *mem_root, ...); -extern void free_root(MEM_ROOT *root, myf MyFLAGS); -extern void set_prealloc_root(MEM_ROOT *root, char *ptr); -extern void reset_root_defaults(MEM_ROOT *mem_root, size_t block_size, - size_t prealloc_size); -extern char *strdup_root(MEM_ROOT *root,const char *str); -static inline char *safe_strdup_root(MEM_ROOT *root, const char *str) -{ - return str ? strdup_root(root, str) : 0; -} -extern char *strmake_root(MEM_ROOT *root,const char *str,size_t len); -extern void *memdup_root(MEM_ROOT *root,const void *str, size_t len); -extern LEX_CSTRING safe_lexcstrdup_root(MEM_ROOT *root, const LEX_CSTRING str); -extern my_bool my_compress(uchar *, size_t *, size_t *); -extern my_bool my_uncompress(uchar *, size_t , size_t *); -extern uchar *my_compress_alloc(const uchar *packet, size_t *len, - size_t *complen); -extern void *my_az_allocator(void *dummy, unsigned int items, unsigned int size); -extern void my_az_free(void *dummy, void *address); -extern int my_compress_buffer(uchar *dest, size_t *destLen, - const uchar *source, size_t sourceLen); -extern int packfrm(const uchar *, size_t, uchar **, size_t *); -extern int unpackfrm(uchar **, size_t *, const uchar *); - -extern uint32 my_checksum(uint32, const void *, size_t); -extern uint32 my_crc32c(uint32, const void *, size_t); - -extern const char *my_crc32c_implementation(); - -#ifdef DBUG_ASSERT_EXISTS -extern void my_debug_put_break_here(void); -#else -#define my_debug_put_break_here() do {} while(0) -#endif - -extern void my_sleep(ulong m_seconds); -extern uint my_set_max_open_files(uint files); -void my_free_open_file_info(void); - -extern my_bool my_gethwaddr(uchar *to); -extern int my_getncpus(void); - -#define HRTIME_RESOLUTION 1000000ULL /* microseconds */ -typedef struct {ulonglong val;} my_hrtime_t; -void my_time_init(void); -extern my_hrtime_t my_hrtime(void); - -#ifdef _WIN32 -extern my_hrtime_t my_hrtime_coarse(); -#else -#define my_hrtime_coarse() my_hrtime() -#endif - -extern ulonglong my_interval_timer(void); -extern ulonglong my_getcputime(void); - -#define microsecond_interval_timer() (my_interval_timer()/1000) -#define hrtime_to_time(X) ((time_t)((X).val/HRTIME_RESOLUTION)) -#define hrtime_from_time(X) ((ulonglong)((X)*HRTIME_RESOLUTION)) -#define hrtime_to_double(X) ((X).val/(double)HRTIME_RESOLUTION) -#define hrtime_sec_part(X) ((ulong)((X).val % HRTIME_RESOLUTION)) -#define my_time(X) hrtime_to_time(my_hrtime_coarse()) - -#if STACK_DIRECTION < 0 -#define available_stack_size(CUR,END) (long) ((char*)(CUR) - (char*)(END)) -#else -#define available_stack_size(CUR,END) (long) ((char*)(END) - (char*)(CUR)) -#endif - -#ifndef MAP_SYNC -#define MAP_SYNC 0x80000 -#endif -#ifndef MAP_SHARED_VALIDATE -#define MAP_SHARED_VALIDATE 0x03 -#endif - -#ifdef HAVE_SYS_MMAN_H -#ifndef MAP_NOSYNC -#define MAP_NOSYNC 0 -#endif -#ifndef MAP_NORESERVE -#define MAP_NORESERVE 0 /* For irix and AIX */ -#endif - -/* Compatibility with pre linux 3.8 distributions */ -#ifdef __linux__ -#define MAP_HUGE_SHIFT 26 -#define MAP_HUGETLB 0x40000 -#endif - -#ifdef HAVE_MMAP64 -#define my_mmap(a,b,c,d,e,f) mmap64(a,b,c,d,e,f) -#else -#define my_mmap(a,b,c,d,e,f) mmap(a,b,c,d,e,f) -#endif -#define my_munmap(a,b) munmap((a),(b)) - -#else -/* not a complete set of mmap() flags, but only those that nesessary */ -#define PROT_READ 1 -#define PROT_WRITE 2 -#define MAP_NORESERVE 0 -#define MAP_SHARED 0x0001 -#define MAP_PRIVATE 0x0002 -#define MAP_NOSYNC 0x0800 -#define MAP_FAILED ((void *)-1) -#define MS_SYNC 0x0000 - -#define HAVE_MMAP -void *my_mmap(void *, size_t, int, int, int, my_off_t); -int my_munmap(void *, size_t); -#endif - -#ifdef _WIN32 -extern FILE* my_win_popen(const char*, const char*); -extern int my_win_pclose(FILE*); -#define my_popen(A,B) my_win_popen(A,B) -#define my_pclose(A) my_win_pclose(A) -#else -#define my_popen(A,B) popen(A,B) -#define my_pclose(A) pclose(A) -#endif - -/* my_getpagesize */ -#ifdef HAVE_GETPAGESIZE -#define my_getpagesize() getpagesize() -#else -int my_getpagesize(void); -#endif - -int my_msync(int, void *, size_t, int); - -#define MY_UUID_SIZE 16 -#define MY_UUID_STRING_LENGTH (8+1+4+1+4+1+4+1+12) - -void my_uuid_init(ulong seed1, ulong seed2); -void my_uuid(uchar *guid); -void my_uuid2str(const uchar *guid, char *s); -void my_uuid_end(void); - -const char *my_dlerror(const char *dlpath); - -/* character sets */ -extern void my_charset_loader_init_mysys(MY_CHARSET_LOADER *loader); -extern uint get_charset_number(const char *cs_name, uint cs_flags); -extern uint get_collation_number(const char *name); -extern const char *get_charset_name(uint cs_number); - -extern CHARSET_INFO *get_charset(uint cs_number, myf flags); -extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags); -extern CHARSET_INFO *my_collation_get_by_name(MY_CHARSET_LOADER *loader, - const char *name, myf flags); -extern CHARSET_INFO *get_charset_by_csname(const char *cs_name, - uint cs_flags, myf my_flags); -extern CHARSET_INFO *my_charset_get_by_name(MY_CHARSET_LOADER *loader, - const char *name, - uint cs_flags, myf my_flags); -extern my_bool resolve_charset(const char *cs_name, - CHARSET_INFO *default_cs, - CHARSET_INFO **cs); -extern my_bool resolve_collation(const char *cl_name, - CHARSET_INFO *default_cl, - CHARSET_INFO **cl); -extern void free_charsets(void); -extern char *get_charsets_dir(char *buf); -static inline my_bool my_charset_same(CHARSET_INFO *cs1, CHARSET_INFO *cs2) -{ - return (cs1->csname == cs2->csname); -} -extern my_bool init_compiled_charsets(myf flags); -extern void add_compiled_collation(struct charset_info_st *cs); -extern void add_compiled_extra_collation(struct charset_info_st *cs); -extern size_t escape_string_for_mysql(CHARSET_INFO *charset_info, - char *to, size_t to_length, - const char *from, size_t length); -extern char *get_tty_password(const char *opt_message); -#ifdef _WIN32 -#define BACKSLASH_MBTAIL -/* File system character set */ -extern CHARSET_INFO *fs_character_set(void); -#endif -extern const char *my_default_csname(void); -extern size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info, - char *to, size_t to_length, - const char *from, size_t length); - -extern void thd_increment_bytes_sent(void *thd, size_t length); -extern void thd_increment_bytes_received(void *thd, size_t length); -extern void thd_increment_net_big_packet_count(void *thd, size_t length); - -#ifdef _WIN32 - -/* implemented in my_conio.c */ -char* my_cgets(char *string, size_t clen, size_t* plen); - -#endif - -#include - -#ifdef HAVE_PSI_INTERFACE -extern MYSQL_PLUGIN_IMPORT struct PSI_bootstrap *PSI_hook; -extern void set_psi_server(PSI *psi); -void my_init_mysys_psi_keys(void); -#endif - -struct st_mysql_file; -extern struct st_mysql_file *mysql_stdin; -C_MODE_END -#endif /* _my_sys_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_valgrind.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_valgrind.h deleted file mode 100644 index 62794a2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_valgrind.h +++ /dev/null @@ -1,100 +0,0 @@ -/* Copyright (C) 2010, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MY_VALGRIND_INCLUDED -#define MY_VALGRIND_INCLUDED - -/* clang -> gcc */ -#ifndef __has_feature -# define __has_feature(x) 0 -#endif -#if __has_feature(address_sanitizer) -# define __SANITIZE_ADDRESS__ 1 -#endif - -#if __has_feature(memory_sanitizer) -# include -# define HAVE_valgrind -# define MEM_UNDEFINED(a,len) __msan_allocated_memory(a,len) -# define MEM_MAKE_ADDRESSABLE(a,len) MEM_UNDEFINED(a,len) -# define MEM_MAKE_DEFINED(a,len) __msan_unpoison(a,len) -# define MEM_NOACCESS(a,len) ((void) 0) -# define MEM_CHECK_ADDRESSABLE(a,len) ((void) 0) -# define MEM_CHECK_DEFINED(a,len) __msan_check_mem_is_initialized(a,len) -# define MEM_GET_VBITS(a,b,len) __msan_copy_shadow(b,a,len) -# define MEM_SET_VBITS(a,b,len) __msan_copy_shadow(a,b,len) -# define REDZONE_SIZE 8 -#elif defined(HAVE_VALGRIND_MEMCHECK_H) && defined(HAVE_valgrind) -# include -# define MEM_UNDEFINED(a,len) VALGRIND_MAKE_MEM_UNDEFINED(a,len) -# define MEM_MAKE_ADDRESSABLE(a,len) MEM_UNDEFINED(a,len) -# define MEM_MAKE_DEFINED(a,len) VALGRIND_MAKE_MEM_DEFINED(a,len) -# define MEM_NOACCESS(a,len) VALGRIND_MAKE_MEM_NOACCESS(a,len) -# define MEM_CHECK_ADDRESSABLE(a,len) VALGRIND_CHECK_MEM_IS_ADDRESSABLE(a,len) -# define MEM_CHECK_DEFINED(a,len) VALGRIND_CHECK_MEM_IS_DEFINED(a,len) -# define MEM_GET_VBITS(a,b,len) VALGRIND_GET_VBITS(a,b,len) -# define MEM_SET_VBITS(a,b,len) VALGRIND_SET_VBITS(a,b,len) -# define REDZONE_SIZE 8 -#elif defined(__SANITIZE_ADDRESS__) -# include -/* How to do manual poisoning: -https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning */ -# define MEM_UNDEFINED(a,len) ((void) 0) -# define MEM_MAKE_ADDRESSABLE(a,len) ASAN_UNPOISON_MEMORY_REGION(a,len) -# define MEM_MAKE_DEFINED(a,len) ((void) 0) -# define MEM_NOACCESS(a,len) ASAN_POISON_MEMORY_REGION(a,len) -# define MEM_CHECK_ADDRESSABLE(a,len) \ - assert(!__asan_region_is_poisoned((void*) a,len)) -# define MEM_CHECK_DEFINED(a,len) ((void) 0) -# define MEM_GET_VBITS(a,b,len) ((void) 0) -# define MEM_SET_VBITS(a,b,len) ((void) 0) -# define REDZONE_SIZE 8 -#else -# define MEM_UNDEFINED(a,len) ((void) 0) -# define MEM_MAKE_ADDRESSABLE(a,len) ((void) 0) -# define MEM_MAKE_DEFINED(a,len) ((void) 0) -# define MEM_NOACCESS(a,len) ((void) 0) -# define MEM_CHECK_ADDRESSABLE(a,len) ((void) 0) -# define MEM_CHECK_DEFINED(a,len) ((void) 0) -# define MEM_GET_VBITS(a,b,len) ((void) 0) -# define MEM_SET_VBITS(a,b,len) ((void) 0) -# define REDZONE_SIZE 0 -#endif /* __has_feature(memory_sanitizer) */ - -#ifdef HAVE_valgrind -#define IF_VALGRIND(A,B) A -#else -#define IF_VALGRIND(A,B) B -#endif - -#ifdef TRASH_FREED_MEMORY -/* - _TRASH_FILL() has to call MEM_MAKE_ADDRESSABLE() to cancel any effect of - TRASH_FREE(). - This can happen in the case one does - TRASH_ALLOC(A,B) ; TRASH_FREE(A,B) ; TRASH_ALLOC(A,B) - to reuse the same memory in an internal memory allocator like MEM_ROOT. - _TRASH_FILL() is an internal function and should not be used externally. -*/ -#define _TRASH_FILL(A,B,C) do { const size_t trash_tmp= (B); MEM_MAKE_ADDRESSABLE(A, trash_tmp); memset(A, C, trash_tmp); } while (0) -#else -#define _TRASH_FILL(A,B,C) do { MEM_UNDEFINED((A), (B)); } while (0) -#endif -/** Note that some memory became allocated and/or uninitialized. */ -#define TRASH_ALLOC(A,B) do { _TRASH_FILL(A,B,0xA5); MEM_MAKE_ADDRESSABLE(A,B); } while(0) -/** Note that some memory became freed. (Prohibit further access to it.) */ -#define TRASH_FREE(A,B) do { _TRASH_FILL(A,B,0x8F); MEM_NOACCESS(A,B); } while(0) - -#endif /* MY_VALGRIND_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/my_xml.h b/VCMP-LUA/modules/mariadb/include/mysql/server/my_xml.h deleted file mode 100644 index 846448a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/my_xml.h +++ /dev/null @@ -1,97 +0,0 @@ -/* Copyright (c) 2000, 2002, 2003, 2005, 2007 MySQL AB - Use is subject to license terms - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef _my_xml_h -#define _my_xml_h - -#ifdef __cplusplus -extern "C" { -#endif - - -#define MY_XML_OK 0 -#define MY_XML_ERROR 1 - -/* - A flag whether to use absolute tag names in call-back functions, - like "a", "a.b" and "a.b.c" (used in character set file parser), - or relative names like "a", "b" and "c". -*/ -#define MY_XML_FLAG_RELATIVE_NAMES 1 - -/* - A flag whether to skip normilization of text values before calling - call-back functions: i.e. skip leading/trailing spaces, - \r, \n, \t characters. -*/ -#define MY_XML_FLAG_SKIP_TEXT_NORMALIZATION 2 - -enum my_xml_node_type -{ - MY_XML_NODE_TAG, /* can have TAG, ATTR and TEXT children */ - MY_XML_NODE_ATTR, /* can have TEXT children */ - MY_XML_NODE_TEXT /* cannot have children */ -}; - -typedef struct xml_stack_st -{ - int flags; - enum my_xml_node_type current_node_type; - char errstr[128]; - - struct { - char static_buffer[128]; - char *buffer; - size_t buffer_size; - char *start; - char *end; - } attr; - - const char *beg; - const char *cur; - const char *end; - void *user_data; - int (*enter)(struct xml_stack_st *st,const char *val, size_t len); - int (*value)(struct xml_stack_st *st,const char *val, size_t len); - int (*leave_xml)(struct xml_stack_st *st,const char *val, size_t len); -} MY_XML_PARSER; - -void my_xml_parser_create(MY_XML_PARSER *st); -void my_xml_parser_free(MY_XML_PARSER *st); -int my_xml_parse(MY_XML_PARSER *st,const char *str, size_t len); - -void my_xml_set_value_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, - const char *, - size_t len)); -void my_xml_set_enter_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, - const char *, - size_t len)); -void my_xml_set_leave_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, - const char *, - size_t len)); -void my_xml_set_user_data(MY_XML_PARSER *st, void *); - -size_t my_xml_error_pos(MY_XML_PARSER *st); -uint my_xml_error_lineno(MY_XML_PARSER *st); - -const char *my_xml_error_string(MY_XML_PARSER *st); - -#ifdef __cplusplus -} -#endif - -#endif /* _my_xml_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql.h deleted file mode 100644 index 6ff4c6d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql.h +++ /dev/null @@ -1,913 +0,0 @@ -/* - Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 2012, Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - This file defines the client API to MySQL and also the ABI of the - dynamically linked libmysqlclient. - - The ABI should never be changed in a released product of MySQL, - thus you need to take great care when changing the file. In case - the file is changed so the ABI is broken, you must also update - the SHARED_LIB_MAJOR_VERSION in cmake/mysql_version.cmake -*/ - -#ifndef _mysql_h -#define _mysql_h - -#ifdef _AIX /* large-file support will break without this */ -#include -#endif - -#ifdef __CYGWIN__ /* CYGWIN implements a UNIX API */ -#undef WIN -#undef _WIN -#undef _WIN32 -#undef _WIN64 -#undef __WIN__ -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MY_GLOBAL_INCLUDED /* If not standard header */ -#ifndef MYSQL_ABI_CHECK -#include -#endif - -#ifndef MYSQL_PLUGIN_INCLUDED -typedef char my_bool; -#endif - -#if (defined(_WIN32) || defined(_WIN64)) && !defined(__WIN__) -#define __WIN__ -#endif -#if !defined(__WIN__) -#define STDCALL -#else -#define STDCALL __stdcall -#endif - -#ifndef my_socket_defined -#if defined (_WIN64) -#define my_socket unsigned long long -#elif defined (_WIN32) -#define my_socket unsigned int -#else -typedef int my_socket; -#endif /* _WIN64 */ -#endif /* my_socket_defined */ -#endif /* MY_GLOBAL_INCLUDED */ - -#include "mysql_version.h" -#include "mysql_com.h" -#include "mysql_time.h" - -#include "my_list.h" /* for LISTs used in 'MYSQL' and 'MYSQL_STMT' */ - -extern unsigned int mariadb_deinitialize_ssl; -extern unsigned int mysql_port; -extern char *mysql_unix_port; - -#define CLIENT_NET_READ_TIMEOUT (365*24*3600) /* Timeout on read */ -#define CLIENT_NET_WRITE_TIMEOUT (365*24*3600) /* Timeout on write */ - -#define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG) -#define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG) -#define IS_BLOB(n) ((n) & BLOB_FLAG) -/** - Returns true if the value is a number which does not need quotes for - the sql_lex.cc parser to parse correctly. -*/ -#define IS_NUM(t) (((t) <= MYSQL_TYPE_INT24 && (t) != MYSQL_TYPE_TIMESTAMP) || (t) == MYSQL_TYPE_YEAR || (t) == MYSQL_TYPE_NEWDECIMAL) -#define IS_LONGDATA(t) ((t) >= MYSQL_TYPE_TINY_BLOB && (t) <= MYSQL_TYPE_STRING) - - -typedef struct st_mysql_const_lex_string MARIADB_CONST_STRING; - - -typedef struct st_mysql_field { - char *name; /* Name of column */ - char *org_name; /* Original column name, if an alias */ - char *table; /* Table of column if column was a field */ - char *org_table; /* Org table name, if table was an alias */ - char *db; /* Database for table */ - char *catalog; /* Catalog for table */ - char *def; /* Default value (set by mysql_list_fields) */ - unsigned long length; /* Width of column (create length) */ - unsigned long max_length; /* Max width for selected set */ - unsigned int name_length; - unsigned int org_name_length; - unsigned int table_length; - unsigned int org_table_length; - unsigned int db_length; - unsigned int catalog_length; - unsigned int def_length; - unsigned int flags; /* Div flags */ - unsigned int decimals; /* Number of decimals in field */ - unsigned int charsetnr; /* Character set */ - enum enum_field_types type; /* Type of field. See mysql_com.h for types */ - void *extension; -} MYSQL_FIELD; - -typedef char **MYSQL_ROW; /* return data as array of strings */ -typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */ - -#ifndef MY_GLOBAL_INCLUDED -#if defined(NO_CLIENT_LONG_LONG) -typedef unsigned long my_ulonglong; -#elif defined (__WIN__) -typedef unsigned __int64 my_ulonglong; -#else -typedef unsigned long long my_ulonglong; -#endif -#endif - -#include "typelib.h" - -#define MYSQL_COUNT_ERROR (~(my_ulonglong) 0) - -/* backward compatibility define - to be removed eventually */ -#define ER_WARN_DATA_TRUNCATED WARN_DATA_TRUNCATED -#define WARN_PLUGIN_DELETE_BUILTIN ER_PLUGIN_DELETE_BUILTIN -#define ER_FK_DUP_NAME ER_DUP_CONSTRAINT_NAME -#define ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED -#define ER_PRIMARY_KEY_BASED_ON_VIRTUAL_COLUMN ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN -#define ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN -#define ER_UNSUPPORTED_ACTION_ON_VIRTUAL_COLUMN ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN -#define ER_UNSUPPORTED_ENGINE_FOR_VIRTUAL_COLUMNS ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS - -typedef struct st_mysql_rows { - struct st_mysql_rows *next; /* list of rows */ - MYSQL_ROW data; - unsigned long length; -} MYSQL_ROWS; - -typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */ - -#include "my_alloc.h" - -typedef struct embedded_query_result EMBEDDED_QUERY_RESULT; -typedef struct st_mysql_data { - MYSQL_ROWS *data; - struct embedded_query_result *embedded_info; - MEM_ROOT alloc; - my_ulonglong rows; - unsigned int fields; - /* extra info for embedded library */ - void *extension; -} MYSQL_DATA; - -enum mysql_option -{ - MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE, - MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP, - MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE, - MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT, - MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT, - MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION, - MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH, - MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT, - MYSQL_OPT_SSL_VERIFY_SERVER_CERT, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH, - MYSQL_OPT_BIND, - MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, - MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH, MYSQL_OPT_SSL_CIPHER, - MYSQL_OPT_SSL_CRL, MYSQL_OPT_SSL_CRLPATH, - MYSQL_OPT_CONNECT_ATTR_RESET, MYSQL_OPT_CONNECT_ATTR_ADD, - MYSQL_OPT_CONNECT_ATTR_DELETE, - MYSQL_SERVER_PUBLIC_KEY, - MYSQL_ENABLE_CLEARTEXT_PLUGIN, - MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, - - /* MariaDB options */ - MYSQL_PROGRESS_CALLBACK=5999, - MYSQL_OPT_NONBLOCK, - MYSQL_OPT_USE_THREAD_SPECIFIC_MEMORY -}; - -/** - @todo remove the "extension", move st_mysql_options completely - out of mysql.h -*/ -struct st_mysql_options_extention; - -struct st_mysql_options { - unsigned int connect_timeout, read_timeout, write_timeout; - unsigned int port, protocol; - unsigned long client_flag; - char *host,*user,*password,*unix_socket,*db; - struct st_dynamic_array *init_commands; - char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name; - char *ssl_key; /* PEM key file */ - char *ssl_cert; /* PEM cert file */ - char *ssl_ca; /* PEM CA file */ - char *ssl_capath; /* PEM directory of CA-s? */ - char *ssl_cipher; /* cipher to use */ - char *shared_memory_base_name; - unsigned long max_allowed_packet; - my_bool use_ssl; /* if to use SSL or not */ - my_bool compress,named_pipe; - my_bool use_thread_specific_memory; - my_bool unused2; - my_bool unused3; - my_bool unused4; - enum mysql_option methods_to_use; - char *client_ip; - /* Refuse client connecting to server if it uses old (pre-4.1.1) protocol */ - my_bool secure_auth; - /* 0 - never report, 1 - always report (default) */ - my_bool report_data_truncation; - - /* function pointers for local infile support */ - int (*local_infile_init)(void **, const char *, void *); - int (*local_infile_read)(void *, char *, unsigned int); - void (*local_infile_end)(void *); - int (*local_infile_error)(void *, char *, unsigned int); - void *local_infile_userdata; - struct st_mysql_options_extention *extension; -}; - -enum mysql_status -{ - MYSQL_STATUS_READY, MYSQL_STATUS_GET_RESULT, MYSQL_STATUS_USE_RESULT, - MYSQL_STATUS_STATEMENT_GET_RESULT -}; - -enum mysql_protocol_type -{ - MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET, - MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY -}; - -typedef struct character_set -{ - unsigned int number; /* character set number */ - unsigned int state; /* character set state */ - const char *csname; /* collation name */ - const char *name; /* character set name */ - const char *comment; /* comment */ - const char *dir; /* character set directory */ - unsigned int mbminlen; /* min. length for multibyte strings */ - unsigned int mbmaxlen; /* max. length for multibyte strings */ -} MY_CHARSET_INFO; - -struct st_mysql_methods; -struct st_mysql_stmt; - -typedef struct st_mysql -{ - NET net; /* Communication parameters */ - unsigned char *connector_fd; /* ConnectorFd for SSL */ - char *host,*user,*passwd,*unix_socket,*server_version,*host_info; - char *info, *db; - const struct charset_info_st *charset; - MYSQL_FIELD *fields; - MEM_ROOT field_alloc; - my_ulonglong affected_rows; - my_ulonglong insert_id; /* id if insert on table with NEXTNR */ - my_ulonglong extra_info; /* Not used */ - unsigned long thread_id; /* Id for connection in server */ - unsigned long packet_length; - unsigned int port; - unsigned long client_flag,server_capabilities; - unsigned int protocol_version; - unsigned int field_count; - unsigned int server_status; - unsigned int server_language; - unsigned int warning_count; - struct st_mysql_options options; - enum mysql_status status; - my_bool free_me; /* If free in mysql_close */ - my_bool reconnect; /* set to 1 if automatic reconnect */ - - /* session-wide random string */ - char scramble[SCRAMBLE_LENGTH+1]; - my_bool auto_local_infile; - void *unused2, *unused3, *unused4, *unused5; - - LIST *stmts; /* list of all statements */ - const struct st_mysql_methods *methods; - void *thd; - /* - Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag - from mysql_stmt_close if close had to cancel result set of this object. - */ - my_bool *unbuffered_fetch_owner; - /* needed for embedded server - no net buffer to store the 'info' */ - char *info_buffer; - void *extension; -} MYSQL; - - -typedef struct st_mysql_res { - my_ulonglong row_count; - MYSQL_FIELD *fields; - MYSQL_DATA *data; - MYSQL_ROWS *data_cursor; - unsigned long *lengths; /* column lengths of current row */ - MYSQL *handle; /* for unbuffered reads */ - const struct st_mysql_methods *methods; - MYSQL_ROW row; /* If unbuffered read */ - MYSQL_ROW current_row; /* buffer to current row */ - MEM_ROOT field_alloc; - unsigned int field_count, current_field; - my_bool eof; /* Used by mysql_fetch_row */ - /* mysql_stmt_close() had to cancel this result */ - my_bool unbuffered_fetch_cancelled; - void *extension; -} MYSQL_RES; - - -#if !defined(MYSQL_SERVER) && !defined(MYSQL_CLIENT) -#define MYSQL_CLIENT -#endif - - -typedef struct st_mysql_parameters -{ - unsigned long *p_max_allowed_packet; - unsigned long *p_net_buffer_length; - void *extension; -} MYSQL_PARAMETERS; - -/* - Flag bits, the asynchronous methods return a combination of these ORed - together to let the application know when to resume the suspended operation. -*/ - -/* - Wait for data to be available on socket to read. - mysql_get_socket_fd() will return socket descriptor. -*/ -#define MYSQL_WAIT_READ 1 -/* Wait for socket to be ready to write data. */ -#define MYSQL_WAIT_WRITE 2 -/* Wait for select() to mark exception on socket. */ -#define MYSQL_WAIT_EXCEPT 4 -/* - Wait until timeout occurs. Value of timeout can be obtained from - mysql_get_timeout_value(). -*/ -#define MYSQL_WAIT_TIMEOUT 8 - -#if !defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY) -#define max_allowed_packet (*mysql_get_parameters()->p_max_allowed_packet) -#define net_buffer_length (*mysql_get_parameters()->p_net_buffer_length) -#endif - -/* - Set up and bring down the server; to ensure that applications will - work when linked against either the standard client library or the - embedded server library, these functions should be called. -*/ -int STDCALL mysql_server_init(int argc, char **argv, char **groups); -void STDCALL mysql_server_end(void); - -/* - mysql_server_init/end need to be called when using libmysqld or - libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so - you don't need to call it explicitly; but you need to call - mysql_server_end() to free memory). The names are a bit misleading - (mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general - names which suit well whether you're using libmysqld or libmysqlclient. We - intend to promote these aliases over the mysql_server* ones. -*/ -#define mysql_library_init mysql_server_init -#define mysql_library_end mysql_server_end - -MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void); - -/* - Set up and bring down a thread; these function should be called - for each thread in an application which opens at least one MySQL - connection. All uses of the connection(s) should be between these - function calls. -*/ -my_bool STDCALL mysql_thread_init(void); -void STDCALL mysql_thread_end(void); - -/* - Functions to get information from the MYSQL and MYSQL_RES structures - Should definitely be used if one uses shared libraries. -*/ - -my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res); -unsigned int STDCALL mysql_num_fields(MYSQL_RES *res); -my_bool STDCALL mysql_eof(MYSQL_RES *res); -MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res, - unsigned int fieldnr); -MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res); -MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res); -MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res); - - - - -int STDCALL mariadb_field_attr(MARIADB_CONST_STRING *attr, - const MYSQL_FIELD *field, - enum mariadb_field_attr_t type); - - -unsigned int STDCALL mysql_field_count(MYSQL *mysql); -my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql); -my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql); -unsigned int STDCALL mysql_errno(MYSQL *mysql); -const char * STDCALL mysql_error(MYSQL *mysql); -const char *STDCALL mysql_sqlstate(MYSQL *mysql); -unsigned int STDCALL mysql_warning_count(MYSQL *mysql); -const char * STDCALL mysql_info(MYSQL *mysql); -unsigned long STDCALL mysql_thread_id(MYSQL *mysql); -const char * STDCALL mysql_character_set_name(MYSQL *mysql); -int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname); -int STDCALL mysql_set_character_set_start(int *ret, MYSQL *mysql, - const char *csname); -int STDCALL mysql_set_character_set_cont(int *ret, MYSQL *mysql, - int status); - -MYSQL * STDCALL mysql_init(MYSQL *mysql); -my_bool STDCALL mysql_ssl_set(MYSQL *mysql, const char *key, - const char *cert, const char *ca, - const char *capath, const char *cipher); -const char * STDCALL mysql_get_ssl_cipher(MYSQL *mysql); -my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user, - const char *passwd, const char *db); -int STDCALL mysql_change_user_start(my_bool *ret, MYSQL *mysql, - const char *user, - const char *passwd, - const char *db); -int STDCALL mysql_change_user_cont(my_bool *ret, MYSQL *mysql, - int status); -MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host, - const char *user, - const char *passwd, - const char *db, - unsigned int port, - const char *unix_socket, - unsigned long clientflag); -int STDCALL mysql_real_connect_start(MYSQL **ret, MYSQL *mysql, - const char *host, - const char *user, - const char *passwd, - const char *db, - unsigned int port, - const char *unix_socket, - unsigned long clientflag); -int STDCALL mysql_real_connect_cont(MYSQL **ret, MYSQL *mysql, - int status); -int STDCALL mysql_select_db(MYSQL *mysql, const char *db); -int STDCALL mysql_select_db_start(int *ret, MYSQL *mysql, - const char *db); -int STDCALL mysql_select_db_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_query(MYSQL *mysql, const char *q); -int STDCALL mysql_query_start(int *ret, MYSQL *mysql, - const char *q); -int STDCALL mysql_query_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_send_query(MYSQL *mysql, const char *q, - unsigned long length); -int STDCALL mysql_send_query_start(int *ret, MYSQL *mysql, - const char *q, - unsigned long length); -int STDCALL mysql_send_query_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_real_query(MYSQL *mysql, const char *q, - unsigned long length); -int STDCALL mysql_real_query_start(int *ret, MYSQL *mysql, - const char *q, - unsigned long length); -int STDCALL mysql_real_query_cont(int *ret, MYSQL *mysql, - int status); -MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql); -int STDCALL mysql_store_result_start(MYSQL_RES **ret, MYSQL *mysql); -int STDCALL mysql_store_result_cont(MYSQL_RES **ret, MYSQL *mysql, - int status); -MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql); - -void STDCALL mysql_get_character_set_info(MYSQL *mysql, - MY_CHARSET_INFO *charset); - -/* local infile support */ - -#define LOCAL_INFILE_ERROR_LEN 512 - -void -mysql_set_local_infile_handler(MYSQL *mysql, - int (*local_infile_init)(void **, const char *, - void *), - int (*local_infile_read)(void *, char *, - unsigned int), - void (*local_infile_end)(void *), - int (*local_infile_error)(void *, char*, - unsigned int), - void *); - -void -mysql_set_local_infile_default(MYSQL *mysql); - -int STDCALL mysql_shutdown(MYSQL *mysql, - enum mysql_enum_shutdown_level - shutdown_level); -int STDCALL mysql_shutdown_start(int *ret, MYSQL *mysql, - enum mysql_enum_shutdown_level - shutdown_level); -int STDCALL mysql_shutdown_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_dump_debug_info(MYSQL *mysql); -int STDCALL mysql_dump_debug_info_start(int *ret, MYSQL *mysql); -int STDCALL mysql_dump_debug_info_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_refresh(MYSQL *mysql, - unsigned int refresh_options); -int STDCALL mysql_refresh_start(int *ret, MYSQL *mysql, - unsigned int refresh_options); -int STDCALL mysql_refresh_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid); -int STDCALL mysql_kill_start(int *ret, MYSQL *mysql, - unsigned long pid); -int STDCALL mysql_kill_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_set_server_option(MYSQL *mysql, - enum enum_mysql_set_option - option); -int STDCALL mysql_set_server_option_start(int *ret, MYSQL *mysql, - enum enum_mysql_set_option - option); -int STDCALL mysql_set_server_option_cont(int *ret, MYSQL *mysql, - int status); -int STDCALL mysql_ping(MYSQL *mysql); -int STDCALL mysql_ping_start(int *ret, MYSQL *mysql); -int STDCALL mysql_ping_cont(int *ret, MYSQL *mysql, int status); -const char * STDCALL mysql_stat(MYSQL *mysql); -int STDCALL mysql_stat_start(const char **ret, MYSQL *mysql); -int STDCALL mysql_stat_cont(const char **ret, MYSQL *mysql, - int status); -const char * STDCALL mysql_get_server_info(MYSQL *mysql); -const char * STDCALL mysql_get_server_name(MYSQL *mysql); -const char * STDCALL mysql_get_client_info(void); -unsigned long STDCALL mysql_get_client_version(void); -const char * STDCALL mysql_get_host_info(MYSQL *mysql); -unsigned long STDCALL mysql_get_server_version(MYSQL *mysql); -unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql); -MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild); -int STDCALL mysql_list_dbs_start(MYSQL_RES **ret, MYSQL *mysql, - const char *wild); -int STDCALL mysql_list_dbs_cont(MYSQL_RES **ret, MYSQL *mysql, - int status); -MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild); -int STDCALL mysql_list_tables_start(MYSQL_RES **ret, MYSQL *mysql, - const char *wild); -int STDCALL mysql_list_tables_cont(MYSQL_RES **ret, MYSQL *mysql, - int status); -MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql); -int STDCALL mysql_list_processes_start(MYSQL_RES **ret, - MYSQL *mysql); -int STDCALL mysql_list_processes_cont(MYSQL_RES **ret, MYSQL *mysql, - int status); -int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option, - const void *arg); -int STDCALL mysql_options4(MYSQL *mysql,enum mysql_option option, - const void *arg1, const void *arg2); -void STDCALL mysql_free_result(MYSQL_RES *result); -int STDCALL mysql_free_result_start(MYSQL_RES *result); -int STDCALL mysql_free_result_cont(MYSQL_RES *result, int status); -void STDCALL mysql_data_seek(MYSQL_RES *result, - my_ulonglong offset); -MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result, - MYSQL_ROW_OFFSET offset); -MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result, - MYSQL_FIELD_OFFSET offset); -MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); -int STDCALL mysql_fetch_row_start(MYSQL_ROW *ret, - MYSQL_RES *result); -int STDCALL mysql_fetch_row_cont(MYSQL_ROW *ret, MYSQL_RES *result, - int status); -unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result); -MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result); -MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table, - const char *wild); -int STDCALL mysql_list_fields_start(MYSQL_RES **ret, MYSQL *mysql, - const char *table, - const char *wild); -int STDCALL mysql_list_fields_cont(MYSQL_RES **ret, MYSQL *mysql, - int status); -unsigned long STDCALL mysql_escape_string(char *to,const char *from, - unsigned long from_length); -unsigned long STDCALL mysql_hex_string(char *to,const char *from, - unsigned long from_length); -unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql, - char *to,const char *from, - unsigned long length); -void STDCALL mysql_debug(const char *debug); -void STDCALL myodbc_remove_escape(MYSQL *mysql,char *name); -unsigned int STDCALL mysql_thread_safe(void); -my_bool STDCALL mysql_embedded(void); -my_bool STDCALL mariadb_connection(MYSQL *mysql); -my_bool STDCALL mysql_read_query_result(MYSQL *mysql); -int STDCALL mysql_read_query_result_start(my_bool *ret, - MYSQL *mysql); -int STDCALL mysql_read_query_result_cont(my_bool *ret, - MYSQL *mysql, int status); - - -/* - The following definitions are added for the enhanced - client-server protocol -*/ - -/* statement state */ -enum enum_mysql_stmt_state -{ - MYSQL_STMT_INIT_DONE= 1, MYSQL_STMT_PREPARE_DONE, MYSQL_STMT_EXECUTE_DONE, - MYSQL_STMT_FETCH_DONE -}; - - -/* - This structure is used to define bind information, and - internally by the client library. - Public members with their descriptions are listed below - (conventionally `On input' refers to the binds given to - mysql_stmt_bind_param, `On output' refers to the binds given - to mysql_stmt_bind_result): - - buffer_type - One of the MYSQL_* types, used to describe - the host language type of buffer. - On output: if column type is different from - buffer_type, column value is automatically converted - to buffer_type before it is stored in the buffer. - buffer - On input: points to the buffer with input data. - On output: points to the buffer capable to store - output data. - The type of memory pointed by buffer must correspond - to buffer_type. See the correspondence table in - the comment to mysql_stmt_bind_param. - - The two above members are mandatory for any kind of bind. - - buffer_length - the length of the buffer. You don't have to set - it for any fixed length buffer: float, double, - int, etc. It must be set however for variable-length - types, such as BLOBs or STRINGs. - - length - On input: in case when lengths of input values - are different for each execute, you can set this to - point at a variable containining value length. This - way the value length can be different in each execute. - If length is not NULL, buffer_length is not used. - Note, length can even point at buffer_length if - you keep bind structures around while fetching: - this way you can change buffer_length before - each execution, everything will work ok. - On output: if length is set, mysql_stmt_fetch will - write column length into it. - - is_null - On input: points to a boolean variable that should - be set to TRUE for NULL values. - This member is useful only if your data may be - NULL in some but not all cases. - If your data is never NULL, is_null should be set to 0. - If your data is always NULL, set buffer_type - to MYSQL_TYPE_NULL, and is_null will not be used. - - is_unsigned - On input: used to signify that values provided for one - of numeric types are unsigned. - On output describes signedness of the output buffer. - If, taking into account is_unsigned flag, column data - is out of range of the output buffer, data for this column - is regarded truncated. Note that this has no correspondence - to the sign of result set column, if you need to find it out - use mysql_stmt_result_metadata. - error - where to write a truncation error if it is present. - possible error value is: - 0 no truncation - 1 value is out of range or buffer is too small - - Please note that MYSQL_BIND also has internals members. -*/ - -typedef struct st_mysql_bind -{ - unsigned long *length; /* output length pointer */ - my_bool *is_null; /* Pointer to null indicator */ - void *buffer; /* buffer to get/put data */ - /* set this if you want to track data truncations happened during fetch */ - my_bool *error; - unsigned char *row_ptr; /* for the current data position */ - void (*store_param_func)(NET *net, struct st_mysql_bind *param); - void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *, - unsigned char **row); - void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *, - unsigned char **row); - /* output buffer length, must be set when fetching str/binary */ - unsigned long buffer_length; - unsigned long offset; /* offset position for char/binary fetch */ - unsigned long length_value; /* Used if length is 0 */ - unsigned int param_number; /* For null count and error messages */ - unsigned int pack_length; /* Internal length for packed data */ - enum enum_field_types buffer_type; /* buffer type */ - my_bool error_value; /* used if error is 0 */ - my_bool is_unsigned; /* set if integer type is unsigned */ - my_bool long_data_used; /* If used with mysql_send_long_data */ - my_bool is_null_value; /* Used if is_null is 0 */ - void *extension; -} MYSQL_BIND; - - -struct st_mysql_stmt_extension; - -/* statement handler */ -typedef struct st_mysql_stmt -{ - MEM_ROOT mem_root; /* root allocations */ - LIST list; /* list to keep track of all stmts */ - MYSQL *mysql; /* connection handle */ - MYSQL_BIND *params; /* input parameters */ - MYSQL_BIND *bind; /* output parameters */ - MYSQL_FIELD *fields; /* result set metadata */ - MYSQL_DATA result; /* cached result set */ - MYSQL_ROWS *data_cursor; /* current row in cached result */ - /* - mysql_stmt_fetch() calls this function to fetch one row (it's different - for buffered, unbuffered and cursor fetch). - */ - int (*read_row_func)(struct st_mysql_stmt *stmt, - unsigned char **row); - /* copy of mysql->affected_rows after statement execution */ - my_ulonglong affected_rows; - my_ulonglong insert_id; /* copy of mysql->insert_id */ - unsigned long stmt_id; /* Id for prepared statement */ - unsigned long flags; /* i.e. type of cursor to open */ - unsigned long prefetch_rows; /* number of rows per one COM_FETCH */ - /* - Copied from mysql->server_status after execute/fetch to know - server-side cursor status for this statement. - */ - unsigned int server_status; - unsigned int last_errno; /* error code */ - unsigned int param_count; /* input parameter count */ - unsigned int field_count; /* number of columns in result set */ - enum enum_mysql_stmt_state state; /* statement state */ - char last_error[MYSQL_ERRMSG_SIZE]; /* error message */ - char sqlstate[SQLSTATE_LENGTH+1]; - /* Types of input parameters should be sent to server */ - my_bool send_types_to_server; - my_bool bind_param_done; /* input buffers were supplied */ - unsigned char bind_result_done; /* output buffers were supplied */ - /* mysql_stmt_close() had to cancel this result */ - my_bool unbuffered_fetch_cancelled; - /* - Is set to true if we need to calculate field->max_length for - metadata fields when doing mysql_stmt_store_result. - */ - my_bool update_max_length; - struct st_mysql_stmt_extension *extension; -} MYSQL_STMT; - -enum enum_stmt_attr_type -{ - /* - When doing mysql_stmt_store_result calculate max_length attribute - of statement metadata. This is to be consistent with the old API, - where this was done automatically. - In the new API we do that only by request because it slows down - mysql_stmt_store_result sufficiently. - */ - STMT_ATTR_UPDATE_MAX_LENGTH, - /* - unsigned long with combination of cursor flags (read only, for update, - etc) - */ - STMT_ATTR_CURSOR_TYPE, - /* - Amount of rows to retrieve from server per one fetch if using cursors. - Accepts unsigned long attribute in the range 1 - ulong_max - */ - STMT_ATTR_PREFETCH_ROWS -}; - -MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql); -int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, - unsigned long length); -int STDCALL mysql_stmt_prepare_start(int *ret, MYSQL_STMT *stmt, - const char *query, unsigned long length); -int STDCALL mysql_stmt_prepare_cont(int *ret, MYSQL_STMT *stmt, int status); -int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_execute_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_execute_cont(int *ret, MYSQL_STMT *stmt, int status); -int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_fetch_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_fetch_cont(int *ret, MYSQL_STMT *stmt, int status); -int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg, - unsigned int column, - unsigned long offset); -int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_store_result_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_store_result_cont(int *ret, MYSQL_STMT *stmt, - int status); -unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt); -my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt, - enum enum_stmt_attr_type attr_type, - const void *attr); -my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt, - enum enum_stmt_attr_type attr_type, - void *attr); -my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd); -my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd); -my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt); -int STDCALL mysql_stmt_close_start(my_bool *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_close_cont(my_bool *ret, MYSQL_STMT * stmt, int status); -my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt); -int STDCALL mysql_stmt_reset_start(my_bool *ret, MYSQL_STMT * stmt); -int STDCALL mysql_stmt_reset_cont(my_bool *ret, MYSQL_STMT *stmt, int status); -my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_free_result_start(my_bool *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_free_result_cont(my_bool *ret, MYSQL_STMT *stmt, - int status); -my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt, - unsigned int param_number, - const char *data, - unsigned long length); -int STDCALL mysql_stmt_send_long_data_start(my_bool *ret, MYSQL_STMT *stmt, - unsigned int param_number, - const char *data, - unsigned long len); -int STDCALL mysql_stmt_send_long_data_cont(my_bool *ret, MYSQL_STMT *stmt, - int status); -MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt); -MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt); -unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt); -const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt); -const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt); -MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt, - MYSQL_ROW_OFFSET offset); -MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt); -void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset); -my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt); -my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt); -my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt); -unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt); - -my_bool STDCALL mysql_commit(MYSQL * mysql); -int STDCALL mysql_commit_start(my_bool *ret, MYSQL * mysql); -int STDCALL mysql_commit_cont(my_bool *ret, MYSQL * mysql, int status); -my_bool STDCALL mysql_rollback(MYSQL * mysql); -int STDCALL mysql_rollback_start(my_bool *ret, MYSQL * mysql); -int STDCALL mysql_rollback_cont(my_bool *ret, MYSQL * mysql, int status); -my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode); -int STDCALL mysql_autocommit_start(my_bool *ret, MYSQL * mysql, - my_bool auto_mode); -int STDCALL mysql_autocommit_cont(my_bool *ret, MYSQL * mysql, int status); -my_bool STDCALL mysql_more_results(MYSQL *mysql); -int STDCALL mysql_next_result(MYSQL *mysql); -int STDCALL mysql_next_result_start(int *ret, MYSQL *mysql); -int STDCALL mysql_next_result_cont(int *ret, MYSQL *mysql, int status); -int STDCALL mysql_stmt_next_result(MYSQL_STMT *stmt); -int STDCALL mysql_stmt_next_result_start(int *ret, MYSQL_STMT *stmt); -int STDCALL mysql_stmt_next_result_cont(int *ret, MYSQL_STMT *stmt, int status); -void STDCALL mysql_close_slow_part(MYSQL *mysql); -void STDCALL mysql_close(MYSQL *sock); -int STDCALL mysql_close_start(MYSQL *sock); -int STDCALL mysql_close_cont(MYSQL *sock, int status); -my_socket STDCALL mysql_get_socket(const MYSQL *mysql); -unsigned int STDCALL mysql_get_timeout_value(const MYSQL *mysql); -unsigned int STDCALL mysql_get_timeout_value_ms(const MYSQL *mysql); - -/******************************************************************** - mysql_net_ functions - low-level API to MySQL protocol -*********************************************************************/ -unsigned long STDCALL mysql_net_read_packet(MYSQL *mysql); -unsigned long STDCALL mysql_net_field_length(unsigned char **packet); - -/* status return codes */ -#define MYSQL_NO_DATA 100 -#define MYSQL_DATA_TRUNCATED 101 - -#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT) - -#ifdef USE_OLD_FUNCTIONS -MYSQL * STDCALL mysql_connect(MYSQL *mysql, const char *host, - const char *user, const char *passwd); -int STDCALL mysql_create_db(MYSQL *mysql, const char *DB); -int STDCALL mysql_drop_db(MYSQL *mysql, const char *DB); -#endif -#define HAVE_MYSQL_REAL_CONNECT - -#ifdef __cplusplus -} -#endif - -#endif /* _mysql_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/auth_dialog_client.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/auth_dialog_client.h deleted file mode 100644 index f1ad3e6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/auth_dialog_client.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef MYSQL_AUTH_DIALOG_CLIENT_INCLUDED -/* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Definitions needed to use Dialog client authentication plugin -*/ - -struct st_mysql; - -#define MYSQL_AUTH_DIALOG_CLIENT_INCLUDED - -/** - type of the mysql_authentication_dialog_ask function - - @param mysql mysql - @param type type of the input - 1 - ordinary string input - 2 - password string - @param prompt prompt - @param buf a buffer to store the use input - @param buf_len the length of the buffer - - @retval a pointer to the user input string. - It may be equal to 'buf' or to 'mysql->password'. - In all other cases it is assumed to be an allocated - string, and the "dialog" plugin will free() it. -*/ -typedef char *(*mysql_authentication_dialog_ask_t)(struct st_mysql *mysql, - int type, const char *prompt, char *buf, int buf_len); - -/** - first byte of the question string is the question "type". - It can be an "ordinary" or a "password" question. - The last bit set marks a last question in the authentication exchange. -*/ -#define ORDINARY_QUESTION "\2" -#define LAST_QUESTION "\3" -#define PASSWORD_QUESTION "\4" -#define LAST_PASSWORD "\5" - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/client_plugin.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/client_plugin.h deleted file mode 100644 index 990cecc..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/client_plugin.h +++ /dev/null @@ -1,188 +0,0 @@ -#ifndef MYSQL_CLIENT_PLUGIN_INCLUDED -/* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab - Copyright (c) 2010, 2011, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - MySQL Client Plugin API - - This file defines the API for plugins that work on the client side -*/ -#define MYSQL_CLIENT_PLUGIN_INCLUDED - -/* - On Windows, exports from DLL need to be declared - Also, plugin needs to be declared as extern "C" because MSVC - unlike other compilers, uses C++ mangling for variables not only - for functions. -*/ -#undef MYSQL_PLUGIN_EXPORT -#if defined(_MSC_VER) - #define MYSQL_PLUGIN_EXPORT_C __declspec(dllexport) -#else /*_MSC_VER */ - #define MYSQL_PLUGIN_EXPORT_C -#endif -#ifdef __cplusplus -#define MYSQL_PLUGIN_EXPORT extern "C" MYSQL_PLUGIN_EXPORT_C -#define C_MODE_START extern "C" { -#define C_MODE_END } -#else -#define MYSQL_PLUGIN_EXPORT MYSQL_PLUGIN_EXPORT_C -#define C_MODE_START -#define C_MODE_END -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#include -#endif - -/* known plugin types */ -#define MYSQL_CLIENT_reserved1 0 -#define MYSQL_CLIENT_reserved2 1 -#define MYSQL_CLIENT_AUTHENTICATION_PLUGIN 2 - -#define MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION 0x0100 - -#define MYSQL_CLIENT_MAX_PLUGINS 3 - -#define mysql_declare_client_plugin(X) \ - C_MODE_START MYSQL_PLUGIN_EXPORT_C \ - struct st_mysql_client_plugin_ ## X \ - _mysql_client_plugin_declaration_ = { \ - MYSQL_CLIENT_ ## X ## _PLUGIN, \ - MYSQL_CLIENT_ ## X ## _PLUGIN_INTERFACE_VERSION, -#define mysql_end_client_plugin }; C_MODE_END - -/* generic plugin header structure */ -#define MYSQL_CLIENT_PLUGIN_HEADER \ - int type; \ - unsigned int interface_version; \ - const char *name; \ - const char *author; \ - const char *desc; \ - unsigned int version[3]; \ - const char *license; \ - void *mysql_api; \ - int (*init)(char *, size_t, int, va_list); \ - int (*deinit)(); \ - int (*options)(const char *option, const void *); - -struct st_mysql_client_plugin -{ - MYSQL_CLIENT_PLUGIN_HEADER -}; - -struct st_mysql; - -/******** authentication plugin specific declarations *********/ -#include - -struct st_mysql_client_plugin_AUTHENTICATION -{ - MYSQL_CLIENT_PLUGIN_HEADER - int (*authenticate_user)(MYSQL_PLUGIN_VIO *vio, struct st_mysql *mysql); -}; - -#include - -/******** using plugins ************/ - -/** - loads a plugin and initializes it - - @param mysql MYSQL structure. - @param name a name of the plugin to load - @param type type of plugin that should be loaded, -1 to disable type check - @param argc number of arguments to pass to the plugin initialization - function - @param ... arguments for the plugin initialization function - - @retval - a pointer to the loaded plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * -mysql_load_plugin(struct st_mysql *mysql, const char *name, int type, - int argc, ...); - -/** - loads a plugin and initializes it, taking va_list as an argument - - This is the same as mysql_load_plugin, but take va_list instead of - a list of arguments. - - @param mysql MYSQL structure. - @param name a name of the plugin to load - @param type type of plugin that should be loaded, -1 to disable type check - @param argc number of arguments to pass to the plugin initialization - function - @param args arguments for the plugin initialization function - - @retval - a pointer to the loaded plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * -mysql_load_plugin_v(struct st_mysql *mysql, const char *name, int type, - int argc, va_list args); - -/** - finds an already loaded plugin by name, or loads it, if necessary - - @param mysql MYSQL structure. - @param name a name of the plugin to load - @param type type of plugin that should be loaded - - @retval - a pointer to the plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * -mysql_client_find_plugin(struct st_mysql *mysql, const char *name, int type); - -/** - adds a plugin structure to the list of loaded plugins - - This is useful if an application has the necessary functionality - (for example, a special load data handler) statically linked into - the application binary. It can use this function to register the plugin - directly, avoiding the need to factor it out into a shared object. - - @param mysql MYSQL structure. It is only used for error reporting - @param plugin an st_mysql_client_plugin structure to register - - @retval - a pointer to the plugin, or NULL in case of a failure -*/ -struct st_mysql_client_plugin * -mysql_client_register_plugin(struct st_mysql *mysql, - struct st_mysql_client_plugin *plugin); - -/** - set plugin options - - Can be used to set extra options and affect behavior for a plugin. - This function may be called multiple times to set several options - - @param plugin an st_mysql_client_plugin structure - @param option a string which specifies the option to set - @param value value for the option. - - @retval 0 on success, 1 in case of failure -**/ -int mysql_plugin_options(struct st_mysql_client_plugin *plugin, - const char *option, const void *value); -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin.h deleted file mode 100644 index 07e7597..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin.h +++ /dev/null @@ -1,767 +0,0 @@ -/* Copyright (c) 2005, 2013, Oracle and/or its affiliates - Copyright (C) 2009, 2017, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_PLUGIN_INCLUDED -#define MYSQL_PLUGIN_INCLUDED - -/* - On Windows, exports from DLL need to be declared - Also, plugin needs to be declared as extern "C" because MSVC - unlike other compilers, uses C++ mangling for variables not only - for functions. -*/ -#ifdef MYSQL_DYNAMIC_PLUGIN - #ifdef _MSC_VER - #define MYSQL_DLLEXPORT _declspec(dllexport) - #else - #define MYSQL_DLLEXPORT - #endif -#else - #define MYSQL_DLLEXPORT -#endif - -#ifdef __cplusplus - #define MYSQL_PLUGIN_EXPORT extern "C" MYSQL_DLLEXPORT -#else - #define MYSQL_PLUGIN_EXPORT MYSQL_DLLEXPORT -#endif - -#ifdef __cplusplus -class THD; -class Item; -#define MYSQL_THD THD* -#else -#define MYSQL_THD void* -#endif - -typedef char my_bool; -typedef void * MYSQL_PLUGIN; - -#include - -#define MYSQL_XIDDATASIZE 128 -/** - struct st_mysql_xid is binary compatible with the XID structure as - in the X/Open CAE Specification, Distributed Transaction Processing: - The XA Specification, X/Open Company Ltd., 1991. - http://www.opengroup.org/bookstore/catalog/c193.htm - - @see XID in sql/handler.h -*/ -struct st_mysql_xid { - long formatID; - long gtrid_length; - long bqual_length; - char data[MYSQL_XIDDATASIZE]; /* Not \0-terminated */ -}; -typedef struct st_mysql_xid MYSQL_XID; - -/************************************************************************* - Plugin API. Common for all plugin types. -*/ - -/* MySQL plugin interface version */ -#define MYSQL_PLUGIN_INTERFACE_VERSION 0x0104 - -/* MariaDB plugin interface version */ -#define MARIA_PLUGIN_INTERFACE_VERSION 0x010e - -/* - The allowable types of plugins -*/ -#define MYSQL_UDF_PLUGIN 0 /* not implemented */ -#define MYSQL_STORAGE_ENGINE_PLUGIN 1 -#define MYSQL_FTPARSER_PLUGIN 2 /* Full-text parser plugin */ -#define MYSQL_DAEMON_PLUGIN 3 -#define MYSQL_INFORMATION_SCHEMA_PLUGIN 4 -#define MYSQL_AUDIT_PLUGIN 5 -#define MYSQL_REPLICATION_PLUGIN 6 -#define MYSQL_AUTHENTICATION_PLUGIN 7 -#define MYSQL_MAX_PLUGIN_TYPE_NUM 12 /* The number of plugin types */ - -/* MariaDB plugin types */ -#define MariaDB_PASSWORD_VALIDATION_PLUGIN 8 -#define MariaDB_ENCRYPTION_PLUGIN 9 -#define MariaDB_DATA_TYPE_PLUGIN 10 -#define MariaDB_FUNCTION_PLUGIN 11 - -/* We use the following strings to define licenses for plugins */ -#define PLUGIN_LICENSE_PROPRIETARY 0 -#define PLUGIN_LICENSE_GPL 1 -#define PLUGIN_LICENSE_BSD 2 - -#define PLUGIN_LICENSE_PROPRIETARY_STRING "PROPRIETARY" -#define PLUGIN_LICENSE_GPL_STRING "GPL" -#define PLUGIN_LICENSE_BSD_STRING "BSD" - -/* definitions of code maturity for plugins */ -#define MariaDB_PLUGIN_MATURITY_UNKNOWN 0 -#define MariaDB_PLUGIN_MATURITY_EXPERIMENTAL 1 -#define MariaDB_PLUGIN_MATURITY_ALPHA 2 -#define MariaDB_PLUGIN_MATURITY_BETA 3 -#define MariaDB_PLUGIN_MATURITY_GAMMA 4 -#define MariaDB_PLUGIN_MATURITY_STABLE 5 - -/* - Macros for beginning and ending plugin declarations. Between - mysql_declare_plugin and mysql_declare_plugin_end there should - be a st_mysql_plugin struct for each plugin to be declared. -*/ - - -#ifndef MYSQL_DYNAMIC_PLUGIN -#define __MYSQL_DECLARE_PLUGIN(NAME, VERSION, PSIZE, DECLS) \ -int VERSION= MYSQL_PLUGIN_INTERFACE_VERSION; \ -int PSIZE= sizeof(struct st_mysql_plugin); \ -struct st_mysql_plugin DECLS[]= { - -#define MARIA_DECLARE_PLUGIN__(NAME, VERSION, PSIZE, DECLS) \ -MYSQL_PLUGIN_EXPORT int VERSION; \ -int VERSION= MARIA_PLUGIN_INTERFACE_VERSION; \ -MYSQL_PLUGIN_EXPORT int PSIZE; \ -int PSIZE= sizeof(struct st_maria_plugin); \ -MYSQL_PLUGIN_EXPORT struct st_maria_plugin DECLS[]; \ -struct st_maria_plugin DECLS[]= { -#else - -#define __MYSQL_DECLARE_PLUGIN(NAME, VERSION, PSIZE, DECLS) \ -MYSQL_PLUGIN_EXPORT int _mysql_plugin_interface_version_; \ -int _mysql_plugin_interface_version_= MYSQL_PLUGIN_INTERFACE_VERSION; \ -MYSQL_PLUGIN_EXPORT int _mysql_sizeof_struct_st_plugin_; \ -int _mysql_sizeof_struct_st_plugin_= sizeof(struct st_mysql_plugin); \ -MYSQL_PLUGIN_EXPORT struct st_mysql_plugin _mysql_plugin_declarations_[]; \ -struct st_mysql_plugin _mysql_plugin_declarations_[]= { - -#define MARIA_DECLARE_PLUGIN__(NAME, VERSION, PSIZE, DECLS) \ -MYSQL_PLUGIN_EXPORT int _maria_plugin_interface_version_; \ -int _maria_plugin_interface_version_= MARIA_PLUGIN_INTERFACE_VERSION; \ -MYSQL_PLUGIN_EXPORT int _maria_sizeof_struct_st_plugin_; \ -int _maria_sizeof_struct_st_plugin_= sizeof(struct st_maria_plugin); \ -MYSQL_PLUGIN_EXPORT struct st_maria_plugin _maria_plugin_declarations_[]; \ -struct st_maria_plugin _maria_plugin_declarations_[]= { - -#endif - -#define mysql_declare_plugin(NAME) \ -__MYSQL_DECLARE_PLUGIN(NAME, \ - builtin_ ## NAME ## _plugin_interface_version, \ - builtin_ ## NAME ## _sizeof_struct_st_plugin, \ - builtin_ ## NAME ## _plugin) - -#define maria_declare_plugin(NAME) \ -MARIA_DECLARE_PLUGIN__(NAME, \ - builtin_maria_ ## NAME ## _plugin_interface_version, \ - builtin_maria_ ## NAME ## _sizeof_struct_st_plugin, \ - builtin_maria_ ## NAME ## _plugin) - -#define mysql_declare_plugin_end ,{0,0,0,0,0,0,0,0,0,0,0,0,0}} -#define maria_declare_plugin_end ,{0,0,0,0,0,0,0,0,0,0,0,0,0}} - -/* - declarations for SHOW STATUS support in plugins -*/ -enum enum_mysql_show_type -{ - SHOW_UNDEF, SHOW_BOOL, SHOW_UINT, SHOW_ULONG, - SHOW_ULONGLONG, SHOW_CHAR, SHOW_CHAR_PTR, - SHOW_ARRAY, SHOW_FUNC, SHOW_DOUBLE, - SHOW_SINT, SHOW_SLONG, SHOW_SLONGLONG, SHOW_SIMPLE_FUNC, - SHOW_SIZE_T, SHOW_always_last -}; - -/* backward compatibility mapping. */ -#define SHOW_INT SHOW_UINT -#define SHOW_LONG SHOW_ULONG -#define SHOW_LONGLONG SHOW_ULONGLONG - -enum enum_var_type -{ - SHOW_OPT_DEFAULT= 0, SHOW_OPT_SESSION, SHOW_OPT_GLOBAL -}; - -struct st_mysql_show_var { - const char *name; - void *value; - enum enum_mysql_show_type type; -}; - -struct system_status_var; - -#define SHOW_VAR_FUNC_BUFF_SIZE (256 * sizeof(void*)) -typedef int (*mysql_show_var_func)(MYSQL_THD, struct st_mysql_show_var*, void *, struct system_status_var *status_var, enum enum_var_type); - - -/* - Constants for plugin flags. - */ - -#define PLUGIN_OPT_NO_INSTALL 1UL /* Not dynamically loadable */ -#define PLUGIN_OPT_NO_UNINSTALL 2UL /* Not dynamically unloadable */ - - -/* - declarations for server variables and command line options -*/ - - -#define PLUGIN_VAR_BOOL 0x0001 -#define PLUGIN_VAR_INT 0x0002 -#define PLUGIN_VAR_LONG 0x0003 -#define PLUGIN_VAR_LONGLONG 0x0004 -#define PLUGIN_VAR_STR 0x0005 -#define PLUGIN_VAR_ENUM 0x0006 -#define PLUGIN_VAR_SET 0x0007 -#define PLUGIN_VAR_DOUBLE 0x0008 -#define PLUGIN_VAR_UNSIGNED 0x0080 -#define PLUGIN_VAR_THDLOCAL 0x0100 /* Variable is per-connection */ -#define PLUGIN_VAR_READONLY 0x0200 /* Server variable is read only */ -#define PLUGIN_VAR_NOSYSVAR 0x0400 /* Not a server variable */ -#define PLUGIN_VAR_NOCMDOPT 0x0800 /* Not a command line option */ -#define PLUGIN_VAR_NOCMDARG 0x1000 /* No argument for cmd line */ -#define PLUGIN_VAR_RQCMDARG 0x0000 /* Argument required for cmd line */ -#define PLUGIN_VAR_OPCMDARG 0x2000 /* Argument optional for cmd line */ -#define PLUGIN_VAR_MEMALLOC 0x8000 /* String needs memory allocated */ - -struct st_mysql_sys_var; -struct st_mysql_value; - -/* - SYNOPSIS - (*mysql_var_check_func)() - thd thread handle - var dynamic variable being altered - save pointer to temporary storage - value user provided value - RETURN - 0 user provided value is OK and the update func may be called. - any other value indicates error. - - This function should parse the user provided value and store in the - provided temporary storage any data as required by the update func. - There is sufficient space in the temporary storage to store a double. - Note that the update func may not be called if any other error occurs - so any memory allocated should be thread-local so that it may be freed - automatically at the end of the statement. -*/ - -typedef int (*mysql_var_check_func)(MYSQL_THD thd, - struct st_mysql_sys_var *var, - void *save, struct st_mysql_value *value); - -/* - SYNOPSIS - (*mysql_var_update_func)() - thd thread handle - var dynamic variable being altered - var_ptr pointer to dynamic variable - save pointer to temporary storage - RETURN - NONE - - This function should use the validated value stored in the temporary store - and persist it in the provided pointer to the dynamic variable. - For example, strings may require memory to be allocated. -*/ -typedef void (*mysql_var_update_func)(MYSQL_THD thd, - struct st_mysql_sys_var *var, - void *var_ptr, const void *save); - - -/* the following declarations are for internal use only */ - - -#define PLUGIN_VAR_MASK \ - (PLUGIN_VAR_READONLY | PLUGIN_VAR_NOSYSVAR | \ - PLUGIN_VAR_NOCMDOPT | PLUGIN_VAR_NOCMDARG | \ - PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_RQCMDARG | PLUGIN_VAR_MEMALLOC) - -#define MYSQL_PLUGIN_VAR_HEADER \ - int flags; \ - const char *name; \ - const char *comment; \ - mysql_var_check_func check; \ - mysql_var_update_func update - -#define MYSQL_SYSVAR_NAME(name) mysql_sysvar_ ## name -#define MYSQL_SYSVAR(name) \ - ((struct st_mysql_sys_var *)&(MYSQL_SYSVAR_NAME(name))) - -/* - for global variables, the value pointer is the first - element after the header, the default value is the second. - for thread variables, the value offset is the first - element after the header, the default value is the second. -*/ - - -#define DECLARE_MYSQL_SYSVAR_BASIC(name, type) struct { \ - MYSQL_PLUGIN_VAR_HEADER; \ - type *value; \ - const type def_val; \ -} MYSQL_SYSVAR_NAME(name) - -#define DECLARE_MYSQL_SYSVAR_SIMPLE(name, type) struct { \ - MYSQL_PLUGIN_VAR_HEADER; \ - type *value; type def_val; \ - type min_val; type max_val; \ - type blk_sz; \ -} MYSQL_SYSVAR_NAME(name) - -#define DECLARE_MYSQL_SYSVAR_TYPELIB(name, type) struct { \ - MYSQL_PLUGIN_VAR_HEADER; \ - type *value; type def_val; \ - TYPELIB *typelib; \ -} MYSQL_SYSVAR_NAME(name) - -#define DECLARE_THDVAR_FUNC(type) \ - type *(*resolve)(MYSQL_THD thd, int offset) - -#define DECLARE_MYSQL_THDVAR_BASIC(name, type) struct { \ - MYSQL_PLUGIN_VAR_HEADER; \ - int offset; \ - const type def_val; \ - DECLARE_THDVAR_FUNC(type); \ -} MYSQL_SYSVAR_NAME(name) - -#define DECLARE_MYSQL_THDVAR_SIMPLE(name, type) struct { \ - MYSQL_PLUGIN_VAR_HEADER; \ - int offset; \ - type def_val; type min_val; \ - type max_val; type blk_sz; \ - DECLARE_THDVAR_FUNC(type); \ -} MYSQL_SYSVAR_NAME(name) - -#define DECLARE_MYSQL_THDVAR_TYPELIB(name, type) struct { \ - MYSQL_PLUGIN_VAR_HEADER; \ - int offset; \ - const type def_val; \ - DECLARE_THDVAR_FUNC(type); \ - TYPELIB *typelib; \ -} MYSQL_SYSVAR_NAME(name) - - -/* - the following declarations are for use by plugin implementors -*/ - -#define MYSQL_SYSVAR_BOOL(name, varname, opt, comment, check, update, def) \ -DECLARE_MYSQL_SYSVAR_BASIC(name, char) = { \ - PLUGIN_VAR_BOOL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def} - -#define MYSQL_SYSVAR_STR(name, varname, opt, comment, check, update, def) \ -DECLARE_MYSQL_SYSVAR_BASIC(name, char *) = { \ - PLUGIN_VAR_STR | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def} - -#define MYSQL_SYSVAR_INT(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, int) = { \ - PLUGIN_VAR_INT | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#define MYSQL_SYSVAR_UINT(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, unsigned int) = { \ - PLUGIN_VAR_INT | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#define MYSQL_SYSVAR_LONG(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, long) = { \ - PLUGIN_VAR_LONG | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#define MYSQL_SYSVAR_ULONG(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, unsigned long) = { \ - PLUGIN_VAR_LONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#define MYSQL_SYSVAR_LONGLONG(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, long long) = { \ - PLUGIN_VAR_LONGLONG | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#define MYSQL_SYSVAR_ULONGLONG(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, unsigned long long) = { \ - PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#define MYSQL_SYSVAR_UINT64_T(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, uint64_t) = { \ - PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#ifdef _WIN64 -#define MYSQL_SYSVAR_SIZE_T(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, size_t) = { \ - PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } -#else -#define MYSQL_SYSVAR_SIZE_T(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, size_t) = { \ - PLUGIN_VAR_LONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } -#endif - -#define MYSQL_SYSVAR_ENUM(name, varname, opt, comment, check, update, def, typelib) \ -DECLARE_MYSQL_SYSVAR_TYPELIB(name, unsigned long) = { \ - PLUGIN_VAR_ENUM | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, typelib } - -#define MYSQL_SYSVAR_SET(name, varname, opt, comment, check, update, def, typelib) \ -DECLARE_MYSQL_SYSVAR_TYPELIB(name, unsigned long long) = { \ - PLUGIN_VAR_SET | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, typelib } - -#define MYSQL_SYSVAR_DOUBLE(name, varname, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_SYSVAR_SIMPLE(name, double) = { \ - PLUGIN_VAR_DOUBLE | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, &varname, def, min, max, blk } - -#define MYSQL_THDVAR_BOOL(name, opt, comment, check, update, def) \ -DECLARE_MYSQL_THDVAR_BASIC(name, char) = { \ - PLUGIN_VAR_BOOL | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, NULL} - -#define MYSQL_THDVAR_STR(name, opt, comment, check, update, def) \ -DECLARE_MYSQL_THDVAR_BASIC(name, char *) = { \ - PLUGIN_VAR_STR | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, NULL} - -#define MYSQL_THDVAR_INT(name, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_THDVAR_SIMPLE(name, int) = { \ - PLUGIN_VAR_INT | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, min, max, blk, NULL } - -#define MYSQL_THDVAR_UINT(name, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_THDVAR_SIMPLE(name, unsigned int) = { \ - PLUGIN_VAR_INT | PLUGIN_VAR_THDLOCAL | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, min, max, blk, NULL } - -#define MYSQL_THDVAR_LONG(name, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_THDVAR_SIMPLE(name, long) = { \ - PLUGIN_VAR_LONG | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, min, max, blk, NULL } - -#define MYSQL_THDVAR_ULONG(name, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_THDVAR_SIMPLE(name, unsigned long) = { \ - PLUGIN_VAR_LONG | PLUGIN_VAR_THDLOCAL | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, min, max, blk, NULL } - -#define MYSQL_THDVAR_LONGLONG(name, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_THDVAR_SIMPLE(name, long long) = { \ - PLUGIN_VAR_LONGLONG | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, min, max, blk, NULL } - -#define MYSQL_THDVAR_ULONGLONG(name, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_THDVAR_SIMPLE(name, unsigned long long) = { \ - PLUGIN_VAR_LONGLONG | PLUGIN_VAR_THDLOCAL | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, min, max, blk, NULL } - -#define MYSQL_THDVAR_ENUM(name, opt, comment, check, update, def, typelib) \ -DECLARE_MYSQL_THDVAR_TYPELIB(name, unsigned long) = { \ - PLUGIN_VAR_ENUM | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, NULL, typelib } - -#define MYSQL_THDVAR_SET(name, opt, comment, check, update, def, typelib) \ -DECLARE_MYSQL_THDVAR_TYPELIB(name, unsigned long long) = { \ - PLUGIN_VAR_SET | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, NULL, typelib } - -#define MYSQL_THDVAR_DOUBLE(name, opt, comment, check, update, def, min, max, blk) \ -DECLARE_MYSQL_THDVAR_SIMPLE(name, double) = { \ - PLUGIN_VAR_DOUBLE | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ - #name, comment, check, update, -1, def, min, max, blk, NULL } - -/* accessor macros */ - -#define SYSVAR(name) \ - (*(MYSQL_SYSVAR_NAME(name).value)) - -/* when thd == null, result points to global value */ -#define THDVAR(thd, name) \ - (*(MYSQL_SYSVAR_NAME(name).resolve(thd, MYSQL_SYSVAR_NAME(name).offset))) - - -/* - Plugin description structure. -*/ - -struct st_mysql_plugin -{ - int type; /* the plugin type (a MYSQL_XXX_PLUGIN value) */ - void *info; /* pointer to type-specific plugin descriptor */ - const char *name; /* plugin name */ - const char *author; /* plugin author (for I_S.PLUGINS) */ - const char *descr; /* general descriptive text (for I_S.PLUGINS) */ - int license; /* the plugin license (PLUGIN_LICENSE_XXX) */ - int (*init)(void *); /* the function to invoke when plugin is loaded */ - int (*deinit)(void *);/* the function to invoke when plugin is unloaded */ - unsigned int version; /* plugin version (for I_S.PLUGINS) */ - struct st_mysql_show_var *status_vars; - struct st_mysql_sys_var **system_vars; - void * __reserved1; /* reserved for dependency checking */ - unsigned long flags; /* flags for plugin */ -}; - -/* - MariaDB extension for plugins declaration structure. - - It also copy current MySQL plugin fields to have more independency - in plugins extension -*/ - -struct st_maria_plugin -{ - int type; /* the plugin type (a MYSQL_XXX_PLUGIN value) */ - void *info; /* pointer to type-specific plugin descriptor */ - const char *name; /* plugin name */ - const char *author; /* plugin author (for SHOW PLUGINS) */ - const char *descr; /* general descriptive text (for SHOW PLUGINS ) */ - int license; /* the plugin license (PLUGIN_LICENSE_XXX) */ - int (*init)(void *); /* the function to invoke when plugin is loaded */ - int (*deinit)(void *);/* the function to invoke when plugin is unloaded */ - unsigned int version; /* plugin version (for SHOW PLUGINS) */ - struct st_mysql_show_var *status_vars; - struct st_mysql_sys_var **system_vars; - const char *version_info; /* plugin version string */ - unsigned int maturity; /* MariaDB_PLUGIN_MATURITY_XXX */ -}; - -/************************************************************************* - API for Full-text parser plugin. (MYSQL_FTPARSER_PLUGIN) -*/ -#include "plugin_ftparser.h" - -/************************************************************************* - API for Storage Engine plugin. (MYSQL_DAEMON_PLUGIN) -*/ - -/* handlertons of different MySQL releases are incompatible */ -#define MYSQL_DAEMON_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) - -/* - Here we define only the descriptor structure, that is referred from - st_mysql_plugin. -*/ - -struct st_mysql_daemon -{ - int interface_version; -}; - - -/************************************************************************* - API for I_S plugin. (MYSQL_INFORMATION_SCHEMA_PLUGIN) -*/ - -/* handlertons of different MySQL releases are incompatible */ -#define MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) - -/* - Here we define only the descriptor structure, that is referred from - st_mysql_plugin. -*/ - -struct st_mysql_information_schema -{ - int interface_version; -}; - - -/************************************************************************* - API for Storage Engine plugin. (MYSQL_STORAGE_ENGINE_PLUGIN) -*/ - -/* handlertons of different MySQL releases are incompatible */ -#define MYSQL_HANDLERTON_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) - -/* - The real API is in the sql/handler.h - Here we define only the descriptor structure, that is referred from - st_mysql_plugin. -*/ - -struct st_mysql_storage_engine -{ - int interface_version; -}; - -struct handlerton; - - -/* - API for Replication plugin. (MYSQL_REPLICATION_PLUGIN) -*/ - #define MYSQL_REPLICATION_INTERFACE_VERSION 0x0200 - - /** - Replication plugin descriptor - */ - struct Mysql_replication { - int interface_version; - }; - -/************************************************************************* - st_mysql_value struct for reading values from mysqld. - Used by server variables framework to parse user-provided values. - Will be used for arguments when implementing UDFs. - - Note that val_str() returns a string in temporary memory - that will be freed at the end of statement. Copy the string - if you need it to persist. -*/ - -#define MYSQL_VALUE_TYPE_STRING 0 -#define MYSQL_VALUE_TYPE_REAL 1 -#define MYSQL_VALUE_TYPE_INT 2 - -struct st_mysql_value -{ - int (*value_type)(struct st_mysql_value *); - const char *(*val_str)(struct st_mysql_value *, char *buffer, int *length); - int (*val_real)(struct st_mysql_value *, double *realbuf); - int (*val_int)(struct st_mysql_value *, long long *intbuf); - int (*is_unsigned)(struct st_mysql_value *); -}; - - -/************************************************************************* - Miscellaneous functions for plugin implementors -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -int thd_in_lock_tables(const MYSQL_THD thd); -int thd_tablespace_op(const MYSQL_THD thd); -long long thd_test_options(const MYSQL_THD thd, long long test_options); -int thd_sql_command(const MYSQL_THD thd); -void thd_storage_lock_wait(MYSQL_THD thd, long long value); -int thd_tx_isolation(const MYSQL_THD thd); -int thd_tx_is_read_only(const MYSQL_THD thd); -/** - Create a temporary file. - - @details - The temporary file is created in a location specified by the mysql - server configuration (--tmpdir option). The caller does not need to - delete the file, it will be deleted automatically. - - @param prefix prefix for temporary file name - @retval -1 error - @retval >= 0 a file handle that can be passed to dup or my_close -*/ -int mysql_tmpfile(const char *prefix); - -/** - Return the thread id of a user thread - - @param thd user thread connection handle - @return thread id -*/ -unsigned long thd_get_thread_id(const MYSQL_THD thd); - -/** - Get the XID for this connection's transaction - - @param thd user thread connection handle - @param xid location where identifier is stored -*/ -void thd_get_xid(const MYSQL_THD thd, MYSQL_XID *xid); - -/** - Invalidate the query cache for a given table. - - @param thd user thread connection handle - @param key databasename\\0tablename\\0 - @param key_length length of key in bytes, including the NUL bytes - @param using_trx flag: TRUE if using transactions, FALSE otherwise -*/ -void mysql_query_cache_invalidate4(MYSQL_THD thd, - const char *key, unsigned int key_length, - int using_trx); - - -/** - Provide a handler data getter to simplify coding -*/ -void *thd_get_ha_data(const MYSQL_THD thd, const struct handlerton *hton); - - -/** - Provide a handler data setter to simplify coding - - @details - Set ha_data pointer (storage engine per-connection information). - - To avoid unclean deactivation (uninstall) of storage engine plugin - in the middle of transaction, additional storage engine plugin - lock is acquired. - - If ha_data is not null and storage engine plugin was not locked - by thd_set_ha_data() in this connection before, storage engine - plugin gets locked. - - If ha_data is null and storage engine plugin was locked by - thd_set_ha_data() in this connection before, storage engine - plugin lock gets released. - - If handlerton::close_connection() didn't reset ha_data, server does - it immediately after calling handlerton::close_connection(). -*/ -void thd_set_ha_data(MYSQL_THD thd, const struct handlerton *hton, - const void *ha_data); - - -/** - Signal that the first part of handler commit is finished, and that the - committed transaction is now visible and has fixed commit ordering with - respect to other transactions. The commit need _not_ be durable yet, and - typically will not be when this call makes sense. - - This call is optional, if the storage engine does not call it the upper - layer will after the handler commit() method is done. However, the storage - engine may choose to call it itself to increase the possibility for group - commit. - - In-order parallel replication uses this to apply different transaction in - parallel, but delay the commits of later transactions until earlier - transactions have committed first, thus achieving increased performance on - multi-core systems while still preserving full transaction consistency. - - The storage engine can call this from within the commit() method, typically - after the commit record has been written to the transaction log, but before - the log has been fsync()'ed. This will allow the next replicated transaction - to proceed to commit before the first one has done fsync() or similar. Thus, - it becomes possible for multiple sequential replicated transactions to share - a single fsync() inside the engine in group commit. - - Note that this method should _not_ be called from within the commit_ordered() - method, or any other place in the storage engine. When commit_ordered() is - used (typically when binlog is enabled), the transaction coordinator takes - care of this and makes group commit in the storage engine possible without - any other action needed on the part of the storage engine. This function - thd_wakeup_subsequent_commits() is only needed when no transaction - coordinator is used, meaning a single storage engine and no binary log. -*/ -void thd_wakeup_subsequent_commits(MYSQL_THD thd, int wakeup_error); - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_audit.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_audit.h deleted file mode 100644 index e99c013..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_audit.h +++ /dev/null @@ -1,180 +0,0 @@ -/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_audit_h -#define _my_audit_h - -/************************************************************************* - API for Audit plugin. (MYSQL_AUDIT_PLUGIN) -*/ - -#include "plugin.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define MYSQL_AUDIT_CLASS_MASK_SIZE 1 - -#define MYSQL_AUDIT_INTERFACE_VERSION 0x0302 - - -/************************************************************************* - AUDIT CLASS : GENERAL - - LOG events occurs before emitting to the general query log. - ERROR events occur before transmitting errors to the user. - RESULT events occur after transmitting a resultset to the user. - STATUS events occur after transmitting a resultset or errors - to the user. -*/ - -#define MYSQL_AUDIT_GENERAL_CLASS 0 -#define MYSQL_AUDIT_GENERAL_CLASSMASK (1 << MYSQL_AUDIT_GENERAL_CLASS) -#define MYSQL_AUDIT_GENERAL_LOG 0 -#define MYSQL_AUDIT_GENERAL_ERROR 1 -#define MYSQL_AUDIT_GENERAL_RESULT 2 -#define MYSQL_AUDIT_GENERAL_STATUS 3 - -struct mysql_event_general -{ - unsigned int event_subclass; - int general_error_code; - unsigned long general_thread_id; - const char *general_user; - unsigned int general_user_length; - const char *general_command; - unsigned int general_command_length; - const char *general_query; - unsigned int general_query_length; - const struct charset_info_st *general_charset; - unsigned long long general_time; - unsigned long long general_rows; - /* Added in version 0x302 */ - unsigned long long query_id; - MYSQL_CONST_LEX_STRING database; -}; - - -/* - AUDIT CLASS : CONNECTION - - CONNECT occurs after authentication phase is completed. - DISCONNECT occurs after connection is terminated. - CHANGE_USER occurs after COM_CHANGE_USER RPC is completed. -*/ - -#define MYSQL_AUDIT_CONNECTION_CLASS 1 -#define MYSQL_AUDIT_CONNECTION_CLASSMASK (1 << MYSQL_AUDIT_CONNECTION_CLASS) -#define MYSQL_AUDIT_CONNECTION_CONNECT 0 -#define MYSQL_AUDIT_CONNECTION_DISCONNECT 1 -#define MYSQL_AUDIT_CONNECTION_CHANGE_USER 2 - -struct mysql_event_connection -{ - unsigned int event_subclass; - int status; - unsigned long thread_id; - const char *user; - unsigned int user_length; - const char *priv_user; - unsigned int priv_user_length; - const char *external_user; - unsigned int external_user_length; - const char *proxy_user; - unsigned int proxy_user_length; - const char *host; - unsigned int host_length; - const char *ip; - unsigned int ip_length; - MYSQL_CONST_LEX_STRING database; -}; - -/* - AUDIT CLASS : TABLE - - LOCK occurs when a connection "locks" (this does not necessarily mean a table - lock and also happens for row-locking engines) the table at the beginning of - a statement. This event is generated at the beginning of every statement for - every affected table, unless there's a LOCK TABLES statement in effect (in - which case it is generated once for LOCK TABLES and then is suppressed until - the tables are unlocked). - - CREATE/DROP/RENAME occur when a table is created, dropped, or renamed. -*/ - -#define MYSQL_AUDIT_TABLE_CLASS 15 -#define MYSQL_AUDIT_TABLE_CLASSMASK (1 << MYSQL_AUDIT_TABLE_CLASS) -#define MYSQL_AUDIT_TABLE_LOCK 0 -#define MYSQL_AUDIT_TABLE_CREATE 1 -#define MYSQL_AUDIT_TABLE_DROP 2 -#define MYSQL_AUDIT_TABLE_RENAME 3 -#define MYSQL_AUDIT_TABLE_ALTER 4 - -struct mysql_event_table -{ - unsigned int event_subclass; - unsigned long thread_id; - const char *user; - const char *priv_user; - const char *priv_host; - const char *external_user; - const char *proxy_user; - const char *host; - const char *ip; - MYSQL_CONST_LEX_STRING database; - MYSQL_CONST_LEX_STRING table; - /* for MYSQL_AUDIT_TABLE_RENAME */ - MYSQL_CONST_LEX_STRING new_database; - MYSQL_CONST_LEX_STRING new_table; - /* for MYSQL_AUDIT_TABLE_LOCK, true if read-only, false if read/write */ - int read_only; - /* Added in version 0x302 */ - unsigned long long query_id; -}; - -/************************************************************************* - Here we define the descriptor structure, that is referred from - st_mysql_plugin. - - release_thd() event occurs when the event class consumer is to be - disassociated from the specified THD. This would typically occur - before some operation which may require sleeping - such as when - waiting for the next query from the client. - - event_notify() is invoked whenever an event occurs which is of any - class for which the plugin has interest. The second argument - indicates the specific event class and the third argument is data - as required for that class. - - class_mask is an array of bits used to indicate what event classes - that this plugin wants to receive. -*/ - -struct st_mysql_audit -{ - int interface_version; - void (*release_thd)(MYSQL_THD); - void (*event_notify)(MYSQL_THD, unsigned int, const void *); - unsigned long class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; -}; - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_auth.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_auth.h deleted file mode 100644 index ae9c936..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_auth.h +++ /dev/null @@ -1,182 +0,0 @@ -#ifndef MYSQL_PLUGIN_AUTH_INCLUDED -/* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab - Copyright (c) 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Authentication Plugin API. - - This file defines the API for server authentication plugins. -*/ - -#define MYSQL_PLUGIN_AUTH_INCLUDED - -#include - -#define MYSQL_AUTHENTICATION_INTERFACE_VERSION 0x0202 - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* defines for MYSQL_SERVER_AUTH_INFO.password_used */ - -#define PASSWORD_USED_NO 0 -#define PASSWORD_USED_YES 1 -#define PASSWORD_USED_NO_MENTION 2 - - -/** - Provides server plugin access to authentication information -*/ -typedef struct st_mysql_server_auth_info -{ - /** - User name as sent by the client and shown in USER(). - NULL if the client packet with the user name was not received yet. - */ - const char *user_name; - - /** - Length of user_name - */ - unsigned int user_name_length; - - /** - A corresponding column value from the mysql.user table for the - matching account name or the preprocessed value, if preprocess_hash - method is not NULL - */ - const char *auth_string; - - /** - Length of auth_string - */ - unsigned long auth_string_length; - - /** - Matching account name as found in the mysql.user table. - A plugin can override it with another name that will be - used by MySQL for authorization, and shown in CURRENT_USER() - */ - char authenticated_as[MYSQL_USERNAME_LENGTH+1]; - - - /** - The unique user name that was used by the plugin to authenticate. - Not used by the server. - Available through the @@EXTERNAL_USER variable. - */ - char external_user[MYSQL_USERNAME_LENGTH+1]; - - /** - This only affects the "Authentication failed. Password used: %s" - error message. has the following values : - 0 : %s will be NO. - 1 : %s will be YES. - 2 : there will be no %s. - Set it as appropriate or ignore at will. - */ - int password_used; - - /** - Set to the name of the connected client host, if it can be resolved, - or to its IP address otherwise. - */ - const char *host_or_ip; - - /** - Length of host_or_ip - */ - unsigned int host_or_ip_length; - - /** - Current THD pointer (to use with various services) - */ - MYSQL_THD thd; - -} MYSQL_SERVER_AUTH_INFO; - -/** - Server authentication plugin descriptor -*/ -struct st_mysql_auth -{ - int interface_version; /**< version plugin uses */ - /** - A plugin that a client must use for authentication with this server - plugin. Can be NULL to mean "any plugin". - */ - const char *client_auth_plugin; - /** - Function provided by the plugin which should perform authentication (using - the vio functions if necessary) and return 0 if successful. The plugin can - also fill the info.authenticated_as field if a different username should be - used for authorization. - */ - int (*authenticate_user)(MYSQL_PLUGIN_VIO *vio, MYSQL_SERVER_AUTH_INFO *info); - /** - Create a password hash (or digest) out of a plain-text password - - Used in SET PASSWORD, GRANT, and CREATE USER to convert user specified - plain-text password into a value that will be stored in mysql.user table. - - @see preprocess_hash - - @param password plain-text password - @param password_length plain-text password length - @param hash the digest will be stored there - @param hash_length in: hash buffer size - out: the actual length of the hash - - @return 0 for ok, 1 for error - - Can be NULL. - */ - int (*hash_password)(const char *password, size_t password_length, - char *hash, size_t *hash_length); - - /** - Prepare the password hash for authentication. - - Password hash is stored in the authentication_string column of the - mysql.user table in a text form. If a plugin needs to preprocess the - value somehow before the authentication (e.g. convert from hex or base64 - to binary), it can do it in this method. This way the conversion - will happen only once, not for every authentication attempt. - - The value written to the out buffer will be cached and later made - available to the authenticate_user() method in the - MYSQL_SERVER_AUTH_INFO::auth_string[] buffer. - - @return 0 for ok, 1 for error - - Can be NULL, in this case the mysql.user.authentication_string value will - be given to the authenticate_user() method as is, unconverted. - */ - int (*preprocess_hash)(const char *hash, size_t hash_length, - unsigned char *out, size_t *out_length); -}; - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_auth_common.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_auth_common.h deleted file mode 100644 index 8edd712..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_auth_common.h +++ /dev/null @@ -1,131 +0,0 @@ -#ifndef MYSQL_PLUGIN_AUTH_COMMON_INCLUDED -/* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab - Copyright (c) 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef _WIN32 -#include -#endif - -/** - @file - - This file defines constants and data structures that are the same for - both client- and server-side authentication plugins. -*/ -#define MYSQL_PLUGIN_AUTH_COMMON_INCLUDED - -/** the max allowed length for a user name */ -#define MYSQL_USERNAME_LENGTH 512 - -/** - return values of the plugin authenticate_user() method. -*/ - - /** - Authentication failed, plugin internal error. - An error occurred in the authentication plugin itself. - These errors are reported in table performance_schema.host_cache, - column COUNT_AUTH_PLUGIN_ERRORS. -*/ -#define CR_AUTH_PLUGIN_ERROR 3 -/** - Authentication failed, client server handshake. - An error occurred during the client server handshake. - These errors are reported in table performance_schema.host_cache, - column COUNT_HANDSHAKE_ERRORS. -*/ -#define CR_AUTH_HANDSHAKE 2 -/** - Authentication failed, user credentials. - For example, wrong passwords. - These errors are reported in table performance_schema.host_cache, - column COUNT_AUTHENTICATION_ERRORS. -*/ -#define CR_AUTH_USER_CREDENTIALS 1 -/** - Authentication failed. Additionally, all other CR_xxx values - (libmysql error code) can be used too. - - The client plugin may set the error code and the error message directly - in the MYSQL structure and return CR_ERROR. If a CR_xxx specific error - code was returned, an error message in the MYSQL structure will be - overwritten. If CR_ERROR is returned without setting the error in MYSQL, - CR_UNKNOWN_ERROR will be user. -*/ -#define CR_ERROR 0 -/** - Authentication (client part) was successful. It does not mean that the - authentication as a whole was successful, usually it only means - that the client was able to send the user name and the password to the - server. If CR_OK is returned, the libmysql reads the next packet expecting - it to be one of OK, ERROR, or CHANGE_PLUGIN packets. -*/ -#define CR_OK -1 -/** - Authentication was successful. - It means that the client has done its part successfully and also that - a plugin has read the last packet (one of OK, ERROR, CHANGE_PLUGIN). - In this case, libmysql will not read a packet from the server, - but it will use the data at mysql->net.read_pos. - - A plugin may return this value if the number of roundtrips in the - authentication protocol is not known in advance, and the client plugin - needs to read one packet more to determine if the authentication is finished - or not. -*/ -#define CR_OK_HANDSHAKE_COMPLETE -2 - -typedef struct st_plugin_vio_info -{ - enum { MYSQL_VIO_INVALID, MYSQL_VIO_TCP, MYSQL_VIO_SOCKET, - MYSQL_VIO_PIPE, MYSQL_VIO_MEMORY } protocol; - int socket; /**< it's set, if the protocol is SOCKET or TCP */ -#ifdef _WIN32 - HANDLE handle; /**< it's set, if the protocol is PIPE or MEMORY */ -#endif -} MYSQL_PLUGIN_VIO_INFO; - -/** - Provides plugin access to communication channel -*/ -typedef struct st_plugin_vio -{ - /** - Plugin provides a pointer reference and this function sets it to the - contents of any incoming packet. Returns the packet length, or -1 if - the plugin should terminate. - */ - int (*read_packet)(struct st_plugin_vio *vio, - unsigned char **buf); - - /** - Plugin provides a buffer with data and the length and this - function sends it as a packet. Returns 0 on success, 1 on failure. - */ - int (*write_packet)(struct st_plugin_vio *vio, - const unsigned char *packet, - int packet_len); - - /** - Fills in a st_plugin_vio_info structure, providing the information - about the connection. - */ - void (*info)(struct st_plugin_vio *vio, struct st_plugin_vio_info *info); - -} MYSQL_PLUGIN_VIO; - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_data_type.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_data_type.h deleted file mode 100644 index 77aa9fb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_data_type.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef MARIADB_PLUGIN_DATA_TYPE_INCLUDED -#define MARIADB_PLUGIN_DATA_TYPE_INCLUDED -/* Copyright (C) 2019, Alexander Barkov and MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Data Type Plugin API. - - This file defines the API for server plugins that manage data types. -*/ - -#ifdef __cplusplus - -#include - -/* - API for data type plugins. (MariaDB_DATA_TYPE_PLUGIN) -*/ -#define MariaDB_DATA_TYPE_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) - - -struct st_mariadb_data_type -{ - int interface_version; - class Type_handler *type_handler; -}; - - -/** - Data type plugin descriptor -*/ - -#endif /* __cplusplus */ - -#endif /* MARIADB_PLUGIN_DATA_TYPE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_encryption.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_encryption.h deleted file mode 100644 index 3c574aa..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_encryption.h +++ /dev/null @@ -1,126 +0,0 @@ -#ifndef MYSQL_PLUGIN_ENCRYPTION_INCLUDED -/* Copyright (C) 2014, 2015 Sergei Golubchik and MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Encryption Plugin API. - - This file defines the API for server plugins that manage encryption - keys for MariaDB on-disk data encryption. -*/ - -#define MYSQL_PLUGIN_ENCRYPTION_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MariaDB_ENCRYPTION_INTERFACE_VERSION 0x0300 - -/** - Encryption plugin descriptor -*/ -struct st_mariadb_encryption -{ - int interface_version; /**< version plugin uses */ - - /*********** KEY MANAGEMENT ********************************************/ - - /** - function returning latest key version for a given key id - - @return a version or ENCRYPTION_KEY_VERSION_INVALID to indicate an error. - */ - unsigned int (*get_latest_key_version)(unsigned int key_id); - - /** - function returning a key for a key version - - @param version the requested key version - @param key the key will be stored there. Can be NULL - - in which case no key will be returned - @param key_length in: key buffer size - out: the actual length of the key - - This method can be used to query the key length - the required - buffer size - by passing key==NULL. - - If the buffer size is less than the key length the content of the - key buffer is undefined (the plugin is free to partially fill it with - the key data or leave it untouched). - - @return 0 on success, or - ENCRYPTION_KEY_VERSION_INVALID, ENCRYPTION_KEY_BUFFER_TOO_SMALL - or any other non-zero number for errors - */ - unsigned int (*get_key)(unsigned int key_id, unsigned int version, - unsigned char *key, unsigned int *key_length); - - /*********** ENCRYPTION ************************************************/ - /* - the caller uses encryption as follows: - 1. create the encryption context object of the crypt_ctx_size() bytes. - 2. initialize it with crypt_ctx_init(). - 3. repeat crypt_ctx_update() until there are no more data to encrypt. - 4. write the remaining output bytes and destroy the context object - with crypt_ctx_finish(). - */ - - /** - returns the size of the encryption context object in bytes - */ - unsigned int (*crypt_ctx_size)(unsigned int key_id, unsigned int key_version); - /** - initializes the encryption context object. - */ - int (*crypt_ctx_init)(void *ctx, const unsigned char* key, unsigned int klen, - const unsigned char* iv, unsigned int ivlen, - int flags, unsigned int key_id, - unsigned int key_version); - /** - processes (encrypts or decrypts) a chunk of data - - writes the output to th dst buffer. note that it might write - more bytes that were in the input. or less. or none at all. - */ - int (*crypt_ctx_update)(void *ctx, const unsigned char* src, unsigned int slen, - unsigned char* dst, unsigned int* dlen); - /** - writes the remaining output bytes and destroys the encryption context - - crypt_ctx_update might've cached part of the output in the context, - this method will flush these data out. - */ - int (*crypt_ctx_finish)(void *ctx, unsigned char* dst, unsigned int* dlen); - /** - returns the length of the encrypted data - - it returns the exact length, given only the source length. - which means, this API only supports encryption algorithms where - the length of the encrypted data only depends on the length of the - input (a.k.a. compression is not supported). - */ - unsigned int (*encrypted_length)(unsigned int slen, unsigned int key_id, unsigned int key_version); -}; - -#ifdef __cplusplus -} -#endif -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_ftparser.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_ftparser.h deleted file mode 100644 index 99bb6b2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_ftparser.h +++ /dev/null @@ -1,220 +0,0 @@ -/* Copyright (c) 2005 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_plugin_ftparser_h -#define _my_plugin_ftparser_h -#include "plugin.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/************************************************************************* - API for Full-text parser plugin. (MYSQL_FTPARSER_PLUGIN) -*/ - -#define MYSQL_FTPARSER_INTERFACE_VERSION 0x0100 - -/* Parsing modes. Set in MYSQL_FTPARSER_PARAM::mode */ -enum enum_ftparser_mode -{ -/* - Fast and simple mode. This mode is used for indexing, and natural - language queries. - - The parser is expected to return only those words that go into the - index. Stopwords or too short/long words should not be returned. The - 'boolean_info' argument of mysql_add_word() does not have to be set. -*/ - MYSQL_FTPARSER_SIMPLE_MODE= 0, - -/* - Parse with stopwords mode. This mode is used in boolean searches for - "phrase matching." - - The parser is not allowed to ignore words in this mode. Every word - should be returned, including stopwords and words that are too short - or long. The 'boolean_info' argument of mysql_add_word() does not - have to be set. -*/ - MYSQL_FTPARSER_WITH_STOPWORDS= 1, - -/* - Parse in boolean mode. This mode is used to parse a boolean query string. - - The parser should provide a valid MYSQL_FTPARSER_BOOLEAN_INFO - structure in the 'boolean_info' argument to mysql_add_word(). - Usually that means that the parser should recognize boolean operators - in the parsing stream and set appropriate fields in - MYSQL_FTPARSER_BOOLEAN_INFO structure accordingly. As for - MYSQL_FTPARSER_WITH_STOPWORDS mode, no word should be ignored. - Instead, use FT_TOKEN_STOPWORD for the token type of such a word. -*/ - MYSQL_FTPARSER_FULL_BOOLEAN_INFO= 2 -}; - -/* - Token types for boolean mode searching (used for the type member of - MYSQL_FTPARSER_BOOLEAN_INFO struct) - - FT_TOKEN_EOF: End of data. - FT_TOKEN_WORD: Regular word. - FT_TOKEN_LEFT_PAREN: Left parenthesis (start of group/sub-expression). - FT_TOKEN_RIGHT_PAREN: Right parenthesis (end of group/sub-expression). - FT_TOKEN_STOPWORD: Stopword. -*/ - -enum enum_ft_token_type -{ - FT_TOKEN_EOF= 0, - FT_TOKEN_WORD= 1, - FT_TOKEN_LEFT_PAREN= 2, - FT_TOKEN_RIGHT_PAREN= 3, - FT_TOKEN_STOPWORD= 4 -}; - -/* - This structure is used in boolean search mode only. It conveys - boolean-mode metadata to the MySQL search engine for every word in - the search query. A valid instance of this structure must be filled - in by the plugin parser and passed as an argument in the call to - mysql_add_word (the callback function in the MYSQL_FTPARSER_PARAM - structure) when a query is parsed in boolean mode. - - type: The token type. Should be one of the enum_ft_token_type values. - - yesno: Whether the word must be present for a match to occur: - >0 Must be present - <0 Must not be present - 0 Neither; the word is optional but its presence increases the relevance - With the default settings of the ft_boolean_syntax system variable, - >0 corresponds to the '+' operator, <0 corrresponds to the '-' operator, - and 0 means neither operator was used. - - weight_adjust: A weighting factor that determines how much a match - for the word counts. Positive values increase, negative - decrease the - relative word's importance in the query. - - wasign: The sign of the word's weight in the query. If it's non-negative - the match for the word will increase document relevance, if it's - negative - decrease (the word becomes a "noise word", the less of it the - better). - - trunc: Corresponds to the '*' operator in the default setting of the - ft_boolean_syntax system variable. -*/ - -typedef struct st_mysql_ftparser_boolean_info -{ - enum enum_ft_token_type type; - int yesno; - int weight_adjust; - char wasign; - char trunc; - /* These are parser state and must be removed. */ - char prev; - char *quot; -} MYSQL_FTPARSER_BOOLEAN_INFO; - -/* - The following flag means that buffer with a string (document, word) - may be overwritten by the caller before the end of the parsing (that is - before st_mysql_ftparser::deinit() call). If one needs the string - to survive between two successive calls of the parsing function, she - needs to save a copy of it. The flag may be set by MySQL before calling - st_mysql_ftparser::parse(), or it may be set by a plugin before calling - st_mysql_ftparser_param::mysql_parse() or - st_mysql_ftparser_param::mysql_add_word(). -*/ -#define MYSQL_FTFLAGS_NEED_COPY 1 - -/* - An argument of the full-text parser plugin. This structure is - filled in by MySQL server and passed to the parsing function of the - plugin as an in/out parameter. - - mysql_parse: A pointer to the built-in parser implementation of the - server. It's set by the server and can be used by the parser plugin - to invoke the MySQL default parser. If plugin's role is to extract - textual data from .doc, .pdf or .xml content, it might extract - plaintext from the content, and then pass the text to the default - MySQL parser to be parsed. - - mysql_add_word: A server callback to add a new word. When parsing - a document, the server sets this to point at a function that adds - the word to MySQL full-text index. When parsing a search query, - this function will add the new word to the list of words to search - for. The boolean_info argument can be NULL for all cases except - when mode is MYSQL_FTPARSER_FULL_BOOLEAN_INFO. - - ftparser_state: A generic pointer. The plugin can set it to point - to information to be used internally for its own purposes. - - mysql_ftparam: This is set by the server. It is used by MySQL functions - called via mysql_parse() and mysql_add_word() callback. The plugin - should not modify it. - - cs: Information about the character set of the document or query string. - - doc: A pointer to the document or query string to be parsed. - - length: Length of the document or query string, in bytes. - - flags: See MYSQL_FTFLAGS_* constants above. - - mode: The parsing mode. With boolean operators, with stopwords, or - nothing. See enum_ftparser_mode above. -*/ - -typedef struct st_mysql_ftparser_param -{ - int (*mysql_parse)(struct st_mysql_ftparser_param *, - const char *doc, int doc_len); - int (*mysql_add_word)(struct st_mysql_ftparser_param *, - const char *word, int word_len, - MYSQL_FTPARSER_BOOLEAN_INFO *boolean_info); - void *ftparser_state; - void *mysql_ftparam; - const struct charset_info_st *cs; - const char *doc; - int length; - unsigned int flags; - enum enum_ftparser_mode mode; -} MYSQL_FTPARSER_PARAM; - -/* - Full-text parser descriptor. - - interface_version is, e.g., MYSQL_FTPARSER_INTERFACE_VERSION. - The parsing, initialization, and deinitialization functions are - invoked per SQL statement for which the parser is used. -*/ - -struct st_mysql_ftparser -{ - int interface_version; - int (*parse)(MYSQL_FTPARSER_PARAM *param); - int (*init)(MYSQL_FTPARSER_PARAM *param); - int (*deinit)(MYSQL_FTPARSER_PARAM *param); -}; - - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_function.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_function.h deleted file mode 100644 index 117acd4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_function.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef MARIADB_PLUGIN_FUNCTION_INCLUDED -#define MARIADB_PLUGIN_FUNCTION_INCLUDED -/* Copyright (C) 2019, Alexander Barkov and MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Function Plugin API. - - This file defines the API for server plugins that manage functions. -*/ - -#ifdef __cplusplus - -#include - -/* - API for function plugins. (MariaDB_FUNCTION_PLUGIN) -*/ -#define MariaDB_FUNCTION_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) - - -class Plugin_function -{ - int m_interface_version; - Create_func *m_builder; -public: - Plugin_function(Create_func *builder) - :m_interface_version(MariaDB_FUNCTION_INTERFACE_VERSION), - m_builder(builder) - { } - Create_func *create_func() - { - return m_builder; - } -}; - - -#endif /* __cplusplus */ - -#endif /* MARIADB_PLUGIN_FUNCTION_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_password_validation.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_password_validation.h deleted file mode 100644 index 23d2c88..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/plugin_password_validation.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef MYSQL_PLUGIN_PASSWORD_VALIDATION_INCLUDED -/* Copyright (C) 2014 Sergei Golubchik and MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Password Validation Plugin API. - - This file defines the API for server password validation plugins. -*/ - -#define MYSQL_PLUGIN_PASSWORD_VALIDATION_INCLUDED - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MariaDB_PASSWORD_VALIDATION_INTERFACE_VERSION 0x0100 - -/** - Password validation plugin descriptor -*/ -struct st_mariadb_password_validation -{ - int interface_version; /**< version plugin uses */ - /** - Function provided by the plugin which should perform password validation - and return 0 if the password has passed the validation. - */ - int (*validate_password)(const MYSQL_CONST_LEX_STRING *username, - const MYSQL_CONST_LEX_STRING *password); -}; - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_file.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_file.h deleted file mode 100644 index 761482d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_file.h +++ /dev/null @@ -1,1454 +0,0 @@ -/* Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_FILE_H -#define MYSQL_FILE_H - -/* For strlen() */ -#include -/* For MY_STAT */ -#include -/* For my_chsize */ -#include - -/** - @file mysql/psi/mysql_file.h - Instrumentation helpers for mysys file io. - This header file provides the necessary declarations - to use the mysys file API with the performance schema instrumentation. - In some compilers (SunStudio), 'static inline' functions, when declared - but not used, are not optimized away (because they are unused) by default, - so that including a static inline function from a header file does - create unwanted dependencies, causing unresolved symbols at link time. - Other compilers, like gcc, optimize these dependencies by default. - - Since the instrumented APIs declared here are wrapper on top - of mysys file io APIs, including mysql/psi/mysql_file.h assumes that - the dependency on my_sys already exists. -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_FILE_CALL -#define PSI_FILE_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup File_instrumentation File Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -/** - @def mysql_file_register(P1, P2, P3) - File registration. -*/ -#define mysql_file_register(P1, P2, P3) \ - inline_mysql_file_register(P1, P2, P3) - -/** - @def mysql_file_fgets(P1, P2, F) - Instrumented fgets. - @c mysql_file_fgets is a replacement for @c fgets. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fgets(P1, P2, F) \ - inline_mysql_file_fgets(__FILE__, __LINE__, P1, P2, F) -#else - #define mysql_file_fgets(P1, P2, F) \ - inline_mysql_file_fgets(P1, P2, F) -#endif - -/** - @def mysql_file_fgetc(F) - Instrumented fgetc. - @c mysql_file_fgetc is a replacement for @c fgetc. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fgetc(F) inline_mysql_file_fgetc(__FILE__, __LINE__, F) -#else - #define mysql_file_fgetc(F) inline_mysql_file_fgetc(F) -#endif - -/** - @def mysql_file_fputs(P1, F) - Instrumented fputs. - @c mysql_file_fputs is a replacement for @c fputs. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fputs(P1, F) \ - inline_mysql_file_fputs(__FILE__, __LINE__, P1, F) -#else - #define mysql_file_fputs(P1, F)\ - inline_mysql_file_fputs(P1, F) -#endif - -/** - @def mysql_file_fputc(P1, F) - Instrumented fputc. - @c mysql_file_fputc is a replacement for @c fputc. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fputc(P1, F) \ - inline_mysql_file_fputc(__FILE__, __LINE__, P1, F) -#else - #define mysql_file_fputc(P1, F) \ - inline_mysql_file_fputc(P1, F) -#endif - -/** - @def mysql_file_fprintf - Instrumented fprintf. - @c mysql_file_fprintf is a replacement for @c fprintf. -*/ -#define mysql_file_fprintf inline_mysql_file_fprintf - -/** - @def mysql_file_vfprintf(F, P1, P2) - Instrumented vfprintf. - @c mysql_file_vfprintf is a replacement for @c vfprintf. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_vfprintf(F, P1, P2) \ - inline_mysql_file_vfprintf(__FILE__, __LINE__, F, P1, P2) -#else - #define mysql_file_vfprintf(F, P1, P2) \ - inline_mysql_file_vfprintf(F, P1, P2) -#endif - -/** - @def mysql_file_fflush(F, P1, P2) - Instrumented fflush. - @c mysql_file_fflush is a replacement for @c fflush. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fflush(F) \ - inline_mysql_file_fflush(__FILE__, __LINE__, F) -#else - #define mysql_file_fflush(F) \ - inline_mysql_file_fflush(F) -#endif - -/** - @def mysql_file_feof(F) - Instrumented feof. - @c mysql_file_feof is a replacement for @c feof. -*/ -#define mysql_file_feof(F) inline_mysql_file_feof(F) - -/** - @def mysql_file_fstat(FN, S, FL) - Instrumented fstat. - @c mysql_file_fstat is a replacement for @c my_fstat. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fstat(FN, S, FL) \ - inline_mysql_file_fstat(__FILE__, __LINE__, FN, S, FL) -#else - #define mysql_file_fstat(FN, S, FL) \ - inline_mysql_file_fstat(FN, S, FL) -#endif - -/** - @def mysql_file_stat(K, FN, S, FL) - Instrumented stat. - @c mysql_file_stat is a replacement for @c my_stat. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_stat(K, FN, S, FL) \ - inline_mysql_file_stat(K, __FILE__, __LINE__, FN, S, FL) -#else - #define mysql_file_stat(K, FN, S, FL) \ - inline_mysql_file_stat(FN, S, FL) -#endif - -/** - @def mysql_file_chsize(F, P1, P2, P3) - Instrumented chsize. - @c mysql_file_chsize is a replacement for @c my_chsize. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_chsize(F, P1, P2, P3) \ - inline_mysql_file_chsize(__FILE__, __LINE__, F, P1, P2, P3) -#else - #define mysql_file_chsize(F, P1, P2, P3) \ - inline_mysql_file_chsize(F, P1, P2, P3) -#endif - -/** - @def mysql_file_fopen(K, N, F1, F2) - Instrumented fopen. - @c mysql_file_fopen is a replacement for @c my_fopen. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fopen(K, N, F1, F2) \ - inline_mysql_file_fopen(K, __FILE__, __LINE__, N, F1, F2) -#else - #define mysql_file_fopen(K, N, F1, F2) \ - inline_mysql_file_fopen(N, F1, F2) -#endif - -/** - @def mysql_file_fclose(FD, FL) - Instrumented fclose. - @c mysql_file_fclose is a replacement for @c my_fclose. - Without the instrumentation, this call will have the same behavior as the - undocumented and possibly platform specific my_fclose(NULL, ...) behavior. - With the instrumentation, mysql_fclose(NULL, ...) will safely return 0, - which is an extension compared to my_fclose and is therefore compliant. - mysql_fclose is on purpose *not* implementing - @code DBUG_ASSERT(file != NULL) @endcode, - since doing so could introduce regressions. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fclose(FD, FL) \ - inline_mysql_file_fclose(__FILE__, __LINE__, FD, FL) -#else - #define mysql_file_fclose(FD, FL) \ - inline_mysql_file_fclose(FD, FL) -#endif - -/** - @def mysql_file_fread(FD, P1, P2, P3) - Instrumented fread. - @c mysql_file_fread is a replacement for @c my_fread. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fread(FD, P1, P2, P3) \ - inline_mysql_file_fread(__FILE__, __LINE__, FD, P1, P2, P3) -#else - #define mysql_file_fread(FD, P1, P2, P3) \ - inline_mysql_file_fread(FD, P1, P2, P3) -#endif - -/** - @def mysql_file_fwrite(FD, P1, P2, P3) - Instrumented fwrite. - @c mysql_file_fwrite is a replacement for @c my_fwrite. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fwrite(FD, P1, P2, P3) \ - inline_mysql_file_fwrite(__FILE__, __LINE__, FD, P1, P2, P3) -#else - #define mysql_file_fwrite(FD, P1, P2, P3) \ - inline_mysql_file_fwrite(FD, P1, P2, P3) -#endif - -/** - @def mysql_file_fseek(FD, P, W, F) - Instrumented fseek. - @c mysql_file_fseek is a replacement for @c my_fseek. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_fseek(FD, P, W, F) \ - inline_mysql_file_fseek(__FILE__, __LINE__, FD, P, W, F) -#else - #define mysql_file_fseek(FD, P, W, F) \ - inline_mysql_file_fseek(FD, P, W, F) -#endif - -/** - @def mysql_file_ftell(FD, F) - Instrumented ftell. - @c mysql_file_ftell is a replacement for @c my_ftell. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_ftell(FD, F) \ - inline_mysql_file_ftell(__FILE__, __LINE__, FD, F) -#else - #define mysql_file_ftell(FD, F) \ - inline_mysql_file_ftell(FD, F) -#endif - -/** - @def mysql_file_create(K, N, F1, F2, F3) - Instrumented create. - @c mysql_file_create is a replacement for @c my_create. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_create(K, N, F1, F2, F3) \ - inline_mysql_file_create(K, __FILE__, __LINE__, N, F1, F2, F3) -#else - #define mysql_file_create(K, N, F1, F2, F3) \ - inline_mysql_file_create(N, F1, F2, F3) -#endif - -/** - @def mysql_file_create_temp(K, T, D, P, M, F) - Instrumented create_temp_file. - @c mysql_file_create_temp is a replacement for @c create_temp_file. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_create_temp(K, T, D, P, M, F) \ - inline_mysql_file_create_temp(K, __FILE__, __LINE__, T, D, P, M, F) -#else - #define mysql_file_create_temp(K, T, D, P, M, F) \ - inline_mysql_file_create_temp(T, D, P, M, F) -#endif - -/** - @def mysql_file_open(K, N, F1, F2) - Instrumented open. - @c mysql_file_open is a replacement for @c my_open. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_open(K, N, F1, F2) \ - inline_mysql_file_open(K, __FILE__, __LINE__, N, F1, F2) -#else - #define mysql_file_open(K, N, F1, F2) \ - inline_mysql_file_open(N, F1, F2) -#endif - -/** - @def mysql_file_close(FD, F) - Instrumented close. - @c mysql_file_close is a replacement for @c my_close. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_close(FD, F) \ - inline_mysql_file_close(__FILE__, __LINE__, FD, F) -#else - #define mysql_file_close(FD, F) \ - inline_mysql_file_close(FD, F) -#endif - -/** - @def mysql_file_read(FD, B, S, F) - Instrumented read. - @c mysql_read is a replacement for @c my_read. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_read(FD, B, S, F) \ - inline_mysql_file_read(__FILE__, __LINE__, FD, B, S, F) -#else - #define mysql_file_read(FD, B, S, F) \ - inline_mysql_file_read(FD, B, S, F) -#endif - -/** - @def mysql_file_write(FD, B, S, F) - Instrumented write. - @c mysql_file_write is a replacement for @c my_write. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_write(FD, B, S, F) \ - inline_mysql_file_write(__FILE__, __LINE__, FD, B, S, F) -#else - #define mysql_file_write(FD, B, S, F) \ - inline_mysql_file_write(FD, B, S, F) -#endif - -/** - @def mysql_file_pread(FD, B, S, O, F) - Instrumented pread. - @c mysql_pread is a replacement for @c my_pread. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_pread(FD, B, S, O, F) \ - inline_mysql_file_pread(__FILE__, __LINE__, FD, B, S, O, F) -#else - #define mysql_file_pread(FD, B, S, O, F) \ - inline_mysql_file_pread(FD, B, S, O, F) -#endif - -/** - @def mysql_file_pwrite(FD, B, S, O, F) - Instrumented pwrite. - @c mysql_file_pwrite is a replacement for @c my_pwrite. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_pwrite(FD, B, S, O, F) \ - inline_mysql_file_pwrite(__FILE__, __LINE__, FD, B, S, O, F) -#else - #define mysql_file_pwrite(FD, B, S, O, F) \ - inline_mysql_file_pwrite(FD, B, S, O, F) -#endif - -/** - @def mysql_file_seek(FD, P, W, F) - Instrumented seek. - @c mysql_file_seek is a replacement for @c my_seek. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_seek(FD, P, W, F) \ - inline_mysql_file_seek(__FILE__, __LINE__, FD, P, W, F) -#else - #define mysql_file_seek(FD, P, W, F) \ - inline_mysql_file_seek(FD, P, W, F) -#endif - -/** - @def mysql_file_tell(FD, F) - Instrumented tell. - @c mysql_file_tell is a replacement for @c my_tell. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_tell(FD, F) \ - inline_mysql_file_tell(__FILE__, __LINE__, FD, F) -#else - #define mysql_file_tell(FD, F) \ - inline_mysql_file_tell(FD, F) -#endif - -/** - @def mysql_file_delete(K, P1, P2) - Instrumented delete. - @c mysql_file_delete is a replacement for @c my_delete. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_delete(K, P1, P2) \ - inline_mysql_file_delete(K, __FILE__, __LINE__, P1, P2) -#else - #define mysql_file_delete(K, P1, P2) \ - inline_mysql_file_delete(P1, P2) -#endif - -/** - @def mysql_file_rename(K, P1, P2, P3) - Instrumented rename. - @c mysql_file_rename is a replacement for @c my_rename. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_rename(K, P1, P2, P3) \ - inline_mysql_file_rename(K, __FILE__, __LINE__, P1, P2, P3) -#else - #define mysql_file_rename(K, P1, P2, P3) \ - inline_mysql_file_rename(P1, P2, P3) -#endif - -/** - @def mysql_file_create_with_symlink(K, P1, P2, P3, P4, P5) - Instrumented create with symbolic link. - @c mysql_file_create_with_symlink is a replacement - for @c my_create_with_symlink. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_create_with_symlink(K, P1, P2, P3, P4, P5) \ - inline_mysql_file_create_with_symlink(K, __FILE__, __LINE__, \ - P1, P2, P3, P4, P5) -#else - #define mysql_file_create_with_symlink(K, P1, P2, P3, P4, P5) \ - inline_mysql_file_create_with_symlink(P1, P2, P3, P4, P5) -#endif - -/** - @def mysql_file_delete_with_symlink(K, P1, P2, P3) - Instrumented delete with symbolic link. - @c mysql_file_delete_with_symlink is a replacement - for @c my_handler_delete_with_symlink. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_delete_with_symlink(K, P1, P2, P3) \ - inline_mysql_file_delete_with_symlink(K, __FILE__, __LINE__, P1, P2, P3) -#else - #define mysql_file_delete_with_symlink(K, P1, P2, P3) \ - inline_mysql_file_delete_with_symlink(P1, P2, P3) -#endif - -/** - @def mysql_file_rename_with_symlink(K, P1, P2, P3) - Instrumented rename with symbolic link. - @c mysql_file_rename_with_symlink is a replacement - for @c my_rename_with_symlink. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_rename_with_symlink(K, P1, P2, P3) \ - inline_mysql_file_rename_with_symlink(K, __FILE__, __LINE__, P1, P2, P3) -#else - #define mysql_file_rename_with_symlink(K, P1, P2, P3) \ - inline_mysql_file_rename_with_symlink(P1, P2, P3) -#endif - -/** - @def mysql_file_sync(P1, P2) - Instrumented file sync. - @c mysql_file_sync is a replacement for @c my_sync. -*/ -#ifdef HAVE_PSI_FILE_INTERFACE - #define mysql_file_sync(P1, P2) \ - inline_mysql_file_sync(__FILE__, __LINE__, P1, P2) -#else - #define mysql_file_sync(P1, P2) \ - inline_mysql_file_sync(P1, P2) -#endif - -/** - An instrumented FILE structure. - @sa MYSQL_FILE -*/ -struct st_mysql_file -{ - /** The real file. */ - FILE *m_file; - /** - The instrumentation hook. - Note that this hook is not conditionally defined, - for binary compatibility of the @c MYSQL_FILE interface. - */ - struct PSI_file *m_psi; -}; - -/** - Type of an instrumented file. - @c MYSQL_FILE is a drop-in replacement for @c FILE. - @sa mysql_file_open -*/ -typedef struct st_mysql_file MYSQL_FILE; - -static inline void inline_mysql_file_register( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *category, - PSI_file_info *info, - int count -#else - const char *category __attribute__ ((unused)), - void *info __attribute__ ((unused)), - int count __attribute__ ((unused)) -#endif -) -{ -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_FILE_CALL(register_file)(category, info, count); -#endif -} - -static inline char * -inline_mysql_file_fgets( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - char *str, int size, MYSQL_FILE *file) -{ - char *result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_READ); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) size, src_file, src_line); - result= fgets(str, size, file->m_file); - PSI_FILE_CALL(end_file_wait)(locker, result ? strlen(result) : 0); - return result; - } - } -#endif - - result= fgets(str, size, file->m_file); - return result; -} - -static inline int -inline_mysql_file_fgetc( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_READ); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 1, src_file, src_line); - result= fgetc(file->m_file); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 1); - return result; - } - } -#endif - - result= fgetc(file->m_file); - return result; -} - -static inline int -inline_mysql_file_fputs( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - const char *str, MYSQL_FILE *file) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - size_t bytes; - locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); - if (likely(locker != NULL)) - { - bytes= str ? strlen(str) : 0; - PSI_FILE_CALL(start_file_wait)(locker, bytes, src_file, src_line); - result= fputs(str, file->m_file); - PSI_FILE_CALL(end_file_wait)(locker, bytes); - return result; - } - } -#endif - - result= fputs(str, file->m_file); - return result; -} - -static inline int -inline_mysql_file_fputc( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - char c, MYSQL_FILE *file) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 1, src_file, src_line); - result= fputc(c, file->m_file); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 1); - return result; - } - } -#endif - - result= fputc(c, file->m_file); - return result; -} - -static inline int -inline_mysql_file_fprintf(MYSQL_FILE *file, const char *format, ...) -{ - /* - TODO: figure out how to pass src_file and src_line from the caller. - */ - int result; - va_list args; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, __FILE__, __LINE__); - va_start(args, format); - result= vfprintf(file->m_file, format, args); - va_end(args); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) result); - return result; - } - } -#endif - - va_start(args, format); - result= vfprintf(file->m_file, format, args); - va_end(args); - return result; -} - -static inline int -inline_mysql_file_vfprintf( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file, const char *format, va_list args) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= vfprintf(file->m_file, format, args); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) result); - return result; - } - } -#endif - - result= vfprintf(file->m_file, format, args); - return result; -} - -static inline int -inline_mysql_file_fflush( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_FLUSH); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= fflush(file->m_file); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); - return result; - } - } -#endif - - result= fflush(file->m_file); - return result; -} - -static inline int inline_mysql_file_feof(MYSQL_FILE *file) -{ - /* Not instrumented, there is no wait involved */ - return feof(file->m_file); -} - -static inline int -inline_mysql_file_fstat( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - int filenr, MY_STAT *stat_area, myf flags) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, filenr, PSI_FILE_FSTAT); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_fstat(filenr, stat_area, flags); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); - return result; - } -#endif - - result= my_fstat(filenr, stat_area, flags); - return result; -} - -static inline MY_STAT * -inline_mysql_file_stat( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *path, MY_STAT *stat_area, myf flags) -{ - MY_STAT *result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_STAT, path, &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); - result= my_stat(path, stat_area, flags); - PSI_FILE_CALL(end_file_open_wait)(locker, result); - return result; - } -#endif - - result= my_stat(path, stat_area, flags); - return result; -} - -static inline int -inline_mysql_file_chsize( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, my_off_t newlength, int filler, myf flags) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_CHSIZE); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) newlength, src_file, - src_line); - result= my_chsize(file, newlength, filler, flags); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) newlength); - return result; - } -#endif - - result= my_chsize(file, newlength, filler, flags); - return result; -} - -static inline MYSQL_FILE* -inline_mysql_file_fopen( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *filename, int flags, myf myFlags) -{ - MYSQL_FILE *that; - that= (MYSQL_FILE*) my_malloc(PSI_NOT_INSTRUMENTED, - sizeof(MYSQL_FILE), MYF(MY_WME)); - if (likely(that != NULL)) - { -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_STREAM_OPEN, - filename, that); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); - that->m_file= my_fopen(filename, flags, myFlags); - that->m_psi= PSI_FILE_CALL(end_file_open_wait)(locker, that->m_file); - if (unlikely(that->m_file == NULL)) - { - my_free(that); - return NULL; - } - return that; - } -#endif - - that->m_psi= NULL; - that->m_file= my_fopen(filename, flags, myFlags); - if (unlikely(that->m_file == NULL)) - { - my_free(that); - return NULL; - } - } - return that; -} - -static inline int -inline_mysql_file_fclose( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file, myf flags) -{ - int result= 0; - if (likely(file != NULL)) - { -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, - PSI_FILE_STREAM_CLOSE); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); - result= my_fclose(file->m_file, flags); - PSI_FILE_CALL(end_file_close_wait)(locker, result); - my_free(file); - return result; - } - } -#endif - - result= my_fclose(file->m_file, flags); - my_free(file); - } - return result; -} - -static inline size_t -inline_mysql_file_fread( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file, uchar *buffer, size_t count, myf flags) -{ - size_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - size_t bytes_read; - locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_READ); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); - result= my_fread(file->m_file, buffer, count, flags); - if (flags & (MY_NABP | MY_FNABP)) - bytes_read= (result == 0) ? count : 0; - else - bytes_read= (result != MY_FILE_ERROR) ? result : 0; - PSI_FILE_CALL(end_file_wait)(locker, bytes_read); - return result; - } - } -#endif - - result= my_fread(file->m_file, buffer, count, flags); - return result; -} - -static inline size_t -inline_mysql_file_fwrite( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file, const uchar *buffer, size_t count, myf flags) -{ - size_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - size_t bytes_written; - locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_WRITE); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); - result= my_fwrite(file->m_file, buffer, count, flags); - if (flags & (MY_NABP | MY_FNABP)) - bytes_written= (result == 0) ? count : 0; - else - bytes_written= (result != MY_FILE_ERROR) ? result : 0; - PSI_FILE_CALL(end_file_wait)(locker, bytes_written); - return result; - } - } -#endif - - result= my_fwrite(file->m_file, buffer, count, flags); - return result; -} - -static inline my_off_t -inline_mysql_file_fseek( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file, my_off_t pos, int whence, myf flags) -{ - my_off_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_SEEK); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_fseek(file->m_file, pos, whence, flags); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); - return result; - } - } -#endif - - result= my_fseek(file->m_file, pos, whence, flags); - return result; -} - -static inline my_off_t -inline_mysql_file_ftell( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_FILE *file, myf flags) -{ - my_off_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - if (psi_likely(file->m_psi)) - { - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_TELL); - if (likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_ftell(file->m_file, flags); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); - return result; - } - } -#endif - - result= my_ftell(file->m_file, flags); - return result; -} - -static inline File -inline_mysql_file_create( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *filename, int create_flags, int access_flags, myf myFlags) -{ - File file; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_CREATE, filename, - &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); - file= my_create(filename, create_flags, access_flags, myFlags); - PSI_FILE_CALL(end_file_open_wait_and_bind_to_descriptor)(locker, file); - return file; - } -#endif - - file= my_create(filename, create_flags, access_flags, myFlags); - return file; -} - -static inline File -inline_mysql_file_create_temp( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - char *to, const char *dir, const char *pfx, int mode, myf myFlags) -{ - File file; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker) - (&state, key, PSI_FILE_CREATE, NULL, &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); - /* The file name is generated by create_temp_file(). */ - file= create_temp_file(to, dir, pfx, mode, myFlags); - PSI_FILE_CALL(end_temp_file_open_wait_and_bind_to_descriptor)(locker, file, (const char*)to); - return file; - } -#endif - - file= create_temp_file(to, dir, pfx, mode, myFlags); - return file; -} - -static inline File -inline_mysql_file_open( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *filename, int flags, myf myFlags) -{ - File file; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_OPEN, filename, - &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); - file= my_open(filename, flags, myFlags); - PSI_FILE_CALL(end_file_open_wait_and_bind_to_descriptor)(locker, file); - return file; - } -#endif - - file= my_open(filename, flags, myFlags); - return file; -} - -static inline int -inline_mysql_file_close( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, myf flags) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_CLOSE); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); - result= my_close(file, flags); - PSI_FILE_CALL(end_file_close_wait)(locker, result); - return result; - } -#endif - - result= my_close(file, flags); - return result; -} - -static inline size_t -inline_mysql_file_read( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, uchar *buffer, size_t count, myf flags) -{ - size_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - size_t bytes_read; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_READ); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); - result= my_read(file, buffer, count, flags); - if (flags & (MY_NABP | MY_FNABP)) - bytes_read= (result == 0) ? count : 0; - else - bytes_read= (result != MY_FILE_ERROR) ? result : 0; - PSI_FILE_CALL(end_file_wait)(locker, bytes_read); - return result; - } -#endif - - result= my_read(file, buffer, count, flags); - return result; -} - -static inline size_t -inline_mysql_file_write( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, const uchar *buffer, size_t count, myf flags) -{ - size_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - size_t bytes_written; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_WRITE); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); - result= my_write(file, buffer, count, flags); - if (flags & (MY_NABP | MY_FNABP)) - bytes_written= (result == 0) ? count : 0; - else - bytes_written= (result != MY_FILE_ERROR) ? result : 0; - PSI_FILE_CALL(end_file_wait)(locker, bytes_written); - return result; - } -#endif - - result= my_write(file, buffer, count, flags); - return result; -} - -static inline size_t -inline_mysql_file_pread( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, uchar *buffer, size_t count, my_off_t offset, myf flags) -{ - size_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - size_t bytes_read; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_READ); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); - result= my_pread(file, buffer, count, offset, flags); - if (flags & (MY_NABP | MY_FNABP)) - bytes_read= (result == 0) ? count : 0; - else - bytes_read= (result != MY_FILE_ERROR) ? result : 0; - PSI_FILE_CALL(end_file_wait)(locker, bytes_read); - return result; - } -#endif - - result= my_pread(file, buffer, count, offset, flags); - return result; -} - -static inline size_t -inline_mysql_file_pwrite( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, const uchar *buffer, size_t count, my_off_t offset, myf flags) -{ - size_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - size_t bytes_written; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_WRITE); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); - result= my_pwrite(file, buffer, count, offset, flags); - if (flags & (MY_NABP | MY_FNABP)) - bytes_written= (result == 0) ? count : 0; - else - bytes_written= (result != MY_FILE_ERROR) ? result : 0; - PSI_FILE_CALL(end_file_wait)(locker, bytes_written); - return result; - } -#endif - - result= my_pwrite(file, buffer, count, offset, flags); - return result; -} - -static inline my_off_t -inline_mysql_file_seek( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, my_off_t pos, int whence, myf flags) -{ - my_off_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_SEEK); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_seek(file, pos, whence, flags); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); - return result; - } -#endif - - result= my_seek(file, pos, whence, flags); - return result; -} - -static inline my_off_t -inline_mysql_file_tell( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File file, myf flags) -{ - my_off_t result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_TELL); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_tell(file, flags); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); - return result; - } -#endif - - result= my_tell(file, flags); - return result; -} - -static inline int -inline_mysql_file_delete( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *name, myf flags) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_DELETE, name, &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); - result= my_delete(name, flags); - PSI_FILE_CALL(end_file_close_wait)(locker, result); - return result; - } -#endif - - result= my_delete(name, flags); - return result; -} - -static inline int -inline_mysql_file_rename( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *from, const char *to, myf flags) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker) - (&state, key, PSI_FILE_RENAME, from, &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_rename(from, to, flags); - PSI_FILE_CALL(end_file_rename_wait)(locker, from, to, result); - return result; - } -#endif - - result= my_rename(from, to, flags); - return result; -} - - -static inline File -inline_mysql_file_create_with_symlink( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *linkname, const char *filename, int create_flags, - int access_flags, myf flags) -{ - File file; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_CREATE, filename, - &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); - file= my_create_with_symlink(linkname, filename, create_flags, access_flags, - flags); - PSI_FILE_CALL(end_file_open_wait_and_bind_to_descriptor)(locker, file); - return file; - } -#endif - - file= my_create_with_symlink(linkname, filename, create_flags, access_flags, - flags); - return file; -} - - -static inline int -inline_mysql_file_delete_with_symlink( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *name, const char *ext, myf flags) -{ - int result; - char buf[FN_REFLEN]; - char *fullname= fn_format(buf, name, "", ext, MY_UNPACK_FILENAME | MY_APPEND_EXT); -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_DELETE, fullname, - &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); - result= my_handler_delete_with_symlink(fullname, flags); - PSI_FILE_CALL(end_file_close_wait)(locker, result); - return result; - } -#endif - - result= my_handler_delete_with_symlink(fullname, flags); - return result; -} - - -static inline int -inline_mysql_file_rename_with_symlink( -#ifdef HAVE_PSI_FILE_INTERFACE - PSI_file_key key, const char *src_file, uint src_line, -#endif - const char *from, const char *to, myf flags) -{ - int result; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_name_locker) - (&state, key, PSI_FILE_RENAME, from, &locker); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_rename_with_symlink(from, to, flags); - PSI_FILE_CALL(end_file_rename_wait)(locker, from, to, result); - return result; - } -#endif - - result= my_rename_with_symlink(from, to, flags); - return result; -} - -static inline int -inline_mysql_file_sync( -#ifdef HAVE_PSI_FILE_INTERFACE - const char *src_file, uint src_line, -#endif - File fd, myf flags) -{ - int result= 0; -#ifdef HAVE_PSI_FILE_INTERFACE - struct PSI_file_locker *locker; - PSI_file_locker_state state; - locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, fd, PSI_FILE_SYNC); - if (psi_likely(locker != NULL)) - { - PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); - result= my_sync(fd, flags); - PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); - return result; - } -#endif - - result= my_sync(fd, flags); - return result; -} - -/** @} (end of group File_instrumentation) */ - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_idle.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_idle.h deleted file mode 100644 index f808507..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_idle.h +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_IDLE_H -#define MYSQL_IDLE_H - -/** - @file mysql/psi/mysql_idle.h - Instrumentation helpers for idle waits. -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_IDLE_CALL -#define PSI_IDLE_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Idle_instrumentation Idle Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -/** - @def MYSQL_START_IDLE_WAIT - Instrumentation helper for table io_waits. - This instrumentation marks the start of a wait event. - @param LOCKER the locker - @param STATE the locker state - @sa MYSQL_END_IDLE_WAIT. -*/ -#ifdef HAVE_PSI_IDLE_INTERFACE - #define MYSQL_START_IDLE_WAIT(LOCKER, STATE) \ - LOCKER= inline_mysql_start_idle_wait(STATE, __FILE__, __LINE__) -#else - #define MYSQL_START_IDLE_WAIT(LOCKER, STATE) \ - do {} while (0) -#endif - -/** - @def MYSQL_END_IDLE_WAIT - Instrumentation helper for idle waits. - This instrumentation marks the end of a wait event. - @param LOCKER the locker - @sa MYSQL_START_IDLE_WAIT. -*/ -#ifdef HAVE_PSI_IDLE_INTERFACE - #define MYSQL_END_IDLE_WAIT(LOCKER) \ - inline_mysql_end_idle_wait(LOCKER) -#else - #define MYSQL_END_IDLE_WAIT(LOCKER) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_IDLE_INTERFACE -/** - Instrumentation calls for MYSQL_START_IDLE_WAIT. - @sa MYSQL_END_IDLE_WAIT. -*/ -static inline struct PSI_idle_locker * -inline_mysql_start_idle_wait(PSI_idle_locker_state *state, - const char *src_file, uint src_line) -{ - struct PSI_idle_locker *locker; - locker= PSI_IDLE_CALL(start_idle_wait)(state, src_file, src_line); - return locker; -} - -/** - Instrumentation calls for MYSQL_END_IDLE_WAIT. - @sa MYSQL_START_IDLE_WAIT. -*/ -static inline void -inline_mysql_end_idle_wait(struct PSI_idle_locker *locker) -{ - if (psi_likely(locker != NULL)) - PSI_IDLE_CALL(end_idle_wait)(locker); -} -#endif - -/** @} (end of group Idle_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_mdl.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_mdl.h deleted file mode 100644 index 20d6c94..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_mdl.h +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_MDL_H -#define MYSQL_MDL_H - -/** - @file mysql/psi/mysql_mdl.h - Instrumentation helpers for metadata locks. -*/ - -#include "mysql/psi/psi.h" - -#ifdef HAVE_PSI_METADATA_INTERFACE - -#ifndef PSI_METADATA_CALL -#define PSI_METADATA_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -#define PSI_CALL_start_metadata_wait(A,B,C,D) PSI_METADATA_CALL(start_metadata_wait)(A,B,C,D) -#define PSI_CALL_end_metadata_wait(A,B) PSI_METADATA_CALL(end_metadata_wait)(A,B) -#define PSI_CALL_create_metadata_lock(A,B,C,D,E,F,G) PSI_METADATA_CALL(create_metadata_lock)(A,B,C,D,E,F,G) -#define PSI_CALL_set_metadata_lock_status(A,B) PSI_METADATA_CALL(set_metadata_lock_status)(A,B) -#define PSI_CALL_destroy_metadata_lock(A) PSI_METADATA_CALL(destroy_metadata_lock)(A) -#else -#define PSI_CALL_start_metadata_wait(A,B,C,D) 0 -#define PSI_CALL_end_metadata_wait(A,B) do { } while(0) -#define PSI_CALL_create_metadata_lock(A,B,C,D,E,F,G) 0 -#define PSI_CALL_set_metadata_lock_status(A,B) do {} while(0) -#define PSI_CALL_destroy_metadata_lock(A) do {} while(0) -#endif - -/** - @defgroup Thread_instrumentation Metadata Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -/** - @def mysql_mdl_create(K, M, A) - Instrumented metadata lock creation. - @param I Metadata lock identity - @param K Metadata key - @param T Metadata lock type - @param D Metadata lock duration - @param S Metadata lock status - @param F request source file - @param L request source line -*/ - -#ifdef HAVE_PSI_METADATA_INTERFACE - #define mysql_mdl_create(I, K, T, D, S, F, L) \ - inline_mysql_mdl_create(I, K, T, D, S, F, L) -#else - #define mysql_mdl_create(I, K, T, D, S, F, L) NULL -#endif - -#ifdef HAVE_PSI_METADATA_INTERFACE - #define mysql_mdl_set_status(L, S) \ - inline_mysql_mdl_set_status(L, S) -#else - #define mysql_mdl_set_status(L, S) \ - do {} while (0) -#endif - - -/** - @def mysql_mdl_destroy(M) - Instrumented metadata lock destruction. - @param M Metadata lock -*/ -#ifdef HAVE_PSI_METADATA_INTERFACE - #define mysql_mdl_destroy(M) \ - inline_mysql_mdl_destroy(M, __FILE__, __LINE__) -#else - #define mysql_mdl_destroy(M) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_METADATA_INTERFACE - -static inline PSI_metadata_lock * -inline_mysql_mdl_create(void *identity, - const MDL_key *mdl_key, - enum_mdl_type mdl_type, - enum_mdl_duration mdl_duration, - MDL_ticket::enum_psi_status mdl_status, - const char *src_file, uint src_line) -{ - PSI_metadata_lock *result; - - /* static_cast: Fit a round C++ enum peg into a square C int hole ... */ - result= PSI_METADATA_CALL(create_metadata_lock) - (identity, - mdl_key, - static_cast (mdl_type), - static_cast (mdl_duration), - static_cast (mdl_status), - src_file, src_line); - - return result; -} - -static inline void inline_mysql_mdl_set_status( - PSI_metadata_lock *psi, - MDL_ticket::enum_psi_status mdl_status) -{ - if (psi != NULL) - PSI_METADATA_CALL(set_metadata_lock_status)(psi, mdl_status); -} - -static inline void inline_mysql_mdl_destroy( - PSI_metadata_lock *psi, - const char *src_file, uint src_line) -{ - if (psi != NULL) - PSI_METADATA_CALL(destroy_metadata_lock)(psi); -} -#endif /* HAVE_PSI_METADATA_INTERFACE */ - -/** @} (end of group Metadata_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_memory.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_memory.h deleted file mode 100644 index a79579c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_memory.h +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_MEMORY_H -#define MYSQL_MEMORY_H - -/** - @file mysql/psi/mysql_memory.h - Instrumentation helpers for memory allocation. -*/ - -#include "mysql/psi/psi.h" - -#ifdef HAVE_PSI_MEMORY_INTERFACE -#define PSI_CALL_memory_alloc(A1,A2,A3) PSI_MEMORY_CALL(memory_alloc)(A1,A2,A3) -#define PSI_CALL_memory_free(A1,A2,A3) PSI_MEMORY_CALL(memory_free)(A1,A2,A3) -#define PSI_CALL_memory_realloc(A1,A2,A3,A4) PSI_MEMORY_CALL(memory_realloc)(A1,A2,A3,A4) -#define PSI_CALL_register_memory(A1,A2,A3) PSI_MEMORY_CALL(register_memory)(A1,A2,A3) -#else -#define PSI_CALL_memory_alloc(A1,A2,A3) 0 -#define PSI_CALL_memory_free(A1,A2,A3) do { } while(0) -#define PSI_CALL_memory_realloc(A1,A2,A3,A4) 0 -#define PSI_CALL_register_memory(A1,A2,A3) do { } while(0) -#endif - -#ifndef PSI_MEMORY_CALL -#define PSI_MEMORY_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Memory_instrumentation Memory Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -/** - @def mysql_memory_register(P1, P2, P3) - Memory registration. -*/ -#define mysql_memory_register(P1, P2, P3) \ - inline_mysql_memory_register(P1, P2, P3) - -static inline void inline_mysql_memory_register( -#ifdef HAVE_PSI_MEMORY_INTERFACE - const char *category, - PSI_memory_info *info, - int count) -#else - const char *category __attribute__((unused)), - void *info __attribute__((unused)), - int count __attribute__((unused))) -#endif -{ - PSI_CALL_register_memory(category, info, count); -} - -/** @} (end of group Memory_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_ps.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_ps.h deleted file mode 100644 index f0b2733..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_ps.h +++ /dev/null @@ -1,108 +0,0 @@ -/* Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef MYSQL_PS_H -#define MYSQL_PS_H - -/** - @file mysql/psi/mysql_ps.h - Instrumentation helpers for prepared statements. -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_PS_CALL -#define PSI_PS_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -#ifdef HAVE_PSI_PS_INTERFACE - #define MYSQL_CREATE_PS(IDENTITY, ID, LOCKER, NAME, NAME_LENGTH) \ - inline_mysql_create_prepared_stmt(IDENTITY, ID, LOCKER, NAME, NAME_LENGTH) - #define MYSQL_EXECUTE_PS(LOCKER, PREPARED_STMT) \ - inline_mysql_execute_prepared_stmt(LOCKER, PREPARED_STMT) - #define MYSQL_DESTROY_PS(PREPARED_STMT) \ - inline_mysql_destroy_prepared_stmt(PREPARED_STMT) - #define MYSQL_REPREPARE_PS(PREPARED_STMT) \ - inline_mysql_reprepare_prepared_stmt(PREPARED_STMT) - #define MYSQL_SET_PS_TEXT(PREPARED_STMT, SQLTEXT, SQLTEXT_LENGTH) \ - inline_mysql_set_prepared_stmt_text(PREPARED_STMT, SQLTEXT, SQLTEXT_LENGTH) -#else - #define MYSQL_CREATE_PS(IDENTITY, ID, LOCKER, NAME, NAME_LENGTH) \ - NULL - #define MYSQL_EXECUTE_PS(LOCKER, PREPARED_STMT) \ - do {} while (0) - #define MYSQL_DESTROY_PS(PREPARED_STMT) \ - do {} while (0) - #define MYSQL_REPREPARE_PS(PREPARED_STMT) \ - do {} while (0) - #define MYSQL_SET_PS_TEXT(PREPARED_STMT, SQLTEXT, SQLTEXT_LENGTH) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_PS_INTERFACE -static inline struct PSI_prepared_stmt* -inline_mysql_create_prepared_stmt(void *identity, uint stmt_id, - PSI_statement_locker *locker, - const char *stmt_name, size_t stmt_name_length) -{ - if (locker == NULL) - return NULL; - return PSI_PS_CALL(create_prepared_stmt)(identity, stmt_id, - locker, - stmt_name, stmt_name_length); -} - -static inline void -inline_mysql_execute_prepared_stmt(PSI_statement_locker *locker, - PSI_prepared_stmt* prepared_stmt) -{ - if (prepared_stmt != NULL && locker != NULL) - PSI_PS_CALL(execute_prepared_stmt)(locker, prepared_stmt); -} - -static inline void -inline_mysql_destroy_prepared_stmt(PSI_prepared_stmt *prepared_stmt) -{ - if (prepared_stmt != NULL) - PSI_PS_CALL(destroy_prepared_stmt)(prepared_stmt); -} - -static inline void -inline_mysql_reprepare_prepared_stmt(PSI_prepared_stmt *prepared_stmt) -{ - if (prepared_stmt != NULL) - PSI_PS_CALL(reprepare_prepared_stmt)(prepared_stmt); -} - -static inline void -inline_mysql_set_prepared_stmt_text(PSI_prepared_stmt *prepared_stmt, - const char *text, - uint text_len) -{ - if (prepared_stmt != NULL) - { - PSI_PS_CALL(set_prepared_stmt_text)(prepared_stmt, text, text_len); - } -} -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_socket.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_socket.h deleted file mode 100644 index aa85daa..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_socket.h +++ /dev/null @@ -1,1295 +0,0 @@ -/* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, MariaDB Corporation. - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License, version 2.0, -as published by the Free Software Foundation. - -This program is also distributed with certain software (including -but not limited to OpenSSL) that is licensed under separate terms, -as designated in a particular file or component or in included license -documentation. The authors of MySQL hereby grant you an additional -permission to link the program and your derivative works with the -separately licensed software that they have included with MySQL. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License, version 2.0, for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA -02110-1335 USA -*/ - -#ifndef MYSQL_SOCKET_H -#define MYSQL_SOCKET_H - -/* For MY_STAT */ -#include -/* For my_chsize */ -#include -/* For socket api */ -#ifdef _WIN32 - #include - #include - #include - #define SOCKBUF_T char -#else - #include - #define SOCKBUF_T void -#endif -/** - @file mysql/psi/mysql_socket.h -[...] -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_SOCKET_CALL -#define PSI_SOCKET_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Socket_instrumentation Socket Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -/** - @def mysql_socket_register(P1, P2, P3) - Socket registration. -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_register(P1, P2, P3) \ - inline_mysql_socket_register(P1, P2, P3) -#else - #define mysql_socket_register(P1, P2, P3) \ - do {} while (0) -#endif - -/** An instrumented socket. */ -struct st_mysql_socket -{ - /** The real socket descriptor. */ - my_socket fd; - - /** - The instrumentation hook. - Note that this hook is not conditionally defined, - for binary compatibility of the @c MYSQL_SOCKET interface. - */ - struct PSI_socket *m_psi; -}; - -/** - An instrumented socket. - @c MYSQL_SOCKET is a replacement for @c my_socket. -*/ -typedef struct st_mysql_socket MYSQL_SOCKET; - - -/** - @def MYSQL_INVALID_SOCKET - MYSQL_SOCKET initial value. -*/ -//MYSQL_SOCKET MYSQL_INVALID_SOCKET= {INVALID_SOCKET, NULL}; -#define MYSQL_INVALID_SOCKET mysql_socket_invalid() - -/** - MYSQL_SOCKET helper. Initialize instrumented socket. - @sa mysql_socket_getfd - @sa mysql_socket_setfd -*/ -static inline MYSQL_SOCKET -mysql_socket_invalid() -{ - MYSQL_SOCKET mysql_socket= {INVALID_SOCKET, NULL}; - return mysql_socket; -} - -/** - Set socket descriptor and address. - @param socket nstrumented socket - @param addr unformatted socket address - @param addr_len length of socket address -*/ - -static inline void -mysql_socket_set_address( -#ifdef HAVE_PSI_SOCKET_INTERFACE - MYSQL_SOCKET socket, - const struct sockaddr *addr, - socklen_t addr_len -#else - MYSQL_SOCKET socket __attribute__ ((unused)), - const struct sockaddr *addr __attribute__ ((unused)), - socklen_t addr_len __attribute__ ((unused)) -#endif -) -{ -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (socket.m_psi != NULL) - PSI_SOCKET_CALL(set_socket_info)(socket.m_psi, NULL, addr, addr_len); -#endif -} - -/** - Set socket descriptor and address. - @param socket instrumented socket -*/ -static inline void -mysql_socket_set_thread_owner( -#ifdef HAVE_PSI_SOCKET_INTERFACE -MYSQL_SOCKET socket -#else -MYSQL_SOCKET socket __attribute__ ((unused)) -#endif -) -{ -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (socket.m_psi != NULL) - PSI_SOCKET_CALL(set_socket_thread_owner)(socket.m_psi); -#endif -} - -/** - MYSQL_SOCKET helper. Get socket descriptor. - @param mysql_socket Instrumented socket - @sa mysql_socket_getfd -*/ -static inline my_socket -mysql_socket_getfd(MYSQL_SOCKET mysql_socket) -{ - return mysql_socket.fd; -} - -/** - MYSQL_SOCKET helper. Set socket descriptor. - @param mysql_socket Instrumented socket - @param fd Socket descriptor - @sa mysql_socket_setfd -*/ -static inline void -mysql_socket_setfd(MYSQL_SOCKET *mysql_socket, my_socket fd) -{ - if (likely(mysql_socket != NULL)) - mysql_socket->fd= fd; -} - -/** - @def MYSQL_SOCKET_WAIT_VARIABLES - Instrumentation helper for socket waits. - This instrumentation declares local variables. - Do not use a ';' after this macro - @param LOCKER locker - @param STATE locker state - @sa MYSQL_START_SOCKET_WAIT. - @sa MYSQL_END_SOCKET_WAIT. -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define MYSQL_SOCKET_WAIT_VARIABLES(LOCKER, STATE) \ - struct PSI_socket_locker* LOCKER; \ - PSI_socket_locker_state STATE; -#else - #define MYSQL_SOCKET_WAIT_VARIABLES(LOCKER, STATE) -#endif - -/** - @def MYSQL_START_SOCKET_WAIT - Instrumentation helper for socket waits. - This instrumentation marks the start of a wait event. - @param LOCKER locker - @param STATE locker state - @param SOCKET instrumented socket - @param OP The socket operation to be performed - @param COUNT bytes to be written/read - @sa MYSQL_END_SOCKET_WAIT. -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define MYSQL_START_SOCKET_WAIT(LOCKER, STATE, SOCKET, OP, COUNT) \ - LOCKER= inline_mysql_start_socket_wait(STATE, SOCKET, OP, COUNT,\ - __FILE__, __LINE__) -#else - #define MYSQL_START_SOCKET_WAIT(LOCKER, STATE, SOCKET, OP, COUNT) \ - do {} while (0) -#endif - -/** - @def MYSQL_END_SOCKET_WAIT - Instrumentation helper for socket waits. - This instrumentation marks the end of a wait event. - @param LOCKER locker - @param COUNT actual bytes written/read, or -1 - @sa MYSQL_START_SOCKET_WAIT. -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define MYSQL_END_SOCKET_WAIT(LOCKER, COUNT) \ - inline_mysql_end_socket_wait(LOCKER, COUNT) -#else - #define MYSQL_END_SOCKET_WAIT(LOCKER, COUNT) \ - do {} while (0) -#endif - -/** - @def MYSQL_SOCKET_SET_STATE - Set the state (IDLE, ACTIVE) of an instrumented socket. - @param SOCKET the instrumented socket - @param STATE the new state - @sa PSI_socket_state -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define MYSQL_SOCKET_SET_STATE(SOCKET, STATE) \ - inline_mysql_socket_set_state(SOCKET, STATE) -#else - #define MYSQL_SOCKET_SET_STATE(SOCKET, STATE) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_SOCKET_INTERFACE -/** - Instrumentation calls for MYSQL_START_SOCKET_WAIT. - @sa MYSQL_START_SOCKET_WAIT. -*/ -static inline struct PSI_socket_locker* -inline_mysql_start_socket_wait(PSI_socket_locker_state *state, - MYSQL_SOCKET mysql_socket, - enum PSI_socket_operation op, - size_t byte_count, - const char *src_file, uint src_line) -{ - struct PSI_socket_locker *locker; - if (psi_likely(mysql_socket.m_psi != NULL)) - { - locker= PSI_SOCKET_CALL(start_socket_wait) - (state, mysql_socket.m_psi, op, byte_count, src_file, src_line); - } - else - locker= NULL; - return locker; -} - -/** - Instrumentation calls for MYSQL_END_SOCKET_WAIT. - @sa MYSQL_END_SOCKET_WAIT. -*/ -static inline void -inline_mysql_end_socket_wait(struct PSI_socket_locker *locker, size_t byte_count) -{ - if (psi_likely(locker != NULL)) - PSI_SOCKET_CALL(end_socket_wait)(locker, byte_count); -} - -/** - Set the state (IDLE, ACTIVE) of an instrumented socket. - @param socket the instrumented socket - @param state the new state - @sa PSI_socket_state -*/ -static inline void -inline_mysql_socket_set_state(MYSQL_SOCKET socket, enum PSI_socket_state state) -{ - if (socket.m_psi != NULL) - PSI_SOCKET_CALL(set_socket_state)(socket.m_psi, state); -} -#endif /* HAVE_PSI_SOCKET_INTERFACE */ - -/** - @def mysql_socket_socket(K, D, T, P) - Create a socket. - @c mysql_socket_socket is a replacement for @c socket. - @param K PSI_socket_key for this instrumented socket - @param D Socket domain - @param T Protocol type - @param P Transport protocol -*/ - -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_socket(K, D, T, P) \ - inline_mysql_socket_socket(K, D, T, P) -#else - #define mysql_socket_socket(K, D, T, P) \ - inline_mysql_socket_socket(D, T, P) -#endif - -/** - @def mysql_socket_bind(FD, AP, L) - Bind a socket to a local port number and IP address - @c mysql_socket_bind is a replacement for @c bind. - @param FD Instrumented socket descriptor returned by socket() - @param AP Pointer to local port number and IP address in sockaddr structure - @param L Length of sockaddr structure -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_bind(FD, AP, L) \ - inline_mysql_socket_bind(__FILE__, __LINE__, FD, AP, L) -#else - #define mysql_socket_bind(FD, AP, L) \ - inline_mysql_socket_bind(FD, AP, L) -#endif - -/** - @def mysql_socket_getsockname(FD, AP, LP) - Return port number and IP address of the local host - @c mysql_socket_getsockname is a replacement for @c getsockname. - @param FD Instrumented socket descriptor returned by socket() - @param AP Pointer to returned address of local host in @c sockaddr structure - @param LP Pointer to length of @c sockaddr structure -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_getsockname(FD, AP, LP) \ - inline_mysql_socket_getsockname(__FILE__, __LINE__, FD, AP, LP) -#else - #define mysql_socket_getsockname(FD, AP, LP) \ - inline_mysql_socket_getsockname(FD, AP, LP) -#endif - -/** - @def mysql_socket_connect(FD, AP, L) - Establish a connection to a remote host. - @c mysql_socket_connect is a replacement for @c connect. - @param FD Instrumented socket descriptor returned by socket() - @param AP Pointer to target address in sockaddr structure - @param L Length of sockaddr structure -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_connect(FD, AP, L) \ - inline_mysql_socket_connect(__FILE__, __LINE__, FD, AP, L) -#else - #define mysql_socket_connect(FD, AP, L) \ - inline_mysql_socket_connect(FD, AP, L) -#endif - -/** - @def mysql_socket_getpeername(FD, AP, LP) - Get port number and IP address of remote host that a socket is connected to. - @c mysql_socket_getpeername is a replacement for @c getpeername. - @param FD Instrumented socket descriptor returned by socket() or accept() - @param AP Pointer to returned address of remote host in sockaddr structure - @param LP Pointer to length of sockaddr structure -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_getpeername(FD, AP, LP) \ - inline_mysql_socket_getpeername(__FILE__, __LINE__, FD, AP, LP) -#else - #define mysql_socket_getpeername(FD, AP, LP) \ - inline_mysql_socket_getpeername(FD, AP, LP) -#endif - -/** - @def mysql_socket_send(FD, B, N, FL) - Send data from the buffer, B, to a connected socket. - @c mysql_socket_send is a replacement for @c send. - @param FD Instrumented socket descriptor returned by socket() or accept() - @param B Buffer to send - @param N Number of bytes to send - @param FL Control flags -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_send(FD, B, N, FL) \ - inline_mysql_socket_send(__FILE__, __LINE__, FD, B, N, FL) -#else - #define mysql_socket_send(FD, B, N, FL) \ - inline_mysql_socket_send(FD, B, N, FL) -#endif - -/** - @def mysql_socket_recv(FD, B, N, FL) - Receive data from a connected socket. - @c mysql_socket_recv is a replacement for @c recv. - @param FD Instrumented socket descriptor returned by socket() or accept() - @param B Buffer to receive to - @param N Maximum bytes to receive - @param FL Control flags -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_recv(FD, B, N, FL) \ - inline_mysql_socket_recv(__FILE__, __LINE__, FD, B, N, FL) -#else - #define mysql_socket_recv(FD, B, N, FL) \ - inline_mysql_socket_recv(FD, B, N, FL) -#endif - -/** - @def mysql_socket_sendto(FD, B, N, FL, AP, L) - Send data to a socket at the specified address. - @c mysql_socket_sendto is a replacement for @c sendto. - @param FD Instrumented socket descriptor returned by socket() - @param B Buffer to send - @param N Number of bytes to send - @param FL Control flags - @param AP Pointer to destination sockaddr structure - @param L Size of sockaddr structure -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_sendto(FD, B, N, FL, AP, L) \ - inline_mysql_socket_sendto(__FILE__, __LINE__, FD, B, N, FL, AP, L) -#else - #define mysql_socket_sendto(FD, B, N, FL, AP, L) \ - inline_mysql_socket_sendto(FD, B, N, FL, AP, L) -#endif - -/** - @def mysql_socket_recvfrom(FD, B, N, FL, AP, L) - Receive data from a socket and return source address information - @c mysql_socket_recvfrom is a replacement for @c recvfrom. - @param FD Instrumented socket descriptor returned by socket() - @param B Buffer to receive to - @param N Maximum bytes to receive - @param FL Control flags - @param AP Pointer to source address in sockaddr_storage structure - @param LP Size of sockaddr_storage structure -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_recvfrom(FD, B, N, FL, AP, LP) \ - inline_mysql_socket_recvfrom(__FILE__, __LINE__, FD, B, N, FL, AP, LP) -#else - #define mysql_socket_recvfrom(FD, B, N, FL, AP, LP) \ - inline_mysql_socket_recvfrom(FD, B, N, FL, AP, LP) -#endif - -/** - @def mysql_socket_getsockopt(FD, LV, ON, OP, OL) - Get a socket option for the specified socket. - @c mysql_socket_getsockopt is a replacement for @c getsockopt. - @param FD Instrumented socket descriptor returned by socket() - @param LV Protocol level - @param ON Option to query - @param OP Buffer which will contain the value for the requested option - @param OL Pointer to length of OP -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_getsockopt(FD, LV, ON, OP, OL) \ - inline_mysql_socket_getsockopt(__FILE__, __LINE__, FD, LV, ON, OP, OL) -#else - #define mysql_socket_getsockopt(FD, LV, ON, OP, OL) \ - inline_mysql_socket_getsockopt(FD, LV, ON, OP, OL) -#endif - -/** - @def mysql_socket_setsockopt(FD, LV, ON, OP, OL) - Set a socket option for the specified socket. - @c mysql_socket_setsockopt is a replacement for @c setsockopt. - @param FD Instrumented socket descriptor returned by socket() - @param LV Protocol level - @param ON Option to modify - @param OP Buffer containing the value for the specified option - @param OL Pointer to length of OP -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_setsockopt(FD, LV, ON, OP, OL) \ - inline_mysql_socket_setsockopt(__FILE__, __LINE__, FD, LV, ON, OP, OL) -#else - #define mysql_socket_setsockopt(FD, LV, ON, OP, OL) \ - inline_mysql_socket_setsockopt(FD, LV, ON, OP, OL) -#endif - -/** - @def mysql_sock_set_nonblocking - Set socket to non-blocking. - @param FD instrumented socket descriptor -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_sock_set_nonblocking(FD) \ - inline_mysql_sock_set_nonblocking(__FILE__, __LINE__, FD) -#else - #define mysql_sock_set_nonblocking(FD) \ - inline_mysql_sock_set_nonblocking(FD) -#endif - -/** - @def mysql_socket_listen(FD, N) - Set socket state to listen for an incoming connection. - @c mysql_socket_listen is a replacement for @c listen. - @param FD Instrumented socket descriptor, bound and connected - @param N Maximum number of pending connections allowed. -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_listen(FD, N) \ - inline_mysql_socket_listen(__FILE__, __LINE__, FD, N) -#else - #define mysql_socket_listen(FD, N) \ - inline_mysql_socket_listen(FD, N) -#endif - -/** - @def mysql_socket_accept(K, FD, AP, LP) - Accept a connection from any remote host; TCP only. - @c mysql_socket_accept is a replacement for @c accept. - @param K PSI_socket_key for this instrumented socket - @param FD Instrumented socket descriptor, bound and placed in a listen state - @param AP Pointer to sockaddr structure with returned IP address and port of connected host - @param LP Pointer to length of valid information in AP -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_accept(K, FD, AP, LP) \ - inline_mysql_socket_accept(__FILE__, __LINE__, K, FD, AP, LP) -#else - #define mysql_socket_accept(K, FD, AP, LP) \ - inline_mysql_socket_accept(FD, AP, LP) -#endif - -/** - @def mysql_socket_close(FD) - Close a socket and sever any connections. - @c mysql_socket_close is a replacement for @c close. - @param FD Instrumented socket descriptor returned by socket() or accept() -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_close(FD) \ - inline_mysql_socket_close(__FILE__, __LINE__, FD) -#else - #define mysql_socket_close(FD) \ - inline_mysql_socket_close(FD) -#endif - -/** - @def mysql_socket_shutdown(FD, H) - Disable receives and/or sends on a socket. - @c mysql_socket_shutdown is a replacement for @c shutdown. - @param FD Instrumented socket descriptor returned by socket() or accept() - @param H Specifies which operations to shutdown -*/ -#ifdef HAVE_PSI_SOCKET_INTERFACE - #define mysql_socket_shutdown(FD, H) \ - inline_mysql_socket_shutdown(__FILE__, __LINE__, FD, H) -#else - #define mysql_socket_shutdown(FD, H) \ - inline_mysql_socket_shutdown(FD, H) -#endif - -#ifdef HAVE_PSI_SOCKET_INTERFACE -static inline void inline_mysql_socket_register( - const char *category, - PSI_socket_info *info, - int count) -{ - PSI_SOCKET_CALL(register_socket)(category, info, count); -} -#endif - -/** mysql_socket_socket */ - -static inline MYSQL_SOCKET -inline_mysql_socket_socket -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - PSI_socket_key key, -#endif - int domain, int type, int protocol) -{ - MYSQL_SOCKET mysql_socket= MYSQL_INVALID_SOCKET; - mysql_socket.fd= socket(domain, type | SOCK_CLOEXEC, protocol); - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (likely(mysql_socket.fd != INVALID_SOCKET)) - { - mysql_socket.m_psi= PSI_SOCKET_CALL(init_socket) - (key, (const my_socket*)&mysql_socket.fd, NULL, 0); - } -#endif - - /* SOCK_CLOEXEC isn't always a number - can't preprocessor compare */ -#if defined(HAVE_FCNTL) && defined(FD_CLOEXEC) && !defined(HAVE_SOCK_CLOEXEC) - (void) fcntl(mysql_socket.fd, F_SETFD, FD_CLOEXEC); -#endif - - return mysql_socket; -} - -/** mysql_socket_bind */ - -static inline int -inline_mysql_socket_bind -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, const struct sockaddr *addr, size_t len) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker_state state; - PSI_socket_locker *locker; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_BIND, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= bind(mysql_socket.fd, addr, (int)len); - - /* Instrumentation end */ - if (result == 0) - PSI_SOCKET_CALL(set_socket_info)(mysql_socket.m_psi, NULL, addr, (socklen_t)len); - - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= bind(mysql_socket.fd, addr, (int)len); - return result; -} - -/** mysql_socket_getsockname */ - -static inline int -inline_mysql_socket_getsockname -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, struct sockaddr *addr, socklen_t *len) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_BIND, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= getsockname(mysql_socket.fd, addr, len); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= getsockname(mysql_socket.fd, addr, len); - - return result; -} - -/** mysql_socket_connect */ - -static inline int -inline_mysql_socket_connect -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, const struct sockaddr *addr, socklen_t len) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_CONNECT, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= connect(mysql_socket.fd, addr, len); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= connect(mysql_socket.fd, addr, len); - - return result; -} - -/** mysql_socket_getpeername */ - -static inline int -inline_mysql_socket_getpeername -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, struct sockaddr *addr, socklen_t *len) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_BIND, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= getpeername(mysql_socket.fd, addr, len); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= getpeername(mysql_socket.fd, addr, len); - - return result; -} - -/** mysql_socket_send */ - -static inline ssize_t -inline_mysql_socket_send -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, const SOCKBUF_T *buf, size_t n, int flags) -{ - ssize_t result; - DBUG_ASSERT(mysql_socket.fd != INVALID_SOCKET); -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_SEND, n, src_file, src_line); - - /* Instrumented code */ - result= send(mysql_socket.fd, buf, IF_WIN((int),) n, flags); - - /* Instrumentation end */ - if (locker != NULL) - { - size_t bytes_written= (result > 0) ? (size_t) result : 0; - PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_written); - } - - return result; - } -#endif - - /* Non instrumented code */ - result= send(mysql_socket.fd, buf, IF_WIN((int),) n, flags); - - return result; -} - -/** mysql_socket_recv */ - -static inline ssize_t -inline_mysql_socket_recv -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, SOCKBUF_T *buf, size_t n, int flags) -{ - ssize_t result; - DBUG_ASSERT(mysql_socket.fd != INVALID_SOCKET); -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_RECV, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= recv(mysql_socket.fd, buf, IF_WIN((int),) n, flags); - - /* Instrumentation end */ - if (locker != NULL) - { - size_t bytes_read= (result > 0) ? (size_t) result : 0; - PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_read); - } - - return result; - } -#endif - - /* Non instrumented code */ - result= recv(mysql_socket.fd, buf, IF_WIN((int),) n, flags); - - return result; -} - -/** mysql_socket_sendto */ - -static inline ssize_t -inline_mysql_socket_sendto -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, const SOCKBUF_T *buf, size_t n, int flags, const struct sockaddr *addr, socklen_t addr_len) -{ - ssize_t result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_SEND, n, src_file, src_line); - - /* Instrumented code */ - result= sendto(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); - - /* Instrumentation end */ - if (locker != NULL) - { - size_t bytes_written = (result > 0) ? (size_t) result : 0; - PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_written); - } - - return result; - } -#endif - - /* Non instrumented code */ - result= sendto(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); - - return result; -} - -/** mysql_socket_recvfrom */ - -static inline ssize_t -inline_mysql_socket_recvfrom -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, SOCKBUF_T *buf, size_t n, int flags, - struct sockaddr *addr, socklen_t *addr_len) -{ - ssize_t result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_RECV, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= recvfrom(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); - - /* Instrumentation end */ - if (locker != NULL) - { - size_t bytes_read= (result > 0) ? (size_t) result : 0; - PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_read); - } - - return result; - } -#endif - - /* Non instrumented code */ - result= recvfrom(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); - - return result; -} - -/** mysql_socket_getsockopt */ - -static inline int -inline_mysql_socket_getsockopt -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, int level, int optname, SOCKBUF_T *optval, socklen_t *optlen) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_OPT, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= getsockopt(mysql_socket.fd, level, optname, optval, optlen); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= getsockopt(mysql_socket.fd, level, optname, optval, optlen); - - return result; -} - -/** mysql_socket_setsockopt */ - -static inline int -inline_mysql_socket_setsockopt -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, int level, int optname, const SOCKBUF_T *optval, - socklen_t optlen) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_OPT, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= setsockopt(mysql_socket.fd, level, optname, optval, optlen); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= setsockopt(mysql_socket.fd, level, optname, optval, optlen); - - return result; -} - -/** set_socket_nonblock */ -static inline int -set_socket_nonblock(my_socket fd) -{ - int ret= 0; -#ifdef _WIN32 - { - u_long nonblocking= 1; - ret= ioctlsocket(fd, FIONBIO, &nonblocking); - } -#else - { - int fd_flags; - fd_flags= fcntl(fd, F_GETFL, 0); - if (fd_flags < 0) - return errno; -#if defined(O_NONBLOCK) - fd_flags |= O_NONBLOCK; -#elif defined(O_NDELAY) - fd_flags |= O_NDELAY; -#elif defined(O_FNDELAY) - fd_flags |= O_FNDELAY; -#else -#error "No definition of non-blocking flag found." -#endif /* O_NONBLOCK */ - if (fcntl(fd, F_SETFL, fd_flags) == -1) - ret= errno; - } -#endif /* _WIN32 */ - return ret; -} - -/** mysql_socket_set_nonblocking */ - -static inline int -inline_mysql_sock_set_nonblocking -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket -) -{ - int result= 0; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (mysql_socket.m_psi) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_OPT, - (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= set_socket_nonblock(mysql_socket.fd); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= set_socket_nonblock(mysql_socket.fd); - - return result; -} - -/** mysql_socket_listen */ - -static inline int -inline_mysql_socket_listen -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, int backlog) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_CONNECT, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= listen(mysql_socket.fd, backlog); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ - result= listen(mysql_socket.fd, backlog); - - return result; -} - -/** mysql_socket_accept */ - -static inline MYSQL_SOCKET -inline_mysql_socket_accept -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, PSI_socket_key key, -#endif - MYSQL_SOCKET socket_listen, struct sockaddr *addr, socklen_t *addr_len) -{ -#ifdef FD_CLOEXEC - int flags __attribute__ ((unused)); -#endif - - MYSQL_SOCKET socket_accept; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (socket_listen.m_psi != NULL) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, socket_listen.m_psi, PSI_SOCKET_CONNECT, (size_t)0, src_file, src_line); - - /* Instrumented code */ -#ifdef HAVE_ACCEPT4 - socket_accept.fd= accept4(socket_listen.fd, addr, addr_len, SOCK_CLOEXEC); -#else - socket_accept.fd= accept(socket_listen.fd, addr, addr_len); -#ifdef FD_CLOEXEC - if (socket_accept.fd != INVALID_SOCKET) - { - flags= fcntl(socket_accept.fd, F_GETFD); - if (flags != -1) - { - flags |= FD_CLOEXEC; - fcntl(socket_accept.fd, F_SETFD, flags); - } - } -#endif -#endif - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - } - else -#endif - { - /* Non instrumented code */ -#ifdef HAVE_ACCEPT4 - socket_accept.fd= accept4(socket_listen.fd, addr, addr_len, SOCK_CLOEXEC); -#else - socket_accept.fd= accept(socket_listen.fd, addr, addr_len); -#ifdef FD_CLOEXEC - if (socket_accept.fd != INVALID_SOCKET) - { - flags= fcntl(socket_accept.fd, F_GETFD); - if (flags != -1) - { - flags |= FD_CLOEXEC; - fcntl(socket_accept.fd, F_SETFD, flags); - } - } -#endif -#endif - } - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (likely(socket_accept.fd != INVALID_SOCKET)) - { - /* Initialize the instrument with the new socket descriptor and address */ - socket_accept.m_psi= PSI_SOCKET_CALL(init_socket) - (key, (const my_socket*)&socket_accept.fd, addr, *addr_len); - } -#endif - - return socket_accept; -} - -/** mysql_socket_close */ - -static inline int -inline_mysql_socket_close -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket) -{ - int result; - -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - /* Instrumentation start */ - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_CLOSE, (size_t)0, src_file, src_line); - - /* Instrumented code */ - result= closesocket(mysql_socket.fd); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - /* Remove the instrumentation for this socket. */ - if (mysql_socket.m_psi != NULL) - PSI_SOCKET_CALL(destroy_socket)(mysql_socket.m_psi); - - return result; - } -#endif - - /* Non instrumented code */ - result= closesocket(mysql_socket.fd); - - return result; -} - -/** mysql_socket_shutdown */ - -static inline int -inline_mysql_socket_shutdown -( -#ifdef HAVE_PSI_SOCKET_INTERFACE - const char *src_file, uint src_line, -#endif - MYSQL_SOCKET mysql_socket, int how) -{ - int result; - -#ifdef _WIN32 - static LPFN_DISCONNECTEX DisconnectEx = NULL; - if (DisconnectEx == NULL) - { - DWORD dwBytesReturned; - GUID guidDisconnectEx = WSAID_DISCONNECTEX; - WSAIoctl(mysql_socket.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, - &guidDisconnectEx, sizeof(GUID), - &DisconnectEx, sizeof(DisconnectEx), - &dwBytesReturned, NULL, NULL); - } -#endif - -/* Instrumentation start */ -#ifdef HAVE_PSI_SOCKET_INTERFACE - if (psi_likely(mysql_socket.m_psi != NULL)) - { - PSI_socket_locker *locker; - PSI_socket_locker_state state; - locker= PSI_SOCKET_CALL(start_socket_wait) - (&state, mysql_socket.m_psi, PSI_SOCKET_SHUTDOWN, (size_t)0, src_file, src_line); - - /* Instrumented code */ -#ifdef _WIN32 - if (DisconnectEx) - result= (DisconnectEx(mysql_socket.fd, (LPOVERLAPPED) NULL, - (DWORD) 0, (DWORD) 0) == TRUE) ? 0 : -1; - else -#endif - result= shutdown(mysql_socket.fd, how); - - /* Instrumentation end */ - if (locker != NULL) - PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); - - return result; - } -#endif - - /* Non instrumented code */ -#ifdef _WIN32 - if (DisconnectEx) - result= (DisconnectEx(mysql_socket.fd, (LPOVERLAPPED) NULL, - (DWORD) 0, (DWORD) 0) == TRUE) ? 0 : -1; - else -#endif - result= shutdown(mysql_socket.fd, how); - - return result; -} - -/** @} (end of group Socket_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_sp.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_sp.h deleted file mode 100644 index 5eeea37..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_sp.h +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef MYSQL_SP_H -#define MYSQL_SP_H - -/** - @file mysql/psi/mysql_sp.h - Instrumentation helpers for stored programs. -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_SP_CALL -#define PSI_SP_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -#ifdef HAVE_PSI_SP_INTERFACE - #define MYSQL_START_SP(STATE, SP_SHARE) \ - inline_mysql_start_sp(STATE, SP_SHARE) -#else - #define MYSQL_START_SP(STATE, SP_SHARE) \ - NULL -#endif - - -#ifdef HAVE_PSI_SP_INTERFACE - #define MYSQL_END_SP(LOCKER) \ - inline_mysql_end_sp(LOCKER) -#else - #define MYSQL_END_SP(LOCKER) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_SP_INTERFACE - #define MYSQL_DROP_SP(OT, SN, SNL, ON, ONL) \ - inline_mysql_drop_sp(OT, SN, SNL, ON, ONL) -#else - #define MYSQL_DROP_SP(OT, SN, SNL, ON, ONL) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_SP_INTERFACE - #define MYSQL_GET_SP_SHARE(OT, SN, SNL, ON, ONL) \ - inline_mysql_get_sp_share(OT, SN, SNL, ON, ONL) -#else - #define MYSQL_GET_SP_SHARE(OT, SN, SNL, ON, ONL) \ - NULL -#endif - -#ifdef HAVE_PSI_SP_INTERFACE -static inline struct PSI_sp_locker* -inline_mysql_start_sp(PSI_sp_locker_state *state, PSI_sp_share *sp_share) -{ - return PSI_SP_CALL(start_sp)(state, sp_share); -} - -static inline void inline_mysql_end_sp(PSI_sp_locker *locker) -{ - if (likely(locker != NULL)) - PSI_SP_CALL(end_sp)(locker); -} - -static inline void -inline_mysql_drop_sp(uint sp_type, - const char* schema_name, uint shcema_name_length, - const char* object_name, uint object_name_length) -{ - PSI_SP_CALL(drop_sp)(sp_type, - schema_name, shcema_name_length, - object_name, object_name_length); -} - -static inline PSI_sp_share* -inline_mysql_get_sp_share(uint sp_type, - const char* schema_name, uint shcema_name_length, - const char* object_name, uint object_name_length) -{ - return PSI_SP_CALL(get_sp_share)(sp_type, - schema_name, shcema_name_length, - object_name, object_name_length); -} -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_stage.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_stage.h deleted file mode 100644 index 732df6b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_stage.h +++ /dev/null @@ -1,205 +0,0 @@ -/* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_STAGE_H -#define MYSQL_STAGE_H - -/** - @file mysql/psi/mysql_stage.h - Instrumentation helpers for stages. -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_STAGE_CALL -#define PSI_STAGE_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Stage_instrumentation Stage Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -/** - @def mysql_stage_register(P1, P2, P3) - Stage registration. -*/ -#ifdef HAVE_PSI_STAGE_INTERFACE -#define mysql_stage_register(P1, P2, P3) \ - inline_mysql_stage_register(P1, P2, P3) -#else -#define mysql_stage_register(P1, P2, P3) \ - do {} while (0) -#endif - -/** - @def MYSQL_SET_STAGE - Set the current stage. - Use this API when the file and line - is passed from the caller. - @param K the stage key - @param F the source file name - @param L the source file line - @return the current stage progress -*/ -#ifdef HAVE_PSI_STAGE_INTERFACE - #define MYSQL_SET_STAGE(K, F, L) \ - inline_mysql_set_stage(K, F, L) -#else - #define MYSQL_SET_STAGE(K, F, L) \ - NULL -#endif - -/** - @def mysql_set_stage - Set the current stage. - @param K the stage key - @return the current stage progress -*/ -#ifdef HAVE_PSI_STAGE_INTERFACE - #define mysql_set_stage(K) \ - inline_mysql_set_stage(K, __FILE__, __LINE__) -#else - #define mysql_set_stage(K) \ - NULL -#endif - -/** - @def mysql_end_stage - End the last stage -*/ -#ifdef HAVE_PSI_STAGE_INTERFACE - #define mysql_end_stage() \ - inline_mysql_end_stage() -#else - #define mysql_end_stage() \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -static inline void inline_mysql_stage_register( - const char *category, PSI_stage_info **info, int count) -{ - PSI_STAGE_CALL(register_stage)(category, info, count); -} -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -static inline PSI_stage_progress* -inline_mysql_set_stage(PSI_stage_key key, - const char *src_file, int src_line) -{ - return PSI_STAGE_CALL(start_stage)(key, src_file, src_line); -} -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -static inline void -inline_mysql_end_stage() -{ - PSI_STAGE_CALL(end_stage)(); -} -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -#define mysql_stage_set_work_completed(P1, P2) \ - inline_mysql_stage_set_work_completed(P1, P2) - -#define mysql_stage_get_work_completed(P1) \ - inline_mysql_stage_get_work_completed(P1) -#else -#define mysql_stage_set_work_completed(P1, P2) \ - do {} while (0) - -#define mysql_stage_get_work_completed(P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -#define mysql_stage_inc_work_completed(P1, P2) \ - inline_mysql_stage_inc_work_completed(P1, P2) -#else -#define mysql_stage_inc_work_completed(P1, P2) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -#define mysql_stage_set_work_estimated(P1, P2) \ - inline_mysql_stage_set_work_estimated(P1, P2) - -#define mysql_stage_get_work_estimated(P1) \ - inline_mysql_stage_get_work_estimated(P1) -#else -#define mysql_stage_set_work_estimated(P1, P2) \ - do {} while (0) - -#define mysql_stage_get_work_estimated(P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -static inline void -inline_mysql_stage_set_work_completed(PSI_stage_progress *progress, - ulonglong val) -{ - if (progress != NULL) - progress->m_work_completed= val; -} - -static inline ulonglong -inline_mysql_stage_get_work_completed(PSI_stage_progress *progress) -{ - return progress->m_work_completed; -} -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -static inline void -inline_mysql_stage_inc_work_completed(PSI_stage_progress *progress, - ulonglong val) -{ - if (progress != NULL) - progress->m_work_completed+= val; -} -#endif - -#ifdef HAVE_PSI_STAGE_INTERFACE -static inline void -inline_mysql_stage_set_work_estimated(PSI_stage_progress *progress, - ulonglong val) -{ - if (progress != NULL) - progress->m_work_estimated= val; -} - -static inline ulonglong -inline_mysql_stage_get_work_estimated(PSI_stage_progress *progress) -{ - return progress->m_work_estimated; -} -#endif - -/** @} (end of group Stage_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_statement.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_statement.h deleted file mode 100644 index fab23d2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_statement.h +++ /dev/null @@ -1,243 +0,0 @@ -/* Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_STATEMENT_H -#define MYSQL_STATEMENT_H - -/** - @file mysql/psi/mysql_statement.h - Instrumentation helpers for statements. -*/ - -#include "mysql/psi/psi.h" - -class Diagnostics_area; -typedef const struct charset_info_st CHARSET_INFO; - -#ifndef PSI_STATEMENT_CALL -#define PSI_STATEMENT_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -#ifndef PSI_DIGEST_CALL -#define PSI_DIGEST_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Statement_instrumentation Statement Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -/** - @def mysql_statement_register(P1, P2, P3) - Statement registration. -*/ -#ifdef HAVE_PSI_STATEMENT_INTERFACE -#define mysql_statement_register(P1, P2, P3) \ - inline_mysql_statement_register(P1, P2, P3) -#else -#define mysql_statement_register(P1, P2, P3) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE - #define MYSQL_DIGEST_START(LOCKER) \ - inline_mysql_digest_start(LOCKER) -#else - #define MYSQL_DIGEST_START(LOCKER) \ - NULL -#endif - -#ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE - #define MYSQL_DIGEST_END(LOCKER, DIGEST) \ - inline_mysql_digest_end(LOCKER, DIGEST) -#else - #define MYSQL_DIGEST_END(LOCKER, DIGEST) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE - #define MYSQL_START_STATEMENT(STATE, K, DB, DB_LEN, CS, SPS) \ - inline_mysql_start_statement(STATE, K, DB, DB_LEN, CS, SPS, __FILE__, __LINE__) -#else - #define MYSQL_START_STATEMENT(STATE, K, DB, DB_LEN, CS, SPS) \ - NULL -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE - #define MYSQL_REFINE_STATEMENT(LOCKER, K) \ - inline_mysql_refine_statement(LOCKER, K) -#else - #define MYSQL_REFINE_STATEMENT(LOCKER, K) \ - NULL -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE - #define MYSQL_SET_STATEMENT_TEXT(LOCKER, P1, P2) \ - inline_mysql_set_statement_text(LOCKER, P1, P2) -#else - #define MYSQL_SET_STATEMENT_TEXT(LOCKER, P1, P2) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE - #define MYSQL_SET_STATEMENT_LOCK_TIME(LOCKER, P1) \ - inline_mysql_set_statement_lock_time(LOCKER, P1) -#else - #define MYSQL_SET_STATEMENT_LOCK_TIME(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE - #define MYSQL_SET_STATEMENT_ROWS_SENT(LOCKER, P1) \ - inline_mysql_set_statement_rows_sent(LOCKER, P1) -#else - #define MYSQL_SET_STATEMENT_ROWS_SENT(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE - #define MYSQL_SET_STATEMENT_ROWS_EXAMINED(LOCKER, P1) \ - inline_mysql_set_statement_rows_examined(LOCKER, P1) -#else - #define MYSQL_SET_STATEMENT_ROWS_EXAMINED(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE - #define MYSQL_END_STATEMENT(LOCKER, DA) \ - inline_mysql_end_statement(LOCKER, DA) -#else - #define MYSQL_END_STATEMENT(LOCKER, DA) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_STATEMENT_INTERFACE -static inline void inline_mysql_statement_register( - const char *category, PSI_statement_info *info, int count) -{ - PSI_STATEMENT_CALL(register_statement)(category, info, count); -} - -#ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE -static inline struct PSI_digest_locker * -inline_mysql_digest_start(PSI_statement_locker *locker) -{ - PSI_digest_locker* digest_locker= NULL; - - if (psi_likely(locker != NULL)) - digest_locker= PSI_DIGEST_CALL(digest_start)(locker); - return digest_locker; -} -#endif - -#ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE -static inline void -inline_mysql_digest_end(PSI_digest_locker *locker, const sql_digest_storage *digest) -{ - if (psi_likely(locker != NULL)) - PSI_DIGEST_CALL(digest_end)(locker, digest); -} -#endif - -static inline struct PSI_statement_locker * -inline_mysql_start_statement(PSI_statement_locker_state *state, - PSI_statement_key key, - const char *db, size_t db_len, - CHARSET_INFO *charset, - PSI_sp_share *sp_share, - const char *src_file, uint src_line) -{ - PSI_statement_locker *locker; - locker= PSI_STATEMENT_CALL(get_thread_statement_locker)(state, key, charset, - sp_share); - if (psi_likely(locker != NULL)) - PSI_STATEMENT_CALL(start_statement)(locker, db, (uint)db_len, src_file, src_line); - return locker; -} - -static inline struct PSI_statement_locker * -inline_mysql_refine_statement(PSI_statement_locker *locker, - PSI_statement_key key) -{ - if (psi_likely(locker != NULL)) - { - locker= PSI_STATEMENT_CALL(refine_statement)(locker, key); - } - return locker; -} - -static inline void -inline_mysql_set_statement_text(PSI_statement_locker *locker, - const char *text, uint text_len) -{ - if (psi_likely(locker != NULL)) - { - PSI_STATEMENT_CALL(set_statement_text)(locker, text, text_len); - } -} - -static inline void -inline_mysql_set_statement_lock_time(PSI_statement_locker *locker, - ulonglong count) -{ - if (psi_likely(locker != NULL)) - { - PSI_STATEMENT_CALL(set_statement_lock_time)(locker, count); - } -} - -static inline void -inline_mysql_set_statement_rows_sent(PSI_statement_locker *locker, - ulonglong count) -{ - if (psi_likely(locker != NULL)) - { - PSI_STATEMENT_CALL(set_statement_rows_sent)(locker, count); - } -} - -static inline void -inline_mysql_set_statement_rows_examined(PSI_statement_locker *locker, - ulonglong count) -{ - if (psi_likely(locker != NULL)) - { - PSI_STATEMENT_CALL(set_statement_rows_examined)(locker, count); - } -} - -static inline void -inline_mysql_end_statement(struct PSI_statement_locker *locker, - Diagnostics_area *stmt_da) -{ - PSI_STAGE_CALL(end_stage)(); - if (psi_likely(locker != NULL)) - PSI_STATEMENT_CALL(end_statement)(locker, stmt_da); -} -#endif - -/** @} (end of group Statement_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_table.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_table.h deleted file mode 100644 index a212406..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_table.h +++ /dev/null @@ -1,172 +0,0 @@ -/* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_TABLE_H -#define MYSQL_TABLE_H - -/** - @file mysql/psi/mysql_table.h - Instrumentation helpers for table io. -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_TABLE_CALL -#define PSI_TABLE_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Table_instrumentation Table Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -#ifdef HAVE_PSI_TABLE_INTERFACE -#define MYSQL_UNBIND_TABLE(handler) (handler)->unbind_psi() - -#define PSI_CALL_unbind_table PSI_TABLE_CALL(unbind_table) -#define PSI_CALL_rebind_table PSI_TABLE_CALL(rebind_table) -#define PSI_CALL_open_table PSI_TABLE_CALL(open_table) -#define PSI_CALL_close_table PSI_TABLE_CALL(close_table) -#define PSI_CALL_get_table_share PSI_TABLE_CALL(get_table_share) -#define PSI_CALL_release_table_share PSI_TABLE_CALL(release_table_share) -#define PSI_CALL_drop_table_share PSI_TABLE_CALL(drop_table_share) -#else -#define MYSQL_UNBIND_TABLE(handler) do { } while(0) - -#define PSI_CALL_unbind_table(A1) do { } while(0) -#define PSI_CALL_rebind_table(A1,A2,A3) NULL -#define PSI_CALL_close_table(A1,A2) do { } while(0) -#define PSI_CALL_open_table(A1,A2) NULL -#define PSI_CALL_get_table_share(A1,A2) NULL -#define PSI_CALL_release_table_share(A1) do { } while(0) -#define PSI_CALL_drop_table_share(A1,A2,A3,A4,A5) do { } while(0) -#endif - -/** - @def MYSQL_TABLE_WAIT_VARIABLES - Instrumentation helper for table waits. - This instrumentation declares local variables. - Do not use a ';' after this macro - @param LOCKER the locker - @param STATE the locker state - @sa MYSQL_START_TABLE_IO_WAIT. - @sa MYSQL_END_TABLE_IO_WAIT. - @sa MYSQL_START_TABLE_LOCK_WAIT. - @sa MYSQL_END_TABLE_LOCK_WAIT. -*/ -#ifdef HAVE_PSI_TABLE_INTERFACE - #define MYSQL_TABLE_WAIT_VARIABLES(LOCKER, STATE) \ - struct PSI_table_locker* LOCKER; \ - PSI_table_locker_state STATE; -#else - #define MYSQL_TABLE_WAIT_VARIABLES(LOCKER, STATE) -#endif - -/** - @def MYSQL_START_TABLE_LOCK_WAIT - Instrumentation helper for table lock waits. - This instrumentation marks the start of a wait event. - @param LOCKER the locker - @param STATE the locker state - @param PSI the instrumented table - @param OP the table operation to be performed - @param FLAGS per table operation flags. - @sa MYSQL_END_TABLE_LOCK_WAIT. -*/ -#ifdef HAVE_PSI_TABLE_INTERFACE - #define MYSQL_START_TABLE_LOCK_WAIT(LOCKER, STATE, PSI, OP, FLAGS) \ - LOCKER= inline_mysql_start_table_lock_wait(STATE, PSI, \ - OP, FLAGS, __FILE__, __LINE__) -#else - #define MYSQL_START_TABLE_LOCK_WAIT(LOCKER, STATE, PSI, OP, FLAGS) \ - do {} while (0) -#endif - -/** - @def MYSQL_END_TABLE_LOCK_WAIT - Instrumentation helper for table lock waits. - This instrumentation marks the end of a wait event. - @param LOCKER the locker - @sa MYSQL_START_TABLE_LOCK_WAIT. -*/ -#ifdef HAVE_PSI_TABLE_INTERFACE - #define MYSQL_END_TABLE_LOCK_WAIT(LOCKER) \ - inline_mysql_end_table_lock_wait(LOCKER) -#else - #define MYSQL_END_TABLE_LOCK_WAIT(LOCKER) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TABLE_INTERFACE - #define MYSQL_UNLOCK_TABLE(T) \ - inline_mysql_unlock_table(T) -#else - #define MYSQL_UNLOCK_TABLE(T) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TABLE_INTERFACE -/** - Instrumentation calls for MYSQL_START_TABLE_LOCK_WAIT. - @sa MYSQL_END_TABLE_LOCK_WAIT. -*/ -static inline struct PSI_table_locker * -inline_mysql_start_table_lock_wait(PSI_table_locker_state *state, - struct PSI_table *psi, - enum PSI_table_lock_operation op, - ulong flags, const char *src_file, uint src_line) -{ - if (psi_likely(psi != NULL)) - { - struct PSI_table_locker *locker; - locker= PSI_TABLE_CALL(start_table_lock_wait) - (state, psi, op, flags, src_file, src_line); - return locker; - } - return NULL; -} - -/** - Instrumentation calls for MYSQL_END_TABLE_LOCK_WAIT. - @sa MYSQL_START_TABLE_LOCK_WAIT. -*/ -static inline void -inline_mysql_end_table_lock_wait(struct PSI_table_locker *locker) -{ - if (psi_likely(locker != NULL)) - PSI_TABLE_CALL(end_table_lock_wait)(locker); -} - -static inline void -inline_mysql_unlock_table(struct PSI_table *table) -{ - if (table != NULL) - PSI_TABLE_CALL(unlock_table)(table); -} -#endif - -/** @} (end of group Table_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_thread.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_thread.h deleted file mode 100644 index 47f89f7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_thread.h +++ /dev/null @@ -1,1349 +0,0 @@ -/* Copyright (c) 2008, 2013, Oracle and/or its affiliates. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_THREAD_H -#define MYSQL_THREAD_H - -/** - @file mysql/psi/mysql_thread.h - Instrumentation helpers for mysys threads, mutexes, - read write locks and conditions. - This header file provides the necessary declarations - to use the mysys thread API with the performance schema instrumentation. - In some compilers (SunStudio), 'static inline' functions, when declared - but not used, are not optimized away (because they are unused) by default, - so that including a static inline function from a header file does - create unwanted dependencies, causing unresolved symbols at link time. - Other compilers, like gcc, optimize these dependencies by default. - - Since the instrumented APIs declared here are wrapper on top - of my_pthread / safemutex / etc APIs, - including mysql/psi/mysql_thread.h assumes that - the dependency on my_pthread and safemutex already exists. -*/ -/* - Note: there are several orthogonal dimensions here. - - Dimension 1: Instrumentation - HAVE_PSI_INTERFACE is defined when the instrumentation is compiled in. - This may happen both in debug or production builds. - - Dimension 2: Debug - SAFE_MUTEX is defined when debug is compiled in. - This may happen both with and without instrumentation. - - Dimension 3: Platform - Mutexes are implemented with one of: - - the pthread library - - fast mutexes - - window apis - This is implemented by various macro definitions in my_pthread.h - - This causes complexity with '#ifdef'-ery that can't be avoided. -*/ - -#include "mysql/psi/psi.h" -#ifdef MYSQL_SERVER -#ifndef MYSQL_DYNAMIC_PLUGIN -#include "pfs_thread_provider.h" -#endif -#endif - -#ifndef PSI_MUTEX_CALL -#define PSI_MUTEX_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -#ifndef PSI_RWLOCK_CALL -#define PSI_RWLOCK_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -#ifndef PSI_COND_CALL -#define PSI_COND_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -#ifndef PSI_THREAD_CALL -#define PSI_THREAD_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Thread_instrumentation Thread Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -#ifdef HAVE_PSI_THREAD_INTERFACE -#define PSI_CALL_delete_current_thread PSI_THREAD_CALL(delete_current_thread) -#define PSI_CALL_get_thread PSI_THREAD_CALL(get_thread) -#define PSI_CALL_new_thread PSI_THREAD_CALL(new_thread) -#define PSI_CALL_register_thread PSI_THREAD_CALL(register_thread) -#define PSI_CALL_set_thread PSI_THREAD_CALL(set_thread) -#define PSI_CALL_set_thread_THD PSI_THREAD_CALL(set_thread_THD) -#define PSI_CALL_set_thread_connect_attrs PSI_THREAD_CALL(set_thread_connect_attrs) -#define PSI_CALL_set_thread_db PSI_THREAD_CALL(set_thread_db) -#define PSI_CALL_set_thread_id PSI_THREAD_CALL(set_thread_id) -#define PSI_CALL_set_thread_os_id PSI_THREAD_CALL(set_thread_os_id) -#define PSI_CALL_set_thread_info PSI_THREAD_CALL(set_thread_info) -#define PSI_CALL_set_thread_start_time PSI_THREAD_CALL(set_thread_start_time) -#define PSI_CALL_set_thread_account PSI_THREAD_CALL(set_thread_account) -#define PSI_CALL_spawn_thread PSI_THREAD_CALL(spawn_thread) -#define PSI_CALL_set_connection_type PSI_THREAD_CALL(set_connection_type) -#else -#define PSI_CALL_delete_current_thread() do { } while(0) -#define PSI_CALL_get_thread() NULL -#define PSI_CALL_new_thread(A1,A2,A3) NULL -#define PSI_CALL_register_thread(A1,A2,A3) do { } while(0) -#define PSI_CALL_set_thread(A1) do { } while(0) -#define PSI_CALL_set_thread_THD(A1,A2) do { } while(0) -#define PSI_CALL_set_thread_connect_attrs(A1,A2,A3) 0 -#define PSI_CALL_set_thread_db(A1,A2) do { } while(0) -#define PSI_CALL_set_thread_id(A1,A2) do { } while(0) -#define PSI_CALL_set_thread_os_id(A1) do { } while(0) -#define PSI_CALL_set_thread_info(A1, A2) do { } while(0) -#define PSI_CALL_set_thread_start_time(A1) do { } while(0) -#define PSI_CALL_set_thread_account(A1, A2, A3, A4) do { } while(0) -#define PSI_CALL_spawn_thread(A1, A2, A3, A4, A5) 0 -#define PSI_CALL_set_connection_type(A) do { } while(0) -#endif - - -/** - An instrumented mutex structure. - @sa mysql_mutex_t -*/ -struct st_mysql_mutex -{ - /** The real mutex. */ -#ifdef SAFE_MUTEX - safe_mutex_t m_mutex; -#else - pthread_mutex_t m_mutex; -#endif - /** - The instrumentation hook. - Note that this hook is not conditionally defined, - for binary compatibility of the @c mysql_mutex_t interface. - */ - struct PSI_mutex *m_psi; -}; - -/** - Type of an instrumented mutex. - @c mysql_mutex_t is a drop-in replacement for @c pthread_mutex_t. - @sa mysql_mutex_assert_owner - @sa mysql_mutex_assert_not_owner - @sa mysql_mutex_init - @sa mysql_mutex_lock - @sa mysql_mutex_unlock - @sa mysql_mutex_destroy -*/ -typedef struct st_mysql_mutex mysql_mutex_t; - -/** - An instrumented rwlock structure. - @sa mysql_rwlock_t -*/ -struct st_mysql_rwlock -{ - /** The real rwlock */ - rw_lock_t m_rwlock; - /** - The instrumentation hook. - Note that this hook is not conditionally defined, - for binary compatibility of the @c mysql_rwlock_t interface. - */ - struct PSI_rwlock *m_psi; -}; - -/** - An instrumented prlock structure. - @sa mysql_prlock_t -*/ -struct st_mysql_prlock -{ - /** The real prlock */ - rw_pr_lock_t m_prlock; - /** - The instrumentation hook. - Note that this hook is not conditionally defined, - for binary compatibility of the @c mysql_rwlock_t interface. - */ - struct PSI_rwlock *m_psi; -}; - -/** - Type of an instrumented rwlock. - @c mysql_rwlock_t is a drop-in replacement for @c pthread_rwlock_t. - @sa mysql_rwlock_init - @sa mysql_rwlock_rdlock - @sa mysql_rwlock_tryrdlock - @sa mysql_rwlock_wrlock - @sa mysql_rwlock_trywrlock - @sa mysql_rwlock_unlock - @sa mysql_rwlock_destroy -*/ -typedef struct st_mysql_rwlock mysql_rwlock_t; - -/** - Type of an instrumented prlock. - A prlock is a read write lock that 'prefers readers' (pr). - @c mysql_prlock_t is a drop-in replacement for @c rw_pr_lock_t. - @sa mysql_prlock_init - @sa mysql_prlock_rdlock - @sa mysql_prlock_wrlock - @sa mysql_prlock_unlock - @sa mysql_prlock_destroy -*/ -typedef struct st_mysql_prlock mysql_prlock_t; - -/** - An instrumented cond structure. - @sa mysql_cond_t -*/ -struct st_mysql_cond -{ - /** The real condition */ - pthread_cond_t m_cond; - /** - The instrumentation hook. - Note that this hook is not conditionally defined, - for binary compatibility of the @c mysql_cond_t interface. - */ - struct PSI_cond *m_psi; -}; - -/** - Type of an instrumented condition. - @c mysql_cond_t is a drop-in replacement for @c pthread_cond_t. - @sa mysql_cond_init - @sa mysql_cond_wait - @sa mysql_cond_timedwait - @sa mysql_cond_signal - @sa mysql_cond_broadcast - @sa mysql_cond_destroy -*/ -typedef struct st_mysql_cond mysql_cond_t; - -/* - Consider the following code: - static inline void foo() { bar(); } - when foo() is never called. - - With gcc, foo() is a local static function, so the dependencies - are optimized away at compile time, and there is no dependency on bar(). - With other compilers (HP, Sun Studio), the function foo() implementation - is compiled, and bar() needs to be present to link. - - Due to the existing header dependencies in MySQL code, this header file - is sometime used when it is not needed, which in turn cause link failures - on some platforms. - The proper fix would be to cut these extra dependencies in the calling code. - DISABLE_MYSQL_THREAD_H is a work around to limit dependencies. - DISABLE_MYSQL_PRLOCK_H is similar, and is used to disable specifically - the prlock wrappers. -*/ -#ifndef DISABLE_MYSQL_THREAD_H - -#define mysql_mutex_is_owner(M) safe_mutex_is_owner(&(M)->m_mutex) -/** - @def mysql_mutex_assert_owner(M) - Wrapper, to use safe_mutex_assert_owner with instrumented mutexes. - @c mysql_mutex_assert_owner is a drop-in replacement - for @c safe_mutex_assert_owner. -*/ -#define mysql_mutex_assert_owner(M) \ - safe_mutex_assert_owner(&(M)->m_mutex) - -/** - @def mysql_mutex_assert_not_owner(M) - Wrapper, to use safe_mutex_assert_not_owner with instrumented mutexes. - @c mysql_mutex_assert_not_owner is a drop-in replacement - for @c safe_mutex_assert_not_owner. -*/ -#define mysql_mutex_assert_not_owner(M) \ - safe_mutex_assert_not_owner(&(M)->m_mutex) - -#define mysql_mutex_setflags(M, F) \ - safe_mutex_setflags(&(M)->m_mutex, (F)) - -/** - @def mysql_prlock_assert_write_owner(M) - Drop-in replacement - for @c rw_pr_lock_assert_write_owner. -*/ -#define mysql_prlock_assert_write_owner(M) \ - rw_pr_lock_assert_write_owner(&(M)->m_prlock) - -/** - @def mysql_prlock_assert_not_write_owner(M) - Drop-in replacement - for @c rw_pr_lock_assert_not_write_owner. -*/ -#define mysql_prlock_assert_not_write_owner(M) \ - rw_pr_lock_assert_not_write_owner(&(M)->m_prlock) - -/** - @def mysql_mutex_register(P1, P2, P3) - Mutex registration. -*/ -#define mysql_mutex_register(P1, P2, P3) \ - inline_mysql_mutex_register(P1, P2, P3) - -/** - @def mysql_mutex_init(K, M, A) - Instrumented mutex_init. - @c mysql_mutex_init is a replacement for @c pthread_mutex_init. - @param K The PSI_mutex_key for this instrumented mutex - @param M The mutex to initialize - @param A Mutex attributes -*/ - -#ifdef HAVE_PSI_MUTEX_INTERFACE - #ifdef SAFE_MUTEX - #define mysql_mutex_init(K, M, A) \ - inline_mysql_mutex_init(K, M, A, #M, __FILE__, __LINE__) - #else - #define mysql_mutex_init(K, M, A) \ - inline_mysql_mutex_init(K, M, A) - #endif -#else - #ifdef SAFE_MUTEX - #define mysql_mutex_init(K, M, A) \ - inline_mysql_mutex_init(M, A, #M, __FILE__, __LINE__) - #else - #define mysql_mutex_init(K, M, A) \ - inline_mysql_mutex_init(M, A) - #endif -#endif - -/** - @def mysql_mutex_destroy(M) - Instrumented mutex_destroy. - @c mysql_mutex_destroy is a drop-in replacement - for @c pthread_mutex_destroy. -*/ -#ifdef SAFE_MUTEX - #define mysql_mutex_destroy(M) \ - inline_mysql_mutex_destroy(M, __FILE__, __LINE__) -#else - #define mysql_mutex_destroy(M) \ - inline_mysql_mutex_destroy(M) -#endif - -/** - @def mysql_mutex_lock(M) - Instrumented mutex_lock. - @c mysql_mutex_lock is a drop-in replacement for @c pthread_mutex_lock. - @param M The mutex to lock -*/ - -#if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) - #define mysql_mutex_lock(M) \ - inline_mysql_mutex_lock(M, __FILE__, __LINE__) -#else - #define mysql_mutex_lock(M) \ - inline_mysql_mutex_lock(M) -#endif - -/** - @def mysql_mutex_trylock(M) - Instrumented mutex_lock. - @c mysql_mutex_trylock is a drop-in replacement - for @c pthread_mutex_trylock. -*/ - -#if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) - #define mysql_mutex_trylock(M) \ - inline_mysql_mutex_trylock(M, __FILE__, __LINE__) -#else - #define mysql_mutex_trylock(M) \ - inline_mysql_mutex_trylock(M) -#endif - -/** - @def mysql_mutex_unlock(M) - Instrumented mutex_unlock. - @c mysql_mutex_unlock is a drop-in replacement for @c pthread_mutex_unlock. -*/ -#ifdef SAFE_MUTEX - #define mysql_mutex_unlock(M) \ - inline_mysql_mutex_unlock(M, __FILE__, __LINE__) -#else - #define mysql_mutex_unlock(M) \ - inline_mysql_mutex_unlock(M) -#endif - -/** - @def mysql_rwlock_register(P1, P2, P3) - Rwlock registration. -*/ -#define mysql_rwlock_register(P1, P2, P3) \ - inline_mysql_rwlock_register(P1, P2, P3) - -/** - @def mysql_rwlock_init(K, RW) - Instrumented rwlock_init. - @c mysql_rwlock_init is a replacement for @c pthread_rwlock_init. - Note that pthread_rwlockattr_t is not supported in MySQL. - @param K The PSI_rwlock_key for this instrumented rwlock - @param RW The rwlock to initialize -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_rwlock_init(K, RW) inline_mysql_rwlock_init(K, RW) -#else - #define mysql_rwlock_init(K, RW) inline_mysql_rwlock_init(RW) -#endif - -/** - @def mysql_prlock_init(K, RW) - Instrumented rw_pr_init. - @c mysql_prlock_init is a replacement for @c rw_pr_init. - @param K The PSI_rwlock_key for this instrumented prlock - @param RW The prlock to initialize -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_prlock_init(K, RW) inline_mysql_prlock_init(K, RW) -#else - #define mysql_prlock_init(K, RW) inline_mysql_prlock_init(RW) -#endif - -/** - @def mysql_rwlock_destroy(RW) - Instrumented rwlock_destroy. - @c mysql_rwlock_destroy is a drop-in replacement - for @c pthread_rwlock_destroy. -*/ -#define mysql_rwlock_destroy(RW) inline_mysql_rwlock_destroy(RW) - -/** - @def mysql_prlock_destroy(RW) - Instrumented rw_pr_destroy. - @c mysql_prlock_destroy is a drop-in replacement - for @c rw_pr_destroy. -*/ -#define mysql_prlock_destroy(RW) inline_mysql_prlock_destroy(RW) - -/** - @def mysql_rwlock_rdlock(RW) - Instrumented rwlock_rdlock. - @c mysql_rwlock_rdlock is a drop-in replacement - for @c pthread_rwlock_rdlock. -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_rwlock_rdlock(RW) \ - inline_mysql_rwlock_rdlock(RW, __FILE__, __LINE__) -#else - #define mysql_rwlock_rdlock(RW) \ - inline_mysql_rwlock_rdlock(RW) -#endif - -/** - @def mysql_prlock_rdlock(RW) - Instrumented rw_pr_rdlock. - @c mysql_prlock_rdlock is a drop-in replacement - for @c rw_pr_rdlock. -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_prlock_rdlock(RW) \ - inline_mysql_prlock_rdlock(RW, __FILE__, __LINE__) -#else - #define mysql_prlock_rdlock(RW) \ - inline_mysql_prlock_rdlock(RW) -#endif - -/** - @def mysql_rwlock_wrlock(RW) - Instrumented rwlock_wrlock. - @c mysql_rwlock_wrlock is a drop-in replacement - for @c pthread_rwlock_wrlock. -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_rwlock_wrlock(RW) \ - inline_mysql_rwlock_wrlock(RW, __FILE__, __LINE__) -#else - #define mysql_rwlock_wrlock(RW) \ - inline_mysql_rwlock_wrlock(RW) -#endif - -/** - @def mysql_prlock_wrlock(RW) - Instrumented rw_pr_wrlock. - @c mysql_prlock_wrlock is a drop-in replacement - for @c rw_pr_wrlock. -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_prlock_wrlock(RW) \ - inline_mysql_prlock_wrlock(RW, __FILE__, __LINE__) -#else - #define mysql_prlock_wrlock(RW) \ - inline_mysql_prlock_wrlock(RW) -#endif - -/** - @def mysql_rwlock_tryrdlock(RW) - Instrumented rwlock_tryrdlock. - @c mysql_rwlock_tryrdlock is a drop-in replacement - for @c pthread_rwlock_tryrdlock. -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_rwlock_tryrdlock(RW) \ - inline_mysql_rwlock_tryrdlock(RW, __FILE__, __LINE__) -#else - #define mysql_rwlock_tryrdlock(RW) \ - inline_mysql_rwlock_tryrdlock(RW) -#endif - -/** - @def mysql_rwlock_trywrlock(RW) - Instrumented rwlock_trywrlock. - @c mysql_rwlock_trywrlock is a drop-in replacement - for @c pthread_rwlock_trywrlock. -*/ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - #define mysql_rwlock_trywrlock(RW) \ - inline_mysql_rwlock_trywrlock(RW, __FILE__, __LINE__) -#else - #define mysql_rwlock_trywrlock(RW) \ - inline_mysql_rwlock_trywrlock(RW) -#endif - -/** - @def mysql_rwlock_unlock(RW) - Instrumented rwlock_unlock. - @c mysql_rwlock_unlock is a drop-in replacement - for @c pthread_rwlock_unlock. -*/ -#define mysql_rwlock_unlock(RW) inline_mysql_rwlock_unlock(RW) - -/** - @def mysql_prlock_unlock(RW) - Instrumented rw_pr_unlock. - @c mysql_prlock_unlock is a drop-in replacement - for @c rw_pr_unlock. -*/ -#define mysql_prlock_unlock(RW) inline_mysql_prlock_unlock(RW) - -/** - @def mysql_cond_register(P1, P2, P3) - Cond registration. -*/ -#define mysql_cond_register(P1, P2, P3) \ - inline_mysql_cond_register(P1, P2, P3) - -/** - @def mysql_cond_init(K, C, A) - Instrumented cond_init. - @c mysql_cond_init is a replacement for @c pthread_cond_init. - @param C The cond to initialize - @param K The PSI_cond_key for this instrumented cond - @param A Condition attributes -*/ -#ifdef HAVE_PSI_COND_INTERFACE - #define mysql_cond_init(K, C, A) inline_mysql_cond_init(K, C, A) -#else - #define mysql_cond_init(K, C, A) inline_mysql_cond_init(C, A) -#endif - -/** - @def mysql_cond_destroy(C) - Instrumented cond_destroy. - @c mysql_cond_destroy is a drop-in replacement for @c pthread_cond_destroy. -*/ -#define mysql_cond_destroy(C) inline_mysql_cond_destroy(C) - -/** - @def mysql_cond_wait(C) - Instrumented cond_wait. - @c mysql_cond_wait is a drop-in replacement for @c pthread_cond_wait. -*/ -#if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) - #define mysql_cond_wait(C, M) \ - inline_mysql_cond_wait(C, M, __FILE__, __LINE__) -#else - #define mysql_cond_wait(C, M) \ - inline_mysql_cond_wait(C, M) -#endif - -/** - @def mysql_cond_timedwait(C, M, W) - Instrumented cond_timedwait. - @c mysql_cond_timedwait is a drop-in replacement - for @c pthread_cond_timedwait. -*/ -#if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) - #define mysql_cond_timedwait(C, M, W) \ - inline_mysql_cond_timedwait(C, M, W, __FILE__, __LINE__) -#else - #define mysql_cond_timedwait(C, M, W) \ - inline_mysql_cond_timedwait(C, M, W) -#endif - -/** - @def mysql_cond_signal(C) - Instrumented cond_signal. - @c mysql_cond_signal is a drop-in replacement for @c pthread_cond_signal. -*/ -#define mysql_cond_signal(C) inline_mysql_cond_signal(C) - -/** - @def mysql_cond_broadcast(C) - Instrumented cond_broadcast. - @c mysql_cond_broadcast is a drop-in replacement - for @c pthread_cond_broadcast. -*/ -#define mysql_cond_broadcast(C) inline_mysql_cond_broadcast(C) - -/** - @def mysql_thread_register(P1, P2, P3) - Thread registration. -*/ -#define mysql_thread_register(P1, P2, P3) \ - inline_mysql_thread_register(P1, P2, P3) - -/** - @def mysql_thread_create(K, P1, P2, P3, P4) - Instrumented pthread_create. - This function creates both the thread instrumentation and a thread. - @c mysql_thread_create is a replacement for @c pthread_create. - The parameter P4 (or, if it is NULL, P1) will be used as the - instrumented thread "indentity". - Providing a P1 / P4 parameter with a different value for each call - will on average improve performances, since this thread identity value - is used internally to randomize access to data and prevent contention. - This is optional, and the improvement is not guaranteed, only statistical. - @param K The PSI_thread_key for this instrumented thread - @param P1 pthread_create parameter 1 - @param P2 pthread_create parameter 2 - @param P3 pthread_create parameter 3 - @param P4 pthread_create parameter 4 -*/ -#ifdef HAVE_PSI_THREAD_INTERFACE - #define mysql_thread_create(K, P1, P2, P3, P4) \ - inline_mysql_thread_create(K, P1, P2, P3, P4) -#else - #define mysql_thread_create(K, P1, P2, P3, P4) \ - pthread_create(P1, P2, P3, P4) -#endif - -/** - @def mysql_thread_set_psi_id(I) - Set the thread identifier for the instrumentation. - @param I The thread identifier -*/ -#ifdef HAVE_PSI_THREAD_INTERFACE - #define mysql_thread_set_psi_id(I) inline_mysql_thread_set_psi_id(I) -#else - #define mysql_thread_set_psi_id(I) do {} while (0) -#endif - -/** - @def mysql_thread_set_psi_THD(T) - Set the thread sql session for the instrumentation. - @param I The thread identifier -*/ -#ifdef HAVE_PSI_THREAD_INTERFACE - #define mysql_thread_set_psi_THD(T) inline_mysql_thread_set_psi_THD(T) -#else - #define mysql_thread_set_psi_THD(T) do {} while (0) -#endif - -static inline void inline_mysql_mutex_register( -#ifdef HAVE_PSI_MUTEX_INTERFACE - const char *category, - PSI_mutex_info *info, - int count -#else - const char *category __attribute__ ((unused)), - void *info __attribute__ ((unused)), - int count __attribute__ ((unused)) -#endif -) -{ -#ifdef HAVE_PSI_MUTEX_INTERFACE - PSI_MUTEX_CALL(register_mutex)(category, info, count); -#endif -} - -static inline int inline_mysql_mutex_init( -#ifdef HAVE_PSI_MUTEX_INTERFACE - PSI_mutex_key key, -#endif - mysql_mutex_t *that, - const pthread_mutexattr_t *attr -#ifdef SAFE_MUTEX - , const char *src_name, const char *src_file, uint src_line -#endif - ) -{ -#ifdef HAVE_PSI_MUTEX_INTERFACE - that->m_psi= PSI_MUTEX_CALL(init_mutex)(key, &that->m_mutex); -#else - that->m_psi= NULL; -#endif -#ifdef SAFE_MUTEX - return safe_mutex_init(&that->m_mutex, attr, src_name, src_file, src_line); -#else - return pthread_mutex_init(&that->m_mutex, attr); -#endif -} - -static inline int inline_mysql_mutex_destroy( - mysql_mutex_t *that -#ifdef SAFE_MUTEX - , const char *src_file, uint src_line -#endif - ) -{ -#ifdef HAVE_PSI_MUTEX_INTERFACE - if (that->m_psi != NULL) - { - PSI_MUTEX_CALL(destroy_mutex)(that->m_psi); - that->m_psi= NULL; - } -#endif -#ifdef SAFE_MUTEX - return safe_mutex_destroy(&that->m_mutex, src_file, src_line); -#else - return pthread_mutex_destroy(&that->m_mutex); -#endif -} - -static inline int inline_mysql_mutex_lock( - mysql_mutex_t *that -#if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_MUTEX_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_mutex_locker *locker; - PSI_mutex_locker_state state; - locker= PSI_MUTEX_CALL(start_mutex_wait)(&state, that->m_psi, - PSI_MUTEX_LOCK, src_file, src_line); - - /* Instrumented code */ -#ifdef SAFE_MUTEX - result= safe_mutex_lock(&that->m_mutex, FALSE, src_file, src_line); -#else - result= pthread_mutex_lock(&that->m_mutex); -#endif - - /* Instrumentation end */ - if (locker != NULL) - PSI_MUTEX_CALL(end_mutex_wait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ -#ifdef SAFE_MUTEX - result= safe_mutex_lock(&that->m_mutex, FALSE, src_file, src_line); -#else - result= pthread_mutex_lock(&that->m_mutex); -#endif - - return result; -} - -static inline int inline_mysql_mutex_trylock( - mysql_mutex_t *that -#if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_MUTEX_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_mutex_locker *locker; - PSI_mutex_locker_state state; - locker= PSI_MUTEX_CALL(start_mutex_wait)(&state, that->m_psi, - PSI_MUTEX_TRYLOCK, src_file, src_line); - - /* Instrumented code */ -#ifdef SAFE_MUTEX - result= safe_mutex_lock(&that->m_mutex, TRUE, src_file, src_line); -#else - result= pthread_mutex_trylock(&that->m_mutex); -#endif - - /* Instrumentation end */ - if (locker != NULL) - PSI_MUTEX_CALL(end_mutex_wait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ -#ifdef SAFE_MUTEX - result= safe_mutex_lock(&that->m_mutex, TRUE, src_file, src_line); -#else - result= pthread_mutex_trylock(&that->m_mutex); -#endif - - return result; -} - -static inline int inline_mysql_mutex_unlock( - mysql_mutex_t *that -#ifdef SAFE_MUTEX - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_MUTEX_INTERFACE - if (psi_likely(that->m_psi != NULL)) - PSI_MUTEX_CALL(unlock_mutex)(that->m_psi); -#endif - -#ifdef SAFE_MUTEX - result= safe_mutex_unlock(&that->m_mutex, src_file, src_line); -#else - result= pthread_mutex_unlock(&that->m_mutex); -#endif - - return result; -} - -static inline void inline_mysql_rwlock_register( -#ifdef HAVE_PSI_RWLOCK_INTERFACE - const char *category, - PSI_rwlock_info *info, - int count -#else - const char *category __attribute__ ((unused)), - void *info __attribute__ ((unused)), - int count __attribute__ ((unused)) -#endif -) -{ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - PSI_RWLOCK_CALL(register_rwlock)(category, info, count); -#endif -} - -static inline int inline_mysql_rwlock_init( -#ifdef HAVE_PSI_RWLOCK_INTERFACE - PSI_rwlock_key key, -#endif - mysql_rwlock_t *that) -{ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - that->m_psi= PSI_RWLOCK_CALL(init_rwlock)(key, &that->m_rwlock); -#else - that->m_psi= NULL; -#endif - /* - pthread_rwlockattr_t is not used in MySQL. - */ - return my_rwlock_init(&that->m_rwlock, NULL); -} - -#ifndef DISABLE_MYSQL_PRLOCK_H -static inline int inline_mysql_prlock_init( -#ifdef HAVE_PSI_RWLOCK_INTERFACE - PSI_rwlock_key key, -#endif - mysql_prlock_t *that) -{ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - that->m_psi= PSI_RWLOCK_CALL(init_rwlock)(key, &that->m_prlock); -#else - that->m_psi= NULL; -#endif - return rw_pr_init(&that->m_prlock); -} -#endif - -static inline int inline_mysql_rwlock_destroy( - mysql_rwlock_t *that) -{ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - PSI_RWLOCK_CALL(destroy_rwlock)(that->m_psi); - that->m_psi= NULL; - } -#endif - return rwlock_destroy(&that->m_rwlock); -} - -#ifndef DISABLE_MYSQL_PRLOCK_H -static inline int inline_mysql_prlock_destroy( - mysql_prlock_t *that) -{ -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - PSI_RWLOCK_CALL(destroy_rwlock)(that->m_psi); - that->m_psi= NULL; - } -#endif - return rw_pr_destroy(&that->m_prlock); -} -#endif - -static inline int inline_mysql_rwlock_rdlock( - mysql_rwlock_t *that -#ifdef HAVE_PSI_RWLOCK_INTERFACE - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_rwlock_locker *locker; - PSI_rwlock_locker_state state; - locker= PSI_RWLOCK_CALL(start_rwlock_rdwait)(&state, that->m_psi, - PSI_RWLOCK_READLOCK, src_file, src_line); - - /* Instrumented code */ - result= rw_rdlock(&that->m_rwlock); - - /* Instrumentation end */ - if (locker != NULL) - PSI_RWLOCK_CALL(end_rwlock_rdwait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= rw_rdlock(&that->m_rwlock); - - return result; -} - -#ifndef DISABLE_MYSQL_PRLOCK_H -static inline int inline_mysql_prlock_rdlock( - mysql_prlock_t *that -#ifdef HAVE_PSI_RWLOCK_INTERFACE - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_rwlock_locker *locker; - PSI_rwlock_locker_state state; - locker= PSI_RWLOCK_CALL(start_rwlock_rdwait)(&state, that->m_psi, - PSI_RWLOCK_READLOCK, src_file, src_line); - - /* Instrumented code */ - result= rw_pr_rdlock(&that->m_prlock); - - /* Instrumentation end */ - if (locker != NULL) - PSI_RWLOCK_CALL(end_rwlock_rdwait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= rw_pr_rdlock(&that->m_prlock); - - return result; -} -#endif - -static inline int inline_mysql_rwlock_wrlock( - mysql_rwlock_t *that -#ifdef HAVE_PSI_RWLOCK_INTERFACE - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_rwlock_locker *locker; - PSI_rwlock_locker_state state; - locker= PSI_RWLOCK_CALL(start_rwlock_wrwait)(&state, that->m_psi, - PSI_RWLOCK_WRITELOCK, src_file, src_line); - - /* Instrumented code */ - result= rw_wrlock(&that->m_rwlock); - - /* Instrumentation end */ - if (locker != NULL) - PSI_RWLOCK_CALL(end_rwlock_wrwait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= rw_wrlock(&that->m_rwlock); - - return result; -} - -#ifndef DISABLE_MYSQL_PRLOCK_H -static inline int inline_mysql_prlock_wrlock( - mysql_prlock_t *that -#ifdef HAVE_PSI_RWLOCK_INTERFACE - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_rwlock_locker *locker; - PSI_rwlock_locker_state state; - locker= PSI_RWLOCK_CALL(start_rwlock_wrwait)(&state, that->m_psi, - PSI_RWLOCK_WRITELOCK, src_file, src_line); - - /* Instrumented code */ - result= rw_pr_wrlock(&that->m_prlock); - - /* Instrumentation end */ - if (locker != NULL) - PSI_RWLOCK_CALL(end_rwlock_wrwait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= rw_pr_wrlock(&that->m_prlock); - - return result; -} -#endif - -static inline int inline_mysql_rwlock_tryrdlock( - mysql_rwlock_t *that -#ifdef HAVE_PSI_RWLOCK_INTERFACE - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_rwlock_locker *locker; - PSI_rwlock_locker_state state; - locker= PSI_RWLOCK_CALL(start_rwlock_rdwait)(&state, that->m_psi, - PSI_RWLOCK_TRYREADLOCK, src_file, src_line); - - /* Instrumented code */ - result= rw_tryrdlock(&that->m_rwlock); - - /* Instrumentation end */ - if (locker != NULL) - PSI_RWLOCK_CALL(end_rwlock_rdwait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= rw_tryrdlock(&that->m_rwlock); - - return result; -} - -static inline int inline_mysql_rwlock_trywrlock( - mysql_rwlock_t *that -#ifdef HAVE_PSI_RWLOCK_INTERFACE - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_rwlock_locker *locker; - PSI_rwlock_locker_state state; - locker= PSI_RWLOCK_CALL(start_rwlock_wrwait)(&state, that->m_psi, - PSI_RWLOCK_TRYWRITELOCK, src_file, src_line); - - /* Instrumented code */ - result= rw_trywrlock(&that->m_rwlock); - - /* Instrumentation end */ - if (locker != NULL) - PSI_RWLOCK_CALL(end_rwlock_wrwait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= rw_trywrlock(&that->m_rwlock); - - return result; -} - -static inline int inline_mysql_rwlock_unlock( - mysql_rwlock_t *that) -{ - int result; -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - PSI_RWLOCK_CALL(unlock_rwlock)(that->m_psi); -#endif - result= rw_unlock(&that->m_rwlock); - return result; -} - -#ifndef DISABLE_MYSQL_PRLOCK_H -static inline int inline_mysql_prlock_unlock( - mysql_prlock_t *that) -{ - int result; -#ifdef HAVE_PSI_RWLOCK_INTERFACE - if (psi_likely(that->m_psi != NULL)) - PSI_RWLOCK_CALL(unlock_rwlock)(that->m_psi); -#endif - result= rw_pr_unlock(&that->m_prlock); - return result; -} -#endif - -static inline void inline_mysql_cond_register( -#ifdef HAVE_PSI_COND_INTERFACE - const char *category, - PSI_cond_info *info, - int count -#else - const char *category __attribute__ ((unused)), - void *info __attribute__ ((unused)), - int count __attribute__ ((unused)) -#endif -) -{ -#ifdef HAVE_PSI_COND_INTERFACE - PSI_COND_CALL(register_cond)(category, info, count); -#endif -} - -static inline int inline_mysql_cond_init( -#ifdef HAVE_PSI_COND_INTERFACE - PSI_cond_key key, -#endif - mysql_cond_t *that, - const pthread_condattr_t *attr) -{ -#ifdef HAVE_PSI_COND_INTERFACE - that->m_psi= PSI_COND_CALL(init_cond)(key, &that->m_cond); -#else - that->m_psi= NULL; -#endif - return pthread_cond_init(&that->m_cond, attr); -} - -static inline int inline_mysql_cond_destroy( - mysql_cond_t *that) -{ -#ifdef HAVE_PSI_COND_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - PSI_COND_CALL(destroy_cond)(that->m_psi); - that->m_psi= NULL; - } -#endif - return pthread_cond_destroy(&that->m_cond); -} - -static inline int inline_mysql_cond_wait( - mysql_cond_t *that, - mysql_mutex_t *mutex -#if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_COND_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_cond_locker *locker; - PSI_cond_locker_state state; - locker= PSI_COND_CALL(start_cond_wait)(&state, that->m_psi, mutex->m_psi, - PSI_COND_WAIT, src_file, src_line); - - /* Instrumented code */ - result= my_cond_wait(&that->m_cond, &mutex->m_mutex); - - /* Instrumentation end */ - if (locker != NULL) - PSI_COND_CALL(end_cond_wait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= my_cond_wait(&that->m_cond, &mutex->m_mutex); - - return result; -} - -static inline int inline_mysql_cond_timedwait( - mysql_cond_t *that, - mysql_mutex_t *mutex, - const struct timespec *abstime -#if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) - , const char *src_file, uint src_line -#endif - ) -{ - int result; - -#ifdef HAVE_PSI_COND_INTERFACE - if (psi_likely(that->m_psi != NULL)) - { - /* Instrumentation start */ - PSI_cond_locker *locker; - PSI_cond_locker_state state; - locker= PSI_COND_CALL(start_cond_wait)(&state, that->m_psi, mutex->m_psi, - PSI_COND_TIMEDWAIT, src_file, src_line); - - /* Instrumented code */ - result= my_cond_timedwait(&that->m_cond, &mutex->m_mutex, abstime); - - /* Instrumentation end */ - if (psi_likely(locker != NULL)) - PSI_COND_CALL(end_cond_wait)(locker, result); - - return result; - } -#endif - - /* Non instrumented code */ - result= my_cond_timedwait(&that->m_cond, &mutex->m_mutex, abstime); - - return result; -} - -static inline int inline_mysql_cond_signal( - mysql_cond_t *that) -{ - int result; -#ifdef HAVE_PSI_COND_INTERFACE - if (psi_likely(that->m_psi != NULL)) - PSI_COND_CALL(signal_cond)(that->m_psi); -#endif - result= pthread_cond_signal(&that->m_cond); - return result; -} - -static inline int inline_mysql_cond_broadcast( - mysql_cond_t *that) -{ - int result; -#ifdef HAVE_PSI_COND_INTERFACE - if (psi_likely(that->m_psi != NULL)) - PSI_COND_CALL(broadcast_cond)(that->m_psi); -#endif - result= pthread_cond_broadcast(&that->m_cond); - return result; -} - -static inline void inline_mysql_thread_register( -#ifdef HAVE_PSI_THREAD_INTERFACE - const char *category, - PSI_thread_info *info, - int count -#else - const char *category __attribute__ ((unused)), - void *info __attribute__ ((unused)), - int count __attribute__ ((unused)) -#endif -) -{ -#ifdef HAVE_PSI_THREAD_INTERFACE - PSI_THREAD_CALL(register_thread)(category, info, count); -#endif -} - -#ifdef HAVE_PSI_THREAD_INTERFACE -static inline int inline_mysql_thread_create( - PSI_thread_key key, - pthread_t *thread, const pthread_attr_t *attr, - void *(*start_routine)(void*), void *arg) -{ - int result; - result= PSI_THREAD_CALL(spawn_thread)(key, thread, attr, start_routine, arg); - return result; -} - -static inline void inline_mysql_thread_set_psi_id(my_thread_id id) -{ - struct PSI_thread *psi= PSI_THREAD_CALL(get_thread)(); - PSI_THREAD_CALL(set_thread_id)(psi, id); -} - -#ifdef __cplusplus -class THD; -static inline void inline_mysql_thread_set_psi_THD(THD *thd) -{ - struct PSI_thread *psi= PSI_THREAD_CALL(get_thread)(); - PSI_THREAD_CALL(set_thread_THD)(psi, thd); -} -#endif /* __cplusplus */ - -#endif - -#endif /* DISABLE_MYSQL_THREAD_H */ - -/** @} (end of group Thread_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_transaction.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_transaction.h deleted file mode 100644 index 6de794d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/mysql_transaction.h +++ /dev/null @@ -1,220 +0,0 @@ -/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef MYSQL_TRANSACTION_H -#define MYSQL_TRANSACTION_H - -/** - @file mysql/psi/mysql_transaction.h - Instrumentation helpers for transactions. -*/ - -#include "mysql/psi/psi.h" - -#ifndef PSI_TRANSACTION_CALL -#define PSI_TRANSACTION_CALL(M) PSI_DYNAMIC_CALL(M) -#endif - -/** - @defgroup Transaction_instrumentation Transaction Instrumentation - @ingroup Instrumentation_interface - @{ -*/ - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_START_TRANSACTION(STATE, XID, TRXID, ISO, RO, AC) \ - inline_mysql_start_transaction(STATE, XID, TRXID, ISO, RO, AC, __FILE__, __LINE__) -#else - #define MYSQL_START_TRANSACTION(STATE, XID, TRXID, ISO, RO, AC) \ - 0 -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_SET_TRANSACTION_GTID(LOCKER, P1, P2) \ - inline_mysql_set_transaction_gtid(LOCKER, P1, P2) -#else - #define MYSQL_SET_TRANSACTION_GTID(LOCKER, P1, P2) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_SET_TRANSACTION_XID(LOCKER, P1, P2) \ - inline_mysql_set_transaction_xid(LOCKER, P1, P2) -#else - #define MYSQL_SET_TRANSACTION_XID(LOCKER, P1, P2) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_SET_TRANSACTION_XA_STATE(LOCKER, P1) \ - inline_mysql_set_transaction_xa_state(LOCKER, P1) -#else - #define MYSQL_SET_TRANSACTION_XA_STATE(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_SET_TRANSACTION_TRXID(LOCKER, P1) \ - inline_mysql_set_transaction_trxid(LOCKER, P1) -#else - #define MYSQL_SET_TRANSACTION_TRXID(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_INC_TRANSACTION_SAVEPOINTS(LOCKER, P1) \ - inline_mysql_inc_transaction_savepoints(LOCKER, P1) -#else - #define MYSQL_INC_TRANSACTION_SAVEPOINTS(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_INC_TRANSACTION_ROLLBACK_TO_SAVEPOINT(LOCKER, P1) \ - inline_mysql_inc_transaction_rollback_to_savepoint(LOCKER, P1) -#else - #define MYSQL_INC_TRANSACTION_ROLLBACK_TO_SAVEPOINT(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_INC_TRANSACTION_RELEASE_SAVEPOINT(LOCKER, P1) \ - inline_mysql_inc_transaction_release_savepoint(LOCKER, P1) -#else - #define MYSQL_INC_TRANSACTION_RELEASE_SAVEPOINT(LOCKER, P1) \ - do {} while (0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_ROLLBACK_TRANSACTION(LOCKER) \ - inline_mysql_rollback_transaction(LOCKER) -#else - #define MYSQL_ROLLBACK_TRANSACTION(LOCKER) \ - do { } while(0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - #define MYSQL_COMMIT_TRANSACTION(LOCKER) \ - inline_mysql_commit_transaction(LOCKER) -#else - #define MYSQL_COMMIT_TRANSACTION(LOCKER) \ - do { } while(0) -#endif - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE -static inline struct PSI_transaction_locker * -inline_mysql_start_transaction(PSI_transaction_locker_state *state, - const void *xid, - ulonglong trxid, - int isolation_level, - my_bool read_only, - my_bool autocommit, - const char *src_file, int src_line) -{ - PSI_transaction_locker *locker; - locker= PSI_TRANSACTION_CALL(get_thread_transaction_locker)(state, - xid, trxid, - isolation_level, - read_only, - autocommit); - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(start_transaction)(locker, src_file, src_line); - return locker; -} - -static inline void -inline_mysql_set_transaction_gtid(PSI_transaction_locker *locker, - const void *sid, - const void *gtid_spec) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(set_transaction_gtid)(locker, sid, gtid_spec); -} - -static inline void -inline_mysql_set_transaction_xid(PSI_transaction_locker *locker, - const void *xid, - int xa_state) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(set_transaction_xid)(locker, xid, xa_state); -} - -static inline void -inline_mysql_set_transaction_xa_state(PSI_transaction_locker *locker, - int xa_state) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(set_transaction_xa_state)(locker, xa_state); -} - -static inline void -inline_mysql_set_transaction_trxid(PSI_transaction_locker *locker, - const ulonglong *trxid) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(set_transaction_trxid)(locker, trxid); -} - -static inline void -inline_mysql_inc_transaction_savepoints(PSI_transaction_locker *locker, - ulong count) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(inc_transaction_savepoints)(locker, count); -} - -static inline void -inline_mysql_inc_transaction_rollback_to_savepoint(PSI_transaction_locker *locker, - ulong count) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(inc_transaction_rollback_to_savepoint)(locker, count); -} - -static inline void -inline_mysql_inc_transaction_release_savepoint(PSI_transaction_locker *locker, - ulong count) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(inc_transaction_release_savepoint)(locker, count); -} - -static inline void -inline_mysql_rollback_transaction(struct PSI_transaction_locker *locker) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(end_transaction)(locker, false); -} - -static inline void -inline_mysql_commit_transaction(struct PSI_transaction_locker *locker) -{ - if (likely(locker != NULL)) - PSI_TRANSACTION_CALL(end_transaction)(locker, true); -} -#endif - -/** @} (end of group Transaction_instrumentation) */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi.h deleted file mode 100644 index 958a086..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi.h +++ /dev/null @@ -1,3028 +0,0 @@ -/* Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H -#define MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H - -#ifndef MY_GLOBAL_INCLUDED -/* - Make sure a .c or .cc file contains an include to my_global.h first. - When this include is missing, all the #ifdef HAVE_XXX have no effect, - and the resulting binary won't build, or won't link, - or will crash at runtime - since various structures will have different binary definitions. -*/ -#error "You must include my_global.h in the code for the build to be correct." -#endif - -/* - If PSI_ON_BY_DFAULT is defined, assume PSI will be enabled by default and - optimize jumps testing for PSI this case. If not, optimize the binary for - that PSI is not enabled -*/ - -#ifdef PSI_ON_BY_DEFAULT -#define psi_likely(A) likely(A) -#define psi_unlikely(A) unlikely(A) -#else -#define psi_likely(A) unlikely(A) -#define psi_unlikely(A) likely(A) -#endif - -#include "psi_base.h" -#include "psi_memory.h" - -#ifdef _WIN32 -typedef struct thread_attr pthread_attr_t; -typedef DWORD pthread_t; -typedef DWORD pthread_key_t; -#endif - -/* - MAINTAINER: - The following pattern: - typedef struct XYZ XYZ; - is not needed in C++, but required for C. -*/ - -C_MODE_START - -/** @sa MDL_key. */ -struct MDL_key; -typedef struct MDL_key MDL_key; - -/** @sa enum_mdl_type. */ -typedef int opaque_mdl_type; - -/** @sa enum_mdl_duration. */ -typedef int opaque_mdl_duration; - -/** @sa MDL_wait::enum_wait_status. */ -typedef int opaque_mdl_status; - -/** @sa enum_vio_type. */ -typedef int opaque_vio_type; - -struct TABLE_SHARE; - -struct sql_digest_storage; - -#ifdef __cplusplus - class THD; -#else - /* - Phony declaration when compiling C code. - This is ok, because the C code will never have a THD anyway. - */ - struct opaque_THD - { - int dummy; - }; - typedef struct opaque_THD THD; -#endif - -/** - @file mysql/psi/psi.h - Performance schema instrumentation interface. - - @defgroup Instrumentation_interface Instrumentation Interface - @ingroup Performance_schema - @{ -*/ - -/** - Interface for an instrumented mutex. - This is an opaque structure. -*/ -struct PSI_mutex; -typedef struct PSI_mutex PSI_mutex; - -/** - Interface for an instrumented rwlock. - This is an opaque structure. -*/ -struct PSI_rwlock; -typedef struct PSI_rwlock PSI_rwlock; - -/** - Interface for an instrumented condition. - This is an opaque structure. -*/ -struct PSI_cond; -typedef struct PSI_cond PSI_cond; - -/** - Interface for an instrumented table share. - This is an opaque structure. -*/ -struct PSI_table_share; -typedef struct PSI_table_share PSI_table_share; - -/** - Interface for an instrumented table handle. - This is an opaque structure. -*/ -struct PSI_table; -typedef struct PSI_table PSI_table; - -/** - Interface for an instrumented thread. - This is an opaque structure. -*/ -struct PSI_thread; -typedef struct PSI_thread PSI_thread; - -/** - Interface for an instrumented file handle. - This is an opaque structure. -*/ -struct PSI_file; -typedef struct PSI_file PSI_file; - -/** - Interface for an instrumented socket descriptor. - This is an opaque structure. -*/ -struct PSI_socket; -typedef struct PSI_socket PSI_socket; - -/** - Interface for an instrumented prepared statement. - This is an opaque structure. -*/ -struct PSI_prepared_stmt; -typedef struct PSI_prepared_stmt PSI_prepared_stmt; - -/** - Interface for an instrumented table operation. - This is an opaque structure. -*/ -struct PSI_table_locker; -typedef struct PSI_table_locker PSI_table_locker; - -/** - Interface for an instrumented statement. - This is an opaque structure. -*/ -struct PSI_statement_locker; -typedef struct PSI_statement_locker PSI_statement_locker; - -/** - Interface for an instrumented transaction. - This is an opaque structure. -*/ -struct PSI_transaction_locker; -typedef struct PSI_transaction_locker PSI_transaction_locker; - -/** - Interface for an instrumented idle operation. - This is an opaque structure. -*/ -struct PSI_idle_locker; -typedef struct PSI_idle_locker PSI_idle_locker; - -/** - Interface for an instrumented statement digest operation. - This is an opaque structure. -*/ -struct PSI_digest_locker; -typedef struct PSI_digest_locker PSI_digest_locker; - -/** - Interface for an instrumented stored procedure share. - This is an opaque structure. -*/ -struct PSI_sp_share; -typedef struct PSI_sp_share PSI_sp_share; - -/** - Interface for an instrumented stored program. - This is an opaque structure. -*/ -struct PSI_sp_locker; -typedef struct PSI_sp_locker PSI_sp_locker; - -/** - Interface for an instrumented metadata lock. - This is an opaque structure. -*/ -struct PSI_metadata_lock; -typedef struct PSI_metadata_lock PSI_metadata_lock; - -/** - Interface for an instrumented stage progress. - This is a public structure, for efficiency. -*/ -struct PSI_stage_progress -{ - ulonglong m_work_completed; - ulonglong m_work_estimated; -}; -typedef struct PSI_stage_progress PSI_stage_progress; - -/** IO operation performed on an instrumented table. */ -enum PSI_table_io_operation -{ - /** Row fetch. */ - PSI_TABLE_FETCH_ROW= 0, - /** Row write. */ - PSI_TABLE_WRITE_ROW= 1, - /** Row update. */ - PSI_TABLE_UPDATE_ROW= 2, - /** Row delete. */ - PSI_TABLE_DELETE_ROW= 3 -}; -typedef enum PSI_table_io_operation PSI_table_io_operation; - -/** - State data storage for @c start_table_io_wait_v1_t, - @c start_table_lock_wait_v1_t. - This structure provide temporary storage to a table locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa start_table_io_wait_v1_t - @sa start_table_lock_wait_v1_t -*/ -struct PSI_table_locker_state -{ - /** Internal state. */ - uint m_flags; - /** Current io operation. */ - enum PSI_table_io_operation m_io_operation; - /** Current table handle. */ - struct PSI_table *m_table; - /** Current table share. */ - struct PSI_table_share *m_table_share; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_wait; - /** - Implementation specific. - For table io, the table io index. - For table lock, the lock type. - */ - uint m_index; -}; -typedef struct PSI_table_locker_state PSI_table_locker_state; - -/** Entry point for the performance schema interface. */ -struct PSI_bootstrap -{ - /** - ABI interface finder. - Calling this method with an interface version number returns either - an instance of the ABI for this version, or NULL. - @param version the interface version number to find - @return a versioned interface (PSI_v1, PSI_v2 or PSI) - @sa PSI_VERSION_1 - @sa PSI_v1 - @sa PSI_VERSION_2 - @sa PSI_v2 - @sa PSI_CURRENT_VERSION - @sa PSI - */ - void* (*get_interface)(int version); -}; -typedef struct PSI_bootstrap PSI_bootstrap; - -#ifdef HAVE_PSI_INTERFACE - -#ifdef DISABLE_ALL_PSI - -#ifndef DISABLE_PSI_THREAD -#define DISABLE_PSI_THREAD -#endif - -#ifndef DISABLE_PSI_MUTEX -#define DISABLE_PSI_MUTEX -#endif - -#ifndef DISABLE_PSI_RWLOCK -#define DISABLE_PSI_RWLOCK -#endif - -#ifndef DISABLE_PSI_COND -#define DISABLE_PSI_COND -#endif - -#ifndef DISABLE_PSI_FILE -#define DISABLE_PSI_FILE -#endif - -#ifndef DISABLE_PSI_TABLE -#define DISABLE_PSI_TABLE -#endif - -#ifndef DISABLE_PSI_SOCKET -#define DISABLE_PSI_SOCKET -#endif - -#ifndef DISABLE_PSI_STAGE -#define DISABLE_PSI_STAGE -#endif - -#ifndef DISABLE_PSI_STATEMENT -#define DISABLE_PSI_STATEMENT -#endif - -#ifndef DISABLE_PSI_SP -#define DISABLE_PSI_SP -#endif - -#ifndef DISABLE_PSI_IDLE -#define DISABLE_PSI_IDLE -#endif - -#ifndef DISABLE_PSI_STATEMENT_DIGEST -#define DISABLE_PSI_STATEMENT_DIGEST -#endif - -#ifndef DISABLE_PSI_METADATA -#define DISABLE_PSI_METADATA -#endif - -#ifndef DISABLE_PSI_MEMORY -#define DISABLE_PSI_MEMORY -#endif - -#ifndef DISABLE_PSI_TRANSACTION -#define DISABLE_PSI_TRANSACTION -#endif - -#ifndef DISABLE_PSI_SP -#define DISABLE_PSI_SP -#endif - -#ifndef DISABLE_PSI_PS -#define DISABLE_PSI_PS -#endif - -#endif - -/** - @def DISABLE_PSI_MUTEX - Compiling option to disable the mutex instrumentation. - This option is mostly intended to be used during development, - when doing special builds with only a subset of the performance schema instrumentation, - for code analysis / profiling / performance tuning of a specific instrumentation alone. - @sa DISABLE_PSI_RWLOCK - @sa DISABLE_PSI_COND - @sa DISABLE_PSI_FILE - @sa DISABLE_PSI_THREAD - @sa DISABLE_PSI_TABLE - @sa DISABLE_PSI_STAGE - @sa DISABLE_PSI_STATEMENT - @sa DISABLE_PSI_SP - @sa DISABLE_PSI_STATEMENT_DIGEST - @sa DISABLE_PSI_SOCKET - @sa DISABLE_PSI_MEMORY - @sa DISABLE_PSI_IDLE - @sa DISABLE_PSI_METADATA - @sa DISABLE PSI_TRANSACTION -*/ - -#ifndef DISABLE_PSI_MUTEX -#define HAVE_PSI_MUTEX_INTERFACE -#endif - -/** - @def DISABLE_PSI_RWLOCK - Compiling option to disable the rwlock instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_RWLOCK -#define HAVE_PSI_RWLOCK_INTERFACE -#endif - -/** - @def DISABLE_PSI_COND - Compiling option to disable the cond instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_COND -#define HAVE_PSI_COND_INTERFACE -#endif - -/** - @def DISABLE_PSI_FILE - Compiling option to disable the file instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_FILE -#define HAVE_PSI_FILE_INTERFACE -#endif - -/** - @def DISABLE_PSI_THREAD - Compiling option to disable the thread instrumentation. - @sa DISABLE_PSI_MUTEX -*/ -#ifndef DISABLE_PSI_THREAD -#define HAVE_PSI_THREAD_INTERFACE -#endif - -/** - @def DISABLE_PSI_TABLE - Compiling option to disable the table instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_TABLE -#define HAVE_PSI_TABLE_INTERFACE -#endif - -/** - @def DISABLE_PSI_STAGE - Compiling option to disable the stage instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_STAGE -#define HAVE_PSI_STAGE_INTERFACE -#endif - -/** - @def DISABLE_PSI_STATEMENT - Compiling option to disable the statement instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_STATEMENT -#define HAVE_PSI_STATEMENT_INTERFACE -#endif - -/** - @def DISABLE_PSI_SP - Compiling option to disable the stored program instrumentation. - @sa DISABLE_PSI_MUTEX -*/ -#ifndef DISABLE_PSI_SP -#define HAVE_PSI_SP_INTERFACE -#endif - -/** - @def DISABLE_PSI_PS - Compiling option to disable the prepared statement instrumentation. - @sa DISABLE_PSI_MUTEX -*/ -#ifndef DISABLE_PSI_STATEMENT -#ifndef DISABLE_PSI_PS -#define HAVE_PSI_PS_INTERFACE -#endif -#endif - -/** - @def DISABLE_PSI_STATEMENT_DIGEST - Compiling option to disable the statement digest instrumentation. -*/ - -#ifndef DISABLE_PSI_STATEMENT -#ifndef DISABLE_PSI_STATEMENT_DIGEST -#define HAVE_PSI_STATEMENT_DIGEST_INTERFACE -#endif -#endif - -/** - @def DISABLE_PSI_TRANSACTION - Compiling option to disable the transaction instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_TRANSACTION -#define HAVE_PSI_TRANSACTION_INTERFACE -#endif - -/** - @def DISABLE_PSI_SOCKET - Compiling option to disable the statement instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_SOCKET -#define HAVE_PSI_SOCKET_INTERFACE -#endif - -/** - @def DISABLE_PSI_MEMORY - Compiling option to disable the memory instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_MEMORY -#define HAVE_PSI_MEMORY_INTERFACE -#endif - -/** - @def DISABLE_PSI_IDLE - Compiling option to disable the idle instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_IDLE -#define HAVE_PSI_IDLE_INTERFACE -#endif - -/** - @def DISABLE_PSI_METADATA - Compiling option to disable the metadata instrumentation. - @sa DISABLE_PSI_MUTEX -*/ - -#ifndef DISABLE_PSI_METADATA -#define HAVE_PSI_METADATA_INTERFACE -#endif - -/** - @def PSI_VERSION_1 - Performance Schema Interface number for version 1. - This version is supported. -*/ -#define PSI_VERSION_1 1 - -/** - @def PSI_VERSION_2 - Performance Schema Interface number for version 2. - This version is not implemented, it's a placeholder. -*/ -#define PSI_VERSION_2 2 - -/** - @def PSI_CURRENT_VERSION - Performance Schema Interface number for the most recent version. - The most current version is @c PSI_VERSION_1 -*/ -#define PSI_CURRENT_VERSION 1 - -#ifndef USE_PSI_2 -#ifndef USE_PSI_1 -#define USE_PSI_1 -#endif -#endif - -/** - Interface for an instrumented mutex operation. - This is an opaque structure. -*/ -struct PSI_mutex_locker; -typedef struct PSI_mutex_locker PSI_mutex_locker; - -/** - Interface for an instrumented rwlock operation. - This is an opaque structure. -*/ -struct PSI_rwlock_locker; -typedef struct PSI_rwlock_locker PSI_rwlock_locker; - -/** - Interface for an instrumented condition operation. - This is an opaque structure. -*/ -struct PSI_cond_locker; -typedef struct PSI_cond_locker PSI_cond_locker; - -/** - Interface for an instrumented file operation. - This is an opaque structure. -*/ -struct PSI_file_locker; -typedef struct PSI_file_locker PSI_file_locker; - -/** - Interface for an instrumented socket operation. - This is an opaque structure. -*/ -struct PSI_socket_locker; -typedef struct PSI_socket_locker PSI_socket_locker; - -/** - Interface for an instrumented MDL operation. - This is an opaque structure. -*/ -struct PSI_metadata_locker; -typedef struct PSI_metadata_locker PSI_metadata_locker; - -/** Operation performed on an instrumented mutex. */ -enum PSI_mutex_operation -{ - /** Lock. */ - PSI_MUTEX_LOCK= 0, - /** Lock attempt. */ - PSI_MUTEX_TRYLOCK= 1 -}; -typedef enum PSI_mutex_operation PSI_mutex_operation; - -/** - Operation performed on an instrumented rwlock. - For basic READ / WRITE lock, - operations are "READ" or "WRITE". - For SX-locks, operations are "SHARED", "SHARED-EXCLUSIVE" or "EXCLUSIVE". -*/ -enum PSI_rwlock_operation -{ - /** Read lock. */ - PSI_RWLOCK_READLOCK= 0, - /** Write lock. */ - PSI_RWLOCK_WRITELOCK= 1, - /** Read lock attempt. */ - PSI_RWLOCK_TRYREADLOCK= 2, - /** Write lock attempt. */ - PSI_RWLOCK_TRYWRITELOCK= 3, - - /** Shared lock. */ - PSI_RWLOCK_SHAREDLOCK= 4, - /** Shared Exclusive lock. */ - PSI_RWLOCK_SHAREDEXCLUSIVELOCK= 5, - /** Exclusive lock. */ - PSI_RWLOCK_EXCLUSIVELOCK= 6, - /** Shared lock attempt. */ - PSI_RWLOCK_TRYSHAREDLOCK= 7, - /** Shared Exclusive lock attempt. */ - PSI_RWLOCK_TRYSHAREDEXCLUSIVELOCK= 8, - /** Exclusive lock attempt. */ - PSI_RWLOCK_TRYEXCLUSIVELOCK= 9 - -}; -typedef enum PSI_rwlock_operation PSI_rwlock_operation; - -/** Operation performed on an instrumented condition. */ -enum PSI_cond_operation -{ - /** Wait. */ - PSI_COND_WAIT= 0, - /** Wait, with timeout. */ - PSI_COND_TIMEDWAIT= 1 -}; -typedef enum PSI_cond_operation PSI_cond_operation; - -/** Operation performed on an instrumented file. */ -enum PSI_file_operation -{ - /** File creation, as in @c create(). */ - PSI_FILE_CREATE= 0, - /** Temporary file creation, as in @c create_temp_file(). */ - PSI_FILE_CREATE_TMP= 1, - /** File open, as in @c open(). */ - PSI_FILE_OPEN= 2, - /** File open, as in @c fopen(). */ - PSI_FILE_STREAM_OPEN= 3, - /** File close, as in @c close(). */ - PSI_FILE_CLOSE= 4, - /** File close, as in @c fclose(). */ - PSI_FILE_STREAM_CLOSE= 5, - /** - Generic file read, such as @c fgets(), @c fgetc(), @c fread(), @c read(), - @c pread(). - */ - PSI_FILE_READ= 6, - /** - Generic file write, such as @c fputs(), @c fputc(), @c fprintf(), - @c vfprintf(), @c fwrite(), @c write(), @c pwrite(). - */ - PSI_FILE_WRITE= 7, - /** Generic file seek, such as @c fseek() or @c seek(). */ - PSI_FILE_SEEK= 8, - /** Generic file tell, such as @c ftell() or @c tell(). */ - PSI_FILE_TELL= 9, - /** File flush, as in @c fflush(). */ - PSI_FILE_FLUSH= 10, - /** File stat, as in @c stat(). */ - PSI_FILE_STAT= 11, - /** File stat, as in @c fstat(). */ - PSI_FILE_FSTAT= 12, - /** File chsize, as in @c my_chsize(). */ - PSI_FILE_CHSIZE= 13, - /** File delete, such as @c my_delete() or @c my_handler_delete_with_symlink(). */ - PSI_FILE_DELETE= 14, - /** File rename, such as @c my_rename() or @c my_rename_with_symlink(). */ - PSI_FILE_RENAME= 15, - /** File sync, as in @c fsync() or @c my_sync(). */ - PSI_FILE_SYNC= 16 -}; -typedef enum PSI_file_operation PSI_file_operation; - -/** Lock operation performed on an instrumented table. */ -enum PSI_table_lock_operation -{ - /** Table lock, in the server layer. */ - PSI_TABLE_LOCK= 0, - /** Table lock, in the storage engine layer. */ - PSI_TABLE_EXTERNAL_LOCK= 1 -}; -typedef enum PSI_table_lock_operation PSI_table_lock_operation; - -/** State of an instrumented socket. */ -enum PSI_socket_state -{ - /** Idle, waiting for the next command. */ - PSI_SOCKET_STATE_IDLE= 1, - /** Active, executing a command. */ - PSI_SOCKET_STATE_ACTIVE= 2 -}; -typedef enum PSI_socket_state PSI_socket_state; - -/** Operation performed on an instrumented socket. */ -enum PSI_socket_operation -{ - /** Socket creation, as in @c socket() or @c socketpair(). */ - PSI_SOCKET_CREATE= 0, - /** Socket connection, as in @c connect(), @c listen() and @c accept(). */ - PSI_SOCKET_CONNECT= 1, - /** Socket bind, as in @c bind(), @c getsockname() and @c getpeername(). */ - PSI_SOCKET_BIND= 2, - /** Socket close, as in @c shutdown(). */ - PSI_SOCKET_CLOSE= 3, - /** Socket send, @c send(). */ - PSI_SOCKET_SEND= 4, - /** Socket receive, @c recv(). */ - PSI_SOCKET_RECV= 5, - /** Socket send, @c sendto(). */ - PSI_SOCKET_SENDTO= 6, - /** Socket receive, @c recvfrom). */ - PSI_SOCKET_RECVFROM= 7, - /** Socket send, @c sendmsg(). */ - PSI_SOCKET_SENDMSG= 8, - /** Socket receive, @c recvmsg(). */ - PSI_SOCKET_RECVMSG= 9, - /** Socket seek, such as @c fseek() or @c seek(). */ - PSI_SOCKET_SEEK= 10, - /** Socket options, as in @c getsockopt() and @c setsockopt(). */ - PSI_SOCKET_OPT= 11, - /** Socket status, as in @c sockatmark() and @c isfdtype(). */ - PSI_SOCKET_STAT= 12, - /** Socket shutdown, as in @c shutdown(). */ - PSI_SOCKET_SHUTDOWN= 13, - /** Socket select, as in @c select() and @c poll(). */ - PSI_SOCKET_SELECT= 14 -}; -typedef enum PSI_socket_operation PSI_socket_operation; - -#endif -/** - Instrumented mutex key. - To instrument a mutex, a mutex key must be obtained using @c register_mutex. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_mutex_key; - -/** - Instrumented rwlock key. - To instrument a rwlock, a rwlock key must be obtained - using @c register_rwlock. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_rwlock_key; - -/** - Instrumented cond key. - To instrument a condition, a condition key must be obtained - using @c register_cond. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_cond_key; - -/** - Instrumented thread key. - To instrument a thread, a thread key must be obtained - using @c register_thread. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_thread_key; - -/** - Instrumented file key. - To instrument a file, a file key must be obtained using @c register_file. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_file_key; - -/** - Instrumented stage key. - To instrument a stage, a stage key must be obtained using @c register_stage. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_stage_key; - -/** - Instrumented statement key. - To instrument a statement, a statement key must be obtained using @c register_statement. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_statement_key; - -/** - Instrumented socket key. - To instrument a socket, a socket key must be obtained using @c register_socket. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_socket_key; - -#ifdef HAVE_PSI_1 - -/** - @defgroup Group_PSI_v1 Application Binary Interface, version 1 - @ingroup Instrumentation_interface - @{ -*/ - -/** - Mutex information. - @since PSI_VERSION_1 - This structure is used to register an instrumented mutex. -*/ -struct PSI_mutex_info_v1 -{ - /** - Pointer to the key assigned to the registered mutex. - */ - PSI_mutex_key *m_key; - /** - The name of the mutex to register. - */ - const char *m_name; - /** - The flags of the mutex to register. - @sa PSI_FLAG_GLOBAL - */ - int m_flags; -}; -typedef struct PSI_mutex_info_v1 PSI_mutex_info_v1; - -/** - Rwlock information. - @since PSI_VERSION_1 - This structure is used to register an instrumented rwlock. -*/ -struct PSI_rwlock_info_v1 -{ - /** - Pointer to the key assigned to the registered rwlock. - */ - PSI_rwlock_key *m_key; - /** - The name of the rwlock to register. - */ - const char *m_name; - /** - The flags of the rwlock to register. - @sa PSI_FLAG_GLOBAL - */ - int m_flags; -}; -typedef struct PSI_rwlock_info_v1 PSI_rwlock_info_v1; - -/** - Condition information. - @since PSI_VERSION_1 - This structure is used to register an instrumented cond. -*/ -struct PSI_cond_info_v1 -{ - /** - Pointer to the key assigned to the registered cond. - */ - PSI_cond_key *m_key; - /** - The name of the cond to register. - */ - const char *m_name; - /** - The flags of the cond to register. - @sa PSI_FLAG_GLOBAL - */ - int m_flags; -}; -typedef struct PSI_cond_info_v1 PSI_cond_info_v1; - -/** - Thread instrument information. - @since PSI_VERSION_1 - This structure is used to register an instrumented thread. -*/ -struct PSI_thread_info_v1 -{ - /** - Pointer to the key assigned to the registered thread. - */ - PSI_thread_key *m_key; - /** - The name of the thread instrument to register. - */ - const char *m_name; - /** - The flags of the thread to register. - @sa PSI_FLAG_GLOBAL - */ - int m_flags; -}; -typedef struct PSI_thread_info_v1 PSI_thread_info_v1; - -/** - File instrument information. - @since PSI_VERSION_1 - This structure is used to register an instrumented file. -*/ -struct PSI_file_info_v1 -{ - /** - Pointer to the key assigned to the registered file. - */ - PSI_file_key *m_key; - /** - The name of the file instrument to register. - */ - const char *m_name; - /** - The flags of the file instrument to register. - @sa PSI_FLAG_GLOBAL - */ - int m_flags; -}; -typedef struct PSI_file_info_v1 PSI_file_info_v1; - -/** - Stage instrument information. - @since PSI_VERSION_1 - This structure is used to register an instrumented stage. -*/ -struct PSI_stage_info_v1 -{ - /** The registered stage key. */ - PSI_stage_key m_key; - /** The name of the stage instrument to register. */ - const char *m_name; - /** The flags of the stage instrument to register. */ - int m_flags; -}; -typedef struct PSI_stage_info_v1 PSI_stage_info_v1; - -/** - Statement instrument information. - @since PSI_VERSION_1 - This structure is used to register an instrumented statement. -*/ -struct PSI_statement_info_v1 -{ - /** The registered statement key. */ - PSI_statement_key m_key; - /** The name of the statement instrument to register. */ - const char *m_name; - /** The flags of the statement instrument to register. */ - int m_flags; -}; -typedef struct PSI_statement_info_v1 PSI_statement_info_v1; - -/** - Socket instrument information. - @since PSI_VERSION_1 - This structure is used to register an instrumented socket. -*/ -struct PSI_socket_info_v1 -{ - /** - Pointer to the key assigned to the registered socket. - */ - PSI_socket_key *m_key; - /** - The name of the socket instrument to register. - */ - const char *m_name; - /** - The flags of the socket instrument to register. - @sa PSI_FLAG_GLOBAL - */ - int m_flags; -}; -typedef struct PSI_socket_info_v1 PSI_socket_info_v1; - -/** - State data storage for @c start_idle_wait_v1_t. - This structure provide temporary storage to an idle locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa start_idle_wait_v1_t. -*/ -struct PSI_idle_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_wait; -}; -typedef struct PSI_idle_locker_state_v1 PSI_idle_locker_state_v1; - -/** - State data storage for @c start_mutex_wait_v1_t. - This structure provide temporary storage to a mutex locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa start_mutex_wait_v1_t -*/ -struct PSI_mutex_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current operation. */ - enum PSI_mutex_operation m_operation; - /** Current mutex. */ - struct PSI_mutex *m_mutex; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_wait; -}; -typedef struct PSI_mutex_locker_state_v1 PSI_mutex_locker_state_v1; - -/** - State data storage for @c start_rwlock_rdwait_v1_t, @c start_rwlock_wrwait_v1_t. - This structure provide temporary storage to a rwlock locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa start_rwlock_rdwait_v1_t - @sa start_rwlock_wrwait_v1_t -*/ -struct PSI_rwlock_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current operation. */ - enum PSI_rwlock_operation m_operation; - /** Current rwlock. */ - struct PSI_rwlock *m_rwlock; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_wait; -}; -typedef struct PSI_rwlock_locker_state_v1 PSI_rwlock_locker_state_v1; - -/** - State data storage for @c start_cond_wait_v1_t. - This structure provide temporary storage to a condition locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa start_cond_wait_v1_t -*/ -struct PSI_cond_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current operation. */ - enum PSI_cond_operation m_operation; - /** Current condition. */ - struct PSI_cond *m_cond; - /** Current mutex. */ - struct PSI_mutex *m_mutex; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_wait; -}; -typedef struct PSI_cond_locker_state_v1 PSI_cond_locker_state_v1; - -/** - State data storage for @c get_thread_file_name_locker_v1_t. - This structure provide temporary storage to a file locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa get_thread_file_name_locker_v1_t - @sa get_thread_file_stream_locker_v1_t - @sa get_thread_file_descriptor_locker_v1_t -*/ -struct PSI_file_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current operation. */ - enum PSI_file_operation m_operation; - /** Current file. */ - struct PSI_file *m_file; - /** Current file name. */ - const char *m_name; - /** Current file class. */ - void *m_class; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Operation number of bytes. */ - size_t m_number_of_bytes; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_wait; -}; -typedef struct PSI_file_locker_state_v1 PSI_file_locker_state_v1; - -/** - State data storage for @c start_metadata_wait_v1_t. - This structure provide temporary storage to a metadata locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa start_metadata_wait_v1_t -*/ -struct PSI_metadata_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current metadata lock. */ - struct PSI_metadata_lock *m_metadata_lock; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_wait; -}; -typedef struct PSI_metadata_locker_state_v1 PSI_metadata_locker_state_v1; - -/* Duplicate of NAME_LEN, to avoid dependency on mysql_com.h */ -#define PSI_SCHEMA_NAME_LEN (64 * 3) - -/** - State data storage for @c get_thread_statement_locker_v1_t, - @c get_thread_statement_locker_v1_t. - This structure provide temporary storage to a statement locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa get_thread_statement_locker_v1_t -*/ -struct PSI_statement_locker_state_v1 -{ - /** Discarded flag. */ - my_bool m_discarded; - /** In prepare flag. */ - my_bool m_in_prepare; - /** Metric, no index used flag. */ - uchar m_no_index_used; - /** Metric, no good index used flag. */ - uchar m_no_good_index_used; - /** Internal state. */ - uint m_flags; - /** Instrumentation class. */ - void *m_class; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_statement; - /** Locked time. */ - ulonglong m_lock_time; - /** Rows sent. */ - ulonglong m_rows_sent; - /** Rows examined. */ - ulonglong m_rows_examined; - /** Metric, temporary tables created on disk. */ - ulong m_created_tmp_disk_tables; - /** Metric, temporary tables created. */ - ulong m_created_tmp_tables; - /** Metric, number of select full join. */ - ulong m_select_full_join; - /** Metric, number of select full range join. */ - ulong m_select_full_range_join; - /** Metric, number of select range. */ - ulong m_select_range; - /** Metric, number of select range check. */ - ulong m_select_range_check; - /** Metric, number of select scan. */ - ulong m_select_scan; - /** Metric, number of sort merge passes. */ - ulong m_sort_merge_passes; - /** Metric, number of sort merge. */ - ulong m_sort_range; - /** Metric, number of sort rows. */ - ulong m_sort_rows; - /** Metric, number of sort scans. */ - ulong m_sort_scan; - /** Statement digest. */ - const struct sql_digest_storage *m_digest; - /** Current schema name. */ - char m_schema_name[PSI_SCHEMA_NAME_LEN]; - /** Length in bytes of @c m_schema_name. */ - uint m_schema_name_length; - /** Statement character set number. */ - uint m_cs_number; - PSI_sp_share *m_parent_sp_share; - PSI_prepared_stmt *m_parent_prepared_stmt; -}; -typedef struct PSI_statement_locker_state_v1 PSI_statement_locker_state_v1; - -/** - State data storage for @c get_thread_transaction_locker_v1_t, - @c get_thread_transaction_locker_v1_t. - This structure provide temporary storage to a transaction locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa get_thread_transaction_locker_v1_t -*/ -struct PSI_transaction_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Instrumentation class. */ - void *m_class; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Internal data. */ - void *m_transaction; - /** True if read-only transaction, false if read-write. */ - my_bool m_read_only; - /** True if transaction is autocommit. */ - my_bool m_autocommit; - /** Number of statements. */ - ulong m_statement_count; - /** Total number of savepoints. */ - ulong m_savepoint_count; - /** Number of rollback_to_savepoint. */ - ulong m_rollback_to_savepoint_count; - /** Number of release_savepoint. */ - ulong m_release_savepoint_count; -}; - -typedef struct PSI_transaction_locker_state_v1 PSI_transaction_locker_state_v1; - -/** - State data storage for @c start_socket_wait_v1_t. - This structure provide temporary storage to a socket locker. - The content of this structure is considered opaque, - the fields are only hints of what an implementation - of the psi interface can use. - This memory is provided by the instrumented code for performance reasons. - @sa start_socket_wait_v1_t -*/ -struct PSI_socket_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current socket. */ - struct PSI_socket *m_socket; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Operation number of bytes. */ - size_t m_number_of_bytes; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Current operation. */ - enum PSI_socket_operation m_operation; - /** Source file. */ - const char* m_src_file; - /** Source line number. */ - int m_src_line; - /** Internal data. */ - void *m_wait; -}; -typedef struct PSI_socket_locker_state_v1 PSI_socket_locker_state_v1; - -struct PSI_sp_locker_state_v1 -{ - /** Internal state. */ - uint m_flags; - /** Current thread. */ - struct PSI_thread *m_thread; - /** Timer start. */ - ulonglong m_timer_start; - /** Timer function. */ - ulonglong (*m_timer)(void); - /** Stored Procedure share. */ - PSI_sp_share* m_sp_share; -}; -typedef struct PSI_sp_locker_state_v1 PSI_sp_locker_state_v1; - -/* Using typedef to make reuse between PSI_v1 and PSI_v2 easier later. */ - -/** - Mutex registration API. - @param category a category name (typically a plugin name) - @param info an array of mutex info to register - @param count the size of the info array -*/ -typedef void (*register_mutex_v1_t) - (const char *category, struct PSI_mutex_info_v1 *info, int count); - -/** - Rwlock registration API. - @param category a category name (typically a plugin name) - @param info an array of rwlock info to register - @param count the size of the info array -*/ -typedef void (*register_rwlock_v1_t) - (const char *category, struct PSI_rwlock_info_v1 *info, int count); - -/** - Cond registration API. - @param category a category name (typically a plugin name) - @param info an array of cond info to register - @param count the size of the info array -*/ -typedef void (*register_cond_v1_t) - (const char *category, struct PSI_cond_info_v1 *info, int count); - -/** - Thread registration API. - @param category a category name (typically a plugin name) - @param info an array of thread info to register - @param count the size of the info array -*/ -typedef void (*register_thread_v1_t) - (const char *category, struct PSI_thread_info_v1 *info, int count); - -/** - File registration API. - @param category a category name (typically a plugin name) - @param info an array of file info to register - @param count the size of the info array -*/ -typedef void (*register_file_v1_t) - (const char *category, struct PSI_file_info_v1 *info, int count); - -/** - Stage registration API. - @param category a category name - @param info an array of stage info to register - @param count the size of the info array -*/ -typedef void (*register_stage_v1_t) - (const char *category, struct PSI_stage_info_v1 **info, int count); - -/** - Statement registration API. - @param category a category name - @param info an array of stage info to register - @param count the size of the info array -*/ -typedef void (*register_statement_v1_t) - (const char *category, struct PSI_statement_info_v1 *info, int count); - -/** - Socket registration API. - @param category a category name (typically a plugin name) - @param info an array of socket info to register - @param count the size of the info array -*/ -typedef void (*register_socket_v1_t) - (const char *category, struct PSI_socket_info_v1 *info, int count); - -/** - Mutex instrumentation initialisation API. - @param key the registered mutex key - @param identity the address of the mutex itself - @return an instrumented mutex -*/ -typedef struct PSI_mutex* (*init_mutex_v1_t) - (PSI_mutex_key key, const void *identity); - -/** - Mutex instrumentation destruction API. - @param mutex the mutex to destroy -*/ -typedef void (*destroy_mutex_v1_t)(struct PSI_mutex *mutex); - -/** - Rwlock instrumentation initialisation API. - @param key the registered rwlock key - @param identity the address of the rwlock itself - @return an instrumented rwlock -*/ -typedef struct PSI_rwlock* (*init_rwlock_v1_t) - (PSI_rwlock_key key, const void *identity); - -/** - Rwlock instrumentation destruction API. - @param rwlock the rwlock to destroy -*/ -typedef void (*destroy_rwlock_v1_t)(struct PSI_rwlock *rwlock); - -/** - Cond instrumentation initialisation API. - @param key the registered key - @param identity the address of the rwlock itself - @return an instrumented cond -*/ -typedef struct PSI_cond* (*init_cond_v1_t) - (PSI_cond_key key, const void *identity); - -/** - Cond instrumentation destruction API. - @param cond the rcond to destroy -*/ -typedef void (*destroy_cond_v1_t)(struct PSI_cond *cond); - -/** - Socket instrumentation initialisation API. - @param key the registered mutex key - @param socket descriptor - @param addr the socket ip address - @param addr_len length of socket ip address - @return an instrumented socket -*/ -typedef struct PSI_socket* (*init_socket_v1_t) - (PSI_socket_key key, const my_socket *fd, - const struct sockaddr *addr, socklen_t addr_len); - -/** - socket instrumentation destruction API. - @param socket the socket to destroy -*/ -typedef void (*destroy_socket_v1_t)(struct PSI_socket *socket); - -/** - Acquire a table share instrumentation. - @param temporary True for temporary tables - @param share The SQL layer table share - @return a table share instrumentation, or NULL -*/ -typedef struct PSI_table_share* (*get_table_share_v1_t) - (my_bool temporary, struct TABLE_SHARE *share); - -/** - Release a table share. - @param info the table share to release -*/ -typedef void (*release_table_share_v1_t)(struct PSI_table_share *share); - -/** - Drop a table share. - @param temporary True for temporary tables - @param schema_name the table schema name - @param schema_name_length the table schema name length - @param table_name the table name - @param table_name_length the table name length -*/ -typedef void (*drop_table_share_v1_t) - (my_bool temporary, const char *schema_name, int schema_name_length, - const char *table_name, int table_name_length); - -/** - Open an instrumentation table handle. - @param share the table to open - @param identity table handle identity - @return a table handle, or NULL -*/ -typedef struct PSI_table* (*open_table_v1_t) - (struct PSI_table_share *share, const void *identity); - -/** - Unbind a table handle from the current thread. - This operation happens when an opened table is added to the open table cache. - @param table the table to unbind -*/ -typedef void (*unbind_table_v1_t) - (struct PSI_table *table); - -/** - Rebind a table handle to the current thread. - This operation happens when a table from the open table cache - is reused for a thread. - @param table the table to unbind -*/ -typedef PSI_table* (*rebind_table_v1_t) - (PSI_table_share *share, const void *identity, PSI_table *table); - -/** - Close an instrumentation table handle. - Note that the table handle is invalid after this call. - @param table the table handle to close -*/ -typedef void (*close_table_v1_t)(struct TABLE_SHARE *server_share, - struct PSI_table *table); - -/** - Create a file instrumentation for a created file. - This method does not create the file itself, but is used to notify the - instrumentation interface that a file was just created. - @param key the file instrumentation key for this file - @param name the file name - @param file the file handle -*/ -typedef void (*create_file_v1_t)(PSI_file_key key, const char *name, - File file); - -/** - Spawn a thread. - This method creates a new thread, with instrumentation. - @param key the instrumentation key for this thread - @param thread the resulting thread - @param attr the thread attributes - @param start_routine the thread start routine - @param arg the thread start routine argument -*/ -typedef int (*spawn_thread_v1_t)(PSI_thread_key key, - pthread_t *thread, - const pthread_attr_t *attr, - void *(*start_routine)(void*), void *arg); - -/** - Create instrumentation for a thread. - @param key the registered key - @param identity an address typical of the thread - @return an instrumented thread -*/ -typedef struct PSI_thread* (*new_thread_v1_t) - (PSI_thread_key key, const void *identity, ulonglong thread_id); - -/** - Assign a THD to an instrumented thread. - @param thread the instrumented thread - @param THD the sql layer THD to assign -*/ -typedef void (*set_thread_THD_v1_t)(struct PSI_thread *thread, - THD *thd); - -/** - Assign an id to an instrumented thread. - @param thread the instrumented thread - @param id the id to assign -*/ -typedef void (*set_thread_id_v1_t)(struct PSI_thread *thread, - ulonglong id); - -/** - Assign the current operating system thread id to an instrumented thread. - The operating system task id is obtained from @c gettid() - @param thread the instrumented thread -*/ -typedef void (*set_thread_os_id_v1_t)(struct PSI_thread *thread); - -/** - Get the instrumentation for the running thread. - For this function to return a result, - the thread instrumentation must have been attached to the - running thread using @c set_thread() - @return the instrumentation for the running thread -*/ -typedef struct PSI_thread* (*get_thread_v1_t)(void); - -/** - Assign a user name to the instrumented thread. - @param user the user name - @param user_len the user name length -*/ -typedef void (*set_thread_user_v1_t)(const char *user, int user_len); - -/** - Assign a user name and host name to the instrumented thread. - @param user the user name - @param user_len the user name length - @param host the host name - @param host_len the host name length -*/ -typedef void (*set_thread_account_v1_t)(const char *user, int user_len, - const char *host, int host_len); - -/** - Assign a current database to the instrumented thread. - @param db the database name - @param db_len the database name length -*/ -typedef void (*set_thread_db_v1_t)(const char* db, int db_len); - -/** - Assign a current command to the instrumented thread. - @param command the current command -*/ -typedef void (*set_thread_command_v1_t)(int command); - -/** - Assign a connection type to the instrumented thread. - @param conn_type the connection type -*/ -typedef void (*set_connection_type_v1_t)(opaque_vio_type conn_type); - - -/** - Assign a start time to the instrumented thread. - @param start_time the thread start time -*/ -typedef void (*set_thread_start_time_v1_t)(time_t start_time); - -/** - Assign a state to the instrumented thread. - @param state the thread state -*/ -typedef void (*set_thread_state_v1_t)(const char* state); - -/** - Assign a process info to the instrumented thread. - @param info the process into string - @param info_len the process into string length -*/ -typedef void (*set_thread_info_v1_t)(const char* info, uint info_len); - -/** - Attach a thread instrumentation to the running thread. - In case of thread pools, this method should be called when - a worker thread picks a work item and runs it. - Also, this method should be called if the instrumented code does not - keep the pointer returned by @c new_thread() and relies on @c get_thread() - instead. - @param thread the thread instrumentation -*/ -typedef void (*set_thread_v1_t)(struct PSI_thread *thread); - -/** Delete the current thread instrumentation. */ -typedef void (*delete_current_thread_v1_t)(void); - -/** Delete a thread instrumentation. */ -typedef void (*delete_thread_v1_t)(struct PSI_thread *thread); - -/** - Get a file instrumentation locker, for opening or creating a file. - @param state data storage for the locker - @param key the file instrumentation key - @param op the operation to perform - @param name the file name - @param identity a pointer representative of this file. - @return a file locker, or NULL -*/ -typedef struct PSI_file_locker* (*get_thread_file_name_locker_v1_t) - (struct PSI_file_locker_state_v1 *state, - PSI_file_key key, enum PSI_file_operation op, const char *name, - const void *identity); - -/** - Get a file stream instrumentation locker. - @param state data storage for the locker - @param file the file stream to access - @param op the operation to perform - @return a file locker, or NULL -*/ -typedef struct PSI_file_locker* (*get_thread_file_stream_locker_v1_t) - (struct PSI_file_locker_state_v1 *state, - struct PSI_file *file, enum PSI_file_operation op); - -/** - Get a file instrumentation locker. - @param state data storage for the locker - @param file the file descriptor to access - @param op the operation to perform - @return a file locker, or NULL -*/ -typedef struct PSI_file_locker* (*get_thread_file_descriptor_locker_v1_t) - (struct PSI_file_locker_state_v1 *state, - File file, enum PSI_file_operation op); - -/** - Record a mutex instrumentation unlock event. - @param mutex the mutex instrumentation -*/ -typedef void (*unlock_mutex_v1_t) - (struct PSI_mutex *mutex); - -/** - Record a rwlock instrumentation unlock event. - @param rwlock the rwlock instrumentation -*/ -typedef void (*unlock_rwlock_v1_t) - (struct PSI_rwlock *rwlock); - -/** - Record a condition instrumentation signal event. - @param cond the cond instrumentation -*/ -typedef void (*signal_cond_v1_t) - (struct PSI_cond *cond); - -/** - Record a condition instrumentation broadcast event. - @param cond the cond instrumentation -*/ -typedef void (*broadcast_cond_v1_t) - (struct PSI_cond *cond); - -/** - Record an idle instrumentation wait start event. - @param state data storage for the locker - @param file the source file name - @param line the source line number - @return an idle locker, or NULL -*/ -typedef struct PSI_idle_locker* (*start_idle_wait_v1_t) - (struct PSI_idle_locker_state_v1 *state, const char *src_file, uint src_line); - -/** - Record an idle instrumentation wait end event. - @param locker a thread locker for the running thread -*/ -typedef void (*end_idle_wait_v1_t) - (struct PSI_idle_locker *locker); - -/** - Record a mutex instrumentation wait start event. - @param state data storage for the locker - @param mutex the instrumented mutex to lock - @param op the operation to perform - @param file the source file name - @param line the source line number - @return a mutex locker, or NULL -*/ -typedef struct PSI_mutex_locker* (*start_mutex_wait_v1_t) - (struct PSI_mutex_locker_state_v1 *state, - struct PSI_mutex *mutex, - enum PSI_mutex_operation op, - const char *src_file, uint src_line); - -/** - Record a mutex instrumentation wait end event. - @param locker a thread locker for the running thread - @param rc the wait operation return code -*/ -typedef void (*end_mutex_wait_v1_t) - (struct PSI_mutex_locker *locker, int rc); - -/** - Record a rwlock instrumentation read wait start event. - @param locker a thread locker for the running thread - @param must must block: 1 for lock, 0 for trylock -*/ -typedef struct PSI_rwlock_locker* (*start_rwlock_rdwait_v1_t) - (struct PSI_rwlock_locker_state_v1 *state, - struct PSI_rwlock *rwlock, - enum PSI_rwlock_operation op, - const char *src_file, uint src_line); - -/** - Record a rwlock instrumentation read wait end event. - @param locker a thread locker for the running thread - @param rc the wait operation return code -*/ -typedef void (*end_rwlock_rdwait_v1_t) - (struct PSI_rwlock_locker *locker, int rc); - -/** - Record a rwlock instrumentation write wait start event. - @param locker a thread locker for the running thread - @param must must block: 1 for lock, 0 for trylock -*/ -typedef struct PSI_rwlock_locker* (*start_rwlock_wrwait_v1_t) - (struct PSI_rwlock_locker_state_v1 *state, - struct PSI_rwlock *rwlock, - enum PSI_rwlock_operation op, - const char *src_file, uint src_line); - -/** - Record a rwlock instrumentation write wait end event. - @param locker a thread locker for the running thread - @param rc the wait operation return code -*/ -typedef void (*end_rwlock_wrwait_v1_t) - (struct PSI_rwlock_locker *locker, int rc); - -/** - Record a condition instrumentation wait start event. - @param locker a thread locker for the running thread - @param must must block: 1 for wait, 0 for timedwait -*/ -typedef struct PSI_cond_locker* (*start_cond_wait_v1_t) - (struct PSI_cond_locker_state_v1 *state, - struct PSI_cond *cond, - struct PSI_mutex *mutex, - enum PSI_cond_operation op, - const char *src_file, uint src_line); - -/** - Record a condition instrumentation wait end event. - @param locker a thread locker for the running thread - @param rc the wait operation return code -*/ -typedef void (*end_cond_wait_v1_t) - (struct PSI_cond_locker *locker, int rc); - -/** - Record a table instrumentation io wait start event. - @param locker a table locker for the running thread - @param file the source file name - @param line the source line number -*/ -typedef struct PSI_table_locker* (*start_table_io_wait_v1_t) - (struct PSI_table_locker_state *state, - struct PSI_table *table, - enum PSI_table_io_operation op, - uint index, - const char *src_file, uint src_line); - -/** - Record a table instrumentation io wait end event. - @param locker a table locker for the running thread - @param numrows the number of rows involved in io -*/ -typedef void (*end_table_io_wait_v1_t) - (struct PSI_table_locker *locker, - ulonglong numrows); - -/** - Record a table instrumentation lock wait start event. - @param locker a table locker for the running thread - @param file the source file name - @param line the source line number -*/ -typedef struct PSI_table_locker* (*start_table_lock_wait_v1_t) - (struct PSI_table_locker_state *state, - struct PSI_table *table, - enum PSI_table_lock_operation op, - ulong flags, - const char *src_file, uint src_line); - -/** - Record a table instrumentation lock wait end event. - @param locker a table locker for the running thread -*/ -typedef void (*end_table_lock_wait_v1_t)(struct PSI_table_locker *locker); - -typedef void (*unlock_table_v1_t)(struct PSI_table *table); - -/** - Start a file instrumentation open operation. - @param locker the file locker - @param op the operation to perform - @param src_file the source file name - @param src_line the source line number -*/ -typedef void (*start_file_open_wait_v1_t) - (struct PSI_file_locker *locker, const char *src_file, uint src_line); - -/** - End a file instrumentation open operation, for file streams. - @param locker the file locker. - @param result the opened file (NULL indicates failure, non NULL success). - @return an instrumented file handle -*/ -typedef struct PSI_file* (*end_file_open_wait_v1_t) - (struct PSI_file_locker *locker, void *result); - -/** - End a file instrumentation open operation, for non stream files. - @param locker the file locker. - @param file the file number assigned by open() or create() for this file. -*/ -typedef void (*end_file_open_wait_and_bind_to_descriptor_v1_t) - (struct PSI_file_locker *locker, File file); - -/** - End a file instrumentation open operation, for non stream temporary files. - @param locker the file locker. - @param file the file number assigned by open() or create() for this file. - @param filename the file name generated during temporary file creation. -*/ -typedef void (*end_temp_file_open_wait_and_bind_to_descriptor_v1_t) - (struct PSI_file_locker *locker, File file, const char *filename); - -/** - Record a file instrumentation start event. - @param locker a file locker for the running thread - @param op file operation to be performed - @param count the number of bytes requested, or 0 if not applicable - @param src_file the source file name - @param src_line the source line number -*/ -typedef void (*start_file_wait_v1_t) - (struct PSI_file_locker *locker, size_t count, - const char *src_file, uint src_line); - -/** - Record a file instrumentation end event. - Note that for file close operations, the instrumented file handle - associated with the file (which was provided to obtain a locker) - is invalid after this call. - @param locker a file locker for the running thread - @param count the number of bytes actually used in the operation, - or 0 if not applicable, or -1 if the operation failed - @sa get_thread_file_name_locker - @sa get_thread_file_stream_locker - @sa get_thread_file_descriptor_locker -*/ -typedef void (*end_file_wait_v1_t) - (struct PSI_file_locker *locker, size_t count); - -/** - Start a file instrumentation close operation. - @param locker the file locker - @param op the operation to perform - @param src_file the source file name - @param src_line the source line number -*/ -typedef void (*start_file_close_wait_v1_t) - (struct PSI_file_locker *locker, const char *src_file, uint src_line); - -/** - End a file instrumentation close operation. - @param locker the file locker. - @param rc the close operation return code (0 for success). - @return an instrumented file handle -*/ -typedef void (*end_file_close_wait_v1_t) - (struct PSI_file_locker *locker, int rc); - -/** - Rename a file instrumentation close operation. - @param locker the file locker. - @param old_name name of the file to be renamed. - @param new_name name of the file after rename. - @param rc the rename operation return code (0 for success). -*/ -typedef void (*end_file_rename_wait_v1_t) - (struct PSI_file_locker *locker, const char *old_name, - const char *new_name, int rc); - -/** - Start a new stage, and implicitly end the previous stage. - @param key the key of the new stage - @param src_file the source file name - @param src_line the source line number - @return the new stage progress -*/ -typedef PSI_stage_progress* (*start_stage_v1_t) - (PSI_stage_key key, const char *src_file, int src_line); - -typedef PSI_stage_progress* (*get_current_stage_progress_v1_t)(void); - -/** End the current stage. */ -typedef void (*end_stage_v1_t) (void); - -/** - Get a statement instrumentation locker. - @param state data storage for the locker - @param key the statement instrumentation key - @param charset client character set - @return a statement locker, or NULL -*/ -typedef struct PSI_statement_locker* (*get_thread_statement_locker_v1_t) - (struct PSI_statement_locker_state_v1 *state, - PSI_statement_key key, const void *charset, PSI_sp_share *sp_share); - -/** - Refine a statement locker to a more specific key. - Note that only events declared mutable can be refined. - @param the statement locker for the current event - @param key the new key for the event - @sa PSI_FLAG_MUTABLE -*/ -typedef struct PSI_statement_locker* (*refine_statement_v1_t) - (struct PSI_statement_locker *locker, - PSI_statement_key key); - -/** - Start a new statement event. - @param locker the statement locker for this event - @param db the active database name for this statement - @param db_length the active database name length for this statement - @param src_file source file name - @param src_line source line number -*/ -typedef void (*start_statement_v1_t) - (struct PSI_statement_locker *locker, - const char *db, uint db_length, - const char *src_file, uint src_line); - -/** - Set the statement text for a statement event. - @param locker the current statement locker - @param text the statement text - @param text_len the statement text length -*/ -typedef void (*set_statement_text_v1_t) - (struct PSI_statement_locker *locker, - const char *text, uint text_len); - -/** - Set a statement event lock time. - @param locker the statement locker - @param lock_time the locked time, in microseconds -*/ -typedef void (*set_statement_lock_time_t) - (struct PSI_statement_locker *locker, ulonglong lock_time); - -/** - Set a statement event rows sent metric. - @param locker the statement locker - @param count the number of rows sent -*/ -typedef void (*set_statement_rows_sent_t) - (struct PSI_statement_locker *locker, ulonglong count); - -/** - Set a statement event rows examined metric. - @param locker the statement locker - @param count the number of rows examined -*/ -typedef void (*set_statement_rows_examined_t) - (struct PSI_statement_locker *locker, ulonglong count); - -/** - Increment a statement event "created tmp disk tables" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_created_tmp_disk_tables_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "created tmp tables" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_created_tmp_tables_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "select full join" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_select_full_join_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "select full range join" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_select_full_range_join_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "select range join" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_select_range_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "select range check" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_select_range_check_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "select scan" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_select_scan_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "sort merge passes" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_sort_merge_passes_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "sort range" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_sort_range_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "sort rows" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_sort_rows_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Increment a statement event "sort scan" metric. - @param locker the statement locker - @param count the metric increment value -*/ -typedef void (*inc_statement_sort_scan_t) - (struct PSI_statement_locker *locker, ulong count); - -/** - Set a statement event "no index used" metric. - @param locker the statement locker - @param count the metric value -*/ -typedef void (*set_statement_no_index_used_t) - (struct PSI_statement_locker *locker); - -/** - Set a statement event "no good index used" metric. - @param locker the statement locker - @param count the metric value -*/ -typedef void (*set_statement_no_good_index_used_t) - (struct PSI_statement_locker *locker); - -/** - End a statement event. - @param locker the statement locker - @param stmt_da the statement diagnostics area. - @sa Diagnostics_area -*/ -typedef void (*end_statement_v1_t) - (struct PSI_statement_locker *locker, void *stmt_da); - -/** - Get a transaction instrumentation locker. - @param state data storage for the locker - @param xid the xid for this transaction - @param trxid the InnoDB transaction id - @param iso_level isolation level for this transaction - @param read_only true if transaction access mode is read-only - @param autocommit true if transaction is autocommit - @return a transaction locker, or NULL -*/ -typedef struct PSI_transaction_locker* (*get_thread_transaction_locker_v1_t) - (struct PSI_transaction_locker_state_v1 *state, const void *xid, - ulonglong trxid, int isolation_level, my_bool read_only, - my_bool autocommit); - -/** - Start a new transaction event. - @param locker the transaction locker for this event - @param src_file source file name - @param src_line source line number -*/ -typedef void (*start_transaction_v1_t) - (struct PSI_transaction_locker *locker, - const char *src_file, uint src_line); - -/** - Set the transaction xid. - @param locker the transaction locker for this event - @param xid the id of the XA transaction - #param xa_state is the state of the XA transaction -*/ -typedef void (*set_transaction_xid_v1_t) - (struct PSI_transaction_locker *locker, - const void *xid, int xa_state); - -/** - Set the state of the XA transaction. - @param locker the transaction locker for this event - @param xa_state the new state of the xa transaction -*/ -typedef void (*set_transaction_xa_state_v1_t) - (struct PSI_transaction_locker *locker, - int xa_state); - -/** - Set the transaction gtid. - @param locker the transaction locker for this event - @param sid the source id for the transaction, mapped from sidno - @param gtid_spec the gtid specifier for the transaction -*/ -typedef void (*set_transaction_gtid_v1_t) - (struct PSI_transaction_locker *locker, - const void *sid, const void *gtid_spec); - -/** - Set the transaction trx_id. - @param locker the transaction locker for this event - @param trxid the storage engine transaction ID -*/ -typedef void (*set_transaction_trxid_v1_t) - (struct PSI_transaction_locker *locker, - const ulonglong *trxid); - -/** - Increment a transaction event savepoint count. - @param locker the transaction locker - @param count the increment value -*/ -typedef void (*inc_transaction_savepoints_v1_t) - (struct PSI_transaction_locker *locker, ulong count); - -/** - Increment a transaction event rollback to savepoint count. - @param locker the transaction locker - @param count the increment value -*/ -typedef void (*inc_transaction_rollback_to_savepoint_v1_t) - (struct PSI_transaction_locker *locker, ulong count); - -/** - Increment a transaction event release savepoint count. - @param locker the transaction locker - @param count the increment value -*/ -typedef void (*inc_transaction_release_savepoint_v1_t) - (struct PSI_transaction_locker *locker, ulong count); - -/** - Commit or rollback the transaction. - @param locker the transaction locker for this event - @param commit true if transaction was committed, false if rolled back -*/ -typedef void (*end_transaction_v1_t) - (struct PSI_transaction_locker *locker, - my_bool commit); - -/** - Record a socket instrumentation start event. - @param locker a socket locker for the running thread - @param op socket operation to be performed - @param count the number of bytes requested, or 0 if not applicable - @param src_file the source file name - @param src_line the source line number -*/ -typedef struct PSI_socket_locker* (*start_socket_wait_v1_t) - (struct PSI_socket_locker_state_v1 *state, - struct PSI_socket *socket, - enum PSI_socket_operation op, - size_t count, - const char *src_file, uint src_line); - -/** - Record a socket instrumentation end event. - Note that for socket close operations, the instrumented socket handle - associated with the socket (which was provided to obtain a locker) - is invalid after this call. - @param locker a socket locker for the running thread - @param count the number of bytes actually used in the operation, - or 0 if not applicable, or -1 if the operation failed - @sa get_thread_socket_locker -*/ -typedef void (*end_socket_wait_v1_t) - (struct PSI_socket_locker *locker, size_t count); - -/** - Set the socket state for an instrumented socket. - @param socket the instrumented socket - @param state socket state - */ -typedef void (*set_socket_state_v1_t)(struct PSI_socket *socket, - enum PSI_socket_state state); - -/** - Set the socket info for an instrumented socket. - @param socket the instrumented socket - @param fd the socket descriptor - @param addr the socket ip address - @param addr_len length of socket ip address - @param thread_id associated thread id -*/ -typedef void (*set_socket_info_v1_t)(struct PSI_socket *socket, - const my_socket *fd, - const struct sockaddr *addr, - socklen_t addr_len); - -/** - Bind a socket to the thread that owns it. - @param socket instrumented socket -*/ -typedef void (*set_socket_thread_owner_v1_t)(struct PSI_socket *socket); - -/** - Get a prepare statement. - @param locker a statement locker for the running thread. -*/ -typedef PSI_prepared_stmt* (*create_prepared_stmt_v1_t) - (void *identity, uint stmt_id, PSI_statement_locker *locker, - const char *stmt_name, size_t stmt_name_length); - -/** - destroy a prepare statement. - @param prepared_stmt prepared statement. -*/ -typedef void (*destroy_prepared_stmt_v1_t) - (PSI_prepared_stmt *prepared_stmt); - -/** - repreare a prepare statement. - @param prepared_stmt prepared statement. -*/ -typedef void (*reprepare_prepared_stmt_v1_t) - (PSI_prepared_stmt *prepared_stmt); - -/** - Record a prepare statement instrumentation execute event. - @param locker a statement locker for the running thread. - @param prepared_stmt prepared statement. -*/ -typedef void (*execute_prepared_stmt_v1_t) - (PSI_statement_locker *locker, PSI_prepared_stmt* prepared_stmt); - -/** - Set the statement text for a prepared statment event. - @param prepared_stmt prepared statement. - @param text the prepared statement text - @param text_len the prepared statement text length -*/ -typedef void (*set_prepared_stmt_text_v1_t)(PSI_prepared_stmt *prepared_stmt, - const char *text, - uint text_len); -/** - Get a digest locker for the current statement. - @param locker a statement locker for the running thread -*/ -typedef struct PSI_digest_locker * (*digest_start_v1_t) - (struct PSI_statement_locker *locker); - -/** - Add a token to the current digest instrumentation. - @param locker a digest locker for the current statement - @param token the lexical token to add - @param yylval the lexical token attributes -*/ -typedef void (*digest_end_v1_t) - (struct PSI_digest_locker *locker, const struct sql_digest_storage *digest); - -typedef PSI_sp_locker* (*start_sp_v1_t) - (struct PSI_sp_locker_state_v1 *state, struct PSI_sp_share* sp_share); - -typedef void (*end_sp_v1_t) - (struct PSI_sp_locker *locker); - -typedef void (*drop_sp_v1_t) - (uint object_type, - const char *schema_name, uint schema_name_length, - const char *object_name, uint object_name_length); - -/** - Acquire a sp share instrumentation. - @param type of stored program - @param schema name of stored program - @param name of stored program - @return a stored program share instrumentation, or NULL -*/ -typedef struct PSI_sp_share* (*get_sp_share_v1_t) - (uint object_type, - const char *schema_name, uint schema_name_length, - const char *object_name, uint object_name_length); - -/** - Release a stored program share. - @param info the stored program share to release -*/ -typedef void (*release_sp_share_v1_t)(struct PSI_sp_share *share); - -typedef PSI_metadata_lock* (*create_metadata_lock_v1_t) - (void *identity, - const MDL_key *key, - opaque_mdl_type mdl_type, - opaque_mdl_duration mdl_duration, - opaque_mdl_status mdl_status, - const char *src_file, - uint src_line); - -typedef void (*set_metadata_lock_status_v1_t)(PSI_metadata_lock *lock, - opaque_mdl_status mdl_status); - -typedef void (*destroy_metadata_lock_v1_t)(PSI_metadata_lock *lock); - -typedef struct PSI_metadata_locker* (*start_metadata_wait_v1_t) - (struct PSI_metadata_locker_state_v1 *state, - struct PSI_metadata_lock *mdl, - const char *src_file, uint src_line); - -typedef void (*end_metadata_wait_v1_t) - (struct PSI_metadata_locker *locker, int rc); - -/** - Stores an array of connection attributes - @param buffer char array of length encoded connection attributes - in network format - @param length length of the data in buffer - @param from_cs charset in which @c buffer is encoded - @return state - @retval non_0 attributes truncated - @retval 0 stored the attribute -*/ -typedef int (*set_thread_connect_attrs_v1_t)(const char *buffer, uint length, - const void *from_cs); - -/** - Performance Schema Interface, version 1. - @since PSI_VERSION_1 -*/ -struct PSI_v1 -{ - /** @sa register_mutex_v1_t. */ - register_mutex_v1_t register_mutex; - /** @sa register_rwlock_v1_t. */ - register_rwlock_v1_t register_rwlock; - /** @sa register_cond_v1_t. */ - register_cond_v1_t register_cond; - /** @sa register_thread_v1_t. */ - register_thread_v1_t register_thread; - /** @sa register_file_v1_t. */ - register_file_v1_t register_file; - /** @sa register_stage_v1_t. */ - register_stage_v1_t register_stage; - /** @sa register_statement_v1_t. */ - register_statement_v1_t register_statement; - /** @sa register_socket_v1_t. */ - register_socket_v1_t register_socket; - /** @sa init_mutex_v1_t. */ - init_mutex_v1_t init_mutex; - /** @sa destroy_mutex_v1_t. */ - destroy_mutex_v1_t destroy_mutex; - /** @sa init_rwlock_v1_t. */ - init_rwlock_v1_t init_rwlock; - /** @sa destroy_rwlock_v1_t. */ - destroy_rwlock_v1_t destroy_rwlock; - /** @sa init_cond_v1_t. */ - init_cond_v1_t init_cond; - /** @sa destroy_cond_v1_t. */ - destroy_cond_v1_t destroy_cond; - /** @sa init_socket_v1_t. */ - init_socket_v1_t init_socket; - /** @sa destroy_socket_v1_t. */ - destroy_socket_v1_t destroy_socket; - - /** @sa get_table_share_v1_t. */ - get_table_share_v1_t get_table_share; - /** @sa release_table_share_v1_t. */ - release_table_share_v1_t release_table_share; - /** @sa drop_table_share_v1_t. */ - drop_table_share_v1_t drop_table_share; - /** @sa open_table_v1_t. */ - open_table_v1_t open_table; - /** @sa unbind_table_v1_t. */ - unbind_table_v1_t unbind_table; - /** @sa rebind_table_v1_t. */ - rebind_table_v1_t rebind_table; - /** @sa close_table_v1_t. */ - close_table_v1_t close_table; - /** @sa create_file_v1_t. */ - create_file_v1_t create_file; - /** @sa spawn_thread_v1_t. */ - spawn_thread_v1_t spawn_thread; - /** @sa new_thread_v1_t. */ - new_thread_v1_t new_thread; - /** @sa set_thread_id_v1_t. */ - set_thread_id_v1_t set_thread_id; - /** @sa set_thread_THD_v1_t. */ - set_thread_THD_v1_t set_thread_THD; - /** @sa set_thread_os_id_v1_t. */ - set_thread_os_id_v1_t set_thread_os_id; - /** @sa get_thread_v1_t. */ - get_thread_v1_t get_thread; - /** @sa set_thread_user_v1_t. */ - set_thread_user_v1_t set_thread_user; - /** @sa set_thread_account_v1_t. */ - set_thread_account_v1_t set_thread_account; - /** @sa set_thread_db_v1_t. */ - set_thread_db_v1_t set_thread_db; - /** @sa set_thread_command_v1_t. */ - set_thread_command_v1_t set_thread_command; - /** @sa set_connection_type_v1_t. */ - set_connection_type_v1_t set_connection_type; - /** @sa set_thread_start_time_v1_t. */ - set_thread_start_time_v1_t set_thread_start_time; - /** @sa set_thread_state_v1_t. */ - set_thread_state_v1_t set_thread_state; - /** @sa set_thread_info_v1_t. */ - set_thread_info_v1_t set_thread_info; - /** @sa set_thread_v1_t. */ - set_thread_v1_t set_thread; - /** @sa delete_current_thread_v1_t. */ - delete_current_thread_v1_t delete_current_thread; - /** @sa delete_thread_v1_t. */ - delete_thread_v1_t delete_thread; - /** @sa get_thread_file_name_locker_v1_t. */ - get_thread_file_name_locker_v1_t get_thread_file_name_locker; - /** @sa get_thread_file_stream_locker_v1_t. */ - get_thread_file_stream_locker_v1_t get_thread_file_stream_locker; - /** @sa get_thread_file_descriptor_locker_v1_t. */ - get_thread_file_descriptor_locker_v1_t get_thread_file_descriptor_locker; - /** @sa unlock_mutex_v1_t. */ - unlock_mutex_v1_t unlock_mutex; - /** @sa unlock_rwlock_v1_t. */ - unlock_rwlock_v1_t unlock_rwlock; - /** @sa signal_cond_v1_t. */ - signal_cond_v1_t signal_cond; - /** @sa broadcast_cond_v1_t. */ - broadcast_cond_v1_t broadcast_cond; - /** @sa start_idle_wait_v1_t. */ - start_idle_wait_v1_t start_idle_wait; - /** @sa end_idle_wait_v1_t. */ - end_idle_wait_v1_t end_idle_wait; - /** @sa start_mutex_wait_v1_t. */ - start_mutex_wait_v1_t start_mutex_wait; - /** @sa end_mutex_wait_v1_t. */ - end_mutex_wait_v1_t end_mutex_wait; - /** @sa start_rwlock_rdwait_v1_t. */ - start_rwlock_rdwait_v1_t start_rwlock_rdwait; - /** @sa end_rwlock_rdwait_v1_t. */ - end_rwlock_rdwait_v1_t end_rwlock_rdwait; - /** @sa start_rwlock_wrwait_v1_t. */ - start_rwlock_wrwait_v1_t start_rwlock_wrwait; - /** @sa end_rwlock_wrwait_v1_t. */ - end_rwlock_wrwait_v1_t end_rwlock_wrwait; - /** @sa start_cond_wait_v1_t. */ - start_cond_wait_v1_t start_cond_wait; - /** @sa end_cond_wait_v1_t. */ - end_cond_wait_v1_t end_cond_wait; - /** @sa start_table_io_wait_v1_t. */ - start_table_io_wait_v1_t start_table_io_wait; - /** @sa end_table_io_wait_v1_t. */ - end_table_io_wait_v1_t end_table_io_wait; - /** @sa start_table_lock_wait_v1_t. */ - start_table_lock_wait_v1_t start_table_lock_wait; - /** @sa end_table_lock_wait_v1_t. */ - end_table_lock_wait_v1_t end_table_lock_wait; - /** @sa start_file_open_wait_v1_t. */ - start_file_open_wait_v1_t start_file_open_wait; - /** @sa end_file_open_wait_v1_t. */ - end_file_open_wait_v1_t end_file_open_wait; - /** @sa end_file_open_wait_and_bind_to_descriptor_v1_t. */ - end_file_open_wait_and_bind_to_descriptor_v1_t - end_file_open_wait_and_bind_to_descriptor; - /** @sa end_temp_file_open_wait_and_bind_to_descriptor_v1_t. */ - end_temp_file_open_wait_and_bind_to_descriptor_v1_t - end_temp_file_open_wait_and_bind_to_descriptor; - /** @sa start_file_wait_v1_t. */ - start_file_wait_v1_t start_file_wait; - /** @sa end_file_wait_v1_t. */ - end_file_wait_v1_t end_file_wait; - /** @sa start_file_close_wait_v1_t. */ - start_file_close_wait_v1_t start_file_close_wait; - /** @sa end_file_close_wait_v1_t. */ - end_file_close_wait_v1_t end_file_close_wait; - /** @sa rename_file_close_wait_v1_t. */ - end_file_rename_wait_v1_t end_file_rename_wait; - /** @sa start_stage_v1_t. */ - start_stage_v1_t start_stage; - /** @sa get_current_stage_progress_v1_t. */ - get_current_stage_progress_v1_t get_current_stage_progress; - /** @sa end_stage_v1_t. */ - end_stage_v1_t end_stage; - /** @sa get_thread_statement_locker_v1_t. */ - get_thread_statement_locker_v1_t get_thread_statement_locker; - /** @sa refine_statement_v1_t. */ - refine_statement_v1_t refine_statement; - /** @sa start_statement_v1_t. */ - start_statement_v1_t start_statement; - /** @sa set_statement_text_v1_t. */ - set_statement_text_v1_t set_statement_text; - /** @sa set_statement_lock_time_t. */ - set_statement_lock_time_t set_statement_lock_time; - /** @sa set_statement_rows_sent_t. */ - set_statement_rows_sent_t set_statement_rows_sent; - /** @sa set_statement_rows_examined_t. */ - set_statement_rows_examined_t set_statement_rows_examined; - /** @sa inc_statement_created_tmp_disk_tables. */ - inc_statement_created_tmp_disk_tables_t inc_statement_created_tmp_disk_tables; - /** @sa inc_statement_created_tmp_tables. */ - inc_statement_created_tmp_tables_t inc_statement_created_tmp_tables; - /** @sa inc_statement_select_full_join. */ - inc_statement_select_full_join_t inc_statement_select_full_join; - /** @sa inc_statement_select_full_range_join. */ - inc_statement_select_full_range_join_t inc_statement_select_full_range_join; - /** @sa inc_statement_select_range. */ - inc_statement_select_range_t inc_statement_select_range; - /** @sa inc_statement_select_range_check. */ - inc_statement_select_range_check_t inc_statement_select_range_check; - /** @sa inc_statement_select_scan. */ - inc_statement_select_scan_t inc_statement_select_scan; - /** @sa inc_statement_sort_merge_passes. */ - inc_statement_sort_merge_passes_t inc_statement_sort_merge_passes; - /** @sa inc_statement_sort_range. */ - inc_statement_sort_range_t inc_statement_sort_range; - /** @sa inc_statement_sort_rows. */ - inc_statement_sort_rows_t inc_statement_sort_rows; - /** @sa inc_statement_sort_scan. */ - inc_statement_sort_scan_t inc_statement_sort_scan; - /** @sa set_statement_no_index_used. */ - set_statement_no_index_used_t set_statement_no_index_used; - /** @sa set_statement_no_good_index_used. */ - set_statement_no_good_index_used_t set_statement_no_good_index_used; - /** @sa end_statement_v1_t. */ - end_statement_v1_t end_statement; - /** @sa get_thread_transaction_locker_v1_t. */ - get_thread_transaction_locker_v1_t get_thread_transaction_locker; - /** @sa start_transaction_v1_t. */ - start_transaction_v1_t start_transaction; - /** @sa set_transaction_xid_v1_t. */ - set_transaction_xid_v1_t set_transaction_xid; - /** @sa set_transaction_xa_state_v1_t. */ - set_transaction_xa_state_v1_t set_transaction_xa_state; - /** @sa set_transaction_gtid_v1_t. */ - set_transaction_gtid_v1_t set_transaction_gtid; - /** @sa set_transaction_trxid_v1_t. */ - set_transaction_trxid_v1_t set_transaction_trxid; - /** @sa inc_transaction_savepoints_v1_t. */ - inc_transaction_savepoints_v1_t inc_transaction_savepoints; - /** @sa inc_transaction_rollback_to_savepoint_v1_t. */ - inc_transaction_rollback_to_savepoint_v1_t inc_transaction_rollback_to_savepoint; - /** @sa inc_transaction_release_savepoint_v1_t. */ - inc_transaction_release_savepoint_v1_t inc_transaction_release_savepoint; - /** @sa end_transaction_v1_t. */ - end_transaction_v1_t end_transaction; - /** @sa start_socket_wait_v1_t. */ - start_socket_wait_v1_t start_socket_wait; - /** @sa end_socket_wait_v1_t. */ - end_socket_wait_v1_t end_socket_wait; - /** @sa set_socket_state_v1_t. */ - set_socket_state_v1_t set_socket_state; - /** @sa set_socket_info_v1_t. */ - set_socket_info_v1_t set_socket_info; - /** @sa set_socket_thread_owner_v1_t. */ - set_socket_thread_owner_v1_t set_socket_thread_owner; - /** @sa create_prepared_stmt_v1_t. */ - create_prepared_stmt_v1_t create_prepared_stmt; - /** @sa destroy_prepared_stmt_v1_t. */ - destroy_prepared_stmt_v1_t destroy_prepared_stmt; - /** @sa reprepare_prepared_stmt_v1_t. */ - reprepare_prepared_stmt_v1_t reprepare_prepared_stmt; - /** @sa execute_prepared_stmt_v1_t. */ - execute_prepared_stmt_v1_t execute_prepared_stmt; - /** @sa set_prepared_stmt_text_v1_t. */ - set_prepared_stmt_text_v1_t set_prepared_stmt_text; - /** @sa digest_start_v1_t. */ - digest_start_v1_t digest_start; - /** @sa digest_end_v1_t. */ - digest_end_v1_t digest_end; - /** @sa set_thread_connect_attrs_v1_t. */ - set_thread_connect_attrs_v1_t set_thread_connect_attrs; - /** @sa start_sp_v1_t. */ - start_sp_v1_t start_sp; - /** @sa start_sp_v1_t. */ - end_sp_v1_t end_sp; - /** @sa drop_sp_v1_t. */ - drop_sp_v1_t drop_sp; - /** @sa get_sp_share_v1_t. */ - get_sp_share_v1_t get_sp_share; - /** @sa release_sp_share_v1_t. */ - release_sp_share_v1_t release_sp_share; - /** @sa register_memory_v1_t. */ - register_memory_v1_t register_memory; - /** @sa memory_alloc_v1_t. */ - memory_alloc_v1_t memory_alloc; - /** @sa memory_realloc_v1_t. */ - memory_realloc_v1_t memory_realloc; - /** @sa memory_claim_v1_t. */ - memory_claim_v1_t memory_claim; - /** @sa memory_free_v1_t. */ - memory_free_v1_t memory_free; - - unlock_table_v1_t unlock_table; - - create_metadata_lock_v1_t create_metadata_lock; - set_metadata_lock_status_v1_t set_metadata_lock_status; - destroy_metadata_lock_v1_t destroy_metadata_lock; - - start_metadata_wait_v1_t start_metadata_wait; - end_metadata_wait_v1_t end_metadata_wait; -}; - -/** @} (end of group Group_PSI_v1) */ - -#endif /* HAVE_PSI_1 */ - -#ifdef USE_PSI_2 -#define HAVE_PSI_2 -#endif - -#ifdef HAVE_PSI_2 - -/** - @defgroup Group_PSI_v2 Application Binary Interface, version 2 - @ingroup Instrumentation_interface - @{ -*/ - -/** - Performance Schema Interface, version 2. - This is a placeholder, this interface is not defined yet. - @since PSI_VERSION_2 -*/ -struct PSI_v2 -{ - /** Placeholder */ - int placeholder; - /* ... extended interface ... */ -}; - -/** Placeholder */ -struct PSI_mutex_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_rwlock_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_cond_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_thread_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_file_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_stage_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_statement_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_transaction_info_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_idle_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_mutex_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_rwlock_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_cond_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_file_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_statement_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_transaction_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -/** Placeholder */ -struct PSI_socket_locker_state_v2 -{ - /** Placeholder */ - int placeholder; -}; - -struct PSI_metadata_locker_state_v2 -{ - int placeholder; -}; - -/** @} (end of group Group_PSI_v2) */ - -#endif /* HAVE_PSI_2 */ - -/** - @typedef PSI - The instrumentation interface for the current version. - @sa PSI_CURRENT_VERSION -*/ - -/** - @typedef PSI_mutex_info - The mutex information structure for the current version. -*/ - -/** - @typedef PSI_rwlock_info - The rwlock information structure for the current version. -*/ - -/** - @typedef PSI_cond_info - The cond information structure for the current version. -*/ - -/** - @typedef PSI_thread_info - The thread information structure for the current version. -*/ - -/** - @typedef PSI_file_info - The file information structure for the current version. -*/ - -/* Export the required version */ -#ifdef USE_PSI_1 -typedef struct PSI_v1 PSI; -typedef struct PSI_mutex_info_v1 PSI_mutex_info; -typedef struct PSI_rwlock_info_v1 PSI_rwlock_info; -typedef struct PSI_cond_info_v1 PSI_cond_info; -typedef struct PSI_thread_info_v1 PSI_thread_info; -typedef struct PSI_file_info_v1 PSI_file_info; -typedef struct PSI_stage_info_v1 PSI_stage_info; -typedef struct PSI_statement_info_v1 PSI_statement_info; -typedef struct PSI_transaction_info_v1 PSI_transaction_info; -typedef struct PSI_socket_info_v1 PSI_socket_info; -typedef struct PSI_idle_locker_state_v1 PSI_idle_locker_state; -typedef struct PSI_mutex_locker_state_v1 PSI_mutex_locker_state; -typedef struct PSI_rwlock_locker_state_v1 PSI_rwlock_locker_state; -typedef struct PSI_cond_locker_state_v1 PSI_cond_locker_state; -typedef struct PSI_file_locker_state_v1 PSI_file_locker_state; -typedef struct PSI_statement_locker_state_v1 PSI_statement_locker_state; -typedef struct PSI_transaction_locker_state_v1 PSI_transaction_locker_state; -typedef struct PSI_socket_locker_state_v1 PSI_socket_locker_state; -typedef struct PSI_sp_locker_state_v1 PSI_sp_locker_state; -typedef struct PSI_metadata_locker_state_v1 PSI_metadata_locker_state; -#endif - -#ifdef USE_PSI_2 -typedef struct PSI_v2 PSI; -typedef struct PSI_mutex_info_v2 PSI_mutex_info; -typedef struct PSI_rwlock_info_v2 PSI_rwlock_info; -typedef struct PSI_cond_info_v2 PSI_cond_info; -typedef struct PSI_thread_info_v2 PSI_thread_info; -typedef struct PSI_file_info_v2 PSI_file_info; -typedef struct PSI_stage_info_v2 PSI_stage_info; -typedef struct PSI_statement_info_v2 PSI_statement_info; -typedef struct PSI_transaction_info_v2 PSI_transaction_info; -typedef struct PSI_socket_info_v2 PSI_socket_info; -typedef struct PSI_idle_locker_state_v2 PSI_idle_locker_state; -typedef struct PSI_mutex_locker_state_v2 PSI_mutex_locker_state; -typedef struct PSI_rwlock_locker_state_v2 PSI_rwlock_locker_state; -typedef struct PSI_cond_locker_state_v2 PSI_cond_locker_state; -typedef struct PSI_file_locker_state_v2 PSI_file_locker_state; -typedef struct PSI_statement_locker_state_v2 PSI_statement_locker_state; -typedef struct PSI_transaction_locker_state_v2 PSI_transaction_locker_state; -typedef struct PSI_socket_locker_state_v2 PSI_socket_locker_state; -typedef struct PSI_sp_locker_state_v2 PSI_sp_locker_state; -typedef struct PSI_metadata_locker_state_v2 PSI_metadata_locker_state; -#endif - -#ifndef HAVE_PSI_INTERFACE - -/** - Dummy structure, used to declare PSI_server when no instrumentation - is available. - The content does not matter, since PSI_server will be NULL. -*/ -struct PSI_none -{ - int opaque; -}; -typedef struct PSI_none PSI; - -/** - Stage instrument information. - @since PSI_VERSION_1 - This structure is used to register an instrumented stage. -*/ -struct PSI_stage_info_none -{ - /** Unused stage key. */ - unsigned int m_key; - /** The name of the stage instrument. */ - const char *m_name; - /** Unused stage flags. */ - int m_flags; -}; - -/** - The stage instrumentation has to co exist with the legacy - THD::set_proc_info instrumentation. - To avoid duplication of the instrumentation in the server, - the common PSI_stage_info structure is used, - so we export it here, even when not building - with HAVE_PSI_INTERFACE. -*/ -typedef struct PSI_stage_info_none PSI_stage_info; -typedef struct PSI_stage_info_none PSI_statement_info; -typedef struct PSI_stage_info_none PSI_sp_locker_state; -typedef struct PSI_stage_info_none PSI_metadata_locker_state; -typedef struct PSI_stage_info_none PSI_metadata_locker; - -#endif /* HAVE_PSI_INTERFACE */ - -extern MYSQL_PLUGIN_IMPORT PSI *PSI_server; - -/* - Allow to override PSI_XXX_CALL at compile time - with more efficient implementations, if available. - If nothing better is available, - make a dynamic call using the PSI_server function pointer. -*/ - -#define PSI_DYNAMIC_CALL(M) PSI_server->M - -/** @} */ - -C_MODE_END -#endif /* MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H */ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v0.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v0.h deleted file mode 100644 index 5c879fb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v0.h +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file mysql/psi/psi_abi_v0.h - ABI check for mysql/psi/psi.h, when compiling without instrumentation. - This file is only used to automate detection of changes between versions. - Do not include this file, include mysql/psi/psi.h instead. -*/ -#define MY_GLOBAL_INCLUDED -#include "mysql/psi/psi.h" - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v1.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v1.h deleted file mode 100644 index 488e832..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v1.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file mysql/psi/psi_abi_v1.h - ABI check for mysql/psi/psi.h, when using PSI_VERSION_1. - This file is only used to automate detection of changes between versions. - Do not include this file, include mysql/psi/psi.h instead. -*/ -#define USE_PSI_1 -#define HAVE_PSI_INTERFACE -#define MY_GLOBAL_INCLUDED -#include "mysql/psi/psi.h" - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v2.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v2.h deleted file mode 100644 index 3495d61..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_abi_v2.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file mysql/psi/psi_abi_v1.h - ABI check for mysql/psi/psi.h, when using PSI_VERSION_2. - This file is only used to automate detection of changes between versions. - Do not include this file, include mysql/psi/psi.h instead. -*/ -#define USE_PSI_2 -#define HAVE_PSI_INTERFACE -#define MY_GLOBAL_INCLUDED -#include "mysql/psi/psi.h" - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_base.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_base.h deleted file mode 100644 index f365e26..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_base.h +++ /dev/null @@ -1,172 +0,0 @@ -/* Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - Without limiting anything contained in the foregoing, this file, - which is part of C Driver for MySQL (Connector/C), is also subject to the - Universal FOSS Exception, version 1.0, a copy of which can be found at - http://oss.oracle.com/licenses/universal-foss-exception. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_PSI_BASE_H -#define MYSQL_PSI_BASE_H - -#ifdef EMBEDDED_LIBRARY -#define DISABLE_ALL_PSI -#endif /* EMBEDDED_LIBRARY */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** - @file mysql/psi/psi_base.h - Performance schema instrumentation interface. - - @defgroup Instrumentation_interface Instrumentation Interface - @ingroup Performance_schema - @{ -*/ - -#define PSI_INSTRUMENT_ME 0 -#define PSI_INSTRUMENT_MEM ((PSI_memory_key)0) - -#define PSI_NOT_INSTRUMENTED 0 - -/** - Global flag. - This flag indicate that an instrumentation point is a global variable, - or a singleton. -*/ -#define PSI_FLAG_GLOBAL (1 << 0) - -/** - Mutable flag. - This flag indicate that an instrumentation point is a general placeholder, - that can mutate into a more specific instrumentation point. -*/ -#define PSI_FLAG_MUTABLE (1 << 1) - -#define PSI_FLAG_THREAD (1 << 2) - -/** - Stage progress flag. - This flag apply to the stage instruments only. - It indicates the instrumentation provides progress data. -*/ -#define PSI_FLAG_STAGE_PROGRESS (1 << 3) - -/** - Shared Exclusive flag. - Indicates that rwlock support the shared exclusive state. -*/ -#define PSI_RWLOCK_FLAG_SX (1 << 4) - -/** - Transferable flag. - This flag indicate that an instrumented object can - be created by a thread and destroyed by another thread. -*/ -#define PSI_FLAG_TRANSFER (1 << 5) - -/** - Volatility flag. - This flag indicate that an instrumented object - has a volatility (life cycle) comparable - to the volatility of a session. -*/ -#define PSI_FLAG_VOLATILITY_SESSION (1 << 6) - -#ifdef HAVE_PSI_INTERFACE - -/** - @def PSI_VERSION_1 - Performance Schema Interface number for version 1. - This version is supported. -*/ -#define PSI_VERSION_1 1 - -/** - @def PSI_VERSION_2 - Performance Schema Interface number for version 2. - This version is not implemented, it's a placeholder. -*/ -#define PSI_VERSION_2 2 - -/** - @def PSI_CURRENT_VERSION - Performance Schema Interface number for the most recent version. - The most current version is @c PSI_VERSION_1 -*/ -#define PSI_CURRENT_VERSION 1 - -/** - @def USE_PSI_1 - Define USE_PSI_1 to use the interface version 1. -*/ - -/** - @def USE_PSI_2 - Define USE_PSI_2 to use the interface version 2. -*/ - -/** - @def HAVE_PSI_1 - Define HAVE_PSI_1 if the interface version 1 needs to be compiled in. -*/ - -/** - @def HAVE_PSI_2 - Define HAVE_PSI_2 if the interface version 2 needs to be compiled in. -*/ - -#ifndef USE_PSI_2 -#ifndef USE_PSI_1 -#define USE_PSI_1 -#endif -#endif - -#ifdef USE_PSI_1 -#define HAVE_PSI_1 -#endif - -#ifdef USE_PSI_2 -#define HAVE_PSI_2 -#endif - -/* - Allow to override PSI_XXX_CALL at compile time - with more efficient implementations, if available. - If nothing better is available, - make a dynamic call using the PSI_server function pointer. -*/ - -#define PSI_DYNAMIC_CALL(M) PSI_server->M - -#endif /* HAVE_PSI_INTERFACE */ - -/** @} */ - -#ifdef __cplusplus -} -#endif - -#endif /* MYSQL_PSI_BASE_H */ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_memory.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_memory.h deleted file mode 100644 index bbe2be3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/psi/psi_memory.h +++ /dev/null @@ -1,167 +0,0 @@ -/* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License, version 2.0, - as published by the Free Software Foundation. - - This program is also distributed with certain software (including - but not limited to OpenSSL) that is licensed under separate terms, - as designated in a particular file or component or in included license - documentation. The authors of MySQL hereby grant you an additional - permission to link the program and your derivative works with the - separately licensed software that they have included with MySQL. - - Without limiting anything contained in the foregoing, this file, - which is part of C Driver for MySQL (Connector/C), is also subject to the - Universal FOSS Exception, version 1.0, a copy of which can be found at - http://oss.oracle.com/licenses/universal-foss-exception. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License, version 2.0, for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_PSI_MEMORY_H -#define MYSQL_PSI_MEMORY_H - -#include "psi_base.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - @file mysql/psi/psi_memory.h - Performance schema instrumentation interface. - - @defgroup Instrumentation_interface Instrumentation Interface - @ingroup Performance_schema - @{ -*/ - -#ifdef HAVE_PSI_INTERFACE -#ifndef DISABLE_ALL_PSI -#ifndef DISABLE_PSI_MEMORY -#define HAVE_PSI_MEMORY_INTERFACE -#endif /* DISABLE_PSI_MEMORY */ -#endif /* DISABLE_ALL_PSI */ -#endif /* HAVE_PSI_INTERFACE */ - -struct PSI_thread; - -/** - Instrumented memory key. - To instrument memory, a memory key must be obtained using @c register_memory. - Using a zero key always disable the instrumentation. -*/ -typedef unsigned int PSI_memory_key; - -#ifdef HAVE_PSI_1 - -/** - @defgroup Group_PSI_v1 Application Binary Interface, version 1 - @ingroup Instrumentation_interface - @{ -*/ - -/** - Memory instrument information. - @since PSI_VERSION_1 - This structure is used to register instrumented memory. -*/ -struct PSI_memory_info_v1 -{ - /** Pointer to the key assigned to the registered memory. */ - PSI_memory_key *m_key; - /** The name of the memory instrument to register. */ - const char *m_name; - /** - The flags of the socket instrument to register. - @sa PSI_FLAG_GLOBAL - */ - int m_flags; -}; -typedef struct PSI_memory_info_v1 PSI_memory_info_v1; - -/** - Memory registration API. - @param category a category name (typically a plugin name) - @param info an array of memory info to register - @param count the size of the info array -*/ -typedef void (*register_memory_v1_t) - (const char *category, struct PSI_memory_info_v1 *info, int count); - -/** - Instrument memory allocation. - @param key the memory instrument key - @param size the size of memory allocated - @param[out] owner the memory owner - @return the effective memory instrument key -*/ -typedef PSI_memory_key (*memory_alloc_v1_t) - (PSI_memory_key key, size_t size, struct PSI_thread ** owner); - -/** - Instrument memory re allocation. - @param key the memory instrument key - @param old_size the size of memory previously allocated - @param new_size the size of memory re allocated - @param[in, out] owner the memory owner - @return the effective memory instrument key -*/ -typedef PSI_memory_key (*memory_realloc_v1_t) - (PSI_memory_key key, size_t old_size, size_t new_size, struct PSI_thread ** owner); - -/** - Instrument memory claim. - @param key the memory instrument key - @param size the size of memory allocated - @param[in, out] owner the memory owner - @return the effective memory instrument key -*/ -typedef PSI_memory_key (*memory_claim_v1_t) - (PSI_memory_key key, size_t size, struct PSI_thread ** owner); - -/** - Instrument memory free. - @param key the memory instrument key - @param size the size of memory allocated - @param owner the memory owner -*/ -typedef void (*memory_free_v1_t) - (PSI_memory_key key, size_t size, struct PSI_thread * owner); - -/** @} (end of group Group_PSI_v1) */ - -#endif /* HAVE_PSI_1 */ - -#ifdef HAVE_PSI_2 -struct PSI_memory_info_v2 -{ - int placeholder; -}; - -#endif /* HAVE_PSI_2 */ - -#ifdef USE_PSI_1 -typedef struct PSI_memory_info_v1 PSI_memory_info; -#endif - -#ifdef USE_PSI_2 -typedef struct PSI_memory_info_v2 PSI_memory_info; -#endif - -/** @} (end of group Instrumentation_interface) */ - -#ifdef __cplusplus -} -#endif - - -#endif /* MYSQL_PSI_MEMORY_H */ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_base64.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_base64.h deleted file mode 100644 index 43b5ba3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_base64.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef MYSQL_SERVICE_BASE64_INCLUDED -/* Copyright (c) 2017, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - my base64 service - - Functions for base64 en- and decoding -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -/* Allow multuple chunks 'AAA= AA== AA==', binlog uses this */ -#define MY_BASE64_DECODE_ALLOW_MULTIPLE_CHUNKS 1 - -extern struct base64_service_st { - int (*base64_needed_encoded_length_ptr)(int length_of_data); - int (*base64_encode_max_arg_length_ptr)(void); - int (*base64_needed_decoded_length_ptr)(int length_of_encoded_data); - int (*base64_decode_max_arg_length_ptr)(); - int (*base64_encode_ptr)(const void *src, size_t src_len, char *dst); - int (*base64_decode_ptr)(const char *src, size_t src_len, - void *dst, const char **end_ptr, int flags); -} *base64_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define my_base64_needed_encoded_length(A) base64_service->base64_needed_encoded_length_ptr(A) -#define my_base64_encode_max_arg_length() base64_service->base64_encode_max_arg_length_ptr() -#define my_base64_needed_decoded_length(A) base64_service->base64_needed_decoded_length_ptr(A) -#define my_base64_decode_max_arg_length() base64_service->base64_decode_max_arg_length_ptr() -#define my_base64_encode(A,B,C) base64_service->base64_encode_ptr(A,B,C) -#define my_base64_decode(A,B,C,D,E) base64_service->base64_decode_ptr(A,B,C,D,E) - -#else - -/* Calculate how much memory needed for dst of my_base64_encode() */ -int my_base64_needed_encoded_length(int length_of_data); - -/* Maximum length my_base64_encode_needed_length() can accept with no overflow. */ -int my_base64_encode_max_arg_length(void); - -/* Calculate how much memory needed for dst of my_base64_decode() */ -int my_base64_needed_decoded_length(int length_of_encoded_data); - -/* Maximum length my_base64_decode_needed_length() can accept with no overflow. */ -int my_base64_decode_max_arg_length(); - -/* Encode data as a my_base64 string */ -int my_base64_encode(const void *src, size_t src_len, char *dst); - -/* Decode a my_base64 string into data */ -int my_base64_decode(const char *src, size_t src_len, - void *dst, const char **end_ptr, int flags); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_BASE64_INCLUDED -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_debug_sync.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_debug_sync.h deleted file mode 100644 index 0bd49a1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_debug_sync.h +++ /dev/null @@ -1,361 +0,0 @@ -#ifndef MYSQL_SERVICE_DEBUG_SYNC_INCLUDED -/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. - Copyright (c) 2012, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - == Debug Sync Facility == - - The Debug Sync Facility allows placement of synchronization points in - the server code by using the DEBUG_SYNC macro: - - open_tables(...) - - DEBUG_SYNC(thd, "after_open_tables"); - - lock_tables(...) - - When activated, a sync point can - - - Emit a signal and/or - - Wait for a signal - - Nomenclature: - - - signal: A value of a global variable that persists - until overwritten by a new signal. The global - variable can also be seen as a "signal post" - or "flag mast". Then the signal is what is - attached to the "signal post" or "flag mast". - - - emit a signal: Assign the value (the signal) to the global - variable ("set a flag") and broadcast a - global condition to wake those waiting for - a signal. - - - wait for a signal: Loop over waiting for the global condition until - the global value matches the wait-for signal. - - By default, all sync points are inactive. They do nothing (except to - burn a couple of CPU cycles for checking if they are active). - - A sync point becomes active when an action is requested for it. - To do so, put a line like this in the test case file: - - SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed'; - - This activates the sync point 'after_open_tables'. It requests it to - emit the signal 'opened' and wait for another thread to emit the signal - 'flushed' when the thread's execution runs through the sync point. - - For every sync point there can be one action per thread only. Every - thread can request multiple actions, but only one per sync point. In - other words, a thread can activate multiple sync points. - - Here is an example how to activate and use the sync points: - - --connection conn1 - SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed'; - send INSERT INTO t1 VALUES(1); - --connection conn2 - SET DEBUG_SYNC= 'now WAIT_FOR opened'; - SET DEBUG_SYNC= 'after_abort_locks SIGNAL flushed'; - FLUSH TABLE t1; - - When conn1 runs through the INSERT statement, it hits the sync point - 'after_open_tables'. It notices that it is active and executes its - action. It emits the signal 'opened' and waits for another thread to - emit the signal 'flushed'. - - conn2 waits immediately at the special sync point 'now' for another - thread to emit the 'opened' signal. - - A signal remains in effect until it is overwritten. If conn1 signals - 'opened' before conn2 reaches 'now', conn2 will still find the 'opened' - signal. It does not wait in this case. - - When conn2 reaches 'after_abort_locks', it signals 'flushed', which lets - conn1 awake. - - Normally the activation of a sync point is cleared when it has been - executed. Sometimes it is necessary to keep the sync point active for - another execution. You can add an execute count to the action: - - SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 3'; - - This sets the signal point's activation counter to 3. Each execution - decrements the counter. After the third execution the sync point - becomes inactive. - - One of the primary goals of this facility is to eliminate sleeps from - the test suite. In most cases it should be possible to rewrite test - cases so that they do not need to sleep. (But this facility cannot - synchronize multiple processes.) However, to support test development, - and as a last resort, sync point waiting times out. There is a default - timeout, but it can be overridden: - - SET DEBUG_SYNC= 'name WAIT_FOR sig TIMEOUT 10 EXECUTE 2'; - - TIMEOUT 0 is special: If the signal is not present, the wait times out - immediately. - - When a wait timed out (even on TIMEOUT 0), a warning is generated so - that it shows up in the test result. - - You can throw an error message and kill the query when a synchronization - point is hit a certain number of times: - - SET DEBUG_SYNC= 'name HIT_LIMIT 3'; - - Or combine it with signal and/or wait: - - SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 2 HIT_LIMIT 3'; - - Here the first two hits emit the signal, the third hit returns the error - message and kills the query. - - For cases where you are not sure that an action is taken and thus - cleared in any case, you can force to clear (deactivate) a sync point: - - SET DEBUG_SYNC= 'name CLEAR'; - - If you want to clear all actions and clear the global signal, use: - - SET DEBUG_SYNC= 'RESET'; - - This is the only way to reset the global signal to an empty string. - - For testing of the facility itself you can execute a sync point just - as if it had been hit: - - SET DEBUG_SYNC= 'name TEST'; - - - === Formal Syntax === - - The string to "assign" to the DEBUG_SYNC variable can contain: - - {RESET | - TEST | - CLEAR | - {{SIGNAL | - WAIT_FOR [TIMEOUT ]} - [EXECUTE ] &| HIT_LIMIT } - - Here '&|' means 'and/or'. This means that one of the sections - separated by '&|' must be present or both of them. - - - === Activation/Deactivation === - - The facility is an optional part of the MySQL server. - It is enabled in a debug server by default. - - ./configure --enable-debug-sync - - The Debug Sync Facility, when compiled in, is disabled by default. It - can be enabled by a mysqld command line option: - - --debug-sync-timeout[=default_wait_timeout_value_in_seconds] - - 'default_wait_timeout_value_in_seconds' is the default timeout for the - WAIT_FOR action. If set to zero, the facility stays disabled. - - The facility is enabled by default in the test suite, but can be - disabled with: - - mysql-test-run.pl ... --debug-sync-timeout=0 ... - - Likewise the default wait timeout can be set: - - mysql-test-run.pl ... --debug-sync-timeout=10 ... - - The command line option influences the readable value of the system - variable 'debug_sync'. - - * If the facility is not compiled in, the system variable does not exist. - - * If --debug-sync-timeout=0 the value of the variable reads as "OFF". - - * Otherwise the value reads as "ON - current signal: " followed by the - current signal string, which can be empty. - - The readable variable value is the same, regardless if read as global - or session value. - - Setting the 'debug-sync' system variable requires 'SUPER' privilege. - You can never read back the string that you assigned to the variable, - unless you assign the value that the variable does already have. But - that would give a parse error. A syntactically correct string is - parsed into a debug sync action and stored apart from the variable value. - - - === Implementation === - - Pseudo code for a sync point: - - #define DEBUG_SYNC(thd, sync_point_name) - if (unlikely(opt_debug_sync_timeout)) - debug_sync(thd, STRING_WITH_LEN(sync_point_name)) - - The sync point performs a binary search in a sorted array of actions - for this thread. - - The SET DEBUG_SYNC statement adds a requested action to the array or - overwrites an existing action for the same sync point. When it adds a - new action, the array is sorted again. - - - === A typical synchronization pattern === - - There are quite a few places in MySQL, where we use a synchronization - pattern like this: - - mysql_mutex_lock(&mutex); - thd->enter_cond(&condition_variable, &mutex, new_message); - #if defined(ENABLE_DEBUG_SYNC) - if (!thd->killed && !end_of_wait_condition) - DEBUG_SYNC(thd, "sync_point_name"); - #endif - while (!thd->killed && !end_of_wait_condition) - mysql_cond_wait(&condition_variable, &mutex); - thd->exit_cond(old_message); - - Here some explanations: - - thd->enter_cond() is used to register the condition variable and the - mutex in thd->mysys_var. This is done to allow the thread to be - interrupted (killed) from its sleep. Another thread can find the - condition variable to signal and mutex to use for synchronization in - this thread's THD::mysys_var. - - thd->enter_cond() requires the mutex to be acquired in advance. - - thd->exit_cond() unregisters the condition variable and mutex and - releases the mutex. - - If you want to have a Debug Sync point with the wait, please place it - behind enter_cond(). Only then you can safely decide, if the wait will - be taken. Also you will have THD::proc_info correct when the sync - point emits a signal. DEBUG_SYNC sets its own proc_info, but restores - the previous one before releasing its internal mutex. As soon as - another thread sees the signal, it does also see the proc_info from - before entering the sync point. In this case it will be "new_message", - which is associated with the wait that is to be synchronized. - - In the example above, the wait condition is repeated before the sync - point. This is done to skip the sync point, if no wait takes place. - The sync point is before the loop (not inside the loop) to have it hit - once only. It is possible that the condition variable is signaled - multiple times without the wait condition to be true. - - A bit off-topic: At some places, the loop is taken around the whole - synchronization pattern: - - while (!thd->killed && !end_of_wait_condition) - { - mysql_mutex_lock(&mutex); - thd->enter_cond(&condition_variable, &mutex, new_message); - if (!thd->killed [&& !end_of_wait_condition]) - { - [DEBUG_SYNC(thd, "sync_point_name");] - mysql_cond_wait(&condition_variable, &mutex); - } - thd->exit_cond(old_message); - } - - Note that it is important to repeat the test for thd->killed after - enter_cond(). Otherwise the killing thread may kill this thread after - it tested thd->killed in the loop condition and before it registered - the condition variable and mutex in enter_cond(). In this case, the - killing thread does not know that this thread is going to wait on a - condition variable. It would just set THD::killed. But if we would not - test it again, we would go asleep though we are killed. If the killing - thread would kill us when we are after the second test, but still - before sleeping, we hold the mutex, which is registered in mysys_var. - The killing thread would try to acquire the mutex before signaling - the condition variable. Since the mutex is only released implicitly in - mysql_cond_wait(), the signaling happens at the right place. We - have a safe synchronization. - - === Co-work with the DBUG facility === - - When running the MySQL test suite with the --debug-dbug command line - option, the Debug Sync Facility writes trace messages to the DBUG - trace. The following shell commands proved very useful in extracting - relevant information: - - egrep 'query:|debug_sync_exec:' mysql-test/var/log/mysqld.1.trace - - It shows all executed SQL statements and all actions executed by - synchronization points. - - Sometimes it is also useful to see, which synchronization points have - been run through (hit) with or without executing actions. Then add - "|debug_sync_point:" to the egrep pattern. - - === Further reading === - - For a discussion of other methods to synchronize threads see - http://forge.mysql.com/wiki/MySQL_Internals_Test_Synchronization - - For complete syntax tests, functional tests, and examples see the test - case debug_sync.test. - - See also http://forge.mysql.com/worklog/task.php?id=4259 -*/ - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef MYSQL_DYNAMIC_PLUGIN -extern void (*debug_sync_service)(MYSQL_THD, const char *, size_t); -#else -#define debug_sync_service debug_sync_C_callback_ptr -extern void (*debug_sync_C_callback_ptr)(MYSQL_THD, const char *, size_t); -#endif - -#ifdef ENABLED_DEBUG_SYNC -#define DEBUG_SYNC(thd, name) \ - do { \ - if (debug_sync_service) \ - debug_sync_service(thd, STRING_WITH_LEN(name)); \ - } while(0) - -#define DEBUG_SYNC_C_IF_THD(thd, name) \ - do { \ - if (debug_sync_service && thd) \ - debug_sync_service((MYSQL_THD) thd, STRING_WITH_LEN(name)); \ - } while(0) -#else -#define DEBUG_SYNC(thd,name) do { } while(0) -#define DEBUG_SYNC_C_IF_THD(thd, _sync_point_name_) do { } while(0) -#endif /* defined(ENABLED_DEBUG_SYNC) */ - -/* compatibility macro */ -#define DEBUG_SYNC_C(name) DEBUG_SYNC(NULL, name) - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_DEBUG_SYNC_INCLUDED -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_encryption.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_encryption.h deleted file mode 100644 index a4e908f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_encryption.h +++ /dev/null @@ -1,131 +0,0 @@ -#ifndef MYSQL_SERVICE_ENCRYPTION_INCLUDED -/* Copyright (c) 2015, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - encryption service - - Functions to support data encryption and encryption key management. - They are normally implemented in an encryption plugin, so this service - connects encryption *consumers* (e.g. storage engines) to the encryption - *provider* (encryption plugin). -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#ifdef _WIN32 -#include -#ifndef __cplusplus -#define inline __inline -#endif -#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) -#include -#else -#include -#endif -#endif - -/* returned from encryption_key_get_latest_version() */ -#define ENCRYPTION_KEY_VERSION_INVALID (~(unsigned int)0) -#define ENCRYPTION_KEY_NOT_ENCRYPTED (0) - -#define ENCRYPTION_KEY_SYSTEM_DATA 1 -#define ENCRYPTION_KEY_TEMPORARY_DATA 2 - -/* returned from encryption_key_get() */ -#define ENCRYPTION_KEY_BUFFER_TOO_SMALL (100) - -#define ENCRYPTION_FLAG_DECRYPT 0 -#define ENCRYPTION_FLAG_ENCRYPT 1 -#define ENCRYPTION_FLAG_NOPAD 2 - -struct encryption_service_st { - unsigned int (*encryption_key_get_latest_version_func)(unsigned int key_id); - unsigned int (*encryption_key_get_func)(unsigned int key_id, unsigned int key_version, - unsigned char* buffer, unsigned int* length); - unsigned int (*encryption_ctx_size_func)(unsigned int key_id, unsigned int key_version); - int (*encryption_ctx_init_func)(void *ctx, const unsigned char* key, unsigned int klen, - const unsigned char* iv, unsigned int ivlen, - int flags, unsigned int key_id, - unsigned int key_version); - int (*encryption_ctx_update_func)(void *ctx, const unsigned char* src, unsigned int slen, - unsigned char* dst, unsigned int* dlen); - int (*encryption_ctx_finish_func)(void *ctx, unsigned char* dst, unsigned int* dlen); - unsigned int (*encryption_encrypted_length_func)(unsigned int slen, unsigned int key_id, unsigned int key_version); -}; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -extern struct encryption_service_st *encryption_service; - -#define encryption_key_get_latest_version(KI) encryption_service->encryption_key_get_latest_version_func(KI) -#define encryption_key_get(KI,KV,K,S) encryption_service->encryption_key_get_func((KI),(KV),(K),(S)) -#define encryption_ctx_size(KI,KV) encryption_service->encryption_ctx_size_func((KI),(KV)) -#define encryption_ctx_init(CTX,K,KL,IV,IVL,F,KI,KV) encryption_service->encryption_ctx_init_func((CTX),(K),(KL),(IV),(IVL),(F),(KI),(KV)) -#define encryption_ctx_update(CTX,S,SL,D,DL) encryption_service->encryption_ctx_update_func((CTX),(S),(SL),(D),(DL)) -#define encryption_ctx_finish(CTX,D,DL) encryption_service->encryption_ctx_finish_func((CTX),(D),(DL)) -#define encryption_encrypted_length(SL,KI,KV) encryption_service->encryption_encrypted_length_func((SL),(KI),(KV)) -#else - -extern struct encryption_service_st encryption_handler; - -#define encryption_key_get_latest_version(KI) encryption_handler.encryption_key_get_latest_version_func(KI) -#define encryption_key_get(KI,KV,K,S) encryption_handler.encryption_key_get_func((KI),(KV),(K),(S)) -#define encryption_ctx_size(KI,KV) encryption_handler.encryption_ctx_size_func((KI),(KV)) -#define encryption_ctx_init(CTX,K,KL,IV,IVL,F,KI,KV) encryption_handler.encryption_ctx_init_func((CTX),(K),(KL),(IV),(IVL),(F),(KI),(KV)) -#define encryption_ctx_update(CTX,S,SL,D,DL) encryption_handler.encryption_ctx_update_func((CTX),(S),(SL),(D),(DL)) -#define encryption_ctx_finish(CTX,D,DL) encryption_handler.encryption_ctx_finish_func((CTX),(D),(DL)) -#define encryption_encrypted_length(SL,KI,KV) encryption_handler.encryption_encrypted_length_func((SL),(KI),(KV)) -#endif - -static inline unsigned int encryption_key_id_exists(unsigned int id) -{ - return encryption_key_get_latest_version(id) != ENCRYPTION_KEY_VERSION_INVALID; -} - -static inline unsigned int encryption_key_version_exists(unsigned int id, unsigned int version) -{ - unsigned int unused; - return encryption_key_get(id, version, NULL, &unused) != ENCRYPTION_KEY_VERSION_INVALID; -} - -static inline int encryption_crypt(const unsigned char* src, unsigned int slen, - unsigned char* dst, unsigned int* dlen, - const unsigned char* key, unsigned int klen, - const unsigned char* iv, unsigned int ivlen, - int flags, unsigned int key_id, unsigned int key_version) -{ - void *ctx= alloca(encryption_ctx_size(key_id, key_version)); - int res1, res2; - unsigned int d1, d2; - if ((res1= encryption_ctx_init(ctx, key, klen, iv, ivlen, flags, key_id, key_version))) - return res1; - res1= encryption_ctx_update(ctx, src, slen, dst, &d1); - res2= encryption_ctx_finish(ctx, dst + d1, &d2); - *dlen= d1 + d2; - return res1 ? res1 : res2; -} - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_ENCRYPTION_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_encryption_scheme.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_encryption_scheme.h deleted file mode 100644 index bcd4d64..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_encryption_scheme.h +++ /dev/null @@ -1,133 +0,0 @@ -#ifndef MYSQL_SERVICE_ENCRYPTION_SCHEME_INCLUDED -/* Copyright (c) 2015, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - encryption scheme service - - A higher-level access to encryption service. - - This is a helper service that storage engines use to encrypt tables on disk. - It requests keys from the plugin, generates temporary or local keys - from the global (as returned by the plugin) keys, etc. - - To use the service: - - * st_encryption_scheme object is created per space. A "space" can be - a table space in XtraDB/InnoDB, a file in Aria, etc. The whole - space is encrypted with the one key id. - - * The service does not take the key and the IV as parameters for - encryption or decryption. Instead it takes two 32-bit integers and - one 64-bit integer (and requests the key from an encryption - plugin, if needed). - - * The service requests the global key from the encryption plugin - automatically as needed. Three last keys are cached in the - st_encryption_scheme. Number of key requests (number of cache - misses) are counted in st_encryption_scheme::keyserver_requests - - * If an st_encryption_scheme can be used concurrently by different - threads, it needs to be able to lock itself when accessing the key - cache. Set the st_encryption_scheme::locker appropriately. If - non-zero, it will be invoked by encrypt/decrypt functions to lock - and unlock the scheme when needed. - - * Implementation details (in particular, key derivation) are defined - by the scheme type. Currently only schema type 1 is supported. - - In the schema type 1, every "space" (table space in XtraDB/InnoDB, - file in Aria) is encrypted with a different space-local key: - - * Every space has a 16-byte unique identifier (typically it's - generated randomly and stored in the space). The caller should - put it into st_encryption_scheme::iv. - - * Space-local key is generated by encrypting this identifier with - the global encryption key (of the given id and version) using AES_ECB. - - * Encryption/decryption parameters for a page are typically the - 4-byte space id, 4-byte page position (offset, page number, etc), - and the 8-byte LSN. This guarantees that they'll be different for - any two pages (of the same or different tablespaces) and also that - they'll change for the same page when it's modified. They don't need - to be secret (they create the IV, not the encryption key). -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#define ENCRYPTION_SCHEME_KEY_INVALID -1 -#define ENCRYPTION_SCHEME_BLOCK_LENGTH 16 - -struct st_encryption_scheme_key { - unsigned int version; - unsigned char key[ENCRYPTION_SCHEME_BLOCK_LENGTH]; -}; - -struct st_encryption_scheme { - unsigned char iv[ENCRYPTION_SCHEME_BLOCK_LENGTH]; - struct st_encryption_scheme_key key[3]; - unsigned int keyserver_requests; - unsigned int key_id; - unsigned int type; - - void (*locker)(struct st_encryption_scheme *self, int release); -}; - -extern struct encryption_scheme_service_st { - int (*encryption_scheme_encrypt_func) - (const unsigned char* src, unsigned int slen, - unsigned char* dst, unsigned int* dlen, - struct st_encryption_scheme *scheme, - unsigned int key_version, unsigned int i32_1, - unsigned int i32_2, unsigned long long i64); - int (*encryption_scheme_decrypt_func) - (const unsigned char* src, unsigned int slen, - unsigned char* dst, unsigned int* dlen, - struct st_encryption_scheme *scheme, - unsigned int key_version, unsigned int i32_1, - unsigned int i32_2, unsigned long long i64); -} *encryption_scheme_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define encryption_scheme_encrypt(S,SL,D,DL,SCH,KV,I32,J32,I64) encryption_scheme_service->encryption_scheme_encrypt_func(S,SL,D,DL,SCH,KV,I32,J32,I64) -#define encryption_scheme_decrypt(S,SL,D,DL,SCH,KV,I32,J32,I64) encryption_scheme_service->encryption_scheme_decrypt_func(S,SL,D,DL,SCH,KV,I32,J32,I64) - -#else - -int encryption_scheme_encrypt(const unsigned char* src, unsigned int slen, - unsigned char* dst, unsigned int* dlen, - struct st_encryption_scheme *scheme, - unsigned int key_version, unsigned int i32_1, - unsigned int i32_2, unsigned long long i64); -int encryption_scheme_decrypt(const unsigned char* src, unsigned int slen, - unsigned char* dst, unsigned int* dlen, - struct st_encryption_scheme *scheme, - unsigned int key_version, unsigned int i32_1, - unsigned int i32_2, unsigned long long i64); - -#endif - - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_ENCRYPTION_SCHEME_INCLUDED -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_json.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_json.h deleted file mode 100644 index 141b762..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_json.h +++ /dev/null @@ -1,117 +0,0 @@ -/* Copyright (C) 2018 MariaDB Corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ - -#ifndef MYSQL_SERVICE_JSON -#define MYSQL_SERVICE_JSON - -/** - @file - json service - - Esports JSON parsing methods for plugins to use. - - Fuctions of the service: - js_type - returns the type of the JSON argument, - and the parsed value if it's scalar (not object or array) - - js_get_array_item - expecs JSON array as an argument, - and returns the n_item's item's type and value - Returns JSV_NOTHING type if the array is shorter - than n_item and the actual length of the array in v_len. - - js_get_object_key - expects JSON object as an argument, - searches for a key in the object, return it's type and value. - JSV_NOTHING if no such key found, the number of keys - in v_len. - - js_get_object_nkey - expects JSON object as an argument. - finds n_key's key in the object, returns it's name, type and value. - JSV_NOTHING if object has less keys than n_key. -*/ - - -#ifdef __cplusplus -extern "C" { -#endif - -enum json_types -{ - JSV_BAD_JSON=-1, - JSV_NOTHING=0, - JSV_OBJECT=1, - JSV_ARRAY=2, - JSV_STRING=3, - JSV_NUMBER=4, - JSV_TRUE=5, - JSV_FALSE=6, - JSV_NULL=7 -}; - -extern struct json_service_st { - enum json_types (*json_type)(const char *js, const char *js_end, - const char **value, int *value_len); - enum json_types (*json_get_array_item)(const char *js, const char *js_end, - int n_item, - const char **value, int *value_len); - enum json_types (*json_get_object_key)(const char *js, const char *js_end, - const char *key, - const char **value, int *value_len); - enum json_types (*json_get_object_nkey)(const char *js,const char *js_end, - int nkey, - const char **keyname, const char **keyname_end, - const char **value, int *value_len); - int (*json_escape_string)(const char *str,const char *str_end, - char *json, char *json_end); - int (*json_unescape_json)(const char *json_str, const char *json_end, - char *res, char *res_end); -} *json_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define json_type json_service->json_type -#define json_get_array_item json_service->json_get_array_item -#define json_get_object_key json_service->json_get_object_key -#define json_get_object_nkey json_service->json_get_object_nkey -#define json_escape_string json_service->json_escape_string -#define json_unescape_json json_service->json_unescape_json - -#else - -enum json_types json_type(const char *js, const char *js_end, - const char **value, int *value_len); -enum json_types json_get_array_item(const char *js, const char *js_end, - int n_item, - const char **value, int *value_len); -enum json_types json_get_object_key(const char *js, const char *js_end, - const char *key, - const char **value, int *value_len); -enum json_types json_get_object_nkey(const char *js,const char *js_end, int nkey, - const char **keyname, const char **keyname_end, - const char **value, int *value_len); -int json_escape_string(const char *str,const char *str_end, - char *json, char *json_end); -int json_unescape_json(const char *json_str, const char *json_end, - char *res, char *res_end); - -#endif /*MYSQL_DYNAMIC_PLUGIN*/ - - -#ifdef __cplusplus -} -#endif - -#endif /*MYSQL_SERVICE_JSON */ - - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_kill_statement.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_kill_statement.h deleted file mode 100644 index 9f3415a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_kill_statement.h +++ /dev/null @@ -1,71 +0,0 @@ -/* Copyright (c) 2013, 2018, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_SERVICE_KILL_STATEMENT_INCLUDED -#define MYSQL_SERVICE_KILL_STATEMENT_INCLUDED - -/** - @file - This service provides functions that allow plugins to support - the KILL statement. - - In MySQL support for the KILL statement is cooperative. The KILL - statement only sets a "killed" flag. This function returns the value - of that flag. A thread should check it often, especially inside - time-consuming loops, and gracefully abort the operation if it is - non-zero. - - thd_killed(thd) - @return 0 - no KILL statement was issued, continue normally - @return 1 - there was a KILL statement, abort the execution. - - thd_kill_level(thd) - @return thd_kill_levels_enum values -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -enum thd_kill_levels { - THD_IS_NOT_KILLED=0, - THD_ABORT_SOFTLY=50, /**< abort when possible, don't leave tables corrupted */ - THD_ABORT_ASAP=100, /**< abort asap */ -}; - -extern struct kill_statement_service_st { - enum thd_kill_levels (*thd_kill_level_func)(const MYSQL_THD); -} *thd_kill_statement_service; - -/* backward compatibility helper */ -#define thd_killed(THD) (thd_kill_level(THD) == THD_ABORT_ASAP) - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define thd_kill_level(THD) \ - thd_kill_statement_service->thd_kill_level_func(THD) - -#else - -enum thd_kill_levels thd_kill_level(const MYSQL_THD); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_logger.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_logger.h deleted file mode 100644 index 5979901..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_logger.h +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright (C) 2012 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_SERVICE_LOGGER_INCLUDED -#define MYSQL_SERVICE_LOGGER_INCLUDED - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -/** - @file - logger service - - Log file with rotation implementation. - - This service implements logging with possible rotation - of the log files. Interface intentionally tries to be similar to FILE* - related functions. - - So that one can open the log with logger_open(), specifying - the limit on the logfile size and the rotations number. - - Then it's possible to write messages to the log with - logger_printf or logger_vprintf functions. - - As the size of the logfile grows over the specified limit, - it is renamed to 'logfile.1'. The former 'logfile.1' becomes - 'logfile.2', etc. The file 'logfile.rotations' is removed. - That's how the rotation works. - - The rotation can be forced with the logger_rotate() call. - - Finally the log should be closed with logger_close(). - -@notes: - Implementation checks the size of the log file before it starts new - printf into it. So the size of the file gets over the limit when it rotates. - - The access is secured with the mutex, so the log is threadsafe. -*/ - - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct logger_handle_st LOGGER_HANDLE; - -extern struct logger_service_st { - void (*logger_init_mutexes)(); - LOGGER_HANDLE* (*open)(const char *path, - unsigned long long size_limit, - unsigned int rotations); - int (*close)(LOGGER_HANDLE *log); - int (*vprintf)(LOGGER_HANDLE *log, const char *fmt, va_list argptr); - int (*printf)(LOGGER_HANDLE *log, const char *fmt, ...); - int (*write)(LOGGER_HANDLE *log, const char *buffer, size_t size); - int (*rotate)(LOGGER_HANDLE *log); -} *logger_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define logger_init_mutexes logger_service->logger_init_mutexes -#define logger_open(path, size_limit, rotations) \ - (logger_service->open(path, size_limit, rotations)) -#define logger_close(log) (logger_service->close(log)) -#define logger_rotate(log) (logger_service->rotate(log)) -#define logger_vprintf(log, fmt, argptr) (logger_service->\ - vprintf(log, fmt, argptr)) -#define logger_printf (*logger_service->printf) -#define logger_write(log, buffer, size) \ - (logger_service->write(log, buffer, size)) -#else - - void logger_init_mutexes(); - LOGGER_HANDLE *logger_open(const char *path, - unsigned long long size_limit, - unsigned int rotations); - int logger_close(LOGGER_HANDLE *log); - int logger_vprintf(LOGGER_HANDLE *log, const char *fmt, va_list argptr); - int logger_printf(LOGGER_HANDLE *log, const char *fmt, ...); - int logger_write(LOGGER_HANDLE *log, const char *buffer, size_t size); - int logger_rotate(LOGGER_HANDLE *log); -#endif - - -#ifdef __cplusplus -} -#endif - -#endif /*MYSQL_SERVICE_LOGGER_INCLUDED*/ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_md5.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_md5.h deleted file mode 100644 index 336cf70..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_md5.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef MYSQL_SERVICE_MD5_INCLUDED -/* Copyright (c) 2014, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - my md5 service - - Functions to calculate MD5 hash from a memory buffer -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -#define MY_MD5_HASH_SIZE 16 /* Hash size in bytes */ - -extern struct my_md5_service_st { - void (*my_md5_type)(unsigned char*, const char*, size_t); - void (*my_md5_multi_type)(unsigned char*, ...); - size_t (*my_md5_context_size_type)(); - void (*my_md5_init_type)(void *); - void (*my_md5_input_type)(void *, const unsigned char *, size_t); - void (*my_md5_result_type)(void *, unsigned char *); -} *my_md5_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define my_md5(A,B,C) my_md5_service->my_md5_type(A,B,C) -#define my_md5_multi my_md5_service->my_md5_multi_type -#define my_md5_context_size() my_md5_service->my_md5_context_size_type() -#define my_md5_init(A) my_md5_service->my_md5_init_type(A) -#define my_md5_input(A,B,C) my_md5_service->my_md5_input_type(A,B,C) -#define my_md5_result(A,B) my_md5_service->my_md5_result_type(A,B) - -#else - -void my_md5(unsigned char*, const char*, size_t); -void my_md5_multi(unsigned char*, ...); -size_t my_md5_context_size(); -void my_md5_init(void *context); -void my_md5_input(void *context, const unsigned char *buf, size_t len); -void my_md5_result(void *context, unsigned char *digest); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_MD5_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_crypt.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_crypt.h deleted file mode 100644 index 930d12a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_crypt.h +++ /dev/null @@ -1,120 +0,0 @@ -#ifndef MYSQL_SERVICE_MY_CRYPT_INCLUDED -#define MYSQL_SERVICE_MY_CRYPT_INCLUDED - -/* - Copyright (c) 2014 Google Inc. - Copyright (c) 2014, 2015 MariaDB Corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - my crypt service - - AES encryption functions, and a function to generate random bytes. - - Include my_config.h before this file to use CTR and GCM modes - (they only work if server was compiled with openssl). -*/ - - -#ifdef __cplusplus -extern "C" { -#endif - -/* return values from my_aes_encrypt/my_aes_decrypt functions */ -#define MY_AES_OK 0 -#define MY_AES_BAD_DATA -100 -#define MY_AES_OPENSSL_ERROR -101 -#define MY_AES_BAD_KEYSIZE -102 - -/* The block size for all supported algorithms */ -#define MY_AES_BLOCK_SIZE 16 - -/* The max key length of all supported algorithms */ -#define MY_AES_MAX_KEY_LENGTH 32 - -#define MY_AES_CTX_SIZE 640 - -enum my_aes_mode { - MY_AES_ECB, MY_AES_CBC -#ifdef HAVE_EncryptAes128Ctr - , MY_AES_CTR -#endif -#ifdef HAVE_EncryptAes128Gcm - , MY_AES_GCM -#endif -}; - -extern struct my_crypt_service_st { - int (*my_aes_crypt_init)(void *ctx, enum my_aes_mode mode, int flags, - const unsigned char* key, unsigned int klen, - const unsigned char* iv, unsigned int ivlen); - int (*my_aes_crypt_update)(void *ctx, const unsigned char *src, unsigned int slen, - unsigned char *dst, unsigned int *dlen); - int (*my_aes_crypt_finish)(void *ctx, unsigned char *dst, unsigned int *dlen); - int (*my_aes_crypt)(enum my_aes_mode mode, int flags, - const unsigned char *src, unsigned int slen, unsigned char *dst, unsigned int *dlen, - const unsigned char *key, unsigned int klen, const unsigned char *iv, unsigned int ivlen); - unsigned int (*my_aes_get_size)(enum my_aes_mode mode, unsigned int source_length); - unsigned int (*my_aes_ctx_size)(enum my_aes_mode mode); - int (*my_random_bytes)(unsigned char* buf, int num); -} *my_crypt_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define my_aes_crypt_init(A,B,C,D,E,F,G) \ - my_crypt_service->my_aes_crypt_init(A,B,C,D,E,F,G) - -#define my_aes_crypt_update(A,B,C,D,E) \ - my_crypt_service->my_aes_crypt_update(A,B,C,D,E) - -#define my_aes_crypt_finish(A,B,C) \ - my_crypt_service->my_aes_crypt_finish(A,B,C) - -#define my_aes_crypt(A,B,C,D,E,F,G,H,I,J) \ - my_crypt_service->my_aes_crypt(A,B,C,D,E,F,G,H,I,J) - -#define my_aes_get_size(A,B)\ - my_crypt_service->my_aes_get_size(A,B) - -#define my_aes_ctx_size(A)\ - my_crypt_service->my_aes_ctx_size(A) - -#define my_random_bytes(A,B)\ - my_crypt_service->my_random_bytes(A,B) - -#else - -int my_aes_crypt_init(void *ctx, enum my_aes_mode mode, int flags, - const unsigned char* key, unsigned int klen, - const unsigned char* iv, unsigned int ivlen); -int my_aes_crypt_update(void *ctx, const unsigned char *src, unsigned int slen, - unsigned char *dst, unsigned int *dlen); -int my_aes_crypt_finish(void *ctx, unsigned char *dst, unsigned int *dlen); -int my_aes_crypt(enum my_aes_mode mode, int flags, - const unsigned char *src, unsigned int slen, unsigned char *dst, unsigned int *dlen, - const unsigned char *key, unsigned int klen, const unsigned char *iv, unsigned int ivlen); - -int my_random_bytes(unsigned char* buf, int num); -unsigned int my_aes_get_size(enum my_aes_mode mode, unsigned int source_length); -unsigned int my_aes_ctx_size(enum my_aes_mode mode); -#endif - - -#ifdef __cplusplus -} -#endif - -#endif /* MYSQL_SERVICE_MY_CRYPT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_print_error.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_print_error.h deleted file mode 100644 index 74ba6a2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_print_error.h +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright (c) 2016, MariaDB - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; version 2 of the License. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_SERVICE_MY_PRINT_ERROR_INCLUDED -#define MYSQL_SERVICE_MY_PRINT_ERROR_INCLUDED - -/** - @file include/mysql/service_my_print_error.h - - This service provides functions for plugins to report - errors to client (without client, the errors are written to the error log). - -*/ -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#include -#endif - -#define ME_ERROR_LOG 64 /* Write the message to the error log */ -#define ME_ERROR_LOG_ONLY 128 /* Write the error message to error log only */ -#define ME_NOTE 1024 /* Not an error, just a note */ -#define ME_WARNING 2048 /* Not an error, just a warning */ -#define ME_FATAL 4096 /* Fatal statement error */ - -extern struct my_print_error_service_st { - void (*my_error_func)(unsigned int nr, unsigned long MyFlags, ...); - void (*my_printf_error_func)(unsigned int nr, const char *fmt, unsigned long MyFlags,...); - void (*my_printv_error_func)(unsigned int error, const char *format, unsigned long MyFlags, va_list ap); -} *my_print_error_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define my_error my_print_error_service->my_error_func -#define my_printf_error my_print_error_service->my_printf_error_func -#define my_printv_error(A,B,C,D) my_print_error_service->my_printv_error_func(A,B,C,D) - -#else -extern void my_error(unsigned int nr, unsigned long MyFlags, ...); -extern void my_printf_error(unsigned int my_err, const char *format, unsigned long MyFlags, ...); -extern void my_printv_error(unsigned int error, const char *format, unsigned long MyFlags,va_list ap); -#endif /* MYSQL_DYNAMIC_PLUGIN */ - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_snprintf.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_snprintf.h deleted file mode 100644 index 6757a65..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_my_snprintf.h +++ /dev/null @@ -1,110 +0,0 @@ -#ifndef MYSQL_SERVICE_MY_SNPRINTF_INCLUDED -/* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - my_snprintf service - - Portable and limited vsnprintf() implementation. - - This is a portable, limited vsnprintf() implementation, with some - extra features. "Portable" means that it'll produce identical result - on all platforms (for example, on Windows and Linux system printf %e - formats the exponent differently, on different systems %p either - prints leading 0x or not, %s may accept null pointer or crash on - it). "Limited" means that it does not support all the C89 features. - But it supports few extensions, not in any standard. - - my_vsnprintf(to, n, fmt, ap) - - @param[out] to A buffer to store the result in - @param[in] n Store up to n-1 characters, followed by an end 0 - @param[in] fmt printf-like format string - @param[in] ap Arguments - - @return a number of bytes written to a buffer *excluding* terminating '\0' - - @post - The syntax of a format string is generally the same: - % - where everithing but the format is optional. - - Three one-character flags are recognized: - '0' has the standard zero-padding semantics; - '-' is parsed, but silently ignored; - '`' (backtick) is only supported for strings (%s) and means that the - string will be quoted according to MySQL identifier quoting rules. - - Both and can be specified as numbers or '*'. - If an asterisk is used, an argument of type int is consumed. - - can be 'l', 'll', or 'z'. - - Supported formats are 's' (null pointer is accepted, printed as - "(null)"), 'b' (extension, see below), 'c', 'd', 'i', 'u', 'x', 'o', - 'X', 'p' (works as 0x%x), 'f', 'g', 'M' (extension, see below), - 'T' (extension, see below). - - Standard syntax for positional arguments $n is supported. - - Extensions: - - Flag '`' (backtick): see above. - - Format 'b': binary buffer, prints exactly bytes from the - argument, without stopping at '\0'. - - Format 'M': takes one integer, prints this integer, space, double quote - error message, double quote. In other words - printf("%M", n) === printf("%d \"%s\"", n, strerror(n)) - - Format 'T': takes string and print it like s but if the strints should be - truncated puts "..." at the end. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#include -#endif - -extern struct my_snprintf_service_st { - size_t (*my_snprintf_type)(char*, size_t, const char*, ...); - size_t (*my_vsnprintf_type)(char *, size_t, const char*, va_list); -} *my_snprintf_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define my_vsnprintf my_snprintf_service->my_vsnprintf_type -#define my_snprintf my_snprintf_service->my_snprintf_type - -#else - -size_t my_snprintf(char* to, size_t n, const char* fmt, ...); -size_t my_vsnprintf(char *to, size_t n, const char* fmt, va_list ap); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_MY_SNPRINTF_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_progress_report.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_progress_report.h deleted file mode 100644 index 11fc24d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_progress_report.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef MYSQL_SERVICE_PROGRESS_REPORT_INCLUDED -/* Copyright (C) 2011 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - This service allows plugins to report progress of long running operations - to the server. The progress report is visible in SHOW PROCESSLIST, - INFORMATION_SCHEMA.PROCESSLIST, and is sent to the client - if requested. - - The functions are documented at - https://mariadb.com/kb/en/progress-reporting/#how-to-add-support-for-progress-reporting-to-a-storage-engine -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#define thd_proc_info(thd, msg) set_thd_proc_info(thd, msg, \ - __func__, __FILE__, __LINE__) - -extern struct progress_report_service_st { - void (*thd_progress_init_func)(MYSQL_THD thd, unsigned int max_stage); - void (*thd_progress_report_func)(MYSQL_THD thd, - unsigned long long progress, - unsigned long long max_progress); - void (*thd_progress_next_stage_func)(MYSQL_THD thd); - void (*thd_progress_end_func)(MYSQL_THD thd); - const char *(*set_thd_proc_info_func)(MYSQL_THD, const char *info, - const char *func, - const char *file, - unsigned int line); -} *progress_report_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define thd_progress_init(thd,max_stage) (progress_report_service->thd_progress_init_func((thd),(max_stage))) -#define thd_progress_report(thd, progress, max_progress) (progress_report_service->thd_progress_report_func((thd), (progress), (max_progress))) -#define thd_progress_next_stage(thd) (progress_report_service->thd_progress_next_stage_func(thd)) -#define thd_progress_end(thd) (progress_report_service->thd_progress_end_func(thd)) -#define set_thd_proc_info(thd,info,func,file,line) (progress_report_service->set_thd_proc_info_func((thd),(info),(func),(file),(line))) - -#else - -/** - Report progress for long running operations - - @param thd User thread connection handle - @param progress Where we are now - @param max_progress Progress will continue up to this -*/ -void thd_progress_init(MYSQL_THD thd, unsigned int max_stage); -void thd_progress_report(MYSQL_THD thd, - unsigned long long progress, - unsigned long long max_progress); -void thd_progress_next_stage(MYSQL_THD thd); -void thd_progress_end(MYSQL_THD thd); -const char *set_thd_proc_info(MYSQL_THD, const char * info, const char *func, - const char *file, unsigned int line); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_PROGRESS_REPORT_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_sha1.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_sha1.h deleted file mode 100644 index d864e23..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_sha1.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef MYSQL_SERVICE_SHA1_INCLUDED -/* Copyright (c) 2013, 2014, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - my sha1 service - - Functions to calculate SHA1 hash from a memory buffer -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -#define MY_SHA1_HASH_SIZE 20 /* Hash size in bytes */ - -extern struct my_sha1_service_st { - void (*my_sha1_type)(unsigned char*, const char*, size_t); - void (*my_sha1_multi_type)(unsigned char*, ...); - size_t (*my_sha1_context_size_type)(); - void (*my_sha1_init_type)(void *); - void (*my_sha1_input_type)(void *, const unsigned char *, size_t); - void (*my_sha1_result_type)(void *, unsigned char *); -} *my_sha1_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define my_sha1(A,B,C) my_sha1_service->my_sha1_type(A,B,C) -#define my_sha1_multi my_sha1_service->my_sha1_multi_type -#define my_sha1_context_size() my_sha1_service->my_sha1_context_size_type() -#define my_sha1_init(A) my_sha1_service->my_sha1_init_type(A) -#define my_sha1_input(A,B,C) my_sha1_service->my_sha1_input_type(A,B,C) -#define my_sha1_result(A,B) my_sha1_service->my_sha1_result_type(A,B) - -#else - -void my_sha1(unsigned char*, const char*, size_t); -void my_sha1_multi(unsigned char*, ...); -size_t my_sha1_context_size(); -void my_sha1_init(void *context); -void my_sha1_input(void *context, const unsigned char *buf, size_t len); -void my_sha1_result(void *context, unsigned char *digest); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_SHA1_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_sha2.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_sha2.h deleted file mode 100644 index 00834a9..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_sha2.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef MYSQL_SERVICE_SHA2_INCLUDED -/* Copyright (c) 2017, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - my sha2 service - - Functions to calculate SHA2 hash from a memory buffer -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -extern struct my_sha2_service_st { - void (*my_sha224_type)(unsigned char*, const char*, size_t); - void (*my_sha224_multi_type)(unsigned char*, ...); - size_t (*my_sha224_context_size_type)(); - void (*my_sha224_init_type)(void *); - void (*my_sha224_input_type)(void *, const unsigned char *, size_t); - void (*my_sha224_result_type)(void *, unsigned char *); - - void (*my_sha256_type)(unsigned char*, const char*, size_t); - void (*my_sha256_multi_type)(unsigned char*, ...); - size_t (*my_sha256_context_size_type)(); - void (*my_sha256_init_type)(void *); - void (*my_sha256_input_type)(void *, const unsigned char *, size_t); - void (*my_sha256_result_type)(void *, unsigned char *); - - void (*my_sha384_type)(unsigned char*, const char*, size_t); - void (*my_sha384_multi_type)(unsigned char*, ...); - size_t (*my_sha384_context_size_type)(); - void (*my_sha384_init_type)(void *); - void (*my_sha384_input_type)(void *, const unsigned char *, size_t); - void (*my_sha384_result_type)(void *, unsigned char *); - - void (*my_sha512_type)(unsigned char*, const char*, size_t); - void (*my_sha512_multi_type)(unsigned char*, ...); - size_t (*my_sha512_context_size_type)(); - void (*my_sha512_init_type)(void *); - void (*my_sha512_input_type)(void *, const unsigned char *, size_t); - void (*my_sha512_result_type)(void *, unsigned char *); -} *my_sha2_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define my_sha224(A,B,C) my_sha2_service->my_sha224_type(A,B,C) -#define my_sha224_multi my_sha2_service->my_sha224_multi_type -#define my_sha224_context_size() my_sha2_service->my_sha224_context_size_type() -#define my_sha224_init(A) my_sha2_service->my_sha224_init_type(A) -#define my_sha224_input(A,B,C) my_sha2_service->my_sha224_input_type(A,B,C) -#define my_sha224_result(A,B) my_sha2_service->my_sha224_result_type(A,B) - -#define my_sha256(A,B,C) my_sha2_service->my_sha256_type(A,B,C) -#define my_sha256_multi my_sha2_service->my_sha256_multi_type -#define my_sha256_context_size() my_sha2_service->my_sha256_context_size_type() -#define my_sha256_init(A) my_sha2_service->my_sha256_init_type(A) -#define my_sha256_input(A,B,C) my_sha2_service->my_sha256_input_type(A,B,C) -#define my_sha256_result(A,B) my_sha2_service->my_sha256_result_type(A,B) - -#define my_sha384(A,B,C) my_sha2_service->my_sha384_type(A,B,C) -#define my_sha384_multi my_sha2_service->my_sha384_multi_type -#define my_sha384_context_size() my_sha2_service->my_sha384_context_size_type() -#define my_sha384_init(A) my_sha2_service->my_sha384_init_type(A) -#define my_sha384_input(A,B,C) my_sha2_service->my_sha384_input_type(A,B,C) -#define my_sha384_result(A,B) my_sha2_service->my_sha384_result_type(A,B) - -#define my_sha512(A,B,C) my_sha2_service->my_sha512_type(A,B,C) -#define my_sha512_multi my_sha2_service->my_sha512_multi_type -#define my_sha512_context_size() my_sha2_service->my_sha512_context_size_type() -#define my_sha512_init(A) my_sha2_service->my_sha512_init_type(A) -#define my_sha512_input(A,B,C) my_sha2_service->my_sha512_input_type(A,B,C) -#define my_sha512_result(A,B) my_sha2_service->my_sha512_result_type(A,B) - -#else - -void my_sha224(unsigned char*, const char*, size_t); -void my_sha224_multi(unsigned char*, ...); -size_t my_sha224_context_size(); -void my_sha224_init(void *context); -void my_sha224_input(void *context, const unsigned char *buf, size_t len); -void my_sha224_result(void *context, unsigned char *digest); - -void my_sha256(unsigned char*, const char*, size_t); -void my_sha256_multi(unsigned char*, ...); -size_t my_sha256_context_size(); -void my_sha256_init(void *context); -void my_sha256_input(void *context, const unsigned char *buf, size_t len); -void my_sha256_result(void *context, unsigned char *digest); - -void my_sha384(unsigned char*, const char*, size_t); -void my_sha384_multi(unsigned char*, ...); -size_t my_sha384_context_size(); -void my_sha384_init(void *context); -void my_sha384_input(void *context, const unsigned char *buf, size_t len); -void my_sha384_result(void *context, unsigned char *digest); - -void my_sha512(unsigned char*, const char*, size_t); -void my_sha512_multi(unsigned char*, ...); -size_t my_sha512_context_size(); -void my_sha512_init(void *context); -void my_sha512_input(void *context, const unsigned char *buf, size_t len); -void my_sha512_result(void *context, unsigned char *digest); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_SHA2_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_alloc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_alloc.h deleted file mode 100644 index 0be4687..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_alloc.h +++ /dev/null @@ -1,139 +0,0 @@ -#ifndef MYSQL_SERVICE_THD_ALLOC_INCLUDED -/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - This service provides functions to allocate memory in a connection local - memory pool. The memory allocated there will be automatically freed at the - end of the statement, don't use it for allocations that should live longer - than that. For short living allocations this is more efficient than - using my_malloc and friends, and automatic "garbage collection" allows not - to think about memory leaks. - - The pool is best for small to medium objects, don't use it for large - allocations - they are better served with my_malloc. -*/ - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -struct st_mysql_lex_string -{ - char *str; - size_t length; -}; -typedef struct st_mysql_lex_string MYSQL_LEX_STRING; - -struct st_mysql_const_lex_string -{ - const char *str; - size_t length; -}; -typedef struct st_mysql_const_lex_string MYSQL_CONST_LEX_STRING; - -extern struct thd_alloc_service_st { - void *(*thd_alloc_func)(MYSQL_THD, size_t); - void *(*thd_calloc_func)(MYSQL_THD, size_t); - char *(*thd_strdup_func)(MYSQL_THD, const char *); - char *(*thd_strmake_func)(MYSQL_THD, const char *, size_t); - void *(*thd_memdup_func)(MYSQL_THD, const void*, size_t); - MYSQL_CONST_LEX_STRING *(*thd_make_lex_string_func)(MYSQL_THD, - MYSQL_CONST_LEX_STRING *, - const char *, size_t, int); -} *thd_alloc_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define thd_alloc(thd,size) (thd_alloc_service->thd_alloc_func((thd), (size))) - -#define thd_calloc(thd,size) (thd_alloc_service->thd_calloc_func((thd), (size))) - -#define thd_strdup(thd,str) (thd_alloc_service->thd_strdup_func((thd), (str))) - -#define thd_strmake(thd,str,size) \ - (thd_alloc_service->thd_strmake_func((thd), (str), (size))) - -#define thd_memdup(thd,str,size) \ - (thd_alloc_service->thd_memdup_func((thd), (str), (size))) - -#define thd_make_lex_string(thd, lex_str, str, size, allocate_lex_string) \ - (thd_alloc_service->thd_make_lex_string_func((thd), (lex_str), (str), \ - (size), (allocate_lex_string))) - -#else - -/** - Allocate memory in the connection's local memory pool - - @details - When properly used in place of @c my_malloc(), this can significantly - improve concurrency. Don't use this or related functions to allocate - large chunks of memory. Use for temporary storage only. The memory - will be freed automatically at the end of the statement; no explicit - code is required to prevent memory leaks. - - @see alloc_root() -*/ -void *thd_alloc(MYSQL_THD thd, size_t size); -/** - @see thd_alloc() -*/ -void *thd_calloc(MYSQL_THD thd, size_t size); -/** - @see thd_alloc() -*/ -char *thd_strdup(MYSQL_THD thd, const char *str); -/** - @see thd_alloc() -*/ -char *thd_strmake(MYSQL_THD thd, const char *str, size_t size); -/** - @see thd_alloc() -*/ -void *thd_memdup(MYSQL_THD thd, const void* str, size_t size); - -/** - Create a LEX_STRING in this connection's local memory pool - - @param thd user thread connection handle - @param lex_str pointer to LEX_STRING object to be initialized - @param str initializer to be copied into lex_str - @param size length of str, in bytes - @param allocate_lex_string flag: if TRUE, allocate new LEX_STRING object, - instead of using lex_str value - @return NULL on failure, or pointer to the LEX_STRING object - - @see thd_alloc() -*/ -MYSQL_CONST_LEX_STRING -*thd_make_lex_string(MYSQL_THD thd, MYSQL_CONST_LEX_STRING *lex_str, - const char *str, size_t size, - int allocate_lex_string); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_THD_ALLOC_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_autoinc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_autoinc.h deleted file mode 100644 index 28bd2bb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_autoinc.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef MYSQL_SERVICE_THD_AUTOINC_INCLUDED -/* Copyright (C) 2013 MariaDB Foundation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - This service provides access to the auto_increment related system variables: - - @@auto_increment_offset - @@auto_increment_increment -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -extern struct thd_autoinc_service_st { - void (*thd_get_autoinc_func)(const MYSQL_THD thd, - unsigned long* off, unsigned long* inc); -} *thd_autoinc_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN -#define thd_get_autoinc(thd, off, inc) \ - (thd_autoinc_service->thd_get_autoinc_func((thd), (off), (inc))) -#else -/** - Return autoincrement system variables - @param IN thd user thread connection handle - @param OUT off the value of @@SESSION.auto_increment_offset - @param OUT inc the value of @@SESSION.auto_increment_increment -*/ -void thd_get_autoinc(const MYSQL_THD thd, - unsigned long* off, unsigned long* inc); -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_THD_AUTOINC_INCLUDED -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_error_context.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_error_context.h deleted file mode 100644 index 0b9082d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_error_context.h +++ /dev/null @@ -1,93 +0,0 @@ -#ifndef MYSQL_SERVICE_THD_STMT_DA_INCLUDED -/* Copyright (C) 2013 MariaDB Foundation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - This service provides access to the statement diagnostics area: - - error message - - error number - - row for warning (e.g. for multi-row INSERT statements) -*/ - -#ifdef __cplusplus -extern "C" { -#endif - - -extern struct thd_error_context_service_st { - const char *(*thd_get_error_message_func)(const MYSQL_THD thd); - unsigned int (*thd_get_error_number_func)(const MYSQL_THD thd); - unsigned long (*thd_get_error_row_func)(const MYSQL_THD thd); - void (*thd_inc_error_row_func)(MYSQL_THD thd); - char *(*thd_get_error_context_description_func)(MYSQL_THD thd, - char *buffer, - unsigned int length, - unsigned int max_query_length); -} *thd_error_context_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN -#define thd_get_error_message(thd) \ - (thd_error_context_service->thd_get_error_message_func((thd))) -#define thd_get_error_number(thd) \ - (thd_error_context_service->thd_get_error_number_func((thd))) -#define thd_get_error_row(thd) \ - (thd_error_context_service->thd_get_error_row_func((thd))) -#define thd_inc_error_row(thd) \ - (thd_error_context_service->thd_inc_error_row_func((thd))) -#define thd_get_error_context_description(thd, buffer, length, max_query_len) \ - (thd_error_context_service->thd_get_error_context_description_func((thd), \ - (buffer), \ - (length), \ - (max_query_len))) -#else -/** - Return error message - @param thd user thread connection handle - @return error text -*/ -const char *thd_get_error_message(const MYSQL_THD thd); -/** - Return error number - @param thd user thread connection handle - @return error number -*/ -unsigned int thd_get_error_number(const MYSQL_THD thd); -/** - Return the current row number (i.e. in a multiple INSERT statement) - @param thd user thread connection handle - @return row number -*/ -unsigned long thd_get_error_row(const MYSQL_THD thd); -/** - Increment the current row number - @param thd user thread connection handle -*/ -void thd_inc_error_row(MYSQL_THD thd); -/** - Return a text description of a thread, its security context (user,host) - and the current query. -*/ -char *thd_get_error_context_description(MYSQL_THD thd, - char *buffer, unsigned int length, - unsigned int max_query_length); -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_THD_STMT_DA_INCLUDED -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_mdl.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_mdl.h deleted file mode 100644 index 19b0476..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_mdl.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright (c) 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#pragma once - -/** - @file include/mysql/service_thd_mdl.h - This service provides functions for plugins and storage engines to access - metadata locks. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - - -extern struct thd_mdl_service_st { - void *(*thd_mdl_context)(MYSQL_THD); -} *thd_mdl_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN -# define thd_mdl_context(_THD) thd_mdl_service->thd_mdl_context(_THD) -#else -/** - MDL_context accessor - @param thd the current session - @return pointer to thd->mdl_context -*/ -void *thd_mdl_context(MYSQL_THD thd); -#endif - -#ifdef __cplusplus -} -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_rnd.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_rnd.h deleted file mode 100644 index 8761077..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_rnd.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef MYSQL_SERVICE_THD_RND_INCLUDED -/* Copyright (C) 2017 MariaDB Corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - This service provides access to the thd-local random number generator. - - It's preferable over the global one, because concurrent threads - can generate random numbers without fighting each other over the access - to the shared rnd state. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MYSQL_ABI_CHECK -#include -#endif - -extern struct thd_rnd_service_st { - double (*thd_rnd_ptr)(MYSQL_THD thd); - void (*thd_c_r_p_ptr)(MYSQL_THD thd, char *to, size_t length); -} *thd_rnd_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN -#define thd_rnd(A) thd_rnd_service->thd_rnd_ptr(A) -#define thd_create_random_password(A,B,C) thd_rnd_service->thd_c_r_p_ptr(A,B,C) -#else - -double thd_rnd(MYSQL_THD thd); - -/** - Generate string of printable random characters of requested length. - - @param to[out] Buffer for generation; must be at least length+1 bytes - long; result string is always null-terminated - @param length[in] How many random characters to put in buffer -*/ -void thd_create_random_password(MYSQL_THD thd, char *to, size_t length); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_THD_RND_INCLUDED -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_specifics.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_specifics.h deleted file mode 100644 index a4078bd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_specifics.h +++ /dev/null @@ -1,110 +0,0 @@ -#ifndef MYSQL_SERVICE_THD_SPECIFICS_INCLUDED -/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - THD specific for plugin(s) - - This API provides pthread_getspecific like functionality to plugin authors. - This is a functional alternative to the declarative MYSQL_THDVAR - - A plugin should at init call thd_key_create that create a key that - will have storage in each THD. The key should be used by all threads - and can be used concurrently from all threads. - - A plugin should at deinit call thd_key_delete. - - Alternatively, a plugin can use thd_key_create_from_var(K,V) to create - a key that corresponds to a named MYSQL_THDVAR variable. - - This API is also safe when using pool-of-threads in which case - pthread_getspecific is not, because the actual OS thread may change. - - @note - - Normally one should prefer MYSQL_THDVAR declarative API. - - The benefits are: - - - It supports typed variables (int, char*, enum, etc), not only void*. - - The memory allocated for MYSQL_THDVAR is free'd automatically - (if PLUGIN_VAR_MEMALLOC is specified). - - Continuous loading and unloading of the same plugin does not allocate - memory for same variables over and over again. - - An example of using MYSQL_THDVAR for a thd local storage: - - MYSQL_THDVAR_STR(my_tls, - PLUGIN_VAR_MEMALLOC | PLUGIN_VAR_NOSYSVAR | PLUGIN_VAR_NOCMDOPT, - "thd local storage example", 0, 0, 0); -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -typedef int MYSQL_THD_KEY_T; - -extern struct thd_specifics_service_st { - int (*thd_key_create_func)(MYSQL_THD_KEY_T *key); - void (*thd_key_delete_func)(MYSQL_THD_KEY_T *key); - void *(*thd_getspecific_func)(MYSQL_THD thd, MYSQL_THD_KEY_T key); - int (*thd_setspecific_func)(MYSQL_THD thd, MYSQL_THD_KEY_T key, void *value); -} *thd_specifics_service; - -#define thd_key_create_from_var(K, V) do { *(K)= MYSQL_SYSVAR_NAME(V).offset; } while(0) - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define thd_key_create(K) (thd_specifics_service->thd_key_create_func(K)) -#define thd_key_delete(K) (thd_specifics_service->thd_key_delete_func(K)) -#define thd_getspecific(T, K) (thd_specifics_service->thd_getspecific_func(T, K)) -#define thd_setspecific(T, K, V) (thd_specifics_service->thd_setspecific_func(T, K, V)) - -#else - -/** - * create THD specific storage - * @return 0 on success - * else errno is returned - */ -int thd_key_create(MYSQL_THD_KEY_T *key); - -/** - * delete THD specific storage - */ -void thd_key_delete(MYSQL_THD_KEY_T *key); - -/** - * get/set thd specific storage - * - first time this is called from a thread it will return 0 - * - this call is thread-safe in that different threads may call this - * simultaneously if operating on different THDs. - * - this call acquires no mutexes and is implemented as an array lookup - */ -void* thd_getspecific(MYSQL_THD thd, MYSQL_THD_KEY_T key); -int thd_setspecific(MYSQL_THD thd, MYSQL_THD_KEY_T key, void *value); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_THD_SPECIFICS_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_timezone.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_timezone.h deleted file mode 100644 index 89e7527..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_timezone.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef MYSQL_SERVICE_THD_TIMEZONE_INCLUDED -/* Copyright (C) 2013 MariaDB Foundation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - This service provdes functions to convert between my_time_t and - MYSQL_TIME taking into account the current value of the time_zone - session variable. - - The values of the my_time_t type are in Unix timestamp format, - i.e. the number of seconds since "1970-01-01 00:00:00 UTC". - - The values of the MYSQL_TIME type are in the current time zone, - according to thd->variables.time_zone. - - If the MYSQL_THD parameter is NULL, then global_system_variables.time_zone - is used for conversion. -*/ - -#ifndef MYSQL_ABI_CHECK -/* - This service currently does not depend on any system headers. - If it needs system headers in the future, make sure to put - them inside this ifndef. -*/ -#endif - -#include "mysql_time.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -extern struct thd_timezone_service_st { - my_time_t (*thd_TIME_to_gmt_sec)(MYSQL_THD thd, const MYSQL_TIME *ltime, unsigned int *errcode); - void (*thd_gmt_sec_to_TIME)(MYSQL_THD thd, MYSQL_TIME *ltime, my_time_t t); -} *thd_timezone_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define thd_TIME_to_gmt_sec(thd, ltime, errcode) \ - (thd_timezone_service->thd_TIME_to_gmt_sec((thd), (ltime), (errcode))) - -#define thd_gmt_sec_to_TIME(thd, ltime, t) \ - (thd_timezone_service->thd_gmt_sec_to_TIME((thd), (ltime), (t))) - -#else - -my_time_t thd_TIME_to_gmt_sec(MYSQL_THD thd, const MYSQL_TIME *ltime, unsigned int *errcode); -void thd_gmt_sec_to_TIME(MYSQL_THD thd, MYSQL_TIME *ltime, my_time_t t); - -#endif - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICE_THD_TIMEZONE_INCLUDED -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_wait.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_wait.h deleted file mode 100644 index c20878f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_thd_wait.h +++ /dev/null @@ -1,104 +0,0 @@ -/* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQL_SERVICE_THD_WAIT_INCLUDED -#define MYSQL_SERVICE_THD_WAIT_INCLUDED - -/** - @file include/mysql/service_thd_wait.h - This service provides functions for plugins and storage engines to report - when they are going to sleep/stall. - - SYNOPSIS - thd_wait_begin() - call just before a wait begins - thd Thread object - Use NULL if the thd is NOT known. - wait_type Type of wait - 1 -- short wait (e.g. for mutex) - 2 -- medium wait (e.g. for disk io) - 3 -- large wait (e.g. for locked row/table) - NOTES - This is used by the threadpool to have better knowledge of which - threads that currently are actively running on CPUs. When a thread - reports that it's going to sleep/stall, the threadpool scheduler is - free to start another thread in the pool most likely. The expected wait - time is simply an indication of how long the wait is expected to - become, the real wait time could be very different. - - thd_wait_end() called immediately after the wait is complete - - thd_wait_end() MUST be called if thd_wait_begin() was called. - - Using thd_wait_...() service is optional but recommended. Using it will - improve performance as the thread pool will be more active at managing the - thread workload. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - One should only report wait events that could potentially block for a - long time. A mutex wait is too short of an event to report. The reason - is that an event which is reported leads to a new thread starts - executing a query and this has a negative impact of usage of CPU caches - and thus the expected gain of starting a new thread must be higher than - the expected cost of lost performance due to starting a new thread. - - Good examples of events that should be reported are waiting for row locks - that could easily be for many milliseconds or even seconds and the same - holds true for global read locks, table locks and other meta data locks. - Another event of interest is going to sleep for an extended time. -*/ -typedef enum _thd_wait_type_e { - THD_WAIT_SLEEP= 1, - THD_WAIT_DISKIO= 2, - THD_WAIT_ROW_LOCK= 3, - THD_WAIT_GLOBAL_LOCK= 4, - THD_WAIT_META_DATA_LOCK= 5, - THD_WAIT_TABLE_LOCK= 6, - THD_WAIT_USER_LOCK= 7, - THD_WAIT_BINLOG= 8, - THD_WAIT_GROUP_COMMIT= 9, - THD_WAIT_SYNC= 10, - THD_WAIT_NET= 11, - THD_WAIT_LAST= 12 -} thd_wait_type; - -extern struct thd_wait_service_st { - void (*thd_wait_begin_func)(MYSQL_THD, int); - void (*thd_wait_end_func)(MYSQL_THD); -} *thd_wait_service; - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define thd_wait_begin(_THD, _WAIT_TYPE) \ - thd_wait_service->thd_wait_begin_func(_THD, _WAIT_TYPE) -#define thd_wait_end(_THD) thd_wait_service->thd_wait_end_func(_THD) - -#else - -void thd_wait_begin(MYSQL_THD thd, int wait_type); -void thd_wait_end(MYSQL_THD thd); - -#endif - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_wsrep.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_wsrep.h deleted file mode 100644 index f16331f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/service_wsrep.h +++ /dev/null @@ -1,238 +0,0 @@ -#ifndef MYSQL_SERVICE_WSREP_INCLUDED -#define MYSQL_SERVICE_WSREP_INCLUDED - -enum Wsrep_service_key_type -{ - WSREP_SERVICE_KEY_SHARED, - WSREP_SERVICE_KEY_REFERENCE, - WSREP_SERVICE_KEY_UPDATE, - WSREP_SERVICE_KEY_EXCLUSIVE -}; - -#if (defined (MYSQL_DYNAMIC_PLUGIN) && defined(MYSQL_SERVICE_WSREP_DYNAMIC_INCLUDED)) || (!defined(MYSQL_DYNAMIC_PLUGIN) && defined(MYSQL_SERVICE_WSREP_STATIC_INCLUDED)) - -#else - -/* Copyright (c) 2015, 2020, MariaDB Corporation Ab - 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - wsrep service - - Interface to WSREP functionality in the server. - For engines that want to support galera. -*/ -#include -#ifdef __cplusplus -#endif - -struct xid_t; -struct wsrep_ws_handle; -struct wsrep_buf; - -/* Must match to definition in sql/mysqld.h */ -typedef int64 query_id_t; - - -extern struct wsrep_service_st { - my_bool (*get_wsrep_recovery_func)(); - bool (*wsrep_consistency_check_func)(MYSQL_THD thd); - int (*wsrep_is_wsrep_xid_func)(const void *xid); - long long (*wsrep_xid_seqno_func)(const struct xid_t *xid); - const unsigned char* (*wsrep_xid_uuid_func)(const struct xid_t *xid); - my_bool (*wsrep_on_func)(const MYSQL_THD thd); - bool (*wsrep_prepare_key_for_innodb_func)(MYSQL_THD thd, const unsigned char*, size_t, const unsigned char*, size_t, struct wsrep_buf*, size_t*); - void (*wsrep_thd_LOCK_func)(const MYSQL_THD thd); - void (*wsrep_thd_UNLOCK_func)(const MYSQL_THD thd); - const char * (*wsrep_thd_query_func)(const MYSQL_THD thd); - int (*wsrep_thd_retry_counter_func)(const MYSQL_THD thd); - bool (*wsrep_thd_ignore_table_func)(MYSQL_THD thd); - long long (*wsrep_thd_trx_seqno_func)(const MYSQL_THD thd); - void (*wsrep_thd_auto_increment_variables_func)(THD *thd, unsigned long long *offset, unsigned long long *increment); - my_bool (*wsrep_thd_is_aborting_func)(const MYSQL_THD thd); - void (*wsrep_set_data_home_dir_func)(const char *data_dir); - my_bool (*wsrep_thd_is_BF_func)(const MYSQL_THD thd, my_bool sync); - my_bool (*wsrep_thd_is_local_func)(const MYSQL_THD thd); - void (*wsrep_thd_self_abort_func)(MYSQL_THD thd); - int (*wsrep_thd_append_key_func)(MYSQL_THD thd, const struct wsrep_key* key, - int n_keys, enum Wsrep_service_key_type); - const char* (*wsrep_thd_client_state_str_func)(const MYSQL_THD thd); - const char* (*wsrep_thd_client_mode_str_func)(const MYSQL_THD thd); - const char* (*wsrep_thd_transaction_state_str_func)(const MYSQL_THD thd); - query_id_t (*wsrep_thd_transaction_id_func)(const MYSQL_THD thd); - my_bool (*wsrep_thd_bf_abort_func)(MYSQL_THD bf_thd, - MYSQL_THD victim_thd, - my_bool signal); - my_bool (*wsrep_thd_order_before_func)(const MYSQL_THD left, const MYSQL_THD right); - void (*wsrep_handle_SR_rollback_func)(MYSQL_THD BF_thd, MYSQL_THD victim_thd); - my_bool (*wsrep_thd_skip_locking_func)(const MYSQL_THD thd); - const char* (*wsrep_get_sr_table_name_func)(); - my_bool (*wsrep_get_debug_func)(); - void (*wsrep_commit_ordered_func)(MYSQL_THD thd); - my_bool (*wsrep_thd_is_applying_func)(const MYSQL_THD thd); - ulong (*wsrep_OSU_method_get_func)(const MYSQL_THD thd); - my_bool (*wsrep_thd_has_ignored_error_func)(const MYSQL_THD thd); - void (*wsrep_thd_set_ignored_error_func)(MYSQL_THD thd, my_bool val); - bool (*wsrep_thd_set_wsrep_aborter_func)(MYSQL_THD bf_thd, MYSQL_THD thd); - void (*wsrep_report_bf_lock_wait_func)(const MYSQL_THD thd, - unsigned long long trx_id); -} *wsrep_service; - -#define MYSQL_SERVICE_WSREP_INCLUDED -#endif - -#ifdef MYSQL_DYNAMIC_PLUGIN - -#define MYSQL_SERVICE_WSREP_DYNAMIC_INCLUDED -#define get_wsrep_recovery() wsrep_service->get_wsrep_recovery_func() -#define wsrep_consistency_check(T) wsrep_service->wsrep_consistency_check_func(T) -#define wsrep_is_wsrep_xid(X) wsrep_service->wsrep_is_wsrep_xid_func(X) -#define wsrep_xid_seqno(X) wsrep_service->wsrep_xid_seqno_func(X) -#define wsrep_xid_uuid(X) wsrep_service->wsrep_xid_uuid_func(X) -#define wsrep_on(thd) (thd) && WSREP_ON && wsrep_service->wsrep_on_func(thd) -#define wsrep_prepare_key_for_innodb(A,B,C,D,E,F,G) wsrep_service->wsrep_prepare_key_for_innodb_func(A,B,C,D,E,F,G) -#define wsrep_thd_LOCK(T) wsrep_service->wsrep_thd_LOCK_func(T) -#define wsrep_thd_UNLOCK(T) wsrep_service->wsrep_thd_UNLOCK_func(T) -#define wsrep_thd_query(T) wsrep_service->wsrep_thd_query_func(T) -#define wsrep_thd_retry_counter(T) wsrep_service->wsrep_thd_retry_counter_func(T) -#define wsrep_thd_ignore_table(T) wsrep_service->wsrep_thd_ignore_table_func(T) -#define wsrep_thd_trx_seqno(T) wsrep_service->wsrep_thd_trx_seqno_func(T) -#define wsrep_thd_auto_increment_variables(T,O,I) wsrep_service->wsrep_thd_auto_increment_variables_func(T,O,I) -#define wsrep_set_data_home_dir(A) wsrep_service->wsrep_set_data_home_dir_func(A) -#define wsrep_thd_is_BF(T,S) wsrep_service->wsrep_thd_is_BF_func(T,S) -#define wsrep_thd_is_aborting(T) wsrep_service->wsrep_thd_is_aborting_func(T) -#define wsrep_thd_is_local(T) wsrep_service->wsrep_thd_is_local_func(T) -#define wsrep_thd_self_abort(T) wsrep_service->wsrep_thd_self_abort_func(T) -#define wsrep_thd_append_key(T,W,N,K) wsrep_service->wsrep_thd_append_key_func(T,W,N,K) -#define wsrep_thd_client_state_str(T) wsrep_service->wsrep_thd_client_state_str_func(T) -#define wsrep_thd_client_mode_str(T) wsrep_service->wsrep_thd_client_mode_str_func(T) -#define wsrep_thd_transaction_state_str(T) wsrep_service->wsrep_thd_transaction_state_str_func(T) -#define wsrep_thd_transaction_id(T) wsrep_service->wsrep_thd_transaction_id_func(T) -#define wsrep_thd_bf_abort(T,T2,S) wsrep_service->wsrep_thd_bf_abort_func(T,T2,S) -#define wsrep_thd_order_before(L,R) wsrep_service->wsrep_thd_order_before_func(L,R) -#define wsrep_handle_SR_rollback(B,V) wsrep_service->wsrep_handle_SR_rollback_func(B,V) -#define wsrep_thd_skip_locking(T) wsrep_service->wsrep_thd_skip_locking_func(T) -#define wsrep_get_sr_table_name() wsrep_service->wsrep_get_sr_table_name_func() -#define wsrep_get_debug() wsrep_service->wsrep_get_debug_func() -#define wsrep_commit_ordered(T) wsrep_service->wsrep_commit_ordered_func(T) -#define wsrep_thd_is_applying(T) wsrep_service->wsrep_thd_is_applying_func(T) -#define wsrep_OSU_method_get(T) wsrep_service->wsrep_OSU_method_get_func(T) -#define wsrep_thd_has_ignored_error(T) wsrep_service->wsrep_thd_has_ignored_error_func(T) -#define wsrep_thd_set_ignored_error(T,V) wsrep_service->wsrep_thd_set_ignored_error_func(T,V) -#define wsrep_thd_set_wsrep_aborter(T) wsrep_service->wsrep_thd_set_wsrep_aborter_func(T1, T2) -#define wsrep_report_bf_lock_wait(T,I) wsrep_service->wsrep_report_bf_lock_wait(T,I) -#else - -#define MYSQL_SERVICE_WSREP_STATIC_INCLUDED -extern ulong wsrep_debug; -extern my_bool wsrep_log_conflicts; -extern my_bool wsrep_certify_nonPK; -extern my_bool wsrep_load_data_splitting; -extern my_bool wsrep_drupal_282555_workaround; -extern my_bool wsrep_recovery; -extern long wsrep_protocol_version; - -extern "C" bool wsrep_consistency_check(MYSQL_THD thd); -bool wsrep_prepare_key_for_innodb(MYSQL_THD thd, const unsigned char* cache_key, size_t cache_key_len, const unsigned char* row_id, size_t row_id_len, struct wsrep_buf* key, size_t* key_len); -extern "C" const char *wsrep_thd_query(const MYSQL_THD thd); -extern "C" int wsrep_is_wsrep_xid(const void* xid); -extern "C" long long wsrep_xid_seqno(const struct xid_t* xid); -const unsigned char* wsrep_xid_uuid(const struct xid_t* xid); -extern "C" long long wsrep_thd_trx_seqno(const MYSQL_THD thd); -my_bool get_wsrep_recovery(); -void wsrep_thd_auto_increment_variables(THD *thd, unsigned long long *offset, unsigned long long *increment); -bool wsrep_thd_ignore_table(MYSQL_THD thd); -void wsrep_set_data_home_dir(const char *data_dir); - -/* from mysql wsrep-lib */ -#include "my_global.h" -#include "my_pthread.h" - -/* Return true if wsrep is enabled for a thd. This means that - wsrep is enabled globally and the thd has wsrep on */ -extern "C" my_bool wsrep_on(const MYSQL_THD thd); -/* Lock thd wsrep lock */ -extern "C" void wsrep_thd_LOCK(const MYSQL_THD thd); -/* Unlock thd wsrep lock */ -extern "C" void wsrep_thd_UNLOCK(const MYSQL_THD thd); - -/* Return thd client state string */ -extern "C" const char* wsrep_thd_client_state_str(const MYSQL_THD thd); -/* Return thd client mode string */ -extern "C" const char* wsrep_thd_client_mode_str(const MYSQL_THD thd); -/* Return thd transaction state string */ -extern "C" const char* wsrep_thd_transaction_state_str(const MYSQL_THD thd); - -/* Return current transaction id */ -extern "C" query_id_t wsrep_thd_transaction_id(const MYSQL_THD thd); -/* Mark thd own transaction as aborted */ -extern "C" void wsrep_thd_self_abort(MYSQL_THD thd); -/* Return true if thd is in replicating mode */ -extern "C" my_bool wsrep_thd_is_local(const MYSQL_THD thd); -/* Return true if thd is in high priority mode */ -/* todo: rename to is_high_priority() */ -extern "C" my_bool wsrep_thd_is_applying(const MYSQL_THD thd); -/* set wsrep_aborter for the target THD */ -extern "C" bool wsrep_thd_set_wsrep_aborter(MYSQL_THD bf_thd, MYSQL_THD victim_thd); -/* Return true if thd is in TOI mode */ -extern "C" my_bool wsrep_thd_is_toi(const MYSQL_THD thd); -/* Return true if thd is in replicating TOI mode */ -extern "C" my_bool wsrep_thd_is_local_toi(const MYSQL_THD thd); -/* Return true if thd is in RSU mode */ -extern "C" my_bool wsrep_thd_is_in_rsu(const MYSQL_THD thd); -/* Return true if thd is in BF mode, either high_priority or TOI */ -extern "C" my_bool wsrep_thd_is_BF(const MYSQL_THD thd, my_bool sync); -/* Return true if thd is streaming */ -extern "C" my_bool wsrep_thd_is_SR(const MYSQL_THD thd); -extern "C" void wsrep_handle_SR_rollback(MYSQL_THD BF_thd, MYSQL_THD victim_thd); -/* Return thd retry counter */ -extern "C" int wsrep_thd_retry_counter(const MYSQL_THD thd); -/* BF abort victim_thd */ -extern "C" my_bool wsrep_thd_bf_abort(MYSQL_THD bf_thd, - MYSQL_THD victim_thd, - my_bool signal); -/* Return true if left thd is ordered before right thd */ -extern "C" my_bool wsrep_thd_order_before(const MYSQL_THD left, const MYSQL_THD right); -/* Return true if thd should skip locking. This means that the thd - is operating on shared resource inside commit order critical section. */ -extern "C" my_bool wsrep_thd_skip_locking(const MYSQL_THD thd); -/* Return true if thd is aborting */ -extern "C" my_bool wsrep_thd_is_aborting(const MYSQL_THD thd); - -struct wsrep_key; -struct wsrep_key_array; -extern "C" int wsrep_thd_append_key(MYSQL_THD thd, - const struct wsrep_key* key, - int n_keys, - enum Wsrep_service_key_type); - -extern const char* wsrep_sr_table_name_full; - -extern "C" const char* wsrep_get_sr_table_name(); - -extern "C" my_bool wsrep_get_debug(); - -extern "C" void wsrep_commit_ordered(MYSQL_THD thd); -extern "C" my_bool wsrep_thd_is_applying(const MYSQL_THD thd); -extern "C" ulong wsrep_OSU_method_get(const MYSQL_THD thd); -extern "C" my_bool wsrep_thd_has_ignored_error(const MYSQL_THD thd); -extern "C" void wsrep_thd_set_ignored_error(MYSQL_THD thd, my_bool val); -extern "C" bool wsrep_thd_set_wsrep_aborter(MYSQL_THD bf_thd, MYSQL_THD victim_thd); -extern "C" void wsrep_report_bf_lock_wait(const THD *thd, - unsigned long long trx_id); -#endif -#endif /* MYSQL_SERVICE_WSREP_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/services.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/services.h deleted file mode 100644 index 2c3a0ae..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql/services.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef MYSQL_SERVICES_INCLUDED -/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. - Copyright (c) 2012, 2017, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -/*#include */ - -#ifdef __cplusplus -} -#endif - -#define MYSQL_SERVICES_INCLUDED -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_com.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_com.h deleted file mode 100644 index fa5960a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_com.h +++ /dev/null @@ -1,770 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. - Copyright (c) 2010, 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* -** Common definition between mysql server & client -*/ - -#ifndef _mysql_com_h -#define _mysql_com_h - -#include "my_decimal_limits.h" - -#define HOSTNAME_LENGTH 60 -#define SYSTEM_CHARSET_MBMAXLEN 3 -#define NAME_CHAR_LEN 64 /* Field/table name length */ -#define USERNAME_CHAR_LENGTH 128 -#define USERNAME_CHAR_LENGTH_STR STRINGIFY_ARG(USERNAME_CHAR_LENGTH) - -#define NAME_LEN (NAME_CHAR_LEN*SYSTEM_CHARSET_MBMAXLEN) -#define USERNAME_LENGTH (USERNAME_CHAR_LENGTH*SYSTEM_CHARSET_MBMAXLEN) -#define DEFINER_CHAR_LENGTH (USERNAME_CHAR_LENGTH + HOSTNAME_LENGTH + 1) -#define DEFINER_LENGTH (USERNAME_LENGTH + HOSTNAME_LENGTH + 1) - -#define MYSQL_AUTODETECT_CHARSET_NAME "auto" - -#define MYSQL50_TABLE_NAME_PREFIX "#mysql50#" -#define MYSQL50_TABLE_NAME_PREFIX_LENGTH (sizeof(MYSQL50_TABLE_NAME_PREFIX)-1) -#define SAFE_NAME_LEN (NAME_LEN + MYSQL50_TABLE_NAME_PREFIX_LENGTH) - -/* - MDEV-4088 - - MySQL (and MariaDB 5.x before the fix) was using the first character of the - server version string (as sent in the first handshake protocol packet) to - decide on the replication event formats. And for 10.x the first character - is "1", which the slave thought comes from some ancient 1.x version - (ignoring the fact that the first ever MySQL version was 3.x). - - To support replication to these old clients, we fake the version in the - first handshake protocol packet to start from "5.5.5-" (for example, - it might be "5.5.5-10.0.1-MariaDB-debug-log". - - On the client side we remove this fake version prefix to restore the - correct server version. The version "5.5.5" did not support - pluggable authentication, so any version starting from "5.5.5-" and - claiming to support pluggable auth, must be using this fake prefix. -*/ -/* this version must be the one that *does not* support pluggable auth */ -#define RPL_VERSION_HACK "5.5.5-" - -#define SERVER_VERSION_LENGTH 60 -#define SQLSTATE_LENGTH 5 -#define LIST_PROCESS_HOST_LEN 64 - -/* - Maximum length of comments -*/ -#define TABLE_COMMENT_INLINE_MAXLEN 180 /* pre 5.5: 60 characters */ -#define TABLE_COMMENT_MAXLEN 2048 -#define COLUMN_COMMENT_MAXLEN 1024 -#define INDEX_COMMENT_MAXLEN 1024 -#define TABLE_PARTITION_COMMENT_MAXLEN 1024 -#define DATABASE_COMMENT_MAXLEN 1024 - -/* - Maximum length of protocol packet. - OK packet length limit also restricted to this value as any length greater - than this value will have first byte of OK packet to be 254 thus does not - provide a means to identify if this is OK or EOF packet. -*/ -#define MAX_PACKET_LENGTH (256L*256L*256L-1) - -/* - USER_HOST_BUFF_SIZE -- length of string buffer, that is enough to contain - username and hostname parts of the user identifier with trailing zero in - MySQL standard format: - user_name_part@host_name_part\0 -*/ -#define USER_HOST_BUFF_SIZE HOSTNAME_LENGTH + USERNAME_LENGTH + 2 - -#define LOCAL_HOST "localhost" -#define LOCAL_HOST_NAMEDPIPE "." - - -#if defined(__WIN__) && !defined( _CUSTOMCONFIG_) -#define MYSQL_NAMEDPIPE "MySQL" -#define MYSQL_SERVICENAME "MySQL" -#endif /* __WIN__ */ - -/* - You should add new commands to the end of this list, otherwise old - servers won't be able to handle them as 'unsupported'. -*/ - -enum enum_server_command -{ - COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, - COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, - COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, - COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, - COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE, - COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, - COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_DAEMON, - COM_UNIMPLEMENTED, /* COM_BINLOG_DUMP_GTID in MySQL */ - COM_RESET_CONNECTION, - /* don't forget to update const char *command_name[] in sql_parse.cc */ - COM_MDB_GAP_BEG, - COM_MDB_GAP_END=249, - COM_STMT_BULK_EXECUTE=250, - COM_SLAVE_WORKER=251, - COM_SLAVE_IO=252, - COM_SLAVE_SQL=253, - COM_MULTI=254, - /* Must be last */ - COM_END=255 -}; - - -/* - Bulk PS protocol indicator value: -*/ -enum enum_indicator_type -{ - STMT_INDICATOR_NONE= 0, - STMT_INDICATOR_NULL, - STMT_INDICATOR_DEFAULT, - STMT_INDICATOR_IGNORE -}; - -/* - bulk PS flags -*/ -#define STMT_BULK_FLAG_CLIENT_SEND_TYPES 128 -#define STMT_BULK_FLAG_INSERT_ID_REQUEST 64 - - -/* sql type stored in .frm files for virtual fields */ -#define MYSQL_TYPE_VIRTUAL 245 -/* - Length of random string sent by server on handshake; this is also length of - obfuscated password, received from client -*/ -#define SCRAMBLE_LENGTH 20 -#define SCRAMBLE_LENGTH_323 8 -/* length of password stored in the db: new passwords are preceded with '*' */ -#define SCRAMBLED_PASSWORD_CHAR_LENGTH (SCRAMBLE_LENGTH*2+1) -#define SCRAMBLED_PASSWORD_CHAR_LENGTH_323 (SCRAMBLE_LENGTH_323*2) - - -#define NOT_NULL_FLAG 1U /* Field can't be NULL */ -#define PRI_KEY_FLAG 2U /* Field is part of a primary key */ -#define UNIQUE_KEY_FLAG 4U /* Field is part of a unique key */ -#define MULTIPLE_KEY_FLAG 8U /* Field is part of a key */ -#define BLOB_FLAG 16U /* Field is a blob */ -#define UNSIGNED_FLAG 32U /* Field is unsigned */ -#define ZEROFILL_FLAG 64U /* Field is zerofill */ -#define BINARY_FLAG 128U /* Field is binary */ - -/* The following are only sent to new clients */ -#define ENUM_FLAG 256U /* field is an enum */ -#define AUTO_INCREMENT_FLAG 512U /* field is a autoincrement field */ -#define TIMESTAMP_FLAG 1024U /* Field is a timestamp */ -#define SET_FLAG 2048U /* field is a set */ -#define NO_DEFAULT_VALUE_FLAG 4096U /* Field doesn't have default value */ -#define ON_UPDATE_NOW_FLAG 8192U /* Field is set to NOW on UPDATE */ -#define NUM_FLAG 32768U /* Field is num (for clients) */ -#define PART_KEY_FLAG 16384U /* Intern; Part of some key */ -#define GROUP_FLAG 32768U /* Intern: Group field */ -#define BINCMP_FLAG 131072U /* Intern: Used by sql_yacc */ -#define GET_FIXED_FIELDS_FLAG (1U << 18) /* Used to get fields in item tree */ -#define FIELD_IN_PART_FUNC_FLAG (1U << 19)/* Field part of partition func */ -#define PART_INDIRECT_KEY_FLAG (1U << 20) - -/** - Intern: Field in TABLE object for new version of altered table, - which participates in a newly added index. -*/ -#define FIELD_IN_ADD_INDEX (1U << 20) -#define FIELD_IS_RENAMED (1U << 21) /* Intern: Field is being renamed */ -#define FIELD_FLAGS_STORAGE_MEDIA 22 /* Field storage media, bit 22-23 */ -#define FIELD_FLAGS_STORAGE_MEDIA_MASK (3U << FIELD_FLAGS_STORAGE_MEDIA) -#define FIELD_FLAGS_COLUMN_FORMAT 24 /* Field column format, bit 24-25 */ -#define FIELD_FLAGS_COLUMN_FORMAT_MASK (3U << FIELD_FLAGS_COLUMN_FORMAT) -#define FIELD_IS_DROPPED (1U << 26) /* Intern: Field is being dropped */ - -#define VERS_SYS_START_FLAG (1 << 27) /* autogenerated column declared with - `generated always as row start` - (see II.a SQL Standard) */ -#define VERS_SYS_END_FLAG (1 << 28) /* autogenerated column declared with - `generated always as row end` - (see II.a SQL Standard).*/ -#define VERS_SYSTEM_FIELD (VERS_SYS_START_FLAG | VERS_SYS_END_FLAG) -#define VERS_UPDATE_UNVERSIONED_FLAG (1 << 29) /* column that doesn't support - system versioning when table - itself supports it*/ -#define LONG_UNIQUE_HASH_FIELD (1<< 30) /* This field will store hash for unique - column */ -#define FIELD_PART_OF_TMP_UNIQUE (1<< 31) /* part of an unique constrain - for a tmporary table*/ - -#define REFRESH_GRANT (1ULL << 0) /* Refresh grant tables */ -#define REFRESH_LOG (1ULL << 1) /* Start on new log file */ -#define REFRESH_TABLES (1ULL << 2) /* close all tables */ -#define REFRESH_HOSTS (1ULL << 3) /* Flush host cache */ -#define REFRESH_STATUS (1ULL << 4) /* Flush status variables */ -#define REFRESH_THREADS (1ULL << 5) /* Flush thread cache */ -#define REFRESH_SLAVE (1ULL << 6) /* Reset master info and restart slave - thread */ -#define REFRESH_MASTER (1ULL << 7) /* Remove all bin logs in the index - and truncate the index */ - -/* The following can't be set with mysql_refresh() */ -#define REFRESH_ERROR_LOG (1ULL << 8) /* Rotate only the error log */ -#define REFRESH_ENGINE_LOG (1ULL << 9) /* Flush all storage engine logs */ -#define REFRESH_BINARY_LOG (1ULL << 10) /* Flush the binary log */ -#define REFRESH_RELAY_LOG (1ULL << 11) /* Flush the relay log */ -#define REFRESH_GENERAL_LOG (1ULL << 12) /* Flush the general log */ -#define REFRESH_SLOW_LOG (1ULL << 13) /* Flush the slow query log */ - -#define REFRESH_READ_LOCK (1ULL << 14) /* Lock tables for read */ -#define REFRESH_CHECKPOINT (1ULL << 15) /* With REFRESH_READ_LOCK: block checkpoints too */ - -#define REFRESH_QUERY_CACHE (1ULL << 16) /* clear the query cache */ -#define REFRESH_QUERY_CACHE_FREE (1ULL << 17) /* pack query cache */ -#define REFRESH_DES_KEY_FILE (1ULL << 18) -#define REFRESH_USER_RESOURCES (1ULL << 19) -#define REFRESH_FOR_EXPORT (1ULL << 20) /* FLUSH TABLES ... FOR EXPORT */ -#define REFRESH_SSL (1ULL << 21) - -#define REFRESH_GENERIC (1ULL << 30) -#define REFRESH_FAST (1ULL << 31) /* Intern flag */ - -#define CLIENT_LONG_PASSWORD 0 /* obsolete flag */ -#define CLIENT_MYSQL 1ULL /* mysql/old mariadb server/client */ -#define CLIENT_FOUND_ROWS 2ULL /* Found instead of affected rows */ -#define CLIENT_LONG_FLAG 4ULL /* Get all column flags */ -#define CLIENT_CONNECT_WITH_DB 8ULL /* One can specify db on connect */ -#define CLIENT_NO_SCHEMA 16ULL /* Don't allow database.table.column */ -#define CLIENT_COMPRESS 32ULL /* Can use compression protocol */ -#define CLIENT_ODBC 64ULL /* Odbc client */ -#define CLIENT_LOCAL_FILES 128ULL /* Can use LOAD DATA LOCAL */ -#define CLIENT_IGNORE_SPACE 256ULL /* Ignore spaces before '(' */ -#define CLIENT_PROTOCOL_41 512ULL /* New 4.1 protocol */ -#define CLIENT_INTERACTIVE 1024ULL /* This is an interactive client */ -#define CLIENT_SSL 2048ULL /* Switch to SSL after handshake */ -#define CLIENT_IGNORE_SIGPIPE 4096ULL /* IGNORE sigpipes */ -#define CLIENT_TRANSACTIONS 8192ULL /* Client knows about transactions */ -#define CLIENT_RESERVED 16384ULL /* Old flag for 4.1 protocol */ -#define CLIENT_SECURE_CONNECTION 32768ULL /* New 4.1 authentication */ -#define CLIENT_MULTI_STATEMENTS (1ULL << 16) /* Enable/disable multi-stmt support */ -#define CLIENT_MULTI_RESULTS (1ULL << 17) /* Enable/disable multi-results */ -#define CLIENT_PS_MULTI_RESULTS (1ULL << 18) /* Multi-results in PS-protocol */ - -#define CLIENT_PLUGIN_AUTH (1ULL << 19) /* Client supports plugin authentication */ -#define CLIENT_CONNECT_ATTRS (1ULL << 20) /* Client supports connection attributes */ -/* Enable authentication response packet to be larger than 255 bytes. */ -#define CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA (1ULL << 21) -/* Don't close the connection for a connection with expired password. */ -#define CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS (1ULL << 22) - -/** - Capable of handling server state change information. Its a hint to the - server to include the state change information in Ok packet. -*/ -#define CLIENT_SESSION_TRACK (1ULL << 23) -/* Client no longer needs EOF packet */ -#define CLIENT_DEPRECATE_EOF (1ULL << 24) - -#define CLIENT_PROGRESS_OBSOLETE (1ULL << 29) -#define CLIENT_SSL_VERIFY_SERVER_CERT (1ULL << 30) -/* - It used to be that if mysql_real_connect() failed, it would delete any - options set by the client, unless the CLIENT_REMEMBER_OPTIONS flag was - given. - That behaviour does not appear very useful, and it seems unlikely that - any applications would actually depend on this. So from MariaDB 5.5 we - always preserve any options set in case of failed connect, and this - option is effectively always set. -*/ -#define CLIENT_REMEMBER_OPTIONS (1ULL << 31) - -/* MariaDB extended capability flags */ -#define MARIADB_CLIENT_FLAGS_MASK 0xffffffff00000000ULL -/* Client support progress indicator */ -#define MARIADB_CLIENT_PROGRESS (1ULL << 32) -/* support COM_MULTI */ -#define MARIADB_CLIENT_COM_MULTI (1ULL << 33) -/* support of array binding */ -#define MARIADB_CLIENT_STMT_BULK_OPERATIONS (1ULL << 34) -/* support of extended metadata (e.g. type/format information) */ -#define MARIADB_CLIENT_EXTENDED_METADATA (1ULL << 35) - -#ifdef HAVE_COMPRESS -#define CAN_CLIENT_COMPRESS CLIENT_COMPRESS -#else -#define CAN_CLIENT_COMPRESS 0 -#endif - -/* - Gather all possible capabilities (flags) supported by the server - - MARIADB_* flags supported only by MariaDB connector(s). -*/ -#define CLIENT_ALL_FLAGS (\ - CLIENT_FOUND_ROWS | \ - CLIENT_LONG_FLAG | \ - CLIENT_CONNECT_WITH_DB | \ - CLIENT_NO_SCHEMA | \ - CLIENT_COMPRESS | \ - CLIENT_ODBC | \ - CLIENT_LOCAL_FILES | \ - CLIENT_IGNORE_SPACE | \ - CLIENT_PROTOCOL_41 | \ - CLIENT_INTERACTIVE | \ - CLIENT_SSL | \ - CLIENT_IGNORE_SIGPIPE | \ - CLIENT_TRANSACTIONS | \ - CLIENT_RESERVED | \ - CLIENT_SECURE_CONNECTION | \ - CLIENT_MULTI_STATEMENTS | \ - CLIENT_MULTI_RESULTS | \ - CLIENT_PS_MULTI_RESULTS | \ - CLIENT_SSL_VERIFY_SERVER_CERT | \ - CLIENT_REMEMBER_OPTIONS | \ - MARIADB_CLIENT_PROGRESS | \ - CLIENT_PLUGIN_AUTH | \ - CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | \ - CLIENT_SESSION_TRACK |\ - CLIENT_DEPRECATE_EOF |\ - CLIENT_CONNECT_ATTRS |\ - MARIADB_CLIENT_COM_MULTI |\ - MARIADB_CLIENT_STMT_BULK_OPERATIONS |\ - MARIADB_CLIENT_EXTENDED_METADATA|\ - CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) - -/* - Switch off the flags that are optional and depending on build flags - If any of the optional flags is supported by the build it will be switched - on before sending to the client during the connection handshake. -*/ -#define CLIENT_BASIC_FLAGS (((CLIENT_ALL_FLAGS & ~CLIENT_SSL) \ - & ~CLIENT_COMPRESS) \ - & ~CLIENT_SSL_VERIFY_SERVER_CERT) - -enum mariadb_field_attr_t -{ - MARIADB_FIELD_ATTR_DATA_TYPE_NAME= 0, - MARIADB_FIELD_ATTR_FORMAT_NAME= 1 -}; - -#define MARIADB_FIELD_ATTR_LAST MARIADB_FIELD_ATTR_FORMAT_NAME - - -/** - Is raised when a multi-statement transaction - has been started, either explicitly, by means - of BEGIN or COMMIT AND CHAIN, or - implicitly, by the first transactional - statement, when autocommit=off. -*/ -#define SERVER_STATUS_IN_TRANS 1U -#define SERVER_STATUS_AUTOCOMMIT 2U /* Server in auto_commit mode */ -#define SERVER_MORE_RESULTS_EXISTS 8U /* Multi query - next query exists */ -#define SERVER_QUERY_NO_GOOD_INDEX_USED 16U -#define SERVER_QUERY_NO_INDEX_USED 32U -/** - The server was able to fulfill the clients request and opened a - read-only non-scrollable cursor for a query. This flag comes - in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. -*/ -#define SERVER_STATUS_CURSOR_EXISTS 64U -/** - This flag is sent when a read-only cursor is exhausted, in reply to - COM_STMT_FETCH command. -*/ -#define SERVER_STATUS_LAST_ROW_SENT 128U -#define SERVER_STATUS_DB_DROPPED 256U /* A database was dropped */ -#define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512U -/** - Sent to the client if after a prepared statement reprepare - we discovered that the new statement returns a different - number of result set columns. -*/ -#define SERVER_STATUS_METADATA_CHANGED 1024U -#define SERVER_QUERY_WAS_SLOW 2048U - -/** - To mark ResultSet containing output parameter values. -*/ -#define SERVER_PS_OUT_PARAMS 4096U - -/** - Set at the same time as SERVER_STATUS_IN_TRANS if the started - multi-statement transaction is a read-only transaction. Cleared - when the transaction commits or aborts. Since this flag is sent - to clients in OK and EOF packets, the flag indicates the - transaction status at the end of command execution. -*/ -#define SERVER_STATUS_IN_TRANS_READONLY 8192U - -/** - This status flag, when on, implies that one of the state information has - changed on the server because of the execution of the last statement. -*/ -#define SERVER_SESSION_STATE_CHANGED 16384U - -#define SERVER_STATUS_ANSI_QUOTES 32768U - -/** - Server status flags that must be cleared when starting - execution of a new SQL statement. - Flags from this set are only added to the - current server status by the execution engine, but - never removed -- the execution engine expects them - to disappear automagically by the next command. -*/ -#define SERVER_STATUS_CLEAR_SET (SERVER_QUERY_NO_GOOD_INDEX_USED| \ - SERVER_QUERY_NO_INDEX_USED|\ - SERVER_MORE_RESULTS_EXISTS|\ - SERVER_STATUS_METADATA_CHANGED |\ - SERVER_QUERY_WAS_SLOW |\ - SERVER_STATUS_DB_DROPPED |\ - SERVER_STATUS_CURSOR_EXISTS|\ - SERVER_STATUS_LAST_ROW_SENT|\ - SERVER_SESSION_STATE_CHANGED) - -#define MYSQL_ERRMSG_SIZE 512 -#define NET_READ_TIMEOUT 30 /* Timeout on read */ -#define NET_WRITE_TIMEOUT 60 /* Timeout on write */ -#define NET_WAIT_TIMEOUT 8*60*60 /* Wait for new query */ - -struct st_vio; /* Only C */ -typedef struct st_vio Vio; - -#define MAX_TINYINT_WIDTH 3 /* Max width for a TINY w.o. sign */ -#define MAX_SMALLINT_WIDTH 5 /* Max width for a SHORT w.o. sign */ -#define MAX_MEDIUMINT_WIDTH 8 /* Max width for a INT24 w.o. sign */ -#define MAX_INT_WIDTH 10 /* Max width for a LONG w.o. sign */ -#define MAX_BIGINT_WIDTH 20 /* Max width for a LONGLONG */ -#define MAX_CHAR_WIDTH 255 /* Max length for a CHAR column */ -#define MAX_BLOB_WIDTH 16777216 /* Default width for blob */ - -typedef struct st_net { -#if !defined(CHECK_EMBEDDED_DIFFERENCES) || !defined(EMBEDDED_LIBRARY) - Vio *vio; - unsigned char *buff,*buff_end,*write_pos,*read_pos; - my_socket fd; /* For Perl DBI/dbd */ - /* - The following variable is set if we are doing several queries in one - command ( as in LOAD TABLE ... FROM MASTER ), - and do not want to confuse the client with OK at the wrong time - */ - unsigned long remain_in_buf,length, buf_length, where_b; - unsigned long max_packet,max_packet_size; - unsigned int pkt_nr,compress_pkt_nr; - unsigned int write_timeout, read_timeout, retry_count; - int fcntl; - unsigned int *return_status; - unsigned char reading_or_writing; - char save_char; - char net_skip_rest_factor; - my_bool thread_specific_malloc; - unsigned char compress; - my_bool unused3; /* Please remove with the next incompatible ABI change. */ - /* - Pointer to query object in query cache, do not equal NULL (0) for - queries in cache that have not stored its results yet - */ -#endif - void *thd; /* Used by MariaDB server to avoid calling current_thd */ - unsigned int last_errno; - unsigned char error; - my_bool unused4; /* Please remove with the next incompatible ABI change. */ - my_bool unused5; /* Please remove with the next incompatible ABI change. */ - /** Client library error message buffer. Actually belongs to struct MYSQL. */ - char last_error[MYSQL_ERRMSG_SIZE]; - /** Client library sqlstate buffer. Set along with the error message. */ - char sqlstate[SQLSTATE_LENGTH+1]; - void *extension; -} NET; - - -#define packet_error ~0UL - -enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY, - MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, - MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE, - MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP, - MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24, - MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, - MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, - MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR, - MYSQL_TYPE_BIT, - /* - mysql-5.6 compatibility temporal types. - They're only used internally for reading RBR - mysql-5.6 binary log events and mysql-5.6 frm files. - They're never sent to the client. - */ - MYSQL_TYPE_TIMESTAMP2, - MYSQL_TYPE_DATETIME2, - MYSQL_TYPE_TIME2, - /* Compressed types are only used internally for RBR. */ - MYSQL_TYPE_BLOB_COMPRESSED= 140, - MYSQL_TYPE_VARCHAR_COMPRESSED= 141, - - MYSQL_TYPE_NEWDECIMAL=246, - MYSQL_TYPE_ENUM=247, - MYSQL_TYPE_SET=248, - MYSQL_TYPE_TINY_BLOB=249, - MYSQL_TYPE_MEDIUM_BLOB=250, - MYSQL_TYPE_LONG_BLOB=251, - MYSQL_TYPE_BLOB=252, - MYSQL_TYPE_VAR_STRING=253, - MYSQL_TYPE_STRING=254, - MYSQL_TYPE_GEOMETRY=255 - -}; - -/* For backward compatibility */ -#define CLIENT_MULTI_QUERIES CLIENT_MULTI_STATEMENTS -#define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL -#define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL -#define FIELD_TYPE_TINY MYSQL_TYPE_TINY -#define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT -#define FIELD_TYPE_LONG MYSQL_TYPE_LONG -#define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT -#define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE -#define FIELD_TYPE_NULL MYSQL_TYPE_NULL -#define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP -#define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG -#define FIELD_TYPE_INT24 MYSQL_TYPE_INT24 -#define FIELD_TYPE_DATE MYSQL_TYPE_DATE -#define FIELD_TYPE_TIME MYSQL_TYPE_TIME -#define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME -#define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR -#define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE -#define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM -#define FIELD_TYPE_SET MYSQL_TYPE_SET -#define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB -#define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB -#define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB -#define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB -#define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING -#define FIELD_TYPE_STRING MYSQL_TYPE_STRING -#define FIELD_TYPE_CHAR MYSQL_TYPE_TINY -#define FIELD_TYPE_INTERVAL MYSQL_TYPE_ENUM -#define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY -#define FIELD_TYPE_BIT MYSQL_TYPE_BIT - - -/* Shutdown/kill enums and constants */ - -/* Bits for THD::killable. */ -#define MYSQL_SHUTDOWN_KILLABLE_CONNECT (unsigned char)(1 << 0) -#define MYSQL_SHUTDOWN_KILLABLE_TRANS (unsigned char)(1 << 1) -#define MYSQL_SHUTDOWN_KILLABLE_LOCK_TABLE (unsigned char)(1 << 2) -#define MYSQL_SHUTDOWN_KILLABLE_UPDATE (unsigned char)(1 << 3) - -enum mysql_enum_shutdown_level { - /* - We want levels to be in growing order of hardness (because we use number - comparisons). Note that DEFAULT does not respect the growing property, but - it's ok. - */ - SHUTDOWN_DEFAULT = 0, - /* wait for existing connections to finish */ - SHUTDOWN_WAIT_CONNECTIONS= MYSQL_SHUTDOWN_KILLABLE_CONNECT, - /* wait for existing trans to finish */ - SHUTDOWN_WAIT_TRANSACTIONS= MYSQL_SHUTDOWN_KILLABLE_TRANS, - /* wait for existing updates to finish (=> no partial MyISAM update) */ - SHUTDOWN_WAIT_UPDATES= MYSQL_SHUTDOWN_KILLABLE_UPDATE, - /* flush InnoDB buffers and other storage engines' buffers*/ - SHUTDOWN_WAIT_ALL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1), - /* don't flush InnoDB buffers, flush other storage engines' buffers*/ - SHUTDOWN_WAIT_CRITICAL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1) + 1 -}; - -enum enum_cursor_type -{ - CURSOR_TYPE_NO_CURSOR= 0, - CURSOR_TYPE_READ_ONLY= 1, - CURSOR_TYPE_FOR_UPDATE= 2, - CURSOR_TYPE_SCROLLABLE= 4 -}; - - -/* options for mysql_set_option */ -enum enum_mysql_set_option -{ - MYSQL_OPTION_MULTI_STATEMENTS_ON, - MYSQL_OPTION_MULTI_STATEMENTS_OFF -}; - -/* - Type of state change information that the server can include in the Ok - packet. -*/ -enum enum_session_state_type -{ - SESSION_TRACK_SYSTEM_VARIABLES, /* Session system variables */ - SESSION_TRACK_SCHEMA, /* Current schema */ - SESSION_TRACK_STATE_CHANGE, /* track session state changes */ - SESSION_TRACK_GTIDS, - SESSION_TRACK_TRANSACTION_CHARACTERISTICS, /* Transaction chistics */ - SESSION_TRACK_TRANSACTION_STATE, /* Transaction state */ -#ifdef USER_VAR_TRACKING - SESSION_TRACK_MYSQL_RESERVED1, - SESSION_TRACK_MYSQL_RESERVED2, - SESSION_TRACK_MYSQL_RESERVED3, - SESSION_TRACK_MYSQL_RESERVED4, - SESSION_TRACK_MYSQL_RESERVED5, - SESSION_TRACK_MYSQL_RESERVED6, - SESSION_TRACK_USER_VARIABLES, -#endif // USER_VAR_TRACKING - SESSION_TRACK_always_at_the_end /* must be last */ -}; - -#define SESSION_TRACK_BEGIN SESSION_TRACK_SYSTEM_VARIABLES - -#define IS_SESSION_STATE_TYPE(T) \ - (((int)(T) >= SESSION_TRACK_BEGIN) && ((T) < SESSION_TRACK_always_at_the_end)) - -#define net_new_transaction(net) ((net)->pkt_nr=0) - -#ifdef __cplusplus -extern "C" { -#endif - -my_bool my_net_init(NET *net, Vio* vio, void *thd, unsigned int my_flags); -void my_net_local_init(NET *net); -void net_end(NET *net); -void net_clear(NET *net, my_bool clear_buffer); -my_bool net_realloc(NET *net, size_t length); -my_bool net_flush(NET *net); -my_bool my_net_write(NET *net,const unsigned char *packet, size_t len); -my_bool net_write_command(NET *net,unsigned char command, - const unsigned char *header, size_t head_len, - const unsigned char *packet, size_t len); -int net_real_write(NET *net,const unsigned char *packet, size_t len); -unsigned long my_net_read_packet(NET *net, my_bool read_from_server); -unsigned long my_net_read_packet_reallen(NET *net, my_bool read_from_server, - unsigned long* reallen); -#define my_net_read(A) my_net_read_packet((A), 0) - -#ifdef MY_GLOBAL_INCLUDED -void my_net_set_write_timeout(NET *net, uint timeout); -void my_net_set_read_timeout(NET *net, uint timeout); -#endif - -struct sockaddr; -int my_connect(my_socket s, const struct sockaddr *name, unsigned int namelen, - unsigned int timeout); -struct my_rnd_struct; - -#ifdef __cplusplus -} -#endif - - /* The following is for user defined functions */ - -enum Item_result -{ - STRING_RESULT=0, REAL_RESULT, INT_RESULT, ROW_RESULT, DECIMAL_RESULT, - TIME_RESULT -}; - -typedef struct st_udf_args -{ - unsigned int arg_count; /* Number of arguments */ - enum Item_result *arg_type; /* Pointer to item_results */ - char **args; /* Pointer to argument */ - unsigned long *lengths; /* Length of string arguments */ - char *maybe_null; /* Set to 1 for all maybe_null args */ - const char **attributes; /* Pointer to attribute name */ - unsigned long *attribute_lengths; /* Length of attribute arguments */ - void *extension; -} UDF_ARGS; - - /* This holds information about the result */ - -typedef struct st_udf_init -{ - my_bool maybe_null; /* 1 if function can return NULL */ - unsigned int decimals; /* for real functions */ - unsigned long max_length; /* For string functions */ - char *ptr; /* free pointer for function data */ - my_bool const_item; /* 1 if function always returns the same value */ - void *extension; -} UDF_INIT; -/* - TODO: add a notion for determinism of the UDF. - See Item_udf_func::update_used_tables () -*/ - - /* Constants when using compression */ -#define NET_HEADER_SIZE 4 /* standard header size */ -#define COMP_HEADER_SIZE 3 /* compression header extra size */ - - /* Prototypes to password functions */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - These functions are used for authentication by client and server and - implemented in sql/password.c -*/ - -void create_random_string(char *to, unsigned int length, - struct my_rnd_struct *rand_st); - -void hash_password(unsigned long *to, const char *password, unsigned int password_len); -void make_scrambled_password_323(char *to, const char *password); -void scramble_323(char *to, const char *message, const char *password); -my_bool check_scramble_323(const unsigned char *reply, const char *message, - unsigned long *salt); -void get_salt_from_password_323(unsigned long *res, const char *password); -void make_scrambled_password(char *to, const char *password); -void scramble(char *to, const char *message, const char *password); -my_bool check_scramble(const unsigned char *reply, const char *message, - const unsigned char *hash_stage2); -void get_salt_from_password(unsigned char *res, const char *password); -char *octet2hex(char *to, const char *str, size_t len); - -/* end of password.c */ - -char *get_tty_password(const char *opt_message); -void get_tty_password_buff(const char *opt_message, char *to, size_t length); -const char *mysql_errno_to_sqlstate(unsigned int mysql_errno); - -/* Some other useful functions */ - -my_bool my_thread_init(void); -void my_thread_end(void); - -#ifdef MY_GLOBAL_INCLUDED -#include "pack.h" -#endif - -#ifdef __cplusplus -} -#endif - -#define NULL_LENGTH ~0UL /* For net_store_length */ -#define MYSQL_STMT_HEADER 4U -#define MYSQL_LONG_DATA_HEADER 6U - -/* - If a float or double field have more than this number of decimals, - it's regarded as floating point field without any specific number of - decimals -*/ - - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_com_server.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_com_server.h deleted file mode 100644 index d8bf531..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_com_server.h +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Definitions private to the server, - used in the networking layer to notify specific events. -*/ - -#ifndef _mysql_com_server_h -#define _mysql_com_server_h - -struct st_net_server; - -typedef void (*before_header_callback_fn) - (struct st_net *net, void *user_data, size_t count); - -typedef void (*after_header_callback_fn) - (struct st_net *net, void *user_data, size_t count, my_bool rc); - -struct st_net_server -{ - before_header_callback_fn m_before_header; - after_header_callback_fn m_after_header; - void *m_user_data; -}; - -typedef struct st_net_server NET_SERVER; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_embed.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_embed.h deleted file mode 100644 index 775040a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_embed.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef MYSQL_EMBED_INCLUDED -#define MYSQL_EMBED_INCLUDED - -/* - Copyright (c) 2000, 2011, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Defines that are unique to the embedded version of MySQL */ - -#ifdef EMBEDDED_LIBRARY - -/* Things we don't need in the embedded version of MySQL */ -/* TODO HF add #undef HAVE_VIO if we don't want client in embedded library */ - -#undef HAVE_DLOPEN /* No udf functions */ - -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_EMBED_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_time.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_time.h deleted file mode 100644 index ef78441..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_time.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (c) 2004, 2006 MySQL AB - Use is subject to license terms - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _mysql_time_h_ -#define _mysql_time_h_ - -/* - Portable time_t replacement. - Should be signed and hold seconds for 1902 -- 2038-01-19 range - i.e at least a 32bit variable - - Using the system built in time_t is not an option as - we rely on the above requirements in the time functions -*/ -typedef long my_time_t; - - -/* - Time declarations shared between the server and client API: - you should not add anything to this header unless it's used - (and hence should be visible) in mysql.h. - If you're looking for a place to add new time-related declaration, - it's most likely my_time.h. See also "C API Handling of Date - and Time Values" chapter in documentation. -*/ - -enum enum_mysql_timestamp_type -{ - MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1, - MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2 -}; - - -/* - Structure which is used to represent datetime values inside MySQL. - - We assume that values in this structure are normalized, i.e. year <= 9999, - month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions - in server such as my_system_gmt_sec() or make_time() family of functions - rely on this (actually now usage of make_*() family relies on a bit weaker - restriction). Also functions that produce MYSQL_TIME as result ensure this. - There is one exception to this rule though if this structure holds time - value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold - bigger values. -*/ -typedef struct st_mysql_time -{ - unsigned int year, month, day, hour, minute, second; - unsigned long second_part; - my_bool neg; - enum enum_mysql_timestamp_type time_type; -} MYSQL_TIME; - -#endif /* _mysql_time_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_version.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_version.h deleted file mode 100644 index 5577ca0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysql_version.h +++ /dev/null @@ -1,42 +0,0 @@ -/* Copyright Abandoned 1996,1999 TCX DataKonsult AB & Monty Program KB - & Detron HB, 1996, 1999-2004, 2007 MySQL AB. - This file is public domain and comes with NO WARRANTY of any kind -*/ - -/* Version numbers for protocol & mysqld */ - -#ifndef _mysql_version_h -#define _mysql_version_h -#ifdef _CUSTOMCONFIG_ -#include -#else -#define PROTOCOL_VERSION 10 -#define MYSQL_SERVER_VERSION "10.5.7-MariaDB" -#define MYSQL_BASE_VERSION "mysqld-10.5" -#define MARIADB_BASE_VERSION "mariadb-10.5" -#define MARIADBD_BASE_VERSION "mariadbd-10.5" -#define MYSQL_SERVER_SUFFIX_DEF "" -#define FRM_VER 6 -#define MYSQL_VERSION_ID 100507 -#define MARIADB_PORT 3306 -#define MYSQL_PORT_DEFAULT 0 -#define MARIADB_UNIX_ADDR "/tmp/mysql.sock" -#define MYSQL_CONFIG_NAME "my" -#define MYSQL_COMPILATION_COMMENT "mariadb.org binary distribution" -#define SERVER_MATURITY_LEVEL MariaDB_PLUGIN_MATURITY_STABLE - -#define MYSQL_PORT MARIADB_PORT -#define MYSQL_UNIX_ADDR MARIADB_UNIX_ADDR - -#ifdef WITH_WSREP -#define WSREP_PATCH_VERSION "" -#endif - -/* mysqld compile time options */ -#endif /* _CUSTOMCONFIG_ */ - -#ifndef LICENSE -#define LICENSE GPL -#endif /* LICENSE */ - -#endif /* _mysql_version_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysqld_ername.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysqld_ername.h deleted file mode 100644 index 6ad26a9..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysqld_ername.h +++ /dev/null @@ -1,1201 +0,0 @@ -/* Autogenerated file, please don't edit */ - -{ "ER_HASHCHK", 1000, "hashchk" }, -{ "ER_NISAMCHK", 1001, "isamchk" }, -{ "ER_NO", 1002, "NO" }, -{ "ER_YES", 1003, "YES" }, -{ "ER_CANT_CREATE_FILE", 1004, "Can\'t create file \'%-.200s\' (errno: %M)" }, -{ "ER_CANT_CREATE_TABLE", 1005, "Can\'t create table %`s.%`s (errno: %M)" }, -{ "ER_CANT_CREATE_DB", 1006, "Can\'t create database \'%-.192s\' (errno: %M)" }, -{ "ER_DB_CREATE_EXISTS", 1007, "Can\'t create database \'%-.192s\'; database exists" }, -{ "ER_DB_DROP_EXISTS", 1008, "Can\'t drop database \'%-.192s\'; database doesn\'t exist" }, -{ "ER_DB_DROP_DELETE", 1009, "Error dropping database (can\'t delete \'%-.192s\', errno: %M)" }, -{ "ER_DB_DROP_RMDIR", 1010, "Error dropping database (can\'t rmdir \'%-.192s\', errno: %M)" }, -{ "ER_CANT_DELETE_FILE", 1011, "Error on delete of \'%-.192s\' (errno: %M)" }, -{ "ER_CANT_FIND_SYSTEM_REC", 1012, "Can\'t read record in system table" }, -{ "ER_CANT_GET_STAT", 1013, "Can\'t get status of \'%-.200s\' (errno: %M)" }, -{ "ER_CANT_GET_WD", 1014, "Can\'t get working directory (errno: %M)" }, -{ "ER_CANT_LOCK", 1015, "Can\'t lock file (errno: %M)" }, -{ "ER_CANT_OPEN_FILE", 1016, "Can\'t open file: \'%-.200s\' (errno: %M)" }, -{ "ER_FILE_NOT_FOUND", 1017, "Can\'t find file: \'%-.200s\' (errno: %M)" }, -{ "ER_CANT_READ_DIR", 1018, "Can\'t read dir of \'%-.192s\' (errno: %M)" }, -{ "ER_CANT_SET_WD", 1019, "Can\'t change dir to \'%-.192s\' (errno: %M)" }, -{ "ER_CHECKREAD", 1020, "Record has changed since last read in table \'%-.192s\'" }, -{ "ER_DISK_FULL", 1021, "Disk full (%s); waiting for someone to free some space... (errno: %M)" }, -{ "ER_DUP_KEY", 1022, "Can\'t write; duplicate key in table \'%-.192s\'" }, -{ "ER_ERROR_ON_CLOSE", 1023, "Error on close of \'%-.192s\' (errno: %M)" }, -{ "ER_ERROR_ON_READ", 1024, "Error reading file \'%-.200s\' (errno: %M)" }, -{ "ER_ERROR_ON_RENAME", 1025, "Error on rename of \'%-.210s\' to \'%-.210s\' (errno: %M)" }, -{ "ER_ERROR_ON_WRITE", 1026, "Error writing file \'%-.200s\' (errno: %M)" }, -{ "ER_FILE_USED", 1027, "\'%-.192s\' is locked against change" }, -{ "ER_FILSORT_ABORT", 1028, "Sort aborted" }, -{ "ER_FORM_NOT_FOUND", 1029, "View \'%-.192s\' doesn\'t exist for \'%-.192s\'" }, -{ "ER_GET_ERRNO", 1030, "Got error %M from storage engine %s" }, -{ "ER_ILLEGAL_HA", 1031, "Storage engine %s of the table %`s.%`s doesn\'t have this option" }, -{ "ER_KEY_NOT_FOUND", 1032, "Can\'t find record in \'%-.192s\'" }, -{ "ER_NOT_FORM_FILE", 1033, "Incorrect information in file: \'%-.200s\'" }, -{ "ER_NOT_KEYFILE", 1034, "Index for table \'%-.200s\' is corrupt; try to repair it" }, -{ "ER_OLD_KEYFILE", 1035, "Old key file for table \'%-.192s\'; repair it!" }, -{ "ER_OPEN_AS_READONLY", 1036, "Table \'%-.192s\' is read only" }, -{ "ER_OUTOFMEMORY", 1037, "Out of memory; restart server and try again (needed %d bytes)" }, -{ "ER_OUT_OF_SORTMEMORY", 1038, "Out of sort memory, consider increasing server sort buffer size" }, -{ "ER_UNEXPECTED_EOF", 1039, "Unexpected EOF found when reading file \'%-.192s\' (errno: %M)" }, -{ "ER_CON_COUNT_ERROR", 1040, "Too many connections" }, -{ "ER_OUT_OF_RESOURCES", 1041, "Out of memory." }, -{ "ER_BAD_HOST_ERROR", 1042, "Can\'t get hostname for your address" }, -{ "ER_HANDSHAKE_ERROR", 1043, "Bad handshake" }, -{ "ER_DBACCESS_DENIED_ERROR", 1044, "Access denied for user \'%s\'@\'%s\' to database \'%-.192s\'" }, -{ "ER_ACCESS_DENIED_ERROR", 1045, "Access denied for user \'%s\'@\'%s\' (using password: %s)" }, -{ "ER_NO_DB_ERROR", 1046, "No database selected" }, -{ "ER_UNKNOWN_COM_ERROR", 1047, "Unknown command" }, -{ "ER_BAD_NULL_ERROR", 1048, "Column \'%-.192s\' cannot be null" }, -{ "ER_BAD_DB_ERROR", 1049, "Unknown database \'%-.192s\'" }, -{ "ER_TABLE_EXISTS_ERROR", 1050, "Table \'%-.192s\' already exists" }, -{ "ER_BAD_TABLE_ERROR", 1051, "Unknown table \'%-.100T\'" }, -{ "ER_NON_UNIQ_ERROR", 1052, "Column \'%-.192s\' in %-.192s is ambiguous" }, -{ "ER_SERVER_SHUTDOWN", 1053, "Server shutdown in progress" }, -{ "ER_BAD_FIELD_ERROR", 1054, "Unknown column \'%-.192s\' in \'%-.192s\'" }, -{ "ER_WRONG_FIELD_WITH_GROUP", 1055, "\'%-.192s\' isn\'t in GROUP BY" }, -{ "ER_WRONG_GROUP_FIELD", 1056, "Can\'t group on \'%-.192s\'" }, -{ "ER_WRONG_SUM_SELECT", 1057, "Statement has sum functions and columns in same statement" }, -{ "ER_WRONG_VALUE_COUNT", 1058, "Column count doesn\'t match value count" }, -{ "ER_TOO_LONG_IDENT", 1059, "Identifier name \'%-.100T\' is too long" }, -{ "ER_DUP_FIELDNAME", 1060, "Duplicate column name \'%-.192s\'" }, -{ "ER_DUP_KEYNAME", 1061, "Duplicate key name \'%-.192s\'" }, -{ "ER_DUP_ENTRY", 1062, "Duplicate entry \'%-.192T\' for key %d" }, -{ "ER_WRONG_FIELD_SPEC", 1063, "Incorrect column specifier for column \'%-.192s\'" }, -{ "ER_PARSE_ERROR", 1064, "%s near \'%-.80T\' at line %d" }, -{ "ER_EMPTY_QUERY", 1065, "Query was empty" }, -{ "ER_NONUNIQ_TABLE", 1066, "Not unique table/alias: \'%-.192s\'" }, -{ "ER_INVALID_DEFAULT", 1067, "Invalid default value for \'%-.192s\'" }, -{ "ER_MULTIPLE_PRI_KEY", 1068, "Multiple primary key defined" }, -{ "ER_TOO_MANY_KEYS", 1069, "Too many keys specified; max %d keys allowed" }, -{ "ER_TOO_MANY_KEY_PARTS", 1070, "Too many key parts specified; max %d parts allowed" }, -{ "ER_TOO_LONG_KEY", 1071, "Specified key was too long; max key length is %d bytes" }, -{ "ER_KEY_COLUMN_DOES_NOT_EXITS", 1072, "Key column \'%-.192s\' doesn\'t exist in table" }, -{ "ER_BLOB_USED_AS_KEY", 1073, "BLOB column %`s can\'t be used in key specification in the %s table" }, -{ "ER_TOO_BIG_FIELDLENGTH", 1074, "Column length too big for column \'%-.192s\' (max = %lu); use BLOB or TEXT instead" }, -{ "ER_WRONG_AUTO_KEY", 1075, "Incorrect table definition; there can be only one auto column and it must be defined as a key" }, -{ "ER_BINLOG_CANT_DELETE_GTID_DOMAIN", 1076, "Could not delete gtid domain. Reason: %s." }, -{ "ER_NORMAL_SHUTDOWN", 1077, "%s (initiated by: %s): Normal shutdown" }, -{ "ER_GOT_SIGNAL", 1078, "%s: Got signal %d. Aborting!\n" }, -{ "ER_SHUTDOWN_COMPLETE", 1079, "%s: Shutdown complete\n" }, -{ "ER_FORCING_CLOSE", 1080, "%s: Forcing close of thread %ld user: \'%-.48s\'\n" }, -{ "ER_IPSOCK_ERROR", 1081, "Can\'t create IP socket" }, -{ "ER_NO_SUCH_INDEX", 1082, "Table \'%-.192s\' has no index like the one used in CREATE INDEX; recreate the table" }, -{ "ER_WRONG_FIELD_TERMINATORS", 1083, "Field separator argument is not what is expected; check the manual" }, -{ "ER_BLOBS_AND_NO_TERMINATED", 1084, "You can\'t use fixed rowlength with BLOBs; please use \'fields terminated by\'" }, -{ "ER_TEXTFILE_NOT_READABLE", 1085, "The file \'%-.128s\' must be in the database directory or be readable by all" }, -{ "ER_FILE_EXISTS_ERROR", 1086, "File \'%-.200s\' already exists" }, -{ "ER_LOAD_INFO", 1087, "Records: %ld Deleted: %ld Skipped: %ld Warnings: %ld" }, -{ "ER_ALTER_INFO", 1088, "Records: %ld Duplicates: %ld" }, -{ "ER_WRONG_SUB_KEY", 1089, "Incorrect prefix key; the used key part isn\'t a string, the used length is longer than the key part, or the storage engine doesn\'t support unique prefix keys" }, -{ "ER_CANT_REMOVE_ALL_FIELDS", 1090, "You can\'t delete all columns with ALTER TABLE; use DROP TABLE instead" }, -{ "ER_CANT_DROP_FIELD_OR_KEY", 1091, "Can\'t DROP %s %`-.192s; check that it exists" }, -{ "ER_INSERT_INFO", 1092, "Records: %ld Duplicates: %ld Warnings: %ld" }, -{ "ER_UPDATE_TABLE_USED", 1093, "Table \'%-.192s\' is specified twice, both as a target for \'%s\' and as a separate source for data" }, -{ "ER_NO_SUCH_THREAD", 1094, "Unknown thread id: %lu" }, -{ "ER_KILL_DENIED_ERROR", 1095, "You are not owner of thread %lu" }, -{ "ER_NO_TABLES_USED", 1096, "No tables used" }, -{ "ER_TOO_BIG_SET", 1097, "Too many strings for column %-.192s and SET" }, -{ "ER_NO_UNIQUE_LOGFILE", 1098, "Can\'t generate a unique log-filename %-.200s.(1-999)\n" }, -{ "ER_TABLE_NOT_LOCKED_FOR_WRITE", 1099, "Table \'%-.192s\' was locked with a READ lock and can\'t be updated" }, -{ "ER_TABLE_NOT_LOCKED", 1100, "Table \'%-.192s\' was not locked with LOCK TABLES" }, -{ "ER_UNUSED_17", 1101, "You should never see it" }, -{ "ER_WRONG_DB_NAME", 1102, "Incorrect database name \'%-.100T\'" }, -{ "ER_WRONG_TABLE_NAME", 1103, "Incorrect table name \'%-.100s\'" }, -{ "ER_TOO_BIG_SELECT", 1104, "The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay" }, -{ "ER_UNKNOWN_ERROR", 1105, "Unknown error" }, -{ "ER_UNKNOWN_PROCEDURE", 1106, "Unknown procedure \'%-.192s\'" }, -{ "ER_WRONG_PARAMCOUNT_TO_PROCEDURE", 1107, "Incorrect parameter count to procedure \'%-.192s\'" }, -{ "ER_WRONG_PARAMETERS_TO_PROCEDURE", 1108, "Incorrect parameters to procedure \'%-.192s\'" }, -{ "ER_UNKNOWN_TABLE", 1109, "Unknown table \'%-.192s\' in %-.32s" }, -{ "ER_FIELD_SPECIFIED_TWICE", 1110, "Column \'%-.192s\' specified twice" }, -{ "ER_INVALID_GROUP_FUNC_USE", 1111, "Invalid use of group function" }, -{ "ER_UNSUPPORTED_EXTENSION", 1112, "Table \'%-.192s\' uses an extension that doesn\'t exist in this MariaDB version" }, -{ "ER_TABLE_MUST_HAVE_COLUMNS", 1113, "A table must have at least 1 column" }, -{ "ER_RECORD_FILE_FULL", 1114, "The table \'%-.192s\' is full" }, -{ "ER_UNKNOWN_CHARACTER_SET", 1115, "Unknown character set: \'%-.64s\'" }, -{ "ER_TOO_MANY_TABLES", 1116, "Too many tables; MariaDB can only use %d tables in a join" }, -{ "ER_TOO_MANY_FIELDS", 1117, "Too many columns" }, -{ "ER_TOO_BIG_ROWSIZE", 1118, "Row size too large. The maximum row size for the used table type, not counting BLOBs, is %ld. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs" }, -{ "ER_STACK_OVERRUN", 1119, "Thread stack overrun: Used: %ld of a %ld stack. Consider increasing the thread_stack system variable" }, -{ "ER_WRONG_OUTER_JOIN", 1120, "Cross dependency found in OUTER JOIN; examine your ON conditions" }, -{ "ER_NULL_COLUMN_IN_INDEX", 1121, "Table handler doesn\'t support NULL in given index. Please change column \'%-.192s\' to be NOT NULL or use another handler" }, -{ "ER_CANT_FIND_UDF", 1122, "Can\'t load function \'%-.192s\'" }, -{ "ER_CANT_INITIALIZE_UDF", 1123, "Can\'t initialize function \'%-.192s\'; %-.80s" }, -{ "ER_UDF_NO_PATHS", 1124, "No paths allowed for shared library" }, -{ "ER_UDF_EXISTS", 1125, "Function \'%-.192s\' already exists" }, -{ "ER_CANT_OPEN_LIBRARY", 1126, "Can\'t open shared library \'%-.192s\' (errno: %d, %-.128s)" }, -{ "ER_CANT_FIND_DL_ENTRY", 1127, "Can\'t find symbol \'%-.128s\' in library" }, -{ "ER_FUNCTION_NOT_DEFINED", 1128, "Function \'%-.192s\' is not defined" }, -{ "ER_HOST_IS_BLOCKED", 1129, "Host \'%-.64s\' is blocked because of many connection errors; unblock with \'mariadb-admin flush-hosts\'" }, -{ "ER_HOST_NOT_PRIVILEGED", 1130, "Host \'%-.64s\' is not allowed to connect to this MariaDB server" }, -{ "ER_PASSWORD_ANONYMOUS_USER", 1131, "You are using MariaDB as an anonymous user and anonymous users are not allowed to modify user settings" }, -{ "ER_PASSWORD_NOT_ALLOWED", 1132, "You must have privileges to update tables in the mysql database to be able to change passwords for others" }, -{ "ER_PASSWORD_NO_MATCH", 1133, "Can\'t find any matching row in the user table" }, -{ "ER_UPDATE_INFO", 1134, "Rows matched: %ld Changed: %ld Warnings: %ld" }, -{ "ER_CANT_CREATE_THREAD", 1135, "Can\'t create a new thread (errno %M); if you are not out of available memory, you can consult the manual for a possible OS-dependent bug" }, -{ "ER_WRONG_VALUE_COUNT_ON_ROW", 1136, "Column count doesn\'t match value count at row %lu" }, -{ "ER_CANT_REOPEN_TABLE", 1137, "Can\'t reopen table: \'%-.192s\'" }, -{ "ER_INVALID_USE_OF_NULL", 1138, "Invalid use of NULL value" }, -{ "ER_REGEXP_ERROR", 1139, "Regex error \'%s\'" }, -{ "ER_MIX_OF_GROUP_FUNC_AND_FIELDS", 1140, "Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause" }, -{ "ER_NONEXISTING_GRANT", 1141, "There is no such grant defined for user \'%-.48s\' on host \'%-.64s\'" }, -{ "ER_TABLEACCESS_DENIED_ERROR", 1142, "%-.100T command denied to user \'%s\'@\'%s\' for table \'%-.192s\'" }, -{ "ER_COLUMNACCESS_DENIED_ERROR", 1143, "%-.32s command denied to user \'%s\'@\'%s\' for column \'%-.192s\' in table \'%-.192s\'" }, -{ "ER_ILLEGAL_GRANT_FOR_TABLE", 1144, "Illegal GRANT/REVOKE command; please consult the manual to see which privileges can be used" }, -{ "ER_GRANT_WRONG_HOST_OR_USER", 1145, "The host or user argument to GRANT is too long" }, -{ "ER_NO_SUCH_TABLE", 1146, "Table \'%-.192s.%-.192s\' doesn\'t exist" }, -{ "ER_NONEXISTING_TABLE_GRANT", 1147, "There is no such grant defined for user \'%-.48s\' on host \'%-.64s\' on table \'%-.192s\'" }, -{ "ER_NOT_ALLOWED_COMMAND", 1148, "The used command is not allowed with this MariaDB version" }, -{ "ER_SYNTAX_ERROR", 1149, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use" }, -{ "ER_DELAYED_CANT_CHANGE_LOCK", 1150, "Delayed insert thread couldn\'t get requested lock for table %-.192s" }, -{ "ER_TOO_MANY_DELAYED_THREADS", 1151, "Too many delayed threads in use" }, -{ "ER_ABORTING_CONNECTION", 1152, "Aborted connection %ld to db: \'%-.192s\' user: \'%-.48s\' (%-.64s)" }, -{ "ER_NET_PACKET_TOO_LARGE", 1153, "Got a packet bigger than \'max_allowed_packet\' bytes" }, -{ "ER_NET_READ_ERROR_FROM_PIPE", 1154, "Got a read error from the connection pipe" }, -{ "ER_NET_FCNTL_ERROR", 1155, "Got an error from fcntl()" }, -{ "ER_NET_PACKETS_OUT_OF_ORDER", 1156, "Got packets out of order" }, -{ "ER_NET_UNCOMPRESS_ERROR", 1157, "Couldn\'t uncompress communication packet" }, -{ "ER_NET_READ_ERROR", 1158, "Got an error reading communication packets" }, -{ "ER_NET_READ_INTERRUPTED", 1159, "Got timeout reading communication packets" }, -{ "ER_NET_ERROR_ON_WRITE", 1160, "Got an error writing communication packets" }, -{ "ER_NET_WRITE_INTERRUPTED", 1161, "Got timeout writing communication packets" }, -{ "ER_TOO_LONG_STRING", 1162, "Result string is longer than \'max_allowed_packet\' bytes" }, -{ "ER_TABLE_CANT_HANDLE_BLOB", 1163, "Storage engine %s doesn\'t support BLOB/TEXT columns" }, -{ "ER_TABLE_CANT_HANDLE_AUTO_INCREMENT", 1164, "Storage engine %s doesn\'t support AUTO_INCREMENT columns" }, -{ "ER_DELAYED_INSERT_TABLE_LOCKED", 1165, "INSERT DELAYED can\'t be used with table \'%-.192s\' because it is locked with LOCK TABLES" }, -{ "ER_WRONG_COLUMN_NAME", 1166, "Incorrect column name \'%-.100s\'" }, -{ "ER_WRONG_KEY_COLUMN", 1167, "The storage engine %s can\'t index column %`s" }, -{ "ER_WRONG_MRG_TABLE", 1168, "Unable to open underlying table which is differently defined or of non-MyISAM type or doesn\'t exist" }, -{ "ER_DUP_UNIQUE", 1169, "Can\'t write, because of unique constraint, to table \'%-.192s\'" }, -{ "ER_BLOB_KEY_WITHOUT_LENGTH", 1170, "BLOB/TEXT column \'%-.192s\' used in key specification without a key length" }, -{ "ER_PRIMARY_CANT_HAVE_NULL", 1171, "All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead" }, -{ "ER_TOO_MANY_ROWS", 1172, "Result consisted of more than one row" }, -{ "ER_REQUIRES_PRIMARY_KEY", 1173, "This table type requires a primary key" }, -{ "ER_NO_RAID_COMPILED", 1174, "This version of MariaDB is not compiled with RAID support" }, -{ "ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE", 1175, "You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column" }, -{ "ER_KEY_DOES_NOT_EXISTS", 1176, "Key \'%-.192s\' doesn\'t exist in table \'%-.192s\'" }, -{ "ER_CHECK_NO_SUCH_TABLE", 1177, "Can\'t open table" }, -{ "ER_CHECK_NOT_IMPLEMENTED", 1178, "The storage engine for the table doesn\'t support %s" }, -{ "ER_CANT_DO_THIS_DURING_AN_TRANSACTION", 1179, "You are not allowed to execute this command in a transaction" }, -{ "ER_ERROR_DURING_COMMIT", 1180, "Got error %M during COMMIT" }, -{ "ER_ERROR_DURING_ROLLBACK", 1181, "Got error %M during ROLLBACK" }, -{ "ER_ERROR_DURING_FLUSH_LOGS", 1182, "Got error %M during FLUSH_LOGS" }, -{ "ER_ERROR_DURING_CHECKPOINT", 1183, "Got error %M during CHECKPOINT" }, -{ "ER_NEW_ABORTING_CONNECTION", 1184, "Aborted connection %lld to db: \'%-.192s\' user: \'%-.48s\' host: \'%-.64s\' (%-.64s)" }, -{ "ER_UNUSED_10", 1185, "You should never see it" }, -{ "ER_FLUSH_MASTER_BINLOG_CLOSED", 1186, "Binlog closed, cannot RESET MASTER" }, -{ "ER_INDEX_REBUILD", 1187, "Failed rebuilding the index of dumped table \'%-.192s\'" }, -{ "ER_MASTER", 1188, "Error from master: \'%-.64s\'" }, -{ "ER_MASTER_NET_READ", 1189, "Net error reading from master" }, -{ "ER_MASTER_NET_WRITE", 1190, "Net error writing to master" }, -{ "ER_FT_MATCHING_KEY_NOT_FOUND", 1191, "Can\'t find FULLTEXT index matching the column list" }, -{ "ER_LOCK_OR_ACTIVE_TRANSACTION", 1192, "Can\'t execute the given command because you have active locked tables or an active transaction" }, -{ "ER_UNKNOWN_SYSTEM_VARIABLE", 1193, "Unknown system variable \'%-.*s\'" }, -{ "ER_CRASHED_ON_USAGE", 1194, "Table \'%-.192s\' is marked as crashed and should be repaired" }, -{ "ER_CRASHED_ON_REPAIR", 1195, "Table \'%-.192s\' is marked as crashed and last (automatic?) repair failed" }, -{ "ER_WARNING_NOT_COMPLETE_ROLLBACK", 1196, "Some non-transactional changed tables couldn\'t be rolled back" }, -{ "ER_TRANS_CACHE_FULL", 1197, "Multi-statement transaction required more than \'max_binlog_cache_size\' bytes of storage" }, -{ "ER_SLAVE_MUST_STOP", 1198, "This operation cannot be performed as you have a running slave \'%2$*1$s\'; run STOP SLAVE \'%2$*1$s\' first" }, -{ "ER_SLAVE_NOT_RUNNING", 1199, "This operation requires a running slave; configure slave and do START SLAVE" }, -{ "ER_BAD_SLAVE", 1200, "The server is not configured as slave; fix in config file or with CHANGE MASTER TO" }, -{ "ER_MASTER_INFO", 1201, "Could not initialize master info structure for \'%.*s\'; more error messages can be found in the MariaDB error log" }, -{ "ER_SLAVE_THREAD", 1202, "Could not create slave thread; check system resources" }, -{ "ER_TOO_MANY_USER_CONNECTIONS", 1203, "User %-.64s already has more than \'max_user_connections\' active connections" }, -{ "ER_SET_CONSTANTS_ONLY", 1204, "You may only use constant expressions in this statement" }, -{ "ER_LOCK_WAIT_TIMEOUT", 1205, "Lock wait timeout exceeded; try restarting transaction" }, -{ "ER_LOCK_TABLE_FULL", 1206, "The total number of locks exceeds the lock table size" }, -{ "ER_READ_ONLY_TRANSACTION", 1207, "Update locks cannot be acquired during a READ UNCOMMITTED transaction" }, -{ "ER_DROP_DB_WITH_READ_LOCK", 1208, "DROP DATABASE not allowed while thread is holding global read lock" }, -{ "ER_CREATE_DB_WITH_READ_LOCK", 1209, "CREATE DATABASE not allowed while thread is holding global read lock" }, -{ "ER_WRONG_ARGUMENTS", 1210, "Incorrect arguments to %s" }, -{ "ER_NO_PERMISSION_TO_CREATE_USER", 1211, "\'%s\'@\'%s\' is not allowed to create new users" }, -{ "ER_UNION_TABLES_IN_DIFFERENT_DIR", 1212, "Incorrect table definition; all MERGE tables must be in the same database" }, -{ "ER_LOCK_DEADLOCK", 1213, "Deadlock found when trying to get lock; try restarting transaction" }, -{ "ER_TABLE_CANT_HANDLE_FT", 1214, "The storage engine %s doesn\'t support FULLTEXT indexes" }, -{ "ER_CANNOT_ADD_FOREIGN", 1215, "Cannot add foreign key constraint for `%s`" }, -{ "ER_NO_REFERENCED_ROW", 1216, "Cannot add or update a child row: a foreign key constraint fails" }, -{ "ER_ROW_IS_REFERENCED", 1217, "Cannot delete or update a parent row: a foreign key constraint fails" }, -{ "ER_CONNECT_TO_MASTER", 1218, "Error connecting to master: %-.128s" }, -{ "ER_QUERY_ON_MASTER", 1219, "Error running query on master: %-.128s" }, -{ "ER_ERROR_WHEN_EXECUTING_COMMAND", 1220, "Error when executing command %s: %-.128s" }, -{ "ER_WRONG_USAGE", 1221, "Incorrect usage of %s and %s" }, -{ "ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT", 1222, "The used SELECT statements have a different number of columns" }, -{ "ER_CANT_UPDATE_WITH_READLOCK", 1223, "Can\'t execute the query because you have a conflicting read lock" }, -{ "ER_MIXING_NOT_ALLOWED", 1224, "Mixing of transactional and non-transactional tables is disabled" }, -{ "ER_DUP_ARGUMENT", 1225, "Option \'%s\' used twice in statement" }, -{ "ER_USER_LIMIT_REACHED", 1226, "User \'%-.64s\' has exceeded the \'%s\' resource (current value: %ld)" }, -{ "ER_SPECIFIC_ACCESS_DENIED_ERROR", 1227, "Access denied; you need (at least one of) the %-.128s privilege(s) for this operation" }, -{ "ER_LOCAL_VARIABLE", 1228, "Variable \'%-.64s\' is a SESSION variable and can\'t be used with SET GLOBAL" }, -{ "ER_GLOBAL_VARIABLE", 1229, "Variable \'%-.64s\' is a GLOBAL variable and should be set with SET GLOBAL" }, -{ "ER_NO_DEFAULT", 1230, "Variable \'%-.64s\' doesn\'t have a default value" }, -{ "ER_WRONG_VALUE_FOR_VAR", 1231, "Variable \'%-.64s\' can\'t be set to the value of \'%-.200T\'" }, -{ "ER_WRONG_TYPE_FOR_VAR", 1232, "Incorrect argument type to variable \'%-.64s\'" }, -{ "ER_VAR_CANT_BE_READ", 1233, "Variable \'%-.64s\' can only be set, not read" }, -{ "ER_CANT_USE_OPTION_HERE", 1234, "Incorrect usage/placement of \'%s\'" }, -{ "ER_NOT_SUPPORTED_YET", 1235, "This version of MariaDB doesn\'t yet support \'%s\'" }, -{ "ER_MASTER_FATAL_ERROR_READING_BINLOG", 1236, "Got fatal error %d from master when reading data from binary log: \'%-.320s\'" }, -{ "ER_SLAVE_IGNORED_TABLE", 1237, "Slave SQL thread ignored the query because of replicate-*-table rules" }, -{ "ER_INCORRECT_GLOBAL_LOCAL_VAR", 1238, "Variable \'%-.192s\' is a %s variable" }, -{ "ER_WRONG_FK_DEF", 1239, "Incorrect foreign key definition for \'%-.192s\': %s" }, -{ "ER_KEY_REF_DO_NOT_MATCH_TABLE_REF", 1240, "Key reference and table reference don\'t match" }, -{ "ER_OPERAND_COLUMNS", 1241, "Operand should contain %d column(s)" }, -{ "ER_SUBQUERY_NO_1_ROW", 1242, "Subquery returns more than 1 row" }, -{ "ER_UNKNOWN_STMT_HANDLER", 1243, "Unknown prepared statement handler (%.*s) given to %s" }, -{ "ER_CORRUPT_HELP_DB", 1244, "Help database is corrupt or does not exist" }, -{ "ER_CYCLIC_REFERENCE", 1245, "Cyclic reference on subqueries" }, -{ "ER_AUTO_CONVERT", 1246, "Converting column \'%s\' from %s to %s" }, -{ "ER_ILLEGAL_REFERENCE", 1247, "Reference \'%-.64s\' not supported (%s)" }, -{ "ER_DERIVED_MUST_HAVE_ALIAS", 1248, "Every derived table must have its own alias" }, -{ "ER_SELECT_REDUCED", 1249, "Select %u was reduced during optimization" }, -{ "ER_TABLENAME_NOT_ALLOWED_HERE", 1250, "Table \'%-.192s\' from one of the SELECTs cannot be used in %-.32s" }, -{ "ER_NOT_SUPPORTED_AUTH_MODE", 1251, "Client does not support authentication protocol requested by server; consider upgrading MariaDB client" }, -{ "ER_SPATIAL_CANT_HAVE_NULL", 1252, "All parts of a SPATIAL index must be NOT NULL" }, -{ "ER_COLLATION_CHARSET_MISMATCH", 1253, "COLLATION \'%s\' is not valid for CHARACTER SET \'%s\'" }, -{ "ER_SLAVE_WAS_RUNNING", 1254, "Slave is already running" }, -{ "ER_SLAVE_WAS_NOT_RUNNING", 1255, "Slave already has been stopped" }, -{ "ER_TOO_BIG_FOR_UNCOMPRESS", 1256, "Uncompressed data size too large; the maximum size is %d (probably, length of uncompressed data was corrupted)" }, -{ "ER_ZLIB_Z_MEM_ERROR", 1257, "ZLIB: Not enough memory" }, -{ "ER_ZLIB_Z_BUF_ERROR", 1258, "ZLIB: Not enough room in the output buffer (probably, length of uncompressed data was corrupted)" }, -{ "ER_ZLIB_Z_DATA_ERROR", 1259, "ZLIB: Input data corrupted" }, -{ "ER_CUT_VALUE_GROUP_CONCAT", 1260, "Row %u was cut by %s)" }, -{ "ER_WARN_TOO_FEW_RECORDS", 1261, "Row %lu doesn\'t contain data for all columns" }, -{ "ER_WARN_TOO_MANY_RECORDS", 1262, "Row %lu was truncated; it contained more data than there were input columns" }, -{ "ER_WARN_NULL_TO_NOTNULL", 1263, "Column set to default value; NULL supplied to NOT NULL column \'%s\' at row %lu" }, -{ "ER_WARN_DATA_OUT_OF_RANGE", 1264, "Out of range value for column \'%s\' at row %lu" }, -{ "WARN_DATA_TRUNCATED", 1265, "Data truncated for column \'%s\' at row %lu" }, -{ "ER_WARN_USING_OTHER_HANDLER", 1266, "Using storage engine %s for table \'%s\'" }, -{ "ER_CANT_AGGREGATE_2COLLATIONS", 1267, "Illegal mix of collations (%s,%s) and (%s,%s) for operation \'%s\'" }, -{ "ER_DROP_USER", 1268, "Cannot drop one or more of the requested users" }, -{ "ER_REVOKE_GRANTS", 1269, "Can\'t revoke all privileges for one or more of the requested users" }, -{ "ER_CANT_AGGREGATE_3COLLATIONS", 1270, "Illegal mix of collations (%s,%s), (%s,%s), (%s,%s) for operation \'%s\'" }, -{ "ER_CANT_AGGREGATE_NCOLLATIONS", 1271, "Illegal mix of collations for operation \'%s\'" }, -{ "ER_VARIABLE_IS_NOT_STRUCT", 1272, "Variable \'%-.64s\' is not a variable component (can\'t be used as XXXX.variable_name)" }, -{ "ER_UNKNOWN_COLLATION", 1273, "Unknown collation: \'%-.64s\'" }, -{ "ER_SLAVE_IGNORED_SSL_PARAMS", 1274, "SSL parameters in CHANGE MASTER are ignored because this MariaDB slave was compiled without SSL support; they can be used later if MariaDB slave with SSL is started" }, -{ "ER_SERVER_IS_IN_SECURE_AUTH_MODE", 1275, "Server is running in --secure-auth mode, but \'%s\'@\'%s\' has a password in the old format; please change the password to the new format" }, -{ "ER_WARN_FIELD_RESOLVED", 1276, "Field or reference \'%-.192s%s%-.192s%s%-.192s\' of SELECT #%d was resolved in SELECT #%d" }, -{ "ER_BAD_SLAVE_UNTIL_COND", 1277, "Incorrect parameter or combination of parameters for START SLAVE UNTIL" }, -{ "ER_MISSING_SKIP_SLAVE", 1278, "It is recommended to use --skip-slave-start when doing step-by-step replication with START SLAVE UNTIL; otherwise, you will get problems if you get an unexpected slave\'s mariadbd restart" }, -{ "ER_UNTIL_COND_IGNORED", 1279, "SQL thread is not to be started so UNTIL options are ignored" }, -{ "ER_WRONG_NAME_FOR_INDEX", 1280, "Incorrect index name \'%-.100s\'" }, -{ "ER_WRONG_NAME_FOR_CATALOG", 1281, "Incorrect catalog name \'%-.100s\'" }, -{ "ER_WARN_QC_RESIZE", 1282, "Query cache failed to set size %llu; new query cache size is %lu" }, -{ "ER_BAD_FT_COLUMN", 1283, "Column \'%-.192s\' cannot be part of FULLTEXT index" }, -{ "ER_UNKNOWN_KEY_CACHE", 1284, "Unknown key cache \'%-.100s\'" }, -{ "ER_WARN_HOSTNAME_WONT_WORK", 1285, "MariaDB is started in --skip-name-resolve mode; you must restart it without this switch for this grant to work" }, -{ "ER_UNKNOWN_STORAGE_ENGINE", 1286, "Unknown storage engine \'%s\'" }, -{ "ER_WARN_DEPRECATED_SYNTAX", 1287, "\'%s\' is deprecated and will be removed in a future release. Please use %s instead" }, -{ "ER_NON_UPDATABLE_TABLE", 1288, "The target table %-.100s of the %s is not updatable" }, -{ "ER_FEATURE_DISABLED", 1289, "The \'%s\' feature is disabled; you need MariaDB built with \'%s\' to have it working" }, -{ "ER_OPTION_PREVENTS_STATEMENT", 1290, "The MariaDB server is running with the %s option so it cannot execute this statement" }, -{ "ER_DUPLICATED_VALUE_IN_TYPE", 1291, "Column \'%-.100s\' has duplicated value \'%-.64s\' in %s" }, -{ "ER_TRUNCATED_WRONG_VALUE", 1292, "Truncated incorrect %-.32T value: \'%-.128T\'" }, -{ "ER_TOO_MUCH_AUTO_TIMESTAMP_COLS", 1293, "Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause" }, -{ "ER_INVALID_ON_UPDATE", 1294, "Invalid ON UPDATE clause for \'%-.192s\' column" }, -{ "ER_UNSUPPORTED_PS", 1295, "This command is not supported in the prepared statement protocol yet" }, -{ "ER_GET_ERRMSG", 1296, "Got error %d \'%-.200s\' from %s" }, -{ "ER_GET_TEMPORARY_ERRMSG", 1297, "Got temporary error %d \'%-.200s\' from %s" }, -{ "ER_UNKNOWN_TIME_ZONE", 1298, "Unknown or incorrect time zone: \'%-.64s\'" }, -{ "ER_WARN_INVALID_TIMESTAMP", 1299, "Invalid TIMESTAMP value in column \'%s\' at row %lu" }, -{ "ER_INVALID_CHARACTER_STRING", 1300, "Invalid %s character string: \'%.64T\'" }, -{ "ER_WARN_ALLOWED_PACKET_OVERFLOWED", 1301, "Result of %s() was larger than max_allowed_packet (%ld) - truncated" }, -{ "ER_CONFLICTING_DECLARATIONS", 1302, "Conflicting declarations: \'%s%s\' and \'%s%s\'" }, -{ "ER_SP_NO_RECURSIVE_CREATE", 1303, "Can\'t create a %s from within another stored routine" }, -{ "ER_SP_ALREADY_EXISTS", 1304, "%s %s already exists" }, -{ "ER_SP_DOES_NOT_EXIST", 1305, "%s %s does not exist" }, -{ "ER_SP_DROP_FAILED", 1306, "Failed to DROP %s %s" }, -{ "ER_SP_STORE_FAILED", 1307, "Failed to CREATE %s %s" }, -{ "ER_SP_LILABEL_MISMATCH", 1308, "%s with no matching label: %s" }, -{ "ER_SP_LABEL_REDEFINE", 1309, "Redefining label %s" }, -{ "ER_SP_LABEL_MISMATCH", 1310, "End-label %s without match" }, -{ "ER_SP_UNINIT_VAR", 1311, "Referring to uninitialized variable %s" }, -{ "ER_SP_BADSELECT", 1312, "PROCEDURE %s can\'t return a result set in the given context" }, -{ "ER_SP_BADRETURN", 1313, "RETURN is only allowed in a FUNCTION" }, -{ "ER_SP_BADSTATEMENT", 1314, "%s is not allowed in stored procedures" }, -{ "ER_UPDATE_LOG_DEPRECATED_IGNORED", 1315, "The update log is deprecated and replaced by the binary log; SET SQL_LOG_UPDATE has been ignored. This option will be removed in MariaDB 5.6" }, -{ "ER_UPDATE_LOG_DEPRECATED_TRANSLATED", 1316, "The update log is deprecated and replaced by the binary log; SET SQL_LOG_UPDATE has been translated to SET SQL_LOG_BIN. This option will be removed in MariaDB 5.6" }, -{ "ER_QUERY_INTERRUPTED", 1317, "Query execution was interrupted" }, -{ "ER_SP_WRONG_NO_OF_ARGS", 1318, "Incorrect number of arguments for %s %s; expected %u, got %u" }, -{ "ER_SP_COND_MISMATCH", 1319, "Undefined CONDITION: %s" }, -{ "ER_SP_NORETURN", 1320, "No RETURN found in FUNCTION %s" }, -{ "ER_SP_NORETURNEND", 1321, "FUNCTION %s ended without RETURN" }, -{ "ER_SP_BAD_CURSOR_QUERY", 1322, "Cursor statement must be a SELECT" }, -{ "ER_SP_BAD_CURSOR_SELECT", 1323, "Cursor SELECT must not have INTO" }, -{ "ER_SP_CURSOR_MISMATCH", 1324, "Undefined CURSOR: %s" }, -{ "ER_SP_CURSOR_ALREADY_OPEN", 1325, "Cursor is already open" }, -{ "ER_SP_CURSOR_NOT_OPEN", 1326, "Cursor is not open" }, -{ "ER_SP_UNDECLARED_VAR", 1327, "Undeclared variable: %s" }, -{ "ER_SP_WRONG_NO_OF_FETCH_ARGS", 1328, "Incorrect number of FETCH variables" }, -{ "ER_SP_FETCH_NO_DATA", 1329, "No data - zero rows fetched, selected, or processed" }, -{ "ER_SP_DUP_PARAM", 1330, "Duplicate parameter: %s" }, -{ "ER_SP_DUP_VAR", 1331, "Duplicate variable: %s" }, -{ "ER_SP_DUP_COND", 1332, "Duplicate condition: %s" }, -{ "ER_SP_DUP_CURS", 1333, "Duplicate cursor: %s" }, -{ "ER_SP_CANT_ALTER", 1334, "Failed to ALTER %s %s" }, -{ "ER_SP_SUBSELECT_NYI", 1335, "Subquery value not supported" }, -{ "ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG", 1336, "%s is not allowed in stored function or trigger" }, -{ "ER_SP_VARCOND_AFTER_CURSHNDLR", 1337, "Variable or condition declaration after cursor or handler declaration" }, -{ "ER_SP_CURSOR_AFTER_HANDLER", 1338, "Cursor declaration after handler declaration" }, -{ "ER_SP_CASE_NOT_FOUND", 1339, "Case not found for CASE statement" }, -{ "ER_FPARSER_TOO_BIG_FILE", 1340, "Configuration file \'%-.192s\' is too big" }, -{ "ER_FPARSER_BAD_HEADER", 1341, "Malformed file type header in file \'%-.192s\'" }, -{ "ER_FPARSER_EOF_IN_COMMENT", 1342, "Unexpected end of file while parsing comment \'%-.200s\'" }, -{ "ER_FPARSER_ERROR_IN_PARAMETER", 1343, "Error while parsing parameter \'%-.192s\' (line: \'%-.192s\')" }, -{ "ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER", 1344, "Unexpected end of file while skipping unknown parameter \'%-.192s\'" }, -{ "ER_VIEW_NO_EXPLAIN", 1345, "ANALYZE/EXPLAIN/SHOW can not be issued; lacking privileges for underlying table" }, -{ "ER_FRM_UNKNOWN_TYPE", 1346, "File \'%-.192s\' has unknown type \'%-.64s\' in its header" }, -{ "ER_WRONG_OBJECT", 1347, "\'%-.192s.%-.192s\' is not of type \'%s\'" }, -{ "ER_NONUPDATEABLE_COLUMN", 1348, "Column \'%-.192s\' is not updatable" }, -{ "ER_VIEW_SELECT_DERIVED", 1349, "View\'s SELECT contains a subquery in the FROM clause" }, -{ "ER_VIEW_SELECT_CLAUSE", 1350, "View\'s SELECT contains a \'%s\' clause" }, -{ "ER_VIEW_SELECT_VARIABLE", 1351, "View\'s SELECT contains a variable or parameter" }, -{ "ER_VIEW_SELECT_TMPTABLE", 1352, "View\'s SELECT refers to a temporary table \'%-.192s\'" }, -{ "ER_VIEW_WRONG_LIST", 1353, "View\'s SELECT and view\'s field list have different column counts" }, -{ "ER_WARN_VIEW_MERGE", 1354, "View merge algorithm can\'t be used here for now (assumed undefined algorithm)" }, -{ "ER_WARN_VIEW_WITHOUT_KEY", 1355, "View being updated does not have complete key of underlying table in it" }, -{ "ER_VIEW_INVALID", 1356, "View \'%-.192s.%-.192s\' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them" }, -{ "ER_SP_NO_DROP_SP", 1357, "Can\'t drop or alter a %s from within another stored routine" }, -{ "ER_SP_GOTO_IN_HNDLR", 1358, "GOTO is not allowed in a stored procedure handler" }, -{ "ER_TRG_ALREADY_EXISTS", 1359, "Trigger \'%s\' already exists" }, -{ "ER_TRG_DOES_NOT_EXIST", 1360, "Trigger does not exist" }, -{ "ER_TRG_ON_VIEW_OR_TEMP_TABLE", 1361, "Trigger\'s \'%-.192s\' is view or temporary table" }, -{ "ER_TRG_CANT_CHANGE_ROW", 1362, "Updating of %s row is not allowed in %strigger" }, -{ "ER_TRG_NO_SUCH_ROW_IN_TRG", 1363, "There is no %s row in %s trigger" }, -{ "ER_NO_DEFAULT_FOR_FIELD", 1364, "Field \'%-.192s\' doesn\'t have a default value" }, -{ "ER_DIVISION_BY_ZERO", 1365, "Division by 0" }, -{ "ER_TRUNCATED_WRONG_VALUE_FOR_FIELD", 1366, "Incorrect %-.32s value: \'%-.128T\' for column `%.192s`.`%.192s`.`%.192s` at row %lu" }, -{ "ER_ILLEGAL_VALUE_FOR_TYPE", 1367, "Illegal %s \'%-.192T\' value found during parsing" }, -{ "ER_VIEW_NONUPD_CHECK", 1368, "CHECK OPTION on non-updatable view %`-.192s.%`-.192s" }, -{ "ER_VIEW_CHECK_FAILED", 1369, "CHECK OPTION failed %`-.192s.%`-.192s" }, -{ "ER_PROCACCESS_DENIED_ERROR", 1370, "%-.32s command denied to user \'%s\'@\'%s\' for routine \'%-.192s\'" }, -{ "ER_RELAY_LOG_FAIL", 1371, "Failed purging old relay logs: %s" }, -{ "ER_PASSWD_LENGTH", 1372, "Password hash should be a %d-digit hexadecimal number" }, -{ "ER_UNKNOWN_TARGET_BINLOG", 1373, "Target log not found in binlog index" }, -{ "ER_IO_ERR_LOG_INDEX_READ", 1374, "I/O error reading log index file" }, -{ "ER_BINLOG_PURGE_PROHIBITED", 1375, "Server configuration does not permit binlog purge" }, -{ "ER_FSEEK_FAIL", 1376, "Failed on fseek()" }, -{ "ER_BINLOG_PURGE_FATAL_ERR", 1377, "Fatal error during log purge" }, -{ "ER_LOG_IN_USE", 1378, "A purgeable log is in use, will not purge" }, -{ "ER_LOG_PURGE_UNKNOWN_ERR", 1379, "Unknown error during log purge" }, -{ "ER_RELAY_LOG_INIT", 1380, "Failed initializing relay log position: %s" }, -{ "ER_NO_BINARY_LOGGING", 1381, "You are not using binary logging" }, -{ "ER_RESERVED_SYNTAX", 1382, "The \'%-.64s\' syntax is reserved for purposes internal to the MariaDB server" }, -{ "ER_WSAS_FAILED", 1383, "WSAStartup Failed" }, -{ "ER_DIFF_GROUPS_PROC", 1384, "Can\'t handle procedures with different groups yet" }, -{ "ER_NO_GROUP_FOR_PROC", 1385, "Select must have a group with this procedure" }, -{ "ER_ORDER_WITH_PROC", 1386, "Can\'t use ORDER clause with this procedure" }, -{ "ER_LOGGING_PROHIBIT_CHANGING_OF", 1387, "Binary logging and replication forbid changing the global server %s" }, -{ "ER_NO_FILE_MAPPING", 1388, "Can\'t map file: %-.200s, errno: %M" }, -{ "ER_WRONG_MAGIC", 1389, "Wrong magic in %-.64s" }, -{ "ER_PS_MANY_PARAM", 1390, "Prepared statement contains too many placeholders" }, -{ "ER_KEY_PART_0", 1391, "Key part \'%-.192s\' length cannot be 0" }, -{ "ER_VIEW_CHECKSUM", 1392, "View text checksum failed" }, -{ "ER_VIEW_MULTIUPDATE", 1393, "Can not modify more than one base table through a join view \'%-.192s.%-.192s\'" }, -{ "ER_VIEW_NO_INSERT_FIELD_LIST", 1394, "Can not insert into join view \'%-.192s.%-.192s\' without fields list" }, -{ "ER_VIEW_DELETE_MERGE_VIEW", 1395, "Can not delete from join view \'%-.192s.%-.192s\'" }, -{ "ER_CANNOT_USER", 1396, "Operation %s failed for %.256s" }, -{ "ER_XAER_NOTA", 1397, "XAER_NOTA: Unknown XID" }, -{ "ER_XAER_INVAL", 1398, "XAER_INVAL: Invalid arguments (or unsupported command)" }, -{ "ER_XAER_RMFAIL", 1399, "XAER_RMFAIL: The command cannot be executed when global transaction is in the %.64s state" }, -{ "ER_XAER_OUTSIDE", 1400, "XAER_OUTSIDE: Some work is done outside global transaction" }, -{ "ER_XAER_RMERR", 1401, "XAER_RMERR: Fatal error occurred in the transaction branch - check your data for consistency" }, -{ "ER_XA_RBROLLBACK", 1402, "XA_RBROLLBACK: Transaction branch was rolled back" }, -{ "ER_NONEXISTING_PROC_GRANT", 1403, "There is no such grant defined for user \'%-.48s\' on host \'%-.64s\' on routine \'%-.192s\'" }, -{ "ER_PROC_AUTO_GRANT_FAIL", 1404, "Failed to grant EXECUTE and ALTER ROUTINE privileges" }, -{ "ER_PROC_AUTO_REVOKE_FAIL", 1405, "Failed to revoke all privileges to dropped routine" }, -{ "ER_DATA_TOO_LONG", 1406, "Data too long for column \'%s\' at row %lu" }, -{ "ER_SP_BAD_SQLSTATE", 1407, "Bad SQLSTATE: \'%s\'" }, -{ "ER_STARTUP", 1408, "%s: ready for connections.\nVersion: \'%s\' socket: \'%s\' port: %d %s" }, -{ "ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR", 1409, "Can\'t load value from file with fixed size rows to variable" }, -{ "ER_CANT_CREATE_USER_WITH_GRANT", 1410, "You are not allowed to create a user with GRANT" }, -{ "ER_WRONG_VALUE_FOR_TYPE", 1411, "Incorrect %-.32s value: \'%-.128T\' for function %-.32s" }, -{ "ER_TABLE_DEF_CHANGED", 1412, "Table definition has changed, please retry transaction" }, -{ "ER_SP_DUP_HANDLER", 1413, "Duplicate handler declared in the same block" }, -{ "ER_SP_NOT_VAR_ARG", 1414, "OUT or INOUT argument %d for routine %s is not a variable or NEW pseudo-variable in BEFORE trigger" }, -{ "ER_SP_NO_RETSET", 1415, "Not allowed to return a result set from a %s" }, -{ "ER_CANT_CREATE_GEOMETRY_OBJECT", 1416, "Cannot get geometry object from data you send to the GEOMETRY field" }, -{ "ER_FAILED_ROUTINE_BREAK_BINLOG", 1417, "A routine failed and has neither NO SQL nor READS SQL DATA in its declaration and binary logging is enabled; if non-transactional tables were updated, the binary log will miss their changes" }, -{ "ER_BINLOG_UNSAFE_ROUTINE", 1418, "This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)" }, -{ "ER_BINLOG_CREATE_ROUTINE_NEED_SUPER", 1419, "You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)" }, -{ "ER_EXEC_STMT_WITH_OPEN_CURSOR", 1420, "You can\'t execute a prepared statement which has an open cursor associated with it. Reset the statement to re-execute it" }, -{ "ER_STMT_HAS_NO_OPEN_CURSOR", 1421, "The statement (%lu) has no open cursor" }, -{ "ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG", 1422, "Explicit or implicit commit is not allowed in stored function or trigger" }, -{ "ER_NO_DEFAULT_FOR_VIEW_FIELD", 1423, "Field of view \'%-.192s.%-.192s\' underlying table doesn\'t have a default value" }, -{ "ER_SP_NO_RECURSION", 1424, "Recursive stored functions and triggers are not allowed" }, -{ "ER_TOO_BIG_SCALE", 1425, "Too big scale %llu specified for \'%-.192s\'. Maximum is %u" }, -{ "ER_TOO_BIG_PRECISION", 1426, "Too big precision %llu specified for \'%-.192s\'. Maximum is %u" }, -{ "ER_M_BIGGER_THAN_D", 1427, "For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column \'%-.192s\')" }, -{ "ER_WRONG_LOCK_OF_SYSTEM_TABLE", 1428, "You can\'t combine write-locking of system tables with other tables or lock types" }, -{ "ER_CONNECT_TO_FOREIGN_DATA_SOURCE", 1429, "Unable to connect to foreign data source: %.64s" }, -{ "ER_QUERY_ON_FOREIGN_DATA_SOURCE", 1430, "There was a problem processing the query on the foreign data source. Data source error: %-.64s" }, -{ "ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST", 1431, "The foreign data source you are trying to reference does not exist. Data source error: %-.64s" }, -{ "ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE", 1432, "Can\'t create federated table. The data source connection string \'%-.64s\' is not in the correct format" }, -{ "ER_FOREIGN_DATA_STRING_INVALID", 1433, "The data source connection string \'%-.64s\' is not in the correct format" }, -{ "ER_CANT_CREATE_FEDERATED_TABLE", 1434, "Can\'t create federated table. Foreign data src error: %-.64s" }, -{ "ER_TRG_IN_WRONG_SCHEMA", 1435, "Trigger in wrong schema" }, -{ "ER_STACK_OVERRUN_NEED_MORE", 1436, "Thread stack overrun: %ld bytes used of a %ld byte stack, and %ld bytes needed. Consider increasing the thread_stack system variable." }, -{ "ER_TOO_LONG_BODY", 1437, "Routine body for \'%-.100s\' is too long" }, -{ "ER_WARN_CANT_DROP_DEFAULT_KEYCACHE", 1438, "Cannot drop default keycache" }, -{ "ER_TOO_BIG_DISPLAYWIDTH", 1439, "Display width out of range for \'%-.192s\' (max = %lu)" }, -{ "ER_XAER_DUPID", 1440, "XAER_DUPID: The XID already exists" }, -{ "ER_DATETIME_FUNCTION_OVERFLOW", 1441, "Datetime function: %-.32s field overflow" }, -{ "ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG", 1442, "Can\'t update table \'%-.192s\' in stored function/trigger because it is already used by statement which invoked this stored function/trigger" }, -{ "ER_VIEW_PREVENT_UPDATE", 1443, "The definition of table \'%-.192s\' prevents operation %.192s on table \'%-.192s\'" }, -{ "ER_PS_NO_RECURSION", 1444, "The prepared statement contains a stored routine call that refers to that same statement. It\'s not allowed to execute a prepared statement in such a recursive manner" }, -{ "ER_SP_CANT_SET_AUTOCOMMIT", 1445, "Not allowed to set autocommit from a stored function or trigger" }, -{ "ER_MALFORMED_DEFINER", 1446, "Invalid definer" }, -{ "ER_VIEW_FRM_NO_USER", 1447, "View \'%-.192s\'.\'%-.192s\' has no definer information (old table format). Current user is used as definer. Please recreate the view!" }, -{ "ER_VIEW_OTHER_USER", 1448, "You need the SUPER privilege for creation view with \'%-.192s\'@\'%-.192s\' definer" }, -{ "ER_NO_SUCH_USER", 1449, "The user specified as a definer (\'%-.64s\'@\'%-.64s\') does not exist" }, -{ "ER_FORBID_SCHEMA_CHANGE", 1450, "Changing schema from \'%-.192s\' to \'%-.192s\' is not allowed" }, -{ "ER_ROW_IS_REFERENCED_2", 1451, "Cannot delete or update a parent row: a foreign key constraint fails (%.192s)" }, -{ "ER_NO_REFERENCED_ROW_2", 1452, "Cannot add or update a child row: a foreign key constraint fails (%.192s)" }, -{ "ER_SP_BAD_VAR_SHADOW", 1453, "Variable \'%-.64s\' must be quoted with `...`, or renamed" }, -{ "ER_TRG_NO_DEFINER", 1454, "No definer attribute for trigger \'%-.192s\'.\'%-.192s\'. The trigger will be activated under the authorization of the invoker, which may have insufficient privileges. Please recreate the trigger" }, -{ "ER_OLD_FILE_FORMAT", 1455, "\'%-.192s\' has an old format, you should re-create the \'%s\' object(s)" }, -{ "ER_SP_RECURSION_LIMIT", 1456, "Recursive limit %d (as set by the max_sp_recursion_depth variable) was exceeded for routine %.192s" }, -{ "ER_SP_PROC_TABLE_CORRUPT", 1457, "Failed to load routine %-.192s (internal code %d). For more details, run SHOW WARNINGS" }, -{ "ER_SP_WRONG_NAME", 1458, "Incorrect routine name \'%-.192s\'" }, -{ "ER_TABLE_NEEDS_UPGRADE", 1459, "Upgrade required. Please do \"REPAIR %s %`s\" or dump/reload to fix it!" }, -{ "ER_SP_NO_AGGREGATE", 1460, "AGGREGATE is not supported for stored functions" }, -{ "ER_MAX_PREPARED_STMT_COUNT_REACHED", 1461, "Can\'t create more than max_prepared_stmt_count statements (current value: %u)" }, -{ "ER_VIEW_RECURSIVE", 1462, "%`s.%`s contains view recursion" }, -{ "ER_NON_GROUPING_FIELD_USED", 1463, "Non-grouping field \'%-.192s\' is used in %-.64s clause" }, -{ "ER_TABLE_CANT_HANDLE_SPKEYS", 1464, "The storage engine %s doesn\'t support SPATIAL indexes" }, -{ "ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA", 1465, "Triggers can not be created on system tables" }, -{ "ER_REMOVED_SPACES", 1466, "Leading spaces are removed from name \'%s\'" }, -{ "ER_AUTOINC_READ_FAILED", 1467, "Failed to read auto-increment value from storage engine" }, -{ "ER_USERNAME", 1468, "user name" }, -{ "ER_HOSTNAME", 1469, "host name" }, -{ "ER_WRONG_STRING_LENGTH", 1470, "String \'%-.70T\' is too long for %s (should be no longer than %d)" }, -{ "ER_NON_INSERTABLE_TABLE", 1471, "The target table %-.100s of the %s is not insertable-into" }, -{ "ER_ADMIN_WRONG_MRG_TABLE", 1472, "Table \'%-.64s\' is differently defined or of non-MyISAM type or doesn\'t exist" }, -{ "ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT", 1473, "Too high level of nesting for select" }, -{ "ER_NAME_BECOMES_EMPTY", 1474, "Name \'%-.64s\' has become \'\'" }, -{ "ER_AMBIGUOUS_FIELD_TERM", 1475, "First character of the FIELDS TERMINATED string is ambiguous; please use non-optional and non-empty FIELDS ENCLOSED BY" }, -{ "ER_FOREIGN_SERVER_EXISTS", 1476, "The foreign server, %s, you are trying to create already exists" }, -{ "ER_FOREIGN_SERVER_DOESNT_EXIST", 1477, "The foreign server name you are trying to reference does not exist. Data source error: %-.64s" }, -{ "ER_ILLEGAL_HA_CREATE_OPTION", 1478, "Table storage engine \'%-.64s\' does not support the create option \'%.64s\'" }, -{ "ER_PARTITION_REQUIRES_VALUES_ERROR", 1479, "Syntax error: %-.64s PARTITIONING requires definition of VALUES %-.64s for each partition" }, -{ "ER_PARTITION_WRONG_VALUES_ERROR", 1480, "Only %-.64s PARTITIONING can use VALUES %-.64s in partition definition" }, -{ "ER_PARTITION_MAXVALUE_ERROR", 1481, "MAXVALUE can only be used in last partition definition" }, -{ "ER_PARTITION_SUBPARTITION_ERROR", 1482, "Subpartitions can only be hash partitions and by key" }, -{ "ER_PARTITION_SUBPART_MIX_ERROR", 1483, "Must define subpartitions on all partitions if on one partition" }, -{ "ER_PARTITION_WRONG_NO_PART_ERROR", 1484, "Wrong number of partitions defined, mismatch with previous setting" }, -{ "ER_PARTITION_WRONG_NO_SUBPART_ERROR", 1485, "Wrong number of subpartitions defined, mismatch with previous setting" }, -{ "ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR", 1486, "Constant, random or timezone-dependent expressions in (sub)partitioning function are not allowed" }, -{ "ER_NOT_CONSTANT_EXPRESSION", 1487, "Expression in %s must be constant" }, -{ "ER_FIELD_NOT_FOUND_PART_ERROR", 1488, "Field in list of fields for partition function not found in table" }, -{ "ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR", 1489, "List of fields is only allowed in KEY partitions" }, -{ "ER_INCONSISTENT_PARTITION_INFO_ERROR", 1490, "The partition info in the frm file is not consistent with what can be written into the frm file" }, -{ "ER_PARTITION_FUNC_NOT_ALLOWED_ERROR", 1491, "The %-.192s function returns the wrong type" }, -{ "ER_PARTITIONS_MUST_BE_DEFINED_ERROR", 1492, "For %-.64s partitions each partition must be defined" }, -{ "ER_RANGE_NOT_INCREASING_ERROR", 1493, "VALUES LESS THAN value must be strictly increasing for each partition" }, -{ "ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR", 1494, "VALUES value must be of same type as partition function" }, -{ "ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR", 1495, "Multiple definition of same constant in list partitioning" }, -{ "ER_PARTITION_ENTRY_ERROR", 1496, "Partitioning can not be used stand-alone in query" }, -{ "ER_MIX_HANDLER_ERROR", 1497, "The mix of handlers in the partitions is not allowed in this version of MariaDB" }, -{ "ER_PARTITION_NOT_DEFINED_ERROR", 1498, "For the partitioned engine it is necessary to define all %-.64s" }, -{ "ER_TOO_MANY_PARTITIONS_ERROR", 1499, "Too many partitions (including subpartitions) were defined" }, -{ "ER_SUBPARTITION_ERROR", 1500, "It is only possible to mix RANGE/LIST partitioning with HASH/KEY partitioning for subpartitioning" }, -{ "ER_CANT_CREATE_HANDLER_FILE", 1501, "Failed to create specific handler file" }, -{ "ER_BLOB_FIELD_IN_PART_FUNC_ERROR", 1502, "A BLOB field is not allowed in partition function" }, -{ "ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF", 1503, "A %-.192s must include all columns in the table\'s partitioning function" }, -{ "ER_NO_PARTS_ERROR", 1504, "Number of %-.64s = 0 is not an allowed value" }, -{ "ER_PARTITION_MGMT_ON_NONPARTITIONED", 1505, "Partition management on a not partitioned table is not possible" }, -{ "ER_FEATURE_NOT_SUPPORTED_WITH_PARTITIONING", 1506, "Partitioned tables do not support %s" }, -{ "ER_DROP_PARTITION_NON_EXISTENT", 1507, "Error in list of partitions to %-.64s" }, -{ "ER_DROP_LAST_PARTITION", 1508, "Cannot remove all partitions, use DROP TABLE instead" }, -{ "ER_COALESCE_ONLY_ON_HASH_PARTITION", 1509, "COALESCE PARTITION can only be used on HASH/KEY partitions" }, -{ "ER_REORG_HASH_ONLY_ON_SAME_NO", 1510, "REORGANIZE PARTITION can only be used to reorganize partitions not to change their numbers" }, -{ "ER_REORG_NO_PARAM_ERROR", 1511, "REORGANIZE PARTITION without parameters can only be used on auto-partitioned tables using HASH PARTITIONs" }, -{ "ER_ONLY_ON_RANGE_LIST_PARTITION", 1512, "%-.64s PARTITION can only be used on RANGE/LIST partitions" }, -{ "ER_ADD_PARTITION_SUBPART_ERROR", 1513, "Trying to Add partition(s) with wrong number of subpartitions" }, -{ "ER_ADD_PARTITION_NO_NEW_PARTITION", 1514, "At least one partition must be added" }, -{ "ER_COALESCE_PARTITION_NO_PARTITION", 1515, "At least one partition must be coalesced" }, -{ "ER_REORG_PARTITION_NOT_EXIST", 1516, "More partitions to reorganize than there are partitions" }, -{ "ER_SAME_NAME_PARTITION", 1517, "Duplicate partition name %-.192s" }, -{ "ER_NO_BINLOG_ERROR", 1518, "It is not allowed to shut off binlog on this command" }, -{ "ER_CONSECUTIVE_REORG_PARTITIONS", 1519, "When reorganizing a set of partitions they must be in consecutive order" }, -{ "ER_REORG_OUTSIDE_RANGE", 1520, "Reorganize of range partitions cannot change total ranges except for last partition where it can extend the range" }, -{ "ER_PARTITION_FUNCTION_FAILURE", 1521, "Partition function not supported in this version for this handler" }, -{ "ER_PART_STATE_ERROR", 1522, "Partition state cannot be defined from CREATE/ALTER TABLE" }, -{ "ER_LIMITED_PART_RANGE", 1523, "The %-.64s handler only supports 32 bit integers in VALUES" }, -{ "ER_PLUGIN_IS_NOT_LOADED", 1524, "Plugin \'%-.192s\' is not loaded" }, -{ "ER_WRONG_VALUE", 1525, "Incorrect %-.32s value: \'%-.128T\'" }, -{ "ER_NO_PARTITION_FOR_GIVEN_VALUE", 1526, "Table has no partition for value %-.64s" }, -{ "ER_FILEGROUP_OPTION_ONLY_ONCE", 1527, "It is not allowed to specify %s more than once" }, -{ "ER_CREATE_FILEGROUP_FAILED", 1528, "Failed to create %s" }, -{ "ER_DROP_FILEGROUP_FAILED", 1529, "Failed to drop %s" }, -{ "ER_TABLESPACE_AUTO_EXTEND_ERROR", 1530, "The handler doesn\'t support autoextend of tablespaces" }, -{ "ER_WRONG_SIZE_NUMBER", 1531, "A size parameter was incorrectly specified, either number or on the form 10M" }, -{ "ER_SIZE_OVERFLOW_ERROR", 1532, "The size number was correct but we don\'t allow the digit part to be more than 2 billion" }, -{ "ER_ALTER_FILEGROUP_FAILED", 1533, "Failed to alter: %s" }, -{ "ER_BINLOG_ROW_LOGGING_FAILED", 1534, "Writing one row to the row-based binary log failed" }, -{ "ER_BINLOG_ROW_WRONG_TABLE_DEF", 1535, "Table definition on master and slave does not match: %s" }, -{ "ER_BINLOG_ROW_RBR_TO_SBR", 1536, "Slave running with --log-slave-updates must use row-based binary logging to be able to replicate row-based binary log events" }, -{ "ER_EVENT_ALREADY_EXISTS", 1537, "Event \'%-.192s\' already exists" }, -{ "ER_EVENT_STORE_FAILED", 1538, "Failed to store event %s. Error code %M from storage engine" }, -{ "ER_EVENT_DOES_NOT_EXIST", 1539, "Unknown event \'%-.192s\'" }, -{ "ER_EVENT_CANT_ALTER", 1540, "Failed to alter event \'%-.192s\'" }, -{ "ER_EVENT_DROP_FAILED", 1541, "Failed to drop %s" }, -{ "ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG", 1542, "INTERVAL is either not positive or too big" }, -{ "ER_EVENT_ENDS_BEFORE_STARTS", 1543, "ENDS is either invalid or before STARTS" }, -{ "ER_EVENT_EXEC_TIME_IN_THE_PAST", 1544, "Event execution time is in the past. Event has been disabled" }, -{ "ER_EVENT_OPEN_TABLE_FAILED", 1545, "Failed to open mysql.event" }, -{ "ER_EVENT_NEITHER_M_EXPR_NOR_M_AT", 1546, "No datetime expression provided" }, -{ "ER_UNUSED_2", 1547, "You should never see it" }, -{ "ER_UNUSED_3", 1548, "You should never see it" }, -{ "ER_EVENT_CANNOT_DELETE", 1549, "Failed to delete the event from mysql.event" }, -{ "ER_EVENT_COMPILE_ERROR", 1550, "Error during compilation of event\'s body" }, -{ "ER_EVENT_SAME_NAME", 1551, "Same old and new event name" }, -{ "ER_EVENT_DATA_TOO_LONG", 1552, "Data for column \'%s\' too long" }, -{ "ER_DROP_INDEX_FK", 1553, "Cannot drop index \'%-.192s\': needed in a foreign key constraint" }, -{ "ER_WARN_DEPRECATED_SYNTAX_WITH_VER", 1554, "The syntax \'%s\' is deprecated and will be removed in MariaDB %s. Please use %s instead" }, -{ "ER_CANT_WRITE_LOCK_LOG_TABLE", 1555, "You can\'t write-lock a log table. Only read access is possible" }, -{ "ER_CANT_LOCK_LOG_TABLE", 1556, "You can\'t use locks with log tables" }, -{ "ER_UNUSED_4", 1557, "You should never see it" }, -{ "ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE", 1558, "Column count of mysql.%s is wrong. Expected %d, found %d. Created with MariaDB %d, now running %d. Please use mariadb-upgrade to fix this error" }, -{ "ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR", 1559, "Cannot switch out of the row-based binary log format when the session has open temporary tables" }, -{ "ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT", 1560, "Cannot change the binary logging format inside a stored function or trigger" }, -{ "ER_UNUSED_13", 1561, "You should never see it" }, -{ "ER_PARTITION_NO_TEMPORARY", 1562, "Cannot create temporary table with partitions" }, -{ "ER_PARTITION_CONST_DOMAIN_ERROR", 1563, "Partition constant is out of partition function domain" }, -{ "ER_PARTITION_FUNCTION_IS_NOT_ALLOWED", 1564, "This partition function is not allowed" }, -{ "ER_DDL_LOG_ERROR", 1565, "Error in DDL log" }, -{ "ER_NULL_IN_VALUES_LESS_THAN", 1566, "Not allowed to use NULL value in VALUES LESS THAN" }, -{ "ER_WRONG_PARTITION_NAME", 1567, "Incorrect partition name" }, -{ "ER_CANT_CHANGE_TX_CHARACTERISTICS", 1568, "Transaction characteristics can\'t be changed while a transaction is in progress" }, -{ "ER_DUP_ENTRY_AUTOINCREMENT_CASE", 1569, "ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry \'%-.192T\' for key \'%-.192s\'" }, -{ "ER_EVENT_MODIFY_QUEUE_ERROR", 1570, "Internal scheduler error %d" }, -{ "ER_EVENT_SET_VAR_ERROR", 1571, "Error during starting/stopping of the scheduler. Error code %M" }, -{ "ER_PARTITION_MERGE_ERROR", 1572, "Engine cannot be used in partitioned tables" }, -{ "ER_CANT_ACTIVATE_LOG", 1573, "Cannot activate \'%-.64s\' log" }, -{ "ER_RBR_NOT_AVAILABLE", 1574, "The server was not built with row-based replication" }, -{ "ER_BASE64_DECODE_ERROR", 1575, "Decoding of base64 string failed" }, -{ "ER_EVENT_RECURSION_FORBIDDEN", 1576, "Recursion of EVENT DDL statements is forbidden when body is present" }, -{ "ER_EVENTS_DB_ERROR", 1577, "Cannot proceed, because event scheduler is disabled" }, -{ "ER_ONLY_INTEGERS_ALLOWED", 1578, "Only integers allowed as number here" }, -{ "ER_UNSUPORTED_LOG_ENGINE", 1579, "Storage engine %s cannot be used for log tables" }, -{ "ER_BAD_LOG_STATEMENT", 1580, "You cannot \'%s\' a log table if logging is enabled" }, -{ "ER_CANT_RENAME_LOG_TABLE", 1581, "Cannot rename \'%s\'. When logging enabled, rename to/from log table must rename two tables: the log table to an archive table and another table back to \'%s\'" }, -{ "ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT", 1582, "Incorrect parameter count in the call to native function \'%-.192s\'" }, -{ "ER_WRONG_PARAMETERS_TO_NATIVE_FCT", 1583, "Incorrect parameters in the call to native function \'%-.192s\'" }, -{ "ER_WRONG_PARAMETERS_TO_STORED_FCT", 1584, "Incorrect parameters in the call to stored function \'%-.192s\'" }, -{ "ER_NATIVE_FCT_NAME_COLLISION", 1585, "This function \'%-.192s\' has the same name as a native function" }, -{ "ER_DUP_ENTRY_WITH_KEY_NAME", 1586, "Duplicate entry \'%-.64T\' for key \'%-.192s\'" }, -{ "ER_BINLOG_PURGE_EMFILE", 1587, "Too many files opened, please execute the command again" }, -{ "ER_EVENT_CANNOT_CREATE_IN_THE_PAST", 1588, "Event execution time is in the past and ON COMPLETION NOT PRESERVE is set. The event was dropped immediately after creation" }, -{ "ER_EVENT_CANNOT_ALTER_IN_THE_PAST", 1589, "Event execution time is in the past and ON COMPLETION NOT PRESERVE is set. The event was not changed. Specify a time in the future" }, -{ "ER_SLAVE_INCIDENT", 1590, "The incident %s occurred on the master. Message: %-.64s" }, -{ "ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT", 1591, "Table has no partition for some existing values" }, -{ "ER_BINLOG_UNSAFE_STATEMENT", 1592, "Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. %s" }, -{ "ER_SLAVE_FATAL_ERROR", 1593, "Fatal error: %s" }, -{ "ER_SLAVE_RELAY_LOG_READ_FAILURE", 1594, "Relay log read failure: %s" }, -{ "ER_SLAVE_RELAY_LOG_WRITE_FAILURE", 1595, "Relay log write failure: %s" }, -{ "ER_SLAVE_CREATE_EVENT_FAILURE", 1596, "Failed to create %s" }, -{ "ER_SLAVE_MASTER_COM_FAILURE", 1597, "Master command %s failed: %s" }, -{ "ER_BINLOG_LOGGING_IMPOSSIBLE", 1598, "Binary logging not possible. Message: %s" }, -{ "ER_VIEW_NO_CREATION_CTX", 1599, "View %`s.%`s has no creation context" }, -{ "ER_VIEW_INVALID_CREATION_CTX", 1600, "Creation context of view %`s.%`s is invalid" }, -{ "ER_SR_INVALID_CREATION_CTX", 1601, "Creation context of stored routine %`s.%`s is invalid" }, -{ "ER_TRG_CORRUPTED_FILE", 1602, "Corrupted TRG file for table %`s.%`s" }, -{ "ER_TRG_NO_CREATION_CTX", 1603, "Triggers for table %`s.%`s have no creation context" }, -{ "ER_TRG_INVALID_CREATION_CTX", 1604, "Trigger creation context of table %`s.%`s is invalid" }, -{ "ER_EVENT_INVALID_CREATION_CTX", 1605, "Creation context of event %`s.%`s is invalid" }, -{ "ER_TRG_CANT_OPEN_TABLE", 1606, "Cannot open table for trigger %`s.%`s" }, -{ "ER_CANT_CREATE_SROUTINE", 1607, "Cannot create stored routine %`s. Check warnings" }, -{ "ER_UNUSED_11", 1608, "You should never see it" }, -{ "ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT", 1609, "The BINLOG statement of type %s was not preceded by a format description BINLOG statement" }, -{ "ER_SLAVE_CORRUPT_EVENT", 1610, "Corrupted replication event was detected" }, -{ "ER_LOAD_DATA_INVALID_COLUMN", 1611, "Invalid column reference (%-.64s) in LOAD DATA" }, -{ "ER_LOG_PURGE_NO_FILE", 1612, "Being purged log %s was not found" }, -{ "ER_XA_RBTIMEOUT", 1613, "XA_RBTIMEOUT: Transaction branch was rolled back: took too long" }, -{ "ER_XA_RBDEADLOCK", 1614, "XA_RBDEADLOCK: Transaction branch was rolled back: deadlock was detected" }, -{ "ER_NEED_REPREPARE", 1615, "Prepared statement needs to be re-prepared" }, -{ "ER_DELAYED_NOT_SUPPORTED", 1616, "DELAYED option not supported for table \'%-.192s\'" }, -{ "WARN_NO_MASTER_INFO", 1617, "There is no master connection \'%.*s\'" }, -{ "WARN_OPTION_IGNORED", 1618, "<%-.64s> option ignored" }, -{ "ER_PLUGIN_DELETE_BUILTIN", 1619, "Built-in plugins cannot be deleted" }, -{ "WARN_PLUGIN_BUSY", 1620, "Plugin is busy and will be uninstalled on shutdown" }, -{ "ER_VARIABLE_IS_READONLY", 1621, "%s variable \'%s\' is read-only. Use SET %s to assign the value" }, -{ "ER_WARN_ENGINE_TRANSACTION_ROLLBACK", 1622, "Storage engine %s does not support rollback for this statement. Transaction rolled back and must be restarted" }, -{ "ER_SLAVE_HEARTBEAT_FAILURE", 1623, "Unexpected master\'s heartbeat data: %s" }, -{ "ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE", 1624, "The requested value for the heartbeat period is either negative or exceeds the maximum allowed (%u seconds)" }, -{ "ER_UNUSED_14", 1625, "You should never see it" }, -{ "ER_CONFLICT_FN_PARSE_ERROR", 1626, "Error in parsing conflict function. Message: %-.64s" }, -{ "ER_EXCEPTIONS_WRITE_ERROR", 1627, "Write to exceptions table failed. Message: %-.128s\"" }, -{ "ER_TOO_LONG_TABLE_COMMENT", 1628, "Comment for table \'%-.64s\' is too long (max = %u)" }, -{ "ER_TOO_LONG_FIELD_COMMENT", 1629, "Comment for field \'%-.64s\' is too long (max = %u)" }, -{ "ER_FUNC_INEXISTENT_NAME_COLLISION", 1630, "FUNCTION %s does not exist. Check the \'Function Name Parsing and Resolution\' section in the Reference Manual" }, -{ "ER_DATABASE_NAME", 1631, "Database" }, -{ "ER_TABLE_NAME", 1632, "Table" }, -{ "ER_PARTITION_NAME", 1633, "Partition" }, -{ "ER_SUBPARTITION_NAME", 1634, "Subpartition" }, -{ "ER_TEMPORARY_NAME", 1635, "Temporary" }, -{ "ER_RENAMED_NAME", 1636, "Renamed" }, -{ "ER_TOO_MANY_CONCURRENT_TRXS", 1637, "Too many active concurrent transactions" }, -{ "WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED", 1638, "Non-ASCII separator arguments are not fully supported" }, -{ "ER_DEBUG_SYNC_TIMEOUT", 1639, "debug sync point wait timed out" }, -{ "ER_DEBUG_SYNC_HIT_LIMIT", 1640, "debug sync point hit limit reached" }, -{ "ER_DUP_SIGNAL_SET", 1641, "Duplicate condition information item \'%s\'" }, -{ "ER_SIGNAL_WARN", 1642, "Unhandled user-defined warning condition" }, -{ "ER_SIGNAL_NOT_FOUND", 1643, "Unhandled user-defined not found condition" }, -{ "ER_SIGNAL_EXCEPTION", 1644, "Unhandled user-defined exception condition" }, -{ "ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER", 1645, "RESIGNAL when handler not active" }, -{ "ER_SIGNAL_BAD_CONDITION_TYPE", 1646, "SIGNAL/RESIGNAL can only use a CONDITION defined with SQLSTATE" }, -{ "WARN_COND_ITEM_TRUNCATED", 1647, "Data truncated for condition item \'%s\'" }, -{ "ER_COND_ITEM_TOO_LONG", 1648, "Data too long for condition item \'%s\'" }, -{ "ER_UNKNOWN_LOCALE", 1649, "Unknown locale: \'%-.64s\'" }, -{ "ER_SLAVE_IGNORE_SERVER_IDS", 1650, "The requested server id %d clashes with the slave startup option --replicate-same-server-id" }, -{ "ER_QUERY_CACHE_DISABLED", 1651, "Query cache is disabled; set query_cache_type to ON or DEMAND to enable it" }, -{ "ER_SAME_NAME_PARTITION_FIELD", 1652, "Duplicate partition field name \'%-.192s\'" }, -{ "ER_PARTITION_COLUMN_LIST_ERROR", 1653, "Inconsistency in usage of column lists for partitioning" }, -{ "ER_WRONG_TYPE_COLUMN_VALUE_ERROR", 1654, "Partition column values of incorrect type" }, -{ "ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR", 1655, "Too many fields in \'%-.192s\'" }, -{ "ER_MAXVALUE_IN_VALUES_IN", 1656, "Cannot use MAXVALUE as value in VALUES IN" }, -{ "ER_TOO_MANY_VALUES_ERROR", 1657, "Cannot have more than one value for this type of %-.64s partitioning" }, -{ "ER_ROW_SINGLE_PARTITION_FIELD_ERROR", 1658, "Row expressions in VALUES IN only allowed for multi-field column partitioning" }, -{ "ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD", 1659, "Field \'%-.192s\' is of a not allowed type for this type of partitioning" }, -{ "ER_PARTITION_FIELDS_TOO_LONG", 1660, "The total length of the partitioning fields is too large" }, -{ "ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE", 1661, "Cannot execute statement: impossible to write to binary log since both row-incapable engines and statement-incapable engines are involved" }, -{ "ER_BINLOG_ROW_MODE_AND_STMT_ENGINE", 1662, "Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = ROW and at least one table uses a storage engine limited to statement-based logging" }, -{ "ER_BINLOG_UNSAFE_AND_STMT_ENGINE", 1663, "Cannot execute statement: impossible to write to binary log since statement is unsafe, storage engine is limited to statement-based logging, and BINLOG_FORMAT = MIXED. %s" }, -{ "ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE", 1664, "Cannot execute statement: impossible to write to binary log since statement is in row format and at least one table uses a storage engine limited to statement-based logging" }, -{ "ER_BINLOG_STMT_MODE_AND_ROW_ENGINE", 1665, "Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a storage engine limited to row-based logging.%s" }, -{ "ER_BINLOG_ROW_INJECTION_AND_STMT_MODE", 1666, "Cannot execute statement: impossible to write to binary log since statement is in row format and BINLOG_FORMAT = STATEMENT" }, -{ "ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE", 1667, "Cannot execute statement: impossible to write to binary log since more than one engine is involved and at least one engine is self-logging" }, -{ "ER_BINLOG_UNSAFE_LIMIT", 1668, "The statement is unsafe because it uses a LIMIT clause. This is unsafe because the set of rows included cannot be predicted" }, -{ "ER_BINLOG_UNSAFE_INSERT_DELAYED", 1669, "The statement is unsafe because it uses INSERT DELAYED. This is unsafe because the times when rows are inserted cannot be predicted" }, -{ "ER_BINLOG_UNSAFE_SYSTEM_TABLE", 1670, "The statement is unsafe because it uses the general log, slow query log, or performance_schema table(s). This is unsafe because system tables may differ on slaves" }, -{ "ER_BINLOG_UNSAFE_AUTOINC_COLUMNS", 1671, "Statement is unsafe because it invokes a trigger or a stored function that inserts into an AUTO_INCREMENT column. Inserted values cannot be logged correctly" }, -{ "ER_BINLOG_UNSAFE_UDF", 1672, "Statement is unsafe because it uses a UDF which may not return the same value on the slave" }, -{ "ER_BINLOG_UNSAFE_SYSTEM_VARIABLE", 1673, "Statement is unsafe because it uses a system variable that may have a different value on the slave" }, -{ "ER_BINLOG_UNSAFE_SYSTEM_FUNCTION", 1674, "Statement is unsafe because it uses a system function that may return a different value on the slave" }, -{ "ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS", 1675, "Statement is unsafe because it accesses a non-transactional table after accessing a transactional table within the same transaction" }, -{ "ER_MESSAGE_AND_STATEMENT", 1676, "%s Statement: %s" }, -{ "ER_SLAVE_CONVERSION_FAILED", 1677, "Column %d of table \'%-.192s.%-.192s\' cannot be converted from type \'%-.50s\' to type \'%-.50s\'" }, -{ "ER_SLAVE_CANT_CREATE_CONVERSION", 1678, "Can\'t create conversion table for table \'%-.192s.%-.192s\'" }, -{ "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT", 1679, "Cannot modify @@session.binlog_format inside a transaction" }, -{ "ER_PATH_LENGTH", 1680, "The path specified for %.64T is too long" }, -{ "ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT", 1681, "\'%s\' is deprecated and will be removed in a future release" }, -{ "ER_WRONG_NATIVE_TABLE_STRUCTURE", 1682, "Native table \'%-.64s\'.\'%-.64s\' has the wrong structure" }, -{ "ER_WRONG_PERFSCHEMA_USAGE", 1683, "Invalid performance_schema usage" }, -{ "ER_WARN_I_S_SKIPPED_TABLE", 1684, "Table \'%s\'.\'%s\' was skipped since its definition is being modified by concurrent DDL statement" }, -{ "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT", 1685, "Cannot modify @@session.binlog_direct_non_transactional_updates inside a transaction" }, -{ "ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT", 1686, "Cannot change the binlog direct flag inside a stored function or trigger" }, -{ "ER_SPATIAL_MUST_HAVE_GEOM_COL", 1687, "A SPATIAL index may only contain a geometrical type column" }, -{ "ER_TOO_LONG_INDEX_COMMENT", 1688, "Comment for index \'%-.64s\' is too long (max = %lu)" }, -{ "ER_LOCK_ABORTED", 1689, "Wait on a lock was aborted due to a pending exclusive lock" }, -{ "ER_DATA_OUT_OF_RANGE", 1690, "%s value is out of range in \'%s\'" }, -{ "ER_WRONG_SPVAR_TYPE_IN_LIMIT", 1691, "A variable of a non-integer based type in LIMIT clause" }, -{ "ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE", 1692, "Mixing self-logging and non-self-logging engines in a statement is unsafe" }, -{ "ER_BINLOG_UNSAFE_MIXED_STATEMENT", 1693, "Statement accesses nontransactional table as well as transactional or temporary table, and writes to any of them" }, -{ "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN", 1694, "Cannot modify @@session.sql_log_bin inside a transaction" }, -{ "ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN", 1695, "Cannot change the sql_log_bin inside a stored function or trigger" }, -{ "ER_FAILED_READ_FROM_PAR_FILE", 1696, "Failed to read from the .par file" }, -{ "ER_VALUES_IS_NOT_INT_TYPE_ERROR", 1697, "VALUES value for partition \'%-.64s\' must have type INT" }, -{ "ER_ACCESS_DENIED_NO_PASSWORD_ERROR", 1698, "Access denied for user \'%s\'@\'%s\'" }, -{ "ER_SET_PASSWORD_AUTH_PLUGIN", 1699, "SET PASSWORD is ignored for users authenticating via %s plugin" }, -{ "ER_GRANT_PLUGIN_USER_EXISTS", 1700, "GRANT with IDENTIFIED WITH is illegal because the user %-.*s already exists" }, -{ "ER_TRUNCATE_ILLEGAL_FK", 1701, "Cannot truncate a table referenced in a foreign key constraint (%.192s)" }, -{ "ER_PLUGIN_IS_PERMANENT", 1702, "Plugin \'%s\' is force_plus_permanent and can not be unloaded" }, -{ "ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN", 1703, "The requested value for the heartbeat period is less than 1 millisecond. The value is reset to 0, meaning that heartbeating will effectively be disabled" }, -{ "ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX", 1704, "The requested value for the heartbeat period exceeds the value of `slave_net_timeout\' seconds. A sensible value for the period should be less than the timeout" }, -{ "ER_STMT_CACHE_FULL", 1705, "Multi-row statements required more than \'max_binlog_stmt_cache_size\' bytes of storage." }, -{ "ER_MULTI_UPDATE_KEY_CONFLICT", 1706, "Primary key/partition key update is not allowed since the table is updated both as \'%-.192s\' and \'%-.192s\'" }, -{ "ER_TABLE_NEEDS_REBUILD", 1707, "Table rebuild required. Please do \"ALTER TABLE %`s FORCE\" or dump/reload to fix it!" }, -{ "WARN_OPTION_BELOW_LIMIT", 1708, "The value of \'%s\' should be no less than the value of \'%s\'" }, -{ "ER_INDEX_COLUMN_TOO_LONG", 1709, "Index column size too large. The maximum column size is %lu bytes" }, -{ "ER_ERROR_IN_TRIGGER_BODY", 1710, "Trigger \'%-.64s\' has an error in its body: \'%-.256s\'" }, -{ "ER_ERROR_IN_UNKNOWN_TRIGGER_BODY", 1711, "Unknown trigger has an error in its body: \'%-.256s\'" }, -{ "ER_INDEX_CORRUPT", 1712, "Index %s is corrupted" }, -{ "ER_UNDO_RECORD_TOO_BIG", 1713, "Undo log record is too big" }, -{ "ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT", 1714, "INSERT IGNORE... SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE", 1715, "INSERT... SELECT... ON DUPLICATE KEY UPDATE is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are updated. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_BINLOG_UNSAFE_REPLACE_SELECT", 1716, "REPLACE... SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are replaced. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT", 1717, "CREATE... IGNORE SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT", 1718, "CREATE... REPLACE SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are replaced. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_BINLOG_UNSAFE_UPDATE_IGNORE", 1719, "UPDATE IGNORE is unsafe because the order in which rows are updated determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_UNUSED_15", 1720, "You should never see it" }, -{ "ER_UNUSED_16", 1721, "You should never see it" }, -{ "ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT", 1722, "Statements writing to a table with an auto-increment column after selecting from another table are unsafe because the order in which rows are retrieved determines what (if any) rows will be written. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC", 1723, "CREATE TABLE... SELECT... on a table with an auto-increment column is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are inserted. This order cannot be predicted and may differ on master and the slave" }, -{ "ER_BINLOG_UNSAFE_INSERT_TWO_KEYS", 1724, "INSERT... ON DUPLICATE KEY UPDATE on a table with more than one UNIQUE KEY is unsafe" }, -{ "ER_TABLE_IN_FK_CHECK", 1725, "Table is being used in foreign key check" }, -{ "ER_UNUSED_1", 1726, "You should never see it" }, -{ "ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST", 1727, "INSERT into autoincrement field which is not the first part in the composed primary key is unsafe" }, -{ "ER_CANNOT_LOAD_FROM_TABLE_V2", 1728, "Cannot load from %s.%s. The table is probably corrupted" }, -{ "ER_MASTER_DELAY_VALUE_OUT_OF_RANGE", 1729, "The requested value %lu for the master delay exceeds the maximum %lu" }, -{ "ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT", 1730, "Only Format_description_log_event and row events are allowed in BINLOG statements (but %s was provided)" }, -{ "ER_PARTITION_EXCHANGE_DIFFERENT_OPTION", 1731, "Non matching attribute \'%-.64s\' between partition and table" }, -{ "ER_PARTITION_EXCHANGE_PART_TABLE", 1732, "Table to exchange with partition is partitioned: \'%-.64s\'" }, -{ "ER_PARTITION_EXCHANGE_TEMP_TABLE", 1733, "Table to exchange with partition is temporary: \'%-.64s\'" }, -{ "ER_PARTITION_INSTEAD_OF_SUBPARTITION", 1734, "Subpartitioned table, use subpartition instead of partition" }, -{ "ER_UNKNOWN_PARTITION", 1735, "Unknown partition \'%-.64s\' in table \'%-.64s\'" }, -{ "ER_TABLES_DIFFERENT_METADATA", 1736, "Tables have different definitions" }, -{ "ER_ROW_DOES_NOT_MATCH_PARTITION", 1737, "Found a row that does not match the partition" }, -{ "ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX", 1738, "Option binlog_cache_size (%lu) is greater than max_binlog_cache_size (%lu); setting binlog_cache_size equal to max_binlog_cache_size" }, -{ "ER_WARN_INDEX_NOT_APPLICABLE", 1739, "Cannot use %-.64s access on index \'%-.64s\' due to type or collation conversion on field \'%-.64s\'" }, -{ "ER_PARTITION_EXCHANGE_FOREIGN_KEY", 1740, "Table to exchange with partition has foreign key references: \'%-.64s\'" }, -{ "ER_NO_SUCH_KEY_VALUE", 1741, "Key value \'%-.192s\' was not found in table \'%-.192s.%-.192s\'" }, -{ "ER_VALUE_TOO_LONG", 1742, "Too long value for \'%s\'" }, -{ "ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE", 1743, "Replication event checksum verification failed while reading from network" }, -{ "ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE", 1744, "Replication event checksum verification failed while reading from a log file" }, -{ "ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX", 1745, "Option binlog_stmt_cache_size (%lu) is greater than max_binlog_stmt_cache_size (%lu); setting binlog_stmt_cache_size equal to max_binlog_stmt_cache_size" }, -{ "ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT", 1746, "Can\'t update table \'%-.192s\' while \'%-.192s\' is being created" }, -{ "ER_PARTITION_CLAUSE_ON_NONPARTITIONED", 1747, "PARTITION () clause on non partitioned table" }, -{ "ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET", 1748, "Found a row not matching the given partition set" }, -{ "ER_UNUSED_5", 1749, "You should never see it" }, -{ "ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE", 1750, "Failure while changing the type of replication repository: %s" }, -{ "ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE", 1751, "The creation of some temporary tables could not be rolled back" }, -{ "ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE", 1752, "Some temporary tables were dropped, but these operations could not be rolled back" }, -{ "ER_MTS_FEATURE_IS_NOT_SUPPORTED", 1753, "%s is not supported in multi-threaded slave mode. %s" }, -{ "ER_MTS_UPDATED_DBS_GREATER_MAX", 1754, "The number of modified databases exceeds the maximum %d; the database names will not be included in the replication event metadata" }, -{ "ER_MTS_CANT_PARALLEL", 1755, "Cannot execute the current event group in the parallel mode. Encountered event %s, relay-log name %s, position %s which prevents execution of this event group in parallel mode. Reason: %s" }, -{ "ER_MTS_INCONSISTENT_DATA", 1756, "%s" }, -{ "ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING", 1757, "FULLTEXT index is not supported for partitioned tables" }, -{ "ER_DA_INVALID_CONDITION_NUMBER", 1758, "Invalid condition number" }, -{ "ER_INSECURE_PLAIN_TEXT", 1759, "Sending passwords in plain text without SSL/TLS is extremely insecure" }, -{ "ER_INSECURE_CHANGE_MASTER", 1760, "Storing MariaDB user name or password information in the master.info repository is not secure and is therefore not recommended. Please see the MariaDB Manual for more about this issue and possible alternatives" }, -{ "ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO", 1761, "Foreign key constraint for table \'%.192s\', record \'%-.192s\' would lead to a duplicate entry in table \'%.192s\', key \'%.192s\'" }, -{ "ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO", 1762, "Foreign key constraint for table \'%.192s\', record \'%-.192s\' would lead to a duplicate entry in a child table" }, -{ "ER_SQLTHREAD_WITH_SECURE_SLAVE", 1763, "Setting authentication options is not possible when only the Slave SQL Thread is being started" }, -{ "ER_TABLE_HAS_NO_FT", 1764, "The table does not have FULLTEXT index to support this query" }, -{ "ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER", 1765, "The system variable %.200s cannot be set in stored functions or triggers" }, -{ "ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION", 1766, "The system variable %.200s cannot be set when there is an ongoing transaction" }, -{ "ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST", 1767, "The system variable @@SESSION.GTID_NEXT has the value %.200s, which is not listed in @@SESSION.GTID_NEXT_LIST" }, -{ "ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL", 1768, "When @@SESSION.GTID_NEXT_LIST == NULL, the system variable @@SESSION.GTID_NEXT cannot change inside a transaction" }, -{ "ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION", 1769, "The statement \'SET %.200s\' cannot invoke a stored function" }, -{ "ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL", 1770, "The system variable @@SESSION.GTID_NEXT cannot be \'AUTOMATIC\' when @@SESSION.GTID_NEXT_LIST is non-NULL" }, -{ "ER_SKIPPING_LOGGED_TRANSACTION", 1771, "Skipping transaction %.200s because it has already been executed and logged" }, -{ "ER_MALFORMED_GTID_SET_SPECIFICATION", 1772, "Malformed GTID set specification \'%.200s\'" }, -{ "ER_MALFORMED_GTID_SET_ENCODING", 1773, "Malformed GTID set encoding" }, -{ "ER_MALFORMED_GTID_SPECIFICATION", 1774, "Malformed GTID specification \'%.200s\'" }, -{ "ER_GNO_EXHAUSTED", 1775, "Impossible to generate Global Transaction Identifier: the integer component reached the maximal value. Restart the server with a new server_uuid" }, -{ "ER_BAD_SLAVE_AUTO_POSITION", 1776, "Parameters MASTER_LOG_FILE, MASTER_LOG_POS, RELAY_LOG_FILE and RELAY_LOG_POS cannot be set when MASTER_AUTO_POSITION is active" }, -{ "ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON", 1777, "CHANGE MASTER TO MASTER_AUTO_POSITION = 1 can only be executed when GTID_MODE = ON" }, -{ "ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET", 1778, "Cannot execute statements with implicit commit inside a transaction when GTID_NEXT != AUTOMATIC or GTID_NEXT_LIST != NULL" }, -{ "ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON", 1779, "GTID_MODE = ON or GTID_MODE = UPGRADE_STEP_2 requires ENFORCE_GTID_CONSISTENCY = 1" }, -{ "ER_GTID_MODE_REQUIRES_BINLOG", 1780, "GTID_MODE = ON or UPGRADE_STEP_1 or UPGRADE_STEP_2 requires --log-bin and --log-slave-updates" }, -{ "ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF", 1781, "GTID_NEXT cannot be set to UUID:NUMBER when GTID_MODE = OFF" }, -{ "ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON", 1782, "GTID_NEXT cannot be set to ANONYMOUS when GTID_MODE = ON" }, -{ "ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF", 1783, "GTID_NEXT_LIST cannot be set to a non-NULL value when GTID_MODE = OFF" }, -{ "ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF", 1784, "Found a Gtid_log_event or Previous_gtids_log_event when GTID_MODE = OFF" }, -{ "ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE", 1785, "When ENFORCE_GTID_CONSISTENCY = 1, updates to non-transactional tables can only be done in either autocommitted statements or single-statement transactions, and never in the same statement as updates to transactional tables" }, -{ "ER_GTID_UNSAFE_CREATE_SELECT", 1786, "CREATE TABLE ... SELECT is forbidden when ENFORCE_GTID_CONSISTENCY = 1" }, -{ "ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION", 1787, "When ENFORCE_GTID_CONSISTENCY = 1, the statements CREATE TEMPORARY TABLE and DROP TEMPORARY TABLE can be executed in a non-transactional context only, and require that AUTOCOMMIT = 1" }, -{ "ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME", 1788, "The value of GTID_MODE can only change one step at a time: OFF <-> UPGRADE_STEP_1 <-> UPGRADE_STEP_2 <-> ON. Also note that this value must be stepped up or down simultaneously on all servers; see the Manual for instructions." }, -{ "ER_MASTER_HAS_PURGED_REQUIRED_GTIDS", 1789, "The slave is connecting using CHANGE MASTER TO MASTER_AUTO_POSITION = 1, but the master has purged binary logs containing GTIDs that the slave requires" }, -{ "ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID", 1790, "GTID_NEXT cannot be changed by a client that owns a GTID. The client owns %s. Ownership is released on COMMIT or ROLLBACK" }, -{ "ER_UNKNOWN_EXPLAIN_FORMAT", 1791, "Unknown %s format name: \'%s\'" }, -{ "ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION", 1792, "Cannot execute statement in a READ ONLY transaction" }, -{ "ER_TOO_LONG_TABLE_PARTITION_COMMENT", 1793, "Comment for table partition \'%-.64s\' is too long (max = %lu)" }, -{ "ER_SLAVE_CONFIGURATION", 1794, "Slave is not configured or failed to initialize properly. You must at least set --server-id to enable either a master or a slave. Additional error messages can be found in the MariaDB error log" }, -{ "ER_INNODB_FT_LIMIT", 1795, "InnoDB presently supports one FULLTEXT index creation at a time" }, -{ "ER_INNODB_NO_FT_TEMP_TABLE", 1796, "Cannot create FULLTEXT index on temporary InnoDB table" }, -{ "ER_INNODB_FT_WRONG_DOCID_COLUMN", 1797, "Column \'%-.192s\' is of wrong type for an InnoDB FULLTEXT index" }, -{ "ER_INNODB_FT_WRONG_DOCID_INDEX", 1798, "Index \'%-.192s\' is of wrong type for an InnoDB FULLTEXT index" }, -{ "ER_INNODB_ONLINE_LOG_TOO_BIG", 1799, "Creating index \'%-.192s\' required more than \'innodb_online_alter_log_max_size\' bytes of modification log. Please try again" }, -{ "ER_UNKNOWN_ALTER_ALGORITHM", 1800, "Unknown ALGORITHM \'%s\'" }, -{ "ER_UNKNOWN_ALTER_LOCK", 1801, "Unknown LOCK type \'%s\'" }, -{ "ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS", 1802, "CHANGE MASTER cannot be executed when the slave was stopped with an error or killed in MTS mode. Consider using RESET SLAVE or START SLAVE UNTIL" }, -{ "ER_MTS_RECOVERY_FAILURE", 1803, "Cannot recover after SLAVE errored out in parallel execution mode. Additional error messages can be found in the MariaDB error log" }, -{ "ER_MTS_RESET_WORKERS", 1804, "Cannot clean up worker info tables. Additional error messages can be found in the MariaDB error log" }, -{ "ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2", 1805, "Column count of %s.%s is wrong. Expected %d, found %d. The table is probably corrupted" }, -{ "ER_SLAVE_SILENT_RETRY_TRANSACTION", 1806, "Slave must silently retry current transaction" }, -{ "ER_UNUSED_22", 1807, "You should never see it" }, -{ "ER_TABLE_SCHEMA_MISMATCH", 1808, "Schema mismatch (%s)" }, -{ "ER_TABLE_IN_SYSTEM_TABLESPACE", 1809, "Table %-.192s in system tablespace" }, -{ "ER_IO_READ_ERROR", 1810, "IO Read error: (%lu, %s) %s" }, -{ "ER_IO_WRITE_ERROR", 1811, "IO Write error: (%lu, %s) %s" }, -{ "ER_TABLESPACE_MISSING", 1812, "Tablespace is missing for table \'%-.192s\'" }, -{ "ER_TABLESPACE_EXISTS", 1813, "Tablespace for table \'%-.192s\' exists. Please DISCARD the tablespace before IMPORT" }, -{ "ER_TABLESPACE_DISCARDED", 1814, "Tablespace has been discarded for table %`s" }, -{ "ER_INTERNAL_ERROR", 1815, "Internal error: %-.192s" }, -{ "ER_INNODB_IMPORT_ERROR", 1816, "ALTER TABLE \'%-.192s\' IMPORT TABLESPACE failed with error %lu : \'%s\'" }, -{ "ER_INNODB_INDEX_CORRUPT", 1817, "Index corrupt: %s" }, -{ "ER_INVALID_YEAR_COLUMN_LENGTH", 1818, "YEAR(%lu) column type is deprecated. Creating YEAR(4) column instead" }, -{ "ER_NOT_VALID_PASSWORD", 1819, "Your password does not satisfy the current policy requirements" }, -{ "ER_MUST_CHANGE_PASSWORD", 1820, "You must SET PASSWORD before executing this statement" }, -{ "ER_FK_NO_INDEX_CHILD", 1821, "Failed to add the foreign key constaint. Missing index for constraint \'%s\' in the foreign table \'%s\'" }, -{ "ER_FK_NO_INDEX_PARENT", 1822, "Failed to add the foreign key constaint. Missing index for constraint \'%s\' in the referenced table \'%s\'" }, -{ "ER_FK_FAIL_ADD_SYSTEM", 1823, "Failed to add the foreign key constraint \'%s\' to system tables" }, -{ "ER_FK_CANNOT_OPEN_PARENT", 1824, "Failed to open the referenced table \'%s\'" }, -{ "ER_FK_INCORRECT_OPTION", 1825, "Failed to add the foreign key constraint on table \'%s\'. Incorrect options in FOREIGN KEY constraint \'%s\'" }, -{ "ER_DUP_CONSTRAINT_NAME", 1826, "Duplicate %s constraint name \'%s\'" }, -{ "ER_PASSWORD_FORMAT", 1827, "The password hash doesn\'t have the expected format. Check if the correct password algorithm is being used with the PASSWORD() function" }, -{ "ER_FK_COLUMN_CANNOT_DROP", 1828, "Cannot drop column \'%-.192s\': needed in a foreign key constraint \'%-.192s\'" }, -{ "ER_FK_COLUMN_CANNOT_DROP_CHILD", 1829, "Cannot drop column \'%-.192s\': needed in a foreign key constraint \'%-.192s\' of table %-.192s" }, -{ "ER_FK_COLUMN_NOT_NULL", 1830, "Column \'%-.192s\' cannot be NOT NULL: needed in a foreign key constraint \'%-.192s\' SET NULL" }, -{ "ER_DUP_INDEX", 1831, "Duplicate index %`s. This is deprecated and will be disallowed in a future release" }, -{ "ER_FK_COLUMN_CANNOT_CHANGE", 1832, "Cannot change column \'%-.192s\': used in a foreign key constraint \'%-.192s\'" }, -{ "ER_FK_COLUMN_CANNOT_CHANGE_CHILD", 1833, "Cannot change column \'%-.192s\': used in a foreign key constraint \'%-.192s\' of table \'%-.192s\'" }, -{ "ER_FK_CANNOT_DELETE_PARENT", 1834, "Cannot delete rows from table which is parent in a foreign key constraint \'%-.192s\' of table \'%-.192s\'" }, -{ "ER_MALFORMED_PACKET", 1835, "Malformed communication packet" }, -{ "ER_READ_ONLY_MODE", 1836, "Running in read-only mode" }, -{ "ER_GTID_NEXT_TYPE_UNDEFINED_GROUP", 1837, "When GTID_NEXT is set to a GTID, you must explicitly set it again after a COMMIT or ROLLBACK. If you see this error message in the slave SQL thread, it means that a table in the current transaction is transactional on the master and non-transactional on the slave. In a client connection, it means that you executed SET GTID_NEXT before a transaction and forgot to set GTID_NEXT to a different identifier or to \'AUTOMATIC\' after COMMIT or ROLLBACK. Current GTID_NEXT is \'%s\'" }, -{ "ER_VARIABLE_NOT_SETTABLE_IN_SP", 1838, "The system variable %.200s cannot be set in stored procedures" }, -{ "ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF", 1839, "GTID_PURGED can only be set when GTID_MODE = ON" }, -{ "ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY", 1840, "GTID_PURGED can only be set when GTID_EXECUTED is empty" }, -{ "ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY", 1841, "GTID_PURGED can only be set when there are no ongoing transactions (not even in other clients)" }, -{ "ER_GTID_PURGED_WAS_CHANGED", 1842, "GTID_PURGED was changed from \'%s\' to \'%s\'" }, -{ "ER_GTID_EXECUTED_WAS_CHANGED", 1843, "GTID_EXECUTED was changed from \'%s\' to \'%s\'" }, -{ "ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES", 1844, "Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT, and both replicated and non replicated tables are written to" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED", 1845, "%s is not supported for this operation. Try %s" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON", 1846, "%s is not supported. Reason: %s. Try %s" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY", 1847, "COPY algorithm requires a lock" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION", 1848, "Partition specific operations do not yet support LOCK/ALGORITHM" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME", 1849, "Columns participating in a foreign key are renamed" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE", 1850, "Cannot change column type" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK", 1851, "Adding foreign keys needs foreign_key_checks=OFF" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE", 1852, "Creating unique indexes with IGNORE requires COPY algorithm to remove duplicate rows" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK", 1853, "Dropping a primary key is not allowed without also adding a new primary key" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC", 1854, "Adding an auto-increment column requires a lock" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS", 1855, "Cannot replace hidden FTS_DOC_ID with a user-visible one" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS", 1856, "Cannot drop or rename FTS_DOC_ID" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS", 1857, "Fulltext index creation requires a lock" }, -{ "ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE", 1858, "sql_slave_skip_counter can not be set when the server is running with GTID_MODE = ON. Instead, for each transaction that you want to skip, generate an empty transaction with the same GTID as the transaction" }, -{ "ER_DUP_UNKNOWN_IN_INDEX", 1859, "Duplicate entry for key \'%-.192s\'" }, -{ "ER_IDENT_CAUSES_TOO_LONG_PATH", 1860, "Long database name and identifier for object resulted in path length exceeding %d characters. Path: \'%s\'" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL", 1861, "cannot convert NULL to non-constant DEFAULT" }, -{ "ER_MUST_CHANGE_PASSWORD_LOGIN", 1862, "Your password has expired. To log in you must change it using a client that supports expired passwords" }, -{ "ER_ROW_IN_WRONG_PARTITION", 1863, "Found a row in wrong partition %s" }, -{ "ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX", 1864, "Cannot schedule event %s, relay-log name %s, position %s to Worker thread because its size %lu exceeds %lu of slave_pending_jobs_size_max" }, -{ "ER_INNODB_NO_FT_USES_PARSER", 1865, "Cannot CREATE FULLTEXT INDEX WITH PARSER on InnoDB table" }, -{ "ER_BINLOG_LOGICAL_CORRUPTION", 1866, "The binary log file \'%s\' is logically corrupted: %s" }, -{ "ER_WARN_PURGE_LOG_IN_USE", 1867, "file %s was not purged because it was being read by %d thread(s), purged only %d out of %d files" }, -{ "ER_WARN_PURGE_LOG_IS_ACTIVE", 1868, "file %s was not purged because it is the active log file" }, -{ "ER_AUTO_INCREMENT_CONFLICT", 1869, "Auto-increment value in UPDATE conflicts with internally generated values" }, -{ "WARN_ON_BLOCKHOLE_IN_RBR", 1870, "Row events are not logged for %s statements that modify BLACKHOLE tables in row format. Table(s): \'%-.192s\'" }, -{ "ER_SLAVE_MI_INIT_REPOSITORY", 1871, "Slave failed to initialize master info structure from the repository" }, -{ "ER_SLAVE_RLI_INIT_REPOSITORY", 1872, "Slave failed to initialize relay log info structure from the repository" }, -{ "ER_ACCESS_DENIED_CHANGE_USER_ERROR", 1873, "Access denied trying to change to user \'%-.48s\'@\'%-.64s\' (using password: %s). Disconnecting" }, -{ "ER_INNODB_READ_ONLY", 1874, "InnoDB is in read only mode" }, -{ "ER_STOP_SLAVE_SQL_THREAD_TIMEOUT", 1875, "STOP SLAVE command execution is incomplete: Slave SQL thread got the stop signal, thread is busy, SQL thread will stop once the current task is complete" }, -{ "ER_STOP_SLAVE_IO_THREAD_TIMEOUT", 1876, "STOP SLAVE command execution is incomplete: Slave IO thread got the stop signal, thread is busy, IO thread will stop once the current task is complete" }, -{ "ER_TABLE_CORRUPT", 1877, "Operation cannot be performed. The table \'%-.64s.%-.64s\' is missing, corrupt or contains bad data" }, -{ "ER_TEMP_FILE_WRITE_FAILURE", 1878, "Temporary file write failure" }, -{ "ER_INNODB_FT_AUX_NOT_HEX_ID", 1879, "Upgrade index name failed, please use create index(alter table) algorithm copy to rebuild index" }, -{ "ER_LAST_MYSQL_ERROR_MESSAGE", 1880, "\"" }, -{ "ER_UNUSED_18", 1900, "\"" }, -{ "ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED", 1901, "Function or expression \'%s\' cannot be used in the %s clause of %`s" }, -{ "ER_UNUSED_19", 1902, "\"" }, -{ "ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN", 1903, "Primary key cannot be defined upon a generated column" }, -{ "ER_KEY_BASED_ON_GENERATED_VIRTUAL_COLUMN", 1904, "Key/Index cannot be defined on a virtual generated column" }, -{ "ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN", 1905, "Cannot define foreign key with %s clause on a generated column" }, -{ "ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN", 1906, "The value specified for generated column \'%s\' in table \'%s\' has been ignored" }, -{ "ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN", 1907, "This is not yet supported for generated columns" }, -{ "ER_UNUSED_20", 1908, "\"" }, -{ "ER_UNUSED_21", 1909, "\"" }, -{ "ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS", 1910, "%s storage engine does not support generated columns" }, -{ "ER_UNKNOWN_OPTION", 1911, "Unknown option \'%-.64s\'" }, -{ "ER_BAD_OPTION_VALUE", 1912, "Incorrect value \'%-.64T\' for option \'%-.64s\'" }, -{ "ER_UNUSED_6", 1913, "You should never see it" }, -{ "ER_UNUSED_7", 1914, "You should never see it" }, -{ "ER_UNUSED_8", 1915, "You should never see it" }, -{ "ER_DATA_OVERFLOW", 1916, "Got overflow when converting \'%-.128s\' to %-.32s. Value truncated" }, -{ "ER_DATA_TRUNCATED", 1917, "Truncated value \'%-.128s\' when converting to %-.32s" }, -{ "ER_BAD_DATA", 1918, "Encountered illegal value \'%-.128s\' when converting to %-.32s" }, -{ "ER_DYN_COL_WRONG_FORMAT", 1919, "Encountered illegal format of dynamic column string" }, -{ "ER_DYN_COL_IMPLEMENTATION_LIMIT", 1920, "Dynamic column implementation limit reached" }, -{ "ER_DYN_COL_DATA", 1921, "Illegal value used as argument of dynamic column function" }, -{ "ER_DYN_COL_WRONG_CHARSET", 1922, "Dynamic column contains unknown character set" }, -{ "ER_ILLEGAL_SUBQUERY_OPTIMIZER_SWITCHES", 1923, "At least one of the \'in_to_exists\' or \'materialization\' optimizer_switch flags must be \'on\'" }, -{ "ER_QUERY_CACHE_IS_DISABLED", 1924, "Query cache is disabled (resize or similar command in progress); repeat this command later" }, -{ "ER_QUERY_CACHE_IS_GLOBALY_DISABLED", 1925, "Query cache is globally disabled and you can\'t enable it only for this session" }, -{ "ER_VIEW_ORDERBY_IGNORED", 1926, "View \'%-.192s\'.\'%-.192s\' ORDER BY clause ignored because there is other ORDER BY clause already" }, -{ "ER_CONNECTION_KILLED", 1927, "Connection was killed" }, -{ "ER_UNUSED_12", 1928, "You should never see it" }, -{ "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SKIP_REPLICATION", 1929, "Cannot modify @@session.skip_replication inside a transaction" }, -{ "ER_STORED_FUNCTION_PREVENTS_SWITCH_SKIP_REPLICATION", 1930, "Cannot modify @@session.skip_replication inside a stored function or trigger" }, -{ "ER_QUERY_EXCEEDED_ROWS_EXAMINED_LIMIT", 1931, "Query execution was interrupted. The query examined at least %llu rows, which exceeds LIMIT ROWS EXAMINED (%llu). The query result may be incomplete" }, -{ "ER_NO_SUCH_TABLE_IN_ENGINE", 1932, "Table \'%-.192s.%-.192s\' doesn\'t exist in engine" }, -{ "ER_TARGET_NOT_EXPLAINABLE", 1933, "Target is not running an EXPLAINable command" }, -{ "ER_CONNECTION_ALREADY_EXISTS", 1934, "Connection \'%.*s\' conflicts with existing connection \'%.*s\'" }, -{ "ER_MASTER_LOG_PREFIX", 1935, "Master \'%.*s\': " }, -{ "ER_CANT_START_STOP_SLAVE", 1936, "Can\'t %s SLAVE \'%.*s\'" }, -{ "ER_SLAVE_STARTED", 1937, "SLAVE \'%.*s\' started" }, -{ "ER_SLAVE_STOPPED", 1938, "SLAVE \'%.*s\' stopped" }, -{ "ER_SQL_DISCOVER_ERROR", 1939, "Engine %s failed to discover table %`-.192s.%`-.192s with \'%s\'" }, -{ "ER_FAILED_GTID_STATE_INIT", 1940, "Failed initializing replication GTID state" }, -{ "ER_INCORRECT_GTID_STATE", 1941, "Could not parse GTID list" }, -{ "ER_CANNOT_UPDATE_GTID_STATE", 1942, "Could not update replication slave gtid state" }, -{ "ER_DUPLICATE_GTID_DOMAIN", 1943, "GTID %u-%u-%llu and %u-%u-%llu conflict (duplicate domain id %u)" }, -{ "ER_GTID_OPEN_TABLE_FAILED", 1944, "Failed to open %s.%s" }, -{ "ER_GTID_POSITION_NOT_FOUND_IN_BINLOG", 1945, "Connecting slave requested to start from GTID %u-%u-%llu, which is not in the master\'s binlog" }, -{ "ER_CANNOT_LOAD_SLAVE_GTID_STATE", 1946, "Failed to load replication slave GTID position from table %s.%s" }, -{ "ER_MASTER_GTID_POS_CONFLICTS_WITH_BINLOG", 1947, "Specified GTID %u-%u-%llu conflicts with the binary log which contains a more recent GTID %u-%u-%llu. If MASTER_GTID_POS=CURRENT_POS is used, the binlog position will override the new value of @@gtid_slave_pos" }, -{ "ER_MASTER_GTID_POS_MISSING_DOMAIN", 1948, "Specified value for @@gtid_slave_pos contains no value for replication domain %u. This conflicts with the binary log which contains GTID %u-%u-%llu. If MASTER_GTID_POS=CURRENT_POS is used, the binlog position will override the new value of @@gtid_slave_pos" }, -{ "ER_UNTIL_REQUIRES_USING_GTID", 1949, "START SLAVE UNTIL master_gtid_pos requires that slave is using GTID" }, -{ "ER_GTID_STRICT_OUT_OF_ORDER", 1950, "An attempt was made to binlog GTID %u-%u-%llu which would create an out-of-order sequence number with existing GTID %u-%u-%llu, and gtid strict mode is enabled" }, -{ "ER_GTID_START_FROM_BINLOG_HOLE", 1951, "The binlog on the master is missing the GTID %u-%u-%llu requested by the slave (even though a subsequent sequence number does exist), and GTID strict mode is enabled" }, -{ "ER_SLAVE_UNEXPECTED_MASTER_SWITCH", 1952, "Unexpected GTID received from master after reconnect. This normally indicates that the master server was replaced without restarting the slave threads. %s" }, -{ "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO", 1953, "Cannot modify @@session.gtid_domain_id or @@session.gtid_seq_no inside a transaction" }, -{ "ER_STORED_FUNCTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO", 1954, "Cannot modify @@session.gtid_domain_id or @@session.gtid_seq_no inside a stored function or trigger" }, -{ "ER_GTID_POSITION_NOT_FOUND_IN_BINLOG2", 1955, "Connecting slave requested to start from GTID %u-%u-%llu, which is not in the master\'s binlog. Since the master\'s binlog contains GTIDs with higher sequence numbers, it probably means that the slave has diverged due to executing extra erroneous transactions" }, -{ "ER_BINLOG_MUST_BE_EMPTY", 1956, "This operation is not allowed if any GTID has been logged to the binary log. Run RESET MASTER first to erase the log" }, -{ "ER_NO_SUCH_QUERY", 1957, "Unknown query id: %lld" }, -{ "ER_BAD_BASE64_DATA", 1958, "Bad base64 data as position %u" }, -{ "ER_INVALID_ROLE", 1959, "Invalid role specification %`s" }, -{ "ER_INVALID_CURRENT_USER", 1960, "The current user is invalid" }, -{ "ER_CANNOT_GRANT_ROLE", 1961, "Cannot grant role \'%s\' to: %s" }, -{ "ER_CANNOT_REVOKE_ROLE", 1962, "Cannot revoke role \'%s\' from: %s" }, -{ "ER_CHANGE_SLAVE_PARALLEL_THREADS_ACTIVE", 1963, "Cannot change @@slave_parallel_threads while another change is in progress" }, -{ "ER_PRIOR_COMMIT_FAILED", 1964, "Commit failed due to failure of an earlier commit on which this one depends" }, -{ "ER_IT_IS_A_VIEW", 1965, "\'%-.192s\' is a view" }, -{ "ER_SLAVE_SKIP_NOT_IN_GTID", 1966, "When using parallel replication and GTID with multiple replication domains, @@sql_slave_skip_counter can not be used. Instead, setting @@gtid_slave_pos explicitly can be used to skip to after a given GTID position" }, -{ "ER_TABLE_DEFINITION_TOO_BIG", 1967, "The definition for table %`s is too big" }, -{ "ER_PLUGIN_INSTALLED", 1968, "Plugin \'%-.192s\' already installed" }, -{ "ER_STATEMENT_TIMEOUT", 1969, "Query execution was interrupted (max_statement_time exceeded)" }, -{ "ER_SUBQUERIES_NOT_SUPPORTED", 1970, "%s does not support subqueries or stored functions" }, -{ "ER_SET_STATEMENT_NOT_SUPPORTED", 1971, "The system variable %.200s cannot be set in SET STATEMENT." }, -{ "ER_UNUSED_9", 1972, "You should never see it" }, -{ "ER_USER_CREATE_EXISTS", 1973, "Can\'t create user \'%-.64s\'@\'%-.64s\'; it already exists" }, -{ "ER_USER_DROP_EXISTS", 1974, "Can\'t drop user \'%-.64s\'@\'%-.64s\'; it doesn\'t exist" }, -{ "ER_ROLE_CREATE_EXISTS", 1975, "Can\'t create role \'%-.64s\'; it already exists" }, -{ "ER_ROLE_DROP_EXISTS", 1976, "Can\'t drop role \'%-.64s\'; it doesn\'t exist" }, -{ "ER_CANNOT_CONVERT_CHARACTER", 1977, "Cannot convert \'%s\' character 0x%-.64s to \'%s\'" }, -{ "ER_INVALID_DEFAULT_VALUE_FOR_FIELD", 1978, "Incorrect default value \'%-.128T\' for column \'%.192s\'" }, -{ "ER_KILL_QUERY_DENIED_ERROR", 1979, "You are not owner of query %lu" }, -{ "ER_NO_EIS_FOR_FIELD", 1980, "Engine-independent statistics are not collected for column \'%s\'" }, -{ "ER_WARN_AGGFUNC_DEPENDENCE", 1981, "Aggregate function \'%-.192s)\' of SELECT #%d belongs to SELECT #%d" }, -{ "WARN_INNODB_PARTITION_OPTION_IGNORED", 1982, "<%-.64s> option ignored for InnoDB partition" }, -{ "ER_FILE_CORRUPT", 3000, "File %s is corrupted" }, -{ "ER_ERROR_ON_MASTER", 3001, "Query partially completed on the master (error on master: %d) and was aborted. There is a chance that your master is inconsistent at this point. If you are sure that your master is ok, run this query manually on the slave and then restart the slave with SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; START SLAVE;. Query:\'%s\'" }, -{ "ER_INCONSISTENT_ERROR", 3002, "Query caused different errors on master and slave. Error on master: message (format)=\'%s\' error code=%d; Error on slave:actual message=\'%s\', error code=%d. Default database:\'%s\'. Query:\'%s\'" }, -{ "ER_STORAGE_ENGINE_NOT_LOADED", 3003, "Storage engine for table \'%s\'.\'%s\' is not loaded." }, -{ "ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER", 3004, "GET STACKED DIAGNOSTICS when handler not active" }, -{ "ER_WARN_LEGACY_SYNTAX_CONVERTED", 3005, "%s is no longer supported. The statement was converted to %s." }, -{ "ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN", 3006, "Statement is unsafe because it uses a fulltext parser plugin which may not return the same value on the slave." }, -{ "ER_CANNOT_DISCARD_TEMPORARY_TABLE", 3007, "Cannot DISCARD/IMPORT tablespace associated with temporary table" }, -{ "ER_FK_DEPTH_EXCEEDED", 3008, "Foreign key cascade delete/update exceeds max depth of %d." }, -{ "ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2", 3009, "Column count of %s.%s is wrong. Expected %d, found %d. Created with MariaDB %d, now running %d. Please use mariadb-upgrade to fix this error." }, -{ "ER_WARN_TRIGGER_DOESNT_HAVE_CREATED", 3010, "Trigger %s.%s.%s does not have CREATED attribute." }, -{ "ER_REFERENCED_TRG_DOES_NOT_EXIST_MYSQL", 3011, "Referenced trigger \'%s\' for the given action time and event type does not exist." }, -{ "ER_EXPLAIN_NOT_SUPPORTED", 3012, "EXPLAIN FOR CONNECTION command is supported only for SELECT/UPDATE/INSERT/DELETE/REPLACE" }, -{ "ER_INVALID_FIELD_SIZE", 3013, "Invalid size for column \'%-.192s\'." }, -{ "ER_MISSING_HA_CREATE_OPTION", 3014, "Table storage engine \'%-.64s\' found required create option missing" }, -{ "ER_ENGINE_OUT_OF_MEMORY", 3015, "Out of memory in storage engine \'%-.64s\'." }, -{ "ER_PASSWORD_EXPIRE_ANONYMOUS_USER", 3016, "The password for anonymous user cannot be expired." }, -{ "ER_SLAVE_SQL_THREAD_MUST_STOP", 3017, "This operation cannot be performed with a running slave sql thread; run STOP SLAVE SQL_THREAD first" }, -{ "ER_NO_FT_MATERIALIZED_SUBQUERY", 3018, "Cannot create FULLTEXT index on materialized subquery" }, -{ "ER_INNODB_UNDO_LOG_FULL", 3019, "Undo Log error: %s" }, -{ "ER_INVALID_ARGUMENT_FOR_LOGARITHM", 3020, "Invalid argument for logarithm" }, -{ "ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP", 3021, "This operation cannot be performed with a running slave io thread; run STOP SLAVE IO_THREAD FOR CHANNEL \'%s\' first." }, -{ "ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO", 3022, "This operation may not be safe when the slave has temporary tables. The tables will be kept open until the server restarts or until the tables are deleted by any replicated DROP statement. Suggest to wait until slave_open_temp_tables = 0." }, -{ "ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS", 3023, "CHANGE MASTER TO with a MASTER_LOG_FILE clause but no MASTER_LOG_POS clause may not be safe. The old position value may not be valid for the new binary log file." }, -{ "ER_QUERY_TIMEOUT", 3024, "Query execution was interrupted, maximum statement execution time exceeded" }, -{ "ER_NON_RO_SELECT_DISABLE_TIMER", 3025, "Select is not a read only statement, disabling timer" }, -{ "ER_DUP_LIST_ENTRY", 3026, "Duplicate entry \'%-.192s\'." }, -{ "ER_SQL_MODE_NO_EFFECT", 3027, "\'%s\' mode no longer has any effect. Use STRICT_ALL_TABLES or STRICT_TRANS_TABLES instead." }, -{ "ER_AGGREGATE_ORDER_FOR_UNION", 3028, "Expression #%u of ORDER BY contains aggregate function and applies to a UNION" }, -{ "ER_AGGREGATE_ORDER_NON_AGG_QUERY", 3029, "Expression #%u of ORDER BY contains aggregate function and applies to the result of a non-aggregated query" }, -{ "ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR", 3030, "Slave worker has stopped after at least one previous worker encountered an error when slave-preserve-commit-order was enabled. To preserve commit order, the last transaction executed by this thread has not been committed. When restarting the slave after fixing any failed threads, you should fix this worker as well." }, -{ "ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER", 3031, "slave_preserve_commit_order is not supported %s." }, -{ "ER_SERVER_OFFLINE_MODE", 3032, "The server is currently in offline mode" }, -{ "ER_GIS_DIFFERENT_SRIDS", 3033, "Binary geometry function %s given two geometries of different srids: %u and %u, which should have been identical." }, -{ "ER_GIS_UNSUPPORTED_ARGUMENT", 3034, "Calling geometry function %s with unsupported types of arguments." }, -{ "ER_GIS_UNKNOWN_ERROR", 3035, "Unknown GIS error occurred in function %s." }, -{ "ER_GIS_UNKNOWN_EXCEPTION", 3036, "Unknown exception caught in GIS function %s." }, -{ "ER_GIS_INVALID_DATA", 3037, "Invalid GIS data provided to function %s." }, -{ "ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION", 3038, "The geometry has no data in function %s." }, -{ "ER_BOOST_GEOMETRY_CENTROID_EXCEPTION", 3039, "Unable to calculate centroid because geometry is empty in function %s." }, -{ "ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION", 3040, "Geometry overlay calculation error: geometry data is invalid in function %s." }, -{ "ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION", 3041, "Geometry turn info calculation error: geometry data is invalid in function %s." }, -{ "ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION", 3042, "Analysis procedures of intersection points interrupted unexpectedly in function %s." }, -{ "ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION", 3043, "Unknown exception thrown in function %s." }, -{ "ER_STD_BAD_ALLOC_ERROR", 3044, "Memory allocation error: %-.256s in function %s." }, -{ "ER_STD_DOMAIN_ERROR", 3045, "Domain error: %-.256s in function %s." }, -{ "ER_STD_LENGTH_ERROR", 3046, "Length error: %-.256s in function %s." }, -{ "ER_STD_INVALID_ARGUMENT", 3047, "Invalid argument error: %-.256s in function %s." }, -{ "ER_STD_OUT_OF_RANGE_ERROR", 3048, "Out of range error: %-.256s in function %s." }, -{ "ER_STD_OVERFLOW_ERROR", 3049, "Overflow error error: %-.256s in function %s." }, -{ "ER_STD_RANGE_ERROR", 3050, "Range error: %-.256s in function %s." }, -{ "ER_STD_UNDERFLOW_ERROR", 3051, "Underflow error: %-.256s in function %s." }, -{ "ER_STD_LOGIC_ERROR", 3052, "Logic error: %-.256s in function %s." }, -{ "ER_STD_RUNTIME_ERROR", 3053, "Runtime error: %-.256s in function %s." }, -{ "ER_STD_UNKNOWN_EXCEPTION", 3054, "Unknown exception: %-.384s in function %s." }, -{ "ER_GIS_DATA_WRONG_ENDIANESS", 3055, "Geometry byte string must be little endian." }, -{ "ER_CHANGE_MASTER_PASSWORD_LENGTH", 3056, "The password provided for the replication user exceeds the maximum length of 32 characters" }, -{ "ER_USER_LOCK_WRONG_NAME", 3057, "Incorrect user-level lock name \'%-.192s\'." }, -{ "ER_USER_LOCK_DEADLOCK", 3058, "Deadlock found when trying to get user-level lock; try rolling back transaction/releasing locks and restarting lock acquisition." }, -{ "ER_REPLACE_INACCESSIBLE_ROWS", 3059, "REPLACE cannot be executed as it requires deleting rows that are not in the view" }, -{ "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS", 3060, "Do not support online operation on table with GIS index" }, -{ "ER_COMMULTI_BADCONTEXT", 4000, "COM_MULTI can\'t return a result set in the given context" }, -{ "ER_BAD_COMMAND_IN_MULTI", 4001, "Command \'%s\' is not allowed for COM_MULTI" }, -{ "ER_WITH_COL_WRONG_LIST", 4002, "WITH column list and SELECT field list have different column counts" }, -{ "ER_TOO_MANY_DEFINITIONS_IN_WITH_CLAUSE", 4003, "Too many WITH elements in WITH clause" }, -{ "ER_DUP_QUERY_NAME", 4004, "Duplicate query name %`-.64s in WITH clause" }, -{ "ER_RECURSIVE_WITHOUT_ANCHORS", 4005, "No anchors for recursive WITH element \'%s\'" }, -{ "ER_UNACCEPTABLE_MUTUAL_RECURSION", 4006, "Unacceptable mutual recursion with anchored table \'%s\'" }, -{ "ER_REF_TO_RECURSIVE_WITH_TABLE_IN_DERIVED", 4007, "Reference to recursive WITH table \'%s\' in materialized derived" }, -{ "ER_NOT_STANDARD_COMPLIANT_RECURSIVE", 4008, "Restrictions imposed on recursive definitions are violated for table \'%s\'" }, -{ "ER_WRONG_WINDOW_SPEC_NAME", 4009, "Window specification with name \'%s\' is not defined" }, -{ "ER_DUP_WINDOW_NAME", 4010, "Multiple window specifications with the same name \'%s\'" }, -{ "ER_PARTITION_LIST_IN_REFERENCING_WINDOW_SPEC", 4011, "Window specification referencing another one \'%s\' cannot contain partition list" }, -{ "ER_ORDER_LIST_IN_REFERENCING_WINDOW_SPEC", 4012, "Referenced window specification \'%s\' already contains order list" }, -{ "ER_WINDOW_FRAME_IN_REFERENCED_WINDOW_SPEC", 4013, "Referenced window specification \'%s\' cannot contain window frame" }, -{ "ER_BAD_COMBINATION_OF_WINDOW_FRAME_BOUND_SPECS", 4014, "Unacceptable combination of window frame bound specifications" }, -{ "ER_WRONG_PLACEMENT_OF_WINDOW_FUNCTION", 4015, "Window function is allowed only in SELECT list and ORDER BY clause" }, -{ "ER_WINDOW_FUNCTION_IN_WINDOW_SPEC", 4016, "Window function is not allowed in window specification" }, -{ "ER_NOT_ALLOWED_WINDOW_FRAME", 4017, "Window frame is not allowed with \'%s\'" }, -{ "ER_NO_ORDER_LIST_IN_WINDOW_SPEC", 4018, "No order list in window specification for \'%s\'" }, -{ "ER_RANGE_FRAME_NEEDS_SIMPLE_ORDERBY", 4019, "RANGE-type frame requires ORDER BY clause with single sort key" }, -{ "ER_WRONG_TYPE_FOR_ROWS_FRAME", 4020, "Integer is required for ROWS-type frame" }, -{ "ER_WRONG_TYPE_FOR_RANGE_FRAME", 4021, "Numeric datatype is required for RANGE-type frame" }, -{ "ER_FRAME_EXCLUSION_NOT_SUPPORTED", 4022, "Frame exclusion is not supported yet" }, -{ "ER_WINDOW_FUNCTION_DONT_HAVE_FRAME", 4023, "This window function may not have a window frame" }, -{ "ER_INVALID_NTILE_ARGUMENT", 4024, "Argument of NTILE must be greater than 0" }, -{ "ER_CONSTRAINT_FAILED", 4025, "CONSTRAINT %`s failed for %`-.192s.%`-.192s" }, -{ "ER_EXPRESSION_IS_TOO_BIG", 4026, "Expression in the %s clause is too big" }, -{ "ER_ERROR_EVALUATING_EXPRESSION", 4027, "Got an error evaluating stored expression %s" }, -{ "ER_CALCULATING_DEFAULT_VALUE", 4028, "Got an error when calculating default value for %`s" }, -{ "ER_EXPRESSION_REFERS_TO_UNINIT_FIELD", 4029, "Expression for field %`-.64s is referring to uninitialized field %`s" }, -{ "ER_PARTITION_DEFAULT_ERROR", 4030, "Only one DEFAULT partition allowed" }, -{ "ER_REFERENCED_TRG_DOES_NOT_EXIST", 4031, "Referenced trigger \'%s\' for the given action time and event type does not exist" }, -{ "ER_INVALID_DEFAULT_PARAM", 4032, "Default/ignore value is not supported for such parameter usage" }, -{ "ER_BINLOG_NON_SUPPORTED_BULK", 4033, "Only row based replication supported for bulk operations" }, -{ "ER_BINLOG_UNCOMPRESS_ERROR", 4034, "Uncompress the compressed binlog failed" }, -{ "ER_JSON_BAD_CHR", 4035, "Broken JSON string in argument %d to function \'%s\' at position %d" }, -{ "ER_JSON_NOT_JSON_CHR", 4036, "Character disallowed in JSON in argument %d to function \'%s\' at position %d" }, -{ "ER_JSON_EOS", 4037, "Unexpected end of JSON text in argument %d to function \'%s\'" }, -{ "ER_JSON_SYNTAX", 4038, "Syntax error in JSON text in argument %d to function \'%s\' at position %d" }, -{ "ER_JSON_ESCAPING", 4039, "Incorrect escaping in JSON text in argument %d to function \'%s\' at position %d" }, -{ "ER_JSON_DEPTH", 4040, "Limit of %d on JSON nested strucures depth is reached in argument %d to function \'%s\' at position %d" }, -{ "ER_JSON_PATH_EOS", 4041, "Unexpected end of JSON path in argument %d to function \'%s\'" }, -{ "ER_JSON_PATH_SYNTAX", 4042, "Syntax error in JSON path in argument %d to function \'%s\' at position %d" }, -{ "ER_JSON_PATH_DEPTH", 4043, "Limit of %d on JSON path depth is reached in argument %d to function \'%s\' at position %d" }, -{ "ER_JSON_PATH_NO_WILDCARD", 4044, "Wildcards in JSON path not allowed in argument %d to function \'%s\'" }, -{ "ER_JSON_PATH_ARRAY", 4045, "JSON path should end with an array identifier in argument %d to function \'%s\'" }, -{ "ER_JSON_ONE_OR_ALL", 4046, "Argument 2 to function \'%s\' must be \"one\" or \"all\"." }, -{ "ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE", 4047, "CREATE TEMPORARY TABLE is not allowed with ROW_FORMAT=COMPRESSED or KEY_BLOCK_SIZE." }, -{ "ER_GEOJSON_INCORRECT", 4048, "Incorrect GeoJSON format specified for st_geomfromgeojson function." }, -{ "ER_GEOJSON_TOO_FEW_POINTS", 4049, "Incorrect GeoJSON format - too few points for linestring specified." }, -{ "ER_GEOJSON_NOT_CLOSED", 4050, "Incorrect GeoJSON format - polygon not closed." }, -{ "ER_JSON_PATH_EMPTY", 4051, "Path expression \'$\' is not allowed in argument %d to function \'%s\'." }, -{ "ER_SLAVE_SAME_ID", 4052, "A slave with the same server_uuid/server_id as this slave has connected to the master" }, -{ "ER_FLASHBACK_NOT_SUPPORTED", 4053, "Flashback does not support %s %s" }, -{ "ER_KEYS_OUT_OF_ORDER", 4054, "Keys are out order during bulk load" }, -{ "ER_OVERLAPPING_KEYS", 4055, "Bulk load rows overlap existing rows" }, -{ "ER_REQUIRE_ROW_BINLOG_FORMAT", 4056, "Can\'t execute updates on master with binlog_format != ROW." }, -{ "ER_ISOLATION_MODE_NOT_SUPPORTED", 4057, "MyRocks supports only READ COMMITTED and REPEATABLE READ isolation levels. Please change from current isolation level %s" }, -{ "ER_ON_DUPLICATE_DISABLED", 4058, "When unique checking is disabled in MyRocks, INSERT,UPDATE,LOAD statements with clauses that update or replace the key (i.e. INSERT ON DUPLICATE KEY UPDATE, REPLACE) are not allowed. Query: %s" }, -{ "ER_UPDATES_WITH_CONSISTENT_SNAPSHOT", 4059, "Can\'t execute updates when you started a transaction with START TRANSACTION WITH CONSISTENT [ROCKSDB] SNAPSHOT." }, -{ "ER_ROLLBACK_ONLY", 4060, "This transaction was rolled back and cannot be committed. Only supported operation is to roll it back, so all pending changes will be discarded. Please restart another transaction." }, -{ "ER_ROLLBACK_TO_SAVEPOINT", 4061, "MyRocks currently does not support ROLLBACK TO SAVEPOINT if modifying rows." }, -{ "ER_ISOLATION_LEVEL_WITH_CONSISTENT_SNAPSHOT", 4062, "Only REPEATABLE READ isolation level is supported for START TRANSACTION WITH CONSISTENT SNAPSHOT in RocksDB Storage Engine." }, -{ "ER_UNSUPPORTED_COLLATION", 4063, "Unsupported collation on string indexed column %s.%s Use binary collation (%s)." }, -{ "ER_METADATA_INCONSISTENCY", 4064, "Table \'%s\' does not exist, but metadata information exists inside MyRocks. This is a sign of data inconsistency. Please check if \'%s.frm\' exists, and try to restore it if it does not exist." }, -{ "ER_CF_DIFFERENT", 4065, "Column family (\'%s\') flag (%d) is different from an existing flag (%d). Assign a new CF flag, or do not change existing CF flag." }, -{ "ER_RDB_TTL_DURATION_FORMAT", 4066, "TTL duration (%s) in MyRocks must be an unsigned non-null 64-bit integer." }, -{ "ER_RDB_STATUS_GENERAL", 4067, "Status error %d received from RocksDB: %s" }, -{ "ER_RDB_STATUS_MSG", 4068, "%s, Status error %d received from RocksDB: %s" }, -{ "ER_RDB_TTL_UNSUPPORTED", 4069, "TTL support is currently disabled when table has a hidden PK." }, -{ "ER_RDB_TTL_COL_FORMAT", 4070, "TTL column (%s) in MyRocks must be an unsigned non-null 64-bit integer, exist inside the table, and have an accompanying ttl duration." }, -{ "ER_PER_INDEX_CF_DEPRECATED", 4071, "The per-index column family option has been deprecated" }, -{ "ER_KEY_CREATE_DURING_ALTER", 4072, "MyRocks failed creating new key definitions during alter." }, -{ "ER_SK_POPULATE_DURING_ALTER", 4073, "MyRocks failed populating secondary key during alter." }, -{ "ER_SUM_FUNC_WITH_WINDOW_FUNC_AS_ARG", 4074, "Window functions can not be used as arguments to group functions." }, -{ "ER_NET_OK_PACKET_TOO_LARGE", 4075, "OK packet too large" }, -{ "ER_GEOJSON_EMPTY_COORDINATES", 4076, "Incorrect GeoJSON format - empty \'coordinates\' array." }, -{ "ER_MYROCKS_CANT_NOPAD_COLLATION", 4077, "MyRocks doesn\'t currently support collations with \"No pad\" attribute." }, -{ "ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION", 4078, "Illegal parameter data types %s and %s for operation \'%s\'" }, -{ "ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION", 4079, "Illegal parameter data type %s for operation \'%s\'" }, -{ "ER_WRONG_PARAMCOUNT_TO_CURSOR", 4080, "Incorrect parameter count to cursor \'%-.192s\'" }, -{ "ER_UNKNOWN_STRUCTURED_VARIABLE", 4081, "Unknown structured system variable or ROW routine variable \'%-.*s\'" }, -{ "ER_ROW_VARIABLE_DOES_NOT_HAVE_FIELD", 4082, "Row variable \'%-.192s\' does not have a field \'%-.192s\'" }, -{ "ER_END_IDENTIFIER_DOES_NOT_MATCH", 4083, "END identifier \'%-.192s\' does not match \'%-.192s\'" }, -{ "ER_SEQUENCE_RUN_OUT", 4084, "Sequence \'%-.64s.%-.64s\' has run out" }, -{ "ER_SEQUENCE_INVALID_DATA", 4085, "Sequence \'%-.64s.%-.64s\' values are conflicting" }, -{ "ER_SEQUENCE_INVALID_TABLE_STRUCTURE", 4086, "Sequence \'%-.64s.%-.64s\' table structure is invalid (%s)" }, -{ "ER_SEQUENCE_ACCESS_ERROR", 4087, "Sequence \'%-.64s.%-.64s\' access error" }, -{ "ER_SEQUENCE_BINLOG_FORMAT", 4088, "Sequences requires binlog_format mixed or row" }, -{ "ER_NOT_SEQUENCE", 4089, "\'%-.64s.%-.64s\' is not a SEQUENCE" }, -{ "ER_NOT_SEQUENCE2", 4090, "\'%-.192s\' is not a SEQUENCE" }, -{ "ER_UNKNOWN_SEQUENCES", 4091, "Unknown SEQUENCE: \'%-.300s\'" }, -{ "ER_UNKNOWN_VIEW", 4092, "Unknown VIEW: \'%-.300s\'" }, -{ "ER_WRONG_INSERT_INTO_SEQUENCE", 4093, "Wrong INSERT into a SEQUENCE. One can only do single table INSERT into a sequence object (like with mariadb-dump). If you want to change the SEQUENCE, use ALTER SEQUENCE instead." }, -{ "ER_SP_STACK_TRACE", 4094, "At line %u in %s" }, -{ "ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY", 4095, "Subroutine \'%-.192s\' is declared in the package specification but is not defined in the package body" }, -{ "ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED", 4096, "Subroutine \'%-.192s\' has a forward declaration but is not defined" }, -{ "ER_COMPRESSED_COLUMN_USED_AS_KEY", 4097, "Compressed column \'%-.192s\' can\'t be used in key specification" }, -{ "ER_UNKNOWN_COMPRESSION_METHOD", 4098, "Unknown compression method: %s" }, -{ "ER_WRONG_NUMBER_OF_VALUES_IN_TVC", 4099, "The used table value constructor has a different number of values" }, -{ "ER_FIELD_REFERENCE_IN_TVC", 4100, "Field reference \'%-.192s\' can\'t be used in table value constructor" }, -{ "ER_WRONG_TYPE_FOR_PERCENTILE_FUNC", 4101, "Numeric datatype is required for %s function" }, -{ "ER_ARGUMENT_NOT_CONSTANT", 4102, "Argument to the %s function is not a constant for a partition" }, -{ "ER_ARGUMENT_OUT_OF_RANGE", 4103, "Argument to the %s function does not belong to the range [0,1]" }, -{ "ER_WRONG_TYPE_OF_ARGUMENT", 4104, "%s function only accepts arguments that can be converted to numerical types" }, -{ "ER_NOT_AGGREGATE_FUNCTION", 4105, "Aggregate specific instruction (FETCH GROUP NEXT ROW) used in a wrong context" }, -{ "ER_INVALID_AGGREGATE_FUNCTION", 4106, "Aggregate specific instruction(FETCH GROUP NEXT ROW) missing from the aggregate function" }, -{ "ER_INVALID_VALUE_TO_LIMIT", 4107, "Limit only accepts integer values" }, -{ "ER_INVISIBLE_NOT_NULL_WITHOUT_DEFAULT", 4108, "Invisible column %`s must have a default value" }, -{ "ER_UPDATE_INFO_WITH_SYSTEM_VERSIONING", 4109, "Rows matched: %ld Changed: %ld Inserted: %ld Warnings: %ld" }, -{ "ER_VERS_FIELD_WRONG_TYPE", 4110, "%`s must be of type %s for system-versioned table %`s" }, -{ "ER_VERS_ENGINE_UNSUPPORTED", 4111, "Transaction-precise system versioning for %`s is not supported" }, -{ "ER_UNUSED_23", 4112, "You should never see it" }, -{ "ER_PARTITION_WRONG_TYPE", 4113, "Wrong partitioning type, expected type: %`s" }, -{ "WARN_VERS_PART_FULL", 4114, "Versioned table %`s.%`s: last HISTORY partition (%`s) is out of %s, need more HISTORY partitions" }, -{ "WARN_VERS_PARAMETERS", 4115, "Maybe missing parameters: %s" }, -{ "ER_VERS_DROP_PARTITION_INTERVAL", 4116, "Can only drop oldest partitions when rotating by INTERVAL" }, -{ "ER_UNUSED_25", 4117, "You should never see it" }, -{ "WARN_VERS_PART_NON_HISTORICAL", 4118, "Partition %`s contains non-historical data" }, -{ "ER_VERS_ALTER_NOT_ALLOWED", 4119, "Not allowed for system-versioned %`s.%`s. Change @@system_versioning_alter_history to proceed with ALTER." }, -{ "ER_VERS_ALTER_ENGINE_PROHIBITED", 4120, "Not allowed for system-versioned %`s.%`s. Change to/from native system versioning engine is not supported." }, -{ "ER_VERS_RANGE_PROHIBITED", 4121, "SYSTEM_TIME range selector is not allowed" }, -{ "ER_CONFLICTING_FOR_SYSTEM_TIME", 4122, "Conflicting FOR SYSTEM_TIME clauses in WITH RECURSIVE" }, -{ "ER_VERS_TABLE_MUST_HAVE_COLUMNS", 4123, "Table %`s must have at least one versioned column" }, -{ "ER_VERS_NOT_VERSIONED", 4124, "Table %`s is not system-versioned" }, -{ "ER_MISSING", 4125, "Wrong parameters for %`s: missing \'%s\'" }, -{ "ER_VERS_PERIOD_COLUMNS", 4126, "PERIOD FOR SYSTEM_TIME must use columns %`s and %`s" }, -{ "ER_PART_WRONG_VALUE", 4127, "Wrong parameters for partitioned %`s: wrong value for \'%s\'" }, -{ "ER_VERS_WRONG_PARTS", 4128, "Wrong partitions for %`s: must have at least one HISTORY and exactly one last CURRENT" }, -{ "ER_VERS_NO_TRX_ID", 4129, "TRX_ID %llu not found in `mysql.transaction_registry`" }, -{ "ER_VERS_ALTER_SYSTEM_FIELD", 4130, "Can not change system versioning field %`s" }, -{ "ER_DROP_VERSIONING_SYSTEM_TIME_PARTITION", 4131, "Can not DROP SYSTEM VERSIONING for table %`s partitioned BY SYSTEM_TIME" }, -{ "ER_VERS_DB_NOT_SUPPORTED", 4132, "System-versioned tables in the %`s database are not supported" }, -{ "ER_VERS_TRT_IS_DISABLED", 4133, "Transaction registry is disabled" }, -{ "ER_VERS_DUPLICATE_ROW_START_END", 4134, "Duplicate ROW %s column %`s" }, -{ "ER_VERS_ALREADY_VERSIONED", 4135, "Table %`s is already system-versioned" }, -{ "ER_UNUSED_24", 4136, "You should never see it" }, -{ "ER_VERS_NOT_SUPPORTED", 4137, "System-versioned tables do not support %s" }, -{ "ER_VERS_TRX_PART_HISTORIC_ROW_NOT_SUPPORTED", 4138, "Transaction-precise system-versioned tables do not support partitioning by ROW START or ROW END" }, -{ "ER_INDEX_FILE_FULL", 4139, "The index file for table \'%-.192s\' is full" }, -{ "ER_UPDATED_COLUMN_ONLY_ONCE", 4140, "The column %`s.%`s cannot be changed more than once in a single UPDATE statement" }, -{ "ER_EMPTY_ROW_IN_TVC", 4141, "Row with no elements is not allowed in table value constructor in this context" }, -{ "ER_VERS_QUERY_IN_PARTITION", 4142, "SYSTEM_TIME partitions in table %`s does not support historical query" }, -{ "ER_KEY_DOESNT_SUPPORT", 4143, "%s index %`s does not support this operation" }, -{ "ER_ALTER_OPERATION_TABLE_OPTIONS_NEED_REBUILD", 4144, "Changing table options requires the table to be rebuilt" }, -{ "ER_BACKUP_LOCK_IS_ACTIVE", 4145, "Can\'t execute the command as you have a BACKUP STAGE active" }, -{ "ER_BACKUP_NOT_RUNNING", 4146, "You must start backup with \"BACKUP STAGE START\"" }, -{ "ER_BACKUP_WRONG_STAGE", 4147, "Backup stage \'%s\' is same or before current backup stage \'%s\'" }, -{ "ER_BACKUP_STAGE_FAILED", 4148, "Backup stage \'%s\' failed" }, -{ "ER_BACKUP_UNKNOWN_STAGE", 4149, "Unknown backup stage: \'%s\'. Stage should be one of START, FLUSH, BLOCK_DDL, BLOCK_COMMIT or END" }, -{ "ER_USER_IS_BLOCKED", 4150, "User is blocked because of too many credential errors; unblock with \'FLUSH PRIVILEGES\'" }, -{ "ER_ACCOUNT_HAS_BEEN_LOCKED", 4151, "Access denied, this account is locked" }, -{ "ER_PERIOD_TEMPORARY_NOT_ALLOWED", 4152, "Application-time period table cannot be temporary" }, -{ "ER_PERIOD_TYPES_MISMATCH", 4153, "Fields of PERIOD FOR %`s have different types" }, -{ "ER_MORE_THAN_ONE_PERIOD", 4154, "Cannot specify more than one application-time period" }, -{ "ER_PERIOD_FIELD_WRONG_ATTRIBUTES", 4155, "Period field %`s cannot be %s" }, -{ "ER_PERIOD_NOT_FOUND", 4156, "Period %`s is not found in table" }, -{ "ER_PERIOD_COLUMNS_UPDATED", 4157, "Column %`s used in period %`s specified in update SET list" }, -{ "ER_PERIOD_CONSTRAINT_DROP", 4158, "Can\'t DROP CONSTRAINT `%s`. Use DROP PERIOD `%s` for this" }, -{ "ER_TOO_LONG_KEYPART", 4159, "Specified key part was too long; max key part length is %u bytes" }, -{ "ER_TOO_LONG_DATABASE_COMMENT", 4160, "Comment for database \'%-.64s\' is too long (max = %u)" }, -{ "ER_UNKNOWN_DATA_TYPE", 4161, "Unknown data type: \'%-.64s\'" }, -{ "ER_UNKNOWN_OPERATOR", 4162, "Operator does not exists: \'%-.128s\'" }, -{ "ER_WARN_HISTORY_ROW_START_TIME", 4163, "Table `%s.%s` history row start \'%s\' is later than row end \'%s\'" }, -{ "ER_PART_STARTS_BEYOND_INTERVAL", 4164, "%`s: STARTS is later than query time, first history partition may exceed INTERVAL value" }, -{ "ER_GALERA_REPLICATION_NOT_SUPPORTED", 4165, "DDL-statement is forbidden as table storage engine does not support Galera replication" }, -{ "ER_LOAD_INFILE_CAPABILITY_DISABLED", 4166, "The used command is not allowed because the MariaDB server or client has disabled the local infile capability" }, -{ "ER_NO_SECURE_TRANSPORTS_CONFIGURED", 4167, "No secure transports are configured, unable to set --require_secure_transport=ON" }, -{ "ER_SLAVE_IGNORED_SHARED_TABLE", 4168, "Slave SQL thread ignored the \'%s\' because table is shared" }, -{ "ER_NO_AUTOINCREMENT_WITH_UNIQUE", 4169, "AUTO_INCREMENT column %`s cannot be used in the UNIQUE index %`s" }, -{ "ER_KEY_CONTAINS_PERIOD_FIELDS", 4170, "Key %`s cannot explicitly include column %`s" }, -{ "ER_KEY_CANT_HAVE_WITHOUT_OVERLAPS", 4171, "Key %`s cannot have WITHOUT OVERLAPS" }, -{ "ER_NOT_ALLOWED_IN_THIS_CONTEXT", 4172, "\'%-.128s\' is not allowed in this context" }, -{ "ER_DATA_WAS_COMMITED_UNDER_ROLLBACK", 4173, "Engine %s does not support rollback. Changes were committed during rollback call" }, diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/mysqld_error.h b/VCMP-LUA/modules/mariadb/include/mysql/server/mysqld_error.h deleted file mode 100644 index 04ec2da..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/mysqld_error.h +++ /dev/null @@ -1,1225 +0,0 @@ -/* Autogenerated file, please don't edit */ - -#ifndef ER_ERROR_FIRST -#define ER_ERROR_FIRST 1000 -#define ER_HASHCHK 1000 -#define ER_NISAMCHK 1001 -#define ER_NO 1002 -#define ER_YES 1003 -#define ER_CANT_CREATE_FILE 1004 -#define ER_CANT_CREATE_TABLE 1005 -#define ER_CANT_CREATE_DB 1006 -#define ER_DB_CREATE_EXISTS 1007 -#define ER_DB_DROP_EXISTS 1008 -#define ER_DB_DROP_DELETE 1009 -#define ER_DB_DROP_RMDIR 1010 -#define ER_CANT_DELETE_FILE 1011 -#define ER_CANT_FIND_SYSTEM_REC 1012 -#define ER_CANT_GET_STAT 1013 -#define ER_CANT_GET_WD 1014 -#define ER_CANT_LOCK 1015 -#define ER_CANT_OPEN_FILE 1016 -#define ER_FILE_NOT_FOUND 1017 -#define ER_CANT_READ_DIR 1018 -#define ER_CANT_SET_WD 1019 -#define ER_CHECKREAD 1020 -#define ER_DISK_FULL 1021 -#define ER_DUP_KEY 1022 -#define ER_ERROR_ON_CLOSE 1023 -#define ER_ERROR_ON_READ 1024 -#define ER_ERROR_ON_RENAME 1025 -#define ER_ERROR_ON_WRITE 1026 -#define ER_FILE_USED 1027 -#define ER_FILSORT_ABORT 1028 -#define ER_FORM_NOT_FOUND 1029 -#define ER_GET_ERRNO 1030 -#define ER_ILLEGAL_HA 1031 -#define ER_KEY_NOT_FOUND 1032 -#define ER_NOT_FORM_FILE 1033 -#define ER_NOT_KEYFILE 1034 -#define ER_OLD_KEYFILE 1035 -#define ER_OPEN_AS_READONLY 1036 -#define ER_OUTOFMEMORY 1037 -#define ER_OUT_OF_SORTMEMORY 1038 -#define ER_UNEXPECTED_EOF 1039 -#define ER_CON_COUNT_ERROR 1040 -#define ER_OUT_OF_RESOURCES 1041 -#define ER_BAD_HOST_ERROR 1042 -#define ER_HANDSHAKE_ERROR 1043 -#define ER_DBACCESS_DENIED_ERROR 1044 -#define ER_ACCESS_DENIED_ERROR 1045 -#define ER_NO_DB_ERROR 1046 -#define ER_UNKNOWN_COM_ERROR 1047 -#define ER_BAD_NULL_ERROR 1048 -#define ER_BAD_DB_ERROR 1049 -#define ER_TABLE_EXISTS_ERROR 1050 -#define ER_BAD_TABLE_ERROR 1051 -#define ER_NON_UNIQ_ERROR 1052 -#define ER_SERVER_SHUTDOWN 1053 -#define ER_BAD_FIELD_ERROR 1054 -#define ER_WRONG_FIELD_WITH_GROUP 1055 -#define ER_WRONG_GROUP_FIELD 1056 -#define ER_WRONG_SUM_SELECT 1057 -#define ER_WRONG_VALUE_COUNT 1058 -#define ER_TOO_LONG_IDENT 1059 -#define ER_DUP_FIELDNAME 1060 -#define ER_DUP_KEYNAME 1061 -#define ER_DUP_ENTRY 1062 -#define ER_WRONG_FIELD_SPEC 1063 -#define ER_PARSE_ERROR 1064 -#define ER_EMPTY_QUERY 1065 -#define ER_NONUNIQ_TABLE 1066 -#define ER_INVALID_DEFAULT 1067 -#define ER_MULTIPLE_PRI_KEY 1068 -#define ER_TOO_MANY_KEYS 1069 -#define ER_TOO_MANY_KEY_PARTS 1070 -#define ER_TOO_LONG_KEY 1071 -#define ER_KEY_COLUMN_DOES_NOT_EXITS 1072 -#define ER_BLOB_USED_AS_KEY 1073 -#define ER_TOO_BIG_FIELDLENGTH 1074 -#define ER_WRONG_AUTO_KEY 1075 -#define ER_BINLOG_CANT_DELETE_GTID_DOMAIN 1076 -#define ER_NORMAL_SHUTDOWN 1077 -#define ER_GOT_SIGNAL 1078 -#define ER_SHUTDOWN_COMPLETE 1079 -#define ER_FORCING_CLOSE 1080 -#define ER_IPSOCK_ERROR 1081 -#define ER_NO_SUCH_INDEX 1082 -#define ER_WRONG_FIELD_TERMINATORS 1083 -#define ER_BLOBS_AND_NO_TERMINATED 1084 -#define ER_TEXTFILE_NOT_READABLE 1085 -#define ER_FILE_EXISTS_ERROR 1086 -#define ER_LOAD_INFO 1087 -#define ER_ALTER_INFO 1088 -#define ER_WRONG_SUB_KEY 1089 -#define ER_CANT_REMOVE_ALL_FIELDS 1090 -#define ER_CANT_DROP_FIELD_OR_KEY 1091 -#define ER_INSERT_INFO 1092 -#define ER_UPDATE_TABLE_USED 1093 -#define ER_NO_SUCH_THREAD 1094 -#define ER_KILL_DENIED_ERROR 1095 -#define ER_NO_TABLES_USED 1096 -#define ER_TOO_BIG_SET 1097 -#define ER_NO_UNIQUE_LOGFILE 1098 -#define ER_TABLE_NOT_LOCKED_FOR_WRITE 1099 -#define ER_TABLE_NOT_LOCKED 1100 -#define ER_UNUSED_17 1101 -#define ER_WRONG_DB_NAME 1102 -#define ER_WRONG_TABLE_NAME 1103 -#define ER_TOO_BIG_SELECT 1104 -#define ER_UNKNOWN_ERROR 1105 -#define ER_UNKNOWN_PROCEDURE 1106 -#define ER_WRONG_PARAMCOUNT_TO_PROCEDURE 1107 -#define ER_WRONG_PARAMETERS_TO_PROCEDURE 1108 -#define ER_UNKNOWN_TABLE 1109 -#define ER_FIELD_SPECIFIED_TWICE 1110 -#define ER_INVALID_GROUP_FUNC_USE 1111 -#define ER_UNSUPPORTED_EXTENSION 1112 -#define ER_TABLE_MUST_HAVE_COLUMNS 1113 -#define ER_RECORD_FILE_FULL 1114 -#define ER_UNKNOWN_CHARACTER_SET 1115 -#define ER_TOO_MANY_TABLES 1116 -#define ER_TOO_MANY_FIELDS 1117 -#define ER_TOO_BIG_ROWSIZE 1118 -#define ER_STACK_OVERRUN 1119 -#define ER_WRONG_OUTER_JOIN 1120 -#define ER_NULL_COLUMN_IN_INDEX 1121 -#define ER_CANT_FIND_UDF 1122 -#define ER_CANT_INITIALIZE_UDF 1123 -#define ER_UDF_NO_PATHS 1124 -#define ER_UDF_EXISTS 1125 -#define ER_CANT_OPEN_LIBRARY 1126 -#define ER_CANT_FIND_DL_ENTRY 1127 -#define ER_FUNCTION_NOT_DEFINED 1128 -#define ER_HOST_IS_BLOCKED 1129 -#define ER_HOST_NOT_PRIVILEGED 1130 -#define ER_PASSWORD_ANONYMOUS_USER 1131 -#define ER_PASSWORD_NOT_ALLOWED 1132 -#define ER_PASSWORD_NO_MATCH 1133 -#define ER_UPDATE_INFO 1134 -#define ER_CANT_CREATE_THREAD 1135 -#define ER_WRONG_VALUE_COUNT_ON_ROW 1136 -#define ER_CANT_REOPEN_TABLE 1137 -#define ER_INVALID_USE_OF_NULL 1138 -#define ER_REGEXP_ERROR 1139 -#define ER_MIX_OF_GROUP_FUNC_AND_FIELDS 1140 -#define ER_NONEXISTING_GRANT 1141 -#define ER_TABLEACCESS_DENIED_ERROR 1142 -#define ER_COLUMNACCESS_DENIED_ERROR 1143 -#define ER_ILLEGAL_GRANT_FOR_TABLE 1144 -#define ER_GRANT_WRONG_HOST_OR_USER 1145 -#define ER_NO_SUCH_TABLE 1146 -#define ER_NONEXISTING_TABLE_GRANT 1147 -#define ER_NOT_ALLOWED_COMMAND 1148 -#define ER_SYNTAX_ERROR 1149 -#define ER_DELAYED_CANT_CHANGE_LOCK 1150 -#define ER_TOO_MANY_DELAYED_THREADS 1151 -#define ER_ABORTING_CONNECTION 1152 -#define ER_NET_PACKET_TOO_LARGE 1153 -#define ER_NET_READ_ERROR_FROM_PIPE 1154 -#define ER_NET_FCNTL_ERROR 1155 -#define ER_NET_PACKETS_OUT_OF_ORDER 1156 -#define ER_NET_UNCOMPRESS_ERROR 1157 -#define ER_NET_READ_ERROR 1158 -#define ER_NET_READ_INTERRUPTED 1159 -#define ER_NET_ERROR_ON_WRITE 1160 -#define ER_NET_WRITE_INTERRUPTED 1161 -#define ER_TOO_LONG_STRING 1162 -#define ER_TABLE_CANT_HANDLE_BLOB 1163 -#define ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 1164 -#define ER_DELAYED_INSERT_TABLE_LOCKED 1165 -#define ER_WRONG_COLUMN_NAME 1166 -#define ER_WRONG_KEY_COLUMN 1167 -#define ER_WRONG_MRG_TABLE 1168 -#define ER_DUP_UNIQUE 1169 -#define ER_BLOB_KEY_WITHOUT_LENGTH 1170 -#define ER_PRIMARY_CANT_HAVE_NULL 1171 -#define ER_TOO_MANY_ROWS 1172 -#define ER_REQUIRES_PRIMARY_KEY 1173 -#define ER_NO_RAID_COMPILED 1174 -#define ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE 1175 -#define ER_KEY_DOES_NOT_EXISTS 1176 -#define ER_CHECK_NO_SUCH_TABLE 1177 -#define ER_CHECK_NOT_IMPLEMENTED 1178 -#define ER_CANT_DO_THIS_DURING_AN_TRANSACTION 1179 -#define ER_ERROR_DURING_COMMIT 1180 -#define ER_ERROR_DURING_ROLLBACK 1181 -#define ER_ERROR_DURING_FLUSH_LOGS 1182 -#define ER_ERROR_DURING_CHECKPOINT 1183 -#define ER_NEW_ABORTING_CONNECTION 1184 -#define ER_UNUSED_10 1185 -#define ER_FLUSH_MASTER_BINLOG_CLOSED 1186 -#define ER_INDEX_REBUILD 1187 -#define ER_MASTER 1188 -#define ER_MASTER_NET_READ 1189 -#define ER_MASTER_NET_WRITE 1190 -#define ER_FT_MATCHING_KEY_NOT_FOUND 1191 -#define ER_LOCK_OR_ACTIVE_TRANSACTION 1192 -#define ER_UNKNOWN_SYSTEM_VARIABLE 1193 -#define ER_CRASHED_ON_USAGE 1194 -#define ER_CRASHED_ON_REPAIR 1195 -#define ER_WARNING_NOT_COMPLETE_ROLLBACK 1196 -#define ER_TRANS_CACHE_FULL 1197 -#define ER_SLAVE_MUST_STOP 1198 -#define ER_SLAVE_NOT_RUNNING 1199 -#define ER_BAD_SLAVE 1200 -#define ER_MASTER_INFO 1201 -#define ER_SLAVE_THREAD 1202 -#define ER_TOO_MANY_USER_CONNECTIONS 1203 -#define ER_SET_CONSTANTS_ONLY 1204 -#define ER_LOCK_WAIT_TIMEOUT 1205 -#define ER_LOCK_TABLE_FULL 1206 -#define ER_READ_ONLY_TRANSACTION 1207 -#define ER_DROP_DB_WITH_READ_LOCK 1208 -#define ER_CREATE_DB_WITH_READ_LOCK 1209 -#define ER_WRONG_ARGUMENTS 1210 -#define ER_NO_PERMISSION_TO_CREATE_USER 1211 -#define ER_UNION_TABLES_IN_DIFFERENT_DIR 1212 -#define ER_LOCK_DEADLOCK 1213 -#define ER_TABLE_CANT_HANDLE_FT 1214 -#define ER_CANNOT_ADD_FOREIGN 1215 -#define ER_NO_REFERENCED_ROW 1216 -#define ER_ROW_IS_REFERENCED 1217 -#define ER_CONNECT_TO_MASTER 1218 -#define ER_QUERY_ON_MASTER 1219 -#define ER_ERROR_WHEN_EXECUTING_COMMAND 1220 -#define ER_WRONG_USAGE 1221 -#define ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT 1222 -#define ER_CANT_UPDATE_WITH_READLOCK 1223 -#define ER_MIXING_NOT_ALLOWED 1224 -#define ER_DUP_ARGUMENT 1225 -#define ER_USER_LIMIT_REACHED 1226 -#define ER_SPECIFIC_ACCESS_DENIED_ERROR 1227 -#define ER_LOCAL_VARIABLE 1228 -#define ER_GLOBAL_VARIABLE 1229 -#define ER_NO_DEFAULT 1230 -#define ER_WRONG_VALUE_FOR_VAR 1231 -#define ER_WRONG_TYPE_FOR_VAR 1232 -#define ER_VAR_CANT_BE_READ 1233 -#define ER_CANT_USE_OPTION_HERE 1234 -#define ER_NOT_SUPPORTED_YET 1235 -#define ER_MASTER_FATAL_ERROR_READING_BINLOG 1236 -#define ER_SLAVE_IGNORED_TABLE 1237 -#define ER_INCORRECT_GLOBAL_LOCAL_VAR 1238 -#define ER_WRONG_FK_DEF 1239 -#define ER_KEY_REF_DO_NOT_MATCH_TABLE_REF 1240 -#define ER_OPERAND_COLUMNS 1241 -#define ER_SUBQUERY_NO_1_ROW 1242 -#define ER_UNKNOWN_STMT_HANDLER 1243 -#define ER_CORRUPT_HELP_DB 1244 -#define ER_CYCLIC_REFERENCE 1245 -#define ER_AUTO_CONVERT 1246 -#define ER_ILLEGAL_REFERENCE 1247 -#define ER_DERIVED_MUST_HAVE_ALIAS 1248 -#define ER_SELECT_REDUCED 1249 -#define ER_TABLENAME_NOT_ALLOWED_HERE 1250 -#define ER_NOT_SUPPORTED_AUTH_MODE 1251 -#define ER_SPATIAL_CANT_HAVE_NULL 1252 -#define ER_COLLATION_CHARSET_MISMATCH 1253 -#define ER_SLAVE_WAS_RUNNING 1254 -#define ER_SLAVE_WAS_NOT_RUNNING 1255 -#define ER_TOO_BIG_FOR_UNCOMPRESS 1256 -#define ER_ZLIB_Z_MEM_ERROR 1257 -#define ER_ZLIB_Z_BUF_ERROR 1258 -#define ER_ZLIB_Z_DATA_ERROR 1259 -#define ER_CUT_VALUE_GROUP_CONCAT 1260 -#define ER_WARN_TOO_FEW_RECORDS 1261 -#define ER_WARN_TOO_MANY_RECORDS 1262 -#define ER_WARN_NULL_TO_NOTNULL 1263 -#define ER_WARN_DATA_OUT_OF_RANGE 1264 -#define WARN_DATA_TRUNCATED 1265 -#define ER_WARN_USING_OTHER_HANDLER 1266 -#define ER_CANT_AGGREGATE_2COLLATIONS 1267 -#define ER_DROP_USER 1268 -#define ER_REVOKE_GRANTS 1269 -#define ER_CANT_AGGREGATE_3COLLATIONS 1270 -#define ER_CANT_AGGREGATE_NCOLLATIONS 1271 -#define ER_VARIABLE_IS_NOT_STRUCT 1272 -#define ER_UNKNOWN_COLLATION 1273 -#define ER_SLAVE_IGNORED_SSL_PARAMS 1274 -#define ER_SERVER_IS_IN_SECURE_AUTH_MODE 1275 -#define ER_WARN_FIELD_RESOLVED 1276 -#define ER_BAD_SLAVE_UNTIL_COND 1277 -#define ER_MISSING_SKIP_SLAVE 1278 -#define ER_UNTIL_COND_IGNORED 1279 -#define ER_WRONG_NAME_FOR_INDEX 1280 -#define ER_WRONG_NAME_FOR_CATALOG 1281 -#define ER_WARN_QC_RESIZE 1282 -#define ER_BAD_FT_COLUMN 1283 -#define ER_UNKNOWN_KEY_CACHE 1284 -#define ER_WARN_HOSTNAME_WONT_WORK 1285 -#define ER_UNKNOWN_STORAGE_ENGINE 1286 -#define ER_WARN_DEPRECATED_SYNTAX 1287 -#define ER_NON_UPDATABLE_TABLE 1288 -#define ER_FEATURE_DISABLED 1289 -#define ER_OPTION_PREVENTS_STATEMENT 1290 -#define ER_DUPLICATED_VALUE_IN_TYPE 1291 -#define ER_TRUNCATED_WRONG_VALUE 1292 -#define ER_TOO_MUCH_AUTO_TIMESTAMP_COLS 1293 -#define ER_INVALID_ON_UPDATE 1294 -#define ER_UNSUPPORTED_PS 1295 -#define ER_GET_ERRMSG 1296 -#define ER_GET_TEMPORARY_ERRMSG 1297 -#define ER_UNKNOWN_TIME_ZONE 1298 -#define ER_WARN_INVALID_TIMESTAMP 1299 -#define ER_INVALID_CHARACTER_STRING 1300 -#define ER_WARN_ALLOWED_PACKET_OVERFLOWED 1301 -#define ER_CONFLICTING_DECLARATIONS 1302 -#define ER_SP_NO_RECURSIVE_CREATE 1303 -#define ER_SP_ALREADY_EXISTS 1304 -#define ER_SP_DOES_NOT_EXIST 1305 -#define ER_SP_DROP_FAILED 1306 -#define ER_SP_STORE_FAILED 1307 -#define ER_SP_LILABEL_MISMATCH 1308 -#define ER_SP_LABEL_REDEFINE 1309 -#define ER_SP_LABEL_MISMATCH 1310 -#define ER_SP_UNINIT_VAR 1311 -#define ER_SP_BADSELECT 1312 -#define ER_SP_BADRETURN 1313 -#define ER_SP_BADSTATEMENT 1314 -#define ER_UPDATE_LOG_DEPRECATED_IGNORED 1315 -#define ER_UPDATE_LOG_DEPRECATED_TRANSLATED 1316 -#define ER_QUERY_INTERRUPTED 1317 -#define ER_SP_WRONG_NO_OF_ARGS 1318 -#define ER_SP_COND_MISMATCH 1319 -#define ER_SP_NORETURN 1320 -#define ER_SP_NORETURNEND 1321 -#define ER_SP_BAD_CURSOR_QUERY 1322 -#define ER_SP_BAD_CURSOR_SELECT 1323 -#define ER_SP_CURSOR_MISMATCH 1324 -#define ER_SP_CURSOR_ALREADY_OPEN 1325 -#define ER_SP_CURSOR_NOT_OPEN 1326 -#define ER_SP_UNDECLARED_VAR 1327 -#define ER_SP_WRONG_NO_OF_FETCH_ARGS 1328 -#define ER_SP_FETCH_NO_DATA 1329 -#define ER_SP_DUP_PARAM 1330 -#define ER_SP_DUP_VAR 1331 -#define ER_SP_DUP_COND 1332 -#define ER_SP_DUP_CURS 1333 -#define ER_SP_CANT_ALTER 1334 -#define ER_SP_SUBSELECT_NYI 1335 -#define ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG 1336 -#define ER_SP_VARCOND_AFTER_CURSHNDLR 1337 -#define ER_SP_CURSOR_AFTER_HANDLER 1338 -#define ER_SP_CASE_NOT_FOUND 1339 -#define ER_FPARSER_TOO_BIG_FILE 1340 -#define ER_FPARSER_BAD_HEADER 1341 -#define ER_FPARSER_EOF_IN_COMMENT 1342 -#define ER_FPARSER_ERROR_IN_PARAMETER 1343 -#define ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER 1344 -#define ER_VIEW_NO_EXPLAIN 1345 -#define ER_FRM_UNKNOWN_TYPE 1346 -#define ER_WRONG_OBJECT 1347 -#define ER_NONUPDATEABLE_COLUMN 1348 -#define ER_VIEW_SELECT_DERIVED 1349 -#define ER_VIEW_SELECT_CLAUSE 1350 -#define ER_VIEW_SELECT_VARIABLE 1351 -#define ER_VIEW_SELECT_TMPTABLE 1352 -#define ER_VIEW_WRONG_LIST 1353 -#define ER_WARN_VIEW_MERGE 1354 -#define ER_WARN_VIEW_WITHOUT_KEY 1355 -#define ER_VIEW_INVALID 1356 -#define ER_SP_NO_DROP_SP 1357 -#define ER_SP_GOTO_IN_HNDLR 1358 -#define ER_TRG_ALREADY_EXISTS 1359 -#define ER_TRG_DOES_NOT_EXIST 1360 -#define ER_TRG_ON_VIEW_OR_TEMP_TABLE 1361 -#define ER_TRG_CANT_CHANGE_ROW 1362 -#define ER_TRG_NO_SUCH_ROW_IN_TRG 1363 -#define ER_NO_DEFAULT_FOR_FIELD 1364 -#define ER_DIVISION_BY_ZERO 1365 -#define ER_TRUNCATED_WRONG_VALUE_FOR_FIELD 1366 -#define ER_ILLEGAL_VALUE_FOR_TYPE 1367 -#define ER_VIEW_NONUPD_CHECK 1368 -#define ER_VIEW_CHECK_FAILED 1369 -#define ER_PROCACCESS_DENIED_ERROR 1370 -#define ER_RELAY_LOG_FAIL 1371 -#define ER_PASSWD_LENGTH 1372 -#define ER_UNKNOWN_TARGET_BINLOG 1373 -#define ER_IO_ERR_LOG_INDEX_READ 1374 -#define ER_BINLOG_PURGE_PROHIBITED 1375 -#define ER_FSEEK_FAIL 1376 -#define ER_BINLOG_PURGE_FATAL_ERR 1377 -#define ER_LOG_IN_USE 1378 -#define ER_LOG_PURGE_UNKNOWN_ERR 1379 -#define ER_RELAY_LOG_INIT 1380 -#define ER_NO_BINARY_LOGGING 1381 -#define ER_RESERVED_SYNTAX 1382 -#define ER_WSAS_FAILED 1383 -#define ER_DIFF_GROUPS_PROC 1384 -#define ER_NO_GROUP_FOR_PROC 1385 -#define ER_ORDER_WITH_PROC 1386 -#define ER_LOGGING_PROHIBIT_CHANGING_OF 1387 -#define ER_NO_FILE_MAPPING 1388 -#define ER_WRONG_MAGIC 1389 -#define ER_PS_MANY_PARAM 1390 -#define ER_KEY_PART_0 1391 -#define ER_VIEW_CHECKSUM 1392 -#define ER_VIEW_MULTIUPDATE 1393 -#define ER_VIEW_NO_INSERT_FIELD_LIST 1394 -#define ER_VIEW_DELETE_MERGE_VIEW 1395 -#define ER_CANNOT_USER 1396 -#define ER_XAER_NOTA 1397 -#define ER_XAER_INVAL 1398 -#define ER_XAER_RMFAIL 1399 -#define ER_XAER_OUTSIDE 1400 -#define ER_XAER_RMERR 1401 -#define ER_XA_RBROLLBACK 1402 -#define ER_NONEXISTING_PROC_GRANT 1403 -#define ER_PROC_AUTO_GRANT_FAIL 1404 -#define ER_PROC_AUTO_REVOKE_FAIL 1405 -#define ER_DATA_TOO_LONG 1406 -#define ER_SP_BAD_SQLSTATE 1407 -#define ER_STARTUP 1408 -#define ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR 1409 -#define ER_CANT_CREATE_USER_WITH_GRANT 1410 -#define ER_WRONG_VALUE_FOR_TYPE 1411 -#define ER_TABLE_DEF_CHANGED 1412 -#define ER_SP_DUP_HANDLER 1413 -#define ER_SP_NOT_VAR_ARG 1414 -#define ER_SP_NO_RETSET 1415 -#define ER_CANT_CREATE_GEOMETRY_OBJECT 1416 -#define ER_FAILED_ROUTINE_BREAK_BINLOG 1417 -#define ER_BINLOG_UNSAFE_ROUTINE 1418 -#define ER_BINLOG_CREATE_ROUTINE_NEED_SUPER 1419 -#define ER_EXEC_STMT_WITH_OPEN_CURSOR 1420 -#define ER_STMT_HAS_NO_OPEN_CURSOR 1421 -#define ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG 1422 -#define ER_NO_DEFAULT_FOR_VIEW_FIELD 1423 -#define ER_SP_NO_RECURSION 1424 -#define ER_TOO_BIG_SCALE 1425 -#define ER_TOO_BIG_PRECISION 1426 -#define ER_M_BIGGER_THAN_D 1427 -#define ER_WRONG_LOCK_OF_SYSTEM_TABLE 1428 -#define ER_CONNECT_TO_FOREIGN_DATA_SOURCE 1429 -#define ER_QUERY_ON_FOREIGN_DATA_SOURCE 1430 -#define ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST 1431 -#define ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE 1432 -#define ER_FOREIGN_DATA_STRING_INVALID 1433 -#define ER_CANT_CREATE_FEDERATED_TABLE 1434 -#define ER_TRG_IN_WRONG_SCHEMA 1435 -#define ER_STACK_OVERRUN_NEED_MORE 1436 -#define ER_TOO_LONG_BODY 1437 -#define ER_WARN_CANT_DROP_DEFAULT_KEYCACHE 1438 -#define ER_TOO_BIG_DISPLAYWIDTH 1439 -#define ER_XAER_DUPID 1440 -#define ER_DATETIME_FUNCTION_OVERFLOW 1441 -#define ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG 1442 -#define ER_VIEW_PREVENT_UPDATE 1443 -#define ER_PS_NO_RECURSION 1444 -#define ER_SP_CANT_SET_AUTOCOMMIT 1445 -#define ER_MALFORMED_DEFINER 1446 -#define ER_VIEW_FRM_NO_USER 1447 -#define ER_VIEW_OTHER_USER 1448 -#define ER_NO_SUCH_USER 1449 -#define ER_FORBID_SCHEMA_CHANGE 1450 -#define ER_ROW_IS_REFERENCED_2 1451 -#define ER_NO_REFERENCED_ROW_2 1452 -#define ER_SP_BAD_VAR_SHADOW 1453 -#define ER_TRG_NO_DEFINER 1454 -#define ER_OLD_FILE_FORMAT 1455 -#define ER_SP_RECURSION_LIMIT 1456 -#define ER_SP_PROC_TABLE_CORRUPT 1457 -#define ER_SP_WRONG_NAME 1458 -#define ER_TABLE_NEEDS_UPGRADE 1459 -#define ER_SP_NO_AGGREGATE 1460 -#define ER_MAX_PREPARED_STMT_COUNT_REACHED 1461 -#define ER_VIEW_RECURSIVE 1462 -#define ER_NON_GROUPING_FIELD_USED 1463 -#define ER_TABLE_CANT_HANDLE_SPKEYS 1464 -#define ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA 1465 -#define ER_REMOVED_SPACES 1466 -#define ER_AUTOINC_READ_FAILED 1467 -#define ER_USERNAME 1468 -#define ER_HOSTNAME 1469 -#define ER_WRONG_STRING_LENGTH 1470 -#define ER_NON_INSERTABLE_TABLE 1471 -#define ER_ADMIN_WRONG_MRG_TABLE 1472 -#define ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT 1473 -#define ER_NAME_BECOMES_EMPTY 1474 -#define ER_AMBIGUOUS_FIELD_TERM 1475 -#define ER_FOREIGN_SERVER_EXISTS 1476 -#define ER_FOREIGN_SERVER_DOESNT_EXIST 1477 -#define ER_ILLEGAL_HA_CREATE_OPTION 1478 -#define ER_PARTITION_REQUIRES_VALUES_ERROR 1479 -#define ER_PARTITION_WRONG_VALUES_ERROR 1480 -#define ER_PARTITION_MAXVALUE_ERROR 1481 -#define ER_PARTITION_SUBPARTITION_ERROR 1482 -#define ER_PARTITION_SUBPART_MIX_ERROR 1483 -#define ER_PARTITION_WRONG_NO_PART_ERROR 1484 -#define ER_PARTITION_WRONG_NO_SUBPART_ERROR 1485 -#define ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR 1486 -#define ER_NOT_CONSTANT_EXPRESSION 1487 -#define ER_FIELD_NOT_FOUND_PART_ERROR 1488 -#define ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR 1489 -#define ER_INCONSISTENT_PARTITION_INFO_ERROR 1490 -#define ER_PARTITION_FUNC_NOT_ALLOWED_ERROR 1491 -#define ER_PARTITIONS_MUST_BE_DEFINED_ERROR 1492 -#define ER_RANGE_NOT_INCREASING_ERROR 1493 -#define ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR 1494 -#define ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR 1495 -#define ER_PARTITION_ENTRY_ERROR 1496 -#define ER_MIX_HANDLER_ERROR 1497 -#define ER_PARTITION_NOT_DEFINED_ERROR 1498 -#define ER_TOO_MANY_PARTITIONS_ERROR 1499 -#define ER_SUBPARTITION_ERROR 1500 -#define ER_CANT_CREATE_HANDLER_FILE 1501 -#define ER_BLOB_FIELD_IN_PART_FUNC_ERROR 1502 -#define ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF 1503 -#define ER_NO_PARTS_ERROR 1504 -#define ER_PARTITION_MGMT_ON_NONPARTITIONED 1505 -#define ER_FEATURE_NOT_SUPPORTED_WITH_PARTITIONING 1506 -#define ER_DROP_PARTITION_NON_EXISTENT 1507 -#define ER_DROP_LAST_PARTITION 1508 -#define ER_COALESCE_ONLY_ON_HASH_PARTITION 1509 -#define ER_REORG_HASH_ONLY_ON_SAME_NO 1510 -#define ER_REORG_NO_PARAM_ERROR 1511 -#define ER_ONLY_ON_RANGE_LIST_PARTITION 1512 -#define ER_ADD_PARTITION_SUBPART_ERROR 1513 -#define ER_ADD_PARTITION_NO_NEW_PARTITION 1514 -#define ER_COALESCE_PARTITION_NO_PARTITION 1515 -#define ER_REORG_PARTITION_NOT_EXIST 1516 -#define ER_SAME_NAME_PARTITION 1517 -#define ER_NO_BINLOG_ERROR 1518 -#define ER_CONSECUTIVE_REORG_PARTITIONS 1519 -#define ER_REORG_OUTSIDE_RANGE 1520 -#define ER_PARTITION_FUNCTION_FAILURE 1521 -#define ER_PART_STATE_ERROR 1522 -#define ER_LIMITED_PART_RANGE 1523 -#define ER_PLUGIN_IS_NOT_LOADED 1524 -#define ER_WRONG_VALUE 1525 -#define ER_NO_PARTITION_FOR_GIVEN_VALUE 1526 -#define ER_FILEGROUP_OPTION_ONLY_ONCE 1527 -#define ER_CREATE_FILEGROUP_FAILED 1528 -#define ER_DROP_FILEGROUP_FAILED 1529 -#define ER_TABLESPACE_AUTO_EXTEND_ERROR 1530 -#define ER_WRONG_SIZE_NUMBER 1531 -#define ER_SIZE_OVERFLOW_ERROR 1532 -#define ER_ALTER_FILEGROUP_FAILED 1533 -#define ER_BINLOG_ROW_LOGGING_FAILED 1534 -#define ER_BINLOG_ROW_WRONG_TABLE_DEF 1535 -#define ER_BINLOG_ROW_RBR_TO_SBR 1536 -#define ER_EVENT_ALREADY_EXISTS 1537 -#define ER_EVENT_STORE_FAILED 1538 -#define ER_EVENT_DOES_NOT_EXIST 1539 -#define ER_EVENT_CANT_ALTER 1540 -#define ER_EVENT_DROP_FAILED 1541 -#define ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG 1542 -#define ER_EVENT_ENDS_BEFORE_STARTS 1543 -#define ER_EVENT_EXEC_TIME_IN_THE_PAST 1544 -#define ER_EVENT_OPEN_TABLE_FAILED 1545 -#define ER_EVENT_NEITHER_M_EXPR_NOR_M_AT 1546 -#define ER_UNUSED_2 1547 -#define ER_UNUSED_3 1548 -#define ER_EVENT_CANNOT_DELETE 1549 -#define ER_EVENT_COMPILE_ERROR 1550 -#define ER_EVENT_SAME_NAME 1551 -#define ER_EVENT_DATA_TOO_LONG 1552 -#define ER_DROP_INDEX_FK 1553 -#define ER_WARN_DEPRECATED_SYNTAX_WITH_VER 1554 -#define ER_CANT_WRITE_LOCK_LOG_TABLE 1555 -#define ER_CANT_LOCK_LOG_TABLE 1556 -#define ER_UNUSED_4 1557 -#define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE 1558 -#define ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR 1559 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT 1560 -#define ER_UNUSED_13 1561 -#define ER_PARTITION_NO_TEMPORARY 1562 -#define ER_PARTITION_CONST_DOMAIN_ERROR 1563 -#define ER_PARTITION_FUNCTION_IS_NOT_ALLOWED 1564 -#define ER_DDL_LOG_ERROR 1565 -#define ER_NULL_IN_VALUES_LESS_THAN 1566 -#define ER_WRONG_PARTITION_NAME 1567 -#define ER_CANT_CHANGE_TX_CHARACTERISTICS 1568 -#define ER_DUP_ENTRY_AUTOINCREMENT_CASE 1569 -#define ER_EVENT_MODIFY_QUEUE_ERROR 1570 -#define ER_EVENT_SET_VAR_ERROR 1571 -#define ER_PARTITION_MERGE_ERROR 1572 -#define ER_CANT_ACTIVATE_LOG 1573 -#define ER_RBR_NOT_AVAILABLE 1574 -#define ER_BASE64_DECODE_ERROR 1575 -#define ER_EVENT_RECURSION_FORBIDDEN 1576 -#define ER_EVENTS_DB_ERROR 1577 -#define ER_ONLY_INTEGERS_ALLOWED 1578 -#define ER_UNSUPORTED_LOG_ENGINE 1579 -#define ER_BAD_LOG_STATEMENT 1580 -#define ER_CANT_RENAME_LOG_TABLE 1581 -#define ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT 1582 -#define ER_WRONG_PARAMETERS_TO_NATIVE_FCT 1583 -#define ER_WRONG_PARAMETERS_TO_STORED_FCT 1584 -#define ER_NATIVE_FCT_NAME_COLLISION 1585 -#define ER_DUP_ENTRY_WITH_KEY_NAME 1586 -#define ER_BINLOG_PURGE_EMFILE 1587 -#define ER_EVENT_CANNOT_CREATE_IN_THE_PAST 1588 -#define ER_EVENT_CANNOT_ALTER_IN_THE_PAST 1589 -#define ER_SLAVE_INCIDENT 1590 -#define ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT 1591 -#define ER_BINLOG_UNSAFE_STATEMENT 1592 -#define ER_SLAVE_FATAL_ERROR 1593 -#define ER_SLAVE_RELAY_LOG_READ_FAILURE 1594 -#define ER_SLAVE_RELAY_LOG_WRITE_FAILURE 1595 -#define ER_SLAVE_CREATE_EVENT_FAILURE 1596 -#define ER_SLAVE_MASTER_COM_FAILURE 1597 -#define ER_BINLOG_LOGGING_IMPOSSIBLE 1598 -#define ER_VIEW_NO_CREATION_CTX 1599 -#define ER_VIEW_INVALID_CREATION_CTX 1600 -#define ER_SR_INVALID_CREATION_CTX 1601 -#define ER_TRG_CORRUPTED_FILE 1602 -#define ER_TRG_NO_CREATION_CTX 1603 -#define ER_TRG_INVALID_CREATION_CTX 1604 -#define ER_EVENT_INVALID_CREATION_CTX 1605 -#define ER_TRG_CANT_OPEN_TABLE 1606 -#define ER_CANT_CREATE_SROUTINE 1607 -#define ER_UNUSED_11 1608 -#define ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT 1609 -#define ER_SLAVE_CORRUPT_EVENT 1610 -#define ER_LOAD_DATA_INVALID_COLUMN 1611 -#define ER_LOG_PURGE_NO_FILE 1612 -#define ER_XA_RBTIMEOUT 1613 -#define ER_XA_RBDEADLOCK 1614 -#define ER_NEED_REPREPARE 1615 -#define ER_DELAYED_NOT_SUPPORTED 1616 -#define WARN_NO_MASTER_INFO 1617 -#define WARN_OPTION_IGNORED 1618 -#define ER_PLUGIN_DELETE_BUILTIN 1619 -#define WARN_PLUGIN_BUSY 1620 -#define ER_VARIABLE_IS_READONLY 1621 -#define ER_WARN_ENGINE_TRANSACTION_ROLLBACK 1622 -#define ER_SLAVE_HEARTBEAT_FAILURE 1623 -#define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE 1624 -#define ER_UNUSED_14 1625 -#define ER_CONFLICT_FN_PARSE_ERROR 1626 -#define ER_EXCEPTIONS_WRITE_ERROR 1627 -#define ER_TOO_LONG_TABLE_COMMENT 1628 -#define ER_TOO_LONG_FIELD_COMMENT 1629 -#define ER_FUNC_INEXISTENT_NAME_COLLISION 1630 -#define ER_DATABASE_NAME 1631 -#define ER_TABLE_NAME 1632 -#define ER_PARTITION_NAME 1633 -#define ER_SUBPARTITION_NAME 1634 -#define ER_TEMPORARY_NAME 1635 -#define ER_RENAMED_NAME 1636 -#define ER_TOO_MANY_CONCURRENT_TRXS 1637 -#define WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED 1638 -#define ER_DEBUG_SYNC_TIMEOUT 1639 -#define ER_DEBUG_SYNC_HIT_LIMIT 1640 -#define ER_DUP_SIGNAL_SET 1641 -#define ER_SIGNAL_WARN 1642 -#define ER_SIGNAL_NOT_FOUND 1643 -#define ER_SIGNAL_EXCEPTION 1644 -#define ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER 1645 -#define ER_SIGNAL_BAD_CONDITION_TYPE 1646 -#define WARN_COND_ITEM_TRUNCATED 1647 -#define ER_COND_ITEM_TOO_LONG 1648 -#define ER_UNKNOWN_LOCALE 1649 -#define ER_SLAVE_IGNORE_SERVER_IDS 1650 -#define ER_QUERY_CACHE_DISABLED 1651 -#define ER_SAME_NAME_PARTITION_FIELD 1652 -#define ER_PARTITION_COLUMN_LIST_ERROR 1653 -#define ER_WRONG_TYPE_COLUMN_VALUE_ERROR 1654 -#define ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR 1655 -#define ER_MAXVALUE_IN_VALUES_IN 1656 -#define ER_TOO_MANY_VALUES_ERROR 1657 -#define ER_ROW_SINGLE_PARTITION_FIELD_ERROR 1658 -#define ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD 1659 -#define ER_PARTITION_FIELDS_TOO_LONG 1660 -#define ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE 1661 -#define ER_BINLOG_ROW_MODE_AND_STMT_ENGINE 1662 -#define ER_BINLOG_UNSAFE_AND_STMT_ENGINE 1663 -#define ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE 1664 -#define ER_BINLOG_STMT_MODE_AND_ROW_ENGINE 1665 -#define ER_BINLOG_ROW_INJECTION_AND_STMT_MODE 1666 -#define ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1667 -#define ER_BINLOG_UNSAFE_LIMIT 1668 -#define ER_BINLOG_UNSAFE_INSERT_DELAYED 1669 -#define ER_BINLOG_UNSAFE_SYSTEM_TABLE 1670 -#define ER_BINLOG_UNSAFE_AUTOINC_COLUMNS 1671 -#define ER_BINLOG_UNSAFE_UDF 1672 -#define ER_BINLOG_UNSAFE_SYSTEM_VARIABLE 1673 -#define ER_BINLOG_UNSAFE_SYSTEM_FUNCTION 1674 -#define ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS 1675 -#define ER_MESSAGE_AND_STATEMENT 1676 -#define ER_SLAVE_CONVERSION_FAILED 1677 -#define ER_SLAVE_CANT_CREATE_CONVERSION 1678 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT 1679 -#define ER_PATH_LENGTH 1680 -#define ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT 1681 -#define ER_WRONG_NATIVE_TABLE_STRUCTURE 1682 -#define ER_WRONG_PERFSCHEMA_USAGE 1683 -#define ER_WARN_I_S_SKIPPED_TABLE 1684 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT 1685 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT 1686 -#define ER_SPATIAL_MUST_HAVE_GEOM_COL 1687 -#define ER_TOO_LONG_INDEX_COMMENT 1688 -#define ER_LOCK_ABORTED 1689 -#define ER_DATA_OUT_OF_RANGE 1690 -#define ER_WRONG_SPVAR_TYPE_IN_LIMIT 1691 -#define ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1692 -#define ER_BINLOG_UNSAFE_MIXED_STATEMENT 1693 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN 1694 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN 1695 -#define ER_FAILED_READ_FROM_PAR_FILE 1696 -#define ER_VALUES_IS_NOT_INT_TYPE_ERROR 1697 -#define ER_ACCESS_DENIED_NO_PASSWORD_ERROR 1698 -#define ER_SET_PASSWORD_AUTH_PLUGIN 1699 -#define ER_GRANT_PLUGIN_USER_EXISTS 1700 -#define ER_TRUNCATE_ILLEGAL_FK 1701 -#define ER_PLUGIN_IS_PERMANENT 1702 -#define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN 1703 -#define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX 1704 -#define ER_STMT_CACHE_FULL 1705 -#define ER_MULTI_UPDATE_KEY_CONFLICT 1706 -#define ER_TABLE_NEEDS_REBUILD 1707 -#define WARN_OPTION_BELOW_LIMIT 1708 -#define ER_INDEX_COLUMN_TOO_LONG 1709 -#define ER_ERROR_IN_TRIGGER_BODY 1710 -#define ER_ERROR_IN_UNKNOWN_TRIGGER_BODY 1711 -#define ER_INDEX_CORRUPT 1712 -#define ER_UNDO_RECORD_TOO_BIG 1713 -#define ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT 1714 -#define ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE 1715 -#define ER_BINLOG_UNSAFE_REPLACE_SELECT 1716 -#define ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT 1717 -#define ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT 1718 -#define ER_BINLOG_UNSAFE_UPDATE_IGNORE 1719 -#define ER_UNUSED_15 1720 -#define ER_UNUSED_16 1721 -#define ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT 1722 -#define ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC 1723 -#define ER_BINLOG_UNSAFE_INSERT_TWO_KEYS 1724 -#define ER_TABLE_IN_FK_CHECK 1725 -#define ER_UNUSED_1 1726 -#define ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST 1727 -#define ER_CANNOT_LOAD_FROM_TABLE_V2 1728 -#define ER_MASTER_DELAY_VALUE_OUT_OF_RANGE 1729 -#define ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT 1730 -#define ER_PARTITION_EXCHANGE_DIFFERENT_OPTION 1731 -#define ER_PARTITION_EXCHANGE_PART_TABLE 1732 -#define ER_PARTITION_EXCHANGE_TEMP_TABLE 1733 -#define ER_PARTITION_INSTEAD_OF_SUBPARTITION 1734 -#define ER_UNKNOWN_PARTITION 1735 -#define ER_TABLES_DIFFERENT_METADATA 1736 -#define ER_ROW_DOES_NOT_MATCH_PARTITION 1737 -#define ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX 1738 -#define ER_WARN_INDEX_NOT_APPLICABLE 1739 -#define ER_PARTITION_EXCHANGE_FOREIGN_KEY 1740 -#define ER_NO_SUCH_KEY_VALUE 1741 -#define ER_VALUE_TOO_LONG 1742 -#define ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE 1743 -#define ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE 1744 -#define ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX 1745 -#define ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT 1746 -#define ER_PARTITION_CLAUSE_ON_NONPARTITIONED 1747 -#define ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET 1748 -#define ER_UNUSED_5 1749 -#define ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE 1750 -#define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE 1751 -#define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE 1752 -#define ER_MTS_FEATURE_IS_NOT_SUPPORTED 1753 -#define ER_MTS_UPDATED_DBS_GREATER_MAX 1754 -#define ER_MTS_CANT_PARALLEL 1755 -#define ER_MTS_INCONSISTENT_DATA 1756 -#define ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING 1757 -#define ER_DA_INVALID_CONDITION_NUMBER 1758 -#define ER_INSECURE_PLAIN_TEXT 1759 -#define ER_INSECURE_CHANGE_MASTER 1760 -#define ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO 1761 -#define ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO 1762 -#define ER_SQLTHREAD_WITH_SECURE_SLAVE 1763 -#define ER_TABLE_HAS_NO_FT 1764 -#define ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER 1765 -#define ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION 1766 -#define ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST 1767 -#define ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL 1768 -#define ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION 1769 -#define ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL 1770 -#define ER_SKIPPING_LOGGED_TRANSACTION 1771 -#define ER_MALFORMED_GTID_SET_SPECIFICATION 1772 -#define ER_MALFORMED_GTID_SET_ENCODING 1773 -#define ER_MALFORMED_GTID_SPECIFICATION 1774 -#define ER_GNO_EXHAUSTED 1775 -#define ER_BAD_SLAVE_AUTO_POSITION 1776 -#define ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON 1777 -#define ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET 1778 -#define ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON 1779 -#define ER_GTID_MODE_REQUIRES_BINLOG 1780 -#define ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF 1781 -#define ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON 1782 -#define ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF 1783 -#define ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF 1784 -#define ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE 1785 -#define ER_GTID_UNSAFE_CREATE_SELECT 1786 -#define ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION 1787 -#define ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME 1788 -#define ER_MASTER_HAS_PURGED_REQUIRED_GTIDS 1789 -#define ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID 1790 -#define ER_UNKNOWN_EXPLAIN_FORMAT 1791 -#define ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION 1792 -#define ER_TOO_LONG_TABLE_PARTITION_COMMENT 1793 -#define ER_SLAVE_CONFIGURATION 1794 -#define ER_INNODB_FT_LIMIT 1795 -#define ER_INNODB_NO_FT_TEMP_TABLE 1796 -#define ER_INNODB_FT_WRONG_DOCID_COLUMN 1797 -#define ER_INNODB_FT_WRONG_DOCID_INDEX 1798 -#define ER_INNODB_ONLINE_LOG_TOO_BIG 1799 -#define ER_UNKNOWN_ALTER_ALGORITHM 1800 -#define ER_UNKNOWN_ALTER_LOCK 1801 -#define ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS 1802 -#define ER_MTS_RECOVERY_FAILURE 1803 -#define ER_MTS_RESET_WORKERS 1804 -#define ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2 1805 -#define ER_SLAVE_SILENT_RETRY_TRANSACTION 1806 -#define ER_UNUSED_22 1807 -#define ER_TABLE_SCHEMA_MISMATCH 1808 -#define ER_TABLE_IN_SYSTEM_TABLESPACE 1809 -#define ER_IO_READ_ERROR 1810 -#define ER_IO_WRITE_ERROR 1811 -#define ER_TABLESPACE_MISSING 1812 -#define ER_TABLESPACE_EXISTS 1813 -#define ER_TABLESPACE_DISCARDED 1814 -#define ER_INTERNAL_ERROR 1815 -#define ER_INNODB_IMPORT_ERROR 1816 -#define ER_INNODB_INDEX_CORRUPT 1817 -#define ER_INVALID_YEAR_COLUMN_LENGTH 1818 -#define ER_NOT_VALID_PASSWORD 1819 -#define ER_MUST_CHANGE_PASSWORD 1820 -#define ER_FK_NO_INDEX_CHILD 1821 -#define ER_FK_NO_INDEX_PARENT 1822 -#define ER_FK_FAIL_ADD_SYSTEM 1823 -#define ER_FK_CANNOT_OPEN_PARENT 1824 -#define ER_FK_INCORRECT_OPTION 1825 -#define ER_DUP_CONSTRAINT_NAME 1826 -#define ER_PASSWORD_FORMAT 1827 -#define ER_FK_COLUMN_CANNOT_DROP 1828 -#define ER_FK_COLUMN_CANNOT_DROP_CHILD 1829 -#define ER_FK_COLUMN_NOT_NULL 1830 -#define ER_DUP_INDEX 1831 -#define ER_FK_COLUMN_CANNOT_CHANGE 1832 -#define ER_FK_COLUMN_CANNOT_CHANGE_CHILD 1833 -#define ER_FK_CANNOT_DELETE_PARENT 1834 -#define ER_MALFORMED_PACKET 1835 -#define ER_READ_ONLY_MODE 1836 -#define ER_GTID_NEXT_TYPE_UNDEFINED_GROUP 1837 -#define ER_VARIABLE_NOT_SETTABLE_IN_SP 1838 -#define ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF 1839 -#define ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY 1840 -#define ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY 1841 -#define ER_GTID_PURGED_WAS_CHANGED 1842 -#define ER_GTID_EXECUTED_WAS_CHANGED 1843 -#define ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES 1844 -#define ER_ALTER_OPERATION_NOT_SUPPORTED 1845 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON 1846 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY 1847 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION 1848 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME 1849 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE 1850 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK 1851 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE 1852 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK 1853 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC 1854 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS 1855 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS 1856 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS 1857 -#define ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE 1858 -#define ER_DUP_UNKNOWN_IN_INDEX 1859 -#define ER_IDENT_CAUSES_TOO_LONG_PATH 1860 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL 1861 -#define ER_MUST_CHANGE_PASSWORD_LOGIN 1862 -#define ER_ROW_IN_WRONG_PARTITION 1863 -#define ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX 1864 -#define ER_INNODB_NO_FT_USES_PARSER 1865 -#define ER_BINLOG_LOGICAL_CORRUPTION 1866 -#define ER_WARN_PURGE_LOG_IN_USE 1867 -#define ER_WARN_PURGE_LOG_IS_ACTIVE 1868 -#define ER_AUTO_INCREMENT_CONFLICT 1869 -#define WARN_ON_BLOCKHOLE_IN_RBR 1870 -#define ER_SLAVE_MI_INIT_REPOSITORY 1871 -#define ER_SLAVE_RLI_INIT_REPOSITORY 1872 -#define ER_ACCESS_DENIED_CHANGE_USER_ERROR 1873 -#define ER_INNODB_READ_ONLY 1874 -#define ER_STOP_SLAVE_SQL_THREAD_TIMEOUT 1875 -#define ER_STOP_SLAVE_IO_THREAD_TIMEOUT 1876 -#define ER_TABLE_CORRUPT 1877 -#define ER_TEMP_FILE_WRITE_FAILURE 1878 -#define ER_INNODB_FT_AUX_NOT_HEX_ID 1879 -#define ER_LAST_MYSQL_ERROR_MESSAGE 1880 -#define ER_ERROR_LAST_SECTION_1 1880 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_2 1900 -#define ER_UNUSED_18 1900 -#define ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED 1901 -#define ER_UNUSED_19 1902 -#define ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN 1903 -#define ER_KEY_BASED_ON_GENERATED_VIRTUAL_COLUMN 1904 -#define ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN 1905 -#define ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN 1906 -#define ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN 1907 -#define ER_UNUSED_20 1908 -#define ER_UNUSED_21 1909 -#define ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS 1910 -#define ER_UNKNOWN_OPTION 1911 -#define ER_BAD_OPTION_VALUE 1912 -#define ER_UNUSED_6 1913 -#define ER_UNUSED_7 1914 -#define ER_UNUSED_8 1915 -#define ER_DATA_OVERFLOW 1916 -#define ER_DATA_TRUNCATED 1917 -#define ER_BAD_DATA 1918 -#define ER_DYN_COL_WRONG_FORMAT 1919 -#define ER_DYN_COL_IMPLEMENTATION_LIMIT 1920 -#define ER_DYN_COL_DATA 1921 -#define ER_DYN_COL_WRONG_CHARSET 1922 -#define ER_ILLEGAL_SUBQUERY_OPTIMIZER_SWITCHES 1923 -#define ER_QUERY_CACHE_IS_DISABLED 1924 -#define ER_QUERY_CACHE_IS_GLOBALY_DISABLED 1925 -#define ER_VIEW_ORDERBY_IGNORED 1926 -#define ER_CONNECTION_KILLED 1927 -#define ER_UNUSED_12 1928 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SKIP_REPLICATION 1929 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_SKIP_REPLICATION 1930 -#define ER_QUERY_EXCEEDED_ROWS_EXAMINED_LIMIT 1931 -#define ER_NO_SUCH_TABLE_IN_ENGINE 1932 -#define ER_TARGET_NOT_EXPLAINABLE 1933 -#define ER_CONNECTION_ALREADY_EXISTS 1934 -#define ER_MASTER_LOG_PREFIX 1935 -#define ER_CANT_START_STOP_SLAVE 1936 -#define ER_SLAVE_STARTED 1937 -#define ER_SLAVE_STOPPED 1938 -#define ER_SQL_DISCOVER_ERROR 1939 -#define ER_FAILED_GTID_STATE_INIT 1940 -#define ER_INCORRECT_GTID_STATE 1941 -#define ER_CANNOT_UPDATE_GTID_STATE 1942 -#define ER_DUPLICATE_GTID_DOMAIN 1943 -#define ER_GTID_OPEN_TABLE_FAILED 1944 -#define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG 1945 -#define ER_CANNOT_LOAD_SLAVE_GTID_STATE 1946 -#define ER_MASTER_GTID_POS_CONFLICTS_WITH_BINLOG 1947 -#define ER_MASTER_GTID_POS_MISSING_DOMAIN 1948 -#define ER_UNTIL_REQUIRES_USING_GTID 1949 -#define ER_GTID_STRICT_OUT_OF_ORDER 1950 -#define ER_GTID_START_FROM_BINLOG_HOLE 1951 -#define ER_SLAVE_UNEXPECTED_MASTER_SWITCH 1952 -#define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1953 -#define ER_STORED_FUNCTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1954 -#define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG2 1955 -#define ER_BINLOG_MUST_BE_EMPTY 1956 -#define ER_NO_SUCH_QUERY 1957 -#define ER_BAD_BASE64_DATA 1958 -#define ER_INVALID_ROLE 1959 -#define ER_INVALID_CURRENT_USER 1960 -#define ER_CANNOT_GRANT_ROLE 1961 -#define ER_CANNOT_REVOKE_ROLE 1962 -#define ER_CHANGE_SLAVE_PARALLEL_THREADS_ACTIVE 1963 -#define ER_PRIOR_COMMIT_FAILED 1964 -#define ER_IT_IS_A_VIEW 1965 -#define ER_SLAVE_SKIP_NOT_IN_GTID 1966 -#define ER_TABLE_DEFINITION_TOO_BIG 1967 -#define ER_PLUGIN_INSTALLED 1968 -#define ER_STATEMENT_TIMEOUT 1969 -#define ER_SUBQUERIES_NOT_SUPPORTED 1970 -#define ER_SET_STATEMENT_NOT_SUPPORTED 1971 -#define ER_UNUSED_9 1972 -#define ER_USER_CREATE_EXISTS 1973 -#define ER_USER_DROP_EXISTS 1974 -#define ER_ROLE_CREATE_EXISTS 1975 -#define ER_ROLE_DROP_EXISTS 1976 -#define ER_CANNOT_CONVERT_CHARACTER 1977 -#define ER_INVALID_DEFAULT_VALUE_FOR_FIELD 1978 -#define ER_KILL_QUERY_DENIED_ERROR 1979 -#define ER_NO_EIS_FOR_FIELD 1980 -#define ER_WARN_AGGFUNC_DEPENDENCE 1981 -#define WARN_INNODB_PARTITION_OPTION_IGNORED 1982 -#define ER_ERROR_LAST_SECTION_2 1982 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_3 2000 -#define ER_ERROR_LAST_SECTION_3 2000 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_4 3000 -#define ER_FILE_CORRUPT 3000 -#define ER_ERROR_ON_MASTER 3001 -#define ER_INCONSISTENT_ERROR 3002 -#define ER_STORAGE_ENGINE_NOT_LOADED 3003 -#define ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER 3004 -#define ER_WARN_LEGACY_SYNTAX_CONVERTED 3005 -#define ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN 3006 -#define ER_CANNOT_DISCARD_TEMPORARY_TABLE 3007 -#define ER_FK_DEPTH_EXCEEDED 3008 -#define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2 3009 -#define ER_WARN_TRIGGER_DOESNT_HAVE_CREATED 3010 -#define ER_REFERENCED_TRG_DOES_NOT_EXIST_MYSQL 3011 -#define ER_EXPLAIN_NOT_SUPPORTED 3012 -#define ER_INVALID_FIELD_SIZE 3013 -#define ER_MISSING_HA_CREATE_OPTION 3014 -#define ER_ENGINE_OUT_OF_MEMORY 3015 -#define ER_PASSWORD_EXPIRE_ANONYMOUS_USER 3016 -#define ER_SLAVE_SQL_THREAD_MUST_STOP 3017 -#define ER_NO_FT_MATERIALIZED_SUBQUERY 3018 -#define ER_INNODB_UNDO_LOG_FULL 3019 -#define ER_INVALID_ARGUMENT_FOR_LOGARITHM 3020 -#define ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP 3021 -#define ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO 3022 -#define ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS 3023 -#define ER_QUERY_TIMEOUT 3024 -#define ER_NON_RO_SELECT_DISABLE_TIMER 3025 -#define ER_DUP_LIST_ENTRY 3026 -#define ER_SQL_MODE_NO_EFFECT 3027 -#define ER_AGGREGATE_ORDER_FOR_UNION 3028 -#define ER_AGGREGATE_ORDER_NON_AGG_QUERY 3029 -#define ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR 3030 -#define ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER 3031 -#define ER_SERVER_OFFLINE_MODE 3032 -#define ER_GIS_DIFFERENT_SRIDS 3033 -#define ER_GIS_UNSUPPORTED_ARGUMENT 3034 -#define ER_GIS_UNKNOWN_ERROR 3035 -#define ER_GIS_UNKNOWN_EXCEPTION 3036 -#define ER_GIS_INVALID_DATA 3037 -#define ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION 3038 -#define ER_BOOST_GEOMETRY_CENTROID_EXCEPTION 3039 -#define ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION 3040 -#define ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION 3041 -#define ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION 3042 -#define ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION 3043 -#define ER_STD_BAD_ALLOC_ERROR 3044 -#define ER_STD_DOMAIN_ERROR 3045 -#define ER_STD_LENGTH_ERROR 3046 -#define ER_STD_INVALID_ARGUMENT 3047 -#define ER_STD_OUT_OF_RANGE_ERROR 3048 -#define ER_STD_OVERFLOW_ERROR 3049 -#define ER_STD_RANGE_ERROR 3050 -#define ER_STD_UNDERFLOW_ERROR 3051 -#define ER_STD_LOGIC_ERROR 3052 -#define ER_STD_RUNTIME_ERROR 3053 -#define ER_STD_UNKNOWN_EXCEPTION 3054 -#define ER_GIS_DATA_WRONG_ENDIANESS 3055 -#define ER_CHANGE_MASTER_PASSWORD_LENGTH 3056 -#define ER_USER_LOCK_WRONG_NAME 3057 -#define ER_USER_LOCK_DEADLOCK 3058 -#define ER_REPLACE_INACCESSIBLE_ROWS 3059 -#define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS 3060 -#define ER_ERROR_LAST_SECTION_4 3060 - -/* New section */ - -#define ER_ERROR_FIRST_SECTION_5 4000 -#define ER_COMMULTI_BADCONTEXT 4000 -#define ER_BAD_COMMAND_IN_MULTI 4001 -#define ER_WITH_COL_WRONG_LIST 4002 -#define ER_TOO_MANY_DEFINITIONS_IN_WITH_CLAUSE 4003 -#define ER_DUP_QUERY_NAME 4004 -#define ER_RECURSIVE_WITHOUT_ANCHORS 4005 -#define ER_UNACCEPTABLE_MUTUAL_RECURSION 4006 -#define ER_REF_TO_RECURSIVE_WITH_TABLE_IN_DERIVED 4007 -#define ER_NOT_STANDARD_COMPLIANT_RECURSIVE 4008 -#define ER_WRONG_WINDOW_SPEC_NAME 4009 -#define ER_DUP_WINDOW_NAME 4010 -#define ER_PARTITION_LIST_IN_REFERENCING_WINDOW_SPEC 4011 -#define ER_ORDER_LIST_IN_REFERENCING_WINDOW_SPEC 4012 -#define ER_WINDOW_FRAME_IN_REFERENCED_WINDOW_SPEC 4013 -#define ER_BAD_COMBINATION_OF_WINDOW_FRAME_BOUND_SPECS 4014 -#define ER_WRONG_PLACEMENT_OF_WINDOW_FUNCTION 4015 -#define ER_WINDOW_FUNCTION_IN_WINDOW_SPEC 4016 -#define ER_NOT_ALLOWED_WINDOW_FRAME 4017 -#define ER_NO_ORDER_LIST_IN_WINDOW_SPEC 4018 -#define ER_RANGE_FRAME_NEEDS_SIMPLE_ORDERBY 4019 -#define ER_WRONG_TYPE_FOR_ROWS_FRAME 4020 -#define ER_WRONG_TYPE_FOR_RANGE_FRAME 4021 -#define ER_FRAME_EXCLUSION_NOT_SUPPORTED 4022 -#define ER_WINDOW_FUNCTION_DONT_HAVE_FRAME 4023 -#define ER_INVALID_NTILE_ARGUMENT 4024 -#define ER_CONSTRAINT_FAILED 4025 -#define ER_EXPRESSION_IS_TOO_BIG 4026 -#define ER_ERROR_EVALUATING_EXPRESSION 4027 -#define ER_CALCULATING_DEFAULT_VALUE 4028 -#define ER_EXPRESSION_REFERS_TO_UNINIT_FIELD 4029 -#define ER_PARTITION_DEFAULT_ERROR 4030 -#define ER_REFERENCED_TRG_DOES_NOT_EXIST 4031 -#define ER_INVALID_DEFAULT_PARAM 4032 -#define ER_BINLOG_NON_SUPPORTED_BULK 4033 -#define ER_BINLOG_UNCOMPRESS_ERROR 4034 -#define ER_JSON_BAD_CHR 4035 -#define ER_JSON_NOT_JSON_CHR 4036 -#define ER_JSON_EOS 4037 -#define ER_JSON_SYNTAX 4038 -#define ER_JSON_ESCAPING 4039 -#define ER_JSON_DEPTH 4040 -#define ER_JSON_PATH_EOS 4041 -#define ER_JSON_PATH_SYNTAX 4042 -#define ER_JSON_PATH_DEPTH 4043 -#define ER_JSON_PATH_NO_WILDCARD 4044 -#define ER_JSON_PATH_ARRAY 4045 -#define ER_JSON_ONE_OR_ALL 4046 -#define ER_UNSUPPORT_COMPRESSED_TEMPORARY_TABLE 4047 -#define ER_GEOJSON_INCORRECT 4048 -#define ER_GEOJSON_TOO_FEW_POINTS 4049 -#define ER_GEOJSON_NOT_CLOSED 4050 -#define ER_JSON_PATH_EMPTY 4051 -#define ER_SLAVE_SAME_ID 4052 -#define ER_FLASHBACK_NOT_SUPPORTED 4053 -#define ER_KEYS_OUT_OF_ORDER 4054 -#define ER_OVERLAPPING_KEYS 4055 -#define ER_REQUIRE_ROW_BINLOG_FORMAT 4056 -#define ER_ISOLATION_MODE_NOT_SUPPORTED 4057 -#define ER_ON_DUPLICATE_DISABLED 4058 -#define ER_UPDATES_WITH_CONSISTENT_SNAPSHOT 4059 -#define ER_ROLLBACK_ONLY 4060 -#define ER_ROLLBACK_TO_SAVEPOINT 4061 -#define ER_ISOLATION_LEVEL_WITH_CONSISTENT_SNAPSHOT 4062 -#define ER_UNSUPPORTED_COLLATION 4063 -#define ER_METADATA_INCONSISTENCY 4064 -#define ER_CF_DIFFERENT 4065 -#define ER_RDB_TTL_DURATION_FORMAT 4066 -#define ER_RDB_STATUS_GENERAL 4067 -#define ER_RDB_STATUS_MSG 4068 -#define ER_RDB_TTL_UNSUPPORTED 4069 -#define ER_RDB_TTL_COL_FORMAT 4070 -#define ER_PER_INDEX_CF_DEPRECATED 4071 -#define ER_KEY_CREATE_DURING_ALTER 4072 -#define ER_SK_POPULATE_DURING_ALTER 4073 -#define ER_SUM_FUNC_WITH_WINDOW_FUNC_AS_ARG 4074 -#define ER_NET_OK_PACKET_TOO_LARGE 4075 -#define ER_GEOJSON_EMPTY_COORDINATES 4076 -#define ER_MYROCKS_CANT_NOPAD_COLLATION 4077 -#define ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION 4078 -#define ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION 4079 -#define ER_WRONG_PARAMCOUNT_TO_CURSOR 4080 -#define ER_UNKNOWN_STRUCTURED_VARIABLE 4081 -#define ER_ROW_VARIABLE_DOES_NOT_HAVE_FIELD 4082 -#define ER_END_IDENTIFIER_DOES_NOT_MATCH 4083 -#define ER_SEQUENCE_RUN_OUT 4084 -#define ER_SEQUENCE_INVALID_DATA 4085 -#define ER_SEQUENCE_INVALID_TABLE_STRUCTURE 4086 -#define ER_SEQUENCE_ACCESS_ERROR 4087 -#define ER_SEQUENCE_BINLOG_FORMAT 4088 -#define ER_NOT_SEQUENCE 4089 -#define ER_NOT_SEQUENCE2 4090 -#define ER_UNKNOWN_SEQUENCES 4091 -#define ER_UNKNOWN_VIEW 4092 -#define ER_WRONG_INSERT_INTO_SEQUENCE 4093 -#define ER_SP_STACK_TRACE 4094 -#define ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY 4095 -#define ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED 4096 -#define ER_COMPRESSED_COLUMN_USED_AS_KEY 4097 -#define ER_UNKNOWN_COMPRESSION_METHOD 4098 -#define ER_WRONG_NUMBER_OF_VALUES_IN_TVC 4099 -#define ER_FIELD_REFERENCE_IN_TVC 4100 -#define ER_WRONG_TYPE_FOR_PERCENTILE_FUNC 4101 -#define ER_ARGUMENT_NOT_CONSTANT 4102 -#define ER_ARGUMENT_OUT_OF_RANGE 4103 -#define ER_WRONG_TYPE_OF_ARGUMENT 4104 -#define ER_NOT_AGGREGATE_FUNCTION 4105 -#define ER_INVALID_AGGREGATE_FUNCTION 4106 -#define ER_INVALID_VALUE_TO_LIMIT 4107 -#define ER_INVISIBLE_NOT_NULL_WITHOUT_DEFAULT 4108 -#define ER_UPDATE_INFO_WITH_SYSTEM_VERSIONING 4109 -#define ER_VERS_FIELD_WRONG_TYPE 4110 -#define ER_VERS_ENGINE_UNSUPPORTED 4111 -#define ER_UNUSED_23 4112 -#define ER_PARTITION_WRONG_TYPE 4113 -#define WARN_VERS_PART_FULL 4114 -#define WARN_VERS_PARAMETERS 4115 -#define ER_VERS_DROP_PARTITION_INTERVAL 4116 -#define ER_UNUSED_25 4117 -#define WARN_VERS_PART_NON_HISTORICAL 4118 -#define ER_VERS_ALTER_NOT_ALLOWED 4119 -#define ER_VERS_ALTER_ENGINE_PROHIBITED 4120 -#define ER_VERS_RANGE_PROHIBITED 4121 -#define ER_CONFLICTING_FOR_SYSTEM_TIME 4122 -#define ER_VERS_TABLE_MUST_HAVE_COLUMNS 4123 -#define ER_VERS_NOT_VERSIONED 4124 -#define ER_MISSING 4125 -#define ER_VERS_PERIOD_COLUMNS 4126 -#define ER_PART_WRONG_VALUE 4127 -#define ER_VERS_WRONG_PARTS 4128 -#define ER_VERS_NO_TRX_ID 4129 -#define ER_VERS_ALTER_SYSTEM_FIELD 4130 -#define ER_DROP_VERSIONING_SYSTEM_TIME_PARTITION 4131 -#define ER_VERS_DB_NOT_SUPPORTED 4132 -#define ER_VERS_TRT_IS_DISABLED 4133 -#define ER_VERS_DUPLICATE_ROW_START_END 4134 -#define ER_VERS_ALREADY_VERSIONED 4135 -#define ER_UNUSED_24 4136 -#define ER_VERS_NOT_SUPPORTED 4137 -#define ER_VERS_TRX_PART_HISTORIC_ROW_NOT_SUPPORTED 4138 -#define ER_INDEX_FILE_FULL 4139 -#define ER_UPDATED_COLUMN_ONLY_ONCE 4140 -#define ER_EMPTY_ROW_IN_TVC 4141 -#define ER_VERS_QUERY_IN_PARTITION 4142 -#define ER_KEY_DOESNT_SUPPORT 4143 -#define ER_ALTER_OPERATION_TABLE_OPTIONS_NEED_REBUILD 4144 -#define ER_BACKUP_LOCK_IS_ACTIVE 4145 -#define ER_BACKUP_NOT_RUNNING 4146 -#define ER_BACKUP_WRONG_STAGE 4147 -#define ER_BACKUP_STAGE_FAILED 4148 -#define ER_BACKUP_UNKNOWN_STAGE 4149 -#define ER_USER_IS_BLOCKED 4150 -#define ER_ACCOUNT_HAS_BEEN_LOCKED 4151 -#define ER_PERIOD_TEMPORARY_NOT_ALLOWED 4152 -#define ER_PERIOD_TYPES_MISMATCH 4153 -#define ER_MORE_THAN_ONE_PERIOD 4154 -#define ER_PERIOD_FIELD_WRONG_ATTRIBUTES 4155 -#define ER_PERIOD_NOT_FOUND 4156 -#define ER_PERIOD_COLUMNS_UPDATED 4157 -#define ER_PERIOD_CONSTRAINT_DROP 4158 -#define ER_TOO_LONG_KEYPART 4159 -#define ER_TOO_LONG_DATABASE_COMMENT 4160 -#define ER_UNKNOWN_DATA_TYPE 4161 -#define ER_UNKNOWN_OPERATOR 4162 -#define ER_WARN_HISTORY_ROW_START_TIME 4163 -#define ER_PART_STARTS_BEYOND_INTERVAL 4164 -#define ER_GALERA_REPLICATION_NOT_SUPPORTED 4165 -#define ER_LOAD_INFILE_CAPABILITY_DISABLED 4166 -#define ER_NO_SECURE_TRANSPORTS_CONFIGURED 4167 -#define ER_SLAVE_IGNORED_SHARED_TABLE 4168 -#define ER_NO_AUTOINCREMENT_WITH_UNIQUE 4169 -#define ER_KEY_CONTAINS_PERIOD_FIELDS 4170 -#define ER_KEY_CANT_HAVE_WITHOUT_OVERLAPS 4171 -#define ER_NOT_ALLOWED_IN_THIS_CONTEXT 4172 -#define ER_DATA_WAS_COMMITED_UNDER_ROLLBACK 4173 -#define ER_ERROR_LAST 4173 -#endif /* ER_ERROR_FIRST */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/pack.h b/VCMP-LUA/modules/mariadb/include/mysql/server/pack.h deleted file mode 100644 index f991e72..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/pack.h +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright (c) 2016, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifdef __cplusplus -extern "C" { -#endif - -ulong net_field_length(uchar **packet); -my_ulonglong net_field_length_ll(uchar **packet); -my_ulonglong safe_net_field_length_ll(uchar **packet, size_t packet_len); -uchar *net_store_length(uchar *pkg, ulonglong length); -uchar *safe_net_store_length(uchar *pkg, size_t pkg_len, ulonglong length); -unsigned int net_length_size(ulonglong num); - -#ifdef __cplusplus -} -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/aria_backup.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/aria_backup.h deleted file mode 100644 index f399f6a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/aria_backup.h +++ /dev/null @@ -1,42 +0,0 @@ -/* Copyright (C) 2018,2020 MariaDB Corporation Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ - -/* Interfaces for doing backups of Aria tables */ - -C_MODE_START - -typedef struct st_aria_table_capabilities -{ - my_off_t header_size; - ulong bitmap_pages_covered; - uint block_size; - uint keypage_header; - enum data_file_type data_file_type; - my_bool checksum; - my_bool transactional; - my_bool encrypted; - /* This is true if the table can be copied without any locks */ - my_bool online_backup_safe; - /* s3 capabilities */ - ulong s3_block_size; - uint8 compression; -} ARIA_TABLE_CAPABILITIES; - -int aria_get_capabilities(File kfile, ARIA_TABLE_CAPABILITIES *cap); -int aria_read_index(File kfile, ARIA_TABLE_CAPABILITIES *cap, ulonglong block, - uchar *buffer); -int aria_read_data(File dfile, ARIA_TABLE_CAPABILITIES *cap, ulonglong block, - uchar *buffer, size_t *bytes_read); -C_MODE_END diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/assume_aligned.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/assume_aligned.h deleted file mode 100644 index e1b807c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/assume_aligned.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#pragma once - -#include -#include - -#ifdef _MSC_VER -template -static inline T my_assume_aligned(T ptr) -{ - assert(reinterpret_cast(ptr) % Alignment == 0); - __assume(reinterpret_cast(ptr) % Alignment == 0); - return ptr; -} -#else -template -static inline T my_assume_aligned(T ptr) -{ - assert(reinterpret_cast(ptr) % Alignment == 0); - return static_cast(__builtin_assume_aligned(ptr, Alignment)); -} -#endif - -template -inline void *memcpy_aligned(void *dest, const void *src, size_t n) -{ - static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); - - return std::memcpy(my_assume_aligned(dest), - my_assume_aligned(src), n); -} -template -inline void *memmove_aligned(void *dest, const void *src, size_t n) -{ - static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); - - return std::memmove(my_assume_aligned(dest), - my_assume_aligned(src), n); -} -template -inline int memcmp_aligned(const void *s1, const void *s2, size_t n) -{ - static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); - - return std::memcmp(my_assume_aligned(s1), - my_assume_aligned(s2), n); -} -template -inline void *memset_aligned(void *s, int c, size_t n) -{ - static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); - - return std::memset(my_assume_aligned(s), c, n); -} diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/gcc_builtins.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/gcc_builtins.h deleted file mode 100644 index 5b2b2c9..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/gcc_builtins.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef ATOMIC_GCC_BUILTINS_INCLUDED -#define ATOMIC_GCC_BUILTINS_INCLUDED - -/* Copyright (c) 2017 MariaDB Foundation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#define MY_MEMORY_ORDER_RELAXED __ATOMIC_RELAXED -#define MY_MEMORY_ORDER_CONSUME __ATOMIC_CONSUME -#define MY_MEMORY_ORDER_ACQUIRE __ATOMIC_ACQUIRE -#define MY_MEMORY_ORDER_RELEASE __ATOMIC_RELEASE -#define MY_MEMORY_ORDER_ACQ_REL __ATOMIC_ACQ_REL -#define MY_MEMORY_ORDER_SEQ_CST __ATOMIC_SEQ_CST - -#define my_atomic_store32_explicit(P, D, O) __atomic_store_n((P), (D), (O)) -#define my_atomic_store64_explicit(P, D, O) __atomic_store_n((P), (D), (O)) -#define my_atomic_storeptr_explicit(P, D, O) __atomic_store_n((P), (D), (O)) - -#define my_atomic_load32_explicit(P, O) __atomic_load_n((P), (O)) -#define my_atomic_load64_explicit(P, O) __atomic_load_n((P), (O)) -#define my_atomic_loadptr_explicit(P, O) __atomic_load_n((P), (O)) - -#define my_atomic_fas32_explicit(P, D, O) __atomic_exchange_n((P), (D), (O)) -#define my_atomic_fas64_explicit(P, D, O) __atomic_exchange_n((P), (D), (O)) -#define my_atomic_fasptr_explicit(P, D, O) __atomic_exchange_n((P), (D), (O)) - -#define my_atomic_add32_explicit(P, A, O) __atomic_fetch_add((P), (A), (O)) -#define my_atomic_add64_explicit(P, A, O) __atomic_fetch_add((P), (A), (O)) - -#define my_atomic_cas32_weak_explicit(P, E, D, S, F) \ - __atomic_compare_exchange_n((P), (E), (D), 1, (S), (F)) -#define my_atomic_cas64_weak_explicit(P, E, D, S, F) \ - __atomic_compare_exchange_n((P), (E), (D), 1, (S), (F)) -#define my_atomic_casptr_weak_explicit(P, E, D, S, F) \ - __atomic_compare_exchange_n((P), (E), (D), 1, (S), (F)) - -#define my_atomic_cas32_strong_explicit(P, E, D, S, F) \ - __atomic_compare_exchange_n((P), (E), (D), 0, (S), (F)) -#define my_atomic_cas64_strong_explicit(P, E, D, S, F) \ - __atomic_compare_exchange_n((P), (E), (D), 0, (S), (F)) -#define my_atomic_casptr_strong_explicit(P, E, D, S, F) \ - __atomic_compare_exchange_n((P), (E), (D), 0, (S), (F)) - -#define my_atomic_store32(P, D) __atomic_store_n((P), (D), __ATOMIC_SEQ_CST) -#define my_atomic_store64(P, D) __atomic_store_n((P), (D), __ATOMIC_SEQ_CST) -#define my_atomic_storeptr(P, D) __atomic_store_n((P), (D), __ATOMIC_SEQ_CST) - -#define my_atomic_load32(P) __atomic_load_n((P), __ATOMIC_SEQ_CST) -#define my_atomic_load64(P) __atomic_load_n((P), __ATOMIC_SEQ_CST) -#define my_atomic_loadptr(P) __atomic_load_n((P), __ATOMIC_SEQ_CST) - -#define my_atomic_fas32(P, D) __atomic_exchange_n((P), (D), __ATOMIC_SEQ_CST) -#define my_atomic_fas64(P, D) __atomic_exchange_n((P), (D), __ATOMIC_SEQ_CST) -#define my_atomic_fasptr(P, D) __atomic_exchange_n((P), (D), __ATOMIC_SEQ_CST) - -#define my_atomic_add32(P, A) __atomic_fetch_add((P), (A), __ATOMIC_SEQ_CST) -#define my_atomic_add64(P, A) __atomic_fetch_add((P), (A), __ATOMIC_SEQ_CST) - -#define my_atomic_cas32(P, E, D) \ - __atomic_compare_exchange_n((P), (E), (D), 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) -#define my_atomic_cas64(P, E, D) \ - __atomic_compare_exchange_n((P), (E), (D), 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) -#define my_atomic_casptr(P, E, D) \ - __atomic_compare_exchange_n((P), (E), (D), 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) - -#endif /* ATOMIC_GCC_BUILTINS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/generic-msvc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/generic-msvc.h deleted file mode 100644 index ff2a543..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/generic-msvc.h +++ /dev/null @@ -1,140 +0,0 @@ -#ifndef ATOMIC_MSC_INCLUDED -#define ATOMIC_MSC_INCLUDED - -/* Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include - -static inline int my_atomic_cas32(int32 volatile *a, int32 *cmp, int32 set) -{ - int32 initial_cmp= *cmp; - int32 initial_a= InterlockedCompareExchange((volatile LONG*)a, - set, initial_cmp); - int ret= (initial_a == initial_cmp); - if (!ret) - *cmp= initial_a; - return ret; -} - -static inline int my_atomic_cas64(int64 volatile *a, int64 *cmp, int64 set) -{ - int64 initial_cmp= *cmp; - int64 initial_a= InterlockedCompareExchange64((volatile LONGLONG*)a, - (LONGLONG)set, - (LONGLONG)initial_cmp); - int ret= (initial_a == initial_cmp); - if (!ret) - *cmp= initial_a; - return ret; -} - -static inline int my_atomic_casptr(void * volatile *a, void **cmp, void *set) -{ - void *initial_cmp= *cmp; - void *initial_a= InterlockedCompareExchangePointer(a, set, initial_cmp); - int ret= (initial_a == initial_cmp); - if (!ret) - *cmp= initial_a; - return ret; -} - -static inline int32 my_atomic_add32(int32 volatile *a, int32 v) -{ - return (int32)InterlockedExchangeAdd((volatile LONG*)a, v); -} - -static inline int64 my_atomic_add64(int64 volatile *a, int64 v) -{ - return (int64)InterlockedExchangeAdd64((volatile LONGLONG*)a, (LONGLONG)v); -} - - -/* - According to MSDN: - - Simple reads and writes to properly-aligned 32-bit variables are atomic - operations. - ... - Simple reads and writes to properly aligned 64-bit variables are atomic on - 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be - atomic on 32-bit Windows. - - https://msdn.microsoft.com/en-us/library/windows/desktop/ms684122(v=vs.85).aspx -*/ - -static inline int32 my_atomic_load32(int32 volatile *a) -{ - int32 value= *a; - MemoryBarrier(); - return value; -} - -static inline int64 my_atomic_load64(int64 volatile *a) -{ -#ifdef _M_X64 - int64 value= *a; - MemoryBarrier(); - return value; -#else - return (int64) InterlockedCompareExchange64((volatile LONGLONG *) a, 0, 0); -#endif -} - -static inline void* my_atomic_loadptr(void * volatile *a) -{ - void *value= *a; - MemoryBarrier(); - return value; -} - -static inline int32 my_atomic_fas32(int32 volatile *a, int32 v) -{ - return (int32)InterlockedExchange((volatile LONG*)a, v); -} - -static inline int64 my_atomic_fas64(int64 volatile *a, int64 v) -{ - return (int64)InterlockedExchange64((volatile LONGLONG*)a, v); -} - -static inline void * my_atomic_fasptr(void * volatile *a, void * v) -{ - return InterlockedExchangePointer(a, v); -} - -static inline void my_atomic_store32(int32 volatile *a, int32 v) -{ - MemoryBarrier(); - *a= v; -} - -static inline void my_atomic_store64(int64 volatile *a, int64 v) -{ -#ifdef _M_X64 - MemoryBarrier(); - *a= v; -#else - (void) InterlockedExchange64((volatile LONGLONG *) a, v); -#endif -} - -static inline void my_atomic_storeptr(void * volatile *a, void *v) -{ - MemoryBarrier(); - *a= v; -} - -#endif /* ATOMIC_MSC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/solaris.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/solaris.h deleted file mode 100644 index b48ab46..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/atomic/solaris.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef ATOMIC_SOLARIS_INCLUDED -#define ATOMIC_SOLARIS_INCLUDED - -/* Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include - -#if defined(__GNUC__) -#define atomic_typeof(T,V) __typeof__(V) -#else -#define atomic_typeof(T,V) T -#endif - -static inline int my_atomic_cas32(int32 volatile *a, int32 *cmp, int32 set) -{ - int ret; - atomic_typeof(uint32_t, *cmp) sav; - sav= atomic_cas_32((volatile uint32_t *)a, (uint32_t)*cmp, (uint32_t)set); - ret= (sav == *cmp); - if (!ret) - *cmp= sav; - return ret; -} - -static inline int my_atomic_cas64(int64 volatile *a, int64 *cmp, int64 set) -{ - int ret; - atomic_typeof(uint64_t, *cmp) sav; - sav= atomic_cas_64((volatile uint64_t *)a, (uint64_t)*cmp, (uint64_t)set); - ret= (sav == *cmp); - if (!ret) - *cmp= sav; - return ret; -} - -static inline int my_atomic_casptr(void * volatile *a, void **cmp, void *set) -{ - int ret; - atomic_typeof(void *, *cmp) sav; - sav= atomic_cas_ptr((volatile void **)a, (void *)*cmp, (void *)set); - ret= (sav == *cmp); - if (!ret) - *cmp= sav; - return ret; -} - -static inline int32 my_atomic_add32(int32 volatile *a, int32 v) -{ - int32 nv= atomic_add_32_nv((volatile uint32_t *)a, v); - return nv - v; -} - -static inline int64 my_atomic_add64(int64 volatile *a, int64 v) -{ - int64 nv= atomic_add_64_nv((volatile uint64_t *)a, v); - return nv - v; -} - -static inline int32 my_atomic_fas32(int32 volatile *a, int32 v) -{ - return atomic_swap_32((volatile uint32_t *)a, (uint32_t)v); -} - -static inline int64 my_atomic_fas64(int64 volatile *a, int64 v) -{ - return atomic_swap_64((volatile uint64_t *)a, (uint64_t)v); -} - -static inline void * my_atomic_fasptr(void * volatile *a, void * v) -{ - return atomic_swap_ptr(a, v); -} - -static inline int32 my_atomic_load32(int32 volatile *a) -{ - return atomic_or_32_nv((volatile uint32_t *)a, 0); -} - -static inline int64 my_atomic_load64(int64 volatile *a) -{ - return atomic_or_64_nv((volatile uint64_t *)a, 0); -} - -static inline void* my_atomic_loadptr(void * volatile *a) -{ - return atomic_add_ptr_nv(a, 0); -} - -static inline void my_atomic_store32(int32 volatile *a, int32 v) -{ - (void) atomic_swap_32((volatile uint32_t *)a, (uint32_t)v); -} - -static inline void my_atomic_store64(int64 volatile *a, int64 v) -{ - (void) atomic_swap_64((volatile uint64_t *)a, (uint64_t)v); -} - -static inline void my_atomic_storeptr(void * volatile *a, void *v) -{ - (void) atomic_swap_ptr((volatile void **)a, (void *)v); -} - -#endif /* ATOMIC_SOLARIS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/authors.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/authors.h deleted file mode 100644 index cf0a4c5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/authors.h +++ /dev/null @@ -1,195 +0,0 @@ -#ifndef AUTHORS_INCLUDED -#define AUTHORS_INCLUDED - -/* Copyright (c) 2005, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Structure of the name list */ - -struct show_table_authors_st { - const char *name; - const char *location; - const char *comment; -}; - -/* - Output from "SHOW AUTHORS" - - If you can update it, you get to be in it :) - - Don't be offended if your name is not in here, just add it! - - Active people in the MariaDB are listed first, active people in MySQL - then, not active last. - - Names should be encoded using UTF-8. - - See also https://mariadb.com/kb/en/log-of-mariadb-contributions/ -*/ - -struct show_table_authors_st show_table_authors[]= { - /* Active people on MariaDB */ - { "Michael (Monty) Widenius", "Tusby, Finland", - "Lead developer and main author" }, - { "Sergei Golubchik", "Kerpen, Germany", - "Architect, Full-text search, precision math, plugin framework, merges etc" }, - { "Igor Babaev", "Bellevue, USA", "Optimizer, keycache, core work"}, - { "Sergey Petrunia", "St. Petersburg, Russia", "Optimizer"}, - { "Oleksandr Byelkin", "Lugansk, Ukraine", - "Query Cache (4.0), Subqueries (4.1), Views (5.0)" }, - { "Timour Katchaounov", "Sofia , Bulgaria", "Optimizer"}, - { "Kristian Nielsen", "Copenhagen, Denmark", - "Replication, Async client prototocol, General buildbot stuff" }, - { "Alexander (Bar) Barkov", "Izhevsk, Russia", - "Unicode and character sets" }, - { "Alexey Botchkov (Holyfoot)", "Izhevsk, Russia", - "GIS extensions, embedded server, precision math"}, - { "Daniel Bartholomew", "Raleigh, USA", "MariaDB documentation, Buildbot, releases"}, - { "Colin Charles", "Selangor, Malesia", "MariaDB documentation, talks at a LOT of conferences"}, - { "Sergey Vojtovich", "Izhevsk, Russia", - "initial implementation of plugin architecture, maintained native storage engines (MyISAM, MEMORY, ARCHIVE, etc), rewrite of table cache"}, - { "Vladislav Vaintroub", "Mannheim, Germany", "MariaDB Java connector, new thread pool, Windows optimizations"}, - { "Elena Stepanova", "Sankt Petersburg, Russia", "QA, test cases"}, - { "Georg Richter", "Heidelberg, Germany", "New LGPL C connector, PHP connector"}, - { "Jan Lindström", "Ylämylly, Finland", "Working on InnoDB"}, - { "Lixun Peng", "Hangzhou, China", "Multi Source replication" }, - { "Olivier Bertrand", "Paris, France", "CONNECT storage engine"}, - { "Kentoku Shiba", "Tokyo, Japan", "Spider storage engine, metadata_lock_info Information schema"}, - { "Percona", "CA, USA", "XtraDB, microslow patches, extensions to slow log"}, - { "Vicentiu Ciorbaru", "Bucharest, Romania", "Roles"}, - { "Sudheera Palihakkara", "", "PCRE Regular Expressions" }, - { "Pavel Ivanov", "USA", "Some patches and bug fixes"}, - { "Konstantin Osipov", "Moscow, Russia", - "Prepared statements (4.1), Cursors (5.0), GET_LOCK (10.0)" }, - { "Ian Gilfillan", "South Africa", "MariaDB documentation"}, - { "Federico Razolli", "Italy", "MariaDB documentation Italian translation"}, - { "Vinchen", "Shenzhen, China", "Instant ADD Column for InnoDB, Spider engine optimization, from Tencent Game DBA Team" }, - { "Willhan", "Shenzhen, China", "Big Column Compression, Spider engine optimization, from Tencent Game DBA Team" }, - { "Anders Karlsson", "Ystad, Sweden", "Replication patch for enforcing triggers on slave"}, - { "Otto Kekäläinen", "Tampere, Finland", "Debian packaging, install/upgrade engineering, QA pipelines, documentation"}, - { "Daniel Black", "Canberra, Australia", "Modernising large page support, systemd, and bug fixes"}, - - /* People working on MySQL code base (not NDB) */ - { "Guilhem Bichot", "Bordeaux, France", "Replication (since 4.0)" }, - { "Andrei Elkin", "Espoo, Finland", "Replication" }, - { "Dmitri Lenev", "Moscow, Russia", - "Time zones support (4.1), Triggers (5.0)" }, - { "Marc Alff", "Denver, CO, USA", "Signal, Resignal, Performance schema" }, - { "Mikael Ronström", "Stockholm, Sweden", - "NDB Cluster, Partitioning, online alter table" }, - { "Ingo Strüwing", "Berlin, Germany", - "Bug fixing in MyISAM, Merge tables etc" }, - {"Marko Mäkelä", "Helsinki, Finland", "InnoDB core developer"}, - - /* People not active anymore */ - { "David Axmark", "London, England", - "MySQL founder; Small stuff long time ago, Monty ripped it out!" }, - { "Brian (Krow) Aker", "Seattle, WA, USA", - "Architecture, archive, blackhole, federated, bunch of little stuff :)" }, - { "Venu Anuganti", "", "Client/server protocol (4.1)" }, - { "Omer BarNir", "Sunnyvale, CA, USA", - "Testing (sometimes) and general QA stuff" }, - { "John Birrell", "", "Emulation of pthread_mutex() for OS/2" }, - { "Andreas F. Bobak", "", "AGGREGATE extension to user-defined functions" }, - { "Reggie Burnett", "Nashville, TN, USA", "Windows development, Connectors" }, - { "Kent Boortz", "Orebro, Sweden", "Test platform, and general build stuff" }, - { "Tim Bunce", "", "mysqlhotcopy" }, - { "Yves Carlier", "", "mysqlaccess" }, - { "Joshua Chamas", "Cupertino, CA, USA", - "Concurrent insert, extended date syntax" }, - { "Petr Chardin", "Moscow, Russia", - "Instance Manager (5.0), Server log tables (5.1)" }, - { "Wei-Jou Chen", "", "Chinese (Big5) character set" }, - { "Albert Chin-A-Young", "", - "Tru64 port, large file support, better TCP wrappers support" }, - { "Jorge del Conde", "Mexico City, Mexico", "Windows development" }, - { "Antony T. Curtis", "Norwalk, CA, USA", - "Parser, port to OS/2, storage engines and some random stuff" }, - { "Yuri Dario", "", "OS/2 port" }, - { "Patrick Galbraith", "Sharon, NH", "Federated Engine, mysqlslap" }, - { "Lenz Grimmer", "Hamburg, Germany", - "Production (build and release) engineering" }, - { "Nikolay Grishakin", "Austin, TX, USA", "Testing - Server" }, - { "Wei He", "", "Chinese (GBK) character set" }, - { "Eric Herman", "Amsterdam, Netherlands", "Bug fixing - federated" }, - { "Andrey Hristov", "Walldorf, Germany", "Event scheduler (5.1)" }, - { "Alexander (Alexi) Ivanov", "St. Petersburg, Russia", "Replication" }, - { "Mattias Jonsson", "Uppsala, Sweden", "Partitioning" }, - { "Alexander (Salle) Keremidarski", "Sofia, Bulgaria", - "Bug fixing" }, - { "Mats Kindahl", "Storvreta, Sweden", "Replication" }, - { "Serge Kozlov", "Velikie Luki, Russia", "Testing - Cluster" }, - { "Hakan Küçükyılmaz", "Walldorf, Germany", "Testing - Server" }, - { "Matthias Leich", "Berlin, Germany", "Testing - Server" }, - { "Arjen Lentz", "Brisbane, Australia", - "Documentation (2001-2004), Dutch error messages, LOG2()" }, - { "Marc Liyanage", "", "Created Mac OS X packages" }, - { "Kelly Long", "Denver, CO, USA", "Pool Of Threads" }, - { "Zarko Mocnik", "", "Sorting for Slovenian language" }, - { "Per-Erik Martin", "Uppsala, Sweden", "Stored Procedures (5.0)" }, - { "Alexis Mikhailov", "", "User-defined functions" }, - { "Sinisa Milivojevic", "Larnaca, Cyprus", - "UNION (4.0), Subqueries in FROM clause (4.1), many other features" }, - { "Jonathan (Jeb) Miller", "Kyle, TX, USA", - "Testing - Cluster, Replication" }, - { "Elliot Murphy", "Cocoa, FL, USA", "Replication and backup" }, - { "Pekka Nouisiainen", "Stockholm, Sweden", - "NDB Cluster: BLOB support, character set support, ordered indexes" }, - { "Alexander Nozdrin", "Moscow, Russia", - "Bug fixing (Stored Procedures, 5.0)" }, - { "Per Eric Olsson", "", "Testing of dynamic record format" }, - { "Jonas Oreland", "Stockholm, Sweden", - "NDB Cluster, Online Backup, lots of other things" }, - { "Alexander (Sasha) Pachev", "Provo, UT, USA", - "Statement-based replication, SHOW CREATE TABLE, mysql-bench" }, - { "Irena Pancirov", "", "Port to Windows with Borland compiler" }, - { "Jan Pazdziora", "", "Czech sorting order" }, - { "Benjamin Pflugmann", "", - "Extended MERGE storage engine to handle INSERT" }, - { "Igor Romanenko", "", - "mysqldump" }, - { "Tõnu Samuel", "Estonia", - "VIO interface, other miscellaneous features" }, - { "Carsten Segieth (Pino)", "Fredersdorf, Germany", "Testing - Server"}, - { "Martin Sköld", "Stockholm, Sweden", - "NDB Cluster: Unique indexes, integration into MySQL" }, - { "Timothy Smith", "Auckland, New Zealand", - "Dynamic character sets, parts of the build system, libmysqld"}, - { "Miguel Solorzano", "Florianopolis, Santa Catarina, Brazil", - "Windows development, Windows NT service"}, - { "Punita Srivastava", "Austin, TX, USA", "Testing - Merlin"}, - { "Alexey Stroganov (Ranger)", "Lugansk, Ukraine", "Testing - Benchmarks"}, - { "Magnus Svensson", "Öregrund, Sweden", - "NDB Cluster: Integration into MySQL, test framework" }, - { "Zeev Suraski", "", "FROM_UNIXTIME(), ENCRYPT()" }, - { "TAMITO", "", - "The _MB character set macros and UJIS and SJIS character sets" }, - { "Jani Tolonen", "Helsinki, Finland", - "mysqlimport, extensions to command-line clients, PROCEDURE ANALYSE()" }, - { "Lars Thalmann", "Stockholm, Sweden", - "Replication and cluster development" }, - { "Tomas Ulin", "Stockholm, Sweden", - "NDB Cluster: Configuration, installation" }, - { "Gianmassimo Vigazzola", "", "Initial Windows port" }, - { "Sergey Vojtovich", "Izhevsk, Russia", "Plugins infrastructure (5.1)" }, - { "Matt Wagner", "Northfield, MN, USA", "Bug fixing" }, - { "Jim Winstead Jr.", "Los Angeles, CA, USA", "Bug fixing" }, - { "Peter Zaitsev", "Tacoma, WA, USA", - "SHA1(), AES_ENCRYPT(), AES_DECRYPT(), bug fixing" }, - {"Mark Mark Callaghan", "Texas, USA", "Statistics patches"}, - {NULL, NULL, NULL} -}; - -#endif /* AUTHORS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/backup.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/backup.h deleted file mode 100644 index 8d8a28b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/backup.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef BACKUP_INCLUDED -#define BACKUP_INCLUDED -/* Copyright (c) 2018, MariaDB Corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -enum backup_stages -{ - BACKUP_START, BACKUP_FLUSH, BACKUP_WAIT_FOR_FLUSH, BACKUP_LOCK_COMMIT, - BACKUP_END, BACKUP_FINISHED -}; - -extern TYPELIB backup_stage_names; - -void backup_init(); -bool run_backup_stage(THD *thd, backup_stages stage); -bool backup_end(THD *thd); -void backup_set_alter_copy_lock(THD *thd, TABLE *altered_table); -bool backup_reset_alter_copy_lock(THD *thd); - -bool backup_lock(THD *thd, TABLE_LIST *table); -void backup_unlock(THD *thd); -#endif /* BACKUP_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/bounded_queue.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/bounded_queue.h deleted file mode 100644 index 07ab6db..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/bounded_queue.h +++ /dev/null @@ -1,196 +0,0 @@ -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef BOUNDED_QUEUE_INCLUDED -#define BOUNDED_QUEUE_INCLUDED - -#include "my_base.h" -#include -#include "queues.h" -#include - -class Sort_param; - -/** - A priority queue with a fixed, limited size. - - This is a wrapper on top of QUEUE and the queue_xxx() functions. - It keeps the top-N elements which are inserted. - - Elements of type Element_type are pushed into the queue. - For each element, we call a user-supplied keymaker_function, - to generate a key of type Key_type for the element. - Instances of Key_type are compared with the user-supplied compare_function. - - The underlying QUEUE implementation needs one extra element for replacing - the lowest/highest element when pushing into a full queue. - */ -template -class Bounded_queue -{ -public: - Bounded_queue() - { - memset(&m_queue, 0, sizeof(m_queue)); - } - - ~Bounded_queue() - { - delete_queue(&m_queue); - } - - /** - Function for making sort-key from input data. - @param param Sort parameters. - @param to Where to put the key. - @param from The input data. - */ - typedef uint (*keymaker_function)(Sort_param *param, - Key_type *to, - Element_type *from, - bool packing_keys); - - /** - Function for comparing two keys. - @param n Pointer to number of bytes to compare. - @param a First key. - @param b Second key. - @retval -1, 0, or 1 depending on whether the left argument is - less than, equal to, or greater than the right argument. - */ - typedef int (*compare_function)(size_t *n, Key_type **a, Key_type **b); - - /** - Initialize the queue. - - @param max_elements The size of the queue. - @param max_at_top Set to true if you want biggest element on top. - false: We keep the n largest elements. - pop() will return the smallest key in the result set. - true: We keep the n smallest elements. - pop() will return the largest key in the result set. - @param compare Compare function for elements, takes 3 arguments. - If NULL, we use get_ptr_compare(compare_length). - @param compare_length Length of the data (i.e. the keys) used for sorting. - @param keymaker Function which generates keys for elements. - @param sort_param Sort parameters. - @param sort_keys Array of pointers to keys to sort. - - @retval 0 OK, 1 Could not allocate memory. - - We do *not* take ownership of any of the input pointer arguments. - */ - int init(ha_rows max_elements, bool max_at_top, - compare_function compare, size_t compare_length, - keymaker_function keymaker, Sort_param *sort_param, - Key_type **sort_keys); - - /** - Pushes an element on the queue. - If the queue is already full, we discard one element. - Calls keymaker_function to generate a key for the element. - - @param element The element to be pushed. - */ - void push(Element_type *element); - - /** - Removes the top element from the queue. - - @retval Pointer to the (key of the) removed element. - - @note This function is for unit testing, where we push elements into to the - queue, and test that the appropriate keys are retained. - Interleaving of push() and pop() operations has not been tested. - */ - Key_type **pop() - { - // Don't return the extra element to the client code. - if (queue_is_full((&m_queue))) - queue_remove(&m_queue, 0); - DBUG_ASSERT(m_queue.elements > 0); - if (m_queue.elements == 0) - return NULL; - return reinterpret_cast(queue_remove(&m_queue, 0)); - } - - /** - The number of elements in the queue. - */ - uint num_elements() const { return m_queue.elements; } - - /** - Is the queue initialized? - */ - bool is_initialized() const { return m_queue.max_elements > 0; } - -private: - Key_type **m_sort_keys; - size_t m_compare_length; - keymaker_function m_keymaker; - Sort_param *m_sort_param; - st_queue m_queue; -}; - - -template -int Bounded_queue::init(ha_rows max_elements, - bool max_at_top, - compare_function compare, - size_t compare_length, - keymaker_function keymaker, - Sort_param *sort_param, - Key_type **sort_keys) -{ - DBUG_ASSERT(sort_keys != NULL); - - m_sort_keys= sort_keys; - m_compare_length= compare_length; - m_keymaker= keymaker; - m_sort_param= sort_param; - // init_queue() takes an uint, and also does (max_elements + 1) - if (max_elements >= (UINT_MAX - 1)) - return 1; - if (compare == NULL) - compare= - reinterpret_cast(get_ptr_compare(compare_length)); - // We allocate space for one extra element, for replace when queue is full. - return init_queue(&m_queue, (uint) max_elements + 1, - 0, max_at_top, - reinterpret_cast(compare), - &m_compare_length, 0, 0); -} - - -template -void Bounded_queue::push(Element_type *element) -{ - DBUG_ASSERT(is_initialized()); - if (queue_is_full((&m_queue))) - { - // Replace top element with new key, and re-order the queue. - Key_type **pq_top= reinterpret_cast(queue_top(&m_queue)); - (void)(*m_keymaker)(m_sort_param, *pq_top, element, false); - queue_replace_top(&m_queue); - } else { - // Insert new key into the queue. - (*m_keymaker)(m_sort_param, m_sort_keys[m_queue.elements], - element, false); - queue_insert(&m_queue, - reinterpret_cast(&m_sort_keys[m_queue.elements])); - } -} - -#endif // BOUNDED_QUEUE_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/client_settings.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/client_settings.h deleted file mode 100644 index cc4981e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/client_settings.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef CLIENT_SETTINGS_INCLUDED -#define CLIENT_SETTINGS_INCLUDED -#else -#error You have already included an client_settings.h and it should not be included twice -#endif /* CLIENT_SETTINGS_INCLUDED */ - -#include -#include - -/* - Note: CLIENT_CAPABILITIES is also defined in libmysql/client_settings.h. - When adding capabilities here, consider if they should be also added to - the libmysql version. -*/ -#define CLIENT_CAPABILITIES (CLIENT_MYSQL | \ - CLIENT_LONG_FLAG | \ - CLIENT_TRANSACTIONS | \ - CLIENT_PROTOCOL_41 | \ - CLIENT_SECURE_CONNECTION | \ - CLIENT_PLUGIN_AUTH | \ - CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | \ - CLIENT_CONNECT_ATTRS) - -#define read_user_name(A) A[0]= 0 -#undef _CUSTOMCONFIG_ - -#define mysql_server_init(a,b,c) mysql_client_plugin_init() -#define mysql_server_end() mysql_client_plugin_deinit() - -#ifdef HAVE_REPLICATION -C_MODE_START -void slave_io_thread_detach_vio(); -C_MODE_END -#else -#define slave_io_thread_detach_vio() -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/compat56.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/compat56.h deleted file mode 100644 index 347d614..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/compat56.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef COMPAT56_H_INCLUDED -#define COMPAT56_H_INCLUDED -/* - Copyright (c) 2004, 2012, Oracle and/or its affiliates. - Copyright (c) 2013 MariaDB Foundation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/** MySQL56 routines and macros **/ - -/* - Buffer size for a native TIMESTAMP representation, for use with NativBuffer. - 4 bytes for seconds - 3 bytes for microseconds - 1 byte for the trailing '\0' (class Native reserves extra 1 byte for '\0') -*/ -#define STRING_BUFFER_TIMESTAMP_BINARY_SIZE 8 /* 4 + 3 + 1 */ - -#define MY_PACKED_TIME_GET_INT_PART(x) ((x) >> 24) -#define MY_PACKED_TIME_GET_FRAC_PART(x) ((x) % (1LL << 24)) -#define MY_PACKED_TIME_MAKE(i, f) ((((longlong) (i)) << 24) + (f)) -#define MY_PACKED_TIME_MAKE_INT(i) ((((longlong) (i)) << 24)) - -longlong TIME_to_longlong_datetime_packed(const MYSQL_TIME *); -longlong TIME_to_longlong_time_packed(const MYSQL_TIME *); - -void TIME_from_longlong_datetime_packed(MYSQL_TIME *ltime, longlong nr); -void TIME_from_longlong_time_packed(MYSQL_TIME *ltime, longlong nr); - -void my_datetime_packed_to_binary(longlong nr, uchar *ptr, uint dec); -longlong my_datetime_packed_from_binary(const uchar *ptr, uint dec); -uint my_datetime_binary_length(uint dec); - -void my_time_packed_to_binary(longlong nr, uchar *ptr, uint dec); -longlong my_time_packed_from_binary(const uchar *ptr, uint dec); -uint my_time_binary_length(uint dec); - -void my_timestamp_to_binary(const struct timeval *tm, uchar *ptr, uint dec); -void my_timestamp_from_binary(struct timeval *tm, const uchar *ptr, uint dec); -uint my_timestamp_binary_length(uint dec); -/** End of MySQL routines and macros **/ - -#endif /* COMPAT56_H_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/config.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/config.h deleted file mode 100644 index 22f5893..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/config.h +++ /dev/null @@ -1,558 +0,0 @@ -/* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MY_CONFIG_H -#define MY_CONFIG_H -#define DOT_FRM_VERSION 6 -/* Headers we may want to use. */ -#define STDC_HEADERS 1 -/* #undef _GNU_SOURCE */ -/* #undef HAVE_ALLOCA_H */ -/* #undef HAVE_ARPA_INET_H */ -/* #undef HAVE_ASM_TERMBITS_H */ -/* #undef HAVE_CRYPT_H */ -/* #undef HAVE_CURSES_H */ -/* #undef HAVE_BFD_H */ -/* #undef HAVE_NDIR_H */ -/* #undef HAVE_DIRENT_H */ -/* #undef HAVE_DLFCN_H */ -/* #undef HAVE_EXECINFO_H */ -#define HAVE_FCNTL_H 1 -/* #undef HAVE_FENV_H */ -#define HAVE_FLOAT_H 1 -/* #undef HAVE_FNMATCH_H */ -/* #undef HAVE_FPU_CONTROL_H */ -/* #undef HAVE_GRP_H */ -/* #undef HAVE_IA64INTRIN_H */ -/* #undef HAVE_IEEEFP_H */ -/* #undef HAVE_INTTYPES_H */ -/* #undef HAVE_KQUEUE */ -#define HAVE_LIMITS_H 1 -/* #undef HAVE_LINK_H */ -/* #undef HAVE_LINUX_UNISTD_H */ -#define HAVE_LOCALE_H 1 -#define HAVE_MALLOC_H 1 -#define HAVE_MEMORY_H 1 -/* #undef HAVE_NETINET_IN_H */ -/* #undef HAVE_PATHS_H */ -/* #undef HAVE_POLL_H */ -/* #undef HAVE_PWD_H */ -/* #undef HAVE_SCHED_H */ -/* #undef HAVE_SELECT_H */ -/* #undef HAVE_SOLARIS_LARGE_PAGES */ -#define HAVE_STDDEF_H 1 -#define HAVE_STDLIB_H 1 -#define HAVE_STDARG_H 1 -/* #undef HAVE_STRINGS_H */ -#define HAVE_STRING_H 1 -/* #undef HAVE_STDINT_H */ -/* #undef HAVE_SYNCH_H */ -/* #undef HAVE_SYSENT_H */ -/* #undef HAVE_SYS_DIR_H */ -/* #undef HAVE_SYS_FILE_H */ -/* #undef HAVE_SYS_FPU_H */ -/* #undef HAVE_SYS_IOCTL_H */ -/* #undef HAVE_SYS_MALLOC_H */ -/* #undef HAVE_SYS_MMAN_H */ -/* #undef HAVE_SYS_NDIR_H */ -/* #undef HAVE_SYS_PTE_H */ -/* #undef HAVE_SYS_PTEM_H */ -/* #undef HAVE_SYS_PRCTL_H */ -/* #undef HAVE_SYS_RESOURCE_H */ -/* #undef HAVE_SYS_SELECT_H */ -/* #undef HAVE_SYS_SOCKET_H */ -/* #undef HAVE_SYS_SOCKIO_H */ -/* #undef HAVE_SYS_UTSNAME_H */ -#define HAVE_SYS_STAT_H 1 -/* #undef HAVE_SYS_STREAM_H */ -/* #undef HAVE_SYS_SYSCALL_H */ -#define HAVE_SYS_TIMEB_H 1 -/* #undef HAVE_SYS_TIMES_H */ -/* #undef HAVE_SYS_TIME_H */ -#define HAVE_SYS_TYPES_H 1 -/* #undef HAVE_SYS_UN_H */ -/* #undef HAVE_SYS_VADVISE_H */ -/* #undef HAVE_SYS_STATVFS_H */ -/* #undef HAVE_UCONTEXT_H */ -/* #undef HAVE_TERM_H */ -/* #undef HAVE_TERMBITS_H */ -/* #undef HAVE_TERMIOS_H */ -/* #undef HAVE_TERMIO_H */ -/* #undef HAVE_TERMCAP_H */ -#define HAVE_TIME_H 1 -/* #undef HAVE_UNISTD_H */ -/* #undef HAVE_UTIME_H */ -#define HAVE_VARARGS_H 1 -#define HAVE_SYS_UTIME_H 1 -/* #undef HAVE_SYS_WAIT_H */ -/* #undef HAVE_SYS_PARAM_H */ - -/* Libraries */ -/* #undef HAVE_LIBWRAP */ -/* #undef HAVE_SYSTEMD */ - -/* Does "struct timespec" have a "sec" and "nsec" field? */ -/* #undef HAVE_TIMESPEC_TS_SEC */ - -/* Readline */ -/* #undef HAVE_HIST_ENTRY */ -/* #undef USE_LIBEDIT_INTERFACE */ -/* #undef USE_NEW_READLINE_INTERFACE */ - -/* #undef FIONREAD_IN_SYS_IOCTL */ -/* #undef GWINSZ_IN_SYS_IOCTL */ -/* #undef TIOCSTAT_IN_SYS_IOCTL */ -/* #undef FIONREAD_IN_SYS_FILIO */ - -/* Functions we may want to use. */ -/* #undef HAVE_ACCEPT4 */ -#define HAVE_ACCESS 1 -/* #undef HAVE_ALARM */ -#define HAVE_ALLOCA 1 -/* #undef HAVE_BFILL */ -/* #undef HAVE_INDEX */ -/* #undef HAVE_CLOCK_GETTIME */ -/* #undef HAVE_CRYPT */ -/* #undef HAVE_CUSERID */ -/* #undef HAVE_DLADDR */ -/* #undef HAVE_DLERROR */ -/* #undef HAVE_DLOPEN */ -/* #undef HAVE_FCHMOD */ -/* #undef HAVE_FCNTL */ -/* #undef HAVE_FDATASYNC */ -/* #undef HAVE_DECL_FDATASYNC */ -/* #undef HAVE_FEDISABLEEXCEPT */ -/* #undef HAVE_FESETROUND */ -/* #undef HAVE_FP_EXCEPT */ -/* #undef HAVE_FSEEKO */ -/* #undef HAVE_FSYNC */ -#define HAVE_FTIME 1 -/* #undef HAVE_GETIFADDRS */ -#define HAVE_GETCWD 1 -/* #undef HAVE_GETHOSTBYADDR_R */ -/* #undef HAVE_GETHRTIME */ -/* #undef HAVE_GETPAGESIZE */ -/* #undef HAVE_GETPAGESIZES */ -/* #undef HAVE_GETPASS */ -/* #undef HAVE_GETPASSPHRASE */ -/* #undef HAVE_GETPWNAM */ -/* #undef HAVE_GETPWUID */ -/* #undef HAVE_GETRLIMIT */ -/* #undef HAVE_GETRUSAGE */ -/* #undef HAVE_GETTIMEOFDAY */ -/* #undef HAVE_GETWD */ -#define HAVE_GMTIME_R 1 -/* #undef gmtime_r */ -/* #undef HAVE_IN_ADDR_T */ -/* #undef HAVE_INITGROUPS */ -#define HAVE_LDIV 1 -/* #undef HAVE_LRAND48 */ -#define HAVE_LOCALTIME_R 1 -/* #undef HAVE_LSTAT */ -/* #undef HAVE_MEMALIGN */ -/* #undef HAVE_MLOCK */ -/* #undef HAVE_NL_LANGINFO */ -/* #undef HAVE_MADVISE */ -/* #undef HAVE_DECL_MADVISE */ -/* #undef HAVE_DECL_MHA_MAPSIZE_VA */ -/* #undef HAVE_MALLINFO */ -#define HAVE_MEMCPY 1 -#define HAVE_MEMMOVE 1 -/* #undef HAVE_MKSTEMP */ -/* #undef HAVE_MKOSTEMP */ -/* #undef HAVE_MLOCKALL */ -/* #undef HAVE_MMAP */ -/* #undef HAVE_MMAP64 */ -#define HAVE_PERROR 1 -/* #undef HAVE_POLL */ -/* #undef HAVE_POSIX_FALLOCATE */ -/* #undef HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE */ -/* #undef HAVE_PREAD */ -/* #undef HAVE_READ_REAL_TIME */ -/* #undef HAVE_PTHREAD_ATTR_CREATE */ -/* #undef HAVE_PTHREAD_ATTR_GETGUARDSIZE */ -/* #undef HAVE_PTHREAD_ATTR_GETSTACKSIZE */ -/* #undef HAVE_PTHREAD_ATTR_SETSCOPE */ -/* #undef HAVE_PTHREAD_ATTR_SETSTACKSIZE */ -/* #undef HAVE_PTHREAD_CONDATTR_CREATE */ -/* #undef HAVE_PTHREAD_GETAFFINITY_NP */ -/* #undef HAVE_PTHREAD_KEY_DELETE */ -/* #undef HAVE_PTHREAD_KILL */ -/* #undef HAVE_PTHREAD_RWLOCK_RDLOCK */ -/* #undef HAVE_PTHREAD_SIGMASK */ -/* #undef HAVE_PTHREAD_YIELD_NP */ -/* #undef HAVE_PTHREAD_YIELD_ZERO_ARG */ -/* #undef PTHREAD_ONCE_INITIALIZER */ -#define HAVE_PUTENV 1 -/* #undef HAVE_READDIR_R */ -/* #undef HAVE_READLINK */ -/* #undef HAVE_REALPATH */ -#define HAVE_RENAME 1 -/* #undef HAVE_RWLOCK_INIT */ -/* #undef HAVE_SCHED_YIELD */ -#define HAVE_SELECT 1 -/* #undef HAVE_SETENV */ -#define HAVE_SETLOCALE 1 -/* #undef HAVE_SETUPTERM */ -/* #undef HAVE_SIGSET */ -/* #undef HAVE_SIGACTION */ -/* #undef HAVE_SIGTHREADMASK */ -/* #undef HAVE_SIGWAIT */ -/* #undef HAVE_SIGWAITINFO */ -/* #undef HAVE_SLEEP */ -#define HAVE_SNPRINTF 1 -/* #undef HAVE_STPCPY */ -#define HAVE_STRERROR 1 -#define HAVE_STRCOLL 1 -#define HAVE_STRNLEN 1 -#define HAVE_STRPBRK 1 -#define HAVE_STRTOK_R 1 -#define HAVE_STRTOLL 1 -#define HAVE_STRTOUL 1 -#define HAVE_STRTOULL 1 -#define HAVE_TELL 1 -/* #undef HAVE_THR_SETCONCURRENCY */ -/* #undef HAVE_THR_YIELD */ -#define HAVE_TIME 1 -/* #undef HAVE_TIMES */ -/* #undef HAVE_VIDATTR */ -#define HAVE_VIO_READ_BUFF 1 -/* #undef HAVE_VASPRINTF */ -#define HAVE_VSNPRINTF 1 -/* #undef HAVE_FTRUNCATE */ -#define HAVE_TZNAME 1 -/* Symbols we may use */ -/* #undef HAVE_SYS_ERRLIST */ -/* used by stacktrace functions */ -/* #undef HAVE_BACKTRACE */ -/* #undef HAVE_BACKTRACE_SYMBOLS */ -/* #undef HAVE_BACKTRACE_SYMBOLS_FD */ -/* #undef HAVE_PRINTSTACK */ -#define HAVE_IPV6 1 -/* #undef ss_family */ -/* #undef HAVE_SOCKADDR_IN_SIN_LEN */ -/* #undef HAVE_SOCKADDR_IN6_SIN6_LEN */ -#define STRUCT_TIMESPEC_HAS_TV_SEC 1 -#define STRUCT_TIMESPEC_HAS_TV_NSEC 1 - -#define USE_MB 1 -#define USE_MB_IDENT 1 - -/* this means that valgrind headers and macros are available */ -/* #undef HAVE_VALGRIND_MEMCHECK_H */ - -/* this means WITH_VALGRIND - we change some code paths for valgrind */ -/* #undef HAVE_valgrind */ - -/* Types we may use */ -#ifdef __APPLE__ - /* - Special handling required for OSX to support universal binaries that - mix 32 and 64 bit architectures. - */ - #if(__LP64__) - #define SIZEOF_LONG 8 - #else - #define SIZEOF_LONG 4 - #endif - #define SIZEOF_VOIDP SIZEOF_LONG - #define SIZEOF_CHARP SIZEOF_LONG - #define SIZEOF_SIZE_T SIZEOF_LONG -#else -/* No indentation, to fetch the lines from verification scripts */ -#define SIZEOF_LONG 4 -#define SIZEOF_VOIDP 8 -#define SIZEOF_CHARP 8 -#define SIZEOF_SIZE_T 8 -#endif - -#define HAVE_LONG 1 -#define HAVE_CHARP 1 -#define SIZEOF_INT 4 -#define HAVE_INT 1 -#define SIZEOF_LONG_LONG 8 -#define HAVE_LONG_LONG 1 -#define SIZEOF_OFF_T 4 -#define HAVE_OFF_T 1 -/* #undef SIZEOF_UCHAR */ -/* #undef HAVE_UCHAR */ -/* #undef SIZEOF_UINT */ -/* #undef HAVE_UINT */ -/* #undef SIZEOF_ULONG */ -/* #undef HAVE_ULONG */ -/* #undef SIZEOF_INT8 */ -/* #undef HAVE_INT8 */ -/* #undef SIZEOF_UINT8 */ -/* #undef HAVE_UINT8 */ -/* #undef SIZEOF_INT16 */ -/* #undef HAVE_INT16 */ -/* #undef SIZEOF_UINT16 */ -/* #undef HAVE_UINT16 */ -/* #undef SIZEOF_INT32 */ -/* #undef HAVE_INT32 */ -/* #undef SIZEOF_UINT32 */ -/* #undef HAVE_UINT32 */ -/* #undef SIZEOF_INT64 */ -/* #undef HAVE_INT64 */ -/* #undef SIZEOF_UINT64 */ -/* #undef HAVE_UINT64 */ - -#define SOCKET_SIZE_TYPE int - -/* #undef HAVE_MBSTATE_T */ - -#define MAX_INDEXES 64 - -#define QSORT_TYPE_IS_VOID 1 -#define RETQSORTTYPE void - -#define RETSIGTYPE void -#define VOID_SIGHANDLER 1 -/* #undef HAVE_SIGHANDLER_T */ -#define STRUCT_RLIMIT struct rlimit - -#ifdef __APPLE__ - #if __BIG_ENDIAN - #define WORDS_BIGENDIAN 1 - #endif -#else -/* #undef WORDS_BIGENDIAN */ -#endif - -/* Define to `__inline__' or `__inline' if that's what the C compiler calls - it, or to nothing if 'inline' is not supported under any name. */ -/* #undef C_HAS_inline */ -#if !(C_HAS_inline) -#ifndef __cplusplus -# define inline __inline -#endif -#endif - - -/* #undef TARGET_OS_LINUX */ - -#define HAVE_WCTYPE_H 1 -#define HAVE_WCHAR_H 1 -/* #undef HAVE_LANGINFO_H */ -/* #undef HAVE_MBRLEN */ -/* #undef HAVE_MBSRTOWCS */ -/* #undef HAVE_MBRTOWC */ -/* #undef HAVE_WCWIDTH */ -/* #undef HAVE_ISWLOWER */ -/* #undef HAVE_ISWUPPER */ -/* #undef HAVE_TOWLOWER */ -/* #undef HAVE_TOWUPPER */ -/* #undef HAVE_ISWCTYPE */ -/* #undef HAVE_WCHAR_T */ - - -#define HAVE_STRCASECMP 1 -/* #undef HAVE_TCGETATTR */ - -/* #undef HAVE_WEAK_SYMBOL */ -/* #undef HAVE_ABI_CXA_DEMANGLE */ -/* #undef HAVE_ATTRIBUTE_CLEANUP */ - -/* #undef HAVE_POSIX_SIGNALS */ -/* #undef HAVE_BSD_SIGNALS */ - -/* #undef HAVE_SVR3_SIGNALS */ -/* #undef HAVE_V7_SIGNALS */ -#define HAVE_ERR_remove_thread_state 1 -#define HAVE_X509_check_host 1 - -/* #undef HAVE_SOLARIS_STYLE_GETHOST */ - -/* #undef HAVE_GCC_C11_ATOMICS */ -/* #undef HAVE_SOLARIS_ATOMIC */ -#define NO_FCNTL_NONBLOCK 1 -#define NO_ALARM 1 - -/* #undef _LARGE_FILES */ -#define _LARGEFILE_SOURCE 1 -/* #undef _LARGEFILE64_SOURCE */ - -/* #undef TIME_WITH_SYS_TIME */ - -#define STACK_DIRECTION -1 - -#define SYSTEM_TYPE "Win64" -#define MACHINE_TYPE "AMD64" -#define DEFAULT_MACHINE "x64" -/* #undef HAVE_DTRACE */ - -#define SIGNAL_WITH_VIO_CLOSE 1 - -/* Windows stuff, mostly functions, that have Posix analogs but named differently */ -#define S_IROTH _S_IREAD -#define S_IFIFO _S_IFIFO -/* #undef IPPROTO_IPV6 */ -/* #undef IPV6_V6ONLY */ -#define sigset_t int -#define mode_t int -#define SIGQUIT SIGTERM -#define SIGPIPE SIGINT -#define popen _popen -#define pclose _pclose -#define ssize_t SSIZE_T -#define strcasecmp _stricmp -#define strncasecmp _strnicmp -/* #undef snprintf */ -#define strtok_r strtok_s -#define strtoll _strtoi64 -#define strtoull _strtoui64 -/* #undef vsnprintf */ -#if defined(_MSC_VER) && (_MSC_VER > 1800) -#define tzname _tzname -#define P_tmpdir "C:\\TEMP" -#endif -#if defined(_MSC_VER) && (_MSC_VER > 1310) -# define HAVE_SETENV -#define setenv(a,b,c) _putenv_s(a,b) -#endif -#define PSAPI_VERSION 1 /* for GetProcessMemoryInfo() */ - -/* We don't want the min/max macros */ -#ifdef __WIN__ -#define NOMINMAX 1 -#endif - -/* - MySQL features -*/ -#define LOCAL_INFILE_MODE_OFF 0 -#define LOCAL_INFILE_MODE_ON 1 -#define LOCAL_INFILE_MODE_AUTO 2 -#define ENABLED_LOCAL_INFILE LOCAL_INFILE_MODE_AUTO - -#define ENABLED_PROFILING 1 -/* #undef EXTRA_DEBUG */ -#define USE_SYMDIR 1 - -/* Character sets and collations */ -#define MYSQL_DEFAULT_CHARSET_NAME "latin1" -#define MYSQL_DEFAULT_COLLATION_NAME "latin1_swedish_ci" - -#define USE_MB 1 -#define USE_MB_IDENT 1 - -/* This should mean case insensitive file system */ -#define FN_NO_CASE_SENSE 1 - -#define HAVE_CHARSET_armscii8 1 -#define HAVE_CHARSET_ascii 1 -#define HAVE_CHARSET_big5 1 -#define HAVE_CHARSET_cp1250 1 -#define HAVE_CHARSET_cp1251 1 -#define HAVE_CHARSET_cp1256 1 -#define HAVE_CHARSET_cp1257 1 -#define HAVE_CHARSET_cp850 1 -#define HAVE_CHARSET_cp852 1 -#define HAVE_CHARSET_cp866 1 -#define HAVE_CHARSET_cp932 1 -#define HAVE_CHARSET_dec8 1 -#define HAVE_CHARSET_eucjpms 1 -#define HAVE_CHARSET_euckr 1 -#define HAVE_CHARSET_gb2312 1 -#define HAVE_CHARSET_gbk 1 -#define HAVE_CHARSET_geostd8 1 -#define HAVE_CHARSET_greek 1 -#define HAVE_CHARSET_hebrew 1 -#define HAVE_CHARSET_hp8 1 -#define HAVE_CHARSET_keybcs2 1 -#define HAVE_CHARSET_koi8r 1 -#define HAVE_CHARSET_koi8u 1 -#define HAVE_CHARSET_latin1 1 -#define HAVE_CHARSET_latin2 1 -#define HAVE_CHARSET_latin5 1 -#define HAVE_CHARSET_latin7 1 -#define HAVE_CHARSET_macce 1 -#define HAVE_CHARSET_macroman 1 -#define HAVE_CHARSET_sjis 1 -#define HAVE_CHARSET_swe7 1 -#define HAVE_CHARSET_tis620 1 -#define HAVE_CHARSET_ucs2 1 -#define HAVE_CHARSET_ujis 1 -#define HAVE_CHARSET_utf8mb4 1 -#define HAVE_CHARSET_utf8mb3 1 -#define HAVE_CHARSET_utf16 1 -#define HAVE_CHARSET_utf32 1 -#define HAVE_UCA_COLLATIONS 1 -#define HAVE_COMPRESS 1 -/* #undef HAVE_EncryptAes128Ctr */ -/* #undef HAVE_EncryptAes128Gcm */ - -/* - Stuff that always need to be defined (compile breaks without it) -*/ -#define HAVE_SPATIAL 1 -#define HAVE_RTREE_KEYS 1 -#define HAVE_QUERY_CACHE 1 -#define BIG_TABLES 1 - -/* - Important storage engines (those that really need define - WITH__STORAGE_ENGINE for the whole server) -*/ -#define WITH_INNOBASE_STORAGE_ENGINE 1 -#define WITH_PARTITION_STORAGE_ENGINE 1 -#define WITH_PERFSCHEMA_STORAGE_ENGINE 1 -#define WITH_ARIA_STORAGE_ENGINE 1 -#define USE_ARIA_FOR_TMP_TABLES 1 - -#define DEFAULT_MYSQL_HOME "C:/Program Files/MariaDB 10.5" -#define SHAREDIR "share" -#define DEFAULT_BASEDIR "C:/Program Files/MariaDB 10.5" -#define MYSQL_DATADIR "C:/Program Files/MariaDB 10.5/data" -#define DEFAULT_CHARSET_HOME "C:/Program Files/MariaDB 10.5" -#define PLUGINDIR "C:/Program Files/MariaDB 10.5/lib/plugin" -/* #undef DEFAULT_SYSCONFDIR */ -#define DEFAULT_TMPDIR P_tmpdir - -/* #undef SO_EXT */ - -#define MYSQL_VERSION_MAJOR 10 -#define MYSQL_VERSION_MINOR 5 -#define MYSQL_VERSION_PATCH 7 -#define MYSQL_VERSION_EXTRA "" - -#define PACKAGE "mysql" -#define PACKAGE_BUGREPORT "" -#define PACKAGE_NAME "MySQL Server" -#define PACKAGE_STRING "MySQL Server 10.5.7" -#define PACKAGE_TARNAME "mysql" -#define PACKAGE_VERSION "10.5.7" -#define VERSION "10.5.7" -#define PROTOCOL_VERSION 10 -#define PCRE2_CODE_UNIT_WIDTH 8 - -#define MALLOC_LIBRARY "system" - -/* time_t related defines */ - -#define SIZEOF_TIME_T 8 -#define TIME_T_UNSIGNED 1 - -#ifndef EMBEDDED_LIBRARY -/* #undef WSREP_INTERFACE_VERSION */ -/* #undef WITH_WSREP */ -/* #undef WSREP_PROC_INFO */ -#endif - -#if !defined(__STDC_FORMAT_MACROS) -#define __STDC_FORMAT_MACROS -#endif // !defined(__STDC_FORMAT_MACROS) - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/contributors.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/contributors.h deleted file mode 100644 index 34f0608..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/contributors.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef CONTRIBUTORS_INCLUDED -#define CONTRIBUTORS_INCLUDED - -/* Copyright (c) 2006 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Structure of the name list */ - -struct show_table_contributors_st { - const char *name; - const char *location; - const char *comment; -}; - -/* - Output from "SHOW CONTRIBUTORS" - - Get permission before editing. - - Names should be encoded using UTF-8. - - See also https://mariadb.com/kb/en/log-of-mariadb-contributions/ -*/ - -struct show_table_contributors_st show_table_contributors[]= { - /* MariaDB foundation sponsors, in contribution, size , time order */ - {"Booking.com", "https://www.booking.com", "Founding member, Platinum Sponsor of the MariaDB Foundation"}, - {"Alibaba Cloud", "https://www.alibabacloud.com/", "Platinum Sponsor of the MariaDB Foundation"}, - {"Tencent Cloud", "https://cloud.tencent.com", "Platinum Sponsor of the MariaDB Foundation"}, - {"Microsoft", "https://microsoft.com/", "Platinum Sponsor of the MariaDB Foundation"}, - {"MariaDB Corporation", "https://mariadb.com", "Founding member, Platinum Sponsor of the MariaDB Foundation"}, - {"Visma", "https://visma.com", "Gold Sponsor of the MariaDB Foundation"}, - {"DBS", "https://dbs.com", "Gold Sponsor of the MariaDB Foundation"}, - {"IBM", "https://www.ibm.com", "Gold Sponsor of the MariaDB Foundation"}, - {"Tencent Games", "http://game.qq.com/", "Gold Sponsor of the MariaDB Foundation"}, - {"Nexedi", "https://www.nexedi.com", "Silver Sponsor of the MariaDB Foundation"}, - {"Acronis", "https://www.acronis.com", "Silver Sponsor of the MariaDB Foundation"}, - {"Verkkokauppa.com", "https://www.verkkokauppa.com", "Bronze Sponsor of the MariaDB Foundation"}, - {"Virtuozzo", "https://virtuozzo.com", "Bronze Sponsor of the MariaDB Foundation"}, - {"Tencent Game DBA", "http://tencentdba.com/about", "Bronze Sponsor of the MariaDB Foundation"}, - {"Tencent TDSQL", "http://tdsql.org", "Bronze Sponsor of the MariaDB Foundation"}, - {"Percona", "https://www.percona.com/", "Bronze Sponsor of the MariaDB Foundation"}, - - /* Sponsors of important features */ - {"Google", "USA", "Sponsoring encryption, parallel replication and GTID"}, - {"Facebook", "USA", "Sponsoring non-blocking API, LIMIT ROWS EXAMINED etc"}, - - /* Individual contributors, names in historical order, newer first */ - {"Ronald Bradford", "Brisbane, Australia", "EFF contribution for UC2006 Auction"}, - {"Sheeri Kritzer", "Boston, Mass. USA", "EFF contribution for UC2006 Auction"}, - {"Mark Shuttleworth", "London, UK.", "EFF contribution for UC2006 Auction"}, - {NULL, NULL, NULL} -}; - -#endif /* CONTRIBUTORS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/create_options.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/create_options.h deleted file mode 100644 index ce64516..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/create_options.h +++ /dev/null @@ -1,108 +0,0 @@ -/* Copyright (C) 2010 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Engine defined options of tables/fields/keys in CREATE/ALTER TABLE. -*/ - -#ifndef SQL_CREATE_OPTIONS_INCLUDED -#define SQL_CREATE_OPTIONS_INCLUDED - -#include "sql_class.h" - -enum { ENGINE_OPTION_MAX_LENGTH=32767 }; - -class engine_option_value: public Sql_alloc -{ - public: - LEX_CSTRING name; - LEX_CSTRING value; - engine_option_value *next; ///< parser puts them in a FIFO linked list - bool parsed; ///< to detect unrecognized options - bool quoted_value; ///< option=VAL vs. option='VAL' - - engine_option_value(engine_option_value *src, - engine_option_value **start, engine_option_value **end) : - name(src->name), value(src->value), - next(NULL), parsed(src->parsed), quoted_value(src->quoted_value) - { - link(start, end); - } - engine_option_value(LEX_CSTRING &name_arg, LEX_CSTRING &value_arg, - bool quoted, - engine_option_value **start, engine_option_value **end) : - name(name_arg), value(value_arg), - next(NULL), parsed(false), quoted_value(quoted) - { - link(start, end); - } - engine_option_value(LEX_CSTRING &name_arg, - engine_option_value **start, engine_option_value **end) : - name(name_arg), value(null_clex_str), - next(NULL), parsed(false), quoted_value(false) - { - link(start, end); - } - engine_option_value(LEX_CSTRING &name_arg, ulonglong value_arg, - engine_option_value **start, engine_option_value **end, - MEM_ROOT *root) : - name(name_arg), next(NULL), parsed(false), quoted_value(false) - { - char *str; - if (likely((value.str= str= (char *)alloc_root(root, 22)))) - { - value.length= longlong10_to_str(value_arg, str, 10) - str; - link(start, end); - } - } - static uchar *frm_read(const uchar *buff, const uchar *buff_end, - engine_option_value **start, - engine_option_value **end, MEM_ROOT *root); - void link(engine_option_value **start, engine_option_value **end); - uint frm_length(); - uchar *frm_image(uchar *buff); -}; - -typedef struct st_key KEY; -class Create_field; - -bool resolve_sysvar_table_options(handlerton *hton); -void free_sysvar_table_options(handlerton *hton); -bool parse_engine_table_options(THD *thd, handlerton *ht, TABLE_SHARE *share); -bool parse_option_list(THD* thd, handlerton *hton, void *option_struct, - engine_option_value **option_list, - ha_create_table_option *rules, - bool suppress_warning, MEM_ROOT *root); -bool engine_table_options_frm_read(const uchar *buff, size_t length, - TABLE_SHARE *share); -engine_option_value *merge_engine_table_options(engine_option_value *source, - engine_option_value *changes, - MEM_ROOT *root); - -uint engine_table_options_frm_length(engine_option_value *table_option_list, - List &create_fields, - uint keys, KEY *key_info); -uchar *engine_table_options_frm_image(uchar *buff, - engine_option_value *table_option_list, - List &create_fields, - uint keys, KEY *key_info); - -bool engine_options_differ(void *old_struct, void *new_struct, - ha_create_table_option *rules); -bool is_engine_option_known(engine_option_value *opt, - ha_create_table_option *rules); -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/custom_conf.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/custom_conf.h deleted file mode 100644 index 5847b93..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/custom_conf.h +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright (c) 2000, 2006 MySQL AB - Use is subject to license terms - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef __MYSQL_CUSTOM_BUILD_CONFIG__ -#define __MYSQL_CUSTOM_BUILD_CONFIG__ - -#define MYSQL_PORT 5002 -#ifdef __WIN__ -#define MYSQL_NAMEDPIPE "SwSqlServer" -#define MYSQL_SERVICENAME "SwSqlServer" -#define KEY_SERVICE_PARAMETERS -"SYSTEM\\CurrentControlSet\\Services\\SwSqlServer\\Parameters" -#endif - -#endif /* __MYSQL_CUSTOM_BUILD_CONFIG__ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/datadict.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/datadict.h deleted file mode 100644 index f4af592..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/datadict.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef DATADICT_INCLUDED -#define DATADICT_INCLUDED -/* Copyright (c) 2010, Oracle and/or its affiliates. - Copyright (c) 2017 MariaDB corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "handler.h" - -/* - Data dictionary API. -*/ - -enum Table_type -{ - TABLE_TYPE_UNKNOWN, - TABLE_TYPE_NORMAL, /* Normal table */ - TABLE_TYPE_SEQUENCE, - TABLE_TYPE_VIEW -}; - -/* - Take extra care when using dd_frm_type() - it only checks the .frm file, - and it won't work for any engine that supports discovery. - - Prefer to use ha_table_exists() instead. - To check whether it's an frm of a view, use dd_frm_is_view(). -*/ - -enum Table_type dd_frm_type(THD *thd, char *path, LEX_CSTRING *engine_name); - -static inline bool dd_frm_is_view(THD *thd, char *path) -{ - return dd_frm_type(thd, path, NULL) == TABLE_TYPE_VIEW; -} - -bool dd_recreate_table(THD *thd, const char *db, const char *table_name); - -#endif // DATADICT_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/debug_sync.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/debug_sync.h deleted file mode 100644 index 3b8aa88..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/debug_sync.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef DEBUG_SYNC_INCLUDED -#define DEBUG_SYNC_INCLUDED - -/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Declarations for the Debug Sync Facility. See debug_sync.cc for details. -*/ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -class THD; - -#if defined(ENABLED_DEBUG_SYNC) - -/* Command line option --debug-sync-timeout. See mysqld.cc. */ -extern MYSQL_PLUGIN_IMPORT uint opt_debug_sync_timeout; - -/* Default WAIT_FOR timeout if command line option is given without argument. */ -#define DEBUG_SYNC_DEFAULT_WAIT_TIMEOUT 300 - -/* Debug Sync prototypes. See debug_sync.cc. */ -extern int debug_sync_init(void); -extern void debug_sync_end(void); -extern void debug_sync_init_thread(THD *thd); -extern void debug_sync_end_thread(THD *thd); -void debug_sync_reset_thread(THD *thd); -extern bool debug_sync_set_action(THD *thd, const char *action_str, size_t len); -extern bool debug_sync_update(THD *thd, char *val_str, size_t len); -extern uchar *debug_sync_value_ptr(THD *thd); -#else -static inline void debug_sync_init_thread(THD *thd) {} -static inline void debug_sync_end_thread(THD *thd) {} -static inline void debug_sync_reset_thread(THD *thd) {} -static inline bool debug_sync_set_action(THD *, const char *, size_t) -{ return false; } -#endif /* defined(ENABLED_DEBUG_SYNC) */ - -#endif /* DEBUG_SYNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/derived_handler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/derived_handler.h deleted file mode 100644 index 171165b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/derived_handler.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright (c) 2016, 2017 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef DERIVED_HANDLER_INCLUDED -#define DERIVED_HANDLER_INCLUDED - -#include "mariadb.h" -#include "sql_priv.h" - -class TMP_TABLE_PARAM; - -typedef class st_select_lex_unit SELECT_LEX_UNIT; - -/** - @class derived_handler - - This interface class is to be used for execution of queries that specify - derived table by foreign engines -*/ - -class derived_handler -{ -public: - THD *thd; - handlerton *ht; - - TABLE_LIST *derived; - - /* - Temporary table where all results should be stored in record[0] - The table has a field for every item from the select list of - the specification of derived. - */ - TABLE *table; - - /* The parameters if the temporary table used at its creation */ - TMP_TABLE_PARAM *tmp_table_param; - - SELECT_LEX_UNIT *unit; // Specifies the derived table - - SELECT_LEX *select; // The first select of the specification - - derived_handler(THD *thd_arg, handlerton *ht_arg) - : thd(thd_arg), ht(ht_arg), derived(0),table(0), tmp_table_param(0), - unit(0), select(0) {} - virtual ~derived_handler() {} - - /* - Functions to scan data. All these returns 0 if ok, error code in case - of error - */ - - /* Initialize the process of producing rows of the derived table */ - virtual int init_scan()= 0; - - /* - Put the next produced row of the derived in table->record[0] and return 0. - Return HA_ERR_END_OF_FILE if there are no more rows, return other error - number in case of fatal error. - */ - virtual int next_row()= 0; - - /* End prodicing rows */ - virtual int end_scan()=0; - - /* Report errors */ - virtual void print_error(int error, myf errflag); - - void set_derived(TABLE_LIST *tbl); -}; - -#endif /* DERIVED_HANDLER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/derror.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/derror.h deleted file mode 100644 index 34a71b7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/derror.h +++ /dev/null @@ -1,24 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef DERROR_INCLUDED -#define DERROR_INCLUDED - -bool init_errmessage(void); -void free_error_messages(); -bool read_texts(const char *file_name, const char *language, - const char ****data); - -#endif /* DERROR_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/des_key_file.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/des_key_file.h deleted file mode 100644 index 847cd76..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/des_key_file.h +++ /dev/null @@ -1,40 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef DES_KEY_FILE_INCLUDED -#define DES_KEY_FILE_INCLUDED - -#ifdef HAVE_OPENSSL -#include - -#include "violite.h" /* DES_cblock, DES_key_schedule */ - -struct st_des_keyblock -{ - DES_cblock key1, key2, key3; -}; - -struct st_des_keyschedule -{ - DES_key_schedule ks1, ks2, ks3; -}; - -extern struct st_des_keyschedule des_keyschedule[10]; -extern uint des_default_key; - -bool load_des_key_file(const char *file_name); -#endif /* HAVE_OPENSSL */ - -#endif /* DES_KEY_FILE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/discover.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/discover.h deleted file mode 100644 index 1775f5d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/discover.h +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef DISCOVER_INCLUDED -#define DISCOVER_INCLUDED - -int extension_based_table_discovery(MY_DIR *dirp, const char *ext, - handlerton::discovered_list *tl); - -#ifdef MYSQL_SERVER -int readfrm(const char *name, const uchar **data, size_t *length); -int writefile(const char *path, const char *db, const char *table, - bool tmp_table, const uchar *frmdata, size_t len); - -/* a helper to delete an frm file, given a path w/o .frm extension */ -inline void deletefrm(const char *path) -{ - char frm_name[FN_REFLEN]; - strxmov(frm_name, path, reg_ext, NullS); - mysql_file_delete(key_file_frm, frm_name, MYF(0)); -} - -int ext_table_discovery_simple(MY_DIR *dirp, - handlerton::discovered_list *result); -#endif - -#endif /* DISCOVER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/dur_prop.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/dur_prop.h deleted file mode 100644 index 558ce5a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/dur_prop.h +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef _my_dur_prop_h -#define _my_dur_prop_h - -enum durability_properties -{ - /* - Preserves the durability properties defined by the engine - */ - HA_REGULAR_DURABILITY= 0, - /* - Ignore the durability properties defined by the engine and - write only in-memory entries. - */ - HA_IGNORE_DURABILITY= 1 -}; - -#endif /* _my_dur_prop_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_data_objects.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_data_objects.h deleted file mode 100644 index c20a8c3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_data_objects.h +++ /dev/null @@ -1,207 +0,0 @@ -#ifndef _EVENT_DATA_OBJECTS_H_ -#define _EVENT_DATA_OBJECTS_H_ -/* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @addtogroup Event_Scheduler - @{ - - @file event_data_objects.h -*/ - -#include "event_parse_data.h" -#include "thr_lock.h" /* thr_lock_type */ - -class Field; -class THD; -class Time_zone; -struct TABLE; - -void init_scheduler_psi_keys(void); - -class Event_queue_element_for_exec -{ -public: - Event_queue_element_for_exec(){}; - ~Event_queue_element_for_exec(); - - bool - init(const LEX_CSTRING &dbname, const LEX_CSTRING &name); - - LEX_CSTRING dbname; - LEX_CSTRING name; - bool dropped; - THD *thd; - -private: - /* Prevent use of these */ - Event_queue_element_for_exec(const Event_queue_element_for_exec &); - void operator=(Event_queue_element_for_exec &); -#ifdef HAVE_PSI_INTERFACE -public: - PSI_statement_info* get_psi_info() - { - return & psi_info; - } - - static PSI_statement_info psi_info; -#endif -}; - - -class Event_basic -{ -protected: - MEM_ROOT mem_root; - -public: - - LEX_CSTRING dbname; - LEX_CSTRING name; - LEX_CSTRING definer;// combination of user and host - - Time_zone *time_zone; - - Event_basic(); - virtual ~Event_basic(); - - virtual bool - load_from_row(THD *thd, TABLE *table) = 0; - -protected: - bool - load_string_fields(Field **fields, ...); - - bool - load_time_zone(THD *thd, const LEX_CSTRING *tz_name); -}; - - - -class Event_queue_element : public Event_basic -{ -public: - int on_completion; - int status; - uint32 originator; - - my_time_t last_executed; - my_time_t execute_at; - my_time_t starts; - my_time_t ends; - bool starts_null; - bool ends_null; - bool execute_at_null; - - longlong expression; - interval_type interval; - - bool dropped; - - uint execution_count; - - Event_queue_element(); - virtual ~Event_queue_element(); - - virtual bool - load_from_row(THD *thd, TABLE *table); - - bool - compute_next_execution_time(); - - void - mark_last_executed(THD *thd); -}; - - -class Event_timed : public Event_queue_element -{ - Event_timed(const Event_timed &); /* Prevent use of these */ - void operator=(Event_timed &); - -public: - LEX_CSTRING body; - - LEX_CSTRING definer_user; - LEX_CSTRING definer_host; - - LEX_CSTRING comment; - - ulonglong created; - ulonglong modified; - - sql_mode_t sql_mode; - - class Stored_program_creation_ctx *creation_ctx; - LEX_CSTRING body_utf8; - - Event_timed(); - virtual ~Event_timed(); - - void - init(); - - virtual bool - load_from_row(THD *thd, TABLE *table); - - int - get_create_event(THD *thd, String *buf); -}; - - -class Event_job_data : public Event_basic -{ -public: - LEX_CSTRING body; - LEX_CSTRING definer_user; - LEX_CSTRING definer_host; - - sql_mode_t sql_mode; - - class Stored_program_creation_ctx *creation_ctx; - - Event_job_data(); - - virtual bool - load_from_row(THD *thd, TABLE *table); - - bool - execute(THD *thd, bool drop); -private: - bool - construct_sp_sql(THD *thd, String *sp_sql); - bool - construct_drop_event_sql(THD *thd, String *sp_sql); - - Event_job_data(const Event_job_data &); /* Prevent use of these */ - void operator=(Event_job_data &); -}; - - -/* Compares only the schema part of the identifier */ -bool -event_basic_db_equal(const LEX_CSTRING *db, Event_basic *et); - -/* Compares the whole identifier*/ -bool -event_basic_identifier_equal(const LEX_CSTRING *db, const LEX_CSTRING *name, - Event_basic *b); - -/** - @} (End of group Event_Scheduler) -*/ - -#endif /* _EVENT_DATA_OBJECTS_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_db_repository.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_db_repository.h deleted file mode 100644 index b89a1a1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_db_repository.h +++ /dev/null @@ -1,131 +0,0 @@ -#ifndef _EVENT_DB_REPOSITORY_H_ -#define _EVENT_DB_REPOSITORY_H_ -/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -/** - @addtogroup Event_Scheduler - @{ - - @file event_db_repository.h - - Data Dictionary related operations of Event Scheduler. - - This is a private header file of Events module. Please do not include it - directly. All public declarations of Events module should be stored in - events.h and event_data_objects.h. -*/ - -enum enum_events_table_field -{ - ET_FIELD_DB = 0, - ET_FIELD_NAME, - ET_FIELD_BODY, - ET_FIELD_DEFINER, - ET_FIELD_EXECUTE_AT, - ET_FIELD_INTERVAL_EXPR, - ET_FIELD_TRANSIENT_INTERVAL, - ET_FIELD_CREATED, - ET_FIELD_MODIFIED, - ET_FIELD_LAST_EXECUTED, - ET_FIELD_STARTS, - ET_FIELD_ENDS, - ET_FIELD_STATUS, - ET_FIELD_ON_COMPLETION, - ET_FIELD_SQL_MODE, - ET_FIELD_COMMENT, - ET_FIELD_ORIGINATOR, - ET_FIELD_TIME_ZONE, - ET_FIELD_CHARACTER_SET_CLIENT, - ET_FIELD_COLLATION_CONNECTION, - ET_FIELD_DB_COLLATION, - ET_FIELD_BODY_UTF8, - ET_FIELD_COUNT /* a cool trick to count the number of fields :) */ -}; - - -int -events_table_index_read_for_db(THD *thd, TABLE *schema_table, - TABLE *event_table); - -int -events_table_scan_all(THD *thd, TABLE *schema_table, TABLE *event_table); - - -class Event_basic; -class Event_parse_data; - -class Event_db_repository -{ -public: - Event_db_repository(){} - - bool - create_event(THD *thd, Event_parse_data *parse_data, - bool *event_already_exists); - bool - update_event(THD *thd, Event_parse_data *parse_data, LEX_CSTRING *new_dbname, - LEX_CSTRING *new_name); - - bool - drop_event(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *name, - bool drop_if_exists); - - void - drop_schema_events(THD *thd, const LEX_CSTRING *schema); - - bool - find_named_event(const LEX_CSTRING *db, const LEX_CSTRING *name, - TABLE *table); - - bool - load_named_event(THD *thd, const LEX_CSTRING *dbname, - const LEX_CSTRING *name, - Event_basic *et); - - static bool - open_event_table(THD *thd, enum thr_lock_type lock_type, TABLE **table); - - bool - fill_schema_events(THD *thd, TABLE_LIST *tables, const char *db); - - bool - update_timing_fields_for_event(THD *thd, - const LEX_CSTRING *event_db_name, - const LEX_CSTRING *event_name, - my_time_t last_executed, - ulonglong status); -public: - static bool - check_system_tables(THD *thd); -private: - bool - index_read_for_db_for_i_s(THD *thd, TABLE *schema_table, TABLE *event_table, - const char *db); - - bool - table_scan_all_for_i_s(THD *thd, TABLE *schema_table, TABLE *event_table); - -private: - /* Prevent use of these */ - Event_db_repository(const Event_db_repository &); - void operator=(Event_db_repository &); -}; - -/** - @} (End of group Event_Scheduler) -*/ -#endif /* _EVENT_DB_REPOSITORY_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_parse_data.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_parse_data.h deleted file mode 100644 index 4e68295..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_parse_data.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright (c) 2008, 2011, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _EVENT_PARSE_DATA_H_ -#define _EVENT_PARSE_DATA_H_ - -#include "sql_alloc.h" - -class Item; -class THD; -class sp_name; - -#define EVEX_GET_FIELD_FAILED -2 -#define EVEX_BAD_PARAMS -5 -#define EVEX_MICROSECOND_UNSUP -6 -#define EVEX_MAX_INTERVAL_VALUE 1000000000L - -class Event_parse_data : public Sql_alloc -{ -public: - /* - ENABLED = feature can function normally (is turned on) - SLAVESIDE_DISABLED = feature is turned off on slave - DISABLED = feature is turned off - */ - enum enum_status - { - ENABLED = 1, - DISABLED, - SLAVESIDE_DISABLED - }; - - enum enum_on_completion - { - /* - On CREATE EVENT, DROP is the DEFAULT as per the docs. - On ALTER EVENT, "no change" is the DEFAULT. - */ - ON_COMPLETION_DEFAULT = 0, - ON_COMPLETION_DROP, - ON_COMPLETION_PRESERVE - }; - - int on_completion; - int status; - bool status_changed; - uint32 originator; - /* - do_not_create will be set if STARTS time is in the past and - on_completion == ON_COMPLETION_DROP. - */ - bool do_not_create; - - bool body_changed; - - LEX_CSTRING dbname; - LEX_CSTRING name; - LEX_CSTRING definer;// combination of user and host - LEX_CSTRING comment; - - Item* item_starts; - Item* item_ends; - Item* item_execute_at; - - my_time_t starts; - my_time_t ends; - my_time_t execute_at; - bool starts_null; - bool ends_null; - bool execute_at_null; - - sp_name *identifier; - Item* item_expression; - longlong expression; - interval_type interval; - - static Event_parse_data * - new_instance(THD *thd); - - bool - check_parse_data(THD *thd); - - bool - check_dates(THD *thd, int previous_on_completion); - -private: - - void - init_definer(THD *thd); - - void - init_name(THD *thd, sp_name *spn); - - int - init_execute_at(THD *thd); - - int - init_interval(THD *thd); - - int - init_starts(THD *thd); - - int - init_ends(THD *thd); - - Event_parse_data(); - ~Event_parse_data(); - - void - report_bad_value(const char *item_name, Item *bad_item); - - void - check_if_in_the_past(THD *thd, my_time_t ltime_utc); - - Event_parse_data(const Event_parse_data &); /* Prevent use of these */ - void check_originator_id(THD *thd); - void operator=(Event_parse_data &); -}; -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_queue.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_queue.h deleted file mode 100644 index 2b6a0a5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_queue.h +++ /dev/null @@ -1,135 +0,0 @@ -#ifndef _EVENT_QUEUE_H_ -#define _EVENT_QUEUE_H_ -/* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - - @addtogroup Event_Scheduler - @{ - - @file event_queue.h - - Queue of events awaiting execution. -*/ - -#ifdef HAVE_PSI_INTERFACE -extern PSI_mutex_key key_LOCK_event_queue; -extern PSI_cond_key key_COND_queue_state; -#endif /* HAVE_PSI_INTERFACE */ - -#include "queues.h" // QUEUE -#include "sql_string.h" /* LEX_CSTRING */ -#include "my_time.h" /* my_time_t, interval_type */ - -class Event_basic; -class Event_queue_element; -class Event_queue_element_for_exec; - -class THD; - -/** - Queue of active events awaiting execution. -*/ - -class Event_queue -{ -public: - Event_queue(); - ~Event_queue(); - - bool - init_queue(THD *thd); - - /* Methods for queue management follow */ - - bool - create_event(THD *thd, Event_queue_element *new_element, - bool *created); - - void - update_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name, - Event_queue_element *new_element); - - void - drop_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name); - - void - drop_schema_events(THD *thd, const LEX_CSTRING *schema); - - void - recalculate_activation_times(THD *thd); - - bool - get_top_for_execution_if_time(THD *thd, - Event_queue_element_for_exec **event_name); - - - void - dump_internal_status(); - -private: - void - empty_queue(); - - void - deinit_queue(); - /* helper functions for working with mutexes & conditionals */ - void - lock_data(const char *func, uint line); - - void - unlock_data(const char *func, uint line); - - void - cond_wait(THD *thd, struct timespec *abstime, const PSI_stage_info *stage, - const char *src_func, const char *src_file, uint src_line); - - void - find_n_remove_event(const LEX_CSTRING *db, const LEX_CSTRING *name); - - - void - drop_matching_events(THD *thd, const LEX_CSTRING *pattern, - bool (*)(const LEX_CSTRING*, Event_basic *)); - - - void - dbug_dump_queue(my_time_t now); - - /* LOCK_event_queue is the mutex which protects the access to the queue. */ - mysql_mutex_t LOCK_event_queue; - mysql_cond_t COND_queue_state; - - /* The sorted queue with the Event_queue_element objects */ - QUEUE queue; - - my_time_t next_activation_at; - - uint mutex_last_locked_at_line; - uint mutex_last_unlocked_at_line; - uint mutex_last_attempted_lock_at_line; - const char* mutex_last_locked_in_func; - const char* mutex_last_unlocked_in_func; - const char* mutex_last_attempted_lock_in_func; - bool mutex_queue_data_locked; - bool mutex_queue_data_attempting_lock; - bool waiting_on_cond; -}; -/** - @} (End of group Event_Scheduler) -*/ - -#endif /* _EVENT_QUEUE_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_scheduler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_scheduler.h deleted file mode 100644 index 59ac923..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/event_scheduler.h +++ /dev/null @@ -1,157 +0,0 @@ -#ifndef _EVENT_SCHEDULER_H_ -#define _EVENT_SCHEDULER_H_ -/* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @addtogroup Event_Scheduler - @{ -*/ -/** - @file - - Declarations of the scheduler thread class - and related functionality. - - This file is internal to Event_Scheduler module. Please do not - include it directly. All public declarations of Event_Scheduler - module are in events.h and event_data_objects.h. -*/ - - -class Event_queue; -class Event_job_data; -class Event_db_repository; -class Event_queue_element_for_exec; -class Events; -class THD; - -void -pre_init_event_thread(THD* thd); - -bool -post_init_event_thread(THD* thd); - -void -deinit_event_thread(THD *thd); - - -class Event_worker_thread -{ -public: - static void - init(Event_db_repository *db_repository_arg) - { - db_repository= db_repository_arg; - } - - void - run(THD *thd, Event_queue_element_for_exec *event); - -private: - void - print_warnings(THD *thd, Event_job_data *et); - - static Event_db_repository *db_repository; -}; - - -class Event_scheduler -{ -public: - Event_scheduler(Event_queue *event_queue_arg); - ~Event_scheduler(); - - - /* State changing methods follow */ - - bool - start(int *err_no); - - bool - stop(); - - /* - Need to be public because has to be called from the function - passed to pthread_create. - */ - bool - run(THD *thd); - - - /* Information retrieving methods follow */ - bool - is_running(); - - void - dump_internal_status(); - -private: - uint - workers_count(); - - /* helper functions */ - bool - execute_top(Event_queue_element_for_exec *event_name); - - /* helper functions for working with mutexes & conditionals */ - void - lock_data(const char *func, uint line); - - void - unlock_data(const char *func, uint line); - - void - cond_wait(THD *thd, struct timespec *abstime, const PSI_stage_info *stage, - const char *src_func, const char *src_file, uint src_line); - - mysql_mutex_t LOCK_scheduler_state; - - enum enum_state - { - INITIALIZED = 0, - RUNNING, - STOPPING - }; - - /* This is the current status of the life-cycle of the scheduler. */ - enum enum_state state; - - THD *scheduler_thd; - - mysql_cond_t COND_state; - - Event_queue *queue; - - uint mutex_last_locked_at_line; - uint mutex_last_unlocked_at_line; - const char* mutex_last_locked_in_func; - const char* mutex_last_unlocked_in_func; - bool mutex_scheduler_data_locked; - bool waiting_on_cond; - - ulonglong started_events; - -private: - /* Prevent use of these */ - Event_scheduler(const Event_scheduler &); - void operator=(Event_scheduler &); -}; - -/** - @} (End of group Event_Scheduler) -*/ - -#endif /* _EVENT_SCHEDULER_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/events.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/events.h deleted file mode 100644 index 2fb13d7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/events.h +++ /dev/null @@ -1,164 +0,0 @@ -#ifndef _EVENT_H_ -#define _EVENT_H_ -/* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @defgroup Event_Scheduler Event Scheduler - @ingroup Runtime_Environment - @{ - - @file events.h - - A public interface of Events_Scheduler module. -*/ - -#ifdef HAVE_PSI_INTERFACE -extern PSI_mutex_key key_event_scheduler_LOCK_scheduler_state; -extern PSI_cond_key key_event_scheduler_COND_state; -extern PSI_thread_key key_thread_event_scheduler, key_thread_event_worker; -#endif /* HAVE_PSI_INTERFACE */ - -extern PSI_memory_key key_memory_event_basic_root; - -/* Always defined, for SHOW PROCESSLIST. */ -extern PSI_stage_info stage_waiting_on_empty_queue; -extern PSI_stage_info stage_waiting_for_next_activation; -extern PSI_stage_info stage_waiting_for_scheduler_to_stop; - -#include "sql_string.h" /* LEX_CSTRING */ -#include "my_time.h" /* interval_type */ - -class Event_db_repository; -class Event_parse_data; -class Event_queue; -class Event_scheduler; -struct TABLE_LIST; -class THD; -typedef class Item COND; - -int -sortcmp_lex_string(const LEX_CSTRING *s, const LEX_CSTRING *t, - const CHARSET_INFO *cs); - -/** - @brief A facade to the functionality of the Event Scheduler. - - Every public operation against the scheduler has to be executed via the - interface provided by a static method of this class. No instance of this - class is ever created and it has no non-static data members. - - The life cycle of the Events module is the following: - - At server start up: - init_mutexes() -> init() - When the server is running: - create_event(), drop_event(), start_or_stop_event_scheduler(), etc - At shutdown: - deinit(), destroy_mutexes(). - - The peculiar initialization and shutdown cycle is an adaptation to the - outside server startup/shutdown framework and mimics the rest of MySQL - subsystems (ACL, time zone tables, etc). -*/ - -class Events -{ -public: - /* - the following block is to support --event-scheduler command line option - and the @@global.event_scheduler SQL variable. - See sys_var.cc - */ - enum enum_opt_event_scheduler { EVENTS_OFF, EVENTS_ON, EVENTS_DISABLED, - EVENTS_ORIGINAL }; - /* Protected using LOCK_global_system_variables only. */ - static ulong opt_event_scheduler, startup_state; - static ulong inited; - static bool check_if_system_tables_error(); - static bool start(int *err_no); - static bool stop(); - -public: - /* A hack needed for Event_queue_element */ - static Event_db_repository * - get_db_repository() { return db_repository; } - - static bool init(THD *thd, bool opt_noacl); - - static void - deinit(); - - static void - init_mutexes(); - - static void - destroy_mutexes(); - - static bool - create_event(THD *thd, Event_parse_data *parse_data); - - static bool - update_event(THD *thd, Event_parse_data *parse_data, - LEX_CSTRING *new_dbname, LEX_CSTRING *new_name); - - static bool - drop_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name, - bool if_exists); - - static void - drop_schema_events(THD *thd, const char *db); - - static bool - show_create_event(THD *thd, const LEX_CSTRING *dbname, - const LEX_CSTRING *name); - - /* Needed for both SHOW CREATE EVENT and INFORMATION_SCHEMA */ - static int - reconstruct_interval_expression(String *buf, interval_type interval, - longlong expression); - - static int - fill_schema_events(THD *thd, TABLE_LIST *tables, COND * /* cond */); - - static void - dump_internal_status(); - - static void set_original_state(ulong startup_state_org) - { - startup_state= startup_state_org; - } - -private: - - static bool - load_events_from_db(THD *thd); - -private: - static Event_queue *event_queue; - static Event_scheduler *scheduler; - static Event_db_repository *db_repository; - -private: - /* Prevent use of these */ - Events(const Events &); - void operator=(Events &); -}; - -/** - @} (end of group Event Scheduler) -*/ - -#endif /* _EVENT_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/field.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/field.h deleted file mode 100644 index be4d279..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/field.h +++ /dev/null @@ -1,5828 +0,0 @@ -#ifndef FIELD_INCLUDED -#define FIELD_INCLUDED -/* Copyright (c) 2000, 2015, Oracle and/or its affiliates. - Copyright (c) 2008, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Because of the function make_new_field() all field classes that have static - variables must declare the size_of() member function. -*/ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "mysqld.h" /* system_charset_info */ -#include "table.h" /* TABLE */ -#include "sql_string.h" /* String */ -#include "my_decimal.h" /* my_decimal */ -#include "sql_error.h" /* Sql_condition */ -#include "compat56.h" -#include "sql_type.h" /* Type_std_attributes */ -#include "field_comp.h" - -class Send_field; -class Copy_field; -class Protocol; -class Protocol_text; -class Create_field; -class Relay_log_info; -class Field; -class Column_statistics; -class Column_statistics_collected; -class Item_func; -class Item_bool_func; -class Item_equal; -class Virtual_tmp_table; -class Qualified_column_ident; -class Table_ident; -class SEL_ARG; -class RANGE_OPT_PARAM; -struct KEY_PART; -struct SORT_FIELD; -struct SORT_FIELD_ATTR; - -enum enum_check_fields -{ - CHECK_FIELD_IGNORE, - CHECK_FIELD_EXPRESSION, - CHECK_FIELD_WARN, - CHECK_FIELD_ERROR_FOR_NULL, -}; - - -enum enum_conv_type -{ - CONV_TYPE_PRECISE, - CONV_TYPE_VARIANT, - CONV_TYPE_SUBSET_TO_SUPERSET, - CONV_TYPE_SUPERSET_TO_SUBSET, - CONV_TYPE_IMPOSSIBLE -}; - - -class Conv_param -{ - uint16 m_table_def_flags; -public: - Conv_param(uint16 table_def_flags) - :m_table_def_flags(table_def_flags) - { } - uint16 table_def_flags() const { return m_table_def_flags; } -}; - - -class Conv_source: public Type_handler_hybrid_field_type -{ - uint16 m_metadata; - CHARSET_INFO *m_cs; -public: - Conv_source(const Type_handler *h, uint16 metadata, CHARSET_INFO *cs) - :Type_handler_hybrid_field_type(h), - m_metadata(metadata), - m_cs(cs) - { - DBUG_ASSERT(cs); - } - uint16 metadata() const { return m_metadata; } - uint mbmaxlen() const { return m_cs->mbmaxlen; } -}; - - -/* - Common declarations for Field and Item -*/ -class Value_source -{ -protected: - - // Parameters for warning and note generation - class Warn_filter - { - bool m_want_warning_edom; - bool m_want_note_truncated_spaces; - public: - Warn_filter(bool want_warning_edom, bool want_note_truncated_spaces) : - m_want_warning_edom(want_warning_edom), - m_want_note_truncated_spaces(want_note_truncated_spaces) - { } - Warn_filter(const THD *thd); - bool want_warning_edom() const - { return m_want_warning_edom; } - bool want_note_truncated_spaces() const - { return m_want_note_truncated_spaces; } - }; - class Warn_filter_all: public Warn_filter - { - public: - Warn_filter_all() :Warn_filter(true, true) { } - }; - - class Converter_double_to_longlong - { - protected: - bool m_error; - longlong m_result; - public: - Converter_double_to_longlong(double nr, bool unsigned_flag); - longlong result() const { return m_result; } - bool error() const { return m_error; } - void push_warning(THD *thd, double nr, bool unsigned_flag); - }; - class Converter_double_to_longlong_with_warn: - public Converter_double_to_longlong - { - public: - Converter_double_to_longlong_with_warn(THD *thd, double nr, - bool unsigned_flag) - :Converter_double_to_longlong(nr, unsigned_flag) - { - if (m_error) - push_warning(thd, nr, unsigned_flag); - } - Converter_double_to_longlong_with_warn(double nr, bool unsigned_flag) - :Converter_double_to_longlong(nr, unsigned_flag) - { - if (m_error) - push_warning(current_thd, nr, unsigned_flag); - } - }; - - // String-to-number converters - class Converter_string_to_number - { - protected: - char *m_end_of_num; // Where the low-level conversion routine stopped - int m_error; // The error code returned by the low-level routine - bool m_edom; // If EDOM-alike error happened during conversion - /** - Check string-to-number conversion and produce a warning if - - could not convert any digits (EDOM-alike error) - - found garbage at the end of the string - - found extra spaces at the end (a note) - See also Field_num::check_edom_and_truncation() for a similar function. - - @param thd - the thread that will be used to generate warnings. - Can be NULL (which means current_thd will be used - if a warning is really necessary). - @param type - name of the data type - (e.g. "INTEGER", "DECIMAL", "DOUBLE") - @param cs - character set of the original string - @param str - the original string - @param end - the end of the string - @param allow_notes - tells if trailing space notes should be displayed - or suppressed. - - Unlike Field_num::check_edom_and_truncation(), this function does not - distinguish between EDOM and truncation and reports the same warning for - both cases. Perhaps we should eventually print different warnings, - to make the explicit CAST work closer to the implicit cast in - Field_xxx::store(). - */ - void check_edom_and_truncation(THD *thd, Warn_filter filter, - const char *type, - CHARSET_INFO *cs, - const char *str, - size_t length) const; - public: - int error() const { return m_error; } - }; - - class Converter_strntod: public Converter_string_to_number - { - double m_result; - public: - Converter_strntod(CHARSET_INFO *cs, const char *str, size_t length) - { - m_result= cs->strntod((char *) str, length, &m_end_of_num, &m_error); - // strntod() does not set an error if the input string was empty - m_edom= m_error !=0 || str == m_end_of_num; - } - double result() const { return m_result; } - }; - - class Converter_string_to_longlong: public Converter_string_to_number - { - protected: - longlong m_result; - public: - longlong result() const { return m_result; } - }; - - class Converter_strntoll: public Converter_string_to_longlong - { - public: - Converter_strntoll(CHARSET_INFO *cs, const char *str, size_t length) - { - m_result= cs->strntoll(str, length, 10, &m_end_of_num, &m_error); - /* - All non-zero errors means EDOM error. - strntoll() does not set an error if the input string was empty. - Check it here. - Notice the different with the same condition in Converter_strntoll10. - */ - m_edom= m_error != 0 || str == m_end_of_num; - } - }; - - class Converter_strtoll10: public Converter_string_to_longlong - { - public: - Converter_strtoll10(CHARSET_INFO *cs, const char *str, size_t length) - { - m_end_of_num= (char *) str + length; - m_result= cs->strtoll10(str, &m_end_of_num, &m_error); - /* - Negative error means "good negative number". - Only a positive m_error value means a real error. - strtoll10() sets error to MY_ERRNO_EDOM in case of an empty string, - so we don't have to additionally catch empty strings here. - */ - m_edom= m_error > 0; - } - }; - - class Converter_str2my_decimal: public Converter_string_to_number - { - public: - Converter_str2my_decimal(uint mask, - CHARSET_INFO *cs, const char *str, size_t length, - my_decimal *buf) - { - DBUG_ASSERT(length < UINT_MAX32); - m_error= str2my_decimal(mask, str, length, cs, - buf, (const char **) &m_end_of_num); - // E_DEC_TRUNCATED means a very minor truncation: '1e-100' -> 0 - m_edom= m_error && m_error != E_DEC_TRUNCATED; - } - }; - - - // String-to-number converters with automatic warning generation - class Converter_strntod_with_warn: public Converter_strntod - { - public: - Converter_strntod_with_warn(THD *thd, Warn_filter filter, - CHARSET_INFO *cs, - const char *str, size_t length) - :Converter_strntod(cs, str, length) - { - check_edom_and_truncation(thd, filter, "DOUBLE", cs, str, length); - } - }; - - class Converter_strntoll_with_warn: public Converter_strntoll - { - public: - Converter_strntoll_with_warn(THD *thd, Warn_filter filter, - CHARSET_INFO *cs, - const char *str, size_t length) - :Converter_strntoll(cs, str, length) - { - check_edom_and_truncation(thd, filter, "INTEGER", cs, str, length); - } - }; - - class Converter_strtoll10_with_warn: public Converter_strtoll10 - { - public: - Converter_strtoll10_with_warn(THD *thd, Warn_filter filter, - CHARSET_INFO *cs, - const char *str, size_t length) - :Converter_strtoll10(cs, str, length) - { - check_edom_and_truncation(thd, filter, "INTEGER", cs, str, length); - } - }; - - class Converter_str2my_decimal_with_warn: public Converter_str2my_decimal - { - public: - Converter_str2my_decimal_with_warn(THD *thd, Warn_filter filter, - uint mask, CHARSET_INFO *cs, - const char *str, size_t length, - my_decimal *buf) - :Converter_str2my_decimal(mask, cs, str, length, buf) - { - check_edom_and_truncation(thd, filter, "DECIMAL", cs, str, length); - } - }; - - - // String-to-number conversion methods for the old code compatibility - longlong longlong_from_string_with_check(CHARSET_INFO *cs, const char *cptr, - const char *end) const - { - /* - TODO: Give error if we wanted a signed integer and we got an unsigned - one - - Notice, longlong_from_string_with_check() honors thd->no_error, because - it's used to handle queries like this: - SELECT COUNT(@@basedir); - and is called when Item_func_get_system_var::update_null_value() - suppresses warnings and then calls val_int(). - The other methods {double|decimal}_from_string_with_check() ignore - thd->no_errors, because they are not used for update_null_value() - and they always allow all kind of warnings. - */ - THD *thd= current_thd; - return Converter_strtoll10_with_warn(thd, Warn_filter(thd), - cs, cptr, end - cptr).result(); - } - - double double_from_string_with_check(CHARSET_INFO *cs, const char *cptr, - const char *end) const - { - return Converter_strntod_with_warn(NULL, Warn_filter_all(), - cs, cptr, end - cptr).result(); - } - my_decimal *decimal_from_string_with_check(my_decimal *decimal_value, - CHARSET_INFO *cs, - const char *cptr, - const char *end) - { - Converter_str2my_decimal_with_warn(NULL, Warn_filter_all(), - E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM, - cs, cptr, end - cptr, decimal_value); - return decimal_value; - } - - longlong longlong_from_hex_hybrid(const char *str, size_t length) - { - const char *end= str + length; - const char *ptr= end - MY_MIN(length, sizeof(longlong)); - ulonglong value= 0; - for ( ; ptr != end ; ptr++) - value= (value << 8) + (ulonglong) (uchar) *ptr; - return (longlong) value; - } - - longlong longlong_from_string_with_check(const String *str) const - { - return longlong_from_string_with_check(str->charset(), - str->ptr(), str->end()); - } - double double_from_string_with_check(const String *str) const - { - return double_from_string_with_check(str->charset(), - str->ptr(), str->end()); - } - my_decimal *decimal_from_string_with_check(my_decimal *decimal_value, - const String *str) - { - return decimal_from_string_with_check(decimal_value, str->charset(), - str->ptr(), str->end()); - } - // End of String-to-number conversion methods - -public: - /* - The enumeration Subst_constraint is currently used only in implementations - of the virtual function subst_argument_checker. - */ - enum Subst_constraint - { - ANY_SUBST, /* Any substitution for a field is allowed */ - IDENTITY_SUBST /* Substitution for a field is allowed if any two - different values of the field type are not equal */ - }; - /* - Item context attributes. - Comparison functions pass their attributes to propagate_equal_fields(). - For example, for string comparison, the collation of the comparison - operation is important inside propagate_equal_fields(). - */ - class Context - { - /* - Which type of propagation is allowed: - - ANY_SUBST (loose equality, according to the collation), or - - IDENTITY_SUBST (strict binary equality). - */ - Subst_constraint m_subst_constraint; - /* - Comparison type. - Important only when ANY_SUBSTS. - */ - const Type_handler *m_compare_handler; - /* - Collation of the comparison operation. - Important only when ANY_SUBST. - */ - CHARSET_INFO *m_compare_collation; - public: - Context(Subst_constraint subst, const Type_handler *h, CHARSET_INFO *cs) - :m_subst_constraint(subst), - m_compare_handler(h), - m_compare_collation(cs) - { DBUG_ASSERT(h == h->type_handler_for_comparison()); } - Subst_constraint subst_constraint() const { return m_subst_constraint; } - const Type_handler *compare_type_handler() const - { - DBUG_ASSERT(m_subst_constraint == ANY_SUBST); - return m_compare_handler; - } - CHARSET_INFO *compare_collation() const - { - DBUG_ASSERT(m_subst_constraint == ANY_SUBST); - return m_compare_collation; - } - }; - class Context_identity: public Context - { // Use this to request only exact value, no invariants. - public: - Context_identity() - :Context(IDENTITY_SUBST, &type_handler_long_blob, &my_charset_bin) { } - }; - class Context_boolean: public Context - { // Use this when an item is [a part of] a boolean expression - public: - Context_boolean() - :Context(ANY_SUBST, &type_handler_slonglong, &my_charset_bin) { } - }; -}; - - -#define STORAGE_TYPE_MASK 7 -#define COLUMN_FORMAT_MASK 7 -#define COLUMN_FORMAT_SHIFT 3 - -/* The length of the header part for each virtual column in the .frm file */ -#define FRM_VCOL_OLD_HEADER_SIZE(b) (3 + MY_TEST(b)) -#define FRM_VCOL_NEW_BASE_SIZE 16 -#define FRM_VCOL_NEW_HEADER_SIZE 6 - -class Count_distinct_field; - -struct ha_field_option_struct; - -struct st_cache_field; -int field_conv(Field *to,Field *from); -int truncate_double(double *nr, uint field_length, uint dec, - bool unsigned_flag, double max_value); - -inline uint get_enum_pack_length(int elements) -{ - return elements < 256 ? 1 : 2; -} - -inline uint get_set_pack_length(int elements) -{ - uint len= (elements + 7) / 8; - return len > 4 ? 8 : len; -} - - -/** - Tests if field type is temporal and has date part, - i.e. represents DATE, DATETIME or TIMESTAMP types in SQL. - - @param type Field type, as returned by field->type(). - @retval true If field type is temporal type with date part. - @retval false If field type is not temporal type with date part. -*/ -inline bool is_temporal_type_with_date(enum_field_types type) -{ - switch (type) - { - case MYSQL_TYPE_DATE: - case MYSQL_TYPE_DATETIME: - case MYSQL_TYPE_TIMESTAMP: - return true; - case MYSQL_TYPE_DATETIME2: - case MYSQL_TYPE_TIMESTAMP2: - DBUG_ASSERT(0); // field->real_type() should not get to here. - return false; - default: - return false; - } -} - - -enum enum_vcol_info_type -{ - VCOL_GENERATED_VIRTUAL, VCOL_GENERATED_STORED, - VCOL_DEFAULT, VCOL_CHECK_FIELD, VCOL_CHECK_TABLE, - /* Additional types should be added here */ - /* Following is the highest value last */ - VCOL_TYPE_NONE = 127 // Since the 0 value is already in use -}; - -static inline const char *vcol_type_name(enum_vcol_info_type type) -{ - switch (type) - { - case VCOL_GENERATED_VIRTUAL: - case VCOL_GENERATED_STORED: - return "GENERATED ALWAYS AS"; - case VCOL_DEFAULT: - return "DEFAULT"; - case VCOL_CHECK_FIELD: - case VCOL_CHECK_TABLE: - return "CHECK"; - case VCOL_TYPE_NONE: - return "UNTYPED"; - } - return 0; -} - -/* - Flags for Virtual_column_info. If none is set, the expression must be - a constant with no side-effects, so it's calculated at CREATE TABLE time, - stored in table->record[2], and not recalculated for every statement. -*/ -#define VCOL_FIELD_REF 1 -#define VCOL_NON_DETERMINISTIC 2 -#define VCOL_SESSION_FUNC 4 /* uses session data, e.g. USER or DAYNAME */ -#define VCOL_TIME_FUNC 8 -#define VCOL_AUTO_INC 16 -#define VCOL_IMPOSSIBLE 32 -#define VCOL_NOT_VIRTUAL 64 /* Function can't be virtual */ -#define VCOL_CHECK_CONSTRAINT_IF_NOT_EXISTS 128 - -#define VCOL_NOT_STRICTLY_DETERMINISTIC \ - (VCOL_NON_DETERMINISTIC | VCOL_TIME_FUNC | VCOL_SESSION_FUNC) - -/* - Virtual_column_info is the class to contain additional - characteristics that is specific for a virtual/computed - field such as: - - the defining expression that is evaluated to compute the value - of the field - - whether the field is to be stored in the database - - whether the field is used in a partitioning expression -*/ - -class Virtual_column_info: public Sql_alloc, - private Type_handler_hybrid_field_type -{ -private: - enum_vcol_info_type vcol_type; /* Virtual column expression type */ - /* - The following data is only updated by the parser and read - when a Create_field object is created/initialized. - */ - /* Flag indicating that the field used in a partitioning expression */ - bool in_partitioning_expr; - -public: - /* Flag indicating that the field is physically stored in the database */ - bool stored_in_db; - bool utf8; /* Already in utf8 */ - bool automatic_name; - Item *expr; - Lex_ident name; /* Name of constraint */ - /* see VCOL_* (VCOL_FIELD_REF, ...) */ - uint flags; - - Virtual_column_info() - :Type_handler_hybrid_field_type(&type_handler_null), - vcol_type((enum_vcol_info_type)VCOL_TYPE_NONE), - in_partitioning_expr(FALSE), stored_in_db(FALSE), - utf8(TRUE), automatic_name(FALSE), expr(NULL), flags(0) - { - name.str= NULL; - name.length= 0; - }; - Virtual_column_info* clone(THD *thd); - ~Virtual_column_info() {}; - enum_vcol_info_type get_vcol_type() const - { - return vcol_type; - } - void set_vcol_type(enum_vcol_info_type v_type) - { - vcol_type= v_type; - } - const char *get_vcol_type_name() const - { - DBUG_ASSERT(vcol_type != VCOL_TYPE_NONE); - return vcol_type_name(vcol_type); - } - void set_handler(const Type_handler *handler) - { - /* Calling this function can only be done once. */ - DBUG_ASSERT(type_handler() == &type_handler_null); - Type_handler_hybrid_field_type::set_handler(handler); - } - bool is_stored() const - { - return stored_in_db; - } - void set_stored_in_db_flag(bool stored) - { - stored_in_db= stored; - } - bool is_in_partitioning_expr() const - { - return in_partitioning_expr; - } - void mark_as_in_partitioning_expr() - { - in_partitioning_expr= TRUE; - } - inline bool is_equal(const Virtual_column_info* vcol) const; - inline void print(String*); -}; - -class Binlog_type_info -{ -public: - enum binlog_sign_t - { - SIGN_SIGNED, - SIGN_UNSIGNED, - SIGN_NOT_APPLICABLE // for non-numeric types - }; - uchar m_type_code; // according to Field::binlog_type() - /** - Retrieve the field metadata for fields. - */ - uint16 m_metadata; - uint8 m_metadata_size; - binlog_sign_t m_signedness; - CHARSET_INFO *m_cs; // NULL if not relevant - TYPELIB *m_enum_typelib; // NULL if not relevant - TYPELIB *m_set_typelib; // NULL if not relevant - uchar m_geom_type; // Non-geometry fields can return 0 - Binlog_type_info(uchar type_code, - uint16 metadata, - uint8 metadata_size) - :m_type_code(type_code), - m_metadata(metadata), - m_metadata_size(metadata_size), - m_signedness(SIGN_NOT_APPLICABLE), - m_cs(NULL), - m_enum_typelib(NULL), - m_set_typelib(NULL), - m_geom_type(0) - {}; - Binlog_type_info(uchar type_code, uint16 metadata, - uint8 metadata_size, - binlog_sign_t signedness) - :m_type_code(type_code), - m_metadata(metadata), - m_metadata_size(metadata_size), - m_signedness(signedness), - m_cs(NULL), - m_enum_typelib(NULL), - m_set_typelib(NULL), - m_geom_type(0) - {}; - Binlog_type_info(uchar type_code, uint16 metadata, - uint8 metadata_size, - CHARSET_INFO *cs) - :m_type_code(type_code), - m_metadata(metadata), - m_metadata_size(metadata_size), - m_signedness(SIGN_NOT_APPLICABLE), - m_cs(cs), - m_enum_typelib(NULL), - m_set_typelib(NULL), - m_geom_type(0) - {}; - Binlog_type_info(uchar type_code, uint16 metadata, - uint8 metadata_size, - CHARSET_INFO *cs, - TYPELIB *t_enum, TYPELIB *t_set) - :m_type_code(type_code), - m_metadata(metadata), - m_metadata_size(metadata_size), - m_signedness(SIGN_NOT_APPLICABLE), - m_cs(cs), - m_enum_typelib(t_enum), - m_set_typelib(t_set), - m_geom_type(0) - {}; - Binlog_type_info(uchar type_code, uint16 metadata, - uint8 metadata_size, CHARSET_INFO *cs, - uchar geom_type) - :m_type_code(type_code), - m_metadata(metadata), - m_metadata_size(metadata_size), - m_signedness(SIGN_NOT_APPLICABLE), - m_cs(cs), - m_enum_typelib(NULL), - m_set_typelib(NULL), - m_geom_type(geom_type) - {}; - static void *operator new(size_t size, MEM_ROOT *mem_root) throw () - { return alloc_root(mem_root, size); } -}; - - -class Binlog_type_info_fixed_string: public Binlog_type_info -{ -public: - Binlog_type_info_fixed_string(uchar type_code, - uint32 octet_length, - CHARSET_INFO *cs); -}; - - -class Field: public Value_source -{ - Field(const Item &); /* Prevent use of these */ - void operator=(Field &); -protected: - int save_in_field_str(Field *to) - { - StringBuffer result(charset()); - val_str(&result); - return to->store(result.ptr(), result.length(), charset()); - } - void error_generated_column_function_is_not_allowed(THD *thd, bool error) - const; - static void do_field_eq(Copy_field *copy); - static void do_field_int(Copy_field *copy); - static void do_field_real(Copy_field *copy); - static void do_field_string(Copy_field *copy); - static void do_field_date(Copy_field *copy); - static void do_field_temporal(Copy_field *copy, date_mode_t fuzzydate); - static void do_field_datetime(Copy_field *copy); - static void do_field_timestamp(Copy_field *copy); - static void do_field_decimal(Copy_field *copy); -public: - static void *operator new(size_t size, MEM_ROOT *mem_root) throw () - { return alloc_root(mem_root, size); } - static void *operator new(size_t size) throw () - { - DBUG_ASSERT(size < UINT_MAX32); - return thd_alloc(current_thd, (uint) size); - } - static void operator delete(void *ptr_arg, size_t size) { TRASH_FREE(ptr_arg, size); } - static void operator delete(void *ptr, MEM_ROOT *mem_root) - { DBUG_ASSERT(0); } - - bool marked_for_read() const; - bool marked_for_write_or_computed() const; - - /** - Used by System Versioning. - */ - virtual void set_max() - { DBUG_ASSERT(0); } - virtual bool is_max() - { DBUG_ASSERT(0); return false; } - - uchar *ptr; // Position to field in record - - field_visibility_t invisible; - /** - Byte where the @c NULL bit is stored inside a record. If this Field is a - @c NOT @c NULL field, this member is @c NULL. - */ - uchar *null_ptr; - /* - Note that you can use table->in_use as replacement for current_thd member - only inside of val_*() and store() members (e.g. you can't use it in cons) - */ - TABLE *table; // Pointer for table - TABLE *orig_table; // Pointer to original table - const char * const *table_name; // Pointer to alias in TABLE - LEX_CSTRING field_name; - LEX_CSTRING comment; - /** reference to the list of options or NULL */ - engine_option_value *option_list; - ha_field_option_struct *option_struct; /* structure with parsed options */ - /* Field is part of the following keys */ - key_map key_start, part_of_key, part_of_key_not_clustered; - - /* - Bitmap of indexes that have records ordered by col1, ... this_field, ... - - For example, INDEX (col(prefix_n)) is not present in col.part_of_sortkey. - */ - key_map part_of_sortkey; - /* - We use three additional unireg types for TIMESTAMP to overcome limitation - of current binary format of .frm file. We'd like to be able to support - NOW() as default and on update value for such fields but unable to hold - this info anywhere except unireg_check field. This issue will be resolved - in more clean way with transition to new text based .frm format. - See also comment for Field_timestamp::Field_timestamp(). - */ - enum utype { - NONE=0, - NEXT_NUMBER=15, // AUTO_INCREMENT - TIMESTAMP_OLD_FIELD=18, // TIMESTAMP created before 4.1.3 - TIMESTAMP_DN_FIELD=21, // TIMESTAMP DEFAULT NOW() - TIMESTAMP_UN_FIELD=22, // TIMESTAMP ON UPDATE NOW() - TIMESTAMP_DNUN_FIELD=23, // TIMESTAMP DEFAULT NOW() ON UPDATE NOW() - TMYSQL_COMPRESSED= 24, // Compatibility with TMySQL - }; - enum imagetype { itRAW, itMBR}; - - utype unireg_check; - uint32 field_length; // Length of field - uint32 flags; - uint16 field_index; // field number in fields array - uchar null_bit; // Bit used to test null bit - /** - If true, this field was created in create_tmp_field_from_item from a NULL - value. This means that the type of the field is just a guess, and the type - may be freely coerced to another type. - - @see create_tmp_field_from_item - @see Item_type_holder::get_real_type - - */ - bool is_created_from_null_item; - - /* - Selectivity of the range condition over this field. - When calculating this selectivity a range predicate - is taken into account only if: - - it is extracted from the WHERE clause - - it depends only on the table the field belongs to - */ - double cond_selectivity; - - /* - The next field in the class of equal fields at the top AND level - of the WHERE clause - */ - Field *next_equal_field; - - /* - This structure is used for statistical data on the column - that has been read from the statistical table column_stat - */ - Column_statistics *read_stats; - /* - This structure is used for statistical data on the column that - is collected by the function collect_statistics_for_table - */ - Column_statistics_collected *collected_stats; - - /* - This is additional data provided for any computed(virtual) field, - default function or check constraint. - In particular it includes a pointer to the item by which this field - can be computed from other fields. - */ - Virtual_column_info *vcol_info, *check_constraint, *default_value; - - Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg, - uchar null_bit_arg, utype unireg_check_arg, - const LEX_CSTRING *field_name_arg); - virtual ~Field() {} - - virtual Type_numeric_attributes type_numeric_attributes() const - { - return Type_numeric_attributes(field_length, decimals(), is_unsigned()); - } - Type_std_attributes type_std_attributes() const - { - return Type_std_attributes(type_numeric_attributes(), dtcollation()); - } - - bool is_unsigned() const { return flags & UNSIGNED_FLAG; } - - /** - Convenience definition of a copy function returned by - Field::get_copy_func() - */ - typedef void Copy_func(Copy_field*); - virtual Copy_func *get_copy_func(const Field *from) const= 0; - virtual Copy_func *get_copy_func_to(const Field *to) const - { - return to->get_copy_func(this); - } - /* Store functions returns 1 on overflow and -1 on fatal error */ - virtual int store_field(Field *from) { return from->save_in_field(this); } - virtual int save_in_field(Field *to)= 0; - /** - Check if it is possible just copy the value - of the field 'from' to the field 'this', e.g. for - INSERT INTO t1 (field1) SELECT field2 FROM t2; - @param from - The field to copy from - @retval true - it is possible to just copy value of 'from' to 'this' - @retval false - conversion is needed - */ - virtual bool memcpy_field_possible(const Field *from) const= 0; - virtual bool make_empty_rec_store_default_value(THD *thd, Item *item); - virtual void make_empty_rec_reset(THD *thd) - { - reset(); - } - virtual int store(const char *to, size_t length,CHARSET_INFO *cs)=0; - /* - This is used by engines like CSV and Federated to signal the field - that the data is going to be in text (rather than binary) representation, - even if cs points to &my_charset_bin. - - If a Field distinguishes between text and binary formats (e.g. INET6), - we cannot call store(str,length,&my_charset_bin), - to avoid "field" mis-interpreting the data format as binary. - */ - virtual int store_text(const char *to, size_t length, CHARSET_INFO *cs) - { - return store(to, length, cs); - } - virtual int store_binary(const char *to, size_t length) - { - return store(to, length, &my_charset_bin); - } - virtual int store_hex_hybrid(const char *str, size_t length); - virtual int store(double nr)=0; - virtual int store(longlong nr, bool unsigned_val)=0; - virtual int store_decimal(const my_decimal *d)=0; - virtual int store_time_dec(const MYSQL_TIME *ltime, uint dec); - virtual int store_timestamp_dec(const timeval &ts, uint dec); - int store_timestamp(my_time_t timestamp, ulong sec_part) - { - return store_timestamp_dec(Timeval(timestamp, sec_part), - TIME_SECOND_PART_DIGITS); - } - /** - Store a value represented in native format - */ - virtual int store_native(const Native &value) - { - DBUG_ASSERT(0); - reset(); - return 0; - } - int store_time(const MYSQL_TIME *ltime) - { return store_time_dec(ltime, TIME_SECOND_PART_DIGITS); } - int store(const char *to, size_t length, CHARSET_INFO *cs, - enum_check_fields check_level); - int store_text(const char *to, size_t length, CHARSET_INFO *cs, - enum_check_fields check_level); - int store(const LEX_STRING *ls, CHARSET_INFO *cs) - { - DBUG_ASSERT(ls->length < UINT_MAX32); - return store(ls->str, (uint) ls->length, cs); - } - int store(const LEX_CSTRING *ls, CHARSET_INFO *cs) - { - DBUG_ASSERT(ls->length < UINT_MAX32); - return store(ls->str, (uint) ls->length, cs); - } - int store(const LEX_CSTRING &ls, CHARSET_INFO *cs) - { - DBUG_ASSERT(ls.length < UINT_MAX32); - return store(ls.str, (uint) ls.length, cs); - } - - /* - @brief - Store minimum/maximum value of a column in the statistics table. - @param - field statistical table field - str value buffer - */ - virtual int store_to_statistical_minmax_field(Field *field, String *str); - - /* - @brief - Store minimum/maximum value of a column from the statistical table. - @param - field statistical table field - str value buffer - */ - virtual int store_from_statistical_minmax_field(Field *field, String *str); - -#ifdef HAVE_valgrind - /** - Mark unused memory in the field as defined. Mainly used to ensure - that if we write full field to disk (for example in - Count_distinct_field::add(), we don't write unitalized data to - disk which would confuse valgrind or MSAN. - */ - virtual void mark_unused_memory_as_defined() {} -#else - void mark_unused_memory_as_defined() {} -#endif - - virtual double val_real()=0; - virtual longlong val_int()=0; - /* - Get ulonglong representation. - Negative values are truncated to 0. - */ - virtual ulonglong val_uint(void) - { - longlong nr= val_int(); - return nr < 0 ? 0 : (ulonglong) nr; - } - virtual bool val_bool()= 0; - virtual my_decimal *val_decimal(my_decimal *)=0; - inline String *val_str(String *str) { return val_str(str, str); } - /* - val_str(buf1, buf2) gets two buffers and should use them as follows: - if it needs a temp buffer to convert result to string - use buf1 - example Field_tiny::val_str() - if the value exists as a string already - use buf2 - example Field_string::val_str() - consequently, buf2 may be created as 'String buf;' - no memory - will be allocated for it. buf1 will be allocated to hold a - value if it's too small. Using allocated buffer for buf2 may result in - an unnecessary free (and later, may be an alloc). - This trickery is used to decrease a number of malloc calls. - */ - virtual String *val_str(String*,String *)=0; - virtual bool val_native(Native *to) - { - DBUG_ASSERT(!is_null()); - return to->copy((const char *) ptr, pack_length()); - } - String *val_int_as_str(String *val_buffer, bool unsigned_flag); - /* - Return the field value as a LEX_CSTRING, without padding to full length - (MODE_PAD_CHAR_TO_FULL_LENGTH is temporarily suppressed during the call). - - In case of an empty value, to[0] is assigned to empty_clex_string, - memory is not allocated. - In case of a non-empty value, the memory is allocated on mem_root. - In case of a memory allocation failure, to[0] is assigned to {NULL,0}. - - @param [IN] mem_root store non-empty values here - @param [OUT to return the string here - @retval false (success) - @retval true (EOM) - */ - bool val_str_nopad(MEM_ROOT *mem_root, LEX_CSTRING *to); - fast_field_copier get_fast_field_copier(const Field *from); - /* - str_needs_quotes() returns TRUE if the value returned by val_str() needs - to be quoted when used in constructing an SQL query. - */ - virtual bool str_needs_quotes() const { return false; } - const Type_handler *type_handler_for_comparison() const - { - return type_handler()->type_handler_for_comparison(); - } - Item_result result_type () const - { - return type_handler()->result_type(); - } - Item_result cmp_type () const - { - return type_handler()->cmp_type(); - } - virtual bool eq(Field *field) - { - return (ptr == field->ptr && null_ptr == field->null_ptr && - null_bit == field->null_bit && field->type() == type()); - } - virtual bool eq_def(const Field *field) const; - - /* - pack_length() returns size (in bytes) used to store field data in memory - (i.e. it returns the maximum size of the field in a row of the table, - which is located in RAM). - */ - virtual uint32 pack_length() const { return (uint32) field_length; } - - /* - pack_length_in_rec() returns size (in bytes) used to store field data on - storage (i.e. it returns the maximal size of the field in a row of the - table, which is located on disk). - */ - virtual uint32 pack_length_in_rec() const { return pack_length(); } - virtual bool compatible_field_size(uint metadata, const Relay_log_info *rli, - uint16 mflags, int *order) const; - virtual uint pack_length_from_metadata(uint field_metadata) const - { - DBUG_ENTER("Field::pack_length_from_metadata"); - DBUG_RETURN(field_metadata); - } - virtual uint row_pack_length() const { return 0; } - - /* - data_length() return the "real size" of the data in memory. - */ - virtual uint32 data_length() { return pack_length(); } - virtual uint32 sort_length() const { return pack_length(); } - - /* - sort_suffix_length() return the length bytes needed to store the length - for binary charset - */ - virtual uint32 sort_suffix_length() const { return 0; } - - /* - Get the number bytes occupied by the value in the field. - CHAR values are stripped of trailing spaces. - Flexible values are stripped of their length. - */ - virtual uint32 value_length() - { - uint len; - if (!zero_pack() && - (type() == MYSQL_TYPE_STRING && - (len= pack_length()) >= 4 && len < 256)) - { - uchar *str, *end; - for (str= ptr, end= str+len; end > str && end[-1] == ' '; end--) {} - len=(uint) (end-str); - return len; - } - return data_length(); - } - - /** - Get the maximum size of the data in packed format. - - @return Maximum data length of the field when packed using the - Field::pack() function. - */ - virtual uint32 max_data_length() const { - return pack_length(); - }; - - virtual int reset() { bzero(ptr,pack_length()); return 0; } - virtual void reset_fields() {} - const uchar *ptr_in_record(const uchar *record) const - { - my_ptrdiff_t l_offset= (my_ptrdiff_t) (record - table->record[0]); - return ptr + l_offset; - } - virtual int set_default(); - - bool has_update_default_function() const - { - return flags & ON_UPDATE_NOW_FLAG; - } - bool has_default_now_unireg_check() const - { - return unireg_check == TIMESTAMP_DN_FIELD - || unireg_check == TIMESTAMP_DNUN_FIELD; - } - - /* - Mark the field as having a value supplied by the client, thus it should - not be auto-updated. - */ - void set_has_explicit_value() - { - bitmap_set_bit(&table->has_value_set, field_index); - } - bool has_explicit_value() - { - return bitmap_is_set(&table->has_value_set, field_index); - } - void clear_has_explicit_value() - { - bitmap_clear_bit(&table->has_value_set, field_index); - } - - virtual my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const - { DBUG_ASSERT(0); return 0; } - my_time_t get_timestamp(ulong *sec_part) const - { - return get_timestamp(ptr, sec_part); - } - - virtual bool binary() const { return 1; } - virtual bool zero_pack() const { return 1; } - virtual enum ha_base_keytype key_type() const { return HA_KEYTYPE_BINARY; } - virtual uint16 key_part_flag() const { return 0; } - virtual uint16 key_part_length_bytes() const { return 0; } - virtual uint32 key_length() const { return pack_length(); } - virtual const Type_handler *type_handler() const= 0; - virtual enum_field_types type() const - { - return type_handler()->field_type(); - } - virtual enum_field_types real_type() const - { - return type_handler()->real_field_type(); - } - virtual enum_field_types binlog_type() const - { - /* - Binlog stores field->type() as type code by default. For example, - it puts MYSQL_TYPE_STRING in case of CHAR, VARCHAR, SET and ENUM, - with extra data type details put into metadata. - - Binlog behaviour slightly differs between various MySQL and MariaDB - versions for the temporal data types TIME, DATETIME and TIMESTAMP. - - MySQL prior to 5.6 uses MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME - and MYSQL_TYPE_TIMESTAMP type codes in binlog and stores no - additional metadata. - - MariaDB-5.3 implements new versions for TIME, DATATIME, TIMESTAMP - with fractional second precision, but uses the old format for the - types TIME(0), DATETIME(0), TIMESTAMP(0), and it still stores - MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME and MYSQL_TYPE_TIMESTAMP in binlog, - with no additional metadata. - So row-based replication between temporal data types of - different precision is not possible in MariaDB. - - MySQL-5.6 also implements a new version of TIME, DATETIME, TIMESTAMP - which support fractional second precision 0..6, and use the new - format even for the types TIME(0), DATETIME(0), TIMESTAMP(0). - For these new data types, MySQL-5.6 stores new type codes - MYSQL_TYPE_TIME2, MYSQL_TYPE_DATETIME2, MYSQL_TYPE_TIMESTAMP2 in binlog, - with fractional precision 0..6 put into metadata. - This makes it in theory possible to do row-based replication between - columns of different fractional precision (e.g. from TIME(1) on master - to TIME(6) on slave). However, it's not currently fully implemented yet. - MySQL-5.6 can only do row-based replication from the old types - TIME, DATETIME, TIMESTAMP (represented by MYSQL_TYPE_TIME, - MYSQL_TYPE_DATETIME and MYSQL_TYPE_TIMESTAMP type codes in binlog) - to the new corresponding types TIME(0), DATETIME(0), TIMESTAMP(0). - - Note: MariaDB starting from the version 10.0 understands the new - MySQL-5.6 type codes MYSQL_TYPE_TIME2, MYSQL_TYPE_DATETIME2, - MYSQL_TYPE_TIMESTAMP2. When started over MySQL-5.6 tables both on - master and on slave, MariaDB-10.0 can also do row-based replication - from the old types TIME, DATETIME, TIMESTAMP to the new MySQL-5.6 - types TIME(0), DATETIME(0), TIMESTAMP(0). - - Note: perhaps binlog should eventually be modified to store - real_type() instead of type() for all column types. - */ - return type(); - } - virtual Binlog_type_info binlog_type_info() const - { - DBUG_ASSERT(Field::type() == binlog_type()); - return Binlog_type_info(Field::type(), 0, 0); - } - virtual en_fieldtype tmp_engine_column_type(bool use_packed_rows) const - { - return FIELD_NORMAL; - } - /* - Conversion type for from the source to the current field. - */ - virtual enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) - const= 0; - enum_conv_type rpl_conv_type_from_same_data_type(uint16 metadata, - const Relay_log_info *rli, - const Conv_param ¶m) - const; - inline int cmp(const uchar *str) const { return cmp(ptr,str); } - /* - The following method is used for comparing prefix keys. - Currently it's only used in partitioning. - */ - virtual int cmp_prefix(const uchar *a, const uchar *b, - size_t prefix_len) const - { return cmp(a, b); } - virtual int cmp(const uchar *,const uchar *) const=0; - virtual int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const - { return memcmp(a,b,pack_length()); } - virtual int cmp_offset(my_ptrdiff_t row_offset) - { return cmp(ptr,ptr+row_offset); } - virtual int cmp_binary_offset(uint row_offset) - { return cmp_binary(ptr, ptr+row_offset); }; - virtual int key_cmp(const uchar *a,const uchar *b) const - { return cmp(a, b); } - virtual int key_cmp(const uchar *str, uint length) const - { return cmp(ptr,str); } - /* - Update the value m of the 'min_val' field with the current value v - of this field if force_update is set to TRUE or if v < m. - Return TRUE if the value has been updated. - */ - virtual bool update_min(Field *min_val, bool force_update) - { - bool update_fl= force_update || cmp(ptr, min_val->ptr) < 0; - if (update_fl) - { - min_val->set_notnull(); - memcpy(min_val->ptr, ptr, pack_length()); - } - return update_fl; - } - /* - Update the value m of the 'max_val' field with the current value v - of this field if force_update is set to TRUE or if v > m. - Return TRUE if the value has been updated. - */ - virtual bool update_max(Field *max_val, bool force_update) - { - bool update_fl= force_update || cmp(ptr, max_val->ptr) > 0; - if (update_fl) - { - max_val->set_notnull(); - memcpy(max_val->ptr, ptr, pack_length()); - } - return update_fl; - } - virtual void store_field_value(uchar *val, uint len) - { - memcpy(ptr, val, len); - } - virtual uint decimals() const { return 0; } - virtual Information_schema_numeric_attributes - information_schema_numeric_attributes() const - { - return Information_schema_numeric_attributes(); - } - virtual Information_schema_character_attributes - information_schema_character_attributes() const - { - return Information_schema_character_attributes(); - } - virtual void update_data_type_statistics(Data_type_statistics *st) const - { } - /* - Caller beware: sql_type can change str.Ptr, so check - ptr() to see if it changed if you are using your own buffer - in str and restore it with set() if needed - */ - virtual void sql_type(String &str) const =0; - virtual void sql_rpl_type(String *str) const { sql_type(*str); } - virtual uint size_of() const =0; // For new field - inline bool is_null(my_ptrdiff_t row_offset= 0) const - { - /* - The table may have been marked as containing only NULL values - for all fields if it is a NULL-complemented row of an OUTER JOIN - or if the query is an implicitly grouped query (has aggregate - functions but no GROUP BY clause) with no qualifying rows. If - this is the case (in which TABLE::null_row is true), the field - is considered to be NULL. - - Note that if a table->null_row is set then also all null_bits are - set for the row. - - In the case of the 'result_field' for GROUP BY, table->null_row might - refer to the *next* row in the table (when the algorithm is: read the - next row, see if any of group column values have changed, send the - result - grouped - row to the client if yes). So, table->null_row might - be wrong, but such a result_field is always nullable (that's defined by - original_field->maybe_null()) and we trust its null bit. - */ - return null_ptr ? null_ptr[row_offset] & null_bit : table->null_row; - } - inline bool is_real_null(my_ptrdiff_t row_offset= 0) const - { return null_ptr && (null_ptr[row_offset] & null_bit); } - inline bool is_null_in_record(const uchar *record) const - { - if (maybe_null_in_table()) - return record[(uint) (null_ptr - table->record[0])] & null_bit; - return 0; - } - inline void set_null(my_ptrdiff_t row_offset= 0) - { if (null_ptr) null_ptr[row_offset]|= null_bit; } - inline void set_notnull(my_ptrdiff_t row_offset= 0) - { if (null_ptr) null_ptr[row_offset]&= (uchar) ~null_bit; } - inline bool maybe_null(void) const - { return null_ptr != 0 || table->maybe_null; } - // Set to NULL on LOAD DATA or LOAD XML - virtual bool load_data_set_null(THD *thd); - // Reset when a LOAD DATA file ended unexpectedly - virtual bool load_data_set_no_data(THD *thd, bool fixed_format); - void load_data_set_value(const char *pos, uint length, CHARSET_INFO *cs); - - /* @return true if this field is NULL-able (even if temporarily) */ - inline bool real_maybe_null() const { return null_ptr != 0; } - uint null_offset(const uchar *record) const - { return (uint) (null_ptr - record); } - /* - For a NULL-able field (that can actually store a NULL value in a table) - null_ptr points to the "null bitmap" in the table->record[0] header. For - NOT NULL fields it is either 0 or points outside table->record[0] into the - table->triggers->extra_null_bitmap (so that the field can store a NULL - value temporarily, only in memory) - */ - bool maybe_null_in_table() const - { return null_ptr >= table->record[0] && null_ptr <= ptr; } - - uint null_offset() const - { return null_offset(table->record[0]); } - void set_null_ptr(uchar *p_null_ptr, uint p_null_bit) - { - null_ptr= p_null_ptr; - null_bit= static_cast(p_null_bit); - } - - bool stored_in_db() const { return !vcol_info || vcol_info->stored_in_db; } - bool check_vcol_sql_mode_dependency(THD *, vcol_init_mode mode) const; - - virtual sql_mode_t value_depends_on_sql_mode() const - { - return 0; - } - virtual sql_mode_t conversion_depends_on_sql_mode(THD *thd, - Item *expr) const - { - return (sql_mode_t) 0; - } - virtual sql_mode_t can_handle_sql_mode_dependency_on_store() const - { - return 0; - } - - inline THD *get_thd() const - { return likely(table) ? table->in_use : current_thd; } - - enum { - LAST_NULL_BYTE_UNDEF= 0 - }; - - /* - Find the position of the last null byte for the field. - - SYNOPSIS - last_null_byte() - - DESCRIPTION - Return a pointer to the last byte of the null bytes where the - field conceptually is placed. - - RETURN VALUE - The position of the last null byte relative to the beginning of - the record. If the field does not use any bits of the null - bytes, the value 0 (LAST_NULL_BYTE_UNDEF) is returned. - */ - size_t last_null_byte() const { - size_t bytes= do_last_null_byte(); - DBUG_PRINT("debug", ("last_null_byte() ==> %ld", (long) bytes)); - DBUG_ASSERT(bytes <= table->s->null_bytes); - return bytes; - } - - /* - Create mem-comparable sort key part for a sort key - */ - void make_sort_key_part(uchar *buff, uint length); - - /* - create a compact sort key which can be compared with a comparison - function. They are called packed sort keys - */ - virtual uint make_packed_sort_key_part(uchar *buff, - const SORT_FIELD_ATTR *sort_field); - - virtual void make_send_field(Send_field *); - - /* - Some implementations actually may write up to 8 bytes regardless of what - size was requested. This is due to the minimum value of the system variable - max_sort_length. - */ - - virtual void sort_string(uchar *buff,uint length)=0; - virtual bool optimize_range(uint idx, uint part) const; - virtual void free() {} - virtual Field *make_new_field(MEM_ROOT *root, TABLE *new_table, - bool keep_type); - virtual Field *new_key_field(MEM_ROOT *root, TABLE *new_table, - uchar *new_ptr, uint32 length, - uchar *new_null_ptr, uint new_null_bit); - Field *create_tmp_field(MEM_ROOT *root, TABLE *new_table, - bool maybe_null_arg); - Field *create_tmp_field(MEM_ROOT *root, TABLE *new_table) - { - return create_tmp_field(root, new_table, maybe_null()); - } - Field *clone(MEM_ROOT *mem_root, TABLE *new_table); - Field *clone(MEM_ROOT *mem_root, TABLE *new_table, my_ptrdiff_t diff); - inline void move_field(uchar *ptr_arg,uchar *null_ptr_arg,uchar null_bit_arg) - { - ptr=ptr_arg; null_ptr=null_ptr_arg; null_bit=null_bit_arg; - } - inline void move_field(uchar *ptr_arg) { ptr=ptr_arg; } - inline uchar *record_ptr() // record[0] or wherever the field was moved to - { - my_ptrdiff_t offset= table->s->field[field_index]->ptr - table->s->default_values; - return ptr - offset; - } - virtual void move_field_offset(my_ptrdiff_t ptr_diff) - { - ptr=ADD_TO_PTR(ptr,ptr_diff, uchar*); - if (null_ptr) - null_ptr=ADD_TO_PTR(null_ptr,ptr_diff,uchar*); - } - void get_image(uchar *buff, uint length, CHARSET_INFO *cs) const - { get_image(buff, length, ptr, cs); } - virtual void get_image(uchar *buff, uint length, - const uchar *ptr_arg, CHARSET_INFO *cs) const - { memcpy(buff,ptr_arg,length); } - virtual void set_image(const uchar *buff,uint length, CHARSET_INFO *cs) - { memcpy(ptr,buff,length); } - - - /* - Copy a field part into an output buffer. - - SYNOPSIS - Field::get_key_image() - buff [out] output buffer - length output buffer size - type itMBR for geometry blobs, otherwise itRAW - - DESCRIPTION - This function makes a copy of field part of size equal to or - less than "length" parameter value. - For fields of string types (CHAR, VARCHAR, TEXT) the rest of buffer - is padded by zero byte. - - NOTES - For variable length character fields (i.e. UTF-8) the "length" - parameter means a number of output buffer bytes as if all field - characters have maximal possible size (mbmaxlen). In the other words, - "length" parameter is a number of characters multiplied by - field_charset->mbmaxlen. - - RETURN - Number of copied bytes (excluding padded zero bytes -- see above). - */ - - uint get_key_image(uchar *buff, uint length, imagetype type_arg) const - { return get_key_image(buff, length, ptr, type_arg); } - virtual uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type_arg) const - { - get_image(buff, length, ptr_arg, &my_charset_bin); - return length; - } - virtual void set_key_image(const uchar *buff,uint length) - { set_image(buff,length, &my_charset_bin); } - inline longlong val_int_offset(uint row_offset) - { - ptr+=row_offset; - longlong tmp=val_int(); - ptr-=row_offset; - return tmp; - } - inline longlong val_int(const uchar *new_ptr) - { - uchar *old_ptr= ptr; - longlong return_value; - ptr= (uchar*) new_ptr; - return_value= val_int(); - ptr= old_ptr; - return return_value; - } - inline String *val_str(String *str, const uchar *new_ptr) - { - uchar *old_ptr= ptr; - ptr= (uchar*) new_ptr; - val_str(str); - ptr= old_ptr; - return str; - } - virtual bool send(Protocol *protocol); - - virtual uchar *pack(uchar *to, const uchar *from, uint max_length); - /** - @overload Field::pack(uchar*, const uchar*, uint, bool) - */ - uchar *pack(uchar *to, const uchar *from) - { - DBUG_ENTER("Field::pack"); - uchar *result= this->pack(to, from, UINT_MAX); - DBUG_RETURN(result); - } - - virtual const uchar *unpack(uchar* to, const uchar *from, - const uchar *from_end, uint param_data=0); - - virtual uint packed_col_length(const uchar *to, uint length) - { return length;} - virtual uint max_packed_col_length(uint max_length) - { return max_length;} - virtual bool is_packable() const { return false; } - - uint offset(const uchar *record) const - { - return (uint) (ptr - record); - } - void copy_from_tmp(int offset); - uint fill_cache_field(struct st_cache_field *copy); - virtual bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate); - virtual longlong val_datetime_packed(THD *thd); - virtual longlong val_time_packed(THD *thd); - virtual const TYPELIB *get_typelib() const { return NULL; } - virtual CHARSET_INFO *charset() const= 0; - virtual const DTCollation &dtcollation() const= 0; - virtual CHARSET_INFO *charset_for_protocol(void) const - { return binary() ? &my_charset_bin : charset(); } - virtual CHARSET_INFO *sort_charset(void) const { return charset(); } - virtual bool has_charset(void) const { return FALSE; } - virtual int set_time() { return 1; } - bool set_warning(Sql_condition::enum_warning_level, unsigned int code, - int cuted_increment, ulong current_row=0) const; - virtual void print_key_value(String *out, uint32 length); - void print_key_part_value(String *out, const uchar *key, uint32 length); - void print_key_value_binary(String *out, const uchar* key, uint32 length); -protected: - bool set_warning(unsigned int code, int cuted_increment) const - { - return set_warning(Sql_condition::WARN_LEVEL_WARN, code, cuted_increment); - } - bool set_note(unsigned int code, int cuted_increment) const - { - return set_warning(Sql_condition::WARN_LEVEL_NOTE, code, cuted_increment); - } - void set_datetime_warning(Sql_condition::enum_warning_level, uint code, - const ErrConv *str, const char *typestr, - int cuted_increment) const; - void set_datetime_warning(uint code, - const ErrConv *str, const char *typestr, - int cuted_increment) const - { - set_datetime_warning(Sql_condition::WARN_LEVEL_WARN, code, str, typestr, - cuted_increment); - } - void set_warning_truncated_wrong_value(const char *type, const char *value); - inline bool check_overflow(int op_result) - { - return (op_result == E_DEC_OVERFLOW); - } - int warn_if_overflow(int op_result); - Copy_func *get_identical_copy_func() const; - bool can_optimize_scalar_range(const RANGE_OPT_PARAM *param, - const KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, - const Item *value) const; - uchar *make_key_image(MEM_ROOT *mem_root, const KEY_PART *key_part); - SEL_ARG *get_mm_leaf_int(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value, - bool unsigned_field); - /* - Make a leaf tree for the cases when the value was stored - to the field exactly, without any truncation, rounding or adjustments. - For example, if we stored an INT value into an INT column, - and value->save_in_field_no_warnings() returned 0, - we know that the value was stored exactly. - */ - SEL_ARG *stored_field_make_mm_leaf_exact(RANGE_OPT_PARAM *param, - KEY_PART *key_part, - scalar_comparison_op op, - Item *value); - /* - Make a leaf tree for the cases when we don't know if - the value was stored to the field without any data loss, - or was modified to a smaller or a greater value. - Used for the data types whose methods Field::store*() - silently adjust the value. This is the most typical case. - */ - SEL_ARG *stored_field_make_mm_leaf(RANGE_OPT_PARAM *param, - KEY_PART *key_part, - scalar_comparison_op op, Item *value); - /* - Make a leaf tree when an INT value was stored into a field of INT type, - and some truncation happened. Tries to adjust the range search condition - when possible, e.g. "tinytint < 300" -> "tinyint <= 127". - Can also return SEL_ARG_IMPOSSIBLE(), and NULL (not sargable). - */ - SEL_ARG *stored_field_make_mm_leaf_bounded_int(RANGE_OPT_PARAM *param, - KEY_PART *key_part, - scalar_comparison_op op, - Item *value, - bool unsigned_field); - /* - Make a leaf tree when some truncation happened during - value->save_in_field_no_warning(this), and we cannot yet adjust the range - search condition for the current combination of the field and the value - data types. - Returns SEL_ARG_IMPOSSIBLE() for "=" and "<=>". - Returns NULL (not sargable) for other comparison operations. - */ - SEL_ARG *stored_field_make_mm_leaf_truncated(RANGE_OPT_PARAM *prm, - scalar_comparison_op, - Item *value); -public: - void set_table_name(String *alias) - { - table_name= &alias->Ptr; - } - void init(TABLE *table_arg) - { - orig_table= table= table_arg; - set_table_name(&table_arg->alias); - } - virtual void init_for_tmp_table(Field *org_field, TABLE *new_table) - { - init(new_table); - orig_table= org_field->orig_table; - vcol_info= 0; - cond_selectivity= 1.0; - next_equal_field= NULL; - option_list= NULL; - option_struct= NULL; - if (org_field->type() == MYSQL_TYPE_VAR_STRING || - org_field->type() == MYSQL_TYPE_VARCHAR) - new_table->s->db_create_options|= HA_OPTION_PACK_RECORD; - } - void init_for_make_new_field(TABLE *new_table_arg, TABLE *orig_table_arg) - { - init(new_table_arg); - /* - Normally orig_table is different from table only if field was - created via ::make_new_field. Here we alter the type of field, - so ::make_new_field is not applicable. But we still need to - preserve the original field metadata for the client-server - protocol. - */ - orig_table= orig_table_arg; - } - - /* maximum possible display length */ - virtual uint32 max_display_length() const= 0; - /** - Whether a field being created has the samle type. - Used by the ALTER TABLE - */ - virtual bool is_equal(const Column_definition &new_field) const= 0; - // Used as double dispatch pattern: calls virtual method of handler - virtual bool - can_be_converted_by_engine(const Column_definition &new_type) const - { - return false; - } - /* convert decimal to longlong with overflow check */ - longlong convert_decimal2longlong(const my_decimal *val, bool unsigned_flag, - int *err); - /* - Maximum number of bytes in character representation. - - For string types it is equal to the field capacity, in bytes. - - For non-string types it represents the longest possible string length - after conversion to string. - */ - virtual uint32 character_octet_length() const - { - return field_length; - } - /* The max. number of characters */ - virtual uint32 char_length() const - { - return field_length / charset()->mbmaxlen; - } - - ha_storage_media field_storage_type() const - { - return (ha_storage_media) - ((flags >> FIELD_FLAGS_STORAGE_MEDIA) & 3); - } - - void set_storage_type(ha_storage_media storage_type_arg) - { - DBUG_ASSERT(field_storage_type() == HA_SM_DEFAULT); - flags |= static_cast(storage_type_arg) << - FIELD_FLAGS_STORAGE_MEDIA; - } - - column_format_type column_format() const - { - return (column_format_type) - ((flags >> FIELD_FLAGS_COLUMN_FORMAT) & 3); - } - - void set_column_format(column_format_type column_format_arg) - { - DBUG_ASSERT(column_format() == COLUMN_FORMAT_TYPE_DEFAULT); - flags |= static_cast(column_format_arg) << - FIELD_FLAGS_COLUMN_FORMAT; - } - - bool vers_sys_field() const - { - return flags & (VERS_SYS_START_FLAG | VERS_SYS_END_FLAG); - } - - bool vers_update_unversioned() const - { - return flags & VERS_UPDATE_UNVERSIONED_FLAG; - } - - /* - Validate a non-null field value stored in the given record - according to the current thread settings, e.g. sql_mode. - @param thd - the thread - @param record - the record to check in - */ - virtual bool validate_value_in_record(THD *thd, const uchar *record) const - { return false; } - bool validate_value_in_record_with_warn(THD *thd, const uchar *record); - key_map get_possible_keys(); - - /* Hash value */ - virtual void hash(ulong *nr, ulong *nr2); - - /** - Get the upper limit of the MySQL integral and floating-point type. - - @return maximum allowed value for the field - */ - virtual ulonglong get_max_int_value() const - { - DBUG_ASSERT(false); - return 0ULL; - } - -/** - Checks whether a string field is part of write_set. - - @return - FALSE - If field is not char/varchar/.... - - If field is char/varchar/.. and is not part of write set. - TRUE - If field is char/varchar/.. and is part of write set. -*/ - virtual bool is_varchar_and_in_write_set() const { return FALSE; } - - /* Check whether the field can be used as a join attribute in hash join */ - virtual bool hash_join_is_possible() { return TRUE; } - virtual bool eq_cmp_as_binary() { return TRUE; } - - /* Position of the field value within the interval of [min, max] */ - virtual double pos_in_interval(Field *min, Field *max) - { - return (double) 0.5; - } - - /* - Check if comparison between the field and an item unambiguously - identifies a distinct field value. - - Example1: SELECT * FROM t1 WHERE int_column=10; - This example returns distinct integer value of 10. - - Example2: SELECT * FROM t1 WHERE varchar_column=DATE'2001-01-01' - This example returns non-distinct values. - Comparison as DATE will return '2001-01-01' and '2001-01-01x', - but these two values are not equal to each other as VARCHARs. - See also the function with the same name in sql_select.cc. - */ - virtual bool test_if_equality_guarantees_uniqueness(const Item *const_item) - const; - virtual bool can_be_substituted_to_equal_item(const Context &ctx, - const Item_equal *item); - virtual Item *get_equal_const_item(THD *thd, const Context &ctx, - Item *const_item) - { - return const_item; - } - virtual bool can_optimize_keypart_ref(const Item_bool_func *cond, - const Item *item) const; - virtual bool can_optimize_hash_join(const Item_bool_func *cond, - const Item *item) const - { - return can_optimize_keypart_ref(cond, item); - } - virtual bool can_optimize_group_min_max(const Item_bool_func *cond, - const Item *const_item) const; - /** - Test if Field can use range optimizer for a standard comparison operation: - <=, <, =, <=>, >, >= - Note, this method does not cover spatial operations. - */ - virtual bool can_optimize_range(const Item_bool_func *cond, - const Item *item, - bool is_eq_func) const; - - virtual SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value)= 0; - - bool can_optimize_outer_join_table_elimination(const Item_bool_func *cond, - const Item *item) const - { - // Exactly the same rules with REF access - return can_optimize_keypart_ref(cond, item); - } - - bool save_in_field_default_value(bool view_eror_processing); - bool save_in_field_ignore_value(bool view_error_processing); - - /* Mark field in read map. Updates also virtual fields */ - void register_field_in_read_map(); - - virtual Compression_method *compression_method() const { return 0; } - - virtual Virtual_tmp_table **virtual_tmp_table_addr() - { - return NULL; - } - virtual bool sp_prepare_and_store_item(THD *thd, Item **value); - - friend int cre_myisam(char * name, TABLE *form, uint options, - ulonglong auto_increment_value); - friend class Copy_field; - friend class Item_avg_field; - friend class Item_std_field; - friend class Item_sum_num; - friend class Item_sum_sum; - friend class Item_sum_count; - friend class Item_sum_avg; - friend class Item_sum_std; - friend class Item_sum_min; - friend class Item_sum_max; - friend class Item_func_group_concat; - -private: - /* - Primitive for implementing last_null_byte(). - - SYNOPSIS - do_last_null_byte() - - DESCRIPTION - Primitive for the implementation of the last_null_byte() - function. This represents the inheritance interface and can be - overridden by subclasses. - */ - virtual size_t do_last_null_byte() const; - -protected: - uchar *pack_int(uchar *to, const uchar *from, size_t size) - { - memcpy(to, from, size); - return to + size; - } - - const uchar *unpack_int(uchar* to, const uchar *from, - const uchar *from_end, size_t size) - { - if (from + size > from_end) - return 0; - memcpy(to, from, size); - return from + size; - } - - uchar *pack_int16(uchar *to, const uchar *from) - { return pack_int(to, from, 2); } - const uchar *unpack_int16(uchar* to, const uchar *from, const uchar *from_end) - { return unpack_int(to, from, from_end, 2); } - uchar *pack_int24(uchar *to, const uchar *from) - { return pack_int(to, from, 3); } - const uchar *unpack_int24(uchar* to, const uchar *from, const uchar *from_end) - { return unpack_int(to, from, from_end, 3); } - uchar *pack_int32(uchar *to, const uchar *from) - { return pack_int(to, from, 4); } - const uchar *unpack_int32(uchar* to, const uchar *from, const uchar *from_end) - { return unpack_int(to, from, from_end, 4); } - uchar *pack_int64(uchar* to, const uchar *from) - { return pack_int(to, from, 8); } - const uchar *unpack_int64(uchar* to, const uchar *from, const uchar *from_end) - { return unpack_int(to, from, from_end, 8); } - - double pos_in_interval_val_real(Field *min, Field *max); - double pos_in_interval_val_str(Field *min, Field *max, uint data_offset); -}; - - -class Field_num :public Field { -protected: - int check_edom_and_important_data_truncation(const char *type, bool edom, - CHARSET_INFO *cs, - const char *str, size_t length, - const char *end_of_num); - int check_edom_and_truncation(const char *type, bool edom, - CHARSET_INFO *cs, - const char *str, size_t length, - const char *end_of_num); - int check_int(CHARSET_INFO *cs, const char *str, size_t length, - const char *int_end, int error) - { - return check_edom_and_truncation("integer", - error == MY_ERRNO_EDOM || str == int_end, - cs, str, length, int_end); - } - bool get_int(CHARSET_INFO *cs, const char *from, size_t len, - longlong *rnd, ulonglong unsigned_max, - longlong signed_min, longlong signed_max); - void prepend_zeros(String *value) const; - Item *get_equal_zerofill_const_item(THD *thd, const Context &ctx, - Item *const_item); - Binlog_type_info::binlog_sign_t binlog_signedness() const - { - return (flags & UNSIGNED_FLAG) ? Binlog_type_info::SIGN_UNSIGNED : - Binlog_type_info::SIGN_SIGNED; - } - bool send_numeric_zerofill_str(Protocol_text *protocol, - protocol_send_type_t send_type); - -public: - const uint8 dec; - bool zerofill,unsigned_flag; // Purify cannot handle bit fields - Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - uint8 dec_arg, bool zero_arg, bool unsigned_arg); - CHARSET_INFO *charset() const override - { - return DTCollation_numeric::singleton().collation; - } - const DTCollation &dtcollation() const override - { - return DTCollation_numeric::singleton(); - } - sql_mode_t can_handle_sql_mode_dependency_on_store() const override; - Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) - override - { - return (flags & ZEROFILL_FLAG) ? - get_equal_zerofill_const_item(thd, ctx, const_item) : - const_item; - } - void add_zerofill_and_unsigned(String &res) const; - friend class Create_field; - void make_send_field(Send_field *) override; - uint decimals() const override { return (uint) dec; } - uint size_of() const override { return sizeof(*this); } - bool eq_def(const Field *field) const override; - Copy_func *get_copy_func(const Field *from) const override - { - if (unsigned_flag && from->cmp_type() == DECIMAL_RESULT) - return do_field_decimal; - return do_field_int; - } - int save_in_field(Field *to) override - { - return to->store(val_int(), MY_TEST(flags & UNSIGNED_FLAG)); - } - bool is_equal(const Column_definition &new_field) const override; - uint row_pack_length() const override { return pack_length(); } - uint32 pack_length_from_metadata(uint field_metadata) const override - { - uint32 length= pack_length(); - DBUG_PRINT("result", ("pack_length_from_metadata(%d): %u", - field_metadata, length)); - return length; - } - double pos_in_interval(Field *min, Field *max) override - { - return pos_in_interval_val_real(min, max); - } - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value) override; - Binlog_type_info binlog_type_info() const override - { - DBUG_ASSERT(Field_num::type() == binlog_type()); - return Binlog_type_info(Field_num::type(), 0, 0, binlog_signedness()); - } -}; - - -class Field_str :public Field { -protected: - DTCollation m_collation; - // A short alias for m_collation.collation with non-virtual linkage - const CHARSET_INFO *field_charset() const { return m_collation.collation; } - uint mbmaxlen() const { return m_collation.collation->mbmaxlen; } -public: - bool can_be_substituted_to_equal_item(const Context &ctx, - const Item_equal *item_equal) override; - Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - const DTCollation &collation); - uint decimals() const override { return NOT_FIXED_DEC; } - int save_in_field(Field *to) override { return save_in_field_str(to); } - bool memcpy_field_possible(const Field *from) const override - { - return real_type() == from->real_type() && - pack_length() == from->pack_length() && - charset() == from->charset(); - } - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_decimal(const my_decimal *) override; - int store(const char *to,size_t length,CHARSET_INFO *cs) override=0; - int store_hex_hybrid(const char *str, size_t length) override - { - return store(str, length, &my_charset_bin); - } - CHARSET_INFO *charset() const override { return m_collation.collation; } - const DTCollation &dtcollation() const override - { - return m_collation; - } - bool binary() const override { return field_charset() == &my_charset_bin; } - uint32 max_display_length() const override { return field_length; } - uint32 character_octet_length() const override { return field_length; } - uint32 char_length() const override - { - return field_length / mbmaxlen(); - } - Information_schema_character_attributes - information_schema_character_attributes() const override - { - return Information_schema_character_attributes(max_display_length(), - char_length()); - } - friend class Create_field; - my_decimal *val_decimal(my_decimal *) override; - bool val_bool() override { return val_real() != 0e0; } - bool str_needs_quotes() const override { return true; } - bool eq_cmp_as_binary() override { return MY_TEST(flags & BINARY_FLAG); } - virtual uint length_size() const { return 0; } - double pos_in_interval(Field *min, Field *max) override - { - return pos_in_interval_val_str(min, max, length_size()); - } - bool test_if_equality_guarantees_uniqueness(const Item *const_item) const - override; - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value) override; - Binlog_type_info binlog_type_info() const override - { - DBUG_ASSERT(Field_str::type() == binlog_type()); - return Binlog_type_info(Field_str::type(), 0, 0, charset()); - } -}; - -/* base class for Field_string, Field_varstring and Field_blob */ - -class Field_longstr :public Field_str -{ -protected: - int report_if_important_data(const char *ptr, const char *end, - bool count_spaces); - bool check_string_copy_error(const String_copier *copier, - const char *end, CHARSET_INFO *cs); - int check_conversion_status(const String_copier *copier, - const char *end, CHARSET_INFO *cs, - bool count_spaces) - { - if (check_string_copy_error(copier, end, cs)) - return 2; - return report_if_important_data(copier->source_end_pos(), - end, count_spaces); - } - int well_formed_copy_with_check(char *to, size_t to_length, - CHARSET_INFO *from_cs, - const char *from, size_t from_length, - size_t nchars, bool count_spaces, - uint *copy_length) - { - String_copier copier; - - *copy_length= copier.well_formed_copy(field_charset(), to, to_length, - from_cs, from, from_length, - nchars); - - return check_conversion_status(&copier, from + from_length, from_cs, count_spaces); - } - bool cmp_to_string_with_same_collation(const Item_bool_func *cond, - const Item *item) const; - bool cmp_to_string_with_stricter_collation(const Item_bool_func *cond, - const Item *item) const; - int compress(char *to, uint to_length, - const char *from, uint length, - uint max_length, - uint *out_length, - CHARSET_INFO *cs, size_t nchars); - String *uncompress(String *val_buffer, String *val_ptr, - const uchar *from, uint from_length) const; -public: - Field_longstr(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - const DTCollation &collation) - :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, - field_name_arg, collation) - {} - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - int store_decimal(const my_decimal *d) override; - uint32 max_data_length() const override; - void make_send_field(Send_field *) override; - bool send(Protocol *protocol) override; - - bool is_varchar_and_in_write_set() const override - { - DBUG_ASSERT(table && table->write_set); - return bitmap_is_set(table->write_set, field_index); - } - bool match_collation_to_optimize_range() const { return true; } - - bool can_optimize_keypart_ref(const Item_bool_func *cond, - const Item *item) const override; - bool can_optimize_hash_join(const Item_bool_func *cond, - const Item *item) const override; - bool can_optimize_group_min_max(const Item_bool_func *cond, - const Item *const_item) const override; - bool can_optimize_range(const Item_bool_func *cond, - const Item *item, - bool is_eq_func) const override; - bool is_packable() const override { return true; } - uint make_packed_sort_key_part(uchar *buff, - const SORT_FIELD_ATTR *sort_field)override; - uchar* pack_sort_string(uchar *to, const SORT_FIELD_ATTR *sort_field); -}; - -/* base class for float and double and decimal (old one) */ -class Field_real :public Field_num { -protected: - double get_double(const char *str, size_t length, CHARSET_INFO *cs, int *err); -public: - bool not_fixed; - - Field_real(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - uint8 dec_arg, bool zero_arg, bool unsigned_arg) - :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, - field_name_arg, dec_arg, zero_arg, unsigned_arg), - not_fixed(dec_arg >= FLOATING_POINT_DECIMALS) - {} - Copy_func *get_copy_func(const Field *from) const override - { - return do_field_real; - } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - Information_schema_numeric_attributes - information_schema_numeric_attributes() const override - { - return dec == NOT_FIXED_DEC ? - Information_schema_numeric_attributes(field_length) : - Information_schema_numeric_attributes(field_length, dec); - } - void sql_type(String &str) const override; - int save_in_field(Field *to) override { return to->store(val_real()); } - bool memcpy_field_possible(const Field *from) const override - { - /* - Cannot do memcpy from a longer field to a shorter field, - e.g. a DOUBLE(53,10) into a DOUBLE(10,10). - But it should be OK the other way around. - */ - return real_type() == from->real_type() && - pack_length() == from->pack_length() && - is_unsigned() <= from->is_unsigned() && - decimals() == from->decimals() && - field_length >= from->field_length; - } - int store_decimal(const my_decimal *dec) override - { return store(dec->to_double()); } - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; - my_decimal *val_decimal(my_decimal *) override; - bool val_bool() override { return val_real() != 0e0; } - uint32 max_display_length() const override { return field_length; } - uint size_of() const override { return sizeof *this; } - Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) - override; -}; - - -class Field_decimal final :public Field_real { -public: - Field_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - uint8 dec_arg,bool zero_arg,bool unsigned_arg) - :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, - dec_arg, zero_arg, unsigned_arg) - {} - Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) - override; - const Type_handler *type_handler() const override - { return &type_handler_olddecimal; } - enum ha_base_keytype key_type() const override - { return zerofill ? HA_KEYTYPE_BINARY : HA_KEYTYPE_NUM; } - Information_schema_numeric_attributes - information_schema_numeric_attributes() const override - { - uint tmp= dec ? 2 : 1; // The sign and the decimal point - return Information_schema_numeric_attributes(field_length - tmp, dec); - } - Copy_func *get_copy_func(const Field *from) const override - { - return eq_def(from) ? get_identical_copy_func() : do_field_string; - } - int reset() override; - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - void overflow(bool negative); - bool zero_pack() const override { return false; } - void sql_type(String &str) const override; - uchar *pack(uchar* to, const uchar *from, uint max_length) override - { - return Field::pack(to, from, max_length); - } -}; - - -/* New decimal/numeric field which use fixed point arithmetic */ -class Field_new_decimal final :public Field_num { -public: - /* The maximum number of decimal digits can be stored */ - uint precision; - uint bin_size; - /* - Constructors take max_length of the field as a parameter - not the - precision as the number of decimal digits allowed. - So for example we need to count length from precision handling - CREATE TABLE ( DECIMAL(x,y)) - */ - Field_new_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - uint8 dec_arg, bool zero_arg, bool unsigned_arg); - const Type_handler *type_handler() const override - { return &type_handler_newdecimal; } - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } - Copy_func *get_copy_func(const Field *from) const override - { - // if (from->real_type() == MYSQL_TYPE_BIT) // QQ: why? - // return do_field_int; - return do_field_decimal; - } - int save_in_field(Field *to) override - { - my_decimal tmp(ptr, precision, dec); - return to->store_decimal(&tmp); - } - bool memcpy_field_possible(const Field *from) const override - { - return real_type() == from->real_type() && - pack_length() == from->pack_length() && - is_unsigned() <= from->is_unsigned() && - decimals() == from->decimals() && - field_length == from->field_length; - } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - int reset() override; - bool store_value(const my_decimal *decimal_value); - bool store_value(const my_decimal *decimal_value, int *native_error); - void set_value_on_overflow(my_decimal *decimal_value, bool sign); - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - int store_decimal(const my_decimal *) override; - double val_real() override - { - return my_decimal(ptr, precision, dec).to_double(); - } - longlong val_int() override - { - return my_decimal(ptr, precision, dec).to_longlong(unsigned_flag); - } - ulonglong val_uint() override - { - return (ulonglong) my_decimal(ptr, precision, dec).to_longlong(true); - } - my_decimal *val_decimal(my_decimal *) override; - String *val_str(String *val_buffer, String *) override - { - uint fixed_precision= zerofill ? precision : 0; - return my_decimal(ptr, precision, dec). - to_string(val_buffer, fixed_precision, dec, '0'); - } - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { - my_decimal nr(ptr, precision, dec); - return decimal_to_datetime_with_warn(get_thd(), &nr, ltime, - fuzzydate, table->s, field_name.str); - } - bool val_bool() override - { - return my_decimal(ptr, precision, dec).to_bool(); - } - int cmp(const uchar *, const uchar *) const override; - void sort_string(uchar *buff, uint length) override; - bool zero_pack() const override { return false; } - void sql_type(String &str) const override; - uint32 max_display_length() const override { return field_length; } - Information_schema_numeric_attributes - information_schema_numeric_attributes() const override - { - return Information_schema_numeric_attributes(precision, dec); - } - uint size_of() const override { return sizeof *this; } - uint32 pack_length() const override { return (uint32) bin_size; } - uint pack_length_from_metadata(uint field_metadata) const override; - uint row_pack_length() const override { return pack_length(); } - bool compatible_field_size(uint field_metadata, const Relay_log_info *rli, - uint16 mflags, int *order_var) const override; - bool is_equal(const Column_definition &new_field) const override; - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint param_data) override; - Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) - override; - Binlog_type_info binlog_type_info() const override; -}; - - -class Field_int :public Field_num -{ -protected: - String *val_str_from_long(String *val_buffer, uint max_char_length, - int radix, long nr); -public: - Field_int(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) - :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, 0, zero_arg, unsigned_arg) - {} - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - bool memcpy_field_possible(const Field *from) const override - { - return real_type() == from->real_type() && - pack_length() == from->pack_length() && - is_unsigned() == from->is_unsigned(); - } - int store_decimal(const my_decimal *) override; - my_decimal *val_decimal(my_decimal *) override; - bool val_bool() override { return val_int() != 0; } - ulonglong val_uint() override - { - longlong nr= val_int(); - return nr < 0 && !unsigned_flag ? 0 : (ulonglong) nr; - } - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; - virtual const Type_limits_int *type_limits_int() const= 0; - uint32 max_display_length() const override - { - return type_limits_int()->char_length(); - } - Type_numeric_attributes type_numeric_attributes() const override - { - /* - For integer data types, the user-specified length does not constrain the - supported range, so e.g. a column of the INT(1) data type supports the - full integer range anyway. - Choose the maximum from the user-specified length and the maximum - possible length determined by the data type capacity: - INT(1) -> 11 - INT(10) -> 11 - INT(40) -> 40 - */ - uint32 length1= max_display_length(); - uint32 length2= field_length; - return Type_numeric_attributes(MY_MAX(length1, length2), - decimals(), is_unsigned()); - } - Information_schema_numeric_attributes - information_schema_numeric_attributes() const override - { - uint32 prec= type_limits_int()->precision(); - return Information_schema_numeric_attributes(prec, 0); - } - void sql_type(String &str) const override; - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value) override - { - return get_mm_leaf_int(param, key_part, cond, op, value, unsigned_flag); - } -}; - - -class Field_tiny :public Field_int -{ - const Type_handler_general_purpose_int *type_handler_priv() const - { - if (is_unsigned()) - return &type_handler_utiny; - return &type_handler_stiny; - } -public: - Field_tiny(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - bool zero_arg, bool unsigned_arg) - :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) - {} - const Type_handler *type_handler() const override - { return type_handler_priv(); } - enum ha_base_keytype key_type() const override - { return unsigned_flag ? HA_KEYTYPE_BINARY : HA_KEYTYPE_INT8; } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int reset() override { ptr[0]=0; return 0; } - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 1; } - const Type_limits_int *type_limits_int() const override - { - return type_handler_priv()->type_limits_int(); - } - - uchar *pack(uchar* to, const uchar *from, uint max_length) override - { - *to= *from; - return to + 1; - } - - const uchar *unpack(uchar* to, const uchar *from, - const uchar *from_end, uint param_data) override - { - if (from == from_end) - return 0; - *to= *from; - return from + 1; - } - ulonglong get_max_int_value() const override - { - return unsigned_flag ? 0xFFULL : 0x7FULL; - } -}; - - -class Field_short final :public Field_int -{ - const Type_handler_general_purpose_int *type_handler_priv() const - { - if (is_unsigned()) - return &type_handler_ushort; - return &type_handler_sshort; - } -public: - Field_short(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - bool zero_arg, bool unsigned_arg) - :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) - {} - Field_short(uint32 len_arg,bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, - bool unsigned_arg) - :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, - NONE, field_name_arg, 0, unsigned_arg) - {} - const Type_handler *type_handler() const override - { return type_handler_priv(); } - enum ha_base_keytype key_type() const override - { return unsigned_flag ? HA_KEYTYPE_USHORT_INT : HA_KEYTYPE_SHORT_INT;} - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int reset() override { ptr[0]=ptr[1]=0; return 0; } - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 2; } - const Type_limits_int *type_limits_int() const override - { - return type_handler_priv()->type_limits_int(); - } - uchar *pack(uchar* to, const uchar *from, uint) override - { return pack_int16(to, from); } - - const uchar *unpack(uchar* to, const uchar *from, - const uchar *from_end, uint) override - { return unpack_int16(to, from, from_end); } - ulonglong get_max_int_value() const override - { - return unsigned_flag ? 0xFFFFULL : 0x7FFFULL; - } -}; - -class Field_medium final :public Field_int -{ - const Type_handler_general_purpose_int *type_handler_priv() const - { - if (is_unsigned()) - return &type_handler_uint24; - return &type_handler_sint24; - } -public: - Field_medium(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - bool zero_arg, bool unsigned_arg) - :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) - {} - const Type_handler *type_handler() const override - { return type_handler_priv(); } - enum ha_base_keytype key_type() const override - { return unsigned_flag ? HA_KEYTYPE_UINT24 : HA_KEYTYPE_INT24; } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int reset() override { ptr[0]=ptr[1]=ptr[2]=0; return 0; } - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 3; } - const Type_limits_int *type_limits_int() const override - { - return type_handler_priv()->type_limits_int(); - } - uchar *pack(uchar* to, const uchar *from, uint max_length) override - { - return Field::pack(to, from, max_length); - } - ulonglong get_max_int_value() const override - { - return unsigned_flag ? 0xFFFFFFULL : 0x7FFFFFULL; - } -}; - - -class Field_long final :public Field_int -{ - const Type_handler_general_purpose_int *type_handler_priv() const - { - if (is_unsigned()) - return &type_handler_ulong; - return &type_handler_slong; - } -public: - Field_long(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - bool zero_arg, bool unsigned_arg) - :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) - {} - Field_long(uint32 len_arg,bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, - bool unsigned_arg) - :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, - NONE, field_name_arg, 0, unsigned_arg) - {} - const Type_handler *type_handler() const override - { return type_handler_priv(); } - enum ha_base_keytype key_type() const override - { return unsigned_flag ? HA_KEYTYPE_ULONG_INT : HA_KEYTYPE_LONG_INT; } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int reset() override { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; } - double val_real() override; - longlong val_int() override; - bool send(Protocol *protocol) override; - String *val_str(String *, String *) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 4; } - const Type_limits_int *type_limits_int() const override - { - return type_handler_priv()->type_limits_int(); - } - uchar *pack(uchar* to, const uchar *from, uint) override - { - return pack_int32(to, from); - } - const uchar *unpack(uchar* to, const uchar *from, - const uchar *from_end, uint) override - { - return unpack_int32(to, from, from_end); - } - ulonglong get_max_int_value() const override - { - return unsigned_flag ? 0xFFFFFFFFULL : 0x7FFFFFFFULL; - } -}; - - -class Field_longlong :public Field_int -{ - const Type_handler_general_purpose_int *type_handler_priv() const - { - if (is_unsigned()) - return &type_handler_ulonglong; - return &type_handler_slonglong; - } -public: - Field_longlong(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - bool zero_arg, bool unsigned_arg) - :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) - {} - Field_longlong(uint32 len_arg,bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, - bool unsigned_arg) - :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, - NONE, field_name_arg, 0, unsigned_arg) - {} - const Type_handler *type_handler() const override - { return type_handler_priv(); } - enum ha_base_keytype key_type() const override - { return unsigned_flag ? HA_KEYTYPE_ULONGLONG : HA_KEYTYPE_LONGLONG; } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int reset() override - { - ptr[0]=ptr[1]=ptr[2]=ptr[3]=ptr[4]=ptr[5]=ptr[6]=ptr[7]=0; - return 0; - } - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 8; } - const Type_limits_int *type_limits_int() const override - { - return type_handler_priv()->type_limits_int(); - } - uchar *pack(uchar* to, const uchar *from, uint) override - { - return pack_int64(to, from); - } - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint) override - { - return unpack_int64(to, from, from_end); - } - void set_max() override; - bool is_max() override; - ulonglong get_max_int_value() const override - { - return unsigned_flag ? 0xFFFFFFFFFFFFFFFFULL : 0x7FFFFFFFFFFFFFFFULL; - } -}; - - -class Field_vers_trx_id :public Field_longlong { - MYSQL_TIME cache; - ulonglong cached; -public: - Field_vers_trx_id(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, bool zero_arg, - bool unsigned_arg) - : Field_longlong(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, zero_arg, - unsigned_arg), - cached(0) - {} - const Type_handler *type_handler() const override - { return &type_handler_vers_trx_id; } - uint size_of() const override { return sizeof *this; } - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate, ulonglong trx_id); - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { - return get_date(ltime, fuzzydate, (ulonglong) val_int()); - } - bool test_if_equality_guarantees_uniqueness(const Item *item) const override; - bool can_optimize_keypart_ref(const Item_bool_func *, const Item *) - const override - { - return true; - } - - bool can_optimize_group_min_max(const Item_bool_func *, const Item *) - const override - { - return true; - } - bool can_optimize_range(const Item_bool_func *, const Item *, bool) - const override - { - return true; - } - /* cmp_type() cannot be TIME_RESULT, because we want to compare this field against - integers. But in all other cases we treat it as TIME_RESULT! */ -}; - - -class Field_float final :public Field_real { -public: - Field_float(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - uint8 dec_arg,bool zero_arg,bool unsigned_arg) - :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, - dec_arg, zero_arg, unsigned_arg) - { - if (dec_arg >= FLOATING_POINT_DECIMALS) - dec_arg= NOT_FIXED_DEC; - } - Field_float(uint32 len_arg, bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, uint8 dec_arg) - :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, (uint) 0, - NONE, field_name_arg, dec_arg, 0, 0) - { - if (dec_arg >= FLOATING_POINT_DECIMALS) - dec_arg= NOT_FIXED_DEC; - } - const Type_handler *type_handler() const override - { return &type_handler_float; } - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_FLOAT; } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int reset() override { bzero(ptr,sizeof(float)); return 0; } - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff, uint length) override; - uint32 pack_length() const override { return sizeof(float); } - uint row_pack_length() const override { return pack_length(); } - ulonglong get_max_int_value() const override - { - /* - We use the maximum as per IEEE754-2008 standard, 2^24 - */ - return 0x1000000ULL; - } - Binlog_type_info binlog_type_info() const override; -}; - - -class Field_double :public Field_real { - longlong val_int_from_real(bool want_unsigned_result); -public: - Field_double(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - uint8 dec_arg,bool zero_arg,bool unsigned_arg) - :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, - dec_arg, zero_arg, unsigned_arg) - { - if (dec_arg >= FLOATING_POINT_DECIMALS) - dec_arg= NOT_FIXED_DEC; - } - Field_double(uint32 len_arg, bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, uint8 dec_arg) - :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0, - NONE, field_name_arg, dec_arg, 0, 0) - { - if (dec_arg >= FLOATING_POINT_DECIMALS) - dec_arg= NOT_FIXED_DEC; - } - Field_double(uint32 len_arg, bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, - uint8 dec_arg, bool not_fixed_arg) - :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0, - NONE, field_name_arg, dec_arg, 0, 0) - { - not_fixed= not_fixed_arg; - if (dec_arg >= FLOATING_POINT_DECIMALS) - dec_arg= NOT_FIXED_DEC; - } - void init_for_tmp_table(Field *org_field, TABLE *new_table) override - { - Field::init_for_tmp_table(org_field, new_table); - not_fixed= true; - } - const Type_handler *type_handler() const override - { return &type_handler_double; } - enum ha_base_keytype key_type() const override final { return HA_KEYTYPE_DOUBLE; } - int store(const char *to,size_t length,CHARSET_INFO *charset) override final; - int store(double nr) override final; - int store(longlong nr, bool unsigned_val) override final; - int reset() override final { bzero(ptr,sizeof(double)); return 0; } - double val_real() override final; - longlong val_int() override final { return val_int_from_real(false); } - ulonglong val_uint() override final { return (ulonglong) val_int_from_real(true); } - String *val_str(String *, String *) override final; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override final; - void sort_string(uchar *buff, uint length) override final; - uint32 pack_length() const override final { return sizeof(double); } - uint row_pack_length() const override final { return pack_length(); } - ulonglong get_max_int_value() const override final - { - /* - We use the maximum as per IEEE754-2008 standard, 2^53 - */ - return 0x20000000000000ULL; - } - Binlog_type_info binlog_type_info() const override final; -}; - - -/* Everything saved in this will disappear. It will always return NULL */ - -class Field_null :public Field_str { - static uchar null[1]; -public: - Field_null(uchar *ptr_arg, uint32 len_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - const DTCollation &collation) - :Field_str(ptr_arg, len_arg, null, 1, - unireg_check_arg, field_name_arg, collation) - {} - const Type_handler *type_handler() const override - { return &type_handler_null; } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - Information_schema_character_attributes - information_schema_character_attributes() const override - { - return Information_schema_character_attributes(); - } - Copy_func *get_copy_func(const Field *from) const override - { - return do_field_string; - } - int store(const char *to, size_t length, CHARSET_INFO *cs) override final - { null[0]=1; return 0; } - int store(double nr) override final { null[0]=1; return 0; } - int store(longlong nr, bool unsigned_val) override final { null[0]=1; return 0; } - int store_decimal(const my_decimal *d) override final { null[0]=1; return 0; } - int reset() override final { return 0; } - double val_real() override final { return 0.0;} - longlong val_int() override final { return 0;} - bool val_bool() override final { return false; } - my_decimal *val_decimal(my_decimal *) override final { return 0; } - String *val_str(String *value,String *value2) override final - { value2->length(0); return value2;} - bool is_equal(const Column_definition &new_field) const override final; - int cmp(const uchar *a, const uchar *b) const override final { return 0;} - void sort_string(uchar *buff, uint length) override final {} - uint32 pack_length() const override final { return 0; } - void sql_type(String &str) const override final; - uint size_of() const override final { return sizeof *this; } - uint32 max_display_length() const override final { return 4; } - void move_field_offset(my_ptrdiff_t ptr_diff) override final {} - bool can_optimize_keypart_ref(const Item_bool_func *cond, - const Item *item) const override final - { - return false; - } - bool can_optimize_group_min_max(const Item_bool_func *cond, - const Item *const_item) const override final - { - return false; - } -}; - - -class Field_temporal :public Field { -protected: - Item *get_equal_const_item_datetime(THD *thd, const Context &ctx, - Item *const_item); - void set_warnings(Sql_condition::enum_warning_level trunc_level, - const ErrConv *str, int was_cut, const char *typestr); - int store_TIME_return_code_with_warnings(int warn, const ErrConv *str, - const char *typestr) - { - if (!MYSQL_TIME_WARN_HAVE_WARNINGS(warn) && - MYSQL_TIME_WARN_HAVE_NOTES(warn)) - { - set_warnings(Sql_condition::WARN_LEVEL_NOTE, str, - warn | MYSQL_TIME_WARN_TRUNCATED, typestr); - return 3; - } - set_warnings(Sql_condition::WARN_LEVEL_WARN, str, warn, typestr); - return warn ? 2 : 0; - } - int store_invalid_with_warning(const ErrConv *str, int was_cut, - const char *typestr) - { - DBUG_ASSERT(was_cut); - reset(); - Sql_condition::enum_warning_level level= Sql_condition::WARN_LEVEL_WARN; - if (was_cut & MYSQL_TIME_WARN_ZERO_DATE) - { - set_warnings(level, str, MYSQL_TIME_WARN_OUT_OF_RANGE, typestr); - return 2; - } - set_warnings(level, str, MYSQL_TIME_WARN_TRUNCATED, typestr); - return 1; - } - void sql_type_comment(String &str, - const Name &name, - const Name &comment) const; - void sql_type_dec_comment(String &str, - const Name &name, uint dec, - const Name &comment) const; - void sql_type_opt_dec_comment(String &str, - const Name &name, uint dec, - const Name &comment) const - { - if (dec) - sql_type_dec_comment(str, name, dec, comment); - else - sql_type_comment(str, name, comment); - } - static const Name &type_version_mysql56(); -public: - Field_temporal(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, utype unireg_check_arg, - const LEX_CSTRING *field_name_arg) - :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, - field_name_arg) - { flags|= BINARY_FLAG; } - int store_hex_hybrid(const char *str, size_t length) override - { - return store(str, length, &my_charset_bin); - } - sql_mode_t can_handle_sql_mode_dependency_on_store() const override; - Copy_func *get_copy_func(const Field *from) const override; - int save_in_field(Field *to) override - { - MYSQL_TIME ltime; - // For temporal types no truncation needed. Rounding mode is not important. - if (get_date(<ime, TIME_CONV_NONE | TIME_FRAC_NONE)) - return to->reset(); - return to->store_time_dec(<ime, decimals()); - } - bool memcpy_field_possible(const Field *from) const override; - uint32 max_display_length() const override { return field_length; } - bool str_needs_quotes() const override { return true; } - CHARSET_INFO *charset() const override - { - return DTCollation_numeric::singleton().collation; - } - const DTCollation &dtcollation() const override - { - return DTCollation_numeric::singleton(); - } - CHARSET_INFO *sort_charset() const override { return &my_charset_bin; } - bool binary() const override { return true; } - bool val_bool() override { return val_real() != 0e0; } - bool is_equal(const Column_definition &new_field) const override; - bool eq_def(const Field *field) const override - { - return (Field::eq_def(field) && decimals() == field->decimals()); - } - my_decimal *val_decimal(my_decimal*) override; - double pos_in_interval(Field *min, Field *max) override - { - return pos_in_interval_val_real(min, max); - } - bool can_optimize_keypart_ref(const Item_bool_func *cond, - const Item *item) const override; - bool can_optimize_group_min_max(const Item_bool_func *cond, - const Item *const_item) const override; - bool can_optimize_range(const Item_bool_func *cond, - const Item *item, - bool is_eq_func) const override - { - return true; - } - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value) override; -}; - - -/** - Abstract class for: - - DATE - - DATETIME - - DATETIME(1..6) - - DATETIME(0..6) - MySQL56 version -*/ -class Field_temporal_with_date :public Field_temporal { -protected: - virtual void store_TIME(const MYSQL_TIME *ltime) = 0; - void store_datetime(const Datetime &dt) - { - return store_TIME(dt.get_mysql_time()); - } - virtual bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, - date_mode_t fuzzydate) const = 0; - bool validate_MMDD(bool not_zero_date, uint month, uint day, - date_mode_t fuzzydate) const - { - if (!not_zero_date) - return bool(fuzzydate & TIME_NO_ZERO_DATE); - if (!month || !day) - return bool(fuzzydate & TIME_NO_ZERO_IN_DATE); - return false; - } -public: - Field_temporal_with_date(uchar *ptr_arg, uint32 len_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - utype unireg_check_arg, - const LEX_CSTRING *field_name_arg) - :Field_temporal(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg) - {} - bool validate_value_in_record(THD *thd, const uchar *record) const; -}; - - -class Field_timestamp :public Field_temporal { -protected: - int store_TIME_with_warning(THD *, const Datetime *, - const ErrConv *, int warn); - virtual void store_TIMEVAL(const timeval &tv)= 0; - void store_TIMESTAMP(const Timestamp &ts) - { - store_TIMEVAL(ts.tv()); - } - int zero_time_stored_return_code_with_warning(); -public: - Field_timestamp(uchar *ptr_arg, uint32 len_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share); - const Type_handler *type_handler() const override - { return &type_handler_timestamp; } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - Copy_func *get_copy_func(const Field *from) const override; - sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override; - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - int store_decimal(const my_decimal *) override; - int store_timestamp_dec(const timeval &ts, uint dec) override; - int save_in_field(Field *to) override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool zero_pack() const override { return false; } - /* - This method is used by storage/perfschema and - Item_func_now_local::save_in_field(). - */ - void store_TIME(my_time_t ts, ulong sec_part) - { - int warn; - time_round_mode_t mode= Datetime::default_round_mode(get_thd()); - store_TIMESTAMP(Timestamp(ts, sec_part).round(decimals(), mode, &warn)); - } - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; - int store_native(const Native &value) override; - bool validate_value_in_record(THD *thd, const uchar *record) const override; - Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) - override - { - return get_equal_const_item_datetime(thd, ctx, const_item); - } - bool load_data_set_null(THD *thd) override; - bool load_data_set_no_data(THD *thd, bool fixed_format) override; -}; - - -class Field_timestamp0 :public Field_timestamp -{ - void store_TIMEVAL(const timeval &tv) override - { - int4store(ptr, tv.tv_sec); - } -public: - Field_timestamp0(uchar *ptr_arg, uint32 len_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share) - :Field_timestamp(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, share) - { } - enum ha_base_keytype key_type() const override - { return HA_KEYTYPE_ULONG_INT; } - void sql_type(String &str) const override - { - sql_type_comment(str, Field_timestamp0::type_handler()->name(), - Type_handler::version_mariadb53()); - } - double val_real() override - { - return (double) Field_timestamp0::val_int(); - } - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 4; } - int set_time() override; - /* Get TIMESTAMP field value as seconds since begging of Unix Epoch */ - my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override; - bool val_native(Native *to) override; - uchar *pack(uchar *to, const uchar *from, uint) override - { - return pack_int32(to, from); - } - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint) override - { - return unpack_int32(to, from, from_end); - } - uint size_of() const override { return sizeof *this; } -}; - - -/** - Abstract class for: - - TIMESTAMP(1..6) - - TIMESTAMP(0..6) - MySQL56 version -*/ -class Field_timestamp_with_dec :public Field_timestamp { -protected: - uint dec; -public: - Field_timestamp_with_dec(uchar *ptr_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, uint dec_arg) : - Field_timestamp(ptr_arg, - MAX_DATETIME_WIDTH + dec_arg + MY_TEST(dec_arg), null_ptr_arg, - null_bit_arg, unireg_check_arg, field_name_arg, share), - dec(dec_arg) - { - DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); - } - uint decimals() const override { return dec; } - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } - uchar *pack(uchar *to, const uchar *from, uint max_length) override - { return Field::pack(to, from, max_length); } - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint param_data) override - { return Field::unpack(to, from, from_end, param_data); } - void make_send_field(Send_field *field) override; - void sort_string(uchar *to, uint length) override - { - DBUG_ASSERT(length == pack_length()); - memcpy(to, ptr, length); - } - bool send(Protocol *protocol) override; - double val_real() override; - my_decimal* val_decimal(my_decimal*) override; - int set_time() override; -}; - - -class Field_timestamp_hires :public Field_timestamp_with_dec { - uint sec_part_bytes(uint dec) const - { - return Type_handler_timestamp::sec_part_bytes(dec); - } - void store_TIMEVAL(const timeval &tv) override; -public: - Field_timestamp_hires(uchar *ptr_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, uint dec_arg) : - Field_timestamp_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, share, dec_arg) - { - DBUG_ASSERT(dec); - } - void sql_type(String &str) const override - { - sql_type_dec_comment(str, Field_timestamp_hires::type_handler()->name(), - dec, Type_handler::version_mariadb53()); - } - bool val_native(Native *to) override; - my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override; - int cmp(const uchar *,const uchar *) const override; - uint32 pack_length() const override { return 4 + sec_part_bytes(dec); } - uint size_of() const override { return sizeof *this; } -}; - - -/** - TIMESTAMP(0..6) - MySQL56 version -*/ -class Field_timestampf final :public Field_timestamp_with_dec { - void store_TIMEVAL(const timeval &tv) override; -public: - Field_timestampf(uchar *ptr_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, uint dec_arg) : - Field_timestamp_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, share, dec_arg) - {} - const Type_handler *type_handler() const override - { return &type_handler_timestamp2; } - enum_field_types binlog_type() const override - { return MYSQL_TYPE_TIMESTAMP2; } - void sql_type(String &str) const override - { - sql_type_opt_dec_comment(str, Field_timestampf::type_handler()->name(), - dec, type_version_mysql56()); - - } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - uint32 pack_length() const override - { - return my_timestamp_binary_length(dec); - } - uint row_pack_length() const override { return pack_length(); } - uint pack_length_from_metadata(uint field_metadata) const override - { - DBUG_ENTER("Field_timestampf::pack_length_from_metadata"); - uint tmp= my_timestamp_binary_length(field_metadata); - DBUG_RETURN(tmp); - } - int cmp(const uchar *a_ptr,const uchar *b_ptr) const override - { - return memcmp(a_ptr, b_ptr, pack_length()); - } - void set_max() override; - bool is_max() override; - my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override; - bool val_native(Native *to) override; - uint size_of() const override { return sizeof *this; } - Binlog_type_info binlog_type_info() const override; -}; - - -class Field_year final :public Field_tiny { -public: - Field_year(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) - :Field_tiny(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, 1, 1) - {} - const Type_handler *type_handler() const override - { - return field_length == 2 ? &type_handler_year2 : &type_handler_year; - } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - Copy_func *get_copy_func(const Field *from) const override - { - if (eq_def(from)) - return get_identical_copy_func(); - switch (from->cmp_type()) { - case STRING_RESULT: - { - const Type_handler *handler= from->type_handler(); - if (handler == &type_handler_enum || handler == &type_handler_set) - return do_field_int; - return do_field_string; - } - case TIME_RESULT: - return do_field_date; - case DECIMAL_RESULT: - return do_field_decimal; - case REAL_RESULT: - return do_field_real; - case INT_RESULT: - break; - case ROW_RESULT: - default: - DBUG_ASSERT(0); - break; - } - return do_field_int; - } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; - bool send(Protocol *protocol) override; - Information_schema_numeric_attributes - information_schema_numeric_attributes() const override - { - return Information_schema_numeric_attributes(); - } - uint32 max_display_length() const override { return field_length; } - void sql_type(String &str) const override; -}; - - -class Field_date_common :public Field_temporal_with_date -{ -protected: - int store_TIME_with_warning(const Datetime *ltime, const ErrConv *str, - int was_cut); -public: - Field_date_common(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg) - :Field_temporal_with_date(ptr_arg, MAX_DATE_WIDTH, - null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg) - {} - Copy_func *get_copy_func(const Field *from) const override; - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value) override; - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - int store_decimal(const my_decimal *) override; -}; - - -class Field_date final :public Field_date_common -{ - void store_TIME(const MYSQL_TIME *ltime) override; - bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) - const override; -public: - Field_date(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) - :Field_date_common(ptr_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg) {} - const Type_handler *type_handler() const override - { return &type_handler_date; } - enum ha_base_keytype key_type() const override - { return HA_KEYTYPE_ULONG_INT; } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - int reset() override { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; } - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { return Field_date::get_TIME(ltime, ptr, fuzzydate); } - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 4; } - void sql_type(String &str) const override; - uchar *pack(uchar* to, const uchar *from, uint) override - { - return pack_int32(to, from); - } - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint) override - { - return unpack_int32(to, from, from_end); - } - uint size_of() const override { return sizeof *this; } -}; - - -class Field_newdate final :public Field_date_common -{ - void store_TIME(const MYSQL_TIME *ltime) override; - bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) - const override; -public: - Field_newdate(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) - :Field_date_common(ptr_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg) - {} - const Type_handler *type_handler() const override - { return &type_handler_newdate; } - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_UINT24; } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - int reset() override { ptr[0]=ptr[1]=ptr[2]=0; return 0; } - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 3; } - void sql_type(String &str) const override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { return Field_newdate::get_TIME(ltime, ptr, fuzzydate); } - longlong val_datetime_packed(THD *thd) override; - uint size_of() const override { return sizeof *this; } - Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) - override; -}; - - -class Field_time :public Field_temporal { - /* - when this Field_time instance is used for storing values for index lookups - (see class store_key, Field::new_key_field(), etc), the following - might be set to TO_DAYS(CURDATE()). See also Field_time::store_time_dec() - */ - long curdays; -protected: - virtual void store_TIME(const MYSQL_TIME *ltime)= 0; - void store_TIME(const Time &t) { return store_TIME(t.get_mysql_time()); } - int store_TIME_with_warning(const Time *ltime, const ErrConv *str, int warn); - bool check_zero_in_date_with_warn(date_mode_t fuzzydate); - static void do_field_time(Copy_field *copy); -public: - Field_time(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg) - :Field_temporal(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg), curdays(0) - {} - bool can_be_substituted_to_equal_item(const Context &ctx, - const Item_equal *item_equal) override; - const Type_handler *type_handler() const override - { return &type_handler_time; } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - Copy_func *get_copy_func(const Field *from) const override - { - return from->cmp_type() == REAL_RESULT ? do_field_string : // MDEV-9344 - from->type() == MYSQL_TYPE_YEAR ? do_field_int : - from->type() == MYSQL_TYPE_BIT ? do_field_int : - eq_def(from) ? get_identical_copy_func() : - do_field_time; - } - bool memcpy_field_possible(const Field *from) const override - { - return real_type() == from->real_type() && - decimals() == from->decimals(); - } - sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override; - int store_native(const Native &value) override; - bool val_native(Native *to) override; - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_decimal(const my_decimal *) override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - void set_curdays(THD *thd); - Field *new_key_field(MEM_ROOT *root, TABLE *new_table, - uchar *new_ptr, uint32 length, - uchar *new_null_ptr, uint new_null_bit) override; - Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) - override; -}; - - -class Field_time0 final :public Field_time -{ -protected: - void store_TIME(const MYSQL_TIME *ltime) override; -public: - Field_time0(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg) - :Field_time(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg) - { } - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_INT24; } - void sql_type(String &str) const override - { - sql_type_comment(str, Field_time0::type_handler()->name(), - Type_handler::version_mariadb53()); - } - double val_real() override; - longlong val_int() override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 3; } - uint size_of() const override { return sizeof *this; } -}; - - -/** - Abstract class for: - - TIME(1..6) - - TIME(0..6) - MySQL56 version -*/ -class Field_time_with_dec :public Field_time { -protected: - uint dec; -public: - Field_time_with_dec(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - uint dec_arg) - :Field_time(ptr_arg, MIN_TIME_WIDTH + dec_arg + MY_TEST(dec_arg), - null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg), - dec(dec_arg) - { - DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); - } - uint decimals() const override { return dec; } - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } - longlong val_int() override; - double val_real() override; - void make_send_field(Send_field *) override; -}; - - -/** - TIME(1..6) -*/ -class Field_time_hires final :public Field_time_with_dec { - longlong zero_point; - void store_TIME(const MYSQL_TIME *) override; -public: - Field_time_hires(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - uint dec_arg) - :Field_time_with_dec(ptr_arg, null_ptr_arg, - null_bit_arg, unireg_check_arg, field_name_arg, - dec_arg) - { - DBUG_ASSERT(dec); - zero_point= sec_part_shift( - ((TIME_MAX_VALUE_SECONDS+1LL)*TIME_SECOND_PART_FACTOR), dec); - } - void sql_type(String &str) const override - { - sql_type_dec_comment(str, Field_time_hires::type_handler()->name(), - dec, Type_handler::version_mariadb53()); - } - int reset() override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override - { return Type_handler_time::hires_bytes(dec); } - uint size_of() const override { return sizeof *this; } -}; - - -/** - TIME(0..6) - MySQL56 version -*/ -class Field_timef final :public Field_time_with_dec { - void store_TIME(const MYSQL_TIME *ltime) override; -public: - Field_timef(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - uint dec_arg) - :Field_time_with_dec(ptr_arg, null_ptr_arg, - null_bit_arg, unireg_check_arg, field_name_arg, - dec_arg) - { - DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); - } - const Type_handler *type_handler() const override - { return &type_handler_time2; } - enum_field_types binlog_type() const override { return MYSQL_TYPE_TIME2; } - void sql_type(String &str) const override - { - sql_type_opt_dec_comment(str, Field_timef::type_handler()->name(), - dec, type_version_mysql56()); - } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - uint32 pack_length() const override - { - return my_time_binary_length(dec); - } - uint row_pack_length() const override { return pack_length(); } - uint pack_length_from_metadata(uint field_metadata) const override - { - DBUG_ENTER("Field_timef::pack_length_from_metadata"); - uint tmp= my_time_binary_length(field_metadata); - DBUG_RETURN(tmp); - } - void sort_string(uchar *to, uint length) override - { - DBUG_ASSERT(length == Field_timef::pack_length()); - memcpy(to, ptr, length); - } - int cmp(const uchar *a_ptr, const uchar *b_ptr) const override - { - return memcmp(a_ptr, b_ptr, pack_length()); - } - int reset() override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; - longlong val_time_packed(THD *thd) override; - int store_native(const Native &value) override; - bool val_native(Native *to) override; - uint size_of() const override { return sizeof *this; } - Binlog_type_info binlog_type_info() const override; -}; - - -class Field_datetime :public Field_temporal_with_date { -protected: - int store_TIME_with_warning(const Datetime *ltime, const ErrConv *str, - int was_cut); -public: - Field_datetime(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg) - :Field_temporal_with_date(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg) - { - if (unireg_check == TIMESTAMP_UN_FIELD || - unireg_check == TIMESTAMP_DNUN_FIELD) - flags|= ON_UPDATE_NOW_FLAG; - } - const Type_handler *type_handler() const override - { return &type_handler_datetime; } - sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override; - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; - int store_decimal(const my_decimal *) override; - int set_time() override; - Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) - override - { - return get_equal_const_item_datetime(thd, ctx, const_item); - } -}; - - -/* - Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte -*/ - -class Field_datetime0 final :public Field_datetime -{ - void store_TIME(const MYSQL_TIME *ltime) override; - bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) - const override; -public: - Field_datetime0(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg) - :Field_datetime(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg) - {} - enum ha_base_keytype key_type() const override - { return HA_KEYTYPE_ULONGLONG; } - void sql_type(String &str) const override - { - sql_type_comment(str, Field_datetime0::type_handler()->name(), - Type_handler::version_mariadb53()); - } - double val_real() override - { - return (double) Field_datetime0::val_int(); - } - longlong val_int() override; - String *val_str(String *, String *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return 8; } - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { return Field_datetime0::get_TIME(ltime, ptr, fuzzydate); } - uchar *pack(uchar* to, const uchar *from, uint) override - { - return pack_int64(to, from); - } - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint) override - { - return unpack_int64(to, from, from_end); - } - uint size_of() const override { return sizeof *this; } -}; - - -/** - Abstract class for: - - DATETIME(1..6) - - DATETIME(0..6) - MySQL56 version -*/ -class Field_datetime_with_dec :public Field_datetime { -protected: - uint dec; -public: - Field_datetime_with_dec(uchar *ptr_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, uint dec_arg) - :Field_datetime(ptr_arg, MAX_DATETIME_WIDTH + dec_arg + MY_TEST(dec_arg), - null_ptr_arg, null_bit_arg, unireg_check_arg, - field_name_arg), dec(dec_arg) - { - DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); - } - uint decimals() const override final { return dec; } - enum ha_base_keytype key_type() const override final { return HA_KEYTYPE_BINARY; } - void make_send_field(Send_field *field) override final; - bool send(Protocol *protocol) override final; - uchar *pack(uchar *to, const uchar *from, uint max_length) override final - { return Field::pack(to, from, max_length); } - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint param_data) override final - { return Field::unpack(to, from, from_end, param_data); } - void sort_string(uchar *to, uint length) override final - { - DBUG_ASSERT(length == pack_length()); - memcpy(to, ptr, length); - } - double val_real() override final; - longlong val_int() override final; - String *val_str(String *, String *) override final; -}; - - -/** - DATETIME(1..6) -*/ -class Field_datetime_hires final :public Field_datetime_with_dec { - void store_TIME(const MYSQL_TIME *ltime) override; - bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) - const override; -public: - Field_datetime_hires(uchar *ptr_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, uint dec_arg) - :Field_datetime_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, dec_arg) - { - DBUG_ASSERT(dec); - } - void sql_type(String &str) const override - { - sql_type_dec_comment(str, Field_datetime_hires::type_handler()->name(), - dec, Type_handler::version_mariadb53()); - } - int cmp(const uchar *,const uchar *) const override; - uint32 pack_length() const override - { return Type_handler_datetime::hires_bytes(dec); } - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { return Field_datetime_hires::get_TIME(ltime, ptr, fuzzydate); } - uint size_of() const override { return sizeof *this; } -}; - - -/** - DATETIME(0..6) - MySQL56 version -*/ - -class Field_datetimef final :public Field_datetime_with_dec { - void store_TIME(const MYSQL_TIME *ltime) override; - bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) - const override; -public: - Field_datetimef(uchar *ptr_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, uint dec_arg) - :Field_datetime_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, dec_arg) - {} - const Type_handler *type_handler() const override - { return &type_handler_datetime2; } - enum_field_types binlog_type() const override - { return MYSQL_TYPE_DATETIME2; } - void sql_type(String &str) const override - { - sql_type_opt_dec_comment(str, Field_datetimef::type_handler()->name(), - dec, type_version_mysql56()); - } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - uint32 pack_length() const override - { - return my_datetime_binary_length(dec); - } - uint row_pack_length() const override { return pack_length(); } - uint pack_length_from_metadata(uint field_metadata) const override - { - DBUG_ENTER("Field_datetimef::pack_length_from_metadata"); - uint tmp= my_datetime_binary_length(field_metadata); - DBUG_RETURN(tmp); - } - int cmp(const uchar *a_ptr, const uchar *b_ptr) const override - { - return memcmp(a_ptr, b_ptr, pack_length()); - } - int reset() override; - bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { return Field_datetimef::get_TIME(ltime, ptr, fuzzydate); } - longlong val_datetime_packed(THD *thd) override; - uint size_of() const override { return sizeof *this; } - Binlog_type_info binlog_type_info() const override; -}; - - -static inline Field_timestamp * -new_Field_timestamp(MEM_ROOT *root,uchar *ptr, uchar *null_ptr, uchar null_bit, - enum Field::utype unireg_check, - const LEX_CSTRING *field_name, - TABLE_SHARE *share, uint dec) -{ - if (dec==0) - return new (root) - Field_timestamp0(ptr, MAX_DATETIME_WIDTH, null_ptr, - null_bit, unireg_check, field_name, share); - if (dec >= FLOATING_POINT_DECIMALS) - dec= MAX_DATETIME_PRECISION; - return new (root) - Field_timestamp_hires(ptr, null_ptr, null_bit, unireg_check, - field_name, share, dec); -} - -static inline Field_time * -new_Field_time(MEM_ROOT *root, uchar *ptr, uchar *null_ptr, uchar null_bit, - enum Field::utype unireg_check, const LEX_CSTRING *field_name, - uint dec) -{ - if (dec == 0) - return new (root) - Field_time0(ptr, MIN_TIME_WIDTH, null_ptr, null_bit, unireg_check, - field_name); - if (dec >= FLOATING_POINT_DECIMALS) - dec= MAX_DATETIME_PRECISION; - return new (root) - Field_time_hires(ptr, null_ptr, null_bit, unireg_check, field_name, dec); -} - -static inline Field_datetime * -new_Field_datetime(MEM_ROOT *root, uchar *ptr, uchar *null_ptr, uchar null_bit, - enum Field::utype unireg_check, - const LEX_CSTRING *field_name, uint dec) -{ - if (dec == 0) - return new (root) - Field_datetime0(ptr, MAX_DATETIME_WIDTH, null_ptr, null_bit, - unireg_check, field_name); - if (dec >= FLOATING_POINT_DECIMALS) - dec= MAX_DATETIME_PRECISION; - return new (root) - Field_datetime_hires(ptr, null_ptr, null_bit, - unireg_check, field_name, dec); -} - -class Field_string final :public Field_longstr { - class Warn_filter_string: public Warn_filter - { - public: - Warn_filter_string(const THD *thd, const Field_string *field); - }; - bool is_var_string() const - { - return can_alter_field_type && - orig_table && - (orig_table->s->db_create_options & HA_OPTION_PACK_RECORD) && - field_length >= 4 && - orig_table->s->frm_version < FRM_VER_TRUE_VARCHAR; - } -public: - bool can_alter_field_type; - Field_string(uchar *ptr_arg, uint32 len_arg,uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - const DTCollation &collation) - :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, collation), - can_alter_field_type(1) {}; - Field_string(uint32 len_arg,bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, - const DTCollation &collation) - :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0, - NONE, field_name_arg, collation), - can_alter_field_type(1) {}; - - const Type_handler *type_handler() const override - { - if (is_var_string()) - return &type_handler_var_string; - return &type_handler_string; - } - enum ha_base_keytype key_type() const override - { return binary() ? HA_KEYTYPE_BINARY : HA_KEYTYPE_TEXT; } - en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override; - bool zero_pack() const override { return false; } - Copy_func *get_copy_func(const Field *from) const override; - int reset() override - { - charset()->fill((char*) ptr, field_length, (has_charset() ? ' ' : 0)); - return 0; - } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - using Field_str::store; - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - my_decimal *val_decimal(my_decimal *) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - void update_data_type_statistics(Data_type_statistics *st) const override - { - st->m_fixed_string_count++; - st->m_fixed_string_total_length+= pack_length(); - } - void sql_type(String &str) const override; - void sql_rpl_type(String*) const override; - bool is_equal(const Column_definition &new_field) const override; - bool can_be_converted_by_engine(const Column_definition &new_type) const - override - { - return table->file->can_convert_string(this, new_type); - } - uchar *pack(uchar *to, const uchar *from, uint max_length) override; - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint param_data) override; - uint pack_length_from_metadata(uint field_metadata) const override - { - DBUG_PRINT("debug", ("field_metadata: 0x%04x", field_metadata)); - if (field_metadata == 0) - return row_pack_length(); - return (((field_metadata >> 4) & 0x300) ^ 0x300) + (field_metadata & 0x00ff); - } - bool compatible_field_size(uint field_metadata, const Relay_log_info *rli, - uint16 mflags, int *order_var) const override; - uint row_pack_length() const override { return field_length; } - int pack_cmp(const uchar *a,const uchar *b,uint key_length, - bool insert_or_update); - int pack_cmp(const uchar *b,uint key_length,bool insert_or_update); - uint packed_col_length(const uchar *to, uint length) override; - uint max_packed_col_length(uint max_length) override; - uint size_of() const override { return sizeof *this; } - bool has_charset() const override { return charset() != &my_charset_bin; } - Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) - override; - uint get_key_image(uchar *buff, uint length, - const uchar *ptr_arg, imagetype type) const override; - sql_mode_t value_depends_on_sql_mode() const override; - sql_mode_t can_handle_sql_mode_dependency_on_store() const override; - void print_key_value(String *out, uint32 length) override; - Binlog_type_info binlog_type_info() const override; -}; - - -class Field_varstring :public Field_longstr { -public: - const uchar *get_data() const - { - return get_data(ptr); - } - const uchar *get_data(const uchar *ptr_arg) const - { - return ptr_arg + length_bytes; - } - uint get_length() const - { - return get_length(ptr); - } - uint get_length(const uchar *ptr_arg) const - { - return length_bytes == 1 ? (uint) *ptr_arg : uint2korr(ptr_arg); - } -protected: - void store_length(uint32 number) - { - if (length_bytes == 1) - *ptr= (uchar) number; - else - int2store(ptr, number); - } - virtual void val_str_from_ptr(String *val, const uchar *ptr) const; -public: - /* - The maximum space available in a Field_varstring, in bytes. See - length_bytes. - */ - static const uint MAX_SIZE; - /* Store number of bytes used to store length (1 or 2) */ - uint32 length_bytes; - Field_varstring(uchar *ptr_arg, - uint32 len_arg, uint length_bytes_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, const DTCollation &collation) - :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, collation), - length_bytes(length_bytes_arg) - { - share->varchar_fields++; - } - Field_varstring(uint32 len_arg,bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, const DTCollation &collation) - :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0, - NONE, field_name_arg, collation), - length_bytes(len_arg < 256 ? 1 :2) - { - share->varchar_fields++; - } - - const Type_handler *type_handler() const override - { return &type_handler_varchar; } - en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override - { - return FIELD_VARCHAR; - } - enum ha_base_keytype key_type() const override; - uint16 key_part_flag() const override { return HA_VAR_LENGTH_PART; } - uint16 key_part_length_bytes() const override { return HA_KEY_BLOB_LENGTH; } - uint row_pack_length() const override { return field_length; } - bool zero_pack() const override { return false; } - int reset() override { bzero(ptr,field_length+length_bytes); return 0; } - uint32 pack_length() const override - { return (uint32) field_length+length_bytes; } - uint32 key_length() const override { return (uint32) field_length; } - uint32 sort_length() const override - { - return (uint32) field_length + sort_suffix_length(); - } - virtual uint32 sort_suffix_length() const override - { - return (field_charset() == &my_charset_bin ? length_bytes : 0); - } - Copy_func *get_copy_func(const Field *from) const override; - bool memcpy_field_possible(const Field *from) const override; - void update_data_type_statistics(Data_type_statistics *st) const override - { - st->m_variable_string_count++; - st->m_variable_string_total_length+= pack_length(); - } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - using Field_str::store; -#ifdef HAVE_valgrind - void mark_unused_memory_as_defined() override; -#endif - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - my_decimal *val_decimal(my_decimal *) override; - bool send(Protocol *protocol) override; - int cmp(const uchar *a,const uchar *b) const override; - int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_len) const - override; - void sort_string(uchar *buff,uint length) override; - uint get_key_image(uchar *buff, uint length, - const uchar *ptr_arg, imagetype type) const override; - void set_key_image(const uchar *buff,uint length) override; - void sql_type(String &str) const override; - void sql_rpl_type(String*) const override; - uchar *pack(uchar *to, const uchar *from, uint max_length) override; - const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, - uint param_data) override; - int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const - override; - int key_cmp(const uchar *,const uchar*) const override; - int key_cmp(const uchar *str, uint length) const override; - uint packed_col_length(const uchar *to, uint length) override; - uint max_packed_col_length(uint max_length) override; - uint32 data_length() override; - uint size_of() const override { return sizeof *this; } - bool has_charset() const override - { return charset() == &my_charset_bin ? FALSE : TRUE; } - Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) - override; - Field *new_key_field(MEM_ROOT *root, TABLE *new_table, - uchar *new_ptr, uint32 length, - uchar *new_null_ptr, uint new_null_bit) override; - bool is_equal(const Column_definition &new_field) const override; - bool can_be_converted_by_engine(const Column_definition &new_type) const - override - { - return table->file->can_convert_varstring(this, new_type); - } - void hash(ulong *nr, ulong *nr2) override; - uint length_size() const override { return length_bytes; } - void print_key_value(String *out, uint32 length) override; - Binlog_type_info binlog_type_info() const override; -}; - - -class Field_varstring_compressed final :public Field_varstring { -public: - Field_varstring_compressed(uchar *ptr_arg, - uint32 len_arg, uint length_bytes_arg, - uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, const DTCollation &collation, - Compression_method *compression_method_arg): - Field_varstring(ptr_arg, len_arg, length_bytes_arg, null_ptr_arg, - null_bit_arg, unireg_check_arg, field_name_arg, - share, collation), - compression_method_ptr(compression_method_arg) { DBUG_ASSERT(len_arg > 0); } - Compression_method *compression_method() const override - { return compression_method_ptr; } -private: - Compression_method *compression_method_ptr; - void val_str_from_ptr(String *val, const uchar *ptr) const override; - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - using Field_str::store; - String *val_str(String *, String *) override; - double val_real() override; - longlong val_int() override; - uint size_of() const override { return sizeof *this; } - /* - We use the default Field::send() implementation, - because the derived optimized version (from Field_longstr) - is not suitable for compressed fields. - */ - bool send(Protocol *protocol) override - { - return Field::send(protocol); - } - enum_field_types binlog_type() const override - { return MYSQL_TYPE_VARCHAR_COMPRESSED; } - void sql_type(String &str) const override - { - Field_varstring::sql_type(str); - str.append(STRING_WITH_LEN(" /*!100301 COMPRESSED*/")); - } - uint32 max_display_length() const override { return field_length - 1; } - uint32 character_octet_length() const override { return field_length - 1; } - uint32 char_length() const override - { - return (field_length - 1) / mbmaxlen(); - } - int cmp(const uchar *a_ptr, const uchar *b_ptr) const override; - - /* - Compressed fields can't have keys as two rows may have different - compression methods or compression levels. - */ - - int key_cmp(const uchar *str, uint length) const override - { DBUG_ASSERT(0); return 0; } - using Field_varstring::key_cmp; - Binlog_type_info binlog_type_info() const override; -}; - - -static inline uint8 number_storage_requirement(uint32 n) -{ - return n < 256 ? 1 : n < 65536 ? 2 : n < 16777216 ? 3 : 4; -} - - -static inline void store_bigendian(ulonglong num, uchar *to, uint bytes) -{ - switch(bytes) { - case 1: mi_int1store(to, num); break; - case 2: mi_int2store(to, num); break; - case 3: mi_int3store(to, num); break; - case 4: mi_int4store(to, num); break; - case 5: mi_int5store(to, num); break; - case 6: mi_int6store(to, num); break; - case 7: mi_int7store(to, num); break; - case 8: mi_int8store(to, num); break; - default: DBUG_ASSERT(0); - } -} - - -static inline longlong read_bigendian(const uchar *from, uint bytes) -{ - switch(bytes) { - case 1: return mi_uint1korr(from); - case 2: return mi_uint2korr(from); - case 3: return mi_uint3korr(from); - case 4: return mi_uint4korr(from); - case 5: return mi_uint5korr(from); - case 6: return mi_uint6korr(from); - case 7: return mi_uint7korr(from); - case 8: return mi_sint8korr(from); - default: DBUG_ASSERT(0); return 0; - } -} - -static inline void store_lowendian(ulonglong num, uchar *to, uint bytes) -{ - switch(bytes) { - case 1: *to= (uchar)num; break; - case 2: int2store(to, num); break; - case 3: int3store(to, num); break; - case 4: int4store(to, num); break; - case 8: int8store(to, num); break; - default: DBUG_ASSERT(0); - } -} - -static inline longlong read_lowendian(const uchar *from, uint bytes) -{ - switch(bytes) { - case 1: return from[0]; - case 2: return uint2korr(from); - case 3: return uint3korr(from); - case 4: return uint4korr(from); - case 8: return sint8korr(from); - default: DBUG_ASSERT(0); return 0; - } -} - - -extern LEX_CSTRING temp_lex_str; - -class Field_blob :public Field_longstr { -protected: - /** - The number of bytes used to represent the length of the blob. - */ - uint packlength; - - /** - The 'value'-object is a cache fronting the storage engine. - */ - String value; - /** - Cache for blob values when reading a row with a virtual blob - field. This is needed to not destroy the old cached value when - updating the blob with a new value when creating the new row. - */ - String read_value; - - static void do_copy_blob(Copy_field *copy); - static void do_conv_blob(Copy_field *copy); - uint get_key_image_itRAW(const uchar *ptr_arg, uchar *buff, uint length) const; -public: - Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, uint blob_pack_length, - const DTCollation &collation); - Field_blob(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, - const DTCollation &collation) - :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0, - NONE, field_name_arg, collation), - packlength(4) - { - flags|= BLOB_FLAG; - } - Field_blob(uint32 len_arg,bool maybe_null_arg, - const LEX_CSTRING *field_name_arg, - const DTCollation &collation, bool set_packlength) - :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0, - NONE, field_name_arg, collation) - { - flags|= BLOB_FLAG; - packlength= set_packlength ? number_storage_requirement(len_arg) : 4; - } - Field_blob(uint32 packlength_arg) - :Field_longstr((uchar*) 0, 0, (uchar*) "", 0, NONE, &temp_lex_str, - system_charset_info), - packlength(packlength_arg) {} - const Type_handler *type_handler() const override; - /* Note that the default copy constructor is used, in clone() */ - enum_field_types type() const override - { - /* - We cannot return type_handler()->field_type() here. - Some pieces of the code (e.g. in engines) rely on the fact - that Field::type(), Field::real_type() and Item_field::field_type() - return MYSQL_TYPE_BLOB for all blob variants. - We should eventually fix all such code pieces to expect - all BLOB type codes. - */ - return MYSQL_TYPE_BLOB; - } - enum_field_types real_type() const override - { - return MYSQL_TYPE_BLOB; - } - enum ha_base_keytype key_type() const override - { return binary() ? HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2; } - uint16 key_part_flag() const override { return HA_BLOB_PART; } - uint16 key_part_length_bytes() const override { return HA_KEY_BLOB_LENGTH; } - en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override - { - return FIELD_BLOB; - } - Type_numeric_attributes type_numeric_attributes() const override - { - return Type_numeric_attributes(Field_blob::max_display_length(), - decimals(), is_unsigned()); - } - Information_schema_character_attributes - information_schema_character_attributes() const override - { - uint32 octets= Field_blob::character_octet_length(); - uint32 chars= octets / field_charset()->mbminlen; - return Information_schema_character_attributes(octets, chars); - } - void update_data_type_statistics(Data_type_statistics *st) const override - { - st->m_blob_count++; - } - void make_send_field(Send_field *) override; - Copy_func *get_copy_func(const Field *from) const override - { - /* - TODO: MDEV-9331 - if (from->type() == MYSQL_TYPE_BIT) - return do_field_int; - */ - if (!(from->flags & BLOB_FLAG) || from->charset() != charset() || - !from->compression_method() != !compression_method()) - return do_conv_blob; - if (from->pack_length() != Field_blob::pack_length()) - return do_copy_blob; - return get_identical_copy_func(); - } - int store_field(Field *from) override - { // Be sure the value is stored - if (field_charset() == &my_charset_bin && - from->type_handler()->convert_to_binary_using_val_native()) - { - NativeBuffer<64> tmp; - from->val_native(&tmp); - value.copy(tmp.ptr(), tmp.length(), &my_charset_bin); - return store(value.ptr(), value.length(), &my_charset_bin); - } - from->val_str(&value); - if (table->copy_blobs || - (!value.is_alloced() && from->is_varchar_and_in_write_set())) - value.copy(); - return store(value.ptr(), value.length(), from->charset()); - } - bool memcpy_field_possible(const Field *from) const override - { - return Field_str::memcpy_field_possible(from) && - !compression_method() == !from->compression_method() && - !table->copy_blobs; - } - bool make_empty_rec_store_default_value(THD *thd, Item *item) override; - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - using Field_str::store; - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - my_decimal *val_decimal(my_decimal *) override; - int cmp(const uchar *a, const uchar *b) const override; - int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_len) const - override; - int cmp(const uchar *a, uint32 a_length, const uchar *b, uint32 b_length) - const; - int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const - override; - int key_cmp(const uchar *,const uchar*) const override; - int key_cmp(const uchar *str, uint length) const override; - /* Never update the value of min_val for a blob field */ - bool update_min(Field *min_val, bool force_update) override { return false; } - /* Never update the value of max_val for a blob field */ - bool update_max(Field *max_val, bool force_update) override { return false; } - uint32 key_length() const override { return 0; } - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override - { return (uint32) (packlength + portable_sizeof_char_ptr); } - - /** - Return the packed length without the pointer size added. - - This is used to determine the size of the actual data in the row - buffer. - - @returns The length of the raw data itself without the pointer. - */ - uint32 pack_length_no_ptr() const - { return (uint32) (packlength); } - uint row_pack_length() const override { return pack_length_no_ptr(); } - uint32 sort_length() const override; - uint32 sort_suffix_length() const override; - uint32 value_length() override { return get_length(); } - virtual uint32 max_data_length() const override - { - return (uint32) (((ulonglong) 1 << (packlength*8)) -1); - } - int reset() override { bzero(ptr, packlength+sizeof(uchar*)); return 0; } - void reset_fields() override - { - bzero((uchar*) &value, sizeof value); - bzero((uchar*) &read_value, sizeof read_value); - } - uint32 get_field_buffer_size() { return value.alloced_length(); } - void store_length(uchar *i_ptr, uint i_packlength, uint32 i_number); - void store_length(size_t number) - { - DBUG_ASSERT(number < UINT_MAX32); - store_length(ptr, packlength, (uint32)number); - } - inline uint32 get_length(my_ptrdiff_t row_offset= 0) const - { return get_length(ptr+row_offset, this->packlength); } - uint32 get_length(const uchar *ptr, uint packlength) const; - uint32 get_length(const uchar *ptr_arg) const - { return get_length(ptr_arg, this->packlength); } - inline uchar *get_ptr() const { return get_ptr(ptr); } - inline uchar *get_ptr(const uchar *ptr_arg) const - { - uchar *s; - memcpy(&s, ptr_arg + packlength, sizeof(uchar*)); - return s; - } - inline void set_ptr(uchar *length, uchar *data) - { - memcpy(ptr,length,packlength); - memcpy(ptr+packlength, &data,sizeof(char*)); - } - void set_ptr_offset(my_ptrdiff_t ptr_diff, uint32 length, const uchar *data) - { - uchar *ptr_ofs= ADD_TO_PTR(ptr,ptr_diff,uchar*); - store_length(ptr_ofs, packlength, length); - memcpy(ptr_ofs+packlength, &data, sizeof(char*)); - } - inline void set_ptr(uint32 length, uchar *data) - { - set_ptr_offset(0, length, data); - } - int copy_value(Field_blob *from); - uint get_key_image(uchar *buff, uint length, - const uchar *ptr_arg, imagetype type) const override - { - DBUG_ASSERT(type == itRAW); - return get_key_image_itRAW(ptr_arg, buff, length); - } - void set_key_image(const uchar *buff,uint length) override; - Field *new_key_field(MEM_ROOT *root, TABLE *new_table, - uchar *new_ptr, uint32 length, - uchar *new_null_ptr, uint new_null_bit) override; - void sql_type(String &str) const override; - inline bool copy() - { - uchar *tmp= get_ptr(); - if (value.copy((char*) tmp, get_length(), charset())) - { - Field_blob::reset(); - return 1; - } - tmp=(uchar*) value.ptr(); - memcpy(ptr+packlength, &tmp, sizeof(char*)); - return 0; - } - /* store value for the duration of the current read record */ - inline void swap_value_and_read_value() - { - read_value.swap(value); - } - inline void set_value(uchar *data) - { - /* Set value pointer. Lengths are not important */ - value.reset((char*) data, 1, 1, &my_charset_bin); - } - uchar *pack(uchar *to, const uchar *from, uint max_length) override; - const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, - uint param_data) override; - uint packed_col_length(const uchar *col_ptr, uint length) override; - uint max_packed_col_length(uint max_length) override; - void free() override - { - value.free(); - read_value.free(); - } - inline void clear_temporary() - { - uchar *tmp= get_ptr(); - if (likely(value.ptr() == (char*) tmp)) - bzero((uchar*) &value, sizeof(value)); - else - { - /* - Currently read_value should never point to tmp, the following code - is mainly here to make things future proof. - */ - if (unlikely(read_value.ptr() == (char*) tmp)) - bzero((uchar*) &read_value, sizeof(read_value)); - } - } - uint size_of() const override { return sizeof *this; } - bool has_charset() const override { return charset() != &my_charset_bin; } - uint32 max_display_length() const override; - uint32 char_length() const override; - uint32 character_octet_length() const override; - bool is_equal(const Column_definition &new_field) const override; - bool can_be_converted_by_engine(const Column_definition &new_type) const - override - { - return table->file->can_convert_blob(this, new_type); - } - void print_key_value(String *out, uint32 length) override; - Binlog_type_info binlog_type_info() const override; - - friend void TABLE::remember_blob_values(String *blob_storage); - friend void TABLE::restore_blob_values(String *blob_storage); -}; - - -class Field_blob_compressed final :public Field_blob { -public: - Field_blob_compressed(uchar *ptr_arg, uchar *null_ptr_arg, - uchar null_bit_arg, enum utype unireg_check_arg, - const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, - uint blob_pack_length, const DTCollation &collation, - Compression_method *compression_method_arg): - Field_blob(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, - field_name_arg, share, blob_pack_length, collation), - compression_method_ptr(compression_method_arg) {} - Compression_method *compression_method() const override - { return compression_method_ptr; } -private: - Compression_method *compression_method_ptr; - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - using Field_str::store; - String *val_str(String *, String *) override; - double val_real() override; - longlong val_int() override; - /* - We use the default Field::send() implementation, - because the derived optimized version (from Field_longstr) - is not suitable for compressed fields. - */ - bool send(Protocol *protocol) override - { - return Field::send(protocol); - } - uint size_of() const override { return sizeof *this; } - enum_field_types binlog_type() const override - { return MYSQL_TYPE_BLOB_COMPRESSED; } - void sql_type(String &str) const override - { - Field_blob::sql_type(str); - str.append(STRING_WITH_LEN(" /*!100301 COMPRESSED*/")); - } - - /* - Compressed fields can't have keys as two rows may have different - compression methods or compression levels. - */ - - uint get_key_image(uchar *buff, uint length, - const uchar *ptr_arg, imagetype type_arg) const override - { DBUG_ASSERT(0); return 0; } - void set_key_image(const uchar *, uint) override - { DBUG_ASSERT(0); } - int key_cmp(const uchar *, const uchar *) const override - { DBUG_ASSERT(0); return 0; } - int key_cmp(const uchar *, uint) const override - { DBUG_ASSERT(0); return 0; } - Field *new_key_field(MEM_ROOT *, TABLE *, uchar *, uint32, uchar *, uint) - override - { DBUG_ASSERT(0); return 0; } - Binlog_type_info binlog_type_info() const override; -}; - - -class Field_enum :public Field_str { - static void do_field_enum(Copy_field *copy_field); - longlong val_int(const uchar *) const; -protected: - uint packlength; -public: - const TYPELIB *typelib; - Field_enum(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - uint packlength_arg, - const TYPELIB *typelib_arg, - const DTCollation &collation) - :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, collation), - packlength(packlength_arg),typelib(typelib_arg) - { - flags|=ENUM_FLAG; - } - Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) - override; - const Type_handler *type_handler() const override - { return &type_handler_enum; } - enum ha_base_keytype key_type() const override; - sql_mode_t can_handle_sql_mode_dependency_on_store() const override; - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - Copy_func *get_copy_func(const Field *from) const override - { - if (eq_def(from)) - return get_identical_copy_func(); - if (real_type() == MYSQL_TYPE_ENUM && - from->real_type() == MYSQL_TYPE_ENUM) - return do_field_enum; - if (from->result_type() == STRING_RESULT) - return do_field_string; - return do_field_int; - } - int store_field(Field *from) override - { - if (from->real_type() == MYSQL_TYPE_ENUM && from->val_int() == 0) - { - store_type(0); - return 0; - } - return from->save_in_field(this); - } - int save_in_field(Field *to) override - { - if (to->result_type() != STRING_RESULT) - return to->store(val_int(), 0); - return save_in_field_str(to); - } - bool memcpy_field_possible(const Field *from) const override - { return false; } - void make_empty_rec_reset(THD *) override - { - if (flags & NOT_NULL_FLAG) - { - set_notnull(); - store((longlong) 1, true); - } - else - reset(); - } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - double val_real() override; - longlong val_int() override; - String *val_str(String *, String *) override; - int cmp(const uchar *,const uchar *) const override; - void sort_string(uchar *buff,uint length) override; - uint32 pack_length() const override { return (uint32) packlength; } - void store_type(ulonglong value); - void sql_type(String &str) const override; - uint size_of() const override { return sizeof *this; } - uint pack_length_from_metadata(uint field_metadata) const override - { return (field_metadata & 0x00ff); } - uint row_pack_length() const override { return pack_length(); } - bool zero_pack() const override { return false; } - bool optimize_range(uint, uint) const override { return false; } - bool eq_def(const Field *field) const override; - bool has_charset() const override { return true; } - /* enum and set are sorted as integers */ - CHARSET_INFO *sort_charset() const override { return &my_charset_bin; } - uint decimals() const override { return 0; } - const TYPELIB *get_typelib() const override { return typelib; } - - uchar *pack(uchar *to, const uchar *from, uint max_length) override; - const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, - uint param_data) override; - - bool can_optimize_keypart_ref(const Item_bool_func *cond, - const Item *item) const override; - bool can_optimize_group_min_max(const Item_bool_func *, const Item *) - const override - { - /* - Can't use GROUP_MIN_MAX optimization for ENUM and SET, - because the values are stored as numbers in index, - while MIN() and MAX() work as strings. - It would return the records with min and max enum numeric indexes. - "Bug#45300 MAX() and ENUM type" should be fixed first. - */ - return false; - } - bool can_optimize_range(const Item_bool_func *cond, - const Item *item, - bool is_eq_func) const override; - Binlog_type_info binlog_type_info() const override; -private: - bool is_equal(const Column_definition &new_field) const override; -}; - - -class Field_set final :public Field_enum { -public: - Field_set(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - uint32 packlength_arg, - const TYPELIB *typelib_arg, const DTCollation &collation) - :Field_enum(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, - unireg_check_arg, field_name_arg, - packlength_arg, - typelib_arg, collation), - empty_set_string("", 0, collation.collation) - { - flags=(flags & ~ENUM_FLAG) | SET_FLAG; - } - void make_empty_rec_reset(THD *thd) override - { - Field::make_empty_rec_reset(thd); - } - - int store_field(Field *from) override { return from->save_in_field(this); } - int store(const char *to,size_t length,CHARSET_INFO *charset) override; - int store(double nr) override - { return Field_set::store((longlong) nr, FALSE); } - int store(longlong nr, bool unsigned_val) override; - - bool zero_pack() const override { return true; } - String *val_str(String *, String *) override; - void sql_type(String &str) const override; - uint size_of() const override { return sizeof *this; } - const Type_handler *type_handler() const override - { return &type_handler_set; } - bool has_charset() const override { return true; } - Binlog_type_info binlog_type_info() const override; -private: - const String empty_set_string; -}; - - -/* - Note: - To use Field_bit::cmp_binary() you need to copy the bits stored in - the beginning of the record (the NULL bytes) to each memory you - want to compare (where the arguments point). - - This is the reason: - - Field_bit::cmp_binary() is only implemented in the base class - (Field::cmp_binary()). - - Field::cmp_binary() currently uses pack_length() to calculate how - long the data is. - - pack_length() includes size of the bits stored in the NULL bytes - of the record. -*/ -class Field_bit :public Field { -public: - uchar *bit_ptr; // position in record where 'uneven' bits store - uchar bit_ofs; // offset to 'uneven' high bits - uint bit_len; // number of 'uneven' high bits - uint bytes_in_rec; - Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg); - const Type_handler *type_handler() const override - { return &type_handler_bit; } - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BIT; } - uint16 key_part_flag() const override { return HA_BIT_PART; } - uint32 key_length() const override - { return (uint32) (field_length + 7) / 8; } - uint32 max_data_length() const override { return key_length(); } - uint32 max_display_length() const override { return field_length; } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - CHARSET_INFO *charset() const override { return &my_charset_bin; } - const DTCollation & dtcollation() const override; - Information_schema_numeric_attributes - information_schema_numeric_attributes() const override - { - return Information_schema_numeric_attributes(field_length); - } - void update_data_type_statistics(Data_type_statistics *st) const override - { - st->m_uneven_bit_length+= field_length & 7; - } - uint size_of() const override { return sizeof *this; } - int reset() override - { - bzero(ptr, bytes_in_rec); - if (bit_ptr && (bit_len > 0)) // reset odd bits among null bits - clr_rec_bits(bit_ptr, bit_ofs, bit_len); - return 0; - } - Copy_func *get_copy_func(const Field *from) const override - { - if (from->cmp_type() == DECIMAL_RESULT) - return do_field_decimal; - return do_field_int; - } - int save_in_field(Field *to) override { return to->store(val_int(), true); } - bool memcpy_field_possible(const Field *from) const override{ return false; } - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_decimal(const my_decimal *) override; - double val_real() override; - longlong val_int() override; - String *val_str(String*, String *) override; - bool str_needs_quotes() const override { return true; } - my_decimal *val_decimal(my_decimal *) override; - bool val_bool() override { return val_int() != 0; } - int cmp(const uchar *a, const uchar *b) const override - { - DBUG_ASSERT(ptr == a || ptr == b); - if (ptr == a) - return Field_bit::key_cmp(b, bytes_in_rec + MY_TEST(bit_len)); - else - return Field_bit::key_cmp(a, bytes_in_rec + MY_TEST(bit_len)) * -1; - } - int cmp_binary_offset(uint row_offset) override - { return cmp_offset(row_offset); } - int cmp_prefix(const uchar *a, const uchar *b, - size_t max_length) const override; - int key_cmp(const uchar *a, const uchar *b) const override - { return cmp_binary((uchar *) a, (uchar *) b); } - int key_cmp(const uchar *str, uint length) const override; - int cmp_offset(my_ptrdiff_t row_offset) override; - bool update_min(Field *min_val, bool force_update) override - { - longlong val= val_int(); - bool update_fl= force_update || val < min_val->val_int(); - if (update_fl) - { - min_val->set_notnull(); - min_val->store(val, FALSE); - } - return update_fl; - } - bool update_max(Field *max_val, bool force_update) override - { - longlong val= val_int(); - bool update_fl= force_update || val > max_val->val_int(); - if (update_fl) - { - max_val->set_notnull(); - max_val->store(val, FALSE); - } - return update_fl; - } - void store_field_value(uchar *val, uint) override - { - store(*((longlong *)val), TRUE); - } - double pos_in_interval(Field *min, Field *max) override - { - return pos_in_interval_val_real(min, max); - } - void get_image(uchar *buff, uint length, - const uchar *ptr_arg, CHARSET_INFO *cs) const override - { get_key_image(buff, length, ptr_arg, itRAW); } - void set_image(const uchar *buff,uint length, CHARSET_INFO *cs) override - { Field_bit::store((char *) buff, length, cs); } - uint get_key_image(uchar *buff, uint length, - const uchar *ptr_arg, imagetype type) const override; - void set_key_image(const uchar *buff, uint length) override - { Field_bit::store((char*) buff, length, &my_charset_bin); } - void sort_string(uchar *buff, uint length) override - { get_key_image(buff, length, ptr, itRAW); } - uint32 pack_length() const override - { return (uint32) (field_length + 7) / 8; } - uint32 pack_length_in_rec() const override { return bytes_in_rec; } - uint pack_length_from_metadata(uint field_metadata) const override; - uint row_pack_length() const override - { return (bytes_in_rec + ((bit_len > 0) ? 1 : 0)); } - bool compatible_field_size(uint metadata, const Relay_log_info *rli, - uint16 mflags, int *order_var) const override; - void sql_type(String &str) const override; - uchar *pack(uchar *to, const uchar *from, uint max_length) override; - const uchar *unpack(uchar *to, const uchar *from, - const uchar *from_end, uint param_data) override; - int set_default() override; - - Field *new_key_field(MEM_ROOT *root, TABLE *new_table, - uchar *new_ptr, uint32 length, - uchar *new_null_ptr, uint new_null_bit) override; - void set_bit_ptr(uchar *bit_ptr_arg, uchar bit_ofs_arg) - { - bit_ptr= bit_ptr_arg; - bit_ofs= bit_ofs_arg; - } - bool eq(Field *field) override - { - return (Field::eq(field) && - bit_ptr == ((Field_bit *)field)->bit_ptr && - bit_ofs == ((Field_bit *)field)->bit_ofs); - } - bool is_equal(const Column_definition &new_field) const override; - void move_field_offset(my_ptrdiff_t ptr_diff) override - { - Field::move_field_offset(ptr_diff); - bit_ptr= ADD_TO_PTR(bit_ptr, ptr_diff, uchar*); - } - void hash(ulong *nr, ulong *nr2) override; - - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, - const Item_bool_func *cond, - scalar_comparison_op op, Item *value) override - { - return get_mm_leaf_int(param, key_part, cond, op, value, true); - } - void print_key_value(String *out, uint32 length) override - { - val_int_as_str(out, 1); - } - /** - Save the field metadata for bit fields. - Saves the bit length in the first byte and bytes in record in the - second byte of the field metadata array at index of *metadata_ptr and - *(metadata_ptr + 1). - - @param metadata_ptr First byte of field metadata - - @returns number of bytes written to metadata_ptr - */ - Binlog_type_info binlog_type_info() const override - { - DBUG_PRINT("debug", ("bit_len: %d, bytes_in_rec: %d", - bit_len, bytes_in_rec)); - /* - Since this class and Field_bit_as_char have different ideas of - what should be stored here, we compute the values of the metadata - explicitly using the field_length. - */ - return Binlog_type_info(type(), - static_cast((field_length & 7) | - ((field_length / 8) << 8)), 2); - } - -private: - size_t do_last_null_byte() const override; -}; - - -/** - BIT field represented as chars for non-MyISAM tables. - - @todo The inheritance relationship is backwards since Field_bit is - an extended version of Field_bit_as_char and not the other way - around. Hence, we should refactor it to fix the hierarchy order. - */ -class Field_bit_as_char final :public Field_bit { -public: - Field_bit_as_char(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, - uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg); - enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } - uint size_of() const override { return sizeof *this; } - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - int store(double nr) override { return Field_bit::store(nr); } - int store(longlong nr, bool unsigned_val) override - { return Field_bit::store(nr, unsigned_val); } - void sql_type(String &str) const override; -}; - - -class Field_row final :public Field_null -{ - class Virtual_tmp_table *m_table; -public: - Field_row(uchar *ptr_arg, const LEX_CSTRING *field_name_arg) - :Field_null(ptr_arg, 0, Field::NONE, field_name_arg, &my_charset_bin), - m_table(NULL) - {} - ~Field_row(); - en_fieldtype tmp_engine_column_type(bool use_packed_rows) const - { - DBUG_ASSERT(0); - return Field::tmp_engine_column_type(use_packed_rows); - } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const - { - DBUG_ASSERT(0); - return CONV_TYPE_IMPOSSIBLE; - } - Virtual_tmp_table **virtual_tmp_table_addr() { return &m_table; } - bool sp_prepare_and_store_item(THD *thd, Item **value); -}; - - -extern const LEX_CSTRING null_clex_str; - -class Column_definition_attributes -{ -public: - /* - At various stages in execution this can be length of field in bytes or - max number of characters. - */ - ulonglong length; - uint decimals; - Field::utype unireg_check; - const TYPELIB *interval; // Which interval to use - CHARSET_INFO *charset; - uint32 srid; - uint pack_flag; - Column_definition_attributes() - :length(0), - decimals(0), - unireg_check(Field::NONE), - interval(NULL), - charset(&my_charset_bin), - srid(0), - pack_flag(0) - { } - Column_definition_attributes(const Field *field); - Column_definition_attributes(const Type_all_attributes &attr); - Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root, - const Record_addr *rec, - const Type_handler *handler, - const LEX_CSTRING *field_name, - uint32 flags) const; - uint temporal_dec(uint intlen) const - { - return (uint) (length > intlen ? length - intlen - 1 : 0); - } - uint pack_flag_to_pack_length() const; - void frm_pack_basic(uchar *buff) const; - void frm_pack_charset(uchar *buff) const; - void frm_pack_numeric_with_dec(uchar *buff) const; - void frm_unpack_basic(const uchar *buff); - bool frm_unpack_charset(TABLE_SHARE *share, const uchar *buff); - bool frm_unpack_numeric_with_dec(TABLE_SHARE *share, const uchar *buff); - bool frm_unpack_temporal_with_dec(TABLE_SHARE *share, uint intlen, - const uchar *buff); - void set_length_and_dec(const Lex_length_and_dec_st &attr); -}; - - -/* - Create field class for CREATE TABLE -*/ -class Column_definition: public Sql_alloc, - public Type_handler_hybrid_field_type, - public Column_definition_attributes -{ - /** - Create "interval" from "interval_list". - @param mem_root - memory root to create the TYPELIB - instance and its values on - @param reuse_interval_list_values - determines if TYPELIB can reuse strings - from interval_list, or should always - allocate a copy on mem_root, even if - character set conversion is not needed - @retval false on success - @retval true on error (bad values, or EOM) - */ - bool create_interval_from_interval_list(MEM_ROOT *mem_root, - bool reuse_interval_list_values); - - /* - Calculate TYPELIB (set or enum) max and total lengths - - @param cs charset+collation pair of the interval - @param max_length length of the longest item - @param tot_length sum of the item lengths - - After this method call: - - ENUM uses max_length - - SET uses tot_length. - */ - void calculate_interval_lengths(uint32 *max_length, uint32 *tot_length) - { - const char **pos; - uint *len; - *max_length= *tot_length= 0; - for (pos= interval->type_names, len= interval->type_lengths; - *pos ; pos++, len++) - { - size_t length= charset->numchars(*pos, *pos + *len); - DBUG_ASSERT(length < UINT_MAX32); - *tot_length+= (uint) length; - set_if_bigger(*max_length, (uint32)length); - } - } - bool prepare_stage1_check_typelib_default(); - bool prepare_stage1_convert_default(THD *, MEM_ROOT *, CHARSET_INFO *to); - const Type_handler *field_type() const; // Prevent using this - Compression_method *compression_method_ptr; -public: - LEX_CSTRING field_name; - LEX_CSTRING comment; // Comment for field - enum enum_column_versioning - { - VERSIONING_NOT_SET, - WITH_VERSIONING, - WITHOUT_VERSIONING - }; - Item *on_update; // ON UPDATE NOW() - field_visibility_t invisible; - /* - The value of `length' as set by parser: is the number of characters - for most of the types, or of bytes for BLOBs or numeric types. - */ - uint32 char_length; - uint flags, pack_length; - List interval_list; - engine_option_value *option_list; - - - /* - This is additinal data provided for any computed(virtual) field. - In particular it includes a pointer to the item by which this field - can be computed from other fields. - */ - Virtual_column_info - *vcol_info, // Virtual field - *default_value, // Default value - *check_constraint; // Check constraint - - enum_column_versioning versioning; - - Table_period_info *period; - - Column_definition() - :Type_handler_hybrid_field_type(&type_handler_null), - compression_method_ptr(0), - comment(null_clex_str), - on_update(NULL), invisible(VISIBLE), char_length(0), - flags(0), pack_length(0), - option_list(NULL), - vcol_info(0), default_value(0), check_constraint(0), - versioning(VERSIONING_NOT_SET), period(NULL) - { - interval_list.empty(); - } - - Column_definition(THD *thd, Field *field, Field *orig_field); - bool set_attributes(THD *thd, - const Lex_field_type_st &attr, - CHARSET_INFO *cs, - column_definition_type_t type); - void create_length_to_internal_length_null() - { - DBUG_ASSERT(length == 0); - pack_length= 0; - } - void create_length_to_internal_length_simple() - { - pack_length= type_handler()->calc_pack_length((uint32) length); - } - void create_length_to_internal_length_string() - { - length*= charset->mbmaxlen; - if (real_field_type() == MYSQL_TYPE_VARCHAR && compression_method()) - length++; - set_if_smaller(length, UINT_MAX32); - pack_length= type_handler()->calc_pack_length((uint32) length); - } - void create_length_to_internal_length_typelib() - { - /* Pack_length already calculated in sql_parse.cc */ - length*= charset->mbmaxlen; - } - bool vers_sys_field() const - { - return flags & (VERS_SYS_START_FLAG | VERS_SYS_END_FLAG); - } - void create_length_to_internal_length_bit(); - void create_length_to_internal_length_newdecimal(); - - /** - Prepare a SET/ENUM field. - Create "interval" from "interval_list" if needed, and adjust "length". - @param mem_root - Memory root to allocate TYPELIB and - its values on - @param reuse_interval_list_values - determines if TYPELIB can reuse value - buffers from interval_list, or should - always allocate a copy on mem_root, - even if character set conversion - is not needed - */ - bool prepare_interval_field(MEM_ROOT *mem_root, - bool reuse_interval_list_values); - - void prepare_interval_field_calc_length() - { - uint32 field_length, dummy; - if (real_field_type() == MYSQL_TYPE_SET) - { - calculate_interval_lengths(&dummy, &field_length); - length= field_length + (interval->count - 1); - } - else /* MYSQL_TYPE_ENUM */ - { - calculate_interval_lengths(&field_length, &dummy); - length= field_length; - } - set_if_smaller(length, MAX_FIELD_WIDTH - 1); - } - - bool prepare_blob_field(THD *thd); - - bool sp_prepare_create_field(THD *thd, MEM_ROOT *mem_root); - - bool prepare_stage1(THD *thd, MEM_ROOT *mem_root, - handler *file, ulonglong table_flags); - bool prepare_stage1_typelib(THD *thd, MEM_ROOT *mem_root, - handler *file, ulonglong table_flags); - bool prepare_stage1_string(THD *thd, MEM_ROOT *mem_root, - handler *file, ulonglong table_flags); - bool prepare_stage1_bit(THD *thd, MEM_ROOT *mem_root, - handler *file, ulonglong table_flags); - - void redefine_stage1_common(const Column_definition *dup_field, - const handler *file, - const Schema_specification_st *schema); - bool redefine_stage1(const Column_definition *dup_field, const handler *file, - const Schema_specification_st *schema) - { - const Type_handler *handler= dup_field->type_handler(); - return handler->Column_definition_redefine_stage1(this, dup_field, - file, schema); - } - bool prepare_stage2(handler *handler, ulonglong table_flags); - bool prepare_stage2_blob(handler *handler, - ulonglong table_flags, uint field_flags); - bool prepare_stage2_varchar(ulonglong table_flags); - bool prepare_stage2_typelib(const char *type_name, uint field_flags, - uint *dup_val_count); - uint pack_flag_numeric() const; - uint sign_length() const { return flags & UNSIGNED_FLAG ? 0 : 1; } - bool check_length(uint mysql_errno, uint max_allowed_length) const; - bool fix_attributes_real(uint default_length); - bool fix_attributes_int(uint default_length); - bool fix_attributes_decimal(); - bool fix_attributes_temporal_with_time(uint int_part_length); - bool fix_attributes_bit(); - - bool check(THD *thd); - bool validate_check_constraint(THD *thd); - - bool stored_in_db() const { return !vcol_info || vcol_info->stored_in_db; } - - ha_storage_media field_storage_type() const - { - return (ha_storage_media) - ((flags >> FIELD_FLAGS_STORAGE_MEDIA) & 3); - } - - column_format_type column_format() const - { - return (column_format_type) - ((flags >> FIELD_FLAGS_COLUMN_FORMAT) & 3); - } - - bool has_default_function() const - { - return unireg_check != Field::NONE; - } - - Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root, - const Record_addr *addr, - const LEX_CSTRING *field_name_arg) const - { - return Column_definition_attributes::make_field(share, mem_root, addr, - type_handler(), - field_name_arg, flags); - } - Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root, - const LEX_CSTRING *field_name_arg) const - { - Record_addr addr(true); - return make_field(share, mem_root, &addr, field_name_arg); - } - /* Return true if default is an expression that must be saved explicitely */ - bool has_default_expression(); - - bool has_default_now_unireg_check() const - { - return unireg_check == Field::TIMESTAMP_DN_FIELD - || unireg_check == Field::TIMESTAMP_DNUN_FIELD; - } - - void set_type(const Column_definition &other) - { - set_handler(other.type_handler()); - length= other.length; - char_length= other.char_length; - decimals= other.decimals; - flags= other.flags; - pack_length= other.pack_length; - unireg_check= other.unireg_check; - interval= other.interval; - charset= other.charset; - srid= other.srid; - pack_flag= other.pack_flag; - } - - // Replace the entire value by another definition - void set_column_definition(const Column_definition *def) - { - *this= *def; - } - bool set_compressed(const char *method); - bool set_compressed_deprecated(THD *thd, const char *method); - bool set_compressed_deprecated_column_attribute(THD *thd, - const char *pos, - const char *method); - void set_compression_method(Compression_method *compression_method_arg) - { compression_method_ptr= compression_method_arg; } - Compression_method *compression_method() const - { return compression_method_ptr; } - - bool check_vcol_for_key(THD *thd) const; -}; - - -/** - List of ROW element definitions, e.g.: - DECLARE a ROW(a INT,b VARCHAR(10)) -*/ -class Row_definition_list: public List -{ -public: - inline bool eq_name(const Spvar_definition *def, const LEX_CSTRING *name) const; - /** - Find a ROW field by name. - @param [IN] name - the name - @param [OUT] offset - if the ROW field found, its offset it returned here - @retval NULL - the ROW field was not found - @retval !NULL - the pointer to the found ROW field - */ - Spvar_definition *find_row_field_by_name(const LEX_CSTRING *name, uint *offset) const - { - // Cast-off the "const" qualifier - List_iterator it(*((List*)this)); - Spvar_definition *def; - for (*offset= 0; (def= it++); (*offset)++) - { - if (eq_name(def, name)) - return def; - } - return 0; - } - static Row_definition_list *make(MEM_ROOT *mem_root, Spvar_definition *var) - { - Row_definition_list *list; - if (!(list= new (mem_root) Row_definition_list())) - return NULL; - return list->push_back(var, mem_root) ? NULL : list; - } - bool append_uniq(MEM_ROOT *thd, Spvar_definition *var); - bool adjust_formal_params_to_actual_params(THD *thd, List *args); - bool adjust_formal_params_to_actual_params(THD *thd, - Item **args, uint arg_count); - bool resolve_type_refs(THD *); -}; - -/** - This class is used during a stored routine or a trigger execution, - at sp_rcontext::create() time. - Currently it can represent: - - variables with explicit data types: DECLARE a INT; - - variables with data type references: DECLARE a t1.a%TYPE; - - ROW type variables - - Notes: - - Scalar variables have m_field_definitions==NULL. - - ROW variables are defined as having MYSQL_TYPE_NULL, - with a non-empty m_field_definitions. - - Data type references to other object types will be added soon, e.g.: - - DECLARE a table_name%ROWTYPE; - - DECLARE a cursor_name%ROWTYPE; - - DECLARE a record_name%TYPE; - - DECLARE a variable_name%TYPE; -*/ -class Spvar_definition: public Column_definition -{ - Qualified_column_ident *m_column_type_ref; // for %TYPE - Table_ident *m_table_rowtype_ref; // for table%ROWTYPE - bool m_cursor_rowtype_ref; // for cursor%ROWTYPE - uint m_cursor_rowtype_offset; // for cursor%ROWTYPE - Row_definition_list *m_row_field_definitions; // for ROW -public: - Spvar_definition() - :m_column_type_ref(NULL), - m_table_rowtype_ref(NULL), - m_cursor_rowtype_ref(false), - m_cursor_rowtype_offset(0), - m_row_field_definitions(NULL) - { } - Spvar_definition(THD *thd, Field *field) - :Column_definition(thd, field, NULL), - m_column_type_ref(NULL), - m_table_rowtype_ref(NULL), - m_cursor_rowtype_ref(false), - m_cursor_rowtype_offset(0), - m_row_field_definitions(NULL) - { } - const Type_handler *type_handler() const - { - return Type_handler_hybrid_field_type::type_handler(); - } - bool is_column_type_ref() const { return m_column_type_ref != 0; } - bool is_table_rowtype_ref() const { return m_table_rowtype_ref != 0; } - bool is_cursor_rowtype_ref() const { return m_cursor_rowtype_ref; } - bool is_explicit_data_type() const - { - return !is_column_type_ref() && - !is_table_rowtype_ref() && - !is_cursor_rowtype_ref(); - } - Qualified_column_ident *column_type_ref() const - { - return m_column_type_ref; - } - void set_column_type_ref(Qualified_column_ident *ref) - { - m_column_type_ref= ref; - } - - Table_ident *table_rowtype_ref() const - { - return m_table_rowtype_ref; - } - void set_table_rowtype_ref(Table_ident *ref) - { - DBUG_ASSERT(ref); - set_handler(&type_handler_row); - m_table_rowtype_ref= ref; - } - - uint cursor_rowtype_offset() const - { - return m_cursor_rowtype_offset; - } - void set_cursor_rowtype_ref(uint offset) - { - set_handler(&type_handler_row); - m_cursor_rowtype_ref= true; - m_cursor_rowtype_offset= offset; - } - - /* - Find a ROW field by name. - See Row_field_list::find_row_field_by_name() for details. - */ - Spvar_definition *find_row_field_by_name(const LEX_CSTRING *name, uint *offset) const - { - DBUG_ASSERT(m_row_field_definitions); - return m_row_field_definitions->find_row_field_by_name(name, offset); - } - uint is_row() const - { - return m_row_field_definitions != NULL; - } - // Check if "this" defines a ROW variable with n elements - uint is_row(uint n) const - { - return m_row_field_definitions != NULL && - m_row_field_definitions->elements == n; - } - Row_definition_list *row_field_definitions() const - { - return m_row_field_definitions; - } - void set_row_field_definitions(Row_definition_list *list) - { - DBUG_ASSERT(list); - set_handler(&type_handler_row); - m_row_field_definitions= list; - } - -}; - - -inline bool Row_definition_list::eq_name(const Spvar_definition *def, - const LEX_CSTRING *name) const -{ - return def->field_name.length == name->length && my_strcasecmp(system_charset_info, def->field_name.str, name->str) == 0; -} - - -class Create_field :public Column_definition -{ -public: - LEX_CSTRING change; // If done with alter table - LEX_CSTRING after; // Put column after this one - Field *field; // For alter table - const TYPELIB *save_interval; // Temporary copy for the above - // Used only for UCS2 intervals - - /** structure with parsed options (for comparing fields in ALTER TABLE) */ - ha_field_option_struct *option_struct; - uint offset; - uint8 interval_id; - bool create_if_not_exists; // Used in ALTER TABLE IF NOT EXISTS - - Create_field(): - Column_definition(), - field(0), option_struct(NULL), - create_if_not_exists(false) - { - change= after= null_clex_str; - } - Create_field(THD *thd, Field *old_field, Field *orig_field): - Column_definition(thd, old_field, orig_field), - change(old_field->field_name), - field(old_field), option_struct(old_field->option_struct), - create_if_not_exists(false) - { - after= null_clex_str; - } - /* Used to make a clone of this object for ALTER/CREATE TABLE */ - Create_field *clone(MEM_ROOT *mem_root) const; -}; - - -/* - A class for sending info to the client -*/ - -class Send_field :public Sql_alloc, - public Type_handler_hybrid_field_type, - public Send_field_extended_metadata -{ -public: - LEX_CSTRING db_name; - LEX_CSTRING table_name, org_table_name; - LEX_CSTRING col_name, org_col_name; - ulong length; - uint flags, decimals; - Send_field(Field *field) - { - field->make_send_field(this); - DBUG_ASSERT(table_name.str != 0); - normalize(); - } - Send_field(THD *thd, Item *item); - Send_field(Field *field, - const LEX_CSTRING &db_name_arg, - const LEX_CSTRING &table_name_arg) - :Type_handler_hybrid_field_type(field->type_handler()), - db_name(db_name_arg), - table_name(table_name_arg), - org_table_name(table_name_arg), - col_name(field->field_name), - org_col_name(field->field_name), - length(field->field_length), - flags(field->table->maybe_null ? - (field->flags & ~NOT_NULL_FLAG) : field->flags), - decimals(field->decimals()) - { - normalize(); - } - -private: - void normalize() - { - /* limit number of decimals for float and double */ - if (type_handler()->field_type() == MYSQL_TYPE_FLOAT || - type_handler()->field_type() == MYSQL_TYPE_DOUBLE) - set_if_smaller(decimals, FLOATING_POINT_DECIMALS); - } -public: - // This should move to Type_handler eventually - uint32 max_char_length(CHARSET_INFO *cs) const - { - return type_handler()->field_type() >= MYSQL_TYPE_TINY_BLOB && - type_handler()->field_type() <= MYSQL_TYPE_BLOB - ? static_cast(length / cs->mbminlen) - : static_cast(length / cs->mbmaxlen); - } - uint32 max_octet_length(CHARSET_INFO *from, CHARSET_INFO *to) const - { - /* - For TEXT/BLOB columns, field_length describes the maximum data - length in bytes. There is no limit to the number of characters - that a TEXT column can store, as long as the data fits into - the designated space. - For the rest of textual columns, field_length is evaluated as - char_count * mbmaxlen, where character count is taken from the - definition of the column. In other words, the maximum number - of characters here is limited by the column definition. - - When one has a LONG TEXT column with a single-byte - character set, and the connection character set is multi-byte, the - client may get fields longer than UINT_MAX32, due to - -> conversion. - In that case column max length would not fit into the 4 bytes - reserved for it in the protocol. So we cut it here to UINT_MAX32. - */ - return char_to_byte_length_safe(max_char_length(from), to->mbmaxlen); - } - - // This should move to Type_handler eventually - bool is_sane_float() const - { - return (decimals <= FLOATING_POINT_DECIMALS || - (type_handler()->field_type() != MYSQL_TYPE_FLOAT && - type_handler()->field_type() != MYSQL_TYPE_DOUBLE)); - } - bool is_sane_signess() const - { - if (type_handler() == type_handler()->type_handler_signed() && - type_handler() == type_handler()->type_handler_unsigned()) - return true; // Any signess is allowed, e.g. DOUBLE, DECIMAL - /* - We are here e.g. in case of INT data type. - The UNSIGNED_FLAG bit must match in flags and in the type handler. - */ - return ((bool) (flags & UNSIGNED_FLAG)) == type_handler()->is_unsigned(); - } - bool is_sane() const - { - return is_sane_float() && is_sane_signess(); - } -}; - - -/* - A class for quick copying data to fields -*/ - -class Copy_field :public Sql_alloc { -public: - uchar *from_ptr,*to_ptr; - uchar *from_null_ptr,*to_null_ptr; - bool *null_row; - uint from_bit,to_bit; - /** - Number of bytes in the fields pointed to by 'from_ptr' and - 'to_ptr'. Usually this is the number of bytes that are copied from - 'from_ptr' to 'to_ptr'. - - For variable-length fields (VARCHAR), the first byte(s) describe - the actual length of the text. For VARCHARs with length - < 256 there is 1 length byte - >= 256 there is 2 length bytes - Thus, if from_field is VARCHAR(10), from_length (and in most cases - to_length) is 11. For VARCHAR(1024), the length is 1026. @see - Field_varstring::length_bytes - - Note that for VARCHARs, do_copy() will be do_varstring*() which - only copies the length-bytes (1 or 2) + the actual length of the - text instead of from/to_length bytes. - */ - uint from_length,to_length; - Field *from_field,*to_field; - String tmp; // For items - - Copy_field() {} - ~Copy_field() {} - void set(Field *to,Field *from,bool save); // Field to field - void set(uchar *to,Field *from); // Field to string - void (*do_copy)(Copy_field *); - void (*do_copy2)(Copy_field *); // Used to handle null values -}; - - -uint pack_length_to_packflag(uint type); -enum_field_types get_blob_type_from_length(ulong length); -int set_field_to_null(Field *field); -int set_field_to_null_with_conversions(Field *field, bool no_conversions); -int convert_null_to_field_value_or_error(Field *field); -bool check_expression(Virtual_column_info *vcol, const LEX_CSTRING *name, - enum_vcol_info_type type, Alter_info *alter_info= NULL); - -/* - The following are for the interface with the .frm file -*/ - -#define FIELDFLAG_DECIMAL 1U -#define FIELDFLAG_BINARY 1U // Shares same flag -#define FIELDFLAG_NUMBER 2U -#define FIELDFLAG_ZEROFILL 4U -#define FIELDFLAG_PACK 120U // Bits used for packing -#define FIELDFLAG_INTERVAL 256U // mangled with decimals! -#define FIELDFLAG_BITFIELD 512U // mangled with decimals! -#define FIELDFLAG_BLOB 1024U // mangled with decimals! -#define FIELDFLAG_GEOM 2048U // mangled with decimals! - -#define FIELDFLAG_TREAT_BIT_AS_CHAR 4096U /* use Field_bit_as_char */ -#define FIELDFLAG_LONG_DECIMAL 8192U -#define FIELDFLAG_NO_DEFAULT 16384U /* sql */ -#define FIELDFLAG_MAYBE_NULL 32768U // sql -#define FIELDFLAG_HEX_ESCAPE 0x10000U -#define FIELDFLAG_PACK_SHIFT 3 -#define FIELDFLAG_DEC_SHIFT 8 -#define FIELDFLAG_MAX_DEC 63U - -#define FIELDFLAG_DEC_MASK 0x3F00U - -#define MTYP_TYPENR(type) ((type) & 127U) // Remove bits from type - -#define f_is_dec(x) ((x) & FIELDFLAG_DECIMAL) -#define f_is_num(x) ((x) & FIELDFLAG_NUMBER) -#define f_is_zerofill(x) ((x) & FIELDFLAG_ZEROFILL) -#define f_is_packed(x) ((x) & FIELDFLAG_PACK) -#define f_packtype(x) (((x) >> FIELDFLAG_PACK_SHIFT) & 15) -#define f_decimals(x) ((uint8) (((x) >> FIELDFLAG_DEC_SHIFT) & FIELDFLAG_MAX_DEC)) -#define f_is_alpha(x) (!f_is_num(x)) -#define f_is_binary(x) ((x) & FIELDFLAG_BINARY) // 4.0- compatibility -#define f_is_enum(x) (((x) & (FIELDFLAG_INTERVAL | FIELDFLAG_NUMBER)) == FIELDFLAG_INTERVAL) -#define f_is_bitfield(x) (((x) & (FIELDFLAG_BITFIELD | FIELDFLAG_NUMBER)) == FIELDFLAG_BITFIELD) -#define f_is_blob(x) (((x) & (FIELDFLAG_BLOB | FIELDFLAG_NUMBER)) == FIELDFLAG_BLOB) -#define f_is_geom(x) (((x) & (FIELDFLAG_GEOM | FIELDFLAG_NUMBER)) == FIELDFLAG_GEOM) -#define f_settype(x) (((uint) (x)) << FIELDFLAG_PACK_SHIFT) -#define f_maybe_null(x) ((x) & FIELDFLAG_MAYBE_NULL) -#define f_no_default(x) ((x) & FIELDFLAG_NO_DEFAULT) -#define f_bit_as_char(x) ((x) & FIELDFLAG_TREAT_BIT_AS_CHAR) -#define f_is_hex_escape(x) ((x) & FIELDFLAG_HEX_ESCAPE) -#define f_visibility(x) (static_cast ((x) & INVISIBLE_MAX_BITS)) - -inline -ulonglong TABLE::vers_end_id() const -{ - DBUG_ASSERT(versioned(VERS_TRX_ID)); - return static_cast(vers_end_field()->val_int()); -} - -inline -ulonglong TABLE::vers_start_id() const -{ - DBUG_ASSERT(versioned(VERS_TRX_ID)); - return static_cast(vers_start_field()->val_int()); -} - - -#endif /* FIELD_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/field_comp.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/field_comp.h deleted file mode 100644 index 7eb8ab1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/field_comp.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef FIELD_COMP_H_INCLUDED -#define FIELD_COMP_H_INCLUDED -/* Copyright (C) 2017 MariaDB Foundation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - -#define MAX_COMPRESSION_METHODS 16 - -struct Compression_method -{ - const char *name; - uint (*compress)(THD *thd, char *to, const char *from, uint length); - int (*uncompress)(String *to, const uchar *from, uint from_length, - uint field_length); -}; - - -extern Compression_method compression_methods[MAX_COMPRESSION_METHODS]; -#define zlib_compression_method (&compression_methods[8]) - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/filesort.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/filesort.h deleted file mode 100644 index 9f71da0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/filesort.h +++ /dev/null @@ -1,231 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef FILESORT_INCLUDED -#define FILESORT_INCLUDED - -#include "my_base.h" /* ha_rows */ -#include "sql_alloc.h" -#include "filesort_utils.h" - -class SQL_SELECT; -class THD; -struct TABLE; -class Filesort_tracker; -struct SORT_FIELD; -struct SORT_FIELD_ATTR; -typedef struct st_order ORDER; -class JOIN; -class Addon_fields; -class Sort_keys; - - -/** - Sorting related info. - To be extended by another WL to include complete filesort implementation. -*/ -class Filesort: public Sql_alloc -{ -public: - /** List of expressions to order the table by */ - ORDER *order; - /** Number of records to return */ - ha_rows limit; - /** ORDER BY list with some precalculated info for filesort */ - SORT_FIELD *sortorder; - /** select to use for getting records */ - SQL_SELECT *select; - /** TRUE <=> free select on destruction */ - bool own_select; - /** true means we are using Priority Queue for order by with limit. */ - bool using_pq; - - /* - TRUE means sort operation must produce table rowids. - FALSE means that it halso has an option of producing {sort_key, - addon_fields} pairs. - */ - bool sort_positions; - - Filesort_tracker *tracker; - Sort_keys *sort_keys; - - Filesort(ORDER *order_arg, ha_rows limit_arg, bool sort_positions_arg, - SQL_SELECT *select_arg): - order(order_arg), - limit(limit_arg), - sortorder(NULL), - select(select_arg), - own_select(false), - using_pq(false), - sort_positions(sort_positions_arg), - sort_keys(NULL) - { - DBUG_ASSERT(order); - }; - - ~Filesort() { cleanup(); } - /* Prepare ORDER BY list for sorting. */ - Sort_keys* make_sortorder(THD *thd, JOIN *join, table_map first_table_bit); - -private: - void cleanup(); -}; - - -class SORT_INFO -{ - /// Buffer for sorting keys. - Filesort_buffer filesort_buffer; - -public: - SORT_INFO() - :addon_fields(NULL), record_pointers(0), - sort_keys(NULL), - sorted_result_in_fsbuf(FALSE) - { - buffpek.str= 0; - my_b_clear(&io_cache); - } - - ~SORT_INFO(); - - void free_data() - { - close_cached_file(&io_cache); - free_addon_buff(); - my_free(record_pointers); - my_free(buffpek.str); - my_free(addon_fields); - free_sort_buffer(); - } - - void reset() - { - free_data(); - record_pointers= 0; - buffpek.str= 0; - addon_fields= 0; - sorted_result_in_fsbuf= false; - } - - void free_addon_buff(); - - IO_CACHE io_cache; /* If sorted through filesort */ - LEX_STRING buffpek; /* Buffer for buffpek structures */ - Addon_fields *addon_fields; /* Addon field descriptors */ - uchar *record_pointers; /* If sorted in memory */ - Sort_keys *sort_keys; /* Sort key descriptors*/ - - /** - If the entire result of filesort fits in memory, we skip the merge phase. - We may leave the result in filesort_buffer - (indicated by sorted_result_in_fsbuf), or we may strip away - the sort keys, and copy the sorted result into a new buffer. - @see save_index() - */ - bool sorted_result_in_fsbuf; - - /* - How many rows in final result. - Also how many rows in record_pointers, if used - */ - ha_rows return_rows; - ha_rows examined_rows; /* How many rows read */ - ha_rows found_rows; /* How many rows was accepted */ - - /** Sort filesort_buffer */ - void sort_buffer(Sort_param *param, uint count) - { filesort_buffer.sort_buffer(param, count); } - - uchar **get_sort_keys() - { return filesort_buffer.get_sort_keys(); } - - uchar *get_sorted_record(uint ix) - { return filesort_buffer.get_sorted_record(ix); } - - uchar *alloc_sort_buffer(uint num_records, uint record_length) - { return filesort_buffer.alloc_sort_buffer(num_records, record_length); } - - void free_sort_buffer() - { filesort_buffer.free_sort_buffer(); } - - bool isfull() const - { return filesort_buffer.isfull(); } - void init_record_pointers() - { filesort_buffer.init_record_pointers(); } - void init_next_record_pointer() - { filesort_buffer.init_next_record_pointer(); } - uchar *get_next_record_pointer() - { return filesort_buffer.get_next_record_pointer(); } - void adjust_next_record_pointer(uint val) - { filesort_buffer.adjust_next_record_pointer(val); } - - Bounds_checked_array get_raw_buf() - { return filesort_buffer.get_raw_buf(); } - - size_t sort_buffer_size() const - { return filesort_buffer.sort_buffer_size(); } - - bool is_allocated() const - { return filesort_buffer.is_allocated(); } - void set_sort_length(uint val) - { filesort_buffer.set_sort_length(val); } - uint get_sort_length() const - { return filesort_buffer.get_sort_length(); } - - bool has_filesort_result_in_memory() const - { - return record_pointers || sorted_result_in_fsbuf; - } - - /// Are we using "addon fields"? - bool using_addon_fields() const - { - return addon_fields != NULL; - } - - /// Are we using "packed addon fields"? - bool using_packed_addons(); - - /** - Copies (unpacks) values appended to sorted fields from a buffer back to - their regular positions specified by the Field::ptr pointers. - @param buff Buffer which to unpack the value from - */ - template - inline void unpack_addon_fields(uchar *buff); - - bool using_packed_sortkeys(); - - friend SORT_INFO *filesort(THD *thd, TABLE *table, Filesort *filesort, - Filesort_tracker* tracker, JOIN *join, - table_map first_table_bit); -}; - -SORT_INFO *filesort(THD *thd, TABLE *table, Filesort *filesort, - Filesort_tracker* tracker, JOIN *join=NULL, - table_map first_table_bit=0); - -bool filesort_use_addons(TABLE *table, uint sortlength, - uint *length, uint *fields, uint *null_fields, - uint *m_packable_length); - -void change_double_for_sort(double nr,uchar *to); -void store_length(uchar *to, uint length, uint pack_length); -void -reverse_key(uchar *to, const SORT_FIELD_ATTR *sort_field); - -#endif /* FILESORT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/filesort_utils.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/filesort_utils.h deleted file mode 100644 index 1962f14..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/filesort_utils.h +++ /dev/null @@ -1,286 +0,0 @@ -/* Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef FILESORT_UTILS_INCLUDED -#define FILESORT_UTILS_INCLUDED - -#include "my_base.h" -#include "sql_array.h" - -class Sort_param; -/* - Calculate cost of merge sort - - @param num_rows Total number of rows. - @param num_keys_per_buffer Number of keys per buffer. - @param elem_size Size of each element. - - Calculates cost of merge sort by simulating call to merge_many_buff(). - - @retval - Computed cost of merge sort in disk seeks. - - @note - Declared here in order to be able to unit test it, - since library dependencies have not been sorted out yet. - - See also comments get_merge_many_buffs_cost(). -*/ - -double get_merge_many_buffs_cost_fast(ha_rows num_rows, - ha_rows num_keys_per_buffer, - uint elem_size); - - -/** - A wrapper class around the buffer used by filesort(). - The sort buffer is a contiguous chunk of memory, - containing both records to be sorted, and pointers to said records: - - - |rec 0|record 1 |rec 2| ............ |ptr to rec2|ptr to rec1|ptr to rec0| - - Records will be inserted "left-to-right". Records are not necessarily - fixed-size, they can be packed and stored without any "gaps". - - Record pointers will be inserted "right-to-left", as a side-effect - of inserting the actual records. - - We wrap the buffer in order to be able to do lazy initialization of the - pointers: the buffer is often much larger than what we actually need. - - With this allocation scheme, and lazy initialization of the pointers, - we are able to pack variable-sized records in the buffer, - and thus possibly have space for more records than we initially estimated. - - The buffer must be kept available for multiple executions of the - same sort operation, so we have explicit allocate and free functions, - rather than doing alloc/free in CTOR/DTOR. -*/ - -class Filesort_buffer -{ -public: - Filesort_buffer() : - m_next_rec_ptr(NULL), m_rawmem(NULL), m_record_pointers(NULL), - m_sort_keys(NULL), - m_num_records(0), m_record_length(0), - m_sort_length(0), - m_size_in_bytes(0), m_idx(0) - {} - - /** Sort me... */ - void sort_buffer(const Sort_param *param, uint count); - - /** - Reverses the record pointer array, to avoid recording new results for - non-deterministic mtr tests. - */ - void reverse_record_pointers() - { - if (m_idx < 2) // There is nothing to swap. - return; - uchar **keys= get_sort_keys(); - const longlong count= m_idx - 1; - for (longlong ix= 0; ix <= count/2; ++ix) - { - uchar *tmp= keys[count - ix]; - keys[count - ix] = keys[ix]; - keys[ix]= tmp; - } - } - - /** - Initializes all the record pointers. - */ - void init_record_pointers() - { - init_next_record_pointer(); - while (m_idx < m_num_records) - (void) get_next_record_pointer(); - reverse_record_pointers(); - } - - /** - Prepares the buffer for the next batch of records to process. - */ - void init_next_record_pointer() - { - m_idx= 0; - m_next_rec_ptr= m_rawmem; - m_sort_keys= NULL; - } - - /** - @returns the number of bytes currently in use for data. - */ - size_t space_used_for_data() const - { - return m_next_rec_ptr ? m_next_rec_ptr - m_rawmem : 0; - } - - /** - @returns the number of bytes left in the buffer. - */ - size_t spaceleft() const - { - DBUG_ASSERT(m_next_rec_ptr >= m_rawmem); - const size_t spaceused= - (m_next_rec_ptr - m_rawmem) + - (static_cast(m_idx) * sizeof(uchar*)); - return m_size_in_bytes - spaceused; - } - - /** - Is the buffer full? - */ - bool isfull() const - { - if (m_idx < m_num_records) - return false; - return spaceleft() < (m_record_length + sizeof(uchar*)); - } - - /** - Where should the next record be stored? - */ - uchar *get_next_record_pointer() - { - uchar *retval= m_next_rec_ptr; - // Save the return value in the record pointer array. - m_record_pointers[-m_idx]= m_next_rec_ptr; - // Prepare for the subsequent request. - m_idx++; - m_next_rec_ptr+= m_record_length; - return retval; - } - - /** - Adjusts for actual record length. get_next_record_pointer() above was - pessimistic, and assumed that the record could not be packed. - */ - void adjust_next_record_pointer(uint val) - { - m_next_rec_ptr-= (m_record_length - val); - } - - /// Returns total size: pointer array + record buffers. - size_t sort_buffer_size() const - { - return m_size_in_bytes; - } - - bool is_allocated() const - { - return m_rawmem; - } - - /** - Allocates the buffer, but does *not* initialize pointers. - Total size = (num_records * record_length) + (num_records * sizeof(pointer)) - space for records space for pointer to records - Caller is responsible for raising an error if allocation fails. - - @param num_records Number of records. - @param record_length (maximum) size of each record. - @returns Pointer to allocated area, or NULL in case of out-of-memory. - */ - uchar *alloc_sort_buffer(uint num_records, uint record_length); - - /// Frees the buffer. - void free_sort_buffer(); - - void reset() - { - m_rawmem= NULL; - } - /** - Used to access the "right-to-left" array of record pointers as an ordinary - "left-to-right" array, so that we can pass it directly on to std::sort(). - */ - uchar **get_sort_keys() - { - if (m_idx == 0) - return NULL; - return &m_record_pointers[1 - m_idx]; - } - - /** - Gets sorted record number ix. @see get_sort_keys() - Only valid after buffer has been sorted! - */ - uchar *get_sorted_record(uint ix) - { - return m_sort_keys[ix]; - } - - /** - @returns The entire buffer, as a character array. - This is for reusing the memory for merge buffers. - */ - Bounds_checked_array get_raw_buf() - { - return Bounds_checked_array(m_rawmem, m_size_in_bytes); - } - - /** - We need an assignment operator, see filesort(). - This happens to have the same semantics as the one that would be - generated by the compiler. We still implement it here, to show shallow - assignment explicitly: we have two objects sharing the same array. - */ - Filesort_buffer &operator=(const Filesort_buffer &rhs) - { - m_next_rec_ptr= rhs.m_next_rec_ptr; - m_rawmem= rhs.m_rawmem; - m_record_pointers= rhs.m_record_pointers; - m_sort_keys= rhs.m_sort_keys; - m_num_records= rhs.m_num_records; - m_record_length= rhs.m_record_length; - m_sort_length= rhs.m_sort_length; - m_size_in_bytes= rhs.m_size_in_bytes; - m_idx= rhs.m_idx; - return *this; - } - - uint get_sort_length() const { return m_sort_length; } - void set_sort_length(uint val) { m_sort_length= val; } - -private: - uchar *m_next_rec_ptr; /// The next record will be inserted here. - uchar *m_rawmem; /// The raw memory buffer. - uchar **m_record_pointers; /// The "right-to-left" array of record pointers. - uchar **m_sort_keys; /// Caches the value of get_sort_keys() - uint m_num_records; /// Saved value from alloc_sort_buffer() - uint m_record_length; /// Saved value from alloc_sort_buffer() - uint m_sort_length; /// The length of the sort key. - size_t m_size_in_bytes; /// Size of raw buffer, in bytes. - - /** - This is the index in the "right-to-left" array of the next record to - be inserted into the buffer. It is signed, because we use it in signed - expressions like: - m_record_pointers[-m_idx]; - It is longlong rather than int, to ensure that it covers UINT_MAX32 - without any casting/warning. - */ - longlong m_idx; -}; - -int compare_packed_sort_keys(void *sort_keys, unsigned char **a, - unsigned char **b); -qsort2_cmp get_packed_keys_compare_ptr(); - -#endif // FILESORT_UTILS_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ft_global.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/ft_global.h deleted file mode 100644 index 725363c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ft_global.h +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright (c) 2000-2005, 2007 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Written by Sergei A. Golubchik, who has a shared copyright to this code */ - -/* some definitions for full-text indices */ - -/* #include "myisam.h" */ - -#ifndef _ft_global_h -#define _ft_global_h -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#define HA_FT_MAXBYTELEN 254 -#define HA_FT_MAXCHARLEN (HA_FT_MAXBYTELEN/3) - -#define DEFAULT_FTB_SYNTAX "+ -><()~*:\"\"&|" - -typedef struct st_ft_info FT_INFO; -struct _ft_vft -{ - int (*read_next)(FT_INFO *, char *); - float (*find_relevance)(FT_INFO *, uchar *, uint); - void (*close_search)(FT_INFO *); - float (*get_relevance)(FT_INFO *); - void (*reinit_search)(FT_INFO *); -}; - -typedef struct st_ft_info_ext FT_INFO_EXT; -struct _ft_vft_ext -{ - uint (*get_version)(); // Extended API version - ulonglong (*get_flags)(); - ulonglong (*get_docid)(FT_INFO_EXT *); - ulonglong (*count_matches)(FT_INFO_EXT *); -}; - -/* Flags for extended FT API */ -#define FTS_ORDERED_RESULT (1LL << 1) -#define FTS_DOCID_IN_RESULT (1LL << 2) - -#define FTS_DOC_ID_COL_NAME "FTS_DOC_ID" - -#ifndef FT_CORE -struct st_ft_info -{ - struct _ft_vft *please; /* INTERCAL style :-) */ -}; - -struct st_ft_info_ext -{ - struct _ft_vft *please; /* INTERCAL style :-) */ - struct _ft_vft_ext *could_you; -}; -#endif - -extern const char *ft_stopword_file; -extern const char *ft_precompiled_stopwords[]; - -extern ulong ft_min_word_len; -extern ulong ft_max_word_len; -extern ulong ft_query_expansion_limit; -extern const char *ft_boolean_syntax; -extern struct st_mysql_ftparser ft_default_parser; - -int ft_init_stopwords(void); -void ft_free_stopwords(void); - -#define FT_NL 0 -#define FT_BOOL 1 -#define FT_SORTED 2 -#define FT_EXPAND 4 /* query expansion */ - -FT_INFO *ft_init_search(uint,void *, uint, uchar *, size_t, - CHARSET_INFO *, uchar *); -my_bool ft_boolean_check_syntax_string(const uchar *); - -/* Internal symbols for fulltext between maria and MyISAM */ - -#define HA_FT_WTYPE HA_KEYTYPE_FLOAT -#define HA_FT_WLEN 4 -#define FT_SEGS 2 - -#define ft_sintXkorr(A) mi_sint4korr(A) -#define ft_intXstore(T,A) mi_int4store(T,A) - -extern const HA_KEYSEG ft_keysegs[FT_SEGS]; - -typedef union {int32 i; float f;} FT_WEIGTH; - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/gcalc_slicescan.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/gcalc_slicescan.h deleted file mode 100644 index b5188f2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/gcalc_slicescan.h +++ /dev/null @@ -1,607 +0,0 @@ -/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved. - Copyright (C) 2011 Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef GCALC_SLICESCAN_INCLUDED -#define GCALC_SLICESCAN_INCLUDED - -#ifndef DBUG_OFF -// #define GCALC_CHECK_WITH_FLOAT -#else -#define GCALC_DBUG_OFF -#endif /*DBUG_OFF*/ - -#ifndef GCALC_DBUG_OFF -#define GCALC_DBUG_PRINT(b) DBUG_PRINT("Gcalc", b) -#define GCALC_DBUG_ENTER(a) DBUG_ENTER("Gcalc " a) -#define GCALC_DBUG_RETURN(r) DBUG_RETURN(r) -#define GCALC_DBUG_VOID_RETURN DBUG_VOID_RETURN -#define GCALC_DBUG_ASSERT(r) DBUG_ASSERT(r) -#else -#define GCALC_DBUG_PRINT(b) do {} while(0) -#define GCALC_DBUG_ENTER(a) do {} while(0) -#define GCALC_DBUG_RETURN(r) return (r) -#define GCALC_DBUG_VOID_RETURN do {} while(0) -#define GCALC_DBUG_ASSERT(r) do {} while(0) -#endif /*GCALC_DBUG_OFF*/ - -#define GCALC_TERMINATED(state_var) (state_var && (*state_var)) -#define GCALC_SET_TERMINATED(state_var, val) state_var= val -#define GCALC_DECL_TERMINATED_STATE(varname) \ - volatile int *varname; - -/* - Gcalc_dyn_list class designed to manage long lists of same-size objects - with the possible efficiency. - It allocates fixed-size blocks of memory (blk_size specified at the time - of creation). When new object is added to the list, it occupies part of - this block until it's full. Then the new block is allocated. - Freed objects are chained to the m_free list, and if it's not empty, the - newly added object is taken from this list instead the block. -*/ - -class Gcalc_dyn_list -{ -public: - class Item - { - public: - Item *next; - }; - - Gcalc_dyn_list(size_t blk_size, size_t sizeof_item); - Gcalc_dyn_list(const Gcalc_dyn_list &dl); - ~Gcalc_dyn_list(); - Item *new_item() - { - Item *result; - if (m_free) - { - result= m_free; - m_free= m_free->next; - } - else - result= alloc_new_blk(); - - return result; - } - inline void free_item(Item *item) - { - item->next= m_free; - m_free= item; - } - inline void free_list(Item **list, Item **hook) - { - *hook= m_free; - m_free= *list; - } - - void free_list(Item *list) - { - Item **hook= &list; - while (*hook) - hook= &(*hook)->next; - free_list(&list, hook); - } - - void reset(); - void cleanup(); - -protected: - size_t m_blk_size; - size_t m_sizeof_item; - unsigned int m_points_per_blk; - void *m_first_blk; - void **m_blk_hook; - Item *m_free; - Item *m_keep; - - Item *alloc_new_blk(); - void format_blk(void* block); - inline Item *ptr_add(Item *ptr, int n_items) - { - return (Item *)(((char*)ptr) + n_items * m_sizeof_item); - } -}; - -/* Internal Gcalc coordinates to provide the precise calculations */ - -#define GCALC_DIG_BASE 1000000000 -typedef uint32 gcalc_digit_t; -typedef unsigned long long gcalc_coord2; -typedef gcalc_digit_t Gcalc_internal_coord; -#define GCALC_COORD_BASE 2 -#define GCALC_COORD_BASE2 4 -#define GCALC_COORD_BASE3 6 -#define GCALC_COORD_BASE4 8 -#define GCALC_COORD_BASE5 10 - -typedef gcalc_digit_t Gcalc_coord1[GCALC_COORD_BASE]; -typedef gcalc_digit_t Gcalc_coord2[GCALC_COORD_BASE*2]; -typedef gcalc_digit_t Gcalc_coord3[GCALC_COORD_BASE*3]; - - -void gcalc_mul_coord(Gcalc_internal_coord *result, int result_len, - const Gcalc_internal_coord *a, int a_len, - const Gcalc_internal_coord *b, int b_len); - -void gcalc_add_coord(Gcalc_internal_coord *result, int result_len, - const Gcalc_internal_coord *a, - const Gcalc_internal_coord *b); - -void gcalc_sub_coord(Gcalc_internal_coord *result, int result_len, - const Gcalc_internal_coord *a, - const Gcalc_internal_coord *b); - -int gcalc_cmp_coord(const Gcalc_internal_coord *a, - const Gcalc_internal_coord *b, int len); - -/* Internal coordinates declarations end. */ - - -typedef uint gcalc_shape_info; - -/* - Gcalc_heap represents the 'dynamic list' of Info objects, that - contain information about vertexes of all the shapes that take - part in some spatial calculation. Can become quite long. - After filled, the list is usually sorted and then walked through - in the slicescan algorithm. - The Gcalc_heap and the algorithm can only operate with two - kinds of shapes - polygon and polyline. So all the spatial - objects should be represented as sets of these two. -*/ - -class Gcalc_heap : public Gcalc_dyn_list -{ -public: - enum node_type - { - nt_shape_node, - nt_intersection, - nt_eq_node - }; - class Info : public Gcalc_dyn_list::Item - { - public: - node_type type; - union - { - struct - { - /* nt_shape_node */ - gcalc_shape_info shape; - Info *left; - Info *right; - double x,y; - Gcalc_coord1 ix, iy; - int top_node; - } shape; - struct - { - /* nt_intersection */ - /* Line p1-p2 supposed to intersect line p3-p4 */ - const Info *p1; - const Info *p2; - const Info *p3; - const Info *p4; - void *data; - int equal; - } intersection; - struct - { - /* nt_eq_node */ - const Info *node; - void *data; - } eq; - } node; - - bool is_bottom() const - { GCALC_DBUG_ASSERT(type == nt_shape_node); return !node.shape.left; } - bool is_top() const - { GCALC_DBUG_ASSERT(type == nt_shape_node); return node.shape.top_node; } - bool is_single_node() const - { return is_bottom() && is_top(); } - - void calc_xy(double *x, double *y) const; - int equal_pi(const Info *pi) const; -#ifdef GCALC_CHECK_WITH_FLOAT - void calc_xy_ld(long double *x, long double *y) const; -#endif /*GCALC_CHECK_WITH_FLOAT*/ - - Info *get_next() { return (Info *)next; } - const Info *get_next() const { return (const Info *)next; } - }; - - Gcalc_heap(size_t blk_size=8192) : - Gcalc_dyn_list(blk_size, sizeof(Info)), - m_hook(&m_first), m_n_points(0) - {} - - Gcalc_heap(const Gcalc_heap &gh) : - Gcalc_dyn_list(gh), - m_hook(&m_first), m_n_points(0) - {} - - void set_extent(double xmin, double xmax, double ymin, double ymax); - Info *new_point_info(double x, double y, gcalc_shape_info shape); - void free_point_info(Info *i, Gcalc_dyn_list::Item **i_hook); - Info *new_intersection(const Info *p1, const Info *p2, - const Info *p3, const Info *p4); - void prepare_operation(); - inline bool ready() const { return m_hook == NULL; } - Info *get_first() { return (Info *)m_first; } - const Info *get_first() const { return (const Info *)m_first; } - Gcalc_dyn_list::Item **get_last_hook() { return m_hook; } - void reset(); -#ifdef GCALC_CHECK_WITH_FLOAT - long double get_double(const Gcalc_internal_coord *c) const; -#endif /*GCALC_CHECK_WITH_FLOAT*/ - double coord_extent; - Gcalc_dyn_list::Item **get_cur_hook() { return m_hook; } - -private: - Gcalc_dyn_list::Item *m_first; - Gcalc_dyn_list::Item **m_hook; - int m_n_points; -}; - - -/* - the spatial object has to be represented as a set of - simple polygones and polylines to be sent to the slicescan. - - Gcalc_shape_transporter class and his descendants are used to - simplify storing the information about the shape into necessary structures. - This base class only fills the Gcalc_heap with the information about - shapes and vertices. - - Normally the Gcalc_shape_transporter family object is sent as a parameter - to the 'get_shapes' method of an 'spatial' object so it can pass - the spatial information about itself. The virtual methods are - treating this data in a way the caller needs. -*/ - -class Gcalc_shape_transporter -{ -private: - Gcalc_heap::Info *m_first; - Gcalc_heap::Info *m_prev; - Gcalc_dyn_list::Item **m_prev_hook; - int m_shape_started; - void int_complete(); -protected: - Gcalc_heap *m_heap; - int int_single_point(gcalc_shape_info Info, double x, double y); - int int_add_point(gcalc_shape_info Info, double x, double y); - void int_start_line() - { - DBUG_ASSERT(!m_shape_started); - m_shape_started= 1; - m_first= m_prev= NULL; - } - void int_complete_line() - { - DBUG_ASSERT(m_shape_started== 1); - int_complete(); - m_shape_started= 0; - } - void int_start_ring() - { - DBUG_ASSERT(m_shape_started== 2); - m_shape_started= 3; - m_first= m_prev= NULL; - } - void int_complete_ring() - { - DBUG_ASSERT(m_shape_started== 3); - int_complete(); - m_shape_started= 2; - } - void int_start_poly() - { - DBUG_ASSERT(!m_shape_started); - m_shape_started= 2; - } - void int_complete_poly() - { - DBUG_ASSERT(m_shape_started== 2); - m_shape_started= 0; - } - bool line_started() { return m_shape_started == 1; }; -public: - Gcalc_shape_transporter(Gcalc_heap *heap) : - m_shape_started(0), m_heap(heap) {} - - virtual int single_point(double x, double y)=0; - virtual int start_line()=0; - virtual int complete_line()=0; - virtual int start_poly()=0; - virtual int complete_poly()=0; - virtual int start_ring()=0; - virtual int complete_ring()=0; - virtual int add_point(double x, double y)=0; - virtual int start_collection(int n_objects) { return 0; } - virtual int empty_shape() { return 0; } - int start_simple_poly() - { - return start_poly() || start_ring(); - } - int complete_simple_poly() - { - return complete_ring() || complete_poly(); - } - virtual ~Gcalc_shape_transporter() {} -}; - - -enum Gcalc_scan_events -{ - scev_none= 0, - scev_point= 1, /* Just a new point in thread */ - scev_thread= 2, /* Start of the new thread */ - scev_two_threads= 4, /* A couple of new threads started */ - scev_intersection= 8, /* Intersection happened */ - scev_end= 16, /* Single thread finished */ - scev_two_ends= 32, /* A couple of threads finished */ - scev_single_point= 64 /* Got single point */ -}; - - -/* - Gcalc_scan_iterator incapsulates the slicescan algorithm. - It takes filled Gcalc_heap as a datasource. Then can be - iterated through the vertexes and intersection points with - the step() method. After the 'step()' one usually observes - the current 'slice' to do the necessary calculations, like - looking for intersections, calculating the area, whatever. -*/ - -class Gcalc_scan_iterator : public Gcalc_dyn_list -{ -public: - class point : public Gcalc_dyn_list::Item - { - public: - Gcalc_coord1 dx; - Gcalc_coord1 dy; - Gcalc_heap::Info *pi; - Gcalc_heap::Info *next_pi; - Gcalc_heap::Info *ev_pi; - const Gcalc_coord1 *l_border; - const Gcalc_coord1 *r_border; - point *ev_next; - - Gcalc_scan_events event; - - inline const point *c_get_next() const - { return (const point *)next; } - inline bool is_bottom() const { return !next_pi; } - gcalc_shape_info get_shape() const { return pi->node.shape.shape; } - inline point *get_next() { return (point *)next; } - inline const point *get_next() const { return (const point *)next; } - /* Compare the dx_dy parameters regarding the horiz_dir */ - /* returns -1 if less, 0 if equal, 1 if bigger */ - static int cmp_dx_dy(const Gcalc_coord1 dx_a, - const Gcalc_coord1 dy_a, - const Gcalc_coord1 dx_b, - const Gcalc_coord1 dy_b); - static int cmp_dx_dy(const Gcalc_heap::Info *p1, - const Gcalc_heap::Info *p2, - const Gcalc_heap::Info *p3, - const Gcalc_heap::Info *p4); - int cmp_dx_dy(const point *p) const; - point **next_ptr() { return (point **) &next; } -#ifndef GCALC_DBUG_OFF - unsigned int thread; -#endif /*GCALC_DBUG_OFF*/ -#ifdef GCALC_CHECK_WITH_FLOAT - void calc_x(long double *x, long double y, long double ix) const; -#endif /*GCALC_CHECK_WITH_FLOAT*/ - }; - - /* That class introduced mostly for the 'typecontrol' reason. */ - /* only difference from the point classis the get_next() function. */ - class event_point : public point - { - public: - inline const event_point *get_next() const - { return (const event_point*) ev_next; } - int simple_event() const - { - return !ev_next ? (event & (scev_point | scev_end)) : - (!ev_next->ev_next && event == scev_two_ends); - } - }; - - class intersection_info : public Gcalc_dyn_list::Item - { - public: - point *edge_a; - point *edge_b; - - Gcalc_coord2 t_a; - Gcalc_coord2 t_b; - int t_calculated; - Gcalc_coord3 x_exp; - int x_calculated; - Gcalc_coord3 y_exp; - int y_calculated; - void calc_t() - {if (!t_calculated) do_calc_t(); } - void calc_y_exp() - { if (!y_calculated) do_calc_y(); } - void calc_x_exp() - { if (!x_calculated) do_calc_x(); } - - void do_calc_t(); - void do_calc_x(); - void do_calc_y(); - }; - - - class slice_state - { - public: - point *slice; - point **event_position_hook; - point *event_end; - const Gcalc_heap::Info *pi; - }; - -public: - Gcalc_scan_iterator(size_t blk_size= 8192); - - GCALC_DECL_TERMINATED_STATE(killed) - - void init(Gcalc_heap *points); /* Iterator can be reused */ - void reset(); - int step(); - - Gcalc_heap::Info *more_points() { return m_cur_pi; } - bool more_trapezoids() - { return m_cur_pi && m_cur_pi->next; } - - const point *get_bottom_points() const - { return m_bottom_points; } - const point *get_event_position() const - { return *state.event_position_hook; } - const point *get_event_end() const - { return state.event_end; } - const event_point *get_events() const - { return (const event_point *) - (*state.event_position_hook == state.event_end ? - m_bottom_points : *state.event_position_hook); } - const point *get_b_slice() const { return state.slice; } - double get_h() const; - double get_y() const; - double get_event_x() const; - double get_sp_x(const point *sp) const; - int intersection_step() const - { return state.pi->type == Gcalc_heap::nt_intersection; } - const Gcalc_heap::Info *get_cur_pi() const - { - return state.pi; - } - -private: - Gcalc_heap *m_heap; - Gcalc_heap::Info *m_cur_pi; - slice_state state; - -#ifndef GCALC_DBUG_OFF - unsigned int m_cur_thread; -#endif /*GCALC_DBUG_OFF*/ - - point *m_bottom_points; - point **m_bottom_hook; - - int node_scan(); - void eq_scan(); - void intersection_scan(); - void remove_bottom_node(); - int insert_top_node(); - int add_intersection(point *sp_a, point *sp_b, - Gcalc_heap::Info *pi_from); - int add_eq_node(Gcalc_heap::Info *node, point *sp); - int add_events_for_node(point *sp_node); - - point *new_slice_point() - { - point *new_point= (point *)new_item(); - return new_point; - } - intersection_info *new_intersection_info(point *a, point *b) - { - intersection_info *ii= (intersection_info *)new_item(); - ii->edge_a= a; - ii->edge_b= b; - ii->t_calculated= ii->x_calculated= ii->y_calculated= 0; - return ii; - } - int arrange_event(int do_sorting, int n_intersections); - static double get_pure_double(const Gcalc_internal_coord *d, int d_len); -}; - - -/* - Gcalc_trapezoid_iterator simplifies the calculations on - the current slice of the Gcalc_scan_iterator. - One can walk through the trapezoids formed between - previous and current slices. -*/ - -#ifdef TMP_BLOCK -class Gcalc_trapezoid_iterator -{ -protected: - const Gcalc_scan_iterator::point *sp0; - const Gcalc_scan_iterator::point *sp1; -public: - Gcalc_trapezoid_iterator(const Gcalc_scan_iterator *scan_i) : - sp0(scan_i->get_b_slice()), - sp1(scan_i->get_t_slice()) - {} - - inline bool more() const { return sp1 && sp1->next; } - - const Gcalc_scan_iterator::point *lt() const { return sp1; } - const Gcalc_scan_iterator::point *lb() const { return sp0; } - const Gcalc_scan_iterator::point *rb() const - { - const Gcalc_scan_iterator::point *result= sp0; - while ((result= result->c_get_next())->is_bottom()) - {} - return result; - } - const Gcalc_scan_iterator::point *rt() const - { return sp1->c_get_next(); } - - void operator++() - { - sp0= rb(); - sp1= rt(); - } -}; -#endif /*TMP_BLOCK*/ - - -/* - Gcalc_point_iterator simplifies the calculations on - the current slice of the Gcalc_scan_iterator. - One can walk through the points on the current slice. -*/ - -class Gcalc_point_iterator -{ -protected: - const Gcalc_scan_iterator::point *sp; -public: - Gcalc_point_iterator(const Gcalc_scan_iterator *scan_i): - sp(scan_i->get_b_slice()) - {} - - inline bool more() const { return sp != NULL; } - inline void operator++() { sp= sp->c_get_next(); } - inline const Gcalc_scan_iterator::point *point() const { return sp; } - inline const Gcalc_heap::Info *get_pi() const { return sp->pi; } - inline gcalc_shape_info get_shape() const { return sp->get_shape(); } - inline void restart(const Gcalc_scan_iterator *scan_i) - { sp= scan_i->get_b_slice(); } -}; - -#endif /*GCALC_SLICESCAN_INCLUDED*/ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/gcalc_tools.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/gcalc_tools.h deleted file mode 100644 index 77da791..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/gcalc_tools.h +++ /dev/null @@ -1,357 +0,0 @@ -/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved. - Copyright (C) 2011 Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef GCALC_TOOLS_INCLUDED -#define GCALC_TOOLS_INCLUDED - -#include "gcalc_slicescan.h" -#include "sql_string.h" - - -/* - The Gcalc_function class objects are used to check for a binary relation. - The relation can be constructed with the prefix notation using predicates as - op_not (as !A) - op_union ( A || B || C... ) - op_intersection ( A && B && C ... ) - op_symdifference ( A+B+C+... == 1 ) - op_difference ( A && !(B||C||..)) - with the calls of the add_operation(operation, n_operands) method. - The relation is calculated over a set of shapes, that in turn have - to be added with the add_new_shape() method. All the 'shapes' can - be set to 0 with clear_shapes() method and single value - can be changed with the invert_state() method. - Then the value of the relation can be calculated with the count() method. - Frequently used method is find_function(Gcalc_scan_iterator it) that - iterates through the 'it' until the relation becomes TRUE. -*/ - -class Gcalc_function -{ -private: - String shapes_buffer; - String function_buffer; - int *i_states; - int *b_states; - uint32 cur_object_id; - uint n_shapes; - int count_internal(const char *cur_func, uint set_type, - const char **end); -public: - enum value - { - v_empty= 0x0000000, - v_find_t= 0x1000000, - v_find_f= 0x2000000, - v_t_found= 0x3000000, - v_f_found= 0x4000000, - v_mask= 0x7000000 - }; - enum op_type - { - op_not= 0x80000000, - op_shape= 0x00000000, - op_union= 0x10000000, - op_intersection= 0x20000000, - op_symdifference= 0x30000000, - op_difference= 0x40000000, - op_repeat= 0x50000000, - op_border= 0x60000000, - op_internals= 0x70000000, - op_false= 0x08000000, - op_any= 0x78000000 /* The mask to get any of the operations */ - }; - enum shape_type - { - shape_point= 0, - shape_line= 1, - shape_polygon= 2, - shape_hole= 3 - }; - enum count_result - { - result_false= 0, - result_true= 1, - result_unknown= 2 - }; - Gcalc_function() : n_shapes(0) {} - gcalc_shape_info add_new_shape(uint32 shape_id, shape_type shape_kind); - /* - Adds the leaf operation that returns the shape value. - Also adds the shape to the list of operands. - */ - int single_shape_op(shape_type shape_kind, gcalc_shape_info *si); - void add_operation(uint operation, uint32 n_operands); - void add_not_operation(op_type operation, uint32 n_operands); - uint32 get_next_expression_pos() { return function_buffer.length(); } - void add_operands_to_op(uint32 operation_pos, uint32 n_operands); - int repeat_expression(uint32 exp_pos); - void set_cur_obj(uint32 cur_obj) { cur_object_id= cur_obj; } - int reserve_shape_buffer(uint n_shapes); - int reserve_op_buffer(uint n_ops); - uint get_nshapes() const { return n_shapes; } - shape_type get_shape_kind(gcalc_shape_info si) const - { - return (shape_type) uint4korr(shapes_buffer.ptr() + (si*4)); - } - - void set_states(int *shape_states) { i_states= shape_states; } - int alloc_states(); - void invert_i_state(gcalc_shape_info shape) { i_states[shape]^= 1; } - void set_i_state(gcalc_shape_info shape) { i_states[shape]= 1; } - void clear_i_state(gcalc_shape_info shape) { i_states[shape]= 0; } - void set_b_state(gcalc_shape_info shape) { b_states[shape]= 1; } - void clear_b_state(gcalc_shape_info shape) { b_states[shape]= 0; } - int get_state(gcalc_shape_info shape) - { return i_states[shape] | b_states[shape]; } - int get_i_state(gcalc_shape_info shape) { return i_states[shape]; } - int get_b_state(gcalc_shape_info shape) { return b_states[shape]; } - int count() - { return count_internal(function_buffer.ptr(), 0, 0); } - int count_last() - { return count_internal(function_buffer.ptr(), 1, 0); } - void clear_i_states(); - void clear_b_states(); - void reset(); - - int check_function(Gcalc_scan_iterator &scan_it); -}; - - -/* - Gcalc_operation_transporter class extends the Gcalc_shape_transporter. - In addition to the parent's functionality, it fills the Gcalc_function - object so it has the function that determines the proper shape. - For example Multipolyline will be represented as an union of polylines. -*/ - -class Gcalc_operation_transporter : public Gcalc_shape_transporter -{ -protected: - Gcalc_function *m_fn; - gcalc_shape_info m_si; -public: - Gcalc_operation_transporter(Gcalc_function *fn, Gcalc_heap *heap) : - Gcalc_shape_transporter(heap), m_fn(fn) {} - - int single_point(double x, double y); - int start_line(); - int complete_line(); - int start_poly(); - int complete_poly(); - int start_ring(); - int complete_ring(); - int add_point(double x, double y); - int start_collection(int n_objects); - int empty_shape(); -}; - - -/* - When we calculate the result of an spatial operation like - Union or Intersection, we receive vertexes of the result - one-by-one, and probably need to treat them in variative ways. - So, the Gcalc_result_receiver class designed to get these - vertexes and construct shapes/objects out of them. - and to store the result in an appropriate format -*/ - -class Gcalc_result_receiver -{ - String buffer; - uint32 n_points; - Gcalc_function::shape_type common_shapetype; - bool collection_result; - uint32 n_shapes; - uint32 n_holes; - - Gcalc_function::shape_type cur_shape; - uint32 shape_pos; - double first_x, first_y, prev_x, prev_y; - double shape_area; -public: - Gcalc_result_receiver() : collection_result(FALSE), n_shapes(0), n_holes(0) - {} - int start_shape(Gcalc_function::shape_type shape); - int add_point(double x, double y); - int complete_shape(); - int single_point(double x, double y); - int done(); - void reset(); - - const char *result() { return buffer.ptr(); } - uint length() { return buffer.length(); } - int get_nshapes() { return n_shapes; } - int get_nholes() { return n_holes; } - int get_result_typeid(); - uint32 position() { return buffer.length(); } - int move_hole(uint32 dest_position, uint32 source_position, - uint32 *position_shift); -}; - - -/* - Gcalc_operation_reducer class incapsulates the spatial - operation functionality. It analyses the slices generated by - the slicescan and calculates the shape of the result defined - by some Gcalc_function. -*/ - -class Gcalc_operation_reducer : public Gcalc_dyn_list -{ -public: - enum modes - { - /* Numeric values important here - careful with changing */ - default_mode= 0, - prefer_big_with_holes= 1, - polygon_selfintersections_allowed= 2, /* allowed in the result */ - line_selfintersections_allowed= 4 /* allowed in the result */ - }; - - Gcalc_operation_reducer(size_t blk_size=8192); - Gcalc_operation_reducer(const Gcalc_operation_reducer &gor); - void init(Gcalc_function *fn, modes mode= default_mode); - Gcalc_operation_reducer(Gcalc_function *fn, modes mode= default_mode, - size_t blk_size=8192); - GCALC_DECL_TERMINATED_STATE(killed) - int count_slice(Gcalc_scan_iterator *si); - int count_all(Gcalc_heap *hp); - int get_result(Gcalc_result_receiver *storage); - void reset(); - -#ifndef GCALC_DBUG_OFF - int n_res_points; -#endif /*GCALC_DBUG_OFF*/ - class res_point : public Gcalc_dyn_list::Item - { - public: - int intersection_point; - union - { - const Gcalc_heap::Info *pi; - res_point *first_poly_node; - }; - union - { - res_point *outer_poly; - uint32 poly_position; - }; - res_point *up; - res_point *down; - res_point *glue; - Gcalc_function::shape_type type; - Gcalc_dyn_list::Item **prev_hook; -#ifndef GCALC_DBUG_OFF - int point_n; -#endif /*GCALC_DBUG_OFF*/ - void set(const Gcalc_scan_iterator *si); - res_point *get_next() { return (res_point *)next; } - }; - - class active_thread : public Gcalc_dyn_list::Item - { - public: - res_point *rp; - res_point *thread_start; - - const Gcalc_heap::Info *p1, *p2; - res_point *enabled() { return rp; } - active_thread *get_next() { return (active_thread *)next; } - }; - - class poly_instance : public Gcalc_dyn_list::Item - { - public: - uint32 *after_poly_position; - poly_instance *get_next() { return (poly_instance *)next; } - }; - - class line : public Gcalc_dyn_list::Item - { - public: - active_thread *t; - int incoming; - const Gcalc_scan_iterator::point *p; - line *get_next() { return (line *)next; } - }; - - class poly_border : public Gcalc_dyn_list::Item - { - public: - active_thread *t; - int incoming; - int prev_state; - const Gcalc_scan_iterator::point *p; - poly_border *get_next() { return (poly_border *)next; } - }; - - line *m_lines; - Gcalc_dyn_list::Item **m_lines_hook; - poly_border *m_poly_borders; - Gcalc_dyn_list::Item **m_poly_borders_hook; - line *new_line() { return (line *) new_item(); } - poly_border *new_poly_border() { return (poly_border *) new_item(); } - int add_line(int incoming, active_thread *t, - const Gcalc_scan_iterator::point *p); - int add_poly_border(int incoming, active_thread *t, int prev_state, - const Gcalc_scan_iterator::point *p); - -protected: - Gcalc_function *m_fn; - Gcalc_dyn_list::Item **m_res_hook; - res_point *m_result; - int m_mode; - - res_point *result_heap; - active_thread *m_first_active_thread; - - res_point *add_res_point(Gcalc_function::shape_type type); - active_thread *new_active_thread() { return (active_thread *)new_item(); } - - poly_instance *new_poly() { return (poly_instance *) new_item(); } - -private: - int start_line(active_thread *t, const Gcalc_scan_iterator::point *p, - const Gcalc_scan_iterator *si); - int end_line(active_thread *t, const Gcalc_scan_iterator *si); - int connect_threads(int incoming_a, int incoming_b, - active_thread *ta, active_thread *tb, - const Gcalc_scan_iterator::point *pa, - const Gcalc_scan_iterator::point *pb, - active_thread *prev_range, - const Gcalc_scan_iterator *si, - Gcalc_function::shape_type s_t); - int add_single_point(const Gcalc_scan_iterator *si); - poly_border *get_pair_border(poly_border *b1); - int continue_range(active_thread *t, const Gcalc_heap::Info *p, - const Gcalc_heap::Info *p_next); - int continue_i_range(active_thread *t, - const Gcalc_heap::Info *ii); - int end_couple(active_thread *t0, active_thread *t1, const Gcalc_heap::Info *p); - int get_single_result(res_point *res, Gcalc_result_receiver *storage); - int get_result_thread(res_point *cur, Gcalc_result_receiver *storage, - int move_upward, res_point *first_poly_node); - int get_polygon_result(res_point *cur, Gcalc_result_receiver *storage, - res_point *first_poly_node); - int get_line_result(res_point *cur, Gcalc_result_receiver *storage); - - void free_result(res_point *res); -}; - -#endif /*GCALC_TOOLS_INCLUDED*/ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/grant.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/grant.h deleted file mode 100644 index 5fbec44..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/grant.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_GRANT_INCLUDED -#define SQL_GRANT_INCLUDED - -#include "lex_string.h" -#include "privilege.h" - -class LEX_COLUMN; -class Lex_ident_sys; -class Table_ident; - -/* - Represents the object name in this standard SQL grammar: - GRANT ON -*/ -class Grant_object_name -{ -public: - enum Type - { - STAR, // ON * - IDENT_STAR, // ON db.* - STAR_STAR, // ON *.* - TABLE_IDENT // ON db.name - }; - Lex_cstring m_db; - Table_ident *m_table_ident; - Type m_type; -public: - Grant_object_name(Table_ident *table_ident) - :m_table_ident(table_ident), - m_type(TABLE_IDENT) - { } - Grant_object_name(const LEX_CSTRING &db, Type type) - :m_db(db), - m_table_ident(NULL), - m_type(type) - { } - privilege_t all_privileges_by_type() const; -}; - - - -/* - Represents standard SQL statements described by: - - - - -*/ -class Grant_privilege -{ -protected: - List m_columns; - Lex_cstring m_db; - privilege_t m_object_privilege; - privilege_t m_column_privilege_total; - bool m_all_privileges; -public: - Grant_privilege() - :m_object_privilege(NO_ACL), - m_column_privilege_total(NO_ACL), - m_all_privileges(false) - { } - Grant_privilege(privilege_t privilege, bool all_privileges) - :m_object_privilege(privilege), - m_column_privilege_total(NO_ACL), - m_all_privileges(all_privileges) - { } - void add_object_privilege(privilege_t privilege) - { - m_object_privilege|= privilege; - } - bool add_column_privilege(THD *thd, const Lex_ident_sys &col, - privilege_t privilege); - bool add_column_list_privilege(THD *thd, List &list, - privilege_t privilege); - bool set_object_name(THD *thd, - const Grant_object_name &ident, - SELECT_LEX *sel, - privilege_t with_grant_option); - const List & columns() const { return m_columns; } -}; - - -#endif // SQL_GRANT_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/group_by_handler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/group_by_handler.h deleted file mode 100644 index ff3b204..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/group_by_handler.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - Copyright (c) 2014, 2015 SkySQL Ab & MariaDB Foundation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef GROUP_BY_HANDLER_INCLUDED -#define GROUP_BY_HANDLER_INCLUDED - -class Select_limit_counters; -/* - This file implements the group_by_handler interface. This interface - can be used by storage handlers that can intercept summary or GROUP - BY queries from MariaDB and itself return the result to the user or - upper level. It is part of the Storage Engine API - - Both main and sub queries are supported. Here are some examples of what the - storage engine could intersept: - - SELECT count(*) FROM t1; - SELECT a,count(*) FROM t1 group by a; - SELECT a,count(*) as sum FROM t1 where b > 10 group by a, order by sum; - SELECT a,count(*) FROM t1,t2; - SELECT a, (select sum(*) from t2 where t1.a=t2.a) from t2; -*/ - -/** - The structure describing various parts of the query - - The engine is supposed to take out parts that it can do internally. - For example, if the engine can return results sorted according to - the specified order_by clause, it sets Query::order_by=NULL before - returning. - - At the moment the engine must take group_by (or return an error), and - optionally can take distinct, where, order_by, and having. - - The engine should not modify the select list. It is the extended SELECT - clause (extended, because it has more items than the original - user-specified SELECT clause) and it contains all aggregate functions, - used in the query. -*/ -struct Query -{ - List *select; - bool distinct; - TABLE_LIST *from; - Item *where; - ORDER *group_by; - ORDER *order_by; - Item *having; - // LIMIT - Select_limit_counters *limit; -}; - -class group_by_handler -{ -public: - THD *thd; - handlerton *ht; - - /* - Temporary table where all results should be stored in record[0] - The table has a field for every item from the Query::select list. - */ - TABLE *table; - - group_by_handler(THD *thd_arg, handlerton *ht_arg) - : thd(thd_arg), ht(ht_arg), table(0) {} - virtual ~group_by_handler() {} - - /* - Functions to scan data. All these returns 0 if ok, error code in case - of error - */ - - /* - Initialize group_by scan, prepare for next_row(). - If this is a sub query with group by, this can be called many times for - a query. - */ - virtual int init_scan()= 0; - - /* - Return next group by result in table->record[0]. - Return 0 if row found, HA_ERR_END_OF_FILE if last row and other error - number in case of fatal error. - */ - virtual int next_row()= 0; - - /* End scanning */ - virtual int end_scan()=0; - - /* Report errors */ - virtual void print_error(int error, myf errflag); -}; - -#endif //GROUP_BY_HANDLER_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/gstream.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/gstream.h deleted file mode 100644 index c5c7153..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/gstream.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef GSTREAM_INCLUDED -#define GSTREAM_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#include /* MY_ALLOW_ZERO_PTR */ -#include "m_ctype.h" /* my_charset_latin1, my_charset_bin */ - -class Gis_read_stream -{ -public: - enum enum_tok_types - { - unknown, - eostream, - word, - numeric, - l_bra, - r_bra, - comma - }; - - Gis_read_stream(CHARSET_INFO *charset, const char *buffer, int size) - :m_cur(buffer), m_limit(buffer + size), m_err_msg(NULL), m_charset(charset) - {} - Gis_read_stream(): m_cur(NullS), m_limit(NullS), m_err_msg(NullS) - {} - ~Gis_read_stream() - { - my_free(m_err_msg); - } - - enum enum_tok_types get_next_toc_type(); - bool lookup_next_word(LEX_STRING *res); - bool get_next_word(LEX_STRING *); - bool get_next_number(double *); - bool check_next_symbol(char); - - inline void skip_space() - { - while ((m_cur < m_limit) && my_isspace(&my_charset_latin1, *m_cur)) - m_cur++; - } - /* Skip next character, if match. Return 1 if no match */ - inline bool skip_char(char skip) - { - skip_space(); - if ((m_cur >= m_limit) || *m_cur != skip) - return 1; /* Didn't find char */ - m_cur++; - return 0; - } - /* Returns the next notempty character. */ - char next_symbol() - { - skip_space(); - if (m_cur >= m_limit) - return 0; /* EOL meet. */ - return *m_cur; - } - void set_error_msg(const char *msg); - - // caller should free this pointer - char *get_error_msg() - { - char *err_msg = m_err_msg; - m_err_msg= NullS; - return err_msg; - } - -protected: - const char *m_cur; - const char *m_limit; - char *m_err_msg; - CHARSET_INFO *m_charset; -}; - -#endif /* GSTREAM_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ha_partition.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/ha_partition.h deleted file mode 100644 index 8d0557f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ha_partition.h +++ /dev/null @@ -1,1654 +0,0 @@ -#ifndef HA_PARTITION_INCLUDED -#define HA_PARTITION_INCLUDED - -/* - Copyright (c) 2005, 2012, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "sql_partition.h" /* part_id_range, partition_element */ -#include "queues.h" /* QUEUE */ - -#define PARTITION_BYTES_IN_POS 2 -#define PAR_EXT ".par" - -/** Struct used for partition_name_hash */ -typedef struct st_part_name_def -{ - uchar *partition_name; - uint length; - uint32 part_id; - my_bool is_subpart; -} PART_NAME_DEF; - -/** class where to save partitions Handler_share's */ -class Parts_share_refs -{ -public: - uint num_parts; /**< Size of ha_share array */ - Handler_share **ha_shares; /**< Storage for each part */ - Parts_share_refs() - { - num_parts= 0; - ha_shares= NULL; - } - ~Parts_share_refs() - { - uint i; - for (i= 0; i < num_parts; i++) - delete ha_shares[i]; - delete[] ha_shares; - } - bool init(uint arg_num_parts) - { - DBUG_ASSERT(!num_parts && !ha_shares); - num_parts= arg_num_parts; - /* Allocate an array of Handler_share pointers */ - ha_shares= new Handler_share *[num_parts]; - if (!ha_shares) - { - num_parts= 0; - return true; - } - memset(ha_shares, 0, sizeof(Handler_share*) * num_parts); - return false; - } -}; - -class ha_partition; - -/* Partition Full Text Search info */ -struct st_partition_ft_info -{ - struct _ft_vft *please; - st_partition_ft_info *next; - ha_partition *file; - FT_INFO **part_ft_info; -}; - - -#ifdef HAVE_PSI_MUTEX_INTERFACE -extern PSI_mutex_key key_partition_auto_inc_mutex; -#endif - -/** - Partition specific Handler_share. -*/ -class Partition_share : public Handler_share -{ -public: - bool auto_inc_initialized; - mysql_mutex_t auto_inc_mutex; /**< protecting auto_inc val */ - ulonglong next_auto_inc_val; /**< first non reserved value */ - ulonglong prev_auto_inc_val; /**< stored next_auto_inc_val */ - /** - Hash of partition names. Initialized in the first ha_partition::open() - for the table_share. After that it is read-only, i.e. no locking required. - */ - bool partition_name_hash_initialized; - HASH partition_name_hash; - /** Storage for each partitions Handler_share */ - Parts_share_refs partitions_share_refs; - Partition_share() - : auto_inc_initialized(false), - next_auto_inc_val(0), - prev_auto_inc_val(0), - partition_name_hash_initialized(false), - partition_names(NULL) - { - mysql_mutex_init(key_partition_auto_inc_mutex, - &auto_inc_mutex, - MY_MUTEX_INIT_FAST); - } - - ~Partition_share() - { - mysql_mutex_destroy(&auto_inc_mutex); - if (partition_names) - { - my_free(partition_names); - } - if (partition_name_hash_initialized) - { - my_hash_free(&partition_name_hash); - } - } - - bool init(uint num_parts); - - /** - Release reserved auto increment values not used. - @param thd Thread. - @param table_share Table Share - @param next_insert_id Next insert id (first non used auto inc value). - @param max_reserved End of reserved auto inc range. - */ - void release_auto_inc_if_possible(THD *thd, TABLE_SHARE *table_share, - const ulonglong next_insert_id, - const ulonglong max_reserved); - - /** lock mutex protecting auto increment value next_auto_inc_val. */ - inline void lock_auto_inc() - { - mysql_mutex_lock(&auto_inc_mutex); - } - /** unlock mutex protecting auto increment value next_auto_inc_val. */ - inline void unlock_auto_inc() - { - mysql_mutex_unlock(&auto_inc_mutex); - } - /** - Populate partition_name_hash with partition and subpartition names - from part_info. - @param part_info Partition info containing all partitions metadata. - - @return Operation status. - @retval false Success. - @retval true Failure. - */ - bool populate_partition_name_hash(partition_info *part_info); - /** Get partition name. - - @param part_id Partition id (for subpartitioned table only subpartition - names will be returned.) - - @return partition name or NULL if error. - */ - const char *get_partition_name(size_t part_id) const; -private: - const uchar **partition_names; - /** - Insert [sub]partition name into partition_name_hash - @param name Partition name. - @param part_id Partition id. - @param is_subpart True if subpartition else partition. - - @return Operation status. - @retval false Success. - @retval true Failure. - */ - bool insert_partition_name_in_hash(const char *name, - uint part_id, - bool is_subpart); -}; - - -/* - List of ranges to be scanned by ha_partition's MRR implementation - - This object is - - A KEY_MULTI_RANGE structure (the MRR range) - - Storage for the range endpoints that the KEY_MULTI_RANGE has pointers to - - list of such ranges (connected through the "next" pointer). -*/ - -typedef struct st_partition_key_multi_range -{ - /* - Number of the range. The ranges are numbered in the order RANGE_SEQ_IF has - emitted them, starting from 1. The numbering in used by ordered MRR scans. - */ - uint id; - uchar *key[2]; - /* - Sizes of allocated memory in key[]. These may be larger then the actual - values as this structure is reused across MRR scans - */ - uint length[2]; - - /* - The range. - key_multi_range.ptr is a pointer to the this PARTITION_KEY_MULTI_RANGE - object - */ - KEY_MULTI_RANGE key_multi_range; - - // Range id from the SQL layer - range_id_t ptr; - - // The next element in the list of MRR ranges. - st_partition_key_multi_range *next; -} PARTITION_KEY_MULTI_RANGE; - - -/* - List of ranges to be scanned in a certain [sub]partition - - The idea is that there's a list of ranges to be scanned in the table - (formed by PARTITION_KEY_MULTI_RANGE structures), - and for each [sub]partition, we only need to scan a subset of that list. - - PKMR1 --> PKMR2 --> PKMR3 -->... // list of PARTITION_KEY_MULTI_RANGE - ^ ^ - | | - PPKMR1 ----------> PPKMR2 -->... // list of PARTITION_PART_KEY_MULTI_RANGE - - This way, per-partition lists of PARTITION_PART_KEY_MULTI_RANGE have pointers - to the elements of the global list of PARTITION_KEY_MULTI_RANGE. -*/ - -typedef struct st_partition_part_key_multi_range -{ - PARTITION_KEY_MULTI_RANGE *partition_key_multi_range; - st_partition_part_key_multi_range *next; -} PARTITION_PART_KEY_MULTI_RANGE; - - -class ha_partition; - -/* - The structure holding information about range sequence to be used with one - partition. - (pointer to this is used as seq_init_param for RANGE_SEQ_IF structure when - invoking MRR for an individual partition) -*/ - -typedef struct st_partition_part_key_multi_range_hld -{ - /* Owner object */ - ha_partition *partition; - - /* id of the the partition this structure is for */ - uint32 part_id; - - /* Current range we're iterating through */ - PARTITION_PART_KEY_MULTI_RANGE *partition_part_key_multi_range; -} PARTITION_PART_KEY_MULTI_RANGE_HLD; - - -extern "C" int cmp_key_part_id(void *key_p, uchar *ref1, uchar *ref2); -extern "C" int cmp_key_rowid_part_id(void *ptr, uchar *ref1, uchar *ref2); - -class ha_partition :public handler -{ -private: - enum partition_index_scan_type - { - partition_index_read= 0, - partition_index_first= 1, - partition_index_last= 3, - partition_index_read_last= 4, - partition_read_range = 5, - partition_no_index_scan= 6, - partition_read_multi_range = 7, - partition_ft_read= 8 - }; - /* Data for the partition handler */ - int m_mode; // Open mode - uint m_open_test_lock; // Open test_if_locked - uchar *m_file_buffer; // Content of the .par file - char *m_name_buffer_ptr; // Pointer to first partition name - MEM_ROOT m_mem_root; - plugin_ref *m_engine_array; // Array of types of the handlers - handler **m_file; // Array of references to handler inst. - uint m_file_tot_parts; // Debug - handler **m_new_file; // Array of references to new handlers - handler **m_reorged_file; // Reorganised partitions - handler **m_added_file; // Added parts kept for errors - LEX_CSTRING *m_connect_string; - partition_info *m_part_info; // local reference to partition - Field **m_part_field_array; // Part field array locally to save acc - uchar *m_ordered_rec_buffer; // Row and key buffer for ord. idx scan - st_partition_ft_info *ft_first; - st_partition_ft_info *ft_current; - /* - Current index. - When used in key_rec_cmp: If clustered pk, index compare - must compare pk if given index is same for two rows. - So normally m_curr_key_info[0]= current index and m_curr_key[1]= NULL, - and if clustered pk, [0]= current index, [1]= pk, [2]= NULL - */ - KEY *m_curr_key_info[3]; // Current index - uchar *m_rec0; // table->record[0] - const uchar *m_err_rec; // record which gave error - QUEUE m_queue; // Prio queue used by sorted read - - /* - Length of an element in m_ordered_rec_buffer. The elements are composed of - - [part_no] [table->record copy] [underlying_table_rowid] - - underlying_table_rowid is only stored when the table has no extended keys. - */ - size_t m_priority_queue_rec_len; - - /* - If true, then sorting records by key value also sorts them by their - underlying_table_rowid. - */ - bool m_using_extended_keys; - - /* - Since the partition handler is a handler on top of other handlers, it - is necessary to keep information about what the underlying handler - characteristics is. It is not possible to keep any handler instances - for this since the MySQL Server sometimes allocating the handler object - without freeing them. - */ - enum enum_handler_status - { - handler_not_initialized= 0, - handler_initialized, - handler_opened, - handler_closed - }; - enum_handler_status m_handler_status; - - uint m_reorged_parts; // Number of reorganised parts - uint m_tot_parts; // Total number of partitions; - uint m_num_locks; // For engines like ha_blackhole, which needs no locks - uint m_last_part; // Last file that we update,write,read - part_id_range m_part_spec; // Which parts to scan - uint m_scan_value; // Value passed in rnd_init - // call - uint m_ref_length; // Length of position in this - // handler object - key_range m_start_key; // index read key range - enum partition_index_scan_type m_index_scan_type;// What type of index - // scan - uint m_top_entry; // Which partition is to - // deliver next result - uint m_rec_length; // Local copy of record length - - bool m_ordered; // Ordered/Unordered index scan - bool m_create_handler; // Handler used to create table - bool m_is_sub_partitioned; // Is subpartitioned - bool m_ordered_scan_ongoing; - bool m_rnd_init_and_first; - bool m_ft_init_and_first; - - /* - If set, this object was created with ha_partition::clone and doesn't - "own" the m_part_info structure. - */ - ha_partition *m_is_clone_of; - MEM_ROOT *m_clone_mem_root; - - /* - We keep track if all underlying handlers are MyISAM since MyISAM has a - great number of extra flags not needed by other handlers. - */ - bool m_myisam; // Are all underlying handlers - // MyISAM - /* - We keep track of InnoDB handlers below since it requires proper setting - of query_id in fields at index_init and index_read calls. - */ - bool m_innodb; // Are all underlying handlers - // InnoDB - /* - When calling extra(HA_EXTRA_CACHE) we do not pass this to the underlying - handlers immediately. Instead we cache it and call the underlying - immediately before starting the scan on the partition. This is to - prevent allocating a READ CACHE for each partition in parallel when - performing a full table scan on MyISAM partitioned table. - This state is cleared by extra(HA_EXTRA_NO_CACHE). - */ - bool m_extra_cache; - uint m_extra_cache_size; - /* The same goes for HA_EXTRA_PREPARE_FOR_UPDATE */ - bool m_extra_prepare_for_update; - /* Which partition has active cache */ - uint m_extra_cache_part_id; - - void init_handler_variables(); - /* - Variables for lock structures. - */ - - bool auto_increment_lock; /**< lock reading/updating auto_inc */ - /** - Flag to keep the auto_increment lock through out the statement. - This to ensure it will work with statement based replication. - */ - bool auto_increment_safe_stmt_log_lock; - /** For optimizing ha_start_bulk_insert calls */ - MY_BITMAP m_bulk_insert_started; - ha_rows m_bulk_inserted_rows; - /** used for prediction of start_bulk_insert rows */ - enum_monotonicity_info m_part_func_monotonicity_info; - part_id_range m_direct_update_part_spec; - bool m_pre_calling; - bool m_pre_call_use_parallel; - /* Keep track of bulk access requests */ - bool bulk_access_executing; - - /** keep track of locked partitions */ - MY_BITMAP m_locked_partitions; - /** Stores shared auto_increment etc. */ - Partition_share *part_share; - /** Fix spurious -Werror=overloaded-virtual in GCC 9 */ - virtual void restore_auto_increment(ulonglong prev_insert_id) override - { - handler::restore_auto_increment(prev_insert_id); - } - /** Store and restore next_auto_inc_val over duplicate key errors. */ - void store_auto_increment() override - { - DBUG_ASSERT(part_share); - part_share->prev_auto_inc_val= part_share->next_auto_inc_val; - handler::store_auto_increment(); - } - void restore_auto_increment() override - { - DBUG_ASSERT(part_share); - part_share->next_auto_inc_val= part_share->prev_auto_inc_val; - handler::restore_auto_increment(); - } - void sum_copy_info(handler *file); - void sum_copy_infos(); - void reset_copy_info() override; - /** Temporary storage for new partitions Handler_shares during ALTER */ - List m_new_partitions_share_refs; - /** Sorted array of partition ids in descending order of number of rows. */ - uint32 *m_part_ids_sorted_by_num_of_records; - /* Compare function for my_qsort2, for reversed order. */ - static int compare_number_of_records(ha_partition *me, - const uint32 *a, - const uint32 *b); - /** keep track of partitions to call ha_reset */ - MY_BITMAP m_partitions_to_reset; - /** partitions that returned HA_ERR_KEY_NOT_FOUND. */ - MY_BITMAP m_key_not_found_partitions; - bool m_key_not_found; - List *m_partitions_to_open; - MY_BITMAP m_opened_partitions; - /** This is one of the m_file-s that it guaranteed to be opened. */ - /** It is set in open_read_partitions() */ - handler *m_file_sample; -public: - handler **get_child_handlers() - { - return m_file; - } - ha_partition *get_clone_source() - { - return m_is_clone_of; - } - virtual part_id_range *get_part_spec() - { - return &m_part_spec; - } - virtual uint get_no_current_part_id() - { - return NO_CURRENT_PART_ID; - } - Partition_share *get_part_share() { return part_share; } - handler *clone(const char *name, MEM_ROOT *mem_root) override; - virtual void set_part_info(partition_info *part_info) override - { - m_part_info= part_info; - m_is_sub_partitioned= part_info->is_sub_partitioned(); - } - - void return_record_by_parent() override; - - bool vers_can_native(THD *thd) override - { - if (thd->lex->part_info) - { - // PARTITION BY SYSTEM_TIME is not supported for now - return thd->lex->part_info->part_type != VERSIONING_PARTITION; - } - else - { - bool can= true; - for (uint i= 0; i < m_tot_parts && can; i++) - can= can && m_file[i]->vers_can_native(thd); - return can; - } - } - - /* - ------------------------------------------------------------------------- - MODULE create/delete handler object - ------------------------------------------------------------------------- - Object create/delete method. Normally called when a table object - exists. There is also a method to create the handler object with only - partition information. This is used from mysql_create_table when the - table is to be created and the engine type is deduced to be the - partition handler. - ------------------------------------------------------------------------- - */ - ha_partition(handlerton *hton, TABLE_SHARE * table); - ha_partition(handlerton *hton, partition_info * part_info); - ha_partition(handlerton *hton, TABLE_SHARE *share, - partition_info *part_info_arg, - ha_partition *clone_arg, - MEM_ROOT *clone_mem_root_arg); - ~ha_partition(); - void ha_partition_init(); - /* - A partition handler has no characteristics in itself. It only inherits - those from the underlying handlers. Here we set-up those constants to - enable later calls of the methods to retrieve constants from the under- - lying handlers. Returns false if not successful. - */ - bool initialize_partition(MEM_ROOT *mem_root); - - /* - ------------------------------------------------------------------------- - MODULE meta data changes - ------------------------------------------------------------------------- - Meta data routines to CREATE, DROP, RENAME table and often used at - ALTER TABLE (update_create_info used from ALTER TABLE and SHOW ..). - - update_table_comment is used in SHOW TABLE commands to provide a - chance for the handler to add any interesting comments to the table - comments not provided by the users comment. - - create_partitioning_metadata is called before opening a new handler object - with openfrm to call create. It is used to create any local handler - object needed in opening the object in openfrm - ------------------------------------------------------------------------- - */ - int delete_table(const char *from) override; - int rename_table(const char *from, const char *to) override; - int create(const char *name, TABLE *form, - HA_CREATE_INFO *create_info) override; - int create_partitioning_metadata(const char *name, - const char *old_name, - chf_create_flags action_flag) - override; - bool check_if_updates_are_ignored(const char *op) const override; - void update_create_info(HA_CREATE_INFO *create_info) override; - char *update_table_comment(const char *comment) override; - int change_partitions(HA_CREATE_INFO *create_info, const char *path, - ulonglong * const copied, ulonglong * const deleted, - const uchar *pack_frm_data, size_t pack_frm_len) - override; - int drop_partitions(const char *path) override; - int rename_partitions(const char *path) override; - bool get_no_parts(const char *, uint *num_parts) override - { - DBUG_ENTER("ha_partition::get_no_parts"); - *num_parts= m_tot_parts; - DBUG_RETURN(0); - } - void change_table_ptr(TABLE *table_arg, TABLE_SHARE *share) override; - bool check_if_incompatible_data(HA_CREATE_INFO *create_info, - uint table_changes) override; - void update_part_create_info(HA_CREATE_INFO *create_info, uint part_id) - { - m_file[part_id]->update_create_info(create_info); - } -private: - int copy_partitions(ulonglong * const copied, ulonglong * const deleted); - void cleanup_new_partition(uint part_count); - int prepare_new_partition(TABLE *table, HA_CREATE_INFO *create_info, - handler *file, const char *part_name, - partition_element *p_elem, - uint disable_non_uniq_indexes); - /* - delete_table and rename_table uses very similar logic which - is packed into this routine. - */ - uint del_ren_table(const char *from, const char *to); - /* - One method to create the table_name.par file containing the names of the - underlying partitions, their engine and the number of partitions. - And one method to read it in. - */ - bool create_handler_file(const char *name); - bool setup_engine_array(MEM_ROOT *mem_root); - bool read_par_file(const char *name); - bool get_from_handler_file(const char *name, MEM_ROOT *mem_root, - bool is_clone); - bool new_handlers_from_part_info(MEM_ROOT *mem_root); - bool create_handlers(MEM_ROOT *mem_root); - void clear_handler_file(); - int set_up_table_before_create(TABLE *table_arg, - const char *partition_name_with_path, - HA_CREATE_INFO *info, - partition_element *p_elem); - partition_element *find_partition_element(uint part_id); - bool insert_partition_name_in_hash(const char *name, uint part_id, - bool is_subpart); - bool populate_partition_name_hash(); - Partition_share *get_share(); - bool set_ha_share_ref(Handler_share **ha_share) override; - void fix_data_dir(char* path); - bool init_partition_bitmaps(); - void free_partition_bitmaps(); - -public: - - /* - ------------------------------------------------------------------------- - MODULE open/close object - ------------------------------------------------------------------------- - Open and close handler object to ensure all underlying files and - objects allocated and deallocated for query handling is handled - properly. - ------------------------------------------------------------------------- - - A handler object is opened as part of its initialisation and before - being used for normal queries (not before meta-data changes always. - If the object was opened it will also be closed before being deleted. - */ - int open(const char *name, int mode, uint test_if_locked) override; - int close() override; - - /* - ------------------------------------------------------------------------- - MODULE start/end statement - ------------------------------------------------------------------------- - This module contains methods that are used to understand start/end of - statements, transaction boundaries, and aid for proper concurrency - control. - The partition handler need not implement abort and commit since this - will be handled by any underlying handlers implementing transactions. - There is only one call to each handler type involved per transaction - and these go directly to the handlers supporting transactions - ------------------------------------------------------------------------- - */ - THR_LOCK_DATA **store_lock(THD * thd, THR_LOCK_DATA ** to, - enum thr_lock_type lock_type) override; - int external_lock(THD * thd, int lock_type) override; - LEX_CSTRING *engine_name() override { return hton_name(partition_ht()); } - /* - When table is locked a statement is started by calling start_stmt - instead of external_lock - */ - int start_stmt(THD * thd, thr_lock_type lock_type) override; - /* - Lock count is number of locked underlying handlers (I assume) - */ - uint lock_count() const override; - /* - Call to unlock rows not to be updated in transaction - */ - void unlock_row() override; - /* - Check if semi consistent read - */ - bool was_semi_consistent_read() override; - /* - Call to hint about semi consistent read - */ - void try_semi_consistent_read(bool) override; - - /* - NOTE: due to performance and resource issues with many partitions, - we only use the m_psi on the ha_partition handler, excluding all - partitions m_psi. - */ -#ifdef HAVE_M_PSI_PER_PARTITION - /* - Bind the table/handler thread to track table i/o. - */ - virtual void unbind_psi(); - virtual int rebind(); -#endif - int discover_check_version() override; - /* - ------------------------------------------------------------------------- - MODULE change record - ------------------------------------------------------------------------- - This part of the handler interface is used to change the records - after INSERT, DELETE, UPDATE, REPLACE method calls but also other - special meta-data operations as ALTER TABLE, LOAD DATA, TRUNCATE. - ------------------------------------------------------------------------- - - These methods are used for insert (write_row), update (update_row) - and delete (delete_row). All methods to change data always work on - one row at a time. update_row and delete_row also contains the old - row. - delete_all_rows will delete all rows in the table in one call as a - special optimisation for DELETE from table; - - Bulk inserts are supported if all underlying handlers support it. - start_bulk_insert and end_bulk_insert is called before and after a - number of calls to write_row. - */ - int write_row(const uchar * buf) override; - bool start_bulk_update() override; - int exec_bulk_update(ha_rows *dup_key_found) override; - int end_bulk_update() override; - int bulk_update_row(const uchar *old_data, const uchar *new_data, - ha_rows *dup_key_found) override; - int update_row(const uchar * old_data, const uchar * new_data) override; - int direct_update_rows_init(List *update_fields) override; - int pre_direct_update_rows_init(List *update_fields) override; - int direct_update_rows(ha_rows *update_rows, ha_rows *found_rows) override; - int pre_direct_update_rows() override; - bool start_bulk_delete() override; - int end_bulk_delete() override; - int delete_row(const uchar * buf) override; - int direct_delete_rows_init() override; - int pre_direct_delete_rows_init() override; - int direct_delete_rows(ha_rows *delete_rows) override; - int pre_direct_delete_rows() override; - int delete_all_rows() override; - int truncate() override; - void start_bulk_insert(ha_rows rows, uint flags) override; - int end_bulk_insert() override; -private: - ha_rows guess_bulk_insert_rows(); - void start_part_bulk_insert(THD *thd, uint part_id); - long estimate_read_buffer_size(long original_size); -public: - - /* - Method for truncating a specific partition. - (i.e. ALTER TABLE t1 TRUNCATE PARTITION p). - - @remark This method is a partitioning-specific hook - and thus not a member of the general SE API. - */ - int truncate_partition(Alter_info *, bool *binlog_stmt); - - bool is_fatal_error(int error, uint flags) override - { - if (!handler::is_fatal_error(error, flags) || - error == HA_ERR_NO_PARTITION_FOUND || - error == HA_ERR_NOT_IN_LOCK_PARTITIONS) - return FALSE; - return TRUE; - } - - - /* - ------------------------------------------------------------------------- - MODULE full table scan - ------------------------------------------------------------------------- - This module is used for the most basic access method for any table - handler. This is to fetch all data through a full table scan. No - indexes are needed to implement this part. - It contains one method to start the scan (rnd_init) that can also be - called multiple times (typical in a nested loop join). Then proceeding - to the next record (rnd_next) and closing the scan (rnd_end). - To remember a record for later access there is a method (position) - and there is a method used to retrieve the record based on the stored - position. - The position can be a file position, a primary key, a ROWID dependent - on the handler below. - ------------------------------------------------------------------------- - */ - /* - unlike index_init(), rnd_init() can be called two times - without rnd_end() in between (it only makes sense if scan=1). - then the second call should prepare for the new table scan - (e.g if rnd_init allocates the cursor, second call should - position it to the start of the table, no need to deallocate - and allocate it again - */ - int rnd_init(bool scan) override; - int rnd_end() override; - int rnd_next(uchar * buf) override; - int rnd_pos(uchar * buf, uchar * pos) override; - int rnd_pos_by_record(uchar *record) override; - void position(const uchar * record) override; - - /* - ------------------------------------------------------------------------- - MODULE index scan - ------------------------------------------------------------------------- - This part of the handler interface is used to perform access through - indexes. The interface is defined as a scan interface but the handler - can also use key lookup if the index is a unique index or a primary - key index. - Index scans are mostly useful for SELECT queries but are an important - part also of UPDATE, DELETE, REPLACE and CREATE TABLE table AS SELECT - and so forth. - Naturally an index is needed for an index scan and indexes can either - be ordered, hash based. Some ordered indexes can return data in order - but not necessarily all of them. - There are many flags that define the behavior of indexes in the - various handlers. These methods are found in the optimizer module. - ------------------------------------------------------------------------- - - index_read is called to start a scan of an index. The find_flag defines - the semantics of the scan. These flags are defined in - include/my_base.h - index_read_idx is the same but also initializes index before calling doing - the same thing as index_read. Thus it is similar to index_init followed - by index_read. This is also how we implement it. - - index_read/index_read_idx does also return the first row. Thus for - key lookups, the index_read will be the only call to the handler in - the index scan. - - index_init initializes an index before using it and index_end does - any end processing needed. - */ - int index_read_map(uchar * buf, const uchar * key, - key_part_map keypart_map, - enum ha_rkey_function find_flag) override; - int index_init(uint idx, bool sorted) override; - int index_end() override; - - /** - @breif - Positions an index cursor to the index specified in the handle. Fetches the - row if available. If the key value is null, begin at first key of the - index. - */ - int index_read_idx_map(uchar *buf, uint index, const uchar *key, - key_part_map keypart_map, - enum ha_rkey_function find_flag) override; - /* - These methods are used to jump to next or previous entry in the index - scan. There are also methods to jump to first and last entry. - */ - int index_next(uchar * buf) override; - int index_prev(uchar * buf) override; - int index_first(uchar * buf) override; - int index_last(uchar * buf) override; - int index_next_same(uchar * buf, const uchar * key, uint keylen) override; - - int index_read_last_map(uchar *buf, - const uchar *key, - key_part_map keypart_map) override; - - /* - read_first_row is virtual method but is only implemented by - handler.cc, no storage engine has implemented it so neither - will the partition handler. - - int read_first_row(uchar *buf, uint primary_key) override; - */ - - - int read_range_first(const key_range * start_key, - const key_range * end_key, - bool eq_range, bool sorted) override; - int read_range_next() override; - - - HANDLER_BUFFER *m_mrr_buffer; - uint *m_mrr_buffer_size; - uchar *m_mrr_full_buffer; - uint m_mrr_full_buffer_size; - uint m_mrr_new_full_buffer_size; - MY_BITMAP m_mrr_used_partitions; - uint *m_stock_range_seq; - /* not used: uint m_current_range_seq; */ - - /* Value of mrr_mode passed to ha_partition::multi_range_read_init */ - uint m_mrr_mode; - - /* Value of n_ranges passed to ha_partition::multi_range_read_init */ - uint m_mrr_n_ranges; - - /* - Ordered MRR mode: m_range_info[N] has the range_id of the last record that - we've got from partition N - */ - range_id_t *m_range_info; - - /* - TRUE <=> This ha_partition::multi_range_read_next() call is the first one - */ - bool m_multi_range_read_first; - - /* not used: uint m_mrr_range_init_flags; */ - - /* Number of elements in the list pointed by m_mrr_range_first. Not used */ - uint m_mrr_range_length; - - /* Linked list of ranges to scan */ - PARTITION_KEY_MULTI_RANGE *m_mrr_range_first; - PARTITION_KEY_MULTI_RANGE *m_mrr_range_current; - - /* - For each partition: number of ranges MRR scan will scan in the partition - */ - uint *m_part_mrr_range_length; - - /* For each partition: List of ranges to scan in this partition */ - PARTITION_PART_KEY_MULTI_RANGE **m_part_mrr_range_first; - PARTITION_PART_KEY_MULTI_RANGE **m_part_mrr_range_current; - PARTITION_PART_KEY_MULTI_RANGE_HLD *m_partition_part_key_multi_range_hld; - - /* - Sequence of ranges to be scanned (TODO: why not store this in - handler::mrr_{iter,funcs}?) - */ - range_seq_t m_seq; - RANGE_SEQ_IF *m_seq_if; - - /* Range iterator structure to be supplied to partitions */ - RANGE_SEQ_IF m_part_seq_if; - - virtual int multi_range_key_create_key( - RANGE_SEQ_IF *seq, - range_seq_t seq_it - ); - ha_rows multi_range_read_info_const(uint keyno, RANGE_SEQ_IF *seq, - void *seq_init_param, - uint n_ranges, uint *bufsz, - uint *mrr_mode, - Cost_estimate *cost) override; - ha_rows multi_range_read_info(uint keyno, uint n_ranges, uint keys, - uint key_parts, uint *bufsz, - uint *mrr_mode, Cost_estimate *cost) override; - int multi_range_read_init(RANGE_SEQ_IF *seq, void *seq_init_param, - uint n_ranges, uint mrr_mode, - HANDLER_BUFFER *buf) override; - int multi_range_read_next(range_id_t *range_info) override; - int multi_range_read_explain_info(uint mrr_mode, char *str, size_t size) - override; - uint last_part() { return m_last_part; } - -private: - bool init_record_priority_queue(); - void destroy_record_priority_queue(); - int common_index_read(uchar * buf, bool have_start_key); - int common_first_last(uchar * buf); - int partition_scan_set_up(uchar * buf, bool idx_read_flag); - bool check_parallel_search(); - int handle_pre_scan(bool reverse_order, bool use_parallel); - int handle_unordered_next(uchar * buf, bool next_same); - int handle_unordered_scan_next_partition(uchar * buf); - int handle_ordered_index_scan(uchar * buf, bool reverse_order); - int handle_ordered_index_scan_key_not_found(); - int handle_ordered_next(uchar * buf, bool next_same); - int handle_ordered_prev(uchar * buf); - void return_top_record(uchar * buf); -public: - /* - ------------------------------------------------------------------------- - MODULE information calls - ------------------------------------------------------------------------- - This calls are used to inform the handler of specifics of the ongoing - scans and other actions. Most of these are used for optimisation - purposes. - ------------------------------------------------------------------------- - */ - int info(uint) override; - void get_dynamic_partition_info(PARTITION_STATS *stat_info, uint part_id) - override; - void set_partitions_to_open(List *partition_names) override; - int change_partitions_to_open(List *partition_names) override; - int open_read_partitions(char *name_buff, size_t name_buff_size); - int extra(enum ha_extra_function operation) override; - int extra_opt(enum ha_extra_function operation, ulong arg) override; - int reset() override; - uint count_query_cache_dependant_tables(uint8 *tables_type) override; - my_bool register_query_cache_dependant_tables(THD *thd, - Query_cache *cache, - Query_cache_block_table **block, - uint *n) override; - -private: - typedef int handler_callback(handler *, void *); - - my_bool reg_query_cache_dependant_table(THD *thd, - char *engine_key, - uint engine_key_len, - char *query_key, uint query_key_len, - uint8 type, - Query_cache *cache, - Query_cache_block_table - **block_table, - handler *file, uint *n); - static const uint NO_CURRENT_PART_ID= NOT_A_PARTITION_ID; - int loop_partitions(handler_callback callback, void *param); - int loop_extra_alter(enum ha_extra_function operations); - void late_extra_cache(uint partition_id); - void late_extra_no_cache(uint partition_id); - void prepare_extra_cache(uint cachesize); - handler *get_open_file_sample() const { return m_file_sample; } -public: - - /* - ------------------------------------------------------------------------- - MODULE optimiser support - ------------------------------------------------------------------------- - ------------------------------------------------------------------------- - */ - - /* - NOTE !!!!!! - ------------------------------------------------------------------------- - ------------------------------------------------------------------------- - One important part of the public handler interface that is not depicted in - the methods is the attribute records - - which is defined in the base class. This is looked upon directly and is - set by calling info(HA_STATUS_INFO) ? - ------------------------------------------------------------------------- - */ - -private: - /* Helper functions for optimizer hints. */ - ha_rows min_rows_for_estimate(); - uint get_biggest_used_partition(uint *part_index); -public: - - /* - keys_to_use_for_scanning can probably be implemented as the - intersection of all underlying handlers if mixed handlers are used. - This method is used to derive whether an index can be used for - index-only scanning when performing an ORDER BY query. - Only called from one place in sql_select.cc - */ - const key_map *keys_to_use_for_scanning() override; - - /* - Called in test_quick_select to determine if indexes should be used. - */ - double scan_time() override; - - double key_scan_time(uint inx) override; - - double keyread_time(uint inx, uint ranges, ha_rows rows) override; - - /* - The next method will never be called if you do not implement indexes. - */ - double read_time(uint index, uint ranges, ha_rows rows) override; - /* - For the given range how many records are estimated to be in this range. - Used by optimiser to calculate cost of using a particular index. - */ - ha_rows records_in_range(uint inx, - const key_range * min_key, - const key_range * max_key, - page_range *pages) override; - - /* - Upper bound of number records returned in scan is sum of all - underlying handlers. - */ - ha_rows estimate_rows_upper_bound() override; - - /* - table_cache_type is implemented by the underlying handler but all - underlying handlers must have the same implementation for it to work. - */ - uint8 table_cache_type() override; - ha_rows records() override; - - /* Calculate hash value for PARTITION BY KEY tables. */ - static uint32 calculate_key_hash_value(Field **field_array); - - /* - ------------------------------------------------------------------------- - MODULE print messages - ------------------------------------------------------------------------- - This module contains various methods that returns text messages for - table types, index type and error messages. - ------------------------------------------------------------------------- - */ - /* - The name of the index type that will be used for display - Here we must ensure that all handlers use the same index type - for each index created. - */ - const char *index_type(uint inx) override; - - /* The name of the table type that will be used for display purposes */ - const char *table_type() const; - - /* The name of the row type used for the underlying tables. */ - enum row_type get_row_type() const override; - - /* - Handler specific error messages - */ - void print_error(int error, myf errflag) override; - bool get_error_message(int error, String * buf) override; - /* - ------------------------------------------------------------------------- - MODULE handler characteristics - ------------------------------------------------------------------------- - This module contains a number of methods defining limitations and - characteristics of the handler. The partition handler will calculate - this characteristics based on underlying handler characteristics. - ------------------------------------------------------------------------- - - This is a list of flags that says what the storage engine - implements. The current table flags are documented in handler.h - The partition handler will support whatever the underlying handlers - support except when specifically mentioned below about exceptions - to this rule. - NOTE: This cannot be cached since it can depend on TRANSACTION ISOLATION - LEVEL which is dynamic, see bug#39084. - - HA_READ_RND_SAME: - Not currently used. (Means that the handler supports the rnd_same() call) - (MyISAM, HEAP) - - HA_TABLE_SCAN_ON_INDEX: - Used to avoid scanning full tables on an index. If this flag is set then - the handler always has a primary key (hidden if not defined) and this - index is used for scanning rather than a full table scan in all - situations. - (InnoDB, Federated) - - HA_REC_NOT_IN_SEQ: - This flag is set for handlers that cannot guarantee that the rows are - returned according to incremental positions (0, 1, 2, 3...). - This also means that rnd_next() should return HA_ERR_RECORD_DELETED - if it finds a deleted row. - (MyISAM (not fixed length row), HEAP, InnoDB) - - HA_CAN_GEOMETRY: - Can the storage engine handle spatial data. - Used to check that no spatial attributes are declared unless - the storage engine is capable of handling it. - (MyISAM) - - HA_FAST_KEY_READ: - Setting this flag indicates that the handler is equally fast in - finding a row by key as by position. - This flag is used in a very special situation in conjunction with - filesort's. For further explanation see intro to init_read_record. - (HEAP, InnoDB) - - HA_NULL_IN_KEY: - Is NULL values allowed in indexes. - If this is not allowed then it is not possible to use an index on a - NULLable field. - (HEAP, MyISAM, InnoDB) - - HA_DUPLICATE_POS: - Tells that we can the position for the conflicting duplicate key - record is stored in table->file->dupp_ref. (insert uses rnd_pos() on - this to find the duplicated row) - (MyISAM) - - HA_CAN_INDEX_BLOBS: - Is the storage engine capable of defining an index of a prefix on - a BLOB attribute. - (Federated, MyISAM, InnoDB) - - HA_AUTO_PART_KEY: - Auto increment fields can be part of a multi-part key. For second part - auto-increment keys, the auto_incrementing is done in handler.cc - (Federated, MyISAM) - - HA_REQUIRE_PRIMARY_KEY: - Can't define a table without primary key (and cannot handle a table - with hidden primary key) - (No handler has this limitation currently) - - HA_STATS_RECORDS_IS_EXACT: - Does the counter of records after the info call specify an exact - value or not. If it does this flag is set. - Only MyISAM and HEAP uses exact count. - - HA_CAN_INSERT_DELAYED: - Can the storage engine support delayed inserts. - To start with the partition handler will not support delayed inserts. - Further investigation needed. - (HEAP, MyISAM) - - HA_PRIMARY_KEY_IN_READ_INDEX: - This parameter is set when the handler will also return the primary key - when doing read-only-key on another index. - - HA_NOT_DELETE_WITH_CACHE: - Seems to be an old MyISAM feature that is no longer used. No handler - has it defined but it is checked in init_read_record. - Further investigation needed. - (No handler defines it) - - HA_NO_PREFIX_CHAR_KEYS: - Indexes on prefixes of character fields is not allowed. - (Federated) - - HA_CAN_FULLTEXT: - Does the storage engine support fulltext indexes - The partition handler will start by not supporting fulltext indexes. - (MyISAM) - - HA_CAN_SQL_HANDLER: - Can the HANDLER interface in the MySQL API be used towards this - storage engine. - (MyISAM, InnoDB) - - HA_NO_AUTO_INCREMENT: - Set if the storage engine does not support auto increment fields. - (Currently not set by any handler) - - HA_HAS_CHECKSUM: - Special MyISAM feature. Has special SQL support in CREATE TABLE. - No special handling needed by partition handler. - (MyISAM) - - HA_FILE_BASED: - Should file names always be in lower case (used by engines - that map table names to file names. - Since partition handler has a local file this flag is set. - (Federated, MyISAM) - - HA_CAN_BIT_FIELD: - Is the storage engine capable of handling bit fields? - (MyISAM) - - HA_NEED_READ_RANGE_BUFFER: - Is Read Multi-Range supported => need multi read range buffer - This parameter specifies whether a buffer for read multi range - is needed by the handler. Whether the handler supports this - feature or not is dependent of whether the handler implements - read_multi_range* calls or not. The only handler currently - supporting this feature is NDB so the partition handler need - not handle this call. There are methods in handler.cc that will - transfer those calls into index_read and other calls in the - index scan module. - (No handler defines it) - - HA_PRIMARY_KEY_REQUIRED_FOR_POSITION: - Does the storage engine need a PK for position? - (InnoDB) - - HA_FILE_BASED is always set for partition handler since we use a - special file for handling names of partitions, engine types. - HA_REC_NOT_IN_SEQ is always set for partition handler since we cannot - guarantee that the records will be returned in sequence. - HA_DUPLICATE_POS, - HA_CAN_INSERT_DELAYED, HA_PRIMARY_KEY_REQUIRED_FOR_POSITION is disabled - until further investigated. - */ - Table_flags table_flags() const override; - - /* - This is a bitmap of flags that says how the storage engine - implements indexes. The current index flags are documented in - handler.h. If you do not implement indexes, just return zero - here. - - part is the key part to check. First key part is 0 - If all_parts it's set, MySQL want to know the flags for the combined - index up to and including 'part'. - - HA_READ_NEXT: - Does the index support read next, this is assumed in the server - code and never checked so all indexes must support this. - Note that the handler can be used even if it doesn't have any index. - (HEAP, MyISAM, Federated, InnoDB) - - HA_READ_PREV: - Can the index be used to scan backwards. - (HEAP, MyISAM, InnoDB) - - HA_READ_ORDER: - Can the index deliver its record in index order. Typically true for - all ordered indexes and not true for hash indexes. - In first step this is not true for partition handler until a merge - sort has been implemented in partition handler. - Used to set keymap part_of_sortkey - This keymap is only used to find indexes usable for resolving an ORDER BY - in the query. Thus in most cases index_read will work just fine without - order in result production. When this flag is set it is however safe to - order all output started by index_read since most engines do this. With - read_multi_range calls there is a specific flag setting order or not - order so in those cases ordering of index output can be avoided. - (InnoDB, HEAP, MyISAM) - - HA_READ_RANGE: - Specify whether index can handle ranges, typically true for all - ordered indexes and not true for hash indexes. - Used by optimiser to check if ranges (as key >= 5) can be optimised - by index. - (InnoDB, MyISAM, HEAP) - - HA_ONLY_WHOLE_INDEX: - Can't use part key searches. This is typically true for hash indexes - and typically not true for ordered indexes. - (Federated, HEAP) - - HA_KEYREAD_ONLY: - Does the storage engine support index-only scans on this index. - Enables use of HA_EXTRA_KEYREAD and HA_EXTRA_NO_KEYREAD - Used to set key_map keys_for_keyread and to check in optimiser for - index-only scans. When doing a read under HA_EXTRA_KEYREAD the handler - only have to fill in the columns the key covers. If - HA_PRIMARY_KEY_IN_READ_INDEX is set then also the PRIMARY KEY columns - must be updated in the row. - (InnoDB, MyISAM) - */ - ulong index_flags(uint inx, uint part, bool all_parts) const override - { - /* - The following code is not safe if you are using different - storage engines or different index types per partition. - */ - return m_file[0]->index_flags(inx, part, all_parts); - } - - /** - wrapper function for handlerton alter_table_flags, since - the ha_partition_hton cannot know all its capabilities - */ - alter_table_operations alter_table_flags(alter_table_operations flags) - override; - /* - unireg.cc will call the following to make sure that the storage engine - can handle the data it is about to send. - - The maximum supported values is the minimum of all handlers in the table - */ - uint min_of_the_max_uint(uint (handler::*operator_func)(void) const) const; - uint max_supported_record_length() const override; - uint max_supported_keys() const override; - uint max_supported_key_parts() const override; - uint max_supported_key_length() const override; - uint max_supported_key_part_length() const override; - uint min_record_length(uint options) const override; - - /* - ------------------------------------------------------------------------- - MODULE compare records - ------------------------------------------------------------------------- - cmp_ref checks if two references are the same. For most handlers this is - a simple memcmp of the reference. However some handlers use primary key - as reference and this can be the same even if memcmp says they are - different. This is due to character sets and end spaces and so forth. - For the partition handler the reference is first two bytes providing the - partition identity of the referred record and then the reference of the - underlying handler. - Thus cmp_ref for the partition handler always returns FALSE for records - not in the same partition and uses cmp_ref on the underlying handler - to check whether the rest of the reference part is also the same. - ------------------------------------------------------------------------- - */ - int cmp_ref(const uchar * ref1, const uchar * ref2) override; - /* - ------------------------------------------------------------------------- - MODULE auto increment - ------------------------------------------------------------------------- - This module is used to handle the support of auto increments. - - This variable in the handler is used as part of the handler interface - It is maintained by the parent handler object and should not be - touched by child handler objects (see handler.cc for its use). - - auto_increment_column_changed - ------------------------------------------------------------------------- - */ - bool need_info_for_auto_inc() override; - bool can_use_for_auto_inc_init() override; - void get_auto_increment(ulonglong offset, ulonglong increment, - ulonglong nb_desired_values, - ulonglong *first_value, - ulonglong *nb_reserved_values) override; - void release_auto_increment() override; -private: - int reset_auto_increment(ulonglong value) override; - void update_next_auto_inc_val(); - virtual void lock_auto_increment() - { - /* lock already taken */ - if (auto_increment_safe_stmt_log_lock) - return; - if (table_share->tmp_table == NO_TMP_TABLE) - { - part_share->lock_auto_inc(); - DBUG_ASSERT(!auto_increment_lock); - auto_increment_lock= TRUE; - } - } - virtual void unlock_auto_increment() - { - /* - If auto_increment_safe_stmt_log_lock is true, we have to keep the lock. - It will be set to false and thus unlocked at the end of the statement by - ha_partition::release_auto_increment. - */ - if (auto_increment_lock && !auto_increment_safe_stmt_log_lock) - { - auto_increment_lock= FALSE; - part_share->unlock_auto_inc(); - } - } - virtual void set_auto_increment_if_higher(Field *field) - { - ulonglong nr= (((Field_num*) field)->unsigned_flag || - field->val_int() > 0) ? field->val_int() : 0; - lock_auto_increment(); - DBUG_ASSERT(part_share->auto_inc_initialized || - !can_use_for_auto_inc_init()); - /* must check when the mutex is taken */ - if (nr >= part_share->next_auto_inc_val) - part_share->next_auto_inc_val= nr + 1; - unlock_auto_increment(); - } - - void check_insert_autoincrement() - { - /* - If we INSERT into the table having the AUTO_INCREMENT column, - we have to read all partitions for the next autoincrement value - unless we already did it. - */ - if (!part_share->auto_inc_initialized && - ha_thd()->lex->sql_command == SQLCOM_INSERT && - table->found_next_number_field) - bitmap_set_all(&m_part_info->read_partitions); - } - -public: - - /* - ------------------------------------------------------------------------- - MODULE initialize handler for HANDLER call - ------------------------------------------------------------------------- - This method is a special InnoDB method called before a HANDLER query. - ------------------------------------------------------------------------- - */ - void init_table_handle_for_HANDLER() override; - - /* - The remainder of this file defines the handler methods not implemented - by the partition handler - */ - - /* - ------------------------------------------------------------------------- - MODULE foreign key support - ------------------------------------------------------------------------- - The following methods are used to implement foreign keys as supported by - InnoDB. Implement this ?? - get_foreign_key_create_info is used by SHOW CREATE TABLE to get a textual - description of how the CREATE TABLE part to define FOREIGN KEY's is done. - free_foreign_key_create_info is used to free the memory area that provided - this description. - can_switch_engines checks if it is ok to switch to a new engine based on - the foreign key info in the table. - ------------------------------------------------------------------------- - - virtual char* get_foreign_key_create_info() - virtual void free_foreign_key_create_info(char* str) - - virtual int get_foreign_key_list(THD *thd, - List *f_key_list) - virtual uint referenced_by_foreign_key() - */ - bool can_switch_engines() override; - /* - ------------------------------------------------------------------------- - MODULE fulltext index - ------------------------------------------------------------------------- - */ - void ft_close_search(FT_INFO *handler); - int ft_init() override; - int pre_ft_init() override; - void ft_end() override; - int pre_ft_end() override; - FT_INFO *ft_init_ext(uint flags, uint inx, String *key) override; - int ft_read(uchar *buf) override; - int pre_ft_read(bool use_parallel) override; - - /* - ------------------------------------------------------------------------- - MODULE restart full table scan at position (MyISAM) - ------------------------------------------------------------------------- - The following method is only used by MyISAM when used as - temporary tables in a join. - int restart_rnd_next(uchar *buf, uchar *pos) override; - */ - - /* - ------------------------------------------------------------------------- - MODULE in-place ALTER TABLE - ------------------------------------------------------------------------- - These methods are in the handler interface. (used by innodb-plugin) - They are used for in-place alter table: - ------------------------------------------------------------------------- - */ - enum_alter_inplace_result - check_if_supported_inplace_alter(TABLE *altered_table, - Alter_inplace_info *ha_alter_info) - override; - bool prepare_inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info) - override; - bool inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info) override; - bool commit_inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info, - bool commit) override; - /* - ------------------------------------------------------------------------- - MODULE tablespace support - ------------------------------------------------------------------------- - Admin of table spaces is not applicable to the partition handler (InnoDB) - This means that the following method is not implemented: - ------------------------------------------------------------------------- - virtual int discard_or_import_tablespace(my_bool discard) - */ - - /* - ------------------------------------------------------------------------- - MODULE admin MyISAM - ------------------------------------------------------------------------- - - ------------------------------------------------------------------------- - OPTIMIZE TABLE, CHECK TABLE, ANALYZE TABLE and REPAIR TABLE are - mapped to a routine that handles looping over a given set of - partitions and those routines send a flag indicating to execute on - all partitions. - ------------------------------------------------------------------------- - */ - int optimize(THD* thd, HA_CHECK_OPT *check_opt) override; - int analyze(THD* thd, HA_CHECK_OPT *check_opt) override; - int check(THD* thd, HA_CHECK_OPT *check_opt) override; - int repair(THD* thd, HA_CHECK_OPT *check_opt) override; - bool check_and_repair(THD *thd) override; - bool auto_repair(int error) const override; - bool is_crashed() const override; - int check_for_upgrade(HA_CHECK_OPT *check_opt) override; - - /* - ------------------------------------------------------------------------- - MODULE condition pushdown - ------------------------------------------------------------------------- - */ - const COND *cond_push(const COND *cond) override; - void cond_pop() override; - int info_push(uint info_type, void *info) override; - - private: - int handle_opt_partitions(THD *thd, HA_CHECK_OPT *check_opt, uint flags); - int handle_opt_part(THD *thd, HA_CHECK_OPT *check_opt, uint part_id, - uint flag); - /** - Check if the rows are placed in the correct partition. If the given - argument is true, then move the rows to the correct partition. - */ - int check_misplaced_rows(uint read_part_id, bool repair); - void append_row_to_str(String &str); - public: - - int pre_calculate_checksum() override; - int calculate_checksum() override; - - /* Enabled keycache for performance reasons, WL#4571 */ - int assign_to_keycache(THD* thd, HA_CHECK_OPT *check_opt) override; - int preload_keys(THD* thd, HA_CHECK_OPT* check_opt) override; - TABLE_LIST *get_next_global_for_child() override; - - /* - ------------------------------------------------------------------------- - MODULE enable/disable indexes - ------------------------------------------------------------------------- - Enable/Disable Indexes are only supported by HEAP and MyISAM. - ------------------------------------------------------------------------- - */ - int disable_indexes(uint mode) override; - int enable_indexes(uint mode) override; - int indexes_are_disabled() override; - - /* - ------------------------------------------------------------------------- - MODULE append_create_info - ------------------------------------------------------------------------- - append_create_info is only used by MyISAM MERGE tables and the partition - handler will not support this handler as underlying handler. - Implement this?? - ------------------------------------------------------------------------- - virtual void append_create_info(String *packet) - */ - - /* - the following heavily relies on the fact that all partitions - are in the same storage engine. - - When this limitation is lifted, the following hack should go away, - and a proper interface for engines needs to be introduced: - - an PARTITION_SHARE structure that has a pointer to the TABLE_SHARE. - is given to engines everywhere where TABLE_SHARE is used now - has members like option_struct, ha_data - perhaps TABLE needs to be split the same way too... - - this can also be done before partition will support a mix of engines, - but preferably together with other incompatible API changes. - */ - handlerton *partition_ht() const override - { - handlerton *h= m_file[0]->ht; - for (uint i=1; i < m_tot_parts; i++) - DBUG_ASSERT(h == m_file[i]->ht); - return h; - } - - ha_rows part_records(partition_element *part_elem) - { - DBUG_ASSERT(m_part_info); - uint32 sub_factor= m_part_info->num_subparts ? m_part_info->num_subparts : 1; - uint32 part_id= part_elem->id * sub_factor; - uint32 part_id_end= part_id + sub_factor; - DBUG_ASSERT(part_id_end <= m_tot_parts); - ha_rows part_recs= 0; - for (; part_id < part_id_end; ++part_id) - { - handler *file= m_file[part_id]; - DBUG_ASSERT(bitmap_is_set(&(m_part_info->read_partitions), part_id)); - file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_OPEN); - part_recs+= file->stats.records; - } - return part_recs; - } - - friend int cmp_key_rowid_part_id(void *ptr, uchar *ref1, uchar *ref2); - friend int cmp_key_part_id(void *key_p, uchar *ref1, uchar *ref2); - bool can_convert_string( - const Field_string* field, - const Column_definition& new_field) const override; - - bool can_convert_varstring( - const Field_varstring* field, - const Column_definition& new_field) const override; - - bool can_convert_blob( - const Field_blob* field, - const Column_definition& new_field) const override; -}; -#endif /* HA_PARTITION_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ha_sequence.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/ha_sequence.h deleted file mode 100644 index 72e59a4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ha_sequence.h +++ /dev/null @@ -1,165 +0,0 @@ -#ifndef HA_SEQUENCE_INCLUDED -#define HA_SEQUENCE_INCLUDED -/* - Copyright (c) 2017 Aliyun and/or its affiliates. - Copyright (c) 2017 MariaDB corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "sql_sequence.h" -#include "table.h" -#include "handler.h" - -extern handlerton *sql_sequence_hton; - -/* - Sequence engine handler. - - The sequence engine is a logic engine. It doesn't store any data. - All the sequence data stored into the base table which must support - non rollback writes (HA_CAN_TABLES_WITHOUT_ROLLBACK) - - The sequence data (SEQUENCE class) is stored in TABLE_SHARE->sequence - - TABLE RULES: - 1. When table is created, one row is automaticlly inserted into - the table. The table will always have one and only one row. - 2. Any inserts or updates to the table will be validated. - 3. Inserts will overwrite the original row. - 4. DELETE and TRUNCATE will not affect the table. - Instead a warning will be given. - 5. Cache will be reset for any updates. - - CACHE RULES: - SEQUENCE class is used to cache values that sequence defined. - 1. If hit cache, we can query back the sequence nextval directly - instead of reading the underlying table. - - 2. When run out of values, the sequence engine will reserve new values - in update the base table. - - 3. The cache is invalidated if any update on based table. -*/ - -class ha_sequence :public handler -{ -private: - handler *file; - SEQUENCE *sequence; /* From table_share->sequence */ - -public: - /* Set when handler is write locked */ - bool write_locked; - - ha_sequence(handlerton *hton, TABLE_SHARE *share); - ~ha_sequence(); - - /* virtual function that are re-implemented for sequence */ - int open(const char *name, int mode, uint test_if_locked); - int create(const char *name, TABLE *form, - HA_CREATE_INFO *create_info); - handler *clone(const char *name, MEM_ROOT *mem_root); - int write_row(const uchar *buf); - Table_flags table_flags() const; - /* One can't update or delete from sequence engine */ - int update_row(const uchar *old_data, const uchar *new_data) - { return HA_ERR_WRONG_COMMAND; } - int delete_row(const uchar *buf) - { return HA_ERR_WRONG_COMMAND; } - /* One can't delete from sequence engine */ - int truncate() - { return HA_ERR_WRONG_COMMAND; } - /* Can't use query cache */ - uint8 table_cache_type() - { return HA_CACHE_TBL_NOCACHE; } - void print_error(int error, myf errflag); - int info(uint); - LEX_CSTRING *engine_name() { return hton_name(file->ht); } - int external_lock(THD *thd, int lock_type); - int extra(enum ha_extra_function operation); - /* For ALTER ONLINE TABLE */ - bool check_if_incompatible_data(HA_CREATE_INFO *create_info, - uint table_changes); - void write_lock() { write_locked= 1;} - void unlock() { write_locked= 0; } - bool is_locked() { return write_locked; } - - /* Functions that are directly mapped to the underlying handler */ - int rnd_init(bool scan) - { return file->rnd_init(scan); } - /* - We need to have a lock here to protect engines like MyISAM from - simultaneous read and write. For sequence's this is not critical - as this function is used extremely seldom. - */ - int rnd_next(uchar *buf) - { - int error; - table->s->sequence->read_lock(table); - error= file->rnd_next(buf); - table->s->sequence->read_unlock(table); - return error; - } - int rnd_end() - { return file->rnd_end(); } - int rnd_pos(uchar *buf, uchar *pos) - { - int error; - table->s->sequence->read_lock(table); - error= file->rnd_pos(buf, pos); - table->s->sequence->read_unlock(table); - return error; - } - void position(const uchar *record) - { return file->position(record); } - const char *table_type() const - { return file->table_type(); } - ulong index_flags(uint inx, uint part, bool all_parts) const - { return file->index_flags(inx, part, all_parts); } - THR_LOCK_DATA **store_lock(THD *thd, THR_LOCK_DATA **to, - enum thr_lock_type lock_type) - { return file->store_lock(thd, to, lock_type); } - int close(void) - { return file->close(); } - const char **bas_ext() const - { return file->bas_ext(); } - int delete_table(const char*name) - { return file->delete_table(name); } - int rename_table(const char *from, const char *to) - { return file->rename_table(from, to); } - void unbind_psi() - { file->unbind_psi(); } - void rebind_psi() - { file->rebind_psi(); } - - bool auto_repair(int error) const - { return file->auto_repair(error); } - int repair(THD* thd, HA_CHECK_OPT* check_opt) - { return file->repair(thd, check_opt); } - bool check_and_repair(THD *thd) - { return file->check_and_repair(thd); } - bool is_crashed() const - { return file->is_crashed(); } - void column_bitmaps_signal() - { return file->column_bitmaps_signal(); } - - /* New methods */ - void register_original_handler(handler *file_arg) - { - file= file_arg; - init(); /* Update cached_table_flags */ - } -}; -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/handle_connections_win.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/handle_connections_win.h deleted file mode 100644 index bf66c08..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/handle_connections_win.h +++ /dev/null @@ -1,21 +0,0 @@ -/* Copyright (c) 2018 MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - -/** - Handles incoming socket and pipe connections, on Windows. - Creates new (THD) connections.. -*/ -extern void handle_connections_win(); -extern void network_init_win(); diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/handler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/handler.h deleted file mode 100644 index e06b6a7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/handler.h +++ /dev/null @@ -1,5314 +0,0 @@ -#ifndef HANDLER_INCLUDED -#define HANDLER_INCLUDED -/* - Copyright (c) 2000, 2019, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -/* Definitions for parameters to do with handler-routines */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_const.h" -#include "sql_basic_types.h" -#include "mysqld.h" /* server_id */ -#include "sql_plugin.h" /* plugin_ref, st_plugin_int, plugin */ -#include "thr_lock.h" /* thr_lock_type, THR_LOCK_DATA */ -#include "sql_cache.h" -#include "structs.h" /* SHOW_COMP_OPTION */ -#include "sql_array.h" /* Dynamic_array<> */ -#include "mdl.h" -#include "vers_string.h" - -#include "sql_analyze_stmt.h" // for Exec_time_tracker - -#include -#include -#include -#include -#include "sql_sequence.h" -#include "mem_root_array.h" - -class Alter_info; -class Virtual_column_info; -class sequence_definition; -class Rowid_filter; -class Field_string; -class Field_varstring; -class Field_blob; -class Column_definition; - -// the following is for checking tables - -#define HA_ADMIN_ALREADY_DONE 1 -#define HA_ADMIN_OK 0 -#define HA_ADMIN_NOT_IMPLEMENTED -1 -#define HA_ADMIN_FAILED -2 -#define HA_ADMIN_CORRUPT -3 -#define HA_ADMIN_INTERNAL_ERROR -4 -#define HA_ADMIN_INVALID -5 -#define HA_ADMIN_REJECT -6 -#define HA_ADMIN_TRY_ALTER -7 -#define HA_ADMIN_WRONG_CHECKSUM -8 -#define HA_ADMIN_NOT_BASE_TABLE -9 -#define HA_ADMIN_NEEDS_UPGRADE -10 -#define HA_ADMIN_NEEDS_ALTER -11 -#define HA_ADMIN_NEEDS_CHECK -12 -#define HA_ADMIN_COMMIT_ERROR -13 - -/** - Return values for check_if_supported_inplace_alter(). - - @see check_if_supported_inplace_alter() for description of - the individual values. -*/ -enum enum_alter_inplace_result { - HA_ALTER_ERROR, - HA_ALTER_INPLACE_COPY_NO_LOCK, - HA_ALTER_INPLACE_COPY_LOCK, - HA_ALTER_INPLACE_NOCOPY_LOCK, - HA_ALTER_INPLACE_NOCOPY_NO_LOCK, - HA_ALTER_INPLACE_INSTANT, - HA_ALTER_INPLACE_NOT_SUPPORTED, - HA_ALTER_INPLACE_EXCLUSIVE_LOCK, - HA_ALTER_INPLACE_SHARED_LOCK, - HA_ALTER_INPLACE_NO_LOCK -}; - -/* Flags for create_partitioning_metadata() */ - -enum chf_create_flags { - CHF_CREATE_FLAG, - CHF_DELETE_FLAG, - CHF_RENAME_FLAG, - CHF_INDEX_FLAG -}; - -/* Bits in table_flags() to show what database can do */ - -#define HA_NO_TRANSACTIONS (1ULL << 0) /* Doesn't support transactions */ -#define HA_PARTIAL_COLUMN_READ (1ULL << 1) /* read may not return all columns */ -#define HA_TABLE_SCAN_ON_INDEX (1ULL << 2) /* No separate data/index file */ -/* - The following should be set if the following is not true when scanning - a table with rnd_next() - - We will see all rows (including deleted ones) - - Row positions are 'table->s->db_record_offset' apart - If this flag is not set, filesort will do a position() call for each matched - row to be able to find the row later. -*/ -#define HA_REC_NOT_IN_SEQ (1ULL << 3) -#define HA_CAN_GEOMETRY (1ULL << 4) -/* - Reading keys in random order is as fast as reading keys in sort order - (Used in records.cc to decide if we should use a record cache and by - filesort to decide if we should sort key + data or key + pointer-to-row -*/ -#define HA_FAST_KEY_READ (1ULL << 5) -/* - Set the following flag if we on delete should force all key to be read - and on update read all keys that changes -*/ -#define HA_REQUIRES_KEY_COLUMNS_FOR_DELETE (1ULL << 6) -#define HA_NULL_IN_KEY (1ULL << 7) /* One can have keys with NULL */ -#define HA_DUPLICATE_POS (1ULL << 8) /* ha_position() gives dup row */ -#define HA_NO_BLOBS (1ULL << 9) /* Doesn't support blobs */ -#define HA_CAN_INDEX_BLOBS (1ULL << 10) -#define HA_AUTO_PART_KEY (1ULL << 11) /* auto-increment in multi-part key */ -/* - The engine requires every table to have a user-specified PRIMARY KEY. - Do not set the flag if the engine can generate a hidden primary key internally. - This flag is ignored if a SEQUENCE is created (which, in turn, needs - HA_CAN_TABLES_WITHOUT_ROLLBACK flag) -*/ -#define HA_REQUIRE_PRIMARY_KEY (1ULL << 12) -#define HA_STATS_RECORDS_IS_EXACT (1ULL << 13) /* stats.records is exact */ -/* - INSERT_DELAYED only works with handlers that uses MySQL internal table - level locks -*/ -#define HA_CAN_INSERT_DELAYED (1ULL << 14) -/* - If we get the primary key columns for free when we do an index read - (usually, it also implies that HA_PRIMARY_KEY_REQUIRED_FOR_POSITION - flag is set). -*/ -#define HA_PRIMARY_KEY_IN_READ_INDEX (1ULL << 15) -/* - If HA_PRIMARY_KEY_REQUIRED_FOR_POSITION is set, it means that to position() - uses a primary key given by the record argument. - Without primary key, we can't call position(). - If not set, the position is returned as the current rows position - regardless of what argument is given. -*/ -#define HA_PRIMARY_KEY_REQUIRED_FOR_POSITION (1ULL << 16) -#define HA_CAN_RTREEKEYS (1ULL << 17) -#define HA_NOT_DELETE_WITH_CACHE (1ULL << 18) /* unused */ -/* - The following is we need to a primary key to delete (and update) a row. - If there is no primary key, all columns needs to be read on update and delete -*/ -#define HA_PRIMARY_KEY_REQUIRED_FOR_DELETE (1ULL << 19) -#define HA_NO_PREFIX_CHAR_KEYS (1ULL << 20) -#define HA_CAN_FULLTEXT (1ULL << 21) -#define HA_CAN_SQL_HANDLER (1ULL << 22) -#define HA_NO_AUTO_INCREMENT (1ULL << 23) -/* Has automatic checksums and uses the old checksum format */ -#define HA_HAS_OLD_CHECKSUM (1ULL << 24) -/* Table data are stored in separate files (for lower_case_table_names) */ -#define HA_FILE_BASED (1ULL << 26) -#define HA_CAN_BIT_FIELD (1ULL << 28) /* supports bit fields */ -#define HA_NEED_READ_RANGE_BUFFER (1ULL << 29) /* for read_multi_range */ -#define HA_ANY_INDEX_MAY_BE_UNIQUE (1ULL << 30) -#define HA_NO_COPY_ON_ALTER (1ULL << 31) -#define HA_HAS_RECORDS (1ULL << 32) /* records() gives exact count*/ -/* Has it's own method of binlog logging */ -#define HA_HAS_OWN_BINLOGGING (1ULL << 33) -/* - Engine is capable of row-format and statement-format logging, - respectively -*/ -#define HA_BINLOG_ROW_CAPABLE (1ULL << 34) -#define HA_BINLOG_STMT_CAPABLE (1ULL << 35) - -/* - When a multiple key conflict happens in a REPLACE command mysql - expects the conflicts to be reported in the ascending order of - key names. - - For e.g. - - CREATE TABLE t1 (a INT, UNIQUE (a), b INT NOT NULL, UNIQUE (b), c INT NOT - NULL, INDEX(c)); - - REPLACE INTO t1 VALUES (1,1,1),(2,2,2),(2,1,3); - - MySQL expects the conflict with 'a' to be reported before the conflict with - 'b'. - - If the underlying storage engine does not report the conflicting keys in - ascending order, it causes unexpected errors when the REPLACE command is - executed. - - This flag helps the underlying SE to inform the server that the keys are not - ordered. -*/ -#define HA_DUPLICATE_KEY_NOT_IN_ORDER (1ULL << 36) - -/* - Engine supports REPAIR TABLE. Used by CHECK TABLE FOR UPGRADE if an - incompatible table is detected. If this flag is set, CHECK TABLE FOR UPGRADE - will report ER_TABLE_NEEDS_UPGRADE, otherwise ER_TABLE_NEED_REBUILD. -*/ -#define HA_CAN_REPAIR (1ULL << 37) - -/* Has automatic checksums and uses the new checksum format */ -#define HA_HAS_NEW_CHECKSUM (1ULL << 38) -#define HA_CAN_VIRTUAL_COLUMNS (1ULL << 39) -#define HA_MRR_CANT_SORT (1ULL << 40) -/* All of VARCHAR is stored, including bytes after real varchar data */ -#define HA_RECORD_MUST_BE_CLEAN_ON_WRITE (1ULL << 41) - -/* - This storage engine supports condition pushdown -*/ -#define HA_CAN_TABLE_CONDITION_PUSHDOWN (1ULL << 42) -/* old name for the same flag */ -#define HA_MUST_USE_TABLE_CONDITION_PUSHDOWN HA_CAN_TABLE_CONDITION_PUSHDOWN - -/** - The handler supports read before write removal optimization - - Read before write removal may be used for storage engines which support - write without previous read of the row to be updated. Handler returning - this flag must implement start_read_removal() and end_read_removal(). - The handler may return "fake" rows constructed from the key of the row - asked for. This is used to optimize UPDATE and DELETE by reducing the - number of roundtrips between handler and storage engine. - - Example: - UPDATE a=1 WHERE pk IN () - - mysql_update() - { - if () - start_read_removal() - -> handler returns true if read removal supported for this table/query - - while(read_record("pk=")) - -> handler returns fake row with column "pk" set to - - ha_update_row() - -> handler sends write "a=1" for row with "pk=" - - end_read_removal() - -> handler returns the number of rows actually written - } - - @note This optimization in combination with batching may be used to - remove even more roundtrips. -*/ -#define HA_READ_BEFORE_WRITE_REMOVAL (1ULL << 43) - -/* - Engine supports extended fulltext API - */ -#define HA_CAN_FULLTEXT_EXT (1ULL << 44) - -/* - Storage engine supports table export using the - FLUSH TABLE FOR EXPORT statement - (meaning, after this statement one can copy table files out of the - datadir and later "import" (somehow) in another MariaDB instance) - */ -#define HA_CAN_EXPORT (1ULL << 45) - -/* - Storage engine does not require an exclusive metadata lock - on the table during optimize. (TODO and repair?). - It can allow other connections to open the table. - (it does not necessarily mean that other connections can - read or modify the table - this is defined by THR locks and the - ::store_lock() method). -*/ -#define HA_CONCURRENT_OPTIMIZE (1ULL << 46) - -/* - If the storage engine support tables that will not roll back on commit - In addition the table should not lock rows and support READ and WRITE - UNCOMMITTED. - This is useful for implementing things like SEQUENCE but can also in - the future be useful to do logging that should never roll back. -*/ -#define HA_CAN_TABLES_WITHOUT_ROLLBACK (1ULL << 47) - -/* - Mainly for usage by SEQUENCE engine. Setting this flag means - that the table will never roll back and that all operations - for this table should stored in the non transactional log - space that will always be written, even on rollback. -*/ - -#define HA_PERSISTENT_TABLE (1ULL << 48) - -/* If storage engine uses another engine as a base */ -#define HA_REUSES_FILE_NAMES (1ULL << 49) - -/* - Set of all binlog flags. Currently only contain the capabilities - flags. - */ -#define HA_BINLOG_FLAGS (HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE) - -/* The following are used by Spider */ -#define HA_CAN_FORCE_BULK_UPDATE (1ULL << 50) -#define HA_CAN_FORCE_BULK_DELETE (1ULL << 51) -#define HA_CAN_DIRECT_UPDATE_AND_DELETE (1ULL << 52) - -/* The following is for partition handler */ -#define HA_CAN_MULTISTEP_MERGE (1LL << 53) - -/* calling cmp_ref() on the engine is expensive */ -#define HA_SLOW_CMP_REF (1ULL << 54) -#define HA_CMP_REF_IS_EXPENSIVE HA_SLOW_CMP_REF - -/** - Some engines are unable to provide an efficient implementation for rnd_pos(). - Server will try to avoid it, if possible - - TODO better to do it with cost estimates, not with an explicit flag -*/ -#define HA_SLOW_RND_POS (1ULL << 55) - -/* Safe for online backup */ -#define HA_CAN_ONLINE_BACKUPS (1ULL << 56) - -/* Support native hash index */ -#define HA_CAN_HASH_KEYS (1ULL << 57) -#define HA_CRASH_SAFE (1ULL << 58) - -/* - There is no need to evict the table from the table definition cache having - run ANALYZE TABLE on it - */ -#define HA_ONLINE_ANALYZE (1ULL << 59) - -#define HA_LAST_TABLE_FLAG HA_ONLINE_ANALYZE - - -/* bits in index_flags(index_number) for what you can do with index */ -#define HA_READ_NEXT 1 /* TODO really use this flag */ -#define HA_READ_PREV 2 /* supports ::index_prev */ -#define HA_READ_ORDER 4 /* index_next/prev follow sort order */ -#define HA_READ_RANGE 8 /* can find all records in a range */ -#define HA_ONLY_WHOLE_INDEX 16 /* Can't use part key searches */ -#define HA_KEYREAD_ONLY 64 /* Support HA_EXTRA_KEYREAD */ - -/* - Index scan will not return records in rowid order. Not guaranteed to be - set for unordered (e.g. HASH) indexes. -*/ -#define HA_KEY_SCAN_NOT_ROR 128 -#define HA_DO_INDEX_COND_PUSHDOWN 256 /* Supports Index Condition Pushdown */ -/* - Data is clustered on this key. This means that when you read the key - you also get the row data without any additional disk reads. -*/ -#define HA_CLUSTERED_INDEX 512 - -#define HA_DO_RANGE_FILTER_PUSHDOWN 1024 - -/* - bits in alter_table_flags: -*/ -/* - These bits are set if different kinds of indexes can be created or dropped - in-place without re-creating the table using a temporary table. - NO_READ_WRITE indicates that the handler needs concurrent reads and writes - of table data to be blocked. - Partitioning needs both ADD and DROP to be supported by its underlying - handlers, due to error handling, see bug#57778. -*/ -#define HA_INPLACE_ADD_INDEX_NO_READ_WRITE (1UL << 0) -#define HA_INPLACE_DROP_INDEX_NO_READ_WRITE (1UL << 1) -#define HA_INPLACE_ADD_UNIQUE_INDEX_NO_READ_WRITE (1UL << 2) -#define HA_INPLACE_DROP_UNIQUE_INDEX_NO_READ_WRITE (1UL << 3) -#define HA_INPLACE_ADD_PK_INDEX_NO_READ_WRITE (1UL << 4) -#define HA_INPLACE_DROP_PK_INDEX_NO_READ_WRITE (1UL << 5) -/* - These are set if different kinds of indexes can be created or dropped - in-place while still allowing concurrent reads (but not writes) of table - data. If a handler is capable of one or more of these, it should also set - the corresponding *_NO_READ_WRITE bit(s). -*/ -#define HA_INPLACE_ADD_INDEX_NO_WRITE (1UL << 6) -#define HA_INPLACE_DROP_INDEX_NO_WRITE (1UL << 7) -#define HA_INPLACE_ADD_UNIQUE_INDEX_NO_WRITE (1UL << 8) -#define HA_INPLACE_DROP_UNIQUE_INDEX_NO_WRITE (1UL << 9) -#define HA_INPLACE_ADD_PK_INDEX_NO_WRITE (1UL << 10) -#define HA_INPLACE_DROP_PK_INDEX_NO_WRITE (1UL << 11) -/* - HA_PARTITION_FUNCTION_SUPPORTED indicates that the function is - supported at all. - HA_FAST_CHANGE_PARTITION means that optimised variants of the changes - exists but they are not necessarily done online. - - HA_ONLINE_DOUBLE_WRITE means that the handler supports writing to both - the new partition and to the old partitions when updating through the - old partitioning schema while performing a change of the partitioning. - This means that we can support updating of the table while performing - the copy phase of the change. For no lock at all also a double write - from new to old must exist and this is not required when this flag is - set. - This is actually removed even before it was introduced the first time. - The new idea is that handlers will handle the lock level already in - store_lock for ALTER TABLE partitions. - - HA_PARTITION_ONE_PHASE is a flag that can be set by handlers that take - care of changing the partitions online and in one phase. Thus all phases - needed to handle the change are implemented inside the storage engine. - The storage engine must also support auto-discovery since the frm file - is changed as part of the change and this change must be controlled by - the storage engine. A typical engine to support this is NDB (through - WL #2498). -*/ -#define HA_PARTITION_FUNCTION_SUPPORTED (1UL << 12) -#define HA_FAST_CHANGE_PARTITION (1UL << 13) -#define HA_PARTITION_ONE_PHASE (1UL << 14) - -/* operations for disable/enable indexes */ -#define HA_KEY_SWITCH_NONUNIQ 0 -#define HA_KEY_SWITCH_ALL 1 -#define HA_KEY_SWITCH_NONUNIQ_SAVE 2 -#define HA_KEY_SWITCH_ALL_SAVE 3 - -/* - Note: the following includes binlog and closing 0. - TODO remove the limit, use dynarrays -*/ -#define MAX_HA 64 - -/* - Use this instead of 0 as the initial value for the slot number of - handlerton, so that we can distinguish uninitialized slot number - from slot 0. -*/ -#define HA_SLOT_UNDEF ((uint)-1) - -/* - Parameters for open() (in register form->filestat) - HA_GET_INFO does an implicit HA_ABORT_IF_LOCKED -*/ - -#define HA_OPEN_KEYFILE 1U -#define HA_READ_ONLY 16U /* File opened as readonly */ -/* Try readonly if can't open with read and write */ -#define HA_TRY_READ_ONLY 32U - - /* Some key definitions */ -#define HA_KEY_NULL_LENGTH 1 -#define HA_KEY_BLOB_LENGTH 2 - -/* Maximum length of any index lookup key, in bytes */ - -#define MAX_KEY_LENGTH (MAX_DATA_LENGTH_FOR_KEY \ - +(MAX_REF_PARTS \ - *(HA_KEY_NULL_LENGTH + HA_KEY_BLOB_LENGTH))) - -#define HA_LEX_CREATE_TMP_TABLE 1U -#define HA_CREATE_TMP_ALTER 8U -#define HA_LEX_CREATE_SEQUENCE 16U -#define HA_VERSIONED_TABLE 32U - -#define HA_MAX_REC_LENGTH 65535 - -/* Table caching type */ -#define HA_CACHE_TBL_NONTRANSACT 0 -#define HA_CACHE_TBL_NOCACHE 1U -#define HA_CACHE_TBL_ASKTRANSACT 2U -#define HA_CACHE_TBL_TRANSACT 4U - -/** - Options for the START TRANSACTION statement. - - Note that READ ONLY and READ WRITE are logically mutually exclusive. - This is enforced by the parser and depended upon by trans_begin(). - - We need two flags instead of one in order to differentiate between - situation when no READ WRITE/ONLY clause were given and thus transaction - is implicitly READ WRITE and the case when READ WRITE clause was used - explicitly. -*/ - -// WITH CONSISTENT SNAPSHOT option -static const uint MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT = 1; -// READ ONLY option -static const uint MYSQL_START_TRANS_OPT_READ_ONLY = 2; -// READ WRITE option -static const uint MYSQL_START_TRANS_OPT_READ_WRITE = 4; - -/* Flags for method is_fatal_error */ -#define HA_CHECK_DUP_KEY 1U -#define HA_CHECK_DUP_UNIQUE 2U -#define HA_CHECK_FK_ERROR 4U -#define HA_CHECK_DUP (HA_CHECK_DUP_KEY + HA_CHECK_DUP_UNIQUE) -#define HA_CHECK_ALL (~0U) - -/* Options for info_push() */ -#define INFO_KIND_UPDATE_FIELDS 101 -#define INFO_KIND_UPDATE_VALUES 102 -#define INFO_KIND_FORCE_LIMIT_BEGIN 103 -#define INFO_KIND_FORCE_LIMIT_END 104 - -enum legacy_db_type -{ - /* note these numerical values are fixed and can *not* be changed */ - DB_TYPE_UNKNOWN=0, - DB_TYPE_HEAP=6, - DB_TYPE_MYISAM=9, - DB_TYPE_MRG_MYISAM=10, - DB_TYPE_INNODB=12, - DB_TYPE_EXAMPLE_DB=15, - DB_TYPE_ARCHIVE_DB=16, - DB_TYPE_CSV_DB=17, - DB_TYPE_FEDERATED_DB=18, - DB_TYPE_BLACKHOLE_DB=19, - DB_TYPE_PARTITION_DB=20, - DB_TYPE_BINLOG=21, - DB_TYPE_PBXT=23, - DB_TYPE_PERFORMANCE_SCHEMA=28, - DB_TYPE_S3=41, - DB_TYPE_ARIA=42, - DB_TYPE_TOKUDB=43, - DB_TYPE_SEQUENCE=44, - DB_TYPE_FIRST_DYNAMIC=45, - DB_TYPE_DEFAULT=127 // Must be last -}; -/* - Better name for DB_TYPE_UNKNOWN. Should be used for engines that do not have - a hard-coded type value here. - */ -#define DB_TYPE_AUTOASSIGN DB_TYPE_UNKNOWN - -enum row_type { ROW_TYPE_NOT_USED=-1, ROW_TYPE_DEFAULT, ROW_TYPE_FIXED, - ROW_TYPE_DYNAMIC, ROW_TYPE_COMPRESSED, - ROW_TYPE_REDUNDANT, ROW_TYPE_COMPACT, ROW_TYPE_PAGE }; - -/* not part of the enum, so that it shouldn't be in switch(row_type) */ -#define ROW_TYPE_MAX ((uint)ROW_TYPE_PAGE + 1) - -/* Specifies data storage format for individual columns */ -enum column_format_type { - COLUMN_FORMAT_TYPE_DEFAULT= 0, /* Not specified (use engine default) */ - COLUMN_FORMAT_TYPE_FIXED= 1, /* FIXED format */ - COLUMN_FORMAT_TYPE_DYNAMIC= 2 /* DYNAMIC format */ -}; - -enum enum_binlog_func { - BFN_RESET_LOGS= 1, - BFN_RESET_SLAVE= 2, - BFN_BINLOG_WAIT= 3, - BFN_BINLOG_END= 4, - BFN_BINLOG_PURGE_FILE= 5 -}; - -enum enum_binlog_command { - LOGCOM_CREATE_TABLE, - LOGCOM_ALTER_TABLE, - LOGCOM_RENAME_TABLE, - LOGCOM_DROP_TABLE, - LOGCOM_CREATE_DB, - LOGCOM_ALTER_DB, - LOGCOM_DROP_DB -}; - -/* struct to hold information about the table that should be created */ - -/* Bits in used_fields */ -#define HA_CREATE_USED_AUTO (1UL << 0) -#define HA_CREATE_USED_RAID (1UL << 1) //RAID is no longer available -#define HA_CREATE_USED_UNION (1UL << 2) -#define HA_CREATE_USED_INSERT_METHOD (1UL << 3) -#define HA_CREATE_USED_MIN_ROWS (1UL << 4) -#define HA_CREATE_USED_MAX_ROWS (1UL << 5) -#define HA_CREATE_USED_AVG_ROW_LENGTH (1UL << 6) -#define HA_CREATE_USED_PACK_KEYS (1UL << 7) -#define HA_CREATE_USED_CHARSET (1UL << 8) -#define HA_CREATE_USED_DEFAULT_CHARSET (1UL << 9) -#define HA_CREATE_USED_DATADIR (1UL << 10) -#define HA_CREATE_USED_INDEXDIR (1UL << 11) -#define HA_CREATE_USED_ENGINE (1UL << 12) -#define HA_CREATE_USED_CHECKSUM (1UL << 13) -#define HA_CREATE_USED_DELAY_KEY_WRITE (1UL << 14) -#define HA_CREATE_USED_ROW_FORMAT (1UL << 15) -#define HA_CREATE_USED_COMMENT (1UL << 16) -#define HA_CREATE_USED_PASSWORD (1UL << 17) -#define HA_CREATE_USED_CONNECTION (1UL << 18) -#define HA_CREATE_USED_KEY_BLOCK_SIZE (1UL << 19) -/* The following two are used by Maria engine: */ -#define HA_CREATE_USED_TRANSACTIONAL (1UL << 20) -#define HA_CREATE_USED_PAGE_CHECKSUM (1UL << 21) -/** This is set whenever STATS_PERSISTENT=0|1|default has been -specified in CREATE/ALTER TABLE. See also HA_OPTION_STATS_PERSISTENT in -include/my_base.h. It is possible to distinguish whether -STATS_PERSISTENT=default has been specified or no STATS_PERSISTENT= is -given at all. */ -#define HA_CREATE_USED_STATS_PERSISTENT (1UL << 22) -/** - This is set whenever STATS_AUTO_RECALC=0|1|default has been - specified in CREATE/ALTER TABLE. See enum_stats_auto_recalc. - It is possible to distinguish whether STATS_AUTO_RECALC=default - has been specified or no STATS_AUTO_RECALC= is given at all. -*/ -#define HA_CREATE_USED_STATS_AUTO_RECALC (1UL << 23) -/** - This is set whenever STATS_SAMPLE_PAGES=N|default has been - specified in CREATE/ALTER TABLE. It is possible to distinguish whether - STATS_SAMPLE_PAGES=default has been specified or no STATS_SAMPLE_PAGES= is - given at all. -*/ -#define HA_CREATE_USED_STATS_SAMPLE_PAGES (1UL << 24) - -/* Create a sequence */ -#define HA_CREATE_USED_SEQUENCE (1UL << 25) -/* Tell binlog_show_create_table to print all engine options */ -#define HA_CREATE_PRINT_ALL_OPTIONS (1UL << 26) - -typedef ulonglong alter_table_operations; -typedef bool Log_func(THD*, TABLE*, bool, const uchar*, const uchar*); - -/* - These flags are set by the parser and describes the type of - operation(s) specified by the ALTER TABLE statement. -*/ - -// Set by parser for ADD [COLUMN] -#define ALTER_PARSER_ADD_COLUMN (1ULL << 0) -// Set by parser for DROP [COLUMN] -#define ALTER_PARSER_DROP_COLUMN (1ULL << 1) -// Set for CHANGE [COLUMN] | MODIFY [CHANGE] & mysql_recreate_table -#define ALTER_CHANGE_COLUMN (1ULL << 2) -// Set for ADD INDEX | ADD KEY | ADD PRIMARY KEY | ADD UNIQUE KEY | -// ADD UNIQUE INDEX | ALTER ADD [COLUMN] -#define ALTER_ADD_INDEX (1ULL << 3) -// Set for DROP PRIMARY KEY | DROP FOREIGN KEY | DROP KEY | DROP INDEX -#define ALTER_DROP_INDEX (1ULL << 4) -// Set for RENAME [TO] -#define ALTER_RENAME (1ULL << 5) -// Set for ORDER BY -#define ALTER_ORDER (1ULL << 6) -// Set for table_options, like table comment -#define ALTER_OPTIONS (1ULL << 7) -// Set for ALTER [COLUMN] ... SET DEFAULT ... | DROP DEFAULT -#define ALTER_CHANGE_COLUMN_DEFAULT (1ULL << 8) -// Set for DISABLE KEYS | ENABLE KEYS -#define ALTER_KEYS_ONOFF (1ULL << 9) -// Set for FORCE, ENGINE(same engine), by mysql_recreate_table() -#define ALTER_RECREATE (1ULL << 10) -// Set for CONVERT TO -#define ALTER_CONVERT_TO (1ULL << 11) -// Set for DROP ... ADD some_index -#define ALTER_RENAME_INDEX (1ULL << 12) -// Set for ADD FOREIGN KEY -#define ALTER_ADD_FOREIGN_KEY (1ULL << 21) -// Set for DROP FOREIGN KEY -#define ALTER_DROP_FOREIGN_KEY (1ULL << 22) -#define ALTER_CHANGE_INDEX_COMMENT (1ULL << 23) -// Set for ADD [COLUMN] FIRST | AFTER -#define ALTER_COLUMN_ORDER (1ULL << 25) -#define ALTER_ADD_CHECK_CONSTRAINT (1ULL << 27) -#define ALTER_DROP_CHECK_CONSTRAINT (1ULL << 28) -#define ALTER_RENAME_COLUMN (1ULL << 29) -#define ALTER_COLUMN_UNVERSIONED (1ULL << 30) -#define ALTER_ADD_SYSTEM_VERSIONING (1ULL << 31) -#define ALTER_DROP_SYSTEM_VERSIONING (1ULL << 32) -#define ALTER_ADD_PERIOD (1ULL << 33) -#define ALTER_DROP_PERIOD (1ULL << 34) - -/* - Following defines are used by ALTER_INPLACE_TABLE - - They do describe in more detail the type operation(s) to be executed - by the storage engine. For example, which type of type of index to be - added/dropped. These are set by fill_alter_inplace_info(). -*/ - -#define ALTER_RECREATE_TABLE ALTER_RECREATE -#define ALTER_CHANGE_CREATE_OPTION ALTER_OPTIONS -#define ALTER_ADD_COLUMN (ALTER_ADD_VIRTUAL_COLUMN | \ - ALTER_ADD_STORED_BASE_COLUMN | \ - ALTER_ADD_STORED_GENERATED_COLUMN) -#define ALTER_DROP_COLUMN (ALTER_DROP_VIRTUAL_COLUMN | \ - ALTER_DROP_STORED_COLUMN) -#define ALTER_COLUMN_DEFAULT ALTER_CHANGE_COLUMN_DEFAULT - -// Add non-unique, non-primary index -#define ALTER_ADD_NON_UNIQUE_NON_PRIM_INDEX (1ULL << 35) - -// Drop non-unique, non-primary index -#define ALTER_DROP_NON_UNIQUE_NON_PRIM_INDEX (1ULL << 36) - -// Add unique, non-primary index -#define ALTER_ADD_UNIQUE_INDEX (1ULL << 37) - -// Drop unique, non-primary index -#define ALTER_DROP_UNIQUE_INDEX (1ULL << 38) - -// Add primary index -#define ALTER_ADD_PK_INDEX (1ULL << 39) - -// Drop primary index -#define ALTER_DROP_PK_INDEX (1ULL << 40) - -// Virtual generated column -#define ALTER_ADD_VIRTUAL_COLUMN (1ULL << 41) -// Stored base (non-generated) column -#define ALTER_ADD_STORED_BASE_COLUMN (1ULL << 42) -// Stored generated column -#define ALTER_ADD_STORED_GENERATED_COLUMN (1ULL << 43) - -// Drop column -#define ALTER_DROP_VIRTUAL_COLUMN (1ULL << 44) -#define ALTER_DROP_STORED_COLUMN (1ULL << 45) - -// Rename column (verified; ALTER_RENAME_COLUMN may use original name) -#define ALTER_COLUMN_NAME (1ULL << 46) - -// Change column datatype -#define ALTER_VIRTUAL_COLUMN_TYPE (1ULL << 47) -#define ALTER_STORED_COLUMN_TYPE (1ULL << 48) - - -// Engine can handle type change by itself in ALGORITHM=INPLACE -#define ALTER_COLUMN_TYPE_CHANGE_BY_ENGINE (1ULL << 49) - -// Reorder column -#define ALTER_STORED_COLUMN_ORDER (1ULL << 50) - -// Reorder column -#define ALTER_VIRTUAL_COLUMN_ORDER (1ULL << 51) - -// Change column from NOT NULL to NULL -#define ALTER_COLUMN_NULLABLE (1ULL << 52) - -// Change column from NULL to NOT NULL -#define ALTER_COLUMN_NOT_NULLABLE (1ULL << 53) - -// Change column generation expression -#define ALTER_VIRTUAL_GCOL_EXPR (1ULL << 54) -#define ALTER_STORED_GCOL_EXPR (1ULL << 55) - -// column's engine options changed, something in field->option_struct -#define ALTER_COLUMN_OPTION (1ULL << 56) - -// MySQL alias for the same thing: -#define ALTER_COLUMN_STORAGE_TYPE ALTER_COLUMN_OPTION - -// Change the column format of column -#define ALTER_COLUMN_COLUMN_FORMAT (1ULL << 57) - -/** - Changes in generated columns that affect storage, - for example, when a vcol type or expression changes - and this vcol is indexed or used in a partitioning expression -*/ -#define ALTER_COLUMN_VCOL (1ULL << 58) - -/** - ALTER TABLE for a partitioned table. The engine needs to commit - online alter of all partitions atomically (using group_commit_ctx) -*/ -#define ALTER_PARTITIONED (1ULL << 59) - -/** - Change in index length such that it doesn't require index rebuild. -*/ -#define ALTER_COLUMN_INDEX_LENGTH (1ULL << 60) - -/* - Flags set in partition_flags when altering partitions -*/ - -// Set for ADD PARTITION -#define ALTER_PARTITION_ADD (1ULL << 1) -// Set for DROP PARTITION -#define ALTER_PARTITION_DROP (1ULL << 2) -// Set for COALESCE PARTITION -#define ALTER_PARTITION_COALESCE (1ULL << 3) -// Set for REORGANIZE PARTITION ... INTO -#define ALTER_PARTITION_REORGANIZE (1ULL << 4) -// Set for partition_options -#define ALTER_PARTITION_INFO (1ULL << 5) -// Set for LOAD INDEX INTO CACHE ... PARTITION -// Set for CACHE INDEX ... PARTITION -#define ALTER_PARTITION_ADMIN (1ULL << 6) -// Set for REBUILD PARTITION -#define ALTER_PARTITION_REBUILD (1ULL << 7) -// Set for partitioning operations specifying ALL keyword -#define ALTER_PARTITION_ALL (1ULL << 8) -// Set for REMOVE PARTITIONING -#define ALTER_PARTITION_REMOVE (1ULL << 9) -// Set for EXCHANGE PARITION -#define ALTER_PARTITION_EXCHANGE (1ULL << 10) -// Set by Sql_cmd_alter_table_truncate_partition::execute() -#define ALTER_PARTITION_TRUNCATE (1ULL << 11) -// Set for REORGANIZE PARTITION -#define ALTER_PARTITION_TABLE_REORG (1ULL << 12) - -/* - This is master database for most of system tables. However there - can be other databases which can hold system tables. Respective - storage engines define their own system database names. -*/ -extern const char *mysqld_system_database; - -/* - Structure to hold list of system_database.system_table. - This is used at both mysqld and storage engine layer. -*/ -struct st_system_tablename -{ - const char *db; - const char *tablename; -}; - - -typedef ulonglong my_xid; // this line is the same as in log_event.h -#define MYSQL_XID_PREFIX "MySQLXid" -#define MYSQL_XID_PREFIX_LEN 8 // must be a multiple of 8 -#define MYSQL_XID_OFFSET (MYSQL_XID_PREFIX_LEN+sizeof(server_id)) -#define MYSQL_XID_GTRID_LEN (MYSQL_XID_OFFSET+sizeof(my_xid)) - -#define XIDDATASIZE MYSQL_XIDDATASIZE -#define MAXGTRIDSIZE 64 -#define MAXBQUALSIZE 64 - -#define COMPATIBLE_DATA_YES 0 -#define COMPATIBLE_DATA_NO 1 - -/** - struct xid_t is binary compatible with the XID structure as - in the X/Open CAE Specification, Distributed Transaction Processing: - The XA Specification, X/Open Company Ltd., 1991. - http://www.opengroup.org/bookstore/catalog/c193.htm - - @see MYSQL_XID in mysql/plugin.h -*/ -struct xid_t { - long formatID; - long gtrid_length; - long bqual_length; - char data[XIDDATASIZE]; // not \0-terminated ! - - xid_t() {} /* Remove gcc warning */ - bool eq(struct xid_t *xid) const - { return !xid->is_null() && eq(xid->gtrid_length, xid->bqual_length, xid->data); } - bool eq(long g, long b, const char *d) const - { return !is_null() && g == gtrid_length && b == bqual_length && !memcmp(d, data, g+b); } - void set(struct xid_t *xid) - { memcpy(this, xid, xid->length()); } - void set(long f, const char *g, long gl, const char *b, long bl) - { - formatID= f; - memcpy(data, g, gtrid_length= gl); - memcpy(data+gl, b, bqual_length= bl); - } - void set(ulonglong xid) - { - my_xid tmp; - formatID= 1; - set(MYSQL_XID_PREFIX_LEN, 0, MYSQL_XID_PREFIX); - memcpy(data+MYSQL_XID_PREFIX_LEN, &server_id, sizeof(server_id)); - tmp= xid; - memcpy(data+MYSQL_XID_OFFSET, &tmp, sizeof(tmp)); - gtrid_length=MYSQL_XID_GTRID_LEN; - } - void set(long g, long b, const char *d) - { - formatID= 1; - gtrid_length= g; - bqual_length= b; - memcpy(data, d, g+b); - } - bool is_null() const { return formatID == -1; } - void null() { formatID= -1; } - my_xid quick_get_my_xid() - { - my_xid tmp; - memcpy(&tmp, data+MYSQL_XID_OFFSET, sizeof(tmp)); - return tmp; - } - my_xid get_my_xid() - { - return gtrid_length == MYSQL_XID_GTRID_LEN && bqual_length == 0 && - !memcmp(data, MYSQL_XID_PREFIX, MYSQL_XID_PREFIX_LEN) ? - quick_get_my_xid() : 0; - } - uint length() - { - return static_cast(sizeof(formatID)) + key_length(); - } - uchar *key() const - { - return (uchar *)>rid_length; - } - uint key_length() const - { - return static_cast(sizeof(gtrid_length)+sizeof(bqual_length)+ - gtrid_length+bqual_length); - } -}; -typedef struct xid_t XID; - -/* for recover() handlerton call */ -#define MIN_XID_LIST_SIZE 128 -#define MAX_XID_LIST_SIZE (1024*128) - -/* - These structures are used to pass information from a set of SQL commands - on add/drop/change tablespace definitions to the proper hton. -*/ -#define UNDEF_NODEGROUP 65535 -enum ts_command_type -{ - TS_CMD_NOT_DEFINED = -1, - CREATE_TABLESPACE = 0, - ALTER_TABLESPACE = 1, - CREATE_LOGFILE_GROUP = 2, - ALTER_LOGFILE_GROUP = 3, - DROP_TABLESPACE = 4, - DROP_LOGFILE_GROUP = 5, - CHANGE_FILE_TABLESPACE = 6, - ALTER_ACCESS_MODE_TABLESPACE = 7 -}; - -enum ts_alter_tablespace_type -{ - TS_ALTER_TABLESPACE_TYPE_NOT_DEFINED = -1, - ALTER_TABLESPACE_ADD_FILE = 1, - ALTER_TABLESPACE_DROP_FILE = 2 -}; - -enum tablespace_access_mode -{ - TS_NOT_DEFINED= -1, - TS_READ_ONLY = 0, - TS_READ_WRITE = 1, - TS_NOT_ACCESSIBLE = 2 -}; - -/* Statistics about batch operations like bulk_insert */ -struct ha_copy_info -{ - ha_rows records; /* Used to check if rest of variables can be used */ - ha_rows touched; - ha_rows copied; - ha_rows deleted; - ha_rows updated; -}; - -struct handlerton; -class st_alter_tablespace : public Sql_alloc -{ - public: - const char *tablespace_name; - const char *logfile_group_name; - enum ts_command_type ts_cmd_type; - enum ts_alter_tablespace_type ts_alter_tablespace_type; - const char *data_file_name; - const char *undo_file_name; - const char *redo_file_name; - ulonglong extent_size; - ulonglong undo_buffer_size; - ulonglong redo_buffer_size; - ulonglong initial_size; - ulonglong autoextend_size; - ulonglong max_size; - uint nodegroup_id; - handlerton *storage_engine; - bool wait_until_completed; - const char *ts_comment; - enum tablespace_access_mode ts_access_mode; - st_alter_tablespace() - { - tablespace_name= NULL; - logfile_group_name= "DEFAULT_LG"; //Default log file group - ts_cmd_type= TS_CMD_NOT_DEFINED; - data_file_name= NULL; - undo_file_name= NULL; - redo_file_name= NULL; - extent_size= 1024*1024; //Default 1 MByte - undo_buffer_size= 8*1024*1024; //Default 8 MByte - redo_buffer_size= 8*1024*1024; //Default 8 MByte - initial_size= 128*1024*1024; //Default 128 MByte - autoextend_size= 0; //No autoextension as default - max_size= 0; //Max size == initial size => no extension - storage_engine= NULL; - nodegroup_id= UNDEF_NODEGROUP; - wait_until_completed= TRUE; - ts_comment= NULL; - ts_access_mode= TS_NOT_DEFINED; - } -}; - -/* The handler for a table type. Will be included in the TABLE structure */ - -struct TABLE; - -/* - Make sure that the order of schema_tables and enum_schema_tables are the same. -*/ -enum enum_schema_tables -{ - SCH_ALL_PLUGINS, - SCH_APPLICABLE_ROLES, - SCH_CHARSETS, - SCH_CHECK_CONSTRAINTS, - SCH_COLLATIONS, - SCH_COLLATION_CHARACTER_SET_APPLICABILITY, - SCH_COLUMNS, - SCH_COLUMN_PRIVILEGES, - SCH_ENABLED_ROLES, - SCH_ENGINES, - SCH_EVENTS, - SCH_EXPLAIN, - SCH_FILES, - SCH_GLOBAL_STATUS, - SCH_GLOBAL_VARIABLES, - SCH_KEY_CACHES, - SCH_KEY_COLUMN_USAGE, - SCH_OPEN_TABLES, - SCH_OPT_TRACE, - SCH_PARAMETERS, - SCH_PARTITIONS, - SCH_PLUGINS, - SCH_PROCESSLIST, - SCH_PROFILES, - SCH_REFERENTIAL_CONSTRAINTS, - SCH_PROCEDURES, - SCH_SCHEMATA, - SCH_SCHEMA_PRIVILEGES, - SCH_SESSION_STATUS, - SCH_SESSION_VARIABLES, - SCH_STATISTICS, - SCH_SYSTEM_VARIABLES, - SCH_TABLES, - SCH_TABLESPACES, - SCH_TABLE_CONSTRAINTS, - SCH_TABLE_NAMES, - SCH_TABLE_PRIVILEGES, - SCH_TRIGGERS, - SCH_USER_PRIVILEGES, - SCH_VIEWS -}; - -struct TABLE_SHARE; -struct HA_CREATE_INFO; -struct st_foreign_key_info; -typedef struct st_foreign_key_info FOREIGN_KEY_INFO; -typedef bool (stat_print_fn)(THD *thd, const char *type, size_t type_len, - const char *file, size_t file_len, - const char *status, size_t status_len); -enum ha_stat_type { HA_ENGINE_STATUS, HA_ENGINE_LOGS, HA_ENGINE_MUTEX }; -extern MYSQL_PLUGIN_IMPORT st_plugin_int *hton2plugin[MAX_HA]; - -/* Transaction log maintains type definitions */ -enum log_status -{ - HA_LOG_STATUS_FREE= 0, /* log is free and can be deleted */ - HA_LOG_STATUS_INUSE= 1, /* log can't be deleted because it is in use */ - HA_LOG_STATUS_NOSUCHLOG= 2 /* no such log (can't be returned by - the log iterator status) */ -}; -/* - Function for signaling that the log file changed its state from - LOG_STATUS_INUSE to LOG_STATUS_FREE - - Now it do nothing, will be implemented as part of new transaction - log management for engines. - TODO: implement the function. -*/ -void signal_log_not_needed(struct handlerton, char *log_file); -/* - Data of transaction log iterator. -*/ -struct handler_log_file_data { - LEX_STRING filename; - enum log_status status; -}; - -/* - Definitions for engine-specific table/field/index options in the CREATE TABLE. - - Options are declared with HA_*OPTION_* macros (HA_TOPTION_NUMBER, - HA_FOPTION_ENUM, HA_IOPTION_STRING, etc). - - Every macros takes the option name, and the name of the underlying field of - the appropriate C structure. The "appropriate C structure" is - ha_table_option_struct for table level options, - ha_field_option_struct for field level options, - ha_index_option_struct for key level options. The engine either - defines a structure of this name, or uses #define's to map - these "appropriate" names to the actual structure type name. - - ULL options use a ulonglong as the backing store. - HA_*OPTION_NUMBER() takes the option name, the structure field name, - the default value for the option, min, max, and blk_siz values. - - STRING options use a char* as a backing store. - HA_*OPTION_STRING takes the option name and the structure field name. - The default value will be 0. - - ENUM options use a uint as a backing store (not enum!!!). - HA_*OPTION_ENUM takes the option name, the structure field name, - the default value for the option as a number, and a string with the - permitted values for this enum - one string with comma separated values, - for example: "gzip,bzip2,lzma" - - BOOL options use a bool as a backing store. - HA_*OPTION_BOOL takes the option name, the structure field name, - and the default value for the option. - From the SQL, BOOL options accept YES/NO, ON/OFF, and 1/0. - - The name of the option is limited to 255 bytes, - the value (for string options) - to the 32767 bytes. - - See ha_example.cc for an example. -*/ - -struct ha_table_option_struct; -struct ha_field_option_struct; -struct ha_index_option_struct; - -enum ha_option_type { HA_OPTION_TYPE_ULL, /* unsigned long long */ - HA_OPTION_TYPE_STRING, /* char * */ - HA_OPTION_TYPE_ENUM, /* uint */ - HA_OPTION_TYPE_BOOL, /* bool */ - HA_OPTION_TYPE_SYSVAR};/* type of the sysval */ - -#define HA_xOPTION_NUMBER(name, struc, field, def, min, max, blk_siz) \ - { HA_OPTION_TYPE_ULL, name, sizeof(name)-1, \ - offsetof(struc, field), def, min, max, blk_siz, 0, 0 } -#define HA_xOPTION_STRING(name, struc, field) \ - { HA_OPTION_TYPE_STRING, name, sizeof(name)-1, \ - offsetof(struc, field), 0, 0, 0, 0, 0, 0} -#define HA_xOPTION_ENUM(name, struc, field, values, def) \ - { HA_OPTION_TYPE_ENUM, name, sizeof(name)-1, \ - offsetof(struc, field), def, 0, \ - sizeof(values)-1, 0, values, 0 } -#define HA_xOPTION_BOOL(name, struc, field, def) \ - { HA_OPTION_TYPE_BOOL, name, sizeof(name)-1, \ - offsetof(struc, field), def, 0, 1, 0, 0, 0 } -#define HA_xOPTION_SYSVAR(name, struc, field, sysvar) \ - { HA_OPTION_TYPE_SYSVAR, name, sizeof(name)-1, \ - offsetof(struc, field), 0, 0, 0, 0, 0, MYSQL_SYSVAR(sysvar) } -#define HA_xOPTION_END { HA_OPTION_TYPE_ULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 } - -#define HA_TOPTION_NUMBER(name, field, def, min, max, blk_siz) \ - HA_xOPTION_NUMBER(name, ha_table_option_struct, field, def, min, max, blk_siz) -#define HA_TOPTION_STRING(name, field) \ - HA_xOPTION_STRING(name, ha_table_option_struct, field) -#define HA_TOPTION_ENUM(name, field, values, def) \ - HA_xOPTION_ENUM(name, ha_table_option_struct, field, values, def) -#define HA_TOPTION_BOOL(name, field, def) \ - HA_xOPTION_BOOL(name, ha_table_option_struct, field, def) -#define HA_TOPTION_SYSVAR(name, field, sysvar) \ - HA_xOPTION_SYSVAR(name, ha_table_option_struct, field, sysvar) -#define HA_TOPTION_END HA_xOPTION_END - -#define HA_FOPTION_NUMBER(name, field, def, min, max, blk_siz) \ - HA_xOPTION_NUMBER(name, ha_field_option_struct, field, def, min, max, blk_siz) -#define HA_FOPTION_STRING(name, field) \ - HA_xOPTION_STRING(name, ha_field_option_struct, field) -#define HA_FOPTION_ENUM(name, field, values, def) \ - HA_xOPTION_ENUM(name, ha_field_option_struct, field, values, def) -#define HA_FOPTION_BOOL(name, field, def) \ - HA_xOPTION_BOOL(name, ha_field_option_struct, field, def) -#define HA_FOPTION_SYSVAR(name, field, sysvar) \ - HA_xOPTION_SYSVAR(name, ha_field_option_struct, field, sysvar) -#define HA_FOPTION_END HA_xOPTION_END - -#define HA_IOPTION_NUMBER(name, field, def, min, max, blk_siz) \ - HA_xOPTION_NUMBER(name, ha_index_option_struct, field, def, min, max, blk_siz) -#define HA_IOPTION_STRING(name, field) \ - HA_xOPTION_STRING(name, ha_index_option_struct, field) -#define HA_IOPTION_ENUM(name, field, values, def) \ - HA_xOPTION_ENUM(name, ha_index_option_struct, field, values, def) -#define HA_IOPTION_BOOL(name, field, def) \ - HA_xOPTION_BOOL(name, ha_index_option_struct, field, def) -#define HA_IOPTION_SYSVAR(name, field, sysvar) \ - HA_xOPTION_SYSVAR(name, ha_index_option_struct, field, sysvar) -#define HA_IOPTION_END HA_xOPTION_END - -typedef struct st_ha_create_table_option { - enum ha_option_type type; - const char *name; - size_t name_length; - ptrdiff_t offset; - ulonglong def_value; - ulonglong min_value, max_value, block_size; - const char *values; - struct st_mysql_sys_var *var; -} ha_create_table_option; - -enum handler_iterator_type -{ - /* request of transaction log iterator */ - HA_TRANSACTLOG_ITERATOR= 1 -}; -enum handler_create_iterator_result -{ - HA_ITERATOR_OK, /* iterator created */ - HA_ITERATOR_UNSUPPORTED, /* such type of iterator is not supported */ - HA_ITERATOR_ERROR /* error during iterator creation */ -}; - -/* - Iterator structure. Can be used by handler/handlerton for different purposes. - - Iterator should be created in the way to point "before" the first object - it iterate, so next() call move it to the first object or return !=0 if - there is nothing to iterate through. -*/ -struct handler_iterator { - /* - Moves iterator to next record and return 0 or return !=0 - if there is no records. - iterator_object will be filled by this function if next() returns 0. - Content of the iterator_object depend on iterator type. - */ - int (*next)(struct handler_iterator *, void *iterator_object); - /* - Free resources allocated by iterator, after this call iterator - is not usable. - */ - void (*destroy)(struct handler_iterator *); - /* - Pointer to buffer for the iterator to use. - Should be allocated by function which created the iterator and - destroyed by freed by above "destroy" call - */ - void *buffer; -}; - -class handler; -class group_by_handler; -class derived_handler; -class select_handler; -struct Query; -typedef class st_select_lex SELECT_LEX; -typedef struct st_order ORDER; - -/* - handlerton is a singleton structure - one instance per storage engine - - to provide access to storage engine functionality that works on the - "global" level (unlike handler class that works on a per-table basis) - - usually handlerton instance is defined statically in ha_xxx.cc as - - static handlerton { ... } xxx_hton; - - savepoint_*, prepare, recover, and *_by_xid pointers can be 0. -*/ -struct handlerton -{ - /* - Historical number used for frm file to determine the correct - storage engine. This is going away and new engines will just use - "name" for this. - */ - enum legacy_db_type db_type; - /* - each storage engine has it's own memory area (actually a pointer) - in the thd, for storing per-connection information. - It is accessed as - - thd->ha_data[xxx_hton.slot] - - slot number is initialized by MySQL after xxx_init() is called. - */ - uint slot; - /* - to store per-savepoint data storage engine is provided with an area - of a requested size (0 is ok here). - savepoint_offset must be initialized statically to the size of - the needed memory to store per-savepoint information. - After xxx_init it is changed to be an offset to savepoint storage - area and need not be used by storage engine. - see binlog_hton and binlog_savepoint_set/rollback for an example. - */ - uint savepoint_offset; - /* - handlerton methods: - - close_connection is only called if - thd->ha_data[xxx_hton.slot] is non-zero, so even if you don't need - this storage area - set it to something, so that MySQL would know - this storage engine was accessed in this connection - */ - int (*close_connection)(handlerton *hton, THD *thd); - /* - Tell handler that query has been killed. - */ - void (*kill_query)(handlerton *hton, THD *thd, enum thd_kill_levels level); - /* - sv points to an uninitialized storage area of requested size - (see savepoint_offset description) - */ - int (*savepoint_set)(handlerton *hton, THD *thd, void *sv); - /* - sv points to a storage area, that was earlier passed - to the savepoint_set call - */ - int (*savepoint_rollback)(handlerton *hton, THD *thd, void *sv); - /** - Check if storage engine allows to release metadata locks which were - acquired after the savepoint if rollback to savepoint is done. - @return true - If it is safe to release MDL locks. - false - If it is not. - */ - bool (*savepoint_rollback_can_release_mdl)(handlerton *hton, THD *thd); - int (*savepoint_release)(handlerton *hton, THD *thd, void *sv); - /* - 'all' is true if it's a real commit, that makes persistent changes - 'all' is false if it's not in fact a commit but an end of the - statement that is part of the transaction. - NOTE 'all' is also false in auto-commit mode where 'end of statement' - and 'real commit' mean the same event. - */ - int (*commit)(handlerton *hton, THD *thd, bool all); - /* - The commit_ordered() method is called prior to the commit() method, after - the transaction manager has decided to commit (not rollback) the - transaction. Unlike commit(), commit_ordered() is called only when the - full transaction is committed, not for each commit of statement - transaction in a multi-statement transaction. - - Not that like prepare(), commit_ordered() is only called when 2-phase - commit takes place. Ie. when no binary log and only a single engine - participates in a transaction, one commit() is called, no - commit_ordered(). So engines must be prepared for this. - - The calls to commit_ordered() in multiple parallel transactions is - guaranteed to happen in the same order in every participating - handler. This can be used to ensure the same commit order among multiple - handlers (eg. in table handler and binlog). So if transaction T1 calls - into commit_ordered() of handler A before T2, then T1 will also call - commit_ordered() of handler B before T2. - - Engines that implement this method should during this call make the - transaction visible to other transactions, thereby making the order of - transaction commits be defined by the order of commit_ordered() calls. - - The intention is that commit_ordered() should do the minimal amount of - work that needs to happen in consistent commit order among handlers. To - preserve ordering, calls need to be serialised on a global mutex, so - doing any time-consuming or blocking operations in commit_ordered() will - limit scalability. - - Handlers can rely on commit_ordered() calls to be serialised (no two - calls can run in parallel, so no extra locking on the handler part is - required to ensure this). - - Note that commit_ordered() can be called from a different thread than the - one handling the transaction! So it can not do anything that depends on - thread local storage, in particular it can not call my_error() and - friends (instead it can store the error code and delay the call of - my_error() to the commit() method). - - Similarly, since commit_ordered() returns void, any return error code - must be saved and returned from the commit() method instead. - - The commit_ordered method is optional, and can be left unset if not - needed in a particular handler (then there will be no ordering guarantees - wrt. other engines and binary log). - */ - void (*commit_ordered)(handlerton *hton, THD *thd, bool all); - int (*rollback)(handlerton *hton, THD *thd, bool all); - int (*prepare)(handlerton *hton, THD *thd, bool all); - /* - The prepare_ordered method is optional. If set, it will be called after - successful prepare() in all handlers participating in 2-phase - commit. Like commit_ordered(), it is called only when the full - transaction is committed, not for each commit of statement transaction. - - The calls to prepare_ordered() among multiple parallel transactions are - ordered consistently with calls to commit_ordered(). This means that - calls to prepare_ordered() effectively define the commit order, and that - each handler will see the same sequence of transactions calling into - prepare_ordered() and commit_ordered(). - - Thus, prepare_ordered() can be used to define commit order for handlers - that need to do this in the prepare step (like binlog). It can also be - used to release transaction's locks early in an order consistent with the - order transactions will be eventually committed. - - Like commit_ordered(), prepare_ordered() calls are serialised to maintain - ordering, so the intention is that they should execute fast, with only - the minimal amount of work needed to define commit order. Handlers can - rely on this serialisation, and do not need to do any extra locking to - avoid two prepare_ordered() calls running in parallel. - - Like commit_ordered(), prepare_ordered() is not guaranteed to be called - in the context of the thread handling the rest of the transaction. So it - cannot invoke code that relies on thread local storage, in particular it - cannot call my_error(). - - prepare_ordered() cannot cause a rollback by returning an error, all - possible errors must be handled in prepare() (the prepare_ordered() - method returns void). In case of some fatal error, a record of the error - must be made internally by the engine and returned from commit() later. - - Note that for user-level XA SQL commands, no consistent ordering among - prepare_ordered() and commit_ordered() is guaranteed (as that would - require blocking all other commits for an indefinite time). - - When 2-phase commit is not used (eg. only one engine (and no binlog) in - transaction), neither prepare() nor prepare_ordered() is called. - */ - void (*prepare_ordered)(handlerton *hton, THD *thd, bool all); - int (*recover)(handlerton *hton, XID *xid_list, uint len); - int (*commit_by_xid)(handlerton *hton, XID *xid); - int (*rollback_by_xid)(handlerton *hton, XID *xid); - /* - The commit_checkpoint_request() handlerton method is used to checkpoint - the XA recovery process for storage engines that support two-phase - commit. - - The method is optional - an engine that does not implemented is expected - to work the traditional way, where every commit() durably flushes the - transaction to disk in the engine before completion, so XA recovery will - no longer be needed for that transaction. - - An engine that does implement commit_checkpoint_request() is also - expected to implement commit_ordered(), so that ordering of commits is - consistent between 2pc participants. Such engine is no longer required to - durably flush to disk transactions in commit(), provided that the - transaction has been successfully prepare()d and commit_ordered(); thus - potentionally saving one fsync() call. (Engine must still durably flush - to disk in commit() when no prepare()/commit_ordered() steps took place, - at least if durable commits are wanted; this happens eg. if binlog is - disabled). - - The TC will periodically (eg. once per binlog rotation) call - commit_checkpoint_request(). When this happens, the engine must arrange - for all transaction that have completed commit_ordered() to be durably - flushed to disk (this does not include transactions that might be in the - middle of executing commit_ordered()). When such flush has completed, the - engine must call commit_checkpoint_notify_ha(), passing back the opaque - "cookie". - - The flush and call of commit_checkpoint_notify_ha() need not happen - immediately - it can be scheduled and performed asynchronously (ie. as - part of next prepare(), or sync every second, or whatever), but should - not be postponed indefinitely. It is however also permissible to do it - immediately, before returning from commit_checkpoint_request(). - - When commit_checkpoint_notify_ha() is called, the TC will know that the - transactions are durably committed, and thus no longer require XA - recovery. It uses that to reduce the work needed for any subsequent XA - recovery process. - */ - void (*commit_checkpoint_request)(handlerton *hton, void *cookie); - /* - "Disable or enable checkpointing internal to the storage engine. This is - used for FLUSH TABLES WITH READ LOCK AND DISABLE CHECKPOINT to ensure that - the engine will never start any recovery from a time between - FLUSH TABLES ... ; UNLOCK TABLES. - - While checkpointing is disabled, the engine should pause any background - write activity (such as tablespace checkpointing) that require consistency - between different files (such as transaction log and tablespace files) for - crash recovery to succeed. The idea is to use this to make safe - multi-volume LVM snapshot backups. - */ - int (*checkpoint_state)(handlerton *hton, bool disabled); - void *(*create_cursor_read_view)(handlerton *hton, THD *thd); - void (*set_cursor_read_view)(handlerton *hton, THD *thd, void *read_view); - void (*close_cursor_read_view)(handlerton *hton, THD *thd, void *read_view); - handler *(*create)(handlerton *hton, TABLE_SHARE *table, MEM_ROOT *mem_root); - void (*drop_database)(handlerton *hton, char* path); - /* - return 0 if dropped successfully, - -1 if nothing was done by design (as in e.g. blackhole) - an error code (e.g. HA_ERR_NO_SUCH_TABLE) otherwise - */ - int (*drop_table)(handlerton *hton, const char* path); - int (*panic)(handlerton *hton, enum ha_panic_function flag); - int (*start_consistent_snapshot)(handlerton *hton, THD *thd); - bool (*flush_logs)(handlerton *hton); - bool (*show_status)(handlerton *hton, THD *thd, stat_print_fn *print, enum ha_stat_type stat); - uint (*partition_flags)(); - alter_table_operations (*alter_table_flags)(alter_table_operations flags); - int (*alter_tablespace)(handlerton *hton, THD *thd, st_alter_tablespace *ts_info); - int (*fill_is_table)(handlerton *hton, THD *thd, TABLE_LIST *tables, - class Item *cond, - enum enum_schema_tables); - uint32 flags; /* global handler flags */ - /* - Those handlerton functions below are properly initialized at handler - init. - */ - int (*binlog_func)(handlerton *hton, THD *thd, enum_binlog_func fn, void *arg); - void (*binlog_log_query)(handlerton *hton, THD *thd, - enum_binlog_command binlog_command, - const char *query, uint query_length, - const char *db, const char *table_name); - - /* - Get log status. - If log_status is null then the handler do not support transaction - log information (i.e. log iterator can't be created). - (see example of implementation in handler.cc, TRANS_LOG_MGM_EXAMPLE_CODE) - - */ - enum log_status (*get_log_status)(handlerton *hton, char *log); - - /* - Iterators creator. - Presence of the pointer should be checked before using - */ - enum handler_create_iterator_result - (*create_iterator)(handlerton *hton, enum handler_iterator_type type, - struct handler_iterator *fill_this_in); - int (*abort_transaction)(handlerton *hton, THD *bf_thd, - THD *victim_thd, my_bool signal); - int (*set_checkpoint)(handlerton *hton, const XID* xid); - int (*get_checkpoint)(handlerton *hton, XID* xid); - /* - Optional clauses in the CREATE/ALTER TABLE - */ - ha_create_table_option *table_options; // table level options - ha_create_table_option *field_options; // these are specified per field - ha_create_table_option *index_options; // these are specified per index - - /** - The list of extensions of files created for a single table in the - database directory (datadir/db_name/). - - Used by open_table_error(), by the default rename_table and delete_table - handler methods, and by the default discovery implementation. - - For engines that have more than one file name extensions (separate - metadata, index, and/or data files), the order of elements is relevant. - First element of engine file name extensions array should be metadata - file extention. This is implied by the open_table_error() - and the default discovery implementation. - - Second element - data file extension. This is implied - assumed by REPAIR TABLE ... USE_FRM implementation. - */ - const char **tablefile_extensions; // by default - empty list - - /********************************************************************** - Functions to intercept queries - **********************************************************************/ - - /* - Create and return a group_by_handler, if the storage engine can execute - the summary / group by query. - If the storage engine can't do that, return NULL. - - The server guaranteeds that all tables in the list belong to this - storage engine. - */ - group_by_handler *(*create_group_by)(THD *thd, Query *query); - - /* - Create and return a derived_handler if the storage engine can execute - the derived table 'derived', otherwise return NULL. - In a general case 'derived' may contain tables not from the engine. - If the engine cannot handle or does not want to handle such pushed derived - the function create_group_by has to return NULL. - */ - derived_handler *(*create_derived)(THD *thd, TABLE_LIST *derived); - - /* - Create and return a select_handler if the storage engine can execute - the select statement 'select, otherwise return NULL - */ - select_handler *(*create_select) (THD *thd, SELECT_LEX *select); - - /********************************************************************* - Table discovery API. - It allows the server to "discover" tables that exist in the storage - engine, without user issuing an explicit CREATE TABLE statement. - **********************************************************************/ - - /* - This method is required for any engine that supports automatic table - discovery, there is no default implementation. - - Given a TABLE_SHARE discover_table() fills it in with a correct table - structure using one of the TABLE_SHARE::init_from_* methods. - - Returns HA_ERR_NO_SUCH_TABLE if the table did not exist in the engine, - zero if the table was discovered successfully, or any other - HA_ERR_* error code as appropriate if the table existed, but the - discovery failed. - */ - int (*discover_table)(handlerton *hton, THD* thd, TABLE_SHARE *share); - - /* - The discover_table_names method tells the server - about all tables in the specified database that the engine - knows about. Tables (or file names of tables) are added to - the provided discovered_list collector object using - add_table() or add_file() methods. - */ - class discovered_list - { - public: - virtual bool add_table(const char *tname, size_t tlen) = 0; - virtual bool add_file(const char *fname) = 0; - protected: virtual ~discovered_list() {} - }; - - /* - By default (if not implemented by the engine, but the discover_table() is - implemented) it will perform a file-based discovery: - - - if tablefile_extensions[0] is not null, this will discovers all tables - with the tablefile_extensions[0] extension. - - Returns 0 on success and 1 on error. - */ - int (*discover_table_names)(handlerton *hton, LEX_CSTRING *db, MY_DIR *dir, - discovered_list *result); - - /* - This is a method that allows to server to check if a table exists without - an overhead of the complete discovery. - - By default (if not implemented by the engine, but the discovery_table() is - implemented) it will try to perform a file-based discovery: - - - if tablefile_extensions[0] is not null this will look for a file name - with the tablefile_extensions[0] extension. - - - if tablefile_extensions[0] is null, this will resort to discover_table(). - - Note that resorting to discover_table() is slow and the engine - should probably implement its own discover_table_existence() method, - if its tablefile_extensions[0] is null. - - Returns 1 if the table exists and 0 if it does not. - */ - int (*discover_table_existence)(handlerton *hton, const char *db, - const char *table_name); - - /* - This is the assisted table discovery method. Unlike the fully - automatic discovery as above, here a user is expected to issue an - explicit CREATE TABLE with the appropriate table attributes to - "assist" the discovery of a table. But this "discovering" CREATE TABLE - statement will not specify the table structure - the engine discovers - it using this method. For example, FederatedX uses it in - - CREATE TABLE t1 ENGINE=FEDERATED CONNECTION="mysql://foo/bar/t1"; - - Given a TABLE_SHARE discover_table_structure() fills it in with a correct - table structure using one of the TABLE_SHARE::init_from_* methods. - - Assisted discovery works independently from the automatic discover. - An engine is allowed to support only assisted discovery and not - support automatic one. Or vice versa. - */ - int (*discover_table_structure)(handlerton *hton, THD* thd, - TABLE_SHARE *share, HA_CREATE_INFO *info); - - /* - Notify the storage engine that the definition of the table (and the .frm - file) has changed. Returns 0 if ok. - */ - int (*notify_tabledef_changed)(handlerton *hton, LEX_CSTRING *db, - LEX_CSTRING *table_name, LEX_CUSTRING *frm, - LEX_CUSTRING *org_tabledef_version); - - /* - System Versioning - */ - /** Determine if system-versioned data was modified by the transaction. - @param[in,out] thd current session - @param[out] trx_id transaction start ID - @return transaction commit ID - @retval 0 if no system-versioned data was affected by the transaction */ - ulonglong (*prepare_commit_versioned)(THD *thd, ulonglong *trx_id); - - /* backup */ - void (*prepare_for_backup)(void); - void (*end_backup)(void); - - /* Server shutdown early notification.*/ - void (*pre_shutdown)(void); - - /* - Inform handler that partitioning engine has changed the .frm and the .par - files - */ - int (*create_partitioning_metadata)(const char *path, - const char *old_path, - chf_create_flags action_flag); -}; - - -static inline LEX_CSTRING *hton_name(const handlerton *hton) -{ - return &(hton2plugin[hton->slot]->name); -} - -static inline handlerton *plugin_hton(plugin_ref plugin) -{ - return plugin_data(plugin, handlerton *); -} - -static inline sys_var *find_hton_sysvar(handlerton *hton, st_mysql_sys_var *var) -{ - return find_plugin_sysvar(hton2plugin[hton->slot], var); -} - -handlerton *ha_default_handlerton(THD *thd); -handlerton *ha_default_tmp_handlerton(THD *thd); - -/* Possible flags of a handlerton (there can be 32 of them) */ -#define HTON_NO_FLAGS 0 -#define HTON_CLOSE_CURSORS_AT_COMMIT (1 << 0) -#define HTON_ALTER_NOT_SUPPORTED (1 << 1) //Engine does not support alter -#define HTON_CAN_RECREATE (1 << 2) //Delete all is used for truncate -#define HTON_HIDDEN (1 << 3) //Engine does not appear in lists -#define HTON_NOT_USER_SELECTABLE (1 << 5) -#define HTON_TEMPORARY_NOT_SUPPORTED (1 << 6) //Having temporary tables not supported -#define HTON_SUPPORT_LOG_TABLES (1 << 7) //Engine supports log tables -#define HTON_NO_PARTITION (1 << 8) //Not partition of these tables - -/* - This flag should be set when deciding that the engine does not allow - row based binary logging (RBL) optimizations. - - Currently, setting this flag, means that table's read/write_set will - be left untouched when logging changes to tables in this engine. In - practice this means that the server will not mess around with - table->write_set and/or table->read_set when using RBL and deciding - whether to log full or minimal rows. - - It's valuable for instance for virtual tables, eg: Performance - Schema which have no meaning for replication. -*/ -#define HTON_NO_BINLOG_ROW_OPT (1 << 9) -#define HTON_SUPPORTS_EXTENDED_KEYS (1 <<10) //supports extended keys -#define HTON_NATIVE_SYS_VERSIONING (1 << 11) //Engine supports System Versioning - -// MySQL compatibility. Unused. -#define HTON_SUPPORTS_FOREIGN_KEYS (1 << 0) //Foreign key constraint supported. - -#define HTON_CAN_MERGE (1 <<11) //Merge type table -// Engine needs to access the main connect string in partitions -#define HTON_CAN_READ_CONNECT_STRING_IN_PARTITION (1 <<12) - -/* can be replicated by wsrep replication provider plugin */ -#define HTON_WSREP_REPLICATION (1 << 13) - -/* - Set this on the *slave* that's connected to a shared with a master storage. - The slave will ignore any CREATE TABLE, DROP or updates for this engine. -*/ -#define HTON_IGNORE_UPDATES (1 << 14) - -/* - Set this on the *master* that's connected to a shared with a slave storage. - The table may not exists on the slave. The effects of having this flag are: - - ALTER TABLE that changes engine from this table to another engine will - be replicated as CREATE + INSERT - - CREATE ... LIKE shared_table will be replicated as a full CREATE TABLE - - ALTER TABLE for this engine will have "IF EXISTS" added. - - RENAME TABLE for this engine will have "IF EXISTS" added. - - DROP TABLE for this engine will have "IF EXISTS" added. -*/ -#define HTON_TABLE_MAY_NOT_EXIST_ON_SLAVE (1 << 15) - -/* - True if handler cannot rollback transactions. If not true, the transaction - will be put in the transactional binlog cache. - For some engines, like Aria, the rollback can happen in case of crash, but - not trough a handler rollback call. -*/ -#define HTON_NO_ROLLBACK (1 << 16) - -/* - This storage engine can support both transactional and non transactional - tables -*/ -#define HTON_TRANSACTIONAL_AND_NON_TRANSACTIONAL (1 << 17) - -class Ha_trx_info; - -struct THD_TRANS -{ - /* true is not all entries in the ht[] support 2pc */ - bool no_2pc; - /* storage engines that registered in this transaction */ - Ha_trx_info *ha_list; - /* - The purpose of this flag is to keep track of non-transactional - tables that were modified in scope of: - - transaction, when the variable is a member of - THD::transaction.all - - top-level statement or sub-statement, when the variable is a - member of THD::transaction.stmt - This member has the following life cycle: - * stmt.modified_non_trans_table is used to keep track of - modified non-transactional tables of top-level statements. At - the end of the previous statement and at the beginning of the session, - it is reset to FALSE. If such functions - as mysql_insert, mysql_update, mysql_delete etc modify a - non-transactional table, they set this flag to TRUE. At the - end of the statement, the value of stmt.modified_non_trans_table - is merged with all.modified_non_trans_table and gets reset. - * all.modified_non_trans_table is reset at the end of transaction - - * Since we do not have a dedicated context for execution of a - sub-statement, to keep track of non-transactional changes in a - sub-statement, we re-use stmt.modified_non_trans_table. - At entrance into a sub-statement, a copy of the value of - stmt.modified_non_trans_table (containing the changes of the - outer statement) is saved on stack. Then - stmt.modified_non_trans_table is reset to FALSE and the - substatement is executed. Then the new value is merged with the - saved value. - */ - bool modified_non_trans_table; - - void reset() { - no_2pc= FALSE; - modified_non_trans_table= FALSE; - m_unsafe_rollback_flags= 0; - } - bool is_empty() const { return ha_list == NULL; } - THD_TRANS() {} /* Remove gcc warning */ - - unsigned int m_unsafe_rollback_flags; - /* - Define the type of statements which cannot be rolled back safely. - Each type occupies one bit in m_unsafe_rollback_flags. - */ - enum unsafe_statement_types - { - CREATED_TEMP_TABLE= 2, - DROPPED_TEMP_TABLE= 4, - DID_WAIT= 8, - DID_DDL= 0x10 - }; - - void mark_created_temp_table() - { - DBUG_PRINT("debug", ("mark_created_temp_table")); - m_unsafe_rollback_flags|= CREATED_TEMP_TABLE; - } - void mark_dropped_temp_table() - { - DBUG_PRINT("debug", ("mark_dropped_temp_table")); - m_unsafe_rollback_flags|= DROPPED_TEMP_TABLE; - } - bool has_created_dropped_temp_table() const { - return - (m_unsafe_rollback_flags & (CREATED_TEMP_TABLE|DROPPED_TEMP_TABLE)) != 0; - } - void mark_trans_did_wait() { m_unsafe_rollback_flags|= DID_WAIT; } - bool trans_did_wait() const { - return (m_unsafe_rollback_flags & DID_WAIT) != 0; - } - bool is_trx_read_write() const; - void mark_trans_did_ddl() { m_unsafe_rollback_flags|= DID_DDL; } - bool trans_did_ddl() const { - return (m_unsafe_rollback_flags & DID_DDL) != 0; - } - -}; - - -/** - Either statement transaction or normal transaction - related - thread-specific storage engine data. - - If a storage engine participates in a statement/transaction, - an instance of this class is present in - thd->transaction.{stmt|all}.ha_list. The addition to - {stmt|all}.ha_list is made by trans_register_ha(). - - When it's time to commit or rollback, each element of ha_list - is used to access storage engine's prepare()/commit()/rollback() - methods, and also to evaluate if a full two phase commit is - necessary. - - @sa General description of transaction handling in handler.cc. -*/ - -class Ha_trx_info -{ -public: - /** Register this storage engine in the given transaction context. */ - void register_ha(THD_TRANS *trans, handlerton *ht_arg) - { - DBUG_ASSERT(m_flags == 0); - DBUG_ASSERT(m_ht == NULL); - DBUG_ASSERT(m_next == NULL); - - m_ht= ht_arg; - m_flags= (int) TRX_READ_ONLY; /* Assume read-only at start. */ - - m_next= trans->ha_list; - trans->ha_list= this; - } - - /** Clear, prepare for reuse. */ - void reset() - { - m_next= NULL; - m_ht= NULL; - m_flags= 0; - } - - Ha_trx_info() { reset(); } - - void set_trx_read_write() - { - DBUG_ASSERT(is_started()); - m_flags|= (int) TRX_READ_WRITE; - } - bool is_trx_read_write() const - { - DBUG_ASSERT(is_started()); - return m_flags & (int) TRX_READ_WRITE; - } - bool is_started() const { return m_ht != NULL; } - /** Mark this transaction read-write if the argument is read-write. */ - void coalesce_trx_with(const Ha_trx_info *stmt_trx) - { - /* - Must be called only after the transaction has been started. - Can be called many times, e.g. when we have many - read-write statements in a transaction. - */ - DBUG_ASSERT(is_started()); - if (stmt_trx->is_trx_read_write()) - set_trx_read_write(); - } - Ha_trx_info *next() const - { - DBUG_ASSERT(is_started()); - return m_next; - } - handlerton *ht() const - { - DBUG_ASSERT(is_started()); - return m_ht; - } -private: - enum { TRX_READ_ONLY= 0, TRX_READ_WRITE= 1 }; - /** Auxiliary, used for ha_list management */ - Ha_trx_info *m_next; - /** - Although a given Ha_trx_info instance is currently always used - for the same storage engine, 'ht' is not-NULL only when the - corresponding storage is a part of a transaction. - */ - handlerton *m_ht; - /** - Transaction flags related to this engine. - Not-null only if this instance is a part of transaction. - May assume a combination of enum values above. - */ - uchar m_flags; -}; - - -inline bool THD_TRANS::is_trx_read_write() const -{ - Ha_trx_info *ha_info; - for (ha_info= ha_list; ha_info; ha_info= ha_info->next()) - if (ha_info->is_trx_read_write()) - return TRUE; - return FALSE; -} - - -enum enum_tx_isolation { ISO_READ_UNCOMMITTED, ISO_READ_COMMITTED, - ISO_REPEATABLE_READ, ISO_SERIALIZABLE}; - - -typedef struct { - ulonglong data_file_length; - ulonglong max_data_file_length; - ulonglong index_file_length; - ulonglong max_index_file_length; - ulonglong delete_length; - ha_rows records; - ulong mean_rec_length; - time_t create_time; - time_t check_time; - time_t update_time; - ulonglong check_sum; - bool check_sum_null; -} PARTITION_STATS; - -#define UNDEF_NODEGROUP 65535 -class Item; -struct st_table_log_memory_entry; - -class partition_info; - -struct st_partition_iter; - -enum ha_choice { HA_CHOICE_UNDEF, HA_CHOICE_NO, HA_CHOICE_YES, HA_CHOICE_MAX }; - -enum enum_stats_auto_recalc { HA_STATS_AUTO_RECALC_DEFAULT= 0, - HA_STATS_AUTO_RECALC_ON, - HA_STATS_AUTO_RECALC_OFF }; - -/** - A helper struct for schema DDL statements: - CREATE SCHEMA [IF NOT EXISTS] name [ schema_specification... ] - ALTER SCHEMA name [ schema_specification... ] - - It stores the "schema_specification" part of the CREATE/ALTER statements and - is passed to mysql_create_db() and mysql_alter_db(). - Currently consists of the schema default character set, collation - and schema_comment. -*/ -struct Schema_specification_st -{ - CHARSET_INFO *default_table_charset; - LEX_CSTRING *schema_comment; - void init() - { - bzero(this, sizeof(*this)); - } -}; - -class Create_field; - -struct Table_period_info: Sql_alloc -{ - Table_period_info() : - create_if_not_exists(false), - constr(NULL), - unique_keys(0) {} - Table_period_info(const char *name_arg, size_t size) : - name(name_arg, size), - create_if_not_exists(false), - constr(NULL), - unique_keys(0){} - - Lex_ident name; - - struct start_end_t - { - start_end_t() {}; - start_end_t(const LEX_CSTRING& _start, const LEX_CSTRING& _end) : - start(_start), - end(_end) {} - Lex_ident start; - Lex_ident end; - }; - start_end_t period; - bool create_if_not_exists; - Virtual_column_info *constr; - uint unique_keys; - - bool is_set() const - { - DBUG_ASSERT(bool(period.start) == bool(period.end)); - return period.start; - } - - void set_period(const Lex_ident& start, const Lex_ident& end) - { - period.start= start; - period.end= end; - } - bool check_field(const Create_field* f, const Lex_ident& f_name) const; -}; - -struct Vers_parse_info: public Table_period_info -{ - Vers_parse_info() : - Table_period_info(STRING_WITH_LEN("SYSTEM_TIME")), - versioned_fields(false), - unversioned_fields(false) - {} - - Table_period_info::start_end_t as_row; - -protected: - friend struct Table_scope_and_contents_source_st; - void set_start(const LEX_CSTRING field_name) - { - as_row.start= field_name; - period.start= field_name; - } - void set_end(const LEX_CSTRING field_name) - { - as_row.end= field_name; - period.end= field_name; - } - bool is_start(const char *name) const; - bool is_end(const char *name) const; - bool is_start(const Create_field &f) const; - bool is_end(const Create_field &f) const; - bool fix_implicit(THD *thd, Alter_info *alter_info); - operator bool() const - { - return as_row.start || as_row.end || period.start || period.end; - } - bool need_check(const Alter_info *alter_info) const; - bool check_conditions(const Lex_table_name &table_name, - const Lex_table_name &db) const; -public: - static const Lex_ident default_start; - static const Lex_ident default_end; - - bool fix_alter_info(THD *thd, Alter_info *alter_info, - HA_CREATE_INFO *create_info, TABLE *table); - bool fix_create_like(Alter_info &alter_info, HA_CREATE_INFO &create_info, - TABLE_LIST &src_table, TABLE_LIST &table); - bool check_sys_fields(const Lex_table_name &table_name, - const Lex_table_name &db, Alter_info *alter_info) const; - - /** - At least one field was specified 'WITH/WITHOUT SYSTEM VERSIONING'. - Useful for error handling. - */ - bool versioned_fields : 1; - bool unversioned_fields : 1; -}; - -/** - A helper struct for table DDL statements, e.g.: - CREATE [OR REPLACE] [TEMPORARY] - TABLE [IF NOT EXISTS] tbl_name table_contents_source; - - Represents a combinations of: - 1. The scope, i.e. TEMPORARY or not TEMPORARY - 2. The "table_contents_source" part of the table DDL statements, - which can be initialized from either of these: - - table_element_list ... // Explicit definition (column and key list) - - LIKE another_table_name ... // Copy structure from another table - - [AS] SELECT ... // Copy structure from a subquery -*/ - -struct Table_scope_and_contents_source_pod_st // For trivial members -{ - CHARSET_INFO *table_charset; - LEX_CUSTRING tabledef_version; - LEX_CSTRING connect_string; - LEX_CSTRING comment; - LEX_CSTRING alias; - const char *password, *tablespace; - const char *data_file_name, *index_file_name; - ulonglong max_rows,min_rows; - ulonglong auto_increment_value; - ulong table_options; ///< HA_OPTION_ values - ulong avg_row_length; - ulong used_fields; - ulong key_block_size; - ulong expression_length; - ulong field_check_constraints; - /* - number of pages to sample during - stats estimation, if used, otherwise 0. - */ - uint stats_sample_pages; - uint null_bits; /* NULL bits at start of record */ - uint options; /* OR of HA_CREATE_ options */ - uint merge_insert_method; - uint extra_size; /* length of extra data segment */ - handlerton *db_type; - /** - Row type of the table definition. - - Defaults to ROW_TYPE_DEFAULT for all non-ALTER statements. - For ALTER TABLE defaults to ROW_TYPE_NOT_USED (means "keep the current"). - - Can be changed either explicitly by the parser. - If nothing specified inherits the value of the original table (if present). - */ - enum row_type row_type; - enum ha_choice transactional; - enum ha_storage_media storage_media; ///< DEFAULT, DISK or MEMORY - enum ha_choice page_checksum; ///< If we have page_checksums - engine_option_value *option_list; ///< list of table create options - enum_stats_auto_recalc stats_auto_recalc; - bool varchar; ///< 1 if table has a VARCHAR - bool sequence; // If SEQUENCE=1 was used - - List *check_constraint_list; - - /* the following three are only for ALTER TABLE, check_if_incompatible_data() */ - ha_table_option_struct *option_struct; ///< structure with parsed table options - ha_field_option_struct **fields_option_struct; ///< array of field option structures - ha_index_option_struct **indexes_option_struct; ///< array of index option structures - - /* The following is used to remember the old state for CREATE OR REPLACE */ - TABLE *table; - TABLE_LIST *pos_in_locked_tables; - TABLE_LIST *merge_list; - MDL_ticket *mdl_ticket; - bool table_was_deleted; - sequence_definition *seq_create_info; - - void init() - { - bzero(this, sizeof(*this)); - } - bool tmp_table() const { return options & HA_LEX_CREATE_TMP_TABLE; } - void use_default_db_type(THD *thd) - { - db_type= tmp_table() ? ha_default_tmp_handlerton(thd) - : ha_default_handlerton(thd); - } - - bool versioned() const - { - return options & HA_VERSIONED_TABLE; - } -}; - - -struct Table_scope_and_contents_source_st: - public Table_scope_and_contents_source_pod_st -{ - Vers_parse_info vers_info; - Table_period_info period_info; - - void init() - { - Table_scope_and_contents_source_pod_st::init(); - vers_info= {}; - period_info= {}; - } - - bool fix_create_fields(THD *thd, Alter_info *alter_info, - const TABLE_LIST &create_table); - bool fix_period_fields(THD *thd, Alter_info *alter_info); - bool check_fields(THD *thd, Alter_info *alter_info, - const Lex_table_name &table_name, - const Lex_table_name &db, - int select_count= 0); - bool check_period_fields(THD *thd, Alter_info *alter_info); - - bool vers_fix_system_fields(THD *thd, Alter_info *alter_info, - const TABLE_LIST &create_table); - - bool vers_check_system_fields(THD *thd, Alter_info *alter_info, - const Lex_table_name &table_name, - const Lex_table_name &db, - int select_count= 0); - -}; - - -/** - This struct is passed to handler table routines, e.g. ha_create(). - It does not include the "OR REPLACE" and "IF NOT EXISTS" parts, as these - parts are handled on the SQL level and are not needed on the handler level. -*/ -struct HA_CREATE_INFO: public Table_scope_and_contents_source_st, - public Schema_specification_st -{ - /* TODO: remove after MDEV-20865 */ - Alter_info *alter_info; - - void init() - { - Table_scope_and_contents_source_st::init(); - Schema_specification_st::init(); - alter_info= NULL; - } - bool check_conflicting_charset_declarations(CHARSET_INFO *cs); - bool add_table_option_default_charset(CHARSET_INFO *cs) - { - // cs can be NULL, e.g.: CREATE TABLE t1 (..) CHARACTER SET DEFAULT; - if (check_conflicting_charset_declarations(cs)) - return true; - default_table_charset= cs; - used_fields|= HA_CREATE_USED_DEFAULT_CHARSET; - return false; - } - bool add_alter_list_item_convert_to_charset(CHARSET_INFO *cs) - { - /* - cs cannot be NULL, as sql_yacc.yy translates - CONVERT TO CHARACTER SET DEFAULT - to - CONVERT TO CHARACTER SET - TODO: Shouldn't we postpone resolution of DEFAULT until the - character set of the table owner database is loaded from its db.opt? - */ - DBUG_ASSERT(cs); - if (check_conflicting_charset_declarations(cs)) - return true; - table_charset= default_table_charset= cs; - used_fields|= (HA_CREATE_USED_CHARSET | HA_CREATE_USED_DEFAULT_CHARSET); - return false; - } - ulong table_options_with_row_type() - { - if (row_type == ROW_TYPE_DYNAMIC || row_type == ROW_TYPE_PAGE) - return table_options | HA_OPTION_PACK_RECORD; - else - return table_options; - } -}; - - -/** - This struct is passed to mysql_create_table() and similar creation functions, - as well as to show_create_table(). -*/ -struct Table_specification_st: public HA_CREATE_INFO, - public DDL_options_st -{ - // Deep initialization - void init() - { - HA_CREATE_INFO::init(); - DDL_options_st::init(); - } - void init(DDL_options_st::Options options_arg) - { - HA_CREATE_INFO::init(); - DDL_options_st::init(options_arg); - } - /* - Quick initialization, for parser. - Most of the HA_CREATE_INFO is left uninitialized. - It gets fully initialized in sql_yacc.yy, only when the parser - scans a related keyword (e.g. CREATE, ALTER). - */ - void lex_start() - { - HA_CREATE_INFO::options= 0; - DDL_options_st::init(); - } -}; - - -/** - In-place alter handler context. - - This is a superclass intended to be subclassed by individual handlers - in order to store handler unique context between in-place alter API calls. - - The handler is responsible for creating the object. This can be done - as early as during check_if_supported_inplace_alter(). - - The SQL layer is responsible for destroying the object. - The class extends Sql_alloc so the memory will be mem root allocated. - - @see Alter_inplace_info -*/ - -class inplace_alter_handler_ctx : public Sql_alloc -{ -public: - inplace_alter_handler_ctx() {} - - virtual ~inplace_alter_handler_ctx() {} - virtual void set_shared_data(const inplace_alter_handler_ctx& ctx) {} -}; - - -/** - Class describing changes to be done by ALTER TABLE. - Instance of this class is passed to storage engine in order - to determine if this ALTER TABLE can be done using in-place - algorithm. It is also used for executing the ALTER TABLE - using in-place algorithm. -*/ - -class Alter_inplace_info -{ -public: - - /** - Create options (like MAX_ROWS) for the new version of table. - - @note The referenced instance of HA_CREATE_INFO object was already - used to create new .FRM file for table being altered. So it - has been processed by mysql_prepare_create_table() already. - For example, this means that it has HA_OPTION_PACK_RECORD - flag in HA_CREATE_INFO::table_options member correctly set. - */ - HA_CREATE_INFO *create_info; - - /** - Alter options, fields and keys for the new version of table. - - @note The referenced instance of Alter_info object was already - used to create new .FRM file for table being altered. So it - has been processed by mysql_prepare_create_table() already. - In particular, this means that in Create_field objects for - fields which were present in some form in the old version - of table, Create_field::field member points to corresponding - Field instance for old version of table. - */ - Alter_info *alter_info; - - /** - Array of KEYs for new version of table - including KEYs to be added. - - @note Currently this array is produced as result of - mysql_prepare_create_table() call. - This means that it follows different convention for - KEY_PART_INFO::fieldnr values than objects in TABLE::key_info - array. - - @todo This is mainly due to the fact that we need to keep compatibility - with removed handler::add_index() call. We plan to switch to - TABLE::key_info numbering later. - - KEYs are sorted - see sort_keys(). - */ - KEY *key_info_buffer; - - /** Size of key_info_buffer array. */ - uint key_count; - - /** Size of index_drop_buffer array. */ - uint index_drop_count; - - /** - Array of pointers to KEYs to be dropped belonging to the TABLE instance - for the old version of the table. - */ - KEY **index_drop_buffer; - - /** Size of index_add_buffer array. */ - uint index_add_count; - - /** - Array of indexes into key_info_buffer for KEYs to be added, - sorted in increasing order. - */ - uint *index_add_buffer; - - /** - Old and new index names. Used for index rename. - */ - struct Rename_key_pair - { - Rename_key_pair(const KEY *old_key, const KEY *new_key) - : old_key(old_key), new_key(new_key) - { - } - const KEY *old_key; - const KEY *new_key; - }; - /** - Vector of key pairs from DROP/ADD index which can be renamed. - */ - typedef Mem_root_array Rename_keys_vector; - - /** - A list of indexes which should be renamed. - Index definitions stays the same. - */ - Rename_keys_vector rename_keys; - - /** - Context information to allow handlers to keep context between in-place - alter API calls. - - @see inplace_alter_handler_ctx for information about object lifecycle. - */ - inplace_alter_handler_ctx *handler_ctx; - - /** - If the table uses several handlers, like ha_partition uses one handler - per partition, this contains a Null terminated array of ctx pointers - that should all be committed together. - Or NULL if only handler_ctx should be committed. - Set to NULL if the low level handler::commit_inplace_alter_table uses it, - to signal to the main handler that everything was committed as atomically. - - @see inplace_alter_handler_ctx for information about object lifecycle. - */ - inplace_alter_handler_ctx **group_commit_ctx; - - /** - Flags describing in detail which operations the storage engine is to - execute. Flags are defined in sql_alter.h - */ - alter_table_operations handler_flags; - - /* Alter operations involving parititons are strored here */ - ulong partition_flags; - - /** - Partition_info taking into account the partition changes to be performed. - Contains all partitions which are present in the old version of the table - with partitions to be dropped or changed marked as such + all partitions - to be added in the new version of table marked as such. - */ - partition_info *modified_part_info; - - /** true for ALTER IGNORE TABLE ... */ - const bool ignore; - - /** true for online operation (LOCK=NONE) */ - bool online; - - /** which ALGORITHM and LOCK are supported by the storage engine */ - enum_alter_inplace_result inplace_supported; - - /** - Can be set by handler to describe why a given operation cannot be done - in-place (HA_ALTER_INPLACE_NOT_SUPPORTED) or why it cannot be done - online (HA_ALTER_INPLACE_NO_LOCK or HA_ALTER_INPLACE_COPY_NO_LOCK) - If set, it will be used with ER_ALTER_OPERATION_NOT_SUPPORTED_REASON if - results from handler::check_if_supported_inplace_alter() doesn't match - requirements set by user. If not set, the more generic - ER_ALTER_OPERATION_NOT_SUPPORTED will be used. - - Please set to a properly localized string, for example using - my_get_err_msg(), so that the error message as a whole is localized. - */ - const char *unsupported_reason; - - /** true when InnoDB should abort the alter when table is not empty */ - bool error_if_not_empty; - - Alter_inplace_info(HA_CREATE_INFO *create_info_arg, - Alter_info *alter_info_arg, - KEY *key_info_arg, uint key_count_arg, - partition_info *modified_part_info_arg, - bool ignore_arg, bool error_non_empty); - - ~Alter_inplace_info() - { - delete handler_ctx; - } - - /** - Used after check_if_supported_inplace_alter() to report - error if the result does not match the LOCK/ALGORITHM - requirements set by the user. - - @param not_supported Part of statement that was not supported. - @param try_instead Suggestion as to what the user should - replace not_supported with. - */ - void report_unsupported_error(const char *not_supported, - const char *try_instead) const; -}; - - -typedef struct st_key_create_information -{ - enum ha_key_alg algorithm; - ulong block_size; - uint flags; /* HA_USE.. flags */ - LEX_CSTRING parser_name; - LEX_CSTRING comment; - /** - A flag to determine if we will check for duplicate indexes. - This typically means that the key information was specified - directly by the user (set by the parser). - */ - bool check_for_duplicate_indexes; -} KEY_CREATE_INFO; - - -/* - Class for maintaining hooks used inside operations on tables such - as: create table functions, delete table functions, and alter table - functions. - - Class is using the Template Method pattern to separate the public - usage interface from the private inheritance interface. This - imposes no overhead, since the public non-virtual function is small - enough to be inlined. - - The hooks are usually used for functions that does several things, - e.g., create_table_from_items(), which both create a table and lock - it. - */ -class TABLEOP_HOOKS -{ -public: - TABLEOP_HOOKS() {} - virtual ~TABLEOP_HOOKS() {} - - inline void prelock(TABLE **tables, uint count) - { - do_prelock(tables, count); - } - - inline int postlock(TABLE **tables, uint count) - { - return do_postlock(tables, count); - } -private: - /* Function primitive that is called prior to locking tables */ - virtual void do_prelock(TABLE **tables, uint count) - { - /* Default is to do nothing */ - } - - /** - Primitive called after tables are locked. - - If an error is returned, the tables will be unlocked and error - handling start. - - @return Error code or zero. - */ - virtual int do_postlock(TABLE **tables, uint count) - { - return 0; /* Default is to do nothing */ - } -}; - -typedef struct st_savepoint SAVEPOINT; -extern ulong savepoint_alloc_size; -extern KEY_CREATE_INFO default_key_create_info; - -/* Forward declaration for condition pushdown to storage engine */ -typedef class Item COND; - -typedef struct st_ha_check_opt -{ - st_ha_check_opt() {} /* Remove gcc warning */ - uint flags; /* isam layer flags (e.g. for myisamchk) */ - uint sql_flags; /* sql layer flags - for something myisamchk cannot do */ - time_t start_time; /* When check/repair starts */ - KEY_CACHE *key_cache; /* new key cache when changing key cache */ - void init(); -} HA_CHECK_OPT; - - -/******************************************************************************** - * MRR - ********************************************************************************/ - -typedef void *range_seq_t; - -typedef struct st_range_seq_if -{ - /* - Get key information - - SYNOPSIS - get_key_info() - init_params The seq_init_param parameter - length OUT length of the keys in this range sequence - map OUT key_part_map of the keys in this range sequence - - DESCRIPTION - This function is set only when using HA_MRR_FIXED_KEY mode. In that mode, - all ranges are single-point equality ranges that use the same set of key - parts. This function allows the MRR implementation to get the length of - a key, and which keyparts it uses. - */ - void (*get_key_info)(void *init_params, uint *length, key_part_map *map); - - /* - Initialize the traversal of range sequence - - SYNOPSIS - init() - init_params The seq_init_param parameter - n_ranges The number of ranges obtained - flags A combination of HA_MRR_SINGLE_POINT, HA_MRR_FIXED_KEY - - RETURN - An opaque value to be used as RANGE_SEQ_IF::next() parameter - */ - range_seq_t (*init)(void *init_params, uint n_ranges, uint flags); - - - /* - Get the next range in the range sequence - - SYNOPSIS - next() - seq The value returned by RANGE_SEQ_IF::init() - range OUT Information about the next range - - RETURN - FALSE - Ok, the range structure filled with info about the next range - TRUE - No more ranges - */ - bool (*next) (range_seq_t seq, KEY_MULTI_RANGE *range); - - /* - Check whether range_info orders to skip the next record - - SYNOPSIS - skip_record() - seq The value returned by RANGE_SEQ_IF::init() - range_info Information about the next range - (Ignored if MRR_NO_ASSOCIATION is set) - rowid Rowid of the record to be checked (ignored if set to 0) - - RETURN - 1 - Record with this range_info and/or this rowid shall be filtered - out from the stream of records returned by multi_range_read_next() - 0 - The record shall be left in the stream - */ - bool (*skip_record) (range_seq_t seq, range_id_t range_info, uchar *rowid); - - /* - Check if the record combination matches the index condition - SYNOPSIS - skip_index_tuple() - seq The value returned by RANGE_SEQ_IF::init() - range_info Information about the next range - - RETURN - 0 - The record combination satisfies the index condition - 1 - Otherwise - */ - bool (*skip_index_tuple) (range_seq_t seq, range_id_t range_info); -} RANGE_SEQ_IF; - -typedef bool (*SKIP_INDEX_TUPLE_FUNC) (range_seq_t seq, range_id_t range_info); - -class Cost_estimate -{ -public: - double io_count; /* number of I/O to fetch records */ - double avg_io_cost; /* cost of an average I/O oper. to fetch records */ - double idx_io_count; /* number of I/O to read keys */ - double idx_avg_io_cost; /* cost of an average I/O oper. to fetch records */ - double cpu_cost; /* total cost of operations in CPU */ - double idx_cpu_cost; /* cost of operations in CPU for index */ - double import_cost; /* cost of remote operations */ - double mem_cost; /* cost of used memory */ - - static constexpr double IO_COEFF= 1; - static constexpr double CPU_COEFF= 1; - static constexpr double MEM_COEFF= 1; - static constexpr double IMPORT_COEFF= 1; - - Cost_estimate() - { - reset(); - } - - double total_cost() const - { - return IO_COEFF*io_count*avg_io_cost + - IO_COEFF*idx_io_count*idx_avg_io_cost + - CPU_COEFF*(cpu_cost + idx_cpu_cost) + - MEM_COEFF*mem_cost + IMPORT_COEFF*import_cost; - } - - double index_only_cost() - { - return IO_COEFF*idx_io_count*idx_avg_io_cost + - CPU_COEFF*idx_cpu_cost; - } - - /** - Whether or not all costs in the object are zero - - @return true if all costs are zero, false otherwise - */ - bool is_zero() const - { - return io_count == 0.0 && idx_io_count == 0.0 && cpu_cost == 0.0 && - import_cost == 0.0 && mem_cost == 0.0; - } - - void reset() - { - avg_io_cost= 1.0; - idx_avg_io_cost= 1.0; - io_count= idx_io_count= cpu_cost= idx_cpu_cost= mem_cost= import_cost= 0.0; - } - - void multiply(double m) - { - io_count *= m; - cpu_cost *= m; - idx_io_count *= m; - idx_cpu_cost *= m; - import_cost *= m; - /* Don't multiply mem_cost */ - } - - void add(const Cost_estimate* cost) - { - if (cost->io_count != 0.0) - { - double io_count_sum= io_count + cost->io_count; - avg_io_cost= (io_count * avg_io_cost + - cost->io_count * cost->avg_io_cost) - /io_count_sum; - io_count= io_count_sum; - } - if (cost->idx_io_count != 0.0) - { - double idx_io_count_sum= idx_io_count + cost->idx_io_count; - idx_avg_io_cost= (idx_io_count * idx_avg_io_cost + - cost->idx_io_count * cost->idx_avg_io_cost) - /idx_io_count_sum; - idx_io_count= idx_io_count_sum; - } - cpu_cost += cost->cpu_cost; - idx_cpu_cost += cost->idx_cpu_cost; - import_cost += cost->import_cost; - } - - void add_io(double add_io_cnt, double add_avg_cost) - { - /* In edge cases add_io_cnt may be zero */ - if (add_io_cnt > 0) - { - double io_count_sum= io_count + add_io_cnt; - avg_io_cost= (io_count * avg_io_cost + - add_io_cnt * add_avg_cost) / io_count_sum; - io_count= io_count_sum; - } - } - - /// Add to CPU cost - void add_cpu(double add_cpu_cost) { cpu_cost+= add_cpu_cost; } - - /// Add to import cost - void add_import(double add_import_cost) { import_cost+= add_import_cost; } - - /// Add to memory cost - void add_mem(double add_mem_cost) { mem_cost+= add_mem_cost; } - - /* - To be used when we go from old single value-based cost calculations to - the new Cost_estimate-based. - */ - void convert_from_cost(double cost) - { - reset(); - io_count= cost; - } -}; - -void get_sweep_read_cost(TABLE *table, ha_rows nrows, bool interrupted, - Cost_estimate *cost); - -/* - Indicates that all scanned ranges will be singlepoint (aka equality) ranges. - The ranges may not use the full key but all of them will use the same number - of key parts. -*/ -#define HA_MRR_SINGLE_POINT 1U -#define HA_MRR_FIXED_KEY 2U - -/* - Indicates that RANGE_SEQ_IF::next(&range) doesn't need to fill in the - 'range' parameter. -*/ -#define HA_MRR_NO_ASSOCIATION 4U - -/* - The MRR user will provide ranges in key order, and MRR implementation - must return rows in key order. -*/ -#define HA_MRR_SORTED 8U - -/* MRR implementation doesn't have to retrieve full records */ -#define HA_MRR_INDEX_ONLY 16U - -/* - The passed memory buffer is of maximum possible size, the caller can't - assume larger buffer. -*/ -#define HA_MRR_LIMITS 32U - - -/* - Flag set <=> default MRR implementation is used - (The choice is made by **_info[_const]() function which may set this - flag. SQL layer remembers the flag value and then passes it to - multi_read_range_init(). -*/ -#define HA_MRR_USE_DEFAULT_IMPL 64U - -/* - Used only as parameter to multi_range_read_info(): - Flag set <=> the caller guarantees that the bounds of the scanned ranges - will not have NULL values. -*/ -#define HA_MRR_NO_NULL_ENDPOINTS 128U - -/* - The MRR user has materialized range keys somewhere in the user's buffer. - This can be used for optimization of the procedure that sorts these keys - since in this case key values don't have to be copied into the MRR buffer. - - In other words, it is guaranteed that after RANGE_SEQ_IF::next() call the - pointer in range->start_key.key will point to a key value that will remain - there until the end of the MRR scan. -*/ -#define HA_MRR_MATERIALIZED_KEYS 256U - -/* - The following bits are reserved for use by MRR implementation. The intended - use scenario: - - * sql layer calls handler->multi_range_read_info[_const]() - - MRR implementation figures out what kind of scan it will perform, saves - the result in *mrr_mode parameter. - * sql layer remembers what was returned in *mrr_mode - - * the optimizer picks the query plan (which may or may not include the MRR - scan that was estimated by the multi_range_read_info[_const] call) - - * if the query is an EXPLAIN statement, sql layer will call - handler->multi_range_read_explain_info(mrr_mode) to get a text description - of the picked MRR scan; the description will be a part of EXPLAIN output. -*/ -#define HA_MRR_IMPLEMENTATION_FLAG1 512U -#define HA_MRR_IMPLEMENTATION_FLAG2 1024U -#define HA_MRR_IMPLEMENTATION_FLAG3 2048U -#define HA_MRR_IMPLEMENTATION_FLAG4 4096U -#define HA_MRR_IMPLEMENTATION_FLAG5 8192U -#define HA_MRR_IMPLEMENTATION_FLAG6 16384U - -#define HA_MRR_IMPLEMENTATION_FLAGS \ - (512U | 1024U | 2048U | 4096U | 8192U | 16384U) - -/* - This is a buffer area that the handler can use to store rows. - 'end_of_used_area' should be kept updated after calls to - read-functions so that other parts of the code can use the - remaining area (until next read calls is issued). -*/ - -typedef struct st_handler_buffer -{ - /* const? */uchar *buffer; /* Buffer one can start using */ - /* const? */uchar *buffer_end; /* End of buffer */ - uchar *end_of_used_area; /* End of area that was used by handler */ -} HANDLER_BUFFER; - -typedef struct system_status_var SSV; - -class ha_statistics -{ -public: - ulonglong data_file_length; /* Length off data file */ - ulonglong max_data_file_length; /* Length off data file */ - ulonglong index_file_length; - ulonglong max_index_file_length; - ulonglong delete_length; /* Free bytes */ - ulonglong auto_increment_value; - /* - The number of records in the table. - 0 - means the table has exactly 0 rows - other - if (table_flags() & HA_STATS_RECORDS_IS_EXACT) - the value is the exact number of records in the table - else - it is an estimate - */ - ha_rows records; - ha_rows deleted; /* Deleted records */ - ulong mean_rec_length; /* physical reclength */ - time_t create_time; /* When table was created */ - time_t check_time; - time_t update_time; - uint block_size; /* index block size */ - ha_checksum checksum; - bool checksum_null; - - /* - number of buffer bytes that native mrr implementation needs, - */ - uint mrr_length_per_rec; - - ha_statistics(): - data_file_length(0), max_data_file_length(0), - index_file_length(0), max_index_file_length(0), delete_length(0), - auto_increment_value(0), records(0), deleted(0), mean_rec_length(0), - create_time(0), check_time(0), update_time(0), block_size(8192), - checksum(0), checksum_null(FALSE), mrr_length_per_rec(0) - {} -}; - -extern "C" check_result_t handler_index_cond_check(void* h_arg); - -extern "C" check_result_t handler_rowid_filter_check(void* h_arg); -extern "C" int handler_rowid_filter_is_active(void* h_arg); - -uint calculate_key_len(TABLE *, uint, const uchar *, key_part_map); -/* - bitmap with first N+1 bits set - (keypart_map for a key prefix of [0..N] keyparts) -*/ -#define make_keypart_map(N) (((key_part_map)2 << (N)) - 1) -/* - bitmap with first N bits set - (keypart_map for a key prefix of [0..N-1] keyparts) -*/ -#define make_prev_keypart_map(N) (((key_part_map)1 << (N)) - 1) - - -/** Base class to be used by handlers different shares */ -class Handler_share -{ -public: - Handler_share() {} - virtual ~Handler_share() {} -}; - -enum class Compare_keys : uint32_t -{ - Equal= 0, - EqualButKeyPartLength, - EqualButComment, - NotEqual -}; - -/** - The handler class is the interface for dynamically loadable - storage engines. Do not add ifdefs and take care when adding or - changing virtual functions to avoid vtable confusion - - Functions in this class accept and return table columns data. Two data - representation formats are used: - 1. TableRecordFormat - Used to pass [partial] table records to/from - storage engine - - 2. KeyTupleFormat - used to pass index search tuples (aka "keys") to - storage engine. See opt_range.cc for description of this format. - - TableRecordFormat - ================= - [Warning: this description is work in progress and may be incomplete] - The table record is stored in a fixed-size buffer: - - record: null_bytes, column1_data, column2_data, ... - - The offsets of the parts of the buffer are also fixed: every column has - an offset to its column{i}_data, and if it is nullable it also has its own - bit in null_bytes. - - The record buffer only includes data about columns that are marked in the - relevant column set (table->read_set and/or table->write_set, depending on - the situation). - It could be that it is required that null bits of non-present - columns are set to 1 - - VARIOUS EXCEPTIONS AND SPECIAL CASES - - If the table has no nullable columns, then null_bytes is still - present, its length is one byte which must be set to 0xFF - at all times. - - If the table has columns of type BIT, then certain bits from those columns - may be stored in null_bytes as well. Grep around for Field_bit for - details. - - For blob columns (see Field_blob), the record buffer stores length of the - data, following by memory pointer to the blob data. The pointer is owned - by the storage engine and is valid until the next operation. - - If a blob column has NULL value, then its length and blob data pointer - must be set to 0. -*/ - -class handler :public Sql_alloc -{ -public: - typedef ulonglong Table_flags; -protected: - TABLE_SHARE *table_share; /* The table definition */ - TABLE *table; /* The current open table */ - Table_flags cached_table_flags; /* Set on init() and open() */ - - ha_rows estimation_rows_to_insert; - handler *lookup_handler; -public: - handlerton *ht; /* storage engine of this handler */ - uchar *ref; /* Pointer to current row */ - uchar *dup_ref; /* Pointer to duplicate row */ - uchar *lookup_buffer; - - ha_statistics stats; - - /** MultiRangeRead-related members: */ - range_seq_t mrr_iter; /* Iterator to traverse the range sequence */ - RANGE_SEQ_IF mrr_funcs; /* Range sequence traversal functions */ - HANDLER_BUFFER *multi_range_buffer; /* MRR buffer info */ - uint ranges_in_seq; /* Total number of ranges in the traversed sequence */ - /** Current range (the one we're now returning rows from) */ - KEY_MULTI_RANGE mrr_cur_range; - - /** The following are for read_range() */ - key_range save_end_range, *end_range; - KEY_PART_INFO *range_key_part; - int key_compare_result_on_equal; - - /* TRUE <=> source MRR ranges and the output are ordered */ - bool mrr_is_output_sorted; - /** TRUE <=> we're currently traversing a range in mrr_cur_range. */ - bool mrr_have_range; - bool eq_range; - bool internal_tmp_table; /* If internal tmp table */ - bool implicit_emptied; /* Can be !=0 only if HEAP */ - bool mark_trx_read_write_done; /* mark_trx_read_write was called */ - bool check_table_binlog_row_based_done; /* check_table_binlog.. was called */ - bool check_table_binlog_row_based_result; /* cached check_table_binlog... */ - /* - TRUE <=> the engine guarantees that returned records are within the range - being scanned. - */ - bool in_range_check_pushed_down; - - uint lookup_errkey; - uint errkey; /* Last dup key */ - uint key_used_on_scan; - uint active_index, keyread; - - /** Length of ref (1-8 or the clustered key length) */ - uint ref_length; - FT_INFO *ft_handler; - enum init_stat { NONE=0, INDEX, RND }; - init_stat inited, pre_inited; - - const COND *pushed_cond; - /** - next_insert_id is the next value which should be inserted into the - auto_increment column: in a inserting-multi-row statement (like INSERT - SELECT), for the first row where the autoinc value is not specified by the - statement, get_auto_increment() called and asked to generate a value, - next_insert_id is set to the next value, then for all other rows - next_insert_id is used (and increased each time) without calling - get_auto_increment(). - */ - ulonglong next_insert_id; - /** - insert id for the current row (*autogenerated*; if not - autogenerated, it's 0). - At first successful insertion, this variable is stored into - THD::first_successful_insert_id_in_cur_stmt. - */ - ulonglong insert_id_for_cur_row; - /** - Interval returned by get_auto_increment() and being consumed by the - inserter. - */ - /* Statistics variables */ - ulonglong rows_read; - ulonglong rows_tmp_read; - ulonglong rows_changed; - /* One bigger than needed to avoid to test if key == MAX_KEY */ - ulonglong index_rows_read[MAX_KEY+1]; - ha_copy_info copy_info; - -private: - /* ANALYZE time tracker, if present */ - Exec_time_tracker *tracker; -public: - void set_time_tracker(Exec_time_tracker *tracker_arg) { tracker=tracker_arg;} - Exec_time_tracker *get_time_tracker() { return tracker; } - - Item *pushed_idx_cond; - uint pushed_idx_cond_keyno; /* The index which the above condition is for */ - - /* Rowid filter pushed into the engine */ - Rowid_filter *pushed_rowid_filter; - /* true when the pushed rowid filter has been already filled */ - bool rowid_filter_is_active; - - Discrete_interval auto_inc_interval_for_cur_row; - /** - Number of reserved auto-increment intervals. Serves as a heuristic - when we have no estimation of how many records the statement will insert: - the more intervals we have reserved, the bigger the next one. Reset in - handler::ha_release_auto_increment(). - */ - uint auto_inc_intervals_count; - - /** - Instrumented table associated with this handler. - This member should be set to NULL when no instrumentation is in place, - so that linking an instrumented/non instrumented server/plugin works. - For example: - - the server is compiled with the instrumentation. - The server expects either NULL or valid pointers in m_psi. - - an engine plugin is compiled without instrumentation. - The plugin can not leave this pointer uninitialized, - or can not leave a trash value on purpose in this pointer, - as this would crash the server. - */ - PSI_table *m_psi; - -private: - /** Internal state of the batch instrumentation. */ - enum batch_mode_t - { - /** Batch mode not used. */ - PSI_BATCH_MODE_NONE, - /** Batch mode used, before first table io. */ - PSI_BATCH_MODE_STARTING, - /** Batch mode used, after first table io. */ - PSI_BATCH_MODE_STARTED - }; - /** - Batch mode state. - @sa start_psi_batch_mode. - @sa end_psi_batch_mode. - */ - batch_mode_t m_psi_batch_mode; - /** - The number of rows in the batch. - @sa start_psi_batch_mode. - @sa end_psi_batch_mode. - */ - ulonglong m_psi_numrows; - /** - The current event in a batch. - @sa start_psi_batch_mode. - @sa end_psi_batch_mode. - */ - PSI_table_locker *m_psi_locker; - /** - Storage for the event in a batch. - @sa start_psi_batch_mode. - @sa end_psi_batch_mode. - */ - PSI_table_locker_state m_psi_locker_state; - -public: - virtual void unbind_psi(); - virtual void rebind_psi(); - /* Return error if definition doesn't match for already opened table */ - virtual int discover_check_version() { return 0; } - - /** - Put the handler in 'batch' mode when collecting - table io instrumented events. - When operating in batch mode: - - a single start event is generated in the performance schema. - - all table io performed between @c start_psi_batch_mode - and @c end_psi_batch_mode is not instrumented: - the number of rows affected is counted instead in @c m_psi_numrows. - - a single end event is generated in the performance schema - when the batch mode ends with @c end_psi_batch_mode. - */ - void start_psi_batch_mode(); - /** End a batch started with @c start_psi_batch_mode. */ - void end_psi_batch_mode(); - - /* If we have row logging enabled for this table */ - bool row_logging, row_logging_init; - /* If the row logging should be done in transaction cache */ - bool row_logging_has_trans; - -private: - /** - The lock type set by when calling::ha_external_lock(). This is - propagated down to the storage engine. The reason for also storing - it here, is that when doing MRR we need to create/clone a second handler - object. This cloned handler object needs to know about the lock_type used. - */ - int m_lock_type; - /** - Pointer where to store/retrieve the Handler_share pointer. - For non partitioned handlers this is &TABLE_SHARE::ha_share. - */ - Handler_share **ha_share; - - /** Stores next_insert_id for handling duplicate key errors. */ - ulonglong m_prev_insert_id; - -public: - handler(handlerton *ht_arg, TABLE_SHARE *share_arg) - :table_share(share_arg), table(0), - estimation_rows_to_insert(0), - lookup_handler(this), - ht(ht_arg), ref(0), lookup_buffer(NULL), end_range(NULL), - implicit_emptied(0), - mark_trx_read_write_done(0), - check_table_binlog_row_based_done(0), - check_table_binlog_row_based_result(0), - in_range_check_pushed_down(FALSE), lookup_errkey(-1), errkey(-1), - key_used_on_scan(MAX_KEY), - active_index(MAX_KEY), keyread(MAX_KEY), - ref_length(sizeof(my_off_t)), - ft_handler(0), inited(NONE), pre_inited(NONE), - pushed_cond(0), next_insert_id(0), insert_id_for_cur_row(0), - tracker(NULL), - pushed_idx_cond(NULL), - pushed_idx_cond_keyno(MAX_KEY), - pushed_rowid_filter(NULL), - rowid_filter_is_active(0), - auto_inc_intervals_count(0), - m_psi(NULL), - m_psi_batch_mode(PSI_BATCH_MODE_NONE), - m_psi_numrows(0), - m_psi_locker(NULL), - row_logging(0), row_logging_init(0), - m_lock_type(F_UNLCK), ha_share(NULL), m_prev_insert_id(0) - { - DBUG_PRINT("info", - ("handler created F_UNLCK %d F_RDLCK %d F_WRLCK %d", - F_UNLCK, F_RDLCK, F_WRLCK)); - reset_statistics(); - } - virtual ~handler(void) - { - DBUG_ASSERT(m_lock_type == F_UNLCK); - DBUG_ASSERT(inited == NONE); - } - /* To check if table has been properely opened */ - bool is_open() - { - return ref != 0; - } - virtual handler *clone(const char *name, MEM_ROOT *mem_root); - /** This is called after create to allow us to set up cached variables */ - void init() - { - cached_table_flags= table_flags(); - } - /* ha_ methods: pubilc wrappers for private virtual API */ - - int ha_open(TABLE *table, const char *name, int mode, uint test_if_locked, - MEM_ROOT *mem_root= 0, List *partitions_to_open=NULL); - int ha_index_init(uint idx, bool sorted) - { - DBUG_EXECUTE_IF("ha_index_init_fail", return HA_ERR_TABLE_DEF_CHANGED;); - int result; - DBUG_ENTER("ha_index_init"); - DBUG_ASSERT(inited==NONE); - if (!(result= index_init(idx, sorted))) - { - inited= INDEX; - active_index= idx; - end_range= NULL; - } - DBUG_RETURN(result); - } - int ha_index_end() - { - DBUG_ENTER("ha_index_end"); - DBUG_ASSERT(inited==INDEX); - inited= NONE; - active_index= MAX_KEY; - end_range= NULL; - DBUG_RETURN(index_end()); - } - /* This is called after index_init() if we need to do a index scan */ - virtual int prepare_index_scan() { return 0; } - virtual int prepare_index_key_scan_map(const uchar * key, key_part_map keypart_map) - { - uint key_len= calculate_key_len(table, active_index, key, keypart_map); - return prepare_index_key_scan(key, key_len); - } - virtual int prepare_index_key_scan( const uchar * key, uint key_len ) - { return 0; } - virtual int prepare_range_scan(const key_range *start_key, const key_range *end_key) - { return 0; } - - int ha_rnd_init(bool scan) __attribute__ ((warn_unused_result)) - { - DBUG_EXECUTE_IF("ha_rnd_init_fail", return HA_ERR_TABLE_DEF_CHANGED;); - int result; - DBUG_ENTER("ha_rnd_init"); - DBUG_ASSERT(inited==NONE || (inited==RND && scan)); - inited= (result= rnd_init(scan)) ? NONE: RND; - end_range= NULL; - DBUG_RETURN(result); - } - int ha_rnd_end() - { - DBUG_ENTER("ha_rnd_end"); - DBUG_ASSERT(inited==RND); - inited=NONE; - end_range= NULL; - DBUG_RETURN(rnd_end()); - } - int ha_rnd_init_with_error(bool scan) __attribute__ ((warn_unused_result)); - int ha_reset(); - /* this is necessary in many places, e.g. in HANDLER command */ - int ha_index_or_rnd_end() - { - return inited == INDEX ? ha_index_end() : inited == RND ? ha_rnd_end() : 0; - } - /** - The cached_table_flags is set at ha_open and ha_external_lock - */ - Table_flags ha_table_flags() const - { - DBUG_ASSERT(cached_table_flags < (HA_LAST_TABLE_FLAG << 1)); - return cached_table_flags; - } - /** - These functions represent the public interface to *users* of the - handler class, hence they are *not* virtual. For the inheritance - interface, see the (private) functions write_row(), update_row(), - and delete_row() below. - */ - int ha_external_lock(THD *thd, int lock_type); - int ha_external_unlock(THD *thd) { return ha_external_lock(thd, F_UNLCK); } - int ha_write_row(const uchar * buf); - int ha_update_row(const uchar * old_data, const uchar * new_data); - int ha_delete_row(const uchar * buf); - void ha_release_auto_increment(); - - bool keyread_enabled() { return keyread < MAX_KEY; } - int ha_start_keyread(uint idx) - { - int res= keyread_enabled() ? 0 : extra_opt(HA_EXTRA_KEYREAD, idx); - keyread= idx; - return res; - } - int ha_end_keyread() - { - if (!keyread_enabled()) - return 0; - keyread= MAX_KEY; - return extra(HA_EXTRA_NO_KEYREAD); - } - - int check_collation_compatibility(); - int ha_check_for_upgrade(HA_CHECK_OPT *check_opt); - /** to be actually called to get 'check()' functionality*/ - int ha_check(THD *thd, HA_CHECK_OPT *check_opt); - int ha_repair(THD* thd, HA_CHECK_OPT* check_opt); - void ha_start_bulk_insert(ha_rows rows, uint flags= 0) - { - DBUG_ENTER("handler::ha_start_bulk_insert"); - estimation_rows_to_insert= rows; - bzero(©_info,sizeof(copy_info)); - start_bulk_insert(rows, flags); - DBUG_VOID_RETURN; - } - int ha_end_bulk_insert(); - int ha_bulk_update_row(const uchar *old_data, const uchar *new_data, - ha_rows *dup_key_found); - int ha_delete_all_rows(); - int ha_truncate(); - int ha_reset_auto_increment(ulonglong value); - int ha_optimize(THD* thd, HA_CHECK_OPT* check_opt); - int ha_analyze(THD* thd, HA_CHECK_OPT* check_opt); - bool ha_check_and_repair(THD *thd); - int ha_disable_indexes(uint mode); - int ha_enable_indexes(uint mode); - int ha_discard_or_import_tablespace(my_bool discard); - int ha_rename_table(const char *from, const char *to); - void ha_drop_table(const char *name); - - int ha_create(const char *name, TABLE *form, HA_CREATE_INFO *info); - - int ha_create_partitioning_metadata(const char *name, const char *old_name, - chf_create_flags action_flag); - - int ha_change_partitions(HA_CREATE_INFO *create_info, - const char *path, - ulonglong * const copied, - ulonglong * const deleted, - const uchar *pack_frm_data, - size_t pack_frm_len); - int ha_drop_partitions(const char *path); - int ha_rename_partitions(const char *path); - - void adjust_next_insert_id_after_explicit_value(ulonglong nr); - int update_auto_increment(); - virtual void print_error(int error, myf errflag); - virtual bool get_error_message(int error, String *buf); - uint get_dup_key(int error); - /** - Retrieves the names of the table and the key for which there was a - duplicate entry in the case of HA_ERR_FOREIGN_DUPLICATE_KEY. - - If any of the table or key name is not available this method will return - false and will not change any of child_table_name or child_key_name. - - @param child_table_name[out] Table name - @param child_table_name_len[in] Table name buffer size - @param child_key_name[out] Key name - @param child_key_name_len[in] Key name buffer size - - @retval true table and key names were available - and were written into the corresponding - out parameters. - @retval false table and key names were not available, - the out parameters were not touched. - */ - virtual bool get_foreign_dup_key(char *child_table_name, - uint child_table_name_len, - char *child_key_name, - uint child_key_name_len) - { DBUG_ASSERT(false); return(false); } - void reset_statistics() - { - rows_read= rows_changed= rows_tmp_read= 0; - bzero(index_rows_read, sizeof(index_rows_read)); - bzero(©_info, sizeof(copy_info)); - } - virtual void reset_copy_info() {} - void ha_reset_copy_info() - { - bzero(©_info, sizeof(copy_info)); - reset_copy_info(); - } - virtual void change_table_ptr(TABLE *table_arg, TABLE_SHARE *share) - { - table= table_arg; - table_share= share; - reset_statistics(); - } - virtual double scan_time() - { - return ((ulonglong2double(stats.data_file_length) / stats.block_size + 2) * - avg_io_cost()); - } - - virtual double key_scan_time(uint index) - { - return keyread_time(index, 1, records()); - } - - virtual double avg_io_cost() - { - return 1.0; - } - - /** - The cost of reading a set of ranges from the table using an index - to access it. - - @param index The index number. - @param ranges The number of ranges to be read. If 0, it means that - we calculate separately the cost of reading the key. - @param rows Total number of rows to be read. - - This method can be used to calculate the total cost of scanning a table - using an index by calling it using read_time(index, 1, table_size). - */ - virtual double read_time(uint index, uint ranges, ha_rows rows) - { return rows2double(ranges+rows); } - - /** - Calculate cost of 'keyread' scan for given index and number of records. - - @param index index to read - @param ranges #of ranges to read - @param rows #of records to read - */ - virtual double keyread_time(uint index, uint ranges, ha_rows rows); - - virtual const key_map *keys_to_use_for_scanning() { return &key_map_empty; } - - /* - True if changes to the table is persistent (if there are no rollback) - This is used to decide: - - If the table is stored in the transaction or non transactional binary - log - - How things are tracked in trx and in add_changed_table(). - - If we can combine several statements under one commit in the binary log. - */ - bool has_transactions() - { - return ((ha_table_flags() & (HA_NO_TRANSACTIONS | HA_PERSISTENT_TABLE)) - == 0); - } - /* - True if table has both transactions and rollback. This is used to decide - if we should write the changes to the binary log. If this is true, - we don't have to write failed statements to the log as they can be - rolled back. - */ - bool has_transactions_and_rollback() - { - return has_transactions() && has_rollback(); - } - /* - True if the underlaying table support transactions and rollback - */ - bool has_transaction_manager() - { - return ((ha_table_flags() & HA_NO_TRANSACTIONS) == 0 && has_rollback()); - } - - /* - True if table has rollback. Used to check if an update on the table - can be killed fast. - */ - - bool has_rollback() - { - return ((ht->flags & HTON_NO_ROLLBACK) == 0); - } - - /** - This method is used to analyse the error to see whether the error - is ignorable or not, certain handlers can have more error that are - ignorable than others. E.g. the partition handler can get inserts - into a range where there is no partition and this is an ignorable - error. - HA_ERR_FOUND_DUP_UNIQUE is a special case in MyISAM that means the - same thing as HA_ERR_FOUND_DUP_KEY but can in some cases lead to - a slightly different error message. - */ - virtual bool is_fatal_error(int error, uint flags) - { - if (!error || - ((flags & HA_CHECK_DUP_KEY) && - (error == HA_ERR_FOUND_DUPP_KEY || - error == HA_ERR_FOUND_DUPP_UNIQUE)) || - error == HA_ERR_AUTOINC_ERANGE || - ((flags & HA_CHECK_FK_ERROR) && - (error == HA_ERR_ROW_IS_REFERENCED || - error == HA_ERR_NO_REFERENCED_ROW))) - return FALSE; - return TRUE; - } - - /** - Number of rows in table. It will only be called if - (table_flags() & (HA_HAS_RECORDS | HA_STATS_RECORDS_IS_EXACT)) != 0 - */ - virtual int pre_records() { return 0; } - virtual ha_rows records() { return stats.records; } - /** - Return upper bound of current number of records in the table - (max. of how many records one will retrieve when doing a full table scan) - If upper bound is not known, HA_POS_ERROR should be returned as a max - possible upper bound. - */ - virtual ha_rows estimate_rows_upper_bound() - { return stats.records+EXTRA_RECORDS; } - - /** - Get the row type from the storage engine. If this method returns - ROW_TYPE_NOT_USED, the information in HA_CREATE_INFO should be used. - */ - virtual enum row_type get_row_type() const { return ROW_TYPE_NOT_USED; } - - virtual const char *index_type(uint key_number) { DBUG_ASSERT(0); return "";} - - - /** - Signal that the table->read_set and table->write_set table maps changed - The handler is allowed to set additional bits in the above map in this - call. Normally the handler should ignore all calls until we have done - a ha_rnd_init() or ha_index_init(), write_row(), update_row or delete_row() - as there may be several calls to this routine. - */ - virtual void column_bitmaps_signal(); - /* - We have to check for inited as some engines, like innodb, sets - active_index during table scan. - */ - uint get_index(void) const - { return inited == INDEX ? active_index : MAX_KEY; } - int ha_close(void); - - /** - @retval 0 Bulk update used by handler - @retval 1 Bulk update not used, normal operation used - */ - virtual bool start_bulk_update() { return 1; } - /** - @retval 0 Bulk delete used by handler - @retval 1 Bulk delete not used, normal operation used - */ - virtual bool start_bulk_delete() { return 1; } - /** - After this call all outstanding updates must be performed. The number - of duplicate key errors are reported in the duplicate key parameter. - It is allowed to continue to the batched update after this call, the - handler has to wait until end_bulk_update with changing state. - - @param dup_key_found Number of duplicate keys found - - @retval 0 Success - @retval >0 Error code - */ - virtual int exec_bulk_update(ha_rows *dup_key_found) - { - DBUG_ASSERT(FALSE); - return HA_ERR_WRONG_COMMAND; - } - /** - Perform any needed clean-up, no outstanding updates are there at the - moment. - */ - virtual int end_bulk_update() { return 0; } - /** - Execute all outstanding deletes and close down the bulk delete. - - @retval 0 Success - @retval >0 Error code - */ - virtual int end_bulk_delete() - { - DBUG_ASSERT(FALSE); - return HA_ERR_WRONG_COMMAND; - } - virtual int pre_index_read_map(const uchar *key, - key_part_map keypart_map, - enum ha_rkey_function find_flag, - bool use_parallel) - { return 0; } - virtual int pre_index_first(bool use_parallel) - { return 0; } - virtual int pre_index_last(bool use_parallel) - { return 0; } - virtual int pre_index_read_last_map(const uchar *key, - key_part_map keypart_map, - bool use_parallel) - { return 0; } -/* - virtual int pre_read_multi_range_first(KEY_MULTI_RANGE **found_range_p, - KEY_MULTI_RANGE *ranges, - uint range_count, - bool sorted, HANDLER_BUFFER *buffer, - bool use_parallel); -*/ - virtual int pre_multi_range_read_next(bool use_parallel) - { return 0; } - virtual int pre_read_range_first(const key_range *start_key, - const key_range *end_key, - bool eq_range, bool sorted, - bool use_parallel) - { return 0; } - virtual int pre_ft_read(bool use_parallel) - { return 0; } - virtual int pre_rnd_next(bool use_parallel) - { return 0; } - int ha_pre_rnd_init(bool scan) - { - int result; - DBUG_ENTER("ha_pre_rnd_init"); - DBUG_ASSERT(pre_inited==NONE || (pre_inited==RND && scan)); - pre_inited= (result= pre_rnd_init(scan)) ? NONE: RND; - DBUG_RETURN(result); - } - int ha_pre_rnd_end() - { - DBUG_ENTER("ha_pre_rnd_end"); - DBUG_ASSERT(pre_inited==RND); - pre_inited=NONE; - DBUG_RETURN(pre_rnd_end()); - } - virtual int pre_rnd_init(bool scan) { return 0; } - virtual int pre_rnd_end() { return 0; } - virtual int pre_index_init(uint idx, bool sorted) { return 0; } - virtual int pre_index_end() { return 0; } - int ha_pre_index_init(uint idx, bool sorted) - { - int result; - DBUG_ENTER("ha_pre_index_init"); - DBUG_ASSERT(pre_inited==NONE); - if (!(result= pre_index_init(idx, sorted))) - pre_inited=INDEX; - DBUG_RETURN(result); - } - int ha_pre_index_end() - { - DBUG_ENTER("ha_pre_index_end"); - DBUG_ASSERT(pre_inited==INDEX); - pre_inited=NONE; - DBUG_RETURN(pre_index_end()); - } - int ha_pre_index_or_rnd_end() - { - return (pre_inited == INDEX ? - ha_pre_index_end() : - pre_inited == RND ? ha_pre_rnd_end() : 0 ); - } - virtual bool vers_can_native(THD *thd) - { - return ht->flags & HTON_NATIVE_SYS_VERSIONING; - } - - /** - @brief - Positions an index cursor to the index specified in the - handle. Fetches the row if available. If the key value is null, - begin at the first key of the index. - */ -protected: - virtual int index_read_map(uchar * buf, const uchar * key, - key_part_map keypart_map, - enum ha_rkey_function find_flag) - { - uint key_len= calculate_key_len(table, active_index, key, keypart_map); - return index_read(buf, key, key_len, find_flag); - } - /** - @brief - Positions an index cursor to the index specified in the - handle. Fetches the row if available. If the key value is null, - begin at the first key of the index. - */ - virtual int index_read_idx_map(uchar * buf, uint index, const uchar * key, - key_part_map keypart_map, - enum ha_rkey_function find_flag); - virtual int index_next(uchar * buf) - { return HA_ERR_WRONG_COMMAND; } - virtual int index_prev(uchar * buf) - { return HA_ERR_WRONG_COMMAND; } - virtual int index_first(uchar * buf) - { return HA_ERR_WRONG_COMMAND; } - virtual int index_last(uchar * buf) - { return HA_ERR_WRONG_COMMAND; } - virtual int index_next_same(uchar *buf, const uchar *key, uint keylen); - /** - @brief - The following functions works like index_read, but it find the last - row with the current key value or prefix. - @returns @see index_read_map(). - */ - virtual int index_read_last_map(uchar * buf, const uchar * key, - key_part_map keypart_map) - { - uint key_len= calculate_key_len(table, active_index, key, keypart_map); - return index_read_last(buf, key, key_len); - } - virtual int close(void)=0; - inline void update_rows_read() - { - if (likely(!internal_tmp_table)) - rows_read++; - else - rows_tmp_read++; - } - inline void update_index_statistics() - { - index_rows_read[active_index]++; - update_rows_read(); - } -public: - - int ha_index_read_map(uchar * buf, const uchar * key, - key_part_map keypart_map, - enum ha_rkey_function find_flag); - int ha_index_read_idx_map(uchar * buf, uint index, const uchar * key, - key_part_map keypart_map, - enum ha_rkey_function find_flag); - int ha_index_next(uchar * buf); - int ha_index_prev(uchar * buf); - int ha_index_first(uchar * buf); - int ha_index_last(uchar * buf); - int ha_index_next_same(uchar *buf, const uchar *key, uint keylen); - /* - TODO: should we make for those functions non-virtual ha_func_name wrappers, - too? - */ - virtual ha_rows multi_range_read_info_const(uint keyno, RANGE_SEQ_IF *seq, - void *seq_init_param, - uint n_ranges, uint *bufsz, - uint *mrr_mode, - Cost_estimate *cost); - virtual ha_rows multi_range_read_info(uint keyno, uint n_ranges, uint keys, - uint key_parts, uint *bufsz, - uint *mrr_mode, Cost_estimate *cost); - virtual int multi_range_read_init(RANGE_SEQ_IF *seq, void *seq_init_param, - uint n_ranges, uint mrr_mode, - HANDLER_BUFFER *buf); - virtual int multi_range_read_next(range_id_t *range_info); - /* - Return string representation of the MRR plan. - - This is intended to be used for EXPLAIN, via the following scenario: - 1. SQL layer calls handler->multi_range_read_info(). - 1.1. Storage engine figures out whether it will use some non-default - MRR strategy, sets appropritate bits in *mrr_mode, and returns - control to SQL layer - 2. SQL layer remembers the returned mrr_mode - 3. SQL layer compares various options and choses the final query plan. As - a part of that, it makes a choice of whether to use the MRR strategy - picked in 1.1 - 4. EXPLAIN code converts the query plan to its text representation. If MRR - strategy is part of the plan, it calls - multi_range_read_explain_info(mrr_mode) to get a text representation of - the picked MRR strategy. - - @param mrr_mode Mode which was returned by multi_range_read_info[_const] - @param str INOUT string to be printed for EXPLAIN - @param str_end End of the string buffer. The function is free to put the - string into [str..str_end] memory range. - */ - virtual int multi_range_read_explain_info(uint mrr_mode, char *str, - size_t size) - { return 0; } - - virtual int read_range_first(const key_range *start_key, - const key_range *end_key, - bool eq_range, bool sorted); - virtual int read_range_next(); - void set_end_range(const key_range *end_key); - int compare_key(key_range *range); - int compare_key2(key_range *range) const; - virtual int ft_init() { return HA_ERR_WRONG_COMMAND; } - virtual int pre_ft_init() { return HA_ERR_WRONG_COMMAND; } - virtual void ft_end() {} - virtual int pre_ft_end() { return 0; } - virtual FT_INFO *ft_init_ext(uint flags, uint inx,String *key) - { return NULL; } -public: - virtual int ft_read(uchar *buf) { return HA_ERR_WRONG_COMMAND; } - virtual int rnd_next(uchar *buf)=0; - virtual int rnd_pos(uchar * buf, uchar *pos)=0; - /** - This function only works for handlers having - HA_PRIMARY_KEY_REQUIRED_FOR_POSITION set. - It will return the row with the PK given in the record argument. - */ - virtual int rnd_pos_by_record(uchar *record) - { - int error; - DBUG_ASSERT(table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_POSITION); - - error = ha_rnd_init(false); - if (error != 0) - return error; - - position(record); - error = ha_rnd_pos(record, ref); - ha_rnd_end(); - return error; - } - virtual int read_first_row(uchar *buf, uint primary_key); -public: - - /* Same as above, but with statistics */ - inline int ha_ft_read(uchar *buf); - inline void ha_ft_end() { ft_end(); ft_handler=NULL; } - int ha_rnd_next(uchar *buf); - int ha_rnd_pos(uchar *buf, uchar *pos); - inline int ha_rnd_pos_by_record(uchar *buf); - inline int ha_read_first_row(uchar *buf, uint primary_key); - - /** - The following 3 function is only needed for tables that may be - internal temporary tables during joins. - */ - virtual int remember_rnd_pos() - { return HA_ERR_WRONG_COMMAND; } - virtual int restart_rnd_next(uchar *buf) - { return HA_ERR_WRONG_COMMAND; } - virtual int rnd_same(uchar *buf, uint inx) - { return HA_ERR_WRONG_COMMAND; } - - virtual ha_rows records_in_range(uint inx, const key_range *min_key, - const key_range *max_key, - page_range *res) - { return (ha_rows) 10; } - /* - If HA_PRIMARY_KEY_REQUIRED_FOR_POSITION is set, then it sets ref - (reference to the row, aka position, with the primary key given in - the record). - Otherwise it set ref to the current row. - */ - virtual void position(const uchar *record)=0; - virtual int info(uint)=0; // see my_base.h for full description - virtual void get_dynamic_partition_info(PARTITION_STATS *stat_info, - uint part_id); - virtual void set_partitions_to_open(List *partition_names) {} - virtual bool check_if_updates_are_ignored(const char *op) const; - virtual int change_partitions_to_open(List *partition_names) - { return 0; } - virtual int extra(enum ha_extra_function operation) - { return 0; } - virtual int extra_opt(enum ha_extra_function operation, ulong arg) - { return extra(operation); } - - /** - In an UPDATE or DELETE, if the row under the cursor was locked by another - transaction, and the engine used an optimistic read of the last - committed row value under the cursor, then the engine returns 1 from this - function. MySQL must NOT try to update this optimistic value. If the - optimistic value does not match the WHERE condition, MySQL can decide to - skip over this row. Currently only works for InnoDB. This can be used to - avoid unnecessary lock waits. - - If this method returns nonzero, it will also signal the storage - engine that the next read will be a locking re-read of the row. - */ - bool ha_was_semi_consistent_read(); - virtual bool was_semi_consistent_read() { return 0; } - /** - Tell the engine whether it should avoid unnecessary lock waits. - If yes, in an UPDATE or DELETE, if the row under the cursor was locked - by another transaction, the engine may try an optimistic read of - the last committed row value under the cursor. - */ - virtual void try_semi_consistent_read(bool) {} - virtual void unlock_row() {} - virtual int start_stmt(THD *thd, thr_lock_type lock_type) {return 0;} - virtual bool need_info_for_auto_inc() { return 0; } - virtual bool can_use_for_auto_inc_init() { return 1; } - virtual void get_auto_increment(ulonglong offset, ulonglong increment, - ulonglong nb_desired_values, - ulonglong *first_value, - ulonglong *nb_reserved_values); - void set_next_insert_id(ulonglong id) - { - DBUG_PRINT("info",("auto_increment: next value %lu", (ulong)id)); - next_insert_id= id; - } - virtual void restore_auto_increment(ulonglong prev_insert_id) - { - /* - Insertion of a row failed, re-use the lastly generated auto_increment - id, for the next row. This is achieved by resetting next_insert_id to - what it was before the failed insertion (that old value is provided by - the caller). If that value was 0, it was the first row of the INSERT; - then if insert_id_for_cur_row contains 0 it means no id was generated - for this first row, so no id was generated since the INSERT started, so - we should set next_insert_id to 0; if insert_id_for_cur_row is not 0, it - is the generated id of the first and failed row, so we use it. - */ - next_insert_id= (prev_insert_id > 0) ? prev_insert_id : - insert_id_for_cur_row; - } - - /** Store and restore next_insert_id over duplicate key errors. */ - virtual void store_auto_increment() - { - m_prev_insert_id= next_insert_id; - } - virtual void restore_auto_increment() - { - restore_auto_increment(m_prev_insert_id); - } - - virtual void update_create_info(HA_CREATE_INFO *create_info) {} - int check_old_types(); - virtual int assign_to_keycache(THD* thd, HA_CHECK_OPT* check_opt) - { return HA_ADMIN_NOT_IMPLEMENTED; } - virtual int preload_keys(THD* thd, HA_CHECK_OPT* check_opt) - { return HA_ADMIN_NOT_IMPLEMENTED; } - /* end of the list of admin commands */ - - virtual int indexes_are_disabled(void) {return 0;} - virtual char *update_table_comment(const char * comment) - { return (char*) comment;} - virtual void append_create_info(String *packet) {} - /** - If index == MAX_KEY then a check for table is made and if index < - MAX_KEY then a check is made if the table has foreign keys and if - a foreign key uses this index (and thus the index cannot be dropped). - - @param index Index to check if foreign key uses it - - @retval TRUE Foreign key defined on table or index - @retval FALSE No foreign key defined - */ - virtual bool is_fk_defined_on_table_or_index(uint index) - { return FALSE; } - virtual char* get_foreign_key_create_info() - { return(NULL);} /* gets foreign key create string from InnoDB */ - /** - Used in ALTER TABLE to check if changing storage engine is allowed. - - @note Called without holding thr_lock.c lock. - - @retval true Changing storage engine is allowed. - @retval false Changing storage engine not allowed. - */ - virtual bool can_switch_engines() { return true; } - virtual int can_continue_handler_scan() { return 0; } - /** - Get the list of foreign keys in this table. - - @remark Returns the set of foreign keys where this table is the - dependent or child table. - - @param thd The thread handle. - @param f_key_list[out] The list of foreign keys. - - @return The handler error code or zero for success. - */ - virtual int - get_foreign_key_list(THD *thd, List *f_key_list) - { return 0; } - /** - Get the list of foreign keys referencing this table. - - @remark Returns the set of foreign keys where this table is the - referenced or parent table. - - @param thd The thread handle. - @param f_key_list[out] The list of foreign keys. - - @return The handler error code or zero for success. - */ - virtual int - get_parent_foreign_key_list(THD *thd, List *f_key_list) - { return 0; } - virtual uint referenced_by_foreign_key() { return 0;} - virtual void init_table_handle_for_HANDLER() - { return; } /* prepare InnoDB for HANDLER */ - virtual void free_foreign_key_create_info(char* str) {} - /** The following can be called without an open handler */ - const char *table_type() const { return hton_name(ht)->str; } - const char **bas_ext() const { return ht->tablefile_extensions; } - - virtual int get_default_no_partitions(HA_CREATE_INFO *create_info) - { return 1;} - virtual void set_auto_partitions(partition_info *part_info) { return; } - virtual bool get_no_parts(const char *name, - uint *no_parts) - { - *no_parts= 0; - return 0; - } - virtual void set_part_info(partition_info *part_info) {return;} - virtual void return_record_by_parent() { return; } - - /* Information about index. Both index and part starts from 0 */ - virtual ulong index_flags(uint idx, uint part, bool all_parts) const =0; - - uint max_record_length() const - { return MY_MIN(HA_MAX_REC_LENGTH, max_supported_record_length()); } - uint max_keys() const - { return MY_MIN(MAX_KEY, max_supported_keys()); } - uint max_key_parts() const - { return MY_MIN(MAX_REF_PARTS, max_supported_key_parts()); } - uint max_key_length() const - { return MY_MIN(MAX_DATA_LENGTH_FOR_KEY, max_supported_key_length()); } - uint max_key_part_length() const - { return MY_MIN(MAX_DATA_LENGTH_FOR_KEY, max_supported_key_part_length()); } - - virtual uint max_supported_record_length() const { return HA_MAX_REC_LENGTH; } - virtual uint max_supported_keys() const { return 0; } - virtual uint max_supported_key_parts() const { return MAX_REF_PARTS; } - virtual uint max_supported_key_length() const { return MAX_DATA_LENGTH_FOR_KEY; } - virtual uint max_supported_key_part_length() const { return 255; } - virtual uint min_record_length(uint options) const { return 1; } - - virtual int pre_calculate_checksum() { return 0; } - virtual int calculate_checksum(); - virtual bool is_crashed() const { return 0; } - virtual bool auto_repair(int error) const { return 0; } - - void update_global_table_stats(); - void update_global_index_stats(); - - /** - @note lock_count() can return > 1 if the table is MERGE or partitioned. - */ - virtual uint lock_count(void) const { return 1; } - /** - Is not invoked for non-transactional temporary tables. - - @note store_lock() can return more than one lock if the table is MERGE - or partitioned. - - @note that one can NOT rely on table->in_use in store_lock(). It may - refer to a different thread if called from mysql_lock_abort_for_thread(). - - @note If the table is MERGE, store_lock() can return less locks - than lock_count() claimed. This can happen when the MERGE children - are not attached when this is called from another thread. - */ - virtual THR_LOCK_DATA **store_lock(THD *thd, - THR_LOCK_DATA **to, - enum thr_lock_type lock_type)=0; - - /** Type of table for caching query */ - virtual uint8 table_cache_type() { return HA_CACHE_TBL_NONTRANSACT; } - - - /** - @brief Register a named table with a call back function to the query cache. - - @param thd The thread handle - @param table_key A pointer to the table name in the table cache - @param key_length The length of the table name - @param[out] engine_callback The pointer to the storage engine call back - function - @param[out] engine_data Storage engine specific data which could be - anything - - This method offers the storage engine, the possibility to store a reference - to a table name which is going to be used with query cache. - The method is called each time a statement is written to the cache and can - be used to verify if a specific statement is cacheable. It also offers - the possibility to register a generic (but static) call back function which - is called each time a statement is matched against the query cache. - - @note If engine_data supplied with this function is different from - engine_data supplied with the callback function, and the callback returns - FALSE, a table invalidation on the current table will occur. - - @return Upon success the engine_callback will point to the storage engine - call back function, if any, and engine_data will point to any storage - engine data used in the specific implementation. - @retval TRUE Success - @retval FALSE The specified table or current statement should not be - cached - */ - - virtual my_bool register_query_cache_table(THD *thd, const char *table_key, - uint key_length, - qc_engine_callback *callback, - ulonglong *engine_data) - { - *callback= 0; - return TRUE; - } - - /* - Count tables invisible from all tables list on which current one built - (like myisammrg and partitioned tables) - - tables_type mask for the tables should be added herdde - - returns number of such tables - */ - - virtual uint count_query_cache_dependant_tables(uint8 *tables_type - __attribute__((unused))) - { - return 0; - } - - /* - register tables invisible from all tables list on which current one built - (like myisammrg and partitioned tables). - - @note they should be counted by method above - - cache Query cache pointer - block Query cache block to write the table - n Number of the table - - @retval FALSE - OK - @retval TRUE - Error - */ - - virtual my_bool - register_query_cache_dependant_tables(THD *thd - __attribute__((unused)), - Query_cache *cache - __attribute__((unused)), - Query_cache_block_table **block - __attribute__((unused)), - uint *n __attribute__((unused))) - { - return FALSE; - } - - /* - Check if the key is a clustering key - - - Data is stored together with the primary key (no secondary lookup - needed to find the row data). The optimizer uses this to find out - the cost of fetching data. - - Note that in many cases a clustered key is also a reference key. - This means that: - - - The key is part of each secondary key and is used - to find the row data in the primary index when reading trough - secondary indexes. - - When doing a HA_KEYREAD_ONLY we get also all the primary key parts - into the row. This is critical property used by index_merge. - - All the above is usually true for engines that store the row - data in the primary key index (e.g. in a b-tree), and use the key - key value as a position(). InnoDB is an example of such an engine. - - For a clustered (primary) key, the following should also hold: - index_flags() should contain HA_CLUSTERED_INDEX - table_flags() should contain HA_TABLE_SCAN_ON_INDEX - - For a reference key the following should also hold: - table_flags() should contain HA_PRIMARY_KEY_IS_READ_INDEX. - - @retval TRUE yes - @retval FALSE No. - */ - - /* The following code is for primary keys */ - bool pk_is_clustering_key(uint index) const - { - /* - We have to check for MAX_INDEX as table->s->primary_key can be - MAX_KEY in the case where there is no primary key. - */ - return index != MAX_KEY && is_clustering_key(index); - } - /* Same as before but for other keys, in which case we can skip the check */ - bool is_clustering_key(uint index) const - { - DBUG_ASSERT(index != MAX_KEY); - return (index_flags(index, 0, 1) & HA_CLUSTERED_INDEX); - } - - virtual int cmp_ref(const uchar *ref1, const uchar *ref2) - { - return memcmp(ref1, ref2, ref_length); - } - - /* - Condition pushdown to storage engines - */ - - /** - Push condition down to the table handler. - - @param cond Condition to be pushed. The condition tree must not be - modified by the by the caller. - - @return - The 'remainder' condition that caller must use to filter out records. - NULL means the handler will not return rows that do not match the - passed condition. - - @note - The pushed conditions form a stack (from which one can remove the - last pushed condition using cond_pop). - The table handler filters out rows using (pushed_cond1 AND pushed_cond2 - AND ... AND pushed_condN) - or less restrictive condition, depending on handler's capabilities. - - handler->ha_reset() call empties the condition stack. - Calls to rnd_init/rnd_end, index_init/index_end etc do not affect the - condition stack. - */ - virtual const COND *cond_push(const COND *cond) { return cond; }; - /** - Pop the top condition from the condition stack of the handler instance. - - Pops the top if condition stack, if stack is not empty. - */ - virtual void cond_pop() { return; }; - - /** - Push metadata for the current operation down to the table handler. - */ - virtual int info_push(uint info_type, void *info) { return 0; }; - - /** - Push down an index condition to the handler. - - The server will use this method to push down a condition it wants - the handler to evaluate when retrieving records using a specified - index. The pushed index condition will only refer to fields from - this handler that is contained in the index (but it may also refer - to fields in other handlers). Before the handler evaluates the - condition it must read the content of the index entry into the - record buffer. - - The handler is free to decide if and how much of the condition it - will take responsibility for evaluating. Based on this evaluation - it should return the part of the condition it will not evaluate. - If it decides to evaluate the entire condition it should return - NULL. If it decides not to evaluate any part of the condition it - should return a pointer to the same condition as given as argument. - - @param keyno the index number to evaluate the condition on - @param idx_cond the condition to be evaluated by the handler - - @return The part of the pushed condition that the handler decides - not to evaluate - */ - virtual Item *idx_cond_push(uint keyno, Item* idx_cond) { return idx_cond; } - - /** Reset information about pushed index conditions */ - virtual void cancel_pushed_idx_cond() - { - pushed_idx_cond= NULL; - pushed_idx_cond_keyno= MAX_KEY; - in_range_check_pushed_down= false; - } - - virtual void cancel_pushed_rowid_filter() - { - pushed_rowid_filter= NULL; - rowid_filter_is_active= false; - } - - virtual bool rowid_filter_push(Rowid_filter *rowid_filter) { return true; } - - /* Needed for partition / spider */ - virtual TABLE_LIST *get_next_global_for_child() { return NULL; } - - /** - Part of old, deprecated in-place ALTER API. - */ - virtual bool check_if_incompatible_data(HA_CREATE_INFO *create_info, - uint table_changes) - { return COMPATIBLE_DATA_NO; } - - /* On-line/in-place ALTER TABLE interface. */ - - /* - Here is an outline of on-line/in-place ALTER TABLE execution through - this interface. - - Phase 1 : Initialization - ======================== - During this phase we determine which algorithm should be used - for execution of ALTER TABLE and what level concurrency it will - require. - - *) This phase starts by opening the table and preparing description - of the new version of the table. - *) Then we check if it is impossible even in theory to carry out - this ALTER TABLE using the in-place algorithm. For example, because - we need to change storage engine or the user has explicitly requested - usage of the "copy" algorithm. - *) If in-place ALTER TABLE is theoretically possible, we continue - by compiling differences between old and new versions of the table - in the form of HA_ALTER_FLAGS bitmap. We also build a few - auxiliary structures describing requested changes and store - all these data in the Alter_inplace_info object. - *) Then the handler::check_if_supported_inplace_alter() method is called - in order to find if the storage engine can carry out changes requested - by this ALTER TABLE using the in-place algorithm. To determine this, - the engine can rely on data in HA_ALTER_FLAGS/Alter_inplace_info - passed to it as well as on its own checks. If the in-place algorithm - can be used for this ALTER TABLE, the level of required concurrency for - its execution is also returned. - If any errors occur during the handler call, ALTER TABLE is aborted - and no further handler functions are called. - *) Locking requirements of the in-place algorithm are compared to any - concurrency requirements specified by user. If there is a conflict - between them, we either switch to the copy algorithm or emit an error. - - Phase 2 : Execution - =================== - - In this phase the operations are executed. - - *) As the first step, we acquire a lock corresponding to the concurrency - level which was returned by handler::check_if_supported_inplace_alter() - and requested by the user. This lock is held for most of the - duration of in-place ALTER (if HA_ALTER_INPLACE_COPY_LOCK - or HA_ALTER_INPLACE_COPY_NO_LOCK were returned we acquire an - exclusive lock for duration of the next step only). - *) After that we call handler::ha_prepare_inplace_alter_table() to give the - storage engine a chance to update its internal structures with a higher - lock level than the one that will be used for the main step of algorithm. - After that we downgrade the lock if it is necessary. - *) After that, the main step of this phase and algorithm is executed. - We call the handler::ha_inplace_alter_table() method, which carries out the - changes requested by ALTER TABLE but does not makes them visible to other - connections yet. - *) We ensure that no other connection uses the table by upgrading our - lock on it to exclusive. - *) a) If the previous step succeeds, handler::ha_commit_inplace_alter_table() is - called to allow the storage engine to do any final updates to its structures, - to make all earlier changes durable and visible to other connections. - b) If we have failed to upgrade lock or any errors have occurred during the - handler functions calls (including commit), we call - handler::ha_commit_inplace_alter_table() - to rollback all changes which were done during previous steps. - - Phase 3 : Final - =============== - - In this phase we: - - *) Update SQL-layer data-dictionary by installing .FRM file for the new version - of the table. - *) Inform the storage engine about this change by calling the - hton::notify_table_changed() - *) Destroy the Alter_inplace_info and handler_ctx objects. - - */ - - /** - Check if a storage engine supports a particular alter table in-place - - @param altered_table TABLE object for new version of table. - @param ha_alter_info Structure describing changes to be done - by ALTER TABLE and holding data used - during in-place alter. - - @retval HA_ALTER_ERROR Unexpected error. - @retval HA_ALTER_INPLACE_NOT_SUPPORTED Not supported, must use copy. - @retval HA_ALTER_INPLACE_EXCLUSIVE_LOCK Supported, but requires X lock. - @retval HA_ALTER_INPLACE_COPY_LOCK - Supported, but requires SNW lock - during main phase. Prepare phase - requires X lock. - @retval HA_ALTER_INPLACE_SHARED_LOCK Supported, but requires SNW lock. - @retval HA_ALTER_INPLACE_COPY_NO_LOCK - Supported, concurrent reads/writes - allowed. However, prepare phase - requires X lock. - @retval HA_ALTER_INPLACE_NO_LOCK Supported, concurrent - reads/writes allowed. - - @note The default implementation uses the old in-place ALTER API - to determine if the storage engine supports in-place ALTER or not. - - @note Called without holding thr_lock.c lock. - */ - virtual enum_alter_inplace_result - check_if_supported_inplace_alter(TABLE *altered_table, - Alter_inplace_info *ha_alter_info); - - - /** - Public functions wrapping the actual handler call. - @see prepare_inplace_alter_table() - */ - bool ha_prepare_inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info); - - - /** - Public function wrapping the actual handler call. - @see inplace_alter_table() - */ - bool ha_inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info) - { - return inplace_alter_table(altered_table, ha_alter_info); - } - - - /** - Public function wrapping the actual handler call. - Allows us to enforce asserts regardless of handler implementation. - @see commit_inplace_alter_table() - */ - bool ha_commit_inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info, - bool commit); - - -protected: - /** - Allows the storage engine to update internal structures with concurrent - writes blocked. If check_if_supported_inplace_alter() returns - HA_ALTER_INPLACE_COPY_NO_LOCK or HA_ALTER_INPLACE_COPY_LOCK, - this function is called with exclusive lock otherwise the same level - of locking as for inplace_alter_table() will be used. - - @note Storage engines are responsible for reporting any errors by - calling my_error()/print_error() - - @note If this function reports error, commit_inplace_alter_table() - will be called with commit= false. - - @note For partitioning, failing to prepare one partition, means that - commit_inplace_alter_table() will be called to roll back changes for - all partitions. This means that commit_inplace_alter_table() might be - called without prepare_inplace_alter_table() having been called first - for a given partition. - - @param altered_table TABLE object for new version of table. - @param ha_alter_info Structure describing changes to be done - by ALTER TABLE and holding data used - during in-place alter. - - @retval true Error - @retval false Success - */ - virtual bool prepare_inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info) - { return false; } - - - /** - Alter the table structure in-place with operations specified using HA_ALTER_FLAGS - and Alter_inplace_info. The level of concurrency allowed during this - operation depends on the return value from check_if_supported_inplace_alter(). - - @note Storage engines are responsible for reporting any errors by - calling my_error()/print_error() - - @note If this function reports error, commit_inplace_alter_table() - will be called with commit= false. - - @param altered_table TABLE object for new version of table. - @param ha_alter_info Structure describing changes to be done - by ALTER TABLE and holding data used - during in-place alter. - - @retval true Error - @retval false Success - */ - virtual bool inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info) - { return false; } - - - /** - Commit or rollback the changes made during prepare_inplace_alter_table() - and inplace_alter_table() inside the storage engine. - Note that in case of rollback the allowed level of concurrency during - this operation will be the same as for inplace_alter_table() and thus - might be higher than during prepare_inplace_alter_table(). (For example, - concurrent writes were blocked during prepare, but might not be during - rollback). - - @note Storage engines are responsible for reporting any errors by - calling my_error()/print_error() - - @note If this function with commit= true reports error, it will be called - again with commit= false. - - @note In case of partitioning, this function might be called for rollback - without prepare_inplace_alter_table() having been called first. - Also partitioned tables sets ha_alter_info->group_commit_ctx to a NULL - terminated array of the partitions handlers and if all of them are - committed as one, then group_commit_ctx should be set to NULL to indicate - to the partitioning handler that all partitions handlers are committed. - @see prepare_inplace_alter_table(). - - @param altered_table TABLE object for new version of table. - @param ha_alter_info Structure describing changes to be done - by ALTER TABLE and holding data used - during in-place alter. - @param commit True => Commit, False => Rollback. - - @retval true Error - @retval false Success - */ - virtual bool commit_inplace_alter_table(TABLE *altered_table, - Alter_inplace_info *ha_alter_info, - bool commit) -{ - /* Nothing to commit/rollback, mark all handlers committed! */ - ha_alter_info->group_commit_ctx= NULL; - return false; -} - -public: - /* End of On-line/in-place ALTER TABLE interface. */ - - - /** - use_hidden_primary_key() is called in case of an update/delete when - (table_flags() and HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) is defined - but we don't have a primary key - */ - virtual void use_hidden_primary_key(); - virtual alter_table_operations alter_table_flags(alter_table_operations flags) - { - if (ht->alter_table_flags) - return ht->alter_table_flags(flags); - return 0; - } - - virtual LEX_CSTRING *engine_name(); - - TABLE* get_table() { return table; } - TABLE_SHARE* get_table_share() { return table_share; } -protected: - /* Service methods for use by storage engines. */ - THD *ha_thd(void) const; - - /** - Acquire the instrumented table information from a table share. - @return an instrumented table share, or NULL. - */ - PSI_table_share *ha_table_share_psi() const; - - /** - Default rename_table() and delete_table() rename/delete files with a - given name and extensions from bas_ext(). - - These methods can be overridden, but their default implementation - provide useful functionality. - */ - virtual int rename_table(const char *from, const char *to); - - -public: - /** - Delete a table in the engine. Called for base as well as temporary - tables. - */ - virtual int delete_table(const char *name); - bool check_table_binlog_row_based(); - bool prepare_for_row_logging(); - int prepare_for_insert(bool do_create); - int binlog_log_row(TABLE *table, - const uchar *before_record, - const uchar *after_record, - Log_func *log_func); - - inline void clear_cached_table_binlog_row_based_flag() - { - check_table_binlog_row_based_done= 0; - } -private: - /* Cache result to avoid extra calls */ - inline void mark_trx_read_write() - { - if (unlikely(!mark_trx_read_write_done)) - { - mark_trx_read_write_done= 1; - mark_trx_read_write_internal(); - } - } - -private: - void mark_trx_read_write_internal(); - bool check_table_binlog_row_based_internal(); - - int create_lookup_handler(); - void alloc_lookup_buffer(); - int check_duplicate_long_entries(const uchar *new_rec); - int check_duplicate_long_entries_update(const uchar *new_rec); - int check_duplicate_long_entry_key(const uchar *new_rec, uint key_no); - /** PRIMARY KEY/UNIQUE WITHOUT OVERLAPS check */ - int ha_check_overlaps(const uchar *old_data, const uchar* new_data); - -protected: - /* - These are intended to be used only by handler::ha_xxxx() functions - However, engines that implement read_range_XXX() (like MariaRocks) - or embed other engines (like ha_partition) may need to call these also - */ - inline void increment_statistics(ulong SSV::*offset) const; - inline void decrement_statistics(ulong SSV::*offset) const; - -private: - /* - Low-level primitives for storage engines. These should be - overridden by the storage engine class. To call these methods, use - the corresponding 'ha_*' method above. - */ - - virtual int open(const char *name, int mode, uint test_if_locked)=0; - /* Note: ha_index_read_idx_map() may bypass index_init() */ - virtual int index_init(uint idx, bool sorted) { return 0; } - virtual int index_end() { return 0; } - /** - rnd_init() can be called two times without rnd_end() in between - (it only makes sense if scan=1). - then the second call should prepare for the new table scan (e.g - if rnd_init allocates the cursor, second call should position it - to the start of the table, no need to deallocate and allocate it again - */ - virtual int rnd_init(bool scan)= 0; - virtual int rnd_end() { return 0; } - virtual int write_row(const uchar *buf __attribute__((unused))) - { - return HA_ERR_WRONG_COMMAND; - } - - /** - Update a single row. - - Note: If HA_ERR_FOUND_DUPP_KEY is returned, the handler must read - all columns of the row so MySQL can create an error message. If - the columns required for the error message are not read, the error - message will contain garbage. - */ - virtual int update_row(const uchar *old_data __attribute__((unused)), - const uchar *new_data __attribute__((unused))) - { - return HA_ERR_WRONG_COMMAND; - } - - /* - Optimized function for updating the first row. Only used by sequence - tables - */ - virtual int update_first_row(const uchar *new_data); - - virtual int delete_row(const uchar *buf __attribute__((unused))) - { - return HA_ERR_WRONG_COMMAND; - } - - /* Perform initialization for a direct update request */ -public: - int ha_direct_update_rows(ha_rows *update_rows, ha_rows *found_rows); - virtual int direct_update_rows_init(List *update_fields) - { - return HA_ERR_WRONG_COMMAND; - } -private: - virtual int pre_direct_update_rows_init(List *update_fields) - { - return HA_ERR_WRONG_COMMAND; - } - virtual int direct_update_rows(ha_rows *update_rows __attribute__((unused)), - ha_rows *found_rows __attribute__((unused))) - { - return HA_ERR_WRONG_COMMAND; - } - virtual int pre_direct_update_rows() - { - return HA_ERR_WRONG_COMMAND; - } - - /* Perform initialization for a direct delete request */ -public: - int ha_direct_delete_rows(ha_rows *delete_rows); - virtual int direct_delete_rows_init() - { - return HA_ERR_WRONG_COMMAND; - } -private: - virtual int pre_direct_delete_rows_init() - { - return HA_ERR_WRONG_COMMAND; - } - virtual int direct_delete_rows(ha_rows *delete_rows __attribute__((unused))) - { - return HA_ERR_WRONG_COMMAND; - } - virtual int pre_direct_delete_rows() - { - return HA_ERR_WRONG_COMMAND; - } - - /** - Reset state of file to after 'open'. - This function is called after every statement for all tables used - by that statement. - */ - virtual int reset() { return 0; } - virtual Table_flags table_flags(void) const= 0; - /** - Is not invoked for non-transactional temporary tables. - - Tells the storage engine that we intend to read or write data - from the table. This call is prefixed with a call to handler::store_lock() - and is invoked only for those handler instances that stored the lock. - - Calls to rnd_init/index_init are prefixed with this call. When table - IO is complete, we call external_lock(F_UNLCK). - A storage engine writer should expect that each call to - ::external_lock(F_[RD|WR]LOCK is followed by a call to - ::external_lock(F_UNLCK). If it is not, it is a bug in MySQL. - - The name and signature originate from the first implementation - in MyISAM, which would call fcntl to set/clear an advisory - lock on the data file in this method. - - @param lock_type F_RDLCK, F_WRLCK, F_UNLCK - - @return non-0 in case of failure, 0 in case of success. - When lock_type is F_UNLCK, the return value is ignored. - */ - virtual int external_lock(THD *thd __attribute__((unused)), - int lock_type __attribute__((unused))) - { - return 0; - } - virtual void release_auto_increment() { return; }; - /** admin commands - called from mysql_admin_table */ - virtual int check_for_upgrade(HA_CHECK_OPT *check_opt) - { return 0; } - virtual int check(THD* thd, HA_CHECK_OPT* check_opt) - { return HA_ADMIN_NOT_IMPLEMENTED; } - - /** - In this method check_opt can be modified - to specify CHECK option to use to call check() - upon the table. - */ - virtual int repair(THD* thd, HA_CHECK_OPT* check_opt) - { - DBUG_ASSERT(!(ha_table_flags() & HA_CAN_REPAIR)); - return HA_ADMIN_NOT_IMPLEMENTED; - } -protected: - virtual void start_bulk_insert(ha_rows rows, uint flags) {} - virtual int end_bulk_insert() { return 0; } - virtual int index_read(uchar * buf, const uchar * key, uint key_len, - enum ha_rkey_function find_flag) - { return HA_ERR_WRONG_COMMAND; } - virtual int index_read_last(uchar * buf, const uchar * key, uint key_len) - { - my_errno= HA_ERR_WRONG_COMMAND; - return HA_ERR_WRONG_COMMAND; - } - friend class ha_partition; - friend class ha_sequence; -public: - /** - This method is similar to update_row, however the handler doesn't need - to execute the updates at this point in time. The handler can be certain - that another call to bulk_update_row will occur OR a call to - exec_bulk_update before the set of updates in this query is concluded. - - @param old_data Old record - @param new_data New record - @param dup_key_found Number of duplicate keys found - - @retval 0 Bulk delete used by handler - @retval 1 Bulk delete not used, normal operation used - */ - virtual int bulk_update_row(const uchar *old_data, const uchar *new_data, - ha_rows *dup_key_found) - { - DBUG_ASSERT(FALSE); - return HA_ERR_WRONG_COMMAND; - } - /** - This is called to delete all rows in a table - If the handler don't support this, then this function will - return HA_ERR_WRONG_COMMAND and MySQL will delete the rows one - by one. - */ - virtual int delete_all_rows() - { return (my_errno=HA_ERR_WRONG_COMMAND); } - /** - Quickly remove all rows from a table. - - @remark This method is responsible for implementing MySQL's TRUNCATE - TABLE statement, which is a DDL operation. As such, a engine - can bypass certain integrity checks and in some cases avoid - fine-grained locking (e.g. row locks) which would normally be - required for a DELETE statement. - - @remark Typically, truncate is not used if it can result in integrity - violation. For example, truncate is not used when a foreign - key references the table, but it might be used if foreign key - checks are disabled. - - @remark Engine is responsible for resetting the auto-increment counter. - - @remark The table is locked in exclusive mode. - */ - virtual int truncate() - { - int error= delete_all_rows(); - return error ? error : reset_auto_increment(0); - } - /** - Reset the auto-increment counter to the given value, i.e. the next row - inserted will get the given value. - */ - virtual int reset_auto_increment(ulonglong value) - { return 0; } - virtual int optimize(THD* thd, HA_CHECK_OPT* check_opt) - { return HA_ADMIN_NOT_IMPLEMENTED; } - virtual int analyze(THD* thd, HA_CHECK_OPT* check_opt) - { return HA_ADMIN_NOT_IMPLEMENTED; } - virtual bool check_and_repair(THD *thd) { return TRUE; } - virtual int disable_indexes(uint mode) { return HA_ERR_WRONG_COMMAND; } - virtual int enable_indexes(uint mode) { return HA_ERR_WRONG_COMMAND; } - virtual int discard_or_import_tablespace(my_bool discard) - { return (my_errno=HA_ERR_WRONG_COMMAND); } - virtual void drop_table(const char *name); - virtual int create(const char *name, TABLE *form, HA_CREATE_INFO *info)=0; - - virtual int create_partitioning_metadata(const char *name, - const char *old_name, - chf_create_flags action_flag) - { return FALSE; } - - virtual int change_partitions(HA_CREATE_INFO *create_info, - const char *path, - ulonglong * const copied, - ulonglong * const deleted, - const uchar *pack_frm_data, - size_t pack_frm_len) - { return HA_ERR_WRONG_COMMAND; } - virtual int drop_partitions(const char *path) - { return HA_ERR_WRONG_COMMAND; } - virtual int rename_partitions(const char *path) - { return HA_ERR_WRONG_COMMAND; } - virtual bool set_ha_share_ref(Handler_share **arg_ha_share) - { - DBUG_ASSERT(!ha_share); - DBUG_ASSERT(arg_ha_share); - if (ha_share || !arg_ha_share) - return true; - ha_share= arg_ha_share; - return false; - } - void set_table(TABLE* table_arg) { table= table_arg; } - int get_lock_type() const { return m_lock_type; } -public: - /* XXX to be removed, see ha_partition::partition_ht() */ - virtual handlerton *partition_ht() const - { return ht; } - inline int ha_write_tmp_row(uchar *buf); - inline int ha_delete_tmp_row(uchar *buf); - inline int ha_update_tmp_row(const uchar * old_data, uchar * new_data); - - virtual void set_lock_type(enum thr_lock_type lock); - friend check_result_t handler_index_cond_check(void* h_arg); - friend check_result_t handler_rowid_filter_check(void *h_arg); - - /** - Find unique record by index or unique constrain - - @param record record to find (also will be fillded with - actual record fields) - @param unique_ref index or unique constraiun number (depends - on what used in the engine - - @retval -1 Error - @retval 1 Not found - @retval 0 Found - */ - virtual int find_unique_row(uchar *record, uint unique_ref) - { return -1; /*unsupported */} - - bool native_versioned() const - { DBUG_ASSERT(ht); return partition_ht()->flags & HTON_NATIVE_SYS_VERSIONING; } - virtual void update_partition(uint part_id) - {} - - /** - Some engines can perform column type conversion with ALGORITHM=INPLACE. - These functions check for such possibility. - Implementation could be based on Field_xxx::is_equal() - */ - virtual bool can_convert_string(const Field_string *field, - const Column_definition &new_type) const - { - return false; - } - virtual bool can_convert_varstring(const Field_varstring *field, - const Column_definition &new_type) const - { - return false; - } - virtual bool can_convert_blob(const Field_blob *field, - const Column_definition &new_type) const - { - return false; - } - /* If the table is using sql level unique constraints on some column */ - inline bool has_long_unique(); - - /* Used for ALTER TABLE. - Some engines can handle some differences in indexes by themself. */ - virtual Compare_keys compare_key_parts(const Field &old_field, - const Column_definition &new_field, - const KEY_PART_INFO &old_part, - const KEY_PART_INFO &new_part) const; - -protected: - Handler_share *get_ha_share_ptr(); - void set_ha_share_ptr(Handler_share *arg_ha_share); - void lock_shared_ha_data(); - void unlock_shared_ha_data(); -}; - -#include "multi_range_read.h" -#include "group_by_handler.h" - -bool key_uses_partial_cols(TABLE_SHARE *table, uint keyno); - - /* Some extern variables used with handlers */ - -extern const char *ha_row_type[]; -extern MYSQL_PLUGIN_IMPORT const char *tx_isolation_names[]; -extern MYSQL_PLUGIN_IMPORT const char *binlog_format_names[]; -extern TYPELIB tx_isolation_typelib; -extern const char *myisam_stats_method_names[]; -extern ulong total_ha, total_ha_2pc; - -/* lookups */ -plugin_ref ha_resolve_by_name(THD *thd, const LEX_CSTRING *name, bool tmp_table); -plugin_ref ha_lock_engine(THD *thd, const handlerton *hton); -handlerton *ha_resolve_by_legacy_type(THD *thd, enum legacy_db_type db_type); -handler *get_new_handler(TABLE_SHARE *share, MEM_ROOT *alloc, - handlerton *db_type); -handlerton *ha_checktype(THD *thd, handlerton *hton, bool no_substitute); - -static inline handlerton *ha_checktype(THD *thd, enum legacy_db_type type, - bool no_substitute = 0) -{ - return ha_checktype(thd, ha_resolve_by_legacy_type(thd, type), no_substitute); -} - -static inline enum legacy_db_type ha_legacy_type(const handlerton *db_type) -{ - return (db_type == NULL) ? DB_TYPE_UNKNOWN : db_type->db_type; -} - -static inline const char *ha_resolve_storage_engine_name(const handlerton *db_type) -{ - return db_type == NULL ? "UNKNOWN" : hton_name(db_type)->str; -} - -static inline bool ha_check_storage_engine_flag(const handlerton *db_type, uint32 flag) -{ - return db_type == NULL ? FALSE : MY_TEST(db_type->flags & flag); -} - -static inline bool ha_storage_engine_is_enabled(const handlerton *db_type) -{ - return db_type && db_type->create; -} - -#define view_pseudo_hton ((handlerton *)1) - -/* basic stuff */ -int ha_init_errors(void); -int ha_init(void); -int ha_end(void); -int ha_initialize_handlerton(st_plugin_int *plugin); -int ha_finalize_handlerton(st_plugin_int *plugin); - -TYPELIB *ha_known_exts(void); -int ha_panic(enum ha_panic_function flag); -void ha_close_connection(THD* thd); -void ha_kill_query(THD* thd, enum thd_kill_levels level); -bool ha_flush_logs(); -void ha_drop_database(char* path); -void ha_checkpoint_state(bool disable); -void ha_commit_checkpoint_request(void *cookie, void (*pre_hook)(void *)); -int ha_create_table(THD *thd, const char *path, - const char *db, const char *table_name, - HA_CREATE_INFO *create_info, LEX_CUSTRING *frm); -int ha_delete_table(THD *thd, handlerton *db_type, const char *path, - const LEX_CSTRING *db, const LEX_CSTRING *alias, - bool generate_warning); -int ha_delete_table_force(THD *thd, const char *path, const LEX_CSTRING *db, - const LEX_CSTRING *alias); - -void ha_prepare_for_backup(); -void ha_end_backup(); -void ha_pre_shutdown(); - -/* statistics and info */ -bool ha_show_status(THD *thd, handlerton *db_type, enum ha_stat_type stat); - -/* discovery */ -#ifdef MYSQL_SERVER -class Discovered_table_list: public handlerton::discovered_list -{ - THD *thd; - const char *wild, *wend; - bool with_temps; // whether to include temp tables in the result -public: - Dynamic_array *tables; - - Discovered_table_list(THD *thd_arg, Dynamic_array *tables_arg, - const LEX_CSTRING *wild_arg); - Discovered_table_list(THD *thd_arg, Dynamic_array *tables_arg) - : thd(thd_arg), wild(NULL), with_temps(true), tables(tables_arg) {} - ~Discovered_table_list() {} - - bool add_table(const char *tname, size_t tlen); - bool add_file(const char *fname); - - void sort(); - void remove_duplicates(); // assumes that the list is sorted -#ifndef DBUG_OFF - /* - Used to find unstable mtr tests querying - INFORMATION_SCHEMA.TABLES without ORDER BY. - */ - void sort_desc(); -#endif /* DBUG_OFF */ -}; - -int ha_discover_table(THD *thd, TABLE_SHARE *share); -int ha_discover_table_names(THD *thd, LEX_CSTRING *db, MY_DIR *dirp, - Discovered_table_list *result, bool reusable); -bool ha_table_exists(THD *thd, const LEX_CSTRING *db, - const LEX_CSTRING *table_name, - handlerton **hton= 0, bool *is_sequence= 0); -bool ha_check_if_updates_are_ignored(THD *thd, handlerton *hton, - const char *op); -#endif /* MYSQL_SERVER */ - -/* key cache */ -extern "C" int ha_init_key_cache(const char *name, KEY_CACHE *key_cache, void *); -int ha_resize_key_cache(KEY_CACHE *key_cache); -int ha_change_key_cache_param(KEY_CACHE *key_cache); -int ha_repartition_key_cache(KEY_CACHE *key_cache); -int ha_change_key_cache(KEY_CACHE *old_key_cache, KEY_CACHE *new_key_cache); - -/* transactions: interface to handlerton functions */ -int ha_start_consistent_snapshot(THD *thd); -int ha_commit_or_rollback_by_xid(XID *xid, bool commit); -int ha_commit_one_phase(THD *thd, bool all); -int ha_commit_trans(THD *thd, bool all); -int ha_rollback_trans(THD *thd, bool all); -int ha_prepare(THD *thd); -int ha_recover(HASH *commit_list); - -/* transactions: these functions never call handlerton functions directly */ -int ha_enable_transaction(THD *thd, bool on); - -/* savepoints */ -int ha_rollback_to_savepoint(THD *thd, SAVEPOINT *sv); -bool ha_rollback_to_savepoint_can_release_mdl(THD *thd); -int ha_savepoint(THD *thd, SAVEPOINT *sv); -int ha_release_savepoint(THD *thd, SAVEPOINT *sv); -#ifdef WITH_WSREP -int ha_abort_transaction(THD *bf_thd, THD *victim_thd, my_bool signal); -#endif - -/* these are called by storage engines */ -void trans_register_ha(THD *thd, bool all, handlerton *ht, - ulonglong trxid); - -/* - Storage engine has to assume the transaction will end up with 2pc if - - there is more than one 2pc-capable storage engine available - - in the current transaction 2pc was not disabled yet -*/ -#define trans_need_2pc(thd, all) ((total_ha_2pc > 1) && \ - !((all ? &thd->transaction.all : &thd->transaction.stmt)->no_2pc)) - -const char *get_canonical_filename(handler *file, const char *path, - char *tmp_path); -void commit_checkpoint_notify_ha(handlerton *hton, void *cookie); - -inline const LEX_CSTRING *table_case_name(HA_CREATE_INFO *info, const LEX_CSTRING *name) -{ - return ((lower_case_table_names == 2 && info->alias.str) ? &info->alias : name); -} - -typedef bool Log_func(THD*, TABLE*, bool, const uchar*, const uchar*); -int binlog_log_row(TABLE* table, - const uchar *before_record, - const uchar *after_record, - Log_func *log_func); - -/** - @def MYSQL_TABLE_IO_WAIT - Instrumentation helper for table io_waits. - Note that this helper is intended to be used from - within the handler class only, as it uses members - from @c handler - Performance schema events are instrumented as follows: - - in non batch mode, one event is generated per call - - in batch mode, the number of rows affected is saved - in @c m_psi_numrows, so that @c end_psi_batch_mode() - generates a single event for the batch. - @param OP the table operation to be performed - @param INDEX the table index used if any, or MAX_KEY. - @param PAYLOAD instrumented code to execute - @sa handler::end_psi_batch_mode. -*/ -#ifdef HAVE_PSI_TABLE_INTERFACE - #define MYSQL_TABLE_IO_WAIT(OP, INDEX, RESULT, PAYLOAD) \ - { \ - if (m_psi != NULL) \ - { \ - switch (m_psi_batch_mode) \ - { \ - case PSI_BATCH_MODE_NONE: \ - { \ - PSI_table_locker *sub_locker= NULL; \ - PSI_table_locker_state reentrant_safe_state; \ - sub_locker= PSI_TABLE_CALL(start_table_io_wait) \ - (& reentrant_safe_state, m_psi, OP, INDEX, \ - __FILE__, __LINE__); \ - PAYLOAD \ - if (sub_locker != NULL) \ - PSI_TABLE_CALL(end_table_io_wait) \ - (sub_locker, 1); \ - break; \ - } \ - case PSI_BATCH_MODE_STARTING: \ - { \ - m_psi_locker= PSI_TABLE_CALL(start_table_io_wait) \ - (& m_psi_locker_state, m_psi, OP, INDEX, \ - __FILE__, __LINE__); \ - PAYLOAD \ - if (!RESULT) \ - m_psi_numrows++; \ - m_psi_batch_mode= PSI_BATCH_MODE_STARTED; \ - break; \ - } \ - case PSI_BATCH_MODE_STARTED: \ - default: \ - { \ - DBUG_ASSERT(m_psi_batch_mode \ - == PSI_BATCH_MODE_STARTED); \ - PAYLOAD \ - if (!RESULT) \ - m_psi_numrows++; \ - break; \ - } \ - } \ - } \ - else \ - { \ - PAYLOAD \ - } \ - } -#else - #define MYSQL_TABLE_IO_WAIT(OP, INDEX, RESULT, PAYLOAD) \ - PAYLOAD -#endif - -#define TABLE_IO_WAIT(TRACKER, OP, INDEX, RESULT, PAYLOAD) \ - { \ - Exec_time_tracker *this_tracker; \ - if (unlikely((this_tracker= tracker))) \ - tracker->start_tracking(table->in_use); \ - \ - MYSQL_TABLE_IO_WAIT(OP, INDEX, RESULT, PAYLOAD); \ - \ - if (unlikely(this_tracker)) \ - tracker->stop_tracking(table->in_use); \ - } -void print_keydup_error(TABLE *table, KEY *key, const char *msg, myf errflag); -void print_keydup_error(TABLE *table, KEY *key, myf errflag); - -int del_global_index_stat(THD *thd, TABLE* table, KEY* key_info); -int del_global_table_stat(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table); -uint ha_count_rw_all(THD *thd, Ha_trx_info **ptr_ha_info); -bool non_existing_table_error(int error); -#endif /* HANDLER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/hash.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/hash.h deleted file mode 100644 index 00ffca5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/hash.h +++ /dev/null @@ -1,107 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. - Copyright (c) 2011, 2013, Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Dynamic hashing of record with different key-length */ - -#ifndef _hash_h -#define _hash_h - -#include "my_sys.h" /* DYNAMIC_ARRAY */ - -/* - This forward declaration is used from C files where the real - definition is included before. Since C does not allow repeated - typedef declarations, even when identical, the definition may not be - repeated. -*/ -#ifdef __cplusplus -extern "C" { -#endif - -/* - Overhead to store an element in hash - Can be used to approximate memory consumption for a hash - */ -#define HASH_OVERHEAD (sizeof(char*)*2) - -/* flags for hash_init */ -#define HASH_UNIQUE 1 /* hash_insert fails on duplicate key */ -#define HASH_THREAD_SPECIFIC 2 /* Mark allocated memory THREAD_SPECIFIC */ - -typedef uint32 my_hash_value_type; -typedef uchar *(*my_hash_get_key)(const uchar *,size_t*,my_bool); -typedef my_hash_value_type (*my_hash_function)(CHARSET_INFO *, - const uchar *, size_t); -typedef void (*my_hash_free_key)(void *); -typedef my_bool (*my_hash_walk_action)(void *,void *); - -typedef struct st_hash { - size_t key_offset,key_length; /* Length of key if const length */ - size_t blength; - ulong records; - uint flags; - DYNAMIC_ARRAY array; /* Place for hash_keys */ - my_hash_get_key get_key; - my_hash_function hash_function; - void (*free)(void *); - CHARSET_INFO *charset; -} HASH; - -/* A search iterator state */ -typedef uint HASH_SEARCH_STATE; - -#define my_hash_init(A,B,C,D,E,F,G,H,I) my_hash_init2(A,B,0,C,D,E,F,G,0,H,I) -my_bool my_hash_init2(PSI_memory_key psi_key, HASH *hash, uint growth_size, - CHARSET_INFO *charset, ulong default_array_elements, - size_t key_offset, size_t key_length, - my_hash_get_key get_key, my_hash_function hash_function, - void (*free_element)(void*), uint flags); -void my_hash_free(HASH *tree); -void my_hash_reset(HASH *hash); -uchar *my_hash_element(HASH *hash, size_t idx); -uchar *my_hash_search(const HASH *info, const uchar *key, size_t length); -uchar *my_hash_search_using_hash_value(const HASH *info, - my_hash_value_type hash_value, - const uchar *key, size_t length); -my_hash_value_type my_hash_sort(CHARSET_INFO *cs, - const uchar *key, size_t length); -#define my_calc_hash(A, B, C) my_hash_sort((A)->charset, B, C) -uchar *my_hash_first(const HASH *info, const uchar *key, size_t length, - HASH_SEARCH_STATE *state); -uchar *my_hash_first_from_hash_value(const HASH *info, - my_hash_value_type hash_value, - const uchar *key, - size_t length, - HASH_SEARCH_STATE *state); -uchar *my_hash_next(const HASH *info, const uchar *key, size_t length, - HASH_SEARCH_STATE *state); -my_bool my_hash_insert(HASH *info, const uchar *data); -my_bool my_hash_delete(HASH *hash, uchar *record); -my_bool my_hash_update(HASH *hash, uchar *record, uchar *old_key, - size_t old_key_length); -void my_hash_replace(HASH *hash, HASH_SEARCH_STATE *state, uchar *new_row); -my_bool my_hash_check(HASH *hash); /* Only in debug library */ -my_bool my_hash_iterate(HASH *hash, my_hash_walk_action action, void *argument); - -#define my_hash_clear(H) bzero((char*) (H), sizeof(*(H))) -#define my_hash_inited(H) ((H)->blength != 0) -#define my_hash_init_opt(A,B,C,D,E,F,G,H,I) \ - (!my_hash_inited(B) && my_hash_init(A,B,C,D,E,F,G,H,I)) - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/hash_filo.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/hash_filo.h deleted file mode 100644 index ac84e5c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/hash_filo.h +++ /dev/null @@ -1,214 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* -** A class for static sized hash tables where old entries are deleted in -** first-in-last-out to usage. -*/ - -#ifndef HASH_FILO_H -#define HASH_FILO_H - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class interface */ -#endif - -#include "hash.h" /* my_hash_get_key, my_hash_free_key, HASH */ -#include "m_string.h" /* bzero */ -#include "mysqld.h" /* key_hash_filo_lock */ - -class hash_filo_element -{ -private: - hash_filo_element *next_used,*prev_used; - public: - hash_filo_element() {} - hash_filo_element *next() - { return next_used; } - hash_filo_element *prev() - { return prev_used; } - - friend class hash_filo; -}; - - -class hash_filo -{ -private: - PSI_memory_key m_psi_key; - const uint key_offset, key_length; - const my_hash_get_key get_key; - /** Size of this hash table. */ - uint m_size; - my_hash_free_key free_element; - bool init; - CHARSET_INFO *hash_charset; - - hash_filo_element *first_link,*last_link; -public: - mysql_mutex_t lock; - HASH cache; - - hash_filo(PSI_memory_key psi_key, uint size_arg, uint key_offset_arg, - uint key_length_arg, my_hash_get_key get_key_arg, - my_hash_free_key free_element_arg, CHARSET_INFO *hash_charset_arg) - : m_psi_key(psi_key), key_offset(key_offset_arg), - key_length(key_length_arg), get_key(get_key_arg), m_size(size_arg), - free_element(free_element_arg),init(0), hash_charset(hash_charset_arg), - first_link(NULL), last_link(NULL) - { - bzero((char*) &cache,sizeof(cache)); - } - - ~hash_filo() - { - if (init) - { - if (cache.array.buffer) /* Avoid problems with thread library */ - (void) my_hash_free(&cache); - mysql_mutex_destroy(&lock); - } - } - void clear(bool locked=0) - { - if (!init) - { - init=1; - mysql_mutex_init(key_hash_filo_lock, &lock, MY_MUTEX_INIT_FAST); - } - if (!locked) - mysql_mutex_lock(&lock); - first_link= NULL; - last_link= NULL; - (void) my_hash_free(&cache); - (void) my_hash_init(m_psi_key, &cache,hash_charset,m_size,key_offset, - key_length, get_key, free_element, 0); - if (!locked) - mysql_mutex_unlock(&lock); - } - - hash_filo_element *first() - { - mysql_mutex_assert_owner(&lock); - return first_link; - } - - hash_filo_element *last() - { - mysql_mutex_assert_owner(&lock); - return last_link; - } - - hash_filo_element *search(uchar* key, size_t length) - { - mysql_mutex_assert_owner(&lock); - - hash_filo_element *entry=(hash_filo_element*) - my_hash_search(&cache,(uchar*) key,length); - if (entry) - { // Found; link it first - DBUG_ASSERT(first_link != NULL); - DBUG_ASSERT(last_link != NULL); - if (entry != first_link) - { // Relink used-chain - if (entry == last_link) - { - last_link= last_link->prev_used; - /* - The list must have at least 2 elements, - otherwise entry would be equal to first_link. - */ - DBUG_ASSERT(last_link != NULL); - last_link->next_used= NULL; - } - else - { - DBUG_ASSERT(entry->next_used != NULL); - DBUG_ASSERT(entry->prev_used != NULL); - entry->next_used->prev_used = entry->prev_used; - entry->prev_used->next_used = entry->next_used; - } - entry->prev_used= NULL; - entry->next_used= first_link; - - first_link->prev_used= entry; - first_link=entry; - } - } - return entry; - } - - bool add(hash_filo_element *entry) - { - if (!m_size) return 1; - if (cache.records == m_size) - { - hash_filo_element *tmp=last_link; - last_link= last_link->prev_used; - if (last_link != NULL) - { - last_link->next_used= NULL; - } - else - { - /* Pathological case, m_size == 1 */ - first_link= NULL; - } - my_hash_delete(&cache,(uchar*) tmp); - } - if (my_hash_insert(&cache,(uchar*) entry)) - { - if (free_element) - (*free_element)(entry); // This should never happen - return 1; - } - entry->prev_used= NULL; - entry->next_used= first_link; - if (first_link != NULL) - first_link->prev_used= entry; - else - last_link= entry; - first_link= entry; - - return 0; - } - - uint size() - { return m_size; } - - void resize(uint new_size) - { - mysql_mutex_lock(&lock); - m_size= new_size; - clear(true); - mysql_mutex_unlock(&lock); - } -}; - -template class Hash_filo: public hash_filo -{ -public: - Hash_filo(PSI_memory_key psi_key, uint size_arg, uint key_offset_arg, uint - key_length_arg, my_hash_get_key get_key_arg, my_hash_free_key - free_element_arg, CHARSET_INFO *hash_charset_arg) : - hash_filo(psi_key, size_arg, key_offset_arg, key_length_arg, - get_key_arg, free_element_arg, hash_charset_arg) {} - T* first() { return (T*)hash_filo::first(); } - T* last() { return (T*)hash_filo::last(); } - T* search(uchar* key, size_t len) { return (T*)hash_filo::search(key, len); } -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/heap.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/heap.h deleted file mode 100644 index f0ac527..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/heap.h +++ /dev/null @@ -1,271 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -/* This file should be included when using heap_database_functions */ -/* Author: Michael Widenius */ - -#ifndef _heap_h -#define _heap_h -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef _my_base_h -#include -#endif - -#include -#include - -#include "my_compare.h" -#include "my_tree.h" - - /* defines used by heap-funktions */ - -#define HP_MAX_LEVELS 4 /* 128^5 records is enough */ -#define HP_PTRS_IN_NOD 128 - - /* struct used with heap_funktions */ - -typedef struct st_heapinfo /* Struct from heap_info */ -{ - ulong records; /* Records in database */ - ulong deleted; /* Deleted records in database */ - ulong max_records; - ulonglong data_length; - ulonglong index_length; - uint reclength; /* Length of one record */ - int errkey; - ulonglong auto_increment; - time_t create_time; -} HEAPINFO; - - - /* Structs used by heap-database-handler */ - -typedef struct st_heap_ptrs -{ - uchar *blocks[HP_PTRS_IN_NOD]; /* pointers to HP_PTRS or records */ -} HP_PTRS; - -struct st_level_info -{ - /* Number of unused slots in *last_blocks HP_PTRS block (0 for 0th level) */ - uint free_ptrs_in_block; - - /* - Maximum number of records that can be 'contained' inside of each element - of last_blocks array. For level 0 - 1, for level 1 - HP_PTRS_IN_NOD, for - level 2 - HP_PTRS_IN_NOD^2 and so forth. - */ - ulong records_under_level; - - /* - Ptr to last allocated HP_PTRS (or records buffer for level 0) on this - level. - */ - HP_PTRS *last_blocks; -}; - - -/* - Heap table records and hash index entries are stored in HP_BLOCKs. - HP_BLOCK is used as a 'growable array' of fixed-size records. Size of record - is recbuffer bytes. - The internal representation is as follows: - HP_BLOCK is a hierarchical structure of 'blocks'. - A block at level 0 is an array records_in_block records. - A block at higher level is an HP_PTRS structure with pointers to blocks at - lower levels. - At the highest level there is one top block. It is stored in HP_BLOCK::root. - - See hp_find_block for a description of how record pointer is obtained from - its index. - See hp_get_new_block -*/ - -typedef struct st_heap_block -{ - HP_PTRS *root; /* Top-level block */ - struct st_level_info level_info[HP_MAX_LEVELS+1]; - uint levels; /* number of used levels */ - uint recbuffer; /* Length of one saved record */ - ulong records_in_block; /* Records in one heap-block */ - ulong last_allocated; /* number of records there is allocated space for */ -} HP_BLOCK; - -struct st_heap_info; /* For referense */ - -typedef struct st_hp_keydef /* Key definition with open */ -{ - uint flag; /* HA_NOSAME | HA_NULL_PART_KEY */ - uint keysegs; /* Number of key-segment */ - uint length; /* Length of key (automatic) */ - uint8 algorithm; /* HASH / BTREE */ - HA_KEYSEG *seg; - HP_BLOCK block; /* Where keys are saved */ - /* - Number of buckets used in hash table. Used only to provide - #records estimates for heap key scans. - */ - ha_rows hash_buckets; - TREE rb_tree; - int (*write_key)(struct st_heap_info *info, struct st_hp_keydef *keyinfo, - const uchar *record, uchar *recpos); - int (*delete_key)(struct st_heap_info *info, struct st_hp_keydef *keyinfo, - const uchar *record, uchar *recpos, int flag); - uint (*get_key_length)(struct st_hp_keydef *keydef, const uchar *key); -} HP_KEYDEF; - -typedef struct st_heap_share -{ - HP_BLOCK block; - HP_KEYDEF *keydef; - ulonglong data_length,index_length,max_table_size; - ulonglong auto_increment; - ulong min_records,max_records; /* Params to open */ - ulong records; /* records */ - ulong blength; /* records rounded up to 2^n */ - ulong deleted; /* Deleted records in database */ - uint key_stat_version; /* version to indicate insert/delete */ - uint key_version; /* Updated on key change */ - uint file_version; /* Update on clear */ - uint reclength; /* Length of one record */ - uint visible; /* Offset to the visible/deleted mark */ - uint changed; - uint keys,max_key_length; - uint currently_disabled_keys; /* saved value from "keys" when disabled */ - uint open_count; - uchar *del_link; /* Link to next block with del. rec */ - char * name; /* Name of "memory-file" */ - time_t create_time; - THR_LOCK lock; - my_bool delete_on_close; - my_bool internal; /* Internal temporary table */ - LIST open_list; - uint auto_key; - uint auto_key_type; /* real type of the auto key segment */ -} HP_SHARE; - -struct st_hp_hash_info; - -typedef struct st_heap_info -{ - HP_SHARE *s; - uchar *current_ptr; - struct st_hp_hash_info *current_hash_ptr; - ulong current_record,next_block; - int lastinx,errkey; - int mode; /* Mode of file (READONLY..) */ - uint opt_flag,update; - uchar *lastkey; /* Last used key with rkey */ - uchar *recbuf; /* Record buffer for rb-tree keys */ - enum ha_rkey_function last_find_flag; - TREE_ELEMENT *parents[MAX_TREE_HEIGHT+1]; - TREE_ELEMENT **last_pos; - uint key_version; /* Version at last read */ - uint file_version; /* Version at scan */ - uint lastkey_len; - my_bool implicit_emptied; - THR_LOCK_DATA lock; - LIST open_list; -} HP_INFO; - - -typedef struct st_heap_create_info -{ - HP_KEYDEF *keydef; - uint auto_key; /* keynr [1 - maxkey] for auto key */ - uint auto_key_type; - uint keys; - uint reclength; - ulong max_records; - ulong min_records; - ulonglong max_table_size; - ulonglong auto_increment; - my_bool with_auto_increment; - my_bool internal_table; - /* - TRUE if heap_create should 'pin' the created share by setting - open_count to 1. Is only looked at if not internal_table. - */ - my_bool pin_share; -} HP_CREATE_INFO; - - /* Prototypes for heap-functions */ - -extern HP_INFO *heap_open(const char *name, int mode); -extern HP_INFO *heap_open_from_share(HP_SHARE *share, int mode); -extern HP_INFO *heap_open_from_share_and_register(HP_SHARE *share, int mode); -extern void heap_release_share(HP_SHARE *share, my_bool internal_table); -extern int heap_close(HP_INFO *info); -extern int heap_write(HP_INFO *info,const uchar *buff); -extern int heap_update(HP_INFO *info,const uchar *old,const uchar *newdata); -extern int heap_rrnd(HP_INFO *info,uchar *buf,uchar *pos); -extern int heap_scan_init(HP_INFO *info); -extern int heap_scan(HP_INFO *info, uchar *record); -extern int heap_delete(HP_INFO *info,const uchar *buff); -extern int heap_info(HP_INFO *info,HEAPINFO *x,int flag); -extern int heap_create(const char *name, - HP_CREATE_INFO *create_info, HP_SHARE **share, - my_bool *created_new_share); -extern int heap_delete_table(const char *name); -extern void heap_drop_table(HP_INFO *info); -extern int heap_extra(HP_INFO *info,enum ha_extra_function function); -extern int heap_reset(HP_INFO *info); -extern int heap_rename(const char *old_name,const char *new_name); -extern int heap_panic(enum ha_panic_function flag); -extern int heap_rsame(HP_INFO *info,uchar *record,int inx); -extern int heap_rnext(HP_INFO *info,uchar *record); -extern int heap_rprev(HP_INFO *info,uchar *record); -extern int heap_rfirst(HP_INFO *info,uchar *record,int inx); -extern int heap_rlast(HP_INFO *info,uchar *record,int inx); -extern void heap_clear(HP_INFO *info); -extern void heap_clear_keys(HP_INFO *info); -extern int heap_disable_indexes(HP_INFO *info); -extern int heap_enable_indexes(HP_INFO *info); -extern int heap_indexes_are_disabled(HP_INFO *info); -extern void heap_update_auto_increment(HP_INFO *info, const uchar *record); -ha_rows hp_rb_records_in_range(HP_INFO *info, int inx, - const key_range *min_key, - const key_range *max_key); -int hp_panic(enum ha_panic_function flag); -int heap_rkey(HP_INFO *info, uchar *record, int inx, const uchar *key, - key_part_map keypart_map, enum ha_rkey_function find_flag); -extern uchar * heap_find(HP_INFO *info,int inx,const uchar *key); -extern int heap_check_heap(const HP_INFO *info, my_bool print_status); -extern uchar *heap_position(HP_INFO *info); - -/* The following is for programs that uses the old HEAP interface where - pointer to rows where a long instead of a (uchar*). -*/ - -#if defined(WANT_OLD_HEAP_VERSION) || defined(OLD_HEAP_VERSION) -extern int heap_rrnd_old(HP_INFO *info,uchar *buf,ulong pos); -extern ulong heap_position_old(HP_INFO *info); -#endif -#ifdef OLD_HEAP_VERSION -typedef ulong HEAP_PTR; -#define heap_position(A) heap_position_old(A) -#define heap_rrnd(A,B,C) heap_rrnd_old(A,B,C) -#else -typedef uchar *HEAP_PTR; -#endif - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/hostname.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/hostname.h deleted file mode 100644 index 3a371dc..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/hostname.h +++ /dev/null @@ -1,183 +0,0 @@ -/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef HOSTNAME_INCLUDED -#define HOSTNAME_INCLUDED - -#include "my_net.h" -#include "hash_filo.h" - -struct Host_errors -{ -public: - Host_errors(); - ~Host_errors(); - - void reset(); - void aggregate(const Host_errors *errors); - - /** Number of connect errors. */ - ulong m_connect; - - /** Number of host blocked errors. */ - ulong m_host_blocked; - /** Number of transient errors from getnameinfo(). */ - ulong m_nameinfo_transient; - /** Number of permanent errors from getnameinfo(). */ - ulong m_nameinfo_permanent; - /** Number of errors from is_hostname_valid(). */ - ulong m_format; - /** Number of transient errors from getaddrinfo(). */ - ulong m_addrinfo_transient; - /** Number of permanent errors from getaddrinfo(). */ - ulong m_addrinfo_permanent; - /** Number of errors from Forward-Confirmed reverse DNS checks. */ - ulong m_FCrDNS; - /** Number of errors from host grants. */ - ulong m_host_acl; - /** Number of errors from missing auth plugin. */ - ulong m_no_auth_plugin; - /** Number of errors from auth plugin. */ - ulong m_auth_plugin; - /** Number of errors from authentication plugins. */ - ulong m_handshake; - /** Number of errors from proxy user. */ - ulong m_proxy_user; - /** Number of errors from proxy user acl. */ - ulong m_proxy_user_acl; - /** Number of errors from authentication. */ - ulong m_authentication; - /** Number of errors from ssl. */ - ulong m_ssl; - /** Number of errors from max user connection. */ - ulong m_max_user_connection; - /** Number of errors from max user connection per hour. */ - ulong m_max_user_connection_per_hour; - /** Number of errors from the default database. */ - ulong m_default_database; - /** Number of errors from init_connect. */ - ulong m_init_connect; - /** Number of errors from the server itself. */ - ulong m_local; - - bool has_error() const - { - return ((m_host_blocked != 0) - || (m_nameinfo_transient != 0) - || (m_nameinfo_permanent != 0) - || (m_format != 0) - || (m_addrinfo_transient != 0) - || (m_addrinfo_permanent != 0) - || (m_FCrDNS != 0) - || (m_host_acl != 0) - || (m_no_auth_plugin != 0) - || (m_auth_plugin != 0) - || (m_handshake != 0) - || (m_proxy_user != 0) - || (m_proxy_user_acl != 0) - || (m_authentication != 0) - || (m_ssl != 0) - || (m_max_user_connection != 0) - || (m_max_user_connection_per_hour != 0) - || (m_default_database != 0) - || (m_init_connect != 0) - || (m_local != 0)); - } - - void sum_connect_errors() - { - /* Current (historical) behavior: */ - m_connect= m_handshake; - } - - void clear_connect_errors() - { - m_connect= 0; - } -}; - -/** Size of IP address string in the hash cache. */ -#define HOST_ENTRY_KEY_SIZE INET6_ADDRSTRLEN - -/** - An entry in the hostname hash table cache. - - Host name cache does two things: - - caches host names to save DNS look ups; - - counts errors from IP. - - Host name can be empty (that means DNS look up failed), - but errors still are counted. -*/ -class Host_entry : public hash_filo_element -{ -public: - Host_entry *next() - { return (Host_entry*) hash_filo_element::next(); } - - /** - Client IP address. This is the key used with the hash table. - - The client IP address is always expressed in IPv6, even when the - network IPv6 stack is not present. - - This IP address is never used to connect to a socket. - */ - char ip_key[HOST_ENTRY_KEY_SIZE]; - - /** - One of the host names for the IP address. May be a zero length string. - */ - char m_hostname[HOSTNAME_LENGTH + 1]; - /** Length in bytes of @c m_hostname. */ - uint m_hostname_length; - /** The hostname is validated and used for authorization. */ - bool m_host_validated; - ulonglong m_first_seen; - ulonglong m_last_seen; - ulonglong m_first_error_seen; - ulonglong m_last_error_seen; - /** Error statistics. */ - Host_errors m_errors; - - void set_error_timestamps(ulonglong now) - { - if (m_first_error_seen == 0) - m_first_error_seen= now; - m_last_error_seen= now; - } -}; - -/** The size of the host_cache. */ -extern ulong host_cache_size; - -#define RC_OK 0 -#define RC_BLOCKED_HOST 1 -int ip_to_hostname(struct sockaddr_storage *ip_storage, - const char *ip_string, - const char **hostname, uint *connect_errors); - -void inc_host_errors(const char *ip_string, Host_errors *errors); -void reset_host_connect_errors(const char *ip_string); -bool hostname_cache_init(); -void hostname_cache_free(); -void hostname_cache_refresh(void); -uint hostname_cache_size(); -void hostname_cache_resize(uint size); -void hostname_cache_lock(); -void hostname_cache_unlock(); -Host_entry *hostname_cache_first(); - -#endif /* HOSTNAME_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ilist.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/ilist.h deleted file mode 100644 index 92812ba..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ilist.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - Copyright (c) 2019, 2020, MariaDB - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -#ifndef ILIST_H -#define ILIST_H - -#include "my_dbug.h" - -#include -#include - -// Derive your class from this struct to insert to a linked list. -template struct ilist_node -{ - ilist_node() noexcept -#ifndef DBUG_OFF - : next(NULL), prev(NULL) -#endif - { - } - - ilist_node(ilist_node *next, ilist_node *prev) noexcept - : next(next), prev(prev) - { - } - - ilist_node *next; - ilist_node *prev; -}; - -// Modelled after std::list -template class ilist -{ -public: - typedef ilist_node ListNode; - class Iterator; - - // All containers in C++ should define these types to implement generic - // container interface. - typedef T value_type; - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - typedef value_type &reference; - typedef const value_type &const_reference; - typedef T *pointer; - typedef const T *const_pointer; - typedef Iterator iterator; - typedef Iterator const_iterator; /* FIXME */ - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - class Iterator - { - public: - // All iterators in C++ should define these types to implement generic - // iterator interface. - typedef std::bidirectional_iterator_tag iterator_category; - typedef T value_type; - typedef std::ptrdiff_t difference_type; - typedef T *pointer; - typedef T &reference; - - Iterator(ListNode *node) noexcept : node_(node) - { DBUG_ASSERT(node_ != nullptr); } - - Iterator &operator++() noexcept - { - node_= node_->next; - DBUG_ASSERT(node_ != nullptr); - return *this; - } - Iterator operator++(int) noexcept - { - Iterator tmp(*this); - operator++(); - return tmp; - } - - Iterator &operator--() noexcept - { - node_= node_->prev; - DBUG_ASSERT(node_ != nullptr); - return *this; - } - Iterator operator--(int) noexcept - { - Iterator tmp(*this); - operator--(); - return tmp; - } - - reference operator*() noexcept { return *static_cast(node_); } - pointer operator->() noexcept { return static_cast(node_); } - - friend bool operator==(const Iterator &lhs, const Iterator &rhs) noexcept - { - return lhs.node_ == rhs.node_; - } - friend bool operator!=(const Iterator &lhs, const Iterator &rhs) noexcept - { - return !(lhs == rhs); - } - - private: - ListNode *node_; - - friend class ilist; - }; - - ilist() noexcept : sentinel_(&sentinel_, &sentinel_) {} - - reference front() noexcept { return *begin(); } - reference back() noexcept { return *--end(); } - const_reference front() const noexcept { return *begin(); } - const_reference back() const noexcept { return *--end(); } - - iterator begin() noexcept { return iterator(sentinel_.next); } - const_iterator begin() const noexcept - { - return iterator(const_cast(sentinel_.next)); - } - iterator end() noexcept { return iterator(&sentinel_); } - const_iterator end() const noexcept - { - return iterator(const_cast(&sentinel_)); - } - - reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const noexcept - { - return reverse_iterator(end()); - } - reverse_iterator rend() noexcept { return reverse_iterator(begin()); } - const_reverse_iterator rend() const noexcept - { - return reverse_iterator(begin()); - } - - bool empty() const noexcept { return sentinel_.next == &sentinel_; } - - // Not implemented because it's O(N) - // size_type size() const - // { - // return static_cast(std::distance(begin(), end())); - // } - - void clear() noexcept - { - sentinel_.next= &sentinel_; - sentinel_.prev= &sentinel_; - } - - iterator insert(iterator pos, reference value) noexcept - { - ListNode *curr= pos.node_; - ListNode *prev= pos.node_->prev; - - prev->next= &value; - curr->prev= &value; - - static_cast(value).prev= prev; - static_cast(value).next= curr; - - return iterator(&value); - } - - iterator erase(iterator pos) noexcept - { - ListNode *prev= pos.node_->prev; - ListNode *next= pos.node_->next; - - prev->next= next; - next->prev= prev; - -#ifndef DBUG_OFF - ListNode *curr= pos.node_; - curr->prev= nullptr; - curr->next= nullptr; -#endif - - return next; - } - - void push_back(reference value) noexcept { insert(end(), value); } - void pop_back() noexcept { erase(end()); } - - void push_front(reference value) noexcept { insert(begin(), value); } - void pop_front() noexcept { erase(begin()); } - - // STL version is O(n) but this is O(1) because an element can't be inserted - // several times in the same ilist. - void remove(reference value) noexcept { erase(iterator(&value)); } - -private: - ListNode sentinel_; -}; - -// Similar to ilist but also has O(1) size() method. -template class sized_ilist : public ilist -{ - typedef ilist BASE; - -public: - // All containers in C++ should define these types to implement generic - // container interface. - typedef T value_type; - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - typedef value_type &reference; - typedef const value_type &const_reference; - typedef T *pointer; - typedef const T *const_pointer; - typedef typename BASE::Iterator iterator; - typedef const typename BASE::Iterator const_iterator; - typedef std::reverse_iterator reverse_iterator; - typedef std::reverse_iterator const_reverse_iterator; - - sized_ilist() noexcept : size_(0) {} - - size_type size() const noexcept { return size_; } - - void clear() noexcept - { - BASE::clear(); - size_= 0; - } - - iterator insert(iterator pos, reference value) noexcept - { - ++size_; - return BASE::insert(pos, value); - } - - iterator erase(iterator pos) noexcept - { - --size_; - return BASE::erase(pos); - } - - void push_back(reference value) noexcept { insert(BASE::end(), value); } - void pop_back() noexcept { erase(BASE::end()); } - - void push_front(reference value) noexcept { insert(BASE::begin(), value); } - void pop_front() noexcept { erase(BASE::begin()); } - - void remove(reference value) noexcept { erase(iterator(&value)); } - -private: - size_type size_; -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/init.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/init.h deleted file mode 100644 index b9d5053..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/init.h +++ /dev/null @@ -1,21 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef INIT_INCLUDED -#define INIT_INCLUDED - -void unireg_init(ulong options); - -#endif /* INIT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/innodb_priv.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/innodb_priv.h deleted file mode 100644 index bec63a8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/innodb_priv.h +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef INNODB_PRIV_INCLUDED -#define INNODB_PRIV_INCLUDED - -/** @file Declaring server-internal functions that are used by InnoDB. */ - -#include -#include /* strconvert */ - -class THD; - -int get_quote_char_for_identifier(THD *thd, const char *name, size_t length); -bool schema_table_store_record(THD *thd, TABLE *table); -void localtime_to_TIME(MYSQL_TIME *to, struct tm *from); - -void sql_print_error(const char *format, ...); - -#define thd_binlog_pos(X, Y, Z) mysql_bin_log_commit_pos(X, Z, Y) - -#endif /* INNODB_PRIV_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item.h deleted file mode 100644 index fb480b4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item.h +++ /dev/null @@ -1,7502 +0,0 @@ -#ifndef SQL_ITEM_INCLUDED -#define SQL_ITEM_INCLUDED - -/* Copyright (c) 2000, 2017, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_priv.h" /* STRING_BUFFER_USUAL_SIZE */ -#include "unireg.h" -#include "sql_const.h" /* RAND_TABLE_BIT, MAX_FIELD_NAME */ -#include "field.h" /* Derivation */ -#include "sql_type.h" -#include "sql_time.h" -#include "mem_root_array.h" - -C_MODE_START -#include - -/* - A prototype for a C-compatible structure to store a value of any data type. - Currently it has to stay in /sql, as it depends on String and my_decimal. - We'll do the following changes: - 1. add pure C "struct st_string" and "struct st_my_decimal" - 2. change type of m_string to struct st_string and move inside the union - 3. change type of m_decmal to struct st_my_decimal and move inside the union - 4. move the definition to some file in /include -*/ -struct st_value -{ - enum enum_dynamic_column_type m_type; - union - { - longlong m_longlong; - double m_double; - MYSQL_TIME m_time; - } value; - String m_string; - my_decimal m_decimal; -}; - -C_MODE_END - - -class Value: public st_value -{ -public: - bool is_null() const { return m_type == DYN_COL_NULL; } - bool is_longlong() const - { - return m_type == DYN_COL_UINT || m_type == DYN_COL_INT; - } - bool is_double() const { return m_type == DYN_COL_DOUBLE; } - bool is_temporal() const { return m_type == DYN_COL_DATETIME; } - bool is_string() const { return m_type == DYN_COL_STRING; } - bool is_decimal() const { return m_type == DYN_COL_DECIMAL; } -}; - - -template -class ValueBuffer: public Value -{ - char buffer[buffer_size]; - void reset_buffer() - { - m_string.set(buffer, buffer_size, &my_charset_bin); - } -public: - ValueBuffer() - { - reset_buffer(); - } -}; - - -#ifdef DBUG_OFF -static inline const char *dbug_print_item(Item *item) { return NULL; } -#else -const char *dbug_print_item(Item *item); -#endif - -class Virtual_tmp_table; -class sp_head; -class Protocol; -struct TABLE_LIST; -void item_init(void); /* Init item functions */ -class Item_basic_value; -class Item_result_field; -class Item_field; -class Item_ref; -class Item_param; -class user_var_entry; -class JOIN; -struct KEY_FIELD; -struct SARGABLE_PARAM; -class RANGE_OPT_PARAM; -class SEL_TREE; -class With_sum_func_cache; - -enum precedence { - LOWEST_PRECEDENCE, - ASSIGN_PRECEDENCE, // := - OR_PRECEDENCE, // OR, || (unless PIPES_AS_CONCAT) - XOR_PRECEDENCE, // XOR - AND_PRECEDENCE, // AND, && - NOT_PRECEDENCE, // NOT (unless HIGH_NOT_PRECEDENCE) - CMP_PRECEDENCE, // =, <=>, >=, >, <=, <, <>, !=, IS - BETWEEN_PRECEDENCE, // BETWEEN - IN_PRECEDENCE, // IN, LIKE, REGEXP - BITOR_PRECEDENCE, // | - BITAND_PRECEDENCE, // & - SHIFT_PRECEDENCE, // <<, >> - INTERVAL_PRECEDENCE, // first argument in +INTERVAL - ADD_PRECEDENCE, // +, - - MUL_PRECEDENCE, // *, /, DIV, %, MOD - BITXOR_PRECEDENCE, // ^ - PIPES_PRECEDENCE, // || (if PIPES_AS_CONCAT) - NEG_PRECEDENCE, // unary -, ~, !, NOT (if HIGH_NOT_PRECEDENCE) - COLLATE_PRECEDENCE, // BINARY, COLLATE - DEFAULT_PRECEDENCE, - HIGHEST_PRECEDENCE -}; - -bool mark_unsupported_function(const char *where, void *store, uint result); - -/* convenience helper for mark_unsupported_function() above */ -bool mark_unsupported_function(const char *w1, const char *w2, - void *store, uint result); - -/* Bits for the split_sum_func() function */ -#define SPLIT_SUM_SKIP_REGISTERED 1 /* Skip registered funcs */ -#define SPLIT_SUM_SELECT 2 /* SELECT item; Split all parts */ - - -#define NO_EXTRACTION_FL (1 << 6) -#define FULL_EXTRACTION_FL (1 << 7) -#define DELETION_FL (1 << 8) -#define IMMUTABLE_FL (1 << 9) -#define SUBSTITUTION_FL (1 << 10) -#define EXTRACTION_MASK \ - (NO_EXTRACTION_FL | FULL_EXTRACTION_FL | DELETION_FL | IMMUTABLE_FL) - -extern const char *item_empty_name; - -void dummy_error_processor(THD *thd, void *data); - -void view_error_processor(THD *thd, void *data); - -/* - Instances of Name_resolution_context store the information necessary for - name resolution of Items and other context analysis of a query made in - fix_fields(). - - This structure is a part of SELECT_LEX, a pointer to this structure is - assigned when an item is created (which happens mostly during parsing - (sql_yacc.yy)), but the structure itself will be initialized after parsing - is complete - - TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to - separate SELECT_LEX which allow to remove tricks of changing this - structure before and after INSERT/CREATE and its SELECT to make correct - field name resolution. -*/ -struct Name_resolution_context: Sql_alloc -{ - /* - The name resolution context to search in when an Item cannot be - resolved in this context (the context of an outer select) - */ - Name_resolution_context *outer_context; - - /* - List of tables used to resolve the items of this context. Usually these - are tables from the FROM clause of SELECT statement. The exceptions are - INSERT ... SELECT and CREATE ... SELECT statements, where SELECT - subquery is not moved to a separate SELECT_LEX. For these types of - statements we have to change this member dynamically to ensure correct - name resolution of different parts of the statement. - */ - TABLE_LIST *table_list; - /* - In most cases the two table references below replace 'table_list' above - for the purpose of name resolution. The first and last name resolution - table references allow us to search only in a sub-tree of the nested - join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING - and JOIN ... ON. - */ - TABLE_LIST *first_name_resolution_table; - /* - Last table to search in the list of leaf table references that begins - with first_name_resolution_table. - */ - TABLE_LIST *last_name_resolution_table; - - /* Cache first_name_resolution_table in setup_natural_join_row_types */ - TABLE_LIST *natural_join_first_table; - /* - SELECT_LEX item belong to, in case of merged VIEW it can differ from - SELECT_LEX where item was created, so we can't use table_list/field_list - from there - */ - st_select_lex *select_lex; - - /* - Processor of errors caused during Item name resolving, now used only to - hide underlying tables in errors about views (i.e. it substitute some - errors for views) - */ - void (*error_processor)(THD *, void *); - void *error_processor_data; - - /* - When TRUE items are resolved in this context both against the - SELECT list and this->table_list. If FALSE, items are resolved - only against this->table_list. - */ - bool resolve_in_select_list; - - /* - Security context of this name resolution context. It's used for views - and is non-zero only if the view is defined with SQL SECURITY DEFINER. - */ - Security_context *security_ctx; - - Name_resolution_context() - :outer_context(0), table_list(0), select_lex(0), - error_processor_data(0), - security_ctx(0) - {} - - void init() - { - resolve_in_select_list= FALSE; - error_processor= &dummy_error_processor; - first_name_resolution_table= NULL; - last_name_resolution_table= NULL; - } - - void resolve_in_table_list_only(TABLE_LIST *tables) - { - table_list= first_name_resolution_table= tables; - resolve_in_select_list= FALSE; - } - - void process_error(THD *thd) - { - (*error_processor)(thd, error_processor_data); - } - st_select_lex *outer_select() - { - return (outer_context ? - outer_context->select_lex : - NULL); - } -}; - - -/* - Store and restore the current state of a name resolution context. -*/ - -class Name_resolution_context_state -{ -private: - TABLE_LIST *save_table_list; - TABLE_LIST *save_first_name_resolution_table; - TABLE_LIST *save_next_name_resolution_table; - bool save_resolve_in_select_list; - TABLE_LIST *save_next_local; - -public: - Name_resolution_context_state() {} /* Remove gcc warning */ - -public: - /* Save the state of a name resolution context. */ - void save_state(Name_resolution_context *context, TABLE_LIST *table_list) - { - save_table_list= context->table_list; - save_first_name_resolution_table= context->first_name_resolution_table; - save_resolve_in_select_list= context->resolve_in_select_list; - save_next_local= table_list->next_local; - save_next_name_resolution_table= table_list->next_name_resolution_table; - } - - /* Restore a name resolution context from saved state. */ - void restore_state(Name_resolution_context *context, TABLE_LIST *table_list) - { - table_list->next_local= save_next_local; - table_list->next_name_resolution_table= save_next_name_resolution_table; - context->table_list= save_table_list; - context->first_name_resolution_table= save_first_name_resolution_table; - context->resolve_in_select_list= save_resolve_in_select_list; - } - - TABLE_LIST *get_first_name_resolution_table() - { - return save_first_name_resolution_table; - } -}; - -class Name_resolution_context_backup -{ - Name_resolution_context &ctx; - TABLE_LIST &table_list; - table_map save_map; - Name_resolution_context_state ctx_state; - -public: - Name_resolution_context_backup(Name_resolution_context &_ctx, TABLE_LIST &_table_list) - : ctx(_ctx), table_list(_table_list), save_map(_table_list.map) - { - ctx_state.save_state(&ctx, &table_list); - ctx.table_list= &table_list; - ctx.first_name_resolution_table= &table_list; - } - ~Name_resolution_context_backup() - { - ctx_state.restore_state(&ctx, &table_list); - table_list.map= save_map; - } -}; - - -/* - This enum is used to report information about monotonicity of function - represented by Item* tree. - Monotonicity is defined only for Item* trees that represent table - partitioning expressions (i.e. have no subselects/user vars/PS parameters - etc etc). An Item* tree is assumed to have the same monotonicity properties - as its corresponding function F: - - [signed] longlong F(field1, field2, ...) { - put values of field_i into table record buffer; - return item->val_int(); - } - - NOTE - At the moment function monotonicity is not well defined (and so may be - incorrect) for Item trees with parameters/return types that are different - from INT_RESULT, may be NULL, or are unsigned. - It will be possible to address this issue once the related partitioning bugs - (BUG#16002, BUG#15447, BUG#13436) are fixed. - - The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns - NULL which puts those rows into the NULL partition, but - '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed - for this (see Bug#20577). -*/ - -typedef enum monotonicity_info -{ - NON_MONOTONIC, /* none of the below holds */ - MONOTONIC_INCREASING, /* F() is unary and (x < y) => (F(x) <= F(y)) */ - MONOTONIC_INCREASING_NOT_NULL, /* But only for valid/real x and y */ - MONOTONIC_STRICT_INCREASING,/* F() is unary and (x < y) => (F(x) < F(y)) */ - MONOTONIC_STRICT_INCREASING_NOT_NULL /* But only for valid/real x and y */ -} enum_monotonicity_info; - -/*************************************************************************/ - -class sp_rcontext; - -/** - A helper class to collect different behavior of various kinds of SP variables: - - local SP variables and SP parameters - - PACKAGE BODY routine variables - - (there will be more kinds in the future) -*/ - -class Sp_rcontext_handler -{ -public: - virtual ~Sp_rcontext_handler() {} - /** - A prefix used for SP variable names in queries: - - EXPLAIN EXTENDED - - SHOW PROCEDURE CODE - Local variables and SP parameters have empty prefixes. - Package body variables are marked with a special prefix. - This improves readability of the output of these queries, - especially when a local variable or a parameter has the same - name with a package body variable. - */ - virtual const LEX_CSTRING *get_name_prefix() const= 0; - /** - At execution time THD->spcont points to the run-time context (sp_rcontext) - of the currently executed routine. - Local variables store their data in the sp_rcontext pointed by thd->spcont. - Package body variables store data in separate sp_rcontext that belongs - to the package. - This method provides access to the proper sp_rcontext structure, - depending on the SP variable kind. - */ - virtual sp_rcontext *get_rcontext(sp_rcontext *ctx) const= 0; -}; - - -class Sp_rcontext_handler_local: public Sp_rcontext_handler -{ -public: - const LEX_CSTRING *get_name_prefix() const; - sp_rcontext *get_rcontext(sp_rcontext *ctx) const; -}; - - -class Sp_rcontext_handler_package_body: public Sp_rcontext_handler -{ -public: - const LEX_CSTRING *get_name_prefix() const; - sp_rcontext *get_rcontext(sp_rcontext *ctx) const; -}; - - -extern MYSQL_PLUGIN_IMPORT - Sp_rcontext_handler_local sp_rcontext_handler_local; - - -extern MYSQL_PLUGIN_IMPORT - Sp_rcontext_handler_package_body sp_rcontext_handler_package_body; - - - -class Item_equal; - -struct st_join_table* const NO_PARTICULAR_TAB= (struct st_join_table*)0x1; - -typedef struct replace_equal_field_arg -{ - Item_equal *item_equal; - struct st_join_table *context_tab; -} REPLACE_EQUAL_FIELD_ARG; - -class Settable_routine_parameter -{ -public: - /* - Set required privileges for accessing the parameter. - - SYNOPSIS - set_required_privilege() - rw if 'rw' is true then we are going to read and set the - parameter, so SELECT and UPDATE privileges might be - required, otherwise we only reading it and SELECT - privilege might be required. - */ - Settable_routine_parameter() {} - virtual ~Settable_routine_parameter() {} - virtual void set_required_privilege(bool rw) {}; - - /* - Set parameter value. - - SYNOPSIS - set_value() - thd thread handle - ctx context to which parameter belongs (if it is local - variable). - it item which represents new value - - RETURN - FALSE if parameter value has been set, - TRUE if error has occurred. - */ - virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it)= 0; - - virtual void set_out_param_info(Send_field *info) {} - - virtual const Send_field *get_out_param_info() const - { return NULL; } - - virtual Item_param *get_item_param() { return 0; } -}; - - -/* - A helper class to calculate offset and length of a query fragment - - outside of SP - - inside an SP - - inside a compound block -*/ -class Query_fragment -{ - uint m_pos; - uint m_length; - void set(size_t pos, size_t length) - { - DBUG_ASSERT(pos < UINT_MAX32); - DBUG_ASSERT(length < UINT_MAX32); - m_pos= (uint) pos; - m_length= (uint) length; - } -public: - Query_fragment(THD *thd, sp_head *sphead, const char *start, const char *end); - uint pos() const { return m_pos; } - uint length() const { return m_length; } -}; - - -/** - This is used for items in the query that needs to be rewritten - before binlogging - - At the moment this applies to Item_param and Item_splocal -*/ -class Rewritable_query_parameter -{ - public: - /* - Offset inside the query text. - Value of 0 means that this object doesn't have to be replaced - (for example SP variables in control statements) - */ - my_ptrdiff_t pos_in_query; - - /* - Byte length of parameter name in the statement. This is not - Item::name.length because name.length contains byte length of UTF8-encoded - name, but the query string is in the client charset. - */ - uint len_in_query; - - bool limit_clause_param; - - Rewritable_query_parameter(uint pos_in_q= 0, uint len_in_q= 0) - : pos_in_query(pos_in_q), len_in_query(len_in_q), - limit_clause_param(false) - { } - - virtual ~Rewritable_query_parameter() { } - - virtual bool append_for_log(THD *thd, String *str) = 0; -}; - -class Copy_query_with_rewrite -{ - THD *thd; - const char *src; - size_t src_len, from; - String *dst; - - bool copy_up_to(size_t bytes) - { - DBUG_ASSERT(bytes >= from); - return dst->append(src + from, uint32(bytes - from)); - } - -public: - - Copy_query_with_rewrite(THD *t, const char *s, size_t l, String *d) - :thd(t), src(s), src_len(l), from(0), dst(d) { } - - bool append(Rewritable_query_parameter *p) - { - if (copy_up_to(p->pos_in_query) || p->append_for_log(thd, dst)) - return true; - from= p->pos_in_query + p->len_in_query; - return false; - } - - bool finalize() - { return copy_up_to(src_len); } -}; - -struct st_dyncall_create_def -{ - Item *key, *value; - CHARSET_INFO *cs; - uint len, frac; - DYNAMIC_COLUMN_TYPE type; -}; - -typedef struct st_dyncall_create_def DYNCALL_CREATE_DEF; - - -typedef bool (Item::*Item_processor) (void *arg); -/* - Analyzer function - SYNOPSIS - argp in/out IN: Analysis parameter - OUT: Parameter to be passed to the transformer - - RETURN - TRUE Invoke the transformer - FALSE Don't do it - -*/ -typedef bool (Item::*Item_analyzer) (uchar **argp); -typedef Item* (Item::*Item_transformer) (THD *thd, uchar *arg); -typedef void (*Cond_traverser) (const Item *item, void *arg); -typedef bool (Item::*Pushdown_checker) (uchar *arg); - -struct st_cond_statistic; - -struct find_selective_predicates_list_processor_data -{ - TABLE *table; - List list; -}; - -class MY_LOCALE; - -class Item_equal; -class COND_EQUAL; - -class st_select_lex_unit; - -class Item_func_not; -class Item_splocal; - -/* Item::common_flags */ -/* Indicates that name of this Item autogenerated or set by user */ -#define IS_AUTO_GENERATED_NAME 1 -/* Indicates that this item is in CYCLE clause of WITH */ -#define IS_IN_WITH_CYCLE 2 - - -/** - String_copier that sends Item specific warnings. -*/ -class String_copier_for_item: public String_copier -{ - THD *m_thd; -public: - bool copy_with_warn(CHARSET_INFO *dstcs, String *dst, - CHARSET_INFO *srccs, const char *src, - uint32 src_length, uint32 nchars); - String_copier_for_item(THD *thd): m_thd(thd) { } -}; - - -/** - A helper class describing what kind of Item created a temporary field. - - If m_field is set, then the temporary field was created from Field - (e.g. when the Item was Item_field, or Item_ref pointing to Item_field) - - If m_default_field is set, then there is a usable DEFAULT value. - (e.g. when the Item is Item_field) - - If m_item_result_field is set, then the temporary field was created - from certain sub-types of Item_result_field (e.g. Item_func) - See create_tmp_field() in sql_select.cc for details. -*/ - -class Tmp_field_src -{ - Field *m_field; - Field *m_default_field; - Item_result_field *m_item_result_field; -public: - Tmp_field_src() - :m_field(0), - m_default_field(0), - m_item_result_field(0) - { } - Field *field() const { return m_field; } - Field *default_field() const { return m_default_field; } - Item_result_field *item_result_field() const { return m_item_result_field; } - void set_field(Field *field) { m_field= field; } - void set_default_field(Field *field) { m_default_field= field; } - void set_item_result_field(Item_result_field *item) - { m_item_result_field= item; } -}; - - -/** - Parameters for create_tmp_field_ex(). - See create_tmp_field() in sql_select.cc for details. -*/ - -class Tmp_field_param -{ - bool m_group; - bool m_modify_item; - bool m_table_cant_handle_bit_fields; - bool m_make_copy_field; -public: - Tmp_field_param(bool group, - bool modify_item, - bool table_cant_handle_bit_fields, - bool make_copy_field) - :m_group(group), - m_modify_item(modify_item), - m_table_cant_handle_bit_fields(table_cant_handle_bit_fields), - m_make_copy_field(make_copy_field) - { } - bool group() const { return m_group; } - bool modify_item() const { return m_modify_item; } - bool table_cant_handle_bit_fields() const - { return m_table_cant_handle_bit_fields; } - bool make_copy_field() const { return m_make_copy_field; } - void set_modify_item(bool to) { m_modify_item= to; } -}; - - -class Item_const -{ -public: - virtual ~Item_const() {} - virtual const Type_all_attributes *get_type_all_attributes_from_const() const= 0; - virtual bool const_is_null() const { return false; } - virtual const longlong *const_ptr_longlong() const { return NULL; } - virtual const double *const_ptr_double() const { return NULL; } - virtual const my_decimal *const_ptr_my_decimal() const { return NULL; } - virtual const MYSQL_TIME *const_ptr_mysql_time() const { return NULL; } - virtual const String *const_ptr_string() const { return NULL; } -}; - - -/****************************************************************************/ - -#define STOP_PTR ((void *) 1) - -class Item: public Value_source, - public Type_all_attributes -{ - /** - The index in the JOIN::join_tab array of the JOIN_TAB this Item is attached - to. Items are attached (or 'pushed') to JOIN_TABs during optimization by the - make_cond_for_table procedure. During query execution, this item is - evaluated when the join loop reaches the corresponding JOIN_TAB. - - If the value of join_tab_idx >= MAX_TABLES, this means that there is no - corresponding JOIN_TAB. - */ - uint join_tab_idx; - - static void *operator new(size_t size); - -public: - static void *operator new(size_t size, MEM_ROOT *mem_root) throw () - { return alloc_root(mem_root, size); } - static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); } - static void operator delete(void *ptr, MEM_ROOT *mem_root) {} - - enum Type {FIELD_ITEM= 0, FUNC_ITEM, SUM_FUNC_ITEM, - WINDOW_FUNC_ITEM, - /* - NOT NULL literal-alike constants, which do not change their - value during an SQL statement execution, but can optionally - change their value between statements: - - Item_literal - real NOT NULL constants - - Item_param - can change between statements - - Item_splocal - can change between statements - - Item_user_var_as_out_param - hack - Note, Item_user_var_as_out_param actually abuses the type code. - It should be moved out of the Item tree eventually. - */ - CONST_ITEM, - NULL_ITEM, // Item_null or Item_param bound to NULL - COPY_STR_ITEM, FIELD_AVG_ITEM, DEFAULT_VALUE_ITEM, - CONTEXTUALLY_TYPED_VALUE_ITEM, - PROC_ITEM,COND_ITEM, REF_ITEM, FIELD_STD_ITEM, - FIELD_VARIANCE_ITEM, INSERT_VALUE_ITEM, - SUBSELECT_ITEM, ROW_ITEM, CACHE_ITEM, TYPE_HOLDER, - PARAM_ITEM, TRIGGER_FIELD_ITEM, - EXPR_CACHE_ITEM}; - - enum cond_result { COND_UNDEF,COND_OK,COND_TRUE,COND_FALSE }; - - enum traverse_order { POSTFIX, PREFIX }; - - /* Cache of the result of is_expensive(). */ - int8 is_expensive_cache; - - /* Reuse size, only used by SP local variable assignment, otherwise 0 */ - uint rsize; - -protected: - /* - str_values's main purpose is to be used to cache the value in - save_in_field - */ - String str_value; - - SEL_TREE *get_mm_tree_for_const(RANGE_OPT_PARAM *param); - - /** - Create a field based on the exact data type handler. - */ - Field *create_table_field_from_handler(MEM_ROOT *root, TABLE *table) - { - const Type_handler *h= type_handler(); - return h->make_and_init_table_field(root, &name, - Record_addr(maybe_null), - *this, table); - } - /** - Create a field based on field_type of argument. - This is used to create a field for - - IFNULL(x,something) - - time functions - - prepared statement placeholders - - SP variables with data type references: DECLARE a TYPE OF t1.a; - @retval NULL error - @retval !NULL on success - */ - Field *tmp_table_field_from_field_type(MEM_ROOT *root, TABLE *table) - { - DBUG_ASSERT(is_fixed()); - const Type_handler *h= type_handler()->type_handler_for_tmp_table(this); - return h->make_and_init_table_field(root, &name, - Record_addr(maybe_null), - *this, table); - } - /** - Create a temporary field for a simple Item, which does not - need any special action after the field creation: - - is not an Item_field descendant (and not a reference to Item_field) - - is not an Item_result_field descendant - - does not need to copy any DEFAULT value to the result Field - - does not need to set Field::is_created_from_null_item for the result - See create_tmp_field_ex() for details on parameters and return values. - */ - Field *create_tmp_field_ex_simple(MEM_ROOT *root, - TABLE *table, - Tmp_field_src *src, - const Tmp_field_param *param) - { - DBUG_ASSERT(!param->make_copy_field()); - DBUG_ASSERT(!is_result_field()); - DBUG_ASSERT(type() != NULL_ITEM); - return tmp_table_field_from_field_type(root, table); - } - Field *create_tmp_field_int(MEM_ROOT *root, TABLE *table, - uint convert_int_length); - Field *tmp_table_field_from_field_type_maybe_null(MEM_ROOT *root, - TABLE *table, - Tmp_field_src *src, - const Tmp_field_param *param, - bool is_explicit_null); - - void raise_error_not_evaluable(); - void push_note_converted_to_negative_complement(THD *thd); - void push_note_converted_to_positive_complement(THD *thd); - - /* Helper methods, to get an Item value from another Item */ - double val_real_from_item(Item *item) - { - DBUG_ASSERT(is_fixed()); - double value= item->val_real(); - null_value= item->null_value; - return value; - } - longlong val_int_from_item(Item *item) - { - DBUG_ASSERT(is_fixed()); - longlong value= item->val_int(); - null_value= item->null_value; - return value; - } - String *val_str_from_item(Item *item, String *str) - { - DBUG_ASSERT(is_fixed()); - String *res= item->val_str(str); - if (res) - res->set_charset(collation.collation); - if ((null_value= item->null_value)) - res= NULL; - return res; - } - bool val_native_from_item(THD *thd, Item *item, Native *to) - { - DBUG_ASSERT(is_fixed()); - null_value= item->val_native(thd, to); - DBUG_ASSERT(null_value == item->null_value); - return null_value; - } - bool val_native_from_field(Field *field, Native *to) - { - if ((null_value= field->is_null())) - return true; - return (null_value= field->val_native(to)); - } - bool val_native_with_conversion_from_item(THD *thd, Item *item, Native *to, - const Type_handler *handler) - { - DBUG_ASSERT(is_fixed()); - return null_value= item->val_native_with_conversion(thd, to, handler); - } - my_decimal *val_decimal_from_item(Item *item, my_decimal *decimal_value) - { - DBUG_ASSERT(is_fixed()); - my_decimal *value= item->val_decimal(decimal_value); - if ((null_value= item->null_value)) - value= NULL; - return value; - } - bool get_date_from_item(THD *thd, Item *item, - MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - bool rc= item->get_date(thd, ltime, fuzzydate); - null_value= MY_TEST(rc || item->null_value); - return rc; - } -public: - - /* - Cache val_str() into the own buffer, e.g. to evaluate constant - expressions with subqueries in the ORDER/GROUP clauses. - */ - String *val_str() { return val_str(&str_value); } - virtual Item_func *get_item_func() { return NULL; } - - const MY_LOCALE *locale_from_val_str(); - - LEX_CSTRING name; /* Name of item */ - /* Original item name (if it was renamed)*/ - const char *orig_name; - /** - Intrusive list pointer for free list. If not null, points to the next - Item on some Query_arena's free list. For instance, stored procedures - have their own Query_arena's. - - @see Query_arena::free_list - */ - Item *next; - int marker; - bool maybe_null; /* If item may be null */ - bool in_rollup; /* If used in GROUP BY list - of a query with ROLLUP */ - bool null_value; /* if item is null */ - bool with_param; /* True if contains an SP parameter */ - bool with_window_func; /* True if item contains a window func */ - /** - True if any item except Item_sum contains a field. Set during parsing. - */ - bool with_field; - uint8 common_flags; - bool is_autogenerated_name() - { return (common_flags & IS_AUTO_GENERATED_NAME); } - // alloc & destruct is done as start of select on THD::mem_root - Item(THD *thd); - /* - Constructor used by Item_field, Item_ref & aggregate (sum) functions. - Used for duplicating lists in processing queries with temporary - tables - Also it used for Item_cond_and/Item_cond_or for creating - top AND/OR structure of WHERE clause to protect it of - optimisation changes in prepared statements - */ - Item(THD *thd, Item *item); - virtual ~Item() - { -#ifdef EXTRA_DEBUG - name.str= 0; - name.length= 0; -#endif - } /*lint -e1509 */ - void set_name(THD *thd, const char *str, size_t length, CHARSET_INFO *cs); - void set_name(THD *thd, String *str) - { - set_name(thd, str->ptr(), str->length(), str->charset()); - } - void set_name(THD *thd, const LEX_CSTRING &str, - CHARSET_INFO *cs= system_charset_info) - { - set_name(thd, str.str, str.length, cs); - } - void set_name_no_truncate(THD *thd, const char *str, uint length, - CHARSET_INFO *cs); - void init_make_send_field(Send_field *tmp_field, const Type_handler *h); - virtual void cleanup(); - virtual void make_send_field(THD *thd, Send_field *field); - - bool fix_fields_if_needed(THD *thd, Item **ref) - { - return is_fixed() ? false : fix_fields(thd, ref); - } - bool fix_fields_if_needed_for_scalar(THD *thd, Item **ref) - { - return fix_fields_if_needed(thd, ref) || check_cols(1); - } - bool fix_fields_if_needed_for_bool(THD *thd, Item **ref) - { - return fix_fields_if_needed_for_scalar(thd, ref); - } - bool fix_fields_if_needed_for_order_by(THD *thd, Item **ref) - { - return fix_fields_if_needed_for_scalar(thd, ref); - } - /* - By default we assume that an Item is fixed by the contstructor. - */ - virtual bool fix_fields(THD *, Item **) - { - /* - This should not normally be called, because usually before - fix_fields() we check is_fixed() to be false. - But historically we allow fix_fields() to be called for Items - who return basic_const_item()==true. - */ - DBUG_ASSERT(is_fixed()); - DBUG_ASSERT(basic_const_item()); - return false; - } - virtual bool is_fixed() const { return true; } - virtual void unfix_fields() - { - DBUG_ASSERT(0); - } - - /* - Fix after some tables has been pulled out. Basically re-calculate all - attributes that are dependent on the tables. - */ - virtual void fix_after_pullout(st_select_lex *new_parent, Item **ref, - bool merge) - {}; - - /* - This method should be used in case where we are sure that we do not need - complete fix_fields() procedure. - Usually this method is used by the optimizer when it has to create a new - item out of other already fixed items. For example, if the optimizer has - to create a new Item_func for an inferred equality whose left and right - parts are already fixed items. In some cases the optimizer cannot use - directly fixed items as the arguments of the created functional item, - but rather uses intermediate type conversion items. Then the method is - supposed to be applied recursively. - */ - virtual void quick_fix_field() - { - DBUG_ASSERT(0); - } - - bool save_in_value(THD *thd, struct st_value *value) - { - return type_handler()->Item_save_in_value(thd, this, value); - } - - /* Function returns 1 on overflow and -1 on fatal errors */ - int save_in_field_no_warnings(Field *field, bool no_conversions); - virtual int save_in_field(Field *field, bool no_conversions); - virtual bool save_in_param(THD *thd, Item_param *param); - virtual void save_org_in_field(Field *field, - fast_field_copier data - __attribute__ ((__unused__))) - { (void) save_in_field(field, 1); } - virtual fast_field_copier setup_fast_field_copier(Field *field) - { return NULL; } - virtual int save_safe_in_field(Field *field) - { return save_in_field(field, 1); } - virtual bool send(Protocol *protocol, st_value *buffer) - { - return type_handler()->Item_send(this, protocol, buffer); - } - virtual bool eq(const Item *, bool binary_cmp) const; - enum_field_types field_type() const - { - return type_handler()->field_type(); - } - virtual const Type_handler *type_handler() const= 0; - /** - Detects if an Item has a fixed data type which is known - even before fix_fields(). - Currently it's important only to find Items with a fixed boolean - data type. More item types can be marked in the future as having - a fixed data type (e.g. all literals, all fixed type functions, etc). - - @retval NULL if the Item type is not known before fix_fields() - @retval the pointer to the data type handler, if the data type - is known before fix_fields(). - */ - virtual const Type_handler *fixed_type_handler() const - { - return NULL; - } - const Type_handler *type_handler_for_comparison() const - { - return type_handler()->type_handler_for_comparison(); - } - virtual const Type_handler *real_type_handler() const - { - return type_handler(); - } - const Type_handler *cast_to_int_type_handler() const - { - return real_type_handler()->cast_to_int_type_handler(); - } - /* result_type() of an item specifies how the value should be returned */ - Item_result result_type() const - { - return type_handler()->result_type(); - } - /* ... while cmp_type() specifies how it should be compared */ - Item_result cmp_type() const - { - return type_handler()->cmp_type(); - } - const Type_handler *string_type_handler() const - { - return Type_handler::string_type_handler(max_length); - } - /* - Calculate the maximum length of an expression. - This method is used in data type aggregation for UNION, e.g.: - SELECT 'b' UNION SELECT COALESCE(double_10_3_field) FROM t1; - - The result is usually equal to max_length, except for some numeric types. - In case of the INT, FLOAT, DOUBLE data types Item::max_length and - Item::decimals are ignored, so the returned value depends only on the - data type itself. E.g. for an expression of the DOUBLE(10,3) data type, - the result is always 53 (length 10 and precision 3 do not matter). - - max_length is ignored for these numeric data types because the length limit - means only "expected maximum length", it is not a hard limit, so it does - not impose any data truncation. E.g. a column of the type INT(4) can - normally store big values up to 2147483647 without truncation. When we're - aggregating such column for UNION it's important to create a long enough - result column, not to lose any data. - - For detailed behaviour of various data types see implementations of - the corresponding Type_handler_xxx::max_display_length(). - - Note, Item_field::max_display_length() overrides this to get - max_display_length() from the underlying field. - */ - virtual uint32 max_display_length() const - { - return type_handler()->max_display_length(this); - } - const TYPELIB *get_typelib() const { return NULL; } - void set_maybe_null(bool maybe_null_arg) { maybe_null= maybe_null_arg; } - void set_typelib(const TYPELIB *typelib) - { - // Non-field Items (e.g. hybrid functions) never have ENUM/SET types yet. - DBUG_ASSERT(0); - } - Item_cache* get_cache(THD *thd) const - { - return type_handler()->Item_get_cache(thd, this); - } - virtual enum Type type() const =0; - bool is_of_type(Type t, Item_result cmp) const - { - return type() == t && cmp_type() == cmp; - } - /* - real_type() is the type of base item. This is same as type() for - most items, except Item_ref() and Item_cache_wrapper() where it - shows the type for the underlying item. - */ - virtual enum Type real_type() const { return type(); } - - /* - Return information about function monotonicity. See comment for - enum_monotonicity_info for details. This function can only be called - after fix_fields() call. - */ - virtual enum_monotonicity_info get_monotonicity_info() const - { return NON_MONOTONIC; } - - /* - Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$ const2" - - SYNOPSIS - val_int_endpoint() - left_endp FALSE <=> The interval is "x < const" or "x <= const" - TRUE <=> The interval is "x > const" or "x >= const" - - incl_endp IN FALSE <=> the comparison is '<' or '>' - TRUE <=> the comparison is '<=' or '>=' - OUT The same but for the "F(x) $CMP$ F(const)" comparison - - DESCRIPTION - This function is defined only for unary monotonic functions. The caller - supplies the source half-interval - - x $CMP$ const - - The value of const is supplied implicitly as the value this item's - argument, the form of $CMP$ comparison is specified through the - function's arguments. The calle returns the result interval - - F(x) $CMP2$ F(const) - - passing back F(const) as the return value, and the form of $CMP2$ - through the out parameter. NULL values are assumed to be comparable and - be less than any non-NULL values. - - RETURN - The output range bound, which equal to the value of val_int() - - If the value of the function is NULL then the bound is the - smallest possible value of LONGLONG_MIN - */ - virtual longlong val_int_endpoint(bool left_endp, bool *incl_endp) - { DBUG_ASSERT(0); return 0; } - - - /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */ - /* - Return double precision floating point representation of item. - - SYNOPSIS - val_real() - - RETURN - In case of NULL value return 0.0 and set null_value flag to TRUE. - If value is not null null_value flag will be reset to FALSE. - */ - virtual double val_real()=0; - Double_null to_double_null() - { - // val_real() must be caleed on a separate line. See to_longlong_null() - double nr= val_real(); - return Double_null(nr, null_value); - } - /* - Return integer representation of item. - - SYNOPSIS - val_int() - - RETURN - In case of NULL value return 0 and set null_value flag to TRUE. - If value is not null null_value flag will be reset to FALSE. - */ - virtual longlong val_int()=0; - Longlong_hybrid to_longlong_hybrid() - { - return Longlong_hybrid(val_int(), unsigned_flag); - } - Longlong_null to_longlong_null() - { - longlong nr= val_int(); - /* - C++ does not guarantee the order of parameter evaluation, - so to make sure "null_value" is passed to the constructor - after the val_int() call, val_int() is caled on a separate line. - */ - return Longlong_null(nr, null_value); - } - Longlong_hybrid_null to_longlong_hybrid_null() - { - return Longlong_hybrid_null(to_longlong_null(), unsigned_flag); - } - /** - Get a value for CAST(x AS SIGNED). - Too large positive unsigned integer values are converted - to negative complements. - Values of non-integer data types are adjusted to the SIGNED range. - */ - virtual longlong val_int_signed_typecast() - { - return cast_to_int_type_handler()->Item_val_int_signed_typecast(this); - } - longlong val_int_signed_typecast_from_str(); - /** - Get a value for CAST(x AS UNSIGNED). - Negative signed integer values are converted - to positive complements. - Values of non-integer data types are adjusted to the UNSIGNED range. - */ - virtual longlong val_int_unsigned_typecast() - { - return cast_to_int_type_handler()->Item_val_int_unsigned_typecast(this); - } - longlong val_int_unsigned_typecast_from_int(); - longlong val_int_unsigned_typecast_from_str(); - longlong val_int_unsigned_typecast_from_real(); - - /** - Get a value for CAST(x AS UNSIGNED). - Huge positive unsigned values are converted to negative complements. - */ - longlong val_int_signed_typecast_from_int(); - longlong val_int_signed_typecast_from_real(); - - /* - This is just a shortcut to avoid the cast. You should still use - unsigned_flag to check the sign of the item. - */ - inline ulonglong val_uint() { return (ulonglong) val_int(); } - - /* - Return string representation of this item object. - - SYNOPSIS - val_str() - str an allocated buffer this or any nested Item object can use to - store return value of this method. - - NOTE - The caller can modify the returned String, if it's not marked - "const" (with the String::mark_as_const() method). That means that - if the item returns its own internal buffer (e.g. tmp_value), it - *must* be marked "const" [1]. So normally it's preferable to - return the result value in the String, that was passed as an - argument. But, for example, SUBSTR() returns a String that simply - points into the buffer of SUBSTR()'s args[0]->val_str(). Such a - String is always "const", so it's ok to use tmp_value for that and - avoid reallocating/copying of the argument String. - - [1] consider SELECT CONCAT(f, ":", f) FROM (SELECT func() AS f); - here the return value of f() is used twice in the top-level - select, and if they share the same tmp_value buffer, modifying the - first one will implicitly modify the second too. - - RETURN - In case of NULL value return 0 (NULL pointer) and set null_value flag - to TRUE. - If value is not null null_value flag will be reset to FALSE. - */ - virtual String *val_str(String *str)=0; - - - bool val_native_with_conversion(THD *thd, Native *to, const Type_handler *th) - { - return th->Item_val_native_with_conversion(thd, this, to); - } - bool val_native_with_conversion_result(THD *thd, Native *to, - const Type_handler *th) - { - return th->Item_val_native_with_conversion_result(thd, this, to); - } - - virtual bool val_native(THD *thd, Native *to) - { - /* - The default implementation for the Items that do not need native format: - - Item_basic_value (default implementation) - - Item_copy - - Item_exists_subselect - - Item_sum_field - - Item_sum_or_func (default implementation) - - Item_proc - - Item_type_holder (as val_xxx() are never called for it); - - These hybrid Item types override val_native(): - - Item_field - - Item_param - - Item_sp_variable - - Item_ref - - Item_cache_wrapper - - Item_direct_ref - - Item_direct_view_ref - - Item_ref_null_helper - - Item_name_const - - Item_time_literal - - Item_sum_or_func - Note, these hybrid type Item_sum_or_func descendants - override the default implementation: - * Item_sum_hybrid - * Item_func_hybrid_field_type - * Item_func_min_max - * Item_func_sp - * Item_func_last_value - * Item_func_rollup_const - */ - DBUG_ASSERT(0); - return null_value= true; - } - virtual bool val_native_result(THD *thd, Native *to) - { - return val_native(thd, to); - } - - /* - Returns string representation of this item in ASCII format. - - SYNOPSIS - val_str_ascii() - str - similar to val_str(); - - NOTE - This method is introduced for performance optimization purposes. - - 1. val_str() result of some Items in string context - depends on @@character_set_results. - @@character_set_results can be set to a "real multibyte" character - set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples - below for convenience.) - - So the default string result of such functions - in these circumstances is real multi-byte character set, like UTF32. - - For example, all numbers in string context - return result in @@character_set_results: - - SELECT CONCAT(20010101); -> UTF32 - - We do sprintf() first (to get ASCII representation) - and then convert to UTF32; - - So these kind "data sources" can use ASCII representation - internally, but return multi-byte data only because - @@character_set_results wants so. - Therefore, conversion from ASCII to UTF32 is applied internally. - - - 2. Some other functions need in fact ASCII input. - - For example, - inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT(). - - Similar, fields of certain type, like DATE, TIME, - when you insert string data into them, expect in fact ASCII input. - If they get non-ASCII input, for example UTF32, they - convert input from UTF32 to ASCII, and then use ASCII - representation to do further processing. - - - 3. Now imagine we pass result of a data source of the first type - to a data destination of the second type. - - What happens: - a. data source converts data from ASCII to UTF32, because - @@character_set_results wants so and passes the result to - data destination. - b. data destination gets UTF32 string. - c. data destination converts UTF32 string to ASCII, - because it needs ASCII representation to be able to handle data - correctly. - - As a result we get two steps of unnecessary conversion: - From ASCII to UTF32, then from UTF32 to ASCII. - - A better way to handle these situations is to pass ASCII - representation directly from the source to the destination. - - This is why val_str_ascii() introduced. - - RETURN - Similar to val_str() - */ - virtual String *val_str_ascii(String *str); - - /* - Returns the result of val_str_ascii(), translating NULLs back - to empty strings (if MODE_EMPTY_STRING_IS_NULL is set). - */ - String *val_str_ascii_revert_empty_string_is_null(THD *thd, String *str); - - /* - Returns the val_str() value converted to the given character set. - */ - String *val_str(String *str, String *converter, CHARSET_INFO *to); - - virtual String *val_json(String *str) { return val_str(str); } - /* - Return decimal representation of item with fixed point. - - SYNOPSIS - val_decimal() - decimal_buffer buffer which can be used by Item for returning value - (but can be not) - - NOTE - Returned value should not be changed if it is not the same which was - passed via argument. - - RETURN - Return pointer on my_decimal (it can be other then passed via argument) - if value is not NULL (null_value flag will be reset to FALSE). - In case of NULL value it return 0 pointer and set null_value flag - to TRUE. - */ - virtual my_decimal *val_decimal(my_decimal *decimal_buffer)= 0; - /* - Return boolean value of item. - - RETURN - FALSE value is false or NULL - TRUE value is true (not equal to 0) - */ - virtual bool val_bool() - { - return type_handler()->Item_val_bool(this); - } - - bool eval_const_cond() - { - DBUG_ASSERT(const_item()); - DBUG_ASSERT(!is_expensive()); - return val_bool(); - } - - /* - save_val() is method of val_* family which stores value in the given - field. - */ - virtual void save_val(Field *to) { save_org_in_field(to, NULL); } - /* - save_result() is method of val*result() family which stores value in - the given field. - */ - virtual void save_result(Field *to) { save_val(to); } - /* Helper functions, see item_sum.cc */ - String *val_string_from_real(String *str); - String *val_string_from_int(String *str); - my_decimal *val_decimal_from_real(my_decimal *decimal_value); - my_decimal *val_decimal_from_int(my_decimal *decimal_value); - my_decimal *val_decimal_from_string(my_decimal *decimal_value); - longlong val_int_from_real() - { - DBUG_ASSERT(is_fixed()); - return Converter_double_to_longlong_with_warn(val_real(), false).result(); - } - longlong val_int_from_str(int *error); - - /* - Returns true if this item can be calculated during - value_depends_on_sql_mode() - */ - bool value_depends_on_sql_mode_const_item() - { - /* - Currently we use value_depends_on_sql_mode() only for virtual - column expressions. They should not contain any expensive items. - If we ever get a crash on the assert below, it means - check_vcol_func_processor() is badly implemented for this item. - */ - DBUG_ASSERT(!is_expensive()); - /* - It should return const_item() actually. - But for some reasons Item_field::const_item() returns true - at value_depends_on_sql_mode() call time. - This should be checked and fixed. - */ - return basic_const_item(); - } - virtual Sql_mode_dependency value_depends_on_sql_mode() const - { - return Sql_mode_dependency(); - } - - int save_time_in_field(Field *field, bool no_conversions); - int save_date_in_field(Field *field, bool no_conversions); - int save_str_in_field(Field *field, bool no_conversions); - int save_real_in_field(Field *field, bool no_conversions); - int save_int_in_field(Field *field, bool no_conversions); - int save_decimal_in_field(Field *field, bool no_conversions); - - int save_str_value_in_field(Field *field, String *result); - - virtual Field *get_tmp_table_field() { return 0; } - virtual Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table); - virtual const char *full_name() const { return name.str ? name.str : "???"; } - const char *field_name_or_null() - { return real_item()->type() == Item::FIELD_ITEM ? name.str : NULL; } - const TABLE_SHARE *field_table_or_null(); - - /* - *result* family of methods is analog of *val* family (see above) but - return value of result_field of item if it is present. If Item have not - result field, it return val(). This methods set null_value flag in same - way as *val* methods do it. - */ - virtual double val_result() { return val_real(); } - virtual longlong val_int_result() { return val_int(); } - virtual String *str_result(String* tmp) { return val_str(tmp); } - virtual my_decimal *val_decimal_result(my_decimal *val) - { return val_decimal(val); } - virtual bool val_bool_result() { return val_bool(); } - virtual bool is_null_result() { return is_null(); } - /* - Returns 1 if result type and collation for val_str() can change between - calls - */ - virtual bool dynamic_result() { return 0; } - /* - Bitmap of tables used by item - (note: if you need to check dependencies on individual columns, check out - class Field_enumerator) - */ - virtual table_map used_tables() const { return (table_map) 0L; } - virtual table_map all_used_tables() const { return used_tables(); } - /* - Return table map of tables that can't be NULL tables (tables that are - used in a context where if they would contain a NULL row generated - by a LEFT or RIGHT join, the item would not be true). - This expression is used on WHERE item to determinate if a LEFT JOIN can be - converted to a normal join. - Generally this function should return used_tables() if the function - would return null if any of the arguments are null - As this is only used in the beginning of optimization, the value don't - have to be updated in update_used_tables() - */ - virtual table_map not_null_tables() const { return used_tables(); } - /* - Returns true if this is a simple constant item like an integer, not - a constant expression. Used in the optimizer to propagate basic constants. - */ - virtual bool basic_const_item() const { return 0; } - /** - Determines if the expression is allowed as - a virtual column assignment source: - INSERT INTO t1 (vcol) VALUES (10) -> error - INSERT INTO t1 (vcol) VALUES (NULL) -> ok - */ - virtual bool vcol_assignment_allowed_value() const { return false; } - /** - Test if "this" is an ORDER position (rather than an expression). - Notes: - - can be called before fix_fields(). - - local SP variables (even of integer types) are always expressions, not - positions. (And they can't be used before fix_fields is called for them). - */ - virtual bool is_order_clause_position() const { return false; } - /* - Determines if the Item is an evaluable expression, that is - it can return a value, so we can call methods val_xxx(), get_date(), etc. - Most items are evaluable expressions. - Examples of non-evaluable expressions: - - Item_contextually_typed_value_specification (handling DEFAULT and IGNORE) - - Item_type_param bound to DEFAULT and IGNORE - We cannot call the mentioned methods for these Items, - their method implementations typically have DBUG_ASSERT(0). - */ - virtual bool is_evaluable_expression() const { return true; } - bool check_is_evaluable_expression_or_error() - { - if (is_evaluable_expression()) - return false; // Ok - raise_error_not_evaluable(); - return true; // Error - } - /* cloning of constant items (0 if it is not const) */ - virtual Item *clone_item(THD *thd) { return 0; } - /* deep copy item */ - virtual Item* build_clone(THD *thd) { return get_copy(thd); } - virtual cond_result eq_cmp_result() const { return COND_OK; } - inline uint float_length(uint decimals_par) const - { return decimals < FLOATING_POINT_DECIMALS ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;} - /* Returns total number of decimal digits */ - virtual uint decimal_precision() const - { - return type_handler()->Item_decimal_precision(this); - } - /* Returns the number of integer part digits only */ - inline int decimal_int_part() const - { return my_decimal_int_part(decimal_precision(), decimals); } - /* - Returns the number of fractional digits only. - NOT_FIXED_DEC is replaced to the maximum possible number - of fractional digits, taking into account the data type. - */ - uint decimal_scale() const - { - return type_handler()->Item_decimal_scale(this); - } - /* - Returns how many digits a divisor adds into a division result. - This is important when the integer part of the divisor can be 0. - In this example: - SELECT 1 / 0.000001; -> 1000000.0000 - the divisor adds 5 digits into the result precision. - - Currently this method only replaces NOT_FIXED_DEC to - TIME_SECOND_PART_DIGITS for temporal data types. - This method can be made virtual, to create more efficient (smaller) - data types for division results. - For example, in - SELECT 1/1.000001; - the divisor could provide no additional precision into the result, - so could any other items that are know to return a result - with non-zero integer part. - */ - uint divisor_precision_increment() const - { - return type_handler()->Item_divisor_precision_increment(this); - } - /** - TIME or DATETIME precision of the item: 0..6 - */ - uint time_precision(THD *thd) - { - return const_item() ? type_handler()->Item_time_precision(thd, this) : - MY_MIN(decimals, TIME_SECOND_PART_DIGITS); - } - uint datetime_precision(THD *thd) - { - return const_item() ? type_handler()->Item_datetime_precision(thd, this) : - MY_MIN(decimals, TIME_SECOND_PART_DIGITS); - } - virtual longlong val_int_min() const - { - return LONGLONG_MIN; - } - /* - Returns true if this is constant (during query execution, i.e. its value - will not change until next fix_fields) and its value is known. - */ - virtual bool const_item() const { return used_tables() == 0; } - /* - Returns true if this is constant but its value may be not known yet. - (Can be used for parameters of prep. stmts or of stored procedures.) - */ - virtual bool const_during_execution() const - { return (used_tables() & ~PARAM_TABLE_BIT) == 0; } - - /** - This method is used for to: - - to generate a view definition query (SELECT-statement); - - to generate a SQL-query for EXPLAIN EXTENDED; - - to generate a SQL-query to be shown in INFORMATION_SCHEMA; - - debug. - - For more information about view definition query, INFORMATION_SCHEMA - query and why they should be generated from the Item-tree, @see - mysql_register_view(). - */ - virtual enum precedence precedence() const { return DEFAULT_PRECEDENCE; } - enum precedence higher_precedence() const - { return (enum precedence)(precedence() + 1); } - void print_parenthesised(String *str, enum_query_type query_type, - enum precedence parent_prec); - /** - This helper is used to print expressions as a part of a table definition, - in particular for - - generated columns - - check constraints - - default value expressions - - partitioning expressions - */ - void print_for_table_def(String *str) - { - print_parenthesised(str, - (enum_query_type)(QT_ITEM_ORIGINAL_FUNC_NULLIF | - QT_ITEM_IDENT_SKIP_DB_NAMES | - QT_ITEM_IDENT_SKIP_TABLE_NAMES | - QT_NO_DATA_EXPANSION | - QT_TO_SYSTEM_CHARSET), - LOWEST_PRECEDENCE); - } - virtual void print(String *str, enum_query_type query_type); - - class Print: public String - { - public: - Print(Item *item, enum_query_type type) - { - item->print(this, type); - } - }; - - void print_item_w_name(String *str, enum_query_type query_type); - void print_value(String *str); - - virtual void update_used_tables() {} - virtual COND *build_equal_items(THD *thd, COND_EQUAL *inheited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref) - { - update_used_tables(); - DBUG_ASSERT(!cond_equal_ref || !cond_equal_ref[0]); - return this; - } - virtual COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, - bool top_level); - virtual void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, - table_map usable_tables, - SARGABLE_PARAM **sargables) - { - return; - } - /* - Make a select tree for all keys in a condition or a condition part - @param param Context - @param cond_ptr[OUT] Store a replacement item here if the condition - can be simplified, e.g.: - WHERE part1 OR part2 OR part3 - with one of the partN evaluating to SEL_TREE::ALWAYS. - */ - virtual SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); - /* - Checks whether the item is: - - a simple equality (field=field_item or field=constant_item), or - - a row equality - and form multiple equality predicates. - */ - virtual bool check_equality(THD *thd, COND_EQUAL *cond, List *eq_list) - { - return false; - } - virtual void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, uint flags) {} - /* Called for items that really have to be split */ - void split_sum_func2(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, - Item **ref, uint flags); - virtual bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)= 0; - bool get_date_from_int(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool get_date_from_real(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool get_date_from_string(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool get_time(THD *thd, MYSQL_TIME *ltime) - { return get_date(thd, ltime, Time::Options(thd)); } - // Get a DATE or DATETIME value in numeric packed format for comparison - virtual longlong val_datetime_packed(THD *thd) - { - return Datetime(thd, this, Datetime::Options_cmp(thd)).to_packed(); - } - // Get a TIME value in numeric packed format for comparison - virtual longlong val_time_packed(THD *thd) - { - return Time(thd, this, Time::Options_cmp(thd)).to_packed(); - } - longlong val_datetime_packed_result(THD *thd); - longlong val_time_packed_result(THD *thd); - - virtual bool get_date_result(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date(thd, ltime,fuzzydate); } - - /* - The method allows to determine nullness of a complex expression - without fully evaluating it, instead of calling val/result*() then - checking null_value. Used in Item_func_isnull/Item_func_isnotnull - and Item_sum_count. - Any new item which can be NULL must implement this method. - */ - virtual bool is_null() { return 0; } - - /* - Make sure the null_value member has a correct value. - */ - virtual void update_null_value () - { - return type_handler()->Item_update_null_value(this); - } - - /* - Inform the item that there will be no distinction between its result - being FALSE or NULL. - - NOTE - This function will be called for eg. Items that are top-level AND-parts - of the WHERE clause. Items implementing this function (currently - Item_cond_and and subquery-related item) enable special optimizations - when they are "top level". - */ - virtual void top_level_item() {} - /* - Return TRUE if it is item of top WHERE level (AND/OR) and it is - important, return FALSE if it not important (we can not use to simplify - calculations) or not top level - */ - virtual bool is_top_level_item() const - { return FALSE; /* not important */} - /* - return IN/ALL/ANY subquery or NULL - */ - virtual Item_in_subselect* get_IN_subquery() - { return NULL; /* in is not IN/ALL/ANY */ } - /* - set field of temporary table for Item which can be switched on temporary - table during query processing (grouping and so on) - */ - virtual bool is_result_field() { return 0; } - virtual bool is_json_type() { return false; } - virtual bool is_bool_literal() const { return false; } - /* This is to handle printing of default values */ - virtual bool need_parentheses_in_default() { return false; } - virtual void save_in_result_field(bool no_conversions) {} - /* - Data type format implied by the CHECK CONSTRAINT, - to be sent to the client in the result set metadata. - */ - virtual bool set_format_by_check_constraint(Send_field_extended_metadata *) - const - { - return false; - } - /* - set value of aggregate function in case of no rows for grouping were found - */ - virtual void no_rows_in_result() {} - virtual void restore_to_before_no_rows_in_result() {} - virtual Item *copy_or_same(THD *thd) { return this; } - virtual Item *copy_andor_structure(THD *thd) { return this; } - virtual Item *real_item() { return this; } - virtual Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); } - virtual Item *make_odbc_literal(THD *thd, const LEX_CSTRING *typestr) - { - return this; - } - - static CHARSET_INFO *default_charset(); - - CHARSET_INFO *charset_for_protocol(void) const - { - return type_handler()->charset_for_protocol(this); - }; - - virtual bool walk(Item_processor processor, bool walk_subquery, void *arg) - { - return (this->*processor)(arg); - } - - virtual Item* transform(THD *thd, Item_transformer transformer, uchar *arg); - - /* - This function performs a generic "compilation" of the Item tree. - The process of compilation is assumed to go as follows: - - compile() - { - if (this->*some_analyzer(...)) - { - compile children if any; - this->*some_transformer(...); - } - } - - i.e. analysis is performed top-down while transformation is done - bottom-up. - */ - virtual Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, - Item_transformer transformer, uchar *arg_t) - { - if ((this->*analyzer) (arg_p)) - return ((this->*transformer) (thd, arg_t)); - return 0; - } - - virtual void traverse_cond(Cond_traverser traverser, - void *arg, traverse_order order) - { - (*traverser)(this, arg); - } - - /*========= Item processors, to be used with Item::walk() ========*/ - virtual bool remove_dependence_processor(void *arg) { return 0; } - virtual bool cleanup_processor(void *arg); - virtual bool cleanup_excluding_fields_processor (void *arg) - { return cleanup_processor(arg); } - bool cleanup_excluding_immutables_processor (void *arg); - virtual bool cleanup_excluding_const_fields_processor (void *arg) - { return cleanup_processor(arg); } - virtual bool collect_item_field_processor(void *arg) { return 0; } - virtual bool unknown_splocal_processor(void *arg) { return 0; } - virtual bool collect_outer_ref_processor(void *arg) {return 0; } - virtual bool check_inner_refs_processor(void *arg) { return 0; } - virtual bool find_item_in_field_list_processor(void *arg) { return 0; } - virtual bool find_item_processor(void *arg); - virtual bool change_context_processor(void *arg) { return 0; } - virtual bool reset_query_id_processor(void *arg) { return 0; } - virtual bool is_expensive_processor(void *arg) { return 0; } - - // FIXME reduce the number of "add field to bitmap" processors - virtual bool add_field_to_set_processor(void *arg) { return 0; } - virtual bool register_field_in_read_map(void *arg) { return 0; } - virtual bool register_field_in_write_map(void *arg) { return 0; } - virtual bool register_field_in_bitmap(void *arg) { return 0; } - virtual bool update_table_bitmaps_processor(void *arg) { return 0; } - - virtual bool enumerate_field_refs_processor(void *arg) { return 0; } - virtual bool mark_as_eliminated_processor(void *arg) { return 0; } - virtual bool eliminate_subselect_processor(void *arg) { return 0; } - virtual bool set_fake_select_as_master_processor(void *arg) { return 0; } - virtual bool view_used_tables_processor(void *arg) { return 0; } - virtual bool eval_not_null_tables(void *arg) { return 0; } - virtual bool is_subquery_processor(void *arg) { return 0; } - virtual bool count_sargable_conds(void *arg) { return 0; } - virtual bool limit_index_condition_pushdown_processor(void *arg) { return 0; } - virtual bool exists2in_processor(void *arg) { return 0; } - virtual bool find_selective_predicates_list_processor(void *arg) { return 0; } - bool cleanup_is_expensive_cache_processor(void *arg) - { - is_expensive_cache= (int8)(-1); - return 0; - } - - /* - TRUE if the expression depends only on the table indicated by tab_map - or can be converted to such an exression using equalities. - Not to be used for AND/OR formulas. - */ - virtual bool excl_dep_on_table(table_map tab_map) { return false; } - /* - TRUE if the expression depends only on grouping fields of sel - or can be converted to such an expression using equalities. - It also checks if the expression doesn't contain stored procedures, - subqueries or randomly generated elements. - Not to be used for AND/OR formulas. - */ - virtual bool excl_dep_on_grouping_fields(st_select_lex *sel) - { return false; } - /* - TRUE if the expression depends only on fields from the left part of - IN subquery or can be converted to such an expression using equalities. - Not to be used for AND/OR formulas. - */ - virtual bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) - { return false; } - - virtual bool switch_to_nullable_fields_processor(void *arg) { return 0; } - virtual bool find_function_processor (void *arg) { return 0; } - /* - Check if a partition function is allowed - SYNOPSIS - check_partition_func_processor() - int_arg Ignored - RETURN VALUE - TRUE Partition function not accepted - FALSE Partition function accepted - - DESCRIPTION - check_partition_func_processor is used to check if a partition function - uses an allowed function. An allowed function will always ensure that - X=Y guarantees that also part_function(X)=part_function(Y) where X is - a set of partition fields and so is Y. The problems comes mainly from - character sets where two equal strings can be quite unequal. E.g. the - german character for double s is equal to 2 s. - - The default is that an item is not allowed - in a partition function. Allowed functions - can never depend on server version, they cannot depend on anything - related to the environment. They can also only depend on a set of - fields in the table itself. They cannot depend on other tables and - cannot contain any queries and cannot contain udf's or similar. - If a new Item class is defined and it inherits from a class that is - allowed in a partition function then it is very important to consider - whether this should be inherited to the new class. If not the function - below should be defined in the new Item class. - - The general behaviour is that most integer functions are allowed. - If the partition function contains any multi-byte collations then - the function check_part_func_fields will report an error on the - partition function independent of what functions are used. So the - only character sets allowed are single character collation and - even for those only a limited set of functions are allowed. The - problem with multi-byte collations is that almost every string - function has the ability to change things such that two strings - that are equal will not be equal after manipulated by a string - function. E.g. two strings one contains a double s, there is a - special german character that is equal to two s. Now assume a - string function removes one character at this place, then in - one the double s will be removed and in the other there will - still be one s remaining and the strings are no longer equal - and thus the partition function will not sort equal strings into - the same partitions. - - So the check if a partition function is valid is two steps. First - check that the field types are valid, next check that the partition - function is valid. The current set of partition functions valid - assumes that there are no multi-byte collations amongst the partition - fields. - */ - virtual bool check_partition_func_processor(void *arg) { return 1;} - virtual bool post_fix_fields_part_expr_processor(void *arg) { return 0; } - virtual bool rename_fields_processor(void *arg) { return 0; } - /* - TRUE if the function is knowingly TRUE or FALSE. - Not to be used for AND/OR formulas. - */ - virtual bool is_simplified_cond_processor(void *arg) { return false; } - - /** Processor used to check acceptability of an item in the defining - expression for a virtual column - - @param arg always ignored - - @retval 0 the item is accepted in the definition of a virtual column - @retval 1 otherwise - */ - struct vcol_func_processor_result - { - uint errors; /* Bits of possible errors */ - const char *name; /* Not supported function */ - Alter_info *alter_info; - vcol_func_processor_result() : - errors(0), name(NULL), alter_info(NULL) {} - }; - struct func_processor_rename - { - LEX_CSTRING db_name; - LEX_CSTRING table_name; - List fields; - }; - virtual bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(full_name(), arg, VCOL_IMPOSSIBLE); - } - virtual bool check_field_expression_processor(void *arg) { return 0; } - virtual bool check_func_default_processor(void *arg) { return 0; } - /* - Check if an expression value has allowed arguments, like DATE/DATETIME - for date functions. Also used by partitioning code to reject - timezone-dependent expressions in a (sub)partitioning function. - */ - virtual bool check_valid_arguments_processor(void *arg) { return 0; } - virtual bool update_vcol_processor(void *arg) { return 0; } - virtual bool set_fields_as_dependent_processor(void *arg) { return 0; } - /* - Find if some of the key parts of table keys (the reference on table is - passed as an argument) participate in the expression. - If there is some, sets a bit for this key in the proper key map. - */ - virtual bool check_index_dependence(void *arg) { return 0; } - /*============== End of Item processor list ======================*/ - - /* - Given a condition P from the WHERE clause or from an ON expression of - the processed SELECT S and a set of join tables from S marked in the - parameter 'allowed'={T} a call of P->find_not_null_fields({T}) has to - find the set fields {F} of the tables from 'allowed' such that: - - each field from {F} is declared as nullable - - each record of table t from {T} that contains NULL as the value for at - at least one field from {F} can be ignored when building the result set - for S - It is assumed here that the condition P is conjunctive and all its column - references belong to T. - - Examples: - CREATE TABLE t1 (a int, b int); - CREATE TABLE t2 (a int, b int); - - SELECT * FROM t1,t2 WHERE t1.a=t2.a and t1.b > 5; - A call of find_not_null_fields() for the whole WHERE condition and {t1,t2} - should find {t1.a,t1.b,t2.a} - - SELECT * FROM t1 LEFT JOIN ON (t1.a=t2.a and t2.a > t2.b); - A call of find_not_null_fields() for the ON expression and {t2} - should find {t2.a,t2.b} - - The function returns TRUE if it succeeds to prove that all records of - a table from {T} can be ignored. Otherwise it always returns FALSE. - - Example: - SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t2.a IS NULL; - A call of find_not_null_fields() for the WHERE condition and {t1,t2} - will return TRUE. - - It is assumed that the implementation of this virtual function saves - the info on the found set of fields in the structures associates with - tables from {T}. - */ - virtual bool find_not_null_fields(table_map allowed) { return false; } - - /* - Does not guarantee deep copy (depends on copy ctor). - See build_clone() for deep copy. - */ - virtual Item *get_copy(THD *thd)=0; - - bool cache_const_expr_analyzer(uchar **arg); - Item* cache_const_expr_transformer(THD *thd, uchar *arg); - - virtual Item* propagate_equal_fields(THD*, const Context &, COND_EQUAL *) - { - return this; - }; - - Item* propagate_equal_fields_and_change_item_tree(THD *thd, - const Context &ctx, - COND_EQUAL *cond, - Item **place); - - /* arg points to REPLACE_EQUAL_FIELD_ARG object */ - virtual Item *replace_equal_field(THD *thd, uchar *arg) { return this; } - - struct Collect_deps_prm - { - List *parameters; - /* unit from which we count nest_level */ - st_select_lex_unit *nest_level_base; - uint count; - int nest_level; - bool collect; - }; - - /* - For SP local variable returns pointer to Item representing its - current value and pointer to current Item otherwise. - */ - virtual Item *this_item() { return this; } - virtual const Item *this_item() const { return this; } - - /* - For SP local variable returns address of pointer to Item representing its - current value and pointer passed via parameter otherwise. - */ - virtual Item **this_item_addr(THD *thd, Item **addr_arg) { return addr_arg; } - - // Row emulation - virtual uint cols() const { return 1; } - virtual Item* element_index(uint i) { return this; } - virtual Item** addr(uint i) { return 0; } - virtual bool check_cols(uint c); - bool check_type_traditional_scalar(const char *opname) const; - bool check_type_scalar(const char *opname) const; - bool check_type_or_binary(const char *opname, const Type_handler *handler) const; - bool check_type_general_purpose_string(const char *opname) const; - bool check_type_can_return_int(const char *opname) const; - bool check_type_can_return_decimal(const char *opname) const; - bool check_type_can_return_real(const char *opname) const; - bool check_type_can_return_str(const char *opname) const; - bool check_type_can_return_text(const char *opname) const; - bool check_type_can_return_date(const char *opname) const; - bool check_type_can_return_time(const char *opname) const; - // It is not row => null inside is impossible - virtual bool null_inside() { return 0; } - // used in row subselects to get value of elements - virtual void bring_value() {} - - const Type_handler *type_handler_long_or_longlong() const - { - return Type_handler::type_handler_long_or_longlong(max_char_length(), - unsigned_flag); - } - - /** - Create field for temporary table. - @param table Temporary table - @param [OUT] src Who created the fields - @param param Create parameters - @retval NULL (on error) - @retval a pointer to a newly create Field (on success) - */ - virtual Field *create_tmp_field_ex(MEM_ROOT *root, - TABLE *table, - Tmp_field_src *src, - const Tmp_field_param *param)= 0; - virtual Item_field *field_for_view_update() { return 0; } - - virtual Item *neg_transformer(THD *thd) { return NULL; } - virtual Item *update_value_transformer(THD *thd, uchar *select_arg) - { return this; } - virtual Item *expr_cache_insert_transformer(THD *thd, uchar *unused) - { return this; } - virtual Item *derived_field_transformer_for_having(THD *thd, uchar *arg) - { return this; } - virtual Item *derived_field_transformer_for_where(THD *thd, uchar *arg) - { return this; } - virtual Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) - { return this; } - /* Now is not used. */ - virtual Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) - { return this; } - virtual Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) - { return this; } - virtual Item *in_predicate_to_in_subs_transformer(THD *thd, uchar *arg) - { return this; } - virtual Item *field_transformer_for_having_pushdown(THD *thd, uchar *arg) - { return this; } - virtual Item *multiple_equality_transformer(THD *thd, uchar *arg) - { return this; } - virtual bool expr_cache_is_needed(THD *) { return FALSE; } - virtual Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs); - bool needs_charset_converter(uint32 length, CHARSET_INFO *tocs) const - { - /* - This will return "true" if conversion happens: - - between two non-binary different character sets - - from "binary" to "unsafe" character set - (those that can have non-well-formed string) - - from "binary" to UCS2-alike character set with mbminlen>1, - when prefix left-padding is needed for an incomplete character: - binary 0xFF -> ucs2 0x00FF) - */ - if (!String::needs_conversion_on_storage(length, - collation.collation, tocs)) - return false; - /* - No needs to add converter if an "arg" is NUMERIC or DATETIME - value (which is pure ASCII) and at the same time target DTCollation - is ASCII-compatible. For example, no needs to rewrite: - SELECT * FROM t1 WHERE datetime_field = '2010-01-01'; - to - SELECT * FROM t1 WHERE CONVERT(datetime_field USING cs) = '2010-01-01'; - - TODO: avoid conversion of any values with - repertoire ASCII and 7bit-ASCII-compatible, - not only numeric/datetime origin. - */ - if (collation.derivation == DERIVATION_NUMERIC && - collation.repertoire == MY_REPERTOIRE_ASCII && - !(collation.collation->state & MY_CS_NONASCII) && - !(tocs->state & MY_CS_NONASCII)) - return false; - return true; - } - bool needs_charset_converter(CHARSET_INFO *tocs) - { - // Pass 1 as length to force conversion if tocs->mbminlen>1. - return needs_charset_converter(1, tocs); - } - Item *const_charset_converter(THD *thd, CHARSET_INFO *tocs, bool lossless, - const char *func_name); - Item *const_charset_converter(THD *thd, CHARSET_INFO *tocs, bool lossless) - { return const_charset_converter(thd, tocs, lossless, NULL); } - void delete_self() - { - cleanup(); - delete this; - } - - virtual const Item_const *get_item_const() const { return NULL; } - virtual Item_splocal *get_item_splocal() { return 0; } - virtual Rewritable_query_parameter *get_rewritable_query_parameter() - { return 0; } - - /* - Return Settable_routine_parameter interface of the Item. Return 0 - if this Item is not Settable_routine_parameter. - */ - virtual Settable_routine_parameter *get_settable_routine_parameter() - { - return 0; - } - - virtual Load_data_outvar *get_load_data_outvar() - { - return 0; - } - Load_data_outvar *get_load_data_outvar_or_error() - { - Load_data_outvar *dst= get_load_data_outvar(); - if (dst) - return dst; - my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), name.str); - return NULL; - } - - /** - Test whether an expression is expensive to compute. Used during - optimization to avoid computing expensive expressions during this - phase. Also used to force temp tables when sorting on expensive - functions. - @todo - Normally we should have a method: - cost Item::execution_cost(), - where 'cost' is either 'double' or some structure of various cost - parameters. - - @note - This function is now used to prevent evaluation of expensive subquery - predicates during the optimization phase. It also prevents evaluation - of predicates that are not computable at this moment. - */ - virtual bool is_expensive() - { - if (is_expensive_cache < 0) - is_expensive_cache= walk(&Item::is_expensive_processor, 0, NULL); - return MY_TEST(is_expensive_cache); - } - String *check_well_formed_result(String *str, bool send_error= 0); - bool eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs); - bool too_big_for_varchar() const - { return max_char_length() > CONVERT_IF_BIGGER_TO_BLOB; } - void fix_length_and_charset(uint32 max_char_length_arg, CHARSET_INFO *cs) - { - max_length= char_to_byte_length_safe(max_char_length_arg, cs->mbmaxlen); - collation.collation= cs; - } - void fix_char_length(size_t max_char_length_arg) - { - max_length= char_to_byte_length_safe(max_char_length_arg, - collation.collation->mbmaxlen); - } - /* - Return TRUE if the item points to a column of an outer-joined table. - */ - virtual bool is_outer_field() const { DBUG_ASSERT(is_fixed()); return FALSE; } - - /** - Checks if this item or any of its descendents contains a subquery. - This is a replacement of the former Item::has_subquery() and - Item::with_subselect. - */ - virtual bool with_subquery() const { DBUG_ASSERT(is_fixed()); return false; } - - virtual bool with_sum_func() const { return false; } - virtual With_sum_func_cache* get_with_sum_func_cache() { return NULL; } - - Item* set_expr_cache(THD *thd); - - virtual Item_equal *get_item_equal() { return NULL; } - virtual void set_item_equal(Item_equal *item_eq) {}; - virtual Item_equal *find_item_equal(COND_EQUAL *cond_equal) { return NULL; } - /** - Set the join tab index to the minimal (left-most) JOIN_TAB to which this - Item is attached. The number is an index is depth_first_tab() traversal - order. - */ - virtual void set_join_tab_idx(uint join_tab_idx_arg) - { - if (join_tab_idx_arg < join_tab_idx) - join_tab_idx= join_tab_idx_arg; - } - uint get_join_tab_idx() const { return join_tab_idx; } - - table_map view_used_tables(TABLE_LIST *view) - { - view->view_used_tables= 0; - walk(&Item::view_used_tables_processor, 0, view); - return view->view_used_tables; - } - - /** - Collect and add to the list cache parameters for this Item. - - @note Now implemented only for subqueries and in_optimizer, - if we need it for general function then this method should - be defined for Item_func. - */ - virtual void get_cache_parameters(List ¶meters) { }; - - virtual void mark_as_condition_AND_part(TABLE_LIST *embedding) {}; - - /* how much position should be reserved for Exists2In transformation */ - virtual uint exists2in_reserved_items() { return 0; }; - - virtual Item *neg(THD *thd); - - /** - Inform the item that it is located under a NOT, which is a top-level item. - */ - virtual void under_not(Item_func_not * upper - __attribute__((unused))) {}; - /* - If Item_field is wrapped in Item_direct_wrep remove this Item_direct_ref - wrapper. - */ - virtual Item *remove_item_direct_ref() { return this; } - - - void register_in(THD *thd); - - bool depends_only_on(table_map view_map) - { return marker & FULL_EXTRACTION_FL; } - int get_extraction_flag() - { return marker & EXTRACTION_MASK; } - void set_extraction_flag(int flags) - { - marker &= ~EXTRACTION_MASK; - marker|= flags; - } - void clear_extraction_flag() - { - marker &= ~EXTRACTION_MASK; - } - void check_pushable_cond(Pushdown_checker excl_dep_func, uchar *arg); - bool pushable_cond_checker_for_derived(uchar *arg) - { - return excl_dep_on_table(*((table_map *)arg)); - } - bool pushable_cond_checker_for_subquery(uchar *arg) - { - DBUG_ASSERT(((Item*) arg)->get_IN_subquery()); - return excl_dep_on_in_subq_left_part(((Item*)arg)->get_IN_subquery()); - } - Item *build_pushable_cond(THD *thd, - Pushdown_checker checker, - uchar *arg); - /* - Checks if this item depends only on the arg table - */ - bool pushable_equality_checker_for_derived(uchar *arg) - { - return (used_tables() == *((table_map *)arg)); - } - /* - Checks if this item consists in the left part of arg IN subquery predicate - */ - bool pushable_equality_checker_for_subquery(uchar *arg); -}; - -MEM_ROOT *get_thd_memroot(THD *thd); - -template -inline Item* get_item_copy (THD *thd, T* item) -{ - Item *copy= new (get_thd_memroot(thd)) T(*item); - if (likely(copy)) - copy->register_in(thd); - return copy; -} - - -#ifndef DBUG_OFF -/** - A helper class to print the data type and the value for an Item - in debug builds. -*/ -class DbugStringItemTypeValue: public StringBuffer<128> -{ -public: - DbugStringItemTypeValue(THD *thd, const Item *item) - { - append('('); - append(item->type_handler()->name().ptr()); - append(')'); - const_cast(item)->print(this, QT_EXPLAIN); - /* Append end \0 to allow usage of c_ptr() */ - append('\0'); - str_length--; - } -}; -#endif - -class With_sum_func_cache -{ -protected: - bool m_with_sum_func; // True if the owner item contains a sum func -public: - With_sum_func_cache() - :m_with_sum_func(false) - { } - With_sum_func_cache(const Item *a) - :m_with_sum_func(a->with_sum_func()) - { } - With_sum_func_cache(const Item *a, const Item *b) - :m_with_sum_func(a->with_sum_func() || b->with_sum_func()) - { } - With_sum_func_cache(const Item *a, const Item *b, const Item *c) - :m_with_sum_func(a->with_sum_func() || b->with_sum_func() || - c->with_sum_func()) - { } - With_sum_func_cache(const Item *a, const Item *b, const Item *c, - const Item *d) - :m_with_sum_func(a->with_sum_func() || b->with_sum_func() || - c->with_sum_func() || d->with_sum_func()) - { } - With_sum_func_cache(const Item *a, const Item *b, const Item *c, - const Item *d, const Item *e) - :m_with_sum_func(a->with_sum_func() || b->with_sum_func() || - c->with_sum_func() || d->with_sum_func() || - e->with_sum_func()) - { } - void set_with_sum_func() { m_with_sum_func= true; } - void reset_with_sum_func() { m_with_sum_func= false; } - void copy_with_sum_func(const Item *item) - { - m_with_sum_func= item->with_sum_func(); - } - void join_with_sum_func(const Item *item) - { - m_with_sum_func|= item->with_sum_func(); - } -}; - - -/* - This class is a replacement for the former member Item::with_subselect. - Determines if the descendant Item is a subselect or some of - its arguments is or contains a subselect. -*/ -class With_subquery_cache -{ -protected: - bool m_with_subquery; -public: - With_subquery_cache(): m_with_subquery(false) { } - void join(const Item *item) { m_with_subquery|= item->with_subquery(); } -}; - - -/** - Compare two Items for List::add_unique() -*/ - -bool cmp_items(Item *a, Item *b); - - -/** - Array of items, e.g. function or aggerate function arguments. -*/ -class Item_args -{ -protected: - Item **args, *tmp_arg[2]; - uint arg_count; - void set_arguments(THD *thd, List &list); - bool walk_args(Item_processor processor, bool walk_subquery, void *arg) - { - for (uint i= 0; i < arg_count; i++) - { - if (args[i]->walk(processor, walk_subquery, arg)) - return true; - } - return false; - } - bool transform_args(THD *thd, Item_transformer transformer, uchar *arg); - void propagate_equal_fields(THD *, const Item::Context &, COND_EQUAL *); - bool excl_dep_on_table(table_map tab_map) - { - for (uint i= 0; i < arg_count; i++) - { - if (args[i]->const_item()) - continue; - if (!args[i]->excl_dep_on_table(tab_map)) - return false; - } - return true; - } - bool excl_dep_on_grouping_fields(st_select_lex *sel); - bool eq(const Item_args *other, bool binary_cmp) const - { - for (uint i= 0; i < arg_count ; i++) - { - if (!args[i]->eq(other->args[i], binary_cmp)) - return false; - } - return true; - } - bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) - { - for (uint i= 0; i < arg_count; i++) - { - if (args[i]->const_item()) - continue; - if (!args[i]->excl_dep_on_in_subq_left_part(subq_pred)) - return false; - } - return true; - } -public: - Item_args(void) - :args(NULL), arg_count(0) - { } - Item_args(Item *a) - :args(tmp_arg), arg_count(1) - { - args[0]= a; - } - Item_args(Item *a, Item *b) - :args(tmp_arg), arg_count(2) - { - args[0]= a; args[1]= b; - } - Item_args(THD *thd, Item *a, Item *b, Item *c) - { - arg_count= 0; - if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 3)))) - { - arg_count= 3; - args[0]= a; args[1]= b; args[2]= c; - } - } - Item_args(THD *thd, Item *a, Item *b, Item *c, Item *d) - { - arg_count= 0; - if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 4)))) - { - arg_count= 4; - args[0]= a; args[1]= b; args[2]= c; args[3]= d; - } - } - Item_args(THD *thd, Item *a, Item *b, Item *c, Item *d, Item* e) - { - arg_count= 5; - if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 5)))) - { - arg_count= 5; - args[0]= a; args[1]= b; args[2]= c; args[3]= d; args[4]= e; - } - } - Item_args(THD *thd, List &list) - { - set_arguments(thd, list); - } - Item_args(THD *thd, const Item_args *other); - bool alloc_arguments(THD *thd, uint count); - void add_argument(Item *item) - { - args[arg_count++]= item; - } - /** - Extract row elements from the given position. - For example, for this input: (1,2),(3,4),(5,6) - pos=0 will extract (1,3,5) - pos=1 will extract (2,4,6) - @param thd - current thread, to allocate memory on its mem_root - @param rows - an array of compatible ROW-type items - @param pos - the element position to extract - */ - bool alloc_and_extract_row_elements(THD *thd, const Item_args *rows, uint pos) - { - DBUG_ASSERT(rows->argument_count() > 0); - DBUG_ASSERT(rows->arguments()[0]->cols() > pos); - if (alloc_arguments(thd, rows->argument_count())) - return true; - for (uint i= 0; i < rows->argument_count(); i++) - { - DBUG_ASSERT(rows->arguments()[0]->cols() == rows->arguments()[i]->cols()); - Item *arg= rows->arguments()[i]->element_index(pos); - add_argument(arg); - } - DBUG_ASSERT(argument_count() == rows->argument_count()); - return false; - } - inline Item **arguments() const { return args; } - inline uint argument_count() const { return arg_count; } - inline void remove_arguments() { arg_count=0; } - Sql_mode_dependency value_depends_on_sql_mode_bit_or() const; -}; - - -/* - Class to be used to enumerate all field references in an item tree. This - includes references to outside but not fields of the tables within a - subquery. - Suggested usage: - - class My_enumerator : public Field_enumerator - { - virtual void visit_field() { ... your actions ...} - } - - My_enumerator enumerator; - item->walk(Item::enumerate_field_refs_processor, ...,&enumerator); - - This is similar to Visitor pattern. -*/ - -class Field_enumerator -{ -public: - virtual void visit_field(Item_field *field)= 0; - virtual ~Field_enumerator() {}; /* purecov: inspected */ - Field_enumerator() {} /* Remove gcc warning */ -}; - -class Item_string; - - -class Item_fixed_hybrid: public Item -{ -public: - bool fixed; // If item was fixed with fix_fields -public: - Item_fixed_hybrid(THD *thd): Item(thd), fixed(false) - { } - Item_fixed_hybrid(THD *thd, Item_fixed_hybrid *item) - :Item(thd, item), fixed(item->fixed) - { } - bool fix_fields(THD *thd, Item **ref) - { - DBUG_ASSERT(!fixed); - fixed= true; - return false; - } - void cleanup() - { - Item::cleanup(); - fixed= false; - } - void quick_fix_field() { fixed= true; } - void unfix_fields() { fixed= false; } - bool is_fixed() const { return fixed; } -}; - - -/** - A common class for Item_basic_constant and Item_param -*/ -class Item_basic_value :public Item, - public Item_const -{ -protected: - // Value metadata, e.g. to make string processing easier - class Metadata: private MY_STRING_METADATA - { - public: - Metadata(const String *str) - { - my_string_metadata_get(this, str->charset(), str->ptr(), str->length()); - } - Metadata(const String *str, my_repertoire_t repertoire_arg) - { - MY_STRING_METADATA::repertoire= repertoire_arg; - MY_STRING_METADATA::char_length= str->numchars(); - } - my_repertoire_t repertoire() const - { - return MY_STRING_METADATA::repertoire; - } - size_t char_length() const { return MY_STRING_METADATA::char_length; } - }; - void fix_charset_and_length(CHARSET_INFO *cs, - Derivation dv, Metadata metadata) - { - /* - We have to have a different max_length than 'length' here to - ensure that we get the right length if we do use the item - to create a new table. In this case max_length must be the maximum - number of chars for a string of this type because we in Create_field:: - divide the max_length with mbmaxlen). - */ - collation.set(cs, dv, metadata.repertoire()); - fix_char_length(metadata.char_length()); - decimals= NOT_FIXED_DEC; - } - void fix_charset_and_length_from_str_value(const String &str, Derivation dv) - { - fix_charset_and_length(str.charset(), dv, Metadata(&str)); - } - Item_basic_value(THD *thd): Item(thd) {} -public: - Field *create_tmp_field_ex(MEM_ROOT *root, - TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - - /* - create_tmp_field_ex() for this type of Items is called for: - - CREATE TABLE ... SELECT - - In ORDER BY: SELECT max(a) FROM t1 GROUP BY a ORDER BY 'const'; - - In CURSORS: - DECLARE c CURSOR FOR SELECT 'test'; - OPEN c; - */ - return tmp_table_field_from_field_type_maybe_null(root, - table, src, param, - type() == Item::NULL_ITEM); - } - bool eq(const Item *item, bool binary_cmp) const; - const Type_all_attributes *get_type_all_attributes_from_const() const - { return this; } -}; - - -class Item_basic_constant :public Item_basic_value -{ -public: - Item_basic_constant(THD *thd): Item_basic_value(thd) {}; - bool check_vcol_func_processor(void *arg) { return false; } - const Item_const *get_item_const() const { return this; } - virtual Item_basic_constant *make_string_literal_concat(THD *thd, - const LEX_CSTRING *) - { - DBUG_ASSERT(0); - return this; - } -}; - - -/***************************************************************************** - The class is a base class for representation of stored routine variables in - the Item-hierarchy. There are the following kinds of SP-vars: - - local variables (Item_splocal); - - CASE expression (Item_case_expr); -*****************************************************************************/ - -class Item_sp_variable :public Item_fixed_hybrid -{ -protected: - /* - THD, which is stored in fix_fields() and is used in this_item() to avoid - current_thd use. - */ - THD *m_thd; - - bool fix_fields_from_item(THD *thd, Item **, const Item *); -public: - LEX_CSTRING m_name; - -public: -#ifdef DBUG_ASSERT_EXISTS - /* - Routine to which this Item_splocal belongs. Used for checking if correct - runtime context is used for variable handling. - */ - const sp_head *m_sp; -#endif - -public: - Item_sp_variable(THD *thd, const LEX_CSTRING *sp_var_name); - -public: - bool fix_fields(THD *thd, Item **)= 0; - - double val_real(); - longlong val_int(); - String *val_str(String *sp); - my_decimal *val_decimal(my_decimal *decimal_value); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool val_native(THD *thd, Native *to); - bool is_null(); - -public: - void make_send_field(THD *thd, Send_field *field); - - inline bool const_item() const; - - Field *create_tmp_field_ex(MEM_ROOT *root, - TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - return create_tmp_field_ex_simple(root, table, src, param); - } - inline int save_in_field(Field *field, bool no_conversions); - inline bool send(Protocol *protocol, st_value *buffer); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(m_name.str, arg, VCOL_IMPOSSIBLE); - } -}; - -/***************************************************************************** - Item_sp_variable inline implementation. -*****************************************************************************/ - -inline bool Item_sp_variable::const_item() const -{ - return TRUE; -} - -inline int Item_sp_variable::save_in_field(Field *field, bool no_conversions) -{ - return this_item()->save_in_field(field, no_conversions); -} - -inline bool Item_sp_variable::send(Protocol *protocol, st_value *buffer) -{ - return this_item()->send(protocol, buffer); -} - - -/***************************************************************************** - A reference to local SP variable (incl. reference to SP parameter), used in - runtime. -*****************************************************************************/ - -class Item_splocal :public Item_sp_variable, - private Settable_routine_parameter, - public Rewritable_query_parameter, - public Type_handler_hybrid_field_type -{ -protected: - const Sp_rcontext_handler *m_rcontext_handler; - - uint m_var_idx; - - Type m_type; - - bool append_value_for_log(THD *thd, String *str); - - sp_rcontext *get_rcontext(sp_rcontext *local_ctx) const; - Item_field *get_variable(sp_rcontext *ctx) const; - -public: - Item_splocal(THD *thd, const Sp_rcontext_handler *rh, - const LEX_CSTRING *sp_var_name, uint sp_var_idx, - const Type_handler *handler, - uint pos_in_q= 0, uint len_in_q= 0); - - bool fix_fields(THD *, Item **); - Item *this_item(); - const Item *this_item() const; - Item **this_item_addr(THD *thd, Item **); - - virtual void print(String *str, enum_query_type query_type); - -public: - inline const LEX_CSTRING *my_name() const; - - inline uint get_var_idx() const; - - inline enum Type type() const; - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - uint cols() const { return this_item()->cols(); } - Item* element_index(uint i) { return this_item()->element_index(i); } - Item** addr(uint i) { return this_item()->addr(i); } - bool check_cols(uint c); - -private: - bool set_value(THD *thd, sp_rcontext *ctx, Item **it); - -public: - Item_splocal *get_item_splocal() { return this; } - - Rewritable_query_parameter *get_rewritable_query_parameter() - { return this; } - - Settable_routine_parameter *get_settable_routine_parameter() - { return this; } - - bool append_for_log(THD *thd, String *str); - - Item *get_copy(THD *thd) { return 0; } - - /* - Override the inherited create_field_for_create_select(), - because we want to preserve the exact data type for: - DECLARE a1 INT; - DECLARE a2 TYPE OF t1.a2; - CREATE TABLE t1 AS SELECT a1, a2; - The inherited implementation would create a column - based on result_type(), which is less exact. - */ - Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) - { return create_table_field_from_handler(root, table); } - - bool is_valid_limit_clause_variable_with_error() const - { - /* - In case if the variable has an anchored data type, e.g.: - DECLARE a TYPE OF t1.a; - type_handler() is set to &type_handler_null and this - function detects such variable as not valid in LIMIT. - */ - if (type_handler()->is_limit_clause_valid_type()) - return true; - my_error(ER_WRONG_SPVAR_TYPE_IN_LIMIT, MYF(0)); - return false; - } -}; - - -/** - An Item_splocal variant whose data type becomes known only at - sp_rcontext creation time, e.g. "DECLARE var1 t1.col1%TYPE". -*/ -class Item_splocal_with_delayed_data_type: public Item_splocal -{ -public: - Item_splocal_with_delayed_data_type(THD *thd, - const Sp_rcontext_handler *rh, - const LEX_CSTRING *sp_var_name, - uint sp_var_idx, - uint pos_in_q, uint len_in_q) - :Item_splocal(thd, rh, sp_var_name, sp_var_idx, &type_handler_null, - pos_in_q, len_in_q) - { } -}; - - -/** - SP variables that are fields of a ROW. - DELCARE r ROW(a INT,b INT); - SELECT r.a; -- This is handled by Item_splocal_row_field -*/ -class Item_splocal_row_field :public Item_splocal -{ -protected: - LEX_CSTRING m_field_name; - uint m_field_idx; - bool set_value(THD *thd, sp_rcontext *ctx, Item **it); -public: - Item_splocal_row_field(THD *thd, - const Sp_rcontext_handler *rh, - const LEX_CSTRING *sp_var_name, - const LEX_CSTRING *sp_field_name, - uint sp_var_idx, uint sp_field_idx, - const Type_handler *handler, - uint pos_in_q= 0, uint len_in_q= 0) - :Item_splocal(thd, rh, sp_var_name, sp_var_idx, handler, pos_in_q, len_in_q), - m_field_name(*sp_field_name), - m_field_idx(sp_field_idx) - { } - bool fix_fields(THD *thd, Item **); - Item *this_item(); - const Item *this_item() const; - Item **this_item_addr(THD *thd, Item **); - bool append_for_log(THD *thd, String *str); - void print(String *str, enum_query_type query_type); -}; - - -class Item_splocal_row_field_by_name :public Item_splocal_row_field -{ - bool set_value(THD *thd, sp_rcontext *ctx, Item **it); -public: - Item_splocal_row_field_by_name(THD *thd, - const Sp_rcontext_handler *rh, - const LEX_CSTRING *sp_var_name, - const LEX_CSTRING *sp_field_name, - uint sp_var_idx, - const Type_handler *handler, - uint pos_in_q= 0, uint len_in_q= 0) - :Item_splocal_row_field(thd, rh, sp_var_name, sp_field_name, - sp_var_idx, 0 /* field index will be set later */, - handler, pos_in_q, len_in_q) - { } - bool fix_fields(THD *thd, Item **it); - void print(String *str, enum_query_type query_type); -}; - - -/***************************************************************************** - Item_splocal inline implementation. -*****************************************************************************/ - -inline const LEX_CSTRING *Item_splocal::my_name() const -{ - return &m_name; -} - -inline uint Item_splocal::get_var_idx() const -{ - return m_var_idx; -} - -inline enum Item::Type Item_splocal::type() const -{ - return m_type; -} - -/***************************************************************************** - A reference to case expression in SP, used in runtime. -*****************************************************************************/ - -class Item_case_expr :public Item_sp_variable -{ -public: - Item_case_expr(THD *thd, uint case_expr_id); - -public: - bool fix_fields(THD *thd, Item **); - Item *this_item(); - const Item *this_item() const; - Item **this_item_addr(THD *thd, Item **); - - inline enum Type type() const; - const Type_handler *type_handler() const { return this_item()->type_handler(); } - -public: - /* - NOTE: print() is intended to be used from views and for debug. - Item_case_expr can not occur in views, so here it is only for debug - purposes. - */ - virtual void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) { return 0; } - -private: - uint m_case_expr_id; -}; - -/***************************************************************************** - Item_case_expr inline implementation. -*****************************************************************************/ - -inline enum Item::Type Item_case_expr::type() const -{ - return this_item()->type(); -} - -/* - NAME_CONST(given_name, const_value). - This 'function' has all properties of the supplied const_value (which is - assumed to be a literal constant), and the name given_name. - - This is used to replace references to SP variables when we write PROCEDURE - statements into the binary log. - - TODO - Together with Item_splocal and Item::this_item() we can actually extract - common a base of this class and Item_splocal. Maybe it is possible to - extract a common base with class Item_ref, too. -*/ - -class Item_name_const : public Item_fixed_hybrid -{ - Item *value_item; - Item *name_item; -public: - Item_name_const(THD *thd, Item *name_arg, Item *val); - - bool fix_fields(THD *, Item **); - - enum Type type() const; - double val_real(); - longlong val_int(); - String *val_str(String *sp); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool val_native(THD *thd, Native *to); - bool is_null(); - virtual void print(String *str, enum_query_type query_type); - - const Type_handler *type_handler() const - { - return value_item->type_handler(); - } - - bool const_item() const - { - return TRUE; - } - - Field *create_tmp_field_ex(MEM_ROOT *root, - TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - /* - We can get to here when using a CURSOR for a query with NAME_CONST(): - DECLARE c CURSOR FOR SELECT NAME_CONST('x','y') FROM t1; - OPEN c; - */ - return tmp_table_field_from_field_type_maybe_null(root, table, src, param, - type() == Item::NULL_ITEM); - } - int save_in_field(Field *field, bool no_conversions) - { - return value_item->save_in_field(field, no_conversions); - } - - bool send(Protocol *protocol, st_value *buffer) - { - return value_item->send(protocol, buffer); - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function("name_const()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_literal: public Item_basic_constant -{ -public: - Item_literal(THD *thd): Item_basic_constant(thd) - { } - enum Type type() const { return CONST_ITEM; } - bool check_partition_func_processor(void *int_arg) { return false;} - bool const_item() const { return true; } - bool basic_const_item() const { return true; } -}; - - -class Item_num: public Item_literal -{ -public: - Item_num(THD *thd): Item_literal(thd) { collation= DTCollation_numeric(); } - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } -}; - -#define NO_CACHED_FIELD_INDEX ((uint)(-1)) - -class st_select_lex; - - -class Item_result_field :public Item_fixed_hybrid /* Item with result field */ -{ -protected: - Field *create_tmp_field_ex_from_handler(MEM_ROOT *root, TABLE *table, - Tmp_field_src *src, - const Tmp_field_param *param, - const Type_handler *h); -public: - Field *result_field; /* Save result here */ - Item_result_field(THD *thd): Item_fixed_hybrid(thd), result_field(0) {} - // Constructor used for Item_sum/Item_cond_and/or (see Item comment) - Item_result_field(THD *thd, Item_result_field *item): - Item_fixed_hybrid(thd, item), result_field(item->result_field) - {} - ~Item_result_field() {} /* Required with gcc 2.95 */ - Field *get_tmp_table_field() { return result_field; } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - DBUG_ASSERT(fixed); - const Type_handler *h= type_handler()->type_handler_for_tmp_table(this); - return create_tmp_field_ex_from_handler(root, table, src, param, h); - } - void get_tmp_field_src(Tmp_field_src *src, const Tmp_field_param *param); - /* - This implementation of used_tables() used by Item_avg_field and - Item_variance_field which work when only temporary table left, so theu - return table map of the temporary table. - */ - table_map used_tables() const { return 1; } - bool is_result_field() { return true; } - void save_in_result_field(bool no_conversions) - { - save_in_field(result_field, no_conversions); - } - void cleanup(); - bool check_vcol_func_processor(void *arg) { return FALSE;} -}; - - -class Item_ident :public Item_result_field -{ -protected: - /* - We have to store initial values of db_name, table_name and field_name - to be able to restore them during cleanup() because they can be - updated during fix_fields() to values from Field object and life-time - of those is shorter than life-time of Item_field. - */ - LEX_CSTRING orig_db_name; - LEX_CSTRING orig_table_name; - LEX_CSTRING orig_field_name; - - void undeclared_spvar_error() const; - -public: - Name_resolution_context *context; - LEX_CSTRING db_name; - LEX_CSTRING table_name; - LEX_CSTRING field_name; - bool alias_name_used; /* true if item was resolved against alias */ - /* - Cached value of index for this field in table->field array, used by prep. - stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX - if index value is not known. - */ - uint cached_field_index; - /* - Cached pointer to table which contains this field, used for the same reason - by prep. stmt. too in case then we have not-fully qualified field. - 0 - means no cached value. - */ - TABLE_LIST *cached_table; - st_select_lex *depended_from; - /* - Some Items resolved in another select should not be marked as dependency - of the subquery where they are. During normal name resolution, we check - this. Stored procedures and prepared statements first try to resolve an - ident item using a cached table reference and field position from the - previous query execution (cached_table/cached_field_index). If the - tables were not changed, the ident matches the table/field, and we have - faster resolution of the ident without looking through all tables and - fields in the query. But in this case, we can not check all conditions - about this ident item dependency, so we should cache the condition in - this variable. - */ - bool can_be_depended; - Item_ident(THD *thd, Name_resolution_context *context_arg, - const LEX_CSTRING &db_name_arg, const LEX_CSTRING &table_name_arg, - const LEX_CSTRING &field_name_arg); - Item_ident(THD *thd, Item_ident *item); - Item_ident(THD *thd, TABLE_LIST *view_arg, const LEX_CSTRING &field_name_arg); - const char *full_name() const; - void cleanup(); - st_select_lex *get_depended_from() const; - bool remove_dependence_processor(void * arg); - virtual void print(String *str, enum_query_type query_type); - virtual bool change_context_processor(void *cntx) - { context= (Name_resolution_context *)cntx; return FALSE; } - /** - Collect outer references - */ - virtual bool collect_outer_ref_processor(void *arg); - friend bool insert_fields(THD *thd, Name_resolution_context *context, - const char *db_name, - const char *table_name, List_iterator *it, - bool any_privileges); -}; - - -class Item_field :public Item_ident, - public Load_data_outvar -{ -protected: - void set_field(Field *field); -public: - Field *field; - Item_equal *item_equal; - /* - if any_privileges set to TRUE then here real effective privileges will - be stored - */ - privilege_t have_privileges; - /* field need any privileges (for VIEW creation) */ - bool any_privileges; - Item_field(THD *thd, Name_resolution_context *context_arg, - const LEX_CSTRING &db_arg, const LEX_CSTRING &table_name_arg, - const LEX_CSTRING &field_name_arg); - Item_field(THD *thd, Name_resolution_context *context_arg, - const LEX_CSTRING &field_name_arg) - :Item_field(thd, context_arg, null_clex_str, null_clex_str, field_name_arg) - { } - Item_field(THD *thd, Name_resolution_context *context_arg) - :Item_field(thd, context_arg, null_clex_str, null_clex_str, null_clex_str) - { } - /* - Constructor needed to process subselect with temporary tables (see Item) - */ - Item_field(THD *thd, Item_field *item); - /* - Constructor used inside setup_wild(), ensures that field, table, - and database names will live as long as Item_field (this is important - in prepared statements). - */ - Item_field(THD *thd, Name_resolution_context *context_arg, Field *field); - /* - If this constructor is used, fix_fields() won't work, because - db_name, table_name and column_name are unknown. It's necessary to call - reset_field() before fix_fields() for all fields created this way. - */ - Item_field(THD *thd, Field *field); - enum Type type() const { return FIELD_ITEM; } - bool eq(const Item *item, bool binary_cmp) const; - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal *); - String *val_str(String*); - void save_result(Field *to); - double val_result(); - longlong val_int_result(); - bool val_native(THD *thd, Native *to); - bool val_native_result(THD *thd, Native *to); - String *str_result(String* tmp); - my_decimal *val_decimal_result(my_decimal *); - bool val_bool_result(); - bool is_null_result(); - bool is_json_type(); - bool send(Protocol *protocol, st_value *buffer); - Load_data_outvar *get_load_data_outvar() - { - return this; - } - bool load_data_set_null(THD *thd, const Load_data_param *param) - { - return field->load_data_set_null(thd); - } - bool load_data_set_value(THD *thd, const char *pos, uint length, - const Load_data_param *param) - { - field->load_data_set_value(pos, length, param->charset()); - return false; - } - bool load_data_set_no_data(THD *thd, const Load_data_param *param); - void load_data_print_for_log_event(THD *thd, String *to) const; - bool load_data_add_outvar(THD *thd, Load_data_param *param) const - { - return param->add_outvar_field(thd, field); - } - uint load_data_fixed_length() const - { - return field->field_length; - } - void reset_field(Field *f); - bool fix_fields(THD *, Item **); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - void make_send_field(THD *thd, Send_field *tmp_field); - int save_in_field(Field *field,bool no_conversions); - void save_org_in_field(Field *field, fast_field_copier optimizer_data); - fast_field_copier setup_fast_field_copier(Field *field); - table_map used_tables() const; - table_map all_used_tables() const; - const Type_handler *type_handler() const - { - const Type_handler *handler= field->type_handler(); - return handler->type_handler_for_item_field(); - } - const Type_handler *real_type_handler() const - { - if (field->is_created_from_null_item) - return &type_handler_null; - return field->type_handler(); - } - Field *create_tmp_field_from_item_field(MEM_ROOT *root, TABLE *new_table, - Item_ref *orig_item, - const Tmp_field_param *param); - Field *create_tmp_field_ex(MEM_ROOT *root, - TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param); - const TYPELIB *get_typelib() const { return field->get_typelib(); } - enum_monotonicity_info get_monotonicity_info() const - { - return MONOTONIC_STRICT_INCREASING; - } - Sql_mode_dependency value_depends_on_sql_mode() const - { - return Sql_mode_dependency(0, field->value_depends_on_sql_mode()); - } - longlong val_int_endpoint(bool left_endp, bool *incl_endp); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool get_date_result(THD *thd, MYSQL_TIME *ltime,date_mode_t fuzzydate); - longlong val_datetime_packed(THD *thd); - longlong val_time_packed(THD *thd); - bool is_null() { return field->is_null(); } - void update_null_value(); - void update_table_bitmaps() - { - if (field && field->table) - { - TABLE *tab= field->table; - tab->covering_keys.intersect(field->part_of_key); - if (tab->read_set) - tab->mark_column_with_deps(field); - } - } - void update_used_tables() - { - update_table_bitmaps(); - } - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref) - { - /* - normilize_cond() replaced all conditions of type - WHERE/HAVING field - to: - WHERE/HAVING field<>0 - By the time of a build_equal_items() call, all such conditions should - already be replaced. No Item_field are possible. - Note, some Item_field derivants are still possible. - Item_insert_value: - SELECT * FROM t1 WHERE VALUES(a); - Item_default_value: - SELECT * FROM t1 WHERE DEFAULT(a); - */ - DBUG_ASSERT(type() != FIELD_ITEM); - return Item_ident::build_equal_items(thd, inherited, link_item_fields, - cond_equal_ref); - } - bool is_result_field() { return false; } - void save_in_result_field(bool no_conversions); - Item *get_tmp_table_item(THD *thd); - bool find_not_null_fields(table_map allowed); - bool collect_item_field_processor(void * arg); - bool unknown_splocal_processor(void *arg); - bool add_field_to_set_processor(void * arg); - bool find_item_in_field_list_processor(void *arg); - bool register_field_in_read_map(void *arg); - bool register_field_in_write_map(void *arg); - bool register_field_in_bitmap(void *arg); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool post_fix_fields_part_expr_processor(void *bool_arg); - bool check_valid_arguments_processor(void *bool_arg); - bool check_field_expression_processor(void *arg); - bool enumerate_field_refs_processor(void *arg); - bool update_table_bitmaps_processor(void *arg); - bool switch_to_nullable_fields_processor(void *arg); - bool update_vcol_processor(void *arg); - bool rename_fields_processor(void *arg); - bool check_vcol_func_processor(void *arg); - bool set_fields_as_dependent_processor(void *arg) - { - if (!(used_tables() & OUTER_REF_TABLE_BIT)) - { - depended_from= (st_select_lex *) arg; - item_equal= NULL; - } - return 0; - } - void cleanup(); - Item_equal *get_item_equal() { return item_equal; } - void set_item_equal(Item_equal *item_eq) { item_equal= item_eq; } - Item_equal *find_item_equal(COND_EQUAL *cond_equal); - Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *); - Item *replace_equal_field(THD *thd, uchar *arg); - uint32 max_display_length() const { return field->max_display_length(); } - Item_field *field_for_view_update() { return this; } - int fix_outer_field(THD *thd, Field **field, Item **reference); - virtual Item *update_value_transformer(THD *thd, uchar *select_arg); - Item *derived_field_transformer_for_having(THD *thd, uchar *arg); - Item *derived_field_transformer_for_where(THD *thd, uchar *arg); - Item *grouping_field_transformer_for_where(THD *thd, uchar *arg); - Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg); - Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg); - virtual void print(String *str, enum_query_type query_type); - bool excl_dep_on_table(table_map tab_map); - bool excl_dep_on_grouping_fields(st_select_lex *sel); - bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred); - bool cleanup_excluding_fields_processor(void *arg) - { return field ? 0 : cleanup_processor(arg); } - bool cleanup_excluding_const_fields_processor(void *arg) - { return field && const_item() ? 0 : cleanup_processor(arg); } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - bool is_outer_field() const - { - DBUG_ASSERT(fixed); - return field->table->pos_in_table_list->outer_join; - } - bool check_index_dependence(void *arg); - friend class Item_default_value; - friend class Item_insert_value; - friend class st_select_lex_unit; -}; - - -/** - Item_field for the ROW data type -*/ -class Item_field_row: public Item_field, - public Item_args -{ -public: - Item_field_row(THD *thd, Field *field) - :Item_field(thd, field), - Item_args() - { } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - - const Type_handler *type_handler() const { return &type_handler_row; } - uint cols() const { return arg_count; } - Item* element_index(uint i) { return arg_count ? args[i] : this; } - Item** addr(uint i) { return arg_count ? args + i : NULL; } - bool check_cols(uint c) - { - if (cols() != c) - { - my_error(ER_OPERAND_COLUMNS, MYF(0), c); - return true; - } - return false; - } - bool row_create_items(THD *thd, List *list); -}; - - -/* - @brief - Item_temptable_field is the same as Item_field, except that print() - continues to work even if the table has been dropped. - - @detail - - We need this item for "ANALYZE statement" feature. Query execution has - these steps: - - 1. Run the query. - 2. Cleanup starts. Temporary tables are destroyed - 3. print "ANALYZE statement" output, if needed - 4. Call close_thread_table() for regular tables. - - Step #4 is done after step #3, so "ANALYZE stmt" has no problem printing - Item_field objects that refer to regular tables. - - However, Step #3 is done after Step #2. Attempt to print Item_field objects - that refer to temporary tables will cause access to freed memory. - - To resolve this, we use Item_temptable_field to refer to items in temporary - (work) tables. -*/ - -class Item_temptable_field :public Item_field -{ -public: - Item_temptable_field(THD *thd, Name_resolution_context *context_arg, Field *field) - : Item_field(thd, context_arg, field) {} - - Item_temptable_field(THD *thd, Field *field) - : Item_field(thd, field) {} - - Item_temptable_field(THD *thd, Item_field *item) : Item_field(thd, item) {}; - - virtual void print(String *str, enum_query_type query_type); -}; - - -class Item_null :public Item_basic_constant -{ -public: - Item_null(THD *thd, const char *name_par=0, CHARSET_INFO *cs= &my_charset_bin): - Item_basic_constant(thd) - { - maybe_null= null_value= TRUE; - max_length= 0; - name.str= name_par ? name_par : "NULL"; - name.length= strlen(name.str); - collation.set(cs, DERIVATION_IGNORABLE, MY_REPERTOIRE_ASCII); - } - enum Type type() const { return NULL_ITEM; } - bool vcol_assignment_allowed_value() const { return true; } - double val_real(); - longlong val_int(); - String *val_str(String *str); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - longlong val_datetime_packed(THD *); - longlong val_time_packed(THD *); - int save_in_field(Field *field, bool no_conversions); - int save_safe_in_field(Field *field); - bool send(Protocol *protocol, st_value *buffer); - const Type_handler *type_handler() const { return &type_handler_null; } - bool basic_const_item() const { return 1; } - Item *clone_item(THD *thd); - bool const_is_null() const { return true; } - bool is_null() { return 1; } - - virtual inline void print(String *str, enum_query_type query_type) - { - str->append(STRING_WITH_LEN("NULL")); - } - - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - Item_basic_constant *make_string_literal_concat(THD *thd, - const LEX_CSTRING *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_null_result :public Item_null -{ -public: - Field *result_field; - Item_null_result(THD *thd): Item_null(thd), result_field(0) {} - bool is_result_field() { return result_field != 0; } - const Type_handler *type_handler() const - { - if (result_field) - return result_field->type_handler(); - return &type_handler_null; - } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - DBUG_ASSERT(0); - return NULL; - } - void save_in_result_field(bool no_conversions) - { - save_in_field(result_field, no_conversions); - } - bool check_partition_func_processor(void *int_arg) {return TRUE;} - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(full_name(), arg, VCOL_IMPOSSIBLE); - } -}; - -/* - Item represents one placeholder ('?') of prepared statement - - Notes: - Item_param::field_type() is used when this item is in a temporary table. - This is NOT placeholder metadata sent to client, as this value - is assigned after sending metadata (in setup_one_conversion_function). - For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both - in result set and placeholders metadata, no matter what type you will - supply for this placeholder in mysql_stmt_execute. - - Item_param has two Type_handler pointers, - which can point to different handlers: - - 1. In the Type_handler_hybrid_field_type member - It's initialized in: - - Item_param::setup_conversion(), for client-server PS protocol, - according to the bind type. - - Item_param::set_from_item(), for EXECUTE and EXECUTE IMMEDIATE, - according to the actual parameter data type. - - 2. In the "value" member. - It's initialized in: - - Item_param::set_param_func(), for client-server PS protocol. - - Item_param::set_from_item(), for EXECUTE and EXECUTE IMMEDIATE. -*/ - -class Item_param :public Item_basic_value, - private Settable_routine_parameter, - public Rewritable_query_parameter, - private Type_handler_hybrid_field_type -{ - /* - NO_VALUE is a special value meaning that the parameter has not been - assigned yet. Item_param::state is assigned to NO_VALUE in constructor - and is used at prepare time. - - 1. At prepare time - Item_param::fix_fields() sets "fixed" to true, - but as Item_param::state is still NO_VALUE, - Item_param::basic_const_item() returns false. This prevents various - optimizations to happen at prepare time fix_fields(). - For example, in this query: - PREPARE stmt FROM 'SELECT FORMAT(10000,2,?)'; - Item_param::basic_const_item() is tested from - Item_func_format::fix_length_and_dec(). - - 2. At execute time: - When Item_param gets a value - (or a pseudo-value like DEFAULT_VALUE or IGNORE_VALUE): - - Item_param::state changes from NO_VALUE to something else - - Item_param::fixed is changed to true - All Item_param::set_xxx() make sure to do so. - In the state with an assigned value: - - Item_param::basic_const_item() returns true - - Item::type() returns NULL_ITEM or CONST_ITEM, - depending on the value assigned. - So in this state Item_param behaves in many cases like a literal. - - When Item_param::cleanup() is called: - - Item_param::state does not change - - Item_param::fixed changes to false - Note, this puts Item_param into an inconsistent state: - - Item_param::basic_const_item() still returns "true" - - Item_param::type() still pretends to be a basic constant Item - Both are not expected in combination with fixed==false. - However, these methods are not really called in this state, - see asserts in Item_param::basic_const_item() and Item_param::type(). - - When Item_param::reset() is called: - - Item_param::state changes to NO_VALUE - - Item_param::fixed changes to false - */ - enum enum_item_param_state - { - NO_VALUE, NULL_VALUE, SHORT_DATA_VALUE, LONG_DATA_VALUE, - DEFAULT_VALUE, IGNORE_VALUE - } state; - - void fix_temporal(uint32 max_length_arg, uint decimals_arg); - - struct CONVERSION_INFO - { - /* - Character sets conversion info for string values. - Character sets of client and connection defined at bind time are used - for all conversions, even if one of them is later changed (i.e. - between subsequent calls to mysql_stmt_execute). - */ - CHARSET_INFO *character_set_client; - CHARSET_INFO *character_set_of_placeholder; - /* - This points at character set of connection if conversion - to it is required (i. e. if placeholder typecode is not BLOB). - Otherwise it's equal to character_set_client (to simplify - check in convert_str_value()). - */ - CHARSET_INFO *final_character_set_of_str_value; - private: - bool needs_conversion() const - { - return final_character_set_of_str_value != - character_set_of_placeholder; - } - bool convert(THD *thd, String *str); - public: - void set(THD *thd, CHARSET_INFO *cs); - bool convert_if_needed(THD *thd, String *str) - { - /* - Check is so simple because all charsets were set up properly - in setup_one_conversion_function, where typecode of - placeholder was also taken into account: the variables are different - here only if conversion is really necessary. - */ - if (needs_conversion()) - return convert(thd, str); - str->set_charset(final_character_set_of_str_value); - return false; - } - }; - - bool m_empty_string_is_null; - - class PValue_simple - { - public: - union - { - longlong integer; - double real; - CONVERSION_INFO cs_info; - MYSQL_TIME time; - }; - void swap(PValue_simple &other) - { - swap_variables(PValue_simple, *this, other); - } - }; - - class PValue: public Type_handler_hybrid_field_type, - public PValue_simple, - public Value_source - { - public: - PValue(): Type_handler_hybrid_field_type(&type_handler_null) {} - my_decimal m_decimal; - String m_string; - /* - A buffer for string and long data values. Historically all allocated - values returned from val_str() were treated as eligible to - modification. I. e. in some cases Item_func_concat can append it's - second argument to return value of the first one. Because of that we - can't return the original buffer holding string data from val_str(), - and have to have one buffer for data and another just pointing to - the data. This is the latter one and it's returned from val_str(). - Can not be declared inside the union as it's not a POD type. - */ - String m_string_ptr; - - void swap(PValue &other) - { - Type_handler_hybrid_field_type::swap(other); - PValue_simple::swap(other); - m_decimal.swap(other.m_decimal); - m_string.swap(other.m_string); - m_string_ptr.swap(other.m_string_ptr); - } - double val_real() const; - longlong val_int(const Type_std_attributes *attr) const; - my_decimal *val_decimal(my_decimal *dec, const Type_std_attributes *attr); - String *val_str(String *str, const Type_std_attributes *attr); - }; - - PValue value; - - const String *value_query_val_str(THD *thd, String* str) const; - Item *value_clone_item(THD *thd); - bool is_evaluable_expression() const; - bool can_return_value() const; - -public: - /* - Used for bulk protocol only. - */ - enum enum_indicator_type indicator; - - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - - bool vcol_assignment_allowed_value() const - { - switch (state) { - case NULL_VALUE: - case DEFAULT_VALUE: - case IGNORE_VALUE: - return true; - case NO_VALUE: - case SHORT_DATA_VALUE: - case LONG_DATA_VALUE: - break; - } - return false; - } - - Item_param(THD *thd, const LEX_CSTRING *name_arg, - uint pos_in_query_arg, uint len_in_query_arg); - - enum Type type() const - { - // Don't pretend to be a constant unless value for this item is set. - switch (state) { - case NO_VALUE: return PARAM_ITEM; - case NULL_VALUE: return NULL_ITEM; - case SHORT_DATA_VALUE: return CONST_ITEM; - case LONG_DATA_VALUE: return CONST_ITEM; - case DEFAULT_VALUE: return PARAM_ITEM; - case IGNORE_VALUE: return PARAM_ITEM; - } - DBUG_ASSERT(0); - return PARAM_ITEM; - } - - bool is_order_clause_position() const - { - return state == SHORT_DATA_VALUE && - type_handler()->is_order_clause_position_type(); - } - - const Item_const *get_item_const() const - { - switch (state) { - case SHORT_DATA_VALUE: - case LONG_DATA_VALUE: - case NULL_VALUE: - return this; - case IGNORE_VALUE: - case DEFAULT_VALUE: - case NO_VALUE: - break; - } - return NULL; - } - - bool const_is_null() const { return state == NULL_VALUE; } - bool can_return_const_value(Item_result type) const - { - return can_return_value() && - value.type_handler()->cmp_type() == type && - type_handler()->cmp_type() == type; - } - const longlong *const_ptr_longlong() const - { return can_return_const_value(INT_RESULT) ? &value.integer : NULL; } - const double *const_ptr_double() const - { return can_return_const_value(REAL_RESULT) ? &value.real : NULL; } - const my_decimal *const_ptr_my_decimal() const - { return can_return_const_value(DECIMAL_RESULT) ? &value.m_decimal : NULL; } - const MYSQL_TIME *const_ptr_mysql_time() const - { return can_return_const_value(TIME_RESULT) ? &value.time : NULL; } - const String *const_ptr_string() const - { return can_return_const_value(STRING_RESULT) ? &value.m_string : NULL; } - - double val_real() - { - return can_return_value() ? value.val_real() : 0e0; - } - longlong val_int() - { - return can_return_value() ? value.val_int(this) : 0; - } - my_decimal *val_decimal(my_decimal *dec) - { - return can_return_value() ? value.val_decimal(dec, this) : NULL; - } - String *val_str(String *str) - { - return can_return_value() ? value.val_str(str, this) : NULL; - } - bool get_date(THD *thd, MYSQL_TIME *tm, date_mode_t fuzzydate); - bool val_native(THD *thd, Native *to) - { - return Item_param::type_handler()->Item_param_val_native(thd, this, to); - } - - int save_in_field(Field *field, bool no_conversions); - - void set_default(); - void set_ignore(); - void set_null(); - void set_int(longlong i, uint32 max_length_arg); - void set_double(double i); - void set_decimal(const char *str, ulong length); - void set_decimal(const my_decimal *dv, bool unsigned_arg); - bool set_str(const char *str, ulong length, - CHARSET_INFO *fromcs, CHARSET_INFO *tocs); - bool set_longdata(const char *str, ulong length); - void set_time(MYSQL_TIME *tm, timestamp_type type, uint32 max_length_arg); - void set_time(const MYSQL_TIME *tm, uint32 max_length_arg, uint decimals_arg); - bool set_from_item(THD *thd, Item *item); - void reset(); - - void set_param_tiny(uchar **pos, ulong len); - void set_param_short(uchar **pos, ulong len); - void set_param_int32(uchar **pos, ulong len); - void set_param_int64(uchar **pos, ulong len); - void set_param_float(uchar **pos, ulong len); - void set_param_double(uchar **pos, ulong len); - void set_param_decimal(uchar **pos, ulong len); - void set_param_time(uchar **pos, ulong len); - void set_param_datetime(uchar **pos, ulong len); - void set_param_date(uchar **pos, ulong len); - void set_param_str(uchar **pos, ulong len); - - void setup_conversion(THD *thd, uchar param_type); - void setup_conversion_blob(THD *thd); - void setup_conversion_string(THD *thd, CHARSET_INFO *fromcs); - - /* - Assign placeholder value from bind data. - Note, that 'len' has different semantics in embedded library (as we - don't need to check that packet is not broken there). See - sql_prepare.cc for details. - */ - void set_param_func(uchar **pos, ulong len) - { - /* - To avoid Item_param::set_xxx() asserting on data type mismatch, - we set the value type handler here: - - It can not be initialized yet after Item_param::setup_conversion(). - - Also, for LIMIT clause parameters, the value type handler might have - changed from the real type handler to type_handler_longlong. - So here we'll restore it. - */ - const Type_handler *h= Item_param::type_handler(); - value.set_handler(h); - h->Item_param_set_param_func(this, pos, len); - } - - bool set_value(THD *thd, const Type_all_attributes *attr, - const st_value *val, const Type_handler *h) - { - value.set_handler(h); // See comments in set_param_func() - return h->Item_param_set_from_value(thd, this, attr, val); - } - - bool set_limit_clause_param(longlong nr) - { - value.set_handler(&type_handler_slonglong); - set_int(nr, MY_INT64_NUM_DECIMAL_DIGITS); - return !unsigned_flag && value.integer < 0; - } - const String *query_val_str(THD *thd, String *str) const; - - bool convert_str_value(THD *thd); - - /* - If value for parameter was not set we treat it as non-const - so no one will use parameters value in fix_fields still - parameter is constant during execution. - */ - bool const_item() const - { - return state != NO_VALUE; - } - virtual table_map used_tables() const - { - return state != NO_VALUE ? (table_map)0 : PARAM_TABLE_BIT; - } - virtual void print(String *str, enum_query_type query_type); - bool is_null() - { DBUG_ASSERT(state != NO_VALUE); return state == NULL_VALUE; } - bool basic_const_item() const; - bool has_no_value() const - { - return state == NO_VALUE; - } - bool has_long_data_value() const - { - return state == LONG_DATA_VALUE; - } - bool has_int_value() const - { - return state == SHORT_DATA_VALUE && - value.type_handler()->cmp_type() == INT_RESULT; - } - /* - This method is used to make a copy of a basic constant item when - propagating constants in the optimizer. The reason to create a new - item and not use the existing one is not precisely known (2005/04/16). - Probably we are trying to preserve tree structure of items, in other - words, avoid pointing at one item from two different nodes of the tree. - Return a new basic constant item if parameter value is a basic - constant, assert otherwise. This method is called only if - basic_const_item returned TRUE. - */ - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs); - Item *clone_item(THD *thd); - void set_param_type_and_swap_value(Item_param *from); - - Rewritable_query_parameter *get_rewritable_query_parameter() - { return this; } - Settable_routine_parameter *get_settable_routine_parameter() - { return m_is_settable_routine_parameter ? this : NULL; } - - bool append_for_log(THD *thd, String *str); - bool check_vcol_func_processor(void *int_arg) {return FALSE;} - Item *get_copy(THD *thd) { return 0; } - - bool add_as_clone(THD *thd); - void sync_clones(); - bool register_clone(Item_param *i) { return m_clones.push_back(i); } - -private: - void invalid_default_param() const; - - virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it); - - virtual void set_out_param_info(Send_field *info); - -public: - virtual const Send_field *get_out_param_info() const; - - Item_param *get_item_param() { return this; } - - virtual void make_send_field(THD *thd, Send_field *field); - -private: - Send_field *m_out_param_info; - bool m_is_settable_routine_parameter; - /* - Array of all references of this parameter marker used in a CTE to its clones - created for copies of this marker used the CTE's copies. It's used to - synchronize the actual value of the parameter with the values of the clones. - */ - Mem_root_array m_clones; -}; - - -class Item_int :public Item_num -{ -public: - longlong value; - Item_int(THD *thd, int32 i,size_t length= MY_INT32_NUM_DECIMAL_DIGITS): - Item_num(thd), value((longlong) i) - { max_length=(uint32)length; } - Item_int(THD *thd, longlong i,size_t length= MY_INT64_NUM_DECIMAL_DIGITS): - Item_num(thd), value(i) - { max_length=(uint32)length; } - Item_int(THD *thd, ulonglong i, size_t length= MY_INT64_NUM_DECIMAL_DIGITS): - Item_num(thd), value((longlong)i) - { max_length=(uint32)length; unsigned_flag= 1; } - Item_int(THD *thd, const char *str_arg,longlong i,size_t length): - Item_num(thd), value(i) - { - max_length=(uint32)length; - name.str= str_arg; name.length= safe_strlen(name.str); - } - Item_int(THD *thd, const char *str_arg,longlong i,size_t length, bool flag): - Item_num(thd), value(i) - { - max_length=(uint32)length; - name.str= str_arg; name.length= safe_strlen(name.str); - unsigned_flag= flag; - } - Item_int(THD *thd, const char *str_arg, size_t length=64); - const Type_handler *type_handler() const - { return type_handler_long_or_longlong(); } - Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) - { return tmp_table_field_from_field_type(root, table); } - const longlong *const_ptr_longlong() const { return &value; } - longlong val_int() { return value; } - longlong val_int_min() const { return value; } - double val_real() { return (double) value; } - my_decimal *val_decimal(my_decimal *); - String *val_str(String*); - int save_in_field(Field *field, bool no_conversions); - bool is_order_clause_position() const { return true; } - Item *clone_item(THD *thd); - virtual void print(String *str, enum_query_type query_type); - Item *neg(THD *thd); - uint decimal_precision() const - { return (uint) (max_length - MY_TEST(value < 0)); } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - We sometimes need to distinguish a number from a boolean: - a[1] and a[true] are different things in XPath. - Also in JSON boolean values should be treated differently. -*/ -class Item_bool :public Item_int -{ -public: - Item_bool(THD *thd, const char *str_arg, longlong i): - Item_int(thd, str_arg, i, 1) {} - Item_bool(THD *thd, bool i) :Item_int(thd, (longlong) i, 1) { } - bool is_bool_literal() const { return true; } - Item *neg_transformer(THD *thd); - const Type_handler *type_handler() const - { return &type_handler_bool; } - const Type_handler *fixed_type_handler() const - { return &type_handler_bool; } - void quick_fix_field() - { - /* - We can get here when Item_bool is created instead of a constant - predicate at various condition optimization stages in sql_select. - */ - } -}; - - -class Item_uint :public Item_int -{ -public: - Item_uint(THD *thd, const char *str_arg, size_t length); - Item_uint(THD *thd, ulonglong i): Item_int(thd, i, 10) {} - Item_uint(THD *thd, const char *str_arg, longlong i, uint length); - double val_real() { return ulonglong2double((ulonglong)value); } - Item *clone_item(THD *thd); - Item *neg(THD *thd); - uint decimal_precision() const { return max_length; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_datetime :public Item_int -{ -protected: - MYSQL_TIME ltime; -public: - Item_datetime(THD *thd): Item_int(thd, 0) { unsigned_flag=0; } - int save_in_field(Field *field, bool no_conversions); - longlong val_int(); - double val_real() { return (double)val_int(); } - void set(longlong packed, enum_mysql_timestamp_type ts_type); - bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate) - { - *to= ltime; - return false; - } -}; - - -/* decimal (fixed point) constant */ -class Item_decimal :public Item_num -{ -protected: - my_decimal decimal_value; -public: - Item_decimal(THD *thd, const char *str_arg, size_t length, - CHARSET_INFO *charset); - Item_decimal(THD *thd, const char *str, const my_decimal *val_arg, - uint decimal_par, uint length); - Item_decimal(THD *thd, const my_decimal *value_par); - Item_decimal(THD *thd, longlong val, bool unsig); - Item_decimal(THD *thd, double val, int precision, int scale); - Item_decimal(THD *thd, const uchar *bin, int precision, int scale); - - const Type_handler *type_handler() const { return &type_handler_newdecimal; } - longlong val_int() { return decimal_value.to_longlong(unsigned_flag); } - double val_real() { return decimal_value.to_double(); } - String *val_str(String *to) { return decimal_value.to_string(to); } - my_decimal *val_decimal(my_decimal *val) { return &decimal_value; } - const my_decimal *const_ptr_my_decimal() const { return &decimal_value; } - int save_in_field(Field *field, bool no_conversions); - Item *clone_item(THD *thd); - virtual void print(String *str, enum_query_type query_type) - { - decimal_value.to_string(&str_value); - str->append(str_value); - } - Item *neg(THD *thd); - uint decimal_precision() const { return decimal_value.precision(); } - void set_decimal_value(my_decimal *value_par); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_float :public Item_num -{ - const char *presentation; -public: - double value; - Item_float(THD *thd, const char *str_arg, size_t length); - Item_float(THD *thd, const char *str, double val_arg, uint decimal_par, - uint length): Item_num(thd), value(val_arg) - { - presentation= name.str= str; - name.length= safe_strlen(str); - decimals=(uint8) decimal_par; - max_length= length; - } - Item_float(THD *thd, double value_par, uint decimal_par): - Item_num(thd), presentation(0), value(value_par) - { - decimals= (uint8) decimal_par; - } - int save_in_field(Field *field, bool no_conversions); - const Type_handler *type_handler() const { return &type_handler_double; } - const double *const_ptr_double() const { return &value; } - double val_real() { return value; } - longlong val_int() - { - if (value <= (double) LONGLONG_MIN) - { - return LONGLONG_MIN; - } - else if (value >= (double) (ulonglong) LONGLONG_MAX) - { - return LONGLONG_MAX; - } - return (longlong) rint(value); - } - String *val_str(String*); - my_decimal *val_decimal(my_decimal *); - Item *clone_item(THD *thd); - Item *neg(THD *thd); - virtual void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_static_float_func :public Item_float -{ - const char *func_name; -public: - Item_static_float_func(THD *thd, const char *str, double val_arg, - uint decimal_par, uint length): - Item_float(thd, NullS, val_arg, decimal_par, length), func_name(str) - {} - - virtual inline void print(String *str, enum_query_type query_type) - { - str->append(func_name); - } - - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) - { - return const_charset_converter(thd, tocs, true, func_name); - } -}; - - -class Item_string :public Item_literal -{ -protected: - void fix_from_value(Derivation dv, const Metadata metadata) - { - fix_charset_and_length(str_value.charset(), dv, metadata); - } - void fix_and_set_name_from_value(THD *thd, Derivation dv, - const Metadata metadata) - { - fix_from_value(dv, metadata); - set_name(thd, &str_value); - } -protected: - /* Just create an item and do not fill string representation */ - Item_string(THD *thd, CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE): - Item_literal(thd) - { - collation.set(cs, dv); - max_length= 0; - set_name(thd, NULL, 0, system_charset_info); - decimals= NOT_FIXED_DEC; - } -public: - Item_string(THD *thd, CHARSET_INFO *csi, const char *str_arg, uint length_arg) - :Item_literal(thd) - { - collation.set(csi, DERIVATION_COERCIBLE); - set_name(thd, NULL, 0, system_charset_info); - decimals= NOT_FIXED_DEC; - str_value.copy(str_arg, length_arg, csi); - max_length= str_value.numchars() * csi->mbmaxlen; - } - // Constructors with the item name set from its value - Item_string(THD *thd, const char *str, uint length, CHARSET_INFO *cs, - Derivation dv, my_repertoire_t repertoire) - :Item_literal(thd) - { - str_value.set_or_copy_aligned(str, length, cs); - fix_and_set_name_from_value(thd, dv, Metadata(&str_value, repertoire)); - } - Item_string(THD *thd, const char *str, size_t length, - CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE) - :Item_literal(thd) - { - str_value.set_or_copy_aligned(str, length, cs); - fix_and_set_name_from_value(thd, dv, Metadata(&str_value)); - } - Item_string(THD *thd, const String *str, CHARSET_INFO *tocs, uint *conv_errors, - Derivation dv, my_repertoire_t repertoire) - :Item_literal(thd) - { - if (str_value.copy(str, tocs, conv_errors)) - str_value.set("", 0, tocs); // EOM ? - str_value.mark_as_const(); - fix_and_set_name_from_value(thd, dv, Metadata(&str_value, repertoire)); - } - // Constructors with an externally provided item name - Item_string(THD *thd, const LEX_CSTRING &name_par, const LEX_CSTRING &str, - CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE) - :Item_literal(thd) - { - str_value.set_or_copy_aligned(str.str, str.length, cs); - fix_from_value(dv, Metadata(&str_value)); - set_name(thd, name_par); - } - Item_string(THD *thd, const LEX_CSTRING &name_par, const LEX_CSTRING &str, - CHARSET_INFO *cs, Derivation dv, my_repertoire_t repertoire) - :Item_literal(thd) - { - str_value.set_or_copy_aligned(str.str, str.length, cs); - fix_from_value(dv, Metadata(&str_value, repertoire)); - set_name(thd, name_par); - } - void print_value(String *to) const - { - str_value.print(to); - } - double val_real(); - longlong val_int(); - const String *const_ptr_string() const - { - return &str_value; - } - String *val_str(String*) - { - return (String*) &str_value; - } - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return get_date_from_string(thd, ltime, fuzzydate); - } - int save_in_field(Field *field, bool no_conversions); - const Type_handler *type_handler() const { return &type_handler_varchar; } - Item *clone_item(THD *thd); - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) - { - return const_charset_converter(thd, tocs, true); - } - inline void append(const char *str, uint length) - { - str_value.append(str, length); - max_length= str_value.numchars() * collation.collation->mbmaxlen; - } - virtual void print(String *str, enum_query_type query_type); - - /** - Return TRUE if character-set-introducer was explicitly specified in the - original query for this item (text literal). - - This operation is to be called from Item_string::print(). The idea is - that when a query is generated (re-constructed) from the Item-tree, - character-set-introducers should appear only for those literals, where - they were explicitly specified by the user. Otherwise, that may lead to - loss collation information (character set introducers implies default - collation for the literal). - - Basically, that makes sense only for views and hopefully will be gone - one day when we start using original query as a view definition. - - @return This operation returns the value of m_cs_specified attribute. - @retval TRUE if character set introducer was explicitly specified in - the original query. - @retval FALSE otherwise. - */ - virtual bool is_cs_specified() const - { - return false; - } - - String *check_well_formed_result(bool send_error) - { return Item::check_well_formed_result(&str_value, send_error); } - - Item_basic_constant *make_string_literal_concat(THD *thd, - const LEX_CSTRING *); - Item *make_odbc_literal(THD *thd, const LEX_CSTRING *typestr); - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - -}; - - -class Item_string_with_introducer :public Item_string -{ -public: - Item_string_with_introducer(THD *thd, const LEX_CSTRING &str, - CHARSET_INFO *cs): - Item_string(thd, str.str, str.length, cs) - { } - Item_string_with_introducer(THD *thd, const LEX_CSTRING &name_arg, - const LEX_CSTRING &str, CHARSET_INFO *tocs): - Item_string(thd, name_arg, str, tocs) - { } - virtual bool is_cs_specified() const - { - return true; - } -}; - - -class Item_string_sys :public Item_string -{ -public: - Item_string_sys(THD *thd, const char *str, uint length): - Item_string(thd, str, length, system_charset_info) - { } - Item_string_sys(THD *thd, const char *str): - Item_string(thd, str, (uint) strlen(str), system_charset_info) - { } -}; - - -class Item_string_ascii :public Item_string -{ -public: - Item_string_ascii(THD *thd, const char *str, uint length): - Item_string(thd, str, length, &my_charset_latin1, - DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII) - { } - Item_string_ascii(THD *thd, const char *str): - Item_string(thd, str, (uint) strlen(str), &my_charset_latin1, - DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII) - { } -}; - - -class Item_static_string_func :public Item_string -{ - const LEX_CSTRING func_name; -public: - Item_static_string_func(THD *thd, const LEX_CSTRING &name_par, - const LEX_CSTRING &str, CHARSET_INFO *cs, - Derivation dv= DERIVATION_COERCIBLE): - Item_string(thd, LEX_CSTRING({NullS,0}), str, cs, dv), func_name(name_par) - {} - Item_static_string_func(THD *thd, const LEX_CSTRING &name_par, - const String *str, - CHARSET_INFO *tocs, uint *conv_errors, - Derivation dv, my_repertoire_t repertoire): - Item_string(thd, str, tocs, conv_errors, dv, repertoire), - func_name(name_par) - {} - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) - { - return const_charset_converter(thd, tocs, true, func_name.str); - } - - virtual inline void print(String *str, enum_query_type query_type) - { - str->append(func_name); - } - - bool check_partition_func_processor(void *int_arg) {return TRUE;} - - bool check_vcol_func_processor(void *arg) - { // VCOL_TIME_FUNC because the value is not constant, but does not - // require fix_fields() to be re-run for every statement. - return mark_unsupported_function(func_name.str, arg, VCOL_TIME_FUNC); - } -}; - - -/* for show tables */ -class Item_partition_func_safe_string: public Item_string -{ -public: - Item_partition_func_safe_string(THD *thd, const LEX_CSTRING &name_arg, - uint length, CHARSET_INFO *cs): - Item_string(thd, name_arg, LEX_CSTRING({0,0}), cs) - { - max_length= length; - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function("safe_string", arg, VCOL_IMPOSSIBLE); - } -}; - - -/** - Item_empty_string -- is a utility class to put an item into List - which is then used in protocol.send_result_set_metadata() when sending SHOW output to - the client. -*/ - -class Item_empty_string :public Item_partition_func_safe_string -{ -public: - Item_empty_string(THD *thd, const LEX_CSTRING &header, uint length, - CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci) - :Item_partition_func_safe_string(thd, header, length * cs->mbmaxlen, cs) - { } - Item_empty_string(THD *thd, const char *header, uint length, - CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci) - :Item_partition_func_safe_string(thd, LEX_CSTRING({header, strlen(header)}), - length * cs->mbmaxlen, cs) - { } - void make_send_field(THD *thd, Send_field *field); -}; - - -class Item_return_int :public Item_int -{ - enum_field_types int_field_type; -public: - Item_return_int(THD *thd, const char *name_arg, uint length, - enum_field_types field_type_arg, longlong value_arg= 0): - Item_int(thd, name_arg, value_arg, length), int_field_type(field_type_arg) - { - unsigned_flag=1; - } - const Type_handler *type_handler() const - { - const Type_handler *h= - Type_handler::get_handler_by_field_type(int_field_type); - return unsigned_flag ? h->type_handler_unsigned() : h; - } -}; - - -/** - Item_hex_constant -- a common class for hex literals: X'HHHH' and 0xHHHH -*/ -class Item_hex_constant: public Item_literal -{ -private: - void hex_string_init(THD *thd, const char *str, size_t str_length); -public: - Item_hex_constant(THD *thd): Item_literal(thd) - { - hex_string_init(thd, "", 0); - } - Item_hex_constant(THD *thd, const char *str, size_t str_length): - Item_literal(thd) - { - hex_string_init(thd, str, str_length); - } - const Type_handler *type_handler() const { return &type_handler_varchar; } - virtual Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) - { - return const_charset_converter(thd, tocs, true); - } - const String *const_ptr_string() const { return &str_value; } - String *val_str(String*) { return &str_value; } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } -}; - - -/** - Item_hex_hybrid -- is a class implementing 0xHHHH literals, e.g.: - SELECT 0x3132; - They can behave as numbers and as strings depending on context. -*/ -class Item_hex_hybrid: public Item_hex_constant -{ -public: - Item_hex_hybrid(THD *thd): Item_hex_constant(thd) {} - Item_hex_hybrid(THD *thd, const char *str, size_t str_length): - Item_hex_constant(thd, str, str_length) {} - const Type_handler *type_handler() const { return &type_handler_hex_hybrid; } - uint decimal_precision() const; - double val_real() - { - return (double) (ulonglong) Item_hex_hybrid::val_int(); - } - longlong val_int() - { - return longlong_from_hex_hybrid(str_value.ptr(), str_value.length()); - } - my_decimal *val_decimal(my_decimal *decimal_value) - { - longlong value= Item_hex_hybrid::val_int(); - int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value); - return decimal_value; - } - int save_in_field(Field *field, bool no_conversions) - { - field->set_notnull(); - return field->store_hex_hybrid(str_value.ptr(), str_value.length()); - } - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - Item_hex_string -- is a class implementing X'HHHH' literals, e.g.: - SELECT X'3132'; - Unlike Item_hex_hybrid, X'HHHH' literals behave as strings in all contexts. - X'HHHH' are also used in replication of string constants in case of - "dangerous" charsets (sjis, cp932, big5, gbk) who can have backslash (0x5C) - as the second byte of a multi-byte character, so using '\' escaping for - these charsets is not desirable. -*/ -class Item_hex_string: public Item_hex_constant -{ -public: - Item_hex_string(THD *thd): Item_hex_constant(thd) {} - Item_hex_string(THD *thd, const char *str, size_t str_length): - Item_hex_constant(thd, str, str_length) {} - longlong val_int() - { - return longlong_from_string_with_check(&str_value); - } - double val_real() - { - return double_from_string_with_check(&str_value); - } - my_decimal *val_decimal(my_decimal *decimal_value) - { - return val_decimal_from_string(decimal_value); - } - int save_in_field(Field *field, bool no_conversions) - { - field->set_notnull(); - return field->store(str_value.ptr(), str_value.length(), - collation.collation); - } - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_bin_string: public Item_hex_hybrid -{ -public: - Item_bin_string(THD *thd, const char *str, size_t str_length); -}; - - -class Item_timestamp_literal: public Item_literal -{ - Timestamp_or_zero_datetime m_value; -public: - Item_timestamp_literal(THD *thd) - :Item_literal(thd) - { } - const Type_handler *type_handler() const { return &type_handler_timestamp2; } - int save_in_field(Field *field, bool no_conversions) - { - Timestamp_or_zero_datetime_native native(m_value, decimals); - return native.save_in_field(field, decimals); - } - longlong val_int() - { - return m_value.to_datetime(current_thd).to_longlong(); - } - double val_real() - { - return m_value.to_datetime(current_thd).to_double(); - } - String *val_str(String *to) - { - return m_value.to_datetime(current_thd).to_string(to, decimals); - } - my_decimal *val_decimal(my_decimal *to) - { - return m_value.to_datetime(current_thd).to_decimal(to); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - bool res= m_value.to_TIME(thd, ltime, fuzzydate); - DBUG_ASSERT(!res); - return res; - } - bool val_native(THD *thd, Native *to) - { - return m_value.to_native(to, decimals); - } - void set_value(const Timestamp_or_zero_datetime &value) - { - m_value= value; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_temporal_literal :public Item_literal -{ -public: - Item_temporal_literal(THD *thd) - :Item_literal(thd) - { - collation= DTCollation_numeric(); - decimals= 0; - } - Item_temporal_literal(THD *thd, uint dec_arg): - Item_literal(thd) - { - collation= DTCollation_numeric(); - decimals= dec_arg; - } - - int save_in_field(Field *field, bool no_conversions) - { return save_date_in_field(field, no_conversions); } -}; - - -/** - DATE'2010-01-01' -*/ -class Item_date_literal: public Item_temporal_literal -{ -protected: - Date cached_time; - bool update_null() - { - return maybe_null && - (null_value= cached_time.check_date_with_warn(current_thd)); - } -public: - Item_date_literal(THD *thd, const Date *ltime) - :Item_temporal_literal(thd), - cached_time(*ltime) - { - DBUG_ASSERT(cached_time.is_valid_date()); - max_length= MAX_DATE_WIDTH; - /* - If date has zero month or day, it can return NULL in case of - NO_ZERO_DATE or NO_ZERO_IN_DATE. - If date is `February 30`, it can return NULL in case if - no ALLOW_INVALID_DATES is set. - We can't set null_value using the current sql_mode here in constructor, - because sql_mode can change in case of prepared statements - between PREPARE and EXECUTE. - Here we only set maybe_null to true if the value has such anomalies. - Later (during execution time), if maybe_null is true, then the value - will be checked per row, according to the execution time sql_mode. - The check_date() below call should cover all cases mentioned. - */ - maybe_null= cached_time.check_date(TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE); - } - const Type_handler *type_handler() const { return &type_handler_newdate; } - void print(String *str, enum_query_type query_type); - const MYSQL_TIME *const_ptr_mysql_time() const - { - return cached_time.get_mysql_time(); - } - Item *clone_item(THD *thd); - longlong val_int() - { - return update_null() ? 0 : cached_time.to_longlong(); - } - double val_real() - { - return update_null() ? 0 : cached_time.to_double(); - } - String *val_str(String *to) - { - return update_null() ? 0 : cached_time.to_string(to); - } - my_decimal *val_decimal(my_decimal *to) - { - return update_null() ? 0 : cached_time.to_decimal(to); - } - longlong val_datetime_packed(THD *thd) - { - return update_null() ? 0 : cached_time.valid_date_to_packed(); - } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - TIME'10:10:10' -*/ -class Item_time_literal: public Item_temporal_literal -{ -protected: - Time cached_time; -public: - Item_time_literal(THD *thd, const Time *ltime, uint dec_arg): - Item_temporal_literal(thd, dec_arg), - cached_time(*ltime) - { - DBUG_ASSERT(cached_time.is_valid_time()); - max_length= MIN_TIME_WIDTH + (decimals ? decimals + 1 : 0); - } - const Type_handler *type_handler() const { return &type_handler_time2; } - void print(String *str, enum_query_type query_type); - const MYSQL_TIME *const_ptr_mysql_time() const - { - return cached_time.get_mysql_time(); - } - Item *clone_item(THD *thd); - longlong val_int() { return cached_time.to_longlong(); } - double val_real() { return cached_time.to_double(); } - String *val_str(String *to) { return cached_time.to_string(to, decimals); } - my_decimal *val_decimal(my_decimal *to) { return cached_time.to_decimal(to); } - longlong val_time_packed(THD *thd) - { - return cached_time.valid_time_to_packed(); - } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - bool val_native(THD *thd, Native *to) - { - return Time(thd, this).to_native(to, decimals); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - TIMESTAMP'2001-01-01 10:20:30' -*/ -class Item_datetime_literal: public Item_temporal_literal -{ -protected: - Datetime cached_time; - bool update_null() - { - return maybe_null && - (null_value= cached_time.check_date_with_warn(current_thd)); - } -public: - Item_datetime_literal(THD *thd, const Datetime *ltime, uint dec_arg): - Item_temporal_literal(thd, dec_arg), - cached_time(*ltime) - { - DBUG_ASSERT(cached_time.is_valid_datetime()); - max_length= MAX_DATETIME_WIDTH + (decimals ? decimals + 1 : 0); - // See the comment on maybe_null in Item_date_literal - maybe_null= cached_time.check_date(TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE); - } - const Type_handler *type_handler() const { return &type_handler_datetime2; } - void print(String *str, enum_query_type query_type); - const MYSQL_TIME *const_ptr_mysql_time() const - { - return cached_time.get_mysql_time(); - } - Item *clone_item(THD *thd); - longlong val_int() - { - return update_null() ? 0 : cached_time.to_longlong(); - } - double val_real() - { - return update_null() ? 0 : cached_time.to_double(); - } - String *val_str(String *to) - { - return update_null() ? NULL : cached_time.to_string(to, decimals); - } - my_decimal *val_decimal(my_decimal *to) - { - return update_null() ? NULL : cached_time.to_decimal(to); - } - longlong val_datetime_packed(THD *thd) - { - return update_null() ? 0 : cached_time.valid_datetime_to_packed(); - } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - An error-safe counterpart for Item_date_literal -*/ -class Item_date_literal_for_invalid_dates: public Item_date_literal -{ - /** - During equal field propagation we can replace non-temporal constants - found in equalities to their native temporal equivalents: - WHERE date_column='2001-01-01' ... -> - WHERE date_column=DATE'2001-01-01' ... - - This is done to make the eqial field propagation code handle mixtures of - different temporal types in the same expressions easier (MDEV-8706), e.g. - WHERE LENGTH(date_column)=10 AND date_column=TIME'00:00:00' - - Item_date_literal_for_invalid_dates::get_date() - (unlike the regular Item_date_literal::get_date()) - does not check the result for NO_ZERO_IN_DATE and NO_ZERO_DATE, - always returns success (false), and does not produce error/warning messages. - - We need these _for_invalid_dates classes to be able to rewrite: - SELECT * FROM t1 WHERE date_column='0000-00-00' ... - to: - SELECT * FROM t1 WHERE date_column=DATE'0000-00-00' ... - - to avoid returning NULL value instead of '0000-00-00' even - in sql_mode=TRADITIONAL. - */ -public: - Item_date_literal_for_invalid_dates(THD *thd, const Date *ltime) - :Item_date_literal(thd, ltime) - { - maybe_null= false; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - cached_time.copy_to_mysql_time(ltime); - return (null_value= false); - } -}; - - -/** - An error-safe counterpart for Item_datetime_literal - (see Item_date_literal_for_invalid_dates for comments) -*/ -class Item_datetime_literal_for_invalid_dates: public Item_datetime_literal -{ -public: - Item_datetime_literal_for_invalid_dates(THD *thd, - const Datetime *ltime, uint dec_arg) - :Item_datetime_literal(thd, ltime, dec_arg) - { - maybe_null= false; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - cached_time.copy_to_mysql_time(ltime); - return (null_value= false); - } -}; - - -class Used_tables_and_const_cache -{ -public: - /* - In some cases used_tables_cache is not what used_tables() return - so the method should be used where one need used tables bit map - (even internally in Item_func_* code). - */ - table_map used_tables_cache; - bool const_item_cache; - - Used_tables_and_const_cache() - :used_tables_cache(0), - const_item_cache(true) - { } - Used_tables_and_const_cache(const Used_tables_and_const_cache *other) - :used_tables_cache(other->used_tables_cache), - const_item_cache(other->const_item_cache) - { } - void used_tables_and_const_cache_init() - { - used_tables_cache= 0; - const_item_cache= true; - } - void used_tables_and_const_cache_join(const Item *item) - { - used_tables_cache|= item->used_tables(); - const_item_cache&= item->const_item(); - } - void used_tables_and_const_cache_update_and_join(Item *item) - { - item->update_used_tables(); - used_tables_and_const_cache_join(item); - } - /* - Call update_used_tables() for all "argc" items in the array "argv" - and join with the current cache. - "this" must be initialized with a constructor or - re-initialized with used_tables_and_const_cache_init(). - */ - void used_tables_and_const_cache_update_and_join(uint argc, Item **argv) - { - for (uint i=0 ; i < argc ; i++) - used_tables_and_const_cache_update_and_join(argv[i]); - } - /* - Call update_used_tables() for all items in the list - and join with the current cache. - "this" must be initialized with a constructor or - re-initialized with used_tables_and_const_cache_init(). - */ - void used_tables_and_const_cache_update_and_join(List &list) - { - List_iterator_fast li(list); - Item *item; - while ((item=li++)) - used_tables_and_const_cache_update_and_join(item); - } -}; - - -/** - An abstract class representing common features of - regular functions and aggregate functions. -*/ -class Item_func_or_sum: public Item_result_field, - public Item_args, - public Used_tables_and_const_cache, - public With_subquery_cache -{ -protected: - bool agg_arg_charsets(DTCollation &c, Item **items, uint nitems, - uint flags, int item_sep) - { - return Type_std_attributes::agg_arg_charsets(c, func_name(), - items, nitems, - flags, item_sep); - } - bool agg_arg_charsets_for_string_result(DTCollation &c, - Item **items, uint nitems, - int item_sep= 1) - { - return Type_std_attributes:: - agg_arg_charsets_for_string_result(c, func_name(), - items, nitems, item_sep); - } - bool agg_arg_charsets_for_string_result_with_comparison(DTCollation &c, - Item **items, - uint nitems, - int item_sep= 1) - { - return Type_std_attributes:: - agg_arg_charsets_for_string_result_with_comparison(c, func_name(), - items, nitems, - item_sep); - } - - /* - Aggregate arguments for comparison, e.g: a=b, a LIKE b, a RLIKE b - - don't convert to @@character_set_connection if all arguments are numbers - - don't allow DERIVATION_NONE - */ - bool agg_arg_charsets_for_comparison(DTCollation &c, - Item **items, uint nitems, - int item_sep= 1) - { - return Type_std_attributes:: - agg_arg_charsets_for_comparison(c, func_name(), items, nitems, item_sep); - } - -public: - // This method is used by Arg_comparator - bool agg_arg_charsets_for_comparison(CHARSET_INFO **cs, Item **a, Item **b) - { - DTCollation tmp; - if (tmp.set((*a)->collation, (*b)->collation, MY_COLL_CMP_CONV) || - tmp.derivation == DERIVATION_NONE) - { - my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0), - (*a)->collation.collation->name, - (*a)->collation.derivation_name(), - (*b)->collation.collation->name, - (*b)->collation.derivation_name(), - func_name()); - return true; - } - if (agg_item_set_converter(tmp, func_name(), - a, 1, MY_COLL_CMP_CONV, 1) || - agg_item_set_converter(tmp, func_name(), - b, 1, MY_COLL_CMP_CONV, 1)) - return true; - *cs= tmp.collation; - return false; - } - -public: - Item_func_or_sum(THD *thd): Item_result_field(thd), Item_args() {} - Item_func_or_sum(THD *thd, Item *a): Item_result_field(thd), Item_args(a) { } - Item_func_or_sum(THD *thd, Item *a, Item *b): - Item_result_field(thd), Item_args(a, b) { } - Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c): - Item_result_field(thd), Item_args(thd, a, b, c) { } - Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c, Item *d): - Item_result_field(thd), Item_args(thd, a, b, c, d) { } - Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c, Item *d, Item *e): - Item_result_field(thd), Item_args(thd, a, b, c, d, e) { } - Item_func_or_sum(THD *thd, Item_func_or_sum *item): - Item_result_field(thd, item), Item_args(thd, item), - Used_tables_and_const_cache(item) { } - Item_func_or_sum(THD *thd, List &list): - Item_result_field(thd), Item_args(thd, list) { } - bool with_subquery() const { DBUG_ASSERT(fixed); return m_with_subquery; } - bool walk(Item_processor processor, bool walk_subquery, void *arg) - { - if (walk_args(processor, walk_subquery, arg)) - return true; - return (this->*processor)(arg); - } - /* - This method is used for debug purposes to print the name of an - item to the debug log. The second use of this method is as - a helper function of print() and error messages, where it is - applicable. To suit both goals it should return a meaningful, - distinguishable and sintactically correct string. This method - should not be used for runtime type identification, use enum - {Sum}Functype and Item_func::functype()/Item_sum::sum_func() - instead. - Added here, to the parent class of both Item_func and Item_sum. - - NOTE: for Items inherited from Item_sum, func_name() return part of - function name till first argument (including '(') to make difference in - names for functions with 'distinct' clause and without 'distinct' and - also to make printing of items inherited from Item_sum uniform. - */ - virtual const char *func_name() const= 0; - virtual bool fix_length_and_dec()= 0; - bool const_item() const { return const_item_cache; } - table_map used_tables() const { return used_tables_cache; } - Item* build_clone(THD *thd); - Sql_mode_dependency value_depends_on_sql_mode() const - { - return Item_args::value_depends_on_sql_mode_bit_or().soft_to_hard(); - } -}; - -class sp_head; -class sp_name; -struct st_sp_security_context; - -class Item_sp -{ -protected: - // Can be NULL in some non-SELECT queries - Name_resolution_context *context; -public: - sp_name *m_name; - sp_head *m_sp; - TABLE *dummy_table; - uchar result_buf[64]; - sp_rcontext *func_ctx; - MEM_ROOT sp_mem_root; - Query_arena *sp_query_arena; - - /* - The result field of the stored function. - */ - Field *sp_result_field; - Item_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name_arg); - Item_sp(THD *thd, Item_sp *item); - const char *func_name(THD *thd) const; - void cleanup(); - bool sp_check_access(THD *thd); - bool execute(THD *thd, bool *null_value, Item **args, uint arg_count); - bool execute_impl(THD *thd, Item **args, uint arg_count); - bool init_result_field(THD *thd, uint max_length, uint maybe_null, - bool *null_value, LEX_CSTRING *name); - void process_error(THD *thd) - { - if (context) - context->process_error(thd); - } -}; - -class Item_ref :public Item_ident, - protected With_sum_func_cache -{ -protected: - void set_properties(); - bool set_properties_only; // the item doesn't need full fix_fields -public: - enum Ref_Type { REF, DIRECT_REF, VIEW_REF, OUTER_REF, AGGREGATE_REF }; - Item **ref; - bool reference_trough_name; - Item_ref(THD *thd, Name_resolution_context *context_arg, - const LEX_CSTRING &db_arg, const LEX_CSTRING &table_name_arg, - const LEX_CSTRING &field_name_arg): - Item_ident(thd, context_arg, db_arg, table_name_arg, field_name_arg), - set_properties_only(0), ref(0), reference_trough_name(1) {} - Item_ref(THD *thd, Name_resolution_context *context_arg, - const LEX_CSTRING &field_name_arg) - :Item_ref(thd, context_arg, null_clex_str, null_clex_str, field_name_arg) - { } - /* - This constructor is used in two scenarios: - A) *item = NULL - No initialization is performed, fix_fields() call will be necessary. - - B) *item points to an Item this Item_ref will refer to. This is - used for GROUP BY. fix_fields() will not be called in this case, - so we call set_properties to make this item "fixed". set_properties - performs a subset of action Item_ref::fix_fields does, and this subset - is enough for Item_ref's used in GROUP BY. - - TODO we probably fix a superset of problems like in BUG#6658. Check this - with Bar, and if we have a more broader set of problems like this. - */ - Item_ref(THD *thd, Name_resolution_context *context_arg, Item **item, - const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg, - bool alias_name_used_arg= FALSE); - Item_ref(THD *thd, TABLE_LIST *view_arg, Item **item, - const LEX_CSTRING &field_name_arg, bool alias_name_used_arg= FALSE); - - /* Constructor need to process subselect with temporary tables (see Item) */ - Item_ref(THD *thd, Item_ref *item) - :Item_ident(thd, item), With_sum_func_cache(*item), - set_properties_only(0), ref(item->ref) {} - enum Type type() const { return REF_ITEM; } - enum Type real_type() const { return ref ? (*ref)->type() : - REF_ITEM; } - bool eq(const Item *item, bool binary_cmp) const - { - Item *it= ((Item *) item)->real_item(); - return ref && (*ref)->eq(it, binary_cmp); - } - void save_val(Field *to); - void save_result(Field *to); - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal *); - bool val_bool(); - String *val_str(String* tmp); - bool val_native(THD *thd, Native *to); - bool is_null(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - longlong val_datetime_packed(THD *); - longlong val_time_packed(THD *); - double val_result(); - longlong val_int_result(); - String *str_result(String* tmp); - bool val_native_result(THD *thd, Native *to); - my_decimal *val_decimal_result(my_decimal *); - bool val_bool_result(); - bool is_null_result(); - bool send(Protocol *prot, st_value *buffer); - void make_send_field(THD *thd, Send_field *field); - bool fix_fields(THD *, Item **); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - int save_in_field(Field *field, bool no_conversions); - void save_org_in_field(Field *field, fast_field_copier optimizer_data); - fast_field_copier setup_fast_field_copier(Field *field) - { return (*ref)->setup_fast_field_copier(field); } - const Type_handler *type_handler() const { return (*ref)->type_handler(); } - const Type_handler *real_type_handler() const - { return (*ref)->real_type_handler(); } - Field *get_tmp_table_field() - { return result_field ? result_field : (*ref)->get_tmp_table_field(); } - Item *get_tmp_table_item(THD *thd); - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param); - Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *); - table_map used_tables() const; - void update_used_tables(); - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref) - { - /* - normilize_cond() replaced all conditions of type - WHERE/HAVING field - to: - WHERE/HAVING field<>0 - By the time of a build_equal_items() call, all such conditions should - already be replaced. No Item_ref referencing to Item_field are possible. - */ - DBUG_ASSERT(real_type() != FIELD_ITEM); - return Item_ident::build_equal_items(thd, inherited, link_item_fields, - cond_equal_ref); - } - bool const_item() const - { - return (*ref)->const_item(); - } - table_map not_null_tables() const - { - return depended_from ? 0 : (*ref)->not_null_tables(); - } - bool find_not_null_fields(table_map allowed) - { - return depended_from ? false : (*ref)->find_not_null_fields(allowed); - } - void save_in_result_field(bool no_conversions) - { - (*ref)->save_in_field(result_field, no_conversions); - } - Item *real_item() - { - return ref ? (*ref)->real_item() : this; - } - const TYPELIB *get_typelib() const - { - return ref ? (*ref)->get_typelib() : NULL; - } - bool is_json_type() { return (*ref)->is_json_type(); } - - bool walk(Item_processor processor, bool walk_subquery, void *arg) - { - if (ref && *ref) - return (*ref)->walk(processor, walk_subquery, arg) || - (this->*processor)(arg); - else - return FALSE; - } - Item* transform(THD *thd, Item_transformer, uchar *arg); - Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, - Item_transformer transformer, uchar *arg_t); - bool enumerate_field_refs_processor(void *arg) - { return (*ref)->enumerate_field_refs_processor(arg); } - void no_rows_in_result() - { - (*ref)->no_rows_in_result(); - } - void restore_to_before_no_rows_in_result() - { - (*ref)->restore_to_before_no_rows_in_result(); - } - void print(String *str, enum_query_type query_type); - enum precedence precedence() const - { - return ref ? (*ref)->precedence() : DEFAULT_PRECEDENCE; - } - void cleanup(); - Item_field *field_for_view_update() - { return (*ref)->field_for_view_update(); } - Load_data_outvar *get_load_data_outvar() - { - return (*ref)->get_load_data_outvar(); - } - virtual Ref_Type ref_type() { return REF; } - - // Row emulation: forwarding of ROW-related calls to ref - uint cols() const - { - return ref && result_type() == ROW_RESULT ? (*ref)->cols() : 1; - } - Item* element_index(uint i) - { - return ref && result_type() == ROW_RESULT ? (*ref)->element_index(i) : this; - } - Item** addr(uint i) - { - return ref && result_type() == ROW_RESULT ? (*ref)->addr(i) : 0; - } - bool check_cols(uint c) - { - return ref && result_type() == ROW_RESULT ? (*ref)->check_cols(c) - : Item::check_cols(c); - } - bool null_inside() - { - return ref && result_type() == ROW_RESULT ? (*ref)->null_inside() : 0; - } - void bring_value() - { - if (ref && result_type() == ROW_RESULT) - (*ref)->bring_value(); - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function("ref", arg, VCOL_IMPOSSIBLE); - } - bool basic_const_item() const { return ref && (*ref)->basic_const_item(); } - bool is_outer_field() const - { - DBUG_ASSERT(fixed); - DBUG_ASSERT(ref); - return (*ref)->is_outer_field(); - } - - Item* build_clone(THD *thd); - - /** - Checks if the item tree that ref points to contains a subquery. - */ - virtual bool with_subquery() const - { - return (*ref)->with_subquery(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - bool excl_dep_on_table(table_map tab_map) - { - table_map used= used_tables(); - if (used & OUTER_REF_TABLE_BIT) - return false; - return (used == tab_map) || (*ref)->excl_dep_on_table(tab_map); - } - bool excl_dep_on_grouping_fields(st_select_lex *sel) - { return (*ref)->excl_dep_on_grouping_fields(sel); } - bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) - { return (*ref)->excl_dep_on_in_subq_left_part(subq_pred); } - bool cleanup_excluding_fields_processor(void *arg) - { - Item *item= real_item(); - if (item && item->type() == FIELD_ITEM && - ((Item_field *)item)->field) - return 0; - return cleanup_processor(arg); - } - bool cleanup_excluding_const_fields_processor(void *arg) - { - Item *item= real_item(); - if (item && item->type() == FIELD_ITEM && - ((Item_field *) item)->field && item->const_item()) - return 0; - return cleanup_processor(arg); - } - bool with_sum_func() const { return m_with_sum_func; } - With_sum_func_cache* get_with_sum_func_cache() { return this; } - Item *field_transformer_for_having_pushdown(THD *thd, uchar *arg) - { return (*ref)->field_transformer_for_having_pushdown(thd, arg); } - Item *remove_item_direct_ref() - { - *ref= (*ref)->remove_item_direct_ref(); - return this; - } -}; - - -/* - The same as Item_ref, but get value from val_* family of method to get - value of item on which it referred instead of result* family. -*/ -class Item_direct_ref :public Item_ref -{ -public: - Item_direct_ref(THD *thd, Name_resolution_context *context_arg, Item **item, - const LEX_CSTRING &table_name_arg, - const LEX_CSTRING &field_name_arg, - bool alias_name_used_arg= FALSE): - Item_ref(thd, context_arg, item, table_name_arg, - field_name_arg, alias_name_used_arg) - {} - /* Constructor need to process subselect with temporary tables (see Item) */ - Item_direct_ref(THD *thd, Item_direct_ref *item) : Item_ref(thd, item) {} - Item_direct_ref(THD *thd, TABLE_LIST *view_arg, Item **item, - const LEX_CSTRING &field_name_arg, - bool alias_name_used_arg= FALSE): - Item_ref(thd, view_arg, item, field_name_arg, - alias_name_used_arg) - {} - - bool fix_fields(THD *thd, Item **it) - { - if ((*ref)->fix_fields_if_needed_for_scalar(thd, ref)) - return TRUE; - return Item_ref::fix_fields(thd, it); - } - void save_val(Field *to); - double val_real(); - longlong val_int(); - String *val_str(String* tmp); - bool val_native(THD *thd, Native *to); - my_decimal *val_decimal(my_decimal *); - bool val_bool(); - bool is_null(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - virtual Ref_Type ref_type() { return DIRECT_REF; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *remove_item_direct_ref() - { return (*ref)->remove_item_direct_ref(); } -}; - - -/** - This class is the same as Item_direct_ref but created to wrap Item_ident - before fix_fields() call -*/ - -class Item_direct_ref_to_ident :public Item_direct_ref -{ - Item_ident *ident; -public: - Item_direct_ref_to_ident(THD *thd, Item_ident *item): - Item_direct_ref(thd, item->context, (Item**)&item, item->table_name, - item->field_name, FALSE) - { - ident= item; - ref= (Item**)&ident; - } - - bool fix_fields(THD *thd, Item **it) - { - DBUG_ASSERT(ident->type() == FIELD_ITEM || ident->type() == REF_ITEM); - if (ident->fix_fields_if_needed_for_scalar(thd, ref)) - return TRUE; - set_properties(); - return FALSE; - } - - virtual void print(String *str, enum_query_type query_type) - { ident->print(str, query_type); } - -}; - - -class Item_cache; -class Expression_cache; -class Expression_cache_tracker; - -/** - The objects of this class can store its values in an expression cache. -*/ - -class Item_cache_wrapper :public Item_result_field, - public With_subquery_cache, - protected With_sum_func_cache -{ -private: - /* Pointer on the cached expression */ - Item *orig_item; - Expression_cache *expr_cache; - /* - In order to put the expression into the expression cache and return - value of val_*() method, we will need to get the expression value twice - (probably in different types). In order to avoid making two - (potentially costly) orig_item->val_*() calls, we store expression value - in this Item_cache object. - */ - Item_cache *expr_value; - - List parameters; - - Item *check_cache(); - void cache(); - void init_on_demand(); - -public: - Item_cache_wrapper(THD *thd, Item *item_arg); - ~Item_cache_wrapper(); - - enum Type type() const { return EXPR_CACHE_ITEM; } - enum Type real_type() const { return orig_item->type(); } - bool with_subquery() const { DBUG_ASSERT(fixed); return m_with_subquery; } - bool with_sum_func() const { return m_with_sum_func; } - With_sum_func_cache* get_with_sum_func_cache() { return this; } - - bool set_cache(THD *thd); - Expression_cache_tracker* init_tracker(MEM_ROOT *mem_root); - - bool fix_fields(THD *thd, Item **it); - void cleanup(); - - Item *get_orig_item() const { return orig_item; } - - /* Methods of getting value which should be cached in the cache */ - void save_val(Field *to); - double val_real(); - longlong val_int(); - String *val_str(String* tmp); - bool val_native(THD *thd, Native *to); - my_decimal *val_decimal(my_decimal *); - bool val_bool(); - bool is_null(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool send(Protocol *protocol, st_value *buffer); - void save_org_in_field(Field *field, - fast_field_copier data __attribute__ ((__unused__))) - { - save_val(field); - } - void save_in_result_field(bool no_conversions) - { - save_val(result_field); - } - Item* get_tmp_table_item(THD *thd_arg); - - /* Following methods make this item transparent as much as possible */ - - virtual void print(String *str, enum_query_type query_type); - virtual const char *full_name() const { return orig_item->full_name(); } - virtual void make_send_field(THD *thd, Send_field *field) - { orig_item->make_send_field(thd, field); } - bool eq(const Item *item, bool binary_cmp) const - { - Item *it= ((Item *) item)->real_item(); - return orig_item->eq(it, binary_cmp); - } - void fix_after_pullout(st_select_lex *new_parent, Item **refptr, bool merge) - { - orig_item->fix_after_pullout(new_parent, &orig_item, merge); - } - int save_in_field(Field *to, bool no_conversions); - const Type_handler *type_handler() const { return orig_item->type_handler(); } - table_map used_tables() const { return orig_item->used_tables(); } - void update_used_tables() - { - orig_item->update_used_tables(); - } - bool const_item() const { return orig_item->const_item(); } - table_map not_null_tables() const { return orig_item->not_null_tables(); } - bool walk(Item_processor processor, bool walk_subquery, void *arg) - { - return orig_item->walk(processor, walk_subquery, arg) || - (this->*processor)(arg); - } - bool enumerate_field_refs_processor(void *arg) - { return orig_item->enumerate_field_refs_processor(arg); } - Item_field *field_for_view_update() - { return orig_item->field_for_view_update(); } - - /* Row emulation: forwarding of ROW-related calls to orig_item */ - uint cols() const - { return result_type() == ROW_RESULT ? orig_item->cols() : 1; } - Item* element_index(uint i) - { return result_type() == ROW_RESULT ? orig_item->element_index(i) : this; } - Item** addr(uint i) - { return result_type() == ROW_RESULT ? orig_item->addr(i) : 0; } - bool check_cols(uint c) - { - return (result_type() == ROW_RESULT ? - orig_item->check_cols(c) : - Item::check_cols(c)); - } - bool null_inside() - { return result_type() == ROW_RESULT ? orig_item->null_inside() : 0; } - void bring_value() - { - if (result_type() == ROW_RESULT) - orig_item->bring_value(); - } - bool is_expensive() { return orig_item->is_expensive(); } - bool is_expensive_processor(void *arg) - { return orig_item->is_expensive_processor(arg); } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function("cache", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *build_clone(THD *thd) { return 0; } -}; - - -/* - Class for view fields, the same as Item_direct_ref, but call fix_fields - of reference if it is not called yet -*/ -class Item_direct_view_ref :public Item_direct_ref -{ - Item_equal *item_equal; - TABLE_LIST *view; - TABLE *null_ref_table; - -#define NO_NULL_TABLE (reinterpret_cast(0x1)) - - void set_null_ref_table() - { - if (!view->is_inner_table_of_outer_join() || - !(null_ref_table= view->get_real_join_table())) - null_ref_table= NO_NULL_TABLE; - } - - bool check_null_ref() - { - DBUG_ASSERT(null_ref_table); - if (null_ref_table != NO_NULL_TABLE && null_ref_table->null_row) - { - null_value= 1; - return TRUE; - } - return FALSE; - } - -public: - Item_direct_view_ref(THD *thd, Name_resolution_context *context_arg, - Item **item, - LEX_CSTRING &table_name_arg, - LEX_CSTRING &field_name_arg, - TABLE_LIST *view_arg): - Item_direct_ref(thd, context_arg, item, table_name_arg, field_name_arg), - item_equal(0), view(view_arg), - null_ref_table(NULL) - { - if (fixed) - set_null_ref_table(); - } - - bool fix_fields(THD *, Item **); - bool eq(const Item *item, bool binary_cmp) const; - Item *get_tmp_table_item(THD *thd) - { - if (const_item()) - return copy_or_same(thd); - Item *item= Item_ref::get_tmp_table_item(thd); - item->name= name; - return item; - } - virtual Ref_Type ref_type() { return VIEW_REF; } - Item_equal *get_item_equal() { return item_equal; } - void set_item_equal(Item_equal *item_eq) { item_equal= item_eq; } - Item_equal *find_item_equal(COND_EQUAL *cond_equal); - Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *); - Item *replace_equal_field(THD *thd, uchar *arg); - table_map used_tables() const; - void update_used_tables(); - table_map not_null_tables() const; - bool const_item() const { return used_tables() == 0; } - TABLE *get_null_ref_table() const { return null_ref_table; } - bool walk(Item_processor processor, bool walk_subquery, void *arg) - { - return (*ref)->walk(processor, walk_subquery, arg) || - (this->*processor)(arg); - } - bool view_used_tables_processor(void *arg) - { - TABLE_LIST *view_arg= (TABLE_LIST *) arg; - if (view_arg == view) - view_arg->view_used_tables|= (*ref)->used_tables(); - return 0; - } - bool excl_dep_on_table(table_map tab_map); - bool excl_dep_on_grouping_fields(st_select_lex *sel); - bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred); - Item *derived_field_transformer_for_having(THD *thd, uchar *arg); - Item *derived_field_transformer_for_where(THD *thd, uchar *arg); - Item *grouping_field_transformer_for_where(THD *thd, uchar *arg); - Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg); - Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg); - - void save_val(Field *to) - { - if (check_null_ref()) - to->set_null(); - else - Item_direct_ref::save_val(to); - } - double val_real() - { - if (check_null_ref()) - return 0; - else - return Item_direct_ref::val_real(); - } - longlong val_int() - { - if (check_null_ref()) - return 0; - else - return Item_direct_ref::val_int(); - } - String *val_str(String* tmp) - { - if (check_null_ref()) - return NULL; - else - return Item_direct_ref::val_str(tmp); - } - bool val_native(THD *thd, Native *to) - { - if (check_null_ref()) - return true; - return Item_direct_ref::val_native(thd, to); - } - my_decimal *val_decimal(my_decimal *tmp) - { - if (check_null_ref()) - return NULL; - else - return Item_direct_ref::val_decimal(tmp); - } - bool val_bool() - { - if (check_null_ref()) - return 0; - else - return Item_direct_ref::val_bool(); - } - bool is_null() - { - if (check_null_ref()) - return 1; - else - return Item_direct_ref::is_null(); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - if (check_null_ref()) - { - bzero((char*) ltime,sizeof(*ltime)); - return 1; - } - return Item_direct_ref::get_date(thd, ltime, fuzzydate); - } - bool send(Protocol *protocol, st_value *buffer); - void save_org_in_field(Field *field, - fast_field_copier data __attribute__ ((__unused__))) - { - if (check_null_ref()) - field->set_null(); - else - Item_direct_ref::save_val(field); - } - void save_in_result_field(bool no_conversions) - { - if (check_null_ref()) - result_field->set_null(); - else - Item_direct_ref::save_in_result_field(no_conversions); - } - - void cleanup() - { - null_ref_table= NULL; - item_equal= NULL; - Item_direct_ref::cleanup(); - } - /* - TODO move these val_*_result function to Item_dierct_ref (maybe) - */ - double val_result(); - longlong val_int_result(); - String *str_result(String* tmp); - my_decimal *val_decimal_result(my_decimal *val); - bool val_bool_result(); - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *field_transformer_for_having_pushdown(THD *thd, uchar *arg) - { return this; } - Item *remove_item_direct_ref() { return this; } -}; - - -/* - Class for outer fields. - An object of this class is created when the select where the outer field was - resolved is a grouping one. After it has been fixed the ref field will point - to either an Item_ref or an Item_direct_ref object which will be used to - access the field. - See also comments for the fix_inner_refs() and the - Item_field::fix_outer_field() functions. -*/ - -class Item_sum; -class Item_outer_ref :public Item_direct_ref -{ -public: - Item *outer_ref; - /* The aggregate function under which this outer ref is used, if any. */ - Item_sum *in_sum_func; - /* - TRUE <=> that the outer_ref is already present in the select list - of the outer select. - */ - bool found_in_select_list; - bool found_in_group_by; - Item_outer_ref(THD *thd, Name_resolution_context *context_arg, - Item_field *outer_field_arg): - Item_direct_ref(thd, context_arg, 0, outer_field_arg->table_name, - outer_field_arg->field_name), - outer_ref(outer_field_arg), in_sum_func(0), - found_in_select_list(0), found_in_group_by(0) - { - ref= &outer_ref; - set_properties(); - fixed= 0; /* reset flag set in set_properties() */ - } - Item_outer_ref(THD *thd, Name_resolution_context *context_arg, Item **item, - const LEX_CSTRING &table_name_arg, LEX_CSTRING &field_name_arg, - bool alias_name_used_arg): - Item_direct_ref(thd, context_arg, item, table_name_arg, field_name_arg, - alias_name_used_arg), - outer_ref(0), in_sum_func(0), found_in_select_list(1), found_in_group_by(0) - {} - void save_in_result_field(bool no_conversions) - { - outer_ref->save_org_in_field(result_field, NULL); - } - bool fix_fields(THD *, Item **); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - table_map used_tables() const - { - return (*ref)->const_item() ? 0 : OUTER_REF_TABLE_BIT; - } - table_map not_null_tables() const { return 0; } - virtual Ref_Type ref_type() { return OUTER_REF; } - bool check_inner_refs_processor(void * arg); -}; - - -class Item_in_subselect; - - -/* - An object of this class: - - Converts val_XXX() calls to ref->val_XXX_result() calls, like Item_ref. - - Sets owner->was_null=TRUE if it has returned a NULL value from any - val_XXX() function. This allows to inject an Item_ref_null_helper - object into subquery and then check if the subquery has produced a row - with NULL value. -*/ - -class Item_ref_null_helper: public Item_ref -{ -protected: - Item_in_subselect* owner; -public: - Item_ref_null_helper(THD *thd, Name_resolution_context *context_arg, - Item_in_subselect* master, Item **item, - const LEX_CSTRING &table_name_arg, - const LEX_CSTRING &field_name_arg): - Item_ref(thd, context_arg, item, table_name_arg, field_name_arg), - owner(master) {} - void save_val(Field *to); - double val_real(); - longlong val_int(); - String* val_str(String* s); - my_decimal *val_decimal(my_decimal *); - bool val_bool(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool val_native(THD *thd, Native *to); - virtual void print(String *str, enum_query_type query_type); - table_map used_tables() const; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* - The following class is used to optimize comparing of date and bigint columns - We need to save the original item ('ref') to be able to call - ref->save_in_field(). This is used to create index search keys. - - An instance of Item_int_with_ref may have signed or unsigned integer value. - -*/ - -class Item_int_with_ref :public Item_int -{ - Item *ref; -public: - Item_int_with_ref(THD *thd, longlong i, Item *ref_arg, bool unsigned_arg): - Item_int(thd, i), ref(ref_arg) - { - unsigned_flag= unsigned_arg; - } - int save_in_field(Field *field, bool no_conversions) - { - return ref->save_in_field(field, no_conversions); - } - Item *clone_item(THD *thd); - virtual Item *real_item() { return ref; } -}; - -#ifdef MYSQL_SERVER -#include "item_sum.h" -#include "item_func.h" -#include "item_row.h" -#include "item_cmpfunc.h" -#include "item_strfunc.h" -#include "item_timefunc.h" -#include "item_subselect.h" -#include "item_xmlfunc.h" -#include "item_jsonfunc.h" -#include "item_create.h" -#include "item_vers.h" -#endif - -/** - Base class to implement typed value caching Item classes - - Item_copy_ classes are very similar to the corresponding Item_ - classes (e.g. Item_copy_string is similar to Item_string) but they add - the following additional functionality to Item_ : - 1. Nullability - 2. Possibility to store the value not only on instantiation time, - but also later. - Item_copy_ classes are a functionality subset of Item_cache_ - classes, as e.g. they don't support comparisons with the original Item - as Item_cache_ classes do. - Item_copy_ classes are used in GROUP BY calculation. - TODO: Item_copy should be made an abstract interface and Item_copy_ - classes should inherit both the respective Item_ class and the interface. - Ideally we should drop Item_copy_ classes altogether and merge - their functionality to Item_cache_ (and these should be made to inherit - from Item_). -*/ - -class Item_copy :public Item, - public Type_handler_hybrid_field_type -{ -protected: - - /** - Type_handler_hybrid_field_type is used to - store the type of the resulting field that would be used to store the data - in the cache. This is to avoid calls to the original item. - */ - - /** The original item that is copied */ - Item *item; - - /** - Constructor of the Item_copy class - - stores metadata information about the original class as well as a - pointer to it. - */ - Item_copy(THD *thd, Item *i): Item(thd) - { - DBUG_ASSERT(i->is_fixed()); - item= i; - null_value=maybe_null=item->maybe_null; - Type_std_attributes::set(item); - name= item->name; - set_handler(item->type_handler()); - } - -public: - - /** - Update the cache with the value of the original item - - This is the method that updates the cached value. - It must be explicitly called by the user of this class to store the value - of the original item in the cache. - */ - virtual void copy() = 0; - - Item *get_item() { return item; } - /** All of the subclasses should have the same type tag */ - enum Type type() const { return COPY_STR_ITEM; } - - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - DBUG_ASSERT(0); - return NULL; - } - void make_send_field(THD *thd, Send_field *field) - { item->make_send_field(thd, field); } - table_map used_tables() const { return (table_map) 1L; } - bool const_item() const { return 0; } - bool is_null() { return null_value; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function("copy", arg, VCOL_IMPOSSIBLE); - } - - /* - Override the methods below as pure virtual to make sure all the - sub-classes implement them. - */ - - virtual String *val_str(String*) = 0; - virtual my_decimal *val_decimal(my_decimal *) = 0; - virtual double val_real() = 0; - virtual longlong val_int() = 0; - virtual int save_in_field(Field *field, bool no_conversions) = 0; - bool walk(Item_processor processor, bool walk_subquery, void *args) - { - return (item->walk(processor, walk_subquery, args)) || - (this->*processor)(args); - } -}; - -/** - Implementation of a string cache. - - Uses Item::str_value for storage -*/ -class Item_copy_string : public Item_copy -{ -public: - Item_copy_string(THD *thd, Item *item_arg): Item_copy(thd, item_arg) {} - - String *val_str(String*); - my_decimal *val_decimal(my_decimal *); - double val_real(); - longlong val_int(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_string(thd, ltime, fuzzydate); } - void copy(); - int save_in_field(Field *field, bool no_conversions); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - We need a separate class Item_copy_timestamp because - TIMESTAMP->string->TIMESTAMP conversion is not round trip safe - near the DST change, e.g. '2010-10-31 02:25:26' can mean: - - my_time_t(1288477526) - summer time in Moscow - - my_time_t(1288481126) - winter time in Moscow, one hour later -*/ -class Item_copy_timestamp: public Item_copy -{ - Timestamp_or_zero_datetime m_value; - bool sane() const { return !null_value || m_value.is_zero_datetime(); } -public: - Item_copy_timestamp(THD *thd, Item *arg): Item_copy(thd, arg) { } - const Type_handler *type_handler() const { return &type_handler_timestamp2; } - void copy() - { - Timestamp_or_zero_datetime_native_null tmp(current_thd, item, false); - null_value= tmp.is_null(); - m_value= tmp.is_null() ? Timestamp_or_zero_datetime() : - Timestamp_or_zero_datetime(tmp); - } - int save_in_field(Field *field, bool no_conversions) - { - DBUG_ASSERT(sane()); - if (null_value) - return set_field_to_null(field); - Timestamp_or_zero_datetime_native native(m_value, decimals); - return native.save_in_field(field, decimals); - } - longlong val_int() - { - DBUG_ASSERT(sane()); - return null_value ? 0 : - m_value.to_datetime(current_thd).to_longlong(); - } - double val_real() - { - DBUG_ASSERT(sane()); - return null_value ? 0e0 : - m_value.to_datetime(current_thd).to_double(); - } - String *val_str(String *to) - { - DBUG_ASSERT(sane()); - return null_value ? NULL : - m_value.to_datetime(current_thd).to_string(to, decimals); - } - my_decimal *val_decimal(my_decimal *to) - { - DBUG_ASSERT(sane()); - return null_value ? NULL : - m_value.to_datetime(current_thd).to_decimal(to); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - DBUG_ASSERT(sane()); - bool res= m_value.to_TIME(thd, ltime, fuzzydate); - DBUG_ASSERT(!res); - return null_value || res; - } - bool val_native(THD *thd, Native *to) - { - DBUG_ASSERT(sane()); - return null_value || m_value.to_native(to, decimals); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - Cached_item_XXX objects are not exactly caches. They do the following: - - Each Cached_item_XXX object has - - its source item - - saved value of the source item - - cmp() method that compares the saved value with the current value of the - source item, and if they were not equal saves item's value into the saved - value. - - TODO: add here: - - a way to save the new value w/o comparison - - a way to do less/equal/greater comparison -*/ - -class Cached_item :public Sql_alloc -{ -public: - bool null_value; - Cached_item() :null_value(0) {} - /* - Compare the cached value with the source value. If not equal, copy - the source value to the cache. - @return - true - Not equal - false - Equal - */ - virtual bool cmp(void)=0; - - /* Compare the cached value with the source value, without copying */ - virtual int cmp_read_only()=0; - - virtual ~Cached_item(); /*line -e1509 */ -}; - -class Cached_item_item : public Cached_item -{ -protected: - Item *item; - - Cached_item_item(Item *arg) : item(arg) {} -public: - void fetch_value_from(Item *new_item) - { - Item *save= item; - item= new_item; - cmp(); - item= save; - } -}; - -class Cached_item_str :public Cached_item_item -{ - uint32 value_max_length; - String value,tmp_value; -public: - Cached_item_str(THD *thd, Item *arg); - bool cmp(void); - int cmp_read_only(); - ~Cached_item_str(); // Deallocate String:s -}; - - -class Cached_item_real :public Cached_item_item -{ - double value; -public: - Cached_item_real(Item *item_par) :Cached_item_item(item_par),value(0.0) {} - bool cmp(void); - int cmp_read_only(); -}; - -class Cached_item_int :public Cached_item_item -{ - longlong value; -public: - Cached_item_int(Item *item_par) :Cached_item_item(item_par),value(0) {} - bool cmp(void); - int cmp_read_only(); -}; - - -class Cached_item_decimal :public Cached_item_item -{ - my_decimal value; -public: - Cached_item_decimal(Item *item_par); - bool cmp(void); - int cmp_read_only(); -}; - -class Cached_item_field :public Cached_item -{ - uchar *buff; - Field *field; - uint length; - -public: - Cached_item_field(THD *thd, Field *arg_field): field(arg_field) - { - field= arg_field; - /* TODO: take the memory allocation below out of the constructor. */ - buff= (uchar*) thd_calloc(thd, length= field->pack_length()); - } - bool cmp(void); - int cmp_read_only(); -}; - -class Item_default_value : public Item_field -{ - void calculate(); -public: - Item *arg= nullptr; - Field *cached_field= nullptr; - Item_default_value(THD *thd, Name_resolution_context *context_arg, Item *a) : - Item_field(thd, context_arg), arg(a) {} - enum Type type() const { return DEFAULT_VALUE_ITEM; } - bool eq(const Item *item, bool binary_cmp) const; - bool fix_fields(THD *, Item **); - void cleanup(); - void print(String *str, enum_query_type query_type); - String *val_str(String *str); - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal *decimal_value); - bool get_date(THD *thd, MYSQL_TIME *ltime,date_mode_t fuzzydate); - bool val_native(THD *thd, Native *to); - bool send(Protocol *protocol, st_value *buffer); - int save_in_field(Field *field_arg, bool no_conversions); - bool save_in_param(THD *thd, Item_param *param) - { - // It should not be possible to have "EXECUTE .. USING DEFAULT(a)" - DBUG_ASSERT(0); - param->set_default(); - return false; - } - table_map used_tables() const; - virtual void update_used_tables() - { - if (field && field->default_value) - field->default_value->expr->update_used_tables(); - } - Field *get_tmp_table_field() { return 0; } - Item *get_tmp_table_item(THD *thd) { return this; } - Item_field *field_for_view_update() { return 0; } - bool update_vcol_processor(void *arg) { return 0; } - bool check_func_default_processor(void *arg) { return true; } - - bool walk(Item_processor processor, bool walk_subquery, void *args) - { - return (arg && arg->walk(processor, walk_subquery, args)) || - (this->*processor)(args); - } - - Item *transform(THD *thd, Item_transformer transformer, uchar *args); -}; - - -class Item_contextually_typed_value_specification: public Item -{ -public: - Item_contextually_typed_value_specification(THD *thd) :Item(thd) - { } - enum Type type() const { return CONTEXTUALLY_TYPED_VALUE_ITEM; } - bool vcol_assignment_allowed_value() const { return true; } - bool eq(const Item *item, bool binary_cmp) const - { - return false; - } - bool is_evaluable_expression() const { return false; } - Field *create_tmp_field_ex(MEM_ROOT *root, - TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - DBUG_ASSERT(0); - return NULL; - } - String *val_str(String *str) - { - DBUG_ASSERT(0); // never should be called - null_value= true; - return 0; - } - double val_real() - { - DBUG_ASSERT(0); // never should be called - null_value= true; - return 0.0; - } - longlong val_int() - { - DBUG_ASSERT(0); // never should be called - null_value= true; - return 0; - } - my_decimal *val_decimal(my_decimal *decimal_value) - { - DBUG_ASSERT(0); // never should be called - null_value= true; - return 0; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - DBUG_ASSERT(0); // never should be called - return null_value= true; - } - bool send(Protocol *protocol, st_value *buffer) - { - DBUG_ASSERT(0); - return true; - } - const Type_handler *type_handler() const - { - DBUG_ASSERT(0); - return &type_handler_null; - } -}; - - -/* - ::= DEFAULT -*/ -class Item_default_specification: - public Item_contextually_typed_value_specification -{ -public: - Item_default_specification(THD *thd) - :Item_contextually_typed_value_specification(thd) - { } - void print(String *str, enum_query_type query_type) - { - str->append(STRING_WITH_LEN("default")); - } - int save_in_field(Field *field_arg, bool no_conversions) - { - return field_arg->save_in_field_default_value(false); - } - bool save_in_param(THD *thd, Item_param *param) - { - param->set_default(); - return false; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - This class is used as bulk parameter INGNORE representation. - - It just do nothing when assigned to a field - - This is a non-standard MariaDB extension. -*/ - -class Item_ignore_specification: - public Item_contextually_typed_value_specification -{ -public: - Item_ignore_specification(THD *thd) - :Item_contextually_typed_value_specification(thd) - { } - void print(String *str, enum_query_type query_type) - { - str->append(STRING_WITH_LEN("ignore")); - } - int save_in_field(Field *field_arg, bool no_conversions) - { - return field_arg->save_in_field_ignore_value(false); - } - bool save_in_param(THD *thd, Item_param *param) - { - param->set_ignore(); - return false; - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - Item_insert_value -- an implementation of VALUES() function. - You can use the VALUES(col_name) function in the UPDATE clause - to refer to column values from the INSERT portion of the INSERT - ... UPDATE statement. In other words, VALUES(col_name) in the - UPDATE clause refers to the value of col_name that would be - inserted, had no duplicate-key conflict occurred. - In all other places this function returns NULL. -*/ - -class Item_insert_value : public Item_field -{ -public: - Item *arg; - Item_insert_value(THD *thd, Name_resolution_context *context_arg, Item *a) - :Item_field(thd, context_arg), - arg(a) {} - bool eq(const Item *item, bool binary_cmp) const; - bool fix_fields(THD *, Item **); - virtual void print(String *str, enum_query_type query_type); - int save_in_field(Field *field_arg, bool no_conversions) - { - return Item_field::save_in_field(field_arg, no_conversions); - } - enum Type type() const { return INSERT_VALUE_ITEM; } - /* - We use RAND_TABLE_BIT to prevent Item_insert_value from - being treated as a constant and precalculated before execution - */ - table_map used_tables() const { return RAND_TABLE_BIT; } - - Item_field *field_for_view_update() { return 0; } - - bool walk(Item_processor processor, bool walk_subquery, void *args) - { - return arg->walk(processor, walk_subquery, args) || - (this->*processor)(args); - } - bool check_partition_func_processor(void *int_arg) {return TRUE;} - bool update_vcol_processor(void *arg) { return 0; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function("value()", arg, VCOL_IMPOSSIBLE); - } -}; - - -class Table_triggers_list; - -/* - Represents NEW/OLD version of field of row which is - changed/read in trigger. - - Note: For this item main part of actual binding to Field object happens - not during fix_fields() call (like for Item_field) but right after - parsing of trigger definition, when table is opened, with special - setup_field() call. On fix_fields() stage we simply choose one of - two Field instances representing either OLD or NEW version of this - field. -*/ -class Item_trigger_field : public Item_field, - private Settable_routine_parameter -{ -public: - /* Is this item represents row from NEW or OLD row ? */ - enum row_version_type {OLD_ROW, NEW_ROW}; - row_version_type row_version; - /* Next in list of all Item_trigger_field's in trigger */ - Item_trigger_field *next_trg_field; - /* Index of the field in the TABLE::field array */ - uint field_idx; - /* Pointer to Table_trigger_list object for table of this trigger */ - Table_triggers_list *triggers; - - Item_trigger_field(THD *thd, Name_resolution_context *context_arg, - row_version_type row_ver_arg, - const LEX_CSTRING &field_name_arg, - privilege_t priv, const bool ro) - :Item_field(thd, context_arg, field_name_arg), - row_version(row_ver_arg), field_idx((uint)-1), original_privilege(priv), - want_privilege(priv), table_grants(NULL), read_only (ro) - {} - void setup_field(THD *thd, TABLE *table, GRANT_INFO *table_grant_info); - enum Type type() const { return TRIGGER_FIELD_ITEM; } - bool eq(const Item *item, bool binary_cmp) const; - bool fix_fields(THD *, Item **); - virtual void print(String *str, enum_query_type query_type); - table_map used_tables() const { return (table_map)0L; } - Field *get_tmp_table_field() { return 0; } - Item *copy_or_same(THD *thd) { return this; } - Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); } - void cleanup(); - -private: - void set_required_privilege(bool rw); - bool set_value(THD *thd, sp_rcontext *ctx, Item **it); - -public: - Settable_routine_parameter *get_settable_routine_parameter() - { - return (read_only ? 0 : this); - } - - bool set_value(THD *thd, Item **it) - { - return set_value(thd, NULL, it); - } - -private: - /* - 'want_privilege' holds privileges required to perform operation on - this trigger field (SELECT_ACL if we are going to read it and - UPDATE_ACL if we are going to update it). It is initialized at - parse time but can be updated later if this trigger field is used - as OUT or INOUT parameter of stored routine (in this case - set_required_privilege() is called to appropriately update - want_privilege and cleanup() is responsible for restoring of - original want_privilege once parameter's value is updated). - */ - privilege_t original_privilege; - privilege_t want_privilege; - GRANT_INFO *table_grants; - /* - Trigger field is read-only unless it belongs to the NEW row in a - BEFORE INSERT of BEFORE UPDATE trigger. - */ - bool read_only; -public: - bool unknown_splocal_processor(void *arg) { return false; } - bool check_vcol_func_processor(void *arg); -}; - - -/** - @todo - Implement the is_null() method for this class. Currently calling is_null() - on any Item_cache object resolves to Item::is_null(), which returns FALSE - for any value. -*/ - -class Item_cache: public Item, - public Type_handler_hybrid_field_type -{ -protected: - Item *example; - /** - Field that this object will get value from. This is used by - index-based subquery engines to detect and remove the equality injected - by IN->EXISTS transformation. - */ - Field *cached_field; - /* - TRUE <=> cache holds value of the last stored item (i.e actual value). - store() stores item to be cached and sets this flag to FALSE. - On the first call of val_xxx function if this flag is set to FALSE the - cache_value() will be called to actually cache value of saved item. - cache_value() will set this flag to TRUE. - */ - bool value_cached; - - table_map used_table_map; -public: - Item_cache(THD *thd): - Item(thd), - Type_handler_hybrid_field_type(&type_handler_string), - example(0), cached_field(0), - value_cached(0), - used_table_map(0) - { - maybe_null= 1; - null_value= 1; - } -protected: - Item_cache(THD *thd, const Type_handler *handler): - Item(thd), - Type_handler_hybrid_field_type(handler), - example(0), cached_field(0), - value_cached(0), - used_table_map(0) - { - maybe_null= 1; - null_value= 1; - } - -public: - virtual bool allocate(THD *thd, uint i) { return 0; } - virtual bool setup(THD *thd, Item *item) - { - example= item; - Type_std_attributes::set(item); - if (item->type() == FIELD_ITEM) - cached_field= ((Item_field *)item)->field; - return 0; - }; - - void set_used_tables(table_map map) { used_table_map= map; } - table_map used_tables() const { return used_table_map; } - enum Type type() const { return CACHE_ITEM; } - - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - return create_tmp_field_ex_simple(root, table, src, param); - } - - virtual void keep_array() {} - virtual void print(String *str, enum_query_type query_type); - bool eq_def(const Field *field) - { - return cached_field ? cached_field->eq_def (field) : FALSE; - } - bool eq(const Item *item, bool binary_cmp) const - { - return this == item; - } - bool check_vcol_func_processor(void *arg) - { - if (example) - { - Item::vcol_func_processor_result *res= (Item::vcol_func_processor_result*)arg; - example->check_vcol_func_processor(arg); - /* - Item_cache of a non-deterministic function requires re-fixing - even if the function itself doesn't (e.g. CURRENT_TIMESTAMP) - */ - if (res->errors & VCOL_NOT_STRICTLY_DETERMINISTIC) - res->errors|= VCOL_SESSION_FUNC; - return false; - } - return mark_unsupported_function("cache", arg, VCOL_IMPOSSIBLE); - } - void cleanup() - { - clear(); - Item::cleanup(); - } - /** - Check if saved item has a non-NULL value. - Will cache value of saved item if not already done. - @return TRUE if cached value is non-NULL. - */ - bool has_value() - { - return (value_cached || cache_value()) && !null_value; - } - - virtual void store(Item *item); - virtual Item *get_item() { return example; } - virtual bool cache_value()= 0; - bool basic_const_item() const - { return example && example->basic_const_item(); } - virtual void clear() { null_value= TRUE; value_cached= FALSE; } - bool is_null() { return !has_value(); } - virtual bool is_expensive() - { - if (value_cached) - return false; - return example->is_expensive(); - } - bool is_expensive_processor(void *arg) - { - DBUG_ASSERT(example); - if (value_cached) - return false; - return example->is_expensive_processor(arg); - } - virtual void set_null(); - bool walk(Item_processor processor, bool walk_subquery, void *arg) - { - if (arg == STOP_PTR) - return FALSE; - if (example && example->walk(processor, walk_subquery, arg)) - return TRUE; - return (this->*processor)(arg); - } - virtual Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs); - void split_sum_func2_example(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, uint flags) - { - example->split_sum_func2(thd, ref_pointer_array, fields, &example, flags); - } - Item *get_example() const { return example; } - - virtual Item *convert_to_basic_const_item(THD *thd) { return 0; }; - Item *derived_field_transformer_for_having(THD *thd, uchar *arg) - { return convert_to_basic_const_item(thd); } - Item *derived_field_transformer_for_where(THD *thd, uchar *arg) - { return convert_to_basic_const_item(thd); } - Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) - { return convert_to_basic_const_item(thd); } - Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) - { return convert_to_basic_const_item(thd); } - Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) - { return convert_to_basic_const_item(thd); } -}; - - -class Item_cache_int: public Item_cache -{ -protected: - longlong value; -public: - Item_cache_int(THD *thd, const Type_handler *handler): - Item_cache(thd, handler), value(0) {} - - double val_real(); - longlong val_int(); - String* val_str(String *str); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_int(thd, ltime, fuzzydate); } - bool cache_value(); - int save_in_field(Field *field, bool no_conversions); - Item *convert_to_basic_const_item(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_cache_year: public Item_cache_int -{ -public: - Item_cache_year(THD *thd, const Type_handler *handler) - :Item_cache_int(thd, handler) { } - bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) - { - return type_handler_year.Item_get_date_with_warn(thd, this, to, mode); - } -}; - - -class Item_cache_temporal: public Item_cache_int -{ -protected: - Item_cache_temporal(THD *thd, const Type_handler *handler); -public: - bool cache_value(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - int save_in_field(Field *field, bool no_conversions); - bool setup(THD *thd, Item *item) - { - if (Item_cache_int::setup(thd, item)) - return true; - set_if_smaller(decimals, TIME_SECOND_PART_DIGITS); - return false; - } - void store_packed(longlong val_arg, Item *example); - /* - Having a clone_item method tells optimizer that this object - is a constant and need not be optimized further. - Important when storing packed datetime values. - */ - Item *clone_item(THD *thd); - Item *convert_to_basic_const_item(THD *thd); - virtual Item *make_literal(THD *) =0; -}; - - -class Item_cache_time: public Item_cache_temporal -{ -public: - Item_cache_time(THD *thd) - :Item_cache_temporal(thd, &type_handler_time2) { } - bool cache_value(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *make_literal(THD *); - longlong val_datetime_packed(THD *thd) - { - Datetime::Options_cmp opt(thd); - return has_value() ? Datetime(thd, this, opt).to_packed() : 0; - } - longlong val_time_packed(THD *thd) - { - return has_value() ? value : 0; - } - longlong val_int() - { - return has_value() ? Time(this).to_longlong() : 0; - } - double val_real() - { - return has_value() ? Time(this).to_double() : 0; - } - String *val_str(String *to) - { - return has_value() ? Time(this).to_string(to, decimals) : NULL; - } - my_decimal *val_decimal(my_decimal *to) - { - return has_value() ? Time(this).to_decimal(to) : NULL; - } - bool val_native(THD *thd, Native *to) - { - return has_value() ? Time(thd, this).to_native(to, decimals) : true; - } -}; - - -class Item_cache_datetime: public Item_cache_temporal -{ -public: - Item_cache_datetime(THD *thd) - :Item_cache_temporal(thd, &type_handler_datetime2) { } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *make_literal(THD *); - longlong val_datetime_packed(THD *thd) - { - return has_value() ? value : 0; - } - longlong val_time_packed(THD *thd) - { - return Time(thd, this, Time::Options_cmp(thd)).to_packed(); - } - longlong val_int() - { - return has_value() ? Datetime(this).to_longlong() : 0; - } - double val_real() - { - return has_value() ? Datetime(this).to_double() : 0; - } - String *val_str(String *to) - { - return has_value() ? Datetime(this).to_string(to, decimals) : NULL; - } - my_decimal *val_decimal(my_decimal *to) - { - return has_value() ? Datetime(this).to_decimal(to) : NULL; - } -}; - - -class Item_cache_date: public Item_cache_temporal -{ -public: - Item_cache_date(THD *thd) - :Item_cache_temporal(thd, &type_handler_newdate) { } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *make_literal(THD *); - longlong val_datetime_packed(THD *thd) - { - return has_value() ? value : 0; - } - longlong val_time_packed(THD *thd) - { - return Time(thd, this, Time::Options_cmp(thd)).to_packed(); - } - longlong val_int() { return has_value() ? Date(this).to_longlong() : 0; } - double val_real() { return has_value() ? Date(this).to_double() : 0; } - String *val_str(String *to) - { - return has_value() ? Date(this).to_string(to) : NULL; - } - my_decimal *val_decimal(my_decimal *to) - { - return has_value() ? Date(this).to_decimal(to) : NULL; - } -}; - - -class Item_cache_timestamp: public Item_cache -{ - Timestamp_or_zero_datetime_native m_native; - Datetime to_datetime(THD *thd); -public: - Item_cache_timestamp(THD *thd) - :Item_cache(thd, &type_handler_timestamp2) { } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - bool cache_value(); - String* val_str(String *to) - { - return to_datetime(current_thd).to_string(to, decimals); - } - my_decimal *val_decimal(my_decimal *to) - { - return to_datetime(current_thd).to_decimal(to); - } - longlong val_int() - { - return to_datetime(current_thd).to_longlong(); - } - double val_real() - { - return to_datetime(current_thd).to_double(); - } - longlong val_datetime_packed(THD *thd) - { - return to_datetime(current_thd).to_packed(); - } - longlong val_time_packed(THD *thd) - { - DBUG_ASSERT(0); - return 0; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - int save_in_field(Field *field, bool no_conversions); - bool val_native(THD *thd, Native *to); -}; - - -class Item_cache_real: public Item_cache -{ -protected: - double value; -public: - Item_cache_real(THD *thd, const Type_handler *h) - :Item_cache(thd, h), - value(0) - {} - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_real(thd, ltime, fuzzydate); } - bool cache_value(); - Item *convert_to_basic_const_item(THD *thd); -}; - - -class Item_cache_double: public Item_cache_real -{ -public: - Item_cache_double(THD *thd) - :Item_cache_real(thd, &type_handler_double) - { } - String* val_str(String *str); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_cache_float: public Item_cache_real -{ -public: - Item_cache_float(THD *thd) - :Item_cache_real(thd, &type_handler_float) - { } - String* val_str(String *str); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_cache_decimal: public Item_cache -{ -protected: - my_decimal decimal_value; -public: - Item_cache_decimal(THD *thd): Item_cache(thd, &type_handler_newdecimal) {} - - double val_real(); - longlong val_int(); - String* val_str(String *str); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) - { - return decimal_to_datetime_with_warn(thd, VDec(this).ptr(), to, mode, - NULL, NULL); - } - bool cache_value(); - Item *convert_to_basic_const_item(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_cache_str: public Item_cache -{ - char buffer[STRING_BUFFER_USUAL_SIZE]; - String *value, value_buff; - bool is_varbinary; - -public: - Item_cache_str(THD *thd, const Item *item): - Item_cache(thd, item->type_handler()), value(0), - is_varbinary(item->type() == FIELD_ITEM && - Item_cache_str::field_type() == MYSQL_TYPE_VARCHAR && - !((const Item_field *) item)->field->has_charset()) - { - collation.set(const_cast(item->collation)); - } - double val_real(); - longlong val_int(); - String* val_str(String *); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_string(thd, ltime, fuzzydate); } - CHARSET_INFO *charset() const { return value->charset(); }; - int save_in_field(Field *field, bool no_conversions); - bool cache_value(); - Item *convert_to_basic_const_item(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_cache_str_for_nullif: public Item_cache_str -{ -public: - Item_cache_str_for_nullif(THD *thd, const Item *item) - :Item_cache_str(thd, item) - { } - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) - { - /** - Item_cache_str::safe_charset_converter() returns a new Item_cache - with Item_func_conv_charset installed on "example". The original - Item_cache is not referenced (neither directly nor recursively) - from the result of Item_cache_str::safe_charset_converter(). - - For NULLIF() purposes we need a different behavior: - we need a new instance of Item_func_conv_charset, - with the original Item_cache referenced in args[0]. See MDEV-9181. - */ - return Item::safe_charset_converter(thd, tocs); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_cache_row: public Item_cache -{ - Item_cache **values; - uint item_count; - bool save_array; -public: - Item_cache_row(THD *thd): - Item_cache(thd), values(0), item_count(2), - save_array(0) {} - - /* - 'allocate' used only in row transformer, to preallocate space for row - cache. - */ - bool allocate(THD *thd, uint num); - /* - 'setup' is needed only by row => it not called by simple row subselect - (only by IN subselect (in subselect optimizer)) - */ - bool setup(THD *thd, Item *item); - void store(Item *item); - void illegal_method_call(const char *); - void make_send_field(THD *thd, Send_field *) - { - illegal_method_call((const char*)"make_send_field"); - }; - double val_real() - { - illegal_method_call((const char*)"val"); - return 0; - }; - longlong val_int() - { - illegal_method_call((const char*)"val_int"); - return 0; - }; - String *val_str(String *) - { - illegal_method_call((const char*)"val_str"); - return 0; - }; - my_decimal *val_decimal(my_decimal *val) - { - illegal_method_call((const char*)"val_decimal"); - return 0; - }; - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - illegal_method_call((const char*)"val_decimal"); - return true; - } - - uint cols() const { return item_count; } - Item *element_index(uint i) { return values[i]; } - Item **addr(uint i) { return (Item **) (values + i); } - bool check_cols(uint c); - bool null_inside(); - void bring_value(); - void keep_array() { save_array= 1; } - void cleanup() - { - DBUG_ENTER("Item_cache_row::cleanup"); - Item_cache::cleanup(); - if (save_array) - bzero(values, item_count*sizeof(Item**)); - else - values= 0; - DBUG_VOID_RETURN; - } - bool cache_value(); - virtual void set_null(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - Item_type_holder used to store type. name, length of Item for UNIONS & - derived tables. - - Item_type_holder do not need cleanup() because its time of live limited by - single SP/PS execution. -*/ -class Item_type_holder: public Item, - public Type_handler_hybrid_field_type -{ -protected: - const TYPELIB *enum_set_typelib; -public: - Item_type_holder(THD *thd, Item *item) - :Item(thd, item), - Type_handler_hybrid_field_type(item->real_type_handler()), - enum_set_typelib(0) - { - DBUG_ASSERT(item->is_fixed()); - maybe_null= item->maybe_null; - } - Item_type_holder(THD *thd, - Item *item, - const Type_handler *handler, - const Type_all_attributes *attr, - bool maybe_null_arg) - :Item(thd), - Type_handler_hybrid_field_type(handler), - enum_set_typelib(attr->get_typelib()) - { - name= item->name; - Type_std_attributes::set(*attr); - maybe_null= maybe_null_arg; - common_flags= item->common_flags; - } - - const Type_handler *type_handler() const - { - return Type_handler_hybrid_field_type::type_handler()-> - type_handler_for_item_field(); - } - const Type_handler *real_type_handler() const - { - return Type_handler_hybrid_field_type::type_handler(); - } - - enum Type type() const { return TYPE_HOLDER; } - const TYPELIB *get_typelib() const { return enum_set_typelib; } - /* - When handling a query like this: - VALUES ('') UNION VALUES( _utf16 0x0020 COLLATE utf16_bin); - Item_type_holder can be passed to - Type_handler_xxx::Item_hybrid_func_fix_attributes() - We don't want the latter to perform character set conversion of a - Item_type_holder by calling its val_str(), which calls DBUG_ASSERT(0). - Let's override const_item() and is_expensive() to avoid this. - Note, Item_hybrid_func_fix_attributes() could probably - have a new argument to distinguish what we need: - - (a) aggregate data type attributes only - - (b) install converters after attribute aggregation - So st_select_lex_unit::join_union_type_attributes() could - ask it to do (a) only, without (b). - */ - bool const_item() const { return false; } - bool is_expensive() { return true; } - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal *); - String *val_str(String*); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - return Item_type_holder::real_type_handler()-> - make_and_init_table_field(root, &name, Record_addr(maybe_null), - *this, table); - } - Item* get_copy(THD *thd) { return 0; } - -}; - - -class st_select_lex; -void mark_select_range_as_dependent(THD *thd, - st_select_lex *last_select, - st_select_lex *current_sel, - Field *found_field, Item *found_item, - Item_ident *resolved_item); - -extern Cached_item *new_Cached_item(THD *thd, Item *item, - bool pass_through_ref); -extern Item_result item_cmp_type(Item_result a,Item_result b); -extern void resolve_const_item(THD *thd, Item **ref, Item *cmp_item); -extern int stored_field_cmp_to_item(THD *thd, Field *field, Item *item); - -extern const String my_null_string; - -/** - Interface for Item iterator -*/ - -class Item_iterator -{ -public: - /** - Shall set this iterator to the position before the first item - - @note - This method also may perform some other initialization actions like - allocation of certain resources. - */ - virtual void open()= 0; - /** - Shall return the next Item (or NULL if there is no next item) and - move pointer to position after it. - */ - virtual Item *next()= 0; - /** - Shall force iterator to free resources (if it holds them) - - @note - One should not use the iterator without open() call after close() - */ - virtual void close()= 0; - - virtual ~Item_iterator() {} -}; - - -/** - Item iterator over List_iterator_fast for Item references -*/ - -class Item_iterator_ref_list: public Item_iterator -{ - List_iterator list; -public: - Item_iterator_ref_list(List_iterator &arg_list): - list(arg_list) {} - void open() { list.rewind(); } - Item *next() { return *(list++); } - void close() {} -}; - - -/** - Item iterator over List_iterator_fast for Items -*/ - -class Item_iterator_list: public Item_iterator -{ - List_iterator list; -public: - Item_iterator_list(List_iterator &arg_list): - list(arg_list) {} - void open() { list.rewind(); } - Item *next() { return (list++); } - void close() {} -}; - - -/** - Item iterator over Item interface for rows -*/ - -class Item_iterator_row: public Item_iterator -{ - Item *base_item; - uint current; -public: - Item_iterator_row(Item *base) : base_item(base), current(0) {} - void open() { current= 0; } - Item *next() - { - if (current >= base_item->cols()) - return NULL; - return base_item->element_index(current++); - } - void close() {} -}; - - -/* - It's used in ::fix_fields() methods of LIKE and JSON_SEARCH - functions to handle the ESCAPE parameter. - This parameter is quite non-standard so the specific function. -*/ -bool fix_escape_item(THD *thd, Item *escape_item, String *tmp_str, - bool escape_used_in_parsing, CHARSET_INFO *cmp_cs, - int *escape); - -inline bool Virtual_column_info::is_equal(const Virtual_column_info* vcol) const -{ - return type_handler() == vcol->type_handler() - && stored_in_db == vcol->is_stored() - && expr->eq(vcol->expr, true); -} - -inline void Virtual_column_info::print(String* str) -{ - expr->print_for_table_def(str); -} - -inline bool TABLE::mark_column_with_deps(Field *field) -{ - bool res; - if (!(res= bitmap_fast_test_and_set(read_set, field->field_index))) - { - if (field->vcol_info) - mark_virtual_column_deps(field); - } - return res; -} - -inline bool TABLE::mark_virtual_column_with_deps(Field *field) -{ - bool res; - DBUG_ASSERT(field->vcol_info); - if (!(res= bitmap_fast_test_and_set(read_set, field->field_index))) - mark_virtual_column_deps(field); - return res; -} - -inline void TABLE::mark_virtual_column_deps(Field *field) -{ - DBUG_ASSERT(field->vcol_info); - DBUG_ASSERT(field->vcol_info->expr); - field->vcol_info->expr->walk(&Item::register_field_in_read_map, 1, 0); -} - -inline void TABLE::use_all_stored_columns() -{ - bitmap_set_all(read_set); - if (Field **vf= vfield) - for (; *vf; vf++) - bitmap_clear_bit(read_set, (*vf)->field_index); -} - -#endif /* SQL_ITEM_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_cmpfunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_cmpfunc.h deleted file mode 100644 index fa715ba..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_cmpfunc.h +++ /dev/null @@ -1,3590 +0,0 @@ -#ifndef ITEM_CMPFUNC_INCLUDED -#define ITEM_CMPFUNC_INCLUDED -/* Copyright (c) 2000, 2015, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* compare and test functions */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "item_func.h" /* Item_int_func, Item_bool_func */ -#include "item.h" - -extern Item_result item_cmp_type(Item_result a,Item_result b); -inline Item_result item_cmp_type(const Item *a, const Item *b) -{ - return item_cmp_type(a->cmp_type(), b->cmp_type()); -} -inline Item_result item_cmp_type(Item_result a, const Item *b) -{ - return item_cmp_type(a, b->cmp_type()); -} -class Item_bool_func2; -class Arg_comparator; - -typedef int (Arg_comparator::*arg_cmp_func)(); - -typedef int (*Item_field_cmpfunc)(Item *f1, Item *f2, void *arg); - -class Arg_comparator: public Sql_alloc -{ - Item **a, **b; - const Type_handler *m_compare_handler; - CHARSET_INFO *m_compare_collation; - arg_cmp_func func; - Item_func_or_sum *owner; - bool set_null; // TRUE <=> set owner->null_value - Arg_comparator *comparators; // used only for compare_row() - double precision; - /* Fields used in DATE/DATETIME comparison. */ - Item *a_cache, *b_cache; // Cached values of a and b items - // when one of arguments is NULL. - - int set_cmp_func(Item_func_or_sum *owner_arg, Item **a1, Item **a2); - - int compare_not_null_values(longlong val1, longlong val2) - { - if (set_null) - owner->null_value= false; - if (val1 < val2) return -1; - if (val1 == val2) return 0; - return 1; - } - NativeBuffer m_native1, m_native2; -public: - /* Allow owner function to use string buffers. */ - String value1, value2; - - Arg_comparator(): - m_compare_handler(&type_handler_null), - m_compare_collation(&my_charset_bin), - set_null(TRUE), comparators(0), - a_cache(0), b_cache(0) {}; - Arg_comparator(Item **a1, Item **a2): a(a1), b(a2), - m_compare_handler(&type_handler_null), - m_compare_collation(&my_charset_bin), - set_null(TRUE), comparators(0), - a_cache(0), b_cache(0) {}; - -public: - bool set_cmp_func_for_row_arguments(); - bool set_cmp_func_row(); - bool set_cmp_func_string(); - bool set_cmp_func_time(); - bool set_cmp_func_datetime(); - bool set_cmp_func_native(); - bool set_cmp_func_int(); - bool set_cmp_func_real(); - bool set_cmp_func_decimal(); - - inline int set_cmp_func(Item_func_or_sum *owner_arg, - Item **a1, Item **a2, bool set_null_arg) - { - set_null= set_null_arg; - return set_cmp_func(owner_arg, a1, a2); - } - inline int compare() { return (this->*func)(); } - - int compare_string(); // compare args[0] & args[1] - int compare_real(); // compare args[0] & args[1] - int compare_decimal(); // compare args[0] & args[1] - int compare_int_signed(); // compare args[0] & args[1] - int compare_int_signed_unsigned(); - int compare_int_unsigned_signed(); - int compare_int_unsigned(); - int compare_row(); // compare args[0] & args[1] - int compare_e_string(); // compare args[0] & args[1] - int compare_e_real(); // compare args[0] & args[1] - int compare_e_decimal(); // compare args[0] & args[1] - int compare_e_int(); // compare args[0] & args[1] - int compare_e_int_diff_signedness(); - int compare_e_row(); // compare args[0] & args[1] - int compare_real_fixed(); - int compare_e_real_fixed(); - int compare_datetime(); - int compare_e_datetime(); - int compare_time(); - int compare_e_time(); - int compare_native(); - int compare_e_native(); - int compare_json_str_basic(Item *j, Item *s); - int compare_json_str(); - int compare_str_json(); - int compare_e_json_str_basic(Item *j, Item *s); - int compare_e_json_str(); - int compare_e_str_json(); - - void min_max_update_field_native(THD *thd, Field *field, Item *item, - int cmp_sign); - - Item** cache_converted_constant(THD *thd, Item **value, Item **cache, - const Type_handler *type); - inline bool is_owner_equal_func() - { - return (owner->type() == Item::FUNC_ITEM && - ((Item_func*)owner)->functype() == Item_func::EQUAL_FUNC); - } - const Type_handler *compare_type_handler() const { return m_compare_handler; } - Item_result compare_type() const { return m_compare_handler->cmp_type(); } - CHARSET_INFO *compare_collation() const { return m_compare_collation; } - Arg_comparator *subcomparators() const { return comparators; } - void cleanup() - { - delete [] comparators; - comparators= 0; - } - friend class Item_func; - friend class Item_bool_rowready_func2; -}; - - -class SEL_ARG; -struct KEY_PART; - -class Item_bool_func :public Item_int_func, - public Type_cmp_attributes -{ -protected: - /* - Build a SEL_TREE for a simple predicate - @param param PARAM from SQL_SELECT::test_quick_select - @param field field in the predicate - @param value constant in the predicate - @return Pointer to the tree built tree - */ - virtual SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *value) - { - DBUG_ENTER("Item_bool_func::get_func_mm_tree"); - DBUG_ASSERT(0); - DBUG_RETURN(0); - } - /* - Return the full select tree for "field_item" and "value": - - a single SEL_TREE if the field is not in a multiple equality, or - - a conjunction of all SEL_TREEs for all fields from - the same multiple equality with "field_item". - */ - SEL_TREE *get_full_func_mm_tree(RANGE_OPT_PARAM *param, - Item_field *field_item, Item *value); - /** - Test if "item" and "value" are suitable for the range optimization - and get their full select tree. - - "Suitable" means: - - "item" is a field or a field reference - - "value" is NULL (e.g. WHERE field IS NULL), or - "value" is an unexpensive item (e.g. WHERE field OP value) - - @param item - the argument that is checked to be a field - @param value - the other argument - @returns - NULL if the arguments are not suitable for the range optimizer. - @returns - the full select tree if the arguments are suitable. - */ - SEL_TREE *get_full_func_mm_tree_for_args(RANGE_OPT_PARAM *param, - Item *item, Item *value) - { - DBUG_ENTER("Item_bool_func::get_full_func_mm_tree_for_args"); - Item *field= item->real_item(); - if (field->type() == Item::FIELD_ITEM && !field->const_item() && - (!value || !value->is_expensive())) - DBUG_RETURN(get_full_func_mm_tree(param, (Item_field *) field, value)); - DBUG_RETURN(NULL); - } - SEL_TREE *get_mm_parts(RANGE_OPT_PARAM *param, Field *field, - Item_func::Functype type, Item *value); - SEL_TREE *get_ne_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *lt_value, Item *gt_value); - virtual SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, - KEY_PART *key_part, - Item_func::Functype type, Item *value); -public: - Item_bool_func(THD *thd): Item_int_func(thd) {} - Item_bool_func(THD *thd, Item *a): Item_int_func(thd, a) {} - Item_bool_func(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} - Item_bool_func(THD *thd, Item *a, Item *b, Item *c): Item_int_func(thd, a, b, c) {} - Item_bool_func(THD *thd, List &list): Item_int_func(thd, list) { } - Item_bool_func(THD *thd, Item_bool_func *item) :Item_int_func(thd, item) {} - const Type_handler *type_handler() const { return &type_handler_bool; } - const Type_handler *fixed_type_handler() const { return &type_handler_bool; } - CHARSET_INFO *compare_collation() const { return NULL; } - bool fix_length_and_dec() { decimals=0; max_length=1; return FALSE; } - uint decimal_precision() const { return 1; } - bool need_parentheses_in_default() { return true; } -}; - - -/** - Abstract Item class, to represent X IS [NOT] (TRUE | FALSE) - boolean predicates. -*/ - -class Item_func_truth : public Item_bool_func -{ -public: - virtual bool val_bool(); - virtual longlong val_int(); - virtual bool fix_length_and_dec(); - virtual void print(String *str, enum_query_type query_type); - enum precedence precedence() const { return CMP_PRECEDENCE; } - -protected: - Item_func_truth(THD *thd, Item *a, bool a_value, bool a_affirmative): - Item_bool_func(thd, a), value(a_value), affirmative(a_affirmative) - {} - - ~Item_func_truth() - {} -private: - /** - True for X IS [NOT] TRUE, - false for X IS [NOT] FALSE predicates. - */ - const bool value; - /** - True for X IS Y, false for X IS NOT Y predicates. - */ - const bool affirmative; -}; - - -/** - This Item represents a X IS TRUE boolean predicate. -*/ - -class Item_func_istrue : public Item_func_truth -{ -public: - Item_func_istrue(THD *thd, Item *a): Item_func_truth(thd, a, true, true) {} - ~Item_func_istrue() {} - virtual const char* func_name() const { return "istrue"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - This Item represents a X IS NOT TRUE boolean predicate. -*/ - -class Item_func_isnottrue : public Item_func_truth -{ -public: - Item_func_isnottrue(THD *thd, Item *a): - Item_func_truth(thd, a, true, false) {} - ~Item_func_isnottrue() {} - virtual const char* func_name() const { return "isnottrue"; } - bool find_not_null_fields(table_map allowed) { return false; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - bool eval_not_null_tables(void *) { not_null_tables_cache= 0; return false; } -}; - - -/** - This Item represents a X IS FALSE boolean predicate. -*/ - -class Item_func_isfalse : public Item_func_truth -{ -public: - Item_func_isfalse(THD *thd, Item *a): Item_func_truth(thd, a, false, true) {} - ~Item_func_isfalse() {} - virtual const char* func_name() const { return "isfalse"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - This Item represents a X IS NOT FALSE boolean predicate. -*/ - -class Item_func_isnotfalse : public Item_func_truth -{ -public: - Item_func_isnotfalse(THD *thd, Item *a): - Item_func_truth(thd, a, false, false) {} - ~Item_func_isnotfalse() {} - virtual const char* func_name() const { return "isnotfalse"; } - bool find_not_null_fields(table_map allowed) { return false; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - bool eval_not_null_tables(void *) { not_null_tables_cache= 0; return false; } -}; - - -class Item_cache; -#define UNKNOWN (-1) - - -/* - Item_in_optimizer(left_expr, Item_in_subselect(...)) - - Item_in_optimizer is used to wrap an instance of Item_in_subselect. This - class does the following: - - Evaluate the left expression and store it in Item_cache_* object (to - avoid re-evaluating it many times during subquery execution) - - Shortcut the evaluation of "NULL IN (...)" to NULL in the cases where we - don't care if the result is NULL or FALSE. - - NOTE - It is not quite clear why the above listed functionality should be - placed into a separate class called 'Item_in_optimizer'. -*/ - -class Item_in_optimizer: public Item_bool_func -{ -protected: - Item_cache *cache; - Item *expr_cache; - bool save_cache; - /* - Stores the value of "NULL IN (SELECT ...)" for uncorrelated subqueries: - UNKNOWN - "NULL in (SELECT ...)" has not yet been evaluated - FALSE - result is FALSE - TRUE - result is NULL - */ - int result_for_null_param; -public: - Item_in_optimizer(THD *thd, Item *a, Item *b): - Item_bool_func(thd, a, b), cache(0), expr_cache(0), - save_cache(0), result_for_null_param(UNKNOWN) - { m_with_subquery= true; } - bool fix_fields(THD *, Item **) override; - bool fix_left(THD *thd); - table_map not_null_tables() const override { return 0; } - bool is_null() override; - longlong val_int() override; - void cleanup() override; - enum Functype functype() const override { return IN_OPTIMIZER_FUNC; } - const char *func_name() const override { return ""; } - Item_cache **get_cache() { return &cache; } - void keep_top_level_cache(); - Item *transform(THD *thd, Item_transformer transformer, uchar *arg) override; - Item *expr_cache_insert_transformer(THD *thd, uchar *unused) override; - bool is_expensive_processor(void *arg) override; - bool is_expensive() override; - void set_join_tab_idx(uint join_tab_idx_arg) override - { args[1]->set_join_tab_idx(join_tab_idx_arg); } - void get_cache_parameters(List ¶meters) override; - bool is_top_level_item() const override; - bool eval_not_null_tables(void *opt_arg) override; - bool find_not_null_fields(table_map allowed) override; - void fix_after_pullout(st_select_lex *new_parent, Item **ref, - bool merge) override; - bool invisible_mode(); - void reset_cache() { cache= NULL; } - void print(String *str, enum_query_type query_type) override; - void restore_first_argument(); - Item* get_wrapped_in_subselect_item() - { return args[1]; } - Item *get_copy(THD *thd) override - { return get_item_copy(thd, this); } - enum precedence precedence() const override { return args[1]->precedence(); } -}; - - -/* - Functions and operators with two arguments that can use range optimizer. -*/ -class Item_bool_func2 :public Item_bool_func -{ /* Bool with 2 string args */ -protected: - void add_key_fields_optimize_op(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables, bool equal_func); -public: - Item_bool_func2(THD *thd, Item *a, Item *b): - Item_bool_func(thd, a, b) { } - - bool is_null() { return MY_TEST(args[0]->is_null() || args[1]->is_null()); } - COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, - bool top_level); - bool count_sargable_conds(void *arg); - /* - Specifies which result type the function uses to compare its arguments. - This method is used in equal field propagation. - */ - virtual const Type_handler *compare_type_handler() const - { - /* - Have STRING_RESULT by default, which means the function compares - val_str() results of the arguments. This is suitable for Item_func_like - and for Item_func_spatial_rel. - Note, Item_bool_rowready_func2 overrides this default behaviour. - */ - return &type_handler_varchar; - } - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) - { - DBUG_ENTER("Item_bool_func2::get_mm_tree"); - DBUG_ASSERT(arg_count == 2); - SEL_TREE *ftree= get_full_func_mm_tree_for_args(param, args[0], args[1]); - if (!ftree) - ftree= Item_func::get_mm_tree(param, cond_ptr); - DBUG_RETURN(ftree); - } -}; - - -/** - A class for functions and operators that can use the range optimizer and - have a reverse function/operator that can also use the range optimizer, - so this condition: - WHERE value OP field - can be optimized as equivalent to: - WHERE field REV_OP value - - This class covers: - - scalar comparison predicates: <, <=, =, <=>, >=, > - - MBR and precise spatial relation predicates (e.g. SP_TOUCHES(x,y)) - - For example: - WHERE 10 > field - can be optimized as: - WHERE field < 10 -*/ -class Item_bool_func2_with_rev :public Item_bool_func2 -{ -protected: - SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *value) - { - DBUG_ENTER("Item_bool_func2_with_rev::get_func_mm_tree"); - Item_func::Functype func_type= - (value != arguments()[0]) ? functype() : rev_functype(); - DBUG_RETURN(get_mm_parts(param, field, func_type, value)); - } -public: - Item_bool_func2_with_rev(THD *thd, Item *a, Item *b): - Item_bool_func2(thd, a, b) { } - virtual enum Functype rev_functype() const= 0; - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) - { - DBUG_ENTER("Item_bool_func2_with_rev::get_mm_tree"); - DBUG_ASSERT(arg_count == 2); - SEL_TREE *ftree; - /* - Even if get_full_func_mm_tree_for_args(param, args[0], args[1]) will not - return a range predicate it may still be possible to create one - by reversing the order of the operands. Note that this only - applies to predicates where both operands are fields. Example: A - query of the form - - WHERE t1.a OP t2.b - - In this case, args[0] == t1.a and args[1] == t2.b. - When creating range predicates for t2, - get_full_func_mm_tree_for_args(param, args[0], args[1]) - will return NULL because 'field' belongs to t1 and only - predicates that applies to t2 are of interest. In this case a - call to get_full_func_mm_tree_for_args() with reversed operands - may succeed. - */ - if (!(ftree= get_full_func_mm_tree_for_args(param, args[0], args[1])) && - !(ftree= get_full_func_mm_tree_for_args(param, args[1], args[0]))) - ftree= Item_func::get_mm_tree(param, cond_ptr); - DBUG_RETURN(ftree); - } -}; - - -class Item_bool_rowready_func2 :public Item_bool_func2_with_rev -{ -protected: - Arg_comparator cmp; - bool check_arguments() const - { - return check_argument_types_like_args0(); - } -public: - Item_bool_rowready_func2(THD *thd, Item *a, Item *b): - Item_bool_func2_with_rev(thd, a, b), cmp(tmp_arg, tmp_arg + 1) - { } - Sql_mode_dependency value_depends_on_sql_mode() const; - void print(String *str, enum_query_type query_type) - { - Item_func::print_op(str, query_type); - } - enum precedence precedence() const { return CMP_PRECEDENCE; } - Item *neg_transformer(THD *thd); - virtual Item *negated_item(THD *thd); - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - Item_args::propagate_equal_fields(thd, - Context(ANY_SUBST, - cmp.compare_type_handler(), - compare_collation()), - cond); - return this; - } - bool fix_length_and_dec(); - int set_cmp_func() - { - return cmp.set_cmp_func(this, tmp_arg, tmp_arg + 1, true); - } - CHARSET_INFO *compare_collation() const { return cmp.compare_collation(); } - const Type_handler *compare_type_handler() const - { - return cmp.compare_type_handler(); - } - Arg_comparator *get_comparator() { return &cmp; } - void cleanup() - { - Item_bool_func2::cleanup(); - cmp.cleanup(); - } - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables) - { - return add_key_fields_optimize_op(join, key_fields, and_level, - usable_tables, sargables, false); - } - Item *build_clone(THD *thd) - { - Item_bool_rowready_func2 *clone= - (Item_bool_rowready_func2 *) Item_func::build_clone(thd); - if (clone) - { - clone->cmp.comparators= 0; - } - return clone; - } -}; - -/** - XOR inherits from Item_bool_func because it is not optimized yet. - Later, when XOR is optimized, it needs to inherit from - Item_cond instead. See WL#5800. -*/ -class Item_func_xor :public Item_bool_func -{ -public: - Item_func_xor(THD *thd, Item *i1, Item *i2): Item_bool_func(thd, i1, i2) {} - enum Functype functype() const { return XOR_FUNC; } - const char *func_name() const { return "xor"; } - enum precedence precedence() const { return XOR_PRECEDENCE; } - void print(String *str, enum_query_type query_type) - { Item_func::print_op(str, query_type); } - longlong val_int(); - bool find_not_null_fields(table_map allowed) { return false; } - Item *neg_transformer(THD *thd); - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - Item_args::propagate_equal_fields(thd, Context_boolean(), cond); - return this; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_not :public Item_bool_func -{ - bool abort_on_null; -public: - Item_func_not(THD *thd, Item *a): - Item_bool_func(thd, a), abort_on_null(FALSE) {} - void top_level_item() override { abort_on_null= 1; } - bool is_top_level_item() const override { return abort_on_null; } - longlong val_int() override; - enum Functype functype() const override { return NOT_FUNC; } - const char *func_name() const override { return "not"; } - bool find_not_null_fields(table_map allowed) override { return false; } - enum precedence precedence() const override { return NEG_PRECEDENCE; } - Item *neg_transformer(THD *thd) override; - bool fix_fields(THD *, Item **) override; - void print(String *str, enum_query_type query_type) override; - Item *get_copy(THD *thd) override - { return get_item_copy(thd, this); } -}; - -class Item_maxmin_subselect; - -/* - trigcond(arg) ::= param? arg : TRUE - - The class Item_func_trig_cond is used for guarded predicates - which are employed only for internal purposes. - A guarded predicate is an object consisting of an a regular or - a guarded predicate P and a pointer to a boolean guard variable g. - A guarded predicate P/g is evaluated to true if the value of the - guard g is false, otherwise it is evaluated to the same value that - the predicate P: val(P/g)= g ? val(P):true. - Guarded predicates allow us to include predicates into a conjunction - conditionally. Currently they are utilized for pushed down predicates - in queries with outer join operations. - - In the future, probably, it makes sense to extend this class to - the objects consisting of three elements: a predicate P, a pointer - to a variable g and a firing value s with following evaluation - rule: val(P/g,s)= g==s? val(P) : true. It will allow us to build only - one item for the objects of the form P/g1/g2... - - Objects of this class are built only for query execution after - the execution plan has been already selected. That's why this - class needs only val_int out of generic methods. - - Current uses of Item_func_trig_cond objects: - - To wrap selection conditions when executing outer joins - - To wrap condition that is pushed down into subquery -*/ - -class Item_func_trig_cond: public Item_bool_func -{ - bool *trig_var; -public: - Item_func_trig_cond(THD *thd, Item *a, bool *f): Item_bool_func(thd, a) - { trig_var= f; } - longlong val_int() { return *trig_var ? args[0]->val_int() : 1; } - enum Functype functype() const { return TRIG_COND_FUNC; }; - const char *func_name() const { return "trigcond"; }; - bool const_item() const { return FALSE; } - bool *get_trig_var() { return trig_var; } - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_not_all :public Item_func_not -{ - /* allow to check presence of values in max/min optimization */ - Item_sum_min_max *test_sum_item; - Item_maxmin_subselect *test_sub_item; - -public: - bool show; - - Item_func_not_all(THD *thd, Item *a): - Item_func_not(thd, a), test_sum_item(0), test_sub_item(0), show(0) - {} - table_map not_null_tables() const { return 0; } - longlong val_int(); - enum Functype functype() const { return NOT_ALL_FUNC; } - const char *func_name() const { return ""; } - bool fix_fields(THD *thd, Item **ref) - {return Item_func::fix_fields(thd, ref);} - virtual void print(String *str, enum_query_type query_type); - void set_sum_test(Item_sum_min_max *item) { test_sum_item= item; test_sub_item= 0; }; - void set_sub_test(Item_maxmin_subselect *item) { test_sub_item= item; test_sum_item= 0;}; - bool empty_underlying_subquery(); - Item *neg_transformer(THD *thd); -}; - - -class Item_func_nop_all :public Item_func_not_all -{ -public: - - Item_func_nop_all(THD *thd, Item *a): Item_func_not_all(thd, a) {} - longlong val_int(); - const char *func_name() const { return ""; } - Item *neg_transformer(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_eq :public Item_bool_rowready_func2 -{ - bool abort_on_null; -public: - Item_func_eq(THD *thd, Item *a, Item *b): - Item_bool_rowready_func2(thd, a, b), - abort_on_null(false), in_equality_no(UINT_MAX) - {} - longlong val_int(); - enum Functype functype() const { return EQ_FUNC; } - enum Functype rev_functype() const { return EQ_FUNC; } - cond_result eq_cmp_result() const { return COND_TRUE; } - const char *func_name() const { return "="; } - void top_level_item() { abort_on_null= true; } - Item *negated_item(THD *thd); - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref); - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables) - { - return add_key_fields_optimize_op(join, key_fields, and_level, - usable_tables, sargables, true); - } - bool check_equality(THD *thd, COND_EQUAL *cond, List *eq_list); - /* - - If this equality is created from the subquery's IN-equality: - number of the item it was created from, e.g. for - (a,b) IN (SELECT c,d ...) a=c will have in_equality_no=0, - and b=d will have in_equality_no=1. - - Otherwise, UINT_MAX - */ - uint in_equality_no; - virtual uint exists2in_reserved_items() { return 1; }; - friend class Arg_comparator; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_equal final :public Item_bool_rowready_func2 -{ -public: - Item_func_equal(THD *thd, Item *a, Item *b): - Item_bool_rowready_func2(thd, a, b) {} - longlong val_int(); - bool fix_length_and_dec(); - table_map not_null_tables() const { return 0; } - bool find_not_null_fields(table_map allowed) { return false; } - enum Functype functype() const { return EQUAL_FUNC; } - enum Functype rev_functype() const { return EQUAL_FUNC; } - cond_result eq_cmp_result() const { return COND_TRUE; } - const char *func_name() const { return "<=>"; } - Item *neg_transformer(THD *thd) { return 0; } - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables) - { - return add_key_fields_optimize_op(join, key_fields, and_level, - usable_tables, sargables, true); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_ge :public Item_bool_rowready_func2 -{ -public: - Item_func_ge(THD *thd, Item *a, Item *b): - Item_bool_rowready_func2(thd, a, b) {}; - longlong val_int(); - enum Functype functype() const { return GE_FUNC; } - enum Functype rev_functype() const { return LE_FUNC; } - cond_result eq_cmp_result() const { return COND_TRUE; } - const char *func_name() const { return ">="; } - Item *negated_item(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_gt :public Item_bool_rowready_func2 -{ -public: - Item_func_gt(THD *thd, Item *a, Item *b): - Item_bool_rowready_func2(thd, a, b) {}; - longlong val_int(); - enum Functype functype() const { return GT_FUNC; } - enum Functype rev_functype() const { return LT_FUNC; } - cond_result eq_cmp_result() const { return COND_FALSE; } - const char *func_name() const { return ">"; } - Item *negated_item(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_le :public Item_bool_rowready_func2 -{ -public: - Item_func_le(THD *thd, Item *a, Item *b): - Item_bool_rowready_func2(thd, a, b) {}; - longlong val_int(); - enum Functype functype() const { return LE_FUNC; } - enum Functype rev_functype() const { return GE_FUNC; } - cond_result eq_cmp_result() const { return COND_TRUE; } - const char *func_name() const { return "<="; } - Item *negated_item(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_lt :public Item_bool_rowready_func2 -{ -public: - Item_func_lt(THD *thd, Item *a, Item *b): - Item_bool_rowready_func2(thd, a, b) {} - longlong val_int(); - enum Functype functype() const { return LT_FUNC; } - enum Functype rev_functype() const { return GT_FUNC; } - cond_result eq_cmp_result() const { return COND_FALSE; } - const char *func_name() const { return "<"; } - Item *negated_item(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_ne :public Item_bool_rowready_func2 -{ -protected: - SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *value) - { - DBUG_ENTER("Item_func_ne::get_func_mm_tree"); - DBUG_RETURN(get_ne_mm_tree(param, field, value, value)); - } -public: - Item_func_ne(THD *thd, Item *a, Item *b): - Item_bool_rowready_func2(thd, a, b) {} - longlong val_int(); - enum Functype functype() const { return NE_FUNC; } - enum Functype rev_functype() const { return NE_FUNC; } - cond_result eq_cmp_result() const { return COND_FALSE; } - const char *func_name() const { return "<>"; } - Item *negated_item(THD *thd); - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, - table_map usable_tables, SARGABLE_PARAM **sargables); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - The class Item_func_opt_neg is defined to factor out the functionality - common for the classes Item_func_between and Item_func_in. The objects - of these classes can express predicates or there negations. - The alternative approach would be to create pairs Item_func_between, - Item_func_notbetween and Item_func_in, Item_func_notin. - -*/ - -class Item_func_opt_neg :public Item_bool_func -{ -protected: - /* - The data type handler that will be used for comparison. - Data type handlers of all arguments are mixed to here. - */ - Type_handler_hybrid_field_type m_comparator; - /* - The collation that will be used for comparison in case - when m_compare_type is STRING_RESULT. - */ - DTCollation cmp_collation; -public: - bool negated; /* <=> the item represents NOT */ - bool pred_level; /* <=> [NOT] is used on a predicate level */ -public: - Item_func_opt_neg(THD *thd, Item *a, Item *b, Item *c): - Item_bool_func(thd, a, b, c), negated(0), pred_level(0) {} - Item_func_opt_neg(THD *thd, List &list): - Item_bool_func(thd, list), negated(0), pred_level(0) {} -public: - void top_level_item() override { pred_level= 1; } - bool is_top_level_item() const override { return pred_level; } - Item *neg_transformer(THD *thd) override - { - negated= !negated; - return this; - } - bool eq(const Item *item, bool binary_cmp) const override; - CHARSET_INFO *compare_collation() const override - { - return cmp_collation.collation; - } - Item *propagate_equal_fields(THD *, const Context &, - COND_EQUAL *) override= 0; -}; - -class Item_func_between :public Item_func_opt_neg -{ -protected: - SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *value); - bool val_int_cmp_int_finalize(longlong value, longlong a, longlong b); -public: - String value0,value1,value2; - Item_func_between(THD *thd, Item *a, Item *b, Item *c): - Item_func_opt_neg(thd, a, b, c) { } - longlong val_int() - { - DBUG_ASSERT(fixed); - return m_comparator.type_handler()->Item_func_between_val_int(this); - } - enum Functype functype() const { return BETWEEN; } - const char *func_name() const { return "between"; } - enum precedence precedence() const { return BETWEEN_PRECEDENCE; } - bool fix_length_and_dec(); - bool fix_length_and_dec_string(THD *) - { - return agg_arg_charsets_for_comparison(cmp_collation, args, 3); - } - bool fix_length_and_dec_temporal(THD *); - bool fix_length_and_dec_numeric(THD *); - virtual void print(String *str, enum_query_type query_type); - bool eval_not_null_tables(void *opt_arg); - bool find_not_null_fields(table_map allowed); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - bool count_sargable_conds(void *arg); - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - Item_args::propagate_equal_fields(thd, - Context(ANY_SUBST, - m_comparator.type_handler(), - compare_collation()), - cond); - return this; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - - longlong val_int_cmp_string(); - longlong val_int_cmp_datetime(); - longlong val_int_cmp_time(); - longlong val_int_cmp_native(); - longlong val_int_cmp_int(); - longlong val_int_cmp_real(); - longlong val_int_cmp_decimal(); -}; - - -class Item_func_strcmp :public Item_long_func -{ - bool check_arguments() const - { return check_argument_types_can_return_str(0, 2); } - String value1, value2; - DTCollation cmp_collation; -public: - Item_func_strcmp(THD *thd, Item *a, Item *b): - Item_long_func(thd, a, b) {} - longlong val_int(); - uint decimal_precision() const { return 1; } - const char *func_name() const { return "strcmp"; } - bool fix_length_and_dec() - { - if (agg_arg_charsets_for_comparison(cmp_collation, args, 2)) - return TRUE; - fix_char_length(2); // returns "1" or "0" or "-1" - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -struct interval_range -{ - Item_result type; - double dbl; - my_decimal dec; -}; - -class Item_func_interval :public Item_long_func -{ - Item_row *row; - bool use_decimal_comparison; - interval_range *intervals; - bool check_arguments() const - { - return check_argument_types_like_args0(); - } -public: - Item_func_interval(THD *thd, Item_row *a): - Item_long_func(thd, a), row(a), intervals(0) - { } - bool fix_fields(THD *, Item **); - longlong val_int(); - bool fix_length_and_dec(); - const char *func_name() const { return "interval"; } - uint decimal_precision() const { return 2; } - void print(String *str, enum_query_type query_type) - { - str->append(func_name()); - print_args(str, 0, query_type); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_coalesce :public Item_func_case_expression -{ -public: - Item_func_coalesce(THD *thd, Item *a, Item *b): - Item_func_case_expression(thd, a, b) {} - Item_func_coalesce(THD *thd, List &list): - Item_func_case_expression(thd, list) {} - double real_op(); - longlong int_op(); - String *str_op(String *); - my_decimal *decimal_op(my_decimal *); - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool time_op(THD *thd, MYSQL_TIME *ltime); - bool native_op(THD *thd, Native *to); - bool fix_length_and_dec() - { - if (aggregate_for_result(func_name(), args, arg_count, true)) - return TRUE; - fix_attributes(args, arg_count); - return FALSE; - } - const char *func_name() const { return "coalesce"; } - table_map not_null_tables() const { return 0; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - Case abbreviations that aggregate its result field type by two arguments: - IFNULL(arg1, arg2) - IF(switch, arg1, arg2) - NVL2(switch, arg1, arg2) -*/ -class Item_func_case_abbreviation2 :public Item_func_case_expression -{ -protected: - bool fix_length_and_dec2(Item **items) - { - if (aggregate_for_result(func_name(), items, 2, true)) - return TRUE; - fix_attributes(items, 2); - return FALSE; - } - - void cache_type_info(const Item *source, bool maybe_null_arg) - { - Type_std_attributes::set(source); - set_handler(source->type_handler()); - maybe_null= maybe_null_arg; - } - - bool fix_length_and_dec2_eliminate_null(Item **items) - { - // Let IF(cond, expr, NULL) and IF(cond, NULL, expr) inherit type from expr. - if (items[0]->type() == NULL_ITEM) - { - cache_type_info(items[1], true); - // If both arguments are NULL, make resulting type BINARY(0). - if (items[1]->type() == NULL_ITEM) - set_handler(&type_handler_string); - } - else if (items[1]->type() == NULL_ITEM) - { - cache_type_info(items[0], true); - } - else - { - if (fix_length_and_dec2(items)) - return TRUE; - } - return FALSE; - } - -public: - Item_func_case_abbreviation2(THD *thd, Item *a, Item *b): - Item_func_case_expression(thd, a, b) { } - Item_func_case_abbreviation2(THD *thd, Item *a, Item *b, Item *c): - Item_func_case_expression(thd, a, b, c) { } -}; - - -class Item_func_ifnull :public Item_func_case_abbreviation2 -{ -public: - Item_func_ifnull(THD *thd, Item *a, Item *b): - Item_func_case_abbreviation2(thd, a, b) {} - double real_op(); - longlong int_op(); - String *str_op(String *str); - my_decimal *decimal_op(my_decimal *); - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool time_op(THD *thd, MYSQL_TIME *ltime); - bool native_op(THD *thd, Native *to); - bool fix_length_and_dec() - { - /* - Set nullability from args[1] by default. - Note, some type handlers may reset maybe_null - in Item_hybrid_func_fix_attributes() if args[1] - is NOT NULL but cannot always be converted to - the data type of "this" safely. - E.g. Type_handler_inet6 does: - IFNULL(inet6_not_null_expr, 'foo') -> INET6 NULL - IFNULL(inet6_not_null_expr, '::1') -> INET6 NOT NULL - */ - maybe_null= args[1]->maybe_null; - if (Item_func_case_abbreviation2::fix_length_and_dec2(args)) - return TRUE; - return FALSE; - } - const char *func_name() const { return "ifnull"; } - - table_map not_null_tables() const { return 0; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - Case abbreviations that have a switch argument and - two return arguments to choose from. Returns the value - of either of the two return arguments depending on the switch argument value. - - IF(switch, arg1, arg2) - NVL(switch, arg1, arg2) -*/ -class Item_func_case_abbreviation2_switch: public Item_func_case_abbreviation2 -{ -protected: - virtual Item *find_item() const= 0; - -public: - Item_func_case_abbreviation2_switch(THD *thd, Item *a, Item *b, Item *c) - :Item_func_case_abbreviation2(thd, a, b, c) - { } - - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - Datetime_truncation_not_needed dt(thd, find_item(), fuzzydate); - return (null_value= dt.copy_to_mysql_time(ltime, mysql_timestamp_type())); - } - bool time_op(THD *thd, MYSQL_TIME *ltime) - { - return (null_value= Time(find_item()).copy_to_mysql_time(ltime)); - } - longlong int_op() - { - return val_int_from_item(find_item()); - } - double real_op() - { - return val_real_from_item(find_item()); - } - my_decimal *decimal_op(my_decimal *decimal_value) - { - return val_decimal_from_item(find_item(), decimal_value); - } - String *str_op(String *str) - { - return val_str_from_item(find_item(), str); - } - bool native_op(THD *thd, Native *to) - { - return val_native_with_conversion_from_item(thd, find_item(), to, - type_handler()); - } -}; - - -class Item_func_if :public Item_func_case_abbreviation2_switch -{ -protected: - Item *find_item() const { return args[0]->val_bool() ? args[1] : args[2]; } - -public: - Item_func_if(THD *thd, Item *a, Item *b, Item *c): - Item_func_case_abbreviation2_switch(thd, a, b, c) - {} - bool fix_fields(THD *, Item **); - bool fix_length_and_dec() - { - return fix_length_and_dec2_eliminate_null(args + 1); - } - const char *func_name() const { return "if"; } - bool eval_not_null_tables(void *opt_arg); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -private: - void cache_type_info(Item *source); -}; - - -class Item_func_nvl2 :public Item_func_case_abbreviation2_switch -{ -protected: - Item *find_item() const { return args[0]->is_null() ? args[2] : args[1]; } - -public: - Item_func_nvl2(THD *thd, Item *a, Item *b, Item *c): - Item_func_case_abbreviation2_switch(thd, a, b, c) - {} - const char *func_name() const { return "nvl2"; } - bool fix_length_and_dec() - { - return fix_length_and_dec2_eliminate_null(args + 1); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_nullif :public Item_func_case_expression -{ - Arg_comparator cmp; - /* - NULLIF(a,b) is a short for: - CASE WHEN a=b THEN NULL ELSE a END - - The left "a" is for comparison purposes. - The right "a" is for return value purposes. - These are two different "a" and they can be replaced to different items. - - The left "a" is in a comparison and can be replaced by: - - Item_func::convert_const_compared_to_int_field() - - agg_item_set_converter() in set_cmp_func() - - cache_converted_constant() in set_cmp_func() - - Both "a"s are subject to equal fields propagation and can be replaced by: - - Item_field::propagate_equal_fields(ANY_SUBST) for the left "a" - - Item_field::propagate_equal_fields(IDENTITY_SUBST) for the right "a" - */ - Item_cache *m_cache; - int compare(); - void reset_first_arg_if_needed() - { - if (arg_count == 3 && args[0] != args[2]) - args[0]= args[2]; - } - Item *m_arg0; -public: - /* - Here we pass three arguments to the parent constructor, as NULLIF - is a three-argument function, it needs two copies of the first argument - (see above). But fix_fields() will be confused if we try to prepare the - same Item twice (if args[0]==args[2]), so we hide the third argument - (decrementing arg_count) and copy args[2]=args[0] again after fix_fields(). - See also Item_func_nullif::fix_length_and_dec(). - */ - Item_func_nullif(THD *thd, Item *a, Item *b): - Item_func_case_expression(thd, a, b, a), - m_cache(NULL), - m_arg0(NULL) - { arg_count--; } - void cleanup() - { - Item_func_hybrid_field_type::cleanup(); - arg_count= 2; // See the comment to the constructor - } - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool time_op(THD *thd, MYSQL_TIME *ltime); - double real_op(); - longlong int_op(); - String *str_op(String *str); - my_decimal *decimal_op(my_decimal *); - bool native_op(THD *thd, Native *to); - bool fix_length_and_dec(); - bool walk(Item_processor processor, bool walk_subquery, void *arg); - const char *func_name() const { return "nullif"; } - void print(String *str, enum_query_type query_type); - void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, uint flags); - void update_used_tables(); - table_map not_null_tables() const { return 0; } - bool is_null(); - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - Context cmpctx(ANY_SUBST, cmp.compare_type_handler(), - cmp.compare_collation()); - const Item *old0= args[0]; - args[0]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, - cond, &args[0]); - args[1]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, - cond, &args[1]); - /* - MDEV-9712 Performance degradation of nested NULLIF - ANY_SUBST is more relaxed than IDENTITY_SUBST. - If ANY_SUBST did not change args[0], - then we can skip propagation for args[2]. - */ - if (old0 != args[0]) - args[2]->propagate_equal_fields_and_change_item_tree(thd, - Context_identity(), - cond, &args[2]); - return this; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *derived_field_transformer_for_having(THD *thd, uchar *arg) - { reset_first_arg_if_needed(); return this; } - Item *derived_field_transformer_for_where(THD *thd, uchar *arg) - { reset_first_arg_if_needed(); return this; } - Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) - { reset_first_arg_if_needed(); return this; } - Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) - { reset_first_arg_if_needed(); return this; } - Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) - { reset_first_arg_if_needed(); return this; } -}; - - -/* Functions to handle the optimized IN */ - - -/* A vector of values of some type */ - -class in_vector :public Sql_alloc -{ -public: - char *base; - uint size; - qsort2_cmp compare; - CHARSET_INFO *collation; - uint count; - uint used_count; - in_vector() {} - in_vector(THD *thd, uint elements, uint element_length, qsort2_cmp cmp_func, - CHARSET_INFO *cmp_coll) - :base((char*) thd_calloc(thd, elements * element_length)), - size(element_length), compare(cmp_func), collation(cmp_coll), - count(elements), used_count(elements) {} - virtual ~in_vector() {} - virtual void set(uint pos,Item *item)=0; - virtual uchar *get_value(Item *item)=0; - void sort() - { - my_qsort2(base,used_count,size,compare,(void*)collation); - } - bool find(Item *item); - - /* - Create an instance of Item_{type} (e.g. Item_decimal) constant object - which type allows it to hold an element of this vector without any - conversions. - The purpose of this function is to be able to get elements of this - vector in form of Item_xxx constants without creating Item_xxx object - for every array element you get (i.e. this implements "FlyWeight" pattern) - */ - virtual Item* create_item(THD *thd) { return NULL; } - - /* - Store the value at position #pos into provided item object - SYNOPSIS - value_to_item() - pos Index of value to store - item Constant item to store value into. The item must be of the same - type that create_item() returns. - */ - virtual void value_to_item(uint pos, Item *item) { } - - /* Compare values number pos1 and pos2 for equality */ - bool compare_elems(uint pos1, uint pos2) - { - return MY_TEST(compare(collation, base + pos1 * size, base + pos2 * size)); - } - virtual const Type_handler *type_handler() const= 0; -}; - -class in_string :public in_vector -{ - char buff[STRING_BUFFER_USUAL_SIZE]; - String tmp; - class Item_string_for_in_vector: public Item_string - { - public: - Item_string_for_in_vector(THD *thd, CHARSET_INFO *cs): - Item_string(thd, cs) - { } - void set_value(const String *str) - { - str_value= *str; - collation.set(str->charset()); - } - }; -public: - in_string(THD *thd, uint elements, qsort2_cmp cmp_func, CHARSET_INFO *cs); - ~in_string(); - void set(uint pos,Item *item); - uchar *get_value(Item *item); - Item* create_item(THD *thd); - void value_to_item(uint pos, Item *item) - { - String *str=((String*) base)+pos; - Item_string_for_in_vector *to= (Item_string_for_in_vector*) item; - to->set_value(str); - } - const Type_handler *type_handler() const { return &type_handler_varchar; } -}; - -class in_longlong :public in_vector -{ -protected: - /* - Here we declare a temporary variable (tmp) of the same type as the - elements of this vector. tmp is used in finding if a given value is in - the list. - */ - struct packed_longlong - { - longlong val; - longlong unsigned_flag; // Use longlong, not bool, to preserve alignment - } tmp; -public: - in_longlong(THD *thd, uint elements); - void set(uint pos,Item *item); - uchar *get_value(Item *item); - Item* create_item(THD *thd); - void value_to_item(uint pos, Item *item) - { - ((Item_int*) item)->value= ((packed_longlong*) base)[pos].val; - ((Item_int*) item)->unsigned_flag= (bool) - ((packed_longlong*) base)[pos].unsigned_flag; - } - const Type_handler *type_handler() const { return &type_handler_slonglong; } - - friend int cmp_longlong(void *cmp_arg, packed_longlong *a,packed_longlong *b); -}; - - -class in_timestamp :public in_vector -{ - Timestamp_or_zero_datetime tmp; -public: - in_timestamp(THD *thd, uint elements); - void set(uint pos,Item *item); - uchar *get_value(Item *item); - Item* create_item(THD *thd); - void value_to_item(uint pos, Item *item); - const Type_handler *type_handler() const { return &type_handler_timestamp2; } -}; - - -/* - Class to represent a vector of constant DATE/DATETIME values. -*/ -class in_temporal :public in_longlong -{ -public: - /* Cache for the left item. */ - - in_temporal(THD *thd, uint elements) - :in_longlong(thd, elements) {}; - Item *create_item(THD *thd); - void value_to_item(uint pos, Item *item) - { - packed_longlong *val= reinterpret_cast(base)+pos; - Item_datetime *dt= static_cast(item); - dt->set(val->val, type_handler()->mysql_timestamp_type()); - } - friend int cmp_longlong(void *cmp_arg, packed_longlong *a,packed_longlong *b); -}; - - -class in_datetime :public in_temporal -{ -public: - in_datetime(THD *thd, uint elements) - :in_temporal(thd, elements) - {} - void set(uint pos,Item *item); - uchar *get_value(Item *item); - const Type_handler *type_handler() const { return &type_handler_datetime2; } -}; - - -class in_time :public in_temporal -{ -public: - in_time(THD *thd, uint elements) - :in_temporal(thd, elements) - {} - void set(uint pos,Item *item); - uchar *get_value(Item *item); - const Type_handler *type_handler() const { return &type_handler_time2; } -}; - - -class in_double :public in_vector -{ - double tmp; -public: - in_double(THD *thd, uint elements); - void set(uint pos,Item *item); - uchar *get_value(Item *item); - Item *create_item(THD *thd); - void value_to_item(uint pos, Item *item) - { - ((Item_float*)item)->value= ((double*) base)[pos]; - } - const Type_handler *type_handler() const { return &type_handler_double; } -}; - - -class in_decimal :public in_vector -{ - my_decimal val; -public: - in_decimal(THD *thd, uint elements); - void set(uint pos, Item *item); - uchar *get_value(Item *item); - Item *create_item(THD *thd); - void value_to_item(uint pos, Item *item) - { - my_decimal *dec= ((my_decimal *)base) + pos; - Item_decimal *item_dec= (Item_decimal*)item; - item_dec->set_decimal_value(dec); - } - const Type_handler *type_handler() const { return &type_handler_newdecimal; } -}; - - -/* -** Classes for easy comparing of non const items -*/ - -class cmp_item :public Sql_alloc -{ -public: - CHARSET_INFO *cmp_charset; - cmp_item() { cmp_charset= &my_charset_bin; } - virtual ~cmp_item() {} - virtual void store_value(Item *item)= 0; - /** - @returns result (TRUE, FALSE or UNKNOWN) of - "stored argument's value <> item's value" - */ - virtual int cmp(Item *item)= 0; - virtual int cmp_not_null(const Value *value)= 0; - // for optimized IN with row - virtual int compare(cmp_item *item)= 0; - virtual cmp_item *make_same()= 0; - virtual void store_value_by_template(THD *thd, cmp_item *tmpl, Item *item) - { - store_value(item); - } -}; - -/// cmp_item which stores a scalar (i.e. non-ROW). -class cmp_item_scalar : public cmp_item -{ -protected: - bool m_null_value; ///< If stored value is NULL -}; - -class cmp_item_string : public cmp_item_scalar -{ -protected: - String *value_res; -public: - cmp_item_string () {} - cmp_item_string (CHARSET_INFO *cs) { cmp_charset= cs; } - void set_charset(CHARSET_INFO *cs) { cmp_charset= cs; } - friend class cmp_item_sort_string; - friend class cmp_item_sort_string_in_static; -}; - -class cmp_item_sort_string :public cmp_item_string -{ -protected: - char value_buff[STRING_BUFFER_USUAL_SIZE]; - String value; -public: - cmp_item_sort_string(): - cmp_item_string() {} - cmp_item_sort_string(CHARSET_INFO *cs): - cmp_item_string(cs), - value(value_buff, sizeof(value_buff), cs) {} - void store_value(Item *item) - { - value_res= item->val_str(&value); - m_null_value= item->null_value; - // Make sure to cache the result String inside "value" - if (value_res && value_res != &value) - { - if (value.copy(*value_res)) - value.set("", 0, item->collation.collation); - value_res= &value; - } - } - int cmp_not_null(const Value *val) - { - DBUG_ASSERT(!val->is_null()); - DBUG_ASSERT(val->is_string()); - return sortcmp(value_res, &val->m_string, cmp_charset) != 0; - } - int cmp(Item *arg) - { - char buff[STRING_BUFFER_USUAL_SIZE]; - String tmp(buff, sizeof(buff), cmp_charset), *res= arg->val_str(&tmp); - if (m_null_value || arg->null_value) - return UNKNOWN; - if (value_res && res) - return sortcmp(value_res, res, cmp_charset) != 0; - else if (!value_res && !res) - return FALSE; - else - return TRUE; - } - int compare(cmp_item *ci) - { - cmp_item_string *l_cmp= (cmp_item_string *) ci; - return sortcmp(value_res, l_cmp->value_res, cmp_charset); - } - cmp_item *make_same(); - void set_charset(CHARSET_INFO *cs) - { - cmp_charset= cs; - value.set_quick(value_buff, sizeof(value_buff), cs); - } -}; - -class cmp_item_int : public cmp_item_scalar -{ - longlong value; -public: - cmp_item_int() {} /* Remove gcc warning */ - void store_value(Item *item) - { - value= item->val_int(); - m_null_value= item->null_value; - } - int cmp_not_null(const Value *val) - { - DBUG_ASSERT(!val->is_null()); - DBUG_ASSERT(val->is_longlong()); - return value != val->value.m_longlong; - } - int cmp(Item *arg) - { - const bool rc= value != arg->val_int(); - return (m_null_value || arg->null_value) ? UNKNOWN : rc; - } - int compare(cmp_item *ci) - { - cmp_item_int *l_cmp= (cmp_item_int *)ci; - return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1); - } - cmp_item *make_same(); -}; - -/* - Compare items in the DATETIME context. -*/ -class cmp_item_temporal: public cmp_item_scalar -{ -protected: - longlong value; -public: - cmp_item_temporal() {} - int compare(cmp_item *ci); -}; - - -class cmp_item_datetime: public cmp_item_temporal -{ -public: - cmp_item_datetime() - :cmp_item_temporal() - { } - void store_value(Item *item) - { - value= item->val_datetime_packed(current_thd); - m_null_value= item->null_value; - } - int cmp_not_null(const Value *val); - int cmp(Item *arg); - cmp_item *make_same(); -}; - - -class cmp_item_time: public cmp_item_temporal -{ -public: - cmp_item_time() - :cmp_item_temporal() - { } - void store_value(Item *item) - { - value= item->val_time_packed(current_thd); - m_null_value= item->null_value; - } - int cmp_not_null(const Value *val); - int cmp(Item *arg); - cmp_item *make_same(); -}; - - -class cmp_item_timestamp: public cmp_item_scalar -{ - Timestamp_or_zero_datetime_native m_native; -public: - cmp_item_timestamp() :cmp_item_scalar() { } - void store_value(Item *item); - int cmp_not_null(const Value *val); - int cmp(Item *arg); - int compare(cmp_item *ci); - cmp_item *make_same(); -}; - - -class cmp_item_real : public cmp_item_scalar -{ - double value; -public: - cmp_item_real() {} /* Remove gcc warning */ - void store_value(Item *item) - { - value= item->val_real(); - m_null_value= item->null_value; - } - int cmp_not_null(const Value *val) - { - DBUG_ASSERT(!val->is_null()); - DBUG_ASSERT(val->is_double()); - return value != val->value.m_double; - } - int cmp(Item *arg) - { - const bool rc= value != arg->val_real(); - return (m_null_value || arg->null_value) ? UNKNOWN : rc; - } - int compare(cmp_item *ci) - { - cmp_item_real *l_cmp= (cmp_item_real *) ci; - return (value < l_cmp->value)? -1 : ((value == l_cmp->value) ? 0 : 1); - } - cmp_item *make_same(); -}; - - -class cmp_item_decimal : public cmp_item_scalar -{ - my_decimal value; -public: - cmp_item_decimal() {} /* Remove gcc warning */ - void store_value(Item *item); - int cmp(Item *arg); - int cmp_not_null(const Value *val); - int compare(cmp_item *c); - cmp_item *make_same(); -}; - - -/* - cmp_item for optimized IN with row (right part string, which never - be changed) -*/ - -class cmp_item_sort_string_in_static :public cmp_item_string -{ - protected: - String value; -public: - cmp_item_sort_string_in_static(CHARSET_INFO *cs): - cmp_item_string(cs) {} - void store_value(Item *item) - { - value_res= item->val_str(&value); - m_null_value= item->null_value; - } - int cmp_not_null(const Value *val) - { - DBUG_ASSERT(false); - return TRUE; - } - int cmp(Item *item) - { - // Should never be called - DBUG_ASSERT(false); - return TRUE; - } - int compare(cmp_item *ci) - { - cmp_item_string *l_cmp= (cmp_item_string *) ci; - return sortcmp(value_res, l_cmp->value_res, cmp_charset); - } - cmp_item *make_same() - { - return new cmp_item_sort_string_in_static(cmp_charset); - } -}; - - -/** - A helper class to handle situations when some item "pred" (the predicant) - is consequently compared to a list of other items value0..valueN (the values). - Currently used to handle: - - - pred IN (value0, value1, value2) - - - CASE pred WHEN value0 .. WHEN value1 .. WHEN value2 .. END - - Every pair {pred,valueN} can be compared by its own Type_handler. - Some pairs can use the same Type_handler. - In cases when all pairs use exactly the same Type_handler, - we say "all types are compatible". - - For example, for an expression - 1 IN (1, 1e0, 1.0, 2) - - pred is 1 - - value0 is 1 - - value1 is 1e0 - - value2 is 1.1 - - value3 is 2 - - Pairs (pred,valueN) are compared as follows: - N expr1 Type - - ----- ---- - 0 1 INT - 1 1e0 DOUBLE - 2 1.0 DECIMAL - 3 2 INT - - Types are not compatible in this example. - - During add_value() calls, each pair {pred,valueN} is analysed: - - If valueN is an explicit NULL, it can be ignored in the caller asks to do so - - If valueN is not an explicit NULL (or if the caller didn't ask to skip - NULLs), then the value add an element in the array m_comparators[]. - - Every element m_comparators[] stores the following information: - 1. m_arg_index - the position of the value expression in the original - argument array, e.g. in Item_func_in::args[] or Item_func_case::args[]. - - 2. m_handler - the pointer to the data type handler that the owner - will use to compare the pair {args[m_predicate_index],args[m_arg_index]}. - - 3. m_handler_index - the index of an m_comparators[] element corresponding - to the leftmost pair that uses exactly the same Type_handler for - comparison. m_handler_index helps to maintain unique data type handlers. - - m_comparators[i].m_handler_index==i means that this is the - leftmost pair that uses the Type_handler m_handler for comparision. - - If m_comparators[i].m_handlex_index!=i, it means that some earlier - element m_comparators[jm_cmp_item; - DBUG_ASSERT(in_item); - /* - If this is the leftmost pair that uses the data type handler - pointed by m_comparators[i].m_handler, then we need to cache - the predicant value representation used by this handler. - */ - if (m_comparators[i].m_handler_index == i) - in_item->store_value(args->arguments()[m_predicant_index]); - /* - If the predicant item has null_value==true then: - - In case of scalar expression we can returns UNKNOWN immediately. - No needs to check the result of the value item. - - In case of ROW, null_value==true means that *some* row elements - returned NULL, but *some* elements can still be non-NULL! - We need to get the result of the value item and test - if non-NULL elements in the predicant and the value produce - TRUE (not equal), or UNKNOWN. - */ - if (args->arguments()[m_predicant_index]->null_value && - m_comparators[i].m_handler != &type_handler_row) - return UNKNOWN; - return in_item->cmp(args->arguments()[m_comparators[i].m_arg_index]); - } - int cmp_args_nulls_equal(THD *thd, Item_args *args, uint i) - { - Predicant_to_value_comparator *cmp= - &m_comparators[m_comparators[i].m_handler_index]; - cmp_item *in_item= cmp->m_cmp_item; - DBUG_ASSERT(in_item); - Item *predicant= args->arguments()[m_predicant_index]; - Item *arg= args->arguments()[m_comparators[i].m_arg_index]; - ValueBuffer val; - if (m_comparators[i].m_handler_index == i) - in_item->store_value(predicant); - m_comparators[i].m_handler->Item_save_in_value(thd, arg, &val); - if (predicant->null_value && val.is_null()) - return FALSE; // Two nulls are equal - if (predicant->null_value || val.is_null()) - return UNKNOWN; - return in_item->cmp_not_null(&val); - } - /** - Predicant_to_value_comparator - a comparator for one pair (pred,valueN). - See comments above. - */ - struct Predicant_to_value_comparator - { - const Type_handler *m_handler; - cmp_item *m_cmp_item; - uint m_arg_index; - uint m_handler_index; - void cleanup() - { - if (m_cmp_item) - delete m_cmp_item; - memset(this, 0, sizeof(*this)); - } - }; - - Predicant_to_value_comparator *m_comparators; // The comparator array - uint m_comparator_count;// The number of elements in m_comparators[] - uint m_predicant_index; // The position of the predicant in its argument list, - // e.g. for Item_func_in m_predicant_index is 0, - // as predicant is stored in Item_func_in::args[0]. - // For Item_func_case m_predicant_index is - // set to Item_func_case::first_expr_num. - -public: - Predicant_to_list_comparator(THD *thd, uint nvalues) - :m_comparator_count(0), - m_predicant_index(0) - { - alloc_comparators(thd, nvalues); - } - - uint comparator_count() const { return m_comparator_count; } - const Type_handler *get_comparator_type_handler(uint i) const - { - DBUG_ASSERT(i < m_comparator_count); - return m_comparators[i].m_handler; - } - uint get_comparator_arg_index(uint i) const - { - DBUG_ASSERT(i < m_comparator_count); - return m_comparators[i].m_arg_index; - } - cmp_item *get_comparator_cmp_item(uint i) const - { - DBUG_ASSERT(i < m_comparator_count); - return m_comparators[i].m_cmp_item; - } - -#ifndef DBUG_OFF - void debug_print(THD *thd) - { - for (uint i= 0; i < m_comparator_count; i++) - { - DBUG_EXECUTE_IF("Predicant_to_list_comparator", - push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, - ER_UNKNOWN_ERROR, "DBUG: [%d] arg=%d handler=%d (%s)", i, - m_comparators[i].m_arg_index, - m_comparators[i].m_handler_index, - m_comparators[m_comparators[i].m_handler_index]. - m_handler->name().ptr());); - } - } -#endif - - void add_predicant(Item_args *args, uint predicant_index) - { - DBUG_ASSERT(m_comparator_count == 0); // Set in constructor - DBUG_ASSERT(m_predicant_index == 0); // Set in constructor - DBUG_ASSERT(predicant_index < args->argument_count()); - m_predicant_index= predicant_index; - } - /** - Add a new element into m_comparators[], using a {pred,valueN} pair. - - @param funcname - the name of the operation, for error reporting - @param args - the owner function's argument list - @param value_index - the value position in args - @retval true - could not add an element because of non-comparable - arguments (e.g. ROWs with size) - @retval false - a new element was successfully added. - */ - bool add_value(const char *funcname, Item_args *args, uint value_index); - - /** - Add a new element into m_comparators[], ignoring explicit NULL values. - If the value appeared to be an explicit NULL, nulls_found[0] is set to true. - */ - bool add_value_skip_null(const char *funcname, - Item_args *args, uint value_index, - bool *nulls_found); - - /** - Signal "this" that there will be no new add_value*() calls, - so it can prepare its internal structures for comparison. - - @param [OUT] compatible - If all comparators are compatible, - their data type handler is returned here. - @param [OUT] unuque_cnt - The number of unique data type handlers found. - If the value returned in *unique_cnt is 0, - it means all values were explicit NULLs: - expr0 IN (NULL,NULL,..,NULL) - @param [OUT] found_type - The bit mask for all found cmp_type()'s. - */ - void all_values_added(Type_handler_hybrid_field_type *compatible, - uint *unique_cnt, uint *found_types) - { - detect_unique_handlers(compatible, unique_cnt, found_types); - } - /** - Creates cmp_item instances for all unique handlers and stores - them into m_comparators[].m_cmp_item, using the information previously - populated by add_predicant(), add_value() and detect_unque_handlers(). - */ - bool make_unique_cmp_items(THD *thd, CHARSET_INFO *cs); - void cleanup() - { - DBUG_ASSERT(m_comparators); - for (uint i= 0; i < m_comparator_count; i++) - m_comparators[i].cleanup(); - memset(m_comparators, 0, sizeof(m_comparators[0]) * m_comparator_count); - m_comparator_count= 0; - m_predicant_index= 0; - } - bool init_clone(THD *thd, uint nvalues) - { - m_comparator_count= 0; - m_predicant_index= 0; - return alloc_comparators(thd, nvalues); - } - /** - @param [IN] args - The argument list that was previously used with - add_predicant() and add_value(). - @param [OUT] idx - In case if a value that is equal to the predicant - was found, the index of the matching value is returned - here. Otherwise, *idx is not changed. - @param [IN/OUT] found_unknown_values - how to handle UNKNOWN results. - If found_unknown_values is NULL (e.g. Item_func_case), - cmp() returns immediately when the first UNKNOWN - result is found. - If found_unknown_values is non-NULL (Item_func_in), - cmp() does not return when an UNKNOWN result is found, - sets *found_unknown_values to true, and continues - to compare the remaining pairs to find FALSE - (i.e. the value that is equal to the predicant). - - @retval false - Found a value that is equal to the predicant - @retval true - Didn't find an equal value - */ - bool cmp(Item_args *args, uint *idx, bool *found_unknown_values) - { - for (uint i= 0 ; i < m_comparator_count ; i++) - { - DBUG_ASSERT(m_comparators[i].m_handler != NULL); - const int rc= cmp_arg(args, i); - if (rc == FALSE) - { - *idx= m_comparators[i].m_arg_index; - return false; // Found a matching value - } - if (rc == UNKNOWN) - { - if (!found_unknown_values) - return true; - *found_unknown_values= true; - } - } - return true; // Not found - } - /* - Same as above, but treats two NULLs as equal, e.g. as in DECODE_ORACLE(). - */ - bool cmp_nulls_equal(THD *thd, Item_args *args, uint *idx) - { - for (uint i= 0 ; i < m_comparator_count ; i++) - { - DBUG_ASSERT(m_comparators[i].m_handler != NULL); - if (cmp_args_nulls_equal(thd, args, i) == FALSE) - { - *idx= m_comparators[i].m_arg_index; - return false; // Found a matching value - } - } - return true; // Not found - } -}; - - -/* - The class Item_func_case is the CASE ... WHEN ... THEN ... END function - implementation. -*/ - -class Item_func_case :public Item_func_case_expression -{ -protected: - String tmp_value; - DTCollation cmp_collation; - bool aggregate_then_and_else_arguments(THD *thd, uint count); - virtual Item **else_expr_addr() const= 0; - virtual Item *find_item()= 0; - inline void print_when_then_arguments(String *str, - enum_query_type query_type, - Item **items, uint count); - inline void print_else_argument(String *str, enum_query_type query_type, - Item *item); - void reorder_args(uint start); -public: - Item_func_case(THD *thd, List &list) - :Item_func_case_expression(thd, list) - { } - double real_op(); - longlong int_op(); - String *str_op(String *); - my_decimal *decimal_op(my_decimal *); - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool time_op(THD *thd, MYSQL_TIME *ltime); - bool native_op(THD *thd, Native *to); - bool fix_fields(THD *thd, Item **ref); - table_map not_null_tables() const { return 0; } - const char *func_name() const { return "case"; } - CHARSET_INFO *compare_collation() const { return cmp_collation.collation; } - bool need_parentheses_in_default() { return true; } -}; - - -/* - CASE WHEN cond THEN res [WHEN cond THEN res...] [ELSE res] END - - Searched CASE checks all WHEN expressions one after another. - When some WHEN expression evaluated to TRUE then the - value of the corresponding THEN expression is returned. -*/ -class Item_func_case_searched: public Item_func_case -{ - uint when_count() const { return arg_count / 2; } - bool with_else() const { return arg_count % 2; } - Item **else_expr_addr() const { return with_else() ? &args[arg_count - 1] : 0; } -public: - Item_func_case_searched(THD *thd, List &list) - :Item_func_case(thd, list) - { - DBUG_ASSERT(arg_count >= 2); - reorder_args(0); - } - enum Functype functype() const { return CASE_SEARCHED_FUNC; } - void print(String *str, enum_query_type query_type); - bool fix_length_and_dec(); - Item *propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - // None of the arguments are in a comparison context - Item_args::propagate_equal_fields(thd, Context_identity(), cond); - return this; - } - Item *find_item(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - CASE pred WHEN value THEN res [WHEN value THEN res...] [ELSE res] END - - When the predicant expression is specified then it is compared to each WHEN - expression individually. When an equal WHEN expression is found - the corresponding THEN expression is returned. - In order to do correct comparisons several comparators are used. One for - each result type. Different result types that are used in particular - CASE ... END expression are collected in the fix_length_and_dec() member - function and only comparators for there result types are used. -*/ -class Item_func_case_simple: public Item_func_case, - public Predicant_to_list_comparator -{ -protected: - uint m_found_types; - uint when_count() const { return (arg_count - 1) / 2; } - bool with_else() const { return arg_count % 2 == 0; } - Item **else_expr_addr() const { return with_else() ? &args[arg_count - 1] : 0; } - bool aggregate_switch_and_when_arguments(THD *thd, bool nulls_equal); - bool prepare_predicant_and_values(THD *thd, uint *found_types, - bool nulls_equal); -public: - Item_func_case_simple(THD *thd, List &list) - :Item_func_case(thd, list), - Predicant_to_list_comparator(thd, arg_count), - m_found_types(0) - { - DBUG_ASSERT(arg_count >= 3); - reorder_args(1); - } - void cleanup() - { - DBUG_ENTER("Item_func_case_simple::cleanup"); - Item_func::cleanup(); - Predicant_to_list_comparator::cleanup(); - DBUG_VOID_RETURN; - } - enum Functype functype() const { return CASE_SIMPLE_FUNC; } - void print(String *str, enum_query_type query_type); - bool fix_length_and_dec(); - Item *propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond); - Item *find_item(); - Item *build_clone(THD *thd) - { - Item_func_case_simple *clone= (Item_func_case_simple *) - Item_func_case::build_clone(thd); - uint ncases= when_count(); - if (clone && clone->Predicant_to_list_comparator::init_clone(thd, ncases)) - return NULL; - return clone; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_decode_oracle: public Item_func_case_simple -{ -public: - Item_func_decode_oracle(THD *thd, List &list) - :Item_func_case_simple(thd, list) - { } - const char *func_name() const { return "decode_oracle"; } - void print(String *str, enum_query_type query_type); - bool fix_length_and_dec(); - Item *find_item(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - The Item_func_in class implements - in_expr IN () - and - in_expr NOT IN () - - The current implementation distinguishes 2 cases: - 1) all items in are constants and have the same - result type. This case is handled by in_vector class, - implementing fast bisection search. - 2) otherwise Item_func_in employs several cmp_item objects to perform - comparisons of in_expr and an item from . One cmp_item - object for each result type. Different result types are collected in the - fix_length_and_dec() member function by means of collect_cmp_types() - function. - - Bisection is possible when: - 1. All types are similar - 2. All expressions in are const - In the presence of NULLs, the correct result of evaluating this item - must be UNKNOWN or FALSE. To achieve that: - - If type is scalar, we can use bisection and the "have_null" boolean. - - If type is ROW, we will need to scan all of when - searching, so bisection is impossible. Unless: - 3. UNKNOWN and FALSE are equivalent results - 4. Neither left expression nor contain any NULL value -*/ -class Item_func_in :public Item_func_opt_neg, - public Predicant_to_list_comparator -{ - /** - Usable if is made only of constants. Returns true if one - of these constants contains a NULL. Example: - IN ( (-5, (12,NULL)), ... ). - */ - bool list_contains_null(); - bool all_items_are_consts(Item **items, uint nitems) const - { - for (uint i= 0; i < nitems; i++) - { - if (!items[i]->const_item() || items[i]->is_expensive()) - return false; - } - return true; - } - bool prepare_predicant_and_values(THD *thd, uint *found_types); - bool check_arguments() const - { - return check_argument_types_like_args0(); - } -protected: - SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *value); - bool transform_into_subq; -public: - /// An array of values, created when the bisection lookup method is used - in_vector *array; - /** - If there is some NULL among , during a val_int() call; for - example - IN ( (1,(3,'col')), ... ), where 'col' is a column which evaluates to - NULL. - */ - bool have_null; - /** - true when all arguments of the IN list are of compatible types - and can be used safely as comparisons for key conditions - */ - bool arg_types_compatible; - - TABLE_LIST *emb_on_expr_nest; - - Item_func_in(THD *thd, List &list): - Item_func_opt_neg(thd, list), - Predicant_to_list_comparator(thd, arg_count - 1), - transform_into_subq(false), - array(0), have_null(0), - arg_types_compatible(FALSE), emb_on_expr_nest(0) - { } - longlong val_int(); - bool fix_fields(THD *, Item **); - bool fix_length_and_dec(); - bool compatible_types_scalar_bisection_possible() - { - DBUG_ASSERT(m_comparator.cmp_type() != ROW_RESULT); - return all_items_are_consts(args + 1, arg_count - 1); // Bisection #2 - } - bool compatible_types_row_bisection_possible() - { - DBUG_ASSERT(m_comparator.cmp_type() == ROW_RESULT); - return all_items_are_consts(args + 1, arg_count - 1) && // Bisection #2 - ((is_top_level_item() && !negated) || // Bisection #3 - (!list_contains_null() && !args[0]->maybe_null)); // Bisection #4 - } - bool agg_all_arg_charsets_for_comparison() - { - return agg_arg_charsets_for_comparison(cmp_collation, args, arg_count); - } - void fix_in_vector(); - bool value_list_convert_const_to_int(THD *thd); - bool fix_for_scalar_comparison_using_bisection(THD *thd) - { - array= m_comparator.type_handler()->make_in_vector(thd, this, arg_count - 1); - if (!array) // OOM - return true; - fix_in_vector(); - return false; - } - bool fix_for_scalar_comparison_using_cmp_items(THD *thd, uint found_types); - - bool fix_for_row_comparison_using_cmp_items(THD *thd); - bool fix_for_row_comparison_using_bisection(THD *thd); - - void cleanup() - { - DBUG_ENTER("Item_func_in::cleanup"); - Item_int_func::cleanup(); - delete array; - array= 0; - Predicant_to_list_comparator::cleanup(); - DBUG_VOID_RETURN; - } - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, - table_map usable_tables, SARGABLE_PARAM **sargables); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); - SEL_TREE *get_func_row_mm_tree(RANGE_OPT_PARAM *param, Item_row *key_row); - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - /* - Note, we pass ANY_SUBST, this makes sure that non of the args - will be replaced to a zero-filled Item_string. - Such a change would require rebuilding of cmp_items. - */ - if (arg_types_compatible) - { - Context cmpctx(ANY_SUBST, m_comparator.type_handler(), - Item_func_in::compare_collation()); - args[0]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, - cond, &args[0]); - } - for (uint i= 0; i < comparator_count(); i++) - { - Context cmpctx(ANY_SUBST, get_comparator_type_handler(i), - Item_func_in::compare_collation()); - uint idx= get_comparator_arg_index(i); - args[idx]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, - cond, &args[idx]); - } - return this; - } - virtual void print(String *str, enum_query_type query_type); - enum Functype functype() const { return IN_FUNC; } - const char *func_name() const { return "in"; } - enum precedence precedence() const { return IN_PRECEDENCE; } - bool eval_not_null_tables(void *opt_arg); - bool find_not_null_fields(table_map allowed); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - bool count_sargable_conds(void *arg); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *build_clone(THD *thd) - { - Item_func_in *clone= (Item_func_in *) Item_func::build_clone(thd); - if (clone) - { - clone->array= 0; - if (clone->Predicant_to_list_comparator::init_clone(thd, arg_count - 1)) - return NULL; - } - return clone; - } - void mark_as_condition_AND_part(TABLE_LIST *embedding); - bool to_be_transformed_into_in_subq(THD *thd); - bool create_value_list_for_tvc(THD *thd, List< List > *values); - Item *in_predicate_to_in_subs_transformer(THD *thd, uchar *arg); - uint32 max_length_of_left_expr(); -}; - -class cmp_item_row :public cmp_item -{ - cmp_item **comparators; - uint n; - bool alloc_comparators(THD *thd, uint n); - bool aggregate_row_elements_for_comparison(THD *thd, - Type_handler_hybrid_field_type *cmp, - Item_args *tmp, - const char *funcname, - uint col, - uint level); -public: - cmp_item_row(): comparators(0), n(0) {} - ~cmp_item_row(); - void store_value(Item *item); - bool prepare_comparators(THD *, const char *funcname, - const Item_args *args, uint level); - int cmp(Item *arg); - int cmp_not_null(const Value *val) - { - DBUG_ASSERT(false); - return TRUE; - } - int compare(cmp_item *arg); - cmp_item *make_same(); - void store_value_by_template(THD *thd, cmp_item *tmpl, Item *); - friend class Item_func_in; - cmp_item *get_comparator(uint i) { return comparators[i]; } -}; - - -class in_row :public in_vector -{ - cmp_item_row tmp; -public: - in_row(THD *thd, uint elements, Item *); - ~in_row(); - void set(uint pos,Item *item); - uchar *get_value(Item *item); - friend class Item_func_in; - const Type_handler *type_handler() const { return &type_handler_row; } - cmp_item *get_cmp_item() { return &tmp; } -}; - -/* Functions used by where clause */ -class Item_func_null_predicate :public Item_bool_func -{ -protected: - SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *value) - { - DBUG_ENTER("Item_func_null_predicate::get_func_mm_tree"); - DBUG_RETURN(get_mm_parts(param, field, functype(), value)); - } - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, - KEY_PART *key_part, - Item_func::Functype type, Item *value); -public: - Item_func_null_predicate(THD *thd, Item *a): Item_bool_func(thd, a) { } - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, - table_map usable_tables, SARGABLE_PARAM **sargables); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) - { - DBUG_ENTER("Item_func_null_predicate::get_mm_tree"); - SEL_TREE *ftree= get_full_func_mm_tree_for_args(param, args[0], NULL); - if (!ftree) - ftree= Item_func::get_mm_tree(param, cond_ptr); - DBUG_RETURN(ftree); - } - CHARSET_INFO *compare_collation() const - { return args[0]->collation.collation; } - bool fix_length_and_dec() - { - decimals=0; max_length=1; maybe_null=0; - return FALSE; - } - bool count_sargable_conds(void *arg); -}; - - -class Item_func_isnull :public Item_func_null_predicate -{ -public: - Item_func_isnull(THD *thd, Item *a): Item_func_null_predicate(thd, a) {} - longlong val_int(); - enum Functype functype() const { return ISNULL_FUNC; } - const char *func_name() const { return "isnull"; } - void print(String *str, enum_query_type query_type); - enum precedence precedence() const { return CMP_PRECEDENCE; } - - bool arg_is_datetime_notnull_field() - { - Item **args= arguments(); - if (args[0]->real_item()->type() == Item::FIELD_ITEM) - { - Field *field=((Item_field*) args[0]->real_item())->field; - - if ((field->flags & NOT_NULL_FLAG) && - field->type_handler()->cond_notnull_field_isnull_to_field_eq_zero()) - return true; - } - return false; - } - - /* Optimize case of not_null_column IS NULL */ - virtual void update_used_tables() - { - if (!args[0]->maybe_null && !arg_is_datetime_notnull_field()) - { - used_tables_cache= 0; /* is always false */ - const_item_cache= 1; - } - else - { - args[0]->update_used_tables(); - used_tables_cache= args[0]->used_tables(); - const_item_cache= args[0]->const_item(); - } - } - COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, - bool top_level); - table_map not_null_tables() const { return 0; } - bool find_not_null_fields(table_map allowed); - Item *neg_transformer(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* Functions used by HAVING for rewriting IN subquery */ - -class Item_in_subselect; - -/* - This is like IS NOT NULL but it also remembers if it ever has - encountered a NULL. -*/ -class Item_is_not_null_test :public Item_func_isnull -{ - Item_in_subselect* owner; -public: - Item_is_not_null_test(THD *thd, Item_in_subselect* ow, Item *a): - Item_func_isnull(thd, a), owner(ow) - {} - enum Functype functype() const { return ISNOTNULLTEST_FUNC; } - longlong val_int(); - const char *func_name() const { return ""; } - void update_used_tables(); - /* - we add RAND_TABLE_BIT to prevent moving this item from HAVING to WHERE - */ - table_map used_tables() const - { return used_tables_cache | RAND_TABLE_BIT; } - bool const_item() const { return FALSE; } -}; - - -class Item_func_isnotnull :public Item_func_null_predicate -{ - bool abort_on_null; -public: - Item_func_isnotnull(THD *thd, Item *a): - Item_func_null_predicate(thd, a), abort_on_null(0) - { } - longlong val_int(); - enum Functype functype() const { return ISNOTNULL_FUNC; } - const char *func_name() const { return "isnotnull"; } - enum precedence precedence() const { return CMP_PRECEDENCE; } - table_map not_null_tables() const - { return abort_on_null ? not_null_tables_cache : 0; } - Item *neg_transformer(THD *thd); - void print(String *str, enum_query_type query_type); - void top_level_item() { abort_on_null=1; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_like :public Item_bool_func2 -{ - // Turbo Boyer-Moore data - bool canDoTurboBM; // pattern is '%abcd%' case - const char* pattern; - int pattern_len; - - // TurboBM buffers, *this is owner - int* bmGs; // good suffix shift table, size is pattern_len + 1 - int* bmBc; // bad character shift table, size is alphabet_size - - void turboBM_compute_suffixes(int* suff); - void turboBM_compute_good_suffix_shifts(int* suff); - void turboBM_compute_bad_character_shifts(); - bool turboBM_matches(const char* text, int text_len) const; - enum { alphabet_size = 256 }; - - Item *escape_item; - - bool escape_used_in_parsing; - bool use_sampling; - - DTCollation cmp_collation; - String cmp_value1, cmp_value2; - bool with_sargable_pattern() const; -protected: - SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, - Field *field, Item *value) - { - DBUG_ENTER("Item_func_like::get_func_mm_tree"); - DBUG_RETURN(get_mm_parts(param, field, LIKE_FUNC, value)); - } - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, - KEY_PART *key_part, - Item_func::Functype type, Item *value); -public: - int escape; - bool negated; - - Item_func_like(THD *thd, Item *a, Item *b, Item *escape_arg, bool escape_used): - Item_bool_func2(thd, a, b), canDoTurboBM(FALSE), pattern(0), pattern_len(0), - bmGs(0), bmBc(0), escape_item(escape_arg), - escape_used_in_parsing(escape_used), use_sampling(0), negated(0) {} - - bool get_negated() const { return negated; } // Used by ColumnStore - - Sql_mode_dependency value_depends_on_sql_mode() const; - longlong val_int(); - enum Functype functype() const { return LIKE_FUNC; } - void print(String *str, enum_query_type query_type); - CHARSET_INFO *compare_collation() const - { return cmp_collation.collation; } - cond_result eq_cmp_result() const - { - /** - We cannot always rewrite conditions as follows: - from: WHERE expr1=const AND expr1 LIKE expr2 - to: WHERE expr1=const AND const LIKE expr2 - or - from: WHERE expr1=const AND expr2 LIKE expr1 - to: WHERE expr1=const AND expr2 LIKE const - - because LIKE works differently comparing to the regular "=" operator: - - 1. LIKE performs a stricter one-character-to-one-character comparison - and does not recognize contractions and expansions. - Replacing "expr1" to "const in LIKE would make the condition - stricter in case of a complex collation. - - 2. LIKE does not ignore trailing spaces and thus works differently - from the "=" operator in case of "PAD SPACE" collations - (which are the majority in MariaDB). So, for "PAD SPACE" collations: - - - expr1=const - ignores trailing spaces - - const LIKE expr2 - does not ignore trailing spaces - - expr2 LIKE const - does not ignore trailing spaces - - Allow only "binary" for now. - It neither ignores trailing spaces nor has contractions/expansions. - - TODO: - We could still replace "expr1" to "const" in "expr1 LIKE expr2" - in case of a "PAD SPACE" collation, but only if "expr2" has '%' - at the end. - */ - return compare_collation() == &my_charset_bin ? COND_TRUE : COND_OK; - } - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, - table_map usable_tables, SARGABLE_PARAM **sargables); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - /* - LIKE differs from the regular comparison operator ('=') in the following: - - LIKE never ignores trailing spaces (even for PAD SPACE collations) - Propagation of equal fields with a PAD SPACE collation into LIKE - is not safe. - Example: - WHERE a='a ' AND a LIKE 'a' - returns true for 'a' - cannot be rewritten to: - WHERE a='a ' AND 'a ' LIKE 'a' - returns false for 'a' - Note, binary collations in MySQL/MariaDB, e.g. latin1_bin, - still have the PAD SPACE attribute and ignore trailing spaces! - - LIKE does not take into account contractions, expansions, - and ignorable characters. - Propagation of equal fields with contractions/expansions/ignorables - is also not safe. - - It's safe to propagate my_charset_bin (BINARY/VARBINARY/BLOB) values, - because they do not ignore trailing spaces and have one-to-one mapping - between a string and its weights. - The below condition should be true only for my_charset_bin - (as of version 10.1.7). - */ - uint flags= Item_func_like::compare_collation()->state; - if ((flags & MY_CS_NOPAD) && !(flags & MY_CS_NON1TO1)) - Item_args::propagate_equal_fields(thd, - Context(ANY_SUBST, - &type_handler_long_blob, - compare_collation()), - cond); - return this; - } - const char *func_name() const { return "like"; } - enum precedence precedence() const { return IN_PRECEDENCE; } - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec() - { - max_length= 1; - return agg_arg_charsets_for_comparison(cmp_collation, args, 2); - } - void cleanup(); - - Item *neg_transformer(THD *thd) - { - negated= !negated; - return this; - } - - bool find_selective_predicates_list_processor(void *arg); - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -typedef struct pcre2_real_code_8 pcre2_code; -typedef struct pcre2_real_match_data_8 pcre2_match_data; -#define PCRE2_SIZE size_t -class Regexp_processor_pcre -{ - pcre2_code *m_pcre; - pcre2_match_data *m_pcre_match_data; - bool m_conversion_is_needed; - bool m_is_const; - int m_library_flags; - CHARSET_INFO *m_library_charset; - String m_prev_pattern; - int m_pcre_exec_rc; - PCRE2_SIZE *m_SubStrVec; - void pcre_exec_warn(int rc) const; - int pcre_exec_with_warn(const pcre2_code *code, - pcre2_match_data *data, - const char *subject, int length, int startoffset, - int options); -public: - String *convert_if_needed(String *src, String *converter); - String subject_converter; - String pattern_converter; - String replace_converter; - Regexp_processor_pcre() : - m_pcre(NULL), m_pcre_match_data(NULL), - m_conversion_is_needed(true), m_is_const(0), - m_library_flags(0), - m_library_charset(&my_charset_utf8mb3_general_ci) - {} - int default_regex_flags(); - void init(CHARSET_INFO *data_charset, int extra_flags); - void fix_owner(Item_func *owner, Item *subject_arg, Item *pattern_arg); - bool compile(String *pattern, bool send_error); - bool compile(Item *item, bool send_error); - bool recompile(Item *item) - { - return !m_is_const && compile(item, false); - } - bool exec(const char *str, size_t length, size_t offset); - bool exec(String *str, int offset, uint n_result_offsets_to_convert); - bool exec(Item *item, int offset, uint n_result_offsets_to_convert); - bool match() const { return m_pcre_exec_rc < 0 ? 0 : 1; } - int nsubpatterns() const { return m_pcre_exec_rc <= 0 ? 0 : m_pcre_exec_rc; } - size_t subpattern_start(int n) const - { - return m_pcre_exec_rc <= 0 ? 0 : m_SubStrVec[n * 2]; - } - size_t subpattern_end(int n) const - { - return m_pcre_exec_rc <= 0 ? 0 : m_SubStrVec[n * 2 + 1]; - } - size_t subpattern_length(int n) const - { - return subpattern_end(n) - subpattern_start(n); - } - void reset() - { - m_pcre= NULL; - m_pcre_match_data= NULL; - m_prev_pattern.length(0); - } - void cleanup(); - bool is_compiled() const { return m_pcre != NULL; } - bool is_const() const { return m_is_const; } - void set_const(bool arg) { m_is_const= arg; } - CHARSET_INFO * library_charset() const { return m_library_charset; } -}; - - -class Item_func_regex :public Item_bool_func -{ - Regexp_processor_pcre re; - DTCollation cmp_collation; -public: - Item_func_regex(THD *thd, Item *a, Item *b): Item_bool_func(thd, a, b) - {} - void cleanup() - { - DBUG_ENTER("Item_func_regex::cleanup"); - Item_bool_func::cleanup(); - re.cleanup(); - DBUG_VOID_RETURN; - } - longlong val_int(); - bool fix_length_and_dec(); - const char *func_name() const { return "regexp"; } - enum precedence precedence() const { return IN_PRECEDENCE; } - Item *get_copy(THD *) { return 0; } - void print(String *str, enum_query_type query_type) - { - print_op(str, query_type); - } - - CHARSET_INFO *compare_collation() const { return cmp_collation.collation; } -}; - - -/* - In the corner case REGEXP_INSTR could return (2^32 + 1), - which would not fit into Item_long_func range. - But string lengths are limited with max_allowed_packet, - which cannot be bigger than 1024*1024*1024. -*/ -class Item_func_regexp_instr :public Item_long_func -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_str(func_name()) || - args[1]->check_type_can_return_text(func_name()); - } - Regexp_processor_pcre re; - DTCollation cmp_collation; -public: - Item_func_regexp_instr(THD *thd, Item *a, Item *b) - :Item_long_func(thd, a, b) - {} - void cleanup() - { - DBUG_ENTER("Item_func_regexp_instr::cleanup"); - Item_int_func::cleanup(); - re.cleanup(); - DBUG_VOID_RETURN; - } - longlong val_int(); - bool fix_length_and_dec(); - const char *func_name() const { return "regexp_instr"; } - Item *get_copy(THD *thd) { return 0; } -}; - - -typedef class Item COND; - -class Item_cond :public Item_bool_func -{ -protected: - List list; - bool abort_on_null; - table_map and_tables_cache; - -public: - /* Item_cond() is only used to create top level items */ - Item_cond(THD *thd): Item_bool_func(thd), abort_on_null(1) - { const_item_cache=0; } - Item_cond(THD *thd, Item *i1, Item *i2); - Item_cond(THD *thd, Item_cond *item); - Item_cond(THD *thd, List &nlist): - Item_bool_func(thd), list(nlist), abort_on_null(0) {} - bool add(Item *item, MEM_ROOT *root) - { - DBUG_ASSERT(item); - return list.push_back(item, root); - } - bool add_at_head(Item *item, MEM_ROOT *root) - { - DBUG_ASSERT(item); - return list.push_front(item, root); - } - void add_at_head(List *nlist) - { - DBUG_ASSERT(nlist->elements); - list.prepend(nlist); - } - void add_at_end(List *nlist) - { - DBUG_ASSERT(nlist->elements); - list.append(nlist); - } - bool fix_fields(THD *, Item **ref); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - - enum Type type() const { return COND_ITEM; } - List* argument_list() { return &list; } - table_map used_tables() const; - void update_used_tables() - { - used_tables_and_const_cache_init(); - used_tables_and_const_cache_update_and_join(list); - } - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref); - COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, - bool top_level); - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); - virtual void print(String *str, enum_query_type query_type); - void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, uint flags); - friend int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves, - COND **conds); - void top_level_item() { abort_on_null=1; } - bool top_level() { return abort_on_null; } - void copy_andor_arguments(THD *thd, Item_cond *item); - bool walk(Item_processor processor, bool walk_subquery, void *arg); - Item *transform(THD *thd, Item_transformer transformer, uchar *arg); - void traverse_cond(Cond_traverser, void *arg, traverse_order order); - void neg_arguments(THD *thd); - Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *); - Item *compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, - Item_transformer transformer, uchar *arg_t); - bool eval_not_null_tables(void *opt_arg); - bool find_not_null_fields(table_map allowed); - Item *build_clone(THD *thd); - bool excl_dep_on_table(table_map tab_map); - bool excl_dep_on_grouping_fields(st_select_lex *sel); -}; - -template class LI, class T> class Item_equal_iterator; - -/* - The class Item_equal is used to represent conjunctions of equality - predicates of the form field1 = field2, and field=const in where - conditions and on expressions. - - All equality predicates of the form field1=field2 contained in a - conjunction are substituted for a sequence of items of this class. - An item of this class Item_equal(f1,f2,...fk) represents a - multiple equality f1=f2=...=fk.l - - If a conjunction contains predicates f1=f2 and f2=f3, a new item of - this class is created Item_equal(f1,f2,f3) representing the multiple - equality f1=f2=f3 that substitutes the above equality predicates in - the conjunction. - A conjunction of the predicates f2=f1 and f3=f1 and f3=f2 will be - substituted for the item representing the same multiple equality - f1=f2=f3. - An item Item_equal(f1,f2) can appear instead of a conjunction of - f2=f1 and f1=f2, or instead of just the predicate f1=f2. - - An item of the class Item_equal inherits equalities from outer - conjunctive levels. - - Suppose we have a where condition of the following form: - WHERE f1=f2 AND f3=f4 AND f3=f5 AND ... AND (...OR (f1=f3 AND ...)). - In this case: - f1=f2 will be substituted for Item_equal(f1,f2); - f3=f4 and f3=f5 will be substituted for Item_equal(f3,f4,f5); - f1=f3 will be substituted for Item_equal(f1,f2,f3,f4,f5); - - An object of the class Item_equal can contain an optional constant - item c. Then it represents a multiple equality of the form - c=f1=...=fk. - - Objects of the class Item_equal are used for the following: - - 1. An object Item_equal(t1.f1,...,tk.fk) allows us to consider any - pair of tables ti and tj as joined by an equi-condition. - Thus it provide us with additional access paths from table to table. - - 2. An object Item_equal(t1.f1,...,tk.fk) is applied to deduce new - SARGable predicates: - f1=...=fk AND P(fi) => f1=...=fk AND P(fi) AND P(fj). - It also can give us additional index scans and can allow us to - improve selectivity estimates. - - 3. An object Item_equal(t1.f1,...,tk.fk) is used to optimize the - selected execution plan for the query: if table ti is accessed - before the table tj then in any predicate P in the where condition - the occurrence of tj.fj is substituted for ti.fi. This can allow - an evaluation of the predicate at an earlier step. - - When feature 1 is supported they say that join transitive closure - is employed. - When feature 2 is supported they say that search argument transitive - closure is employed. - Both features are usually supported by preprocessing original query and - adding additional predicates. - We do not just add predicates, we rather dynamically replace some - predicates that can not be used to access tables in the investigated - plan for those, obtained by substitution of some fields for equal fields, - that can be used. - - Prepared Statements/Stored Procedures note: instances of class - Item_equal are created only at the time a PS/SP is executed and - are deleted in the end of execution. All changes made to these - objects need not be registered in the list of changes of the parse - tree and do not harm PS/SP re-execution. - - Item equal objects are employed only at the optimize phase. Usually they are - not supposed to be evaluated. Yet in some cases we call the method val_int() - for them. We have to take care of restricting the predicate such an - object represents f1=f2= ...=fn to the projection of known fields fi1=...=fik. -*/ - -class Item_equal: public Item_bool_func -{ - /* - The list of equal items. Currently the list can contain: - - Item_fields items for references to table columns - - Item_direct_view_ref items for references to view columns - - one const item - - If the list contains a constant item this item is always first in the list. - The list contains at least two elements. - Currently all Item_fields/Item_direct_view_ref items in the list should - refer to table columns with equavalent type definitions. In particular - if these are string columns they should have the same charset/collation. - - Use objects of the companion class Item_equal_fields_iterator to iterate - over all items from the list of the Item_field/Item_direct_view_ref classes. - */ - List equal_items; - /* - TRUE <-> one of the items is a const item. - Such item is always first in in the equal_items list - */ - bool with_const; - /* - The field eval_item is used when this item is evaluated - with the method val_int() - */ - cmp_item *eval_item; - /* - This initially is set to FALSE. It becomes TRUE when this item is evaluated - as being always false. If the flag is TRUE the contents of the list - the equal_items should be ignored. - */ - bool cond_false; - /* - This initially is set to FALSE. It becomes TRUE when this item is evaluated - as being always true. If the flag is TRUE the contents of the list - the equal_items should be ignored. - */ - bool cond_true; - /* - For Item_equal objects inside an OR clause: one of the fields that were - used in the original equality. - */ - Item_field *context_field; - - bool link_equal_fields; - - const Type_handler *m_compare_handler; - CHARSET_INFO *m_compare_collation; -public: - - COND_EQUAL *upper_levels; /* multiple equalities of upper and levels */ - - Item_equal(THD *thd, const Type_handler *handler, - Item *f1, Item *f2, bool with_const_item); - Item_equal(THD *thd, Item_equal *item_equal); - /* Currently the const item is always the first in the list of equal items */ - inline Item* get_const() { return with_const ? equal_items.head() : NULL; } - void add_const(THD *thd, Item *c); - /** Add a non-constant item to the multiple equality */ - void add(Item *f, MEM_ROOT *root) { equal_items.push_back(f, root); } - bool contains(Field *field); - Item* get_first(struct st_join_table *context, Item *field); - /** Get number of field items / references to field items in this object */ - uint n_field_items() { return equal_items.elements - MY_TEST(with_const); } - void merge(THD *thd, Item_equal *item); - bool merge_with_check(THD *thd, Item_equal *equal_item, bool save_merged); - void merge_into_list(THD *thd, List *list, bool save_merged, - bool only_intersected); - void update_const(THD *thd); - enum Functype functype() const { return MULT_EQUAL_FUNC; } - longlong val_int(); - const char *func_name() const { return "multiple equal"; } - void sort(Item_field_cmpfunc compare, void *arg); - bool fix_length_and_dec(); - bool fix_fields(THD *thd, Item **ref); - void cleanup() - { - delete eval_item; - eval_item= NULL; - } - void update_used_tables(); - bool find_not_null_fields(table_map allowed); - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref); - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); - bool walk(Item_processor processor, bool walk_subquery, void *arg); - Item *transform(THD *thd, Item_transformer transformer, uchar *arg); - virtual void print(String *str, enum_query_type query_type); - const Type_handler *compare_type_handler() const { return m_compare_handler; } - CHARSET_INFO *compare_collation() const { return m_compare_collation; } - - void set_context_field(Item_field *ctx_field) { context_field= ctx_field; } - void set_link_equal_fields(bool flag) { link_equal_fields= flag; } - Item* get_copy(THD *thd) { return 0; } - /* - This does not comply with the specification of the virtual method, - but Item_equal items are processed distinguishly anyway - */ - bool excl_dep_on_table(table_map tab_map) - { - return used_tables() & tab_map; - } - bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred); - bool excl_dep_on_grouping_fields(st_select_lex *sel); - bool create_pushable_equalities(THD *thd, List *equalities, - Pushdown_checker checker, uchar *arg, - bool clone_const); - /* Return the number of elements in this multiple equality */ - uint elements_count() { return equal_items.elements; } - friend class Item_equal_fields_iterator; - bool count_sargable_conds(void *arg); - Item *multiple_equality_transformer(THD *thd, uchar *arg); - friend class Item_equal_iterator; - friend class Item_equal_iterator; - friend Item *eliminate_item_equal(THD *thd, COND *cond, - COND_EQUAL *upper_levels, - Item_equal *item_equal); - friend bool setup_sj_materialization_part1(struct st_join_table *tab); - friend bool setup_sj_materialization_part2(struct st_join_table *tab); -}; - -class COND_EQUAL: public Sql_alloc -{ -public: - uint max_members; /* max number of members the current level - list and all lower level lists */ - COND_EQUAL *upper_levels; /* multiple equalities of upper and levels */ - List current_level; /* list of multiple equalities of - the current and level */ - COND_EQUAL() - { - upper_levels= 0; - } - COND_EQUAL(Item_equal *item, MEM_ROOT *mem_root) - :upper_levels(0) - { - current_level.push_back(item, mem_root); - } - void copy(COND_EQUAL &cond_equal) - { - max_members= cond_equal.max_members; - upper_levels= cond_equal.upper_levels; - if (cond_equal.current_level.is_empty()) - current_level.empty(); - else - current_level= cond_equal.current_level; - } - bool is_empty() - { - return (current_level.elements == 0); - } -}; - - -/* - The template Item_equal_iterator is used to define classes - Item_equal_fields_iterator and Item_equal_fields_iterator_slow. - These are helper classes for the class Item equal - Both classes are used to iterate over references to table/view columns - from the list of equal items that included in an Item_equal object. - The second class supports the operation of removal of the current member - from the list when performing an iteration. -*/ - -template class LI, typename T> class Item_equal_iterator - : public LI -{ -protected: - Item_equal *item_equal; - Item *curr_item; -public: - Item_equal_iterator(Item_equal &item_eq) - :LI (item_eq.equal_items) - { - curr_item= NULL; - item_equal= &item_eq; - if (item_eq.with_const) - { - LI *list_it= this; - curr_item= (*list_it)++; - } - } - Item* operator++(int) - { - LI *list_it= this; - curr_item= (*list_it)++; - return curr_item; - } - void rewind(void) - { - LI *list_it= this; - list_it->rewind(); - if (item_equal->with_const) - curr_item= (*list_it)++; - } - Field *get_curr_field() - { - Item_field *item= (Item_field *) (curr_item->real_item()); - return item->field; - } -}; - -typedef Item_equal_iterator Item_equal_iterator_fast; - -class Item_equal_fields_iterator - :public Item_equal_iterator_fast -{ -public: - Item_equal_fields_iterator(Item_equal &item_eq) - :Item_equal_iterator_fast(item_eq) - { } - Item ** ref() - { - return List_iterator_fast::ref(); - } -}; - -typedef Item_equal_iterator Item_equal_iterator_iterator_slow; - -class Item_equal_fields_iterator_slow - :public Item_equal_iterator_iterator_slow -{ -public: - Item_equal_fields_iterator_slow(Item_equal &item_eq) - :Item_equal_iterator_iterator_slow(item_eq) - { } - void remove() - { - List_iterator::remove(); - } -}; - - -class Item_cond_and final :public Item_cond -{ -public: - COND_EQUAL m_cond_equal; /* contains list of Item_equal objects for - the current and level and reference - to multiple equalities of upper and levels */ - Item_cond_and(THD *thd): Item_cond(thd) {} - Item_cond_and(THD *thd, Item *i1,Item *i2): Item_cond(thd, i1, i2) {} - Item_cond_and(THD *thd, Item_cond_and *item): Item_cond(thd, item) {} - Item_cond_and(THD *thd, List &list_arg): Item_cond(thd, list_arg) {} - enum Functype functype() const { return COND_AND_FUNC; } - longlong val_int(); - const char *func_name() const { return "and"; } - enum precedence precedence() const { return AND_PRECEDENCE; } - table_map not_null_tables() const - { return abort_on_null ? not_null_tables_cache: and_tables_cache; } - Item *copy_andor_structure(THD *thd); - Item *neg_transformer(THD *thd); - void mark_as_condition_AND_part(TABLE_LIST *embedding); - virtual uint exists2in_reserved_items() { return list.elements; }; - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref); - bool set_format_by_check_constraint(Send_field_extended_metadata *to) const; - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, - table_map usable_tables, SARGABLE_PARAM **sargables); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -inline bool is_cond_and(Item *item) -{ - Item_func *func_item= item->get_item_func(); - return func_item && func_item->functype() == Item_func::COND_AND_FUNC; -} - -class Item_cond_or final :public Item_cond -{ -public: - Item_cond_or(THD *thd): Item_cond(thd) {} - Item_cond_or(THD *thd, Item *i1,Item *i2): Item_cond(thd, i1, i2) {} - Item_cond_or(THD *thd, Item_cond_or *item): Item_cond(thd, item) {} - Item_cond_or(THD *thd, List &list_arg): Item_cond(thd, list_arg) {} - enum Functype functype() const { return COND_OR_FUNC; } - longlong val_int(); - const char *func_name() const { return "or"; } - enum precedence precedence() const { return OR_PRECEDENCE; } - table_map not_null_tables() const { return and_tables_cache; } - Item *copy_andor_structure(THD *thd); - Item *neg_transformer(THD *thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_dyncol_check :public Item_bool_func -{ -public: - Item_func_dyncol_check(THD *thd, Item *str): Item_bool_func(thd, str) {} - longlong val_int(); - const char *func_name() const { return "column_check"; } - bool need_parentheses_in_default() { return false; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_dyncol_exists :public Item_bool_func -{ -public: - Item_func_dyncol_exists(THD *thd, Item *str, Item *num): - Item_bool_func(thd, str, num) {} - longlong val_int(); - const char *func_name() const { return "column_exists"; } - bool need_parentheses_in_default() { return false; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_cursor_bool_attr: public Item_bool_func, public Cursor_ref -{ -public: - Item_func_cursor_bool_attr(THD *thd, const LEX_CSTRING *name, uint offset) - :Item_bool_func(thd), Cursor_ref(name, offset) - { } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), arg, VCOL_SESSION_FUNC); - } - void print(String *str, enum_query_type query_type) - { - Cursor_ref::print_func(str, func_name()); - } -}; - - -class Item_func_cursor_isopen: public Item_func_cursor_bool_attr -{ -public: - Item_func_cursor_isopen(THD *thd, const LEX_CSTRING *name, uint offset) - :Item_func_cursor_bool_attr(thd, name, offset) { } - const char *func_name() const { return "%ISOPEN"; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_cursor_found: public Item_func_cursor_bool_attr -{ -public: - Item_func_cursor_found(THD *thd, const LEX_CSTRING *name, uint offset) - :Item_func_cursor_bool_attr(thd, name, offset) { maybe_null= true; } - const char *func_name() const { return "%FOUND"; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_cursor_notfound: public Item_func_cursor_bool_attr -{ -public: - Item_func_cursor_notfound(THD *thd, const LEX_CSTRING *name, uint offset) - :Item_func_cursor_bool_attr(thd, name, offset) { maybe_null= true; } - const char *func_name() const { return "%NOTFOUND"; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - - -inline bool is_cond_or(Item *item) -{ - Item_func *func_item= item->get_item_func(); - return func_item && func_item->functype() == Item_func::COND_OR_FUNC; -} - -Item *and_expressions(Item *a, Item *b, Item **org_item); - -class Comp_creator -{ -public: - Comp_creator() {} /* Remove gcc warning */ - virtual ~Comp_creator() {} /* Remove gcc warning */ - /** - Create operation with given arguments. - */ - virtual Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) - const = 0; - /** - Create operation with given arguments in swap order. - */ - virtual Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) - const = 0; - virtual const char* symbol(bool invert) const = 0; - virtual bool eqne_op() const = 0; - virtual bool l_op() const = 0; -}; - -class Eq_creator :public Comp_creator -{ -public: - Eq_creator() {} /* Remove gcc warning */ - virtual ~Eq_creator() {} /* Remove gcc warning */ - Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const; - Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const; - const char* symbol(bool invert) const { return invert? "<>" : "="; } - bool eqne_op() const { return 1; } - bool l_op() const { return 0; } -}; - -class Ne_creator :public Comp_creator -{ -public: - Ne_creator() {} /* Remove gcc warning */ - virtual ~Ne_creator() {} /* Remove gcc warning */ - Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const; - Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const; - const char* symbol(bool invert) const { return invert? "=" : "<>"; } - bool eqne_op() const { return 1; } - bool l_op() const { return 0; } -}; - -class Gt_creator :public Comp_creator -{ -public: - Gt_creator() {} /* Remove gcc warning */ - virtual ~Gt_creator() {} /* Remove gcc warning */ - Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const; - Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const; - const char* symbol(bool invert) const { return invert? "<=" : ">"; } - bool eqne_op() const { return 0; } - bool l_op() const { return 0; } -}; - -class Lt_creator :public Comp_creator -{ -public: - Lt_creator() {} /* Remove gcc warning */ - virtual ~Lt_creator() {} /* Remove gcc warning */ - Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const; - Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const; - const char* symbol(bool invert) const { return invert? ">=" : "<"; } - bool eqne_op() const { return 0; } - bool l_op() const { return 1; } -}; - -class Ge_creator :public Comp_creator -{ -public: - Ge_creator() {} /* Remove gcc warning */ - virtual ~Ge_creator() {} /* Remove gcc warning */ - Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const; - Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const; - const char* symbol(bool invert) const { return invert? "<" : ">="; } - bool eqne_op() const { return 0; } - bool l_op() const { return 0; } -}; - -class Le_creator :public Comp_creator -{ -public: - Le_creator() {} /* Remove gcc warning */ - virtual ~Le_creator() {} /* Remove gcc warning */ - Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const; - Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const; - const char* symbol(bool invert) const { return invert? ">" : "<="; } - bool eqne_op() const { return 0; } - bool l_op() const { return 1; } -}; - -/* - These need definitions from this file but the variables are defined - in mysqld.h. The variables really belong in this component, but for - the time being we leave them in mysqld.cc to avoid merge problems. -*/ -extern Eq_creator eq_creator; -extern Ne_creator ne_creator; -extern Gt_creator gt_creator; -extern Lt_creator lt_creator; -extern Ge_creator ge_creator; -extern Le_creator le_creator; - -#endif /* ITEM_CMPFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_create.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_create.h deleted file mode 100644 index c9bdb23..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_create.h +++ /dev/null @@ -1,344 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. - Copyright (c) 2008-2011 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Functions to create an item. Used by sql/sql_yacc.yy */ - -#ifndef ITEM_CREATE_H -#define ITEM_CREATE_H - -#include "item_func.h" // Cast_target - -typedef struct st_udf_func udf_func; - -/** - Public function builder interface. - The parser (sql/sql_yacc.yy) uses a factory / builder pattern to - construct an Item object for each function call. - All the concrete function builders implements this interface, - either directly or indirectly with some adapter helpers. - Keeping the function creation separated from the bison grammar allows - to simplify the parser, and avoid the need to introduce a new token - for each function, which has undesirable side effects in the grammar. -*/ - -class Create_func -{ -public: - /** - The builder create method. - Given the function name and list or arguments, this method creates - an Item that represents the function call. - In case or errors, a NULL item is returned, and an error is reported. - Note that the thd object may be modified by the builder. - In particular, the following members/methods can be set/called, - depending on the function called and the function possible side effects. -
    -
  • thd->lex->binlog_row_based_if_mixed
  • -
  • thd->lex->current_context()
  • -
  • thd->lex->safe_to_cache_query
  • -
  • thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT)
  • -
  • thd->lex->uncacheable(UNCACHEABLE_RAND)
  • -
  • thd->lex->add_time_zone_tables_to_query_tables(thd)
  • -
- @param thd The current thread - @param name The function name - @param item_list The list of arguments to the function, can be NULL - @return An item representing the parsed function call, or NULL - */ - virtual Item *create_func(THD *thd, LEX_CSTRING *name, List *item_list) = 0; - -protected: - /** Constructor */ - Create_func() {} - /** Destructor */ - virtual ~Create_func() {} -}; - - -/** - Adapter for functions that takes exactly zero arguments. -*/ - -class Create_func_arg0 : public Create_func -{ -public: - virtual Item *create_func(THD *thd, LEX_CSTRING *name, - List *item_list); - - /** - Builder method, with no arguments. - @param thd The current thread - @return An item representing the function call - */ - virtual Item *create_builder(THD *thd) = 0; - -protected: - /** Constructor. */ - Create_func_arg0() {} - /** Destructor. */ - virtual ~Create_func_arg0() {} -}; - - -/** - Adapter for functions that takes exactly one argument. -*/ - -class Create_func_arg1 : public Create_func -{ -public: - virtual Item *create_func(THD *thd, LEX_CSTRING *name, List *item_list); - - /** - Builder method, with one argument. - @param thd The current thread - @param arg1 The first argument of the function - @return An item representing the function call - */ - virtual Item *create_1_arg(THD *thd, Item *arg1) = 0; - -protected: - /** Constructor. */ - Create_func_arg1() {} - /** Destructor. */ - virtual ~Create_func_arg1() {} -}; - - -/** - Adapter for functions that takes exactly two arguments. -*/ - -class Create_func_arg2 : public Create_func -{ -public: - virtual Item *create_func(THD *thd, LEX_CSTRING *name, List *item_list); - - /** - Builder method, with two arguments. - @param thd The current thread - @param arg1 The first argument of the function - @param arg2 The second argument of the function - @return An item representing the function call - */ - virtual Item *create_2_arg(THD *thd, Item *arg1, Item *arg2) = 0; - -protected: - /** Constructor. */ - Create_func_arg2() {} - /** Destructor. */ - virtual ~Create_func_arg2() {} -}; - - -/** - Adapter for functions that takes exactly three arguments. -*/ - -class Create_func_arg3 : public Create_func -{ -public: - virtual Item *create_func(THD *thd, LEX_CSTRING *name, List *item_list); - - /** - Builder method, with three arguments. - @param thd The current thread - @param arg1 The first argument of the function - @param arg2 The second argument of the function - @param arg3 The third argument of the function - @return An item representing the function call - */ - virtual Item *create_3_arg(THD *thd, Item *arg1, Item *arg2, Item *arg3) = 0; - -protected: - /** Constructor. */ - Create_func_arg3() {} - /** Destructor. */ - virtual ~Create_func_arg3() {} -}; - - - - -/** - Adapter for native functions with a variable number of arguments. - The main use of this class is to discard the following calls: - foo(expr1 AS name1, expr2 AS name2, ...) - which are syntactically correct (the syntax can refer to a UDF), - but semantically invalid for native functions. -*/ - -class Create_native_func : public Create_func -{ -public: - virtual Item *create_func(THD *thd, LEX_CSTRING *name, - List *item_list); - - /** - Builder method, with no arguments. - @param thd The current thread - @param name The native function name - @param item_list The function parameters, none of which are named - @return An item representing the function call - */ - virtual Item *create_native(THD *thd, LEX_CSTRING *name, - List *item_list) = 0; - -protected: - /** Constructor. */ - Create_native_func() {} - /** Destructor. */ - virtual ~Create_native_func() {} -}; - - -/** - Function builder for qualified functions. - This builder is used with functions call using a qualified function name - syntax, as in db.func(expr, expr, ...). -*/ - -class Create_qfunc : public Create_func -{ -public: - /** - The builder create method, for unqualified functions. - This builder will use the current database for the database name. - @param thd The current thread - @param name The function name - @param item_list The list of arguments to the function, can be NULL - @return An item representing the parsed function call - */ - virtual Item *create_func(THD *thd, LEX_CSTRING *name, - List *item_list); - - /** - The builder create method, for qualified functions. - @param thd The current thread - @param db The database name - @param name The function name - @param use_explicit_name Should the function be represented as 'db.name'? - @param item_list The list of arguments to the function, can be NULL - @return An item representing the parsed function call - */ - virtual Item *create_with_db(THD *thd, LEX_CSTRING *db, LEX_CSTRING *name, - bool use_explicit_name, - List *item_list) = 0; - -protected: - /** Constructor. */ - Create_qfunc() {} - /** Destructor. */ - virtual ~Create_qfunc() {} -}; - - -/** - Find the native function builder associated with a given function name. - @param thd The current thread - @param name The native function name - @return The native function builder associated with the name, or NULL -*/ -extern Create_func *find_native_function_builder(THD *thd, - const LEX_CSTRING *name); - - -/** - Find the function builder for qualified functions. - @param thd The current thread - @return A function builder for qualified functions -*/ -extern Create_qfunc * find_qualified_function_builder(THD *thd); - - -#ifdef HAVE_DLOPEN -/** - Function builder for User Defined Functions. -*/ - -class Create_udf_func : public Create_func -{ -public: - virtual Item *create_func(THD *thd, LEX_CSTRING *name, - List *item_list); - - /** - The builder create method, for User Defined Functions. - @param thd The current thread - @param fct The User Defined Function metadata - @param item_list The list of arguments to the function, can be NULL - @return An item representing the parsed function call - */ - Item *create(THD *thd, udf_func *fct, List *item_list); - - /** Singleton. */ - static Create_udf_func s_singleton; - -protected: - /** Constructor. */ - Create_udf_func() {} - /** Destructor. */ - virtual ~Create_udf_func() {} -}; -#endif - - -struct Native_func_registry -{ - LEX_CSTRING name; - Create_func *builder; -}; - -int item_create_init(); -int item_create_append(Native_func_registry array[]); -void item_create_cleanup(); - -Item *create_func_dyncol_create(THD *thd, List &list); -Item *create_func_dyncol_add(THD *thd, Item *str, - List &list); -Item *create_func_dyncol_delete(THD *thd, Item *str, List &nums); -Item *create_func_dyncol_get(THD *thd, Item *num, Item *str, - const Type_handler *handler, - const char *c_len, const char *c_dec, - CHARSET_INFO *cs); -Item *create_func_dyncol_json(THD *thd, Item *str); - - -class Native_func_registry_array -{ - const Native_func_registry *m_elements; - size_t m_count; -public: - Native_func_registry_array() - :m_elements(NULL), - m_count(0) - { } - Native_func_registry_array(const Native_func_registry *elements, size_t count) - :m_elements(elements), - m_count(count) - { } - const Native_func_registry& element(size_t i) const - { - DBUG_ASSERT(i < m_count); - return m_elements[i]; - } - size_t count() const { return m_count; } - bool append_to_hash(HASH *hash) const; -}; - - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_func.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_func.h deleted file mode 100644 index 6a4a9fa..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_func.h +++ /dev/null @@ -1,3792 +0,0 @@ -#ifndef ITEM_FUNC_INCLUDED -#define ITEM_FUNC_INCLUDED -/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* Function items used by mysql */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#ifdef HAVE_IEEEFP_H -extern "C" /* Bug in BSDI include file */ -{ -#include -} -#endif - -#include "sql_udf.h" // udf_handler -#include "my_decimal.h" // string2my_decimal -#include - - -class Item_func :public Item_func_or_sum, - protected With_sum_func_cache -{ - void sync_with_sum_func_and_with_field(List &list); -protected: - virtual bool check_arguments() const - { - return check_argument_types_scalar(0, arg_count); - } - bool check_argument_types_like_args0() const; - bool check_argument_types_scalar(uint start, uint end) const; - bool check_argument_types_traditional_scalar(uint start, uint end) const; - bool check_argument_types_or_binary(const Type_handler *handler, - uint start, uint end) const; - bool check_argument_types_can_return_int(uint start, uint end) const; - bool check_argument_types_can_return_real(uint start, uint end) const; - bool check_argument_types_can_return_str(uint start, uint end) const; - bool check_argument_types_can_return_text(uint start, uint end) const; - bool check_argument_types_can_return_date(uint start, uint end) const; - bool check_argument_types_can_return_time(uint start, uint end) const; - void print_cast_temporal(String *str, enum_query_type query_type); -public: - - table_map not_null_tables_cache; - - enum Functype { UNKNOWN_FUNC,EQ_FUNC,EQUAL_FUNC,NE_FUNC,LT_FUNC,LE_FUNC, - GE_FUNC,GT_FUNC,FT_FUNC, - LIKE_FUNC,ISNULL_FUNC,ISNOTNULL_FUNC, - COND_AND_FUNC, COND_OR_FUNC, XOR_FUNC, - BETWEEN, IN_FUNC, MULT_EQUAL_FUNC, - INTERVAL_FUNC, ISNOTNULLTEST_FUNC, - SP_EQUALS_FUNC, SP_DISJOINT_FUNC,SP_INTERSECTS_FUNC, - SP_TOUCHES_FUNC,SP_CROSSES_FUNC,SP_WITHIN_FUNC, - SP_CONTAINS_FUNC,SP_OVERLAPS_FUNC, - SP_STARTPOINT,SP_ENDPOINT,SP_EXTERIORRING, - SP_POINTN,SP_GEOMETRYN,SP_INTERIORRINGN, SP_RELATE_FUNC, - NOT_FUNC, NOT_ALL_FUNC, TEMPTABLE_ROWID, - NOW_FUNC, NOW_UTC_FUNC, SYSDATE_FUNC, TRIG_COND_FUNC, - SUSERVAR_FUNC, GUSERVAR_FUNC, COLLATE_FUNC, - EXTRACT_FUNC, CHAR_TYPECAST_FUNC, FUNC_SP, UDF_FUNC, - NEG_FUNC, GSYSVAR_FUNC, IN_OPTIMIZER_FUNC, DYNCOL_FUNC, - JSON_EXTRACT_FUNC, JSON_VALID_FUNC, - CASE_SEARCHED_FUNC, // Used by ColumnStore/Spider - CASE_SIMPLE_FUNC // Used by ColumnStore/spider - }; - static scalar_comparison_op functype_to_scalar_comparison_op(Functype type) - { - switch (type) { - case EQ_FUNC: return SCALAR_CMP_EQ; - case EQUAL_FUNC: return SCALAR_CMP_EQUAL; - case LT_FUNC: return SCALAR_CMP_LT; - case LE_FUNC: return SCALAR_CMP_LE; - case GE_FUNC: return SCALAR_CMP_GE; - case GT_FUNC: return SCALAR_CMP_GT; - default: break; - } - DBUG_ASSERT(0); - return SCALAR_CMP_EQ; - } - enum Type type() const { return FUNC_ITEM; } - virtual enum Functype functype() const { return UNKNOWN_FUNC; } - Item_func(THD *thd): Item_func_or_sum(thd) - { - with_field= 0; - with_param= 0; - } - Item_func(THD *thd, Item *a) - :Item_func_or_sum(thd, a), With_sum_func_cache(a) - { - with_param= a->with_param; - with_field= a->with_field; - } - Item_func(THD *thd, Item *a, Item *b) - :Item_func_or_sum(thd, a, b), With_sum_func_cache(a, b) - { - with_param= a->with_param || b->with_param; - with_field= a->with_field || b->with_field; - } - Item_func(THD *thd, Item *a, Item *b, Item *c) - :Item_func_or_sum(thd, a, b, c), With_sum_func_cache(a, b, c) - { - with_field= a->with_field || b->with_field || c->with_field; - with_param= a->with_param || b->with_param || c->with_param; - } - Item_func(THD *thd, Item *a, Item *b, Item *c, Item *d) - :Item_func_or_sum(thd, a, b, c, d), With_sum_func_cache(a, b, c, d) - { - with_field= a->with_field || b->with_field || - c->with_field || d->with_field; - with_param= a->with_param || b->with_param || - c->with_param || d->with_param; - } - Item_func(THD *thd, Item *a, Item *b, Item *c, Item *d, Item* e) - :Item_func_or_sum(thd, a, b, c, d, e), With_sum_func_cache(a, b, c, d, e) - { - with_field= a->with_field || b->with_field || - c->with_field || d->with_field || e->with_field; - with_param= a->with_param || b->with_param || - c->with_param || d->with_param || e->with_param; - } - Item_func(THD *thd, List &list): - Item_func_or_sum(thd, list) - { - set_arguments(thd, list); - } - // Constructor used for Item_cond_and/or (see Item comment) - Item_func(THD *thd, Item_func *item) - :Item_func_or_sum(thd, item), With_sum_func_cache(item), - not_null_tables_cache(item->not_null_tables_cache) - { } - bool fix_fields(THD *, Item **ref); - void cleanup() - { - Item_func_or_sum::cleanup(); - used_tables_and_const_cache_init(); - } - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - void quick_fix_field(); - table_map not_null_tables() const; - void update_used_tables() - { - used_tables_and_const_cache_init(); - used_tables_and_const_cache_update_and_join(arg_count, args); - } - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref); - SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) - { - DBUG_ENTER("Item_func::get_mm_tree"); - DBUG_RETURN(const_item() ? get_mm_tree_for_const(param) : NULL); - } - bool eq(const Item *item, bool binary_cmp) const; - virtual Item *key_item() const { return args[0]; } - void set_arguments(THD *thd, List &list) - { - Item_args::set_arguments(thd, list); - sync_with_sum_func_and_with_field(list); - list.empty(); // Fields are used - } - void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, uint flags); - virtual void print(String *str, enum_query_type query_type); - void print_op(String *str, enum_query_type query_type); - void print_args(String *str, uint from, enum_query_type query_type); - bool is_null() { - update_null_value(); - return null_value; - } - String *val_str_from_val_str_ascii(String *str, String *str2); - - void signal_divide_by_null(); - friend class udf_handler; - Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) - { return tmp_table_field_from_field_type(root, table); } - Item *get_tmp_table_item(THD *thd); - - void fix_char_length_ulonglong(ulonglong max_char_length_arg) - { - ulonglong max_result_length= max_char_length_arg * - collation.collation->mbmaxlen; - if (max_result_length >= MAX_BLOB_WIDTH) - { - max_length= MAX_BLOB_WIDTH; - maybe_null= 1; - } - else - max_length= (uint32) max_result_length; - } - Item *transform(THD *thd, Item_transformer transformer, uchar *arg); - Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, - Item_transformer transformer, uchar *arg_t); - void traverse_cond(Cond_traverser traverser, - void * arg, traverse_order order); - bool eval_not_null_tables(void *opt_arg); - bool find_not_null_fields(table_map allowed); - // bool is_expensive_processor(void *arg); - // virtual bool is_expensive() { return 0; } - inline void raise_numeric_overflow(const char *type_name) - { - char buf[256]; - String str(buf, sizeof(buf), system_charset_info); - str.length(0); - print(&str, QT_NO_DATA_EXPANSION); - my_error(ER_DATA_OUT_OF_RANGE, MYF(0), type_name, str.c_ptr_safe()); - } - inline double raise_float_overflow() - { - raise_numeric_overflow("DOUBLE"); - return 0.0; - } - inline longlong raise_integer_overflow() - { - raise_numeric_overflow(unsigned_flag ? "BIGINT UNSIGNED": "BIGINT"); - return 0; - } - inline int raise_decimal_overflow() - { - raise_numeric_overflow("DECIMAL"); - return E_DEC_OVERFLOW; - } - /** - Throw an error if the input double number is not finite, i.e. is either - +/-INF or NAN. - */ - inline double check_float_overflow(double value) - { - return std::isfinite(value) ? value : raise_float_overflow(); - } - /** - Throw an error if the input BIGINT value represented by the - (longlong value, bool unsigned flag) pair cannot be returned by the - function, i.e. is not compatible with this Item's unsigned_flag. - */ - inline longlong check_integer_overflow(longlong value, bool val_unsigned) - { - if ((unsigned_flag && !val_unsigned && value < 0) || - (!unsigned_flag && val_unsigned && - (ulonglong) value > (ulonglong) LONGLONG_MAX)) - return raise_integer_overflow(); - return value; - } - /** - Throw an error if the error code of a DECIMAL operation is E_DEC_OVERFLOW. - */ - inline int check_decimal_overflow(int error) - { - return (error == E_DEC_OVERFLOW) ? raise_decimal_overflow() : error; - } - - bool has_timestamp_args() - { - DBUG_ASSERT(fixed == TRUE); - for (uint i= 0; i < arg_count; i++) - { - if (args[i]->type() == Item::FIELD_ITEM && - args[i]->field_type() == MYSQL_TYPE_TIMESTAMP) - return TRUE; - } - return FALSE; - } - - bool has_date_args() - { - DBUG_ASSERT(fixed == TRUE); - for (uint i= 0; i < arg_count; i++) - { - if (args[i]->type() == Item::FIELD_ITEM && - (args[i]->field_type() == MYSQL_TYPE_DATE || - args[i]->field_type() == MYSQL_TYPE_DATETIME)) - return TRUE; - } - return FALSE; - } - - bool has_time_args() - { - DBUG_ASSERT(fixed == TRUE); - for (uint i= 0; i < arg_count; i++) - { - if (args[i]->type() == Item::FIELD_ITEM && - (args[i]->field_type() == MYSQL_TYPE_TIME || - args[i]->field_type() == MYSQL_TYPE_DATETIME)) - return TRUE; - } - return FALSE; - } - - bool has_datetime_args() - { - DBUG_ASSERT(fixed == TRUE); - for (uint i= 0; i < arg_count; i++) - { - if (args[i]->type() == Item::FIELD_ITEM && - args[i]->field_type() == MYSQL_TYPE_DATETIME) - return TRUE; - } - return FALSE; - } - - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - /* - By default only substitution for a field whose two different values - are never equal is allowed in the arguments of a function. - This is overruled for the direct arguments of comparison functions. - */ - Item_args::propagate_equal_fields(thd, Context_identity(), cond); - return this; - } - - bool has_rand_bit() - { - return used_tables() & RAND_TABLE_BIT; - } - - bool excl_dep_on_table(table_map tab_map) - { - if (used_tables() & OUTER_REF_TABLE_BIT) - return false; - return !(used_tables() & ~tab_map) || - Item_args::excl_dep_on_table(tab_map); - } - - bool excl_dep_on_grouping_fields(st_select_lex *sel) - { - if (has_rand_bit() || with_subquery()) - return false; - return Item_args::excl_dep_on_grouping_fields(sel); - } - - bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) - { - return Item_args::excl_dep_on_in_subq_left_part(subq_pred); - } - - /* - We assume the result of any function that has a TIMESTAMP argument to be - timezone-dependent, since a TIMESTAMP value in both numeric and string - contexts is interpreted according to the current timezone. - The only exception is UNIX_TIMESTAMP() which returns the internal - representation of a TIMESTAMP argument verbatim, and thus does not depend on - the timezone. - */ - virtual bool check_valid_arguments_processor(void *bool_arg) - { - return has_timestamp_args(); - } - - virtual bool find_function_processor (void *arg) - { - return functype() == *(Functype *) arg; - } - - void no_rows_in_result() - { - for (uint i= 0; i < arg_count; i++) - { - args[i]->no_rows_in_result(); - } - } - void restore_to_before_no_rows_in_result() - { - for (uint i= 0; i < arg_count; i++) - { - args[i]->no_rows_in_result(); - } - } - void convert_const_compared_to_int_field(THD *thd); - /** - Prepare arguments and setup a comparator. - Used in Item_func_xxx with two arguments and a comparator, - e.g. Item_bool_func2 and Item_func_nullif. - args[0] or args[1] can be modified: - - converted to character set and collation of the operation - - or replaced to an Item_int_with_ref - */ - bool setup_args_and_comparator(THD *thd, Arg_comparator *cmp); - - bool with_sum_func() const { return m_with_sum_func; } - With_sum_func_cache* get_with_sum_func_cache() { return this; } - Item_func *get_item_func() { return this; } - bool is_simplified_cond_processor(void *arg) - { return const_item() && !val_int(); } -}; - - -class Item_real_func :public Item_func -{ -public: - Item_real_func(THD *thd): Item_func(thd) { collation= DTCollation_numeric(); } - Item_real_func(THD *thd, Item *a): Item_func(thd, a) - { collation= DTCollation_numeric(); } - Item_real_func(THD *thd, Item *a, Item *b): Item_func(thd, a, b) - { collation= DTCollation_numeric(); } - Item_real_func(THD *thd, List &list): Item_func(thd, list) - { collation= DTCollation_numeric(); } - String *val_str(String*str); - my_decimal *val_decimal(my_decimal *decimal_value); - longlong val_int() - { - DBUG_ASSERT(fixed == 1); - return Converter_double_to_longlong(val_real(), unsigned_flag).result(); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_real(thd, ltime, fuzzydate); } - const Type_handler *type_handler() const { return &type_handler_double; } - bool fix_length_and_dec() - { - decimals= NOT_FIXED_DEC; - max_length= float_length(decimals); - return FALSE; - } -}; - - -/** - Functions whose returned field type is determined at fix_fields() time. -*/ -class Item_hybrid_func: public Item_func, - public Type_handler_hybrid_field_type -{ -protected: - bool fix_attributes(Item **item, uint nitems); -public: - Item_hybrid_func(THD *thd): Item_func(thd) { } - Item_hybrid_func(THD *thd, Item *a): Item_func(thd, a) { } - Item_hybrid_func(THD *thd, Item *a, Item *b): Item_func(thd, a, b) { } - Item_hybrid_func(THD *thd, Item *a, Item *b, Item *c): - Item_func(thd, a, b, c) { } - Item_hybrid_func(THD *thd, List &list): Item_func(thd, list) { } - Item_hybrid_func(THD *thd, Item_hybrid_func *item) - :Item_func(thd, item), Type_handler_hybrid_field_type(item) { } - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - void fix_length_and_dec_long_or_longlong(uint char_length, bool unsigned_arg) - { - collation= DTCollation_numeric(); - unsigned_flag= unsigned_arg; - max_length= char_length; - set_handler(Type_handler::type_handler_long_or_longlong(char_length, - unsigned_arg)); - } - void fix_length_and_dec_ulong_or_ulonglong_by_nbits(uint nbits) - { - uint digits= Type_handler_bit::Bit_decimal_notation_int_digits_by_nbits(nbits); - collation= DTCollation_numeric(); - unsigned_flag= true; - max_length= digits; - if (nbits > 32) - set_handler(&type_handler_ulonglong); - else - set_handler(&type_handler_ulong); - } -}; - - -class Item_handled_func: public Item_func -{ -public: - class Handler - { - public: - virtual ~Handler() { } - virtual String *val_str(Item_handled_func *, String *) const= 0; - virtual String *val_str_ascii(Item_handled_func *, String *) const= 0; - virtual double val_real(Item_handled_func *) const= 0; - virtual longlong val_int(Item_handled_func *) const= 0; - virtual my_decimal *val_decimal(Item_handled_func *, my_decimal *) const= 0; - virtual bool get_date(THD *thd, Item_handled_func *, MYSQL_TIME *, date_mode_t fuzzydate) const= 0; - virtual bool val_native(THD *thd, Item_handled_func *, Native *to) const - { - DBUG_ASSERT(0); - to->length(0); - return true; - } - virtual const Type_handler * - return_type_handler(const Item_handled_func *item) const= 0; - virtual const Type_handler * - type_handler_for_create_select(const Item_handled_func *item) const - { - return return_type_handler(item); - } - virtual bool fix_length_and_dec(Item_handled_func *) const= 0; - }; - - class Handler_str: public Handler - { - public: - String *val_str_ascii(Item_handled_func *item, String *str) const - { - return item->Item::val_str_ascii(str); - } - double val_real(Item_handled_func *item) const - { - DBUG_ASSERT(item->is_fixed()); - StringBuffer<64> tmp; - String *res= item->val_str(&tmp); - return res ? item->double_from_string_with_check(res) : 0.0; - } - longlong val_int(Item_handled_func *item) const - { - DBUG_ASSERT(item->is_fixed()); - StringBuffer<22> tmp; - String *res= item->val_str(&tmp); - return res ? item->longlong_from_string_with_check(res) : 0; - } - my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const - { - return item->val_decimal_from_string(to); - } - bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, - date_mode_t fuzzydate) const - { - return item->get_date_from_string(thd, to, fuzzydate); - } - }; - - /** - Abstract class for functions returning TIME, DATE, DATETIME or string values, - whose data type depends on parameters and is set at fix_fields time. - */ - class Handler_temporal: public Handler - { - public: - String *val_str(Item_handled_func *item, String *to) const - { - StringBuffer ascii_buf; - return item->val_str_from_val_str_ascii(to, &ascii_buf); - } - }; - - /** - Abstract class for functions returning strings, - which are generated from get_date() results, - when get_date() can return different MYSQL_TIMESTAMP_XXX per row. - */ - class Handler_temporal_string: public Handler_temporal - { - public: - const Type_handler *return_type_handler(const Item_handled_func *) const - { - return &type_handler_string; - } - const Type_handler * - type_handler_for_create_select(const Item_handled_func *item) const - { - return return_type_handler(item)->type_handler_for_tmp_table(item); - } - double val_real(Item_handled_func *item) const - { - return Temporal_hybrid(item).to_double(); - } - longlong val_int(Item_handled_func *item) const - { - return Temporal_hybrid(item).to_longlong(); - } - my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const - { - return Temporal_hybrid(item).to_decimal(to); - } - String *val_str_ascii(Item_handled_func *item, String *to) const - { - return Temporal_hybrid(item).to_string(to, item->decimals); - } - }; - - - class Handler_date: public Handler_temporal - { - public: - const Type_handler *return_type_handler(const Item_handled_func *) const - { - return &type_handler_newdate; - } - bool fix_length_and_dec(Item_handled_func *item) const - { - item->fix_attributes_date(); - return false; - } - double val_real(Item_handled_func *item) const - { - return Date(item).to_double(); - } - longlong val_int(Item_handled_func *item) const - { - return Date(item).to_longlong(); - } - my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const - { - return Date(item).to_decimal(to); - } - String *val_str_ascii(Item_handled_func *item, String *to) const - { - return Date(item).to_string(to); - } - }; - - - class Handler_time: public Handler_temporal - { - public: - const Type_handler *return_type_handler(const Item_handled_func *) const - { - return &type_handler_time2; - } - double val_real(Item_handled_func *item) const - { - return Time(item).to_double(); - } - longlong val_int(Item_handled_func *item) const - { - return Time(item).to_longlong(); - } - my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const - { - return Time(item).to_decimal(to); - } - String *val_str_ascii(Item_handled_func *item, String *to) const - { - return Time(item).to_string(to, item->decimals); - } - bool val_native(THD *thd, Item_handled_func *item, Native *to) const - { - return Time(thd, item).to_native(to, item->decimals); - } - }; - - - class Handler_datetime: public Handler_temporal - { - public: - const Type_handler *return_type_handler(const Item_handled_func *) const - { - return &type_handler_datetime2; - } - double val_real(Item_handled_func *item) const - { - return Datetime(item).to_double(); - } - longlong val_int(Item_handled_func *item) const - { - return Datetime(item).to_longlong(); - } - my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const - { - return Datetime(item).to_decimal(to); - } - String *val_str_ascii(Item_handled_func *item, String *to) const - { - return Datetime(item).to_string(to, item->decimals); - } - }; - - - class Handler_int: public Handler - { - public: - String *val_str(Item_handled_func *item, String *to) const - { - longlong nr= val_int(item); - if (item->null_value) - return 0; - to->set_int(nr, item->unsigned_flag, item->collation.collation); - return to; - } - String *val_str_ascii(Item_handled_func *item, String *to) const - { - return item->Item::val_str_ascii(to); - } - double val_real(Item_handled_func *item) const - { - return item->unsigned_flag ? (double) ((ulonglong) val_int(item)) : - (double) val_int(item); - } - my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const - { - return item->val_decimal_from_int(to); - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzydate) const - { - return item->get_date_from_int(thd, to, fuzzydate); - } - longlong val_int(Item_handled_func *item) const - { - Longlong_null tmp= to_longlong_null(item); - item->null_value= tmp.is_null(); - return tmp.value(); - } - virtual Longlong_null to_longlong_null(Item_handled_func *item) const= 0; - }; - - class Handler_slong: public Handler_int - { - public: - const Type_handler *return_type_handler(const Item_handled_func *item) const - { - return &type_handler_slong; - } - bool fix_length_and_dec(Item_handled_func *item) const - { - item->unsigned_flag= false; - item->collation= DTCollation_numeric(); - item->fix_char_length(11); - return false; - } - }; - - class Handler_slong2: public Handler_slong - { - public: - bool fix_length_and_dec(Item_handled_func *func) const - { - bool rc= Handler_slong::fix_length_and_dec(func); - func->max_length= 2; - return rc; - } - }; - - class Handler_ulonglong: public Handler_int - { - public: - const Type_handler *return_type_handler(const Item_handled_func *item) const - { - return &type_handler_ulonglong; - } - bool fix_length_and_dec(Item_handled_func *item) const - { - item->unsigned_flag= true; - item->collation= DTCollation_numeric(); - item->fix_char_length(21); - return false; - } - }; - -protected: - const Handler *m_func_handler; -public: - Item_handled_func(THD *thd, Item *a) - :Item_func(thd, a), m_func_handler(NULL) { } - Item_handled_func(THD *thd, Item *a, Item *b) - :Item_func(thd, a, b), m_func_handler(NULL) { } - void set_func_handler(const Handler *handler) - { - m_func_handler= handler; - } - const Type_handler *type_handler() const - { - return m_func_handler->return_type_handler(this); - } - Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) - { - DBUG_ASSERT(fixed); - const Type_handler *h= m_func_handler->type_handler_for_create_select(this); - return h->make_and_init_table_field(root, &name, - Record_addr(maybe_null), - *this, table); - } - String *val_str(String *to) - { - return m_func_handler->val_str(this, to); - } - String *val_str_ascii(String *to) - { - return m_func_handler->val_str_ascii(this, to); - } - double val_real() - { - return m_func_handler->val_real(this); - } - longlong val_int() - { - return m_func_handler->val_int(this); - } - my_decimal *val_decimal(my_decimal *to) - { - return m_func_handler->val_decimal(this, to); - } - bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate) - { - return m_func_handler->get_date(thd, this, to, fuzzydate); - } - bool val_native(THD *thd, Native *to) - { - return m_func_handler->val_native(thd, this, to); - } -}; - - -/** - Functions that at fix_fields() time determine the returned field type, - trying to preserve the exact data type of the arguments. - - The descendants have to implement "native" value methods, - i.e. str_op(), date_op(), int_op(), real_op(), decimal_op(). - fix_fields() chooses which of the above value methods will be - used during execution time, according to the returned field type. - - For example, if fix_fields() determines that the returned value type - is MYSQL_TYPE_LONG, then: - - int_op() is chosen as the execution time native method. - - val_int() returns the result of int_op() as is. - - all other methods, i.e. val_real(), val_decimal(), val_str(), get_date(), - call int_op() first, then convert the result to the requested data type. -*/ -class Item_func_hybrid_field_type: public Item_hybrid_func -{ - /* - Helper methods to make sure that the result of - decimal_op(), str_op() and date_op() is properly synched with null_value. - */ - bool date_op_with_null_check(THD *thd, MYSQL_TIME *ltime) - { - bool rc= date_op(thd, ltime, date_mode_t(0)); - DBUG_ASSERT(!rc ^ null_value); - return rc; - } - bool time_op_with_null_check(THD *thd, MYSQL_TIME *ltime) - { - bool rc= time_op(thd, ltime); - DBUG_ASSERT(!rc ^ null_value); - DBUG_ASSERT(rc || ltime->time_type == MYSQL_TIMESTAMP_TIME); - return rc; - } - String *str_op_with_null_check(String *str) - { - String *res= str_op(str); - DBUG_ASSERT((res != NULL) ^ null_value); - return res; - } - -public: - // Value methods that involve no conversion - String *val_str_from_str_op(String *str) - { - return str_op_with_null_check(&str_value); - } - longlong val_int_from_int_op() - { - return int_op(); - } - double val_real_from_real_op() - { - return real_op(); - } - - // Value methods that involve conversion - String *val_str_from_real_op(String *str); - String *val_str_from_int_op(String *str); - String *val_str_from_date_op(String *str); - String *val_str_from_time_op(String *str); - - my_decimal *val_decimal_from_str_op(my_decimal *dec); - my_decimal *val_decimal_from_real_op(my_decimal *dec); - my_decimal *val_decimal_from_int_op(my_decimal *dec); - my_decimal *val_decimal_from_date_op(my_decimal *dec); - my_decimal *val_decimal_from_time_op(my_decimal *dec); - - longlong val_int_from_str_op(); - longlong val_int_from_real_op(); - longlong val_int_from_date_op(); - longlong val_int_from_time_op(); - - double val_real_from_str_op(); - double val_real_from_date_op(); - double val_real_from_time_op(); - double val_real_from_int_op(); - -public: - Item_func_hybrid_field_type(THD *thd): - Item_hybrid_func(thd) - { collation= DTCollation_numeric(); } - Item_func_hybrid_field_type(THD *thd, Item *a): - Item_hybrid_func(thd, a) - { collation= DTCollation_numeric(); } - Item_func_hybrid_field_type(THD *thd, Item *a, Item *b): - Item_hybrid_func(thd, a, b) - { collation= DTCollation_numeric(); } - Item_func_hybrid_field_type(THD *thd, Item *a, Item *b, Item *c): - Item_hybrid_func(thd, a, b, c) - { collation= DTCollation_numeric(); } - Item_func_hybrid_field_type(THD *thd, List &list): - Item_hybrid_func(thd, list) - { collation= DTCollation_numeric(); } - - double val_real() - { - DBUG_ASSERT(fixed); - return Item_func_hybrid_field_type::type_handler()-> - Item_func_hybrid_field_type_val_real(this); - } - longlong val_int() - { - DBUG_ASSERT(fixed); - return Item_func_hybrid_field_type::type_handler()-> - Item_func_hybrid_field_type_val_int(this); - } - my_decimal *val_decimal(my_decimal *dec) - { - DBUG_ASSERT(fixed); - return Item_func_hybrid_field_type::type_handler()-> - Item_func_hybrid_field_type_val_decimal(this, dec); - } - String *val_str(String*str) - { - DBUG_ASSERT(fixed); - String *res= Item_func_hybrid_field_type::type_handler()-> - Item_func_hybrid_field_type_val_str(this, str); - DBUG_ASSERT(null_value == (res == NULL)); - return res; - } - bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) - { - DBUG_ASSERT(fixed); - return Item_func_hybrid_field_type::type_handler()-> - Item_func_hybrid_field_type_get_date_with_warn(thd, this, to, mode); - } - - bool val_native(THD *thd, Native *to) - { - DBUG_ASSERT(fixed); - return native_op(thd, to); - } - - /** - @brief Performs the operation that this functions implements when the - result type is INT. - - @return The result of the operation. - */ - virtual longlong int_op()= 0; - Longlong_null to_longlong_null_op() - { - longlong nr= int_op(); - /* - C++ does not guarantee the order of parameter evaluation, - so to make sure "null_value" is passed to the constructor - after the int_op() call, int_op() is caled on a separate line. - */ - return Longlong_null(nr, null_value); - } - Longlong_hybrid_null to_longlong_hybrid_null_op() - { - return Longlong_hybrid_null(to_longlong_null_op(), unsigned_flag); - } - - /** - @brief Performs the operation that this functions implements when the - result type is REAL. - - @return The result of the operation. - */ - virtual double real_op()= 0; - Double_null to_double_null_op() - { - // val_real() must be caleed on a separate line. See to_longlong_null() - double nr= real_op(); - return Double_null(nr, null_value); - } - - /** - @brief Performs the operation that this functions implements when the - result type is DECIMAL. - - @param A pointer where the DECIMAL value will be allocated. - @return - - 0 If the result is NULL - - The same pointer it was given, with the area initialized to the - result of the operation. - */ - virtual my_decimal *decimal_op(my_decimal *)= 0; - - /** - @brief Performs the operation that this functions implements when the - result type is a string type. - - @return The result of the operation. - */ - virtual String *str_op(String *)= 0; - - /** - @brief Performs the operation that this functions implements when - field type is DATETIME or DATE. - @return The result of the operation. - */ - virtual bool date_op(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate)= 0; - - /** - @brief Performs the operation that this functions implements when - field type is TIME. - @return The result of the operation. - */ - virtual bool time_op(THD *thd, MYSQL_TIME *res)= 0; - - virtual bool native_op(THD *thd, Native *native)= 0; -}; - - -/* - This class resembles SQL standard CASE-alike expressions: - CASE and its abbreviations COALESCE, NULLIF, IFNULL, IF. - - ::= - | -*/ -class Item_func_case_expression: public Item_func_hybrid_field_type -{ -public: - Item_func_case_expression(THD *thd) - :Item_func_hybrid_field_type(thd) - { } - Item_func_case_expression(THD *thd, Item *a) - :Item_func_hybrid_field_type(thd, a) - { } - Item_func_case_expression(THD *thd, Item *a, Item *b) - :Item_func_hybrid_field_type(thd, a, b) - { } - Item_func_case_expression(THD *thd, Item *a, Item *b, Item *c) - :Item_func_hybrid_field_type(thd, a, b, c) - { } - Item_func_case_expression(THD *thd, List &list): - Item_func_hybrid_field_type(thd, list) - { } - bool find_not_null_fields(table_map allowed) { return false; } -}; - - -class Item_func_numhybrid: public Item_func_hybrid_field_type -{ -protected: - - inline void fix_decimals() - { - DBUG_ASSERT(result_type() == DECIMAL_RESULT); - if (decimals == NOT_FIXED_DEC) - set_if_smaller(decimals, max_length - 1); - } - -public: - Item_func_numhybrid(THD *thd): Item_func_hybrid_field_type(thd) - { } - Item_func_numhybrid(THD *thd, Item *a): Item_func_hybrid_field_type(thd, a) - { } - Item_func_numhybrid(THD *thd, Item *a, Item *b): - Item_func_hybrid_field_type(thd, a, b) - { } - Item_func_numhybrid(THD *thd, Item *a, Item *b, Item *c): - Item_func_hybrid_field_type(thd, a, b, c) - { } - Item_func_numhybrid(THD *thd, List &list): - Item_func_hybrid_field_type(thd, list) - { } - String *str_op(String *str) { DBUG_ASSERT(0); return 0; } - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - DBUG_ASSERT(0); - return true; - } - bool time_op(THD *thd, MYSQL_TIME *ltime) - { - DBUG_ASSERT(0); - return true; - } - bool native_op(THD *thd, Native *to) - { - DBUG_ASSERT(0); - return true; - } -}; - - -/* function where type of result detected by first argument */ -class Item_func_num1: public Item_func_numhybrid -{ -public: - Item_func_num1(THD *thd, Item *a): Item_func_numhybrid(thd, a) {} - Item_func_num1(THD *thd, Item *a, Item *b): Item_func_numhybrid(thd, a, b) {} - bool check_partition_func_processor(void *int_arg) { return FALSE; } - bool check_vcol_func_processor(void *arg) { return FALSE; } -}; - - -/* Base class for operations like '+', '-', '*' */ -class Item_num_op :public Item_func_numhybrid -{ -protected: - bool check_arguments() const - { - return false; // Checked by aggregate_for_num_op() - } -public: - Item_num_op(THD *thd, Item *a, Item *b): Item_func_numhybrid(thd, a, b) {} - virtual void result_precision()= 0; - - virtual inline void print(String *str, enum_query_type query_type) - { - print_op(str, query_type); - } - bool fix_type_handler(const Type_aggregator *aggregator); - void fix_length_and_dec_double() - { - aggregate_numeric_attributes_real(args, arg_count); - max_length= float_length(decimals); - } - void fix_length_and_dec_decimal() - { - unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; - result_precision(); - fix_decimals(); - } - void fix_length_and_dec_int() - { - unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; - result_precision(); - decimals= 0; - set_handler(type_handler_long_or_longlong()); - } - void fix_length_and_dec_temporal(bool downcast_decimal_to_int) - { - set_handler(&type_handler_newdecimal); - fix_length_and_dec_decimal(); - if (decimals == 0 && downcast_decimal_to_int) - set_handler(type_handler_long_or_longlong()); - } - bool need_parentheses_in_default() { return true; } -}; - - -class Item_int_func :public Item_func -{ -public: - /* - QQ: shouldn't 20 characters be enough: - Max unsigned = 18,446,744,073,709,551,615 = 20 digits, 20 characters - Max signed = 9,223,372,036,854,775,807 = 19 digits, 19 characters - Min signed = -9,223,372,036,854,775,808 = 19 digits, 20 characters - */ - Item_int_func(THD *thd): Item_func(thd) - { collation= DTCollation_numeric(); fix_char_length(21); } - Item_int_func(THD *thd, Item *a): Item_func(thd, a) - { collation= DTCollation_numeric(); fix_char_length(21); } - Item_int_func(THD *thd, Item *a, Item *b): Item_func(thd, a, b) - { collation= DTCollation_numeric(); fix_char_length(21); } - Item_int_func(THD *thd, Item *a, Item *b, Item *c): Item_func(thd, a, b, c) - { collation= DTCollation_numeric(); fix_char_length(21); } - Item_int_func(THD *thd, Item *a, Item *b, Item *c, Item *d): - Item_func(thd, a, b, c, d) - { collation= DTCollation_numeric(); fix_char_length(21); } - Item_int_func(THD *thd, List &list): Item_func(thd, list) - { collation= DTCollation_numeric(); fix_char_length(21); } - Item_int_func(THD *thd, Item_int_func *item) :Item_func(thd, item) - { collation= DTCollation_numeric(); } - double val_real(); - String *val_str(String*str); - my_decimal *val_decimal(my_decimal *decimal_value) - { - return val_decimal_from_int(decimal_value); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_int(thd, ltime, fuzzydate); } - const Type_handler *type_handler() const= 0; - bool fix_length_and_dec() { return FALSE; } -}; - - -class Item_long_func: public Item_int_func -{ -public: - Item_long_func(THD *thd): Item_int_func(thd) { } - Item_long_func(THD *thd, Item *a): Item_int_func(thd, a) {} - Item_long_func(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} - Item_long_func(THD *thd, Item *a, Item *b, Item *c): Item_int_func(thd, a, b, c) {} - Item_long_func(THD *thd, List &list): Item_int_func(thd, list) { } - Item_long_func(THD *thd, Item_long_func *item) :Item_int_func(thd, item) {} - const Type_handler *type_handler() const - { - if (unsigned_flag) - return &type_handler_ulong; - return &type_handler_slong; - } - bool fix_length_and_dec() { max_length= 11; return FALSE; } -}; - - -class Item_func_hash: public Item_int_func -{ -public: - Item_func_hash(THD *thd, List &item): Item_int_func(thd, item) - {} - longlong val_int(); - bool fix_length_and_dec(); - const Type_handler *type_handler() const { return &type_handler_slong; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - const char *func_name() const { return ""; } -}; - -class Item_longlong_func: public Item_int_func -{ -public: - Item_longlong_func(THD *thd): Item_int_func(thd) { } - Item_longlong_func(THD *thd, Item *a): Item_int_func(thd, a) {} - Item_longlong_func(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} - Item_longlong_func(THD *thd, Item *a, Item *b, Item *c): Item_int_func(thd, a, b, c) {} - Item_longlong_func(THD *thd, Item *a, Item *b, Item *c, Item *d): - Item_int_func(thd, a, b, c, d) {} - Item_longlong_func(THD *thd, List &list): Item_int_func(thd, list) { } - Item_longlong_func(THD *thd, Item_longlong_func *item) :Item_int_func(thd, item) {} - const Type_handler *type_handler() const - { - if (unsigned_flag) - return &type_handler_ulonglong; - return &type_handler_slonglong; - } -}; - - -class Cursor_ref -{ -protected: - LEX_CSTRING m_cursor_name; - uint m_cursor_offset; - class sp_cursor *get_open_cursor_or_error(); - Cursor_ref(const LEX_CSTRING *name, uint offset) - :m_cursor_name(*name), m_cursor_offset(offset) - { } - void print_func(String *str, const char *func_name); -}; - - - -class Item_func_cursor_rowcount: public Item_longlong_func, - public Cursor_ref -{ -public: - Item_func_cursor_rowcount(THD *thd, const LEX_CSTRING *name, uint offset) - :Item_longlong_func(thd), Cursor_ref(name, offset) { maybe_null= true; } - const char *func_name() const { return "%ROWCOUNT"; } - longlong val_int(); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), arg, VCOL_SESSION_FUNC); - } - void print(String *str, enum_query_type query_type) - { - return Cursor_ref::print_func(str, func_name()); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - - -class Item_func_connection_id :public Item_long_func -{ - longlong value; - -public: - Item_func_connection_id(THD *thd): Item_long_func(thd) { unsigned_flag=1; } - const char *func_name() const { return "connection_id"; } - bool fix_length_and_dec(); - bool fix_fields(THD *thd, Item **ref); - longlong val_int() { DBUG_ASSERT(fixed == 1); return value; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_signed :public Item_int_func -{ -public: - Item_func_signed(THD *thd, Item *a): Item_int_func(thd, a) - { - unsigned_flag= 0; - } - const char *func_name() const { return "cast_as_signed"; } - const Type_handler *type_handler() const - { - return Type_handler::type_handler_long_or_longlong(max_char_length(), - false); - } - longlong val_int() - { - longlong value= args[0]->val_int_signed_typecast(); - null_value= args[0]->null_value; - return value; - } - void fix_length_and_dec_double() - { - fix_char_length(MAX_BIGINT_WIDTH); - } - void fix_length_and_dec_generic() - { - uint32 char_length= MY_MIN(args[0]->max_char_length(), - MY_INT64_NUM_DECIMAL_DIGITS); - /* - args[0]->max_char_length() can return 0. - Reserve max_length to fit at least one character for one digit, - plus one character for the sign (if signed). - */ - set_if_bigger(char_length, 1U + (unsigned_flag ? 0 : 1)); - fix_char_length(char_length); - } - void fix_length_and_dec_string() - { - /* - For strings, use decimal_int_part() instead of max_char_length(). - This is important for Item_hex_hybrid: - SELECT CAST(0x1FFFFFFFF AS SIGNED); - Length is 5, decimal_int_part() is 13. - */ - uint32 char_length= MY_MIN(args[0]->decimal_int_part(), - MY_INT64_NUM_DECIMAL_DIGITS); - set_if_bigger(char_length, 1U + (unsigned_flag ? 0 : 1)); - fix_char_length(char_length); - } - bool fix_length_and_dec() - { - return args[0]->type_handler()->Item_func_signed_fix_length_and_dec(this); - } - virtual void print(String *str, enum_query_type query_type); - uint decimal_precision() const { return args[0]->decimal_precision(); } - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_unsigned :public Item_func_signed -{ -public: - Item_func_unsigned(THD *thd, Item *a): Item_func_signed(thd, a) - { - unsigned_flag= 1; - } - const char *func_name() const { return "cast_as_unsigned"; } - const Type_handler *type_handler() const - { - if (max_char_length() <= MY_INT32_NUM_DECIMAL_DIGITS - 1) - return &type_handler_ulong; - return &type_handler_ulonglong; - } - longlong val_int() - { - longlong value= args[0]->val_int_unsigned_typecast(); - null_value= args[0]->null_value; - return value; - } - bool fix_length_and_dec() - { - return args[0]->type_handler()->Item_func_unsigned_fix_length_and_dec(this); - } - uint decimal_precision() const { return max_length; } - virtual void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_decimal_typecast :public Item_func -{ - my_decimal decimal_value; -public: - Item_decimal_typecast(THD *thd, Item *a, uint len, uint dec) - :Item_func(thd, a) - { - decimals= (uint8) dec; - collation= DTCollation_numeric(); - fix_char_length(my_decimal_precision_to_length_no_truncation(len, dec, - unsigned_flag)); - } - String *val_str(String *str) { return VDec(this).to_string(str); } - double val_real() { return VDec(this).to_double(); } - longlong val_int() { return VDec(this).to_longlong(unsigned_flag); } - my_decimal *val_decimal(my_decimal*); - bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) - { - return decimal_to_datetime_with_warn(thd, VDec(this).ptr(), to, mode, - NULL, NULL); - } - const Type_handler *type_handler() const { return &type_handler_newdecimal; } - void fix_length_and_dec_generic() {} - bool fix_length_and_dec() - { - return - args[0]->type_handler()->Item_decimal_typecast_fix_length_and_dec(this); - } - const char *func_name() const { return "decimal_typecast"; } - virtual void print(String *str, enum_query_type query_type); - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_real_typecast: public Item_real_func -{ -protected: - double val_real_with_truncate(double max_value); -public: - Item_real_typecast(THD *thd, Item *a, uint len, uint dec) - :Item_real_func(thd, a) - { - decimals= (uint8) dec; - max_length= (uint32) len; - } - bool need_parentheses_in_default() { return true; } - void print(String *str, enum_query_type query_type); - void fix_length_and_dec_generic() { maybe_null= 1; } -}; - - -class Item_float_typecast :public Item_real_typecast -{ -public: - Item_float_typecast(THD *thd, Item *a) - :Item_real_typecast(thd, a, MAX_FLOAT_STR_LENGTH, NOT_FIXED_DEC) - { } - const Type_handler *type_handler() const { return &type_handler_float; } - bool fix_length_and_dec() - { - return - args[0]->type_handler()->Item_float_typecast_fix_length_and_dec(this); - } - const char *func_name() const { return "float_typecast"; } - double val_real() - { - return (double) (float) val_real_with_truncate(FLT_MAX); - } - String *val_str(String*str) - { - Float nr(Item_float_typecast::val_real()); - if (null_value) - return 0; - nr.to_string(str, decimals); - return str; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_double_typecast :public Item_real_typecast -{ -public: - Item_double_typecast(THD *thd, Item *a, uint len, uint dec): - Item_real_typecast(thd, a, len, dec) - { } - bool fix_length_and_dec() - { - return - args[0]->type_handler()->Item_double_typecast_fix_length_and_dec(this); - } - const char *func_name() const { return "double_typecast"; } - double val_real() { return val_real_with_truncate(DBL_MAX); } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_additive_op :public Item_num_op -{ -public: - Item_func_additive_op(THD *thd, Item *a, Item *b): Item_num_op(thd, a, b) {} - void result_precision(); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} -}; - - -class Item_func_plus :public Item_func_additive_op -{ -public: - Item_func_plus(THD *thd, Item *a, Item *b): - Item_func_additive_op(thd, a, b) {} - const char *func_name() const { return "+"; } - enum precedence precedence() const { return ADD_PRECEDENCE; } - bool fix_length_and_dec(); - longlong int_op(); - double real_op(); - my_decimal *decimal_op(my_decimal *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_minus :public Item_func_additive_op -{ - bool m_depends_on_sql_mode_no_unsigned_subtraction; -public: - Item_func_minus(THD *thd, Item *a, Item *b): - Item_func_additive_op(thd, a, b), - m_depends_on_sql_mode_no_unsigned_subtraction(false) - { } - const char *func_name() const { return "-"; } - enum precedence precedence() const { return ADD_PRECEDENCE; } - Sql_mode_dependency value_depends_on_sql_mode() const; - longlong int_op(); - double real_op(); - my_decimal *decimal_op(my_decimal *); - bool fix_length_and_dec(); - void fix_unsigned_flag(); - void fix_length_and_dec_double() - { - Item_func_additive_op::fix_length_and_dec_double(); - fix_unsigned_flag(); - } - void fix_length_and_dec_decimal() - { - Item_func_additive_op::fix_length_and_dec_decimal(); - fix_unsigned_flag(); - } - void fix_length_and_dec_int() - { - Item_func_additive_op::fix_length_and_dec_int(); - fix_unsigned_flag(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_mul :public Item_num_op -{ -public: - Item_func_mul(THD *thd, Item *a, Item *b): - Item_num_op(thd, a, b) {} - const char *func_name() const { return "*"; } - enum precedence precedence() const { return MUL_PRECEDENCE; } - longlong int_op(); - double real_op(); - my_decimal *decimal_op(my_decimal *); - void result_precision(); - bool fix_length_and_dec(); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_div :public Item_num_op -{ -public: - uint prec_increment; - Item_func_div(THD *thd, Item *a, Item *b): Item_num_op(thd, a, b) {} - longlong int_op() { DBUG_ASSERT(0); return 0; } - double real_op(); - my_decimal *decimal_op(my_decimal *); - const char *func_name() const { return "/"; } - enum precedence precedence() const { return MUL_PRECEDENCE; } - bool fix_length_and_dec(); - void fix_length_and_dec_double(); - void fix_length_and_dec_int(); - void result_precision(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_int_div :public Item_int_func -{ -public: - Item_func_int_div(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) - {} - longlong val_int(); - const char *func_name() const { return "DIV"; } - enum precedence precedence() const { return MUL_PRECEDENCE; } - const Type_handler *type_handler() const - { return type_handler_long_or_longlong(); } - bool fix_length_and_dec(); - void print(String *str, enum_query_type query_type) - { - print_op(str, query_type); - } - - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_mod :public Item_num_op -{ -public: - Item_func_mod(THD *thd, Item *a, Item *b): Item_num_op(thd, a, b) {} - longlong int_op(); - double real_op(); - my_decimal *decimal_op(my_decimal *); - const char *func_name() const { return "MOD"; } - enum precedence precedence() const { return MUL_PRECEDENCE; } - void result_precision(); - bool fix_length_and_dec(); - void fix_length_and_dec_double() - { - Item_num_op::fix_length_and_dec_double(); - unsigned_flag= args[0]->unsigned_flag; - } - void fix_length_and_dec_decimal() - { - result_precision(); - fix_decimals(); - } - void fix_length_and_dec_int() - { - result_precision(); - DBUG_ASSERT(decimals == 0); - set_handler(type_handler_long_or_longlong()); - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_neg :public Item_func_num1 -{ -public: - Item_func_neg(THD *thd, Item *a): Item_func_num1(thd, a) {} - double real_op(); - longlong int_op(); - my_decimal *decimal_op(my_decimal *); - const char *func_name() const { return "-"; } - enum Functype functype() const { return NEG_FUNC; } - enum precedence precedence() const { return NEG_PRECEDENCE; } - void print(String *str, enum_query_type query_type) - { - str->append(func_name()); - args[0]->print_parenthesised(str, query_type, precedence()); - } - void fix_length_and_dec_int(); - void fix_length_and_dec_double(); - void fix_length_and_dec_decimal(); - bool fix_length_and_dec(); - uint decimal_precision() const { return args[0]->decimal_precision(); } - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_abs :public Item_func_num1 -{ -public: - Item_func_abs(THD *thd, Item *a): Item_func_num1(thd, a) {} - double real_op(); - longlong int_op(); - my_decimal *decimal_op(my_decimal *); - const char *func_name() const { return "abs"; } - void fix_length_and_dec_int(); - void fix_length_and_dec_double(); - void fix_length_and_dec_decimal(); - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -// A class to handle logarithmic and trigonometric functions - -class Item_dec_func :public Item_real_func -{ - bool check_arguments() const - { return check_argument_types_can_return_real(0, arg_count); } - public: - Item_dec_func(THD *thd, Item *a): Item_real_func(thd, a) {} - Item_dec_func(THD *thd, Item *a, Item *b): Item_real_func(thd, a, b) {} - bool fix_length_and_dec() - { - decimals=NOT_FIXED_DEC; max_length=float_length(decimals); - maybe_null=1; - return FALSE; - } -}; - -class Item_func_exp :public Item_dec_func -{ -public: - Item_func_exp(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "exp"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_ln :public Item_dec_func -{ -public: - Item_func_ln(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "ln"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_log :public Item_dec_func -{ -public: - Item_func_log(THD *thd, Item *a): Item_dec_func(thd, a) {} - Item_func_log(THD *thd, Item *a, Item *b): Item_dec_func(thd, a, b) {} - double val_real(); - const char *func_name() const { return "log"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_log2 :public Item_dec_func -{ -public: - Item_func_log2(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "log2"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_log10 :public Item_dec_func -{ -public: - Item_func_log10(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "log10"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_sqrt :public Item_dec_func -{ -public: - Item_func_sqrt(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "sqrt"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_pow :public Item_dec_func -{ -public: - Item_func_pow(THD *thd, Item *a, Item *b): Item_dec_func(thd, a, b) {} - double val_real(); - const char *func_name() const { return "pow"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_acos :public Item_dec_func -{ -public: - Item_func_acos(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "acos"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_asin :public Item_dec_func -{ -public: - Item_func_asin(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "asin"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_atan :public Item_dec_func -{ -public: - Item_func_atan(THD *thd, Item *a): Item_dec_func(thd, a) {} - Item_func_atan(THD *thd, Item *a, Item *b): Item_dec_func(thd, a, b) {} - double val_real(); - const char *func_name() const { return "atan"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_cos :public Item_dec_func -{ -public: - Item_func_cos(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "cos"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_sin :public Item_dec_func -{ -public: - Item_func_sin(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "sin"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_tan :public Item_dec_func -{ -public: - Item_func_tan(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "tan"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_cot :public Item_dec_func -{ -public: - Item_func_cot(THD *thd, Item *a): Item_dec_func(thd, a) {} - double val_real(); - const char *func_name() const { return "cot"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_int_val :public Item_func_hybrid_field_type -{ -public: - Item_func_int_val(THD *thd, Item *a): Item_func_hybrid_field_type(thd, a) {} - bool check_partition_func_processor(void *int_arg) { return FALSE; } - bool check_vcol_func_processor(void *arg) { return FALSE; } - virtual decimal_round_mode round_mode() const= 0; - void fix_length_and_dec_double(); - void fix_length_and_dec_int_or_decimal(); - void fix_length_and_dec_time() - { - fix_attributes_time(0); - set_handler(&type_handler_time2); - } - void fix_length_and_dec_datetime() - { - fix_attributes_datetime(0); - set_handler(&type_handler_datetime2); - maybe_null= true; // E.g. CEILING(TIMESTAMP'0000-01-01 23:59:59.9') - } - bool fix_length_and_dec(); - String *str_op(String *str) { DBUG_ASSERT(0); return 0; } - bool native_op(THD *thd, Native *to) - { - DBUG_ASSERT(0); - return true; - } -}; - - -class Item_func_ceiling :public Item_func_int_val -{ -public: - Item_func_ceiling(THD *thd, Item *a): Item_func_int_val(thd, a) {} - const char *func_name() const { return "ceiling"; } - decimal_round_mode round_mode() const { return CEILING; } - longlong int_op(); - double real_op(); - my_decimal *decimal_op(my_decimal *); - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool time_op(THD *thd, MYSQL_TIME *ltime); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_floor :public Item_func_int_val -{ -public: - Item_func_floor(THD *thd, Item *a): Item_func_int_val(thd, a) {} - const char *func_name() const { return "floor"; } - decimal_round_mode round_mode() const { return FLOOR; } - longlong int_op(); - double real_op(); - my_decimal *decimal_op(my_decimal *); - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool time_op(THD *thd, MYSQL_TIME *ltime); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* This handles round and truncate */ - -class Item_func_round :public Item_func_hybrid_field_type -{ - bool truncate; - void fix_length_and_dec_decimal(uint decimals_to_set); - void fix_length_and_dec_double(uint decimals_to_set); - bool test_if_length_can_increase(); -public: - Item_func_round(THD *thd, Item *a, Item *b, bool trunc_arg) - :Item_func_hybrid_field_type(thd, a, b), truncate(trunc_arg) {} - const char *func_name() const { return truncate ? "truncate" : "round"; } - double real_op(); - longlong int_op(); - my_decimal *decimal_op(my_decimal *); - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool time_op(THD *thd, MYSQL_TIME *ltime); - bool native_op(THD *thd, Native *to) - { - DBUG_ASSERT(0); - return true; - } - String *str_op(String *str) - { - DBUG_ASSERT(0); - return NULL; - } - void fix_arg_decimal(); - void fix_arg_int(const Type_handler *preferred, - const Type_std_attributes *preferred_attributes, - bool use_decimal_on_length_increase); - void fix_arg_hex_hybrid(); - void fix_arg_double(); - void fix_arg_time(); - void fix_arg_datetime(); - void fix_arg_temporal(const Type_handler *h, uint int_part_length); - bool fix_length_and_dec() - { - /* - We don't want to translate ENUM/SET to CHAR here. - So let's real_type_handler(), not type_handler(). - */ - return args[0]->real_type_handler()->Item_func_round_fix_length_and_dec(this); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_rand :public Item_real_func -{ - struct my_rnd_struct *rand; - bool first_eval; // TRUE if val_real() is called 1st time - bool check_arguments() const - { return check_argument_types_can_return_int(0, arg_count); } -public: - Item_func_rand(THD *thd, Item *a): - Item_real_func(thd, a), rand(0), first_eval(TRUE) {} - Item_func_rand(THD *thd): Item_real_func(thd) {} - double val_real(); - const char *func_name() const { return "rand"; } - bool const_item() const { return 0; } - void update_used_tables(); - bool fix_fields(THD *thd, Item **ref); - void cleanup() { first_eval= TRUE; Item_real_func::cleanup(); } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_NON_DETERMINISTIC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -private: - void seed_random (Item * val); -}; - - -class Item_func_sign :public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_real(func_name()); } -public: - Item_func_sign(THD *thd, Item *a): Item_long_func(thd, a) {} - const char *func_name() const { return "sign"; } - uint decimal_precision() const { return 1; } - bool fix_length_and_dec() { fix_char_length(2); return FALSE; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_units :public Item_real_func -{ - char *name; - double mul,add; - bool check_arguments() const - { return check_argument_types_can_return_real(0, arg_count); } -public: - Item_func_units(THD *thd, char *name_arg, Item *a, double mul_arg, - double add_arg): - Item_real_func(thd, a), name(name_arg), mul(mul_arg), add(add_arg) {} - double val_real(); - const char *func_name() const { return name; } - bool fix_length_and_dec() - { - decimals= NOT_FIXED_DEC; - max_length= float_length(decimals); - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - Item_func_min_max does not derive from Item_func_hybrid_field_type - because the way how its methods val_xxx() and get_date() work depend - not only by its arguments, but also on the context in which - LEAST() and GREATEST() appear. - For example, using Item_func_min_max in a CAST like this: - CAST(LEAST('11','2') AS SIGNED) - forces Item_func_min_max to compare the arguments as numbers rather - than strings. - Perhaps this should be changed eventually (see MDEV-5893). -*/ -class Item_func_min_max :public Item_hybrid_func -{ - String tmp_value; - int cmp_sign; -protected: - bool check_arguments() const - { - return false; // Checked by aggregate_for_min_max() - } - bool fix_attributes(Item **item, uint nitems); -public: - Item_func_min_max(THD *thd, List &list, int cmp_sign_arg): - Item_hybrid_func(thd, list), cmp_sign(cmp_sign_arg) - {} - String *val_str_native(String *str); - double val_real_native(); - longlong val_int_native(); - my_decimal *val_decimal_native(my_decimal *); - bool get_date_native(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - bool get_time_native(THD *thd, MYSQL_TIME *res); - - double val_real() - { - DBUG_ASSERT(fixed); - return Item_func_min_max::type_handler()-> - Item_func_min_max_val_real(this); - } - longlong val_int() - { - DBUG_ASSERT(fixed); - return Item_func_min_max::type_handler()-> - Item_func_min_max_val_int(this); - } - String *val_str(String *str) - { - DBUG_ASSERT(fixed); - return Item_func_min_max::type_handler()-> - Item_func_min_max_val_str(this, str); - } - my_decimal *val_decimal(my_decimal *dec) - { - DBUG_ASSERT(fixed); - return Item_func_min_max::type_handler()-> - Item_func_min_max_val_decimal(this, dec); - } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) - { - DBUG_ASSERT(fixed); - return Item_func_min_max::type_handler()-> - Item_func_min_max_get_date(thd, this, res, fuzzydate); - } - bool val_native(THD *thd, Native *to); - void aggregate_attributes_real(Item **items, uint nitems) - { - /* - Aggregating attributes for the double data type for LEAST/GREATEST - is almost the same with aggregating for CASE-alike hybrid functions, - (CASE..THEN, COALESCE, IF, etc). - There is one notable difference though, when a numeric argument is mixed - with a string argument: - - CASE-alike functions return a string data type in such cases - COALESCE(10,'x') -> VARCHAR(2) = '10' - - LEAST/GREATEST returns double: - GREATEST(10,'10e4') -> DOUBLE = 100000 - As the string argument can represent a number in the scientific notation, - like in the example above, max_length of the result can be longer than - max_length of the arguments. To handle this properly, max_length is - additionally assigned to the result of float_length(decimals). - */ - Item_func::aggregate_attributes_real(items, nitems); - max_length= float_length(decimals); - } - bool fix_length_and_dec() - { - if (aggregate_for_min_max(func_name(), args, arg_count)) - return true; - fix_attributes(args, arg_count); - return false; - } -}; - -class Item_func_min :public Item_func_min_max -{ -public: - Item_func_min(THD *thd, List &list): Item_func_min_max(thd, list, 1) {} - const char *func_name() const { return "least"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_max :public Item_func_min_max -{ -public: - Item_func_max(THD *thd, List &list): Item_func_min_max(thd, list, -1) {} - const char *func_name() const { return "greatest"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - Objects of this class are used for ROLLUP queries to wrap up - each constant item referred to in GROUP BY list. -*/ - -class Item_func_rollup_const :public Item_func -{ -public: - Item_func_rollup_const(THD *thd, Item *a): Item_func(thd, a) - { - name= a->name; - } - double val_real() { return val_real_from_item(args[0]); } - longlong val_int() { return val_int_from_item(args[0]); } - String *val_str(String *str) { return val_str_from_item(args[0], str); } - bool val_native(THD *thd, Native *to) - { return val_native_from_item(thd, args[0], to); } - my_decimal *val_decimal(my_decimal *dec) - { return val_decimal_from_item(args[0], dec); } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_item(thd, args[0], ltime, fuzzydate); } - const char *func_name() const { return "rollup_const"; } - bool const_item() const { return 0; } - const Type_handler *type_handler() const { return args[0]->type_handler(); } - bool fix_length_and_dec() - { - Type_std_attributes::set(*args[0]); - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_long_func_length: public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_str(func_name()); } -public: - Item_long_func_length(THD *thd, Item *a): Item_long_func(thd, a) {} - bool fix_length_and_dec() { max_length=10; return FALSE; } -}; - - -class Item_func_octet_length :public Item_long_func_length -{ - String value; -public: - Item_func_octet_length(THD *thd, Item *a): Item_long_func_length(thd, a) {} - longlong val_int(); - const char *func_name() const { return "octet_length"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_bit_length :public Item_longlong_func -{ - String value; -public: - Item_func_bit_length(THD *thd, Item *a): Item_longlong_func(thd, a) {} - bool fix_length_and_dec() - { - max_length= 11; // 0x100000000*8 = 34,359,738,368 - return FALSE; - } - longlong val_int(); - const char *func_name() const { return "bit_length"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_char_length :public Item_long_func_length -{ - String value; -public: - Item_func_char_length(THD *thd, Item *a): Item_long_func_length(thd, a) {} - longlong val_int(); - const char *func_name() const { return "char_length"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_coercibility :public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_str(func_name()); } -public: - Item_func_coercibility(THD *thd, Item *a): Item_long_func(thd, a) {} - longlong val_int(); - const char *func_name() const { return "coercibility"; } - bool fix_length_and_dec() { max_length=10; maybe_null= 0; return FALSE; } - bool eval_not_null_tables(void *) - { - not_null_tables_cache= 0; - return false; - } - bool find_not_null_fields(table_map allowed) - { - return false; - } - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { return this; } - bool const_item() const { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - In the corner case LOCATE could return (4,294,967,296 + 1), - which would not fit into Item_long_func range. - But string lengths are limited with max_allowed_packet, - which cannot be bigger than 1024*1024*1024. -*/ -class Item_func_locate :public Item_long_func -{ - bool check_arguments() const - { - return check_argument_types_can_return_str(0, 2) || - (arg_count > 2 && args[2]->check_type_can_return_int(func_name())); - } - String value1,value2; - DTCollation cmp_collation; -public: - Item_func_locate(THD *thd, Item *a, Item *b) - :Item_long_func(thd, a, b) {} - Item_func_locate(THD *thd, Item *a, Item *b, Item *c) - :Item_long_func(thd, a, b, c) {} - const char *func_name() const { return "locate"; } - longlong val_int(); - bool fix_length_and_dec() - { - max_length= MY_INT32_NUM_DECIMAL_DIGITS; - return agg_arg_charsets_for_comparison(cmp_collation, args, 2); - } - virtual void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_field :public Item_long_func -{ - String value,tmp; - Item_result cmp_type; - DTCollation cmp_collation; -public: - Item_func_field(THD *thd, List &list): Item_long_func(thd, list) {} - longlong val_int(); - const char *func_name() const { return "field"; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_ascii :public Item_long_func -{ - bool check_arguments() const - { return check_argument_types_can_return_str(0, arg_count); } - String value; -public: - Item_func_ascii(THD *thd, Item *a): Item_long_func(thd, a) {} - longlong val_int(); - const char *func_name() const { return "ascii"; } - bool fix_length_and_dec() { max_length=3; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_ord :public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_str(func_name()); } - String value; -public: - Item_func_ord(THD *thd, Item *a): Item_long_func(thd, a) {} - bool fix_length_and_dec() { fix_char_length(7); return FALSE; } - longlong val_int(); - const char *func_name() const { return "ord"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_find_in_set :public Item_long_func -{ - bool check_arguments() const - { return check_argument_types_can_return_str(0, 2); } - String value,value2; - uint enum_value; - ulonglong enum_bit; - DTCollation cmp_collation; -public: - Item_func_find_in_set(THD *thd, Item *a, Item *b): - Item_long_func(thd, a, b), enum_value(0) {} - longlong val_int(); - const char *func_name() const { return "find_in_set"; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* Base class for all bit functions: '~', '|', '^', '&', '>>', '<<' */ - -class Item_func_bit_operator: public Item_handled_func -{ - bool check_arguments() const - { return check_argument_types_can_return_int(0, arg_count); } -protected: - bool fix_length_and_dec_op1_std(const Handler *ha_int, const Handler *ha_dec) - { - set_func_handler(args[0]->cmp_type() == INT_RESULT ? ha_int : ha_dec); - return m_func_handler->fix_length_and_dec(this); - } - bool fix_length_and_dec_op2_std(const Handler *ha_int, const Handler *ha_dec) - { - set_func_handler(args[0]->cmp_type() == INT_RESULT && - args[1]->cmp_type() == INT_RESULT ? ha_int : ha_dec); - return m_func_handler->fix_length_and_dec(this); - } -public: - Item_func_bit_operator(THD *thd, Item *a) - :Item_handled_func(thd, a) {} - Item_func_bit_operator(THD *thd, Item *a, Item *b) - :Item_handled_func(thd, a, b) {} - void print(String *str, enum_query_type query_type) - { - print_op(str, query_type); - } - bool need_parentheses_in_default() { return true; } -}; - -class Item_func_bit_or :public Item_func_bit_operator -{ -public: - Item_func_bit_or(THD *thd, Item *a, Item *b) - :Item_func_bit_operator(thd, a, b) {} - bool fix_length_and_dec(); - const char *func_name() const { return "|"; } - enum precedence precedence() const { return BITOR_PRECEDENCE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_bit_and :public Item_func_bit_operator -{ -public: - Item_func_bit_and(THD *thd, Item *a, Item *b) - :Item_func_bit_operator(thd, a, b) {} - bool fix_length_and_dec(); - const char *func_name() const { return "&"; } - enum precedence precedence() const { return BITAND_PRECEDENCE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_bit_count :public Item_handled_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_int(func_name()); } -public: - Item_func_bit_count(THD *thd, Item *a): Item_handled_func(thd, a) {} - const char *func_name() const { return "bit_count"; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_shift_left :public Item_func_bit_operator -{ -public: - Item_func_shift_left(THD *thd, Item *a, Item *b) - :Item_func_bit_operator(thd, a, b) {} - bool fix_length_and_dec(); - const char *func_name() const { return "<<"; } - enum precedence precedence() const { return SHIFT_PRECEDENCE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_shift_right :public Item_func_bit_operator -{ -public: - Item_func_shift_right(THD *thd, Item *a, Item *b) - :Item_func_bit_operator(thd, a, b) {} - bool fix_length_and_dec(); - const char *func_name() const { return ">>"; } - enum precedence precedence() const { return SHIFT_PRECEDENCE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_bit_neg :public Item_func_bit_operator -{ -public: - Item_func_bit_neg(THD *thd, Item *a): Item_func_bit_operator(thd, a) {} - bool fix_length_and_dec(); - const char *func_name() const { return "~"; } - enum precedence precedence() const { return NEG_PRECEDENCE; } - void print(String *str, enum_query_type query_type) - { - str->append(func_name()); - args[0]->print_parenthesised(str, query_type, precedence()); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_last_insert_id :public Item_longlong_func -{ - bool check_arguments() const - { return check_argument_types_can_return_int(0, arg_count); } -public: - Item_func_last_insert_id(THD *thd): Item_longlong_func(thd) {} - Item_func_last_insert_id(THD *thd, Item *a): Item_longlong_func(thd, a) {} - longlong val_int(); - const char *func_name() const { return "last_insert_id"; } - bool fix_length_and_dec() - { - unsigned_flag= true; - if (arg_count) - max_length= args[0]->max_length; - return FALSE; - } - bool fix_fields(THD *thd, Item **ref); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_benchmark :public Item_long_func -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_int(func_name()) || - args[1]->check_type_scalar(func_name()); - } -public: - Item_func_benchmark(THD *thd, Item *count_expr, Item *expr): - Item_long_func(thd, count_expr, expr) - {} - longlong val_int(); - const char *func_name() const { return "benchmark"; } - bool fix_length_and_dec() { max_length=1; maybe_null=0; return FALSE; } - virtual void print(String *str, enum_query_type query_type); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -void item_func_sleep_init(void); -void item_func_sleep_free(void); - -class Item_func_sleep :public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_real(func_name()); } -public: - Item_func_sleep(THD *thd, Item *a): Item_long_func(thd, a) {} - bool fix_length_and_dec() { fix_char_length(1); return FALSE; } - bool const_item() const { return 0; } - const char *func_name() const { return "sleep"; } - table_map used_tables() const - { - return used_tables_cache | RAND_TABLE_BIT; - } - bool is_expensive() { return 1; } - longlong val_int(); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - - -#ifdef HAVE_DLOPEN - -class Item_udf_func :public Item_func -{ - /** - Mark "this" as non-deterministic if it uses no tables - and is not a constant at the same time. - */ - void set_non_deterministic_if_needed() - { - if (!const_item_cache && !used_tables_cache) - used_tables_cache= RAND_TABLE_BIT; - } -protected: - udf_handler udf; - bool is_expensive_processor(void *arg) { return TRUE; } - - class VDec_udf: public Dec_ptr_and_buffer - { - public: - VDec_udf(Item_udf_func *func, udf_handler *udf) - { - my_bool tmp_null_value; - m_ptr= udf->val_decimal(&tmp_null_value, &m_buffer); - DBUG_ASSERT(is_null() == (tmp_null_value != 0)); - func->null_value= is_null(); - } - }; - -public: - Item_udf_func(THD *thd, udf_func *udf_arg): - Item_func(thd), udf(udf_arg) {} - Item_udf_func(THD *thd, udf_func *udf_arg, List &list): - Item_func(thd, list), udf(udf_arg) {} - const char *func_name() const { return udf.name(); } - enum Functype functype() const { return UDF_FUNC; } - bool fix_fields(THD *thd, Item **ref) - { - DBUG_ASSERT(fixed == 0); - bool res= udf.fix_fields(thd, this, arg_count, args); - set_non_deterministic_if_needed(); - fixed= 1; - return res; - } - void fix_num_length_and_dec(); - void update_used_tables() - { - /* - TODO: Make a member in UDF_INIT and return if a UDF is deterministic or - not. - Currently UDF_INIT has a member (const_item) that is an in/out - parameter to the init() call. - The code in udf_handler::fix_fields also duplicates the arguments - handling code in Item_func::fix_fields(). - - The lack of information if a UDF is deterministic makes writing - a correct update_used_tables() for UDFs impossible. - One solution to this would be : - - Add a is_deterministic member of UDF_INIT - - (optionally) deprecate the const_item member of UDF_INIT - - Take away the duplicate code from udf_handler::fix_fields() and - make Item_udf_func call Item_func::fix_fields() to process its - arguments as for any other function. - - Store the deterministic flag returned by _init into the - udf_handler. - - Don't implement Item_udf_func::fix_fields, implement - Item_udf_func::fix_length_and_dec() instead (similar to non-UDF - functions). - - Override Item_func::update_used_tables to call - Item_func::update_used_tables() and add a RAND_TABLE_BIT to the - result of Item_func::update_used_tables() if the UDF is - non-deterministic. - - (optionally) rename RAND_TABLE_BIT to NONDETERMINISTIC_BIT to - better describe its usage. - - The above would require a change of the UDF API. - Until that change is done here's how the current code works: - We call Item_func::update_used_tables() only when we know that - the function depends on real non-const tables and is deterministic. - This can be done only because we know that the optimizer will - call update_used_tables() only when there's possibly a new const - table. So update_used_tables() can only make a Item_func more - constant than it is currently. - That's why we don't need to do anything if a function is guaranteed - to return non-constant (it's non-deterministic) or is already a - const. - */ - if ((used_tables_cache & ~PSEUDO_TABLE_BITS) && - !(used_tables_cache & RAND_TABLE_BIT)) - { - Item_func::update_used_tables(); - set_non_deterministic_if_needed(); - } - } - void cleanup(); - bool eval_not_null_tables(void *opt_arg) - { - not_null_tables_cache= 0; - return 0; - } - bool find_not_null_fields(table_map allowed) - { - return false; - } - bool is_expensive() { return 1; } - virtual void print(String *str, enum_query_type query_type); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_NON_DETERMINISTIC); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } - bool excl_dep_on_grouping_fields(st_select_lex *sel) - { return false; } -}; - - -class Item_func_udf_float :public Item_udf_func -{ - public: - Item_func_udf_float(THD *thd, udf_func *udf_arg): - Item_udf_func(thd, udf_arg) {} - Item_func_udf_float(THD *thd, udf_func *udf_arg, - List &list): - Item_udf_func(thd, udf_arg, list) {} - longlong val_int() - { - DBUG_ASSERT(fixed == 1); - return Converter_double_to_longlong(Item_func_udf_float::val_real(), - unsigned_flag).result(); - } - my_decimal *val_decimal(my_decimal *dec_buf) - { - double res=val_real(); - if (null_value) - return NULL; - double2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf); - return dec_buf; - } - double val_real(); - String *val_str(String *str); - const Type_handler *type_handler() const { return &type_handler_double; } - bool fix_length_and_dec() { fix_num_length_and_dec(); return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_udf_int :public Item_udf_func -{ -public: - Item_func_udf_int(THD *thd, udf_func *udf_arg): - Item_udf_func(thd, udf_arg) {} - Item_func_udf_int(THD *thd, udf_func *udf_arg, - List &list): - Item_udf_func(thd, udf_arg, list) {} - longlong val_int(); - double val_real() { return (double) Item_func_udf_int::val_int(); } - my_decimal *val_decimal(my_decimal *decimal_value) - { - return val_decimal_from_int(decimal_value); - } - String *val_str(String *str); - const Type_handler *type_handler() const - { - if (unsigned_flag) - return &type_handler_ulonglong; - return &type_handler_slonglong; - } - bool fix_length_and_dec() { decimals= 0; max_length= 21; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_udf_decimal :public Item_udf_func -{ -public: - Item_func_udf_decimal(THD *thd, udf_func *udf_arg): - Item_udf_func(thd, udf_arg) {} - Item_func_udf_decimal(THD *thd, udf_func *udf_arg, List &list): - Item_udf_func(thd, udf_arg, list) {} - longlong val_int() - { - return VDec_udf(this, &udf).to_longlong(unsigned_flag); - } - double val_real() - { - return VDec_udf(this, &udf).to_double(); - } - my_decimal *val_decimal(my_decimal *); - String *val_str(String *str) - { - return VDec_udf(this, &udf).to_string_round(str, decimals); - } - const Type_handler *type_handler() const { return &type_handler_newdecimal; } - bool fix_length_and_dec() { fix_num_length_and_dec(); return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_udf_str :public Item_udf_func -{ -public: - Item_func_udf_str(THD *thd, udf_func *udf_arg): - Item_udf_func(thd, udf_arg) {} - Item_func_udf_str(THD *thd, udf_func *udf_arg, List &list): - Item_udf_func(thd, udf_arg, list) {} - String *val_str(String *); - double val_real() - { - int err_not_used; - char *end_not_used; - String *res; - res= val_str(&str_value); - return res ? res->charset()->strntod((char*) res->ptr(), res->length(), - &end_not_used, &err_not_used) : 0.0; - } - longlong val_int() - { - int err_not_used; - String *res; res=val_str(&str_value); - return res ? res->charset()->strntoll(res->ptr(),res->length(),10, - (char**) 0, &err_not_used) : (longlong) 0; - } - my_decimal *val_decimal(my_decimal *dec_buf) - { - String *res=val_str(&str_value); - if (!res) - return NULL; - string2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf); - return dec_buf; - } - const Type_handler *type_handler() const { return string_type_handler(); } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -#else /* Dummy functions to get sql_yacc.cc compiled */ - -class Item_func_udf_float :public Item_real_func -{ - public: - Item_func_udf_float(THD *thd, udf_func *udf_arg): - Item_real_func(thd) {} - Item_func_udf_float(THD *thd, udf_func *udf_arg, List &list): - Item_real_func(thd, list) {} - double val_real() { DBUG_ASSERT(fixed == 1); return 0.0; } -}; - - -class Item_func_udf_int :public Item_int_func -{ -public: - Item_func_udf_int(THD *thd, udf_func *udf_arg): - Item_int_func(thd) {} - Item_func_udf_int(THD *thd, udf_func *udf_arg, List &list): - Item_int_func(thd, list) {} - const Type_handler *type_handler() const { return &type_handler_slonglong; } - longlong val_int() { DBUG_ASSERT(fixed == 1); return 0; } -}; - - -class Item_func_udf_decimal :public Item_int_func -{ -public: - Item_func_udf_decimal(THD *thd, udf_func *udf_arg): - Item_int_func(thd) {} - Item_func_udf_decimal(THD *thd, udf_func *udf_arg, List &list): - Item_int_func(thd, list) {} - const Type_handler *type_handler() const { return &type_handler_slonglong; } - my_decimal *val_decimal(my_decimal *) { DBUG_ASSERT(fixed == 1); return 0; } -}; - - -class Item_func_udf_str :public Item_func -{ -public: - Item_func_udf_str(THD *thd, udf_func *udf_arg): - Item_func(thd) {} - Item_func_udf_str(THD *thd, udf_func *udf_arg, List &list): - Item_func(thd, list) {} - String *val_str(String *) - { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } - double val_real() { DBUG_ASSERT(fixed == 1); null_value= 1; return 0.0; } - longlong val_int() { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } - bool fix_length_and_dec() { maybe_null=1; max_length=0; return FALSE; } -}; - -#endif /* HAVE_DLOPEN */ - -void mysql_ull_cleanup(THD *thd); -void mysql_ull_set_explicit_lock_duration(THD *thd); - - -class Item_func_lock :public Item_long_func -{ - public: - Item_func_lock(THD *thd): Item_long_func(thd) { } - Item_func_lock(THD *thd, Item *a): Item_long_func(thd, a) {} - Item_func_lock(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} - table_map used_tables() const - { - return used_tables_cache | RAND_TABLE_BIT; - } - bool const_item() const { return 0; } - bool is_expensive() { return 1; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } -}; - - -class Item_func_get_lock final :public Item_func_lock -{ - bool check_arguments() const - { - return args[0]->check_type_general_purpose_string(func_name()) || - args[1]->check_type_can_return_real(func_name()); - } - String value; - public: - Item_func_get_lock(THD *thd, Item *a, Item *b) :Item_func_lock(thd, a, b) {} - longlong val_int() final; - const char *func_name() const final { return "get_lock"; } - bool fix_length_and_dec() { max_length= 1; maybe_null= 1; return FALSE; } - Item *get_copy(THD *thd) final - { return get_item_copy(thd, this); } -}; - - -class Item_func_release_all_locks final :public Item_func_lock -{ -public: - Item_func_release_all_locks(THD *thd): Item_func_lock(thd) - { unsigned_flag= 1; } - longlong val_int() final; - const char *func_name() const final { return "release_all_locks"; } - Item *get_copy(THD *thd) final - { return get_item_copy(thd, this); } -}; - - -class Item_func_release_lock final :public Item_func_lock -{ - bool check_arguments() const - { return args[0]->check_type_general_purpose_string(func_name()); } - String value; -public: - Item_func_release_lock(THD *thd, Item *a): Item_func_lock(thd, a) {} - longlong val_int() final; - const char *func_name() const { return "release_lock"; } - bool fix_length_and_dec() { max_length= 1; maybe_null= 1; return FALSE; } - Item *get_copy(THD *thd) final - { return get_item_copy(thd, this); } -}; - - -/* replication functions */ - -class Item_master_pos_wait :public Item_longlong_func -{ - bool check_arguments() const - { - return - args[0]->check_type_general_purpose_string(func_name()) || - args[1]->check_type_can_return_int(func_name()) || - (arg_count > 2 && args[2]->check_type_can_return_int(func_name())) || - (arg_count > 3 && args[3]->check_type_general_purpose_string(func_name())); - } - String value; -public: - Item_master_pos_wait(THD *thd, Item *a, Item *b) - :Item_longlong_func(thd, a, b) {} - Item_master_pos_wait(THD *thd, Item *a, Item *b, Item *c): - Item_longlong_func(thd, a, b, c) {} - Item_master_pos_wait(THD *thd, Item *a, Item *b, Item *c, Item *d): - Item_longlong_func(thd, a, b, c, d) {} - longlong val_int(); - const char *func_name() const { return "master_pos_wait"; } - bool fix_length_and_dec() { max_length=21; maybe_null=1; return FALSE; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_master_gtid_wait :public Item_long_func -{ - bool check_arguments() const - { - return args[0]->check_type_general_purpose_string(func_name()) || - (arg_count > 1 && args[1]->check_type_can_return_real(func_name())); - } - String value; -public: - Item_master_gtid_wait(THD *thd, Item *a) - :Item_long_func(thd, a) {} - Item_master_gtid_wait(THD *thd, Item *a, Item *b) - :Item_long_func(thd, a, b) {} - longlong val_int(); - const char *func_name() const { return "master_gtid_wait"; } - bool fix_length_and_dec() { max_length=2; return FALSE; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* Handling of user definable variables */ - -class user_var_entry; - - -/** - A class to set and get user variables -*/ -class Item_func_user_var :public Item_hybrid_func -{ -protected: - user_var_entry *m_var_entry; -public: - LEX_CSTRING name; // keep it public - Item_func_user_var(THD *thd, const LEX_CSTRING *a) - :Item_hybrid_func(thd), m_var_entry(NULL), name(*a) { } - Item_func_user_var(THD *thd, const LEX_CSTRING *a, Item *b) - :Item_hybrid_func(thd, b), m_var_entry(NULL), name(*a) { } - Item_func_user_var(THD *thd, Item_func_user_var *item) - :Item_hybrid_func(thd, item), - m_var_entry(item->m_var_entry), name(item->name) { } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - DBUG_ASSERT(fixed); - return create_tmp_field_ex_from_handler(root, table, src, param, - type_handler()); - } - Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) - { return create_table_field_from_handler(root, table); } - bool check_vcol_func_processor(void *arg); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } -}; - - -class Item_func_set_user_var :public Item_func_user_var -{ - /* - The entry_thread_id variable is used: - 1) to skip unnecessary updates of the entry field (see above); - 2) to reset the entry field that was initialized in the other thread - (for example, an item tree of a trigger that updates user variables - may be shared between several connections, and the entry_thread_id field - prevents updates of one connection user variables from a concurrent - connection calling the same trigger that initially updated some - user variable it the first connection context). - */ - my_thread_id entry_thread_id; - String value; - my_decimal decimal_buff; - bool null_item; - union - { - longlong vint; - double vreal; - String *vstr; - my_decimal *vdec; - } save_result; - -public: - Item_func_set_user_var(THD *thd, const LEX_CSTRING *a, Item *b): - Item_func_user_var(thd, a, b), - entry_thread_id(0) - {} - Item_func_set_user_var(THD *thd, Item_func_set_user_var *item) - :Item_func_user_var(thd, item), - entry_thread_id(item->entry_thread_id), - value(item->value), decimal_buff(item->decimal_buff), - null_item(item->null_item), save_result(item->save_result) - {} - - enum Functype functype() const { return SUSERVAR_FUNC; } - double val_real(); - longlong val_int(); - String *val_str(String *str); - my_decimal *val_decimal(my_decimal *); - double val_result(); - longlong val_int_result(); - bool val_bool_result(); - String *str_result(String *str); - my_decimal *val_decimal_result(my_decimal *); - bool is_null_result(); - bool update_hash(void *ptr, size_t length, enum Item_result type, - CHARSET_INFO *cs, bool unsigned_arg); - bool send(Protocol *protocol, st_value *buffer); - void make_send_field(THD *thd, Send_field *tmp_field); - bool check(bool use_result_field); - void save_item_result(Item *item); - bool update(); - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec(); - void print(String *str, enum_query_type query_type); - enum precedence precedence() const { return ASSIGN_PRECEDENCE; } - void print_as_stmt(String *str, enum_query_type query_type); - const char *func_name() const { return "set_user_var"; } - int save_in_field(Field *field, bool no_conversions, - bool can_use_result_field); - int save_in_field(Field *field, bool no_conversions) - { - return save_in_field(field, no_conversions, 1); - } - void save_org_in_field(Field *field, - fast_field_copier data __attribute__ ((__unused__))) - { (void)save_in_field(field, 1, 0); } - bool register_field_in_read_map(void *arg); - bool register_field_in_bitmap(void *arg); - bool set_entry(THD *thd, bool create_if_not_exists); - void cleanup(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - bool excl_dep_on_table(table_map tab_map) { return false; } -}; - - -class Item_func_get_user_var :public Item_func_user_var, - private Settable_routine_parameter -{ -public: - Item_func_get_user_var(THD *thd, const LEX_CSTRING *a): - Item_func_user_var(thd, a) {} - enum Functype functype() const { return GUSERVAR_FUNC; } - LEX_CSTRING get_name() { return name; } - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal*); - String *val_str(String* str); - bool fix_length_and_dec(); - virtual void print(String *str, enum_query_type query_type); - /* - We must always return variables as strings to guard against selects of type - select @t1:=1,@t1,@t:="hello",@t from foo where (@t1:= t2.b) - */ - const char *func_name() const { return "get_user_var"; } - bool const_item() const; - table_map used_tables() const - { return const_item() ? 0 : RAND_TABLE_BIT; } - bool eq(const Item *item, bool binary_cmp) const; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -private: - bool set_value(THD *thd, sp_rcontext *ctx, Item **it); - -public: - Settable_routine_parameter *get_settable_routine_parameter() - { - return this; - } -}; - - -/* - This item represents user variable used as out parameter (e.g in LOAD DATA), - and it is supposed to be used only for this purprose. So it is simplified - a lot. Actually you should never obtain its value. - - The only two reasons for this thing being an Item is possibility to store it - in List and desire to place this code somewhere near other functions - working with user variables. -*/ -class Item_user_var_as_out_param :public Item_fixed_hybrid, - public Load_data_outvar -{ - LEX_CSTRING org_name; - user_var_entry *entry; -public: - Item_user_var_as_out_param(THD *thd, const LEX_CSTRING *a) - :Item_fixed_hybrid(thd) - { - DBUG_ASSERT(a->length < UINT_MAX32); - org_name= *a; - set_name(thd, a->str, a->length, system_charset_info); - } - Load_data_outvar *get_load_data_outvar() - { - return this; - } - bool load_data_set_null(THD *thd, const Load_data_param *param) - { - set_null_value(param->charset()); - return false; - } - bool load_data_set_no_data(THD *thd, const Load_data_param *param) - { - set_null_value(param->charset()); - return false; - } - bool load_data_set_value(THD *thd, const char *pos, uint length, - const Load_data_param *param) - { - set_value(pos, length, param->charset()); - return false; - } - void load_data_print_for_log_event(THD *thd, String *to) const; - bool load_data_add_outvar(THD *thd, Load_data_param *param) const - { - return param->add_outvar_user_var(thd); - } - uint load_data_fixed_length() const - { - return 0; - } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - DBUG_ASSERT(0); - return NULL; - } - /* We should return something different from FIELD_ITEM here */ - enum Type type() const { return CONST_ITEM;} - double val_real(); - longlong val_int(); - String *val_str(String *str); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - my_decimal *val_decimal(my_decimal *decimal_buffer); - /* fix_fields() binds variable name with its entry structure */ - bool fix_fields(THD *thd, Item **ref); - void set_null_value(CHARSET_INFO* cs); - void set_value(const char *str, uint length, CHARSET_INFO* cs); - const Type_handler *type_handler() const { return &type_handler_double; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* A system variable */ - -#define GET_SYS_VAR_CACHE_LONG 1 -#define GET_SYS_VAR_CACHE_DOUBLE 2 -#define GET_SYS_VAR_CACHE_STRING 4 - -class Item_func_get_system_var :public Item_func -{ - sys_var *var; - enum_var_type var_type, orig_var_type; - LEX_CSTRING component; - longlong cached_llval; - double cached_dval; - String cached_strval; - bool cached_null_value; - query_id_t used_query_id; - uchar cache_present; - -public: - Item_func_get_system_var(THD *thd, sys_var *var_arg, - enum_var_type var_type_arg, - LEX_CSTRING *component_arg, const char *name_arg, - size_t name_len_arg); - enum Functype functype() const { return GSYSVAR_FUNC; } - void update_null_value(); - bool fix_length_and_dec(); - void print(String *str, enum_query_type query_type); - bool const_item() const { return true; } - table_map used_tables() const { return 0; } - const Type_handler *type_handler() const; - double val_real(); - longlong val_int(); - String* val_str(String*); - my_decimal *val_decimal(my_decimal *dec_buf) - { return val_decimal_from_real(dec_buf); } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } - /* TODO: fix to support views */ - const char *func_name() const { return "get_system_var"; } - /** - Indicates whether this system variable is written to the binlog or not. - - Variables are written to the binlog as part of "status_vars" in - Query_log_event, as an Intvar_log_event, or a Rand_log_event. - - @return true if the variable is written to the binlog, false otherwise. - */ - bool is_written_to_binlog(); - bool eq(const Item *item, bool binary_cmp) const; - - void cleanup(); - bool check_vcol_func_processor(void *arg); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* for fulltext search */ - -class Item_func_match :public Item_real_func -{ -public: - uint key, flags; - bool join_key; - DTCollation cmp_collation; - FT_INFO *ft_handler; - TABLE *table; - Item_func_match *master; // for master-slave optimization - Item *concat_ws; // Item_func_concat_ws - String value; // value of concat_ws - String search_value; // key_item()'s value converted to cmp_collation - - Item_func_match(THD *thd, List &a, uint b): - Item_real_func(thd, a), key(0), flags(b), join_key(0), ft_handler(0), - table(0), master(0), concat_ws(0) { } - void cleanup() - { - DBUG_ENTER("Item_func_match::cleanup"); - Item_real_func::cleanup(); - if (!master && ft_handler) - ft_handler->please->close_search(ft_handler); - ft_handler= 0; - concat_ws= 0; - table= 0; // required by Item_func_match::eq() - DBUG_VOID_RETURN; - } - bool is_expensive_processor(void *arg) { return TRUE; } - enum Functype functype() const { return FT_FUNC; } - const char *func_name() const { return "match"; } - bool eval_not_null_tables(void *opt_arg) - { - not_null_tables_cache= 0; - return 0; - } - bool find_not_null_fields(table_map allowed) - { - return false; - } - bool fix_fields(THD *thd, Item **ref); - bool eq(const Item *, bool binary_cmp) const; - /* The following should be safe, even if we compare doubles */ - longlong val_int() { DBUG_ASSERT(fixed == 1); return val_real() != 0.0; } - double val_real(); - virtual void print(String *str, enum_query_type query_type); - - bool fix_index(); - bool init_search(THD *thd, bool no_order); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function("match ... against()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *build_clone(THD *thd) { return 0; } -private: - /** - Check whether storage engine for given table, - allows FTS Boolean search on non-indexed columns. - - @todo A flag should be added to the extended fulltext API so that - it may be checked whether search on non-indexed columns are - supported. Currently, it is not possible to check for such a - flag since @c this->ft_handler is not yet set when this function is - called. The current hack is to assume that search on non-indexed - columns are supported for engines that does not support the extended - fulltext API (e.g., MyISAM), while it is not supported for other - engines (e.g., InnoDB) - - @param table_arg Table for which storage engine to check - - @retval true if BOOLEAN search on non-indexed columns is supported - @retval false otherwise - */ - bool allows_search_on_non_indexed_columns(TABLE* table_arg) - { - // Only Boolean search may support non_indexed columns - if (!(flags & FT_BOOL)) - return false; - - DBUG_ASSERT(table_arg && table_arg->file); - - // Assume that if extended fulltext API is not supported, - // non-indexed columns are allowed. This will be true for MyISAM. - if ((table_arg->file->ha_table_flags() & HA_CAN_FULLTEXT_EXT) == 0) - return true; - - return false; - } -}; - - -class Item_func_bit_xor : public Item_func_bit_operator -{ -public: - Item_func_bit_xor(THD *thd, Item *a, Item *b) - :Item_func_bit_operator(thd, a, b) {} - bool fix_length_and_dec(); - const char *func_name() const { return "^"; } - enum precedence precedence() const { return BITXOR_PRECEDENCE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_is_free_lock :public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_general_purpose_string(func_name()); } - String value; -public: - Item_func_is_free_lock(THD *thd, Item *a): Item_long_func(thd, a) {} - longlong val_int(); - const char *func_name() const { return "is_free_lock"; } - bool fix_length_and_dec() - { - decimals=0; max_length=1; maybe_null=1; - return FALSE; - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_is_used_lock :public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_general_purpose_string(func_name()); } - String value; -public: - Item_func_is_used_lock(THD *thd, Item *a): Item_long_func(thd, a) {} - longlong val_int(); - const char *func_name() const { return "is_used_lock"; } - bool fix_length_and_dec() - { - decimals=0; max_length=10; maybe_null=1; - return FALSE; - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -struct Lex_cast_type_st: public Lex_length_and_dec_st -{ -private: - const Type_handler *m_type_handler; -public: - void set(const Type_handler *handler, const char *length, const char *dec) - { - m_type_handler= handler; - Lex_length_and_dec_st::set(length, dec); - } - void set(const Type_handler *handler, Lex_length_and_dec_st length_and_dec) - { - m_type_handler= handler; - Lex_length_and_dec_st::operator=(length_and_dec); - } - void set(const Type_handler *handler, const char *length) - { - set(handler, length, 0); - } - void set(const Type_handler *handler) - { - set(handler, 0, 0); - } - const Type_handler *type_handler() const { return m_type_handler; } - Item *create_typecast_item(THD *thd, Item *item, - CHARSET_INFO *cs= NULL) const - { - return m_type_handler-> - create_typecast_item(thd, item, - Type_cast_attributes(length(), dec(), cs)); - } - Item *create_typecast_item_or_error(THD *thd, Item *item, - CHARSET_INFO *cs= NULL) const; -}; - - -class Item_func_row_count :public Item_longlong_func -{ -public: - Item_func_row_count(THD *thd): Item_longlong_func(thd) {} - longlong val_int(); - const char *func_name() const { return "row_count"; } - bool fix_length_and_dec() { decimals= 0; maybe_null=0; return FALSE; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - * - * Stored FUNCTIONs - * - */ - -class Item_func_sp :public Item_func, - public Item_sp -{ -private: - const Sp_handler *m_handler; - - bool execute(); - -protected: - bool is_expensive_processor(void *arg) - { return is_expensive(); } - - bool check_arguments() const - { - // sp_prepare_func_item() checks that the number of columns is correct - return false; - } -public: - - Item_func_sp(THD *thd, Name_resolution_context *context_arg, - sp_name *name, const Sp_handler *sph); - - Item_func_sp(THD *thd, Name_resolution_context *context_arg, - sp_name *name, const Sp_handler *sph, List &list); - - virtual ~Item_func_sp() - {} - - void update_used_tables(); - - void cleanup(); - - const char *func_name() const; - - const Type_handler *type_handler() const; - - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param); - Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) - { - return result_type() != STRING_RESULT ? - sp_result_field : - create_table_field_from_handler(root, table); - } - void make_send_field(THD *thd, Send_field *tmp_field); - - longlong val_int() - { - if (execute()) - return (longlong) 0; - return sp_result_field->val_int(); - } - - double val_real() - { - if (execute()) - return 0.0; - return sp_result_field->val_real(); - } - - my_decimal *val_decimal(my_decimal *dec_buf) - { - if (execute()) - return NULL; - return sp_result_field->val_decimal(dec_buf); - } - - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - if (execute()) - return true; - return sp_result_field->get_date(ltime, fuzzydate); - } - - String *val_str(String *str) - { - String buf; - char buff[20]; - buf.set(buff, 20, str->charset()); - buf.length(0); - if (execute()) - return NULL; - /* - result_field will set buf pointing to internal buffer - of the resul_field. Due to this it will change any time - when SP is executed. In order to prevent occasional - corruption of returned value, we make here a copy. - */ - sp_result_field->val_str(&buf); - str->copy(buf); - return str; - } - - bool val_native(THD *thd, Native *to) - { - if (execute()) - return true; - return null_value= sp_result_field->val_native(to); - } - - void update_null_value() - { - execute(); - } - - virtual bool change_context_processor(void *cntx) - { context= (Name_resolution_context *)cntx; return FALSE; } - - virtual enum Functype functype() const { return FUNC_SP; } - - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec(void); - bool is_expensive(); - - inline Field *get_sp_result_field() - { - return sp_result_field; - } - const sp_name *get_sp_name() const - { - return m_name; - } - - bool check_vcol_func_processor(void *arg); - bool limit_index_condition_pushdown_processor(void *opt_arg) - { - return TRUE; - } - Item *get_copy(THD *) { return 0; } - bool eval_not_null_tables(void *opt_arg) - { - not_null_tables_cache= 0; - return 0; - } - bool excl_dep_on_grouping_fields(st_select_lex *sel) - { return false; } - bool find_not_null_fields(table_map allowed) - { - return false; - } -}; - - -class Item_func_found_rows :public Item_longlong_func -{ -public: - Item_func_found_rows(THD *thd): Item_longlong_func(thd) {} - longlong val_int(); - const char *func_name() const { return "found_rows"; } - bool fix_length_and_dec() { decimals= 0; maybe_null=0; return FALSE; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_oracle_sql_rowcount :public Item_longlong_func -{ -public: - Item_func_oracle_sql_rowcount(THD *thd): Item_longlong_func(thd) {} - longlong val_int(); - const char *func_name() const { return "SQL%ROWCOUNT"; } - void print(String *str, enum_query_type query_type) - { - str->append(func_name()); - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_sqlcode: public Item_long_func -{ -public: - Item_func_sqlcode(THD *thd): Item_long_func(thd) { } - longlong val_int(); - const char *func_name() const { return "SQLCODE"; } - void print(String *str, enum_query_type query_type) - { - str->append(func_name()); - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - bool fix_length_and_dec() - { - maybe_null= null_value= false; - max_length= 11; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -void uuid_short_init(); - -class Item_func_uuid_short :public Item_longlong_func -{ -public: - Item_func_uuid_short(THD *thd): Item_longlong_func(thd) {} - const char *func_name() const { return "uuid_short"; } - longlong val_int(); - bool const_item() const { return false; } - bool fix_length_and_dec() - { max_length= 21; unsigned_flag=1; return FALSE; } - table_map used_tables() const { return RAND_TABLE_BIT; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_NON_DETERMINISTIC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_last_value :public Item_func -{ -protected: - Item *last_value; -public: - Item_func_last_value(THD *thd, List &list): Item_func(thd, list) {} - double val_real(); - longlong val_int(); - String *val_str(String *); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool val_native(THD *thd, Native *); - bool fix_length_and_dec(); - const char *func_name() const { return "last_value"; } - const Type_handler *type_handler() const { return last_value->type_handler(); } - bool eval_not_null_tables(void *) - { - not_null_tables_cache= 0; - return 0; - } - bool find_not_null_fields(table_map allowed) - { - return false; - } - bool const_item() const { return 0; } - void evaluate_sideeffects(); - void update_used_tables() - { - Item_func::update_used_tables(); - maybe_null= last_value->maybe_null; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* Implementation for sequences: NEXT VALUE FOR sequence and NEXTVAL() */ - -class Item_func_nextval :public Item_longlong_func -{ -protected: - TABLE_LIST *table_list; - TABLE *table; -public: - Item_func_nextval(THD *thd, TABLE_LIST *table_list_arg): - Item_longlong_func(thd), table_list(table_list_arg) {} - longlong val_int(); - const char *func_name() const { return "nextval"; } - bool fix_length_and_dec() - { - unsigned_flag= 0; - max_length= MAX_BIGINT_WIDTH; - maybe_null= 1; /* In case of errors */ - return FALSE; - } - /* - update_table() function must be called during the value function - as in case of DEFAULT the sequence table may not yet be open - while fix_fields() are called - */ - void update_table() - { - if (!(table= table_list->table)) - { - /* - If nextval was used in DEFAULT then next_local points to - the table_list used by to open the sequence table - */ - table= table_list->next_local->table; - } - } - bool const_item() const { return 0; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - void print(String *str, enum_query_type query_type); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, - (VCOL_NON_DETERMINISTIC | - VCOL_NOT_VIRTUAL)); - } -}; - - -/* Implementation for sequences: LASTVAL(sequence), PostgreSQL style */ - -class Item_func_lastval :public Item_func_nextval -{ -public: - Item_func_lastval(THD *thd, TABLE_LIST *table_list_arg): - Item_func_nextval(thd, table_list_arg) {} - longlong val_int(); - const char *func_name() const { return "lastval"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* Implementation for sequences: SETVAL(sequence), PostgreSQL style */ - -class Item_func_setval :public Item_func_nextval -{ - longlong nextval; - ulonglong round; - bool is_used; -public: - Item_func_setval(THD *thd, TABLE_LIST *table_list_arg, longlong nextval_arg, - ulonglong round_arg, bool is_used_arg) - : Item_func_nextval(thd, table_list_arg), - nextval(nextval_arg), round(round_arg), is_used(is_used_arg) - {} - longlong val_int(); - const char *func_name() const { return "setval"; } - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -Item *get_system_var(THD *thd, enum_var_type var_type, - const LEX_CSTRING *name, const LEX_CSTRING *component); -extern bool check_reserved_words(const LEX_CSTRING *name); -double my_double_round(double value, longlong dec, bool dec_unsigned, - bool truncate); - -extern bool volatile mqh_used; - -bool update_hash(user_var_entry *entry, bool set_null, void *ptr, size_t length, - Item_result type, CHARSET_INFO *cs, - bool unsigned_arg); - -#endif /* ITEM_FUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_geofunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_geofunc.h deleted file mode 100644 index c38d0b9..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_geofunc.h +++ /dev/null @@ -1,1109 +0,0 @@ -#ifndef ITEM_GEOFUNC_INCLUDED -#define ITEM_GEOFUNC_INCLUDED - -/* Copyright (c) 2000, 2016 Oracle and/or its affiliates. - Copyright (C) 2011, 2016, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* This file defines all spatial functions */ - -#ifdef HAVE_SPATIAL - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_type_geom.h" -#include "item.h" -#include "gstream.h" -#include "spatial.h" -#include "gcalc_slicescan.h" -#include "gcalc_tools.h" - -class Item_geometry_func: public Item_str_func -{ -public: - Item_geometry_func(THD *thd): Item_str_func(thd) {} - Item_geometry_func(THD *thd, Item *a): Item_str_func(thd, a) {} - Item_geometry_func(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} - Item_geometry_func(THD *thd, Item *a, Item *b, Item *c): - Item_str_func(thd, a, b, c) {} - Item_geometry_func(THD *thd, List &list): Item_str_func(thd, list) {} - bool fix_length_and_dec(); - const Type_handler *type_handler() const { return &type_handler_geometry; } -}; - - -/* - Functions returning REAL measurements of a single GEOMETRY argument -*/ -class Item_real_func_args_geometry: public Item_real_func -{ -protected: - String value; - bool check_arguments() const - { - DBUG_ASSERT(arg_count == 1); - return Type_handler_geometry::check_type_geom_or_binary(func_name(), - args[0]); - } -public: - Item_real_func_args_geometry(THD *thd, Item *a) - :Item_real_func(thd, a) {} -}; - - -/* - Functions returning INT measurements of a single GEOMETRY argument -*/ -class Item_long_func_args_geometry: public Item_long_func -{ - bool check_arguments() const - { - DBUG_ASSERT(arg_count == 1); - return Type_handler_geometry::check_type_geom_or_binary(func_name(), - args[0]); - } -protected: - String value; -public: - Item_long_func_args_geometry(THD *thd, Item *a) - :Item_long_func(thd, a) {} -}; - - -/* - Functions returning BOOL measurements of a single GEOMETRY argument -*/ -class Item_bool_func_args_geometry: public Item_bool_func -{ -protected: - String value; - bool check_arguments() const - { - DBUG_ASSERT(arg_count == 1); - return Type_handler_geometry::check_type_geom_or_binary(func_name(), - args[0]); - } -public: - Item_bool_func_args_geometry(THD *thd, Item *a) - :Item_bool_func(thd, a) {} -}; - - -/* - Functions returning ASCII string measurements of a single GEOMETRY argument -*/ -class Item_str_ascii_func_args_geometry: public Item_str_ascii_func -{ -protected: - bool check_arguments() const - { - DBUG_ASSERT(arg_count >= 1); - return Type_handler_geometry::check_type_geom_or_binary(func_name(), - args[0]); - } -public: - Item_str_ascii_func_args_geometry(THD *thd, Item *a) - :Item_str_ascii_func(thd, a) {} - Item_str_ascii_func_args_geometry(THD *thd, Item *a, Item *b) - :Item_str_ascii_func(thd, a, b) {} - Item_str_ascii_func_args_geometry(THD *thd, Item *a, Item *b, Item *c) - :Item_str_ascii_func(thd, a, b, c) {} -}; - - -/* - Functions returning binary string measurements of a single GEOMETRY argument -*/ -class Item_binary_func_args_geometry: public Item_str_func -{ -protected: - bool check_arguments() const - { - DBUG_ASSERT(arg_count >= 1); - return Type_handler_geometry::check_type_geom_or_binary(func_name(), - args[0]); - } -public: - Item_binary_func_args_geometry(THD *thd, Item *a) - :Item_str_func(thd, a) {} -}; - - -/* - Functions returning GEOMETRY measurements of a single GEOEMETRY argument -*/ -class Item_geometry_func_args_geometry: public Item_geometry_func -{ -protected: - bool check_arguments() const - { - DBUG_ASSERT(arg_count >= 1); - return Type_handler_geometry::check_type_geom_or_binary(func_name(), - args[0]); - } -public: - Item_geometry_func_args_geometry(THD *thd, Item *a) - :Item_geometry_func(thd, a) {} - Item_geometry_func_args_geometry(THD *thd, Item *a, Item *b) - :Item_geometry_func(thd, a, b) {} -}; - - -/* - Functions returning REAL result relationships between two GEOMETRY arguments -*/ -class Item_real_func_args_geometry_geometry: public Item_real_func -{ -protected: - bool check_arguments() const - { - DBUG_ASSERT(arg_count >= 2); - return Type_handler_geometry::check_types_geom_or_binary(func_name(), - args, 0, 2); - } -public: - Item_real_func_args_geometry_geometry(THD *thd, Item *a, Item *b) - :Item_real_func(thd, a, b) {} -}; - - -/* - Functions returning BOOL result relationships between two GEOMETRY arguments -*/ -class Item_bool_func_args_geometry_geometry: public Item_bool_func -{ -protected: - String value; - bool check_arguments() const - { - DBUG_ASSERT(arg_count >= 2); - return Type_handler_geometry::check_types_geom_or_binary(func_name(), - args, 0, 2); - } -public: - Item_bool_func_args_geometry_geometry(THD *thd, Item *a, Item *b, Item *c) - :Item_bool_func(thd, a, b, c) {} -}; - - -class Item_func_geometry_from_text: public Item_geometry_func -{ - bool check_arguments() const - { - return args[0]->check_type_general_purpose_string(func_name()) || - check_argument_types_can_return_int(1, MY_MIN(2, arg_count)); - } -public: - Item_func_geometry_from_text(THD *thd, Item *a): Item_geometry_func(thd, a) {} - Item_func_geometry_from_text(THD *thd, Item *a, Item *srid): - Item_geometry_func(thd, a, srid) {} - const char *func_name() const { return "st_geometryfromtext"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_geometry_from_wkb: public Item_geometry_func -{ - bool check_arguments() const - { - return - Type_handler_geometry::check_type_geom_or_binary(func_name(), args[0]) || - check_argument_types_can_return_int(1, MY_MIN(2, arg_count)); - } -public: - Item_func_geometry_from_wkb(THD *thd, Item *a): Item_geometry_func(thd, a) {} - Item_func_geometry_from_wkb(THD *thd, Item *a, Item *srid): - Item_geometry_func(thd, a, srid) {} - const char *func_name() const { return "st_geometryfromwkb"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_geometry_from_json: public Item_geometry_func -{ - String tmp_js; - bool check_arguments() const - { - // TODO: check with Alexey, for better args[1] and args[2] type control - return args[0]->check_type_general_purpose_string(func_name()) || - check_argument_types_traditional_scalar(1, MY_MIN(3, arg_count)); - } -public: - Item_func_geometry_from_json(THD *thd, Item *js): Item_geometry_func(thd, js) {} - Item_func_geometry_from_json(THD *thd, Item *js, Item *opt): - Item_geometry_func(thd, js, opt) {} - Item_func_geometry_from_json(THD *thd, Item *js, Item *opt, Item *srid): - Item_geometry_func(thd, js, opt, srid) {} - const char *func_name() const { return "st_geomfromgeojson"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_as_wkt: public Item_str_ascii_func_args_geometry -{ -public: - Item_func_as_wkt(THD *thd, Item *a) - :Item_str_ascii_func_args_geometry(thd, a) {} - const char *func_name() const { return "st_astext"; } - String *val_str_ascii(String *); - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_as_wkb: public Item_binary_func_args_geometry -{ -public: - Item_func_as_wkb(THD *thd, Item *a) - :Item_binary_func_args_geometry(thd, a) {} - const char *func_name() const { return "st_aswkb"; } - String *val_str(String *); - const Type_handler *type_handler() const { return &type_handler_long_blob; } - bool fix_length_and_dec() - { - collation.set(&my_charset_bin); - decimals=0; - max_length= (uint32) UINT_MAX32; - maybe_null= 1; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_as_geojson: public Item_str_ascii_func_args_geometry -{ - bool check_arguments() const - { - // TODO: check with Alexey, for better args[1] and args[2] type control - return Item_str_ascii_func_args_geometry::check_arguments() || - check_argument_types_traditional_scalar(1, MY_MIN(3, arg_count)); - } -public: - Item_func_as_geojson(THD *thd, Item *js) - :Item_str_ascii_func_args_geometry(thd, js) {} - Item_func_as_geojson(THD *thd, Item *js, Item *max_dec_digits) - :Item_str_ascii_func_args_geometry(thd, js, max_dec_digits) {} - Item_func_as_geojson(THD *thd, Item *js, Item *max_dec_digits, Item *opt) - :Item_str_ascii_func_args_geometry(thd, js, max_dec_digits, opt) {} - const char *func_name() const { return "st_asgeojson"; } - bool fix_length_and_dec(); - String *val_str_ascii(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_geometry_type: public Item_str_ascii_func_args_geometry -{ -public: - Item_func_geometry_type(THD *thd, Item *a) - :Item_str_ascii_func_args_geometry(thd, a) {} - String *val_str_ascii(String *); - const char *func_name() const { return "st_geometrytype"; } - bool fix_length_and_dec() - { - // "GeometryCollection" is the longest - fix_length_and_charset(20, default_charset()); - maybe_null= 1; - return FALSE; - }; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -// #define HEAVY_CONVEX_HULL -class Item_func_convexhull: public Item_geometry_func_args_geometry -{ - class ch_node: public Gcalc_dyn_list::Item - { - public: - const Gcalc_heap::Info *pi; - ch_node *prev; - Gcalc_dyn_list::Item *next; - ch_node *get_next() { return (ch_node *) next; } - }; - - Gcalc_heap collector; - Gcalc_function func; - Gcalc_dyn_list res_heap; - - Gcalc_result_receiver res_receiver; - String tmp_value; -#ifdef HEAVY_CONVEX_HULL - Gcalc_scan_iterator scan_it; -#endif /*HEAVY_CONVEX_HULL*/ - ch_node *new_ch_node() { return (ch_node *) res_heap.new_item(); } - int add_node_to_line(ch_node **p_cur, int dir, const Gcalc_heap::Info *pi); -public: - Item_func_convexhull(THD *thd, Item *a) - :Item_geometry_func_args_geometry(thd, a), - res_heap(8192, sizeof(ch_node)) - {} - const char *func_name() const { return "st_convexhull"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_centroid: public Item_geometry_func_args_geometry -{ -public: - Item_func_centroid(THD *thd, Item *a) - :Item_geometry_func_args_geometry(thd, a) {} - const char *func_name() const { return "st_centroid"; } - String *val_str(String *); - const Type_handler *type_handler() const - { - return &type_handler_point; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_envelope: public Item_geometry_func_args_geometry -{ -public: - Item_func_envelope(THD *thd, Item *a) - :Item_geometry_func_args_geometry(thd, a) {} - const char *func_name() const { return "st_envelope"; } - String *val_str(String *); - const Type_handler *type_handler() const - { - return &type_handler_polygon; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_boundary: public Item_geometry_func_args_geometry -{ - class Transporter : public Gcalc_shape_transporter - { - Gcalc_result_receiver *m_receiver; - uint n_points; - Gcalc_function::shape_type current_type; - double last_x, last_y; - public: - Transporter(Gcalc_result_receiver *receiver) : - Gcalc_shape_transporter(NULL), m_receiver(receiver) - {} - int single_point(double x, double y); - int start_line(); - int complete_line(); - int start_poly(); - int complete_poly(); - int start_ring(); - int complete_ring(); - int add_point(double x, double y); - - int start_collection(int n_objects); - }; - Gcalc_result_receiver res_receiver; -public: - Item_func_boundary(THD *thd, Item *a) - :Item_geometry_func_args_geometry(thd, a) {} - const char *func_name() const { return "st_boundary"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_point: public Item_geometry_func -{ - bool check_arguments() const - { return check_argument_types_can_return_real(0, 2); } -public: - Item_func_point(THD *thd, Item *a, Item *b): Item_geometry_func(thd, a, b) {} - Item_func_point(THD *thd, Item *a, Item *b, Item *srid): - Item_geometry_func(thd, a, b, srid) {} - const char *func_name() const { return "point"; } - String *val_str(String *); - const Type_handler *type_handler() const - { - return &type_handler_point; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_spatial_decomp: public Item_geometry_func_args_geometry -{ - enum Functype decomp_func; -public: - Item_func_spatial_decomp(THD *thd, Item *a, Item_func::Functype ft): - Item_geometry_func_args_geometry(thd, a) { decomp_func = ft; } - const char *func_name() const - { - switch (decomp_func) - { - case SP_STARTPOINT: - return "st_startpoint"; - case SP_ENDPOINT: - return "st_endpoint"; - case SP_EXTERIORRING: - return "st_exteriorring"; - default: - DBUG_ASSERT(0); // Should never happened - return "spatial_decomp_unknown"; - } - } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_spatial_decomp_n: public Item_geometry_func_args_geometry -{ - enum Functype decomp_func_n; - bool check_arguments() const - { - return Item_geometry_func_args_geometry::check_arguments() || - args[1]->check_type_can_return_int(func_name()); - } -public: - Item_func_spatial_decomp_n(THD *thd, Item *a, Item *b, Item_func::Functype ft) - :Item_geometry_func_args_geometry(thd, a, b), - decomp_func_n(ft) - { } - const char *func_name() const - { - switch (decomp_func_n) - { - case SP_POINTN: - return "st_pointn"; - case SP_GEOMETRYN: - return "st_geometryn"; - case SP_INTERIORRINGN: - return "st_interiorringn"; - default: - DBUG_ASSERT(0); // Should never happened - return "spatial_decomp_n_unknown"; - } - } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_spatial_collection: public Item_geometry_func -{ - bool check_arguments() const - { - return Type_handler_geometry::check_types_geom_or_binary(func_name(), args, - 0, arg_count); - } - enum Geometry::wkbType coll_type; - enum Geometry::wkbType item_type; -public: - Item_func_spatial_collection(THD *thd, - List &list, enum Geometry::wkbType ct, enum Geometry::wkbType it): - Item_geometry_func(thd, list) - { - coll_type=ct; - item_type=it; - } - String *val_str(String *); - bool fix_length_and_dec() - { - if (Item_geometry_func::fix_length_and_dec()) - return TRUE; - for (unsigned int i= 0; i < arg_count; ++i) - { - if (args[i]->is_fixed() && args[i]->field_type() != MYSQL_TYPE_GEOMETRY) - { - String str; - args[i]->print(&str, QT_NO_DATA_EXPANSION); - str.append('\0'); - my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "non geometric", - str.ptr()); - return TRUE; - } - } - return FALSE; - } -}; - - -class Item_func_geometrycollection: public Item_func_spatial_collection -{ -public: - Item_func_geometrycollection(THD *thd, List &list) - :Item_func_spatial_collection(thd, list, - Geometry::wkb_geometrycollection, - Geometry::wkb_point) - { } - const Type_handler *type_handler() const - { - return &type_handler_geometrycollection; - } - const char *func_name() const { return "geometrycollection"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_linestring: public Item_func_spatial_collection -{ -public: - Item_func_linestring(THD *thd, List &list) - :Item_func_spatial_collection(thd, list, - Geometry::wkb_linestring, - Geometry::wkb_point) - { } - const Type_handler *type_handler() const { return &type_handler_linestring; } - const char *func_name() const { return "linestring"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_polygon: public Item_func_spatial_collection -{ -public: - Item_func_polygon(THD *thd, List &list) - :Item_func_spatial_collection(thd, list, - Geometry::wkb_polygon, - Geometry::wkb_linestring) - { } - const Type_handler *type_handler() const { return &type_handler_polygon; } - const char *func_name() const { return "polygon"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_multilinestring: public Item_func_spatial_collection -{ -public: - Item_func_multilinestring(THD *thd, List &list) - :Item_func_spatial_collection(thd, list, - Geometry::wkb_multilinestring, - Geometry::wkb_linestring) - { } - const Type_handler *type_handler() const - { - return &type_handler_multilinestring; - } - const char *func_name() const { return "multilinestring"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_multipoint: public Item_func_spatial_collection -{ -public: - Item_func_multipoint(THD *thd, List &list) - :Item_func_spatial_collection(thd, list, - Geometry::wkb_multipoint, - Geometry::wkb_point) - { } - const Type_handler *type_handler() const - { - return &type_handler_multipoint; - } - const char *func_name() const { return "multipoint"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_multipolygon: public Item_func_spatial_collection -{ -public: - Item_func_multipolygon(THD *thd, List &list) - :Item_func_spatial_collection(thd, list, - Geometry::wkb_multipolygon, - Geometry::wkb_polygon) - { } - const Type_handler *type_handler() const - { - return &type_handler_multipolygon; - } - const char *func_name() const { return "multipolygon"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - - -/* - Spatial relations -*/ - -class Item_func_spatial_rel: public Item_bool_func2_with_rev -{ -protected: - enum Functype spatial_rel; - String tmp_value1, tmp_value2; - SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, - KEY_PART *key_part, - Item_func::Functype type, Item *value); - bool check_arguments() const - { - DBUG_ASSERT(arg_count >= 2); - return Type_handler_geometry::check_types_geom_or_binary(func_name(), - args, 0, 2); - } -public: - Item_func_spatial_rel(THD *thd, Item *a, Item *b, enum Functype sp_rel): - Item_bool_func2_with_rev(thd, a, b), spatial_rel(sp_rel) - { - maybe_null= true; - } - enum Functype functype() const { return spatial_rel; } - enum Functype rev_functype() const - { - switch (spatial_rel) - { - case SP_CONTAINS_FUNC: - return SP_WITHIN_FUNC; - case SP_WITHIN_FUNC: - return SP_CONTAINS_FUNC; - default: - return spatial_rel; - } - } - bool is_null() { (void) val_int(); return null_value; } - void add_key_fields(JOIN *join, KEY_FIELD **key_fields, - uint *and_level, table_map usable_tables, - SARGABLE_PARAM **sargables) - { - return add_key_fields_optimize_op(join, key_fields, and_level, - usable_tables, sargables, false); - } - bool need_parentheses_in_default() { return false; } - Item *build_clone(THD *thd) { return 0; } -}; - - -class Item_func_spatial_mbr_rel: public Item_func_spatial_rel -{ -public: - Item_func_spatial_mbr_rel(THD *thd, Item *a, Item *b, enum Functype sp_rel): - Item_func_spatial_rel(thd, a, b, sp_rel) - { } - longlong val_int(); - const char *func_name() const; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_spatial_precise_rel: public Item_func_spatial_rel -{ - Gcalc_heap collector; - Gcalc_scan_iterator scan_it; - Gcalc_function func; -public: - Item_func_spatial_precise_rel(THD *thd, Item *a, Item *b, enum Functype sp_rel): - Item_func_spatial_rel(thd, a, b, sp_rel), collector() - { } - longlong val_int(); - const char *func_name() const; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_spatial_relate: public Item_bool_func_args_geometry_geometry -{ - Gcalc_heap collector; - Gcalc_scan_iterator scan_it; - Gcalc_function func; - String tmp_value1, tmp_value2, tmp_matrix; - bool check_arguments() const - { - return Item_bool_func_args_geometry_geometry::check_arguments() || - args[2]->check_type_general_purpose_string(func_name()); - } -public: - Item_func_spatial_relate(THD *thd, Item *a, Item *b, Item *matrix): - Item_bool_func_args_geometry_geometry(thd, a, b, matrix) - { } - longlong val_int(); - const char *func_name() const { return "st_relate"; } - bool need_parentheses_in_default() { return false; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - Spatial operations -*/ - -class Item_func_spatial_operation: public Item_geometry_func -{ - bool check_arguments() const - { - DBUG_ASSERT(arg_count >= 2); - return Type_handler_geometry::check_types_geom_or_binary(func_name(), - args, 0, 2); - } -public: - Gcalc_function::op_type spatial_op; - Gcalc_heap collector; - Gcalc_function func; - - Gcalc_result_receiver res_receiver; - Gcalc_operation_reducer operation; - String tmp_value1,tmp_value2; -public: - Item_func_spatial_operation(THD *thd, Item *a,Item *b, - Gcalc_function::op_type sp_op): - Item_geometry_func(thd, a, b), spatial_op(sp_op) - {} - virtual ~Item_func_spatial_operation(); - String *val_str(String *); - const char *func_name() const; - virtual inline void print(String *str, enum_query_type query_type) - { - Item_func::print(str, query_type); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_buffer: public Item_geometry_func_args_geometry -{ - bool check_arguments() const - { - return Item_geometry_func_args_geometry::check_arguments() || - args[1]->check_type_can_return_real(func_name()); - } -protected: - class Transporter : public Gcalc_operation_transporter - { - int m_npoints; - double m_d; - double x1,y1,x2,y2; - double x00,y00,x01,y01; - int add_edge_buffer(double x3, double y3, bool round_p1, bool round_p2); - int add_last_edge_buffer(); - int add_point_buffer(double x, double y); - int complete(); - int m_nshapes; - Gcalc_function::op_type buffer_op; - int last_shape_pos; - bool skip_line; - - public: - Transporter(Gcalc_function *fn, Gcalc_heap *heap, double d) : - Gcalc_operation_transporter(fn, heap), m_npoints(0), m_d(d), - m_nshapes(0), buffer_op((d > 0.0) ? Gcalc_function::op_union : - Gcalc_function::op_difference), - skip_line(FALSE) - {} - int single_point(double x, double y); - int start_line(); - int complete_line(); - int start_poly(); - int complete_poly(); - int start_ring(); - int complete_ring(); - int add_point(double x, double y); - - int start_collection(int n_objects); - }; - Gcalc_heap collector; - Gcalc_function func; - - Gcalc_result_receiver res_receiver; - Gcalc_operation_reducer operation; - -public: - Item_func_buffer(THD *thd, Item *obj, Item *distance) - :Item_geometry_func_args_geometry(thd, obj, distance) {} - const char *func_name() const { return "st_buffer"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_isempty: public Item_bool_func_args_geometry -{ -public: - Item_func_isempty(THD *thd, Item *a) - :Item_bool_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_isempty"; } - bool fix_length_and_dec() { maybe_null= 1; return FALSE; } - bool need_parentheses_in_default() { return false; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_issimple: public Item_long_func_args_geometry -{ - Gcalc_heap collector; - Gcalc_function func; - Gcalc_scan_iterator scan_it; - String tmp; -public: - Item_func_issimple(THD *thd, Item *a) - :Item_long_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_issimple"; } - bool fix_length_and_dec() { decimals=0; max_length=2; return FALSE; } - uint decimal_precision() const { return 1; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_isclosed: public Item_long_func_args_geometry -{ -public: - Item_func_isclosed(THD *thd, Item *a) - :Item_long_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_isclosed"; } - bool fix_length_and_dec() { decimals=0; max_length=2; return FALSE; } - uint decimal_precision() const { return 1; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_isring: public Item_func_issimple -{ -public: - Item_func_isring(THD *thd, Item *a): Item_func_issimple(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_isring"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_dimension: public Item_long_func_args_geometry -{ -public: - Item_func_dimension(THD *thd, Item *a) - :Item_long_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_dimension"; } - bool fix_length_and_dec() { max_length= 10; maybe_null= 1; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_x: public Item_real_func_args_geometry -{ -public: - Item_func_x(THD *thd, Item *a): Item_real_func_args_geometry(thd, a) {} - double val_real(); - const char *func_name() const { return "st_x"; } - bool fix_length_and_dec() - { - if (Item_real_func::fix_length_and_dec()) - return TRUE; - maybe_null= 1; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_y: public Item_real_func_args_geometry -{ -public: - Item_func_y(THD *thd, Item *a): Item_real_func_args_geometry(thd, a) {} - double val_real(); - const char *func_name() const { return "st_y"; } - bool fix_length_and_dec() - { - if (Item_real_func::fix_length_and_dec()) - return TRUE; - maybe_null= 1; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_numgeometries: public Item_long_func_args_geometry -{ -public: - Item_func_numgeometries(THD *thd, Item *a) - :Item_long_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_numgeometries"; } - bool fix_length_and_dec() { max_length= 10; maybe_null= 1; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_numinteriorring: public Item_long_func_args_geometry -{ -public: - Item_func_numinteriorring(THD *thd, Item *a) - :Item_long_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_numinteriorrings"; } - bool fix_length_and_dec() { max_length= 10; maybe_null= 1; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_numpoints: public Item_long_func_args_geometry -{ -public: - Item_func_numpoints(THD *thd, Item *a) - :Item_long_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "st_numpoints"; } - bool fix_length_and_dec() { max_length= 10; maybe_null= 1; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_area: public Item_real_func_args_geometry -{ -public: - Item_func_area(THD *thd, Item *a): Item_real_func_args_geometry(thd, a) {} - double val_real(); - const char *func_name() const { return "st_area"; } - bool fix_length_and_dec() - { - if (Item_real_func::fix_length_and_dec()) - return TRUE; - maybe_null= 1; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_glength: public Item_real_func_args_geometry -{ - String value; -public: - Item_func_glength(THD *thd, Item *a) - :Item_real_func_args_geometry(thd, a) {} - double val_real(); - const char *func_name() const { return "st_length"; } - bool fix_length_and_dec() - { - if (Item_real_func::fix_length_and_dec()) - return TRUE; - maybe_null= 1; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_srid: public Item_long_func_args_geometry -{ -public: - Item_func_srid(THD *thd, Item *a) - :Item_long_func_args_geometry(thd, a) {} - longlong val_int(); - const char *func_name() const { return "srid"; } - bool fix_length_and_dec() { max_length= 10; maybe_null= 1; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_distance: public Item_real_func_args_geometry_geometry -{ - String tmp_value1; - String tmp_value2; - Gcalc_heap collector; - Gcalc_function func; - Gcalc_scan_iterator scan_it; -public: - Item_func_distance(THD *thd, Item *a, Item *b) - :Item_real_func_args_geometry_geometry(thd, a, b) {} - double val_real(); - const char *func_name() const { return "st_distance"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_pointonsurface: public Item_geometry_func_args_geometry -{ - String tmp_value; - Gcalc_heap collector; - Gcalc_function func; - Gcalc_scan_iterator scan_it; -public: - Item_func_pointonsurface(THD *thd, Item *a) - :Item_geometry_func_args_geometry(thd, a) {} - const char *func_name() const { return "st_pointonsurface"; } - String *val_str(String *); - const Type_handler *type_handler() const - { - return &type_handler_point; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -#ifndef DBUG_OFF -class Item_func_gis_debug: public Item_long_func -{ - public: - Item_func_gis_debug(THD *thd, Item *a): Item_long_func(thd, a) - { null_value= false; } - bool fix_length_and_dec() { fix_char_length(10); return FALSE; } - const char *func_name() const { return "st_gis_debug"; } - longlong val_int(); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; -#endif - - -#define GEOM_NEW(thd, obj_constructor) new (thd->mem_root) obj_constructor -#define GEOM_TYPE(x) (x) - -#else /*HAVE_SPATIAL*/ - -#define GEOM_NEW(thd, obj_constructor) NULL -#define GEOM_TYPE(x) NULL - -#endif /*HAVE_SPATIAL*/ -#endif /* ITEM_GEOFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_jsonfunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_jsonfunc.h deleted file mode 100644 index ec6c669..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_jsonfunc.h +++ /dev/null @@ -1,626 +0,0 @@ -#ifndef ITEM_JSONFUNC_INCLUDED -#define ITEM_JSONFUNC_INCLUDED - -/* Copyright (c) 2016, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - -/* This file defines all JSON functions */ - - -#include -#include "item_cmpfunc.h" // Item_bool_func -#include "item_strfunc.h" // Item_str_func -#include "item_sum.h" - - -class json_path_with_flags -{ -public: - json_path_t p; - bool constant; - bool parsed; - json_path_step_t *cur_step; - void set_constant_flag(bool s_constant) - { - constant= s_constant; - parsed= FALSE; - } -}; - - -class Json_engine_scan: public json_engine_t -{ -public: - Json_engine_scan(CHARSET_INFO *i_cs, const uchar *str, const uchar *end) - { - json_scan_start(this, i_cs, str, end); - } - Json_engine_scan(const String &str) - :Json_engine_scan(str.charset(), (const uchar *) str.ptr(), - (const uchar *) str.end()) - { } - bool check_and_get_value_scalar(String *res, int *error); - bool check_and_get_value_complex(String *res, int *error); -}; - - -class Json_path_extractor: public json_path_with_flags -{ -protected: - String tmp_js, tmp_path; - virtual ~Json_path_extractor() { } - virtual bool check_and_get_value(Json_engine_scan *je, - String *to, int *error)=0; - bool extract(String *to, Item *js, Item *jp, CHARSET_INFO *cs); -}; - - -class Item_func_json_valid: public Item_bool_func -{ -protected: - String tmp_value; - -public: - Item_func_json_valid(THD *thd, Item *json) : Item_bool_func(thd, json) {} - longlong val_int(); - const char *func_name() const { return "json_valid"; } - bool fix_length_and_dec() - { - if (Item_bool_func::fix_length_and_dec()) - return TRUE; - maybe_null= 1; - return FALSE; - } - bool set_format_by_check_constraint(Send_field_extended_metadata *to) const - { - static const Lex_cstring fmt(STRING_WITH_LEN("json")); - return to->set_format_name(fmt); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - enum Functype functype() const { return JSON_VALID_FUNC; } -}; - - -class Item_func_json_exists: public Item_bool_func -{ -protected: - json_path_with_flags path; - String tmp_js, tmp_path; - -public: - Item_func_json_exists(THD *thd, Item *js, Item *i_path): - Item_bool_func(thd, js, i_path) {} - const char *func_name() const { return "json_exists"; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - longlong val_int(); -}; - - -class Item_json_func: public Item_str_func -{ -public: - Item_json_func(THD *thd) - :Item_str_func(thd) { } - Item_json_func(THD *thd, Item *a) - :Item_str_func(thd, a) { } - Item_json_func(THD *thd, Item *a, Item *b) - :Item_str_func(thd, a, b) { } - Item_json_func(THD *thd, List &list) - :Item_str_func(thd, list) { } - bool is_json_type() { return true; } - void make_send_field(THD *thd, Send_field *tmp_field) - { - Item_str_func::make_send_field(thd, tmp_field); - static const Lex_cstring fmt(STRING_WITH_LEN("json")); - tmp_field->set_format_name(fmt); - } -}; - - -class Item_func_json_value: public Item_str_func, - public Json_path_extractor -{ - -public: - Item_func_json_value(THD *thd, Item *js, Item *i_path): - Item_str_func(thd, js, i_path) {} - const char *func_name() const override { return "json_value"; } - bool fix_length_and_dec() override ; - String *val_str(String *to) override - { - null_value= Json_path_extractor::extract(to, args[0], args[1], - collation.collation); - return null_value ? NULL : to; - } - bool check_and_get_value(Json_engine_scan *je, - String *res, int *error) override - { - return je->check_and_get_value_scalar(res, error); - } - Item *get_copy(THD *thd) override - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_query: public Item_json_func, - public Json_path_extractor -{ -public: - Item_func_json_query(THD *thd, Item *js, Item *i_path): - Item_json_func(thd, js, i_path) {} - const char *func_name() const override { return "json_query"; } - bool fix_length_and_dec() override; - String *val_str(String *to) override - { - null_value= Json_path_extractor::extract(to, args[0], args[1], - collation.collation); - return null_value ? NULL : to; - } - bool check_and_get_value(Json_engine_scan *je, - String *res, int *error) override - { - return je->check_and_get_value_complex(res, error); - } - Item *get_copy(THD *thd) override - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_quote: public Item_str_func -{ -protected: - String tmp_s; - -public: - Item_func_json_quote(THD *thd, Item *s): Item_str_func(thd, s) {} - const char *func_name() const { return "json_quote"; } - bool fix_length_and_dec(); - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_unquote: public Item_str_func -{ -protected: - String tmp_s; - String *read_json(json_engine_t *je); -public: - Item_func_json_unquote(THD *thd, Item *s): Item_str_func(thd, s) {} - const char *func_name() const { return "json_unquote"; } - bool fix_length_and_dec(); - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_json_str_multipath: public Item_json_func -{ -protected: - json_path_with_flags *paths; - String *tmp_paths; -public: - Item_json_str_multipath(THD *thd, List &list): - Item_json_func(thd, list), tmp_paths(0) {} - bool fix_fields(THD *thd, Item **ref); - void cleanup(); - virtual uint get_n_paths() const = 0; -}; - - -class Item_func_json_extract: public Item_json_str_multipath -{ -protected: - String tmp_js; -public: - String *read_json(String *str, json_value_types *type, - char **out_val, int *value_len); - Item_func_json_extract(THD *thd, List &list): - Item_json_str_multipath(thd, list) {} - const char *func_name() const { return "json_extract"; } - enum Functype functype() const { return JSON_EXTRACT_FUNC; } - bool fix_length_and_dec(); - String *val_str(String *); - longlong val_int(); - double val_real(); - my_decimal *val_decimal(my_decimal *); - uint get_n_paths() const { return arg_count - 1; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_contains: public Item_bool_func -{ -protected: - String tmp_js; - json_path_with_flags path; - String tmp_path; - bool a2_constant, a2_parsed; - String tmp_val, *val; -public: - Item_func_json_contains(THD *thd, List &list): - Item_bool_func(thd, list) {} - const char *func_name() const { return "json_contains"; } - bool fix_length_and_dec(); - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_contains_path: public Item_bool_func -{ -protected: - String tmp_js; - json_path_with_flags *paths; - String *tmp_paths; - bool mode_one; - bool ooa_constant, ooa_parsed; - bool *p_found; - -public: - Item_func_json_contains_path(THD *thd, List &list): - Item_bool_func(thd, list), tmp_paths(0) {} - const char *func_name() const { return "json_contains_path"; } - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec(); - void cleanup(); - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_array: public Item_json_func -{ -protected: - String tmp_val; - ulong result_limit; -public: - Item_func_json_array(THD *thd): - Item_json_func(thd) {} - Item_func_json_array(THD *thd, List &list): - Item_json_func(thd, list) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "json_array"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_array_append: public Item_json_str_multipath -{ -protected: - String tmp_js; - String tmp_val; -public: - Item_func_json_array_append(THD *thd, List &list): - Item_json_str_multipath(thd, list) {} - bool fix_length_and_dec(); - String *val_str(String *); - uint get_n_paths() const { return arg_count/2; } - const char *func_name() const { return "json_array_append"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_array_insert: public Item_func_json_array_append -{ -public: - Item_func_json_array_insert(THD *thd, List &list): - Item_func_json_array_append(thd, list) {} - String *val_str(String *); - const char *func_name() const { return "json_array_insert"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_object: public Item_func_json_array -{ -public: - Item_func_json_object(THD *thd): - Item_func_json_array(thd) {} - Item_func_json_object(THD *thd, List &list): - Item_func_json_array(thd, list) {} - String *val_str(String *); - const char *func_name() const { return "json_object"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_merge: public Item_func_json_array -{ -protected: - String tmp_js1, tmp_js2; -public: - Item_func_json_merge(THD *thd, List &list): - Item_func_json_array(thd, list) {} - String *val_str(String *); - const char *func_name() const { return "json_merge_preserve"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_json_merge_patch: public Item_func_json_merge -{ -public: - Item_func_json_merge_patch(THD *thd, List &list): - Item_func_json_merge(thd, list) {} - const char *func_name() const { return "json_merge_patch"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_json_length: public Item_long_func -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_text(func_name()) || - (arg_count > 1 && - args[1]->check_type_general_purpose_string(func_name())); - } -protected: - json_path_with_flags path; - String tmp_js; - String tmp_path; -public: - Item_func_json_length(THD *thd, List &list): - Item_long_func(thd, list) {} - const char *func_name() const { return "json_length"; } - bool fix_length_and_dec(); - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_depth: public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_text(func_name()); } -protected: - String tmp_js; -public: - Item_func_json_depth(THD *thd, Item *js): Item_long_func(thd, js) {} - const char *func_name() const { return "json_depth"; } - bool fix_length_and_dec() { max_length= 10; return FALSE; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_type: public Item_str_func -{ -protected: - String tmp_js; -public: - Item_func_json_type(THD *thd, Item *js): Item_str_func(thd, js) {} - const char *func_name() const { return "json_type"; } - bool fix_length_and_dec(); - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_insert: public Item_json_str_multipath -{ -protected: - String tmp_js; - String tmp_val; - bool mode_insert, mode_replace; -public: - Item_func_json_insert(bool i_mode, bool r_mode, THD *thd, List &list): - Item_json_str_multipath(thd, list), - mode_insert(i_mode), mode_replace(r_mode) {} - bool fix_length_and_dec(); - String *val_str(String *); - uint get_n_paths() const { return arg_count/2; } - const char *func_name() const - { - return mode_insert ? - (mode_replace ? "json_set" : "json_insert") : "json_update"; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_remove: public Item_json_str_multipath -{ -protected: - String tmp_js; -public: - Item_func_json_remove(THD *thd, List &list): - Item_json_str_multipath(thd, list) {} - bool fix_length_and_dec(); - String *val_str(String *); - uint get_n_paths() const { return arg_count - 1; } - const char *func_name() const { return "json_remove"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_keys: public Item_str_func -{ -protected: - json_path_with_flags path; - String tmp_js, tmp_path; - -public: - Item_func_json_keys(THD *thd, List &list): - Item_str_func(thd, list) {} - const char *func_name() const { return "json_keys"; } - bool fix_length_and_dec(); - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_search: public Item_json_str_multipath -{ -protected: - String tmp_js, tmp_path, esc_value; - bool mode_one; - bool ooa_constant, ooa_parsed; - int escape; - int n_path_found; - json_path_t sav_path; - - int compare_json_value_wild(json_engine_t *je, const String *cmp_str); - -public: - Item_func_json_search(THD *thd, List &list): - Item_json_str_multipath(thd, list) {} - const char *func_name() const { return "json_search"; } - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec(); - String *val_str(String *); - uint get_n_paths() const { return arg_count > 4 ? arg_count - 4 : 0; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_format: public Item_json_func -{ -public: - enum formats - { - NONE, - COMPACT, - LOOSE, - DETAILED - }; -protected: - formats fmt; - String tmp_js; -public: - Item_func_json_format(THD *thd, Item *js, formats format): - Item_json_func(thd, js), fmt(format) {} - Item_func_json_format(THD *thd, List &list): - Item_json_func(thd, list), fmt(DETAILED) {} - - const char *func_name() const; - bool fix_length_and_dec(); - String *val_str(String *str); - String *val_json(String *str); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_arrayagg : public Item_func_group_concat -{ -protected: - /* - Overrides Item_func_group_concat::skip_nulls() - NULL-s should be added to the result as JSON null value. - */ - bool skip_nulls() const { return false; } - String *get_str_from_item(Item *i, String *tmp); - String *get_str_from_field(Item *i, Field *f, String *tmp, - const uchar *key, size_t offset); - void cut_max_length(String *result, - uint old_length, uint max_length) const; -public: - String m_tmp_json; /* Used in get_str_from_*.. */ - Item_func_json_arrayagg(THD *thd, Name_resolution_context *context_arg, - bool is_distinct, List *is_select, - const SQL_I_List &is_order, String *is_separator, - bool limit_clause, Item *row_limit, Item *offset_limit): - Item_func_group_concat(thd, context_arg, is_distinct, is_select, is_order, - is_separator, limit_clause, row_limit, offset_limit) - { - } - Item_func_json_arrayagg(THD *thd, Item_func_json_arrayagg *item); - bool is_json_type() { return true; } - - const char *func_name() const { return "json_arrayagg("; } - enum Sumfunctype sum_func() const {return JSON_ARRAYAGG_FUNC;} - - String* val_str(String *str); - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_json_objectagg : public Item_sum -{ - String result; -public: - Item_func_json_objectagg(THD *thd, Item *key, Item *value) : - Item_sum(thd, key, value) - { - quick_group= FALSE; - result.append("{"); - } - - Item_func_json_objectagg(THD *thd, Item_func_json_objectagg *item); - bool is_json_type() { return true; } - void cleanup(); - - enum Sumfunctype sum_func () const {return JSON_OBJECTAGG_FUNC;} - const char *func_name() const { return "json_objectagg"; } - const Type_handler *type_handler() const - { - if (too_big_for_varchar()) - return &type_handler_blob; - return &type_handler_varchar; - } - void clear(); - bool add(); - void reset_field() { DBUG_ASSERT(0); } // not used - void update_field() { DBUG_ASSERT(0); } // not used - bool fix_fields(THD *,Item **); - - double val_real() - { return 0.0; } - longlong val_int() - { return 0; } - my_decimal *val_decimal(my_decimal *decimal_value) - { - my_decimal_set_zero(decimal_value); - return decimal_value; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return get_date_from_string(thd, ltime, fuzzydate); - } - String* val_str(String* str); - Item *copy_or_same(THD* thd); - void no_rows_in_result() {} - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -#endif /* ITEM_JSONFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_row.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_row.h deleted file mode 100644 index 2872a49..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_row.h +++ /dev/null @@ -1,160 +0,0 @@ -#ifndef ITEM_ROW_INCLUDED -#define ITEM_ROW_INCLUDED - -/* - Copyright (c) 2002, 2013, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - Row items used for comparing rows and IN operations on rows: - - @verbatim - (a, b, c) > (10, 10, 30) - (a, b, c) = (select c, d, e, from t1 where x=12) - (a, b, c) IN ((1,2,2), (3,4,5), (6,7,8) - (a, b, c) IN (select c, d, e, from t1) - @endverbatim -*/ - - -/** - Item which stores (x,y,...) and ROW(x,y,...). - Note that this can be recursive: ((x,y),(z,t)) is a ROW of ROWs. -*/ -class Item_row: public Item_fixed_hybrid, - private Item_args, - private Used_tables_and_const_cache, - private With_subquery_cache, - private With_sum_func_cache -{ - table_map not_null_tables_cache; - /** - If elements are made only of constants, of which one or more are - NULL. For example, this item is (1,2,NULL), or ( (1,NULL), (2,3) ). - */ - bool with_null; -public: - Item_row(THD *thd, List &list) - :Item_fixed_hybrid(thd), Item_args(thd, list), - not_null_tables_cache(0), with_null(0) - { } - Item_row(THD *thd, Item_row *row) - :Item_fixed_hybrid(thd), Item_args(thd, static_cast(row)), - Used_tables_and_const_cache(), - With_sum_func_cache(*row), - not_null_tables_cache(0), with_null(0) - { } - - bool with_subquery() const { DBUG_ASSERT(fixed); return m_with_subquery; } - enum Type type() const { return ROW_ITEM; }; - const Type_handler *type_handler() const { return &type_handler_row; } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - return NULL; // Check with Vicentiu why it's called for Item_row - } - void illegal_method_call(const char *); - bool is_null() { return null_value; } - void make_send_field(THD *thd, Send_field *) - { - illegal_method_call((const char*)"make_send_field"); - }; - double val_real() - { - illegal_method_call((const char*)"val"); - return 0; - }; - longlong val_int() - { - illegal_method_call((const char*)"val_int"); - return 0; - }; - String *val_str(String *) - { - illegal_method_call((const char*)"val_str"); - return 0; - }; - my_decimal *val_decimal(my_decimal *) - { - illegal_method_call((const char*)"val_decimal"); - return 0; - }; - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - illegal_method_call((const char*)"get_date"); - return true; - } - bool fix_fields(THD *thd, Item **ref); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge); - void cleanup(); - void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, uint flags); - bool with_sum_func() const { return m_with_sum_func; } - With_sum_func_cache* get_with_sum_func_cache() { return this; } - table_map used_tables() const { return used_tables_cache; }; - bool const_item() const { return const_item_cache; }; - void update_used_tables() - { - used_tables_and_const_cache_init(); - used_tables_and_const_cache_update_and_join(arg_count, args); - } - table_map not_null_tables() const { return not_null_tables_cache; } - virtual void print(String *str, enum_query_type query_type); - - bool walk(Item_processor processor, bool walk_subquery, void *arg) - { - if (walk_args(processor, walk_subquery, arg)) - return true; - return (this->*processor)(arg); - } - Item *transform(THD *thd, Item_transformer transformer, uchar *arg); - bool eval_not_null_tables(void *opt_arg); - bool find_not_null_fields(table_map allowed); - - uint cols() const { return arg_count; } - Item* element_index(uint i) { return args[i]; } - Item** addr(uint i) { return args + i; } - bool check_cols(uint c); - bool null_inside() { return with_null; }; - void bring_value(); - - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { - Item_args::propagate_equal_fields(thd, Context_identity(), cond); - return this; - } - - bool excl_dep_on_table(table_map tab_map) - { - return Item_args::excl_dep_on_table(tab_map); - } - - bool excl_dep_on_grouping_fields(st_select_lex *sel) - { - return Item_args::excl_dep_on_grouping_fields(sel); - } - - bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) - { - return Item_args::excl_dep_on_in_subq_left_part(subq_pred); - } - - bool check_vcol_func_processor(void *arg) {return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *build_clone(THD *thd); -}; - -#endif /* ITEM_ROW_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_strfunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_strfunc.h deleted file mode 100644 index 1ae62a4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_strfunc.h +++ /dev/null @@ -1,1871 +0,0 @@ -#ifndef ITEM_STRFUNC_INCLUDED -#define ITEM_STRFUNC_INCLUDED - -/* - Copyright (c) 2000, 2011, Oracle and/or its affiliates. - Copyright (c) 2009, 2019, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* This file defines all string functions */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -extern size_t username_char_length; - -class Item_str_func :public Item_func -{ -protected: - /** - Sets the result value of the function an empty string, using the current - character set. No memory is allocated. - @retval A pointer to the str_value member. - */ - virtual String *make_empty_result() - { - /* - Reset string length to an empty string. We don't use str_value.set() as - we don't want to free and potentially have to reallocate the buffer - for each call. - */ - str_value.length(0); - str_value.set_charset(collation.collation); - return &str_value; - } -public: - Item_str_func(THD *thd): Item_func(thd) { decimals=NOT_FIXED_DEC; } - Item_str_func(THD *thd, Item *a): Item_func(thd, a) {decimals=NOT_FIXED_DEC; } - Item_str_func(THD *thd, Item *a, Item *b): - Item_func(thd, a, b) { decimals=NOT_FIXED_DEC; } - Item_str_func(THD *thd, Item *a, Item *b, Item *c): - Item_func(thd, a, b, c) { decimals=NOT_FIXED_DEC; } - Item_str_func(THD *thd, Item *a, Item *b, Item *c, Item *d): - Item_func(thd, a, b, c, d) { decimals=NOT_FIXED_DEC; } - Item_str_func(THD *thd, Item *a, Item *b, Item *c, Item *d, Item* e): - Item_func(thd, a, b, c, d, e) { decimals=NOT_FIXED_DEC; } - Item_str_func(THD *thd, List &list): - Item_func(thd, list) { decimals=NOT_FIXED_DEC; } - longlong val_int(); - double val_real(); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { return get_date_from_string(thd, ltime, fuzzydate); } - const Type_handler *type_handler() const { return string_type_handler(); } - void left_right_max_length(); - bool fix_fields(THD *thd, Item **ref); -}; - - - -/* - Functions that return values with ASCII repertoire -*/ -class Item_str_ascii_func :public Item_str_func -{ - String ascii_buf; -public: - Item_str_ascii_func(THD *thd): Item_str_func(thd) {} - Item_str_ascii_func(THD *thd, Item *a): Item_str_func(thd, a) {} - Item_str_ascii_func(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} - Item_str_ascii_func(THD *thd, Item *a, Item *b, Item *c): - Item_str_func(thd, a, b, c) {} - String *val_str(String *str) - { - return val_str_from_val_str_ascii(str, &ascii_buf); - } - String *val_str_ascii(String *)= 0; -}; - - -/** - Functions that return a checksum or a hash of the argument, - or somehow else encode or decode the argument, - returning an ASCII-repertoire string. -*/ -class Item_str_ascii_checksum_func: public Item_str_ascii_func -{ -public: - Item_str_ascii_checksum_func(THD *thd, Item *a) - :Item_str_ascii_func(thd, a) { } - Item_str_ascii_checksum_func(THD *thd, Item *a, Item *b) - :Item_str_ascii_func(thd, a, b) { } - bool eq(const Item *item, bool binary_cmp) const - { - // Always use binary argument comparison: MD5('x') != MD5('X') - return Item_func::eq(item, true); - } -}; - - -/** - Functions that return a checksum or a hash of the argument, - or somehow else encode or decode the argument, - returning a binary string. -*/ -class Item_str_binary_checksum_func: public Item_str_func -{ -public: - Item_str_binary_checksum_func(THD *thd, Item *a) - :Item_str_func(thd, a) { } - Item_str_binary_checksum_func(THD *thd, Item *a, Item *b) - :Item_str_func(thd, a, b) { } - bool eq(const Item *item, bool binary_cmp) const - { - /* - Always use binary argument comparison: - FROM_BASE64('test') != FROM_BASE64('TEST') - */ - return Item_func::eq(item, true); - } -}; - - -class Item_func_md5 :public Item_str_ascii_checksum_func -{ -public: - Item_func_md5(THD *thd, Item *a): Item_str_ascii_checksum_func(thd, a) {} - String *val_str_ascii(String *); - bool fix_length_and_dec() - { - fix_length_and_charset(32, default_charset()); - return FALSE; - } - const char *func_name() const { return "md5"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_sha :public Item_str_ascii_checksum_func -{ -public: - Item_func_sha(THD *thd, Item *a): Item_str_ascii_checksum_func(thd, a) {} - String *val_str_ascii(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "sha"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_sha2 :public Item_str_ascii_checksum_func -{ -public: - Item_func_sha2(THD *thd, Item *a, Item *b) - :Item_str_ascii_checksum_func(thd, a, b) {} - String *val_str_ascii(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "sha2"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_to_base64 :public Item_str_ascii_checksum_func -{ - String tmp_value; -public: - Item_func_to_base64(THD *thd, Item *a) - :Item_str_ascii_checksum_func(thd, a) {} - String *val_str_ascii(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "to_base64"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_from_base64 :public Item_str_binary_checksum_func -{ - String tmp_value; -public: - Item_func_from_base64(THD *thd, Item *a) - :Item_str_binary_checksum_func(thd, a) { } - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "from_base64"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -#include - -class Item_aes_crypt :public Item_str_binary_checksum_func -{ - enum { AES_KEY_LENGTH = 128 }; - void create_key(String *user_key, uchar* key); - -protected: - int what; - String tmp_value; -public: - Item_aes_crypt(THD *thd, Item *a, Item *b) - :Item_str_binary_checksum_func(thd, a, b) {} - String *val_str(String *); -}; - -class Item_func_aes_encrypt :public Item_aes_crypt -{ -public: - Item_func_aes_encrypt(THD *thd, Item *a, Item *b) - :Item_aes_crypt(thd, a, b) {} - bool fix_length_and_dec(); - const char *func_name() const { return "aes_encrypt"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_aes_decrypt :public Item_aes_crypt -{ -public: - Item_func_aes_decrypt(THD *thd, Item *a, Item *b): - Item_aes_crypt(thd, a, b) {} - bool fix_length_and_dec(); - const char *func_name() const { return "aes_decrypt"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_concat :public Item_str_func -{ -protected: - String tmp_value; - /* - Append a non-NULL value to the result. - @param [IN] thd - The current thread. - @param [IN/OUT] res - The current val_str() return value. - @param [IN] app - The value to be appended. - @retval - false on success, true on error - */ - bool append_value(THD *thd, String *res, const String *app); - bool realloc_result(String *str, uint length) const; -public: - Item_func_concat(THD *thd, List &list): Item_str_func(thd, list) {} - Item_func_concat(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "concat"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - This class handles the || operator in sql_mode=ORACLE. - Unlike the traditional MariaDB concat(), it treats NULL arguments as ''. -*/ -class Item_func_concat_operator_oracle :public Item_func_concat -{ -public: - Item_func_concat_operator_oracle(THD *thd, List &list) - :Item_func_concat(thd, list) - { } - Item_func_concat_operator_oracle(THD *thd, Item *a, Item *b) - :Item_func_concat(thd, a, b) - { } - String *val_str(String *); - const char *func_name() const { return "concat_operator_oracle"; } - Item *get_copy(THD *thd) - { - return get_item_copy(thd, this); - } -}; - - -class Item_func_decode_histogram :public Item_str_func -{ -public: - Item_func_decode_histogram(THD *thd, Item *a, Item *b): - Item_str_func(thd, a, b) {} - String *val_str(String *); - bool fix_length_and_dec() - { - collation.set(system_charset_info); - max_length= MAX_BLOB_WIDTH; - maybe_null= 1; - return FALSE; - } - const char *func_name() const { return "decode_histogram"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_concat_ws :public Item_str_func -{ - String tmp_value; -public: - Item_func_concat_ws(THD *thd, List &list): Item_str_func(thd, list) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "concat_ws"; } - table_map not_null_tables() const { return 0; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_reverse :public Item_str_func -{ - String tmp_value; -public: - Item_func_reverse(THD *thd, Item *a): Item_str_func(thd, a) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "reverse"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_replace :public Item_str_func -{ - String tmp_value,tmp_value2; -public: - Item_func_replace(THD *thd, Item *org, Item *find, Item *replace): - Item_str_func(thd, org, find, replace) {} - String *val_str(String *to) { return val_str_internal(to, NULL); }; - bool fix_length_and_dec(); - String *val_str_internal(String *str, String *empty_string_for_null); - const char *func_name() const { return "replace"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_replace_oracle :public Item_func_replace -{ - String tmp_emtpystr; -public: - Item_func_replace_oracle(THD *thd, Item *org, Item *find, Item *replace): - Item_func_replace(thd, org, find, replace) {} - String *val_str(String *to) { return val_str_internal(to, &tmp_emtpystr); }; - const char *func_name() const { return "replace_oracle"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_regexp_replace :public Item_str_func -{ - Regexp_processor_pcre re; - bool append_replacement(String *str, - const LEX_CSTRING *source, - const LEX_CSTRING *replace); -public: - Item_func_regexp_replace(THD *thd, Item *a, Item *b, Item *c): - Item_str_func(thd, a, b, c) - {} - void cleanup() - { - DBUG_ENTER("Item_func_regexp_replace::cleanup"); - Item_str_func::cleanup(); - re.cleanup(); - DBUG_VOID_RETURN; - } - String *val_str(String *str); - bool fix_length_and_dec(); - const char *func_name() const { return "regexp_replace"; } - Item *get_copy(THD *thd) { return 0;} -}; - - -class Item_func_regexp_substr :public Item_str_func -{ - Regexp_processor_pcre re; -public: - Item_func_regexp_substr(THD *thd, Item *a, Item *b): - Item_str_func(thd, a, b) - {} - void cleanup() - { - DBUG_ENTER("Item_func_regexp_substr::cleanup"); - Item_str_func::cleanup(); - re.cleanup(); - DBUG_VOID_RETURN; - } - String *val_str(String *str); - bool fix_length_and_dec(); - const char *func_name() const { return "regexp_substr"; } - Item *get_copy(THD *thd) { return 0; } -}; - - -class Item_func_insert :public Item_str_func -{ - String tmp_value; -public: - Item_func_insert(THD *thd, Item *org, Item *start, Item *length, - Item *new_str): - Item_str_func(thd, org, start, length, new_str) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "insert"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_str_conv :public Item_str_func -{ -protected: - uint multiply; - my_charset_conv_case converter; - String tmp_value; -public: - Item_str_conv(THD *thd, Item *item): Item_str_func(thd, item) {} - String *val_str(String *); -}; - - -class Item_func_lcase :public Item_str_conv -{ -public: - Item_func_lcase(THD *thd, Item *item): Item_str_conv(thd, item) {} - const char *func_name() const { return "lcase"; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_ucase :public Item_str_conv -{ -public: - Item_func_ucase(THD *thd, Item *item): Item_str_conv(thd, item) {} - const char *func_name() const { return "ucase"; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_left :public Item_str_func -{ - String tmp_value; -public: - Item_func_left(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "left"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_right :public Item_str_func -{ - String tmp_value; -public: - Item_func_right(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "right"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_substr :public Item_str_func -{ - String tmp_value; -protected: - virtual longlong get_position() { return args[1]->val_int(); } -public: - Item_func_substr(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} - Item_func_substr(THD *thd, Item *a, Item *b, Item *c): - Item_str_func(thd, a, b, c) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "substr"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_substr_oracle :public Item_func_substr -{ -protected: - longlong get_position() - { longlong pos= args[1]->val_int(); return pos == 0 ? 1 : pos; } - String *make_empty_result() - { null_value= 1; return NULL; } -public: - Item_func_substr_oracle(THD *thd, Item *a, Item *b): - Item_func_substr(thd, a, b) {} - Item_func_substr_oracle(THD *thd, Item *a, Item *b, Item *c): - Item_func_substr(thd, a, b, c) {} - bool fix_length_and_dec() - { - bool res= Item_func_substr::fix_length_and_dec(); - maybe_null= true; - return res; - } - const char *func_name() const { return "substr_oracle"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_substr_index :public Item_str_func -{ - String tmp_value; -public: - Item_func_substr_index(THD *thd, Item *a,Item *b,Item *c): - Item_str_func(thd, a, b, c) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "substring_index"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - -}; - - -class Item_func_trim :public Item_str_func -{ -protected: - String tmp_value; - String remove; - String *trimmed_value(String *res, uint32 offset, uint32 length) - { - if (length == 0) - return make_empty_result(); - - tmp_value.set(*res, offset, length); - /* - Make sure to return correct charset and collation: - TRIM(0x000000 FROM _ucs2 0x0061) - should set charset to "binary" rather than to "ucs2". - */ - tmp_value.set_charset(collation.collation); - return &tmp_value; - } - String *non_trimmed_value(String *res) - { - return trimmed_value(res, 0, res->length()); - } - virtual const char *func_name_ext() const { return ""; } -public: - Item_func_trim(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} - Item_func_trim(THD *thd, Item *a): Item_str_func(thd, a) {} - Sql_mode_dependency value_depends_on_sql_mode() const; - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "trim"; } - void print(String *str, enum_query_type query_type); - virtual const char *mode_name() const { return "both"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_trim_oracle :public Item_func_trim -{ -protected: - String *make_empty_result() - { null_value= 1; return NULL; } - const char *func_name_ext() const { return "_oracle"; } -public: - Item_func_trim_oracle(THD *thd, Item *a, Item *b): - Item_func_trim(thd, a, b) {} - Item_func_trim_oracle(THD *thd, Item *a): Item_func_trim(thd, a) {} - const char *func_name() const { return "trim_oracle"; } - bool fix_length_and_dec() - { - bool res= Item_func_trim::fix_length_and_dec(); - maybe_null= true; - return res; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_ltrim :public Item_func_trim -{ -public: - Item_func_ltrim(THD *thd, Item *a, Item *b): Item_func_trim(thd, a, b) {} - Item_func_ltrim(THD *thd, Item *a): Item_func_trim(thd, a) {} - Sql_mode_dependency value_depends_on_sql_mode() const - { - return Item_func::value_depends_on_sql_mode(); - } - String *val_str(String *); - const char *func_name() const { return "ltrim"; } - const char *mode_name() const { return "leading"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_ltrim_oracle :public Item_func_ltrim -{ -protected: - String *make_empty_result() - { null_value= 1; return NULL; } - const char *func_name_ext() const { return "_oracle"; } -public: - Item_func_ltrim_oracle(THD *thd, Item *a, Item *b): - Item_func_ltrim(thd, a, b) {} - Item_func_ltrim_oracle(THD *thd, Item *a): Item_func_ltrim(thd, a) {} - const char *func_name() const { return "ltrim_oracle"; } - bool fix_length_and_dec() - { - bool res= Item_func_ltrim::fix_length_and_dec(); - maybe_null= true; - return res; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_rtrim :public Item_func_trim -{ -public: - Item_func_rtrim(THD *thd, Item *a, Item *b): Item_func_trim(thd, a, b) {} - Item_func_rtrim(THD *thd, Item *a): Item_func_trim(thd, a) {} - String *val_str(String *); - const char *func_name() const { return "rtrim"; } - const char *mode_name() const { return "trailing"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_rtrim_oracle :public Item_func_rtrim -{ -protected: - String *make_empty_result() - { null_value= 1; return NULL; } - const char *func_name_ext() const { return "_oracle"; } -public: - Item_func_rtrim_oracle(THD *thd, Item *a, Item *b): - Item_func_rtrim(thd, a, b) {} - Item_func_rtrim_oracle(THD *thd, Item *a): Item_func_rtrim(thd, a) {} - const char *func_name() const { return "rtrim_oracle"; } - bool fix_length_and_dec() - { - bool res= Item_func_rtrim::fix_length_and_dec(); - maybe_null= true; - return res; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* - Item_func_password -- new (4.1.1) PASSWORD() function implementation. - Returns strcat('*', octet2hex(sha1(sha1(password)))). '*' stands for new - password format, sha1(sha1(password) is so-called hash_stage2 value. - Length of returned string is always 41 byte. To find out how entire - authentication procedure works, see comments in password.c. -*/ - -class Item_func_password :public Item_str_ascii_checksum_func -{ -public: - enum PW_Alg {OLD, NEW}; -private: - char tmp_value[SCRAMBLED_PASSWORD_CHAR_LENGTH+1]; - enum PW_Alg alg; - bool deflt; -public: - Item_func_password(THD *thd, Item *a): - Item_str_ascii_checksum_func(thd, a), alg(NEW), deflt(1) {} - Item_func_password(THD *thd, Item *a, PW_Alg al): - Item_str_ascii_checksum_func(thd, a), alg(al), deflt(0) {} - String *val_str_ascii(String *str); - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec() - { - fix_length_and_charset((alg == 1 ? - SCRAMBLED_PASSWORD_CHAR_LENGTH : - SCRAMBLED_PASSWORD_CHAR_LENGTH_323), - default_charset()); - return FALSE; - } - const char *func_name() const { return ((deflt || alg == 1) ? - "password" : "old_password"); } - static char *alloc(THD *thd, const char *password, size_t pass_len, - enum PW_Alg al); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - - -class Item_func_des_encrypt :public Item_str_binary_checksum_func -{ - String tmp_value,tmp_arg; -public: - Item_func_des_encrypt(THD *thd, Item *a) - :Item_str_binary_checksum_func(thd, a) {} - Item_func_des_encrypt(THD *thd, Item *a, Item *b) - :Item_str_binary_checksum_func(thd, a, b) {} - String *val_str(String *); - bool fix_length_and_dec() - { - maybe_null=1; - /* 9 = MAX ((8- (arg_len % 8)) + 1) */ - max_length = args[0]->max_length + 9; - return FALSE; - } - const char *func_name() const { return "des_encrypt"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_des_decrypt :public Item_str_binary_checksum_func -{ - String tmp_value; -public: - Item_func_des_decrypt(THD *thd, Item *a) - :Item_str_binary_checksum_func(thd, a) {} - Item_func_des_decrypt(THD *thd, Item *a, Item *b) - :Item_str_binary_checksum_func(thd, a, b) {} - String *val_str(String *); - bool fix_length_and_dec() - { - maybe_null=1; - /* 9 = MAX ((8- (arg_len % 8)) + 1) */ - max_length= args[0]->max_length; - if (max_length >= 9U) - max_length-= 9U; - return FALSE; - } - const char *func_name() const { return "des_decrypt"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - QQ: Item_func_encrypt should derive from Item_str_ascii_checksum_func. - However, it should be fixed to handle UCS2, UTF16, UTF32 properly first, - as the underlying crypt() call expects a null-terminated input string. -*/ -class Item_func_encrypt :public Item_str_binary_checksum_func -{ - String tmp_value; - - /* Encapsulate common constructor actions */ - void constructor_helper() - { - collation.set(&my_charset_bin); - } -public: - Item_func_encrypt(THD *thd, Item *a): Item_str_binary_checksum_func(thd, a) - { - constructor_helper(); - } - Item_func_encrypt(THD *thd, Item *a, Item *b) - :Item_str_binary_checksum_func(thd, a, b) - { - constructor_helper(); - } - String *val_str(String *); - bool fix_length_and_dec() { maybe_null=1; max_length = 13; return FALSE; } - const char *func_name() const { return "encrypt"; } - bool check_vcol_func_processor(void *arg) - { - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -#include "sql_crypt.h" - - -class Item_func_encode :public Item_str_binary_checksum_func -{ -private: - /** Whether the PRNG has already been seeded. */ - bool seeded; -protected: - SQL_CRYPT sql_crypt; -public: - Item_func_encode(THD *thd, Item *a, Item *seed_arg): - Item_str_binary_checksum_func(thd, a, seed_arg) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "encode"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -protected: - virtual void crypto_transform(String *); -private: - /** Provide a seed for the PRNG sequence. */ - bool seed(); -}; - - -class Item_func_decode :public Item_func_encode -{ -public: - Item_func_decode(THD *thd, Item *a, Item *seed_arg): Item_func_encode(thd, a, seed_arg) {} - const char *func_name() const { return "decode"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -protected: - void crypto_transform(String *); -}; - - -class Item_func_sysconst :public Item_str_func -{ -public: - Item_func_sysconst(THD *thd): Item_str_func(thd) - { collation.set(system_charset_info,DERIVATION_SYSCONST); } - Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs); - /* - Used to create correct Item name in new converted item in - safe_charset_converter, return string representation of this function - call - */ - virtual const char *fully_qualified_func_name() const = 0; - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(fully_qualified_func_name(), arg, - VCOL_SESSION_FUNC); - } - bool const_item() const; -}; - - -class Item_func_database :public Item_func_sysconst -{ -public: - Item_func_database(THD *thd): Item_func_sysconst(thd) {} - String *val_str(String *); - bool fix_length_and_dec() - { - max_length= MAX_FIELD_NAME * system_charset_info->mbmaxlen; - maybe_null=1; - return FALSE; - } - const char *func_name() const { return "database"; } - const char *fully_qualified_func_name() const { return "database()"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_sqlerrm :public Item_func_sysconst -{ -public: - Item_func_sqlerrm(THD *thd): Item_func_sysconst(thd) {} - String *val_str(String *); - const char *func_name() const { return "SQLERRM"; } - const char *fully_qualified_func_name() const { return "SQLERRM"; } - void print(String *str, enum_query_type query_type) - { - str->append(func_name()); - } - bool fix_length_and_dec() - { - max_length= 512 * system_charset_info->mbmaxlen; - null_value= maybe_null= false; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_user :public Item_func_sysconst -{ -protected: - bool init (const char *user, const char *host); - -public: - Item_func_user(THD *thd): Item_func_sysconst(thd) - { - str_value.set("", 0, system_charset_info); - } - String *val_str(String *) - { - DBUG_ASSERT(fixed == 1); - return (null_value ? 0 : &str_value); - } - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec() - { - max_length= (uint32) (username_char_length + - HOSTNAME_LENGTH + 1) * SYSTEM_CHARSET_MBMAXLEN; - return FALSE; - } - const char *func_name() const { return "user"; } - const char *fully_qualified_func_name() const { return "user()"; } - int save_in_field(Field *field, bool no_conversions) - { - return save_str_value_in_field(field, &str_value); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_current_user :public Item_func_user -{ - Name_resolution_context *context; - -public: - Item_func_current_user(THD *thd, Name_resolution_context *context_arg): - Item_func_user(thd), context(context_arg) {} - bool fix_fields(THD *thd, Item **ref); - const char *func_name() const { return "current_user"; } - const char *fully_qualified_func_name() const { return "current_user()"; } - bool check_vcol_func_processor(void *arg) - { - context= 0; - return mark_unsupported_function(fully_qualified_func_name(), arg, - VCOL_SESSION_FUNC); - } -}; - - -class Item_func_current_role :public Item_func_sysconst -{ - Name_resolution_context *context; - -public: - Item_func_current_role(THD *thd, Name_resolution_context *context_arg): - Item_func_sysconst(thd), context(context_arg) {} - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec() - { - max_length= (uint32) username_char_length * SYSTEM_CHARSET_MBMAXLEN; - return FALSE; - } - int save_in_field(Field *field, bool no_conversions) - { return save_str_value_in_field(field, &str_value); } - const char *func_name() const { return "current_role"; } - const char *fully_qualified_func_name() const { return "current_role()"; } - String *val_str(String *) - { - DBUG_ASSERT(fixed == 1); - return null_value ? NULL : &str_value; - } - bool check_vcol_func_processor(void *arg) - { - - context= 0; - return mark_unsupported_function(fully_qualified_func_name(), arg, - VCOL_SESSION_FUNC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_soundex :public Item_str_func -{ - String tmp_value; -public: - Item_func_soundex(THD *thd, Item *a): Item_str_func(thd, a) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "soundex"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_elt :public Item_str_func -{ -public: - Item_func_elt(THD *thd, List &list): Item_str_func(thd, list) {} - double val_real(); - longlong val_int(); - String *val_str(String *str); - bool fix_length_and_dec(); - const char *func_name() const { return "elt"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_make_set :public Item_str_func -{ - String tmp_str; - -public: - Item_func_make_set(THD *thd, List &list): Item_str_func(thd, list) {} - String *val_str(String *str); - bool fix_length_and_dec(); - const char *func_name() const { return "make_set"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_format :public Item_str_ascii_func -{ - const MY_LOCALE *locale; -public: - Item_func_format(THD *thd, Item *org, Item *dec): - Item_str_ascii_func(thd, org, dec) {} - Item_func_format(THD *thd, Item *org, Item *dec, Item *lang): - Item_str_ascii_func(thd, org, dec, lang) {} - - String *val_str_ascii(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "format"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_char :public Item_str_func -{ -public: - Item_func_char(THD *thd, List &list): Item_str_func(thd, list) - { collation.set(&my_charset_bin); } - Item_func_char(THD *thd, List &list, CHARSET_INFO *cs): - Item_str_func(thd, list) - { collation.set(cs); } - Item_func_char(THD *thd, Item *arg1, CHARSET_INFO *cs): - Item_str_func(thd, arg1) - { collation.set(cs); } - String *val_str(String *); - void append_char(String * str, int32 num); - bool fix_length_and_dec() - { - max_length= arg_count * 4; - return FALSE; - } - const char *func_name() const { return "char"; } - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_chr :public Item_func_char -{ -public: - Item_func_chr(THD *thd, Item *arg1, CHARSET_INFO *cs): - Item_func_char(thd, arg1, cs) {} - String *val_str(String *); - bool fix_length_and_dec() - { - max_length= 4; - return FALSE; - } - const char *func_name() const { return "chr"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_repeat :public Item_str_func -{ - String tmp_value; -public: - Item_func_repeat(THD *thd, Item *arg1, Item *arg2): - Item_str_func(thd, arg1, arg2) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "repeat"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_space :public Item_str_func -{ -public: - Item_func_space(THD *thd, Item *arg1): Item_str_func(thd, arg1) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "space"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_binlog_gtid_pos :public Item_str_func -{ -public: - Item_func_binlog_gtid_pos(THD *thd, Item *arg1, Item *arg2): - Item_str_func(thd, arg1, arg2) {} - String *val_str(String *); - bool fix_length_and_dec(); - const char *func_name() const { return "binlog_gtid_pos"; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_pad: public Item_str_func -{ -protected: - String tmp_value, pad_str; -public: - Item_func_pad(THD *thd, Item *arg1, Item *arg2, Item *arg3): - Item_str_func(thd, arg1, arg2, arg3) {} - Item_func_pad(THD *thd, Item *arg1, Item *arg2): - Item_str_func(thd, arg1, arg2) {} - bool fix_length_and_dec(); -}; - - -class Item_func_rpad :public Item_func_pad -{ -public: - Item_func_rpad(THD *thd, Item *arg1, Item *arg2, Item *arg3): - Item_func_pad(thd, arg1, arg2, arg3) {} - Item_func_rpad(THD *thd, Item *arg1, Item *arg2): - Item_func_pad(thd, arg1, arg2) {} - String *val_str(String *); - const char *func_name() const { return "rpad"; } - Sql_mode_dependency value_depends_on_sql_mode() const; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_rpad_oracle :public Item_func_rpad -{ - String *make_empty_result() - { null_value= 1; return NULL; } -public: - Item_func_rpad_oracle(THD *thd, Item *arg1, Item *arg2, Item *arg3): - Item_func_rpad(thd, arg1, arg2, arg3) {} - Item_func_rpad_oracle(THD *thd, Item *arg1, Item *arg2): - Item_func_rpad(thd, arg1, arg2) {} - bool fix_length_and_dec() - { - bool res= Item_func_rpad::fix_length_and_dec(); - maybe_null= true; - return res; - } - const char *func_name() const { return "rpad_oracle"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_lpad :public Item_func_pad -{ -public: - Item_func_lpad(THD *thd, Item *arg1, Item *arg2, Item *arg3): - Item_func_pad(thd, arg1, arg2, arg3) {} - Item_func_lpad(THD *thd, Item *arg1, Item *arg2): - Item_func_pad(thd, arg1, arg2) {} - String *val_str(String *); - const char *func_name() const { return "lpad"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_lpad_oracle :public Item_func_lpad -{ - String *make_empty_result() - { null_value= 1; return NULL; } -public: - Item_func_lpad_oracle(THD *thd, Item *arg1, Item *arg2, Item *arg3): - Item_func_lpad(thd, arg1, arg2, arg3) {} - Item_func_lpad_oracle(THD *thd, Item *arg1, Item *arg2): - Item_func_lpad(thd, arg1, arg2) {} - bool fix_length_and_dec() - { - bool res= Item_func_lpad::fix_length_and_dec(); - maybe_null= true; - return res; - } - const char *func_name() const { return "lpad_oracle"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_conv :public Item_str_func -{ -public: - Item_func_conv(THD *thd, Item *a, Item *b, Item *c): - Item_str_func(thd, a, b, c) {} - const char *func_name() const { return "conv"; } - String *val_str(String *); - bool fix_length_and_dec() - { - collation.set(default_charset()); - fix_char_length(64); - maybe_null= 1; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_hex :public Item_str_ascii_checksum_func -{ -protected: - String tmp_value; - /* - Calling arg[0]->type_handler() can be expensive on every row. - It's a virtual method, and in case if args[0] is a complex Item, - its type_handler() can call more virtual methods. - So let's cache it during fix_length_and_dec(). - */ - const Type_handler *m_arg0_type_handler; -public: - Item_func_hex(THD *thd, Item *a): - Item_str_ascii_checksum_func(thd, a), m_arg0_type_handler(NULL) {} - const char *func_name() const { return "hex"; } - String *val_str_ascii_from_val_int(String *str); - String *val_str_ascii_from_val_real(String *str); - String *val_str_ascii_from_val_str(String *str); - String *val_str_ascii(String *str) - { - DBUG_ASSERT(fixed); - return m_arg0_type_handler->Item_func_hex_val_str_ascii(this, str); - } - bool fix_length_and_dec() - { - collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII); - decimals=0; - fix_char_length(args[0]->max_length * 2); - m_arg0_type_handler= args[0]->type_handler(); - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_unhex :public Item_str_func -{ - String tmp_value; -public: - Item_func_unhex(THD *thd, Item *a): Item_str_func(thd, a) - { - /* there can be bad hex strings */ - maybe_null= 1; - } - const char *func_name() const { return "unhex"; } - String *val_str(String *); - bool fix_length_and_dec() - { - collation.set(&my_charset_bin); - decimals=0; - max_length=(1+args[0]->max_length)/2; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -#ifndef DBUG_OFF -class Item_func_like_range :public Item_str_func -{ -protected: - String min_str; - String max_str; - const bool is_min; -public: - Item_func_like_range(THD *thd, Item *a, Item *b, bool is_min_arg): - Item_str_func(thd, a, b), is_min(is_min_arg) - { maybe_null= 1; } - String *val_str(String *); - bool fix_length_and_dec() - { - collation.set(args[0]->collation); - decimals=0; - max_length= MAX_BLOB_WIDTH; - return FALSE; - } -}; - - -class Item_func_like_range_min :public Item_func_like_range -{ -public: - Item_func_like_range_min(THD *thd, Item *a, Item *b): - Item_func_like_range(thd, a, b, true) { } - const char *func_name() const { return "like_range_min"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_like_range_max :public Item_func_like_range -{ -public: - Item_func_like_range_max(THD *thd, Item *a, Item *b): - Item_func_like_range(thd, a, b, false) { } - const char *func_name() const { return "like_range_max"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; -#endif - - -class Item_func_binary :public Item_str_func -{ -public: - Item_func_binary(THD *thd, Item *a): Item_str_func(thd, a) {} - String *val_str(String *a) - { - DBUG_ASSERT(fixed == 1); - String *tmp=args[0]->val_str(a); - null_value=args[0]->null_value; - if (tmp) - tmp->set_charset(&my_charset_bin); - return tmp; - } - bool fix_length_and_dec() - { - collation.set(&my_charset_bin); - max_length=args[0]->max_length; - return FALSE; - } - void print(String *str, enum_query_type query_type); - const char *func_name() const { return "cast_as_binary"; } - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_load_file :public Item_str_func -{ - String tmp_value; -public: - Item_load_file(THD *thd, Item *a): Item_str_func(thd, a) {} - String *val_str(String *); - const char *func_name() const { return "load_file"; } - bool fix_length_and_dec() - { - collation.set(&my_charset_bin, DERIVATION_COERCIBLE); - maybe_null=1; - max_length=MAX_BLOB_WIDTH; - return FALSE; - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_export_set: public Item_str_func -{ - public: - Item_func_export_set(THD *thd, Item *a, Item *b, Item* c): - Item_str_func(thd, a, b, c) {} - Item_func_export_set(THD *thd, Item *a, Item *b, Item* c, Item* d): - Item_str_func(thd, a, b, c, d) {} - Item_func_export_set(THD *thd, Item *a, Item *b, Item* c, Item* d, Item* e): - Item_str_func(thd, a, b, c, d, e) {} - String *val_str(String *str); - bool fix_length_and_dec(); - const char *func_name() const { return "export_set"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_quote :public Item_str_func -{ - String tmp_value; -public: - Item_func_quote(THD *thd, Item *a): Item_str_func(thd, a) {} - const char *func_name() const { return "quote"; } - String *val_str(String *); - bool fix_length_and_dec() - { - collation.set(args[0]->collation); - ulonglong max_result_length= (ulonglong) args[0]->max_length * 2 + - 2 * collation.collation->mbmaxlen; - max_length= (uint32) MY_MIN(max_result_length, MAX_BLOB_WIDTH); - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_conv_charset :public Item_str_func -{ - bool use_cached_value; - String tmp_value; -public: - bool safe; - Item_func_conv_charset(THD *thd, Item *a, CHARSET_INFO *cs): - Item_str_func(thd, a) - { - collation.set(cs, DERIVATION_IMPLICIT); - use_cached_value= 0; safe= 0; - } - Item_func_conv_charset(THD *thd, Item *a, CHARSET_INFO *cs, bool cache_if_const): - Item_str_func(thd, a) - { - collation.set(cs, DERIVATION_IMPLICIT); - if (cache_if_const && args[0]->const_item() && !args[0]->is_expensive()) - { - uint errors= 0; - String tmp, *str= args[0]->val_str(&tmp); - if (!str || str_value.copy(str->ptr(), str->length(), - str->charset(), cs, &errors)) - null_value= 1; - use_cached_value= 1; - str_value.mark_as_const(); - safe= (errors == 0); - } - else - { - use_cached_value= 0; - /* - Conversion from and to "binary" is safe. - Conversion to Unicode is safe. - Conversion from an expression with the ASCII repertoire - to any character set that can store characters U+0000..U+007F - is safe: - - All supported multibyte character sets can store U+0000..U+007F - - All supported 7bit character sets can store U+0000..U+007F - except those marked with MY_CS_NONASCII (e.g. swe7). - Other kind of conversions are potentially lossy. - */ - safe= (args[0]->collation.collation == &my_charset_bin || - cs == &my_charset_bin || - (cs->state & MY_CS_UNICODE) || - (args[0]->collation.repertoire == MY_REPERTOIRE_ASCII && - (cs->mbmaxlen > 1 || !(cs->state & MY_CS_NONASCII)))); - } - } - bool is_json_type() { return args[0]->is_json_type(); } - String *val_str(String *); - longlong val_int() - { - if (args[0]->result_type() == STRING_RESULT) - return Item_str_func::val_int(); - longlong res= args[0]->val_int(); - if ((null_value= args[0]->null_value)) - return 0; - return res; - } - double val_real() - { - if (args[0]->result_type() == STRING_RESULT) - return Item_str_func::val_real(); - double res= args[0]->val_real(); - if ((null_value= args[0]->null_value)) - return 0; - return res; - } - my_decimal *val_decimal(my_decimal *d) - { - if (args[0]->result_type() == STRING_RESULT) - return Item_str_func::val_decimal(d); - my_decimal *res= args[0]->val_decimal(d); - if ((null_value= args[0]->null_value)) - return NULL; - return res; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - if (args[0]->result_type() == STRING_RESULT) - return Item_str_func::get_date(thd, ltime, fuzzydate); - bool res= args[0]->get_date(thd, ltime, fuzzydate); - if ((null_value= args[0]->null_value)) - return 1; - return res; - } - bool fix_length_and_dec(); - const char *func_name() const { return "convert"; } - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_set_collation :public Item_str_func -{ - CHARSET_INFO *m_set_collation; -public: - Item_func_set_collation(THD *thd, Item *a, CHARSET_INFO *set_collation): - Item_str_func(thd, a), m_set_collation(set_collation) {} - String *val_str(String *); - bool fix_length_and_dec(); - bool eq(const Item *item, bool binary_cmp) const; - const char *func_name() const { return "collate"; } - enum precedence precedence() const { return COLLATE_PRECEDENCE; } - enum Functype functype() const { return COLLATE_FUNC; } - void print(String *str, enum_query_type query_type); - Item_field *field_for_view_update() - { - /* this function is transparent for view updating */ - return args[0]->field_for_view_update(); - } - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_expr_str_metadata :public Item_str_func -{ -public: - Item_func_expr_str_metadata(THD *thd, Item *a): Item_str_func(thd, a) { } - bool fix_length_and_dec() - { - collation.set(system_charset_info); - max_length= 64 * collation.collation->mbmaxlen; // should be enough - maybe_null= 0; - return FALSE; - }; - table_map not_null_tables() const { return 0; } - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { return this; } - bool const_item() const { return true; } -}; - - -class Item_func_charset :public Item_func_expr_str_metadata -{ -public: - Item_func_charset(THD *thd, Item *a) - :Item_func_expr_str_metadata(thd, a) { } - String *val_str(String *); - const char *func_name() const { return "charset"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_collation :public Item_func_expr_str_metadata -{ -public: - Item_func_collation(THD *thd, Item *a) - :Item_func_expr_str_metadata(thd, a) {} - String *val_str(String *); - const char *func_name() const { return "collation"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_weight_string :public Item_str_func -{ - String tmp_value; - uint flags; - uint nweights; - uint result_length; -public: - Item_func_weight_string(THD *thd, Item *a, uint result_length_arg, - uint nweights_arg, uint flags_arg): - Item_str_func(thd, a) - { - nweights= nweights_arg; - flags= flags_arg; - result_length= result_length_arg; - } - const char *func_name() const { return "weight_string"; } - String *val_str(String *); - bool fix_length_and_dec(); - bool eq(const Item *item, bool binary_cmp) const - { - if (!Item_str_func::eq(item, binary_cmp)) - return false; - Item_func_weight_string *that= (Item_func_weight_string *)item; - return this->flags == that->flags && - this->nweights == that->nweights && - this->result_length == that->result_length; - } - Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) - { return this; } - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_crc32 :public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_str(func_name()); } - String value; -public: - Item_func_crc32(THD *thd, Item *a): Item_long_func(thd, a) - { unsigned_flag= 1; } - const char *func_name() const { return "crc32"; } - bool fix_length_and_dec() { max_length=10; return FALSE; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_uncompressed_length : public Item_long_func_length -{ - String value; -public: - Item_func_uncompressed_length(THD *thd, Item *a) - :Item_long_func_length(thd, a) {} - const char *func_name() const{return "uncompressed_length";} - bool fix_length_and_dec() { max_length=10; maybe_null= true; return FALSE; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -#ifdef HAVE_COMPRESS -#define ZLIB_DEPENDED_FUNCTION ; -#else -#define ZLIB_DEPENDED_FUNCTION { null_value=1; return 0; } -#endif - -class Item_func_compress: public Item_str_binary_checksum_func -{ - String tmp_value; -public: - Item_func_compress(THD *thd, Item *a) - :Item_str_binary_checksum_func(thd, a) {} - bool fix_length_and_dec() - { - max_length= (args[0]->max_length * 120) / 100 + 12; - return FALSE; - } - const char *func_name() const{return "compress";} - String *val_str(String *) ZLIB_DEPENDED_FUNCTION - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_uncompress: public Item_str_binary_checksum_func -{ - String tmp_value; -public: - Item_func_uncompress(THD *thd, Item *a) - :Item_str_binary_checksum_func(thd, a) {} - bool fix_length_and_dec() - { - maybe_null= 1; max_length= MAX_BLOB_WIDTH; - return FALSE; - } - const char *func_name() const{return "uncompress";} - String *val_str(String *) ZLIB_DEPENDED_FUNCTION - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_uuid: public Item_str_func -{ -public: - Item_func_uuid(THD *thd): Item_str_func(thd) {} - bool fix_length_and_dec() - { - collation.set(DTCollation_numeric()); - fix_char_length(MY_UUID_STRING_LENGTH); - return FALSE; - } - bool const_item() const { return false; } - table_map used_tables() const { return RAND_TABLE_BIT; } - const char *func_name() const{ return "uuid"; } - String *val_str(String *); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_NON_DETERMINISTIC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_dyncol_create: public Item_str_func -{ -protected: - DYNCALL_CREATE_DEF *defs; - DYNAMIC_COLUMN_VALUE *vals; - uint *keys_num; - LEX_STRING *keys_str; - bool names, force_names; - bool prepare_arguments(THD *thd, bool force_names); - void print_arguments(String *str, enum_query_type query_type); -public: - Item_func_dyncol_create(THD *thd, List &args, DYNCALL_CREATE_DEF *dfs); - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec(); - const char *func_name() const{ return "column_create"; } - String *val_str(String *); - void print(String *str, enum_query_type query_type); - enum Functype functype() const { return DYNCOL_FUNC; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_dyncol_add: public Item_func_dyncol_create -{ -public: - Item_func_dyncol_add(THD *thd, List &args_arg, DYNCALL_CREATE_DEF *dfs): - Item_func_dyncol_create(thd, args_arg, dfs) - {} - const char *func_name() const{ return "column_add"; } - String *val_str(String *); - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_dyncol_json: public Item_str_func -{ -public: - Item_func_dyncol_json(THD *thd, Item *str): Item_str_func(thd, str) - {collation.set(DYNCOL_UTF);} - const char *func_name() const{ return "column_json"; } - String *val_str(String *); - bool fix_length_and_dec() - { - max_length= MAX_BLOB_WIDTH; - maybe_null= 1; - decimals= 0; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* - The following functions is always called from an Item_cast function -*/ - -class Item_dyncol_get: public Item_str_func -{ -public: - Item_dyncol_get(THD *thd, Item *str, Item *num): Item_str_func(thd, str, num) - {} - bool fix_length_and_dec() - { maybe_null= 1;; max_length= MAX_BLOB_WIDTH; return FALSE; } - /* Mark that collation can change between calls */ - bool dynamic_result() { return 1; } - - const char *func_name() const { return "column_get"; } - String *val_str(String *); - longlong val_int(); - longlong val_int_signed_typecast() - { - unsigned_flag= false; // Mark that we want to have a signed value - longlong value= val_int(); // val_int() can change unsigned_flag - if (!null_value && unsigned_flag && value < 0) - push_note_converted_to_negative_complement(current_thd); - return value; - } - longlong val_int_unsigned_typecast() - { - unsigned_flag= true; // Mark that we want to have an unsigned value - longlong value= val_int(); // val_int() can change unsigned_flag - if (!null_value && unsigned_flag == 0 && value < 0) - push_note_converted_to_positive_complement(current_thd); - return value; - } - double val_real(); - my_decimal *val_decimal(my_decimal *); - bool get_dyn_value(THD *thd, DYNAMIC_COLUMN_VALUE *val, String *tmp); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_dyncol_list: public Item_str_func -{ -public: - Item_func_dyncol_list(THD *thd, Item *str): Item_str_func(thd, str) - {collation.set(DYNCOL_UTF);} - bool fix_length_and_dec() - { maybe_null= 1; max_length= MAX_BLOB_WIDTH; return FALSE; }; - const char *func_name() const{ return "column_list"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* - this is used by JOIN_TAB::keep_current_rowid - and stores handler::position(). - It has nothing to do with _rowid pseudo-column, that the parser supports. -*/ -class Item_temptable_rowid :public Item_str_func -{ -public: - TABLE *table; - Item_temptable_rowid(TABLE *table_arg); - const Type_handler *type_handler() const { return &type_handler_string; } - Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table) - { return create_table_field_from_handler(root, table); } - String *val_str(String *str); - enum Functype functype() const { return TEMPTABLE_ROWID; } - const char *func_name() const { return ""; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; -#ifdef WITH_WSREP - -#include "wsrep_api.h" - -class Item_func_wsrep_last_written_gtid: public Item_str_ascii_func -{ - String gtid_str; -public: - Item_func_wsrep_last_written_gtid(THD *thd): Item_str_ascii_func(thd) {} - const char *func_name() const { return "wsrep_last_written_gtid"; } - String *val_str_ascii(String *); - bool fix_length_and_dec() - { - max_length= WSREP_GTID_STR_LEN; - maybe_null= true; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_wsrep_last_seen_gtid: public Item_str_ascii_func -{ - String gtid_str; -public: - Item_func_wsrep_last_seen_gtid(THD *thd): Item_str_ascii_func(thd) {} - const char *func_name() const { return "wsrep_last_seen_gtid"; } - String *val_str_ascii(String *); - bool fix_length_and_dec() - { - max_length= WSREP_GTID_STR_LEN; - maybe_null= true; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_wsrep_sync_wait_upto: public Item_int_func -{ - String value; -public: - Item_func_wsrep_sync_wait_upto(THD *thd, Item *a): Item_int_func(thd, a) {} - Item_func_wsrep_sync_wait_upto(THD *thd, Item *a, Item* b): Item_int_func(thd, a, b) {} - const Type_handler *type_handler() const { return &type_handler_string; } - const char *func_name() const { return "wsrep_sync_wait_upto_gtid"; } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; -#endif /* WITH_WSREP */ - -#endif /* ITEM_STRFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_subselect.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_subselect.h deleted file mode 100644 index ec4398b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_subselect.h +++ /dev/null @@ -1,1533 +0,0 @@ -#ifndef ITEM_SUBSELECT_INCLUDED -#define ITEM_SUBSELECT_INCLUDED - -/* Copyright (c) 2002, 2011, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* subselect Item */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include - -class st_select_lex; -class st_select_lex_unit; -class JOIN; -class select_result_interceptor; -class subselect_engine; -class subselect_hash_sj_engine; -class Item_bool_func2; -class Comp_creator; -class With_element; -class Field_pair; - -typedef class st_select_lex SELECT_LEX; - -/** - Convenience typedef used in this file, and further used by any files - including this file. -*/ -typedef Comp_creator* (*chooser_compare_func_creator)(bool invert); -class Cached_item; - -/* base class for subselects */ - -class Item_subselect :public Item_result_field, - protected Used_tables_and_const_cache, - protected With_sum_func_cache -{ - bool value_assigned; /* value already assigned to subselect */ - bool own_engine; /* the engine was not taken from other Item_subselect */ -protected: - /* thread handler, will be assigned in fix_fields only */ - THD *thd; - /* old engine if engine was changed */ - subselect_engine *old_engine; - /* allowed number of columns (1 for single value subqueries) */ - uint max_columns; - /* where subquery is placed */ - enum_parsing_place parsing_place; - /* work with 'substitution' */ - bool have_to_be_excluded; - - bool inside_first_fix_fields; - bool done_first_fix_fields; - Item *expr_cache; - /* - Set to TRUE if at optimization or execution time we determine that this - item's value is a constant. We need this member because it is not possible - to substitute 'this' with a constant item. - */ - bool forced_const; - /* Set to the result of the last call of is_expensive() */ - bool expensive_fl; -#ifndef DBUG_OFF - /* Count the number of times this subquery predicate has been executed. */ - uint exec_counter; -#endif -public: - /* - Used inside Item_subselect::fix_fields() according to this scenario: - > Item_subselect::fix_fields - > engine->prepare - > child_join->prepare - (Here we realize we need to do the rewrite and set - substitution= some new Item, eg. Item_in_optimizer ) - < child_join->prepare - < engine->prepare - *ref= substitution; - substitution= NULL; - < Item_subselect::fix_fields - */ - /* TODO make this protected member again. */ - Item *substitution; - /* engine that perform execution of subselect (single select or union) */ - /* TODO make this protected member again. */ - subselect_engine *engine; - /* unit of subquery */ - st_select_lex_unit *unit; - /* Cached buffers used when calling filesort in sub queries */ - Filesort_buffer filesort_buffer; - LEX_STRING sortbuffer; - /* A reference from inside subquery predicate to somewhere outside of it */ - class Ref_to_outside : public Sql_alloc - { - public: - st_select_lex *select; /* Select where the reference is pointing to */ - /* - What is being referred. This may be NULL when we're referring to an - aggregate function. - */ - Item *item; - }; - /* - References from within this subquery to somewhere outside of it (i.e. to - parent select, grandparent select, etc) - */ - List upper_refs; - st_select_lex *parent_select; - - /* - TRUE<=>Table Elimination has made it redundant to evaluate this select - (and so it is not part of QEP, etc) - */ - bool eliminated; - - /* subquery is transformed */ - bool changed; - - /* TRUE <=> The underlying SELECT is correlated w.r.t some ancestor select */ - bool is_correlated; - - /* - TRUE <=> the subquery contains a recursive reference in the FROM list - of one of its selects. In this case some of subquery optimization - strategies cannot be applied for the subquery; - */ - bool with_recursive_reference; - - /* To link Item_subselects containing references to the same recursive CTE */ - Item_subselect *next_with_rec_ref; - - enum subs_type {UNKNOWN_SUBS, SINGLEROW_SUBS, - EXISTS_SUBS, IN_SUBS, ALL_SUBS, ANY_SUBS}; - - Item_subselect(THD *thd); - - virtual subs_type substype() { return UNKNOWN_SUBS; } - bool is_exists_predicate() - { - return substype() == Item_subselect::EXISTS_SUBS; - } - bool is_in_predicate() - { - return get_IN_subquery() != NULL; - } - - /* - We need this method, because some compilers do not allow 'this' - pointer in constructor initialization list, but we need to pass a pointer - to subselect Item class to select_result_interceptor's constructor. - */ - virtual void init (st_select_lex *select_lex, - select_result_interceptor *result); - - ~Item_subselect(); - void cleanup() override; - virtual void reset() - { - eliminated= FALSE; - null_value= 1; - } - /** - Set the subquery result to a default value consistent with the semantics of - the result row produced for queries with implicit grouping. - */ - void no_rows_in_result() override= 0; - virtual bool select_transformer(JOIN *join); - bool assigned() { return value_assigned; } - void assigned(bool a) { value_assigned= a; } - enum Type type() const override; - bool is_null() override - { - update_null_value(); - return null_value; - } - bool fix_fields(THD *thd, Item **ref) override; - bool with_subquery() const override { DBUG_ASSERT(fixed); return true; } - bool with_sum_func() const override { return m_with_sum_func; } - With_sum_func_cache* get_with_sum_func_cache() override { return this; } - bool mark_as_dependent(THD *thd, st_select_lex *select, Item *item); - void fix_after_pullout(st_select_lex *new_parent, Item **ref, - bool merge) override; - void recalc_used_tables(st_select_lex *new_parent, bool after_pullout); - virtual bool exec(); - /* - If subquery optimization or execution determines that the subquery has - an empty result, mark the subquery predicate as a constant value. - */ - void make_const() - { - used_tables_cache= 0; - const_item_cache= 0; - forced_const= TRUE; - } - virtual bool fix_length_and_dec(); - table_map used_tables() const override; - table_map not_null_tables() const override { return 0; } - bool const_item() const override; - inline table_map get_used_tables_cache() { return used_tables_cache; } - Item *get_tmp_table_item(THD *thd) override; - void update_used_tables() override; - void print(String *str, enum_query_type query_type) override; - virtual bool have_guarded_conds() { return FALSE; } - bool change_engine(subselect_engine *eng) - { - old_engine= engine; - engine= eng; - return eng == 0; - } - bool engine_changed(subselect_engine *eng) { return engine != eng; } - /* - True if this subquery has been already evaluated. Implemented only for - single select and union subqueries only. - */ - bool is_evaluated() const; - bool is_uncacheable() const; - bool is_expensive() override; - - /* - Used by max/min subquery to initialize value presence registration - mechanism. Engine call this method before rexecution query. - */ - virtual void reset_value_registration() {} - enum_parsing_place place() { return parsing_place; } - bool walk(Item_processor processor, bool walk_subquery, void *arg) override; - bool unknown_splocal_processor(void *arg) override; - bool mark_as_eliminated_processor(void *arg) override; - bool eliminate_subselect_processor(void *arg) override; - bool set_fake_select_as_master_processor(void *arg) override; - bool enumerate_field_refs_processor(void *arg) override; - bool check_vcol_func_processor(void *arg) override - { - return mark_unsupported_function("select ...", arg, VCOL_IMPOSSIBLE); - } - /** - Callback to test if an IN predicate is expensive. - - @notes - The return value affects the behavior of make_cond_for_table(). - - @retval TRUE if the predicate is expensive - @retval FALSE otherwise - */ - bool is_expensive_processor(void *arg) override { return is_expensive(); } - - /** - Get the SELECT_LEX structure associated with this Item. - @return the SELECT_LEX structure associated with this Item - */ - st_select_lex* get_select_lex(); - bool expr_cache_is_needed(THD *) override; - void get_cache_parameters(List ¶meters) override; - bool is_subquery_processor (void *opt_arg) override { return 1; } - bool exists2in_processor(void *opt_arg) override { return 0; } - bool limit_index_condition_pushdown_processor(void *opt_arg) override - { - return TRUE; - } - - void register_as_with_rec_ref(With_element *with_elem); - void init_expr_cache_tracker(THD *thd); - - Item* build_clone(THD *thd) override { return 0; } - Item* get_copy(THD *thd) override { return 0; } - - bool wrap_tvc_into_select(THD *thd, st_select_lex *tvc_sl); - - friend class select_result_interceptor; - friend class Item_in_optimizer; - friend bool Item_field::fix_fields(THD *, Item **); - friend int Item_field::fix_outer_field(THD *, Field **, Item **); - friend bool Item_ref::fix_fields(THD *, Item **); - friend void mark_select_range_as_dependent(THD*, - st_select_lex*, st_select_lex*, - Field*, Item*, Item_ident*); - friend bool convert_join_subqueries_to_semijoins(JOIN *join); -}; - -/* single value subselect */ - -class Item_cache; -class Item_singlerow_subselect :public Item_subselect -{ -protected: - Item_cache *value, **row; -public: - Item_singlerow_subselect(THD *thd_arg, st_select_lex *select_lex); - Item_singlerow_subselect(THD *thd_arg): Item_subselect(thd_arg), value(0), row (0) - {} - - void cleanup(); - subs_type substype() { return SINGLEROW_SUBS; } - - void reset(); - void no_rows_in_result(); - bool select_transformer(JOIN *join); - void store(uint i, Item* item); - double val_real(); - longlong val_int (); - String *val_str (String *); - bool val_native(THD *thd, Native *); - my_decimal *val_decimal(my_decimal *); - bool val_bool(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - const Type_handler *type_handler() const; - bool fix_length_and_dec(); - - uint cols() const; - Item* element_index(uint i) { return reinterpret_cast(row[i]); } - Item** addr(uint i) { return (Item**)row + i; } - bool check_cols(uint c); - bool null_inside(); - void bring_value(); - - /** - This method is used to implement a special case of semantic tree - rewriting, mandated by a SQL:2003 exception in the specification. - The only caller of this method is handle_sql2003_note184_exception(), - see the code there for more details. - Note that this method breaks the object internal integrity, by - removing it's association with the corresponding SELECT_LEX, - making this object orphan from the parse tree. - No other method, beside the destructor, should be called on this - object, as it is now invalid. - @return the SELECT_LEX structure that was given in the constructor. - */ - st_select_lex* invalidate_and_restore_select_lex(); - - Item* expr_cache_insert_transformer(THD *thd, uchar *unused); - - friend class select_singlerow_subselect; -}; - -/* used in static ALL/ANY optimization */ -class select_max_min_finder_subselect; -class Item_maxmin_subselect :public Item_singlerow_subselect -{ -protected: - bool max; - bool was_values; // Set if we have found at least one row -public: - Item_maxmin_subselect(THD *thd, Item_subselect *parent, - st_select_lex *select_lex, bool max); - virtual void print(String *str, enum_query_type query_type); - void cleanup(); - bool any_value() { return was_values; } - void register_value() { was_values= TRUE; } - void reset_value_registration() { was_values= FALSE; } - void no_rows_in_result(); -}; - -/* exists subselect */ - -class Item_exists_subselect :public Item_subselect -{ -protected: - Item_func_not *upper_not; - bool value; /* value of this item (boolean: exists/not-exists) */ - bool abort_on_null; - - void init_length_and_dec(); - bool select_prepare_to_be_in(); - -public: - /* - Used by subquery optimizations to keep track about in which clause this - subquery predicate is located: - NO_JOIN_NEST - the predicate is an AND-part of the WHERE - join nest pointer - the predicate is an AND-part of ON expression - of a join nest - NULL - for all other locations - */ - TABLE_LIST *emb_on_expr_nest; - /** - Reference on the Item_in_optimizer wrapper of this subquery - */ - Item_in_optimizer *optimizer; - /* true if we got this from EXISTS or to IN */ - bool exists_transformed; - - Item_exists_subselect(THD *thd_arg, st_select_lex *select_lex); - Item_exists_subselect(THD *thd_arg): - Item_subselect(thd_arg), upper_not(NULL), abort_on_null(0), - emb_on_expr_nest(NULL), optimizer(0), exists_transformed(0) - {} - - subs_type substype() override { return EXISTS_SUBS; } - void reset() override - { - eliminated= FALSE; - value= 0; - } - void no_rows_in_result() override; - - const Type_handler *type_handler() const override - { - return &type_handler_bool; - } - longlong val_int() override; - double val_real() override; - String *val_str(String*) override; - my_decimal *val_decimal(my_decimal *) override; - bool val_bool() override; - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override - { return get_date_from_int(thd, ltime, fuzzydate); } - bool fix_fields(THD *thd, Item **ref) override; - bool fix_length_and_dec() override; - void print(String *str, enum_query_type query_type) override; - bool select_transformer(JOIN *join) override; - void top_level_item() override { abort_on_null=1; } - bool is_top_level_item() const override { return abort_on_null; } - bool exists2in_processor(void *opt_arg) override; - - Item* expr_cache_insert_transformer(THD *thd, uchar *unused) override; - - void mark_as_condition_AND_part(TABLE_LIST *embedding) override - { - emb_on_expr_nest= embedding; - } - void under_not(Item_func_not *upper) override { upper_not= upper; }; - - void set_exists_transformed() { exists_transformed= TRUE; } - - friend class select_exists_subselect; - friend class subselect_uniquesubquery_engine; - friend class subselect_indexsubquery_engine; -}; - - -TABLE_LIST * const NO_JOIN_NEST=(TABLE_LIST*)0x1; - -/* - Possible methods to execute an IN predicate. These are set by the optimizer - based on user-set optimizer switches, semantic analysis and cost comparison. -*/ -#define SUBS_NOT_TRANSFORMED 0 /* No execution method was chosen for this IN. */ -/* The Final decision about the strategy is made. */ -#define SUBS_STRATEGY_CHOSEN 1 -#define SUBS_SEMI_JOIN 2 /* IN was converted to semi-join. */ -#define SUBS_IN_TO_EXISTS 4 /* IN was converted to correlated EXISTS. */ -#define SUBS_MATERIALIZATION 8 /* Execute IN via subquery materialization. */ -/* Partial matching substrategies of MATERIALIZATION. */ -#define SUBS_PARTIAL_MATCH_ROWID_MERGE 16 -#define SUBS_PARTIAL_MATCH_TABLE_SCAN 32 -/* ALL/ANY will be transformed with max/min optimization */ -/* The subquery has not aggregates, transform it into a MAX/MIN query. */ -#define SUBS_MAXMIN_INJECTED 64 -/* The subquery has aggregates, use a special max/min subselect engine. */ -#define SUBS_MAXMIN_ENGINE 128 - - -/** - Representation of IN subquery predicates of the form - "left_expr IN (SELECT ...)". - - @details - This class has: - - A "subquery execution engine" (as a subclass of Item_subselect) that allows - it to evaluate subqueries. (and this class participates in execution by - having was_null variable where part of execution result is stored. - - Transformation methods (todo: more on this). - - This class is not used directly, it is "wrapped" into Item_in_optimizer - which provides some small bits of subquery evaluation. -*/ - -class Item_in_subselect :public Item_exists_subselect -{ -protected: - /* - Cache of the left operand of the subquery predicate. Allocated in the - runtime memory root, for each execution, thus need not be freed. - */ - List *left_expr_cache; - bool first_execution; - - /* - expr & optimizer used in subselect rewriting to store Item for - all JOIN in UNION - */ - Item *expr; - bool was_null; - /* A bitmap of possible execution strategies for an IN predicate. */ - uchar in_strategy; -protected: - /* Used to trigger on/off conditions that were pushed down to subselect */ - bool *pushed_cond_guards; - Comp_creator *func; - -protected: - bool init_cond_guards(); - bool select_in_like_transformer(JOIN *join); - bool single_value_transformer(JOIN *join); - bool row_value_transformer(JOIN * join); - bool fix_having(Item *having, st_select_lex *select_lex); - bool create_single_in_to_exists_cond(JOIN * join, - Item **where_item, - Item **having_item); - bool create_row_in_to_exists_cond(JOIN * join, - Item **where_item, - Item **having_item); - Item *left_expr; - /* - Important for PS/SP: left_expr_orig is the item that left_expr originally - pointed at. That item is allocated on the statement arena, while - left_expr could later be changed to something on the execution arena. - */ - Item *left_expr_orig; -public: - /* Priority of this predicate in the convert-to-semi-join-nest process. */ - int sj_convert_priority; - /* May be TRUE only for the candidates to semi-join conversion */ - bool do_not_convert_to_sj; - /* - Types of left_expr and subquery's select list allow to perform subquery - materialization. Currently, we set this to FALSE when it as well could - be TRUE. This is to be properly addressed with fix for BUG#36752. - */ - bool types_allow_materialization; - - /* - Same as above, but they also allow to scan the materialized table. - */ - bool sjm_scan_allowed; - - /* - JoinTaB Materialization (JTBM) members - */ - - /* - TRUE <=> This subselect has been converted into non-mergeable semi-join - table. - */ - bool is_jtbm_merged; - - /* (Applicable if is_jtbm_merged==TRUE) Time required to run the materialized join */ - double jtbm_read_time; - - /* (Applicable if is_jtbm_merged==TRUE) Number of output rows in materialized join */ - double jtbm_record_count; - - /* - (Applicable if is_jtbm_merged==TRUE) TRUE <=> The materialized subselect is - a degenerate subselect which produces 0 or 1 rows, which we know at - optimization phase. - Examples: - 1. subquery has "Impossible WHERE": - - SELECT * FROM ot WHERE ot.column IN (SELECT it.col FROM it WHERE 2 > 3) - - 2. Subquery produces one row which opt_sum.cc is able to get with one lookup: - - SELECT * FROM ot WHERE ot.column IN (SELECT MAX(it.key_col) FROM it) - */ - bool is_jtbm_const_tab; - - /* - (Applicable if is_jtbm_const_tab==TRUE) Whether the subquery has produced - the row (or not) - */ - bool jtbm_const_row_found; - - /* - TRUE<=>this is a flattenable semi-join, false otherwise. - */ - bool is_flattenable_semijoin; - - /* - TRUE<=>registered in the list of semijoins in outer select - */ - bool is_registered_semijoin; - - List corresponding_fields; - - /* - Used to determine how this subselect item is represented in the item tree, - in case there is a need to locate it there and replace with something else. - Two options are possible: - 1. This item is there 'as-is'. - 1. This item is wrapped within Item_in_optimizer. - */ - Item *original_item() - { - return (is_flattenable_semijoin && !exists_transformed ? - (Item*)this : - (Item*)optimizer); - } - - bool *get_cond_guard(int i) - { - return pushed_cond_guards ? pushed_cond_guards + i : NULL; - } - void set_cond_guard_var(int i, bool v) - { - if ( pushed_cond_guards) - pushed_cond_guards[i]= v; - } - bool have_guarded_conds() override { return MY_TEST(pushed_cond_guards); } - - Item_func_not_all *upper_item; // point on NOT/NOP before ALL/SOME subquery - - Item_in_subselect(THD *thd_arg, Item * left_expr, st_select_lex *select_lex); - Item_in_subselect(THD *thd_arg): - Item_exists_subselect(thd_arg), left_expr_cache(0), first_execution(TRUE), - in_strategy(SUBS_NOT_TRANSFORMED), - pushed_cond_guards(NULL), func(NULL), do_not_convert_to_sj(FALSE), - is_jtbm_merged(FALSE), is_jtbm_const_tab(FALSE), upper_item(0) {} - void cleanup() override; - subs_type substype() override { return IN_SUBS; } - void reset() override - { - eliminated= FALSE; - value= 0; - null_value= 0; - was_null= 0; - } - bool select_transformer(JOIN *join) override; - bool create_in_to_exists_cond(JOIN *join_arg); - bool inject_in_to_exists_cond(JOIN *join_arg); - - bool exec() override; - longlong val_int() override; - double val_real() override; - String *val_str(String*) override; - my_decimal *val_decimal(my_decimal *) override; - bool val_bool() override; - bool test_limit(st_select_lex_unit *unit); - void print(String *str, enum_query_type query_type) override; - enum precedence precedence() const override { return IN_PRECEDENCE; } - bool fix_fields(THD *thd, Item **ref) override; - bool fix_length_and_dec() override; - void fix_after_pullout(st_select_lex *new_parent, Item **ref, - bool merge) override; - bool const_item() const override - { - return Item_subselect::const_item() && left_expr->const_item(); - } - void update_used_tables() override; - bool setup_mat_engine(); - bool init_left_expr_cache(); - /* Inform 'this' that it was computed, and contains a valid result. */ - void set_first_execution() { if (first_execution) first_execution= FALSE; } - bool expr_cache_is_needed(THD *thd) override; - inline bool left_expr_has_null(); - - void disable_cond_guard_for_const_null_left_expr(int i) - { - if (left_expr->const_item() && !left_expr->is_expensive()) - { - if (left_expr->element_index(i)->is_null()) - set_cond_guard_var(i,FALSE); - } - } - - int optimize(double *out_rows, double *cost); - /* - Return the identifier that we could use to identify the subquery for the - user. - */ - int get_identifier(); - - void block_conversion_to_sj () { do_not_convert_to_sj= TRUE; } - - bool test_strategy(uchar strategy) - { return MY_TEST(in_strategy & strategy); } - - /** - Test that the IN strategy was chosen for execution. This is so - when the CHOSEN flag is ON, and there is no other strategy. - */ - bool test_set_strategy(uchar strategy) - { - DBUG_ASSERT(strategy == SUBS_SEMI_JOIN || - strategy == SUBS_IN_TO_EXISTS || - strategy == SUBS_MATERIALIZATION || - strategy == SUBS_PARTIAL_MATCH_ROWID_MERGE || - strategy == SUBS_PARTIAL_MATCH_TABLE_SCAN || - strategy == SUBS_MAXMIN_INJECTED || - strategy == SUBS_MAXMIN_ENGINE); - return ((in_strategy & SUBS_STRATEGY_CHOSEN) && - (in_strategy & ~SUBS_STRATEGY_CHOSEN) == strategy); - } - - bool is_set_strategy() - { return MY_TEST(in_strategy & SUBS_STRATEGY_CHOSEN); } - - bool has_strategy() - { return in_strategy != SUBS_NOT_TRANSFORMED; } - - void add_strategy (uchar strategy) - { - DBUG_ENTER("Item_in_subselect::add_strategy"); - DBUG_PRINT("enter", ("current: %u add: %u", - (uint) in_strategy, (uint) strategy)); - DBUG_ASSERT(strategy != SUBS_NOT_TRANSFORMED); - DBUG_ASSERT(!(strategy & SUBS_STRATEGY_CHOSEN)); - /* - TODO: PS re-execution breaks this condition, because - check_and_do_in_subquery_rewrites() is called for each reexecution - and re-adds the same strategies. - DBUG_ASSERT(!(in_strategy & SUBS_STRATEGY_CHOSEN)); - */ - in_strategy|= strategy; - DBUG_VOID_RETURN; - } - - void reset_strategy(uchar strategy) - { - DBUG_ENTER("Item_in_subselect::reset_strategy"); - DBUG_PRINT("enter", ("current: %u new: %u", - (uint) in_strategy, (uint) strategy)); - DBUG_ASSERT(strategy != SUBS_NOT_TRANSFORMED); - in_strategy= strategy; - DBUG_VOID_RETURN; - } - - void set_strategy(uchar strategy) - { - DBUG_ENTER("Item_in_subselect::set_strategy"); - DBUG_PRINT("enter", ("current: %u set: %u", - (uint) in_strategy, - (uint) (SUBS_STRATEGY_CHOSEN | strategy))); - /* Check that only one strategy is set for execution. */ - DBUG_ASSERT(strategy == SUBS_SEMI_JOIN || - strategy == SUBS_IN_TO_EXISTS || - strategy == SUBS_MATERIALIZATION || - strategy == SUBS_PARTIAL_MATCH_ROWID_MERGE || - strategy == SUBS_PARTIAL_MATCH_TABLE_SCAN || - strategy == SUBS_MAXMIN_INJECTED || - strategy == SUBS_MAXMIN_ENGINE); - in_strategy= (SUBS_STRATEGY_CHOSEN | strategy); - DBUG_VOID_RETURN; - } - - bool walk(Item_processor processor, bool walk_subquery, void *arg) override - { - return left_expr->walk(processor, walk_subquery, arg) || - Item_subselect::walk(processor, walk_subquery, arg); - } - - bool exists2in_processor(void *opt_arg __attribute__((unused))) override - { - return 0; - }; - - bool pushdown_cond_for_in_subquery(THD *thd, Item *cond); - - Item_in_subselect *get_IN_subquery() override - { return this; } - inline Item** left_exp_ptr() - { return &left_expr; } - inline Item* left_exp() const - { return left_expr; } - inline Item* left_exp_orig() const - { return left_expr_orig; } - - friend class Item_ref_null_helper; - friend class Item_is_not_null_test; - friend class Item_in_optimizer; - friend class subselect_indexsubquery_engine; - friend class subselect_hash_sj_engine; - friend class subselect_partial_match_engine; - friend class Item_exists_subselect; -}; - - -/* ALL/ANY/SOME subselect */ -class Item_allany_subselect :public Item_in_subselect -{ -public: - chooser_compare_func_creator func_creator; - bool all; - - Item_allany_subselect(THD *thd_arg, Item * left_expr, - chooser_compare_func_creator fc, - st_select_lex *select_lex, bool all); - - void cleanup(); - // only ALL subquery has upper not - subs_type substype() { return all?ALL_SUBS:ANY_SUBS; } - bool select_transformer(JOIN *join); - void create_comp_func(bool invert) { func= func_creator(invert); } - void print(String *str, enum_query_type query_type); - bool is_maxmin_applicable(JOIN *join); - bool transform_into_max_min(JOIN *join); - void no_rows_in_result(); -}; - - -class subselect_engine: public Sql_alloc, - public Type_handler_hybrid_field_type -{ -protected: - select_result_interceptor *result; /* results storage class */ - THD *thd; /* pointer to current THD */ - Item_subselect *item; /* item, that use this engine */ - bool maybe_null; /* may be null (first item in select) */ -public: - - enum enum_engine_type {ABSTRACT_ENGINE, SINGLE_SELECT_ENGINE, - UNION_ENGINE, UNIQUESUBQUERY_ENGINE, - INDEXSUBQUERY_ENGINE, HASH_SJ_ENGINE, - ROWID_MERGE_ENGINE, TABLE_SCAN_ENGINE}; - - subselect_engine(Item_subselect *si, - select_result_interceptor *res): - Type_handler_hybrid_field_type(&type_handler_varchar), - thd(NULL) - { - result= res; - item= si; - maybe_null= 0; - } - virtual ~subselect_engine() {}; // to satisfy compiler - virtual void cleanup()= 0; - - /* - Also sets "thd" for subselect_engine::result. - Should be called before prepare(). - */ - void set_thd(THD *thd_arg); - THD * get_thd() { return thd ? thd : current_thd; } - virtual int prepare(THD *)= 0; - virtual bool fix_length_and_dec(Item_cache** row)= 0; - /* - Execute the engine - - SYNOPSIS - exec() - - DESCRIPTION - Execute the engine. The result of execution is subquery value that is - either captured by previously set up select_result-based 'sink' or - stored somewhere by the exec() method itself. - - A required side effect: If at least one pushed-down predicate is - disabled, subselect_engine->no_rows() must return correct result after - the exec() call. - - RETURN - 0 - OK - 1 - Either an execution error, or the engine was "changed", and the - caller should call exec() again for the new engine. - */ - virtual int exec()= 0; - virtual uint cols() const= 0; /* return number of columns in select */ - virtual uint8 uncacheable()= 0; /* query is uncacheable */ - virtual void exclude()= 0; - virtual bool may_be_null() { return maybe_null; }; - virtual table_map upper_select_const_tables()= 0; - static table_map calc_const_tables(TABLE_LIST *); - static table_map calc_const_tables(List &list); - virtual void print(String *str, enum_query_type query_type)= 0; - virtual bool change_result(Item_subselect *si, - select_result_interceptor *result, - bool temp= FALSE)= 0; - virtual bool no_tables()= 0; - virtual bool is_executed() const { return FALSE; } - /* Check if subquery produced any rows during last query execution */ - virtual bool no_rows() = 0; - virtual enum_engine_type engine_type() { return ABSTRACT_ENGINE; } - virtual int get_identifier() { DBUG_ASSERT(0); return 0; } - virtual void force_reexecution() {} -protected: - bool set_row(List &item_list, Item_cache **row); -}; - -class subselect_single_select_engine: public subselect_engine -{ - bool prepared; /* simple subselect is prepared */ - bool executed; /* simple subselect is executed */ - st_select_lex *select_lex; /* corresponding select_lex */ - JOIN * join; /* corresponding JOIN structure */ -public: - subselect_single_select_engine(st_select_lex *select, - select_result_interceptor *result, - Item_subselect *item); - void cleanup(); - int prepare(THD *thd); - bool fix_length_and_dec(Item_cache** row); - int exec(); - uint cols() const; - uint8 uncacheable(); - void exclude(); - table_map upper_select_const_tables(); - void print (String *str, enum_query_type query_type); - bool change_result(Item_subselect *si, - select_result_interceptor *result, - bool temp); - bool no_tables(); - bool may_be_null(); - bool is_executed() const { return executed; } - bool no_rows(); - virtual enum_engine_type engine_type() { return SINGLE_SELECT_ENGINE; } - int get_identifier(); - void force_reexecution(); - void change_select(st_select_lex *new_select) { select_lex= new_select; } - - friend class subselect_hash_sj_engine; - friend class Item_in_subselect; - friend bool execute_degenerate_jtbm_semi_join(THD *thd, - TABLE_LIST *tbl, - Item_in_subselect *subq_pred, - List &eq_list); -}; - - -class subselect_union_engine: public subselect_engine -{ - st_select_lex_unit *unit; /* corresponding unit structure */ -public: - subselect_union_engine(st_select_lex_unit *u, - select_result_interceptor *result, - Item_subselect *item); - void cleanup(); - int prepare(THD *); - bool fix_length_and_dec(Item_cache** row); - int exec(); - uint cols() const; - uint8 uncacheable(); - void exclude(); - table_map upper_select_const_tables(); - void print (String *str, enum_query_type query_type); - bool change_result(Item_subselect *si, - select_result_interceptor *result, - bool temp= FALSE); - bool no_tables(); - bool is_executed() const; - void force_reexecution(); - bool no_rows(); - virtual enum_engine_type engine_type() { return UNION_ENGINE; } -}; - - -struct st_join_table; - - -/* - A subquery execution engine that evaluates the subquery by doing one index - lookup in a unique index. - - This engine is used to resolve subqueries in forms - - outer_expr IN (SELECT tbl.unique_key FROM tbl WHERE subq_where) - - or, tuple-based: - - (oe1, .. oeN) IN (SELECT uniq_key_part1, ... uniq_key_partK - FROM tbl WHERE subqwhere) - - i.e. the subquery is a single table SELECT without GROUP BY, aggregate - functions, etc. -*/ - -class subselect_uniquesubquery_engine: public subselect_engine -{ -protected: - st_join_table *tab; - Item *cond; /* The WHERE condition of subselect */ - /* - TRUE<=> last execution produced empty set. Valid only when left - expression is NULL. - */ - bool empty_result_set; -public: - - // constructor can assign THD because it will be called after JOIN::prepare - subselect_uniquesubquery_engine(THD *thd_arg, st_join_table *tab_arg, - Item_in_subselect *subs, Item *where) - :subselect_engine(subs, 0), tab(tab_arg), cond(where) - { DBUG_ASSERT(subs); } - ~subselect_uniquesubquery_engine(); - void cleanup(); - int prepare(THD *); - bool fix_length_and_dec(Item_cache** row); - int exec(); - uint cols() const { return 1; } - uint8 uncacheable() { return UNCACHEABLE_DEPENDENT_INJECTED; } - void exclude(); - table_map upper_select_const_tables() { return 0; } - void print (String *str, enum_query_type query_type); - bool change_result(Item_subselect *si, - select_result_interceptor *result, - bool temp= FALSE); - bool no_tables(); - int index_lookup(); /* TIMOUR: this method needs refactoring. */ - int scan_table(); - bool copy_ref_key(bool skip_constants); - bool no_rows() { return empty_result_set; } - virtual enum_engine_type engine_type() { return UNIQUESUBQUERY_ENGINE; } -}; - - -class subselect_indexsubquery_engine: public subselect_uniquesubquery_engine -{ - /* FALSE for 'ref', TRUE for 'ref-or-null'. */ - bool check_null; - /* - The "having" clause. This clause (further referred to as "artificial - having") was inserted by subquery transformation code. It contains - Item(s) that have a side-effect: they record whether the subquery has - produced a row with NULL certain components. We need to use it for cases - like - (oe1, oe2) IN (SELECT t.key, t.no_key FROM t1) - where we do index lookup on t.key=oe1 but need also to check if there - was a row such that t.no_key IS NULL. - - NOTE: This is currently here and not in the uniquesubquery_engine. Ideally - it should have been in uniquesubquery_engine in order to allow execution of - subqueries like - - (oe1, oe2) IN (SELECT primary_key, non_key_maybe_null_field FROM tbl) - - We could use uniquesubquery_engine for the first component and let - Item_is_not_null_test( non_key_maybe_null_field) to handle the second. - - However, subqueries like the above are currently not handled by index - lookup-based subquery engines, the engine applicability check misses - them: it doesn't switch the engine for case of artificial having and - [eq_]ref access (only for artificial having + ref_or_null or no having). - The above example subquery is handled as a full-blown SELECT with eq_ref - access to one table. - - Due to this limitation, the "artificial having" currently needs to be - checked by only in indexsubquery_engine. - */ - Item *having; -public: - - // constructor can assign THD because it will be called after JOIN::prepare - subselect_indexsubquery_engine(THD *thd_arg, st_join_table *tab_arg, - Item_in_subselect *subs, Item *where, - Item *having_arg, bool chk_null) - :subselect_uniquesubquery_engine(thd_arg, tab_arg, subs, where), - check_null(chk_null), - having(having_arg) - { DBUG_ASSERT(subs); } - int exec(); - void print (String *str, enum_query_type query_type); - virtual enum_engine_type engine_type() { return INDEXSUBQUERY_ENGINE; } -}; - -/* - This function is actually defined in sql_parse.cc, but it depends on - chooser_compare_func_creator defined in this file. - */ -Item * all_any_subquery_creator(THD *thd, Item *left_expr, - chooser_compare_func_creator cmp, - bool all, - SELECT_LEX *select_lex); - - -inline bool Item_subselect::is_evaluated() const -{ - return engine->is_executed(); -} - - -inline bool Item_subselect::is_uncacheable() const -{ - return engine->uncacheable(); -} - -/** - Compute an IN predicate via a hash semi-join. This class is responsible for - the materialization of the subquery, and the selection of the correct and - optimal execution method (e.g. direct index lookup, or partial matching) for - the IN predicate. -*/ - -class subselect_hash_sj_engine : public subselect_engine -{ -public: - /* The table into which the subquery is materialized. */ - TABLE *tmp_table; - /* TRUE if the subquery was materialized into a temp table. */ - bool is_materialized; - /* - The old engine already chosen at parse time and stored in permanent memory. - Through this member we can re-create and re-prepare materialize_join for - each execution of a prepared statement. We also reuse the functionality - of subselect_single_select_engine::[prepare | cols]. - */ - subselect_single_select_engine *materialize_engine; - /* - QEP to execute the subquery and materialize its result into a - temporary table. Created during the first call to exec(). - */ - JOIN *materialize_join; - /* - A conjunction of all the equality conditions between all pairs of expressions - that are arguments of an IN predicate. We need these to post-filter some - IN results because index lookups sometimes match values that are actually - not equal to the search key in SQL terms. - */ - Item_cond_and *semi_join_conds; - Name_resolution_context *semi_join_conds_context; - - - subselect_hash_sj_engine(THD *thd_arg, Item_in_subselect *in_predicate, - subselect_single_select_engine *old_engine) - : subselect_engine(in_predicate, NULL), - tmp_table(NULL), is_materialized(FALSE), materialize_engine(old_engine), - materialize_join(NULL), semi_join_conds(NULL), lookup_engine(NULL), - count_partial_match_columns(0), count_null_only_columns(0), - count_columns_with_nulls(0), strategy(UNDEFINED) - { DBUG_ASSERT(in_predicate); } - ~subselect_hash_sj_engine(); - - bool init(List *tmp_columns, uint subquery_id); - void cleanup(); - int prepare(THD *); - int exec(); - void print(String *str, enum_query_type query_type); - uint cols() const { return materialize_engine->cols(); } - uint8 uncacheable() { return materialize_engine->uncacheable(); } - table_map upper_select_const_tables() { return 0; } - bool no_rows() { return !tmp_table->file->stats.records; } - virtual enum_engine_type engine_type() { return HASH_SJ_ENGINE; } - /* - TODO: factor out all these methods in a base subselect_index_engine class - because all of them have dummy implementations and should never be called. - */ - bool fix_length_and_dec(Item_cache** row);//=>base class - void exclude(); //=>base class - //=>base class - bool change_result(Item_subselect *si, - select_result_interceptor *result, - bool temp= FALSE); - bool no_tables();//=>base class - -protected: - /* The engine used to compute the IN predicate. */ - subselect_engine *lookup_engine; - /* Keyparts of the only non-NULL composite index in a rowid merge. */ - MY_BITMAP non_null_key_parts; - /* Keyparts of the single column indexes with NULL, one keypart per index. */ - MY_BITMAP partial_match_key_parts; - uint count_partial_match_columns; - uint count_null_only_columns; - uint count_columns_with_nulls; - /* Possible execution strategies that can be used to compute hash semi-join.*/ - enum exec_strategy { - UNDEFINED, - COMPLETE_MATCH, /* Use regular index lookups. */ - PARTIAL_MATCH, /* Use some partial matching strategy. */ - PARTIAL_MATCH_MERGE, /* Use partial matching through index merging. */ - PARTIAL_MATCH_SCAN, /* Use partial matching through table scan. */ - IMPOSSIBLE /* Subquery materialization is not applicable. */ - }; - /* The chosen execution strategy. Computed after materialization. */ - exec_strategy strategy; - exec_strategy get_strategy_using_schema(); - exec_strategy get_strategy_using_data(); - ulonglong rowid_merge_buff_size(bool has_non_null_key, - bool has_covering_null_row, - MY_BITMAP *partial_match_key_parts); - void choose_partial_match_strategy(bool has_non_null_key, - bool has_covering_null_row, - MY_BITMAP *partial_match_key_parts); - bool make_semi_join_conds(); - subselect_uniquesubquery_engine* make_unique_engine(); - -}; - - -/* - Distinguish the type of (0-based) row numbers from the type of the index into - an array of row numbers. -*/ -typedef ha_rows rownum_t; - - -/* - An Ordered_key is an in-memory table index that allows O(log(N)) time - lookups of a multi-part key. - - If the index is over a single column, then this column may contain NULLs, and - the NULLs are stored and tested separately for NULL in O(1) via is_null(). - Multi-part indexes assume that the indexed columns do not contain NULLs. - - TODO: - = Due to the unnatural assymetry between single and multi-part indexes, it - makes sense to somehow refactor or extend the class. - - = This class can be refactored into a base abstract interface, and two - subclasses: - - one to represent single-column indexes, and - - another to represent multi-column indexes. - Such separation would allow slightly more efficient implementation of - the single-column indexes. - = The current design requires such indexes to be fully recreated for each - PS (re)execution, however most of the comprising objects can be reused. -*/ - -class Ordered_key : public Sql_alloc -{ -protected: - /* - Index of the key in an array of keys. This index allows to - construct (sub)sets of keys represented by bitmaps. - */ - uint keyid; - /* The table being indexed. */ - TABLE *tbl; - /* The columns being indexed. */ - Item_field **key_columns; - /* Number of elements in 'key_columns' (number of key parts). */ - uint key_column_count; - /* - An expression, or sequence of expressions that forms the search key. - The search key is a sequence when it is Item_row. Each element of the - sequence is accessible via Item::element_index(int i). - */ - Item *search_key; - -/* Value index related members. */ - /* - The actual value index, consists of a sorted sequence of row numbers. - */ - rownum_t *key_buff; - /* Number of elements in key_buff. */ - ha_rows key_buff_elements; - /* Current element in 'key_buff'. */ - ha_rows cur_key_idx; - /* - Mapping from row numbers to row ids. The element row_num_to_rowid[i] - contains a buffer with the rowid for the row numbered 'i'. - The memory for this member is not maintanined by this class because - all Ordered_key indexes of the same table share the same mapping. - */ - uchar *row_num_to_rowid; - /* - A sequence of predicates to compare the search key with the corresponding - columns of a table row from the index. - */ - Item_func_lt **compare_pred; - -/* Null index related members. */ - MY_BITMAP null_key; - /* Count of NULLs per column. */ - ha_rows null_count; - /* The row number that contains the first NULL in a column. */ - rownum_t min_null_row; - /* The row number that contains the last NULL in a column. */ - rownum_t max_null_row; - -protected: - bool alloc_keys_buffers(); - /* - Quick sort comparison function that compares two rows of the same table - indentfied with their row numbers. - */ - int cmp_keys_by_row_data(rownum_t a, rownum_t b); - static int cmp_keys_by_row_data_and_rownum(Ordered_key *key, - rownum_t* a, rownum_t* b); - - int cmp_key_with_search_key(rownum_t row_num); - -public: - Ordered_key(uint keyid_arg, TABLE *tbl_arg, - Item *search_key_arg, ha_rows null_count_arg, - ha_rows min_null_row_arg, ha_rows max_null_row_arg, - uchar *row_num_to_rowid_arg); - ~Ordered_key(); - void cleanup(); - /* Initialize a multi-column index. */ - bool init(MY_BITMAP *columns_to_index); - /* Initialize a single-column index. */ - bool init(int col_idx); - - uint get_column_count() { return key_column_count; } - uint get_keyid() { return keyid; } - Field *get_field(uint i) - { - DBUG_ASSERT(i < key_column_count); - return key_columns[i]->field; - } - rownum_t get_min_null_row() { return min_null_row; } - rownum_t get_max_null_row() { return max_null_row; } - MY_BITMAP * get_null_key() { return &null_key; } - ha_rows get_null_count() { return null_count; } - /* - Get the search key element that corresponds to the i-th key part of this - index. - */ - Item *get_search_key(uint i) - { - return search_key->element_index(key_columns[i]->field->field_index); - } - void add_key(rownum_t row_num) - { - /* The caller must know how many elements to add. */ - DBUG_ASSERT(key_buff_elements && cur_key_idx < key_buff_elements); - key_buff[cur_key_idx]= row_num; - ++cur_key_idx; - } - - bool sort_keys(); - double null_selectivity(); - - /* - Position the current element at the first row that matches the key. - The key itself is propagated by evaluating the current value(s) of - this->search_key. - */ - bool lookup(); - /* Move the current index cursor to the first key. */ - void first() - { - DBUG_ASSERT(key_buff_elements); - cur_key_idx= 0; - } - /* TODO */ - bool next_same(); - /* Move the current index cursor to the next key. */ - bool next() - { - DBUG_ASSERT(key_buff_elements); - if (cur_key_idx < key_buff_elements - 1) - { - ++cur_key_idx; - return TRUE; - } - return FALSE; - }; - /* Return the current index element. */ - rownum_t current() - { - DBUG_ASSERT(key_buff_elements && cur_key_idx < key_buff_elements); - return key_buff[cur_key_idx]; - } - - void set_null(rownum_t row_num) - { - bitmap_set_bit(&null_key, (uint)row_num); - } - bool is_null(rownum_t row_num) - { - /* - Indexes consisting of only NULLs do not have a bitmap buffer at all. - Their only initialized member is 'n_bits', which is equal to the number - of temp table rows. - */ - if (null_count == tbl->file->stats.records) - { - DBUG_ASSERT(tbl->file->stats.records == null_key.n_bits); - return TRUE; - } - if (row_num > max_null_row || row_num < min_null_row) - return FALSE; - return bitmap_is_set(&null_key, (uint)row_num); - } - void print(String *str); -}; - - -class subselect_partial_match_engine : public subselect_engine -{ -protected: - /* The temporary table that contains a materialized subquery. */ - TABLE *tmp_table; - /* - The engine used to check whether an IN predicate is TRUE or not. If not - TRUE, then subselect_rowid_merge_engine further distinguishes between - FALSE and UNKNOWN. - */ - subselect_uniquesubquery_engine *lookup_engine; - /* A list of equalities between each pair of IN operands. */ - List *equi_join_conds; - /* - True if there is an all NULL row in tmp_table. If so, then if there is - no complete match, there is a guaranteed partial match. - */ - bool has_covering_null_row; - - /* - True if all nullable columns of tmp_table consist of only NULL values. - If so, then if there is a match in the non-null columns, there is a - guaranteed partial match. - */ - bool has_covering_null_columns; - uint count_columns_with_nulls; - -protected: - virtual bool partial_match()= 0; -public: - subselect_partial_match_engine(subselect_uniquesubquery_engine *engine_arg, - TABLE *tmp_table_arg, Item_subselect *item_arg, - select_result_interceptor *result_arg, - List *equi_join_conds_arg, - bool has_covering_null_row_arg, - bool has_covering_null_columns_arg, - uint count_columns_with_nulls_arg); - int prepare(THD *thd_arg) { set_thd(thd_arg); return 0; } - int exec(); - bool fix_length_and_dec(Item_cache**) { return FALSE; } - uint cols() const { /* TODO: what is the correct value? */ return 1; } - uint8 uncacheable() { return UNCACHEABLE_DEPENDENT; } - void exclude() {} - table_map upper_select_const_tables() { return 0; } - bool change_result(Item_subselect*, - select_result_interceptor*, - bool temp= FALSE) - { DBUG_ASSERT(FALSE); return false; } - bool no_tables() { return false; } - bool no_rows() - { - /* - TODO: It is completely unclear what is the semantics of this - method. The current result is computed so that the call to no_rows() - from Item_in_optimizer::val_int() sets Item_in_optimizer::null_value - correctly. - */ - return !(item->get_IN_subquery()->null_value); - } - void print(String*, enum_query_type); - - friend void subselect_hash_sj_engine::cleanup(); -}; - - -class subselect_rowid_merge_engine: public subselect_partial_match_engine -{ -protected: - /* - Mapping from row numbers to row ids. The rowids are stored sequentially - in the array - rowid[i] is located in row_num_to_rowid + i * rowid_length. - */ - uchar *row_num_to_rowid; - /* - A subset of all the keys for which there is a match for the same row. - Used during execution. Computed for each outer reference - */ - MY_BITMAP matching_keys; - /* - The columns of the outer reference that are NULL. Computed for each - outer reference. - */ - MY_BITMAP matching_outer_cols; - /* - Indexes of row numbers, sorted by . If an - index may contain NULLs, the NULLs are stored efficiently in a bitmap. - - The indexes are sorted by the selectivity of their NULL sub-indexes, the - one with the fewer NULLs is first. Thus, if there is any index on - non-NULL columns, it is contained in keys[0]. - */ - Ordered_key **merge_keys; - /* The number of elements in merge_keys. */ - uint merge_keys_count; - /* The NULL bitmaps of merge keys.*/ - MY_BITMAP **null_bitmaps; - /* - An index on all non-NULL columns of 'tmp_table'. The index has the - logical form: <[v_i1 | ... | v_ik], rownum>. It allows to find the row - number where the columns c_i1,...,c1_k contain the values v_i1,...,v_ik. - If such an index exists, it is always the first element of 'merge_keys'. - */ - Ordered_key *non_null_key; - /* - Priority queue of Ordered_key indexes, one per NULLable column. - This queue is used by the partial match algorithm in method exec(). - */ - QUEUE pq; -protected: - /* - Comparison function to compare keys in order of decreasing bitmap - selectivity. - */ - static int cmp_keys_by_null_selectivity(Ordered_key **k1, Ordered_key **k2); - /* - Comparison function used by the priority queue pq, the 'smaller' key - is the one with the smaller current row number. - */ - static int cmp_keys_by_cur_rownum(void *arg, uchar *k1, uchar *k2); - - bool test_null_row(rownum_t row_num); - bool exists_complementing_null_row(MY_BITMAP *keys_to_complement); - bool partial_match(); -public: - subselect_rowid_merge_engine(subselect_uniquesubquery_engine *engine_arg, - TABLE *tmp_table_arg, uint merge_keys_count_arg, - bool has_covering_null_row_arg, - bool has_covering_null_columns_arg, - uint count_columns_with_nulls_arg, - Item_subselect *item_arg, - select_result_interceptor *result_arg, - List *equi_join_conds_arg) - :subselect_partial_match_engine(engine_arg, tmp_table_arg, - item_arg, result_arg, equi_join_conds_arg, - has_covering_null_row_arg, - has_covering_null_columns_arg, - count_columns_with_nulls_arg), - merge_keys_count(merge_keys_count_arg), non_null_key(NULL) - {} - ~subselect_rowid_merge_engine(); - bool init(MY_BITMAP *non_null_key_parts, MY_BITMAP *partial_match_key_parts); - void cleanup(); - virtual enum_engine_type engine_type() { return ROWID_MERGE_ENGINE; } -}; - - -class subselect_table_scan_engine: public subselect_partial_match_engine -{ -protected: - bool partial_match(); -public: - subselect_table_scan_engine(subselect_uniquesubquery_engine *engine_arg, - TABLE *tmp_table_arg, Item_subselect *item_arg, - select_result_interceptor *result_arg, - List *equi_join_conds_arg, - bool has_covering_null_row_arg, - bool has_covering_null_columns_arg, - uint count_columns_with_nulls_arg); - void cleanup(); - virtual enum_engine_type engine_type() { return TABLE_SCAN_ENGINE; } -}; -#endif /* ITEM_SUBSELECT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_sum.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_sum.h deleted file mode 100644 index 118f78e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_sum.h +++ /dev/null @@ -1,2026 +0,0 @@ -#ifndef ITEM_SUM_INCLUDED -#define ITEM_SUM_INCLUDED -/* Copyright (c) 2000, 2013 Oracle and/or its affiliates. - Copyright (c) 2008, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* classes for sum functions */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include -#include "sql_udf.h" /* udf_handler */ - -class Item_sum; -class Aggregator_distinct; -class Aggregator_simple; - -/** - The abstract base class for the Aggregator_* classes. - It implements the data collection functions (setup/add/clear) - as either pass-through to the real functionality or - as collectors into an Unique (for distinct) structure. - - Note that update_field/reset_field are not in that - class, because they're simply not called when - GROUP BY/DISTINCT can be handled with help of index on grouped - fields (quick_group = 0); -*/ - -class Aggregator : public Sql_alloc -{ - friend class Item_sum; - friend class Item_sum_sum; - friend class Item_sum_count; - friend class Item_sum_avg; - - /* - All members are protected as this class is not usable outside of an - Item_sum descendant. - */ -protected: - /* the aggregate function class to act on */ - Item_sum *item_sum; - -public: - Aggregator (Item_sum *arg): item_sum(arg) {} - virtual ~Aggregator () {} /* Keep gcc happy */ - - enum Aggregator_type { SIMPLE_AGGREGATOR, DISTINCT_AGGREGATOR }; - virtual Aggregator_type Aggrtype() = 0; - - /** - Called before adding the first row. - Allocates and sets up the internal aggregation structures used, - e.g. the Unique instance used to calculate distinct. - */ - virtual bool setup(THD *) = 0; - - /** - Called when we need to wipe out all the data from the aggregator : - all the values acumulated and all the state. - Cleans up the internal structures and resets them to their initial state. - */ - virtual void clear() = 0; - - /** - Called when there's a new value to be aggregated. - Updates the internal state of the aggregator to reflect the new value. - */ - virtual bool add() = 0; - - /** - Called when there are no more data and the final value is to be retrieved. - Finalises the state of the aggregator, so the final result can be retrieved. - */ - virtual void endup() = 0; - - /** Decimal value of being-aggregated argument */ - virtual my_decimal *arg_val_decimal(my_decimal * value) = 0; - /** Floating point value of being-aggregated argument */ - virtual double arg_val_real() = 0; - /** - NULLness of being-aggregated argument. - - @param use_null_value Optimization: to determine if the argument is NULL - we must, in the general case, call is_null() on it, which itself might - call val_*() on it, which might be costly. If you just have called - arg_val*(), you can pass use_null_value=true; this way, arg_is_null() - might avoid is_null() and instead do a cheap read of the Item's null_value - (updated by arg_val*()). - */ - virtual bool arg_is_null(bool use_null_value) = 0; -}; - - -class st_select_lex; -class Window_spec; - -/** - Class Item_sum is the base class used for special expressions that SQL calls - 'set functions'. These expressions are formed with the help of aggregate - functions such as SUM, MAX, GROUP_CONCAT etc. - - GENERAL NOTES - - A set function cannot be used in certain positions where expressions are - accepted. There are some quite explicable restrictions for the usage of - set functions. - - In the query: - SELECT AVG(b) FROM t1 WHERE SUM(b) > 20 GROUP by a - the usage of the set function AVG(b) is legal, while the usage of SUM(b) - is illegal. A WHERE condition must contain expressions that can be - evaluated for each row of the table. Yet the expression SUM(b) can be - evaluated only for each group of rows with the same value of column a. - In the query: - SELECT AVG(b) FROM t1 WHERE c > 30 GROUP BY a HAVING SUM(b) > 20 - both set function expressions AVG(b) and SUM(b) are legal. - - We can say that in a query without nested selects an occurrence of a - set function in an expression of the SELECT list or/and in the HAVING - clause is legal, while in the WHERE clause it's illegal. - - The general rule to detect whether a set function is legal in a query with - nested subqueries is much more complicated. - - Consider the the following query: - SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a > ALL (SELECT t2.c FROM t2 WHERE SUM(t1.b) < t2.c). - The set function SUM(b) is used here in the WHERE clause of the subquery. - Nevertheless it is legal since it is under the HAVING clause of the query - to which this function relates. The expression SUM(t1.b) is evaluated - for each group defined in the main query, not for groups of the subquery. - - The problem of finding the query where to aggregate a particular - set function is not so simple as it seems to be. - - In the query: - SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a > ALL(SELECT t2.c FROM t2 GROUP BY t2.c - HAVING SUM(t1.a) < t2.c) - the set function can be evaluated for both outer and inner selects. - If we evaluate SUM(t1.a) for the outer query then we get the value of t1.a - multiplied by the cardinality of a group in table t1. In this case - in each correlated subquery SUM(t1.a) is used as a constant. But we also - can evaluate SUM(t1.a) for the inner query. In this case t1.a will be a - constant for each correlated subquery and summation is performed - for each group of table t2. - (Here it makes sense to remind that the query - SELECT c FROM t GROUP BY a HAVING SUM(1) < a - is quite legal in our SQL). - - So depending on what query we assign the set function to we - can get different result sets. - - The general rule to detect the query where a set function is to be - evaluated can be formulated as follows. - Consider a set function S(E) where E is an expression with occurrences - of column references C1, ..., CN. Resolve these column references against - subqueries that contain the set function S(E). Let Q be the innermost - subquery of those subqueries. (It should be noted here that S(E) - in no way can be evaluated in the subquery embedding the subquery Q, - otherwise S(E) would refer to at least one unbound column reference) - If S(E) is used in a construct of Q where set functions are allowed then - we evaluate S(E) in Q. - Otherwise we look for a innermost subquery containing S(E) of those where - usage of S(E) is allowed. - - Let's demonstrate how this rule is applied to the following queries. - - 1. SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b - HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c - HAVING SUM(t1.a+t2.b) < t3.c)) - For this query the set function SUM(t1.a+t2.b) depends on t1.a and t2.b - with t1.a defined in the outermost query, and t2.b defined for its - subquery. The set function is in the HAVING clause of the subquery and can - be evaluated in this subquery. - - 2. SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a > ALL(SELECT t2.b FROM t2 - WHERE t2.b > ALL (SELECT t3.c FROM t3 GROUP BY t3.c - HAVING SUM(t1.a+t2.b) < t3.c)) - Here the set function SUM(t1.a+t2.b)is in the WHERE clause of the second - subquery - the most upper subquery where t1.a and t2.b are defined. - If we evaluate the function in this subquery we violate the context rules. - So we evaluate the function in the third subquery (over table t3) where it - is used under the HAVING clause. - - 3. SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a > ALL(SELECT t2.b FROM t2 - WHERE t2.b > ALL (SELECT t3.c FROM t3 - WHERE SUM(t1.a+t2.b) < t3.c)) - In this query evaluation of SUM(t1.a+t2.b) is not legal neither in the second - nor in the third subqueries. So this query is invalid. - - Mostly set functions cannot be nested. In the query - SELECT t1.a from t1 GROUP BY t1.a HAVING AVG(SUM(t1.b)) > 20 - the expression SUM(b) is not acceptable, though it is under a HAVING clause. - Yet it is acceptable in the query: - SELECT t.1 FROM t1 GROUP BY t1.a HAVING SUM(t1.b) > 20. - - An argument of a set function does not have to be a reference to a table - column as we saw it in examples above. This can be a more complex expression - SELECT t1.a FROM t1 GROUP BY t1.a HAVING SUM(t1.b+1) > 20. - The expression SUM(t1.b+1) has a very clear semantics in this context: - we sum up the values of t1.b+1 where t1.b varies for all values within a - group of rows that contain the same t1.a value. - - A set function for an outer query yields a constant within a subquery. So - the semantics of the query - SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c - HAVING AVG(t2.c+SUM(t1.b)) > 20) - is still clear. For a group of the rows with the same t1.a values we - calculate the value of SUM(t1.b). This value 's' is substituted in the - the subquery: - SELECT t2.c FROM t2 GROUP BY t2.c HAVING AVG(t2.c+s) - than returns some result set. - - By the same reason the following query with a subquery - SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c - HAVING AVG(SUM(t1.b)) > 20) - is also acceptable. - - IMPLEMENTATION NOTES - - Three methods were added to the class to check the constraints specified - in the previous section. These methods utilize several new members. - - The field 'nest_level' contains the number of the level for the subquery - containing the set function. The main SELECT is of level 0, its subqueries - are of levels 1, the subqueries of the latter are of level 2 and so on. - - The field 'aggr_level' is to contain the nest level of the subquery - where the set function is aggregated. - - The field 'max_arg_level' is for the maximum of the nest levels of the - unbound column references occurred in the set function. A column reference - is unbound within a set function if it is not bound by any subquery - used as a subexpression in this function. A column reference is bound by - a subquery if it is a reference to the column by which the aggregation - of some set function that is used in the subquery is calculated. - For the set function used in the query - SELECT t1.a FROM t1 GROUP BY t1.a - HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b - HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c - HAVING SUM(t1.a+t2.b) < t3.c)) - the value of max_arg_level is equal to 1 since t1.a is bound in the main - query, and t2.b is bound by the first subquery whose nest level is 1. - Obviously a set function cannot be aggregated in the subquery whose - nest level is less than max_arg_level. (Yet it can be aggregated in the - subqueries whose nest level is greater than max_arg_level.) - In the query - SELECT t.a FROM t1 HAVING AVG(t1.a+(SELECT MIN(t2.c) FROM t2)) - the value of the max_arg_level for the AVG set function is 0 since - the reference t2.c is bound in the subquery. - - The field 'max_sum_func_level' is to contain the maximum of the - nest levels of the set functions that are used as subexpressions of - the arguments of the given set function, but not aggregated in any - subquery within this set function. A nested set function s1 can be - used within set function s0 only if s1.max_sum_func_level < - s0.max_sum_func_level. Set function s1 is considered as nested - for set function s0 if s1 is not calculated in any subquery - within s0. - - A set function that is used as a subexpression in an argument of another - set function refers to the latter via the field 'in_sum_func'. - - The condition imposed on the usage of set functions are checked when - we traverse query subexpressions with the help of the recursive method - fix_fields. When we apply this method to an object of the class - Item_sum, first, on the descent, we call the method init_sum_func_check - that initialize members used at checking. Then, on the ascent, we - call the method check_sum_func that validates the set function usage - and reports an error if it is illegal. - The method register_sum_func serves to link the items for the set functions - that are aggregated in the embedding (sub)queries. Circular chains of such - functions are attached to the corresponding st_select_lex structures - through the field inner_sum_func_list. - - Exploiting the fact that the members mentioned above are used in one - recursive function we could have allocated them on the thread stack. - Yet we don't do it now. - - We assume that the nesting level of subquries does not exceed 127. - TODO: to catch queries where the limit is exceeded to make the - code clean here. - - @note - The implementation takes into account the used strategy: - - Items resolved at optimization phase return 0 from Item_sum::used_tables(). - - Items that depend on the number of join output records, but not columns of - any particular table (like COUNT(*)), returm 0 from Item_sum::used_tables(), - but still return false from Item_sum::const_item(). -*/ - -class Item_sum :public Item_func_or_sum -{ - friend class Aggregator_distinct; - friend class Aggregator_simple; - -protected: - /** - Aggregator class instance. Not set initially. Allocated only after - it is determined if the incoming data are already distinct. - */ - Aggregator *aggr; - -private: - /** - Used in making ROLLUP. Set for the ROLLUP copies of the original - Item_sum and passed to create_tmp_field() to cause it to work - over the temp table buffer that is referenced by - Item_result_field::result_field. - */ - bool force_copy_fields; - - /** - Indicates how the aggregate function was specified by the parser : - 1 if it was written as AGGREGATE(DISTINCT), - 0 if it was AGGREGATE() - */ - bool with_distinct; - - /* TRUE if this is aggregate function of a window function */ - bool window_func_sum_expr_flag; - -public: - - bool has_force_copy_fields() const { return force_copy_fields; } - bool has_with_distinct() const { return with_distinct; } - - enum Sumfunctype - { COUNT_FUNC, COUNT_DISTINCT_FUNC, SUM_FUNC, SUM_DISTINCT_FUNC, AVG_FUNC, - AVG_DISTINCT_FUNC, MIN_FUNC, MAX_FUNC, STD_FUNC, - VARIANCE_FUNC, SUM_BIT_FUNC, UDF_SUM_FUNC, GROUP_CONCAT_FUNC, - ROW_NUMBER_FUNC, RANK_FUNC, DENSE_RANK_FUNC, PERCENT_RANK_FUNC, - CUME_DIST_FUNC, NTILE_FUNC, FIRST_VALUE_FUNC, LAST_VALUE_FUNC, - NTH_VALUE_FUNC, LEAD_FUNC, LAG_FUNC, PERCENTILE_CONT_FUNC, - PERCENTILE_DISC_FUNC, SP_AGGREGATE_FUNC, JSON_ARRAYAGG_FUNC, - JSON_OBJECTAGG_FUNC - }; - - Item **ref_by; /* pointer to a ref to the object used to register it */ - Item_sum *next; /* next in the circular chain of registered objects */ - Item_sum *in_sum_func; /* embedding set function if any */ - st_select_lex * aggr_sel; /* select where the function is aggregated */ - int8 nest_level; /* number of the nesting level of the set function */ - int8 aggr_level; /* nesting level of the aggregating subquery */ - int8 max_arg_level; /* max level of unbound column references */ - int8 max_sum_func_level;/* max level of aggregation for embedded functions */ - bool quick_group; /* If incremental update of fields */ - /* - This list is used by the check for mixing non aggregated fields and - sum functions in the ONLY_FULL_GROUP_BY_MODE. We save all outer fields - directly or indirectly used under this function it as it's unclear - at the moment of fixing outer field whether it's aggregated or not. - */ - List outer_fields; - -protected: - /* - Copy of the arguments list to hold the original set of arguments. - Used in EXPLAIN EXTENDED instead of the current argument list because - the current argument list can be altered by usage of temporary tables. - */ - Item **orig_args, *tmp_orig_args[2]; - - static size_t ram_limitation(THD *thd); -public: - // Methods used by ColumnStore - Item **get_orig_args() const { return orig_args; } -public: - - void mark_as_sum_func(); - Item_sum(THD *thd): Item_func_or_sum(thd), quick_group(1) - { - mark_as_sum_func(); - init_aggregator(); - } - Item_sum(THD *thd, Item *a): Item_func_or_sum(thd, a), quick_group(1), - orig_args(tmp_orig_args) - { - mark_as_sum_func(); - init_aggregator(); - } - Item_sum(THD *thd, Item *a, Item *b): Item_func_or_sum(thd, a, b), - quick_group(1), orig_args(tmp_orig_args) - { - mark_as_sum_func(); - init_aggregator(); - } - Item_sum(THD *thd, List &list); - //Copy constructor, need to perform subselects with temporary tables - Item_sum(THD *thd, Item_sum *item); - enum Type type() const { return SUM_FUNC_ITEM; } - virtual enum Sumfunctype sum_func () const=0; - bool is_aggr_sum_func() - { - switch (sum_func()) { - case COUNT_FUNC: - case COUNT_DISTINCT_FUNC: - case SUM_FUNC: - case SUM_DISTINCT_FUNC: - case AVG_FUNC: - case AVG_DISTINCT_FUNC: - case MIN_FUNC: - case MAX_FUNC: - case STD_FUNC: - case VARIANCE_FUNC: - case SUM_BIT_FUNC: - case UDF_SUM_FUNC: - case GROUP_CONCAT_FUNC: - case JSON_ARRAYAGG_FUNC: - return true; - default: - return false; - } - } - /** - Resets the aggregate value to its default and aggregates the current - value of its attribute(s). - */ - inline bool reset_and_add() - { - aggregator_clear(); - return aggregator_add(); - }; - - /* - Called when new group is started and results are being saved in - a temporary table. Similarly to reset_and_add() it resets the - value to its default and aggregates the value of its - attribute(s), but must also store it in result_field. - This set of methods (result_item(), reset_field, update_field()) of - Item_sum is used only if quick_group is not null. Otherwise - copy_or_same() is used to obtain a copy of this item. - */ - virtual void reset_field()=0; - /* - Called for each new value in the group, when temporary table is in use. - Similar to add(), but uses temporary table field to obtain current value, - Updated value is then saved in the field. - */ - virtual void update_field()=0; - virtual bool fix_length_and_dec() - { maybe_null=1; null_value=1; return FALSE; } - virtual Item *result_item(THD *thd, Field *field); - - void update_used_tables (); - COND *build_equal_items(THD *thd, COND_EQUAL *inherited, - bool link_item_fields, - COND_EQUAL **cond_equal_ref) - { - /* - Item_sum (and derivants) of the original WHERE/HAVING clauses - should already be replaced to Item_aggregate_ref by the time when - build_equal_items() is called. See Item::split_sum_func2(). - */ - DBUG_ASSERT(0); - return Item::build_equal_items(thd, inherited, link_item_fields, - cond_equal_ref); - } - bool is_null() { return null_value; } - /** - make_const() - Called if we've managed to calculate the value of this Item in - opt_sum_query(), hence it can be considered constant at all subsequent - steps. - */ - void make_const () - { - used_tables_cache= 0; - const_item_cache= true; - } - void reset_forced_const() { const_item_cache= false; } - virtual bool const_during_execution() const { return false; } - virtual void print(String *str, enum_query_type query_type); - void fix_num_length_and_dec(); - - /** - Mark an aggregate as having no rows. - - This function is called by the execution engine to assign 'NO ROWS - FOUND' value to an aggregate item, when the underlying result set - has no rows. Such value, in a general case, may be different from - the default value of the item after 'clear()': e.g. a numeric item - may be initialized to 0 by clear() and to NULL by - no_rows_in_result(). - */ - virtual void no_rows_in_result() - { - set_aggregator(with_distinct ? - Aggregator::DISTINCT_AGGREGATOR : - Aggregator::SIMPLE_AGGREGATOR); - aggregator_clear(); - } - virtual void make_unique() { force_copy_fields= TRUE; } - Item *get_tmp_table_item(THD *thd); - virtual Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table); - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - return create_tmp_field(root, param->group(), table); - } - virtual bool collect_outer_ref_processor(void *param); - bool init_sum_func_check(THD *thd); - bool check_sum_func(THD *thd, Item **ref); - bool register_sum_func(THD *thd, Item **ref); - st_select_lex *depended_from() - { return (nest_level == aggr_level ? 0 : aggr_sel); } - - Item *get_arg(uint i) const { return args[i]; } - Item *set_arg(uint i, THD *thd, Item *new_val); - uint get_arg_count() const { return arg_count; } - virtual Item **get_args() { return fixed ? orig_args : args; } - - /* Initialization of distinct related members */ - void init_aggregator() - { - aggr= NULL; - with_distinct= FALSE; - force_copy_fields= FALSE; - } - - /** - Called to initialize the aggregator. - */ - - inline bool aggregator_setup(THD *thd) { return aggr->setup(thd); }; - - /** - Called to cleanup the aggregator. - */ - - inline void aggregator_clear() { aggr->clear(); } - - /** - Called to add value to the aggregator. - */ - - inline bool aggregator_add() { return aggr->add(); }; - - /* stores the declared DISTINCT flag (from the parser) */ - void set_distinct(bool distinct) - { - with_distinct= distinct; - quick_group= with_distinct ? 0 : 1; - } - - /* - Set the type of aggregation : DISTINCT or not. - - May be called multiple times. - */ - - int set_aggregator(Aggregator::Aggregator_type aggregator); - - virtual void clear()= 0; - virtual bool add()= 0; - virtual bool setup(THD *thd) { return false; } - - virtual bool supports_removal() const { return false; } - virtual void remove() { DBUG_ASSERT(0); } - - virtual void cleanup(); - bool check_vcol_func_processor(void *arg); - virtual void setup_window_func(THD *thd, Window_spec *window_spec) {} - void mark_as_window_func_sum_expr() { window_func_sum_expr_flag= true; } - bool is_window_func_sum_expr() { return window_func_sum_expr_flag; } - virtual void setup_caches(THD *thd) {}; - - bool with_sum_func() const { return true; } - virtual void set_partition_row_count(ulonglong count) { DBUG_ASSERT(0); } -}; - - -class Unique; - - -/** - The distinct aggregator. - Implements AGGFN (DISTINCT ..) - Collects all the data into an Unique (similarly to what Item_sum - does currently when with_distinct=true) and then (if applicable) iterates over - the list of unique values and pumps them back into its object -*/ - -class Aggregator_distinct : public Aggregator -{ - friend class Item_sum_sum; - - /* - flag to prevent consecutive runs of endup(). Normally in endup there are - expensive calculations (like walking the distinct tree for example) - which we must do only once if there are no data changes. - We can re-use the data for the second and subsequent val_xxx() calls. - endup_done set to TRUE also means that the calculated values for - the aggregate functions are correct and don't need recalculation. - */ - bool endup_done; - - /* - Used depending on the type of the aggregate function and the presence of - blob columns in it: - - For COUNT(DISTINCT) and no blob fields this points to a real temporary - table. It's used as a hash table. - - For AVG/SUM(DISTINCT) or COUNT(DISTINCT) with blob fields only the - in-memory data structure of a temporary table is constructed. - It's used by the Field classes to transform data into row format. - */ - TABLE *table; - - /* - An array of field lengths on row allocated and used only for - COUNT(DISTINCT) with multiple columns and no blobs. Used in - Aggregator_distinct::composite_key_cmp (called from Unique to compare - nodes - */ - uint32 *field_lengths; - - /* - Used in conjunction with 'table' to support the access to Field classes - for COUNT(DISTINCT). Needed by copy_fields()/copy_funcs(). - */ - TMP_TABLE_PARAM *tmp_table_param; - - /* - If there are no blobs in the COUNT(DISTINCT) arguments, we can use a tree, - which is faster than heap table. In that case, we still use the table - to help get things set up, but we insert nothing in it. - For AVG/SUM(DISTINCT) we always use this tree (as it takes a single - argument) to get the distinct rows. - */ - Unique *tree; - - /* - The length of the temp table row. Must be a member of the class as it - gets passed down to simple_raw_key_cmp () as a compare function argument - to Unique. simple_raw_key_cmp () is used as a fast comparison function - when the entire row can be binary compared. - */ - uint tree_key_length; - - /* - Set to true if the result is known to be always NULL. - If set deactivates creation and usage of the temporary table (in the - 'table' member) and the Unique instance (in the 'tree' member) as well as - the calculation of the final value on the first call to - Item_[sum|avg|count]::val_xxx(). - */ - bool always_null; - - /** - When feeding back the data in endup() from Unique/temp table back to - Item_sum::add() methods we must read the data from Unique (and not - recalculate the functions that are given as arguments to the aggregate - function. - This flag is to tell the arg_*() methods to take the data from the Unique - instead of calling the relevant val_..() method. - */ - bool use_distinct_values; - -public: - Aggregator_distinct (Item_sum *sum) : - Aggregator(sum), table(NULL), tmp_table_param(NULL), tree(NULL), - always_null(false), use_distinct_values(false) {} - virtual ~Aggregator_distinct (); - Aggregator_type Aggrtype() { return DISTINCT_AGGREGATOR; } - - bool setup(THD *); - void clear(); - bool add(); - void endup(); - virtual my_decimal *arg_val_decimal(my_decimal * value); - virtual double arg_val_real(); - virtual bool arg_is_null(bool use_null_value); - - bool unique_walk_function(void *element); - bool unique_walk_function_for_count(void *element); - static int composite_key_cmp(void* arg, uchar* key1, uchar* key2); -}; - - -/** - The pass-through aggregator. - Implements AGGFN (DISTINCT ..) by knowing it gets distinct data on input. - So it just pumps them back to the Item_sum descendant class. -*/ -class Aggregator_simple : public Aggregator -{ -public: - - Aggregator_simple (Item_sum *sum) : - Aggregator(sum) {} - Aggregator_type Aggrtype() { return Aggregator::SIMPLE_AGGREGATOR; } - - bool setup(THD * thd) { return item_sum->setup(thd); } - void clear() { item_sum->clear(); } - bool add() { return item_sum->add(); } - void endup() {}; - virtual my_decimal *arg_val_decimal(my_decimal * value); - virtual double arg_val_real(); - virtual bool arg_is_null(bool use_null_value); -}; - - -class Item_sum_num :public Item_sum -{ -public: - Item_sum_num(THD *thd): Item_sum(thd) {} - Item_sum_num(THD *thd, Item *item_par): - Item_sum(thd, item_par) {} - Item_sum_num(THD *thd, Item *a, Item* b): - Item_sum(thd, a, b) {} - Item_sum_num(THD *thd, List &list): - Item_sum(thd, list) {} - Item_sum_num(THD *thd, Item_sum_num *item): - Item_sum(thd, item) {} - bool fix_fields(THD *, Item **); -}; - - -class Item_sum_double :public Item_sum_num -{ -public: - Item_sum_double(THD *thd): Item_sum_num(thd) {} - Item_sum_double(THD *thd, Item *item_par): Item_sum_num(thd, item_par) {} - Item_sum_double(THD *thd, List &list): Item_sum_num(thd, list) {} - Item_sum_double(THD *thd, Item_sum_double *item) :Item_sum_num(thd, item) {} - longlong val_int() - { - return val_int_from_real(); - } - String *val_str(String*str) - { - return val_string_from_real(str); - } - my_decimal *val_decimal(my_decimal *to) - { - return val_decimal_from_real(to); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return get_date_from_real(thd, ltime, fuzzydate); - } - const Type_handler *type_handler() const { return &type_handler_double; } -}; - - -class Item_sum_int :public Item_sum_num -{ -public: - Item_sum_int(THD *thd): Item_sum_num(thd) {} - Item_sum_int(THD *thd, Item *item_par): Item_sum_num(thd, item_par) {} - Item_sum_int(THD *thd, List &list): Item_sum_num(thd, list) {} - Item_sum_int(THD *thd, Item_sum_int *item) :Item_sum_num(thd, item) {} - double val_real() { DBUG_ASSERT(fixed == 1); return (double) val_int(); } - String *val_str(String*str); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return get_date_from_int(thd, ltime, fuzzydate); - } - bool fix_length_and_dec() - { decimals=0; max_length=21; maybe_null=null_value=0; return FALSE; } -}; - - -class Item_sum_sum :public Item_sum_num, - public Type_handler_hybrid_field_type -{ -protected: - bool direct_added; - bool direct_reseted_field; - bool direct_sum_is_null; - double direct_sum_real; - double sum; - my_decimal direct_sum_decimal; - my_decimal dec_buffs[2]; - uint curr_dec_buff; - bool fix_length_and_dec(); - -public: - Item_sum_sum(THD *thd, Item *item_par, bool distinct): - Item_sum_num(thd, item_par), direct_added(FALSE), - direct_reseted_field(FALSE) - { - set_distinct(distinct); - } - Item_sum_sum(THD *thd, Item_sum_sum *item); - enum Sumfunctype sum_func () const - { - return has_with_distinct() ? SUM_DISTINCT_FUNC : SUM_FUNC; - } - void cleanup(); - void direct_add(my_decimal *add_sum_decimal); - void direct_add(double add_sum_real, bool add_sum_is_null); - void clear(); - bool add(); - double val_real(); - longlong val_int(); - String *val_str(String*str); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - void fix_length_and_dec_double(); - void fix_length_and_dec_decimal(); - void reset_field(); - void update_field(); - void no_rows_in_result() {} - const char *func_name() const - { - return has_with_distinct() ? "sum(distinct " : "sum("; - } - Item *copy_or_same(THD* thd); - void remove(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - - bool supports_removal() const - { - return true; - } - -private: - void add_helper(bool perform_removal); - ulonglong count; -}; - - -class Item_sum_count :public Item_sum_int -{ - bool direct_counted; - bool direct_reseted_field; - longlong direct_count; - longlong count; - - friend class Aggregator_distinct; - - void clear(); - bool add(); - void cleanup(); - void remove(); - -public: - Item_sum_count(THD *thd, Item *item_par): - Item_sum_int(thd, item_par), direct_counted(FALSE), - direct_reseted_field(FALSE), count(0) - {} - - /** - Constructs an instance for COUNT(DISTINCT) - - @param list a list of the arguments to the aggregate function - - This constructor is called by the parser only for COUNT (DISTINCT). - */ - - Item_sum_count(THD *thd, List &list): - Item_sum_int(thd, list), direct_counted(FALSE), - direct_reseted_field(FALSE), count(0) - { - set_distinct(TRUE); - } - Item_sum_count(THD *thd, Item_sum_count *item): - Item_sum_int(thd, item), direct_counted(FALSE), - direct_reseted_field(FALSE), count(item->count) - {} - enum Sumfunctype sum_func () const - { - return has_with_distinct() ? COUNT_DISTINCT_FUNC : COUNT_FUNC; - } - void no_rows_in_result() { count=0; } - void make_const(longlong count_arg) - { - count=count_arg; - Item_sum::make_const(); - } - const Type_handler *type_handler() const { return &type_handler_slonglong; } - longlong val_int(); - void reset_field(); - void update_field(); - void direct_add(longlong add_count); - const char *func_name() const - { - return has_with_distinct() ? "count(distinct " : "count("; - } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - - bool supports_removal() const - { - return true; - } -}; - - -class Item_sum_avg :public Item_sum_sum -{ -public: - // TODO-cvicentiu given that Item_sum_sum now uses a counter of its own, in - // order to implement remove(), it is possible to remove this member. - ulonglong count; - uint prec_increment; - uint f_precision, f_scale, dec_bin_size; - - Item_sum_avg(THD *thd, Item *item_par, bool distinct): - Item_sum_sum(thd, item_par, distinct), count(0) - {} - Item_sum_avg(THD *thd, Item_sum_avg *item) - :Item_sum_sum(thd, item), count(item->count), - prec_increment(item->prec_increment) {} - - void fix_length_and_dec_double(); - void fix_length_and_dec_decimal(); - bool fix_length_and_dec(); - enum Sumfunctype sum_func () const - { - return has_with_distinct() ? AVG_DISTINCT_FUNC : AVG_FUNC; - } - void clear(); - bool add(); - void remove(); - double val_real(); - // In SPs we might force the "wrong" type with select into a declare variable - longlong val_int() { return val_int_from_real(); } - my_decimal *val_decimal(my_decimal *); - String *val_str(String *str); - void reset_field(); - void update_field(); - Item *result_item(THD *thd, Field *field); - void no_rows_in_result() {} - const char *func_name() const - { - return has_with_distinct() ? "avg(distinct " : "avg("; - } - Item *copy_or_same(THD* thd); - Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table); - void cleanup() - { - count= 0; - Item_sum_sum::cleanup(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - - bool supports_removal() const - { - return true; - } -}; - - -/* - variance(a) = - - = sum (ai - avg(a))^2 / count(a) ) - = sum (ai^2 - 2*ai*avg(a) + avg(a)^2) / count(a) - = (sum(ai^2) - sum(2*ai*avg(a)) + sum(avg(a)^2))/count(a) = - = (sum(ai^2) - 2*avg(a)*sum(a) + count(a)*avg(a)^2)/count(a) = - = (sum(ai^2) - 2*sum(a)*sum(a)/count(a) + count(a)*sum(a)^2/count(a)^2 )/count(a) = - = (sum(ai^2) - 2*sum(a)^2/count(a) + sum(a)^2/count(a) )/count(a) = - = (sum(ai^2) - sum(a)^2/count(a))/count(a) - -But, this falls prey to catastrophic cancellation. Instead, use the recurrence formulas - - M_{1} = x_{1}, ~ M_{k} = M_{k-1} + (x_{k} - M_{k-1}) / k newline - S_{1} = 0, ~ S_{k} = S_{k-1} + (x_{k} - M_{k-1}) times (x_{k} - M_{k}) newline - for 2 <= k <= n newline - ital variance = S_{n} / (n-1) - -*/ - -class Stddev -{ - double m_m; - double m_s; - ulonglong m_count; -public: - Stddev() :m_m(0), m_s(0), m_count(0) { } - Stddev(double nr) :m_m(nr), m_s(0.0), m_count(1) { } - Stddev(const uchar *); - void to_binary(uchar *) const; - void recurrence_next(double nr); - double result(bool is_simple_variance); - ulonglong count() const { return m_count; } - static uint32 binary_size() - { - return (uint32) (sizeof(double) * 2 + sizeof(ulonglong)); - }; -}; - - - -class Item_sum_variance :public Item_sum_double -{ - Stddev m_stddev; - bool fix_length_and_dec() override; - -public: - uint sample; - uint prec_increment; - - Item_sum_variance(THD *thd, Item *item_par, uint sample_arg): - Item_sum_double(thd, item_par), - sample(sample_arg) - {} - Item_sum_variance(THD *thd, Item_sum_variance *item); - Sumfunctype sum_func () const override { return VARIANCE_FUNC; } - void fix_length_and_dec_double(); - void fix_length_and_dec_decimal(); - void clear() override final; - bool add() override final; - double val_real() override; - void reset_field() override final; - void update_field() override final; - Item *result_item(THD *thd, Field *field) override; - void no_rows_in_result() override final {} - const char *func_name() const override - { return sample ? "var_samp(" : "variance("; } - Item *copy_or_same(THD* thd) override; - Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table) override - final; - void cleanup() override final - { - m_stddev= Stddev(); - Item_sum_double::cleanup(); - } - Item *get_copy(THD *thd) override - { return get_item_copy(thd, this); } -}; - -/* - standard_deviation(a) = sqrt(variance(a)) -*/ - -class Item_sum_std final :public Item_sum_variance -{ - public: - Item_sum_std(THD *thd, Item *item_par, uint sample_arg): - Item_sum_variance(thd, item_par, sample_arg) {} - Item_sum_std(THD *thd, Item_sum_std *item) - :Item_sum_variance(thd, item) - {} - enum Sumfunctype sum_func () const override final { return STD_FUNC; } - double val_real() override final; - Item *result_item(THD *thd, Field *field) override final; - const char *func_name() const override final { return "std("; } - Item *copy_or_same(THD* thd) override final; - Item *get_copy(THD *thd) override final - { return get_item_copy(thd, this); } -}; - - -class Item_sum_hybrid : public Item_sum, - public Type_handler_hybrid_field_type -{ -public: - Item_sum_hybrid(THD *thd, Item *item_par): - Item_sum(thd, item_par), - Type_handler_hybrid_field_type(&type_handler_slonglong) - { collation.set(&my_charset_bin); } - Item_sum_hybrid(THD *thd, Item *a, Item *b): - Item_sum(thd, a, b), - Type_handler_hybrid_field_type(&type_handler_slonglong) - { collation.set(&my_charset_bin); } - Item_sum_hybrid(THD *thd, Item_sum_hybrid *item) - :Item_sum(thd, item), - Type_handler_hybrid_field_type(item) - { } - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - bool fix_length_and_dec_generic(); - bool fix_length_and_dec_numeric(const Type_handler *h); - bool fix_length_and_dec_string(); -}; - - -// This class is a string or number function depending on num_func -class Arg_comparator; -class Item_cache; -class Item_sum_min_max :public Item_sum_hybrid -{ -protected: - bool direct_added; - Item *direct_item; - Item_cache *value, *arg_cache; - Arg_comparator *cmp; - int cmp_sign; - bool was_values; // Set if we have found at least one row (for max/min only) - bool was_null_value; - -public: - Item_sum_min_max(THD *thd, Item *item_par,int sign): - Item_sum_hybrid(thd, item_par), - direct_added(FALSE), value(0), arg_cache(0), cmp(0), - cmp_sign(sign), was_values(TRUE) - { collation.set(&my_charset_bin); } - Item_sum_min_max(THD *thd, Item_sum_min_max *item) - :Item_sum_hybrid(thd, item), - direct_added(FALSE), value(item->value), arg_cache(0), - cmp_sign(item->cmp_sign), was_values(item->was_values) - { } - bool fix_fields(THD *, Item **); - bool fix_length_and_dec(); - void setup_hybrid(THD *thd, Item *item, Item *value_arg); - void clear(); - void direct_add(Item *item); - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal *); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - void reset_field(); - String *val_str(String *); - bool val_native(THD *thd, Native *); - const Type_handler *real_type_handler() const - { - return get_arg(0)->real_type_handler(); - } - const TYPELIB *get_typelib() const { return args[0]->get_typelib(); } - void update_field(); - void min_max_update_str_field(); - void min_max_update_real_field(); - void min_max_update_int_field(); - void min_max_update_decimal_field(); - void min_max_update_native_field(); - void cleanup(); - bool any_value() { return was_values; } - void no_rows_in_result(); - void restore_to_before_no_rows_in_result(); - Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table); - void setup_caches(THD *thd) { setup_hybrid(thd, arguments()[0], NULL); } -}; - - -class Item_sum_min final :public Item_sum_min_max -{ -public: - Item_sum_min(THD *thd, Item *item_par): Item_sum_min_max(thd, item_par, 1) {} - Item_sum_min(THD *thd, Item_sum_min *item) :Item_sum_min_max(thd, item) {} - enum Sumfunctype sum_func () const {return MIN_FUNC;} - - bool add(); - const char *func_name() const { return "min("; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_sum_max final :public Item_sum_min_max -{ -public: - Item_sum_max(THD *thd, Item *item_par): Item_sum_min_max(thd, item_par, -1) {} - Item_sum_max(THD *thd, Item_sum_max *item) :Item_sum_min_max(thd, item) {} - enum Sumfunctype sum_func () const {return MAX_FUNC;} - - bool add(); - const char *func_name() const { return "max("; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_sum_bit :public Item_sum_int -{ -public: - Item_sum_bit(THD *thd, Item *item_par, ulonglong reset_arg): - Item_sum_int(thd, item_par), reset_bits(reset_arg), bits(reset_arg), - as_window_function(FALSE), num_values_added(0) {} - Item_sum_bit(THD *thd, Item_sum_bit *item): - Item_sum_int(thd, item), reset_bits(item->reset_bits), bits(item->bits), - as_window_function(item->as_window_function), - num_values_added(item->num_values_added) - { - if (as_window_function) - memcpy(bit_counters, item->bit_counters, sizeof(bit_counters)); - } - enum Sumfunctype sum_func () const {return SUM_BIT_FUNC;} - void clear(); - longlong val_int(); - void reset_field(); - void update_field(); - const Type_handler *type_handler() const { return &type_handler_ulonglong; } - bool fix_length_and_dec() - { - if (args[0]->check_type_can_return_int(func_name())) - return true; - decimals= 0; max_length=21; unsigned_flag= 1; maybe_null= null_value= 0; - return FALSE; - } - void cleanup() - { - bits= reset_bits; - if (as_window_function) - clear_as_window(); - Item_sum_int::cleanup(); - } - void setup_window_func(THD *thd __attribute__((unused)), - Window_spec *window_spec __attribute__((unused))) - { - as_window_function= TRUE; - clear_as_window(); - } - void remove() - { - if (as_window_function) - { - remove_as_window(args[0]->val_int()); - return; - } - // Unless we're counting bits, we can not remove anything. - DBUG_ASSERT(0); - } - - bool supports_removal() const - { - return true; - } - -protected: - enum bit_counters { NUM_BIT_COUNTERS= 64 }; - ulonglong reset_bits,bits; - /* - Marks whether the function is to be computed as a window function. - */ - bool as_window_function; - // When used as an aggregate window function, we need to store - // this additional information. - ulonglong num_values_added; - ulonglong bit_counters[NUM_BIT_COUNTERS]; - bool add_as_window(ulonglong value); - bool remove_as_window(ulonglong value); - bool clear_as_window(); - virtual void set_bits_from_counters()= 0; -}; - - -class Item_sum_or final :public Item_sum_bit -{ -public: - Item_sum_or(THD *thd, Item *item_par): Item_sum_bit(thd, item_par, 0) {} - Item_sum_or(THD *thd, Item_sum_or *item) :Item_sum_bit(thd, item) {} - bool add(); - const char *func_name() const { return "bit_or("; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - -private: - void set_bits_from_counters(); -}; - - -class Item_sum_and final :public Item_sum_bit -{ -public: - Item_sum_and(THD *thd, Item *item_par): - Item_sum_bit(thd, item_par, ULONGLONG_MAX) {} - Item_sum_and(THD *thd, Item_sum_and *item) :Item_sum_bit(thd, item) {} - bool add(); - const char *func_name() const { return "bit_and("; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - -private: - void set_bits_from_counters(); -}; - -class Item_sum_xor final :public Item_sum_bit -{ -public: - Item_sum_xor(THD *thd, Item *item_par): Item_sum_bit(thd, item_par, 0) {} - Item_sum_xor(THD *thd, Item_sum_xor *item) :Item_sum_bit(thd, item) {} - bool add(); - const char *func_name() const { return "bit_xor("; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - -private: - void set_bits_from_counters(); -}; - -class sp_head; -class sp_name; -class Query_arena; -struct st_sp_security_context; - -/* - Item_sum_sp handles STORED AGGREGATE FUNCTIONS - - Each Item_sum_sp represents a custom aggregate function. Inside the - function's body, we require at least one occurrence of FETCH GROUP NEXT ROW - instruction. This cursor is what makes custom stored aggregates possible. - - During computation the function's add method is called. This in turn performs - an execution of the function. The function will execute from the current - function context (and instruction), if one exists, or from the start if not. - See Item_sp for more details. - - Upon encounter of FETCH GROUP NEXT ROW instruction, the function will pause - execution. We assume that the user has performed the necessary additions for - a row, between two encounters of FETCH GROUP NEXT ROW. - - Example: - create aggregate function f1(x INT) returns int - begin - declare continue handler for not found return s; - declare s int default 0 - loop - fetch group next row; - set s = s + x; - end loop; - end - - The function will always stop after an encounter of FETCH GROUP NEXT ROW, - except (!) on first encounter, as the value for the first row in the - group is already set in the argument x. This behaviour is done so when - a user writes a function, he should "logically" include FETCH GROUP NEXT ROW - before any "add" instructions in the stored function. This means however that - internally, the first occurrence doesn't stop the function. See the - implementation of FETCH GROUP NEXT ROW for details as to how it happens. - - Either way, one should assume that after calling "Item_sum_sp::add()" that - the values for that particular row have been added to the aggregation. - - To produce values for val_xxx methods we need an extra syntactic construct. - We require a continue handler when "no more rows are available". val_xxx - methods force a function return by executing the function again, while - setting a server flag that no more rows have been found. This implies - that val_xxx methods should only be called once per group however. - - Example: - DECLARE CONTINUE HANDLER FOR NOT FOUND RETURN ret_val; -*/ -class Item_sum_sp final :public Item_sum, - public Item_sp -{ - private: - bool execute(); - -public: - Item_sum_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name, - sp_head *sp); - - Item_sum_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name, - sp_head *sp, List &list); - Item_sum_sp(THD *thd, Item_sum_sp *item); - - enum Sumfunctype sum_func () const - { - return SP_AGGREGATE_FUNC; - } - Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) - { - return create_table_field_from_handler(root, table); - } - bool fix_length_and_dec(); - bool fix_fields(THD *thd, Item **ref); - const char *func_name() const; - const Type_handler *type_handler() const; - bool add(); - - /* val_xx functions */ - longlong val_int() - { - if(execute()) - return 0; - return sp_result_field->val_int(); - } - - double val_real() - { - if(execute()) - return 0.0; - return sp_result_field->val_real(); - } - - my_decimal *val_decimal(my_decimal *dec_buf) - { - if(execute()) - return NULL; - return sp_result_field->val_decimal(dec_buf); - } - - bool val_native(THD *thd, Native *to) - { - return null_value= execute() || sp_result_field->val_native(to); - } - - String *val_str(String *str) - { - String buf; - char buff[20]; - buf.set(buff, 20, str->charset()); - buf.length(0); - if (execute()) - return NULL; - /* - result_field will set buf pointing to internal buffer - of the resul_field. Due to this it will change any time - when SP is executed. In order to prevent occasional - corruption of returned value, we make here a copy. - */ - sp_result_field->val_str(&buf); - str->copy(buf); - return str; - } - void reset_field(){DBUG_ASSERT(0);} - void update_field(){DBUG_ASSERT(0);} - void clear(); - void cleanup(); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return execute() || sp_result_field->get_date(ltime, fuzzydate); - } - inline Field *get_sp_result_field() - { - return sp_result_field; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - Item *copy_or_same(THD *thd); -}; - -/* Items to get the value of a stored sum function */ - -class Item_sum_field :public Item -{ -protected: - Field *field; -public: - Item_sum_field(THD *thd, Item_sum *item) - :Item(thd), field(item->result_field) - { - name= item->name; - maybe_null= true; - decimals= item->decimals; - max_length= item->max_length; - unsigned_flag= item->unsigned_flag; - } - table_map used_tables() const { return (table_map) 1L; } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - return create_tmp_field_ex_simple(root, table, src, param); - } - void save_in_result_field(bool no_conversions) { DBUG_ASSERT(0); } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(name.str, arg, VCOL_IMPOSSIBLE); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } -}; - - -class Item_avg_field :public Item_sum_field -{ -protected: - uint prec_increment; -public: - Item_avg_field(THD *thd, Item_sum_avg *item) - :Item_sum_field(thd, item), prec_increment(item->prec_increment) - { } - enum Type type() const { return FIELD_AVG_ITEM; } - bool is_null() { update_null_value(); return null_value; } -}; - - -class Item_avg_field_double :public Item_avg_field -{ -public: - Item_avg_field_double(THD *thd, Item_sum_avg *item) - :Item_avg_field(thd, item) - { } - const Type_handler *type_handler() const { return &type_handler_double; } - longlong val_int() { return val_int_from_real(); } - my_decimal *val_decimal(my_decimal *dec) { return val_decimal_from_real(dec); } - String *val_str(String *str) { return val_string_from_real(str); } - double val_real(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_avg_field_decimal :public Item_avg_field -{ - uint f_precision, f_scale, dec_bin_size; -public: - Item_avg_field_decimal(THD *thd, Item_sum_avg *item) - :Item_avg_field(thd, item), - f_precision(item->f_precision), - f_scale(item->f_scale), - dec_bin_size(item->dec_bin_size) - { } - const Type_handler *type_handler() const { return &type_handler_newdecimal; } - double val_real() - { - return VDec(this).to_double(); - } - longlong val_int() - { - return VDec(this).to_longlong(unsigned_flag); - } - String *val_str(String *str) - { - return VDec(this).to_string_round(str, decimals); - } - my_decimal *val_decimal(my_decimal *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_variance_field :public Item_sum_field -{ - uint sample; -public: - Item_variance_field(THD *thd, Item_sum_variance *item) - :Item_sum_field(thd, item), sample(item->sample) - { } - enum Type type() const {return FIELD_VARIANCE_ITEM; } - double val_real(); - longlong val_int() { return val_int_from_real(); } - String *val_str(String *str) - { return val_string_from_real(str); } - my_decimal *val_decimal(my_decimal *dec_buf) - { return val_decimal_from_real(dec_buf); } - bool is_null() { update_null_value(); return null_value; } - const Type_handler *type_handler() const { return &type_handler_double; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_std_field :public Item_variance_field -{ -public: - Item_std_field(THD *thd, Item_sum_std *item) - :Item_variance_field(thd, item) - { } - enum Type type() const { return FIELD_STD_ITEM; } - double val_real(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - User defined aggregates -*/ - -#ifdef HAVE_DLOPEN - -class Item_udf_sum : public Item_sum -{ -protected: - udf_handler udf; - -public: - Item_udf_sum(THD *thd, udf_func *udf_arg): - Item_sum(thd), udf(udf_arg) - { quick_group=0; } - Item_udf_sum(THD *thd, udf_func *udf_arg, List &list): - Item_sum(thd, list), udf(udf_arg) - { quick_group=0;} - Item_udf_sum(THD *thd, Item_udf_sum *item) - :Item_sum(thd, item), udf(item->udf) - { udf.not_original= TRUE; } - const char *func_name() const { return udf.name(); } - bool fix_fields(THD *thd, Item **ref) - { - DBUG_ASSERT(fixed == 0); - - if (init_sum_func_check(thd)) - return TRUE; - - fixed= 1; - /* - We set const_item_cache to false in constructors. - It can be later changed to "true", in a Item_sum::make_const() call. - No make_const() calls should have happened so far. - */ - DBUG_ASSERT(!const_item_cache); - if (udf.fix_fields(thd, this, this->arg_count, this->args)) - return TRUE; - /** - The above call for udf.fix_fields() updates - the Used_tables_and_const_cache part of "this" as if it was a regular - non-aggregate UDF function and can change both const_item_cache and - used_tables_cache members. - - The used_tables_cache will be re-calculated in update_used_tables() - which is called from check_sum_func() below. So we don't care about - its current value. - - The const_item_cache must stay "false" until a Item_sum::make_const() - call happens, if ever. So we need to reset const_item_cache back to - "false" here. - */ - const_item_cache= false; - memcpy (orig_args, args, sizeof (Item *) * arg_count); - return check_sum_func(thd, ref); - } - enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } - virtual bool have_field_update(void) const { return 0; } - - void clear(); - bool add(); - bool supports_removal() const; - void remove(); - void reset_field() {}; - void update_field() {}; - void cleanup(); - virtual void print(String *str, enum_query_type query_type); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } -}; - - -class Item_sum_udf_float :public Item_udf_sum -{ - public: - Item_sum_udf_float(THD *thd, udf_func *udf_arg): - Item_udf_sum(thd, udf_arg) {} - Item_sum_udf_float(THD *thd, udf_func *udf_arg, List &list): - Item_udf_sum(thd, udf_arg, list) {} - Item_sum_udf_float(THD *thd, Item_sum_udf_float *item) - :Item_udf_sum(thd, item) {} - longlong val_int() { return val_int_from_real(); } - double val_real(); - String *val_str(String*str); - my_decimal *val_decimal(my_decimal *); - const Type_handler *type_handler() const { return &type_handler_double; } - bool fix_length_and_dec() { fix_num_length_and_dec(); return FALSE; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_sum_udf_int :public Item_udf_sum -{ -public: - Item_sum_udf_int(THD *thd, udf_func *udf_arg): - Item_udf_sum(thd, udf_arg) {} - Item_sum_udf_int(THD *thd, udf_func *udf_arg, List &list): - Item_udf_sum(thd, udf_arg, list) {} - Item_sum_udf_int(THD *thd, Item_sum_udf_int *item) - :Item_udf_sum(thd, item) {} - longlong val_int(); - double val_real() - { DBUG_ASSERT(fixed == 1); return (double) Item_sum_udf_int::val_int(); } - String *val_str(String*str); - my_decimal *val_decimal(my_decimal *); - const Type_handler *type_handler() const - { - if (unsigned_flag) - return &type_handler_ulonglong; - return &type_handler_slonglong; - } - bool fix_length_and_dec() { decimals=0; max_length=21; return FALSE; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_sum_udf_str :public Item_udf_sum -{ -public: - Item_sum_udf_str(THD *thd, udf_func *udf_arg): - Item_udf_sum(thd, udf_arg) {} - Item_sum_udf_str(THD *thd, udf_func *udf_arg, List &list): - Item_udf_sum(thd, udf_arg, list) {} - Item_sum_udf_str(THD *thd, Item_sum_udf_str *item) - :Item_udf_sum(thd, item) {} - String *val_str(String *); - double val_real() - { - int err_not_used; - char *end_not_used; - String *res; - res=val_str(&str_value); - return res ? res->charset()->strntod((char*) res->ptr(),res->length(), - &end_not_used, &err_not_used) : 0.0; - } - longlong val_int() - { - int err_not_used; - char *end; - String *res; - CHARSET_INFO *cs; - - if (!(res= val_str(&str_value))) - return 0; /* Null value */ - cs= res->charset(); - end= (char*) res->ptr()+res->length(); - return cs->strtoll10(res->ptr(), &end, &err_not_used); - } - my_decimal *val_decimal(my_decimal *dec); - const Type_handler *type_handler() const { return string_type_handler(); } - bool fix_length_and_dec(); - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_sum_udf_decimal :public Item_udf_sum -{ -public: - Item_sum_udf_decimal(THD *thd, udf_func *udf_arg): - Item_udf_sum(thd, udf_arg) {} - Item_sum_udf_decimal(THD *thd, udf_func *udf_arg, List &list): - Item_udf_sum(thd, udf_arg, list) {} - Item_sum_udf_decimal(THD *thd, Item_sum_udf_decimal *item) - :Item_udf_sum(thd, item) {} - String *val_str(String *str) - { - return VDec(this).to_string_round(str, decimals); - } - double val_real() - { - return VDec(this).to_double(); - } - longlong val_int() - { - return VDec(this).to_longlong(unsigned_flag); - } - my_decimal *val_decimal(my_decimal *); - const Type_handler *type_handler() const { return &type_handler_newdecimal; } - bool fix_length_and_dec() { fix_num_length_and_dec(); return FALSE; } - Item *copy_or_same(THD* thd); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -#else /* Dummy functions to get sql_yacc.cc compiled */ - -class Item_sum_udf_float :public Item_sum_double -{ - public: - Item_sum_udf_float(THD *thd, udf_func *udf_arg): - Item_sum_double(thd) {} - Item_sum_udf_float(THD *thd, udf_func *udf_arg, List &list): - Item_sum_double(thd) {} - Item_sum_udf_float(THD *thd, Item_sum_udf_float *item) - :Item_sum_double(thd, item) {} - enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } - double val_real() { DBUG_ASSERT(fixed == 1); return 0.0; } - void clear() {} - bool add() { return 0; } - void reset_field() { DBUG_ASSERT(0); }; - void update_field() {} -}; - - -class Item_sum_udf_int :public Item_sum_double -{ -public: - Item_sum_udf_int(THD *thd, udf_func *udf_arg): - Item_sum_double(thd) {} - Item_sum_udf_int(THD *thd, udf_func *udf_arg, List &list): - Item_sum_double(thd) {} - Item_sum_udf_int(THD *thd, Item_sum_udf_int *item) - :Item_sum_double(thd, item) {} - enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } - longlong val_int() { DBUG_ASSERT(fixed == 1); return 0; } - double val_real() { DBUG_ASSERT(fixed == 1); return 0; } - void clear() {} - bool add() { return 0; } - void reset_field() { DBUG_ASSERT(0); }; - void update_field() {} -}; - - -class Item_sum_udf_decimal :public Item_sum_double -{ - public: - Item_sum_udf_decimal(THD *thd, udf_func *udf_arg): - Item_sum_double(thd) {} - Item_sum_udf_decimal(THD *thd, udf_func *udf_arg, List &list): - Item_sum_double(thd) {} - Item_sum_udf_decimal(THD *thd, Item_sum_udf_float *item) - :Item_sum_double(thd, item) {} - enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } - double val_real() { DBUG_ASSERT(fixed == 1); return 0.0; } - my_decimal *val_decimal(my_decimal *) { DBUG_ASSERT(fixed == 1); return 0; } - void clear() {} - bool add() { return 0; } - void reset_field() { DBUG_ASSERT(0); }; - void update_field() {} -}; - - -class Item_sum_udf_str :public Item_sum_double -{ -public: - Item_sum_udf_str(THD *thd, udf_func *udf_arg): - Item_sum_double(thd) {} - Item_sum_udf_str(THD *thd, udf_func *udf_arg, List &list): - Item_sum_double(thd) {} - Item_sum_udf_str(THD *thd, Item_sum_udf_str *item) - :Item_sum_double(thd, item) {} - String *val_str(String *) - { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } - double val_real() { DBUG_ASSERT(fixed == 1); null_value=1; return 0.0; } - longlong val_int() { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } - bool fix_length_and_dec() { maybe_null=1; max_length=0; return FALSE; } - enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } - void clear() {} - bool add() { return 0; } - void reset_field() { DBUG_ASSERT(0); }; - void update_field() {} -}; - -#endif /* HAVE_DLOPEN */ - -C_MODE_START -int group_concat_key_cmp_with_distinct(void* arg, const void* key1, - const void* key2); -int group_concat_key_cmp_with_distinct_with_nulls(void* arg, const void* key1, - const void* key2); -int group_concat_key_cmp_with_order(void* arg, const void* key1, - const void* key2); -int group_concat_key_cmp_with_order_with_nulls(void *arg, const void *key1, - const void *key2); -int dump_leaf_key(void* key_arg, - element_count count __attribute__((unused)), - void* item_arg); -C_MODE_END - -class Item_func_group_concat : public Item_sum -{ -protected: - TMP_TABLE_PARAM *tmp_table_param; - String result; - String *separator; - TREE tree_base; - TREE *tree; - size_t tree_len; - Item **ref_pointer_array; - - /** - If DISTINCT is used with this GROUP_CONCAT, this member is used to filter - out duplicates. - @see Item_func_group_concat::setup - @see Item_func_group_concat::add - @see Item_func_group_concat::clear - */ - Unique *unique_filter; - TABLE *table; - ORDER **order; - Name_resolution_context *context; - /** The number of ORDER BY items. */ - uint arg_count_order; - /** The number of selected items, aka the expr list. */ - uint arg_count_field; - uint row_count; - bool distinct; - bool warning_for_row; - bool always_null; - bool force_copy_fields; - /** True if entire result of GROUP_CONCAT has been written to output buffer. */ - bool result_finalized; - /** Limits the rows in the result */ - Item *row_limit; - /** Skips a particular number of rows in from the result*/ - Item *offset_limit; - bool limit_clause; - /* copy of the offset limit */ - ulonglong copy_offset_limit; - /*copy of the row limit */ - ulonglong copy_row_limit; - - /* - Following is 0 normal object and pointer to original one for copy - (to correctly free resources) - */ - Item_func_group_concat *original; - - /* - Used by Item_func_group_concat and Item_func_json_arrayagg. The latter - needs null values but the former doesn't. - */ - bool add(bool exclude_nulls); - - friend int group_concat_key_cmp_with_distinct(void* arg, const void* key1, - const void* key2); - friend int group_concat_key_cmp_with_distinct_with_nulls(void* arg, - const void* key1, - const void* key2); - friend int group_concat_key_cmp_with_order(void* arg, const void* key1, - const void* key2); - friend int group_concat_key_cmp_with_order_with_nulls(void *arg, - const void *key1, const void *key2); - friend int dump_leaf_key(void* key_arg, - element_count count __attribute__((unused)), - void* item_arg); - - bool repack_tree(THD *thd); - - /* - Says whether the function should skip NULL arguments - or add them to the result. - Redefined in JSON_ARRAYAGG. - */ - virtual bool skip_nulls() const { return true; } - virtual String *get_str_from_item(Item *i, String *tmp) - { return i->val_str(tmp); } - virtual String *get_str_from_field(Item *i, Field *f, String *tmp, - const uchar *key, size_t offset) - { return f->val_str(tmp, key + offset); } - virtual void cut_max_length(String *result, - uint old_length, uint max_length) const; -public: - // Methods used by ColumnStore - bool get_distinct() const { return distinct; } - uint get_count_field() const { return arg_count_field; } - uint get_order_field() const { return arg_count_order; } - const String* get_separator() const { return separator; } - ORDER** get_order() const { return order; } - -public: - Item_func_group_concat(THD *thd, Name_resolution_context *context_arg, - bool is_distinct, List *is_select, - const SQL_I_List &is_order, String *is_separator, - bool limit_clause, Item *row_limit, Item *offset_limit); - - Item_func_group_concat(THD *thd, Item_func_group_concat *item); - ~Item_func_group_concat(); - void cleanup(); - - enum Sumfunctype sum_func () const {return GROUP_CONCAT_FUNC;} - const char *func_name() const { return "group_concat("; } - const Type_handler *type_handler() const - { - if (too_big_for_varchar()) - return &type_handler_blob; - return &type_handler_varchar; - } - void clear(); - bool add() - { - return add(skip_nulls()); - } - void reset_field() { DBUG_ASSERT(0); } // not used - void update_field() { DBUG_ASSERT(0); } // not used - bool fix_fields(THD *,Item **); - bool setup(THD *thd); - void make_unique(); - double val_real() - { - int error; - const char *end; - String *res; - if (!(res= val_str(&str_value))) - return 0.0; - end= res->ptr() + res->length(); - return (my_strtod(res->ptr(), (char**) &end, &error)); - } - longlong val_int() - { - String *res; - char *end_ptr; - int error; - if (!(res= val_str(&str_value))) - return (longlong) 0; - end_ptr= (char*) res->ptr()+ res->length(); - return my_strtoll10(res->ptr(), &end_ptr, &error); - } - my_decimal *val_decimal(my_decimal *decimal_value) - { - return val_decimal_from_string(decimal_value); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return get_date_from_string(thd, ltime, fuzzydate); - } - String* val_str(String* str); - Item *copy_or_same(THD* thd); - void no_rows_in_result() {} - void print(String *str, enum_query_type query_type); - bool change_context_processor(void *cntx) - { context= (Name_resolution_context *)cntx; return FALSE; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - qsort_cmp2 get_comparator_function_for_distinct(); - qsort_cmp2 get_comparator_function_for_order_by(); - uchar* get_record_pointer(); - uint get_null_bytes(); - -}; - -#endif /* ITEM_SUM_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_timefunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_timefunc.h deleted file mode 100644 index a910b2c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_timefunc.h +++ /dev/null @@ -1,1776 +0,0 @@ -#ifndef ITEM_TIMEFUNC_INCLUDED -#define ITEM_TIMEFUNC_INCLUDED -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. - Copyright (c) 2009-2011, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* Function items used by mysql */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -class MY_LOCALE; - - -bool get_interval_value(THD *thd, Item *args, - interval_type int_type, INTERVAL *interval); - - -class Item_long_func_date_field: public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_date(func_name()); } -public: - Item_long_func_date_field(THD *thd, Item *a) - :Item_long_func(thd, a) { } -}; - - -class Item_long_func_time_field: public Item_long_func -{ - bool check_arguments() const - { return args[0]->check_type_can_return_time(func_name()); } -public: - Item_long_func_time_field(THD *thd, Item *a) - :Item_long_func(thd, a) { } -}; - - -class Item_func_period_add :public Item_long_func -{ - bool check_arguments() const - { return check_argument_types_can_return_int(0, 2); } -public: - Item_func_period_add(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} - longlong val_int(); - const char *func_name() const { return "period_add"; } - bool fix_length_and_dec() - { - max_length=6*MY_CHARSET_BIN_MB_MAXLEN; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_period_diff :public Item_long_func -{ - bool check_arguments() const - { return check_argument_types_can_return_int(0, 2); } -public: - Item_func_period_diff(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} - longlong val_int(); - const char *func_name() const { return "period_diff"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=6*MY_CHARSET_BIN_MB_MAXLEN; - return FALSE; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_to_days :public Item_long_func_date_field -{ -public: - Item_func_to_days(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "to_days"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=6*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - enum_monotonicity_info get_monotonicity_info() const; - longlong val_int_endpoint(bool left_endp, bool *incl_endp); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_to_seconds :public Item_longlong_func -{ - bool check_arguments() const - { return check_argument_types_can_return_date(0, arg_count); } -public: - Item_func_to_seconds(THD *thd, Item *a): Item_longlong_func(thd, a) {} - longlong val_int(); - const char *func_name() const { return "to_seconds"; } - bool fix_length_and_dec() - { - decimals=0; - fix_char_length(12); - maybe_null= 1; - return FALSE; - } - enum_monotonicity_info get_monotonicity_info() const; - longlong val_int_endpoint(bool left_endp, bool *incl_endp); - bool check_partition_func_processor(void *bool_arg) { return FALSE;} - - /* Only meaningful with date part and optional time part */ - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_dayofmonth :public Item_long_func_date_field -{ -public: - Item_func_dayofmonth(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "dayofmonth"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_month :public Item_long_func -{ -public: - Item_func_month(THD *thd, Item *a): Item_long_func(thd, a) - { } - longlong val_int(); - const char *func_name() const { return "month"; } - bool fix_length_and_dec() - { - decimals= 0; - fix_char_length(2); - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_monthname :public Item_str_func -{ - MY_LOCALE *locale; -public: - Item_func_monthname(THD *thd, Item *a): Item_str_func(thd, a) {} - const char *func_name() const { return "monthname"; } - String *val_str(String *str); - bool fix_length_and_dec(); - bool check_partition_func_processor(void *int_arg) {return TRUE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_dayofyear :public Item_long_func_date_field -{ -public: - Item_func_dayofyear(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "dayofyear"; } - bool fix_length_and_dec() - { - decimals= 0; - fix_char_length(3); - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_hour :public Item_long_func_time_field -{ -public: - Item_func_hour(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "hour"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_time_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_minute :public Item_long_func_time_field -{ -public: - Item_func_minute(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "minute"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_time_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_quarter :public Item_long_func_date_field -{ -public: - Item_func_quarter(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "quarter"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=1*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_second :public Item_long_func_time_field -{ -public: - Item_func_second(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "second"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_time_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_week :public Item_long_func -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_date(func_name()) || - (arg_count > 1 && args[1]->check_type_can_return_int(func_name())); - } -public: - Item_func_week(THD *thd, Item *a): Item_long_func(thd, a) {} - Item_func_week(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} - longlong val_int(); - const char *func_name() const { return "week"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_vcol_func_processor(void *arg) - { - if (arg_count == 2) - return FALSE; - return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); - } - bool check_valid_arguments_processor(void *int_arg) - { - return arg_count == 2; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_yearweek :public Item_long_func -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_date(func_name()) || - args[1]->check_type_can_return_int(func_name()); - } -public: - Item_func_yearweek(THD *thd, Item *a, Item *b) - :Item_long_func(thd, a, b) {} - longlong val_int(); - const char *func_name() const { return "yearweek"; } - bool fix_length_and_dec() - { - decimals=0; - max_length=6*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_year :public Item_long_func_date_field -{ -public: - Item_func_year(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "year"; } - enum_monotonicity_info get_monotonicity_info() const; - longlong val_int_endpoint(bool left_endp, bool *incl_endp); - bool fix_length_and_dec() - { - decimals=0; - max_length=4*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_weekday :public Item_long_func -{ - bool odbc_type; -public: - Item_func_weekday(THD *thd, Item *a, bool type_arg): - Item_long_func(thd, a), odbc_type(type_arg) { } - longlong val_int(); - const char *func_name() const - { - return (odbc_type ? "dayofweek" : "weekday"); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } - bool fix_length_and_dec() - { - decimals= 0; - fix_char_length(1); - maybe_null=1; - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_dayname :public Item_str_func -{ - MY_LOCALE *locale; - public: - Item_func_dayname(THD *thd, Item *a): Item_str_func(thd, a) {} - const char *func_name() const { return "dayname"; } - String *val_str(String *str); - const Type_handler *type_handler() const { return &type_handler_varchar; } - bool fix_length_and_dec(); - bool check_partition_func_processor(void *int_arg) {return TRUE;} - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); - } - bool check_valid_arguments_processor(void *int_arg) - { - return !has_date_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_seconds_hybrid: public Item_func_numhybrid -{ -public: - Item_func_seconds_hybrid(THD *thd): Item_func_numhybrid(thd) {} - Item_func_seconds_hybrid(THD *thd, Item *a): Item_func_numhybrid(thd, a) {} - void fix_length_and_dec_generic(uint dec) - { - DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); - decimals= dec; - max_length=17 + (decimals ? decimals + 1 : 0); - maybe_null= true; - if (decimals) - set_handler(&type_handler_newdecimal); - else - set_handler(type_handler_long_or_longlong()); - } - double real_op() { DBUG_ASSERT(0); return 0; } - String *str_op(String *str) { DBUG_ASSERT(0); return 0; } - bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - DBUG_ASSERT(0); - return true; - } -}; - - -class Item_func_unix_timestamp :public Item_func_seconds_hybrid -{ - bool get_timestamp_value(my_time_t *seconds, ulong *second_part); -public: - Item_func_unix_timestamp(THD *thd): Item_func_seconds_hybrid(thd) {} - Item_func_unix_timestamp(THD *thd, Item *a): - Item_func_seconds_hybrid(thd, a) {} - const char *func_name() const { return "unix_timestamp"; } - enum_monotonicity_info get_monotonicity_info() const; - longlong val_int_endpoint(bool left_endp, bool *incl_endp); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - /* - UNIX_TIMESTAMP() depends on the current timezone - (and thus may not be used as a partitioning function) - when its argument is NOT of the TIMESTAMP type. - */ - bool check_valid_arguments_processor(void *int_arg) - { - return !has_timestamp_args(); - } - bool check_vcol_func_processor(void *arg) - { - if (arg_count) - return FALSE; - return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); - } - bool fix_length_and_dec() - { - fix_length_and_dec_generic(arg_count ? - args[0]->datetime_precision(current_thd) : 0); - return FALSE; - } - longlong int_op(); - my_decimal *decimal_op(my_decimal* buf); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_time_to_sec :public Item_func_seconds_hybrid -{ -public: - Item_func_time_to_sec(THD *thd, Item *item): - Item_func_seconds_hybrid(thd, item) {} - const char *func_name() const { return "time_to_sec"; } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_time_args(); - } - bool fix_length_and_dec() - { - fix_length_and_dec_generic(args[0]->time_precision(current_thd)); - return FALSE; - } - longlong int_op(); - my_decimal *decimal_op(my_decimal* buf); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_datefunc :public Item_func -{ -public: - Item_datefunc(THD *thd): Item_func(thd) { } - Item_datefunc(THD *thd, Item *a): Item_func(thd, a) { } - Item_datefunc(THD *thd, Item *a, Item *b): Item_func(thd, a, b) { } - const Type_handler *type_handler() const { return &type_handler_newdate; } - longlong val_int() { return Date(this).to_longlong(); } - double val_real() { return Date(this).to_double(); } - String *val_str(String *to) { return Date(this).to_string(to); } - my_decimal *val_decimal(my_decimal *to) { return Date(this).to_decimal(to); } - bool fix_length_and_dec() - { - fix_attributes_date(); - maybe_null= (arg_count > 0); - return FALSE; - } -}; - - -class Item_timefunc :public Item_func -{ -public: - Item_timefunc(THD *thd): Item_func(thd) {} - Item_timefunc(THD *thd, Item *a): Item_func(thd, a) {} - Item_timefunc(THD *thd, Item *a, Item *b): Item_func(thd, a, b) {} - Item_timefunc(THD *thd, Item *a, Item *b, Item *c): Item_func(thd, a, b ,c) {} - const Type_handler *type_handler() const { return &type_handler_time2; } - longlong val_int() { return Time(this).to_longlong(); } - double val_real() { return Time(this).to_double(); } - String *val_str(String *to) { return Time(this).to_string(to, decimals); } - my_decimal *val_decimal(my_decimal *to) { return Time(this).to_decimal(to); } - bool val_native(THD *thd, Native *to) - { - return Time(thd, this).to_native(to, decimals); - } -}; - - -class Item_datetimefunc :public Item_func -{ -public: - Item_datetimefunc(THD *thd): Item_func(thd) {} - Item_datetimefunc(THD *thd, Item *a): Item_func(thd, a) {} - Item_datetimefunc(THD *thd, Item *a, Item *b): Item_func(thd, a, b) {} - Item_datetimefunc(THD *thd, Item *a, Item *b, Item *c): - Item_func(thd, a, b ,c) {} - const Type_handler *type_handler() const { return &type_handler_datetime2; } - longlong val_int() { return Datetime(this).to_longlong(); } - double val_real() { return Datetime(this).to_double(); } - String *val_str(String *to) { return Datetime(this).to_string(to, decimals); } - my_decimal *val_decimal(my_decimal *to) { return Datetime(this).to_decimal(to); } -}; - - -/* Abstract CURTIME function. Children should define what time zone is used */ - -class Item_func_curtime :public Item_timefunc -{ - MYSQL_TIME ltime; - query_id_t last_query_id; -public: - Item_func_curtime(THD *thd, uint dec): Item_timefunc(thd), last_query_id(0) - { decimals= dec; } - bool fix_fields(THD *, Item **); - bool fix_length_and_dec() { fix_attributes_time(decimals); return FALSE; } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - /* - Abstract method that defines which time zone is used for conversion. - Converts time current time in my_time_t representation to broken-down - MYSQL_TIME representation using UTC-SYSTEM or per-thread time zone. - */ - virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time)=0; - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); - } - void print(String *str, enum_query_type query_type); -}; - - -class Item_func_curtime_local :public Item_func_curtime -{ -public: - Item_func_curtime_local(THD *thd, uint dec): Item_func_curtime(thd, dec) {} - const char *func_name() const { return "curtime"; } - virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_curtime_utc :public Item_func_curtime -{ -public: - Item_func_curtime_utc(THD *thd, uint dec): Item_func_curtime(thd, dec) {} - const char *func_name() const { return "utc_time"; } - virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* Abstract CURDATE function. See also Item_func_curtime. */ - -class Item_func_curdate :public Item_datefunc -{ - query_id_t last_query_id; - MYSQL_TIME ltime; -public: - Item_func_curdate(THD *thd): Item_datefunc(thd), last_query_id(0) {} - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time)=0; - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); - } -}; - - -class Item_func_curdate_local :public Item_func_curdate -{ -public: - Item_func_curdate_local(THD *thd): Item_func_curdate(thd) {} - const char *func_name() const { return "curdate"; } - void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_curdate_utc :public Item_func_curdate -{ -public: - Item_func_curdate_utc(THD *thd): Item_func_curdate(thd) {} - const char *func_name() const { return "utc_date"; } - void store_now_in_TIME(THD* thd, MYSQL_TIME *now_time); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* Abstract CURRENT_TIMESTAMP function. See also Item_func_curtime */ - -class Item_func_now :public Item_datetimefunc -{ - MYSQL_TIME ltime; - query_id_t last_query_id; -public: - Item_func_now(THD *thd, uint dec): Item_datetimefunc(thd), last_query_id(0) - { decimals= dec; } - bool fix_fields(THD *, Item **); - bool fix_length_and_dec() - { fix_attributes_datetime(decimals); return FALSE;} - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time)=0; - bool check_vcol_func_processor(void *arg) - { - /* - NOW is safe for replication as slaves will run with same time as - master - */ - return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); - } - void print(String *str, enum_query_type query_type); -}; - - -class Item_func_now_local :public Item_func_now -{ -public: - Item_func_now_local(THD *thd, uint dec): Item_func_now(thd, dec) {} - const char *func_name() const { return "current_timestamp"; } - int save_in_field(Field *field, bool no_conversions); - virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time); - virtual enum Functype functype() const { return NOW_FUNC; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_now_utc :public Item_func_now -{ -public: - Item_func_now_utc(THD *thd, uint dec): Item_func_now(thd, dec) {} - const char *func_name() const { return "utc_timestamp"; } - virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time); - virtual enum Functype functype() const { return NOW_UTC_FUNC; } - virtual bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, - VCOL_TIME_FUNC | VCOL_NON_DETERMINISTIC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - This is like NOW(), but always uses the real current time, not the - query_start(). This matches the Oracle behavior. -*/ -class Item_func_sysdate_local :public Item_func_now -{ -public: - Item_func_sysdate_local(THD *thd, uint dec): Item_func_now(thd, dec) {} - bool const_item() const { return 0; } - const char *func_name() const { return "sysdate"; } - void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time); - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - table_map used_tables() const { return RAND_TABLE_BIT; } - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, - VCOL_TIME_FUNC | VCOL_NON_DETERMINISTIC); - } - virtual enum Functype functype() const { return SYSDATE_FUNC; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_from_days :public Item_datefunc -{ - bool check_arguments() const - { return args[0]->check_type_can_return_int(func_name()); } -public: - Item_func_from_days(THD *thd, Item *a): Item_datefunc(thd, a) {} - const char *func_name() const { return "from_days"; } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return has_date_args() || has_time_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_date_format :public Item_str_func -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_date(func_name()) || - check_argument_types_can_return_text(1, arg_count); - } - const MY_LOCALE *locale; - int fixed_length; - String value; -protected: - bool is_time_format; -public: - Item_func_date_format(THD *thd, Item *a, Item *b): - Item_str_func(thd, a, b), locale(0), is_time_format(false) {} - Item_func_date_format(THD *thd, Item *a, Item *b, Item *c): - Item_str_func(thd, a, b, c), locale(0), is_time_format(false) {} - String *val_str(String *str); - const char *func_name() const { return "date_format"; } - bool fix_length_and_dec(); - uint format_length(const String *format); - bool eq(const Item *item, bool binary_cmp) const; - bool check_vcol_func_processor(void *arg) - { - if (arg_count > 2) - return false; - return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_time_format: public Item_func_date_format -{ -public: - Item_func_time_format(THD *thd, Item *a, Item *b): - Item_func_date_format(thd, a, b) { is_time_format= true; } - const char *func_name() const { return "time_format"; } - bool check_vcol_func_processor(void *arg) { return false; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_from_unixtime :public Item_datetimefunc -{ - bool check_arguments() const - { return args[0]->check_type_can_return_decimal(func_name()); } - Time_zone *tz; - public: - Item_func_from_unixtime(THD *thd, Item *a): Item_datetimefunc(thd, a) {} - const char *func_name() const { return "from_unixtime"; } - bool fix_length_and_dec(); - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - bool check_vcol_func_processor(void *arg) - { - return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - We need Time_zone class declaration for storing pointers in - Item_func_convert_tz. -*/ -class Time_zone; - -/* - This class represents CONVERT_TZ() function. - The important fact about this function that it is handled in special way. - When such function is met in expression time_zone system tables are added - to global list of tables to open, so later those already opened and locked - tables can be used during this function calculation for loading time zone - descriptions. -*/ -class Item_func_convert_tz :public Item_datetimefunc -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_date(func_name()) || - check_argument_types_can_return_text(1, arg_count); - } - /* - If time zone parameters are constants we are caching objects that - represent them (we use separate from_tz_cached/to_tz_cached members - to indicate this fact, since NULL is legal value for from_tz/to_tz - members. - */ - bool from_tz_cached, to_tz_cached; - Time_zone *from_tz, *to_tz; - public: - Item_func_convert_tz(THD *thd, Item *a, Item *b, Item *c): - Item_datetimefunc(thd, a, b, c), from_tz_cached(0), to_tz_cached(0) {} - const char *func_name() const { return "convert_tz"; } - bool fix_length_and_dec() - { - fix_attributes_datetime(args[0]->datetime_precision(current_thd)); - maybe_null= true; - return FALSE; - } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - void cleanup(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_sec_to_time :public Item_timefunc -{ - bool check_arguments() const - { return args[0]->check_type_can_return_decimal(func_name()); } -public: - Item_func_sec_to_time(THD *thd, Item *item): Item_timefunc(thd, item) {} - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - bool fix_length_and_dec() - { - fix_attributes_time(args[0]->decimals); - maybe_null= true; - return FALSE; - } - const char *func_name() const { return "sec_to_time"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_date_add_interval :public Item_handled_func -{ -public: - const interval_type int_type; // keep it public - const bool date_sub_interval; // keep it public - Item_date_add_interval(THD *thd, Item *a, Item *b, interval_type type_arg, - bool neg_arg): - Item_handled_func(thd, a, b), int_type(type_arg), - date_sub_interval(neg_arg) {} - const char *func_name() const { return "date_add_interval"; } - bool fix_length_and_dec(); - bool eq(const Item *item, bool binary_cmp) const; - void print(String *str, enum_query_type query_type); - enum precedence precedence() const { return INTERVAL_PRECEDENCE; } - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_extract :public Item_int_func, - public Type_handler_hybrid_field_type -{ - date_mode_t m_date_mode; - const Type_handler_int_result *handler_by_length(uint32 length, - uint32 threashold) - { - if (length >= threashold) - return &type_handler_slonglong; - return &type_handler_slong; - } - void set_date_length(uint32 length) - { - /* - Although DATE components (e.g. YEAR, YEAR_MONTH, QUARTER, MONTH, WEEK) - cannot have a sign, we should probably still add +1, - because all around the code we assume that max_length is sign inclusive. - Another options is to set unsigned_flag to "true". - */ - set_handler(handler_by_length(max_length= length, 10)); // QQ: see above - m_date_mode= date_mode_t(0); - } - void set_day_length(uint32 length) - { - /* - Units starting with DAY can be negative: - EXTRACT(DAY FROM '-24:00:00') -> -1 - */ - set_handler(handler_by_length(max_length= length + 1/*sign*/, 11)); - m_date_mode= Temporal::Options(TIME_INTERVAL_DAY, current_thd); - } - void set_time_length(uint32 length) - { - set_handler(handler_by_length(max_length= length + 1/*sign*/, 11)); - m_date_mode= Temporal::Options(TIME_INTERVAL_hhmmssff, current_thd); - } - public: - const interval_type int_type; // keep it public - Item_extract(THD *thd, interval_type type_arg, Item *a): - Item_int_func(thd, a), - Type_handler_hybrid_field_type(&type_handler_slonglong), - m_date_mode(date_mode_t(0)), - int_type(type_arg) - { } - const Type_handler *type_handler() const - { - return Type_handler_hybrid_field_type::type_handler(); - } - longlong val_int(); - enum Functype functype() const { return EXTRACT_FUNC; } - const char *func_name() const { return "extract"; } - bool check_arguments() const; - bool fix_length_and_dec(); - bool eq(const Item *item, bool binary_cmp) const; - void print(String *str, enum_query_type query_type); - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) - { - if (int_type != INTERVAL_WEEK) - return FALSE; - return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); - } - bool check_valid_arguments_processor(void *int_arg) - { - switch (int_type) { - case INTERVAL_YEAR: - case INTERVAL_YEAR_MONTH: - case INTERVAL_QUARTER: - case INTERVAL_MONTH: - /* case INTERVAL_WEEK: Not allowed as partitioning function, bug#57071 */ - case INTERVAL_DAY: - return !has_date_args(); - case INTERVAL_DAY_HOUR: - case INTERVAL_DAY_MINUTE: - case INTERVAL_DAY_SECOND: - case INTERVAL_DAY_MICROSECOND: - return !has_datetime_args(); - case INTERVAL_HOUR: - case INTERVAL_HOUR_MINUTE: - case INTERVAL_HOUR_SECOND: - case INTERVAL_MINUTE: - case INTERVAL_MINUTE_SECOND: - case INTERVAL_SECOND: - case INTERVAL_MICROSECOND: - case INTERVAL_HOUR_MICROSECOND: - case INTERVAL_MINUTE_MICROSECOND: - case INTERVAL_SECOND_MICROSECOND: - return !has_time_args(); - default: - /* - INTERVAL_LAST is only an end marker, - INTERVAL_WEEK depends on default_week_format which is a session - variable and cannot be used for partitioning. See bug#57071. - */ - break; - } - return true; - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_char_typecast :public Item_handled_func -{ - uint cast_length; - CHARSET_INFO *cast_cs, *from_cs; - bool charset_conversion; - String tmp_value; - bool m_suppress_warning_to_error_escalation; -public: - bool has_explicit_length() const { return cast_length != ~0U; } -private: - String *reuse(String *src, size_t length); - String *copy(String *src, CHARSET_INFO *cs); - uint adjusted_length_with_warn(uint length); - void check_truncation_with_warn(String *src, size_t dstlen); - void fix_length_and_dec_internal(CHARSET_INFO *fromcs); -public: - // Methods used by ColumnStore - uint get_cast_length() const { return cast_length; } -public: - Item_char_typecast(THD *thd, Item *a, uint length_arg, CHARSET_INFO *cs_arg): - Item_handled_func(thd, a), cast_length(length_arg), cast_cs(cs_arg), - m_suppress_warning_to_error_escalation(false) {} - enum Functype functype() const { return CHAR_TYPECAST_FUNC; } - bool eq(const Item *item, bool binary_cmp) const; - const char *func_name() const { return "cast_as_char"; } - CHARSET_INFO *cast_charset() const { return cast_cs; } - String *val_str_generic(String *a); - String *val_str_binary_from_native(String *a); - void fix_length_and_dec_generic(); - void fix_length_and_dec_numeric(); - void fix_length_and_dec_str(); - void fix_length_and_dec_native_to_binary(uint32 octet_length); - bool fix_length_and_dec() - { - return args[0]->type_handler()->Item_char_typecast_fix_length_and_dec(this); - } - void print(String *str, enum_query_type query_type); - bool need_parentheses_in_default() { return true; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_interval_DDhhmmssff_typecast :public Item_char_typecast -{ - uint m_fsp; -public: - Item_interval_DDhhmmssff_typecast(THD *thd, Item *a, uint fsp) - :Item_char_typecast(thd, a,Interval_DDhhmmssff::max_char_length(fsp), - &my_charset_latin1), - m_fsp(fsp) - { } - String *val_str(String *to) - { - Interval_DDhhmmssff it(current_thd, args[0], m_fsp); - null_value= !it.is_valid_interval_DDhhmmssff(); - return it.to_string(to, m_fsp); - } -}; - - -class Item_date_typecast :public Item_datefunc -{ -public: - Item_date_typecast(THD *thd, Item *a): Item_datefunc(thd, a) {} - const char *func_name() const { return "cast_as_date"; } - void print(String *str, enum_query_type query_type) - { - print_cast_temporal(str, query_type); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool fix_length_and_dec() - { - return args[0]->type_handler()->Item_date_typecast_fix_length_and_dec(this); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_time_typecast :public Item_timefunc -{ -public: - Item_time_typecast(THD *thd, Item *a, uint dec_arg): - Item_timefunc(thd, a) { decimals= dec_arg; } - const char *func_name() const { return "cast_as_time"; } - void print(String *str, enum_query_type query_type) - { - print_cast_temporal(str, query_type); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool fix_length_and_dec() - { - return args[0]->type_handler()-> - Item_time_typecast_fix_length_and_dec(this); - } - Sql_mode_dependency value_depends_on_sql_mode() const; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_datetime_typecast :public Item_datetimefunc -{ -public: - Item_datetime_typecast(THD *thd, Item *a, uint dec_arg): - Item_datetimefunc(thd, a) { decimals= dec_arg; } - const char *func_name() const { return "cast_as_datetime"; } - void print(String *str, enum_query_type query_type) - { - print_cast_temporal(str, query_type); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - bool fix_length_and_dec() - { - return args[0]->type_handler()-> - Item_datetime_typecast_fix_length_and_dec(this); - } - Sql_mode_dependency value_depends_on_sql_mode() const; - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_makedate :public Item_datefunc -{ - bool check_arguments() const - { return check_argument_types_can_return_int(0, arg_count); } -public: - Item_func_makedate(THD *thd, Item *a, Item *b): - Item_datefunc(thd, a, b) {} - const char *func_name() const { return "makedate"; } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_timestamp :public Item_datetimefunc -{ - bool check_arguments() const - { - return args[0]->check_type_can_return_date(func_name()) || - args[1]->check_type_can_return_time(func_name()); - } -public: - Item_func_timestamp(THD *thd, Item *a, Item *b) - :Item_datetimefunc(thd, a, b) - { } - const char *func_name() const { return "timestamp"; } - bool fix_length_and_dec() - { - THD *thd= current_thd; - uint dec0= args[0]->datetime_precision(thd); - uint dec1= Interval_DDhhmmssff::fsp(thd, args[1]); - fix_attributes_datetime(MY_MAX(dec0, dec1)); - maybe_null= true; - return false; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - Datetime dt(thd, args[0], Datetime::Options(TIME_CONV_NONE, thd)); - if (!dt.is_valid_datetime()) - return null_value= true; - Interval_DDhhmmssff it(thd, args[1]); - if (!it.is_valid_interval_DDhhmmssff()) - return null_value= true; - return (null_value= Sec6_add(dt.get_mysql_time(), it.get_mysql_time(), 1). - to_datetime(ltime)); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/** - ADDTIME(t,a) and SUBTIME(t,a) are time functions that calculate a - time/datetime value - - t: time_or_datetime_expression - a: time_expression - - Result: Time value or datetime value -*/ - -class Item_func_add_time :public Item_handled_func -{ - int sign; -public: - // Methods used by ColumnStore - int get_sign() const { return sign; } -public: - Item_func_add_time(THD *thd, Item *a, Item *b, bool neg_arg) - :Item_handled_func(thd, a, b), sign(neg_arg ? -1 : 1) - { } - bool fix_length_and_dec(); - const char *func_name() const { return sign > 0 ? "addtime" : "subtime"; } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_timediff :public Item_timefunc -{ - bool check_arguments() const - { return check_argument_types_can_return_time(0, arg_count); } -public: - Item_func_timediff(THD *thd, Item *a, Item *b): Item_timefunc(thd, a, b) {} - const char *func_name() const { return "timediff"; } - bool fix_length_and_dec() - { - THD *thd= current_thd; - uint dec= MY_MAX(args[0]->time_precision(thd), - args[1]->time_precision(thd)); - fix_attributes_time(dec); - maybe_null= true; - return FALSE; - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_maketime :public Item_timefunc -{ - bool check_arguments() const - { - return check_argument_types_can_return_int(0, 2) || - args[2]->check_type_can_return_decimal(func_name()); - } -public: - Item_func_maketime(THD *thd, Item *a, Item *b, Item *c): - Item_timefunc(thd, a, b, c) - {} - bool fix_length_and_dec() - { - fix_attributes_time(args[2]->decimals); - maybe_null= true; - return FALSE; - } - const char *func_name() const { return "maketime"; } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_microsecond :public Item_long_func_time_field -{ -public: - Item_func_microsecond(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} - longlong val_int(); - const char *func_name() const { return "microsecond"; } - bool fix_length_and_dec() - { - decimals=0; - maybe_null=1; - fix_char_length(6); - return FALSE; - } - bool check_partition_func_processor(void *int_arg) {return FALSE;} - bool check_vcol_func_processor(void *arg) { return FALSE;} - bool check_valid_arguments_processor(void *int_arg) - { - return !has_time_args(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_timestamp_diff :public Item_longlong_func -{ - bool check_arguments() const - { return check_argument_types_can_return_date(0, arg_count); } - const interval_type int_type; -public: - // Methods used by ColumnStore - interval_type get_int_type() const { return int_type; }; -public: - Item_func_timestamp_diff(THD *thd, Item *a, Item *b, interval_type type_arg): - Item_longlong_func(thd, a, b), int_type(type_arg) {} - const char *func_name() const { return "timestampdiff"; } - longlong val_int(); - bool fix_length_and_dec() - { - decimals=0; - maybe_null=1; - return FALSE; - } - virtual void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -enum date_time_format -{ - USA_FORMAT, JIS_FORMAT, ISO_FORMAT, EUR_FORMAT, INTERNAL_FORMAT -}; - -class Item_func_get_format :public Item_str_ascii_func -{ -public: - const timestamp_type type; // keep it public - Item_func_get_format(THD *thd, timestamp_type type_arg, Item *a): - Item_str_ascii_func(thd, a), type(type_arg) - {} - String *val_str_ascii(String *str); - const char *func_name() const { return "get_format"; } - bool fix_length_and_dec() - { - maybe_null= 1; - decimals=0; - fix_length_and_charset(17, default_charset()); - return FALSE; - } - virtual void print(String *str, enum_query_type query_type); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_str_to_date :public Item_handled_func -{ - bool const_item; - String subject_converter; - String format_converter; - CHARSET_INFO *internal_charset; -public: - Item_func_str_to_date(THD *thd, Item *a, Item *b): - Item_handled_func(thd, a, b), const_item(false), - internal_charset(NULL) - {} - bool get_date_common(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate, - timestamp_type); - const char *func_name() const { return "str_to_date"; } - bool fix_length_and_dec(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_last_day :public Item_datefunc -{ - bool check_arguments() const - { return args[0]->check_type_can_return_date(func_name()); } -public: - Item_func_last_day(THD *thd, Item *a): Item_datefunc(thd, a) {} - const char *func_name() const { return "last_day"; } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/*****************************************************************************/ - -class Func_handler_date_add_interval -{ -protected: - static uint interval_dec(const Item *item, interval_type int_type) - { - if (int_type == INTERVAL_MICROSECOND || - (int_type >= INTERVAL_DAY_MICROSECOND && - int_type <= INTERVAL_SECOND_MICROSECOND)) - return TIME_SECOND_PART_DIGITS; - if (int_type == INTERVAL_SECOND && item->decimals > 0) - return MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); - return 0; - } - interval_type int_type(const Item_handled_func *item) const - { - return static_cast(item)->int_type; - } - bool sub(const Item_handled_func *item) const - { - return static_cast(item)->date_sub_interval; - } - bool add(THD *thd, Item *item, interval_type type, bool sub, MYSQL_TIME *to) const - { - INTERVAL interval; - if (get_interval_value(thd, item, type, &interval)) - return true; - if (sub) - interval.neg = !interval.neg; - return date_add_interval(thd, to, type, interval); - } -}; - - -class Func_handler_date_add_interval_datetime: - public Item_handled_func::Handler_datetime, - public Func_handler_date_add_interval -{ -public: - bool fix_length_and_dec(Item_handled_func *item) const - { - uint dec= MY_MAX(item->arguments()[0]->datetime_precision(current_thd), - interval_dec(item->arguments()[1], int_type(item))); - item->fix_attributes_datetime(dec); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - Datetime::Options opt(TIME_CONV_NONE, thd); - Datetime dt(thd, item->arguments()[0], opt); - if (!dt.is_valid_datetime() || - dt.check_date_with_warn(thd, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE)) - return (item->null_value= true); - dt.copy_to_mysql_time(to); - return (item->null_value= add(thd, item->arguments()[1], - int_type(item), sub(item), to)); - } -}; - - -class Func_handler_date_add_interval_datetime_arg0_time: - public Func_handler_date_add_interval_datetime -{ -public: - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const; -}; - - -class Func_handler_date_add_interval_date: - public Item_handled_func::Handler_date, - public Func_handler_date_add_interval -{ -public: - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - /* - The first argument is known to be of the DATE data type (not DATETIME). - We don't need rounding here. - */ - Date d(thd, item->arguments()[0], TIME_CONV_NONE); - if (!d.is_valid_date() || - d.check_date_with_warn(thd, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE)) - return (item->null_value= true); - d.copy_to_mysql_time(to); - return (item->null_value= add(thd, item->arguments()[1], - int_type(item), sub(item), to)); - } -}; - - -class Func_handler_date_add_interval_time: - public Item_handled_func::Handler_time, - public Func_handler_date_add_interval -{ -public: - bool fix_length_and_dec(Item_handled_func *item) const - { - uint dec= MY_MAX(item->arguments()[0]->time_precision(current_thd), - interval_dec(item->arguments()[1], int_type(item))); - item->fix_attributes_time(dec); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - Time t(thd, item->arguments()[0]); - if (!t.is_valid_time()) - return (item->null_value= true); - t.copy_to_mysql_time(to); - return (item->null_value= add(thd, item->arguments()[1], - int_type(item), sub(item), to)); - } -}; - - -class Func_handler_date_add_interval_string: - public Item_handled_func::Handler_temporal_string, - public Func_handler_date_add_interval -{ -public: - bool fix_length_and_dec(Item_handled_func *item) const - { - uint dec= MY_MAX(item->arguments()[0]->datetime_precision(current_thd), - interval_dec(item->arguments()[1], int_type(item))); - item->Type_std_attributes::set( - Type_temporal_attributes_not_fixed_dec(MAX_DATETIME_WIDTH, dec, false), - DTCollation(item->default_charset(), - DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII)); - item->fix_char_length(item->max_length); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - if (item->arguments()[0]-> - get_date(thd, to, Datetime::Options(TIME_CONV_NONE, thd)) || - (to->time_type != MYSQL_TIMESTAMP_TIME && - check_date_with_warn(thd, to, TIME_NO_ZEROS, MYSQL_TIMESTAMP_ERROR))) - return (item->null_value= true); - return (item->null_value= add(thd, item->arguments()[1], - int_type(item), sub(item), to)); - } -}; - - -class Func_handler_sign -{ -protected: - int m_sign; - Func_handler_sign(int sign) :m_sign(sign) { } -}; - - -class Func_handler_add_time_datetime: - public Item_handled_func::Handler_datetime, - public Func_handler_sign -{ -public: - Func_handler_add_time_datetime(int sign) - :Func_handler_sign(sign) - { } - bool fix_length_and_dec(Item_handled_func *item) const - { - THD *thd= current_thd; - uint dec0= item->arguments()[0]->datetime_precision(thd); - uint dec1= Interval_DDhhmmssff::fsp(thd, item->arguments()[1]); - item->fix_attributes_datetime(MY_MAX(dec0, dec1)); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - DBUG_ASSERT(item->is_fixed()); - Datetime::Options opt(TIME_CONV_NONE, thd); - Datetime dt(thd, item->arguments()[0], opt); - if (!dt.is_valid_datetime()) - return item->null_value= true; - Interval_DDhhmmssff it(thd, item->arguments()[1]); - if (!it.is_valid_interval_DDhhmmssff()) - return item->null_value= true; - return (item->null_value= (Sec6_add(dt.get_mysql_time(), - it.get_mysql_time(), m_sign). - to_datetime(to))); - } -}; - - -class Func_handler_add_time_time: - public Item_handled_func::Handler_time, - public Func_handler_sign -{ -public: - Func_handler_add_time_time(int sign) - :Func_handler_sign(sign) - { } - bool fix_length_and_dec(Item_handled_func *item) const - { - THD *thd= current_thd; - uint dec0= item->arguments()[0]->time_precision(thd); - uint dec1= Interval_DDhhmmssff::fsp(thd, item->arguments()[1]); - item->fix_attributes_time(MY_MAX(dec0, dec1)); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - DBUG_ASSERT(item->is_fixed()); - Time t(thd, item->arguments()[0]); - if (!t.is_valid_time()) - return item->null_value= true; - Interval_DDhhmmssff i(thd, item->arguments()[1]); - if (!i.is_valid_interval_DDhhmmssff()) - return item->null_value= true; - return (item->null_value= (Sec6_add(t.get_mysql_time(), - i.get_mysql_time(), m_sign). - to_time(thd, to, item->decimals))); - } -}; - - -class Func_handler_add_time_string: - public Item_handled_func::Handler_temporal_string, - public Func_handler_sign -{ -public: - Func_handler_add_time_string(int sign) - :Func_handler_sign(sign) - { } - bool fix_length_and_dec(Item_handled_func *item) const - { - uint dec0= item->arguments()[0]->decimals; - uint dec1= Interval_DDhhmmssff::fsp(current_thd, item->arguments()[1]); - uint dec= MY_MAX(dec0, dec1); - item->Type_std_attributes::set( - Type_temporal_attributes_not_fixed_dec(MAX_DATETIME_WIDTH, dec, false), - DTCollation(item->default_charset(), - DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII)); - item->fix_char_length(item->max_length); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - DBUG_ASSERT(item->is_fixed()); - // Detect a proper timestamp type based on the argument values - Temporal_hybrid l_time1(thd, item->arguments()[0], - Temporal::Options(TIME_TIME_ONLY, thd)); - if (!l_time1.is_valid_temporal()) - return (item->null_value= true); - Interval_DDhhmmssff l_time2(thd, item->arguments()[1]); - if (!l_time2.is_valid_interval_DDhhmmssff()) - return (item->null_value= true); - Sec6_add add(l_time1.get_mysql_time(), l_time2.get_mysql_time(), m_sign); - return (item->null_value= (l_time1.get_mysql_time()->time_type == - MYSQL_TIMESTAMP_TIME ? - add.to_time(thd, to, item->decimals) : - add.to_datetime(to))); - } -}; - - -class Func_handler_str_to_date_datetime_sec: - public Item_handled_func::Handler_datetime -{ -public: - bool fix_length_and_dec(Item_handled_func *item) const - { - item->fix_attributes_datetime(0); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - return static_cast(item)-> - get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_DATETIME); - } -}; - - -class Func_handler_str_to_date_datetime_usec: - public Item_handled_func::Handler_datetime -{ -public: - bool fix_length_and_dec(Item_handled_func *item) const - { - item->fix_attributes_datetime(TIME_SECOND_PART_DIGITS); - return false; - } - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - return static_cast(item)-> - get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_DATETIME); - } -}; - - -class Func_handler_str_to_date_date: public Item_handled_func::Handler_date -{ -public: - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - return static_cast(item)-> - get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_DATE); - } -}; - - -class Func_handler_str_to_date_time: public Item_handled_func::Handler_time -{ -public: - bool get_date(THD *thd, Item_handled_func *item, - MYSQL_TIME *to, date_mode_t fuzzy) const - { - if (static_cast(item)-> - get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_TIME)) - return true; - if (to->day) - { - /* - Day part for time type can be nonzero value and so - we should add hours from day part to hour part to - keep valid time value. - */ - to->hour+= to->day * 24; - to->day= 0; - } - return false; - } -}; - - -class Func_handler_str_to_date_time_sec: public Func_handler_str_to_date_time -{ -public: - bool fix_length_and_dec(Item_handled_func *item) const - { - item->fix_attributes_time(0); - return false; - } -}; - - -class Func_handler_str_to_date_time_usec: public Func_handler_str_to_date_time -{ -public: - bool fix_length_and_dec(Item_handled_func *item) const - { - item->fix_attributes_time(TIME_SECOND_PART_DIGITS); - return false; - } -}; - - -#endif /* ITEM_TIMEFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_vers.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_vers.h deleted file mode 100644 index a42b5a0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_vers.h +++ /dev/null @@ -1,116 +0,0 @@ -#ifndef ITEM_VERS_INCLUDED -#define ITEM_VERS_INCLUDED -/* Copyright (c) 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ - - -/* System Versioning items */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -class Item_func_trt_ts: public Item_datetimefunc -{ - TR_table::field_id_t trt_field; -public: - Item_func_trt_ts(THD *thd, Item* a, TR_table::field_id_t _trt_field); - const char *func_name() const - { - if (trt_field == TR_table::FLD_BEGIN_TS) - { - return "trt_begin_ts"; - } - return "trt_commit_ts"; - } - bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - bool fix_length_and_dec() - { fix_attributes_datetime(decimals); return FALSE; } -}; - -class Item_func_trt_id : public Item_longlong_func -{ - TR_table::field_id_t trt_field; - bool backwards; - - longlong get_by_trx_id(ulonglong trx_id); - longlong get_by_commit_ts(MYSQL_TIME &commit_ts, bool backwards); - -public: - Item_func_trt_id(THD *thd, Item* a, TR_table::field_id_t _trt_field, bool _backwards= false); - Item_func_trt_id(THD *thd, Item* a, Item* b, TR_table::field_id_t _trt_field); - - const char *func_name() const - { - switch (trt_field) - { - case TR_table::FLD_TRX_ID: - return "trt_trx_id"; - case TR_table::FLD_COMMIT_ID: - return "trt_commit_id"; - case TR_table::FLD_ISO_LEVEL: - return "trt_iso_level"; - default: - DBUG_ASSERT(0); - } - return NULL; - } - - bool fix_length_and_dec() - { - bool res= Item_int_func::fix_length_and_dec(); - max_length= 20; - return res; - } - - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_trt_trx_sees : public Item_bool_func -{ -protected: - bool accept_eq; - -public: - Item_func_trt_trx_sees(THD *thd, Item* a, Item* b); - const char *func_name() const - { - return "trt_trx_sees"; - } - longlong val_int(); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_func_trt_trx_sees_eq : - public Item_func_trt_trx_sees -{ -public: - Item_func_trt_trx_sees_eq(THD *thd, Item* a, Item* b) : - Item_func_trt_trx_sees(thd, a, b) - { - accept_eq= true; - } - const char *func_name() const - { - return "trt_trx_sees_eq"; - } -}; - -#endif /* ITEM_VERS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_windowfunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_windowfunc.h deleted file mode 100644 index 99ef738..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_windowfunc.h +++ /dev/null @@ -1,1372 +0,0 @@ -/* - Copyright (c) 2016, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef ITEM_WINDOWFUNC_INCLUDED -#define ITEM_WINDOWFUNC_INCLUDED - -#include "item.h" - -class Window_spec; - - -int test_if_group_changed(List &list); - - -/* A wrapper around test_if_group_changed */ -class Group_bound_tracker -{ -public: - - Group_bound_tracker(THD *thd, SQL_I_List *list) - { - for (ORDER *curr = list->first; curr; curr=curr->next) - { - Cached_item *tmp= new_Cached_item(thd, curr->item[0], TRUE); - group_fields.push_back(tmp); - } - } - - void init() - { - first_check= true; - } - - /* - Check if the current row is in a different group than the previous row - this function was called for. - XXX: Side-effect: The new row's group becomes the current row's group. - - Returns true if there is a change between the current_group and the cached - value, or if it is the first check after a call to init. - */ - bool check_if_next_group() - { - if (test_if_group_changed(group_fields) > -1 || first_check) - { - first_check= false; - return true; - } - return false; - } - - /* - Check if the current row is in a different group than the previous row - check_if_next_group was called for. - - Compares the groups without the additional side effect of updating the - current cached values. - */ - int compare_with_cache() - { - List_iterator li(group_fields); - Cached_item *ptr; - int res; - while ((ptr= li++)) - { - if ((res= ptr->cmp_read_only())) - return res; - } - return 0; - } - ~Group_bound_tracker() - { - group_fields.delete_elements(); - } - -private: - List group_fields; - /* - During the first check_if_next_group, the list of cached_items is not - initialized. The compare function will return that the items match if - the field's value is the same as the Cached_item's default value (0). - This flag makes sure that we always return true during the first check. - - XXX This is better to be implemented within test_if_group_changed, but - since it is used in other parts of the codebase, we keep it here for now. - */ - bool first_check; -}; - -/* - ROW_NUMBER() OVER (...) - - @detail - - This is a Window function (not just an aggregate) - - It can be computed by doing one pass over select output, provided - the output is sorted according to the window definition. -*/ - -class Item_sum_row_number: public Item_sum_int -{ - longlong count; - -public: - - Item_sum_row_number(THD *thd) - : Item_sum_int(thd), count(0) {} - - const Type_handler *type_handler() const { return &type_handler_slonglong; } - - void clear() - { - count= 0; - } - - bool add() - { - count++; - return false; - } - - void reset_field() { DBUG_ASSERT(0); } - void update_field() {} - - enum Sumfunctype sum_func() const - { - return ROW_NUMBER_FUNC; - } - - longlong val_int() - { - return count; - } - const char*func_name() const - { - return "row_number"; - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - RANK() OVER (...) Windowing function - - @detail - - This is a Window function (not just an aggregate) - - It can be computed by doing one pass over select output, provided - the output is sorted according to the window definition. - - The function is defined as: - - "The rank of row R is defined as 1 (one) plus the number of rows that - precede R and are not peers of R" - - "This implies that if two or more rows are not distinct with respect to - the window ordering, then there will be one or more" -*/ - -class Item_sum_rank: public Item_sum_int -{ -protected: - longlong row_number; // just ROW_NUMBER() - longlong cur_rank; // current value - - Group_bound_tracker *peer_tracker; -public: - - Item_sum_rank(THD *thd) : Item_sum_int(thd), peer_tracker(NULL) {} - - const Type_handler *type_handler() const { return &type_handler_slonglong; } - - void clear() - { - /* This is called on partition start */ - cur_rank= 1; - row_number= 0; - } - - bool add(); - - longlong val_int() - { - return cur_rank; - } - - void reset_field() { DBUG_ASSERT(0); } - void update_field() {} - - enum Sumfunctype sum_func () const - { - return RANK_FUNC; - } - - const char*func_name() const - { - return "rank"; - } - - void setup_window_func(THD *thd, Window_spec *window_spec); - - void cleanup() - { - if (peer_tracker) - { - delete peer_tracker; - peer_tracker= NULL; - } - Item_sum_int::cleanup(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -/* - DENSE_RANK() OVER (...) Windowing function - - @detail - - This is a Window function (not just an aggregate) - - It can be computed by doing one pass over select output, provided - the output is sorted according to the window definition. - - The function is defined as: - - "If DENSE_RANK is specified, then the rank of row R is defined as the - number of rows preceding and including R that are distinct with respect - to the window ordering" - - "This implies that there are no gaps in the sequential rank numbering of - rows in each window partition." -*/ - - -class Item_sum_dense_rank: public Item_sum_int -{ - longlong dense_rank; - bool first_add; - Group_bound_tracker *peer_tracker; - public: - /* - XXX(cvicentiu) This class could potentially be implemented in the rank - class, with a switch for the DENSE case. - */ - void clear() - { - dense_rank= 0; - first_add= true; - } - bool add(); - void reset_field() { DBUG_ASSERT(0); } - void update_field() {} - longlong val_int() - { - return dense_rank; - } - - Item_sum_dense_rank(THD *thd) - : Item_sum_int(thd), dense_rank(0), first_add(true), peer_tracker(NULL) {} - const Type_handler *type_handler() const { return &type_handler_slonglong; } - enum Sumfunctype sum_func () const - { - return DENSE_RANK_FUNC; - } - - const char*func_name() const - { - return "dense_rank"; - } - - void setup_window_func(THD *thd, Window_spec *window_spec); - - void cleanup() - { - if (peer_tracker) - { - delete peer_tracker; - peer_tracker= NULL; - } - Item_sum_int::cleanup(); - } - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_sum_hybrid_simple : public Item_sum_hybrid -{ - public: - Item_sum_hybrid_simple(THD *thd, Item *arg): - Item_sum_hybrid(thd, arg), - value(NULL) - { } - - Item_sum_hybrid_simple(THD *thd, Item *arg1, Item *arg2): - Item_sum_hybrid(thd, arg1, arg2), - value(NULL) - { } - - bool add(); - bool fix_fields(THD *, Item **); - bool fix_length_and_dec(); - void setup_hybrid(THD *thd, Item *item); - double val_real(); - longlong val_int(); - my_decimal *val_decimal(my_decimal *); - void reset_field(); - String *val_str(String *); - bool val_native(THD *thd, Native *to); - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); - const Type_handler *type_handler() const - { return Type_handler_hybrid_field_type::type_handler(); } - void update_field(); - Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table); - void clear() - { - value->clear(); - null_value= 1; - } - - private: - Item_cache *value; -}; - -/* - This item will remember the first value added to it. It will not update - the value unless it is cleared. -*/ -class Item_sum_first_value : public Item_sum_hybrid_simple -{ - public: - Item_sum_first_value(THD* thd, Item* arg_expr) : - Item_sum_hybrid_simple(thd, arg_expr) {} - - - enum Sumfunctype sum_func () const - { - return FIRST_VALUE_FUNC; - } - - const char*func_name() const - { - return "first_value"; - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -/* - This item will remember the last value added to it. - - This item does not support removal, and can be cleared only by calling - clear(). -*/ -class Item_sum_last_value : public Item_sum_hybrid_simple -{ - public: - Item_sum_last_value(THD* thd, Item* arg_expr) : - Item_sum_hybrid_simple(thd, arg_expr) {} - - enum Sumfunctype sum_func() const - { - return LAST_VALUE_FUNC; - } - - const char*func_name() const - { - return "last_value"; - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_sum_nth_value : public Item_sum_hybrid_simple -{ - public: - Item_sum_nth_value(THD *thd, Item *arg_expr, Item* offset_expr) : - Item_sum_hybrid_simple(thd, arg_expr, offset_expr) {} - - enum Sumfunctype sum_func() const - { - return NTH_VALUE_FUNC; - } - - const char*func_name() const - { - return "nth_value"; - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_sum_lead : public Item_sum_hybrid_simple -{ - public: - Item_sum_lead(THD *thd, Item *arg_expr, Item* offset_expr) : - Item_sum_hybrid_simple(thd, arg_expr, offset_expr) {} - - enum Sumfunctype sum_func() const - { - return LEAD_FUNC; - } - - const char*func_name() const - { - return "lead"; - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -class Item_sum_lag : public Item_sum_hybrid_simple -{ - public: - Item_sum_lag(THD *thd, Item *arg_expr, Item* offset_expr) : - Item_sum_hybrid_simple(thd, arg_expr, offset_expr) {} - - enum Sumfunctype sum_func() const - { - return LAG_FUNC; - } - - const char*func_name() const - { - return "lag"; - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Partition_row_count -{ -public: - Partition_row_count() :partition_row_count_(0) { } - void set_partition_row_count(ulonglong count) - { - partition_row_count_ = count; - } - double calc_val_real(bool *null_value, - ulonglong current_row_count) - { - if ((*null_value= (partition_row_count_ == 0))) - return 0; - return static_cast(current_row_count) / partition_row_count_; - } -protected: - longlong get_row_count() { return partition_row_count_; } - ulonglong partition_row_count_; -}; - - -class Current_row_count -{ -public: - Current_row_count() :current_row_count_(0) { } -protected: - ulonglong get_row_number() { return current_row_count_ ; } - ulonglong current_row_count_; -}; - - -/* - @detail - "The relative rank of a row R is defined as (RK-1)/(NR-1), where RK is - defined to be the RANK of R and NR is defined to be the number of rows in - the window partition of R." - - Computation of this function requires two passes: - - First pass to find #rows in the partition - This is held within the row_count context. - - Second pass to compute rank of current row and the value of the function -*/ -class Item_sum_percent_rank: public Item_sum_double, - public Partition_row_count -{ - public: - Item_sum_percent_rank(THD *thd) - : Item_sum_double(thd), cur_rank(1), peer_tracker(NULL) {} - - longlong val_int() - { - /* - Percent rank is a real value so calling the integer value should never - happen. It makes no sense as it gets truncated to either 0 or 1. - */ - DBUG_ASSERT(0); - return 0; - } - - double val_real() - { - /* - We can not get the real value without knowing the number of rows - in the partition. Don't divide by 0. - */ - ulonglong partition_rows = get_row_count(); - null_value= partition_rows > 0 ? false : true; - - return partition_rows > 1 ? - static_cast(cur_rank - 1) / (partition_rows - 1) : 0; - } - - enum Sumfunctype sum_func () const - { - return PERCENT_RANK_FUNC; - } - - const char*func_name() const - { - return "percent_rank"; - } - - void update_field() {} - - void clear() - { - cur_rank= 1; - row_number= 0; - } - bool add(); - const Type_handler *type_handler() const { return &type_handler_double; } - - bool fix_length_and_dec() - { - decimals = 10; // TODO-cvicentiu find out how many decimals the standard - // requires. - return FALSE; - } - - void setup_window_func(THD *thd, Window_spec *window_spec); - - void reset_field() { DBUG_ASSERT(0); } - - void set_partition_row_count(ulonglong count) - { - Partition_row_count::set_partition_row_count(count); - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - - private: - longlong cur_rank; // Current rank of the current row. - longlong row_number; // Value if this were ROW_NUMBER() function. - - Group_bound_tracker *peer_tracker; - - void cleanup() - { - if (peer_tracker) - { - delete peer_tracker; - peer_tracker= NULL; - } - Item_sum_num::cleanup(); - } -}; - - - - -/* - @detail - "The relative rank of a row R is defined as NP/NR, where - - NP is defined to be the number of rows preceding or peer with R in the - window ordering of the window partition of R - - NR is defined to be the number of rows in the window partition of R. - - Just like with Item_sum_percent_rank, computation of this function requires - two passes. -*/ - -class Item_sum_cume_dist: public Item_sum_double, - public Partition_row_count, - public Current_row_count -{ - public: - Item_sum_cume_dist(THD *thd) :Item_sum_double(thd) { } - Item_sum_cume_dist(THD *thd, Item *arg) :Item_sum_double(thd, arg) { } - - double val_real() - { - return calc_val_real(&null_value, current_row_count_); - } - - bool add() - { - current_row_count_++; - return false; - } - - enum Sumfunctype sum_func() const - { - return CUME_DIST_FUNC; - } - - void clear() - { - current_row_count_= 0; - partition_row_count_= 0; - } - - const char*func_name() const - { - return "cume_dist"; - } - - void update_field() {} - const Type_handler *type_handler() const { return &type_handler_double; } - - bool fix_length_and_dec() - { - decimals = 10; // TODO-cvicentiu find out how many decimals the standard - // requires. - return FALSE; - } - - void reset_field() { DBUG_ASSERT(0); } - - void set_partition_row_count(ulonglong count) - { - Partition_row_count::set_partition_row_count(count); - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - -}; - -class Item_sum_ntile : public Item_sum_int, - public Partition_row_count, - public Current_row_count -{ - public: - Item_sum_ntile(THD* thd, Item* num_quantiles_expr) : - Item_sum_int(thd, num_quantiles_expr), n_old_val_(0) - { } - - longlong val_int() - { - if (get_row_count() == 0) - { - null_value= true; - return 0; - } - - longlong num_quantiles= get_num_quantiles(); - - if (num_quantiles <= 0 || - (static_cast(num_quantiles) != n_old_val_ && n_old_val_ > 0)) - { - my_error(ER_INVALID_NTILE_ARGUMENT, MYF(0)); - return true; - } - n_old_val_= static_cast(num_quantiles); - null_value= false; - ulonglong quantile_size = get_row_count() / num_quantiles; - ulonglong extra_rows = get_row_count() - quantile_size * num_quantiles; - - if (current_row_count_ <= extra_rows * (quantile_size + 1)) - return (current_row_count_ - 1) / (quantile_size + 1) + 1; - - return (current_row_count_ - 1 - extra_rows) / quantile_size + 1; - } - - bool add() - { - current_row_count_++; - return false; - } - - enum Sumfunctype sum_func() const - { - return NTILE_FUNC; - } - - void clear() - { - current_row_count_= 0; - partition_row_count_= 0; - n_old_val_= 0; - } - - const char*func_name() const - { - return "ntile"; - } - - void update_field() {} - - const Type_handler *type_handler() const { return &type_handler_slonglong; } - - void reset_field() { DBUG_ASSERT(0); } - - void set_partition_row_count(ulonglong count) - { - Partition_row_count::set_partition_row_count(count); - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - - private: - longlong get_num_quantiles() { return args[0]->val_int(); } - ulonglong n_old_val_; -}; - -class Item_sum_percentile_disc : public Item_sum_num, - public Type_handler_hybrid_field_type, - public Partition_row_count, - public Current_row_count -{ -public: - Item_sum_percentile_disc(THD *thd, Item* arg) : Item_sum_num(thd, arg), - Type_handler_hybrid_field_type(&type_handler_slonglong), - value(NULL), val_calculated(FALSE), first_call(TRUE), - prev_value(0), order_item(NULL){} - - double val_real() - { - if (get_row_count() == 0 || get_arg(0)->is_null()) - { - null_value= true; - return 0; - } - null_value= false; - return value->val_real(); - } - - longlong val_int() - { - if (get_row_count() == 0 || get_arg(0)->is_null()) - { - null_value= true; - return 0; - } - null_value= false; - return value->val_int(); - } - - my_decimal* val_decimal(my_decimal* dec) - { - if (get_row_count() == 0 || get_arg(0)->is_null()) - { - null_value= true; - return 0; - } - null_value= false; - return value->val_decimal(dec); - } - - String* val_str(String *str) - { - if (get_row_count() == 0 || get_arg(0)->is_null()) - { - null_value= true; - return 0; - } - null_value= false; - return value->val_str(str); - } - - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - if (get_row_count() == 0 || get_arg(0)->is_null()) - { - null_value= true; - return true; - } - null_value= false; - return value->get_date(thd, ltime, fuzzydate); - } - - bool val_native(THD *thd, Native *to) - { - if (get_row_count() == 0 || get_arg(0)->is_null()) - { - null_value= true; - return true; - } - null_value= false; - return value->val_native(thd, to); - } - - bool add() - { - Item *arg= get_arg(0); - if (arg->is_null()) - return false; - - if (first_call) - { - prev_value= arg->val_real(); - if (prev_value > 1 || prev_value < 0) - { - my_error(ER_ARGUMENT_OUT_OF_RANGE, MYF(0), func_name()); - return true; - } - first_call= false; - } - - double arg_val= arg->val_real(); - - if (prev_value != arg_val) - { - my_error(ER_ARGUMENT_NOT_CONSTANT, MYF(0), func_name()); - return true; - } - - if (val_calculated) - return false; - - value->store(order_item); - value->cache_value(); - if (value->null_value) - return false; - - current_row_count_++; - double val= calc_val_real(&null_value, current_row_count_); - - if (val >= prev_value && !val_calculated) - val_calculated= true; - return false; - } - - enum Sumfunctype sum_func() const - { - return PERCENTILE_DISC_FUNC; - } - - void clear() - { - val_calculated= false; - first_call= true; - value->clear(); - partition_row_count_= 0; - current_row_count_= 0; - } - - const char*func_name() const - { - return "percentile_disc"; - } - - void update_field() {} - const Type_handler *type_handler() const - {return Type_handler_hybrid_field_type::type_handler();} - - bool fix_length_and_dec() - { - decimals = 10; // TODO-cvicentiu find out how many decimals the standard - // requires. - return FALSE; - } - - void reset_field() { DBUG_ASSERT(0); } - - void set_partition_row_count(ulonglong count) - { - Partition_row_count::set_partition_row_count(count); - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - void setup_window_func(THD *thd, Window_spec *window_spec); - void setup_hybrid(THD *thd, Item *item); - bool fix_fields(THD *thd, Item **ref); - -private: - Item_cache *value; - bool val_calculated; - bool first_call; - double prev_value; - Item *order_item; -}; - -class Item_sum_percentile_cont : public Item_sum_double, - public Partition_row_count, - public Current_row_count -{ -public: - Item_sum_percentile_cont(THD *thd, Item* arg) : Item_sum_double(thd, arg), - floor_value(NULL), ceil_value(NULL), first_call(TRUE),prev_value(0), - ceil_val_calculated(FALSE), floor_val_calculated(FALSE), order_item(NULL){} - - double val_real() - { - if (get_row_count() == 0 || get_arg(0)->is_null()) - { - null_value= true; - return 0; - } - null_value= false; - double val= 1 + prev_value * (get_row_count()-1); - - /* - Applying the formula to get the value - If (CRN = FRN = RN) then the result is (value of expression from row at RN) - Otherwise the result is - (CRN - RN) * (value of expression for row at FRN) + - (RN - FRN) * (value of expression for row at CRN) - */ - - if(ceil(val) == floor(val)) - return floor_value->val_real(); - - double ret_val= ((val - floor(val)) * ceil_value->val_real()) + - ((ceil(val) - val) * floor_value->val_real()); - - return ret_val; - } - - bool add() - { - Item *arg= get_arg(0); - if (arg->is_null()) - return false; - - if (first_call) - { - first_call= false; - prev_value= arg->val_real(); - if (prev_value > 1 || prev_value < 0) - { - my_error(ER_ARGUMENT_OUT_OF_RANGE, MYF(0), func_name()); - return true; - } - } - - double arg_val= arg->val_real(); - if (prev_value != arg_val) - { - my_error(ER_ARGUMENT_NOT_CONSTANT, MYF(0), func_name()); - return true; - } - - if (!floor_val_calculated) - { - floor_value->store(order_item); - floor_value->cache_value(); - if (floor_value->null_value) - return false; - } - if (floor_val_calculated && !ceil_val_calculated) - { - ceil_value->store(order_item); - ceil_value->cache_value(); - if (ceil_value->null_value) - return false; - } - - current_row_count_++; - double val= 1 + prev_value * (get_row_count()-1); - - if (!floor_val_calculated && get_row_number() == floor(val)) - floor_val_calculated= true; - - if (!ceil_val_calculated && get_row_number() == ceil(val)) - ceil_val_calculated= true; - return false; - } - - enum Sumfunctype sum_func() const - { - return PERCENTILE_CONT_FUNC; - } - - void clear() - { - first_call= true; - floor_value->clear(); - ceil_value->clear(); - floor_val_calculated= false; - ceil_val_calculated= false; - partition_row_count_= 0; - current_row_count_= 0; - } - - const char*func_name() const - { - return "percentile_cont"; - } - void update_field() {} - - bool fix_length_and_dec() - { - decimals = 10; // TODO-cvicentiu find out how many decimals the standard - // requires. - return FALSE; - } - - void reset_field() { DBUG_ASSERT(0); } - - void set_partition_row_count(ulonglong count) - { - Partition_row_count::set_partition_row_count(count); - } - - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } - void setup_window_func(THD *thd, Window_spec *window_spec); - void setup_hybrid(THD *thd, Item *item); - bool fix_fields(THD *thd, Item **ref); - -private: - Item_cache *floor_value; - Item_cache *ceil_value; - bool first_call; - double prev_value; - bool ceil_val_calculated; - bool floor_val_calculated; - Item *order_item; -}; - - - - -class Item_window_func : public Item_func_or_sum -{ - /* Window function parameters as we've got them from the parser */ -public: - LEX_CSTRING *window_name; -public: - Window_spec *window_spec; - -public: - Item_window_func(THD *thd, Item_sum *win_func, LEX_CSTRING *win_name) - : Item_func_or_sum(thd, (Item *) win_func), - window_name(win_name), window_spec(NULL), - force_return_blank(true), - read_value_from_result_field(false) {} - - Item_window_func(THD *thd, Item_sum *win_func, Window_spec *win_spec) - : Item_func_or_sum(thd, (Item *) win_func), - window_name(NULL), window_spec(win_spec), - force_return_blank(true), - read_value_from_result_field(false) {} - - Item_sum *window_func() const { return (Item_sum *) args[0]; } - - void update_used_tables(); - - /* - This is used by filesort to mark the columns it needs to read (because they - participate in the sort criteria and/or row retrieval. Window functions can - only be used in sort criteria). - - Sorting by window function value is only done after the window functions - have been computed. In that case, window function will need to read its - temp.table field. In order to allow that, mark that field in the read_set. - */ - bool register_field_in_read_map(void *arg) - { - TABLE *table= (TABLE*) arg; - if (result_field && (result_field->table == table || !table)) - { - bitmap_set_bit(result_field->table->read_set, result_field->field_index); - } - return 0; - } - - bool is_frame_prohibited() const - { - switch (window_func()->sum_func()) { - case Item_sum::ROW_NUMBER_FUNC: - case Item_sum::RANK_FUNC: - case Item_sum::DENSE_RANK_FUNC: - case Item_sum::PERCENT_RANK_FUNC: - case Item_sum::CUME_DIST_FUNC: - case Item_sum::NTILE_FUNC: - case Item_sum::PERCENTILE_CONT_FUNC: - case Item_sum::PERCENTILE_DISC_FUNC: - return true; - default: - return false; - } - } - - bool requires_special_cursors() const - { - switch (window_func()->sum_func()) { - case Item_sum::FIRST_VALUE_FUNC: - case Item_sum::LAST_VALUE_FUNC: - case Item_sum::NTH_VALUE_FUNC: - case Item_sum::LAG_FUNC: - case Item_sum::LEAD_FUNC: - return true; - default: - return false; - } - } - - bool requires_partition_size() const - { - switch (window_func()->sum_func()) { - case Item_sum::PERCENT_RANK_FUNC: - case Item_sum::CUME_DIST_FUNC: - case Item_sum::NTILE_FUNC: - case Item_sum::PERCENTILE_CONT_FUNC: - case Item_sum::PERCENTILE_DISC_FUNC: - return true; - default: - return false; - } - } - - bool requires_peer_size() const - { - switch (window_func()->sum_func()) { - case Item_sum::CUME_DIST_FUNC: - return true; - default: - return false; - } - } - - bool is_order_list_mandatory() const - { - switch (window_func()->sum_func()) { - case Item_sum::RANK_FUNC: - case Item_sum::DENSE_RANK_FUNC: - case Item_sum::PERCENT_RANK_FUNC: - case Item_sum::CUME_DIST_FUNC: - case Item_sum::LAG_FUNC: - case Item_sum::LEAD_FUNC: - case Item_sum::PERCENTILE_CONT_FUNC: - case Item_sum::PERCENTILE_DISC_FUNC: - return true; - default: - return false; - } - } - - bool only_single_element_order_list() const - { - switch (window_func()->sum_func()){ - case Item_sum::PERCENTILE_CONT_FUNC: - case Item_sum::PERCENTILE_DISC_FUNC: - return true; - default: - return false; - } - } - - bool check_result_type_of_order_item(); - - - - /* - Computation functions. - TODO: consoder merging these with class Group_bound_tracker. - */ - void setup_partition_border_check(THD *thd); - - const Type_handler *type_handler() const - { - return ((Item_sum *) args[0])->type_handler(); - } - enum Item::Type type() const { return Item::WINDOW_FUNC_ITEM; } - -private: - /* - Window functions are very special functions, so val_() methods have - special meaning for them: - - - Phase#1, "Initial" we run the join and put its result into temporary - table. For window functions, we write the default value (NULL?) as - a placeholder. - - - Phase#2: "Computation": executor does the scan in {PARTITION, ORDER BY} - order of this window function. It calls appropriate methods to inform - the window function about rows entering/leaving the window. - It calls window_func()->val_int() so that current window function value - can be saved and stored in the temp.table. - - - Phase#3: "Retrieval" the temporary table is read and passed to query - output. However, Item_window_func still remains in the select list, - so item_windowfunc->val_int() will be called. - During Phase#3, read_value_from_result_field= true. - */ - bool force_return_blank; - bool read_value_from_result_field; - void print_for_percentile_functions(String *str, enum_query_type query_type); - -public: - void set_phase_to_initial() - { - force_return_blank= true; - read_value_from_result_field= false; - } - void set_phase_to_computation() - { - force_return_blank= false; - read_value_from_result_field= false; - } - void set_phase_to_retrieval() - { - force_return_blank= false; - read_value_from_result_field= true; - } - - bool is_null() - { - if (force_return_blank) - return true; - - if (read_value_from_result_field) - return result_field->is_null(); - - return window_func()->is_null(); - } - - double val_real() - { - double res; - if (force_return_blank) - { - res= 0.0; - null_value= true; - } - else if (read_value_from_result_field) - { - res= result_field->val_real(); - null_value= result_field->is_null(); - } - else - { - res= window_func()->val_real(); - null_value= window_func()->null_value; - } - return res; - } - - longlong val_int() - { - longlong res; - if (force_return_blank) - { - res= 0; - null_value= true; - } - else if (read_value_from_result_field) - { - res= result_field->val_int(); - null_value= result_field->is_null(); - } - else - { - res= window_func()->val_int(); - null_value= window_func()->null_value; - } - return res; - } - - String* val_str(String* str) - { - String *res; - if (force_return_blank) - { - null_value= true; - res= NULL; - } - else if (read_value_from_result_field) - { - if ((null_value= result_field->is_null())) - res= NULL; - else - res= result_field->val_str(str); - } - else - { - res= window_func()->val_str(str); - null_value= window_func()->null_value; - } - return res; - } - - bool val_native(THD *thd, Native *to) - { - if (force_return_blank) - return null_value= true; - if (read_value_from_result_field) - return val_native_from_field(result_field, to); - return val_native_from_item(thd, window_func(), to); - } - - my_decimal* val_decimal(my_decimal* dec) - { - my_decimal *res; - if (force_return_blank) - { - null_value= true; - res= NULL; - } - else if (read_value_from_result_field) - { - if ((null_value= result_field->is_null())) - res= NULL; - else - res= result_field->val_decimal(dec); - } - else - { - res= window_func()->val_decimal(dec); - null_value= window_func()->null_value; - } - return res; - } - - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - bool res; - if (force_return_blank) - { - null_value= true; - res= true; - } - else if (read_value_from_result_field) - { - if ((null_value= result_field->is_null())) - res= true; - else - res= result_field->get_date(ltime, fuzzydate); - } - else - { - res= window_func()->get_date(thd, ltime, fuzzydate); - null_value= window_func()->null_value; - } - return res; - } - - void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, - List &fields, uint flags); - - bool fix_length_and_dec() - { - Type_std_attributes::set(window_func()); - return FALSE; - } - - const char* func_name() const { return "WF"; } - - bool fix_fields(THD *thd, Item **ref); - - bool resolve_window_name(THD *thd); - - void print(String *str, enum_query_type query_type); - - Item *get_copy(THD *thd) { return 0; } - -}; - -#endif /* ITEM_WINDOWFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_xmlfunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_xmlfunc.h deleted file mode 100644 index 806739d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/item_xmlfunc.h +++ /dev/null @@ -1,157 +0,0 @@ -#ifndef ITEM_XMLFUNC_INCLUDED -#define ITEM_XMLFUNC_INCLUDED - -/* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2009, 2019, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* This file defines all XML functions */ - - -typedef struct my_xml_node_st MY_XML_NODE; - - -/* Structure to store nodeset elements */ -class MY_XPATH_FLT -{ -public: - uint num; // Absolute position in MY_XML_NODE array - uint pos; // Relative position in context - uint size; // Context size -public: - MY_XPATH_FLT(uint32 num_arg, uint32 pos_arg) - :num(num_arg), pos(pos_arg), size(0) - { } - MY_XPATH_FLT(uint32 num_arg, uint32 pos_arg, uint32 size_arg) - :num(num_arg), pos(pos_arg), size(size_arg) - { } - bool append_to(Native *to) const - { - return to->append((const char*) this, (uint32) sizeof(*this)); - } -}; - - -class NativeNodesetBuffer: public NativeBuffer<16*sizeof(MY_XPATH_FLT)> -{ -public: - const MY_XPATH_FLT &element(uint i) const - { - const MY_XPATH_FLT *p= (MY_XPATH_FLT*) (ptr() + i * sizeof(MY_XPATH_FLT)); - return *p; - } - uint32 elements() const - { - return length() / sizeof(MY_XPATH_FLT); - } -}; - - -class Item_xml_str_func: public Item_str_func -{ -protected: - /* - A helper class to store raw and parsed XML. - */ - class XML - { - bool m_cached; - String *m_raw_ptr; // Pointer to text representation - String m_raw_buf; // Cached text representation - String m_parsed_buf; // Array of MY_XML_NODEs, pointing to raw_buffer - bool parse(); - void reset() - { - m_cached= false; - m_raw_ptr= (String *) 0; - } - public: - XML() { reset(); } - void set_charset(CHARSET_INFO *cs) { m_parsed_buf.set_charset(cs); } - String *raw() { return m_raw_ptr; } - String *parsed() { return &m_parsed_buf; } - const MY_XML_NODE *node(uint idx); - bool cached() { return m_cached; } - bool parse(String *raw, bool cache); - bool parse(Item *item, bool cache) - { - String *res; - if (!(res= item->val_str(&m_raw_buf))) - { - m_raw_ptr= (String *) 0; - m_cached= cache; - return true; - } - return parse(res, cache); - } - }; - String m_xpath_query; // XPath query text - Item *nodeset_func; - XML xml; - bool get_xml(XML *xml_arg, bool cache= false) - { - if (!cache && xml_arg->cached()) - return xml_arg->raw() == 0; - return xml_arg->parse(args[0], cache); - } -public: - Item_xml_str_func(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) - { - maybe_null= TRUE; - } - Item_xml_str_func(THD *thd, Item *a, Item *b, Item *c): - Item_str_func(thd, a, b, c) - { - maybe_null= TRUE; - } - bool fix_fields(THD *thd, Item **ref); - bool fix_length_and_dec(); - bool const_item() const - { - return const_item_cache && (!nodeset_func || nodeset_func->const_item()); - } -}; - - -class Item_func_xml_extractvalue: public Item_xml_str_func -{ -public: - Item_func_xml_extractvalue(THD *thd, Item *a, Item *b): - Item_xml_str_func(thd, a, b) {} - const char *func_name() const { return "extractvalue"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - - -class Item_func_xml_update: public Item_xml_str_func -{ - NativeNodesetBuffer tmp_native_value2; - String tmp_value3; - bool collect_result(String *str, - const MY_XML_NODE *cut, - const String *replace); -public: - Item_func_xml_update(THD *thd, Item *a, Item *b, Item *c): - Item_xml_str_func(thd, a, b, c) {} - const char *func_name() const { return "updatexml"; } - String *val_str(String *); - Item *get_copy(THD *thd) - { return get_item_copy(thd, this); } -}; - -#endif /* ITEM_XMLFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/key.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/key.h deleted file mode 100644 index 871373b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/key.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef KEY_INCLUDED -#define KEY_INCLUDED - -class Field; -class String; -struct TABLE; -typedef struct st_bitmap MY_BITMAP; -typedef struct st_key KEY; -typedef struct st_key_part_info KEY_PART_INFO; - -int find_ref_key(KEY *key, uint key_count, uchar *record, Field *field, - uint *key_length, uint *keypart); -void key_copy(uchar *to_key, const uchar *from_record, const KEY *key_info, - uint key_length, bool with_zerofill= FALSE); -void key_restore(uchar *to_record, const uchar *from_key, KEY *key_info, - uint key_length); -bool key_cmp_if_same(TABLE *form,const uchar *key,uint index,uint key_length); -void key_unpack(String *to, TABLE *table, KEY *key); -void field_unpack(String *to, Field *field, const uchar *rec, uint max_length, - bool prefix_key); -bool is_key_used(TABLE *table, uint idx, const MY_BITMAP *fields); -int key_cmp(KEY_PART_INFO *key_part, const uchar *key, uint key_length); -ulong key_hashnr(KEY *key_info, uint used_key_parts, const uchar *key); -bool key_buf_cmp(KEY *key_info, uint used_key_parts, - const uchar *key1, const uchar *key2); -extern "C" int key_rec_cmp(void *key_info, uchar *a, uchar *b); -int key_tuple_cmp(KEY_PART_INFO *part, uchar *key1, uchar *key2, uint tuple_length); - -#endif /* KEY_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/keycaches.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/keycaches.h deleted file mode 100644 index 68c3dd3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/keycaches.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef KEYCACHES_INCLUDED -#define KEYCACHES_INCLUDED - -/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "sql_list.h" -#include -#include - -extern "C" -{ - typedef int (*process_key_cache_t) (const char *, KEY_CACHE *, void *); -} - -class NAMED_ILINK; - -class NAMED_ILIST: public I_List -{ - public: - void delete_elements(void (*free_element)(const char*, void*)); - bool delete_element(const char *name, size_t length, void (*free_element)(const char*, void*)); -}; - -/* For key cache */ -extern LEX_CSTRING default_key_cache_base; -extern KEY_CACHE zero_key_cache; -extern NAMED_ILIST key_caches; - -KEY_CACHE *create_key_cache(const char *name, size_t length); -KEY_CACHE *get_key_cache(const LEX_CSTRING *cache_name); -KEY_CACHE *get_or_create_key_cache(const char *name, size_t length); -void free_key_cache(const char *name, void *key_cache); -bool process_key_caches(process_key_cache_t func, void *param); - -/* For Rpl_filter */ -extern LEX_CSTRING default_rpl_filter_base; -extern NAMED_ILIST rpl_filters; - -Rpl_filter *create_rpl_filter(const char *name, size_t length); -Rpl_filter *get_rpl_filter(LEX_CSTRING *filter_name); -Rpl_filter *get_or_create_rpl_filter(const char *name, size_t length); -void free_all_rpl_filters(void); - -#endif /* KEYCACHES_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex.h deleted file mode 100644 index 542356c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex.h +++ /dev/null @@ -1,791 +0,0 @@ -#ifndef LEX_INCLUDED -#define LEX_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. - Copyright (c) 2009, 2015, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* This file includes all reserved words and functions */ - -#include "lex_symbol.h" - -SYM_GROUP sym_group_common= {"", ""}; -SYM_GROUP sym_group_geom= {"Spatial extensions", "HAVE_SPATIAL"}; -SYM_GROUP sym_group_rtree= {"RTree keys", "HAVE_RTREE_KEYS"}; - -/* We don't want to include sql_yacc.h into gen_lex_hash */ -#ifdef NO_YACC_SYMBOLS -#define SYM_OR_NULL(A) 0 -#else -#define SYM_OR_NULL(A) A -#endif - -#define SYM(A) SYM_OR_NULL(A),0,&sym_group_common - -/* - Symbols are broken into separated arrays to allow field names with - same name as functions. - These are kept sorted for human lookup (the symbols are hashed). - - NOTE! The symbol tables should be the same regardless of what features - are compiled into the server. Don't add ifdef'ed symbols to the - lists - NOTE!! - If you add or delete symbols from this file, you must also update results for - the perfschema.start_server_low_digest_sql_length test! -*/ - -static SYMBOL symbols[] = { - { "&&", SYM(AND_AND_SYM)}, - { "<=", SYM(LE)}, - { "<>", SYM(NE)}, - { "!=", SYM(NE)}, - { ">=", SYM(GE)}, - { "<<", SYM(SHIFT_LEFT)}, - { ">>", SYM(SHIFT_RIGHT)}, - { "<=>", SYM(EQUAL_SYM)}, - { "ACCESSIBLE", SYM(ACCESSIBLE_SYM)}, - { "ACCOUNT", SYM(ACCOUNT_SYM)}, - { "ACTION", SYM(ACTION)}, - { "ADD", SYM(ADD)}, - { "ADMIN", SYM(ADMIN_SYM)}, - { "AFTER", SYM(AFTER_SYM)}, - { "AGAINST", SYM(AGAINST)}, - { "AGGREGATE", SYM(AGGREGATE_SYM)}, - { "ALL", SYM(ALL)}, - { "ALGORITHM", SYM(ALGORITHM_SYM)}, - { "ALTER", SYM(ALTER)}, - { "ALWAYS", SYM(ALWAYS_SYM)}, - { "ANALYZE", SYM(ANALYZE_SYM)}, - { "AND", SYM(AND_SYM)}, - { "ANY", SYM(ANY_SYM)}, - { "AS", SYM(AS)}, - { "ASC", SYM(ASC)}, - { "ASCII", SYM(ASCII_SYM)}, - { "ASENSITIVE", SYM(ASENSITIVE_SYM)}, - { "AT", SYM(AT_SYM)}, - { "ATOMIC", SYM(ATOMIC_SYM)}, - { "AUTHORS", SYM(AUTHORS_SYM)}, - { "AUTO_INCREMENT", SYM(AUTO_INC)}, - { "AUTOEXTEND_SIZE", SYM(AUTOEXTEND_SIZE_SYM)}, - { "AUTO", SYM(AUTO_SYM)}, - { "AVG", SYM(AVG_SYM)}, - { "AVG_ROW_LENGTH", SYM(AVG_ROW_LENGTH)}, - { "BACKUP", SYM(BACKUP_SYM)}, - { "BEFORE", SYM(BEFORE_SYM)}, - { "BEGIN", SYM(BEGIN_MARIADB_SYM)}, - { "BETWEEN", SYM(BETWEEN_SYM)}, - { "BIGINT", SYM(BIGINT)}, - { "BINARY", SYM(BINARY)}, - { "BINLOG", SYM(BINLOG_SYM)}, - { "BIT", SYM(BIT_SYM)}, - { "BLOB", SYM(BLOB_MARIADB_SYM)}, - { "BLOCK", SYM(BLOCK_SYM)}, - { "BODY", SYM(BODY_MARIADB_SYM)}, - { "BOOL", SYM(BOOL_SYM)}, - { "BOOLEAN", SYM(BOOLEAN_SYM)}, - { "BOTH", SYM(BOTH)}, - { "BTREE", SYM(BTREE_SYM)}, - { "BY", SYM(BY)}, - { "BYTE", SYM(BYTE_SYM)}, - { "CACHE", SYM(CACHE_SYM)}, - { "CALL", SYM(CALL_SYM)}, - { "CASCADE", SYM(CASCADE)}, - { "CASCADED", SYM(CASCADED)}, - { "CASE", SYM(CASE_SYM)}, - { "CATALOG_NAME", SYM(CATALOG_NAME_SYM)}, - { "CHAIN", SYM(CHAIN_SYM)}, - { "CHANGE", SYM(CHANGE)}, - { "CHANGED", SYM(CHANGED)}, - { "CHAR", SYM(CHAR_SYM)}, - { "CHARACTER", SYM(CHAR_SYM)}, - { "CHARSET", SYM(CHARSET)}, - { "CHECK", SYM(CHECK_SYM)}, - { "CHECKPOINT", SYM(CHECKPOINT_SYM)}, - { "CHECKSUM", SYM(CHECKSUM_SYM)}, - { "CIPHER", SYM(CIPHER_SYM)}, - { "CLASS_ORIGIN", SYM(CLASS_ORIGIN_SYM)}, - { "CLIENT", SYM(CLIENT_SYM)}, - { "CLOB", SYM(CLOB_MARIADB_SYM)}, - { "CLOSE", SYM(CLOSE_SYM)}, - { "COALESCE", SYM(COALESCE)}, - { "CODE", SYM(CODE_SYM)}, - { "COLLATE", SYM(COLLATE_SYM)}, - { "COLLATION", SYM(COLLATION_SYM)}, - { "COLUMN", SYM(COLUMN_SYM)}, - { "COLUMN_NAME", SYM(COLUMN_NAME_SYM)}, - { "COLUMNS", SYM(COLUMNS)}, - { "COLUMN_ADD", SYM(COLUMN_ADD_SYM)}, - { "COLUMN_CHECK", SYM(COLUMN_CHECK_SYM)}, - { "COLUMN_CREATE", SYM(COLUMN_CREATE_SYM)}, - { "COLUMN_DELETE", SYM(COLUMN_DELETE_SYM)}, - { "COLUMN_GET", SYM(COLUMN_GET_SYM)}, - { "COMMENT", SYM(COMMENT_SYM)}, - { "COMMIT", SYM(COMMIT_SYM)}, - { "COMMITTED", SYM(COMMITTED_SYM)}, - { "COMPACT", SYM(COMPACT_SYM)}, - { "COMPLETION", SYM(COMPLETION_SYM)}, - { "COMPRESSED", SYM(COMPRESSED_SYM)}, - { "CONCURRENT", SYM(CONCURRENT)}, - { "CONDITION", SYM(CONDITION_SYM)}, - { "CONNECTION", SYM(CONNECTION_SYM)}, - { "CONSISTENT", SYM(CONSISTENT_SYM)}, - { "CONSTRAINT", SYM(CONSTRAINT)}, - { "CONSTRAINT_CATALOG", SYM(CONSTRAINT_CATALOG_SYM)}, - { "CONSTRAINT_NAME", SYM(CONSTRAINT_NAME_SYM)}, - { "CONSTRAINT_SCHEMA", SYM(CONSTRAINT_SCHEMA_SYM)}, - { "CONTAINS", SYM(CONTAINS_SYM)}, - { "CONTEXT", SYM(CONTEXT_SYM)}, - { "CONTINUE", SYM(CONTINUE_MARIADB_SYM)}, - { "CONTRIBUTORS", SYM(CONTRIBUTORS_SYM)}, - { "CONVERT", SYM(CONVERT_SYM)}, - { "CPU", SYM(CPU_SYM)}, - { "CREATE", SYM(CREATE)}, - { "CROSS", SYM(CROSS)}, - { "CUBE", SYM(CUBE_SYM)}, - { "CURRENT", SYM(CURRENT_SYM)}, - { "CURRENT_DATE", SYM(CURDATE)}, - { "CURRENT_POS", SYM(CURRENT_POS_SYM)}, - { "CURRENT_ROLE", SYM(CURRENT_ROLE)}, - { "CURRENT_TIME", SYM(CURTIME)}, - { "CURRENT_TIMESTAMP", SYM(NOW_SYM)}, - { "CURRENT_USER", SYM(CURRENT_USER)}, - { "CURSOR", SYM(CURSOR_SYM)}, - { "CURSOR_NAME", SYM(CURSOR_NAME_SYM)}, - { "CYCLE", SYM(CYCLE_SYM)}, - { "DATA", SYM(DATA_SYM)}, - { "DATABASE", SYM(DATABASE)}, - { "DATABASES", SYM(DATABASES)}, - { "DATAFILE", SYM(DATAFILE_SYM)}, - { "DATE", SYM(DATE_SYM)}, - { "DATETIME", SYM(DATETIME)}, - { "DAY", SYM(DAY_SYM)}, - { "DAY_HOUR", SYM(DAY_HOUR_SYM)}, - { "DAY_MICROSECOND", SYM(DAY_MICROSECOND_SYM)}, - { "DAY_MINUTE", SYM(DAY_MINUTE_SYM)}, - { "DAY_SECOND", SYM(DAY_SECOND_SYM)}, - { "DEALLOCATE", SYM(DEALLOCATE_SYM)}, - { "DEC", SYM(DECIMAL_SYM)}, - { "DECIMAL", SYM(DECIMAL_SYM)}, - { "DECLARE", SYM(DECLARE_MARIADB_SYM)}, - { "DEFAULT", SYM(DEFAULT)}, - { "DEFINER", SYM(DEFINER_SYM)}, - { "DELAYED", SYM(DELAYED_SYM)}, - { "DELAY_KEY_WRITE", SYM(DELAY_KEY_WRITE_SYM)}, - { "DELETE", SYM(DELETE_SYM)}, - { "DELETE_DOMAIN_ID", SYM(DELETE_DOMAIN_ID_SYM)}, - { "DESC", SYM(DESC)}, - { "DESCRIBE", SYM(DESCRIBE)}, - { "DES_KEY_FILE", SYM(DES_KEY_FILE)}, - { "DETERMINISTIC", SYM(DETERMINISTIC_SYM)}, - { "DIAGNOSTICS", SYM(DIAGNOSTICS_SYM)}, - { "DIRECTORY", SYM(DIRECTORY_SYM)}, - { "DISABLE", SYM(DISABLE_SYM)}, - { "DISCARD", SYM(DISCARD)}, - { "DISK", SYM(DISK_SYM)}, - { "DISTINCT", SYM(DISTINCT)}, - { "DISTINCTROW", SYM(DISTINCT)}, /* Access likes this */ - { "DIV", SYM(DIV_SYM)}, - { "DO", SYM(DO_SYM)}, - { "DOUBLE", SYM(DOUBLE_SYM)}, - { "DO_DOMAIN_IDS", SYM(DO_DOMAIN_IDS_SYM)}, - { "DROP", SYM(DROP)}, - { "DUAL", SYM(DUAL_SYM)}, - { "DUMPFILE", SYM(DUMPFILE)}, - { "DUPLICATE", SYM(DUPLICATE_SYM)}, - { "DYNAMIC", SYM(DYNAMIC_SYM)}, - { "EACH", SYM(EACH_SYM)}, - { "ELSE", SYM(ELSE)}, - { "ELSEIF", SYM(ELSEIF_MARIADB_SYM)}, - { "ELSIF", SYM(ELSIF_MARIADB_SYM)}, - { "ENABLE", SYM(ENABLE_SYM)}, - { "ENCLOSED", SYM(ENCLOSED)}, - { "END", SYM(END)}, - { "ENDS", SYM(ENDS_SYM)}, - { "ENGINE", SYM(ENGINE_SYM)}, - { "ENGINES", SYM(ENGINES_SYM)}, - { "ENUM", SYM(ENUM)}, - { "ERROR", SYM(ERROR_SYM)}, - { "ERRORS", SYM(ERRORS)}, - { "ESCAPE", SYM(ESCAPE_SYM)}, - { "ESCAPED", SYM(ESCAPED)}, - { "EVENT", SYM(EVENT_SYM)}, - { "EVENTS", SYM(EVENTS_SYM)}, - { "EVERY", SYM(EVERY_SYM)}, - { "EXAMINED", SYM(EXAMINED_SYM)}, - { "EXCEPT", SYM(EXCEPT_SYM)}, - { "EXCHANGE", SYM(EXCHANGE_SYM)}, - { "EXCLUDE", SYM(EXCLUDE_SYM)}, - { "EXECUTE", SYM(EXECUTE_SYM)}, - { "EXCEPTION", SYM(EXCEPTION_MARIADB_SYM)}, - { "EXISTS", SYM(EXISTS)}, - { "EXIT", SYM(EXIT_MARIADB_SYM)}, - { "EXPANSION", SYM(EXPANSION_SYM)}, - { "EXPIRE", SYM(EXPIRE_SYM)}, - { "EXPORT", SYM(EXPORT_SYM)}, - { "EXPLAIN", SYM(DESCRIBE)}, - { "EXTENDED", SYM(EXTENDED_SYM)}, - { "EXTENT_SIZE", SYM(EXTENT_SIZE_SYM)}, - { "FALSE", SYM(FALSE_SYM)}, - { "FAST", SYM(FAST_SYM)}, - { "FAULTS", SYM(FAULTS_SYM)}, - { "FEDERATED", SYM(FEDERATED_SYM)}, - { "FETCH", SYM(FETCH_SYM)}, - { "FIELDS", SYM(COLUMNS)}, - { "FILE", SYM(FILE_SYM)}, - { "FIRST", SYM(FIRST_SYM)}, - { "FIXED", SYM(FIXED_SYM)}, - { "FLOAT", SYM(FLOAT_SYM)}, - { "FLOAT4", SYM(FLOAT_SYM)}, - { "FLOAT8", SYM(DOUBLE_SYM)}, - { "FLUSH", SYM(FLUSH_SYM)}, - { "FOLLOWING", SYM(FOLLOWING_SYM)}, - { "FOLLOWS", SYM(FOLLOWS_SYM)}, - { "FOR", SYM(FOR_SYM)}, - { "FORCE", SYM(FORCE_SYM)}, - { "FOREIGN", SYM(FOREIGN)}, - { "FORMAT", SYM(FORMAT_SYM)}, - { "FOUND", SYM(FOUND_SYM)}, - { "FROM", SYM(FROM)}, - { "FULL", SYM(FULL)}, - { "FULLTEXT", SYM(FULLTEXT_SYM)}, - { "FUNCTION", SYM(FUNCTION_SYM)}, - { "GENERAL", SYM(GENERAL)}, - { "GENERATED", SYM(GENERATED_SYM)}, - { "GET_FORMAT", SYM(GET_FORMAT)}, - { "GET", SYM(GET_SYM)}, - { "GLOBAL", SYM(GLOBAL_SYM)}, - { "GOTO", SYM(GOTO_MARIADB_SYM)}, - { "GRANT", SYM(GRANT)}, - { "GRANTS", SYM(GRANTS)}, - { "GROUP", SYM(GROUP_SYM)}, - { "HANDLER", SYM(HANDLER_SYM)}, - { "HARD", SYM(HARD_SYM)}, - { "HASH", SYM(HASH_SYM)}, - { "HAVING", SYM(HAVING)}, - { "HELP", SYM(HELP_SYM)}, - { "HIGH_PRIORITY", SYM(HIGH_PRIORITY)}, - { "HISTORY", SYM(HISTORY_SYM)}, - { "HOST", SYM(HOST_SYM)}, - { "HOSTS", SYM(HOSTS_SYM)}, - { "HOUR", SYM(HOUR_SYM)}, - { "HOUR_MICROSECOND", SYM(HOUR_MICROSECOND_SYM)}, - { "HOUR_MINUTE", SYM(HOUR_MINUTE_SYM)}, - { "HOUR_SECOND", SYM(HOUR_SECOND_SYM)}, - { "ID", SYM(ID_SYM)}, - { "IDENTIFIED", SYM(IDENTIFIED_SYM)}, - { "IF", SYM(IF_SYM)}, - { "IGNORE", SYM(IGNORE_SYM)}, - { "IGNORE_DOMAIN_IDS", SYM(IGNORE_DOMAIN_IDS_SYM)}, - { "IGNORE_SERVER_IDS", SYM(IGNORE_SERVER_IDS_SYM)}, - { "IMMEDIATE", SYM(IMMEDIATE_SYM)}, - { "IMPORT", SYM(IMPORT)}, - { "INTERSECT", SYM(INTERSECT_SYM)}, - { "IN", SYM(IN_SYM)}, - { "INCREMENT", SYM(INCREMENT_SYM)}, - { "INDEX", SYM(INDEX_SYM)}, - { "INDEXES", SYM(INDEXES)}, - { "INFILE", SYM(INFILE)}, - { "INITIAL_SIZE", SYM(INITIAL_SIZE_SYM)}, - { "INNER", SYM(INNER_SYM)}, - { "INOUT", SYM(INOUT_SYM)}, - { "INSENSITIVE", SYM(INSENSITIVE_SYM)}, - { "INSERT", SYM(INSERT)}, - { "INSERT_METHOD", SYM(INSERT_METHOD)}, - { "INSTALL", SYM(INSTALL_SYM)}, - { "INT", SYM(INT_SYM)}, - { "INT1", SYM(TINYINT)}, - { "INT2", SYM(SMALLINT)}, - { "INT3", SYM(MEDIUMINT)}, - { "INT4", SYM(INT_SYM)}, - { "INT8", SYM(BIGINT)}, - { "INTEGER", SYM(INT_SYM)}, - { "INTERVAL", SYM(INTERVAL_SYM)}, - { "INVISIBLE", SYM(INVISIBLE_SYM)}, - { "INTO", SYM(INTO)}, - { "IO", SYM(IO_SYM)}, - { "IO_THREAD", SYM(RELAY_THREAD)}, - { "IPC", SYM(IPC_SYM)}, - { "IS", SYM(IS)}, - { "ISOLATION", SYM(ISOLATION)}, - { "ISOPEN", SYM(ISOPEN_SYM)}, - { "ISSUER", SYM(ISSUER_SYM)}, - { "ITERATE", SYM(ITERATE_SYM)}, - { "INVOKER", SYM(INVOKER_SYM)}, - { "JOIN", SYM(JOIN_SYM)}, - { "JSON", SYM(JSON_SYM)}, - { "KEY", SYM(KEY_SYM)}, - { "KEYS", SYM(KEYS)}, - { "KEY_BLOCK_SIZE", SYM(KEY_BLOCK_SIZE)}, - { "KILL", SYM(KILL_SYM)}, - { "LANGUAGE", SYM(LANGUAGE_SYM)}, - { "LAST", SYM(LAST_SYM)}, - { "LAST_VALUE", SYM(LAST_VALUE)}, - { "LASTVAL", SYM(LASTVAL_SYM)}, - { "LEADING", SYM(LEADING)}, - { "LEAVE", SYM(LEAVE_SYM)}, - { "LEAVES", SYM(LEAVES)}, - { "LEFT", SYM(LEFT)}, - { "LESS", SYM(LESS_SYM)}, - { "LEVEL", SYM(LEVEL_SYM)}, - { "LIKE", SYM(LIKE)}, - { "LIMIT", SYM(LIMIT)}, - { "LINEAR", SYM(LINEAR_SYM)}, - { "LINES", SYM(LINES)}, - { "LIST", SYM(LIST_SYM)}, - { "LOAD", SYM(LOAD)}, - { "LOCAL", SYM(LOCAL_SYM)}, - { "LOCALTIME", SYM(NOW_SYM)}, - { "LOCALTIMESTAMP", SYM(NOW_SYM)}, - { "LOCK", SYM(LOCK_SYM)}, - { "LOCKS", SYM(LOCKS_SYM)}, - { "LOGFILE", SYM(LOGFILE_SYM)}, - { "LOGS", SYM(LOGS_SYM)}, - { "LONG", SYM(LONG_SYM)}, - { "LONGBLOB", SYM(LONGBLOB)}, - { "LONGTEXT", SYM(LONGTEXT)}, - { "LOOP", SYM(LOOP_SYM)}, - { "LOW_PRIORITY", SYM(LOW_PRIORITY)}, - { "MASTER", SYM(MASTER_SYM)}, - { "MASTER_CONNECT_RETRY", SYM(MASTER_CONNECT_RETRY_SYM)}, - { "MASTER_DELAY", SYM(MASTER_DELAY_SYM)}, - { "MASTER_GTID_POS", SYM(MASTER_GTID_POS_SYM)}, - { "MASTER_HOST", SYM(MASTER_HOST_SYM)}, - { "MASTER_LOG_FILE", SYM(MASTER_LOG_FILE_SYM)}, - { "MASTER_LOG_POS", SYM(MASTER_LOG_POS_SYM)}, - { "MASTER_PASSWORD", SYM(MASTER_PASSWORD_SYM)}, - { "MASTER_PORT", SYM(MASTER_PORT_SYM)}, - { "MASTER_SERVER_ID", SYM(MASTER_SERVER_ID_SYM)}, - { "MASTER_SSL", SYM(MASTER_SSL_SYM)}, - { "MASTER_SSL_CA", SYM(MASTER_SSL_CA_SYM)}, - { "MASTER_SSL_CAPATH",SYM(MASTER_SSL_CAPATH_SYM)}, - { "MASTER_SSL_CERT", SYM(MASTER_SSL_CERT_SYM)}, - { "MASTER_SSL_CIPHER",SYM(MASTER_SSL_CIPHER_SYM)}, - { "MASTER_SSL_CRL", SYM(MASTER_SSL_CRL_SYM)}, - { "MASTER_SSL_CRLPATH",SYM(MASTER_SSL_CRLPATH_SYM)}, - { "MASTER_SSL_KEY", SYM(MASTER_SSL_KEY_SYM)}, - { "MASTER_SSL_VERIFY_SERVER_CERT", SYM(MASTER_SSL_VERIFY_SERVER_CERT_SYM)}, - { "MASTER_USER", SYM(MASTER_USER_SYM)}, - { "MASTER_USE_GTID", SYM(MASTER_USE_GTID_SYM)}, - { "MASTER_HEARTBEAT_PERIOD", SYM(MASTER_HEARTBEAT_PERIOD_SYM)}, - { "MATCH", SYM(MATCH)}, - { "MAX_CONNECTIONS_PER_HOUR", SYM(MAX_CONNECTIONS_PER_HOUR)}, - { "MAX_QUERIES_PER_HOUR", SYM(MAX_QUERIES_PER_HOUR)}, - { "MAX_ROWS", SYM(MAX_ROWS)}, - { "MAX_SIZE", SYM(MAX_SIZE_SYM)}, - { "MAX_STATEMENT_TIME", SYM(MAX_STATEMENT_TIME_SYM)}, - { "MAX_UPDATES_PER_HOUR", SYM(MAX_UPDATES_PER_HOUR)}, - { "MAX_USER_CONNECTIONS", SYM(MAX_USER_CONNECTIONS_SYM)}, - { "MAXVALUE", SYM(MAXVALUE_SYM)}, - { "MEDIUM", SYM(MEDIUM_SYM)}, - { "MEDIUMBLOB", SYM(MEDIUMBLOB)}, - { "MEDIUMINT", SYM(MEDIUMINT)}, - { "MEDIUMTEXT", SYM(MEDIUMTEXT)}, - { "MEMORY", SYM(MEMORY_SYM)}, - { "MERGE", SYM(MERGE_SYM)}, - { "MESSAGE_TEXT", SYM(MESSAGE_TEXT_SYM)}, - { "MICROSECOND", SYM(MICROSECOND_SYM)}, - { "MIDDLEINT", SYM(MEDIUMINT)}, /* For powerbuilder */ - { "MIGRATE", SYM(MIGRATE_SYM)}, - { "MINUTE", SYM(MINUTE_SYM)}, - { "MINUTE_MICROSECOND", SYM(MINUTE_MICROSECOND_SYM)}, - { "MINUTE_SECOND", SYM(MINUTE_SECOND_SYM)}, - { "MINVALUE", SYM(MINVALUE_SYM)}, - { "MIN_ROWS", SYM(MIN_ROWS)}, - { "MOD", SYM(MOD_SYM)}, - { "MODE", SYM(MODE_SYM)}, - { "MODIFIES", SYM(MODIFIES_SYM)}, - { "MODIFY", SYM(MODIFY_SYM)}, - { "MONITOR", SYM(MONITOR_SYM)}, - { "MONTH", SYM(MONTH_SYM)}, - { "MUTEX", SYM(MUTEX_SYM)}, - { "MYSQL", SYM(MYSQL_SYM)}, - { "MYSQL_ERRNO", SYM(MYSQL_ERRNO_SYM)}, - { "NAME", SYM(NAME_SYM)}, - { "NAMES", SYM(NAMES_SYM)}, - { "NATIONAL", SYM(NATIONAL_SYM)}, - { "NATURAL", SYM(NATURAL)}, - { "NCHAR", SYM(NCHAR_SYM)}, - { "NEVER", SYM(NEVER_SYM)}, - { "NEW", SYM(NEW_SYM)}, - { "NEXT", SYM(NEXT_SYM)}, - { "NEXTVAL", SYM(NEXTVAL_SYM)}, - { "NO", SYM(NO_SYM)}, - { "NOMAXVALUE", SYM(NOMAXVALUE_SYM)}, - { "NOMINVALUE", SYM(NOMINVALUE_SYM)}, - { "NOCACHE", SYM(NOCACHE_SYM)}, - { "NOCYCLE", SYM(NOCYCLE_SYM)}, - { "NO_WAIT", SYM(NO_WAIT_SYM)}, - { "NOWAIT", SYM(NOWAIT_SYM)}, - { "NODEGROUP", SYM(NODEGROUP_SYM)}, - { "NONE", SYM(NONE_SYM)}, - { "NOT", SYM(NOT_SYM)}, - { "NOTFOUND", SYM(NOTFOUND_SYM)}, - { "NO_WRITE_TO_BINLOG", SYM(NO_WRITE_TO_BINLOG)}, - { "NULL", SYM(NULL_SYM)}, - { "NUMBER", SYM(NUMBER_MARIADB_SYM)}, - { "NUMERIC", SYM(NUMERIC_SYM)}, - { "NVARCHAR", SYM(NVARCHAR_SYM)}, - { "OF", SYM(OF_SYM)}, - { "OFFSET", SYM(OFFSET_SYM)}, - { "OLD_PASSWORD", SYM(OLD_PASSWORD_SYM)}, - { "ON", SYM(ON)}, - { "ONE", SYM(ONE_SYM)}, - { "ONLINE", SYM(ONLINE_SYM)}, - { "ONLY", SYM(ONLY_SYM)}, - { "OPEN", SYM(OPEN_SYM)}, - { "OPTIMIZE", SYM(OPTIMIZE)}, - { "OPTIONS", SYM(OPTIONS_SYM)}, - { "OPTION", SYM(OPTION)}, - { "OPTIONALLY", SYM(OPTIONALLY)}, - { "OR", SYM(OR_SYM)}, - { "ORDER", SYM(ORDER_SYM)}, - { "OTHERS", SYM(OTHERS_MARIADB_SYM)}, - { "OUT", SYM(OUT_SYM)}, - { "OUTER", SYM(OUTER)}, - { "OUTFILE", SYM(OUTFILE)}, - { "OVER", SYM(OVER_SYM)}, - { "OVERLAPS", SYM(OVERLAPS_SYM)}, - { "OWNER", SYM(OWNER_SYM)}, - { "PACKAGE", SYM(PACKAGE_MARIADB_SYM)}, - { "PACK_KEYS", SYM(PACK_KEYS_SYM)}, - { "PAGE", SYM(PAGE_SYM)}, - { "PAGE_CHECKSUM", SYM(PAGE_CHECKSUM_SYM)}, - { "PARSER", SYM(PARSER_SYM)}, - { "PARSE_VCOL_EXPR", SYM(PARSE_VCOL_EXPR_SYM)}, - { "PERIOD", SYM(PERIOD_SYM)}, - { "PARTIAL", SYM(PARTIAL)}, - { "PARTITION", SYM(PARTITION_SYM)}, - { "PARTITIONING", SYM(PARTITIONING_SYM)}, - { "PARTITIONS", SYM(PARTITIONS_SYM)}, - { "PASSWORD", SYM(PASSWORD_SYM)}, - { "PERSISTENT", SYM(PERSISTENT_SYM)}, - { "PHASE", SYM(PHASE_SYM)}, - { "PLUGIN", SYM(PLUGIN_SYM)}, - { "PLUGINS", SYM(PLUGINS_SYM)}, - { "PORT", SYM(PORT_SYM)}, - { "PORTION", SYM(PORTION_SYM)}, - { "PRECEDES", SYM(PRECEDES_SYM)}, - { "PRECEDING", SYM(PRECEDING_SYM)}, - { "PRECISION", SYM(PRECISION)}, - { "PREPARE", SYM(PREPARE_SYM)}, - { "PRESERVE", SYM(PRESERVE_SYM)}, - { "PREV", SYM(PREV_SYM)}, - { "PREVIOUS", SYM(PREVIOUS_SYM)}, - { "PRIMARY", SYM(PRIMARY_SYM)}, - { "PRIVILEGES", SYM(PRIVILEGES)}, - { "PROCEDURE", SYM(PROCEDURE_SYM)}, - { "PROCESS" , SYM(PROCESS)}, - { "PROCESSLIST", SYM(PROCESSLIST_SYM)}, - { "PROFILE", SYM(PROFILE_SYM)}, - { "PROFILES", SYM(PROFILES_SYM)}, - { "PROXY", SYM(PROXY_SYM)}, - { "PURGE", SYM(PURGE)}, - { "QUARTER", SYM(QUARTER_SYM)}, - { "QUERY", SYM(QUERY_SYM)}, - { "QUICK", SYM(QUICK)}, - { "RAISE", SYM(RAISE_MARIADB_SYM)}, - { "RANGE", SYM(RANGE_SYM)}, - { "RAW", SYM(RAW_MARIADB_SYM)}, - { "READ", SYM(READ_SYM)}, - { "READ_ONLY", SYM(READ_ONLY_SYM)}, - { "READ_WRITE", SYM(READ_WRITE_SYM)}, - { "READS", SYM(READS_SYM)}, - { "REAL", SYM(REAL)}, - { "REBUILD", SYM(REBUILD_SYM)}, - { "RECOVER", SYM(RECOVER_SYM)}, - { "RECURSIVE", SYM(RECURSIVE_SYM)}, - { "REDO_BUFFER_SIZE", SYM(REDO_BUFFER_SIZE_SYM)}, - { "REDOFILE", SYM(REDOFILE_SYM)}, - { "REDUNDANT", SYM(REDUNDANT_SYM)}, - { "REFERENCES", SYM(REFERENCES)}, - { "REGEXP", SYM(REGEXP)}, - { "RELAY", SYM(RELAY)}, - { "RELAYLOG", SYM(RELAYLOG_SYM)}, - { "RELAY_LOG_FILE", SYM(RELAY_LOG_FILE_SYM)}, - { "RELAY_LOG_POS", SYM(RELAY_LOG_POS_SYM)}, - { "RELAY_THREAD", SYM(RELAY_THREAD)}, - { "RELEASE", SYM(RELEASE_SYM)}, - { "RELOAD", SYM(RELOAD)}, - { "REMOVE", SYM(REMOVE_SYM)}, - { "RENAME", SYM(RENAME)}, - { "REORGANIZE", SYM(REORGANIZE_SYM)}, - { "REPAIR", SYM(REPAIR)}, - { "REPEATABLE", SYM(REPEATABLE_SYM)}, - { "REPLACE", SYM(REPLACE)}, - { "REPLAY", SYM(REPLAY_SYM)}, - { "REPLICA", SYM(SLAVE)}, - { "REPLICAS", SYM(SLAVES)}, - { "REPLICA_POS", SYM(SLAVE_POS_SYM)}, - { "REPLICATION", SYM(REPLICATION)}, - { "REPEAT", SYM(REPEAT_SYM)}, - { "REQUIRE", SYM(REQUIRE_SYM)}, - { "RESET", SYM(RESET_SYM)}, - { "RESIGNAL", SYM(RESIGNAL_SYM)}, - { "RESTART", SYM(RESTART_SYM)}, - { "RESTORE", SYM(RESTORE_SYM)}, - { "RESTRICT", SYM(RESTRICT)}, - { "RESUME", SYM(RESUME_SYM)}, - { "RETURNED_SQLSTATE",SYM(RETURNED_SQLSTATE_SYM)}, - { "RETURN", SYM(RETURN_MARIADB_SYM)}, - { "RETURNING", SYM(RETURNING_SYM)}, - { "RETURNS", SYM(RETURNS_SYM)}, - { "REUSE", SYM(REUSE_SYM)}, - { "REVERSE", SYM(REVERSE_SYM)}, - { "REVOKE", SYM(REVOKE)}, - { "RIGHT", SYM(RIGHT)}, - { "RLIKE", SYM(REGEXP)}, /* Like in mSQL2 */ - { "ROLE", SYM(ROLE_SYM)}, - { "ROLLBACK", SYM(ROLLBACK_SYM)}, - { "ROLLUP", SYM(ROLLUP_SYM)}, - { "ROUTINE", SYM(ROUTINE_SYM)}, - { "ROW", SYM(ROW_SYM)}, - { "ROWCOUNT", SYM(ROWCOUNT_SYM)}, /* Oracle-N */ - { "ROWS", SYM(ROWS_SYM)}, - { "ROWTYPE", SYM(ROWTYPE_MARIADB_SYM)}, - { "ROW_COUNT", SYM(ROW_COUNT_SYM)}, - { "ROW_FORMAT", SYM(ROW_FORMAT_SYM)}, - { "RTREE", SYM(RTREE_SYM)}, - { "SAVEPOINT", SYM(SAVEPOINT_SYM)}, - { "SCHEDULE", SYM(SCHEDULE_SYM)}, - { "SCHEMA", SYM(DATABASE)}, - { "SCHEMA_NAME", SYM(SCHEMA_NAME_SYM)}, - { "SCHEMAS", SYM(DATABASES)}, - { "SECOND", SYM(SECOND_SYM)}, - { "SECOND_MICROSECOND", SYM(SECOND_MICROSECOND_SYM)}, - { "SECURITY", SYM(SECURITY_SYM)}, - { "SELECT", SYM(SELECT_SYM)}, - { "SENSITIVE", SYM(SENSITIVE_SYM)}, - { "SEPARATOR", SYM(SEPARATOR_SYM)}, - { "SEQUENCE", SYM(SEQUENCE_SYM)}, - { "SERIAL", SYM(SERIAL_SYM)}, - { "SERIALIZABLE", SYM(SERIALIZABLE_SYM)}, - { "SESSION", SYM(SESSION_SYM)}, - { "SERVER", SYM(SERVER_SYM)}, - { "SET", SYM(SET)}, - { "SETVAL", SYM(SETVAL_SYM)}, - { "SHARE", SYM(SHARE_SYM)}, - { "SHOW", SYM(SHOW)}, - { "SHUTDOWN", SYM(SHUTDOWN)}, - { "SIGNAL", SYM(SIGNAL_SYM)}, - { "SIGNED", SYM(SIGNED_SYM)}, - { "SIMPLE", SYM(SIMPLE_SYM)}, - { "SLAVE", SYM(SLAVE)}, - { "SLAVES", SYM(SLAVES)}, - { "SLAVE_POS", SYM(SLAVE_POS_SYM)}, - { "SLOW", SYM(SLOW)}, - { "SNAPSHOT", SYM(SNAPSHOT_SYM)}, - { "SMALLINT", SYM(SMALLINT)}, - { "SOCKET", SYM(SOCKET_SYM)}, - { "SOFT", SYM(SOFT_SYM)}, - { "SOME", SYM(ANY_SYM)}, - { "SONAME", SYM(SONAME_SYM)}, - { "SOUNDS", SYM(SOUNDS_SYM)}, - { "SOURCE", SYM(SOURCE_SYM)}, - { "STAGE", SYM(STAGE_SYM)}, - { "STORED", SYM(STORED_SYM)}, - { "SPATIAL", SYM(SPATIAL_SYM)}, - { "SPECIFIC", SYM(SPECIFIC_SYM)}, - { "REF_SYSTEM_ID", SYM(REF_SYSTEM_ID_SYM)}, - { "SQL", SYM(SQL_SYM)}, - { "SQLEXCEPTION", SYM(SQLEXCEPTION_SYM)}, - { "SQLSTATE", SYM(SQLSTATE_SYM)}, - { "SQLWARNING", SYM(SQLWARNING_SYM)}, - { "SQL_BIG_RESULT", SYM(SQL_BIG_RESULT)}, - { "SQL_BUFFER_RESULT", SYM(SQL_BUFFER_RESULT)}, - { "SQL_CACHE", SYM(SQL_CACHE_SYM)}, - { "SQL_CALC_FOUND_ROWS", SYM(SQL_CALC_FOUND_ROWS)}, - { "SQL_NO_CACHE", SYM(SQL_NO_CACHE_SYM)}, - { "SQL_SMALL_RESULT", SYM(SQL_SMALL_RESULT)}, - { "SQL_THREAD", SYM(SQL_THREAD)}, - { "SQL_TSI_SECOND", SYM(SECOND_SYM)}, - { "SQL_TSI_MINUTE", SYM(MINUTE_SYM)}, - { "SQL_TSI_HOUR", SYM(HOUR_SYM)}, - { "SQL_TSI_DAY", SYM(DAY_SYM)}, - { "SQL_TSI_WEEK", SYM(WEEK_SYM)}, - { "SQL_TSI_MONTH", SYM(MONTH_SYM)}, - { "SQL_TSI_QUARTER", SYM(QUARTER_SYM)}, - { "SQL_TSI_YEAR", SYM(YEAR_SYM)}, - { "SSL", SYM(SSL_SYM)}, - { "START", SYM(START_SYM)}, - { "STARTING", SYM(STARTING)}, - { "STARTS", SYM(STARTS_SYM)}, - { "STATEMENT", SYM(STATEMENT_SYM)}, - { "STATS_AUTO_RECALC",SYM(STATS_AUTO_RECALC_SYM)}, - { "STATS_PERSISTENT", SYM(STATS_PERSISTENT_SYM)}, - { "STATS_SAMPLE_PAGES",SYM(STATS_SAMPLE_PAGES_SYM)}, - { "STATUS", SYM(STATUS_SYM)}, - { "STOP", SYM(STOP_SYM)}, - { "STORAGE", SYM(STORAGE_SYM)}, - { "STRAIGHT_JOIN", SYM(STRAIGHT_JOIN)}, - { "STRING", SYM(STRING_SYM)}, - { "SUBCLASS_ORIGIN", SYM(SUBCLASS_ORIGIN_SYM)}, - { "SUBJECT", SYM(SUBJECT_SYM)}, - { "SUBPARTITION", SYM(SUBPARTITION_SYM)}, - { "SUBPARTITIONS", SYM(SUBPARTITIONS_SYM)}, - { "SUPER", SYM(SUPER_SYM)}, - { "SUSPEND", SYM(SUSPEND_SYM)}, - { "SWAPS", SYM(SWAPS_SYM)}, - { "SWITCHES", SYM(SWITCHES_SYM)}, - { "SYSTEM", SYM(SYSTEM)}, - { "SYSTEM_TIME", SYM(SYSTEM_TIME_SYM)}, - { "TABLE", SYM(TABLE_SYM)}, - { "TABLE_NAME", SYM(TABLE_NAME_SYM)}, - { "TABLES", SYM(TABLES)}, - { "TABLESPACE", SYM(TABLESPACE)}, - { "TABLE_CHECKSUM", SYM(TABLE_CHECKSUM_SYM)}, - { "TEMPORARY", SYM(TEMPORARY)}, - { "TEMPTABLE", SYM(TEMPTABLE_SYM)}, - { "TERMINATED", SYM(TERMINATED)}, - { "TEXT", SYM(TEXT_SYM)}, - { "THAN", SYM(THAN_SYM)}, - { "THEN", SYM(THEN_SYM)}, - { "TIES", SYM(TIES_SYM)}, - { "TIME", SYM(TIME_SYM)}, - { "TIMESTAMP", SYM(TIMESTAMP)}, - { "TIMESTAMPADD", SYM(TIMESTAMP_ADD)}, - { "TIMESTAMPDIFF", SYM(TIMESTAMP_DIFF)}, - { "TINYBLOB", SYM(TINYBLOB)}, - { "TINYINT", SYM(TINYINT)}, - { "TINYTEXT", SYM(TINYTEXT)}, - { "TO", SYM(TO_SYM)}, - { "TRAILING", SYM(TRAILING)}, - { "TRANSACTION", SYM(TRANSACTION_SYM)}, - { "TRANSACTIONAL", SYM(TRANSACTIONAL_SYM)}, - { "THREADS", SYM(THREADS_SYM)}, - { "TRIGGER", SYM(TRIGGER_SYM)}, - { "TRIGGERS", SYM(TRIGGERS_SYM)}, - { "TRUE", SYM(TRUE_SYM)}, - { "TRUNCATE", SYM(TRUNCATE_SYM)}, - { "TYPE", SYM(TYPE_SYM)}, - { "TYPES", SYM(TYPES_SYM)}, - { "UNBOUNDED", SYM(UNBOUNDED_SYM)}, - { "UNCOMMITTED", SYM(UNCOMMITTED_SYM)}, - { "UNDEFINED", SYM(UNDEFINED_SYM)}, - { "UNDO_BUFFER_SIZE", SYM(UNDO_BUFFER_SIZE_SYM)}, - { "UNDOFILE", SYM(UNDOFILE_SYM)}, - { "UNDO", SYM(UNDO_SYM)}, - { "UNICODE", SYM(UNICODE_SYM)}, - { "UNION", SYM(UNION_SYM)}, - { "UNIQUE", SYM(UNIQUE_SYM)}, - { "UNKNOWN", SYM(UNKNOWN_SYM)}, - { "UNLOCK", SYM(UNLOCK_SYM)}, - { "UNINSTALL", SYM(UNINSTALL_SYM)}, - { "UNSIGNED", SYM(UNSIGNED)}, - { "UNTIL", SYM(UNTIL_SYM)}, - { "UPDATE", SYM(UPDATE_SYM)}, - { "UPGRADE", SYM(UPGRADE_SYM)}, - { "USAGE", SYM(USAGE)}, - { "USE", SYM(USE_SYM)}, - { "USER", SYM(USER_SYM)}, - { "USER_RESOURCES", SYM(RESOURCES)}, - { "USE_FRM", SYM(USE_FRM)}, - { "USING", SYM(USING)}, - { "UTC_DATE", SYM(UTC_DATE_SYM)}, - { "UTC_TIME", SYM(UTC_TIME_SYM)}, - { "UTC_TIMESTAMP", SYM(UTC_TIMESTAMP_SYM)}, - { "VALUE", SYM(VALUE_SYM)}, - { "VALUES", SYM(VALUES)}, - { "VARBINARY", SYM(VARBINARY)}, - { "VARCHAR", SYM(VARCHAR)}, - { "VARCHARACTER", SYM(VARCHAR)}, - { "VARCHAR2", SYM(VARCHAR2_MARIADB_SYM)}, - { "VARIABLES", SYM(VARIABLES)}, - { "VARYING", SYM(VARYING)}, - { "VIA", SYM(VIA_SYM)}, - { "VIEW", SYM(VIEW_SYM)}, - { "VIRTUAL", SYM(VIRTUAL_SYM)}, - { "VISIBLE", SYM(VISIBLE_SYM)}, - { "VERSIONING", SYM(VERSIONING_SYM)}, - { "WAIT", SYM(WAIT_SYM)}, - { "WARNINGS", SYM(WARNINGS)}, - { "WEEK", SYM(WEEK_SYM)}, - { "WEIGHT_STRING", SYM(WEIGHT_STRING_SYM)}, - { "WHEN", SYM(WHEN_SYM)}, - { "WHERE", SYM(WHERE)}, - { "WHILE", SYM(WHILE_SYM)}, - { "WINDOW", SYM(WINDOW_SYM)}, - { "WITH", SYM(WITH)}, - { "WITHIN", SYM(WITHIN)}, - { "WITHOUT", SYM(WITHOUT)}, - { "WORK", SYM(WORK_SYM)}, - { "WRAPPER", SYM(WRAPPER_SYM)}, - { "WRITE", SYM(WRITE_SYM)}, - { "X509", SYM(X509_SYM)}, - { "XOR", SYM(XOR)}, - { "XA", SYM(XA_SYM)}, - { "XML", SYM(XML_SYM)}, /* LOAD XML Arnold/Erik */ - { "YEAR", SYM(YEAR_SYM)}, - { "YEAR_MONTH", SYM(YEAR_MONTH_SYM)}, - { "ZEROFILL", SYM(ZEROFILL)}, - { "||", SYM(OR2_SYM)} -}; - - -static SYMBOL sql_functions[] = { - { "ADDDATE", SYM(ADDDATE_SYM)}, - { "BIT_AND", SYM(BIT_AND)}, - { "BIT_OR", SYM(BIT_OR)}, - { "BIT_XOR", SYM(BIT_XOR)}, - { "CAST", SYM(CAST_SYM)}, - { "COUNT", SYM(COUNT_SYM)}, - { "CUME_DIST", SYM(CUME_DIST_SYM)}, - { "CURDATE", SYM(CURDATE)}, - { "CURTIME", SYM(CURTIME)}, - { "DATE_ADD", SYM(DATE_ADD_INTERVAL)}, - { "DATE_SUB", SYM(DATE_SUB_INTERVAL)}, - { "DATE_FORMAT", SYM(DATE_FORMAT_SYM)}, - { "DECODE", SYM(DECODE_MARIADB_SYM)}, - { "DENSE_RANK", SYM(DENSE_RANK_SYM)}, - { "EXTRACT", SYM(EXTRACT_SYM)}, - { "FIRST_VALUE", SYM(FIRST_VALUE_SYM)}, - { "GROUP_CONCAT", SYM(GROUP_CONCAT_SYM)}, - { "JSON_ARRAYAGG", SYM(JSON_ARRAYAGG_SYM)}, - { "JSON_OBJECTAGG", SYM(JSON_OBJECTAGG_SYM)}, - { "LAG", SYM(LAG_SYM)}, - { "LEAD", SYM(LEAD_SYM)}, - { "MAX", SYM(MAX_SYM)}, - { "MEDIAN", SYM(MEDIAN_SYM)}, - { "MID", SYM(SUBSTRING)}, /* unireg function */ - { "MIN", SYM(MIN_SYM)}, - { "NOW", SYM(NOW_SYM)}, - { "NTH_VALUE", SYM(NTH_VALUE_SYM)}, - { "NTILE", SYM(NTILE_SYM)}, - { "POSITION", SYM(POSITION_SYM)}, - { "PERCENT_RANK", SYM(PERCENT_RANK_SYM)}, - { "PERCENTILE_CONT", SYM(PERCENTILE_CONT_SYM)}, - { "PERCENTILE_DISC", SYM(PERCENTILE_DISC_SYM)}, - { "RANK", SYM(RANK_SYM)}, - { "ROW_NUMBER", SYM(ROW_NUMBER_SYM)}, - { "SESSION_USER", SYM(USER_SYM)}, - { "STD", SYM(STD_SYM)}, - { "STDDEV", SYM(STD_SYM)}, - { "STDDEV_POP", SYM(STD_SYM)}, - { "STDDEV_SAMP", SYM(STDDEV_SAMP_SYM)}, - { "SUBDATE", SYM(SUBDATE_SYM)}, - { "SUBSTR", SYM(SUBSTRING)}, - { "SUBSTRING", SYM(SUBSTRING)}, - { "SUM", SYM(SUM_SYM)}, - { "SYSDATE", SYM(SYSDATE)}, - { "SYSTEM_USER", SYM(USER_SYM)}, - { "TRIM", SYM(TRIM)}, - { "TRIM_ORACLE", SYM(TRIM_ORACLE)}, - { "VARIANCE", SYM(VARIANCE_SYM)}, - { "VAR_POP", SYM(VARIANCE_SYM)}, - { "VAR_SAMP", SYM(VAR_SAMP_SYM)}, -}; - -#endif /* LEX_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex_string.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex_string.h deleted file mode 100644 index 008e5f7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex_string.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - Copyright (c) 2018, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - -#ifndef LEX_STRING_INCLUDED -#define LEX_STRING_INCLUDED - - -typedef struct st_mysql_const_lex_string LEX_CSTRING; - - -class Lex_cstring : public LEX_CSTRING -{ - public: - Lex_cstring() - { - str= NULL; - length= 0; - } - Lex_cstring(const LEX_CSTRING &str) - { - LEX_CSTRING::operator=(str); - } - Lex_cstring(const char *_str, size_t _len) - { - str= _str; - length= _len; - } - Lex_cstring(const char *start, const char *end) - { - DBUG_ASSERT(start <= end); - str= start; - length= end - start; - } - void set(const char *_str, size_t _len) - { - str= _str; - length= _len; - } -}; - - -class Lex_cstring_strlen: public Lex_cstring -{ -public: - Lex_cstring_strlen(const char *from) - :Lex_cstring(from, from ? strlen(from) : 0) - { } -}; - - -/* Functions to compare if two lex strings are equal */ - -static inline bool lex_string_cmp(CHARSET_INFO *charset, const LEX_CSTRING *a, - const LEX_CSTRING *b) -{ - return my_strcasecmp(charset, a->str, b->str); -} - -/* - Compare to LEX_CSTRING's and return 0 if equal -*/ - -static inline bool cmp(const LEX_CSTRING *a, const LEX_CSTRING *b) -{ - return (a->length != b->length || - memcmp(a->str, b->str, a->length)); -} -static inline bool cmp(const LEX_CSTRING a, const LEX_CSTRING b) -{ - return a.length != b.length || memcmp(a.str, b.str, a.length); -} - -/* - Compare if two LEX_CSTRING are equal. Assumption is that - character set is ASCII (like for plugin names) -*/ - -static inline bool lex_string_eq(const LEX_CSTRING *a, const LEX_CSTRING *b) -{ - if (a->length != b->length) - return 0; /* Different */ - return strcasecmp(a->str, b->str) == 0; -} - -/* - To be used when calling lex_string_eq with STRING_WITH_LEN() as second - argument -*/ - -static inline bool lex_string_eq(const LEX_CSTRING *a, const char *b, size_t b_length) -{ - if (a->length != b_length) - return 0; /* Different */ - return strcasecmp(a->str, b) == 0; -} - -#endif /* LEX_STRING_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex_symbol.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex_symbol.h deleted file mode 100644 index e7819cd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lex_symbol.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (c) 2000, 2001, 2004, 2006, 2007 MySQL AB - Use is subject to license terms - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* This struct includes all reserved words and functions */ - -#ifndef _lex_symbol_h -#define _lex_symbol_h - -struct st_sym_group; - -typedef struct st_symbol { - const char *name; - uint tok; - uint length; - struct st_sym_group *group; -} SYMBOL; - -typedef struct st_lex_symbol -{ - SYMBOL *symbol; - char *str; - uint length; -} LEX_SYMBOL; - -typedef struct st_sym_group { - const char *name; - const char *needed_define; -} SYM_GROUP; - -extern SYM_GROUP sym_group_common; -extern SYM_GROUP sym_group_geom; -extern SYM_GROUP sym_group_rtree; - -#endif /* _lex_symbol_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lf.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/lf.h deleted file mode 100644 index 88ac644..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lf.h +++ /dev/null @@ -1,184 +0,0 @@ -/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef INCLUDE_LF_INCLUDED -#define INCLUDE_LF_INCLUDED - -#include - -C_MODE_START - -/* - wait-free dynamic array, see lf_dynarray.c - - 4 levels of 256 elements each mean 4311810304 elements in an array - it - should be enough for a while -*/ -#define LF_DYNARRAY_LEVEL_LENGTH 256 -#define LF_DYNARRAY_LEVELS 4 - -typedef struct { - void * volatile level[LF_DYNARRAY_LEVELS]; - uint size_of_element; -} LF_DYNARRAY; - -typedef int (*lf_dynarray_func)(void *, void *); - -void lf_dynarray_init(LF_DYNARRAY *array, uint element_size); -void lf_dynarray_destroy(LF_DYNARRAY *array); - -void *lf_dynarray_value(LF_DYNARRAY *array, uint idx); -void *lf_dynarray_lvalue(LF_DYNARRAY *array, uint idx); -int lf_dynarray_iterate(LF_DYNARRAY *array, lf_dynarray_func func, void *arg); - -/* - pin manager for memory allocator, lf_alloc-pin.c -*/ - -#define LF_PINBOX_PINS 4 -#define LF_PURGATORY_SIZE 100 - -typedef void lf_pinbox_free_func(void *, void *, void*); - -typedef struct { - LF_DYNARRAY pinarray; - lf_pinbox_free_func *free_func; - void *free_func_arg; - uint free_ptr_offset; - uint32 volatile pinstack_top_ver; /* this is a versioned pointer */ - uint32 volatile pins_in_array; /* number of elements in array */ -} LF_PINBOX; - -typedef struct { - void * volatile pin[LF_PINBOX_PINS]; - LF_PINBOX *pinbox; - void *purgatory; - uint32 purgatory_count; - uint32 volatile link; - /* avoid false sharing */ - char pad[CPU_LEVEL1_DCACHE_LINESIZE]; -} LF_PINS; - -/* compile-time assert to make sure we have enough pins. */ -#define lf_pin(PINS, PIN, ADDR) \ - do { \ - compile_time_assert(PIN < LF_PINBOX_PINS); \ - my_atomic_storeptr(&(PINS)->pin[PIN], (ADDR)); \ - } while(0) - -#define lf_unpin(PINS, PIN) lf_pin(PINS, PIN, NULL) -#define lf_assert_pin(PINS, PIN) assert((PINS)->pin[PIN] != 0) -#define lf_assert_unpin(PINS, PIN) assert((PINS)->pin[PIN] == 0) - -void lf_pinbox_init(LF_PINBOX *pinbox, uint free_ptr_offset, - lf_pinbox_free_func *free_func, void * free_func_arg); -void lf_pinbox_destroy(LF_PINBOX *pinbox); - -LF_PINS *lf_pinbox_get_pins(LF_PINBOX *pinbox); -void lf_pinbox_put_pins(LF_PINS *pins); -void lf_pinbox_free(LF_PINS *pins, void *addr); - -/* - memory allocator, lf_alloc-pin.c -*/ - -typedef struct st_lf_allocator { - LF_PINBOX pinbox; - uchar * volatile top; - uint element_size; - uint32 volatile mallocs; - void (*constructor)(uchar *); /* called, when an object is malloc()'ed */ - void (*destructor)(uchar *); /* called, when an object is free()'d */ -} LF_ALLOCATOR; - -void lf_alloc_init(LF_ALLOCATOR *allocator, uint size, uint free_ptr_offset); -void lf_alloc_destroy(LF_ALLOCATOR *allocator); -uint lf_alloc_pool_count(LF_ALLOCATOR *allocator); -/* - shortcut macros to access underlying pinbox functions from an LF_ALLOCATOR - see lf_pinbox_get_pins() and lf_pinbox_put_pins() -*/ -#define lf_alloc_free(PINS, PTR) lf_pinbox_free((PINS), (PTR)) -#define lf_alloc_get_pins(A) lf_pinbox_get_pins(&(A)->pinbox) -#define lf_alloc_put_pins(PINS) lf_pinbox_put_pins(PINS) -#define lf_alloc_direct_free(ALLOC, ADDR) \ - do { \ - if ((ALLOC)->destructor) \ - (ALLOC)->destructor((uchar*) ADDR); \ - my_free(ADDR); \ - } while(0) - -void *lf_alloc_new(LF_PINS *pins); - -C_MODE_END - -/* - extendible hash, lf_hash.c -*/ -#include - -C_MODE_START - -typedef struct st_lf_hash LF_HASH; -typedef void (*lf_hash_initializer)(LF_HASH *hash, void *dst, const void *src); - -#define LF_HASH_UNIQUE 1 - -/* lf_hash overhead per element (that is, sizeof(LF_SLIST) */ -extern const int LF_HASH_OVERHEAD; - -struct st_lf_hash { - LF_DYNARRAY array; /* hash itself */ - LF_ALLOCATOR alloc; /* allocator for elements */ - my_hash_get_key get_key; /* see HASH */ - lf_hash_initializer initializer; /* called when an element is inserted */ - my_hash_function hash_function; /* see HASH */ - CHARSET_INFO *charset; /* see HASH */ - uint key_offset, key_length; /* see HASH */ - uint element_size; /* size of memcpy'ed area on insert */ - uint flags; /* LF_HASH_UNIQUE, etc */ - int32 volatile size; /* size of array */ - int32 volatile count; /* number of elements in the hash */ -}; - -void lf_hash_init(LF_HASH *hash, uint element_size, uint flags, - uint key_offset, uint key_length, my_hash_get_key get_key, - CHARSET_INFO *charset); -void lf_hash_destroy(LF_HASH *hash); -int lf_hash_insert(LF_HASH *hash, LF_PINS *pins, const void *data); -void *lf_hash_search(LF_HASH *hash, LF_PINS *pins, const void *key, uint keylen); -void *lf_hash_search_using_hash_value(LF_HASH *hash, LF_PINS *pins, - my_hash_value_type hash_value, - const void *key, uint keylen); -int lf_hash_delete(LF_HASH *hash, LF_PINS *pins, const void *key, uint keylen); -int lf_hash_iterate(LF_HASH *hash, LF_PINS *pins, - my_hash_walk_action action, void *argument); -#define lf_hash_size(hash) \ - my_atomic_load32_explicit(&(hash)->count, MY_MEMORY_ORDER_RELAXED) -/* - shortcut macros to access underlying pinbox functions from an LF_HASH - see lf_pinbox_get_pins() and lf_pinbox_put_pins() -*/ -#define lf_hash_get_pins(HASH) lf_alloc_get_pins(&(HASH)->alloc) -#define lf_hash_put_pins(PINS) lf_pinbox_put_pins(PINS) -#define lf_hash_search_unpin(PINS) lf_unpin((PINS), 2) -/* - cleanup -*/ - -C_MODE_END - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lock.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/lock.h deleted file mode 100644 index 0b23ddd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/lock.h +++ /dev/null @@ -1,54 +0,0 @@ -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef LOCK_INCLUDED -#define LOCK_INCLUDED - -#include "thr_lock.h" /* thr_lock_type */ -#include "mdl.h" - -// Forward declarations -struct TABLE; -struct TABLE_LIST; -class THD; -typedef struct st_mysql_lock MYSQL_LOCK; - - -MYSQL_LOCK *mysql_lock_tables(THD *thd, TABLE **table, uint count, uint flags); -bool mysql_lock_tables(THD *thd, MYSQL_LOCK *sql_lock, uint flags); -int mysql_unlock_tables(THD *thd, MYSQL_LOCK *sql_lock, bool free_lock); -int mysql_unlock_tables(THD *thd, MYSQL_LOCK *sql_lock); -int mysql_unlock_read_tables(THD *thd, MYSQL_LOCK *sql_lock); -int mysql_unlock_some_tables(THD *thd, TABLE **table,uint count, uint flag); -int mysql_lock_remove(THD *thd, MYSQL_LOCK *locked,TABLE *table); -bool mysql_lock_abort_for_thread(THD *thd, TABLE *table); -MYSQL_LOCK *mysql_lock_merge(MYSQL_LOCK *a,MYSQL_LOCK *b); -/* Lock based on name */ -bool lock_schema_name(THD *thd, const char *db); -/* Lock based on stored routine name */ -bool lock_object_name(THD *thd, MDL_key::enum_mdl_namespace mdl_type, - const char *db, const char *name); - -/* flags for get_lock_data */ -#define GET_LOCK_UNLOCK 0 -#define GET_LOCK_STORE_LOCKS 1 -#define GET_LOCK_ACTION_MASK 1 -#define GET_LOCK_ON_THD (1 << 1) -#define GET_LOCK_SKIP_SEQUENCES (1 << 2) - -MYSQL_LOCK *get_lock_data(THD *thd, TABLE **table_ptr, uint count, uint flags); -void reset_lock_data(MYSQL_LOCK *sql_lock, bool unlock); - -#endif /* LOCK_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/log.h deleted file mode 100644 index 58e6819..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log.h +++ /dev/null @@ -1,1240 +0,0 @@ -/* Copyright (c) 2005, 2016, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef LOG_H -#define LOG_H - -#include "handler.h" /* my_xid */ -#include "wsrep_mysqld.h" -#include "rpl_constants.h" - -class Relay_log_info; - -class Format_description_log_event; - -bool reopen_fstreams(const char *filename, FILE *outstream, FILE *errstream); -void setup_log_handling(); -bool trans_has_updated_trans_table(const THD* thd); -bool stmt_has_updated_trans_table(const THD *thd); -bool use_trans_cache(const THD* thd, bool is_transactional); -bool ending_trans(THD* thd, const bool all); -bool ending_single_stmt_trans(THD* thd, const bool all); -bool trans_has_updated_non_trans_table(const THD* thd); -bool stmt_has_updated_non_trans_table(const THD* thd); - -/* - Transaction Coordinator log - a base abstract class - for two different implementations -*/ -class TC_LOG -{ - public: - int using_heuristic_recover(); - TC_LOG() {} - virtual ~TC_LOG() {} - - virtual int open(const char *opt_name)=0; - virtual void close()=0; - /* - Transaction coordinator 2-phase commit. - - Must invoke the run_prepare_ordered and run_commit_ordered methods, as - described below for these methods. - - In addition, must invoke THD::wait_for_prior_commit(), or equivalent - wait, to ensure that one commit waits for another if registered to do so. - */ - virtual int log_and_order(THD *thd, my_xid xid, bool all, - bool need_prepare_ordered, - bool need_commit_ordered) = 0; - virtual int unlog(ulong cookie, my_xid xid)=0; - virtual int unlog_xa_prepare(THD *thd, bool all)= 0; - virtual void commit_checkpoint_notify(void *cookie)= 0; - -protected: - /* - These methods are meant to be invoked from log_and_order() implementations - to run any prepare_ordered() respectively commit_ordered() methods in - participating handlers. - - They must be called using suitable thread syncronisation to ensure that - they are each called in the correct commit order among all - transactions. However, it is only necessary to call them if the - corresponding flag passed to log_and_order is set (it is safe, but not - required, to call them when the flag is false). - - The caller must be holding LOCK_prepare_ordered respectively - LOCK_commit_ordered when calling these methods. - */ - void run_prepare_ordered(THD *thd, bool all); - void run_commit_ordered(THD *thd, bool all); -}; - -/* - Locks used to ensure serialised execution of TC_LOG::run_prepare_ordered() - and TC_LOG::run_commit_ordered(), or any other code that calls handler - prepare_ordered() or commit_ordered() methods. -*/ -extern mysql_mutex_t LOCK_prepare_ordered; -extern mysql_cond_t COND_prepare_ordered; -extern mysql_mutex_t LOCK_after_binlog_sync; -extern mysql_mutex_t LOCK_commit_ordered; -#ifdef HAVE_PSI_INTERFACE -extern PSI_mutex_key key_LOCK_prepare_ordered, key_LOCK_commit_ordered; -extern PSI_mutex_key key_LOCK_after_binlog_sync; -extern PSI_cond_key key_COND_prepare_ordered; -#endif - -class TC_LOG_DUMMY: public TC_LOG // use it to disable the logging -{ -public: - TC_LOG_DUMMY() {} - int open(const char *opt_name) { return 0; } - void close() { } - /* - TC_LOG_DUMMY is only used when there are <= 1 XA-capable engines, and we - only use internal XA during commit when >= 2 XA-capable engines - participate. - */ - int log_and_order(THD *thd, my_xid xid, bool all, - bool need_prepare_ordered, bool need_commit_ordered) - { - DBUG_ASSERT(0); - return 1; - } - int unlog(ulong cookie, my_xid xid) { return 0; } - int unlog_xa_prepare(THD *thd, bool all) - { - return 0; - } - void commit_checkpoint_notify(void *cookie) { DBUG_ASSERT(0); }; -}; - -#define TC_LOG_PAGE_SIZE 8192 - -#ifdef HAVE_MMAP -class TC_LOG_MMAP: public TC_LOG -{ - public: // only to keep Sun Forte on sol9x86 happy - typedef enum { - PS_POOL, // page is in pool - PS_ERROR, // last sync failed - PS_DIRTY // new xids added since last sync - } PAGE_STATE; - - struct pending_cookies { - uint count; - uint pending_count; - ulong cookies[1]; - }; - - private: - typedef struct st_page { - struct st_page *next; // page a linked in a fifo queue - my_xid *start, *end; // usable area of a page - my_xid *ptr; // next xid will be written here - int size, free; // max and current number of free xid slots on the page - int waiters; // number of waiters on condition - PAGE_STATE state; // see above - mysql_mutex_t lock; // to access page data or control structure - mysql_cond_t cond; // to wait for a sync - } PAGE; - - /* List of THDs for which to invoke commit_ordered(), in order. */ - struct commit_entry - { - struct commit_entry *next; - THD *thd; - }; - - char logname[FN_REFLEN]; - File fd; - my_off_t file_length; - uint npages, inited; - uchar *data; - struct st_page *pages, *syncing, *active, *pool, **pool_last_ptr; - /* - note that, e.g. LOCK_active is only used to protect - 'active' pointer, to protect the content of the active page - one has to use active->lock. - Same for LOCK_pool and LOCK_sync - */ - mysql_mutex_t LOCK_active, LOCK_pool, LOCK_sync, LOCK_pending_checkpoint; - mysql_cond_t COND_pool, COND_active; - /* - Queue of threads that need to call commit_ordered(). - Access to this queue must be protected by LOCK_prepare_ordered. - */ - commit_entry *commit_ordered_queue; - /* - This flag and condition is used to reserve the queue while threads in it - each run the commit_ordered() methods one after the other. Only once the - last commit_ordered() in the queue is done can we start on a new queue - run. - - Since we start this process in the first thread in the queue and finish in - the last (and possibly different) thread, we need a condition variable for - this (we cannot unlock a mutex in a different thread than the one who - locked it). - - The condition is used together with the LOCK_prepare_ordered mutex. - */ - mysql_cond_t COND_queue_busy; - my_bool commit_ordered_queue_busy; - pending_cookies* pending_checkpoint; - - public: - TC_LOG_MMAP(): inited(0), pending_checkpoint(0) {} - int open(const char *opt_name); - void close(); - int log_and_order(THD *thd, my_xid xid, bool all, - bool need_prepare_ordered, bool need_commit_ordered); - int unlog(ulong cookie, my_xid xid); - int unlog_xa_prepare(THD *thd, bool all) - { - return 0; - } - void commit_checkpoint_notify(void *cookie); - int recover(); - - private: - int log_one_transaction(my_xid xid); - void get_active_from_pool(); - int sync(); - int overflow(); - int delete_entry(ulong cookie); -}; -#else -#define TC_LOG_MMAP TC_LOG_DUMMY -#endif - -extern TC_LOG *tc_log; -extern TC_LOG_MMAP tc_log_mmap; -extern TC_LOG_DUMMY tc_log_dummy; - -/* log info errors */ -#define LOG_INFO_EOF -1 -#define LOG_INFO_IO -2 -#define LOG_INFO_INVALID -3 -#define LOG_INFO_SEEK -4 -#define LOG_INFO_MEM -6 -#define LOG_INFO_FATAL -7 -#define LOG_INFO_IN_USE -8 -#define LOG_INFO_EMFILE -9 - - -/* bitmap to SQL_LOG::close() */ -#define LOG_CLOSE_INDEX 1 -#define LOG_CLOSE_TO_BE_OPENED 2 -#define LOG_CLOSE_STOP_EVENT 4 -#define LOG_CLOSE_DELAYED_CLOSE 8 - -/* - Maximum unique log filename extension. - Note: setting to 0x7FFFFFFF due to atol windows - overflow/truncate. - */ -#define MAX_LOG_UNIQUE_FN_EXT 0x7FFFFFFF - -/* - Number of warnings that will be printed to error log - before extension number is exhausted. -*/ -#define LOG_WARN_UNIQUE_FN_EXT_LEFT 1000 - -class Relay_log_info; - -/* - Note that we destroy the lock mutex in the desctructor here. - This means that object instances cannot be destroyed/go out of scope, - until we have reset thd->current_linfo to NULL; - */ -typedef struct st_log_info -{ - char log_file_name[FN_REFLEN]; - my_off_t index_file_offset, index_file_start_offset; - my_off_t pos; - bool fatal; // if the purge happens to give us a negative offset - st_log_info() : index_file_offset(0), index_file_start_offset(0), - pos(0), fatal(0) - { - DBUG_ENTER("LOG_INFO"); - log_file_name[0] = '\0'; - DBUG_VOID_RETURN; - } -} LOG_INFO; - -/* - Currently we have only 3 kinds of logging functions: old-fashioned - logs, stdout and csv logging routines. -*/ -#define MAX_LOG_HANDLERS_NUM 3 - -/* log event handler flags */ -#define LOG_NONE 1U -#define LOG_FILE 2U -#define LOG_TABLE 4U - -class Log_event; -class Rows_log_event; - -enum enum_log_type { LOG_UNKNOWN, LOG_NORMAL, LOG_BIN }; -enum enum_log_state { LOG_OPENED, LOG_CLOSED, LOG_TO_BE_OPENED }; - -/* - Use larger buffers when reading from and to binary log - We make it one step smaller than 64K to account for malloc overhead. -*/ -#define LOG_BIN_IO_SIZE MY_ALIGN_DOWN(65536-1, IO_SIZE) - -/* - TODO use mmap instead of IO_CACHE for binlog - (mmap+fsync is two times faster than write+fsync) -*/ - -class MYSQL_LOG -{ -public: - MYSQL_LOG(); - virtual ~MYSQL_LOG() {} - void init_pthread_objects(); - void cleanup(); - bool open( -#ifdef HAVE_PSI_INTERFACE - PSI_file_key log_file_key, -#endif - const char *log_name, - enum_log_type log_type, - const char *new_name, ulong next_file_number, - enum cache_type io_cache_type_arg); - void close(uint exiting); - inline bool is_open() { return log_state != LOG_CLOSED; } - const char *generate_name(const char *log_name, - const char *suffix, - bool strip_ext, char *buff); - virtual int generate_new_name(char *new_name, const char *log_name, - ulong next_log_number); - protected: - /* LOCK_log is inited by init_pthread_objects() */ - mysql_mutex_t LOCK_log; - char *name; - char log_file_name[FN_REFLEN]; - char time_buff[20], db[NAME_LEN + 1]; - bool write_error, inited; - IO_CACHE log_file; - enum_log_type log_type; - volatile enum_log_state log_state; - enum cache_type io_cache_type; - friend class Log_event; -#ifdef HAVE_PSI_INTERFACE - /** Instrumentation key to use for file io in @c log_file */ - PSI_file_key m_log_file_key; -#endif - - bool init_and_set_log_file_name(const char *log_name, - const char *new_name, - ulong next_log_number, - enum_log_type log_type_arg, - enum cache_type io_cache_type_arg); -}; - -/* Tell the io thread if we can delay the master info sync. */ -#define SEMI_SYNC_SLAVE_DELAY_SYNC 1 -/* Tell the io thread if the current event needs a ack. */ -#define SEMI_SYNC_NEED_ACK 2 - -class MYSQL_QUERY_LOG: public MYSQL_LOG -{ -public: - MYSQL_QUERY_LOG() : last_time(0) {} - void reopen_file(); - bool write(time_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, - const char *command_type, size_t command_type_len, - const char *sql_text, size_t sql_text_len); - bool write(THD *thd, time_t current_time, - const char *user_host, size_t user_host_len, - ulonglong query_utime, ulonglong lock_utime, bool is_command, - const char *sql_text, size_t sql_text_len); - bool open_slow_log(const char *log_name) - { - char buf[FN_REFLEN]; - return open( -#ifdef HAVE_PSI_INTERFACE - key_file_slow_log, -#endif - generate_name(log_name, "-slow.log", 0, buf), - LOG_NORMAL, 0, 0, WRITE_CACHE); - } - bool open_query_log(const char *log_name) - { - char buf[FN_REFLEN]; - return open( -#ifdef HAVE_PSI_INTERFACE - key_file_query_log, -#endif - generate_name(log_name, ".log", 0, buf), - LOG_NORMAL, 0, 0, WRITE_CACHE); - } - -private: - time_t last_time; -}; - -/* - We assign each binlog file an internal ID, used to identify them for unlog(). - The IDs start from 0 and increment for each new binlog created. - - In unlog() we need to know the ID of the binlog file that the corresponding - transaction was written into. We also need a special value for a corner - case where there is no corresponding binlog id (since nothing was logged). - And we need an error flag to mark that unlog() must return failure. - - We use the following macros to pack all of this information into the single - ulong available with log_and_order() / unlog(). - - Note that we cannot use the value 0 for cookie, as that is reserved as error - return value from log_and_order(). - */ -#define BINLOG_COOKIE_ERROR_RETURN 0 -#define BINLOG_COOKIE_DUMMY_ID 1 -#define BINLOG_COOKIE_BASE 2 -#define BINLOG_COOKIE_DUMMY(error_flag) \ - ( (BINLOG_COOKIE_DUMMY_ID<<1) | ((error_flag)&1) ) -#define BINLOG_COOKIE_MAKE(id, error_flag) \ - ( (((id)+BINLOG_COOKIE_BASE)<<1) | ((error_flag)&1) ) -#define BINLOG_COOKIE_GET_ERROR_FLAG(c) ((c) & 1) -#define BINLOG_COOKIE_GET_ID(c) ( ((ulong)(c)>>1) - BINLOG_COOKIE_BASE ) -#define BINLOG_COOKIE_IS_DUMMY(c) \ - ( ((ulong)(c)>>1) == BINLOG_COOKIE_DUMMY_ID ) - -class binlog_cache_mngr; -class binlog_cache_data; -struct rpl_gtid; -struct wait_for_commit; - -class MYSQL_BIN_LOG: public TC_LOG, private MYSQL_LOG -{ - /** The instrumentation key to use for @ LOCK_index. */ - PSI_mutex_key m_key_LOCK_index; - /** The instrumentation key to use for @ COND_relay_log_updated */ - PSI_cond_key m_key_relay_log_update; - /** The instrumentation key to use for @ COND_bin_log_updated */ - PSI_cond_key m_key_bin_log_update; - /** The instrumentation key to use for opening the log file. */ - PSI_file_key m_key_file_log, m_key_file_log_cache; - /** The instrumentation key to use for opening the log index file. */ - PSI_file_key m_key_file_log_index, m_key_file_log_index_cache; - - PSI_cond_key m_key_COND_queue_busy; - /** The instrumentation key to use for LOCK_binlog_end_pos. */ - PSI_mutex_key m_key_LOCK_binlog_end_pos; - - struct group_commit_entry - { - struct group_commit_entry *next; - THD *thd; - binlog_cache_mngr *cache_mngr; - bool using_stmt_cache; - bool using_trx_cache; - /* - Extra events (COMMIT/ROLLBACK/XID, and possibly INCIDENT) to be - written during group commit. The incident_event is only valid if - trx_data->has_incident() is true. - */ - Log_event *end_event; - Log_event *incident_event; - /* Set during group commit to record any per-thread error. */ - int error; - int commit_errno; - IO_CACHE *error_cache; - /* This is the `all' parameter for ha_commit_ordered(). */ - bool all; - /* - True if we need to increment xid_count in trx_group_commit_leader() and - decrement in unlog() (this is needed if there is a participating engine - that does not implement the commit_checkpoint_request() handlerton - method). - */ - bool need_unlog; - /* - Fields used to pass the necessary information to the last thread in a - group commit, only used when opt_optimize_thread_scheduling is not set. - */ - bool check_purge; - /* Flag used to optimise around wait_for_prior_commit. */ - bool queued_by_other; - ulong binlog_id; - }; - - /* - When this is set, a RESET MASTER is in progress. - - Then we should not write any binlog checkpoints into the binlog (that - could result in deadlock on LOCK_log, and we will delete all binlog files - anyway). Instead we should signal COND_xid_list whenever a new binlog - checkpoint arrives - when all have arrived, RESET MASTER will complete. - */ - uint reset_master_pending; - ulong mark_xid_done_waiting; - - /* LOCK_log and LOCK_index are inited by init_pthread_objects() */ - mysql_mutex_t LOCK_index; - mysql_mutex_t LOCK_binlog_end_pos; - mysql_mutex_t LOCK_xid_list; - mysql_cond_t COND_xid_list; - mysql_cond_t COND_relay_log_updated, COND_bin_log_updated; - ulonglong bytes_written; - IO_CACHE index_file; - char index_file_name[FN_REFLEN]; - /* - purge_file is a temp file used in purge_logs so that the index file - can be updated before deleting files from disk, yielding better crash - recovery. It is created on demand the first time purge_logs is called - and then reused for subsequent calls. It is cleaned up in cleanup(). - */ - IO_CACHE purge_index_file; - char purge_index_file_name[FN_REFLEN]; - /* - The max size before rotation (usable only if log_type == LOG_BIN: binary - logs and relay logs). - For a binlog, max_size should be max_binlog_size. - max_size is set in init(), and dynamically changed (when one does SET - GLOBAL MAX_BINLOG_SIZE|MAX_RELAY_LOG_SIZE) from sys_vars.cc - */ - ulong max_size; - /* - Number generated by last call of find_uniq_filename(). Corresponds - closely with current_binlog_id - */ - ulong last_used_log_number; - // current file sequence number for load data infile binary logging - uint file_id; - uint open_count; // For replication - int readers_count; - /* Queue of transactions queued up to participate in group commit. */ - group_commit_entry *group_commit_queue; - /* - Condition variable to mark that the group commit queue is busy. - Used when each thread does it's own commit_ordered() (when - binlog_optimize_thread_scheduling=1). - Used with the LOCK_commit_ordered mutex. - */ - my_bool group_commit_queue_busy; - mysql_cond_t COND_queue_busy; - /* Total number of committed transactions. */ - ulonglong num_commits; - /* Number of group commits done. */ - ulonglong num_group_commits; - /* The reason why the group commit was grouped */ - ulonglong group_commit_trigger_count, group_commit_trigger_timeout; - ulonglong group_commit_trigger_lock_wait; - - /* binlog encryption data */ - struct Binlog_crypt_data crypto; - - /* pointer to the sync period variable, for binlog this will be - sync_binlog_period, for relay log this will be - sync_relay_log_period - */ - uint *sync_period_ptr; - uint sync_counter; - bool state_file_deleted; - bool binlog_state_recover_done; - - inline uint get_sync_period() - { - return *sync_period_ptr; - } - - int write_to_file(IO_CACHE *cache); - /* - This is used to start writing to a new log file. The difference from - new_file() is locking. new_file_without_locking() does not acquire - LOCK_log. - */ - int new_file_without_locking(); - int new_file_impl(); - void do_checkpoint_request(ulong binlog_id); - void purge(); - int write_transaction_or_stmt(group_commit_entry *entry, uint64 commit_id); - int queue_for_group_commit(group_commit_entry *entry); - bool write_transaction_to_binlog_events(group_commit_entry *entry); - void trx_group_commit_leader(group_commit_entry *leader); - bool is_xidlist_idle_nolock(); -public: - /* - A list of struct xid_count_per_binlog is used to keep track of how many - XIDs are in prepared, but not committed, state in each binlog. And how - many commit_checkpoint_request()'s are pending. - - When count drops to zero in a binlog after rotation, it means that there - are no more XIDs in prepared state, so that binlog is no longer needed - for XA crash recovery, and we can log a new binlog checkpoint event. - - The list is protected against simultaneous access from multiple - threads by LOCK_xid_list. - */ - struct xid_count_per_binlog : public ilink { - char *binlog_name; - uint binlog_name_len; - ulong binlog_id; - /* Total prepared XIDs and pending checkpoint requests in this binlog. */ - long xid_count; - long notify_count; - /* For linking in requests to the binlog background thread. */ - xid_count_per_binlog *next_in_queue; - xid_count_per_binlog(char *log_file_name, uint log_file_name_len) - :binlog_id(0), xid_count(0), notify_count(0) - { - binlog_name_len= log_file_name_len; - binlog_name= (char *) my_malloc(PSI_INSTRUMENT_ME, binlog_name_len, MYF(MY_ZEROFILL)); - if (binlog_name) - memcpy(binlog_name, log_file_name, binlog_name_len); - } - ~xid_count_per_binlog() - { - my_free(binlog_name); - } - }; - I_List binlog_xid_count_list; - mysql_mutex_t LOCK_binlog_background_thread; - mysql_cond_t COND_binlog_background_thread; - mysql_cond_t COND_binlog_background_thread_end; - - void stop_background_thread(); - - using MYSQL_LOG::generate_name; - using MYSQL_LOG::is_open; - - /* This is relay log */ - bool is_relay_log; - ulong relay_signal_cnt; // update of the counter is checked by heartbeat - enum enum_binlog_checksum_alg checksum_alg_reset; // to contain a new value when binlog is rotated - /* - Holds the last seen in Relay-Log FD's checksum alg value. - The initial value comes from the slave's local FD that heads - the very first Relay-Log file. In the following the value may change - with each received master's FD_m. - Besides to be used in verification events that IO thread receives - (except the 1st fake Rotate, see @c Master_info:: checksum_alg_before_fd), - the value specifies if/how to compute checksum for slave's local events - and the first fake Rotate (R_f^1) coming from the master. - R_f^1 needs logging checksum-compatibly with the RL's heading FD_s. - - Legends for the checksum related comments: - - FD - Format-Description event, - R - Rotate event - R_f - the fake Rotate event - E - an arbirary event - - The underscore indexes for any event - `_s' indicates the event is generated by Slave - `_m' - by Master - - Two special underscore indexes of FD: - FD_q - Format Description event for queuing (relay-logging) - FD_e - Format Description event for executing (relay-logging) - - Upper indexes: - E^n - n:th event is a sequence - - RL - Relay Log - (A) - checksum algorithm descriptor value - FD.(A) - the value of (A) in FD - */ - enum enum_binlog_checksum_alg relay_log_checksum_alg; - /* - These describe the log's format. This is used only for relay logs. - _for_exec is used by the SQL thread, _for_queue by the I/O thread. It's - necessary to have 2 distinct objects, because the I/O thread may be reading - events in a different format from what the SQL thread is reading (consider - the case of a master which has been upgraded from 5.0 to 5.1 without doing - RESET MASTER, or from 4.x to 5.0). - */ - Format_description_log_event *description_event_for_exec, - *description_event_for_queue; - /* - Binlog position of last commit (or non-transactional write) to the binlog. - Access to this is protected by LOCK_commit_ordered. - */ - char last_commit_pos_file[FN_REFLEN]; - my_off_t last_commit_pos_offset; - ulong current_binlog_id; - - MYSQL_BIN_LOG(uint *sync_period); - /* - note that there's no destructor ~MYSQL_BIN_LOG() ! - The reason is that we don't want it to be automatically called - on exit() - but only during the correct shutdown process - */ - -#ifdef HAVE_PSI_INTERFACE - void set_psi_keys(PSI_mutex_key key_LOCK_index, - PSI_cond_key key_relay_log_update, - PSI_cond_key key_bin_log_update, - PSI_file_key key_file_log, - PSI_file_key key_file_log_cache, - PSI_file_key key_file_log_index, - PSI_file_key key_file_log_index_cache, - PSI_cond_key key_COND_queue_busy, - PSI_mutex_key key_LOCK_binlog_end_pos) - { - m_key_LOCK_index= key_LOCK_index; - m_key_relay_log_update= key_relay_log_update; - m_key_bin_log_update= key_bin_log_update; - m_key_file_log= key_file_log; - m_key_file_log_cache= key_file_log_cache; - m_key_file_log_index= key_file_log_index; - m_key_file_log_index_cache= key_file_log_index_cache; - m_key_COND_queue_busy= key_COND_queue_busy; - m_key_LOCK_binlog_end_pos= key_LOCK_binlog_end_pos; - } -#endif - - int open(const char *opt_name); - void close(); - virtual int generate_new_name(char *new_name, const char *log_name, - ulong next_log_number); - int log_and_order(THD *thd, my_xid xid, bool all, - bool need_prepare_ordered, bool need_commit_ordered); - int unlog(ulong cookie, my_xid xid); - int unlog_xa_prepare(THD *thd, bool all); - void commit_checkpoint_notify(void *cookie); - int recover(LOG_INFO *linfo, const char *last_log_name, IO_CACHE *first_log, - Format_description_log_event *fdle, bool do_xa); - int do_binlog_recovery(const char *opt_name, bool do_xa_recovery); -#if !defined(MYSQL_CLIENT) - - int flush_and_set_pending_rows_event(THD *thd, Rows_log_event* event, - bool is_transactional); - int remove_pending_rows_event(THD *thd, bool is_transactional); - -#endif /* !defined(MYSQL_CLIENT) */ - void reset_bytes_written() - { - bytes_written = 0; - } - void harvest_bytes_written(ulonglong* counter) - { -#ifndef DBUG_OFF - char buf1[22],buf2[22]; -#endif - DBUG_ENTER("harvest_bytes_written"); - (*counter)+=bytes_written; - DBUG_PRINT("info",("counter: %s bytes_written: %s", llstr(*counter,buf1), - llstr(bytes_written,buf2))); - bytes_written=0; - DBUG_VOID_RETURN; - } - void set_max_size(ulong max_size_arg); - - /* Handle signaling that relay has been updated */ - void signal_relay_log_update() - { - mysql_mutex_assert_owner(&LOCK_log); - DBUG_ASSERT(is_relay_log); - DBUG_ENTER("MYSQL_BIN_LOG::signal_relay_log_update"); - relay_signal_cnt++; - mysql_cond_broadcast(&COND_relay_log_updated); - DBUG_VOID_RETURN; - } - void signal_bin_log_update() - { - mysql_mutex_assert_owner(&LOCK_binlog_end_pos); - DBUG_ASSERT(!is_relay_log); - DBUG_ENTER("MYSQL_BIN_LOG::signal_bin_log_update"); - mysql_cond_broadcast(&COND_bin_log_updated); - DBUG_VOID_RETURN; - } - void update_binlog_end_pos() - { - if (is_relay_log) - signal_relay_log_update(); - else - { - lock_binlog_end_pos(); - binlog_end_pos= my_b_safe_tell(&log_file); - signal_bin_log_update(); - unlock_binlog_end_pos(); - } - } - void update_binlog_end_pos(my_off_t pos) - { - mysql_mutex_assert_owner(&LOCK_log); - mysql_mutex_assert_not_owner(&LOCK_binlog_end_pos); - lock_binlog_end_pos(); - /* - Note: it would make more sense to assert(pos > binlog_end_pos) - but there are two places triggered by mtr that has pos == binlog_end_pos - i didn't investigate but accepted as it should do no harm - */ - DBUG_ASSERT(pos >= binlog_end_pos); - binlog_end_pos= pos; - signal_bin_log_update(); - unlock_binlog_end_pos(); - } - - void wait_for_sufficient_commits(); - void binlog_trigger_immediate_group_commit(); - void wait_for_update_relay_log(THD* thd); - void init(ulong max_size); - void init_pthread_objects(); - void cleanup(); - bool open(const char *log_name, - const char *new_name, - ulong next_log_number, - enum cache_type io_cache_type_arg, - ulong max_size, - bool null_created, - bool need_mutex); - bool open_index_file(const char *index_file_name_arg, - const char *log_name, bool need_mutex); - /* Use this to start writing a new log file */ - int new_file(); - - bool write(Log_event* event_info, - my_bool *with_annotate= 0); // binary log write - bool write_transaction_to_binlog(THD *thd, binlog_cache_mngr *cache_mngr, - Log_event *end_ev, bool all, - bool using_stmt_cache, bool using_trx_cache); - - bool write_incident_already_locked(THD *thd); - bool write_incident(THD *thd); - void write_binlog_checkpoint_event_already_locked(const char *name, uint len); - int write_cache(THD *thd, IO_CACHE *cache); - void set_write_error(THD *thd, bool is_transactional); - bool check_write_error(THD *thd); - - void start_union_events(THD *thd, query_id_t query_id_param); - void stop_union_events(THD *thd); - bool is_query_in_union(THD *thd, query_id_t query_id_param); - - bool write_event(Log_event *ev, binlog_cache_data *data, IO_CACHE *file); - bool write_event(Log_event *ev) { return write_event(ev, 0, &log_file); } - - bool write_event_buffer(uchar* buf,uint len); - bool append(Log_event* ev); - bool append_no_lock(Log_event* ev); - - void mark_xids_active(ulong cookie, uint xid_count); - void mark_xid_done(ulong cookie, bool write_checkpoint); - void make_log_name(char* buf, const char* log_ident); - bool is_active(const char* log_file_name); - bool can_purge_log(const char *log_file_name); - int update_log_index(LOG_INFO* linfo, bool need_update_threads); - int rotate(bool force_rotate, bool* check_purge); - void checkpoint_and_purge(ulong binlog_id); - int rotate_and_purge(bool force_rotate, DYNAMIC_ARRAY* drop_gtid_domain= NULL); - /** - Flush binlog cache and synchronize to disk. - - This function flushes events in binlog cache to binary log file, - it will do synchronizing according to the setting of system - variable 'sync_binlog'. If file is synchronized, @c synced will - be set to 1, otherwise 0. - - @param[out] synced if not NULL, set to 1 if file is synchronized, otherwise 0 - - @retval 0 Success - @retval other Failure - */ - bool flush_and_sync(bool *synced); - int purge_logs(const char *to_log, bool included, - bool need_mutex, bool need_update_threads, - ulonglong *decrease_log_space); - int purge_logs_before_date(time_t purge_time); - int purge_first_log(Relay_log_info* rli, bool included); - int set_purge_index_file_name(const char *base_file_name); - int open_purge_index_file(bool destroy); - bool is_inited_purge_index_file(); - int close_purge_index_file(); - int clean_purge_index_file(); - int sync_purge_index_file(); - int register_purge_index_entry(const char* entry); - int register_create_index_entry(const char* entry); - int purge_index_entry(THD *thd, ulonglong *decrease_log_space, - bool need_mutex); - bool reset_logs(THD* thd, bool create_new_log, - rpl_gtid *init_state, uint32 init_state_len, - ulong next_log_number); - void wait_for_last_checkpoint_event(); - void close(uint exiting); - void clear_inuse_flag_when_closing(File file); - - // iterating through the log index file - int find_log_pos(LOG_INFO* linfo, const char* log_name, - bool need_mutex); - int find_next_log(LOG_INFO* linfo, bool need_mutex); - int get_current_log(LOG_INFO* linfo); - int raw_get_current_log(LOG_INFO* linfo); - uint next_file_id(); - inline char* get_index_fname() { return index_file_name;} - inline char* get_log_fname() { return log_file_name; } - inline char* get_name() { return name; } - inline mysql_mutex_t* get_log_lock() { return &LOCK_log; } - inline mysql_cond_t* get_bin_log_cond() { return &COND_bin_log_updated; } - inline IO_CACHE* get_log_file() { return &log_file; } - - inline void lock_index() { mysql_mutex_lock(&LOCK_index);} - inline void unlock_index() { mysql_mutex_unlock(&LOCK_index);} - inline IO_CACHE *get_index_file() { return &index_file;} - inline uint32 get_open_count() { return open_count; } - void set_status_variables(THD *thd); - bool is_xidlist_idle(); - bool write_gtid_event(THD *thd, bool standalone, bool is_transactional, - uint64 commit_id); - int read_state_from_file(); - int write_state_to_file(); - int get_most_recent_gtid_list(rpl_gtid **list, uint32 *size); - bool append_state_pos(String *str); - bool append_state(String *str); - bool is_empty_state(); - bool find_in_binlog_state(uint32 domain_id, uint32 server_id, - rpl_gtid *out_gtid); - bool lookup_domain_in_binlog_state(uint32 domain_id, rpl_gtid *out_gtid); - int bump_seq_no_counter_if_needed(uint32 domain_id, uint64 seq_no); - bool check_strict_gtid_sequence(uint32 domain_id, uint32 server_id, - uint64 seq_no); - - /** - * used when opening new file, and binlog_end_pos moves backwards - */ - void reset_binlog_end_pos(const char file_name[FN_REFLEN], my_off_t pos) - { - mysql_mutex_assert_owner(&LOCK_log); - mysql_mutex_assert_not_owner(&LOCK_binlog_end_pos); - lock_binlog_end_pos(); - binlog_end_pos= pos; - strcpy(binlog_end_pos_file, file_name); - signal_bin_log_update(); - unlock_binlog_end_pos(); - } - - /* - It is called by the threads(e.g. dump thread) which want to read - log without LOCK_log protection. - */ - my_off_t get_binlog_end_pos(char file_name_buf[FN_REFLEN]) const - { - mysql_mutex_assert_not_owner(&LOCK_log); - mysql_mutex_assert_owner(&LOCK_binlog_end_pos); - strcpy(file_name_buf, binlog_end_pos_file); - return binlog_end_pos; - } - void lock_binlog_end_pos() { mysql_mutex_lock(&LOCK_binlog_end_pos); } - void unlock_binlog_end_pos() { mysql_mutex_unlock(&LOCK_binlog_end_pos); } - mysql_mutex_t* get_binlog_end_pos_lock() { return &LOCK_binlog_end_pos; } - - int wait_for_update_binlog_end_pos(THD* thd, struct timespec * timeout); - - /* - Binlog position of end of the binlog. - Access to this is protected by LOCK_binlog_end_pos - - The difference between this and last_commit_pos_{file,offset} is that - the commit position is updated later. If semi-sync wait point is set - to WAIT_AFTER_SYNC, the commit pos is update after semi-sync-ack has - been received and the end point is updated after the write as it's needed - for the dump threads to be able to semi-sync the event. - */ - my_off_t binlog_end_pos; - char binlog_end_pos_file[FN_REFLEN]; -}; - -class Log_event_handler -{ -public: - Log_event_handler() {} - virtual bool init()= 0; - virtual void cleanup()= 0; - - virtual bool log_slow(THD *thd, my_hrtime_t current_time, - const char *user_host, size_t user_host_len, ulonglong query_utime, - ulonglong lock_utime, bool is_command, - const char *sql_text, size_t sql_text_len)= 0; - virtual bool log_error(enum loglevel level, const char *format, - va_list args)= 0; - virtual bool log_general(THD *thd, my_hrtime_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, - const char *command_type, size_t command_type_len, - const char *sql_text, size_t sql_text_len, - CHARSET_INFO *client_cs)= 0; - virtual ~Log_event_handler() {} -}; - - -int check_if_log_table(const TABLE_LIST *table, bool check_if_opened, - const char *errmsg); - -class Log_to_csv_event_handler: public Log_event_handler -{ - friend class LOGGER; - -public: - Log_to_csv_event_handler(); - ~Log_to_csv_event_handler(); - virtual bool init(); - virtual void cleanup(); - - virtual bool log_slow(THD *thd, my_hrtime_t current_time, - const char *user_host, size_t user_host_len, ulonglong query_utime, - ulonglong lock_utime, bool is_command, - const char *sql_text, size_t sql_text_len); - virtual bool log_error(enum loglevel level, const char *format, - va_list args); - virtual bool log_general(THD *thd, my_hrtime_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, - const char *command_type, size_t command_type_len, - const char *sql_text, size_t sql_text_len, - CHARSET_INFO *client_cs); - - int activate_log(THD *thd, uint log_type); -}; - - -/* type of the log table */ -#define QUERY_LOG_SLOW 1 -#define QUERY_LOG_GENERAL 2 - -class Log_to_file_event_handler: public Log_event_handler -{ - MYSQL_QUERY_LOG mysql_log; - MYSQL_QUERY_LOG mysql_slow_log; - bool is_initialized; -public: - Log_to_file_event_handler(): is_initialized(FALSE) - {} - virtual bool init(); - virtual void cleanup(); - - virtual bool log_slow(THD *thd, my_hrtime_t current_time, - const char *user_host, size_t user_host_len, ulonglong query_utime, - ulonglong lock_utime, bool is_command, - const char *sql_text, size_t sql_text_len); - virtual bool log_error(enum loglevel level, const char *format, - va_list args); - virtual bool log_general(THD *thd, my_hrtime_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, - const char *command_type, size_t command_type_len, - const char *sql_text, size_t sql_text_len, - CHARSET_INFO *client_cs); - void flush(); - void init_pthread_objects(); - MYSQL_QUERY_LOG *get_mysql_slow_log() { return &mysql_slow_log; } - MYSQL_QUERY_LOG *get_mysql_log() { return &mysql_log; } -}; - - -/* Class which manages slow, general and error log event handlers */ -class LOGGER -{ - mysql_rwlock_t LOCK_logger; - /* flag to check whether logger mutex is initialized */ - uint inited; - - /* available log handlers */ - Log_to_csv_event_handler *table_log_handler; - Log_to_file_event_handler *file_log_handler; - - /* NULL-terminated arrays of log handlers */ - Log_event_handler *error_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; - Log_event_handler *slow_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; - Log_event_handler *general_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; - -public: - - bool is_log_tables_initialized; - - LOGGER() : inited(0), table_log_handler(NULL), - file_log_handler(NULL), is_log_tables_initialized(FALSE) - {} - void lock_shared() { mysql_rwlock_rdlock(&LOCK_logger); } - void lock_exclusive() { mysql_rwlock_wrlock(&LOCK_logger); } - void unlock() { mysql_rwlock_unlock(&LOCK_logger); } - bool is_log_table_enabled(uint log_table_type); - bool log_command(THD *thd, enum enum_server_command command); - - /* - We want to initialize all log mutexes as soon as possible, - but we cannot do it in constructor, as safe_mutex relies on - initialization, performed by MY_INIT(). This why this is done in - this function. - */ - void init_base(); - void init_log_tables(); - bool flush_slow_log(); - bool flush_general_log(); - /* Perform basic logger cleanup. this will leave e.g. error log open. */ - void cleanup_base(); - /* Free memory. Nothing could be logged after this function is called */ - void cleanup_end(); - bool error_log_print(enum loglevel level, const char *format, - va_list args); - bool slow_log_print(THD *thd, const char *query, size_t query_length, - ulonglong current_utime); - bool general_log_print(THD *thd,enum enum_server_command command, - const char *format, va_list args); - bool general_log_write(THD *thd, enum enum_server_command command, - const char *query, size_t query_length); - - /* we use this function to setup all enabled log event handlers */ - int set_handlers(ulonglong error_log_printer, - ulonglong slow_log_printer, - ulonglong general_log_printer); - void init_error_log(ulonglong error_log_printer); - void init_slow_log(ulonglong slow_log_printer); - void init_general_log(ulonglong general_log_printer); - void deactivate_log_handler(THD* thd, uint log_type); - bool activate_log_handler(THD* thd, uint log_type); - MYSQL_QUERY_LOG *get_slow_log_file_handler() const - { - if (file_log_handler) - return file_log_handler->get_mysql_slow_log(); - return NULL; - } - MYSQL_QUERY_LOG *get_log_file_handler() const - { - if (file_log_handler) - return file_log_handler->get_mysql_log(); - return NULL; - } -}; - -enum enum_binlog_format { - BINLOG_FORMAT_MIXED= 0, ///< statement if safe, otherwise row - autodetected - BINLOG_FORMAT_STMT= 1, ///< statement-based - BINLOG_FORMAT_ROW= 2, ///< row-based - BINLOG_FORMAT_UNSPEC=3 ///< thd_binlog_format() returns it when binlog is closed -}; - -int query_error_code(THD *thd, bool not_killed); -uint purge_log_get_error_code(int res); - -int vprint_msg_to_log(enum loglevel level, const char *format, va_list args); -void sql_print_error(const char *format, ...); -void sql_print_warning(const char *format, ...); -void sql_print_information(const char *format, ...); -void sql_print_information_v(const char *format, va_list ap); -typedef void (*sql_print_message_func)(const char *format, ...); -extern sql_print_message_func sql_print_message_handlers[]; - -int error_log_print(enum loglevel level, const char *format, - va_list args); - -bool slow_log_print(THD *thd, const char *query, uint query_length, - ulonglong current_utime); - -bool general_log_print(THD *thd, enum enum_server_command command, - const char *format,...); - -bool general_log_write(THD *thd, enum enum_server_command command, - const char *query, size_t query_length); - -void binlog_report_wait_for(THD *thd, THD *other_thd); -void sql_perror(const char *message); -bool flush_error_log(); - -File open_binlog(IO_CACHE *log, const char *log_file_name, - const char **errmsg); - -void make_default_log_name(char **out, const char* log_ext, bool once); -void binlog_reset_cache(THD *thd); -bool write_annotated_row(THD *thd); - -extern MYSQL_PLUGIN_IMPORT MYSQL_BIN_LOG mysql_bin_log; -extern handlerton *binlog_hton; -extern LOGGER logger; - -extern const char *log_bin_index; -extern const char *log_bin_basename; - -/** - Turns a relative log binary log path into a full path, based on the - opt_bin_logname or opt_relay_logname. - - @param from The log name we want to make into an absolute path. - @param to The buffer where to put the results of the - normalization. - @param is_relay_log Switch that makes is used inside to choose which - option (opt_bin_logname or opt_relay_logname) to - use when calculating the base path. - - @returns true if a problem occurs, false otherwise. - */ - -inline bool normalize_binlog_name(char *to, const char *from, bool is_relay_log) -{ - DBUG_ENTER("normalize_binlog_name"); - bool error= false; - char buff[FN_REFLEN]; - char *ptr= (char*) from; - char *opt_name= is_relay_log ? opt_relay_logname : opt_bin_logname; - - DBUG_ASSERT(from); - - /* opt_name is not null and not empty and from is a relative path */ - if (opt_name && opt_name[0] && from && !test_if_hard_path(from)) - { - // take the path from opt_name - // take the filename from from - char log_dirpart[FN_REFLEN], log_dirname[FN_REFLEN]; - size_t log_dirpart_len, log_dirname_len; - dirname_part(log_dirpart, opt_name, &log_dirpart_len); - dirname_part(log_dirname, from, &log_dirname_len); - - /* log may be empty => relay-log or log-bin did not - hold paths, just filename pattern */ - if (log_dirpart_len > 0) - { - /* create the new path name */ - if(fn_format(buff, from+log_dirname_len, log_dirpart, "", - MYF(MY_UNPACK_FILENAME | MY_SAFE_PATH)) == NULL) - { - error= true; - goto end; - } - - ptr= buff; - } - } - - DBUG_ASSERT(ptr); - - if (ptr) - strmake(to, ptr, strlen(ptr)); - -end: - DBUG_RETURN(error); -} - -static inline TC_LOG *get_tc_log_implementation() -{ - if (total_ha_2pc <= 1) - return &tc_log_dummy; - if (opt_bin_log) - return &mysql_bin_log; - return &tc_log_mmap; -} - -#ifdef WITH_WSREP -IO_CACHE* wsrep_get_trans_cache(THD *); -void wsrep_thd_binlog_trx_reset(THD * thd); -void wsrep_thd_binlog_stmt_rollback(THD * thd); -#endif /* WITH_WSREP */ - -class Gtid_list_log_event; -const char * -get_gtid_list_event(IO_CACHE *cache, Gtid_list_log_event **out_gtid_list); - -#endif /* LOG_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_event.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_event.h deleted file mode 100644 index 4e19323..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_event.h +++ /dev/null @@ -1,5781 +0,0 @@ -/* Copyright (c) 2000, 2014, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @addtogroup Replication - @{ - - @file - - @brief Binary log event definitions. This includes generic code - common to all types of log events, as well as specific code for each - type of log event. -*/ - - -#ifndef _log_event_h -#define _log_event_h - -#if defined(USE_PRAGMA_INTERFACE) && defined(MYSQL_SERVER) -#pragma interface /* gcc class implementation */ -#endif - -#include -#include "rpl_constants.h" -#include -#include -#include -#include -#include - -#ifdef MYSQL_CLIENT -#include "sql_const.h" -#include "rpl_utility.h" -#include "hash.h" -#include "rpl_tblmap.h" -#include "sql_string.h" -#endif - -#ifdef MYSQL_SERVER -#include "rpl_record.h" -#include "rpl_reporting.h" -#include "sql_class.h" /* THD */ -#endif - -#include "rpl_gtid.h" - -/* Forward declarations */ -#ifndef MYSQL_CLIENT -class String; -#endif - -#define PREFIX_SQL_LOAD "SQL_LOAD-" -#define LONG_FIND_ROW_THRESHOLD 60 /* seconds */ - -/** - Either assert or return an error. - - In debug build, the condition will be checked, but in non-debug - builds, the error code given will be returned instead. - - @param COND Condition to check - @param ERRNO Error number to return in non-debug builds -*/ -#ifdef DBUG_OFF -#define ASSERT_OR_RETURN_ERROR(COND, ERRNO) \ - do { if (!(COND)) return ERRNO; } while (0) -#else -#define ASSERT_OR_RETURN_ERROR(COND, ERRNO) \ - DBUG_ASSERT(COND) -#endif - -#define LOG_READ_EOF -1 -#define LOG_READ_BOGUS -2 -#define LOG_READ_IO -3 -#define LOG_READ_MEM -5 -#define LOG_READ_TRUNC -6 -#define LOG_READ_TOO_LARGE -7 -#define LOG_READ_CHECKSUM_FAILURE -8 -#define LOG_READ_DECRYPT -9 - -#define LOG_EVENT_OFFSET 4 - -/* - 3 is MySQL 4.x; 4 is MySQL 5.0.0. - Compared to version 3, version 4 has: - - a different Start_log_event, which includes info about the binary log - (sizes of headers); this info is included for better compatibility if the - master's MySQL version is different from the slave's. - - all events have a unique ID (the triplet (server_id, timestamp at server - start, other) to be sure an event is not executed more than once in a - multimaster setup, example: - M1 - / \ - v v - M2 M3 - \ / - v v - S - if a query is run on M1, it will arrive twice on S, so we need that S - remembers the last unique ID it has processed, to compare and know if the - event should be skipped or not. Example of ID: we already have the server id - (4 bytes), plus: - timestamp_when_the_master_started (4 bytes), a counter (a sequence number - which increments every time we write an event to the binlog) (3 bytes). - Q: how do we handle when the counter is overflowed and restarts from 0 ? - - - Query and Load (Create or Execute) events may have a more precise - timestamp (with microseconds), number of matched/affected/warnings rows - and fields of session variables: SQL_MODE, - FOREIGN_KEY_CHECKS, UNIQUE_CHECKS, SQL_AUTO_IS_NULL, the collations and - charsets, the PASSWORD() version (old/new/...). -*/ -#define BINLOG_VERSION 4 - -/* - We could have used SERVER_VERSION_LENGTH, but this introduces an - obscure dependency - if somebody decided to change SERVER_VERSION_LENGTH - this would break the replication protocol -*/ -#define ST_SERVER_VER_LEN 50 - -/* - These are flags and structs to handle all the LOAD DATA INFILE options (LINES - TERMINATED etc). -*/ - -/* - These are flags and structs to handle all the LOAD DATA INFILE options (LINES - TERMINATED etc). - DUMPFILE_FLAG is probably useless (DUMPFILE is a clause of SELECT, not of LOAD - DATA). -*/ -#define DUMPFILE_FLAG 0x1 -#define OPT_ENCLOSED_FLAG 0x2 -#define REPLACE_FLAG 0x4 -#define IGNORE_FLAG 0x8 - -#define FIELD_TERM_EMPTY 0x1 -#define ENCLOSED_EMPTY 0x2 -#define LINE_TERM_EMPTY 0x4 -#define LINE_START_EMPTY 0x8 -#define ESCAPED_EMPTY 0x10 - -#define NUM_LOAD_DELIM_STRS 5 - -/***************************************************************************** - - MySQL Binary Log - - This log consists of events. Each event has a fixed-length header, - possibly followed by a variable length data body. - - The data body consists of an optional fixed length segment (post-header) - and an optional variable length segment. - - See the #defines below for the format specifics. - - The events which really update data are Query_log_event, - Execute_load_query_log_event and old Load_log_event and - Execute_load_log_event events (Execute_load_query is used together with - Begin_load_query and Append_block events to replicate LOAD DATA INFILE. - Create_file/Append_block/Execute_load (which includes Load_log_event) - were used to replicate LOAD DATA before the 5.0.3). - - ****************************************************************************/ - -#define LOG_EVENT_HEADER_LEN 19 /* the fixed header length */ -#define OLD_HEADER_LEN 13 /* the fixed header length in 3.23 */ -/* - Fixed header length, where 4.x and 5.0 agree. That is, 5.0 may have a longer - header (it will for sure when we have the unique event's ID), but at least - the first 19 bytes are the same in 4.x and 5.0. So when we have the unique - event's ID, LOG_EVENT_HEADER_LEN will be something like 26, but - LOG_EVENT_MINIMAL_HEADER_LEN will remain 19. -*/ -#define LOG_EVENT_MINIMAL_HEADER_LEN 19 - -/* event-specific post-header sizes */ -// where 3.23, 4.x and 5.0 agree -#define QUERY_HEADER_MINIMAL_LEN (4 + 4 + 1 + 2) -// where 5.0 differs: 2 for len of N-bytes vars. -#define QUERY_HEADER_LEN (QUERY_HEADER_MINIMAL_LEN + 2) -#define STOP_HEADER_LEN 0 -#define LOAD_HEADER_LEN (4 + 4 + 4 + 1 +1 + 4) -#define SLAVE_HEADER_LEN 0 -#define START_V3_HEADER_LEN (2 + ST_SERVER_VER_LEN + 4) -#define ROTATE_HEADER_LEN 8 // this is FROZEN (the Rotate post-header is frozen) -#define INTVAR_HEADER_LEN 0 -#define CREATE_FILE_HEADER_LEN 4 -#define APPEND_BLOCK_HEADER_LEN 4 -#define EXEC_LOAD_HEADER_LEN 4 -#define DELETE_FILE_HEADER_LEN 4 -#define NEW_LOAD_HEADER_LEN LOAD_HEADER_LEN -#define RAND_HEADER_LEN 0 -#define USER_VAR_HEADER_LEN 0 -#define FORMAT_DESCRIPTION_HEADER_LEN (START_V3_HEADER_LEN+1+LOG_EVENT_TYPES) -#define XID_HEADER_LEN 0 -#define BEGIN_LOAD_QUERY_HEADER_LEN APPEND_BLOCK_HEADER_LEN -#define ROWS_HEADER_LEN_V1 8 -#define TABLE_MAP_HEADER_LEN 8 -#define EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN (4 + 4 + 4 + 1) -#define EXECUTE_LOAD_QUERY_HEADER_LEN (QUERY_HEADER_LEN + EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN) -#define INCIDENT_HEADER_LEN 2 -#define HEARTBEAT_HEADER_LEN 0 -#define IGNORABLE_HEADER_LEN 0 -#define ROWS_HEADER_LEN_V2 10 -#define ANNOTATE_ROWS_HEADER_LEN 0 -#define BINLOG_CHECKPOINT_HEADER_LEN 4 -#define GTID_HEADER_LEN 19 -#define GTID_LIST_HEADER_LEN 4 -#define START_ENCRYPTION_HEADER_LEN 0 -#define XA_PREPARE_HEADER_LEN 0 - -/* - Max number of possible extra bytes in a replication event compared to a - packet (i.e. a query) sent from client to master; - First, an auxiliary log_event status vars estimation: -*/ -#define MAX_SIZE_LOG_EVENT_STATUS (1 + 4 /* type, flags2 */ + \ - 1 + 8 /* type, sql_mode */ + \ - 1 + 1 + 255 /* type, length, catalog */ + \ - 1 + 4 /* type, auto_increment */ + \ - 1 + 6 /* type, charset */ + \ - 1 + 1 + 255 /* type, length, time_zone */ + \ - 1 + 2 /* type, lc_time_names_number */ + \ - 1 + 2 /* type, charset_database_number */ + \ - 1 + 8 /* type, table_map_for_update */ + \ - 1 + 4 /* type, master_data_written */ + \ - 1 + 3 /* type, sec_part of NOW() */ + \ - 1 + 16 + 1 + 60/* type, user_len, user, host_len, host */) -#define MAX_LOG_EVENT_HEADER ( /* in order of Query_log_event::write */ \ - LOG_EVENT_HEADER_LEN + /* write_header */ \ - QUERY_HEADER_LEN + /* write_data */ \ - EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN + /*write_post_header_for_derived */ \ - MAX_SIZE_LOG_EVENT_STATUS + /* status */ \ - NAME_LEN + 1) - -/* - The new option is added to handle large packets that are sent from the master - to the slave. It is used to increase the thd(max_allowed) for both the - DUMP thread on the master and the SQL/IO thread on the slave. -*/ -#define MAX_MAX_ALLOWED_PACKET (1024*1024*1024) - -/* - Event header offsets; - these point to places inside the fixed header. -*/ - -#define EVENT_TYPE_OFFSET 4 -#define SERVER_ID_OFFSET 5 -#define EVENT_LEN_OFFSET 9 -#define LOG_POS_OFFSET 13 -#define FLAGS_OFFSET 17 - -/* start event post-header (for v3 and v4) */ - -#define ST_BINLOG_VER_OFFSET 0 -#define ST_SERVER_VER_OFFSET 2 -#define ST_CREATED_OFFSET (ST_SERVER_VER_OFFSET + ST_SERVER_VER_LEN) -#define ST_COMMON_HEADER_LEN_OFFSET (ST_CREATED_OFFSET + 4) - -/* slave event post-header (this event is never written) */ - -#define SL_MASTER_PORT_OFFSET 8 -#define SL_MASTER_POS_OFFSET 0 -#define SL_MASTER_HOST_OFFSET 10 - -/* query event post-header */ - -#define Q_THREAD_ID_OFFSET 0 -#define Q_EXEC_TIME_OFFSET 4 -#define Q_DB_LEN_OFFSET 8 -#define Q_ERR_CODE_OFFSET 9 -#define Q_STATUS_VARS_LEN_OFFSET 11 -#define Q_DATA_OFFSET QUERY_HEADER_LEN -/* these are codes, not offsets; not more than 256 values (1 byte). */ -#define Q_FLAGS2_CODE 0 -#define Q_SQL_MODE_CODE 1 -/* - Q_CATALOG_CODE is catalog with end zero stored; it is used only by MySQL - 5.0.x where 0<=x<=3. We have to keep it to be able to replicate these - old masters. -*/ -#define Q_CATALOG_CODE 2 -#define Q_AUTO_INCREMENT 3 -#define Q_CHARSET_CODE 4 -#define Q_TIME_ZONE_CODE 5 -/* - Q_CATALOG_NZ_CODE is catalog withOUT end zero stored; it is used by MySQL - 5.0.x where x>=4. Saves one byte in every Query_log_event in binlog, - compared to Q_CATALOG_CODE. The reason we didn't simply re-use - Q_CATALOG_CODE is that then a 5.0.3 slave of this 5.0.x (x>=4) master would - crash (segfault etc) because it would expect a 0 when there is none. -*/ -#define Q_CATALOG_NZ_CODE 6 - -#define Q_LC_TIME_NAMES_CODE 7 - -#define Q_CHARSET_DATABASE_CODE 8 - -#define Q_TABLE_MAP_FOR_UPDATE_CODE 9 - -#define Q_MASTER_DATA_WRITTEN_CODE 10 - -#define Q_INVOKER 11 - -#define Q_HRNOW 128 - -/* Intvar event post-header */ - -/* Intvar event data */ -#define I_TYPE_OFFSET 0 -#define I_VAL_OFFSET 1 - -/* Rand event data */ -#define RAND_SEED1_OFFSET 0 -#define RAND_SEED2_OFFSET 8 - -/* User_var event data */ -#define UV_VAL_LEN_SIZE 4 -#define UV_VAL_IS_NULL 1 -#define UV_VAL_TYPE_SIZE 1 -#define UV_NAME_LEN_SIZE 4 -#define UV_CHARSET_NUMBER_SIZE 4 - -/* Load event post-header */ -#define L_THREAD_ID_OFFSET 0 -#define L_EXEC_TIME_OFFSET 4 -#define L_SKIP_LINES_OFFSET 8 -#define L_TBL_LEN_OFFSET 12 -#define L_DB_LEN_OFFSET 13 -#define L_NUM_FIELDS_OFFSET 14 -#define L_SQL_EX_OFFSET 18 -#define L_DATA_OFFSET LOAD_HEADER_LEN - -/* Rotate event post-header */ -#define R_POS_OFFSET 0 -#define R_IDENT_OFFSET 8 - -/* CF to DF handle LOAD DATA INFILE */ - -/* CF = "Create File" */ -#define CF_FILE_ID_OFFSET 0 -#define CF_DATA_OFFSET CREATE_FILE_HEADER_LEN - -/* AB = "Append Block" */ -#define AB_FILE_ID_OFFSET 0 -#define AB_DATA_OFFSET APPEND_BLOCK_HEADER_LEN - -/* EL = "Execute Load" */ -#define EL_FILE_ID_OFFSET 0 - -/* DF = "Delete File" */ -#define DF_FILE_ID_OFFSET 0 - -/* TM = "Table Map" */ -#define TM_MAPID_OFFSET 0 -#define TM_FLAGS_OFFSET 6 - -/* RW = "RoWs" */ -#define RW_MAPID_OFFSET 0 -#define RW_FLAGS_OFFSET 6 -#define RW_VHLEN_OFFSET 8 -#define RW_V_TAG_LEN 1 -#define RW_V_EXTRAINFO_TAG 0 - -/* ELQ = "Execute Load Query" */ -#define ELQ_FILE_ID_OFFSET QUERY_HEADER_LEN -#define ELQ_FN_POS_START_OFFSET ELQ_FILE_ID_OFFSET + 4 -#define ELQ_FN_POS_END_OFFSET ELQ_FILE_ID_OFFSET + 8 -#define ELQ_DUP_HANDLING_OFFSET ELQ_FILE_ID_OFFSET + 12 - -/* 4 bytes which all binlogs should begin with */ -#define BINLOG_MAGIC (const uchar*) "\xfe\x62\x69\x6e" - -/* - The 2 flags below were useless : - - the first one was never set - - the second one was set in all Rotate events on the master, but not used for - anything useful. - So they are now removed and their place may later be reused for other - flags. Then one must remember that Rotate events in 4.x have - LOG_EVENT_FORCED_ROTATE_F set, so one should not rely on the value of the - replacing flag when reading a Rotate event. - I keep the defines here just to remember what they were. -*/ -#ifdef TO_BE_REMOVED -#define LOG_EVENT_TIME_F 0x1 -#define LOG_EVENT_FORCED_ROTATE_F 0x2 -#endif - -/* - This flag only makes sense for Format_description_log_event. It is set - when the event is written, and *reset* when a binlog file is - closed (yes, it's the only case when MySQL modifies already written - part of binlog). Thus it is a reliable indicator that binlog was - closed correctly. (Stop_log_event is not enough, there's always a - small chance that mysqld crashes in the middle of insert and end of - the binlog would look like a Stop_log_event). - - This flag is used to detect a restart after a crash, and to provide - "unbreakable" binlog. The problem is that on a crash storage engines - rollback automatically, while binlog does not. To solve this we use this - flag and automatically append ROLLBACK to every non-closed binlog (append - virtually, on reading, file itself is not changed). If this flag is found, - mysqlbinlog simply prints "ROLLBACK" Replication master does not abort on - binlog corruption, but takes it as EOF, and replication slave forces a - rollback in this case. - - Note, that old binlogs does not have this flag set, so we get a - a backward-compatible behaviour. -*/ - -#define LOG_EVENT_BINLOG_IN_USE_F 0x1 - -/** - @def LOG_EVENT_THREAD_SPECIFIC_F - - If the query depends on the thread (for example: TEMPORARY TABLE). - Currently this is used by mysqlbinlog to know it must print - SET @@PSEUDO_THREAD_ID=xx; before the query (it would not hurt to print it - for every query but this would be slow). -*/ -#define LOG_EVENT_THREAD_SPECIFIC_F 0x4 - -/** - @def LOG_EVENT_SUPPRESS_USE_F - - Suppress the generation of 'USE' statements before the actual - statement. This flag should be set for any events that does not need - the current database set to function correctly. Most notable cases - are 'CREATE DATABASE' and 'DROP DATABASE'. - - This flags should only be used in exceptional circumstances, since - it introduce a significant change in behaviour regarding the - replication logic together with the flags --binlog-do-db and - --replicated-do-db. - */ -#define LOG_EVENT_SUPPRESS_USE_F 0x8 - -/* - Note: this is a place holder for the flag - LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F (0x10), which is not used any - more, please do not reused this value for other flags. - */ - -/** - @def LOG_EVENT_ARTIFICIAL_F - - Artificial events are created arbitrarily and not written to binary - log - - These events should not update the master log position when slave - SQL thread executes them. -*/ -#define LOG_EVENT_ARTIFICIAL_F 0x20 - -/** - @def LOG_EVENT_RELAY_LOG_F - - Events with this flag set are created by slave IO thread and written - to relay log -*/ -#define LOG_EVENT_RELAY_LOG_F 0x40 - -/** - @def LOG_EVENT_IGNORABLE_F - - For an event, 'e', carrying a type code, that a slave, - 's', does not recognize, 's' will check 'e' for - LOG_EVENT_IGNORABLE_F, and if the flag is set, then 'e' - is ignored. Otherwise, 's' acknowledges that it has - found an unknown event in the relay log. -*/ -#define LOG_EVENT_IGNORABLE_F 0x80 - -/** - @def LOG_EVENT_SKIP_REPLICATION_F - - Flag set by application creating the event (with @@skip_replication); the - slave will skip replication of such events if - --replicate-events-marked-for-skip is not set to REPLICATE. - - This is a MariaDB flag; we allocate it from the end of the available - values to reduce risk of conflict with new MySQL flags. -*/ -#define LOG_EVENT_SKIP_REPLICATION_F 0x8000 - - -/** - @def OPTIONS_WRITTEN_TO_BIN_LOG - - OPTIONS_WRITTEN_TO_BIN_LOG are the bits of thd->options which must - be written to the binlog. OPTIONS_WRITTEN_TO_BIN_LOG could be - written into the Format_description_log_event, so that if later we - don't want to replicate a variable we did replicate, or the - contrary, it's doable. But it should not be too hard to decide once - for all of what we replicate and what we don't, among the fixed 32 - bits of thd->options. - - I (Guilhem) have read through every option's usage, and it looks - like OPTION_AUTO_IS_NULL and OPTION_NO_FOREIGN_KEYS are the only - ones which alter how the query modifies the table. It's good to - replicate OPTION_RELAXED_UNIQUE_CHECKS too because otherwise, the - slave may insert data slower than the master, in InnoDB. - OPTION_BIG_SELECTS is not needed (the slave thread runs with - max_join_size=HA_POS_ERROR) and OPTION_BIG_TABLES is not needed - either, as the manual says (because a too big in-memory temp table - is automatically written to disk). -*/ -#define OPTIONS_WRITTEN_TO_BIN_LOG \ - (OPTION_AUTO_IS_NULL | OPTION_NO_FOREIGN_KEY_CHECKS | \ - OPTION_RELAXED_UNIQUE_CHECKS | OPTION_NOT_AUTOCOMMIT | OPTION_IF_EXISTS) - -/* Shouldn't be defined before */ -#define EXPECTED_OPTIONS \ - ((1ULL << 14) | (1ULL << 26) | (1ULL << 27) | (1ULL << 19) | (1ULL << 28)) - -#if OPTIONS_WRITTEN_TO_BIN_LOG != EXPECTED_OPTIONS -#error OPTIONS_WRITTEN_TO_BIN_LOG must NOT change their values! -#endif -#undef EXPECTED_OPTIONS /* You shouldn't use this one */ - -#define CHECKSUM_CRC32_SIGNATURE_LEN 4 -/** - defined statically while there is just one alg implemented -*/ -#define BINLOG_CHECKSUM_LEN CHECKSUM_CRC32_SIGNATURE_LEN -#define BINLOG_CHECKSUM_ALG_DESC_LEN 1 /* 1 byte checksum alg descriptor */ - -/* - These are capability numbers for MariaDB slave servers. - - Newer MariaDB slaves set this to inform the master about their capabilities. - This allows the master to decide which events it can send to the slave - without breaking replication on old slaves that maybe do not understand - all events from newer masters. - - As new releases are backwards compatible, a given capability implies also - all capabilities with smaller number. - - Older MariaDB slaves and other MySQL slave servers do not set this, so they - are recorded with capability 0. -*/ - -/* MySQL or old MariaDB slave with no announced capability. */ -#define MARIA_SLAVE_CAPABILITY_UNKNOWN 0 -/* MariaDB >= 5.3, which understands ANNOTATE_ROWS_EVENT. */ -#define MARIA_SLAVE_CAPABILITY_ANNOTATE 1 -/* - MariaDB >= 5.5. This version has the capability to tolerate events omitted - from the binlog stream without breaking replication (MySQL slaves fail - because they mis-compute the offsets into the master's binlog). -*/ -#define MARIA_SLAVE_CAPABILITY_TOLERATE_HOLES 2 -/* MariaDB >= 10.0, which knows about binlog_checkpoint_log_event. */ -#define MARIA_SLAVE_CAPABILITY_BINLOG_CHECKPOINT 3 -/* MariaDB >= 10.0.1, which knows about global transaction id events. */ -#define MARIA_SLAVE_CAPABILITY_GTID 4 - -/* Our capability. */ -#define MARIA_SLAVE_CAPABILITY_MINE MARIA_SLAVE_CAPABILITY_GTID - - -/** - @enum Log_event_type - - Enumeration type for the different types of log events. -*/ -enum Log_event_type -{ - /* - Every time you update this enum (when you add a type), you have to - fix Format_description_log_event::Format_description_log_event(). - */ - UNKNOWN_EVENT= 0, - START_EVENT_V3= 1, - QUERY_EVENT= 2, - STOP_EVENT= 3, - ROTATE_EVENT= 4, - INTVAR_EVENT= 5, - LOAD_EVENT= 6, - SLAVE_EVENT= 7, - CREATE_FILE_EVENT= 8, - APPEND_BLOCK_EVENT= 9, - EXEC_LOAD_EVENT= 10, - DELETE_FILE_EVENT= 11, - /* - NEW_LOAD_EVENT is like LOAD_EVENT except that it has a longer - sql_ex, allowing multibyte TERMINATED BY etc; both types share the - same class (Load_log_event) - */ - NEW_LOAD_EVENT= 12, - RAND_EVENT= 13, - USER_VAR_EVENT= 14, - FORMAT_DESCRIPTION_EVENT= 15, - XID_EVENT= 16, - BEGIN_LOAD_QUERY_EVENT= 17, - EXECUTE_LOAD_QUERY_EVENT= 18, - - TABLE_MAP_EVENT = 19, - - /* - These event numbers were used for 5.1.0 to 5.1.15 and are - therefore obsolete. - */ - PRE_GA_WRITE_ROWS_EVENT = 20, - PRE_GA_UPDATE_ROWS_EVENT = 21, - PRE_GA_DELETE_ROWS_EVENT = 22, - - /* - These event numbers are used from 5.1.16 until mysql-5.6.6, - and in MariaDB - */ - WRITE_ROWS_EVENT_V1 = 23, - UPDATE_ROWS_EVENT_V1 = 24, - DELETE_ROWS_EVENT_V1 = 25, - - /* - Something out of the ordinary happened on the master - */ - INCIDENT_EVENT= 26, - - /* - Heartbeat event to be send by master at its idle time - to ensure master's online status to slave - */ - HEARTBEAT_LOG_EVENT= 27, - - /* - In some situations, it is necessary to send over ignorable - data to the slave: data that a slave can handle in case there - is code for handling it, but which can be ignored if it is not - recognized. - - These mysql-5.6 events are not recognized (and ignored) by MariaDB - */ - IGNORABLE_LOG_EVENT= 28, - ROWS_QUERY_LOG_EVENT= 29, - - /* Version 2 of the Row events, generated only by mysql-5.6.6+ */ - WRITE_ROWS_EVENT = 30, - UPDATE_ROWS_EVENT = 31, - DELETE_ROWS_EVENT = 32, - - /* MySQL 5.6 GTID events, ignored by MariaDB */ - GTID_LOG_EVENT= 33, - ANONYMOUS_GTID_LOG_EVENT= 34, - PREVIOUS_GTIDS_LOG_EVENT= 35, - - /* MySQL 5.7 events, ignored by MariaDB */ - TRANSACTION_CONTEXT_EVENT= 36, - VIEW_CHANGE_EVENT= 37, - /* not ignored */ - XA_PREPARE_LOG_EVENT= 38, - - /* - Add new events here - right above this comment! - Existing events (except ENUM_END_EVENT) should never change their numbers - */ - - /* New MySQL/Sun events are to be added right above this comment */ - MYSQL_EVENTS_END, - - MARIA_EVENTS_BEGIN= 160, - /* New Maria event numbers start from here */ - ANNOTATE_ROWS_EVENT= 160, - /* - Binlog checkpoint event. Used for XA crash recovery on the master, not used - in replication. - A binlog checkpoint event specifies a binlog file such that XA crash - recovery can start from that file - and it is guaranteed to find all XIDs - that are prepared in storage engines but not yet committed. - */ - BINLOG_CHECKPOINT_EVENT= 161, - /* - Gtid event. For global transaction ID, used to start a new event group, - instead of the old BEGIN query event, and also to mark stand-alone - events. - */ - GTID_EVENT= 162, - /* - Gtid list event. Logged at the start of every binlog, to record the - current replication state. This consists of the last GTID seen for - each replication domain. - */ - GTID_LIST_EVENT= 163, - - START_ENCRYPTION_EVENT= 164, - - /* - Compressed binlog event. - - Note that the order between WRITE/UPDATE/DELETE events is significant; - this is so that we can convert from the compressed to the uncompressed - event type with (type-WRITE_ROWS_COMPRESSED_EVENT + WRITE_ROWS_EVENT) - and similar for _V1. - */ - QUERY_COMPRESSED_EVENT = 165, - WRITE_ROWS_COMPRESSED_EVENT_V1 = 166, - UPDATE_ROWS_COMPRESSED_EVENT_V1 = 167, - DELETE_ROWS_COMPRESSED_EVENT_V1 = 168, - WRITE_ROWS_COMPRESSED_EVENT = 169, - UPDATE_ROWS_COMPRESSED_EVENT = 170, - DELETE_ROWS_COMPRESSED_EVENT = 171, - - /* Add new MariaDB events here - right above this comment! */ - - ENUM_END_EVENT /* end marker */ -}; - - -/* - Bit flags for what has been writting to cache. Used to - discard logs with table map events but not row events and - nothing else important. This is stored by cache. -*/ - -enum enum_logged_status -{ - LOGGED_TABLE_MAP= 1, - LOGGED_ROW_EVENT= 2, - LOGGED_NO_DATA= 4, - LOGGED_CRITICAL= 8 -}; - -static inline bool LOG_EVENT_IS_QUERY(enum Log_event_type type) -{ - return type == QUERY_EVENT || type == QUERY_COMPRESSED_EVENT; -} - - -static inline bool LOG_EVENT_IS_WRITE_ROW(enum Log_event_type type) -{ - return type == WRITE_ROWS_EVENT || type == WRITE_ROWS_EVENT_V1 || - type == WRITE_ROWS_COMPRESSED_EVENT || - type == WRITE_ROWS_COMPRESSED_EVENT_V1; -} - - -static inline bool LOG_EVENT_IS_UPDATE_ROW(enum Log_event_type type) -{ - return type == UPDATE_ROWS_EVENT || type == UPDATE_ROWS_EVENT_V1 || - type == UPDATE_ROWS_COMPRESSED_EVENT || - type == UPDATE_ROWS_COMPRESSED_EVENT_V1; -} - - -static inline bool LOG_EVENT_IS_DELETE_ROW(enum Log_event_type type) -{ - return type == DELETE_ROWS_EVENT || type == DELETE_ROWS_EVENT_V1 || - type == DELETE_ROWS_COMPRESSED_EVENT || - type == DELETE_ROWS_COMPRESSED_EVENT_V1; -} - - -static inline bool LOG_EVENT_IS_ROW_COMPRESSED(enum Log_event_type type) -{ - return type == WRITE_ROWS_COMPRESSED_EVENT || - type == WRITE_ROWS_COMPRESSED_EVENT_V1 || - type == UPDATE_ROWS_COMPRESSED_EVENT || - type == UPDATE_ROWS_COMPRESSED_EVENT_V1 || - type == DELETE_ROWS_COMPRESSED_EVENT || - type == DELETE_ROWS_COMPRESSED_EVENT_V1; -} - - -static inline bool LOG_EVENT_IS_ROW_V2(enum Log_event_type type) -{ - return (type >= WRITE_ROWS_EVENT && type <= DELETE_ROWS_EVENT) || - (type >= WRITE_ROWS_COMPRESSED_EVENT && type <= DELETE_ROWS_COMPRESSED_EVENT); -} - - -/* - The number of types we handle in Format_description_log_event (UNKNOWN_EVENT - is not to be handled, it does not exist in binlogs, it does not have a - format). -*/ -#define LOG_EVENT_TYPES (ENUM_END_EVENT-1) - -enum Int_event_type -{ - INVALID_INT_EVENT = 0, LAST_INSERT_ID_EVENT = 1, INSERT_ID_EVENT = 2 -}; - -#ifdef MYSQL_SERVER -class String; -class MYSQL_BIN_LOG; -class THD; -#endif - -class Format_description_log_event; -class Relay_log_info; -class binlog_cache_data; - -bool copy_event_cache_to_file_and_reinit(IO_CACHE *cache, FILE *file); - -#ifdef MYSQL_CLIENT -enum enum_base64_output_mode { - BASE64_OUTPUT_NEVER= 0, - BASE64_OUTPUT_AUTO= 1, - BASE64_OUTPUT_ALWAYS= 2, - BASE64_OUTPUT_UNSPEC= 3, - BASE64_OUTPUT_DECODE_ROWS= 4, - /* insert new output modes here */ - BASE64_OUTPUT_MODE_COUNT -}; - -bool copy_event_cache_to_string_and_reinit(IO_CACHE *cache, LEX_STRING *to); - -/* - A structure for mysqlbinlog to know how to print events - - This structure is passed to the event's print() methods, - - There are two types of settings stored here: - 1. Last db, flags2, sql_mode etc comes from the last printed event. - They are stored so that only the necessary USE and SET commands - are printed. - 2. Other information on how to print the events, e.g. short_form, - hexdump_from. These are not dependent on the last event. -*/ -typedef struct st_print_event_info -{ - /* - Settings for database, sql_mode etc that comes from the last event - that was printed. We cache these so that we don't have to print - them if they are unchanged. - */ - char db[FN_REFLEN+1]; // TODO: make this a LEX_STRING when thd->db is - char charset[6]; // 3 variables, each of them storable in 2 bytes - char time_zone_str[MAX_TIME_ZONE_NAME_LENGTH]; - char delimiter[16]; - sql_mode_t sql_mode; /* must be same as THD.variables.sql_mode */ - my_thread_id thread_id; - ulonglong row_events; - ulong auto_increment_increment, auto_increment_offset; - uint lc_time_names_number; - uint charset_database_number; - uint verbose; - uint32 flags2; - uint32 server_id; - uint32 domain_id; - uint8 common_header_len; - enum_base64_output_mode base64_output_mode; - my_off_t hexdump_from; - - table_mapping m_table_map; - table_mapping m_table_map_ignored; - bool flags2_inited; - bool sql_mode_inited; - bool charset_inited; - bool thread_id_printed; - bool server_id_printed; - bool domain_id_printed; - bool allow_parallel; - bool allow_parallel_printed; - bool found_row_event; - bool print_row_count; - static const uint max_delimiter_size= 16; - /* Settings on how to print the events */ - bool short_form; - /* - This is set whenever a Format_description_event is printed. - Later, when an event is printed in base64, this flag is tested: if - no Format_description_event has been seen, it is unsafe to print - the base64 event, so an error message is generated. - */ - bool printed_fd_event; - /* - Track when @@skip_replication changes so we need to output a SET - statement for it. - */ - bool skip_replication; - bool print_table_metadata; - - /* - These two caches are used by the row-based replication events to - collect the header information and the main body of the events - making up a statement. - */ - IO_CACHE head_cache; - IO_CACHE body_cache; - IO_CACHE tail_cache; -#ifdef WHEN_FLASHBACK_REVIEW_READY - /* Storing the SQL for reviewing */ - IO_CACHE review_sql_cache; -#endif - FILE *file; - st_print_event_info(); - - ~st_print_event_info() { - close_cached_file(&head_cache); - close_cached_file(&body_cache); - close_cached_file(&tail_cache); -#ifdef WHEN_FLASHBACK_REVIEW_READY - close_cached_file(&review_sql_cache); -#endif - } - bool init_ok() /* tells if construction was successful */ - { return my_b_inited(&head_cache) && my_b_inited(&body_cache) -#ifdef WHEN_FLASHBACK_REVIEW_READY - && my_b_inited(&review_sql_cache) -#endif - ; } - void flush_for_error() - { - if (!copy_event_cache_to_file_and_reinit(&head_cache, file)) - copy_event_cache_to_file_and_reinit(&body_cache, file); - fflush(file); - } -} PRINT_EVENT_INFO; -#endif - -/** - This class encapsulates writing of Log_event objects to IO_CACHE. - Automatically calculates the checksum and encrypts the data, if necessary. -*/ - -class Log_event_writer -{ - /* Log_event_writer is updated when ctx is set */ - int (Log_event_writer::*encrypt_or_write)(const uchar *pos, size_t len); -public: - ulonglong bytes_written; - void *ctx; ///< Encryption context or 0 if no encryption is needed - uint checksum_len; - int write(Log_event *ev); - int write_header(uchar *pos, size_t len); - int write_data(const uchar *pos, size_t len); - int write_footer(); - my_off_t pos() { return my_b_safe_tell(file); } - void add_status(enum_logged_status status); - void set_incident(); - void set_encrypted_writer() - { encrypt_or_write= &Log_event_writer::encrypt_and_write; } - - Log_event_writer(IO_CACHE *file_arg, binlog_cache_data *cache_data_arg, - Binlog_crypt_data *cr= 0) - :encrypt_or_write(&Log_event_writer::write_internal), - bytes_written(0), ctx(0), - file(file_arg), cache_data(cache_data_arg), crypto(cr) { } - -private: - IO_CACHE *file; - binlog_cache_data *cache_data; - /** - Placeholder for event checksum while writing to binlog. - */ - ha_checksum crc; - /** - Encryption data (key, nonce). Only used if ctx != 0. - */ - Binlog_crypt_data *crypto; - /** - Event length to be written into the next encrypted block - */ - uint event_len; - int write_internal(const uchar *pos, size_t len); - int encrypt_and_write(const uchar *pos, size_t len); - int maybe_write_event_len(uchar *pos, size_t len); -}; - -/** - the struct aggregates two parameters that identify an event - uniquely in scope of communication of a particular master and slave couple. - I.e there can not be 2 events from the same staying connected master which - have the same coordinates. - @note - Such identifier is not yet unique generally as the event originating master - is resettable. Also the crashed master can be replaced with some other. -*/ -typedef struct event_coordinates -{ - char * file_name; // binlog file name (directories stripped) - my_off_t pos; // event's position in the binlog file -} LOG_POS_COORD; - -/** - @class Log_event - - This is the abstract base class for binary log events. - - @section Log_event_binary_format Binary Format - - Any @c Log_event saved on disk consists of the following three - components. - - - Common-Header - - Post-Header - - Body - - The Common-Header, documented in the table @ref Table_common_header - "below", always has the same form and length within one version of - MySQL. Each event type specifies a format and length of the - Post-Header. The length of the Common-Header is the same for all - events of the same type. The Body may be of different format and - length even for different events of the same type. The binary - formats of Post-Header and Body are documented separately in each - subclass. The binary format of Common-Header is as follows. - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Common-Header
NameFormatDescription
timestamp4 byte unsigned integerThe time when the query started, in seconds since 1970. -
type1 byte enumerationSee enum #Log_event_type.
server_id4 byte unsigned integerServer ID of the server that created the event.
total_size4 byte unsigned integerThe total size of this event, in bytes. In other words, this - is the sum of the sizes of Common-Header, Post-Header, and Body. -
master_position4 byte unsigned integerThe position of the next event in the master binary log, in - bytes from the beginning of the file. In a binlog that is not a - relay log, this is just the position of the next event, in bytes - from the beginning of the file. In a relay log, this is - the position of the next event in the master's binlog. -
flags2 byte bitfieldSee Log_event::flags.
- - Summing up the numbers above, we see that the total size of the - common header is 19 bytes. - - @subsection Log_event_format_of_atomic_primitives Format of Atomic Primitives - - - All numbers, whether they are 16-, 24-, 32-, or 64-bit numbers, - are stored in little endian, i.e., the least significant byte first, - unless otherwise specified. - - @anchor packed_integer - - Some events use a special format for efficient representation of - unsigned integers, called Packed Integer. A Packed Integer has the - capacity of storing up to 8-byte integers, while small integers - still can use 1, 3, or 4 bytes. The value of the first byte - determines how to read the number, according to the following table: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Format of Packed Integer
First byteFormat
0-250The first byte is the number (in the range 0-250), and no more - bytes are used.
252Two more bytes are used. The number is in the range - 251-0xffff.
253Three more bytes are used. The number is in the range - 0xffff-0xffffff.
254Eight more bytes are used. The number is in the range - 0xffffff-0xffffffffffffffff.
- - - Strings are stored in various formats. The format of each string - is documented separately. -*/ -class Log_event -{ -public: - /** - Enumeration of what kinds of skipping (and non-skipping) that can - occur when the slave executes an event. - - @see shall_skip - @see do_shall_skip - */ - enum enum_skip_reason { - /** - Don't skip event. - */ - EVENT_SKIP_NOT, - - /** - Skip event by ignoring it. - - This means that the slave skip counter will not be changed. - */ - EVENT_SKIP_IGNORE, - - /** - Skip event and decrease skip counter. - */ - EVENT_SKIP_COUNT - }; - - enum enum_event_cache_type - { - EVENT_INVALID_CACHE, - /* - If possible the event should use a non-transactional cache before - being flushed to the binary log. This means that it must be flushed - right after its correspondent statement is completed. - */ - EVENT_STMT_CACHE, - /* - The event should use a transactional cache before being flushed to - the binary log. This means that it must be flushed upon commit or - rollback. - */ - EVENT_TRANSACTIONAL_CACHE, - /* - The event must be written directly to the binary log without going - through a cache. - */ - EVENT_NO_CACHE, - /** - If there is a need for different types, introduce them before this. - */ - EVENT_CACHE_COUNT - }; - - /* - The following type definition is to be used whenever data is placed - and manipulated in a common buffer. Use this typedef for buffers - that contain data containing binary and character data. - */ - typedef unsigned char Byte; - - /* - The offset in the log where this event originally appeared (it is - preserved in relay logs, making SHOW SLAVE STATUS able to print - coordinates of the event in the master's binlog). Note: when a - transaction is written by the master to its binlog (wrapped in - BEGIN/COMMIT) the log_pos of all the queries it contains is the - one of the BEGIN (this way, when one does SHOW SLAVE STATUS it - sees the offset of the BEGIN, which is logical as rollback may - occur), except the COMMIT query which has its real offset. - */ - my_off_t log_pos; - /* - A temp buffer for read_log_event; it is later analysed according to the - event's type, and its content is distributed in the event-specific fields. - */ - char *temp_buf; - - /* - TRUE <=> this event 'owns' temp_buf and should call my_free() when done - with it - */ - bool event_owns_temp_buf; - - /* - Timestamp on the master(for debugging and replication of - NOW()/TIMESTAMP). It is important for queries and LOAD DATA - INFILE. This is set at the event's creation time, except for Query - and Load (et al.) events where this is set at the query's - execution time, which guarantees good replication (otherwise, we - could have a query and its event with different timestamps). - */ - my_time_t when; - ulong when_sec_part; - /* The number of seconds the query took to run on the master. */ - ulong exec_time; - /* Number of bytes written by write() function */ - size_t data_written; - - /* - The master's server id (is preserved in the relay log; used to - prevent from infinite loops in circular replication). - */ - uint32 server_id; - - /** - Some 16 flags. See the definitions above for LOG_EVENT_TIME_F, - LOG_EVENT_FORCED_ROTATE_F, LOG_EVENT_THREAD_SPECIFIC_F, - LOG_EVENT_SUPPRESS_USE_F, and LOG_EVENT_SKIP_REPLICATION_F for notes. - */ - uint16 flags; - - enum_event_cache_type cache_type; - - /** - A storage to cache the global system variable's value. - Handling of a separate event will be governed its member. - */ - ulong slave_exec_mode; - - Log_event_writer *writer; - -#ifdef MYSQL_SERVER - THD* thd; - - Log_event(); - Log_event(THD* thd_arg, uint16 flags_arg, bool is_transactional); - - /* - init_show_field_list() prepares the column names and types for the - output of SHOW BINLOG EVENTS; it is used only by SHOW BINLOG - EVENTS. - */ - static void init_show_field_list(THD *thd, List* field_list); -#ifdef HAVE_REPLICATION - int net_send(Protocol *protocol, const char* log_name, my_off_t pos); - - /* - pack_info() is used by SHOW BINLOG EVENTS; as print() it prepares and sends - a string to display to the user, so it resembles print(). - */ - - virtual void pack_info(Protocol *protocol); - -#endif /* HAVE_REPLICATION */ - virtual const char* get_db() - { - return thd ? thd->db.str : 0; - } -#else - Log_event() : temp_buf(0), when(0), flags(0) {} - ha_checksum crc; - /* print*() functions are used by mysqlbinlog */ - virtual bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) = 0; - bool print_timestamp(IO_CACHE* file, time_t *ts = 0); - bool print_header(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info, - bool is_more); - bool print_base64(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info, - bool do_print_encoded); -#endif /* MYSQL_SERVER */ - - /* The following code used for Flashback */ -#ifdef MYSQL_CLIENT - my_bool is_flashback; - my_bool need_flashback_review; - String output_buf; // Storing the event output -#ifdef WHEN_FLASHBACK_REVIEW_READY - String m_review_dbname; - String m_review_tablename; - - void set_review_dbname(const char *name) - { - if (name) - { - m_review_dbname.free(); - m_review_dbname.append(name); - } - } - void set_review_tablename(const char *name) - { - if (name) - { - m_review_tablename.free(); - m_review_tablename.append(name); - } - } - const char *get_review_dbname() const { return m_review_dbname.ptr(); } - const char *get_review_tablename() const { return m_review_tablename.ptr(); } -#endif -#endif - - /* - read_log_event() functions read an event from a binlog or relay - log; used by SHOW BINLOG EVENTS, the binlog_dump thread on the - master (reads master's binlog), the slave IO thread (reads the - event sent by binlog_dump), the slave SQL thread (reads the event - from the relay log). If mutex is 0, the read will proceed without - mutex. We need the description_event to be able to parse the - event (to know the post-header's size); in fact in read_log_event - we detect the event's type, then call the specific event's - constructor and pass description_event as an argument. - */ - static Log_event* read_log_event(IO_CACHE* file, - const Format_description_log_event - *description_event, - my_bool crc_check); - - /** - Reads an event from a binlog or relay log. Used by the dump thread - this method reads the event into a raw buffer without parsing it. - - @Note If mutex is 0, the read will proceed without mutex. - - @Note If a log name is given than the method will check if the - given binlog is still active. - - @param[in] file log file to be read - @param[out] packet packet to hold the event - @param[in] checksum_alg_arg verify the event checksum using this - algorithm (or don't if it's - use BINLOG_CHECKSUM_ALG_OFF) - - @retval 0 success - @retval LOG_READ_EOF end of file, nothing was read - @retval LOG_READ_BOGUS malformed event - @retval LOG_READ_IO io error while reading - @retval LOG_READ_MEM packet memory allocation failed - @retval LOG_READ_TRUNC only a partial event could be read - @retval LOG_READ_TOO_LARGE event too large - */ - static int read_log_event(IO_CACHE* file, String* packet, - const Format_description_log_event *fdle, - enum enum_binlog_checksum_alg checksum_alg_arg); - /* - The value is set by caller of FD constructor and - Log_event::write_header() for the rest. - In the FD case it's propagated into the last byte - of post_header_len[] at FD::write(). - On the slave side the value is assigned from post_header_len[last] - of the last seen FD event. - */ - enum enum_binlog_checksum_alg checksum_alg; - - static void *operator new(size_t size) - { - extern PSI_memory_key key_memory_log_event; - return my_malloc(key_memory_log_event, size, MYF(MY_WME|MY_FAE)); - } - - static void operator delete(void *ptr, size_t) - { - my_free(ptr); - } - - /* Placement version of the above operators */ - static void *operator new(size_t, void* ptr) { return ptr; } - static void operator delete(void*, void*) { } - -#ifdef MYSQL_SERVER - bool write_header(size_t event_data_length); - bool write_data(const uchar *buf, size_t data_length) - { return writer->write_data(buf, data_length); } - bool write_data(const char *buf, size_t data_length) - { return write_data((uchar*)buf, data_length); } - bool write_footer() - { return writer->write_footer(); } - - my_bool need_checksum(); - - virtual bool write() - { - return write_header(get_data_size()) || write_data_header() || - write_data_body() || write_footer(); - } - virtual bool write_data_header() - { return 0; } - virtual bool write_data_body() - { return 0; } - - /* Return start of query time or current time */ - inline my_time_t get_time() - { - THD *tmp_thd; - if (when) - return when; - if (thd) - { - when= thd->start_time; - when_sec_part= thd->start_time_sec_part; - return when; - } - /* thd will only be 0 here at time of log creation */ - if ((tmp_thd= current_thd)) - { - when= tmp_thd->start_time; - when_sec_part= tmp_thd->start_time_sec_part; - return when; - } - my_hrtime_t hrtime= my_hrtime(); - when= hrtime_to_my_time(hrtime); - when_sec_part= hrtime_sec_part(hrtime); - return when; - } -#endif - virtual Log_event_type get_type_code() = 0; - virtual enum_logged_status logged_status() { return LOGGED_CRITICAL; } - virtual bool is_valid() const = 0; - virtual my_off_t get_header_len(my_off_t len) { return len; } - void set_artificial_event() { flags |= LOG_EVENT_ARTIFICIAL_F; } - void set_relay_log_event() { flags |= LOG_EVENT_RELAY_LOG_F; } - bool is_artificial_event() const { return flags & LOG_EVENT_ARTIFICIAL_F; } - bool is_relay_log_event() const { return flags & LOG_EVENT_RELAY_LOG_F; } - inline bool use_trans_cache() const - { - return (cache_type == Log_event::EVENT_TRANSACTIONAL_CACHE); - } - inline void set_direct_logging() - { - cache_type = Log_event::EVENT_NO_CACHE; - } - inline bool use_direct_logging() - { - return (cache_type == Log_event::EVENT_NO_CACHE); - } - Log_event(const char* buf, const Format_description_log_event - *description_event); - virtual ~Log_event() { free_temp_buf();} - void register_temp_buf(char* buf, bool must_free) - { - temp_buf= buf; - event_owns_temp_buf= must_free; - } - void free_temp_buf() - { - if (temp_buf) - { - if (event_owns_temp_buf) - my_free(temp_buf); - temp_buf = 0; - } - } - /* - Get event length for simple events. For complicated events the length - is calculated during write() - */ - virtual int get_data_size() { return 0;} - static Log_event* read_log_event(const char* buf, uint event_len, - const char **error, - const Format_description_log_event - *description_event, my_bool crc_check); - /** - Returns the human readable name of the given event type. - */ - static const char* get_type_str(Log_event_type type); - /** - Returns the human readable name of this event's type. - */ - const char* get_type_str(); - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - - /** - Apply the event to the database. - - This function represents the public interface for applying an - event. - - @see do_apply_event - */ - int apply_event(rpl_group_info *rgi) - { - int res; - THD_STAGE_INFO(thd, stage_apply_event); - res= do_apply_event(rgi); - THD_STAGE_INFO(thd, stage_after_apply_event); - return res; - } - - - /** - Update the relay log position. - - This function represents the public interface for "stepping over" - the event and will update the relay log information. - - @see do_update_pos - */ - int update_pos(rpl_group_info *rgi) - { - return do_update_pos(rgi); - } - - /** - Decide if the event shall be skipped, and the reason for skipping - it. - - @see do_shall_skip - */ - enum_skip_reason shall_skip(rpl_group_info *rgi) - { - return do_shall_skip(rgi); - } - - - /* - Check if an event is non-final part of a stand-alone event group, - such as Intvar_log_event (such events should be processed as part - of the following event group, not individually). - See also is_part_of_group() - */ - static bool is_part_of_group(enum Log_event_type ev_type) - { - switch (ev_type) - { - case GTID_EVENT: - case INTVAR_EVENT: - case RAND_EVENT: - case USER_VAR_EVENT: - case TABLE_MAP_EVENT: - case ANNOTATE_ROWS_EVENT: - return true; - case DELETE_ROWS_EVENT: - case UPDATE_ROWS_EVENT: - case WRITE_ROWS_EVENT: - /* - ToDo: also check for non-final Rows_log_event (though such events - are usually in a BEGIN-COMMIT group). - */ - default: - return false; - } - } - /* - Same as above, but works on the object. In addition this is true for all - rows event except the last one. - */ - virtual bool is_part_of_group() { return 0; } - - static bool is_group_event(enum Log_event_type ev_type) - { - switch (ev_type) - { - case START_EVENT_V3: - case STOP_EVENT: - case ROTATE_EVENT: - case SLAVE_EVENT: - case FORMAT_DESCRIPTION_EVENT: - case INCIDENT_EVENT: - case HEARTBEAT_LOG_EVENT: - case BINLOG_CHECKPOINT_EVENT: - case GTID_LIST_EVENT: - case START_ENCRYPTION_EVENT: - return false; - - default: - return true; - } - } - -protected: - - /** - Helper function to ignore an event w.r.t. the slave skip counter. - - This function can be used inside do_shall_skip() for functions - that cannot end a group. If the slave skip counter is 1 when - seeing such an event, the event shall be ignored, the counter - left intact, and processing continue with the next event. - - A typical usage is: - @code - enum_skip_reason do_shall_skip(rpl_group_info *rgi) { - return continue_group(rgi); - } - @endcode - - @return Skip reason - */ - enum_skip_reason continue_group(rpl_group_info *rgi); - - /** - Primitive to apply an event to the database. - - This is where the change to the database is made. - - @note The primitive is protected instead of private, since there - is a hierarchy of actions to be performed in some cases. - - @see Format_description_log_event::do_apply_event() - - @param rli Pointer to relay log info structure - - @retval 0 Event applied successfully - @retval errno Error code if event application failed - */ - virtual int do_apply_event(rpl_group_info *rgi) - { - return 0; /* Default implementation does nothing */ - } - - - /** - Advance relay log coordinates. - - This function is called to advance the relay log coordinates to - just after the event. It is essential that both the relay log - coordinate and the group log position is updated correctly, since - this function is used also for skipping events. - - Normally, each implementation of do_update_pos() shall: - - - Update the event position to refer to the position just after - the event. - - - Update the group log position to refer to the position just - after the event if the event is last in a group - - @param rli Pointer to relay log info structure - - @retval 0 Coordinates changed successfully - @retval errno Error code if advancing failed (usually just - 1). Observe that handler errors are returned by the - do_apply_event() function, and not by this one. - */ - virtual int do_update_pos(rpl_group_info *rgi); - - - /** - Decide if this event shall be skipped or not and the reason for - skipping it. - - The default implementation decide that the event shall be skipped - if either: - - - the server id of the event is the same as the server id of the - server and rli->replicate_same_server_id is true, - or - - - if rli->slave_skip_counter is greater than zero. - - @see do_apply_event - @see do_update_pos - - @retval Log_event::EVENT_SKIP_NOT - The event shall not be skipped and should be applied. - - @retval Log_event::EVENT_SKIP_IGNORE - The event shall be skipped by just ignoring it, i.e., the slave - skip counter shall not be changed. This happends if, for example, - the originating server id of the event is the same as the server - id of the slave. - - @retval Log_event::EVENT_SKIP_COUNT - The event shall be skipped because the slave skip counter was - non-zero. The caller shall decrease the counter by one. - */ - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -/* - One class for each type of event. - Two constructors for each class: - - one to create the event for logging (when the server acts as a master), - called after an update to the database is done, - which accepts parameters like the query, the database, the options for LOAD - DATA INFILE... - - one to create the event from a packet (when the server acts as a slave), - called before reproducing the update, which accepts parameters (like a - buffer). Used to read from the master, from the relay log, and in - mysqlbinlog. This constructor must be format-tolerant. -*/ - -/** - @class Query_log_event - - A @c Query_log_event is created for each query that modifies the - database, unless the query is logged row-based. - - @section Query_log_event_binary_format Binary format - - See @ref Log_event_binary_format "Binary format for log events" for - a general discussion and introduction to the binary format of binlog - events. - - The Post-Header has five components: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Post-Header for Query_log_event
NameFormatDescription
slave_proxy_id4 byte unsigned integerAn integer identifying the client thread that issued the - query. The id is unique per server. (Note, however, that two - threads on different servers may have the same slave_proxy_id.) - This is used when a client thread creates a temporary table local - to the client. The slave_proxy_id is used to distinguish - temporary tables that belong to different clients. -
exec_time4 byte unsigned integerThe time from when the query started to when it was logged in - the binlog, in seconds.
db_len1 byte integerThe length of the name of the currently selected database.
error_code2 byte unsigned integerError code generated by the master. If the master fails, the - slave will fail with the same error code, except for the error - codes ER_DB_CREATE_EXISTS == 1007 and ER_DB_DROP_EXISTS == 1008. -
status_vars_len2 byte unsigned integerThe length of the status_vars block of the Body, in bytes. See - @ref query_log_event_status_vars "below". -
- - The Body has the following components: - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Body for Query_log_event
NameFormatDescription
@anchor query_log_event_status_vars status_varsstatus_vars_len bytesZero or more status variables. Each status variable consists - of one byte identifying the variable stored, followed by the value - of the variable. The possible variables are listed separately in - the table @ref Table_query_log_event_status_vars "below". MySQL - always writes events in the order defined below; however, it is - capable of reading them in any order.
dbdb_len+1The currently selected database, as a null-terminated string. - - (The trailing zero is redundant since the length is already known; - it is db_len from Post-Header.) -
queryvariable length string without trailing zero, extending to the - end of the event (determined by the length field of the - Common-Header) - The SQL query.
- - The following table lists the status variables that may appear in - the status_vars field. - - @anchor Table_query_log_event_status_vars - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Status variables for Query_log_event
Status variable1 byte identifierFormatDescription
flags2Q_FLAGS2_CODE == 04 byte bitfieldThe flags in @c thd->options, binary AND-ed with @c - OPTIONS_WRITTEN_TO_BIN_LOG. The @c thd->options bitfield contains - options for "SELECT". @c OPTIONS_WRITTEN identifies those options - that need to be written to the binlog (not all do). Specifically, - @c OPTIONS_WRITTEN_TO_BIN_LOG equals (@c OPTION_AUTO_IS_NULL | @c - OPTION_NO_FOREIGN_KEY_CHECKS | @c OPTION_RELAXED_UNIQUE_CHECKS | - @c OPTION_NOT_AUTOCOMMIT), or 0x0c084000 in hex. - - These flags correspond to the SQL variables SQL_AUTO_IS_NULL, - FOREIGN_KEY_CHECKS, UNIQUE_CHECKS, and AUTOCOMMIT, documented in - the "SET Syntax" section of the MySQL Manual. - - This field is always written to the binlog in version >= 5.0, and - never written in version < 5.0. -
sql_modeQ_SQL_MODE_CODE == 18 byte bitfieldThe @c sql_mode variable. See the section "SQL Modes" in the - MySQL manual, and see sql_priv.h for a list of the possible - flags. Currently (2007-10-04), the following flags are available: -
-    MODE_REAL_AS_FLOAT==0x1
-    MODE_PIPES_AS_CONCAT==0x2
-    MODE_ANSI_QUOTES==0x4
-    MODE_IGNORE_SPACE==0x8
-    MODE_IGNORE_BAD_TABLE_OPTIONS==0x10
-    MODE_ONLY_FULL_GROUP_BY==0x20
-    MODE_NO_UNSIGNED_SUBTRACTION==0x40
-    MODE_NO_DIR_IN_CREATE==0x80
-    MODE_POSTGRESQL==0x100
-    MODE_ORACLE==0x200
-    MODE_MSSQL==0x400
-    MODE_DB2==0x800
-    MODE_MAXDB==0x1000
-    MODE_NO_KEY_OPTIONS==0x2000
-    MODE_NO_TABLE_OPTIONS==0x4000
-    MODE_NO_FIELD_OPTIONS==0x8000
-    MODE_MYSQL323==0x10000
-    MODE_MYSQL323==0x20000
-    MODE_MYSQL40==0x40000
-    MODE_ANSI==0x80000
-    MODE_NO_AUTO_VALUE_ON_ZERO==0x100000
-    MODE_NO_BACKSLASH_ESCAPES==0x200000
-    MODE_STRICT_TRANS_TABLES==0x400000
-    MODE_STRICT_ALL_TABLES==0x800000
-    MODE_NO_ZERO_IN_DATE==0x1000000
-    MODE_NO_ZERO_DATE==0x2000000
-    MODE_INVALID_DATES==0x4000000
-    MODE_ERROR_FOR_DIVISION_BY_ZERO==0x8000000
-    MODE_TRADITIONAL==0x10000000
-    MODE_NO_AUTO_CREATE_USER==0x20000000
-    MODE_HIGH_NOT_PRECEDENCE==0x40000000
-    MODE_PAD_CHAR_TO_FULL_LENGTH==0x80000000
-    
- All these flags are replicated from the server. However, all - flags except @c MODE_NO_DIR_IN_CREATE are honored by the slave; - the slave always preserves its old value of @c - MODE_NO_DIR_IN_CREATE. For a rationale, see comment in - @c Query_log_event::do_apply_event in @c log_event.cc. - - This field is always written to the binlog. -
catalogQ_CATALOG_NZ_CODE == 6Variable-length string: the length in bytes (1 byte) followed - by the characters (at most 255 bytes) - Stores the client's current catalog. Every database belongs - to a catalog, the same way that every table belongs to a - database. Currently, there is only one catalog, "std". - - This field is written if the length of the catalog is > 0; - otherwise it is not written. -
auto_incrementQ_AUTO_INCREMENT == 3two 2 byte unsigned integers, totally 2+2=4 bytesThe two variables auto_increment_increment and - auto_increment_offset, in that order. For more information, see - "System variables" in the MySQL manual. - - This field is written if auto_increment > 1. Otherwise, it is not - written. -
charsetQ_CHARSET_CODE == 4three 2 byte unsigned integers, totally 2+2+2=6 bytesThe three variables character_set_client, - collation_connection, and collation_server, in that order. - character_set_client is a code identifying the character set and - collation used by the client to encode the query. - collation_connection identifies the character set and collation - that the master converts the query to when it receives it; this is - useful when comparing literal strings. collation_server is the - default character set and collation used when a new database is - created. - - See also "Connection Character Sets and Collations" in the MySQL - 5.1 manual. - - All three variables are codes identifying a (character set, - collation) pair. To see which codes map to which pairs, run the - query "SELECT id, character_set_name, collation_name FROM - COLLATIONS". - - Cf. Q_CHARSET_DATABASE_CODE below. - - This field is always written. -
time_zoneQ_TIME_ZONE_CODE == 5Variable-length string: the length in bytes (1 byte) followed - by the characters (at most 255 bytes). - The time_zone of the master. - - See also "System Variables" and "MySQL Server Time Zone Support" - in the MySQL manual. - - This field is written if the length of the time zone string is > - 0; otherwise, it is not written. -
lc_time_names_numberQ_LC_TIME_NAMES_CODE == 72 byte integerA code identifying a table of month and day names. The - mapping from codes to languages is defined in @c sql_locale.cc. - - This field is written if it is not 0, i.e., if the locale is not - en_US. -
charset_database_numberQ_CHARSET_DATABASE_CODE == 82 byte integerThe value of the collation_database system variable (in the - source code stored in @c thd->variables.collation_database), which - holds the code for a (character set, collation) pair as described - above (see Q_CHARSET_CODE). - - collation_database was used in old versions (???WHEN). Its value - was loaded when issuing a "use db" query and could be changed by - issuing a "SET collation_database=xxx" query. It used to affect - the "LOAD DATA INFILE" and "CREATE TABLE" commands. - - In newer versions, "CREATE TABLE" has been changed to take the - character set from the database of the created table, rather than - the character set of the current database. This makes a - difference when creating a table in another database than the - current one. "LOAD DATA INFILE" has not yet changed to do this, - but there are plans to eventually do it, and to make - collation_database read-only. - - This field is written if it is not 0. -
table_map_for_updateQ_TABLE_MAP_FOR_UPDATE_CODE == 98 byte integerThe value of the table map that is to be updated by the - multi-table update query statement. Every bit of this variable - represents a table, and is set to 1 if the corresponding table is - to be updated by this statement. - - The value of this variable is set when executing a multi-table update - statement and used by slave to apply filter rules without opening - all the tables on slave. This is required because some tables may - not exist on slave because of the filter rules. -
- - @subsection Query_log_event_notes_on_previous_versions Notes on Previous Versions - - * Status vars were introduced in version 5.0. To read earlier - versions correctly, check the length of the Post-Header. - - * The status variable Q_CATALOG_CODE == 2 existed in MySQL 5.0.x, - where 0<=x<=3. It was identical to Q_CATALOG_CODE, except that the - string had a trailing '\0'. The '\0' was removed in 5.0.4 since it - was redundant (the string length is stored before the string). The - Q_CATALOG_CODE will never be written by a new master, but can still - be understood by a new slave. - - * See Q_CHARSET_DATABASE_CODE in the table above. - - * When adding new status vars, please don't forget to update the - MAX_SIZE_LOG_EVENT_STATUS, and update function code_name - -*/ -class Query_log_event: public Log_event -{ - LEX_CSTRING user; - LEX_CSTRING host; -protected: - Log_event::Byte* data_buf; -public: - const char* query; - const char* catalog; - const char* db; - /* - If we already know the length of the query string - we pass it with q_len, so we would not have to call strlen() - otherwise, set it to 0, in which case, we compute it with strlen() - */ - uint32 q_len; - uint32 db_len; - uint16 error_code; - my_thread_id thread_id; - /* - For events created by Query_log_event::do_apply_event (and - Load_log_event::do_apply_event()) we need the *original* thread - id, to be able to log the event with the original (=master's) - thread id (fix for BUG#1686). - */ - ulong slave_proxy_id; - - /* - Binlog format 3 and 4 start to differ (as far as class members are - concerned) from here. - */ - - uint catalog_len; // <= 255 char; 0 means uninited - - /* - We want to be able to store a variable number of N-bit status vars: - (generally N=32; but N=64 for SQL_MODE) a user may want to log the number - of affected rows (for debugging) while another does not want to lose 4 - bytes in this. - The storage on disk is the following: - status_vars_len is part of the post-header, - status_vars are in the variable-length part, after the post-header, before - the db & query. - status_vars on disk is a sequence of pairs (code, value) where 'code' means - 'sql_mode', 'affected' etc. Sometimes 'value' must be a short string, so - its first byte is its length. For now the order of status vars is: - flags2 - sql_mode - catalog - autoinc - charset - We should add the same thing to Load_log_event, but in fact - LOAD DATA INFILE is going to be logged with a new type of event (logging of - the plain text query), so Load_log_event would be frozen, so no need. The - new way of logging LOAD DATA INFILE would use a derived class of - Query_log_event, so automatically benefit from the work already done for - status variables in Query_log_event. - */ - uint16 status_vars_len; - - /* - 'flags2' is a second set of flags (on top of those in Log_event), for - session variables. These are thd->options which is & against a mask - (OPTIONS_WRITTEN_TO_BIN_LOG). - flags2_inited helps make a difference between flags2==0 (3.23 or 4.x - master, we don't know flags2, so use the slave server's global options) and - flags2==0 (5.0 master, we know this has a meaning of flags all down which - must influence the query). - */ - bool flags2_inited; - bool sql_mode_inited; - bool charset_inited; - - uint32 flags2; - sql_mode_t sql_mode; - ulong auto_increment_increment, auto_increment_offset; - char charset[6]; - uint time_zone_len; /* 0 means uninited */ - const char *time_zone_str; - uint lc_time_names_number; /* 0 means en_US */ - uint charset_database_number; - /* - map for tables that will be updated for a multi-table update query - statement, for other query statements, this will be zero. - */ - ulonglong table_map_for_update; - /* - Holds the original length of a Query_log_event that comes from a - master of version < 5.0 (i.e., binlog_version < 4). When the IO - thread writes the relay log, it augments the Query_log_event with a - Q_MASTER_DATA_WRITTEN_CODE status_var that holds the original event - length. This field is initialized to non-zero in the SQL thread when - it reads this augmented event. SQL thread does not write - Q_MASTER_DATA_WRITTEN_CODE to the slave's server binlog. - */ - uint32 master_data_written; - -#ifdef MYSQL_SERVER - - Query_log_event(THD* thd_arg, const char* query_arg, size_t query_length, - bool using_trans, bool direct, bool suppress_use, int error); - const char* get_db() { return db; } -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print_query_header(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info); - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Query_log_event(); - Query_log_event(const char* buf, uint event_len, - const Format_description_log_event *description_event, - Log_event_type event_type); - ~Query_log_event() - { - if (data_buf) - my_free(data_buf); - } - Log_event_type get_type_code() { return QUERY_EVENT; } - static int dummy_event(String *packet, ulong ev_offset, enum enum_binlog_checksum_alg checksum_alg); - static int begin_event(String *packet, ulong ev_offset, enum enum_binlog_checksum_alg checksum_alg); -#ifdef MYSQL_SERVER - bool write(); - virtual bool write_post_header_for_derived() { return FALSE; } -#endif - bool is_valid() const { return query != 0; } - - /* - Returns number of bytes additionally written to post header by derived - events (so far it is only Execute_load_query event). - */ - virtual ulong get_post_header_size_for_derived() { return 0; } - /* Writes derived event-specific part of post header. */ - -public: /* !!! Public in this patch to allow old usage */ -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); - virtual int do_apply_event(rpl_group_info *rgi); - - int do_apply_event(rpl_group_info *rgi, - const char *query_arg, - uint32 q_len_arg); - static bool peek_is_commit_rollback(const char *event_start, - size_t event_len, enum enum_binlog_checksum_alg checksum_alg); -#endif /* HAVE_REPLICATION */ - /* - If true, the event always be applied by slave SQL thread or be printed by - mysqlbinlog - */ - bool is_trans_keyword() - { - /* - Before the patch for bug#50407, The 'SAVEPOINT and ROLLBACK TO' - queries input by user was written into log events directly. - So the keywords can be written in both upper case and lower case - together, strncasecmp is used to check both cases. they also could be - binlogged with comments in the front of these keywords. for examples: - / * bla bla * / SAVEPOINT a; - / * bla bla * / ROLLBACK TO a; - but we don't handle these cases and after the patch, both quiries are - binlogged in upper case with no comments. - */ - return !strncmp(query, "BEGIN", q_len) || - !strncmp(query, "COMMIT", q_len) || - !strncasecmp(query, "SAVEPOINT", 9) || - !strncasecmp(query, "ROLLBACK", 8); - } - virtual bool is_begin() { return !strcmp(query, "BEGIN"); } - virtual bool is_commit() { return !strcmp(query, "COMMIT"); } - virtual bool is_rollback() { return !strcmp(query, "ROLLBACK"); } -}; - -class Query_compressed_log_event:public Query_log_event{ -protected: - Log_event::Byte* query_buf; // point to the uncompressed query -public: - Query_compressed_log_event(const char* buf, uint event_len, - const Format_description_log_event *description_event, - Log_event_type event_type); - ~Query_compressed_log_event() - { - if (query_buf) - my_free(query_buf); - } - Log_event_type get_type_code() { return QUERY_COMPRESSED_EVENT; } - - /* - the min length of log_bin_compress_min_len is 10, - means that Begin/Commit/Rollback would never be compressed! - */ - virtual bool is_begin() { return false; } - virtual bool is_commit() { return false; } - virtual bool is_rollback() { return false; } -#ifdef MYSQL_SERVER - Query_compressed_log_event(THD* thd_arg, const char* query_arg, - ulong query_length, - bool using_trans, bool direct, bool suppress_use, - int error); - virtual bool write(); -#endif -}; - - -/***************************************************************************** - sql_ex_info struct - ****************************************************************************/ -struct sql_ex_info -{ - const char* field_term; - const char* enclosed; - const char* line_term; - const char* line_start; - const char* escaped; - int cached_new_format= -1; - uint8 field_term_len= 0, enclosed_len= 0, line_term_len= 0, - line_start_len= 0, escaped_len= 0; - char opt_flags; - char empty_flags= 0; - - // store in new format even if old is possible - void force_new_format() { cached_new_format = 1;} - int data_size() - { - return (new_format() ? - field_term_len + enclosed_len + line_term_len + - line_start_len + escaped_len + 6 : 7); - } - bool write_data(Log_event_writer *writer); - const char* init(const char* buf, const char* buf_end, bool use_new_format); - bool new_format() - { - return ((cached_new_format != -1) ? cached_new_format : - (cached_new_format=(field_term_len > 1 || - enclosed_len > 1 || - line_term_len > 1 || line_start_len > 1 || - escaped_len > 1))); - } -}; - -/** - @class Load_log_event - - This log event corresponds to a "LOAD DATA INFILE" SQL query on the - following form: - - @verbatim - (1) USE db; - (2) LOAD DATA [CONCURRENT] [LOCAL] INFILE 'file_name' - (3) [REPLACE | IGNORE] - (4) INTO TABLE 'table_name' - (5) [FIELDS - (6) [TERMINATED BY 'field_term'] - (7) [[OPTIONALLY] ENCLOSED BY 'enclosed'] - (8) [ESCAPED BY 'escaped'] - (9) ] - (10) [LINES - (11) [TERMINATED BY 'line_term'] - (12) [LINES STARTING BY 'line_start'] - (13) ] - (14) [IGNORE skip_lines LINES] - (15) (field_1, field_2, ..., field_n)@endverbatim - - @section Load_log_event_binary_format Binary Format - - The Post-Header consists of the following six components. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Post-Header for Load_log_event
NameFormatDescription
slave_proxy_id4 byte unsigned integerAn integer identifying the client thread that issued the - query. The id is unique per server. (Note, however, that two - threads on different servers may have the same slave_proxy_id.) - This is used when a client thread creates a temporary table local - to the client. The slave_proxy_id is used to distinguish - temporary tables that belong to different clients. -
exec_time4 byte unsigned integerThe time from when the query started to when it was logged in - the binlog, in seconds.
skip_lines4 byte unsigned integerThe number on line (14) above, if present, or 0 if line (14) - is left out. -
table_name_len1 byte unsigned integerThe length of 'table_name' on line (4) above.
db_len1 byte unsigned integerThe length of 'db' on line (1) above.
num_fields4 byte unsigned integerThe number n of fields on line (15) above.
- - The Body contains the following components. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Body of Load_log_event
NameFormatDescription
sql_exvariable lengthDescribes the part of the query on lines (3) and - (5)–(13) above. More precisely, it stores the five strings - (on lines) field_term (6), enclosed (7), escaped (8), line_term - (11), and line_start (12); as well as a bitfield indicating the - presence of the keywords REPLACE (3), IGNORE (3), and OPTIONALLY - (7). - - The data is stored in one of two formats, called "old" and "new". - The type field of Common-Header determines which of these two - formats is used: type LOAD_EVENT means that the old format is - used, and type NEW_LOAD_EVENT means that the new format is used. - When MySQL writes a Load_log_event, it uses the new format if at - least one of the five strings is two or more bytes long. - Otherwise (i.e., if all strings are 0 or 1 bytes long), the old - format is used. - - The new and old format differ in the way the five strings are - stored. - -
    -
  • In the new format, the strings are stored in the order - field_term, enclosed, escaped, line_term, line_start. Each string - consists of a length (1 byte), followed by a sequence of - characters (0-255 bytes). Finally, a boolean combination of the - following flags is stored in 1 byte: REPLACE_FLAG==0x4, - IGNORE_FLAG==0x8, and OPT_ENCLOSED_FLAG==0x2. If a flag is set, - it indicates the presence of the corresponding keyword in the SQL - query. - -
  • In the old format, we know that each string has length 0 or - 1. Therefore, only the first byte of each string is stored. The - order of the strings is the same as in the new format. These five - bytes are followed by the same 1 byte bitfield as in the new - format. Finally, a 1 byte bitfield called empty_flags is stored. - The low 5 bits of empty_flags indicate which of the five strings - have length 0. For each of the following flags that is set, the - corresponding string has length 0; for the flags that are not set, - the string has length 1: FIELD_TERM_EMPTY==0x1, - ENCLOSED_EMPTY==0x2, LINE_TERM_EMPTY==0x4, LINE_START_EMPTY==0x8, - ESCAPED_EMPTY==0x10. -
- - Thus, the size of the new format is 6 bytes + the sum of the sizes - of the five strings. The size of the old format is always 7 - bytes. -
field_lensnum_fields 1 byte unsigned integersAn array of num_fields integers representing the length of - each field in the query. (num_fields is from the Post-Header). -
fieldsnum_fields null-terminated stringsAn array of num_fields null-terminated strings, each - representing a field in the query. (The trailing zero is - redundant, since the length are stored in the num_fields array.) - The total length of all strings equals to the sum of all - field_lens, plus num_fields bytes for all the trailing zeros. -
table_namenull-terminated string of length table_len+1 bytesThe 'table_name' from the query, as a null-terminated string. - (The trailing zero is actually redundant since the table_len is - known from Post-Header.) -
dbnull-terminated string of length db_len+1 bytesThe 'db' from the query, as a null-terminated string. - (The trailing zero is actually redundant since the db_len is known - from Post-Header.) -
file_namevariable length string without trailing zero, extending to the - end of the event (determined by the length field of the - Common-Header) - The 'file_name' from the query. -
- - @subsection Load_log_event_notes_on_previous_versions Notes on Previous Versions - - This event type is understood by current versions, but only - generated by MySQL 3.23 and earlier. -*/ -class Load_log_event: public Log_event -{ -private: -protected: - int copy_log_event(const char *buf, ulong event_len, - int body_offset, - const Format_description_log_event* description_event); - -public: - bool print_query(THD *thd, bool need_db, const char *cs, String *buf, - my_off_t *fn_start, my_off_t *fn_end, - const char *qualify_db); - my_thread_id thread_id; - ulong slave_proxy_id; - uint32 table_name_len; - /* - No need to have a catalog, as these events can only come from 4.x. - TODO: this may become false if Dmitri pushes his new LOAD DATA INFILE in - 5.0 only (not in 4.x). - */ - uint32 db_len; - uint32 fname_len; - uint32 num_fields; - const char* fields; - const uchar* field_lens; - uint32 field_block_len; - - const char* table_name; - const char* db; - const char* fname; - uint32 skip_lines; - sql_ex_info sql_ex; - bool local_fname; - /** - Indicates that this event corresponds to LOAD DATA CONCURRENT, - - @note Since Load_log_event event coming from the binary log - lacks information whether LOAD DATA on master was concurrent - or not, this flag is only set to TRUE for an auxiliary - Load_log_event object which is used in mysql_load() to - re-construct LOAD DATA statement from function parameters, - for logging. - */ - bool is_concurrent; - - /* fname doesn't point to memory inside Log_event::temp_buf */ - void set_fname_outside_temp_buf(const char *afname, size_t alen) - { - fname= afname; - fname_len= (uint)alen; - local_fname= TRUE; - } - /* fname doesn't point to memory inside Log_event::temp_buf */ - int check_fname_outside_temp_buf() - { - return local_fname; - } - -#ifdef MYSQL_SERVER - String field_lens_buf; - String fields_buf; - - Load_log_event(THD* thd, const sql_exchange* ex, const char* db_arg, - const char* table_name_arg, - List& fields_arg, - bool is_concurrent_arg, - enum enum_duplicates handle_dup, bool ignore, - bool using_trans); - void set_fields(const char* db, List &fields_arg, - Name_resolution_context *context); - const char* get_db() { return db; } -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, bool commented); -#endif - - /* - Note that for all the events related to LOAD DATA (Load_log_event, - Create_file/Append/Exec/Delete, we pass description_event; however as - logging of LOAD DATA is going to be changed in 4.1 or 5.0, this is only used - for the common_header_len (post_header_len will not be changed). - */ - Load_log_event(const char* buf, uint event_len, - const Format_description_log_event* description_event); - ~Load_log_event() - {} - Log_event_type get_type_code() - { - return sql_ex.new_format() ? NEW_LOAD_EVENT: LOAD_EVENT; - } -#ifdef MYSQL_SERVER - bool write_data_header(); - bool write_data_body(); -#endif - bool is_valid() const { return table_name != 0; } - int get_data_size() - { - return (table_name_len + db_len + 2 + fname_len - + LOAD_HEADER_LEN - + sql_ex.data_size() + field_block_len + num_fields); - } - -public: /* !!! Public in this patch to allow old usage */ -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi) - { - return do_apply_event(thd->slave_net,rgi,0); - } - - int do_apply_event(NET *net, rpl_group_info *rgi, - bool use_rli_only_for_errors); -#endif -}; - -/** - @class Start_log_event_v3 - - Start_log_event_v3 is the Start_log_event of binlog format 3 (MySQL 3.23 and - 4.x). - - Format_description_log_event derives from Start_log_event_v3; it is - the Start_log_event of binlog format 4 (MySQL 5.0), that is, the - event that describes the other events' Common-Header/Post-Header - lengths. This event is sent by MySQL 5.0 whenever it starts sending - a new binlog if the requested position is >4 (otherwise if ==4 the - event will be sent naturally). - - @section Start_log_event_v3_binary_format Binary Format -*/ -class Start_log_event_v3: public Log_event -{ -public: - /* - If this event is at the start of the first binary log since server - startup 'created' should be the timestamp when the event (and the - binary log) was created. In the other case (i.e. this event is at - the start of a binary log created by FLUSH LOGS or automatic - rotation), 'created' should be 0. This "trick" is used by MySQL - >=4.0.14 slaves to know whether they must drop stale temporary - tables and whether they should abort unfinished transaction. - - Note that when 'created'!=0, it is always equal to the event's - timestamp; indeed Start_log_event is written only in log.cc where - the first constructor below is called, in which 'created' is set - to 'when'. So in fact 'created' is a useless variable. When it is - 0 we can read the actual value from timestamp ('when') and when it - is non-zero we can read the same value from timestamp - ('when'). Conclusion: - - we use timestamp to print when the binlog was created. - - we use 'created' only to know if this is a first binlog or not. - In 3.23.57 we did not pay attention to this identity, so mysqlbinlog in - 3.23.57 does not print 'created the_date' if created was zero. This is now - fixed. - */ - time_t created; - uint16 binlog_version; - char server_version[ST_SERVER_VER_LEN]; - /* - We set this to 1 if we don't want to have the created time in the log, - which is the case when we rollover to a new log. - */ - bool dont_set_created; - -#ifdef MYSQL_SERVER - Start_log_event_v3(); -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - Start_log_event_v3() {} - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Start_log_event_v3(const char* buf, uint event_len, - const Format_description_log_event* description_event); - ~Start_log_event_v3() {} - Log_event_type get_type_code() { return START_EVENT_V3;} - my_off_t get_header_len(my_off_t l __attribute__((unused))) - { return LOG_EVENT_MINIMAL_HEADER_LEN; } -#ifdef MYSQL_SERVER - bool write(); -#endif - bool is_valid() const { return server_version[0] != 0; } - int get_data_size() - { - return START_V3_HEADER_LEN; //no variable-sized part - } - -protected: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info*) - { - /* - Events from ourself should be skipped, but they should not - decrease the slave skip counter. - */ - if (this->server_id == global_system_variables.server_id) - return Log_event::EVENT_SKIP_IGNORE; - else - return Log_event::EVENT_SKIP_NOT; - } -#endif -}; - -/** - @class Start_encryption_log_event - - Start_encryption_log_event marks the beginning of encrypted data (all events - after this event are encrypted). - - It contains the cryptographic scheme used for the encryption as well as any - data required to decrypt (except the actual key). - - For binlog cryptoscheme 1: key version, and nonce for iv generation. -*/ -class Start_encryption_log_event : public Log_event -{ -public: -#ifdef MYSQL_SERVER - Start_encryption_log_event(uint crypto_scheme_arg, uint key_version_arg, - const uchar* nonce_arg) - : crypto_scheme(crypto_scheme_arg), key_version(key_version_arg) - { - cache_type = EVENT_NO_CACHE; - DBUG_ASSERT(crypto_scheme == 1); - memcpy(nonce, nonce_arg, BINLOG_NONCE_LENGTH); - } - - bool write_data_body() - { - uchar scheme_buf= crypto_scheme; - uchar key_version_buf[BINLOG_KEY_VERSION_LENGTH]; - int4store(key_version_buf, key_version); - return write_data(&scheme_buf, sizeof(scheme_buf)) || - write_data(key_version_buf, sizeof(key_version_buf)) || - write_data(nonce, BINLOG_NONCE_LENGTH); - } -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Start_encryption_log_event( - const char* buf, uint event_len, - const Format_description_log_event* description_event); - - bool is_valid() const { return crypto_scheme == 1; } - - Log_event_type get_type_code() { return START_ENCRYPTION_EVENT; } - - int get_data_size() - { - return BINLOG_CRYPTO_SCHEME_LENGTH + BINLOG_KEY_VERSION_LENGTH + - BINLOG_NONCE_LENGTH; - } - - uint crypto_scheme; - uint key_version; - uchar nonce[BINLOG_NONCE_LENGTH]; - -protected: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info* rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info* rgi) - { - return Log_event::EVENT_SKIP_NOT; - } -#endif - -}; - - -class Version -{ -protected: - uchar m_ver[3]; - int cmp(const Version &other) const - { - return memcmp(m_ver, other.m_ver, 3); - } -public: - Version() - { - m_ver[0]= m_ver[1]= m_ver[2]= '\0'; - } - Version(uchar v0, uchar v1, uchar v2) - { - m_ver[0]= v0; - m_ver[1]= v1; - m_ver[2]= v2; - } - Version(const char *version, const char **endptr); - const uchar& operator [] (size_t i) const - { - DBUG_ASSERT(i < 3); - return m_ver[i]; - } - bool operator<(const Version &other) const { return cmp(other) < 0; } - bool operator>(const Version &other) const { return cmp(other) > 0; } - bool operator<=(const Version &other) const { return cmp(other) <= 0; } - bool operator>=(const Version &other) const { return cmp(other) >= 0; } -}; - - -/** - @class Format_description_log_event - - For binlog version 4. - This event is saved by threads which read it, as they need it for future - use (to decode the ordinary events). - - @section Format_description_log_event_binary_format Binary Format -*/ - -class Format_description_log_event: public Start_log_event_v3 -{ -public: - /* - The size of the fixed header which _all_ events have - (for binlogs written by this version, this is equal to - LOG_EVENT_HEADER_LEN), except FORMAT_DESCRIPTION_EVENT and ROTATE_EVENT - (those have a header of size LOG_EVENT_MINIMAL_HEADER_LEN). - */ - uint8 common_header_len; - uint8 number_of_event_types; - /* - The list of post-headers' lengths followed - by the checksum alg description byte - */ - uint8 *post_header_len; - class master_version_split: public Version { - public: - enum {KIND_MYSQL, KIND_MARIADB}; - int kind; - master_version_split() :kind(KIND_MARIADB) { } - master_version_split(const char *version); - bool version_is_valid() const - { - /* It is invalid only when all version numbers are 0 */ - return !(m_ver[0] == 0 && m_ver[1] == 0 && m_ver[2] == 0); - } - }; - master_version_split server_version_split; - const uint8 *event_type_permutation; - - Format_description_log_event(uint8 binlog_ver, const char* server_ver=0); - Format_description_log_event(const char* buf, uint event_len, - const Format_description_log_event - *description_event); - ~Format_description_log_event() - { - my_free(post_header_len); - } - Log_event_type get_type_code() { return FORMAT_DESCRIPTION_EVENT;} -#ifdef MYSQL_SERVER - bool write(); -#endif - bool header_is_valid() const - { - return ((common_header_len >= ((binlog_version==1) ? OLD_HEADER_LEN : - LOG_EVENT_MINIMAL_HEADER_LEN)) && - (post_header_len != NULL)); - } - - bool is_valid() const - { - return header_is_valid() && server_version_split.version_is_valid(); - } - - int get_data_size() - { - /* - The vector of post-header lengths is considered as part of the - post-header, because in a given version it never changes (contrary to the - query in a Query_log_event). - */ - return FORMAT_DESCRIPTION_HEADER_LEN; - } - - Binlog_crypt_data crypto_data; - bool start_decryption(Start_encryption_log_event* sele); - void copy_crypto_data(const Format_description_log_event* o) - { - crypto_data= o->crypto_data; - } - void reset_crypto() - { - crypto_data.scheme= 0; - } - - void calc_server_version_split(); - static bool is_version_before_checksum(const master_version_split *version_split); -protected: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -/** - @class Intvar_log_event - - An Intvar_log_event will be created just before a Query_log_event, - if the query uses one of the variables LAST_INSERT_ID or INSERT_ID. - Each Intvar_log_event holds the value of one of these variables. - - @section Intvar_log_event_binary_format Binary Format - - The Post-Header for this event type is empty. The Body has two - components: - - - - - - - - - - - - - - - - - - - - - - -
Body for Intvar_log_event
NameFormatDescription
type1 byte enumerationOne byte identifying the type of variable stored. Currently, - two identifiers are supported: LAST_INSERT_ID_EVENT==1 and - INSERT_ID_EVENT==2. -
value8 byte unsigned integerThe value of the variable.
-*/ -class Intvar_log_event: public Log_event -{ -public: - ulonglong val; - uchar type; - -#ifdef MYSQL_SERVER -Intvar_log_event(THD* thd_arg,uchar type_arg, ulonglong val_arg, - bool using_trans, bool direct) - :Log_event(thd_arg,0,using_trans),val(val_arg),type(type_arg) - { - if (direct) - cache_type= Log_event::EVENT_NO_CACHE; - } -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Intvar_log_event(const char* buf, - const Format_description_log_event *description_event); - ~Intvar_log_event() {} - Log_event_type get_type_code() { return INTVAR_EVENT;} - const char* get_var_type_name(); - int get_data_size() { return 9; /* sizeof(type) + sizeof(val) */;} -#ifdef MYSQL_SERVER - bool write(); -#endif - bool is_valid() const { return 1; } - bool is_part_of_group() { return 1; } - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -/** - @class Rand_log_event - - Logs random seed used by the next RAND(), and by PASSWORD() in 4.1.0. - 4.1.1 does not need it (it's repeatable again) so this event needn't be - written in 4.1.1 for PASSWORD() (but the fact that it is written is just a - waste, it does not cause bugs). - - The state of the random number generation consists of 128 bits, - which are stored internally as two 64-bit numbers. - - @section Rand_log_event_binary_format Binary Format - - The Post-Header for this event type is empty. The Body has two - components: - - - - - - - - - - - - - - - - - - - - - -
Body for Rand_log_event
NameFormatDescription
seed18 byte unsigned integer64 bit random seed1.
seed28 byte unsigned integer64 bit random seed2.
-*/ - -class Rand_log_event: public Log_event -{ - public: - ulonglong seed1; - ulonglong seed2; - -#ifdef MYSQL_SERVER - Rand_log_event(THD* thd_arg, ulonglong seed1_arg, ulonglong seed2_arg, - bool using_trans, bool direct) - :Log_event(thd_arg,0,using_trans),seed1(seed1_arg),seed2(seed2_arg) - { - if (direct) - cache_type= Log_event::EVENT_NO_CACHE; - } -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Rand_log_event(const char* buf, - const Format_description_log_event *description_event); - ~Rand_log_event() {} - Log_event_type get_type_code() { return RAND_EVENT;} - int get_data_size() { return 16; /* sizeof(ulonglong) * 2*/ } -#ifdef MYSQL_SERVER - bool write(); -#endif - bool is_valid() const { return 1; } - bool is_part_of_group() { return 1; } - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -class Xid_apply_log_event: public Log_event -{ -public: -#ifdef MYSQL_SERVER - Xid_apply_log_event(THD* thd_arg): - Log_event(thd_arg, 0, TRUE) {} -#endif - Xid_apply_log_event(const char* buf, - const Format_description_log_event *description_event): - Log_event(buf, description_event) {} - - ~Xid_apply_log_event() {} - bool is_valid() const { return 1; } -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_commit()= 0; - virtual int do_apply_event(rpl_group_info *rgi); - int do_record_gtid(THD *thd, rpl_group_info *rgi, bool in_trans, - void **out_hton); - enum_skip_reason do_shall_skip(rpl_group_info *rgi); - virtual const char* get_query()= 0; -#endif -}; - - -/** - @class Xid_log_event - - Logs xid of the transaction-to-be-committed in the 2pc protocol. - Has no meaning in replication, slaves ignore it. - - @section Xid_log_event_binary_format Binary Format -*/ -#ifdef MYSQL_CLIENT -typedef ulonglong my_xid; // this line is the same as in handler.h -#endif - -class Xid_log_event: public Xid_apply_log_event -{ -public: - my_xid xid; - -#ifdef MYSQL_SERVER - Xid_log_event(THD* thd_arg, my_xid x, bool direct): - Xid_apply_log_event(thd_arg), xid(x) - { - if (direct) - cache_type= Log_event::EVENT_NO_CACHE; - } - const char* get_query() - { - return "COMMIT /* implicit, from Xid_log_event */"; - } -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Xid_log_event(const char* buf, - const Format_description_log_event *description_event); - ~Xid_log_event() {} - Log_event_type get_type_code() { return XID_EVENT;} - int get_data_size() { return sizeof(xid); } -#ifdef MYSQL_SERVER - bool write(); -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - int do_commit(); -#endif -}; - - -/** - @class XA_prepare_log_event - - Similar to Xid_log_event except that - - it is specific to XA transaction - - it carries out the prepare logics rather than the final committing - when @c one_phase member is off. The latter option is only for - compatibility with the upstream. - - From the groupping perspective the event finalizes the current - "prepare" group that is started with Gtid_log_event similarly to the - regular replicated transaction. -*/ - -/** - Function serializes XID which is characterized by by four last arguments - of the function. - Serialized XID is presented in valid hex format and is returned to - the caller in a buffer pointed by the first argument. - The buffer size provived by the caller must be not less than - 8 + 2 * XIDDATASIZE + 4 * sizeof(XID::formatID) + 1, see - {MYSQL_,}XID definitions. - - @param buf pointer to a buffer allocated for storing serialized data - @param fmt formatID value - @param gln gtrid_length value - @param bln bqual_length value - @param dat data value - - @return the value of the buffer pointer -*/ - -inline char *serialize_xid(char *buf, long fmt, long gln, long bln, - const char *dat) -{ - int i; - char *c= buf; - /* - Build a string consisting of the hex format representation of XID - as passed through fmt,gln,bln,dat argument: - X'hex11hex12...hex1m',X'hex21hex22...hex2n',11 - and store it into buf. - */ - c[0]= 'X'; - c[1]= '\''; - c+= 2; - for (i= 0; i < gln; i++) - { - c[0]=_dig_vec_lower[((uchar*) dat)[i] >> 4]; - c[1]=_dig_vec_lower[((uchar*) dat)[i] & 0x0f]; - c+= 2; - } - c[0]= '\''; - c[1]= ','; - c[2]= 'X'; - c[3]= '\''; - c+= 4; - - for (; i < gln + bln; i++) - { - c[0]=_dig_vec_lower[((uchar*) dat)[i] >> 4]; - c[1]=_dig_vec_lower[((uchar*) dat)[i] & 0x0f]; - c+= 2; - } - c[0]= '\''; - sprintf(c+1, ",%lu", fmt); - - return buf; -} - -/* - The size of the string containing serialized Xid representation - is computed as a sum of - eight as the number of formatting symbols (X'',X'',) - plus 2 x XIDDATASIZE (2 due to hex format), - plus space for decimal digits of XID::formatID, - plus one for 0x0. -*/ -static const uint ser_buf_size= - 8 + 2 * MYSQL_XIDDATASIZE + 4 * sizeof(long) + 1; - -struct event_mysql_xid_t : MYSQL_XID -{ - char buf[ser_buf_size]; - char *serialize() - { - return serialize_xid(buf, formatID, gtrid_length, bqual_length, data); - } -}; - -#ifndef MYSQL_CLIENT -struct event_xid_t : XID -{ - char buf[ser_buf_size]; - - char *serialize(char *buf_arg) - { - return serialize_xid(buf_arg, formatID, gtrid_length, bqual_length, data); - } - char *serialize() - { - return serialize(buf); - } -}; -#endif - -class XA_prepare_log_event: public Xid_apply_log_event -{ -protected: - - /* Constant contributor to subheader in write() by members of XID struct. */ - static const int xid_subheader_no_data= 12; - event_mysql_xid_t m_xid; - void *xid; - bool one_phase; - -public: -#ifdef MYSQL_SERVER - XA_prepare_log_event(THD* thd_arg, XID *xid_arg, bool one_phase_arg): - Xid_apply_log_event(thd_arg), xid(xid_arg), one_phase(one_phase_arg) - { - cache_type= Log_event::EVENT_NO_CACHE; - } -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - XA_prepare_log_event(const char* buf, - const Format_description_log_event *description_event); - ~XA_prepare_log_event() {} - Log_event_type get_type_code() { return XA_PREPARE_LOG_EVENT; } - bool is_valid() const { return m_xid.formatID != -1; } - int get_data_size() - { - return xid_subheader_no_data + m_xid.gtrid_length + m_xid.bqual_length; - } - -#ifdef MYSQL_SERVER - bool write(); -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - char query[sizeof("XA COMMIT ONE PHASE") + 1 + ser_buf_size]; - int do_commit(); - const char* get_query() - { - sprintf(query, - (one_phase ? "XA COMMIT %s ONE PHASE" : "XA PREPARE %s"), - m_xid.serialize()); - return query; - } -#endif -}; - - -/** - @class User_var_log_event - - Every time a query uses the value of a user variable, a User_var_log_event is - written before the Query_log_event, to set the user variable. - - @section User_var_log_event_binary_format Binary Format -*/ - -class User_var_log_event: public Log_event -{ -public: - enum { - UNDEF_F= 0, - UNSIGNED_F= 1 - }; - const char *name; - size_t name_len; - const char *val; - size_t val_len; - Item_result type; - uint charset_number; - bool is_null; - uchar flags; -#ifdef MYSQL_SERVER - bool deferred; - query_id_t query_id; - User_var_log_event(THD* thd_arg, const char *name_arg, size_t name_len_arg, - const char *val_arg, size_t val_len_arg, Item_result type_arg, - uint charset_number_arg, uchar flags_arg, - bool using_trans, bool direct) - :Log_event(thd_arg, 0, using_trans), - name(name_arg), name_len(name_len_arg), val(val_arg), - val_len(val_len_arg), type(type_arg), charset_number(charset_number_arg), - flags(flags_arg), deferred(false) - { - is_null= !val; - if (direct) - cache_type= Log_event::EVENT_NO_CACHE; - } - void pack_info(Protocol* protocol); -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - User_var_log_event(const char* buf, uint event_len, - const Format_description_log_event *description_event); - ~User_var_log_event() {} - Log_event_type get_type_code() { return USER_VAR_EVENT;} -#ifdef MYSQL_SERVER - bool write(); - /* - Getter and setter for deferred User-event. - Returns true if the event is not applied directly - and which case the applier adjusts execution path. - */ - bool is_deferred() { return deferred; } - /* - In case of the deferred applying the variable instance is flagged - and the parsing time query id is stored to be used at applying time. - */ - void set_deferred(query_id_t qid) { deferred= true; query_id= qid; } -#endif - bool is_valid() const { return name != 0; } - bool is_part_of_group() { return 1; } - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -/** - @class Stop_log_event - - @section Stop_log_event_binary_format Binary Format - - The Post-Header and Body for this event type are empty; it only has - the Common-Header. -*/ -class Stop_log_event: public Log_event -{ -public: -#ifdef MYSQL_SERVER - Stop_log_event() :Log_event() - {} -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Stop_log_event(const char* buf, - const Format_description_log_event *description_event): - Log_event(buf, description_event) - {} - ~Stop_log_event() {} - Log_event_type get_type_code() { return STOP_EVENT;} - bool is_valid() const { return 1; } - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi) - { - /* - Events from ourself should be skipped, but they should not - decrease the slave skip counter. - */ - if (this->server_id == global_system_variables.server_id) - return Log_event::EVENT_SKIP_IGNORE; - else - return Log_event::EVENT_SKIP_NOT; - } -#endif -}; - -/** - @class Rotate_log_event - - This will be deprecated when we move to using sequence ids. - - @section Rotate_log_event_binary_format Binary Format - - The Post-Header has one component: - - - - - - - - - - - - - - - - -
Post-Header for Rotate_log_event
NameFormatDescription
position8 byte integerThe position within the binlog to rotate to.
- - The Body has one component: - - - - - - - - - - - - - - - - -
Body for Rotate_log_event
NameFormatDescription
new_logvariable length string without trailing zero, extending to the - end of the event (determined by the length field of the - Common-Header) - Name of the binlog to rotate to.
-*/ - -class Rotate_log_event: public Log_event -{ -public: - enum { - DUP_NAME= 2, // if constructor should dup the string argument - RELAY_LOG=4 // rotate event for relay log - }; - const char* new_log_ident; - ulonglong pos; - uint ident_len; - uint flags; -#ifdef MYSQL_SERVER - Rotate_log_event(const char* new_log_ident_arg, - uint ident_len_arg, - ulonglong pos_arg, uint flags); -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Rotate_log_event(const char* buf, uint event_len, - const Format_description_log_event* description_event); - ~Rotate_log_event() - { - if (flags & DUP_NAME) - my_free((void*) new_log_ident); - } - Log_event_type get_type_code() { return ROTATE_EVENT;} - my_off_t get_header_len(my_off_t l __attribute__((unused))) - { return LOG_EVENT_MINIMAL_HEADER_LEN; } - int get_data_size() { return ident_len + ROTATE_HEADER_LEN;} - bool is_valid() const { return new_log_ident != 0; } -#ifdef MYSQL_SERVER - bool write(); -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -class Binlog_checkpoint_log_event: public Log_event -{ -public: - char *binlog_file_name; - uint binlog_file_len; - -#ifdef MYSQL_SERVER - Binlog_checkpoint_log_event(const char *binlog_file_name_arg, - uint binlog_file_len_arg); -#ifdef HAVE_REPLICATION - void pack_info(Protocol *protocol); -#endif -#else - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - Binlog_checkpoint_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); - ~Binlog_checkpoint_log_event() { my_free(binlog_file_name); } - Log_event_type get_type_code() { return BINLOG_CHECKPOINT_EVENT;} - int get_data_size() { return binlog_file_len + BINLOG_CHECKPOINT_HEADER_LEN;} - bool is_valid() const { return binlog_file_name != 0; } -#ifdef MYSQL_SERVER - bool write(); - enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -/** - @class Gtid_log_event - - This event is logged as part of every event group to give the global - transaction id (GTID) of that group. - - It replaces the BEGIN query event used in earlier versions to begin most - event groups, but is also used for events that used to be stand-alone. - - @section Gtid_log_event_binary_format Binary Format - - The binary format for Gtid_log_event has 6 extra reserved bytes to make the - length a total of 19 byte (+ 19 bytes of header in common with all events). - This is just the minimal size for a BEGIN query event, which makes it easy - to replace this event with such BEGIN event to remain compatible with old - slave servers. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Post-Header
NameFormatDescription
seq_no8 byte unsigned integerincreasing id within one server_id. Starts at 1, holes in the sequence - may occur
domain_id4 byte unsigned integerReplication domain id, identifying independent replication streams>
flags1 byte bitfieldBit 0 set indicates stand-alone event (no terminating COMMIT)Bit 1 set indicates group commit, and that commit id existsBit 2 set indicates a transactional event group (can be safely rolled - back).Bit 3 set indicates that user allowed optimistic parallel apply (the - @@SESSION.replicate_allow_parallel value was true at commit).Bit 4 set indicates that this transaction encountered a row (or other) - lock wait during execution.
Reserved (no group commit) / commit id (group commit) (see flags bit 1)6 bytes / 8 bytesReserved bytes, set to 0. Maybe be used for future expansion (no - group commit). OR commit id, same for all GTIDs in the same group - commit (see flags bit 1).
- - The Body of Gtid_log_event is empty. The total event size is 19 bytes + - the normal 19 bytes common-header. -*/ - -class Gtid_log_event: public Log_event -{ -public: - uint64 seq_no; - uint64 commit_id; - uint32 domain_id; -#ifdef MYSQL_SERVER - event_xid_t xid; -#else - event_mysql_xid_t xid; -#endif - uchar flags2; - /* Flags2. */ - - /* FL_STANDALONE is set when there is no terminating COMMIT event. */ - static const uchar FL_STANDALONE= 1; - /* - FL_GROUP_COMMIT_ID is set when event group is part of a group commit on the - master. Groups with same commit_id are part of the same group commit. - */ - static const uchar FL_GROUP_COMMIT_ID= 2; - /* - FL_TRANSACTIONAL is set for an event group that can be safely rolled back - (no MyISAM, eg.). - */ - static const uchar FL_TRANSACTIONAL= 4; - /* - FL_ALLOW_PARALLEL reflects the (negation of the) value of - @@SESSION.skip_parallel_replication at the time of commit. - */ - static const uchar FL_ALLOW_PARALLEL= 8; - /* - FL_WAITED is set if a row lock wait (or other wait) is detected during the - execution of the transaction. - */ - static const uchar FL_WAITED= 16; - /* FL_DDL is set for event group containing DDL. */ - static const uchar FL_DDL= 32; - /* FL_PREPARED_XA is set for XA transaction. */ - static const uchar FL_PREPARED_XA= 64; - /* FL_"COMMITTED or ROLLED-BACK"_XA is set for XA transaction. */ - static const uchar FL_COMPLETED_XA= 128; - -#ifdef MYSQL_SERVER - Gtid_log_event(THD *thd_arg, uint64 seq_no, uint32 domain_id, bool standalone, - uint16 flags, bool is_transactional, uint64 commit_id); -#ifdef HAVE_REPLICATION - void pack_info(Protocol *protocol); - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -#else - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - Gtid_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); - ~Gtid_log_event() { } - Log_event_type get_type_code() { return GTID_EVENT; } - enum_logged_status logged_status() { return LOGGED_NO_DATA; } - int get_data_size() - { - return GTID_HEADER_LEN + ((flags2 & FL_GROUP_COMMIT_ID) ? 2 : 0); - } - bool is_valid() const { return seq_no != 0; } -#ifdef MYSQL_SERVER - bool write(); - static int make_compatible_event(String *packet, bool *need_dummy_event, - ulong ev_offset, enum enum_binlog_checksum_alg checksum_alg); - static bool peek(const char *event_start, size_t event_len, - enum enum_binlog_checksum_alg checksum_alg, - uint32 *domain_id, uint32 *server_id, uint64 *seq_no, - uchar *flags2, const Format_description_log_event *fdev); -#endif -}; - - -/** - @class Gtid_list_log_event - - This event is logged at the start of every binlog file to record the - current replication state: the last global transaction id (GTID) applied - on the server within each replication domain. - - It consists of a list of GTIDs, one for each replication domain ever seen - on the server. - - @section Gtid_list_log_event_binary_format Binary Format - - - - - - - - - - - - - - - -
Post-Header
NameFormatDescription
count4 byte unsigned integerThe lower 28 bits are the number of GTIDs. The upper 4 bits are - flags bits.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Body
NameFormatDescription
domain_id4 byte unsigned integerReplication domain id of one GTID
server_id4 byte unsigned integerServer id of one GTID
seq_no8 byte unsigned integersequence number of one GTID
- - The three elements in the body repeat COUNT times to form the GTID list. - - At the time of writing, only two flag bit are in use. - - Bit 28 of `count' is used for flag FLAG_UNTIL_REACHED, which is sent in a - Gtid_list event from the master to the slave to indicate that the START - SLAVE UNTIL master_gtid_pos=xxx condition has been reached. (This flag is - only sent in "fake" events generated on the fly, it is not written into - the binlog). -*/ - -class Gtid_list_log_event: public Log_event -{ -public: - uint32 count; - uint32 gl_flags; - struct rpl_gtid *list; - uint64 *sub_id_list; - - static const uint element_size= 4+4+8; - /* Upper bits stored in 'count'. See comment above */ - enum gtid_flags - { - FLAG_UNTIL_REACHED= (1<<28), - FLAG_IGN_GTIDS= (1<<29), - }; -#ifdef MYSQL_SERVER - Gtid_list_log_event(rpl_binlog_state *gtid_set, uint32 gl_flags); - Gtid_list_log_event(slave_connection_state *gtid_set, uint32 gl_flags); -#ifdef HAVE_REPLICATION - void pack_info(Protocol *protocol); -#endif -#else - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - Gtid_list_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); - ~Gtid_list_log_event() { my_free(list); my_free(sub_id_list); } - Log_event_type get_type_code() { return GTID_LIST_EVENT; } - int get_data_size() { - /* - Replacing with dummy event, needed for older slaves, requires a minimum - of 6 bytes in the body. - */ - return (count==0 ? - GTID_LIST_HEADER_LEN+2 : GTID_LIST_HEADER_LEN+count*element_size); - } - bool is_valid() const { return list != NULL; } -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - bool to_packet(String *packet); - bool write(); - virtual int do_apply_event(rpl_group_info *rgi); - enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif - static bool peek(const char *event_start, size_t event_len, - enum enum_binlog_checksum_alg checksum_alg, - rpl_gtid **out_gtid_list, uint32 *out_list_len, - const Format_description_log_event *fdev); -}; - - -/* the classes below are for the new LOAD DATA INFILE logging */ - -/** - @class Create_file_log_event - - @section Create_file_log_event_binary_format Binary Format -*/ - -class Create_file_log_event: public Load_log_event -{ -protected: - /* - Pretend we are Load event, so we can write out just - our Load part - used on the slave when writing event out to - SQL_LOAD-*.info file - */ - bool fake_base; -public: - uchar* block; - const char *event_buf; - uint block_len; - uint file_id; - bool inited_from_old; - -#ifdef MYSQL_SERVER - Create_file_log_event(THD* thd, sql_exchange* ex, const char* db_arg, - const char* table_name_arg, - List& fields_arg, - bool is_concurrent_arg, - enum enum_duplicates handle_dup, bool ignore, - uchar* block_arg, uint block_len_arg, - bool using_trans); -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, - bool enable_local); -#endif - - Create_file_log_event(const char* buf, uint event_len, - const Format_description_log_event* description_event); - ~Create_file_log_event() - { - my_free((void*) event_buf); - } - - Log_event_type get_type_code() - { - return fake_base ? Load_log_event::get_type_code() : CREATE_FILE_EVENT; - } - int get_data_size() - { - return (fake_base ? Load_log_event::get_data_size() : - Load_log_event::get_data_size() + - 4 + 1 + block_len); - } - bool is_valid() const { return inited_from_old || block != 0; } -#ifdef MYSQL_SERVER - bool write_data_header(); - bool write_data_body(); - /* - Cut out Create_file extensions and - write it as Load event - used on the slave - */ - bool write_base(); -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); -#endif -}; - - -/** - @class Append_block_log_event - - @section Append_block_log_event_binary_format Binary Format -*/ - -class Append_block_log_event: public Log_event -{ -public: - uchar* block; - uint block_len; - uint file_id; - /* - 'db' is filled when the event is created in mysql_load() (the - event needs to have a 'db' member to be well filtered by - binlog-*-db rules). 'db' is not written to the binlog (it's not - used by Append_block_log_event::write()), so it can't be read in - the Append_block_log_event(const char* buf, int event_len) - constructor. In other words, 'db' is used only for filtering by - binlog-*-db rules. Create_file_log_event is different: it's 'db' - (which is inherited from Load_log_event) is written to the binlog - and can be re-read. - */ - const char* db; - -#ifdef MYSQL_SERVER - Append_block_log_event(THD* thd, const char* db_arg, uchar* block_arg, - uint block_len_arg, bool using_trans); -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); - virtual int get_create_or_append() const; -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Append_block_log_event(const char* buf, uint event_len, - const Format_description_log_event - *description_event); - ~Append_block_log_event() {} - Log_event_type get_type_code() { return APPEND_BLOCK_EVENT;} - int get_data_size() { return block_len + APPEND_BLOCK_HEADER_LEN ;} - bool is_valid() const { return block != 0; } -#ifdef MYSQL_SERVER - bool write(); - const char* get_db() { return db; } -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); -#endif -}; - - -/** - @class Delete_file_log_event - - @section Delete_file_log_event_binary_format Binary Format -*/ - -class Delete_file_log_event: public Log_event -{ -public: - uint file_id; - const char* db; /* see comment in Append_block_log_event */ - -#ifdef MYSQL_SERVER - Delete_file_log_event(THD* thd, const char* db_arg, bool using_trans); -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, - bool enable_local); -#endif - - Delete_file_log_event(const char* buf, uint event_len, - const Format_description_log_event* description_event); - ~Delete_file_log_event() {} - Log_event_type get_type_code() { return DELETE_FILE_EVENT;} - int get_data_size() { return DELETE_FILE_HEADER_LEN ;} - bool is_valid() const { return file_id != 0; } -#ifdef MYSQL_SERVER - bool write(); - const char* get_db() { return db; } -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); -#endif -}; - - -/** - @class Execute_load_log_event - - @section Delete_file_log_event_binary_format Binary Format -*/ - -class Execute_load_log_event: public Log_event -{ -public: - uint file_id; - const char* db; /* see comment in Append_block_log_event */ - -#ifdef MYSQL_SERVER - Execute_load_log_event(THD* thd, const char* db_arg, bool using_trans); -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); -#endif - - Execute_load_log_event(const char* buf, uint event_len, - const Format_description_log_event - *description_event); - ~Execute_load_log_event() {} - Log_event_type get_type_code() { return EXEC_LOAD_EVENT;} - int get_data_size() { return EXEC_LOAD_HEADER_LEN ;} - bool is_valid() const { return file_id != 0; } -#ifdef MYSQL_SERVER - bool write(); - const char* get_db() { return db; } -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); -#endif -}; - - -/** - @class Begin_load_query_log_event - - Event for the first block of file to be loaded, its only difference from - Append_block event is that this event creates or truncates existing file - before writing data. - - @section Begin_load_query_log_event_binary_format Binary Format -*/ -class Begin_load_query_log_event: public Append_block_log_event -{ -public: -#ifdef MYSQL_SERVER - Begin_load_query_log_event(THD* thd_arg, const char *db_arg, - uchar* block_arg, uint block_len_arg, - bool using_trans); -#ifdef HAVE_REPLICATION - Begin_load_query_log_event(THD* thd); - int get_create_or_append() const; -#endif /* HAVE_REPLICATION */ -#endif - Begin_load_query_log_event(const char* buf, uint event_len, - const Format_description_log_event - *description_event); - ~Begin_load_query_log_event() {} - Log_event_type get_type_code() { return BEGIN_LOAD_QUERY_EVENT; } -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif -}; - - -/* - Elements of this enum describe how LOAD DATA handles duplicates. -*/ -enum enum_load_dup_handling { LOAD_DUP_ERROR= 0, LOAD_DUP_IGNORE, - LOAD_DUP_REPLACE }; - -/** - @class Execute_load_query_log_event - - Event responsible for LOAD DATA execution, it similar to Query_log_event - but before executing the query it substitutes original filename in LOAD DATA - query with name of temporary file. - - @section Execute_load_query_log_event_binary_format Binary Format -*/ -class Execute_load_query_log_event: public Query_log_event -{ -public: - uint file_id; // file_id of temporary file - uint fn_pos_start; // pointer to the part of the query that should - // be substituted - uint fn_pos_end; // pointer to the end of this part of query - /* - We have to store type of duplicate handling explicitly, because - for LOAD DATA it also depends on LOCAL option. And this part - of query will be rewritten during replication so this information - may be lost... - */ - enum_load_dup_handling dup_handling; - -#ifdef MYSQL_SERVER - Execute_load_query_log_event(THD* thd, const char* query_arg, - ulong query_length, uint fn_pos_start_arg, - uint fn_pos_end_arg, - enum_load_dup_handling dup_handling_arg, - bool using_trans, bool direct, - bool suppress_use, int errcode); -#ifdef HAVE_REPLICATION - void pack_info(Protocol* protocol); -#endif /* HAVE_REPLICATION */ -#else - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); - /* Prints the query as LOAD DATA LOCAL and with rewritten filename */ - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, - const char *local_fname); -#endif - Execute_load_query_log_event(const char* buf, uint event_len, - const Format_description_log_event - *description_event); - ~Execute_load_query_log_event() {} - - Log_event_type get_type_code() { return EXECUTE_LOAD_QUERY_EVENT; } - bool is_valid() const { return Query_log_event::is_valid() && file_id != 0; } - - ulong get_post_header_size_for_derived(); -#ifdef MYSQL_SERVER - bool write_post_header_for_derived(); -#endif - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); -#endif -}; - - -#ifdef MYSQL_CLIENT -/** - @class Unknown_log_event - - @section Unknown_log_event_binary_format Binary Format -*/ -class Unknown_log_event: public Log_event -{ -public: - enum { UNKNOWN, ENCRYPTED } what; - /* - Even if this is an unknown event, we still pass description_event to - Log_event's ctor, this way we can extract maximum information from the - event's header (the unique ID for example). - */ - Unknown_log_event(const char* buf, - const Format_description_log_event *description_event): - Log_event(buf, description_event), what(UNKNOWN) - {} - /* constructor for hopelessly corrupted events */ - Unknown_log_event(): Log_event(), what(ENCRYPTED) {} - ~Unknown_log_event() {} - bool print(FILE* file, PRINT_EVENT_INFO* print_event_info); - Log_event_type get_type_code() { return UNKNOWN_EVENT;} - bool is_valid() const { return 1; } -}; -#endif -char *str_to_hex(char *to, const char *from, size_t len); - -/** - @class Annotate_rows_log_event - - In row-based mode, if binlog_annotate_row_events = ON, each group of - Table_map_log_events is preceded by an Annotate_rows_log_event which - contains the query which caused the subsequent rows operations. - - The Annotate_rows_log_event has no post-header and its body contains - the corresponding query (without trailing zero). Note. The query length - is to be calculated as a difference between the whole event length and - the common header length. -*/ -class Annotate_rows_log_event: public Log_event -{ -public: -#ifndef MYSQL_CLIENT - Annotate_rows_log_event(THD*, bool using_trans, bool direct); -#endif - Annotate_rows_log_event(const char *buf, uint event_len, - const Format_description_log_event*); - ~Annotate_rows_log_event(); - - virtual int get_data_size(); - virtual Log_event_type get_type_code(); - enum_logged_status logged_status() { return LOGGED_NO_DATA; } - virtual bool is_valid() const; - virtual bool is_part_of_group() { return 1; } - -#ifndef MYSQL_CLIENT - virtual bool write_data_header(); - virtual bool write_data_body(); -#endif - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - virtual void pack_info(Protocol*); -#endif - -#ifdef MYSQL_CLIENT - virtual bool print(FILE*, PRINT_EVENT_INFO*); -#endif - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) -private: - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info*); -#endif - -private: - char *m_query_txt; - uint m_query_len; - char *m_save_thd_query_txt; - uint m_save_thd_query_len; - bool m_saved_thd_query; - bool m_used_query_txt; -}; - -/** - @class Table_map_log_event - - In row-based mode, every row operation event is preceded by a - Table_map_log_event which maps a table definition to a number. The - table definition consists of database name, table name, and column - definitions. - - @section Table_map_log_event_binary_format Binary Format - - The Post-Header has the following components: - - - - - - - - - - - - - - - - - - - - - - -
Post-Header for Table_map_log_event
NameFormatDescription
table_id6 bytes unsigned integerThe number that identifies the table.
flags2 byte bitfieldReserved for future use; currently always 0.
- - The Body has the following components: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Body for Table_map_log_event
NameFormatDescription
database_nameone byte string length, followed by null-terminated stringThe name of the database in which the table resides. The name - is represented as a one byte unsigned integer representing the - number of bytes in the name, followed by length bytes containing - the database name, followed by a terminating 0 byte. (Note the - redundancy in the representation of the length.)
table_nameone byte string length, followed by null-terminated stringThe name of the table, encoded the same way as the database - name above.
column_count@ref packed_integer "Packed Integer"The number of columns in the table, represented as a packed - variable-length integer.
column_typeList of column_count 1 byte enumeration valuesThe type of each column in the table, listed from left to - right. Each byte is mapped to a column type according to the - enumeration type enum_field_types defined in mysql_com.h. The - mapping of types to numbers is listed in the table @ref - Table_table_map_log_event_column_types "below" (along with - description of the associated metadata field).
metadata_length@ref packed_integer "Packed Integer"The length of the following metadata block
metadatalist of metadata for each columnFor each column from left to right, a chunk of data who's - length and semantics depends on the type of the column. The - length and semantics for the metadata for each column are listed - in the table @ref Table_table_map_log_event_column_types - "below".
null_bitscolumn_count bits, rounded up to nearest byteFor each column, a bit indicating whether data in the column - can be NULL or not. The number of bytes needed for this is - int((column_count+7)/8). The flag for the first column from the - left is in the least-significant bit of the first byte, the second - is in the second least significant bit of the first byte, the - ninth is in the least significant bit of the second byte, and so - on.
optional metadata fieldsoptional metadata fields are stored in Type, Length, Value(TLV) format. - Type takes 1 byte. Length is a packed integer value. Values takes - Length bytes. - There are some optional metadata defined. They are listed in the table - @ref Table_table_map_event_optional_metadata. Optional metadata fields - follow null_bits. Whether binlogging an optional metadata is decided by the - server. The order is not defined, so they can be binlogged in any order. -
- - The table below lists all column types, along with the numerical - identifier for it and the size and interpretation of meta-data used - to describe the type. - - @anchor Table_table_map_log_event_column_types - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table_map_log_event column types: numerical identifier and - metadata
NameIdentifierSize of metadata in bytesDescription of metadata
MYSQL_TYPE_DECIMAL00No column metadata.
MYSQL_TYPE_TINY10No column metadata.
MYSQL_TYPE_SHORT20No column metadata.
MYSQL_TYPE_LONG30No column metadata.
MYSQL_TYPE_FLOAT41 byte1 byte unsigned integer, representing the "pack_length", which - is equal to sizeof(float) on the server from which the event - originates.
MYSQL_TYPE_DOUBLE51 byte1 byte unsigned integer, representing the "pack_length", which - is equal to sizeof(double) on the server from which the event - originates.
MYSQL_TYPE_NULL60No column metadata.
MYSQL_TYPE_TIMESTAMP70No column metadata.
MYSQL_TYPE_LONGLONG80No column metadata.
MYSQL_TYPE_INT2490No column metadata.
MYSQL_TYPE_DATE100No column metadata.
MYSQL_TYPE_TIME110No column metadata.
MYSQL_TYPE_DATETIME120No column metadata.
MYSQL_TYPE_YEAR130No column metadata.
MYSQL_TYPE_NEWDATE14–This enumeration value is only used internally and cannot - exist in a binlog.
MYSQL_TYPE_VARCHAR152 bytes2 byte unsigned integer representing the maximum length of - the string.
MYSQL_TYPE_BIT162 bytesA 1 byte unsigned int representing the length in bits of the - bitfield (0 to 64), followed by a 1 byte unsigned int - representing the number of bytes occupied by the bitfield. The - number of bytes is either int((length+7)/8) or int(length/8).
MYSQL_TYPE_NEWDECIMAL2462 bytesA 1 byte unsigned int representing the precision, followed - by a 1 byte unsigned int representing the number of decimals.
MYSQL_TYPE_ENUM247–This enumeration value is only used internally and cannot - exist in a binlog.
MYSQL_TYPE_SET248–This enumeration value is only used internally and cannot - exist in a binlog.
MYSQL_TYPE_TINY_BLOB249–This enumeration value is only used internally and cannot - exist in a binlog.
MYSQL_TYPE_MEDIUM_BLOB250–This enumeration value is only used internally and cannot - exist in a binlog.
MYSQL_TYPE_LONG_BLOB251–This enumeration value is only used internally and cannot - exist in a binlog.
MYSQL_TYPE_BLOB2521 byteThe pack length, i.e., the number of bytes needed to represent - the length of the blob: 1, 2, 3, or 4.
MYSQL_TYPE_VAR_STRING2532 bytesThis is used to store both strings and enumeration values. - The first byte is a enumeration value storing the real - type, which may be either MYSQL_TYPE_VAR_STRING or - MYSQL_TYPE_ENUM. The second byte is a 1 byte unsigned integer - representing the field size, i.e., the number of bytes needed to - store the length of the string.
MYSQL_TYPE_STRING2542 bytesThe first byte is always MYSQL_TYPE_VAR_STRING (i.e., 253). - The second byte is the field size, i.e., the number of bytes in - the representation of size of the string: 3 or 4.
MYSQL_TYPE_GEOMETRY2551 byteThe pack length, i.e., the number of bytes needed to represent - the length of the geometry: 1, 2, 3, or 4.
- The table below lists all optional metadata types, along with the numerical - identifier for it and the size and interpretation of meta-data used - to describe the type. - - @anchor Table_table_map_event_optional_metadata - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table_map_event optional metadata types: numerical identifier and - metadata. Optional metadata fields are stored in TLV fields. - Format of values are described in this table.
TypeDescriptionFormat
SIGNEDNESSsignedness of numeric colums. This is included for all values of - binlog_row_metadata.For each numeric column, a bit indicates whether the numeric - colunm has unsigned flag. 1 means it is unsigned. The number of - bytes needed for this is int((column_count + 7) / 8). The order is - the same as the order of column_type field.
DEFAULT_CHARSETCharsets of character columns. It has a default charset for - the case that most of character columns have same charset and the - most used charset is binlogged as default charset.Collation - numbers are binlogged for identifying charsets. They are stored in - packed length format. Either DEFAULT_CHARSET or COLUMN_CHARSET is - included for all values of binlog_row_metadata.Default charset's collation is logged first. The charsets which are not - same to default charset are logged following default charset. They are - logged as column index and charset collation number pair sequence. The - column index is counted only in all character columns. The order is same to - the order of column_type - field.
COLUMN_CHARSETCharsets of character columns. For the case that most of columns have - different charsets, this field is logged. It is never logged with - DEFAULT_CHARSET together. Either DEFAULT_CHARSET or COLUMN_CHARSET is - included for all values of binlog_row_metadata.It is a collation number sequence for all character columns.
COLUMN_NAMENames of columns. This is only included if - binlog_row_metadata=FULL.A sequence of column names. For each column name, 1 byte for - the string length in bytes is followed by a string without null - terminator.
SET_STR_VALUEThe string values of SET columns. This is only included if - binlog_row_metadata=FULL.For each SET column, a pack_length representing the value - count is followed by a sequence of length and string pairs. length - is the byte count in pack_length format. The string has no null - terminator.
ENUM_STR_VALUEThe string values is ENUM columns. This is only included - if binlog_row_metadata=FULL.The format is the same as SET_STR_VALUE.
GEOMETRY_TYPEThe real type of geometry columns. This is only included - if binlog_row_metadata=FULL.A sequence of real type of geometry columns are stored in pack_length - format.
SIMPLE_PRIMARY_KEYThe primary key without any prefix. This is only included - if binlog_row_metadata=FULL and there is a primary key where every - key part covers an entire column.A sequence of column indexes. The indexes are stored in pack_length - format.
PRIMARY_KEY_WITH_PREFIXThe primary key with some prefix. It doesn't appear together with - SIMPLE_PRIMARY_KEY. This is only included if - binlog_row_metadata=FULL and there is a primary key where some key - part covers a prefix of the column.A sequence of column index and prefix length pairs. Both - column index and prefix length are in pack_length format. Prefix length - 0 means that the whole column value is used.
ENUM_AND_SET_DEFAULT_CHARSETCharsets of ENUM and SET columns. It has the same layout as - DEFAULT_CHARSET. If there are SET or ENUM columns and - binlog_row_metadata=FULL, exactly one of - ENUM_AND_SET_DEFAULT_CHARSET and ENUM_AND_SET_COLUMN_CHARSET - appears (the encoder chooses the representation that uses the - least amount of space). Otherwise, none of them appears.The same format as for DEFAULT_CHARSET, except it counts ENUM - and SET columns rather than character columns.
ENUM_AND_SET_COLUMN_CHARSETCharsets of ENUM and SET columns. It has the same layout as - COLUMN_CHARSET. If there are SET or ENUM columns and - binlog_row_metadata=FULL, exactly one of - ENUM_AND_SET_DEFAULT_CHARSET and ENUM_AND_SET_COLUMN_CHARSET - appears (the encoder chooses the representation that uses the - least amount of space). Otherwise, none of them appears.The same format as for COLUMN_CHARSET, except it counts ENUM - and SET columns rather than character columns.
-*/ -class Table_map_log_event : public Log_event -{ -public: - /* Constants */ - enum - { - TYPE_CODE = TABLE_MAP_EVENT - }; - - /** - Enumeration of the errors that can be returned. - */ - enum enum_error - { - ERR_OPEN_FAILURE = -1, /**< Failure to open table */ - ERR_OK = 0, /**< No error */ - ERR_TABLE_LIMIT_EXCEEDED = 1, /**< No more room for tables */ - ERR_OUT_OF_MEM = 2, /**< Out of memory */ - ERR_BAD_TABLE_DEF = 3, /**< Table definition does not match */ - ERR_RBR_TO_SBR = 4 /**< daisy-chanining RBR to SBR not allowed */ - }; - - enum enum_flag - { - /* - Nothing here right now, but the flags support is there in - preparation for changes that are coming. Need to add a - constant to make it compile under HP-UX: aCC does not like - empty enumerations. - */ - ENUM_FLAG_COUNT - }; - - typedef uint16 flag_set; - /** - DEFAULT_CHARSET and COLUMN_CHARSET don't appear together, and - ENUM_AND_SET_DEFAULT_CHARSET and ENUM_AND_SET_COLUMN_CHARSET don't - appear together. They are just alternative ways to pack character - set information. When binlogging, it logs character sets in the - way that occupies least storage. - - SIMPLE_PRIMARY_KEY and PRIMARY_KEY_WITH_PREFIX don't appear together. - SIMPLE_PRIMARY_KEY is for the primary keys which only use whole values of - pk columns. PRIMARY_KEY_WITH_PREFIX is - for the primary keys which just use part value of pk columns. - */ - enum Optional_metadata_field_type - { - SIGNEDNESS = 1, // UNSIGNED flag of numeric columns - DEFAULT_CHARSET, /* Character set of string columns, optimized to - minimize space when many columns have the - same charset. */ - COLUMN_CHARSET, /* Character set of string columns, optimized to - minimize space when columns have many - different charsets. */ - COLUMN_NAME, - SET_STR_VALUE, // String value of SET columns - ENUM_STR_VALUE, // String value of ENUM columns - GEOMETRY_TYPE, // Real type of geometry columns - SIMPLE_PRIMARY_KEY, // Primary key without prefix - PRIMARY_KEY_WITH_PREFIX, // Primary key with prefix - ENUM_AND_SET_DEFAULT_CHARSET, /* Character set of enum and set - columns, optimized to minimize - space when many columns have the - same charset. */ - ENUM_AND_SET_COLUMN_CHARSET, /* Character set of enum and set - columns, optimized to minimize - space when many columns have the - same charset. */ - }; - /** - Metadata_fields organizes m_optional_metadata into a structured format which - is easy to access. - */ - // Values for binlog_row_metadata sysvar - enum enum_binlog_row_metadata - { - BINLOG_ROW_METADATA_NO_LOG= 0, - BINLOG_ROW_METADATA_MINIMAL= 1, - BINLOG_ROW_METADATA_FULL= 2 - }; - struct Optional_metadata_fields - { - typedef std::pair uint_pair; - typedef std::vector str_vector; - - struct Default_charset - { - Default_charset() : default_charset(0) {} - bool empty() const { return default_charset == 0; } - - // Default charset for the columns which are not in charset_pairs. - unsigned int default_charset; - - /* The uint_pair means . */ - std::vector charset_pairs; - }; - - // Contents of DEFAULT_CHARSET field is converted into Default_charset. - Default_charset m_default_charset; - // Contents of ENUM_AND_SET_DEFAULT_CHARSET are converted into - // Default_charset. - Default_charset m_enum_and_set_default_charset; - std::vector m_signedness; - // Character set number of every string column - std::vector m_column_charset; - // Character set number of every ENUM or SET column. - std::vector m_enum_and_set_column_charset; - std::vector m_column_name; - // each str_vector stores values of one enum/set column - std::vector m_enum_str_value; - std::vector m_set_str_value; - std::vector m_geometry_type; - /* - The uint_pair means . Prefix length is 0 if - whole column value is used. - */ - std::vector m_primary_key; - - /* - It parses m_optional_metadata and populates into above variables. - - @param[in] optional_metadata points to the begin of optional metadata - fields in table_map_event. - @param[in] optional_metadata_len length of optional_metadata field. - */ - Optional_metadata_fields(unsigned char* optional_metadata, - unsigned int optional_metadata_len); - }; - - /** - Print column metadata. Its format looks like: - # Columns(colume_name type, colume_name type, ...) - if colume_name field is not logged into table_map_log_event, then - only type is printed. - - @@param[out] file the place where colume metadata is printed - @@param[in] The metadata extracted from optional metadata fields - */ - void print_columns(IO_CACHE *file, - const Optional_metadata_fields &fields); - /** - Print primary information. Its format looks like: - # Primary Key(colume_name, column_name(prifix), ...) - if colume_name field is not logged into table_map_log_event, then - colume index is printed. - - @@param[out] file the place where primary key is printed - @@param[in] The metadata extracted from optional metadata fields - */ - void print_primary_key(IO_CACHE *file, - const Optional_metadata_fields &fields); - - /* Special constants representing sets of flags */ - enum - { - TM_NO_FLAGS = 0U, - TM_BIT_LEN_EXACT_F = (1U << 0), - // MariaDB flags (we starts from the other end) - TM_BIT_HAS_TRIGGERS_F= (1U << 14) - }; - - flag_set get_flags(flag_set flag) const { return m_flags & flag; } - -#ifdef MYSQL_SERVER - Table_map_log_event(THD *thd, TABLE *tbl, ulong tid, bool is_transactional); -#endif -#ifdef HAVE_REPLICATION - Table_map_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif - - ~Table_map_log_event(); - -#ifdef MYSQL_CLIENT - table_def *create_table_def() - { - return new table_def(m_coltype, m_colcnt, m_field_metadata, - m_field_metadata_size, m_null_bits, m_flags); - } - int rewrite_db(const char* new_name, size_t new_name_len, - const Format_description_log_event*); -#endif - ulonglong get_table_id() const { return m_table_id; } - const char *get_table_name() const { return m_tblnam; } - const char *get_db_name() const { return m_dbnam; } - - virtual Log_event_type get_type_code() { return TABLE_MAP_EVENT; } - virtual enum_logged_status logged_status() { return LOGGED_TABLE_MAP; } - virtual bool is_valid() const { return m_memory != NULL; /* we check malloc */ } - virtual bool is_part_of_group() { return 1; } - - virtual int get_data_size() { return (uint) m_data_size; } -#ifdef MYSQL_SERVER - virtual int save_field_metadata(); - virtual bool write_data_header(); - virtual bool write_data_body(); - virtual const char *get_db() { return m_dbnam; } -#endif - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual void pack_info(Protocol *protocol); -#endif - -#ifdef MYSQL_CLIENT - virtual bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - - -private: -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); -#endif - -#ifdef MYSQL_SERVER - TABLE *m_table; - Binlog_type_info *binlog_type_info_array; - - - // Metadata fields buffer - StringBuffer<1024> m_metadata_buf; - - /** - Capture the optional metadata fields which should be logged into - table_map_log_event and serialize them into m_metadata_buf. - */ - void init_metadata_fields(); - bool init_signedness_field(); - /** - Capture and serialize character sets. Character sets for - character columns (TEXT etc) and character sets for ENUM and SET - columns are stored in different metadata fields. The reason is - that TEXT character sets are included even when - binlog_row_metadata=MINIMAL, whereas ENUM and SET character sets - are included only when binlog_row_metadata=FULL. - - @param include_type Predicate to determine if a given Field object - is to be included in the metadata field. - - @param default_charset_type Type code when storing in "default - charset" format. (See comment above Table_maps_log_event in - libbinlogevents/include/rows_event.h) - - @param column_charset_type Type code when storing in "column - charset" format. (See comment above Table_maps_log_event in - libbinlogevents/include/rows_event.h) - */ - bool init_charset_field(bool(* include_type)(Binlog_type_info *, Field *), - Optional_metadata_field_type default_charset_type, - Optional_metadata_field_type column_charset_type); - bool init_column_name_field(); - bool init_set_str_value_field(); - bool init_enum_str_value_field(); - bool init_geometry_type_field(); - bool init_primary_key_field(); -#endif - -#ifdef MYSQL_CLIENT - class Charset_iterator; - class Default_charset_iterator; - class Column_charset_iterator; -#endif - char const *m_dbnam; - size_t m_dblen; - char const *m_tblnam; - size_t m_tbllen; - ulong m_colcnt; - uchar *m_coltype; - - uchar *m_memory; - ulonglong m_table_id; - flag_set m_flags; - - size_t m_data_size; - - uchar *m_field_metadata; // buffer for field metadata - /* - The size of field metadata buffer set by calling save_field_metadata() - */ - ulong m_field_metadata_size; - uchar *m_null_bits; - uchar *m_meta_memory; - unsigned int m_optional_metadata_len; - unsigned char *m_optional_metadata; -}; - - -/** - @class Rows_log_event - - Common base class for all row-containing log events. - - RESPONSIBILITIES - - Encode the common parts of all events containing rows, which are: - - Write data header and data body to an IO_CACHE. - - Provide an interface for adding an individual row to the event. - - @section Rows_log_event_binary_format Binary Format -*/ - - -class Rows_log_event : public Log_event -{ -public: - /** - Enumeration of the errors that can be returned. - */ - enum enum_error - { - ERR_OPEN_FAILURE = -1, /**< Failure to open table */ - ERR_OK = 0, /**< No error */ - ERR_TABLE_LIMIT_EXCEEDED = 1, /**< No more room for tables */ - ERR_OUT_OF_MEM = 2, /**< Out of memory */ - ERR_BAD_TABLE_DEF = 3, /**< Table definition does not match */ - ERR_RBR_TO_SBR = 4 /**< daisy-chanining RBR to SBR not allowed */ - }; - - /* - These definitions allow you to combine the flags into an - appropriate flag set using the normal bitwise operators. The - implicit conversion from an enum-constant to an integer is - accepted by the compiler, which is then used to set the real set - of flags. - */ - enum enum_flag - { - /* Last event of a statement */ - STMT_END_F = (1U << 0), - - /* Value of the OPTION_NO_FOREIGN_KEY_CHECKS flag in thd->options */ - NO_FOREIGN_KEY_CHECKS_F = (1U << 1), - - /* Value of the OPTION_RELAXED_UNIQUE_CHECKS flag in thd->options */ - RELAXED_UNIQUE_CHECKS_F = (1U << 2), - - /** - Indicates that rows in this event are complete, that is contain - values for all columns of the table. - */ - COMPLETE_ROWS_F = (1U << 3), - - /* Value of the OPTION_NO_CHECK_CONSTRAINT_CHECKS flag in thd->options */ - NO_CHECK_CONSTRAINT_CHECKS_F = (1U << 7) - }; - - typedef uint16 flag_set; - - /* Special constants representing sets of flags */ - enum - { - RLE_NO_FLAGS = 0U - }; - - virtual ~Rows_log_event(); - - void set_flags(flag_set flags_arg) { m_flags |= flags_arg; } - void clear_flags(flag_set flags_arg) { m_flags &= ~flags_arg; } - flag_set get_flags(flag_set flags_arg) const { return m_flags & flags_arg; } - void update_flags() { int2store(temp_buf + m_flags_pos, m_flags); } - - Log_event_type get_type_code() { return m_type; } /* Specific type (_V1 etc) */ - enum_logged_status logged_status() { return LOGGED_ROW_EVENT; } - virtual Log_event_type get_general_type_code() = 0; /* General rows op type, no version */ - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual void pack_info(Protocol *protocol); -#endif - -#ifdef MYSQL_CLIENT - /* not for direct call, each derived has its own ::print() */ - virtual bool print(FILE *file, PRINT_EVENT_INFO *print_event_info)= 0; - void change_to_flashback_event(PRINT_EVENT_INFO *print_event_info, uchar *rows_buff, Log_event_type ev_type); - bool print_verbose(IO_CACHE *file, - PRINT_EVENT_INFO *print_event_info); - size_t print_verbose_one_row(IO_CACHE *file, table_def *td, - PRINT_EVENT_INFO *print_event_info, - MY_BITMAP *cols_bitmap, - const uchar *ptr, const uchar *prefix, - const my_bool no_fill_output= 0); // if no_fill_output=1, then print result is unnecessary - size_t calc_row_event_length(table_def *td, - PRINT_EVENT_INFO *print_event_info, - MY_BITMAP *cols_bitmap, - const uchar *value); - void count_row_events(PRINT_EVENT_INFO *print_event_info); - -#endif - -#ifdef MYSQL_SERVER - int add_row_data(uchar *data, size_t length) - { - return do_add_row_data(data,length); - } -#endif - - /* Member functions to implement superclass interface */ - virtual int get_data_size(); - - MY_BITMAP const *get_cols() const { return &m_cols; } - MY_BITMAP const *get_cols_ai() const { return &m_cols_ai; } - size_t get_width() const { return m_width; } - ulonglong get_table_id() const { return m_table_id; } - -#if defined(MYSQL_SERVER) - /* - This member function compares the table's read/write_set - with this event's m_cols and m_cols_ai. Comparison takes - into account what type of rows event is this: Delete, Write or - Update, therefore it uses the correct m_cols[_ai] according - to the event type code. - - Note that this member function should only be called for the - following events: - - Delete_rows_log_event - - Write_rows_log_event - - Update_rows_log_event - - @param[IN] table The table to compare this events bitmaps - against. - - @return TRUE if sets match, FALSE otherwise. (following - bitmap_cmp return logic). - - */ - bool read_write_bitmaps_cmp(TABLE *table) - { - bool res= FALSE; - - switch (get_general_type_code()) - { - case DELETE_ROWS_EVENT: - res= bitmap_cmp(get_cols(), table->read_set); - break; - case UPDATE_ROWS_EVENT: - res= (bitmap_cmp(get_cols(), table->read_set) && - bitmap_cmp(get_cols_ai(), table->rpl_write_set)); - break; - case WRITE_ROWS_EVENT: - res= bitmap_cmp(get_cols(), table->rpl_write_set); - break; - default: - /* - We should just compare bitmaps for Delete, Write - or Update rows events. - */ - DBUG_ASSERT(0); - } - return res; - } -#endif - -#ifdef MYSQL_SERVER - virtual bool write_data_header(); - virtual bool write_data_body(); - virtual bool write_compressed(); - virtual const char *get_db() { return m_table->s->db.str; } -#endif - /* - Check that malloc() succeeded in allocating memory for the rows - buffer and the COLS vector. Checking that an Update_rows_log_event - is valid is done in the Update_rows_log_event::is_valid() - function. - */ - virtual bool is_valid() const - { - return m_rows_buf && m_cols.bitmap; - } - bool is_part_of_group() { return get_flags(STMT_END_F) != 0; } - - uint m_row_count; /* The number of rows added to the event */ - - const uchar* get_extra_row_data() const { return m_extra_row_data; } - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual uint8 get_trg_event_map()= 0; - - inline bool do_invoke_trigger() - { - return (slave_run_triggers_for_rbr && !master_had_triggers) || - slave_run_triggers_for_rbr == SLAVE_RUN_TRIGGERS_FOR_RBR_ENFORCE; - } -#endif - -protected: - /* - The constructors are protected since you're supposed to inherit - this class, not create instances of this class. - */ -#ifdef MYSQL_SERVER - Rows_log_event(THD*, TABLE*, ulong table_id, - MY_BITMAP const *cols, bool is_transactional, - Log_event_type event_type); -#endif - Rows_log_event(const char *row_data, uint event_len, - const Format_description_log_event *description_event); - void uncompress_buf(); - -#ifdef MYSQL_CLIENT - bool print_helper(FILE *, PRINT_EVENT_INFO *, char const *const name); -#endif - -#ifdef MYSQL_SERVER - virtual int do_add_row_data(uchar *data, size_t length); -#endif - -#ifdef MYSQL_SERVER - TABLE *m_table; /* The table the rows belong to */ -#endif - ulonglong m_table_id; /* Table ID */ - MY_BITMAP m_cols; /* Bitmap denoting columns available */ - ulong m_width; /* The width of the columns bitmap */ - /* - Bitmap for columns available in the after image, if present. These - fields are only available for Update_rows events. Observe that the - width of both the before image COLS vector and the after image - COLS vector is the same: the number of columns of the table on the - master. - */ - MY_BITMAP m_cols_ai; - - ulong m_master_reclength; /* Length of record on master side */ - - /* Bit buffers in the same memory as the class */ - uint32 m_bitbuf[128/(sizeof(uint32)*8)]; - uint32 m_bitbuf_ai[128/(sizeof(uint32)*8)]; - - uchar *m_rows_buf; /* The rows in packed format */ - uchar *m_rows_cur; /* One-after the end of the data */ - uchar *m_rows_end; /* One-after the end of the allocated space */ - - size_t m_rows_before_size; /* The length before m_rows_buf */ - size_t m_flags_pos; /* The position of the m_flags */ - - flag_set m_flags; /* Flags for row-level events */ - - Log_event_type m_type; /* Actual event type */ - - uchar *m_extra_row_data; /* Pointer to extra row data if any */ - /* If non null, first byte is length */ - - bool m_vers_from_plain; - - - /* helper functions */ - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - const uchar *m_curr_row; /* Start of the row being processed */ - const uchar *m_curr_row_end; /* One-after the end of the current row */ - uchar *m_key; /* Buffer to keep key value during searches */ - KEY *m_key_info; /* Pointer to KEY info for m_key_nr */ - uint m_key_nr; /* Key number */ - bool master_had_triggers; /* set after tables opening */ - - int find_key(); // Find a best key to use in find_row() - int find_row(rpl_group_info *); - int write_row(rpl_group_info *, const bool); - int update_sequence(); - - // Unpack the current row into m_table->record[0], but with - // a different columns bitmap. - int unpack_current_row(rpl_group_info *rgi, MY_BITMAP const *cols) - { - DBUG_ASSERT(m_table); - - ASSERT_OR_RETURN_ERROR(m_curr_row <= m_rows_end, HA_ERR_CORRUPT_EVENT); - return ::unpack_row(rgi, m_table, m_width, m_curr_row, cols, - &m_curr_row_end, &m_master_reclength, m_rows_end); - } - - // Unpack the current row into m_table->record[0] - int unpack_current_row(rpl_group_info *rgi) - { - DBUG_ASSERT(m_table); - - ASSERT_OR_RETURN_ERROR(m_curr_row <= m_rows_end, HA_ERR_CORRUPT_EVENT); - return ::unpack_row(rgi, m_table, m_width, m_curr_row, &m_cols, - &m_curr_row_end, &m_master_reclength, m_rows_end); - } - bool process_triggers(trg_event_type event, - trg_action_time_type time_type, - bool old_row_is_record1); - - /** - Helper function to check whether there is an auto increment - column on the table where the event is to be applied. - - @return true if there is an autoincrement field on the extra - columns, false otherwise. - */ - inline bool is_auto_inc_in_extra_columns() - { - DBUG_ASSERT(m_table); - return (m_table->next_number_field && - m_table->next_number_field->field_index >= m_width); - } -#endif - -private: - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); - - /* - Primitive to prepare for a sequence of row executions. - - DESCRIPTION - - Before doing a sequence of do_prepare_row() and do_exec_row() - calls, this member function should be called to prepare for the - entire sequence. Typically, this member function will allocate - space for any buffers that are needed for the two member - functions mentioned above. - - RETURN VALUE - - The member function will return 0 if all went OK, or a non-zero - error code otherwise. - */ - virtual - int do_before_row_operations(const Slave_reporting_capability *const log) = 0; - - /* - Primitive to clean up after a sequence of row executions. - - DESCRIPTION - - After doing a sequence of do_prepare_row() and do_exec_row(), - this member function should be called to clean up and release - any allocated buffers. - - The error argument, if non-zero, indicates an error which happened during - row processing before this function was called. In this case, even if - function is successful, it should return the error code given in the argument. - */ - virtual - int do_after_row_operations(const Slave_reporting_capability *const log, - int error) = 0; - - /* - Primitive to do the actual execution necessary for a row. - - DESCRIPTION - The member function will do the actual execution needed to handle a row. - The row is located at m_curr_row. When the function returns, - m_curr_row_end should point at the next row (one byte after the end - of the current row). - - RETURN VALUE - 0 if execution succeeded, 1 if execution failed. - - */ - virtual int do_exec_row(rpl_group_info *rli) = 0; -#endif /* defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) */ - - friend class Old_rows_log_event; -}; - -/** - @class Write_rows_log_event - - Log row insertions and updates. The event contain several - insert/update rows for a table. Note that each event contains only - rows for one table. - - @section Write_rows_log_event_binary_format Binary Format -*/ -class Write_rows_log_event : public Rows_log_event -{ -public: - enum - { - /* Support interface to THD::binlog_prepare_pending_rows_event */ - TYPE_CODE = WRITE_ROWS_EVENT - }; - -#if defined(MYSQL_SERVER) - Write_rows_log_event(THD*, TABLE*, ulong table_id, - bool is_transactional); -#endif -#ifdef HAVE_REPLICATION - Write_rows_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif -#if defined(MYSQL_SERVER) - static bool binlog_row_logging_function(THD *thd, TABLE *table, - bool is_transactional, - const uchar *before_record - __attribute__((unused)), - const uchar *after_record) - { - DBUG_ASSERT(!table->versioned(VERS_TRX_ID)); - return thd->binlog_write_row(table, is_transactional, after_record); - } -#endif - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - uint8 get_trg_event_map(); -#endif - -private: - virtual Log_event_type get_general_type_code() { return (Log_event_type)TYPE_CODE; } - -#ifdef MYSQL_CLIENT - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_before_row_operations(const Slave_reporting_capability *const); - virtual int do_after_row_operations(const Slave_reporting_capability *const,int); - virtual int do_exec_row(rpl_group_info *); -#endif -}; - -class Write_rows_compressed_log_event : public Write_rows_log_event -{ -public: -#if defined(MYSQL_SERVER) - Write_rows_compressed_log_event(THD*, TABLE*, ulong table_id, - bool is_transactional); - virtual bool write(); -#endif -#ifdef HAVE_REPLICATION - Write_rows_compressed_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif -private: -#if defined(MYSQL_CLIENT) - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif -}; - -/** - @class Update_rows_log_event - - Log row updates with a before image. The event contain several - update rows for a table. Note that each event contains only rows for - one table. - - Also note that the row data consists of pairs of row data: one row - for the old data and one row for the new data. - - @section Update_rows_log_event_binary_format Binary Format -*/ -class Update_rows_log_event : public Rows_log_event -{ -public: - enum - { - /* Support interface to THD::binlog_prepare_pending_rows_event */ - TYPE_CODE = UPDATE_ROWS_EVENT - }; - -#ifdef MYSQL_SERVER - Update_rows_log_event(THD*, TABLE*, ulong table_id, - bool is_transactional); - - void init(MY_BITMAP const *cols); -#endif - - virtual ~Update_rows_log_event(); - -#ifdef HAVE_REPLICATION - Update_rows_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif - -#ifdef MYSQL_SERVER - static bool binlog_row_logging_function(THD *thd, TABLE *table, - bool is_transactional, - const uchar *before_record, - const uchar *after_record) - { - DBUG_ASSERT(!table->versioned(VERS_TRX_ID)); - return thd->binlog_update_row(table, is_transactional, - before_record, after_record); - } -#endif - - virtual bool is_valid() const - { - return Rows_log_event::is_valid() && m_cols_ai.bitmap; - } - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - uint8 get_trg_event_map(); -#endif - -protected: - virtual Log_event_type get_general_type_code() { return (Log_event_type)TYPE_CODE; } - -#ifdef MYSQL_CLIENT - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_before_row_operations(const Slave_reporting_capability *const); - virtual int do_after_row_operations(const Slave_reporting_capability *const,int); - virtual int do_exec_row(rpl_group_info *); -#endif /* defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) */ -}; - -class Update_rows_compressed_log_event : public Update_rows_log_event -{ -public: -#if defined(MYSQL_SERVER) - Update_rows_compressed_log_event(THD*, TABLE*, ulong table_id, - bool is_transactional); - virtual bool write(); -#endif -#ifdef HAVE_REPLICATION - Update_rows_compressed_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif -private: -#if defined(MYSQL_CLIENT) - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif -}; - -/** - @class Delete_rows_log_event - - Log row deletions. The event contain several delete rows for a - table. Note that each event contains only rows for one table. - - RESPONSIBILITIES - - - Act as a container for rows that has been deleted on the master - and should be deleted on the slave. - - COLLABORATION - - Row_writer - Create the event and add rows to the event. - Row_reader - Extract the rows from the event. - - @section Delete_rows_log_event_binary_format Binary Format -*/ -class Delete_rows_log_event : public Rows_log_event -{ -public: - enum - { - /* Support interface to THD::binlog_prepare_pending_rows_event */ - TYPE_CODE = DELETE_ROWS_EVENT - }; - -#ifdef MYSQL_SERVER - Delete_rows_log_event(THD*, TABLE*, ulong, bool is_transactional); -#endif -#ifdef HAVE_REPLICATION - Delete_rows_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif -#ifdef MYSQL_SERVER - static bool binlog_row_logging_function(THD *thd, TABLE *table, - bool is_transactional, - const uchar *before_record, - const uchar *after_record - __attribute__((unused))) - { - DBUG_ASSERT(!table->versioned(VERS_TRX_ID)); - return thd->binlog_delete_row(table, is_transactional, - before_record); - } -#endif - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - uint8 get_trg_event_map(); -#endif - -protected: - virtual Log_event_type get_general_type_code() { return (Log_event_type)TYPE_CODE; } - -#ifdef MYSQL_CLIENT - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_before_row_operations(const Slave_reporting_capability *const); - virtual int do_after_row_operations(const Slave_reporting_capability *const,int); - virtual int do_exec_row(rpl_group_info *); -#endif -}; - -class Delete_rows_compressed_log_event : public Delete_rows_log_event -{ -public: -#if defined(MYSQL_SERVER) - Delete_rows_compressed_log_event(THD*, TABLE*, ulong, bool is_transactional); - virtual bool write(); -#endif -#ifdef HAVE_REPLICATION - Delete_rows_compressed_log_event(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif -private: -#if defined(MYSQL_CLIENT) - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif -}; - - -#include "log_event_old.h" - -/** - @class Incident_log_event - - Class representing an incident, an occurence out of the ordinary, - that happened on the master. - - The event is used to inform the slave that something out of the - ordinary happened on the master that might cause the database to be - in an inconsistent state. - - - - - - - - - - - - - - - - - - - - - - - -
Incident event format
SymbolFormatDescription
INCIDENT2Incident number as an unsigned integer
MSGLEN1Message length as an unsigned integer
MESSAGEMSGLENThe message, if present. Not null terminated.
- - @section Delete_rows_log_event_binary_format Binary Format -*/ -class Incident_log_event : public Log_event { -public: -#ifdef MYSQL_SERVER - Incident_log_event(THD *thd_arg, Incident incident) - : Log_event(thd_arg, 0, FALSE), m_incident(incident) - { - DBUG_ENTER("Incident_log_event::Incident_log_event"); - DBUG_PRINT("enter", ("m_incident: %d", m_incident)); - m_message.str= NULL; /* Just as a precaution */ - m_message.length= 0; - set_direct_logging(); - /* Replicate the incident regardless of @@skip_replication. */ - flags&= ~LOG_EVENT_SKIP_REPLICATION_F; - DBUG_VOID_RETURN; - } - - Incident_log_event(THD *thd_arg, Incident incident, const LEX_CSTRING *msg) - : Log_event(thd_arg, 0, FALSE), m_incident(incident) - { - extern PSI_memory_key key_memory_Incident_log_event_message; - DBUG_ENTER("Incident_log_event::Incident_log_event"); - DBUG_PRINT("enter", ("m_incident: %d", m_incident)); - m_message.length= 0; - if (!(m_message.str= (char*) my_malloc(key_memory_Incident_log_event_message, - msg->length + 1, MYF(MY_WME)))) - { - /* Mark this event invalid */ - m_incident= INCIDENT_NONE; - DBUG_VOID_RETURN; - } - strmake(m_message.str, msg->str, msg->length); - m_message.length= msg->length; - set_direct_logging(); - /* Replicate the incident regardless of @@skip_replication. */ - flags&= ~LOG_EVENT_SKIP_REPLICATION_F; - DBUG_VOID_RETURN; - } -#endif - -#ifdef MYSQL_SERVER - void pack_info(Protocol*); - - virtual bool write_data_header(); - virtual bool write_data_body(); -#endif - - Incident_log_event(const char *buf, uint event_len, - const Format_description_log_event *descr_event); - - virtual ~Incident_log_event(); - -#ifdef MYSQL_CLIENT - virtual bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - -#if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); -#endif - - virtual Log_event_type get_type_code() { return INCIDENT_EVENT; } - - virtual bool is_valid() const - { - return m_incident > INCIDENT_NONE && m_incident < INCIDENT_COUNT; - } - virtual int get_data_size() { - return INCIDENT_HEADER_LEN + 1 + (uint) m_message.length; - } - -private: - const char *description() const; - - Incident m_incident; - LEX_STRING m_message; -}; - -/** - @class Ignorable_log_event - - Base class for ignorable log events. Events deriving from - this class can be safely ignored by slaves that cannot - recognize them. Newer slaves, will be able to read and - handle them. This has been designed to be an open-ended - architecture, so adding new derived events shall not harm - the old slaves that support ignorable log event mechanism - (they will just ignore unrecognized ignorable events). - - @note The only thing that makes an event ignorable is that it has - the LOG_EVENT_IGNORABLE_F flag set. It is not strictly necessary - that ignorable event types derive from Ignorable_log_event; they may - just as well derive from Log_event and pass LOG_EVENT_IGNORABLE_F as - argument to the Log_event constructor. -**/ - -class Ignorable_log_event : public Log_event { -public: - int number; - const char *description; - -#ifndef MYSQL_CLIENT - Ignorable_log_event(THD *thd_arg) - :Log_event(thd_arg, LOG_EVENT_IGNORABLE_F, FALSE), - number(0), description("internal") - { - DBUG_ENTER("Ignorable_log_event::Ignorable_log_event"); - DBUG_VOID_RETURN; - } -#endif - - Ignorable_log_event(const char *buf, - const Format_description_log_event *descr_event, - const char *event_name); - virtual ~Ignorable_log_event(); - -#ifndef MYSQL_CLIENT - void pack_info(Protocol*); -#endif - -#ifdef MYSQL_CLIENT - virtual bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - - virtual Log_event_type get_type_code() { return IGNORABLE_LOG_EVENT; } - - virtual bool is_valid() const { return 1; } - - virtual int get_data_size() { return IGNORABLE_HEADER_LEN; } -}; - -#ifdef MYSQL_CLIENT -bool copy_cache_to_string_wrapped(IO_CACHE *body, - LEX_STRING *to, - bool do_wrap, - const char *delimiter, - bool is_verbose); -bool copy_cache_to_file_wrapped(IO_CACHE *body, - FILE *file, - bool do_wrap, - const char *delimiter, - bool is_verbose); -#endif - -#ifdef MYSQL_SERVER -/***************************************************************************** - - Heartbeat Log Event class - - Replication event to ensure to slave that master is alive. - The event is originated by master's dump thread and sent straight to - slave without being logged. Slave itself does not store it in relay log - but rather uses a data for immediate checks and throws away the event. - - Two members of the class log_ident and Log_event::log_pos comprise - @see the event_coordinates instance. The coordinates that a heartbeat - instance carries correspond to the last event master has sent from - its binlog. - - ****************************************************************************/ -class Heartbeat_log_event: public Log_event -{ -public: - Heartbeat_log_event(const char* buf, uint event_len, - const Format_description_log_event* description_event); - Log_event_type get_type_code() { return HEARTBEAT_LOG_EVENT; } - bool is_valid() const - { - return (log_ident != NULL && - log_pos >= BIN_LOG_HEADER_SIZE); - } - const char * get_log_ident() { return log_ident; } - uint get_ident_len() { return ident_len; } - -private: - const char* log_ident; - uint ident_len; -}; - -inline int Log_event_writer::write(Log_event *ev) -{ - ev->writer= this; - int res= ev->write(); - IF_DBUG(ev->writer= 0,); // writer must be set before every Log_event::write - add_status(ev->logged_status()); - return res; -} - -/** - The function is called by slave applier in case there are - active table filtering rules to force gathering events associated - with Query-log-event into an array to execute - them once the fate of the Query is determined for execution. -*/ -bool slave_execute_deferred_events(THD *thd); -#endif - -bool event_that_should_be_ignored(const char *buf); -bool event_checksum_test(uchar *buf, ulong event_len, enum_binlog_checksum_alg alg); -enum enum_binlog_checksum_alg get_checksum_alg(const char* buf, ulong len); -extern TYPELIB binlog_checksum_typelib; -#ifdef WITH_WSREP -enum Log_event_type wsrep_peak_event(rpl_group_info *rgi, ulonglong* event_size); -#endif /* WITH_WSREP */ - -/** - @} (end of group Replication) -*/ - - -int binlog_buf_compress(const char *src, char *dst, uint32 len, uint32 *comlen); -int binlog_buf_uncompress(const char *src, char *dst, uint32 len, uint32 *newlen); -uint32 binlog_get_compress_len(uint32 len); -uint32 binlog_get_uncompress_len(const char *buf); - -int query_event_uncompress(const Format_description_log_event *description_event, bool contain_checksum, - const char *src, ulong src_len, char* buf, ulong buf_size, bool* is_malloc, - char **dst, ulong *newlen); - -int row_log_event_uncompress(const Format_description_log_event *description_event, bool contain_checksum, - const char *src, ulong src_len, char* buf, ulong buf_size, bool* is_malloc, - char **dst, ulong *newlen); - -#endif /* _log_event_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_event_old.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_event_old.h deleted file mode 100644 index 3a11313..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_event_old.h +++ /dev/null @@ -1,569 +0,0 @@ -/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef LOG_EVENT_OLD_H -#define LOG_EVENT_OLD_H - -/* - Need to include this file at the proper position of log_event.h - */ - - -/** - @file - - @brief This file contains classes handling old formats of row-based - binlog events. -*/ -/* - Around 2007-10-31, I made these classes completely separated from - the new classes (before, there was a complex class hierarchy - involving multiple inheritance; see BUG#31581), by simply copying - and pasting the entire contents of Rows_log_event into - Old_rows_log_event and the entire contents of - {Write|Update|Delete}_rows_log_event into - {Write|Update|Delete}_rows_log_event_old. For clarity, I will keep - the comments marking which code was cut-and-pasted for some time. - With the classes collapsed into one, there is probably some - redundancy (maybe some methods can be simplified and/or removed), - but we keep them this way for now. /Sven -*/ - -/* These classes are based on the v1 RowsHeaderLen */ -#undef ROWS_HEADER_LEN -#define ROWS_HEADER_LEN ROWS_HEADER_LEN_V1 - -/** - @class Old_rows_log_event - - Base class for the three types of row-based events - {Write|Update|Delete}_row_log_event_old, with event type codes - PRE_GA_{WRITE|UPDATE|DELETE}_ROWS_EVENT. These events are never - created any more, except when reading a relay log created by an old - server. -*/ -class Old_rows_log_event : public Log_event -{ - /********** BEGIN CUT & PASTE FROM Rows_log_event **********/ -public: - /** - Enumeration of the errors that can be returned. - */ - enum enum_error - { - ERR_OPEN_FAILURE = -1, /**< Failure to open table */ - ERR_OK = 0, /**< No error */ - ERR_TABLE_LIMIT_EXCEEDED = 1, /**< No more room for tables */ - ERR_OUT_OF_MEM = 2, /**< Out of memory */ - ERR_BAD_TABLE_DEF = 3, /**< Table definition does not match */ - ERR_RBR_TO_SBR = 4 /**< daisy-chanining RBR to SBR not allowed */ - }; - - /* - These definitions allow you to combine the flags into an - appropriate flag set using the normal bitwise operators. The - implicit conversion from an enum-constant to an integer is - accepted by the compiler, which is then used to set the real set - of flags. - */ - enum enum_flag - { - /* Last event of a statement */ - STMT_END_F = (1U << 0), - - /* Value of the OPTION_NO_FOREIGN_KEY_CHECKS flag in thd->options */ - NO_FOREIGN_KEY_CHECKS_F = (1U << 1), - - /* Value of the OPTION_RELAXED_UNIQUE_CHECKS flag in thd->options */ - RELAXED_UNIQUE_CHECKS_F = (1U << 2), - - /** - Indicates that rows in this event are complete, that is contain - values for all columns of the table. - */ - COMPLETE_ROWS_F = (1U << 3) - }; - - typedef uint16 flag_set; - - /* Special constants representing sets of flags */ - enum - { - RLE_NO_FLAGS = 0U - }; - - virtual ~Old_rows_log_event(); - - void set_flags(flag_set flags_arg) { m_flags |= flags_arg; } - void clear_flags(flag_set flags_arg) { m_flags &= ~flags_arg; } - flag_set get_flags(flag_set flags_arg) const { return m_flags & flags_arg; } - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - virtual void pack_info(Protocol *protocol); -#endif - -#ifdef MYSQL_CLIENT - /* not for direct call, each derived has its own ::print() */ - virtual bool print(FILE *file, PRINT_EVENT_INFO *print_event_info)= 0; -#endif - -#ifndef MYSQL_CLIENT - int add_row_data(uchar *data, size_t length) - { - return do_add_row_data(data,length); - } -#endif - - /* Member functions to implement superclass interface */ - virtual int get_data_size(); - - MY_BITMAP const *get_cols() const { return &m_cols; } - size_t get_width() const { return m_width; } - ulong get_table_id() const { return m_table_id; } - -#ifndef MYSQL_CLIENT - virtual bool write_data_header(); - virtual bool write_data_body(); - virtual const char *get_db() { return m_table->s->db.str; } -#endif - /* - Check that malloc() succeeded in allocating memory for the rows - buffer and the COLS vector. Checking that an Update_rows_log_event_old - is valid is done in the Update_rows_log_event_old::is_valid() - function. - */ - virtual bool is_valid() const - { - return m_rows_buf && m_cols.bitmap; - } - bool is_part_of_group() { return 1; } - - uint m_row_count; /* The number of rows added to the event */ - -protected: - /* - The constructors are protected since you're supposed to inherit - this class, not create instances of this class. - */ -#ifndef MYSQL_CLIENT - Old_rows_log_event(THD*, TABLE*, ulong table_id, - MY_BITMAP const *cols, bool is_transactional); -#endif - Old_rows_log_event(const char *row_data, uint event_len, - Log_event_type event_type, - const Format_description_log_event *description_event); - -#ifdef MYSQL_CLIENT - bool print_helper(FILE *, PRINT_EVENT_INFO *, char const *const name); -#endif - -#ifndef MYSQL_CLIENT - virtual int do_add_row_data(uchar *data, size_t length); -#endif - -#ifndef MYSQL_CLIENT - TABLE *m_table; /* The table the rows belong to */ -#endif - ulong m_table_id; /* Table ID */ - MY_BITMAP m_cols; /* Bitmap denoting columns available */ - ulong m_width; /* The width of the columns bitmap */ - - ulong m_master_reclength; /* Length of record on master side */ - - /* Bit buffers in the same memory as the class */ - uint32 m_bitbuf[128/(sizeof(uint32)*8)]; - uint32 m_bitbuf_ai[128/(sizeof(uint32)*8)]; - - uchar *m_rows_buf; /* The rows in packed format */ - uchar *m_rows_cur; /* One-after the end of the data */ - uchar *m_rows_end; /* One-after the end of the allocated space */ - - flag_set m_flags; /* Flags for row-level events */ - - /* helper functions */ - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - const uchar *m_curr_row; /* Start of the row being processed */ - const uchar *m_curr_row_end; /* One-after the end of the current row */ - uchar *m_key; /* Buffer to keep key value during searches */ - - int find_row(rpl_group_info *); - int write_row(rpl_group_info *, const bool); - - // Unpack the current row into m_table->record[0] - int unpack_current_row(rpl_group_info *rgi) - { - DBUG_ASSERT(m_table); - ASSERT_OR_RETURN_ERROR(m_curr_row < m_rows_end, HA_ERR_CORRUPT_EVENT); - return ::unpack_row(rgi, m_table, m_width, m_curr_row, &m_cols, - &m_curr_row_end, &m_master_reclength, m_rows_end); - } -#endif - -private: - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - virtual int do_apply_event(rpl_group_info *rgi); - virtual int do_update_pos(rpl_group_info *rgi); - virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); - - /* - Primitive to prepare for a sequence of row executions. - - DESCRIPTION - - Before doing a sequence of do_prepare_row() and do_exec_row() - calls, this member function should be called to prepare for the - entire sequence. Typically, this member function will allocate - space for any buffers that are needed for the two member - functions mentioned above. - - RETURN VALUE - - The member function will return 0 if all went OK, or a non-zero - error code otherwise. - */ - virtual - int do_before_row_operations(const Slave_reporting_capability *const log) = 0; - - /* - Primitive to clean up after a sequence of row executions. - - DESCRIPTION - - After doing a sequence of do_prepare_row() and do_exec_row(), - this member function should be called to clean up and release - any allocated buffers. - - The error argument, if non-zero, indicates an error which happened during - row processing before this function was called. In this case, even if - function is successful, it should return the error code given in the argument. - */ - virtual - int do_after_row_operations(const Slave_reporting_capability *const log, - int error) = 0; - - /* - Primitive to do the actual execution necessary for a row. - - DESCRIPTION - The member function will do the actual execution needed to handle a row. - The row is located at m_curr_row. When the function returns, - m_curr_row_end should point at the next row (one byte after the end - of the current row). - - RETURN VALUE - 0 if execution succeeded, 1 if execution failed. - - */ - virtual int do_exec_row(rpl_group_info *rgi) = 0; -#endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ - - /********** END OF CUT & PASTE FROM Rows_log_event **********/ - protected: - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - - int do_apply_event(Old_rows_log_event*, rpl_group_info *rgi); - - /* - Primitive to prepare for a sequence of row executions. - - DESCRIPTION - - Before doing a sequence of do_prepare_row() and do_exec_row() - calls, this member function should be called to prepare for the - entire sequence. Typically, this member function will allocate - space for any buffers that are needed for the two member - functions mentioned above. - - RETURN VALUE - - The member function will return 0 if all went OK, or a non-zero - error code otherwise. - */ - virtual int do_before_row_operations(TABLE *table) = 0; - - /* - Primitive to clean up after a sequence of row executions. - - DESCRIPTION - - After doing a sequence of do_prepare_row() and do_exec_row(), - this member function should be called to clean up and release - any allocated buffers. - */ - virtual int do_after_row_operations(TABLE *table, int error) = 0; - - /* - Primitive to prepare for handling one row in a row-level event. - - DESCRIPTION - - The member function prepares for execution of operations needed for one - row in a row-level event by reading up data from the buffer containing - the row. No specific interpretation of the data is normally done here, - since SQL thread specific data is not available: that data is made - available for the do_exec function. - - A pointer to the start of the next row, or NULL if the preparation - failed. Currently, preparation cannot fail, but don't rely on this - behavior. - - RETURN VALUE - Error code, if something went wrong, 0 otherwise. - */ - virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, - uchar const *row_start, - uchar const **row_end) = 0; - - /* - Primitive to do the actual execution necessary for a row. - - DESCRIPTION - The member function will do the actual execution needed to handle a row. - - RETURN VALUE - 0 if execution succeeded, 1 if execution failed. - - */ - virtual int do_exec_row(TABLE *table) = 0; - -#endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ -}; - - -/** - @class Write_rows_log_event_old - - Old class for binlog events that write new rows to a table (event - type code PRE_GA_WRITE_ROWS_EVENT). Such events are never produced - by this version of the server, but they may be read from a relay log - created by an old server. New servers create events of class - Write_rows_log_event (event type code WRITE_ROWS_EVENT) instead. -*/ -class Write_rows_log_event_old : public Old_rows_log_event -{ - /********** BEGIN CUT & PASTE FROM Write_rows_log_event **********/ -public: -#if !defined(MYSQL_CLIENT) - Write_rows_log_event_old(THD*, TABLE*, ulong table_id, - MY_BITMAP const *cols, bool is_transactional); -#endif -#ifdef HAVE_REPLICATION - Write_rows_log_event_old(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif -#if !defined(MYSQL_CLIENT) - static bool binlog_row_logging_function(THD *thd, TABLE *table, - bool is_transactional, - const uchar *before_record - __attribute__((unused)), - const uchar *after_record) - { - return thd->binlog_write_row(table, is_transactional, after_record); - } -#endif - -private: -#ifdef MYSQL_CLIENT - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - virtual int do_before_row_operations(const Slave_reporting_capability *const); - virtual int do_after_row_operations(const Slave_reporting_capability *const,int); - virtual int do_exec_row(rpl_group_info *); -#endif - /********** END OF CUT & PASTE FROM Write_rows_log_event **********/ - -public: - enum - { - /* Support interface to THD::binlog_prepare_pending_rows_event */ - TYPE_CODE = PRE_GA_WRITE_ROWS_EVENT - }; - -private: - virtual Log_event_type get_type_code() { return (Log_event_type)TYPE_CODE; } - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - // use old definition of do_apply_event() - virtual int do_apply_event(rpl_group_info *rgi) - { return Old_rows_log_event::do_apply_event(this, rgi); } - - // primitives for old version of do_apply_event() - virtual int do_before_row_operations(TABLE *table); - virtual int do_after_row_operations(TABLE *table, int error); - virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, - uchar const *row_start, uchar const **row_end); - virtual int do_exec_row(TABLE *table); - -#endif -}; - - -/** - @class Update_rows_log_event_old - - Old class for binlog events that modify existing rows to a table - (event type code PRE_GA_UPDATE_ROWS_EVENT). Such events are never - produced by this version of the server, but they may be read from a - relay log created by an old server. New servers create events of - class Update_rows_log_event (event type code UPDATE_ROWS_EVENT) - instead. -*/ -class Update_rows_log_event_old : public Old_rows_log_event -{ - /********** BEGIN CUT & PASTE FROM Update_rows_log_event **********/ -public: -#ifndef MYSQL_CLIENT - Update_rows_log_event_old(THD*, TABLE*, ulong table_id, - MY_BITMAP const *cols, - bool is_transactional); -#endif - -#ifdef HAVE_REPLICATION - Update_rows_log_event_old(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif - -#if !defined(MYSQL_CLIENT) - static bool binlog_row_logging_function(THD *thd, TABLE *table, - bool is_transactional, - MY_BITMAP *cols, - uint fields, - const uchar *before_record, - const uchar *after_record) - { - return thd->binlog_update_row(table, is_transactional, - before_record, after_record); - } -#endif - -protected: -#ifdef MYSQL_CLIENT - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - virtual int do_before_row_operations(const Slave_reporting_capability *const); - virtual int do_after_row_operations(const Slave_reporting_capability *const,int); - virtual int do_exec_row(rpl_group_info *); -#endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ - /********** END OF CUT & PASTE FROM Update_rows_log_event **********/ - - uchar *m_after_image, *m_memory; - -public: - enum - { - /* Support interface to THD::binlog_prepare_pending_rows_event */ - TYPE_CODE = PRE_GA_UPDATE_ROWS_EVENT - }; - -private: - virtual Log_event_type get_type_code() { return (Log_event_type)TYPE_CODE; } - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - // use old definition of do_apply_event() - virtual int do_apply_event(rpl_group_info *rgi) - { return Old_rows_log_event::do_apply_event(this, rgi); } - - // primitives for old version of do_apply_event() - virtual int do_before_row_operations(TABLE *table); - virtual int do_after_row_operations(TABLE *table, int error); - virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, - uchar const *row_start, uchar const **row_end); - virtual int do_exec_row(TABLE *table); -#endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ -}; - - -/** - @class Delete_rows_log_event_old - - Old class for binlog events that delete existing rows from a table - (event type code PRE_GA_DELETE_ROWS_EVENT). Such events are never - produced by this version of the server, but they may be read from a - relay log created by an old server. New servers create events of - class Delete_rows_log_event (event type code DELETE_ROWS_EVENT) - instead. -*/ -class Delete_rows_log_event_old : public Old_rows_log_event -{ - /********** BEGIN CUT & PASTE FROM Update_rows_log_event **********/ -public: -#ifndef MYSQL_CLIENT - Delete_rows_log_event_old(THD*, TABLE*, ulong, - MY_BITMAP const *cols, bool is_transactional); -#endif -#ifdef HAVE_REPLICATION - Delete_rows_log_event_old(const char *buf, uint event_len, - const Format_description_log_event *description_event); -#endif -#if !defined(MYSQL_CLIENT) - static bool binlog_row_logging_function(THD *thd, TABLE *table, - bool is_transactional, - MY_BITMAP *cols, - uint fields, - const uchar *before_record, - const uchar *after_record - __attribute__((unused))) - { - return thd->binlog_delete_row(table, is_transactional, before_record); - } -#endif - -protected: -#ifdef MYSQL_CLIENT - bool print(FILE *file, PRINT_EVENT_INFO *print_event_info); -#endif - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - virtual int do_before_row_operations(const Slave_reporting_capability *const); - virtual int do_after_row_operations(const Slave_reporting_capability *const,int); - virtual int do_exec_row(rpl_group_info *); -#endif - /********** END CUT & PASTE FROM Delete_rows_log_event **********/ - - uchar *m_after_image, *m_memory; - -public: - enum - { - /* Support interface to THD::binlog_prepare_pending_rows_event */ - TYPE_CODE = PRE_GA_DELETE_ROWS_EVENT - }; - -private: - virtual Log_event_type get_type_code() { return (Log_event_type)TYPE_CODE; } - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) - // use old definition of do_apply_event() - virtual int do_apply_event(rpl_group_info *rgi) - { return Old_rows_log_event::do_apply_event(this, rgi); } - - // primitives for old version of do_apply_event() - virtual int do_before_row_operations(TABLE *table); - virtual int do_after_row_operations(TABLE *table, int error); - virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, - uchar const *row_start, uchar const **row_end); - virtual int do_exec_row(TABLE *table); -#endif -}; - - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_slow.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_slow.h deleted file mode 100644 index c6b3407..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/log_slow.h +++ /dev/null @@ -1,54 +0,0 @@ -/* Copyright (C) 2009, 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 or later of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Defining what to log to slow log */ - -#ifndef LOG_SLOW_INCLUDED -#define LOG_SLOW_INCLUDED - -#define LOG_SLOW_VERBOSITY_INIT 0 -#define LOG_SLOW_VERBOSITY_INNODB (1U << 0) -#define LOG_SLOW_VERBOSITY_QUERY_PLAN (1U << 1) -#define LOG_SLOW_VERBOSITY_EXPLAIN (1U << 2) - -#define QPLAN_INIT QPLAN_QC_NO - -#define QPLAN_ADMIN (1U << 0) -#define QPLAN_FILESORT (1U << 1) -#define QPLAN_FILESORT_DISK (1U << 2) -#define QPLAN_FILESORT_PRIORITY_QUEUE (1U << 3) -#define QPLAN_FULL_JOIN (1U << 4) -#define QPLAN_FULL_SCAN (1U << 5) -#define QPLAN_NOT_USING_INDEX (1U << 6) -#define QPLAN_QC (1U << 7) -#define QPLAN_QC_NO (1U << 8) -#define QPLAN_TMP_TABLE (1U << 9) -#define QPLAN_TMP_DISK (1U << 10) - -/* ... */ -#define QPLAN_STATUS (1UL << 31) /* not in the slow_log_filter */ -#define QPLAN_MAX (1UL << 31) /* reserved as placeholder */ - -/* Bits for log_slow_disabled_statements */ -#define LOG_SLOW_DISABLE_ADMIN (1 << 0) -#define LOG_SLOW_DISABLE_CALL (1 << 1) -#define LOG_SLOW_DISABLE_SLAVE (1 << 2) -#define LOG_SLOW_DISABLE_SP (1 << 3) - -/* Bits for log_disabled_statements */ -#define LOG_DISABLE_SLAVE (1 << 0) -#define LOG_DISABLE_SP (1 << 1) - -#endif /* LOG_SLOW_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/maria.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/maria.h deleted file mode 100644 index 7fdf95f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/maria.h +++ /dev/null @@ -1,154 +0,0 @@ -/* Copyright (C) 2006-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. - Copyright (c) 2009, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* This file should be included when using maria functions */ - -#ifndef _maria_h -#define _maria_h -#include -#include -#include "my_compare.h" -#include "ft_global.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MARIA_UNIQUE_HASH_LENGTH 4 -extern my_bool maria_delay_key_write; -uint maria_max_key_length(void); -#define maria_max_key_segments() HA_MAX_KEY_SEG - -struct st_maria_bit_buff; -struct st_maria_page; -struct st_maria_s_param; -struct st_maria_share; -typedef struct st_maria_decode_tree MARIA_DECODE_TREE; -typedef struct st_maria_handler MARIA_HA; -typedef struct st_maria_key MARIA_KEY; -typedef ulonglong MARIA_RECORD_POS; - -typedef struct st_maria_keydef /* Key definition with open & info */ -{ - struct st_maria_share *share; /* Pointer to base (set in open) */ - mysql_rwlock_t root_lock; /* locking of tree */ - uint16 keysegs; /* Number of key-segment */ - uint16 flag; /* NOSAME, PACK_USED */ - - uint8 key_alg; /* BTREE, RTREE */ - uint8 key_nr; /* key number (auto) */ - uint16 block_length; /* Length of keyblock (auto) */ - uint16 underflow_block_length; /* When to execute underflow */ - uint16 keylength; /* Tot length of keyparts (auto) */ - uint16 minlength; /* min length of (packed) key (auto) */ - uint16 maxlength; /* max length of (packed) key (auto) */ - uint16 max_store_length; /* Size to store key + overhead */ - uint32 write_comp_flag; /* compare flag for write key (auto) */ - uint32 version; /* For concurrent read/write */ - uint32 ftkey_nr; /* full-text index number */ - - HA_KEYSEG *seg, *end; - struct st_mysql_ftparser *parser; /* Fulltext [pre]parser */ - int (*bin_search)(const MARIA_KEY *key, const struct st_maria_page *page, - uint32 comp_flag, uchar **ret_pos, uchar *buff, - my_bool *was_last_key); - uint (*get_key)(MARIA_KEY *key, uint page_flag, uint nod_flag, - uchar **page); - uchar *(*skip_key)(MARIA_KEY *key, uint page_flag, uint nod_flag, - uchar *page); - int (*pack_key)(const MARIA_KEY *key, uint nod_flag, - uchar *next_key, uchar *org_key, uchar *prev_key, - struct st_maria_s_param *s_temp); - void (*store_key)(struct st_maria_keydef *keyinfo, uchar *key_pos, - struct st_maria_s_param *s_temp); - my_bool (*ck_insert)(MARIA_HA *inf, MARIA_KEY *key); - my_bool (*ck_delete)(MARIA_HA *inf, MARIA_KEY *klen); - MARIA_KEY *(*make_key)(MARIA_HA *info, MARIA_KEY *int_key, uint keynr, - uchar *key, const uchar *record, - MARIA_RECORD_POS filepos, ulonglong trid); -} MARIA_KEYDEF; - - -typedef struct st_maria_unique_def /* Segment definition of unique */ -{ - uint16 keysegs; /* Number of key-segment */ - uint8 key; /* Mapped to which key */ - uint8 null_are_equal; - HA_KEYSEG *seg, *end; -} MARIA_UNIQUEDEF; - -/* - Note that null markers should always be first in a row ! - When creating a column, one should only specify: - type, length, null_bit and null_pos -*/ - -typedef struct st_maria_columndef /* column information */ -{ - enum en_fieldtype type; - uint32 offset; /* Offset to position in row */ - uint16 length; /* length of field */ - uint16 column_nr; - /* Intern variable (size of total storage area for the row) */ - uint16 fill_length; - uint16 null_pos; /* Position for null marker */ - uint16 empty_pos; /* Position for empty marker */ - uint8 null_bit; /* If column may be NULL */ - /* Intern. Set if column should be zero packed (part of empty_bits) */ - uint8 empty_bit; - -#ifndef NOT_PACKED_DATABASES - void(*unpack)(struct st_maria_columndef *rec, - struct st_maria_bit_buff *buff, - uchar *start, uchar *end); - enum en_fieldtype base_type; - uint space_length_bits, pack_type; - MARIA_DECODE_TREE *huff_tree; -#endif -} MARIA_COLUMNDEF; - - -typedef struct st_maria_create_info -{ - const char *index_file_name, *data_file_name; /* If using symlinks */ - ha_rows max_rows; - ha_rows reloc_rows; - ulonglong auto_increment; - ulonglong data_file_length; - ulonglong key_file_length; - ulong s3_block_size; - /* Size of null bitmap at start of row */ - uint null_bytes; - uint old_options; - uint compression_algorithm; - enum data_file_type org_data_file_type; - uint16 language; - my_bool with_auto_increment, transactional, encrypted; -} MARIA_CREATE_INFO; - -extern int maria_create(const char *name, enum data_file_type record_type, - uint keys, MARIA_KEYDEF *keydef, - uint columns, MARIA_COLUMNDEF *columndef, - uint uniques, MARIA_UNIQUEDEF *uniquedef, - MARIA_CREATE_INFO *create_info, uint flags); - -#ifdef __cplusplus -} -#endif -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mariadb.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mariadb.h deleted file mode 100644 index 00cf2ed..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mariadb.h +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright (c) 2010, 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -/* - Include file that should always be included first in all file in the sql - directory. Used to ensure that some files, like my_global.h and my_config.h - are always included first. - It can also be used to speed up compilation by using precompiled headers. - - This file should include a minum set of header files used by all files - and header files that are very seldom changed. - It can also include some defines that all files should be aware of. -*/ - -#ifndef MARIADB_INCLUDED -#define MARIADB_INCLUDED -#include -#endif /* MARIADB_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mdl.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mdl.h deleted file mode 100644 index f6b7154..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mdl.h +++ /dev/null @@ -1,1132 +0,0 @@ -#ifndef MDL_H -#define MDL_H -/* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "sql_plist.h" -#include "ilist.h" -#include -#include -#include -#include - -class THD; - -class MDL_context; -class MDL_lock; -class MDL_ticket; -bool ok_for_lower_case_names(const char *name); - -typedef unsigned short mdl_bitmap_t; -#define MDL_BIT(A) static_cast(1U << A) - - -/** - @def ENTER_COND(C, M, S, O) - Start a wait on a condition. - @param C the condition to wait on - @param M the associated mutex - @param S the new stage to enter - @param O the previous stage - @sa EXIT_COND(). -*/ -#define ENTER_COND(C, M, S, O) enter_cond(C, M, S, O, __func__, __FILE__, __LINE__) - -/** - @def EXIT_COND(S) - End a wait on a condition - @param S the new stage to enter -*/ -#define EXIT_COND(S) exit_cond(S, __func__, __FILE__, __LINE__) - -/** - An interface to separate the MDL module from the THD, and the rest of the - server code. - */ - -class MDL_context_owner -{ -public: - virtual ~MDL_context_owner() {} - - /** - Enter a condition wait. - For @c enter_cond() / @c exit_cond() to work the mutex must be held before - @c enter_cond(); this mutex is then released by @c exit_cond(). - Usage must be: lock mutex; enter_cond(); your code; exit_cond(). - @param cond the condition to wait on - @param mutex the associated mutex - @param [in] stage the stage to enter, or NULL - @param [out] old_stage the previous stage, or NULL - @param src_function function name of the caller - @param src_file file name of the caller - @param src_line line number of the caller - @sa ENTER_COND(), THD::enter_cond() - @sa EXIT_COND(), THD::exit_cond() - */ - virtual void enter_cond(mysql_cond_t *cond, mysql_mutex_t *mutex, - const PSI_stage_info *stage, PSI_stage_info *old_stage, - const char *src_function, const char *src_file, - int src_line) = 0; - - /** - @def EXIT_COND(S) - End a wait on a condition - @param [in] stage the new stage to enter - @param src_function function name of the caller - @param src_file file name of the caller - @param src_line line number of the caller - @sa ENTER_COND(), THD::enter_cond() - @sa EXIT_COND(), THD::exit_cond() - */ - virtual void exit_cond(const PSI_stage_info *stage, - const char *src_function, const char *src_file, - int src_line) = 0; - /** - Has the owner thread been killed? - */ - virtual int is_killed() = 0; - - /** - This one is only used for DEBUG_SYNC. - (Do not use it to peek/poke into other parts of THD.) - */ - virtual THD* get_thd() = 0; - - /** - @see THD::notify_shared_lock() - */ - virtual bool notify_shared_lock(MDL_context_owner *in_use, - bool needs_thr_lock_abort) = 0; -}; - -/** - Type of metadata lock request. - - @sa Comments for MDL_object_lock::can_grant_lock() and - MDL_scoped_lock::can_grant_lock() for details. - - Scoped locks are database (or schema) locks. - The object locks are for tables, triggers etc. -*/ - -enum enum_mdl_type { - /* This means that the MDL_request is not initialized */ - MDL_NOT_INITIALIZED= -1, - /* - An intention exclusive metadata lock (IX). Used only for scoped locks. - Owner of this type of lock can acquire upgradable exclusive locks on - individual objects. - Compatible with other IX locks, but is incompatible with scoped S and - X locks. - IX lock is taken in SCHEMA namespace when we intend to modify - object metadata. Object may refer table, stored procedure, trigger, - view/etc. - */ - MDL_INTENTION_EXCLUSIVE= 0, - /* - A shared metadata lock (S). - To be used in cases when we are interested in object metadata only - and there is no intention to access object data (e.g. for stored - routines or during preparing prepared statements). - We also mis-use this type of lock for open HANDLERs, since lock - acquired by this statement has to be compatible with lock acquired - by LOCK TABLES ... WRITE statement, i.e. SNRW (We can't get by by - acquiring S lock at HANDLER ... OPEN time and upgrading it to SR - lock for HANDLER ... READ as it doesn't solve problem with need - to abort DML statements which wait on table level lock while having - open HANDLER in the same connection). - To avoid deadlock which may occur when SNRW lock is being upgraded to - X lock for table on which there is an active S lock which is owned by - thread which waits in its turn for table-level lock owned by thread - performing upgrade we have to use thr_abort_locks_for_thread() - facility in such situation. - This problem does not arise for locks on stored routines as we don't - use SNRW locks for them. It also does not arise when S locks are used - during PREPARE calls as table-level locks are not acquired in this - case. - This lock is taken for global read lock, when caching a stored - procedure in memory for the duration of the transaction and for - tables used by prepared statements. - */ - MDL_SHARED, - /* - A high priority shared metadata lock. - Used for cases when there is no intention to access object data (i.e. - data in the table). - "High priority" means that, unlike other shared locks, it is granted - ignoring pending requests for exclusive locks. Intended for use in - cases when we only need to access metadata and not data, e.g. when - filling an INFORMATION_SCHEMA table. - Since SH lock is compatible with SNRW lock, the connection that - holds SH lock lock should not try to acquire any kind of table-level - or row-level lock, as this can lead to a deadlock. Moreover, after - acquiring SH lock, the connection should not wait for any other - resource, as it might cause starvation for X locks and a potential - deadlock during upgrade of SNW or SNRW to X lock (e.g. if the - upgrading connection holds the resource that is being waited for). - */ - MDL_SHARED_HIGH_PRIO, - /* - A shared metadata lock (SR) for cases when there is an intention to read - data from table. - A connection holding this kind of lock can read table metadata and read - table data (after acquiring appropriate table and row-level locks). - This means that one can only acquire TL_READ, TL_READ_NO_INSERT, and - similar table-level locks on table if one holds SR MDL lock on it. - To be used for tables in SELECTs, subqueries, and LOCK TABLE ... READ - statements. - */ - MDL_SHARED_READ, - /* - A shared metadata lock (SW) for cases when there is an intention to modify - (and not just read) data in the table. - A connection holding SW lock can read table metadata and modify or read - table data (after acquiring appropriate table and row-level locks). - To be used for tables to be modified by INSERT, UPDATE, DELETE - statements, but not LOCK TABLE ... WRITE or DDL). Also taken by - SELECT ... FOR UPDATE. - */ - MDL_SHARED_WRITE, - /* - An upgradable shared metadata lock for cases when there is an - intention to modify (and not just read) data in the table. - Can be upgraded to MDL_SHARED_NO_WRITE and MDL_EXCLUSIVE. - A connection holding SU lock can read table metadata and modify or read - table data (after acquiring appropriate table and row-level locks). - To be used for the first phase of ALTER TABLE. - */ - MDL_SHARED_UPGRADABLE, - /* - A shared metadata lock for cases when we need to read data from table - and block all concurrent modifications to it (for both data and metadata). - Used by LOCK TABLES READ statement. - */ - MDL_SHARED_READ_ONLY, - /* - An upgradable shared metadata lock which blocks all attempts to update - table data, allowing reads. - A connection holding this kind of lock can read table metadata and read - table data. - Can be upgraded to X metadata lock. - Note, that since this type of lock is not compatible with SNRW or SW - lock types, acquiring appropriate engine-level locks for reading - (TL_READ* for MyISAM, shared row locks in InnoDB) should be - contention-free. - To be used for the first phase of ALTER TABLE, when copying data between - tables, to allow concurrent SELECTs from the table, but not UPDATEs. - */ - MDL_SHARED_NO_WRITE, - /* - An upgradable shared metadata lock which allows other connections - to access table metadata, but not data. - It blocks all attempts to read or update table data, while allowing - INFORMATION_SCHEMA and SHOW queries. - A connection holding this kind of lock can read table metadata modify and - read table data. - Can be upgraded to X metadata lock. - To be used for LOCK TABLES WRITE statement. - Not compatible with any other lock type except S and SH. - */ - MDL_SHARED_NO_READ_WRITE, - /* - An exclusive metadata lock (X). - A connection holding this lock can modify both table's metadata and data. - No other type of metadata lock can be granted while this lock is held. - To be used for CREATE/DROP/RENAME TABLE statements and for execution of - certain phases of other DDL statements. - */ - MDL_EXCLUSIVE, - /* This should be the last !!! */ - MDL_TYPE_END -}; - - -/** Backup locks */ - -/** - Block concurrent backup -*/ -#define MDL_BACKUP_START enum_mdl_type(0) -/** - Block new write requests to non transactional tables -*/ -#define MDL_BACKUP_FLUSH enum_mdl_type(1) -/** - In addition to previous locks, blocks running requests to non trans tables - Used to wait until all DML usage of on trans tables are finished -*/ -#define MDL_BACKUP_WAIT_FLUSH enum_mdl_type(2) -/** - In addition to previous locks, blocks new DDL's from starting -*/ -#define MDL_BACKUP_WAIT_DDL enum_mdl_type(3) -/** - In addition to previous locks, blocks commits -*/ -#define MDL_BACKUP_WAIT_COMMIT enum_mdl_type(4) - -/** - Blocks (or is blocked by) statements that intend to modify data. Acquired - before commit lock by FLUSH TABLES WITH READ LOCK. -*/ -#define MDL_BACKUP_FTWRL1 enum_mdl_type(5) - -/** - Blocks (or is blocked by) commits. Acquired after global read lock by - FLUSH TABLES WITH READ LOCK. -*/ -#define MDL_BACKUP_FTWRL2 enum_mdl_type(6) - -#define MDL_BACKUP_DML enum_mdl_type(7) -#define MDL_BACKUP_TRANS_DML enum_mdl_type(8) -#define MDL_BACKUP_SYS_DML enum_mdl_type(9) - -/** - Must be acquired by DDL statements that intend to modify data. - Currently it's also used for LOCK TABLES. -*/ -#define MDL_BACKUP_DDL enum_mdl_type(10) - -/** - Blocks new DDL's. Used by backup code to enable DDL logging -*/ -#define MDL_BACKUP_BLOCK_DDL enum_mdl_type(11) - -/* - Statement is modifying data, but will not block MDL_BACKUP_DDL or earlier - BACKUP stages. - ALTER TABLE is started with MDL_BACKUP_DDL, but changed to - MDL_BACKUP_ALTER_COPY while alter table is copying or modifing data. -*/ - -#define MDL_BACKUP_ALTER_COPY enum_mdl_type(12) - -/** - Must be acquired during commit. -*/ -#define MDL_BACKUP_COMMIT enum_mdl_type(13) -#define MDL_BACKUP_END enum_mdl_type(14) - - -/** Duration of metadata lock. */ - -enum enum_mdl_duration { - /** - Locks with statement duration are automatically released at the end - of statement or transaction. - */ - MDL_STATEMENT= 0, - /** - Locks with transaction duration are automatically released at the end - of transaction. - */ - MDL_TRANSACTION, - /** - Locks with explicit duration survive the end of statement and transaction. - They have to be released explicitly by calling MDL_context::release_lock(). - */ - MDL_EXPLICIT, - /* This should be the last ! */ - MDL_DURATION_END }; - - -/** Maximal length of key for metadata locking subsystem. */ -#define MAX_MDLKEY_LENGTH (1 + NAME_LEN + 1 + NAME_LEN + 1) - - -/** - Metadata lock object key. - - A lock is requested or granted based on a fully qualified name and type. - E.g. They key for a table consists of <0 (=table)>++. - Elsewhere in the comments this triple will be referred to simply as "key" - or "name". -*/ - -struct MDL_key -{ -public: -#ifdef HAVE_PSI_INTERFACE - static void init_psi_keys(); -#endif - - /** - Object namespaces. - Sic: when adding a new member to this enum make sure to - update m_namespace_to_wait_state_name array in mdl.cc and - metadata_lock_info_lock_name in metadata_lock_info.cc! - - Different types of objects exist in different namespaces - - SCHEMA is for databases (to protect against DROP DATABASE) - - TABLE is for tables and views. - - BACKUP is for locking DML, DDL and COMMIT's during BACKUP STAGES - - FUNCTION is for stored functions. - - PROCEDURE is for stored procedures. - - TRIGGER is for triggers. - - EVENT is for event scheduler events - Note that although there isn't metadata locking on triggers, - it's necessary to have a separate namespace for them since - MDL_key is also used outside of the MDL subsystem. - */ - enum enum_mdl_namespace { BACKUP=0, - SCHEMA, - TABLE, - FUNCTION, - PROCEDURE, - PACKAGE_BODY, - TRIGGER, - EVENT, - USER_LOCK, /* user level locks. */ - /* This should be the last ! */ - NAMESPACE_END }; - - const uchar *ptr() const { return (uchar*) m_ptr; } - uint length() const { return m_length; } - - const char *db_name() const { return m_ptr + 1; } - uint db_name_length() const { return m_db_name_length; } - - const char *name() const { return m_ptr + m_db_name_length + 2; } - uint name_length() const { return m_length - m_db_name_length - 3; } - - enum_mdl_namespace mdl_namespace() const - { return (enum_mdl_namespace)(m_ptr[0]); } - - /** - Construct a metadata lock key from a triplet (mdl_namespace, - database and name). - - @remark The key for a table is ++
- - @param mdl_namespace Id of namespace of object to be locked - @param db Name of database to which the object belongs - @param name Name of of the object - @param key Where to store the the MDL key. - */ - void mdl_key_init(enum_mdl_namespace mdl_namespace_arg, - const char *db, const char *name_arg) - { - m_ptr[0]= (char) mdl_namespace_arg; - /* - It is responsibility of caller to ensure that db and object names - are not longer than NAME_LEN. Still we play safe and try to avoid - buffer overruns. - */ - DBUG_ASSERT(strlen(db) <= NAME_LEN); - DBUG_ASSERT(strlen(name_arg) <= NAME_LEN); - m_db_name_length= static_cast(strmake(m_ptr + 1, db, NAME_LEN) - - m_ptr - 1); - m_length= static_cast(strmake(m_ptr + m_db_name_length + 2, - name_arg, - NAME_LEN) - m_ptr + 1); - m_hash_value= my_hash_sort(&my_charset_bin, (uchar*) m_ptr + 1, - m_length - 1); - DBUG_SLOW_ASSERT(mdl_namespace_arg == USER_LOCK || ok_for_lower_case_names(db)); - } - void mdl_key_init(const MDL_key *rhs) - { - memcpy(m_ptr, rhs->m_ptr, rhs->m_length); - m_length= rhs->m_length; - m_db_name_length= rhs->m_db_name_length; - m_hash_value= rhs->m_hash_value; - } - bool is_equal(const MDL_key *rhs) const - { - return (m_length == rhs->m_length && - memcmp(m_ptr, rhs->m_ptr, m_length) == 0); - } - /** - Compare two MDL keys lexicographically. - */ - int cmp(const MDL_key *rhs) const - { - /* - The key buffer is always '\0'-terminated. Since key - character set is utf-8, we can safely assume that no - character starts with a zero byte. - */ - return memcmp(m_ptr, rhs->m_ptr, MY_MIN(m_length, rhs->m_length)); - } - - MDL_key(const MDL_key *rhs) - { - mdl_key_init(rhs); - } - MDL_key(enum_mdl_namespace namespace_arg, - const char *db_arg, const char *name_arg) - { - mdl_key_init(namespace_arg, db_arg, name_arg); - } - MDL_key() {} /* To use when part of MDL_request. */ - - /** - Get thread state name to be used in case when we have to - wait on resource identified by key. - */ - const PSI_stage_info * get_wait_state_name() const - { - return & m_namespace_to_wait_state_name[(int)mdl_namespace()]; - } - my_hash_value_type hash_value() const - { - return m_hash_value + mdl_namespace(); - } - my_hash_value_type tc_hash_value() const - { - return m_hash_value; - } - -private: - uint16 m_length; - uint16 m_db_name_length; - my_hash_value_type m_hash_value; - char m_ptr[MAX_MDLKEY_LENGTH]; - static PSI_stage_info m_namespace_to_wait_state_name[NAMESPACE_END]; -private: - MDL_key(const MDL_key &); /* not implemented */ - MDL_key &operator=(const MDL_key &); /* not implemented */ - friend my_hash_value_type mdl_hash_function(CHARSET_INFO *, - const uchar *, size_t); -}; - - -/** - A pending metadata lock request. - - A lock request and a granted metadata lock are represented by - different classes because they have different allocation - sites and hence different lifetimes. The allocation of lock requests is - controlled from outside of the MDL subsystem, while allocation of granted - locks (tickets) is controlled within the MDL subsystem. - - MDL_request is a C structure, you don't need to call a constructor - or destructor for it. -*/ - -class MDL_request -{ -public: - /** Type of metadata lock. */ - enum enum_mdl_type type; - /** Duration for requested lock. */ - enum enum_mdl_duration duration; - - /** - Pointers for participating in the list of lock requests for this context. - */ - MDL_request *next_in_list; - MDL_request **prev_in_list; - /** - Pointer to the lock ticket object for this lock request. - Valid only if this lock request is satisfied. - */ - MDL_ticket *ticket; - - /** A lock is requested based on a fully qualified name and type. */ - MDL_key key; - - const char *m_src_file; - uint m_src_line; - -public: - - static void *operator new(size_t size, MEM_ROOT *mem_root) throw () - { return alloc_root(mem_root, size); } - static void operator delete(void *, MEM_ROOT *) {} - - void init_with_source(MDL_key::enum_mdl_namespace namespace_arg, - const char *db_arg, const char *name_arg, - enum_mdl_type mdl_type_arg, - enum_mdl_duration mdl_duration_arg, - const char *src_file, uint src_line); - void init_by_key_with_source(const MDL_key *key_arg, enum_mdl_type mdl_type_arg, - enum_mdl_duration mdl_duration_arg, - const char *src_file, uint src_line); - /** Set type of lock request. Can be only applied to pending locks. */ - inline void set_type(enum_mdl_type type_arg) - { - DBUG_ASSERT(ticket == NULL); - type= type_arg; - } - void move_from(MDL_request &from) - { - type= from.type; - duration= from.duration; - ticket= from.ticket; - next_in_list= from.next_in_list; - prev_in_list= from.prev_in_list; - key.mdl_key_init(&from.key); - from.ticket= NULL; // that's what "move" means - } - - /** - Is this a request for a lock which allow data to be updated? - - @note This method returns true for MDL_SHARED_UPGRADABLE type of - lock. Even though this type of lock doesn't allow updates - it will always be upgraded to one that does. - */ - bool is_write_lock_request() const - { - return (type >= MDL_SHARED_WRITE && - type != MDL_SHARED_READ_ONLY); - } - - /* - This is to work around the ugliness of TABLE_LIST - compiler-generated assignment operator. It is currently used - in several places to quickly copy "most" of the members of the - table list. These places currently never assume that the mdl - request is carried over to the new TABLE_LIST, or shared - between lists. - - This method does not initialize the instance being assigned! - Use of init() for initialization after this assignment operator - is mandatory. Can only be used before the request has been - granted. - */ - MDL_request& operator=(const MDL_request &) - { - type= MDL_NOT_INITIALIZED; - ticket= NULL; - /* Do nothing, in particular, don't try to copy the key. */ - return *this; - } - /* Another piece of ugliness for TABLE_LIST constructor */ - MDL_request(): type(MDL_NOT_INITIALIZED), ticket(NULL) {} - - MDL_request(const MDL_request *rhs) - :type(rhs->type), - duration(rhs->duration), - ticket(NULL), - key(&rhs->key) - {} -}; - - -typedef void (*mdl_cached_object_release_hook)(void *); - -#define MDL_REQUEST_INIT(R, P1, P2, P3, P4, P5) \ - (*R).init_with_source(P1, P2, P3, P4, P5, __FILE__, __LINE__) - -#define MDL_REQUEST_INIT_BY_KEY(R, P1, P2, P3) \ - (*R).init_by_key_with_source(P1, P2, P3, __FILE__, __LINE__) - - -/** - An abstract class for inspection of a connected - subgraph of the wait-for graph. -*/ - -class MDL_wait_for_graph_visitor -{ -public: - virtual bool enter_node(MDL_context *node) = 0; - virtual void leave_node(MDL_context *node) = 0; - - virtual bool inspect_edge(MDL_context *dest) = 0; - virtual ~MDL_wait_for_graph_visitor(); - MDL_wait_for_graph_visitor() {} -}; - -/** - Abstract class representing an edge in the waiters graph - to be traversed by deadlock detection algorithm. -*/ - -class MDL_wait_for_subgraph -{ -public: - virtual ~MDL_wait_for_subgraph(); - - /** - Accept a wait-for graph visitor to inspect the node - this edge is leading to. - */ - virtual bool accept_visitor(MDL_wait_for_graph_visitor *gvisitor) = 0; - - enum enum_deadlock_weight - { - DEADLOCK_WEIGHT_FTWRL1= 0, - DEADLOCK_WEIGHT_DML= 1, - DEADLOCK_WEIGHT_DDL= 100 - }; - /* A helper used to determine which lock request should be aborted. */ - virtual uint get_deadlock_weight() const = 0; -}; - - -/** - A granted metadata lock. - - @warning MDL_ticket members are private to the MDL subsystem. - - @note Multiple shared locks on a same object are represented by a - single ticket. The same does not apply for other lock types. - - @note There are two groups of MDL_ticket members: - - "Externally accessible". These members can be accessed from - threads/contexts different than ticket owner in cases when - ticket participates in some list of granted or waiting tickets - for a lock. Therefore one should change these members before - including then to waiting/granted lists or while holding lock - protecting those lists. - - "Context private". Such members are private to thread/context - owning this ticket. I.e. they should not be accessed from other - threads/contexts. -*/ - -class MDL_ticket : public MDL_wait_for_subgraph, public ilist_node<> -{ -public: - /** - Pointers for participating in the list of lock requests for this context. - Context private. - */ - MDL_ticket *next_in_context; - MDL_ticket **prev_in_context; -public: -#ifdef WITH_WSREP - void wsrep_report(bool debug) const; -#endif /* WITH_WSREP */ - bool has_pending_conflicting_lock() const; - - MDL_context *get_ctx() const { return m_ctx; } - bool is_upgradable_or_exclusive() const - { - return m_type == MDL_SHARED_UPGRADABLE || - m_type == MDL_SHARED_NO_WRITE || - m_type == MDL_SHARED_NO_READ_WRITE || - m_type == MDL_EXCLUSIVE; - } - enum_mdl_type get_type() const { return m_type; } - const LEX_STRING *get_type_name() const; - const LEX_STRING *get_type_name(enum_mdl_type type) const; - MDL_lock *get_lock() const { return m_lock; } - MDL_key *get_key() const; - void downgrade_lock(enum_mdl_type type); - - bool has_stronger_or_equal_type(enum_mdl_type type) const; - - bool is_incompatible_when_granted(enum_mdl_type type) const; - bool is_incompatible_when_waiting(enum_mdl_type type) const; - - /** Implement MDL_wait_for_subgraph interface. */ - virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor); - virtual uint get_deadlock_weight() const; - /** - Status of lock request represented by the ticket as reflected in P_S. - */ - enum enum_psi_status { PENDING = 0, GRANTED, - PRE_ACQUIRE_NOTIFY, POST_RELEASE_NOTIFY }; -private: - friend class MDL_context; - - MDL_ticket(MDL_context *ctx_arg, enum_mdl_type type_arg -#ifndef DBUG_OFF - , enum_mdl_duration duration_arg -#endif - ) - : m_type(type_arg), -#ifndef DBUG_OFF - m_duration(duration_arg), -#endif - m_ctx(ctx_arg), - m_lock(NULL), - m_psi(NULL) - {} - - virtual ~MDL_ticket() - { - DBUG_ASSERT(m_psi == NULL); - } - - static MDL_ticket *create(MDL_context *ctx_arg, enum_mdl_type type_arg -#ifndef DBUG_OFF - , enum_mdl_duration duration_arg -#endif - ); - static void destroy(MDL_ticket *ticket); -private: - /** Type of metadata lock. Externally accessible. */ - enum enum_mdl_type m_type; -#ifndef DBUG_OFF - /** - Duration of lock represented by this ticket. - Context private. Debug-only. - */ - enum_mdl_duration m_duration; -#endif - /** - Context of the owner of the metadata lock ticket. Externally accessible. - */ - MDL_context *m_ctx; - - /** - Pointer to the lock object for this lock ticket. Externally accessible. - */ - MDL_lock *m_lock; - - PSI_metadata_lock *m_psi; - -private: - MDL_ticket(const MDL_ticket &); /* not implemented */ - MDL_ticket &operator=(const MDL_ticket &); /* not implemented */ -}; - - -/** - Savepoint for MDL context. - - Doesn't include metadata locks with explicit duration as - they are not released during rollback to savepoint. -*/ - -class MDL_savepoint -{ -public: - MDL_savepoint() {}; - -private: - MDL_savepoint(MDL_ticket *stmt_ticket, MDL_ticket *trans_ticket) - : m_stmt_ticket(stmt_ticket), m_trans_ticket(trans_ticket) - {} - - friend class MDL_context; - -private: - /** - Pointer to last lock with statement duration which was taken - before creation of savepoint. - */ - MDL_ticket *m_stmt_ticket; - /** - Pointer to last lock with transaction duration which was taken - before creation of savepoint. - */ - MDL_ticket *m_trans_ticket; -}; - - -/** - A reliable way to wait on an MDL lock. -*/ - -class MDL_wait -{ -public: - MDL_wait(); - ~MDL_wait(); - - enum enum_wait_status { EMPTY = 0, GRANTED, VICTIM, TIMEOUT, KILLED }; - - bool set_status(enum_wait_status result_arg); - enum_wait_status get_status(); - void reset_status(); - enum_wait_status timed_wait(MDL_context_owner *owner, - struct timespec *abs_timeout, - bool signal_timeout, - const PSI_stage_info *wait_state_name); -private: - /** - Condvar which is used for waiting until this context's pending - request can be satisfied or this thread has to perform actions - to resolve a potential deadlock (we subscribe to such - notification by adding a ticket corresponding to the request - to an appropriate queue of waiters). - */ - mysql_mutex_t m_LOCK_wait_status; - mysql_cond_t m_COND_wait_status; - enum_wait_status m_wait_status; -}; - - -typedef I_P_List, - I_P_List_counter> - MDL_request_list; - -/** - Context of the owner of metadata locks. I.e. each server - connection has such a context. -*/ - -class MDL_context -{ -public: - typedef I_P_List > - Ticket_list; - - typedef Ticket_list::Iterator Ticket_iterator; - - MDL_context(); - void destroy(); - - bool try_acquire_lock(MDL_request *mdl_request); - bool acquire_lock(MDL_request *mdl_request, double lock_wait_timeout); - bool acquire_locks(MDL_request_list *requests, double lock_wait_timeout); - bool upgrade_shared_lock(MDL_ticket *mdl_ticket, - enum_mdl_type new_type, - double lock_wait_timeout); - - bool clone_ticket(MDL_request *mdl_request); - - void release_all_locks_for_name(MDL_ticket *ticket); - void release_lock(MDL_ticket *ticket); - - bool is_lock_owner(MDL_key::enum_mdl_namespace mdl_namespace, - const char *db, const char *name, - enum_mdl_type mdl_type); - unsigned long get_lock_owner(MDL_key *mdl_key); - - bool has_lock(const MDL_savepoint &mdl_savepoint, MDL_ticket *mdl_ticket); - - inline bool has_locks() const - { - return !(m_tickets[MDL_STATEMENT].is_empty() && - m_tickets[MDL_TRANSACTION].is_empty() && - m_tickets[MDL_EXPLICIT].is_empty()); - } - inline bool has_transactional_locks() const - { - return !m_tickets[MDL_TRANSACTION].is_empty(); - } - - MDL_savepoint mdl_savepoint() - { - return MDL_savepoint(m_tickets[MDL_STATEMENT].front(), - m_tickets[MDL_TRANSACTION].front()); - } - - void set_explicit_duration_for_all_locks(); - void set_transaction_duration_for_all_locks(); - void set_lock_duration(MDL_ticket *mdl_ticket, enum_mdl_duration duration); - - void release_statement_locks(); - void release_transactional_locks(); - void release_explicit_locks(); - void rollback_to_savepoint(const MDL_savepoint &mdl_savepoint); - - MDL_context_owner *get_owner() { return m_owner; } - - /** @pre Only valid if we started waiting for lock. */ - inline uint get_deadlock_weight() const - { return m_waiting_for->get_deadlock_weight(); } - /** - Post signal to the context (and wake it up if necessary). - - @retval FALSE - Success, signal was posted. - @retval TRUE - Failure, signal was not posted since context - already has received some signal or closed - signal slot. - */ - void init(MDL_context_owner *arg) { m_owner= arg; } - - void set_needs_thr_lock_abort(bool needs_thr_lock_abort) - { - /* - @note In theory, this member should be modified under protection - of some lock since it can be accessed from different threads. - In practice, this is not necessary as code which reads this - value and so might miss the fact that value was changed will - always re-try reading it after small timeout and therefore - will see the new value eventually. - */ - m_needs_thr_lock_abort= needs_thr_lock_abort; - } - bool get_needs_thr_lock_abort() const - { - return m_needs_thr_lock_abort; - } -public: - /** - If our request for a lock is scheduled, or aborted by the deadlock - detector, the result is recorded in this class. - */ - MDL_wait m_wait; -private: - /** - Lists of all MDL tickets acquired by this connection. - - Lists of MDL tickets: - --------------------- - The entire set of locks acquired by a connection can be separated - in three subsets according to their duration: locks released at - the end of statement, at the end of transaction and locks are - released explicitly. - - Statement and transactional locks are locks with automatic scope. - They are accumulated in the course of a transaction, and released - either at the end of uppermost statement (for statement locks) or - on COMMIT, ROLLBACK or ROLLBACK TO SAVEPOINT (for transactional - locks). They must not be (and never are) released manually, - i.e. with release_lock() call. - - Tickets with explicit duration are taken for locks that span - multiple transactions or savepoints. - These are: HANDLER SQL locks (HANDLER SQL is - transaction-agnostic), LOCK TABLES locks (you can COMMIT/etc - under LOCK TABLES, and the locked tables stay locked), user level - locks (GET_LOCK()/RELEASE_LOCK() functions) and - locks implementing "global read lock". - - Statement/transactional locks are always prepended to the - beginning of the appropriate list. In other words, they are - stored in reverse temporal order. Thus, when we rollback to - a savepoint, we start popping and releasing tickets from the - front until we reach the last ticket acquired after the savepoint. - - Locks with explicit duration are not stored in any - particular order, and among each other can be split into - four sets: - - [LOCK TABLES locks] [USER locks] [HANDLER locks] [GLOBAL READ LOCK locks] - - The following is known about these sets: - - * GLOBAL READ LOCK locks are always stored last. - This is because one can't say SET GLOBAL read_only=1 or - FLUSH TABLES WITH READ LOCK if one has locked tables. One can, - however, LOCK TABLES after having entered the read only mode. - Note, that subsequent LOCK TABLES statement will unlock the previous - set of tables, but not the GRL! - There are no HANDLER locks after GRL locks because - SET GLOBAL read_only performs a FLUSH TABLES WITH - READ LOCK internally, and FLUSH TABLES, in turn, implicitly - closes all open HANDLERs. - However, one can open a few HANDLERs after entering the - read only mode. - * LOCK TABLES locks include intention exclusive locks on - involved schemas and global intention exclusive lock. - */ - Ticket_list m_tickets[MDL_DURATION_END]; - MDL_context_owner *m_owner; - /** - TRUE - if for this context we will break protocol and try to - acquire table-level locks while having only S lock on - some table. - To avoid deadlocks which might occur during concurrent - upgrade of SNRW lock on such object to X lock we have to - abort waits for table-level locks for such connections. - FALSE - Otherwise. - */ - bool m_needs_thr_lock_abort; - - /** - Read-write lock protecting m_waiting_for member. - - @note The fact that this read-write lock prefers readers is - important as deadlock detector won't work correctly - otherwise. @sa Comment for MDL_lock::m_rwlock. - */ - mysql_prlock_t m_LOCK_waiting_for; - /** - Tell the deadlock detector what metadata lock or table - definition cache entry this session is waiting for. - In principle, this is redundant, as information can be found - by inspecting waiting queues, but we'd very much like it to be - readily available to the wait-for graph iterator. - */ - MDL_wait_for_subgraph *m_waiting_for; - LF_PINS *m_pins; -private: - MDL_ticket *find_ticket(MDL_request *mdl_req, - enum_mdl_duration *duration); - void release_locks_stored_before(enum_mdl_duration duration, MDL_ticket *sentinel); - void release_lock(enum_mdl_duration duration, MDL_ticket *ticket); - bool try_acquire_lock_impl(MDL_request *mdl_request, - MDL_ticket **out_ticket); - bool fix_pins(); - -public: - THD *get_thd() const { return m_owner->get_thd(); } - bool has_explicit_locks(); - void find_deadlock(); - - ulong get_thread_id() const { return thd_get_thread_id(get_thd()); } - - bool visit_subgraph(MDL_wait_for_graph_visitor *dvisitor); - - /** Inform the deadlock detector there is an edge in the wait-for graph. */ - void will_wait_for(MDL_wait_for_subgraph *waiting_for_arg) - { - mysql_prlock_wrlock(&m_LOCK_waiting_for); - m_waiting_for= waiting_for_arg; - mysql_prlock_unlock(&m_LOCK_waiting_for); - } - - /** Remove the wait-for edge from the graph after we're done waiting. */ - void done_waiting_for() - { - mysql_prlock_wrlock(&m_LOCK_waiting_for); - m_waiting_for= NULL; - mysql_prlock_unlock(&m_LOCK_waiting_for); - } - void lock_deadlock_victim() - { - mysql_prlock_rdlock(&m_LOCK_waiting_for); - } - void unlock_deadlock_victim() - { - mysql_prlock_unlock(&m_LOCK_waiting_for); - } -private: - MDL_context(const MDL_context &rhs); /* not implemented */ - MDL_context &operator=(MDL_context &rhs); /* not implemented */ - - /* metadata_lock_info plugin */ - friend int i_s_metadata_lock_info_fill_row(MDL_ticket*, void*); -}; - - -void mdl_init(); -void mdl_destroy(); - -extern "C" unsigned long thd_get_thread_id(const MYSQL_THD thd); - -/** - Check if a connection in question is no longer connected. - - @details - Replication apply thread is always connected. Otherwise, - does a poll on the associated socket to check if the client - is gone. -*/ -extern "C" int thd_is_connected(MYSQL_THD thd); - - -/* - Metadata locking subsystem tries not to grant more than - max_write_lock_count high-prio, strong locks successively, - to avoid starving out weak, low-prio locks. -*/ -extern "C" ulong max_write_lock_count; - -typedef int (*mdl_iterator_callback)(MDL_ticket *ticket, void *arg, - bool granted); -extern MYSQL_PLUGIN_IMPORT -int mdl_iterate(mdl_iterator_callback callback, void *arg); -#ifndef DBUG_OFF -void mdl_dbug_print_locks(); -#else - static inline void mdl_dbug_print_locks() {} -#endif /* DBUG_OFF */ -#endif /* MDL_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mem_root_array.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mem_root_array.h deleted file mode 100644 index 3d03a5a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mem_root_array.h +++ /dev/null @@ -1,245 +0,0 @@ -/* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef MEM_ROOT_ARRAY_INCLUDED -#define MEM_ROOT_ARRAY_INCLUDED - -#include - -/** - A typesafe replacement for DYNAMIC_ARRAY. - We use MEM_ROOT for allocating storage, rather than the C++ heap. - The interface is chosen to be similar to std::vector. - - @remark - Unlike DYNAMIC_ARRAY, elements are properly copied - (rather than memcpy()d) if the underlying array needs to be expanded. - - @remark - Depending on has_trivial_destructor, we destroy objects which are - removed from the array (including when the array object itself is destroyed). - - @remark - Note that MEM_ROOT has no facility for reusing free space, - so don't use this if multiple re-expansions are likely to happen. - - @param Element_type The type of the elements of the container. - Elements must be copyable. - @param has_trivial_destructor If true, we don't destroy elements. - We could have used type traits to determine this. - __has_trivial_destructor is supported by some (but not all) - compilers we use. -*/ -template -class Mem_root_array -{ -public: - /// Convenience typedef, same typedef name as std::vector - typedef Element_type value_type; - - Mem_root_array(MEM_ROOT *root) - : m_root(root), m_array(NULL), m_size(0), m_capacity(0) - { - DBUG_ASSERT(m_root != NULL); - } - - Mem_root_array(MEM_ROOT *root, size_t n, const value_type &val= value_type()) - : m_root(root), m_array(NULL), m_size(0), m_capacity(0) - { - resize(n, val); - } - - ~Mem_root_array() - { - clear(); - } - - Element_type &at(size_t n) - { - DBUG_ASSERT(n < size()); - return m_array[n]; - } - - const Element_type &at(size_t n) const - { - DBUG_ASSERT(n < size()); - return m_array[n]; - } - - Element_type &operator[](size_t n) { return at(n); } - const Element_type &operator[](size_t n) const { return at(n); } - - Element_type &back() { return at(size() - 1); } - const Element_type &back() const { return at(size() - 1); } - - // Returns a pointer to the first element in the array. - Element_type *begin() { return &m_array[0]; } - const Element_type *begin() const { return &m_array[0]; } - - // Returns a pointer to the past-the-end element in the array. - Element_type *end() { return &m_array[size()]; } - const Element_type *end() const { return &m_array[size()]; } - - // Erases all of the elements. - void clear() - { - if (!empty()) - chop(0); - } - - /* - Chops the tail off the array, erasing all tail elements. - @param pos Index of first element to erase. - */ - void chop(const size_t pos) - { - DBUG_ASSERT(pos < m_size); - if (!has_trivial_destructor) - { - for (size_t ix= pos; ix < m_size; ++ix) - { - Element_type *p= &m_array[ix]; - p->~Element_type(); // Destroy discarded element. - } - } - m_size= pos; - } - - /* - Reserves space for array elements. - Copies over existing elements, in case we are re-expanding the array. - - @param n number of elements. - @retval true if out-of-memory, false otherwise. - */ - bool reserve(size_t n) - { - if (n <= m_capacity) - return false; - - void *mem= alloc_root(m_root, n * element_size()); - if (!mem) - return true; - Element_type *array= static_cast(mem); - - // Copy all the existing elements into the new array. - for (size_t ix= 0; ix < m_size; ++ix) - { - Element_type *new_p= &array[ix]; - Element_type *old_p= &m_array[ix]; - new (new_p) Element_type(*old_p); // Copy into new location. - if (!has_trivial_destructor) - old_p->~Element_type(); // Destroy the old element. - } - - // Forget the old array. - m_array= array; - m_capacity= n; - return false; - } - - /* - Adds a new element at the end of the array, after its current last - element. The content of this new element is initialized to a copy of - the input argument. - - @param element Object to copy. - @retval true if out-of-memory, false otherwise. - */ - bool push_back(const Element_type &element) - { - const size_t min_capacity= 20; - const size_t expansion_factor= 2; - if (0 == m_capacity && reserve(min_capacity)) - return true; - if (m_size == m_capacity && reserve(m_capacity * expansion_factor)) - return true; - Element_type *p= &m_array[m_size++]; - new (p) Element_type(element); - return false; - } - - /** - Removes the last element in the array, effectively reducing the - container size by one. This destroys the removed element. - */ - void pop_back() - { - DBUG_ASSERT(!empty()); - if (!has_trivial_destructor) - back().~Element_type(); - m_size-= 1; - } - - /** - Resizes the container so that it contains n elements. - - If n is smaller than the current container size, the content is - reduced to its first n elements, removing those beyond (and - destroying them). - - If n is greater than the current container size, the content is - expanded by inserting at the end as many elements as needed to - reach a size of n. If val is specified, the new elements are - initialized as copies of val, otherwise, they are - value-initialized. - - If n is also greater than the current container capacity, an automatic - reallocation of the allocated storage space takes place. - - Notice that this function changes the actual content of the - container by inserting or erasing elements from it. - */ - void resize(size_t n, const value_type &val= value_type()) - { - if (n == m_size) - return; - if (n > m_size) - { - if (!reserve(n)) - { - while (n != m_size) - push_back(val); - } - return; - } - if (!has_trivial_destructor) - { - while (n != m_size) - pop_back(); - } - m_size= n; - } - - size_t capacity() const { return m_capacity; } - size_t element_size() const { return sizeof(Element_type); } - bool empty() const { return size() == 0; } - size_t size() const { return m_size; } - const MEM_ROOT *mem_root() const { return m_root; } - -private: - MEM_ROOT *const m_root; - Element_type *m_array; - size_t m_size; - size_t m_capacity; - - // Not (yet) implemented. - Mem_root_array(const Mem_root_array&); - Mem_root_array &operator=(const Mem_root_array&); -}; - - -#endif // MEM_ROOT_ARRAY_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/message.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/message.h deleted file mode 100644 index a649173..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/message.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - To change or add messages mysqld writes to the Windows error log, run - mc.exe message.mc - and checkin generated messages.h, messages.rc and msg000001.bin under the - source control. - mc.exe can be installed with Windows SDK, some Visual Studio distributions - do not include it. -*/ -// -// Values are 32 bit values laid out as follows: -// -// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 -// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 -// +---+-+-+-----------------------+-------------------------------+ -// |Sev|C|R| Facility | Code | -// +---+-+-+-----------------------+-------------------------------+ -// -// where -// -// Sev - is the severity code -// -// 00 - Success -// 01 - Informational -// 10 - Warning -// 11 - Error -// -// C - is the Customer code flag -// -// R - is a reserved bit -// -// Facility - is the facility code -// -// Code - is the facility's status code -// -// -// Define the facility codes -// - - -// -// Define the severity codes -// - - -// -// MessageId: MSG_DEFAULT -// -// MessageText: -// -// %1 -// -// -#define MSG_DEFAULT 0xC0000064L - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/multi_range_read.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/multi_range_read.h deleted file mode 100644 index 37a00e3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/multi_range_read.h +++ /dev/null @@ -1,670 +0,0 @@ -/* - Copyright (c) 2009, 2011, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @defgroup DS-MRR declarations - @{ -*/ - -/** - A Disk-Sweep implementation of MRR Interface (DS-MRR for short) - - This is a "plugin"(*) for storage engines that allows to - 1. When doing index scans, read table rows in rowid order; - 2. when making many index lookups, do them in key order and don't - lookup the same key value multiple times; - 3. Do both #1 and #2, when applicable. - These changes are expected to speed up query execution for disk-based - storage engines running io-bound loads and "big" queries (ie. queries that - do joins and enumerate lots of records). - - (*) - only conceptually. No dynamic loading or binary compatibility of any - kind. - - General scheme of things: - - SQL Layer code - | | | - v v v - -|---|---|---- handler->multi_range_read_XXX() function calls - | | | - _____________________________________ - / DS-MRR module \ - | (order/de-duplicate lookup keys, | - | scan indexes in key order, | - | order/de-duplicate rowids, | - | retrieve full record reads in rowid | - | order) | - \_____________________________________/ - | | | - -|---|---|----- handler->read_range_first()/read_range_next(), - | | | handler->index_read(), handler->rnd_pos() calls. - | | | - v v v - Storage engine internals - - - Currently DS-MRR is used by MyISAM, InnoDB and Maria storage engines. - Potentially it can be used with any table handler that has disk-based data - storage and has better performance when reading data in rowid order. -*/ - -#include "sql_lifo_buffer.h" - -class DsMrr_impl; -class Mrr_ordered_index_reader; - - -/* A structure with key parameters that's shared among several classes */ -class Key_parameters -{ -public: - uint key_tuple_length; /* Length of index lookup tuple, in bytes */ - key_part_map key_tuple_map; /* keyparts used in index lookup tuples */ - - /* - This is - = key_tuple_length if we copy keys to buffer - = sizeof(void*) if we're using pointers to materialized keys. - */ - uint key_size_in_keybuf; - - /* TRUE <=> don't copy key values, use pointers to them instead. */ - bool use_key_pointers; - - /* TRUE <=> We can get at most one index tuple for a lookup key */ - bool index_ranges_unique; -}; - - -/** - A class to enumerate (record, range_id) pairs that match given key value. - - @note - - The idea is that we have a Lifo_buffer which holds (key, range_id) pairs - ordered by key value. From the front of the buffer we see - - (key_val1, range_id1), (key_val1, range_id2) ... (key_val2, range_idN) - - we take the first elements that have the same key value (key_val1 in the - example above), and make lookup into the table. The table will have - multiple matches for key_val1: - - == Table Index == - ... - key_val1 -> key_val1, index_tuple1 - key_val1, index_tuple2 - ... - key_val1, index_tupleN - ... - - Our goal is to produce all possible combinations, i.e. we need: - - {(key_val1, index_tuple1), range_id1} - {(key_val1, index_tuple1), range_id2} - ... ... | - {(key_val1, index_tuple1), range_idN}, - - {(key_val1, index_tuple2), range_id1} - {(key_val1, index_tuple2), range_id2} - ... ... | - {(key_val1, index_tuple2), range_idN}, - - ... ... ... - - {(key_val1, index_tupleK), range_idN} -*/ - -class Key_value_records_iterator -{ - /* Use this to get table handler, key buffer and other parameters */ - Mrr_ordered_index_reader *owner; - - /* Iterator to get (key, range_id) pairs from */ - Lifo_buffer_iterator identical_key_it; - - /* - Last of the identical key values (when we get this pointer from - identical_key_it, it will be time to stop). - */ - uchar *last_identical_key_ptr; - - /* - FALSE <=> we're right after the init() call, the record has been already - read with owner->file->index_read_map() call - */ - bool get_next_row; - -public: - int init(Mrr_ordered_index_reader *owner_arg); - int get_next(range_id_t *range_info); - void move_to_next_key_value(); -}; - - -/* - Buffer manager interface. Mrr_reader objects use it to inqure DsMrr_impl - to manage buffer space for them. -*/ -typedef struct st_buffer_manager -{ -public: - /* Opaque value to be passed as the first argument to all member functions */ - void *arg; - - /* - This is called when we've freed more space from the rowid buffer. The - callee will get the unused space from the rowid buffer and give it to the - key buffer. - */ - void (*redistribute_buffer_space)(void *arg); - - /* - This is called when both key and rowid buffers are empty, and so it's time - to reset them to their original size (They've lost their original size, - because we were dynamically growing rowid buffer and shrinking key buffer). - */ - void (*reset_buffer_sizes)(void *arg); - -} Buffer_manager; - - -/* - Mrr_reader - DS-MRR execution strategy abstraction - - A reader produces ([index]_record, range_info) pairs, and requires periodic - refill operations. - - - one starts using the reader by calling reader->get_next(), - - when a get_next() call returns HA_ERR_END_OF_FILE, one must call - refill_buffer() before they can make more get_next() calls. - - when refill_buffer() returns HA_ERR_END_OF_FILE, this means the real - end of stream and get_next() should not be called anymore. - - Both functions can return other error codes, these mean unrecoverable errors - after which one cannot continue. -*/ - -class Mrr_reader -{ -public: - virtual int get_next(range_id_t *range_info) = 0; - virtual int refill_buffer(bool initial) = 0; - virtual ~Mrr_reader() {}; /* just to remove compiler warning */ -}; - - -/* - A common base for readers that do index scans and produce index tuples -*/ - -class Mrr_index_reader : public Mrr_reader -{ -protected: - handler *file; /* Handler object to use */ -public: - virtual int init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, - void *seq_init_param, uint n_ranges, - uint mode, Key_parameters *key_par, - Lifo_buffer *key_buffer, - Buffer_manager *buf_manager_arg) = 0; - - /* Get pointer to place where every get_next() call will put rowid */ - virtual uchar *get_rowid_ptr() = 0; - /* Get the rowid (call this after get_next() call) */ - virtual void position(); - virtual bool skip_record(range_id_t range_id, uchar *rowid) = 0; - - virtual void interrupt_read() {} - virtual void resume_read() {} -}; - - -/* - A "bypass" index reader that just does and index scan. The index scan is done - by calling default MRR implementation (i.e. handler::multi_range_read_XXX()) - functions. -*/ - -class Mrr_simple_index_reader : public Mrr_index_reader -{ -public: - int init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, - void *seq_init_param, uint n_ranges, - uint mode, Key_parameters *key_par, - Lifo_buffer *key_buffer, - Buffer_manager *buf_manager_arg); - int get_next(range_id_t *range_info); - int refill_buffer(bool initial) { return initial? 0: HA_ERR_END_OF_FILE; } - uchar *get_rowid_ptr() { return file->ref; } - bool skip_record(range_id_t range_id, uchar *rowid) - { - return (file->mrr_funcs.skip_record && - file->mrr_funcs.skip_record(file->mrr_iter, range_id, rowid)); - } -}; - - -/* - A reader that sorts the key values before it makes the index lookups. -*/ - -class Mrr_ordered_index_reader : public Mrr_index_reader -{ -public: - int init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, - void *seq_init_param, uint n_ranges, - uint mode, Key_parameters *key_par, - Lifo_buffer *key_buffer, - Buffer_manager *buf_manager_arg); - int get_next(range_id_t *range_info); - int refill_buffer(bool initial); - uchar *get_rowid_ptr() { return file->ref; } - - bool skip_record(range_id_t range_info, uchar *rowid) - { - return (mrr_funcs.skip_record && - mrr_funcs.skip_record(mrr_iter, range_info, rowid)); - } - - bool skip_index_tuple(range_id_t range_info) - { - return (mrr_funcs.skip_index_tuple && - mrr_funcs.skip_index_tuple(mrr_iter, range_info)); - } - - bool set_interruption_temp_buffer(uint rowid_length, uint key_len, - uint saved_pk_len, - uchar **space_start, uchar *space_end); - void set_no_interruption_temp_buffer(); - - void interrupt_read(); - void resume_read(); - void position(); -private: - Key_value_records_iterator kv_it; - - bool scanning_key_val_iter; - - /* Buffer to store (key, range_id) pairs */ - Lifo_buffer *key_buffer; - - /* This manages key buffer allocation and sizing for us */ - Buffer_manager *buf_manager; - - Key_parameters keypar; /* index scan and lookup tuple parameters */ - - /* TRUE <=> need range association, buffers hold {rowid, range_id} pairs */ - bool is_mrr_assoc; - - /* Range sequence iteration members */ - RANGE_SEQ_IF mrr_funcs; - range_seq_t mrr_iter; - - /* TRUE == reached eof when enumerating ranges */ - bool source_exhausted; - - /* - Following members are for interrupt_read()/resume_read(). The idea is that - in some cases index scan that is done by this object is interrupted by - rnd_pos() calls made by Mrr_ordered_rndpos_reader. The problem is that - we're sharing handler->record[0] with that object, and it destroys its - contents. - We need to save/restore our current - - index tuple (for pushed index condition checks) - - clustered primary key values (again, for pushed index condition checks) - - rowid of the last record we've retrieved (in case this rowid matches - multiple ranges and we'll need to return it again) - */ - bool support_scan_interruptions; - /* Space where we save the rowid of the last record we've returned */ - uchar *saved_rowid; - - /* TRUE <=> saved_rowid has the last saved rowid */ - bool have_saved_rowid; - - uchar *saved_key_tuple; /* Saved current key tuple */ - uchar *saved_primary_key; /* Saved current primary key tuple */ - - /* - TRUE<=> saved_key_tuple (and saved_primary_key when applicable) have - valid values. - */ - bool read_was_interrupted; - - static int compare_keys(void* arg, uchar* key1, uchar* key2); - static int compare_keys_reverse(void* arg, uchar* key1, uchar* key2); - - friend class Key_value_records_iterator; - friend class DsMrr_impl; - friend class Mrr_ordered_rndpos_reader; -}; - - -/* - A reader that gets rowids from an Mrr_index_reader, and then sorts them - before getting full records with handler->rndpos() calls. -*/ - -class Mrr_ordered_rndpos_reader : public Mrr_reader -{ -public: - int init(handler *file, Mrr_index_reader *index_reader, uint mode, - Lifo_buffer *buf, Rowid_filter *filter); - int get_next(range_id_t *range_info); - int refill_buffer(bool initial); -private: - handler *file; /* Handler to use */ - - /* This what we get (rowid, range_info) pairs from */ - Mrr_index_reader *index_reader; - - /* index_reader->get_next() puts rowid here */ - uchar *index_rowid; - - /* TRUE <=> index_reader->refill_buffer() call has returned EOF */ - bool index_reader_exhausted; - - /* - TRUE <=> We should call index_reader->refill_buffer(). This happens if - 1. we've made index_reader->get_next() call which returned EOF - 2. we haven't made any index_reader calls (and our first call should - be index_reader->refill_buffer(initial=TRUE) - */ - bool index_reader_needs_refill; - - /* TRUE <=> need range association, buffers hold {rowid, range_id} pairs */ - bool is_mrr_assoc; - - /* - When reading from ordered rowid buffer: the rowid element of the last - buffer element that has rowid identical to this one. - */ - uchar *last_identical_rowid; - - /* Buffer to store (rowid, range_id) pairs */ - Lifo_buffer *rowid_buffer; - - /* Rowid filter to be checked against (if any) */ - Rowid_filter *rowid_filter; - - int refill_from_index_reader(); -}; - - -/* - A primitive "factory" of various Mrr_*_reader classes (the point is to - get various kinds of readers without having to allocate them on the heap) -*/ - -class Mrr_reader_factory -{ -public: - Mrr_ordered_rndpos_reader ordered_rndpos_reader; - Mrr_ordered_index_reader ordered_index_reader; - Mrr_simple_index_reader simple_index_reader; -}; - - -#define DSMRR_IMPL_SORT_KEYS HA_MRR_IMPLEMENTATION_FLAG1 -#define DSMRR_IMPL_SORT_ROWIDS HA_MRR_IMPLEMENTATION_FLAG2 - -/* - DS-MRR implementation for one table. Create/use one object of this class for - each ha_{myisam/innobase/etc} object. That object will be further referred to - as "the handler" - - DsMrr_impl supports has the following execution strategies: - - - Bypass DS-MRR, pass all calls to default MRR implementation, which is - an MRR-to-non-MRR call converter. - - Key-Ordered Retrieval - - Rowid-Ordered Retrieval - - DsMrr_impl will use one of the above strategies, or a combination of them, - according to the following diagram: - - (mrr function calls) - | - +----------------->-----------------+ - | | - ___________v______________ _______________v________________ - / default: use lookup keys \ / KEY-ORDERED RETRIEVAL: \ - | (or ranges) in whatever | | sort lookup keys and then make | - | order they are supplied | | index lookups in index order | - \__________________________/ \________________________________/ - | | | | | - +---<---+ | +--------------->-----------|----+ - | | | | - | | +---------------+ | - | ______v___ ______ | _______________v_______________ - | / default: read \ | / ROWID-ORDERED RETRIEVAL: \ - | | table records | | | Before reading table records, | - v | in random order | v | sort their rowids and then | - | \_________________/ | | read them in rowid order | - | | | \_______________________________/ - | | | | - | | | | - +-->---+ | +----<------+-----------<--------+ - | | | - v v v - (table records and range_ids) - - The choice of strategy depends on MRR scan properties, table properties - (whether we're scanning clustered primary key), and @@optimizer_switch - settings. - - Key-Ordered Retrieval - --------------------- - The idea is: if MRR scan is essentially a series of lookups on - - tbl.key=value1 OR tbl.key=value2 OR ... OR tbl.key=valueN - - then it makes sense to collect and order the set of lookup values, i.e. - - sort(value1, value2, .. valueN) - - and then do index lookups in index order. This results in fewer index page - fetch operations, and we also can avoid making multiple index lookups for the - same value. That is, if value1=valueN we can easily discover that after - sorting and make one index lookup for them instead of two. - - Rowid-Ordered Retrieval - ----------------------- - If we do a regular index scan or a series of index lookups, we'll be hitting - table records at random. For disk-based engines, this is much slower than - reading the same records in disk order. We assume that disk ordering of - rows is the same as ordering of their rowids (which is provided by - handler::cmp_ref()) - In order to retrieve records in different order, we must separate index - scanning and record fetching, that is, MRR scan uses the following steps: - - 1. Scan the index (and only index, that is, with HA_EXTRA_KEYREAD on) and - fill a buffer with {rowid, range_id} pairs - 2. Sort the buffer by rowid value - 3. for each {rowid, range_id} pair in the buffer - get record by rowid and return the {record, range_id} pair - 4. Repeat the above steps until we've exhausted the list of ranges we're - scanning. - - Buffer space management considerations - -------------------------------------- - With regards to buffer/memory management, MRR interface specifies that - - SQL layer provides multi_range_read_init() with buffer of certain size. - - MRR implementation may use (i.e. have at its disposal till the end of - the MRR scan) all of the buffer, or return the unused end of the buffer - to SQL layer. - - DS-MRR needs buffer in order to accumulate and sort rowids and/or keys. When - we need to accumulate/sort only keys (or only rowids), it is fairly trivial. - - When we need to accumulate/sort both keys and rowids, efficient buffer use - gets complicated. We need to: - - First, accumulate keys and sort them - - Then use the keys (smaller values go first) to obtain rowids. A key is not - needed after we've got matching rowids for it. - - Make sure that rowids are accumulated at the front of the buffer, so that we - can return the end part of the buffer to SQL layer, should there be too - few rowid values to occupy the buffer. - - All of these goals are achieved by using the following scheme: - - | | We get an empty buffer from SQL layer. - - | *-| - | *----| First, we fill the buffer with keys. Key_buffer - | *-------| part grows from end of the buffer space to start - | *----------| (In this picture, the buffer is big enough to - | *-------------| accomodate all keys and even have some space left) - - | *=============| We want to do key-ordered index scan, so we sort - the keys - - |-x *===========| Then we use the keys get rowids. Rowids are - |----x *========| stored from start of buffer space towards the end. - |--------x *=====| The part of the buffer occupied with keys - |------------x *===| gradually frees up space for rowids. In this - |--------------x *=| picture we run out of keys before we've ran out - |----------------x | of buffer space (it can be other way as well). - - |================x | Then we sort the rowids. - - | |~~~| The unused part of the buffer is at the end, so - we can return it to the SQL layer. - - |================* Sorted rowids are then used to read table records - in disk order - -*/ - -class DsMrr_impl -{ -public: - typedef void (handler::*range_check_toggle_func_t)(bool on); - - DsMrr_impl() - : secondary_file(NULL), - rowid_filter(NULL) {}; - - void init(handler *h_arg, TABLE *table_arg) - { - primary_file= h_arg; - table= table_arg; - } - int dsmrr_init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, - void *seq_init_param, uint n_ranges, uint mode, - HANDLER_BUFFER *buf); - void dsmrr_close(); - int dsmrr_next(range_id_t *range_info); - - ha_rows dsmrr_info(uint keyno, uint n_ranges, uint keys, uint key_parts, - uint *bufsz, uint *flags, Cost_estimate *cost); - - ha_rows dsmrr_info_const(uint keyno, RANGE_SEQ_IF *seq, - void *seq_init_param, uint n_ranges, uint *bufsz, - uint *flags, Cost_estimate *cost); - - int dsmrr_explain_info(uint mrr_mode, char *str, size_t size); -private: - /* Buffer to store (key, range_id) pairs */ - Lifo_buffer *key_buffer; - - /* - The "owner" handler object (the one that is expected to "own" this object - and call its functions). - */ - handler *primary_file; - TABLE *table; /* Always equal to primary_file->table */ - - /* - Secondary handler object. (created when needed, we need it when we need - to run both index scan and rnd_pos() scan at the same time) - */ - handler *secondary_file; - - /* - The rowid filter that DS-MRR has "unpushed" from the storage engine. - If it's present, DS-MRR will use it. - */ - Rowid_filter *rowid_filter; - - uint keyno; /* index we're running the scan on */ - /* TRUE <=> need range association, buffers hold {rowid, range_id} pairs */ - bool is_mrr_assoc; - - Mrr_reader_factory reader_factory; - - Mrr_reader *strategy; - bool strategy_exhausted; - - Mrr_index_reader *index_strategy; - - /* The whole buffer space that we're using */ - uchar *full_buf; - uchar *full_buf_end; - - /* - When using both rowid and key buffers: the boundary between key and rowid - parts of the buffer. This is the "original" value, actual memory ranges - used by key and rowid parts may be different because of dynamic space - reallocation between them. - */ - uchar *rowid_buffer_end; - - /* - One of the following two is used for key buffer: forward is used when - we only need key buffer, backward is used when we need both key and rowid - buffers. - */ - Forward_lifo_buffer forward_key_buf; - Backward_lifo_buffer backward_key_buf; - - /* - Buffer to store (rowid, range_id) pairs, or just rowids if - is_mrr_assoc==FALSE - */ - Forward_lifo_buffer rowid_buffer; - - bool choose_mrr_impl(uint keyno, ha_rows rows, uint *flags, uint *bufsz, - Cost_estimate *cost); - bool get_disk_sweep_mrr_cost(uint keynr, ha_rows rows, uint flags, - uint *buffer_size, uint extra_mem_overhead, - Cost_estimate *cost); - bool check_cpk_scan(THD *thd, TABLE_SHARE *share, uint keyno, uint mrr_flags); - - bool setup_buffer_sharing(uint key_size_in_keybuf, key_part_map key_tuple_map); - - /* Buffer_manager and its member functions */ - Buffer_manager buf_manager; - static void redistribute_buffer_space(void *dsmrr_arg); - static void reset_buffer_sizes(void *dsmrr_arg); - static void do_nothing(void *dsmrr_arg); - - Lifo_buffer* get_key_buffer() { return key_buffer; } - - friend class Key_value_records_iterator; - friend class Mrr_ordered_index_reader; - friend class Mrr_ordered_rndpos_reader; - - int setup_two_handlers(); - void close_second_handler(); -}; - -/** - @} (end of group DS-MRR declarations) -*/ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_alarm.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_alarm.h deleted file mode 100644 index 14a81c1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_alarm.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2000, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - File to include when we want to use alarm or a loop_counter to display - some information when a program is running -*/ -#ifndef _my_alarm_h -#define _my_alarm_h -#ifdef __cplusplus -extern "C" { -#endif - -extern int volatile my_have_got_alarm; -extern ulong my_time_to_wait_for_lock; - -#if defined(HAVE_ALARM) && !defined(NO_ALARM_LOOP) -#include -#ifdef HAVE_SIGHANDLER_T -#define sig_return sighandler_t -#elif defined(SOLARIS) || defined(__sun) || defined(__APPLE__) || defined(__FreeBSD__) -typedef void (*sig_return)(int); /* Returns type from signal */ -#else -typedef void (*sig_return)(void); /* Returns type from signal */ -#endif -#define ALARM_VARIABLES uint alarm_old=0; \ - sig_return alarm_signal=0 -#define ALARM_INIT my_have_got_alarm=0 ; \ - alarm_old=(uint) alarm(MY_HOW_OFTEN_TO_ALARM); \ - alarm_signal=signal(SIGALRM,my_set_alarm_variable); -#define ALARM_END (void) signal(SIGALRM,alarm_signal); \ - (void) alarm(alarm_old); -#define ALARM_TEST my_have_got_alarm -#ifdef SIGNAL_HANDLER_RESET_ON_DELIVERY -#define ALARM_REINIT (void) alarm(MY_HOW_OFTEN_TO_ALARM); \ - (void) signal(SIGALRM,my_set_alarm_variable);\ - my_have_got_alarm=0; -#else -#define ALARM_REINIT (void) alarm((uint) MY_HOW_OFTEN_TO_ALARM); \ - my_have_got_alarm=0; -#endif /* SIGNAL_HANDLER_RESET_ON_DELIVERY */ -#else -#define ALARM_VARIABLES long alarm_pos=0,alarm_end_pos=MY_HOW_OFTEN_TO_WRITE-1 -#define ALARM_INIT -#define ALARM_END -#define ALARM_TEST (alarm_pos++ >= alarm_end_pos) -#define ALARM_REINIT (alarm_end_pos+=MY_HOW_OFTEN_TO_WRITE) -#endif /* HAVE_ALARM */ - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_apc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_apc.h deleted file mode 100644 index cc98e36..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_apc.h +++ /dev/null @@ -1,161 +0,0 @@ -#ifndef SQL_MY_APC_INCLUDED -#define SQL_MY_APC_INCLUDED -/* - Copyright (c) 2011, 2013 Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Interface - ~~~~~~~~~ - ( - - This is an APC request queue - - We assume there is a particular owner thread which periodically calls - process_apc_requests() to serve the call requests. - - Other threads can post call requests, and block until they are exectued. - ) - - Implementation - ~~~~~~~~~~~~~~ - - The target has a mutex-guarded request queue. - - - After the request has been put into queue, the requestor waits for request - to be satisfied. The worker satisifes the request and signals the - requestor. -*/ - -class THD; - -/* - Target for asynchronous procedure calls (APCs). - - A target is running in some particular thread, - - One can make calls to it from other threads. -*/ -class Apc_target -{ - mysql_mutex_t *LOCK_thd_kill_ptr; -public: - Apc_target() : enabled(0), apc_calls(NULL) {} - ~Apc_target() { DBUG_ASSERT(!enabled && !apc_calls);} - - void init(mysql_mutex_t *target_mutex); - - /* Destroy the target. The target must be disabled when this call is made. */ - void destroy() { DBUG_ASSERT(!enabled); } - - /* Enter ther state where the target is available for serving APC requests */ - void enable() { enabled++; } - - /* - Make the target unavailable for serving APC requests. - - @note - This call will serve all requests that were already enqueued - */ - void disable() - { - DBUG_ASSERT(enabled); - mysql_mutex_lock(LOCK_thd_kill_ptr); - bool process= !--enabled && have_apc_requests(); - mysql_mutex_unlock(LOCK_thd_kill_ptr); - if (unlikely(process)) - process_apc_requests(); - } - - void process_apc_requests(); - /* - A lightweight function, intended to be used in frequent checks like this: - - if (apc_target.have_requests()) apc_target.process_apc_requests() - */ - inline bool have_apc_requests() - { - return MY_TEST(apc_calls); - } - - inline bool is_enabled() { return enabled; } - - /* Functor class for calls you can schedule */ - class Apc_call - { - public: - /* This function will be called in the target thread */ - virtual void call_in_target_thread()= 0; - virtual ~Apc_call() {} - }; - - /* Make a call in the target thread (see function definition for details) */ - bool make_apc_call(THD *caller_thd, Apc_call *call, int timeout_sec, bool *timed_out); - -#ifndef DBUG_OFF - int n_calls_processed; /* Number of calls served by this target */ -#endif -private: - class Call_request; - - /* - Non-zero value means we're enabled. It's an int, not bool, because one can - call enable() N times (and then needs to call disable() N times before the - target is really disabled) - */ - int enabled; - - /* - Circular, double-linked list of all enqueued call requests. - We use this structure, because we - - process requests sequentially: requests are added at the end of the - list and removed from the front. With circular list, we can keep one - pointer, and access both front an back of the list with it. - - a thread that has posted a request may time out (or be KILLed) and - cancel the request, which means we need a fast request-removal - operation. - */ - Call_request *apc_calls; - - class Call_request - { - public: - Apc_call *call; /* Functor to be called */ - - /* The caller will actually wait for "processed==TRUE" */ - bool processed; - - /* Condition that will be signalled when the request has been served */ - mysql_cond_t COND_request; - - /* Double linked-list linkage */ - Call_request *next; - Call_request *prev; - - const char *what; /* (debug) state of the request */ - }; - - void enqueue_request(Call_request *qe); - void dequeue_request(Call_request *qe); - - /* return the first call request in queue, or NULL if there are none enqueued */ - Call_request *get_first_in_queue() - { - return apc_calls; - } -}; - -#ifdef HAVE_PSI_INTERFACE -void init_show_explain_psi_keys(void); -#else -#define init_show_explain_psi_keys() /* no-op */ -#endif - -#endif //SQL_MY_APC_INCLUDED - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_atomic.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_atomic.h deleted file mode 100644 index 81da9e3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_atomic.h +++ /dev/null @@ -1,172 +0,0 @@ -#ifndef MY_ATOMIC_INCLUDED -#define MY_ATOMIC_INCLUDED - -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2018, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - This header defines five atomic operations: - - my_atomic_add#(&var, what) - my_atomic_add#_explicit(&var, what, memory_order) - 'Fetch and Add' - add 'what' to *var, and return the old value of *var - All memory orders are valid. - - my_atomic_fas#(&var, what) - my_atomic_fas#_explicit(&var, what, memory_order) - 'Fetch And Store' - store 'what' in *var, and return the old value of *var - All memory orders are valid. - - my_atomic_cas#(&var, &old, new) - my_atomic_cas#_weak_explicit(&var, &old, new, succ, fail) - my_atomic_cas#_strong_explicit(&var, &old, new, succ, fail) - 'Compare And Swap' - if *var is equal to *old, then store 'new' in *var, and return TRUE - otherwise store *var in *old, and return FALSE - succ - the memory synchronization ordering for the read-modify-write - operation if the comparison succeeds. All memory orders are valid. - fail - the memory synchronization ordering for the load operation if the - comparison fails. Cannot be MY_MEMORY_ORDER_RELEASE or - MY_MEMORY_ORDER_ACQ_REL and cannot specify stronger ordering than succ. - - The weak form is allowed to fail spuriously, that is, act as if *var != *old - even if they are equal. When a compare-and-exchange is in a loop, the weak - version will yield better performance on some platforms. When a weak - compare-and-exchange would require a loop and a strong one would not, the - strong one is preferable. - - my_atomic_load#(&var) - my_atomic_load#_explicit(&var, memory_order) - return *var - Order must be one of MY_MEMORY_ORDER_RELAXED, MY_MEMORY_ORDER_CONSUME, - MY_MEMORY_ORDER_ACQUIRE, MY_MEMORY_ORDER_SEQ_CST. - - my_atomic_store#(&var, what) - my_atomic_store#_explicit(&var, what, memory_order) - store 'what' in *var - Order must be one of MY_MEMORY_ORDER_RELAXED, MY_MEMORY_ORDER_RELEASE, - MY_MEMORY_ORDER_SEQ_CST. - - '#' is substituted by a size suffix - 8, 16, 32, 64, or ptr - (e.g. my_atomic_add8, my_atomic_fas32, my_atomic_casptr). - - The first version orders memory accesses according to MY_MEMORY_ORDER_SEQ_CST, - the second version (with _explicit suffix) orders memory accesses according to - given memory order. - - memory_order specifies how non-atomic memory accesses are to be ordered around - an atomic operation: - - MY_MEMORY_ORDER_RELAXED - there are no constraints on reordering of memory - accesses around the atomic variable. - MY_MEMORY_ORDER_CONSUME - no reads in the current thread dependent on the - value currently loaded can be reordered before this - load. This ensures that writes to dependent - variables in other threads that release the same - atomic variable are visible in the current thread. - On most platforms, this affects compiler - optimization only. - MY_MEMORY_ORDER_ACQUIRE - no reads in the current thread can be reordered - before this load. This ensures that all writes in - other threads that release the same atomic variable - are visible in the current thread. - MY_MEMORY_ORDER_RELEASE - no writes in the current thread can be reordered - after this store. This ensures that all writes in - the current thread are visible in other threads that - acquire the same atomic variable. - MY_MEMORY_ORDER_ACQ_REL - no reads in the current thread can be reordered - before this load as well as no writes in the current - thread can be reordered after this store. The - operation is read-modify-write operation. It is - ensured that all writes in another threads that - release the same atomic variable are visible before - the modification and the modification is visible in - other threads that acquire the same atomic variable. - MY_MEMORY_ORDER_SEQ_CST - The operation has the same semantics as - acquire-release operation, and additionally has - sequentially-consistent operation ordering. - - We choose implementation as follows: on Windows using Visual C++ the native - implementation should be preferable. When using gcc we prefer the Solaris - implementation before the gcc because of stability preference, we choose gcc - builtins if available. -*/ - -#if defined(_MSC_VER) -#include "atomic/generic-msvc.h" -#elif defined(HAVE_SOLARIS_ATOMIC) -#include "atomic/solaris.h" -#elif defined(HAVE_GCC_C11_ATOMICS) -#include "atomic/gcc_builtins.h" -#endif - -#if SIZEOF_LONG == 4 -#define my_atomic_addlong(A,B) my_atomic_add32((int32*) (A), (B)) -#define my_atomic_loadlong(A) my_atomic_load32((int32*) (A)) -#define my_atomic_loadlong_explicit(A,O) my_atomic_load32_explicit((int32*) (A), (O)) -#define my_atomic_storelong(A,B) my_atomic_store32((int32*) (A), (B)) -#define my_atomic_faslong(A,B) my_atomic_fas32((int32*) (A), (B)) -#define my_atomic_caslong(A,B,C) my_atomic_cas32((int32*) (A), (int32*) (B), (C)) -#else -#define my_atomic_addlong(A,B) my_atomic_add64((int64*) (A), (B)) -#define my_atomic_loadlong(A) my_atomic_load64((int64*) (A)) -#define my_atomic_loadlong_explicit(A,O) my_atomic_load64_explicit((int64*) (A), (O)) -#define my_atomic_storelong(A,B) my_atomic_store64((int64*) (A), (B)) -#define my_atomic_faslong(A,B) my_atomic_fas64((int64*) (A), (B)) -#define my_atomic_caslong(A,B,C) my_atomic_cas64((int64*) (A), (int64*) (B), (C)) -#endif - -#ifndef MY_MEMORY_ORDER_SEQ_CST -#define MY_MEMORY_ORDER_RELAXED -#define MY_MEMORY_ORDER_CONSUME -#define MY_MEMORY_ORDER_ACQUIRE -#define MY_MEMORY_ORDER_RELEASE -#define MY_MEMORY_ORDER_ACQ_REL -#define MY_MEMORY_ORDER_SEQ_CST - -#define my_atomic_store32_explicit(P, D, O) my_atomic_store32((P), (D)) -#define my_atomic_store64_explicit(P, D, O) my_atomic_store64((P), (D)) -#define my_atomic_storeptr_explicit(P, D, O) my_atomic_storeptr((P), (D)) - -#define my_atomic_load32_explicit(P, O) my_atomic_load32((P)) -#define my_atomic_load64_explicit(P, O) my_atomic_load64((P)) -#define my_atomic_loadptr_explicit(P, O) my_atomic_loadptr((P)) - -#define my_atomic_fas32_explicit(P, D, O) my_atomic_fas32((P), (D)) -#define my_atomic_fas64_explicit(P, D, O) my_atomic_fas64((P), (D)) -#define my_atomic_fasptr_explicit(P, D, O) my_atomic_fasptr((P), (D)) - -#define my_atomic_add32_explicit(P, A, O) my_atomic_add32((P), (A)) -#define my_atomic_add64_explicit(P, A, O) my_atomic_add64((P), (A)) -#define my_atomic_addptr_explicit(P, A, O) my_atomic_addptr((P), (A)) - -#define my_atomic_cas32_weak_explicit(P, E, D, S, F) \ - my_atomic_cas32((P), (E), (D)) -#define my_atomic_cas64_weak_explicit(P, E, D, S, F) \ - my_atomic_cas64((P), (E), (D)) -#define my_atomic_casptr_weak_explicit(P, E, D, S, F) \ - my_atomic_casptr((P), (E), (D)) - -#define my_atomic_cas32_strong_explicit(P, E, D, S, F) \ - my_atomic_cas32((P), (E), (D)) -#define my_atomic_cas64_strong_explicit(P, E, D, S, F) \ - my_atomic_cas64((P), (E), (D)) -#define my_atomic_casptr_strong_explicit(P, E, D, S, F) \ - my_atomic_casptr((P), (E), (D)) -#endif -#endif /* MY_ATOMIC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_atomic_wrapper.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_atomic_wrapper.h deleted file mode 100644 index 64835e3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_atomic_wrapper.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef __cplusplus -#include -/** - A wrapper for std::atomic, defaulting to std::memory_order_relaxed. - - When it comes to atomic loads or stores at std::memory_order_relaxed - on IA-32 or AMD64, this wrapper is only introducing some constraints - to the C++ compiler, to prevent some optimizations of loads or - stores. - - On POWER and ARM, atomic loads and stores involve different instructions - from normal loads and stores and will thus incur some overhead. - - Because atomic read-modify-write operations will always incur - overhead, we intentionally do not define - operator++(), operator--(), operator+=(), operator-=(), or similar, - to make the overhead stand out in the users of this code. -*/ -template class Atomic_relaxed -{ - std::atomic m; -public: - Atomic_relaxed(const Atomic_relaxed &rhs) - { m.store(rhs, std::memory_order_relaxed); } - Atomic_relaxed(Type val) : m(val) {} - Atomic_relaxed() {} - - operator Type() const { return m.load(std::memory_order_relaxed); } - Type operator=(const Type val) - { m.store(val, std::memory_order_relaxed); return val; } - Type operator=(const Atomic_relaxed &rhs) { return *this= Type{rhs}; } - Type fetch_add(const Type i, std::memory_order o= std::memory_order_relaxed) - { return m.fetch_add(i, o); } - Type fetch_sub(const Type i, std::memory_order o= std::memory_order_relaxed) - { return m.fetch_sub(i, o); } - Type fetch_xor(const Type i, std::memory_order o= std::memory_order_relaxed) - { return m.fetch_xor(i, o); } - bool compare_exchange_strong(Type& i1, const Type i2, - std::memory_order o1= std::memory_order_relaxed, - std::memory_order o2= std::memory_order_relaxed) - { return m.compare_exchange_strong(i1, i2, o1, o2); } - Type exchange(const Type i, std::memory_order o= std::memory_order_relaxed) - { return m.exchange(i, o); } -}; -#endif /* __cplusplus */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_base.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_base.h deleted file mode 100644 index dc5b135..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_base.h +++ /dev/null @@ -1,685 +0,0 @@ -/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 1995, 2018, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* This file includes constants used with all databases */ - -#ifndef _my_base_h -#define _my_base_h - -#include /* This includes types */ -#include -#include -#include - -#ifndef EOVERFLOW -#define EOVERFLOW 84 -#endif - -#include - -/* The following is bits in the flag parameter to ha_open() */ - -#define HA_OPEN_ABORT_IF_LOCKED 0U /* default */ -#define HA_OPEN_WAIT_IF_LOCKED 1U -#define HA_OPEN_IGNORE_IF_LOCKED 2U -#define HA_OPEN_TMP_TABLE 4U /* Table is a temp table */ -#define HA_OPEN_DELAY_KEY_WRITE 8U /* Don't update index */ -#define HA_OPEN_ABORT_IF_CRASHED 16U -#define HA_OPEN_FOR_REPAIR 32U /* open even if crashed */ -#define HA_OPEN_FROM_SQL_LAYER 64U -#define HA_OPEN_MMAP 128U /* open memory mapped */ -#define HA_OPEN_COPY 256U /* Open copy (for repair) */ -/* Internal temp table, used for temporary results */ -#define HA_OPEN_INTERNAL_TABLE 512U -#define HA_OPEN_NO_PSI_CALL 1024U /* Don't call/connect PSI */ -#define HA_OPEN_MERGE_TABLE 2048U -#define HA_OPEN_FOR_CREATE 4096U - -/* - Allow opening even if table is incompatible as this is for ALTER TABLE which - will fix the table structure. -*/ -#define HA_OPEN_FOR_ALTER 8192U - -/* Open table for FLUSH */ -#define HA_OPEN_FOR_FLUSH 8192U - - -/* The following is parameter to ha_rkey() how to use key */ - -/* - We define a complete-field prefix of a key value as a prefix where - the last included field in the prefix contains the full field, not - just some bytes from the start of the field. A partial-field prefix - is allowed to contain only a few first bytes from the last included - field. - - Below HA_READ_KEY_EXACT, ..., HA_READ_BEFORE_KEY can take a - complete-field prefix of a key value as the search - key. HA_READ_PREFIX and HA_READ_PREFIX_LAST could also take a - partial-field prefix, but currently (4.0.10) they are only used with - complete-field prefixes. MySQL uses a padding trick to implement - LIKE 'abc%' queries. - - NOTE that in InnoDB HA_READ_PREFIX_LAST will NOT work with a - partial-field prefix because InnoDB currently strips spaces from the - end of varchar fields! -*/ - -enum ha_rkey_function { - HA_READ_KEY_EXACT, /* Find first record else error */ - HA_READ_KEY_OR_NEXT, /* Record or next record */ - HA_READ_KEY_OR_PREV, /* Record or previous */ - HA_READ_AFTER_KEY, /* Find next rec. after key-record */ - HA_READ_BEFORE_KEY, /* Find next rec. before key-record */ - HA_READ_PREFIX, /* Key which as same prefix */ - HA_READ_PREFIX_LAST, /* Last key with the same prefix */ - HA_READ_PREFIX_LAST_OR_PREV, /* Last or prev key with the same prefix */ - HA_READ_MBR_CONTAIN, - HA_READ_MBR_INTERSECT, - HA_READ_MBR_WITHIN, - HA_READ_MBR_DISJOINT, - HA_READ_MBR_EQUAL -}; - - /* Key algorithm types */ - -enum ha_key_alg { - HA_KEY_ALG_UNDEF= 0, /* Not specified (old file) */ - HA_KEY_ALG_BTREE= 1, /* B-tree, default one */ - HA_KEY_ALG_RTREE= 2, /* R-tree, for spatial searches */ - HA_KEY_ALG_HASH= 3, /* HASH keys (HEAP tables) */ - HA_KEY_ALG_FULLTEXT= 4, /* FULLTEXT (MyISAM tables) */ - HA_KEY_ALG_LONG_HASH= 5 /* long BLOB keys */ -}; - - /* Storage media types */ - -enum ha_storage_media { - HA_SM_DEFAULT= 0, /* Not specified (engine default) */ - HA_SM_DISK= 1, /* DISK storage */ - HA_SM_MEMORY= 2 /* MAIN MEMORY storage */ -}; - - /* The following is parameter to ha_extra() */ - -enum ha_extra_function { - HA_EXTRA_NORMAL=0, /* Optimize for space (def) */ - HA_EXTRA_QUICK=1, /* Optimize for speed */ - HA_EXTRA_NOT_USED=2, /* Should be ignored by handler */ - HA_EXTRA_CACHE=3, /* Cache record in HA_rrnd() */ - HA_EXTRA_NO_CACHE=4, /* End caching of records (def) */ - HA_EXTRA_NO_READCHECK=5, /* No readcheck on update */ - HA_EXTRA_READCHECK=6, /* Use readcheck (def) */ - HA_EXTRA_KEYREAD=7, /* Read only key to database */ - HA_EXTRA_NO_KEYREAD=8, /* Normal read of records (def) */ - HA_EXTRA_NO_USER_CHANGE=9, /* No user is allowed to write */ - HA_EXTRA_KEY_CACHE=10, - HA_EXTRA_NO_KEY_CACHE=11, - HA_EXTRA_WAIT_LOCK=12, /* Wait until file is avalably (def) */ - HA_EXTRA_NO_WAIT_LOCK=13, /* If file is locked, return quickly */ - HA_EXTRA_WRITE_CACHE=14, /* Use write cache in ha_write() */ - HA_EXTRA_FLUSH_CACHE=15, /* flush write_record_cache */ - HA_EXTRA_NO_KEYS=16, /* Remove all update of keys */ - HA_EXTRA_KEYREAD_CHANGE_POS=17, /* Keyread, but change pos */ - /* xxxxchk -r must be used */ - HA_EXTRA_REMEMBER_POS=18, /* Remember pos for next/prev */ - HA_EXTRA_RESTORE_POS=19, - HA_EXTRA_REINIT_CACHE=20, /* init cache from current record */ - HA_EXTRA_FORCE_REOPEN=21, /* Datafile have changed on disk */ - HA_EXTRA_FLUSH, /* Flush tables to disk */ - HA_EXTRA_NO_ROWS, /* Don't write rows */ - HA_EXTRA_RESET_STATE, /* Reset positions */ - HA_EXTRA_IGNORE_DUP_KEY, /* Dup keys don't rollback everything*/ - HA_EXTRA_NO_IGNORE_DUP_KEY, - HA_EXTRA_PREPARE_FOR_DROP, - HA_EXTRA_PREPARE_FOR_UPDATE, /* Remove read cache if problems */ - HA_EXTRA_PRELOAD_BUFFER_SIZE, /* Set buffer size for preloading */ - /* - On-the-fly switching between unique and non-unique key inserting. - */ - HA_EXTRA_CHANGE_KEY_TO_UNIQUE, - HA_EXTRA_CHANGE_KEY_TO_DUP, - /* - When using HA_EXTRA_KEYREAD, overwrite only key member fields and keep - other fields intact. When this is off (by default) InnoDB will use memcpy - to overwrite entire row. - */ - HA_EXTRA_KEYREAD_PRESERVE_FIELDS, - HA_EXTRA_MMAP, - /* - Ignore if the a tuple is not found, continue processing the - transaction and ignore that 'row'. Needed for idempotency - handling on the slave - */ - HA_EXTRA_IGNORE_NO_KEY, - HA_EXTRA_NO_IGNORE_NO_KEY, - /* - Mark the table as a log table. For some handlers (e.g. CSV) this results - in a special locking for the table. - */ - HA_EXTRA_MARK_AS_LOG_TABLE, - /* - Informs handler that write_row() which tries to insert new row into the - table and encounters some already existing row with same primary/unique - key can replace old row with new row instead of reporting error (basically - it informs handler that we do REPLACE instead of simple INSERT). - Off by default. - */ - HA_EXTRA_WRITE_CAN_REPLACE, - HA_EXTRA_WRITE_CANNOT_REPLACE, - /* - Inform handler that delete_row()/update_row() cannot batch deletes/updates - and should perform them immediately. This may be needed when table has - AFTER DELETE/UPDATE triggers which access to subject table. - These flags are reset by the handler::extra(HA_EXTRA_RESET) call. - */ - HA_EXTRA_DELETE_CANNOT_BATCH, - HA_EXTRA_UPDATE_CANNOT_BATCH, - /* - Inform handler that an "INSERT...ON DUPLICATE KEY UPDATE" will be - executed. This condition is unset by HA_EXTRA_NO_IGNORE_DUP_KEY. - */ - HA_EXTRA_INSERT_WITH_UPDATE, - /* Inform handler that we will do a rename */ - HA_EXTRA_PREPARE_FOR_RENAME, - /* - Special actions for MERGE tables. - */ - HA_EXTRA_ADD_CHILDREN_LIST, - HA_EXTRA_ATTACH_CHILDREN, - HA_EXTRA_IS_ATTACHED_CHILDREN, - HA_EXTRA_DETACH_CHILDREN, - HA_EXTRA_DETACH_CHILD, - /* Inform handler we will force a close as part of flush */ - HA_EXTRA_PREPARE_FOR_FORCED_CLOSE, - /* Inform handler that we will do an alter table */ - HA_EXTRA_PREPARE_FOR_ALTER_TABLE, - /* - Used in ha_partition::handle_ordered_index_scan() to inform engine - that we are starting an ordered index scan. Needed by Spider - */ - HA_EXTRA_STARTING_ORDERED_INDEX_SCAN, - /** Start writing rows during ALTER TABLE...ALGORITHM=COPY. */ - HA_EXTRA_BEGIN_ALTER_COPY, - /** Finish writing rows during ALTER TABLE...ALGORITHM=COPY. */ - HA_EXTRA_END_ALTER_COPY, - /** Fake the start of a statement after wsrep_load_data_splitting hack */ - HA_EXTRA_FAKE_START_STMT -}; - -/* Compatible option, to be deleted in 6.0 */ -#define HA_EXTRA_PREPARE_FOR_DELETE HA_EXTRA_PREPARE_FOR_DROP - - /* The following is parameter to ha_panic() */ - -enum ha_panic_function { - HA_PANIC_CLOSE, /* Close all databases */ - HA_PANIC_WRITE, /* Unlock and write status */ - HA_PANIC_READ /* Lock and read keyinfo */ -}; - - /* The following is parameter to ha_create(); keytypes */ - -enum ha_base_keytype { - HA_KEYTYPE_END=0, - HA_KEYTYPE_TEXT=1, /* Key is sorted as letters */ - HA_KEYTYPE_BINARY=2, /* Key is sorted as unsigned chars */ - HA_KEYTYPE_SHORT_INT=3, - HA_KEYTYPE_LONG_INT=4, - HA_KEYTYPE_FLOAT=5, - HA_KEYTYPE_DOUBLE=6, - HA_KEYTYPE_NUM=7, /* Not packed num with pre-space */ - HA_KEYTYPE_USHORT_INT=8, - HA_KEYTYPE_ULONG_INT=9, - HA_KEYTYPE_LONGLONG=10, - HA_KEYTYPE_ULONGLONG=11, - HA_KEYTYPE_INT24=12, - HA_KEYTYPE_UINT24=13, - HA_KEYTYPE_INT8=14, - /* Varchar (0-255 bytes) with length packed with 1 byte */ - HA_KEYTYPE_VARTEXT1=15, /* Key is sorted as letters */ - HA_KEYTYPE_VARBINARY1=16, /* Key is sorted as unsigned chars */ - /* Varchar (0-65535 bytes) with length packed with 2 bytes */ - HA_KEYTYPE_VARTEXT2=17, /* Key is sorted as letters */ - HA_KEYTYPE_VARBINARY2=18, /* Key is sorted as unsigned chars */ - HA_KEYTYPE_BIT=19 -}; - -#define HA_MAX_KEYTYPE 31 /* Must be log2-1 */ - -/* - These flags kan be OR:ed to key-flag - Note that these can only be up to 16 bits! -*/ - -#define HA_NOSAME 1U /* Set if not dupplicated records */ -#define HA_PACK_KEY 2U /* Pack string key to previous key */ -#define HA_AUTO_KEY 16U -#define HA_BINARY_PACK_KEY 32U /* Packing of all keys to prev key */ -#define HA_FULLTEXT 128U /* For full-text search */ -#define HA_UNIQUE_CHECK 256U /* Check the key for uniqueness */ -#define HA_SPATIAL 1024U /* For spatial search */ -#define HA_NULL_ARE_EQUAL 2048U /* NULL in key are cmp as equal */ -#define HA_GENERATED_KEY 8192U /* Automatically generated key */ - - /* The combination of the above can be used for key type comparison. */ -#define HA_KEYFLAG_MASK (HA_NOSAME | HA_PACK_KEY | HA_AUTO_KEY | \ - HA_BINARY_PACK_KEY | HA_FULLTEXT | HA_UNIQUE_CHECK | \ - HA_SPATIAL | HA_NULL_ARE_EQUAL | HA_GENERATED_KEY) - -/* - Key contains partial segments. - - This flag is internal to the MySQL server by design. It is not supposed - neither to be saved in FRM-files, nor to be passed to storage engines. - It is intended to pass information into internal static sort_keys(KEY *, - KEY *) function. - - This flag can be calculated -- it's based on key lengths comparison. -*/ -#define HA_KEY_HAS_PART_KEY_SEG 65536 -/* Internal Flag Can be calcaluted */ -#define HA_INVISIBLE_KEY 2<<18 - /* Automatic bits in key-flag */ - -#define HA_SPACE_PACK_USED 4 /* Test for if SPACE_PACK used */ -#define HA_VAR_LENGTH_KEY 8 -#define HA_NULL_PART_KEY 64 -#define HA_USES_COMMENT 4096 -#define HA_USES_PARSER 16384 /* Fulltext index uses [pre]parser */ -#define HA_USES_BLOCK_SIZE ((uint) 32768) -#define HA_SORT_ALLOWS_SAME 512 /* Intern bit when sorting records */ - -/* This flag can be used only in KEY::ext_key_flags */ -#define HA_EXT_NOSAME 131072 - - /* These flags can be added to key-seg-flag */ - -#define HA_SPACE_PACK 1 /* Pack space in key-seg */ -#define HA_PART_KEY_SEG 4 /* Used by MySQL for part-key-cols */ -#define HA_VAR_LENGTH_PART 8 -#define HA_NULL_PART 16 -#define HA_BLOB_PART 32 -#define HA_SWAP_KEY 64 -#define HA_REVERSE_SORT 128 /* Sort key in reverse order */ -#define HA_NO_SORT 256 /* do not bother sorting on this keyseg */ - -#define HA_BIT_PART 1024 -#define HA_CAN_MEMCMP 2048 /* internal, never stored in frm */ - - /* optionbits for database */ -#define HA_OPTION_PACK_RECORD 1U -#define HA_OPTION_PACK_KEYS 2U -#define HA_OPTION_COMPRESS_RECORD 4U -#define HA_OPTION_LONG_BLOB_PTR 8U /* new ISAM format */ -#define HA_OPTION_TMP_TABLE 16U -#define HA_OPTION_CHECKSUM 32U -#define HA_OPTION_DELAY_KEY_WRITE 64U -#define HA_OPTION_NO_PACK_KEYS 128U /* Reserved for MySQL */ -/* unused 256 */ -#define HA_OPTION_RELIES_ON_SQL_LAYER 512U -#define HA_OPTION_NULL_FIELDS 1024U -#define HA_OPTION_PAGE_CHECKSUM 2048U -/* - STATS_PERSISTENT=1 has been specified in the SQL command (either CREATE - or ALTER TABLE). Table and index statistics that are collected by the - storage engine and used by the optimizer for query optimization will be - stored on disk and will not change after a server restart. -*/ -#define HA_OPTION_STATS_PERSISTENT 4096U -/* - STATS_PERSISTENT=0 has been specified in CREATE/ALTER TABLE. Statistics - for the table will be wiped away on server shutdown and new ones recalculated - after the server is started again. If none of HA_OPTION_STATS_PERSISTENT or - HA_OPTION_NO_STATS_PERSISTENT is set, this means that the setting is not - explicitly set at table level and the corresponding table will use whatever - is the global server default. -*/ -#define HA_OPTION_NO_STATS_PERSISTENT 8192U - -/* .frm has extra create options in linked-list format */ -#define HA_OPTION_TEXT_CREATE_OPTIONS_legacy (1U << 14) /* 5.2 to 5.5, unused since 10.0 */ -#define HA_OPTION_TEMP_COMPRESS_RECORD (1U << 15) /* set by isamchk */ -#define HA_OPTION_READ_ONLY_DATA (1U << 16) /* Set by isamchk */ -#define HA_OPTION_NO_CHECKSUM (1U << 17) -#define HA_OPTION_NO_DELAY_KEY_WRITE (1U << 18) - - /* Bits in flag to create() */ - -#define HA_DONT_TOUCH_DATA 1U /* Don't empty datafile (isamchk) */ -#define HA_PACK_RECORD 2U /* Request packed record format */ -#define HA_CREATE_TMP_TABLE 4U -#define HA_CREATE_CHECKSUM 8U -#define HA_CREATE_KEEP_FILES 16U /* don't overwrite .MYD and MYI */ -#define HA_CREATE_PAGE_CHECKSUM 32U -#define HA_CREATE_DELAY_KEY_WRITE 64U -#define HA_CREATE_RELIES_ON_SQL_LAYER 128U -#define HA_CREATE_INTERNAL_TABLE 256U -#define HA_PRESERVE_INSERT_ORDER 512U -#define HA_CREATE_NO_ROLLBACK 1024U - -/* Flags used by start_bulk_insert */ - -#define HA_CREATE_UNIQUE_INDEX_BY_SORT 1U - - -/* - The following flags (OR-ed) are passed to handler::info() method. - The method copies misc handler information out of the storage engine - to data structures accessible from MySQL - - Same flags are also passed down to mi_status, myrg_status, etc. -*/ - -/* this one is not used */ -#define HA_STATUS_POS 1U -/* - assuming the table keeps shared actual copy of the 'info' and - local, possibly outdated copy, the following flag means that - it should not try to get the actual data (locking the shared structure) - slightly outdated version will suffice -*/ -#define HA_STATUS_NO_LOCK 2U -/* update the time of the last modification (in handler::update_time) */ -#define HA_STATUS_TIME 4U -/* - update the 'constant' part of the info: - handler::max_data_file_length, max_index_file_length, create_time - sortkey, ref_length, block_size, data_file_name, index_file_name. - handler::table->s->keys_in_use, keys_for_keyread, rec_per_key -*/ -#define HA_STATUS_CONST 8U -/* - update the 'variable' part of the info: - handler::records, deleted, data_file_length, index_file_length, - check_time, mean_rec_length -*/ -#define HA_STATUS_VARIABLE 16U -/* - get the information about the key that caused last duplicate value error - update handler::errkey and handler::dupp_ref - see handler::get_dup_key() -*/ -#define HA_STATUS_ERRKEY 32U -/* - update handler::auto_increment_value -*/ -#define HA_STATUS_AUTO 64U -/* - Get also delete_length when HA_STATUS_VARIABLE is called. It's ok to set it also - when only HA_STATUS_VARIABLE but it won't be used. -*/ -#define HA_STATUS_VARIABLE_EXTRA 128U -/* - Treat empty table as empty (ignore HA_STATUS_TIME hack). -*/ -#define HA_STATUS_OPEN 256U - -/* - Errorcodes given by handler functions - - opt_sum_query() assumes these codes are > 1 - Do not add error numbers before HA_ERR_FIRST. - If necessary to add lower numbers, change HA_ERR_FIRST accordingly. -*/ -#define HA_ERR_FIRST 120 /* Copy of first error nr.*/ - -#define HA_ERR_KEY_NOT_FOUND 120 /* Didn't find key on read or update */ -#define HA_ERR_FOUND_DUPP_KEY 121 /* Dupplicate key on write */ -#define HA_ERR_INTERNAL_ERROR 122 /* Internal error */ -#define HA_ERR_RECORD_CHANGED 123 /* Uppdate with is recoverable */ -#define HA_ERR_WRONG_INDEX 124 /* Wrong index given to function */ -#define HA_ERR_CRASHED 126 /* Indexfile is crashed */ -#define HA_ERR_WRONG_IN_RECORD 127 /* Record-file is crashed */ -#define HA_ERR_OUT_OF_MEM 128 /* Out of memory */ -#define HA_ERR_NOT_A_TABLE 130 /* not a MYI file - no signature */ -#define HA_ERR_WRONG_COMMAND 131 /* Command not supported */ -#define HA_ERR_OLD_FILE 132 /* old databasfile */ -#define HA_ERR_NO_ACTIVE_RECORD 133 /* No record read in update() */ -#define HA_ERR_RECORD_DELETED 134 /* A record is not there */ -#define HA_ERR_RECORD_FILE_FULL 135 /* No more room in file */ -#define HA_ERR_INDEX_FILE_FULL 136 /* No more room in file */ -#define HA_ERR_END_OF_FILE 137 /* end in next/prev/first/last */ -#define HA_ERR_UNSUPPORTED 138 /* unsupported extension used */ -#define HA_ERR_TO_BIG_ROW 139 /* Too big row */ -#define HA_WRONG_CREATE_OPTION 140 /* Wrong create option */ -#define HA_ERR_FOUND_DUPP_UNIQUE 141 /* Dupplicate unique on write */ -#define HA_ERR_UNKNOWN_CHARSET 142 /* Can't open charset */ -#define HA_ERR_WRONG_MRG_TABLE_DEF 143 /* conflicting tables in MERGE */ -#define HA_ERR_CRASHED_ON_REPAIR 144 /* Last (automatic?) repair failed */ -#define HA_ERR_CRASHED_ON_USAGE 145 /* Table must be repaired */ -#define HA_ERR_LOCK_WAIT_TIMEOUT 146 -#define HA_ERR_LOCK_TABLE_FULL 147 -#define HA_ERR_READ_ONLY_TRANSACTION 148 /* Updates not allowed */ -#define HA_ERR_LOCK_DEADLOCK 149 -#define HA_ERR_CANNOT_ADD_FOREIGN 150 /* Cannot add a foreign key constr. */ -#define HA_ERR_NO_REFERENCED_ROW 151 /* Cannot add a child row */ -#define HA_ERR_ROW_IS_REFERENCED 152 /* Cannot delete a parent row */ -#define HA_ERR_NO_SAVEPOINT 153 /* No savepoint with that name */ -#define HA_ERR_NON_UNIQUE_BLOCK_SIZE 154 /* Non unique key block size */ -#define HA_ERR_NO_SUCH_TABLE 155 /* The table does not exist in engine */ -#define HA_ERR_TABLE_EXIST 156 /* The table existed in storage engine */ -#define HA_ERR_NO_CONNECTION 157 /* Could not connect to storage engine */ -/* NULLs are not supported in spatial index */ -#define HA_ERR_NULL_IN_SPATIAL 158 -#define HA_ERR_TABLE_DEF_CHANGED 159 /* The table changed in storage engine */ -/* There's no partition in table for given value */ -#define HA_ERR_NO_PARTITION_FOUND 160 -#define HA_ERR_RBR_LOGGING_FAILED 161 /* Row-based binlogging of row failed */ -#define HA_ERR_DROP_INDEX_FK 162 /* Index needed in foreign key constr */ -/* - Upholding foreign key constraints would lead to a duplicate key error - in some other table. -*/ -#define HA_ERR_FOREIGN_DUPLICATE_KEY 163 -/* The table changed in storage engine */ -#define HA_ERR_TABLE_NEEDS_UPGRADE 164 -#define HA_ERR_TABLE_READONLY 165 /* The table is not writable */ - -#define HA_ERR_AUTOINC_READ_FAILED 166 /* Failed to get next autoinc value */ -#define HA_ERR_AUTOINC_ERANGE 167 /* Failed to set row autoinc value */ -#define HA_ERR_GENERIC 168 /* Generic error */ -/* row not actually updated: new values same as the old values */ -#define HA_ERR_RECORD_IS_THE_SAME 169 -#define HA_ERR_LOGGING_IMPOSSIBLE 170 /* It is not possible to log this - statement */ -#define HA_ERR_CORRUPT_EVENT 171 /* The event was corrupt, leading to - illegal data being read */ -#define HA_ERR_NEW_FILE 172 /* New file format */ -#define HA_ERR_ROWS_EVENT_APPLY 173 /* The event could not be processed - no other hanlder error happened */ -#define HA_ERR_INITIALIZATION 174 /* Error during initialization */ -#define HA_ERR_FILE_TOO_SHORT 175 /* File too short */ -#define HA_ERR_WRONG_CRC 176 /* Wrong CRC on page */ -#define HA_ERR_TOO_MANY_CONCURRENT_TRXS 177 /*Too many active concurrent transactions */ -/* There's no explicitly listed partition in table for the given value */ -#define HA_ERR_NOT_IN_LOCK_PARTITIONS 178 -#define HA_ERR_INDEX_COL_TOO_LONG 179 /* Index column length exceeds limit */ -#define HA_ERR_INDEX_CORRUPT 180 /* Index corrupted */ -#define HA_ERR_UNDO_REC_TOO_BIG 181 /* Undo log record too big */ -#define HA_FTS_INVALID_DOCID 182 /* Invalid InnoDB Doc ID */ -#define HA_ERR_TABLE_IN_FK_CHECK 183 /* Table being used in foreign key check */ -#define HA_ERR_TABLESPACE_EXISTS 184 /* The tablespace existed in storage engine */ -#define HA_ERR_TOO_MANY_FIELDS 185 /* Table has too many columns */ -#define HA_ERR_ROW_IN_WRONG_PARTITION 186 /* Row in wrong partition */ -#define HA_ERR_ROW_NOT_VISIBLE 187 -#define HA_ERR_ABORTED_BY_USER 188 -#define HA_ERR_DISK_FULL 189 -#define HA_ERR_INCOMPATIBLE_DEFINITION 190 -#define HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE 191 /* Too many words in a phrase */ -#define HA_ERR_DECRYPTION_FAILED 192 /* Table encrypted but decypt failed */ -#define HA_ERR_FK_DEPTH_EXCEEDED 193 /* FK cascade depth exceeded */ -#define HA_ERR_TABLESPACE_MISSING 194 /* Missing Tablespace */ -#define HA_ERR_SEQUENCE_INVALID_DATA 195 -#define HA_ERR_SEQUENCE_RUN_OUT 196 -#define HA_ERR_LAST 196 /* Copy of last error nr * */ - -/* Number of different errors */ -#define HA_ERR_ERRORS (HA_ERR_LAST - HA_ERR_FIRST + 1) - -/* aliases */ -#define HA_ERR_TABLE_CORRUPT HA_ERR_WRONG_IN_RECORD -#define HA_ERR_QUERY_INTERRUPTED HA_ERR_ABORTED_BY_USER -#define HA_ERR_NOT_ALLOWED_COMMAND HA_ERR_WRONG_COMMAND - - /* Other constants */ - -#define HA_NAMELEN 64 /* Max length of saved filename */ -#define NO_SUCH_KEY (~(uint)0) /* used as a key no. */ - -typedef ulong key_part_map; -#define HA_WHOLE_KEY (~(key_part_map)0) - - /* Intern constants in databases */ - - /* bits in _search */ -#define SEARCH_FIND 1U -#define SEARCH_NO_FIND 2U -#define SEARCH_SAME 4U -#define SEARCH_BIGGER 8U -#define SEARCH_SMALLER 16U -#define SEARCH_SAVE_BUFF 32U -#define SEARCH_UPDATE 64U -#define SEARCH_PREFIX 128U -#define SEARCH_LAST 256U -#define MBR_CONTAIN 512U -#define MBR_INTERSECT 1024U -#define MBR_WITHIN 2048U -#define MBR_DISJOINT 4096U -#define MBR_EQUAL 8192U -#define MBR_DATA 16384U -#define SEARCH_NULL_ARE_EQUAL 32768U /* NULL in keys are equal */ -#define SEARCH_NULL_ARE_NOT_EQUAL 65536U/* NULL in keys are not equal */ -/* Use this when inserting a key in position order */ -#define SEARCH_INSERT (SEARCH_NULL_ARE_NOT_EQUAL*2) -/* Only part of the key is specified while reading */ -#define SEARCH_PART_KEY (SEARCH_INSERT*2) -/* Used when user key (key 2) contains transaction id's */ -#define SEARCH_USER_KEY_HAS_TRANSID (SEARCH_PART_KEY*2) -/* Used when page key (key 1) contains transaction id's */ -#define SEARCH_PAGE_KEY_HAS_TRANSID (SEARCH_USER_KEY_HAS_TRANSID*2) - - /* bits in opt_flag */ -#define QUICK_USED 1U -#define READ_CACHE_USED 2U -#define READ_CHECK_USED 4U -#define KEY_READ_USED 8U -#define WRITE_CACHE_USED 16U -#define OPT_NO_ROWS 32U - - /* bits in update */ -#define HA_STATE_CHANGED 1U /* Database has changed */ -#define HA_STATE_AKTIV 2U /* Has a current record */ -#define HA_STATE_WRITTEN 4U /* Record is written */ -#define HA_STATE_DELETED 8U -#define HA_STATE_NEXT_FOUND 16U /* Next found record (record before) */ -#define HA_STATE_PREV_FOUND 32U /* Prev found record (record after) */ -#define HA_STATE_NO_KEY 64U /* Last read didn't find record */ -#define HA_STATE_KEY_CHANGED 128U -#define HA_STATE_WRITE_AT_END 256U /* set in _ps_find_writepos */ -#define HA_STATE_BUFF_SAVED 512U /* If current keybuff is info->buff */ -#define HA_STATE_ROW_CHANGED 1024U /* To invalidate ROW cache */ -#define HA_STATE_EXTEND_BLOCK 2048U -#define HA_STATE_RNEXT_SAME 4096U /* rnext_same occupied lastkey2 */ - -/* myisampack expects no more than 32 field types. */ -enum en_fieldtype { - FIELD_LAST=-1,FIELD_NORMAL,FIELD_SKIP_ENDSPACE,FIELD_SKIP_PRESPACE, - FIELD_SKIP_ZERO,FIELD_BLOB,FIELD_CONSTANT,FIELD_INTERVALL,FIELD_ZERO, - FIELD_VARCHAR,FIELD_CHECK, - FIELD_enum_val_count -}; - -enum data_file_type { - STATIC_RECORD, DYNAMIC_RECORD, COMPRESSED_RECORD, BLOCK_RECORD, NO_RECORD -}; - -/* For key ranges */ - -#define NO_MIN_RANGE 1U -#define NO_MAX_RANGE 2U -#define NEAR_MIN 4U -#define NEAR_MAX 8U -#define UNIQUE_RANGE 16U -#define EQ_RANGE 32U -#define NULL_RANGE 64U -#define GEOM_FLAG 128U - -typedef struct st_key_range -{ - const uchar *key; - uint length; - key_part_map keypart_map; - enum ha_rkey_function flag; -} key_range; - -typedef void *range_id_t; - -typedef struct st_key_multi_range -{ - key_range start_key; - key_range end_key; - range_id_t ptr; /* Free to use by caller (ptr to row etc) */ - /* - A set of range flags that describe both endpoints: UNIQUE_RANGE, - NULL_RANGE, EQ_RANGE, GEOM_FLAG. - (Flags that describe one endpoint, NO_{MIN|MAX}_RANGE, NEAR_{MIN|MAX} will - not be set here) - */ - uint range_flag; -} KEY_MULTI_RANGE; - - -/* Store first and last leaf page accessed by records_in_range */ - -typedef struct st_page_range -{ - ulonglong first_page; - ulonglong last_page; -} page_range; - -#define UNUSED_PAGE_NO ULONGLONG_MAX -#define unused_page_range { UNUSED_PAGE_NO, UNUSED_PAGE_NO } - -/* For number of records */ -#ifdef BIG_TABLES -#define rows2double(A) ulonglong2double(A) -typedef my_off_t ha_rows; -#else -#define rows2double(A) (double) (A) -typedef ulong ha_rows; -#endif - -#define HA_POS_ERROR (~ (ha_rows) 0) -#define HA_OFFSET_ERROR (~ (my_off_t) 0) -#define HA_ROWS_MAX HA_POS_ERROR - -#if SIZEOF_OFF_T == 4 -#define MAX_FILE_SIZE INT_MAX32 -#else -#define MAX_FILE_SIZE LONGLONG_MAX -#endif - -#define HA_VARCHAR_PACKLENGTH(field_length) ((field_length) < 256 ? 1 :2) - -/* invalidator function reference for Query Cache */ -C_MODE_START -typedef void (* invalidator_by_filename)(const char * filename); -C_MODE_END - -#endif /* _my_base_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_bit.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_bit.h deleted file mode 100644 index 8ee8b41..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_bit.h +++ /dev/null @@ -1,219 +0,0 @@ -/* Copyright (c) 2007, 2011, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MY_BIT_INCLUDED -#define MY_BIT_INCLUDED - -/* - Some useful bit functions -*/ - -C_MODE_START - -extern const uchar _my_bits_reverse_table[256]; - - -/* - my_bit_log2_xxx() - - In the given value, find the highest bit set, - which is the smallest X that satisfies the condition: (2^X >= value). - Can be used as a reverse operation for (1<> 4)) + 4: - my_bit_log2_hex_digit(value); -} -static inline CONSTEXPR uint my_bit_log2_uint16(uint16 value) -{ - return value & 0xFF00 ? my_bit_log2_uint8((uint8) (value >> 8)) + 8 : - my_bit_log2_uint8((uint8) value); -} -static inline CONSTEXPR uint my_bit_log2_uint32(uint32 value) -{ - return value & 0xFFFF0000UL ? - my_bit_log2_uint16((uint16) (value >> 16)) + 16 : - my_bit_log2_uint16((uint16) value); -} -static inline CONSTEXPR uint my_bit_log2_uint64(ulonglong value) -{ - return value & 0xFFFFFFFF00000000ULL ? - my_bit_log2_uint32((uint32) (value >> 32)) + 32 : - my_bit_log2_uint32((uint32) value); -} -static inline CONSTEXPR uint my_bit_log2_size_t(size_t value) -{ -#ifdef __cplusplus - static_assert(sizeof(size_t) <= sizeof(ulonglong), - "size_t <= ulonglong is an assumption that needs to be fixed " - "for this architecture. Please create an issue on " - "https://jira.mariadb.org"); -#endif - return my_bit_log2_uint64((ulonglong) value); -} - - -/* -Count bits in 32bit integer - - Algorithm by Sean Anderson, according to: - http://graphics.stanford.edu/~seander/bithacks.html - under "Counting bits set, in parallel" - - (Original code public domain). -*/ -static inline uint my_count_bits_uint32(uint32 v) -{ - v = v - ((v >> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >> 2) & 0x33333333); - return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; -} - - -static inline uint my_count_bits(ulonglong x) -{ - return my_count_bits_uint32((uint32)x) + my_count_bits_uint32((uint32)(x >> 32)); -} - - - - -/* - Next highest power of two - - SYNOPSIS - my_round_up_to_next_power() - v Value to check - - RETURN - Next or equal power of 2 - Note: 0 will return 0 - - NOTES - Algorithm by Sean Anderson, according to: - http://graphics.stanford.edu/~seander/bithacks.html - (Original code public domain) - - Comments shows how this works with 01100000000000000000000000001011 -*/ - -static inline uint32 my_round_up_to_next_power(uint32 v) -{ - v--; /* 01100000000000000000000000001010 */ - v|= v >> 1; /* 01110000000000000000000000001111 */ - v|= v >> 2; /* 01111100000000000000000000001111 */ - v|= v >> 4; /* 01111111110000000000000000001111 */ - v|= v >> 8; /* 01111111111111111100000000001111 */ - v|= v >> 16; /* 01111111111111111111111111111111 */ - return v+1; /* 10000000000000000000000000000000 */ -} - -static inline uint32 my_clear_highest_bit(uint32 v) -{ - uint32 w=v >> 1; - w|= w >> 1; - w|= w >> 2; - w|= w >> 4; - w|= w >> 8; - w|= w >> 16; - return v & w; -} - -static inline uint32 my_reverse_bits(uint32 key) -{ - return - ((uint32)_my_bits_reverse_table[ key & 255] << 24) | - ((uint32)_my_bits_reverse_table[(key>> 8) & 255] << 16) | - ((uint32)_my_bits_reverse_table[(key>>16) & 255] << 8) | - (uint32)_my_bits_reverse_table[(key>>24) ]; -} - -/* - a number with the n lowest bits set - an overflow-safe version of (1 << n) - 1 -*/ -static inline uint64 my_set_bits(int n) -{ - return (((1ULL << (n - 1)) - 1) << 1) | 1; -} - -/* Create a mask of the significant bits for the last byte (1,3,7,..255) */ -static inline uchar last_byte_mask(uint bits) -{ - /* Get the number of used bits-1 (0..7) in the last byte */ - unsigned int const used = (bits - 1U) & 7U; - /* Return bitmask for the significant bits */ - return (uchar) ((2U << used) - 1); -} - -#ifdef _MSC_VER -#include -#endif - -/* - Find the position of the first(least significant) bit set in - the argument. Returns 64 if the argument was 0. -*/ -static inline uint my_find_first_bit(ulonglong n) -{ - if(!n) - return 64; -#if defined(__GNUC__) - return __builtin_ctzll(n); -#elif defined(_MSC_VER) -#if defined(_M_IX86) - unsigned long bit; - if( _BitScanForward(&bit, (uint)n)) - return bit; - _BitScanForward(&bit, (uint)(n>>32)); - return bit + 32; -#else - unsigned long bit; - _BitScanForward64(&bit, n); - return bit; -#endif -#else - /* Generic case */ - uint shift= 0; - static const uchar last_bit[16] = { 32, 0, 1, 0, - 2, 0, 1, 0, - 3, 0, 1, 0, - 2, 0, 1, 0}; - uint bit; - while ((bit = last_bit[(n >> shift) & 0xF]) == 32) - shift+= 4; - return shift+bit; -#endif -} -C_MODE_END - -#endif /* MY_BIT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_bitmap.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_bitmap.h deleted file mode 100644 index f192544..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_bitmap.h +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright (c) 2001, 2011, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_bitmap_h_ -#define _my_bitmap_h_ - -#define MY_BIT_NONE (~(uint) 0) - -#include -#include - -typedef uint32 my_bitmap_map; - -typedef struct st_bitmap -{ - my_bitmap_map *bitmap; - my_bitmap_map *last_word_ptr; - /* - mutex will be acquired for the duration of each bitmap operation if - thread_safe flag in bitmap_init was set. Otherwise, we optimize by not - acquiring the mutex - */ - mysql_mutex_t *mutex; - my_bitmap_map last_word_mask; - uint32 n_bits; /* number of bits occupied by the above */ -} MY_BITMAP; - -#ifdef __cplusplus -extern "C" { -#endif - -/* compatibility functions */ -#define bitmap_init(A,B,C,D) my_bitmap_init(A,B,C,D) -#define bitmap_free(A) my_bitmap_free(A) -/* Reset memory. Faster then doing a full bzero */ -#define my_bitmap_clear(A) ((A)->bitmap= 0) - -extern void create_last_word_mask(MY_BITMAP *map); -extern my_bool my_bitmap_init(MY_BITMAP *map, my_bitmap_map *buf, uint n_bits, - my_bool thread_safe); -extern my_bool bitmap_is_clear_all(const MY_BITMAP *map); -extern my_bool bitmap_is_prefix(const MY_BITMAP *map, uint prefix_size); -extern my_bool bitmap_is_set_all(const MY_BITMAP *map); -extern my_bool bitmap_is_subset(const MY_BITMAP *map1, const MY_BITMAP *map2); -extern my_bool bitmap_is_overlapping(const MY_BITMAP *map1, - const MY_BITMAP *map2); -extern my_bool bitmap_test_and_set(MY_BITMAP *map, uint bitmap_bit); -extern my_bool bitmap_test_and_clear(MY_BITMAP *map, uint bitmap_bit); -extern my_bool bitmap_fast_test_and_set(MY_BITMAP *map, uint bitmap_bit); -extern my_bool bitmap_fast_test_and_clear(MY_BITMAP *map, uint bitmap_bit); -extern my_bool bitmap_union_is_set_all(const MY_BITMAP *map1, - const MY_BITMAP *map2); -extern my_bool bitmap_exists_intersection(const MY_BITMAP **bitmap_array, - uint bitmap_count, - uint start_bit, uint end_bit); - -extern uint bitmap_set_next(MY_BITMAP *map); -extern uint bitmap_get_first(const MY_BITMAP *map); -extern uint bitmap_get_first_set(const MY_BITMAP *map); -extern uint bitmap_bits_set(const MY_BITMAP *map); -extern uint bitmap_get_next_set(const MY_BITMAP *map, uint bitmap_bit); -extern void my_bitmap_free(MY_BITMAP *map); -extern void bitmap_set_above(MY_BITMAP *map, uint from_byte, uint use_bit); -extern void bitmap_set_prefix(MY_BITMAP *map, uint prefix_size); -extern void bitmap_intersect(MY_BITMAP *map, const MY_BITMAP *map2); -extern void bitmap_subtract(MY_BITMAP *map, const MY_BITMAP *map2); -extern void bitmap_union(MY_BITMAP *map, const MY_BITMAP *map2); -extern void bitmap_xor(MY_BITMAP *map, const MY_BITMAP *map2); -extern void bitmap_invert(MY_BITMAP *map); -extern void bitmap_copy(MY_BITMAP *map, const MY_BITMAP *map2); - -extern uint bitmap_lock_set_next(MY_BITMAP *map); -extern void bitmap_lock_clear_bit(MY_BITMAP *map, uint bitmap_bit); -/* Fast, not thread safe, bitmap functions */ -#define bitmap_buffer_size(bits) (((bits)+31)/32)*4 -#define no_bytes_in_map(map) (((map)->n_bits + 7)/8) -#define no_words_in_map(map) (((map)->n_bits + 31)/32) -#define bytes_word_aligned(bytes) (4*((bytes + 3)/4)) -/* The following functions must be compatible with create_last_word_mask()! */ -static inline void -bitmap_set_bit(MY_BITMAP *map,uint bit) -{ - uchar *b= (uchar*) map->bitmap + bit / 8; - DBUG_ASSERT(bit < map->n_bits); - *b= (uchar) (*b | 1U << (bit & 7)); -} -static inline void -bitmap_flip_bit(MY_BITMAP *map,uint bit) -{ - uchar *b= (uchar*) map->bitmap + bit / 8; - DBUG_ASSERT(bit < map->n_bits); - *b= (uchar) (*b ^ 1U << (bit & 7)); -} -static inline void -bitmap_clear_bit(MY_BITMAP *map,uint bit) -{ - uchar *b= (uchar*) map->bitmap + bit / 8; - DBUG_ASSERT(bit < map->n_bits); - *b= (uchar) (*b & ~(1U << (bit & 7))); -} -static inline uint -bitmap_is_set(const MY_BITMAP *map,uint bit) -{ - const uchar *b= (const uchar*) map->bitmap + bit / 8; - DBUG_ASSERT(bit < map->n_bits); - return !!(*b & (1U << (bit & 7))); -} - -static inline my_bool bitmap_cmp(const MY_BITMAP *map1, const MY_BITMAP *map2) -{ - if (memcmp(map1->bitmap, map2->bitmap, 4*(no_words_in_map(map1)-1)) != 0) - return FALSE; - return ((*map1->last_word_ptr | map1->last_word_mask) == - (*map2->last_word_ptr | map2->last_word_mask)); -} - -#define bitmap_clear_all(MAP) \ - { memset((MAP)->bitmap, 0, 4*no_words_in_map((MAP))); } -#define bitmap_set_all(MAP) \ - (memset((MAP)->bitmap, 0xFF, 4*no_words_in_map((MAP)))) - -#ifdef __cplusplus -} -#endif - -#endif /* _my_bitmap_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_check_opt.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_check_opt.h deleted file mode 100644 index f5ec522..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_check_opt.h +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; version 2 of the License. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_check_opt_h -#define _my_check_opt_h - -#ifdef __cplusplus -extern "C" { -#endif - -/* - All given definitions needed for MyISAM storage engine: - myisamchk.c or/and ha_myisam.cc or/and micheck.c - Some definitions are needed by the MySQL parser. -*/ - -#define T_AUTO_INC (1UL << 0) -#define T_AUTO_REPAIR (1UL << 1) -#define T_BACKUP_DATA (1UL << 2) -#define T_CALC_CHECKSUM (1UL << 3) -#define T_CHECK (1UL << 4) -#define T_CHECK_ONLY_CHANGED (1UL << 5) -#define T_CREATE_MISSING_KEYS (1UL << 6) -#define T_DESCRIPT (1UL << 7) -#define T_DONT_CHECK_CHECKSUM (1UL << 8) -#define T_EXTEND (1UL << 9) -#define T_FAST (1UL << 10) -#define T_FORCE_CREATE (1UL << 11) -#define T_FORCE_UNIQUENESS (1UL << 12) -#define T_INFO (1UL << 13) -/** CHECK TABLE...MEDIUM (the default) */ -#define T_MEDIUM (1UL << 14) -/** CHECK TABLE...QUICK */ -#define T_QUICK (1UL << 15) -#define T_READONLY (1UL << 16) -#define T_REP (1UL << 17) -#define T_REP_BY_SORT (1UL << 18) -#define T_REP_PARALLEL (1UL << 19) -#define T_RETRY_WITHOUT_QUICK (1UL << 20) -#define T_SAFE_REPAIR (1UL << 21) -#define T_SILENT (1UL << 22) -#define T_SORT_INDEX (1UL << 23) -#define T_SORT_RECORDS (1UL << 24) -#define T_STATISTICS (1UL << 25) -#define T_UNPACK (1UL << 26) -#define T_UPDATE_STATE (1UL << 27) -#define T_VERBOSE (1UL << 28) -#define T_VERY_SILENT (1UL << 29) -#define T_WAIT_FOREVER (1UL << 30) -#define T_WRITE_LOOP (1UL << 31) -#define T_ZEROFILL (1ULL << 32) -#define T_ZEROFILL_KEEP_LSN (1ULL << 33) -/** If repair should not bump create_rename_lsn */ -#define T_NO_CREATE_RENAME_LSN (1ULL << 34) -/** If repair shouldn't do any locks */ -#define T_NO_LOCKS (1ULL << 35) -#define T_CREATE_UNIQUE_BY_SORT (1ULL << 36) -#define T_SUPPRESS_ERR_HANDLING (1ULL << 37) -#define T_FORCE_SORT_MEMORY (1ULL << 38) - -#define T_REP_ANY (T_REP | T_REP_BY_SORT | T_REP_PARALLEL) - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_compare.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_compare.h deleted file mode 100644 index e9c0513..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_compare.h +++ /dev/null @@ -1,159 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. - Copyright (c) 1991, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_compare_h -#define _my_compare_h - -#include "myisampack.h" -#ifdef __cplusplus -extern "C" { -#endif - -#include "m_ctype.h" /* CHARSET_INFO */ - -/* - There is a hard limit for the maximum number of keys as there are only - 8 bits in the index file header for the number of keys in a table. - This means that 0..255 keys can exist for a table. The idea of - HA_MAX_POSSIBLE_KEY is to ensure that one can use myisamchk & tools on - a MyISAM table for which one has more keys than MyISAM is normally - compiled for. If you don't have this, you will get a core dump when - running myisamchk compiled for 128 keys on a table with 255 keys. -*/ - -#define HA_MAX_POSSIBLE_KEY 255 /* For myisamchk */ -/* - The following defines can be increased if necessary. - But beware the dependency of MI_MAX_POSSIBLE_KEY_BUFF and HA_MAX_KEY_LENGTH. -*/ - -#define HA_MAX_KEY_LENGTH 1000 /* Max length in bytes */ -#define HA_MAX_KEY_SEG 32 /* Max segments for key */ - -#define HA_MAX_POSSIBLE_KEY_BUFF (HA_MAX_KEY_LENGTH + 24+ 6+6) -#define HA_MAX_KEY_BUFF (HA_MAX_KEY_LENGTH+HA_MAX_KEY_SEG*6+8+8) - -typedef struct st_HA_KEYSEG /* Key-portion */ -{ - CHARSET_INFO *charset; - uint32 start; /* Start of key in record */ - uint32 null_pos; /* position to NULL indicator */ - uint16 bit_pos; /* Position to bit part */ - uint16 flag; - uint16 length; /* Keylength */ - uint16 language; - uint8 type; /* Type of key (for sort) */ - uint8 null_bit; /* bitmask to test for NULL */ - uint8 bit_start; - uint8 bit_length; /* Length of bit part */ -} HA_KEYSEG; - -#define get_key_length(length,key) \ -{ if (*(const uchar*) (key) != 255) \ - length= (uint) *(const uchar*) ((key)++); \ - else \ - { length= mi_uint2korr((key)+1); (key)+=3; } \ -} - -#define get_key_length_rdonly(length,key) \ -{ if (*(const uchar*) (key) != 255) \ - length= ((uint) *(const uchar*) ((key))); \ - else \ - { length= mi_uint2korr((key)+1); } \ -} - -#define get_key_pack_length(length,length_pack,key) \ -{ if (*(const uchar*) (key) != 255) \ - { length= (uint) *(const uchar*) ((key)++); length_pack= 1; }\ - else \ - { length=mi_uint2korr((key)+1); (key)+= 3; length_pack= 3; } \ -} - -#define store_key_length_inc(key,length) \ -{ if ((length) < 255) \ - { *(key)++= (uchar)(length); } \ - else \ - { *(key)=255; mi_int2store((key)+1,(length)); (key)+=3; } \ -} - -#define size_to_store_key_length(length) ((length) < 255 ? 1 : 3) - -static inline uchar get_rec_bits(const uchar *ptr, uchar ofs, uint len) -{ - uint16 val= ptr[0]; - if (ofs + len > 8) - val|= (uint16)((uint16)(ptr[1]) << 8); - return (uchar) ((val >> ofs) & ((1 << len) - 1)); -} - -static inline void set_rec_bits(uint16 bits, uchar *ptr, uchar ofs, uint len) -{ - ptr[0]= (uchar) ((ptr[0] & ~(((1 << len) - 1) << ofs)) | (bits << ofs)); - if (ofs + len > 8) - ptr[1]= (uchar) ((ptr[1] & ~((1 << (len - 8 + ofs)) - 1)) | - bits >> (8 - ofs)); -} - -#define clr_rec_bits(bit_ptr, bit_ofs, bit_len) \ - set_rec_bits(0, bit_ptr, bit_ofs, bit_len) - -extern int ha_compare_text(CHARSET_INFO *, const uchar *, size_t, - const uchar *, size_t , my_bool); -extern int ha_key_cmp(HA_KEYSEG *keyseg, const uchar *a, - const uchar *b, uint key_length, uint nextflag, - uint *diff_pos); -extern HA_KEYSEG *ha_find_null(HA_KEYSEG *keyseg, const uchar *a); - -/* - Inside an in-memory data record, memory pointers to pieces of the - record (like BLOBs) are stored in their native byte order and in - this amount of bytes. -*/ -#define portable_sizeof_char_ptr 8 -#ifdef __cplusplus -} -#endif - -/** - Return values for pushed index condition or rowid filter check functions. - - 0=CHECK_NEG - The filter is not satisfied. The engine should discard this - index tuple and continue the scan. - 1=CHECK_POS - The filter is statisfied. Current index tuple should be - returned to the SQL layer. - 2=CHECK_OUT_OF_RANGE - the index tuple is outside of the range that we're - scanning. (Example: if we're scanning "t.key BETWEEN 10 AND - 20" and got a "t.key=21" tuple) Tthe engine should stop - scanning and return HA_ERR_END_OF_FILE right away). - 3=CHECK_ABORTED_BY_USER - the engine must stop scanning and should return - HA_ERR_ABORTED_BY_USER right away - -1=CHECK_ERROR - Reserved for internal errors in engines. Should not be - returned by ICP or rowid filter check functions. -*/ - -typedef enum check_result { - CHECK_ERROR=-1, - CHECK_NEG=0, - CHECK_POS=1, - CHECK_OUT_OF_RANGE=2, - CHECK_ABORTED_BY_USER=3 -} check_result_t; - -typedef check_result_t (*index_cond_func_t)(void *param); -typedef check_result_t (*rowid_filter_func_t)(void *param); -typedef int (*rowid_filter_is_active_func_t)(void *param); - -#endif /* _my_compare_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_context.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_context.h deleted file mode 100644 index ea0e349..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_context.h +++ /dev/null @@ -1,232 +0,0 @@ -/* - Copyright 2011 Kristian Nielsen and Monty Program Ab - - This file is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this. If not, see . -*/ - -/* - Simple API for spawning a co-routine, to be used for async libmysqlclient. - - Idea is that by implementing this interface using whatever facilities are - available for given platform, we can use the same code for the generic - libmysqlclient-async code. - - (This particular implementation uses Posix ucontext swapcontext().) -*/ - -#ifdef __WIN__ -#define MY_CONTEXT_USE_WIN32_FIBERS 1 -#elif defined(__GNUC__) && __GNUC__ >= 3 && defined(__x86_64__) && !defined(__ILP32__) -#define MY_CONTEXT_USE_X86_64_GCC_ASM -#elif defined(__GNUC__) && __GNUC__ >= 3 && defined(__i386__) -#define MY_CONTEXT_USE_I386_GCC_ASM -#elif defined(HAVE_UCONTEXT_H) -#define MY_CONTEXT_USE_UCONTEXT -#else -#define MY_CONTEXT_DISABLE -#endif - -#ifdef MY_CONTEXT_USE_WIN32_FIBERS -struct my_context { - void (*user_func)(void *); - void *user_arg; - void *app_fiber; - void *lib_fiber; - int return_value; -#ifndef DBUG_OFF - void *dbug_state; -#endif -}; -#endif - - -#ifdef MY_CONTEXT_USE_UCONTEXT -#include - -struct my_context { - void (*user_func)(void *); - void *user_data; - void *stack; - size_t stack_size; - ucontext_t base_context; - ucontext_t spawned_context; - int active; -#ifdef HAVE_VALGRIND_MEMCHECK_H - unsigned int valgrind_stack_id; -#endif -#ifndef DBUG_OFF - void *dbug_state; -#endif -}; -#endif - - -#ifdef MY_CONTEXT_USE_X86_64_GCC_ASM -#include - -struct my_context { - uint64_t save[9]; - void *stack_top; - void *stack_bot; -#ifdef HAVE_VALGRIND_MEMCHECK_H - unsigned int valgrind_stack_id; -#endif -#ifndef DBUG_OFF - void *dbug_state; -#endif -}; -#endif - - -#ifdef MY_CONTEXT_USE_I386_GCC_ASM -#include - -struct my_context { - uint64_t save[7]; - void *stack_top; - void *stack_bot; -#ifdef HAVE_VALGRIND_MEMCHECK_H - unsigned int valgrind_stack_id; -#endif -#ifndef DBUG_OFF - void *dbug_state; -#endif -}; -#endif - - -#ifdef MY_CONTEXT_DISABLE -struct my_context { - int dummy; -}; -#endif - - -/* - Initialize an asynchroneous context object. - Returns 0 on success, non-zero on failure. -*/ -extern int my_context_init(struct my_context *c, size_t stack_size); - -/* Free an asynchroneous context object, deallocating any resources used. */ -extern void my_context_destroy(struct my_context *c); - -/* - Spawn an asynchroneous context. The context will run the supplied user - function, passing the supplied user data pointer. - - The context must have been initialised with my_context_init() prior to - this call. - - The user function may call my_context_yield(), which will cause this - function to return 1. Then later my_context_continue() may be called, which - will resume the asynchroneous context by returning from the previous - my_context_yield() call. - - When the user function returns, this function returns 0. - - In case of error, -1 is returned. -*/ -extern int my_context_spawn(struct my_context *c, void (*f)(void *), void *d); - -/* - Suspend an asynchroneous context started with my_context_spawn. - - When my_context_yield() is called, execution immediately returns from the - last my_context_spawn() or my_context_continue() call. Then when later - my_context_continue() is called, execution resumes by returning from this - my_context_yield() call. - - Returns 0 if ok, -1 in case of error. -*/ -extern int my_context_yield(struct my_context *c); - -/* - Resume an asynchroneous context. The context was spawned by - my_context_spawn(), and later suspended inside my_context_yield(). - - The asynchroneous context may be repeatedly suspended with - my_context_yield() and resumed with my_context_continue(). - - Each time it is suspended, this function returns 1. When the originally - spawned user function returns, this function returns 0. - - In case of error, -1 is returned. -*/ -extern int my_context_continue(struct my_context *c); - - -struct mysql_async_context { - /* - This is set to the value that should be returned from foo_start() or - foo_cont() when a call is suspended. - */ - unsigned int events_to_wait_for; - /* - It is also set to the event(s) that triggered when a suspended call is - resumed, eg. whether we woke up due to connection completed or timeout - in mysql_real_connect_cont(). - */ - unsigned int events_occurred; - /* - This is set to the result of the whole asynchronous operation when it - completes. It uses a union, as different calls have different return - types. - */ - union { - void *r_ptr; - const void *r_const_ptr; - int r_int; - my_bool r_my_bool; - } ret_result; - /* - The timeout value (in millisecods), for suspended calls that need to wake - up on a timeout (eg. mysql_real_connect_start(). - */ - unsigned int timeout_value; - /* - This flag is set when we are executing inside some asynchronous call - foo_start() or foo_cont(). It is used to decide whether to use the - synchronous or asynchronous version of calls that may block such as - recv(). - - Note that this flag is not set when a call is suspended, eg. after - returning from foo_start() and before re-entering foo_cont(). - */ - my_bool active; - /* - This flag is set when an asynchronous operation is in progress, but - suspended. Ie. it is set when foo_start() or foo_cont() returns because - the operation needs to block, suspending the operation. - - It is used to give an error (rather than crash) if the application - attempts to call some foo_cont() method when no suspended operation foo is - in progress. - */ - my_bool suspended; - /* - If non-NULL, this is a pointer to a callback hook that will be invoked with - the user data argument just before the context is suspended, and just after - it is resumed. - */ - void (*suspend_resume_hook)(my_bool suspend, void *user_data); - void *suspend_resume_hook_user_data; - /* - This is used to save the execution contexts so that we can suspend an - operation and switch back to the application context, to resume the - suspended context later when the application re-invokes us with - foo_cont(). - */ - struct my_context async_context; -}; diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_counter.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_counter.h deleted file mode 100644 index c5cbe29..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_counter.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef MY_COUNTER_H_INCLUDED -#define MY_COUNTER_H_INCLUDED -/* - Copyright (C) 2018 MariaDB Foundation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - - -template class Atomic_counter -{ - std::atomic m_counter; - - Type add(Type i) { return m_counter.fetch_add(i, std::memory_order_relaxed); } - Type sub(Type i) { return m_counter.fetch_sub(i, std::memory_order_relaxed); } - -public: - Atomic_counter(const Atomic_counter &rhs) - { m_counter.store(rhs, std::memory_order_relaxed); } - Atomic_counter(Type val): m_counter(val) {} - Atomic_counter() {} - - Type operator++(int) { return add(1); } - Type operator--(int) { return sub(1); } - - Type operator++() { return add(1) + 1; } - Type operator--() { return sub(1) - 1; } - - Type operator+=(const Type i) { return add(i) + i; } - Type operator-=(const Type i) { return sub(i) - i; } - - operator Type() const { return m_counter.load(std::memory_order_relaxed); } - Type operator=(const Type val) - { m_counter.store(val, std::memory_order_relaxed); return val; } -}; -#endif /* MY_COUNTER_H_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_cpu.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_cpu.h deleted file mode 100644 index e536ff2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_cpu.h +++ /dev/null @@ -1,142 +0,0 @@ -#ifndef MY_CPU_INCLUDED -#define MY_CPU_INCLUDED -/* Copyright (c) 2013, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -/* instructions for specific cpu's */ - -/* - Macros for adjusting thread priority (hardware multi-threading) - The defines are the same ones used by the linux kernel -*/ - -#ifdef _ARCH_PWR8 -#include -/* Very low priority */ -#define HMT_very_low() __ppc_set_ppr_very_low() -/* Low priority */ -#define HMT_low() __ppc_set_ppr_low() -/* Medium low priority */ -#define HMT_medium_low() __ppc_set_ppr_med_low() -/* Medium priority */ -#define HMT_medium() __ppc_set_ppr_med() -/* Medium high priority */ -#define HMT_medium_high() __ppc_set_ppr_med_high() -/* High priority */ -#define HMT_high() asm volatile("or 3,3,3") -#else -#define HMT_very_low() -#define HMT_low() -#define HMT_medium_low() -#define HMT_medium() -#define HMT_medium_high() -#define HMT_high() -#endif - -#if defined __i386__ || defined __x86_64__ || defined _WIN32 -# define HAVE_PAUSE_INSTRUCTION /* added in Intel Pentium 4 */ -#endif - -#ifdef _WIN32 -#elif defined HAVE_PAUSE_INSTRUCTION -#elif defined(_ARCH_PWR8) -#elif defined __GNUC__ && (defined __arm__ || defined __aarch64__) -#else -# include "my_global.h" -# include "my_atomic.h" -#endif - -static inline void MY_RELAX_CPU(void) -{ -#ifdef _WIN32 - /* - In the Win32 API, the x86 PAUSE instruction is executed by calling - the YieldProcessor macro defined in WinNT.h. It is a CPU architecture- - independent way by using YieldProcessor. - */ - YieldProcessor(); -#elif defined HAVE_PAUSE_INSTRUCTION - /* - According to the gcc info page, asm volatile means that the - instruction has important side-effects and must not be removed. - Also asm volatile may trigger a memory barrier (spilling all registers - to memory). - */ -#ifdef __SUNPRO_CC - asm ("pause" ); -#else - __asm__ __volatile__ ("pause"); -#endif -#elif defined(_ARCH_PWR8) - __ppc_get_timebase(); -#elif defined __GNUC__ && (defined __arm__ || defined __aarch64__) - /* Mainly, prevent the compiler from optimizing away delay loops */ - __asm__ __volatile__ ("":::"memory"); -#else - int32 var, oldval = 0; - my_atomic_cas32_strong_explicit(&var, &oldval, 1, MY_MEMORY_ORDER_RELAXED, - MY_MEMORY_ORDER_RELAXED); -#endif -} - - -#ifdef HAVE_PAUSE_INSTRUCTION -# ifdef __cplusplus -extern "C" { -# endif -extern unsigned my_cpu_relax_multiplier; -void my_cpu_init(void); -# ifdef __cplusplus -} -# endif -#else -# define my_cpu_relax_multiplier 200 -# define my_cpu_init() /* nothing */ -#endif - -/* - LF_BACKOFF should be used to improve performance on hyperthreaded CPUs. Intel - recommends to use it in spin loops also on non-HT machines to reduce power - consumption (see e.g http://softwarecommunity.intel.com/articles/eng/2004.htm) - - Running benchmarks for spinlocks implemented with InterlockedCompareExchange - and YieldProcessor shows that much better performance is achieved by calling - YieldProcessor in a loop - that is, yielding longer. On Intel boxes setting - loop count in the range 200-300 brought best results. -*/ - -static inline int LF_BACKOFF(void) -{ - unsigned i= my_cpu_relax_multiplier; - while (i--) - MY_RELAX_CPU(); - return 1; -} - -/** - Run a delay loop while waiting for a shared resource to be released. - @param delay originally, roughly microseconds on 100 MHz Intel Pentium -*/ -static inline void ut_delay(unsigned delay) -{ - unsigned i= my_cpu_relax_multiplier / 4 * delay; - HMT_low(); - while (i--) - MY_RELAX_CPU(); - HMT_medium(); -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_crypt.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_crypt.h deleted file mode 100644 index eced2cd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_crypt.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright (c) 2014 Google Inc. - Copyright (c) 2014, 2015 MariaDB Corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MY_CRYPT_INCLUDED -#define MY_CRYPT_INCLUDED - -#include /* HAVE_EncryptAes128{Ctr,Gcm} */ -#include - -#endif /* MY_CRYPT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_decimal.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_decimal.h deleted file mode 100644 index 4c1f414..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_decimal.h +++ /dev/null @@ -1,538 +0,0 @@ -/* Copyright (c) 2005, 2013, Oracle and/or its affiliates. - Copyright (c) 2011, 2014, SkySQL Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - It is interface module to fixed precision decimals library. - - Most functions use 'uint mask' as parameter, if during operation error - which fit in this mask is detected then it will be processed automatically - here. (errors are E_DEC_* constants, see include/decimal.h) - - Most function are just inline wrappers around library calls -*/ - -#ifndef my_decimal_h -#define my_decimal_h - -#include "sql_basic_types.h" - -#if defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) -#include "sql_string.h" /* String */ -#endif - -C_MODE_START -#include -#include -C_MODE_END - -class String; -class Field; -typedef struct st_mysql_time MYSQL_TIME; - -/** - maximum size of packet length. -*/ -#define DECIMAL_MAX_FIELD_SIZE DECIMAL_MAX_PRECISION - - -inline uint my_decimal_size(uint precision, uint scale) -{ - /* - Always allocate more space to allow library to put decimal point - where it want - */ - return decimal_size(precision, scale) + 1; -} - - -inline int my_decimal_int_part(uint precision, uint decimals) -{ - return precision - ((decimals == DECIMAL_NOT_SPECIFIED) ? 0 : decimals); -} - - -#ifndef MYSQL_CLIENT -int decimal_operation_results(int result, const char *value, const char *type); -#else -inline int decimal_operation_results(int result, const char *value, - const char *type) -{ - return result; -} -#endif /*MYSQL_CLIENT*/ - - -inline int check_result(uint mask, int result) -{ - if (result & mask) - decimal_operation_results(result, "", "DECIMAL"); - return result; -} - - -/** - my_decimal class limits 'decimal_t' type to what we need in MySQL. - - It contains internally all necessary space needed by the instance so - no extra memory is needed. One should call fix_buffer_pointer() function - when he moves my_decimal objects in memory. -*/ - -class my_decimal :public decimal_t -{ - /* - Several of the routines in strings/decimal.c have had buffer - overrun/underrun problems. These are *not* caught by valgrind. - To catch them, we allocate dummy fields around the buffer, - and test that their values do not change. - */ -#if !defined(DBUG_OFF) - int foo1; -#endif - - decimal_digit_t buffer[DECIMAL_BUFF_LENGTH]; - -#if !defined(DBUG_OFF) - int foo2; - static const int test_value= 123; -#endif - -public: - - my_decimal(const my_decimal &rhs) : decimal_t(rhs) - { - init(); - for (uint i= 0; i < DECIMAL_BUFF_LENGTH; i++) - buffer[i]= rhs.buffer[i]; - } - - my_decimal& operator=(const my_decimal &rhs) - { - if (this == &rhs) - return *this; - decimal_t::operator=(rhs); - for (uint i= 0; i < DECIMAL_BUFF_LENGTH; i++) - buffer[i]= rhs.buffer[i]; - fix_buffer_pointer(); - return *this; - } - - void init() - { -#if !defined(DBUG_OFF) - foo1= test_value; - foo2= test_value; -#endif - len= DECIMAL_BUFF_LENGTH; - buf= buffer; - TRASH_ALLOC(buffer, sizeof(buffer)); - } - - my_decimal() - { - init(); - } - my_decimal(const uchar *bin, int prec, int scale) - { - init(); - check_result(E_DEC_FATAL_ERROR, bin2decimal(bin, this, prec, scale)); - } - my_decimal(Field *field); - ~my_decimal() - { - sanity_check(); - } - - void sanity_check() - { - DBUG_SLOW_ASSERT(foo1 == test_value); - DBUG_SLOW_ASSERT(foo2 == test_value); - } - - void fix_buffer_pointer() { buf= buffer; } - - bool sign() const { return decimal_t::sign; } - void sign(bool s) { decimal_t::sign= s; } - uint precision() const { return intg + frac; } - void set_zero() - { - /* - We need the up-cast here, since my_decimal has sign() member functions, - which conflicts with decimal_t::sign - (and decimal_make_zero is a macro, rather than a funcion). - */ - decimal_make_zero(static_cast(this)); - } - int cmp(const my_decimal *other) const - { - return decimal_cmp(this, other); - } - -#ifndef MYSQL_CLIENT - bool to_bool() const - { - return !decimal_is_zero(this); - } - double to_double() const - { - double res; - decimal2double(this, &res); - return res; - } - longlong to_longlong(bool unsigned_flag) const; - /* - Return the value as a signed or unsigned longlong, depending on the sign. - - Positive values are returned as unsigned. - - Negative values are returned as signed. - This is used by bit SQL operators: | & ^ ~ - as well as by the SQL function BIT_COUNT(). - */ - longlong to_xlonglong() const - { return to_longlong(!sign()); } - - // Convert to string returning decimal2string() error code - int to_string_native(String *to, uint prec, uint dec, char filler, - uint mask= E_DEC_FATAL_ERROR) const; - // Convert to string returning the String pointer - String *to_string(String *to, uint prec, uint dec, char filler) const - { - return to_string_native(to, prec, dec, filler) ? NULL : to; - } - String *to_string(String *to) const - { - return to_string(to, 0, 0, 0); - } - String *to_string_round(String *to, int scale, my_decimal *round_buff) const - { - (void) round_to(round_buff, scale, HALF_UP); // QQ: check result? - return round_buff->to_string(to); - } - int round_to(my_decimal *to, int scale, decimal_round_mode mode, - int mask= E_DEC_FATAL_ERROR) const - { - return check_result(mask, decimal_round(this, to, scale, mode)); - } - int to_binary(uchar *bin, int prec, int scale, - uint mask= E_DEC_FATAL_ERROR) const; -#endif - /** Swap two my_decimal values */ - void swap(my_decimal &rhs) - { - swap_variables(my_decimal, *this, rhs); - } -}; - - -#ifndef DBUG_OFF -void print_decimal(const my_decimal *dec); -void print_decimal_buff(const my_decimal *dec, const uchar* ptr, int length); -const char *dbug_decimal_as_string(char *buff, const my_decimal *val); -#else -#define dbug_decimal_as_string(A) NULL -#endif - -bool str_set_decimal(uint mask, const my_decimal *val, uint fixed_prec, - uint fixed_dec, char filler, String *str, - CHARSET_INFO *cs); - -extern my_decimal decimal_zero; - -inline -void max_my_decimal(my_decimal *to, int precision, int frac) -{ - DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION)&& - (frac <= DECIMAL_MAX_SCALE)); - max_decimal(precision, frac, to); -} - -inline void max_internal_decimal(my_decimal *to) -{ - max_my_decimal(to, DECIMAL_MAX_PRECISION, 0); -} - -inline int check_result_and_overflow(uint mask, int result, my_decimal *val) -{ - if (check_result(mask, result) & E_DEC_OVERFLOW) - { - bool sign= val->sign(); - val->fix_buffer_pointer(); - max_internal_decimal(val); - val->sign(sign); - } - return result; -} - -inline uint my_decimal_length_to_precision(uint length, uint scale, - bool unsigned_flag) -{ - /* Precision can't be negative thus ignore unsigned_flag when length is 0. */ - DBUG_ASSERT(length || !scale); - return (uint) (length - (scale>0 ? 1:0) - - (unsigned_flag || !length ? 0:1)); -} - -inline uint32 my_decimal_precision_to_length_no_truncation(uint precision, - uint8 scale, - bool unsigned_flag) -{ - /* - When precision is 0 it means that original length was also 0. Thus - unsigned_flag is ignored in this case. - */ - DBUG_ASSERT(precision || !scale); - return (uint32)(precision + (scale > 0 ? 1 : 0) + - (unsigned_flag || !precision ? 0 : 1)); -} - -inline uint32 my_decimal_precision_to_length(uint precision, uint8 scale, - bool unsigned_flag) -{ - /* - When precision is 0 it means that original length was also 0. Thus - unsigned_flag is ignored in this case. - */ - DBUG_ASSERT(precision || !scale); - set_if_smaller(precision, DECIMAL_MAX_PRECISION); - return my_decimal_precision_to_length_no_truncation(precision, scale, - unsigned_flag); -} - -inline -int my_decimal_string_length(const my_decimal *d) -{ - /* length of string representation including terminating '\0' */ - return decimal_string_size(d); -} - - -inline -int my_decimal_max_length(const my_decimal *d) -{ - /* -1 because we do not count \0 */ - return decimal_string_size(d) - 1; -} - - -inline -int my_decimal_get_binary_size(uint precision, uint scale) -{ - return decimal_bin_size((int)precision, (int)scale); -} - - -inline -void my_decimal2decimal(const my_decimal *from, my_decimal *to) -{ - *to= *from; -} - - -inline -int binary2my_decimal(uint mask, const uchar *bin, my_decimal *d, int prec, - int scale) -{ - return check_result(mask, bin2decimal(bin, d, prec, scale)); -} - - -inline -int my_decimal_set_zero(my_decimal *d) -{ - d->set_zero(); - return 0; -} - - -inline -bool my_decimal_is_zero(const my_decimal *decimal_value) -{ - return decimal_is_zero(decimal_value); -} - - -inline bool str_set_decimal(const my_decimal *val, String *str, - CHARSET_INFO *cs) -{ - return str_set_decimal(E_DEC_FATAL_ERROR, val, 0, 0, 0, str, cs); -} - - -bool my_decimal2seconds(const my_decimal *d, ulonglong *sec, - ulong *microsec, ulong *nanosec); - -my_decimal *seconds2my_decimal(bool sign, ulonglong sec, ulong microsec, - my_decimal *d); - -#define TIME_to_my_decimal(TIME, DECIMAL) \ - seconds2my_decimal((TIME)->neg, TIME_to_ulonglong(TIME), \ - (TIME)->second_part, (DECIMAL)) - -int my_decimal2int(uint mask, const decimal_t *d, bool unsigned_flag, - longlong *l, decimal_round_mode round_type= HALF_UP); - -inline -int my_decimal2double(uint, const decimal_t *d, double *result) -{ - /* No need to call check_result as this will always succeed */ - return decimal2double(d, result); -} - - -inline -int str2my_decimal(uint mask, const char *str, my_decimal *d, char **end) -{ - return check_result_and_overflow(mask, string2decimal(str, d, end), d); -} - - -int str2my_decimal(uint mask, const char *from, size_t length, - CHARSET_INFO *charset, my_decimal *decimal_value, - const char **end); - -inline int str2my_decimal(uint mask, const char *from, size_t length, - CHARSET_INFO *charset, my_decimal *decimal_value) -{ - const char *end; - return str2my_decimal(mask, from, length, charset, decimal_value, &end); -} - -#if defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) -inline -int string2my_decimal(uint mask, const String *str, my_decimal *d) -{ - const char *end; - return str2my_decimal(mask, str->ptr(), str->length(), str->charset(), - d, &end); -} - - -my_decimal *date2my_decimal(const MYSQL_TIME *ltime, my_decimal *dec); - - -#endif /*defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) */ - -inline -int double2my_decimal(uint mask, double val, my_decimal *d) -{ - return check_result_and_overflow(mask, double2decimal(val, d), d); -} - - -inline -int int2my_decimal(uint mask, longlong i, my_bool unsigned_flag, my_decimal *d) -{ - return check_result(mask, (unsigned_flag ? - ulonglong2decimal((ulonglong)i, d) : - longlong2decimal(i, d))); -} - -inline -void decimal2my_decimal(decimal_t *from, my_decimal *to) -{ - DBUG_ASSERT(to->len >= from->len); - to->intg= from->intg; - to->frac= from->frac; - to->sign(from->sign); - memcpy(to->buf, from->buf, to->len*sizeof(decimal_digit_t)); -} - - -inline -void my_decimal_neg(decimal_t *arg) -{ - if (decimal_is_zero(arg)) - { - arg->sign= 0; - return; - } - decimal_neg(arg); -} - - -inline -int my_decimal_add(uint mask, my_decimal *res, const my_decimal *a, - const my_decimal *b) -{ - return check_result_and_overflow(mask, - decimal_add(a, b, res), - res); -} - - -inline -int my_decimal_sub(uint mask, my_decimal *res, const my_decimal *a, - const my_decimal *b) -{ - return check_result_and_overflow(mask, - decimal_sub(a, b, res), - res); -} - - -inline -int my_decimal_mul(uint mask, my_decimal *res, const my_decimal *a, - const my_decimal *b) -{ - return check_result_and_overflow(mask, - decimal_mul(a, b, res), - res); -} - - -inline -int my_decimal_div(uint mask, my_decimal *res, const my_decimal *a, - const my_decimal *b, int div_scale_inc) -{ - return check_result_and_overflow(mask, - decimal_div(a, b, res, div_scale_inc), - res); -} - - -inline -int my_decimal_mod(uint mask, my_decimal *res, const my_decimal *a, - const my_decimal *b) -{ - return check_result_and_overflow(mask, - decimal_mod(a, b, res), - res); -} - -/** - @return - -1 if ab and 0 if a==b -*/ -inline -int my_decimal_cmp(const my_decimal *a, const my_decimal *b) -{ - return decimal_cmp(a, b); -} - - -inline -int my_decimal_intg(const my_decimal *a) -{ - return decimal_intg(a); -} - - -void my_decimal_trim(ulonglong *precision, uint *scale); - - -#endif /*my_decimal_h*/ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_default.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_default.h deleted file mode 100644 index 0f158bb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_default.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright (C) 2013 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Definitions for mysys/my_default.c */ - -#ifndef MY_DEFAULT_INCLUDED -#define MY_DEFAULT_INCLUDED - -C_MODE_START - -extern MYSQL_PLUGIN_IMPORT const char *my_defaults_extra_file; -extern const char *my_defaults_group_suffix; -extern MYSQL_PLUGIN_IMPORT const char *my_defaults_file; -extern my_bool my_defaults_mark_files; - -extern int get_defaults_options(char **argv); -extern int my_load_defaults(const char *conf_file, const char **groups, - int *argc, char ***argv, const char ***); -extern int load_defaults(const char *conf_file, const char **groups, - int *argc, char ***argv); -extern void free_defaults(char **argv); -extern void my_print_default_files(const char *conf_file); -extern void print_defaults(const char *conf_file, const char **groups); - - -/** Simplify load_defaults() common use */ -#define load_defaults_or_exit(A, B, C, D) switch (load_defaults(A, B, C, D)) { \ - case 0: break; \ - case 4: my_end(0); exit(0); \ - default: my_end(0); exit(1); } - -C_MODE_END - -#endif /* MY_DEFAULT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_handler_errors.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_handler_errors.h deleted file mode 100644 index faf7b9f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_handler_errors.h +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef MYSYS_MY_HANDLER_ERRORS_INCLUDED -#define MYSYS_MY_HANDLER_ERRORS_INCLUDED - -/* Copyright (c) 2008, 2013, Oracle and/or its affiliates. - Copyright (c) 2011, 2013, SkySQL Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Errors a handler can give you -*/ - -static const char *handler_error_messages[]= -{ - /* 120 */ - "Didn't find the key on read or update", - "Duplicate key on write or update", - "Internal (unspecified) error in handler", - "Someone has changed the row since it was read (even though the table was locked to prevent it)", - "Wrong index given to a function", - "Undefined handler error 125", - "Index is corrupted", - "Table file is corrupted", - "Out of memory in engine", - "Undefined handler error 129", - /* 130 */ - "Incorrect file format", - "Command not supported by the engine", - "Old database file", - "No record read before update", - "Record was already deleted (or record file crashed)", - "No more room in record file", - "No more room in index file", - "No more records (read after end of file)", - "Unsupported extension used for table", - "Too big row", - /* 140 */ - "Wrong create options", - "Duplicate unique key on write or update", - "Unknown character set used in table", - "Conflicting table definitions in sub-tables of MERGE table", - "Table is crashed and last repair failed", - "Table was marked as crashed and should be repaired", - "Lock timed out; Retry transaction", - "Lock table is full; Restart program with a larger lock table", - "Updates are not allowed under a read only transactions", - "Lock deadlock; Retry transaction", - /* 150 */ - "Foreign key constraint is incorrectly formed", - "Cannot add a child row", - "Cannot delete a parent row", - "No savepoint with that name", - "Non unique key block size", - "The table does not exist in the storage engine", - "The table already existed in the storage engine", - "Could not connect to the storage engine", - "Unexpected null pointer found when using spatial index", - "The table changed in the storage engine", - /* 160 */ - "There's no partition in the table for the given value", - "Row-based binary logging of row failed", - "Index needed in foreign key constraint", - "Upholding foreign key constraints would lead to a duplicate key error in some other table", - "Table needs to be upgraded before it can be used", - "Table is read only", - "Failed to get next auto increment value", - "Failed to set row auto increment value", - "Unknown (generic) error from engine", - "Record was not updated. New values were the same as original values", - /* 170 */ - "It is not possible to log this statement", - "The event was corrupt, leading to illegal data being read", - "The table is of a new format not supported by this version", - "The event could not be processed. No other handler error happened", - "Fatal error during initialization of handler", - "File too short; Expected more data in file", - "Read page with wrong checksum", - "Too many active concurrent transactions", - "Record not matching the given partition set", - "Index column length exceeds limit", - /* 180 */ - "Index corrupted", - "Undo record too big", - "Invalid InnoDB FTS Doc ID", - "Table is being used in foreign key check", - "Tablespace already exists", - "Too many columns", - "Row in wrong partition", - "Row is not visible by the current transaction", - "Operation was interrupted by end user (probably kill command?)", - "Disk full", - /* 190 */ - "Incompatible key or row definition between the MariaDB .frm file and the information in the storage engine. You may have retry or dump and restore the table to fix this", - "Too many words in a FTS phrase or proximity search", - "Table encrypted but decryption failed. This could be because correct encryption management plugin is not loaded, used encryption key is not available or encryption method does not match.", - "Foreign key cascade delete/update exceeds max depth", - "Tablespace is missing for a table", - "Sequence has been run out", - "Sequence values are conflicting" -}; - -#endif /* MYSYS_MY_HANDLER_ERRORS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_json_writer.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_json_writer.h deleted file mode 100644 index bc8002d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_json_writer.h +++ /dev/null @@ -1,692 +0,0 @@ -/* Copyright (C) 2014 SkySQL Ab, MariaDB Corporation Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef JSON_WRITER_INCLUDED -#define JSON_WRITER_INCLUDED -#include "my_base.h" -#include "sql_select.h" -class Opt_trace_stmt; -class Opt_trace_context; -class Json_writer; -struct TABLE_LIST; - - -/* - Single_line_formatting_helper is used by Json_writer to do better formatting - of JSON documents. - - The idea is to catch arrays that can be printed on one line: - - arrayName : [ "boo", 123, 456 ] - - and actually print them on one line. Arrrays that occupy too much space on - the line, or have nested members cannot be printed on one line. - - We hook into JSON printing functions and try to detect the pattern. While - detecting the pattern, we will accumulate "boo", 123, 456 as strings. - - Then, - - either the pattern is broken, and we print the elements out, - - or the pattern lasts till the end of the array, and we print the - array on one line. -*/ - -class Single_line_formatting_helper -{ - enum enum_state - { - INACTIVE, - ADD_MEMBER, - IN_ARRAY, - DISABLED - }; - - /* - This works like a finite automaton. - - state=DISABLED means the helper is disabled - all on_XXX functions will - return false (which means "not handled") and do nothing. - - +->-+ - | v - INACTIVE ---> ADD_MEMBER ---> IN_ARRAY--->-+ - ^ | - +------------------<--------------------+ - - For other states: - INACTIVE - initial state, we have nothing. - ADD_MEMBER - add_member() was called, the buffer has "member_name\0". - IN_ARRAY - start_array() was called. - - - */ - enum enum_state state; - enum { MAX_LINE_LEN= 80 }; - char buffer[80]; - - /* The data in the buffer is located between buffer[0] and buf_ptr */ - char *buf_ptr; - uint line_len; - - Json_writer *owner; -public: - Single_line_formatting_helper() : state(INACTIVE), buf_ptr(buffer) {} - - void init(Json_writer *owner_arg) { owner= owner_arg; } - - bool on_add_member(const char *name, size_t len); - - bool on_start_array(); - bool on_end_array(); - void on_start_object(); - // on_end_object() is not needed. - - bool on_add_str(const char *str, size_t num_bytes); - - void flush_on_one_line(); - void disable_and_flush(); -}; - - -/* - Something that looks like class String, but has an internal limit of - how many bytes one can append to it. - - Bytes that were truncated due to the size limitation are counted. -*/ - -class String_with_limit -{ -public: - - String_with_limit() : size_limit(SIZE_T_MAX), truncated_len(0) - { - str.length(0); - } - - size_t get_truncated_bytes() const { return truncated_len; } - size_t get_size_limit() { return size_limit; } - - void set_size_limit(size_t limit_arg) - { - // Setting size limit to be shorter than length will not have the desired - // effect - DBUG_ASSERT(str.length() < size_limit); - size_limit= limit_arg; - } - - void append(const char *s, size_t size) - { - if (str.length() + size <= size_limit) - { - // Whole string can be added, just do it - str.append(s, size); - } - else - { - // We cannot add the whole string - if (str.length() < size_limit) - { - // But we can still add something - size_t bytes_to_add = size_limit - str.length(); - str.append(s, bytes_to_add); - truncated_len += size - bytes_to_add; - } - else - truncated_len += size; - } - } - - void append(const char *s) - { - append(s, strlen(s)); - } - - void append(char c) - { - if (str.length() + 1 > size_limit) - truncated_len++; - else - str.append(c); - } - - const String *get_string() { return &str; } - size_t length() { return str.length(); } -private: - String str; - - // str must not get longer than this many bytes. - size_t size_limit; - - // How many bytes were truncated from the string - size_t truncated_len; -}; - -/* - A class to write well-formed JSON documents. The documents are also formatted - for human readability. -*/ - -class Json_writer -{ -public: - /* Add a member. We must be in an object. */ - Json_writer& add_member(const char *name); - Json_writer& add_member(const char *name, size_t len); - - /* Add atomic values */ - void add_str(const char* val); - void add_str(const char* val, size_t num_bytes); - void add_str(const String &str); - void add_str(Item *item); - void add_table_name(const JOIN_TAB *tab); - void add_table_name(const TABLE* table); - - void add_ll(longlong val); - void add_ull(ulonglong val); - void add_size(longlong val); - void add_double(double val); - void add_bool(bool val); - void add_null(); - -private: - void add_unquoted_str(const char* val); - void add_unquoted_str(const char* val, size_t len); -public: - /* Start a child object */ - void start_object(); - void start_array(); - - void end_object(); - void end_array(); - - /* - One can set a limit of how large a JSON document should be. - Writes beyond that size will be counted, but will not be collected. - */ - void set_size_limit(size_t mem_size) { output.set_size_limit(mem_size); } - - size_t get_truncated_bytes() { return output.get_truncated_bytes(); } - - Json_writer() : - indent_level(0), document_start(true), element_started(false), - first_child(true) - { - fmt_helper.init(this); - } -private: - // TODO: a stack of (name, bool is_object_or_array) elements. - int indent_level; - enum { INDENT_SIZE = 2 }; - - friend class Single_line_formatting_helper; - friend class Json_writer_nesting_guard; - bool document_start; - bool element_started; - bool first_child; - - Single_line_formatting_helper fmt_helper; - - void append_indent(); - void start_element(); - void start_sub_element(); - -public: - String_with_limit output; -}; - -/* A class to add values to Json_writer_object and Json_writer_array */ -class Json_value_helper -{ - Json_writer* writer; - -public: - void init(Json_writer *my_writer) { writer= my_writer; } - void add_str(const char* val) - { - writer->add_str(val); - } - void add_str(const char* val, size_t length) - { - writer->add_str(val, length); - } - void add_str(const String &str) - { - writer->add_str(str.ptr(), str.length()); - } - void add_str(const LEX_CSTRING &str) - { - writer->add_str(str.str, str.length); - } - void add_str(Item *item) - { - writer->add_str(item); - } - - void add_ll(longlong val) - { - writer->add_ll(val); - } - void add_size(longlong val) - { - writer->add_size(val); - } - void add_double(double val) - { - writer->add_double(val); - } - void add_bool(bool val) - { - writer->add_bool(val); - } - void add_null() - { - writer->add_null(); - } - void add_table_name(const JOIN_TAB *tab) - { - writer->add_table_name(tab); - } - void add_table_name(const TABLE* table) - { - writer->add_table_name(table); - } -}; - -/* A common base for Json_writer_object and Json_writer_array */ -class Json_writer_struct -{ -protected: - Json_writer* my_writer; - Json_value_helper context; - /* - Tells when a json_writer_struct has been closed or not - */ - bool closed; - -public: - explicit Json_writer_struct(THD *thd) - { - my_writer= thd->opt_trace.get_current_json(); - context.init(my_writer); - closed= false; - } - bool trace_started() - { - return my_writer != 0; - } -}; - - -/* - RAII-based class to start/end writing a JSON object into the JSON document - - There is "ignore mode": one can initialize Json_writer_object with a NULL - Json_writer argument, and then all its calls will do nothing. This is used - by optimizer trace which can be enabled or disabled. -*/ - -class Json_writer_object : public Json_writer_struct -{ -private: - void add_member(const char *name) - { - my_writer->add_member(name); - } -public: - explicit Json_writer_object(THD *thd) - : Json_writer_struct(thd) - { - if (unlikely(my_writer)) - my_writer->start_object(); - } - - explicit Json_writer_object(THD* thd, const char *str) - : Json_writer_struct(thd) - { - if (unlikely(my_writer)) - my_writer->add_member(str).start_object(); - } - - ~Json_writer_object() - { - if (my_writer && !closed) - my_writer->end_object(); - closed= TRUE; - } - - Json_writer_object& add(const char *name, bool value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_bool(value); - } - return *this; - } - Json_writer_object& add(const char *name, ulonglong value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_ll(static_cast(value)); - } - return *this; - } - Json_writer_object& add(const char *name, longlong value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_ll(value); - } - return *this; - } - Json_writer_object& add(const char *name, double value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_double(value); - } - return *this; - } - #ifndef _WIN64 - Json_writer_object& add(const char *name, size_t value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_ll(static_cast(value)); - } - return *this; - } - #endif - Json_writer_object& add(const char *name, const char *value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_str(value); - } - return *this; - } - Json_writer_object& add(const char *name, const char *value, size_t num_bytes) - { - add_member(name); - context.add_str(value, num_bytes); - return *this; - } - Json_writer_object& add(const char *name, const LEX_CSTRING &value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_str(value.str, value.length); - } - return *this; - } - Json_writer_object& add(const char *name, Item *value) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_str(value); - } - return *this; - } - Json_writer_object& add_null(const char*name) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member(name); - context.add_null(); - } - return *this; - } - Json_writer_object& add_table_name(const JOIN_TAB *tab) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member("table"); - context.add_table_name(tab); - } - return *this; - } - Json_writer_object& add_table_name(const TABLE *table) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member("table"); - context.add_table_name(table); - } - return *this; - } - Json_writer_object& add_select_number(uint select_number) - { - DBUG_ASSERT(!closed); - if (my_writer) - { - add_member("select_id"); - if (unlikely(select_number >= INT_MAX)) - context.add_str("fake"); - else - context.add_ll(static_cast(select_number)); - } - return *this; - } - void end() - { - DBUG_ASSERT(!closed); - if (unlikely(my_writer)) - my_writer->end_object(); - closed= TRUE; - } -}; - - -/* - RAII-based class to start/end writing a JSON array into the JSON document - - There is "ignore mode": one can initialize Json_writer_array with a NULL - Json_writer argument, and then all its calls will do nothing. This is used - by optimizer trace which can be enabled or disabled. -*/ - -class Json_writer_array : public Json_writer_struct -{ -public: - Json_writer_array(THD *thd): Json_writer_struct(thd) - { - if (unlikely(my_writer)) - my_writer->start_array(); - } - - Json_writer_array(THD *thd, const char *str) : Json_writer_struct(thd) - { - if (unlikely(my_writer)) - my_writer->add_member(str).start_array(); - } - ~Json_writer_array() - { - if (unlikely(my_writer && !closed)) - { - my_writer->end_array(); - closed= TRUE; - } - } - void end() - { - DBUG_ASSERT(!closed); - if (unlikely(my_writer)) - my_writer->end_array(); - closed= TRUE; - } - - Json_writer_array& add(bool value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_bool(value); - return *this; - } - Json_writer_array& add(ulonglong value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_ll(static_cast(value)); - return *this; - } - Json_writer_array& add(longlong value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_ll(value); - return *this; - } - Json_writer_array& add(double value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_double(value); - return *this; - } - #ifndef _WIN64 - Json_writer_array& add(size_t value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_ll(static_cast(value)); - return *this; - } - #endif - Json_writer_array& add(const char *value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_str(value); - return *this; - } - Json_writer_array& add(const char *value, size_t num_bytes) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_str(value, num_bytes); - return *this; - } - Json_writer_array& add(const LEX_CSTRING &value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_str(value.str, value.length); - return *this; - } - Json_writer_array& add(Item *value) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_str(value); - return *this; - } - Json_writer_array& add_null() - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_null(); - return *this; - } - Json_writer_array& add_table_name(const JOIN_TAB *tab) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_table_name(tab); - return *this; - } - Json_writer_array& add_table_name(const TABLE *table) - { - DBUG_ASSERT(!closed); - if (my_writer) - context.add_table_name(table); - return *this; - } -}; - -/* - RAII-based class to disable writing into the JSON document - The tracing is disabled as soon as the object is created. - The destuctor is called as soon as we exit the scope of the object - and the tracing is enabled back. -*/ - -class Json_writer_temp_disable -{ -public: - Json_writer_temp_disable(THD *thd_arg); - ~Json_writer_temp_disable(); - THD *thd; -}; - -/* - RAII-based helper class to detect incorrect use of Json_writer. - - The idea is that a function typically must leave Json_writer at the same - identation level as it was when it was invoked. Leaving it at a different - level typically means we forgot to close an object or an array - - So, here is a way to guard - void foo(Json_writer *writer) - { - Json_writer_nesting_guard(writer); - .. do something with writer - - // at the end of the function, ~Json_writer_nesting_guard() is called - // and it makes sure that the nesting is the same as when the function was - // entered. - } -*/ - -class Json_writer_nesting_guard -{ -#ifdef DBUG_OFF -public: - Json_writer_nesting_guard(Json_writer *) {} -#else - Json_writer* writer; - int indent_level; -public: - Json_writer_nesting_guard(Json_writer *writer_arg) : - writer(writer_arg), - indent_level(writer->indent_level) - {} - - ~Json_writer_nesting_guard() - { - DBUG_ASSERT(indent_level == writer->indent_level); - } -#endif -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_libwrap.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_libwrap.h deleted file mode 100644 index b520080..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_libwrap.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef MY_LIBWRAP_INCLUDED -#define MY_LIBWRAP_INCLUDED - -/* Copyright (c) 2000, 2006 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef HAVE_LIBWRAP -#include -#include -#ifdef NEED_SYS_SYSLOG_H -#include -#endif /* NEED_SYS_SYSLOG_H */ - -extern void my_fromhost(struct request_info *req); -extern int my_hosts_access(struct request_info *req); -extern char *my_eval_client(struct request_info *req); - -#endif /* HAVE_LIBWRAP */ -#endif /* MY_LIBWRAP_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_md5.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_md5.h deleted file mode 100644 index c3919bf..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_md5.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef MY_MD5_INCLUDED -#define MY_MD5_INCLUDED - -/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 2013 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "m_string.h" - -#define MD5_HASH_SIZE 16 /* Hash size in bytes */ - -/* - Wrapper function for MD5 implementation. -*/ -#ifdef __cplusplus -extern "C" { -#endif - -#define compute_md5_hash(A,B,C) my_md5(A,B,C) - -/* - Convert an array of bytes to a hexadecimal representation. - - Used to generate a hexadecimal representation of a message digest. -*/ -static inline void array_to_hex(char *to, const unsigned char *str, uint len) -{ - const unsigned char *str_end= str + len; - for (; str != str_end; ++str) - { - *to++= _dig_vec_lower[((uchar) *str) >> 4]; - *to++= _dig_vec_lower[((uchar) *str) & 0x0F]; - } -} - -#ifdef __cplusplus -} -#endif - -#endif /* MY_MD5_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_nosys.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_nosys.h deleted file mode 100644 index ff13a04..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_nosys.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Header to remove use of my_functions in functions where we need speed and - where calls to posix functions should work -*/ -#ifndef _my_nosys_h -#define _my_nosys_h -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef __MY_NOSYS__ -#define __MY_NOSYS__ - -#ifndef HAVE_STDLIB_H -#include -#endif - -#undef my_read -#undef my_write -#undef my_seek -#define my_read(a,b,c,d) my_quick_read(a,b,c,d) -#define my_write(a,b,c,d) my_quick_write(a,b,c) -extern size_t my_quick_read(File Filedes,uchar *Buffer,size_t Count, - myf myFlags); -extern size_t my_quick_write(File Filedes,const uchar *Buffer,size_t Count); - -#endif /* __MY_NOSYS__ */ - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_rdtsc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_rdtsc.h deleted file mode 100644 index 33d7227..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_rdtsc.h +++ /dev/null @@ -1,236 +0,0 @@ -/* Copyright (c) 2008 MySQL AB, 2009 Sun Microsystems, Inc. - Copyright (c) 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - rdtsc3 -- multi-platform timer code - pgulutzan@mysql.com, 2005-08-29 - modified 2008-11-02 -*/ - -#ifndef MY_RDTSC_H -#define MY_RDTSC_H - -# ifndef __has_builtin -# define __has_builtin(x) 0 /* Compatibility with non-clang compilers */ -# endif -# if __has_builtin(__builtin_readcyclecounter) -# elif defined _WIN32 -# include -# elif defined __i386__ || defined __x86_64__ -# include -# elif defined(__INTEL_COMPILER) && defined(__ia64__) && defined(HAVE_IA64INTRIN_H) -# include -# elif defined(HAVE_SYS_TIMES_H) && defined(HAVE_GETHRTIME) -# include -# endif - -/** - Characteristics of a timer. -*/ -struct my_timer_unit_info -{ - /** Routine used for the timer. */ - ulonglong routine; - /** Overhead of the timer. */ - ulonglong overhead; - /** Frequency of the timer. */ - ulonglong frequency; - /** Resolution of the timer. */ - ulonglong resolution; -}; - -/** - Characteristics of all the supported timers. - @sa my_timer_init(). -*/ -struct my_timer_info -{ - /** Characteristics of the cycle timer. */ - struct my_timer_unit_info cycles; - /** Characteristics of the nanosecond timer. */ - struct my_timer_unit_info nanoseconds; - /** Characteristics of the microsecond timer. */ - struct my_timer_unit_info microseconds; - /** Characteristics of the millisecond timer. */ - struct my_timer_unit_info milliseconds; - /** Characteristics of the tick timer. */ - struct my_timer_unit_info ticks; -}; - -typedef struct my_timer_info MY_TIMER_INFO; - -C_MODE_START - -/** - A cycle timer. - - On clang we use __builtin_readcyclecounter(), except for AARCH64. - On other compilers: - - On IA-32 and AMD64, we use the RDTSC instruction. - On IA-64, we read the ar.itc register. - On SPARC, we read the tick register. - On POWER, we read the Time Base Register (which is not really a cycle count - but a separate counter with less than nanosecond resolution). - On IBM S/390 System z we use the STCK instruction. - On ARM, we probably should use the Generic Timer, but should figure out - how to ensure that it can be accessed. - On AARCH64, we use the generic timer base register. We override clang - implementation for aarch64 as it access a PMU register which is not - guarenteed to be active. - - Sadly, we have nothing for the Digital Alpha, MIPS, Motorola m68k, - HP PA-RISC or other non-mainstream (or obsolete) processors. - - TODO: consider C++11 std::chrono::high_resolution_clock. - - We fall back to gethrtime() where available. - - On the platforms that do not have a CYCLE timer, - "wait" events are initialized to use NANOSECOND instead of CYCLE - during performance_schema initialization (at the server startup). - - Linux performance monitor (see "man perf_event_open") can - provide cycle counter on the platforms that do not have - other kinds of cycle counters. But we don't use it so far. - - ARM notes - --------- - During tests on ARMv7 Debian, perf_even_open() based cycle counter provided - too low frequency with too high overhead: - MariaDB [performance_schema]> SELECT * FROM performance_timers; - +-------------+-----------------+------------------+----------------+ - | TIMER_NAME | TIMER_FREQUENCY | TIMER_RESOLUTION | TIMER_OVERHEAD | - +-------------+-----------------+------------------+----------------+ - | CYCLE | 689368159 | 1 | 970 | - | NANOSECOND | 1000000000 | 1 | 308 | - | MICROSECOND | 1000000 | 1 | 417 | - | MILLISECOND | 1000 | 1000 | 407 | - | TICK | 127 | 1 | 612 | - +-------------+-----------------+------------------+----------------+ - Therefore, it was decided not to use perf_even_open() on ARM - (i.e. go without CYCLE and have "wait" events use NANOSECOND by default). - - @return the current timer value, in cycles. -*/ -static inline ulonglong my_timer_cycles(void) -{ -# if __has_builtin(__builtin_readcyclecounter) && !defined (__aarch64__) - return __builtin_readcyclecounter(); -# elif defined _WIN32 || defined __i386__ || defined __x86_64__ - return __rdtsc(); -# elif defined(__INTEL_COMPILER) && defined(__ia64__) && defined(HAVE_IA64INTRIN_H) - return (ulonglong) __getReg(_IA64_REG_AR_ITC); /* (3116) */ -#elif defined(__GNUC__) && defined(__ia64__) - { - ulonglong result; - __asm __volatile__ ("mov %0=ar.itc" : "=r" (result)); - return result; - } -#elif defined __GNUC__ && defined __powerpc__ - return __builtin_ppc_get_timebase(); -#elif defined(__GNUC__) && defined(__sparcv9) && defined(_LP64) - { - ulonglong result; - __asm __volatile__ ("rd %%tick,%0" : "=r" (result)); - return result; - } -#elif defined(__GNUC__) && defined(__sparc__) && !defined(_LP64) - { - union { - ulonglong wholeresult; - struct { - ulong high; - ulong low; - } splitresult; - } result; - __asm __volatile__ ("rd %%tick,%1; srlx %1,32,%0" : "=r" (result.splitresult.high), "=r" (result.splitresult.low)); - return result.wholeresult; - } -#elif defined(__GNUC__) && defined(__s390__) - /* covers both s390 and s390x */ - { - ulonglong result; - __asm__ __volatile__ ("stck %0" : "=Q" (result) : : "cc"); - return result; - } -#elif defined(__GNUC__) && defined (__aarch64__) - { - ulonglong result; - __asm __volatile("mrs %0, CNTVCT_EL0" : "=&r" (result)); - return result; - } -#elif defined(HAVE_SYS_TIMES_H) && defined(HAVE_GETHRTIME) - /* gethrtime may appear as either cycle or nanosecond counter */ - return (ulonglong) gethrtime(); -#else - return 0; -#endif -} - -/** - A nanosecond timer. - @return the current timer value, in nanoseconds. -*/ -ulonglong my_timer_nanoseconds(void); - -/** - A microseconds timer. - @return the current timer value, in microseconds. -*/ -ulonglong my_timer_microseconds(void); - -/** - A millisecond timer. - @return the current timer value, in milliseconds. -*/ -ulonglong my_timer_milliseconds(void); - -/** - A ticks timer. - @return the current timer value, in ticks. -*/ -ulonglong my_timer_ticks(void); - -/** - Timer initialization function. - @param [out] mti the timer characteristics. -*/ -void my_timer_init(MY_TIMER_INFO *mti); - -C_MODE_END - -#define MY_TIMER_ROUTINE_RDTSC 5 -#define MY_TIMER_ROUTINE_ASM_IA64 6 -#define MY_TIMER_ROUTINE_PPC_GET_TIMEBASE 7 -#define MY_TIMER_ROUTINE_GETHRTIME 9 -#define MY_TIMER_ROUTINE_READ_REAL_TIME 10 -#define MY_TIMER_ROUTINE_CLOCK_GETTIME 11 -#define MY_TIMER_ROUTINE_GETTIMEOFDAY 13 -#define MY_TIMER_ROUTINE_QUERYPERFORMANCECOUNTER 14 -#define MY_TIMER_ROUTINE_GETTICKCOUNT 15 -#define MY_TIMER_ROUTINE_TIME 16 -#define MY_TIMER_ROUTINE_TIMES 17 -#define MY_TIMER_ROUTINE_FTIME 18 -#define MY_TIMER_ROUTINE_ASM_GCC_SPARC64 23 -#define MY_TIMER_ROUTINE_ASM_GCC_SPARC32 24 -#define MY_TIMER_ROUTINE_MACH_ABSOLUTE_TIME 25 -#define MY_TIMER_ROUTINE_GETSYSTEMTIMEASFILETIME 26 -#define MY_TIMER_ROUTINE_ASM_S390 28 -#define MY_TIMER_ROUTINE_AARCH64 29 - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_rnd.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_rnd.h deleted file mode 100644 index a3e3788..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_rnd.h +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (C) 2013 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 or later of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_rnd_h -#define _my_rnd_h - -C_MODE_START - -struct my_rnd_struct { - unsigned long seed1,seed2,max_value; - double max_value_dbl; -}; - -void my_rnd_init(struct my_rnd_struct *rand_st, ulong seed1, ulong seed2); -double my_rnd(struct my_rnd_struct *rand_st); -double my_rnd_ssl(struct my_rnd_struct *rand_st); - -C_MODE_END - -#endif /* _my_rnd_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_service_manager.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_service_manager.h deleted file mode 100644 index 95b5235..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_service_manager.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright (c) 2015 Daniel Black. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA -*/ - - -#ifndef MY_SERVICE_MANAGER_INCLUDED -#define MY_SERVICE_MANAGER_INCLUDED - -#if defined(HAVE_SYSTEMD) && !defined(EMBEDDED_LIBRARY) -/* - sd-daemon.h may include inttypes.h. Explicitly request format macros before - the first inclusion of inttypes.h. -*/ -#if !defined(__STDC_FORMAT_MACROS) -#define __STDC_FORMAT_MACROS -#endif // !defined(__STDC_FORMAT_MACROS) -#include -/** INTERVAL in seconds followed by printf style status */ -#define service_manager_extend_timeout(INTERVAL, FMTSTR, ...) \ - sd_notifyf(0, "STATUS=" FMTSTR "\nEXTEND_TIMEOUT_USEC=%u\n", ##__VA_ARGS__, INTERVAL * 1000000) - -#else -#define sd_notify(X, Y) -#define sd_notifyf(E, F, ...) -#define service_manager_extend_timeout(I, FMTSTR, ...) -#endif - -#endif /* MY_SERVICE_MANAGER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_stack_alloc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_stack_alloc.h deleted file mode 100644 index 95e746d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_stack_alloc.h +++ /dev/null @@ -1,92 +0,0 @@ -/* Copyright 2019 MariaDB corporation AB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -#ifndef _my_stack_alloc_h -#define _my_stack_alloc_h - -/* - Do allocation through alloca if there is enough stack available. - If not, use my_malloc() instead. - - The idea is that to be able to alloc as much as possible through the - stack. To ensure this, we have two different limits, on for big - blocks and one for small blocks. This will enable us to continue to - do allocation for small blocks even when there is less stack space - available. - This is for example used by Aria when traversing the b-tree and the code - needs to allocate one b-tree page and a few keys for each recursion. Even - if there is not space to allocate the b-tree pages on stack we can still - continue to allocate the keys. -*/ - -/* - Default suggested allocations -*/ - -/* Allocate big blocks as long as there is this much left */ -#define STACK_ALLOC_BIG_BLOCK 1024*64 - -/* Allocate small blocks as long as there is this much left */ -#define STACK_ALLOC_SMALL_BLOCK 1024*32 - -/* Allocate small blocks as long as there is this much left */ -#define STACK_ALLOC_SMALL_BLOCK_SIZE 4096 - -/* - Allocate a block on stack or through malloc. - The 'must_be_freed' variable will be set to 1 if malloc was called. - 'must_be_freed' must be a variable on the stack! -*/ - -#ifdef HAVE_ALLOCA -#define alloc_on_stack(stack_end, res, must_be_freed, size) \ -do \ -{ \ - size_t alloc_size= (size); \ - size_t stack_left= available_stack_size(&alloc_size, (stack_end)); \ - if (stack_left > alloc_size && \ - (STACK_ALLOC_BIG_BLOCK < stack_left - alloc_size || \ - ((STACK_ALLOC_SMALL_BLOCK < stack_left - alloc_size) && \ - (STACK_ALLOC_SMALL_BLOCK_SIZE <= alloc_size)))) \ - { \ - (must_be_freed)= 0; \ - (res)= alloca(size); \ - } \ - else \ - { \ - (must_be_freed)= 1; \ - (res)= my_malloc(PSI_INSTRUMENT_ME, size, MYF(MY_THREAD_SPECIFIC | MY_WME)); \ - } \ -} while(0) -#else -#define alloc_on_stack(stack_end, res, must_be_freed, size) \ - do { \ - (must_be_freed)= 1; \ - (res)= my_malloc(PSI_INSTRUMENT_ME, size, MYF(MY_THREAD_SPECIFIC | MY_WME)); \ - } while(0) -#endif /* HAVE_ALLOCA */ - - -/* - Free memory allocated by stack_alloc -*/ - -static inline void stack_alloc_free(void *res, my_bool must_be_freed) -{ - if (must_be_freed) - my_free(res); -} -#endif /* _my_stack_alloc_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_stacktrace.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_stacktrace.h deleted file mode 100644 index 20b86f4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_stacktrace.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright (c) 2001, 2011, Oracle and/or its affiliates. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _my_stacktrace_h_ -#define _my_stacktrace_h_ - -#ifdef TARGET_OS_LINUX -#if defined (__x86_64__) || defined (__i386__) || \ - (defined(__alpha__) && defined(__GNUC__)) -#define HAVE_STACKTRACE 1 -#endif -#elif defined(__WIN__) || defined(HAVE_PRINTSTACK) -#define HAVE_STACKTRACE 1 -#endif - -#if HAVE_BACKTRACE && (HAVE_BACKTRACE_SYMBOLS || HAVE_BACKTRACE_SYMBOLS_FD) -#undef HAVE_STACKTRACE -#define HAVE_STACKTRACE 1 -#endif - -#define HAVE_WRITE_CORE - -#if HAVE_BACKTRACE && HAVE_BACKTRACE_SYMBOLS && HAVE_ABI_CXA_DEMANGLE && \ - HAVE_WEAK_SYMBOL -#define BACKTRACE_DEMANGLE 1 -#endif - -C_MODE_START - -#if defined(HAVE_STACKTRACE) || defined(HAVE_BACKTRACE) -void my_print_stacktrace(uchar* stack_bottom, ulong thread_stack, - my_bool silent); -int my_safe_print_str(const char* val, size_t max_len); -void my_write_core(int sig); -# if BACKTRACE_DEMANGLE -char *my_demangle(const char *mangled_name, int *status); -# endif /* BACKTRACE_DEMANGLE */ -# ifdef __WIN__ -# define my_setup_stacktrace() -void my_set_exception_pointers(EXCEPTION_POINTERS *ep); -# else -void my_setup_stacktrace(void); -# endif /* __WIN__ */ -#else -# define my_setup_stacktrace() -#endif /* ! (defined(HAVE_STACKTRACE) || defined(HAVE_BACKTRACE)) */ - -#ifndef _WIN32 -#define MY_ADDR_RESOLVE_FORK -#endif - -#if defined(HAVE_BFD_H) || defined(MY_ADDR_RESOLVE_FORK) -#define HAVE_MY_ADDR_RESOLVE 1 -#endif - -typedef struct { - const char *file; - const char *func; - uint line; -} my_addr_loc; - -#ifdef HAVE_MY_ADDR_RESOLVE -int my_addr_resolve(void *ptr, my_addr_loc *loc); -const char *my_addr_resolve_init(); -#else -#define my_addr_resolve_init() (0) -#define my_addr_resolve(A,B) (1) -#endif - -#ifdef HAVE_WRITE_CORE -void my_write_core(int sig); -#endif - -/** - A (very) limited version of snprintf, which writes the result to STDERR. - @sa my_safe_snprintf - Implemented with simplicity, and async-signal-safety in mind. - @note Has an internal buffer capacity of 512 bytes, - which should suffice for our signal handling routines. -*/ -size_t my_safe_printf_stderr(const char* fmt, ...) - ATTRIBUTE_FORMAT(printf, 1, 2); - -/** - Writes up to count bytes from buffer to STDERR. - Implemented with simplicity, and async-signal-safety in mind. - @param buf Buffer containing data to be written. - @param count Number of bytes to write. - @returns Number of bytes written. -*/ -size_t my_write_stderr(const void *buf, size_t count); - -C_MODE_END - -#endif /* _my_stacktrace_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_time.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_time.h deleted file mode 100644 index b7b54db..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_time.h +++ /dev/null @@ -1,282 +0,0 @@ -/* - Copyright (c) 2004, 2011, Oracle and/or its affiliates. - Copyright (c) 2017, Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - This is a private header of sql-common library, containing - declarations for my_time.c -*/ - -#ifndef _my_time_h_ -#define _my_time_h_ -#include "mysql_time.h" -#include "my_decimal_limits.h" - -C_MODE_START - -extern MYSQL_PLUGIN_IMPORT ulonglong log_10_int[20]; -extern uchar days_in_month[]; - -#define MY_TIME_T_MAX LONG_MAX -#define MY_TIME_T_MIN LONG_MIN - -/* Time handling defaults */ -#define TIMESTAMP_MAX_YEAR 2038 -#define TIMESTAMP_MIN_YEAR (1900 + YY_PART_YEAR - 1) -#define TIMESTAMP_MAX_VALUE INT_MAX32 -#define TIMESTAMP_MIN_VALUE 0 - -/* two-digit years < this are 20..; >= this are 19.. */ -#define YY_PART_YEAR 70 - -/* - check for valid times only if the range of time_t is greater than - the range of my_time_t -*/ -#if SIZEOF_TIME_T > 4 || defined(TIME_T_UNSIGNED) -# define IS_TIME_T_VALID_FOR_TIMESTAMP(x) \ - ((x) <= TIMESTAMP_MAX_VALUE && \ - (x) >= TIMESTAMP_MIN_VALUE) -#else -# define IS_TIME_T_VALID_FOR_TIMESTAMP(x) \ - ((x) >= TIMESTAMP_MIN_VALUE) -#endif - -/* Flags to str_to_datetime */ - -#define C_TIME_NO_ZERO_IN_DATE (1UL << 23) /* == MODE_NO_ZERO_IN_DATE */ -#define C_TIME_NO_ZERO_DATE (1UL << 24) /* == MODE_NO_ZERO_DATE */ -#define C_TIME_INVALID_DATES (1UL << 25) /* == MODE_INVALID_DATES */ - -#define MYSQL_TIME_WARN_TRUNCATED 1U -#define MYSQL_TIME_WARN_OUT_OF_RANGE 2U -#define MYSQL_TIME_WARN_EDOM 4U -#define MYSQL_TIME_WARN_ZERO_DATE 8U -#define MYSQL_TIME_NOTE_TRUNCATED 16U - -#define MYSQL_TIME_WARN_WARNINGS (MYSQL_TIME_WARN_TRUNCATED|\ - MYSQL_TIME_WARN_OUT_OF_RANGE|\ - MYSQL_TIME_WARN_EDOM|\ - MYSQL_TIME_WARN_ZERO_DATE) -#define MYSQL_TIME_WARN_NOTES (MYSQL_TIME_NOTE_TRUNCATED) - -#define MYSQL_TIME_WARN_HAVE_WARNINGS(x) MY_TEST((x) & MYSQL_TIME_WARN_WARNINGS) -#define MYSQL_TIME_WARN_HAVE_NOTES(x) MY_TEST((x) & MYSQL_TIME_WARN_NOTES) - -/* Useful constants */ -#define SECONDS_IN_24H 86400L - -/* Limits for the INTERVAL data type */ - - /* Number of hours between '0001-01-01 00h' and '9999-12-31 23h' */ -#define TIME_MAX_INTERVAL_HOUR 87649415 -#define TIME_MAX_INTERVAL_HOUR_CHAR_LENGTH 8 - -/* Number of full days between '0001-01-01' and '9999-12-31'*/ -#define TIME_MAX_INTERVAL_DAY 3652058 /*87649415/24*/ -#define TIME_MAX_INTERVAL_DAY_CHAR_LENGTH 7 - -/* Limits for the TIME data type */ -#define TIME_MAX_HOUR 838 -#define TIME_MAX_MINUTE 59 -#define TIME_MAX_SECOND 59 -#define TIME_MAX_SECOND_PART 999999 -#define TIME_SECOND_PART_FACTOR (TIME_MAX_SECOND_PART+1) -#define TIME_SECOND_PART_DIGITS 6 -#define TIME_MAX_VALUE (TIME_MAX_HOUR*10000 + TIME_MAX_MINUTE*100 + TIME_MAX_SECOND) -#define TIME_MAX_VALUE_SECONDS (TIME_MAX_HOUR * 3600L + \ - TIME_MAX_MINUTE * 60L + TIME_MAX_SECOND) - -/* - Structure to return status from - str_to_datetime(), str_to_time(). -*/ -typedef struct st_mysql_time_status -{ - int warnings; - uint precision; - uint nanoseconds; -} MYSQL_TIME_STATUS; - -static inline void my_time_status_init(MYSQL_TIME_STATUS *status) -{ - status->warnings= 0; - status->precision= 0; - status->nanoseconds= 0; -} - -my_bool check_date(const MYSQL_TIME *ltime, my_bool not_zero_date, - ulonglong flags, int *was_cut); -my_bool str_to_DDhhmmssff(const char *str, size_t length, MYSQL_TIME *l_time, - ulong max_hour, MYSQL_TIME_STATUS *status); -my_bool str_to_datetime_or_date_or_time(const char *str, size_t length, - MYSQL_TIME *to, ulonglong flag, - MYSQL_TIME_STATUS *status, - ulong time_max_hour, - ulong time_err_hour); -my_bool -str_to_datetime_or_date_or_interval_hhmmssff(const char *str, size_t length, - MYSQL_TIME *to, ulonglong flag, - MYSQL_TIME_STATUS *status, - ulong time_max_hour, - ulong time_err_hour); -my_bool -str_to_datetime_or_date_or_interval_day(const char *str, size_t length, - MYSQL_TIME *to, ulonglong flag, - MYSQL_TIME_STATUS *status, - ulong time_max_hour, - ulong time_err_hour); -my_bool str_to_datetime_or_date(const char *str, size_t length, MYSQL_TIME *to, - ulonglong flags, MYSQL_TIME_STATUS *status); - -longlong number_to_datetime_or_date(longlong nr, ulong sec_part, - MYSQL_TIME *time_res, - ulonglong flags, int *was_cut); -int number_to_time_only(my_bool neg, ulonglong nr, ulong sec_part, - ulong max_hour, MYSQL_TIME *to, int *was_cut); - -ulonglong TIME_to_ulonglong_datetime(const MYSQL_TIME *); -ulonglong TIME_to_ulonglong_date(const MYSQL_TIME *); -ulonglong TIME_to_ulonglong_time(const MYSQL_TIME *); -ulonglong TIME_to_ulonglong(const MYSQL_TIME *); -double TIME_to_double(const MYSQL_TIME *my_time); - -int check_time_range(struct st_mysql_time *my_time, uint dec, int *warning); -my_bool check_datetime_range(const MYSQL_TIME *ltime); - - -long calc_daynr(uint year,uint month,uint day); -uint calc_days_in_year(uint year); -uint year_2000_handling(uint year); - -void my_init_time(void); - - -/* - Function to check sanity of a TIMESTAMP value - - DESCRIPTION - Check if a given MYSQL_TIME value fits in TIMESTAMP range. - This function doesn't make precise check, but rather a rough - estimate. - - RETURN VALUES - TRUE The value seems sane - FALSE The MYSQL_TIME value is definitely out of range -*/ - -static inline my_bool validate_timestamp_range(const MYSQL_TIME *t) -{ - if ((t->year > TIMESTAMP_MAX_YEAR || t->year < TIMESTAMP_MIN_YEAR) || - (t->year == TIMESTAMP_MAX_YEAR && (t->month > 1 || t->day > 19)) || - (t->year == TIMESTAMP_MIN_YEAR && (t->month < 12 || t->day < 31))) - return FALSE; - - return TRUE; -} - -/* Can't include mysqld_error.h, it needs mysys to build, thus hardcode 2 error values here. */ -#ifndef ER_WARN_DATA_OUT_OF_RANGE -#define ER_WARN_DATA_OUT_OF_RANGE 1264 -#define ER_WARN_INVALID_TIMESTAMP 1299 -#endif - -my_time_t -my_system_gmt_sec(const MYSQL_TIME *t, long *my_timezone, uint *error_code); - -void set_zero_time(MYSQL_TIME *tm, enum enum_mysql_timestamp_type time_type); - -/* - Required buffer length for my_time_to_str, my_date_to_str, - my_datetime_to_str and TIME_to_string functions. Note, that the - caller is still responsible to check that given TIME structure - has values in valid ranges, otherwise size of the buffer could - be not enough. We also rely on the fact that even wrong values - sent using binary protocol fit in this buffer. -*/ -#define MAX_DATE_STRING_REP_LENGTH 30 -#define AUTO_SEC_PART_DIGITS DECIMAL_NOT_SPECIFIED - -int my_interval_DDhhmmssff_to_str(const MYSQL_TIME *, char *to, uint digits); -int my_time_to_str(const MYSQL_TIME *l_time, char *to, uint digits); -int my_date_to_str(const MYSQL_TIME *l_time, char *to); -int my_datetime_to_str(const MYSQL_TIME *l_time, char *to, uint digits); -int my_TIME_to_str(const MYSQL_TIME *l_time, char *to, uint digits); - -int my_timeval_to_str(const struct timeval *tm, char *to, uint dec); - -static inline longlong sec_part_shift(longlong second_part, uint digits) -{ - return second_part / (longlong)log_10_int[TIME_SECOND_PART_DIGITS - digits]; -} -static inline longlong sec_part_unshift(longlong second_part, uint digits) -{ - return second_part * (longlong)log_10_int[TIME_SECOND_PART_DIGITS - digits]; -} - -/* Date/time rounding and truncation functions */ -static inline long my_time_fraction_remainder(long nr, uint decimals) -{ - DBUG_ASSERT(decimals <= TIME_SECOND_PART_DIGITS); - return nr % (long) log_10_int[TIME_SECOND_PART_DIGITS - decimals]; -} -static inline void my_datetime_trunc(MYSQL_TIME *ltime, uint decimals) -{ - ltime->second_part-= my_time_fraction_remainder(ltime->second_part, decimals); -} -static inline void my_time_trunc(MYSQL_TIME *ltime, uint decimals) -{ - ltime->second_part-= my_time_fraction_remainder(ltime->second_part, decimals); - if (!ltime->second_part && ltime->neg && - !ltime->hour && !ltime->minute && !ltime->second) - ltime->neg= FALSE; -} -static inline void my_timeval_trunc(struct timeval *tv, uint decimals) -{ - tv->tv_usec-= my_time_fraction_remainder(tv->tv_usec, decimals); -} - - -#define hrtime_to_my_time(X) ((my_time_t)hrtime_to_time(X)) - -/* - Available interval types used in any statement. - - 'interval_type' must be sorted so that simple intervals comes first, - ie year, quarter, month, week, day, hour, etc. The order based on - interval size is also important and the intervals should be kept in a - large to smaller order. (get_interval_value() depends on this) - - Note: If you change the order of elements in this enum you should fix - order of elements in 'interval_type_to_name' and 'interval_names' - arrays - - See also interval_type_to_name, get_interval_value, interval_names, append_interval -*/ - -enum interval_type -{ - INTERVAL_YEAR, INTERVAL_QUARTER, INTERVAL_MONTH, INTERVAL_WEEK, INTERVAL_DAY, - INTERVAL_HOUR, INTERVAL_MINUTE, INTERVAL_SECOND, INTERVAL_MICROSECOND, - INTERVAL_YEAR_MONTH, INTERVAL_DAY_HOUR, INTERVAL_DAY_MINUTE, - INTERVAL_DAY_SECOND, INTERVAL_HOUR_MINUTE, INTERVAL_HOUR_SECOND, - INTERVAL_MINUTE_SECOND, INTERVAL_DAY_MICROSECOND, INTERVAL_HOUR_MICROSECOND, - INTERVAL_MINUTE_MICROSECOND, INTERVAL_SECOND_MICROSECOND, INTERVAL_LAST -}; - -C_MODE_END - -#endif /* _my_time_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_tree.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_tree.h deleted file mode 100644 index 9bed28e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_tree.h +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _tree_h -#define _tree_h -#ifdef __cplusplus -extern "C" { -#endif - -#include "my_base.h" /* get 'enum ha_rkey_function' */ -#include "my_alloc.h" /* MEM_ROOT */ - -/* Worst case tree is half full. This gives use 2^(MAX_TREE_HEIGHT/2) leafs */ -#define MAX_TREE_HEIGHT 64 - -#define ELEMENT_KEY(tree,element)\ -(tree->offset_to_key ? (void*)((uchar*) element+tree->offset_to_key) :\ - *((void**) (element+1))) - -#define tree_set_pointer(element,ptr) *((uchar **) (element+1))=((uchar*) (ptr)) - -/* - A tree with its flag set to TREE_ONLY_DUPS behaves differently on inserting - an element that is not in the tree: - the element is not added at all, but instead tree_insert() returns a special - address TREE_ELEMENT_UNIQUE as an indication that the function has not failed - due to lack of memory. -*/ - -#define TREE_ELEMENT_UNIQUE ((TREE_ELEMENT *) 1) -#define TREE_NO_DUPS 1 -#define TREE_ONLY_DUPS 2 - -typedef enum { left_root_right, right_root_left } TREE_WALK; -typedef uint32 element_count; -typedef int (*tree_walk_action)(void *,element_count,void *); - -typedef enum { free_init, free_free, free_end } TREE_FREE; -typedef int (*tree_element_free)(void*, TREE_FREE, void *); - -typedef struct st_tree_element { - struct st_tree_element *left,*right; - uint32 count:31, - colour:1; /* black is marked as 1 */ -} TREE_ELEMENT; - -#define ELEMENT_CHILD(element, offs) (*(TREE_ELEMENT**)((char*)element + offs)) - -typedef struct st_tree { - TREE_ELEMENT *root; - TREE_ELEMENT **parents[MAX_TREE_HEIGHT]; - uint offset_to_key,elements_in_tree,size_of_element; - size_t memory_limit, allocated; - qsort_cmp2 compare; - void *custom_arg; - MEM_ROOT mem_root; - my_bool with_delete; - tree_element_free free; - myf my_flags; - uint flag; -} TREE; - - /* Functions on whole tree */ -void init_tree(TREE *tree, size_t default_alloc_size, size_t memory_limit, - int size, qsort_cmp2 compare, - tree_element_free free_element, void *custom_arg, - myf my_flags); -int delete_tree(TREE*, my_bool abort); -int reset_tree(TREE*); - - /* similar to delete tree, except we do not my_free() blocks in mem_root */ -#define is_tree_inited(tree) ((tree)->root != 0) - - /* Functions on leafs */ -TREE_ELEMENT *tree_insert(TREE *tree,void *key, uint key_size, - void *custom_arg); -void *tree_search(TREE *tree, void *key, void *custom_arg); -int tree_walk(TREE *tree,tree_walk_action action, - void *argument, TREE_WALK visit); -int tree_delete(TREE *tree, void *key, uint key_size, void *custom_arg); -void *tree_search_key(TREE *tree, const void *key, - TREE_ELEMENT **parents, TREE_ELEMENT ***last_pos, - enum ha_rkey_function flag, void *custom_arg); -void *tree_search_edge(TREE *tree, TREE_ELEMENT **parents, - TREE_ELEMENT ***last_pos, int child_offs); -void *tree_search_next(TREE *tree, TREE_ELEMENT ***last_pos, int l_offs, - int r_offs); -ha_rows tree_record_pos(TREE *tree, const void *key, - enum ha_rkey_function search_flag, void *custom_arg); -#define reset_free_element(tree) (tree)->free= 0 - -#define TREE_ELEMENT_EXTRA_SIZE (sizeof(TREE_ELEMENT) + sizeof(void*)) - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_uctype.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_uctype.h deleted file mode 100644 index 82949ff..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_uctype.h +++ /dev/null @@ -1,1484 +0,0 @@ -#ifndef MY_UCTYPE_INCLUDED -#define MY_UCTYPE_INCLUDED - -/* Copyright (c) 2006 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Unicode ctype data - Generated from UnicodeData-5.0.0d9.txt -*/ -static unsigned char uctype_page00[256]= -{ - 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, - 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, - 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, - 16, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, - 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 16, 16, 16, 16, 16, - 16, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, - 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 16, 16, 16, 16, 32, - 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, - 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, - 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 16, 16, 32, 16, 16, - 16, 16, 20, 20, 16, 2, 16, 16, 16, 20, 2, 16, 20, 20, 20, 16, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 16, 1, 1, 1, 1, 1, 1, 1, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, 2, 2 -}; - -static unsigned char uctype_page01[256]= -{ - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 2, - 2, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, - 1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 1, - 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, - 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 2, 2, 1, 2, 2, 2, - 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 2, 1, - 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 2, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2 -}; - -static unsigned char uctype_page02[256]= -{ - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, - 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 -}; - -static unsigned char uctype_page03[256]= -{ - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 2, 2, 2, 2, 16, 0, - 0, 0, 0, 0, 16, 16, 1, 16, 1, 1, 1, 0, 1, 0, 1, 1, - 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, - 2, 2, 1, 1, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 2, 2, 2, 2, 1, 2, 16, 1, 2, 1, 1, 2, 2, 1, 1, 1 -}; - -static unsigned char uctype_page04[256]= -{ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 16, 18, 18, 18, 18, 0, 18, 18, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 -}; - -static unsigned char uctype_page05[256]= -{ - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 16, 16, 16, 16, 16, 16, - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 0, 16, 16, 0, 0, 0, 0, 0, - 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 16, 18, - 16, 18, 18, 16, 18, 18, 16, 18, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, - 2, 2, 2, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page06[256]= -{ - 32, 32, 32, 32, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, - 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 16, 0, 0, 16, 16, - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 2, 2, - 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 16, 2, 18, 18, 18, 18, 18, 18, 18, 32, 18, 18, - 18, 18, 18, 18, 18, 2, 2, 18, 18, 16, 18, 18, 18, 18, 2, 2, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 16, 16, 2 -}; - -static unsigned char uctype_page07[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 32, - 2, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 2, 2, 16, 16, 16, 16, 2, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page09[256]= -{ - 0, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, - 2, 18, 18, 18, 18, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 18, 18, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, - 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, - 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, - 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, - 18, 18, 18, 18, 18, 0, 0, 18, 18, 0, 0, 18, 18, 18, 2, 0, - 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 2, 2, 0, 2, - 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 2, 2, 16, 16, 20, 20, 20, 20, 20, 20, 16, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page0A[256]= -{ - 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, - 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, - 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0, 18, 0, 18, 18, - 18, 18, 18, 0, 0, 0, 0, 18, 18, 0, 0, 18, 18, 18, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 0, - 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 18, 18, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, - 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, - 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, - 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 0, 0, - 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page0B[256]= -{ - 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, - 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, - 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, - 18, 18, 18, 18, 0, 0, 0, 18, 18, 0, 0, 18, 18, 18, 0, 0, - 0, 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 2, 2, 0, 2, - 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 18, 2, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, - 2, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 0, 2, 0, 2, 2, - 0, 0, 0, 2, 2, 0, 0, 0, 2, 2, 2, 0, 0, 0, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, - 18, 18, 18, 0, 0, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page0C[256]= -{ - 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, - 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, - 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, - 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, - 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, - 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, - 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 2, 0, - 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page0D[256]= -{ - 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, - 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, - 18, 18, 18, 18, 0, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 18, 0, 0, 0, 0, 18, - 18, 18, 18, 18, 18, 0, 18, 0, 18, 18, 18, 18, 18, 18, 18, 18, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 18, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page0E[256]= -{ - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 18, 2, 2, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 16, - 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 16, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 2, 2, 0, 2, 0, 0, 2, 2, 0, 2, 0, 0, 2, 0, 0, - 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, - 0, 2, 2, 2, 0, 2, 0, 2, 0, 0, 2, 2, 0, 2, 2, 2, - 2, 18, 2, 2, 18, 18, 18, 18, 18, 18, 0, 18, 18, 2, 0, 0, - 2, 2, 2, 2, 2, 0, 2, 0, 18, 18, 18, 18, 18, 18, 0, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 2, 2, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page0F[256]= -{ - 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 16, 16, 16, 16, 16, 16, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 16, 18, 16, 18, 16, 18, 16, 16, 16, 16, 18, 18, - 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, - 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 16, 18, 18, 2, 2, 2, 2, 0, 0, 0, 0, - 18, 18, 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 16, 16, - 16, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 16, 16, 0, 0, 16, - 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page10[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 2, 0, 18, 18, 18, 18, - 18, 18, 18, 0, 0, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, - 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 0, 0, 0 -}; - -static unsigned char uctype_page11[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page12[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, - 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 -}; - -static unsigned char uctype_page13[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page14[256]= -{ - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 -}; - -static unsigned char uctype_page16[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 2, - 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 7, 7, - 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page17[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, - 2, 2, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 18, 18, 18, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, - 2, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 32, 32, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 16, 16, 16, 2, 16, 16, 16, 16, 2, 18, 0, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page18[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 8, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page19[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, - 16, 0, 0, 0, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, - 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 2, 2, 2, 2, 2, 2, 2, 18, 18, 0, 0, 0, 0, 0, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 -}; - -static unsigned char uctype_page1A[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 0, 0, 16, 16, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page1B[256]= -{ - 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page1D[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18 -}; - -static unsigned char uctype_page1E[256]= -{ - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page1F[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1, 0, 1, 0, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 2, 16, - 16, 16, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 16, 16, - 2, 2, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1, 0, 16, 16, 16, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 16, 16, 16, - 0, 0, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 16, 0 -}; - -static unsigned char uctype_page20[256]= -{ - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 32, 32, 32, 32, 32, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 8, 8, 32, 32, 32, 32, 32, 8, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 8, - 32, 32, 32, 32, 0, 0, 0, 0, 0, 0, 32, 32, 32, 32, 32, 32, - 20, 2, 0, 0, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 2, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 0, - 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page21[256]= -{ - 16, 16, 1, 16, 16, 16, 16, 1, 16, 16, 2, 1, 1, 1, 2, 2, - 1, 1, 1, 2, 16, 1, 16, 16, 16, 1, 1, 1, 1, 1, 16, 16, - 16, 16, 16, 16, 1, 16, 1, 16, 1, 16, 1, 1, 1, 1, 16, 2, - 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 16, 16, 2, 2, 1, 1, - 16, 16, 16, 16, 16, 1, 2, 2, 2, 2, 16, 16, 16, 16, 2, 0, - 0, 0, 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 -}; - -static unsigned char uctype_page23[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page24[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 -}; - -static unsigned char uctype_page26[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page27[256]= -{ - 0, 16, 16, 16, 16, 0, 16, 16, 16, 16, 0, 0, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 0, 16, - 16, 16, 16, 0, 0, 0, 16, 0, 16, 16, 16, 16, 16, 16, 16, 0, - 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 20, 20, 20, 20, 16, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 -}; - -static unsigned char uctype_page2B[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page2C[256]= -{ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, - 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, - 0, 0, 0, 0, 2, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, - 1, 2, 1, 2, 2, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 20, 16, 16 -}; - -static unsigned char uctype_page2D[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, - 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, - 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, - 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page2E[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_page2F[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0 -}; - -static unsigned char uctype_page30[256]= -{ - 8, 16, 16, 16, 16, 2, 2, 7, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 7, 7, 7, 7, 7, 7, 7, 7, 7, 18, 18, 18, 18, 18, 18, - 16, 2, 2, 2, 2, 2, 16, 16, 7, 7, 7, 2, 2, 16, 16, 16, - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 0, 0, 18, 18, 16, 16, 2, 2, 2, - 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2 -}; - -static unsigned char uctype_page31[256]= -{ - 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, - 16, 16, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 -}; - -static unsigned char uctype_page32[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0 -}; - -static unsigned char uctype_page4D[256]= -{ - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 -}; - -static unsigned char uctype_page9F[256]= -{ - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageA4[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageA7[256]= -{ - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 0, 0, 0, 0, 0, - 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageA8[256]= -{ - 2, 2, 18, 2, 2, 2, 18, 2, 2, 2, 2, 18, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 18, 18, 18, 18, 18, 16, 16, 16, 16, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageD7[256]= -{ - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageD8[256]= -{ - 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageDB[256]= -{ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, - 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 -}; - -static unsigned char uctype_pageDC[256]= -{ - 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageDF[256]= -{ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 -}; - -static unsigned char uctype_pageE0[256]= -{ - 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageF8[256]= -{ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 -}; - -static unsigned char uctype_pageFA[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -static unsigned char uctype_pageFB[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 18, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 0, - 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 -}; - -static unsigned char uctype_pageFD[256]= -{ - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 0, 0 -}; - -static unsigned char uctype_pageFE[256]= -{ - 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, - 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 0, 0, 0, 0, - 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 32 -}; - -static unsigned char uctype_pageFF[256]= -{ - 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, - 16, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 16, 16, 16, 16, 16, - 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, - 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, - 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 0, 0, 0, - 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 32, 32, 16, 16, 0, 0 -}; - -MY_UNI_CTYPE my_uni_ctype[256]={ - {0,uctype_page00}, - {0,uctype_page01}, - {0,uctype_page02}, - {0,uctype_page03}, - {0,uctype_page04}, - {0,uctype_page05}, - {0,uctype_page06}, - {0,uctype_page07}, - {0,NULL}, - {0,uctype_page09}, - {0,uctype_page0A}, - {0,uctype_page0B}, - {0,uctype_page0C}, - {0,uctype_page0D}, - {0,uctype_page0E}, - {0,uctype_page0F}, - {0,uctype_page10}, - {0,uctype_page11}, - {0,uctype_page12}, - {0,uctype_page13}, - {0,uctype_page14}, - {2,NULL}, - {0,uctype_page16}, - {0,uctype_page17}, - {0,uctype_page18}, - {0,uctype_page19}, - {0,uctype_page1A}, - {0,uctype_page1B}, - {0,NULL}, - {0,uctype_page1D}, - {0,uctype_page1E}, - {0,uctype_page1F}, - {0,uctype_page20}, - {0,uctype_page21}, - {16,NULL}, - {0,uctype_page23}, - {0,uctype_page24}, - {16,NULL}, - {0,uctype_page26}, - {0,uctype_page27}, - {16,NULL}, - {16,NULL}, - {16,NULL}, - {0,uctype_page2B}, - {0,uctype_page2C}, - {0,uctype_page2D}, - {0,uctype_page2E}, - {0,uctype_page2F}, - {0,uctype_page30}, - {0,uctype_page31}, - {0,uctype_page32}, - {16,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {0,uctype_page4D}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {0,uctype_page9F}, - {2,NULL}, - {2,NULL}, - {2,NULL}, - {2,NULL}, - {0,uctype_pageA4}, - {0,NULL}, - {0,NULL}, - {0,uctype_pageA7}, - {0,uctype_pageA8}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {3,NULL}, - {0,uctype_pageD7}, - {0,uctype_pageD8}, - {0,NULL}, - {0,NULL}, - {0,uctype_pageDB}, - {0,uctype_pageDC}, - {0,NULL}, - {0,NULL}, - {0,uctype_pageDF}, - {0,uctype_pageE0}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,NULL}, - {0,uctype_pageF8}, - {2,NULL}, - {0,uctype_pageFA}, - {0,uctype_pageFB}, - {2,NULL}, - {0,uctype_pageFD}, - {0,uctype_pageFE}, - {0,uctype_pageFF} -}; - - -#endif /* MY_UCTYPE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_user.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_user.h deleted file mode 100644 index 46a811d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/my_user.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (c) 2005-2007 MySQL AB - Use is subject to license terms - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - This is a header for libraries containing functions used in both server and - only some of clients (but not in libmysql)... -*/ - -#ifndef _my_user_h_ -#define _my_user_h_ - -C_MODE_START - -int parse_user(const char *user_id_str, size_t user_id_len, - char *user_name_str, size_t *user_name_len, - char *host_name_str, size_t *host_name_len); - -C_MODE_END - -#endif /* _my_user_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisam.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisam.h deleted file mode 100644 index 0942584..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisam.h +++ /dev/null @@ -1,442 +0,0 @@ -/* - Copyright (c) 2000, 2013, Oracle and/or its affiliates. - Copyright (c) 2009, 2013, Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* This file should be included when using myisam_funktions */ - -#ifndef _myisam_h -#define _myisam_h -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include "keycache.h" -#include "my_compare.h" -#include -#include -#include -/* - Limit max keys according to HA_MAX_POSSIBLE_KEY; See myisamchk.h for details -*/ - -#if MAX_INDEXES > HA_MAX_POSSIBLE_KEY -#define MI_MAX_KEY HA_MAX_POSSIBLE_KEY /* Max allowed keys */ -#else -#define MI_MAX_KEY MAX_INDEXES /* Max allowed keys */ -#endif - -#define MI_MAX_POSSIBLE_KEY_BUFF HA_MAX_POSSIBLE_KEY_BUFF -/* - The following defines can be increased if necessary. - But beware the dependency of MI_MAX_POSSIBLE_KEY_BUFF and MI_MAX_KEY_LENGTH. -*/ -#define MI_MAX_KEY_LENGTH 1000 /* Max length in bytes */ -#define MI_MAX_KEY_SEG 16 /* Max segments for key */ - -#define MI_NAME_IEXT ".MYI" -#define MI_NAME_DEXT ".MYD" - -/* Possible values for myisam_block_size (must be power of 2) */ -#define MI_KEY_BLOCK_LENGTH 1024 /* default key block length */ -#define MI_MIN_KEY_BLOCK_LENGTH 1024 /* Min key block length */ -#define MI_MAX_KEY_BLOCK_LENGTH 16384 - -/* - In the following macros '_keyno_' is 0 .. keys-1. - If there can be more keys than bits in the key_map, the highest bit - is for all upper keys. They cannot be switched individually. - This means that clearing of high keys is ignored, setting one high key - sets all high keys. -*/ -#define MI_KEYMAP_BITS (8 * SIZEOF_LONG_LONG) -#define MI_KEYMAP_HIGH_MASK (1ULL << (MI_KEYMAP_BITS - 1)) -#define mi_get_mask_all_keys_active(_keys_) \ - (((_keys_) < MI_KEYMAP_BITS) ? \ - ((1ULL << (_keys_)) - 1ULL) : \ - (~ 0ULL)) - -#if MI_MAX_KEY > MI_KEYMAP_BITS - -#define mi_is_key_active(_keymap_,_keyno_) \ - (((_keyno_) < MI_KEYMAP_BITS) ? \ - MY_TEST((_keymap_) & (1ULL << (_keyno_))) : \ - MY_TEST((_keymap_) & MI_KEYMAP_HIGH_MASK)) -#define mi_set_key_active(_keymap_,_keyno_) \ - (_keymap_)|= (((_keyno_) < MI_KEYMAP_BITS) ? \ - (1ULL << (_keyno_)) : \ - MI_KEYMAP_HIGH_MASK) -#define mi_clear_key_active(_keymap_,_keyno_) \ - (_keymap_)&= (((_keyno_) < MI_KEYMAP_BITS) ? \ - (~ (1ULL << (_keyno_))) : \ - (~ (0ULL)) /*ignore*/ ) - -#else - -#define mi_is_key_active(_keymap_,_keyno_) \ - MY_TEST((_keymap_) & (1ULL << (_keyno_))) -#define mi_set_key_active(_keymap_,_keyno_) \ - (_keymap_)|= (1ULL << (_keyno_)) -#define mi_clear_key_active(_keymap_,_keyno_) \ - (_keymap_)&= (~ (1ULL << (_keyno_))) - -#endif - -#define mi_is_any_key_active(_keymap_) \ - MY_TEST((_keymap_)) -#define mi_is_all_keys_active(_keymap_,_keys_) \ - ((_keymap_) == mi_get_mask_all_keys_active(_keys_)) -#define mi_set_all_keys_active(_keymap_,_keys_) \ - (_keymap_)= mi_get_mask_all_keys_active(_keys_) -#define mi_clear_all_keys_active(_keymap_) \ - (_keymap_)= 0 -#define mi_intersect_keys_active(_to_,_from_) \ - (_to_)&= (_from_) -#define mi_is_any_intersect_keys_active(_keymap1_,_keys_,_keymap2_) \ - ((_keymap1_) & (_keymap2_) & \ - mi_get_mask_all_keys_active(_keys_)) -#define mi_copy_keys_active(_to_,_maxkeys_,_from_) \ - (_to_)= (mi_get_mask_all_keys_active(_maxkeys_) & \ - (_from_)) - - /* Param to/from mi_info */ - -typedef struct st_mi_isaminfo /* Struct from h_info */ -{ - ha_rows records; /* Records in database */ - ha_rows deleted; /* Deleted records in database */ - my_off_t recpos; /* Pos for last used record */ - my_off_t newrecpos; /* Pos if we write new record */ - my_off_t dupp_key_pos; /* Position to record with dupp key */ - my_off_t data_file_length, /* Length of data file */ - max_data_file_length, - index_file_length, - max_index_file_length, - delete_length; - ulong reclength; /* Recordlength */ - ulong mean_reclength; /* Mean recordlength (if packed) */ - ulonglong auto_increment; - ulonglong key_map; /* Which keys are used */ - char *data_file_name, *index_file_name; - uint keys; /* Number of keys in use */ - uint options; /* HA_OPTION_... used */ - int errkey, /* With key was dupplicated on err */ - sortkey; /* clustered by this key */ - File filenr; /* (uniq) filenr for datafile */ - time_t create_time; /* When table was created */ - time_t check_time; - time_t update_time; - uint reflength; - ulong record_offset; - ulong *rec_per_key; /* for sql optimizing */ -} MI_ISAMINFO; - - -typedef struct st_mi_create_info -{ - const char *index_file_name, *data_file_name; /* If using symlinks */ - ha_rows max_rows; - ha_rows reloc_rows; - ulonglong auto_increment; - ulonglong data_file_length; - ulonglong key_file_length; - uint old_options; - uint16 language; - my_bool with_auto_increment; -} MI_CREATE_INFO; - -struct st_myisam_info; /* For referense */ -struct st_mi_isam_share; -typedef struct st_myisam_info MI_INFO; -struct st_mi_s_param; - -typedef struct st_mi_keydef /* Key definition with open & info */ -{ - struct st_mi_isam_share *share; /* Pointer to base (set in mi_open) */ - uint16 keysegs; /* Number of key-segment */ - uint16 flag; /* NOSAME, PACK_USED */ - - uint8 key_alg; /* BTREE, RTREE */ - uint16 block_length; /* Length of keyblock (auto) */ - uint16 underflow_block_length; /* When to execute underflow */ - uint16 keylength; /* Tot length of keyparts (auto) */ - uint16 minlength; /* min length of (packed) key (auto) */ - uint16 maxlength; /* max length of (packed) key (auto) */ - uint16 block_size_index; /* block_size (auto) */ - uint32 version; /* For concurrent read/write */ - uint32 ftkey_nr; /* full-text index number */ - - HA_KEYSEG *seg,*end; - struct st_mysql_ftparser *parser; /* Fulltext [pre]parser */ - int (*bin_search)(struct st_myisam_info *info,struct st_mi_keydef *keyinfo, - uchar *page,uchar *key, - uint key_len,uint comp_flag,uchar * *ret_pos, - uchar *buff, my_bool *was_last_key); - uint (*get_key)(struct st_mi_keydef *keyinfo,uint nod_flag,uchar * *page, - uchar *key); - int (*pack_key)(struct st_mi_keydef *keyinfo,uint nod_flag,uchar *next_key, - uchar *org_key, uchar *prev_key, uchar *key, - struct st_mi_s_param *s_temp); - void (*store_key)(struct st_mi_keydef *keyinfo, uchar *key_pos, - struct st_mi_s_param *s_temp); - int (*ck_insert)(struct st_myisam_info *inf, uint k_nr, uchar *k, uint klen); - int (*ck_delete)(struct st_myisam_info *inf, uint k_nr, uchar *k, uint klen); -} MI_KEYDEF; - - -#define MI_UNIQUE_HASH_LENGTH 4 - -typedef struct st_unique_def /* Segment definition of unique */ -{ - uint16 keysegs; /* Number of key-segment */ - uchar key; /* Mapped to which key */ - uint8 null_are_equal; - HA_KEYSEG *seg,*end; -} MI_UNIQUEDEF; - -typedef struct st_mi_decode_tree /* Decode huff-table */ -{ - uint16 *table; - uint quick_table_bits; - uchar *intervalls; -} MI_DECODE_TREE; - - -struct st_mi_bit_buff; - -/* - Note that null markers should always be first in a row ! - When creating a column, one should only specify: - type, length, null_bit and null_pos -*/ - -typedef struct st_columndef /* column information */ -{ - enum en_fieldtype type; - uint16 length; /* length of field */ - uint32 offset; /* Offset to position in row */ - uint8 null_bit; /* If column may be 0 */ - uint16 null_pos; /* position for null marker */ - -#ifndef NOT_PACKED_DATABASES - void (*unpack)(struct st_columndef *rec,struct st_mi_bit_buff *buff, - uchar *start,uchar *end); - enum en_fieldtype base_type; - uint space_length_bits,pack_type; - MI_DECODE_TREE *huff_tree; -#endif -} MI_COLUMNDEF; - -extern char * myisam_log_filename; /* Name of logfile */ -extern ulong myisam_block_size; -extern ulong myisam_concurrent_insert; -extern my_bool myisam_flush,myisam_delay_key_write,myisam_single_user; -extern my_off_t myisam_max_temp_length; -extern ulong myisam_data_pointer_size; - -/* usually used to check if a symlink points into the mysql data home */ -/* which is normally forbidden */ -extern int (*myisam_test_invalid_symlink)(const char *filename); -extern ulonglong myisam_mmap_size, myisam_mmap_used; -extern mysql_mutex_t THR_LOCK_myisam_mmap; - - /* Prototypes for myisam-functions */ - -extern int mi_close(struct st_myisam_info *file); -extern int mi_delete(struct st_myisam_info *file,const uchar *buff); -extern struct st_myisam_info *mi_open(const char *name,int mode, - uint wait_if_locked); -extern int mi_panic(enum ha_panic_function function); -extern int mi_rfirst(struct st_myisam_info *file,uchar *buf,int inx); -extern int mi_rkey(MI_INFO *info, uchar *buf, int inx, const uchar *key, - key_part_map keypart_map, enum ha_rkey_function search_flag); -extern int mi_rlast(struct st_myisam_info *file,uchar *buf,int inx); -extern int mi_rnext(struct st_myisam_info *file,uchar *buf,int inx); -extern int mi_rnext_same(struct st_myisam_info *info, uchar *buf); -extern int mi_rprev(struct st_myisam_info *file,uchar *buf,int inx); -extern int mi_rrnd(struct st_myisam_info *file,uchar *buf, my_off_t pos); -extern int mi_scan_init(struct st_myisam_info *file); -extern int mi_scan(struct st_myisam_info *file,uchar *buf); -extern int mi_rsame(struct st_myisam_info *file,uchar *record,int inx); -extern int mi_rsame_with_pos(struct st_myisam_info *file,uchar *record, - int inx, my_off_t pos); -extern int mi_update(struct st_myisam_info *file,const uchar *old, - const uchar *new_record); -extern int mi_write(struct st_myisam_info *file,const uchar *buff); -extern my_off_t mi_position(struct st_myisam_info *file); -extern int mi_status(struct st_myisam_info *info, MI_ISAMINFO *x, uint flag); -extern int mi_lock_database(struct st_myisam_info *file,int lock_type); -extern int mi_create(const char *name,uint keys,MI_KEYDEF *keydef, - uint columns, MI_COLUMNDEF *columndef, - uint uniques, MI_UNIQUEDEF *uniquedef, - MI_CREATE_INFO *create_info, uint flags); -extern int mi_delete_table(const char *name); -extern int mi_rename(const char *from, const char *to); -extern int mi_extra(struct st_myisam_info *file, - enum ha_extra_function function, - void *extra_arg); -extern int mi_reset(struct st_myisam_info *file); -extern ha_rows mi_records_in_range(MI_INFO *info,int inx, - const key_range *min_key, - const key_range *max_key, - page_range *pages); -extern int mi_log(int activate_log); -extern int mi_is_changed(struct st_myisam_info *info); -extern int mi_delete_all_rows(struct st_myisam_info *info); -extern ulong _mi_calc_blob_length(uint length , const uchar *pos); -extern uint mi_get_pointer_length(ulonglong file_length, uint def); -extern int mi_make_backup_of_index(struct st_myisam_info *info, - time_t backup_time, myf flags); -#define myisam_max_key_length() HA_MAX_KEY_LENGTH -#define myisam_max_key_segments() HA_MAX_KEY_SEG - -#define MEMMAP_EXTRA_MARGIN 7 /* Write this as a suffix for mmap file */ -/* this is used to pass to mysql_myisamchk_table */ - -#define MYISAMCHK_REPAIR 1 /* equivalent to myisamchk -r */ -#define MYISAMCHK_VERIFY 2 /* Verify, run repair if failure */ - -typedef uint mi_bit_type; -typedef struct st_sort_key_blocks SORT_KEY_BLOCKS; -typedef struct st_sort_ftbuf SORT_FT_BUF; - -typedef struct st_mi_bit_buff -{ /* Used for packing of record */ - mi_bit_type current_byte; - uint bits; - uchar *pos, *end, *blob_pos, *blob_end; - uint error; -} MI_BIT_BUFF; - -typedef struct st_sort_info -{ - /* sync things */ - mysql_mutex_t mutex; - mysql_cond_t cond; - MI_INFO *info; - HA_CHECK *param; - uchar *buff; - SORT_KEY_BLOCKS *key_block, *key_block_end; - SORT_FT_BUF *ft_buf; - my_off_t filelength, dupp, buff_length; - ha_rows max_records; - uint current_key, total_keys; - volatile uint got_error; - uint threads_running; - myf myf_rw; - enum data_file_type new_data_file_type; -} MI_SORT_INFO; - -typedef struct st_mi_sort_param -{ - pthread_t thr; - IO_CACHE read_cache, tempfile, tempfile_for_exceptions; - DYNAMIC_ARRAY buffpek; - MI_BIT_BUFF bit_buff; /* For parallel repair of packrec. */ - - MI_KEYDEF *keyinfo; - MI_SORT_INFO *sort_info; - HA_KEYSEG *seg; - uchar **sort_keys; - uchar *rec_buff; - void *wordlist, *wordptr; - MEM_ROOT wordroot; - uchar *record; - MY_TMPDIR *tmpdir; - - /* - The next two are used to collect statistics, see update_key_parts for - description. - */ - ulonglong unique[HA_MAX_KEY_SEG+1]; - ulonglong notnull[HA_MAX_KEY_SEG+1]; - - my_off_t pos,max_pos,filepos,start_recpos; - uint key, key_length,real_key_length; - uint maxbuffers, find_length; - ulonglong sortbuff_size; - ha_rows keys; - my_bool fix_datafile, master; - my_bool calc_checksum; /* calculate table checksum */ - - int (*key_cmp)(struct st_mi_sort_param *, const void *, const void *); - int (*key_read)(struct st_mi_sort_param *,void *); - int (*key_write)(struct st_mi_sort_param *, const void *); - void (*lock_in_memory)(HA_CHECK *); - int (*write_keys)(struct st_mi_sort_param *, uchar **, - ulonglong , struct st_buffpek *, IO_CACHE *); - my_off_t (*read_to_buffer)(IO_CACHE *,struct st_buffpek *, uint); - int (*write_key)(struct st_mi_sort_param *, IO_CACHE *,uchar *, - uint, ulonglong); -} MI_SORT_PARAM; - -/* functions in mi_check */ -void myisamchk_init(HA_CHECK *param); -int chk_status(HA_CHECK *param, MI_INFO *info); -int chk_del(HA_CHECK *param, MI_INFO *info, ulonglong test_flag); -int chk_size(HA_CHECK *param, MI_INFO *info); -int chk_key(HA_CHECK *param, MI_INFO *info); -int chk_data_link(HA_CHECK *param, MI_INFO *info, my_bool extend); -int mi_repair(HA_CHECK *param, MI_INFO *info, char * name, int rep_quick); -int mi_sort_index(HA_CHECK *param, MI_INFO *info, char * name); -int mi_repair_by_sort(HA_CHECK *param, MI_INFO *info, - const char * name, int rep_quick); -int mi_repair_parallel(HA_CHECK *param, MI_INFO *info, - const char * name, int rep_quick); -int change_to_newfile(const char * filename, const char * old_ext, - const char * new_ext, time_t backup_time, myf myflags); -int lock_file(HA_CHECK *param, File file, my_off_t start, int lock_type, - const char *filetype, const char *filename); -void lock_memory(HA_CHECK *param); -void update_auto_increment_key(HA_CHECK *param, MI_INFO *info, - my_bool repair); -int update_state_info(HA_CHECK *param, MI_INFO *info,uint update); -void update_key_parts(MI_KEYDEF *keyinfo, ulong *rec_per_key_part, - ulonglong *unique, ulonglong *notnull, - ulonglong records); -int filecopy(HA_CHECK *param, File to,File from,my_off_t start, - my_off_t length, const char *type); -int movepoint(MI_INFO *info,uchar *record,my_off_t oldpos, - my_off_t newpos, uint prot_key); -int write_data_suffix(MI_SORT_INFO *sort_info, my_bool fix_datafile); -int test_if_almost_full(MI_INFO *info); -int recreate_table(HA_CHECK *param, MI_INFO **org_info, char *filename); -void mi_disable_non_unique_index(MI_INFO *info, ha_rows rows); -my_bool mi_test_if_sort_rep(MI_INFO *info, ha_rows rows, ulonglong key_map, - my_bool force); - -int mi_init_bulk_insert(MI_INFO *info, size_t cache_size, ha_rows rows); -void mi_flush_bulk_insert(MI_INFO *info, uint inx); -int mi_end_bulk_insert(MI_INFO *info, my_bool abort); -int mi_assign_to_key_cache(MI_INFO *info, ulonglong key_map, - KEY_CACHE *key_cache); -void mi_change_key_cache(KEY_CACHE *old_key_cache, - KEY_CACHE *new_key_cache); -int mi_preload(MI_INFO *info, ulonglong key_map, my_bool ignore_leaves); - -int write_data_suffix(MI_SORT_INFO *sort_info, my_bool fix_datafile); -int flush_pending_blocks(MI_SORT_PARAM *param); -int sort_ft_buf_flush(MI_SORT_PARAM *sort_param); -int thr_write_keys(MI_SORT_PARAM *sort_param); -int sort_write_record(MI_SORT_PARAM *sort_param); -int _create_index_by_sort(MI_SORT_PARAM *info,my_bool no_messages, ulonglong); -my_bool mi_too_big_key_for_sort(MI_KEYDEF *key, ha_rows rows); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisamchk.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisamchk.h deleted file mode 100644 index f1a7348..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisamchk.h +++ /dev/null @@ -1,130 +0,0 @@ -/* Copyright (C) 2006 MySQL AB - Copyright (c) 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Definitions needed for myisamchk/mariachk.c */ - -#ifndef _myisamchk_h -#define _myisamchk_h - -#include - -/* - Flags used by xxxxchk.c or/and ha_xxxx.cc that are NOT passed - to xxxcheck.c follows: -*/ - -#define TT_USEFRM 1U -#define TT_FOR_UPGRADE 2U -#define TT_FROM_MYSQL 4U - -/* Bits set in out_flag */ -#define O_NEW_DATA 2U -#define O_DATA_LOST 4U - -/* - MARIA/MYISAM supports several statistics collection - methods. Currently statistics collection method is not stored in - MARIA file and has to be specified for each table analyze/repair - operation in MI_CHECK::stats_method. -*/ - -typedef enum -{ - /* Treat NULLs as inequal when collecting statistics (default for 4.1/5.0) */ - MI_STATS_METHOD_NULLS_NOT_EQUAL, - /* Treat NULLs as equal when collecting statistics (like 4.0 did) */ - MI_STATS_METHOD_NULLS_EQUAL, - /* Ignore NULLs - count only tuples without NULLs in the index components */ - MI_STATS_METHOD_IGNORE_NULLS -} enum_handler_stats_method; - -struct st_myisam_info; - -typedef struct st_handler_check_param -{ - char *isam_file_name; - MY_TMPDIR *tmpdir; - void *thd; - const char *db_name, *table_name, *op_name; - ulonglong auto_increment_value; - ulonglong max_data_file_length; - ulonglong keys_in_use; - ulonglong max_record_length; - /* - The next two are used to collect statistics, see update_key_parts for - description. - */ - ulonglong unique_count[HA_MAX_KEY_SEG + 1]; - ulonglong notnull_count[HA_MAX_KEY_SEG + 1]; - - my_off_t search_after_block; - my_off_t new_file_pos, key_file_blocks; - my_off_t keydata, totaldata, key_blocks, start_check_pos; - my_off_t used, empty, splits, del_length, link_used, lost; - ha_rows total_records, total_deleted, records,del_blocks; - ha_rows full_page_count, tail_count; - ha_checksum record_checksum, glob_crc; - ha_checksum key_crc[HA_MAX_POSSIBLE_KEY]; - ha_checksum tmp_key_crc[HA_MAX_POSSIBLE_KEY]; - ha_checksum tmp_record_checksum; - ulonglong org_key_map; - ulonglong testflag; - - /* Following is used to check if rows are visible */ - ulonglong max_trid, max_found_trid; - ulonglong not_visible_rows_found; - ulonglong sort_buffer_length; - ulonglong use_buffers; /* Used as param to getopt() */ - size_t read_buffer_length, write_buffer_length, sort_key_blocks; - time_t backup_time; /* To sign backup files */ - ulong rec_per_key_part[HA_MAX_KEY_SEG * HA_MAX_POSSIBLE_KEY]; - double new_rec_per_key_part[HA_MAX_KEY_SEG * HA_MAX_POSSIBLE_KEY]; - uint out_flag, error_printed, verbose; - uint opt_sort_key, total_files, max_level; - uint key_cache_block_size, pagecache_block_size; - int tmpfile_createflag, err_count; - myf myf_rw; - uint16 language; - my_bool warning_printed, note_printed, wrong_trd_printed; - my_bool using_global_keycache, opt_lock_memory, opt_follow_links; - my_bool retry_repair, force_sort, calc_checksum, static_row_size; - char temp_filename[FN_REFLEN]; - IO_CACHE read_cache; - void **stack_end_ptr; - enum_handler_stats_method stats_method; - /* For reporting progress */ - uint stage, max_stage; - uint progress_counter; /* How often to call _report_progress() */ - ulonglong progress, max_progress; - - int (*fix_record)(struct st_myisam_info *info, uchar *record, int keynum); - - mysql_mutex_t print_msg_mutex; - my_bool need_print_msg_lock; - myf malloc_flags; -} HA_CHECK; - - -typedef struct st_buffpek { - my_off_t file_pos; /* Where we are in the sort file */ - uchar *base, *key; /* Key pointers */ - ha_rows count; /* Number of rows in table */ - ha_rows mem_count; /* Numbers of keys in memory */ - ha_rows max_keys; /* Max keys in buffert */ -} BUFFPEK; - -#endif /* _myisamchk_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisammrg.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisammrg.h deleted file mode 100644 index 78e7ac0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisammrg.h +++ /dev/null @@ -1,128 +0,0 @@ -/* Copyright (c) 2000-2002, 2004, 2006-2008 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* This file should be included when using merge_isam_funktions */ - -#ifndef _myisammrg_h -#define _myisammrg_h -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef _my_base_h -#include -#endif -#ifndef _myisam_h -#include -#endif - -#include - -#define MYRG_NAME_EXT ".MRG" -#define MYRG_NAME_TMPEXT ".MRG_TMP" - -/* In which table to INSERT rows */ -#define MERGE_INSERT_DISABLED 0 -#define MERGE_INSERT_TO_FIRST 1 -#define MERGE_INSERT_TO_LAST 2 - -extern TYPELIB merge_insert_method; - - /* Param to/from myrg_info */ - -typedef struct st_mymerge_info /* Struct from h_info */ -{ - ulonglong records; /* Records in database */ - ulonglong deleted; /* Deleted records in database */ - ulonglong recpos; /* Pos for last used record */ - ulonglong data_file_length; - ulonglong dupp_key_pos; /* Offset of the Duplicate key in the merge table */ - uint reclength; /* Recordlength */ - int errkey; /* With key was dupplicated on err */ - uint options; /* HA_OPTION_... used */ - ulong *rec_per_key; /* for sql optimizing */ -} MYMERGE_INFO; - -typedef struct st_myrg_table_info -{ - struct st_myisam_info *table; - ulonglong file_offset; -} MYRG_TABLE; - -typedef struct st_myrg_info -{ - MYRG_TABLE *open_tables,*current_table,*end_table,*last_used_table; - ulonglong records; /* records in tables */ - ulonglong del; /* Removed records */ - ulonglong data_file_length; - ulong cache_size; - uint merge_insert_method; - uint tables,options,reclength,keys; - my_bool cache_in_use; - /* If MERGE children attached to parent. See top comment in ha_myisammrg.cc */ - my_bool children_attached; - LIST open_list; - QUEUE by_key; - ulong *rec_per_key_part; /* for sql optimizing */ - mysql_mutex_t mutex; -} MYRG_INFO; - - - /* Prototypes for merge-functions */ - -extern int myrg_close(MYRG_INFO *file); -extern int myrg_delete(MYRG_INFO *file,const uchar *buff); -extern MYRG_INFO *myrg_open(const char *name,int mode,int wait_if_locked); -extern MYRG_INFO *myrg_parent_open(const char *parent_name, - int (*callback)(void*, const char*), - void *callback_param); -extern int myrg_attach_children(MYRG_INFO *m_info, int handle_locking, - MI_INFO *(*callback)(void*), - void *callback_param, - my_bool *need_compat_check); -extern int myrg_detach_children(MYRG_INFO *m_info); -extern int myrg_panic(enum ha_panic_function function); -extern int myrg_rfirst(MYRG_INFO *file,uchar *buf,int inx); -extern int myrg_rlast(MYRG_INFO *file,uchar *buf,int inx); -extern int myrg_rnext(MYRG_INFO *file,uchar *buf,int inx); -extern int myrg_rprev(MYRG_INFO *file,uchar *buf,int inx); -extern int myrg_rnext_same(MYRG_INFO *file,uchar *buf); -extern int myrg_rkey(MYRG_INFO *info,uchar *buf,int inx, const uchar *key, - key_part_map keypart_map, enum ha_rkey_function search_flag); -extern int myrg_rrnd(MYRG_INFO *file,uchar *buf,ulonglong pos); -extern int myrg_rsame(MYRG_INFO *file,uchar *record,int inx); -extern int myrg_update(MYRG_INFO *file,const uchar *old, - const uchar *new_rec); -extern int myrg_write(MYRG_INFO *info,const uchar *rec); -extern int myrg_status(MYRG_INFO *file,MYMERGE_INFO *x,int flag); -extern int myrg_lock_database(MYRG_INFO *file,int lock_type); -extern int myrg_create(const char *name, const char **table_names, - uint insert_method, my_bool fix_names); -extern int myrg_extra(MYRG_INFO *file,enum ha_extra_function function, - void *extra_arg); -extern int myrg_reset(MYRG_INFO *info); -extern void myrg_extrafunc(MYRG_INFO *info,invalidator_by_filename inv); -extern ha_rows myrg_records_in_range(MYRG_INFO *info, int inx, - const key_range *min_key, - const key_range *max_key, - page_range *pages); -extern ha_rows myrg_records(MYRG_INFO *info); - -extern ulonglong myrg_position(MYRG_INFO *info); -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisampack.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisampack.h deleted file mode 100644 index 6bfe195..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/myisampack.h +++ /dev/null @@ -1,256 +0,0 @@ -#ifndef MYISAMPACK_INCLUDED -#define MYISAMPACK_INCLUDED - -/* Copyright (c) 2000-2002, 2004 MySQL AB, 2009 Sun Microsystems, Inc. - Copyright (c) 2020, MariaDB Corporation. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Storing of values in high byte first order. - - integer keys and file pointers are stored with high byte first to get - better compression -*/ - -/* these two are for uniformity */ -#define mi_sint1korr(A) ((int8)(*A)) -#define mi_uint1korr(A) ((uint8)(*A)) - -#define mi_sint2korr(A) ((int16) (((int16) (((const uchar*) (A))[1])) |\ - ((int16) ((int16) ((const char*) (A))[0]) << 8))) -#define mi_sint3korr(A) ((int32) (((((const uchar*) (A))[0]) & 128) ? \ - (((uint32) 255L << 24) | \ - (((uint32) ((const uchar*) (A))[0]) << 16) |\ - (((uint32) ((const uchar*) (A))[1]) << 8) | \ - ((uint32) ((const uchar*) (A))[2])) : \ - (((uint32) ((const uchar*) (A))[0]) << 16) |\ - (((uint32) ((const uchar*) (A))[1]) << 8) | \ - ((uint32) ((const uchar*) (A))[2]))) -#define mi_sint4korr(A) ((int32) (((int32) (((const uchar*) (A))[3])) |\ - ((int32) (((const uchar*) (A))[2]) << 8) |\ - ((int32) (((const uchar*) (A))[1]) << 16) |\ - ((int32) ((int16) ((const char*) (A))[0]) << 24))) -#define mi_sint8korr(A) ((longlong) mi_uint8korr(A)) -#define mi_uint2korr(A) ((uint16) (((uint16) (((const uchar*) (A))[1])) |\ - ((uint16) (((const uchar*) (A))[0]) << 8))) -#define mi_uint3korr(A) ((uint32) (((uint32) (((const uchar*) (A))[2])) |\ - (((uint32) (((const uchar*) (A))[1])) << 8) |\ - (((uint32) (((const uchar*) (A))[0])) << 16))) -#define mi_uint4korr(A) ((uint32) (((uint32) (((const uchar*) (A))[3])) |\ - (((uint32) (((const uchar*) (A))[2])) << 8) |\ - (((uint32) (((const uchar*) (A))[1])) << 16) |\ - (((uint32) (((const uchar*) (A))[0])) << 24))) - -#ifndef HAVE_mi_uint5korr -#define mi_uint5korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[4])) |\ - (((uint32) (((const uchar*) (A))[3])) << 8) |\ - (((uint32) (((const uchar*) (A))[2])) << 16) |\ - (((uint32) (((const uchar*) (A))[1])) << 24)) |\ - (((ulonglong) (((const uchar*) (A))[0])) << 32)) -#endif /* HAVE_mi_uint5korr */ - -#ifndef HAVE_mi_uint6korr -#define mi_uint6korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[5])) |\ - (((uint32) (((const uchar*) (A))[4])) << 8) |\ - (((uint32) (((const uchar*) (A))[3])) << 16) |\ - (((uint32) (((const uchar*) (A))[2])) << 24)) |\ - (((ulonglong) (((uint32) (((const uchar*) (A))[1])) |\ - (((uint32) (((const uchar*) (A))[0]) << 8)))) <<\ - 32)) -#endif /* HAVE_mi_uint6korr */ - -#ifndef HAVE_mi_uint7korr -#define mi_uint7korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[6])) |\ - (((uint32) (((const uchar*) (A))[5])) << 8) |\ - (((uint32) (((const uchar*) (A))[4])) << 16) |\ - (((uint32) (((const uchar*) (A))[3])) << 24)) |\ - (((ulonglong) (((uint32) (((const uchar*) (A))[2])) |\ - (((uint32) (((const uchar*) (A))[1])) << 8) |\ - (((uint32) (((const uchar*) (A))[0])) << 16))) <<\ - 32)) -#endif /* HAVE_mi_uint7korr */ - -#ifndef HAVE_mi_uint8korr -#define mi_uint8korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[7])) |\ - (((uint32) (((const uchar*) (A))[6])) << 8) |\ - (((uint32) (((const uchar*) (A))[5])) << 16) |\ - (((uint32) (((const uchar*) (A))[4])) << 24)) |\ - (((ulonglong) (((uint32) (((const uchar*) (A))[3])) |\ - (((uint32) (((const uchar*) (A))[2])) << 8) |\ - (((uint32) (((const uchar*) (A))[1])) << 16) |\ - (((uint32) (((const uchar*) (A))[0])) << 24))) <<\ - 32)) -#endif /* HAVE_mi_uint8korr */ - -/* This one is for uniformity */ -#define mi_int1store(T,A) *((uchar*)(T))= (uchar) (A) - -#define mi_int2store(T,A) { uint def_temp= (uint) (A) ;\ - ((uchar*) (T))[1]= (uchar) (def_temp);\ - ((uchar*) (T))[0]= (uchar) (def_temp >> 8); } -#define mi_int3store(T,A) { /*lint -save -e734 */\ - ulong def_temp= (ulong) (A);\ - ((uchar*) (T))[2]= (uchar) (def_temp);\ - ((uchar*) (T))[1]= (uchar) (def_temp >> 8);\ - ((uchar*) (T))[0]= (uchar) (def_temp >> 16);\ - /*lint -restore */} -#define mi_int4store(T,A) { ulong def_temp= (ulong) (A);\ - ((uchar*) (T))[3]= (uchar) (def_temp);\ - ((uchar*) (T))[2]= (uchar) (def_temp >> 8);\ - ((uchar*) (T))[1]= (uchar) (def_temp >> 16);\ - ((uchar*) (T))[0]= (uchar) (def_temp >> 24); } -#define mi_int5store(T,A) { ulong def_temp= (ulong) (A),\ - def_temp2= (ulong) ((A) >> 32);\ - ((uchar*) (T))[4]= (uchar) (def_temp);\ - ((uchar*) (T))[3]= (uchar) (def_temp >> 8);\ - ((uchar*) (T))[2]= (uchar) (def_temp >> 16);\ - ((uchar*) (T))[1]= (uchar) (def_temp >> 24);\ - ((uchar*) (T))[0]= (uchar) (def_temp2); } -#define mi_int6store(T,A) { ulong def_temp= (ulong) (A),\ - def_temp2= (ulong) ((A) >> 32);\ - ((uchar*) (T))[5]= (uchar) (def_temp);\ - ((uchar*) (T))[4]= (uchar) (def_temp >> 8);\ - ((uchar*) (T))[3]= (uchar) (def_temp >> 16);\ - ((uchar*) (T))[2]= (uchar) (def_temp >> 24);\ - ((uchar*) (T))[1]= (uchar) (def_temp2);\ - ((uchar*) (T))[0]= (uchar) (def_temp2 >> 8); } -#define mi_int7store(T,A) { ulong def_temp= (ulong) (A),\ - def_temp2= (ulong) ((A) >> 32);\ - ((uchar*) (T))[6]= (uchar) (def_temp);\ - ((uchar*) (T))[5]= (uchar) (def_temp >> 8);\ - ((uchar*) (T))[4]= (uchar) (def_temp >> 16);\ - ((uchar*) (T))[3]= (uchar) (def_temp >> 24);\ - ((uchar*) (T))[2]= (uchar) (def_temp2);\ - ((uchar*) (T))[1]= (uchar) (def_temp2 >> 8);\ - ((uchar*) (T))[0]= (uchar) (def_temp2 >> 16); } -#define mi_int8store(T,A) { ulong def_temp3= (ulong) (A),\ - def_temp4= (ulong) ((A) >> 32);\ - mi_int4store((uchar*) (T) + 0, def_temp4);\ - mi_int4store((uchar*) (T) + 4, def_temp3); } - -#ifdef WORDS_BIGENDIAN - -#define mi_float4store(T,A) { ((uchar*) (T))[0]= ((uchar*) &A)[0];\ - ((uchar*) (T))[1]= ((uchar*) &A)[1];\ - ((uchar*) (T))[2]= ((uchar*) &A)[2];\ - ((uchar*) (T))[3]= ((uchar*) &A)[3]; } - -#define mi_float4get(V,M) { float def_temp;\ - ((uchar*) &def_temp)[0]= ((const uchar*) (M))[0];\ - ((uchar*) &def_temp)[1]= ((const uchar*) (M))[1]; \ - ((uchar*) &def_temp)[2]= ((const uchar*) (M))[2];\ - ((uchar*) &def_temp)[3]= ((const uchar*) (M))[3];\ - (V)= def_temp; } - -#define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[0];\ - ((uchar*) (T))[1]= ((const uchar*) &V)[1];\ - ((uchar*) (T))[2]= ((const uchar*) &V)[2];\ - ((uchar*) (T))[3]= ((const uchar*) &V)[3];\ - ((uchar*) (T))[4]= ((const uchar*) &V)[4];\ - ((uchar*) (T))[5]= ((const uchar*) &V)[5];\ - ((uchar*) (T))[6]= ((const uchar*) &V)[6];\ - ((uchar*) (T))[7]= ((const uchar*) &V)[7]; } - -#define mi_float8get(V,M) { double def_temp;\ - ((uchar*) &def_temp)[0]= ((const uchar*) (M))[0];\ - ((uchar*) &def_temp)[1]= ((const uchar*) (M))[1];\ - ((uchar*) &def_temp)[2]= ((const uchar*) (M))[2];\ - ((uchar*) &def_temp)[3]= ((const uchar*) (M))[3];\ - ((uchar*) &def_temp)[4]= ((const uchar*) (M))[4];\ - ((uchar*) &def_temp)[5]= ((const uchar*) (M))[5];\ - ((uchar*) &def_temp)[6]= ((const uchar*) (M))[6];\ - ((uchar*) &def_temp)[7]= ((const uchar*) (M))[7]; \ - (V)= def_temp; } -#else - -#define mi_float4store(T,A) { ((uchar*) (T))[0]= ((const uchar*) &A)[3];\ - ((uchar*) (T))[1]= ((const uchar*) &A)[2];\ - ((uchar*) (T))[2]= ((const uchar*) &A)[1];\ - ((uchar*) (T))[3]= ((const uchar*) &A)[0]; } - -#define mi_float4get(V,M) { float def_temp;\ - ((uchar*) &def_temp)[0]= ((const uchar*) (M))[3];\ - ((uchar*) &def_temp)[1]= ((const uchar*) (M))[2];\ - ((uchar*) &def_temp)[2]= ((const uchar*) (M))[1];\ - ((uchar*) &def_temp)[3]= ((const uchar*) (M))[0];\ - (V)= def_temp; } - -#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) -#define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[3];\ - ((uchar*) (T))[1]= ((const uchar*) &V)[2];\ - ((uchar*) (T))[2]= ((const uchar*) &V)[1];\ - ((uchar*) (T))[3]= ((const uchar*) &V)[0];\ - ((uchar*) (T))[4]= ((const uchar*) &V)[7];\ - ((uchar*) (T))[5]= ((const uchar*) &V)[6];\ - ((uchar*) (T))[6]= ((const uchar*) &V)[5];\ - ((uchar*) (T))[7]= ((const uchar*) &V)[4];} - -#define mi_float8get(V,M) { double def_temp;\ - ((uchar*) &def_temp)[0]= ((const uchar*) (M))[3];\ - ((uchar*) &def_temp)[1]= ((const uchar*) (M))[2];\ - ((uchar*) &def_temp)[2]= ((const uchar*) (M))[1];\ - ((uchar*) &def_temp)[3]= ((const uchar*) (M))[0];\ - ((uchar*) &def_temp)[4]= ((const uchar*) (M))[7];\ - ((uchar*) &def_temp)[5]= ((const uchar*) (M))[6];\ - ((uchar*) &def_temp)[6]= ((const uchar*) (M))[5];\ - ((uchar*) &def_temp)[7]= ((const uchar*) (M))[4];\ - (V)= def_temp; } - -#else -#define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[7];\ - ((uchar*) (T))[1]= ((const uchar*) &V)[6];\ - ((uchar*) (T))[2]= ((const uchar*) &V)[5];\ - ((uchar*) (T))[3]= ((const uchar*) &V)[4];\ - ((uchar*) (T))[4]= ((const uchar*) &V)[3];\ - ((uchar*) (T))[5]= ((const uchar*) &V)[2];\ - ((uchar*) (T))[6]= ((const uchar*) &V)[1];\ - ((uchar*) (T))[7]= ((const uchar*) &V)[0];} - -#define mi_float8get(V,M) { double def_temp;\ - ((uchar*) &def_temp)[0]= ((const uchar*) (M))[7];\ - ((uchar*) &def_temp)[1]= ((const uchar*) (M))[6];\ - ((uchar*) &def_temp)[2]= ((const uchar*) (M))[5];\ - ((uchar*) &def_temp)[3]= ((const uchar*) (M))[4];\ - ((uchar*) &def_temp)[4]= ((const uchar*) (M))[3];\ - ((uchar*) &def_temp)[5]= ((const uchar*) (M))[2];\ - ((uchar*) &def_temp)[6]= ((const uchar*) (M))[1];\ - ((uchar*) &def_temp)[7]= ((const uchar*) (M))[0];\ - (V)= def_temp; } -#endif /* __FLOAT_WORD_ORDER */ -#endif /* WORDS_BIGENDIAN */ - -/* Fix to avoid warnings when sizeof(ha_rows) == sizeof(long) */ - -#ifdef BIG_TABLES -#define mi_rowstore(T,A) mi_int8store(T, A) -#define mi_rowkorr(T) mi_uint8korr(T) -#else -#define mi_rowstore(T,A) { mi_int4store(T, 0);\ - mi_int4store(((uchar*) (T) + 4), A); } -#define mi_rowkorr(T) mi_uint4korr((const uchar*) (T) + 4) -#endif - -#if SIZEOF_OFF_T > 4 -#define mi_sizestore(T,A) mi_int8store(T, A) -#define mi_sizekorr(T) mi_uint8korr(T) -#else -#define mi_sizestore(T,A) { if ((A) == HA_OFFSET_ERROR)\ - bfill((char*) (T), 8, 255);\ - else { mi_int4store((T), 0);\ - mi_int4store(((T) + 4), A); }} -#define mi_sizekorr(T) mi_uint4korr((const uchar*) (T) + 4) -#endif -#endif /* MYISAMPACK_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysql_async.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysql_async.h deleted file mode 100644 index 3e4cb35..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysql_async.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright (C) 2012 MariaDB Services and Kristian Nielsen - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Common definitions for MariaDB non-blocking client library. */ - -#ifndef MYSQL_ASYNC_H -#define MYSQL_ASYNC_H - -extern int my_connect_async(struct mysql_async_context *b, my_socket fd, - const struct sockaddr *name, uint namelen, - int vio_timeout); -extern ssize_t my_recv_async(struct mysql_async_context *b, my_socket fd, - unsigned char *buf, size_t size, int timeout); -extern ssize_t my_send_async(struct mysql_async_context *b, my_socket fd, - const unsigned char *buf, size_t size, - int timeout); -extern my_bool my_io_wait_async(struct mysql_async_context *b, - enum enum_vio_io_event event, int timeout); -#ifdef HAVE_OPENSSL -extern int my_ssl_read_async(struct mysql_async_context *b, SSL *ssl, - void *buf, int size); -extern int my_ssl_write_async(struct mysql_async_context *b, SSL *ssl, - const void *buf, int size); -#endif - -#endif /* MYSQL_ASYNC_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld.h deleted file mode 100644 index e8dd570..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld.h +++ /dev/null @@ -1,961 +0,0 @@ -/* Copyright (c) 2006, 2016, Oracle and/or its affiliates. - Copyright (c) 2010, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef MYSQLD_INCLUDED -#define MYSQLD_INCLUDED - -#include "sql_basic_types.h" /* query_id_t */ -#include "sql_mode.h" /* Sql_mode_dependency */ -#include "sql_plugin.h" -#include "sql_bitmap.h" /* Bitmap */ -#include "my_decimal.h" /* my_decimal */ -#include "mysql_com.h" /* SERVER_VERSION_LENGTH */ -#include "my_counter.h" -#include "mysql/psi/mysql_file.h" /* MYSQL_FILE */ -#include "mysql/psi/mysql_socket.h" /* MYSQL_SOCKET */ -#include "sql_list.h" /* I_List */ -#include "sql_cmd.h" -#include -#include "my_pthread.h" -#include "my_rdtsc.h" - -class THD; -class CONNECT; -struct handlerton; -class Time_zone; - -struct scheduler_functions; - -typedef struct st_mysql_show_var SHOW_VAR; - -/* Bits from testflag */ -#define TEST_PRINT_CACHED_TABLES 1U -#define TEST_NO_KEY_GROUP 2U -#define TEST_MIT_THREAD 4U -#define TEST_BLOCKING 8U -#define TEST_KEEP_TMP_TABLES 16U -#define TEST_READCHECK 64U /**< Force use of readcheck */ -#define TEST_NO_EXTRA 128U -#define TEST_CORE_ON_SIGNAL 256U /**< Give core if signal */ -#define TEST_SIGINT 1024U /**< Allow sigint on threads */ -#define TEST_SYNCHRONIZATION 2048U /**< get server to do sleep in - some places */ - -/* Keep things compatible */ -#define OPT_DEFAULT SHOW_OPT_DEFAULT -#define OPT_SESSION SHOW_OPT_SESSION -#define OPT_GLOBAL SHOW_OPT_GLOBAL - -extern MYSQL_PLUGIN_IMPORT MY_TIMER_INFO sys_timer_info; - -/* - Values for --slave-parallel-mode - Must match order in slave_parallel_mode_typelib in sys_vars.cc. -*/ -enum enum_slave_parallel_mode { - SLAVE_PARALLEL_NONE, - SLAVE_PARALLEL_MINIMAL, - SLAVE_PARALLEL_CONSERVATIVE, - SLAVE_PARALLEL_OPTIMISTIC, - SLAVE_PARALLEL_AGGRESSIVE -}; - -/* Function prototypes */ -void kill_mysql(THD *thd); -void close_connection(THD *thd, uint sql_errno= 0); -void handle_connection_in_main_thread(CONNECT *thd); -void create_thread_to_handle_connection(CONNECT *connect); -void unlink_thd(THD *thd); -void refresh_status(THD *thd); -bool is_secure_file_path(char *path); -extern void init_net_server_extension(THD *thd); -extern void handle_accepted_socket(MYSQL_SOCKET new_sock, MYSQL_SOCKET sock); -extern void create_new_thread(CONNECT *connect); - -extern void ssl_acceptor_stats_update(int sslaccept_ret); -extern int reinit_ssl(); - -extern "C" MYSQL_PLUGIN_IMPORT CHARSET_INFO *system_charset_info; -extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *files_charset_info ; -extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *national_charset_info; -extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *table_alias_charset; - -/** - Character set of the buildin error messages loaded from errmsg.sys. -*/ -extern CHARSET_INFO *error_message_charset_info; - -extern CHARSET_INFO *character_set_filesystem; - -extern MY_BITMAP temp_pool; -extern bool opt_large_files; -extern bool opt_update_log, opt_bin_log, opt_error_log, opt_bin_log_compress; -extern uint opt_bin_log_compress_min_len; -extern my_bool opt_log, opt_bootstrap; -extern my_bool opt_backup_history_log; -extern my_bool opt_backup_progress_log; -extern my_bool opt_support_flashback; -extern ulonglong log_output_options; -extern ulong log_backup_output_options; -extern bool opt_disable_networking, opt_skip_show_db; -extern bool opt_skip_name_resolve; -extern bool opt_ignore_builtin_innodb; -extern my_bool opt_character_set_client_handshake; -extern my_bool debug_assert_on_not_freed_memory; -extern MYSQL_PLUGIN_IMPORT bool volatile abort_loop; -extern Atomic_counter connection_count; -extern my_bool opt_safe_user_create; -extern my_bool opt_safe_show_db, opt_local_infile, opt_myisam_use_mmap; -extern my_bool opt_slave_compressed_protocol, use_temp_pool; -extern ulong slave_exec_mode_options, slave_ddl_exec_mode_options; -extern ulong slave_retried_transactions; -extern ulong transactions_multi_engine; -extern ulong rpl_transactions_multi_engine; -extern ulong transactions_gtid_foreign_engine; -extern ulong slave_run_triggers_for_rbr; -extern ulonglong slave_type_conversions_options; -extern my_bool read_only, opt_readonly; -extern MYSQL_PLUGIN_IMPORT my_bool lower_case_file_system; -extern my_bool opt_enable_named_pipe, opt_sync_frm, opt_allow_suspicious_udfs; -extern my_bool opt_secure_auth; -extern my_bool opt_require_secure_transport; -extern const char *current_dbug_option; -extern char* opt_secure_file_priv; -extern char* opt_secure_backup_file_priv; -extern size_t opt_secure_backup_file_priv_len; -extern my_bool sp_automatic_privileges, opt_noacl; -extern ulong use_stat_tables; -extern my_bool opt_old_style_user_limits, trust_function_creators; -extern uint opt_crash_binlog_innodb; -extern const char *shared_memory_base_name; -extern MYSQL_PLUGIN_IMPORT char *mysqld_unix_port; -extern my_bool opt_enable_shared_memory; -extern ulong opt_replicate_events_marked_for_skip; -extern char *default_tz_name; -extern Time_zone *default_tz; -extern char *my_bind_addr_str; -extern int server_socket_ai_family; -extern char *default_storage_engine, *default_tmp_storage_engine; -extern char *enforced_storage_engine; -extern char *gtid_pos_auto_engines; -extern plugin_ref *opt_gtid_pos_auto_plugins; -extern bool opt_endinfo, using_udf_functions; -extern my_bool locked_in_memory; -extern bool opt_using_transactions; -extern ulong current_pid; -extern ulong expire_logs_days; -extern my_bool relay_log_recovery; -extern uint sync_binlog_period, sync_relaylog_period, - sync_relayloginfo_period, sync_masterinfo_period; -extern ulong opt_tc_log_size, tc_log_max_pages_used, tc_log_page_size; -extern ulong tc_log_page_waits; -extern my_bool relay_log_purge, opt_innodb_safe_binlog, opt_innodb; -extern my_bool relay_log_recovery; -extern uint select_errors,ha_open_options; -extern ulonglong test_flags; -extern uint protocol_version, dropping_tables; -extern MYSQL_PLUGIN_IMPORT uint mysqld_port; -extern ulong delay_key_write_options; -extern char *opt_logname, *opt_slow_logname, *opt_bin_logname, - *opt_relay_logname; -extern char *opt_binlog_index_name; -extern char *opt_backup_history_logname, *opt_backup_progress_logname, - *opt_backup_settings_name; -extern const char *log_output_str; -extern const char *log_backup_output_str; - -/* System Versioning begin */ -enum vers_system_time_t -{ - SYSTEM_TIME_UNSPECIFIED = 0, - SYSTEM_TIME_AS_OF, - SYSTEM_TIME_FROM_TO, - SYSTEM_TIME_BETWEEN, - SYSTEM_TIME_BEFORE, // used for DELETE HISTORY ... BEFORE - SYSTEM_TIME_HISTORY, // used for DELETE HISTORY - SYSTEM_TIME_ALL -}; - -struct vers_asof_timestamp_t -{ - ulong type; - MYSQL_TIME ltime; -}; - -enum vers_alter_history_enum -{ - VERS_ALTER_HISTORY_ERROR= 0, - VERS_ALTER_HISTORY_KEEP -}; -/* System Versioning end */ - -extern char *mysql_home_ptr, *pidfile_name_ptr; -extern MYSQL_PLUGIN_IMPORT char glob_hostname[FN_REFLEN]; -extern char mysql_home[FN_REFLEN]; -extern char pidfile_name[FN_REFLEN], system_time_zone[30], *opt_init_file; -extern char default_logfile_name[FN_REFLEN]; -extern char log_error_file[FN_REFLEN], *opt_tc_log_file; -extern const double log_10[309]; -extern ulonglong keybuff_size; -extern ulonglong thd_startup_options; -extern my_thread_id global_thread_id; -extern ulong binlog_cache_use, binlog_cache_disk_use; -extern ulong binlog_stmt_cache_use, binlog_stmt_cache_disk_use; -extern ulong aborted_threads, aborted_connects, aborted_connects_preauth; -extern ulong delayed_insert_timeout; -extern ulong delayed_insert_limit, delayed_queue_size; -extern ulong delayed_insert_threads, delayed_insert_writes; -extern ulong delayed_rows_in_use,delayed_insert_errors; -extern Atomic_counter slave_open_temp_tables; -extern ulonglong query_cache_size; -extern ulong query_cache_limit; -extern ulong query_cache_min_res_unit; -extern ulong slow_launch_threads, slow_launch_time; -extern MYSQL_PLUGIN_IMPORT ulong max_connections; -extern uint max_digest_length; -extern ulong max_connect_errors, connect_timeout; -extern uint max_password_errors; -extern my_bool slave_allow_batching; -extern my_bool allow_slave_start; -extern LEX_CSTRING reason_slave_blocked; -extern ulong slave_trans_retries; -extern ulong slave_trans_retry_interval; -extern uint slave_net_timeout; -extern int max_user_connections; -extern ulong what_to_log,flush_time; -extern uint max_prepared_stmt_count, prepared_stmt_count; -extern MYSQL_PLUGIN_IMPORT ulong open_files_limit; -extern ulonglong binlog_cache_size, binlog_stmt_cache_size, binlog_file_cache_size; -extern ulonglong max_binlog_cache_size, max_binlog_stmt_cache_size; -extern ulong max_binlog_size; -extern ulong slave_max_allowed_packet; -extern ulong opt_binlog_rows_event_max_size; -extern ulong binlog_row_metadata; -extern ulong thread_cache_size; -extern ulong stored_program_cache_size; -extern ulong opt_slave_parallel_threads; -extern ulong opt_slave_domain_parallel_threads; -extern ulong opt_slave_parallel_max_queued; -extern ulong opt_slave_parallel_mode; -extern ulong opt_binlog_commit_wait_count; -extern ulong opt_binlog_commit_wait_usec; -extern my_bool opt_gtid_ignore_duplicates; -extern uint opt_gtid_cleanup_batch_size; -extern ulong back_log; -extern ulong executed_events; -extern char language[FN_REFLEN]; -extern "C" MYSQL_PLUGIN_IMPORT ulong server_id; -extern ulong concurrency; -extern time_t server_start_time, flush_status_time; -extern char *opt_mysql_tmpdir, mysql_charsets_dir[]; -extern size_t mysql_unpacked_real_data_home_len; -extern MYSQL_PLUGIN_IMPORT MY_TMPDIR mysql_tmpdir_list; -extern const char *first_keyword, *delayed_user; -extern MYSQL_PLUGIN_IMPORT const char *my_localhost; -extern MYSQL_PLUGIN_IMPORT const char **errmesg; /* Error messages */ -extern const char *myisam_recover_options_str; -extern const LEX_CSTRING in_left_expr_name, in_additional_cond, in_having_cond; -extern SHOW_VAR status_vars[]; -extern struct system_variables max_system_variables; -extern struct system_status_var global_status_var; -extern struct my_rnd_struct sql_rand; -extern const char *opt_date_time_formats[]; -extern handlerton *partition_hton; -extern handlerton *myisam_hton; -extern handlerton *heap_hton; -extern const char *load_default_groups[]; -extern struct my_option my_long_options[]; -int handle_early_options(); -extern int MYSQL_PLUGIN_IMPORT mysqld_server_started; -extern int mysqld_server_initialized; -extern "C" MYSQL_PLUGIN_IMPORT int orig_argc; -extern "C" MYSQL_PLUGIN_IMPORT char **orig_argv; -extern pthread_attr_t connection_attrib; -extern my_bool old_mode; -extern LEX_STRING opt_init_connect, opt_init_slave; -extern char err_shared_dir[]; -extern ulong connection_errors_select; -extern ulong connection_errors_accept; -extern ulong connection_errors_tcpwrap; -extern ulong connection_errors_internal; -extern ulong connection_errors_max_connection; -extern ulong connection_errors_peer_addr; -extern ulong log_warnings; -extern my_bool encrypt_binlog; -extern my_bool encrypt_tmp_disk_tables, encrypt_tmp_files; -extern ulong encryption_algorithm; -extern const char *encryption_algorithm_names[]; -extern long opt_secure_timestamp; -extern uint default_password_lifetime; -extern my_bool disconnect_on_expired_password; - -enum secure_timestamp { SECTIME_NO, SECTIME_SUPER, SECTIME_REPL, SECTIME_YES }; - -#ifdef HAVE_MMAP -extern PSI_mutex_key key_PAGE_lock, key_LOCK_sync, key_LOCK_active, - key_LOCK_pool, key_LOCK_pending_checkpoint; -#endif /* HAVE_MMAP */ - -#ifdef HAVE_OPENSSL -extern PSI_mutex_key key_LOCK_des_key_file; -#endif - -extern PSI_mutex_key key_BINLOG_LOCK_index, key_BINLOG_LOCK_xid_list, - key_BINLOG_LOCK_binlog_background_thread, - key_LOCK_binlog_end_pos, - key_delayed_insert_mutex, key_hash_filo_lock, key_LOCK_active_mi, - key_LOCK_crypt, key_LOCK_delayed_create, - key_LOCK_delayed_insert, key_LOCK_delayed_status, key_LOCK_error_log, - key_LOCK_gdl, key_LOCK_global_system_variables, - key_LOCK_logger, key_LOCK_manager, - key_LOCK_prepared_stmt_count, - key_LOCK_rpl_status, key_LOCK_server_started, - key_LOCK_status, - key_LOCK_thd_data, key_LOCK_thd_kill, - key_LOCK_user_conn, key_LOG_LOCK_log, - key_master_info_data_lock, key_master_info_run_lock, - key_master_info_sleep_lock, key_master_info_start_stop_lock, - key_mutex_slave_reporting_capability_err_lock, key_relay_log_info_data_lock, - key_relay_log_info_log_space_lock, key_relay_log_info_run_lock, - key_rpl_group_info_sleep_lock, - key_structure_guard_mutex, key_TABLE_SHARE_LOCK_ha_data, - key_LOCK_start_thread, - key_LOCK_error_messages, - key_PARTITION_LOCK_auto_inc; -extern PSI_mutex_key key_RELAYLOG_LOCK_index; -extern PSI_mutex_key key_LOCK_relaylog_end_pos; -extern PSI_mutex_key key_LOCK_slave_state, key_LOCK_binlog_state, - key_LOCK_rpl_thread, key_LOCK_rpl_thread_pool, key_LOCK_parallel_entry; - -extern PSI_mutex_key key_TABLE_SHARE_LOCK_share, key_LOCK_stats, - key_LOCK_global_user_client_stats, key_LOCK_global_table_stats, - key_LOCK_global_index_stats, key_LOCK_wakeup_ready, key_LOCK_wait_commit, - key_TABLE_SHARE_LOCK_rotation; -extern PSI_mutex_key key_LOCK_gtid_waiting; - -extern PSI_rwlock_key key_rwlock_LOCK_grant, key_rwlock_LOCK_logger, - key_rwlock_LOCK_sys_init_connect, key_rwlock_LOCK_sys_init_slave, - key_rwlock_LOCK_system_variables_hash, key_rwlock_query_cache_query_lock, - key_LOCK_SEQUENCE, - key_rwlock_LOCK_vers_stats, key_rwlock_LOCK_stat_serial, - key_rwlock_THD_list; - -#ifdef HAVE_MMAP -extern PSI_cond_key key_PAGE_cond, key_COND_active, key_COND_pool; -#endif /* HAVE_MMAP */ - -extern PSI_cond_key key_BINLOG_COND_xid_list, key_BINLOG_update_cond, - key_BINLOG_COND_binlog_background_thread, - key_BINLOG_COND_binlog_background_thread_end, - key_COND_cache_status_changed, key_COND_manager, - key_COND_rpl_status, key_COND_server_started, - key_delayed_insert_cond, key_delayed_insert_cond_client, - key_item_func_sleep_cond, key_master_info_data_cond, - key_master_info_start_cond, key_master_info_stop_cond, - key_master_info_sleep_cond, - key_relay_log_info_data_cond, key_relay_log_info_log_space_cond, - key_relay_log_info_start_cond, key_relay_log_info_stop_cond, - key_rpl_group_info_sleep_cond, - key_TABLE_SHARE_cond, key_user_level_lock_cond, - key_COND_start_thread; -extern PSI_cond_key key_RELAYLOG_COND_relay_log_updated, - key_RELAYLOG_COND_bin_log_updated, key_COND_wakeup_ready, - key_COND_wait_commit; -extern PSI_cond_key key_RELAYLOG_COND_queue_busy; -extern PSI_cond_key key_TC_LOG_MMAP_COND_queue_busy; -extern PSI_cond_key key_COND_rpl_thread, key_COND_rpl_thread_queue, - key_COND_rpl_thread_stop, key_COND_rpl_thread_pool, - key_COND_parallel_entry, key_COND_group_commit_orderer; -extern PSI_cond_key key_COND_wait_gtid, key_COND_gtid_ignore_duplicates; -extern PSI_cond_key key_TABLE_SHARE_COND_rotation; - -extern PSI_thread_key key_thread_delayed_insert, - key_thread_handle_manager, key_thread_kill_server, key_thread_main, - key_thread_one_connection, key_thread_signal_hand, - key_thread_slave_background, key_rpl_parallel_thread; - -extern PSI_file_key key_file_binlog, key_file_binlog_cache, - key_file_binlog_index, key_file_binlog_index_cache, key_file_casetest, - key_file_dbopt, key_file_des_key_file, key_file_ERRMSG, key_select_to_file, - key_file_fileparser, key_file_frm, key_file_global_ddl_log, key_file_load, - key_file_loadfile, key_file_log_event_data, key_file_log_event_info, - key_file_master_info, key_file_misc, key_file_partition_ddl_log, - key_file_pid, key_file_relay_log_info, key_file_send_file, key_file_tclog, - key_file_trg, key_file_trn, key_file_init; -extern PSI_file_key key_file_query_log, key_file_slow_log; -extern PSI_file_key key_file_relaylog, key_file_relaylog_index, - key_file_relaylog_cache, key_file_relaylog_index_cache; -extern PSI_socket_key key_socket_tcpip, key_socket_unix, - key_socket_client_connection; -extern PSI_file_key key_file_binlog_state; - -#ifdef HAVE_PSI_INTERFACE -void init_server_psi_keys(); -#endif /* HAVE_PSI_INTERFACE */ - -extern PSI_memory_key key_memory_locked_table_list; -extern PSI_memory_key key_memory_locked_thread_list; -extern PSI_memory_key key_memory_thd_transactions; -extern PSI_memory_key key_memory_delegate; -extern PSI_memory_key key_memory_acl_mem; -extern PSI_memory_key key_memory_acl_memex; -extern PSI_memory_key key_memory_acl_cache; -extern PSI_memory_key key_memory_thd_main_mem_root; -extern PSI_memory_key key_memory_help; -extern PSI_memory_key key_memory_frm; -extern PSI_memory_key key_memory_table_share; -extern PSI_memory_key key_memory_gdl; -extern PSI_memory_key key_memory_table_triggers_list; -extern PSI_memory_key key_memory_prepared_statement_map; -extern PSI_memory_key key_memory_prepared_statement_main_mem_root; -extern PSI_memory_key key_memory_protocol_rset_root; -extern PSI_memory_key key_memory_warning_info_warn_root; -extern PSI_memory_key key_memory_sp_cache; -extern PSI_memory_key key_memory_sp_head_main_root; -extern PSI_memory_key key_memory_sp_head_execute_root; -extern PSI_memory_key key_memory_sp_head_call_root; -extern PSI_memory_key key_memory_table_mapping_root; -extern PSI_memory_key key_memory_quick_range_select_root; -extern PSI_memory_key key_memory_quick_index_merge_root; -extern PSI_memory_key key_memory_quick_ror_intersect_select_root; -extern PSI_memory_key key_memory_quick_ror_union_select_root; -extern PSI_memory_key key_memory_quick_group_min_max_select_root; -extern PSI_memory_key key_memory_test_quick_select_exec; -extern PSI_memory_key key_memory_prune_partitions_exec; -extern PSI_memory_key key_memory_binlog_recover_exec; -extern PSI_memory_key key_memory_blob_mem_storage; - -extern PSI_memory_key key_memory_Sys_var_charptr_value; -extern PSI_memory_key key_memory_THD_db; -extern PSI_memory_key key_memory_user_var_entry; -extern PSI_memory_key key_memory_user_var_entry_value; -extern PSI_memory_key key_memory_Slave_job_group_group_relay_log_name; -extern PSI_memory_key key_memory_Relay_log_info_group_relay_log_name; -extern PSI_memory_key key_memory_binlog_cache_mngr; -extern PSI_memory_key key_memory_Row_data_memory_memory; -extern PSI_memory_key key_memory_errmsgs; -extern PSI_memory_key key_memory_Event_queue_element_for_exec_names; -extern PSI_memory_key key_memory_Event_scheduler_scheduler_param; -extern PSI_memory_key key_memory_Gis_read_stream_err_msg; -extern PSI_memory_key key_memory_Geometry_objects_data; -extern PSI_memory_key key_memory_host_cache_hostname; -extern PSI_memory_key key_memory_User_level_lock; -extern PSI_memory_key key_memory_Filesort_info_record_pointers; -extern PSI_memory_key key_memory_Sort_param_tmp_buffer; -extern PSI_memory_key key_memory_Filesort_info_merge; -extern PSI_memory_key key_memory_Filesort_buffer_sort_keys; -extern PSI_memory_key key_memory_handler_errmsgs; -extern PSI_memory_key key_memory_handlerton; -extern PSI_memory_key key_memory_XID; -extern PSI_memory_key key_memory_MYSQL_LOCK; -extern PSI_memory_key key_memory_MYSQL_LOG_name; -extern PSI_memory_key key_memory_TC_LOG_MMAP_pages; -extern PSI_memory_key key_memory_my_str_malloc; -extern PSI_memory_key key_memory_MYSQL_BIN_LOG_basename; -extern PSI_memory_key key_memory_MYSQL_BIN_LOG_index; -extern PSI_memory_key key_memory_MYSQL_RELAY_LOG_basename; -extern PSI_memory_key key_memory_MYSQL_RELAY_LOG_index; -extern PSI_memory_key key_memory_rpl_filter; -extern PSI_memory_key key_memory_Security_context; -extern PSI_memory_key key_memory_NET_buff; -extern PSI_memory_key key_memory_NET_compress_packet; -extern PSI_memory_key key_memory_my_bitmap_map; -extern PSI_memory_key key_memory_QUICK_RANGE_SELECT_mrr_buf_desc; -extern PSI_memory_key key_memory_TABLE_RULE_ENT; -extern PSI_memory_key key_memory_Mutex_cond_array_Mutex_cond; -extern PSI_memory_key key_memory_Owned_gtids_sidno_to_hash; -extern PSI_memory_key key_memory_Sid_map_Node; -extern PSI_memory_key key_memory_bison_stack; -extern PSI_memory_key key_memory_TABLE_sort_io_cache; -extern PSI_memory_key key_memory_DATE_TIME_FORMAT; -extern PSI_memory_key key_memory_DDL_LOG_MEMORY_ENTRY; -extern PSI_memory_key key_memory_ST_SCHEMA_TABLE; -extern PSI_memory_key key_memory_ignored_db; -extern PSI_memory_key key_memory_SLAVE_INFO; -extern PSI_memory_key key_memory_log_event_old; -extern PSI_memory_key key_memory_HASH_ROW_ENTRY; -extern PSI_memory_key key_memory_table_def_memory; -extern PSI_memory_key key_memory_MPVIO_EXT_auth_info; -extern PSI_memory_key key_memory_LOG_POS_COORD; -extern PSI_memory_key key_memory_XID_STATE; -extern PSI_memory_key key_memory_Rpl_info_file_buffer; -extern PSI_memory_key key_memory_Rpl_info_table; -extern PSI_memory_key key_memory_binlog_pos; -extern PSI_memory_key key_memory_db_worker_hash_entry; -extern PSI_memory_key key_memory_rpl_slave_command_buffer; -extern PSI_memory_key key_memory_binlog_ver_1_event; -extern PSI_memory_key key_memory_rpl_slave_check_temp_dir; -extern PSI_memory_key key_memory_TABLE; -extern PSI_memory_key key_memory_binlog_statement_buffer; -extern PSI_memory_key key_memory_user_conn; -extern PSI_memory_key key_memory_dboptions_hash; -extern PSI_memory_key key_memory_hash_index_key_buffer; -extern PSI_memory_key key_memory_THD_handler_tables_hash; -extern PSI_memory_key key_memory_JOIN_CACHE; -extern PSI_memory_key key_memory_READ_INFO; -extern PSI_memory_key key_memory_partition_syntax_buffer; -extern PSI_memory_key key_memory_global_system_variables; -extern PSI_memory_key key_memory_THD_variables; -extern PSI_memory_key key_memory_PROFILE; -extern PSI_memory_key key_memory_LOG_name; -extern PSI_memory_key key_memory_string_iterator; -extern PSI_memory_key key_memory_frm_extra_segment_buff; -extern PSI_memory_key key_memory_frm_form_pos; -extern PSI_memory_key key_memory_frm_string; -extern PSI_memory_key key_memory_Unique_sort_buffer; -extern PSI_memory_key key_memory_Unique_merge_buffer; -extern PSI_memory_key key_memory_shared_memory_name; -extern PSI_memory_key key_memory_opt_bin_logname; -extern PSI_memory_key key_memory_Query_cache; -extern PSI_memory_key key_memory_READ_RECORD_cache; -extern PSI_memory_key key_memory_Quick_ranges; -extern PSI_memory_key key_memory_File_query_log_name; -extern PSI_memory_key key_memory_Table_trigger_dispatcher; -extern PSI_memory_key key_memory_show_slave_status_io_gtid_set; -extern PSI_memory_key key_memory_write_set_extraction; -extern PSI_memory_key key_memory_thd_timer; -extern PSI_memory_key key_memory_THD_Session_tracker; -extern PSI_memory_key key_memory_THD_Session_sysvar_resource_manager; -extern PSI_memory_key key_memory_get_all_tables; -extern PSI_memory_key key_memory_fill_schema_schemata; -extern PSI_memory_key key_memory_native_functions; -extern PSI_memory_key key_memory_JSON; - -/* - MAINTAINER: Please keep this list in order, to limit merge collisions. - Hint: grep PSI_stage_info | sort -u -*/ -extern PSI_stage_info stage_apply_event; -extern PSI_stage_info stage_after_create; -extern PSI_stage_info stage_after_opening_tables; -extern PSI_stage_info stage_after_table_lock; -extern PSI_stage_info stage_allocating_local_table; -extern PSI_stage_info stage_alter_inplace_prepare; -extern PSI_stage_info stage_alter_inplace; -extern PSI_stage_info stage_alter_inplace_commit; -extern PSI_stage_info stage_after_apply_event; -extern PSI_stage_info stage_changing_master; -extern PSI_stage_info stage_checking_master_version; -extern PSI_stage_info stage_checking_permissions; -extern PSI_stage_info stage_checking_privileges_on_cached_query; -extern PSI_stage_info stage_checking_query_cache_for_query; -extern PSI_stage_info stage_cleaning_up; -extern PSI_stage_info stage_closing_tables; -extern PSI_stage_info stage_connecting_to_master; -extern PSI_stage_info stage_converting_heap_to_myisam; -extern PSI_stage_info stage_copying_to_group_table; -extern PSI_stage_info stage_copying_to_tmp_table; -extern PSI_stage_info stage_copy_to_tmp_table; -extern PSI_stage_info stage_creating_delayed_handler; -extern PSI_stage_info stage_creating_sort_index; -extern PSI_stage_info stage_creating_table; -extern PSI_stage_info stage_creating_tmp_table; -extern PSI_stage_info stage_deleting_from_main_table; -extern PSI_stage_info stage_deleting_from_reference_tables; -extern PSI_stage_info stage_discard_or_import_tablespace; -extern PSI_stage_info stage_end; -extern PSI_stage_info stage_enabling_keys; -extern PSI_stage_info stage_executing; -extern PSI_stage_info stage_execution_of_init_command; -extern PSI_stage_info stage_explaining; -extern PSI_stage_info stage_finding_key_cache; -extern PSI_stage_info stage_finished_reading_one_binlog_switching_to_next_binlog; -extern PSI_stage_info stage_flushing_relay_log_and_master_info_repository; -extern PSI_stage_info stage_flushing_relay_log_info_file; -extern PSI_stage_info stage_freeing_items; -extern PSI_stage_info stage_fulltext_initialization; -extern PSI_stage_info stage_got_handler_lock; -extern PSI_stage_info stage_got_old_table; -extern PSI_stage_info stage_init; -extern PSI_stage_info stage_init_update; -extern PSI_stage_info stage_insert; -extern PSI_stage_info stage_invalidating_query_cache_entries_table; -extern PSI_stage_info stage_invalidating_query_cache_entries_table_list; -extern PSI_stage_info stage_killing_slave; -extern PSI_stage_info stage_logging_slow_query; -extern PSI_stage_info stage_making_temp_file_append_before_load_data; -extern PSI_stage_info stage_making_temp_file_create_before_load_data; -extern PSI_stage_info stage_manage_keys; -extern PSI_stage_info stage_master_has_sent_all_binlog_to_slave; -extern PSI_stage_info stage_opening_tables; -extern PSI_stage_info stage_optimizing; -extern PSI_stage_info stage_preparing; -extern PSI_stage_info stage_purging_old_relay_logs; -extern PSI_stage_info stage_query_end; -extern PSI_stage_info stage_starting_cleanup; -extern PSI_stage_info stage_rollback; -extern PSI_stage_info stage_rollback_implicit; -extern PSI_stage_info stage_commit; -extern PSI_stage_info stage_commit_implicit; -extern PSI_stage_info stage_queueing_master_event_to_the_relay_log; -extern PSI_stage_info stage_reading_event_from_the_relay_log; -extern PSI_stage_info stage_recreating_table; -extern PSI_stage_info stage_registering_slave_on_master; -extern PSI_stage_info stage_removing_duplicates; -extern PSI_stage_info stage_removing_tmp_table; -extern PSI_stage_info stage_rename; -extern PSI_stage_info stage_rename_result_table; -extern PSI_stage_info stage_requesting_binlog_dump; -extern PSI_stage_info stage_reschedule; -extern PSI_stage_info stage_searching_rows_for_update; -extern PSI_stage_info stage_sending_binlog_event_to_slave; -extern PSI_stage_info stage_sending_cached_result_to_client; -extern PSI_stage_info stage_sending_data; -extern PSI_stage_info stage_setup; -extern PSI_stage_info stage_slave_has_read_all_relay_log; -extern PSI_stage_info stage_show_explain; -extern PSI_stage_info stage_sorting; -extern PSI_stage_info stage_sorting_for_group; -extern PSI_stage_info stage_sorting_for_order; -extern PSI_stage_info stage_sorting_result; -extern PSI_stage_info stage_sql_thd_waiting_until_delay; -extern PSI_stage_info stage_statistics; -extern PSI_stage_info stage_storing_result_in_query_cache; -extern PSI_stage_info stage_storing_row_into_queue; -extern PSI_stage_info stage_system_lock; -extern PSI_stage_info stage_unlocking_tables; -extern PSI_stage_info stage_table_lock; -extern PSI_stage_info stage_filling_schema_table; -extern PSI_stage_info stage_update; -extern PSI_stage_info stage_updating; -extern PSI_stage_info stage_updating_main_table; -extern PSI_stage_info stage_updating_reference_tables; -extern PSI_stage_info stage_upgrading_lock; -extern PSI_stage_info stage_user_lock; -extern PSI_stage_info stage_user_sleep; -extern PSI_stage_info stage_verifying_table; -extern PSI_stage_info stage_waiting_for_delay_list; -extern PSI_stage_info stage_waiting_for_gtid_to_be_written_to_binary_log; -extern PSI_stage_info stage_waiting_for_handler_insert; -extern PSI_stage_info stage_waiting_for_handler_lock; -extern PSI_stage_info stage_waiting_for_handler_open; -extern PSI_stage_info stage_waiting_for_insert; -extern PSI_stage_info stage_waiting_for_master_to_send_event; -extern PSI_stage_info stage_waiting_for_master_update; -extern PSI_stage_info stage_waiting_for_relay_log_space; -extern PSI_stage_info stage_waiting_for_slave_mutex_on_exit; -extern PSI_stage_info stage_waiting_for_slave_thread_to_start; -extern PSI_stage_info stage_waiting_for_query_cache_lock; -extern PSI_stage_info stage_waiting_for_table_flush; -extern PSI_stage_info stage_waiting_for_the_next_event_in_relay_log; -extern PSI_stage_info stage_waiting_for_the_slave_thread_to_advance_position; -extern PSI_stage_info stage_waiting_to_finalize_termination; -extern PSI_stage_info stage_binlog_waiting_background_tasks; -extern PSI_stage_info stage_binlog_write; -extern PSI_stage_info stage_binlog_processing_checkpoint_notify; -extern PSI_stage_info stage_binlog_stopping_background_thread; -extern PSI_stage_info stage_waiting_for_work_from_sql_thread; -extern PSI_stage_info stage_waiting_for_prior_transaction_to_commit; -extern PSI_stage_info stage_waiting_for_prior_transaction_to_start_commit; -extern PSI_stage_info stage_waiting_for_room_in_worker_thread; -extern PSI_stage_info stage_waiting_for_workers_idle; -extern PSI_stage_info stage_waiting_for_ftwrl; -extern PSI_stage_info stage_waiting_for_ftwrl_threads_to_pause; -extern PSI_stage_info stage_waiting_for_rpl_thread_pool; -extern PSI_stage_info stage_master_gtid_wait_primary; -extern PSI_stage_info stage_master_gtid_wait; -extern PSI_stage_info stage_gtid_wait_other_connection; -extern PSI_stage_info stage_slave_background_process_request; -extern PSI_stage_info stage_slave_background_wait_request; -extern PSI_stage_info stage_waiting_for_deadlock_kill; -extern PSI_stage_info stage_starting; - -#ifdef HAVE_PSI_STATEMENT_INTERFACE -/** - Statement instrumentation keys (sql). - The last entry, at [SQLCOM_END], is for parsing errors. -*/ -extern PSI_statement_info sql_statement_info[(uint) SQLCOM_END + 1]; - -/** - Statement instrumentation keys (com). - The last entry, at [COM_END], is for packet errors. -*/ -extern PSI_statement_info com_statement_info[(uint) COM_END + 1]; - -/** - Statement instrumentation key for replication. -*/ -extern PSI_statement_info stmt_info_rpl; - -void init_sql_statement_info(); -void init_com_statement_info(); -#endif /* HAVE_PSI_STATEMENT_INTERFACE */ - -#ifndef __WIN__ -extern pthread_t signal_thread; -#endif - -#ifdef HAVE_OPENSSL -extern struct st_VioSSLFd * ssl_acceptor_fd; -#endif /* HAVE_OPENSSL */ - -/* - The following variables were under INNODB_COMPABILITY_HOOKS - */ -extern my_bool opt_large_pages; -extern uint opt_large_page_size; -extern char lc_messages_dir[FN_REFLEN]; -extern char *lc_messages_dir_ptr, *log_error_file_ptr; -extern MYSQL_PLUGIN_IMPORT char reg_ext[FN_EXTLEN]; -extern MYSQL_PLUGIN_IMPORT uint reg_ext_length; -extern MYSQL_PLUGIN_IMPORT uint lower_case_table_names; -extern MYSQL_PLUGIN_IMPORT bool mysqld_embedded; -extern ulong specialflag; -extern uint mysql_data_home_len; -extern uint mysql_real_data_home_len; -extern const char *mysql_real_data_home_ptr; -extern ulong thread_handling; -extern "C" MYSQL_PLUGIN_IMPORT char server_version[SERVER_VERSION_LENGTH]; -extern char *server_version_ptr; -extern bool using_custom_server_version; -extern MYSQL_PLUGIN_IMPORT char mysql_real_data_home[]; -extern char mysql_unpacked_real_data_home[]; -extern MYSQL_PLUGIN_IMPORT struct system_variables global_system_variables; -extern char default_logfile_name[FN_REFLEN]; -extern char *my_proxy_protocol_networks; - -#define mysql_tmpdir (my_tmpdir(&mysql_tmpdir_list)) - -extern MYSQL_PLUGIN_IMPORT const key_map key_map_empty; -extern MYSQL_PLUGIN_IMPORT key_map key_map_full; /* Should be threaded as const */ - -/* - Server mutex locks and condition variables. - */ -extern mysql_mutex_t - LOCK_item_func_sleep, LOCK_status, - LOCK_error_log, LOCK_delayed_insert, LOCK_short_uuid_generator, - LOCK_delayed_status, LOCK_delayed_create, LOCK_crypt, LOCK_timezone, - LOCK_active_mi, LOCK_manager, LOCK_user_conn, - LOCK_prepared_stmt_count, LOCK_error_messages, - LOCK_slave_background; -extern MYSQL_PLUGIN_IMPORT mysql_mutex_t LOCK_global_system_variables; -extern mysql_rwlock_t LOCK_all_status_vars; -extern mysql_mutex_t LOCK_start_thread; -#ifdef HAVE_OPENSSL -extern char* des_key_file; -extern mysql_mutex_t LOCK_des_key_file; -#endif -extern MYSQL_PLUGIN_IMPORT mysql_mutex_t LOCK_server_started; -extern MYSQL_PLUGIN_IMPORT mysql_cond_t COND_server_started; -extern mysql_rwlock_t LOCK_grant, LOCK_sys_init_connect, LOCK_sys_init_slave; -extern mysql_rwlock_t LOCK_ssl_refresh; -extern mysql_prlock_t LOCK_system_variables_hash; -extern mysql_cond_t COND_start_thread; -extern mysql_cond_t COND_manager; -extern mysql_cond_t COND_slave_background; -extern Atomic_counter thread_count; - -extern my_bool opt_use_ssl; -extern char *opt_ssl_ca, *opt_ssl_capath, *opt_ssl_cert, *opt_ssl_cipher, - *opt_ssl_key, *opt_ssl_crl, *opt_ssl_crlpath; -extern ulonglong tls_version; - -#ifdef MYSQL_SERVER - -/** - only options that need special treatment in get_one_option() deserve - to be listed below -*/ -enum options_mysqld -{ - OPT_to_set_the_start_number=256, - OPT_BINLOG_DO_DB, - OPT_BINLOG_FORMAT, - OPT_BINLOG_IGNORE_DB, - OPT_BIN_LOG, - OPT_BOOTSTRAP, - OPT_CONSOLE, - OPT_DEBUG_SYNC_TIMEOUT, - OPT_REMOVED_OPTION, - OPT_IGNORE_DB_DIRECTORY, - OPT_ISAM_LOG, - OPT_KEY_BUFFER_SIZE, - OPT_KEY_CACHE_AGE_THRESHOLD, - OPT_KEY_CACHE_BLOCK_SIZE, - OPT_KEY_CACHE_DIVISION_LIMIT, - OPT_KEY_CACHE_PARTITIONS, - OPT_KEY_CACHE_CHANGED_BLOCKS_HASH_SIZE, - OPT_LOG_BASENAME, - OPT_LOG_ERROR, - OPT_LOWER_CASE_TABLE_NAMES, - OPT_PLUGIN_LOAD, - OPT_PLUGIN_LOAD_ADD, - OPT_PFS_INSTRUMENT, - OPT_REPLICATE_DO_DB, - OPT_REPLICATE_DO_TABLE, - OPT_REPLICATE_IGNORE_DB, - OPT_REPLICATE_IGNORE_TABLE, - OPT_REPLICATE_REWRITE_DB, - OPT_REPLICATE_WILD_DO_TABLE, - OPT_REPLICATE_WILD_IGNORE_TABLE, - OPT_SAFE, - OPT_SERVER_ID, - OPT_SILENT, - OPT_SKIP_HOST_CACHE, - OPT_SKIP_RESOLVE, - OPT_SLAVE_PARALLEL_MODE, - OPT_SSL_CA, - OPT_SSL_CAPATH, - OPT_SSL_CERT, - OPT_SSL_CIPHER, - OPT_SSL_CRL, - OPT_SSL_CRLPATH, - OPT_SSL_KEY, - OPT_THREAD_CONCURRENCY, - OPT_WANT_CORE, -#ifdef WITH_WSREP - OPT_WSREP_CAUSAL_READS, - OPT_WSREP_SYNC_WAIT, -#endif /* WITH_WSREP */ - OPT_MYSQL_COMPATIBILITY, - OPT_TLS_VERSION, - OPT_MYSQL_TO_BE_IMPLEMENTED, - OPT_which_is_always_the_last -}; -#endif - -/** - Query type constants (usable as bitmap flags). -*/ -enum enum_query_type -{ - /// Nothing specific, ordinary SQL query. - QT_ORDINARY= 0, - /// In utf8. - QT_TO_SYSTEM_CHARSET= (1 << 0), - /// Without character set introducers. - QT_WITHOUT_INTRODUCERS= (1 << 1), - /// view internal representation (like QT_ORDINARY except ORDER BY clause) - QT_VIEW_INTERNAL= (1 << 2), - /// If identifiers should not include database names, where unambiguous - QT_ITEM_IDENT_SKIP_DB_NAMES= (1 << 3), - /// If identifiers should not include table names, where unambiguous - QT_ITEM_IDENT_SKIP_TABLE_NAMES= (1 << 4), - /// If Item_cache_wrapper should not print - QT_ITEM_CACHE_WRAPPER_SKIP_DETAILS= (1 << 5), - /// If Item_subselect should print as just "(subquery#1)" - /// rather than display the subquery body - QT_ITEM_SUBSELECT_ID_ONLY= (1 << 6), - /// If NULLIF(a,b) should print itself as - /// CASE WHEN a_for_comparison=b THEN NULL ELSE a_for_return_value END - /// when "a" was replaced to two different items - /// (e.g. by equal fields propagation in optimize_cond()) - /// or always as NULLIF(a, b). - /// The default behaviour is to use CASE syntax when - /// a_for_return_value is not the same as a_for_comparison. - /// SHOW CREATE {VIEW|PROCEDURE|FUNCTION} and other cases where the - /// original representation is required, should set this flag. - QT_ITEM_ORIGINAL_FUNC_NULLIF= (1 << 7), - /// good for parsing - QT_PARSABLE= (1 << 8), - - /// This value means focus on readability, not on ability to parse back, etc. - QT_EXPLAIN= QT_TO_SYSTEM_CHARSET | - QT_ITEM_IDENT_SKIP_DB_NAMES | - QT_ITEM_CACHE_WRAPPER_SKIP_DETAILS | - QT_ITEM_SUBSELECT_ID_ONLY, - - QT_SHOW_SELECT_NUMBER= (1<<10), - - /// Do not print database name or table name in the identifiers (even if - /// this means the printout will be ambigous). It is assumed that the caller - /// passing this flag knows what they are doing. - QT_ITEM_IDENT_DISABLE_DB_TABLE_NAMES= (1 <<11), - - /// This is used for EXPLAIN EXTENDED extra warnings / Be more detailed - /// Be more detailed than QT_EXPLAIN. - /// Perhaps we should eventually include QT_ITEM_IDENT_SKIP_CURRENT_DATABASE - /// here, as it would give better readable results - QT_EXPLAIN_EXTENDED= QT_TO_SYSTEM_CHARSET| - QT_SHOW_SELECT_NUMBER, - - // If an expression is constant, print the expression, not the value - // it evaluates to. Should be used for error messages, so that they - // don't reveal values. - QT_NO_DATA_EXPANSION= (1 << 9), -}; - - -/* query_id */ -extern Atomic_counter global_query_id; - -/* increment query_id and return it. */ -inline __attribute__((warn_unused_result)) query_id_t next_query_id() -{ - return global_query_id++; -} - -inline query_id_t get_query_id() -{ - return global_query_id; -} - -/* increment global_thread_id and return it. */ -extern __attribute__((warn_unused_result)) my_thread_id next_thread_id(void); - -/* - TODO: Replace this with an inline function. - */ -#ifndef EMBEDDED_LIBRARY -extern "C" void unireg_abort(int exit_code) __attribute__((noreturn)); -#else -extern "C" void unireg_clear(int exit_code); -#define unireg_abort(exit_code) do { unireg_clear(exit_code); DBUG_RETURN(exit_code); } while(0) -#endif - -inline void table_case_convert(char * name, uint length) -{ - if (lower_case_table_names) - files_charset_info->casedn(name, length, name, length); -} - -extern void set_server_version(char *buf, size_t size); - -#define current_thd _current_thd() -void set_current_thd(THD *thd); - -/* - @todo remove, make it static in ha_maria.cc - currently it's needed for sql_select.cc -*/ -extern handlerton *maria_hton; - -extern uint64 global_gtid_counter; -extern my_bool opt_gtid_strict_mode; -extern my_bool opt_userstat_running, debug_assert_if_crashed_table; -extern uint mysqld_extra_port; -extern ulong opt_progress_report_time; -extern ulong extra_max_connections; -extern ulonglong denied_connections; -extern ulong thread_created; -extern scheduler_functions *thread_scheduler, *extra_thread_scheduler; -extern char *opt_log_basename; -extern my_bool opt_master_verify_checksum; -extern my_bool opt_stack_trace, disable_log_notes; -extern my_bool opt_expect_abort; -extern my_bool opt_slave_sql_verify_checksum; -extern my_bool opt_mysql56_temporal_format, strict_password_validation; -extern my_bool opt_explicit_defaults_for_timestamp; -extern ulong binlog_checksum_options; -extern bool max_user_connections_checking; -extern ulong opt_binlog_dbug_fsync_sleep; - -extern uint volatile global_disable_checkpoint; -extern my_bool opt_help; - -#endif /* MYSQLD_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld_default_groups.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld_default_groups.h deleted file mode 100644 index cf6e92e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld_default_groups.h +++ /dev/null @@ -1,9 +0,0 @@ -const char *load_default_groups[]= { -"mysqld", "server", MYSQL_BASE_VERSION, -"mariadb", MARIADB_BASE_VERSION, -"mariadbd", MARIADBD_BASE_VERSION, -"client-server", -#ifdef WITH_WSREP -"galera", -#endif -0, 0}; diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld_suffix.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld_suffix.h deleted file mode 100644 index 3c36ba2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysqld_suffix.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef MYSQLD_SUFFIX_INCLUDED -#define MYSQLD_SUFFIX_INCLUDED - -/* Copyright (c) 2000-2004, 2006, 2007 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - Set MYSQL_SERVER_SUFFIX_STR. - - The following code is quite ugly as there is no portable way to easily set a - string to the value of a macro -*/ - -#ifdef MYSQL_SERVER_SUFFIX -#define MYSQL_SERVER_SUFFIX_STR STRINGIFY_ARG(MYSQL_SERVER_SUFFIX) -#else -#define MYSQL_SERVER_SUFFIX_STR MYSQL_SERVER_SUFFIX_DEF -#endif -#endif /* MYSQLD_SUFFIX_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysys_err.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysys_err.h deleted file mode 100644 index e0e97d0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/mysys_err.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright (c) 2000, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _mysys_err_h -#define _mysys_err_h - -#ifdef __cplusplus -extern "C" { -#endif - -#define GLOBERRS (EE_ERROR_LAST - EE_ERROR_FIRST + 1) /* Nr of global errors */ -#define EE(X) (globerrs[(X) - EE_ERROR_FIRST]) - -extern const char *globerrs[]; /* my_error_messages is here */ - -/* Error message numbers in global map */ -/* - Do not add error numbers before EE_ERROR_FIRST. - If necessary to add lower numbers, change EE_ERROR_FIRST accordingly. - - We start with error 1 to not confuse peoples with 'error 0' -*/ - -#define EE_ERROR_FIRST 1 /*Copy first error nr.*/ -#define EE_CANTCREATEFILE 1 -#define EE_READ 2 -#define EE_WRITE 3 -#define EE_BADCLOSE 4 -#define EE_OUTOFMEMORY 5 -#define EE_DELETE 6 -#define EE_LINK 7 -#define EE_EOFERR 9 -#define EE_CANTLOCK 10 -#define EE_CANTUNLOCK 11 -#define EE_DIR 12 -#define EE_STAT 13 -#define EE_CANT_CHSIZE 14 -#define EE_CANT_OPEN_STREAM 15 -#define EE_GETWD 16 -#define EE_SETWD 17 -#define EE_LINK_WARNING 18 -#define EE_OPEN_WARNING 19 -#define EE_DISK_FULL 20 -#define EE_CANT_MKDIR 21 -#define EE_UNKNOWN_CHARSET 22 -#define EE_OUT_OF_FILERESOURCES 23 -#define EE_CANT_READLINK 24 -#define EE_CANT_SYMLINK 25 -#define EE_REALPATH 26 -#define EE_SYNC 27 -#define EE_UNKNOWN_COLLATION 28 -#define EE_FILENOTFOUND 29 -#define EE_FILE_NOT_CLOSED 30 -#define EE_CHANGE_OWNERSHIP 31 -#define EE_CHANGE_PERMISSIONS 32 -#define EE_CANT_SEEK 33 -#define EE_CANT_CHMOD 34 -#define EE_CANT_COPY_OWNERSHIP 35 -#define EE_BADMEMORYRELEASE 36 -#define EE_PERM_LOCK_MEMORY 37 -#define EE_MEMCNTL 38 -#define EE_DUPLICATE_CHARSET 39 -#define EE_ERROR_LAST 39 /* Copy last error nr */ - -/* Add error numbers before EE_ERROR_LAST and change it accordingly. */ - - /* exit codes for all MySQL programs */ - -#define EXIT_UNSPECIFIED_ERROR 1 -#define EXIT_UNKNOWN_OPTION 2 -#define EXIT_AMBIGUOUS_OPTION 3 -#define EXIT_NO_ARGUMENT_ALLOWED 4 -#define EXIT_ARGUMENT_REQUIRED 5 -#define EXIT_VAR_PREFIX_NOT_UNIQUE 6 -#define EXIT_UNKNOWN_VARIABLE 7 -#define EXIT_OUT_OF_MEMORY 8 -#define EXIT_UNKNOWN_SUFFIX 9 -#define EXIT_NO_PTR_TO_VARIABLE 10 -#define EXIT_CANNOT_CONNECT_TO_SERVICE 11 -#define EXIT_OPTION_DISABLED 12 -#define EXIT_ARGUMENT_INVALID 13 - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/nt_servc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/nt_servc.h deleted file mode 100644 index 8ba2951..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/nt_servc.h +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef NT_SERVC_INCLUDED -#define NT_SERVC_INCLUDED - -/** - @file - - @brief - Windows NT Service class library - - Copyright Abandoned 1998 Irena Pancirov - Irnet Snc - This file is public domain and comes with NO WARRANTY of any kind -*/ - -// main application thread -typedef void (*THREAD_FC)(void *); - -class NTService -{ - public: - NTService(); - ~NTService(); - - BOOL bOsNT; ///< true if OS is NT, false for Win95 - //install optinos - DWORD dwDesiredAccess; - DWORD dwServiceType; - DWORD dwStartType; - DWORD dwErrorControl; - - LPSTR szLoadOrderGroup; - LPDWORD lpdwTagID; - LPSTR szDependencies; - OSVERSIONINFO osVer; - - // time-out (in milisec) - int nStartTimeOut; - int nStopTimeOut; - int nPauseTimeOut; - int nResumeTimeOut; - - // - DWORD my_argc; - LPTSTR *my_argv; - HANDLE hShutdownEvent; - int nError; - DWORD dwState; - - //init service entry point - long Init(LPCSTR szInternName,THREAD_FC ServiceThread); - - //application shutdown event - void SetShutdownEvent(HANDLE hEvent){ hShutdownEvent=hEvent; } - - - //service install / un-install - BOOL Install(int startType,LPCSTR szInternName,LPCSTR szDisplayName, - LPCSTR szFullPath, LPCSTR szAccountName=NULL, - LPCSTR szPassword=NULL); - BOOL SeekStatus(LPCSTR szInternName, int OperationType); - BOOL Remove(LPCSTR szInternName); - BOOL IsService(LPCSTR ServiceName); - BOOL got_service_option(char **argv, const char *service_option); - BOOL is_super_user(); - - /* - SetRunning() is to be called by the application - when initialization completes and it can accept - stop request - */ - void SetRunning(void); - - /** - Sets a timeout after which SCM will abort service startup if SetRunning() - was not called or the timeout was not extended with another call to - SetSlowStarting(). Should be called when static initialization completes, - and the variable initialization part begins - - @arg timeout the timeout to pass to the SCM (in milliseconds) - */ - void SetSlowStarting(unsigned long timeout); - - /* - Stop() is to be called by the application to stop - the service - */ - void Stop(void); - - protected: - LPSTR ServiceName; - HANDLE hExitEvent; - SERVICE_STATUS_HANDLE hServiceStatusHandle; - BOOL bPause; - BOOL bRunning; - HANDLE hThreadHandle; - THREAD_FC fpServiceThread; - - void PauseService(); - void ResumeService(); - void StopService(); - BOOL StartService(); - - static void WINAPI ServiceMain(DWORD argc, LPTSTR *argv); - static void WINAPI ServiceCtrlHandler (DWORD ctrlCode); - - void Exit(DWORD error); - BOOL SetStatus (DWORD dwCurrentState,DWORD dwWin32ExitCode, - DWORD dwServiceSpecificExitCode, - DWORD dwCheckPoint,DWORD dwWaitHint); - -}; -/* ------------------------- the end -------------------------------------- */ - -#endif /* NT_SERVC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_range.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_range.h deleted file mode 100644 index 664e821..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_range.h +++ /dev/null @@ -1,1753 +0,0 @@ -/* - Copyright (c) 2000, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* classes to use when handling where clause */ - -#ifndef _opt_range_h -#define _opt_range_h - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "records.h" /* READ_RECORD */ -#include "queues.h" /* QUEUE */ -#include "filesort.h" /* SORT_INFO */ - -/* - It is necessary to include set_var.h instead of item.h because there - are dependencies on include order for set_var.h and item.h. This - will be resolved later. -*/ -#include "sql_class.h" // set_var.h: THD -#include "set_var.h" /* Item */ - -class JOIN; -class Item_sum; - -struct KEY_PART { - uint16 key,part; - /* See KEY_PART_INFO for meaning of the next two: */ - uint16 store_length, length; - uint8 null_bit; - /* - Keypart flags (0 when this structure is used by partition pruning code - for fake partitioning index description) - */ - uint8 flag; - Field *field; - Field::imagetype image_type; -}; - - -class RANGE_OPT_PARAM; -/* - A construction block of the SEL_ARG-graph. - - The following description only covers graphs of SEL_ARG objects with - sel_arg->type==KEY_RANGE: - - One SEL_ARG object represents an "elementary interval" in form - - min_value <=? table.keypartX <=? max_value - - The interval is a non-empty interval of any kind: with[out] minimum/maximum - bound, [half]open/closed, single-point interval, etc. - - 1. SEL_ARG GRAPH STRUCTURE - - SEL_ARG objects are linked together in a graph. The meaning of the graph - is better demostrated by an example: - - tree->keys[i] - | - | $ $ - | part=1 $ part=2 $ part=3 - | $ $ - | +-------+ $ +-------+ $ +--------+ - | | kp1<1 |--$-->| kp2=5 |--$-->| kp3=10 | - | +-------+ $ +-------+ $ +--------+ - | | $ $ | - | | $ $ +--------+ - | | $ $ | kp3=12 | - | | $ $ +--------+ - | +-------+ $ $ - \->| kp1=2 |--$--------------$-+ - +-------+ $ $ | +--------+ - | $ $ ==>| kp3=11 | - +-------+ $ $ | +--------+ - | kp1=3 |--$--------------$-+ | - +-------+ $ $ +--------+ - | $ $ | kp3=14 | - ... $ $ +--------+ - - The entire graph is partitioned into "interval lists". - - An interval list is a sequence of ordered disjoint intervals over the same - key part. SEL_ARG are linked via "next" and "prev" pointers. Additionally, - all intervals in the list form an RB-tree, linked via left/right/parent - pointers. The RB-tree root SEL_ARG object will be further called "root of the - interval list". - - In the example pic, there are 4 interval lists: - "kp<1 OR kp1=2 OR kp1=3", "kp2=5", "kp3=10 OR kp3=12", "kp3=11 OR kp3=13". - The vertical lines represent SEL_ARG::next/prev pointers. - - In an interval list, each member X may have SEL_ARG::next_key_part pointer - pointing to the root of another interval list Y. The pointed interval list - must cover a key part with greater number (i.e. Y->part > X->part). - - In the example pic, the next_key_part pointers are represented by - horisontal lines. - - 2. SEL_ARG GRAPH SEMANTICS - - It represents a condition in a special form (we don't have a name for it ATM) - The SEL_ARG::next/prev is "OR", and next_key_part is "AND". - - For example, the picture represents the condition in form: - (kp1 < 1 AND kp2=5 AND (kp3=10 OR kp3=12)) OR - (kp1=2 AND (kp3=11 OR kp3=14)) OR - (kp1=3 AND (kp3=11 OR kp3=14)) - - - 3. SEL_ARG GRAPH USE - - Use get_mm_tree() to construct SEL_ARG graph from WHERE condition. - Then walk the SEL_ARG graph and get a list of dijsoint ordered key - intervals (i.e. intervals in form - - (constA1, .., const1_K) < (keypart1,.., keypartK) < (constB1, .., constB_K) - - Those intervals can be used to access the index. The uses are in: - - check_quick_select() - Walk the SEL_ARG graph and find an estimate of - how many table records are contained within all - intervals. - - get_quick_select() - Walk the SEL_ARG, materialize the key intervals, - and create QUICK_RANGE_SELECT object that will - read records within these intervals. - - 4. SPACE COMPLEXITY NOTES - - SEL_ARG graph is a representation of an ordered disjoint sequence of - intervals over the ordered set of index tuple values. - - For multi-part keys, one can construct a WHERE expression such that its - list of intervals will be of combinatorial size. Here is an example: - - (keypart1 IN (1,2, ..., n1)) AND - (keypart2 IN (1,2, ..., n2)) AND - (keypart3 IN (1,2, ..., n3)) - - For this WHERE clause the list of intervals will have n1*n2*n3 intervals - of form - - (keypart1, keypart2, keypart3) = (k1, k2, k3), where 1 <= k{i} <= n{i} - - SEL_ARG graph structure aims to reduce the amount of required space by - "sharing" the elementary intervals when possible (the pic at the - beginning of this comment has examples of such sharing). The sharing may - prevent combinatorial blowup: - - There are WHERE clauses that have combinatorial-size interval lists but - will be represented by a compact SEL_ARG graph. - Example: - (keypartN IN (1,2, ..., n1)) AND - ... - (keypart2 IN (1,2, ..., n2)) AND - (keypart1 IN (1,2, ..., n3)) - - but not in all cases: - - - There are WHERE clauses that do have a compact SEL_ARG-graph - representation but get_mm_tree() and its callees will construct a - graph of combinatorial size. - Example: - (keypart1 IN (1,2, ..., n1)) AND - (keypart2 IN (1,2, ..., n2)) AND - ... - (keypartN IN (1,2, ..., n3)) - - - There are WHERE clauses for which the minimal possible SEL_ARG graph - representation will have combinatorial size. - Example: - By induction: Let's take any interval on some keypart in the middle: - - kp15=c0 - - Then let's AND it with this interval 'structure' from preceding and - following keyparts: - - (kp14=c1 AND kp16=c3) OR keypart14=c2) (*) - - We will obtain this SEL_ARG graph: - - kp14 $ kp15 $ kp16 - $ $ - +---------+ $ +---------+ $ +---------+ - | kp14=c1 |--$-->| kp15=c0 |--$-->| kp16=c3 | - +---------+ $ +---------+ $ +---------+ - | $ $ - +---------+ $ +---------+ $ - | kp14=c2 |--$-->| kp15=c0 | $ - +---------+ $ +---------+ $ - $ $ - - Note that we had to duplicate "kp15=c0" and there was no way to avoid - that. - The induction step: AND the obtained expression with another "wrapping" - expression like (*). - When the process ends because of the limit on max. number of keyparts - we'll have: - - WHERE clause length is O(3*#max_keyparts) - SEL_ARG graph size is O(2^(#max_keyparts/2)) - - (it is also possible to construct a case where instead of 2 in 2^n we - have a bigger constant, e.g. 4, and get a graph with 4^(31/2)= 2^31 - nodes) - - We avoid consuming too much memory by setting a limit on the number of - SEL_ARG object we can construct during one range analysis invocation. -*/ - -class SEL_ARG :public Sql_alloc -{ - static int sel_cmp(Field *field, uchar *a, uchar *b, uint8 a_flag, - uint8 b_flag); -public: - uint8 min_flag,max_flag,maybe_flag; - uint8 part; // Which key part - uint8 maybe_null; - /* - The ordinal number the least significant component encountered in - the ranges of the SEL_ARG tree (the first component has number 1) - */ - uint16 max_part_no; - /* - Number of children of this element in the RB-tree, plus 1 for this - element itself. - */ - uint32 elements; - /* - Valid only for elements which are RB-tree roots: Number of times this - RB-tree is referred to (it is referred by SEL_ARG::next_key_part or by - SEL_TREE::keys[i] or by a temporary SEL_ARG* variable) - */ - ulong use_count; - - Field *field; - uchar *min_value,*max_value; // Pointer to range - - /* - eq_tree() requires that left == right == 0 if the type is MAYBE_KEY. - */ - SEL_ARG *left,*right; /* R-B tree children */ - SEL_ARG *next,*prev; /* Links for bi-directional interval list */ - SEL_ARG *parent; /* R-B tree parent */ - SEL_ARG *next_key_part; - enum leaf_color { BLACK,RED } color; - enum Type { IMPOSSIBLE, MAYBE, MAYBE_KEY, KEY_RANGE } type; - - enum { MAX_SEL_ARGS = 16000 }; - - SEL_ARG() {} - SEL_ARG(SEL_ARG &); - SEL_ARG(Field *,const uchar *, const uchar *); - SEL_ARG(Field *field, uint8 part, uchar *min_value, uchar *max_value, - uint8 min_flag, uint8 max_flag, uint8 maybe_flag); - SEL_ARG(enum Type type_arg) - :min_flag(0), max_part_no(0) /* first key part means 1. 0 mean 'no parts'*/, - elements(1),use_count(1),left(0),right(0), - next_key_part(0), color(BLACK), type(type_arg) - {} - /** - returns true if a range predicate is equal. Use all_same() - to check for equality of all the predicates on this keypart. - */ - inline bool is_same(const SEL_ARG *arg) const - { - if (type != arg->type || part != arg->part) - return false; - if (type != KEY_RANGE) - return true; - return cmp_min_to_min(arg) == 0 && cmp_max_to_max(arg) == 0; - } - /** - returns true if all the predicates in the keypart tree are equal - */ - bool all_same(const SEL_ARG *arg) const - { - if (type != arg->type || part != arg->part) - return false; - if (type != KEY_RANGE) - return true; - if (arg == this) - return true; - const SEL_ARG *cmp_arg= arg->first(); - const SEL_ARG *cur_arg= first(); - for (; cur_arg && cmp_arg && cur_arg->is_same(cmp_arg); - cur_arg= cur_arg->next, cmp_arg= cmp_arg->next) ; - if (cur_arg || cmp_arg) - return false; - return true; - } - inline void merge_flags(SEL_ARG *arg) { maybe_flag|=arg->maybe_flag; } - inline void maybe_smaller() { maybe_flag=1; } - /* Return true iff it's a single-point null interval */ - inline bool is_null_interval() { return maybe_null && max_value[0] == 1; } - inline int cmp_min_to_min(const SEL_ARG* arg) const - { - return sel_cmp(field,min_value, arg->min_value, min_flag, arg->min_flag); - } - inline int cmp_min_to_max(const SEL_ARG* arg) const - { - return sel_cmp(field,min_value, arg->max_value, min_flag, arg->max_flag); - } - inline int cmp_max_to_max(const SEL_ARG* arg) const - { - return sel_cmp(field,max_value, arg->max_value, max_flag, arg->max_flag); - } - inline int cmp_max_to_min(const SEL_ARG* arg) const - { - return sel_cmp(field,max_value, arg->min_value, max_flag, arg->min_flag); - } - SEL_ARG *clone_and(THD *thd, SEL_ARG* arg) - { // Get overlapping range - uchar *new_min,*new_max; - uint8 flag_min,flag_max; - if (cmp_min_to_min(arg) >= 0) - { - new_min=min_value; flag_min=min_flag; - } - else - { - new_min=arg->min_value; flag_min=arg->min_flag; /* purecov: deadcode */ - } - if (cmp_max_to_max(arg) <= 0) - { - new_max=max_value; flag_max=max_flag; - } - else - { - new_max=arg->max_value; flag_max=arg->max_flag; - } - return new (thd->mem_root) SEL_ARG(field, part, new_min, new_max, flag_min, - flag_max, - MY_TEST(maybe_flag && arg->maybe_flag)); - } - SEL_ARG *clone_first(SEL_ARG *arg) - { // min <= X < arg->min - return new SEL_ARG(field,part, min_value, arg->min_value, - min_flag, arg->min_flag & NEAR_MIN ? 0 : NEAR_MAX, - maybe_flag | arg->maybe_flag); - } - SEL_ARG *clone_last(SEL_ARG *arg) - { // min <= X <= key_max - return new SEL_ARG(field, part, min_value, arg->max_value, - min_flag, arg->max_flag, maybe_flag | arg->maybe_flag); - } - SEL_ARG *clone(RANGE_OPT_PARAM *param, SEL_ARG *new_parent, SEL_ARG **next); - - bool copy_min(SEL_ARG* arg) - { // Get overlapping range - if (cmp_min_to_min(arg) > 0) - { - min_value=arg->min_value; min_flag=arg->min_flag; - if ((max_flag & (NO_MAX_RANGE | NO_MIN_RANGE)) == - (NO_MAX_RANGE | NO_MIN_RANGE)) - return 1; // Full range - } - maybe_flag|=arg->maybe_flag; - return 0; - } - bool copy_max(SEL_ARG* arg) - { // Get overlapping range - if (cmp_max_to_max(arg) <= 0) - { - max_value=arg->max_value; max_flag=arg->max_flag; - if ((max_flag & (NO_MAX_RANGE | NO_MIN_RANGE)) == - (NO_MAX_RANGE | NO_MIN_RANGE)) - return 1; // Full range - } - maybe_flag|=arg->maybe_flag; - return 0; - } - - void copy_min_to_min(SEL_ARG *arg) - { - min_value=arg->min_value; min_flag=arg->min_flag; - } - void copy_min_to_max(SEL_ARG *arg) - { - max_value=arg->min_value; - max_flag=arg->min_flag & NEAR_MIN ? 0 : NEAR_MAX; - } - void copy_max_to_min(SEL_ARG *arg) - { - min_value=arg->max_value; - min_flag=arg->max_flag & NEAR_MAX ? 0 : NEAR_MIN; - } - /* returns a number of keypart values (0 or 1) appended to the key buffer */ - int store_min(uint length, uchar **min_key,uint min_key_flag) - { - /* "(kp1 > c1) AND (kp2 OP c2) AND ..." -> (kp1 > c1) */ - if ((min_flag & GEOM_FLAG) || - (!(min_flag & NO_MIN_RANGE) && - !(min_key_flag & (NO_MIN_RANGE | NEAR_MIN)))) - { - if (maybe_null && *min_value) - { - **min_key=1; - bzero(*min_key+1,length-1); - } - else - memcpy(*min_key,min_value,length); - (*min_key)+= length; - return 1; - } - return 0; - } - /* returns a number of keypart values (0 or 1) appended to the key buffer */ - int store_max(uint length, uchar **max_key, uint max_key_flag) - { - if (!(max_flag & NO_MAX_RANGE) && - !(max_key_flag & (NO_MAX_RANGE | NEAR_MAX))) - { - if (maybe_null && *max_value) - { - **max_key=1; - bzero(*max_key+1,length-1); - } - else - memcpy(*max_key,max_value,length); - (*max_key)+= length; - return 1; - } - return 0; - } - - /* - Returns a number of keypart values appended to the key buffer - for min key and max key. This function is used by both Range - Analysis and Partition pruning. For partition pruning we have - to ensure that we don't store also subpartition fields. Thus - we have to stop at the last partition part and not step into - the subpartition fields. For Range Analysis we set last_part - to MAX_KEY which we should never reach. - */ - int store_min_key(KEY_PART *key, - uchar **range_key, - uint *range_key_flag, - uint last_part) - { - SEL_ARG *key_tree= first(); - uint res= key_tree->store_min(key[key_tree->part].store_length, - range_key, *range_key_flag); - // add flags only if a key_part is written to the buffer - if (!res) - return 0; - *range_key_flag|= key_tree->min_flag; - if (key_tree->next_key_part && - key_tree->next_key_part->type == SEL_ARG::KEY_RANGE && - key_tree->part != last_part && - key_tree->next_key_part->part == key_tree->part+1 && - !(*range_key_flag & (NO_MIN_RANGE | NEAR_MIN))) - res+= key_tree->next_key_part->store_min_key(key, - range_key, - range_key_flag, - last_part); - return res; - } - - /* returns a number of keypart values appended to the key buffer */ - int store_max_key(KEY_PART *key, - uchar **range_key, - uint *range_key_flag, - uint last_part) - { - SEL_ARG *key_tree= last(); - uint res=key_tree->store_max(key[key_tree->part].store_length, - range_key, *range_key_flag); - if (!res) - return 0; - *range_key_flag|= key_tree->max_flag; - if (key_tree->next_key_part && - key_tree->next_key_part->type == SEL_ARG::KEY_RANGE && - key_tree->part != last_part && - key_tree->next_key_part->part == key_tree->part+1 && - !(*range_key_flag & (NO_MAX_RANGE | NEAR_MAX))) - res+= key_tree->next_key_part->store_max_key(key, - range_key, - range_key_flag, - last_part); - return res; - } - - SEL_ARG *insert(SEL_ARG *key); - SEL_ARG *tree_delete(SEL_ARG *key); - SEL_ARG *find_range(SEL_ARG *key); - SEL_ARG *rb_insert(SEL_ARG *leaf); - friend SEL_ARG *rb_delete_fixup(SEL_ARG *root,SEL_ARG *key, SEL_ARG *par); -#ifdef EXTRA_DEBUG - friend int test_rb_tree(SEL_ARG *element,SEL_ARG *parent); - void test_use_count(SEL_ARG *root); -#endif - SEL_ARG *first(); - const SEL_ARG *first() const; - SEL_ARG *last(); - void make_root(); - inline bool simple_key() - { - return !next_key_part && elements == 1; - } - void increment_use_count(long count) - { - if (next_key_part) - { - next_key_part->use_count+=count; - count*= (next_key_part->use_count-count); - for (SEL_ARG *pos=next_key_part->first(); pos ; pos=pos->next) - if (pos->next_key_part) - pos->increment_use_count(count); - } - } - void incr_refs() - { - increment_use_count(1); - use_count++; - } - void incr_refs_all() - { - for (SEL_ARG *pos=first(); pos ; pos=pos->next) - { - pos->increment_use_count(1); - } - use_count++; - } - void free_tree() - { - for (SEL_ARG *pos=first(); pos ; pos=pos->next) - if (pos->next_key_part) - { - pos->next_key_part->use_count--; - pos->next_key_part->free_tree(); - } - } - - inline SEL_ARG **parent_ptr() - { - return parent->left == this ? &parent->left : &parent->right; - } - - - /* - Check if this SEL_ARG object represents a single-point interval - - SYNOPSIS - is_singlepoint() - - DESCRIPTION - Check if this SEL_ARG object (not tree) represents a single-point - interval, i.e. if it represents a "keypart = const" or - "keypart IS NULL". - - RETURN - TRUE This SEL_ARG object represents a singlepoint interval - FALSE Otherwise - */ - - bool is_singlepoint() const - { - /* - Check for NEAR_MIN ("strictly less") and NO_MIN_RANGE (-inf < field) - flags, and the same for right edge. - */ - if (min_flag || max_flag) - return FALSE; - uchar *min_val= min_value; - uchar *max_val= max_value; - - if (maybe_null) - { - /* First byte is a NULL value indicator */ - if (*min_val != *max_val) - return FALSE; - - if (*min_val) - return TRUE; /* This "x IS NULL" */ - min_val++; - max_val++; - } - return !field->key_cmp(min_val, max_val); - } - SEL_ARG *clone_tree(RANGE_OPT_PARAM *param); -}; - -extern MYSQL_PLUGIN_IMPORT SEL_ARG null_element; - -class SEL_ARG_IMPOSSIBLE: public SEL_ARG -{ -public: - SEL_ARG_IMPOSSIBLE(Field *field) - :SEL_ARG(field, 0, 0) - { - type= SEL_ARG::IMPOSSIBLE; - } -}; - - -class RANGE_OPT_PARAM -{ -public: - THD *thd; /* Current thread handle */ - TABLE *table; /* Table being analyzed */ - table_map prev_tables; - table_map read_tables; - table_map current_table; /* Bit of the table being analyzed */ - - /* Array of parts of all keys for which range analysis is performed */ - KEY_PART *key_parts; - KEY_PART *key_parts_end; - MEM_ROOT *mem_root; /* Memory that will be freed when range analysis completes */ - MEM_ROOT *old_root; /* Memory that will last until the query end */ - /* - Number of indexes used in range analysis (In SEL_TREE::keys only first - #keys elements are not empty) - */ - uint keys; - - /* - If true, the index descriptions describe real indexes (and it is ok to - call field->optimize_range(real_keynr[...], ...). - Otherwise index description describes fake indexes. - */ - bool using_real_indexes; - - /* - Aggressively remove "scans" that do not have conditions on first - keyparts. Such scans are usable when doing partition pruning but not - regular range optimization. - */ - bool remove_jump_scans; - - /* - TRUE <=> Range analyzer should remove parts of condition that are found - to be always FALSE. - */ - bool remove_false_where_parts; - - /* - used_key_no -> table_key_no translation table. Only makes sense if - using_real_indexes==TRUE - */ - uint real_keynr[MAX_KEY]; - - /* - Used to store 'current key tuples', in both range analysis and - partitioning (list) analysis - */ - uchar *min_key; - uchar *max_key; - - /* Number of SEL_ARG objects allocated by SEL_ARG::clone_tree operations */ - uint alloced_sel_args; - - bool force_default_mrr; - KEY_PART *key[MAX_KEY]; /* First key parts of keys used in the query */ - - bool statement_should_be_aborted() const - { - return - thd->killed || - thd->is_fatal_error || - thd->is_error() || - alloced_sel_args > SEL_ARG::MAX_SEL_ARGS; - } -}; - - -class Explain_quick_select; -/* - A "MIN_TUPLE < tbl.key_tuple < MAX_TUPLE" interval. - - One of endpoints may be absent. 'flags' member has flags which tell whether - the endpoints are '<' or '<='. -*/ -class QUICK_RANGE :public Sql_alloc { - public: - uchar *min_key,*max_key; - uint16 min_length,max_length,flag; - key_part_map min_keypart_map, // bitmap of used keyparts in min_key - max_keypart_map; // bitmap of used keyparts in max_key -#ifdef HAVE_valgrind - uint16 dummy; /* Avoid warnings on 'flag' */ -#endif - QUICK_RANGE(); /* Full range */ - QUICK_RANGE(THD *thd, const uchar *min_key_arg, uint min_length_arg, - key_part_map min_keypart_map_arg, - const uchar *max_key_arg, uint max_length_arg, - key_part_map max_keypart_map_arg, - uint flag_arg) - : min_key((uchar*) thd->memdup(min_key_arg, min_length_arg + 1)), - max_key((uchar*) thd->memdup(max_key_arg, max_length_arg + 1)), - min_length((uint16) min_length_arg), - max_length((uint16) max_length_arg), - flag((uint16) flag_arg), - min_keypart_map(min_keypart_map_arg), - max_keypart_map(max_keypart_map_arg) - { -#ifdef HAVE_valgrind - dummy=0; -#endif - } - - /** - Initalizes a key_range object for communication with storage engine. - - This function facilitates communication with the Storage Engine API by - translating the minimum endpoint of the interval represented by this - QUICK_RANGE into an index range endpoint specifier for the engine. - - @param Pointer to an uninitialized key_range C struct. - - @param prefix_length The length of the search key prefix to be used for - lookup. - - @param keypart_map A set (bitmap) of keyparts to be used. - */ - void make_min_endpoint(key_range *kr, uint prefix_length, - key_part_map keypart_map) { - make_min_endpoint(kr); - kr->length= MY_MIN(kr->length, prefix_length); - kr->keypart_map&= keypart_map; - } - - /** - Initalizes a key_range object for communication with storage engine. - - This function facilitates communication with the Storage Engine API by - translating the minimum endpoint of the interval represented by this - QUICK_RANGE into an index range endpoint specifier for the engine. - - @param Pointer to an uninitialized key_range C struct. - */ - void make_min_endpoint(key_range *kr) { - kr->key= (const uchar*)min_key; - kr->length= min_length; - kr->keypart_map= min_keypart_map; - kr->flag= ((flag & NEAR_MIN) ? HA_READ_AFTER_KEY : - (flag & EQ_RANGE) ? HA_READ_KEY_EXACT : HA_READ_KEY_OR_NEXT); - } - - /** - Initalizes a key_range object for communication with storage engine. - - This function facilitates communication with the Storage Engine API by - translating the maximum endpoint of the interval represented by this - QUICK_RANGE into an index range endpoint specifier for the engine. - - @param Pointer to an uninitialized key_range C struct. - - @param prefix_length The length of the search key prefix to be used for - lookup. - - @param keypart_map A set (bitmap) of keyparts to be used. - */ - void make_max_endpoint(key_range *kr, uint prefix_length, - key_part_map keypart_map) { - make_max_endpoint(kr); - kr->length= MY_MIN(kr->length, prefix_length); - kr->keypart_map&= keypart_map; - } - - /** - Initalizes a key_range object for communication with storage engine. - - This function facilitates communication with the Storage Engine API by - translating the maximum endpoint of the interval represented by this - QUICK_RANGE into an index range endpoint specifier for the engine. - - @param Pointer to an uninitialized key_range C struct. - */ - void make_max_endpoint(key_range *kr) { - kr->key= (const uchar*)max_key; - kr->length= max_length; - kr->keypart_map= max_keypart_map; - /* - We use READ_AFTER_KEY here because if we are reading on a key - prefix we want to find all keys with this prefix - */ - kr->flag= (flag & NEAR_MAX ? HA_READ_BEFORE_KEY : HA_READ_AFTER_KEY); - } -}; - - -/* - Quick select interface. - This class is a parent for all QUICK_*_SELECT and FT_SELECT classes. - - The usage scenario is as follows: - 1. Create quick select - quick= new QUICK_XXX_SELECT(...); - - 2. Perform lightweight initialization. This can be done in 2 ways: - 2.a: Regular initialization - if (quick->init()) - { - //the only valid action after failed init() call is delete - delete quick; - } - 2.b: Special initialization for quick selects merged by QUICK_ROR_*_SELECT - if (quick->init_ror_merged_scan()) - delete quick; - - 3. Perform zero, one, or more scans. - while (...) - { - // initialize quick select for scan. This may allocate - // buffers and/or prefetch rows. - if (quick->reset()) - { - //the only valid action after failed reset() call is delete - delete quick; - //abort query - } - - // perform the scan - do - { - res= quick->get_next(); - } while (res && ...) - } - - 4. Delete the select: - delete quick; - - NOTE - quick select doesn't use Sql_alloc/MEM_ROOT allocation because "range - checked for each record" functionality may create/destroy - O(#records_in_some_table) quick selects during query execution. -*/ - -class QUICK_SELECT_I -{ -public: - ha_rows records; /* estimate of # of records to be retrieved */ - double read_time; /* time to perform this retrieval */ - TABLE *head; - /* - Index this quick select uses, or MAX_KEY for quick selects - that use several indexes - */ - uint index; - - /* - Total length of first used_key_parts parts of the key. - Applicable if index!= MAX_KEY. - */ - uint max_used_key_length; - - /* - Max. number of (first) key parts this quick select uses for retrieval. - eg. for "(key1p1=c1 AND key1p2=c2) OR key1p1=c2" used_key_parts == 2. - Applicable if index!= MAX_KEY. - - For QUICK_GROUP_MIN_MAX_SELECT it includes MIN/MAX argument keyparts. - */ - uint used_key_parts; - - QUICK_SELECT_I(); - virtual ~QUICK_SELECT_I(){}; - - /* - Do post-constructor initialization. - SYNOPSIS - init() - - init() performs initializations that should have been in constructor if - it was possible to return errors from constructors. The join optimizer may - create and then delete quick selects without retrieving any rows so init() - must not contain any IO or CPU intensive code. - - If init() call fails the only valid action is to delete this quick select, - reset() and get_next() must not be called. - - RETURN - 0 OK - other Error code - */ - virtual int init() = 0; - - /* - Initialize quick select for row retrieval. - SYNOPSIS - reset() - - reset() should be called when it is certain that row retrieval will be - necessary. This call may do heavyweight initialization like buffering first - N records etc. If reset() call fails get_next() must not be called. - Note that reset() may be called several times if - * the quick select is executed in a subselect - * a JOIN buffer is used - - RETURN - 0 OK - other Error code - */ - virtual int reset(void) = 0; - - virtual int get_next() = 0; /* get next record to retrieve */ - - /* Range end should be called when we have looped over the whole index */ - virtual void range_end() {} - - virtual bool reverse_sorted() = 0; - virtual bool unique_key_range() { return false; } - - /* - Request that this quick select produces sorted output. Not all quick - selects can do it, the caller is responsible for calling this function - only for those quick selects that can. - */ - virtual void need_sorted_output() = 0; - enum { - QS_TYPE_RANGE = 0, - QS_TYPE_INDEX_INTERSECT = 1, - QS_TYPE_INDEX_MERGE = 2, - QS_TYPE_RANGE_DESC = 3, - QS_TYPE_FULLTEXT = 4, - QS_TYPE_ROR_INTERSECT = 5, - QS_TYPE_ROR_UNION = 6, - QS_TYPE_GROUP_MIN_MAX = 7 - }; - - /* Get type of this quick select - one of the QS_TYPE_* values */ - virtual int get_type() = 0; - - /* - Initialize this quick select as a merged scan inside a ROR-union or a ROR- - intersection scan. The caller must not additionally call init() if this - function is called. - SYNOPSIS - init_ror_merged_scan() - reuse_handler If true, the quick select may use table->handler, - otherwise it must create and use a separate handler - object. - RETURN - 0 Ok - other Error - */ - virtual int init_ror_merged_scan(bool reuse_handler, MEM_ROOT *alloc) - { DBUG_ASSERT(0); return 1; } - - /* - Save ROWID of last retrieved row in file->ref. This used in ROR-merging. - */ - virtual void save_last_pos(){}; - - void add_key_and_length(String *key_names, - String *used_lengths, - bool *first); - - /* - Append comma-separated list of keys this quick select uses to key_names; - append comma-separated list of corresponding used lengths to used_lengths. - This is used by select_describe. - */ - virtual void add_keys_and_lengths(String *key_names, - String *used_lengths)=0; - - void add_key_name(String *str, bool *first); - - /* Save information about quick select's query plan */ - virtual Explain_quick_select* get_explain(MEM_ROOT *alloc)= 0; - - /* - Return 1 if any index used by this quick select - uses field which is marked in passed bitmap. - */ - virtual bool is_keys_used(const MY_BITMAP *fields); - - /** - Simple sanity check that the quick select has been set up - correctly. Function is overridden by quick selects that merge - indices. - */ - virtual bool is_valid() { return index != MAX_KEY; }; - - /* - rowid of last row retrieved by this quick select. This is used only when - doing ROR-index_merge selects - */ - uchar *last_rowid; - - /* - Table record buffer used by this quick select. - */ - uchar *record; - - virtual void replace_handler(handler *new_file) - { - DBUG_ASSERT(0); /* Only supported in QUICK_RANGE_SELECT */ - } - -#ifndef DBUG_OFF - /* - Print quick select information to DBUG_FILE. Caller is responsible - for locking DBUG_FILE before this call and unlocking it afterwards. - */ - virtual void dbug_dump(int indent, bool verbose)= 0; -#endif - - /* - Returns a QUICK_SELECT with reverse order of to the index. - */ - virtual QUICK_SELECT_I *make_reverse(uint used_key_parts_arg) { return NULL; } - - /* - Add the key columns used by the quick select into table's read set. - - This is used by an optimization in filesort. - */ - virtual void add_used_key_part_to_set()=0; -}; - - -struct st_qsel_param; -class PARAM; - - -/* - MRR range sequence, array implementation: sequence traversal - context. -*/ -typedef struct st_quick_range_seq_ctx -{ - QUICK_RANGE **first; - QUICK_RANGE **cur; - QUICK_RANGE **last; -} QUICK_RANGE_SEQ_CTX; - -range_seq_t quick_range_seq_init(void *init_param, uint n_ranges, uint flags); -bool quick_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range); - - -/* - Quick select that does a range scan on a single key. The records are - returned in key order. -*/ -class QUICK_RANGE_SELECT : public QUICK_SELECT_I -{ -protected: - THD *thd; - bool no_alloc; - MEM_ROOT *parent_alloc; - - /* true if we enabled key only reads */ - handler *file; - - /* Members to deal with case when this quick select is a ROR-merged scan */ - bool in_ror_merged_scan; - MY_BITMAP column_bitmap; - bool free_file; /* TRUE <=> this->file is "owned" by this quick select */ - - /* Range pointers to be used when not using MRR interface */ - /* Members needed to use the MRR interface */ - QUICK_RANGE_SEQ_CTX qr_traversal_ctx; -public: - uint mrr_flags; /* Flags to be used with MRR interface */ -protected: - uint mrr_buf_size; /* copy from thd->variables.mrr_buff_size */ - HANDLER_BUFFER *mrr_buf_desc; /* the handler buffer */ - - /* Info about index we're scanning */ - - DYNAMIC_ARRAY ranges; /* ordered array of range ptrs */ - QUICK_RANGE **cur_range; /* current element in ranges */ - - QUICK_RANGE *last_range; - - KEY_PART *key_parts; - KEY_PART_INFO *key_part_info; - - bool dont_free; /* Used by QUICK_SELECT_DESC */ - - int cmp_next(QUICK_RANGE *range); - int cmp_prev(QUICK_RANGE *range); - bool row_in_ranges(); -public: - MEM_ROOT alloc; - - QUICK_RANGE_SELECT(THD *thd, TABLE *table,uint index_arg,bool no_alloc, - MEM_ROOT *parent_alloc, bool *create_err); - ~QUICK_RANGE_SELECT(); - virtual QUICK_RANGE_SELECT *clone(bool *create_error) - { return new QUICK_RANGE_SELECT(thd, head, index, no_alloc, parent_alloc, - create_error); } - - void need_sorted_output(); - int init(); - int reset(void); - int get_next(); - void range_end(); - int get_next_prefix(uint prefix_length, uint group_key_parts, - uchar *cur_prefix); - bool reverse_sorted() { return 0; } - bool unique_key_range(); - int init_ror_merged_scan(bool reuse_handler, MEM_ROOT *alloc); - void save_last_pos() - { file->position(record); } - int get_type() { return QS_TYPE_RANGE; } - void add_keys_and_lengths(String *key_names, String *used_lengths); - Explain_quick_select *get_explain(MEM_ROOT *alloc); -#ifndef DBUG_OFF - void dbug_dump(int indent, bool verbose); -#endif - virtual void replace_handler(handler *new_file) { file= new_file; } - QUICK_SELECT_I *make_reverse(uint used_key_parts_arg); - - virtual void add_used_key_part_to_set(); - -private: - /* Default copy ctor used by QUICK_SELECT_DESC */ - friend class TRP_ROR_INTERSECT; - friend - QUICK_RANGE_SELECT *get_quick_select_for_ref(THD *thd, TABLE *table, - struct st_table_ref *ref, - ha_rows records); - friend bool get_quick_keys(PARAM *param, QUICK_RANGE_SELECT *quick, - KEY_PART *key, SEL_ARG *key_tree, - uchar *min_key, uint min_key_flag, - uchar *max_key, uint max_key_flag); - friend QUICK_RANGE_SELECT *get_quick_select(PARAM*,uint idx, - SEL_ARG *key_tree, - uint mrr_flags, - uint mrr_buf_size, - MEM_ROOT *alloc); - friend class QUICK_SELECT_DESC; - friend class QUICK_INDEX_SORT_SELECT; - friend class QUICK_INDEX_MERGE_SELECT; - friend class QUICK_ROR_INTERSECT_SELECT; - friend class QUICK_INDEX_INTERSECT_SELECT; - friend class QUICK_GROUP_MIN_MAX_SELECT; - friend bool quick_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range); - friend range_seq_t quick_range_seq_init(void *init_param, - uint n_ranges, uint flags); - friend - int read_keys_and_merge_scans(THD *thd, TABLE *head, - List quick_selects, - QUICK_RANGE_SELECT *pk_quick_select, - READ_RECORD *read_record, - bool intersection, - key_map *filtered_scans, - Unique **unique_ptr); - -}; - - -class QUICK_RANGE_SELECT_GEOM: public QUICK_RANGE_SELECT -{ -public: - QUICK_RANGE_SELECT_GEOM(THD *thd, TABLE *table, uint index_arg, - bool no_alloc, MEM_ROOT *parent_alloc, - bool *create_err) - :QUICK_RANGE_SELECT(thd, table, index_arg, no_alloc, parent_alloc, - create_err) - {}; - virtual QUICK_RANGE_SELECT *clone(bool *create_error) - { - DBUG_ASSERT(0); - return new QUICK_RANGE_SELECT_GEOM(thd, head, index, no_alloc, - parent_alloc, create_error); - } - virtual int get_next(); -}; - - -/* - QUICK_INDEX_SORT_SELECT is the base class for the common functionality of: - - QUICK_INDEX_MERGE_SELECT, access based on multi-index merge/union - - QUICK_INDEX_INTERSECT_SELECT, access based on multi-index intersection - - - QUICK_INDEX_SORT_SELECT uses - * QUICK_RANGE_SELECTs to get rows - * Unique class - - to remove duplicate rows for QUICK_INDEX_MERGE_SELECT - - to intersect rows for QUICK_INDEX_INTERSECT_SELECT - - INDEX MERGE OPTIMIZER - Current implementation doesn't detect all cases where index merge could - be used, in particular: - - * index_merge+'using index' is not supported - - * If WHERE part contains complex nested AND and OR conditions, some ways - to retrieve rows using index merge will not be considered. The choice - of read plan may depend on the order of conjuncts/disjuncts in WHERE - part of the query, see comments near imerge_list_or_list and - SEL_IMERGE::or_sel_tree_with_checks functions for details. - - * There is no "index_merge_ref" method (but index merge on non-first - table in join is possible with 'range checked for each record'). - - - ROW RETRIEVAL ALGORITHM - - index merge/intersection uses Unique class for duplicates removal. - index merge/intersection takes advantage of Clustered Primary Key (CPK) - if the table has one. - The index merge/intersection algorithm consists of two phases: - - Phase 1 - (implemented by a QUICK_INDEX_MERGE_SELECT::read_keys_and_merge call): - - prepare() - { - activate 'index only'; - while(retrieve next row for non-CPK scan) - { - if (there is a CPK scan and row will be retrieved by it) - skip this row; - else - put its rowid into Unique; - } - deactivate 'index only'; - } - - Phase 2 - (implemented as sequence of QUICK_INDEX_MERGE_SELECT::get_next calls): - - fetch() - { - retrieve all rows from row pointers stored in Unique - (merging/intersecting them); - free Unique; - if (! intersection) - retrieve all rows for CPK scan; - } -*/ - -class QUICK_INDEX_SORT_SELECT : public QUICK_SELECT_I -{ -protected: - Unique *unique; -public: - QUICK_INDEX_SORT_SELECT(THD *thd, TABLE *table); - ~QUICK_INDEX_SORT_SELECT(); - - int init(); - void need_sorted_output() { DBUG_ASSERT(0); /* Can't do it */ } - int reset(void); - bool reverse_sorted() { return false; } - bool unique_key_range() { return false; } - bool is_keys_used(const MY_BITMAP *fields); -#ifndef DBUG_OFF - void dbug_dump(int indent, bool verbose); -#endif - Explain_quick_select *get_explain(MEM_ROOT *alloc); - - bool push_quick_back(QUICK_RANGE_SELECT *quick_sel_range); - - /* range quick selects this index merge/intersect consists of */ - List quick_selects; - - /* quick select that uses clustered primary key (NULL if none) */ - QUICK_RANGE_SELECT* pk_quick_select; - - MEM_ROOT alloc; - THD *thd; - virtual bool is_valid() - { - List_iterator_fast it(quick_selects); - QUICK_RANGE_SELECT *quick; - bool valid= true; - while ((quick= it++)) - { - if (!quick->is_valid()) - { - valid= false; - break; - } - } - return valid; - } - virtual int read_keys_and_merge()= 0; - /* used to get rows collected in Unique */ - READ_RECORD read_record; - - virtual void add_used_key_part_to_set(); -}; - - - -class QUICK_INDEX_MERGE_SELECT : public QUICK_INDEX_SORT_SELECT -{ -private: - /* true if this select is currently doing a clustered PK scan */ - bool doing_pk_scan; -protected: - int read_keys_and_merge(); - -public: - QUICK_INDEX_MERGE_SELECT(THD *thd_arg, TABLE *table) - :QUICK_INDEX_SORT_SELECT(thd_arg, table) {} - - int get_next(); - int get_type() { return QS_TYPE_INDEX_MERGE; } - void add_keys_and_lengths(String *key_names, String *used_lengths); -}; - -class QUICK_INDEX_INTERSECT_SELECT : public QUICK_INDEX_SORT_SELECT -{ -protected: - int read_keys_and_merge(); - -public: - QUICK_INDEX_INTERSECT_SELECT(THD *thd_arg, TABLE *table) - :QUICK_INDEX_SORT_SELECT(thd_arg, table) {} - - key_map filtered_scans; - int get_next(); - int get_type() { return QS_TYPE_INDEX_INTERSECT; } - void add_keys_and_lengths(String *key_names, String *used_lengths); - Explain_quick_select *get_explain(MEM_ROOT *alloc); -}; - - -/* - Rowid-Ordered Retrieval (ROR) index intersection quick select. - This quick select produces intersection of row sequences returned - by several QUICK_RANGE_SELECTs it "merges". - - All merged QUICK_RANGE_SELECTs must return rowids in rowid order. - QUICK_ROR_INTERSECT_SELECT will return rows in rowid order, too. - - All merged quick selects retrieve {rowid, covered_fields} tuples (not full - table records). - QUICK_ROR_INTERSECT_SELECT retrieves full records if it is not being used - by QUICK_ROR_INTERSECT_SELECT and all merged quick selects together don't - cover needed all fields. - - If one of the merged quick selects is a Clustered PK range scan, it is - used only to filter rowid sequence produced by other merged quick selects. -*/ - -class QUICK_ROR_INTERSECT_SELECT : public QUICK_SELECT_I -{ -public: - QUICK_ROR_INTERSECT_SELECT(THD *thd, TABLE *table, - bool retrieve_full_rows, - MEM_ROOT *parent_alloc); - ~QUICK_ROR_INTERSECT_SELECT(); - - int init(); - void need_sorted_output() { DBUG_ASSERT(0); /* Can't do it */ } - int reset(void); - int get_next(); - bool reverse_sorted() { return false; } - bool unique_key_range() { return false; } - int get_type() { return QS_TYPE_ROR_INTERSECT; } - void add_keys_and_lengths(String *key_names, String *used_lengths); - Explain_quick_select *get_explain(MEM_ROOT *alloc); - bool is_keys_used(const MY_BITMAP *fields); - void add_used_key_part_to_set(); -#ifndef DBUG_OFF - void dbug_dump(int indent, bool verbose); -#endif - int init_ror_merged_scan(bool reuse_handler, MEM_ROOT *alloc); - bool push_quick_back(MEM_ROOT *alloc, QUICK_RANGE_SELECT *quick_sel_range); - - class QUICK_SELECT_WITH_RECORD : public Sql_alloc - { - public: - QUICK_RANGE_SELECT *quick; - uchar *key_tuple; - ~QUICK_SELECT_WITH_RECORD() { delete quick; } - }; - - /* - Range quick selects this intersection consists of, not including - cpk_quick. - */ - List quick_selects; - - virtual bool is_valid() - { - List_iterator_fast it(quick_selects); - QUICK_SELECT_WITH_RECORD *quick; - bool valid= true; - while ((quick= it++)) - { - if (!quick->quick->is_valid()) - { - valid= false; - break; - } - } - return valid; - } - - /* - Merged quick select that uses Clustered PK, if there is one. This quick - select is not used for row retrieval, it is used for row retrieval. - */ - QUICK_RANGE_SELECT *cpk_quick; - - MEM_ROOT alloc; /* Memory pool for this and merged quick selects data. */ - THD *thd; /* current thread */ - bool need_to_fetch_row; /* if true, do retrieve full table records. */ - /* in top-level quick select, true if merged scans where initialized */ - bool scans_inited; -}; - - -/* - Rowid-Ordered Retrieval index union select. - This quick select produces union of row sequences returned by several - quick select it "merges". - - All merged quick selects must return rowids in rowid order. - QUICK_ROR_UNION_SELECT will return rows in rowid order, too. - - All merged quick selects are set not to retrieve full table records. - ROR-union quick select always retrieves full records. - -*/ - -class QUICK_ROR_UNION_SELECT : public QUICK_SELECT_I -{ -public: - QUICK_ROR_UNION_SELECT(THD *thd, TABLE *table); - ~QUICK_ROR_UNION_SELECT(); - - int init(); - void need_sorted_output() { DBUG_ASSERT(0); /* Can't do it */ } - int reset(void); - int get_next(); - bool reverse_sorted() { return false; } - bool unique_key_range() { return false; } - int get_type() { return QS_TYPE_ROR_UNION; } - void add_keys_and_lengths(String *key_names, String *used_lengths); - Explain_quick_select *get_explain(MEM_ROOT *alloc); - bool is_keys_used(const MY_BITMAP *fields); - void add_used_key_part_to_set(); -#ifndef DBUG_OFF - void dbug_dump(int indent, bool verbose); -#endif - - bool push_quick_back(QUICK_SELECT_I *quick_sel_range); - - List quick_selects; /* Merged quick selects */ - - virtual bool is_valid() - { - List_iterator_fast it(quick_selects); - QUICK_SELECT_I *quick; - bool valid= true; - while ((quick= it++)) - { - if (!quick->is_valid()) - { - valid= false; - break; - } - } - return valid; - } - - QUEUE queue; /* Priority queue for merge operation */ - MEM_ROOT alloc; /* Memory pool for this and merged quick selects data. */ - - THD *thd; /* current thread */ - uchar *cur_rowid; /* buffer used in get_next() */ - uchar *prev_rowid; /* rowid of last row returned by get_next() */ - bool have_prev_rowid; /* true if prev_rowid has valid data */ - uint rowid_length; /* table rowid length */ -private: - bool scans_inited; -}; - - -/* - Index scan for GROUP-BY queries with MIN/MAX aggregate functions. - - This class provides a specialized index access method for GROUP-BY queries - of the forms: - - SELECT A_1,...,A_k, [B_1,...,B_m], [MIN(C)], [MAX(C)] - FROM T - WHERE [RNG(A_1,...,A_p ; where p <= k)] - [AND EQ(B_1,...,B_m)] - [AND PC(C)] - [AND PA(A_i1,...,A_iq)] - GROUP BY A_1,...,A_k; - - or - - SELECT DISTINCT A_i1,...,A_ik - FROM T - WHERE [RNG(A_1,...,A_p ; where p <= k)] - [AND PA(A_i1,...,A_iq)]; - - where all selected fields are parts of the same index. - The class of queries that can be processed by this quick select is fully - specified in the description of get_best_trp_group_min_max() in opt_range.cc. - - The get_next() method directly produces result tuples, thus obviating the - need to call end_send_group() because all grouping is already done inside - get_next(). - - Since one of the requirements is that all select fields are part of the same - index, this class produces only index keys, and not complete records. -*/ - -class QUICK_GROUP_MIN_MAX_SELECT : public QUICK_SELECT_I -{ -private: - handler * const file; /* The handler used to get data. */ - JOIN *join; /* Descriptor of the current query */ - KEY *index_info; /* The index chosen for data access */ - uchar *record; /* Buffer where the next record is returned. */ - uchar *tmp_record; /* Temporary storage for next_min(), next_max(). */ - uchar *group_prefix; /* Key prefix consisting of the GROUP fields. */ - const uint group_prefix_len; /* Length of the group prefix. */ - uint group_key_parts; /* A number of keyparts in the group prefix */ - uchar *last_prefix; /* Prefix of the last group for detecting EOF. */ - bool have_min; /* Specify whether we are computing */ - bool have_max; /* a MIN, a MAX, or both. */ - bool have_agg_distinct;/* aggregate_function(DISTINCT ...). */ - bool seen_first_key; /* Denotes whether the first key was retrieved.*/ - bool doing_key_read; /* true if we enabled key only reads */ - - KEY_PART_INFO *min_max_arg_part; /* The keypart of the only argument field */ - /* of all MIN/MAX functions. */ - uint min_max_arg_len; /* The length of the MIN/MAX argument field */ - uchar *key_infix; /* Infix of constants from equality predicates. */ - uint key_infix_len; - DYNAMIC_ARRAY min_max_ranges; /* Array of range ptrs for the MIN/MAX field. */ - uint real_prefix_len; /* Length of key prefix extended with key_infix. */ - uint real_key_parts; /* A number of keyparts in the above value. */ - List *min_functions; - List *max_functions; - List_iterator *min_functions_it; - List_iterator *max_functions_it; - /* - Use index scan to get the next different key instead of jumping into it - through index read - */ - bool is_index_scan; -public: - /* - The following two members are public to allow easy access from - TRP_GROUP_MIN_MAX::make_quick() - */ - MEM_ROOT alloc; /* Memory pool for this and quick_prefix_select data. */ - QUICK_RANGE_SELECT *quick_prefix_select;/* For retrieval of group prefixes. */ -private: - int next_prefix(); - int next_min_in_range(); - int next_max_in_range(); - int next_min(); - int next_max(); - void update_min_result(); - void update_max_result(); - int cmp_min_max_key(const uchar *key, uint16 length); -public: - QUICK_GROUP_MIN_MAX_SELECT(TABLE *table, JOIN *join, bool have_min, - bool have_max, bool have_agg_distinct, - KEY_PART_INFO *min_max_arg_part, - uint group_prefix_len, uint group_key_parts, - uint used_key_parts, KEY *index_info, uint - use_index, double read_cost, ha_rows records, uint - key_infix_len, uchar *key_infix, MEM_ROOT - *parent_alloc, bool is_index_scan); - ~QUICK_GROUP_MIN_MAX_SELECT(); - bool add_range(SEL_ARG *sel_range); - void update_key_stat(); - void adjust_prefix_ranges(); - bool alloc_buffers(); - int init(); - void need_sorted_output() { /* always do it */ } - int reset(); - int get_next(); - bool reverse_sorted() { return false; } - bool unique_key_range() { return false; } - int get_type() { return QS_TYPE_GROUP_MIN_MAX; } - void add_keys_and_lengths(String *key_names, String *used_lengths); - void add_used_key_part_to_set(); -#ifndef DBUG_OFF - void dbug_dump(int indent, bool verbose); -#endif - bool is_agg_distinct() { return have_agg_distinct; } - bool loose_scan_is_scanning() { return is_index_scan; } - Explain_quick_select *get_explain(MEM_ROOT *alloc); -}; - - -class QUICK_SELECT_DESC: public QUICK_RANGE_SELECT -{ -public: - QUICK_SELECT_DESC(QUICK_RANGE_SELECT *q, uint used_key_parts); - virtual QUICK_RANGE_SELECT *clone(bool *create_error) - { DBUG_ASSERT(0); return new QUICK_SELECT_DESC(this, used_key_parts); } - int get_next(); - bool reverse_sorted() { return 1; } - int get_type() { return QS_TYPE_RANGE_DESC; } - QUICK_SELECT_I *make_reverse(uint used_key_parts_arg) - { - return this; // is already reverse sorted - } -private: - bool range_reads_after_key(QUICK_RANGE *range); - int reset(void) { rev_it.rewind(); return QUICK_RANGE_SELECT::reset(); } - List rev_ranges; - List_iterator rev_it; - uint used_key_parts; -}; - - -class SQL_SELECT :public Sql_alloc { - public: - QUICK_SELECT_I *quick; // If quick-select used - COND *cond; // where condition - - /* - When using Index Condition Pushdown: condition that we've had before - extracting and pushing index condition. - In other cases, NULL. - */ - Item *pre_idx_push_select_cond; - TABLE *head; - IO_CACHE file; // Positions to used records - ha_rows records; // Records in use if read from file - double read_time; // Time to read rows - key_map quick_keys; // Possible quick keys - key_map needed_reg; // Possible quick keys after prev tables. - table_map const_tables,read_tables; - /* See PARAM::possible_keys */ - key_map possible_keys; - bool free_cond; /* Currently not used and always FALSE */ - - SQL_SELECT(); - ~SQL_SELECT(); - void cleanup(); - void set_quick(QUICK_SELECT_I *new_quick) { delete quick; quick= new_quick; } - bool check_quick(THD *thd, bool force_quick_range, ha_rows limit) - { - key_map tmp; - tmp.set_all(); - return test_quick_select(thd, tmp, 0, limit, force_quick_range, - FALSE, FALSE, FALSE) < 0; - } - /* - RETURN - 0 if record must be skipped <-> (cond && cond->val_int() == 0) - -1 if error - 1 otherwise - */ - inline int skip_record(THD *thd) - { - int rc= MY_TEST(!cond || cond->val_int()); - if (thd->is_error()) - rc= -1; - return rc; - } - int test_quick_select(THD *thd, key_map keys, table_map prev_tables, - ha_rows limit, bool force_quick_range, - bool ordered_output, bool remove_false_parts_of_where, - bool only_single_index_range_scan); -}; - - -class SQL_SELECT_auto -{ - SQL_SELECT *select; -public: - SQL_SELECT_auto(): select(NULL) - {} - ~SQL_SELECT_auto() - { - delete select; - } - SQL_SELECT_auto& - operator= (SQL_SELECT *_select) - { - select= _select; - return *this; - } - operator SQL_SELECT * () const - { - return select; - } - SQL_SELECT * - operator-> () const - { - return select; - } - operator bool () const - { - return select; - } -}; - - -class FT_SELECT: public QUICK_RANGE_SELECT -{ -public: - FT_SELECT(THD *thd, TABLE *table, uint key, bool *create_err) : - QUICK_RANGE_SELECT (thd, table, key, 1, NULL, create_err) - { (void) init(); } - ~FT_SELECT() { file->ft_end(); } - virtual QUICK_RANGE_SELECT *clone(bool *create_error) - { DBUG_ASSERT(0); return new FT_SELECT(thd, head, index, create_error); } - int init() { return file->ft_init(); } - int reset() { return 0; } - int get_next() { return file->ha_ft_read(record); } - int get_type() { return QS_TYPE_FULLTEXT; } -}; - -FT_SELECT *get_ft_select(THD *thd, TABLE *table, uint key); -QUICK_RANGE_SELECT *get_quick_select_for_ref(THD *thd, TABLE *table, - struct st_table_ref *ref, - ha_rows records); -SQL_SELECT *make_select(TABLE *head, table_map const_tables, - table_map read_tables, COND *conds, - SORT_INFO* filesort, - bool allow_null_cond, int *error); - -bool calculate_cond_selectivity_for_table(THD *thd, TABLE *table, Item **cond); - -bool eq_ranges_exceeds_limit(RANGE_SEQ_IF *seq, void *seq_init_param, - uint limit); - -#ifdef WITH_PARTITION_STORAGE_ENGINE -bool prune_partitions(THD *thd, TABLE *table, Item *pprune_cond); -#endif -void store_key_image_to_rec(Field *field, uchar *ptr, uint len); - -extern String null_string; - -/* check this number of rows (default value) */ -#define SELECTIVITY_SAMPLING_LIMIT 100 -/* but no more then this part of table (10%) */ -#define SELECTIVITY_SAMPLING_SHARE 0.10 -/* do not check if we are going check less then this number of records */ -#define SELECTIVITY_SAMPLING_THRESHOLD 10 - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_subselect.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_subselect.h deleted file mode 100644 index abd37f1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_subselect.h +++ /dev/null @@ -1,416 +0,0 @@ -/* - Copyright (c) 2010, 2019, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Semi-join subquery optimization code definitions -*/ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -int check_and_do_in_subquery_rewrites(JOIN *join); -bool convert_join_subqueries_to_semijoins(JOIN *join); -int pull_out_semijoin_tables(JOIN *join); -bool optimize_semijoin_nests(JOIN *join, table_map all_table_map); -bool setup_degenerate_jtbm_semi_joins(JOIN *join, - List *join_list, - List &eq_list); -bool setup_jtbm_semi_joins(JOIN *join, List *join_list, - List &eq_list); -void cleanup_empty_jtbm_semi_joins(JOIN *join, List *join_list); - -// used by Loose_scan_opt -ulonglong get_bound_sj_equalities(TABLE_LIST *sj_nest, - table_map remaining_tables); - -/* - This is a class for considering possible loose index scan optimizations. - It's usage pattern is as follows: - best_access_path() - { - Loose_scan_opt opt; - - opt.init() - for each index we can do ref access with - { - opt.next_ref_key(); - for each keyuse - opt.add_keyuse(); - opt.check_ref_access(); - } - - if (some criteria for range scans) - opt.check_range_access(); - - opt.get_best_option(); - } -*/ - -class Loose_scan_opt -{ - /* All methods must check this before doing anything else */ - bool try_loosescan; - - /* - If we consider (oe1, .. oeN) IN (SELECT ie1, .. ieN) then ieK=oeK is - called sj-equality. If oeK depends only on preceding tables then such - equality is called 'bound'. - */ - ulonglong bound_sj_equalities; - - /* Accumulated properties of ref access we're now considering: */ - ulonglong handled_sj_equalities; - key_part_map loose_scan_keyparts; - uint max_loose_keypart; - bool part1_conds_met; - - /* - Use of quick select is a special case. Some of its properties: - */ - uint quick_uses_applicable_index; - uint quick_max_loose_keypart; - - /* Best loose scan method so far */ - uint best_loose_scan_key; - double best_loose_scan_cost; - double best_loose_scan_records; - KEYUSE *best_loose_scan_start_key; - - uint best_max_loose_keypart; - table_map best_ref_depend_map; - -public: - Loose_scan_opt(): - try_loosescan(false), - bound_sj_equalities(0), - quick_uses_applicable_index(0), - quick_max_loose_keypart(0), - best_loose_scan_key(0), - best_loose_scan_cost(0), - best_loose_scan_records(0), - best_loose_scan_start_key(NULL), - best_max_loose_keypart(0), - best_ref_depend_map(0) - { - } - - void init(JOIN *join, JOIN_TAB *s, table_map remaining_tables) - { - /* - Discover the bound equalities. We need to do this if - 1. The next table is an SJ-inner table, and - 2. It is the first table from that semijoin, and - 3. We're not within a semi-join range (i.e. all semi-joins either have - all or none of their tables in join_table_map), except - s->emb_sj_nest (which we've just entered, see #2). - 4. All non-IN-equality correlation references from this sj-nest are - bound - 5. But some of the IN-equalities aren't (so this can't be handled by - FirstMatch strategy) - */ - best_loose_scan_cost= DBL_MAX; - if (!join->emb_sjm_nest && s->emb_sj_nest && // (1) - s->emb_sj_nest->sj_in_exprs < 64 && - ((remaining_tables & s->emb_sj_nest->sj_inner_tables) == // (2) - s->emb_sj_nest->sj_inner_tables) && // (2) - join->cur_sj_inner_tables == 0 && // (3) - !(remaining_tables & - s->emb_sj_nest->nested_join->sj_corr_tables) && // (4) - remaining_tables & s->emb_sj_nest->nested_join->sj_depends_on &&// (5) - optimizer_flag(join->thd, OPTIMIZER_SWITCH_LOOSE_SCAN)) - { - /* This table is an LooseScan scan candidate */ - bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest, - remaining_tables); - try_loosescan= TRUE; - DBUG_PRINT("info", ("Will try LooseScan scan, bound_map=%llx", - (longlong)bound_sj_equalities)); - } - } - - void next_ref_key() - { - handled_sj_equalities=0; - loose_scan_keyparts= 0; - max_loose_keypart= 0; - part1_conds_met= FALSE; - } - - void add_keyuse(table_map remaining_tables, KEYUSE *keyuse) - { - if (try_loosescan && keyuse->sj_pred_no != UINT_MAX && - (keyuse->table->file->index_flags(keyuse->key, 0, 1 ) & HA_READ_ORDER)) - - { - if (!(remaining_tables & keyuse->used_tables)) - { - /* - This allows to use equality propagation to infer that some - sj-equalities are bound. - */ - bound_sj_equalities |= 1ULL << keyuse->sj_pred_no; - } - else - { - handled_sj_equalities |= 1ULL << keyuse->sj_pred_no; - loose_scan_keyparts |= ((key_part_map)1) << keyuse->keypart; - set_if_bigger(max_loose_keypart, keyuse->keypart); - } - } - } - - bool have_a_case() { return MY_TEST(handled_sj_equalities); } - - void check_ref_access_part1(JOIN_TAB *s, uint key, KEYUSE *start_key, - table_map found_part) - { - /* - Check if we can use LooseScan semi-join strategy. We can if - 1. This is the right table at right location - 2. All IN-equalities are either - - "bound", ie. the outer_expr part refers to the preceding tables - - "handled", ie. covered by the index we're considering - 3. Index order allows to enumerate subquery's duplicate groups in - order. This happens when the index definition matches this - pattern: - - (handled_col|bound_col)* (other_col|bound_col) - - */ - if (try_loosescan && // (1) - (handled_sj_equalities | bound_sj_equalities) == // (2) - PREV_BITS(ulonglong, s->emb_sj_nest->sj_in_exprs) && // (2) - (PREV_BITS(key_part_map, max_loose_keypart+1) & // (3) - (found_part | loose_scan_keyparts)) == // (3) - PREV_BITS(key_part_map, max_loose_keypart+1) && // (3) - !key_uses_partial_cols(s->table->s, key)) - { - if (s->quick && s->quick->index == key && - s->quick->get_type() == QUICK_SELECT_I::QS_TYPE_RANGE) - { - quick_uses_applicable_index= TRUE; - quick_max_loose_keypart= max_loose_keypart; - } - DBUG_PRINT("info", ("Can use LooseScan scan")); - - if (found_part & 1) - { - /* Can use LooseScan on ref access if the first key part is bound */ - part1_conds_met= TRUE; - } - - /* - Check if this is a special case where there are no usable bound - IN-equalities, i.e. we have - - outer_expr IN (SELECT innertbl.key FROM ...) - - and outer_expr cannot be evaluated yet, so it's actually full - index scan and not a ref access. - We can do full index scan if it uses index-only. - */ - if (!(found_part & 1 ) && /* no usable ref access for 1st key part */ - s->table->covering_keys.is_set(key)) - { - part1_conds_met= TRUE; - DBUG_PRINT("info", ("Can use full index scan for LooseScan")); - - /* Calculate the cost of complete loose index scan. */ - double records= rows2double(s->table->file->stats.records); - - /* The cost is entire index scan cost (divided by 2) */ - double read_time= s->table->file->keyread_time(key, 1, - (ha_rows) records); - - /* - Now find out how many different keys we will get (for now we - ignore the fact that we have "keypart_i=const" restriction for - some key components, that may make us think think that loose - scan will produce more distinct records than it actually will) - */ - ulong rpc; - if ((rpc= s->table->key_info[key].rec_per_key[max_loose_keypart])) - records= records / rpc; - - // TODO: previous version also did /2 - if (read_time < best_loose_scan_cost) - { - best_loose_scan_key= key; - best_loose_scan_cost= read_time; - best_loose_scan_records= records; - best_max_loose_keypart= max_loose_keypart; - best_loose_scan_start_key= start_key; - best_ref_depend_map= 0; - } - } - } - } - - void check_ref_access_part2(uint key, KEYUSE *start_key, double records, - double read_time, table_map ref_depend_map_arg) - { - if (part1_conds_met && read_time < best_loose_scan_cost) - { - /* TODO use rec-per-key-based fanout calculations */ - best_loose_scan_key= key; - best_loose_scan_cost= read_time; - best_loose_scan_records= records; - best_max_loose_keypart= max_loose_keypart; - best_loose_scan_start_key= start_key; - best_ref_depend_map= ref_depend_map_arg; - } - } - - void check_range_access(JOIN *join, uint idx, QUICK_SELECT_I *quick) - { - /* TODO: this the right part restriction: */ - if (quick_uses_applicable_index && idx == join->const_tables && - quick->read_time < best_loose_scan_cost) - { - best_loose_scan_key= quick->index; - best_loose_scan_cost= quick->read_time; - /* this is ok because idx == join->const_tables */ - best_loose_scan_records= rows2double(quick->records); - best_max_loose_keypart= quick_max_loose_keypart; - best_loose_scan_start_key= NULL; - best_ref_depend_map= 0; - } - } - - void save_to_position(JOIN_TAB *tab, POSITION *pos) - { - pos->read_time= best_loose_scan_cost; - if (best_loose_scan_cost != DBL_MAX) - { - pos->records_read= best_loose_scan_records; - pos->key= best_loose_scan_start_key; - pos->cond_selectivity= 1.0; - pos->loosescan_picker.loosescan_key= best_loose_scan_key; - pos->loosescan_picker.loosescan_parts= best_max_loose_keypart + 1; - pos->use_join_buffer= FALSE; - pos->table= tab; - pos->range_rowid_filter_info= tab->range_rowid_filter_info; - pos->ref_depend_map= best_ref_depend_map; - DBUG_PRINT("info", ("Produced a LooseScan plan, key %s, %s", - tab->table->key_info[best_loose_scan_key].name.str, - best_loose_scan_start_key? "(ref access)": - "(range/index access)")); - } - } -}; - - -void advance_sj_state(JOIN *join, table_map remaining_tables, uint idx, - double *current_record_count, double *current_read_time, - POSITION *loose_scan_pos); -void restore_prev_sj_state(const table_map remaining_tables, - const JOIN_TAB *tab, uint idx); - -void fix_semijoin_strategies_for_picked_join_order(JOIN *join); - -bool setup_sj_materialization_part1(JOIN_TAB *sjm_tab); -bool setup_sj_materialization_part2(JOIN_TAB *sjm_tab); -uint get_number_of_tables_at_top_level(JOIN *join); - - -/* - Temporary table used by semi-join DuplicateElimination strategy - - This consists of the temptable itself and data needed to put records - into it. The table's DDL is as follows: - - CREATE TABLE tmptable (col VARCHAR(n) BINARY, PRIMARY KEY(col)); - - where the primary key can be replaced with unique constraint if n exceeds - the limit (as it is always done for query execution-time temptables). - - The record value is a concatenation of rowids of tables from the join we're - executing. If a join table is on the inner side of the outer join, we - assume that its rowid can be NULL and provide means to store this rowid in - the tuple. -*/ - -class SJ_TMP_TABLE : public Sql_alloc -{ -public: - /* - Array of pointers to tables whose rowids compose the temporary table - record. - */ - class TAB - { - public: - JOIN_TAB *join_tab; - uint rowid_offset; - ushort null_byte; - uchar null_bit; - }; - TAB *tabs; - TAB *tabs_end; - - /* - is_degenerate==TRUE means this is a special case where the temptable record - has zero length (and presence of a unique key means that the temptable can - have either 0 or 1 records). - In this case we don't create the physical temptable but instead record - its state in SJ_TMP_TABLE::have_degenerate_row. - */ - bool is_degenerate; - - /* - When is_degenerate==TRUE: the contents of the table (whether it has the - record or not). - */ - bool have_degenerate_row; - - /* table record parameters */ - uint null_bits; - uint null_bytes; - uint rowid_len; - - /* The temporary table itself (NULL means not created yet) */ - TABLE *tmp_table; - - /* - These are the members we got from temptable creation code. We'll need - them if we'll need to convert table from HEAP to MyISAM/Maria. - */ - TMP_ENGINE_COLUMNDEF *start_recinfo; - TMP_ENGINE_COLUMNDEF *recinfo; - - SJ_TMP_TABLE *next_flush_table; - - int sj_weedout_delete_rows(); - int sj_weedout_check_row(THD *thd); - bool create_sj_weedout_tmp_table(THD *thd); -}; - -int setup_semijoin_loosescan(JOIN *join); -int setup_semijoin_dups_elimination(JOIN *join, ulonglong options, - uint no_jbuf_after); -void destroy_sj_tmp_tables(JOIN *join); -int clear_sj_tmp_tables(JOIN *join); -int rewrite_to_index_subquery_engine(JOIN *join); - - -void get_delayed_table_estimates(TABLE *table, - ha_rows *out_rows, - double *scan_time, - double *startup_cost); - -enum_nested_loop_state join_tab_execution_startup(JOIN_TAB *tab); - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_trace.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_trace.h deleted file mode 100644 index 550f18c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_trace.h +++ /dev/null @@ -1,210 +0,0 @@ -#ifndef OPT_TRACE_INCLUDED -#define OPT_TRACE_INCLUDED -/* This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include "opt_trace_context.h" // Opt_trace_context -#include "sql_lex.h" -#include "my_json_writer.h" -#include "sql_select.h" -class Item; -class THD; -struct TABLE_LIST; - -/* - User-visible information about a trace. -*/ - -struct Opt_trace_info -{ - /** - String containing trace. - If trace has been end()ed, this is 0-terminated, which is only to aid - debugging or unit testing; this property is not relied upon in normal - server usage. - If trace has not been ended, this is not 0-terminated. That rare case can - happen when a substatement reads OPTIMIZER_TRACE (at that stage, the top - statement is still executing so its trace is not ended yet, but may still - be read by the sub-statement). - */ - const char *trace_ptr; - size_t trace_length; - //// String containing original query. - const char *query_ptr; - size_t query_length; - const CHARSET_INFO *query_charset; ///< charset of query string - /** - How many bytes this trace is missing (for traces which were truncated - because of @@@@optimizer-trace-max-mem-size). - The trace is not extended beyond trace-max-mem-size. - */ - size_t missing_bytes; - /* - Whether user lacks privilege to see this trace. - If this is set to TRUE, then we return an empty trace - */ - bool missing_priv; -}; - -/** - Instantiate this class to start tracing a THD's actions (generally at a - statement's start), and to set the "original" query (not transformed, as - sent by client) for the new trace. Destructor will end the trace. - - @param thd the THD - @param tbl list of tables read/written by the statement. - @param sql_command SQL command being prepared or executed - @param set_vars what variables are set by this command (only used if - sql_command is SQLCOM_SET_OPTION) - @param query query - @param length query's length - @param charset charset which was used to encode this query -*/ - - -class Opt_trace_start { - public: - Opt_trace_start(THD *thd_arg, TABLE_LIST *tbl, - enum enum_sql_command sql_command, - List *set_vars, - const char *query, - size_t query_length, - const CHARSET_INFO *query_charset); - ~Opt_trace_start(); - - private: - Opt_trace_context *const ctx; - /* - True: the query will be traced - False: otherwise - */ - bool traceable; -}; - -/** - Prints SELECT query to optimizer trace. It is not the original query (as in - @c Opt_trace_context::set_query()) but a printout of the parse tree - (Item-s). - @param thd the THD - @param select_lex query's parse tree - @param trace_object Json_writer object to which the query will be added -*/ -void opt_trace_print_expanded_query(THD *thd, SELECT_LEX *select_lex, - Json_writer_object *trace_object); - -void add_table_scan_values_to_trace(THD *thd, JOIN_TAB *tab); -void trace_plan_prefix(JOIN *join, uint idx, table_map join_tables); -void print_final_join_order(JOIN *join); -void print_best_access_for_table(THD *thd, POSITION *pos, - enum join_type type); - -/* - Security related (need to add a proper comment here) -*/ - -/** - If the security context is not that of the connected user, inform the trace - system that a privilege is missing. With one exception: see below. - - @param thd - - This serves to eliminate the following issue. - Any information readable by a SELECT may theoretically end up in - the trace. And a SELECT may read information from other places than tables: - - from views (reading their bodies) - - from stored routines (reading their bodies) - - from files (reading their content), with LOAD_FILE() - - from the list of connections (reading their queries...), with - I_S.PROCESSLIST. - If the connected user has EXECUTE privilege on a routine which does a - security context change, the routine can retrieve information internally - (if allowed by the SUID context's privileges), and present only a portion - of it to the connected user. But with tracing on, all information is - possibly in the trace. So the connected user receives more information than - the routine's definer intended to provide. Fixing this issue would require - adding, near many privilege checks in the server, a new - optimizer-trace-specific check done against the connected user's context, - to verify that the connected user has the right to see the retrieved - information. - - Instead, our chosen simpler solution is that if we see a security context - change where SUID user is not the connected user, we disable tracing. With - only one safe exception: if the connected user has all global privileges - (because then she/he can find any information anyway). By "all global - privileges" we mean everything but WITH GRANT OPTION (that latter one isn't - related to information gathering). - - Read access to I_S.OPTIMIZER_TRACE by another user than the connected user - is restricted: @see fill_optimizer_trace_info(). -*/ -void opt_trace_disable_if_no_security_context_access(THD *thd); - -void opt_trace_disable_if_no_tables_access(THD *thd, TABLE_LIST *tbl); - -/** - If tracing is on, checks additional privileges for a view, to make sure - that the user has the right to do SHOW CREATE VIEW. For that: - - this function checks SHOW VIEW - - SELECT is tested in opt_trace_disable_if_no_tables_access() - - SELECT + SHOW VIEW is sufficient for SHOW CREATE VIEW. - We also check underlying tables. - If a privilege is missing, notifies the trace system. - This function should be called when the view's underlying tables have not - yet been merged. - - @param thd THD context - @param view view to check - @param underlying_tables underlying tables/views of 'view' - */ - -void opt_trace_disable_if_no_view_access(THD *thd, TABLE_LIST *view, - TABLE_LIST *underlying_tables); - -/** - If tracing is on, checks additional privileges on a stored routine, to make - sure that the user has the right to do SHOW CREATE PROCEDURE/FUNCTION. For - that, we use the same checks as in those SHOW commands. - If a privilege is missing, notifies the trace system. - - This function is not redundant with - opt_trace_disable_if_no_security_context_access(). - Indeed, for a SQL SECURITY INVOKER routine, there is no context change, but - we must still verify that the invoker can do SHOW CREATE. - - For triggers, see note in sp_head::execute_trigger(). - - @param thd - @param sp routine to check - */ -void opt_trace_disable_if_no_stored_proc_func_access(THD *thd, sp_head *sp); - -/** - Fills information_schema.OPTIMIZER_TRACE with rows (one per trace) - @retval 0 ok - @retval 1 error -*/ -int fill_optimizer_trace_info(THD *thd, TABLE_LIST *tables, Item *); - -#define OPT_TRACE_TRANSFORM(thd, object_level0, object_level1, \ - select_number, from, to) \ - Json_writer_object object_level0(thd); \ - Json_writer_object object_level1(thd, "transformation"); \ - object_level1.add_select_number(select_number).add("from", from).add("to", to); - -#define OPT_TRACE_VIEWS_TRANSFORM(thd, object_level0, object_level1, \ - derived, name, select_number, algorithm) \ - Json_writer_object trace_wrapper(thd); \ - Json_writer_object trace_derived(thd, derived); \ - trace_derived.add("table", name).add_select_number(select_number) \ - .add("algorithm", algorithm); -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_trace_context.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_trace_context.h deleted file mode 100644 index f578a0c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/opt_trace_context.h +++ /dev/null @@ -1,135 +0,0 @@ -#ifndef OPT_TRACE_CONTEXT_INCLUDED -#define OPT_TRACE_CONTEXT_INCLUDED - -#include "sql_array.h" - -class Opt_trace_context; -struct Opt_trace_info; -class Json_writer; - -class Opt_trace_stmt { - public: - /** - Constructor, starts a trace for information_schema and dbug. - @param ctx_arg context - */ - Opt_trace_stmt(Opt_trace_context *ctx_arg); - ~Opt_trace_stmt(); - void set_query(const char *query_ptr, size_t length, const CHARSET_INFO *charset); - void open_struct(const char *key, char opening_bracket); - void close_struct(const char *saved_key, char closing_bracket); - void fill_info(Opt_trace_info* info); - void add(const char *key, char *opening_bracket, size_t val_length); - Json_writer* get_current_json() {return current_json;} - void missing_privilege(); - void disable_tracing_for_children(); - void enable_tracing_for_children(); - bool is_enabled() - { - return I_S_disabled == 0; - } - void set_allowed_mem_size(size_t mem_size); - size_t get_length(); - size_t get_truncated_bytes(); - bool get_missing_priv() { return missing_priv; } - -private: - Opt_trace_context *ctx; - String query; // store the query sent by the user - Json_writer *current_json; // stores the trace - bool missing_priv; ///< whether user lacks privilege to see this trace - /* - 0 <=> this trace should be in information_schema. - !=0 tracing is disabled, this currently happens when we want to trace a - sub-statement. For now traces are only collect for the top statement - not for the sub-statments. - */ - uint I_S_disabled; -}; - - -class Opt_trace_context -{ -public: - Opt_trace_context(); - ~Opt_trace_context(); - - void start(THD *thd, TABLE_LIST *tbl, - enum enum_sql_command sql_command, - const char *query, - size_t query_length, - const CHARSET_INFO *query_charset, - ulong max_mem_size_arg); - void end(); - void set_query(const char *query, size_t length, const CHARSET_INFO *charset); - void delete_traces(); - void set_allowed_mem_size(size_t mem_size); - size_t remaining_mem_size(); - -private: - Opt_trace_stmt* top_trace() - { - return *(traces.front()); - } - -public: - - /* - This returns the top trace from the list of traces. This function - is used when we want to see the contents of the INFORMATION_SCHEMA.OPTIMIZER_TRACE - table. - */ - - Opt_trace_stmt* get_top_trace() - { - if (!traces.elements()) - return NULL; - return top_trace(); - } - - /* - This returns the current trace, to which we are still writing and has not been finished - */ - - Json_writer* get_current_json() - { - if (!is_started()) - return NULL; - return current_trace->get_current_json(); - } - - bool empty() - { - return static_cast(traces.elements()) == 0; - } - - bool is_started() - { - return current_trace && current_trace->is_enabled(); - } - - bool disable_tracing_if_required(); - - bool enable_tracing_if_required(); - - bool is_enabled(); - - void missing_privilege(); - - static const char *flag_names[]; - enum - { - FLAG_DEFAULT = 0, - FLAG_ENABLED = 1 << 0 - }; - -private: - /* - List of traces (currently it stores only 1 trace) - */ - Dynamic_array traces; - Opt_trace_stmt *current_trace; - size_t max_mem_size; -}; - -#endif /* OPT_TRACE_CONTEXT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/parse_file.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/parse_file.h deleted file mode 100644 index cbd41d1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/parse_file.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -*- C++ -*- */ -/* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _PARSE_FILE_H_ -#define _PARSE_FILE_H_ - -#include "sql_string.h" // LEX_STRING -#include "sql_alloc.h" // Sql_alloc - -class THD; - -typedef struct st_mem_root MEM_ROOT; - -#define PARSE_FILE_TIMESTAMPLENGTH 19 - -enum file_opt_type { - FILE_OPTIONS_STRING, /**< String (LEX_STRING) */ - FILE_OPTIONS_ESTRING, /**< Escaped string (LEX_STRING) */ - FILE_OPTIONS_ULONGLONG, /**< ulonglong parameter (ulonglong) */ - FILE_OPTIONS_VIEW_ALGO, /**< Similar to longlong, but needs conversion */ - FILE_OPTIONS_TIMESTAMP, /**< timestamp (LEX_STRING have to be - allocated with length 20 (19+1) */ - FILE_OPTIONS_STRLIST, /**< list of escaped strings - (List) */ - FILE_OPTIONS_ULLLIST /**< list of ulonglong values - (List) */ -}; - -struct File_option -{ - LEX_CSTRING name; /**< Name of the option */ - my_ptrdiff_t offset; /**< offset to base address of value */ - file_opt_type type; /**< Option type */ -}; - - -/** - This hook used to catch no longer supported keys and process them for - backward compatibility. -*/ - -class Unknown_key_hook -{ -public: - Unknown_key_hook() {} /* Remove gcc warning */ - virtual ~Unknown_key_hook() {} /* Remove gcc warning */ - virtual bool process_unknown_string(const char *&unknown_key, uchar* base, - MEM_ROOT *mem_root, const char *end)= 0; -}; - - -/** Dummy hook for parsers which do not need hook for unknown keys. */ - -class File_parser_dummy_hook: public Unknown_key_hook -{ -public: - File_parser_dummy_hook() {} /* Remove gcc warning */ - virtual bool process_unknown_string(const char *&unknown_key, uchar* base, - MEM_ROOT *mem_root, const char *end); -}; - -extern File_parser_dummy_hook file_parser_dummy_hook; - -bool get_file_options_ulllist(const char *&ptr, const char *end, - const char *line, uchar* base, - File_option *parameter, - MEM_ROOT *mem_root); - -const char * -parse_escaped_string(const char *ptr, const char *end, MEM_ROOT *mem_root, - LEX_CSTRING *str); - -class File_parser; -File_parser *sql_parse_prepare(const LEX_CSTRING *file_name, - MEM_ROOT *mem_root, bool bad_format_errors); - -my_bool -sql_create_definition_file(const LEX_CSTRING *dir, - const LEX_CSTRING *file_name, - const LEX_CSTRING *type, - uchar* base, File_option *parameters); -my_bool rename_in_schema_file(THD *thd, - const char *schema, const char *old_name, - const char *new_db, const char *new_name); - -class File_parser: public Sql_alloc -{ - char *start, *end; - LEX_CSTRING file_type; - bool content_ok; -public: - File_parser() :start(0), end(0), content_ok(0) - { file_type.str= 0; file_type.length= 0; } - - bool ok() { return content_ok; } - const LEX_CSTRING *type() const { return &file_type; } - my_bool parse(uchar* base, MEM_ROOT *mem_root, - struct File_option *parameters, uint required, - Unknown_key_hook *hook) const; - - friend File_parser *sql_parse_prepare(const LEX_CSTRING *file_name, - MEM_ROOT *mem_root, - bool bad_format_errors); -}; -#endif /* _PARSE_FILE_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/partition_element.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/partition_element.h deleted file mode 100644 index ff0d0d5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/partition_element.h +++ /dev/null @@ -1,170 +0,0 @@ -#ifndef PARTITION_ELEMENT_INCLUDED -#define PARTITION_ELEMENT_INCLUDED - -/* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "my_base.h" /* ha_rows */ -#include "handler.h" /* UNDEF_NODEGROUP */ - -/** - * An enum and a struct to handle partitioning and subpartitioning. - */ -enum partition_type { - NOT_A_PARTITION= 0, - RANGE_PARTITION, - HASH_PARTITION, - LIST_PARTITION, - VERSIONING_PARTITION -}; - -enum partition_state { - PART_NORMAL= 0, - PART_IS_DROPPED= 1, - PART_TO_BE_DROPPED= 2, - PART_TO_BE_ADDED= 3, - PART_TO_BE_REORGED= 4, - PART_REORGED_DROPPED= 5, - PART_CHANGED= 6, - PART_IS_CHANGED= 7, - PART_IS_ADDED= 8, - PART_ADMIN= 9 -}; - -/* - This struct is used to keep track of column expressions as part - of the COLUMNS concept in conjunction with RANGE and LIST partitioning. - The value can be either of MINVALUE, MAXVALUE and an expression that - must be constant and evaluate to the same type as the column it - represents. - - The data in this fixed in two steps. The parser will only fill in whether - it is a max_value or provide an expression. Filling in - column_value, part_info, partition_id, null_value is done by the - function fix_column_value_function. However the item tree needs - fixed also before writing it into the frm file (in add_column_list_values). - To distinguish between those two variants, fixed= 1 after the - fixing in add_column_list_values and fixed= 2 otherwise. This is - since the fixing in add_column_list_values isn't a complete fixing. -*/ - -typedef struct p_column_list_val -{ - void* column_value; - Item* item_expression; - partition_info *part_info; - uint partition_id; - bool max_value; // MAXVALUE for RANGE type or DEFAULT value for LIST type - bool null_value; - char fixed; -} part_column_list_val; - - -/* - This struct is used to contain the value of an element - in the VALUES IN struct. It needs to keep knowledge of - whether it is a signed/unsigned value and whether it is - NULL or not. -*/ - -typedef struct p_elem_val -{ - longlong value; - uint added_items; - bool null_value; - bool unsigned_flag; - part_column_list_val *col_val_array; -} part_elem_value; - -struct st_ddl_log_memory_entry; - -enum stat_trx_field -{ - STAT_TRX_END= 0 -}; - -class partition_element :public Sql_alloc -{ -public: - enum elem_type_enum - { - CONVENTIONAL= 0, - CURRENT, - HISTORY - }; - - List subpartitions; - List list_val_list; - ha_rows part_max_rows; - ha_rows part_min_rows; - longlong range_value; - const char *partition_name; - const char *tablespace_name; - struct st_ddl_log_memory_entry *log_entry; - const char* part_comment; - const char* data_file_name; - const char* index_file_name; - handlerton *engine_type; - LEX_CSTRING connect_string; - enum partition_state part_state; - uint16 nodegroup_id; - bool has_null_value; - bool signed_flag; // Range value signed - bool max_value; // MAXVALUE range - uint32 id; - bool empty; - elem_type_enum type; - - partition_element() - : part_max_rows(0), part_min_rows(0), range_value(0), - partition_name(NULL), tablespace_name(NULL), - log_entry(NULL), part_comment(NULL), - data_file_name(NULL), index_file_name(NULL), - engine_type(NULL), connect_string(null_clex_str), part_state(PART_NORMAL), - nodegroup_id(UNDEF_NODEGROUP), has_null_value(FALSE), - signed_flag(FALSE), max_value(FALSE), - id(UINT_MAX32), - empty(true), - type(CONVENTIONAL) - {} - partition_element(partition_element *part_elem) - : part_max_rows(part_elem->part_max_rows), - part_min_rows(part_elem->part_min_rows), - range_value(0), partition_name(NULL), - tablespace_name(part_elem->tablespace_name), - part_comment(part_elem->part_comment), - data_file_name(part_elem->data_file_name), - index_file_name(part_elem->index_file_name), - engine_type(part_elem->engine_type), - connect_string(null_clex_str), - part_state(part_elem->part_state), - nodegroup_id(part_elem->nodegroup_id), - has_null_value(FALSE), - id(part_elem->id), - empty(part_elem->empty), - type(CONVENTIONAL) - {} - ~partition_element() {} - - part_column_list_val& get_col_val(uint idx) - { - part_elem_value *ev= list_val_list.head(); - DBUG_ASSERT(ev); - DBUG_ASSERT(ev->col_val_array); - return ev->col_val_array[idx]; - } -}; - -#endif /* PARTITION_ELEMENT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/partition_info.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/partition_info.h deleted file mode 100644 index 0656238..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/partition_info.h +++ /dev/null @@ -1,551 +0,0 @@ -#ifndef PARTITION_INFO_INCLUDED -#define PARTITION_INFO_INCLUDED - -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_class.h" -#include "partition_element.h" -#include "sql_partition.h" - -class partition_info; -struct TABLE_LIST; -/* Some function typedefs */ -typedef int (*get_part_id_func)(partition_info *part_info, uint32 *part_id, - longlong *func_value); -typedef int (*get_subpart_id_func)(partition_info *part_info, uint32 *part_id); -typedef bool (*check_constants_func)(THD *thd, partition_info *part_info); - -struct st_ddl_log_memory_entry; - -#define MAX_PART_NAME_SIZE 8 - - -struct Vers_part_info : public Sql_alloc -{ - Vers_part_info() : - limit(0), - now_part(NULL), - hist_part(NULL) - { - interval.type= INTERVAL_LAST; - } - Vers_part_info(Vers_part_info &src) : - interval(src.interval), - limit(src.limit), - now_part(NULL), - hist_part(NULL) - { - } - bool initialized() - { - if (now_part) - { - DBUG_ASSERT(now_part->id != UINT_MAX32); - DBUG_ASSERT(now_part->type == partition_element::CURRENT); - if (hist_part) - { - DBUG_ASSERT(hist_part->id != UINT_MAX32); - DBUG_ASSERT(hist_part->type == partition_element::HISTORY); - } - return true; - } - return false; - } - struct { - my_time_t start; - INTERVAL step; - enum interval_type type; - bool is_set() { return type < INTERVAL_LAST; } - } interval; - ulonglong limit; - partition_element *now_part; - partition_element *hist_part; -}; - -class partition_info : public Sql_alloc -{ -public: - /* - * Here comes a set of definitions needed for partitioned table handlers. - */ - List partitions; - List temp_partitions; - - List part_field_list; - List subpart_field_list; - - /* - If there is no subpartitioning, use only this func to get partition ids. - If there is subpartitioning, use the this func to get partition id when - you have both partition and subpartition fields. - */ - get_part_id_func get_partition_id; - - /* Get partition id when we don't have subpartition fields */ - get_part_id_func get_part_partition_id; - - /* - Get subpartition id when we have don't have partition fields by we do - have subpartition ids. - Mikael said that for given constant tuple - {subpart_field1, ..., subpart_fieldN} the subpartition id will be the - same in all subpartitions - */ - get_subpart_id_func get_subpartition_id; - - /* - When we have various string fields we might need some preparation - before and clean-up after calling the get_part_id_func's. We need - one such method for get_part_partition_id and one for - get_subpartition_id. - */ - get_part_id_func get_part_partition_id_charset; - get_subpart_id_func get_subpartition_id_charset; - - check_constants_func check_constants; - - /* NULL-terminated array of fields used in partitioned expression */ - Field **part_field_array; - Field **subpart_field_array; - Field **part_charset_field_array; - Field **subpart_charset_field_array; - /* - Array of all fields used in partition and subpartition expression, - without duplicates, NULL-terminated. - */ - Field **full_part_field_array; - /* - Set of all fields used in partition and subpartition expression. - Required for testing of partition fields in write_set when - updating. We need to set all bits in read_set because the row may - need to be inserted in a different [sub]partition. - */ - MY_BITMAP full_part_field_set; - - /* - When we have a field that requires transformation before calling the - partition functions we must allocate field buffers for the field of - the fields in the partition function. - */ - uchar **part_field_buffers; - uchar **subpart_field_buffers; - uchar **restore_part_field_ptrs; - uchar **restore_subpart_field_ptrs; - - Item *part_expr; - Item *subpart_expr; - - Item *item_free_list; - - struct st_ddl_log_memory_entry *first_log_entry; - struct st_ddl_log_memory_entry *exec_log_entry; - struct st_ddl_log_memory_entry *frm_log_entry; - - /* - Bitmaps of partitions used by the current query. - * read_partitions - partitions to be used for reading. - * lock_partitions - partitions that must be locked (read or write). - Usually read_partitions is the same set as lock_partitions, but - in case of UPDATE the WHERE clause can limit the read_partitions set, - but not neccesarily the lock_partitions set. - Usage pattern: - * Initialized in ha_partition::open(). - * read+lock_partitions is set according to explicit PARTITION, - WL#5217, in open_and_lock_tables(). - * Bits in read_partitions can be cleared in prune_partitions() - in the optimizing step. - (WL#4443 is about allowing prune_partitions() to affect lock_partitions - and be done before locking too). - * When the partition enabled handler get an external_lock call it locks - all partitions in lock_partitions (and remembers which partitions it - locked, so that it can unlock them later). In case of LOCK TABLES it will - lock all partitions, and keep them locked while lock_partitions can - change for each statement under LOCK TABLES. - * Freed at the same time item_free_list is freed. - */ - MY_BITMAP read_partitions; - MY_BITMAP lock_partitions; - bool bitmaps_are_initialized; - - union { - longlong *range_int_array; - LIST_PART_ENTRY *list_array; - part_column_list_val *range_col_array; - part_column_list_val *list_col_array; - }; - - Vers_part_info *vers_info; - - /******************************************** - * INTERVAL ANALYSIS - ********************************************/ - /* - Partitioning interval analysis function for partitioning, or NULL if - interval analysis is not supported for this kind of partitioning. - */ - get_partitions_in_range_iter get_part_iter_for_interval; - /* - Partitioning interval analysis function for subpartitioning, or NULL if - interval analysis is not supported for this kind of partitioning. - */ - get_partitions_in_range_iter get_subpart_iter_for_interval; - - /******************************************** - * INTERVAL ANALYSIS ENDS - ********************************************/ - - longlong err_value; - char* part_info_string; - - partition_element *curr_part_elem; // part or sub part - partition_element *current_partition; // partition - part_elem_value *curr_list_val; - uint curr_list_object; - uint num_columns; - - TABLE *table; - /* - These key_map's are used for Partitioning to enable quick decisions - on whether we can derive more information about which partition to - scan just by looking at what index is used. - */ - key_map all_fields_in_PF, all_fields_in_PPF, all_fields_in_SPF; - key_map some_fields_in_PF; - - handlerton *default_engine_type; - partition_type part_type; - partition_type subpart_type; - - uint part_info_len; - - uint num_parts; - uint num_subparts; - uint count_curr_subparts; // used during parsing - - uint num_list_values; - - uint num_part_fields; - uint num_subpart_fields; - uint num_full_part_fields; - - uint has_null_part_id; - uint32 default_partition_id; - /* - This variable is used to calculate the partition id when using - LINEAR KEY/HASH. This functionality is kept in the MySQL Server - but mainly of use to handlers supporting partitioning. - */ - uint16 linear_hash_mask; - /* - PARTITION BY KEY ALGORITHM=N - Which algorithm to use for hashing the fields. - N = 1 - Use 5.1 hashing (numeric fields are hashed as binary) - N = 2 - Use 5.5 hashing (numeric fields are hashed like latin1 bytes) - */ - enum enum_key_algorithm - { - KEY_ALGORITHM_NONE= 0, - KEY_ALGORITHM_51= 1, - KEY_ALGORITHM_55= 2 - }; - enum_key_algorithm key_algorithm; - - /* Only the number of partitions defined (uses default names and options). */ - bool use_default_partitions; - bool use_default_num_partitions; - /* Only the number of subpartitions defined (uses default names etc.). */ - bool use_default_subpartitions; - bool use_default_num_subpartitions; - bool default_partitions_setup; - bool defined_max_value; - inline bool has_default_partititon() - { - return (part_type == LIST_PARTITION && defined_max_value); - } - bool list_of_part_fields; // KEY or COLUMNS PARTITIONING - bool list_of_subpart_fields; // KEY SUBPARTITIONING - bool linear_hash_ind; // LINEAR HASH/KEY - bool fixed; - bool is_auto_partitioned; - bool has_null_value; - bool column_list; // COLUMNS PARTITIONING, 5.5+ - - partition_info() - : get_partition_id(NULL), get_part_partition_id(NULL), - get_subpartition_id(NULL), - part_field_array(NULL), subpart_field_array(NULL), - part_charset_field_array(NULL), - subpart_charset_field_array(NULL), - full_part_field_array(NULL), - part_field_buffers(NULL), subpart_field_buffers(NULL), - restore_part_field_ptrs(NULL), restore_subpart_field_ptrs(NULL), - part_expr(NULL), subpart_expr(NULL), item_free_list(NULL), - first_log_entry(NULL), exec_log_entry(NULL), frm_log_entry(NULL), - bitmaps_are_initialized(FALSE), - list_array(NULL), vers_info(NULL), err_value(0), - part_info_string(NULL), - curr_part_elem(NULL), current_partition(NULL), - curr_list_object(0), num_columns(0), table(NULL), - default_engine_type(NULL), - part_type(NOT_A_PARTITION), subpart_type(NOT_A_PARTITION), - part_info_len(0), - num_parts(0), num_subparts(0), - count_curr_subparts(0), - num_list_values(0), num_part_fields(0), num_subpart_fields(0), - num_full_part_fields(0), has_null_part_id(0), linear_hash_mask(0), - key_algorithm(KEY_ALGORITHM_NONE), - use_default_partitions(TRUE), use_default_num_partitions(TRUE), - use_default_subpartitions(TRUE), use_default_num_subpartitions(TRUE), - default_partitions_setup(FALSE), defined_max_value(FALSE), - list_of_part_fields(FALSE), list_of_subpart_fields(FALSE), - linear_hash_ind(FALSE), fixed(FALSE), - is_auto_partitioned(FALSE), - has_null_value(FALSE), column_list(FALSE) - { - all_fields_in_PF.clear_all(); - all_fields_in_PPF.clear_all(); - all_fields_in_SPF.clear_all(); - some_fields_in_PF.clear_all(); - partitions.empty(); - temp_partitions.empty(); - part_field_list.empty(); - subpart_field_list.empty(); - } - ~partition_info() {} - - partition_info *get_clone(THD *thd); - bool set_named_partition_bitmap(const char *part_name, size_t length); - bool set_partition_bitmaps(List *partition_names); - bool set_partition_bitmaps_from_table(TABLE_LIST *table_list); - /* Answers the question if subpartitioning is used for a certain table */ - bool is_sub_partitioned() - { - return (subpart_type == NOT_A_PARTITION ? FALSE : TRUE); - } - - /* Returns the total number of partitions on the leaf level */ - uint get_tot_partitions() - { - return num_parts * (is_sub_partitioned() ? num_subparts : 1); - } - - bool set_up_defaults_for_partitioning(THD *thd, handler *file, - HA_CREATE_INFO *info, - uint start_no); - const char *find_duplicate_field(); - char *find_duplicate_name(); - bool check_engine_mix(handlerton *engine_type, bool default_engine); - bool check_partition_info(THD *thd, handlerton **eng_type, - handler *file, HA_CREATE_INFO *info, - partition_info *add_or_reorg_part= NULL); - void print_no_partition_found(TABLE *table, myf errflag); - void print_debug(const char *str, uint*); - Item* get_column_item(Item *item, Field *field); - int fix_partition_values(THD *thd, - part_elem_value *val, - partition_element *part_elem); - bool fix_column_value_functions(THD *thd, - part_elem_value *val, - uint part_id); - bool fix_parser_data(THD *thd); - int add_max_value(THD *thd); - void init_col_val(part_column_list_val *col_val, Item *item); - int reorganize_into_single_field_col_val(THD *thd); - part_column_list_val *add_column_value(THD *thd); - bool set_part_expr(THD *thd, Item *item_ptr, bool is_subpart); - bool set_up_charset_field_preps(THD *thd); - bool check_partition_field_length(); - bool init_column_part(THD *thd); - bool add_column_list_value(THD *thd, Item *item); - partition_element *get_part_elem(const char *partition_name, char *file_name, - size_t file_name_size, uint32 *part_id); - void report_part_expr_error(bool use_subpart_expr); - bool has_same_partitioning(partition_info *new_part_info); - bool error_if_requires_values() const; -private: - bool set_up_default_partitions(THD *thd, handler *file, HA_CREATE_INFO *info, - uint start_no); - bool set_up_default_subpartitions(THD *thd, handler *file, - HA_CREATE_INFO *info); - char *create_default_partition_names(THD *thd, uint part_no, uint num_parts, - uint start_no); - char *create_default_subpartition_name(THD *thd, uint subpart_no, - const char *part_name); - bool prune_partition_bitmaps(List *partition_names); // set_read_partitions() in 8.0 - bool add_named_partition(const char *part_name, size_t length); -public: - bool has_unique_name(partition_element *element); - bool field_in_partition_expr(Field *field) const; - - bool vers_init_info(THD *thd); - bool vers_set_interval(THD *thd, Item *interval, - interval_type int_type, Item *starts, - const char *table_name); - bool vers_set_limit(ulonglong limit) - { - DBUG_ASSERT(part_type == VERSIONING_PARTITION); - vers_info->limit= limit; - return !limit; - } - void vers_set_hist_part(THD *thd); - bool vers_fix_field_list(THD *thd); - void vers_update_el_ids(); - partition_element *get_partition(uint part_id) - { - List_iterator it(partitions); - partition_element *el; - while ((el= it++)) - { - if (el->id == part_id) - return el; - } - return NULL; - } - uint next_part_no(uint new_parts) const; -}; - -uint32 get_next_partition_id_range(struct st_partition_iter* part_iter); -bool check_partition_dirs(partition_info *part_info); - -/* Initialize the iterator to return a single partition with given part_id */ - -static inline void init_single_partition_iterator(uint32 part_id, - PARTITION_ITERATOR *part_iter) -{ - part_iter->part_nums.start= part_iter->part_nums.cur= part_id; - part_iter->part_nums.end= part_id+1; - part_iter->ret_null_part= part_iter->ret_null_part_orig= FALSE; - part_iter->ret_default_part= part_iter->ret_default_part_orig= FALSE; - part_iter->get_next= get_next_partition_id_range; -} - -/* Initialize the iterator to enumerate all partitions */ -static inline -void init_all_partitions_iterator(partition_info *part_info, - PARTITION_ITERATOR *part_iter) -{ - part_iter->part_nums.start= part_iter->part_nums.cur= 0; - part_iter->part_nums.end= part_info->num_parts; - part_iter->ret_null_part= part_iter->ret_null_part_orig= FALSE; - part_iter->ret_default_part= part_iter->ret_default_part_orig= FALSE; - part_iter->get_next= get_next_partition_id_range; -} - - -/** - @brief Update part_field_list by row_end field name - - @returns true on error; false on success -*/ -inline -bool partition_info::vers_fix_field_list(THD * thd) -{ - if (!table->versioned()) - { - // frm must be corrupted, normally CREATE/ALTER TABLE checks for that - my_error(ER_FILE_CORRUPT, MYF(0), table->s->path.str); - return true; - } - DBUG_ASSERT(part_type == VERSIONING_PARTITION); - DBUG_ASSERT(table->versioned(VERS_TIMESTAMP)); - - Field *row_end= table->vers_end_field(); - // needed in handle_list_of_fields() - row_end->flags|= GET_FIXED_FIELDS_FLAG; - Name_resolution_context *context= &thd->lex->current_select->context; - Item *row_end_item= new (thd->mem_root) Item_field(thd, context, row_end); - Item *row_end_ts= new (thd->mem_root) Item_func_unix_timestamp(thd, row_end_item); - set_part_expr(thd, row_end_ts, false); - - return false; -} - - -/** - @brief Update partition_element's id - - @returns true on error; false on success -*/ -inline -void partition_info::vers_update_el_ids() -{ - DBUG_ASSERT(part_type == VERSIONING_PARTITION); - DBUG_ASSERT(table->versioned(VERS_TIMESTAMP)); - - List_iterator it(partitions); - partition_element *el; - for(uint32 id= 0; ((el= it++)); id++) - { - DBUG_ASSERT(el->type != partition_element::CONVENTIONAL); - /* Newly added element is inserted before AS_OF_NOW. */ - if (el->id == UINT_MAX32 || el->type == partition_element::CURRENT) - { - el->id= id; - if (el->type == partition_element::CURRENT) - break; - } - } -} - - -inline -bool make_partition_name(char *move_ptr, uint i) -{ - int res= snprintf(move_ptr, MAX_PART_NAME_SIZE + 1, "p%u", i); - return res < 0 || res > MAX_PART_NAME_SIZE; -} - - -#ifdef WITH_PARTITION_STORAGE_ENGINE -inline -uint partition_info::next_part_no(uint new_parts) const -{ - if (part_type != VERSIONING_PARTITION) - return num_parts; - DBUG_ASSERT(new_parts > 0); - /* Choose first non-occupied name suffix */ - uint32 suffix= num_parts - 1; - DBUG_ASSERT(suffix > 0); - char part_name[MAX_PART_NAME_SIZE + 1]; - List_iterator_fast it(table->part_info->partitions); - for (uint cur_part= 0; cur_part < new_parts; ++cur_part, ++suffix) - { - uint32 cur_suffix= suffix; - if (make_partition_name(part_name, suffix)) - return 0; - partition_element *el; - it.rewind(); - while ((el= it++)) - { - if (0 == my_strcasecmp(&my_charset_latin1, el->partition_name, part_name)) - { - if (make_partition_name(part_name, ++suffix)) - return 0; - it.rewind(); - } - } - if (cur_part > 0 && suffix > cur_suffix) - cur_part= 0; - } - return suffix - new_parts; -} -#endif - -#endif /* PARTITION_INFO_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/password.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/password.h deleted file mode 100644 index a076a6a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/password.h +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef PASSWORD_INCLUDED -#define PASSWORD_INCLUDED - -C_MODE_START - -void my_make_scrambled_password_323(char *to, const char *password, - size_t pass_len); -void my_make_scrambled_password(char *to, const char *password, - size_t pass_len); - -void hash_password(ulong *result, const char *password, uint password_len); - -C_MODE_END - -#endif /* PASSWORD_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_file_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_file_provider.h deleted file mode 100644 index 3df9998..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_file_provider.h +++ /dev/null @@ -1,92 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_FILE_PROVIDER_H -#define PFS_FILE_PROVIDER_H - -/** - @file include/pfs_file_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_FILE_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_FILE_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -void pfs_register_file_v1(const char *category, - PSI_file_info_v1 *info, - int count); - -void pfs_create_file_v1(PSI_file_key key, const char *name, File file); - -PSI_file_locker* -pfs_get_thread_file_name_locker_v1(PSI_file_locker_state *state, - PSI_file_key key, - PSI_file_operation op, - const char *name, const void *identity); - -PSI_file_locker* -pfs_get_thread_file_stream_locker_v1(PSI_file_locker_state *state, - PSI_file *file, PSI_file_operation op); - -PSI_file_locker* -pfs_get_thread_file_descriptor_locker_v1(PSI_file_locker_state *state, - File file, PSI_file_operation op); - -void pfs_start_file_open_wait_v1(PSI_file_locker *locker, - const char *src_file, - uint src_line); - -PSI_file* pfs_end_file_open_wait_v1(PSI_file_locker *locker, void *result); - -void pfs_end_file_open_wait_and_bind_to_descriptor_v1 - (PSI_file_locker *locker, File file); - -void pfs_end_temp_file_open_wait_and_bind_to_descriptor_v1 - (PSI_file_locker *locker, File file, const char *filename); - -void pfs_start_file_wait_v1(PSI_file_locker *locker, - size_t count, - const char *src_file, - uint src_line); - -void pfs_end_file_wait_v1(PSI_file_locker *locker, - size_t byte_count); - -void pfs_start_file_close_wait_v1(PSI_file_locker *locker, - const char *src_file, - uint src_line); - -void pfs_end_file_close_wait_v1(PSI_file_locker *locker, int rc); - -void pfs_end_file_rename_wait_v1(PSI_file_locker *locker, const char *old_name, - const char *new_name, int rc); - -C_MODE_END - -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_FILE_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_idle_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_idle_provider.h deleted file mode 100644 index 71d116f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_idle_provider.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_IDLE_PROVIDER_H -#define PFS_IDLE_PROVIDER_H - -/** - @file include/pfs_idle_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_IDLE_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_IDLE_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -PSI_idle_locker* -pfs_start_idle_wait_v1(PSI_idle_locker_state* state, const char *src_file, uint src_line); - -void pfs_end_idle_wait_v1(PSI_idle_locker* locker); - -C_MODE_END - -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_IDLE_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_memory_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_memory_provider.h deleted file mode 100644 index ea60f9d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_memory_provider.h +++ /dev/null @@ -1,57 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_MEMORY_PROVIDER_H -#define PFS_MEMORY_PROVIDER_H - -/** - @file include/pfs_memory_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_MEMORY_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_MEMORY_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -void pfs_register_memory_v1 - (const char *category, struct PSI_memory_info_v1 *info, int count); - -PSI_memory_key -pfs_memory_alloc_v1 - (PSI_memory_key key, size_t size, PSI_thread **owner); - -PSI_memory_key -pfs_memory_realloc_v1 - (PSI_memory_key key, size_t old_size, size_t new_size, PSI_thread **owner); - -void pfs_memory_free_v1 - (PSI_memory_key key, size_t size, PSI_thread *owner); - -C_MODE_END - -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_MEMORY_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_metadata_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_metadata_provider.h deleted file mode 100644 index cf3dd0d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_metadata_provider.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_METADATA_PROVIDER_H -#define PFS_METADATA_PROVIDER_H - -/** - @file include/pfs_metadata_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_METADATA_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_METADATA_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -PSI_metadata_lock* pfs_create_metadata_lock_v1 - (void *identity, - const MDL_key *key, - opaque_mdl_type mdl_type, - opaque_mdl_duration mdl_duration, - opaque_mdl_status mdl_status, - const char *src_file, - uint src_line); - -void pfs_set_metadata_lock_status_v1 - (PSI_metadata_lock *lock, - opaque_mdl_status mdl_status); - -void pfs_destroy_metadata_lock_v1(PSI_metadata_lock *lock); - -struct PSI_metadata_locker* -pfs_start_metadata_wait_v1 - (struct PSI_metadata_locker_state_v1 *state, - struct PSI_metadata_lock *mdl, - const char *src_file, uint src_line); - -void pfs_end_metadata_wait_v1 - (struct PSI_metadata_locker *locker, int rc); - -C_MODE_END - -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_METADATA_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_socket_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_socket_provider.h deleted file mode 100644 index bfafdaa..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_socket_provider.h +++ /dev/null @@ -1,71 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_SOCKET_PROVIDER_H -#define PFS_SOCKET_PROVIDER_H - -/** - @file include/pfs_socket_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_SOCKET_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_SOCKET_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -void pfs_register_socket_v1(const char *category, - PSI_socket_info_v1 *info, - int count); - -PSI_socket* -pfs_init_socket_v1(PSI_socket_key key, const my_socket *fd, - const struct sockaddr *addr, socklen_t addr_len); - -void pfs_destroy_socket_v1(PSI_socket *socket); - -PSI_socket_locker* -pfs_start_socket_wait_v1(PSI_socket_locker_state *state, - PSI_socket *socket, - PSI_socket_operation op, - size_t count, - const char *src_file, uint src_line); - -void pfs_end_socket_wait_v1(PSI_socket_locker *locker, size_t byte_count); - -void pfs_set_socket_state_v1(PSI_socket *socket, PSI_socket_state state); - -void pfs_set_socket_info_v1(PSI_socket *socket, - const my_socket *fd, - const struct sockaddr *addr, - socklen_t addr_len); - -void pfs_set_socket_thread_owner_v1(PSI_socket *socket); - -C_MODE_END - -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_SOCKET_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_stage_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_stage_provider.h deleted file mode 100644 index 2ad2faa..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_stage_provider.h +++ /dev/null @@ -1,52 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_STAGE_PROVIDER_H -#define PFS_STAGE_PROVIDER_H - -/** - @file include/pfs_stage_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_STAGE_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_STAGE_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -void pfs_register_stage_v1(const char *category, - PSI_stage_info_v1 **info_array, - int count); - -PSI_stage_progress* pfs_start_stage_v1(PSI_stage_key key, const char *src_file, int src_line); -PSI_stage_progress* pfs_get_current_stage_progress_v1(); - -void pfs_end_stage_v1(); - -C_MODE_END - -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_STAGE_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_statement_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_statement_provider.h deleted file mode 100644 index 96870d8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_statement_provider.h +++ /dev/null @@ -1,118 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_STATEMENT_PROVIDER_H -#define PFS_STATEMENT_PROVIDER_H - -/** - @file include/pfs_statement_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_STATEMENT_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_STATEMENT_CALL(M) pfs_ ## M ## _v1 -#define PSI_DIGEST_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -void pfs_register_statement_v1(const char *category, - PSI_statement_info_v1 *info, - int count); - -PSI_statement_locker* -pfs_get_thread_statement_locker_v1(PSI_statement_locker_state *state, - PSI_statement_key key, - const void *charset, - PSI_sp_share *sp_share); - -PSI_statement_locker* -pfs_refine_statement_v1(PSI_statement_locker *locker, - PSI_statement_key key); - -void pfs_start_statement_v1(PSI_statement_locker *locker, - const char *db, uint db_len, - const char *src_file, uint src_line); - -void pfs_set_statement_text_v1(PSI_statement_locker *locker, - const char *text, uint text_len); - -void pfs_set_statement_lock_time_v1(PSI_statement_locker *locker, - ulonglong count); - -void pfs_set_statement_rows_sent_v1(PSI_statement_locker *locker, - ulonglong count); - -void pfs_set_statement_rows_examined_v1(PSI_statement_locker *locker, - ulonglong count); - -void pfs_inc_statement_created_tmp_disk_tables_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_created_tmp_tables_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_select_full_join_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_select_full_range_join_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_select_range_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_select_range_check_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_select_scan_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_sort_merge_passes_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_sort_range_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_sort_rows_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_inc_statement_sort_scan_v1(PSI_statement_locker *locker, - ulong count); - -void pfs_set_statement_no_index_used_v1(PSI_statement_locker *locker); - -void pfs_set_statement_no_good_index_used_v1(PSI_statement_locker *locker); - -void pfs_end_statement_v1(PSI_statement_locker *locker, void *stmt_da); - -PSI_digest_locker *pfs_digest_start_v1(PSI_statement_locker *locker); - -void pfs_digest_end_v1(PSI_digest_locker *locker, - const sql_digest_storage *digest); - -C_MODE_END - -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_STATEMENT_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_table_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_table_provider.h deleted file mode 100644 index 0d7ee76..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_table_provider.h +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_TABLE_PROVIDER_H -#define PFS_TABLE_PROVIDER_H - -/** - @file include/pfs_table_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_TABLE_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_TABLE_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -PSI_table_share* -pfs_get_table_share_v1(my_bool temporary, struct TABLE_SHARE *share); - -void pfs_release_table_share_v1(PSI_table_share* share); - -void -pfs_drop_table_share_v1(my_bool temporary, - const char *schema_name, int schema_name_length, - const char *table_name, int table_name_length); - -PSI_table* -pfs_open_table_v1(PSI_table_share *share, const void *identity); - -void pfs_unbind_table_v1(PSI_table *table); - -PSI_table * -pfs_rebind_table_v1(PSI_table_share *share, const void *identity, PSI_table *table); - -void pfs_close_table_v1(struct TABLE_SHARE *server_share, PSI_table *table); - -PSI_table_locker* -pfs_start_table_io_wait_v1(PSI_table_locker_state *state, - PSI_table *table, - PSI_table_io_operation op, - uint index, - const char *src_file, uint src_line); - -PSI_table_locker* -pfs_start_table_lock_wait_v1(PSI_table_locker_state *state, - PSI_table *table, - PSI_table_lock_operation op, - ulong op_flags, - const char *src_file, uint src_line); - -void pfs_end_table_io_wait_v1(PSI_table_locker* locker, ulonglong numrows); - -void pfs_end_table_lock_wait_v1(PSI_table_locker* locker); - -void pfs_unlock_table_v1(PSI_table *table); - -C_MODE_END - -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_TABLE_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_thread_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_thread_provider.h deleted file mode 100644 index c4118a8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_thread_provider.h +++ /dev/null @@ -1,170 +0,0 @@ -/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_THREAD_PROVIDER_H -#define PFS_THREAD_PROVIDER_H - -/** - @file include/pfs_thread_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_THREAD_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_MUTEX_CALL(M) pfs_ ## M ## _v1 -#define PSI_RWLOCK_CALL(M) pfs_ ## M ## _v1 -#define PSI_COND_CALL(M) pfs_ ## M ## _v1 -#define PSI_THREAD_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -void pfs_register_mutex_v1(const char *category, - PSI_mutex_info_v1 *info, - int count); - -void pfs_register_rwlock_v1(const char *category, - PSI_rwlock_info_v1 *info, - int count); - -void pfs_register_cond_v1(const char *category, - PSI_cond_info_v1 *info, - int count); - -void pfs_register_thread_v1(const char *category, - PSI_thread_info_v1 *info, - int count); - -PSI_mutex* -pfs_init_mutex_v1(PSI_mutex_key key, const void *identity); - -void pfs_destroy_mutex_v1(PSI_mutex* mutex); - -PSI_rwlock* -pfs_init_rwlock_v1(PSI_rwlock_key key, const void *identity); - -void pfs_destroy_rwlock_v1(PSI_rwlock* rwlock); - -PSI_cond* -pfs_init_cond_v1(PSI_cond_key key, const void *identity); - -void pfs_destroy_cond_v1(PSI_cond* cond); - -int pfs_spawn_thread_v1(PSI_thread_key key, - pthread_t *thread, const pthread_attr_t *attr, - void *(*start_routine)(void*), void *arg); - -PSI_thread* -pfs_new_thread_v1(PSI_thread_key key, const void *identity, ulonglong processlist_id); - -void pfs_set_thread_id_v1(PSI_thread *thread, ulonglong processlist_id); -void pfs_set_thread_THD_v1(PSI_thread *thread, THD *thd); -void pfs_set_thread_os_id_v1(PSI_thread *thread); - -PSI_thread* -pfs_get_thread_v1(void); - -void pfs_set_thread_user_v1(const char *user, int user_len); - -void pfs_set_thread_account_v1(const char *user, int user_len, - const char *host, int host_len); - -void pfs_set_thread_db_v1(const char* db, int db_len); - -void pfs_set_thread_command_v1(int command); - -void pfs_set_thread_start_time_v1(time_t start_time); - -void pfs_set_thread_state_v1(const char* state); - -void pfs_set_connection_type_v1(opaque_vio_type conn_type); - -void pfs_set_thread_info_v1(const char* info, uint info_len); - -void pfs_set_thread_v1(PSI_thread* thread); - -void pfs_delete_current_thread_v1(void); - -void pfs_delete_thread_v1(PSI_thread *thread); - -PSI_mutex_locker* -pfs_start_mutex_wait_v1(PSI_mutex_locker_state *state, - PSI_mutex *mutex, PSI_mutex_operation op, - const char *src_file, uint src_line); - -PSI_rwlock_locker* -pfs_start_rwlock_rdwait_v1(PSI_rwlock_locker_state *state, - PSI_rwlock *rwlock, - PSI_rwlock_operation op, - const char *src_file, uint src_line); - -PSI_rwlock_locker* -pfs_start_rwlock_wrwait_v1(PSI_rwlock_locker_state *state, - PSI_rwlock *rwlock, - PSI_rwlock_operation op, - const char *src_file, uint src_line); - -PSI_cond_locker* -pfs_start_cond_wait_v1(PSI_cond_locker_state *state, - PSI_cond *cond, PSI_mutex *mutex, - PSI_cond_operation op, - const char *src_file, uint src_line); - -PSI_table_locker* -pfs_start_table_io_wait_v1(PSI_table_locker_state *state, - PSI_table *table, - PSI_table_io_operation op, - uint index, - const char *src_file, uint src_line); - -PSI_table_locker* -pfs_start_table_lock_wait_v1(PSI_table_locker_state *state, - PSI_table *table, - PSI_table_lock_operation op, - ulong op_flags, - const char *src_file, uint src_line); - -void pfs_unlock_mutex_v1(PSI_mutex *mutex); - -void pfs_unlock_rwlock_v1(PSI_rwlock *rwlock); - -void pfs_signal_cond_v1(PSI_cond* cond); - -void pfs_broadcast_cond_v1(PSI_cond* cond); - -void pfs_end_mutex_wait_v1(PSI_mutex_locker* locker, int rc); - -void pfs_end_rwlock_rdwait_v1(PSI_rwlock_locker* locker, int rc); - -void pfs_end_rwlock_wrwait_v1(PSI_rwlock_locker* locker, int rc); - -void pfs_end_cond_wait_v1(PSI_cond_locker* locker, int rc); - -int pfs_set_thread_connect_attrs_v1(const char *buffer, uint length, - const void *from_cs); - -C_MODE_END - -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_THREAD_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_transaction_provider.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_transaction_provider.h deleted file mode 100644 index fdaad8a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/pfs_transaction_provider.h +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ - -#ifndef PFS_TRANSACTION_PROVIDER_H -#define PFS_TRANSACTION_PROVIDER_H - -/** - @file include/pfs_transaction_provider.h - Performance schema instrumentation (declarations). -*/ - -#ifdef HAVE_PSI_TRANSACTION_INTERFACE -#ifdef MYSQL_SERVER -#ifndef EMBEDDED_LIBRARY -#ifndef MYSQL_DYNAMIC_PLUGIN - -#include "mysql/psi/psi.h" - -#define PSI_TRANSACTION_CALL(M) pfs_ ## M ## _v1 - -C_MODE_START - -PSI_transaction_locker* -pfs_get_thread_transaction_locker_v1(PSI_transaction_locker_state *state, - const void *xid, - ulonglong trxid, - int isolation_level, - my_bool read_only, - my_bool autocommit); - -void pfs_start_transaction_v1(PSI_transaction_locker *locker, - const char *src_file, uint src_line); - -void pfs_set_transaction_xid_v1(PSI_transaction_locker *locker, - const void *xid, - int xa_state); - -void pfs_set_transaction_xa_state_v1(PSI_transaction_locker *locker, - int xa_state); - -void pfs_set_transaction_gtid_v1(PSI_transaction_locker *locker, - const void *sid, - const void *gtid_spec); - -void pfs_set_transaction_trxid_v1(PSI_transaction_locker *locker, - const ulonglong *trxid); - -void pfs_inc_transaction_savepoints_v1(PSI_transaction_locker *locker, - ulong count); - -void pfs_inc_transaction_rollback_to_savepoint_v1(PSI_transaction_locker *locker, - ulong count); - -void pfs_inc_transaction_release_savepoint_v1(PSI_transaction_locker *locker, - ulong count); - -void pfs_end_transaction_v1(PSI_transaction_locker *locker, my_bool commit); - -C_MODE_END - -#endif /* MYSQL_DYNAMIC_PLUGIN */ -#endif /* EMBEDDED_LIBRARY */ -#endif /* MYSQL_SERVER */ -#endif /* HAVE_PSI_TRANSACTION_INTERFACE */ - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/privilege.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/privilege.h deleted file mode 100644 index 37cdf4d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/privilege.h +++ /dev/null @@ -1,738 +0,0 @@ -#ifndef PRIVILEGE_H_INCLUDED -#define PRIVILEGE_H_INCLUDED - -/* Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "my_global.h" // ulonglong - - -/* - A strict enum to store privilege bits. - - We should eventually make if even stricter using "enum class privilege_t" and: - - Replace all code pieces like `if (priv)` to `if (priv != NO_ACL)` - - Remove "delete" comparison operators below -*/ -enum privilege_t: unsigned long long -{ - NO_ACL = (0), - SELECT_ACL = (1UL << 0), - INSERT_ACL = (1UL << 1), - UPDATE_ACL = (1UL << 2), - DELETE_ACL = (1UL << 3), - CREATE_ACL = (1UL << 4), - DROP_ACL = (1UL << 5), - RELOAD_ACL = (1UL << 6), - SHUTDOWN_ACL = (1UL << 7), - PROCESS_ACL = (1UL << 8), - FILE_ACL = (1UL << 9), - GRANT_ACL = (1UL << 10), - REFERENCES_ACL = (1UL << 11), - INDEX_ACL = (1UL << 12), - ALTER_ACL = (1UL << 13), - SHOW_DB_ACL = (1UL << 14), - SUPER_ACL = (1UL << 15), - CREATE_TMP_ACL = (1UL << 16), - LOCK_TABLES_ACL = (1UL << 17), - EXECUTE_ACL = (1UL << 18), - REPL_SLAVE_ACL = (1UL << 19), - BINLOG_MONITOR_ACL = (1UL << 20), // Was REPL_CLIENT_ACL prior to 10.5.2 - CREATE_VIEW_ACL = (1UL << 21), - SHOW_VIEW_ACL = (1UL << 22), - CREATE_PROC_ACL = (1UL << 23), - ALTER_PROC_ACL = (1UL << 24), - CREATE_USER_ACL = (1UL << 25), - EVENT_ACL = (1UL << 26), - TRIGGER_ACL = (1UL << 27), - CREATE_TABLESPACE_ACL = (1UL << 28), - DELETE_HISTORY_ACL = (1UL << 29), // Added in 10.3.4 - SET_USER_ACL = (1UL << 30), // Added in 10.5.2 - FEDERATED_ADMIN_ACL = (1UL << 31), // Added in 10.5.2 - CONNECTION_ADMIN_ACL = (1ULL << 32), // Added in 10.5.2 - READ_ONLY_ADMIN_ACL = (1ULL << 33), // Added in 10.5.2 - REPL_SLAVE_ADMIN_ACL = (1ULL << 34), // Added in 10.5.2 - REPL_MASTER_ADMIN_ACL = (1ULL << 35), // Added in 10.5.2 - BINLOG_ADMIN_ACL = (1ULL << 36), // Added in 10.5.2 - BINLOG_REPLAY_ACL = (1ULL << 37) // Added in 10.5.2 - /* - When adding new privilege bits, don't forget to update: - In this file: - - Add a new LAST_version_ACL - - Add a new ALL_KNOWN_ACL_version - - Change ALL_KNOWN_ACL to ALL_KNOWN_ACL_version - - Change GLOBAL_ACLS if needed - - Change SUPER_ADDED_SINCE_USER_TABLE_ACL if needed - - In other files: - - static struct show_privileges_st sys_privileges[] - - static const char *command_array[] and static uint command_lengths[] - - mysql_system_tables.sql and mysql_system_tables_fix.sql - - acl_init() or whatever - to define behaviour for old privilege tables - - Update User_table_json::get_access() - - sql_yacc.yy - for GRANT/REVOKE to work - - Important: the enum should contain only single-bit values. - In this case, debuggers print bit combinations in the readable form: - (gdb) p (privilege_t) (15) - $8 = (SELECT_ACL | INSERT_ACL | UPDATE_ACL | DELETE_ACL) - - Bit-OR combinations of the above values should be declared outside! - */ -}; - - -// Version markers -constexpr privilege_t LAST_100304_ACL= DELETE_HISTORY_ACL; -constexpr privilege_t LAST_100502_ACL= BINLOG_REPLAY_ACL; - -// Current version markers -constexpr privilege_t LAST_CURRENT_ACL= LAST_100502_ACL; -constexpr uint PRIVILEGE_T_MAX_BIT= - my_bit_log2_uint64((ulonglong) LAST_CURRENT_ACL); - -static_assert((privilege_t)(1ULL << PRIVILEGE_T_MAX_BIT) == LAST_CURRENT_ACL, - "Something went fatally badly: " - "LAST_CURRENT_ACL and PRIVILEGE_T_MAX_BIT do not match"); - -// A combination of all bits defined in 10.3.4 (and earlier) -constexpr privilege_t ALL_KNOWN_ACL_100304 = - (privilege_t) ((LAST_100304_ACL << 1) - 1); - -// A combination of all bits defined in 10.5.2 -constexpr privilege_t ALL_KNOWN_ACL_100502= - (privilege_t) ((LAST_100502_ACL << 1) - 1); - -// A combination of all bits defined as of the current version -constexpr privilege_t ALL_KNOWN_ACL= ALL_KNOWN_ACL_100502; - - -// Unary operators -static inline constexpr ulonglong operator~(privilege_t access) -{ - return ~static_cast(access); -} - -/* - Comparison operators. - Delete automatic conversion between to/from integer types as much as possible. - This forces to use `(priv == NO_ACL)` instead of `(priv == 0)`. - - Note: these operators will be gone when we change privilege_t to - "enum class privilege_t". See comments above. -*/ -static inline bool operator==(privilege_t, ulonglong)= delete; -static inline bool operator==(privilege_t, ulong)= delete; -static inline bool operator==(privilege_t, uint)= delete; -static inline bool operator==(privilege_t, uchar)= delete; -static inline bool operator==(privilege_t, longlong)= delete; -static inline bool operator==(privilege_t, long)= delete; -static inline bool operator==(privilege_t, int)= delete; -static inline bool operator==(privilege_t, char)= delete; -static inline bool operator==(privilege_t, bool)= delete; - -static inline bool operator==(ulonglong, privilege_t)= delete; -static inline bool operator==(ulong, privilege_t)= delete; -static inline bool operator==(uint, privilege_t)= delete; -static inline bool operator==(uchar, privilege_t)= delete; -static inline bool operator==(longlong, privilege_t)= delete; -static inline bool operator==(long, privilege_t)= delete; -static inline bool operator==(int, privilege_t)= delete; -static inline bool operator==(char, privilege_t)= delete; -static inline bool operator==(bool, privilege_t)= delete; - -static inline bool operator!=(privilege_t, ulonglong)= delete; -static inline bool operator!=(privilege_t, ulong)= delete; -static inline bool operator!=(privilege_t, uint)= delete; -static inline bool operator!=(privilege_t, uchar)= delete; -static inline bool operator!=(privilege_t, longlong)= delete; -static inline bool operator!=(privilege_t, long)= delete; -static inline bool operator!=(privilege_t, int)= delete; -static inline bool operator!=(privilege_t, char)= delete; -static inline bool operator!=(privilege_t, bool)= delete; - -static inline bool operator!=(ulonglong, privilege_t)= delete; -static inline bool operator!=(ulong, privilege_t)= delete; -static inline bool operator!=(uint, privilege_t)= delete; -static inline bool operator!=(uchar, privilege_t)= delete; -static inline bool operator!=(longlong, privilege_t)= delete; -static inline bool operator!=(long, privilege_t)= delete; -static inline bool operator!=(int, privilege_t)= delete; -static inline bool operator!=(char, privilege_t)= delete; -static inline bool operator!=(bool, privilege_t)= delete; - - -// Dyadic bitwise operators -static inline constexpr privilege_t operator&(privilege_t a, privilege_t b) -{ - return static_cast(static_cast(a) & - static_cast(b)); -} - -static inline constexpr privilege_t operator&(ulonglong a, privilege_t b) -{ - return static_cast(a & static_cast(b)); -} - -static inline constexpr privilege_t operator&(privilege_t a, ulonglong b) -{ - return static_cast(static_cast(a) & b); -} - -static inline constexpr privilege_t operator|(privilege_t a, privilege_t b) -{ - return static_cast(static_cast(a) | - static_cast(b)); -} - - -// Dyadyc bitwise assignment operators -static inline privilege_t& operator&=(privilege_t &a, privilege_t b) -{ - return a= a & b; -} - -static inline privilege_t& operator&=(privilege_t &a, ulonglong b) -{ - return a= a & b; -} - -static inline privilege_t& operator|=(privilege_t &a, privilege_t b) -{ - return a= a | b; -} - - -/* - A combination of all SUPER privileges added since the old user table format. - These privileges are automatically added when upgrading from the - old format mysql.user table if a user has the SUPER privilege. -*/ -constexpr privilege_t GLOBAL_SUPER_ADDED_SINCE_USER_TABLE_ACLS= - SET_USER_ACL | - FEDERATED_ADMIN_ACL | - CONNECTION_ADMIN_ACL | - READ_ONLY_ADMIN_ACL | - REPL_SLAVE_ADMIN_ACL | - BINLOG_ADMIN_ACL | - BINLOG_REPLAY_ACL; - - -constexpr privilege_t COL_DML_ACLS= - SELECT_ACL | INSERT_ACL | UPDATE_ACL | DELETE_ACL; - -constexpr privilege_t VIEW_ACLS= - CREATE_VIEW_ACL | SHOW_VIEW_ACL; - -constexpr privilege_t STD_TABLE_DDL_ACLS= - CREATE_ACL | DROP_ACL | ALTER_ACL; - -constexpr privilege_t ALL_TABLE_DDL_ACLS= - STD_TABLE_DDL_ACLS | INDEX_ACL; - -constexpr privilege_t COL_ACLS= - SELECT_ACL | INSERT_ACL | UPDATE_ACL | REFERENCES_ACL; - -constexpr privilege_t PROC_DDL_ACLS= - CREATE_PROC_ACL | ALTER_PROC_ACL; - -constexpr privilege_t SHOW_PROC_ACLS= - PROC_DDL_ACLS | EXECUTE_ACL; - -constexpr privilege_t TABLE_ACLS= - COL_DML_ACLS | ALL_TABLE_DDL_ACLS | VIEW_ACLS | - GRANT_ACL | REFERENCES_ACL | - TRIGGER_ACL | DELETE_HISTORY_ACL; - -constexpr privilege_t DB_ACLS= - TABLE_ACLS | PROC_DDL_ACLS | EXECUTE_ACL | - CREATE_TMP_ACL | LOCK_TABLES_ACL | EVENT_ACL; - -constexpr privilege_t PROC_ACLS= - ALTER_PROC_ACL | EXECUTE_ACL | GRANT_ACL; - -constexpr privilege_t GLOBAL_ACLS= - DB_ACLS | SHOW_DB_ACL | - CREATE_USER_ACL | CREATE_TABLESPACE_ACL | - SUPER_ACL | RELOAD_ACL | SHUTDOWN_ACL | PROCESS_ACL | FILE_ACL | - REPL_SLAVE_ACL | BINLOG_MONITOR_ACL | - GLOBAL_SUPER_ADDED_SINCE_USER_TABLE_ACLS | - REPL_MASTER_ADMIN_ACL; - -constexpr privilege_t DEFAULT_CREATE_PROC_ACLS= - ALTER_PROC_ACL | EXECUTE_ACL; - -constexpr privilege_t SHOW_CREATE_TABLE_ACLS= - COL_DML_ACLS | ALL_TABLE_DDL_ACLS | - TRIGGER_ACL | REFERENCES_ACL | GRANT_ACL | VIEW_ACLS; - -/** - Table-level privileges which are automatically "granted" to everyone on - existing temporary tables (CREATE_ACL is necessary for ALTER ... RENAME). -*/ -constexpr privilege_t TMP_TABLE_ACLS= - COL_DML_ACLS | ALL_TABLE_DDL_ACLS; - - - -/* - Allow to set an object definer: - CREATE DEFINER=xxx {TRIGGER|VIEW|FUNCTION|PROCEDURE} - Was SUPER prior to 10.5.2 -*/ -constexpr privilege_t PRIV_DEFINER_CLAUSE= SET_USER_ACL | SUPER_ACL; -/* - If a VIEW has a `definer=invoker@host` clause and - the specified definer does not exists, then - - The invoker with REVEAL_MISSING_DEFINER_ACL gets: - ERROR: The user specified as a definer ('definer1'@'localhost') doesn't exist - - The invoker without MISSING_DEFINER_ACL gets a generic access error, - without revealing details that the definer does not exists. - - TODO: we should eventually test the same privilege when processing - other objects that have the DEFINER clause (e.g. routines, triggers). - Currently the missing definer is revealed for non-privileged invokers - in case of routines, triggers, etc. - - Was SUPER prior to 10.5.2 -*/ -constexpr privilege_t PRIV_REVEAL_MISSING_DEFINER= SET_USER_ACL | SUPER_ACL; - -/* Actions that require only the SUPER privilege */ -constexpr privilege_t PRIV_DES_DECRYPT_ONE_ARG= SUPER_ACL; -constexpr privilege_t PRIV_LOG_BIN_TRUSTED_SP_CREATOR= SUPER_ACL; -constexpr privilege_t PRIV_DEBUG= SUPER_ACL; -constexpr privilege_t PRIV_SET_GLOBAL_SYSTEM_VARIABLE= SUPER_ACL; -constexpr privilege_t PRIV_SET_RESTRICTED_SESSION_SYSTEM_VARIABLE= SUPER_ACL; - -/* The following variables respected only SUPER_ACL prior to 10.5.2 */ -constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_FORMAT= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_DIRECT_NON_TRANSACTIONAL_UPDATES= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_ANNOTATE_ROW_EVENTS= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_ROW_IMAGE= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_VAR_SQL_LOG_BIN= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_CACHE_SIZE= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_FILE_CACHE_SIZE= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_STMT_CACHE_SIZE= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_COMMIT_WAIT_COUNT= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_COMMIT_WAIT_USEC= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_ROW_METADATA= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_EXPIRE_LOGS_DAYS= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_LOG_BIN_COMPRESS= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_LOG_BIN_COMPRESS_MIN_LEN= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_LOG_BIN_TRUST_FUNCTION_CREATORS= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_BINLOG_CACHE_SIZE= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_BINLOG_STMT_CACHE_SIZE= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_BINLOG_SIZE= - SUPER_ACL | BINLOG_ADMIN_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_BINLOG= - SUPER_ACL | BINLOG_ADMIN_ACL; - - - -/* Privileges related to --read-only */ -// Was super prior to 10.5.2 -constexpr privilege_t PRIV_IGNORE_READ_ONLY= READ_ONLY_ADMIN_ACL | SUPER_ACL; -// Was super prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_READ_ONLY= - READ_ONLY_ADMIN_ACL | SUPER_ACL; - -/* - Privileges related to connection handling. -*/ -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_IGNORE_INIT_CONNECT= CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_IGNORE_MAX_USER_CONNECTIONS= CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_IGNORE_MAX_CONNECTIONS= CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_IGNORE_MAX_PASSWORD_ERRORS= CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_KILL_OTHER_USER_PROCESS= CONNECTION_ADMIN_ACL | SUPER_ACL; - -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_CONNECT_TIMEOUT= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_DISCONNECT_ON_EXPIRED_PASSWORD= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_EXTRA_MAX_CONNECTIONS= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_INIT_CONNECT= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_CONNECTIONS= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_CONNECT_ERRORS= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_PASSWORD_ERRORS= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_PROXY_PROTOCOL_NETWORKS= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SECURE_AUTH= - CONNECTION_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLOW_LAUNCH_TIME= - CONNECTION_ADMIN_ACL | SUPER_ACL; - -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_THREAD_POOL= - CONNECTION_ADMIN_ACL | SUPER_ACL; - - -/* - Binary log related privileges that are checked regardless - of active replication running. -*/ - -/* - This command was renamed from "SHOW MASTER STATUS" - to "SHOW BINLOG STATUS" in 10.5.2. - Was SUPER_ACL | REPL_CLIENT_ACL prior to 10.5.2 - REPL_CLIENT_ACL was renamed to BINLOG_MONITOR_ACL. -*/ -constexpr privilege_t PRIV_STMT_SHOW_BINLOG_STATUS= BINLOG_MONITOR_ACL | SUPER_ACL; - -/* - Was SUPER_ACL | REPL_CLIENT_ACL prior to 10.5.2 - REPL_CLIENT_ACL was renamed to BINLOG_MONITOR_ACL. -*/ -constexpr privilege_t PRIV_STMT_SHOW_BINARY_LOGS= BINLOG_MONITOR_ACL | SUPER_ACL; - -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_PURGE_BINLOG= BINLOG_ADMIN_ACL | SUPER_ACL; - -// Was REPL_SLAVE_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_SHOW_BINLOG_EVENTS= BINLOG_MONITOR_ACL; - - -/* - Privileges for replication related statements and commands - that are executed on the master. -*/ -constexpr privilege_t PRIV_COM_REGISTER_SLAVE= REPL_SLAVE_ACL; -constexpr privilege_t PRIV_COM_BINLOG_DUMP= REPL_SLAVE_ACL; -// Was REPL_SLAVE_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_SHOW_SLAVE_HOSTS= REPL_MASTER_ADMIN_ACL; - -/* - Replication master related variable privileges. - Where SUPER prior to 10.5.2 -*/ -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_ENABLED= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_TIMEOUT= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_WAIT_NO_SLAVE= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_TRACE_LEVEL= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_WAIT_POINT= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MASTER_VERIFY_CHECKSUM= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_BINLOG_STATE= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SERVER_ID= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_DOMAIN_ID= - REPL_MASTER_ADMIN_ACL | SUPER_ACL; - - -/* Privileges for statements that are executed on the slave */ -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_START_SLAVE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_STOP_SLAVE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_CHANGE_MASTER= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -// Was (SUPER_ACL | REPL_CLIENT_ACL) prior to 10.5.2 -constexpr privilege_t PRIV_STMT_SHOW_SLAVE_STATUS= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -// Was REPL_SLAVE_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_SHOW_RELAYLOG_EVENTS= REPL_SLAVE_ADMIN_ACL; - -/* - Privileges related to binlog replying. - Were SUPER_ACL prior to 10.5.2 -*/ -constexpr privilege_t PRIV_STMT_BINLOG= BINLOG_REPLAY_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_GTID_SEQ_NO= - BINLOG_REPLAY_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_PSEUDO_THREAD_ID= - BINLOG_REPLAY_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_SERVER_ID= - BINLOG_REPLAY_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_GTID_DOMAIN_ID= - BINLOG_REPLAY_ACL | SUPER_ACL; - -/* - Privileges for slave related global variables. - Were SUPER prior to 10.5.2. -*/ -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_EVENTS_MARKED_FOR_SKIP= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_DO_DB= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_DO_TABLE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_IGNORE_DB= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_IGNORE_TABLE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_WILD_DO_TABLE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_WILD_IGNORE_TABLE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_READ_BINLOG_SPEED_LIMIT= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_COMPRESSED_PROTOCOL= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_DDL_EXEC_MODE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_DOMAIN_PARALLEL_THREADS= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_EXEC_MODE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_MAX_ALLOWED_PACKET= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_NET_TIMEOUT= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_MAX_QUEUED= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_MODE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_THREADS= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_WORKERS= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_RUN_TRIGGERS_FOR_RBR= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_SQL_VERIFY_CHECKSUM= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_TRANSACTION_RETRY_INTERVAL= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_TYPE_CONVERSIONS= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_INIT_SLAVE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_ENABLED= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_TRACE_LEVEL= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_DELAY_MASTER= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_KILL_CONN_TIMEOUT= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RELAY_LOG_PURGE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RELAY_LOG_RECOVERY= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_MASTER_INFO= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_RELAY_LOG= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_RELAY_LOG_INFO= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; - -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_CLEANUP_BATCH_SIZE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_IGNORE_DUPLICATES= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_POS_AUTO_ENGINES= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_SLAVE_POS= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; -constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_STRICT_MODE= - REPL_SLAVE_ADMIN_ACL | SUPER_ACL; - - -/* Privileges for federated database related statements */ -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_CREATE_SERVER= FEDERATED_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_ALTER_SERVER= FEDERATED_ADMIN_ACL | SUPER_ACL; -// Was SUPER_ACL prior to 10.5.2 -constexpr privilege_t PRIV_STMT_DROP_SERVER= FEDERATED_ADMIN_ACL | SUPER_ACL; - - -/* Privileges related to processes */ -constexpr privilege_t PRIV_COM_PROCESS_INFO= PROCESS_ACL; -constexpr privilege_t PRIV_STMT_SHOW_EXPLAIN= PROCESS_ACL; -constexpr privilege_t PRIV_STMT_SHOW_ENGINE_STATUS= PROCESS_ACL; -constexpr privilege_t PRIV_STMT_SHOW_ENGINE_MUTEX= PROCESS_ACL; -constexpr privilege_t PRIV_STMT_SHOW_PROCESSLIST= PROCESS_ACL; - - -/* - Defines to change the above bits to how things are stored in tables - This is needed as the 'host' and 'db' table is missing a few privileges -*/ - -/* Privileges that need to be reallocated (in continous chunks) */ -constexpr privilege_t DB_CHUNK0 (COL_DML_ACLS | CREATE_ACL | DROP_ACL); -constexpr privilege_t DB_CHUNK1 (GRANT_ACL | REFERENCES_ACL | INDEX_ACL | ALTER_ACL); -constexpr privilege_t DB_CHUNK2 (CREATE_TMP_ACL | LOCK_TABLES_ACL); -constexpr privilege_t DB_CHUNK3 (VIEW_ACLS | PROC_DDL_ACLS); -constexpr privilege_t DB_CHUNK4 (EXECUTE_ACL); -constexpr privilege_t DB_CHUNK5 (EVENT_ACL | TRIGGER_ACL); -constexpr privilege_t DB_CHUNK6 (DELETE_HISTORY_ACL); - - -static inline privilege_t fix_rights_for_db(privilege_t access) -{ - ulonglong A(access); - return static_cast - (((A) & DB_CHUNK0) | - ((A << 4) & DB_CHUNK1) | - ((A << 6) & DB_CHUNK2) | - ((A << 9) & DB_CHUNK3) | - ((A << 2) & DB_CHUNK4) | - ((A << 9) & DB_CHUNK5) | - ((A << 10) & DB_CHUNK6)); -} - -static inline privilege_t get_rights_for_db(privilege_t access) -{ - ulonglong A(access); - return static_cast - ((A & DB_CHUNK0) | - ((A & DB_CHUNK1) >> 4) | - ((A & DB_CHUNK2) >> 6) | - ((A & DB_CHUNK3) >> 9) | - ((A & DB_CHUNK4) >> 2) | - ((A & DB_CHUNK5) >> 9) | - ((A & DB_CHUNK6) >> 10)); -} - - -#define TBL_CHUNK0 DB_CHUNK0 -#define TBL_CHUNK1 DB_CHUNK1 -#define TBL_CHUNK2 (CREATE_VIEW_ACL | SHOW_VIEW_ACL) -#define TBL_CHUNK3 TRIGGER_ACL -#define TBL_CHUNK4 (DELETE_HISTORY_ACL) - - -static inline privilege_t fix_rights_for_table(privilege_t access) -{ - ulonglong A(access); - return static_cast - ((A & TBL_CHUNK0) | - ((A << 4) & TBL_CHUNK1) | - ((A << 11) & TBL_CHUNK2) | - ((A << 15) & TBL_CHUNK3) | - ((A << 16) & TBL_CHUNK4)); -} - - -static inline privilege_t get_rights_for_table(privilege_t access) -{ - ulonglong A(access); - return static_cast - ((A & TBL_CHUNK0) | - ((A & TBL_CHUNK1) >> 4) | - ((A & TBL_CHUNK2) >> 11) | - ((A & TBL_CHUNK3) >> 15) | - ((A & TBL_CHUNK4) >> 16)); -} - - -static inline privilege_t fix_rights_for_column(privilege_t A) -{ - const ulonglong mask(SELECT_ACL | INSERT_ACL | UPDATE_ACL); - return (A & mask) | static_cast((A & ~mask) << 8); -} - - -static inline privilege_t get_rights_for_column(privilege_t A) -{ - const ulonglong mask(SELECT_ACL | INSERT_ACL | UPDATE_ACL); - return static_cast((static_cast(A) & mask) | - (static_cast(A) >> 8)); -} - - -static inline privilege_t fix_rights_for_procedure(privilege_t access) -{ - ulonglong A(access); - return static_cast - (((A << 18) & EXECUTE_ACL) | - ((A << 23) & ALTER_PROC_ACL) | - ((A << 8) & GRANT_ACL)); -} - - -static inline privilege_t get_rights_for_procedure(privilege_t access) -{ - ulonglong A(access); - return static_cast - (((A & EXECUTE_ACL) >> 18) | - ((A & ALTER_PROC_ACL) >> 23) | - ((A & GRANT_ACL) >> 8)); -} - - -#endif /* PRIVILEGE_H_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/probes_mysql.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/probes_mysql.h deleted file mode 100644 index ce5be04..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/probes_mysql.h +++ /dev/null @@ -1,26 +0,0 @@ -/* Copyright (c) 2008 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef PROBES_MYSQL_H - -#define PROBES_MYSQL_H - -#if defined(HAVE_DTRACE) && !defined(DISABLE_DTRACE) -#include "probes_mysql_dtrace.h" -#else /* no dtrace */ -#include "probes_mysql_nodtrace.h" -#endif -#endif /* PROBES_MYSQL_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/probes_mysql_nodtrace.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/probes_mysql_nodtrace.h deleted file mode 100644 index 2155e84..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/probes_mysql_nodtrace.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Generated by dheadgen(1). - */ - -#ifndef _PROBES_MYSQL_D -#define _PROBES_MYSQL_D - -#ifdef __cplusplus -extern "C" { -#define MYSQL_DTRACE_DISABLED false -#else -#define MYSQL_DTRACE_DISABLED 0 -#endif - -#define MYSQL_CONNECTION_START(arg0, arg1, arg2) -#define MYSQL_CONNECTION_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_CONNECTION_DONE(arg0, arg1) -#define MYSQL_CONNECTION_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_COMMAND_START(arg0, arg1, arg2, arg3) -#define MYSQL_COMMAND_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_COMMAND_DONE(arg0) -#define MYSQL_COMMAND_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_START(arg0, arg1, arg2, arg3, arg4) -#define MYSQL_QUERY_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_DONE(arg0) -#define MYSQL_QUERY_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_PARSE_START(arg0) -#define MYSQL_QUERY_PARSE_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_PARSE_DONE(arg0) -#define MYSQL_QUERY_PARSE_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_CACHE_HIT(arg0, arg1) -#define MYSQL_QUERY_CACHE_HIT_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_CACHE_MISS(arg0) -#define MYSQL_QUERY_CACHE_MISS_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_EXEC_START(arg0, arg1, arg2, arg3, arg4, arg5) -#define MYSQL_QUERY_EXEC_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_QUERY_EXEC_DONE(arg0) -#define MYSQL_QUERY_EXEC_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INSERT_ROW_START(arg0, arg1) -#define MYSQL_INSERT_ROW_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INSERT_ROW_DONE(arg0) -#define MYSQL_INSERT_ROW_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_UPDATE_ROW_START(arg0, arg1) -#define MYSQL_UPDATE_ROW_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_UPDATE_ROW_DONE(arg0) -#define MYSQL_UPDATE_ROW_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_DELETE_ROW_START(arg0, arg1) -#define MYSQL_DELETE_ROW_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_DELETE_ROW_DONE(arg0) -#define MYSQL_DELETE_ROW_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_READ_ROW_START(arg0, arg1, arg2) -#define MYSQL_READ_ROW_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_READ_ROW_DONE(arg0) -#define MYSQL_READ_ROW_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INDEX_READ_ROW_START(arg0, arg1) -#define MYSQL_INDEX_READ_ROW_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INDEX_READ_ROW_DONE(arg0) -#define MYSQL_INDEX_READ_ROW_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_HANDLER_RDLOCK_START(arg0, arg1) -#define MYSQL_HANDLER_RDLOCK_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_HANDLER_WRLOCK_START(arg0, arg1) -#define MYSQL_HANDLER_WRLOCK_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_HANDLER_UNLOCK_START(arg0, arg1) -#define MYSQL_HANDLER_UNLOCK_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_HANDLER_RDLOCK_DONE(arg0) -#define MYSQL_HANDLER_RDLOCK_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_HANDLER_WRLOCK_DONE(arg0) -#define MYSQL_HANDLER_WRLOCK_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_HANDLER_UNLOCK_DONE(arg0) -#define MYSQL_HANDLER_UNLOCK_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_FILESORT_START(arg0, arg1) -#define MYSQL_FILESORT_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_FILESORT_DONE(arg0, arg1) -#define MYSQL_FILESORT_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_SELECT_START(arg0) -#define MYSQL_SELECT_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_SELECT_DONE(arg0, arg1) -#define MYSQL_SELECT_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INSERT_START(arg0) -#define MYSQL_INSERT_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INSERT_DONE(arg0, arg1) -#define MYSQL_INSERT_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INSERT_SELECT_START(arg0) -#define MYSQL_INSERT_SELECT_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_INSERT_SELECT_DONE(arg0, arg1) -#define MYSQL_INSERT_SELECT_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_UPDATE_START(arg0) -#define MYSQL_UPDATE_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_UPDATE_DONE(arg0, arg1, arg2) -#define MYSQL_UPDATE_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_MULTI_UPDATE_START(arg0) -#define MYSQL_MULTI_UPDATE_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_MULTI_UPDATE_DONE(arg0, arg1, arg2) -#define MYSQL_MULTI_UPDATE_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_DELETE_START(arg0) -#define MYSQL_DELETE_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_DELETE_DONE(arg0, arg1) -#define MYSQL_DELETE_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_MULTI_DELETE_START(arg0) -#define MYSQL_MULTI_DELETE_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_MULTI_DELETE_DONE(arg0, arg1) -#define MYSQL_MULTI_DELETE_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_NET_READ_START() -#define MYSQL_NET_READ_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_NET_READ_DONE(arg0, arg1) -#define MYSQL_NET_READ_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_NET_WRITE_START(arg0) -#define MYSQL_NET_WRITE_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_NET_WRITE_DONE(arg0) -#define MYSQL_NET_WRITE_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_READ_START(arg0, arg1, arg2, arg3) -#define MYSQL_KEYCACHE_READ_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_READ_BLOCK(arg0) -#define MYSQL_KEYCACHE_READ_BLOCK_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_READ_HIT() -#define MYSQL_KEYCACHE_READ_HIT_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_READ_MISS() -#define MYSQL_KEYCACHE_READ_MISS_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_READ_DONE(arg0, arg1) -#define MYSQL_KEYCACHE_READ_DONE_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_WRITE_START(arg0, arg1, arg2, arg3) -#define MYSQL_KEYCACHE_WRITE_START_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_WRITE_BLOCK(arg0) -#define MYSQL_KEYCACHE_WRITE_BLOCK_ENABLED() MYSQL_DTRACE_DISABLED -#define MYSQL_KEYCACHE_WRITE_DONE(arg0, arg1) -#define MYSQL_KEYCACHE_WRITE_DONE_ENABLED() MYSQL_DTRACE_DISABLED - -#ifdef __cplusplus -} -#endif - -#endif /* _PROBES_MYSQL_D */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/procedure.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/procedure.h deleted file mode 100644 index 769eac5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/procedure.h +++ /dev/null @@ -1,184 +0,0 @@ -#ifndef PROCEDURE_INCLUDED -#define PROCEDURE_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* When using sql procedures */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -/* - It is necessary to include set_var.h instead of item.h because there - are dependencies on include order for set_var.h and item.h. This - will be resolved later. -*/ -#include "sql_class.h" /* select_result, set_var.h: THD */ -#include "set_var.h" /* Item */ - -#define PROC_NO_SORT 1 /**< Bits in flags */ -#define PROC_GROUP 2 /**< proc must have group */ - -/* Procedure items used by procedures to store values for send_result_set_metadata */ - -class Item_proc :public Item -{ -public: - Item_proc(THD *thd, const char *name_par): Item(thd) - { - this->name.str= name_par; - this->name.length= strlen(name_par); - } - enum Type type() const { return Item::PROC_ITEM; } - Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, - const Tmp_field_param *param) - { - /* - We can get to here when using a CURSOR for a query with PROCEDURE: - DECLARE c CURSOR FOR SELECT * FROM t1 PROCEDURE analyse(); - OPEN c; - */ - return create_tmp_field_ex_simple(root, table, src, param); - } - virtual void set(double nr)=0; - virtual void set(const char *str,uint length,CHARSET_INFO *cs)=0; - virtual void set(longlong nr)=0; - const Type_handler *type_handler() const=0; - void set(const char *str) { set(str,(uint) strlen(str), default_charset()); } - unsigned int size_of() { return sizeof(*this);} - bool check_vcol_func_processor(void *arg) - { - DBUG_ASSERT(0); // impossible - return mark_unsupported_function("proc", arg, VCOL_IMPOSSIBLE); - } - bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) - { - return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); - } - Item* get_copy(THD *thd) { return 0; } -}; - -class Item_proc_real :public Item_proc -{ - double value; -public: - Item_proc_real(THD *thd, const char *name_par, uint dec): - Item_proc(thd, name_par) - { - decimals=dec; max_length=float_length(dec); - } - const Type_handler *type_handler() const { return &type_handler_double; } - void set(double nr) { value=nr; } - void set(longlong nr) { value=(double) nr; } - void set(const char *str,uint length,CHARSET_INFO *cs) - { - int err_not_used; - char *end_not_used; - value= cs->strntod((char*) str,length, &end_not_used, &err_not_used); - } - double val_real() { return value; } - longlong val_int() { return (longlong) value; } - String *val_str(String *s) - { - s->set_real(value,decimals,default_charset()); - return s; - } - my_decimal *val_decimal(my_decimal *); - unsigned int size_of() { return sizeof(*this);} -}; - -class Item_proc_int :public Item_proc -{ - longlong value; -public: - Item_proc_int(THD *thd, const char *name_par): Item_proc(thd, name_par) - { max_length=11; } - const Type_handler *type_handler() const - { - if (unsigned_flag) - return &type_handler_ulonglong; - return &type_handler_slonglong; - } - void set(double nr) { value=(longlong) nr; } - void set(longlong nr) { value=nr; } - void set(const char *str,uint length, CHARSET_INFO *cs) - { int err; value= cs->strntoll(str,length,10,NULL,&err); } - double val_real() { return (double) value; } - longlong val_int() { return value; } - String *val_str(String *s) { s->set(value, default_charset()); return s; } - my_decimal *val_decimal(my_decimal *); - unsigned int size_of() { return sizeof(*this);} -}; - - -class Item_proc_string :public Item_proc -{ -public: - Item_proc_string(THD *thd, const char *name_par, uint length): - Item_proc(thd, name_par) { this->max_length=length; } - const Type_handler *type_handler() const { return &type_handler_varchar; } - void set(double nr) { str_value.set_real(nr, 2, default_charset()); } - void set(longlong nr) { str_value.set(nr, default_charset()); } - void set(const char *str, uint length, CHARSET_INFO *cs) - { str_value.copy(str,length,cs); } - double val_real() - { - int err_not_used; - char *end_not_used; - CHARSET_INFO *cs= str_value.charset(); - return cs->strntod((char*) str_value.ptr(), str_value.length(), - &end_not_used, &err_not_used); - } - longlong val_int() - { - int err; - CHARSET_INFO *cs=str_value.charset(); - return cs->strntoll(str_value.ptr(),str_value.length(),10,NULL,&err); - } - String *val_str(String*) - { - return null_value ? (String*) 0 : (String*) &str_value; - } - my_decimal *val_decimal(my_decimal *); - unsigned int size_of() { return sizeof(*this);} -}; - -/* The procedure class definitions */ - -class Procedure { -protected: - List *fields; - select_result *result; -public: - const uint flags; - ORDER *group,*param_fields; - Procedure(select_result *res,uint flags_par) :result(res),flags(flags_par), - group(0),param_fields(0) {} - virtual ~Procedure() {group=param_fields=0; fields=0; } - virtual void add(void)=0; - virtual void end_group(void)=0; - virtual int send_row(List &fields)=0; - virtual bool change_columns(THD *thd, List &fields)= 0; - virtual void update_refs(void) {} - virtual int end_of_records() { return 0; } -}; - -Procedure *setup_procedure(THD *thd,ORDER *proc_param,select_result *result, - List &field_list,int *error); - -#endif /* PROCEDURE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/protocol.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/protocol.h deleted file mode 100644 index eb11304..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/protocol.h +++ /dev/null @@ -1,331 +0,0 @@ -#ifndef PROTOCOL_INCLUDED -#define PROTOCOL_INCLUDED - -/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_error.h" -#include "my_decimal.h" /* my_decimal */ -#include "sql_type.h" - -class i_string; -class Field; -class Send_field; -class THD; -class Item_param; -struct TABLE_LIST; -typedef struct st_mysql_field MYSQL_FIELD; -typedef struct st_mysql_rows MYSQL_ROWS; - -class Protocol -{ -protected: - String *packet; - /* Used by net_store_data() for charset conversions */ - String *convert; - uint field_pos; -#ifndef DBUG_OFF - const Type_handler **field_handlers; - bool valid_handler(uint pos, protocol_send_type_t type) const - { - return field_handlers == 0 || - field_handlers[field_pos]->protocol_send_type() == type; - } -#endif - uint field_count; - virtual bool net_store_data(const uchar *from, size_t length); - virtual bool net_store_data_cs(const uchar *from, size_t length, - CHARSET_INFO *fromcs, CHARSET_INFO *tocs); - virtual bool net_send_ok(THD *, uint, uint, ulonglong, ulonglong, const char *, - bool, bool); - virtual bool net_send_error_packet(THD *, uint, const char *, const char *); -#ifdef EMBEDDED_LIBRARY - char **next_field; - MYSQL_FIELD *next_mysql_field; - MEM_ROOT *alloc; -#endif - bool needs_conversion(CHARSET_INFO *fromcs, - CHARSET_INFO *tocs) const - { - // 'tocs' is set 0 when client issues SET character_set_results=NULL - return tocs && !my_charset_same(fromcs, tocs) && - fromcs != &my_charset_bin && - tocs != &my_charset_bin; - } - /* - The following two are low-level functions that are invoked from - higher-level store_xxx() funcs. The data is stored into this->packet. - */ - bool store_string_aux(const char *from, size_t length, - CHARSET_INFO *fromcs, CHARSET_INFO *tocs); - - virtual bool send_ok(uint server_status, uint statement_warn_count, - ulonglong affected_rows, ulonglong last_insert_id, - const char *message, bool skip_flush); - - virtual bool send_eof(uint server_status, uint statement_warn_count); - - virtual bool send_error(uint sql_errno, const char *err_msg, - const char *sql_state); - - CHARSET_INFO *character_set_results() const; - -public: - THD *thd; - Protocol(THD *thd_arg) { init(thd_arg); } - virtual ~Protocol() {} - void init(THD* thd_arg); - - enum { SEND_NUM_ROWS= 1, SEND_EOF= 2 }; - virtual bool send_result_set_metadata(List *list, uint flags); - bool send_list_fields(List *list, const TABLE_LIST *table_list); - bool send_result_set_row(List *row_items); - - bool store(I_List *str_list); - bool store(const char *from, CHARSET_INFO *cs); - bool store_warning(const char *from, size_t length); - String *storage_packet() { return packet; } - inline void free() { packet->free(); } - virtual bool write(); - inline bool store(int from) - { return store_long((longlong) from); } - inline bool store(uint32 from) - { return store_long((longlong) from); } - inline bool store(longlong from) - { return store_longlong((longlong) from, 0); } - inline bool store(ulonglong from) - { return store_longlong((longlong) from, 1); } - inline bool store(String *str) - { return store((char*) str->ptr(), str->length(), str->charset()); } - - virtual bool prepare_for_send(uint num_columns) - { - field_count= num_columns; - return 0; - } - virtual bool flush(); - virtual void end_partial_result_set(THD *thd); - virtual void prepare_for_resend()=0; - - virtual bool store_null()=0; - virtual bool store_tiny(longlong from)=0; - virtual bool store_short(longlong from)=0; - virtual bool store_long(longlong from)=0; - virtual bool store_longlong(longlong from, bool unsigned_flag)=0; - virtual bool store_decimal(const my_decimal *)=0; - virtual bool store_str(const char *from, size_t length, - CHARSET_INFO *fromcs, CHARSET_INFO *tocs)=0; - virtual bool store_float(float from, uint32 decimals)=0; - virtual bool store_double(double from, uint32 decimals)=0; - virtual bool store(MYSQL_TIME *time, int decimals)=0; - virtual bool store_date(MYSQL_TIME *time)=0; - virtual bool store_time(MYSQL_TIME *time, int decimals)=0; - virtual bool store(Field *field)=0; - - // Various useful wrappers for the virtual store*() methods. - // Backward wrapper for store_str() - bool store(const char *from, size_t length, CHARSET_INFO *cs) - { - return store_str(from, length, cs, character_set_results()); - } - bool store_lex_cstring(const LEX_CSTRING &s, - CHARSET_INFO *fromcs, - CHARSET_INFO *tocs) - { - return store_str(s.str, (uint) s.length, fromcs, tocs); - } - bool store_binary_string(const char *str, size_t length) - { - return store_str(str, (uint) length, &my_charset_bin, &my_charset_bin); - } - bool store_ident(const LEX_CSTRING &s) - { - return store_lex_cstring(s, system_charset_info, character_set_results()); - } - // End of wrappers - - virtual bool send_out_parameters(List *sp_params)=0; -#ifdef EMBEDDED_LIBRARY - bool begin_dataset(); - bool begin_dataset(THD *thd, uint numfields); - virtual void remove_last_row() {} -#else - void remove_last_row() {} -#endif - enum enum_protocol_type - { - /* - Before adding a new type, please make sure - there is enough storage for it in Query_cache_query_flags. - */ - PROTOCOL_TEXT= 0, PROTOCOL_BINARY= 1, PROTOCOL_LOCAL= 2, - PROTOCOL_DISCARD= 3 /* Should be last, not used by Query_cache */ - }; - virtual enum enum_protocol_type type()= 0; - - virtual bool net_send_eof(THD *thd, uint server_status, uint statement_warn_count); - bool net_send_error(THD *thd, uint sql_errno, const char *err, - const char* sqlstate); - void end_statement(); - - friend int send_answer_1(Protocol *protocol, String *s1, String *s2, - String *s3); - friend int send_header_2(Protocol *protocol, bool for_category); -}; - - -/** Class used for the old (MySQL 4.0 protocol). */ - -class Protocol_text :public Protocol -{ - StringBuffer buffer; - bool store_numeric_string_aux(const char *from, size_t length); -public: - Protocol_text(THD *thd_arg, ulong prealloc= 0) - :Protocol(thd_arg) - { - if (prealloc) - packet->alloc(prealloc); - } - void prepare_for_resend() override; - bool store_null() override; - bool store_tiny(longlong from) override; - bool store_short(longlong from) override; - bool store_long(longlong from) override; - bool store_longlong(longlong from, bool unsigned_flag) override; - bool store_decimal(const my_decimal *) override; - bool store_str(const char *from, size_t length, - CHARSET_INFO *fromcs, CHARSET_INFO *tocs) override; - bool store(MYSQL_TIME *time, int decimals) override; - bool store_date(MYSQL_TIME *time) override; - bool store_time(MYSQL_TIME *time, int decimals) override; - bool store_float(float nr, uint32 decimals) override; - bool store_double(double from, uint32 decimals) override; - bool store(Field *field) override; - - bool send_out_parameters(List *sp_params) override; - - bool store_numeric_zerofill_str(const char *from, size_t length, - protocol_send_type_t send_type); - -#ifdef EMBEDDED_LIBRARY - void remove_last_row() override; -#endif - virtual bool store_field_metadata(const THD *thd, const Send_field &field, - CHARSET_INFO *charset_for_protocol, - uint pos); - bool store_item_metadata(THD *thd, Item *item, uint pos); - bool store_field_metadata_for_list_fields(const THD *thd, Field *field, - const TABLE_LIST *table_list, - uint pos); - enum enum_protocol_type type() override { return PROTOCOL_TEXT; }; -}; - - -class Protocol_binary final :public Protocol -{ -private: - uint bit_fields; -public: - Protocol_binary(THD *thd_arg) :Protocol(thd_arg) {} - bool prepare_for_send(uint num_columns) override; - void prepare_for_resend() override; -#ifdef EMBEDDED_LIBRARY - bool write() override; - bool net_store_data(const uchar *from, size_t length) override; - bool net_store_data_cs(const uchar *from, size_t length, - CHARSET_INFO *fromcs, CHARSET_INFO *tocs) override; -#endif - bool store_null() override; - bool store_tiny(longlong from) override; - bool store_short(longlong from) override; - bool store_long(longlong from) override; - bool store_longlong(longlong from, bool unsigned_flag) override; - bool store_decimal(const my_decimal *) override; - bool store_str(const char *from, size_t length, - CHARSET_INFO *fromcs, CHARSET_INFO *tocs) override; - bool store(MYSQL_TIME *time, int decimals) override; - bool store_date(MYSQL_TIME *time) override; - bool store_time(MYSQL_TIME *time, int decimals) override; - bool store_float(float nr, uint32 decimals) override; - bool store_double(double from, uint32 decimals) override; - bool store(Field *field) override; - - bool send_out_parameters(List *sp_params) override; - - enum enum_protocol_type type() override { return PROTOCOL_BINARY; }; -}; - - -/* - A helper for "ANALYZE $stmt" which looks a real network procotol but doesn't - write results to the network. - - At first glance, class select_send looks like a more appropriate place to - implement the "write nothing" hook. This is not true, because - - we need to evaluate the value of every item, and do it the way - select_send does it (i.e. call item->val_int() or val_real() or...) - - select_send::send_data() has some other code, like telling the storage - engine that the row can be unlocked. We want to keep that also. - as a result, "ANALYZE $stmt" uses a select_send_analyze which still uses - select_send::send_data() & co., and also uses Protocol_discard object. -*/ - -class Protocol_discard final : public Protocol -{ -public: - Protocol_discard(THD *thd_arg) : Protocol(thd_arg) {} - bool write() override { return 0; } - bool send_result_set_metadata(List *, uint) override { return 0; } - bool send_eof(uint, uint) override { return 0; } - void prepare_for_resend() override { IF_DBUG(field_pos= 0,); } - bool send_out_parameters(List *sp_params) override { return false; } - - /* - Provide dummy overrides for any storage methods so that we - avoid allocating and copying of data - */ - bool store_null() override { return false; } - bool store_tiny(longlong) override { return false; } - bool store_short(longlong) override { return false; } - bool store_long(longlong) override { return false; } - bool store_longlong(longlong, bool) override { return false; } - bool store_decimal(const my_decimal *) override { return false; } - bool store_str(const char *, size_t, CHARSET_INFO *, CHARSET_INFO *) override - { - return false; - } - bool store(MYSQL_TIME *, int) override { return false; } - bool store_date(MYSQL_TIME *) override { return false; } - bool store_time(MYSQL_TIME *, int) override { return false; } - bool store_float(float, uint32) override { return false; } - bool store_double(double, uint32) override { return false; } - bool store(Field *) override { return false; } - enum enum_protocol_type type() override { return PROTOCOL_DISCARD; }; -}; - - -void send_warning(THD *thd, uint sql_errno, const char *err=0); -void net_send_progress_packet(THD *thd); -uchar *net_store_data(uchar *to,const uchar *from, size_t length); -uchar *net_store_data(uchar *to,int32 from); -uchar *net_store_data(uchar *to,longlong from); - -#endif /* PROTOCOL_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/proxy_protocol.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/proxy_protocol.h deleted file mode 100644 index 0f873e2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/proxy_protocol.h +++ /dev/null @@ -1,19 +0,0 @@ -#include "my_net.h" - -struct proxy_peer_info -{ - struct sockaddr_storage peer_addr; - int port; - bool is_local_command; -}; - -extern bool has_proxy_protocol_header(NET *net); -extern int parse_proxy_protocol_header(NET *net, proxy_peer_info *peer_info); -extern bool is_proxy_protocol_allowed(const sockaddr *remote_addr); - -extern int init_proxy_protocol_networks(const char *spec); -extern void destroy_proxy_protocol_networks(); - -extern int set_proxy_protocol_networks(const char *spec); -extern bool proxy_protocol_networks_valid(const char *spec); - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/queues.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/queues.h deleted file mode 100644 index e994885..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/queues.h +++ /dev/null @@ -1,87 +0,0 @@ -/* Copyright (C) 2010 Monty Program Ab - 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 following disclaimer - in the documentation and/or other materials provided with the - distribution. - - 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 - 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. -*/ - -/* - Code for generell handling of priority Queues. - Implementation of queues from "Algorithms in C" by Robert Sedgewick. -*/ - -#ifndef _queues_h -#define _queues_h - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct st_queue { - uchar **root; - void *first_cmp_arg; - uint elements; - uint max_elements; - uint offset_to_key; /* compare is done on element+offset */ - uint offset_to_queue_pos; /* If we want to store position in element */ - uint auto_extent; - int max_at_top; /* Normally 1, set to -1 if queue_top gives max */ - int (*compare)(void *, uchar *,uchar *); -} QUEUE; - -#define queue_first_element(queue) 1 -#define queue_last_element(queue) (queue)->elements -#define queue_empty(queue) ((queue)->elements == 0) -#define queue_top(queue) ((queue)->root[1]) -#define queue_element(queue,index) ((queue)->root[index]) -#define queue_end(queue) ((queue)->root[(queue)->elements]) -#define queue_replace_top(queue) _downheap(queue, 1) -#define queue_set_cmp_arg(queue, set_arg) (queue)->first_cmp_arg= set_arg -#define queue_set_max_at_top(queue, set_arg) \ - (queue)->max_at_top= set_arg ? -1 : 1 -#define queue_remove_top(queue_arg) queue_remove((queue_arg), queue_first_element(queue_arg)) -typedef int (*queue_compare)(void *,uchar *, uchar *); - -int init_queue(QUEUE *queue,uint max_elements,uint offset_to_key, - my_bool max_at_top, queue_compare compare, - void *first_cmp_arg, uint offset_to_queue_pos, - uint auto_extent); -int reinit_queue(QUEUE *queue,uint max_elements,uint offset_to_key, - my_bool max_at_top, queue_compare compare, - void *first_cmp_arg, uint offset_to_queue_pos, - uint auto_extent); -int resize_queue(QUEUE *queue, uint max_elements); -void delete_queue(QUEUE *queue); -void queue_insert(QUEUE *queue, uchar *element); -int queue_insert_safe(QUEUE *queue, uchar *element); -uchar *queue_remove(QUEUE *queue,uint idx); -void queue_replace(QUEUE *queue,uint idx); - -#define queue_remove_all(queue) { (queue)->elements= 0; } -#define queue_is_full(queue) (queue->elements == queue->max_elements) -void _downheap(QUEUE *queue, uint idx); -void queue_fix(QUEUE *queue); -#define is_queue_inited(queue) ((queue)->root != 0) - -#ifdef __cplusplus -} -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/records.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/records.h deleted file mode 100644 index 272bbd0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/records.h +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef SQL_RECORDS_H -#define SQL_RECORDS_H -/* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "table.h" - -struct st_join_table; -class handler; -class THD; -class SQL_SELECT; -class Copy_field; -class SORT_INFO; - -struct READ_RECORD; - -void end_read_record(READ_RECORD *info); -void free_cache(READ_RECORD *info); - -/** - A context for reading through a single table using a chosen access method: - index read, scan, etc, use of cache, etc. - - Use by: - READ_RECORD read_record; - init_read_record(&read_record, ...); - while (read_record.read_record()) - { - ... - } - end_read_record(); -*/ - -struct READ_RECORD -{ - typedef int (*Read_func)(READ_RECORD*); - typedef void (*Unlock_row_func)(st_join_table *); - typedef int (*Setup_func)(struct st_join_table*); - - TABLE *table; /* Head-form */ - Unlock_row_func unlock_row; - Read_func read_record_func; - THD *thd; - SQL_SELECT *select; - uint ref_length, reclength, rec_cache_size, error_offset; - - /** - Counting records when reading result from filesort(). - Used when filesort leaves the result in the filesort buffer. - */ - ha_rows unpack_counter; - - uchar *ref_pos; /* pointer to form->refpos */ - uchar *rec_buf; /* to read field values after filesort */ - uchar *cache,*cache_pos,*cache_end,*read_positions; - - /* - Structure storing information about sorting - */ - SORT_INFO *sort_info; - struct st_io_cache *io_cache; - bool print_error; - - int read_record() { return read_record_func(this); } - uchar *record() const { return table->record[0]; } - - /* - SJ-Materialization runtime may need to read fields from the materialized - table and unpack them into original table fields: - */ - Copy_field *copy_field; - Copy_field *copy_field_end; -public: - READ_RECORD() : table(NULL), cache(NULL) {} - ~READ_RECORD() { end_read_record(this); } -}; - -bool init_read_record(READ_RECORD *info, THD *thd, TABLE *reg_form, - SQL_SELECT *select, SORT_INFO *sort, - int use_record_cache, - bool print_errors, bool disable_rr_cache); -bool init_read_record_idx(READ_RECORD *info, THD *thd, TABLE *table, - bool print_error, uint idx, bool reverse); - -void rr_unlock_row(st_join_table *tab); - -#endif /* SQL_RECORDS_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/repl_failsafe.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/repl_failsafe.h deleted file mode 100644 index 6f8bdfc..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/repl_failsafe.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef REPL_FAILSAFE_INCLUDED -#define REPL_FAILSAFE_INCLUDED - -/* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef HAVE_REPLICATION - -#include "mysql.h" -#include -#include "slave.h" - -extern Atomic_counter binlog_dump_thread_count; -typedef enum {RPL_AUTH_MASTER=0,RPL_IDLE_SLAVE,RPL_ACTIVE_SLAVE, - RPL_LOST_SOLDIER,RPL_TROOP_SOLDIER, - RPL_RECOVERY_CAPTAIN,RPL_NULL /* inactive */, - RPL_ANY /* wild card used by change_rpl_status */ } RPL_STATUS; -extern ulong rpl_status; - -extern mysql_mutex_t LOCK_rpl_status; -extern mysql_cond_t COND_rpl_status; -extern TYPELIB rpl_role_typelib; -extern const char* rpl_role_type[], *rpl_status_type[]; - -void change_rpl_status(ulong from_status, ulong to_status); -int find_recovery_captain(THD* thd, MYSQL* mysql); - -bool show_slave_hosts(THD* thd); - -#endif /* HAVE_REPLICATION */ -#endif /* REPL_FAILSAFE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/replication.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/replication.h deleted file mode 100644 index 49d896f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/replication.h +++ /dev/null @@ -1,567 +0,0 @@ -/* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef REPLICATION_H -#define REPLICATION_H - -/*************************************************************************** - NOTE: plugin locking. - - The plugin is locked on Binlog_transmit_observer::transmit_start and is - unlocked after Binlog_transmit_observer::transmit_stop. All other - master observable events happen between these two and don't lock the - plugin at all. - - Also a plugin is locked on Binlog_relay_IO_observer::thread_start - and unlocked after Binlog_relay_IO_observer::thread_stop. -***************************************************************************/ - -#include - -typedef struct st_mysql MYSQL; - -#ifdef __cplusplus -extern "C" { -#endif - -/** - Transaction observer flags. -*/ -enum Trans_flags { - /** Transaction is a real transaction */ - TRANS_IS_REAL_TRANS = 1 -}; - -/** - Transaction observer parameter -*/ -typedef struct Trans_param { - uint32 server_id; - uint32 flags; - - /* - The latest binary log file name and position written by current - transaction, if binary log is disabled or no log event has been - written into binary log file by current transaction (events - written into transaction log cache are not counted), these two - member will be zero. - */ - const char *log_file; - my_off_t log_pos; -} Trans_param; - -/** - Observes and extends transaction execution -*/ -typedef struct Trans_observer { - uint32 len; - - /** - This callback is called after transaction commit - - This callback is called right after commit to storage engines for - transactional tables. - - For non-transactional tables, this is called at the end of the - statement, before sending statement status, if the statement - succeeded. - - @note The return value is currently ignored by the server. - @note This hook is called wo/ any global mutex held - - @param param The parameter for transaction observers - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_commit)(Trans_param *param); - - /** - This callback is called after transaction rollback - - This callback is called right after rollback to storage engines - for transactional tables. - - For non-transactional tables, this is called at the end of the - statement, before sending statement status, if the statement - failed. - - @note The return value is currently ignored by the server. - - @param param The parameter for transaction observers - - @note This hook is called wo/ any global mutex held - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_rollback)(Trans_param *param); -} Trans_observer; - -/** - Binlog storage flags -*/ -enum Binlog_storage_flags { - /** Binary log was sync:ed */ - BINLOG_STORAGE_IS_SYNCED = 1, - - /** First(or alone) in a group commit */ - BINLOG_GROUP_COMMIT_LEADER = 2, - - /** Last(or alone) in a group commit */ - BINLOG_GROUP_COMMIT_TRAILER = 4 -}; - -/** - Binlog storage observer parameters - */ -typedef struct Binlog_storage_param { - uint32 server_id; -} Binlog_storage_param; - -/** - Observe binlog logging storage -*/ -typedef struct Binlog_storage_observer { - uint32 len; - - /** - This callback is called after binlog has been flushed - - This callback is called after cached events have been flushed to - binary log file. Whether the binary log file is synchronized to - disk is indicated by the bit BINLOG_STORAGE_IS_SYNCED in @a flags. - - @note: this hook is called with LOCK_log mutex held - - @param param Observer common parameter - @param log_file Binlog file name been updated - @param log_pos Binlog position after update - @param flags flags for binlog storage - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_flush)(Binlog_storage_param *param, - const char *log_file, my_off_t log_pos, - uint32 flags); - - /** - This callback is called after binlog has been synced - - This callback is called after events flushed to disk has been sync:ed - ("group committed"). - - @note: this hook is called with LOCK_after_binlog_sync mutex held - - @param param Observer common parameter - @param log_file Binlog file name been updated - @param log_pos Binlog position after update - @param flags flags for binlog storage - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_sync)(Binlog_storage_param *param, - const char *log_file, my_off_t log_pos, - uint32 flags); -} Binlog_storage_observer; - -/** - Replication binlog transmitter (binlog dump) observer parameter. -*/ -typedef struct Binlog_transmit_param { - uint32 server_id; - uint32 flags; -} Binlog_transmit_param; - -/** - Observe and extends the binlog dumping thread. -*/ -typedef struct Binlog_transmit_observer { - uint32 len; - - /** - This callback is called when binlog dumping starts - - - @param param Observer common parameter - @param log_file Binlog file name to transmit from - @param log_pos Binlog position to transmit from - - @retval 0 Sucess - @retval 1 Failure - */ - int (*transmit_start)(Binlog_transmit_param *param, - const char *log_file, my_off_t log_pos); - - /** - This callback is called when binlog dumping stops - - @param param Observer common parameter - - @retval 0 Sucess - @retval 1 Failure - */ - int (*transmit_stop)(Binlog_transmit_param *param); - - /** - This callback is called to reserve bytes in packet header for event transmission - - This callback is called when resetting transmit packet header to - reserve bytes for this observer in packet header. - - The @a header buffer is allocated by the server code, and @a size - is the size of the header buffer. Each observer can only reserve - a maximum size of @a size in the header. - - @param param Observer common parameter - @param header Pointer of the header buffer - @param size Size of the header buffer - @param len Header length reserved by this observer - - @retval 0 Sucess - @retval 1 Failure - */ - int (*reserve_header)(Binlog_transmit_param *param, - unsigned char *header, - unsigned long size, - unsigned long *len); - - /** - This callback is called before sending an event packet to slave - - @param param Observer common parameter - @param packet Binlog event packet to send - @param len Length of the event packet - @param log_file Binlog file name of the event packet to send - @param log_pos Binlog position of the event packet to send - - @retval 0 Sucess - @retval 1 Failure - */ - int (*before_send_event)(Binlog_transmit_param *param, - unsigned char *packet, unsigned long len, - const char *log_file, my_off_t log_pos ); - - /** - This callback is called after sending an event packet to slave - - @param param Observer common parameter - @param event_buf Binlog event packet buffer sent - @param len length of the event packet buffer - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_send_event)(Binlog_transmit_param *param, - const char *event_buf, unsigned long len); - - /** - This callback is called after resetting master status - - This is called when executing the command RESET MASTER, and is - used to reset status variables added by observers. - - @param param Observer common parameter - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_reset_master)(Binlog_transmit_param *param); -} Binlog_transmit_observer; - -/** - Binlog relay IO flags -*/ -enum Binlog_relay_IO_flags { - /** Binary relay log was sync:ed */ - BINLOG_RELAY_IS_SYNCED = 1 -}; - - -/** - Replication binlog relay IO observer parameter -*/ -typedef struct Binlog_relay_IO_param { - uint32 server_id; - - /* Master host, user and port */ - char *host; - char *user; - unsigned int port; - - char *master_log_name; - my_off_t master_log_pos; - - MYSQL *mysql; /* the connection to master */ -} Binlog_relay_IO_param; - -/** - Observes and extends the service of slave IO thread. -*/ -typedef struct Binlog_relay_IO_observer { - uint32 len; - - /** - This callback is called when slave IO thread starts - - @param param Observer common parameter - - @retval 0 Sucess - @retval 1 Failure - */ - int (*thread_start)(Binlog_relay_IO_param *param); - - /** - This callback is called when slave IO thread stops - - @param param Observer common parameter - - @retval 0 Sucess - @retval 1 Failure - */ - int (*thread_stop)(Binlog_relay_IO_param *param); - - /** - This callback is called before slave requesting binlog transmission from master - - This is called before slave issuing BINLOG_DUMP command to master - to request binlog. - - @param param Observer common parameter - @param flags binlog dump flags - - @retval 0 Sucess - @retval 1 Failure - */ - int (*before_request_transmit)(Binlog_relay_IO_param *param, uint32 flags); - - /** - This callback is called after read an event packet from master - - @param param Observer common parameter - @param packet The event packet read from master - @param len Length of the event packet read from master - @param event_buf The event packet return after process - @param event_len The length of event packet return after process - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_read_event)(Binlog_relay_IO_param *param, - const char *packet, unsigned long len, - const char **event_buf, unsigned long *event_len); - - /** - This callback is called after written an event packet to relay log - - @param param Observer common parameter - @param event_buf Event packet written to relay log - @param event_len Length of the event packet written to relay log - @param flags flags for relay log - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_queue_event)(Binlog_relay_IO_param *param, - const char *event_buf, unsigned long event_len, - uint32 flags); - - /** - This callback is called after reset slave relay log IO status - - @param param Observer common parameter - - @retval 0 Sucess - @retval 1 Failure - */ - int (*after_reset_slave)(Binlog_relay_IO_param *param); -} Binlog_relay_IO_observer; - - -/** - Register a transaction observer - - @param observer The transaction observer to register - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer already exists -*/ -int register_trans_observer(Trans_observer *observer, void *p); - -/** - Unregister a transaction observer - - @param observer The transaction observer to unregister - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer not exists -*/ -int unregister_trans_observer(Trans_observer *observer, void *p); - -/** - Register a binlog storage observer - - @param observer The binlog storage observer to register - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer already exists -*/ -int register_binlog_storage_observer(Binlog_storage_observer *observer, void *p); - -/** - Unregister a binlog storage observer - - @param observer The binlog storage observer to unregister - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer not exists -*/ -int unregister_binlog_storage_observer(Binlog_storage_observer *observer, void *p); - -/** - Register a binlog transmit observer - - @param observer The binlog transmit observer to register - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer already exists -*/ -int register_binlog_transmit_observer(Binlog_transmit_observer *observer, void *p); - -/** - Unregister a binlog transmit observer - - @param observer The binlog transmit observer to unregister - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer not exists -*/ -int unregister_binlog_transmit_observer(Binlog_transmit_observer *observer, void *p); - -/** - Register a binlog relay IO (slave IO thread) observer - - @param observer The binlog relay IO observer to register - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer already exists -*/ -int register_binlog_relay_io_observer(Binlog_relay_IO_observer *observer, void *p); - -/** - Unregister a binlog relay IO (slave IO thread) observer - - @param observer The binlog relay IO observer to unregister - @param p pointer to the internal plugin structure - - @retval 0 Sucess - @retval 1 Observer not exists -*/ -int unregister_binlog_relay_io_observer(Binlog_relay_IO_observer *observer, void *p); - -/** - Connect to master - - This function can only used in the slave I/O thread context, and - will use the same master information to do the connection. - - @code - MYSQL *mysql = mysql_init(NULL); - if (rpl_connect_master(mysql)) - { - // do stuff with the connection - } - mysql_close(mysql); // close the connection - @endcode - - @param mysql address of MYSQL structure to use, pass NULL will - create a new one - - @return address of MYSQL structure on success, NULL on failure -*/ -MYSQL *rpl_connect_master(MYSQL *mysql); - -/** - Get the value of user variable as an integer. - - This function will return the value of variable @a name as an - integer. If the original value of the variable is not an integer, - the value will be converted into an integer. - - @param name user variable name - @param value pointer to return the value - @param null_value if not NULL, the function will set it to true if - the value of variable is null, set to false if not - - @retval 0 Success - @retval 1 Variable not found -*/ -int get_user_var_int(const char *name, - long long int *value, int *null_value); - -/** - Get the value of user variable as a double precision float number. - - This function will return the value of variable @a name as real - number. If the original value of the variable is not a real number, - the value will be converted into a real number. - - @param name user variable name - @param value pointer to return the value - @param null_value if not NULL, the function will set it to true if - the value of variable is null, set to false if not - - @retval 0 Success - @retval 1 Variable not found -*/ -int get_user_var_real(const char *name, - double *value, int *null_value); - -/** - Get the value of user variable as a string. - - This function will return the value of variable @a name as - string. If the original value of the variable is not a string, - the value will be converted into a string. - - @param name user variable name - @param value pointer to the value buffer - @param len length of the value buffer - @param precision precision of the value if it is a float number - @param null_value if not NULL, the function will set it to true if - the value of variable is null, set to false if not - - @retval 0 Success - @retval 1 Variable not found -*/ -int get_user_var_str(const char *name, - char *value, unsigned long len, - unsigned int precision, int *null_value); - - - -#ifdef __cplusplus -} -#endif -#endif /* REPLICATION_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rijndael.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rijndael.h deleted file mode 100644 index 552430a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rijndael.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef RIJNDAEL_INCLUDED -#define RIJNDAEL_INCLUDED - -/* Copyright (c) 2002, 2006 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* - rijndael-alg-fst.h - - @version 3.0 (December 2000) - Optimised ANSI C code for the Rijndael cipher (now AES) - @author Vincent Rijmen - @author Antoon Bosselaers - @author Paulo Barreto - - This code is hereby placed in the public domain. - Modified by Peter Zaitsev to fit MySQL coding style. - */ - -#define AES_MAXKC (256/32) -#define AES_MAXKB (256/8) -#define AES_MAXNR 14 - -int rijndaelKeySetupEnc(uint32 rk[/*4*(Nr + 1)*/], const uint8 cipherKey[], - int keyBits); -int rijndaelKeySetupDec(uint32 rk[/*4*(Nr + 1)*/], const uint8 cipherKey[], - int keyBits); -void rijndaelEncrypt(const uint32 rk[/*4*(Nr + 1)*/], int Nr, - const uint8 pt[16], uint8 ct[16]); -void rijndaelDecrypt(const uint32 rk[/*4*(Nr + 1)*/], int Nr, - const uint8 ct[16], uint8 pt[16]); - -#endif /* RIJNDAEL_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rowid_filter.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rowid_filter.h deleted file mode 100644 index 467b688..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rowid_filter.h +++ /dev/null @@ -1,470 +0,0 @@ -/* - Copyright (c) 2018, 2019 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef ROWID_FILTER_INCLUDED -#define ROWID_FILTER_INCLUDED - - -#include "mariadb.h" -#include "sql_array.h" - -/* - - What rowid / primary filters are - -------------------------------- - - Consider a join query Q of the form - SELECT * FROM T1, ... , Tk WHERE P. - - For any of the table reference Ti(Q) from the from clause of Q different - rowid / primary key filters (pk-filters for short) can be built. - A pk-filter F built for Ti(Q) is a set of rowids / primary keys of Ti - F= {pk1,...,pkN} such that for any row r=r1||...||rk from the result set of Q - ri's rowid / primary key pk(ri) is contained in F. - - When pk-filters are useful - -------------------------- - - If building a pk-filter F for Ti(Q )is not too costly and its cardinality #F - is much less than the cardinality of T - #T then using the pk-filter when - executing Q might be quite beneficial. - - Let r be a random row from Ti. Let s(F) be the probability that pk(r) - belongs to F. Let BC(F) be the cost of building F. - - Suppose that the optimizer has chosen for Q a plan with this join order - T1 => ... Tk and that the table Ti is accessed by a ref access using index I. - Let K = {k1,...,kM} be the set of all rowid/primary keys values used to access - rows of Ti when looking for matches in this table.to join Ti by index I. - - Let's assume that two set sets K and F are uncorrelated. With this assumption - if before accessing data from Ti by the rowid / primary key k we first - check whether k is in F then we can expect saving on M*(1-s(S)) accesses of - data rows from Ti. If we can guarantee that test whether k is in F is - relatively cheap then we can gain a lot assuming that BC(F) is much less - then the cost of fetching M*(1-s(S)) records from Ti and following - evaluation of conditions pushed into Ti. - - Making pk-filter test cheap - --------------------------- - - If the search structure to test whether an element is in F can be fully - placed in RAM then this test is expected to be be much cheaper than a random - access of a record from Ti. We'll consider two search structures for - pk-filters: ordered array and bloom filter. Ordered array is easy to - implement, but it's space consuming. If a filter contains primary keys - then at least space for each primary key from the filter must be allocated - in the search structure. On a the opposite a bloom filter requires a - fixed number of bits and this number does not depend on the cardinality - of the pk-filter (10 bits per element will serve pk-filter of any size). - -*/ - -/* - - How and when the optimizer builds and uses range rowid filters - -------------------------------------------------------------- - - 1. In make_join_statistics() - for each join table s - after the call of get_quick_record_count() - the TABLE::method init_cost_info_for_usable_range_rowid_filters() - is called - The method build an array of Range_rowid_filter_cost_info elements - containing the cost info on possible range filters for s->table. - The array is optimized for further usage. - - 2. For each partial join order when the optimizer considers joining - table s to this partial join - In the function best_access_path() - a. When evaluating a ref access r by index idx to join s - the optimizer estimates the effect of usage of each possible - range filter f and chooses one with the best gain. The gain - is taken into account when the cost of thr ref access r is - calculated. If it turns out that this is the best ref access - to join s then the info about the chosen filter together - with the info on r is remembered in the corresponding element - of the array of POSITION structures. - [We evaluate every pair (ref access, range_filter) rather then - every pair (best ref access, range filter) because if the index - ref_idx used for ref access r correlates with the index rf_idx - used by the filter f then the pair (r,f) is not evaluated - at all as we don't know how to estimate the effect of correlation - between ref_idx and rf_idx.] - b. When evaluating the best range access to join table s the - optimizer estimates the effect of usage of each possible - range filter f and chooses one with the best gain. - [Here we should have evaluated every pair (range access, - range filter) as well, but it's not done yet.] - - 3. When the cheapest execution plan has been chosen and after the - call of JOIN::get_best_combination() - The method JOIN::make_range_rowid_filters() is called - For each range rowid filter used in the chosen execution plan - the method creates a quick select object to be able to perform - index range scan to fill the filter at the execution stage. - The method also creates Range_rowid_filter objects that are - used at the execution stage. - - 4. Just before the execution stage - The method JOIN::init_range_rowid_filters() is called. - For each join table s that is to be accessed with usage of a range - filter the method allocates containers for the range filter and - it lets the engine know that the filter will be used when - accessing s. - - 5. At the execution stage - In the function sub_select() just before the first access of a join - table s employing a range filter - The method JOIN_TAB::build_range_rowid_filter_if_needed() is called - The method fills the filter using the quick select created by - JOIN::make_range_rowid_filters(). - - 6. The accessed key tuples are checked against the filter within the engine - using the info pushed into it. - -*/ - -struct TABLE; -class SQL_SELECT; -class Rowid_filter_container; -class Range_rowid_filter_cost_info; - -/* Cost to write rowid into array */ -#define ARRAY_WRITE_COST 0.005 -/* Factor used to calculate cost of sorting rowids in array */ -#define ARRAY_SORT_C 0.01 -/* Cost to evaluate condition */ -#define COST_COND_EVAL 0.2 - -typedef enum -{ - SORTED_ARRAY_CONTAINER, - BLOOM_FILTER_CONTAINER // Not used yet -} Rowid_filter_container_type; - -/** - @class Rowid_filter_container - - The interface for different types of containers to store info on the set - of rowids / primary keys that defines a pk-filter. - - There will be two implementations of this abstract class. - - sorted array - - bloom filter -*/ - -class Rowid_filter_container : public Sql_alloc -{ -public: - - virtual Rowid_filter_container_type get_type() = 0; - - /* Allocate memory for the container */ - virtual bool alloc() = 0; - - /* - @brief Add info on a rowid / primary to the container - @param ctxt The context info (opaque) - @param elem The rowid / primary key to be added to the container - @retval true if elem is successfully added - */ - virtual bool add(void *ctxt, char *elem) = 0; - - /* - @brief Check whether a rowid / primary key is in container - @param ctxt The context info (opaque) - @param elem The rowid / primary key to be checked against the container - @retval False if elem is definitely not in the container - */ - virtual bool check(void *ctxt, char *elem) = 0; - - virtual ~Rowid_filter_container() {} -}; - - -/** - @class Rowid_filter - - The interface for different types of pk-filters - - Currently we support only range pk filters. -*/ - -class Rowid_filter : public Sql_alloc -{ -protected: - - /* The container to store info the set of elements in the filter */ - Rowid_filter_container *container; - - Rowid_filter_tracker *tracker; - -public: - Rowid_filter(Rowid_filter_container *container_arg) - : container(container_arg) {} - - /* - Build the filter : - fill it with info on the set of elements placed there - */ - virtual bool build() = 0; - - /* - Check whether an element is in the filter. - Returns false is the elements is definitely not in the filter. - */ - virtual bool check(char *elem) = 0; - - virtual ~Rowid_filter() {} - - Rowid_filter_container *get_container() { return container; } - - void set_tracker(Rowid_filter_tracker *track_arg) { tracker= track_arg; } - Rowid_filter_tracker *get_tracker() { return tracker; } -}; - - -/** - @class Rowid_filter_container - - The implementation of the Rowid_interface used for pk-filters - that are filled when performing range index scans. -*/ - -class Range_rowid_filter: public Rowid_filter -{ - /* The table for which the rowid filter is built */ - TABLE *table; - /* The select to perform the range scan to fill the filter */ - SQL_SELECT *select; - /* The cost info on the filter (used for EXPLAIN/ANALYZE) */ - Range_rowid_filter_cost_info *cost_info; - -public: - Range_rowid_filter(TABLE *tab, - Range_rowid_filter_cost_info *cost_arg, - Rowid_filter_container *container_arg, - SQL_SELECT *sel) - : Rowid_filter(container_arg), table(tab), select(sel), cost_info(cost_arg) - {} - - ~Range_rowid_filter(); - - bool build() { return fill(); } - - bool check(char *elem) - { - bool was_checked= container->check(table, elem); - tracker->increment_checked_elements_count(was_checked); - return was_checked; - } - - bool fill(); - - SQL_SELECT *get_select() { return select; } -}; - - -/** - @class Refpos_container_sorted_array - - The wrapper class over Dynamic_array to facilitate operations over - array of elements of the type char[N] where N is the same for all elements -*/ - -class Refpos_container_sorted_array : public Sql_alloc -{ - /* - Maximum number of elements in the array - (Now is used only at the initialization of the dynamic array) - */ - uint max_elements; - /* Number of bytes allocated for an element */ - uint elem_size; - /* The dynamic array over which the wrapper is built */ - Dynamic_array *array; - -public: - - Refpos_container_sorted_array(uint max_elems, uint elem_sz) - : max_elements(max_elems), elem_size(elem_sz), array(0) {} - - ~Refpos_container_sorted_array() - { - delete array; - array= 0; - } - - bool alloc() - { - array= new Dynamic_array (elem_size * max_elements, - elem_size * max_elements/sizeof(char) + 1); - return array == NULL; - } - - bool add(char *elem) - { - for (uint i= 0; i < elem_size; i++) - { - if (array->append(elem[i])) - return true; - } - return false; - } - - char *get_pos(uint n) - { - return array->get_pos(n * elem_size); - } - - uint elements() { return (uint) (array->elements() / elem_size); } - - void sort (int (*cmp) (void *ctxt, const void *el1, const void *el2), - void *cmp_arg) - { - my_qsort2(array->front(), array->elements()/elem_size, - elem_size, (qsort2_cmp) cmp, cmp_arg); - } -}; - - -/** - @class Rowid_filter_sorted_array - - The implementation of the Rowid_filter_container interface as - a sorted array container of rowids / primary keys -*/ - -class Rowid_filter_sorted_array: public Rowid_filter_container -{ - /* The dynamic array to store rowids / primary keys */ - Refpos_container_sorted_array refpos_container; - /* Initially false, becomes true after the first call of (check() */ - bool is_checked; - -public: - Rowid_filter_sorted_array(uint elems, uint elem_size) - : refpos_container(elems, elem_size), is_checked(false) {} - - Rowid_filter_container_type get_type() - { return SORTED_ARRAY_CONTAINER; } - - bool alloc() { return refpos_container.alloc(); } - - bool add(void *ctxt, char *elem) { return refpos_container.add(elem); } - - bool check(void *ctxt, char *elem); -}; - -/** - @class Range_rowid_filter_cost_info - - An objects of this class is created for each potentially usable - range filter. It contains the info that allows to figure out - whether usage of the range filter promises some gain. -*/ - -class Range_rowid_filter_cost_info : public Sql_alloc -{ - /* The table for which the range filter is to be built (if needed) */ - TABLE *table; - /* Estimated number of elements in the filter */ - ulonglong est_elements; - /* The cost of building the range filter */ - double b; - /* - a*N-b yields the gain of the filter - for N key tuples of the index key_no - */ - double a; - /* The value of N where the gain is 0 */ - double cross_x; - /* Used for pruning of the potential range filters */ - key_map abs_independent; - - /* - These two parameters are used to choose the best range filter - in the function TABLE::best_range_rowid_filter_for_partial_join - */ - double a_adj; - double cross_x_adj; - -public: - /* The type of the container of the range filter */ - Rowid_filter_container_type container_type; - /* The index whose range scan would be used to build the range filter */ - uint key_no; - /* The selectivity of the range filter */ - double selectivity; - - Range_rowid_filter_cost_info() : table(0), key_no(0) {} - - void init(Rowid_filter_container_type cont_type, - TABLE *tab, uint key_no); - - double build_cost(Rowid_filter_container_type container_type); - - inline double lookup_cost(Rowid_filter_container_type cont_type); - - inline double - avg_access_and_eval_gain_per_row(Rowid_filter_container_type cont_type); - - inline double avg_adjusted_gain_per_row(double access_cost_factor); - - inline void set_adjusted_gain_param(double access_cost_factor); - - /* Get the gain that usage of filter promises for r key tuples */ - inline double get_gain(double r) - { - return r * a - b; - } - - /* Get the adjusted gain that usage of filter promises for r key tuples */ - inline double get_adjusted_gain(double r) - { - return r * a_adj - b; - } - - /* - The gain promised by usage of the filter for r key tuples - due to less condition evaluations - */ - inline double get_cmp_gain(double r) - { - return r * (1 - selectivity) / TIME_FOR_COMPARE; - } - - Rowid_filter_container *create_container(); - - double get_a() { return a; } - - void trace_info(THD *thd); - - friend - void TABLE::prune_range_rowid_filters(); - - friend - void TABLE::init_cost_info_for_usable_range_rowid_filters(THD *thd); - - friend - Range_rowid_filter_cost_info * - TABLE::best_range_rowid_filter_for_partial_join(uint access_key_no, - double records, - double access_cost_factor); -}; - -#endif /* ROWID_FILTER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_constants.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_constants.h deleted file mode 100644 index f319d08..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_constants.h +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright (c) 2007 MySQL AB, 2008 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_CONSTANTS_H -#define RPL_CONSTANTS_H - -#include -#include - -/** - Enumeration of the incidents that can occur for the server. - */ -enum Incident { - /** No incident */ - INCIDENT_NONE = 0, - - /** There are possibly lost events in the replication stream */ - INCIDENT_LOST_EVENTS = 1, - - /** Shall be last event of the enumeration */ - INCIDENT_COUNT -}; - - -/** - Enumeration of the reserved formats of Binlog extra row information -*/ -enum ExtraRowInfoFormat { - - /** Reserved formats 0 -> 63 inclusive */ - ERIF_LASTRESERVED = 63, - - /** - Available / uncontrolled formats - 64 -> 254 inclusive - */ - ERIF_OPEN1 = 64, - ERIF_OPEN2 = 65, - - ERIF_LASTOPEN = 254, - - /** - Multi-payload format 255 - - Length is total length, payload is sequence of - sub-payloads with their own headers containing - length + format. - */ - ERIF_MULTI = 255 -}; - -/* - 1 byte length, 1 byte format - Length is total length in bytes, including 2 byte header - Length values 0 and 1 are currently invalid and reserved. -*/ -#define EXTRA_ROW_INFO_LEN_OFFSET 0 -#define EXTRA_ROW_INFO_FORMAT_OFFSET 1 -#define EXTRA_ROW_INFO_HDR_BYTES 2 -#define EXTRA_ROW_INFO_MAX_PAYLOAD (255 - EXTRA_ROW_INFO_HDR_BYTES) - -enum enum_binlog_checksum_alg { - BINLOG_CHECKSUM_ALG_OFF= 0, // Events are without checksum though its generator - // is checksum-capable New Master (NM). - BINLOG_CHECKSUM_ALG_CRC32= 1, // CRC32 of zlib algorithm. - BINLOG_CHECKSUM_ALG_ENUM_END, // the cut line: valid alg range is [1, 0x7f]. - BINLOG_CHECKSUM_ALG_UNDEF= 255 // special value to tag undetermined yet checksum - // or events from checksum-unaware servers -}; - -#define BINLOG_CRYPTO_SCHEME_LENGTH 1 -#define BINLOG_KEY_VERSION_LENGTH 4 -#define BINLOG_IV_LENGTH MY_AES_BLOCK_SIZE -#define BINLOG_IV_OFFS_LENGTH 4 -#define BINLOG_NONCE_LENGTH (BINLOG_IV_LENGTH - BINLOG_IV_OFFS_LENGTH) - -struct Binlog_crypt_data { - uint scheme; - uint key_version, key_length, ctx_size; - uchar key[MY_AES_MAX_KEY_LENGTH]; - uchar nonce[BINLOG_NONCE_LENGTH]; - - int init(uint sch, uint kv) - { - scheme= sch; - ctx_size= encryption_ctx_size(ENCRYPTION_KEY_SYSTEM_DATA, kv); - key_version= kv; - key_length= sizeof(key); - return encryption_key_get(ENCRYPTION_KEY_SYSTEM_DATA, kv, key, &key_length); - } - - void set_iv(uchar* iv, uint32 offs) const - { - memcpy(iv, nonce, BINLOG_NONCE_LENGTH); - int4store(iv + BINLOG_NONCE_LENGTH, offs); - } -}; - -#endif /* RPL_CONSTANTS_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_filter.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_filter.h deleted file mode 100644 index f22ec8a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_filter.h +++ /dev/null @@ -1,158 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_FILTER_H -#define RPL_FILTER_H - -#include "mysql.h" -#include "mysqld.h" -#include "sql_list.h" /* I_List */ -#include "hash.h" /* HASH */ - -class String; -struct TABLE_LIST; -typedef struct st_dynamic_array DYNAMIC_ARRAY; - -typedef struct st_table_rule_ent -{ - char* db; - char* tbl_name; - uint key_len; -} TABLE_RULE_ENT; - -/* - Rpl_filter - - Inclusion and exclusion rules of tables and databases. - Also handles rewrites of db. - Used for replication and binlogging. - */ -class Rpl_filter -{ -public: - Rpl_filter(); - ~Rpl_filter(); - Rpl_filter(Rpl_filter const&); - Rpl_filter& operator=(Rpl_filter const&); - - /* Checks - returns true if ok to replicate/log */ - -#ifndef MYSQL_CLIENT - bool tables_ok(const char* db, TABLE_LIST *tables); -#endif - bool db_ok(const char* db); - bool db_ok_with_wild_table(const char *db); - - bool is_on(); - - /* Setters - add filtering rules */ - - int add_do_table(const char* table_spec); - int add_ignore_table(const char* table_spec); - - int set_do_table(const char* table_spec); - int set_ignore_table(const char* table_spec); - - int add_wild_do_table(const char* table_spec); - int add_wild_ignore_table(const char* table_spec); - - int set_wild_do_table(const char* table_spec); - int set_wild_ignore_table(const char* table_spec); - - int add_do_db(const char* db_spec); - int add_ignore_db(const char* db_spec); - - int set_do_db(const char* db_spec); - int set_ignore_db(const char* db_spec); - - void set_parallel_mode(enum_slave_parallel_mode mode) - { - parallel_mode= mode; - } - /* Return given parallel mode or if one is not given, the default mode */ - enum_slave_parallel_mode get_parallel_mode() - { - return parallel_mode; - } - - void add_db_rewrite(const char* from_db, const char* to_db); - - /* Getters - to get information about current rules */ - - void get_do_table(String* str); - void get_ignore_table(String* str); - - void get_wild_do_table(String* str); - void get_wild_ignore_table(String* str); - - bool rewrite_db_is_empty(); - const char* get_rewrite_db(const char* db, size_t *new_len); - void copy_rewrite_db(Rpl_filter *from); - - I_List* get_do_db(); - I_List* get_ignore_db(); - - void get_do_db(String* str); - void get_ignore_db(String* str); - -private: - - void init_table_rule_hash(HASH* h, bool* h_inited); - void init_table_rule_array(DYNAMIC_ARRAY* a, bool* a_inited); - - int add_table_rule(HASH* h, const char* table_spec); - int add_wild_table_rule(DYNAMIC_ARRAY* a, const char* table_spec); - - typedef int (Rpl_filter::*Add_filter)(char const*); - - int parse_filter_rule(const char* spec, Add_filter func); - - void free_string_array(DYNAMIC_ARRAY *a); - void free_string_list(I_List *l); - - void table_rule_ent_hash_to_str(String* s, HASH* h, bool inited); - void table_rule_ent_dynamic_array_to_str(String* s, DYNAMIC_ARRAY* a, - bool inited); - void db_rule_ent_list_to_str(String* s, I_List* l); - TABLE_RULE_ENT* find_wild(DYNAMIC_ARRAY *a, const char* key, int len); - - int add_string_list(I_List *list, const char* spec); - - /* - Those 4 structures below are uninitialized memory unless the - corresponding *_inited variables are "true". - */ - HASH do_table; - HASH ignore_table; - DYNAMIC_ARRAY wild_do_table; - DYNAMIC_ARRAY wild_ignore_table; - enum_slave_parallel_mode parallel_mode; - - bool table_rules_on; - bool do_table_inited; - bool ignore_table_inited; - bool wild_do_table_inited; - bool wild_ignore_table_inited; - - I_List do_db; - I_List ignore_db; - - I_List rewrite_db; -}; - -extern Rpl_filter *global_rpl_filter; -extern Rpl_filter *binlog_filter; - -#endif // RPL_FILTER_H diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_gtid.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_gtid.h deleted file mode 100644 index 11541c8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_gtid.h +++ /dev/null @@ -1,384 +0,0 @@ -/* Copyright (c) 2013, Kristian Nielsen and MariaDB Services Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_GTID_H -#define RPL_GTID_H - -#include "hash.h" -#include "queues.h" -#include - -/* Definitions for MariaDB global transaction ID (GTID). */ - - -extern const LEX_CSTRING rpl_gtid_slave_state_table_name; - -class String; - -#define GTID_MAX_STR_LENGTH (10+1+10+1+20) - -struct rpl_gtid -{ - uint32 domain_id; - uint32 server_id; - uint64 seq_no; -}; - -inline bool operator==(const rpl_gtid& lhs, const rpl_gtid& rhs) -{ - return - lhs.domain_id == rhs.domain_id && - lhs.server_id == rhs.server_id && - lhs.seq_no == rhs.seq_no; -}; - -enum enum_gtid_skip_type { - GTID_SKIP_NOT, GTID_SKIP_STANDALONE, GTID_SKIP_TRANSACTION -}; - - -/* - Structure to keep track of threads waiting in MASTER_GTID_WAIT(). - - Since replication is (mostly) single-threaded, we want to minimise the - performance impact on that from MASTER_GTID_WAIT(). To achieve this, we - are careful to keep the common lock between replication threads and - MASTER_GTID_WAIT threads held for as short as possible. We keep only - a single thread waiting to be notified by the replication threads; this - thread then handles all the (potentially heavy) lifting of dealing with - all current waiting threads. -*/ -struct gtid_waiting { - /* Elements in the hash, basically a priority queue for each domain. */ - struct hash_element { - QUEUE queue; - uint32 domain_id; - }; - /* A priority queue to handle waiters in one domain in seq_no order. */ - struct queue_element { - uint64 wait_seq_no; - THD *thd; - int queue_idx; - /* - do_small_wait is true if we have responsibility for ensuring that there - is a small waiter. - */ - bool do_small_wait; - /* - The flag `done' is set when the wait is completed (either due to reaching - the position waited for, or due to timeout or kill). The queue_element - is in the queue if and only if `done' is true. - */ - bool done; - }; - - mysql_mutex_t LOCK_gtid_waiting; - HASH hash; - - void init(); - void destroy(); - hash_element *get_entry(uint32 domain_id); - int wait_for_pos(THD *thd, String *gtid_str, longlong timeout_us); - void promote_new_waiter(gtid_waiting::hash_element *he); - int wait_for_gtid(THD *thd, rpl_gtid *wait_gtid, struct timespec *wait_until); - void process_wait_hash(uint64 wakeup_seq_no, gtid_waiting::hash_element *he); - int register_in_wait_queue(THD *thd, rpl_gtid *wait_gtid, hash_element *he, - queue_element *elem); - void remove_from_wait_queue(hash_element *he, queue_element *elem); -}; - - -class Relay_log_info; -struct rpl_group_info; -class Gtid_list_log_event; - -/* - Replication slave state. - - For every independent replication stream (identified by domain_id), this - remembers the last gtid applied on the slave within this domain. - - Since events are always committed in-order within a single domain, this is - sufficient to maintain the state of the replication slave. -*/ -struct rpl_slave_state -{ - /* Elements in the list of GTIDs kept for each domain_id. */ - struct list_element - { - struct list_element *next; - uint64 sub_id; - uint32 domain_id; - uint32 server_id; - uint64 seq_no; - /* - hton of mysql.gtid_slave_pos* table used to record this GTID. - Can be NULL if the gtid table failed to load (eg. missing - mysql.gtid_slave_pos table following an upgrade). - */ - void *hton; - }; - - /* Elements in the HASH that hold the state for one domain_id. */ - struct element - { - struct list_element *list; - uint32 domain_id; - /* Highest seq_no seen so far in this domain. */ - uint64 highest_seq_no; - /* - If this is non-NULL, then it is the waiter responsible for the small - wait in MASTER_GTID_WAIT(). - */ - gtid_waiting::queue_element *gtid_waiter; - /* - If gtid_waiter is non-NULL, then this is the seq_no that its - MASTER_GTID_WAIT() is waiting on. When we reach this seq_no, we need to - signal the waiter on COND_wait_gtid. - */ - uint64 min_wait_seq_no; - mysql_cond_t COND_wait_gtid; - - /* - For --gtid-ignore-duplicates. The Relay_log_info that currently owns - this domain, and the number of worker threads that are active in it. - - The idea is that only one of multiple master connections is allowed to - actively apply events for a given domain. Other connections must either - discard the events (if the seq_no in GTID shows they have already been - applied), or wait to see if the current owner will apply it. - */ - const Relay_log_info *owner_rli; - uint32 owner_count; - mysql_cond_t COND_gtid_ignore_duplicates; - - list_element *grab_list() { list_element *l= list; list= NULL; return l; } - void add(list_element *l) - { - l->next= list; - list= l; - } - }; - - /* Descriptor for mysql.gtid_slave_posXXX table in specific engine. */ - enum gtid_pos_table_state { - GTID_POS_AUTO_CREATE, - GTID_POS_CREATE_REQUESTED, - GTID_POS_CREATE_IN_PROGRESS, - GTID_POS_AVAILABLE - }; - struct gtid_pos_table { - struct gtid_pos_table *next; - /* - Use a void * here, rather than handlerton *, to make explicit that we - are not using the value to access any functionality in the engine. It - is just used as an opaque value to identify which engine we are using - for each GTID row. - */ - void *table_hton; - LEX_CSTRING table_name; - uint8 state; - }; - - /* Mapping from domain_id to its element. */ - HASH hash; - /* GTIDs added since last purge of old mysql.gtid_slave_pos rows. */ - uint32 pending_gtid_count; - /* Mutex protecting access to the state. */ - mysql_mutex_t LOCK_slave_state; - /* Auxiliary buffer to sort gtid list. */ - DYNAMIC_ARRAY gtid_sort_array; - - uint64 last_sub_id; - /* - List of tables available for durably storing the slave GTID position. - - Accesses to this table is protected by LOCK_slave_state. However for - efficiency, there is also a provision for read access to it from a running - slave without lock. - - An element can be added at the head of a list by storing the new - gtid_pos_tables pointer atomically with release semantics, to ensure that - the next pointer of the new element is visible to readers of the new list. - Other changes (like deleting or replacing elements) must happen only while - all SQL driver threads are stopped. LOCK_slave_state must be held in any - case. - - The list can be read without lock by an SQL driver thread or worker thread - by reading the gtid_pos_tables pointer atomically with acquire semantics, - to ensure that it will see the correct next pointer of a new head element. - */ - std::atomic gtid_pos_tables; - /* The default entry in gtid_pos_tables, mysql.gtid_slave_pos. */ - std::atomic default_gtid_pos_table; - bool loaded; - - rpl_slave_state(); - ~rpl_slave_state(); - - void truncate_hash(); - ulong count() const { return hash.records; } - int update(uint32 domain_id, uint32 server_id, uint64 sub_id, - uint64 seq_no, void *hton, rpl_group_info *rgi); - int truncate_state_table(THD *thd); - void select_gtid_pos_table(THD *thd, LEX_CSTRING *out_tablename); - int record_gtid(THD *thd, const rpl_gtid *gtid, uint64 sub_id, - bool in_transaction, bool in_statement, void **out_hton); - list_element *gtid_grab_pending_delete_list(); - LEX_CSTRING *select_gtid_pos_table(void *hton); - void gtid_delete_pending(THD *thd, rpl_slave_state::list_element **list_ptr); - uint64 next_sub_id(uint32 domain_id); - int iterate(int (*cb)(rpl_gtid *, void *), void *data, - rpl_gtid *extra_gtids, uint32 num_extra, - bool sort); - int tostring(String *dest, rpl_gtid *extra_gtids, uint32 num_extra); - bool domain_to_gtid(uint32 domain_id, rpl_gtid *out_gtid); - int load(THD *thd, const char *state_from_master, size_t len, bool reset, - bool in_statement); - bool is_empty(); - - element *get_element(uint32 domain_id); - int put_back_list(list_element *list); - - void update_state_hash(uint64 sub_id, rpl_gtid *gtid, void *hton, - rpl_group_info *rgi); - int record_and_update_gtid(THD *thd, struct rpl_group_info *rgi); - int check_duplicate_gtid(rpl_gtid *gtid, rpl_group_info *rgi); - void release_domain_owner(rpl_group_info *rgi); - void set_gtid_pos_tables_list(gtid_pos_table *new_list, - gtid_pos_table *default_entry); - void add_gtid_pos_table(gtid_pos_table *entry); - struct gtid_pos_table *alloc_gtid_pos_table(LEX_CSTRING *table_name, - void *hton, rpl_slave_state::gtid_pos_table_state state); - void free_gtid_pos_tables(struct gtid_pos_table *list); -}; - - -/* - Binlog state. - This keeps the last GTID written to the binlog for every distinct - (domain_id, server_id) pair. - This will be logged at the start of the next binlog file as a - Gtid_list_log_event; this way, it is easy to find the binlog file - containing a given GTID, by simply scanning backwards from the newest - one until a lower seq_no is found in the Gtid_list_log_event at the - start of a binlog for the given domain_id and server_id. - - We also remember the last logged GTID for every domain_id. This is used - to know where to start when a master is changed to a slave. As a side - effect, it also allows to skip a hash lookup in the very common case of - logging a new GTID with same server id as last GTID. -*/ -struct rpl_binlog_state -{ - struct element { - uint32 domain_id; - HASH hash; /* Containing all server_id for one domain_id */ - /* The most recent entry in the hash. */ - rpl_gtid *last_gtid; - /* Counter to allocate next seq_no for this domain. */ - uint64 seq_no_counter; - - int update_element(const rpl_gtid *gtid); - }; - /* Mapping from domain_id to collection of elements. */ - HASH hash; - /* Mutex protecting access to the state. */ - mysql_mutex_t LOCK_binlog_state; - my_bool initialized; - - /* Auxiliary buffer to sort gtid list. */ - DYNAMIC_ARRAY gtid_sort_array; - - rpl_binlog_state() :initialized(0) {} - ~rpl_binlog_state(); - - void init(); - void reset_nolock(); - void reset(); - void free(); - bool load(struct rpl_gtid *list, uint32 count); - bool load(rpl_slave_state *slave_pos); - int update_nolock(const struct rpl_gtid *gtid, bool strict); - int update(const struct rpl_gtid *gtid, bool strict); - int update_with_next_gtid(uint32 domain_id, uint32 server_id, - rpl_gtid *gtid); - int alloc_element_nolock(const rpl_gtid *gtid); - bool check_strict_sequence(uint32 domain_id, uint32 server_id, uint64 seq_no); - int bump_seq_no_if_needed(uint32 domain_id, uint64 seq_no); - int write_to_iocache(IO_CACHE *dest); - int read_from_iocache(IO_CACHE *src); - uint32 count(); - int get_gtid_list(rpl_gtid *gtid_list, uint32 list_size); - int get_most_recent_gtid_list(rpl_gtid **list, uint32 *size); - bool append_pos(String *str); - bool append_state(String *str); - rpl_gtid *find_nolock(uint32 domain_id, uint32 server_id); - rpl_gtid *find(uint32 domain_id, uint32 server_id); - rpl_gtid *find_most_recent(uint32 domain_id); - const char* drop_domain(DYNAMIC_ARRAY *ids, Gtid_list_log_event *glev, char*); -}; - - -/* - Represent the GTID state that a slave connection to a master requests - the master to start sending binlog events from. -*/ -struct slave_connection_state -{ - struct entry { - rpl_gtid gtid; - uint32 flags; - }; - /* Bits for 'flags' */ - enum start_flags - { - START_OWN_SLAVE_POS= 0x1, - START_ON_EMPTY_DOMAIN= 0x2 - }; - - /* Mapping from domain_id to the entry with GTID requested for that domain. */ - HASH hash; - - /* Auxiliary buffer to sort gtid list. */ - DYNAMIC_ARRAY gtid_sort_array; - - slave_connection_state(); - ~slave_connection_state(); - - void reset() { my_hash_reset(&hash); } - int load(const char *slave_request, size_t len); - int load(const rpl_gtid *gtid_list, uint32 count); - int load(rpl_slave_state *state, rpl_gtid *extra_gtids, uint32 num_extra); - rpl_gtid *find(uint32 domain_id); - entry *find_entry(uint32 domain_id); - int update(const rpl_gtid *in_gtid); - void remove(const rpl_gtid *gtid); - void remove_if_present(const rpl_gtid *in_gtid); - ulong count() const { return hash.records; } - int to_string(String *out_str); - int append_to_string(String *out_str); - int get_gtid_list(rpl_gtid *gtid_list, uint32 list_size); - bool is_pos_reached(); -}; - - -extern bool rpl_slave_state_tostring_helper(String *dest, const rpl_gtid *gtid, - bool *first); -extern int gtid_check_rpl_slave_state_table(TABLE *table); -extern rpl_gtid *gtid_parse_string_to_list(const char *p, size_t len, - uint32 *out_len); - -#endif /* RPL_GTID_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_injector.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_injector.h deleted file mode 100644 index 669a8e2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_injector.h +++ /dev/null @@ -1,316 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef INJECTOR_H -#define INJECTOR_H - -/* Pull in 'byte', 'my_off_t', and 'uint32' */ -#include - -#include "rpl_constants.h" -#include "table.h" /* TABLE */ - -/* Forward declarations */ -class handler; -class MYSQL_BIN_LOG; -struct TABLE; - - -/* - Injector to inject rows into the MySQL server. - - The injector class is used to notify the MySQL server of new rows that have - appeared outside of MySQL control. - - The original purpose of this is to allow clusters---which handle replication - inside the cluster through other means---to insert new rows into binary log. - Note, however, that the injector should be used whenever rows are altered in - any manner that is outside of MySQL server visibility and which therefore - are not seen by the MySQL server. - */ -class injector -{ -public: - - /* - Get an instance of the injector. - - DESCRIPTION - The injector is a Singleton, so this static function return the - available instance of the injector. - - RETURN VALUE - A pointer to the available injector object. - */ - static injector *instance(); - - /* - Delete the singleton instance (if allocated). Used during server shutdown. - */ - static void free_instance(); - - /* - A transaction where rows can be added. - - DESCRIPTION - The transaction class satisfy the **CopyConstructible** and - **Assignable** requirements. Note that the transaction is *not* - default constructible. - */ - class transaction { - friend class injector; - public: - /* Convenience definitions */ - typedef uchar* record_type; - typedef uint32 server_id_type; - - /* - Table reference. - - RESPONSIBILITY - - The class contains constructors to handle several forms of - references to tables. The constructors can implicitly be used to - construct references from, e.g., strings containing table names. - - EXAMPLE - - The class is intended to be used *by value*. Please, do not try to - construct objects of this type using 'new'; instead construct an - object, possibly a temporary object. For example: - - injector::transaction::table tbl(share->table, true); - MY_BITMAP cols; - my_bitmap_init(&cols, NULL, (i + 7) / 8, false); - inj->write_row(::server_id, tbl, &cols, row_data); - - or - - MY_BITMAP cols; - my_bitmap_init(&cols, NULL, (i + 7) / 8, false); - inj->write_row(::server_id, - injector::transaction::table(share->table, true), - &cols, row_data); - - This will work, be more efficient, and have greater chance of - inlining, not run the risk of losing pointers. - - COLLABORATION - - injector::transaction - Provide a flexible interface to the representation of tables. - - */ - class table - { - public: - table(TABLE *table, bool is_transactional_arg) - : m_table(table), m_is_transactional(is_transactional_arg) - { - } - - char const *db_name() const { return m_table->s->db.str; } - char const *table_name() const { return m_table->s->table_name.str; } - TABLE *get_table() const { return m_table; } - bool is_transactional() const { return m_is_transactional; } - - private: - TABLE *m_table; - bool m_is_transactional; - }; - - /* - Binlog position as a structure. - */ - class binlog_pos { - friend class transaction; - public: - char const *file_name() const { return m_file_name; } - my_off_t file_pos() const { return m_file_pos; } - - private: - char const *m_file_name; - my_off_t m_file_pos; - }; - - transaction() : m_thd(NULL) { } - transaction(transaction const&); - ~transaction(); - - /* Clear transaction, i.e., make calls to 'good()' return false. */ - void clear() { m_thd= NULL; } - - /* Is the transaction in a good state? */ - bool good() const { return m_thd != NULL; } - - /* Default assignment operator: standard implementation */ - transaction& operator=(transaction t) { - swap(t); - return *this; - } - - /* - - DESCRIPTION - - Register table for use within the transaction. All tables - that are going to be used need to be registered before being - used below. The member function will fail with an error if - use_table() is called after any *_row() function has been - called for the transaction. - - RETURN VALUE - - 0 All OK - >0 Failure - - */ -#ifdef TO_BE_DELETED - int use_table(server_id_type sid, table tbl); -#endif - /* - Commit a transaction. - - This member function will clean up after a sequence of *_row calls by, - for example, releasing resource and unlocking files. - */ - int commit(); - - /* - Get the position for the start of the transaction. - - Returns the position in the binary log of the first event in this - transaction. If no event is yet written, the position where the event - *will* be written is returned. This position is known, since a - new_transaction() will lock the binary log and prevent any other - writes to the binary log. - */ - binlog_pos start_pos() const; - - private: - /* Only the injector may construct these object */ - transaction(MYSQL_BIN_LOG *, THD *); - - void swap(transaction& o) { - /* std::swap(m_start_pos, o.m_start_pos); */ - { - binlog_pos const tmp= m_start_pos; - m_start_pos= o.m_start_pos; - o.m_start_pos= tmp; - } - - /* std::swap(m_thd, o.m_thd); */ - { - THD* const tmp= m_thd; - m_thd= o.m_thd; - o.m_thd= tmp; - } - { - enum_state const tmp= m_state; - m_state= o.m_state; - o.m_state= tmp; - } - } - - enum enum_state - { - START_STATE, /* Start state */ - TABLE_STATE, /* At least one table has been registered */ - ROW_STATE, /* At least one row has been registered */ - STATE_COUNT /* State count and sink state */ - } m_state; - - /* - Check and update the state. - - PARAMETER(S) - - target_state - The state we are moving to: TABLE_STATE if we are - writing a table and ROW_STATE if we are writing a row. - - DESCRIPTION - - The internal state will be updated to the target state if - and only if it is a legal move. The only legal moves are: - - START_STATE -> START_STATE - START_STATE -> TABLE_STATE - TABLE_STATE -> TABLE_STATE - TABLE_STATE -> ROW_STATE - - That is: - - It is not possible to write any row before having written at - least one table - - It is not possible to write a table after at least one row - has been written - - RETURN VALUE - - 0 All OK - -1 Incorrect call sequence - */ - int check_state(enum_state const target_state) - { -#ifndef DBUG_OFF - static char const *state_name[] = { - "START_STATE", "TABLE_STATE", "ROW_STATE", "STATE_COUNT" - }; - - DBUG_ASSERT(target_state <= STATE_COUNT); - DBUG_PRINT("info", ("In state %s", state_name[m_state])); -#endif - - if (m_state <= target_state && target_state <= m_state + 1 && - m_state < STATE_COUNT) - m_state= target_state; - else - m_state= STATE_COUNT; - return m_state == STATE_COUNT ? 1 : 0; - } - - - binlog_pos m_start_pos; - THD *m_thd; - }; - - /* - Create a new transaction. This member function will prepare for a - sequence of *_row calls by, for example, reserving resources and - locking files. There are two overloaded alternatives: one returning a - transaction by value and one using placement semantics. The following - two calls are equivalent, with the exception that the latter will - overwrite the transaction. - - injector::transaction trans1= inj->new_trans(thd); - - injector::transaction trans2; - inj->new_trans(thd, &trans); - */ - transaction new_trans(THD *); - void new_trans(THD *, transaction *); - - int record_incident(THD*, Incident incident); - int record_incident(THD*, Incident incident, const LEX_CSTRING *message); - -private: - explicit injector(); - ~injector() { } /* Nothing needs to be done */ - injector(injector const&); /* You're not allowed to copy injector - instances. - */ -}; - -#endif /* INJECTOR_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_mi.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_mi.h deleted file mode 100644 index 4d47689..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_mi.h +++ /dev/null @@ -1,422 +0,0 @@ -/* Copyright (c) 2006, 2012, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_MI_H -#define RPL_MI_H - -#ifdef HAVE_REPLICATION - -#include "rpl_rli.h" -#include "rpl_reporting.h" -#include -#include "rpl_filter.h" -#include "keycaches.h" - -typedef struct st_mysql MYSQL; - -/** - Domain id based filter to handle DO_DOMAIN_IDS and IGNORE_DOMAIN_IDS used to - set filtering on replication slave based on event's GTID domain_id. -*/ -class Domain_id_filter -{ -private: - /* - Flag to tell whether the events in the current GTID group get written to - the relay log. It is set according to the domain_id based filtering rule - on every GTID_EVENT and reset at the end of current GTID event group. - */ - bool m_filter; - - /* - DO_DOMAIN_IDS (0): - Ignore all the events which do not belong to any of the domain ids in the - list. - - IGNORE_DOMAIN_IDS (1): - Ignore the events which belong to one of the domain ids in the list. - */ - DYNAMIC_ARRAY m_domain_ids[2]; - -public: - /* domain id list types */ - enum enum_list_type { - DO_DOMAIN_IDS= 0, - IGNORE_DOMAIN_IDS - }; - - Domain_id_filter(); - - ~Domain_id_filter(); - - /* - Returns whether the current group needs to be filtered. - */ - bool is_group_filtered() { return m_filter; } - - /* - Checks whether the group with the specified domain_id needs to be - filtered and updates m_filter flag accordingly. - */ - void do_filter(ulong domain_id); - - /* - Reset m_filter. It should be called when IO thread receives COMMIT_EVENT or - XID_EVENT. - */ - void reset_filter(); - - /* - Update the do/ignore domain id filter lists. - - @param do_ids [IN] domain ids to be kept - @param ignore_ids [IN] domain ids to be filtered out - @param using_gtid [IN] use GTID? - - @retval false Success - true Error - */ - bool update_ids(DYNAMIC_ARRAY *do_ids, DYNAMIC_ARRAY *ignore_ids, - bool using_gtid); - - /* - Serialize and store the ids from domain id lists into the thd's protocol - buffer. - - @param thd [IN] thread handler - - @retval void - */ - void store_ids(THD *thd); - - /* - Initialize the given domain id list (DYNAMIC_ARRAY) with the - space-separated list of numbers from the specified IO_CACHE where - the first number is the total number of entries to follows. - - @param f [IN] IO_CACHE file - @param type [IN] domain id list type - - @retval false Success - true Error - */ - bool init_ids(IO_CACHE *f, enum_list_type type); - - /* - Return the elements of the give domain id list type as string. - - @param type [IN] domain id list type - - @retval a string buffer storing the total number - of elements followed by the individual - elements (space-separated) in the - specified list. - - Note: Its caller's responsibility to free the returned string buffer. - */ - char *as_string(enum_list_type type); - -}; - - -extern TYPELIB slave_parallel_mode_typelib; - -typedef struct st_rows_event_tracker -{ - char binlog_file_name[FN_REFLEN]; - my_off_t first_seen; - my_off_t last_seen; - bool stmt_end_seen; - void update(const char* file_name, my_off_t pos, - const char* buf, - const Format_description_log_event *fdle); - void reset(); - bool check_and_report(const char* file_name, my_off_t pos); -} Rows_event_tracker; - -/***************************************************************************** - Replication IO Thread - - Master_info contains: - - information about how to connect to a master - - current master log name - - current master log offset - - misc control variables - - Master_info is initialized once from the master.info file if such - exists. Otherwise, data members corresponding to master.info fields - are initialized with defaults specified by master-* options. The - initialization is done through init_master_info() call. - - The format of master.info file: - - log_name - log_pos - master_host - master_user - master_pass - master_port - master_connect_retry - - To write out the contents of master.info file to disk ( needed every - time we read and queue data from the master ), a call to - flush_master_info() is required. - - To clean up, call end_master_info() - -*****************************************************************************/ - -class Master_info : public Slave_reporting_capability -{ - public: - enum enum_using_gtid { - USE_GTID_NO= 0, USE_GTID_CURRENT_POS= 1, USE_GTID_SLAVE_POS= 2 - }; - - Master_info(LEX_CSTRING *connection_name, bool is_slave_recovery); - ~Master_info(); - bool shall_ignore_server_id(ulong s_id); - void clear_in_memory_info(bool all); - bool error() - { - /* If malloc() in initialization failed */ - return connection_name.str == 0; - } - static const char *using_gtid_astext(enum enum_using_gtid arg); - bool using_parallel() - { - return opt_slave_parallel_threads > 0 && - parallel_mode > SLAVE_PARALLEL_NONE; - } - void release(); - void wait_until_free(); - void lock_slave_threads(); - void unlock_slave_threads(); - - /* the variables below are needed because we can change masters on the fly */ - char master_log_name[FN_REFLEN+6]; /* Room for multi-*/ - char host[HOSTNAME_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; - char user[USERNAME_LENGTH+1]; - char password[MAX_PASSWORD_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; - LEX_CSTRING connection_name; /* User supplied connection name */ - LEX_CSTRING cmp_connection_name; /* Connection name in lower case */ - bool ssl; // enables use of SSL connection if true - char ssl_ca[FN_REFLEN], ssl_capath[FN_REFLEN], ssl_cert[FN_REFLEN]; - char ssl_cipher[FN_REFLEN], ssl_key[FN_REFLEN]; - char ssl_crl[FN_REFLEN], ssl_crlpath[FN_REFLEN]; - bool ssl_verify_server_cert; - - my_off_t master_log_pos; - File fd; // we keep the file open, so we need to remember the file pointer - IO_CACHE file; - - mysql_mutex_t data_lock, run_lock, sleep_lock, start_stop_lock; - mysql_cond_t data_cond, start_cond, stop_cond, sleep_cond; - THD *io_thd; - MYSQL* mysql; - uint32 file_id; /* for 3.23 load data infile */ - Relay_log_info rli; - uint port; - Rpl_filter* rpl_filter; /* Each replication can set its filter rule*/ - /* - to hold checksum alg in use until IO thread has received FD. - Initialized to novalue, then set to the queried from master - @@global.binlog_checksum and deactivated once FD has been received. - */ - enum enum_binlog_checksum_alg checksum_alg_before_fd; - uint connect_retry; -#ifndef DBUG_OFF - int events_till_disconnect; - - /* - The following are auxiliary DBUG variables used to kill IO thread in the - middle of a group/transaction (see "kill_slave_io_after_2_events"). - */ - bool dbug_do_disconnect; - int dbug_event_counter; -#endif - bool inited; - volatile bool abort_slave; - volatile uint slave_running; - volatile ulong slave_run_id; - /* - The difference in seconds between the clock of the master and the clock of - the slave (second - first). It must be signed as it may be <0 or >0. - clock_diff_with_master is computed when the I/O thread starts; for this the - I/O thread does a SELECT UNIX_TIMESTAMP() on the master. - "how late the slave is compared to the master" is computed like this: - clock_of_slave - last_timestamp_executed_by_SQL_thread - clock_diff_with_master - - */ - long clock_diff_with_master; - /* - Keeps track of the number of events before fsyncing. - The option --sync-master-info determines how many - events should happen before fsyncing. - */ - uint sync_counter; - float heartbeat_period; // interface with CHANGE MASTER or master.info - ulonglong received_heartbeats; // counter of received heartbeat events - DYNAMIC_ARRAY ignore_server_ids; - ulong master_id; - /* - At reconnect and until the first rotate event is seen, prev_master_id is - the value of master_id during the previous connection, used to detect - silent change of master server during reconnects. - */ - ulong prev_master_id; - /* - Which kind of GTID position (if any) is used when connecting to master. - - Note that you can not change the numeric values of these, they are used - in master.info. - */ - enum enum_using_gtid using_gtid; - - /* - This GTID position records how far we have fetched into the relay logs. - This is used to continue fetching when the IO thread reconnects to the - master. - - (Full slave stop/start does not use it, as it resets the relay logs). - */ - slave_connection_state gtid_current_pos; - /* - If events_queued_since_last_gtid is non-zero, it is the number of events - queued so far in the relaylog of a GTID-prefixed event group. - It is zero when no partial event group has been queued at the moment. - */ - uint64 events_queued_since_last_gtid; - /* - The GTID of the partially-queued event group, when - events_queued_since_last_gtid is non-zero. - */ - rpl_gtid last_queued_gtid; - /* Whether last_queued_gtid had the FL_STANDALONE flag set. */ - bool last_queued_gtid_standalone; - /* - When slave IO thread needs to reconnect, gtid_reconnect_event_skip_count - counts number of events to skip from the first GTID-prefixed event group, - to avoid duplicating events in the relay log. - */ - uint64 gtid_reconnect_event_skip_count; - /* gtid_event_seen is false until we receive first GTID event from master. */ - bool gtid_event_seen; - /** - The struct holds some history of Rows- log-event reading/queuing - by the receiver thread. Its fields are updated per each such event - at time of queue_event(), and they are checked to detect - the Rows- event group integrity violation at time of first non-Rows- - event gets handled. - */ - Rows_event_tracker rows_event_tracker; - bool in_start_all_slaves, in_stop_all_slaves; - bool in_flush_all_relay_logs; - uint users; /* Active user for object */ - uint killed; - - - /* No of DDL event group */ - Atomic_counter total_ddl_groups; - - /* No of non-transactional event group*/ - Atomic_counter total_non_trans_groups; - - /* No of transactional event group*/ - Atomic_counter total_trans_groups; - - /* domain-id based filter */ - Domain_id_filter domain_id_filter; - - /* The parallel replication mode. */ - enum_slave_parallel_mode parallel_mode; - /* - semi_ack is used to identify if the current binlog event needs an - ACK from slave, or if delay_master is enabled. - */ - int semi_ack; -}; - -int init_master_info(Master_info* mi, const char* master_info_fname, - const char* slave_info_fname, - bool abort_if_no_master_info_file, - int thread_mask); -void end_master_info(Master_info* mi); -int flush_master_info(Master_info* mi, - bool flush_relay_log_cache, - bool need_lock_relay_log); -void copy_filter_setting(Rpl_filter* dst_filter, Rpl_filter* src_filter); -void update_change_master_ids(DYNAMIC_ARRAY *new_ids, DYNAMIC_ARRAY *old_ids); -void prot_store_ids(THD *thd, DYNAMIC_ARRAY *ids); - -/* - Multi master are handled trough this struct. - Changes to this needs to be protected by LOCK_active_mi; -*/ - -class Master_info_index -{ -private: - IO_CACHE index_file; - char index_file_name[FN_REFLEN]; - -public: - Master_info_index(); - ~Master_info_index(); - - HASH master_info_hash; - - bool init_all_master_info(); - bool write_master_name_to_index_file(LEX_CSTRING *connection_name, - bool do_sync); - - bool check_duplicate_master_info(LEX_CSTRING *connection_name, - const char *host, uint port); - bool add_master_info(Master_info *mi, bool write_to_file); - bool remove_master_info(Master_info *mi); - Master_info *get_master_info(const LEX_CSTRING *connection_name, - Sql_condition::enum_warning_level warning); - bool start_all_slaves(THD *thd); - bool stop_all_slaves(THD *thd); - void free_connections(); - bool flush_all_relay_logs(); -}; - - -/* - The class rpl_io_thread_info is the THD::system_thread_info for the IO thread. -*/ -class rpl_io_thread_info -{ -public: -}; - - -Master_info *get_master_info(const LEX_CSTRING *connection_name, - Sql_condition::enum_warning_level warning); -bool check_master_connection_name(LEX_CSTRING *name); -void create_logfile_name_with_suffix(char *res_file_name, size_t length, - const char *info_file, - bool append, - LEX_CSTRING *suffix); - -uchar *get_key_master_info(Master_info *mi, size_t *length, - my_bool not_used __attribute__((unused))); -void free_key_master_info(Master_info *mi); -uint any_slave_sql_running(bool already_locked); -bool give_error_if_slave_running(bool already_lock); - -#endif /* HAVE_REPLICATION */ -#endif /* RPL_MI_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_parallel.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_parallel.h deleted file mode 100644 index b88e77d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_parallel.h +++ /dev/null @@ -1,382 +0,0 @@ -#ifndef RPL_PARALLEL_H -#define RPL_PARALLEL_H - -#include "log_event.h" - - -struct rpl_parallel; -struct rpl_parallel_entry; -struct rpl_parallel_thread_pool; - -class Relay_log_info; -struct inuse_relaylog; - - -/* - Structure used to keep track of the parallel replication of a batch of - event-groups that group-committed together on the master. - - It is used to ensure that every event group in one batch has reached the - commit stage before the next batch starts executing. - - Note the lifetime of this structure: - - - It is allocated when the first event in a new batch of group commits - is queued, from the free list rpl_parallel_entry::gco_free_list. - - - The gco for the batch currently being queued is owned by - rpl_parallel_entry::current_gco. The gco for a previous batch that has - been fully queued is owned by the gco->prev_gco pointer of the gco for - the following batch. - - - The worker thread waits on gco->COND_group_commit_orderer for - rpl_parallel_entry::count_committing_event_groups to reach wait_count - before starting; the first waiter links the gco into the next_gco - pointer of the gco of the previous batch for signalling. - - - When an event group reaches the commit stage, it signals the - COND_group_commit_orderer if its gco->next_gco pointer is non-NULL and - rpl_parallel_entry::count_committing_event_groups has reached - gco->next_gco->wait_count. - - - The gco lives until all its event groups have completed their commit. - This is detected by rpl_parallel_entry::last_committed_sub_id being - greater than or equal gco->last_sub_id. Once this happens, the gco is - freed. Note that since update of last_committed_sub_id can happen - out-of-order, the thread that frees a given gco can be for any later - event group, not necessarily an event group from the gco being freed. -*/ -struct group_commit_orderer { - /* Wakeup condition, used with rpl_parallel_entry::LOCK_parallel_entry. */ - mysql_cond_t COND_group_commit_orderer; - uint64 wait_count; - group_commit_orderer *prev_gco; - group_commit_orderer *next_gco; - /* - The sub_id of last event group in the previous GCO. - Only valid if prev_gco != NULL. - */ - uint64 prior_sub_id; - /* - The sub_id of the last event group in this GCO. Only valid when next_gco - is non-NULL. - */ - uint64 last_sub_id; - /* - This flag is set when this GCO has been installed into the next_gco pointer - of the previous GCO. - */ - bool installed; - - enum force_switch_bits - { - /* - This flag is set for a GCO in which we have event groups with multiple - different commit_id values from the master. This happens when we - optimistically try to execute in parallel transactions not known to be - conflict-free. - - When this flag is set, in case of DDL we need to start a new GCO - regardless of current commit_id, as DDL is not safe to - speculatively apply in parallel with prior event groups. - */ - MULTI_BATCH= 1, - /* - This flag is set for a GCO that contains DDL. If set, it forces - a switch to a new GCO upon seeing a new commit_id, as DDL is not - safe to speculatively replicate in parallel with subsequent - transactions. - */ - FORCE_SWITCH= 2 - }; - uint8 flags; -}; - - -struct rpl_parallel_thread { - bool delay_start; - bool running; - bool stop; - bool pause_for_ftwrl; - mysql_mutex_t LOCK_rpl_thread; - mysql_cond_t COND_rpl_thread; - mysql_cond_t COND_rpl_thread_queue; - mysql_cond_t COND_rpl_thread_stop; - struct rpl_parallel_thread *next; /* For free list. */ - struct rpl_parallel_thread_pool *pool; - THD *thd; - /* - Who owns the thread, if any (it's a pointer into the - rpl_parallel_entry::rpl_threads array. - */ - struct rpl_parallel_thread **current_owner; - /* The rpl_parallel_entry of the owner. */ - rpl_parallel_entry *current_entry; - struct queued_event { - queued_event *next; - /* - queued_event can hold either an event to be executed, or just a binlog - position to be updated without any associated event. - */ - enum queued_event_t { - QUEUED_EVENT, - QUEUED_POS_UPDATE, - QUEUED_MASTER_RESTART - } typ; - union { - Log_event *ev; /* QUEUED_EVENT */ - rpl_parallel_entry *entry_for_queued; /* QUEUED_POS_UPDATE and - QUEUED_MASTER_RESTART */ - }; - rpl_group_info *rgi; - inuse_relaylog *ir; - ulonglong future_event_relay_log_pos; - char event_relay_log_name[FN_REFLEN]; - char future_event_master_log_name[FN_REFLEN]; - ulonglong event_relay_log_pos; - my_off_t future_event_master_log_pos; - size_t event_size; - } *event_queue, *last_in_queue; - uint64 queued_size; - /* These free lists are protected by LOCK_rpl_thread. */ - queued_event *qev_free_list; - rpl_group_info *rgi_free_list; - group_commit_orderer *gco_free_list; - /* - These free lists are local to the thread, so need not be protected by any - lock. They are moved to the global free lists in batches in the function - batch_free(), to reduce LOCK_rpl_thread contention. - - The lists are not NULL-terminated (as we do not need to traverse them). - Instead, if they are non-NULL, the loc_XXX_last_ptr_ptr points to the - `next' pointer of the last element, which is used to link into the front - of the global freelists. - */ - queued_event *loc_qev_list, **loc_qev_last_ptr_ptr; - size_t loc_qev_size; - uint64 qev_free_pending; - rpl_group_info *loc_rgi_list, **loc_rgi_last_ptr_ptr; - group_commit_orderer *loc_gco_list, **loc_gco_last_ptr_ptr; - /* These keep track of batch update of inuse_relaylog refcounts. */ - inuse_relaylog *accumulated_ir_last; - uint64 accumulated_ir_count; - - void enqueue(queued_event *qev) - { - if (last_in_queue) - last_in_queue->next= qev; - else - event_queue= qev; - last_in_queue= qev; - queued_size+= qev->event_size; - } - - void dequeue1(queued_event *list) - { - DBUG_ASSERT(list == event_queue); - event_queue= last_in_queue= NULL; - } - - void dequeue2(size_t dequeue_size) - { - queued_size-= dequeue_size; - } - - queued_event *get_qev_common(Log_event *ev, ulonglong event_size); - queued_event *get_qev(Log_event *ev, ulonglong event_size, - Relay_log_info *rli); - queued_event *retry_get_qev(Log_event *ev, queued_event *orig_qev, - const char *relay_log_name, - ulonglong event_pos, ulonglong event_size); - /* - Put a qev on the local free list, to be later released to the global free - list by batch_free(). - */ - void loc_free_qev(queued_event *qev); - /* - Release an rgi immediately to the global free list. Requires holding the - LOCK_rpl_thread mutex. - */ - void free_qev(queued_event *qev); - rpl_group_info *get_rgi(Relay_log_info *rli, Gtid_log_event *gtid_ev, - rpl_parallel_entry *e, ulonglong event_size); - /* - Put an gco on the local free list, to be later released to the global free - list by batch_free(). - */ - void loc_free_rgi(rpl_group_info *rgi); - /* - Release an rgi immediately to the global free list. Requires holding the - LOCK_rpl_thread mutex. - */ - void free_rgi(rpl_group_info *rgi); - group_commit_orderer *get_gco(uint64 wait_count, group_commit_orderer *prev, - uint64 first_sub_id); - /* - Put a gco on the local free list, to be later released to the global free - list by batch_free(). - */ - void loc_free_gco(group_commit_orderer *gco); - /* - Move all local free lists to the global ones. Requires holding - LOCK_rpl_thread. - */ - void batch_free(); - /* Update inuse_relaylog refcounts with what we have accumulated so far. */ - void inuse_relaylog_refcount_update(); -}; - - -struct rpl_parallel_thread_pool { - struct rpl_parallel_thread **threads; - struct rpl_parallel_thread *free_list; - mysql_mutex_t LOCK_rpl_thread_pool; - mysql_cond_t COND_rpl_thread_pool; - uint32 count; - bool inited; - /* - While FTWRL runs, this counter is incremented to make SQL thread or - STOP/START slave not try to start new activity while that operation - is in progress. - */ - bool busy; - - rpl_parallel_thread_pool(); - int init(uint32 size); - void destroy(); - void deactivate(); - void destroy_cond_mutex(); - struct rpl_parallel_thread *get_thread(rpl_parallel_thread **owner, - rpl_parallel_entry *entry); - void release_thread(rpl_parallel_thread *rpt); -}; - - -struct rpl_parallel_entry { - mysql_mutex_t LOCK_parallel_entry; - mysql_cond_t COND_parallel_entry; - uint32 domain_id; - /* - Incremented by wait_for_workers_idle() and rpl_pause_for_ftwrl() to show - that they are waiting, so that finish_event_group knows to signal them - when last_committed_sub_id is increased. - */ - uint32 need_sub_id_signal; - uint64 last_commit_id; - bool active; - /* - Set when SQL thread is shutting down, and no more events can be processed, - so worker threads must force abort any current transactions without - waiting for event groups to complete. - */ - bool force_abort; - /* - At STOP SLAVE (force_abort=true), we do not want to process all events in - the queue (which could unnecessarily delay stop, if a lot of events happen - to be queued). The stop_count provides a safe point at which to stop, so - that everything before becomes committed and nothing after does. The value - corresponds to group_commit_orderer::wait_count; if wait_count is less than - or equal to stop_count, we execute the associated event group, else we - skip it (and all following) and stop. - */ - uint64 stop_count; - - /* - Cyclic array recording the last rpl_thread_max worker threads that we - queued event for. This is used to limit how many workers a single domain - can occupy (--slave-domain-parallel-threads). - - Note that workers are never explicitly deleted from the array. Instead, - we need to check (under LOCK_rpl_thread) that the thread still belongs - to us before re-using (rpl_thread::current_owner). - */ - rpl_parallel_thread **rpl_threads; - uint32 rpl_thread_max; - uint32 rpl_thread_idx; - /* - The sub_id of the last transaction to commit within this domain_id. - Must be accessed under LOCK_parallel_entry protection. - - Event groups commit in order, so the rpl_group_info for an event group - will be alive (at least) as long as - rpl_group_info::gtid_sub_id > last_committed_sub_id. This can be used to - safely refer back to previous event groups if they are still executing, - and ignore them if they completed, without requiring explicit - synchronisation between the threads. - */ - uint64 last_committed_sub_id; - /* - The sub_id of the last event group in this replication domain that was - queued for execution by a worker thread. - */ - uint64 current_sub_id; - /* - The largest sub_id that has started its transaction. Protected by - LOCK_parallel_entry. - - (Transactions can start out-of-order, so this value signifies that no - transactions with larger sub_id have started, but not necessarily that all - transactions with smaller sub_id have started). - */ - uint64 largest_started_sub_id; - rpl_group_info *current_group_info; - /* - If we get an error in some event group, we set the sub_id of that event - group here. Then later event groups (with higher sub_id) can know not to - try to start (event groups that already started will be rolled back when - wait_for_prior_commit() returns error). - The value is ULONGLONG_MAX when no error occurred. - */ - uint64 stop_on_error_sub_id; - /* - During FLUSH TABLES WITH READ LOCK, transactions with sub_id larger than - this value must not start, but wait until the global read lock is released. - The value is set to ULONGLONG_MAX when no FTWRL is pending. - */ - uint64 pause_sub_id; - /* Total count of event groups queued so far. */ - uint64 count_queued_event_groups; - /* - Count of event groups that have started (but not necessarily completed) - the commit phase. We use this to know when every event group in a previous - batch of master group commits have started committing on the slave, so - that it is safe to start executing the events in the following batch. - */ - uint64 count_committing_event_groups; - /* The group_commit_orderer object for the events currently being queued. */ - group_commit_orderer *current_gco; - - rpl_parallel_thread * choose_thread(rpl_group_info *rgi, bool *did_enter_cond, - PSI_stage_info *old_stage, - Gtid_log_event *gtid_ev); - int queue_master_restart(rpl_group_info *rgi, - Format_description_log_event *fdev); -}; -struct rpl_parallel { - HASH domain_hash; - rpl_parallel_entry *current; - bool sql_thread_stopping; - - rpl_parallel(); - ~rpl_parallel(); - void reset(); - rpl_parallel_entry *find(uint32 domain_id); - void wait_for_done(THD *thd, Relay_log_info *rli); - void stop_during_until(); - bool workers_idle(); - int wait_for_workers_idle(THD *thd); - int do_event(rpl_group_info *serial_rgi, Log_event *ev, ulonglong event_size); -}; - - -extern struct rpl_parallel_thread_pool global_rpl_thread_pool; - - -extern int rpl_parallel_resize_pool_if_no_slaves(void); -extern int rpl_parallel_activate_pool(rpl_parallel_thread_pool *pool); -extern int rpl_parallel_inactivate_pool(rpl_parallel_thread_pool *pool); -extern bool process_gtid_for_restart_pos(Relay_log_info *rli, rpl_gtid *gtid); -extern int rpl_pause_for_ftwrl(THD *thd); -extern void rpl_unpause_after_ftwrl(THD *thd); - -#endif /* RPL_PARALLEL_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_record.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_record.h deleted file mode 100644 index 357dc76..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_record.h +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. - Copyright (c) 2008, 2013, SkySQL Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_RECORD_H -#define RPL_RECORD_H - -#include - -struct rpl_group_info; -struct TABLE; -typedef struct st_bitmap MY_BITMAP; - -#if !defined(MYSQL_CLIENT) -size_t pack_row(TABLE* table, MY_BITMAP const* cols, - uchar *row_data, const uchar *data); -#endif - -#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) -int unpack_row(rpl_group_info *rgi, - TABLE *table, uint const colcnt, - uchar const *const row_data, MY_BITMAP const *cols, - uchar const **const curr_row_end, ulong *const master_reclength, - uchar const *const row_end); - -// Fill table's record[0] with default values. -int prepare_record(TABLE *const table, const uint skip, const bool check); -int fill_extra_persistent_columns(TABLE *table, int master_cols); -#endif - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_record_old.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_record_old.h deleted file mode 100644 index 0b2dd43..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_record_old.h +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_RECORD_OLD_H -#define RPL_RECORD_OLD_H - -#include "log_event.h" /* Log_event_type */ - -#ifndef MYSQL_CLIENT -size_t pack_row_old(TABLE *table, MY_BITMAP const* cols, - uchar *row_data, const uchar *record); - -#ifdef HAVE_REPLICATION -int unpack_row_old(rpl_group_info *rgi, - TABLE *table, uint const colcnt, uchar *record, - uchar const *row, uchar const *row_buffer_end, - MY_BITMAP const *cols, - uchar const **row_end, ulong *master_reclength, - MY_BITMAP* const rw_set, - Log_event_type const event_type); -#endif -#endif -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_reporting.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_reporting.h deleted file mode 100644 index 62b934c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_reporting.h +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_REPORTING_H -#define RPL_REPORTING_H - -#include /* loglevel */ - -/** - Maximum size of an error message from a slave thread. - */ -#define MAX_SLAVE_ERRMSG 1024 - -/** - Mix-in to handle the message logging and reporting for relay log - info and master log info structures. - - By inheriting from this class, the class is imbued with - capabilities to do slave reporting. - */ -class Slave_reporting_capability -{ -public: - /** lock used to synchronize m_last_error on 'SHOW SLAVE STATUS' **/ - mutable mysql_mutex_t err_lock; - /** - Constructor. - - @param thread_name Printable name of the slave thread that is reporting. - */ - Slave_reporting_capability(char const *thread_name); - - /** - Writes a message and, if it's an error message, to Last_Error - (which will be displayed by SHOW SLAVE STATUS). - - @param level The severity level - @param err_code The error code - @param msg The message (usually related to the error - code, but can contain more information), in - printf() format. - */ - void report(loglevel level, int err_code, const char *extra_info, - const char *msg, ...) const - ATTRIBUTE_FORMAT(printf, 5, 6); - - /** - Clear errors. They will not show up under SHOW SLAVE - STATUS. - */ - void clear_error() { - mysql_mutex_lock(&err_lock); - m_last_error.clear(); - mysql_mutex_unlock(&err_lock); - } - - /** - Error information structure. - */ - class Error { - friend class Slave_reporting_capability; - public: - Error() - { - clear(); - } - - void clear() - { - number= 0; - message[0]= '\0'; - } - - /** Error code */ - uint32 number; - /** Error message */ - char message[MAX_SLAVE_ERRMSG]; - }; - - Error const& last_error() const { return m_last_error; } - - virtual ~Slave_reporting_capability()= 0; -private: - /** - Last error produced by the I/O or SQL thread respectively. - */ - mutable Error m_last_error; - - char const *const m_thread_name; - - // not implemented - Slave_reporting_capability(const Slave_reporting_capability& rhs); - Slave_reporting_capability& operator=(const Slave_reporting_capability& rhs); -}; - -#endif // RPL_REPORTING_H - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_rli.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_rli.h deleted file mode 100644 index 4223e01..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_rli.h +++ /dev/null @@ -1,998 +0,0 @@ -/* Copyright (c) 2005, 2017, Oracle and/or its affiliates. - Copyright (c) 2009, 2017, MariaDB Corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_RLI_H -#define RPL_RLI_H - -#include "rpl_tblmap.h" -#include "rpl_reporting.h" -#include "rpl_utility.h" -#include "log.h" /* LOG_INFO, MYSQL_BIN_LOG */ -#include "sql_class.h" /* THD */ -#include "log_event.h" -#include "rpl_parallel.h" - -struct RPL_TABLE_LIST; -class Master_info; -class Rpl_filter; - - -/**************************************************************************** - - Replication SQL Thread - - Relay_log_info contains: - - the current relay log - - the current relay log offset - - master log name - - master log sequence corresponding to the last update - - misc information specific to the SQL thread - - Relay_log_info is initialized from the slave.info file if such - exists. Otherwise, data members are intialized with defaults. The - initialization is done with Relay_log_info::init() call. - - The format of slave.info file: - - relay_log_name - relay_log_pos - master_log_name - master_log_pos - - To clean up, call end_relay_log_info() - -*****************************************************************************/ - -struct rpl_group_info; -struct inuse_relaylog; - -class Relay_log_info : public Slave_reporting_capability -{ -public: - /** - Flags for the state of reading the relay log. Note that these are - bit masks. - */ - enum enum_state_flag { - /** We are inside a group of events forming a statement */ - IN_STMT=1, - /** We have inside a transaction */ - IN_TRANSACTION=2 - }; - - /* - The SQL thread owns one Relay_log_info, and each client that has - executed a BINLOG statement owns one Relay_log_info. This function - returns zero for the Relay_log_info object that belongs to the SQL - thread and nonzero for Relay_log_info objects that belong to - clients. - */ - inline bool belongs_to_client() - { - DBUG_ASSERT(sql_driver_thd); - return !sql_driver_thd->slave_thread; - } - - /* - If true, events with the same server id should be replicated. This - field is set on creation of a relay log info structure by copying - the value of ::replicate_same_server_id and can be overridden if - necessary. For example of when this is done, check sql_binlog.cc, - where the BINLOG statement can be used to execute "raw" events. - */ - bool replicate_same_server_id; - - /*** The following variables can only be read when protect by data lock ****/ - - /* - info_fd - file descriptor of the info file. set only during - initialization or clean up - safe to read anytime - cur_log_fd - file descriptor of the current read relay log - */ - File info_fd,cur_log_fd; - - /* - Protected with internal locks. - Must get data_lock when resetting the logs. - */ - MYSQL_BIN_LOG relay_log; - LOG_INFO linfo; - - /* - cur_log - Pointer that either points at relay_log.get_log_file() or - &rli->cache_buf, depending on whether the log is hot or there was - the need to open a cold relay_log. - - cache_buf - IO_CACHE used when opening cold relay logs. - */ - IO_CACHE cache_buf,*cur_log; - - /* - Keeps track of the number of transactions that commits - before fsyncing. The option --sync-relay-log-info determines - how many transactions should commit before fsyncing. - */ - uint sync_counter; - - /* - Identifies when the recovery process is going on. - See sql/slave.cc:init_recovery for further details. - */ - bool is_relay_log_recovery; - - /* The following variables are safe to read any time */ - - /* IO_CACHE of the info file - set only during init or end */ - IO_CACHE info_file; - - /* - List of temporary tables used by this connection. - This is updated when a temporary table is created or dropped by - a replication thread. - - Not reset when replication ends, to allow one to access the tables - when replication restarts. - - Protected by data_lock. - */ - All_tmp_tables_list *save_temporary_tables; - - /* - standard lock acquisition order to avoid deadlocks: - run_lock, data_lock, relay_log.LOCK_log, relay_log.LOCK_index - */ - mysql_mutex_t data_lock, run_lock; - /* - start_cond is broadcast when SQL thread is started - stop_cond - when stopped - data_cond - when data protected by data_lock changes - */ - mysql_cond_t start_cond, stop_cond, data_cond; - /* parent Master_info structure */ - Master_info *mi; - - /* - List of active relay log files. - (This can be more than one in case of parallel replication). - */ - inuse_relaylog *inuse_relaylog_list; - inuse_relaylog *last_inuse_relaylog; - - /* - Needed to deal properly with cur_log getting closed and re-opened with - a different log under our feet - */ - uint32 cur_log_old_open_count; - - /* - If on init_info() call error_on_rli_init_info is true that means - that previous call to init_info() terminated with an error, RESET - SLAVE must be executed and the problem fixed manually. - */ - bool error_on_rli_init_info; - - /* - Let's call a group (of events) : - - a transaction - or - - an autocommiting query + its associated events (INSERT_ID, - TIMESTAMP...) - We need these rli coordinates : - - relay log name and position of the beginning of the group we currently - are executing. Needed to know where we have to restart when replication has - stopped in the middle of a group (which has been rolled back by the slave). - - relay log name and position just after the event we have just - executed. This event is part of the current group. - Formerly we only had the immediately above coordinates, plus a 'pending' - variable, but this dealt wrong with the case of a transaction starting on a - relay log and finishing (commiting) on another relay log. Case which can - happen when, for example, the relay log gets rotated because of - max_binlog_size. - - Note: group_relay_log_name, group_relay_log_pos must only be - written from the thread owning the Relay_log_info (SQL thread if - !belongs_to_client(); client thread executing BINLOG statement if - belongs_to_client()). - */ - char group_relay_log_name[FN_REFLEN]; - ulonglong group_relay_log_pos; - char event_relay_log_name[FN_REFLEN]; - ulonglong event_relay_log_pos; - ulonglong future_event_relay_log_pos; - /* - The master log name for current event. Only used in parallel replication. - */ - char future_event_master_log_name[FN_REFLEN]; - - /* - Original log name and position of the group we're currently executing - (whose coordinates are group_relay_log_name/pos in the relay log) - in the master's binlog. These concern the *group*, because in the master's - binlog the log_pos that comes with each event is the position of the - beginning of the group. - - Note: group_master_log_name, group_master_log_pos must only be - written from the thread owning the Relay_log_info (SQL thread if - !belongs_to_client(); client thread executing BINLOG statement if - belongs_to_client()). - */ - char group_master_log_name[FN_REFLEN]; - volatile my_off_t group_master_log_pos; - - /* - Handling of the relay_log_space_limit optional constraint. - ignore_log_space_limit is used to resolve a deadlock between I/O and SQL - threads, the SQL thread sets it to unblock the I/O thread and make it - temporarily forget about the constraint. - */ - ulonglong log_space_limit,log_space_total; - bool ignore_log_space_limit; - - /* - Used by the SQL thread to instructs the IO thread to rotate - the logs when the SQL thread needs to purge to release some - disk space. - */ - bool sql_force_rotate_relay; - - time_t last_master_timestamp; - /* - The SQL driver thread sets this true while it is waiting at the end of the - relay log for more events to arrive. SHOW SLAVE STATUS uses this to report - Seconds_Behind_Master as zero while the SQL thread is so waiting. - */ - bool sql_thread_caught_up; - - void clear_until_condition(); - /** - Reset the delay. - This is used by RESET SLAVE to clear the delay. - */ - void clear_sql_delay() - { - sql_delay= 0; - } - - - /* - Needed for problems when slave stops and we want to restart it - skipping one or more events in the master log that have caused - errors, and have been manually applied by DBA already. - Must be ulong as it's refered to from set_var.cc - */ - volatile ulonglong slave_skip_counter; - ulonglong max_relay_log_size; - - volatile ulong abort_pos_wait; /* Incremented on change master */ - volatile ulong slave_run_id; /* Incremented on slave start */ - mysql_mutex_t log_space_lock; - mysql_cond_t log_space_cond; - /* - THD for the main sql thread, the one that starts threads to process - slave requests. If there is only one thread, then this THD is also - used for SQL processing. - A kill sent to this THD will kill the replication. - */ - THD *sql_driver_thd; -#ifndef DBUG_OFF - int events_till_abort; -#endif - - enum_gtid_skip_type gtid_skip_flag; - - /* - inited changes its value within LOCK_active_mi-guarded critical - sections at times of start_slave_threads() (0->1) and end_slave() (1->0). - Readers may not acquire the mutex while they realize potential concurrency - issue. - If not set, the value of other members of the structure are undefined. - */ - volatile bool inited; - volatile bool abort_slave; - volatile bool stop_for_until; - volatile uint slave_running; - - /* - Condition and its parameters from START SLAVE UNTIL clause. - - UNTIL condition is tested with is_until_satisfied() method that is - called by exec_relay_log_event(). is_until_satisfied() caches the result - of the comparison of log names because log names don't change very often; - this cache is invalidated by parts of code which change log names with - notify_*_log_name_updated() methods. (They need to be called only if SQL - thread is running). - */ - - enum { - UNTIL_NONE= 0, UNTIL_MASTER_POS, UNTIL_RELAY_POS, UNTIL_GTID - } until_condition; - char until_log_name[FN_REFLEN]; - ulonglong until_log_pos; - /* extension extracted from log_name and converted to int */ - ulong until_log_name_extension; - /* - Cached result of comparison of until_log_name and current log name - -2 means unitialised, -1,0,1 are comarison results - */ - enum - { - UNTIL_LOG_NAMES_CMP_UNKNOWN= -2, UNTIL_LOG_NAMES_CMP_LESS= -1, - UNTIL_LOG_NAMES_CMP_EQUAL= 0, UNTIL_LOG_NAMES_CMP_GREATER= 1 - } until_log_names_cmp_result; - /* Condition for UNTIL master_gtid_pos. */ - slave_connection_state until_gtid_pos; - - /* - retried_trans is a cumulative counter: how many times the slave - has retried a transaction (any) since slave started. - Protected by data_lock. - */ - ulong retried_trans; - /* - Number of executed events for SLAVE STATUS. - Protected by slave_executed_entries_lock - */ - Atomic_counter executed_entries; - - /* - If the end of the hot relay log is made of master's events ignored by the - slave I/O thread, these two keep track of the coords (in the master's - binlog) of the last of these events seen by the slave I/O thread. If not, - ign_master_log_name_end[0] == 0. - As they are like a Rotate event read/written from/to the relay log, they - are both protected by rli->relay_log.LOCK_log. - */ - char ign_master_log_name_end[FN_REFLEN]; - ulonglong ign_master_log_pos_end; - /* Similar for ignored GTID events. */ - slave_connection_state ign_gtids; - - /* - Indentifies where the SQL Thread should create temporary files for the - LOAD DATA INFILE. This is used for security reasons. - */ - char slave_patternload_file[FN_REFLEN]; - size_t slave_patternload_file_size; - - rpl_parallel parallel; - /* - The relay_log_state keeps track of the current binlog state of the - execution of the relay log. This is used to know where to resume - current GTID position if the slave thread is stopped and - restarted. It is only accessed from the SQL thread, so it does - not need any locking. - */ - rpl_binlog_state relay_log_state; - /* - The restart_gtid_state is used when the SQL thread restarts on a relay log - in GTID mode. In multi-domain parallel replication, each domain may have a - separat position, so some events in more progressed domains may need to be - skipped. This keeps track of the domains that have not yet reached their - starting event. - */ - slave_connection_state restart_gtid_pos; - - Relay_log_info(bool is_slave_recovery, const char* thread_name= "SQL"); - ~Relay_log_info(); - - /* - Invalidate cached until_log_name and group_relay_log_name comparison - result. Should be called after any update of group_realy_log_name if - there chances that sql_thread is running. - */ - inline void notify_group_relay_log_name_update() - { - if (until_condition==UNTIL_RELAY_POS) - until_log_names_cmp_result= UNTIL_LOG_NAMES_CMP_UNKNOWN; - } - - /* - The same as previous but for group_master_log_name. - */ - inline void notify_group_master_log_name_update() - { - if (until_condition==UNTIL_MASTER_POS) - until_log_names_cmp_result= UNTIL_LOG_NAMES_CMP_UNKNOWN; - } - - void inc_group_relay_log_pos(ulonglong log_pos, - rpl_group_info *rgi, - bool skip_lock=0); - - int wait_for_pos(THD* thd, String* log_name, longlong log_pos, - longlong timeout); - void close_temporary_tables(); - - /* Check if UNTIL condition is satisfied. See slave.cc for more. */ - bool is_until_satisfied(Log_event *ev); - inline ulonglong until_pos() - { - DBUG_ASSERT(until_condition == UNTIL_MASTER_POS || - until_condition == UNTIL_RELAY_POS); - return ((until_condition == UNTIL_MASTER_POS) ? group_master_log_pos : - group_relay_log_pos); - } - inline char *until_name() - { - DBUG_ASSERT(until_condition == UNTIL_MASTER_POS || - until_condition == UNTIL_RELAY_POS); - return ((until_condition == UNTIL_MASTER_POS) ? group_master_log_name : - group_relay_log_name); - } - /** - Helper function to do after statement completion. - - This function is called from an event to complete the group by - either stepping the group position, if the "statement" is not - inside a transaction; or increase the event position, if the - "statement" is inside a transaction. - - @param event_log_pos - Master log position of the event. The position is recorded in the - relay log info and used to produce information for SHOW - SLAVE STATUS. - */ - bool stmt_done(my_off_t event_log_pos, THD *thd, rpl_group_info *rgi); - int alloc_inuse_relaylog(const char *name); - void free_inuse_relaylog(inuse_relaylog *ir); - void reset_inuse_relaylog(); - int update_relay_log_state(rpl_gtid *gtid_list, uint32 count); - - /** - Is the replication inside a group? - - The reader of the relay log is inside a group if either: - - The IN_TRANSACTION flag is set, meaning we're inside a transaction - - The IN_STMT flag is set, meaning we have read at least one row from - a multi-event entry. - - This flag reflects the state of the log 'just now', ie after the last - read event would be executed. - This allow us to test if we can stop replication before reading - the next entry. - - @retval true Replication thread is currently inside a group - @retval false Replication thread is currently not inside a group - */ - bool is_in_group() const { - return (m_flags & (IN_STMT | IN_TRANSACTION)); - } - - /** - Set the value of a replication state flag. - - @param flag Flag to set - */ - void set_flag(enum_state_flag flag) - { - m_flags|= flag; - } - - /** - Get the value of a replication state flag. - - @param flag Flag to get value of - - @return @c true if the flag was set, @c false otherwise. - */ - bool get_flag(enum_state_flag flag) - { - return m_flags & flag; - } - - /** - Clear the value of a replication state flag. - - @param flag Flag to clear - */ - void clear_flag(enum_state_flag flag) - { - m_flags&= ~flag; - } - - /** - Text used in THD::proc_info when the slave SQL thread is delaying. - */ - static const char *const state_delaying_string; - - bool flush(); - - /** - Reads the relay_log.info file. - */ - int init(const char* info_filename); - - /** - Indicate that a delay starts. - - This does not actually sleep; it only sets the state of this - Relay_log_info object to delaying so that the correct state can be - reported by SHOW SLAVE STATUS and SHOW PROCESSLIST. - - Requires rli->data_lock. - - @param delay_end The time when the delay shall end. - */ - void start_sql_delay(time_t delay_end) - { - mysql_mutex_assert_owner(&data_lock); - sql_delay_end= delay_end; - thd_proc_info(sql_driver_thd, state_delaying_string); - } - - int32 get_sql_delay() { return sql_delay; } - void set_sql_delay(int32 _sql_delay) { sql_delay= _sql_delay; } - time_t get_sql_delay_end() { return sql_delay_end; } - -private: - - - /** - Delay slave SQL thread by this amount, compared to master (in - seconds). This is set with CHANGE MASTER TO MASTER_DELAY=X. - - Guarded by data_lock. Initialized by the client thread executing - START SLAVE. Written by client threads executing CHANGE MASTER TO - MASTER_DELAY=X. Read by SQL thread and by client threads - executing SHOW SLAVE STATUS. Note: must not be written while the - slave SQL thread is running, since the SQL thread reads it without - a lock when executing Relay_log_info::flush(). - */ - int sql_delay; - - /** - During a delay, specifies the point in time when the delay ends. - - This is used for the SQL_Remaining_Delay column in SHOW SLAVE STATUS. - - Guarded by data_lock. Written by the sql thread. Read by client - threads executing SHOW SLAVE STATUS. - */ - time_t sql_delay_end; - - /* - Before the MASTER_DELAY parameter was added (WL#344), - relay_log.info had 4 lines. Now it has 5 lines. - */ - static const int LINES_IN_RELAY_LOG_INFO_WITH_DELAY= 5; - /* - Hint for when to stop event distribution by sql driver thread. - The flag is set ON by a non-group event when this event is in the middle - of a group (e.g a transaction group) so it's too early - to refresh the current-relay-log vs until-log cached comparison result. - And it is checked and to decide whether it's a right time to do so - when the being processed group has been fully scheduled. - */ - bool until_relay_log_names_defer; - - /* - Holds the state of the data in the relay log. - We need this to ensure that we are not in the middle of a - statement or inside BEGIN ... COMMIT when should rotate the - relay log. - */ - uint32 m_flags; -}; - - -/* - In parallel replication, if we need to re-try a transaction due to a - deadlock or other temporary error, we may need to go back and re-read events - out of an earlier relay log. - - This structure keeps track of the relaylogs that are potentially in use. - Each rpl_group_info has a pointer to one of those, corresponding to the - first GTID event. - - A pair of reference count keeps track of how long a relay log is potentially - in use. When the `completed' flag is set, all events have been read out of - the relay log, but the log might still be needed for retry in worker - threads. As worker threads complete an event group, they increment - atomically the `dequeued_count' with number of events queued. Thus, when - completed is set and dequeued_count equals queued_count, the relay log file - is finally done with and can be purged. - - By separating the queued and dequeued count, only the dequeued_count needs - multi-thread synchronisation; the completed flag and queued_count fields - are only accessed by the SQL driver thread and need no synchronisation. -*/ -struct inuse_relaylog { - inuse_relaylog *next; - Relay_log_info *rli; - /* - relay_log_state holds the binlog state corresponding to the start of this - relay log file. It is an array with relay_log_state_count elements. - */ - rpl_gtid *relay_log_state; - uint32 relay_log_state_count; - /* Number of events in this relay log queued for worker threads. */ - int64 queued_count; - /* Number of events completed by worker threads. */ - Atomic_counter dequeued_count; - /* Set when all events have been read from a relaylog. */ - bool completed; - char name[FN_REFLEN]; - - inuse_relaylog(Relay_log_info *rli_arg, rpl_gtid *relay_log_state_arg, - uint32 relay_log_state_count_arg, - const char *name_arg): - next(0), rli(rli_arg), relay_log_state(relay_log_state_arg), - relay_log_state_count(relay_log_state_count_arg), queued_count(0), - dequeued_count(0), completed(false) - { - strmake_buf(name, name_arg); - } -}; - - -/* - This is data for various state needed to be kept for the processing of - one event group (transaction) during replication. - - In single-threaded replication, there will be one global rpl_group_info and - one global Relay_log_info per master connection. They will be linked - together. - - In parallel replication, there will be one rpl_group_info object for - each running sql thread, each having their own thd. - - All rpl_group_info will share the same Relay_log_info. -*/ - -struct rpl_group_info -{ - rpl_group_info *next; /* For free list in rpl_parallel_thread */ - Relay_log_info *rli; - THD *thd; - /* - Current GTID being processed. - The sub_id gives the binlog order within one domain_id. A zero sub_id - means that there is no active GTID. - */ - uint64 gtid_sub_id; - rpl_gtid current_gtid; - uint64 commit_id; - /* - This is used to keep transaction commit order. - We will signal this when we commit, and can register it to wait for the - commit_orderer of the previous commit to signal us. - */ - wait_for_commit commit_orderer; - /* - If non-zero, the sub_id of a prior event group whose commit we have to wait - for before committing ourselves. Then wait_commit_group_info points to the - event group to wait for. - - Before using this, rpl_parallel_entry::last_committed_sub_id should be - compared against wait_commit_sub_id. Only if last_committed_sub_id is - smaller than wait_commit_sub_id must the wait be done (otherwise the - waited-for transaction is already committed, so we would otherwise wait - for the wrong commit). - */ - uint64 wait_commit_sub_id; - rpl_group_info *wait_commit_group_info; - /* - This holds a pointer to a struct that keeps track of the need to wait - for the previous batch of event groups to reach the commit stage, before - this batch can start to execute. - - (When we execute in parallel the transactions that group committed - together on the master, we still need to wait for any prior transactions - to have reached the commit stage). - - The pointed-to gco is only valid for as long as - gtid_sub_id < parallel_entry->last_committed_sub_id. After that, it can - be freed by another thread. - */ - group_commit_orderer *gco; - - struct rpl_parallel_entry *parallel_entry; - - /* - A container to hold on Intvar-, Rand-, Uservar- log-events in case - the slave is configured with table filtering rules. - The withhold events are executed when their parent Query destiny is - determined for execution as well. - */ - Deferred_log_events *deferred_events; - - /* - State of the container: true stands for IRU events gathering, - false does for execution, either deferred or direct. - */ - bool deferred_events_collecting; - - Annotate_rows_log_event *m_annotate_event; - - RPL_TABLE_LIST *tables_to_lock; /* RBR: Tables to lock */ - uint tables_to_lock_count; /* RBR: Count of tables to lock */ - table_mapping m_table_map; /* RBR: Mapping table-id to table */ - mysql_mutex_t sleep_lock; - mysql_cond_t sleep_cond; - - /* - trans_retries varies between 0 to slave_transaction_retries and counts how - many times the slave has retried the present transaction; gets reset to 0 - when the transaction finally succeeds. - */ - ulong trans_retries; - - /* - Used to defer stopping the SQL thread to give it a chance - to finish up the current group of events. - The timestamp is set and reset in @c sql_slave_killed(). - */ - time_t last_event_start_time; - - char *event_relay_log_name; - char event_relay_log_name_buf[FN_REFLEN]; - ulonglong event_relay_log_pos; - ulonglong future_event_relay_log_pos; - /* - The master log name for current event. Only used in parallel replication. - */ - char future_event_master_log_name[FN_REFLEN]; - bool is_parallel_exec; - /* When gtid_pending is true, we have not yet done record_gtid(). */ - bool gtid_pending; - int worker_error; - /* - Set true when we signalled that we reach the commit phase. Used to avoid - counting one event group twice. - */ - bool did_mark_start_commit; - /* Copy of flags2 from GTID event. */ - uchar gtid_ev_flags2; - enum { - GTID_DUPLICATE_NULL=0, - GTID_DUPLICATE_IGNORE=1, - GTID_DUPLICATE_OWNER=2 - }; - /* - When --gtid-ignore-duplicates, this is set to one of the above three - values: - GTID_DUPLICATE_NULL - Not using --gtid-ignore-duplicates. - GTID_DUPLICATE_IGNORE - This gtid already applied, skip the event group. - GTID_DUPLICATE_OWNER - We are the current owner of the domain, and must - apply the event group and then release the domain. - */ - uint8 gtid_ignore_duplicate_state; - - /* - Runtime state for printing a note when slave is taking - too long while processing a row event. - */ - longlong row_stmt_start_timestamp; - bool long_find_row_note_printed; - /* Needs room for "Gtid D-S-N\x00". */ - char gtid_info_buf[5+10+1+10+1+20+1]; - - /* - The timestamp, from the master, of the commit event. - Used to do delayed update of rli->last_master_timestamp, for getting - reasonable values out of Seconds_Behind_Master in SHOW SLAVE STATUS. - */ - time_t last_master_timestamp; - - /* - Information to be able to re-try an event group in case of a deadlock or - other temporary error. - */ - inuse_relaylog *relay_log; - uint64 retry_start_offset; - uint64 retry_event_count; - /* - If `speculation' is != SPECULATE_NO, then we are optimistically running - this transaction in parallel, even though it might not be safe (there may - be a conflict with a prior event group). - - In this case, a conflict can cause other errors than deadlocks (like - duplicate key for example). So in case of _any_ error, we need to roll - back and retry the event group. - */ - enum enum_speculation { - /* - This transaction was group-committed together on the master with the - other transactions with which it is replicated in parallel. - */ - SPECULATE_NO, - /* - We will optimistically try to run this transaction in parallel with - other transactions, even though it is not known to be conflict free. - If we get a conflict, we will detect it as a deadlock, roll back and - retry. - */ - SPECULATE_OPTIMISTIC, - /* - This transaction got a conflict during speculative parallel apply, or - it was marked on the master as likely to cause a conflict or unsafe to - speculate. So it will wait for the prior transaction to commit before - starting to replicate. - */ - SPECULATE_WAIT - } speculation; - enum enum_retry_killed { - RETRY_KILL_NONE = 0, - RETRY_KILL_PENDING, - RETRY_KILL_KILLED - }; - uchar killed_for_retry; - - rpl_group_info(Relay_log_info *rli_); - ~rpl_group_info(); - void reinit(Relay_log_info *rli); - - /* - Returns true if the argument event resides in the containter; - more specifically, the checking is done against the last added event. - */ - bool is_deferred_event(Log_event * ev) - { - return deferred_events_collecting ? deferred_events->is_last(ev) : false; - }; - /* The general cleanup that slave applier may need at the end of query. */ - inline void cleanup_after_query() - { - if (deferred_events) - deferred_events->rewind(); - }; - /* The general cleanup that slave applier may need at the end of session. */ - void cleanup_after_session() - { - if (deferred_events) - { - delete deferred_events; - deferred_events= NULL; - } - }; - - /** - Save pointer to Annotate_rows event and switch on the - binlog_annotate_row_events for this sql thread. - To be called when sql thread receives an Annotate_rows event. - */ - inline void set_annotate_event(Annotate_rows_log_event *event) - { - DBUG_ASSERT(m_annotate_event == NULL); - m_annotate_event= event; - this->thd->variables.binlog_annotate_row_events= 1; - } - - /** - Returns pointer to the saved Annotate_rows event or NULL if there is - no saved event. - */ - inline Annotate_rows_log_event* get_annotate_event() - { - return m_annotate_event; - } - - /** - Delete saved Annotate_rows event (if any) and switch off the - binlog_annotate_row_events for this sql thread. - To be called when sql thread has applied the last (i.e. with - STMT_END_F flag) rbr event. - */ - inline void free_annotate_event() - { - if (m_annotate_event) - { - this->thd->variables.binlog_annotate_row_events= 0; - delete m_annotate_event; - m_annotate_event= 0; - } - } - - bool get_table_data(TABLE *table_arg, table_def **tabledef_var, TABLE **conv_table_var) const - { - DBUG_ASSERT(tabledef_var && conv_table_var); - for (TABLE_LIST *ptr= tables_to_lock ; ptr != NULL ; ptr= ptr->next_global) - if (ptr->table == table_arg) - { - *tabledef_var= &static_cast(ptr)->m_tabledef; - *conv_table_var= static_cast(ptr)->m_conv_table; - DBUG_PRINT("debug", ("Fetching table data for table %s.%s:" - " tabledef: %p, conv_table: %p", - table_arg->s->db.str, table_arg->s->table_name.str, - *tabledef_var, *conv_table_var)); - return true; - } - return false; - } - - void clear_tables_to_lock(); - void cleanup_context(THD *, bool); - void slave_close_thread_tables(THD *); - void mark_start_commit_no_lock(); - void mark_start_commit(); - char *gtid_info(); - void unmark_start_commit(); - - longlong get_row_stmt_start_timestamp() - { - return row_stmt_start_timestamp; - } - - void set_row_stmt_start_timestamp() - { - if (row_stmt_start_timestamp == 0) - row_stmt_start_timestamp= microsecond_interval_timer(); - } - - void reset_row_stmt_start_timestamp() - { - row_stmt_start_timestamp= 0; - } - - void set_long_find_row_note_printed() - { - long_find_row_note_printed= true; - } - - void unset_long_find_row_note_printed() - { - long_find_row_note_printed= false; - } - - bool is_long_find_row_note_printed() - { - return long_find_row_note_printed; - } - - inline void inc_event_relay_log_pos() - { - if (!is_parallel_exec) - rli->event_relay_log_pos= future_event_relay_log_pos; - } -}; - - -/* - The class rpl_sql_thread_info is the THD::system_thread_info for an SQL - thread; this is either the driver SQL thread or a worker thread for parallel - replication. -*/ -class rpl_sql_thread_info -{ -public: - char cached_charset[6]; - Rpl_filter* rpl_filter; - - rpl_sql_thread_info(Rpl_filter *filter); - - /* - Last charset (6 bytes) seen by slave SQL thread is cached here; it helps - the thread save 3 get_charset() per Query_log_event if the charset is not - changing from event to event (common situation). - When the 6 bytes are equal to 0 is used to mean "cache is invalidated". - */ - void cached_charset_invalidate(); - bool cached_charset_compare(char *charset) const; -}; - - -extern struct rpl_slave_state *rpl_global_gtid_slave_state; -extern gtid_waiting rpl_global_gtid_waiting; - -int rpl_load_gtid_slave_state(THD *thd); -int find_gtid_slave_pos_tables(THD *thd); -int event_group_new_gtid(rpl_group_info *rgi, Gtid_log_event *gev); -void delete_or_keep_event_post_apply(rpl_group_info *rgi, - Log_event_type typ, Log_event *ev); - -#endif /* RPL_RLI_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_tblmap.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_tblmap.h deleted file mode 100644 index 63bac5e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_tblmap.h +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef TABLE_MAPPING_H -#define TABLE_MAPPING_H - -/* Forward declarations */ -#ifndef MYSQL_CLIENT -struct TABLE; -#else -class Table_map_log_event; -typedef Table_map_log_event TABLE; -void free_table_map_log_event(TABLE *table); -#endif - - -/* - CLASS table_mapping - - RESPONSIBILITIES - The table mapping is used to map table id's to table pointers - - COLLABORATION - RELAY_LOG For mapping table id:s to tables when receiving events. - */ - -/* - Guilhem to Mats: - in the table_mapping class, the memory is allocated and never freed (until - destruction). So this is a good candidate for allocating inside a MEM_ROOT: - it gives the efficient allocation in chunks (like in expand()). So I have - introduced a MEM_ROOT. - - Note that inheriting from Sql_alloc had no effect: it has effects only when - "ptr= new table_mapping" is called, and this is never called. And it would - then allocate from thd->mem_root which is a highly volatile object (reset - from example after executing each query, see dispatch_command(), it has a - free_root() at end); as the table_mapping object is supposed to live longer - than a query, it was dangerous. - A dedicated MEM_ROOT needs to be used, see below. -*/ - -#include "hash.h" /* HASH */ - -class table_mapping { - -private: - MEM_ROOT m_mem_root; - -public: - - enum enum_error { - ERR_NO_ERROR = 0, - ERR_LIMIT_EXCEEDED, - ERR_MEMORY_ALLOCATION - }; - - table_mapping(); - ~table_mapping(); - - TABLE* get_table(ulonglong table_id); - - int set_table(ulonglong table_id, TABLE* table); - int remove_table(ulonglong table_id); - void clear_tables(); - ulong count() const { return m_table_ids.records; } - -private: - /* - This is a POD (Plain Old Data). Keep it that way (we apply offsetof() to - it, which only works for PODs) - */ - struct entry { - ulonglong table_id; - union { - TABLE *table; - entry *next; - }; - }; - - entry *find_entry(ulonglong table_id) - { - return (entry *) my_hash_search(&m_table_ids, - (uchar*)&table_id, - sizeof(table_id)); - } - int expand(); - - /* - Head of the list of free entries; "free" in the sense that it's an - allocated entry free for use, NOT in the sense that it's freed - memory. - */ - entry *m_free; - - /* Correspondance between an id (a number) and a TABLE object */ - HASH m_table_ids; -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_utility.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_utility.h deleted file mode 100644 index c28e8aa..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/rpl_utility.h +++ /dev/null @@ -1,309 +0,0 @@ -/* - Copyright (c) 2006, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef RPL_UTILITY_H -#define RPL_UTILITY_H - -#ifndef __cplusplus -#error "Don't include this C++ header file from a non-C++ file!" -#endif - -#include "sql_priv.h" -#include "m_string.h" /* bzero, memcpy */ -#ifdef MYSQL_SERVER -#include "table.h" /* TABLE_LIST */ -#endif -#include "mysql_com.h" - -class Relay_log_info; -class Log_event; -struct rpl_group_info; - -/** - A table definition from the master. - - The responsibilities of this class is: - - Extract and decode table definition data from the table map event - - Check if table definition in table map is compatible with table - definition on slave - */ - -class table_def -{ -public: - /** - Constructor. - - @param types Array of types, each stored as a byte - @param size Number of elements in array 'types' - @param field_metadata Array of extra information about fields - @param metadata_size Size of the field_metadata array - @param null_bitmap The bitmap of fields that can be null - */ - table_def(unsigned char *types, ulong size, uchar *field_metadata, - int metadata_size, uchar *null_bitmap, uint16 flags); - - ~table_def(); - - /** - Return the number of fields there is type data for. - - @return The number of fields that there is type data for. - */ - ulong size() const { return m_size; } - - - /** - Returns internal binlog type code for one field, - without translation to real types. - */ - enum_field_types binlog_type(ulong index) const - { - return static_cast(m_type[index]); - } - /* - Return a representation of the type data for one field. - - @param index Field index to return data for - - @return Will return a representation of the type data for field - index. Currently, only the type identifier is - returned. - */ - enum_field_types type(ulong index) const - { - DBUG_ASSERT(index < m_size); - /* - If the source type is MYSQL_TYPE_STRING, it can in reality be - either MYSQL_TYPE_STRING, MYSQL_TYPE_ENUM, or MYSQL_TYPE_SET, so - we might need to modify the type to get the real type. - */ - enum_field_types source_type= binlog_type(index); - uint16 source_metadata= m_field_metadata[index]; - switch (source_type) - { - case MYSQL_TYPE_STRING: - { - int real_type= source_metadata >> 8; - if (real_type == MYSQL_TYPE_ENUM || real_type == MYSQL_TYPE_SET) - source_type= static_cast(real_type); - break; - } - - /* - This type has not been used since before row-based replication, - so we can safely assume that it really is MYSQL_TYPE_NEWDATE. - */ - case MYSQL_TYPE_DATE: - source_type= MYSQL_TYPE_NEWDATE; - break; - - default: - /* Do nothing */ - break; - } - - return source_type; - } -#ifdef MYSQL_SERVER - const Type_handler *field_type_handler(uint index) const; -#endif - - /* - This function allows callers to get the extra field data from the - table map for a given field. If there is no metadata for that field - or there is no extra metadata at all, the function returns 0. - - The function returns the value for the field metadata for column at - position indicated by index. As mentioned, if the field was a type - that stores field metadata, that value is returned else zero (0) is - returned. This method is used in the unpack() methods of the - corresponding fields to properly extract the data from the binary log - in the event that the master's field is smaller than the slave. - */ - uint16 field_metadata(uint index) const - { - DBUG_ASSERT(index < m_size); - if (m_field_metadata_size) - return m_field_metadata[index]; - else - return 0; - } - - /* - This function returns whether the field on the master can be null. - This value is derived from field->maybe_null(). - */ - my_bool maybe_null(uint index) const - { - DBUG_ASSERT(index < m_size); - return ((m_null_bits[(index / 8)] & - (1 << (index % 8))) == (1 << (index %8))); - } - - /* - This function returns the field size in raw bytes based on the type - and the encoded field data from the master's raw data. This method can - be used for situations where the slave needs to skip a column (e.g., - WL#3915) or needs to advance the pointer for the fields in the raw - data from the master to a specific column. - */ - uint32 calc_field_size(uint col, uchar *master_data) const; - - /** - Decide if the table definition is compatible with a table. - - Compare the definition with a table to see if it is compatible - with it. - - A table definition is compatible with a table if: - - The columns types of the table definition is a (not - necessarily proper) prefix of the column type of the table. - - - The other way around. - - - Each column on the master that also exists on the slave can be - converted according to the current settings of @c - SLAVE_TYPE_CONVERSIONS. - - @param thd - @param rli Pointer to relay log info - @param table Pointer to table to compare with. - - @param[out] tmp_table_var Pointer to temporary table for holding - conversion table. - - @retval 1 if the table definition is not compatible with @c table - @retval 0 if the table definition is compatible with @c table - */ -#ifndef MYSQL_CLIENT - bool compatible_with(THD *thd, rpl_group_info *rgi, TABLE *table, - TABLE **conv_table_var) const; - - /** - Create a virtual in-memory temporary table structure. - - The table structure has records and field array so that a row can - be unpacked into the record for further processing. - - In the virtual table, each field that requires conversion will - have a non-NULL value, while fields that do not require - conversion will have a NULL value. - - Some information that is missing in the events, such as the - character set for string types, are taken from the table that the - field is going to be pushed into, so the target table that the data - eventually need to be pushed into need to be supplied. - - @param thd Thread to allocate memory from. - @param rli Relay log info structure, for error reporting. - @param target_table Target table for fields. - - @return A pointer to a temporary table with memory allocated in the - thread's memroot, NULL if the table could not be created - */ - TABLE *create_conversion_table(THD *thd, rpl_group_info *rgi, - TABLE *target_table) const; -#endif - - -private: - ulong m_size; // Number of elements in the types array - unsigned char *m_type; // Array of type descriptors - uint m_field_metadata_size; - uint16 *m_field_metadata; - uchar *m_null_bits; - uint16 m_flags; // Table flags - uchar *m_memory; -}; - - -#ifndef MYSQL_CLIENT -/** - Extend the normal table list with a few new fields needed by the - slave thread, but nowhere else. - */ -struct RPL_TABLE_LIST - : public TABLE_LIST -{ - bool m_tabledef_valid; - table_def m_tabledef; - TABLE *m_conv_table; - bool master_had_triggers; -}; - - -/* Anonymous namespace for template functions/classes */ -CPP_UNNAMED_NS_START - - /* - Smart pointer that will automatically call my_afree (a macro) when - the pointer goes out of scope. This is used so that I do not have - to remember to call my_afree() before each return. There is no - overhead associated with this, since all functions are inline. - - I (Matz) would prefer to use the free function as a template - parameter, but that is not possible when the "function" is a - macro. - */ - template - class auto_afree_ptr - { - Obj* m_ptr; - public: - auto_afree_ptr(Obj* ptr) : m_ptr(ptr) { } - ~auto_afree_ptr() { if (m_ptr) my_afree(m_ptr); } - void assign(Obj* ptr) { - /* Only to be called if it hasn't been given a value before. */ - DBUG_ASSERT(m_ptr == NULL); - m_ptr= ptr; - } - Obj* get() { return m_ptr; } - }; - -CPP_UNNAMED_NS_END - -class Deferred_log_events -{ -private: - DYNAMIC_ARRAY array; - Log_event *last_added; - -public: - Deferred_log_events(Relay_log_info *rli); - ~Deferred_log_events(); - /* queue for exection at Query-log-event time prior the Query */ - int add(Log_event *ev); - bool is_empty(); - bool execute(struct rpl_group_info *rgi); - void rewind(); - bool is_last(Log_event *ev) { return ev == last_added; }; -}; - -#endif - -// NB. number of printed bit values is limited to sizeof(buf) - 1 -#define DBUG_PRINT_BITSET(N,FRM,BS) \ - do { \ - char buf[256]; \ - uint i; \ - for (i = 0 ; i < MY_MIN(sizeof(buf) - 1, (BS)->n_bits) ; i++) \ - buf[i] = bitmap_is_set((BS), i) ? '1' : '0'; \ - buf[i] = '\0'; \ - DBUG_PRINT((N), ((FRM), buf)); \ - } while (0) - -#endif /* RPL_UTILITY_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/scheduler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/scheduler.h deleted file mode 100644 index ebf8d6e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/scheduler.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef SCHEDULER_INCLUDED -#define SCHEDULER_INCLUDED - -/* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2012, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Classes for the thread scheduler -*/ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface -#endif - -class THD; - -/* Functions used when manipulating threads */ - -struct scheduler_functions -{ - uint max_threads; - Atomic_counter *connection_count; - ulong *max_connections; - bool (*init)(void); - void (*add_connection)(CONNECT *connect); - void (*thd_wait_begin)(THD *thd, int wait_type); - void (*thd_wait_end)(THD *thd); - void (*post_kill_notification)(THD *thd); - void (*end)(void); -}; - - -/** - Scheduler types enumeration. - - The default of --thread-handling is the first one in the - thread_handling_names array, this array has to be consistent with - the order in this array, so to change default one has to change the - first entry in this enum and the first entry in the - thread_handling_names array. - - @note The last entry of the enumeration is also used to mark the - thread handling as dynamic. In this case the name of the thread - handling is fetched from the name of the plugin that implements it. -*/ -enum scheduler_types -{ - /* - The default of --thread-handling is the first one in the - thread_handling_names array, this array has to be consistent with - the order in this array, so to change default one has to change - the first entry in this enum and the first entry in the - thread_handling_names array. - */ - SCHEDULER_ONE_THREAD_PER_CONNECTION=0, - SCHEDULER_NO_THREADS, - SCHEDULER_TYPES_COUNT -}; - -void one_thread_per_connection_scheduler(scheduler_functions *func, - ulong *arg_max_connections, Atomic_counter *arg_connection_count); -void one_thread_scheduler(scheduler_functions *func); - -extern void scheduler_init(); -extern void post_kill_notification(THD *); -/* - To be used for pool-of-threads (implemeneted differently on various OSs) -*/ -struct thd_scheduler -{ -public: - void *data; /* scheduler-specific data structure */ -}; - -#ifdef HAVE_POOL_OF_THREADS -void pool_of_threads_scheduler(scheduler_functions* func, - ulong *arg_max_connections, - Atomic_counter *arg_connection_count); -#else -#define pool_of_threads_scheduler(A,B,C) \ - one_thread_per_connection_scheduler(A, B, C) -#endif /*HAVE_POOL_OF_THREADS*/ - -#endif /* SCHEDULER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/scope.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/scope.h deleted file mode 100644 index b9e2e96..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/scope.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2020, MariaDB - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -#pragma once - -#include -#include - -namespace detail -{ - -template class scope_exit -{ -public: - template - explicit scope_exit(F &&f) : function_(std::forward(f)) - { - } - - scope_exit(scope_exit &&rhs) - : function_(std::move(rhs.function_)), engaged_(rhs.engaged_) - { - rhs.release(); - } - - scope_exit(const scope_exit &)= delete; - scope_exit &operator=(scope_exit &&)= delete; - scope_exit &operator=(const scope_exit &)= delete; - - void release() { engaged_= false; } - - ~scope_exit() - { - if (engaged_) - function_(); - } - -private: - Callable function_; - bool engaged_= true; -}; - -} // end namespace detail - -template -detail::scope_exit::type> -make_scope_exit(Callable &&f) -{ - return detail::scope_exit::type>( - std::forward(f)); -} diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/select_handler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/select_handler.h deleted file mode 100644 index 5cc6323..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/select_handler.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright (c) 2018, 2019 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef SELECT_HANDLER_INCLUDED -#define SELECT_HANDLER_INCLUDED - -#include "mariadb.h" -#include "sql_priv.h" - -/** - @class select_handler - - This interface class is to be used for execution of select queries - by foreign engines -*/ - -class select_handler -{ - public: - THD *thd; - handlerton *ht; - - SELECT_LEX *select; // Select to be excuted - - /* - Temporary table where all results should be stored in record[0] - The table has a field for every item from the select_lex::item_list. - The table is actually never filled. Only its record buffer is used. - */ - TABLE *table; - List result_columns; - - bool is_analyze; - - bool send_result_set_metadata(); - bool send_data(); - - select_handler(THD *thd_arg, handlerton *ht_arg); - - virtual ~select_handler(); - - int execute(); - - virtual bool prepare(); - - static TABLE *create_tmp_table(THD *thd, SELECT_LEX *sel); - -protected: - /* - Functions to scan the select result set. - All these returns 0 if ok, error code in case of error. - */ - - /* Initialize the process of producing rows of result set */ - virtual int init_scan() = 0; - - /* - Put the next produced row of the result set in table->record[0] - and return 0. Return HA_ERR_END_OF_FILE if there are no more rows, - return other error number in case of fatal error. - */ - virtual int next_row() = 0; - - /* Finish scanning */ - virtual int end_scan() = 0; - - /* Report errors */ - virtual void print_error(int error, myf errflag); - - bool send_eof(); -}; - -#endif /* SELECT_HANDLER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync.h deleted file mode 100644 index 44f2366..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync.h +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright (C) 2007 Google Inc. - Copyright (C) 2008 MySQL AB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef SEMISYNC_H -#define SEMISYNC_H - -#include "mysqld.h" -#include "log_event.h" -#include "replication.h" - -/** - This class is used to trace function calls and other process - information -*/ -class Trace { -public: - static const unsigned long k_trace_function; - static const unsigned long k_trace_general; - static const unsigned long k_trace_detail; - static const unsigned long k_trace_net_wait; - - unsigned long m_trace_level; /* the level for tracing */ - - Trace() - :m_trace_level(0L) - {} - Trace(unsigned long trace_level) - :m_trace_level(trace_level) - {} -}; - -/** - Base class for semi-sync master and slave classes -*/ -class Repl_semi_sync_base - :public Trace { -public: - static const unsigned char k_sync_header[2]; /* three byte packet header */ - - /* Constants in network packet header. */ - static const unsigned char k_packet_magic_num; - static const unsigned char k_packet_flag_sync; -}; - -/* The layout of a semisync slave reply packet: - 1 byte for the magic num - 8 bytes for the binlog positon - n bytes for the binlog filename, terminated with a '\0' -*/ -#define REPLY_MAGIC_NUM_LEN 1 -#define REPLY_BINLOG_POS_LEN 8 -#define REPLY_BINLOG_NAME_LEN (FN_REFLEN + 1) -#define REPLY_MAGIC_NUM_OFFSET 0 -#define REPLY_BINLOG_POS_OFFSET (REPLY_MAGIC_NUM_OFFSET + REPLY_MAGIC_NUM_LEN) -#define REPLY_BINLOG_NAME_OFFSET (REPLY_BINLOG_POS_OFFSET + REPLY_BINLOG_POS_LEN) -#define REPLY_MESSAGE_MAX_LENGTH \ - (REPLY_MAGIC_NUM_LEN + REPLY_BINLOG_POS_LEN + REPLY_BINLOG_NAME_LEN) - -#endif /* SEMISYNC_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_master.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_master.h deleted file mode 100644 index 9f0acf5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_master.h +++ /dev/null @@ -1,673 +0,0 @@ -/* Copyright (C) 2007 Google Inc. - Copyright (c) 2008 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef SEMISYNC_MASTER_H -#define SEMISYNC_MASTER_H - -#include "semisync.h" -#include "semisync_master_ack_receiver.h" - -#ifdef HAVE_PSI_INTERFACE -extern PSI_mutex_key key_LOCK_rpl_semi_sync_master_enabled; -extern PSI_mutex_key key_LOCK_binlog; -extern PSI_cond_key key_COND_binlog_send; -#endif - -struct Tranx_node { - char log_name[FN_REFLEN]; - my_off_t log_pos; - struct Tranx_node *next; /* the next node in the sorted list */ - struct Tranx_node *hash_next; /* the next node during hash collision */ -}; - -/** - @class Tranx_node_allocator - - This class provides memory allocating and freeing methods for - Tranx_node. The main target is performance. - - @section ALLOCATE How to allocate a node - The pointer of the first node after 'last_node' in current_block is - returned. current_block will move to the next free Block when all nodes of - it are in use. A new Block is allocated and is put into the rear of the - Block link table if no Block is free. - - The list starts up empty (ie, there is no allocated Block). - - After some nodes are freed, there probably are some free nodes before - the sequence of the allocated nodes, but we do not reuse it. It is better - to keep the allocated nodes are in the sequence, for it is more efficient - for allocating and freeing Tranx_node. - - @section FREENODE How to free nodes - There are two methods for freeing nodes. They are free_all_nodes and - free_nodes_before. - - 'A Block is free' means all of its nodes are free. - @subsection free_nodes_before - As all allocated nodes are in the sequence, 'Before one node' means all - nodes before given node in the same Block and all Blocks before the Block - which containing the given node. As such, all Blocks before the given one - ('node') are free Block and moved into the rear of the Block link table. - The Block containing the given 'node', however, is not. For at least the - given 'node' is still in use. This will waste at most one Block, but it is - more efficient. - */ -#define BLOCK_TRANX_NODES 16 -class Tranx_node_allocator -{ -public: - /** - @param reserved_nodes - The number of reserved Tranx_nodes. It is used to set 'reserved_blocks' - which can contain at least 'reserved_nodes' number of Tranx_nodes. When - freeing memory, we will reserve at least reserved_blocks of Blocks not - freed. - */ - Tranx_node_allocator(uint reserved_nodes) : - reserved_blocks(reserved_nodes/BLOCK_TRANX_NODES + - (reserved_nodes%BLOCK_TRANX_NODES > 1 ? 2 : 1)), - first_block(NULL), last_block(NULL), - current_block(NULL), last_node(-1), block_num(0) {} - - ~Tranx_node_allocator() - { - Block *block= first_block; - while (block != NULL) - { - Block *next= block->next; - free_block(block); - block= next; - } - } - - /** - The pointer of the first node after 'last_node' in current_block is - returned. current_block will move to the next free Block when all nodes of - it are in use. A new Block is allocated and is put into the rear of the - Block link table if no Block is free. - - @return Return a Tranx_node *, or NULL if an error occurred. - */ - Tranx_node *allocate_node() - { - Tranx_node *trx_node; - Block *block= current_block; - - if (last_node == BLOCK_TRANX_NODES-1) - { - current_block= current_block->next; - last_node= -1; - } - - if (current_block == NULL && allocate_block()) - { - current_block= block; - if (current_block) - last_node= BLOCK_TRANX_NODES-1; - return NULL; - } - - trx_node= &(current_block->nodes[++last_node]); - trx_node->log_name[0] = '\0'; - trx_node->log_pos= 0; - trx_node->next= 0; - trx_node->hash_next= 0; - return trx_node; - } - - /** - All nodes are freed. - - @return Return 0, or 1 if an error occurred. - */ - int free_all_nodes() - { - current_block= first_block; - last_node= -1; - free_blocks(); - return 0; - } - - /** - All Blocks before the given 'node' are free Block and moved into the rear - of the Block link table. - - @param node All nodes before 'node' will be freed - - @return Return 0, or 1 if an error occurred. - */ - int free_nodes_before(Tranx_node* node) - { - Block *block; - Block *prev_block= NULL; - - block= first_block; - while (block != current_block->next) - { - /* Find the Block containing the given node */ - if (&(block->nodes[0]) <= node && &(block->nodes[BLOCK_TRANX_NODES]) >= node) - { - /* All Blocks before the given node are put into the rear */ - if (first_block != block) - { - last_block->next= first_block; - first_block= block; - last_block= prev_block; - last_block->next= NULL; - free_blocks(); - } - return 0; - } - prev_block= block; - block= block->next; - } - - /* Node does not find should never happen */ - DBUG_ASSERT(0); - return 1; - } - -private: - uint reserved_blocks; - - /** - A sequence memory which contains BLOCK_TRANX_NODES Tranx_nodes. - - BLOCK_TRANX_NODES The number of Tranx_nodes which are in a Block. - - next Every Block has a 'next' pointer which points to the next Block. - These linking Blocks constitute a Block link table. - */ - struct Block { - Block *next; - Tranx_node nodes[BLOCK_TRANX_NODES]; - }; - - /** - The 'first_block' is the head of the Block link table; - */ - Block *first_block; - /** - The 'last_block' is the rear of the Block link table; - */ - Block *last_block; - - /** - current_block always points the Block in the Block link table in - which the last allocated node is. The Blocks before it are all in use - and the Blocks after it are all free. - */ - Block *current_block; - - /** - It always points to the last node which has been allocated in the - current_block. - */ - int last_node; - - /** - How many Blocks are in the Block link table. - */ - uint block_num; - - /** - Allocate a block and then assign it to current_block. - */ - int allocate_block() - { - Block *block= (Block *)my_malloc(PSI_INSTRUMENT_ME, sizeof(Block), MYF(0)); - if (block) - { - block->next= NULL; - - if (first_block == NULL) - first_block= block; - else - last_block->next= block; - - /* New Block is always put into the rear */ - last_block= block; - /* New Block is always the current_block */ - current_block= block; - ++block_num; - return 0; - } - return 1; - } - - /** - Free a given Block. - @param block The Block will be freed. - */ - void free_block(Block *block) - { - my_free(block); - --block_num; - } - - - /** - If there are some free Blocks and the total number of the Blocks in the - Block link table is larger than the 'reserved_blocks', Some free Blocks - will be freed until the total number of the Blocks is equal to the - 'reserved_blocks' or there is only one free Block behind the - 'current_block'. - */ - void free_blocks() - { - if (current_block == NULL || current_block->next == NULL) - return; - - /* One free Block is always kept behind the current block */ - Block *block= current_block->next->next; - while (block_num > reserved_blocks && block != NULL) - { - Block *next= block->next; - free_block(block); - block= next; - } - current_block->next->next= block; - if (block == NULL) - last_block= current_block->next; - } -}; - -/** - This class manages memory for active transaction list. - - We record each active transaction with a Tranx_node, each session - can have only one open transaction. Because of EVENT, the total - active transaction nodes can exceed the maximum allowed - connections. -*/ -class Active_tranx - :public Trace { -private: - - Tranx_node_allocator m_allocator; - /* These two record the active transaction list in sort order. */ - Tranx_node *m_trx_front, *m_trx_rear; - - Tranx_node **m_trx_htb; /* A hash table on active transactions. */ - - int m_num_entries; /* maximum hash table entries */ - mysql_mutex_t *m_lock; /* mutex lock */ - - inline void assert_lock_owner(); - - inline unsigned int calc_hash(const unsigned char *key, size_t length); - unsigned int get_hash_value(const char *log_file_name, my_off_t log_file_pos); - - int compare(const char *log_file_name1, my_off_t log_file_pos1, - const Tranx_node *node2) { - return compare(log_file_name1, log_file_pos1, - node2->log_name, node2->log_pos); - } - int compare(const Tranx_node *node1, - const char *log_file_name2, my_off_t log_file_pos2) { - return compare(node1->log_name, node1->log_pos, - log_file_name2, log_file_pos2); - } - int compare(const Tranx_node *node1, const Tranx_node *node2) { - return compare(node1->log_name, node1->log_pos, - node2->log_name, node2->log_pos); - } - -public: - Active_tranx(mysql_mutex_t *lock, unsigned long trace_level); - ~Active_tranx(); - - /* Insert an active transaction node with the specified position. - * - * Return: - * 0: success; non-zero: error - */ - int insert_tranx_node(const char *log_file_name, my_off_t log_file_pos); - - /* Clear the active transaction nodes until(inclusive) the specified - * position. - * If log_file_name is NULL, everything will be cleared: the sorted - * list and the hash table will be reset to empty. - */ - void clear_active_tranx_nodes(const char *log_file_name, - my_off_t log_file_pos); - - /* Given a position, check to see whether the position is an active - * transaction's ending position by probing the hash table. - */ - bool is_tranx_end_pos(const char *log_file_name, my_off_t log_file_pos); - - /* Given two binlog positions, compare which one is bigger based on - * (file_name, file_position). - */ - static int compare(const char *log_file_name1, my_off_t log_file_pos1, - const char *log_file_name2, my_off_t log_file_pos2); - -}; - -/** - The extension class for the master of semi-synchronous replication -*/ -class Repl_semi_sync_master - :public Repl_semi_sync_base { - Active_tranx *m_active_tranxs; /* active transaction list: the list will - be cleared when semi-sync switches off. */ - - /* True when init_object has been called */ - bool m_init_done; - - /* This cond variable is signaled when enough binlog has been sent to slave, - * so that a waiting trx can return the 'ok' to the client for a commit. - */ - mysql_cond_t COND_binlog_send; - - /* Mutex that protects the following state variables and the active - * transaction list. - * Under no cirumstances we can acquire mysql_bin_log.LOCK_log if we are - * already holding m_LOCK_binlog because it can cause deadlocks. - */ - mysql_mutex_t LOCK_binlog; - - /* This is set to true when m_reply_file_name contains meaningful data. */ - bool m_reply_file_name_inited; - - /* The binlog name up to which we have received replies from any slaves. */ - char m_reply_file_name[FN_REFLEN]; - - /* The position in that file up to which we have the reply from any slaves. */ - my_off_t m_reply_file_pos; - - /* This is set to true when we know the 'smallest' wait position. */ - bool m_wait_file_name_inited; - - /* NULL, or the 'smallest' filename that a transaction is waiting for - * slave replies. - */ - char m_wait_file_name[FN_REFLEN]; - - /* The smallest position in that file that a trx is waiting for: the trx - * can proceed and send an 'ok' to the client when the master has got the - * reply from the slave indicating that it already got the binlog events. - */ - my_off_t m_wait_file_pos; - - /* This is set to true when we know the 'largest' transaction commit - * position in the binlog file. - * We always maintain the position no matter whether semi-sync is switched - * on switched off. When a transaction wait timeout occurs, semi-sync will - * switch off. Binlog-dump thread can use the three fields to detect when - * slaves catch up on replication so that semi-sync can switch on again. - */ - bool m_commit_file_name_inited; - - /* The 'largest' binlog filename that a commit transaction is seeing. */ - char m_commit_file_name[FN_REFLEN]; - - /* The 'largest' position in that file that a commit transaction is seeing. */ - my_off_t m_commit_file_pos; - - /* All global variables which can be set by parameters. */ - volatile bool m_master_enabled; /* semi-sync is enabled on the master */ - unsigned long m_wait_timeout; /* timeout period(ms) during tranx wait */ - - bool m_state; /* whether semi-sync is switched */ - - /*Waiting for ACK before/after innodb commit*/ - ulong m_wait_point; - - void lock(); - void unlock(); - void cond_broadcast(); - int cond_timewait(struct timespec *wait_time); - - /* Is semi-sync replication on? */ - bool is_on() { - return (m_state); - } - - void set_master_enabled(bool enabled) { - m_master_enabled = enabled; - } - - /* Switch semi-sync off because of timeout in transaction waiting. */ - void switch_off(); - - /* Switch semi-sync on when slaves catch up. */ - int try_switch_on(int server_id, - const char *log_file_name, my_off_t log_file_pos); - - public: - Repl_semi_sync_master(); - ~Repl_semi_sync_master() {} - - void cleanup(); - - bool get_master_enabled() { - return m_master_enabled; - } - void set_trace_level(unsigned long trace_level) { - m_trace_level = trace_level; - if (m_active_tranxs) - m_active_tranxs->m_trace_level = trace_level; - } - - /* Set the transaction wait timeout period, in milliseconds. */ - void set_wait_timeout(unsigned long wait_timeout) { - m_wait_timeout = wait_timeout; - } - - /*set the ACK point, after binlog sync or after transaction commit*/ - void set_wait_point(unsigned long ack_point) - { - m_wait_point = ack_point; - } - - ulong wait_point() //no cover line - { - return m_wait_point; //no cover line - } - - /* Initialize this class after MySQL parameters are initialized. this - * function should be called once at bootstrap time. - */ - int init_object(); - - /* Enable the object to enable semi-sync replication inside the master. */ - int enable_master(); - - /* Disable the object to disable semi-sync replication inside the master. */ - void disable_master(); - - /* Add a semi-sync replication slave */ - void add_slave(); - - /* Remove a semi-sync replication slave */ - void remove_slave(); - - /* It parses a reply packet and call report_reply_binlog to handle it. */ - int report_reply_packet(uint32 server_id, const uchar *packet, - ulong packet_len); - - /* In semi-sync replication, reports up to which binlog position we have - * received replies from the slave indicating that it already get the events. - * - * Input: - * server_id - (IN) master server id number - * log_file_name - (IN) binlog file name - * end_offset - (IN) the offset in the binlog file up to which we have - * the replies from the slave - * - * Return: - * 0: success; non-zero: error - */ - int report_reply_binlog(uint32 server_id, - const char* log_file_name, - my_off_t end_offset); - - /* Commit a transaction in the final step. This function is called from - * InnoDB before returning from the low commit. If semi-sync is switch on, - * the function will wait to see whether binlog-dump thread get the reply for - * the events of the transaction. Remember that this is not a direct wait, - * instead, it waits to see whether the binlog-dump thread has reached the - * point. If the wait times out, semi-sync status will be switched off and - * all other transaction would not wait either. - * - * Input: (the transaction events' ending binlog position) - * trx_wait_binlog_name - (IN) ending position's file name - * trx_wait_binlog_pos - (IN) ending position's file offset - * - * Return: - * 0: success; non-zero: error - */ - int commit_trx(const char* trx_wait_binlog_name, - my_off_t trx_wait_binlog_pos); - - /*Wait for ACK after writing/sync binlog to file*/ - int wait_after_sync(const char* log_file, my_off_t log_pos); - - /*Wait for ACK after commting the transaction*/ - int wait_after_commit(THD* thd, bool all); - - /*Wait after the transaction is rollback*/ - int wait_after_rollback(THD *thd, bool all); - /*Store the current binlog position in m_active_tranxs. This position should - * be acked by slave*/ - int report_binlog_update(THD *thd, const char *log_file,my_off_t log_pos); - - int dump_start(THD* thd, - const char *log_file, - my_off_t log_pos); - - void dump_end(THD* thd); - - /* Reserve space in the replication event packet header: - * . slave semi-sync off: 1 byte - (0) - * . slave semi-sync on: 3 byte - (0, 0xef, 0/1} - * - * Input: - * packet - (IN) the header buffer - * - * Return: - * size of the bytes reserved for header - */ - int reserve_sync_header(String* packet); - - /* Update the sync bit in the packet header to indicate to the slave whether - * the master will wait for the reply of the event. If semi-sync is switched - * off and we detect that the slave is catching up, we switch semi-sync on. - * - * Input: - * THD - (IN) current dump thread - * packet - (IN) the packet containing the replication event - * log_file_name - (IN) the event ending position's file name - * log_file_pos - (IN) the event ending position's file offset - * need_sync - (IN) identify if flush_net is needed to call. - * server_id - (IN) master server id number - * - * Return: - * 0: success; non-zero: error - */ - int update_sync_header(THD* thd, unsigned char *packet, - const char *log_file_name, - my_off_t log_file_pos, - bool* need_sync); - - /* Called when a transaction finished writing binlog events. - * . update the 'largest' transactions' binlog event position - * . insert the ending position in the active transaction list if - * semi-sync is on - * - * Input: (the transaction events' ending binlog position) - * log_file_name - (IN) transaction ending position's file name - * log_file_pos - (IN) transaction ending position's file offset - * - * Return: - * 0: success; non-zero: error - */ - int write_tranx_in_binlog(const char* log_file_name, my_off_t log_file_pos); - - /* Read the slave's reply so that we know how much progress the slave makes - * on receive replication events. - */ - int flush_net(THD* thd, const char *event_buf); - - /* Export internal statistics for semi-sync replication. */ - void set_export_stats(); - - /* 'reset master' command is issued from the user and semi-sync need to - * go off for that. - */ - int after_reset_master(); - - /*called before reset master*/ - int before_reset_master(); - - void check_and_switch(); - - mysql_mutex_t LOCK_rpl_semi_sync_master_enabled; -}; - -enum rpl_semi_sync_master_wait_point_t { - SEMI_SYNC_MASTER_WAIT_POINT_AFTER_BINLOG_SYNC, - SEMI_SYNC_MASTER_WAIT_POINT_AFTER_STORAGE_COMMIT, -}; - -extern Repl_semi_sync_master repl_semisync_master; -extern Ack_receiver ack_receiver; - -/* System and status variables for the master component */ -extern my_bool rpl_semi_sync_master_enabled; -extern my_bool rpl_semi_sync_master_status; -extern ulong rpl_semi_sync_master_wait_point; -extern ulong rpl_semi_sync_master_clients; -extern ulong rpl_semi_sync_master_timeout; -extern ulong rpl_semi_sync_master_trace_level; -extern ulong rpl_semi_sync_master_yes_transactions; -extern ulong rpl_semi_sync_master_no_transactions; -extern ulong rpl_semi_sync_master_off_times; -extern ulong rpl_semi_sync_master_wait_timeouts; -extern ulong rpl_semi_sync_master_timefunc_fails; -extern ulong rpl_semi_sync_master_num_timeouts; -extern ulong rpl_semi_sync_master_wait_sessions; -extern ulong rpl_semi_sync_master_wait_pos_backtraverse; -extern ulong rpl_semi_sync_master_avg_trx_wait_time; -extern ulong rpl_semi_sync_master_avg_net_wait_time; -extern ulonglong rpl_semi_sync_master_net_wait_num; -extern ulonglong rpl_semi_sync_master_trx_wait_num; -extern ulonglong rpl_semi_sync_master_net_wait_time; -extern ulonglong rpl_semi_sync_master_trx_wait_time; -extern unsigned long long rpl_semi_sync_master_request_ack; -extern unsigned long long rpl_semi_sync_master_get_ack; - -/* - This indicates whether we should keep waiting if no semi-sync slave - is available. - 0 : stop waiting if detected no avaialable semi-sync slave. - 1 (default) : keep waiting until timeout even no available semi-sync slave. -*/ -extern char rpl_semi_sync_master_wait_no_slave; -extern Repl_semi_sync_master repl_semisync_master; - -extern PSI_stage_info stage_waiting_for_semi_sync_ack_from_slave; -extern PSI_stage_info stage_reading_semi_sync_ack; -extern PSI_stage_info stage_waiting_for_semi_sync_slave; - -void semi_sync_master_deinit(); - -#endif /* SEMISYNC_MASTER_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_master_ack_receiver.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_master_ack_receiver.h deleted file mode 100644 index 138f7b5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_master_ack_receiver.h +++ /dev/null @@ -1,240 +0,0 @@ -/* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef SEMISYNC_MASTER_ACK_RECEIVER_DEFINED -#define SEMISYNC_MASTER_ACK_RECEIVER_DEFINED - -#include "my_global.h" -#include "my_pthread.h" -#include "sql_class.h" -#include "semisync.h" -#include - -struct Slave :public ilink -{ - THD *thd; - Vio vio; -#ifdef HAVE_POLL - uint m_fds_index; -#endif - my_socket sock_fd() const { return vio.mysql_socket.fd; } - uint server_id() const { return thd->variables.server_id; } -}; - -typedef I_List Slave_ilist; -typedef I_List_iterator Slave_ilist_iterator; - -/** - Ack_receiver is responsible to control ack receive thread and maintain - slave information used by ack receive thread. - - There are mainly four operations on ack receive thread: - start: start ack receive thread - stop: stop ack receive thread - add_slave: maintain a new semisync slave's information - remove_slave: remove a semisync slave's information - */ -class Ack_receiver : public Repl_semi_sync_base -{ -public: - Ack_receiver(); - ~Ack_receiver() {} - void cleanup(); - /** - Notify ack receiver to receive acks on the dump session. - - It adds the given dump thread into the slave list and wakes - up ack thread if it is waiting for any slave coming. - - @param[in] thd THD of a dump thread. - - @return it return false if succeeds, otherwise true is returned. - */ - bool add_slave(THD *thd); - - /** - Notify ack receiver not to receive ack on the dump session. - - it removes the given dump thread from slave list. - - @param[in] thd THD of a dump thread. - */ - void remove_slave(THD *thd); - - /** - Start ack receive thread - - @return it return false if succeeds, otherwise true is returned. - */ - bool start(); - - /** - Stop ack receive thread - */ - void stop(); - - /** - The core of ack receive thread. - - It monitors all slaves' sockets and receives acks when they come. - */ - void run(); - - void set_trace_level(unsigned long trace_level) - { - m_trace_level= trace_level; - } -private: - enum status {ST_UP, ST_DOWN, ST_STOPPING}; - uint8 m_status; - /* - Protect m_status, m_slaves_changed and m_slaves. ack thread and other - session may access the variables at the same time. - */ - mysql_mutex_t m_mutex; - mysql_cond_t m_cond; - /* If slave list is updated(add or remove). */ - bool m_slaves_changed; - - Slave_ilist m_slaves; - pthread_t m_pid; - -/* Declare them private, so no one can copy the object. */ - Ack_receiver(const Ack_receiver &ack_receiver); - Ack_receiver& operator=(const Ack_receiver &ack_receiver); - - void set_stage_info(const PSI_stage_info &stage); - void wait_for_slave_connection(); -}; - - -#ifdef HAVE_POLL -#include -#include - -class Poll_socket_listener -{ -public: - Poll_socket_listener(const Slave_ilist &slaves) - :m_slaves(slaves) - { - } - - bool listen_on_sockets() - { - return poll(m_fds.data(), m_fds.size(), 1000 /*1 Second timeout*/); - } - - bool is_socket_active(const Slave *slave) - { - return m_fds[slave->m_fds_index].revents & POLLIN; - } - - void clear_socket_info(const Slave *slave) - { - m_fds[slave->m_fds_index].fd= -1; - m_fds[slave->m_fds_index].events= 0; - } - - uint init_slave_sockets() - { - Slave_ilist_iterator it(const_cast(m_slaves)); - Slave *slave; - uint fds_index= 0; - - m_fds.clear(); - while ((slave= it++)) - { - pollfd poll_fd; - poll_fd.fd= slave->sock_fd(); - poll_fd.events= POLLIN; - m_fds.push_back(poll_fd); - slave->m_fds_index= fds_index++; - } - return fds_index; - } - -private: - const Slave_ilist &m_slaves; - std::vector m_fds; -}; - -#else //NO POLL - -class Select_socket_listener -{ -public: - Select_socket_listener(const Slave_ilist &slaves) - :m_slaves(slaves), m_max_fd(INVALID_SOCKET) - { - } - - bool listen_on_sockets() - { - /* Reinitialze the fds with active fds before calling select */ - m_fds= m_init_fds; - struct timeval tv= {1,0}; - /* select requires max fd + 1 for the first argument */ - return select((int) m_max_fd+1, &m_fds, NULL, NULL, &tv); - } - - bool is_socket_active(const Slave *slave) - { - return FD_ISSET(slave->sock_fd(), &m_fds); - } - - void clear_socket_info(const Slave *slave) - { - FD_CLR(slave->sock_fd(), &m_init_fds); - } - - uint init_slave_sockets() - { - Slave_ilist_iterator it(const_cast(m_slaves)); - Slave *slave; - uint fds_index= 0; - - FD_ZERO(&m_init_fds); - while ((slave= it++)) - { - my_socket socket_id= slave->sock_fd(); - m_max_fd= (socket_id > m_max_fd ? socket_id : m_max_fd); -#ifndef _WIN32 - if (socket_id > FD_SETSIZE) - { - sql_print_error("Semisync slave socket fd is %u. " - "select() cannot handle if the socket fd is " - "greater than %u (FD_SETSIZE).", socket_id, FD_SETSIZE); - return 0; - } -#endif //_WIN32 - FD_SET(socket_id, &m_init_fds); - fds_index++; - } - return fds_index; - } - my_socket get_max_fd() { return m_max_fd; } - -private: - const Slave_ilist &m_slaves; - my_socket m_max_fd; - fd_set m_init_fds; - fd_set m_fds; -}; - -#endif //HAVE_POLL - -extern Ack_receiver ack_receiver; -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_slave.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_slave.h deleted file mode 100644 index d65262f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/semisync_slave.h +++ /dev/null @@ -1,115 +0,0 @@ -/* Copyright (c) 2006 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - -#ifndef SEMISYNC_SLAVE_H -#define SEMISYNC_SLAVE_H - -#include "semisync.h" -#include "my_global.h" -#include "sql_priv.h" -#include "rpl_mi.h" -#include "mysql.h" - -class Master_info; - -/** - The extension class for the slave of semi-synchronous replication -*/ -class Repl_semi_sync_slave - :public Repl_semi_sync_base { -public: - Repl_semi_sync_slave() :m_slave_enabled(false) {} - ~Repl_semi_sync_slave() {} - - void set_trace_level(unsigned long trace_level) { - m_trace_level = trace_level; - } - - /* Initialize this class after MySQL parameters are initialized. this - * function should be called once at bootstrap time. - */ - int init_object(); - - bool get_slave_enabled() { - return m_slave_enabled; - } - - void set_slave_enabled(bool enabled) { - m_slave_enabled = enabled; - } - - bool is_delay_master(){ - return m_delay_master; - } - - void set_delay_master(bool enabled) { - m_delay_master = enabled; - } - - void set_kill_conn_timeout(unsigned int timeout) { - m_kill_conn_timeout = timeout; - } - - /* A slave reads the semi-sync packet header and separate the metadata - * from the payload data. - * - * Input: - * header - (IN) packet header pointer - * total_len - (IN) total packet length: metadata + payload - * semi_flags - (IN) store flags: SEMI_SYNC_SLAVE_DELAY_SYNC and - SEMI_SYNC_NEED_ACK - * payload - (IN) payload: the replication event - * payload_len - (IN) payload length - * - * Return: - * 0: success; non-zero: error - */ - int slave_read_sync_header(const char *header, unsigned long total_len, - int *semi_flags, - const char **payload, unsigned long *payload_len); - - /* A slave replies to the master indicating its replication process. It - * indicates that the slave has received all events before the specified - * binlog position. - */ - int slave_reply(Master_info* mi); - int slave_start(Master_info *mi); - int slave_stop(Master_info *mi); - int request_transmit(Master_info*); - void kill_connection(MYSQL *mysql); - int reset_slave(Master_info *mi); - -private: - /* True when init_object has been called */ - bool m_init_done; - bool m_slave_enabled; /* semi-sycn is enabled on the slave */ - bool m_delay_master; - unsigned int m_kill_conn_timeout; -}; - - -/* System and status variables for the slave component */ -extern my_bool rpl_semi_sync_slave_enabled; -extern my_bool rpl_semi_sync_slave_status; -extern ulong rpl_semi_sync_slave_trace_level; -extern Repl_semi_sync_slave repl_semisync_slave; - -extern char rpl_semi_sync_slave_delay_master; -extern unsigned int rpl_semi_sync_slave_kill_conn_timeout; -extern unsigned long long rpl_semi_sync_slave_send_ack; - -#endif /* SEMISYNC_SLAVE_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/service_versions.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/service_versions.h deleted file mode 100644 index 66451ee..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/service_versions.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. - Copyright (c) 2012, 2019, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef _WIN32 -#define SERVICE_VERSION __declspec(dllexport) void * -#else -#define SERVICE_VERSION void * -#endif - -#define VERSION_debug_sync 0x1000 -#define VERSION_kill_statement 0x1000 - -#define VERSION_base64 0x0100 -#define VERSION_encryption 0x0300 -#define VERSION_encryption_scheme 0x0100 -#define VERSION_logger 0x0100 -#define VERSION_my_crypt 0x0100 -#define VERSION_my_md5 0x0100 -#define VERSION_my_print_error 0x0100 -#define VERSION_my_sha1 0x0101 -#define VERSION_my_sha2 0x0100 -#define VERSION_my_snprintf 0x0100 -#define VERSION_progress_report 0x0100 -#define VERSION_thd_alloc 0x0200 -#define VERSION_thd_autoinc 0x0100 -#define VERSION_thd_error_context 0x0200 -#define VERSION_thd_rnd 0x0100 -#define VERSION_thd_specifics 0x0100 -#define VERSION_thd_timezone 0x0100 -#define VERSION_thd_wait 0x0100 -#define VERSION_wsrep 0x0202 -#define VERSION_json 0x0100 -#define VERSION_thd_mdl 0x0100 diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/session_tracker.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/session_tracker.h deleted file mode 100644 index c78778a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/session_tracker.h +++ /dev/null @@ -1,498 +0,0 @@ -#ifndef SESSION_TRACKER_INCLUDED -#define SESSION_TRACKER_INCLUDED - -/* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2016, 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include "m_string.h" -#include "thr_lock.h" -#include "sql_hset.h" - -#ifndef EMBEDDED_LIBRARY -/* forward declarations */ -class THD; -class set_var; -class String; -class user_var_entry; - - -enum enum_session_tracker -{ - SESSION_SYSVARS_TRACKER, /* Session system variables */ - CURRENT_SCHEMA_TRACKER, /* Current schema */ - SESSION_STATE_CHANGE_TRACKER, - TRANSACTION_INFO_TRACKER, /* Transaction state */ -#ifdef USER_VAR_TRACKING - USER_VARIABLES_TRACKER, -#endif // USER_VAR_TRACKING - SESSION_TRACKER_END /* must be the last */ -}; - -/** - State_tracker - - An abstract class that defines the interface for any of the server's - 'session state change tracker'. A tracker, however, is a sub- class of - this class which takes care of tracking the change in value of a part- - icular session state type and thus defines various methods listed in this - interface. The change information is later serialized and transmitted to - the client through protocol's OK packet. - - Tracker system variables :- - A tracker is normally mapped to a system variable. So in order to enable, - disable or modify the sub-entities of a tracker, the user needs to modify - the respective system variable either through SET command or via command - line option. As required in system variable handling, this interface also - includes two functions to help in the verification of the supplied value - (ON_UPDATE) of the tracker system variable, namely - update(). -*/ - -class State_tracker -{ -protected: - /** - Is tracking enabled for a particular session state type ? - - @note: it is a cache of the corresponding thd->variables.session_track_xxx - variable - */ - bool m_enabled; - - void set_changed(THD *thd); - -private: - /** Has the session state type changed ? */ - bool m_changed; - -public: - virtual ~State_tracker() {} - - /** Getters */ - bool is_enabled() const - { return m_enabled; } - - bool is_changed() const - { return m_changed; } - - void reset_changed() { m_changed= false; } - - /** - Called by THD::init() when new connection is being created - - We may inherit m_changed from previous connection served by this THD if - connection was broken or client didn't have session tracking capability. - Thus we have to reset it here. - */ - virtual bool enable(THD *thd) - { - reset_changed(); - return update(thd, 0); - } - - /** To be invoked when the tracker's system variable is updated (ON_UPDATE).*/ - virtual bool update(THD *thd, set_var *var)= 0; - - /** Store changed data into the given buffer. */ - virtual bool store(THD *thd, String *buf)= 0; - - /** Mark the entity as changed. */ - void mark_as_changed(THD *thd) { if (is_enabled()) set_changed(thd); } -}; - - -/** - Session_sysvars_tracker - - This is a tracker class that enables & manages the tracking of session - system variables. It internally maintains a hash of user supplied variable - references and a boolean field to store if the variable was changed by the - last statement. -*/ - -class Session_sysvars_tracker: public State_tracker -{ - struct sysvar_node_st { - sys_var *m_svar; - bool *test_load; - bool m_changed; - }; - - class vars_list - { - /** - Registered system variables. (@@session_track_system_variables) - A hash to store the name of all the system variables specified by the - user. - */ - HASH m_registered_sysvars; - /** - If TRUE then we want to check all session variable. - */ - bool track_all; - void init() - { - my_hash_init(PSI_INSTRUMENT_ME, &m_registered_sysvars, &my_charset_bin, - 0, 0, 0, (my_hash_get_key) sysvars_get_key, my_free, - HASH_UNIQUE | (mysqld_server_initialized ? HASH_THREAD_SPECIFIC : 0)); - } - void free_hash() - { - DBUG_ASSERT(my_hash_inited(&m_registered_sysvars)); - my_hash_free(&m_registered_sysvars); - } - - sysvar_node_st *search(const sys_var *svar) - { - return reinterpret_cast( - my_hash_search(&m_registered_sysvars, - reinterpret_cast(&svar), - sizeof(sys_var*))); - } - - sysvar_node_st *at(ulong i) - { - DBUG_ASSERT(i < m_registered_sysvars.records); - return reinterpret_cast( - my_hash_element(&m_registered_sysvars, i)); - } - public: - vars_list(): track_all(false) { init(); } - ~vars_list() { if (my_hash_inited(&m_registered_sysvars)) free_hash(); } - void deinit() { free_hash(); } - - sysvar_node_st *insert_or_search(const sys_var *svar) - { - sysvar_node_st *res= search(svar); - if (!res) - { - if (track_all) - { - insert(svar); - return search(svar); - } - } - return res; - } - - bool insert(const sys_var *svar); - void reinit(); - void reset(); - inline bool is_enabled() - { - return track_all || m_registered_sysvars.records; - } - void copy(vars_list* from, THD *thd); - bool parse_var_list(THD *thd, LEX_STRING var_list, bool throw_error, - CHARSET_INFO *char_set); - bool construct_var_list(char *buf, size_t buf_len); - bool store(THD *thd, String *buf); - }; - /** - Two objects of vars_list type are maintained to manage - various operations. - */ - vars_list orig_list; - bool m_parsed; - -public: - void init(THD *thd); - void deinit(THD *thd); - bool enable(THD *thd); - bool update(THD *thd, set_var *var); - bool store(THD *thd, String *buf); - void mark_as_changed(THD *thd, const sys_var *var); - void deinit() { orig_list.deinit(); } - /* callback */ - static uchar *sysvars_get_key(const char *entry, size_t *length, - my_bool not_used __attribute__((unused))); - - friend bool sysvartrack_global_update(THD *thd, char *str, size_t len); -}; - - -bool sysvartrack_validate_value(THD *thd, const char *str, size_t len); -bool sysvartrack_global_update(THD *thd, char *str, size_t len); - - -/** - Current_schema_tracker, - - This is a tracker class that enables & manages the tracking of current - schema for a particular connection. -*/ - -class Current_schema_tracker: public State_tracker -{ -public: - bool update(THD *thd, set_var *var); - bool store(THD *thd, String *buf); -}; - - -/* - Session_state_change_tracker - - This is a boolean tracker class that will monitor any change that contributes - to a session state change. - Attributes that contribute to session state change include: - - Successful change to System variables - - User defined variables assignments - - temporary tables created, altered or deleted - - prepared statements added or removed - - change in current database - - change of current role -*/ - -class Session_state_change_tracker: public State_tracker -{ -public: - bool update(THD *thd, set_var *var); - bool store(THD *thd, String *buf); -}; - - -/* - Transaction_state_tracker -*/ - -/** - Transaction state (no transaction, transaction active, work attached, etc.) -*/ -enum enum_tx_state { - TX_EMPTY = 0, ///< "none of the below" - TX_EXPLICIT = 1, ///< an explicit transaction is active - TX_IMPLICIT = 2, ///< an implicit transaction is active - TX_READ_TRX = 4, ///< transactional reads were done - TX_READ_UNSAFE = 8, ///< non-transaction reads were done - TX_WRITE_TRX = 16, ///< transactional writes were done - TX_WRITE_UNSAFE = 32, ///< non-transactional writes were done - TX_STMT_UNSAFE = 64, ///< "unsafe" (non-deterministic like UUID()) stmts - TX_RESULT_SET = 128, ///< result set was sent - TX_WITH_SNAPSHOT= 256, ///< WITH CONSISTENT SNAPSHOT was used - TX_LOCKED_TABLES= 512 ///< LOCK TABLES is active -}; - - -/** - Transaction access mode -*/ -enum enum_tx_read_flags { - TX_READ_INHERIT = 0, ///< not explicitly set, inherit session.tx_read_only - TX_READ_ONLY = 1, ///< START TRANSACTION READ ONLY, or tx_read_only=1 - TX_READ_WRITE = 2, ///< START TRANSACTION READ WRITE, or tx_read_only=0 -}; - - -/** - Transaction isolation level -*/ -enum enum_tx_isol_level { - TX_ISOL_INHERIT = 0, ///< not explicitly set, inherit session.tx_isolation - TX_ISOL_UNCOMMITTED = 1, - TX_ISOL_COMMITTED = 2, - TX_ISOL_REPEATABLE = 3, - TX_ISOL_SERIALIZABLE= 4 -}; - - -/** - Transaction tracking level -*/ -enum enum_session_track_transaction_info { - TX_TRACK_NONE = 0, ///< do not send tracker items on transaction info - TX_TRACK_STATE = 1, ///< track transaction status - TX_TRACK_CHISTICS = 2 ///< track status and characteristics -}; - - -/** - This is a tracker class that enables & manages the tracking of - current transaction info for a particular connection. -*/ - -class Transaction_state_tracker : public State_tracker -{ - /** Helper function: turn table info into table access flag */ - enum_tx_state calc_trx_state(THD *thd, thr_lock_type l, bool has_trx); -public: - - bool enable(THD *thd) - { - m_enabled= false; - tx_changed= TX_CHG_NONE; - tx_curr_state= TX_EMPTY; - tx_reported_state= TX_EMPTY; - tx_read_flags= TX_READ_INHERIT; - tx_isol_level= TX_ISOL_INHERIT; - return State_tracker::enable(thd); - } - - bool update(THD *thd, set_var *var); - bool store(THD *thd, String *buf); - - /** Change transaction characteristics */ - void set_read_flags(THD *thd, enum enum_tx_read_flags flags); - void set_isol_level(THD *thd, enum enum_tx_isol_level level); - - /** Change transaction state */ - void clear_trx_state(THD *thd, uint clear); - void add_trx_state(THD *thd, uint add); - void inline add_trx_state(THD *thd, thr_lock_type l, bool has_trx) - { - add_trx_state(thd, calc_trx_state(thd, l, has_trx)); - } - void add_trx_state_from_thd(THD *thd); - void end_trx(THD *thd); - - -private: - enum enum_tx_changed { - TX_CHG_NONE = 0, ///< no changes from previous stmt - TX_CHG_STATE = 1, ///< state has changed from previous stmt - TX_CHG_CHISTICS = 2 ///< characteristics have changed from previous stmt - }; - - /** any trackable changes caused by this statement? */ - uint tx_changed; - - /** transaction state */ - uint tx_curr_state, tx_reported_state; - - /** r/w or r/o set? session default? */ - enum enum_tx_read_flags tx_read_flags; - - /** isolation level */ - enum enum_tx_isol_level tx_isol_level; - - inline void update_change_flags(THD *thd) - { - tx_changed &= uint(~TX_CHG_STATE); - tx_changed |= (tx_curr_state != tx_reported_state) ? TX_CHG_STATE : 0; - if (tx_changed != TX_CHG_NONE) - set_changed(thd); - } -}; - -#define TRANSACT_TRACKER(X) \ - do { if (thd->variables.session_track_transaction_info > TX_TRACK_NONE) \ - thd->session_tracker.transaction_info.X; } while(0) - - -/** - User_variables_tracker - - This is a tracker class that enables & manages the tracking of user variables. -*/ - -#ifdef USER_VAR_TRACKING -class User_variables_tracker: public State_tracker -{ - Hash_set m_changed_user_variables; -public: - User_variables_tracker(): - m_changed_user_variables(PSI_INSTRUMENT_ME, &my_charset_bin, 0, 0, - sizeof(const user_var_entry*), 0, 0, HASH_UNIQUE | - mysqld_server_initialized ? HASH_THREAD_SPECIFIC : 0) {} - bool update(THD *thd, set_var *var); - bool store(THD *thd, String *buf); - void mark_as_changed(THD *thd, const user_var_entry *var) - { - if (is_enabled()) - { - m_changed_user_variables.insert(var); - set_changed(thd); - } - } - void deinit() { m_changed_user_variables.~Hash_set(); } -}; -#endif // USER_VAR_TRACKING - - -/** - Session_tracker - - This class holds an object each for all tracker classes and provides - methods necessary for systematic detection and generation of session - state change information. -*/ - -class Session_tracker -{ - State_tracker *m_trackers[SESSION_TRACKER_END]; - - /* The following two functions are private to disable copying. */ - Session_tracker(Session_tracker const &other) - { - DBUG_ASSERT(FALSE); - } - Session_tracker& operator= (Session_tracker const &rhs) - { - DBUG_ASSERT(FALSE); - return *this; - } - -public: - Current_schema_tracker current_schema; - Session_state_change_tracker state_change; - Transaction_state_tracker transaction_info; - Session_sysvars_tracker sysvars; -#ifdef USER_VAR_TRACKING - User_variables_tracker user_variables; -#endif // USER_VAR_TRACKING - - Session_tracker() - { - m_trackers[SESSION_SYSVARS_TRACKER]= &sysvars; - m_trackers[CURRENT_SCHEMA_TRACKER]= ¤t_schema; - m_trackers[SESSION_STATE_CHANGE_TRACKER]= &state_change; - m_trackers[TRANSACTION_INFO_TRACKER]= &transaction_info; -#ifdef USER_VAR_TRACKING - m_trackers[USER_VARIABLES_TRACKER]= &user_variables; -#endif // USER_VAR_TRACKING - } - - void enable(THD *thd) - { - for (int i= 0; i < SESSION_TRACKER_END; i++) - m_trackers[i]->enable(thd); - } - - void store(THD *thd, String *main_buf); -}; - - -int session_tracker_init(); -#else - -#define TRANSACT_TRACKER(X) do{}while(0) - -class Session_tracker -{ - class Dummy_tracker - { - public: - void mark_as_changed(THD *thd) {} - void mark_as_changed(THD *thd, const sys_var *var) {} - }; -public: - Dummy_tracker current_schema; - Dummy_tracker state_change; - Dummy_tracker sysvars; -}; - -#endif //EMBEDDED_LIBRARY - -#endif /* SESSION_TRACKER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/set_var.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/set_var.h deleted file mode 100644 index 18c4dbc..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/set_var.h +++ /dev/null @@ -1,477 +0,0 @@ -#ifndef SET_VAR_INCLUDED -#define SET_VAR_INCLUDED -/* Copyright (c) 2002, 2013, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - "public" interface to sys_var - server configuration variables. -*/ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include - -class sys_var; -class set_var; -class sys_var_pluginvar; -class PolyLock; -class Item_func_set_user_var; - -// This include needs to be here since item.h requires enum_var_type :-P -#include "item.h" /* Item */ -#include "sql_class.h" /* THD */ - -extern TYPELIB bool_typelib; - -struct sys_var_chain -{ - sys_var *first; - sys_var *last; -}; - -int mysql_add_sys_var_chain(sys_var *chain); -int mysql_del_sys_var_chain(sys_var *chain); - - -/** - A class representing one system variable - that is something - that can be accessed as @@global.variable_name or @@session.variable_name, - visible in SHOW xxx VARIABLES and in INFORMATION_SCHEMA.xxx_VARIABLES, - optionally it can be assigned to, optionally it can have a command-line - counterpart with the same name. -*/ -class sys_var: protected Value_source // for double_from_string_with_check -{ -public: - sys_var *next; - LEX_CSTRING name; - bool *test_load; - enum flag_enum { GLOBAL, SESSION, ONLY_SESSION, SCOPE_MASK=1023, - READONLY=1024, ALLOCATED=2048, PARSE_EARLY=4096, - NO_SET_STATEMENT=8192, AUTO_SET=16384}; - enum { NO_GETOPT=-1, GETOPT_ONLY_HELP=-2 }; - enum where { CONFIG, COMMAND_LINE, AUTO, SQL, COMPILE_TIME, ENV }; - - /** - Enumeration type to indicate for a system variable whether - it will be written to the binlog or not. - */ - enum binlog_status_enum { VARIABLE_NOT_IN_BINLOG, - SESSION_VARIABLE_IN_BINLOG } binlog_status; - - my_option option; ///< min, max, default values are stored here - enum where value_origin; - const char *origin_filename; - -protected: - typedef bool (*on_check_function)(sys_var *self, THD *thd, set_var *var); - typedef bool (*on_update_function)(sys_var *self, THD *thd, enum_var_type type); - - int flags; ///< or'ed flag_enum values - const SHOW_TYPE show_val_type; ///< what value_ptr() returns for sql_show.cc - PolyLock *guard; ///< *second* lock that protects the variable - ptrdiff_t offset; ///< offset to the value from global_system_variables - on_check_function on_check; - on_update_function on_update; - const char *const deprecation_substitute; - -public: - sys_var(sys_var_chain *chain, const char *name_arg, const char *comment, - int flag_args, ptrdiff_t off, int getopt_id, - enum get_opt_arg_type getopt_arg_type, SHOW_TYPE show_val_type_arg, - longlong def_val, PolyLock *lock, enum binlog_status_enum binlog_status_arg, - on_check_function on_check_func, on_update_function on_update_func, - const char *substitute); - - virtual ~sys_var() {} - - /** - All the cleanup procedures should be performed here - */ - virtual void cleanup() {} - /** - downcast for sys_var_pluginvar. Returns this if it's an instance - of sys_var_pluginvar, and 0 otherwise. - */ - virtual sys_var_pluginvar *cast_pluginvar() { return 0; } - - bool check(THD *thd, set_var *var); - uchar *value_ptr(THD *thd, enum_var_type type, const LEX_CSTRING *base); - - /** - Update the system variable with the default value from either - session or global scope. The default value is stored in the - 'var' argument. Return false when successful. - */ - bool set_default(THD *thd, set_var *var); - bool update(THD *thd, set_var *var); - - String *val_str_nolock(String *str, THD *thd, const uchar *value); - longlong val_int(bool *is_null, THD *thd, enum_var_type type, const LEX_CSTRING *base); - String *val_str(String *str, THD *thd, enum_var_type type, const LEX_CSTRING *base); - double val_real(bool *is_null, THD *thd, enum_var_type type, const LEX_CSTRING *base); - - SHOW_TYPE show_type() { return show_val_type; } - int scope() const { return flags & SCOPE_MASK; } - virtual CHARSET_INFO *charset(THD *thd) const - { - return system_charset_info; - } - bool is_readonly() const { return flags & READONLY; } - /** - the following is only true for keycache variables, - that support the syntax @@keycache_name.variable_name - */ - bool is_struct() { return option.var_type & GET_ASK_ADDR; } - bool is_set_stmt_ok() const { return !(flags & NO_SET_STATEMENT); } - bool is_written_to_binlog(enum_var_type type) - { return type != OPT_GLOBAL && binlog_status == SESSION_VARIABLE_IN_BINLOG; } - bool check_update_type(const Item *item) - { - Item_result type= item->result_type(); - switch (option.var_type & GET_TYPE_MASK) { - case GET_INT: - case GET_UINT: - case GET_LONG: - case GET_ULONG: - case GET_LL: - case GET_ULL: - return type != INT_RESULT && - (type != DECIMAL_RESULT || item->decimals != 0); - case GET_STR: - case GET_STR_ALLOC: - return type != STRING_RESULT; - case GET_ENUM: - case GET_BOOL: - case GET_SET: - case GET_FLAGSET: - case GET_BIT: - return type != STRING_RESULT && type != INT_RESULT; - case GET_DOUBLE: - return type != INT_RESULT && type != REAL_RESULT && type != DECIMAL_RESULT; - default: - return true; - } - } - - bool check_type(enum_var_type type) - { - switch (scope()) - { - case GLOBAL: return type != OPT_GLOBAL; - case SESSION: return false; // always ok - case ONLY_SESSION: return type == OPT_GLOBAL; - } - return true; // keep gcc happy - } - bool register_option(DYNAMIC_ARRAY *array, int parse_flags) - { - DBUG_ASSERT(parse_flags == GETOPT_ONLY_HELP || - parse_flags == PARSE_EARLY || parse_flags == 0); - if (option.id == NO_GETOPT) - return 0; - if (parse_flags == GETOPT_ONLY_HELP) - { - if (option.id != GETOPT_ONLY_HELP) - return 0; - } - else - { - if (option.id == GETOPT_ONLY_HELP) - return 0; - if ((flags & PARSE_EARLY) != parse_flags) - return 0; - } - return insert_dynamic(array, (uchar*)&option); - } - void do_deprecated_warning(THD *thd); - /** - whether session value of a sysvar is a default one. - - in this simple implementation we don't distinguish between default - and non-default values. for most variables it's ok, they don't treat - default values specially. this method is overwritten in descendant - classes as necessary. - */ - virtual bool session_is_default(THD *thd) { return false; } - - virtual uchar *default_value_ptr(THD *thd) - { return (uchar*)&option.def_value; } - - virtual bool on_check_access_global(THD *thd) const; - virtual bool on_check_access_session(THD *thd) const - { - return false; - } - -private: - virtual bool do_check(THD *thd, set_var *var) = 0; - /** - save the session default value of the variable in var - */ - virtual void session_save_default(THD *thd, set_var *var) = 0; - /** - save the global default value of the variable in var - */ - virtual void global_save_default(THD *thd, set_var *var) = 0; - virtual bool session_update(THD *thd, set_var *var) = 0; - virtual bool global_update(THD *thd, set_var *var) = 0; - -protected: - /** - A pointer to a value of the variable for SHOW. - It must be of show_val_type type (my_bool for SHOW_MY_BOOL, - int for SHOW_INT, longlong for SHOW_LONGLONG, etc). - */ - virtual uchar *session_value_ptr(THD *thd, const LEX_CSTRING *base); - virtual uchar *global_value_ptr(THD *thd, const LEX_CSTRING *base); - - /** - A pointer to a storage area of the variable, to the raw data. - Typically it's the same as session_value_ptr(), but it's different, - for example, for ENUM, that is printed as a string, but stored as a number. - */ - uchar *session_var_ptr(THD *thd) - { return ((uchar*)&(thd->variables)) + offset; } - - uchar *global_var_ptr() - { return ((uchar*)&global_system_variables) + offset; } - - void *max_var_ptr() - { - return scope() == SESSION ? (((uchar*)&max_system_variables) + offset) : - 0; - } - - friend class Session_sysvars_tracker; - friend class Session_tracker; -}; - -#include "sql_plugin.h" /* SHOW_HA_ROWS, SHOW_MY_BOOL */ - - -/**************************************************************************** - Classes for parsing of the SET command -****************************************************************************/ - -/** - A base class for everything that can be set with SET command. - It's similar to Items, an instance of this is created by the parser - for every assigmnent in SET (or elsewhere, e.g. in SELECT). -*/ -class set_var_base :public Sql_alloc -{ -public: - set_var_base() {} - virtual ~set_var_base() {} - virtual int check(THD *thd)=0; /* To check privileges etc. */ - virtual int update(THD *thd)=0; /* To set the value */ - virtual int light_check(THD *thd) { return check(thd); } /* for PS */ - virtual bool is_system() { return FALSE; } - /** - @returns whether this variable is @@@@optimizer_trace. - */ - virtual bool is_var_optimizer_trace() const { return false; } -}; - - -/** - set_var_base descendant for assignments to the system variables. -*/ -class set_var :public set_var_base -{ -public: - sys_var *var; ///< system variable to be updated - Item *value; ///< the expression that provides the new value of the variable - enum_var_type type; - union ///< temp storage to hold a value between sys_var::check and ::update - { - ulonglong ulonglong_value; ///< for unsigned integer, set, enum sysvars - longlong longlong_value; ///< for signed integer - double double_value; ///< for Sys_var_double - plugin_ref plugin; ///< for Sys_var_plugin - plugin_ref *plugins; ///< for Sys_var_pluginlist - Time_zone *time_zone; ///< for Sys_var_tz - LEX_STRING string_value; ///< for Sys_var_charptr and others - const void *ptr; ///< for Sys_var_struct - } save_result; - LEX_CSTRING base; /**< for structured variables, like keycache_name.variable_name */ - - set_var(THD *thd, enum_var_type type_arg, sys_var *var_arg, - const LEX_CSTRING *base_name_arg, Item *value_arg); - virtual bool is_system() { return 1; } - int check(THD *thd); - int update(THD *thd); - int light_check(THD *thd); - virtual bool is_var_optimizer_trace() const - { - extern sys_var *Sys_optimizer_trace_ptr; - return var == Sys_optimizer_trace_ptr; - } -}; - - -/* User variables like @my_own_variable */ -class set_var_user: public set_var_base -{ - Item_func_set_user_var *user_var_item; -public: - set_var_user(Item_func_set_user_var *item) - :user_var_item(item) - {} - int check(THD *thd); - int update(THD *thd); - int light_check(THD *thd); -}; - -/* For SET PASSWORD */ - -class set_var_password: public set_var_base -{ - LEX_USER *user; -public: - set_var_password(LEX_USER *user_arg) :user(user_arg) - {} - int check(THD *thd); - int update(THD *thd); -}; - -/* For SET ROLE */ - -class set_var_role: public set_var_base -{ - LEX_CSTRING role; - privilege_t access; -public: - set_var_role(LEX_CSTRING role_arg) : role(role_arg), access(NO_ACL) {} - int check(THD *thd); - int update(THD *thd); -}; - -/* For SET DEFAULT ROLE */ - -class set_var_default_role: public set_var_base -{ - LEX_USER *user, *real_user; - LEX_CSTRING role; - const char *real_role; -public: - set_var_default_role(LEX_USER *user_arg, LEX_CSTRING role_arg) : - user(user_arg), role(role_arg) {} - int check(THD *thd); - int update(THD *thd); -}; - -/* For SET NAMES and SET CHARACTER SET */ - -class set_var_collation_client: public set_var_base -{ - CHARSET_INFO *character_set_client; - CHARSET_INFO *character_set_results; - CHARSET_INFO *collation_connection; -public: - set_var_collation_client(CHARSET_INFO *client_coll_arg, - CHARSET_INFO *connection_coll_arg, - CHARSET_INFO *result_coll_arg) - :character_set_client(client_coll_arg), - character_set_results(result_coll_arg), - collation_connection(connection_coll_arg) - {} - int check(THD *thd); - int update(THD *thd); -}; - - -/* optional things, have_* variables */ -extern SHOW_COMP_OPTION have_csv, have_innodb; -extern SHOW_COMP_OPTION have_ndbcluster, have_partitioning; -extern SHOW_COMP_OPTION have_profiling; - -extern SHOW_COMP_OPTION have_ssl, have_symlink, have_dlopen; -extern SHOW_COMP_OPTION have_query_cache; -extern SHOW_COMP_OPTION have_geometry, have_rtree_keys; -extern SHOW_COMP_OPTION have_crypt; -extern SHOW_COMP_OPTION have_compress; -extern SHOW_COMP_OPTION have_openssl; - -/* - Prototypes for helper functions -*/ -ulong get_system_variable_hash_records(void); -ulonglong get_system_variable_hash_version(void); - -SHOW_VAR* enumerate_sys_vars(THD *thd, bool sorted, enum enum_var_type type); -int fill_sysvars(THD *thd, TABLE_LIST *tables, COND *cond); - -sys_var *find_sys_var(THD *thd, const char *str, size_t length= 0, - bool throw_error= false); -int sql_set_variables(THD *thd, List *var_list, bool free); - -#define SYSVAR_AUTOSIZE(VAR,VAL) \ - do { \ - VAR= (VAL); \ - set_sys_var_value_origin(&VAR, sys_var::AUTO); \ - } while(0) - -#define SYSVAR_AUTOSIZE_IF_CHANGED(VAR,VAL,TYPE) \ - do { \ - TYPE tmp= (VAL); \ - if (VAR != tmp) \ - { \ - VAR= (VAL); \ - set_sys_var_value_origin(&VAR, sys_var::AUTO); \ - } \ - } while(0) - -void set_sys_var_value_origin(void *ptr, enum sys_var::where here); - -enum sys_var::where get_sys_var_value_origin(void *ptr); -inline bool IS_SYSVAR_AUTOSIZE(void *ptr) -{ - enum sys_var::where res= get_sys_var_value_origin(ptr); - return (res == sys_var::AUTO || res == sys_var::COMPILE_TIME); -} - -bool fix_delay_key_write(sys_var *self, THD *thd, enum_var_type type); - -sql_mode_t expand_sql_mode(sql_mode_t sql_mode); -const char *sql_mode_string_representation(uint bit_number); -bool sql_mode_string_representation(THD *thd, sql_mode_t sql_mode, - LEX_CSTRING *ls); -int default_regex_flags_pcre(THD *thd); - -extern sys_var *Sys_autocommit_ptr, *Sys_last_gtid_ptr, - *Sys_character_set_client_ptr, *Sys_character_set_connection_ptr, - *Sys_character_set_results_ptr; - -CHARSET_INFO *get_old_charset_by_name(const char *old_name); - -int sys_var_init(); -uint sys_var_elements(); -int sys_var_add_options(DYNAMIC_ARRAY *long_options, int parse_flags); -void sys_var_end(void); -bool check_has_super(sys_var *self, THD *thd, set_var *var); -plugin_ref *resolve_engine_list(THD *thd, const char *str_arg, size_t str_arg_len, - bool error_on_unknown_engine, bool temp_copy); -void free_engine_list(plugin_ref *list); -plugin_ref *copy_engine_list(plugin_ref *list); -plugin_ref *temp_copy_engine_list(THD *thd, plugin_ref *list); -char *pretty_print_engine_list(THD *thd, plugin_ref *list); - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/slave.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/slave.h deleted file mode 100644 index 5ca6054..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/slave.h +++ /dev/null @@ -1,308 +0,0 @@ -/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. - Copyright (c) 2009, 2016, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SLAVE_H -#define SLAVE_H - -/** - MASTER_DELAY can be at most (1 << 31) - 1. -*/ -#define MASTER_DELAY_MAX (0x7FFFFFFF) -#if INT_MAX < 0x7FFFFFFF -#error "don't support platforms where INT_MAX < 0x7FFFFFFF" -#endif - -/** - @defgroup Replication Replication - @{ - - @file -*/ - -/** - Some of defines are need in parser even though replication is not - compiled in (embedded). -*/ - -/** - The maximum is defined as (ULONG_MAX/1000) with 4 bytes ulong -*/ -#define SLAVE_MAX_HEARTBEAT_PERIOD 4294967 - -#ifdef HAVE_REPLICATION - -#include "log.h" -#include "my_list.h" -#include "rpl_filter.h" -#include "rpl_tblmap.h" -#include "rpl_gtid.h" - -#define SLAVE_NET_TIMEOUT 60 - -#define MAX_SLAVE_ERROR ER_ERROR_LAST+1 - -#define MAX_REPLICATION_THREAD 64 - -// Forward declarations -class Relay_log_info; -class Master_info; -class Master_info_index; -struct rpl_group_info; -struct rpl_parallel_thread; - -int init_intvar_from_file(int* var, IO_CACHE* f, int default_val); -int init_strvar_from_file(char *var, int max_size, IO_CACHE *f, - const char *default_val); -int init_floatvar_from_file(float* var, IO_CACHE* f, float default_val); -int init_dynarray_intvar_from_file(DYNAMIC_ARRAY* arr, IO_CACHE* f); - -/***************************************************************************** - - MySQL Replication - - Replication is implemented via two types of threads: - - I/O Thread - One of these threads is started for each master server. - They maintain a connection to their master server, read log - events from the master as they arrive, and queues them into - a single, shared relay log file. A Master_info - represents each of these threads. - - SQL Thread - One of these threads is started and reads from the relay log - file, executing each event. A Relay_log_info - represents this thread. - - Buffering in the relay log file makes it unnecessary to reread events from - a master server across a slave restart. It also decouples the slave from - the master where long-running updates and event logging are concerned--ie - it can continue to log new events while a slow query executes on the slave. - -*****************************************************************************/ - -/* - MUTEXES in replication: - - LOCK_active_mi: [note: this was originally meant for multimaster, to switch - from a master to another, to protect active_mi] It is used to SERIALIZE ALL - administrative commands of replication: START SLAVE, STOP SLAVE, CHANGE - MASTER, RESET SLAVE, end_slave() (when mysqld stops) [init_slave() does not - need it it's called early]. Any of these commands holds the mutex from the - start till the end. This thus protects us against a handful of deadlocks - (consider start_slave_thread() which, when starting the I/O thread, releases - mi->run_lock, keeps rli->run_lock, and tries to re-acquire mi->run_lock). - - Currently active_mi never moves (it's created at startup and deleted at - shutdown, and not changed: it always points to the same Master_info struct), - because we don't have multimaster. So for the moment, mi does not move, and - mi->rli does not either. - - In Master_info: run_lock, data_lock - run_lock protects all information about the run state: slave_running, thd - and the existence of the I/O thread (to stop/start it, you need this mutex). - data_lock protects some moving members of the struct: counters (log name, - position) and relay log (MYSQL_BIN_LOG object). - - In Relay_log_info: run_lock, data_lock - see Master_info - However, note that run_lock does not protect - Relay_log_info.run_state; that is protected by data_lock. - - Order of acquisition: if you want to have LOCK_active_mi and a run_lock, you - must acquire LOCK_active_mi first. - - In MYSQL_BIN_LOG: LOCK_log, LOCK_index of the binlog and the relay log - LOCK_log: when you write to it. LOCK_index: when you create/delete a binlog - (so that you have to update the .index file). -*/ - -extern ulong master_retry_count; -extern MY_BITMAP slave_error_mask; -extern char slave_skip_error_names[]; -extern bool use_slave_mask; -extern char slave_transaction_retry_error_names[]; -extern uint *slave_transaction_retry_errors; -extern uint slave_transaction_retry_error_length; -extern char *slave_load_tmpdir; -extern char *master_info_file; -extern MYSQL_PLUGIN_IMPORT char *relay_log_info_file; -extern char *opt_relay_logname, *opt_relaylog_index_name; -extern my_bool opt_skip_slave_start, opt_reckless_slave; -extern my_bool opt_log_slave_updates; -extern char *opt_slave_skip_errors; -extern char *opt_slave_transaction_retry_errors; -extern my_bool opt_replicate_annotate_row_events; -extern ulonglong relay_log_space_limit; -extern ulonglong opt_read_binlog_speed_limit; -extern ulonglong slave_skipped_errors; -extern const char *relay_log_index; -extern const char *relay_log_basename; - -/* - 4 possible values for Master_info::slave_running and - Relay_log_info::slave_running. - The values 0,1,2,3 are very important: to keep the diff small, I didn't - substitute places where we use 0/1 with the newly defined symbols. - So don't change these values. - The same way, code is assuming that in Relay_log_info we use only values - 0/1. - I started with using an enum, but - enum_variable=1; is not legal so would have required many line changes. -*/ -#define MYSQL_SLAVE_NOT_RUN 0 -#define MYSQL_SLAVE_RUN_NOT_CONNECT 1 -#define MYSQL_SLAVE_RUN_CONNECT 2 -#define MYSQL_SLAVE_RUN_READING 3 - -#define RPL_LOG_NAME (rli->group_master_log_name[0] ? rli->group_master_log_name :\ - "FIRST") -#define IO_RPL_LOG_NAME (mi->master_log_name[0] ? mi->master_log_name :\ - "FIRST") - -/* - If the following is set, if first gives an error, second will be - tried. Otherwise, if first fails, we fail. -*/ -#define SLAVE_FORCE_ALL 4 - -/* - Values for the option --replicate-events-marked-for-skip. - Must match the names in replicate_events_marked_for_skip_names in sys_vars.cc -*/ -#define RPL_SKIP_REPLICATE 0 -#define RPL_SKIP_FILTER_ON_SLAVE 1 -#define RPL_SKIP_FILTER_ON_MASTER 2 - - -int init_slave(); -int init_recovery(Master_info* mi, const char** errmsg); -bool init_slave_skip_errors(const char* arg); -bool init_slave_transaction_retry_errors(const char* arg); -int register_slave_on_master(MYSQL* mysql); -int terminate_slave_threads(Master_info* mi, int thread_mask, - bool skip_lock = 0); -int start_slave_threads(THD *thd, - bool need_slave_mutex, bool wait_for_start, - Master_info* mi, const char* master_info_fname, - const char* slave_info_fname, int thread_mask); -/* - cond_lock is usually same as start_lock. It is needed for the case when - start_lock is 0 which happens if start_slave_thread() is called already - inside the start_lock section, but at the same time we want a - mysql_cond_wait() on start_cond, start_lock -*/ -int start_slave_thread( -#ifdef HAVE_PSI_INTERFACE - PSI_thread_key thread_key, -#endif - pthread_handler h_func, - mysql_mutex_t *start_lock, - mysql_mutex_t *cond_lock, - mysql_cond_t *start_cond, - volatile uint *slave_running, - volatile ulong *slave_run_id, - Master_info *mi); - -/* If fd is -1, dump to NET */ -int mysql_table_dump(THD* thd, const char* db, - const char* tbl_name, int fd = -1); - -/* retrieve table from master and copy to slave*/ -int fetch_master_table(THD* thd, const char* db_name, const char* table_name, - Master_info* mi, MYSQL* mysql, bool overwrite); - -void show_master_info_get_fields(THD *thd, List *field_list, - bool full, size_t gtid_pos_length); -bool show_master_info(THD* thd, Master_info* mi, bool full); -bool show_all_master_info(THD* thd); -void show_binlog_info_get_fields(THD *thd, List *field_list); -bool show_binlog_info(THD* thd); -bool rpl_master_has_bug(const Relay_log_info *rli, uint bug_id, bool report, - bool (*pred)(const void *), const void *param); -bool rpl_master_erroneous_autoinc(THD* thd); - -const char *print_slave_db_safe(const char *db); -void skip_load_data_infile(NET* net); - -void slave_prepare_for_shutdown(); -void end_slave(); /* release slave threads */ -void close_active_mi(); /* clean up slave threads data */ -void clear_until_condition(Relay_log_info* rli); -void clear_slave_error(Relay_log_info* rli); -void end_relay_log_info(Relay_log_info* rli); -void init_thread_mask(int* mask,Master_info* mi,bool inverse); -Format_description_log_event * -read_relay_log_description_event(IO_CACHE *cur_log, ulonglong start_pos, - const char **errmsg); - -int init_relay_log_pos(Relay_log_info* rli,const char* log,ulonglong pos, - bool need_data_lock, const char** errmsg, - bool look_for_description_event); - -int purge_relay_logs(Relay_log_info* rli, THD *thd, bool just_reset, - const char** errmsg); -void set_slave_thread_options(THD* thd); -void set_slave_thread_default_charset(THD *thd, rpl_group_info *rgi); -int rotate_relay_log(Master_info* mi); -int has_temporary_error(THD *thd); -int sql_delay_event(Log_event *ev, THD *thd, rpl_group_info *rgi); -int apply_event_and_update_pos(Log_event* ev, THD* thd, - struct rpl_group_info *rgi); -int apply_event_and_update_pos_for_parallel(Log_event* ev, THD* thd, - struct rpl_group_info *rgi); - -int init_intvar_from_file(int* var, IO_CACHE* f, int default_val); -int init_floatvar_from_file(float* var, IO_CACHE* f, float default_val); -int init_strvar_from_file(char *var, int max_size, IO_CACHE *f, - const char *default_val); -int init_dynarray_intvar_from_file(DYNAMIC_ARRAY* arr, IO_CACHE* f); - -pthread_handler_t handle_slave_io(void *arg); -void slave_output_error_info(rpl_group_info *rgi, THD *thd); -pthread_handler_t handle_slave_sql(void *arg); -bool net_request_file(NET* net, const char* fname); -void slave_background_kill_request(THD *to_kill); -void slave_background_gtid_pos_create_request - (rpl_slave_state::gtid_pos_table *table_entry); -void slave_background_gtid_pending_delete_request(void); - -extern Master_info *active_mi; /* active_mi for multi-master */ -extern Master_info *default_master_info; /* To replace active_mi */ -extern Master_info_index *master_info_index; -extern LEX_CSTRING default_master_connection_name; -extern my_bool replicate_same_server_id; - -extern int disconnect_slave_event_count, abort_slave_event_count ; - -/* the master variables are defaults read from my.cnf or command line */ -extern uint report_port; -extern char *master_info_file, *report_user; -extern char *report_host, *report_password; - -extern I_List threads; - -#else -#define close_active_mi() /* no-op */ -#endif /* HAVE_REPLICATION */ - -/* masks for start/stop operations on io and sql slave threads */ -#define SLAVE_IO 1 -#define SLAVE_SQL 2 - -/** - @} (end of group Replication) -*/ - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/source_revision.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/source_revision.h deleted file mode 100644 index 15a5b26..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/source_revision.h +++ /dev/null @@ -1 +0,0 @@ -#define SOURCE_REVISION "90f43d260e407c650aa8a7885d674c717618cc37" diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp.h deleted file mode 100644 index e92525e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp.h +++ /dev/null @@ -1,674 +0,0 @@ -/* -*- C++ -*- */ -/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _SP_H_ -#define _SP_H_ - -#include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */ -#include "sql_string.h" // LEX_STRING -#include "sql_cmd.h" -#include "mdl.h" - -class Field; -class Open_tables_backup; -class Open_tables_state; -class Query_arena; -class Query_tables_list; -class Sroutine_hash_entry; -class THD; -class sp_cache; -class sp_head; -class sp_package; -class sp_pcontext; -class sp_name; -class Database_qualified_name; -struct st_sp_chistics; -class Stored_program_creation_ctx; -struct LEX; -struct TABLE; -struct TABLE_LIST; -typedef struct st_hash HASH; -template class SQL_I_List; - -/* - Values for the type enum. This reflects the order of the enum declaration - in the CREATE TABLE command. - See also storage/perfschema/my_thread.h -*/ -enum enum_sp_type -{ - SP_TYPE_FUNCTION=1, - SP_TYPE_PROCEDURE=2, - SP_TYPE_PACKAGE=3, - SP_TYPE_PACKAGE_BODY=4, - SP_TYPE_TRIGGER=5, - SP_TYPE_EVENT=6, -}; - -class Sp_handler -{ - bool sp_resolve_package_routine_explicit(THD *thd, - sp_head *caller, - sp_name *name, - const Sp_handler **pkg_routine_hndlr, - Database_qualified_name *pkgname) - const; - bool sp_resolve_package_routine_implicit(THD *thd, - sp_head *caller, - sp_name *name, - const Sp_handler **pkg_routine_hndlr, - Database_qualified_name *pkgname) - const; -protected: - int db_find_routine_aux(THD *thd, const Database_qualified_name *name, - TABLE *table) const; - int db_find_routine(THD *thd, const Database_qualified_name *name, - sp_head **sphp) const; - int db_find_and_cache_routine(THD *thd, - const Database_qualified_name *name, - sp_head **sp) const; - int db_load_routine(THD *thd, const Database_qualified_name *name, - sp_head **sphp, - sql_mode_t sql_mode, - const LEX_CSTRING ¶ms, - const LEX_CSTRING &returns, - const LEX_CSTRING &body, - const st_sp_chistics &chistics, - const AUTHID &definer, - longlong created, longlong modified, - sp_package *parent, - Stored_program_creation_ctx *creation_ctx) const; - int sp_drop_routine_internal(THD *thd, - const Database_qualified_name *name, - TABLE *table) const; - - sp_head *sp_clone_and_link_routine(THD *thd, - const Database_qualified_name *name, - sp_head *sp) const; - int sp_cache_package_routine(THD *thd, - const LEX_CSTRING &pkgname_cstr, - const Database_qualified_name *name, - bool lookup_only, sp_head **sp) const; - int sp_cache_package_routine(THD *thd, - const Database_qualified_name *name, - bool lookup_only, sp_head **sp) const; - sp_head *sp_find_package_routine(THD *thd, - const LEX_CSTRING pkgname_str, - const Database_qualified_name *name, - bool cache_only) const; - sp_head *sp_find_package_routine(THD *thd, - const Database_qualified_name *name, - bool cache_only) const; -public: // TODO: make it private or protected - virtual int sp_find_and_drop_routine(THD *thd, TABLE *table, - const Database_qualified_name *name) - const; - -public: - virtual ~Sp_handler() {} - static const Sp_handler *handler(enum enum_sql_command cmd); - static const Sp_handler *handler(enum_sp_type type); - static const Sp_handler *handler(MDL_key::enum_mdl_namespace ns); - /* - Return a handler only those SP objects that store - definitions in the mysql.proc system table - */ - static const Sp_handler *handler_mysql_proc(enum_sp_type type) - { - const Sp_handler *sph= handler(type); - return sph ? sph->sp_handler_mysql_proc() : NULL; - } - - static bool eq_routine_name(const LEX_CSTRING &name1, - const LEX_CSTRING &name2) - { - return system_charset_info->strnncoll(name1.str, name1.length, - name2.str, name2.length) == 0; - } - const char *type_str() const { return type_lex_cstring().str; } - virtual const char *show_create_routine_col1_caption() const - { - DBUG_ASSERT(0); - return ""; - } - virtual const char *show_create_routine_col3_caption() const - { - DBUG_ASSERT(0); - return ""; - } - virtual const Sp_handler *package_routine_handler() const - { - return this; - } - virtual enum_sp_type type() const= 0; - virtual LEX_CSTRING type_lex_cstring() const= 0; - virtual LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const - { - static LEX_CSTRING m_empty_body= {STRING_WITH_LEN("???")}; - DBUG_ASSERT(0); - return m_empty_body; - } - virtual MDL_key::enum_mdl_namespace get_mdl_type() const= 0; - virtual const Sp_handler *sp_handler_mysql_proc() const { return this; } - virtual sp_cache **get_cache(THD *) const { return NULL; } -#ifndef NO_EMBEDDED_ACCESS_CHECKS - virtual HASH *get_priv_hash() const { return NULL; } -#endif - virtual ulong recursion_depth(THD *thd) const { return 0; } - /** - Return appropriate error about recursion limit reaching - - @param thd Thread handle - @param sp SP routine - - @remark For functions and triggers we return error about - prohibited recursion. For stored procedures we - return about reaching recursion limit. - */ - virtual void recursion_level_error(THD *thd, const sp_head *sp) const - { - my_error(ER_SP_NO_RECURSION, MYF(0)); - } - virtual bool add_instr_freturn(THD *thd, sp_head *sp, - sp_pcontext *spcont, - Item *item, LEX *lex) const; - virtual bool add_instr_preturn(THD *thd, sp_head *sp, - sp_pcontext *spcont) const; - - void add_used_routine(Query_tables_list *prelocking_ctx, - Query_arena *arena, - const Database_qualified_name *name) const; - - bool sp_resolve_package_routine(THD *thd, - sp_head *caller, - sp_name *name, - const Sp_handler **pkg_routine_handler, - Database_qualified_name *pkgname) const; - virtual sp_head *sp_find_routine(THD *thd, - const Database_qualified_name *name, - bool cache_only) const; - virtual int sp_cache_routine(THD *thd, const Database_qualified_name *name, - bool lookup_only, sp_head **sp) const; - - int sp_cache_routine_reentrant(THD *thd, - const Database_qualified_name *nm, - sp_head **sp) const; - - bool sp_exist_routines(THD *thd, TABLE_LIST *procs) const; - bool sp_show_create_routine(THD *thd, - const Database_qualified_name *name) const; - - bool sp_create_routine(THD *thd, const sp_head *sp) const; - - int sp_update_routine(THD *thd, const Database_qualified_name *name, - const st_sp_chistics *chistics) const; - - int sp_drop_routine(THD *thd, const Database_qualified_name *name) const; - - sp_head *sp_load_for_information_schema(THD *thd, TABLE *proc_table, - const LEX_CSTRING &db, - const LEX_CSTRING &name, - const LEX_CSTRING ¶ms, - const LEX_CSTRING &returns, - sql_mode_t sql_mode, - bool *free_sp_head) const; - - /* - Make a SHOW CREATE statement. - @retval true on error - @retval false on success - */ - virtual bool show_create_sp(THD *thd, String *buf, - const LEX_CSTRING &db, - const LEX_CSTRING &name, - const LEX_CSTRING ¶ms, - const LEX_CSTRING &returns, - const LEX_CSTRING &body, - const st_sp_chistics &chistics, - const AUTHID &definer, - const DDL_options_st ddl_options, - sql_mode_t sql_mode) const; - -}; - - -class Sp_handler_procedure: public Sp_handler -{ -public: - enum_sp_type type() const { return SP_TYPE_PROCEDURE; } - LEX_CSTRING type_lex_cstring() const - { - static LEX_CSTRING m_type_str= { STRING_WITH_LEN("PROCEDURE")}; - return m_type_str; - } - LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const; - const char *show_create_routine_col1_caption() const - { - return "Procedure"; - } - const char *show_create_routine_col3_caption() const - { - return "Create Procedure"; - } - MDL_key::enum_mdl_namespace get_mdl_type() const - { - return MDL_key::PROCEDURE; - } - const Sp_handler *package_routine_handler() const; - sp_cache **get_cache(THD *) const; -#ifndef NO_EMBEDDED_ACCESS_CHECKS - HASH *get_priv_hash() const; -#endif - ulong recursion_depth(THD *thd) const; - void recursion_level_error(THD *thd, const sp_head *sp) const; - bool add_instr_preturn(THD *thd, sp_head *sp, sp_pcontext *spcont) const; -}; - - -class Sp_handler_package_procedure: public Sp_handler_procedure -{ -public: - int sp_cache_routine(THD *thd, const Database_qualified_name *name, - bool lookup_only, sp_head **sp) const - { - return sp_cache_package_routine(thd, name, lookup_only, sp); - } - sp_head *sp_find_routine(THD *thd, - const Database_qualified_name *name, - bool cache_only) const - { - return sp_find_package_routine(thd, name, cache_only); - } -}; - - -class Sp_handler_function: public Sp_handler -{ -public: - enum_sp_type type() const { return SP_TYPE_FUNCTION; } - LEX_CSTRING type_lex_cstring() const - { - static LEX_CSTRING m_type_str= { STRING_WITH_LEN("FUNCTION")}; - return m_type_str; - } - LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const; - const char *show_create_routine_col1_caption() const - { - return "Function"; - } - const char *show_create_routine_col3_caption() const - { - return "Create Function"; - } - MDL_key::enum_mdl_namespace get_mdl_type() const - { - return MDL_key::FUNCTION; - } - const Sp_handler *package_routine_handler() const; - sp_cache **get_cache(THD *) const; -#ifndef NO_EMBEDDED_ACCESS_CHECKS - HASH *get_priv_hash() const; -#endif - bool add_instr_freturn(THD *thd, sp_head *sp, sp_pcontext *spcont, - Item *item, LEX *lex) const; -}; - - -class Sp_handler_package_function: public Sp_handler_function -{ -public: - int sp_cache_routine(THD *thd, const Database_qualified_name *name, - bool lookup_only, sp_head **sp) const - { - return sp_cache_package_routine(thd, name, lookup_only, sp); - } - sp_head *sp_find_routine(THD *thd, - const Database_qualified_name *name, - bool cache_only) const - { - return sp_find_package_routine(thd, name, cache_only); - } -}; - - -class Sp_handler_package: public Sp_handler -{ -public: - bool show_create_sp(THD *thd, String *buf, - const LEX_CSTRING &db, - const LEX_CSTRING &name, - const LEX_CSTRING ¶ms, - const LEX_CSTRING &returns, - const LEX_CSTRING &body, - const st_sp_chistics &chistics, - const AUTHID &definer, - const DDL_options_st ddl_options, - sql_mode_t sql_mode) const; -}; - - -class Sp_handler_package_spec: public Sp_handler_package -{ -public: // TODO: make it private or protected - int sp_find_and_drop_routine(THD *thd, TABLE *table, - const Database_qualified_name *name) - const; -public: - enum_sp_type type() const { return SP_TYPE_PACKAGE; } - LEX_CSTRING type_lex_cstring() const - { - static LEX_CSTRING m_type_str= {STRING_WITH_LEN("PACKAGE")}; - return m_type_str; - } - LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const - { - static LEX_CSTRING m_empty_body= {STRING_WITH_LEN("BEGIN END")}; - return m_empty_body; - } - const char *show_create_routine_col1_caption() const - { - return "Package"; - } - const char *show_create_routine_col3_caption() const - { - return "Create Package"; - } - MDL_key::enum_mdl_namespace get_mdl_type() const - { - return MDL_key::PACKAGE_BODY; - } - sp_cache **get_cache(THD *) const; -#ifndef NO_EMBEDDED_ACCESS_CHECKS - HASH *get_priv_hash() const; -#endif -}; - - -class Sp_handler_package_body: public Sp_handler_package -{ -public: - enum_sp_type type() const { return SP_TYPE_PACKAGE_BODY; } - LEX_CSTRING type_lex_cstring() const - { - static LEX_CSTRING m_type_str= {STRING_WITH_LEN("PACKAGE BODY")}; - return m_type_str; - } - LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const - { - static LEX_CSTRING m_empty_body= {STRING_WITH_LEN("BEGIN END")}; - return m_empty_body; - } - const char *show_create_routine_col1_caption() const - { - return "Package body"; - } - const char *show_create_routine_col3_caption() const - { - return "Create Package Body"; - } - MDL_key::enum_mdl_namespace get_mdl_type() const - { - return MDL_key::PACKAGE_BODY; - } - sp_cache **get_cache(THD *) const; -#ifndef NO_EMBEDDED_ACCESS_CHECKS - HASH *get_priv_hash() const; -#endif -}; - - -class Sp_handler_trigger: public Sp_handler -{ -public: - enum_sp_type type() const { return SP_TYPE_TRIGGER; } - LEX_CSTRING type_lex_cstring() const - { - static LEX_CSTRING m_type_str= { STRING_WITH_LEN("TRIGGER")}; - return m_type_str; - } - MDL_key::enum_mdl_namespace get_mdl_type() const - { - DBUG_ASSERT(0); - return MDL_key::TRIGGER; - } - const Sp_handler *sp_handler_mysql_proc() const { return NULL; } -}; - - -extern MYSQL_PLUGIN_IMPORT Sp_handler_function sp_handler_function; -extern MYSQL_PLUGIN_IMPORT Sp_handler_procedure sp_handler_procedure; -extern MYSQL_PLUGIN_IMPORT Sp_handler_package_spec sp_handler_package_spec; -extern MYSQL_PLUGIN_IMPORT Sp_handler_package_body sp_handler_package_body; -extern MYSQL_PLUGIN_IMPORT Sp_handler_package_function sp_handler_package_function; -extern MYSQL_PLUGIN_IMPORT Sp_handler_package_procedure sp_handler_package_procedure; -extern MYSQL_PLUGIN_IMPORT Sp_handler_trigger sp_handler_trigger; - - -inline const Sp_handler *Sp_handler::handler(enum_sql_command cmd) -{ - switch (cmd) { - case SQLCOM_CREATE_PROCEDURE: - case SQLCOM_ALTER_PROCEDURE: - case SQLCOM_DROP_PROCEDURE: - case SQLCOM_SHOW_PROC_CODE: - case SQLCOM_SHOW_CREATE_PROC: - case SQLCOM_SHOW_STATUS_PROC: - return &sp_handler_procedure; - case SQLCOM_CREATE_SPFUNCTION: - case SQLCOM_ALTER_FUNCTION: - case SQLCOM_DROP_FUNCTION: - case SQLCOM_SHOW_FUNC_CODE: - case SQLCOM_SHOW_CREATE_FUNC: - case SQLCOM_SHOW_STATUS_FUNC: - return &sp_handler_function; - case SQLCOM_CREATE_PACKAGE: - case SQLCOM_DROP_PACKAGE: - case SQLCOM_SHOW_CREATE_PACKAGE: - case SQLCOM_SHOW_STATUS_PACKAGE: - return &sp_handler_package_spec; - case SQLCOM_CREATE_PACKAGE_BODY: - case SQLCOM_DROP_PACKAGE_BODY: - case SQLCOM_SHOW_CREATE_PACKAGE_BODY: - case SQLCOM_SHOW_STATUS_PACKAGE_BODY: - case SQLCOM_SHOW_PACKAGE_BODY_CODE: - return &sp_handler_package_body; - default: - break; - } - return NULL; -} - - -inline const Sp_handler *Sp_handler::handler(enum_sp_type type) -{ - switch (type) { - case SP_TYPE_PROCEDURE: - return &sp_handler_procedure; - case SP_TYPE_FUNCTION: - return &sp_handler_function; - case SP_TYPE_PACKAGE: - return &sp_handler_package_spec; - case SP_TYPE_PACKAGE_BODY: - return &sp_handler_package_body; - case SP_TYPE_TRIGGER: - return &sp_handler_trigger; - case SP_TYPE_EVENT: - break; - } - return NULL; -} - - -inline const Sp_handler *Sp_handler::handler(MDL_key::enum_mdl_namespace type) -{ - switch (type) { - case MDL_key::FUNCTION: - return &sp_handler_function; - case MDL_key::PROCEDURE: - return &sp_handler_procedure; - case MDL_key::PACKAGE_BODY: - return &sp_handler_package_body; - case MDL_key::BACKUP: - case MDL_key::SCHEMA: - case MDL_key::TABLE: - case MDL_key::TRIGGER: - case MDL_key::EVENT: - case MDL_key::USER_LOCK: - case MDL_key::NAMESPACE_END: - break; - } - return NULL; -} - - -/* Tells what SP_DEFAULT_ACCESS should be mapped to */ -#define SP_DEFAULT_ACCESS_MAPPING SP_CONTAINS_SQL - -// Return codes from sp_create_*, sp_drop_*, and sp_show_*: -#define SP_OK 0 -#define SP_KEY_NOT_FOUND -1 -#define SP_OPEN_TABLE_FAILED -2 -#define SP_WRITE_ROW_FAILED -3 -#define SP_DELETE_ROW_FAILED -4 -#define SP_GET_FIELD_FAILED -5 -#define SP_PARSE_ERROR -6 -#define SP_INTERNAL_ERROR -7 -#define SP_NO_DB_ERROR -8 -#define SP_BAD_IDENTIFIER -9 -#define SP_BODY_TOO_LONG -10 -#define SP_FLD_STORE_FAILED -11 - -/* DB storage of Stored PROCEDUREs and FUNCTIONs */ -enum -{ - MYSQL_PROC_FIELD_DB = 0, - MYSQL_PROC_FIELD_NAME, - MYSQL_PROC_MYSQL_TYPE, - MYSQL_PROC_FIELD_SPECIFIC_NAME, - MYSQL_PROC_FIELD_LANGUAGE, - MYSQL_PROC_FIELD_ACCESS, - MYSQL_PROC_FIELD_DETERMINISTIC, - MYSQL_PROC_FIELD_SECURITY_TYPE, - MYSQL_PROC_FIELD_PARAM_LIST, - MYSQL_PROC_FIELD_RETURNS, - MYSQL_PROC_FIELD_BODY, - MYSQL_PROC_FIELD_DEFINER, - MYSQL_PROC_FIELD_CREATED, - MYSQL_PROC_FIELD_MODIFIED, - MYSQL_PROC_FIELD_SQL_MODE, - MYSQL_PROC_FIELD_COMMENT, - MYSQL_PROC_FIELD_CHARACTER_SET_CLIENT, - MYSQL_PROC_FIELD_COLLATION_CONNECTION, - MYSQL_PROC_FIELD_DB_COLLATION, - MYSQL_PROC_FIELD_BODY_UTF8, - MYSQL_PROC_FIELD_AGGREGATE, - MYSQL_PROC_FIELD_COUNT -}; - -/* Drop all routines in database 'db' */ -int -sp_drop_db_routines(THD *thd, const char *db); - -/** - Acquires exclusive metadata lock on all stored routines in the - given database. - - @param thd Thread handler - @param db Database name - - @retval false Success - @retval true Failure - */ -bool lock_db_routines(THD *thd, const char *db); - -/** - Structure that represents element in the set of stored routines - used by statement or routine. -*/ - -class Sroutine_hash_entry -{ -public: - /** - Metadata lock request for routine. - MDL_key in this request is also used as a key for set. - */ - MDL_request mdl_request; - /** - Next element in list linking all routines in set. See also comments - for LEX::sroutine/sroutine_list and sp_head::m_sroutines. - */ - Sroutine_hash_entry *next; - /** - Uppermost view which directly or indirectly uses this routine. - 0 if routine is not used in view. Note that it also can be 0 if - statement uses routine both via view and directly. - */ - TABLE_LIST *belong_to_view; - /** - This is for prepared statement validation purposes. - A statement looks up and pre-loads all its stored functions - at prepare. Later on, if a function is gone from the cache, - execute may fail. - Remember the version of sp_head at prepare to be able to - invalidate the prepared statement at execute if it - changes. - */ - ulong m_sp_cache_version; - - const Sp_handler *m_handler; - - int sp_cache_routine(THD *thd, bool lookup_only, sp_head **sp) const; -}; - - -bool sp_add_used_routine(Query_tables_list *prelocking_ctx, Query_arena *arena, - const MDL_key *key, - const Sp_handler *handler, - TABLE_LIST *belong_to_view); -void sp_remove_not_own_routines(Query_tables_list *prelocking_ctx); -bool sp_update_sp_used_routines(HASH *dst, HASH *src); -void sp_update_stmt_used_routines(THD *thd, Query_tables_list *prelocking_ctx, - HASH *src, TABLE_LIST *belong_to_view); -void sp_update_stmt_used_routines(THD *thd, Query_tables_list *prelocking_ctx, - SQL_I_List *src, - TABLE_LIST *belong_to_view); - -extern "C" uchar* sp_sroutine_key(const uchar *ptr, size_t *plen, - my_bool first); - -/* - Routines which allow open/lock and close mysql.proc table even when - we already have some tables open and locked. -*/ -TABLE *open_proc_table_for_read(THD *thd); - -bool load_charset(MEM_ROOT *mem_root, - Field *field, - CHARSET_INFO *dflt_cs, - CHARSET_INFO **cs); - -bool load_collation(MEM_ROOT *mem_root, - Field *field, - CHARSET_INFO *dflt_cl, - CHARSET_INFO **cl); - -void sp_returns_type(THD *thd, - String &result, - const sp_head *sp); - -#endif /* _SP_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_cache.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_cache.h deleted file mode 100644 index 7506edf..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_cache.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- C++ -*- */ -/* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _SP_CACHE_H_ -#define _SP_CACHE_H_ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -/* - Stored procedures/functions cache. This is used as follows: - * Each thread has its own cache. - * Each sp_head object is put into its thread cache before it is used, and - then remains in the cache until deleted. -*/ - -class sp_head; -class sp_cache; -class Database_qualified_name; - -/* - Cache usage scenarios: - 1. Application-wide init: - sp_cache_init(); - - 2. SP execution in thread: - 2.1 While holding sp_head* pointers: - - // look up a routine in the cache (no checks if it is up to date or not) - sp_cache_lookup(); - - sp_cache_insert(); - sp_cache_invalidate(); - - 2.2 When not holding any sp_head* pointers: - sp_cache_flush_obsolete(); - - 3. Before thread exit: - sp_cache_clear(); -*/ - -void sp_cache_init(); -void sp_cache_end(); -void sp_cache_clear(sp_cache **cp); -void sp_cache_insert(sp_cache **cp, sp_head *sp); -sp_head *sp_cache_lookup(sp_cache **cp, const Database_qualified_name *name); -void sp_cache_invalidate(); -void sp_cache_flush_obsolete(sp_cache **cp, sp_head **sp); -ulong sp_cache_version(); -void sp_cache_enforce_limit(sp_cache *cp, ulong upper_limit_for_elements); - -#endif /* _SP_CACHE_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_head.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_head.h deleted file mode 100644 index 913be1a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_head.h +++ /dev/null @@ -1,2133 +0,0 @@ -/* -*- C++ -*- */ -/* - Copyright (c) 2002, 2011, Oracle and/or its affiliates. - Copyright (c) 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _SP_HEAD_H_ -#define _SP_HEAD_H_ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -/* - It is necessary to include set_var.h instead of item.h because there - are dependencies on include order for set_var.h and item.h. This - will be resolved later. -*/ -#include "sql_class.h" // THD, set_var.h: THD -#include "set_var.h" // Item -#include "sp_pcontext.h" // sp_pcontext -#include -#include "sp.h" - -/** - @defgroup Stored_Routines Stored Routines - @ingroup Runtime_Environment - @{ -*/ - -uint -sp_get_flags_for_command(LEX *lex); - -class sp_instr; -class sp_instr_opt_meta; -class sp_instr_jump_if_not; - -/** - Number of PSI_statement_info instruments - for internal stored programs statements. -*/ -#ifdef HAVE_PSI_INTERFACE -void init_sp_psi_keys(void); -#endif - -/*************************************************************************/ - -/** - Stored_program_creation_ctx -- base class for creation context of stored - programs (stored routines, triggers, events). -*/ - -class Stored_program_creation_ctx :public Default_object_creation_ctx -{ -public: - CHARSET_INFO *get_db_cl() - { - return m_db_cl; - } - -public: - virtual Stored_program_creation_ctx *clone(MEM_ROOT *mem_root) = 0; - -protected: - Stored_program_creation_ctx(THD *thd) - : Default_object_creation_ctx(thd), - m_db_cl(thd->variables.collation_database) - { } - - Stored_program_creation_ctx(CHARSET_INFO *client_cs, - CHARSET_INFO *connection_cl, - CHARSET_INFO *db_cl) - : Default_object_creation_ctx(client_cs, connection_cl), - m_db_cl(db_cl) - { } - -protected: - virtual void change_env(THD *thd) const - { - thd->variables.collation_database= m_db_cl; - - Default_object_creation_ctx::change_env(thd); - } - -protected: - /** - db_cl stores the value of the database collation. Both character set - and collation attributes are used. - - Database collation is included into the context because it defines the - default collation for stored-program variables. - */ - CHARSET_INFO *m_db_cl; -}; - -/*************************************************************************/ - -class sp_name : public Sql_alloc, - public Database_qualified_name -{ -public: - bool m_explicit_name; /**< Prepend the db name? */ - - sp_name(const LEX_CSTRING *db, const LEX_CSTRING *name, - bool use_explicit_name) - : Database_qualified_name(db, name), m_explicit_name(use_explicit_name) - { - if (lower_case_table_names && m_db.str) - m_db.length= my_casedn_str(files_charset_info, (char*) m_db.str); - } - - /** Create temporary sp_name object from MDL key. Store in qname_buff */ - sp_name(const MDL_key *key, char *qname_buff); - - ~sp_name() - {} -}; - - -bool -check_routine_name(const LEX_CSTRING *ident); - -class sp_head :private Query_arena, - public Database_qualified_name, - public Sql_alloc -{ - sp_head(const sp_head &)= delete; - void operator=(sp_head &)= delete; - -protected: - MEM_ROOT main_mem_root; -public: - /** Possible values of m_flags */ - enum { - HAS_RETURN= 1, // For FUNCTIONs only: is set if has RETURN - MULTI_RESULTS= 8, // Is set if a procedure with SELECT(s) - CONTAINS_DYNAMIC_SQL= 16, // Is set if a procedure with PREPARE/EXECUTE - IS_INVOKED= 32, // Is set if this sp_head is being used - HAS_SET_AUTOCOMMIT_STMT= 64,// Is set if a procedure with 'set autocommit' - /* Is set if a procedure with COMMIT (implicit or explicit) | ROLLBACK */ - HAS_COMMIT_OR_ROLLBACK= 128, - LOG_SLOW_STATEMENTS= 256, // Used by events - LOG_GENERAL_LOG= 512, // Used by events - HAS_SQLCOM_RESET= 1024, - HAS_SQLCOM_FLUSH= 2048, - - /** - Marks routines that directly (i.e. not by calling other routines) - change tables. Note that this flag is set automatically based on - type of statements used in the stored routine and is different - from routine characteristic provided by user in a form of CONTAINS - SQL, READS SQL DATA, MODIFIES SQL DATA clauses. The latter are - accepted by parser but pretty much ignored after that. - We don't rely on them: - a) for compatibility reasons. - b) because in CONTAINS SQL case they don't provide enough - information anyway. - */ - MODIFIES_DATA= 4096, - /* - Marks routines that have column type references: DECLARE a t1.a%TYPE; - */ - HAS_COLUMN_TYPE_REFS= 8192, - /* Set if has FETCH GROUP NEXT ROW instr. Used to ensure that only - functions with AGGREGATE keyword use the instr. */ - HAS_AGGREGATE_INSTR= 16384 - }; - - sp_package *m_parent; - const Sp_handler *m_handler; - uint m_flags; // Boolean attributes of a stored routine - - /** - Instrumentation interface for SP. - */ - PSI_sp_share *m_sp_share; - - Column_definition m_return_field_def; /**< This is used for FUNCTIONs only. */ - - const char *m_tmp_query; ///< Temporary pointer to sub query string -private: - /* - Private to guarantee that m_chistics.comment is properly set to: - - a string which is alloced on this->mem_root - - or (NULL,0) - set_chistics() makes sure this. - */ - Sp_chistics m_chistics; - void set_chistics(const st_sp_chistics &chistics); - inline void set_chistics_agg_type(enum enum_sp_aggregate_type type) - { - m_chistics.agg_type= type; - } -public: - sql_mode_t m_sql_mode; ///< For SHOW CREATE and execution - bool m_explicit_name; /**< Prepend the db name? */ - LEX_CSTRING m_qname; ///< db.name - LEX_CSTRING m_params; - LEX_CSTRING m_body; - LEX_CSTRING m_body_utf8; - LEX_CSTRING m_defstr; - AUTHID m_definer; - - const st_sp_chistics &chistics() const { return m_chistics; } - const LEX_CSTRING &comment() const { return m_chistics.comment; } - void set_suid(enum_sp_suid_behaviour suid) { m_chistics.suid= suid; } - enum_sp_suid_behaviour suid() const { return m_chistics.suid; } - bool detistic() const { return m_chistics.detistic; } - enum_sp_data_access daccess() const { return m_chistics.daccess; } - enum_sp_aggregate_type agg_type() const { return m_chistics.agg_type; } - /** - Is this routine being executed? - */ - virtual bool is_invoked() const { return m_flags & IS_INVOKED; } - - /** - Get the value of the SP cache version, as remembered - when the routine was inserted into the cache. - */ - ulong sp_cache_version() const; - - /** Set the value of the SP cache version. */ - void set_sp_cache_version(ulong version_arg) const - { - m_sp_cache_version= version_arg; - } - - sp_rcontext *rcontext_create(THD *thd, Field *retval, List *args); - sp_rcontext *rcontext_create(THD *thd, Field *retval, - Item **args, uint arg_count); - sp_rcontext *rcontext_create(THD *thd, Field *retval, - Row_definition_list *list, - bool switch_security_ctx); - bool eq_routine_spec(const sp_head *) const; -private: - /** - Version of the stored routine cache at the moment when the - routine was added to it. Is used only for functions and - procedures, not used for triggers or events. When sp_head is - created, its version is 0. When it's added to the cache, the - version is assigned the global value 'Cversion'. - If later on Cversion is incremented, we know that the routine - is obsolete and should not be used -- - sp_cache_flush_obsolete() will purge it. - */ - mutable ulong m_sp_cache_version; - Stored_program_creation_ctx *m_creation_ctx; - /** - Boolean combination of (1<clone(mem_root); - } - - longlong m_created; - longlong m_modified; - /** Recursion level of the current SP instance. The levels are numbered from 0 */ - ulong m_recursion_level; - /** - A list of diferent recursion level instances for the same procedure. - For every recursion level we have a sp_head instance. This instances - connected in the list. The list ordered by increasing recursion level - (m_recursion_level). - */ - sp_head *m_next_cached_sp; - /** - Pointer to the first element of the above list - */ - sp_head *m_first_instance; - /** - Pointer to the first free (non-INVOKED) routine in the list of - cached instances for this SP. This pointer is set only for the first - SP in the list of instences (see above m_first_cached_sp pointer). - The pointer equal to 0 if we have no free instances. - For non-first instance value of this pointer meanless (point to itself); - */ - sp_head *m_first_free_instance; - /** - Pointer to the last element in the list of instances of the SP. - For non-first instance value of this pointer meanless (point to itself); - */ - sp_head *m_last_cached_sp; - /** - Set containing names of stored routines used by this routine. - Note that unlike elements of similar set for statement elements of this - set are not linked in one list. Because of this we are able save memory - by using for this set same objects that are used in 'sroutines' sets - for statements of which this stored routine consists. - */ - HASH m_sroutines; - // Pointers set during parsing - const char *m_param_begin; - const char *m_param_end; - -private: - const char *m_body_begin; - -public: - /* - Security context for stored routine which should be run under - definer privileges. - */ - Security_context m_security_ctx; - - /** - List of all items (Item_trigger_field objects) representing fields in - old/new version of row in trigger. We use this list for checking whenever - all such fields are valid at trigger creation time and for binding these - fields to TABLE object at table open (although for latter pointer to table - being opened is probably enough). - */ - SQL_I_List m_trg_table_fields; - -protected: - sp_head(MEM_ROOT *mem_root, sp_package *parent, const Sp_handler *handler, - enum_sp_aggregate_type agg_type); - virtual ~sp_head(); -public: - static void destroy(sp_head *sp); - static sp_head *create(sp_package *parent, const Sp_handler *handler, - enum_sp_aggregate_type agg_type); - - /// Initialize after we have reset mem_root - void - init(LEX *lex); - - /** Copy sp name from parser. */ - void - init_sp_name(const sp_name *spname); - - /** Set the body-definition start position. */ - void - set_body_start(THD *thd, const char *begin_ptr); - - /** Set the statement-definition (body-definition) end position. */ - void - set_stmt_end(THD *thd); - - - bool - execute_trigger(THD *thd, - const LEX_CSTRING *db_name, - const LEX_CSTRING *table_name, - GRANT_INFO *grant_info); - - bool - execute_function(THD *thd, Item **args, uint argcount, Field *return_fld, - sp_rcontext **nctx, Query_arena *call_arena); - - bool - execute_procedure(THD *thd, List *args); - - static void - show_create_routine_get_fields(THD *thd, const Sp_handler *sph, - List *fields); - - bool - show_create_routine(THD *thd, const Sp_handler *sph); - - MEM_ROOT *get_main_mem_root() { return &main_mem_root; } - - int - add_instr(sp_instr *instr); - - bool - add_instr_jump(THD *thd, sp_pcontext *spcont); - - bool - add_instr_jump(THD *thd, sp_pcontext *spcont, uint dest); - - bool - add_instr_jump_forward_with_backpatch(THD *thd, sp_pcontext *spcont, - sp_label *lab); - bool - add_instr_jump_forward_with_backpatch(THD *thd, sp_pcontext *spcont) - { - return add_instr_jump_forward_with_backpatch(thd, spcont, - spcont->last_label()); - } - - bool - add_instr_freturn(THD *thd, sp_pcontext *spcont, Item *item, LEX *lex); - - bool - add_instr_preturn(THD *thd, sp_pcontext *spcont); - - Item *adjust_assignment_source(THD *thd, Item *val, Item *val2); - /** - @param thd - the current thd - @param spcont - the current parse context - @param spv - the SP variable - @param val - the value to be assigned to the variable - @param lex - the LEX that was used to create "val" - @param responsible_to_free_lex - if the generated sp_instr_set should - free "lex". - @retval true - on error - @retval false - on success - */ - bool set_local_variable(THD *thd, sp_pcontext *spcont, - const Sp_rcontext_handler *rh, - sp_variable *spv, Item *val, LEX *lex, - bool responsible_to_free_lex); - bool set_local_variable_row_field(THD *thd, sp_pcontext *spcont, - const Sp_rcontext_handler *rh, - sp_variable *spv, uint field_idx, - Item *val, LEX *lex); - bool set_local_variable_row_field_by_name(THD *thd, sp_pcontext *spcont, - const Sp_rcontext_handler *rh, - sp_variable *spv, - const LEX_CSTRING *field_name, - Item *val, LEX *lex); - bool check_package_routine_end_name(const LEX_CSTRING &end_name) const; - bool check_standalone_routine_end_name(const sp_name *end_name) const; - bool check_group_aggregate_instructions_function() const; - bool check_group_aggregate_instructions_forbid() const; - bool check_group_aggregate_instructions_require() const; -private: - /** - Generate a code to set a single cursor parameter variable. - @param thd - current thd, for mem_root allocations. - @param param_spcont - the context of the parameter block - @param idx - the index of the parameter - @param prm - the actual parameter (contains information about - the assignment source expression Item, - its free list, and its LEX) - */ - bool add_set_cursor_param_variable(THD *thd, - sp_pcontext *param_spcont, uint idx, - sp_assignment_lex *prm) - { - DBUG_ASSERT(idx < param_spcont->context_var_count()); - sp_variable *spvar= param_spcont->get_context_variable(idx); - /* - add_instr() gets free_list from m_thd->free_list. - Initialize it before the set_local_variable() call. - */ - DBUG_ASSERT(m_thd->free_list == NULL); - m_thd->free_list= prm->get_free_list(); - if (set_local_variable(thd, param_spcont, - &sp_rcontext_handler_local, - spvar, prm->get_item(), prm, true)) - return true; - /* - Safety: - The item and its free_list are now fully owned by the sp_instr_set - instance, created by set_local_variable(). The sp_instr_set instance - is now responsible for freeing the item and the free_list. - Reset the "item" and the "free_list" members of "prm", - to avoid double pointers to the same objects from "prm" and - from the sp_instr_set instance. - */ - prm->set_item_and_free_list(NULL, NULL); - return false; - } - - /** - Generate a code to set all cursor parameter variables. - This method is called only when parameters exists, - and the number of formal parameters matches the number of actual - parameters. See also comments to add_open_cursor(). - */ - bool add_set_cursor_param_variables(THD *thd, sp_pcontext *param_spcont, - List *parameters) - { - DBUG_ASSERT(param_spcont->context_var_count() == parameters->elements); - sp_assignment_lex *prm; - List_iterator li(*parameters); - for (uint idx= 0; (prm= li++); idx++) - { - if (add_set_cursor_param_variable(thd, param_spcont, idx, prm)) - return true; - } - return false; - } - - /** - Generate a code to set all cursor parameter variables for a FOR LOOP, e.g.: - FOR index IN cursor(1,2,3) - @param - */ - bool add_set_for_loop_cursor_param_variables(THD *thd, - sp_pcontext *param_spcont, - sp_assignment_lex *param_lex, - Item_args *parameters); - -public: - /** - Generate a code for an "OPEN cursor" statement. - @param thd - current thd, for mem_root allocations - @param spcont - the context of the cursor - @param offset - the offset of the cursor - @param param_spcont - the context of the cursor parameter block - @param parameters - the list of the OPEN actual parameters - - The caller must make sure that the number of local variables - in "param_spcont" (formal parameters) matches the number of list elements - in "parameters" (actual parameters). - NULL in either of them means 0 parameters. - */ - bool add_open_cursor(THD *thd, sp_pcontext *spcont, - uint offset, - sp_pcontext *param_spcont, - List *parameters); - - /** - Generate an initiation code for a CURSOR FOR LOOP, e.g.: - FOR index IN cursor -- cursor without parameters - FOR index IN cursor(1,2,3) -- cursor with parameters - - The code generated by this method does the following during SP run-time: - - Sets all cursor parameter vartiables from "parameters" - - Initializes the index ROW-type variable from the cursor - (the structure is copied from the cursor to the index variable) - - The cursor gets opened - - The first records is fetched from the cursor to the variable "index". - - @param thd - the current thread (for mem_root and error reporting) - @param spcont - the current parse context - @param index - the loop "index" ROW-type variable - @param pcursor - the cursor - @param coffset - the cursor offset - @param param_lex - the LEX that owns Items in "parameters" - @param parameters - the cursor parameters Item array - @retval true - on error (EOM) - @retval false - on success - */ - bool add_for_loop_open_cursor(THD *thd, sp_pcontext *spcont, - sp_variable *index, - const sp_pcursor *pcursor, uint coffset, - sp_assignment_lex *param_lex, - Item_args *parameters); - /** - Returns true if any substatement in the routine directly - (not through another routine) modifies data/changes table. - - @sa Comment for MODIFIES_DATA flag. - */ - bool modifies_data() const - { return m_flags & MODIFIES_DATA; } - - inline uint instructions() - { return m_instr.elements; } - - inline sp_instr * - last_instruction() - { - sp_instr *i; - - get_dynamic(&m_instr, (uchar*)&i, m_instr.elements-1); - return i; - } - - bool replace_instr_to_nop(THD *thd, uint ip); - - /* - Resets lex in 'thd' and keeps a copy of the old one. - - @todo Conflicting comment in sp_head.cc - */ - bool - reset_lex(THD *thd); - - bool - reset_lex(THD *thd, sp_lex_local *sublex); - - /** - Merge two LEX instances. - @param oldlex - the upper level LEX we're going to restore to. - @param sublex - the local lex that have just parsed some substatement. - @returns - false on success, true on error (e.g. failed to - merge the routine list or the table list). - This method is shared by: - - restore_lex(), when the old LEX is popped by sp_head::m_lex.pop() - - THD::restore_from_local_lex_to_old_lex(), when the old LEX - is stored in the caller's local variable. - */ - bool - merge_lex(THD *thd, LEX *oldlex, LEX *sublex); - - /** - Restores lex in 'thd' from our copy, but keeps some status from the - one in 'thd', like ptr, tables, fields, etc. - - @todo Conflicting comment in sp_head.cc - */ - bool - restore_lex(THD *thd) - { - DBUG_ENTER("sp_head::restore_lex"); - LEX *oldlex= (LEX *) m_lex.pop(); - if (!oldlex) - DBUG_RETURN(false); // Nothing to restore - LEX *sublex= thd->lex; - // This restores thd->lex and thd->stmt_lex - if (thd->restore_from_local_lex_to_old_lex(oldlex)) - DBUG_RETURN(true); - if (!sublex->sp_lex_in_use) - { - sublex->sphead= NULL; - lex_end(sublex); - delete sublex; - } - DBUG_RETURN(false); - } - - /// Put the instruction on the backpatch list, associated with the label. - int - push_backpatch(THD *thd, sp_instr *, sp_label *); - int - push_backpatch_goto(THD *thd, sp_pcontext *ctx, sp_label *lab); - - /// Update all instruction with this label in the backpatch list to - /// the current position. - void - backpatch(sp_label *); - void - backpatch_goto(THD *thd, sp_label *, sp_label *); - - /// Check for unresolved goto label - bool - check_unresolved_goto(); - - /// Start a new cont. backpatch level. If 'i' is NULL, the level is just incr. - int - new_cont_backpatch(sp_instr_opt_meta *i); - - /// Add an instruction to the current level - int - add_cont_backpatch(sp_instr_opt_meta *i); - - /// Backpatch (and pop) the current level to the current position. - void - do_cont_backpatch(); - - /// Add cpush instructions for all cursors declared in the current frame - bool sp_add_instr_cpush_for_cursors(THD *thd, sp_pcontext *pcontext); - - const LEX_CSTRING *name() const - { return &m_name; } - - char *create_string(THD *thd, ulong *lenp); - - Field *create_result_field(uint field_max_length, const LEX_CSTRING *field_name, - TABLE *table) const; - - - /** - Check and prepare an instance of Column_definition for field creation - (fill all necessary attributes), for variables, parameters and - function return values. - - @param[in] thd Thread handle - @param[in] lex Yacc parsing context - @param[out] field_def An instance of create_field to be filled - - @retval false on success - @retval true on error - */ - bool fill_field_definition(THD *thd, Column_definition *field_def) - { - const Type_handler *h= field_def->type_handler(); - return h->Column_definition_fix_attributes(field_def) || - field_def->sp_prepare_create_field(thd, mem_root); - } - bool row_fill_field_definitions(THD *thd, Row_definition_list *row) - { - /* - Prepare all row fields. This will (among other things) - - convert VARCHAR lengths from character length to octet length - - calculate interval lengths for SET and ENUM - */ - List_iterator it(*row); - for (Spvar_definition *def= it++; def; def= it++) - { - if (fill_spvar_definition(thd, def)) - return true; - } - return false; - } - /** - Check and prepare a Column_definition for a variable or a parameter. - */ - bool fill_spvar_definition(THD *thd, Column_definition *def) - { - if (fill_field_definition(thd, def)) - return true; - def->pack_flag|= FIELDFLAG_MAYBE_NULL; - return false; - } - bool fill_spvar_definition(THD *thd, Column_definition *def, - LEX_CSTRING *name) - { - def->field_name= *name; - return fill_spvar_definition(thd, def); - } - -private: - /** - Set a column type reference for a parameter definition - */ - void fill_spvar_using_type_reference(sp_variable *spvar, - Qualified_column_ident *ref) - { - spvar->field_def.set_column_type_ref(ref); - spvar->field_def.field_name= spvar->name; - m_flags|= sp_head::HAS_COLUMN_TYPE_REFS; - } - - void fill_spvar_using_table_rowtype_reference(THD *thd, - sp_variable *spvar, - Table_ident *ref) - { - spvar->field_def.set_table_rowtype_ref(ref); - spvar->field_def.field_name= spvar->name; - fill_spvar_definition(thd, &spvar->field_def); - m_flags|= sp_head::HAS_COLUMN_TYPE_REFS; - } - -public: - bool spvar_fill_row(THD *thd, sp_variable *spvar, Row_definition_list *def); - bool spvar_fill_type_reference(THD *thd, sp_variable *spvar, - const LEX_CSTRING &table, - const LEX_CSTRING &column); - bool spvar_fill_type_reference(THD *thd, sp_variable *spvar, - const LEX_CSTRING &db, - const LEX_CSTRING &table, - const LEX_CSTRING &column); - bool spvar_fill_table_rowtype_reference(THD *thd, sp_variable *spvar, - const LEX_CSTRING &table); - bool spvar_fill_table_rowtype_reference(THD *thd, sp_variable *spvar, - const LEX_CSTRING &db, - const LEX_CSTRING &table); - - void set_c_chistics(const st_sp_chistics &chistics); - void set_info(longlong created, longlong modified, - const st_sp_chistics &chistics, sql_mode_t sql_mode); - - void set_definer(const char *definer, size_t definerlen) - { - AUTHID tmp; - tmp.parse(definer, definerlen); - m_definer.copy(mem_root, &tmp.user, &tmp.host); - } - void set_definer(const LEX_CSTRING *user_name, const LEX_CSTRING *host_name) - { - m_definer.copy(mem_root, user_name, host_name); - } - - void reset_thd_mem_root(THD *thd); - - void restore_thd_mem_root(THD *thd); - - /** - Optimize the code. - */ - void optimize(); - - /** - Helper used during flow analysis during code optimization. - See the implementation of opt_mark(). - @param ip the instruction to add to the leads list - @param leads the list of remaining paths to explore in the graph that - represents the code, during flow analysis. - */ - void add_mark_lead(uint ip, List *leads); - - inline sp_instr * - get_instr(uint i) - { - sp_instr *ip; - - if (i < m_instr.elements) - get_dynamic(&m_instr, (uchar*)&ip, i); - else - ip= NULL; - return ip; - } - - /* Add tables used by routine to the table list. */ - bool add_used_tables_to_table_list(THD *thd, - TABLE_LIST ***query_tables_last_ptr, - TABLE_LIST *belong_to_view); - - /** - Check if this stored routine contains statements disallowed - in a stored function or trigger, and set an appropriate error message - if this is the case. - */ - bool is_not_allowed_in_function(const char *where) - { - if (m_flags & CONTAINS_DYNAMIC_SQL) - my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "Dynamic SQL"); - else if (m_flags & MULTI_RESULTS) - my_error(ER_SP_NO_RETSET, MYF(0), where); - else if (m_flags & HAS_SET_AUTOCOMMIT_STMT) - my_error(ER_SP_CANT_SET_AUTOCOMMIT, MYF(0)); - else if (m_flags & HAS_COMMIT_OR_ROLLBACK) - my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); - else if (m_flags & HAS_SQLCOM_RESET) - my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "RESET"); - else if (m_flags & HAS_SQLCOM_FLUSH) - my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "FLUSH"); - - return MY_TEST(m_flags & - (CONTAINS_DYNAMIC_SQL | MULTI_RESULTS | - HAS_SET_AUTOCOMMIT_STMT | HAS_COMMIT_OR_ROLLBACK | - HAS_SQLCOM_RESET | HAS_SQLCOM_FLUSH)); - } - -#ifndef DBUG_OFF - int show_routine_code(THD *thd); -#endif - - /* - This method is intended for attributes of a routine which need - to propagate upwards to the Query_tables_list of the caller (when - a property of a sp_head needs to "taint" the calling statement). - */ - void propagate_attributes(Query_tables_list *prelocking_ctx) - { - DBUG_ENTER("sp_head::propagate_attributes"); - /* - If this routine needs row-based binary logging, the entire top statement - too (we cannot switch from statement-based to row-based only for this - routine, as in statement-based the top-statement may be binlogged and - the substatements not). - */ - DBUG_PRINT("info", ("lex->get_stmt_unsafe_flags(): 0x%x", - prelocking_ctx->get_stmt_unsafe_flags())); - DBUG_PRINT("info", ("sp_head(%p=%s)->unsafe_flags: 0x%x", - this, name()->str, unsafe_flags)); - prelocking_ctx->set_stmt_unsafe_flags(unsafe_flags); - DBUG_VOID_RETURN; - } - - sp_pcontext *get_parse_context() { return m_pcont; } - - /* - Check EXECUTE access: - - in case of a standalone rotuine, for the routine itself - - in case of a package routine, for the owner package body - */ - bool check_execute_access(THD *thd) const; - - virtual sp_package *get_package() - { - return NULL; - } - - virtual void init_psi_share(); - -protected: - - MEM_ROOT *m_thd_root; ///< Temp. store for thd's mem_root - THD *m_thd; ///< Set if we have reset mem_root - - sp_pcontext *m_pcont; ///< Parse context - List m_lex; ///< Temp. store for the other lex - DYNAMIC_ARRAY m_instr; ///< The "instructions" - - enum backpatch_instr_type { GOTO, CPOP, HPOP }; - typedef struct - { - sp_label *lab; - sp_instr *instr; - backpatch_instr_type instr_type; - } bp_t; - List m_backpatch; ///< Instructions needing backpatching - List m_backpatch_goto; // Instructions needing backpatching (for goto) - - /** - We need a special list for backpatching of instructions with a continue - destination (in the case of a continue handler catching an error in - the test), since it would otherwise interfere with the normal backpatch - mechanism - e.g. jump_if_not instructions have two different destinations - which are to be patched differently. - Since these occur in a more restricted way (always the same "level" in - the code), we don't need the label. - */ - List m_cont_backpatch; - uint m_cont_level; // The current cont. backpatch level - - /** - Multi-set representing optimized list of tables to be locked by this - routine. Does not include tables which are used by invoked routines. - - @note - For prelocking-free SPs this multiset is constructed too. - We do so because the same instance of sp_head may be called both - in prelocked mode and in non-prelocked mode. - */ - HASH m_sptabs; - - bool - execute(THD *thd, bool merge_da_on_success); - - /** - Perform a forward flow analysis in the generated code. - Mark reachable instructions, for the optimizer. - */ - void opt_mark(); - - /** - Merge the list of tables used by query into the multi-set of tables used - by routine. - */ - bool merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check); - - /// Put the instruction on the a backpatch list, associated with the label. - int - push_backpatch(THD *thd, sp_instr *, sp_label *, List *list, - backpatch_instr_type itype); - -}; // class sp_head : public Sql_alloc - - -class sp_package: public sp_head -{ - bool validate_public_routines(THD *thd, sp_package *spec); - bool validate_private_routines(THD *thd); -public: - class LexList: public List - { - public: - LexList() { elements= 0; } - // Find a package routine by a non qualified name - LEX *find(const LEX_CSTRING &name, enum_sp_type type); - // Find a package routine by a package-qualified name, e.g. 'pkg.proc' - LEX *find_qualified(const LEX_CSTRING &name, enum_sp_type type); - // Check if a routine with the given qualified name already exists - bool check_dup_qualified(const LEX_CSTRING &name, const Sp_handler *sph) - { - if (!find_qualified(name, sph->type())) - return false; - my_error(ER_SP_ALREADY_EXISTS, MYF(0), sph->type_str(), name.str); - return true; - } - bool check_dup_qualified(const sp_head *sp) - { - return check_dup_qualified(sp->m_name, sp->m_handler); - } - void cleanup(); - }; - /* - The LEX for a new package subroutine is initially assigned to - m_current_routine. After scanning parameters, return type and chistics, - the parser detects if we have a declaration or a definition, e.g.: - PROCEDURE p1(a INT); - vs - PROCEDURE p1(a INT) AS BEGIN NULL; END; - (i.e. either semicolon or the "AS" keyword) - m_current_routine is then added either to m_routine_implementations, - or m_routine_declarations, and then m_current_routine is set to NULL. - */ - LEX *m_current_routine; - LexList m_routine_implementations; - LexList m_routine_declarations; - - LEX *m_top_level_lex; - sp_rcontext *m_rcontext; - uint m_invoked_subroutine_count; - bool m_is_instantiated; - bool m_is_cloning_routine; - -private: - sp_package(MEM_ROOT *mem_root, - LEX *top_level_lex, - const sp_name *name, - const Sp_handler *sph); - ~sp_package(); -public: - static sp_package *create(LEX *top_level_lex, const sp_name *name, - const Sp_handler *sph); - - bool add_routine_declaration(LEX *lex) - { - return m_routine_declarations.check_dup_qualified(lex->sphead) || - m_routine_declarations.push_back(lex, &main_mem_root); - } - bool add_routine_implementation(LEX *lex) - { - return m_routine_implementations.check_dup_qualified(lex->sphead) || - m_routine_implementations.push_back(lex, &main_mem_root); - } - sp_package *get_package() { return this; } - void init_psi_share(); - bool is_invoked() const - { - /* - Cannot flush a package out of the SP cache when: - - its initialization block is running - - one of its subroutine is running - */ - return sp_head::is_invoked() || m_invoked_subroutine_count > 0; - } - sp_variable *find_package_variable(const LEX_CSTRING *name) const - { - /* - sp_head::m_pcont is a special level for routine parameters. - Variables declared inside CREATE PACKAGE BODY reside in m_children.at(0). - */ - sp_pcontext *ctx= m_pcont->child_context(0); - return ctx ? ctx->find_variable(name, true) : NULL; - } - bool validate_after_parser(THD *thd); - bool instantiate_if_needed(THD *thd); -}; - - -class sp_lex_cursor: public sp_lex_local, public Query_arena -{ -public: - sp_lex_cursor(THD *thd, const LEX *oldlex, MEM_ROOT *mem_root_arg) - :sp_lex_local(thd, oldlex), - Query_arena(mem_root_arg, STMT_INITIALIZED_FOR_SP) - { } - sp_lex_cursor(THD *thd, const LEX *oldlex) - :sp_lex_local(thd, oldlex), - Query_arena(thd->lex->sphead->get_main_mem_root(), STMT_INITIALIZED_FOR_SP) - { } - ~sp_lex_cursor() { free_items(); } - void cleanup_stmt() { } - Query_arena *query_arena() { return this; } - bool validate() - { - DBUG_ASSERT(sql_command == SQLCOM_SELECT); - if (result) - { - my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0)); - return true; - } - return false; - } - bool stmt_finalize(THD *thd) - { - if (validate()) - return true; - sp_lex_in_use= true; - free_list= thd->free_list; - thd->free_list= NULL; - return false; - } -}; - - -// -// "Instructions"... -// - -class sp_instr :public Query_arena, public Sql_alloc -{ - sp_instr(const sp_instr &); /**< Prevent use of these */ - void operator=(sp_instr &); - -public: - - uint marked; - uint m_ip; ///< My index - sp_pcontext *m_ctx; ///< My parse context - uint m_lineno; - - /// Should give each a name or type code for debugging purposes? - sp_instr(uint ip, sp_pcontext *ctx) - :Query_arena(0, STMT_INITIALIZED_FOR_SP), marked(0), m_ip(ip), m_ctx(ctx) - {} - - virtual ~sp_instr() - { free_items(); } - - - /** - Execute this instruction - - - @param thd Thread handle - @param[out] nextp index of the next instruction to execute. (For most - instructions this will be the instruction following this - one). Note that this parameter is undefined in case of - errors, use get_cont_dest() to find the continuation - instruction for CONTINUE error handlers. - - @retval 0 on success, - @retval other if some error occurred - */ - - virtual int execute(THD *thd, uint *nextp) = 0; - - /** - Execute open_and_lock_tables() for this statement. - Open and lock the tables used by this statement, as a pre-requisite - to execute the core logic of this instruction with - exec_core(). - @param thd the current thread - @param tables the list of tables to open and lock - @return zero on success, non zero on failure. - */ - int exec_open_and_lock_tables(THD *thd, TABLE_LIST *tables); - - /** - Get the continuation destination of this instruction. - @return the continuation destination - */ - virtual uint get_cont_dest() const; - - /* - Execute core function of instruction after all preparations (e.g. - setting of proper LEX, saving part of the thread context have been - done). - - Should be implemented for instructions using expressions or whole - statements (thus having to have own LEX). Used in concert with - sp_lex_keeper class and its descendants (there are none currently). - */ - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str) = 0; - - virtual void backpatch(uint dest, sp_pcontext *dst_ctx) - {} - - /** - Mark this instruction as reachable during optimization and return the - index to the next instruction. Jump instruction will add their - destination to the leads list. - */ - virtual uint opt_mark(sp_head *sp, List *leads) - { - marked= 1; - return m_ip+1; - } - - /** - Short-cut jumps to jumps during optimization. This is used by the - jump instructions' opt_mark() methods. 'start' is the starting point, - used to prevent the mark sweep from looping for ever. Return the - end destination. - */ - virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) - { - return m_ip; - } - - /** - Inform the instruction that it has been moved during optimization. - Most instructions will simply update its index, but jump instructions - must also take care of their destination pointers. Forward jumps get - pushed to the backpatch list 'ibp'. - */ - virtual void opt_move(uint dst, List *ibp) - { - m_ip= dst; - } - virtual PSI_statement_info* get_psi_info() = 0; - -}; // class sp_instr : public Sql_alloc - - -/** - Auxilary class to which instructions delegate responsibility - for handling LEX and preparations before executing statement - or calculating complex expression. - - Exist mainly to avoid having double hierarchy between instruction - classes. - - @todo - Add ability to not store LEX and do any preparations if - expression used is simple. -*/ - -class sp_lex_keeper -{ - /** Prevent use of these */ - sp_lex_keeper(const sp_lex_keeper &); - void operator=(sp_lex_keeper &); -public: - - sp_lex_keeper(LEX *lex, bool lex_resp) - : m_lex(lex), m_lex_resp(lex_resp), - lex_query_tables_own_last(NULL) - { - lex->sp_lex_in_use= TRUE; - } - virtual ~sp_lex_keeper() - { - if (m_lex_resp) - { - /* Prevent endless recursion. */ - m_lex->sphead= NULL; - lex_end(m_lex); - delete m_lex; - } - } - - /** - Prepare execution of instruction using LEX, if requested check whenever - we have read access to tables used and open/lock them, call instruction's - exec_core() method, perform cleanup afterwards. - - @todo Conflicting comment in sp_head.cc - */ - int reset_lex_and_exec_core(THD *thd, uint *nextp, bool open_tables, - sp_instr* instr); - - int cursor_reset_lex_and_exec_core(THD *thd, uint *nextp, bool open_tables, - sp_instr *instr); - - inline uint sql_command() const - { - return (uint)m_lex->sql_command; - } - - void disable_query_cache() - { - m_lex->safe_to_cache_query= 0; - } - -private: - - LEX *m_lex; - /** - Indicates whenever this sp_lex_keeper instance responsible - for LEX deletion. - */ - bool m_lex_resp; - - /* - Support for being able to execute this statement in two modes: - a) inside prelocked mode set by the calling procedure or its ancestor. - b) outside of prelocked mode, when this statement enters/leaves - prelocked mode itself. - */ - - /** - List of additional tables this statement needs to lock when it - enters/leaves prelocked mode on its own. - */ - TABLE_LIST *prelocking_tables; - - /** - The value m_lex->query_tables_own_last should be set to this when the - statement enters/leaves prelocked mode on its own. - */ - TABLE_LIST **lex_query_tables_own_last; -}; - - -/** - Call out to some prepared SQL statement. -*/ -class sp_instr_stmt : public sp_instr -{ - sp_instr_stmt(const sp_instr_stmt &); /**< Prevent use of these */ - void operator=(sp_instr_stmt &); - -public: - - LEX_STRING m_query; ///< For thd->query - - sp_instr_stmt(uint ip, sp_pcontext *ctx, LEX *lex) - : sp_instr(ip, ctx), m_lex_keeper(lex, TRUE) - { - m_query.str= 0; - m_query.length= 0; - } - - virtual ~sp_instr_stmt() - {}; - - virtual int execute(THD *thd, uint *nextp); - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); - -private: - - sp_lex_keeper m_lex_keeper; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; - -}; // class sp_instr_stmt : public sp_instr - - -class sp_instr_set : public sp_instr -{ - sp_instr_set(const sp_instr_set &); /**< Prevent use of these */ - void operator=(sp_instr_set &); - -public: - - sp_instr_set(uint ip, sp_pcontext *ctx, - const Sp_rcontext_handler *rh, - uint offset, Item *val, - LEX *lex, bool lex_resp) - : sp_instr(ip, ctx), - m_rcontext_handler(rh), m_offset(offset), m_value(val), - m_lex_keeper(lex, lex_resp) - {} - - virtual ~sp_instr_set() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); - -protected: - sp_rcontext *get_rcontext(THD *thd) const; - const Sp_rcontext_handler *m_rcontext_handler; - uint m_offset; ///< Frame offset - Item *m_value; - sp_lex_keeper m_lex_keeper; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_set : public sp_instr - - -/* - This class handles assignments of a ROW fields: - DECLARE rec ROW (a INT,b INT); - SET rec.a= 10; -*/ -class sp_instr_set_row_field : public sp_instr_set -{ - sp_instr_set_row_field(const sp_instr_set_row_field &); // Prevent use of this - void operator=(sp_instr_set_row_field &); - uint m_field_offset; - -public: - - sp_instr_set_row_field(uint ip, sp_pcontext *ctx, - const Sp_rcontext_handler *rh, - uint offset, uint field_offset, - Item *val, - LEX *lex, bool lex_resp) - : sp_instr_set(ip, ctx, rh, offset, val, lex, lex_resp), - m_field_offset(field_offset) - {} - - virtual ~sp_instr_set_row_field() - {} - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); -}; // class sp_instr_set_field : public sp_instr_set - - -/** - This class handles assignment instructions like this: - DECLARE - CURSOR cur IS SELECT * FROM t1; - rec cur%ROWTYPE; - BEGIN - rec.column1:= 10; -- This instruction - END; - - The idea is that during sp_rcontext::create() we do not know the extact - structure of "rec". It gets resolved at run time, during the corresponding - sp_instr_cursor_copy_struct::exec_core(). - - So sp_instr_set_row_field_by_name searches for ROW fields by name, - while sp_instr_set_row_field (see above) searches for ROW fields by index. -*/ -class sp_instr_set_row_field_by_name : public sp_instr_set -{ - // Prevent use of this - sp_instr_set_row_field_by_name(const sp_instr_set_row_field &); - void operator=(sp_instr_set_row_field_by_name &); - const LEX_CSTRING m_field_name; - -public: - - sp_instr_set_row_field_by_name(uint ip, sp_pcontext *ctx, - const Sp_rcontext_handler *rh, - uint offset, const LEX_CSTRING &field_name, - Item *val, - LEX *lex, bool lex_resp) - : sp_instr_set(ip, ctx, rh, offset, val, lex, lex_resp), - m_field_name(field_name) - {} - - virtual ~sp_instr_set_row_field_by_name() - {} - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); -}; // class sp_instr_set_field_by_name : public sp_instr_set - - -/** - Set NEW/OLD row field value instruction. Used in triggers. -*/ -class sp_instr_set_trigger_field : public sp_instr -{ - sp_instr_set_trigger_field(const sp_instr_set_trigger_field &); - void operator=(sp_instr_set_trigger_field &); - -public: - - sp_instr_set_trigger_field(uint ip, sp_pcontext *ctx, - Item_trigger_field *trg_fld, - Item *val, LEX *lex) - : sp_instr(ip, ctx), - trigger_field(trg_fld), - value(val), m_lex_keeper(lex, TRUE) - {} - - virtual ~sp_instr_set_trigger_field() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); - -private: - Item_trigger_field *trigger_field; - Item *value; - sp_lex_keeper m_lex_keeper; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_trigger_field : public sp_instr - - -/** - An abstract class for all instructions with destinations that - needs to be updated by the optimizer. - - Even if not all subclasses will use both the normal destination and - the continuation destination, we put them both here for simplicity. -*/ -class sp_instr_opt_meta : public sp_instr -{ -public: - - uint m_dest; ///< Where we will go - uint m_cont_dest; ///< Where continue handlers will go - - sp_instr_opt_meta(uint ip, sp_pcontext *ctx) - : sp_instr(ip, ctx), - m_dest(0), m_cont_dest(0), m_optdest(0), m_cont_optdest(0) - {} - - sp_instr_opt_meta(uint ip, sp_pcontext *ctx, uint dest) - : sp_instr(ip, ctx), - m_dest(dest), m_cont_dest(0), m_optdest(0), m_cont_optdest(0) - {} - - virtual ~sp_instr_opt_meta() - {} - - virtual void set_destination(uint old_dest, uint new_dest) - = 0; - - virtual uint get_cont_dest() const; - -protected: - - sp_instr *m_optdest; ///< Used during optimization - sp_instr *m_cont_optdest; ///< Used during optimization - -}; // class sp_instr_opt_meta : public sp_instr - -class sp_instr_jump : public sp_instr_opt_meta -{ - sp_instr_jump(const sp_instr_jump &); /**< Prevent use of these */ - void operator=(sp_instr_jump &); - -public: - - sp_instr_jump(uint ip, sp_pcontext *ctx) - : sp_instr_opt_meta(ip, ctx) - {} - - sp_instr_jump(uint ip, sp_pcontext *ctx, uint dest) - : sp_instr_opt_meta(ip, ctx, dest) - {} - - virtual ~sp_instr_jump() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - - virtual uint opt_mark(sp_head *sp, List *leads); - - virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start); - - virtual void opt_move(uint dst, List *ibp); - - virtual void backpatch(uint dest, sp_pcontext *dst_ctx) - { - /* Calling backpatch twice is a logic flaw in jump resolution. */ - DBUG_ASSERT(m_dest == 0); - m_dest= dest; - } - - /** - Update the destination; used by the optimizer. - */ - virtual void set_destination(uint old_dest, uint new_dest) - { - if (m_dest == old_dest) - m_dest= new_dest; - } - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_jump : public sp_instr_opt_meta - - -class sp_instr_jump_if_not : public sp_instr_jump -{ - sp_instr_jump_if_not(const sp_instr_jump_if_not &); /**< Prevent use of these */ - void operator=(sp_instr_jump_if_not &); - -public: - - sp_instr_jump_if_not(uint ip, sp_pcontext *ctx, Item *i, LEX *lex) - : sp_instr_jump(ip, ctx), m_expr(i), - m_lex_keeper(lex, TRUE) - {} - - sp_instr_jump_if_not(uint ip, sp_pcontext *ctx, Item *i, uint dest, LEX *lex) - : sp_instr_jump(ip, ctx, dest), m_expr(i), - m_lex_keeper(lex, TRUE) - {} - - virtual ~sp_instr_jump_if_not() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); - - virtual uint opt_mark(sp_head *sp, List *leads); - - /** Override sp_instr_jump's shortcut; we stop here */ - virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) - { - return m_ip; - } - - virtual void opt_move(uint dst, List *ibp); - - virtual void set_destination(uint old_dest, uint new_dest) - { - sp_instr_jump::set_destination(old_dest, new_dest); - if (m_cont_dest == old_dest) - m_cont_dest= new_dest; - } - -private: - - Item *m_expr; ///< The condition - sp_lex_keeper m_lex_keeper; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_jump_if_not : public sp_instr_jump - - -class sp_instr_preturn : public sp_instr -{ - sp_instr_preturn(const sp_instr_preturn &); /**< Prevent use of these */ - void operator=(sp_instr_preturn &); - -public: - - sp_instr_preturn(uint ip, sp_pcontext *ctx) - : sp_instr(ip, ctx) - {} - - virtual ~sp_instr_preturn() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - - virtual uint opt_mark(sp_head *sp, List *leads) - { - marked= 1; - return UINT_MAX; - } - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_preturn : public sp_instr - - -class sp_instr_freturn : public sp_instr -{ - sp_instr_freturn(const sp_instr_freturn &); /**< Prevent use of these */ - void operator=(sp_instr_freturn &); - -public: - - sp_instr_freturn(uint ip, sp_pcontext *ctx, - Item *val, const Type_handler *handler, LEX *lex) - : sp_instr(ip, ctx), m_value(val), m_type_handler(handler), - m_lex_keeper(lex, TRUE) - {} - - virtual ~sp_instr_freturn() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); - - virtual uint opt_mark(sp_head *sp, List *leads) - { - marked= 1; - return UINT_MAX; - } - -protected: - - Item *m_value; - const Type_handler *m_type_handler; - sp_lex_keeper m_lex_keeper; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_freturn : public sp_instr - - -class sp_instr_hpush_jump : public sp_instr_jump -{ - sp_instr_hpush_jump(const sp_instr_hpush_jump &); /**< Prevent use of these */ - void operator=(sp_instr_hpush_jump &); - -public: - - sp_instr_hpush_jump(uint ip, - sp_pcontext *ctx, - sp_handler *handler) - :sp_instr_jump(ip, ctx), - m_handler(handler), - m_opt_hpop(0), - m_frame(ctx->current_var_count()) - { - DBUG_ASSERT(m_handler->condition_values.elements == 0); - } - - virtual ~sp_instr_hpush_jump() - { - m_handler->condition_values.empty(); - m_handler= NULL; - } - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - - virtual uint opt_mark(sp_head *sp, List *leads); - - /** Override sp_instr_jump's shortcut; we stop here. */ - virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) - { - return m_ip; - } - - virtual void backpatch(uint dest, sp_pcontext *dst_ctx) - { - DBUG_ASSERT(!m_dest || !m_opt_hpop); - if (!m_dest) - m_dest= dest; - else - m_opt_hpop= dest; - } - - void add_condition(sp_condition_value *condition_value) - { m_handler->condition_values.push_back(condition_value); } - - sp_handler *get_handler() - { return m_handler; } - -private: - /// Handler. - sp_handler *m_handler; - - /// hpop marking end of handler scope. - uint m_opt_hpop; - - // This attribute is needed for SHOW PROCEDURE CODE only (i.e. it's needed in - // debug version only). It's used in print(). - uint m_frame; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_hpush_jump : public sp_instr_jump - - -class sp_instr_hpop : public sp_instr -{ - sp_instr_hpop(const sp_instr_hpop &); /**< Prevent use of these */ - void operator=(sp_instr_hpop &); - -public: - - sp_instr_hpop(uint ip, sp_pcontext *ctx, uint count) - : sp_instr(ip, ctx), m_count(count) - {} - - virtual ~sp_instr_hpop() - {} - - void update_count(uint count) - { - m_count= count; - } - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - -private: - - uint m_count; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_hpop : public sp_instr - - -class sp_instr_hreturn : public sp_instr_jump -{ - sp_instr_hreturn(const sp_instr_hreturn &); /**< Prevent use of these */ - void operator=(sp_instr_hreturn &); - -public: - - sp_instr_hreturn(uint ip, sp_pcontext *ctx) - :sp_instr_jump(ip, ctx), - m_frame(ctx->current_var_count()) - {} - - virtual ~sp_instr_hreturn() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - - /* This instruction will not be short cut optimized. */ - virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) - { - return m_ip; - } - - virtual uint opt_mark(sp_head *sp, List *leads); - -private: - - uint m_frame; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_hreturn : public sp_instr_jump - - -/** This is DECLARE CURSOR */ -class sp_instr_cpush : public sp_instr, public sp_cursor -{ - sp_instr_cpush(const sp_instr_cpush &); /**< Prevent use of these */ - void operator=(sp_instr_cpush &); - -public: - - sp_instr_cpush(uint ip, sp_pcontext *ctx, LEX *lex, uint offset) - : sp_instr(ip, ctx), m_lex_keeper(lex, TRUE), m_cursor(offset) - {} - - virtual ~sp_instr_cpush() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - - /** - This call is used to cleanup the instruction when a sensitive - cursor is closed. For now stored procedures always use materialized - cursors and the call is not used. - */ - virtual void cleanup_stmt() { /* no op */ } -private: - - sp_lex_keeper m_lex_keeper; - uint m_cursor; /**< Frame offset (for debugging) */ - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_cpush : public sp_instr - - -class sp_instr_cpop : public sp_instr -{ - sp_instr_cpop(const sp_instr_cpop &); /**< Prevent use of these */ - void operator=(sp_instr_cpop &); - -public: - - sp_instr_cpop(uint ip, sp_pcontext *ctx, uint count) - : sp_instr(ip, ctx), m_count(count) - {} - - virtual ~sp_instr_cpop() - {} - - void update_count(uint count) - { - m_count= count; - } - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - -private: - - uint m_count; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_cpop : public sp_instr - - -class sp_instr_copen : public sp_instr -{ - sp_instr_copen(const sp_instr_copen &); /**< Prevent use of these */ - void operator=(sp_instr_copen &); - -public: - - sp_instr_copen(uint ip, sp_pcontext *ctx, uint c) - : sp_instr(ip, ctx), m_cursor(c) - {} - - virtual ~sp_instr_copen() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); - -private: - - uint m_cursor; ///< Stack index - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_copen : public sp_instr_stmt - - -/** - Initialize the structure of a cursor%ROWTYPE variable - from the LEX containing the cursor SELECT statement. -*/ -class sp_instr_cursor_copy_struct: public sp_instr -{ - /**< Prevent use of these */ - sp_instr_cursor_copy_struct(const sp_instr_cursor_copy_struct &); - void operator=(sp_instr_cursor_copy_struct &); - sp_lex_keeper m_lex_keeper; - uint m_cursor; - uint m_var; -public: - sp_instr_cursor_copy_struct(uint ip, sp_pcontext *ctx, uint coffs, - sp_lex_cursor *lex, uint voffs) - : sp_instr(ip, ctx), m_lex_keeper(lex, FALSE), - m_cursor(coffs), - m_var(voffs) - {} - virtual ~sp_instr_cursor_copy_struct() - {} - virtual int execute(THD *thd, uint *nextp); - virtual int exec_core(THD *thd, uint *nextp); - virtual void print(String *str); - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; - - -class sp_instr_cclose : public sp_instr -{ - sp_instr_cclose(const sp_instr_cclose &); /**< Prevent use of these */ - void operator=(sp_instr_cclose &); - -public: - - sp_instr_cclose(uint ip, sp_pcontext *ctx, uint c) - : sp_instr(ip, ctx), m_cursor(c) - {} - - virtual ~sp_instr_cclose() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - -private: - - uint m_cursor; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_cclose : public sp_instr - - -class sp_instr_cfetch : public sp_instr -{ - sp_instr_cfetch(const sp_instr_cfetch &); /**< Prevent use of these */ - void operator=(sp_instr_cfetch &); - -public: - - sp_instr_cfetch(uint ip, sp_pcontext *ctx, uint c, bool error_on_no_data) - : sp_instr(ip, ctx), m_cursor(c), m_error_on_no_data(error_on_no_data) - { - m_varlist.empty(); - } - - virtual ~sp_instr_cfetch() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - - void add_to_varlist(sp_variable *var) - { - m_varlist.push_back(var); - } - -private: - - uint m_cursor; - List m_varlist; - bool m_error_on_no_data; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_cfetch : public sp_instr - -/* -This class is created for the special fetch instruction -FETCH GROUP NEXT ROW, used in the user-defined aggregate -functions -*/ - -class sp_instr_agg_cfetch : public sp_instr -{ - sp_instr_agg_cfetch(const sp_instr_cfetch &); /**< Prevent use of these */ - void operator=(sp_instr_cfetch &); - -public: - - sp_instr_agg_cfetch(uint ip, sp_pcontext *ctx) - : sp_instr(ip, ctx){} - - virtual ~sp_instr_agg_cfetch() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_agg_cfetch : public sp_instr - - - - -class sp_instr_error : public sp_instr -{ - sp_instr_error(const sp_instr_error &); /**< Prevent use of these */ - void operator=(sp_instr_error &); - -public: - - sp_instr_error(uint ip, sp_pcontext *ctx, int errcode) - : sp_instr(ip, ctx), m_errcode(errcode) - {} - - virtual ~sp_instr_error() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual void print(String *str); - - virtual uint opt_mark(sp_head *sp, List *leads) - { - marked= 1; - return UINT_MAX; - } - -private: - - int m_errcode; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_error : public sp_instr - - -class sp_instr_set_case_expr : public sp_instr_opt_meta -{ -public: - - sp_instr_set_case_expr(uint ip, sp_pcontext *ctx, uint case_expr_id, - Item *case_expr, LEX *lex) - : sp_instr_opt_meta(ip, ctx), - m_case_expr_id(case_expr_id), m_case_expr(case_expr), - m_lex_keeper(lex, TRUE) - {} - - virtual ~sp_instr_set_case_expr() - {} - - virtual int execute(THD *thd, uint *nextp); - - virtual int exec_core(THD *thd, uint *nextp); - - virtual void print(String *str); - - virtual uint opt_mark(sp_head *sp, List *leads); - - virtual void opt_move(uint dst, List *ibp); - - virtual void set_destination(uint old_dest, uint new_dest) - { - if (m_cont_dest == old_dest) - m_cont_dest= new_dest; - } - -private: - - uint m_case_expr_id; - Item *m_case_expr; - sp_lex_keeper m_lex_keeper; - -public: - virtual PSI_statement_info* get_psi_info() { return & psi_info; } - static PSI_statement_info psi_info; -}; // class sp_instr_set_case_expr : public sp_instr_opt_meta - -bool check_show_routine_access(THD *thd, sp_head *sp, bool *full_access); - -#ifndef NO_EMBEDDED_ACCESS_CHECKS -bool -sp_change_security_context(THD *thd, sp_head *sp, - Security_context **backup); -void -sp_restore_security_context(THD *thd, Security_context *backup); - -bool -set_routine_security_ctx(THD *thd, sp_head *sp, Security_context **save_ctx); -#endif /* NO_EMBEDDED_ACCESS_CHECKS */ - -TABLE_LIST * -sp_add_to_query_tables(THD *thd, LEX *lex, - const LEX_CSTRING *db, const LEX_CSTRING *name, - thr_lock_type locktype, - enum_mdl_type mdl_type); - -/** - @} (end of group Stored_Routines) -*/ - -#endif /* _SP_HEAD_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_pcontext.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_pcontext.h deleted file mode 100644 index ffc9c0e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_pcontext.h +++ /dev/null @@ -1,786 +0,0 @@ -/* -*- C++ -*- */ -/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _SP_PCONTEXT_H_ -#define _SP_PCONTEXT_H_ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_string.h" // LEX_STRING -#include "field.h" // Create_field -#include "sql_array.h" // Dynamic_array - - -/// This class represents a stored program variable or a parameter -/// (also referenced as 'SP-variable'). - -class sp_variable : public Sql_alloc -{ -public: - enum enum_mode - { - MODE_IN, - MODE_OUT, - MODE_INOUT - }; - - /// Name of the SP-variable. - LEX_CSTRING name; - - /// Mode of the SP-variable. - enum_mode mode; - - /// The index to the variable's value in the runtime frame. - /// - /// It is calculated during parsing and used when creating sp_instr_set - /// instructions and Item_splocal items. I.e. values are set/referred by - /// array indexing in runtime. - uint offset; - - /// Default value of the SP-variable (if any). - Item *default_value; - - /// Full type information (field meta-data) of the SP-variable. - Spvar_definition field_def; - - /// Field-type of the SP-variable. - const Type_handler *type_handler() const { return field_def.type_handler(); } - -public: - sp_variable(const LEX_CSTRING *name_arg, uint offset_arg) - :Sql_alloc(), - name(*name_arg), - mode(MODE_IN), - offset(offset_arg), - default_value(NULL) - { } - /* - Find a ROW field by its qualified name. - @param var_name - the name of the variable - @param field_name - the name of the variable field - @param[OUT] row_field_offset - the index of the field - - @retval NULL if the variable with the given name was not found, - or it is not a row variable, or it does not have a field - with the given name, or a non-null pointer otherwise. - row_field_offset[0] is set only when the method returns !NULL. - */ - const Spvar_definition *find_row_field(const LEX_CSTRING *var_name, - const LEX_CSTRING *field_name, - uint *row_field_offset); -}; - -/////////////////////////////////////////////////////////////////////////// - -/// This class represents an SQL/PSM label. Can refer to the identifier -/// used with the "label_name:" construct which may precede some SQL/PSM -/// statements, or to an implicit implementation-dependent identifier which -/// the parser inserts before a high-level flow control statement such as -/// IF/WHILE/REPEAT/LOOP, when such statement is rewritten into a -/// combination of low-level jump/jump_if instructions and labels. - - -class sp_label : public Sql_alloc -{ -public: - enum enum_type - { - /// Implicit label generated by parser. - IMPLICIT, - - /// Label at BEGIN. - BEGIN, - - /// Label at iteration control - ITERATION, - - /// Label for jump - GOTO - }; - - /// Name of the label. - LEX_CSTRING name; - - /// Instruction pointer of the label. - uint ip; - - /// Type of the label. - enum_type type; - - /// Scope of the label. - class sp_pcontext *ctx; - -public: - sp_label(const LEX_CSTRING *_name, - uint _ip, enum_type _type, sp_pcontext *_ctx) - :Sql_alloc(), - name(*_name), - ip(_ip), - type(_type), - ctx(_ctx) - { } -}; - - -/////////////////////////////////////////////////////////////////////////// - -/// This class represents condition-value term in DECLARE CONDITION or -/// DECLARE HANDLER statements. sp_condition_value has little to do with -/// SQL-conditions. -/// -/// In some sense, this class is a union -- a set of filled attributes -/// depends on the sp_condition_value::type value. - -class sp_condition_value : public Sql_alloc, public Sql_state_errno -{ - bool m_is_user_defined; -public: - enum enum_type - { - ERROR_CODE, - SQLSTATE, - WARNING, - NOT_FOUND, - EXCEPTION - }; - - /// Type of the condition value. - enum_type type; - -public: - sp_condition_value(uint _mysqlerr) - :Sql_alloc(), - Sql_state_errno(_mysqlerr), - m_is_user_defined(false), - type(ERROR_CODE) - { } - - sp_condition_value(uint _mysqlerr, const char *_sql_state) - :Sql_alloc(), - Sql_state_errno(_mysqlerr, _sql_state), - m_is_user_defined(false), - type(ERROR_CODE) - { } - - sp_condition_value(const char *_sql_state, bool is_user_defined= false) - :Sql_alloc(), - Sql_state_errno(0, _sql_state), - m_is_user_defined(is_user_defined), - type(SQLSTATE) - { } - - sp_condition_value(enum_type _type) - :Sql_alloc(), - m_is_user_defined(false), - type(_type) - { - DBUG_ASSERT(type != ERROR_CODE && type != SQLSTATE); - } - - /// Check if two instances of sp_condition_value are equal or not. - /// - /// @param cv another instance of sp_condition_value to check. - /// - /// @return true if the instances are equal, false otherwise. - bool equals(const sp_condition_value *cv) const; - - - /** - Checks if this condition is OK for search. - See also sp_context::find_handler(). - - @param identity - The condition identity - @param found_cv - A previously found matching condition or NULL. - @return true - If the current value matches identity and - makes a stronger match than the previously - found condition found_cv. - @return false - If the current value does not match identity, - of the current value makes a weaker match than found_cv. - */ - bool matches(const Sql_condition_identity &identity, - const sp_condition_value *found_cv) const; - - Sql_user_condition_identity get_user_condition_identity() const - { - return Sql_user_condition_identity(m_is_user_defined ? this : NULL); - } -}; - - -class sp_condition_value_user_defined: public sp_condition_value -{ -public: - sp_condition_value_user_defined() - :sp_condition_value("45000", true) - { } -}; - - -/////////////////////////////////////////////////////////////////////////// - -/// This class represents 'DECLARE CONDITION' statement. -/// sp_condition has little to do with SQL-conditions. - -class sp_condition : public Sql_alloc -{ -public: - /// Name of the condition. - LEX_CSTRING name; - - /// Value of the condition. - sp_condition_value *value; - -public: - sp_condition(const LEX_CSTRING *name_arg, sp_condition_value *value_arg) - :Sql_alloc(), - name(*name_arg), - value(value_arg) - { } - sp_condition(const char *name_arg, size_t name_length_arg, - sp_condition_value *value_arg) - :value(value_arg) - { - name.str= name_arg; - name.length= name_length_arg; - } - bool eq_name(const LEX_CSTRING *str) const - { - return system_charset_info->strnncoll(name.str, name.length, - str->str, str->length) == 0; - } -}; - - -/////////////////////////////////////////////////////////////////////////// - -/** - class sp_pcursor. - Stores information about a cursor: - - Cursor's name in LEX_STRING. - - Cursor's formal parameter descriptions. - - Formal parameter descriptions reside in a separate context block, - pointed by the "m_param_context" member. - - m_param_context can be NULL. This means a cursor with no parameters. - Otherwise, the number of variables in m_param_context means - the number of cursor's formal parameters. - - Note, m_param_context can be not NULL, but have no variables. - This is also means a cursor with no parameters (similar to NULL). -*/ -class sp_pcursor: public LEX_CSTRING -{ - class sp_pcontext *m_param_context; // Formal parameters - class sp_lex_cursor *m_lex; // The cursor statement LEX -public: - sp_pcursor(const LEX_CSTRING *name, class sp_pcontext *param_ctx, - class sp_lex_cursor *lex) - :LEX_CSTRING(*name), m_param_context(param_ctx), m_lex(lex) - { } - class sp_pcontext *param_context() const { return m_param_context; } - class sp_lex_cursor *lex() const { return m_lex; } - bool check_param_count_with_error(uint param_count) const; -}; - - -/////////////////////////////////////////////////////////////////////////// - -/// This class represents 'DECLARE HANDLER' statement. - -class sp_handler : public Sql_alloc -{ -public: - /// Enumeration of possible handler types. - /// Note: UNDO handlers are not (and have never been) supported. - enum enum_type - { - EXIT, - CONTINUE - }; - - /// Handler type. - enum_type type; - - /// Conditions caught by this handler. - List condition_values; - -public: - /// The constructor. - /// - /// @param _type SQL-handler type. - sp_handler(enum_type _type) - :Sql_alloc(), - type(_type) - { } -}; - -/////////////////////////////////////////////////////////////////////////// - -/// The class represents parse-time context, which keeps track of declared -/// variables/parameters, conditions, handlers, cursors and labels. -/// -/// sp_pcontext objects are organized in a tree according to the following -/// rules: -/// - one sp_pcontext object corresponds for for each BEGIN..END block; -/// - one sp_pcontext object corresponds for each exception handler; -/// - one additional sp_pcontext object is created to contain -/// Stored Program parameters. -/// -/// sp_pcontext objects are used both at parse-time and at runtime. -/// -/// During the parsing stage sp_pcontext objects are used: -/// - to look up defined names (e.g. declared variables and visible -/// labels); -/// - to check for duplicates; -/// - for error checking; -/// - to calculate offsets to be used at runtime. -/// -/// During the runtime phase, a tree of sp_pcontext objects is used: -/// - for error checking (e.g. to check correct number of parameters); -/// - to resolve SQL-handlers. - -class sp_pcontext : public Sql_alloc -{ -public: - enum enum_scope - { - /// REGULAR_SCOPE designates regular BEGIN ... END blocks. - REGULAR_SCOPE, - - /// HANDLER_SCOPE designates SQL-handler blocks. - HANDLER_SCOPE - }; - - class Lex_for_loop: public Lex_for_loop_st - { - public: - Lex_for_loop() { init(); } - }; - -public: - sp_pcontext(); - ~sp_pcontext(); - - - /// Create and push a new context in the tree. - - /// @param thd thread context. - /// @param scope scope of the new parsing context. - /// @return the node created. - sp_pcontext *push_context(THD *thd, enum_scope scope); - - /// Pop a node from the parsing context tree. - /// @return the parent node. - sp_pcontext *pop_context(); - - sp_pcontext *parent_context() const - { return m_parent; } - - sp_pcontext *child_context(uint i) const - { return i < m_children.elements() ? m_children.at(i) : NULL; } - - /// Calculate and return the number of handlers to pop between the given - /// context and this one. - /// - /// @param ctx the other parsing context. - /// @param exclusive specifies if the last scope should be excluded. - /// - /// @return the number of handlers to pop between the given context and - /// this one. If 'exclusive' is true, don't count the last scope we are - /// leaving; this is used for LEAVE where we will jump to the hpop - /// instructions. - uint diff_handlers(const sp_pcontext *ctx, bool exclusive) const; - - /// Calculate and return the number of cursors to pop between the given - /// context and this one. - /// - /// @param ctx the other parsing context. - /// @param exclusive specifies if the last scope should be excluded. - /// - /// @return the number of cursors to pop between the given context and - /// this one. If 'exclusive' is true, don't count the last scope we are - /// leaving; this is used for LEAVE where we will jump to the cpop - /// instructions. - uint diff_cursors(const sp_pcontext *ctx, bool exclusive) const; - - ///////////////////////////////////////////////////////////////////////// - // SP-variables (parameters and variables). - ///////////////////////////////////////////////////////////////////////// - - /// @return the maximum number of variables used in this and all child - /// contexts. For the root parsing context, this gives us the number of - /// slots needed for variables during the runtime phase. - uint max_var_index() const - { return m_max_var_index; } - - /// @return the current number of variables used in the parent contexts - /// (from the root), including this context. - uint current_var_count() const - { return m_var_offset + (uint)m_vars.elements(); } - - /// @return the number of variables in this context alone. - uint context_var_count() const - { return (uint)m_vars.elements(); } - - /// return the i-th variable on the current context - sp_variable *get_context_variable(uint i) const - { - DBUG_ASSERT(i < m_vars.elements()); - return m_vars.at(i); - } - - /* - Return the i-th last context variable. - If i is 0, then return the very last variable in m_vars. - */ - sp_variable *get_last_context_variable(uint i= 0) const - { - DBUG_ASSERT(i < m_vars.elements()); - return m_vars.at(m_vars.elements() - i - 1); - } - - /// Add SP-variable to the parsing context. - /// - /// @param thd Thread context. - /// @param name Name of the SP-variable. - /// - /// @return instance of newly added SP-variable. - sp_variable *add_variable(THD *thd, const LEX_CSTRING *name); - - /// Retrieve full type information about SP-variables in this parsing - /// context and its children. - /// - /// @param field_def_lst[out] Container to store type information. - void retrieve_field_definitions(List *field_def_lst) const; - - /// Find SP-variable by name. - /// - /// The function does a linear search (from newer to older variables, - /// in case we have shadowed names). - /// - /// The function is called only at parsing time. - /// - /// @param name Variable name. - /// @param current_scope_only A flag if we search only in current scope. - /// - /// @return instance of found SP-variable, or NULL if not found. - sp_variable *find_variable(const LEX_CSTRING *name, bool current_scope_only) const; - - /// Find SP-variable by the offset in the root parsing context. - /// - /// The function is used for two things: - /// - When evaluating parameters at the beginning, and setting out parameters - /// at the end, of invocation. (Top frame only, so no recursion then.) - /// - For printing of sp_instr_set. (Debug mode only.) - /// - /// @param offset Variable offset in the root parsing context. - /// - /// @return instance of found SP-variable, or NULL if not found. - sp_variable *find_variable(uint offset) const; - - /// Set the current scope boundary (for default values). - /// - /// @param n The number of variables to skip. - void declare_var_boundary(uint n) - { m_pboundary= n; } - - ///////////////////////////////////////////////////////////////////////// - // CASE expressions. - ///////////////////////////////////////////////////////////////////////// - - int register_case_expr() - { return m_num_case_exprs++; } - - int get_num_case_exprs() const - { return m_num_case_exprs; } - - bool push_case_expr_id(int case_expr_id) - { return m_case_expr_ids.append(case_expr_id); } - - void pop_case_expr_id() - { m_case_expr_ids.pop(); } - - int get_current_case_expr_id() const - { return *m_case_expr_ids.back(); } - - ///////////////////////////////////////////////////////////////////////// - // Labels. - ///////////////////////////////////////////////////////////////////////// - - sp_label *push_label(THD *thd, const LEX_CSTRING *name, uint ip, - sp_label::enum_type type, List * list); - - sp_label *push_label(THD *thd, const LEX_CSTRING *name, uint ip, - sp_label::enum_type type) - { return push_label(thd, name, ip, type, &m_labels); } - - sp_label *push_goto_label(THD *thd, const LEX_CSTRING *name, uint ip, - sp_label::enum_type type) - { return push_label(thd, name, ip, type, &m_goto_labels); } - - sp_label *push_label(THD *thd, const LEX_CSTRING *name, uint ip) - { return push_label(thd, name, ip, sp_label::IMPLICIT); } - - sp_label *push_goto_label(THD *thd, const LEX_CSTRING *name, uint ip) - { return push_goto_label(thd, name, ip, sp_label::GOTO); } - - sp_label *find_label(const LEX_CSTRING *name); - - sp_label *find_goto_label(const LEX_CSTRING *name, bool recusive); - - sp_label *find_goto_label(const LEX_CSTRING *name) - { return find_goto_label(name, true); } - - sp_label *find_label_current_loop_start(); - - sp_label *last_label() - { - sp_label *label= m_labels.head(); - - if (!label && m_parent) - label= m_parent->last_label(); - - return label; - } - - sp_label *last_goto_label() - { - return m_goto_labels.head(); - } - - sp_label *pop_label() - { return m_labels.pop(); } - - bool block_label_declare(LEX_CSTRING *label) - { - sp_label *lab= find_label(label); - if (lab) - { - my_error(ER_SP_LABEL_REDEFINE, MYF(0), label->str); - return true; - } - return false; - } - - ///////////////////////////////////////////////////////////////////////// - // Conditions. - ///////////////////////////////////////////////////////////////////////// - - bool add_condition(THD *thd, const LEX_CSTRING *name, - sp_condition_value *value); - - /// See comment for find_variable() above. - sp_condition_value *find_condition(const LEX_CSTRING *name, - bool current_scope_only) const; - - sp_condition_value * - find_declared_or_predefined_condition(THD *thd, const LEX_CSTRING *name) const; - - bool declare_condition(THD *thd, const LEX_CSTRING *name, - sp_condition_value *val) - { - if (find_condition(name, true)) - { - my_error(ER_SP_DUP_COND, MYF(0), name->str); - return true; - } - return add_condition(thd, name, val); - } - - ///////////////////////////////////////////////////////////////////////// - // Handlers. - ///////////////////////////////////////////////////////////////////////// - - sp_handler *add_handler(THD* thd, sp_handler::enum_type type); - - /// This is an auxilary parsing-time function to check if an SQL-handler - /// exists in the current parsing context (current scope) for the given - /// SQL-condition. This function is used to check for duplicates during - /// the parsing phase. - /// - /// This function can not be used during the runtime phase to check - /// SQL-handler existence because it searches for the SQL-handler in the - /// current scope only (during runtime, current and parent scopes - /// should be checked according to the SQL-handler resolution rules). - /// - /// @param condition_value the handler condition value - /// (not SQL-condition!). - /// - /// @retval true if such SQL-handler exists. - /// @retval false otherwise. - bool check_duplicate_handler(const sp_condition_value *cond_value) const; - - /// Find an SQL handler for the given SQL condition according to the - /// SQL-handler resolution rules. This function is used at runtime. - /// - /// @param value The error code and the SQL state - /// @param level The SQL condition level - /// - /// @return a pointer to the found SQL-handler or NULL. - sp_handler *find_handler(const Sql_condition_identity &identity) const; - - ///////////////////////////////////////////////////////////////////////// - // Cursors. - ///////////////////////////////////////////////////////////////////////// - - bool add_cursor(const LEX_CSTRING *name, sp_pcontext *param_ctx, - class sp_lex_cursor *lex); - - /// See comment for find_variable() above. - const sp_pcursor *find_cursor(const LEX_CSTRING *name, - uint *poff, bool current_scope_only) const; - - const sp_pcursor *find_cursor_with_error(const LEX_CSTRING *name, - uint *poff, - bool current_scope_only) const - { - const sp_pcursor *pcursor= find_cursor(name, poff, current_scope_only); - if (!pcursor) - { - my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str); - return NULL; - } - return pcursor; - } - /// Find cursor by offset (for SHOW {PROCEDURE|FUNCTION} CODE only). - const sp_pcursor *find_cursor(uint offset) const; - - const sp_pcursor *get_cursor_by_local_frame_offset(uint offset) const - { return &m_cursors.at(offset); } - - uint cursor_offset() const - { return m_cursor_offset; } - - uint frame_cursor_count() const - { return (uint)m_cursors.elements(); } - - uint max_cursor_index() const - { return m_max_cursor_index + (uint)m_cursors.elements(); } - - uint current_cursor_count() const - { return m_cursor_offset + (uint)m_cursors.elements(); } - - void set_for_loop(const Lex_for_loop_st &for_loop) - { - m_for_loop.init(for_loop); - } - const Lex_for_loop_st &for_loop() - { - return m_for_loop; - } - -private: - /// Constructor for a tree node. - /// @param prev the parent parsing context - /// @param scope scope of this parsing context - sp_pcontext(sp_pcontext *prev, enum_scope scope); - - void init(uint var_offset, uint cursor_offset, int num_case_expressions); - - /* Prevent use of these */ - sp_pcontext(const sp_pcontext &); - void operator=(sp_pcontext &); - - sp_condition_value *find_predefined_condition(const LEX_CSTRING *name) const; - -private: - /// m_max_var_index -- number of variables (including all types of arguments) - /// in this context including all children contexts. - /// - /// m_max_var_index >= m_vars.elements(). - /// - /// m_max_var_index of the root parsing context contains number of all - /// variables (including arguments) in all enclosed contexts. - uint m_max_var_index; - - /// The maximum sub context's framesizes. - uint m_max_cursor_index; - - /// Parent context. - sp_pcontext *m_parent; - - /// An index of the first SP-variable in this parsing context. The index - /// belongs to a runtime table of SP-variables. - /// - /// Note: - /// - m_var_offset is 0 for root parsing context; - /// - m_var_offset is different for all nested parsing contexts. - uint m_var_offset; - - /// Cursor offset for this context. - uint m_cursor_offset; - - /// Boundary for finding variables in this context. This is the number of - /// variables currently "invisible" to default clauses. This is normally 0, - /// but will be larger during parsing of DECLARE ... DEFAULT, to get the - /// scope right for DEFAULT values. - uint m_pboundary; - - int m_num_case_exprs; - - /// SP parameters/variables. - Dynamic_array m_vars; - - /// Stack of CASE expression ids. - Dynamic_array m_case_expr_ids; - - /// Stack of SQL-conditions. - Dynamic_array m_conditions; - - /// Stack of cursors. - Dynamic_array m_cursors; - - /// Stack of SQL-handlers. - Dynamic_array m_handlers; - - /* - In the below example the label <> has two meanings: - - GOTO lab : must go before the beginning of the loop - - CONTINUE lab : must go to the beginning of the loop - We solve this by storing block labels and goto labels into separate lists. - - BEGIN - <> - FOR i IN a..10 LOOP - ... - GOTO lab; - ... - CONTINUE lab; - ... - END LOOP; - END; - */ - /// List of block labels - List m_labels; - /// List of goto labels - List m_goto_labels; - - /// Children contexts, used for destruction. - Dynamic_array m_children; - - /// Scope of this parsing context. - enum_scope m_scope; - - /// FOR LOOP characteristics - Lex_for_loop m_for_loop; -}; // class sp_pcontext : public Sql_alloc - - -#endif /* _SP_PCONTEXT_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_rcontext.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_rcontext.h deleted file mode 100644 index 0e0e892..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sp_rcontext.h +++ /dev/null @@ -1,407 +0,0 @@ -/* -*- C++ -*- */ -/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _SP_RCONTEXT_H_ -#define _SP_RCONTEXT_H_ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_class.h" // select_result_interceptor -#include "sp_pcontext.h" // sp_condition_value - -/////////////////////////////////////////////////////////////////////////// -// sp_rcontext declaration. -/////////////////////////////////////////////////////////////////////////// - -class sp_cursor; -class sp_lex_keeper; -class sp_instr_cpush; -class sp_instr_hpush_jump; -class Query_arena; -class sp_head; -class Item_cache; -class Virtual_tmp_table; - - -/* - This class is a runtime context of a Stored Routine. It is used in an - execution and is intended to contain all dynamic objects (i.e. objects, which - can be changed during execution), such as: - - stored routine variables; - - cursors; - - handlers; - - Runtime context is used with sp_head class. sp_head class is intended to - contain all static things, related to the stored routines (code, for example). - sp_head instance creates runtime context for the execution of a stored - routine. - - There is a parsing context (an instance of sp_pcontext class), which is used - on parsing stage. However, now it contains some necessary for an execution - things, such as definition of used stored routine variables. That's why - runtime context needs a reference to the parsing context. -*/ - -class sp_rcontext : public Sql_alloc -{ -public: - /// Construct and properly initialize a new sp_rcontext instance. The static - /// create-function is needed because we need a way to return an error from - /// the constructor. - /// - /// @param thd Thread handle. - /// @param root_parsing_ctx Top-level parsing context for this stored program. - /// @param return_value_fld Field object to store the return value - /// (for stored functions only). - /// - /// @return valid sp_rcontext object or NULL in case of OOM-error. - static sp_rcontext *create(THD *thd, - const sp_head *owner, - const sp_pcontext *root_parsing_ctx, - Field *return_value_fld, - Row_definition_list &defs); - - ~sp_rcontext(); - -private: - sp_rcontext(const sp_head *owner, - const sp_pcontext *root_parsing_ctx, - Field *return_value_fld, - bool in_sub_stmt); - - // Prevent use of copying constructor and operator. - sp_rcontext(const sp_rcontext &); - void operator=(sp_rcontext &); - -public: - /// This class stores basic information about SQL-condition, such as: - /// - SQL error code; - /// - error level; - /// - SQLSTATE; - /// - text message. - /// - /// It's used to organize runtime SQL-handler call stack. - /// - /// Standard Sql_condition class can not be used, because we don't always have - /// an Sql_condition object for an SQL-condition in Diagnostics_area. - /// - /// Eventually, this class should be moved to sql_error.h, and be a part of - /// standard SQL-condition processing (Diagnostics_area should contain an - /// object for active SQL-condition, not just information stored in DA's - /// fields). - class Sql_condition_info : public Sql_alloc, - public Sql_condition_identity - { - public: - /// Text message. - char *message; - - /// The constructor. - /// - /// @param _sql_condition The SQL condition. - /// @param arena Query arena for SP - Sql_condition_info(const Sql_condition *_sql_condition, - Query_arena *arena) - :Sql_condition_identity(*_sql_condition) - { - message= strdup_root(arena->mem_root, _sql_condition->get_message_text()); - } - }; - -private: - /// This class represents a call frame of SQL-handler (one invocation of a - /// handler). Basically, it's needed to store continue instruction pointer for - /// CONTINUE SQL-handlers. - class Handler_call_frame : public Sql_alloc - { - public: - /// SQL-condition, triggered handler activation. - const Sql_condition_info *sql_condition; - - /// Continue-instruction-pointer for CONTINUE-handlers. - /// The attribute contains 0 for EXIT-handlers. - uint continue_ip; - - /// The constructor. - /// - /// @param _sql_condition SQL-condition, triggered handler activation. - /// @param _continue_ip Continue instruction pointer. - Handler_call_frame(const Sql_condition_info *_sql_condition, - uint _continue_ip) - :sql_condition(_sql_condition), - continue_ip(_continue_ip) - { } - }; - -public: - /// Arena used to (re) allocate items on. E.g. reallocate INOUT/OUT - /// SP-variables when they don't fit into prealloced items. This is common - /// situation with String items. It is used mainly in sp_eval_func_item(). - Query_arena *callers_arena; - - /// Flag to end an open result set before start executing an SQL-handler - /// (if one is found). Otherwise the client will hang due to a violation - /// of the client/server protocol. - bool end_partial_result_set; - bool pause_state; - bool quit_func; - uint instr_ptr; - - /// The stored program for which this runtime context is created. Used for - /// checking if correct runtime context is used for variable handling, - /// and to access the package run-time context. - /// Also used by slow log. - const sp_head *m_sp; - - ///////////////////////////////////////////////////////////////////////// - // SP-variables. - ///////////////////////////////////////////////////////////////////////// - - uint argument_count() const - { - return m_root_parsing_ctx->context_var_count(); - } - - int set_variable(THD *thd, uint var_idx, Item **value); - int set_variable_row_field(THD *thd, uint var_idx, uint field_idx, - Item **value); - int set_variable_row_field_by_name(THD *thd, uint var_idx, - const LEX_CSTRING &field_name, - Item **value); - int set_variable_row(THD *thd, uint var_idx, List &items); - - int set_parameter(THD *thd, uint var_idx, Item **value) - { - DBUG_ASSERT(var_idx < argument_count()); - return set_variable(thd, var_idx, value); - } - - Item_field *get_variable(uint var_idx) const - { return m_var_items[var_idx]; } - - Item **get_variable_addr(uint var_idx) const - { return ((Item **) m_var_items.array()) + var_idx; } - - Item_field *get_parameter(uint var_idx) const - { - DBUG_ASSERT(var_idx < argument_count()); - return get_variable(var_idx); - } - - bool find_row_field_by_name_or_error(uint *field_idx, uint var_idx, - const LEX_CSTRING &field_name); - - bool set_return_value(THD *thd, Item **return_value_item); - - bool is_return_value_set() const - { return m_return_value_set; } - - ///////////////////////////////////////////////////////////////////////// - // SQL-handlers. - ///////////////////////////////////////////////////////////////////////// - - /// Push an sp_instr_hpush_jump instance to the handler call stack. - /// - /// @param entry The condition handler entry - /// - /// @return error flag. - /// @retval false on success. - /// @retval true on error. - bool push_handler(sp_instr_hpush_jump *entry); - - /// Pop and delete given number of instances from the handler - /// call stack. - /// - /// @param count Number of handler entries to pop & delete. - void pop_handlers(size_t count); - - const Sql_condition_info *raised_condition() const - { - return m_handler_call_stack.elements() ? - (*m_handler_call_stack.back())->sql_condition : NULL; - } - - /// Handle current SQL condition (if any). - /// - /// This is the public-interface function to handle SQL conditions in - /// stored routines. - /// - /// @param thd Thread handle. - /// @param ip[out] Instruction pointer to the first handler - /// instruction. - /// @param cur_spi Current SP instruction. - /// - /// @retval true if an SQL-handler has been activated. That means, all of - /// the following conditions are satisfied: - /// - the SP-instruction raised SQL-condition(s), - /// - and there is an SQL-handler to process at least one of those - /// SQL-conditions, - /// - and that SQL-handler has been activated. - /// Note, that the return value has nothing to do with "error flag" - /// semantics. - /// - /// @retval false otherwise. - bool handle_sql_condition(THD *thd, - uint *ip, - const sp_instr *cur_spi); - - /// Remove latest call frame from the handler call stack. - /// - /// @param da Diagnostics area containing handled conditions. - /// - /// @return continue instruction pointer of the removed handler. - uint exit_handler(Diagnostics_area *da); - - ///////////////////////////////////////////////////////////////////////// - // Cursors. - ///////////////////////////////////////////////////////////////////////// - - /// Push a cursor to the cursor stack. - /// - /// @param cursor The cursor - /// - void push_cursor(sp_cursor *cur); - - void pop_cursor(THD *thd); - /// Pop and delete given number of sp_cursor instance from the cursor stack. - /// - /// @param count Number of cursors to pop & delete. - void pop_cursors(THD *thd, size_t count); - - void pop_all_cursors(THD *thd) - { pop_cursors(thd, m_ccount); } - - sp_cursor *get_cursor(uint i) const - { return m_cstack[i]; } - - ///////////////////////////////////////////////////////////////////////// - // CASE expressions. - ///////////////////////////////////////////////////////////////////////// - - /// Set CASE expression to the specified value. - /// - /// @param thd Thread handler. - /// @param case_expr_id The CASE expression identifier. - /// @param case_expr_item The CASE expression value - /// - /// @return error flag. - /// @retval false on success. - /// @retval true on error. - /// - /// @note The idea is to reuse Item_cache for the expression of the one - /// CASE statement. This optimization takes place when there is CASE - /// statement inside of a loop. So, in other words, we will use the same - /// object on each iteration instead of creating a new one for each - /// iteration. - /// - /// TODO - /// Hypothetically, a type of CASE expression can be different for each - /// iteration. For instance, this can happen if the expression contains - /// a session variable (something like @@VAR) and its type is changed - /// from one iteration to another. - /// - /// In order to cope with this problem, we check type each time, when we - /// use already created object. If the type does not match, we re-create - /// Item. This also can (should?) be optimized. - bool set_case_expr(THD *thd, int case_expr_id, Item **case_expr_item_ptr); - - Item *get_case_expr(int case_expr_id) const - { return m_case_expr_holders[case_expr_id]; } - - Item ** get_case_expr_addr(int case_expr_id) const - { return (Item**) m_case_expr_holders.array() + case_expr_id; } - -private: - /// Internal function to allocate memory for arrays. - /// - /// @param thd Thread handle. - /// - /// @return error flag: false on success, true in case of failure. - bool alloc_arrays(THD *thd); - - /// Create and initialize a table to store SP-variables. - /// - /// param thd Thread handle. - /// - /// @return error flag. - /// @retval false on success. - /// @retval true on error. - bool init_var_table(THD *thd, List &defs); - - /// Create and initialize an Item-adapter (Item_field) for each SP-var field. - /// - /// param thd Thread handle. - /// - /// @return error flag. - /// @retval false on success. - /// @retval true on error. - bool init_var_items(THD *thd, List &defs); - - /// Create an instance of appropriate Item_cache class depending on the - /// specified type in the callers arena. - /// - /// @note We should create cache items in the callers arena, as they are - /// used between in several instructions. - /// - /// @param thd Thread handler. - /// @param item Item to get the expression type. - /// - /// @return Pointer to valid object on success, or NULL in case of error. - Item_cache *create_case_expr_holder(THD *thd, const Item *item) const; - - Virtual_tmp_table *virtual_tmp_table_for_row(uint idx); - -private: - /// Top-level (root) parsing context for this runtime context. - const sp_pcontext *m_root_parsing_ctx; - - /// Virtual table for storing SP-variables. - Virtual_tmp_table *m_var_table; - - /// Collection of Item_field proxies, each of them points to the - /// corresponding field in m_var_table. - Bounds_checked_array m_var_items; - - /// This is a pointer to a field, which should contain return value for - /// stored functions (only). For stored procedures, this pointer is NULL. - Field *m_return_value_fld; - - /// Indicates whether the return value (in m_return_value_fld) has been - /// set during execution. - bool m_return_value_set; - - /// Flag to tell if the runtime context is created for a sub-statement. - bool m_in_sub_stmt; - - /// Stack of visible handlers. - Dynamic_array m_handlers; - - /// Stack of caught SQL conditions. - Dynamic_array m_handler_call_stack; - - /// Stack of cursors. - Bounds_checked_array m_cstack; - - /// Current number of cursors in m_cstack. - uint m_ccount; - - /// Array of CASE expression holders. - Bounds_checked_array m_case_expr_holders; -}; // class sp_rcontext : public Sql_alloc - -#endif /* _SP_RCONTEXT_H_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/span.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/span.h deleted file mode 100644 index 0e85169..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/span.h +++ /dev/null @@ -1,161 +0,0 @@ -/***************************************************************************** - -Copyright (c) 2019, 2020 MariaDB Corporation. - -This program is free software; you can redistribute it and/or modify it under -the terms of the GNU General Public License as published by the Free Software -Foundation; version 2 of the License. - -This program is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License along with -this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA - -*****************************************************************************/ - -#pragma once - -#include -#include - -namespace st_ -{ - -namespace detail -{ - -template struct remove_cv -{ - typedef T type; -}; -template struct remove_cv -{ - typedef T type; -}; -template struct remove_cv -{ - typedef T type; -}; -template struct remove_cv -{ - typedef T type; -}; - -} // namespace detail - -template class span -{ -public: - typedef ElementType element_type; - typedef typename detail::remove_cv::type value_type; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef element_type *pointer; - typedef const element_type *const_pointer; - typedef element_type &reference; - typedef const element_type &const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - typedef std::reverse_iterator reverse_iterator; - - span() : data_(NULL), size_(0) {} - - span(pointer ptr, size_type count) : data_(ptr), size_(count) {} - - span(pointer first, pointer last) : data_(first), size_(last - first) {} - - template span(element_type (&arr)[N]) : data_(arr), size_(N) {} - - template - span(Container &cont) : data_(cont.data()), size_(cont.size()) - { - } - - template - span(const Container &cont) : data_(cont.data()), size_(cont.size()) - { - } - - span(const span &other) : data_(other.data_), size_(other.size_) {} - - ~span(){}; - - span &operator=(const span &other) - { - data_= other.data(); - size_= other.size(); - return *this; - } - - template span first() const - { - assert(!empty()); - return span(data(), 1); - } - template span last() const - { - assert(!empty()); - return span(data() + size() - 1, 1); - } - - span first(size_type count) const - { - assert(!empty()); - return span(data(), 1); - } - span last(size_type count) const - { - assert(!empty()); - return span(data() + size() - 1, 1); - } - span subspan(size_type offset, size_type count) const - { - assert(!empty()); - assert(size() >= offset + count); - return span(data() + offset, count); - } - - size_type size() const { return size_; } - size_type size_bytes() const { return size() * sizeof(ElementType); } - bool empty() const __attribute__((warn_unused_result)) - { - return size() == 0; - } - - reference operator[](size_type idx) const - { - assert(size() > idx); - return data()[idx]; - } - reference front() const - { - assert(!empty()); - return data()[0]; - } - reference back() const - { - assert(!empty()); - return data()[size() - 1]; - } - pointer data() const { return data_; } - - iterator begin() const { return data_; } - iterator end() const { return data_ + size_; } - reverse_iterator rbegin() const - { - return std::reverse_iterator(end()); - } - reverse_iterator rend() const - { - return std::reverse_iterator(begin()); - } - -private: - pointer data_; - size_type size_; -}; - -} // namespace st_ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/spatial.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/spatial.h deleted file mode 100644 index 0b998e2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/spatial.h +++ /dev/null @@ -1,633 +0,0 @@ -/* - Copyright (c) 2002, 2013, Oracle and/or its affiliates. - Copyright (c) 2009, 2013, Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _spatial_h -#define _spatial_h - -#include "sql_string.h" /* String, LEX_STRING */ -#include -#include - -#ifdef HAVE_SPATIAL - -class Gis_read_stream; - -#include "gcalc_tools.h" - -const uint SRID_SIZE= 4; -const uint SIZEOF_STORED_DOUBLE= 8; -const uint POINT_DATA_SIZE= (SIZEOF_STORED_DOUBLE * 2); -const uint WKB_HEADER_SIZE= 1+4; -const uint32 GET_SIZE_ERROR= ((uint32) -1); - -struct st_point_2d -{ - double x; - double y; -}; - -struct st_linear_ring -{ - uint32 n_points; - st_point_2d points; -}; - -/***************************** MBR *******************************/ - - -/* - It's ok that a lot of the functions are inline as these are only used once - in MySQL -*/ - -struct MBR -{ - double xmin, ymin, xmax, ymax; - - MBR() - { - xmin= ymin= DBL_MAX; - xmax= ymax= -DBL_MAX; - } - - MBR(const double xmin_arg, const double ymin_arg, - const double xmax_arg, const double ymax_arg) - :xmin(xmin_arg), ymin(ymin_arg), xmax(xmax_arg), ymax(ymax_arg) - {} - - MBR(const st_point_2d &min, const st_point_2d &max) - :xmin(min.x), ymin(min.y), xmax(max.x), ymax(max.y) - {} - - MBR(const MBR &mbr1, const MBR &mbr2) - :xmin(mbr1.xmin), ymin(mbr1.ymin), xmax(mbr1.xmax), ymax(mbr1.ymax) - { add_mbr(&mbr2); } - - inline void add_xy(double x, double y) - { - /* Not using "else" for proper one point MBR calculation */ - if (x < xmin) - xmin= x; - if (x > xmax) - xmax= x; - if (y < ymin) - ymin= y; - if (y > ymax) - ymax= y; - } - void add_xy(const char *px, const char *py) - { - double x, y; - float8get(x, px); - float8get(y, py); - add_xy(x,y); - } - void add_mbr(const MBR *mbr) - { - if (mbr->xmin < xmin) - xmin= mbr->xmin; - if (mbr->xmax > xmax) - xmax= mbr->xmax; - if (mbr->ymin < ymin) - ymin= mbr->ymin; - if (mbr->ymax > ymax) - ymax= mbr->ymax; - } - void buffer(double d) - { - xmin-= d; - ymin-= d; - xmax+= d; - ymax+= d; - } - - int equals(const MBR *mbr) - { - /* The following should be safe, even if we compare doubles */ - return ((mbr->xmin == xmin) && (mbr->ymin == ymin) && - (mbr->xmax == xmax) && (mbr->ymax == ymax)); - } - - int disjoint(const MBR *mbr) - { - /* The following should be safe, even if we compare doubles */ - return ((mbr->xmin > xmax) || (mbr->ymin > ymax) || - (mbr->xmax < xmin) || (mbr->ymax < ymin)); - } - - int intersects(const MBR *mbr) - { - return !disjoint(mbr); - } - - int touches(const MBR *mbr) - { - /* The following should be safe, even if we compare doubles */ - return ((mbr->xmin == xmax || mbr->xmax == xmin) && - ((mbr->ymin >= ymin && mbr->ymin <= ymax) || - (mbr->ymax >= ymin && mbr->ymax <= ymax))) || - ((mbr->ymin == ymax || mbr->ymax == ymin) && - ((mbr->xmin >= xmin && mbr->xmin <= xmax) || - (mbr->xmax >= xmin && mbr->xmax <= xmax))); - } - - int within(const MBR *mbr); - - int contains(const MBR *mbr) - { - /* The following should be safe, even if we compare doubles */ - return ((mbr->xmin >= xmin) && (mbr->ymin >= ymin) && - (mbr->xmax <= xmax) && (mbr->ymax <= ymax)); - } - - bool inner_point(double x, double y) const - { - /* The following should be safe, even if we compare doubles */ - return (xminx) && (yminy); - } - - /** - The dimension maps to an integer as: - - Polygon -> 2 - - Horizontal or vertical line -> 1 - - Point -> 0 - - Invalid MBR -> -1 - */ - int dimension() const - { - int d= 0; - - if (xmin > xmax) - return -1; - else if (xmin < xmax) - d++; - - if (ymin > ymax) - return -1; - else if (ymin < ymax) - d++; - - return d; - } - - int overlaps(const MBR *mbr) - { - /* - overlaps() requires that some point inside *this is also inside - *mbr, and that both geometries and their intersection are of the - same dimension. - */ - int d = dimension(); - - if (d != mbr->dimension() || d <= 0 || contains(mbr) || within(mbr)) - return 0; - - MBR intersection(MY_MAX(xmin, mbr->xmin), MY_MAX(ymin, mbr->ymin), - MY_MIN(xmax, mbr->xmax), MY_MIN(ymax, mbr->ymax)); - - return (d == intersection.dimension()); - } - - int valid() const - { return xmin <= xmax && ymin <= ymax; } -}; - - -/***************************** Geometry *******************************/ - -struct Geometry_buffer; - -class Geometry -{ -public: - Geometry() {} /* Remove gcc warning */ - virtual ~Geometry() {} /* Remove gcc warning */ - static void *operator new(size_t size, void *buffer) - { - return buffer; - } - - static void operator delete(void *ptr, void *buffer) - {} - - static void operator delete(void *buffer) - {} - - static String bad_geometry_data; - - enum wkbType - { - wkb_point= 1, - wkb_linestring= 2, - wkb_polygon= 3, - wkb_multipoint= 4, - wkb_multilinestring= 5, - wkb_multipolygon= 6, - wkb_geometrycollection= 7, - wkb_last=7 - }; - enum wkbByteOrder - { - wkb_xdr= 0, /* Big Endian */ - wkb_ndr= 1 /* Little Endian */ - }; - enum geojson_errors - { - GEOJ_INCORRECT_GEOJSON= 1, - GEOJ_TOO_FEW_POINTS= 2, - GEOJ_POLYGON_NOT_CLOSED= 3, - GEOJ_DIMENSION_NOT_SUPPORTED= 4, - GEOJ_EMPTY_COORDINATES= 5, - }; - - - /** Callback which creates Geometry objects on top of a given placement. */ - typedef Geometry *(*create_geom_t)(char *); - - class Class_info - { - public: - LEX_STRING m_name; - LEX_STRING m_geojson_name; - int m_type_id; - create_geom_t m_create_func; - Class_info(const char *name, const char *gejson_name, - int type_id, create_geom_t create_func); - }; - - virtual const Class_info *get_class_info() const=0; - virtual uint32 get_data_size() const=0; - virtual bool init_from_wkt(Gis_read_stream *trs, String *wkb)=0; - /* returns the length of the wkb that was read */ - virtual uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, - String *res)=0; - virtual uint init_from_opresult(String *bin, - const char *opres, uint res_len) - { return init_from_wkb(opres + 4, UINT_MAX32, wkb_ndr, bin) + 4; } - virtual bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) - { return true; } - - virtual bool get_data_as_wkt(String *txt, const char **end) const=0; - virtual bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const=0; - virtual bool get_mbr(MBR *mbr, const char **end) const=0; - virtual bool dimension(uint32 *dim, const char **end) const=0; - virtual int get_x(double *x) const { return -1; } - virtual int get_y(double *y) const { return -1; } - virtual int geom_length(double *len, const char **end) const { return -1; } - virtual int area(double *ar, const char **end) const { return -1;} - virtual int is_closed(int *closed) const { return -1; } - virtual int num_interior_ring(uint32 *n_int_rings) const { return -1; } - virtual int num_points(uint32 *n_points) const { return -1; } - virtual int num_geometries(uint32 *num) const { return -1; } - virtual int start_point(String *point) const { return -1; } - virtual int end_point(String *point) const { return -1; } - virtual int exterior_ring(String *ring) const { return -1; } - virtual int centroid(String *point) const { return -1; } - virtual int point_n(uint32 num, String *result) const { return -1; } - virtual int interior_ring_n(uint32 num, String *result) const { return -1; } - virtual int geometry_n(uint32 num, String *result) const { return -1; } - virtual int store_shapes(Gcalc_shape_transporter *trn) const=0; - -public: - static Geometry *create_by_typeid(Geometry_buffer *buffer, int type_id); - - static Geometry *construct(Geometry_buffer *buffer, - const char *data, uint32 data_len); - static Geometry *create_from_wkt(Geometry_buffer *buffer, - Gis_read_stream *trs, String *wkt, - bool init_stream=1); - static Geometry *create_from_wkb(Geometry_buffer *buffer, - const char *wkb, uint32 len, String *res); - static Geometry *create_from_json(Geometry_buffer *buffer, json_engine_t *je, - bool er_on_3D, String *res); - static Geometry *create_from_opresult(Geometry_buffer *g_buf, - String *res, Gcalc_result_receiver &rr); - static uint get_key_image_itMBR(LEX_CSTRING &src, uchar *buff, uint length); - int as_wkt(String *wkt, const char **end); - int as_json(String *wkt, uint max_dec_digits, const char **end); - int bbox_as_json(String *wkt); - - inline void set_data_ptr(const char *data, uint32 data_len) - { - m_data= data; - m_data_end= data + data_len; - } - - inline void shift_wkb_header() - { - m_data+= WKB_HEADER_SIZE; - } - - bool envelope(String *result) const; - static Class_info *ci_collection[wkb_last+1]; - - static bool create_point(String *result, double x, double y); -protected: - static Class_info *find_class(int type_id) - { - return ((type_id < wkb_point) || (type_id > wkb_last)) ? - NULL : ci_collection[type_id]; - } - static Class_info *find_class(const char *name, size_t len); - const char *append_points(String *txt, uint32 n_points, - const char *data, uint32 offset) const; - bool create_point(String *result, const char *data) const; - const char *get_mbr_for_points(MBR *mbr, const char *data, uint offset) - const; - - /** - Check if there're enough data remaining as requested - - @arg cur_data pointer to the position in the binary form - @arg data_amount number of points expected - @return true if not enough data - */ - inline bool no_data(const char *cur_data, size_t data_amount) const - { - return (cur_data + data_amount > m_data_end); - } - - /** - Check if there're enough points remaining as requested - - Need to perform the calculation in logical units, since multiplication - can overflow the size data type. - - @arg data pointer to the beginning of the points array - @arg expected_points number of points expected - @arg extra_point_space extra space for each point element in the array - @return true if there are not enough points - */ - inline bool not_enough_points(const char *data, uint32 expected_points, - uint32 extra_point_space = 0) const - { - return (m_data_end < data || - (expected_points > ((m_data_end - data) / - (POINT_DATA_SIZE + extra_point_space)))); - } - const char *m_data; - const char *m_data_end; -}; - - -/***************************** Point *******************************/ - -class Gis_point: public Geometry -{ -public: - Gis_point() {} /* Remove gcc warning */ - virtual ~Gis_point() {} /* Remove gcc warning */ - uint32 get_data_size() const; - bool init_from_wkt(Gis_read_stream *trs, String *wkb); - uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); - bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb); - bool get_data_as_wkt(String *txt, const char **end) const; - bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const; - bool get_mbr(MBR *mbr, const char **end) const; - - int get_xy(double *x, double *y) const - { - const char *data= m_data; - if (no_data(data, SIZEOF_STORED_DOUBLE * 2)) - return 1; - float8get(*x, data); - float8get(*y, data + SIZEOF_STORED_DOUBLE); - return 0; - } - - int get_x(double *x) const - { - if (no_data(m_data, SIZEOF_STORED_DOUBLE)) - return 1; - float8get(*x, m_data); - return 0; - } - - int get_y(double *y) const - { - const char *data= m_data; - if (no_data(data, SIZEOF_STORED_DOUBLE * 2)) return 1; - float8get(*y, data + SIZEOF_STORED_DOUBLE); - return 0; - } - - int geom_length(double *len, const char **end) const; - int area(double *ar, const char **end) const; - bool dimension(uint32 *dim, const char **end) const - { - *dim= 0; - *end= 0; /* No default end */ - return 0; - } - int store_shapes(Gcalc_shape_transporter *trn) const; - const Class_info *get_class_info() const; -}; - - -/***************************** LineString *******************************/ - -class Gis_line_string: public Geometry -{ -public: - Gis_line_string() {} /* Remove gcc warning */ - virtual ~Gis_line_string() {} /* Remove gcc warning */ - uint32 get_data_size() const; - bool init_from_wkt(Gis_read_stream *trs, String *wkb); - uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); - bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb); - bool get_data_as_wkt(String *txt, const char **end) const; - bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const; - bool get_mbr(MBR *mbr, const char **end) const; - int geom_length(double *len, const char **end) const; - int area(double *ar, const char **end) const; - int is_closed(int *closed) const; - int num_points(uint32 *n_points) const; - int start_point(String *point) const; - int end_point(String *point) const; - int point_n(uint32 n, String *result) const; - bool dimension(uint32 *dim, const char **end) const - { - *dim= 1; - *end= 0; /* No default end */ - return 0; - } - int store_shapes(Gcalc_shape_transporter *trn) const; - const Class_info *get_class_info() const; -}; - - -/***************************** Polygon *******************************/ - -class Gis_polygon: public Geometry -{ -public: - Gis_polygon() {} /* Remove gcc warning */ - virtual ~Gis_polygon() {} /* Remove gcc warning */ - uint32 get_data_size() const; - bool init_from_wkt(Gis_read_stream *trs, String *wkb); - uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); - uint init_from_opresult(String *bin, const char *opres, uint res_len); - bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb); - bool get_data_as_wkt(String *txt, const char **end) const; - bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const; - bool get_mbr(MBR *mbr, const char **end) const; - int area(double *ar, const char **end) const; - int exterior_ring(String *result) const; - int num_interior_ring(uint32 *n_int_rings) const; - int interior_ring_n(uint32 num, String *result) const; - int centroid_xy(double *x, double *y) const; - int centroid(String *result) const; - bool dimension(uint32 *dim, const char **end) const - { - *dim= 2; - *end= 0; /* No default end */ - return 0; - } - int store_shapes(Gcalc_shape_transporter *trn) const; - const Class_info *get_class_info() const; -}; - - -/***************************** MultiPoint *******************************/ - -class Gis_multi_point: public Geometry -{ - // Maximum number of points in MultiPoint that can fit into String - static const uint32 max_n_points= - (uint32) (UINT_MAX32 - WKB_HEADER_SIZE - 4 /* n_points */) / - (WKB_HEADER_SIZE + POINT_DATA_SIZE); -public: - Gis_multi_point() {} /* Remove gcc warning */ - virtual ~Gis_multi_point() {} /* Remove gcc warning */ - uint32 get_data_size() const; - bool init_from_wkt(Gis_read_stream *trs, String *wkb); - uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); - uint init_from_opresult(String *bin, const char *opres, uint res_len); - bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb); - bool get_data_as_wkt(String *txt, const char **end) const; - bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const; - bool get_mbr(MBR *mbr, const char **end) const; - int num_geometries(uint32 *num) const; - int geometry_n(uint32 num, String *result) const; - bool dimension(uint32 *dim, const char **end) const - { - *dim= 0; - *end= 0; /* No default end */ - return 0; - } - int store_shapes(Gcalc_shape_transporter *trn) const; - const Class_info *get_class_info() const; -}; - - -/***************************** MultiLineString *******************************/ - -class Gis_multi_line_string: public Geometry -{ -public: - Gis_multi_line_string() {} /* Remove gcc warning */ - virtual ~Gis_multi_line_string() {} /* Remove gcc warning */ - uint32 get_data_size() const; - bool init_from_wkt(Gis_read_stream *trs, String *wkb); - uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); - uint init_from_opresult(String *bin, const char *opres, uint res_len); - bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb); - bool get_data_as_wkt(String *txt, const char **end) const; - bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const; - bool get_mbr(MBR *mbr, const char **end) const; - int num_geometries(uint32 *num) const; - int geometry_n(uint32 num, String *result) const; - int geom_length(double *len, const char **end) const; - int is_closed(int *closed) const; - bool dimension(uint32 *dim, const char **end) const - { - *dim= 1; - *end= 0; /* No default end */ - return 0; - } - int store_shapes(Gcalc_shape_transporter *trn) const; - const Class_info *get_class_info() const; -}; - - -/***************************** MultiPolygon *******************************/ - -class Gis_multi_polygon: public Geometry -{ -public: - Gis_multi_polygon() {} /* Remove gcc warning */ - virtual ~Gis_multi_polygon() {} /* Remove gcc warning */ - uint32 get_data_size() const; - bool init_from_wkt(Gis_read_stream *trs, String *wkb); - uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); - bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb); - bool get_data_as_wkt(String *txt, const char **end) const; - bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const; - bool get_mbr(MBR *mbr, const char **end) const; - int num_geometries(uint32 *num) const; - int geometry_n(uint32 num, String *result) const; - int area(double *ar, const char **end) const; - int centroid(String *result) const; - bool dimension(uint32 *dim, const char **end) const - { - *dim= 2; - *end= 0; /* No default end */ - return 0; - } - int store_shapes(Gcalc_shape_transporter *trn) const; - const Class_info *get_class_info() const; - uint init_from_opresult(String *bin, const char *opres, uint res_len); -}; - - -/*********************** GeometryCollection *******************************/ - -class Gis_geometry_collection: public Geometry -{ -public: - Gis_geometry_collection() {} /* Remove gcc warning */ - virtual ~Gis_geometry_collection() {} /* Remove gcc warning */ - uint32 get_data_size() const; - bool init_from_wkt(Gis_read_stream *trs, String *wkb); - uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res); - uint init_from_opresult(String *bin, const char *opres, uint res_len); - bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb); - bool get_data_as_wkt(String *txt, const char **end) const; - bool get_data_as_json(String *txt, uint max_dec_digits, - const char **end) const; - bool get_mbr(MBR *mbr, const char **end) const; - int area(double *ar, const char **end) const; - int geom_length(double *len, const char **end) const; - int num_geometries(uint32 *num) const; - int geometry_n(uint32 num, String *result) const; - bool dimension(uint32 *dim, const char **end) const; - int store_shapes(Gcalc_shape_transporter *trn) const; - const Class_info *get_class_info() const; -}; - -struct Geometry_buffer : public - my_aligned_storage {}; - -#endif /*HAVE_SPATIAL*/ -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_acl.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_acl.h deleted file mode 100644 index 570da14..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_acl.h +++ /dev/null @@ -1,376 +0,0 @@ -#ifndef SQL_ACL_INCLUDED -#define SQL_ACL_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "violite.h" /* SSL_type */ -#include "sql_class.h" /* LEX_COLUMN */ -#include "grant.h" -#include "sql_cmd.h" /* Sql_cmd */ - - -enum mysql_db_table_field -{ - MYSQL_DB_FIELD_HOST = 0, - MYSQL_DB_FIELD_DB, - MYSQL_DB_FIELD_USER, - MYSQL_DB_FIELD_SELECT_PRIV, - MYSQL_DB_FIELD_INSERT_PRIV, - MYSQL_DB_FIELD_UPDATE_PRIV, - MYSQL_DB_FIELD_DELETE_PRIV, - MYSQL_DB_FIELD_CREATE_PRIV, - MYSQL_DB_FIELD_DROP_PRIV, - MYSQL_DB_FIELD_GRANT_PRIV, - MYSQL_DB_FIELD_REFERENCES_PRIV, - MYSQL_DB_FIELD_INDEX_PRIV, - MYSQL_DB_FIELD_ALTER_PRIV, - MYSQL_DB_FIELD_CREATE_TMP_TABLE_PRIV, - MYSQL_DB_FIELD_LOCK_TABLES_PRIV, - MYSQL_DB_FIELD_CREATE_VIEW_PRIV, - MYSQL_DB_FIELD_SHOW_VIEW_PRIV, - MYSQL_DB_FIELD_CREATE_ROUTINE_PRIV, - MYSQL_DB_FIELD_ALTER_ROUTINE_PRIV, - MYSQL_DB_FIELD_EXECUTE_PRIV, - MYSQL_DB_FIELD_EVENT_PRIV, - MYSQL_DB_FIELD_TRIGGER_PRIV, - MYSQL_DB_FIELD_DELETE_VERSIONING_ROWS_PRIV, - MYSQL_DB_FIELD_COUNT -}; - -extern const TABLE_FIELD_DEF mysql_db_table_def; -extern bool mysql_user_table_is_in_short_password_format; - -extern LEX_CSTRING host_not_specified; -extern LEX_CSTRING current_user; -extern LEX_CSTRING current_role; -extern LEX_CSTRING current_user_and_current_role; - - -static inline int access_denied_error_code(int passwd_used) -{ -#ifdef mysqld_error_find_printf_error_used - return 0; -#else - return passwd_used == 2 ? ER_ACCESS_DENIED_NO_PASSWORD_ERROR - : ER_ACCESS_DENIED_ERROR; -#endif -} - -/* prototypes */ - -bool hostname_requires_resolving(const char *hostname); -bool acl_init(bool dont_read_acl_tables); -bool acl_reload(THD *thd); -void acl_free(bool end=0); -privilege_t acl_get(const char *host, const char *ip, - const char *user, const char *db, my_bool db_is_pattern); -bool acl_authenticate(THD *thd, uint com_change_user_pkt_len); -bool acl_getroot(Security_context *sctx, const char *user, const char *host, - const char *ip, const char *db); -bool acl_check_host(const char *host, const char *ip); -bool check_change_password(THD *thd, LEX_USER *user); -bool change_password(THD *thd, LEX_USER *user); - -bool mysql_grant_role(THD *thd, List &user_list, bool revoke); -bool mysql_grant(THD *thd, const char *db, List &user_list, - privilege_t rights, bool revoke, bool is_proxy); -int mysql_table_grant(THD *thd, TABLE_LIST *table, List &user_list, - List &column_list, privilege_t rights, - bool revoke); -bool mysql_routine_grant(THD *thd, TABLE_LIST *table, const Sp_handler *sph, - List &user_list, privilege_t rights, - bool revoke, bool write_to_binlog); -bool grant_init(); -void grant_free(void); -bool grant_reload(THD *thd); -bool check_grant(THD *thd, privilege_t want_access, TABLE_LIST *tables, - bool any_combination_will_do, uint number, bool no_errors); -bool check_grant_column (THD *thd, GRANT_INFO *grant, - const char *db_name, const char *table_name, - const char *name, size_t length, Security_context *sctx); -bool check_column_grant_in_table_ref(THD *thd, TABLE_LIST * table_ref, - const char *name, size_t length, Field *fld); -bool check_grant_all_columns(THD *thd, privilege_t want_access, - Field_iterator_table_ref *fields); -bool check_grant_routine(THD *thd, privilege_t want_access, - TABLE_LIST *procs, const Sp_handler *sph, - bool no_error); -bool check_grant_db(THD *thd,const char *db); -bool check_global_access(THD *thd, const privilege_t want_access, bool no_errors= false); -bool check_access(THD *thd, privilege_t want_access, - const char *db, privilege_t *save_priv, - GRANT_INTERNAL_INFO *grant_internal_info, - bool dont_check_global_grants, bool no_errors); -privilege_t get_table_grant(THD *thd, TABLE_LIST *table); -privilege_t get_column_grant(THD *thd, GRANT_INFO *grant, - const char *db_name, const char *table_name, - const char *field_name); -bool get_show_user(THD *thd, LEX_USER *lex_user, const char **username, - const char **hostname, const char **rolename); -void mysql_show_grants_get_fields(THD *thd, List *fields, - const char *name, size_t length); -bool mysql_show_grants(THD *thd, LEX_USER *user); -bool mysql_show_create_user(THD *thd, LEX_USER *user); -int fill_schema_enabled_roles(THD *thd, TABLE_LIST *tables, COND *cond); -int fill_schema_applicable_roles(THD *thd, TABLE_LIST *tables, COND *cond); -void get_privilege_desc(char *to, uint max_length, privilege_t access); -void get_mqh(const char *user, const char *host, USER_CONN *uc); -bool mysql_create_user(THD *thd, List &list, bool handle_as_role); -bool mysql_drop_user(THD *thd, List &list, bool handle_as_role); -bool mysql_rename_user(THD *thd, List &list); -int mysql_alter_user(THD *thd, List &list); -bool mysql_revoke_all(THD *thd, List &list); -void fill_effective_table_privileges(THD *thd, GRANT_INFO *grant, - const char *db, const char *table); -bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name, - const Sp_handler *sph); -bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name, - const Sp_handler *sph); -bool check_routine_level_acl(THD *thd, const char *db, const char *name, - const Sp_handler *sph); -bool is_acl_user(const char *host, const char *user); -int fill_schema_user_privileges(THD *thd, TABLE_LIST *tables, COND *cond); -int fill_schema_schema_privileges(THD *thd, TABLE_LIST *tables, COND *cond); -int fill_schema_table_privileges(THD *thd, TABLE_LIST *tables, COND *cond); -int fill_schema_column_privileges(THD *thd, TABLE_LIST *tables, COND *cond); -int wild_case_compare(CHARSET_INFO *cs, const char *str,const char *wildstr); - -/** - Result of an access check for an internal schema or table. - Internal ACL checks are always performed *before* using - the grant tables. - This mechanism enforces that the server implementation has full - control on its internal tables. - Depending on the internal check result, the server implementation - can choose to: - - always allow access, - - always deny access, - - delegate the decision to the database administrator, - by using the grant tables. -*/ -enum ACL_internal_access_result -{ - /** - Access granted for all the requested privileges, - do not use the grant tables. - */ - ACL_INTERNAL_ACCESS_GRANTED, - /** Access denied, do not use the grant tables. */ - ACL_INTERNAL_ACCESS_DENIED, - /** No decision yet, use the grant tables. */ - ACL_INTERNAL_ACCESS_CHECK_GRANT -}; - -/** - Per internal table ACL access rules. - This class is an interface. - Per table(s) specific access rule should be implemented in a subclass. - @sa ACL_internal_schema_access -*/ -class ACL_internal_table_access -{ -public: - ACL_internal_table_access() - {} - - virtual ~ACL_internal_table_access() - {} - - /** - Check access to an internal table. - When a privilege is granted, this method add the requested privilege - to save_priv. - @param want_access the privileges requested - @param [in, out] save_priv the privileges granted - @return - @retval ACL_INTERNAL_ACCESS_GRANTED All the requested privileges - are granted, and saved in save_priv. - @retval ACL_INTERNAL_ACCESS_DENIED At least one of the requested - privileges was denied. - @retval ACL_INTERNAL_ACCESS_CHECK_GRANT No requested privilege - was denied, and grant should be checked for at least one - privilege. Requested privileges that are granted, if any, are saved - in save_priv. - */ - virtual ACL_internal_access_result check(privilege_t want_access, - privilege_t *save_priv) const= 0; -}; - -/** - Per internal schema ACL access rules. - This class is an interface. - Each per schema specific access rule should be implemented - in a different subclass, and registered. - Per schema access rules can control: - - every schema privileges on schema.* - - every table privileges on schema.table - @sa ACL_internal_schema_registry -*/ -class ACL_internal_schema_access -{ -public: - ACL_internal_schema_access() - {} - - virtual ~ACL_internal_schema_access() - {} - - /** - Check access to an internal schema. - @param want_access the privileges requested - @param [in, out] save_priv the privileges granted - @return - @retval ACL_INTERNAL_ACCESS_GRANTED All the requested privileges - are granted, and saved in save_priv. - @retval ACL_INTERNAL_ACCESS_DENIED At least one of the requested - privileges was denied. - @retval ACL_INTERNAL_ACCESS_CHECK_GRANT No requested privilege - was denied, and grant should be checked for at least one - privilege. Requested privileges that are granted, if any, are saved - in save_priv. - */ - virtual ACL_internal_access_result check(privilege_t want_access, - privilege_t *save_priv) const= 0; - - /** - Search for per table ACL access rules by table name. - @param name the table name - @return per table access rules, or NULL - */ - virtual const ACL_internal_table_access *lookup(const char *name) const= 0; -}; - -/** - A registry for per internal schema ACL. - An 'internal schema' is a database schema maintained by the - server implementation, such as 'performance_schema' and 'INFORMATION_SCHEMA'. -*/ -class ACL_internal_schema_registry -{ -public: - static void register_schema(const LEX_CSTRING *name, - const ACL_internal_schema_access *access); - static const ACL_internal_schema_access *lookup(const char *name); -}; - -const ACL_internal_schema_access * -get_cached_schema_access(GRANT_INTERNAL_INFO *grant_internal_info, - const char *schema_name); - -const ACL_internal_table_access * -get_cached_table_access(GRANT_INTERNAL_INFO *grant_internal_info, - const char *schema_name, - const char *table_name); - -bool acl_check_proxy_grant_access (THD *thd, const char *host, const char *user, - bool with_grant); -int acl_setrole(THD *thd, const char *rolename, privilege_t access); -int acl_check_setrole(THD *thd, const char *rolename, privilege_t *access); -int acl_check_set_default_role(THD *thd, const char *host, const char *user, - const char *role); -int acl_set_default_role(THD *thd, const char *host, const char *user, - const char *rolename); - -extern SHOW_VAR acl_statistics[]; - -/* Check if a role is granted to a user/role. - - If hostname == NULL, search for a role as the starting grantee. -*/ -bool check_role_is_granted(const char *username, - const char *hostname, - const char *rolename); - -#ifndef DBUG_OFF -extern ulong role_global_merges, role_db_merges, role_table_merges, - role_column_merges, role_routine_merges; -#endif - - -class Sql_cmd_grant: public Sql_cmd -{ -protected: - enum_sql_command m_command; -#ifndef NO_EMBEDDED_ACCESS_CHECKS - void warn_hostname_requires_resolving(THD *thd, List &list); - bool user_list_reset_mqh(THD *thd, List &list); - void grant_stage0(THD *thd); -#endif -public: - Sql_cmd_grant(enum_sql_command command) - :m_command(command) - { } - bool is_revoke() const { return m_command == SQLCOM_REVOKE; } - enum_sql_command sql_command_code() const { return m_command; } -}; - - -class Sql_cmd_grant_proxy: public Sql_cmd_grant -{ - privilege_t m_grant_option; -#ifndef NO_EMBEDDED_ACCESS_CHECKS - bool check_access_proxy(THD *thd, List &list); -#endif -public: - Sql_cmd_grant_proxy(enum_sql_command command, privilege_t grant_option) - :Sql_cmd_grant(command), m_grant_option(grant_option) - { } - bool execute(THD *thd); -}; - - -class Sql_cmd_grant_object: public Sql_cmd_grant, public Grant_privilege -{ -protected: -#ifndef NO_EMBEDDED_ACCESS_CHECKS - bool grant_stage0_exact_object(THD *thd, TABLE_LIST *table); -#endif -public: - Sql_cmd_grant_object(enum_sql_command command, const Grant_privilege &grant) - :Sql_cmd_grant(command), Grant_privilege(grant) - { } -}; - - -class Sql_cmd_grant_table: public Sql_cmd_grant_object -{ -#ifndef NO_EMBEDDED_ACCESS_CHECKS - bool execute_table_mask(THD *thd); - bool execute_exact_table(THD *thd, TABLE_LIST *table); -#endif -public: - Sql_cmd_grant_table(enum_sql_command command, const Grant_privilege &grant) - :Sql_cmd_grant_object(command, grant) - { } - bool execute(THD *thd); -}; - - - -class Sql_cmd_grant_sp: public Sql_cmd_grant_object -{ - const Sp_handler &m_sph; -public: - Sql_cmd_grant_sp(enum_sql_command command, const Grant_privilege &grant, - const Sp_handler &sph) - :Sql_cmd_grant_object(command, grant), - m_sph(sph) - { } - bool execute(THD *thd); -}; - -#endif /* SQL_ACL_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_admin.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_admin.h deleted file mode 100644 index d31726d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_admin.h +++ /dev/null @@ -1,125 +0,0 @@ -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_TABLE_MAINTENANCE_H -#define SQL_TABLE_MAINTENANCE_H - -/* Must be able to hold ALTER TABLE t PARTITION BY ... KEY ALGORITHM = 1 ... */ -#define SQL_ADMIN_MSG_TEXT_SIZE (128 * 1024) - -bool mysql_assign_to_keycache(THD* thd, TABLE_LIST* table_list, - const LEX_CSTRING *key_cache_name); -bool mysql_preload_keys(THD* thd, TABLE_LIST* table_list); -int reassign_keycache_tables(THD* thd, KEY_CACHE *src_cache, - KEY_CACHE *dst_cache); - -/** - Sql_cmd_analyze_table represents the ANALYZE TABLE statement. -*/ -class Sql_cmd_analyze_table : public Sql_cmd -{ -public: - /** - Constructor, used to represent a ANALYZE TABLE statement. - */ - Sql_cmd_analyze_table() - {} - - ~Sql_cmd_analyze_table() - {} - - bool execute(THD *thd); - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ANALYZE; - } -}; - - - -/** - Sql_cmd_check_table represents the CHECK TABLE statement. -*/ -class Sql_cmd_check_table : public Sql_cmd -{ -public: - /** - Constructor, used to represent a CHECK TABLE statement. - */ - Sql_cmd_check_table() - {} - - ~Sql_cmd_check_table() - {} - - bool execute(THD *thd); - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_CHECK; - } -}; - - -/** - Sql_cmd_optimize_table represents the OPTIMIZE TABLE statement. -*/ -class Sql_cmd_optimize_table : public Sql_cmd -{ -public: - /** - Constructor, used to represent a OPTIMIZE TABLE statement. - */ - Sql_cmd_optimize_table() - {} - - ~Sql_cmd_optimize_table() - {} - - bool execute(THD *thd); - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_OPTIMIZE; - } -}; - - - -/** - Sql_cmd_repair_table represents the REPAIR TABLE statement. -*/ -class Sql_cmd_repair_table : public Sql_cmd -{ -public: - /** - Constructor, used to represent a REPAIR TABLE statement. - */ - Sql_cmd_repair_table() - {} - - ~Sql_cmd_repair_table() - {} - - bool execute(THD *thd); - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_REPAIR; - } -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_alloc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_alloc.h deleted file mode 100644 index f475ecd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_alloc.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef SQL_ALLOC_INCLUDED -#define SQL_ALLOC_INCLUDED -/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 2017, 2018, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include /* alloc_root, MEM_ROOT, TRASH */ - -THD *thd_get_current_thd(); - -/* mysql standard class memory allocator */ - -class Sql_alloc -{ -public: - static void *operator new(size_t size) throw () - { - return thd_alloc(thd_get_current_thd(), size); - } - static void *operator new[](size_t size) throw () - { - return thd_alloc(thd_get_current_thd(), size); - } - static void *operator new[](size_t size, MEM_ROOT *mem_root) throw () - { return alloc_root(mem_root, size); } - static void *operator new(size_t size, MEM_ROOT *mem_root) throw() - { return alloc_root(mem_root, size); } - static void operator delete(void *ptr, size_t size) { TRASH_FREE(ptr, size); } - static void operator delete(void *, MEM_ROOT *){} - static void operator delete[](void *, MEM_ROOT *) - { /* never called */ } - static void operator delete[](void *ptr, size_t size) { TRASH_FREE(ptr, size); } -#ifdef HAVE_valgrind - bool dummy_for_valgrind; - inline Sql_alloc() :dummy_for_valgrind(0) {} -#endif -}; -#endif /* SQL_ALLOC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_alter.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_alter.h deleted file mode 100644 index 89eb4eb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_alter.h +++ /dev/null @@ -1,439 +0,0 @@ -/* Copyright (c) 2010, 2014, Oracle and/or its affiliates. - Copyright (c) 2013, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_ALTER_TABLE_H -#define SQL_ALTER_TABLE_H - -class Alter_drop; -class Alter_column; -class Alter_rename_key; -class Key; - -/** - Data describing the table being created by CREATE TABLE or - altered by ALTER TABLE. -*/ - -class Alter_info -{ -public: - - enum enum_enable_or_disable { LEAVE_AS_IS, ENABLE, DISABLE }; - - bool vers_prohibited(THD *thd) const; - - /** - The different values of the ALGORITHM clause. - Describes which algorithm to use when altering the table. - */ - enum enum_alter_table_algorithm - { -/* - Use thd->variables.alter_algorithm for alter method. If this is also - default then use the fastest possible ALTER TABLE method - (INSTANT, NOCOPY, INPLACE, COPY) -*/ - ALTER_TABLE_ALGORITHM_DEFAULT, - - // Copy if supported, error otherwise. - ALTER_TABLE_ALGORITHM_COPY, - - // In-place if supported, error otherwise. - ALTER_TABLE_ALGORITHM_INPLACE, - - // No Copy will refuse any operation which does rebuild. - ALTER_TABLE_ALGORITHM_NOCOPY, - - // Instant should allow any operation that changes metadata only. - ALTER_TABLE_ALGORITHM_INSTANT, - - // When there is no specification of algorithm during alter table. - ALTER_TABLE_ALGORITHM_NONE - }; - - - /** - The different values of the LOCK clause. - Describes the level of concurrency during ALTER TABLE. - */ - enum enum_alter_table_lock - { - // Maximum supported level of concurency for the given operation. - ALTER_TABLE_LOCK_DEFAULT, - - // Allow concurrent reads & writes. If not supported, give error. - ALTER_TABLE_LOCK_NONE, - - // Allow concurrent reads only. If not supported, give error. - ALTER_TABLE_LOCK_SHARED, - - // Block reads and writes. - ALTER_TABLE_LOCK_EXCLUSIVE - }; - - - // Columns and keys to be dropped. - List drop_list; - // Columns for ALTER_CHANGE_COLUMN_DEFAULT. - List alter_list; - // List of keys, used by both CREATE and ALTER TABLE. - List key_list; - // List of keys to be renamed. - List alter_rename_key_list; - // List of columns, used by both CREATE and ALTER TABLE. - List create_list; - List check_constraint_list; - // Type of ALTER TABLE operation. - alter_table_operations flags; - ulong partition_flags; - // Enable or disable keys. - enum_enable_or_disable keys_onoff; - // List of partitions. - List partition_names; - // Number of partitions. - uint num_parts; -private: - // Type of ALTER TABLE algorithm. - enum_alter_table_algorithm requested_algorithm; - -public: - // Type of ALTER TABLE lock. - enum_alter_table_lock requested_lock; - - - Alter_info() : - flags(0), partition_flags(0), - keys_onoff(LEAVE_AS_IS), - num_parts(0), - requested_algorithm(ALTER_TABLE_ALGORITHM_NONE), - requested_lock(ALTER_TABLE_LOCK_DEFAULT) - {} - - void reset() - { - drop_list.empty(); - alter_list.empty(); - key_list.empty(); - alter_rename_key_list.empty(); - create_list.empty(); - check_constraint_list.empty(); - flags= 0; - partition_flags= 0; - keys_onoff= LEAVE_AS_IS; - num_parts= 0; - partition_names.empty(); - requested_algorithm= ALTER_TABLE_ALGORITHM_NONE; - requested_lock= ALTER_TABLE_LOCK_DEFAULT; - } - - - /** - Construct a copy of this object to be used for mysql_alter_table - and mysql_create_table. - - Historically, these two functions modify their Alter_info - arguments. This behaviour breaks re-execution of prepared - statements and stored procedures and is compensated by always - supplying a copy of Alter_info to these functions. - - @param rhs Alter_info to make copy of - @param mem_root Mem_root for new Alter_info - - @note You need to use check the error in THD for out - of memory condition after calling this function. - */ - Alter_info(const Alter_info &rhs, MEM_ROOT *mem_root); - - - /** - Parses the given string and sets requested_algorithm - if the string value matches a supported value. - Supported values: INPLACE, COPY, DEFAULT - - @param str String containing the supplied value - @retval false Supported value found, state updated - @retval true Not supported value, no changes made - */ - bool set_requested_algorithm(const LEX_CSTRING *str); - - - /** - Parses the given string and sets requested_lock - if the string value matches a supported value. - Supported values: NONE, SHARED, EXCLUSIVE, DEFAULT - - @param str String containing the supplied value - @retval false Supported value found, state updated - @retval true Not supported value, no changes made - */ - - bool set_requested_lock(const LEX_CSTRING *str); - - /** - Set the requested algorithm to the given algorithm value - @param algo_value algorithm to be set - */ - void set_requested_algorithm(enum_alter_table_algorithm algo_value); - - /** - Returns the algorithm value in the format "algorithm=value" - */ - const char* algorithm_clause(THD *thd) const; - - /** - Returns the lock value in the format "lock=value" - */ - const char* lock() const; - - /** - Check whether the given result can be supported - with the specified user alter algorithm. - - @param thd Thread handle - @param ha_alter_info Structure describing changes to be done - by ALTER TABLE and holding data during - in-place alter - @retval false Supported operation - @retval true Not supported value - */ - bool supports_algorithm(THD *thd, - const Alter_inplace_info *ha_alter_info); - - /** - Check whether the given result can be supported - with the specified user lock type. - - @param ha_alter_info Structure describing changes to be done - by ALTER TABLE and holding data during - in-place alter - @retval false Supported lock type - @retval true Not supported value - */ - bool supports_lock(THD *thd, const Alter_inplace_info *ha_alter_info); - - /** - Return user requested algorithm. If user does not specify - algorithm then return alter_algorithm variable value. - */ - enum_alter_table_algorithm algorithm(const THD *thd) const; - -private: - Alter_info &operator=(const Alter_info &rhs); // not implemented - Alter_info(const Alter_info &rhs); // not implemented -}; - - -/** Runtime context for ALTER TABLE. */ -class Alter_table_ctx -{ -public: - Alter_table_ctx(); - - Alter_table_ctx(THD *thd, TABLE_LIST *table_list, uint tables_opened_arg, - const LEX_CSTRING *new_db_arg, const LEX_CSTRING *new_name_arg); - - /** - @return true if the table is moved to another database, false otherwise. - */ - bool is_database_changed() const - { return (new_db.str != db.str); }; - - /** - @return true if the table is renamed, false otherwise. - */ - bool is_table_renamed() const - { return (is_database_changed() || new_name.str != table_name.str); }; - - /** - @return filename (including .frm) for the new table. - */ - const char *get_new_filename() const - { - DBUG_ASSERT(!tmp_table); - return new_filename; - } - - /** - @return path to the original table. - */ - const char *get_path() const - { - DBUG_ASSERT(!tmp_table); - return path; - } - - /** - @return path to the new table. - */ - const char *get_new_path() const - { - DBUG_ASSERT(!tmp_table); - return new_path; - } - - /** - @return path to the temporary table created during ALTER TABLE. - */ - const char *get_tmp_path() const - { return tmp_path; } - - /** - Mark ALTER TABLE as needing to produce foreign key error if - it deletes a row from the table being changed. - */ - void set_fk_error_if_delete_row(FOREIGN_KEY_INFO *fk) - { - fk_error_if_delete_row= true; - fk_error_id= fk->foreign_id->str; - fk_error_table= fk->foreign_table->str; - } - - void report_implicit_default_value_error(THD *thd, const TABLE_SHARE *) const; -public: - Create_field *implicit_default_value_error_field; - bool error_if_not_empty; - uint tables_opened; - LEX_CSTRING db; - LEX_CSTRING table_name; - LEX_CSTRING alias; - LEX_CSTRING new_db; - LEX_CSTRING new_name; - LEX_CSTRING new_alias; - LEX_CSTRING tmp_name; - char tmp_buff[80]; - /** - Indicates that if a row is deleted during copying of data from old version - of table to the new version ER_FK_CANNOT_DELETE_PARENT error should be - emitted. - */ - bool fk_error_if_delete_row; - /** Name of foreign key for the above error. */ - const char *fk_error_id; - /** Name of table for the above error. */ - const char *fk_error_table; - -private: - char new_filename[FN_REFLEN + 1]; - char new_alias_buff[NAME_LEN + 1]; - char tmp_name_buff[NAME_LEN + 1]; - char path[FN_REFLEN + 1]; - char new_path[FN_REFLEN + 1]; - char tmp_path[FN_REFLEN + 1]; - -#ifdef DBUG_ASSERT_EXISTS - /** Indicates that we are altering temporary table. Used only in asserts. */ - bool tmp_table; -#endif - - Alter_table_ctx &operator=(const Alter_table_ctx &rhs); // not implemented - Alter_table_ctx(const Alter_table_ctx &rhs); // not implemented -}; - - -/** - Sql_cmd_common_alter_table represents the common properties of the ALTER TABLE - statements. - @todo move Alter_info and other ALTER generic structures from Lex here. -*/ -class Sql_cmd_common_alter_table : public Sql_cmd -{ -protected: - /** - Constructor. - */ - Sql_cmd_common_alter_table() - {} - - virtual ~Sql_cmd_common_alter_table() - {} - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_TABLE; - } -}; - -/** - Sql_cmd_alter_table represents the generic ALTER TABLE statement. - @todo move Alter_info and other ALTER specific structures from Lex here. -*/ -class Sql_cmd_alter_table : public Sql_cmd_common_alter_table, - public Storage_engine_name -{ -public: - /** - Constructor, used to represent a ALTER TABLE statement. - */ - Sql_cmd_alter_table() - {} - - ~Sql_cmd_alter_table() - {} - - Storage_engine_name *option_storage_engine_name() { return this; } - - bool execute(THD *thd); -}; - - -/** - Sql_cmd_alter_sequence represents the ALTER SEQUENCE statement. -*/ -class Sql_cmd_alter_sequence : public Sql_cmd, - public DDL_options -{ -public: - /** - Constructor, used to represent a ALTER TABLE statement. - */ - Sql_cmd_alter_sequence(const DDL_options &options) - :DDL_options(options) - {} - - ~Sql_cmd_alter_sequence() - {} - - enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_SEQUENCE; - } - bool execute(THD *thd); -}; - - -/** - Sql_cmd_alter_table_tablespace represents ALTER TABLE - IMPORT/DISCARD TABLESPACE statements. -*/ -class Sql_cmd_discard_import_tablespace : public Sql_cmd_common_alter_table -{ -public: - enum enum_tablespace_op_type - { - DISCARD_TABLESPACE, IMPORT_TABLESPACE - }; - - Sql_cmd_discard_import_tablespace(enum_tablespace_op_type tablespace_op_arg) - : m_tablespace_op(tablespace_op_arg) - {} - - bool execute(THD *thd); - -private: - const enum_tablespace_op_type m_tablespace_op; -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_analyse.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_analyse.h deleted file mode 100644 index 9cdb93f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_analyse.h +++ /dev/null @@ -1,367 +0,0 @@ -#ifndef SQL_ANALYSE_INCLUDED -#define SQL_ANALYSE_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* Analyse database */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "procedure.h" /* Procedure */ - -#define my_thd_charset default_charset_info - -#define DEC_IN_AVG 4 - -typedef struct st_number_info -{ - // if zerofill is true, the number must be zerofill, or string - bool negative, is_float, zerofill, maybe_zerofill; - int8 integers; - int8 decimals; - double dval; - ulonglong ullval; -} NUM_INFO; - -typedef struct st_extreme_value_number_info -{ - ulonglong ullval; - longlong llval; - double max_dval, min_dval; -} EV_NUM_INFO; - -typedef struct st_tree_info -{ - bool found; - String *str; - Item *item; -} TREE_INFO; - -uint check_ulonglong(const char *str, uint length); -bool get_ev_num_info(EV_NUM_INFO *ev_info, NUM_INFO *info, const char *num); -bool test_if_number(NUM_INFO *info, const char *str, uint str_len); -int compare_double(const double *s, const double *t); -int compare_double2(void* cmp_arg __attribute__((unused)), - const double *s, const double *t); -int compare_longlong(const longlong *s, const longlong *t); -int compare_longlong2(void* cmp_arg __attribute__((unused)), - const longlong *s, const longlong *t); -int compare_ulonglong(const ulonglong *s, const ulonglong *t); -int compare_ulonglong2(void* cmp_arg __attribute__((unused)), - const ulonglong *s, const ulonglong *t); -int compare_decimal2(int* len, const char *s, const char *t); -Procedure *proc_analyse_init(THD *thd, ORDER *param, select_result *result, - List &field_list); -int free_string(void* str, TREE_FREE, void*); -class analyse; - -class field_info :public Sql_alloc -{ -protected: - ulong treemem, tree_elements, empty, nulls, min_length, max_length; - uint room_in_tree; - bool found; - TREE tree; - Item *item; - analyse *pc; - -public: - field_info(Item* a, analyse* b) : treemem(0), tree_elements(0), empty(0), - nulls(0), min_length(0), max_length(0), room_in_tree(1), - found(0),item(a), pc(b) {}; - - virtual ~field_info() { delete_tree(&tree, 0); } - virtual void add() = 0; - virtual void get_opt_type(String*, ha_rows) = 0; - virtual String *get_min_arg(String *) = 0; - virtual String *get_max_arg(String *) = 0; - virtual String *avg(String*, ha_rows) = 0; - virtual String *std(String*, ha_rows) = 0; - virtual tree_walk_action collect_enum() = 0; - virtual uint decimals() { return 0; } - friend class analyse; -}; - - -int collect_string(String *element, element_count count, - TREE_INFO *info); - -int sortcmp2(void* cmp_arg __attribute__((unused)), - const String *a,const String *b); - -class field_str :public field_info -{ - String min_arg, max_arg; - ulonglong sum; - bool must_be_blob, was_zero_fill, was_maybe_zerofill, - can_be_still_num; - NUM_INFO num_info; - EV_NUM_INFO ev_num_info; - -public: - field_str(Item* a, analyse* b) :field_info(a,b), - min_arg("",default_charset_info), - max_arg("",default_charset_info), sum(0), - must_be_blob(0), was_zero_fill(0), - was_maybe_zerofill(0), can_be_still_num(1) - { init_tree(&tree, 0, 0, sizeof(String), (qsort_cmp2) sortcmp2, - free_string, NULL, MYF(MY_THREAD_SPECIFIC)); }; - - void add(); - void get_opt_type(String*, ha_rows); - String *get_min_arg(String *not_used __attribute__((unused))) - { return &min_arg; } - String *get_max_arg(String *not_used __attribute__((unused))) - { return &max_arg; } - String *avg(String *s, ha_rows rows) - { - if (!(rows - nulls)) - s->set_real((double) 0.0, 1,my_thd_charset); - else - s->set_real((ulonglong2double(sum) / ulonglong2double(rows - nulls)), - DEC_IN_AVG,my_thd_charset); - return s; - } - friend int collect_string(String *element, element_count count, - TREE_INFO *info); - tree_walk_action collect_enum() - { return (tree_walk_action) collect_string; } - String *std(String *s __attribute__((unused)), - ha_rows rows __attribute__((unused))) - { return (String*) 0; } -}; - - -int collect_decimal(uchar *element, element_count count, - TREE_INFO *info); - -class field_decimal :public field_info -{ - my_decimal min_arg, max_arg; - my_decimal sum[2], sum_sqr[2]; - int cur_sum; - int bin_size; -public: - field_decimal(Item* a, analyse* b) :field_info(a,b) - { - bin_size= my_decimal_get_binary_size(a->max_length, a->decimals); - init_tree(&tree, 0, 0, bin_size, (qsort_cmp2)compare_decimal2, - 0, (void *)&bin_size, MYF(MY_THREAD_SPECIFIC)); - }; - - void add(); - void get_opt_type(String*, ha_rows); - String *get_min_arg(String *); - String *get_max_arg(String *); - String *avg(String *s, ha_rows rows); - friend int collect_decimal(uchar *element, element_count count, - TREE_INFO *info); - tree_walk_action collect_enum() - { return (tree_walk_action) collect_decimal; } - String *std(String *s, ha_rows rows); -}; - - -int collect_real(double *element, element_count count, TREE_INFO *info); - -class field_real: public field_info -{ - double min_arg, max_arg; - double sum, sum_sqr; - uint max_notzero_dec_len; - -public: - field_real(Item* a, analyse* b) :field_info(a,b), - min_arg(0), max_arg(0), sum(0), sum_sqr(0), max_notzero_dec_len(0) - { init_tree(&tree, 0, 0, sizeof(double), - (qsort_cmp2) compare_double2, NULL, NULL, - MYF(MY_THREAD_SPECIFIC)); } - - void add(); - void get_opt_type(String*, ha_rows); - String *get_min_arg(String *s) - { - s->set_real(min_arg, item->decimals, my_thd_charset); - return s; - } - String *get_max_arg(String *s) - { - s->set_real(max_arg, item->decimals, my_thd_charset); - return s; - } - String *avg(String *s, ha_rows rows) - { - if (!(rows - nulls)) - s->set_real((double) 0.0, 1,my_thd_charset); - else - s->set_real(((double)sum / (double) (rows - nulls)), item->decimals,my_thd_charset); - return s; - } - String *std(String *s, ha_rows rows) - { - double tmp = ulonglong2double(rows); - if (!(tmp - nulls)) - s->set_real((double) 0.0, 1,my_thd_charset); - else - { - double tmp2 = ((sum_sqr - sum * sum / (tmp - nulls)) / - (tmp - nulls)); - s->set_real(((double) tmp2 <= 0.0 ? 0.0 : sqrt(tmp2)), item->decimals,my_thd_charset); - } - return s; - } - uint decimals() { return item->decimals; } - friend int collect_real(double *element, element_count count, - TREE_INFO *info); - tree_walk_action collect_enum() - { return (tree_walk_action) collect_real;} -}; - -int collect_longlong(longlong *element, element_count count, - TREE_INFO *info); - -class field_longlong: public field_info -{ - longlong min_arg, max_arg; - longlong sum, sum_sqr; - -public: - field_longlong(Item* a, analyse* b) :field_info(a,b), - min_arg(0), max_arg(0), sum(0), sum_sqr(0) - { init_tree(&tree, 0, 0, sizeof(longlong), - (qsort_cmp2) compare_longlong2, NULL, NULL, - MYF(MY_THREAD_SPECIFIC)); } - - void add(); - void get_opt_type(String*, ha_rows); - String *get_min_arg(String *s) { s->set(min_arg,my_thd_charset); return s; } - String *get_max_arg(String *s) { s->set(max_arg,my_thd_charset); return s; } - String *avg(String *s, ha_rows rows) - { - if (!(rows - nulls)) - s->set_real((double) 0.0, 1,my_thd_charset); - else - s->set_real(((double) sum / (double) (rows - nulls)), DEC_IN_AVG,my_thd_charset); - return s; - } - String *std(String *s, ha_rows rows) - { - double tmp = ulonglong2double(rows); - if (!(tmp - nulls)) - s->set_real((double) 0.0, 1,my_thd_charset); - else - { - double tmp2 = ((sum_sqr - sum * sum / (tmp - nulls)) / - (tmp - nulls)); - s->set_real(((double) tmp2 <= 0.0 ? 0.0 : sqrt(tmp2)), DEC_IN_AVG,my_thd_charset); - } - return s; - } - friend int collect_longlong(longlong *element, element_count count, - TREE_INFO *info); - tree_walk_action collect_enum() - { return (tree_walk_action) collect_longlong;} -}; - -int collect_ulonglong(ulonglong *element, element_count count, - TREE_INFO *info); - -class field_ulonglong: public field_info -{ - ulonglong min_arg, max_arg; - ulonglong sum, sum_sqr; - -public: - field_ulonglong(Item* a, analyse * b) :field_info(a,b), - min_arg(0), max_arg(0), sum(0),sum_sqr(0) - { init_tree(&tree, 0, 0, sizeof(ulonglong), - (qsort_cmp2) compare_ulonglong2, NULL, NULL, - MYF(MY_THREAD_SPECIFIC)); } - void add(); - void get_opt_type(String*, ha_rows); - String *get_min_arg(String *s) { s->set(min_arg,my_thd_charset); return s; } - String *get_max_arg(String *s) { s->set(max_arg,my_thd_charset); return s; } - String *avg(String *s, ha_rows rows) - { - if (!(rows - nulls)) - s->set_real((double) 0.0, 1,my_thd_charset); - else - s->set_real((ulonglong2double(sum) / ulonglong2double(rows - nulls)), - DEC_IN_AVG,my_thd_charset); - return s; - } - String *std(String *s, ha_rows rows) - { - double tmp = ulonglong2double(rows); - if (!(tmp - nulls)) - s->set_real((double) 0.0, 1,my_thd_charset); - else - { - double tmp2 = ((ulonglong2double(sum_sqr) - - ulonglong2double(sum * sum) / (tmp - nulls)) / - (tmp - nulls)); - s->set_real(((double) tmp2 <= 0.0 ? 0.0 : sqrt(tmp2)), DEC_IN_AVG,my_thd_charset); - } - return s; - } - friend int collect_ulonglong(ulonglong *element, element_count count, - TREE_INFO *info); - tree_walk_action collect_enum() - { return (tree_walk_action) collect_ulonglong; } -}; - - -Procedure *proc_analyse_init(THD *thd, ORDER *param, - select_result *result, - List &field_list); - -class analyse: public Procedure -{ -protected: - Item_proc *func_items[10]; - List fields, result_fields; - field_info **f_info, **f_end; - ha_rows rows; - uint output_str_length; - -public: - uint max_tree_elements, max_treemem; - - analyse(select_result *res) :Procedure(res, PROC_NO_SORT), f_info(0), - rows(0), output_str_length(0) {} - - ~analyse() - { - if (f_info) - { - for (field_info **f=f_info; f != f_end; f++) - delete (*f); - } - } - virtual void add() {} - virtual bool change_columns(THD *thd, List &fields); - virtual int send_row(List &field_list); - virtual void end_group(void) {} - virtual int end_of_records(void); - friend Procedure *proc_analyse_init(THD *thd, ORDER *param, - select_result *result, - List &field_list); -}; - -#endif /* SQL_ANALYSE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_analyze_stmt.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_analyze_stmt.h deleted file mode 100644 index 990c79f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_analyze_stmt.h +++ /dev/null @@ -1,427 +0,0 @@ -/* - Copyright (c) 2015, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - -== ANALYZE-stmt classes == - -This file contains classes for supporting "ANALYZE statement" feature. These are -a set of data structures that can be used to store the data about how the -statement executed. - -There are two kinds of data collection: - -1. Various counters. We assume that incrementing counters has very low -overhead. Because of that, execution code increments counters unconditionally -(even when not running "ANALYZE $statement" commands. You run regular SELECT/ -UPDATE/DELETE/etc and the counters are incremented). - -As a free bonus, this lets us print detailed information into the slow query -log, should the query be slow. - -2. Timing data. Measuring the time it took to run parts of query has noticeable -overhead. Because of that, we measure the time only when running "ANALYZE -$stmt"). - -*/ - -class Gap_time_tracker; -void attach_gap_time_tracker(THD *thd, Gap_time_tracker *gap_tracker, ulonglong timeval); -void process_gap_time_tracker(THD *thd, ulonglong timeval); - -/* - A class for tracking time it takes to do a certain action -*/ -class Exec_time_tracker -{ -protected: - ulonglong count; - ulonglong cycles; - ulonglong last_start; - - void cycles_stop_tracking(THD *thd) - { - ulonglong end= my_timer_cycles(); - cycles += end - last_start; - if (unlikely(end < last_start)) - cycles += ULONGLONG_MAX; - - process_gap_time_tracker(thd, end); - if (my_gap_tracker) - attach_gap_time_tracker(thd, my_gap_tracker, end); - } -public: - Exec_time_tracker() : count(0), cycles(0), my_gap_tracker(NULL) {} - - /* - The time spent between stop_tracking() call on this object and any - other time measurement will be billed to this tracker. - */ - Gap_time_tracker *my_gap_tracker; - - // interface for collecting time - void start_tracking(THD *thd) - { - last_start= my_timer_cycles(); - process_gap_time_tracker(thd, last_start); - } - - void stop_tracking(THD *thd) - { - count++; - cycles_stop_tracking(thd); - } - - // interface for getting the time - ulonglong get_loops() const { return count; } - double get_time_ms() const - { - // convert 'cycles' to milliseconds. - return 1000.0 * static_cast(cycles) / - static_cast(sys_timer_info.cycles.frequency); - } -}; - - -/* - Tracker for time spent between the calls to Exec_time_tracker's {start| - stop}_tracking(). - - @seealso Gap_time_tracker_data in sql_class.h -*/ -class Gap_time_tracker -{ - ulonglong cycles; -public: - Gap_time_tracker() : cycles(0) {} - - void log_time(ulonglong start, ulonglong end) { - cycles += end - start; - } - - double get_time_ms() const - { - // convert 'cycles' to milliseconds. - return 1000.0 * static_cast(cycles) / - static_cast(sys_timer_info.cycles.frequency); - } -}; - - - -/* - A class for counting certain actions (in all queries), and optionally - collecting the timings (in ANALYZE queries). -*/ - -class Time_and_counter_tracker: public Exec_time_tracker -{ -public: - const bool timed; - - Time_and_counter_tracker(bool timed_arg) : timed(timed_arg) - {} - - /* Loops are counted in both ANALYZE and regular queries, as this is cheap */ - void incr_loops() { count++; } - - /* - Unlike Exec_time_tracker::stop_tracking, we don't increase loops. - */ - void stop_tracking(THD *thd) - { - cycles_stop_tracking(thd); - } -}; - -#define ANALYZE_START_TRACKING(thd, tracker) \ - { \ - (tracker)->incr_loops(); \ - if (unlikely((tracker)->timed)) \ - { (tracker)->start_tracking(thd); } \ - } - -#define ANALYZE_STOP_TRACKING(thd, tracker) \ - if (unlikely((tracker)->timed)) \ - { (tracker)->stop_tracking(thd); } - -/* - A class for collecting read statistics. - - The idea is that we run several scans. Each scans gets rows, and then filters - some of them out. We count scans, rows, and rows left after filtering. - - (note: at the moment, the class is not actually tied to a physical table. - It can be used to track reading from files, buffers, etc). -*/ - -class Table_access_tracker -{ -public: - Table_access_tracker() : - r_scans(0), r_rows(0), /*r_rows_after_table_cond(0),*/ - r_rows_after_where(0) - {} - - ha_rows r_scans; /* How many scans were ran on this join_tab */ - ha_rows r_rows; /* How many rows we've got after that */ - ha_rows r_rows_after_where; /* Rows after applying attached part of WHERE */ - - bool has_scans() const { return (r_scans != 0); } - ha_rows get_loops() const { return r_scans; } - double get_avg_rows() const - { - return r_scans - ? static_cast(r_rows) / static_cast(r_scans) - : 0; - } - - double get_filtered_after_where() const - { - return r_rows > 0 - ? static_cast(r_rows_after_where) / - static_cast(r_rows) - : 1.0; - } - - inline void on_scan_init() { r_scans++; } - inline void on_record_read() { r_rows++; } - inline void on_record_after_where() { r_rows_after_where++; } -}; - - -class Json_writer; - -/* - This stores the data about how filesort executed. - - A few things from here (e.g. r_used_pq, r_limit) belong to the query plan, - however, these parameters are calculated right during the execution so we - can't easily put them into the query plan. - - The class is designed to handle multiple invocations of filesort(). -*/ - -class Filesort_tracker : public Sql_alloc -{ -public: - Filesort_tracker(bool do_timing) : - time_tracker(do_timing), r_limit(0), r_used_pq(0), - r_examined_rows(0), r_sorted_rows(0), r_output_rows(0), - sort_passes(0), - sort_buffer_size(0), - r_using_addons(false), - r_packed_addon_fields(false), - r_sort_keys_packed(false) - {} - - /* Functions that filesort uses to report various things about its execution */ - - inline void report_use(THD *thd, ha_rows r_limit_arg) - { - if (!time_tracker.get_loops()) - r_limit= r_limit_arg; - else - r_limit= (r_limit != r_limit_arg)? 0: r_limit_arg; - - ANALYZE_START_TRACKING(thd, &time_tracker); - } - inline void incr_pq_used() { r_used_pq++; } - - inline void report_row_numbers(ha_rows examined_rows, - ha_rows sorted_rows, - ha_rows returned_rows) - { - r_examined_rows += examined_rows; - r_sorted_rows += sorted_rows; - r_output_rows += returned_rows; - } - - inline void report_merge_passes_at_start(ulong passes) - { - sort_passes -= passes; - } - inline void report_merge_passes_at_end(THD *thd, ulong passes) - { - ANALYZE_STOP_TRACKING(thd, &time_tracker); - sort_passes += passes; - } - - inline void report_sort_buffer_size(size_t bufsize) - { - if (sort_buffer_size) - sort_buffer_size= ulonglong(-1); // multiple buffers of different sizes - else - sort_buffer_size= bufsize; - } - - inline void report_addon_fields_format(bool addons_packed) - { - r_using_addons= true; - r_packed_addon_fields= addons_packed; - } - inline void report_sort_keys_format(bool sort_keys_packed) - { - r_sort_keys_packed= sort_keys_packed; - } - - void get_data_format(String *str); - - /* Functions to get the statistics */ - void print_json_members(Json_writer *writer); - - ulonglong get_r_loops() const { return time_tracker.get_loops(); } - double get_avg_examined_rows() const - { - return static_cast(r_examined_rows) / - static_cast(get_r_loops()); - } - double get_avg_returned_rows() const - { - return static_cast(r_output_rows) / - static_cast(get_r_loops()); - } - double get_r_filtered() const - { - return r_examined_rows > 0 - ? static_cast(r_sorted_rows) / - static_cast(r_examined_rows) - : 1.0; - } -private: - Time_and_counter_tracker time_tracker; - - //ulonglong r_loops; /* How many times filesort was invoked */ - /* - LIMIT is typically a constant. There is never "LIMIT 0". - HA_POS_ERROR means we never had a limit - 0 means different values of LIMIT were used in - different filesort invocations - other value means the same LIMIT value was used every time. - */ - ulonglong r_limit; - ulonglong r_used_pq; /* How many times PQ was used */ - - /* How many rows were examined (before checking the select->cond) */ - ulonglong r_examined_rows; - - /* - How many rows were put into sorting (this is examined_rows minus rows that - didn't pass the WHERE condition) - */ - ulonglong r_sorted_rows; - - /* - How many rows were returned. This is equal to r_sorted_rows, unless there - was a LIMIT N clause in which case filesort would not have returned more - than N rows. - */ - ulonglong r_output_rows; - - /* How many sorts in total (divide by r_count to get the average) */ - ulonglong sort_passes; - - /* - 0 - means not used (or not known - (ulonglong)-1 - multiple - other - value - */ - ulonglong sort_buffer_size; - bool r_using_addons; - bool r_packed_addon_fields; - bool r_sort_keys_packed; -}; - - -/** - A class to collect data about how rowid filter is executed. - - It stores information about how rowid filter container is filled, - containers size and observed selectivity. - - The observed selectivity is calculated in this way. - Some elements elem_set are checked if they belong to container. - Observed selectivity is calculated as the count of elem_set - elements that belong to container devided by all elem_set elements. -*/ - -class Rowid_filter_tracker : public Sql_alloc -{ -private: - /* A member to track the time to fill the rowid filter */ - Time_and_counter_tracker time_tracker; - - /* Size of the rowid filter container buffer */ - size_t container_buff_size; - - /* Count of elements that were used to fill the rowid filter container */ - uint container_elements; - - /* Elements counts used for observed selectivity calculation */ - uint n_checks; - uint n_positive_checks; -public: - Rowid_filter_tracker(bool do_timing) : - time_tracker(do_timing), container_buff_size(0), - container_elements(0), n_checks(0), n_positive_checks(0) - {} - - inline void start_tracking(THD *thd) - { - ANALYZE_START_TRACKING(thd, &time_tracker); - } - - inline void stop_tracking(THD *thd) - { - ANALYZE_STOP_TRACKING(thd, &time_tracker); - } - - /* Save container buffer size in bytes */ - inline void report_container_buff_size(uint elem_size) - { - container_buff_size= container_elements * elem_size / 8; - } - - Time_and_counter_tracker *get_time_tracker() - { - return &time_tracker; - } - - double get_time_fill_container_ms() const - { - return time_tracker.get_time_ms(); - } - - void increment_checked_elements_count(bool was_checked) - { - n_checks++; - if (was_checked) - n_positive_checks++; - } - - inline void increment_container_elements_count() { container_elements++; } - - uint get_container_elements() const { return container_elements; } - - double get_r_selectivity_pct() const - { - return static_cast(n_positive_checks) / - static_cast(n_checks); - } - - size_t get_container_buff_size() const { return container_buff_size; } -}; - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_array.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_array.h deleted file mode 100644 index b6de1b1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_array.h +++ /dev/null @@ -1,296 +0,0 @@ -#ifndef SQL_ARRAY_INCLUDED -#define SQL_ARRAY_INCLUDED - -/* Copyright (c) 2003, 2005-2007 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include - -/** - A wrapper class which provides array bounds checking. - We do *not* own the array, we simply have a pointer to the first element, - and a length. - - @remark - We want the compiler-generated versions of: - - the copy CTOR (memberwise initialization) - - the assignment operator (memberwise assignment) - - @param Element_type The type of the elements of the container. - */ -template class Bounds_checked_array -{ -public: - Bounds_checked_array()= default; - - Bounds_checked_array(Element_type *el, size_t size_arg) - : m_array(el), m_size(size_arg) - {} - - void reset() { m_array= NULL; m_size= 0; } - - void reset(Element_type *array_arg, size_t size_arg) - { - m_array= array_arg; - m_size= size_arg; - } - - /** - Set a new bound on the array. Does not resize the underlying - array, so the new size must be smaller than or equal to the - current size. - */ - void resize(size_t new_size) - { - DBUG_ASSERT(new_size <= m_size); - m_size= new_size; - } - - Element_type &operator[](size_t n) - { - DBUG_ASSERT(n < m_size); - return m_array[n]; - } - - const Element_type &operator[](size_t n) const - { - DBUG_ASSERT(n < m_size); - return m_array[n]; - } - - size_t element_size() const { return sizeof(Element_type); } - size_t size() const { return m_size; } - - bool is_null() const { return m_array == NULL; } - - void pop_front() - { - DBUG_ASSERT(m_size > 0); - m_array+= 1; - m_size-= 1; - } - - Element_type *array() const { return m_array; } - - Element_type *begin() const { return array(); } - Element_type *end() const { return array() + m_size; } - - - bool operator==(const Bounds_checked_array&rhs) const - { - return m_array == rhs.m_array && m_size == rhs.m_size; - } - bool operator!=(const Bounds_checked_array&rhs) const - { - return m_array != rhs.m_array || m_size != rhs.m_size; - } - -private: - Element_type *m_array= nullptr; - size_t m_size= 0; -}; - -/* - A typesafe wrapper around DYNAMIC_ARRAY - - TODO: Change creator to take a THREAD_SPECIFIC option. -*/ - -template class Dynamic_array -{ - DYNAMIC_ARRAY array; -public: - Dynamic_array(PSI_memory_key psi_key, uint prealloc=16, uint increment=16) - { - init(psi_key, prealloc, increment); - } - - Dynamic_array(MEM_ROOT *root, uint prealloc=16, uint increment=16) - { - void *init_buffer= alloc_root(root, sizeof(Elem) * prealloc); - init_dynamic_array2(root->m_psi_key, &array, sizeof(Elem), init_buffer, - prealloc, increment, MYF(0)); - } - - void init(PSI_memory_key psi_key, uint prealloc=16, uint increment=16) - { - init_dynamic_array2(psi_key, &array, sizeof(Elem), 0, prealloc, increment, MYF(0)); - } - - /** - @note Though formally this could be declared "const" it would be - misleading at it returns a non-const pointer to array's data. - */ - Elem& at(size_t idx) - { - DBUG_ASSERT(idx < array.elements); - return *(((Elem*)array.buffer) + idx); - } - /// Const variant of at(), which cannot change data - const Elem& at(size_t idx) const - { - return *(((Elem*)array.buffer) + idx); - } - - /// @returns pointer to first element - Elem *front() - { - return (Elem*)array.buffer; - } - - /// @returns pointer to first element - const Elem *front() const - { - return (const Elem*)array.buffer; - } - - /// @returns pointer to last element - Elem *back() - { - return ((Elem*)array.buffer) + array.elements - 1; - } - - /// @returns pointer to last element - const Elem *back() const - { - return ((const Elem*)array.buffer) + array.elements - 1; - } - - const Elem *end() const - { - return back() + 1; - } - - /// @returns pointer to n-th element - Elem *get_pos(size_t idx) - { - return ((Elem*)array.buffer) + idx; - } - - /// @returns pointer to n-th element - const Elem *get_pos(size_t idx) const - { - return ((const Elem*)array.buffer) + idx; - } - - /** - @retval false ok - @retval true OOM, @c my_error() has been called. - */ - bool append(const Elem &el) - { - return insert_dynamic(&array, &el); - } - - bool append_val(Elem el) - { - return (insert_dynamic(&array, (uchar*)&el)); - } - - bool push(Elem &el) - { - return append(el); - } - - /// Pops the last element. Does nothing if array is empty. - Elem& pop() - { - return *((Elem*)pop_dynamic(&array)); - } - - void del(size_t idx) - { - DBUG_ASSERT(idx <= array.max_element); - delete_dynamic_element(&array, (uint)idx); - } - - size_t elements() const - { - return array.elements; - } - - void elements(size_t num_elements) - { - DBUG_ASSERT(num_elements <= array.max_element); - array.elements= (uint)num_elements; - } - - void clear() - { - elements(0); - } - - void set(uint idx, const Elem &el) - { - set_dynamic(&array, &el, idx); - } - - void freeze() - { - freeze_size(&array); - } - - bool reserve(size_t new_size) - { - return allocate_dynamic(&array, (uint)new_size); - } - - - bool resize(size_t new_size, Elem default_val) - { - size_t old_size= elements(); - if (reserve(new_size)) - return true; - - if (new_size > old_size) - { - set_dynamic(&array, (uchar*)&default_val, (uint)(new_size - 1)); - /*for (size_t i= old_size; i != new_size; i++) - { - at(i)= default_val; - }*/ - } - return false; - } - - ~Dynamic_array() - { - delete_dynamic(&array); - } - - void free_memory() - { - delete_dynamic(&array); - } - - typedef int (*CMP_FUNC)(const Elem *el1, const Elem *el2); - - void sort(CMP_FUNC cmp_func) - { - my_qsort(array.buffer, array.elements, sizeof(Elem), (qsort_cmp)cmp_func); - } - - typedef int (*CMP_FUNC2)(void *, const Elem *el1, const Elem *el2); - void sort(CMP_FUNC2 cmp_func, void *data) - { - my_qsort2(array.buffer, array.elements, sizeof(Elem), (qsort2_cmp)cmp_func, data); - } -}; - -typedef Bounds_checked_array Ref_ptr_array; - -#endif /* SQL_ARRAY_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_audit.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_audit.h deleted file mode 100644 index 40276c8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_audit.h +++ /dev/null @@ -1,441 +0,0 @@ -#ifndef SQL_AUDIT_INCLUDED -#define SQL_AUDIT_INCLUDED - -/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#include -#include "sql_class.h" - -extern unsigned long mysql_global_audit_mask[]; - - -extern void mysql_audit_initialize(); -extern void mysql_audit_finalize(); - - -extern void mysql_audit_init_thd(THD *thd); -extern void mysql_audit_free_thd(THD *thd); -extern void mysql_audit_acquire_plugins(THD *thd, ulong *event_class_mask); - - -#ifndef EMBEDDED_LIBRARY -extern void mysql_audit_notify(THD *thd, uint event_class, const void *event); - -static inline bool mysql_audit_general_enabled() -{ - return mysql_global_audit_mask[0] & MYSQL_AUDIT_GENERAL_CLASSMASK; -} - -static inline bool mysql_audit_connection_enabled() -{ - return mysql_global_audit_mask[0] & MYSQL_AUDIT_CONNECTION_CLASSMASK; -} - -static inline bool mysql_audit_table_enabled() -{ - return mysql_global_audit_mask[0] & MYSQL_AUDIT_TABLE_CLASSMASK; -} - -#else -static inline void mysql_audit_notify(THD *thd, uint event_class, - const void *event) {} -#define mysql_audit_general_enabled() 0 -#define mysql_audit_connection_enabled() 0 -#define mysql_audit_table_enabled() 0 -#endif -extern my_bool mysql_audit_release_required(THD *thd); -extern void mysql_audit_release(THD *thd); - -static inline unsigned int strlen_uint(const char *s) -{ - return (uint)strlen(s); -} - -static inline unsigned int safe_strlen_uint(const char *s) -{ - return (uint)safe_strlen(s); -} - -#define MAX_USER_HOST_SIZE 512 -static inline uint make_user_name(THD *thd, char *buf) -{ - const Security_context *sctx= thd->security_ctx; - char *end= strxnmov(buf, MAX_USER_HOST_SIZE, - sctx->priv_user[0] ? sctx->priv_user : "", "[", - sctx->user ? sctx->user : "", "] @ ", - sctx->host ? sctx->host : "", " [", - sctx->ip ? sctx->ip : "", "]", NullS); - return (uint)(end-buf); -} - -/** - Call audit plugins of GENERAL audit class, MYSQL_AUDIT_GENERAL_LOG subtype. - - @param[in] thd - @param[in] time time that event occurred - @param[in] user User name - @param[in] userlen User name length - @param[in] cmd Command name - @param[in] cmdlen Command name length - @param[in] query Query string - @param[in] querylen Query string length -*/ - -static inline -void mysql_audit_general_log(THD *thd, time_t time, - const char *user, uint userlen, - const char *cmd, uint cmdlen, - const char *query, uint querylen) -{ - if (mysql_audit_general_enabled()) - { - mysql_event_general event; - - event.event_subclass= MYSQL_AUDIT_GENERAL_LOG; - event.general_error_code= 0; - event.general_time= time; - event.general_user= user; - event.general_user_length= userlen; - event.general_command= cmd; - event.general_command_length= cmdlen; - event.general_query= query; - event.general_query_length= querylen; - event.general_rows= 0; - - if (thd) - { - event.general_thread_id= (unsigned long)thd->thread_id; - event.general_charset= thd->variables.character_set_client; - event.database= thd->db; - event.query_id= thd->query_id; - } - else - { - event.general_thread_id= 0; - event.general_charset= global_system_variables.character_set_client; - event.database= null_clex_str; - event.query_id= 0; - } - - mysql_audit_notify(thd, MYSQL_AUDIT_GENERAL_CLASS, &event); - } -} - -/** - Call audit plugins of GENERAL audit class. - event_subtype should be set to one of: - MYSQL_AUDIT_GENERAL_ERROR - MYSQL_AUDIT_GENERAL_RESULT - MYSQL_AUDIT_GENERAL_STATUS - - @param[in] thd - @param[in] event_subtype Type of general audit event. - @param[in] error_code Error code - @param[in] msg Message -*/ -static inline -void mysql_audit_general(THD *thd, uint event_subtype, - int error_code, const char *msg) -{ - DBUG_ENTER("mysql_audit_general"); - if (mysql_audit_general_enabled()) - { - char user_buff[MAX_USER_HOST_SIZE]; - mysql_event_general event; - - event.event_subclass= event_subtype; - event.general_error_code= error_code; - event.general_time= my_time(0); - event.general_command= msg; - event.general_command_length= safe_strlen_uint(msg); - - if (thd) - { - event.general_user= user_buff; - event.general_user_length= make_user_name(thd, user_buff); - event.general_thread_id= (unsigned long)thd->thread_id; - event.general_query= thd->query_string.str(); - event.general_query_length= (unsigned) thd->query_string.length(); - event.general_charset= thd->query_string.charset(); - event.general_rows= thd->get_stmt_da()->current_row_for_warning(); - event.database= thd->db; - event.query_id= thd->query_id; - } - else - { - event.general_user= NULL; - event.general_user_length= 0; - event.general_thread_id= 0; - event.general_query= NULL; - event.general_query_length= 0; - event.general_charset= &my_charset_bin; - event.general_rows= 0; - event.database= null_clex_str; - event.query_id= 0; - } - - mysql_audit_notify(thd, MYSQL_AUDIT_GENERAL_CLASS, &event); - } - DBUG_VOID_RETURN; -} - -static inline -void mysql_audit_notify_connection_connect(THD *thd) -{ - if (mysql_audit_connection_enabled()) - { - const Security_context *sctx= thd->security_ctx; - mysql_event_connection event; - - event.event_subclass= MYSQL_AUDIT_CONNECTION_CONNECT; - event.status= thd->get_stmt_da()->is_error() ? - thd->get_stmt_da()->sql_errno() : 0; - event.thread_id= (unsigned long)thd->thread_id; - event.user= sctx->user; - event.user_length= safe_strlen_uint(sctx->user); - event.priv_user= sctx->priv_user; - event.priv_user_length= strlen_uint(sctx->priv_user); - event.external_user= sctx->external_user; - event.external_user_length= safe_strlen_uint(sctx->external_user); - event.proxy_user= sctx->proxy_user; - event.proxy_user_length= strlen_uint(sctx->proxy_user); - event.host= sctx->host; - event.host_length= safe_strlen_uint(sctx->host); - event.ip= sctx->ip; - event.ip_length= safe_strlen_uint(sctx->ip); - event.database= thd->db; - - mysql_audit_notify(thd, MYSQL_AUDIT_CONNECTION_CLASS, &event); - } -} - -static inline -void mysql_audit_notify_connection_disconnect(THD *thd, int errcode) -{ - if (mysql_audit_connection_enabled()) - { - const Security_context *sctx= thd->security_ctx; - mysql_event_connection event; - - event.event_subclass= MYSQL_AUDIT_CONNECTION_DISCONNECT; - event.status= errcode; - event.thread_id= (unsigned long)thd->thread_id; - event.user= sctx->user; - event.user_length= safe_strlen_uint(sctx->user); - event.priv_user= sctx->priv_user; - event.priv_user_length= strlen_uint(sctx->priv_user); - event.external_user= sctx->external_user; - event.external_user_length= safe_strlen_uint(sctx->external_user); - event.proxy_user= sctx->proxy_user; - event.proxy_user_length= strlen_uint(sctx->proxy_user); - event.host= sctx->host; - event.host_length= safe_strlen_uint(sctx->host); - event.ip= sctx->ip; - event.ip_length= safe_strlen_uint(sctx->ip) ; - event.database= thd->db; - - mysql_audit_notify(thd, MYSQL_AUDIT_CONNECTION_CLASS, &event); - } -} - -static inline -void mysql_audit_notify_connection_change_user(THD *thd, - const Security_context *old_ctx) -{ - if (mysql_audit_connection_enabled()) - { - mysql_event_connection event; - - event.event_subclass= MYSQL_AUDIT_CONNECTION_CHANGE_USER; - event.status= thd->get_stmt_da()->is_error() ? - thd->get_stmt_da()->sql_errno() : 0; - event.thread_id= (unsigned long)thd->thread_id; - event.user= old_ctx->user; - event.user_length= safe_strlen_uint(old_ctx->user); - event.priv_user= old_ctx->priv_user; - event.priv_user_length= strlen_uint(old_ctx->priv_user); - event.external_user= old_ctx->external_user; - event.external_user_length= safe_strlen_uint(old_ctx->external_user); - event.proxy_user= old_ctx->proxy_user; - event.proxy_user_length= strlen_uint(old_ctx->proxy_user); - event.host= old_ctx->host; - event.host_length= safe_strlen_uint(old_ctx->host); - event.ip= old_ctx->ip; - event.ip_length= safe_strlen_uint(old_ctx->ip); - event.database= thd->db; - - mysql_audit_notify(thd, MYSQL_AUDIT_CONNECTION_CLASS, &event); - } -} - - -static inline -void mysql_audit_external_lock_ex(THD *thd, my_thread_id thread_id, - const char *user, const char *host, const char *ip, query_id_t query_id, - TABLE_SHARE *share, int lock) -{ - if (lock != F_UNLCK && mysql_audit_table_enabled()) - { - const Security_context *sctx= thd->security_ctx; - mysql_event_table event; - - event.event_subclass= MYSQL_AUDIT_TABLE_LOCK; - event.read_only= lock == F_RDLCK; - event.thread_id= (unsigned long)thread_id; - event.user= user; - event.priv_user= sctx->priv_user; - event.priv_host= sctx->priv_host; - event.external_user= sctx->external_user; - event.proxy_user= sctx->proxy_user; - event.host= host; - event.ip= ip; - event.database= share->db; - event.table= share->table_name; - event.new_database= null_clex_str; - event.new_table= null_clex_str; - event.query_id= query_id; - - mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); - } -} - -static inline -void mysql_audit_external_lock(THD *thd, TABLE_SHARE *share, int lock) -{ - mysql_audit_external_lock_ex(thd, thd->thread_id, thd->security_ctx->user, - thd->security_ctx->host, thd->security_ctx->ip, thd->query_id, - share, lock); -} - -static inline -void mysql_audit_create_table(TABLE *table) -{ - if (mysql_audit_table_enabled()) - { - THD *thd= table->in_use; - const TABLE_SHARE *share= table->s; - const Security_context *sctx= thd->security_ctx; - mysql_event_table event; - - event.event_subclass= MYSQL_AUDIT_TABLE_CREATE; - event.read_only= 0; - event.thread_id= (unsigned long)thd->thread_id; - event.user= sctx->user; - event.priv_user= sctx->priv_user; - event.priv_host= sctx->priv_host; - event.external_user= sctx->external_user; - event.proxy_user= sctx->proxy_user; - event.host= sctx->host; - event.ip= sctx->ip; - event.database= share->db; - event.table= share->table_name; - event.new_database= null_clex_str; - event.new_table= null_clex_str; - event.query_id= thd->query_id; - - mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); - } -} - -static inline -void mysql_audit_drop_table(THD *thd, TABLE_LIST *table) -{ - if (mysql_audit_table_enabled()) - { - const Security_context *sctx= thd->security_ctx; - mysql_event_table event; - - event.event_subclass= MYSQL_AUDIT_TABLE_DROP; - event.read_only= 0; - event.thread_id= (unsigned long)thd->thread_id; - event.user= sctx->user; - event.priv_user= sctx->priv_user; - event.priv_host= sctx->priv_host; - event.external_user= sctx->external_user; - event.proxy_user= sctx->proxy_user; - event.host= sctx->host; - event.ip= sctx->ip; - event.database= table->db; - event.table= table->table_name; - event.new_database= null_clex_str; - event.new_table= null_clex_str; - event.query_id= thd->query_id; - - mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); - } -} - -static inline -void mysql_audit_rename_table(THD *thd, const LEX_CSTRING *old_db, - const LEX_CSTRING *old_tb, - const LEX_CSTRING *new_db, const LEX_CSTRING *new_tb) -{ - if (mysql_audit_table_enabled()) - { - const Security_context *sctx= thd->security_ctx; - mysql_event_table event; - - event.event_subclass= MYSQL_AUDIT_TABLE_RENAME; - event.read_only= 0; - event.thread_id= (unsigned long)thd->thread_id; - event.user= sctx->user; - event.priv_user= sctx->priv_user; - event.priv_host= sctx->priv_host; - event.external_user= sctx->external_user; - event.proxy_user= sctx->proxy_user; - event.host= sctx->host; - event.ip= sctx->ip; - event.database= *old_db; - event.table= *old_tb; - event.new_database= *new_db; - event.new_table= *new_tb; - event.query_id= thd->query_id; - - mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); - } -} - -static inline -void mysql_audit_alter_table(THD *thd, TABLE_LIST *table) -{ - if (mysql_audit_table_enabled()) - { - const Security_context *sctx= thd->security_ctx; - mysql_event_table event; - - event.event_subclass= MYSQL_AUDIT_TABLE_ALTER; - event.read_only= 0; - event.thread_id= (unsigned long)thd->thread_id; - event.user= sctx->user; - event.priv_user= sctx->priv_user; - event.priv_host= sctx->priv_host; - event.external_user= sctx->external_user; - event.proxy_user= sctx->proxy_user; - event.host= sctx->host; - event.ip= sctx->ip; - event.database= table->db; - event.table= table->table_name; - event.new_database= null_clex_str; - event.new_table= null_clex_str; - event.query_id= thd->query_id; - - mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); - } -} - -#endif /* SQL_AUDIT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_base.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_base.h deleted file mode 100644 index ccfacaf..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_base.h +++ /dev/null @@ -1,663 +0,0 @@ -/* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2011, 2018, MariaDB - - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_BASE_INCLUDED -#define SQL_BASE_INCLUDED - -#include "sql_class.h" /* enum_column_usage */ -#include "sql_trigger.h" /* trg_event_type */ -#include "mysqld.h" /* key_map */ -#include "table_cache.h" - -class Item_ident; -struct Name_resolution_context; -class Open_table_context; -class Open_tables_state; -class Prelocking_strategy; -struct TABLE_LIST; -class THD; -struct handlerton; -struct TABLE; - -typedef class st_select_lex SELECT_LEX; - -typedef struct st_lock_param_type ALTER_PARTITION_PARAM_TYPE; - -/* - This enumeration type is used only by the function find_item_in_list - to return the info on how an item has been resolved against a list - of possibly aliased items. - The item can be resolved: - - against an alias name of the list's element (RESOLVED_AGAINST_ALIAS) - - against non-aliased field name of the list (RESOLVED_WITH_NO_ALIAS) - - against an aliased field name of the list (RESOLVED_BEHIND_ALIAS) - - ignoring the alias name in cases when SQL requires to ignore aliases - (e.g. when the resolved field reference contains a table name or - when the resolved item is an expression) (RESOLVED_IGNORING_ALIAS) -*/ -enum enum_resolution_type { - NOT_RESOLVED=0, - RESOLVED_IGNORING_ALIAS, - RESOLVED_BEHIND_ALIAS, - RESOLVED_WITH_NO_ALIAS, - RESOLVED_AGAINST_ALIAS -}; - -/* Argument to flush_tables() of what to flush */ -enum flush_tables_type { - FLUSH_ALL, - FLUSH_NON_TRANS_TABLES, - FLUSH_SYS_TABLES -}; - -enum find_item_error_report_type {REPORT_ALL_ERRORS, REPORT_EXCEPT_NOT_FOUND, - IGNORE_ERRORS, REPORT_EXCEPT_NON_UNIQUE, - IGNORE_EXCEPT_NON_UNIQUE}; - -/* Flag bits for unique_table() */ -#define CHECK_DUP_ALLOW_DIFFERENT_ALIAS 1 -#define CHECK_DUP_FOR_CREATE 2 -#define CHECK_DUP_SKIP_TEMP_TABLE 4 - -uint get_table_def_key(const TABLE_LIST *table_list, const char **key); -TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type update, - uint lock_flags); - -/* mysql_lock_tables() and open_table() flags bits */ -#define MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK 0x0001 -#define MYSQL_OPEN_IGNORE_FLUSH 0x0002 -/* MYSQL_OPEN_TEMPORARY_ONLY (0x0004) is not used anymore. */ -#define MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY 0x0008 -#define MYSQL_LOCK_LOG_TABLE 0x0010 -/** - Do not try to acquire a metadata lock on the table: we - already have one. -*/ -#define MYSQL_OPEN_HAS_MDL_LOCK 0x0020 -/** - If in locked tables mode, ignore the locked tables and get - a new instance of the table. -*/ -#define MYSQL_OPEN_GET_NEW_TABLE 0x0040 -/* 0x0080 used to be MYSQL_OPEN_SKIP_TEMPORARY */ -/** Fail instead of waiting when conficting metadata lock is discovered. */ -#define MYSQL_OPEN_FAIL_ON_MDL_CONFLICT 0x0100 -/** Open tables using MDL_SHARED lock instead of one specified in parser. */ -#define MYSQL_OPEN_FORCE_SHARED_MDL 0x0200 -/** - Open tables using MDL_SHARED_HIGH_PRIO lock instead of one specified - in parser. -*/ -#define MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL 0x0400 -/** - When opening or locking the table, use the maximum timeout - (LONG_TIMEOUT = 1 year) rather than the user-supplied timeout value. -*/ -#define MYSQL_LOCK_IGNORE_TIMEOUT 0x0800 -/** - When acquiring "strong" (SNW, SNRW, X) metadata locks on tables to - be open do not acquire global and schema-scope IX locks. -*/ -#define MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK 0x1000 -#define MYSQL_LOCK_NOT_TEMPORARY 0x2000 -#define MYSQL_LOCK_USE_MALLOC 0x4000 -/** - Only check THD::killed if waits happen (e.g. wait on MDL, wait on - table flush, wait on thr_lock.c locks) while opening and locking table. -*/ -#define MYSQL_OPEN_IGNORE_KILLED 0x8000 -/** - Don't try to auto-repair table -*/ -#define MYSQL_OPEN_IGNORE_REPAIR 0x10000 - -/** - Don't call decide_logging_format. Used for statistic tables etc -*/ -#define MYSQL_OPEN_IGNORE_LOGGING_FORMAT 0x20000 - -/** Please refer to the internals manual. */ -#define MYSQL_OPEN_REOPEN (MYSQL_OPEN_IGNORE_FLUSH |\ - MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |\ - MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY |\ - MYSQL_LOCK_IGNORE_TIMEOUT |\ - MYSQL_OPEN_GET_NEW_TABLE |\ - MYSQL_OPEN_HAS_MDL_LOCK) - -bool is_locked_view(THD *thd, TABLE_LIST *t); -bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx); - -bool get_key_map_from_key_list(key_map *map, TABLE *table, - List *index_list); -TABLE *find_locked_table(TABLE *list, const char *db, const char *table_name); -TABLE *find_write_locked_table(TABLE *list, const char *db, - const char *table_name); -thr_lock_type read_lock_type_for_table(THD *thd, - Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, - bool routine_modifies_data); - -my_bool mysql_rm_tmp_tables(void); -void close_tables_for_reopen(THD *thd, TABLE_LIST **tables, - const MDL_savepoint &start_of_statement_svp); -bool table_already_fk_prelocked(TABLE_LIST *tl, LEX_CSTRING *db, - LEX_CSTRING *table, thr_lock_type lock_type); -TABLE_LIST *find_table_in_list(TABLE_LIST *table, - TABLE_LIST *TABLE_LIST::*link, - const LEX_CSTRING *db_name, - const LEX_CSTRING *table_name); -int close_thread_tables(THD *thd); -void switch_to_nullable_trigger_fields(List &items, TABLE *); -void switch_defaults_to_nullable_trigger_fields(TABLE *table); -bool fill_record_n_invoke_before_triggers(THD *thd, TABLE *table, - List &fields, - List &values, - bool ignore_errors, - enum trg_event_type event); -bool fill_record_n_invoke_before_triggers(THD *thd, TABLE *table, - Field **field, - List &values, - bool ignore_errors, - enum trg_event_type event); -bool insert_fields(THD *thd, Name_resolution_context *context, - const char *db_name, const char *table_name, - List_iterator *it, bool any_privileges, - uint *hidden_bit_fields); -void make_leaves_list(THD *thd, List &list, TABLE_LIST *tables, - bool full_table_list, TABLE_LIST *boundary); -int setup_wild(THD *thd, TABLE_LIST *tables, List &fields, - List *sum_func_list, SELECT_LEX *sl); -int setup_returning_fields(THD* thd, TABLE_LIST* table_list); -bool setup_fields(THD *thd, Ref_ptr_array ref_pointer_array, - List &item, enum_column_usage column_usage, - List *sum_func_list, List *pre_fix, - bool allow_sum_func); -void unfix_fields(List &items); -bool fill_record(THD * thd, TABLE *table_arg, List &fields, - List &values, bool ignore_errors, bool update); -bool fill_record(THD *thd, TABLE *table, Field **field, List &values, - bool ignore_errors, bool use_value); - -Field * -find_field_in_tables(THD *thd, Item_ident *item, - TABLE_LIST *first_table, TABLE_LIST *last_table, - Item **ref, find_item_error_report_type report_error, - bool check_privileges, bool register_tree_change); -Field * -find_field_in_table_ref(THD *thd, TABLE_LIST *table_list, - const char *name, size_t length, - const char *item_name, const char *db_name, - const char *table_name, Item **ref, - bool check_privileges, bool allow_rowid, - uint *cached_field_index_ptr, - bool register_tree_change, TABLE_LIST **actual_table); -Field * -find_field_in_table(THD *thd, TABLE *table, const char *name, size_t length, - bool allow_rowid, uint *cached_field_index_ptr); -Field * -find_field_in_table_sef(TABLE *table, const char *name); -Item ** find_item_in_list(Item *item, List &items, uint *counter, - find_item_error_report_type report_error, - enum_resolution_type *resolution, uint limit= 0); -bool setup_tables(THD *thd, Name_resolution_context *context, - List *from_clause, TABLE_LIST *tables, - List &leaves, bool select_insert, - bool full_table_list); -bool setup_tables_and_check_access(THD *thd, - Name_resolution_context *context, - List *from_clause, - TABLE_LIST *tables, - List &leaves, - bool select_insert, - privilege_t want_access_first, - privilege_t want_access, - bool full_table_list); -bool wait_while_table_is_used(THD *thd, TABLE *table, - enum ha_extra_function function); - -void drop_open_table(THD *thd, TABLE *table, const LEX_CSTRING *db_name, - const LEX_CSTRING *table_name); -void update_non_unique_table_error(TABLE_LIST *update, - const char *operation, - TABLE_LIST *duplicate); -int setup_conds(THD *thd, TABLE_LIST *tables, List &leaves, - COND **conds); -void wrap_ident(THD *thd, Item **conds); -int setup_ftfuncs(SELECT_LEX* select); -void cleanup_ftfuncs(SELECT_LEX *select_lex); -int init_ftfuncs(THD *thd, SELECT_LEX* select, bool no_order); -bool lock_table_names(THD *thd, const DDL_options_st &options, - TABLE_LIST *table_list, - TABLE_LIST *table_list_end, ulong lock_wait_timeout, - uint flags); -static inline bool -lock_table_names(THD *thd, TABLE_LIST *table_list, - TABLE_LIST *table_list_end, ulong lock_wait_timeout, - uint flags) -{ - return lock_table_names(thd, thd->lex->create_info, table_list, - table_list_end, lock_wait_timeout, flags); -} -bool open_tables(THD *thd, const DDL_options_st &options, - TABLE_LIST **tables, uint *counter, - uint flags, Prelocking_strategy *prelocking_strategy); - -static inline bool -open_tables(THD *thd, TABLE_LIST **tables, uint *counter, uint flags, - Prelocking_strategy *prelocking_strategy) -{ - return open_tables(thd, thd->lex->create_info, tables, counter, flags, - prelocking_strategy); -} -/* open_and_lock_tables with optional derived handling */ -bool open_and_lock_tables(THD *thd, const DDL_options_st &options, - TABLE_LIST *tables, - bool derived, uint flags, - Prelocking_strategy *prelocking_strategy); -static inline bool -open_and_lock_tables(THD *thd, TABLE_LIST *tables, - bool derived, uint flags, - Prelocking_strategy *prelocking_strategy) -{ - return open_and_lock_tables(thd, thd->lex->create_info, - tables, derived, flags, prelocking_strategy); -} -/* simple open_and_lock_tables without derived handling for single table */ -TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l, - thr_lock_type lock_type, uint flags, - Prelocking_strategy *prelocking_strategy); -bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags, - uint dt_phases); -bool open_tables_only_view_structure(THD *thd, TABLE_LIST *tables, - bool can_deadlock); -bool open_and_lock_internal_tables(TABLE *table, bool lock); -bool lock_tables(THD *thd, TABLE_LIST *tables, uint counter, uint flags); -int decide_logging_format(THD *thd, TABLE_LIST *tables); -void close_thread_table(THD *thd, TABLE **table_ptr); -TABLE_LIST *unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list, - uint check_flag); -bool is_equal(const LEX_CSTRING *a, const LEX_CSTRING *b); - -class Open_tables_backup; -/* Functions to work with system tables. */ -bool open_system_tables_for_read(THD *thd, TABLE_LIST *table_list); -void close_system_tables(THD *thd); -void close_mysql_tables(THD *thd); -TABLE *open_system_table_for_update(THD *thd, TABLE_LIST *one_table); -TABLE *open_log_table(THD *thd, TABLE_LIST *one_table, Open_tables_backup *backup); -void close_log_table(THD *thd, Open_tables_backup *backup); - -bool close_cached_tables(THD *thd, TABLE_LIST *tables, - bool wait_for_refresh, ulong timeout); -void purge_tables(); -bool flush_tables(THD *thd, flush_tables_type flag); -void close_all_tables_for_name(THD *thd, TABLE_SHARE *share, - ha_extra_function extra, - TABLE *skip_table); -OPEN_TABLE_LIST *list_open_tables(THD *thd, const char *db, const char *wild); -bool tdc_open_view(THD *thd, TABLE_LIST *table_list, uint flags); - -TABLE *find_table_for_mdl_upgrade(THD *thd, const char *db, - const char *table_name, - int *p_error); -void mark_tmp_table_for_reuse(TABLE *table); - -int dynamic_column_error_message(enum_dyncol_func_result rc); - -/* open_and_lock_tables with optional derived handling */ -int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived); - -extern "C" int simple_raw_key_cmp(void* arg, const void* key1, - const void* key2); -extern "C" int count_distinct_walk(void *elem, element_count count, void *arg); -int simple_str_key_cmp(void* arg, uchar* key1, uchar* key2); - -extern Item **not_found_item; -extern Field *not_found_field; -extern Field *view_ref_found; - -/** - clean/setup table fields and map. - - @param table TABLE structure pointer (which should be setup) - @param table_list TABLE_LIST structure pointer (owner of TABLE) - @param tablenr table number -*/ - - -inline void setup_table_map(TABLE *table, TABLE_LIST *table_list, uint tablenr) -{ - table->used_fields= 0; - table_list->reset_const_table(); - table->null_row= 0; - table->status= STATUS_NO_RECORD; - table->maybe_null= table_list->outer_join; - TABLE_LIST *embedding= table_list->embedding; - while (!table->maybe_null && embedding) - { - table->maybe_null= embedding->outer_join; - embedding= embedding->embedding; - } - table->tablenr= tablenr; - table->map= (table_map) 1 << tablenr; - table->force_index= table_list->force_index; - table->force_index_order= table->force_index_group= 0; - table->covering_keys= table->s->keys_for_keyread; -} - -inline TABLE_LIST *find_table_in_global_list(TABLE_LIST *table, - LEX_CSTRING *db_name, - LEX_CSTRING *table_name) -{ - return find_table_in_list(table, &TABLE_LIST::next_global, - db_name, table_name); -} - -inline bool setup_fields_with_no_wrap(THD *thd, Ref_ptr_array ref_pointer_array, - List &item, - enum_column_usage column_usage, - List *sum_func_list, - bool allow_sum_func) -{ - bool res; - SELECT_LEX *first= thd->lex->first_select_lex(); - DBUG_ASSERT(thd->lex->current_select == first); - first->no_wrap_view_item= TRUE; - res= setup_fields(thd, ref_pointer_array, item, column_usage, - sum_func_list, NULL, allow_sum_func); - first->no_wrap_view_item= FALSE; - return res; -} - -/** - An abstract class for a strategy specifying how the prelocking - algorithm should extend the prelocking set while processing - already existing elements in the set. -*/ - -class Prelocking_strategy -{ -public: - virtual ~Prelocking_strategy() { } - - virtual void reset(THD *thd) { }; - virtual bool handle_routine(THD *thd, Query_tables_list *prelocking_ctx, - Sroutine_hash_entry *rt, sp_head *sp, - bool *need_prelocking) = 0; - virtual bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, bool *need_prelocking) = 0; - virtual bool handle_view(THD *thd, Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, bool *need_prelocking)= 0; - virtual bool handle_end(THD *thd) { return 0; }; -}; - - -/** - A Strategy for prelocking algorithm suitable for DML statements. - - Ensures that all tables used by all statement's SF/SP/triggers and - required for foreign key checks are prelocked and SF/SPs used are - cached. -*/ - -class DML_prelocking_strategy : public Prelocking_strategy -{ -public: - virtual bool handle_routine(THD *thd, Query_tables_list *prelocking_ctx, - Sroutine_hash_entry *rt, sp_head *sp, - bool *need_prelocking); - virtual bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, bool *need_prelocking); - virtual bool handle_view(THD *thd, Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, bool *need_prelocking); -}; - - -/** - A strategy for prelocking algorithm to be used for LOCK TABLES - statement. -*/ - -class Lock_tables_prelocking_strategy : public DML_prelocking_strategy -{ - virtual bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, bool *need_prelocking); -}; - - -/** - Strategy for prelocking algorithm to be used for ALTER TABLE statements. - - Unlike DML or LOCK TABLES strategy, it doesn't - prelock triggers, views or stored routines, since they are not - used during ALTER. -*/ - -class Alter_table_prelocking_strategy : public Prelocking_strategy -{ -public: - virtual bool handle_routine(THD *thd, Query_tables_list *prelocking_ctx, - Sroutine_hash_entry *rt, sp_head *sp, - bool *need_prelocking); - virtual bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, bool *need_prelocking); - virtual bool handle_view(THD *thd, Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list, bool *need_prelocking); -}; - - -inline bool -open_tables(THD *thd, const DDL_options_st &options, - TABLE_LIST **tables, uint *counter, uint flags) -{ - DML_prelocking_strategy prelocking_strategy; - - return open_tables(thd, options, tables, counter, flags, - &prelocking_strategy); -} -inline bool -open_tables(THD *thd, TABLE_LIST **tables, uint *counter, uint flags) -{ - DML_prelocking_strategy prelocking_strategy; - - return open_tables(thd, thd->lex->create_info, tables, counter, flags, - &prelocking_strategy); -} - -inline TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l, - thr_lock_type lock_type, uint flags) -{ - DML_prelocking_strategy prelocking_strategy; - - return open_n_lock_single_table(thd, table_l, lock_type, flags, - &prelocking_strategy); -} - - -/* open_and_lock_tables with derived handling */ -inline bool open_and_lock_tables(THD *thd, - const DDL_options_st &options, - TABLE_LIST *tables, - bool derived, uint flags) -{ - DML_prelocking_strategy prelocking_strategy; - - return open_and_lock_tables(thd, options, tables, derived, flags, - &prelocking_strategy); -} -inline bool open_and_lock_tables(THD *thd, TABLE_LIST *tables, - bool derived, uint flags) -{ - DML_prelocking_strategy prelocking_strategy; - - return open_and_lock_tables(thd, thd->lex->create_info, - tables, derived, flags, - &prelocking_strategy); -} - - -bool restart_trans_for_tables(THD *thd, TABLE_LIST *table); - -bool extend_table_list(THD *thd, TABLE_LIST *tables, - Prelocking_strategy *prelocking_strategy, - bool has_prelocking_list); - -/** - A context of open_tables() function, used to recover - from a failed open_table() or open_routine() attempt. -*/ - -class Open_table_context -{ -public: - enum enum_open_table_action - { - OT_NO_ACTION= 0, - OT_BACKOFF_AND_RETRY, - OT_REOPEN_TABLES, - OT_DISCOVER, - OT_REPAIR - }; - Open_table_context(THD *thd, uint flags); - - bool recover_from_failed_open(); - bool request_backoff_action(enum_open_table_action action_arg, - TABLE_LIST *table); - - bool can_recover_from_failed_open() const - { return m_action != OT_NO_ACTION; } - - /** - When doing a back-off, we close all tables acquired by this - statement. Return an MDL savepoint taken at the beginning of - the statement, so that we can rollback to it before waiting on - locks. - */ - const MDL_savepoint &start_of_statement_svp() const - { - return m_start_of_statement_svp; - } - - inline ulong get_timeout() const - { - return m_timeout; - } - - uint get_flags() const { return m_flags; } - - /** - Set flag indicating that we have already acquired metadata lock - protecting this statement against GRL while opening tables. - */ - void set_has_protection_against_grl(enum_mdl_type mdl_type) - { - m_has_protection_against_grl|= MDL_BIT(mdl_type); - } - - bool has_protection_against_grl(enum_mdl_type mdl_type) const - { - return (bool) (m_has_protection_against_grl & MDL_BIT(mdl_type)); - } - -private: - /* THD for which tables are opened. */ - THD *m_thd; - /** - For OT_DISCOVER and OT_REPAIR actions, the table list element for - the table which definition should be re-discovered or which - should be repaired. - */ - TABLE_LIST *m_failed_table; - MDL_savepoint m_start_of_statement_svp; - /** - Lock timeout in seconds. Initialized to LONG_TIMEOUT when opening system - tables or to the "lock_wait_timeout" system variable for regular tables. - */ - ulong m_timeout; - /* open_table() flags. */ - uint m_flags; - /** Back off action. */ - enum enum_open_table_action m_action; - /** - Whether we had any locks when this context was created. - If we did, they are from the previous statement of a transaction, - and we can't safely do back-off (and release them). - */ - bool m_has_locks; - /** - Indicates that in the process of opening tables we have acquired - protection against global read lock. - */ - mdl_bitmap_t m_has_protection_against_grl; -}; - - -/** - Check if a TABLE_LIST instance represents a pre-opened temporary table. -*/ - -inline bool is_temporary_table(TABLE_LIST *tl) -{ - if (tl->view || tl->schema_table) - return FALSE; - - if (!tl->table) - return FALSE; - - /* - NOTE: 'table->s' might be NULL for specially constructed TABLE - instances. See SHOW TRIGGERS for example. - */ - - if (!tl->table->s) - return FALSE; - - return tl->table->s->tmp_table != NO_TMP_TABLE; -} - - -/** - This internal handler is used to trap ER_NO_SUCH_TABLE. -*/ - -class No_such_table_error_handler : public Internal_error_handler -{ -public: - No_such_table_error_handler() - : m_handled_errors(0), m_unhandled_errors(0) - {} - - bool handle_condition(THD *thd, - uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level *level, - const char* msg, - Sql_condition ** cond_hdl); - - /** - Returns TRUE if one or more ER_NO_SUCH_TABLE errors have been - trapped and no other errors have been seen. FALSE otherwise. - */ - bool safely_trapped_errors(); - -private: - int m_handled_errors; - int m_unhandled_errors; -}; - - -#endif /* SQL_BASE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_basic_types.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_basic_types.h deleted file mode 100644 index 3200228..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_basic_types.h +++ /dev/null @@ -1,337 +0,0 @@ -/* - Copyright (c) 2000, 2016, Oracle and/or its affiliates. - Copyright (c) 2009, 2016, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* File that includes common types used globally in MariaDB */ - -#ifndef SQL_TYPES_INCLUDED -#define SQL_TYPES_INCLUDED - -typedef ulonglong sql_mode_t; -typedef int64 query_id_t; - -enum enum_nullability { NOT_NULL, NULLABLE }; - - -/* - "fuzzydate" with strict data type control. - Represents a mixture of *only* data type conversion flags, without rounding. - Please keep "explicit" in constructors and conversion methods. -*/ -class date_conv_mode_t -{ -public: - enum value_t - { - CONV_NONE= 0U, - /* - FUZZY_DATES is used for the result will only be used for comparison - purposes. Conversion is as relaxed as possible. - */ - FUZZY_DATES= 1U, - TIME_ONLY= 4U, - INTERVAL_hhmmssff= 8U, - INTERVAL_DAY= 16U, - RANGE0_LAST= INTERVAL_DAY, - NO_ZERO_IN_DATE= (1UL << 23), // MODE_NO_ZERO_IN_DATE - NO_ZERO_DATE= (1UL << 24), // MODE_NO_ZERO_DATE - INVALID_DATES= (1UL << 25) // MODE_INVALID_DATES - }; - - /* - BIT-OR for all known values. Let's have a separate enum for it. - - We don't put this value "value_t", to avoid handling it in switch(). - - We don't put this value as a static const inside the class, - because "gdb" would display it every time when we do "print" - for a time_round_mode_t value. - - We can't put into into a function returning this value, because - it's not allowed to use functions in static_assert. - */ - enum known_values_t - { - KNOWN_MODES= FUZZY_DATES | - TIME_ONLY | INTERVAL_hhmmssff | INTERVAL_DAY | - NO_ZERO_IN_DATE | NO_ZERO_DATE | INVALID_DATES - }; -private: - value_t m_mode; -public: - - // Constructors - explicit date_conv_mode_t(ulonglong fuzzydate) - :m_mode((value_t) fuzzydate) - { } - - // Conversion operators - explicit operator ulonglong() const - { - return m_mode; - } - explicit operator bool() const - { - return m_mode != 0; - } - - // Unary operators - ulonglong operator~() const - { - return ~m_mode; - } - - // Dyadic bitwise operators - date_conv_mode_t operator&(const date_conv_mode_t &other) const - { - return date_conv_mode_t(m_mode & other.m_mode); - } - date_conv_mode_t operator&(const ulonglong other) const - { - return date_conv_mode_t(m_mode & other); - } - - date_conv_mode_t operator|(const date_conv_mode_t &other) const - { - return date_conv_mode_t(m_mode | other.m_mode); - } - - // Dyadic bitwise assignment operators - date_conv_mode_t &operator&=(const date_conv_mode_t &other) - { - m_mode= value_t(m_mode & other.m_mode); - return *this; - } - - date_conv_mode_t &operator|=(const date_conv_mode_t &other) - { - m_mode= value_t(m_mode | other.m_mode); - return *this; - } -}; - - -/* - Fractional rounding mode for temporal data types. -*/ -class time_round_mode_t -{ -public: - enum value_t - { - /* - Use FRAC_NONE when the value needs no rounding nor truncation, - because it is already known not to haveany fractional digits outside - of the requested precision. - */ - FRAC_NONE= 0, - FRAC_TRUNCATE= date_conv_mode_t::RANGE0_LAST << 1, // 32 - FRAC_ROUND= date_conv_mode_t::RANGE0_LAST << 2 // 64 - }; - // BIT-OR for all known values. See comments in time_conv_mode_t. - enum known_values_t - { - KNOWN_MODES= FRAC_TRUNCATE | FRAC_ROUND - }; -private: - value_t m_mode; -public: - // Constructors - explicit time_round_mode_t(ulonglong mode) - :m_mode((value_t) mode) - { - DBUG_ASSERT(mode == FRAC_NONE || - mode == FRAC_TRUNCATE || - mode == FRAC_ROUND); - } - // Conversion operators - explicit operator ulonglong() const - { - return m_mode; - } - value_t mode() const - { - return m_mode; - } - // Comparison operators - bool operator==(const time_round_mode_t &other) - { - return m_mode == other.m_mode; - } -}; - - -/* - "fuzzydate" with strict data type control. - Used as a parameter to get_date() and represents a mixture of: - - data type conversion flags - - fractional second rounding flags - Please keep "explicit" in constructors and conversion methods. -*/ -class date_mode_t -{ -public: - enum value_t - { - CONV_NONE= date_conv_mode_t::CONV_NONE, // 0 - FUZZY_DATES= date_conv_mode_t::FUZZY_DATES, // 1 - TIME_ONLY= date_conv_mode_t::TIME_ONLY, // 4 - INTERVAL_hhmmssff= date_conv_mode_t::INTERVAL_hhmmssff, // 8 - INTERVAL_DAY= date_conv_mode_t::INTERVAL_DAY, // 16 - FRAC_TRUNCATE= time_round_mode_t::FRAC_TRUNCATE, // 32 - FRAC_ROUND= time_round_mode_t::FRAC_ROUND, // 64 - NO_ZERO_IN_DATE= date_conv_mode_t::NO_ZERO_IN_DATE, // (1UL << 23) - NO_ZERO_DATE= date_conv_mode_t::NO_ZERO_DATE, // (1UL << 24) - INVALID_DATES= date_conv_mode_t::INVALID_DATES, // (1UL << 25) - }; -protected: - value_t m_mode; -public: - - // Constructors - explicit date_mode_t(ulonglong fuzzydate) - :m_mode((value_t) fuzzydate) - { } - - // Conversion operators - explicit operator ulonglong() const - { - return m_mode; - } - explicit operator bool() const - { - return m_mode != 0; - } - explicit operator date_conv_mode_t() const - { - return date_conv_mode_t(ulonglong(m_mode) & date_conv_mode_t::KNOWN_MODES); - } - explicit operator time_round_mode_t() const - { - return time_round_mode_t(ulonglong(m_mode) & time_round_mode_t::KNOWN_MODES); - } - // Unary operators - ulonglong operator~() const - { - return ~m_mode; - } - bool operator!() const - { - return !m_mode; - } - - // Dyadic bitwise operators - date_mode_t operator&(const date_mode_t &other) const - { - return date_mode_t(m_mode & other.m_mode); - } - date_mode_t operator&(ulonglong other) const - { - return date_mode_t(m_mode & other); - } - - date_mode_t operator|(const date_mode_t &other) const - { - return date_mode_t(m_mode | other.m_mode); - } - - // Dyadic bitwise assignment operators - date_mode_t &operator&=(const date_mode_t &other) - { - m_mode= value_t(m_mode & other.m_mode); - return *this; - } - - date_mode_t &operator|=(const date_mode_t &other) - { - m_mode= value_t(m_mode | other.m_mode); - return *this; - } - - date_mode_t &operator|=(const date_conv_mode_t &other) - { - m_mode= value_t(m_mode | ulonglong(other)); - return *this; - } -}; - - -// Bitwise OR out-of-class operators for data type mixtures -static inline date_mode_t operator|(const date_mode_t &a, - const date_conv_mode_t &b) -{ - return date_mode_t(ulonglong(a) | ulonglong(b)); -} - -static inline date_mode_t operator|(const date_conv_mode_t &a, - const time_round_mode_t &b) -{ - return date_mode_t(ulonglong(a) | ulonglong(b)); -} - - -static inline date_mode_t operator|(const date_conv_mode_t &a, - const date_mode_t &b) -{ - return date_mode_t(ulonglong(a) | ulonglong(b)); -} - - -// Bitwise AND out-of-class operators for data type mixtures -static inline date_conv_mode_t operator&(const date_mode_t &a, - const date_conv_mode_t &b) -{ - return date_conv_mode_t(ulonglong(a) & ulonglong(b)); -} - -static inline date_conv_mode_t operator&(const date_conv_mode_t &a, - const date_mode_t &b) -{ - return date_conv_mode_t(ulonglong(a) & ulonglong(b)); -} - -static inline date_conv_mode_t operator&(sql_mode_t &a, - const date_conv_mode_t &b) -{ - return date_conv_mode_t(a & ulonglong(b)); -} - - -static const date_conv_mode_t - TIME_CONV_NONE (date_conv_mode_t::CONV_NONE), - TIME_FUZZY_DATES (date_conv_mode_t::FUZZY_DATES), - TIME_TIME_ONLY (date_conv_mode_t::TIME_ONLY), - TIME_INTERVAL_hhmmssff (date_conv_mode_t::INTERVAL_hhmmssff), - TIME_INTERVAL_DAY (date_conv_mode_t::INTERVAL_DAY), - TIME_NO_ZERO_IN_DATE (date_conv_mode_t::NO_ZERO_IN_DATE), - TIME_NO_ZERO_DATE (date_conv_mode_t::NO_ZERO_DATE), - TIME_INVALID_DATES (date_conv_mode_t::INVALID_DATES); - -// An often used combination -static const date_conv_mode_t - TIME_NO_ZEROS (date_conv_mode_t::NO_ZERO_DATE| - date_conv_mode_t::NO_ZERO_IN_DATE); - -// Flags understood by str_to_xxx, number_to_xxx, check_date -static const date_conv_mode_t - TIME_MODE_FOR_XXX_TO_DATE (date_mode_t::NO_ZERO_IN_DATE | - date_mode_t::NO_ZERO_DATE | - date_mode_t::INVALID_DATES); - -static const time_round_mode_t - TIME_FRAC_NONE (time_round_mode_t::FRAC_NONE), - TIME_FRAC_TRUNCATE (time_round_mode_t::FRAC_TRUNCATE), - TIME_FRAC_ROUND (time_round_mode_t::FRAC_ROUND); - - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_binlog.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_binlog.h deleted file mode 100644 index d10d78e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_binlog.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_BINLOG_INCLUDED -#define SQL_BINLOG_INCLUDED - -class THD; - -void mysql_client_binlog_statement(THD *thd); - -#endif /* SQL_BINLOG_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_bitmap.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_bitmap.h deleted file mode 100644 index 02dc819..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_bitmap.h +++ /dev/null @@ -1,314 +0,0 @@ -/* Copyright (c) 2003, 2013, Oracle and/or its affiliates - Copyright (c) 2009, 2013, Monty Program Ab. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Implementation of a bitmap type. - The idea with this is to be able to handle any constant number of bits but - also be able to use 32 or 64 bits bitmaps very efficiently -*/ - -#ifndef SQL_BITMAP_INCLUDED -#define SQL_BITMAP_INCLUDED - -#include -#include -#include - - -/* An iterator to quickly walk over bits in ulonglong bitmap. */ -class Table_map_iterator -{ - ulonglong bmp; -public: - Table_map_iterator(ulonglong t): bmp(t){} - uint next_bit() - { - if (!bmp) - return BITMAP_END; - uint bit= my_find_first_bit(bmp); - bmp &= ~(1ULL << bit); - return bit; - } - int operator++(int) { return next_bit(); } - enum { BITMAP_END= 64 }; -}; - -template class Bitmap -{ -/* - Workaround GCC optimizer bug (generating SSE instuctions on unaligned data) -*/ -#if defined (__GNUC__) && defined(__x86_64__) && (__GNUC__ < 6) && !defined(__clang__) -#define NEED_GCC_NO_SSE_WORKAROUND -#endif - -#ifdef NEED_GCC_NO_SSE_WORKAROUND -#pragma GCC push_options -#pragma GCC target ("no-sse") -#endif - -private: - static const int BITS_PER_ELEMENT= sizeof(ulonglong) * 8; - static const int ARRAY_ELEMENTS= (width + BITS_PER_ELEMENT - 1) / BITS_PER_ELEMENT; - static const ulonglong ALL_BITS_SET= ULLONG_MAX; - - ulonglong buffer[ARRAY_ELEMENTS]; - - uint bit_index(uint n) const - { - DBUG_ASSERT(n < width); - return ARRAY_ELEMENTS == 1 ? 0 : n / BITS_PER_ELEMENT; - } - ulonglong bit_mask(uint n) const - { - DBUG_ASSERT(n < width); - return ARRAY_ELEMENTS == 1 ? 1ULL << n : 1ULL << (n % BITS_PER_ELEMENT); - } - ulonglong last_element_mask(int n) const - { - DBUG_ASSERT(n % BITS_PER_ELEMENT != 0); - return bit_mask(n) - 1; - } - -public: - /* - The default constructor does nothing. - The caller is supposed to either zero the memory - or to call set_all()/clear_all()/set_prefix() - to initialize bitmap. - */ - Bitmap() { } - - explicit Bitmap(uint prefix) - { - set_prefix(prefix); - } - void init(uint prefix) - { - set_prefix(prefix); - } - uint length() const - { - return width; - } - void set_bit(uint n) - { - buffer[bit_index(n)] |= bit_mask(n); - } - void clear_bit(uint n) - { - buffer[bit_index(n)] &= ~bit_mask(n); - } - bool is_set(uint n) const - { - return buffer[bit_index(n)] & bit_mask(n); - } - void set_prefix(uint prefix_size) - { - set_if_smaller(prefix_size, width); - - size_t idx= prefix_size / BITS_PER_ELEMENT; - - for (size_t i= 0; i < idx; i++) - buffer[i]= ALL_BITS_SET; - - if (prefix_size % BITS_PER_ELEMENT) - buffer[idx++]= last_element_mask(prefix_size); - - for (size_t i= idx; i < ARRAY_ELEMENTS; i++) - buffer[i]= 0; - } - bool is_prefix(uint prefix_size) const - { - DBUG_ASSERT(prefix_size <= width); - - size_t idx= prefix_size / BITS_PER_ELEMENT; - - for (size_t i= 0; i < idx; i++) - if (buffer[i] != ALL_BITS_SET) - return false; - - if (prefix_size % BITS_PER_ELEMENT) - if (buffer[idx++] != last_element_mask(prefix_size)) - return false; - - for (size_t i= idx; i < ARRAY_ELEMENTS; i++) - if (buffer[i] != 0) - return false; - - return true; - } - void set_all() - { - if (width % BITS_PER_ELEMENT) - set_prefix(width); - else if (ARRAY_ELEMENTS > 1) - memset(buffer, 0xff, sizeof(buffer)); - else - buffer[0] = ALL_BITS_SET; - } - void clear_all() - { - if (ARRAY_ELEMENTS > 1) - memset(buffer, 0, sizeof(buffer)); - else - buffer[0]= 0; - } - void intersect(const Bitmap& map2) - { - for (size_t i= 0; i < ARRAY_ELEMENTS; i++) - buffer[i] &= map2.buffer[i]; - } - -private: - /* - Intersect with a bitmap represented as as longlong. - In addition, pad the rest of the bitmap with 0 or 1 bits - depending on pad_with_ones parameter. - */ - void intersect_and_pad(ulonglong map2buff, bool pad_with_ones) - { - buffer[0] &= map2buff; - - for (size_t i= 1; i < ARRAY_ELEMENTS; i++) - buffer[i]= pad_with_ones ? ALL_BITS_SET : 0; - - if (ARRAY_ELEMENTS > 1 && (width % BITS_PER_ELEMENT) && pad_with_ones) - buffer[ARRAY_ELEMENTS - 1]= last_element_mask(width); - } - -public: - void intersect(ulonglong map2buff) - { - intersect_and_pad(map2buff, 0); - } - /* Use highest bit for all bits above first element. */ - void intersect_extended(ulonglong map2buff) - { - intersect_and_pad(map2buff, (map2buff & (1ULL << 63))); - } - void subtract(const Bitmap& map2) - { - for (size_t i= 0; i < ARRAY_ELEMENTS; i++) - buffer[i] &= ~(map2.buffer[i]); - } - void merge(const Bitmap& map2) - { - for (size_t i= 0; i < ARRAY_ELEMENTS; i++) - buffer[i] |= map2.buffer[i]; - } - bool is_clear_all() const - { - for (size_t i= 0; i < ARRAY_ELEMENTS; i++) - if (buffer[i]) - return false; - return true; - } - bool is_subset(const Bitmap& map2) const - { - for (size_t i= 0; i < ARRAY_ELEMENTS; i++) - if (buffer[i] & ~(map2.buffer[i])) - return false; - return true; - } - bool is_overlapping(const Bitmap& map2) const - { - for (size_t i= 0; i < ARRAY_ELEMENTS; i++) - if (buffer[i] & map2.buffer[i]) - return true; - return false; - } - bool operator==(const Bitmap& map2) const - { - if (ARRAY_ELEMENTS > 1) - return !memcmp(buffer,map2.buffer,sizeof(buffer)); - return buffer[0] == map2.buffer[0]; - } - bool operator!=(const Bitmap& map2) const - { - return !(*this == map2); - } - /* - Print hexadecimal representation of bitmap. - Truncate trailing zeros. - */ - char *print(char *buf) const - { - size_t last; /*index of the last non-zero element, or 0. */ - - for (last= ARRAY_ELEMENTS - 1; last && !buffer[last]; last--){} - - const int HEX_DIGITS_PER_ELEMENT= BITS_PER_ELEMENT / 4; - for (size_t i= 0; i < last; i++) - { - ulonglong num = buffer[i]; - uint shift = BITS_PER_ELEMENT - 4; - size_t pos= i * HEX_DIGITS_PER_ELEMENT; - for (size_t j= 0; j < HEX_DIGITS_PER_ELEMENT; j++) - { - buf[pos + j]= _dig_vec_upper[(num >> shift) & 0xf]; - shift += 4; - } - } - longlong2str(buffer[last], buf, 16); - return buf; - } - ulonglong to_ulonglong() const - { - return buffer[0]; - } - uint bits_set() - { - uint res= 0; - for (size_t i= 0; i < ARRAY_ELEMENTS; i++) - res += my_count_bits(buffer[i]); - return res; - } - class Iterator - { - const Bitmap& map; - uint offset; - Table_map_iterator tmi; - public: - Iterator(const Bitmap& map2) : map(map2), offset(0), tmi(map2.buffer[0]) {} - int operator++(int) - { - for (;;) - { - int nextbit= tmi++; - - if (nextbit != Table_map_iterator::BITMAP_END) - return offset + nextbit; - - if (offset + BITS_PER_ELEMENT >= map.length()) - return BITMAP_END; - - offset += BITS_PER_ELEMENT; - tmi= Table_map_iterator(map.buffer[offset / BITS_PER_ELEMENT]); - } - } - enum { BITMAP_END = width }; - }; - -#ifdef NEED_GCC_NO_SSE_WORKAROUND -#pragma GCC pop_options -#undef NEED_GCC_NO_SSE_WORKAROUND -#endif -}; - -typedef Bitmap key_map; /* Used for finding keys */ - -#endif /* SQL_BITMAP_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_bootstrap.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_bootstrap.h deleted file mode 100644 index f12d66a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_bootstrap.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef SQL_BOOTSTRAP_H -#define SQL_BOOTSTRAP_H - -/** - The maximum size of a bootstrap query. - Increase this size if parsing a longer query during bootstrap is necessary. - The longest query in use depends on the documentation content, - see the file fill_help_tables.sql -*/ -#define MAX_BOOTSTRAP_QUERY_SIZE 20000 -/** - The maximum size of a bootstrap query, expressed in a single line. - Do not increase this size, use the multiline syntax instead. -*/ -#define MAX_BOOTSTRAP_LINE_SIZE 20000 -#define MAX_BOOTSTRAP_ERROR_LEN 256 - -#define READ_BOOTSTRAP_SUCCESS 0 -#define READ_BOOTSTRAP_EOF 1 -#define READ_BOOTSTRAP_ERROR 2 -#define READ_BOOTSTRAP_QUERY_SIZE 3 - -typedef void *fgets_input_t; -typedef char * (*fgets_fn_t)(char *, size_t, fgets_input_t, int *error); - -int read_bootstrap_query(char *query, int *query_length, - fgets_input_t input, fgets_fn_t fgets_fn, int *error); - -#endif - - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cache.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cache.h deleted file mode 100644 index b92b397..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cache.h +++ /dev/null @@ -1,612 +0,0 @@ -/* Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _SQL_CACHE_H -#define _SQL_CACHE_H - -#include "hash.h" -#include "my_base.h" /* ha_rows */ - -class MY_LOCALE; -struct TABLE_LIST; -class Time_zone; -struct LEX; -struct TABLE; -typedef struct st_changed_table_list CHANGED_TABLE_LIST; - -/* Query cache */ - -/* - Can't create new free memory block if unused memory in block less - then QUERY_CACHE_MIN_ALLOCATION_UNIT. - if QUERY_CACHE_MIN_ALLOCATION_UNIT == 0 then - QUERY_CACHE_MIN_ALLOCATION_UNIT choosed automaticaly -*/ -#define QUERY_CACHE_MIN_ALLOCATION_UNIT 512 - -/* inittial size of hashes */ -#define QUERY_CACHE_DEF_QUERY_HASH_SIZE 1024 -#define QUERY_CACHE_DEF_TABLE_HASH_SIZE 1024 - -/* minimal result data size when data allocated */ -#define QUERY_CACHE_MIN_RESULT_DATA_SIZE (1024*4) - -/* - start estimation of first result block size only when number of queries - bigger then: -*/ -#define QUERY_CACHE_MIN_ESTIMATED_QUERIES_NUMBER 3 - - - -/* memory bins size spacing (see at Query_cache::init_cache (sql_cache.cc)) */ -#define QUERY_CACHE_MEM_BIN_FIRST_STEP_PWR2 4 -#define QUERY_CACHE_MEM_BIN_STEP_PWR2 2 -#define QUERY_CACHE_MEM_BIN_PARTS_INC 1 -#define QUERY_CACHE_MEM_BIN_PARTS_MUL 1.2 -#define QUERY_CACHE_MEM_BIN_SPC_LIM_PWR2 3 - -/* how many free blocks check when finding most suitable before other 'end' - of list of free blocks */ -#define QUERY_CACHE_MEM_BIN_TRY 5 - -/* packing parameters */ -#define QUERY_CACHE_PACK_ITERATION 2 -#define QUERY_CACHE_PACK_LIMIT (512*1024L) - -#define TABLE_COUNTER_TYPE uint - -struct Query_cache_block; -struct Query_cache_block_table; -struct Query_cache_table; -struct Query_cache_query; -struct Query_cache_result; -class Query_cache; -struct Query_cache_tls; -struct LEX; -class THD; - -typedef my_bool (*qc_engine_callback)(THD *thd, const char *table_key, - uint key_length, - ulonglong *engine_data); - -/** - This class represents a node in the linked chain of queries - belonging to one table. - - @note The root of this linked list is not a query-type block, but the table- - type block which all queries has in common. -*/ -struct Query_cache_block_table -{ - Query_cache_block_table() {} /* Remove gcc warning */ - - /** - This node holds a position in a static table list belonging - to the associated query (base 0). - */ - TABLE_COUNTER_TYPE n; - - /** - Pointers to the next and previous node, linking all queries with - a common table. - */ - Query_cache_block_table *next, *prev; - - /** - A pointer to the table-type block which all - linked queries has in common. - */ - Query_cache_table *parent; - - /** - A method to calculate the address of the query cache block - owning this node. The purpose of this calculation is to - make it easier to move the query cache block without having - to modify all the pointer addresses. - */ - inline Query_cache_block *block(); -}; - -struct Query_cache_block -{ - Query_cache_block() {} /* Remove gcc warning */ - enum block_type {FREE, QUERY, RESULT, RES_CONT, RES_BEG, - RES_INCOMPLETE, TABLE, INCOMPLETE}; - - size_t length; // length of all block - size_t used; // length of data - /* - Not used **pprev, **prev because really needed access to pervious block: - *pprev to join free blocks - *prev to access to opposite side of list in cyclic sorted list - */ - Query_cache_block *pnext,*pprev, // physical next/previous block - *next,*prev; // logical next/previous block - block_type type; - TABLE_COUNTER_TYPE n_tables; // number of tables in query - - inline bool is_free(void) { return type == FREE; } - void init(size_t length); - void destroy(); - uint headers_len(); - uchar* data(void); - Query_cache_query *query(); - Query_cache_table *table(); - Query_cache_result *result(); - Query_cache_block_table *table(TABLE_COUNTER_TYPE n); -}; - -struct Query_cache_query -{ - ulonglong limit_found_rows; - mysql_rwlock_t lock; - Query_cache_block *res; - Query_cache_tls *wri; - size_t len; - unsigned int last_pkt_nr; - uint8 tbls_type; - uint8 ready; - ulonglong hit_count; - - Query_cache_query() {} /* Remove gcc warning */ - inline void init_n_lock(); - void unlock_n_destroy(); - inline ulonglong found_rows() { return limit_found_rows; } - inline void found_rows(ulonglong rows) { limit_found_rows= rows; } - inline Query_cache_block *result() { return res; } - inline void result(Query_cache_block *p) { res= p; } - inline Query_cache_tls *writer() { return wri; } - inline void writer(Query_cache_tls *p) { wri= p; } - inline uint8 tables_type() { return tbls_type; } - inline void tables_type(uint8 type) { tbls_type= type; } - inline size_t length() { return len; } - inline size_t add(size_t packet_len) { return(len+= packet_len); } - inline void length(size_t length_arg) { len= length_arg; } - inline uchar* query() - { - return (((uchar*)this) + ALIGN_SIZE(sizeof(Query_cache_query))); - } - /** - following used to check if result ready in plugin without - locking rw_lock of the query. - */ - inline void set_results_ready() { ready= 1; } - inline bool is_results_ready() { return ready; } - inline void increment_hits() { hit_count++; } - inline ulonglong hits() { return hit_count; } - void lock_writing(); - void lock_reading(); - bool try_lock_writing(); - void unlock_writing(); - void unlock_reading(); -}; - - -struct Query_cache_table -{ - Query_cache_table() {} /* Remove gcc warning */ - char *tbl; - uint32 key_len; - uint8 suffix_len; /* For partitioned tables */ - uint8 table_type; - /* unique for every engine reference */ - qc_engine_callback callback_func; - /* data need by some engines */ - ulonglong engine_data_buff; - - /** - The number of queries depending of this table. - */ - int32 m_cached_query_count; - /** - If table included in the table hash to be found by other queries - */ - my_bool hashed; - - inline char *db() { return (char *) data(); } - inline char *table() { return tbl; } - inline void table(char *table_arg) { tbl= table_arg; } - inline uint32 key_length() { return key_len; } - inline void key_length(uint32 len) { key_len= len; } - inline uint8 suffix_length() { return suffix_len; } - inline void suffix_length(uint8 len) { suffix_len= len; } - inline uint8 type() { return table_type; } - inline void type(uint8 t) { table_type= t; } - inline qc_engine_callback callback() { return callback_func; } - inline void callback(qc_engine_callback fn){ callback_func= fn; } - inline ulonglong engine_data() { return engine_data_buff; } - inline void engine_data(ulonglong data_arg){ engine_data_buff= data_arg; } - inline my_bool is_hashed() { return hashed; } - inline void set_hashed(my_bool hash) { hashed= hash; } - inline uchar* data() - { - return (uchar*)(((uchar*)this)+ - ALIGN_SIZE(sizeof(Query_cache_table))); - } -}; - -struct Query_cache_result -{ - Query_cache_result() {} /* Remove gcc warning */ - Query_cache_block *query; - - inline uchar* data() - { - return (uchar*)(((uchar*) this)+ - ALIGN_SIZE(sizeof(Query_cache_result))); - } - /* data_continue (if not whole packet contained by this block) */ - inline Query_cache_block *parent() { return query; } - inline void parent (Query_cache_block *p) { query=p; } -}; - - -extern "C" -{ - uchar *query_cache_query_get_key(const uchar *record, size_t *length, - my_bool not_used); - uchar *query_cache_table_get_key(const uchar *record, size_t *length, - my_bool not_used); -} -extern "C" void query_cache_invalidate_by_MyISAM_filename(const char* filename); - - -struct Query_cache_memory_bin -{ - Query_cache_memory_bin() {} /* Remove gcc warning */ -#ifndef DBUG_OFF - size_t size; -#endif - uint number; - Query_cache_block *free_blocks; - - inline void init(size_t size_arg) - { -#ifndef DBUG_OFF - size = size_arg; -#endif - number = 0; - free_blocks = 0; - } -}; - -struct Query_cache_memory_bin_step -{ - Query_cache_memory_bin_step() {} /* Remove gcc warning */ - size_t size; - size_t increment; - size_t idx; - inline void init(size_t size_arg, size_t idx_arg, size_t increment_arg) - { - size = size_arg; - idx = idx_arg; - increment = increment_arg; - } -}; - -class Query_cache -{ -public: - /* Info */ - size_t query_cache_size, query_cache_limit; - /* statistics */ - size_t free_memory, queries_in_cache, hits, inserts, refused, - free_memory_blocks, total_blocks, lowmem_prunes; - - -private: -#ifndef DBUG_OFF - my_thread_id m_cache_lock_thread_id; -#endif - mysql_cond_t COND_cache_status_changed; - uint m_requests_in_progress; - enum Cache_lock_status { UNLOCKED, LOCKED_NO_WAIT, LOCKED }; - Cache_lock_status m_cache_lock_status; - enum Cache_staus {OK, DISABLE_REQUEST, DISABLED}; - Cache_staus m_cache_status; - - void free_query_internal(Query_cache_block *point); - void invalidate_table_internal(THD *thd, uchar *key, size_t key_length); - -protected: - /* - The following mutex is locked when searching or changing global - query, tables lists or hashes. When we are operating inside the - query structure we locked an internal query block mutex. - LOCK SEQUENCE (to prevent deadlocks): - 1. structure_guard_mutex - 2. query block (for operation inside query (query block/results)) - - Thread doing cache flush releases the mutex once it sets - m_cache_lock_status flag, so other threads may bypass the cache as - if it is disabled, not waiting for reset to finish. The exception - is other threads that were going to do cache flush---they'll wait - till the end of a flush operation. - */ - mysql_mutex_t structure_guard_mutex; - size_t additional_data_size; - uchar *cache; // cache memory - Query_cache_block *first_block; // physical location block list - Query_cache_block *queries_blocks; // query list (LIFO) - Query_cache_block *tables_blocks; - - Query_cache_memory_bin *bins; // free block lists - Query_cache_memory_bin_step *steps; // bins spacing info - HASH queries, tables; - /* options */ - size_t min_allocation_unit, min_result_data_size; - uint def_query_hash_size, def_table_hash_size; - - size_t mem_bin_num, mem_bin_steps; // See at init_cache & find_bin - - bool initialized; - - /* Exclude/include from cyclic double linked list */ - static void double_linked_list_exclude(Query_cache_block *point, - Query_cache_block **list_pointer); - static void double_linked_list_simple_include(Query_cache_block *point, - Query_cache_block ** - list_pointer); - static void double_linked_list_join(Query_cache_block *head_tail, - Query_cache_block *tail_head); - - /* The following functions require that structure_guard_mutex is locked */ - void flush_cache(); - my_bool free_old_query(); - void free_query(Query_cache_block *point); - my_bool allocate_data_chain(Query_cache_block **result_block, - size_t data_len, - Query_cache_block *query_block, - my_bool first_block); - void invalidate_table(THD *thd, TABLE_LIST *table); - void invalidate_table(THD *thd, TABLE *table); - void invalidate_table(THD *thd, uchar *key, size_t key_length); - void invalidate_table(THD *thd, Query_cache_block *table_block); - void invalidate_query_block_list(THD *thd, - Query_cache_block_table *list_root); - - TABLE_COUNTER_TYPE - register_tables_from_list(THD *thd, TABLE_LIST *tables_used, - TABLE_COUNTER_TYPE counter, - Query_cache_block_table **block_table); - my_bool register_all_tables(THD *thd, Query_cache_block *block, - TABLE_LIST *tables_used, - TABLE_COUNTER_TYPE tables); - void unlink_table(Query_cache_block_table *node); - Query_cache_block *get_free_block (size_t len, my_bool not_less, - size_t min); - void free_memory_block(Query_cache_block *point); - void split_block(Query_cache_block *block, size_t len); - Query_cache_block *join_free_blocks(Query_cache_block *first_block, - Query_cache_block *block_in_list); - my_bool append_next_free_block(Query_cache_block *block, - size_t add_size); - void exclude_from_free_memory_list(Query_cache_block *free_block); - void insert_into_free_memory_list(Query_cache_block *new_block); - my_bool move_by_type(uchar **border, Query_cache_block **before, - size_t *gap, Query_cache_block *i); - uint find_bin(size_t size); - void move_to_query_list_end(Query_cache_block *block); - void insert_into_free_memory_sorted_list(Query_cache_block *new_block, - Query_cache_block **list); - void pack_cache(); - void relink(Query_cache_block *oblock, - Query_cache_block *nblock, - Query_cache_block *next, - Query_cache_block *prev, - Query_cache_block *pnext, - Query_cache_block *pprev); - my_bool join_results(size_t join_limit); - - /* - Following function control structure_guard_mutex - by themself or don't need structure_guard_mutex - */ - size_t init_cache(); - void make_disabled(); - void free_cache(); - Query_cache_block *write_block_data(size_t data_len, uchar* data, - size_t header_len, - Query_cache_block::block_type type, - TABLE_COUNTER_TYPE ntab = 0); - my_bool append_result_data(Query_cache_block **result, - size_t data_len, uchar* data, - Query_cache_block *parent); - my_bool write_result_data(Query_cache_block **result, - size_t data_len, uchar* data, - Query_cache_block *parent, - Query_cache_block::block_type - type=Query_cache_block::RESULT); - inline size_t get_min_first_result_data_size(); - inline size_t get_min_append_result_data_size(); - Query_cache_block *allocate_block(size_t len, my_bool not_less, - size_t min); - /* - If query is cacheable return number tables in query - (query without tables not cached) - */ - TABLE_COUNTER_TYPE is_cacheable(THD *thd, - LEX *lex, TABLE_LIST *tables_used, - uint8 *tables_type); - TABLE_COUNTER_TYPE process_and_count_tables(THD *thd, - TABLE_LIST *tables_used, - uint8 *tables_type); - - static my_bool ask_handler_allowance(THD *thd, TABLE_LIST *tables_used); - public: - - Query_cache(size_t query_cache_limit = ULONG_MAX, - size_t min_allocation_unit = QUERY_CACHE_MIN_ALLOCATION_UNIT, - size_t min_result_data_size = QUERY_CACHE_MIN_RESULT_DATA_SIZE, - uint def_query_hash_size = QUERY_CACHE_DEF_QUERY_HASH_SIZE, - uint def_table_hash_size = QUERY_CACHE_DEF_TABLE_HASH_SIZE); - - inline bool is_disabled(void) { return m_cache_status != OK; } - inline bool is_disable_in_progress(void) - { return m_cache_status == DISABLE_REQUEST; } - - /* initialize cache (mutex) */ - void init(); - /* resize query cache (return real query size, 0 if disabled) */ - size_t resize(size_t query_cache_size); - /* set limit on result size */ - inline void result_size_limit(size_t limit){query_cache_limit=limit;} - /* set minimal result data allocation unit size */ - size_t set_min_res_unit(size_t size); - - /* register query in cache */ - void store_query(THD *thd, TABLE_LIST *used_tables); - - /* - Check if the query is in the cache and if this is true send the - data to client. - */ - int send_result_to_client(THD *thd, char *query, uint query_length); - - /* Remove all queries that uses any of the listed following tables */ - void invalidate(THD *thd, TABLE_LIST *tables_used, - my_bool using_transactions); - void invalidate(THD *thd, CHANGED_TABLE_LIST *tables_used); - void invalidate_locked_for_write(THD *thd, TABLE_LIST *tables_used); - void invalidate(THD *thd, TABLE *table, my_bool using_transactions); - void invalidate(THD *thd, const char *key, size_t key_length, - my_bool using_transactions); - - /* Remove all queries that uses any of the tables in following database */ - void invalidate(THD *thd, const char *db); - - /* Remove all queries that uses any of the listed following table */ - void invalidate_by_MyISAM_filename(const char *filename); - - void flush(); - void pack(THD *thd, - size_t join_limit = QUERY_CACHE_PACK_LIMIT, - uint iteration_limit = QUERY_CACHE_PACK_ITERATION); - - void destroy(); - - void insert(THD *thd, Query_cache_tls *query_cache_tls, - const char *packet, - size_t length, - unsigned pkt_nr); - my_bool insert_table(THD *thd, size_t key_len, const char *key, - Query_cache_block_table *node, - size_t db_length, uint8 suffix_length_arg, - uint8 cache_type, - qc_engine_callback callback, - ulonglong engine_data, - my_bool hash); - - void end_of_result(THD *thd); - void abort(THD *thd, Query_cache_tls *query_cache_tls); - - /* - The following functions are only used when debugging - We don't protect these with ifndef DBUG_OFF to not have to recompile - everything if we want to add checks of the cache at some places. - */ - void wreck(uint line, const char *message); - void bins_dump(); - void cache_dump(); - void queries_dump(); - void tables_dump(); - my_bool check_integrity(bool not_locked); - my_bool in_list(Query_cache_block * root, Query_cache_block * point, - const char *name); - my_bool in_table_list(Query_cache_block_table * root, - Query_cache_block_table * point, - const char *name); - my_bool in_blocks(Query_cache_block * point); - - /* Table key generation */ - static uint filename_2_table_key (char *key, const char *filename, - uint32 *db_langth); - - enum Cache_try_lock_mode {WAIT, TIMEOUT, TRY}; - bool try_lock(THD *thd, Cache_try_lock_mode mode= WAIT); - void lock(THD *thd); - void lock_and_suspend(void); - void unlock(void); - - void disable_query_cache(THD *thd); -}; - -#ifdef HAVE_QUERY_CACHE -struct Query_cache_query_flags -{ - unsigned int client_long_flag:1; - unsigned int client_protocol_41:1; - unsigned int client_depr_eof:1; - unsigned int protocol_type:2; - unsigned int more_results_exists:1; - unsigned int in_trans:1; - unsigned int autocommit:1; - unsigned int pkt_nr; - uint character_set_client_num; - uint character_set_results_num; - uint collation_connection_num; - ha_rows limit; - Time_zone *time_zone; - sql_mode_t sql_mode; - ulonglong max_sort_length; - ulonglong group_concat_max_len; - size_t default_week_format; - size_t div_precision_increment; - MY_LOCALE *lc_time_names; -}; -#define QUERY_CACHE_FLAGS_SIZE sizeof(Query_cache_query_flags) -#define QUERY_CACHE_DB_LENGTH_SIZE 2 -#include "sql_cache.h" -#define query_cache_abort(A,B) query_cache.abort(A,B) -#define query_cache_end_of_result(A) query_cache.end_of_result(A) -#define query_cache_store_query(A, B) query_cache.store_query(A, B) -#define query_cache_destroy() query_cache.destroy() -#define query_cache_result_size_limit(A) query_cache.result_size_limit(A) -#define query_cache_init() query_cache.init() -#define query_cache_resize(A) query_cache.resize(A) -#define query_cache_set_min_res_unit(A) query_cache.set_min_res_unit(A) -#define query_cache_invalidate3(A, B, C) query_cache.invalidate(A, B, C) -#define query_cache_invalidate1(A, B) query_cache.invalidate(A, B) -#define query_cache_send_result_to_client(A, B, C) \ - query_cache.send_result_to_client(A, B, C) -#define query_cache_invalidate_by_MyISAM_filename_ref \ - &query_cache_invalidate_by_MyISAM_filename -/* note the "maybe": it's a read without mutex */ -#define query_cache_maybe_disabled(T) \ - (T->variables.query_cache_type == 0 || query_cache.query_cache_size == 0) -#define query_cache_is_cacheable_query(L) \ - (((L)->sql_command == SQLCOM_SELECT) && (L)->safe_to_cache_query) -#else -#define QUERY_CACHE_FLAGS_SIZE 0 -#define query_cache_store_query(A, B) do { } while(0) -#define query_cache_destroy() do { } while(0) -#define query_cache_result_size_limit(A) do { } while(0) -#define query_cache_init() do { } while(0) -#define query_cache_resize(A) do { } while(0) -#define query_cache_set_min_res_unit(A) do { } while(0) -#define query_cache_invalidate3(A, B, C) do { } while(0) -#define query_cache_invalidate1(A,B) do { } while(0) -#define query_cache_send_result_to_client(A, B, C) 0 -#define query_cache_invalidate_by_MyISAM_filename_ref NULL - -#define query_cache_abort(A,B) do { } while(0) -#define query_cache_end_of_result(A) do { } while(0) -#define query_cache_maybe_disabled(T) 1 -#define query_cache_is_cacheable_query(L) 0 -#endif /*HAVE_QUERY_CACHE*/ - -extern MYSQL_PLUGIN_IMPORT Query_cache query_cache; -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_callback.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_callback.h deleted file mode 100644 index 1f798ad..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_callback.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -#ifndef SQL_CALLBACK_INCLUDED -#define SQL_CALLBACK_INCLUDED - -/** - Macro used for an internal callback. - - The macro will check that the object exists and that the function - is defined. If that is the case, it will call the function with the - given parameters. - - If the object or the function is not defined, the callback will be - considered successful (nothing needed to be done) and will - therefore return no error. - */ - -#define MYSQL_CALLBACK(OBJ, FUNC, PARAMS) \ - do { \ - if ((OBJ) && ((OBJ)->FUNC)) \ - (OBJ)->FUNC PARAMS; \ - } while (0) - -#define MYSQL_CALLBACK_ELSE(OBJ, FUNC, PARAMS, ELSE) \ - (((OBJ) && ((OBJ)->FUNC)) ? (OBJ)->FUNC PARAMS : (ELSE)) - -#endif /* SQL_CALLBACK_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_class.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_class.h deleted file mode 100644 index 87773b8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_class.h +++ /dev/null @@ -1,7483 +0,0 @@ -/* - Copyright (c) 2000, 2016, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_CLASS_INCLUDED -#define SQL_CLASS_INCLUDED - -/* Classes in mysql */ - -#include -#include "dur_prop.h" -#include -#include "sql_const.h" -#include -#include "log.h" -#include "rpl_tblmap.h" -#include "mdl.h" -#include "field.h" // Create_field -#include "opt_trace_context.h" -#include "probes_mysql.h" -#include "sql_locale.h" /* my_locale_st */ -#include "sql_profile.h" /* PROFILING */ -#include "scheduler.h" /* thd_scheduler */ -#include "protocol.h" /* Protocol_text, Protocol_binary */ -#include "violite.h" /* vio_is_connected */ -#include "thr_lock.h" /* thr_lock_type, THR_LOCK_DATA, THR_LOCK_INFO */ -#include "thr_timer.h" -#include "thr_malloc.h" -#include "log_slow.h" /* LOG_SLOW_DISABLE_... */ -#include -#include "sql_digest_stream.h" // sql_digest_state -#include -#include -#include -#include -#include -#include "session_tracker.h" -#include "backup.h" -#include "xa.h" - -extern "C" -void set_thd_stage_info(void *thd, - const PSI_stage_info *new_stage, - PSI_stage_info *old_stage, - const char *calling_func, - const char *calling_file, - const unsigned int calling_line); - -#define THD_STAGE_INFO(thd, stage) \ - (thd)->enter_stage(&stage, __func__, __FILE__, __LINE__) - -#include "my_apc.h" -#include "rpl_gtid.h" - -#include "wsrep_mysqld.h" -#ifdef WITH_WSREP -#include -/* wsrep-lib */ -#include "wsrep_client_service.h" -#include "wsrep_client_state.h" -#include "wsrep_mutex.h" -#include "wsrep_condition_variable.h" - -class Wsrep_applier_service; -#endif /* WITH_WSREP */ - -class Reprepare_observer; -class Relay_log_info; -struct rpl_group_info; -class Rpl_filter; -class Query_log_event; -class Load_log_event; -class Log_event_writer; -class sp_rcontext; -class sp_cache; -class Lex_input_stream; -class Parser_state; -class Rows_log_event; -class Sroutine_hash_entry; -class user_var_entry; -struct Trans_binlog_info; -class rpl_io_thread_info; -class rpl_sql_thread_info; -#ifdef HAVE_REPLICATION -struct Slave_info; -#endif - -enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME }; -enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_UPDATE }; -enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON, - DELAY_KEY_WRITE_ALL }; -enum enum_slave_exec_mode { SLAVE_EXEC_MODE_STRICT, - SLAVE_EXEC_MODE_IDEMPOTENT, - SLAVE_EXEC_MODE_LAST_BIT }; -enum enum_slave_run_triggers_for_rbr { SLAVE_RUN_TRIGGERS_FOR_RBR_NO, - SLAVE_RUN_TRIGGERS_FOR_RBR_YES, - SLAVE_RUN_TRIGGERS_FOR_RBR_LOGGING, - SLAVE_RUN_TRIGGERS_FOR_RBR_ENFORCE}; -enum enum_slave_type_conversions { SLAVE_TYPE_CONVERSIONS_ALL_LOSSY, - SLAVE_TYPE_CONVERSIONS_ALL_NON_LOSSY}; - -/* - MARK_COLUMNS_READ: A column is goind to be read. - MARK_COLUMNS_WRITE: A column is going to be written to. - MARK_COLUMNS_READ: A column is goind to be read. - A bit in read set is set to inform handler that the field - is to be read. If field list contains duplicates, then - thd->dup_field is set to point to the last found - duplicate. - MARK_COLUMNS_WRITE: A column is going to be written to. - A bit is set in write set to inform handler that it needs - to update this field in write_row and update_row. -*/ -enum enum_column_usage -{ COLUMNS_READ, COLUMNS_WRITE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE}; - -static inline bool should_mark_column(enum_column_usage column_usage) -{ return column_usage >= MARK_COLUMNS_READ; } - -enum enum_filetype { FILETYPE_CSV, FILETYPE_XML }; - -enum enum_binlog_row_image { - /** PKE in the before image and changed columns in the after image */ - BINLOG_ROW_IMAGE_MINIMAL= 0, - /** Whenever possible, before and after image contain all columns except blobs. */ - BINLOG_ROW_IMAGE_NOBLOB= 1, - /** All columns in both before and after image. */ - BINLOG_ROW_IMAGE_FULL= 2 -}; - - -/* Bits for different SQL modes modes (including ANSI mode) */ -#define MODE_REAL_AS_FLOAT (1ULL << 0) -#define MODE_PIPES_AS_CONCAT (1ULL << 1) -#define MODE_ANSI_QUOTES (1ULL << 2) -#define MODE_IGNORE_SPACE (1ULL << 3) -#define MODE_IGNORE_BAD_TABLE_OPTIONS (1ULL << 4) -#define MODE_ONLY_FULL_GROUP_BY (1ULL << 5) -#define MODE_NO_UNSIGNED_SUBTRACTION (1ULL << 6) -#define MODE_NO_DIR_IN_CREATE (1ULL << 7) -#define MODE_POSTGRESQL (1ULL << 8) -#define MODE_ORACLE (1ULL << 9) -#define MODE_MSSQL (1ULL << 10) -#define MODE_DB2 (1ULL << 11) -#define MODE_MAXDB (1ULL << 12) -#define MODE_NO_KEY_OPTIONS (1ULL << 13) -#define MODE_NO_TABLE_OPTIONS (1ULL << 14) -#define MODE_NO_FIELD_OPTIONS (1ULL << 15) -#define MODE_MYSQL323 (1ULL << 16) -#define MODE_MYSQL40 (1ULL << 17) -#define MODE_ANSI (1ULL << 18) -#define MODE_NO_AUTO_VALUE_ON_ZERO (1ULL << 19) -#define MODE_NO_BACKSLASH_ESCAPES (1ULL << 20) -#define MODE_STRICT_TRANS_TABLES (1ULL << 21) -#define MODE_STRICT_ALL_TABLES (1ULL << 22) -#define MODE_NO_ZERO_IN_DATE (1ULL << 23) -#define MODE_NO_ZERO_DATE (1ULL << 24) -#define MODE_INVALID_DATES (1ULL << 25) -#define MODE_ERROR_FOR_DIVISION_BY_ZERO (1ULL << 26) -#define MODE_TRADITIONAL (1ULL << 27) -#define MODE_NO_AUTO_CREATE_USER (1ULL << 28) -#define MODE_HIGH_NOT_PRECEDENCE (1ULL << 29) -#define MODE_NO_ENGINE_SUBSTITUTION (1ULL << 30) -#define MODE_PAD_CHAR_TO_FULL_LENGTH (1ULL << 31) -/* SQL mode bits defined above are common for MariaDB and MySQL */ -#define MODE_MASK_MYSQL_COMPATIBLE 0xFFFFFFFFULL -/* The following modes are specific to MariaDB */ -#define MODE_EMPTY_STRING_IS_NULL (1ULL << 32) -#define MODE_SIMULTANEOUS_ASSIGNMENT (1ULL << 33) -#define MODE_TIME_ROUND_FRACTIONAL (1ULL << 34) -/* The following modes are specific to MySQL */ -#define MODE_MYSQL80_TIME_TRUNCATE_FRACTIONAL (1ULL << 32) - - -/* Bits for different old style modes */ -#define OLD_MODE_NO_DUP_KEY_WARNINGS_WITH_IGNORE (1 << 0) -#define OLD_MODE_NO_PROGRESS_INFO (1 << 1) -#define OLD_MODE_ZERO_DATE_TIME_CAST (1 << 2) - -extern char internal_table_name[2]; -extern char empty_c_string[1]; -extern MYSQL_PLUGIN_IMPORT const char **errmesg; - -extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd); -extern "C" unsigned long long thd_query_id(const MYSQL_THD thd); -extern "C" size_t thd_query_safe(MYSQL_THD thd, char *buf, size_t buflen); -extern "C" const char *thd_user_name(MYSQL_THD thd); -extern "C" const char *thd_client_host(MYSQL_THD thd); -extern "C" const char *thd_client_ip(MYSQL_THD thd); -extern "C" LEX_CSTRING *thd_current_db(MYSQL_THD thd); -extern "C" int thd_current_status(MYSQL_THD thd); -extern "C" enum enum_server_command thd_current_command(MYSQL_THD thd); - -/** - @class CSET_STRING - @brief Character set armed LEX_STRING -*/ -class CSET_STRING -{ -private: - LEX_STRING string; - CHARSET_INFO *cs; -public: - CSET_STRING() : cs(&my_charset_bin) - { - string.str= NULL; - string.length= 0; - } - CSET_STRING(char *str_arg, size_t length_arg, CHARSET_INFO *cs_arg) : - cs(cs_arg) - { - DBUG_ASSERT(cs_arg != NULL); - string.str= str_arg; - string.length= length_arg; - } - - inline char *str() const { return string.str; } - inline size_t length() const { return string.length; } - CHARSET_INFO *charset() const { return cs; } - - friend LEX_STRING * thd_query_string (MYSQL_THD thd); -}; - - -#define TC_HEURISTIC_RECOVER_COMMIT 1 -#define TC_HEURISTIC_RECOVER_ROLLBACK 2 -extern ulong tc_heuristic_recover; - -typedef struct st_user_var_events -{ - user_var_entry *user_var_event; - char *value; - size_t length; - Item_result type; - uint charset_number; - bool unsigned_flag; -} BINLOG_USER_VAR_EVENT; - -/* - The COPY_INFO structure is used by INSERT/REPLACE code. - The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY - UPDATE code: - If a row is inserted then the copied variable is incremented. - If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the - new data differs from the old one then the copied and the updated - variables are incremented. - The touched variable is incremented if a row was touched by the update part - of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row - was actually changed or not. -*/ -typedef struct st_copy_info { - ha_rows records; /**< Number of processed records */ - ha_rows deleted; /**< Number of deleted records */ - ha_rows updated; /**< Number of updated records */ - ha_rows copied; /**< Number of copied records */ - ha_rows error_count; - ha_rows touched; /* Number of touched records */ - enum enum_duplicates handle_duplicates; - int escape_char, last_errno; - bool ignore; - /* for INSERT ... UPDATE */ - List *update_fields; - List *update_values; - /* for VIEW ... WITH CHECK OPTION */ - TABLE_LIST *view; - TABLE_LIST *table_list; /* Normal table */ -} COPY_INFO; - - -class Key_part_spec :public Sql_alloc { -public: - LEX_CSTRING field_name; - uint length; - bool generated; - Key_part_spec(const LEX_CSTRING *name, uint len, bool gen= false) - : field_name(*name), length(len), generated(gen) - {} - bool operator==(const Key_part_spec& other) const; - /** - Construct a copy of this Key_part_spec. field_name is copied - by-pointer as it is known to never change. At the same time - 'length' may be reset in mysql_prepare_create_table, and this - is why we supply it with a copy. - - @return If out of memory, 0 is returned and an error is set in - THD. - */ - Key_part_spec *clone(MEM_ROOT *mem_root) const - { return new (mem_root) Key_part_spec(*this); } - bool check_key_for_blob(const class handler *file) const; - bool check_key_length_for_blob() const; - bool check_primary_key_for_blob(const class handler *file) const - { - return check_key_for_blob(file) || check_key_length_for_blob(); - } - bool check_foreign_key_for_blob(const class handler *file) const - { - return check_key_for_blob(file) || check_key_length_for_blob(); - } - bool init_multiple_key_for_blob(const class handler *file); -}; - - -class Alter_drop :public Sql_alloc { -public: - enum drop_type { KEY, COLUMN, FOREIGN_KEY, CHECK_CONSTRAINT, PERIOD }; - const char *name; - enum drop_type type; - bool drop_if_exists; - Alter_drop(enum drop_type par_type,const char *par_name, bool par_exists) - :name(par_name), type(par_type), drop_if_exists(par_exists) - { - DBUG_ASSERT(par_name != NULL); - } - /** - Used to make a clone of this object for ALTER/CREATE TABLE - @sa comment for Key_part_spec::clone - */ - Alter_drop *clone(MEM_ROOT *mem_root) const - { return new (mem_root) Alter_drop(*this); } - const char *type_name() - { - return type == COLUMN ? "COLUMN" : - type == CHECK_CONSTRAINT ? "CONSTRAINT" : - type == PERIOD ? "PERIOD" : - type == KEY ? "INDEX" : "FOREIGN KEY"; - } -}; - - -class Alter_column :public Sql_alloc { -public: - LEX_CSTRING name; - LEX_CSTRING new_name; - Virtual_column_info *default_value; - bool alter_if_exists; - Alter_column(LEX_CSTRING par_name, Virtual_column_info *expr, bool par_exists) - :name(par_name), new_name{NULL, 0}, default_value(expr), alter_if_exists(par_exists) {} - Alter_column(LEX_CSTRING par_name, LEX_CSTRING _new_name, bool exists) - :name(par_name), new_name(_new_name), default_value(NULL), alter_if_exists(exists) {} - /** - Used to make a clone of this object for ALTER/CREATE TABLE - @sa comment for Key_part_spec::clone - */ - Alter_column *clone(MEM_ROOT *mem_root) const - { return new (mem_root) Alter_column(*this); } - bool is_rename() - { - DBUG_ASSERT(!new_name.str || !default_value); - return new_name.str; - } -}; - - -class Alter_rename_key : public Sql_alloc -{ -public: - LEX_CSTRING old_name; - LEX_CSTRING new_name; - bool alter_if_exists; - - Alter_rename_key(LEX_CSTRING old_name_arg, LEX_CSTRING new_name_arg, bool exists) - : old_name(old_name_arg), new_name(new_name_arg), alter_if_exists(exists) {} - - Alter_rename_key *clone(MEM_ROOT *mem_root) const - { return new (mem_root) Alter_rename_key(*this); } - -}; - - -class Key :public Sql_alloc, public DDL_options { -public: - enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY}; - enum Keytype type; - KEY_CREATE_INFO key_create_info; - List columns; - LEX_CSTRING name; - engine_option_value *option_list; - bool generated; - bool invisible; - bool without_overlaps; - Lex_ident period; - - Key(enum Keytype type_par, const LEX_CSTRING *name_arg, - ha_key_alg algorithm_arg, bool generated_arg, DDL_options_st ddl_options) - :DDL_options(ddl_options), - type(type_par), key_create_info(default_key_create_info), - name(*name_arg), option_list(NULL), generated(generated_arg), - invisible(false), without_overlaps(false) - { - key_create_info.algorithm= algorithm_arg; - } - Key(enum Keytype type_par, const LEX_CSTRING *name_arg, - KEY_CREATE_INFO *key_info_arg, - bool generated_arg, List *cols, - engine_option_value *create_opt, DDL_options_st ddl_options) - :DDL_options(ddl_options), - type(type_par), key_create_info(*key_info_arg), columns(*cols), - name(*name_arg), option_list(create_opt), generated(generated_arg), - invisible(false), without_overlaps(false) - {} - Key(const Key &rhs, MEM_ROOT *mem_root); - virtual ~Key() {} - /* Equality comparison of keys (ignoring name) */ - friend bool foreign_key_prefix(Key *a, Key *b); - /** - Used to make a clone of this object for ALTER/CREATE TABLE - @sa comment for Key_part_spec::clone - */ - virtual Key *clone(MEM_ROOT *mem_root) const - { return new (mem_root) Key(*this, mem_root); } -}; - - -class Foreign_key: public Key { -public: - enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL, - FK_MATCH_PARTIAL, FK_MATCH_SIMPLE}; - LEX_CSTRING constraint_name; - LEX_CSTRING ref_db; - LEX_CSTRING ref_table; - List ref_columns; - enum enum_fk_option delete_opt, update_opt; - enum fk_match_opt match_opt; - Foreign_key(const LEX_CSTRING *name_arg, List *cols, - const LEX_CSTRING *constraint_name_arg, - const LEX_CSTRING *ref_db_arg, const LEX_CSTRING *ref_table_arg, - List *ref_cols, - enum_fk_option delete_opt_arg, enum_fk_option update_opt_arg, - fk_match_opt match_opt_arg, - DDL_options ddl_options) - :Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols, NULL, - ddl_options), - constraint_name(*constraint_name_arg), - ref_db(*ref_db_arg), ref_table(*ref_table_arg), ref_columns(*ref_cols), - delete_opt(delete_opt_arg), update_opt(update_opt_arg), - match_opt(match_opt_arg) - { - // We don't check for duplicate FKs. - key_create_info.check_for_duplicate_indexes= false; - } - Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root); - /** - Used to make a clone of this object for ALTER/CREATE TABLE - @sa comment for Key_part_spec::clone - */ - virtual Key *clone(MEM_ROOT *mem_root) const - { return new (mem_root) Foreign_key(*this, mem_root); } - /* Used to validate foreign key options */ - bool validate(List &table_fields); -}; - -typedef struct st_mysql_lock -{ - TABLE **table; - THR_LOCK_DATA **locks; - uint table_count,lock_count; - uint flags; -} MYSQL_LOCK; - - -class LEX_COLUMN : public Sql_alloc -{ -public: - String column; - privilege_t rights; - LEX_COLUMN (const String& x,const privilege_t & y ): column (x),rights (y) {} -}; - -class MY_LOCALE; - -/** - Query_cache_tls -- query cache thread local data. -*/ - -struct Query_cache_block; - -struct Query_cache_tls -{ - /* - 'first_query_block' should be accessed only via query cache - functions and methods to maintain proper locking. - */ - Query_cache_block *first_query_block; - void set_first_query_block(Query_cache_block *first_query_block_arg) - { - first_query_block= first_query_block_arg; - } - - Query_cache_tls() :first_query_block(NULL) {} -}; - -/* SIGNAL / RESIGNAL / GET DIAGNOSTICS */ - -/** - This enumeration list all the condition item names of a condition in the - SQL condition area. -*/ -typedef enum enum_diag_condition_item_name -{ - /* - Conditions that can be set by the user (SIGNAL/RESIGNAL), - and by the server implementation. - */ - - DIAG_CLASS_ORIGIN= 0, - FIRST_DIAG_SET_PROPERTY= DIAG_CLASS_ORIGIN, - DIAG_SUBCLASS_ORIGIN= 1, - DIAG_CONSTRAINT_CATALOG= 2, - DIAG_CONSTRAINT_SCHEMA= 3, - DIAG_CONSTRAINT_NAME= 4, - DIAG_CATALOG_NAME= 5, - DIAG_SCHEMA_NAME= 6, - DIAG_TABLE_NAME= 7, - DIAG_COLUMN_NAME= 8, - DIAG_CURSOR_NAME= 9, - DIAG_MESSAGE_TEXT= 10, - DIAG_MYSQL_ERRNO= 11, - LAST_DIAG_SET_PROPERTY= DIAG_MYSQL_ERRNO -} Diag_condition_item_name; - -/** - Name of each diagnostic condition item. - This array is indexed by Diag_condition_item_name. -*/ -extern const LEX_CSTRING Diag_condition_item_names[]; - -/** - These states are bit coded with HARD. For each state there must be a pair - , and _HARD. -*/ -enum killed_state -{ - NOT_KILLED= 0, - KILL_HARD_BIT= 1, /* Bit for HARD KILL */ - KILL_BAD_DATA= 2, - KILL_BAD_DATA_HARD= 3, - KILL_QUERY= 4, - KILL_QUERY_HARD= 5, - /* - ABORT_QUERY signals to the query processor to stop execution ASAP without - issuing an error. Instead a warning is issued, and when possible a partial - query result is returned to the client. - */ - ABORT_QUERY= 6, - ABORT_QUERY_HARD= 7, - KILL_TIMEOUT= 8, - KILL_TIMEOUT_HARD= 9, - /* - When binlog reading thread connects to the server it kills - all the binlog threads with the same ID. - */ - KILL_SLAVE_SAME_ID= 10, - /* - All of the following killed states will kill the connection - KILL_CONNECTION must be the first of these and it must start with - an even number (becasue of HARD bit)! - */ - KILL_CONNECTION= 12, - KILL_CONNECTION_HARD= 13, - KILL_SYSTEM_THREAD= 14, - KILL_SYSTEM_THREAD_HARD= 15, - KILL_SERVER= 16, - KILL_SERVER_HARD= 17, - /* - Used in threadpool to signal wait timeout. - */ - KILL_WAIT_TIMEOUT= 18, - KILL_WAIT_TIMEOUT_HARD= 19 - -}; - -#define killed_mask_hard(killed) ((killed_state) ((killed) & ~KILL_HARD_BIT)) - -enum killed_type -{ - KILL_TYPE_ID, - KILL_TYPE_USER, - KILL_TYPE_QUERY -}; - -#include "sql_lex.h" /* Must be here */ - -class Delayed_insert; -class select_result; -class Time_zone; - -#define THD_SENTRY_MAGIC 0xfeedd1ff -#define THD_SENTRY_GONE 0xdeadbeef - -#define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC) - -typedef struct system_variables -{ - /* - How dynamically allocated system variables are handled: - - The global_system_variables and max_system_variables are "authoritative" - They both should have the same 'version' and 'size'. - When attempting to access a dynamic variable, if the session version - is out of date, then the session version is updated and realloced if - neccessary and bytes copied from global to make up for missing data. - - Note that one should use my_bool instead of bool here, as the variables - are used with my_getopt.c - */ - ulong dynamic_variables_version; - char* dynamic_variables_ptr; - uint dynamic_variables_head; /* largest valid variable offset */ - uint dynamic_variables_size; /* how many bytes are in use */ - - ulonglong max_heap_table_size; - ulonglong tmp_memory_table_size; - ulonglong tmp_disk_table_size; - ulonglong long_query_time; - ulonglong max_statement_time; - ulonglong optimizer_switch; - ulonglong optimizer_trace; - ulong optimizer_trace_max_mem_size; - sql_mode_t sql_mode; ///< which non-standard SQL behaviour should be enabled - sql_mode_t old_behavior; ///< which old SQL behaviour should be enabled - ulonglong option_bits; ///< OPTION_xxx constants, e.g. OPTION_PROFILING - ulonglong join_buff_space_limit; - ulonglong log_slow_filter; - ulonglong log_slow_verbosity; - ulonglong log_slow_disabled_statements; - ulonglong log_disabled_statements; - ulonglong bulk_insert_buff_size; - ulonglong join_buff_size; - ulonglong sortbuff_size; - ulonglong group_concat_max_len; - ulonglong default_regex_flags; - ulonglong max_mem_used; - - /** - Place holders to store Multi-source variables in sys_var.cc during - update and show of variables. - */ - ulonglong slave_skip_counter; - ulonglong max_relay_log_size; - - ha_rows select_limit; - ha_rows max_join_size; - ha_rows expensive_subquery_limit; - ulong auto_increment_increment, auto_increment_offset; -#ifdef WITH_WSREP - /* - Stored values of the auto_increment_increment and auto_increment_offset - that are will be restored when wsrep_auto_increment_control will be set - to 'OFF', because the setting it to 'ON' leads to overwriting of the - original values (which are set by the user) by calculated ones (which - are based on the cluster size): - */ - ulong saved_auto_increment_increment, saved_auto_increment_offset; - ulonglong wsrep_gtid_seq_no; -#endif /* WITH_WSREP */ - uint eq_range_index_dive_limit; - ulong column_compression_zlib_strategy; - ulong lock_wait_timeout; - ulong join_cache_level; - ulong max_allowed_packet; - ulong max_error_count; - ulong max_length_for_sort_data; - ulong max_recursive_iterations; - ulong max_sort_length; - ulong max_tmp_tables; - ulong max_insert_delayed_threads; - ulong min_examined_row_limit; - ulong net_buffer_length; - ulong net_interactive_timeout; - ulong net_read_timeout; - ulong net_retry_count; - ulong net_wait_timeout; - ulong net_write_timeout; - ulong optimizer_prune_level; - ulong optimizer_search_depth; - ulong optimizer_selectivity_sampling_limit; - ulong optimizer_use_condition_selectivity; - ulong use_stat_tables; - double sample_percentage; - ulong histogram_size; - ulong histogram_type; - ulong preload_buff_size; - ulong profiling_history_size; - ulong read_buff_size; - ulong read_rnd_buff_size; - ulong mrr_buff_size; - ulong div_precincrement; - /* Total size of all buffers used by the subselect_rowid_merge_engine. */ - ulong rowid_merge_buff_size; - ulong max_sp_recursion_depth; - ulong default_week_format; - ulong max_seeks_for_key; - ulong range_alloc_block_size; - ulong query_alloc_block_size; - ulong query_prealloc_size; - ulong trans_alloc_block_size; - ulong trans_prealloc_size; - ulong log_warnings; - /* Flags for slow log filtering */ - ulong log_slow_rate_limit; - ulong binlog_format; ///< binlog format for this thd (see enum_binlog_format) - ulong binlog_row_image; - ulong progress_report_time; - ulong completion_type; - ulong query_cache_type; - ulong tx_isolation; - ulong updatable_views_with_limit; - ulong alter_algorithm; - int max_user_connections; - ulong server_id; - /** - In slave thread we need to know in behalf of which - thread the query is being run to replicate temp tables properly - */ - my_thread_id pseudo_thread_id; - /** - When replicating an event group with GTID, keep these values around so - slave binlog can receive the same GTID as the original. - */ - uint32 gtid_domain_id; - uint64 gtid_seq_no; - - /** - Default transaction access mode. READ ONLY (true) or READ WRITE (false). - */ - my_bool tx_read_only; - my_bool low_priority_updates; - my_bool query_cache_wlock_invalidate; - my_bool keep_files_on_create; - - my_bool old_mode; - my_bool old_passwords; - my_bool big_tables; - my_bool only_standard_compliant_cte; - my_bool query_cache_strip_comments; - my_bool sql_log_slow; - my_bool sql_log_bin; - my_bool binlog_annotate_row_events; - my_bool binlog_direct_non_trans_update; - my_bool column_compression_zlib_wrap; - - plugin_ref table_plugin; - plugin_ref tmp_table_plugin; - plugin_ref enforced_table_plugin; - - /* Only charset part of these variables is sensible */ - CHARSET_INFO *character_set_filesystem; - CHARSET_INFO *character_set_client; - CHARSET_INFO *character_set_results; - - /* Both charset and collation parts of these variables are important */ - CHARSET_INFO *collation_server; - CHARSET_INFO *collation_database; - CHARSET_INFO *collation_connection; - - /* Names. These will be allocated in buffers in thd */ - LEX_CSTRING default_master_connection; - - /* Error messages */ - MY_LOCALE *lc_messages; - const char ***errmsgs; /* lc_messages->errmsg->errmsgs */ - - /* Locale Support */ - MY_LOCALE *lc_time_names; - - Time_zone *time_zone; - - my_bool sysdate_is_now; - - /* deadlock detection */ - ulong wt_timeout_short, wt_deadlock_search_depth_short; - ulong wt_timeout_long, wt_deadlock_search_depth_long; - - my_bool wsrep_on; - my_bool wsrep_causal_reads; - uint wsrep_sync_wait; - ulong wsrep_retry_autocommit; - ulonglong wsrep_trx_fragment_size; - ulong wsrep_trx_fragment_unit; - ulong wsrep_OSU_method; - my_bool wsrep_dirty_reads; - double long_query_time_double, max_statement_time_double; - - my_bool pseudo_slave_mode; - - char *session_track_system_variables; - ulong session_track_transaction_info; - my_bool session_track_schema; - my_bool session_track_state_change; -#ifdef USER_VAR_TRACKING - my_bool session_track_user_variables; -#endif // USER_VAR_TRACKING - my_bool tcp_nodelay; - - ulong threadpool_priority; - - uint idle_transaction_timeout; - uint idle_readonly_transaction_timeout; - uint idle_write_transaction_timeout; - uint column_compression_threshold; - uint column_compression_zlib_level; - uint in_subquery_conversion_threshold; - ulonglong max_rowid_filter_size; - - vers_asof_timestamp_t vers_asof_timestamp; - ulong vers_alter_history; -} SV; - -/** - Per thread status variables. - Must be long/ulong up to last_system_status_var so that - add_to_status/add_diff_to_status can work. -*/ - -typedef struct system_status_var -{ - ulong column_compressions; - ulong column_decompressions; - ulong com_stat[(uint) SQLCOM_END]; - ulong com_create_tmp_table; - ulong com_drop_tmp_table; - ulong com_other; - ulong com_multi; - - ulong com_stmt_prepare; - ulong com_stmt_reprepare; - ulong com_stmt_execute; - ulong com_stmt_send_long_data; - ulong com_stmt_fetch; - ulong com_stmt_reset; - ulong com_stmt_close; - - ulong com_register_slave; - ulong created_tmp_disk_tables_; - ulong created_tmp_tables_; - ulong ha_commit_count; - ulong ha_delete_count; - ulong ha_read_first_count; - ulong ha_read_last_count; - ulong ha_read_key_count; - ulong ha_read_next_count; - ulong ha_read_prev_count; - ulong ha_read_retry_count; - ulong ha_read_rnd_count; - ulong ha_read_rnd_next_count; - ulong ha_read_rnd_deleted_count; - - /* - This number doesn't include calls to the default implementation and - calls made by range access. The intent is to count only calls made by - BatchedKeyAccess. - */ - ulong ha_mrr_init_count; - ulong ha_mrr_key_refills_count; - ulong ha_mrr_rowid_refills_count; - - ulong ha_rollback_count; - ulong ha_update_count; - ulong ha_write_count; - /* The following are for internal temporary tables */ - ulong ha_tmp_update_count; - ulong ha_tmp_write_count; - ulong ha_tmp_delete_count; - ulong ha_prepare_count; - ulong ha_icp_attempts; - ulong ha_icp_match; - ulong ha_discover_count; - ulong ha_savepoint_count; - ulong ha_savepoint_rollback_count; - ulong ha_external_lock_count; - - ulong opened_tables; - ulong opened_shares; - ulong opened_views; /* +1 opening a view */ - - ulong select_full_join_count_; - ulong select_full_range_join_count_; - ulong select_range_count_; - ulong select_range_check_count_; - ulong select_scan_count_; - ulong update_scan_count; - ulong delete_scan_count; - ulong executed_triggers; - ulong long_query_count; - ulong filesort_merge_passes_; - ulong filesort_range_count_; - ulong filesort_rows_; - ulong filesort_scan_count_; - ulong filesort_pq_sorts_; - - /* Features used */ - ulong feature_custom_aggregate_functions; /* +1 when custom aggregate - functions are used */ - ulong feature_dynamic_columns; /* +1 when creating a dynamic column */ - ulong feature_fulltext; /* +1 when MATCH is used */ - ulong feature_gis; /* +1 opening a table with GIS features */ - ulong feature_invisible_columns; /* +1 opening a table with invisible column */ - ulong feature_json; /* +1 when JSON function appears in the statement */ - ulong feature_locale; /* +1 when LOCALE is set */ - ulong feature_subquery; /* +1 when subqueries are used */ - ulong feature_system_versioning; /* +1 opening a table WITH SYSTEM VERSIONING */ - ulong feature_application_time_periods; - /* +1 opening a table with application-time period */ - ulong feature_insert_returning; /* +1 when INSERT...RETURNING is used */ - ulong feature_timezone; /* +1 when XPATH is used */ - ulong feature_trigger; /* +1 opening a table with triggers */ - ulong feature_xml; /* +1 when XPATH is used */ - ulong feature_window_functions; /* +1 when window functions are used */ - - /* From MASTER_GTID_WAIT usage */ - ulong master_gtid_wait_timeouts; /* Number of timeouts */ - ulong master_gtid_wait_time; /* Time in microseconds */ - ulong master_gtid_wait_count; - - ulong empty_queries; - ulong access_denied_errors; - ulong lost_connections; - ulong max_statement_time_exceeded; - /* - Number of statements sent from the client - */ - ulong questions; - /* - IMPORTANT! - SEE last_system_status_var DEFINITION BELOW. - Below 'last_system_status_var' are all variables that cannot be handled - automatically by add_to_status()/add_diff_to_status(). - */ - ulonglong bytes_received; - ulonglong bytes_sent; - ulonglong rows_read; - ulonglong rows_sent; - ulonglong rows_tmp_read; - ulonglong binlog_bytes_written; - ulonglong table_open_cache_hits; - ulonglong table_open_cache_misses; - ulonglong table_open_cache_overflows; - double last_query_cost; - double cpu_time, busy_time; - uint32 threads_running; - /* Don't initialize */ - /* Memory used for thread local storage */ - int64 max_local_memory_used; - volatile int64 local_memory_used; - /* Memory allocated for global usage */ - volatile int64 global_memory_used; -} STATUS_VAR; - -/* - This is used for 'SHOW STATUS'. It must be updated to the last ulong - variable in system_status_var which is makes sense to add to the global - counter -*/ - -#define last_system_status_var questions -#define last_cleared_system_status_var local_memory_used - -/** Number of contiguous global status variables */ -constexpr int COUNT_GLOBAL_STATUS_VARS= int(offsetof(STATUS_VAR, - last_system_status_var) / - sizeof(ulong)) + 1; - -/* - Global status variables -*/ - -extern ulong feature_files_opened_with_delayed_keys, feature_check_constraint; - -void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var); - -void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var, - STATUS_VAR *dec_var); - -/* - Update global_memory_used. We have to do this with atomic_add as the - global value can change outside of LOCK_status. -*/ -inline void update_global_memory_status(int64 size) -{ - DBUG_PRINT("info", ("global memory_used: %lld size: %lld", - (longlong) global_status_var.global_memory_used, - size)); - // workaround for gcc 4.2.4-1ubuntu4 -fPIE (from DEB_BUILD_HARDENING=1) - int64 volatile * volatile ptr= &global_status_var.global_memory_used; - my_atomic_add64_explicit(ptr, size, MY_MEMORY_ORDER_RELAXED); -} - -/** - Get collation by name, send error to client on failure. - @param name Collation name - @param name_cs Character set of the name string - @return - @retval NULL on error - @retval Pointter to CHARSET_INFO with the given name on success -*/ -inline CHARSET_INFO * -mysqld_collation_get_by_name(const char *name, - CHARSET_INFO *name_cs= system_charset_info) -{ - CHARSET_INFO *cs; - MY_CHARSET_LOADER loader; - my_charset_loader_init_mysys(&loader); - if (!(cs= my_collation_get_by_name(&loader, name, MYF(0)))) - { - ErrConvString err(name, name_cs); - my_error(ER_UNKNOWN_COLLATION, MYF(0), err.ptr()); - if (loader.error[0]) - push_warning_printf(current_thd, - Sql_condition::WARN_LEVEL_WARN, - ER_UNKNOWN_COLLATION, "%s", loader.error); - } - return cs; -} - -inline bool is_supported_parser_charset(CHARSET_INFO *cs) -{ - return MY_TEST(cs->mbminlen == 1); -} - -/** THD registry */ -class THD_list_iterator -{ -protected: - I_List threads; - mutable mysql_rwlock_t lock; - -public: - - /** - Iterates registered threads. - - @param action called for every element - @param argument opque argument passed to action - - @return - @retval 0 iteration completed successfully - @retval 1 iteration was interrupted (action returned 1) - */ - template int iterate(my_bool (*action)(THD *thd, T *arg), T *arg= 0) - { - int res= 0; - mysql_rwlock_rdlock(&lock); - I_List_iterator it(threads); - while (auto tmp= it++) - if ((res= action(tmp, arg))) - break; - mysql_rwlock_unlock(&lock); - return res; - } - static THD_list_iterator *iterator(); -}; - -#ifdef MYSQL_SERVER - -void free_tmp_table(THD *thd, TABLE *entry); - - -/* The following macro is to make init of Query_arena simpler */ -#ifdef DBUG_ASSERT_EXISTS -#define INIT_ARENA_DBUG_INFO is_backup_arena= 0; is_reprepared= FALSE; -#else -#define INIT_ARENA_DBUG_INFO -#endif - -class Query_arena -{ -public: - /* - List of items created in the parser for this query. Every item puts - itself to the list on creation (see Item::Item() for details)) - */ - Item *free_list; - MEM_ROOT *mem_root; // Pointer to current memroot -#ifdef DBUG_ASSERT_EXISTS - bool is_backup_arena; /* True if this arena is used for backup. */ - bool is_reprepared; -#endif - /* - The states relfects three diffrent life cycles for three - different types of statements: - Prepared statement: STMT_INITIALIZED -> STMT_PREPARED -> STMT_EXECUTED. - Stored procedure: STMT_INITIALIZED_FOR_SP -> STMT_EXECUTED. - Other statements: STMT_CONVENTIONAL_EXECUTION never changes. - */ - enum enum_state - { - STMT_INITIALIZED= 0, STMT_INITIALIZED_FOR_SP= 1, STMT_PREPARED= 2, - STMT_CONVENTIONAL_EXECUTION= 3, STMT_EXECUTED= 4, STMT_ERROR= -1 - }; - - enum_state state; - -public: - /* We build without RTTI, so dynamic_cast can't be used. */ - enum Type - { - STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE, TABLE_ARENA - }; - - Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) : - free_list(0), mem_root(mem_root_arg), state(state_arg) - { INIT_ARENA_DBUG_INFO; } - /* - This constructor is used only when Query_arena is created as - backup storage for another instance of Query_arena. - */ - Query_arena() { INIT_ARENA_DBUG_INFO; } - - virtual Type type() const; - virtual ~Query_arena() {}; - - inline bool is_stmt_prepare() const { return state == STMT_INITIALIZED; } - inline bool is_stmt_prepare_or_first_sp_execute() const - { return (int)state < (int)STMT_PREPARED; } - inline bool is_stmt_prepare_or_first_stmt_execute() const - { return (int)state <= (int)STMT_PREPARED; } - inline bool is_stmt_execute() const - { return state == STMT_PREPARED || state == STMT_EXECUTED; } - inline bool is_conventional() const - { return state == STMT_CONVENTIONAL_EXECUTION; } - - inline void* alloc(size_t size) { return alloc_root(mem_root,size); } - inline void* calloc(size_t size) - { - void *ptr; - if (likely((ptr=alloc_root(mem_root,size)))) - bzero(ptr, size); - return ptr; - } - inline char *strdup(const char *str) - { return strdup_root(mem_root,str); } - inline char *strmake(const char *str, size_t size) - { return strmake_root(mem_root,str,size); } - inline void *memdup(const void *str, size_t size) - { return memdup_root(mem_root,str,size); } - inline void *memdup_w_gap(const void *str, size_t size, size_t gap) - { - void *ptr; - if (likely((ptr= alloc_root(mem_root,size+gap)))) - memcpy(ptr,str,size); - return ptr; - } - - void set_query_arena(Query_arena *set); - - void free_items(); - /* Close the active state associated with execution of this statement */ - virtual void cleanup_stmt(); -}; - - -class Query_arena_memroot: public Query_arena, public Sql_alloc -{ -public: - Query_arena_memroot(MEM_ROOT *mem_root_arg, enum enum_state state_arg) : - Query_arena(mem_root_arg, state_arg) - {} - Query_arena_memroot() : Query_arena() - {} - - virtual ~Query_arena_memroot() {} -}; - - -class Query_arena_stmt -{ - THD *thd; - Query_arena backup; - Query_arena *arena; - -public: - Query_arena_stmt(THD *_thd); - ~Query_arena_stmt(); - bool arena_replaced() - { - return arena != NULL; - } -}; - - -class Server_side_cursor; - -/** - @class Statement - @brief State of a single command executed against this connection. - - One connection can contain a lot of simultaneously running statements, - some of which could be: - - prepared, that is, contain placeholders, - - opened as cursors. We maintain 1 to 1 relationship between - statement and cursor - if user wants to create another cursor for his - query, we create another statement for it. - To perform some action with statement we reset THD part to the state of - that statement, do the action, and then save back modified state from THD - to the statement. It will be changed in near future, and Statement will - be used explicitly. -*/ - -class Statement: public ilink, public Query_arena -{ - Statement(const Statement &rhs); /* not implemented: */ - Statement &operator=(const Statement &rhs); /* non-copyable */ -public: - /* - Uniquely identifies each statement object in thread scope; change during - statement lifetime. FIXME: must be const - */ - ulong id; - - enum enum_column_usage column_usage; - - LEX_CSTRING name; /* name for named prepared statements */ - LEX *lex; // parse tree descriptor - /* - Points to the query associated with this statement. It's const, but - we need to declare it char * because all table handlers are written - in C and need to point to it. - - Note that if we set query = NULL, we must at the same time set - query_length = 0, and protect the whole operation with - LOCK_thd_data mutex. To avoid crashes in races, if we do not - know that thd->query cannot change at the moment, we should print - thd->query like this: - (1) reserve the LOCK_thd_data mutex; - (2) print or copy the value of query and query_length - (3) release LOCK_thd_data mutex. - This printing is needed at least in SHOW PROCESSLIST and SHOW - ENGINE INNODB STATUS. - */ - CSET_STRING query_string; - /* - If opt_query_cache_strip_comments is set, this contains query without - comments. If not set, it contains pointer to query_string. - */ - String base_query; - - - inline char *query() const { return query_string.str(); } - inline uint32 query_length() const - { - return static_cast(query_string.length()); - } - inline char *query_end() const - { - return query_string.str() + query_string.length(); - } - CHARSET_INFO *query_charset() const { return query_string.charset(); } - void set_query_inner(const CSET_STRING &string_arg) - { - query_string= string_arg; - } - void set_query_inner(char *query_arg, uint32 query_length_arg, - CHARSET_INFO *cs_arg) - { - set_query_inner(CSET_STRING(query_arg, query_length_arg, cs_arg)); - } - void reset_query_inner() - { - set_query_inner(CSET_STRING()); - } - /** - Name of the current (default) database. - - If there is the current (default) database, "db.str" contains its name. If - there is no current (default) database, "db.str" is NULL and "db.length" is - 0. In other words, db must either be NULL, or contain a - valid database name. - */ - - LEX_CSTRING db; - - /* This is set to 1 of last call to send_result_to_client() was ok */ - my_bool query_cache_is_applicable; - - /* This constructor is called for backup statements */ - Statement() {} - - Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg, - enum enum_state state_arg, ulong id_arg); - virtual ~Statement(); - - /* Assign execution context (note: not all members) of given stmt to self */ - virtual void set_statement(Statement *stmt); - void set_n_backup_statement(Statement *stmt, Statement *backup); - void restore_backup_statement(Statement *stmt, Statement *backup); - /* return class type */ - virtual Type type() const; -}; - - -/** - Container for all statements created/used in a connection. - Statements in Statement_map have unique Statement::id (guaranteed by id - assignment in Statement::Statement) - Non-empty statement names are unique too: attempt to insert a new statement - with duplicate name causes older statement to be deleted - - Statements are auto-deleted when they are removed from the map and when the - map is deleted. -*/ - -class Statement_map -{ -public: - Statement_map(); - - int insert(THD *thd, Statement *statement); - - Statement *find_by_name(const LEX_CSTRING *name) - { - Statement *stmt; - stmt= (Statement*)my_hash_search(&names_hash, (uchar*)name->str, - name->length); - return stmt; - } - - Statement *find(ulong id) - { - if (last_found_statement == 0 || id != last_found_statement->id) - { - Statement *stmt; - stmt= (Statement *) my_hash_search(&st_hash, (uchar *) &id, sizeof(id)); - if (stmt && stmt->name.str) - return NULL; - last_found_statement= stmt; - } - return last_found_statement; - } - /* - Close all cursors of this connection that use tables of a storage - engine that has transaction-specific state and therefore can not - survive COMMIT or ROLLBACK. Currently all but MyISAM cursors are closed. - */ - void close_transient_cursors(); - void erase(Statement *statement); - /* Erase all statements (calls Statement destructor) */ - void reset(); - ~Statement_map(); -private: - HASH st_hash; - HASH names_hash; - I_List transient_cursor_list; - Statement *last_found_statement; -}; - -struct st_savepoint { - struct st_savepoint *prev; - char *name; - uint length; - Ha_trx_info *ha_list; - /** State of metadata locks before this savepoint was set. */ - MDL_savepoint mdl_savepoint; -}; - -/** - @class Security_context - @brief A set of THD members describing the current authenticated user. -*/ - -class Security_context { -public: - Security_context() - :master_access(NO_ACL), - db_access(NO_ACL) - {} /* Remove gcc warning */ - /* - host - host of the client - user - user of the client, set to NULL until the user has been read from - the connection - priv_user - The user privilege we are using. May be "" for anonymous user. - ip - client IP - */ - const char *host; - const char *user, *ip; - char priv_user[USERNAME_LENGTH]; - char proxy_user[USERNAME_LENGTH + MAX_HOSTNAME + 5]; - /* The host privilege we are using */ - char priv_host[MAX_HOSTNAME]; - /* The role privilege we are using */ - char priv_role[USERNAME_LENGTH]; - /* The external user (if available) */ - char *external_user; - /* points to host if host is available, otherwise points to ip */ - const char *host_or_ip; - privilege_t master_access; /* Global privileges from mysql.user */ - privilege_t db_access; /* Privileges for current db */ - - bool password_expired; - - void init(); - void destroy(); - void skip_grants(); - inline char *priv_host_name() - { - return (*priv_host ? priv_host : (char *)"%"); - } - - bool set_user(char *user_arg); - -#ifndef NO_EMBEDDED_ACCESS_CHECKS - bool - change_security_context(THD *thd, - LEX_CSTRING *definer_user, - LEX_CSTRING *definer_host, - LEX_CSTRING *db, - Security_context **backup); - - void - restore_security_context(THD *thd, Security_context *backup); -#endif - bool user_matches(Security_context *); - /** - Check global access - @param want_access The required privileges - @param match_any if the security context must match all or any of the req. - * privileges. - @return True if the security context fulfills the access requirements. - */ - bool check_access(const privilege_t want_access, bool match_any = false); - bool is_priv_user(const char *user, const char *host); -}; - - -/** - A registry for item tree transformations performed during - query optimization. We register only those changes which require - a rollback to re-execute a prepared statement or stored procedure - yet another time. -*/ - -struct Item_change_record; -class Item_change_list -{ - I_List change_list; -public: - void nocheck_register_item_tree_change(Item **place, Item *old_value, - MEM_ROOT *runtime_memroot); - void check_and_register_item_tree_change(Item **place, Item **new_value, - MEM_ROOT *runtime_memroot); - void rollback_item_tree_changes(); - void move_elements_to(Item_change_list *to) - { - change_list.move_elements_to(&to->change_list); - } - bool is_empty() { return change_list.is_empty(); } -}; - - -class Item_change_list_savepoint: public Item_change_list -{ -public: - Item_change_list_savepoint(Item_change_list *list) - { - list->move_elements_to(this); - } - void rollback(Item_change_list *list) - { - list->rollback_item_tree_changes(); - move_elements_to(list); - } - ~Item_change_list_savepoint() - { - DBUG_ASSERT(is_empty()); - } -}; - - -/** - Type of locked tables mode. - See comment for THD::locked_tables_mode for complete description. -*/ - -enum enum_locked_tables_mode -{ - LTM_NONE= 0, - LTM_LOCK_TABLES, - LTM_PRELOCKED, - LTM_PRELOCKED_UNDER_LOCK_TABLES, - LTM_always_last -}; - -/** - The following structure is an extension to TABLE_SHARE and is - exclusively for temporary tables. - - @note: - Although, TDC_element has data members (like next, prev & - all_tables) to store the list of TABLE_SHARE & TABLE objects - related to a particular TABLE_SHARE, they cannot be moved to - TABLE_SHARE in order to be reused for temporary tables. This - is because, as concurrent threads iterating through hash of - TDC_element's may need access to all_tables, but if all_tables - is made part of TABLE_SHARE, then TDC_element->share->all_tables - is not always guaranteed to be valid, as TDC_element can live - longer than TABLE_SHARE. -*/ -struct TMP_TABLE_SHARE : public TABLE_SHARE -{ -private: - /* - Link to all temporary table shares. Declared as private to - avoid direct manipulation with those objects. One should - use methods of I_P_List template instead. - */ - TMP_TABLE_SHARE *tmp_next; - TMP_TABLE_SHARE **tmp_prev; - - friend struct All_tmp_table_shares; - -public: - /* - Doubly-linked (back-linked) lists of used and unused TABLE objects - for this share. - */ - All_share_tables_list all_tmp_tables; -}; - -/** - Helper class which specifies which members of TMP_TABLE_SHARE are - used for participation in the list of temporary tables. -*/ - -struct All_tmp_table_shares -{ - static inline TMP_TABLE_SHARE **next_ptr(TMP_TABLE_SHARE *l) - { - return &l->tmp_next; - } - static inline TMP_TABLE_SHARE ***prev_ptr(TMP_TABLE_SHARE *l) - { - return &l->tmp_prev; - } -}; - -/* Also used in rpl_rli.h. */ -typedef I_P_List All_tmp_tables_list; - -/** - Class that holds information about tables which were opened and locked - by the thread. It is also used to save/restore this information in - push_open_tables_state()/pop_open_tables_state(). -*/ - -class Open_tables_state -{ -public: - /** - As part of class THD, this member is set during execution - of a prepared statement. When it is set, it is used - by the locking subsystem to report a change in table metadata. - - When Open_tables_state part of THD is reset to open - a system or INFORMATION_SCHEMA table, the member is cleared - to avoid spurious ER_NEED_REPREPARE errors -- system and - INFORMATION_SCHEMA tables are not subject to metadata version - tracking. - @sa check_and_update_table_version() - */ - Reprepare_observer *m_reprepare_observer; - - /** - List of regular tables in use by this thread. Contains temporary and - base tables that were opened with @see open_tables(). - */ - TABLE *open_tables; - - /** - A list of temporary tables used by this thread. This includes - user-level temporary tables, created with CREATE TEMPORARY TABLE, - and internal temporary tables, created, e.g., to resolve a SELECT, - or for an intermediate table used in ALTER. - */ - All_tmp_tables_list *temporary_tables; - - /* - Derived tables. - */ - TABLE *derived_tables; - - /* - Temporary tables created for recursive table references. - */ - TABLE *rec_tables; - - /* - During a MySQL session, one can lock tables in two modes: automatic - or manual. In automatic mode all necessary tables are locked just before - statement execution, and all acquired locks are stored in 'lock' - member. Unlocking takes place automatically as well, when the - statement ends. - Manual mode comes into play when a user issues a 'LOCK TABLES' - statement. In this mode the user can only use the locked tables. - Trying to use any other tables will give an error. - The locked tables are also stored in this member, however, - thd->locked_tables_mode is turned on. Manual locking is described in - the 'LOCK_TABLES' chapter of the MySQL manual. - See also lock_tables() for details. - */ - MYSQL_LOCK *lock; - - /* - CREATE-SELECT keeps an extra lock for the table being - created. This field is used to keep the extra lock available for - lower level routines, which would otherwise miss that lock. - */ - MYSQL_LOCK *extra_lock; - - /* - Enum enum_locked_tables_mode and locked_tables_mode member are - used to indicate whether the so-called "locked tables mode" is on, - and what kind of mode is active. - - Locked tables mode is used when it's necessary to open and - lock many tables at once, for usage across multiple - (sub-)statements. - This may be necessary either for queries that use stored functions - and triggers, in which case the statements inside functions and - triggers may be executed many times, or for implementation of - LOCK TABLES, in which case the opened tables are reused by all - subsequent statements until a call to UNLOCK TABLES. - - The kind of locked tables mode employed for stored functions and - triggers is also called "prelocked mode". - In this mode, first open_tables() call to open the tables used - in a statement analyses all functions used by the statement - and adds all indirectly used tables to the list of tables to - open and lock. - It also marks the parse tree of the statement as requiring - prelocking. After that, lock_tables() locks the entire list - of tables and changes THD::locked_tables_modeto LTM_PRELOCKED. - All statements executed inside functions or triggers - use the prelocked tables, instead of opening their own ones. - Prelocked mode is turned off automatically once close_thread_tables() - of the main statement is called. - */ - enum enum_locked_tables_mode locked_tables_mode; - uint current_tablenr; - - enum enum_flags { - BACKUPS_AVAIL = (1U << 0) /* There are backups available */ - }; - - /* - Flags with information about the open tables state. - */ - uint state_flags; - /** - This constructor initializes Open_tables_state instance which can only - be used as backup storage. To prepare Open_tables_state instance for - operations which open/lock/close tables (e.g. open_table()) one has to - call init_open_tables_state(). - */ - Open_tables_state() : state_flags(0U) { } - - void set_open_tables_state(Open_tables_state *state) - { - *this= *state; - } - - void reset_open_tables_state(THD *thd) - { - open_tables= 0; - temporary_tables= 0; - derived_tables= 0; - rec_tables= 0; - extra_lock= 0; - lock= 0; - locked_tables_mode= LTM_NONE; - state_flags= 0U; - m_reprepare_observer= NULL; - } -}; - - -/** - Storage for backup of Open_tables_state. Must - be used only to open system tables (TABLE_CATEGORY_SYSTEM - and TABLE_CATEGORY_LOG). -*/ - -class Open_tables_backup: public Open_tables_state -{ -public: - /** - When we backup the open tables state to open a system - table or tables, we want to save state of metadata - locks which were acquired before the backup. It is used - to release metadata locks on system tables after they are - no longer used. - */ - MDL_savepoint mdl_system_tables_svp; -}; - -/** - @class Sub_statement_state - @brief Used to save context when executing a function or trigger - - operations on stat tables aren't technically a sub-statement, but they are - similar in a sense that they cannot change the transaction status. -*/ - -/* Defines used for Sub_statement_state::in_sub_stmt */ - -#define SUB_STMT_TRIGGER 1 -#define SUB_STMT_FUNCTION 2 -#define SUB_STMT_STAT_TABLES 4 - - -class Sub_statement_state -{ -public: - Discrete_interval auto_inc_interval_for_cur_row; - Discrete_intervals_list auto_inc_intervals_forced; - SAVEPOINT *savepoints; - ulonglong option_bits; - ulonglong first_successful_insert_id_in_prev_stmt; - ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row; - ulonglong limit_found_rows; - ulonglong tmp_tables_size; - ulonglong client_capabilities; - ulonglong cuted_fields, sent_row_count, examined_row_count; - ulonglong affected_rows; - ulonglong bytes_sent_old; - ulong tmp_tables_used; - ulong tmp_tables_disk_used; - ulong query_plan_fsort_passes; - ulong query_plan_flags; - uint in_sub_stmt; /* 0, SUB_STMT_TRIGGER or SUB_STMT_FUNCTION */ - bool enable_slow_log; - bool last_insert_id_used; - enum enum_check_fields count_cuted_fields; -}; - - -/* Flags for the THD::system_thread variable */ -enum enum_thread_type -{ - NON_SYSTEM_THREAD= 0, - SYSTEM_THREAD_DELAYED_INSERT= 1, - SYSTEM_THREAD_SLAVE_IO= 2, - SYSTEM_THREAD_SLAVE_SQL= 4, - SYSTEM_THREAD_EVENT_SCHEDULER= 8, - SYSTEM_THREAD_EVENT_WORKER= 16, - SYSTEM_THREAD_BINLOG_BACKGROUND= 32, - SYSTEM_THREAD_SLAVE_BACKGROUND= 64, - SYSTEM_THREAD_GENERIC= 128, - SYSTEM_THREAD_SEMISYNC_MASTER_BACKGROUND= 256 -}; - -inline char const * -show_system_thread(enum_thread_type thread) -{ -#define RETURN_NAME_AS_STRING(NAME) case (NAME): return #NAME - switch (thread) { - static char buf[64]; - RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD); - RETURN_NAME_AS_STRING(SYSTEM_THREAD_DELAYED_INSERT); - RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO); - RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL); - RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER); - RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER); - RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_BACKGROUND); - RETURN_NAME_AS_STRING(SYSTEM_THREAD_SEMISYNC_MASTER_BACKGROUND); - default: - sprintf(buf, "", thread); - return buf; - } -#undef RETURN_NAME_AS_STRING -} - -/** - This class represents the interface for internal error handlers. - Internal error handlers are exception handlers used by the server - implementation. -*/ - -class Internal_error_handler -{ -protected: - Internal_error_handler() : - m_prev_internal_handler(NULL) - {} - - virtual ~Internal_error_handler() {} - -public: - /** - Handle a sql condition. - This method can be implemented by a subclass to achieve any of the - following: - - mask a warning/error internally, prevent exposing it to the user, - - mask a warning/error and throw another one instead. - When this method returns true, the sql condition is considered - 'handled', and will not be propagated to upper layers. - It is the responsability of the code installing an internal handler - to then check for trapped conditions, and implement logic to recover - from the anticipated conditions trapped during runtime. - - This mechanism is similar to C++ try/throw/catch: - - 'try' correspond to THD::push_internal_handler(), - - 'throw' correspond to my_error(), - which invokes my_message_sql(), - - 'catch' correspond to checking how/if an internal handler was invoked, - before removing it from the exception stack with - THD::pop_internal_handler(). - - @param thd the calling thread - @param cond the condition raised. - @return true if the condition is handled - */ - virtual bool handle_condition(THD *thd, - uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level *level, - const char* msg, - Sql_condition ** cond_hdl) = 0; - -private: - Internal_error_handler *m_prev_internal_handler; - friend class THD; -}; - - -/** - Implements the trivial error handler which cancels all error states - and prevents an SQLSTATE to be set. -*/ - -class Dummy_error_handler : public Internal_error_handler -{ -public: - bool handle_condition(THD *thd, - uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level *level, - const char* msg, - Sql_condition ** cond_hdl) - { - /* Ignore error */ - return TRUE; - } - Dummy_error_handler() {} /* Remove gcc warning */ -}; - - -/** - Implements the trivial error handler which counts errors as they happen. -*/ - -class Counting_error_handler : public Internal_error_handler -{ -public: - int errors; - bool handle_condition(THD *thd, - uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level *level, - const char* msg, - Sql_condition ** cond_hdl) - { - if (*level == Sql_condition::WARN_LEVEL_ERROR) - errors++; - return false; - } - Counting_error_handler() : errors(0) {} -}; - - -/** - This class is an internal error handler implementation for - DROP TABLE statements. The thing is that there may be warnings during - execution of these statements, which should not be exposed to the user. - This class is intended to silence such warnings. -*/ - -class Drop_table_error_handler : public Internal_error_handler -{ -public: - Drop_table_error_handler() {} - -public: - bool handle_condition(THD *thd, - uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level *level, - const char* msg, - Sql_condition ** cond_hdl); - -private: -}; - - -/** - Internal error handler to process an error from MDL_context::upgrade_lock() - and mysql_lock_tables(). Used by implementations of HANDLER READ and - LOCK TABLES LOCAL. -*/ - -class MDL_deadlock_and_lock_abort_error_handler: public Internal_error_handler -{ -public: - virtual - bool handle_condition(THD *thd, - uint sql_errno, - const char *sqlstate, - Sql_condition::enum_warning_level *level, - const char* msg, - Sql_condition **cond_hdl); - - bool need_reopen() const { return m_need_reopen; }; - void init() { m_need_reopen= FALSE; }; -private: - bool m_need_reopen; -}; - - -/** - Tables that were locked with LOCK TABLES statement. - - Encapsulates a list of TABLE_LIST instances for tables - locked by LOCK TABLES statement, memory root for metadata locks, - and, generally, the context of LOCK TABLES statement. - - In LOCK TABLES mode, the locked tables are kept open between - statements. - Therefore, we can't allocate metadata locks on execution memory - root -- as well as tables, the locks need to stay around till - UNLOCK TABLES is called. - The locks are allocated in the memory root encapsulated in this - class. - - Some SQL commands, like FLUSH TABLE or ALTER TABLE, demand that - the tables they operate on are closed, at least temporarily. - This class encapsulates a list of TABLE_LIST instances, one - for each base table from LOCK TABLES list, - which helps conveniently close the TABLEs when it's necessary - and later reopen them. - - Implemented in sql_base.cc -*/ - -class Locked_tables_list -{ -public: - MEM_ROOT m_locked_tables_root; -private: - TABLE_LIST *m_locked_tables; - TABLE_LIST **m_locked_tables_last; - /** An auxiliary array used only in reopen_tables(). */ - TABLE_LIST **m_reopen_array; - /** - Count the number of tables in m_locked_tables list. We can't - rely on thd->lock->table_count because it excludes - non-transactional temporary tables. We need to know - an exact number of TABLE objects. - */ - uint m_locked_tables_count; -public: - bool some_table_marked_for_reopen; - - Locked_tables_list() - :m_locked_tables(NULL), - m_locked_tables_last(&m_locked_tables), - m_reopen_array(NULL), - m_locked_tables_count(0), - some_table_marked_for_reopen(0) - { - init_sql_alloc(key_memory_locked_table_list, &m_locked_tables_root, - MEM_ROOT_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); - } - int unlock_locked_tables(THD *thd); - int unlock_locked_table(THD *thd, MDL_ticket *mdl_ticket); - ~Locked_tables_list() - { - reset(); - } - void reset(); - bool init_locked_tables(THD *thd); - TABLE_LIST *locked_tables() { return m_locked_tables; } - void unlink_from_list(THD *thd, TABLE_LIST *table_list, - bool remove_from_locked_tables); - void unlink_all_closed_tables(THD *thd, - MYSQL_LOCK *lock, - size_t reopen_count); - bool reopen_tables(THD *thd, bool need_reopen); - bool restore_lock(THD *thd, TABLE_LIST *dst_table_list, TABLE *table, - MYSQL_LOCK *lock); - void add_back_last_deleted_lock(TABLE_LIST *dst_table_list); - void mark_table_for_reopen(THD *thd, TABLE *table); -}; - - -/** - Storage engine specific thread local data. -*/ - -struct Ha_data -{ - /** - Storage engine specific thread local data. - Lifetime: one user connection. - */ - void *ha_ptr; - /** - 0: Life time: one statement within a transaction. If @@autocommit is - on, also represents the entire transaction. - @sa trans_register_ha() - - 1: Life time: one transaction within a connection. - If the storage engine does not participate in a transaction, - this should not be used. - @sa trans_register_ha() - */ - Ha_trx_info ha_info[2]; - /** - NULL: engine is not bound to this thread - non-NULL: engine is bound to this thread, engine shutdown forbidden - */ - plugin_ref lock; - Ha_data() :ha_ptr(NULL) {} - - void reset() - { - ha_ptr= nullptr; - for (auto &info : ha_info) - info.reset(); - lock= nullptr; - } -}; - -/** - An instance of the global read lock in a connection. - Implemented in lock.cc. -*/ - -class Global_read_lock -{ -public: - enum enum_grl_state - { - GRL_NONE, - GRL_ACQUIRED, - GRL_ACQUIRED_AND_BLOCKS_COMMIT - }; - - Global_read_lock() - : m_state(GRL_NONE), - m_mdl_global_read_lock(NULL) - {} - - bool lock_global_read_lock(THD *thd); - void unlock_global_read_lock(THD *thd); - bool make_global_read_lock_block_commit(THD *thd); - bool is_acquired() const { return m_state != GRL_NONE; } - void set_explicit_lock_duration(THD *thd); -private: - enum_grl_state m_state; - /** - Global read lock is acquired in two steps: - 1. acquire MDL_BACKUP_FTWRL1 in BACKUP namespace to prohibit DDL and DML - 2. upgrade to MDL_BACKUP_FTWRL2 to prohibit commits - */ - MDL_ticket *m_mdl_global_read_lock; -}; - - -/* - Class to facilitate the commit of one transactions waiting for the commit of - another transaction to complete first. - - This is used during (parallel) replication, to allow different transactions - to be applied in parallel, but still commit in order. - - The transaction that wants to wait for a prior commit must first register - to wait with register_wait_for_prior_commit(waitee). Such registration - must be done holding the waitee->LOCK_wait_commit, to prevent the other - THD from disappearing during the registration. - - Then during commit, if a THD is registered to wait, it will call - wait_for_prior_commit() as part of ha_commit_trans(). If no wait is - registered, or if the waitee for has already completed commit, then - wait_for_prior_commit() returns immediately. - - And when a THD that may be waited for has completed commit (more precisely - commit_ordered()), then it must call wakeup_subsequent_commits() to wake - up any waiters. Note that this must be done at a point that is guaranteed - to be later than any waiters registering themselves. It is safe to call - wakeup_subsequent_commits() multiple times, as waiters are removed from - registration as part of the wakeup. - - The reason for separate register and wait calls is that this allows to - register the wait early, at a point where the waited-for THD is known to - exist. And then the actual wait can be done much later, where the - waited-for THD may have been long gone. By registering early, the waitee - can signal before disappearing. -*/ -struct wait_for_commit -{ - /* - The LOCK_wait_commit protects the fields subsequent_commits_list and - wakeup_subsequent_commits_running (for a waitee), and the pointer - waitee and associated COND_wait_commit (for a waiter). - */ - mysql_mutex_t LOCK_wait_commit; - mysql_cond_t COND_wait_commit; - /* List of threads that did register_wait_for_prior_commit() on us. */ - wait_for_commit *subsequent_commits_list; - /* Link field for entries in subsequent_commits_list. */ - wait_for_commit *next_subsequent_commit; - /* - Our waitee, if we did register_wait_for_prior_commit(), and were not - yet woken up. Else NULL. - - When this is cleared for wakeup, the COND_wait_commit condition is - signalled. - - This pointer is protected by LOCK_wait_commit. But there is also a "fast - path" where the waiter compares this to NULL without holding the lock. - Such read must be done with acquire semantics (and all corresponding - writes done with release semantics). This ensures that a wakeup with error - is reliably detected as (waitee==NULL && wakeup_error != 0). - */ - std::atomic waitee; - /* - Generic pointer for use by the transaction coordinator to optimise the - waiting for improved group commit. - - Currently used by binlog TC to signal that a waiter is ready to commit, so - that the waitee can grab it and group commit it directly. It is free to be - used by another transaction coordinator for similar purposes. - */ - void *opaque_pointer; - /* The wakeup error code from the waitee. 0 means no error. */ - int wakeup_error; - /* - Flag set when wakeup_subsequent_commits_running() is active, see comments - on that function for details. - */ - bool wakeup_subsequent_commits_running; - /* - This flag can be set when a commit starts, but has not completed yet. - It is used by binlog group commit to allow a waiting transaction T2 to - join the group commit of an earlier transaction T1. When T1 has queued - itself for group commit, it will set the commit_started flag. Then when - T2 becomes ready to commit and needs to wait for T1 to commit first, T2 - can queue itself before waiting, and thereby participate in the same - group commit as T1. - */ - bool commit_started; - - void register_wait_for_prior_commit(wait_for_commit *waitee); - int wait_for_prior_commit(THD *thd) - { - /* - Quick inline check, to avoid function call and locking in the common case - where no wakeup is registered, or a registered wait was already signalled. - */ - if (waitee.load(std::memory_order_acquire)) - return wait_for_prior_commit2(thd); - else - { - if (wakeup_error) - my_error(ER_PRIOR_COMMIT_FAILED, MYF(0)); - return wakeup_error; - } - } - void wakeup_subsequent_commits(int wakeup_error_arg) - { - /* - Do the check inline, so only the wakeup case takes the cost of a function - call for every commmit. - - Note that the check is done without locking. It is the responsibility of - the user of the wakeup facility to ensure that no waiters can register - themselves after the last call to wakeup_subsequent_commits(). - - This avoids having to take another lock for every commit, which would be - pointless anyway - even if we check under lock, there is nothing to - prevent a waiter from arriving just after releasing the lock. - */ - if (subsequent_commits_list) - wakeup_subsequent_commits2(wakeup_error_arg); - } - void unregister_wait_for_prior_commit() - { - if (waitee.load(std::memory_order_relaxed)) - unregister_wait_for_prior_commit2(); - else - wakeup_error= 0; - } - /* - Remove a waiter from the list in the waitee. Used to unregister a wait. - The caller must be holding the locks of both waiter and waitee. - */ - void remove_from_list(wait_for_commit **next_ptr_ptr) - { - wait_for_commit *cur; - - while ((cur= *next_ptr_ptr) != NULL) - { - if (cur == this) - { - *next_ptr_ptr= this->next_subsequent_commit; - break; - } - next_ptr_ptr= &cur->next_subsequent_commit; - } - waitee.store(NULL, std::memory_order_relaxed); - } - - void wakeup(int wakeup_error); - - int wait_for_prior_commit2(THD *thd); - void wakeup_subsequent_commits2(int wakeup_error); - void unregister_wait_for_prior_commit2(); - - wait_for_commit(); - ~wait_for_commit(); - void reinit(); -}; - -extern "C" void my_message_sql(uint error, const char *str, myf MyFlags); - - -class Gap_time_tracker; - -/* - Thread context for Gap_time_tracker class. -*/ -class Gap_time_tracker_data -{ -public: - Gap_time_tracker_data(): bill_to(NULL) {} - - Gap_time_tracker *bill_to; - ulonglong start_time; - - void init() { bill_to = NULL; } -}; - -/** - A wrapper around thread_count. - - It must be specified as a first base class of THD, so that increment is - done before any other THD constructors and decrement - after any other THD - destructors. - - Destructor unblocks close_conneciton() if there are no more THD's left. -*/ -struct THD_count -{ - THD_count() { thread_count++; } - ~THD_count() { thread_count--; } -}; - - -/** - @class THD - For each client connection we create a separate thread with THD serving as - a thread/connection descriptor -*/ - -class THD: public THD_count, /* this must be first */ - public Statement, - /* - This is to track items changed during execution of a prepared - statement/stored procedure. It's created by - nocheck_register_item_tree_change() in memory root of THD, - and freed in rollback_item_tree_changes(). - For conventional execution it's always empty. - */ - public Item_change_list, - public MDL_context_owner, - public Open_tables_state -{ -private: - inline bool is_stmt_prepare() const - { DBUG_ASSERT(0); return Statement::is_stmt_prepare(); } - - inline bool is_stmt_prepare_or_first_sp_execute() const - { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_sp_execute(); } - - inline bool is_stmt_prepare_or_first_stmt_execute() const - { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_stmt_execute(); } - - inline bool is_conventional() const - { DBUG_ASSERT(0); return Statement::is_conventional(); } - -public: - MDL_context mdl_context; - - /* Used to execute base64 coded binlog events in MySQL server */ - Relay_log_info* rli_fake; - rpl_group_info* rgi_fake; - /* Slave applier execution context */ - rpl_group_info* rgi_slave; - - union { - rpl_io_thread_info *rpl_io_info; - rpl_sql_thread_info *rpl_sql_info; - } system_thread_info; - /* Used for BACKUP LOCK */ - MDL_ticket *mdl_backup_ticket, *mdl_backup_lock; - /* Used to register that thread has a MDL_BACKUP_WAIT_COMMIT lock */ - MDL_request *backup_commit_lock; - - void reset_for_next_command(bool do_clear_errors= 1); - /* - Constant for THD::where initialization in the beginning of every query. - - It's needed because we do not save/restore THD::where normally during - primary (non subselect) query execution. - */ - static const char * const DEFAULT_WHERE; - -#ifdef EMBEDDED_LIBRARY - struct st_mysql *mysql; - unsigned long client_stmt_id; - unsigned long client_param_count; - struct st_mysql_bind *client_params; - char *extra_data; - ulong extra_length; - struct st_mysql_data *cur_data; - struct st_mysql_data *first_data; - struct st_mysql_data **data_tail; - void clear_data_list(); - struct st_mysql_data *alloc_new_dataset(); - /* - In embedded server it points to the statement that is processed - in the current query. We store some results directly in statement - fields then. - */ - struct st_mysql_stmt *current_stmt; -#endif -#ifdef HAVE_QUERY_CACHE - Query_cache_tls query_cache_tls; -#endif - NET net; // client connection descriptor - /** Aditional network instrumentation for the server only. */ - NET_SERVER m_net_server_extension; - scheduler_functions *scheduler; // Scheduler for this connection - Protocol *protocol; // Current protocol - Protocol_text protocol_text; // Normal protocol - Protocol_binary protocol_binary; // Binary protocol - HASH user_vars; // hash for user variables - String packet; // dynamic buffer for network I/O - String convert_buffer; // buffer for charset conversions - struct my_rnd_struct rand; // used for authentication - struct system_variables variables; // Changeable local variables - struct system_status_var status_var; // Per thread statistic vars - struct system_status_var org_status_var; // For user statistics - struct system_status_var *initial_status_var; /* used by show status */ - THR_LOCK_INFO lock_info; // Locking info of this thread - /** - Protects THD data accessed from other threads: - - thd->query and thd->query_length (used by SHOW ENGINE - INNODB STATUS and SHOW PROCESSLIST - - thd->db (used in SHOW PROCESSLIST) - Is locked when THD is deleted. - */ - mutable mysql_mutex_t LOCK_thd_data; - /* - Protects: - - kill information - - mysys_var (used by KILL statement and shutdown). - - Also ensures that THD is not deleted while mutex is hold - */ - mysql_mutex_t LOCK_thd_kill; - - /* all prepared statements and cursors of this connection */ - Statement_map stmt_map; - - /* Last created prepared statement */ - Statement *last_stmt; - inline void set_last_stmt(Statement *stmt) - { last_stmt= (is_error() ? NULL : stmt); } - inline void clear_last_stmt() { last_stmt= NULL; } - - /* - A pointer to the stack frame of handle_one_connection(), - which is called first in the thread for handling a client - */ - char *thread_stack; - - /** - Currently selected catalog. - */ - char *catalog; - - /** - @note - Some members of THD (currently 'Statement::db', - 'catalog' and 'query') are set and alloced by the slave SQL thread - (for the THD of that thread); that thread is (and must remain, for now) - the only responsible for freeing these 3 members. If you add members - here, and you add code to set them in replication, don't forget to - free_them_and_set_them_to_0 in replication properly. For details see - the 'err:' label of the handle_slave_sql() in sql/slave.cc. - - @see handle_slave_sql - */ - - Security_context main_security_ctx; - Security_context *security_ctx; - Security_context *security_context() const { return security_ctx; } - void set_security_context(Security_context *sctx) { security_ctx = sctx; } - - /* - Points to info-string that we show in SHOW PROCESSLIST - You are supposed to update thd->proc_info only if you have coded - a time-consuming piece that MySQL can get stuck in for a long time. - - Set it using the thd_proc_info(THD *thread, const char *message) - macro/function. - - This member is accessed and assigned without any synchronization. - Therefore, it may point only to constant (statically - allocated) strings, which memory won't go away over time. - */ - const char *proc_info; - - void set_psi(PSI_thread *psi) - { - my_atomic_storeptr((void*volatile*)&m_psi, psi); - } - - PSI_thread* get_psi() - { - return static_cast(my_atomic_loadptr((void*volatile*)&m_psi)); - } - -private: - unsigned int m_current_stage_key; - - /** Performance schema thread instrumentation for this session. */ - PSI_thread *m_psi; - -public: - void enter_stage(const PSI_stage_info *stage, - const char *calling_func, - const char *calling_file, - const unsigned int calling_line) - { - DBUG_PRINT("THD::enter_stage", ("%s at %s:%d", stage->m_name, - calling_file, calling_line)); - DBUG_ASSERT(stage); - m_current_stage_key= stage->m_key; - proc_info= stage->m_name; -#if defined(ENABLED_PROFILING) - profiling.status_change(proc_info, calling_func, calling_file, - calling_line); -#endif -#ifdef HAVE_PSI_THREAD_INTERFACE - m_stage_progress_psi= MYSQL_SET_STAGE(m_current_stage_key, calling_file, calling_line); -#endif - } - - void backup_stage(PSI_stage_info *stage) - { - stage->m_key= m_current_stage_key; - stage->m_name= proc_info; - } - - const char *get_proc_info() const - { return proc_info; } - - /* - Used in error messages to tell user in what part of MySQL we found an - error. E. g. when where= "having clause", if fix_fields() fails, user - will know that the error was in having clause. - */ - const char *where; - - /* Needed by MariaDB semi sync replication */ - Trans_binlog_info *semisync_info; - /* If this is a semisync slave connection. */ - bool semi_sync_slave; - ulonglong client_capabilities; /* What the client supports */ - ulong max_client_packet_length; - - HASH handler_tables_hash; - /* - A thread can hold named user-level locks. This variable - contains granted tickets if a lock is present. See item_func.cc and - chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK. - */ - HASH ull_hash; - /* Hash of used seqeunces (for PREVIOUS value) */ - HASH sequences; -#ifdef DBUG_ASSERT_EXISTS - uint dbug_sentry; // watch out for memory corruption -#endif - struct st_my_thread_var *mysys_var; - - /* Original charset number from the first client packet, or COM_CHANGE_USER*/ - CHARSET_INFO *org_charset; -private: - /* - Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from - first byte of the packet in do_command() - */ - enum enum_server_command m_command; - -public: - uint32 file_id; // for LOAD DATA INFILE - /* remote (peer) port */ - uint16 peer_port; - my_time_t start_time; // start_time and its sec_part - ulong start_time_sec_part; // are almost always used separately - my_hrtime_t user_time; - // track down slow pthread_create - ulonglong prior_thr_create_utime, thr_create_utime; - ulonglong start_utime, utime_after_lock, utime_after_query; - /* This can be used by handlers to send signals to the SQL level */ - ulonglong replication_flags; - // Process indicator - struct { - /* - true, if the currently running command can send progress report - packets to a client. Set by mysql_execute_command() for safe commands - See CF_REPORT_PROGRESS - */ - bool report_to_client; - /* - true, if we will send progress report packets to a client - (client has requested them, see MARIADB_CLIENT_PROGRESS; report_to_client - is true; not in sub-statement) - */ - bool report; - uint stage, max_stage; - ulonglong counter, max_counter; - ulonglong next_report_time; - Query_arena *arena; - } progress; - - thr_lock_type update_lock_default; - Delayed_insert *di; - - /* <> 0 if we are inside of trigger or stored function. */ - uint in_sub_stmt; - /* True when opt_userstat_running is set at start of query */ - bool userstat_running; - /* - True if we have to log all errors. Are set by some engines to temporary - force errors to the error log. - */ - bool log_all_errors; - - /* Do not set socket timeouts for wait_timeout (used with threadpool) */ - bool skip_wait_timeout; - - bool prepare_derived_at_open; - - /* Set to 1 if status of this THD is already in global status */ - bool status_in_global; - - /* - To signal that the tmp table to be created is created for materialized - derived table or a view. - */ - bool create_tmp_table_for_derived; - - bool save_prep_leaf_list; - - /* container for handler's private per-connection data */ - Ha_data ha_data[MAX_HA]; - - /** - Bit field for the state of binlog warnings. - - The first Lex::BINLOG_STMT_UNSAFE_COUNT bits list all types of - unsafeness that the current statement has. - - This must be a member of THD and not of LEX, because warnings are - detected and issued in different places (@c - decide_logging_format() and @c binlog_query(), respectively). - Between these calls, the THD->lex object may change; e.g., if a - stored routine is invoked. Only THD persists between the calls. - */ - uint32 binlog_unsafe_warning_flags; - -#ifndef MYSQL_CLIENT - binlog_cache_mngr * binlog_setup_trx_data(); - - /* - Public interface to write RBR events to the binlog - */ - void binlog_start_trans_and_stmt(); - void binlog_set_stmt_begin(); - int binlog_write_row(TABLE* table, bool is_transactional, - const uchar *buf); - int binlog_delete_row(TABLE* table, bool is_transactional, - const uchar *buf); - int binlog_update_row(TABLE* table, bool is_transactional, - const uchar *old_data, const uchar *new_data); - bool prepare_handlers_for_update(uint flag); - bool binlog_write_annotated_row(Log_event_writer *writer); - void binlog_prepare_for_row_logging(); - bool binlog_write_table_maps(); - bool binlog_write_table_map(TABLE *table, bool with_annotate); - static void binlog_prepare_row_images(TABLE* table); - - void set_server_id(uint32 sid) { variables.server_id = sid; } - - /* - Member functions to handle pending event for row-level logging. - */ - template Rows_log_event* - binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id, - size_t needed, - bool is_transactional, - RowsEventT* hint); - Rows_log_event* binlog_get_pending_rows_event(bool is_transactional) const; - void binlog_set_pending_rows_event(Rows_log_event* ev, bool is_transactional); - inline int binlog_flush_pending_rows_event(bool stmt_end) - { - return (binlog_flush_pending_rows_event(stmt_end, FALSE) || - binlog_flush_pending_rows_event(stmt_end, TRUE)); - } - int binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional); - int binlog_remove_pending_rows_event(bool clear_maps, bool is_transactional); - - /** - Determine the binlog format of the current statement. - - @retval 0 if the current statement will be logged in statement - format. - @retval nonzero if the current statement will be logged in row - format. - */ - int is_current_stmt_binlog_format_row() const { - DBUG_ASSERT(current_stmt_binlog_format == BINLOG_FORMAT_STMT || - current_stmt_binlog_format == BINLOG_FORMAT_ROW); - return current_stmt_binlog_format == BINLOG_FORMAT_ROW; - } - /** - Determine if binlogging is disabled for this session - @retval 0 if the current statement binlogging is disabled - (could be because of binlog closed/binlog option - is set to false). - @retval 1 if the current statement will be binlogged - */ - inline bool is_current_stmt_binlog_disabled() const - { - return (!(variables.option_bits & OPTION_BIN_LOG) || - !mysql_bin_log.is_open()); - } - - enum binlog_filter_state - { - BINLOG_FILTER_UNKNOWN, - BINLOG_FILTER_CLEAR, - BINLOG_FILTER_SET - }; - - inline void reset_binlog_local_stmt_filter() - { - m_binlog_filter_state= BINLOG_FILTER_UNKNOWN; - } - - inline void clear_binlog_local_stmt_filter() - { - DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN); - m_binlog_filter_state= BINLOG_FILTER_CLEAR; - } - - inline void set_binlog_local_stmt_filter() - { - DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN); - m_binlog_filter_state= BINLOG_FILTER_SET; - } - - inline binlog_filter_state get_binlog_local_stmt_filter() - { - return m_binlog_filter_state; - } - -private: - /** - Indicate if the current statement should be discarded - instead of written to the binlog. - This is used to discard special statements, such as - DML or DDL that affects only 'local' (non replicated) - tables, such as performance_schema.* - */ - binlog_filter_state m_binlog_filter_state; - - /** - Indicates the format in which the current statement will be - logged. This can only be set from @c decide_logging_format(). - */ - enum_binlog_format current_stmt_binlog_format; - -public: - - /* 1 if binlog table maps has been written */ - bool binlog_table_maps; - - void issue_unsafe_warnings(); - void reset_unsafe_warnings() - { binlog_unsafe_warning_flags= 0; } - - void reset_binlog_for_next_statement() - { - binlog_table_maps= 0; - } - bool binlog_table_should_be_logged(const LEX_CSTRING *db); - -#endif /* MYSQL_CLIENT */ - -public: - - struct st_transactions { - SAVEPOINT *savepoints; - THD_TRANS all; // Trans since BEGIN WORK - THD_TRANS stmt; // Trans for current statement - bool on; // see ha_enable_transaction() - XID_STATE xid_state; - XID implicit_xid; - WT_THD wt; ///< for deadlock detection - Rows_log_event *m_pending_rows_event; - - struct st_trans_time : public timeval - { - void reset(THD *thd) - { - tv_sec= thd->query_start(); - tv_usec= (long) thd->query_start_sec_part(); - } - } start_time; - - /* - Tables changed in transaction (that must be invalidated in query cache). - List contain only transactional tables, that not invalidated in query - cache (instead of full list of changed in transaction tables). - */ - CHANGED_TABLE_LIST* changed_tables; - MEM_ROOT mem_root; // Transaction-life memory allocation pool - void cleanup() - { - DBUG_ENTER("THD::st_transactions::cleanup"); - changed_tables= 0; - savepoints= 0; - implicit_xid.null(); - free_root(&mem_root,MYF(MY_KEEP_PREALLOC)); - DBUG_VOID_RETURN; - } - void free() - { - free_root(&mem_root,MYF(0)); - } - bool is_active() - { - return (all.ha_list != NULL); - } - bool is_empty() - { - return all.is_empty() && stmt.is_empty(); - } - st_transactions() - { - bzero((char*)this, sizeof(*this)); - implicit_xid.null(); - init_sql_alloc(key_memory_thd_transactions, &mem_root, - ALLOC_ROOT_MIN_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); - } - } default_transaction, *transaction; - Global_read_lock global_read_lock; - Field *dup_field; -#ifndef __WIN__ - sigset_t signals; -#endif -#ifdef SIGNAL_WITH_VIO_CLOSE - Vio* active_vio; -#endif - - /* - A permanent memory area of the statement. For conventional - execution, the parsed tree and execution runtime reside in the same - memory root. In this case stmt_arena points to THD. In case of - a prepared statement or a stored procedure statement, thd->mem_root - conventionally points to runtime memory, and thd->stmt_arena - points to the memory of the PS/SP, where the parsed tree of the - statement resides. Whenever you need to perform a permanent - transformation of a parsed tree, you should allocate new memory in - stmt_arena, to allow correct re-execution of PS/SP. - Note: in the parser, stmt_arena == thd, even for PS/SP. - */ - Query_arena *stmt_arena; - - void *bulk_param; - - /* - map for tables that will be updated for a multi-table update query - statement, for other query statements, this will be zero. - */ - table_map table_map_for_update; - - /* Tells if LAST_INSERT_ID(#) was called for the current statement */ - bool arg_of_last_insert_id_function; - /* - ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for - insertion into an auto_increment column". - */ - /* - This is the first autogenerated insert id which was *successfully* - inserted by the previous statement (exactly, if the previous statement - didn't successfully insert an autogenerated insert id, then it's the one - of the statement before, etc). - It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#). - It is returned by LAST_INSERT_ID(). - */ - ulonglong first_successful_insert_id_in_prev_stmt; - /* - Variant of the above, used for storing in statement-based binlog. The - difference is that the one above can change as the execution of a stored - function progresses, while the one below is set once and then does not - change (which is the value which statement-based binlog needs). - */ - ulonglong first_successful_insert_id_in_prev_stmt_for_binlog; - /* - This is the first autogenerated insert id which was *successfully* - inserted by the current statement. It is maintained only to set - first_successful_insert_id_in_prev_stmt when statement ends. - */ - ulonglong first_successful_insert_id_in_cur_stmt; - /* - We follow this logic: - - when stmt starts, first_successful_insert_id_in_prev_stmt contains the - first insert id successfully inserted by the previous stmt. - - as stmt makes progress, handler::insert_id_for_cur_row changes; - every time get_auto_increment() is called, - auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the - reserved interval (if statement-based binlogging). - - at first successful insertion of an autogenerated value, - first_successful_insert_id_in_cur_stmt is set to - handler::insert_id_for_cur_row. - - when stmt goes to binlog, - auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if - non-empty. - - when stmt ends, first_successful_insert_id_in_prev_stmt is set to - first_successful_insert_id_in_cur_stmt. - */ - /* - stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when - LAST_INSERT_ID() is used by a statement. - If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be - stored in the statement-based binlog. - This variable is CUMULATIVE along the execution of a stored function or - trigger: if one substatement sets it to 1 it will stay 1 until the - function/trigger ends, thus making sure that - first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore - and is propagated to the caller for binlogging. - */ - bool stmt_depends_on_first_successful_insert_id_in_prev_stmt; - /* - List of auto_increment intervals reserved by the thread so far, for - storage in the statement-based binlog. - Note that its minimum is not first_successful_insert_id_in_cur_stmt: - assuming a table with an autoinc column, and this happens: - INSERT INTO ... VALUES(3); - SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL); - then the latter INSERT will insert no rows - (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3" - in the binlog is still needed; the list's minimum will contain 3. - This variable is cumulative: if several statements are written to binlog - as one (stored functions or triggers are used) this list is the - concatenation of all intervals reserved by all statements. - */ - Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog; - /* Used by replication and SET INSERT_ID */ - Discrete_intervals_list auto_inc_intervals_forced; - /* - There is BUG#19630 where statement-based replication of stored - functions/triggers with two auto_increment columns breaks. - We however ensure that it works when there is 0 or 1 auto_increment - column; our rules are - a) on master, while executing a top statement involving substatements, - first top- or sub- statement to generate auto_increment values wins the - exclusive right to see its values be written to binlog (the write - will be done by the statement or its caller), and the losers won't see - their values be written to binlog. - b) on slave, while replicating a top statement involving substatements, - first top- or sub- statement to need to read auto_increment values from - the master's binlog wins the exclusive right to read them (so the losers - won't read their values from binlog but instead generate on their own). - a) implies that we mustn't backup/restore - auto_inc_intervals_in_cur_stmt_for_binlog. - b) implies that we mustn't backup/restore auto_inc_intervals_forced. - - If there are more than 1 auto_increment columns, then intervals for - different columns may mix into the - auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong, - but there is no point in preventing this mixing by preventing intervals - from the secondly inserted column to come into the list, as such - prevention would be wrong too. - What will happen in the case of - INSERT INTO t1 (auto_inc) VALUES(NULL); - where t1 has a trigger which inserts into an auto_inc column of t2, is - that in binlog we'll store the interval of t1 and the interval of t2 (when - we store intervals, soon), then in slave, t1 will use both intervals, t2 - will use none; if t1 inserts the same number of rows as on master, - normally the 2nd interval will not be used by t1, which is fine. t2's - values will be wrong if t2's internal auto_increment counter is different - from what it was on master (which is likely). In 5.1, in mixed binlogging - mode, row-based binlogging is used for such cases where two - auto_increment columns are inserted. - */ - inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg) - { - if (first_successful_insert_id_in_cur_stmt == 0) - first_successful_insert_id_in_cur_stmt= id_arg; - } - inline ulonglong read_first_successful_insert_id_in_prev_stmt(void) - { - if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt) - { - /* It's the first time we read it */ - first_successful_insert_id_in_prev_stmt_for_binlog= - first_successful_insert_id_in_prev_stmt; - stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1; - } - return first_successful_insert_id_in_prev_stmt; - } - /* - Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#" - (mysqlbinlog). We'll soon add a variant which can take many intervals in - argument. - */ - inline void force_one_auto_inc_interval(ulonglong next_id) - { - auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID - auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0); - } - - ulonglong limit_found_rows; - -private: - /** - Stores the result of ROW_COUNT() function. - - ROW_COUNT() function is a MySQL extention, but we try to keep it - similar to ROW_COUNT member of the GET DIAGNOSTICS stack of the SQL - standard (see SQL99, part 2, search for ROW_COUNT). It's value is - implementation defined for anything except INSERT, DELETE, UPDATE. - - ROW_COUNT is assigned according to the following rules: - - - In my_ok(): - - for DML statements: to the number of affected rows; - - for DDL statements: to 0. - - - In my_eof(): to -1 to indicate that there was a result set. - - We derive this semantics from the JDBC specification, where int - java.sql.Statement.getUpdateCount() is defined to (sic) "return the - current result as an update count; if the result is a ResultSet - object or there are no more results, -1 is returned". - - - In my_error(): to -1 to be compatible with the MySQL C API and - MySQL ODBC driver. - - - For SIGNAL statements: to 0 per WL#2110 specification (see also - sql_signal.cc comment). Zero is used since that's the "default" - value of ROW_COUNT in the diagnostics area. - */ - - longlong m_row_count_func; /* For the ROW_COUNT() function */ - -public: - inline longlong get_row_count_func() const - { - return m_row_count_func; - } - - inline void set_row_count_func(longlong row_count_func) - { - m_row_count_func= row_count_func; - } - inline void set_affected_rows(longlong row_count_func) - { - /* - We have to add to affected_rows (used by slow log), as otherwise - information for 'call' will be wrong - */ - affected_rows+= (row_count_func >= 0 ? row_count_func : 0); - } - - ha_rows cuted_fields; - -private: - /* - number of rows we actually sent to the client, including "synthetic" - rows in ROLLUP etc. - */ - ha_rows m_sent_row_count; - - /** - Number of rows read and/or evaluated for a statement. Used for - slow log reporting. - - An examined row is defined as a row that is read and/or evaluated - according to a statement condition, including in - create_sort_index(). Rows may be counted more than once, e.g., a - statement including ORDER BY could possibly evaluate the row in - filesort() before reading it for e.g. update. - */ - ha_rows m_examined_row_count; - -public: - ha_rows get_sent_row_count() const - { return m_sent_row_count; } - - ha_rows get_examined_row_count() const - { return m_examined_row_count; } - - ulonglong get_affected_rows() const - { return affected_rows; } - - void set_sent_row_count(ha_rows count); - void set_examined_row_count(ha_rows count); - - void inc_sent_row_count(ha_rows count); - void inc_examined_row_count(ha_rows count); - - void inc_status_created_tmp_disk_tables(); - void inc_status_created_tmp_files(); - void inc_status_created_tmp_tables(); - void inc_status_select_full_join(); - void inc_status_select_full_range_join(); - void inc_status_select_range(); - void inc_status_select_range_check(); - void inc_status_select_scan(); - void inc_status_sort_merge_passes(); - void inc_status_sort_range(); - void inc_status_sort_rows(ha_rows count); - void inc_status_sort_scan(); - void set_status_no_index_used(); - void set_status_no_good_index_used(); - - /** - The number of rows and/or keys examined by the query, both read, - changed or written. - */ - ulonglong accessed_rows_and_keys; - - /** - Check if the number of rows accessed by a statement exceeded - LIMIT ROWS EXAMINED. If so, signal the query engine to stop execution. - */ - void check_limit_rows_examined() - { - if (++accessed_rows_and_keys > lex->limit_rows_examined_cnt) - set_killed(ABORT_QUERY); - } - - USER_CONN *user_connect; - CHARSET_INFO *db_charset; -#if defined(ENABLED_PROFILING) - PROFILING profiling; -#endif - - /** Current stage progress instrumentation. */ - PSI_stage_progress *m_stage_progress_psi; - /** Current statement digest. */ - sql_digest_state *m_digest; - /** Current statement digest token array. */ - unsigned char *m_token_array; - /** Top level statement digest. */ - sql_digest_state m_digest_state; - - /** Current statement instrumentation. */ - PSI_statement_locker *m_statement_psi; -#ifdef HAVE_PSI_STATEMENT_INTERFACE - /** Current statement instrumentation state. */ - PSI_statement_locker_state m_statement_state; -#endif /* HAVE_PSI_STATEMENT_INTERFACE */ - - /** Current transaction instrumentation. */ - PSI_transaction_locker *m_transaction_psi; -#ifdef HAVE_PSI_TRANSACTION_INTERFACE - /** Current transaction instrumentation state. */ - PSI_transaction_locker_state m_transaction_state; -#endif /* HAVE_PSI_TRANSACTION_INTERFACE */ - - /** Idle instrumentation. */ - PSI_idle_locker *m_idle_psi; -#ifdef HAVE_PSI_IDLE_INTERFACE - /** Idle instrumentation state. */ - PSI_idle_locker_state m_idle_state; -#endif /* HAVE_PSI_IDLE_INTERFACE */ - - /* - Id of current query. Statement can be reused to execute several queries - query_id is global in context of the whole MySQL server. - ID is automatically generated from mutex-protected counter. - It's used in handler code for various purposes: to check which columns - from table are necessary for this select, to check if it's necessary to - update auto-updatable fields (like auto_increment and timestamp). - */ - query_id_t query_id; - privilege_t col_access; - - /* Statement id is thread-wide. This counter is used to generate ids */ - ulong statement_id_counter; - ulong rand_saved_seed1, rand_saved_seed2; - - /* The following variables are used when printing to slow log */ - ulong query_plan_flags; - ulong query_plan_fsort_passes; - ulong tmp_tables_used; - ulong tmp_tables_disk_used; - ulonglong tmp_tables_size; - ulonglong bytes_sent_old; - ulonglong affected_rows; /* Number of changed rows */ - - Opt_trace_context opt_trace; - pthread_t real_id; /* For debugging */ - my_thread_id thread_id, thread_dbug_id; - uint32 os_thread_id; - uint tmp_table, global_disable_checkpoint; - uint server_status,open_options; - enum enum_thread_type system_thread; - enum backup_stages current_backup_stage; - /* - Current or next transaction isolation level. - When a connection is established, the value is taken from - @@session.tx_isolation (default transaction isolation for - the session), which is in turn taken from @@global.tx_isolation - (the global value). - If there is no transaction started, this variable - holds the value of the next transaction's isolation level. - When a transaction starts, the value stored in this variable - becomes "actual". - At transaction commit or rollback, we assign this variable - again from @@session.tx_isolation. - The only statement that can otherwise change the value - of this variable is SET TRANSACTION ISOLATION LEVEL. - Its purpose is to effect the isolation level of the next - transaction in this session. When this statement is executed, - the value in this variable is changed. However, since - this statement is only allowed when there is no active - transaction, this assignment (naturally) only affects the - upcoming transaction. - At the end of the current active transaction the value is - be reset again from @@session.tx_isolation, as described - above. - */ - enum_tx_isolation tx_isolation; - /* - Current or next transaction access mode. - See comment above regarding tx_isolation. - */ - bool tx_read_only; - enum_check_fields count_cuted_fields; - - DYNAMIC_ARRAY user_var_events; /* For user variables replication */ - MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */ - - /* - Define durability properties that engines may check to - improve performance. Not yet used in MariaDB - */ - enum durability_properties durability_property; - - /* - If checking this in conjunction with a wait condition, please - include a check after enter_cond() if you want to avoid a race - condition. For details see the implementation of awake(), - especially the "broadcast" part. - */ - killed_state volatile killed; - - /* - The following is used if one wants to have a specific error number and - text for the kill - */ - struct err_info - { - int no; - const char msg[256]; - } *killed_err; - - /* See also thd_killed() */ - inline bool check_killed(bool dont_send_error_message= 0) - { - if (unlikely(killed)) - { - if (!dont_send_error_message) - send_kill_message(); - return TRUE; - } - if (apc_target.have_apc_requests()) - apc_target.process_apc_requests(); - return FALSE; - } - - /* scramble - random string sent to client on handshake */ - char scramble[SCRAMBLE_LENGTH+1]; - - /* - If this is a slave, the name of the connection stored here. - This is used for taging error messages in the log files. - */ - LEX_CSTRING connection_name; - char default_master_connection_buff[MAX_CONNECTION_NAME+1]; - uint8 password; /* 0, 1 or 2 */ - uint8 failed_com_change_user; - bool slave_thread; - bool no_errors; - - /** - Set to TRUE if execution of the current compound statement - can not continue. In particular, disables activation of - CONTINUE or EXIT handlers of stored routines. - Reset in the end of processing of the current user request, in - @see THD::reset_for_next_command(). - */ - bool is_fatal_error; - /** - Set by a storage engine to request the entire - transaction (that possibly spans multiple engines) to - rollback. Reset in ha_rollback. - */ - bool transaction_rollback_request; - /** - TRUE if we are in a sub-statement and the current error can - not be safely recovered until we left the sub-statement mode. - In particular, disables activation of CONTINUE and EXIT - handlers inside sub-statements. E.g. if it is a deadlock - error and requires a transaction-wide rollback, this flag is - raised (traditionally, MySQL first has to close all the reads - via @see handler::ha_index_or_rnd_end() and only then perform - the rollback). - Reset to FALSE when we leave the sub-statement mode. - */ - bool is_fatal_sub_stmt_error; - bool rand_used, time_zone_used; - bool query_start_sec_part_used; - /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */ - bool substitute_null_with_insert_id; - bool in_lock_tables; - bool bootstrap, cleanup_done, free_connection_done; - - /** is set if some thread specific value(s) used in a statement. */ - bool thread_specific_used; - /** - is set if a statement accesses a temporary table created through - CREATE TEMPORARY TABLE. - */ -private: - bool charset_is_system_charset, charset_is_collation_connection; - bool charset_is_character_set_filesystem; -public: - bool enable_slow_log; /* Enable slow log for current statement */ - bool abort_on_warning; - bool got_warning; /* Set on call to push_warning() */ - /* set during loop of derived table processing */ - bool derived_tables_processing; - bool tablespace_op; /* This is TRUE in DISCARD/IMPORT TABLESPACE */ - /* True if we have to log the current statement */ - bool log_current_statement; - /** - True if a slave error. Causes the slave to stop. Not the same - as the statement execution error (is_error()), since - a statement may be expected to return an error, e.g. because - it returned an error on master, and this is OK on the slave. - */ - bool is_slave_error; - /* True if we have printed something to the error log for this statement */ - bool error_printed_to_log; - - /* - True when a transaction is queued up for binlog group commit. - Used so that if another transaction needs to wait for a row lock held by - this transaction, it can signal to trigger the group commit immediately, - skipping the normal --binlog-commit-wait-count wait. - */ - bool waiting_on_group_commit; - /* - Set true when another transaction goes to wait on a row lock held by this - transaction. Used together with waiting_on_group_commit. - */ - bool has_waiter; - /* - In case of a slave, set to the error code the master got when executing - the query. 0 if no error on the master. - */ - int slave_expected_error; - enum_sql_command last_sql_command; // Last sql_command exceuted in mysql_execute_command() - - sp_rcontext *spcont; // SP runtime context - sp_cache *sp_proc_cache; - sp_cache *sp_func_cache; - sp_cache *sp_package_spec_cache; - sp_cache *sp_package_body_cache; - - /** number of name_const() substitutions, see sp_head.cc:subst_spvars() */ - uint query_name_consts; - - NET* slave_net; // network connection from slave -> m. - - /* - Used to update global user stats. The global user stats are updated - occasionally with the 'diff' variables. After the update, the 'diff' - variables are reset to 0. - */ - /* Time when the current thread connected to MySQL. */ - time_t current_connect_time; - /* Last time when THD stats were updated in global_user_stats. */ - time_t last_global_update_time; - /* Number of commands not reflected in global_user_stats yet. */ - uint select_commands, update_commands, other_commands; - ulonglong start_cpu_time; - ulonglong start_bytes_received; - - /* Used by the sys_var class to store temporary values */ - union - { - my_bool my_bool_value; - int int_value; - uint uint_value; - long long_value; - ulong ulong_value; - ulonglong ulonglong_value; - double double_value; - void *ptr_value; - } sys_var_tmp; - - struct { - /* - If true, mysql_bin_log::write(Log_event) call will not write events to - binlog, and maintain 2 below variables instead (use - mysql_bin_log.start_union_events to turn this on) - */ - bool do_union; - /* - If TRUE, at least one mysql_bin_log::write(Log_event) call has been - made after last mysql_bin_log.start_union_events() call. - */ - bool unioned_events; - /* - If TRUE, at least one mysql_bin_log::write(Log_event e), where - e.cache_stmt == TRUE call has been made after last - mysql_bin_log.start_union_events() call. - */ - bool unioned_events_trans; - /* - 'queries' (actually SP statements) that run under inside this binlog - union have thd->query_id >= first_query_id. - */ - query_id_t first_query_id; - } binlog_evt_union; - - /** - Internal parser state. - Note that since the parser is not re-entrant, we keep only one parser - state here. This member is valid only when executing code during parsing. - */ - Parser_state *m_parser_state; - - Locked_tables_list locked_tables_list; - -#ifdef WITH_PARTITION_STORAGE_ENGINE - partition_info *work_part_info; -#endif - -#ifndef EMBEDDED_LIBRARY - /** - Array of active audit plugins which have been used by this THD. - This list is later iterated to invoke release_thd() on those - plugins. - */ - DYNAMIC_ARRAY audit_class_plugins; - /** - Array of bits indicating which audit classes have already been - added to the list of audit plugins which are currently in use. - */ - unsigned long audit_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; - int audit_plugin_version; -#endif - -#if defined(ENABLED_DEBUG_SYNC) - /* Debug Sync facility. See debug_sync.cc. */ - struct st_debug_sync_control *debug_sync_control; -#endif /* defined(ENABLED_DEBUG_SYNC) */ - /** - @param id thread identifier - @param is_wsrep_applier thread type - */ - THD(my_thread_id id, bool is_wsrep_applier= false); - - ~THD(); - - void init(); - /* - Initialize memory roots necessary for query processing and (!) - pre-allocate memory for it. We can't do that in THD constructor because - there are use cases (acl_init, delayed inserts, watcher threads, - killing mysqld) where it's vital to not allocate excessive and not used - memory. Note, that we still don't return error from init_for_queries(): - if preallocation fails, we should notice that at the first call to - alloc_root. - */ - void init_for_queries(); - void update_all_stats(); - void update_stats(void); - void change_user(void); - void cleanup(void); - void cleanup_after_query(); - void free_connection(); - void reset_for_reuse(); - void store_globals(); - void reset_globals(); - bool trace_started() - { - return opt_trace.is_started(); - } -#ifdef SIGNAL_WITH_VIO_CLOSE - inline void set_active_vio(Vio* vio) - { - mysql_mutex_lock(&LOCK_thd_data); - active_vio = vio; - mysql_mutex_unlock(&LOCK_thd_data); - } - inline void clear_active_vio() - { - mysql_mutex_lock(&LOCK_thd_data); - active_vio = 0; - mysql_mutex_unlock(&LOCK_thd_data); - } - void close_active_vio(); -#endif - void awake_no_mutex(killed_state state_to_set); - void awake(killed_state state_to_set) - { - bool wsrep_on_local= WSREP_NNULL(this); - /* - mutex locking order (LOCK_thd_data - LOCK_thd_kill)) requires - to grab LOCK_thd_data here - */ - if (wsrep_on_local) - mysql_mutex_lock(&LOCK_thd_data); - mysql_mutex_lock(&LOCK_thd_kill); - awake_no_mutex(state_to_set); - mysql_mutex_unlock(&LOCK_thd_kill); - if (wsrep_on_local) - mysql_mutex_unlock(&LOCK_thd_data); - } - - /** Disconnect the associated communication endpoint. */ - void disconnect(); - - - /* - Allows this thread to serve as a target for others to schedule Async - Procedure Calls on. - - It's possible to schedule any code to be executed this way, by - inheriting from the Apc_call object. Currently, only - Show_explain_request uses this. - */ - Apc_target apc_target; - - Gap_time_tracker_data gap_tracker_data; -#ifndef MYSQL_CLIENT - enum enum_binlog_query_type { - /* The query can be logged in row format or in statement format. */ - ROW_QUERY_TYPE, - - /* The query has to be logged in statement format. */ - STMT_QUERY_TYPE, - - QUERY_TYPE_COUNT - }; - - int binlog_query(enum_binlog_query_type qtype, - char const *query, ulong query_len, bool is_trans, - bool direct, bool suppress_use, - int errcode); - bool binlog_current_query_unfiltered(); -#endif - - inline void - enter_cond(mysql_cond_t *cond, mysql_mutex_t* mutex, - const PSI_stage_info *stage, PSI_stage_info *old_stage, - const char *src_function, const char *src_file, - int src_line) - { - mysql_mutex_assert_owner(mutex); - mysys_var->current_mutex = mutex; - mysys_var->current_cond = cond; - if (old_stage) - backup_stage(old_stage); - if (stage) - enter_stage(stage, src_function, src_file, src_line); - } - inline void exit_cond(const PSI_stage_info *stage, - const char *src_function, const char *src_file, - int src_line) - { - /* - Putting the mutex unlock in thd->exit_cond() ensures that - mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is - locked (if that would not be the case, you'll get a deadlock if someone - does a THD::awake() on you). - */ - mysql_mutex_unlock(mysys_var->current_mutex); - mysql_mutex_lock(&mysys_var->mutex); - mysys_var->current_mutex = 0; - mysys_var->current_cond = 0; - if (stage) - enter_stage(stage, src_function, src_file, src_line); - mysql_mutex_unlock(&mysys_var->mutex); - return; - } - virtual int is_killed() { return killed; } - virtual THD* get_thd() { return this; } - - /** - A callback to the server internals that is used to address - special cases of the locking protocol. - Invoked when acquiring an exclusive lock, for each thread that - has a conflicting shared metadata lock. - - This function: - - aborts waiting of the thread on a data lock, to make it notice - the pending exclusive lock and back off. - - if the thread is an INSERT DELAYED thread, sends it a KILL - signal to terminate it. - - @note This function does not wait for the thread to give away its - locks. Waiting is done outside for all threads at once. - - @param ctx_in_use The MDL context owner (thread) to wake up. - @param needs_thr_lock_abort Indicates that to wake up thread - this call needs to abort its waiting - on table-level lock. - - @retval TRUE if the thread was woken up - @retval FALSE otherwise. - */ - virtual bool notify_shared_lock(MDL_context_owner *ctx_in_use, - bool needs_thr_lock_abort); - - // End implementation of MDL_context_owner interface. - - inline bool is_strict_mode() const - { - return (bool) (variables.sql_mode & (MODE_STRICT_TRANS_TABLES | - MODE_STRICT_ALL_TABLES)); - } - inline bool backslash_escapes() const - { - return !MY_TEST(variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES); - } - const Type_handler *type_handler_for_datetime() const; - bool timestamp_to_TIME(MYSQL_TIME *ltime, my_time_t ts, - ulong sec_part, date_mode_t fuzzydate); - inline my_time_t query_start() { return start_time; } - inline ulong query_start_sec_part() - { query_start_sec_part_used=1; return start_time_sec_part; } - MYSQL_TIME query_start_TIME(); - time_round_mode_t temporal_round_mode() const - { - return variables.sql_mode & MODE_TIME_ROUND_FRACTIONAL ? - TIME_FRAC_ROUND : TIME_FRAC_TRUNCATE; - } - -private: - struct { - my_hrtime_t start; - my_time_t sec; - ulong sec_part; - } system_time; - - void set_system_time() - { - my_hrtime_t hrtime= my_hrtime(); - my_time_t sec= hrtime_to_my_time(hrtime); - ulong sec_part= hrtime_sec_part(hrtime); - if (sec > system_time.sec || - (sec == system_time.sec && sec_part > system_time.sec_part) || - hrtime.val < system_time.start.val) - { - system_time.sec= sec; - system_time.sec_part= sec_part; - system_time.start= hrtime; - } - else - { - if (system_time.sec_part < TIME_MAX_SECOND_PART) - system_time.sec_part++; - else - { - system_time.sec++; - system_time.sec_part= 0; - } - } - } - -public: - timeval transaction_time() - { - if (!in_multi_stmt_transaction_mode()) - transaction->start_time.reset(this); - return transaction->start_time; - } - - inline void set_start_time() - { - if (user_time.val) - { - start_time= hrtime_to_my_time(user_time); - start_time_sec_part= hrtime_sec_part(user_time); - } - else - { - set_system_time(); - start_time= system_time.sec; - start_time_sec_part= system_time.sec_part; - } - PSI_CALL_set_thread_start_time(start_time); - } - inline void set_time() - { - set_start_time(); - start_utime= utime_after_lock= microsecond_interval_timer(); - } - /* only used in SET @@timestamp=... */ - inline void set_time(my_hrtime_t t) - { - user_time= t; - set_time(); - } - /* - this is only used by replication and BINLOG command. - usecs > TIME_MAX_SECOND_PART means "was not in binlog" - */ - inline void set_time(my_time_t t, ulong sec_part) - { - if (opt_secure_timestamp > (slave_thread ? SECTIME_REPL : SECTIME_SUPER)) - set_time(); // note that BINLOG itself requires SUPER - else - { - if (sec_part <= TIME_MAX_SECOND_PART) - { - start_time= system_time.sec= t; - start_time_sec_part= system_time.sec_part= sec_part; - } - else if (t != system_time.sec) - { - start_time= system_time.sec= t; - start_time_sec_part= system_time.sec_part= 0; - } - else - { - start_time= t; - start_time_sec_part= ++system_time.sec_part; - } - user_time.val= hrtime_from_time(start_time) + start_time_sec_part; - PSI_CALL_set_thread_start_time(start_time); - start_utime= utime_after_lock= microsecond_interval_timer(); - } - } - void set_time_after_lock() - { - utime_after_lock= microsecond_interval_timer(); - MYSQL_SET_STATEMENT_LOCK_TIME(m_statement_psi, - (utime_after_lock - start_utime)); - } - ulonglong current_utime() { return microsecond_interval_timer(); } - - /* Tell SHOW PROCESSLIST to show time from this point */ - inline void set_time_for_next_stage() - { - utime_after_query= current_utime(); - } - - /** - Update server status after execution of a top level statement. - Currently only checks if a query was slow, and assigns - the status accordingly. - Evaluate the current time, and if it exceeds the long-query-time - setting, mark the query as slow. - */ - void update_server_status() - { - set_time_for_next_stage(); - if (utime_after_query >= utime_after_lock + variables.long_query_time) - server_status|= SERVER_QUERY_WAS_SLOW; - } - inline ulonglong found_rows(void) - { - return limit_found_rows; - } - /** - Returns TRUE if session is in a multi-statement transaction mode. - - OPTION_NOT_AUTOCOMMIT: When autocommit is off, a multi-statement - transaction is implicitly started on the first statement after a - previous transaction has been ended. - - OPTION_BEGIN: Regardless of the autocommit status, a multi-statement - transaction can be explicitly started with the statements "START - TRANSACTION", "BEGIN [WORK]", "[COMMIT | ROLLBACK] AND CHAIN", etc. - - Note: this doesn't tell you whether a transaction is active. - A session can be in multi-statement transaction mode, and yet - have no active transaction, e.g., in case of: - set @@autocommit=0; - set @a= 3; <-- these statements don't - set transaction isolation level serializable; <-- start an active - flush tables; <-- transaction - - I.e. for the above scenario this function returns TRUE, even - though no active transaction has begun. - @sa in_active_multi_stmt_transaction() - */ - inline bool in_multi_stmt_transaction_mode() - { - return variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN); - } - /** - TRUE if the session is in a multi-statement transaction mode - (@sa in_multi_stmt_transaction_mode()) *and* there is an - active transaction, i.e. there is an explicit start of a - transaction with BEGIN statement, or implicit with a - statement that uses a transactional engine. - - For example, these scenarios don't start an active transaction - (even though the server is in multi-statement transaction mode): - - set @@autocommit=0; - select * from nontrans_table; - set @var=TRUE; - flush tables; - - Note, that even for a statement that starts a multi-statement - transaction (i.e. select * from trans_table), this - flag won't be set until we open the statement's tables - and the engines register themselves for the transaction - (see trans_register_ha()), - hence this method is reliable to use only after - open_tables() has completed. - - Why do we need a flag? - ---------------------- - We need to maintain a (at first glance redundant) - session flag, rather than looking at thd->transaction.all.ha_list - because of explicit start of a transaction with BEGIN. - - I.e. in case of - BEGIN; - select * from nontrans_t1; <-- in_active_multi_stmt_transaction() is true - */ - inline bool in_active_multi_stmt_transaction() - { - return server_status & SERVER_STATUS_IN_TRANS; - } - /* Commit both statement and full transaction */ - int commit_whole_transaction_and_close_tables(); - void give_protection_error(); - /* - Give an error if any of the following is true for this connection - - BACKUP STAGE is active - - FLUSH TABLE WITH READ LOCK is active - - BACKUP LOCK table_name is active - */ - inline bool has_read_only_protection() - { - if (current_backup_stage == BACKUP_FINISHED && - !global_read_lock.is_acquired() && - !mdl_backup_lock) - return FALSE; - give_protection_error(); - return TRUE; - } - inline bool fill_derived_tables() - { - return !stmt_arena->is_stmt_prepare() && !lex->only_view_structure(); - } - inline bool fill_information_schema_tables() - { - return !stmt_arena->is_stmt_prepare(); - } - inline void* trans_alloc(size_t size) - { - return alloc_root(&transaction->mem_root,size); - } - - LEX_CSTRING strmake_lex_cstring(const char *str, size_t length) - { - const char *tmp= strmake_root(mem_root, str, length); - if (!tmp) - return {0,0}; - return {tmp, length}; - } - LEX_CSTRING strmake_lex_cstring(const LEX_CSTRING &from) - { - return strmake_lex_cstring(from.str, from.length); - } - - LEX_STRING *make_lex_string(LEX_STRING *lex_str, const char* str, size_t length) - { - if (!(lex_str->str= strmake_root(mem_root, str, length))) - { - lex_str->length= 0; - return 0; - } - lex_str->length= length; - return lex_str; - } - LEX_CSTRING *make_lex_string(LEX_CSTRING *lex_str, const char* str, size_t length) - { - if (!(lex_str->str= strmake_root(mem_root, str, length))) - { - lex_str->length= 0; - return 0; - } - lex_str->length= length; - return lex_str; - } - // Remove double quotes: aaa""bbb -> aaa"bbb - bool quote_unescape(LEX_CSTRING *dst, const LEX_CSTRING *src, char quote) - { - const char *tmp= src->str; - const char *tmpend= src->str + src->length; - char *to; - if (!(dst->str= to= (char *) alloc(src->length + 1))) - { - dst->length= 0; // Safety - return true; - } - for ( ; tmp < tmpend; ) - { - if ((*to++= *tmp++) == quote) - tmp++; // Skip double quotes - } - *to= 0; // End null for safety - dst->length= to - dst->str; - return false; - } - - LEX_CSTRING *make_clex_string(const char* str, size_t length) - { - LEX_CSTRING *lex_str; - char *tmp; - if (unlikely(!(lex_str= (LEX_CSTRING *)alloc_root(mem_root, - sizeof(LEX_CSTRING) + - length+1)))) - return 0; - tmp= (char*) (lex_str+1); - lex_str->str= tmp; - memcpy(tmp, str, length); - tmp[length]= 0; - lex_str->length= length; - return lex_str; - } - LEX_CSTRING *make_clex_string(const LEX_CSTRING from) - { - return make_clex_string(from.str, from.length); - } - - // Allocate LEX_STRING for character set conversion - bool alloc_lex_string(LEX_STRING *dst, size_t length) - { - if (likely((dst->str= (char*) alloc(length)))) - return false; - dst->length= 0; // Safety - return true; // EOM - } - bool convert_string(LEX_STRING *to, CHARSET_INFO *to_cs, - const char *from, size_t from_length, - CHARSET_INFO *from_cs); - bool convert_string(LEX_CSTRING *to, CHARSET_INFO *to_cs, - const char *from, size_t from_length, - CHARSET_INFO *from_cs) - { - LEX_STRING tmp; - bool rc= convert_string(&tmp, to_cs, from, from_length, from_cs); - to->str= tmp.str; - to->length= tmp.length; - return rc; - } - bool convert_string(LEX_CSTRING *to, CHARSET_INFO *tocs, - const LEX_CSTRING *from, CHARSET_INFO *fromcs, - bool simple_copy_is_possible) - { - if (!simple_copy_is_possible) - return unlikely(convert_string(to, tocs, from->str, from->length, fromcs)); - *to= *from; - return false; - } - /* - Convert a strings between character sets. - Uses my_convert_fix(), which uses an mb_wc .. mc_mb loop internally. - dstcs and srccs cannot be &my_charset_bin. - */ - bool convert_fix(CHARSET_INFO *dstcs, LEX_STRING *dst, - CHARSET_INFO *srccs, const char *src, size_t src_length, - String_copier *status); - - /* - Same as above, but additionally sends ER_INVALID_CHARACTER_STRING - in case of bad byte sequences or Unicode conversion problems. - */ - bool convert_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst, - CHARSET_INFO *srccs, - const char *src, size_t src_length); - /* - If either "dstcs" or "srccs" is &my_charset_bin, - then performs native copying using copy_fix(). - Otherwise, performs Unicode conversion using convert_fix(). - */ - bool copy_fix(CHARSET_INFO *dstcs, LEX_STRING *dst, - CHARSET_INFO *srccs, const char *src, size_t src_length, - String_copier *status); - - /* - Same as above, but additionally sends ER_INVALID_CHARACTER_STRING - in case of bad byte sequences or Unicode conversion problems. - */ - bool copy_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst, - CHARSET_INFO *srccs, const char *src, size_t src_length); - - bool convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs); - - /* - Check if the string is wellformed, raise an error if not wellformed. - @param str - The string to check. - @param length - the string length. - */ - bool check_string_for_wellformedness(const char *str, - size_t length, - CHARSET_INFO *cs) const; - - bool to_ident_sys_alloc(Lex_ident_sys_st *to, const Lex_ident_cli_st *from); - - /* - Create a string literal with optional client->connection conversion. - @param str - the string in the client character set - @param length - length of the string - @param repertoire - the repertoire of the string - */ - Item_basic_constant *make_string_literal(const char *str, size_t length, - my_repertoire_t repertoire); - Item_basic_constant *make_string_literal(const Lex_string_with_metadata_st &str) - { - my_repertoire_t repertoire= str.repertoire(variables.character_set_client); - return make_string_literal(str.str, str.length, repertoire); - } - Item_basic_constant *make_string_literal_nchar(const Lex_string_with_metadata_st &str); - Item_basic_constant *make_string_literal_charset(const Lex_string_with_metadata_st &str, - CHARSET_INFO *cs); - bool make_text_string_sys(LEX_CSTRING *to, - const Lex_string_with_metadata_st *from) - { - return convert_string(to, system_charset_info, - from, charset(), charset_is_system_charset); - } - bool make_text_string_connection(LEX_CSTRING *to, - const Lex_string_with_metadata_st *from) - { - return convert_string(to, variables.collation_connection, - from, charset(), charset_is_collation_connection); - } - bool make_text_string_filesystem(LEX_CSTRING *to, - const Lex_string_with_metadata_st *from) - { - return convert_string(to, variables.character_set_filesystem, - from, charset(), charset_is_character_set_filesystem); - } - void add_changed_table(TABLE *table); - void add_changed_table(const char *key, size_t key_length); - CHANGED_TABLE_LIST * changed_table_dup(const char *key, size_t key_length); - int prepare_explain_fields(select_result *result, List *field_list, - uint8 explain_flags, bool is_analyze); - int send_explain_fields(select_result *result, uint8 explain_flags, - bool is_analyze); - void make_explain_field_list(List &field_list, uint8 explain_flags, - bool is_analyze); - void make_explain_json_field_list(List &field_list, bool is_analyze); - - /** - Clear the current error, if any. - We do not clear is_fatal_error or is_fatal_sub_stmt_error since we - assume this is never called if the fatal error is set. - - @todo: To silence an error, one should use Internal_error_handler - mechanism. Issuing an error that can be possibly later "cleared" is not - compatible with other installed error handlers and audit plugins. - */ - inline void clear_error(bool clear_diagnostics= 0) - { - DBUG_ENTER("clear_error"); - if (get_stmt_da()->is_error() || clear_diagnostics) - get_stmt_da()->reset_diagnostics_area(); - is_slave_error= 0; - if (killed == KILL_BAD_DATA) - reset_killed(); - DBUG_VOID_RETURN; - } - -#ifndef EMBEDDED_LIBRARY - inline bool vio_ok() const { return net.vio != 0; } - /** Return FALSE if connection to client is broken. */ - bool is_connected() - { - /* - All system threads (e.g., the slave IO thread) are connected but - not using vio. So this function always returns true for all - system threads. - */ - return system_thread || (vio_ok() ? vio_is_connected(net.vio) : FALSE); - } -#else - inline bool vio_ok() const { return TRUE; } - inline bool is_connected() { return TRUE; } -#endif - /** - Mark the current error as fatal. Warning: this does not - set any error, it sets a property of the error, so must be - followed or prefixed with my_error(). - */ - inline void fatal_error() - { - DBUG_ASSERT(get_stmt_da()->is_error() || killed); - is_fatal_error= 1; - DBUG_PRINT("error",("Fatal error set")); - } - /** - TRUE if there is an error in the error stack. - - Please use this method instead of direct access to - net.report_error. - - If TRUE, the current (sub)-statement should be aborted. - The main difference between this member and is_fatal_error - is that a fatal error can not be handled by a stored - procedure continue handler, whereas a normal error can. - - To raise this flag, use my_error(). - */ - inline bool is_error() const { return m_stmt_da->is_error(); } - void set_bulk_execution(void *bulk) - { - bulk_param= bulk; - m_stmt_da->set_bulk_execution(MY_TEST(bulk)); - } - bool is_bulk_op() const { return MY_TEST(bulk_param); } - - /// Returns Diagnostics-area for the current statement. - Diagnostics_area *get_stmt_da() - { return m_stmt_da; } - - /// Returns Diagnostics-area for the current statement. - const Diagnostics_area *get_stmt_da() const - { return m_stmt_da; } - - /// Sets Diagnostics-area for the current statement. - void set_stmt_da(Diagnostics_area *da) - { m_stmt_da= da; } - - inline CHARSET_INFO *charset() const { return variables.character_set_client; } - void update_charset(); - void update_charset(CHARSET_INFO *character_set_client, - CHARSET_INFO *collation_connection) - { - variables.character_set_client= character_set_client; - variables.collation_connection= collation_connection; - update_charset(); - } - void update_charset(CHARSET_INFO *character_set_client, - CHARSET_INFO *collation_connection, - CHARSET_INFO *character_set_results) - { - variables.character_set_client= character_set_client; - variables.collation_connection= collation_connection; - variables.character_set_results= character_set_results; - update_charset(); - } - - inline Query_arena *activate_stmt_arena_if_needed(Query_arena *backup) - { - /* - Use the persistent arena if we are in a prepared statement or a stored - procedure statement and we have not already changed to use this arena. - */ - if (!stmt_arena->is_conventional() && mem_root != stmt_arena->mem_root) - { - set_n_backup_active_arena(stmt_arena, backup); - return stmt_arena; - } - return 0; - } - - - bool is_item_tree_change_register_required() - { - return !stmt_arena->is_conventional() - || stmt_arena->type() == Query_arena::TABLE_ARENA; - } - - void change_item_tree(Item **place, Item *new_value) - { - DBUG_ENTER("THD::change_item_tree"); - DBUG_PRINT("enter", ("Register: %p (%p) <- %p", - *place, place, new_value)); - /* TODO: check for OOM condition here */ - if (is_item_tree_change_register_required()) - nocheck_register_item_tree_change(place, *place, mem_root); - *place= new_value; - DBUG_VOID_RETURN; - } - /** - Make change in item tree after checking whether it needs registering - - - @param place place where we should assign new value - @param new_value place of the new value - - @details - see check_and_register_item_tree_change details - */ - void check_and_register_item_tree(Item **place, Item **new_value) - { - if (!stmt_arena->is_conventional()) - check_and_register_item_tree_change(place, new_value, mem_root); - /* - We have to use memcpy instead of *place= *new_value merge to - avoid problems with strict aliasing. - */ - memcpy((char*) place, new_value, sizeof(*new_value)); - } - - /* - Cleanup statement parse state (parse tree, lex) and execution - state after execution of a non-prepared SQL statement. - */ - void end_statement(); - - /* - Mark thread to be killed, with optional error number and string. - string is not released, so it has to be allocted on thd mem_root - or be a global string - - Ensure that we don't replace a kill with a lesser one. For example - if user has done 'kill_connection' we shouldn't replace it with - KILL_QUERY. - */ - inline void set_killed(killed_state killed_arg, - int killed_errno_arg= 0, - const char *killed_err_msg_arg= 0) - { - mysql_mutex_lock(&LOCK_thd_kill); - set_killed_no_mutex(killed_arg, killed_errno_arg, killed_err_msg_arg); - mysql_mutex_unlock(&LOCK_thd_kill); - } - /* - This is only used by THD::awake where we need to keep the lock mutex - locked over some time. - It's ok to have this inline, as in most cases killed_errno_arg will - be a constant 0 and most of the function will disappear. - */ - inline void set_killed_no_mutex(killed_state killed_arg, - int killed_errno_arg= 0, - const char *killed_err_msg_arg= 0) - { - if (killed <= killed_arg) - { - killed= killed_arg; - if (killed_errno_arg) - { - /* - If alloc fails, we only remember the killed flag. - The worst things that can happen is that we get - a suboptimal error message. - */ - killed_err= (err_info*) alloc_root(&main_mem_root, sizeof(*killed_err)); - if (likely(killed_err)) - { - killed_err->no= killed_errno_arg; - ::strmake((char*) killed_err->msg, killed_err_msg_arg, - sizeof(killed_err->msg)-1); - } - } - } - } - int killed_errno(); - void reset_killed(); - inline void reset_kill_query() - { - if (killed < KILL_CONNECTION) - { - reset_killed(); - mysys_var->abort= 0; - } - } - inline void send_kill_message() - { - mysql_mutex_lock(&LOCK_thd_kill); - int err= killed_errno(); - if (err) - my_message(err, killed_err ? killed_err->msg : ER_THD(this, err), - MYF(0)); - mysql_mutex_unlock(&LOCK_thd_kill); - } - /* return TRUE if we will abort query if we make a warning now */ - inline bool really_abort_on_warning() - { - return (abort_on_warning && - (!transaction->stmt.modified_non_trans_table || - (variables.sql_mode & MODE_STRICT_ALL_TABLES))); - } - void set_status_var_init(); - void reset_n_backup_open_tables_state(Open_tables_backup *backup); - void restore_backup_open_tables_state(Open_tables_backup *backup); - void reset_sub_statement_state(Sub_statement_state *backup, uint new_state); - void restore_sub_statement_state(Sub_statement_state *backup); - void store_slow_query_state(Sub_statement_state *backup); - void reset_slow_query_state(); - void add_slow_query_state(Sub_statement_state *backup); - void set_n_backup_active_arena(Query_arena *set, Query_arena *backup); - void restore_active_arena(Query_arena *set, Query_arena *backup); - - inline void get_binlog_format(enum_binlog_format *format, - enum_binlog_format *current_format) - { - *format= (enum_binlog_format) variables.binlog_format; - *current_format= current_stmt_binlog_format; - } - inline enum_binlog_format get_current_stmt_binlog_format() - { - return current_stmt_binlog_format; - } - inline void set_binlog_format(enum_binlog_format format, - enum_binlog_format current_format) - { - DBUG_ENTER("set_binlog_format"); - variables.binlog_format= format; - current_stmt_binlog_format= current_format; - DBUG_VOID_RETURN; - } - inline void set_binlog_format_stmt() - { - DBUG_ENTER("set_binlog_format_stmt"); - variables.binlog_format= BINLOG_FORMAT_STMT; - current_stmt_binlog_format= BINLOG_FORMAT_STMT; - DBUG_VOID_RETURN; - } - /* - @todo Make these methods private or remove them completely. Only - decide_logging_format should call them. /Sven - */ - inline void set_current_stmt_binlog_format_row_if_mixed() - { - DBUG_ENTER("set_current_stmt_binlog_format_row_if_mixed"); - /* - This should only be called from decide_logging_format. - - @todo Once we have ensured this, uncomment the following - statement, remove the big comment below that, and remove the - in_sub_stmt==0 condition from the following 'if'. - */ - /* DBUG_ASSERT(in_sub_stmt == 0); */ - /* - If in a stored/function trigger, the caller should already have done the - change. We test in_sub_stmt to prevent introducing bugs where people - wouldn't ensure that, and would switch to row-based mode in the middle - of executing a stored function/trigger (which is too late, see also - reset_current_stmt_binlog_format_row()); this condition will make their - tests fail and so force them to propagate the - lex->binlog_row_based_if_mixed upwards to the caller. - */ - if ((wsrep_binlog_format() == BINLOG_FORMAT_MIXED) && (in_sub_stmt == 0)) - set_current_stmt_binlog_format_row(); - - DBUG_VOID_RETURN; - } - - inline void set_current_stmt_binlog_format(enum_binlog_format format) - { - current_stmt_binlog_format= format; - } - - inline void set_current_stmt_binlog_format_row() - { - DBUG_ENTER("set_current_stmt_binlog_format_row"); - current_stmt_binlog_format= BINLOG_FORMAT_ROW; - DBUG_VOID_RETURN; - } - /* Set binlog format temporarily to statement. Returns old format */ - inline enum_binlog_format set_current_stmt_binlog_format_stmt() - { - enum_binlog_format orig_format= current_stmt_binlog_format; - DBUG_ENTER("set_current_stmt_binlog_format_stmt"); - current_stmt_binlog_format= BINLOG_FORMAT_STMT; - DBUG_RETURN(orig_format); - } - inline void restore_stmt_binlog_format(enum_binlog_format format) - { - DBUG_ENTER("restore_stmt_binlog_format"); - DBUG_ASSERT(!is_current_stmt_binlog_format_row()); - current_stmt_binlog_format= format; - DBUG_VOID_RETURN; - } - inline void reset_current_stmt_binlog_format_row() - { - DBUG_ENTER("reset_current_stmt_binlog_format_row"); - /* - If there are temporary tables, don't reset back to - statement-based. Indeed it could be that: - CREATE TEMPORARY TABLE t SELECT UUID(); # row-based - # and row-based does not store updates to temp tables - # in the binlog. - INSERT INTO u SELECT * FROM t; # stmt-based - and then the INSERT will fail as data inserted into t was not logged. - So we continue with row-based until the temp table is dropped. - If we are in a stored function or trigger, we mustn't reset in the - middle of its execution (as the binary logging way of a stored function - or trigger is decided when it starts executing, depending for example on - the caller (for a stored function: if caller is SELECT or - INSERT/UPDATE/DELETE...). - */ - DBUG_PRINT("debug", - ("temporary_tables: %s, in_sub_stmt: %s, system_thread: %s", - YESNO(has_thd_temporary_tables()), YESNO(in_sub_stmt), - show_system_thread(system_thread))); - if (in_sub_stmt == 0) - { - if (wsrep_binlog_format() == BINLOG_FORMAT_ROW) - set_current_stmt_binlog_format_row(); - else if (!has_thd_temporary_tables()) - set_current_stmt_binlog_format_stmt(); - } - DBUG_VOID_RETURN; - } - - /** - Set the current database; use deep copy of C-string. - - @param new_db a pointer to the new database name. - @param new_db_len length of the new database name. - - Initialize the current database from a NULL-terminated string with - length. If we run out of memory, we free the current database and - return TRUE. This way the user will notice the error as there will be - no current database selected (in addition to the error message set by - malloc). - - @note This operation just sets {db, db_length}. Switching the current - database usually involves other actions, like switching other database - attributes including security context. In the future, this operation - will be made private and more convenient interface will be provided. - - @return Operation status - @retval FALSE Success - @retval TRUE Out-of-memory error - */ - bool set_db(const LEX_CSTRING *new_db); - - /** Set the current database, without copying */ - void reset_db(const LEX_CSTRING *new_db); - - /* - Copy the current database to the argument. Use the current arena to - allocate memory for a deep copy: current database may be freed after - a statement is parsed but before it's executed. - - Can only be called by owner of thd (no mutex protection) - */ - bool copy_db_to(LEX_CSTRING *to) - { - if (db.str == NULL) - { - /* - No default database is set. In this case if it's guaranteed that - no CTE can be used in the statement then we can throw an error right - now at the parser stage. Otherwise the decision about throwing such - a message must be postponed until a post-parser stage when we are able - to resolve all CTE names as we don't need this message to be thrown - for any CTE references. - */ - if (!lex->with_clauses_list) - { - my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0)); - return TRUE; - } - /* This will allow to throw an error later for non-CTE references */ - to->str= NULL; - to->length= 0; - return FALSE; - } - - to->str= strmake(db.str, db.length); - to->length= db.length; - return to->str == NULL; /* True on error */ - } - /* Get db name or "". Use for printing current db */ - const char *get_db() - { return safe_str(db.str); } - - thd_scheduler event_scheduler; - -public: - inline Internal_error_handler *get_internal_handler() - { return m_internal_handler; } - - /** - Add an internal error handler to the thread execution context. - @param handler the exception handler to add - */ - void push_internal_handler(Internal_error_handler *handler); - -private: - /** - Handle a sql condition. - @param sql_errno the condition error number - @param sqlstate the condition sqlstate - @param level the condition level - @param msg the condition message text - @param[out] cond_hdl the sql condition raised, if any - @return true if the condition is handled - */ - bool handle_condition(uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level *level, - const char* msg, - Sql_condition ** cond_hdl); - -public: - /** - Remove the error handler last pushed. - */ - Internal_error_handler *pop_internal_handler(); - - /** - Raise an exception condition. - @param code the MYSQL_ERRNO error code of the error - */ - void raise_error(uint code); - - /** - Raise an exception condition, with a formatted message. - @param code the MYSQL_ERRNO error code of the error - */ - void raise_error_printf(uint code, ...); - - /** - Raise a completion condition (warning). - @param code the MYSQL_ERRNO error code of the warning - */ - void raise_warning(uint code); - - /** - Raise a completion condition (warning), with a formatted message. - @param code the MYSQL_ERRNO error code of the warning - */ - void raise_warning_printf(uint code, ...); - - /** - Raise a completion condition (note), with a fixed message. - @param code the MYSQL_ERRNO error code of the note - */ - void raise_note(uint code); - - /** - Raise an completion condition (note), with a formatted message. - @param code the MYSQL_ERRNO error code of the note - */ - void raise_note_printf(uint code, ...); - - /** - @brief Push an error message into MySQL error stack with line - and position information. - - This function provides semantic action implementers with a way - to push the famous "You have a syntax error near..." error - message into the error stack, which is normally produced only if - a parse error is discovered internally by the Bison generated - parser. - */ - void parse_error(const char *err_text, const char *yytext) - { - Lex_input_stream *lip= &m_parser_state->m_lip; - if (!yytext && !(yytext= lip->get_tok_start())) - yytext= ""; - /* Push an error into the error stack */ - ErrConvString err(yytext, strlen(yytext), variables.character_set_client); - my_printf_error(ER_PARSE_ERROR, ER_THD(this, ER_PARSE_ERROR), MYF(0), - err_text, err.ptr(), lip->yylineno); - } - void parse_error(uint err_number, const char *yytext= 0) - { - parse_error(ER_THD(this, err_number), yytext); - } - void parse_error() - { - parse_error(ER_SYNTAX_ERROR); - } -#ifdef mysqld_error_find_printf_error_used - void parse_error(const char *t) - { - } -#endif -private: - /* - Only the implementation of the SIGNAL and RESIGNAL statements - is permitted to raise SQL conditions in a generic way, - or to raise them by bypassing handlers (RESIGNAL). - To raise a SQL condition, the code should use the public - raise_error() or raise_warning() methods provided by class THD. - */ - friend class Sql_cmd_common_signal; - friend class Sql_cmd_signal; - friend class Sql_cmd_resignal; - friend void push_warning(THD*, Sql_condition::enum_warning_level, uint, const char*); - friend void my_message_sql(uint, const char *, myf); - - /** - Raise a generic SQL condition. - @param sql_errno the condition error number - @param sqlstate the condition SQLSTATE - @param level the condition level - @param msg the condition message text - @return The condition raised, or NULL - */ - Sql_condition* - raise_condition(uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level level, - const char* msg) - { - return raise_condition(sql_errno, sqlstate, level, - Sql_user_condition_identity(), msg); - } - - /** - Raise a generic or a user defined SQL condition. - @param ucid - the user condition identity - (or an empty identity if not a user condition) - @param sql_errno - the condition error number - @param sqlstate - the condition SQLSTATE - @param level - the condition level - @param msg - the condition message text - @return The condition raised, or NULL - */ - Sql_condition* - raise_condition(uint sql_errno, - const char* sqlstate, - Sql_condition::enum_warning_level level, - const Sql_user_condition_identity &ucid, - const char* msg); - - Sql_condition* - raise_condition(const Sql_condition *cond) - { - Sql_condition *raised= raise_condition(cond->get_sql_errno(), - cond->get_sqlstate(), - cond->get_level(), - *cond/*Sql_user_condition_identity*/, - cond->get_message_text()); - if (raised) - raised->copy_opt_attributes(cond); - return raised; - } - -private: - void push_warning_truncated_priv(Sql_condition::enum_warning_level level, - uint sql_errno, - const char *type_str, const char *val) - { - DBUG_ASSERT(sql_errno == ER_TRUNCATED_WRONG_VALUE || - sql_errno == ER_WRONG_VALUE); - char buff[MYSQL_ERRMSG_SIZE]; - CHARSET_INFO *cs= &my_charset_latin1; - cs->cset->snprintf(cs, buff, sizeof(buff), - ER_THD(this, sql_errno), type_str, val); - /* - Note: the format string can vary between ER_TRUNCATED_WRONG_VALUE - and ER_WRONG_VALUE, but the code passed to push_warning() is - always ER_TRUNCATED_WRONG_VALUE. This is intentional. - */ - push_warning(this, level, ER_TRUNCATED_WRONG_VALUE, buff); - } -public: - void push_warning_truncated_wrong_value(Sql_condition::enum_warning_level level, - const char *type_str, const char *val) - { - return push_warning_truncated_priv(level, ER_TRUNCATED_WRONG_VALUE, - type_str, val); - } - void push_warning_wrong_value(Sql_condition::enum_warning_level level, - const char *type_str, const char *val) - { - return push_warning_truncated_priv(level, ER_WRONG_VALUE, type_str, val); - } - void push_warning_truncated_wrong_value(const char *type_str, const char *val) - { - return push_warning_truncated_wrong_value(Sql_condition::WARN_LEVEL_WARN, - type_str, val); - } - void push_warning_truncated_value_for_field(Sql_condition::enum_warning_level - level, const char *type_str, - const char *val, - const char *db_name, - const char *table_name, - const char *name) - { - DBUG_ASSERT(name); - char buff[MYSQL_ERRMSG_SIZE]; - CHARSET_INFO *cs= &my_charset_latin1; - - if (!db_name) - db_name= ""; - if (!table_name) - table_name= ""; - cs->cset->snprintf(cs, buff, sizeof(buff), - ER_THD(this, ER_TRUNCATED_WRONG_VALUE_FOR_FIELD), - type_str, val, db_name, table_name, name, - (ulong) get_stmt_da()->current_row_for_warning()); - push_warning(this, level, ER_TRUNCATED_WRONG_VALUE, buff); - - } - void push_warning_wrong_or_truncated_value(Sql_condition::enum_warning_level level, - bool totally_useless_value, - const char *type_str, - const char *val, - const char *db_name, - const char *table_name, - const char *field_name) - { - if (field_name) - push_warning_truncated_value_for_field(level, type_str, val, - db_name, table_name, field_name); - else if (totally_useless_value) - push_warning_wrong_value(level, type_str, val); - else - push_warning_truncated_wrong_value(level, type_str, val); - } - -public: - /** Overloaded to guard query/query_length fields */ - virtual void set_statement(Statement *stmt); - void set_command(enum enum_server_command command) - { - m_command= command; -#ifdef HAVE_PSI_THREAD_INTERFACE - PSI_STATEMENT_CALL(set_thread_command)(m_command); -#endif - } - inline enum enum_server_command get_command() const - { return m_command; } - - /** - Assign a new value to thd->query and thd->query_id and mysys_var. - Protected with LOCK_thd_data mutex. - */ - void set_query(char *query_arg, size_t query_length_arg, - CHARSET_INFO *cs_arg) - { - set_query(CSET_STRING(query_arg, query_length_arg, cs_arg)); - } - void set_query(char *query_arg, size_t query_length_arg) /*Mutex protected*/ - { - set_query(CSET_STRING(query_arg, query_length_arg, charset())); - } - void set_query(const CSET_STRING &string_arg) - { - mysql_mutex_lock(&LOCK_thd_data); - set_query_inner(string_arg); - mysql_mutex_unlock(&LOCK_thd_data); - - PSI_CALL_set_thread_info(query(), query_length()); - } - void reset_query() /* Mutex protected */ - { set_query(CSET_STRING()); } - void set_query_and_id(char *query_arg, uint32 query_length_arg, - CHARSET_INFO *cs, query_id_t new_query_id); - void set_query_id(query_id_t new_query_id) - { - query_id= new_query_id; -#ifdef WITH_WSREP - if (WSREP_NNULL(this)) - { - set_wsrep_next_trx_id(query_id); - WSREP_DEBUG("assigned new next trx id: %" PRIu64, wsrep_next_trx_id()); - } -#endif /* WITH_WSREP */ - } - void set_open_tables(TABLE *open_tables_arg) - { - mysql_mutex_lock(&LOCK_thd_data); - open_tables= open_tables_arg; - mysql_mutex_unlock(&LOCK_thd_data); - } - void set_mysys_var(struct st_my_thread_var *new_mysys_var); - void enter_locked_tables_mode(enum_locked_tables_mode mode_arg) - { - DBUG_ASSERT(locked_tables_mode == LTM_NONE); - - if (mode_arg == LTM_LOCK_TABLES) - { - /* - When entering LOCK TABLES mode we should set explicit duration - for all metadata locks acquired so far in order to avoid releasing - them till UNLOCK TABLES statement. - We don't do this when entering prelocked mode since sub-statements - don't release metadata locks and restoring status-quo after leaving - prelocking mode gets complicated. - */ - mdl_context.set_explicit_duration_for_all_locks(); - } - - locked_tables_mode= mode_arg; - } - void leave_locked_tables_mode(); - int decide_logging_format(TABLE_LIST *tables); - /* - In Some cases when decide_logging_format is called it does not have all - information to decide the logging format. So that cases we call decide_logging_format_2 - at later stages in execution. - One example would be binlog format for IODKU but column with unique key is not inserted. - We don't have inserted columns info when we call decide_logging_format so on later stage we call - decide_logging_format_low - - @returns 0 if no format is changed - 1 if there is change in binlog format - */ - int decide_logging_format_low(TABLE *table); - - enum need_invoker { INVOKER_NONE=0, INVOKER_USER, INVOKER_ROLE}; - void binlog_invoker(bool role) { m_binlog_invoker= role ? INVOKER_ROLE : INVOKER_USER; } - enum need_invoker need_binlog_invoker() { return m_binlog_invoker; } - void get_definer(LEX_USER *definer, bool role); - void set_invoker(const LEX_CSTRING *user, const LEX_CSTRING *host) - { - invoker.user= *user; - invoker.host= *host; - } - LEX_CSTRING get_invoker_user() { return invoker.user; } - LEX_CSTRING get_invoker_host() { return invoker.host; } - bool has_invoker() { return invoker.user.length > 0; } - - void print_aborted_warning(uint threshold, const char *reason) - { - if (global_system_variables.log_warnings > threshold) - { - Security_context *sctx= &main_security_ctx; - sql_print_warning(ER_THD(this, ER_NEW_ABORTING_CONNECTION), - thread_id, (db.str ? db.str : "unconnected"), - sctx->user ? sctx->user : "unauthenticated", - sctx->host_or_ip, reason); - } - } - -public: - void clear_wakeup_ready() { wakeup_ready= false; } - /* - Sleep waiting for others to wake us up with signal_wakeup_ready(). - Must call clear_wakeup_ready() before waiting. - */ - void wait_for_wakeup_ready(); - /* Wake this thread up from wait_for_wakeup_ready(). */ - void signal_wakeup_ready(); - - void add_status_to_global() - { - DBUG_ASSERT(status_in_global == 0); - mysql_mutex_lock(&LOCK_status); - add_to_status(&global_status_var, &status_var); - /* Mark that this THD status has already been added in global status */ - status_var.global_memory_used= 0; - status_in_global= 1; - mysql_mutex_unlock(&LOCK_status); - } - - wait_for_commit *wait_for_commit_ptr; - int wait_for_prior_commit() - { - if (wait_for_commit_ptr) - return wait_for_commit_ptr->wait_for_prior_commit(this); - return 0; - } - void wakeup_subsequent_commits(int wakeup_error) - { - if (wait_for_commit_ptr) - wait_for_commit_ptr->wakeup_subsequent_commits(wakeup_error); - } - wait_for_commit *suspend_subsequent_commits() { - wait_for_commit *suspended= wait_for_commit_ptr; - wait_for_commit_ptr= NULL; - return suspended; - } - void resume_subsequent_commits(wait_for_commit *suspended) { - DBUG_ASSERT(!wait_for_commit_ptr); - wait_for_commit_ptr= suspended; - } - - void mark_transaction_to_rollback(bool all); - bool internal_transaction() { return transaction != &default_transaction; } -private: - - /** The current internal error handler for this thread, or NULL. */ - Internal_error_handler *m_internal_handler; - - /** - The lex to hold the parsed tree of conventional (non-prepared) queries. - Whereas for prepared and stored procedure statements we use an own lex - instance for each new query, for conventional statements we reuse - the same lex. (@see mysql_parse for details). - */ - LEX main_lex; - /** - This memory root is used for two purposes: - - for conventional queries, to allocate structures stored in main_lex - during parsing, and allocate runtime data (execution plan, etc.) - during execution. - - for prepared queries, only to allocate runtime data. The parsed - tree itself is reused between executions and thus is stored elsewhere. - */ - MEM_ROOT main_mem_root; - Diagnostics_area main_da; - Diagnostics_area *m_stmt_da; - - /** - It will be set if CURRENT_USER() or CURRENT_ROLE() is called in account - management statements or default definer is set in CREATE/ALTER SP, SF, - Event, TRIGGER or VIEW statements. - - Current user or role will be binlogged into Query_log_event if - m_binlog_invoker is not NONE; It will be stored into invoker_host and - invoker_user by SQL thread. - */ - enum need_invoker m_binlog_invoker; - - /** - It points to the invoker in the Query_log_event. - SQL thread use it as the default definer in CREATE/ALTER SP, SF, Event, - TRIGGER or VIEW statements or current user in account management - statements if it is not NULL. - */ - AUTHID invoker; - -public: - Session_tracker session_tracker; - /* - Flag, mutex and condition for a thread to wait for a signal from another - thread. - - Currently used to wait for group commit to complete, can also be used for - other purposes. - */ - bool wakeup_ready; - mysql_mutex_t LOCK_wakeup_ready; - mysql_cond_t COND_wakeup_ready; - /* - The GTID assigned to the last commit. If no GTID was assigned to any commit - so far, this is indicated by last_commit_gtid.seq_no == 0. - */ -private: - rpl_gtid m_last_commit_gtid; - -public: - rpl_gtid get_last_commit_gtid() { return m_last_commit_gtid; } - void set_last_commit_gtid(rpl_gtid >id); - - - LF_PINS *tdc_hash_pins; - LF_PINS *xid_hash_pins; - bool fix_xid_hash_pins(); - - const XID *get_xid() const - { -#ifdef WITH_WSREP - if (!wsrep_xid.is_null()) - return &wsrep_xid; -#endif /* WITH_WSREP */ - return (transaction->xid_state.is_explicit_XA() ? - transaction->xid_state.get_xid() : - &transaction->implicit_xid); - } - -/* Members related to temporary tables. */ -public: - /* Opened table states. */ - enum Temporary_table_state { - TMP_TABLE_IN_USE, - TMP_TABLE_NOT_IN_USE, - TMP_TABLE_ANY - }; - bool has_thd_temporary_tables(); - bool has_temporary_tables(); - - TABLE *create_and_open_tmp_table(LEX_CUSTRING *frm, - const char *path, - const char *db, - const char *table_name, - bool open_internal_tables); - - TABLE *find_temporary_table(const char *db, const char *table_name, - Temporary_table_state state= TMP_TABLE_IN_USE); - TABLE *find_temporary_table(const TABLE_LIST *tl, - Temporary_table_state state= TMP_TABLE_IN_USE); - - TMP_TABLE_SHARE *find_tmp_table_share_w_base_key(const char *key, - uint key_length); - TMP_TABLE_SHARE *find_tmp_table_share(const char *db, - const char *table_name); - TMP_TABLE_SHARE *find_tmp_table_share(const TABLE_LIST *tl); - TMP_TABLE_SHARE *find_tmp_table_share(const char *key, size_t key_length); - - bool open_temporary_table(TABLE_LIST *tl); - bool open_temporary_tables(TABLE_LIST *tl); - - bool close_temporary_tables(); - bool rename_temporary_table(TABLE *table, const LEX_CSTRING *db, - const LEX_CSTRING *table_name); - bool drop_temporary_table(TABLE *table, bool *is_trans, bool delete_table); - bool rm_temporary_table(handlerton *hton, const char *path); - void mark_tmp_tables_as_free_for_reuse(); - void mark_tmp_table_as_free_for_reuse(TABLE *table); - - TMP_TABLE_SHARE* save_tmp_table_share(TABLE *table); - void restore_tmp_table_share(TMP_TABLE_SHARE *share); - void close_unused_temporary_table_instances(const TABLE_LIST *tl); - -private: - /* Whether a lock has been acquired? */ - bool m_tmp_tables_locked; - - uint create_tmp_table_def_key(char *key, const char *db, - const char *table_name); - TMP_TABLE_SHARE *create_temporary_table(LEX_CUSTRING *frm, - const char *path, const char *db, - const char *table_name); - TABLE *find_temporary_table(const char *key, uint key_length, - Temporary_table_state state); - TABLE *open_temporary_table(TMP_TABLE_SHARE *share, const char *alias); - bool find_and_use_tmp_table(const TABLE_LIST *tl, TABLE **out_table); - bool use_temporary_table(TABLE *table, TABLE **out_table); - void close_temporary_table(TABLE *table); - bool log_events_and_free_tmp_shares(); - void free_tmp_table_share(TMP_TABLE_SHARE *share, bool delete_table); - void free_temporary_table(TABLE *table); - bool lock_temporary_tables(); - void unlock_temporary_tables(); - - inline uint tmpkeyval(TMP_TABLE_SHARE *share) - { - return uint4korr(share->table_cache_key.str + - share->table_cache_key.length - 4); - } - - inline TMP_TABLE_SHARE *tmp_table_share(TABLE *table) - { - DBUG_ASSERT(table->s->tmp_table); - return static_cast(table->s); - } - -public: -#ifdef HAVE_REPLICATION - /* - If we do a purge of binary logs, log index info of the threads - that are currently reading it needs to be adjusted. To do that - each thread that is using LOG_INFO needs to adjust the pointer to it - */ - LOG_INFO *current_linfo; - Slave_info *slave_info; - - void set_current_linfo(LOG_INFO *linfo); - void reset_current_linfo() { set_current_linfo(0); } - - int register_slave(uchar *packet, size_t packet_length); - void unregister_slave(); - bool is_binlog_dump_thread(); -#endif - - inline ulong wsrep_binlog_format() const - { - return WSREP_BINLOG_FORMAT(variables.binlog_format); - } - -#ifdef WITH_WSREP - bool wsrep_applier; /* dedicated slave applier thread */ - bool wsrep_applier_closing; /* applier marked to close */ - bool wsrep_client_thread; /* to identify client threads*/ - query_id_t wsrep_last_query_id; - XID wsrep_xid; - - /** This flag denotes that record locking should be skipped during INSERT - and gap locking during SELECT. Only used by the streaming replication thread - that only modifies the wsrep_schema.SR table. */ - my_bool wsrep_skip_locking; - - mysql_cond_t COND_wsrep_thd; - - // changed from wsrep_seqno_t to wsrep_trx_meta_t in wsrep API rev 75 - uint32 wsrep_rand; - rpl_group_info *wsrep_rgi; - bool wsrep_converted_lock_session; - char wsrep_info[128]; /* string for dynamic proc info */ - ulong wsrep_retry_counter; // of autocommit - bool wsrep_PA_safe; - char* wsrep_retry_query; - size_t wsrep_retry_query_len; - enum enum_server_command wsrep_retry_command; - enum wsrep_consistency_check_mode - wsrep_consistency_check; - std::vector wsrep_status_vars; - int wsrep_mysql_replicated; - const char* wsrep_TOI_pre_query; /* a query to apply before - the actual TOI query */ - size_t wsrep_TOI_pre_query_len; - wsrep_po_handle_t wsrep_po_handle; - size_t wsrep_po_cnt; - void *wsrep_apply_format; - uchar* wsrep_rbr_buf; - wsrep_gtid_t wsrep_sync_wait_gtid; - uint64 wsrep_last_written_gtid_seqno; - uint64 wsrep_current_gtid_seqno; - ulong wsrep_affected_rows; - bool wsrep_has_ignored_error; - - /* - When enabled, do not replicate/binlog updates from the current table that's - being processed. At the moment, it is used to keep mysql.gtid_slave_pos - table updates from being replicated to other nodes via galera replication. - */ - bool wsrep_ignore_table; - /* thread who has started kill for this THD protected by LOCK_thd_data*/ - my_thread_id wsrep_aborter; - - /* - Transaction id: - * m_wsrep_next_trx_id is assigned on the first query after - wsrep_next_trx_id() return WSREP_UNDEFINED_TRX_ID - * Each storage engine must assign value of wsrep_next_trx_id() - when the transaction starts. - * Effective transaction id is returned via wsrep_trx_id() - */ - /* - Return effective transaction id - */ - wsrep_trx_id_t wsrep_trx_id() const - { - return m_wsrep_client_state.transaction().id().get(); - } - - - /* - Set next trx id - */ - void set_wsrep_next_trx_id(query_id_t query_id) - { - m_wsrep_next_trx_id = (wsrep_trx_id_t) query_id; - } - /* - Return next trx id - */ - wsrep_trx_id_t wsrep_next_trx_id() const - { - return m_wsrep_next_trx_id; - } - -private: - wsrep_trx_id_t m_wsrep_next_trx_id; /* cast from query_id_t */ - /* wsrep-lib */ - Wsrep_mutex m_wsrep_mutex; - Wsrep_condition_variable m_wsrep_cond; - Wsrep_client_service m_wsrep_client_service; - Wsrep_client_state m_wsrep_client_state; - -public: - Wsrep_client_state& wsrep_cs() { return m_wsrep_client_state; } - const Wsrep_client_state& wsrep_cs() const { return m_wsrep_client_state; } - const wsrep::transaction& wsrep_trx() const - { return m_wsrep_client_state.transaction(); } - const wsrep::streaming_context& wsrep_sr() const - { return m_wsrep_client_state.transaction().streaming_context(); } - /* Pointer to applier service for streaming THDs. This is needed to - be able to delete applier service object in case of background - rollback. */ - Wsrep_applier_service* wsrep_applier_service; - /* wait_for_commit struct for binlog group commit */ - wait_for_commit wsrep_wfc; -#endif /* WITH_WSREP */ - - /* Handling of timeouts for commands */ - thr_timer_t query_timer; - -public: - void set_query_timer() - { -#ifndef EMBEDDED_LIBRARY - /* - Don't start a query timer if - - If timeouts are not set - - if we are in a stored procedure or sub statement - - If this is a slave thread - - If we already have set a timeout (happens when running prepared - statements that calls mysql_execute_command()) - */ - if (!variables.max_statement_time || spcont || in_sub_stmt || - slave_thread || query_timer.expired == 0) - return; - thr_timer_settime(&query_timer, variables.max_statement_time); -#endif - } - void reset_query_timer() - { -#ifndef EMBEDDED_LIBRARY - if (spcont || in_sub_stmt || slave_thread) - return; - if (!query_timer.expired) - thr_timer_end(&query_timer); -#endif - } - void restore_set_statement_var() - { - main_lex.restore_set_statement_var(); - } - /* Copy relevant `stmt` transaction flags to `all` transaction. */ - void merge_unsafe_rollback_flags() - { - if (transaction->stmt.modified_non_trans_table) - transaction->all.modified_non_trans_table= TRUE; - transaction->all.m_unsafe_rollback_flags|= - (transaction->stmt.m_unsafe_rollback_flags & - (THD_TRANS::DID_WAIT | THD_TRANS::CREATED_TEMP_TABLE | - THD_TRANS::DROPPED_TEMP_TABLE | THD_TRANS::DID_DDL)); - } - - - uint get_net_wait_timeout() - { - if (in_active_multi_stmt_transaction()) - { - if (transaction->all.is_trx_read_write()) - { - if (variables.idle_write_transaction_timeout > 0) - return variables.idle_write_transaction_timeout; - } - else - { - if (variables.idle_readonly_transaction_timeout > 0) - return variables.idle_readonly_transaction_timeout; - } - - if (variables.idle_transaction_timeout > 0) - return variables.idle_transaction_timeout; - } - - return variables.net_wait_timeout; - } - - /** - Switch to a sublex, to parse a substatement or an expression. - */ - void set_local_lex(sp_lex_local *sublex) - { - DBUG_ASSERT(lex->sphead); - lex= sublex; - /* Reset part of parser state which needs this. */ - m_parser_state->m_yacc.reset_before_substatement(); - } - - /** - Switch back from a sublex (currently pointed by this->lex) to the old lex. - Sublex is merged to "oldlex" and this->lex is set to "oldlex". - - This method is called after parsing a substatement or an expression. - set_local_lex() must be previously called. - @param oldlex - The old lex which was active before set_local_lex(). - @returns - false on success, true on error (failed to merge LEX's). - - See also sp_head::merge_lex(). - */ - bool restore_from_local_lex_to_old_lex(LEX *oldlex); - - Item *sp_fix_func_item(Item **it_addr); - Item *sp_prepare_func_item(Item **it_addr, uint cols= 1); - bool sp_eval_expr(Field *result_field, Item **expr_item_ptr); - -}; - - -/* - Start a new independent transaction for the THD. - The old one is stored in this object and restored when calling - restore_old_transaction() or when the object is freed -*/ - -class start_new_trans -{ - /* container for handler's private per-connection data */ - Ha_data old_ha_data[MAX_HA]; - struct THD::st_transactions *old_transaction, new_transaction; - Open_tables_backup open_tables_state_backup; - MDL_savepoint mdl_savepoint; - PSI_transaction_locker *m_transaction_psi; - THD *org_thd; - uint in_sub_stmt; - uint server_status; - my_bool wsrep_on; - -public: - start_new_trans(THD *thd); - ~start_new_trans() - { - destroy(); - } - void destroy() - { - if (org_thd) // Safety - restore_old_transaction(); - new_transaction.free(); - } - void restore_old_transaction(); -}; - -/** A short cut for thd->get_stmt_da()->set_ok_status(). */ - -inline void -my_ok(THD *thd, ulonglong affected_rows_arg= 0, ulonglong id= 0, - const char *message= NULL) -{ - thd->set_row_count_func(affected_rows_arg); - thd->set_affected_rows(affected_rows_arg); - thd->get_stmt_da()->set_ok_status(affected_rows_arg, id, message); -} - - -/** A short cut for thd->get_stmt_da()->set_eof_status(). */ - -inline void -my_eof(THD *thd) -{ - thd->set_row_count_func(-1); - thd->get_stmt_da()->set_eof_status(thd); - - TRANSACT_TRACKER(add_trx_state(thd, TX_RESULT_SET)); -} - -#define tmp_disable_binlog(A) \ - {ulonglong tmp_disable_binlog__save_options= (A)->variables.option_bits; \ - (A)->variables.option_bits&= ~OPTION_BIN_LOG; \ - (A)->variables.option_bits|= OPTION_BIN_TMP_LOG_OFF; - -#define reenable_binlog(A) \ - (A)->variables.option_bits= tmp_disable_binlog__save_options; } - - -inline date_conv_mode_t sql_mode_for_dates(THD *thd) -{ - static_assert((date_conv_mode_t::KNOWN_MODES & - time_round_mode_t::KNOWN_MODES) == 0, - "date_conv_mode_t and time_round_mode_t must use different " - "bit values"); - static_assert(MODE_NO_ZERO_DATE == date_mode_t::NO_ZERO_DATE && - MODE_NO_ZERO_IN_DATE == date_mode_t::NO_ZERO_IN_DATE && - MODE_INVALID_DATES == date_mode_t::INVALID_DATES, - "sql_mode_t and date_mode_t values must be equal"); - return date_conv_mode_t(thd->variables.sql_mode & - (MODE_NO_ZERO_DATE | MODE_NO_ZERO_IN_DATE | MODE_INVALID_DATES)); -} - -/* - Used to hold information about file and file structure in exchange - via non-DB file (...INTO OUTFILE..., ...LOAD DATA...) - XXX: We never call destructor for objects of this class. -*/ - -class sql_exchange :public Sql_alloc -{ -public: - enum enum_filetype filetype; /* load XML, Added by Arnold & Erik */ - const char *file_name; - String *field_term,*enclosed,*line_term,*line_start,*escaped; - bool opt_enclosed; - bool dumpfile; - ulong skip_lines; - CHARSET_INFO *cs; - sql_exchange(const char *name, bool dumpfile_flag, - enum_filetype filetype_arg= FILETYPE_CSV); - bool escaped_given(void) const; -}; - -/* - This is used to get result from a select -*/ - -class JOIN; - -/* Pure interface for sending tabular data */ -class select_result_sink: public Sql_alloc -{ -public: - THD *thd; - select_result_sink(THD *thd_arg): thd(thd_arg) {} - inline int send_data_with_check(List &items, - SELECT_LEX_UNIT *u, - ha_rows sent) - { - if (u->lim.check_offset(sent)) - return 0; - - if (u->thd->killed == ABORT_QUERY) - return 0; - - return send_data(items); - } - /* - send_data returns 0 on ok, 1 on error and -1 if data was ignored, for - example for a duplicate row entry written to a temp table. - */ - virtual int send_data(List &items)=0; - virtual ~select_result_sink() {}; - void reset(THD *thd_arg) { thd= thd_arg; } -}; - -class select_result_interceptor; - -/* - Interface for sending tabular data, together with some other stuff: - - - Primary purpose seems to be seding typed tabular data: - = the DDL is sent with send_fields() - = the rows are sent with send_data() - Besides that, - - there seems to be an assumption that the sent data is a result of - SELECT_LEX_UNIT *unit, - - nest_level is used by SQL parser -*/ - -class select_result :public select_result_sink -{ -protected: - /* - All descendant classes have their send_data() skip the first - unit->offset_limit_cnt rows sent. Select_materialize - also uses unit->get_column_types(). - */ - SELECT_LEX_UNIT *unit; - /* Something used only by the parser: */ -public: - ha_rows est_records; /* estimated number of records in the result */ - select_result(THD *thd_arg): select_result_sink(thd_arg), est_records(0) {} - void set_unit(SELECT_LEX_UNIT *unit_arg) { unit= unit_arg; } - virtual ~select_result() {}; - /** - Change wrapped select_result. - - Replace the wrapped result object with new_result and call - prepare() and prepare2() on new_result. - - This base class implementation doesn't wrap other select_results. - - @param new_result The new result object to wrap around - - @retval false Success - @retval true Error - */ - virtual bool change_result(select_result *new_result) - { - return false; - } - virtual int prepare(List &list, SELECT_LEX_UNIT *u) - { - unit= u; - return 0; - } - virtual int prepare2(JOIN *join) { return 0; } - /* - Because of peculiarities of prepared statements protocol - we need to know number of columns in the result set (if - there is a result set) apart from sending columns metadata. - */ - virtual uint field_count(List &fields) const - { return fields.elements; } - virtual bool send_result_set_metadata(List &list, uint flags)=0; - virtual bool initialize_tables (JOIN *join) { return 0; } - virtual bool send_eof()=0; - /** - Check if this query returns a result set and therefore is allowed in - cursors and set an error message if it is not the case. - - @retval FALSE success - @retval TRUE error, an error message is set - */ - virtual bool check_simple_select() const; - virtual void abort_result_set() {} - /* - Cleanup instance of this class for next execution of a prepared - statement/stored procedure. - */ - virtual void cleanup(); - void set_thd(THD *thd_arg) { thd= thd_arg; } - void reset(THD *thd_arg) - { - select_result_sink::reset(thd_arg); - unit= NULL; - } -#ifdef EMBEDDED_LIBRARY - virtual void begin_dataset() {} -#else - void begin_dataset() {} -#endif - virtual void update_used_tables() {} - - /* this method is called just before the first row of the table can be read */ - virtual void prepare_to_read_rows() {} - - void remove_offset_limit() - { - unit->lim.remove_offset(); - } - - /* - This returns - - NULL if the class sends output row to the client - - this if the output is set elsewhere (a file, @variable, or table). - */ - virtual select_result_interceptor *result_interceptor()=0; - - /* - This method is used to distinguish an normal SELECT from the cursor - structure discovery for cursor%ROWTYPE routine variables. - If this method returns "true", then a SELECT execution performs only - all preparation stages, but does not fetch any rows. - */ - virtual bool view_structure_only() const { return false; } -}; - - -/* - This is a select_result_sink which simply writes all data into a (temporary) - table. Creation/deletion of the table is outside of the scope of the class - - It is aimed at capturing SHOW EXPLAIN output, so: - - Unlike select_result class, we don't assume that the sent data is an - output of a SELECT_LEX_UNIT (and so we don't apply "LIMIT x,y" from the - unit) - - We don't try to convert the target table to MyISAM -*/ - -class select_result_explain_buffer : public select_result_sink -{ -public: - select_result_explain_buffer(THD *thd_arg, TABLE *table_arg) : - select_result_sink(thd_arg), dst_table(table_arg) {}; - - TABLE *dst_table; /* table to write into */ - - /* The following is called in the child thread: */ - int send_data(List &items); -}; - - -/* - This is a select_result_sink which stores the data in text form. - - It is only used to save EXPLAIN output. -*/ - -class select_result_text_buffer : public select_result_sink -{ -public: - select_result_text_buffer(THD *thd_arg): select_result_sink(thd_arg) {} - int send_data(List &items); - bool send_result_set_metadata(List &fields, uint flag); - - void save_to(String *res); -private: - int append_row(List &items, bool send_names); - - List rows; - int n_columns; -}; - - -/* - Base class for select_result descendands which intercept and - transform result set rows. As the rows are not sent to the client, - sending of result set metadata should be suppressed as well. -*/ - -class select_result_interceptor: public select_result -{ -public: - select_result_interceptor(THD *thd_arg): - select_result(thd_arg), suppress_my_ok(false) - { - DBUG_ENTER("select_result_interceptor::select_result_interceptor"); - DBUG_PRINT("enter", ("this %p", this)); - DBUG_VOID_RETURN; - } /* Remove gcc warning */ - uint field_count(List &fields) const { return 0; } - bool send_result_set_metadata(List &fields, uint flag) { return FALSE; } - select_result_interceptor *result_interceptor() { return this; } - - /* - Instruct the object to not call my_ok(). Client output will be handled - elsewhere. (this is used by ANALYZE $stmt feature). - */ - void disable_my_ok_calls() { suppress_my_ok= true; } - void reset(THD *thd_arg) - { - select_result::reset(thd_arg); - suppress_my_ok= false; - } -protected: - bool suppress_my_ok; -}; - - -class sp_cursor_statistics -{ -protected: - ulonglong m_fetch_count; // Number of FETCH commands since last OPEN - ulonglong m_row_count; // Number of successful FETCH since last OPEN - bool m_found; // If last FETCH fetched a row -public: - sp_cursor_statistics() - :m_fetch_count(0), - m_row_count(0), - m_found(false) - { } - bool found() const - { return m_found; } - - ulonglong row_count() const - { return m_row_count; } - - ulonglong fetch_count() const - { return m_fetch_count; } - void reset() { *this= sp_cursor_statistics(); } -}; - - -/* A mediator between stored procedures and server side cursors */ -class sp_lex_keeper; -class sp_cursor: public sp_cursor_statistics -{ -private: - /// An interceptor of cursor result set used to implement - /// FETCH INTO . - class Select_fetch_into_spvars: public select_result_interceptor - { - List *spvar_list; - uint field_count; - bool m_view_structure_only; - bool send_data_to_variable_list(List &vars, List &items); - public: - Select_fetch_into_spvars(THD *thd_arg, bool view_structure_only) - :select_result_interceptor(thd_arg), - m_view_structure_only(view_structure_only) - {} - void reset(THD *thd_arg) - { - select_result_interceptor::reset(thd_arg); - spvar_list= NULL; - field_count= 0; - } - uint get_field_count() { return field_count; } - void set_spvar_list(List *vars) { spvar_list= vars; } - - virtual bool send_eof() { return FALSE; } - virtual int send_data(List &items); - virtual int prepare(List &list, SELECT_LEX_UNIT *u); - virtual bool view_structure_only() const { return m_view_structure_only; } -}; - -public: - sp_cursor() - :result(NULL, false), - m_lex_keeper(NULL), - server_side_cursor(NULL) - { } - sp_cursor(THD *thd_arg, sp_lex_keeper *lex_keeper, bool view_structure_only) - :result(thd_arg, view_structure_only), - m_lex_keeper(lex_keeper), - server_side_cursor(NULL) - {} - - virtual ~sp_cursor() - { destroy(); } - - sp_lex_keeper *get_lex_keeper() { return m_lex_keeper; } - - int open(THD *thd); - - int close(THD *thd); - - my_bool is_open() - { return MY_TEST(server_side_cursor); } - - int fetch(THD *, List *vars, bool error_on_no_data); - - bool export_structure(THD *thd, Row_definition_list *list); - - void reset(THD *thd_arg, sp_lex_keeper *lex_keeper) - { - sp_cursor_statistics::reset(); - result.reset(thd_arg); - m_lex_keeper= lex_keeper; - server_side_cursor= NULL; - } - -private: - Select_fetch_into_spvars result; - sp_lex_keeper *m_lex_keeper; - Server_side_cursor *server_side_cursor; - void destroy(); -}; - - -class select_send :public select_result { - /** - True if we have sent result set metadata to the client. - In this case the client always expects us to end the result - set with an eof or error packet - */ - bool is_result_set_started; -public: - select_send(THD *thd_arg): - select_result(thd_arg), is_result_set_started(FALSE) {} - bool send_result_set_metadata(List &list, uint flags); - int send_data(List &items); - bool send_eof(); - virtual bool check_simple_select() const { return FALSE; } - void abort_result_set(); - virtual void cleanup(); - select_result_interceptor *result_interceptor() { return NULL; } -}; - - -/* - We need this class, because select_send::send_eof() will call ::my_eof. - - See also class Protocol_discard. -*/ - -class select_send_analyze : public select_send -{ - bool send_result_set_metadata(List &list, uint flags) { return 0; } - bool send_eof() { return 0; } - void abort_result_set() {} -public: - select_send_analyze(THD *thd_arg): select_send(thd_arg) {} -}; - - -class select_to_file :public select_result_interceptor { -protected: - sql_exchange *exchange; - File file; - IO_CACHE cache; - ha_rows row_count; - char path[FN_REFLEN]; - -public: - select_to_file(THD *thd_arg, sql_exchange *ex): - select_result_interceptor(thd_arg), exchange(ex), file(-1),row_count(0L) - { path[0]=0; } - ~select_to_file(); - bool send_eof(); - void cleanup(); -}; - - -#define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape - - -/* - List of all possible characters of a numeric value text representation. -*/ -#define NUMERIC_CHARS ".0123456789e+-" - - -class select_export :public select_to_file { - uint field_term_length; - int field_sep_char,escape_char,line_sep_char; - int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT - /* - The is_ambiguous_field_sep field is true if a value of the field_sep_char - field is one of the 'n', 't', 'r' etc characters - (see the READ_INFO::unescape method and the ESCAPE_CHARS constant value). - */ - bool is_ambiguous_field_sep; - /* - The is_ambiguous_field_term is true if field_sep_char contains the first - char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can - contain this character. - */ - bool is_ambiguous_field_term; - /* - The is_unsafe_field_sep field is true if a value of the field_sep_char - field is one of the '0'..'9', '+', '-', '.' and 'e' characters - (see the NUMERIC_CHARS constant value). - */ - bool is_unsafe_field_sep; - bool fixed_row_size; - CHARSET_INFO *write_cs; // output charset -public: - select_export(THD *thd_arg, sql_exchange *ex): select_to_file(thd_arg, ex) {} - ~select_export(); - int prepare(List &list, SELECT_LEX_UNIT *u); - int send_data(List &items); -}; - - -class select_dump :public select_to_file { -public: - select_dump(THD *thd_arg, sql_exchange *ex): select_to_file(thd_arg, ex) {} - int prepare(List &list, SELECT_LEX_UNIT *u); - int send_data(List &items); -}; - - -class select_insert :public select_result_interceptor { - public: - select_result *sel_result; - TABLE_LIST *table_list; - TABLE *table; - List *fields; - ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not - COPY_INFO info; - bool insert_into_view; - select_insert(THD *thd_arg, TABLE_LIST *table_list_par, TABLE *table_par, - List *fields_par, List *update_fields, - List *update_values, enum_duplicates duplic, - bool ignore, select_result *sel_ret_list); - ~select_insert(); - int prepare(List &list, SELECT_LEX_UNIT *u); - virtual int prepare2(JOIN *join); - virtual int send_data(List &items); - virtual void store_values(List &values); - virtual bool can_rollback_data() { return 0; } - bool prepare_eof(); - bool send_ok_packet(); - bool send_eof(); - virtual void abort_result_set(); - /* not implemented: select_insert is never re-used in prepared statements */ - void cleanup(); -}; - - -class select_create: public select_insert { - TABLE_LIST *create_table; - Table_specification_st *create_info; - TABLE_LIST *select_tables; - Alter_info *alter_info; - Field **field; - /* lock data for tmp table */ - MYSQL_LOCK *m_lock; - /* m_lock or thd->extra_lock */ - MYSQL_LOCK **m_plock; - bool exit_done; - TMP_TABLE_SHARE *saved_tmp_table_share; - -public: - select_create(THD *thd_arg, TABLE_LIST *table_arg, - Table_specification_st *create_info_par, - Alter_info *alter_info_arg, - List &select_fields,enum_duplicates duplic, bool ignore, - TABLE_LIST *select_tables_arg): - select_insert(thd_arg, table_arg, NULL, &select_fields, 0, 0, duplic, - ignore, NULL), - create_table(table_arg), - create_info(create_info_par), - select_tables(select_tables_arg), - alter_info(alter_info_arg), - m_plock(NULL), exit_done(0), - saved_tmp_table_share(0) - {} - int prepare(List &list, SELECT_LEX_UNIT *u); - - void store_values(List &values); - bool send_eof(); - virtual void abort_result_set(); - virtual bool can_rollback_data() { return 1; } - - // Needed for access from local class MY_HOOKS in prepare(), since thd is proteted. - const THD *get_thd(void) { return thd; } - const HA_CREATE_INFO *get_create_info() { return create_info; }; - int prepare2(JOIN *join) { return 0; } - -private: - TABLE *create_table_from_items(THD *thd, - List *items, - MYSQL_LOCK **lock, - TABLEOP_HOOKS *hooks); -}; - -#include - -#ifdef WITH_ARIA_STORAGE_ENGINE -#include -#else -#undef USE_ARIA_FOR_TMP_TABLES -#endif - -#ifdef USE_ARIA_FOR_TMP_TABLES -#define TMP_ENGINE_COLUMNDEF MARIA_COLUMNDEF -#define TMP_ENGINE_HTON maria_hton -#define TMP_ENGINE_NAME "Aria" -inline uint tmp_table_max_key_length() { return maria_max_key_length(); } -inline uint tmp_table_max_key_parts() { return maria_max_key_segments(); } -#else -#define TMP_ENGINE_COLUMNDEF MI_COLUMNDEF -#define TMP_ENGINE_HTON myisam_hton -#define TMP_ENGINE_NAME "MyISAM" -inline uint tmp_table_max_key_length() { return MI_MAX_KEY_LENGTH; } -inline uint tmp_table_max_key_parts() { return MI_MAX_KEY_SEG; } -#endif - -/* - Param to create temporary tables when doing SELECT:s - NOTE - This structure is copied using memcpy as a part of JOIN. -*/ - -class TMP_TABLE_PARAM :public Sql_alloc -{ -public: - List copy_funcs; - Copy_field *copy_field, *copy_field_end; - uchar *group_buff; - Item **items_to_copy; /* Fields in tmp table */ - TMP_ENGINE_COLUMNDEF *recinfo, *start_recinfo; - KEY *keyinfo; - ha_rows end_write_records; - /** - Number of normal fields in the query, including those referred to - from aggregate functions. Hence, "SELECT `field1`, - SUM(`field2`) from t1" sets this counter to 2. - - @see count_field_types - */ - uint field_count; - /** - Number of fields in the query that have functions. Includes both - aggregate functions (e.g., SUM) and non-aggregates (e.g., RAND). - Also counts functions referred to from aggregate functions, i.e., - "SELECT SUM(RAND())" sets this counter to 2. - - @see count_field_types - */ - uint func_count; - /** - Number of fields in the query that have aggregate functions. Note - that the optimizer may choose to optimize away these fields by - replacing them with constants, in which case sum_func_count will - need to be updated. - - @see opt_sum_query, count_field_types - */ - uint sum_func_count; - uint hidden_field_count; - uint group_parts,group_length,group_null_parts; - uint quick_group; - /** - Enabled when we have atleast one outer_sum_func. Needed when used - along with distinct. - - @see create_tmp_table - */ - bool using_outer_summary_function; - CHARSET_INFO *table_charset; - bool schema_table; - /* TRUE if the temp table is created for subquery materialization. */ - bool materialized_subquery; - /* TRUE if all columns of the table are guaranteed to be non-nullable */ - bool force_not_null_cols; - /* - True if GROUP BY and its aggregate functions are already computed - by a table access method (e.g. by loose index scan). In this case - query execution should not perform aggregation and should treat - aggregate functions as normal functions. - */ - bool precomputed_group_by; - bool force_copy_fields; - /* - If TRUE, create_tmp_field called from create_tmp_table will convert - all BIT fields to 64-bit longs. This is a workaround the limitation - that MEMORY tables cannot index BIT columns. - */ - bool bit_fields_as_long; - /* - Whether to create or postpone actual creation of this temporary table. - TRUE <=> create_tmp_table will create only the TABLE structure. - */ - bool skip_create_table; - - TMP_TABLE_PARAM() - :copy_field(0), group_parts(0), - group_length(0), group_null_parts(0), - using_outer_summary_function(0), - schema_table(0), materialized_subquery(0), force_not_null_cols(0), - precomputed_group_by(0), - force_copy_fields(0), bit_fields_as_long(0), skip_create_table(0) - {} - ~TMP_TABLE_PARAM() - { - cleanup(); - } - void init(void); - inline void cleanup(void) - { - if (copy_field) /* Fix for Intel compiler */ - { - delete [] copy_field; - copy_field= NULL; - copy_field_end= NULL; - } - } -}; - - -class select_unit :public select_result_interceptor -{ -protected: - uint curr_step, prev_step, curr_sel; - enum sub_select_type step; -public: - TMP_TABLE_PARAM tmp_table_param; - /* Number of additional (hidden) field of the used temporary table */ - int addon_cnt; - int write_err; /* Error code from the last send_data->ha_write_row call. */ - TABLE *table; - - select_unit(THD *thd_arg): - select_result_interceptor(thd_arg), addon_cnt(0), table(0) - { - init(); - tmp_table_param.init(); - } - int prepare(List &list, SELECT_LEX_UNIT *u); - /** - Do prepare() and prepare2() if they have been postponed until - column type information is computed (used by select_union_direct). - - @param types Column types - - @return false on success, true on failure - */ - virtual bool postponed_prepare(List &types) - { return false; } - int send_data(List &items); - int write_record(); - int update_counter(Field *counter, longlong value); - int delete_record(); - bool send_eof(); - virtual bool flush(); - void cleanup(); - virtual bool create_result_table(THD *thd, List *column_types, - bool is_distinct, ulonglong options, - const LEX_CSTRING *alias, - bool bit_fields_as_long, - bool create_table, - bool keep_row_order, - uint hidden); - TMP_TABLE_PARAM *get_tmp_table_param() { return &tmp_table_param; } - void init() - { - curr_step= prev_step= 0; - curr_sel= UINT_MAX; - step= UNION_TYPE; - write_err= 0; - } - virtual void change_select(); - virtual bool force_enable_index_if_needed() { return false; } -}; - - -/** - @class select_unit_ext - - The class used when processing rows produced by operands of query expressions - containing INTERSECT ALL and/or EXCEPT all operations. One or two extra fields - of the temporary to store the rows of the partial and final result can be employed. - Both of them contain counters. The second additional field is used only when - the processed query expression contains INTERSECT ALL. - - Consider how these extra fields are used. - - Let - table t1 (f char(8)) - table t2 (f char(8)) - table t3 (f char(8)) - contain the following sets: - ("b"),("a"),("d"),("c"),("b"),("a"),("c"),("a") - ("c"),("b"),("c"),("c"),("a"),("b"),("g") - ("c"),("a"),("b"),("d"),("b"),("e") - - - Let's demonstrate how the the set operation INTERSECT ALL is proceesed - for the query - SELECT f FROM t1 INTERSECT ALL SELECT f FROM t2 - - When send_data() is called for the rows of the first operand we put - the processed record into the temporary table if there was no such record - setting dup_cnt field to 1 and add_cnt field to 0 and increment the - counter in the dup_cnt field by one otherwise. We get - - |add_cnt|dup_cnt| f | - |0 |2 |b | - |0 |3 |a | - |0 |1 |d | - |0 |2 |c | - - The call of send_eof() for the first operand swaps the values stored in - dup_cnt and add_cnt. After this, we'll see the following rows in the - temporary table - - |add_cnt|dup_cnt| f | - |2 |0 |b | - |3 |0 |a | - |1 |0 |d | - |2 |0 |c | - - When send_data() is called for the rows of the second operand we increment - the counter in dup_cnt if the processed row is found in the table and do - nothing otherwise. As a result we get - - |add_cnt|dup_cnt| f | - |2 |2 |b | - |3 |1 |a | - |1 |0 |d | - |2 |3 |c | - - At the call of send_eof() for the second operand first we disable index. - Then for each record, the minimum of counters from dup_cnt and add_cnt m is - taken. If m == 0 then the record is deleted. Otherwise record is replaced - with m copies of it. Yet the counter in this copies are set to 1 for - dup_cnt and to 0 for add_cnt - - |add_cnt|dup_cnt| f | - |0 |1 |b | - |0 |1 |b | - |0 |1 |a | - |0 |1 |c | - |0 |1 |c | - - - Let's demonstrate how the the set operation EXCEPT ALL is proceesed - for the query - SELECT f FROM t1 EXCEPT ALL SELECT f FROM t3 - - Only one additional counter field dup_cnt is used for EXCEPT ALL. - After the first operand has been processed we have in the temporary table - - |dup_cnt| f | - |2 |b | - |3 |a | - |1 |d | - |2 |c | - - When send_data() is called for the rows of the second operand we decrement - the counter in dup_cnt if the processed row is found in the table and do - nothing otherwise. If the counter becomes 0 we delete the record - - |dup_cnt| f | - |2 |a | - |1 |c | - - Finally at the call of send_eof() for the second operand we disable index - unfold rows adding duplicates - - |dup_cnt| f | - |1 |a | - |1 |a | - |1 |c | - */ - -class select_unit_ext :public select_unit -{ -public: - select_unit_ext(THD *thd_arg): - select_unit(thd_arg), increment(0), is_index_enabled(TRUE), - curr_op_type(UNSPECIFIED) - { - }; - int send_data(List &items); - void change_select(); - int unfold_record(ha_rows cnt); - bool send_eof(); - bool force_enable_index_if_needed() - { - is_index_enabled= true; - return true; - } - bool disable_index_if_needed(SELECT_LEX *curr_sl); - - /* - How to change increment/decrement the counter in duplicate_cnt field - when processing a record produced by the current operand in send_data(). - The value can be 1 or -1 - */ - int increment; - /* TRUE <=> the index of the result temporary table is enabled */ - bool is_index_enabled; - /* The type of the set operation currently executed */ - enum set_op_type curr_op_type; - /* - Points to the extra field of the temporary table where - duplicate counters are stored - */ - Field *duplicate_cnt; - /* - Points to the extra field of the temporary table where additional - counters used only for INTERSECT ALL operations are stored - */ - Field *additional_cnt; -}; - -class select_union_recursive :public select_unit -{ - public: - /* The temporary table with the new records generated by one iterative step */ - TABLE *incr_table; - /* One of tables from the list rec_tables (determined dynamically) */ - TABLE *first_rec_table_to_update; - /* The temporary tables used for recursive table references */ - List
rec_tables; - /* - The count of how many times cleanup() was called with cleaned==false - for the unit specifying the recursive CTE for which this object was created - or for the unit specifying a CTE that mutually recursive with this CTE. - */ - uint cleanup_count; - - select_union_recursive(THD *thd_arg): - select_unit(thd_arg), - incr_table(0), first_rec_table_to_update(0), cleanup_count(0) {}; - - int send_data(List &items); - bool create_result_table(THD *thd, List *column_types, - bool is_distinct, ulonglong options, - const LEX_CSTRING *alias, - bool bit_fields_as_long, - bool create_table, - bool keep_row_order, - uint hidden); - void cleanup(); -}; - -/** - UNION result that is passed directly to the receiving select_result - without filling a temporary table. - - Function calls are forwarded to the wrapped select_result, but some - functions are expected to be called only once for each query, so - they are only executed for the first SELECT in the union (execept - for send_eof(), which is executed only for the last SELECT). - - This select_result is used when a UNION is not DISTINCT and doesn't - have a global ORDER BY clause. @see st_select_lex_unit::prepare(). -*/ - -class select_union_direct :public select_unit -{ -private: - /* Result object that receives all rows */ - select_result *result; - /* The last SELECT_LEX of the union */ - SELECT_LEX *last_select_lex; - - /* Wrapped result has received metadata */ - bool done_send_result_set_metadata; - /* Wrapped result has initialized tables */ - bool done_initialize_tables; - - /* Accumulated limit_found_rows */ - ulonglong limit_found_rows; - - /* Number of rows offset */ - ha_rows offset; - /* Number of rows limit + offset, @see select_union_direct::send_data() */ - ha_rows limit; - -public: - /* Number of rows in the union */ - ha_rows send_records; - select_union_direct(THD *thd_arg, select_result *result_arg, - SELECT_LEX *last_select_lex_arg): - select_unit(thd_arg), result(result_arg), - last_select_lex(last_select_lex_arg), - done_send_result_set_metadata(false), done_initialize_tables(false), - limit_found_rows(0) - { send_records= 0; } - bool change_result(select_result *new_result); - uint field_count(List &fields) const - { - // Only called for top-level select_results, usually select_send - DBUG_ASSERT(false); /* purecov: inspected */ - return 0; /* purecov: inspected */ - } - bool postponed_prepare(List &types); - bool send_result_set_metadata(List &list, uint flags); - int send_data(List &items); - bool initialize_tables (JOIN *join); - bool send_eof(); - bool flush() { return false; } - bool check_simple_select() const - { - /* Only called for top-level select_results, usually select_send */ - DBUG_ASSERT(false); /* purecov: inspected */ - return false; /* purecov: inspected */ - } - void abort_result_set() - { - result->abort_result_set(); /* purecov: inspected */ - } - void cleanup() - { - send_records= 0; - } - void set_thd(THD *thd_arg) - { - /* - Only called for top-level select_results, usually select_send, - and for the results of subquery engines - (select__subselect). - */ - DBUG_ASSERT(false); /* purecov: inspected */ - } - void remove_offset_limit() - { - // EXPLAIN should never output to a select_union_direct - DBUG_ASSERT(false); /* purecov: inspected */ - } - void begin_dataset() - { - // Only called for sp_cursor::Select_fetch_into_spvars - DBUG_ASSERT(false); /* purecov: inspected */ - } -}; - - -/* Base subselect interface class */ -class select_subselect :public select_result_interceptor -{ -protected: - Item_subselect *item; -public: - select_subselect(THD *thd_arg, Item_subselect *item_arg): - select_result_interceptor(thd_arg), item(item_arg) {} - int send_data(List &items)=0; - bool send_eof() { return 0; }; -}; - -/* Single value subselect interface class */ -class select_singlerow_subselect :public select_subselect -{ -public: - select_singlerow_subselect(THD *thd_arg, Item_subselect *item_arg): - select_subselect(thd_arg, item_arg) - {} - int send_data(List &items); -}; - - -/* - This class specializes select_union to collect statistics about the - data stored in the temp table. Currently the class collects statistcs - about NULLs. -*/ - -class select_materialize_with_stats : public select_unit -{ -protected: - class Column_statistics - { - public: - /* Count of NULLs per column. */ - ha_rows null_count; - /* The row number that contains the first NULL in a column. */ - ha_rows min_null_row; - /* The row number that contains the last NULL in a column. */ - ha_rows max_null_row; - }; - - /* Array of statistics data per column. */ - Column_statistics* col_stat; - - /* - The number of columns in the biggest sub-row that consists of only - NULL values. - */ - uint max_nulls_in_row; - /* - Count of rows writtent to the temp table. This is redundant as it is - already stored in handler::stats.records, however that one is relatively - expensive to compute (given we need that for evry row). - */ - ha_rows count_rows; - -protected: - void reset(); - -public: - select_materialize_with_stats(THD *thd_arg): select_unit(thd_arg) - { tmp_table_param.init(); } - bool create_result_table(THD *thd, List *column_types, - bool is_distinct, ulonglong options, - const LEX_CSTRING *alias, - bool bit_fields_as_long, - bool create_table, - bool keep_row_order, - uint hidden); - bool init_result_table(ulonglong select_options); - int send_data(List &items); - void cleanup(); - ha_rows get_null_count_of_col(uint idx) - { - DBUG_ASSERT(idx < table->s->fields); - return col_stat[idx].null_count; - } - ha_rows get_max_null_of_col(uint idx) - { - DBUG_ASSERT(idx < table->s->fields); - return col_stat[idx].max_null_row; - } - ha_rows get_min_null_of_col(uint idx) - { - DBUG_ASSERT(idx < table->s->fields); - return col_stat[idx].min_null_row; - } - uint get_max_nulls_in_row() { return max_nulls_in_row; } -}; - - -/* used in independent ALL/ANY optimisation */ -class select_max_min_finder_subselect :public select_subselect -{ - Item_cache *cache; - bool (select_max_min_finder_subselect::*op)(); - bool fmax; - bool is_all; -public: - select_max_min_finder_subselect(THD *thd_arg, Item_subselect *item_arg, - bool mx, bool all): - select_subselect(thd_arg, item_arg), cache(0), fmax(mx), is_all(all) - {} - void cleanup(); - int send_data(List &items); - bool cmp_real(); - bool cmp_int(); - bool cmp_decimal(); - bool cmp_str(); -}; - -/* EXISTS subselect interface class */ -class select_exists_subselect :public select_subselect -{ -public: - select_exists_subselect(THD *thd_arg, Item_subselect *item_arg): - select_subselect(thd_arg, item_arg) {} - int send_data(List &items); -}; - - -/* - Optimizer and executor structure for the materialized semi-join info. This - structure contains - - The sj-materialization temporary table - - Members needed to make index lookup or a full scan of the temptable. -*/ -class SJ_MATERIALIZATION_INFO : public Sql_alloc -{ -public: - /* Optimal join sub-order */ - struct st_position *positions; - - uint tables; /* Number of tables in the sj-nest */ - - /* Number of rows in the materialized table, before the de-duplication */ - double rows_with_duplicates; - - /* Expected #rows in the materialized table, after de-duplication */ - double rows; - - /* - Cost to materialize - execute the sub-join and write rows into temp.table - */ - Cost_estimate materialization_cost; - - /* Cost to make one lookup in the temptable */ - Cost_estimate lookup_cost; - - /* Cost of scanning the materialized table */ - Cost_estimate scan_cost; - - /* --- Execution structures ---------- */ - - /* - TRUE <=> This structure is used for execution. We don't necessarily pick - sj-materialization, so some of SJ_MATERIALIZATION_INFO structures are not - used by materialization - */ - bool is_used; - - bool materialized; /* TRUE <=> materialization already performed */ - /* - TRUE - the temptable is read with full scan - FALSE - we use the temptable for index lookups - */ - bool is_sj_scan; - - /* The temptable and its related info */ - TMP_TABLE_PARAM sjm_table_param; - List sjm_table_cols; - TABLE *table; - - /* Structure used to make index lookups */ - struct st_table_ref *tab_ref; - Item *in_equality; /* See create_subq_in_equalities() */ - - Item *join_cond; /* See comments in make_join_select() */ - Copy_field *copy_field; /* Needed for SJ_Materialization scan */ -}; - - -/* Structs used when sorting */ -struct SORT_FIELD_ATTR -{ - /* - If using mem-comparable fixed-size keys: - length of the mem-comparable image of the field, in bytes. - - If using packed keys: still the same? Not clear what is the use of it. - */ - uint length; - - /* - For most datatypes, this is 0. - The exception are the VARBINARY columns. - For those columns, the comparison actually compares - - (value_prefix(N), suffix=length(value)) - - Here value_prefix is either the whole value or its prefix if it was too - long, and the suffix is the length of the original value. - (this way, for values X and Y: if X=prefix(Y) then X compares as less - than Y - */ - uint suffix_length; - - /* - If using packed keys, number of bytes that are used to store the length - of the packed key. - - */ - uint length_bytes; - - /* Max. length of the original value, in bytes */ - uint original_length; - enum Type { FIXED_SIZE, VARIABLE_SIZE } type; - /* - TRUE : if the item or field is NULLABLE - FALSE : otherwise - */ - bool maybe_null; - CHARSET_INFO *cs; - uint pack_sort_string(uchar *to, const Binary_string *str, - CHARSET_INFO *cs) const; - int compare_packed_fixed_size_vals(uchar *a, size_t *a_len, - uchar *b, size_t *b_len); - int compare_packed_varstrings(uchar *a, size_t *a_len, - uchar *b, size_t *b_len); - bool check_if_packing_possible(THD *thd) const; - bool is_variable_sized() { return type == VARIABLE_SIZE; } - void set_length_and_original_length(THD *thd, uint length_arg); -}; - - -struct SORT_FIELD: public SORT_FIELD_ATTR -{ - Field *field; /* Field to sort */ - Item *item; /* Item if not sorting fields */ - bool reverse; /* if descending sort */ -}; - - -typedef struct st_sort_buffer { - uint index; /* 0 or 1 */ - uint sort_orders; - uint change_pos; /* If sort-fields changed */ - char **buff; - SORT_FIELD *sortorder; -} SORT_BUFFER; - -/* Structure for db & table in sql_yacc */ - -class Table_ident :public Sql_alloc -{ -public: - LEX_CSTRING db; - LEX_CSTRING table; - SELECT_LEX_UNIT *sel; - inline Table_ident(THD *thd, const LEX_CSTRING *db_arg, - const LEX_CSTRING *table_arg, - bool force) - :table(*table_arg), sel((SELECT_LEX_UNIT *)0) - { - if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA)) - db= null_clex_str; - else - db= *db_arg; - } - inline Table_ident(const LEX_CSTRING *table_arg) - :table(*table_arg), sel((SELECT_LEX_UNIT *)0) - { - db= null_clex_str; - } - /* - This constructor is used only for the case when we create a derived - table. A derived table has no name and doesn't belong to any database. - Later, if there was an alias specified for the table, it will be set - by add_table_to_list. - */ - inline Table_ident(SELECT_LEX_UNIT *s) : sel(s) - { - /* We must have a table name here as this is used with add_table_to_list */ - db.str= empty_c_string; /* a subject to casedn_str */ - db.length= 0; - table.str= internal_table_name; - table.length=1; - } - bool is_derived_table() const { return MY_TEST(sel); } - inline void change_db(LEX_CSTRING *db_name) - { - db= *db_name; - } - bool resolve_table_rowtype_ref(THD *thd, Row_definition_list &defs); - bool append_to(THD *thd, String *to) const; -}; - - -class Qualified_column_ident: public Table_ident -{ -public: - LEX_CSTRING m_column; -public: - Qualified_column_ident(const LEX_CSTRING *column) - :Table_ident(&null_clex_str), - m_column(*column) - { } - Qualified_column_ident(const LEX_CSTRING *table, const LEX_CSTRING *column) - :Table_ident(table), - m_column(*column) - { } - Qualified_column_ident(THD *thd, - const LEX_CSTRING *db, - const LEX_CSTRING *table, - const LEX_CSTRING *column) - :Table_ident(thd, db, table, false), - m_column(*column) - { } - bool resolve_type_ref(THD *thd, Column_definition *def); - bool append_to(THD *thd, String *to) const; -}; - - -// this is needed for user_vars hash -class user_var_entry -{ - CHARSET_INFO *m_charset; - public: - user_var_entry() {} /* Remove gcc warning */ - LEX_CSTRING name; - char *value; - size_t length; - query_id_t update_query_id, used_query_id; - Item_result type; - bool unsigned_flag; - - double val_real(bool *null_value); - longlong val_int(bool *null_value) const; - String *val_str(bool *null_value, String *str, uint decimals) const; - my_decimal *val_decimal(bool *null_value, my_decimal *result); - CHARSET_INFO *charset() const { return m_charset; } - void set_charset(CHARSET_INFO *cs) { m_charset= cs; } -}; - -user_var_entry *get_variable(HASH *hash, LEX_CSTRING *name, - bool create_if_not_exists); - -class SORT_INFO; -class multi_delete :public select_result_interceptor -{ - TABLE_LIST *delete_tables, *table_being_deleted; - Unique **tempfiles; - ha_rows deleted, found; - uint num_of_tables; - int error; - bool do_delete; - /* True if at least one table we delete from is transactional */ - bool transactional_tables; - /* True if at least one table we delete from is not transactional */ - bool normal_tables; - bool delete_while_scanning; - /* - error handling (rollback and binlogging) can happen in send_eof() - so that afterward abort_result_set() needs to find out that. - */ - bool error_handled; - -public: - // Methods used by ColumnStore - uint get_num_of_tables() const { return num_of_tables; } - TABLE_LIST* get_tables() const { return delete_tables; } -public: - multi_delete(THD *thd_arg, TABLE_LIST *dt, uint num_of_tables); - ~multi_delete(); - int prepare(List &list, SELECT_LEX_UNIT *u); - int send_data(List &items); - bool initialize_tables (JOIN *join); - int do_deletes(); - int do_table_deletes(TABLE *table, SORT_INFO *sort_info, bool ignore); - bool send_eof(); - inline ha_rows num_deleted() const { return deleted; } - virtual void abort_result_set(); - void prepare_to_read_rows(); -}; - - -class multi_update :public select_result_interceptor -{ - TABLE_LIST *all_tables; /* query/update command tables */ - List *leaves; /* list of leves of join table tree */ - TABLE_LIST *update_tables; - TABLE **tmp_tables, *main_table, *table_to_update; - TMP_TABLE_PARAM *tmp_table_param; - ha_rows updated, found; - List *fields, *values; - List **fields_for_table, **values_for_table; - uint table_count; - /* - List of tables referenced in the CHECK OPTION condition of - the updated view excluding the updated table. - */ - List
unupdated_check_opt_tables; - Copy_field *copy_field; - enum enum_duplicates handle_duplicates; - bool do_update, trans_safe; - /* True if the update operation has made a change in a transactional table */ - bool transactional_tables; - bool ignore; - /* - error handling (rollback and binlogging) can happen in send_eof() - so that afterward abort_result_set() needs to find out that. - */ - bool error_handled; - - /* Need this to protect against multiple prepare() calls */ - bool prepared; - - // For System Versioning (may need to insert new fields to a table). - ha_rows updated_sys_ver; - - bool has_vers_fields; - -public: - multi_update(THD *thd_arg, TABLE_LIST *ut, List *leaves_list, - List *fields, List *values, - enum_duplicates handle_duplicates, bool ignore); - ~multi_update(); - int prepare(List &list, SELECT_LEX_UNIT *u); - int send_data(List &items); - bool initialize_tables (JOIN *join); - int prepare2(JOIN *join); - int do_updates(); - bool send_eof(); - inline ha_rows num_found() const { return found; } - inline ha_rows num_updated() const { return updated; } - virtual void abort_result_set(); - void update_used_tables(); - void prepare_to_read_rows(); -}; - -class my_var_sp; -class my_var : public Sql_alloc { -public: - const LEX_CSTRING name; - enum type { SESSION_VAR, LOCAL_VAR, PARAM_VAR }; - type scope; - my_var(const LEX_CSTRING *j, enum type s) : name(*j), scope(s) { } - virtual ~my_var() {} - virtual bool set(THD *thd, Item *val) = 0; - virtual my_var_sp *get_my_var_sp() { return NULL; } -}; - -class my_var_sp: public my_var { - const Sp_rcontext_handler *m_rcontext_handler; - const Type_handler *m_type_handler; -public: - uint offset; - /* - Routine to which this Item_splocal belongs. Used for checking if correct - runtime context is used for variable handling. - */ - sp_head *sp; - my_var_sp(const Sp_rcontext_handler *rcontext_handler, - const LEX_CSTRING *j, uint o, const Type_handler *type_handler, - sp_head *s) - : my_var(j, LOCAL_VAR), - m_rcontext_handler(rcontext_handler), - m_type_handler(type_handler), offset(o), sp(s) { } - ~my_var_sp() { } - bool set(THD *thd, Item *val); - my_var_sp *get_my_var_sp() { return this; } - const Type_handler *type_handler() const { return m_type_handler; } - sp_rcontext *get_rcontext(sp_rcontext *local_ctx) const; -}; - -/* - This class handles fields of a ROW SP variable when it's used as a OUT - parameter in a stored procedure. -*/ -class my_var_sp_row_field: public my_var_sp -{ - uint m_field_offset; -public: - my_var_sp_row_field(const Sp_rcontext_handler *rcontext_handler, - const LEX_CSTRING *varname, const LEX_CSTRING *fieldname, - uint var_idx, uint field_idx, sp_head *s) - :my_var_sp(rcontext_handler, varname, var_idx, - &type_handler_double/*Not really used*/, s), - m_field_offset(field_idx) - { } - bool set(THD *thd, Item *val); -}; - -class my_var_user: public my_var { -public: - my_var_user(const LEX_CSTRING *j) - : my_var(j, SESSION_VAR) { } - ~my_var_user() { } - bool set(THD *thd, Item *val); -}; - -class select_dumpvar :public select_result_interceptor { - ha_rows row_count; - my_var_sp *m_var_sp_row; // Not NULL if SELECT INTO row_type_sp_variable - bool send_data_to_var_list(List &items); -public: - List var_list; - select_dumpvar(THD *thd_arg) - :select_result_interceptor(thd_arg), row_count(0), m_var_sp_row(NULL) - { var_list.empty(); } - ~select_dumpvar() {} - int prepare(List &list, SELECT_LEX_UNIT *u); - int send_data(List &items); - bool send_eof(); - virtual bool check_simple_select() const; - void cleanup(); -}; - -/* Bits in sql_command_flags */ - -#define CF_CHANGES_DATA (1U << 0) -#define CF_REPORT_PROGRESS (1U << 1) -#define CF_STATUS_COMMAND (1U << 2) -#define CF_SHOW_TABLE_COMMAND (1U << 3) -#define CF_WRITE_LOGS_COMMAND (1U << 4) - -/** - Must be set for SQL statements that may contain - Item expressions and/or use joins and tables. - Indicates that the parse tree of such statement may - contain rule-based optimizations that depend on metadata - (i.e. number of columns in a table), and consequently - that the statement must be re-prepared whenever - referenced metadata changes. Must not be set for - statements that themselves change metadata, e.g. RENAME, - ALTER and other DDL, since otherwise will trigger constant - reprepare. Consequently, complex item expressions and - joins are currently prohibited in these statements. -*/ -#define CF_REEXECUTION_FRAGILE (1U << 5) -/** - Implicitly commit before the SQL statement is executed. - - Statements marked with this flag will cause any active - transaction to end (commit) before proceeding with the - command execution. - - This flag should be set for statements that probably can't - be rolled back or that do not expect any previously metadata - locked tables. -*/ -#define CF_IMPLICIT_COMMIT_BEGIN (1U << 6) -/** - Implicitly commit after the SQL statement. - - Statements marked with this flag are automatically committed - at the end of the statement. - - This flag should be set for statements that will implicitly - open and take metadata locks on system tables that should not - be carried for the whole duration of a active transaction. -*/ -#define CF_IMPLICIT_COMMIT_END (1U << 7) -/** - CF_IMPLICT_COMMIT_BEGIN and CF_IMPLICIT_COMMIT_END are used - to ensure that the active transaction is implicitly committed - before and after every DDL statement and any statement that - modifies our currently non-transactional system tables. -*/ -#define CF_AUTO_COMMIT_TRANS (CF_IMPLICIT_COMMIT_BEGIN | CF_IMPLICIT_COMMIT_END) - -/** - Diagnostic statement. - Diagnostic statements: - - SHOW WARNING - - SHOW ERROR - - GET DIAGNOSTICS (WL#2111) - do not modify the diagnostics area during execution. -*/ -#define CF_DIAGNOSTIC_STMT (1U << 8) - -/** - Identifies statements that may generate row events - and that may end up in the binary log. -*/ -#define CF_CAN_GENERATE_ROW_EVENTS (1U << 9) - -/** - Identifies statements which may deal with temporary tables and for which - temporary tables should be pre-opened to simplify privilege checks. -*/ -#define CF_PREOPEN_TMP_TABLES (1U << 10) - -/** - Identifies statements for which open handlers should be closed in the - beginning of the statement. -*/ -#define CF_HA_CLOSE (1U << 11) - -/** - Identifies statements that can be explained with EXPLAIN. -*/ -#define CF_CAN_BE_EXPLAINED (1U << 12) - -/** Identifies statements which may generate an optimizer trace */ -#define CF_OPTIMIZER_TRACE (1U << 14) - -/** - Identifies statements that should always be disallowed in - read only transactions. -*/ -#define CF_DISALLOW_IN_RO_TRANS (1U << 15) - -/** - Statement that need the binlog format to be unchanged. -*/ -#define CF_FORCE_ORIGINAL_BINLOG_FORMAT (1U << 16) - -/** - Statement that inserts new rows (INSERT, REPLACE, LOAD, ALTER TABLE) -*/ -#define CF_INSERTS_DATA (1U << 17) - -/** - Statement that updates existing rows (UPDATE, multi-update) -*/ -#define CF_UPDATES_DATA (1U << 18) - -/** - Not logged into slow log as "admin commands" -*/ -#define CF_ADMIN_COMMAND (1U << 19) - -/** - SP Bulk execution safe -*/ -#define CF_PS_ARRAY_BINDING_SAFE (1U << 20) -/** - SP Bulk execution optimized -*/ -#define CF_PS_ARRAY_BINDING_OPTIMIZED (1U << 21) -/** - If command creates or drops a table -*/ -#define CF_SCHEMA_CHANGE (1U << 22) -/** - If command creates or drops a database -*/ -#define CF_DB_CHANGE (1U << 23) - -#ifdef WITH_WSREP -/** - DDL statement that may be subject to error filtering. -*/ -#define CF_WSREP_MAY_IGNORE_ERRORS (1U << 24) -#endif /* WITH_WSREP */ - - -/* Bits in server_command_flags */ - -/** - Statement that deletes existing rows (DELETE, DELETE_MULTI) -*/ -#define CF_DELETES_DATA (1U << 24) - -/** - Skip the increase of the global query id counter. Commonly set for - commands that are stateless (won't cause any change on the server - internal states). -*/ -#define CF_SKIP_QUERY_ID (1U << 0) - -/** - Skip the increase of the number of statements that clients have - sent to the server. Commonly used for commands that will cause - a statement to be executed but the statement might have not been - sent by the user (ie: stored procedure). -*/ -#define CF_SKIP_QUESTIONS (1U << 1) -#ifdef WITH_WSREP -/** - Do not check that wsrep snapshot is ready before allowing this command -*/ -#define CF_SKIP_WSREP_CHECK (1U << 2) -#else -#define CF_SKIP_WSREP_CHECK 0 -#endif /* WITH_WSREP */ - -/** - Do not allow it for COM_MULTI batch -*/ -#define CF_NO_COM_MULTI (1U << 3) - -/* Inline functions */ - -inline bool add_item_to_list(THD *thd, Item *item) -{ - bool res= thd->lex->current_select->add_item_to_list(thd, item); - return res; -} - -inline bool add_value_to_list(THD *thd, Item *value) -{ - return thd->lex->value_list.push_back(value, thd->mem_root); -} - -inline bool add_order_to_list(THD *thd, Item *item, bool asc) -{ - return thd->lex->current_select->add_order_to_list(thd, item, asc); -} - -inline bool add_gorder_to_list(THD *thd, Item *item, bool asc) -{ - return thd->lex->current_select->add_gorder_to_list(thd, item, asc); -} - -inline bool add_group_to_list(THD *thd, Item *item, bool asc) -{ - return thd->lex->current_select->add_group_to_list(thd, item, asc); -} - -inline Item *and_conds(THD *thd, Item *a, Item *b) -{ - if (!b) return a; - if (!a) return b; - return new (thd->mem_root) Item_cond_and(thd, a, b); -} - -/* inline handler methods that need to know TABLE and THD structures */ -inline void handler::increment_statistics(ulong SSV::*offset) const -{ - status_var_increment(table->in_use->status_var.*offset); - table->in_use->check_limit_rows_examined(); -} - -inline void handler::decrement_statistics(ulong SSV::*offset) const -{ - status_var_decrement(table->in_use->status_var.*offset); -} - - -inline int handler::ha_ft_read(uchar *buf) -{ - int error= ft_read(buf); - if (!error) - update_rows_read(); - - table->status=error ? STATUS_NOT_FOUND: 0; - return error; -} - -inline int handler::ha_rnd_pos_by_record(uchar *buf) -{ - int error= rnd_pos_by_record(buf); - table->status=error ? STATUS_NOT_FOUND: 0; - return error; -} - -inline int handler::ha_read_first_row(uchar *buf, uint primary_key) -{ - int error= read_first_row(buf, primary_key); - if (!error) - update_rows_read(); - table->status=error ? STATUS_NOT_FOUND: 0; - return error; -} - -inline int handler::ha_write_tmp_row(uchar *buf) -{ - int error; - MYSQL_INSERT_ROW_START(table_share->db.str, table_share->table_name.str); - increment_statistics(&SSV::ha_tmp_write_count); - TABLE_IO_WAIT(tracker, PSI_TABLE_WRITE_ROW, MAX_KEY, error, - { error= write_row(buf); }) - MYSQL_INSERT_ROW_DONE(error); - return error; -} - -inline int handler::ha_delete_tmp_row(uchar *buf) -{ - int error; - MYSQL_DELETE_ROW_START(table_share->db.str, table_share->table_name.str); - increment_statistics(&SSV::ha_tmp_delete_count); - TABLE_IO_WAIT(tracker, PSI_TABLE_DELETE_ROW, MAX_KEY, error, - { error= delete_row(buf); }) - MYSQL_DELETE_ROW_DONE(error); - return error; -} - -inline int handler::ha_update_tmp_row(const uchar *old_data, uchar *new_data) -{ - int error; - MYSQL_UPDATE_ROW_START(table_share->db.str, table_share->table_name.str); - increment_statistics(&SSV::ha_tmp_update_count); - TABLE_IO_WAIT(tracker, PSI_TABLE_UPDATE_ROW, active_index, error, - { error= update_row(old_data, new_data);}) - MYSQL_UPDATE_ROW_DONE(error); - return error; -} - -inline bool handler::has_long_unique() -{ - return table->s->long_unique_table; -} - -extern pthread_attr_t *get_connection_attrib(void); - -/** - Set thread entering a condition - - This function should be called before putting a thread to wait for - a condition. @a mutex should be held before calling this - function. After being waken up, @f thd_exit_cond should be called. - - @param thd The thread entering the condition, NULL means current thread - @param cond The condition the thread is going to wait for - @param mutex The mutex associated with the condition, this must be - held before call this function - @param stage The new process message for the thread - @param old_stage The old process message for the thread - @param src_function The caller source function name - @param src_file The caller source file name - @param src_line The caller source line number -*/ -void thd_enter_cond(MYSQL_THD thd, mysql_cond_t *cond, mysql_mutex_t *mutex, - const PSI_stage_info *stage, PSI_stage_info *old_stage, - const char *src_function, const char *src_file, - int src_line); - -#define THD_ENTER_COND(P1, P2, P3, P4, P5) \ - thd_enter_cond(P1, P2, P3, P4, P5, __func__, __FILE__, __LINE__) - -/** - Set thread leaving a condition - - This function should be called after a thread being waken up for a - condition. - - @param thd The thread entering the condition, NULL means current thread - @param stage The process message, ususally this should be the old process - message before calling @f thd_enter_cond - @param src_function The caller source function name - @param src_file The caller source file name - @param src_line The caller source line number -*/ -void thd_exit_cond(MYSQL_THD thd, const PSI_stage_info *stage, - const char *src_function, const char *src_file, - int src_line); - -#define THD_EXIT_COND(P1, P2) \ - thd_exit_cond(P1, P2, __func__, __FILE__, __LINE__) - -inline bool binlog_should_compress(size_t len) -{ - return opt_bin_log_compress && - len >= opt_bin_log_compress_min_len; -} - - -/** - Save thd sql_mode on instantiation. - On destruction it resets the mode to the previously stored value. -*/ -class Sql_mode_save -{ - public: - Sql_mode_save(THD *thd) : thd(thd), old_mode(thd->variables.sql_mode) {} - ~Sql_mode_save() { thd->variables.sql_mode = old_mode; } - - private: - THD *thd; - sql_mode_t old_mode; // SQL mode saved at construction time. -}; - -class Switch_to_definer_security_ctx -{ - public: - Switch_to_definer_security_ctx(THD *thd, TABLE_LIST *table) : - m_thd(thd), m_sctx(thd->security_ctx) - { - if (table->security_ctx) - thd->security_ctx= table->security_ctx; - } - ~Switch_to_definer_security_ctx() { m_thd->security_ctx = m_sctx; } - - private: - THD *m_thd; - Security_context *m_sctx; -}; - - -class Sql_mode_instant_set: public Sql_mode_save -{ -public: - Sql_mode_instant_set(THD *thd, sql_mode_t temporary_value) - :Sql_mode_save(thd) - { - thd->variables.sql_mode= temporary_value; - } -}; - - -class Sql_mode_instant_remove: public Sql_mode_save -{ -public: - Sql_mode_instant_remove(THD *thd, sql_mode_t temporary_remove_flags) - :Sql_mode_save(thd) - { - thd->variables.sql_mode&= ~temporary_remove_flags; - } -}; - - -class Abort_on_warning_instant_set -{ - THD *m_thd; - bool m_save_abort_on_warning; -public: - Abort_on_warning_instant_set(THD *thd, bool temporary_value) - :m_thd(thd), m_save_abort_on_warning(thd->abort_on_warning) - { - thd->abort_on_warning= temporary_value; - } - ~Abort_on_warning_instant_set() - { - m_thd->abort_on_warning= m_save_abort_on_warning; - } -}; - - -class Check_level_instant_set -{ - THD *m_thd; - enum_check_fields m_check_level; -public: - Check_level_instant_set(THD *thd, enum_check_fields temporary_value) - :m_thd(thd), m_check_level(thd->count_cuted_fields) - { - thd->count_cuted_fields= temporary_value; - } - ~Check_level_instant_set() - { - m_thd->count_cuted_fields= m_check_level; - } -}; - - -/** - This class resembles the SQL Standard schema qualified object name: - ::= [ ] -*/ -class Database_qualified_name -{ -public: - LEX_CSTRING m_db; - LEX_CSTRING m_name; - Database_qualified_name(const LEX_CSTRING *db, const LEX_CSTRING *name) - :m_db(*db), m_name(*name) - { } - Database_qualified_name(const LEX_CSTRING &db, const LEX_CSTRING &name) - :m_db(db), m_name(name) - { } - Database_qualified_name(const char *db, size_t db_length, - const char *name, size_t name_length) - { - m_db.str= db; - m_db.length= db_length; - m_name.str= name; - m_name.length= name_length; - } - - bool eq(const Database_qualified_name *other) const - { - CHARSET_INFO *cs= lower_case_table_names ? - &my_charset_utf8mb3_general_ci : - &my_charset_utf8mb3_bin; - return - m_db.length == other->m_db.length && - m_name.length == other->m_name.length && - !cs->strnncoll(m_db.str, m_db.length, - other->m_db.str, other->m_db.length) && - !cs->strnncoll(m_name.str, m_name.length, - other->m_name.str, other->m_name.length); - } - void copy(MEM_ROOT *mem_root, const LEX_CSTRING &db, - const LEX_CSTRING &name); - // Export db and name as a qualified name string: 'db.name' - size_t make_qname(char *dst, size_t dstlen) const - { - return my_snprintf(dst, dstlen, "%.*s.%.*s", - (int) m_db.length, m_db.str, - (int) m_name.length, m_name.str); - } - // Export db and name as a qualified name string, allocate on mem_root. - bool make_qname(MEM_ROOT *mem_root, LEX_CSTRING *dst) const - { - const uint dot= !!m_db.length; - char *tmp; - /* format: [database + dot] + name + '\0' */ - dst->length= m_db.length + dot + m_name.length; - if (unlikely(!(dst->str= tmp= (char*) alloc_root(mem_root, - dst->length + 1)))) - return true; - sprintf(tmp, "%.*s%.*s%.*s", - (int) m_db.length, (m_db.length ? m_db.str : ""), - dot, ".", - (int) m_name.length, m_name.str); - DBUG_SLOW_ASSERT(ok_for_lower_case_names(m_db.str)); - return false; - } - - bool make_package_routine_name(MEM_ROOT *mem_root, - const LEX_CSTRING &package, - const LEX_CSTRING &routine) - { - char *tmp; - size_t length= package.length + 1 + routine.length + 1; - if (unlikely(!(tmp= (char *) alloc_root(mem_root, length)))) - return true; - m_name.length= my_snprintf(tmp, length, "%.*s.%.*s", - (int) package.length, package.str, - (int) routine.length, routine.str); - m_name.str= tmp; - return false; - } - - bool make_package_routine_name(MEM_ROOT *mem_root, - const LEX_CSTRING &db, - const LEX_CSTRING &package, - const LEX_CSTRING &routine) - { - if (unlikely(make_package_routine_name(mem_root, package, routine))) - return true; - if (unlikely(!(m_db.str= strmake_root(mem_root, db.str, db.length)))) - return true; - m_db.length= db.length; - return false; - } -}; - - -class ErrConvDQName: public ErrConv -{ - const Database_qualified_name *m_name; -public: - ErrConvDQName(const Database_qualified_name *name) - :m_name(name) - { } - const char *ptr() const - { - m_name->make_qname(err_buffer, sizeof(err_buffer)); - return err_buffer; - } -}; - -class Type_holder: public Sql_alloc, - public Item_args, - public Type_handler_hybrid_field_type, - public Type_all_attributes -{ - const TYPELIB *m_typelib; - bool m_maybe_null; -public: - Type_holder() - :m_typelib(NULL), - m_maybe_null(false) - { } - - void set_maybe_null(bool maybe_null_arg) { m_maybe_null= maybe_null_arg; } - bool get_maybe_null() const { return m_maybe_null; } - - uint decimal_precision() const - { - /* - Type_holder is not used directly to create fields, so - its virtual decimal_precision() is never called. - We should eventually extend create_result_table() to accept - an array of Type_holders directly, without having to allocate - Item_type_holder's and put them into List. - */ - DBUG_ASSERT(0); - return 0; - } - void set_typelib(const TYPELIB *typelib) - { - m_typelib= typelib; - } - const TYPELIB *get_typelib() const - { - return m_typelib; - } - - bool aggregate_attributes(THD *thd) - { - for (uint i= 0; i < arg_count; i++) - m_maybe_null|= args[i]->maybe_null; - return - type_handler()->Item_hybrid_func_fix_attributes(thd, - "UNION", this, this, - args, arg_count); - } -}; - - -/* - A helper class to set THD flags to emit warnings/errors in case of - overflow/type errors during assigning values into the SP variable fields. - Saves original flags values in constructor. - Restores original flags in destructor. -*/ -class Sp_eval_expr_state -{ - THD *m_thd; - enum_check_fields m_count_cuted_fields; - bool m_abort_on_warning; - bool m_stmt_modified_non_trans_table; - void start() - { - m_thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL; - m_thd->abort_on_warning= m_thd->is_strict_mode(); - m_thd->transaction->stmt.modified_non_trans_table= false; - } - void stop() - { - m_thd->count_cuted_fields= m_count_cuted_fields; - m_thd->abort_on_warning= m_abort_on_warning; - m_thd->transaction->stmt.modified_non_trans_table= - m_stmt_modified_non_trans_table; - } -public: - Sp_eval_expr_state(THD *thd) - :m_thd(thd), - m_count_cuted_fields(thd->count_cuted_fields), - m_abort_on_warning(thd->abort_on_warning), - m_stmt_modified_non_trans_table(thd->transaction->stmt. - modified_non_trans_table) - { - start(); - } - ~Sp_eval_expr_state() - { - stop(); - } -}; - - -#ifndef DBUG_OFF -void dbug_serve_apcs(THD *thd, int n_calls); -#endif - -class ScopedStatementReplication -{ -public: - ScopedStatementReplication(THD *thd) : - saved_binlog_format(thd - ? thd->set_current_stmt_binlog_format_stmt() - : BINLOG_FORMAT_MIXED), - thd(thd) - {} - ~ScopedStatementReplication() - { - if (thd) - thd->restore_stmt_binlog_format(saved_binlog_format); - } - -private: - const enum_binlog_format saved_binlog_format; - THD *const thd; -}; - - -/** THD registry */ -class THD_list: public THD_list_iterator -{ -public: - /** - Constructor replacement. - - Unfortunately we can't use fair constructor to initialize mutex - for two reasons: PFS and embedded. The former can probably be fixed, - the latter can probably be dropped. - */ - void init() - { - mysql_rwlock_init(key_rwlock_THD_list, &lock); - } - - /** Destructor replacement. */ - void destroy() - { - mysql_rwlock_destroy(&lock); - } - - /** - Inserts thread to registry. - - @param thd thread - - Thread becomes accessible via server_threads. - */ - void insert(THD *thd) - { - mysql_rwlock_wrlock(&lock); - threads.append(thd); - mysql_rwlock_unlock(&lock); - } - - /** - Removes thread from registry. - - @param thd thread - - Thread becomes not accessible via server_threads. - */ - void erase(THD *thd) - { - thd->assert_linked(); - mysql_rwlock_wrlock(&lock); - thd->unlink(); - mysql_rwlock_unlock(&lock); - } -}; - -extern THD_list server_threads; - -#endif /* MYSQL_SERVER */ -#endif /* SQL_CLASS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cmd.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cmd.h deleted file mode 100644 index ce34852..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cmd.h +++ /dev/null @@ -1,281 +0,0 @@ -/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file Representation of an SQL command. -*/ - -#ifndef SQL_CMD_INCLUDED -#define SQL_CMD_INCLUDED - -/* - When a command is added here, be sure it's also added in mysqld.cc - in "struct show_var_st status_vars[]= {" ... - - If the command returns a result set or is not allowed in stored - functions or triggers, please also make sure that - sp_get_flags_for_command (sp_head.cc) returns proper flags for the - added SQLCOM_. -*/ - -enum enum_sql_command { - SQLCOM_SELECT, SQLCOM_CREATE_TABLE, SQLCOM_CREATE_INDEX, SQLCOM_ALTER_TABLE, - SQLCOM_UPDATE, SQLCOM_INSERT, SQLCOM_INSERT_SELECT, - SQLCOM_DELETE, SQLCOM_TRUNCATE, SQLCOM_DROP_TABLE, SQLCOM_DROP_INDEX, - - SQLCOM_SHOW_DATABASES, SQLCOM_SHOW_TABLES, SQLCOM_SHOW_FIELDS, - SQLCOM_SHOW_KEYS, SQLCOM_SHOW_VARIABLES, SQLCOM_SHOW_STATUS, - SQLCOM_SHOW_ENGINE_LOGS, SQLCOM_SHOW_ENGINE_STATUS, SQLCOM_SHOW_ENGINE_MUTEX, - SQLCOM_SHOW_PROCESSLIST, SQLCOM_SHOW_BINLOG_STAT, SQLCOM_SHOW_SLAVE_STAT, - SQLCOM_SHOW_GRANTS, SQLCOM_SHOW_CREATE, SQLCOM_SHOW_CHARSETS, - SQLCOM_SHOW_COLLATIONS, SQLCOM_SHOW_CREATE_DB, SQLCOM_SHOW_TABLE_STATUS, - SQLCOM_SHOW_TRIGGERS, - - SQLCOM_LOAD,SQLCOM_SET_OPTION,SQLCOM_LOCK_TABLES,SQLCOM_UNLOCK_TABLES, - SQLCOM_GRANT, - SQLCOM_CHANGE_DB, SQLCOM_CREATE_DB, SQLCOM_DROP_DB, SQLCOM_ALTER_DB, - SQLCOM_REPAIR, SQLCOM_REPLACE, SQLCOM_REPLACE_SELECT, - SQLCOM_CREATE_FUNCTION, SQLCOM_DROP_FUNCTION, - SQLCOM_REVOKE,SQLCOM_OPTIMIZE, SQLCOM_CHECK, - SQLCOM_ASSIGN_TO_KEYCACHE, SQLCOM_PRELOAD_KEYS, - SQLCOM_FLUSH, SQLCOM_KILL, SQLCOM_ANALYZE, - SQLCOM_ROLLBACK, SQLCOM_ROLLBACK_TO_SAVEPOINT, - SQLCOM_COMMIT, SQLCOM_SAVEPOINT, SQLCOM_RELEASE_SAVEPOINT, - SQLCOM_SLAVE_START, SQLCOM_SLAVE_STOP, - SQLCOM_BEGIN, SQLCOM_CHANGE_MASTER, - SQLCOM_RENAME_TABLE, - SQLCOM_RESET, SQLCOM_PURGE, SQLCOM_PURGE_BEFORE, SQLCOM_SHOW_BINLOGS, - SQLCOM_SHOW_OPEN_TABLES, - SQLCOM_HA_OPEN, SQLCOM_HA_CLOSE, SQLCOM_HA_READ, - SQLCOM_SHOW_SLAVE_HOSTS, SQLCOM_DELETE_MULTI, SQLCOM_UPDATE_MULTI, - SQLCOM_SHOW_BINLOG_EVENTS, SQLCOM_DO, - SQLCOM_SHOW_WARNS, SQLCOM_EMPTY_QUERY, SQLCOM_SHOW_ERRORS, - SQLCOM_SHOW_STORAGE_ENGINES, SQLCOM_SHOW_PRIVILEGES, - SQLCOM_HELP, SQLCOM_CREATE_USER, SQLCOM_DROP_USER, SQLCOM_RENAME_USER, - SQLCOM_REVOKE_ALL, SQLCOM_CHECKSUM, - SQLCOM_CREATE_PROCEDURE, SQLCOM_CREATE_SPFUNCTION, SQLCOM_CALL, - SQLCOM_DROP_PROCEDURE, SQLCOM_ALTER_PROCEDURE,SQLCOM_ALTER_FUNCTION, - SQLCOM_SHOW_CREATE_PROC, SQLCOM_SHOW_CREATE_FUNC, - SQLCOM_SHOW_STATUS_PROC, SQLCOM_SHOW_STATUS_FUNC, - SQLCOM_PREPARE, SQLCOM_EXECUTE, SQLCOM_DEALLOCATE_PREPARE, - SQLCOM_CREATE_VIEW, SQLCOM_DROP_VIEW, - SQLCOM_CREATE_TRIGGER, SQLCOM_DROP_TRIGGER, - SQLCOM_XA_START, SQLCOM_XA_END, SQLCOM_XA_PREPARE, - SQLCOM_XA_COMMIT, SQLCOM_XA_ROLLBACK, SQLCOM_XA_RECOVER, - SQLCOM_SHOW_PROC_CODE, SQLCOM_SHOW_FUNC_CODE, - SQLCOM_ALTER_TABLESPACE, - SQLCOM_INSTALL_PLUGIN, SQLCOM_UNINSTALL_PLUGIN, - SQLCOM_SHOW_AUTHORS, SQLCOM_BINLOG_BASE64_EVENT, - SQLCOM_SHOW_PLUGINS, SQLCOM_SHOW_CONTRIBUTORS, - SQLCOM_CREATE_SERVER, SQLCOM_DROP_SERVER, SQLCOM_ALTER_SERVER, - SQLCOM_CREATE_EVENT, SQLCOM_ALTER_EVENT, SQLCOM_DROP_EVENT, - SQLCOM_SHOW_CREATE_EVENT, SQLCOM_SHOW_EVENTS, - SQLCOM_SHOW_CREATE_TRIGGER, - SQLCOM_ALTER_DB_UPGRADE, - SQLCOM_SHOW_PROFILE, SQLCOM_SHOW_PROFILES, - SQLCOM_SIGNAL, SQLCOM_RESIGNAL, - SQLCOM_SHOW_RELAYLOG_EVENTS, - SQLCOM_GET_DIAGNOSTICS, - SQLCOM_SLAVE_ALL_START, SQLCOM_SLAVE_ALL_STOP, - SQLCOM_SHOW_EXPLAIN, SQLCOM_SHUTDOWN, - SQLCOM_CREATE_ROLE, SQLCOM_DROP_ROLE, SQLCOM_GRANT_ROLE, SQLCOM_REVOKE_ROLE, - SQLCOM_COMPOUND, - SQLCOM_SHOW_GENERIC, - SQLCOM_ALTER_USER, - SQLCOM_SHOW_CREATE_USER, - SQLCOM_EXECUTE_IMMEDIATE, - SQLCOM_CREATE_SEQUENCE, - SQLCOM_DROP_SEQUENCE, - SQLCOM_ALTER_SEQUENCE, - SQLCOM_CREATE_PACKAGE, - SQLCOM_DROP_PACKAGE, - SQLCOM_CREATE_PACKAGE_BODY, - SQLCOM_DROP_PACKAGE_BODY, - SQLCOM_SHOW_CREATE_PACKAGE, - SQLCOM_SHOW_CREATE_PACKAGE_BODY, - SQLCOM_SHOW_STATUS_PACKAGE, - SQLCOM_SHOW_STATUS_PACKAGE_BODY, - SQLCOM_SHOW_PACKAGE_BODY_CODE, - SQLCOM_BACKUP, SQLCOM_BACKUP_LOCK, - - /* - When a command is added here, be sure it's also added in mysqld.cc - in "struct show_var_st com_status_vars[]= {" ... - */ - /* This should be the last !!! */ - SQLCOM_END -}; - - -class Storage_engine_name -{ -protected: - LEX_CSTRING m_storage_engine_name; -public: - Storage_engine_name() - { - m_storage_engine_name.str= NULL; - m_storage_engine_name.length= 0; - } - Storage_engine_name(const LEX_CSTRING &name) - :m_storage_engine_name(name) - { } - Storage_engine_name(const LEX_STRING &name) - { - m_storage_engine_name.str= name.str; - m_storage_engine_name.length= name.length; - } - bool resolve_storage_engine_with_error(THD *thd, - handlerton **ha, - bool tmp_table); - bool is_set() { return m_storage_engine_name.str != NULL; } -}; - - -/** - @class Sql_cmd - Representation of an SQL command. - - This class is an interface between the parser and the runtime. - The parser builds the appropriate derived classes of Sql_cmd - to represent a SQL statement in the parsed tree. - The execute() method in the derived classes of Sql_cmd contain the runtime - implementation. - Note that this interface is used for SQL statements recently implemented, - the code for older statements tend to load the LEX structure with more - attributes instead. - Implement new statements by sub-classing Sql_cmd, as this improves - code modularity (see the 'big switch' in dispatch_command()), and decreases - the total size of the LEX structure (therefore saving memory in stored - programs). - The recommended name of a derived class of Sql_cmd is Sql_cmd_. - - Notice that the Sql_cmd class should not be confused with the - Statement class. Statement is a class that is used to manage an SQL - command or a set of SQL commands. When the SQL statement text is - analyzed, the parser will create one or more Sql_cmd objects to - represent the actual SQL commands. -*/ -class Sql_cmd : public Sql_alloc -{ -private: - Sql_cmd(const Sql_cmd &); // No copy constructor wanted - void operator=(Sql_cmd &); // No assignment operator wanted - -public: - /** - @brief Return the command code for this statement - */ - virtual enum_sql_command sql_command_code() const = 0; - - /** - Execute this SQL statement. - @param thd the current thread. - @retval false on success. - @retval true on error - */ - virtual bool execute(THD *thd) = 0; - - virtual Storage_engine_name *option_storage_engine_name() - { - return NULL; - } - -protected: - Sql_cmd() - {} - - virtual ~Sql_cmd() - { - /* - Sql_cmd objects are allocated in thd->mem_root. - In MySQL, the C++ destructor is never called, the underlying MEM_ROOT is - simply destroyed instead. - Do not rely on the destructor for any cleanup. - */ - DBUG_ASSERT(FALSE); - } -}; - -class Sql_cmd_show_slave_status: public Sql_cmd -{ -protected: - bool show_all_slaves_status; -public: - Sql_cmd_show_slave_status() - :show_all_slaves_status(false) - {} - - Sql_cmd_show_slave_status(bool status_all) - :show_all_slaves_status(status_all) - {} - - enum_sql_command sql_command_code() const { return SQLCOM_SHOW_SLAVE_STAT; } - - bool execute(THD *thd); - bool is_show_all_slaves_stat() { return show_all_slaves_status; } -}; - - -class Sql_cmd_create_table_like: public Sql_cmd, - public Storage_engine_name -{ -public: - Storage_engine_name *option_storage_engine_name() { return this; } - bool execute(THD *thd); -}; - -class Sql_cmd_create_table: public Sql_cmd_create_table_like -{ -public: - enum_sql_command sql_command_code() const { return SQLCOM_CREATE_TABLE; } -}; - -class Sql_cmd_create_sequence: public Sql_cmd_create_table_like -{ -public: - enum_sql_command sql_command_code() const { return SQLCOM_CREATE_SEQUENCE; } -}; - - -/** - Sql_cmd_call represents the CALL statement. -*/ -class Sql_cmd_call : public Sql_cmd -{ -public: - class sp_name *m_name; - const class Sp_handler *m_handler; - Sql_cmd_call(class sp_name *name, const class Sp_handler *handler) - :m_name(name), - m_handler(handler) - {} - - virtual ~Sql_cmd_call() - {} - - /** - Execute a CALL statement at runtime. - @param thd the current thread. - @return false on success. - */ - bool execute(THD *thd); - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_CALL; - } -}; - -#endif // SQL_CMD_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_connect.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_connect.h deleted file mode 100644 index 152bd71..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_connect.h +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_CONNECT_INCLUDED -#define SQL_CONNECT_INCLUDED - -#include /* pthread_handler_t */ -#include "mysql_com.h" /* enum_server_command */ -#include "structs.h" -#include -#include -#include "violite.h" - -/* - Object to hold connect information to be given to the newly created thread -*/ - -struct scheduler_functions; - -class CONNECT : public ilink { -public: - MYSQL_SOCKET sock; -#ifdef _WIN32 - HANDLE pipe; - CONNECT(HANDLE pipe_arg): pipe(pipe_arg), vio_type(VIO_TYPE_NAMEDPIPE), - scheduler(thread_scheduler), thread_id(0), prior_thr_create_utime(0) {} -#endif - enum enum_vio_type vio_type; - scheduler_functions *scheduler; - my_thread_id thread_id; - - /* Own variables */ - ulonglong prior_thr_create_utime; - - CONNECT(MYSQL_SOCKET sock_arg, enum enum_vio_type vio_type_arg, - scheduler_functions *scheduler_arg): sock(sock_arg), - vio_type(vio_type_arg), scheduler(scheduler_arg), thread_id(0), - prior_thr_create_utime(0) {} - ~CONNECT() { DBUG_ASSERT(vio_type == VIO_CLOSED); } - void close_and_delete(); - void close_with_error(uint sql_errno, - const char *message, uint close_error); - THD *create_thd(THD *thd); -}; - - -class THD; -typedef struct user_conn USER_CONN; - -void init_max_user_conn(void); -void init_global_user_stats(void); -void init_global_table_stats(void); -void init_global_index_stats(void); -void init_global_client_stats(void); -void free_max_user_conn(void); -void free_global_user_stats(void); -void free_global_table_stats(void); -void free_global_index_stats(void); -void free_global_client_stats(void); - -pthread_handler_t handle_one_connection(void *arg); -void do_handle_one_connection(CONNECT *connect, bool put_in_cache); -bool init_new_connection_handler_thread(); -void reset_mqh(LEX_USER *lu, bool get_them); -bool check_mqh(THD *thd, uint check_command); -void time_out_user_resource_limits(THD *thd, USER_CONN *uc); -#ifndef NO_EMBEDDED_ACCESS_CHECKS -void decrease_user_connections(USER_CONN *uc); -#else -#define decrease_user_connections(X) do { } while(0) /* nothing */ -#endif -bool thd_init_client_charset(THD *thd, uint cs_number); -void setup_connection_thread_globals(THD *thd); -bool thd_prepare_connection(THD *thd); -bool thd_is_connection_alive(THD *thd); -int thd_set_peer_addr(THD *thd, sockaddr_storage *addr, - const char *ip, uint port, - bool check_proxy_networks, - uint *host_errors); - -bool login_connection(THD *thd); -void prepare_new_connection_state(THD* thd); -void end_connection(THD *thd); -void update_global_user_stats(THD* thd, bool create_user, time_t now); -int get_or_create_user_conn(THD *thd, const char *user, - const char *host, const USER_RESOURCES *mqh); -int check_for_max_user_connections(THD *thd, USER_CONN *uc); - -extern HASH global_user_stats; -extern HASH global_client_stats; -extern HASH global_table_stats; -extern HASH global_index_stats; - -extern mysql_mutex_t LOCK_global_user_client_stats; -extern mysql_mutex_t LOCK_global_table_stats; -extern mysql_mutex_t LOCK_global_index_stats; -extern mysql_mutex_t LOCK_stats; - -#endif /* SQL_CONNECT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_const.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_const.h deleted file mode 100644 index 3f053a1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_const.h +++ /dev/null @@ -1,315 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - File containing constants that can be used throughout the server. - - @note This file shall not contain or include any declarations of any kinds. -*/ - -#ifndef SQL_CONST_INCLUDED -#define SQL_CONST_INCLUDED - -#include - -#define LIBLEN FN_REFLEN-FN_LEN /* Max l{ngd p} dev */ -/* extra 4+4 bytes for slave tmp tables */ -#define MAX_DBKEY_LENGTH (NAME_LEN*2+1+1+4+4) -#define MAX_ALIAS_NAME 256 -#define MAX_FIELD_NAME 34 /* Max colum name length +2 */ -#define MAX_SYS_VAR_LENGTH 32 -#define MAX_KEY MAX_INDEXES /* Max used keys */ -#define MAX_REF_PARTS 32 /* Max parts used as ref */ - -/* - Maximum length of the data part of an index lookup key. - - The "data part" is defined as the value itself, not including the - NULL-indicator bytes or varchar length bytes ("the Extras"). We need this - value because there was a bug where length of the Extras were not counted. - - You probably need MAX_KEY_LENGTH, not this constant. -*/ -#define MAX_DATA_LENGTH_FOR_KEY 3072 -#if SIZEOF_OFF_T > 4 -#define MAX_REFLENGTH 8 /* Max length for record ref */ -#else -#define MAX_REFLENGTH 4 /* Max length for record ref */ -#endif -#define MAX_HOSTNAME 61 /* len+1 in mysql.user */ -#define MAX_CONNECTION_NAME NAME_LEN - -#define MAX_MBWIDTH 3 /* Max multibyte sequence */ -#define MAX_FILENAME_MBWIDTH 5 -#define MAX_FIELD_CHARLENGTH 255 -/* - In MAX_FIELD_VARCHARLENGTH we reserve extra bytes for the overhead: - - 2 bytes for the length - - 1 byte for NULL bits - to avoid the "Row size too large" error for these three corner definitions: - CREATE TABLE t1 (c VARBINARY(65533)); - CREATE TABLE t1 (c VARBINARY(65534)); - CREATE TABLE t1 (c VARBINARY(65535)); - Like VARCHAR(65536), they will be converted to BLOB automatically - in non-strict mode. -*/ -#define MAX_FIELD_VARCHARLENGTH (65535-2-1) -#define MAX_FIELD_BLOBLENGTH UINT_MAX32 /* cf field_blob::get_length() */ -#define CONVERT_IF_BIGGER_TO_BLOB 512 /* Threshold *in characters* */ - -/* Max column width +1 */ -#define MAX_FIELD_WIDTH (MAX_FIELD_CHARLENGTH*MAX_MBWIDTH+1) - -#define MAX_BIT_FIELD_LENGTH 64 /* Max length in bits for bit fields */ - -#define MAX_DATE_WIDTH 10 /* YYYY-MM-DD */ -#define MIN_TIME_WIDTH 10 /* -HHH:MM:SS */ -#define MAX_TIME_WIDTH 16 /* -DDDDDD HH:MM:SS */ -#define MAX_TIME_FULL_WIDTH 23 /* -DDDDDD HH:MM:SS.###### */ -#define MAX_DATETIME_FULL_WIDTH 26 /* YYYY-MM-DD HH:MM:SS.###### */ -#define MAX_DATETIME_WIDTH 19 /* YYYY-MM-DD HH:MM:SS */ -#define MAX_DATETIME_COMPRESSED_WIDTH 14 /* YYYYMMDDHHMMSS */ -#define MAX_DATETIME_PRECISION 6 - -#define MAX_TABLES (sizeof(table_map)*8-3) /* Max tables in join */ -#define PARAM_TABLE_BIT (((table_map) 1) << (sizeof(table_map)*8-3)) -#define OUTER_REF_TABLE_BIT (((table_map) 1) << (sizeof(table_map)*8-2)) -#define RAND_TABLE_BIT (((table_map) 1) << (sizeof(table_map)*8-1)) -#define PSEUDO_TABLE_BITS (PARAM_TABLE_BIT | OUTER_REF_TABLE_BIT | \ - RAND_TABLE_BIT) -#define CONNECT_STRING_MAXLEN 65535 /* stored in 2 bytes in .frm */ -#define MAX_FIELDS 4096 /* Limit in the .frm file */ -#define MAX_PARTITIONS 8192 - -#define MAX_SELECT_NESTING (SELECT_NESTING_MAP_SIZE - 1) - -#define MAX_SORT_MEMORY 2048*1024 -#define MIN_SORT_MEMORY 1024 - -/* Some portable defines */ - -#define STRING_BUFFER_USUAL_SIZE 80 - -/* Memory allocated when parsing a statement / saving a statement */ -#define MEM_ROOT_BLOCK_SIZE 8192 -#define MEM_ROOT_PREALLOC 8192 -#define TRANS_MEM_ROOT_BLOCK_SIZE 4096 -#define TRANS_MEM_ROOT_PREALLOC 4096 - -#define DEFAULT_ERROR_COUNT 64 -#define EXTRA_RECORDS 10 /* Extra records in sort */ -#define SCROLL_EXTRA 5 /* Extra scroll-rows. */ -#define FIELD_NAME_USED ((uint) 32768) /* Bit set if fieldname used */ -#define FORM_NAME_USED ((uint) 16384) /* Bit set if formname used */ -#define FIELD_NR_MASK 16383 /* To get fieldnumber */ -#define FERR -1 /* Error from my_functions */ -#define CREATE_MODE 0 /* Default mode on new files */ -#define NAMES_SEP_CHAR 255 /* Char to sep. names */ - -#define READ_RECORD_BUFFER (uint) (IO_SIZE*8) /* Pointer_buffer_size */ -#define DISK_BUFFER_SIZE (uint) (IO_SIZE*16) /* Size of diskbuffer */ - -#define FRM_VER_TRUE_VARCHAR (FRM_VER+4) /* 10 */ -#define FRM_VER_EXPRESSSIONS (FRM_VER+5) /* 11 */ -#define FRM_VER_CURRENT FRM_VER_EXPRESSSIONS - -/*************************************************************************** - Configuration parameters -****************************************************************************/ - -#define ACL_CACHE_SIZE 256 -#define MAX_PASSWORD_LENGTH 32 -#define HOST_CACHE_SIZE 128 -#define MAX_ACCEPT_RETRY 10 // Test accept this many times -#define MAX_FIELDS_BEFORE_HASH 32 -#define USER_VARS_HASH_SIZE 16 -#define SEQUENCES_HASH_SIZE 16 -#define TABLE_OPEN_CACHE_MIN 200 -#define TABLE_OPEN_CACHE_DEFAULT 2000 -#define TABLE_DEF_CACHE_DEFAULT 400 -/** - We must have room for at least 400 table definitions in the table - cache, since otherwise there is no chance prepared - statements that use these many tables can work. - Prepared statements use table definition cache ids (table_map_id) - as table version identifiers. If the table definition - cache size is less than the number of tables used in a statement, - the contents of the table definition cache is guaranteed to rotate - between a prepare and execute. This leads to stable validation - errors. In future we shall use more stable version identifiers, - for now the only solution is to ensure that the table definition - cache can contain at least all tables of a given statement. -*/ -#define TABLE_DEF_CACHE_MIN 400 - -/** - Maximum number of connections default value. - 151 is larger than Apache's default max children, - to avoid "too many connections" error in a common setup. -*/ -#define MAX_CONNECTIONS_DEFAULT 151 - -/* - Stack reservation. - Feel free to raise this by the smallest amount you can to get the - "execution_constants" test to pass. -*/ -#define STACK_MIN_SIZE 16000 // Abort if less stack during eval. - -#define STACK_MIN_SIZE_FOR_OPEN (1024*80) -#define STACK_BUFF_ALLOC 352 ///< For stack overrun checks -#ifndef MYSQLD_NET_RETRY_COUNT -#define MYSQLD_NET_RETRY_COUNT 10 ///< Abort read after this many int. -#endif - -#define QUERY_ALLOC_BLOCK_SIZE 16384 -#define QUERY_ALLOC_PREALLOC_SIZE 24576 -#define TRANS_ALLOC_BLOCK_SIZE 8192 -#define TRANS_ALLOC_PREALLOC_SIZE 4096 -#define RANGE_ALLOC_BLOCK_SIZE 4096 -#define ACL_ALLOC_BLOCK_SIZE 1024 -#define UDF_ALLOC_BLOCK_SIZE 1024 -#define TABLE_ALLOC_BLOCK_SIZE 1024 -#define WARN_ALLOC_BLOCK_SIZE 2048 -#define WARN_ALLOC_PREALLOC_SIZE 1024 -/* - Note that if we are using 32K or less, then TCmalloc will use a local - heap without locks! -*/ -#define SHOW_ALLOC_BLOCK_SIZE (32768-MALLOC_OVERHEAD) - -/* - The following parameters is to decide when to use an extra cache to - optimise seeks when reading a big table in sorted order -*/ -#define MIN_FILE_LENGTH_TO_USE_ROW_CACHE (10L*1024*1024) -#define MIN_ROWS_TO_USE_TABLE_CACHE 100 -#define MIN_ROWS_TO_USE_BULK_INSERT 100 - -/** - The following is used to decide if MySQL should use table scanning - instead of reading with keys. The number says how many evaluation of the - WHERE clause is comparable to reading one extra row from a table. -*/ -#define TIME_FOR_COMPARE 5.0 // 5 WHERE compares == one read -#define TIME_FOR_COMPARE_IDX 20.0 - -#define IDX_BLOCK_COPY_COST ((double) 1 / TIME_FOR_COMPARE) -#define IDX_LOOKUP_COST ((double) 1 / 8) -#define MULTI_RANGE_READ_SETUP_COST (IDX_BLOCK_COPY_COST/10) - -/** - Number of comparisons of table rowids equivalent to reading one row from a - table. -*/ -#define TIME_FOR_COMPARE_ROWID (TIME_FOR_COMPARE*100) - -/* cost1 is better that cost2 only if cost1 + COST_EPS < cost2 */ -#define COST_EPS 0.001 - -/* - For sequential disk seeks the cost formula is: - DISK_SEEK_BASE_COST + DISK_SEEK_PROP_COST * #blocks_to_skip - - The cost of average seek - DISK_SEEK_BASE_COST + DISK_SEEK_PROP_COST*BLOCKS_IN_AVG_SEEK =1.0. -*/ -#define DISK_SEEK_BASE_COST ((double)0.9) - -#define BLOCKS_IN_AVG_SEEK 128 - -#define DISK_SEEK_PROP_COST ((double)0.1/BLOCKS_IN_AVG_SEEK) - - -/** - Number of rows in a reference table when refereed through a not unique key. - This value is only used when we don't know anything about the key - distribution. -*/ -#define MATCHING_ROWS_IN_OTHER_TABLE 10 - -/* - Subquery materialization-related constants -*/ -#define HEAP_TEMPTABLE_LOOKUP_COST 0.05 -#define DISK_TEMPTABLE_LOOKUP_COST 1.0 -#define SORT_INDEX_CMP_COST 0.02 - - -#define COST_MAX (DBL_MAX * (1.0 - DBL_EPSILON)) - -#define COST_ADD(c,d) (COST_MAX - (d) > (c) ? (c) + (d) : COST_MAX) - -#define COST_MULT(c,f) (COST_MAX / (f) > (c) ? (c) * (f) : COST_MAX) - - -#define MY_CHARSET_BIN_MB_MAXLEN 1 - -/** Don't pack string keys shorter than this (if PACK_KEYS=1 isn't used). */ -#define KEY_DEFAULT_PACK_LENGTH 8 - -/** Characters shown for the command in 'show processlist'. */ -#define PROCESS_LIST_WIDTH 100 -/* Characters shown for the command in 'information_schema.processlist' */ -#define PROCESS_LIST_INFO_WIDTH 65535 - -#define PRECISION_FOR_DOUBLE 53 -#define PRECISION_FOR_FLOAT 24 - -/* -[digits].E+## */ -#define MAX_FLOAT_STR_LENGTH (FLT_DIG + 6) -/* -[digits].E+### */ -#define MAX_DOUBLE_STR_LENGTH (DBL_DIG + 7) - -/* - Default time to wait before aborting a new client connection - that does not respond to "initial server greeting" timely -*/ -#define CONNECT_TIMEOUT 10 - /* Wait 5 minutes before removing thread from thread cache */ -#define THREAD_CACHE_TIMEOUT 5*60 - -/* The following can also be changed from the command line */ -#define DEFAULT_CONCURRENCY 10 -#define DELAYED_LIMIT 100 /**< pause after xxx inserts */ -#define DELAYED_QUEUE_SIZE 1000 -#define DELAYED_WAIT_TIMEOUT (5*60) /**< Wait for delayed insert */ -#define MAX_CONNECT_ERRORS 100 ///< errors before disabling host - -#define LONG_TIMEOUT ((ulong) 3600L*24L*365L) - -/** - Maximum length of time zone name that we support (Time zone name is - char(64) in db). mysqlbinlog needs it. -*/ -#define MAX_TIME_ZONE_NAME_LENGTH (NAME_LEN + 1) - -#if defined(__WIN__) - -#define INTERRUPT_PRIOR -2 -#define CONNECT_PRIOR -1 -#define WAIT_PRIOR 0 -#define QUERY_PRIOR 2 -#else -#define INTERRUPT_PRIOR 10 -#define CONNECT_PRIOR 9 -#define WAIT_PRIOR 8 -#define QUERY_PRIOR 6 -#endif /* __WIN92__ */ - -#define SP_PSI_STATEMENT_INFO_COUNT 19 - -#endif /* SQL_CONST_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_crypt.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_crypt.h deleted file mode 100644 index 3c90550..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_crypt.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef SQL_CRYPT_INCLUDED -#define SQL_CRYPT_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_alloc.h" /* Sql_alloc */ -#include "my_rnd.h" /* rand_struct */ - -class SQL_CRYPT :public Sql_alloc -{ - struct my_rnd_struct rand,org_rand; - char decode_buff[256],encode_buff[256]; - uint shift; - public: - SQL_CRYPT() {} - SQL_CRYPT(ulong *seed) - { - init(seed); - } - ~SQL_CRYPT() {} - void init(ulong *seed); - void reinit() { shift=0; rand=org_rand; } - void encode(char *str, uint length); - void decode(char *str, uint length); -}; - -#endif /* SQL_CRYPT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cte.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cte.h deleted file mode 100644 index 4c42dd2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cte.h +++ /dev/null @@ -1,475 +0,0 @@ -/* - Copyright (c) 2016, 2017 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef SQL_CTE_INCLUDED -#define SQL_CTE_INCLUDED -#include "sql_list.h" -#include "sql_lex.h" -#include "sql_select.h" - -class select_unit; -struct st_unit_ctxt_elem; - - -/** - @class With_element - @brief Definition of a CTE table - - It contains a reference to the name of the table introduced by this with element, - and a reference to the unit that specificies this table. Also it contains - a reference to the with clause to which this element belongs to. -*/ - -class With_element : public Sql_alloc -{ -private: - With_clause *owner; // with clause this object belongs to - With_element *next; // next element in the with clause - uint number; // number of the element in the with clause (starting from 0) - table_map elem_map; // The map where with only one 1 set in this->number - /* - The map base_dep_map has 1 in the i-th position if the query that - specifies this with element contains a reference to the with element number i - in the query FROM list. - (In this case this with element depends directly on the i-th with element.) - */ - table_map base_dep_map; - /* - The map derived_dep_map has 1 in i-th position if this with element depends - directly or indirectly from the i-th with element. - */ - table_map derived_dep_map; - /* - The map sq_dep_map has 1 in i-th position if there is a reference to this - with element somewhere in subqueries of the specifications of the tables - defined in the with clause containing this element; - */ - table_map sq_dep_map; - table_map work_dep_map; // dependency map used for work - /* Dependency map of with elements mutually recursive with this with element */ - table_map mutually_recursive; - /* - Dependency map built only for the top level references i.e. for those that - are encountered in from lists of the selects of the specification unit - */ - table_map top_level_dep_map; - /* - Points to a recursive reference in subqueries. - Used only for specifications without recursive references on the top level. - */ - TABLE_LIST *sq_rec_ref; - /* - The next with element from the circular chain of the with elements - mutually recursive with this with element. - (If This element is simply recursive than next_mutually_recursive contains - the pointer to itself. If it's not recursive than next_mutually_recursive - is set to NULL.) - */ - With_element *next_mutually_recursive; - /* - Total number of references to this element in the FROM lists of - the queries that are in the scope of the element (including - subqueries and specifications of other with elements). - */ - uint references; - /* - Unparsed specification of the query that specifies this element. - It used to build clones of the specification if they are needed. - */ - LEX_CSTRING unparsed_spec; - /* Offset of the specification in the input string */ - my_ptrdiff_t unparsed_spec_offset; - - /* True if the with element is used a prepared statement */ - bool stmt_prepare_mode; - - /* Return the map where 1 is set only in the position for this element */ - table_map get_elem_map() { return (table_map) 1 << number; } - -public: - /* - The name of the table introduced by this with elememt. The name - can be used in FROM lists of the queries in the scope of the element. - */ - LEX_CSTRING *query_name; - /* - Optional list of column names to name the columns of the table introduced - by this with element. It is used in the case when the names are not - inherited from the query that specified the table. Otherwise the list is - always empty. - */ - List column_list; - List *cycle_list; - /* The query that specifies the table introduced by this with element */ - st_select_lex_unit *spec; - /* - Set to true is recursion is used (directly or indirectly) - for the definition of this element - */ - bool is_recursive; - /* - For a simple recursive CTE: the number of references to the CTE from - outside of the CTE specification. - For a CTE mutually recursive with other CTEs : the total number of - references to all these CTEs outside of their specification. - Each of these mutually recursive CTEs has the same value in this field. - */ - uint rec_outer_references; - /* - Any non-recursive select in the specification of a recursive - with element is a called anchor. In the case mutually recursive - elements the specification of some them may be without any anchor. - Yet at least one of them must contain an anchor. - All anchors of any recursivespecification are moved ahead before - the prepare stage. - */ - /* Set to true if this is a recursive element with an anchor */ - bool with_anchor; - /* - Set to the first recursive select of the unit specifying the element - after all anchor have been moved to the head of the unit. - */ - st_select_lex *first_recursive; - - /* - The number of the last performed iteration for recursive table - (the number of the initial non-recursive step is 0, the number - of the first iteration is 1). - */ - uint level; - - /* - The pointer to the object used to materialize this with element - if it's recursive. This object is built at the end of prepare - stage and is used at the execution stage. - */ - select_union_recursive *rec_result; - - /* List of Item_subselects containing recursive references to this CTE */ - SQL_I_List sq_with_rec_ref; - /* List of derived tables containing recursive references to this CTE */ - SQL_I_List derived_with_rec_ref; - - With_element(LEX_CSTRING *name, - List list, - st_select_lex_unit *unit) - : next(NULL), base_dep_map(0), derived_dep_map(0), - sq_dep_map(0), work_dep_map(0), mutually_recursive(0), - top_level_dep_map(0), sq_rec_ref(NULL), - next_mutually_recursive(NULL), references(0), - query_name(name), column_list(list), cycle_list(0), spec(unit), - is_recursive(false), rec_outer_references(0), with_anchor(false), - level(0), rec_result(NULL) - { unit->with_element= this; } - - bool check_dependencies_in_spec(); - - void check_dependencies_in_select(st_select_lex *sl, st_unit_ctxt_elem *ctxt, - bool in_subq, table_map *dep_map); - - void check_dependencies_in_unit(st_select_lex_unit *unit, - st_unit_ctxt_elem *ctxt, - bool in_subq, - table_map *dep_map); - - void check_dependencies_in_with_clause(With_clause *with_clause, - st_unit_ctxt_elem *ctxt, - bool in_subq, - table_map *dep_map); - - void set_dependency_on(With_element *with_elem) - { base_dep_map|= with_elem->get_elem_map(); } - - bool check_dependency_on(With_element *with_elem) - { return base_dep_map & with_elem->get_elem_map(); } - - TABLE_LIST *find_first_sq_rec_ref_in_select(st_select_lex *sel); - - bool set_unparsed_spec(THD *thd, const char *spec_start, const char *spec_end, - my_ptrdiff_t spec_offset); - - st_select_lex_unit *clone_parsed_spec(THD *thd, TABLE_LIST *with_table); - - bool is_referenced() { return references != 0; } - - void inc_references() { references++; } - - bool process_columns_of_derived_unit(THD *thd, st_select_lex_unit *unit); - - bool prepare_unreferenced(THD *thd); - - bool check_unrestricted_recursive(st_select_lex *sel, - table_map &unrestricted, - table_map &encountered); - - void print(THD *thd, String *str, enum_query_type query_type); - - With_clause *get_owner() { return owner; } - - bool contains_sq_with_recursive_reference() - { return sq_dep_map & mutually_recursive; } - - bool no_rec_ref_on_top_level() - { return !(top_level_dep_map & mutually_recursive); } - - table_map get_mutually_recursive() { return mutually_recursive; } - - With_element *get_next_mutually_recursive() - { return next_mutually_recursive; } - - TABLE_LIST *get_sq_rec_ref() { return sq_rec_ref; } - - bool is_anchor(st_select_lex *sel); - - void move_anchors_ahead(); - - bool is_unrestricted(); - - bool is_with_prepared_anchor(); - - void mark_as_with_prepared_anchor(); - - bool is_cleaned(); - - void mark_as_cleaned(); - - void reset_recursive_for_exec(); - - void cleanup_stabilized(); - - void set_as_stabilized(); - - bool is_stabilized(); - - bool all_are_stabilized(); - - bool instantiate_tmp_tables(); - - void prepare_for_next_iteration(); - - void set_cycle_list(List *cycle_list_arg); - - friend class With_clause; -}; - -const uint max_number_of_elements_in_with_clause= sizeof(table_map)*8; - -/** - @class With_clause - @brief Set of with_elements - - It has a reference to the first with element from this with clause. - This reference allows to navigate through all the elements of the with clause. - It contains a reference to the unit to which this with clause is attached. - It also contains a flag saying whether this with clause was specified as recursive. -*/ - -class With_clause : public Sql_alloc -{ -private: - st_select_lex_unit *owner; // the unit this with clause attached to - - /* The list of all with elements from this with clause */ - SQL_I_List with_list; - /* - The with clause immediately containing this with clause if there is any, - otherwise NULL. Now used only at parsing. - */ - With_clause *embedding_with_clause; - /* - The next with the clause of the chain of with clauses encountered - in the current statement - */ - With_clause *next_with_clause; - /* Set to true if dependencies between with elements have been checked */ - bool dependencies_are_checked; - /* - The bitmap of all recursive with elements whose specifications - are not complied with restrictions imposed by the SQL standards - on recursive specifications. - */ - table_map unrestricted; - /* - The bitmap of all recursive with elements whose anchors - has been already prepared. - */ - table_map with_prepared_anchor; - table_map cleaned; - /* - The bitmap of all recursive with elements that - has been already materialized - */ - table_map stabilized; - -public: - /* If true the specifier RECURSIVE is present in the with clause */ - bool with_recursive; - - With_clause(bool recursive_fl, With_clause *emb_with_clause) - : owner(NULL), embedding_with_clause(emb_with_clause), - next_with_clause(NULL), dependencies_are_checked(false), unrestricted(0), - with_prepared_anchor(0), cleaned(0), stabilized(0), - with_recursive(recursive_fl) - { } - - bool add_with_element(With_element *elem); - - /* Add this with clause to the list of with clauses used in the statement */ - void add_to_list(With_clause ** &last_next) - { - *last_next= this; - last_next= &this->next_with_clause; - } - - st_select_lex_unit *get_owner() { return owner; } - - void set_owner(st_select_lex_unit *unit) { owner= unit; } - - void attach_to(st_select_lex *select_lex); - - With_clause *pop() { return embedding_with_clause; } - - bool check_dependencies(); - - bool check_anchors(); - - void move_anchors_ahead(); - - With_element *find_table_def(TABLE_LIST *table, With_element *barrier); - - With_element *find_table_def_in_with_clauses(TABLE_LIST *table); - - bool prepare_unreferenced_elements(THD *thd); - - void add_unrestricted(table_map map) { unrestricted|= map; } - - void print(THD *thd, String *str, enum_query_type query_type); - - friend class With_element; - - friend - bool - check_dependencies_in_with_clauses(With_clause *with_clauses_list); -}; - -inline -bool With_element::is_unrestricted() -{ - return owner->unrestricted & get_elem_map(); -} - -inline -bool With_element::is_with_prepared_anchor() -{ - return owner->with_prepared_anchor & get_elem_map(); -} - -inline -void With_element::mark_as_with_prepared_anchor() -{ - owner->with_prepared_anchor|= mutually_recursive; -} - - -inline -bool With_element::is_cleaned() -{ - return owner->cleaned & get_elem_map(); -} - - -inline -void With_element::mark_as_cleaned() -{ - owner->cleaned|= get_elem_map(); -} - - -inline -void With_element::reset_recursive_for_exec() -{ - DBUG_ASSERT(is_recursive); - level= 0; - owner->with_prepared_anchor&= ~mutually_recursive; - owner->cleaned&= ~get_elem_map(); - cleanup_stabilized(); - spec->columns_are_renamed= false; -} - - - -inline -void With_element::cleanup_stabilized() -{ - owner->stabilized&= ~mutually_recursive; -} - - -inline -void With_element::set_as_stabilized() -{ - owner->stabilized|= get_elem_map(); -} - - -inline -bool With_element::is_stabilized() -{ - return owner->stabilized & get_elem_map(); -} - - -inline -bool With_element::all_are_stabilized() -{ - return (owner->stabilized & mutually_recursive) == mutually_recursive; -} - - -inline -void With_element::prepare_for_next_iteration() -{ - With_element *with_elem= this; - while ((with_elem= with_elem->get_next_mutually_recursive()) != this) - { - TABLE *rec_table= with_elem->rec_result->first_rec_table_to_update; - if (rec_table) - rec_table->reginfo.join_tab->preread_init_done= false; - } -} - - -inline -void With_clause::attach_to(st_select_lex *select_lex) -{ - for (With_element *with_elem= with_list.first; - with_elem; - with_elem= with_elem->next) - { - select_lex->register_unit(with_elem->spec, NULL); - } -} - - -inline -void st_select_lex::set_with_clause(With_clause *with_clause) -{ - master_unit()->with_clause= with_clause; - if (with_clause) - with_clause->set_owner(master_unit()); -} - -#endif /* SQL_CTE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cursor.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cursor.h deleted file mode 100644 index 00b9cd4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_cursor.h +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _sql_cursor_h_ -#define _sql_cursor_h_ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class interface */ -#endif - -#include "sql_class.h" /* Query_arena */ - -class JOIN; - -/** - @file - - Declarations for implementation of server side cursors. Only - read-only non-scrollable cursors are currently implemented. -*/ - -/** - Server_side_cursor -- an interface for materialized - implementation of cursors. All cursors are self-contained - (created in their own memory root). For that reason they must - be deleted only using a pointer to Server_side_cursor, not to - its base class. -*/ - -class Server_side_cursor: protected Query_arena, public Sql_alloc -{ -protected: - /** Row destination used for fetch */ - select_result *result; -public: - Server_side_cursor(MEM_ROOT *mem_root_arg, select_result *result_arg) - :Query_arena(mem_root_arg, STMT_INITIALIZED), result(result_arg) - {} - - virtual bool is_open() const= 0; - - virtual int open(JOIN *top_level_join)= 0; - virtual void fetch(ulong num_rows)= 0; - virtual void close()= 0; - virtual bool export_structure(THD *thd, Row_definition_list *defs) - { - DBUG_ASSERT(0); - return true; - } - virtual ~Server_side_cursor(); - - static void operator delete(void *ptr, size_t size); - static void operator delete(void *, MEM_ROOT *){} -}; - - -int mysql_open_cursor(THD *thd, select_result *result, - Server_side_cursor **res); - -#endif /* _sql_cusor_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_db.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_db.h deleted file mode 100644 index c9f1ed0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_db.h +++ /dev/null @@ -1,52 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_DB_INCLUDED -#define SQL_DB_INCLUDED - -#include "hash.h" /* HASH */ - -class THD; - -int mysql_create_db(THD *thd, const LEX_CSTRING *db, DDL_options_st options, - const Schema_specification_st *create); -bool mysql_alter_db(THD *thd, const LEX_CSTRING *db, - const Schema_specification_st *create); -bool mysql_rm_db(THD *thd, const LEX_CSTRING *db, bool if_exists); -bool mysql_upgrade_db(THD *thd, const LEX_CSTRING *old_db); -uint mysql_change_db(THD *thd, const LEX_CSTRING *new_db_name, - bool force_switch); - -bool mysql_opt_change_db(THD *thd, - const LEX_CSTRING *new_db_name, - LEX_STRING *saved_db_name, - bool force_switch, - bool *cur_db_changed); -bool my_dboptions_cache_init(void); -void my_dboptions_cache_free(void); -bool check_db_dir_existence(const char *db_name); -bool load_db_opt(THD *thd, const char *path, Schema_specification_st *create); -bool load_db_opt_by_name(THD *thd, const char *db_name, - Schema_specification_st *db_create_info); -CHARSET_INFO *get_default_db_collation(THD *thd, const char *db_name); -bool my_dbopt_init(void); -void my_dbopt_cleanup(void); - -const char *normalize_db_name(const char *db, char *buffer, - size_t buffer_size); - -#define MY_DB_OPT_FILE "db.opt" - -#endif /* SQL_DB_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_delete.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_delete.h deleted file mode 100644 index 520524c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_delete.h +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_DELETE_INCLUDED -#define SQL_DELETE_INCLUDED - -#include "my_base.h" /* ha_rows */ - -class THD; -struct TABLE_LIST; -class Item; -class select_result; - -typedef class Item COND; -template class SQL_I_List; - -int mysql_prepare_delete(THD *thd, TABLE_LIST *table_list, Item **conds, - bool *delete_while_scanning); -bool mysql_delete(THD *thd, TABLE_LIST *table_list, COND *conds, - SQL_I_List *order, ha_rows rows, - ulonglong options, select_result *result); - -#endif /* SQL_DELETE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_derived.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_derived.h deleted file mode 100644 index 403277d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_derived.h +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_DERIVED_INCLUDED -#define SQL_DERIVED_INCLUDED - -struct TABLE_LIST; -class THD; -struct LEX; - -bool mysql_handle_derived(LEX *lex, uint phases); -bool mysql_handle_single_derived(LEX *lex, TABLE_LIST *derived, uint phases); - -bool pushdown_cond_for_derived(THD *thd, Item *cond, TABLE_LIST *derived); - -#endif /* SQL_DERIVED_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_digest.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_digest.h deleted file mode 100644 index cc786a3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_digest.h +++ /dev/null @@ -1,129 +0,0 @@ -/* Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_DIGEST_H -#define SQL_DIGEST_H - -#include -class String; -#include "my_md5.h" - -#define MAX_DIGEST_STORAGE_SIZE (1024*1024) - -/** - Structure to store token count/array for a statement - on which digest is to be calculated. -*/ -struct sql_digest_storage -{ - bool m_full; - uint m_byte_count; - unsigned char m_md5[MD5_HASH_SIZE]; - /** Character set number. */ - uint m_charset_number; - /** - Token array. - Token array is an array of bytes to store tokens received during parsing. - Following is the way token array is formed. - ... <non-id-token> <non-id-token> <id-token> <id_len> <id_text> ... - For Example: - SELECT * FROM T1; - <SELECT_TOKEN> <*> <FROM_TOKEN> <ID_TOKEN> <2> <T1> - - @note Only the first @c m_byte_count bytes are initialized, - out of @c m_token_array_length. - */ - unsigned char *m_token_array; - /* Length of the token array to be considered for DIGEST_TEXT calculation. */ - uint m_token_array_length; - - sql_digest_storage() - { - reset(NULL, 0); - } - - inline void reset(unsigned char *token_array, size_t length) - { - m_token_array= token_array; - m_token_array_length= (uint)length; - reset(); - } - - inline void reset() - { - m_full= false; - m_byte_count= 0; - m_charset_number= 0; - memset(m_md5, 0, MD5_HASH_SIZE); - } - - inline bool is_empty() - { - return (m_byte_count == 0); - } - - inline void copy(const sql_digest_storage *from) - { - /* - Keep in mind this is a dirty copy of something that may change, - as the thread producing the digest is executing concurrently, - without any lock enforced. - */ - uint byte_count_copy= m_token_array_length < from->m_byte_count ? - m_token_array_length : from->m_byte_count; - - if (byte_count_copy > 0) - { - m_full= from->m_full; - m_byte_count= byte_count_copy; - m_charset_number= from->m_charset_number; - memcpy(m_token_array, from->m_token_array, m_byte_count); - memcpy(m_md5, from->m_md5, MD5_HASH_SIZE); - } - else - { - m_full= false; - m_byte_count= 0; - m_charset_number= 0; - } - } -}; -typedef struct sql_digest_storage sql_digest_storage; - -/** - Compute a digest hash. - @param digest_storage The digest - @param [out] md5 The computed digest hash. This parameter is a buffer of size @c MD5_HASH_SIZE. -*/ -void compute_digest_md5(const sql_digest_storage *digest_storage, unsigned char *md5); - -/** - Compute a digest text. - A 'digest text' is a textual representation of a query, - where: - - comments are removed, - - non significant spaces are removed, - - literal values are replaced with a special '?' marker, - - lists of values are collapsed using a shorter notation - @param digest_storage The digest - @param [out] digest_text - @param digest_text_length Size of @c digest_text. - @param [out] truncated true if the text representation was truncated -*/ -void compute_digest_text(const sql_digest_storage *digest_storage, - String *digest_text); - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_digest_stream.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_digest_stream.h deleted file mode 100644 index 75e534e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_digest_stream.h +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_DIGEST_STREAM_H -#define SQL_DIGEST_STREAM_H - -#include "sql_digest.h" - -/** - State data storage for @c digest_start, @c digest_add_token. - This structure extends the @c sql_digest_storage structure - with temporary state used only during parsing. -*/ -struct sql_digest_state -{ - /** - Index, in the digest token array, of the last identifier seen. - Reduce rules used in the digest computation can not - apply to tokens seen before an identifier. - @sa digest_add_token - */ - int m_last_id_index; - sql_digest_storage m_digest_storage; - - inline void reset(unsigned char *token_array, uint length) - { - m_last_id_index= 0; - m_digest_storage.reset(token_array, length); - } - - inline bool is_empty() - { - return m_digest_storage.is_empty(); - } -}; -typedef struct sql_digest_state sql_digest_state; - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_do.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_do.h deleted file mode 100644 index 5280a4a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_do.h +++ /dev/null @@ -1,26 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_DO_INCLUDED -#define SQL_DO_INCLUDED - -#include "sql_list.h" /* List */ - -class THD; -class Item; - -bool mysql_do(THD *thd, List &values); - -#endif /* SQL_DO_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_error.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_error.h deleted file mode 100644 index a0497af..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_error.h +++ /dev/null @@ -1,1294 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_ERROR_H -#define SQL_ERROR_H - -#include "sql_list.h" /* Sql_alloc, MEM_ROOT, list */ -#include "sql_type_int.h" // Longlong_hybrid -#include "sql_string.h" /* String */ -#include "sql_plist.h" /* I_P_List */ -#include "mysql_com.h" /* MYSQL_ERRMSG_SIZE */ -#include "my_time.h" /* MYSQL_TIME */ -#include "decimal.h" - -class THD; -class my_decimal; -class sp_condition_value; - -/////////////////////////////////////////////////////////////////////////// - -class Sql_state -{ -protected: - /** - This member is always NUL terminated. - */ - char m_sqlstate[SQLSTATE_LENGTH + 1]; -public: - Sql_state() - { - memset(m_sqlstate, 0, sizeof(m_sqlstate)); - } - - Sql_state(const char *sqlstate) - { - set_sqlstate(sqlstate); - } - - const char* get_sqlstate() const - { return m_sqlstate; } - - void set_sqlstate(const Sql_state *other) - { - *this= *other; - } - void set_sqlstate(const char *sqlstate) - { - memcpy(m_sqlstate, sqlstate, SQLSTATE_LENGTH); - m_sqlstate[SQLSTATE_LENGTH]= '\0'; - } - bool eq(const Sql_state *other) const - { - return strcmp(m_sqlstate, other->m_sqlstate) == 0; - } - - bool has_sql_state() const { return m_sqlstate[0] != '\0'; } - - /** - Checks if this SQL state defines a WARNING condition. - Note: m_sqlstate must contain a valid SQL-state. - - @retval true if this SQL state defines a WARNING condition. - @retval false otherwise. - */ - inline bool is_warning() const - { return m_sqlstate[0] == '0' && m_sqlstate[1] == '1'; } - - - /** - Checks if this SQL state defines a NOT FOUND condition. - Note: m_sqlstate must contain a valid SQL-state. - - @retval true if this SQL state defines a NOT FOUND condition. - @retval false otherwise. - */ - inline bool is_not_found() const - { return m_sqlstate[0] == '0' && m_sqlstate[1] == '2'; } - - - /** - Checks if this SQL state defines an EXCEPTION condition. - Note: m_sqlstate must contain a valid SQL-state. - - @retval true if this SQL state defines an EXCEPTION condition. - @retval false otherwise. - */ - inline bool is_exception() const - { return m_sqlstate[0] != '0' || m_sqlstate[1] > '2'; } - -}; - - -class Sql_state_errno: public Sql_state -{ -protected: - /** - MySQL extension, MYSQL_ERRNO condition item. - SQL error number. One of ER_ codes from share/errmsg.txt. - Set by set_error_status. - */ - uint m_sql_errno; - -public: - Sql_state_errno() - :m_sql_errno(0) - { } - Sql_state_errno(uint sql_errno) - :m_sql_errno(sql_errno) - { } - Sql_state_errno(uint sql_errno, const char *sql_state) - :Sql_state(sql_state), - m_sql_errno(sql_errno) - { } - /** - Get the SQL_ERRNO of this condition. - @return the sql error number condition item. - */ - uint get_sql_errno() const - { return m_sql_errno; } - - void set(uint sql_errno, const char *sqlstate) - { - m_sql_errno= sql_errno; - set_sqlstate(sqlstate); - } - void clear() - { - m_sql_errno= 0; - } -}; - - -class Sql_state_errno_level: public Sql_state_errno -{ -public: - /* - Enumeration value describing the severity of the error. - - Note that these enumeration values must correspond to the indices - of the sql_print_message_handlers array. - */ - enum enum_warning_level - { WARN_LEVEL_NOTE, WARN_LEVEL_WARN, WARN_LEVEL_ERROR, WARN_LEVEL_END}; - -protected: - /** Severity (error, warning, note) of this condition. */ - enum_warning_level m_level; - - void assign_defaults(const Sql_state_errno *value); - -public: - /** - Get the error level of this condition. - @return the error level condition item. - */ - enum_warning_level get_level() const - { return m_level; } - - Sql_state_errno_level() - :m_level(WARN_LEVEL_ERROR) - { } - - Sql_state_errno_level(uint sqlerrno, const char* sqlstate, - enum_warning_level level) - :Sql_state_errno(sqlerrno, sqlstate), - m_level(level) - { } - Sql_state_errno_level(const Sql_state_errno &state_errno, - enum_warning_level level) - :Sql_state_errno(state_errno), - m_level(level) - { } - void clear() - { - m_level= WARN_LEVEL_ERROR; - Sql_state_errno::clear(); - } -}; - - -/* - class Sql_user_condition_identity. - Instances of this class uniquely idetify user defined conditions (EXCEPTION). - - SET sql_mode=ORACLE; - CREATE PROCEDURE p1 - AS - a EXCEPTION; - BEGIN - RAISE a; - EXCEPTION - WHEN a THEN NULL; - END; - - Currently a user defined condition is identified by a pointer to - its parse time sp_condition_value instance. This can change when - we add packages. See MDEV-10591. -*/ -class Sql_user_condition_identity -{ -protected: - const sp_condition_value *m_user_condition_value; -public: - Sql_user_condition_identity() - :m_user_condition_value(NULL) - { } - Sql_user_condition_identity(const sp_condition_value *value) - :m_user_condition_value(value) - { } - const sp_condition_value *get_user_condition_value() const - { return m_user_condition_value; } - - void set(const Sql_user_condition_identity &identity) - { - *this= identity; - } - void clear() - { - m_user_condition_value= NULL; - } -}; - - -/** - class Sql_condition_identity. - Instances of this class uniquely identify conditions - (including user-defined exceptions for sql_mode=ORACLE) - and store everything that is needed for handler search - purposes in sp_pcontext::find_handler(). -*/ -class Sql_condition_identity: public Sql_state_errno_level, - public Sql_user_condition_identity -{ -public: - Sql_condition_identity() - { } - Sql_condition_identity(const Sql_state_errno_level &st, - const Sql_user_condition_identity &ucid) - :Sql_state_errno_level(st), - Sql_user_condition_identity(ucid) - { } - Sql_condition_identity(const Sql_state_errno &st, - enum_warning_level level, - const Sql_user_condition_identity &ucid) - :Sql_state_errno_level(st, level), - Sql_user_condition_identity(ucid) - { } - Sql_condition_identity(uint sqlerrno, - const char* sqlstate, - enum_warning_level level, - const Sql_user_condition_identity &ucid) - :Sql_state_errno_level(sqlerrno, sqlstate, level), - Sql_user_condition_identity(ucid) - { } - void clear() - { - Sql_state_errno_level::clear(); - Sql_user_condition_identity::clear(); - } -}; - - -class Sql_condition_items -{ -protected: - /** SQL CLASS_ORIGIN condition item. */ - String m_class_origin; - - /** SQL SUBCLASS_ORIGIN condition item. */ - String m_subclass_origin; - - /** SQL CONSTRAINT_CATALOG condition item. */ - String m_constraint_catalog; - - /** SQL CONSTRAINT_SCHEMA condition item. */ - String m_constraint_schema; - - /** SQL CONSTRAINT_NAME condition item. */ - String m_constraint_name; - - /** SQL CATALOG_NAME condition item. */ - String m_catalog_name; - - /** SQL SCHEMA_NAME condition item. */ - String m_schema_name; - - /** SQL TABLE_NAME condition item. */ - String m_table_name; - - /** SQL COLUMN_NAME condition item. */ - String m_column_name; - - /** SQL CURSOR_NAME condition item. */ - String m_cursor_name; - - Sql_condition_items() - :m_class_origin((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_subclass_origin((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_constraint_catalog((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_constraint_schema((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_constraint_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_catalog_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_schema_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_table_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_column_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), - m_cursor_name((const char*) NULL, 0, & my_charset_utf8mb3_bin) - { } - - void clear() - { - m_class_origin.length(0); - m_subclass_origin.length(0); - m_constraint_catalog.length(0); - m_constraint_schema.length(0); - m_constraint_name.length(0); - m_catalog_name.length(0); - m_schema_name.length(0); - m_table_name.length(0); - m_column_name.length(0); - m_cursor_name.length(0); - } -}; - - -/** - Representation of a SQL condition. - A SQL condition can be a completion condition (note, warning), - or an exception condition (error, not found). -*/ -class Sql_condition : public Sql_alloc, - public Sql_condition_identity, - public Sql_condition_items -{ -public: - - /** - Convert a bitmask consisting of MYSQL_TIME_{NOTE|WARN}_XXX bits - to WARN_LEVEL_XXX - */ - static enum_warning_level time_warn_level(uint warnings) - { - return MYSQL_TIME_WARN_HAVE_WARNINGS(warnings) ? - WARN_LEVEL_WARN : WARN_LEVEL_NOTE; - } - - /** - Get the MESSAGE_TEXT of this condition. - @return the message text. - */ - const char* get_message_text() const; - - /** - Get the MESSAGE_OCTET_LENGTH of this condition. - @return the length in bytes of the message text. - */ - int get_message_octet_length() const; - -private: - /* - The interface of Sql_condition is mostly private, by design, - so that only the following code: - - various raise_error() or raise_warning() methods in class THD, - - the implementation of SIGNAL / RESIGNAL / GET DIAGNOSTICS - - catch / re-throw of SQL conditions in stored procedures (sp_rcontext) - is allowed to create / modify a SQL condition. - Enforcing this policy prevents confusion, since the only public - interface available to the rest of the server implementation - is the interface offered by the THD methods (THD::raise_error()), - which should be used. - */ - friend class THD; - friend class Warning_info; - friend class Sql_cmd_common_signal; - friend class Sql_cmd_signal; - friend class Sql_cmd_resignal; - friend class sp_rcontext; - friend class Condition_information_item; - - /** - Default constructor. - This constructor is usefull when allocating arrays. - Note that the init() method should be called to complete the Sql_condition. - */ - Sql_condition() - :m_mem_root(NULL) - { } - - /** - Complete the Sql_condition initialisation. - @param mem_root The memory root to use for the condition items - of this condition - */ - void init(MEM_ROOT *mem_root) - { - DBUG_ASSERT(mem_root != NULL); - DBUG_ASSERT(m_mem_root == NULL); - m_mem_root= mem_root; - } - - /** - Constructor. - @param mem_root The memory root to use for the condition items - of this condition - */ - Sql_condition(MEM_ROOT *mem_root) - :m_mem_root(mem_root) - { - DBUG_ASSERT(mem_root != NULL); - } - - Sql_condition(MEM_ROOT *mem_root, const Sql_user_condition_identity &ucid) - :Sql_condition_identity(Sql_state_errno_level(), ucid), - m_mem_root(mem_root) - { - DBUG_ASSERT(mem_root != NULL); - } - /** - Constructor for a fixed message text. - @param mem_root - memory root - @param value - the error number and the sql state for this condition - @param level - the error level for this condition - @param msg - the message text for this condition - */ - Sql_condition(MEM_ROOT *mem_root, - const Sql_condition_identity &value, - const char *msg) - :Sql_condition_identity(value), - m_mem_root(mem_root) - { - DBUG_ASSERT(mem_root != NULL); - DBUG_ASSERT(value.get_sql_errno() != 0); - DBUG_ASSERT(msg != NULL); - set_builtin_message_text(msg); - } - - /** Destructor. */ - ~Sql_condition() - {} - - /** - Copy optional condition items attributes. - @param cond the condition to copy. - */ - void copy_opt_attributes(const Sql_condition *cond); - - /** - Set the condition message test. - @param str Message text, expressed in the character set derived from - the server --language option - */ - void set_builtin_message_text(const char* str); - - /** Set the CLASS_ORIGIN of this condition. */ - void set_class_origin(); - - /** Set the SUBCLASS_ORIGIN of this condition. */ - void set_subclass_origin(); - - /** - Assign the condition items 'MYSQL_ERRNO', 'level' and 'MESSAGE_TEXT' - default values of a condition. - @param thd - current thread, to access to localized error messages - @param from - copy condition items from here (can be NULL) - */ - void assign_defaults(THD *thd, const Sql_state_errno *from); - - /** - Clear this SQL condition. - */ - void clear() - { - Sql_condition_identity::clear(); - Sql_condition_items::clear(); - m_message_text.length(0); - } - -private: - /** Message text, expressed in the character set implied by --language. */ - String m_message_text; - - /** Pointers for participating in the list of conditions. */ - Sql_condition *next_in_wi; - Sql_condition **prev_in_wi; - - /** Memory root to use to hold condition item values. */ - MEM_ROOT *m_mem_root; -}; - -/////////////////////////////////////////////////////////////////////////// - -/** - Information about warnings of the current connection. -*/ -class Warning_info -{ - /** The type of the counted and doubly linked list of conditions. */ - typedef I_P_List, - I_P_List_counter, - I_P_List_fast_push_back > - Sql_condition_list; - - /** A memory root to allocate warnings and errors */ - MEM_ROOT m_warn_root; - - /** List of warnings of all severities (levels). */ - Sql_condition_list m_warn_list; - - /** A break down of the number of warnings per severity (level). */ - uint m_warn_count[(uint) Sql_condition::WARN_LEVEL_END]; - - /** - The number of warnings of the current statement. Warning_info - life cycle differs from statement life cycle -- it may span - multiple statements. In that case we get - m_current_statement_warn_count 0, whereas m_warn_list is not empty. - */ - uint m_current_statement_warn_count; - - /* - Row counter, to print in errors and warnings. Not increased in - create_sort_index(); may differ from examined_row_count. - */ - ulong m_current_row_for_warning; - - /** Used to optionally clear warnings only once per statement. */ - ulonglong m_warn_id; - - /** - A pointer to an element of m_warn_list. It determines SQL-condition - instance which corresponds to the error state in Diagnostics_area. - - This is needed for properly processing SQL-conditions in SQL-handlers. - When an SQL-handler is found for the current error state in Diagnostics_area, - this pointer is needed to remove the corresponding SQL-condition from the - Warning_info list. - - @note m_error_condition might be NULL in the following cases: - - Diagnostics_area set to fatal error state (like OOM); - - Max number of Warning_info elements has been reached (thus, there is - no corresponding SQL-condition object in Warning_info). - */ - const Sql_condition *m_error_condition; - - /** Indicates if push_warning() allows unlimited number of warnings. */ - bool m_allow_unlimited_warnings; - bool initialized; /* Set to 1 if init() has been called */ - - /** Read only status. */ - bool m_read_only; - - /** Pointers for participating in the stack of Warning_info objects. */ - Warning_info *m_next_in_da; - Warning_info **m_prev_in_da; - - List m_marked_sql_conditions; - -public: - Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings, - bool initialized); - ~Warning_info(); - /* Allocate memory for structures */ - void init(); - void free_memory(); - -private: - Warning_info(const Warning_info &rhs); /* Not implemented */ - Warning_info& operator=(const Warning_info &rhs); /* Not implemented */ - - /** - Checks if Warning_info contains SQL-condition with the given message. - - @param message_str Message string. - @param message_length Length of message string. - - @return true if the Warning_info contains an SQL-condition with the given - message. - */ - bool has_sql_condition(const char *message_str, size_t message_length) const; - - /** - Reset the warning information. Clear all warnings, - the number of warnings, reset current row counter - to point to the first row. - - @param new_id new Warning_info id. - */ - void clear(ulonglong new_id); - - /** - Only clear warning info if haven't yet done that already - for the current query. Allows to be issued at any time - during the query, without risk of clearing some warnings - that have been generated by the current statement. - - @todo: This is a sign of sloppy coding. Instead we need to - designate one place in a statement life cycle where we call - Warning_info::clear(). - - @param query_id Current query id. - */ - void opt_clear(ulonglong query_id) - { - if (query_id != m_warn_id) - clear(query_id); - } - - /** - Concatenate the list of warnings. - - It's considered tolerable to lose an SQL-condition in case of OOM-error, - or if the number of SQL-conditions in the Warning_info reached top limit. - - @param thd Thread context. - @param source Warning_info object to copy SQL-conditions from. - */ - void append_warning_info(THD *thd, const Warning_info *source); - - /** - Reset between two COM_ commands. Warnings are preserved - between commands, but statement_warn_count indicates - the number of warnings of this particular statement only. - */ - void reset_for_next_command() - { m_current_statement_warn_count= 0; } - - /** - Mark active SQL-conditions for later removal. - This is done to simulate stacked DAs for HANDLER statements. - */ - void mark_sql_conditions_for_removal(); - - /** - Unmark SQL-conditions, which were marked for later removal. - This is done to simulate stacked DAs for HANDLER statements. - */ - void unmark_sql_conditions_from_removal() - { m_marked_sql_conditions.empty(); } - - /** - Remove SQL-conditions that are marked for deletion. - This is done to simulate stacked DAs for HANDLER statements. - */ - void remove_marked_sql_conditions(); - - /** - Check if the given SQL-condition is marked for removal in this Warning_info - instance. - - @param cond the SQL-condition. - - @retval true if the given SQL-condition is marked for removal in this - Warning_info instance. - @retval false otherwise. - */ - bool is_marked_for_removal(const Sql_condition *cond) const; - - /** - Mark a single SQL-condition for removal (add the given SQL-condition to the - removal list of this Warning_info instance). - */ - void mark_condition_for_removal(Sql_condition *cond) - { m_marked_sql_conditions.push_back(cond, &m_warn_root); } - - /** - Used for @@warning_count system variable, which prints - the number of rows returned by SHOW WARNINGS. - */ - ulong warn_count() const - { - /* - This may be higher than warn_list.elements() if we have - had more warnings than thd->variables.max_error_count. - */ - return (m_warn_count[(uint) Sql_condition::WARN_LEVEL_NOTE] + - m_warn_count[(uint) Sql_condition::WARN_LEVEL_ERROR] + - m_warn_count[(uint) Sql_condition::WARN_LEVEL_WARN]); - } - - /** - The number of errors, or number of rows returned by SHOW ERRORS, - also the value of session variable @@error_count. - */ - ulong error_count() const - { return m_warn_count[(uint) Sql_condition::WARN_LEVEL_ERROR]; } - - /** - The number of conditions (errors, warnings and notes) in the list. - */ - uint cond_count() const - { - return m_warn_list.elements(); - } - - /** Id of the warning information area. */ - ulonglong id() const { return m_warn_id; } - - /** Set id of the warning information area. */ - void id(ulonglong id_arg) { m_warn_id= id_arg; } - - /** Do we have any errors and warnings that we can *show*? */ - bool is_empty() const { return m_warn_list.is_empty(); } - - /** Increment the current row counter to point at the next row. */ - void inc_current_row_for_warning() { m_current_row_for_warning++; } - - /** Reset the current row counter. Start counting from the first row. */ - void reset_current_row_for_warning() { m_current_row_for_warning= 1; } - - /** Return the current counter value. */ - ulong current_row_for_warning() const { return m_current_row_for_warning; } - - /** Return the number of warnings thrown by the current statement. */ - ulong current_statement_warn_count() const - { return m_current_statement_warn_count; } - - /** Make sure there is room for the given number of conditions. */ - void reserve_space(THD *thd, uint count); - - /** - Add a new SQL-condition to the current list and increment the respective - counters. - - @param thd Thread context. - @param identity SQL-condition identity - @param msg SQL-condition message. - - @return a pointer to the added SQL-condition. - */ - Sql_condition *push_warning(THD *thd, - const Sql_condition_identity *identity, - const char* msg); - - /** - Add a new SQL-condition to the current list and increment the respective - counters. - - @param thd Thread context. - @param sql_condition SQL-condition to copy values from. - - @return a pointer to the added SQL-condition. - */ - Sql_condition *push_warning(THD *thd, const Sql_condition *sql_condition); - - /** - Set the read only status for this statement area. - This is a privileged operation, reserved for the implementation of - diagnostics related statements, to enforce that the statement area is - left untouched during execution. - The diagnostics statements are: - - SHOW WARNINGS - - SHOW ERRORS - - GET DIAGNOSTICS - @param read_only the read only property to set. - */ - void set_read_only(bool read_only_arg) - { m_read_only= read_only_arg; } - - /** - Read only status. - @return the read only property. - */ - bool is_read_only() const - { return m_read_only; } - - /** - @return SQL-condition, which corresponds to the error state in - Diagnostics_area. - - @see m_error_condition. - */ - const Sql_condition *get_error_condition() const - { return m_error_condition; } - - /** - Set SQL-condition, which corresponds to the error state in Diagnostics_area. - - @see m_error_condition. - */ - void set_error_condition(const Sql_condition *error_condition) - { m_error_condition= error_condition; } - - /** - Reset SQL-condition, which corresponds to the error state in - Diagnostics_area. - - @see m_error_condition. - */ - void clear_error_condition() - { m_error_condition= NULL; } - - // for: - // - m_next_in_da / m_prev_in_da - // - is_marked_for_removal() - friend class Diagnostics_area; -}; - - -extern char *err_conv(char *buff, uint to_length, const char *from, - uint from_length, CHARSET_INFO *from_cs); - -class ErrBuff -{ -protected: - mutable char err_buffer[MYSQL_ERRMSG_SIZE]; -public: - ErrBuff() - { - err_buffer[0]= '\0'; - } - const char *ptr() const { return err_buffer; } - const char *set_longlong(const Longlong_hybrid &nr) const - { - return nr.is_unsigned() ? ullstr(nr.value(), err_buffer) : - llstr(nr.value(), err_buffer); - } - const char *set_double(double nr) const - { - my_gcvt(nr, MY_GCVT_ARG_DOUBLE, sizeof(err_buffer), err_buffer, 0); - return err_buffer; - } - const char *set_decimal(const decimal_t *d) const - { - int len= sizeof(err_buffer); - decimal2string(d, err_buffer, &len, 0, 0, ' '); - return err_buffer; - } - const char *set_str(const char *str, size_t len, CHARSET_INFO *cs) const - { - DBUG_ASSERT(len < UINT_MAX32); - return err_conv(err_buffer, (uint) sizeof(err_buffer), str, (uint) len, cs); - } - const char *set_mysql_time(const MYSQL_TIME *ltime) const - { - my_TIME_to_str(ltime, err_buffer, AUTO_SEC_PART_DIGITS); - return err_buffer; - } -}; - - -class ErrConv: public ErrBuff -{ -public: - ErrConv() {} - virtual ~ErrConv() {} - virtual const char *ptr() const = 0; -}; - -class ErrConvString : public ErrConv -{ - const char *str; - size_t len; - CHARSET_INFO *cs; -public: - ErrConvString(const char *str_arg, size_t len_arg, CHARSET_INFO *cs_arg) - : ErrConv(), str(str_arg), len(len_arg), cs(cs_arg) {} - ErrConvString(const char *str_arg, CHARSET_INFO *cs_arg) - : ErrConv(), str(str_arg), len(strlen(str_arg)), cs(cs_arg) {} - ErrConvString(const String *s) - : ErrConv(), str(s->ptr()), len(s->length()), cs(s->charset()) {} - const char *ptr() const - { - return set_str(str, len, cs); - } -}; - -class ErrConvInteger : public ErrConv, public Longlong_hybrid -{ -public: - ErrConvInteger(const Longlong_hybrid &nr) - : ErrConv(), Longlong_hybrid(nr) { } - const char *ptr() const - { - return set_longlong(static_cast(*this)); - } -}; - -class ErrConvDouble: public ErrConv -{ - double num; -public: - ErrConvDouble(double num_arg) : ErrConv(), num(num_arg) {} - const char *ptr() const - { - return set_double(num); - } -}; - -class ErrConvTime : public ErrConv -{ - const MYSQL_TIME *ltime; -public: - ErrConvTime(const MYSQL_TIME *ltime_arg) : ErrConv(), ltime(ltime_arg) {} - const char *ptr() const - { - return set_mysql_time(ltime); - } -}; - -class ErrConvDecimal : public ErrConv -{ - const decimal_t *d; -public: - ErrConvDecimal(const decimal_t *d_arg) : ErrConv(), d(d_arg) {} - const char *ptr() const - { - return set_decimal(d); - } -}; - -/////////////////////////////////////////////////////////////////////////// - -/** - Stores status of the currently executed statement. - Cleared at the beginning of the statement, and then - can hold either OK, ERROR, or EOF status. - Can not be assigned twice per statement. -*/ - -class Diagnostics_area: public Sql_state_errno, - public Sql_user_condition_identity -{ -private: - /** The type of the counted and doubly linked list of conditions. */ - typedef I_P_List, - I_P_List_counter, - I_P_List_fast_push_back > - Warning_info_list; - -public: - /** Const iterator used to iterate through the warning list. */ - typedef Warning_info::Sql_condition_list::Const_Iterator - Sql_condition_iterator; - - enum enum_diagnostics_status - { - /** The area is cleared at start of a statement. */ - DA_EMPTY= 0, - /** Set whenever one calls my_ok(). */ - DA_OK, - /** Set whenever one calls my_eof(). */ - DA_EOF, - /** Set whenever one calls my_ok() in PS bulk mode. */ - DA_OK_BULK, - /** Set whenever one calls my_error() or my_message(). */ - DA_ERROR, - /** Set in case of a custom response, such as one from COM_STMT_PREPARE. */ - DA_DISABLED - }; - - void set_overwrite_status(bool can_overwrite_status) - { m_can_overwrite_status= can_overwrite_status; } - - /** True if status information is sent to the client. */ - bool is_sent() const { return m_is_sent; } - - void set_is_sent(bool is_sent_arg) { m_is_sent= is_sent_arg; } - - void set_ok_status(ulonglong affected_rows, - ulonglong last_insert_id, - const char *message); - - void set_eof_status(THD *thd); - - void set_error_status(uint sql_errno); - - void set_error_status(uint sql_errno, - const char *message, - const char *sqlstate, - const Sql_user_condition_identity &ucid, - const Sql_condition *error_condition); - - void set_error_status(uint sql_errno, - const char *message, - const char *sqlstate, - const Sql_condition *error_condition) - { - set_error_status(sql_errno, message, sqlstate, - Sql_user_condition_identity(), - error_condition); - } - - void disable_status(); - - void reset_diagnostics_area(); - - bool is_set() const { return m_status != DA_EMPTY; } - - bool is_error() const { return m_status == DA_ERROR; } - - bool is_eof() const { return m_status == DA_EOF; } - - bool is_ok() const { return m_status == DA_OK; } - - bool is_disabled() const { return m_status == DA_DISABLED; } - - void set_bulk_execution(bool bulk) { is_bulk_execution= bulk; } - - bool is_bulk_op() const { return is_bulk_execution; } - - enum_diagnostics_status status() const { return m_status; } - - const char *message() const - { DBUG_ASSERT(m_status == DA_ERROR || m_status == DA_OK || - m_status == DA_OK_BULK); return m_message; } - - bool skip_flush() const - { - DBUG_ASSERT(m_status == DA_OK || m_status == DA_OK_BULK); - return m_skip_flush; - } - - void set_skip_flush() - { m_skip_flush= TRUE; } - - uint sql_errno() const - { - DBUG_ASSERT(m_status == DA_ERROR); - return Sql_state_errno::get_sql_errno(); - } - - const char* get_sqlstate() const - { DBUG_ASSERT(m_status == DA_ERROR); return Sql_state::get_sqlstate(); } - - ulonglong affected_rows() const - { - DBUG_ASSERT(m_status == DA_OK || m_status == DA_OK_BULK); - return m_affected_rows; - } - - ulonglong last_insert_id() const - { - DBUG_ASSERT(m_status == DA_OK || m_status == DA_OK_BULK); - return m_last_insert_id; - } - - uint statement_warn_count() const - { - DBUG_ASSERT(m_status == DA_OK || m_status == DA_OK_BULK || - m_status == DA_EOF); - return m_statement_warn_count; - } - - /** - Get the current errno, state and id of the user defined condition - and return them as Sql_condition_identity. - */ - Sql_condition_identity get_error_condition_identity() const - { - DBUG_ASSERT(m_status == DA_ERROR); - return Sql_condition_identity(*this /*Sql_state_errno*/, - Sql_condition::WARN_LEVEL_ERROR, - *this /*Sql_user_condition_identity*/); - } - - /* Used to count any warnings pushed after calling set_ok_status(). */ - void increment_warning() - { - if (m_status != DA_EMPTY) - m_statement_warn_count++; - } - - Diagnostics_area(bool initialize); - Diagnostics_area(ulonglong warning_info_id, bool allow_unlimited_warnings, - bool initialize); - void init() { m_main_wi.init() ; } - void free_memory() { m_main_wi.free_memory() ; } - - void push_warning_info(Warning_info *wi) - { m_wi_stack.push_front(wi); } - - void pop_warning_info() - { - DBUG_ASSERT(m_wi_stack.elements() > 0); - m_wi_stack.remove(m_wi_stack.front()); - } - - void set_warning_info_id(ulonglong id) - { get_warning_info()->id(id); } - - ulonglong warning_info_id() const - { return get_warning_info()->id(); } - - /** - Compare given current warning info and current warning info - and see if they are different. They will be different if - warnings have been generated or statements that use tables - have been executed. This is checked by comparing m_warn_id. - - @param wi Warning info to compare with current Warning info. - - @return false if they are equal, true if they are not. - */ - bool warning_info_changed(const Warning_info *wi) const - { return get_warning_info()->id() != wi->id(); } - - bool is_warning_info_empty() const - { return get_warning_info()->is_empty(); } - - ulong current_statement_warn_count() const - { return get_warning_info()->current_statement_warn_count(); } - - bool has_sql_condition(const char *message_str, size_t message_length) const - { return get_warning_info()->has_sql_condition(message_str, message_length); } - - void reset_for_next_command() - { get_warning_info()->reset_for_next_command(); } - - void clear_warning_info(ulonglong id) - { get_warning_info()->clear(id); } - - void opt_clear_warning_info(ulonglong query_id) - { get_warning_info()->opt_clear(query_id); } - - ulong current_row_for_warning() const - { return get_warning_info()->current_row_for_warning(); } - - void inc_current_row_for_warning() - { get_warning_info()->inc_current_row_for_warning(); } - - void reset_current_row_for_warning() - { get_warning_info()->reset_current_row_for_warning(); } - - bool is_warning_info_read_only() const - { return get_warning_info()->is_read_only(); } - - void set_warning_info_read_only(bool read_only_arg) - { get_warning_info()->set_read_only(read_only_arg); } - - ulong error_count() const - { return get_warning_info()->error_count(); } - - ulong warn_count() const - { return get_warning_info()->warn_count(); } - - uint cond_count() const - { return get_warning_info()->cond_count(); } - - Sql_condition_iterator sql_conditions() const - { return get_warning_info()->m_warn_list; } - - void reserve_space(THD *thd, uint count) - { get_warning_info()->reserve_space(thd, count); } - - Sql_condition *push_warning(THD *thd, const Sql_condition *sql_condition) - { return get_warning_info()->push_warning(thd, sql_condition); } - - Sql_condition *push_warning(THD *thd, - uint sql_errno_arg, - const char* sqlstate, - Sql_condition::enum_warning_level level, - const Sql_user_condition_identity &ucid, - const char* msg) - { - Sql_condition_identity tmp(sql_errno_arg, sqlstate, level, ucid); - return get_warning_info()->push_warning(thd, &tmp, msg); - } - - Sql_condition *push_warning(THD *thd, - uint sqlerrno, - const char* sqlstate, - Sql_condition::enum_warning_level level, - const char* msg) - { - return push_warning(thd, sqlerrno, sqlstate, level, - Sql_user_condition_identity(), msg); - } - void mark_sql_conditions_for_removal() - { get_warning_info()->mark_sql_conditions_for_removal(); } - - void unmark_sql_conditions_from_removal() - { get_warning_info()->unmark_sql_conditions_from_removal(); } - - void remove_marked_sql_conditions() - { get_warning_info()->remove_marked_sql_conditions(); } - - const Sql_condition *get_error_condition() const - { return get_warning_info()->get_error_condition(); } - - void copy_sql_conditions_to_wi(THD *thd, Warning_info *dst_wi) const - { dst_wi->append_warning_info(thd, get_warning_info()); } - - void copy_sql_conditions_from_wi(THD *thd, const Warning_info *src_wi) - { get_warning_info()->append_warning_info(thd, src_wi); } - - void copy_non_errors_from_wi(THD *thd, const Warning_info *src_wi); - -private: - Warning_info *get_warning_info() { return m_wi_stack.front(); } - - const Warning_info *get_warning_info() const { return m_wi_stack.front(); } - -private: - /** True if status information is sent to the client. */ - bool m_is_sent; - - /** Set to make set_error_status after set_{ok,eof}_status possible. */ - bool m_can_overwrite_status; - - /** Skip flushing network buffer after writing OK (for COM_MULTI) */ - bool m_skip_flush; - - /** Message buffer. Can be used by OK or ERROR status. */ - char m_message[MYSQL_ERRMSG_SIZE]; - - /** - The number of rows affected by the last statement. This is - semantically close to thd->m_row_count_func, but has a different - life cycle. thd->m_row_count_func stores the value returned by - function ROW_COUNT() and is cleared only by statements that - update its value, such as INSERT, UPDATE, DELETE and few others. - This member is cleared at the beginning of the next statement. - - We could possibly merge the two, but life cycle of thd->m_row_count_func - can not be changed. - */ - ulonglong m_affected_rows; - - /** - Similarly to the previous member, this is a replacement of - thd->first_successful_insert_id_in_prev_stmt, which is used - to implement LAST_INSERT_ID(). - */ - - ulonglong m_last_insert_id; - /** - Number of warnings of this last statement. May differ from - the number of warnings returned by SHOW WARNINGS e.g. in case - the statement doesn't clear the warnings, and doesn't generate - them. - */ - uint m_statement_warn_count; - - enum_diagnostics_status m_status; - - my_bool is_bulk_execution; - - Warning_info m_main_wi; - - Warning_info_list m_wi_stack; -}; - -/////////////////////////////////////////////////////////////////////////// - -void convert_error_to_warning(THD *thd); - -void push_warning(THD *thd, Sql_condition::enum_warning_level level, - uint code, const char *msg); - -void push_warning_printf(THD *thd, Sql_condition::enum_warning_level level, - uint code, const char *format, ...); - -bool mysqld_show_warnings(THD *thd, ulong levels_to_show); - -size_t convert_error_message(char *to, size_t to_length, - CHARSET_INFO *to_cs, - const char *from, size_t from_length, - CHARSET_INFO *from_cs, uint *errors); - -extern const LEX_CSTRING warning_level_names[]; - -bool is_sqlstate_valid(const LEX_CSTRING *sqlstate); -/** - Checks if the specified SQL-state-string defines COMPLETION condition. - This function assumes that the given string contains a valid SQL-state. - - @param s the condition SQLSTATE. - - @retval true if the given string defines COMPLETION condition. - @retval false otherwise. -*/ -inline bool is_sqlstate_completion(const char *s) -{ return s[0] == '0' && s[1] == '0'; } - - -#endif // SQL_ERROR_H diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_explain.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_explain.h deleted file mode 100644 index 9090416..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_explain.h +++ /dev/null @@ -1,998 +0,0 @@ -/* - Copyright (c) 2013 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - -== EXPLAIN/ANALYZE architecture == - -=== [SHOW] EXPLAIN data === -Query optimization produces two data structures: -1. execution data structures themselves (eg. JOINs, JOIN_TAB, etc, etc) -2. Explain data structures. - -#2 are self contained set of data structures that has sufficient info to -produce output of SHOW EXPLAIN, EXPLAIN [FORMAT=JSON], or -ANALYZE [FORMAT=JSON], without accessing the execution data structures. - -(the only exception is that Explain data structures keep Item* pointers, -and we require that one might call item->print(QT_EXPLAIN) when printing -FORMAT=JSON output) - -=== ANALYZE data === -EXPLAIN data structures have embedded ANALYZE data structures. These are -objects that are used to track how the parts of query plan were executed: -how many times each part of query plan was invoked, how many rows were -read/returned, etc. - -Each execution data structure keeps a direct pointer to its ANALYZE data -structure. It is needed so that execution code can quickly increment the -counters. - -(note that this increases the set of data that is frequently accessed -during the execution. What is the impact of this?) - -Since ANALYZE/EXPLAIN data structures are separated from execution data -structures, it is easy to have them survive until the end of the query, -where we can return ANALYZE [FORMAT=JSON] output to the user, or print -it into the slow query log. - -*/ - -#ifndef SQL_EXPLAIN_INCLUDED -#define SQL_EXPLAIN_INCLUDED - -class String_list: public List -{ -public: - const char *append_str(MEM_ROOT *mem_root, const char *str); -}; - -class Json_writer; - -/************************************************************************************** - - Data structures for producing EXPLAIN outputs. - - These structures - - Can be produced inexpensively from query plan. - - Store sufficient information to produce tabular EXPLAIN output (the goal is - to be able to produce JSON also) - -*************************************************************************************/ - - -const int FAKE_SELECT_LEX_ID= (int)UINT_MAX; - -class Explain_query; - -/* - A node can be either a SELECT, or a UNION. -*/ -class Explain_node : public Sql_alloc -{ -public: - Explain_node(MEM_ROOT *root) : - cache_tracker(NULL), - connection_type(EXPLAIN_NODE_OTHER), - children(root) - {} - /* A type specifying what kind of node this is */ - enum explain_node_type - { - EXPLAIN_UNION, - EXPLAIN_SELECT, - EXPLAIN_BASIC_JOIN, - EXPLAIN_UPDATE, - EXPLAIN_DELETE, - EXPLAIN_INSERT - }; - - /* How this node is connected */ - enum explain_connection_type { - EXPLAIN_NODE_OTHER, - EXPLAIN_NODE_DERIVED, /* Materialized derived table */ - EXPLAIN_NODE_NON_MERGED_SJ /* aka JTBM semi-join */ - }; - - virtual enum explain_node_type get_type()= 0; - virtual int get_select_id()= 0; - - /** - expression cache statistics - */ - Expression_cache_tracker* cache_tracker; - - /* - How this node is connected to its parent. - (NOTE: EXPLAIN_NODE_NON_MERGED_SJ is set very late currently) - */ - enum explain_connection_type connection_type; - - /* - A node may have children nodes. When a node's explain structure is - created, children nodes may not yet have QPFs. This is why we store ids. - */ - Dynamic_array children; - void add_child(int select_no) - { - children.append(select_no); - } - - virtual int print_explain(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze)=0; - virtual void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze)= 0; - - int print_explain_for_children(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze); - void print_explain_json_for_children(Explain_query *query, - Json_writer *writer, bool is_analyze); - bool print_explain_json_cache(Json_writer *writer, bool is_analyze); - virtual ~Explain_node(){} -}; - - -class Explain_table_access; - - -/* - A basic join. This is only used for SJ-Materialization nests. - - Basic join doesn't have ORDER/GROUP/DISTINCT operations. It also cannot be - degenerate. - - It has its own select_id. -*/ -class Explain_basic_join : public Explain_node -{ -public: - enum explain_node_type get_type() { return EXPLAIN_BASIC_JOIN; } - - Explain_basic_join(MEM_ROOT *root) : Explain_node(root), join_tabs(NULL) {} - ~Explain_basic_join(); - - bool add_table(Explain_table_access *tab, Explain_query *query); - - int get_select_id() { return select_id; } - - int select_id; - - int print_explain(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze); - void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); - - void print_explain_json_interns(Explain_query *query, Json_writer *writer, - bool is_analyze); - - /* A flat array of Explain structs for tables. */ - Explain_table_access** join_tabs; - uint n_join_tabs; -}; - - -class Explain_aggr_node; -/* - EXPLAIN structure for a SELECT. - - A select can be: - 1. A degenerate case. In this case, message!=NULL, and it contains a - description of what kind of degenerate case it is (e.g. "Impossible - WHERE"). - 2. a non-degenrate join. In this case, join_tabs describes the join. - - In the non-degenerate case, a SELECT may have a GROUP BY/ORDER BY operation. - - In both cases, the select may have children nodes. class Explain_node - provides a way get node's children. -*/ - -class Explain_select : public Explain_basic_join -{ -public: - enum explain_node_type get_type() { return EXPLAIN_SELECT; } - - Explain_select(MEM_ROOT *root, bool is_analyze) : - Explain_basic_join(root), -#ifndef DBUG_OFF - select_lex(NULL), -#endif - linkage(UNSPECIFIED_TYPE), - is_lateral(false), - message(NULL), - having(NULL), having_value(Item::COND_UNDEF), - using_temporary(false), using_filesort(false), - time_tracker(is_analyze), - aggr_tree(NULL) - {} - - void add_linkage(Json_writer *writer); - -public: -#ifndef DBUG_OFF - SELECT_LEX *select_lex; -#endif - const char *select_type; - enum sub_select_type linkage; - bool is_lateral; - - /* - If message != NULL, this is a degenerate join plan, and all subsequent - members have no info - */ - const char *message; - - /* Expensive constant condition */ - Item *exec_const_cond; - Item *outer_ref_cond; - Item *pseudo_bits_cond; - - /* HAVING condition */ - Item *having; - Item::cond_result having_value; - - /* Global join attributes. In tabular form, they are printed on the first row */ - bool using_temporary; - bool using_filesort; - - /* ANALYZE members */ - Time_and_counter_tracker time_tracker; - - /* - Part of query plan describing sorting, temp.table usage, and duplicate - removal - */ - Explain_aggr_node* aggr_tree; - - int print_explain(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze); - void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); - - Table_access_tracker *get_using_temporary_read_tracker() - { - return &using_temporary_read_tracker; - } -private: - Table_access_tracker using_temporary_read_tracker; -}; - -///////////////////////////////////////////////////////////////////////////// -// EXPLAIN structures for ORDER/GROUP operations. -///////////////////////////////////////////////////////////////////////////// -typedef enum -{ - AGGR_OP_TEMP_TABLE, - AGGR_OP_FILESORT, - //AGGR_OP_READ_SORTED_FILE, // need this? - AGGR_OP_REMOVE_DUPLICATES, - AGGR_OP_WINDOW_FUNCS - //AGGR_OP_JOIN // Need this? -} enum_explain_aggr_node_type; - - -class Explain_aggr_node : public Sql_alloc -{ -public: - virtual enum_explain_aggr_node_type get_type()= 0; - virtual ~Explain_aggr_node() {} - Explain_aggr_node *child; -}; - -class Explain_aggr_filesort : public Explain_aggr_node -{ - List sort_items; - List sort_directions; -public: - enum_explain_aggr_node_type get_type() { return AGGR_OP_FILESORT; } - Filesort_tracker tracker; - - Explain_aggr_filesort(MEM_ROOT *mem_root, bool is_analyze, - Filesort *filesort); - - void print_json_members(Json_writer *writer, bool is_analyze); -}; - -class Explain_aggr_tmp_table : public Explain_aggr_node -{ -public: - enum_explain_aggr_node_type get_type() { return AGGR_OP_TEMP_TABLE; } -}; - -class Explain_aggr_remove_dups : public Explain_aggr_node -{ -public: - enum_explain_aggr_node_type get_type() { return AGGR_OP_REMOVE_DUPLICATES; } -}; - -class Explain_aggr_window_funcs : public Explain_aggr_node -{ - List sorts; -public: - enum_explain_aggr_node_type get_type() { return AGGR_OP_WINDOW_FUNCS; } - - void print_json_members(Json_writer *writer, bool is_analyze); - friend class Window_funcs_computation; -}; - -///////////////////////////////////////////////////////////////////////////// - -extern const char *unit_operation_text[4]; -extern const char *pushed_derived_text; -extern const char *pushed_select_text; - -/* - Explain structure for a UNION. - - A UNION may or may not have "Using filesort". -*/ - -class Explain_union : public Explain_node -{ -public: - Explain_union(MEM_ROOT *root, bool is_analyze) : - Explain_node(root), union_members(PSI_INSTRUMENT_MEM), - is_recursive_cte(false), - fake_select_lex_explain(root, is_analyze) - {} - - enum explain_node_type get_type() { return EXPLAIN_UNION; } - unit_common_op operation; - - int get_select_id() - { - DBUG_ASSERT(union_members.elements() > 0); - return union_members.at(0); - } - /* - Members of the UNION. Note: these are different from UNION's "children". - Example: - - (select * from t1) union - (select * from t2) order by (select col1 from t3 ...) - - here - - select-from-t1 and select-from-t2 are "union members", - - select-from-t3 is the only "child". - */ - Dynamic_array union_members; - - void add_select(int select_no) - { - union_members.append(select_no); - } - int print_explain(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze); - void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); - - const char *fake_select_type; - bool using_filesort; - bool using_tmp; - bool is_recursive_cte; - - /* - Explain data structure for "fake_select_lex" (i.e. for the degenerate - SELECT that reads UNION result). - It doesn't have a query plan, but we still need execution tracker, etc. - */ - Explain_select fake_select_lex_explain; - - Table_access_tracker *get_fake_select_lex_tracker() - { - return &fake_select_lex_tracker; - } - Table_access_tracker *get_tmptable_read_tracker() - { - return &tmptable_read_tracker; - } -private: - uint make_union_table_name(char *buf); - - Table_access_tracker fake_select_lex_tracker; - /* This one is for reading after ORDER BY */ - Table_access_tracker tmptable_read_tracker; -}; - - -class Explain_update; -class Explain_delete; -class Explain_insert; - - -/* - Explain structure for a query (i.e. a statement). - - This should be able to survive when the query plan was deleted. Currently, - we do not intend for it survive until after query's MEM_ROOT is freed. It - does surivive freeing of query's items. - - For reference, the process of post-query cleanup is as follows: - - >dispatch_command - | >mysql_parse - | | ... - | | lex_end() - | | ... - | | >THD::cleanup_after_query - | | | ... - | | | free_items() - | | | ... - | | dispatch_command - - That is, the order of actions is: - - free query's Items - - write to slow query log - - free query's MEM_ROOT - -*/ - -class Explain_query : public Sql_alloc -{ -public: - Explain_query(THD *thd, MEM_ROOT *root); - ~Explain_query(); - - /* Add a new node */ - void add_node(Explain_node *node); - void add_insert_plan(Explain_insert *insert_plan_arg); - void add_upd_del_plan(Explain_update *upd_del_plan_arg); - - /* This will return a select, or a union */ - Explain_node *get_node(uint select_id); - - /* This will return a select (even if there is a union with this id) */ - Explain_select *get_select(uint select_id); - - Explain_union *get_union(uint select_id); - - /* Produce a tabular EXPLAIN output */ - int print_explain(select_result_sink *output, uint8 explain_flags, - bool is_analyze); - - /* Send tabular EXPLAIN to the client */ - int send_explain(THD *thd); - - /* Return tabular EXPLAIN output as a text string */ - bool print_explain_str(THD *thd, String *out_str, bool is_analyze); - - void print_explain_json(select_result_sink *output, bool is_analyze); - - /* If true, at least part of EXPLAIN can be printed */ - bool have_query_plan() { return insert_plan || upd_del_plan|| get_node(1) != NULL; } - - void query_plan_ready(); - - MEM_ROOT *mem_root; - - Explain_update *get_upd_del_plan() { return upd_del_plan; } -private: - /* Explain_delete inherits from Explain_update */ - Explain_update *upd_del_plan; - - /* Query "plan" for INSERTs */ - Explain_insert *insert_plan; - - Dynamic_array unions; - Dynamic_array selects; - - THD *thd; // for APC start/stop - bool apc_enabled; - /* - Debugging aid: count how many times add_node() was called. Ideally, it - should be one, we currently allow O(1) query plan saves for each - select or union. The goal is not to have O(#rows_in_some_table), which - is unacceptable. - */ - longlong operations; -}; - - -/* - Some of the tags have matching text. See extra_tag_text for text names, and - Explain_table_access::append_tag_name() for code to convert from tag form to text - form. -*/ -enum explain_extra_tag -{ - ET_none= 0, /* not-a-tag */ - ET_USING_INDEX_CONDITION, - ET_USING_INDEX_CONDITION_BKA, - ET_USING, /* For quick selects of various kinds */ - ET_RANGE_CHECKED_FOR_EACH_RECORD, - ET_USING_WHERE_WITH_PUSHED_CONDITION, - ET_USING_WHERE, - ET_NOT_EXISTS, - - ET_USING_INDEX, - ET_FULL_SCAN_ON_NULL_KEY, - ET_SKIP_OPEN_TABLE, - ET_OPEN_FRM_ONLY, - ET_OPEN_FULL_TABLE, - - ET_SCANNED_0_DATABASES, - ET_SCANNED_1_DATABASE, - ET_SCANNED_ALL_DATABASES, - - ET_USING_INDEX_FOR_GROUP_BY, - - ET_USING_MRR, // does not print "Using mrr". - - ET_DISTINCT, - ET_LOOSESCAN, - ET_START_TEMPORARY, - ET_END_TEMPORARY, - ET_FIRST_MATCH, - - ET_USING_JOIN_BUFFER, - - ET_CONST_ROW_NOT_FOUND, - ET_UNIQUE_ROW_NOT_FOUND, - ET_IMPOSSIBLE_ON_CONDITION, - - ET_total -}; - - -/* - Explain data structure describing join buffering use. -*/ - -class EXPLAIN_BKA_TYPE -{ -public: - EXPLAIN_BKA_TYPE() : join_alg(NULL) {} - - size_t join_buffer_size; - - bool incremental; - - /* - NULL if no join buferring used. - Other values: BNL, BNLH, BKA, BKAH. - */ - const char *join_alg; - - /* Information about MRR usage. */ - StringBuffer<64> mrr_type; - - bool is_using_jbuf() { return (join_alg != NULL); } -}; - - -/* - Data about how an index is used by some access method -*/ -class Explain_index_use : public Sql_alloc -{ - char *key_name; - uint key_len; - char *filter_name; - uint filter_len; -public: - String_list key_parts_list; - - Explain_index_use() - { - clear(); - } - - void clear() - { - key_name= NULL; - key_len= (uint)-1; - filter_name= NULL; - filter_len= (uint)-1; - } - bool set(MEM_ROOT *root, KEY *key_name, uint key_len_arg); - bool set_pseudo_key(MEM_ROOT *root, const char *key_name); - - inline const char *get_key_name() const { return key_name; } - inline uint get_key_len() const { return key_len; } - //inline const char *get_filter_name() const { return filter_name; } -}; - - -/* - Query Plan data structure for Rowid filter. -*/ -class Explain_rowid_filter : public Sql_alloc -{ -public: - /* Quick select used to collect the rowids into filter */ - Explain_quick_select *quick; - - /* How many rows the above quick select is expected to return */ - ha_rows rows; - - /* Expected selectivity for the filter */ - double selectivity; - - /* Tracker with the information about how rowid filter is executed */ - Rowid_filter_tracker *tracker; - - void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); - - /* - TODO: - Here should be ANALYZE members: - - r_rows for the quick select - - An object that tracked the table access time - - real selectivity of the filter. - */ -}; - - -/* - QPF for quick range selects, as well as index_merge select -*/ -class Explain_quick_select : public Sql_alloc -{ -public: - Explain_quick_select(int quick_type_arg) : quick_type(quick_type_arg) - {} - - const int quick_type; - - bool is_basic() - { - return (quick_type == QUICK_SELECT_I::QS_TYPE_RANGE || - quick_type == QUICK_SELECT_I::QS_TYPE_RANGE_DESC || - quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX); - } - - /* This is used when quick_type == QUICK_SELECT_I::QS_TYPE_RANGE */ - Explain_index_use range; - - /* Used in all other cases */ - List children; - - void print_extra(String *str); - void print_key(String *str); - void print_key_len(String *str); - - void print_json(Json_writer *writer); - - void print_extra_recursive(String *str); -private: - const char *get_name_by_type(); -}; - - -/* - Data structure for "range checked for each record". - It's a set of keys, tabular explain prints hex bitmap, json prints key names. -*/ - -typedef const char* NAME; - -class Explain_range_checked_fer : public Sql_alloc -{ -public: - String_list key_set; - key_map keys_map; -private: - ha_rows full_scan, index_merge; - ha_rows *keys_stat; - NAME *keys_stat_names; - uint keys; - -public: - Explain_range_checked_fer() - :Sql_alloc(), full_scan(0), index_merge(0), - keys_stat(0), keys_stat_names(0), keys(0) - {} - - int append_possible_keys_stat(MEM_ROOT *alloc, - TABLE *table, key_map possible_keys); - void collect_data(QUICK_SELECT_I *quick); - void print_json(Json_writer *writer, bool is_analyze); -}; - - -/* - EXPLAIN data structure for a single JOIN_TAB. -*/ - -class Explain_table_access : public Sql_alloc -{ -public: - Explain_table_access(MEM_ROOT *root) : - derived_select_number(0), - non_merged_sjm_number(0), - extra_tags(root), - range_checked_fer(NULL), - full_scan_on_null_key(false), - start_dups_weedout(false), - end_dups_weedout(false), - where_cond(NULL), - cache_cond(NULL), - pushed_index_cond(NULL), - sjm_nest(NULL), - pre_join_sort(NULL), - rowid_filter(NULL) - {} - ~Explain_table_access() { delete sjm_nest; } - - void push_extra(enum explain_extra_tag extra_tag); - - /* Internals */ - - /* id and 'select_type' are cared-of by the parent Explain_select */ - StringBuffer<32> table_name; - StringBuffer<32> used_partitions; - String_list used_partitions_list; - // valid with ET_USING_MRR - StringBuffer<32> mrr_type; - StringBuffer<32> firstmatch_table_name; - - /* - Non-zero number means this is a derived table. The number can be used to - find the query plan for the derived table - */ - int derived_select_number; - /* TODO: join with the previous member. */ - int non_merged_sjm_number; - - enum join_type type; - - bool used_partitions_set; - - /* Empty means "NULL" will be printed */ - String_list possible_keys; - - bool rows_set; /* not set means 'NULL' should be printed */ - bool filtered_set; /* not set means 'NULL' should be printed */ - // Valid if ET_USING_INDEX_FOR_GROUP_BY is present - bool loose_scan_is_scanning; - - /* - Index use: key name and length. - Note: that when one is accessing I_S tables, those may show use of - non-existant indexes. - - key.key_name == NULL means 'NULL' will be shown in tabular output. - key.key_len == (uint)-1 means 'NULL' will be shown in tabular output. - */ - Explain_index_use key; - - /* - when type==JT_HASH_NEXT, 'key' stores the hash join pseudo-key. - hash_next_key stores the table's key. - */ - Explain_index_use hash_next_key; - - String_list ref_list; - - ha_rows rows; - double filtered; - - /* - Contents of the 'Extra' column. Some are converted into strings, some have - parameters, values for which are stored below. - */ - Dynamic_array extra_tags; - - // Valid if ET_USING tag is present - Explain_quick_select *quick_info; - - /* Non-NULL value means this tab uses "range checked for each record" */ - Explain_range_checked_fer *range_checked_fer; - - bool full_scan_on_null_key; - - // valid with ET_USING_JOIN_BUFFER - EXPLAIN_BKA_TYPE bka_type; - - bool start_dups_weedout; - bool end_dups_weedout; - - /* - Note: lifespan of WHERE condition is less than lifespan of this object. - The below two are valid if tags include "ET_USING_WHERE". - (TODO: indexsubquery may put ET_USING_WHERE without setting where_cond?) - */ - Item *where_cond; - Item *cache_cond; - - /* - This is either pushed index condition, or BKA's index condition. - (the latter refers to columns of other tables and so can only be checked by - BKA code). Examine extra_tags to tell which one it is. - */ - Item *pushed_index_cond; - - Explain_basic_join *sjm_nest; - - /* - This describes a possible filesort() call that is done before doing the - join operation. - */ - Explain_aggr_filesort *pre_join_sort; - - /* ANALYZE members */ - - /* Tracker for reading the table */ - Table_access_tracker tracker; - Exec_time_tracker op_tracker; - Gap_time_tracker extra_time_tracker; - - Table_access_tracker jbuf_tracker; - - Explain_rowid_filter *rowid_filter; - - int print_explain(select_result_sink *output, uint8 explain_flags, - bool is_analyze, - uint select_id, const char *select_type, - bool using_temporary, bool using_filesort); - void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); - -private: - void append_tag_name(String *str, enum explain_extra_tag tag); - void fill_key_str(String *key_str, bool is_json) const; - void fill_key_len_str(String *key_len_str, bool is_json) const; - double get_r_filtered(); - void tag_to_json(Json_writer *writer, enum explain_extra_tag tag); -}; - - -/* - EXPLAIN structure for single-table UPDATE. - - This is similar to Explain_table_access, except that it is more restrictive. - Also, it can have UPDATE operation options, but currently there aren't any. - - Explain_delete inherits from this. -*/ - -class Explain_update : public Explain_node -{ -public: - - Explain_update(MEM_ROOT *root, bool is_analyze) : - Explain_node(root), - filesort_tracker(NULL), - command_tracker(is_analyze) - {} - - virtual enum explain_node_type get_type() { return EXPLAIN_UPDATE; } - virtual int get_select_id() { return 1; /* always root */ } - - const char *select_type; - - StringBuffer<32> used_partitions; - String_list used_partitions_list; - bool used_partitions_set; - - bool impossible_where; - bool no_partitions; - StringBuffer<64> table_name; - - enum join_type jtype; - String_list possible_keys; - - /* Used key when doing a full index scan (possibly with limit) */ - Explain_index_use key; - - /* - MRR that's used with quick select. This should probably belong to the - quick select - */ - StringBuffer<64> mrr_type; - - Explain_quick_select *quick_info; - - bool using_where; - Item *where_cond; - - ha_rows rows; - - bool using_io_buffer; - - /* Tracker for doing reads when filling the buffer */ - Table_access_tracker buf_tracker; - - bool is_using_filesort() { return filesort_tracker? true: false; } - /* - Non-null value of filesort_tracker means "using filesort" - - if we are using filesort, then table_tracker is for the io done inside - filesort. - - 'tracker' is for tracking post-filesort reads. - */ - Filesort_tracker *filesort_tracker; - - /* ANALYZE members and methods */ - Table_access_tracker tracker; - - /* This tracks execution of the whole command */ - Time_and_counter_tracker command_tracker; - - /* TODO: This tracks time to read rows from the table */ - Exec_time_tracker table_tracker; - - virtual int print_explain(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze); - virtual void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); -}; - - -/* - EXPLAIN data structure for an INSERT. - - At the moment this doesn't do much as we don't really have any query plans - for INSERT statements. -*/ - -class Explain_insert : public Explain_node -{ -public: - Explain_insert(MEM_ROOT *root) : - Explain_node(root) - {} - - StringBuffer<64> table_name; - - enum explain_node_type get_type() { return EXPLAIN_INSERT; } - int get_select_id() { return 1; /* always root */ } - - int print_explain(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze); - void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); -}; - - -/* - EXPLAIN data of a single-table DELETE. -*/ - -class Explain_delete: public Explain_update -{ -public: - Explain_delete(MEM_ROOT *root, bool is_analyze) : - Explain_update(root, is_analyze) - {} - - /* - TRUE means we're going to call handler->delete_all_rows() and not read any - rows. - */ - bool deleting_all_rows; - - virtual enum explain_node_type get_type() { return EXPLAIN_DELETE; } - virtual int get_select_id() { return 1; /* always root */ } - - virtual int print_explain(Explain_query *query, select_result_sink *output, - uint8 explain_flags, bool is_analyze); - virtual void print_explain_json(Explain_query *query, Json_writer *writer, - bool is_analyze); -}; - - -#endif //SQL_EXPLAIN_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_expression_cache.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_expression_cache.h deleted file mode 100644 index 031773a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_expression_cache.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - Copyright (c) 2010, 2011, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_EXPRESSION_CACHE_INCLUDED -#define SQL_EXPRESSION_CACHE_INCLUDED - -#include "sql_select.h" - - -/** - Interface for expression cache - - @note - Parameters of an expression cache interface are set on the creation of the - cache. They are passed when a cache object of the implementation class is - constructed. That's why they are not visible in this interface. -*/ - -extern ulong subquery_cache_miss, subquery_cache_hit; - -class Expression_cache :public Sql_alloc -{ -public: - enum result {ERROR, HIT, MISS}; - - Expression_cache(){}; - virtual ~Expression_cache() {}; - /** - Shall check the presence of expression value in the cache for a given - set of values of the expression parameters. Return the result of the - expression if it's found in the cache. - */ - virtual result check_value(Item **value)= 0; - /** - Shall put the value of an expression for given set of its parameters - into the expression cache - */ - virtual my_bool put_value(Item *value)= 0; - - /** - Print cache parameters - */ - virtual void print(String *str, enum_query_type query_type)= 0; - - /** - Is this cache initialized - */ - virtual bool is_inited()= 0; - /** - Initialize this cache - */ - virtual void init()= 0; - - /** - Save this object's statistics into Expression_cache_tracker object - */ - virtual void update_tracker()= 0; -}; - -struct st_table_ref; -struct st_join_table; -class Item_field; - - -class Expression_cache_tracker :public Sql_alloc -{ -public: - enum expr_cache_state {UNINITED, STOPPED, OK}; - Expression_cache_tracker(Expression_cache *c) : - cache(c), hit(0), miss(0), state(UNINITED) - {} - - Expression_cache *cache; - ulong hit, miss; - enum expr_cache_state state; - - static const char* state_str[3]; - void set(ulong h, ulong m, enum expr_cache_state s) - {hit= h; miss= m; state= s;} - - void fetch_current_stats() - { - if (cache) - cache->update_tracker(); - } -}; - - -/** - Implementation of expression cache over a temporary table -*/ - -class Expression_cache_tmptable :public Expression_cache -{ -public: - Expression_cache_tmptable(THD *thd, List &dependants, Item *value); - virtual ~Expression_cache_tmptable(); - virtual result check_value(Item **value); - virtual my_bool put_value(Item *value); - - void print(String *str, enum_query_type query_type); - bool is_inited() { return inited; }; - void init(); - - void set_tracker(Expression_cache_tracker *st) - { - tracker= st; - update_tracker(); - } - virtual void update_tracker() - { - if (tracker) - { - tracker->set(hit, miss, (inited ? (cache_table ? - Expression_cache_tracker::OK : - Expression_cache_tracker::STOPPED) : - Expression_cache_tracker::UNINITED)); - } - } - -private: - void disable_cache(); - - /* tmp table parameters */ - TMP_TABLE_PARAM cache_table_param; - /* temporary table to store this cache */ - TABLE *cache_table; - /* Thread handle for the temporary table */ - THD *table_thd; - /* EXPALIN/ANALYZE statistics */ - Expression_cache_tracker *tracker; - /* TABLE_REF for index lookup */ - struct st_table_ref ref; - /* Cached result */ - Item_field *cached_result; - /* List of parameter items */ - List &items; - /* Value Item example */ - Item *val; - /* hit/miss counters */ - ulong hit, miss; - /* Set on if the object has been successfully initialized with init() */ - bool inited; -}; - -#endif /* SQL_EXPRESSION_CACHE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_get_diagnostics.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_get_diagnostics.h deleted file mode 100644 index f283aa5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_get_diagnostics.h +++ /dev/null @@ -1,318 +0,0 @@ -/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_GET_DIAGNOSTICS_H -#define SQL_GET_DIAGNOSTICS_H - -/** Diagnostics information forward reference. */ -class Diagnostics_information; - - -/** - Sql_cmd_get_diagnostics represents a GET DIAGNOSTICS statement. - - The GET DIAGNOSTICS statement retrieves exception or completion - condition information from a diagnostics area, usually pertaining - to the last non-diagnostic SQL statement that was executed. -*/ -class Sql_cmd_get_diagnostics : public Sql_cmd -{ -public: - /** - Constructor, used to represent a GET DIAGNOSTICS statement. - - @param info Diagnostics information to be obtained. - */ - Sql_cmd_get_diagnostics(Diagnostics_information *info) - : m_info(info) - {} - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_GET_DIAGNOSTICS; - } - - virtual bool execute(THD *thd); - -private: - /** The information to be obtained. */ - Diagnostics_information *m_info; -}; - - -/** - Represents the diagnostics information to be obtained. - - Diagnostic information is made available through statement - information and condition information items. -*/ -class Diagnostics_information : public Sql_alloc -{ -public: - /** - Which diagnostics area to access. - Only CURRENT is supported for now. - */ - enum Which_area - { - /** Access the first diagnostics area. */ - CURRENT_AREA - }; - - /** Set which diagnostics area to access. */ - void set_which_da(Which_area area) - { m_area= area; } - - /** Get which diagnostics area to access. */ - Which_area get_which_da(void) const - { return m_area; } - - /** - Aggregate diagnostics information. - - @param thd The current thread. - @param da The diagnostics area. - - @retval false on success. - @retval true on error - */ - virtual bool aggregate(THD *thd, const Diagnostics_area *da) = 0; - -protected: - /** - Diagnostics_information objects are allocated in thd->mem_root. - Do not rely on the destructor for any cleanup. - */ - virtual ~Diagnostics_information() - { - DBUG_ASSERT(false); - } - - /** - Evaluate a diagnostics information item in a specific context. - - @param thd The current thread. - @param diag_item The diagnostics information item. - @param ctx The context to evaluate the item. - - @retval false on success. - @retval true on error. - */ - template - bool evaluate(THD *thd, Diag_item *diag_item, Context ctx) - { - Item *value; - - /* Get this item's value. */ - if (! (value= diag_item->get_value(thd, ctx))) - return true; - - /* Set variable/parameter value. */ - return diag_item->set_value(thd, &value); - } - -private: - /** Which diagnostics area to access. */ - Which_area m_area; -}; - - -/** - A diagnostics information item. Used to associate a specific - diagnostics information item to a target variable. -*/ -class Diagnostics_information_item : public Sql_alloc -{ -public: - /** - Set a value for this item. - - @param thd The current thread. - @param value The obtained value. - - @retval false on success. - @retval true on error. - */ - bool set_value(THD *thd, Item **value); - -protected: - /** - Constructor, used to represent a diagnostics information item. - - @param target A target that gets the value of this item. - */ - Diagnostics_information_item(Item *target) - : m_target(target) - {} - - /** - Diagnostics_information_item objects are allocated in thd->mem_root. - Do not rely on the destructor for any cleanup. - */ - virtual ~Diagnostics_information_item() - { - DBUG_ASSERT(false); - } - -private: - /** The target variable that will receive the value of this item. */ - Item *m_target; -}; - - -/** - A statement information item. -*/ -class Statement_information_item : public Diagnostics_information_item -{ -public: - /** The name of a statement information item. */ - enum Name - { - NUMBER, - ROW_COUNT - }; - - /** - Constructor, used to represent a statement information item. - - @param name The name of this item. - @param target A target that gets the value of this item. - */ - Statement_information_item(Name name, Item *target) - : Diagnostics_information_item(target), m_name(name) - {} - - /** Obtain value of this statement information item. */ - Item *get_value(THD *thd, const Diagnostics_area *da); - -private: - /** The name of this statement information item. */ - Name m_name; -}; - - -/** - Statement information. - - @remark Provides information about the execution of a statement. -*/ -class Statement_information : public Diagnostics_information -{ -public: - /** - Constructor, used to represent the statement information of a - GET DIAGNOSTICS statement. - - @param items List of requested statement information items. - */ - Statement_information(List *items) - : m_items(items) - {} - - /** Obtain statement information in the context of a diagnostics area. */ - bool aggregate(THD *thd, const Diagnostics_area *da); - -private: - /* List of statement information items. */ - List *m_items; -}; - - -/** - A condition information item. -*/ -class Condition_information_item : public Diagnostics_information_item -{ -public: - /** - The name of a condition information item. - */ - enum Name - { - CLASS_ORIGIN, - SUBCLASS_ORIGIN, - CONSTRAINT_CATALOG, - CONSTRAINT_SCHEMA, - CONSTRAINT_NAME, - CATALOG_NAME, - SCHEMA_NAME, - TABLE_NAME, - COLUMN_NAME, - CURSOR_NAME, - MESSAGE_TEXT, - MYSQL_ERRNO, - RETURNED_SQLSTATE - }; - - /** - Constructor, used to represent a condition information item. - - @param name The name of this item. - @param target A target that gets the value of this item. - */ - Condition_information_item(Name name, Item *target) - : Diagnostics_information_item(target), m_name(name) - {} - - /** Obtain value of this condition information item. */ - Item *get_value(THD *thd, const Sql_condition *cond); - -private: - /** The name of this condition information item. */ - Name m_name; - - /** Create an string item to represent a condition item string. */ - Item *make_utf8_string_item(THD *thd, const String *str); -}; - - -/** - Condition information. - - @remark Provides information about conditions raised during the - execution of a statement. -*/ -class Condition_information : public Diagnostics_information -{ -public: - /** - Constructor, used to represent the condition information of a - GET DIAGNOSTICS statement. - - @param cond_number_expr Number that identifies the diagnostic condition. - @param items List of requested condition information items. - */ - Condition_information(Item *cond_number_expr, - List *items) - : m_cond_number_expr(cond_number_expr), m_items(items) - {} - - /** Obtain condition information in the context of a diagnostics area. */ - bool aggregate(THD *thd, const Diagnostics_area *da); - -private: - /** - Number that identifies the diagnostic condition for which - information is to be obtained. - */ - Item *m_cond_number_expr; - - /** List of condition information items. */ - List *m_items; -}; - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_handler.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_handler.h deleted file mode 100644 index 4ac0d09..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_handler.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef SQL_HANDLER_INCLUDED -#define SQL_HANDLER_INCLUDED -/* Copyright (c) 2006, 2015, Oracle and/or its affiliates. - Copyright (C) 2010, 2015, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_class.h" /* enum_ha_read_mode */ -#include "my_base.h" /* ha_rkey_function, ha_rows */ -#include "sql_list.h" /* List */ - -/* Open handlers are stored here */ - -class SQL_HANDLER { -public: - TABLE *table; - List fields; /* Fields, set on open */ - THD *thd; - LEX_CSTRING handler_name; - LEX_CSTRING db; - LEX_CSTRING table_name; - MEM_ROOT mem_root; - MYSQL_LOCK *lock; - MDL_request mdl_request; - - key_part_map keypart_map; - int keyno; /* Used key */ - uint key_len; - enum enum_ha_read_modes mode; - - /* This is only used when deleting many handler objects */ - SQL_HANDLER *next; - - Query_arena arena; - char *base_data; - SQL_HANDLER(THD *thd_arg) : - thd(thd_arg), arena(&mem_root, Query_arena::STMT_INITIALIZED) - { init(); clear_alloc_root(&mem_root); base_data= 0; } - void init() - { - keyno= -1; - table= 0; - lock= 0; - mdl_request.ticket= 0; - } - void reset(); - - ~SQL_HANDLER(); -}; - -class THD; -struct TABLE_LIST; - -bool mysql_ha_open(THD *thd, TABLE_LIST *tables, SQL_HANDLER *reopen); -bool mysql_ha_close(THD *thd, TABLE_LIST *tables); -bool mysql_ha_read(THD *, TABLE_LIST *,enum enum_ha_read_modes, const char *, - List *,enum ha_rkey_function,Item *,ha_rows,ha_rows); -void mysql_ha_flush(THD *thd); -void mysql_ha_flush_tables(THD *thd, TABLE_LIST *all_tables); -void mysql_ha_rm_tables(THD *thd, TABLE_LIST *tables); -void mysql_ha_cleanup_no_free(THD *thd); -void mysql_ha_cleanup(THD *thd); -void mysql_ha_set_explicit_lock_duration(THD *thd); -void mysql_ha_rm_temporary_tables(THD *thd); - -SQL_HANDLER *mysql_ha_read_prepare(THD *thd, TABLE_LIST *tables, - enum enum_ha_read_modes mode, - const char *keyname, - List *key_expr, enum ha_rkey_function ha_rkey_mode, - Item *cond); -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_help.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_help.h deleted file mode 100644 index cb3314b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_help.h +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_HELP_INCLUDED -#define SQL_HELP_INCLUDED - -class THD; - - -/* - Function prototypes -*/ - -bool mysqld_help (THD *thd, const char *text); - -#endif /* SQL_HELP_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_hset.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_hset.h deleted file mode 100644 index b3d8165..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_hset.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef SQL_HSET_INCLUDED -#define SQL_HSET_INCLUDED -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "hash.h" - - -/** - A type-safe wrapper around mysys HASH. -*/ - -template -class Hash_set -{ -public: - enum { START_SIZE= 8 }; - /** - Constructs an empty hash. Does not allocate memory, it is done upon - the first insert. Thus does not cause or return errors. - */ - Hash_set(PSI_memory_key psi_key, uchar *(*K)(const T *, size_t *, my_bool), - CHARSET_INFO *cs= &my_charset_bin) - { - my_hash_clear(&m_hash); - m_hash.get_key= (my_hash_get_key)K; - m_hash.charset= cs; - m_hash.array.m_psi_key= psi_key; - } - Hash_set(PSI_memory_key psi_key, CHARSET_INFO *charset, ulong default_array_elements, - size_t key_offset, size_t key_length, my_hash_get_key get_key, - void (*free_element)(void*), uint flags) - { - my_hash_init(psi_key, &m_hash, charset, default_array_elements, key_offset, - key_length, get_key, free_element, flags); - } - /** - Destroy the hash by freeing the buckets table. Does - not call destructors for the elements. - */ - ~Hash_set() - { - my_hash_free(&m_hash); - } - /** - Insert a single value into a hash. Does not tell whether - the value was inserted -- if an identical value existed, - it is not replaced. - - @retval TRUE Out of memory. - @retval FALSE OK. The value either was inserted or existed - in the hash. - */ - bool insert(T *value) - { - my_hash_init_opt(m_hash.array.m_psi_key, &m_hash, m_hash.charset, - START_SIZE, 0, 0, m_hash.get_key, 0, HASH_UNIQUE); - return my_hash_insert(&m_hash, reinterpret_cast(value)); - } - bool remove(T *value) - { - return my_hash_delete(&m_hash, reinterpret_cast(value)); - } - T *find(const void *key, size_t klen) const - { - return (T*)my_hash_search(&m_hash, reinterpret_cast(key), klen); - } - /** Is this hash set empty? */ - bool is_empty() const { return m_hash.records == 0; } - /** Returns the number of unique elements. */ - size_t size() const { return static_cast(m_hash.records); } - /** Erases all elements from the container */ - void clear() { my_hash_reset(&m_hash); } - const T* at(size_t i) const - { - return reinterpret_cast(my_hash_element(const_cast(&m_hash), i)); - } - /** An iterator over hash elements. Is not insert-stable. */ - class Iterator - { - public: - Iterator(Hash_set &hash_set) - : m_hash(&hash_set.m_hash), - m_idx(0) - {} - /** - Return the current element and reposition the iterator to the next - element. - */ - inline T *operator++(int) - { - if (m_idx < m_hash->records) - return reinterpret_cast(my_hash_element(m_hash, m_idx++)); - return NULL; - } - void rewind() { m_idx= 0; } - private: - HASH *m_hash; - uint m_idx; - }; -private: - HASH m_hash; -}; - -#endif // SQL_HSET_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_i_s.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_i_s.h deleted file mode 100644 index b9a768f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_i_s.h +++ /dev/null @@ -1,360 +0,0 @@ -#ifndef SQL_I_S_INCLUDED -#define SQL_I_S_INCLUDED -/* Copyright (c) 2000, 2017, Oracle and/or its affiliates. - Copyright (c) 2009, 2019, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "sql_const.h" // MAX_FIELD_VARCHARLENGTH -#include "sql_basic_types.h" // enum_nullability -#include "sql_string.h" // strlen, MY_CS_NAME_SIZE -#include "lex_string.h" // LEX_CSTRING -#include "mysql_com.h" // enum_field_types -#include "my_time.h" // TIME_SECOND_PART_DIGITS -#include "sql_type.h" // Type_handler_xxx - -struct TABLE_LIST; -struct TABLE; -typedef class Item COND; - -#ifdef MYSQL_CLIENT -#error MYSQL_CLIENT must not be defined -#endif // MYSQL_CLIENT - - -bool schema_table_store_record(THD *thd, TABLE *table); -COND *make_cond_for_info_schema(THD *thd, COND *cond, TABLE_LIST *table); - - -enum enum_show_open_table -{ - SKIP_OPEN_TABLE= 0U, // do not open table - OPEN_FRM_ONLY= 1U, // open FRM file only - OPEN_FULL_TABLE= 2U // open FRM,MYD, MYI files -}; - - -enum enum_show_default -{ - DEFAULT_TYPE_IMPLICIT= 0, - DEFAULT_NONE -}; - - -namespace Show { -class Type -{ - /** - This denotes data type for the column. For the most part, there seems to - be one entry in the enum for each SQL data type, although there seem to - be a number of additional entries in the enum. - */ - const Type_handler *m_type_handler; - /** - For string-type columns, this is the maximum number of - characters. Otherwise, it is the 'display-length' for the column. - */ - uint m_char_length; - uint m_unsigned_flag; - const Typelib *m_typelib; -public: - Type(const Type_handler *th, uint length, uint unsigned_flag, - const Typelib *typelib= NULL) - :m_type_handler(th), m_char_length(length), m_unsigned_flag(unsigned_flag), - m_typelib(typelib) - { } - const Type_handler *type_handler() const { return m_type_handler; } - uint char_length() const { return m_char_length; } - uint decimal_precision() const { return (m_char_length / 100) % 100; } - uint decimal_scale() const { return m_char_length % 10; } - uint fsp() const - { - DBUG_ASSERT(m_char_length <= TIME_SECOND_PART_DIGITS); - return m_char_length; - } - uint unsigned_flag() const { return m_unsigned_flag; } - const Typelib *typelib() const { return m_typelib; } -}; -} // namespace Show - - - -class ST_FIELD_INFO: public Show::Type -{ -protected: - LEX_CSTRING m_name; // I_S column name - enum_nullability m_nullability; // NULLABLE or NOT NULL - enum_show_default m_def; // Whether has a DEFAULT value - LEX_CSTRING m_old_name; // SHOW column name - enum_show_open_table m_open_method; -public: - ST_FIELD_INFO(const LEX_CSTRING &name, const Type &type, - enum_nullability nullability, - enum_show_default def, - LEX_CSTRING &old_name, - enum_show_open_table open_method) - :Type(type), m_name(name), - m_nullability(nullability), - m_def(def), - m_old_name(old_name), - m_open_method(open_method) - { } - ST_FIELD_INFO(const char *name, const Type &type, - enum_nullability nullability, - enum_show_default def, - const char *old_name, - enum_show_open_table open_method) - :Type(type), - m_nullability(nullability), - m_def(def), - m_open_method(open_method) - { - m_name.str= name; - m_name.length= safe_strlen(name); - m_old_name.str= old_name; - m_old_name.length= safe_strlen(old_name); - } - const LEX_CSTRING &name() const { return m_name; } - bool nullable() const { return m_nullability == NULLABLE; } - enum_show_default def() const { return m_def; } - const LEX_CSTRING &old_name() const { return m_old_name; } - enum_show_open_table open_method() const { return m_open_method; } - bool end_marker() const { return m_name.str == NULL; } -}; - - -namespace Show -{ - - -class Enum: public Type -{ -public: - Enum(const Typelib *typelib) :Type(&type_handler_enum, 0, false, typelib) { } -}; - - -class Blob: public Type -{ -public: - Blob(uint length) :Type(&type_handler_blob, length, false) { } -}; - - -class Varchar: public Type -{ -public: - Varchar(uint length) :Type(&type_handler_varchar, length, false) - { - DBUG_ASSERT(length * 3 <= MAX_FIELD_VARCHARLENGTH); - } -}; - - -class Longtext: public Type -{ -public: - Longtext(uint length) :Type(&type_handler_varchar, length, false) { } -}; - - -class Yesno: public Varchar -{ -public: - Yesno(): Varchar(3) { } -}; - - -class Catalog: public Varchar -{ -public: - Catalog(): Varchar(FN_REFLEN) { } -}; - - -class Name: public Varchar -{ -public: - Name(): Varchar(NAME_CHAR_LEN) { } -}; - - -class Definer: public Varchar -{ -public: - Definer(): Varchar(DEFINER_CHAR_LENGTH) { } -}; - - -class Userhost: public Varchar -{ -public: - Userhost(): Varchar(USERNAME_CHAR_LENGTH + HOSTNAME_LENGTH + 2) { } -}; - - -class CSName: public Varchar -{ -public: - CSName(): Varchar(MY_CS_NAME_SIZE) { } -}; - - -class SQLMode: public Varchar -{ -public: - SQLMode(): Varchar(32*256) { } -}; - - -class Datetime: public Type -{ -public: - Datetime(uint dec) :Type(&type_handler_datetime2, dec, false) { } -}; - - -class Decimal: public Type -{ -public: - Decimal(uint length) :Type(&type_handler_newdecimal, length, false) { } -}; - - -class ULonglong: public Type -{ -public: - ULonglong(uint length) :Type(&type_handler_ulonglong, length, true) { } - ULonglong() :ULonglong(MY_INT64_NUM_DECIMAL_DIGITS) { } -}; - - -class ULong: public Type -{ -public: - ULong(uint length) :Type(&type_handler_ulong, length, true) { } - ULong() :ULong(MY_INT32_NUM_DECIMAL_DIGITS) { } -}; - - -class SLonglong: public Type -{ -public: - SLonglong(uint length) :Type(&type_handler_slonglong, length, false) { } - SLonglong() :SLonglong(MY_INT64_NUM_DECIMAL_DIGITS) { } -}; - - -class SLong: public Type -{ -public: - SLong(uint length) :Type(&type_handler_slong, length, false) { } - SLong() :SLong(MY_INT32_NUM_DECIMAL_DIGITS) { } -}; - - -class SShort: public Type -{ -public: - SShort(uint length) :Type(&type_handler_sshort, length, false) { } -}; - - -class STiny: public Type -{ -public: - STiny(uint length) :Type(&type_handler_stiny, length, false) { } -}; - - -class Double: public Type -{ -public: - Double(uint length) :Type(&type_handler_double, length, false) { } -}; - - -class Float: public Type -{ -public: - Float(uint length) :Type(&type_handler_float, length, false) { } -}; - - - -class Column: public ST_FIELD_INFO -{ -public: - Column(const char *name, const Type &type, - enum_nullability nullability, - enum_show_default def, - const char *old_name, - enum_show_open_table open_method= SKIP_OPEN_TABLE) - :ST_FIELD_INFO(name, type, nullability, def, old_name, open_method) - { } - Column(const char *name, const Type &type, enum_nullability nullability, - enum_show_default def, - enum_show_open_table open_method= SKIP_OPEN_TABLE) - :ST_FIELD_INFO(name, type, nullability, def, NullS, open_method) - { } - Column(const char *name, const Type &type, - enum_nullability nullability, - const char *old_name, - enum_show_open_table open_method= SKIP_OPEN_TABLE) - :ST_FIELD_INFO(name, type, nullability, DEFAULT_TYPE_IMPLICIT, - old_name, open_method) - { } - Column(const char *name, const Type &type, - enum_nullability nullability, - enum_show_open_table open_method= SKIP_OPEN_TABLE) - :ST_FIELD_INFO(name, type, nullability, DEFAULT_TYPE_IMPLICIT, - NullS, open_method) - { } -}; - - -// End marker -class CEnd: public Column -{ -public: - CEnd() :Column(NullS, Varchar(0), NOT_NULL, NullS, SKIP_OPEN_TABLE) { } -}; - - -} // namespace Show - - -struct TABLE_LIST; -typedef class Item COND; - -typedef struct st_schema_table -{ - const char *table_name; - ST_FIELD_INFO *fields_info; - /* for FLUSH table_name */ - int (*reset_table) (); - /* Fill table with data */ - int (*fill_table) (THD *thd, TABLE_LIST *tables, COND *cond); - /* Handle fileds for old SHOW */ - int (*old_format) (THD *thd, struct st_schema_table *schema_table); - int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table, - bool res, const LEX_CSTRING *db_name, - const LEX_CSTRING *table_name); - int idx_field1, idx_field2; - bool hidden; - uint i_s_requested_object; /* the object we need to open(TABLE | VIEW) */ -} ST_SCHEMA_TABLE; - - -#endif // SQL_I_S_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_insert.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_insert.h deleted file mode 100644 index 80666a8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_insert.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_INSERT_INCLUDED -#define SQL_INSERT_INCLUDED - -#include "sql_class.h" /* enum_duplicates */ -#include "sql_list.h" - -/* Instead of including sql_lex.h we add this typedef here */ -typedef List List_item; -typedef struct st_copy_info COPY_INFO; - -int mysql_prepare_insert(THD *thd, TABLE_LIST *table_list, - List &fields, List_item *values, - List &update_fields, - List &update_values, enum_duplicates duplic, - COND **where, bool select_insert); -bool mysql_insert(THD *thd,TABLE_LIST *table,List &fields, - List &values, List &update_fields, - List &update_values, enum_duplicates flag, - bool ignore, select_result* result); -void upgrade_lock_type_for_insert(THD *thd, thr_lock_type *lock_type, - enum_duplicates duplic, - bool is_multi_insert); -int check_that_all_fields_are_given_values(THD *thd, TABLE *entry, - TABLE_LIST *table_list); -int vers_insert_history_row(TABLE *table); -int check_duplic_insert_without_overlaps(THD *thd, TABLE *table, - enum_duplicates duplic); -int write_record(THD *thd, TABLE *table, COPY_INFO *info, - select_result *returning= NULL); -void kill_delayed_threads(void); -bool binlog_create_table(THD *thd, TABLE *table, bool replace); -bool binlog_drop_table(THD *thd, TABLE *table); - -#ifdef EMBEDDED_LIBRARY -inline void kill_delayed_threads(void) {} -#endif - -#endif /* SQL_INSERT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_join_cache.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_join_cache.h deleted file mode 100644 index 7b8b942..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_join_cache.h +++ /dev/null @@ -1,1443 +0,0 @@ -/* - Copyright (c) 2011, 2012, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - This file contains declarations for implementations - of block based join algorithms -*/ - -#define JOIN_CACHE_INCREMENTAL_BIT 1 -#define JOIN_CACHE_HASHED_BIT 2 -#define JOIN_CACHE_BKA_BIT 4 - -/* - Categories of data fields of variable length written into join cache buffers. - The value of any of these fields is written into cache together with the - prepended length of the value. -*/ -#define CACHE_BLOB 1 /* blob field */ -#define CACHE_STRIPPED 2 /* field stripped of trailing spaces */ -#define CACHE_VARSTR1 3 /* short string value (length takes 1 byte) */ -#define CACHE_VARSTR2 4 /* long string value (length takes 2 bytes) */ -#define CACHE_ROWID 5 /* ROWID field */ - -/* - The CACHE_FIELD structure used to describe fields of records that - are written into a join cache buffer from record buffers and backward. -*/ -typedef struct st_cache_field { - uchar *str; /**< buffer from/to where the field is to be copied */ - uint length; /**< maximal number of bytes to be copied from/to str */ - /* - Field object for the moved field - (0 - for a flag field, see JOIN_CACHE::create_flag_fields). - */ - Field *field; - uint type; /**< category of the of the copied field (CACHE_BLOB et al.) */ - /* - The number of the record offset value for the field in the sequence - of offsets placed after the last field of the record. These - offset values are used to access fields referred to from other caches. - If the value is 0 then no offset for the field is saved in the - trailing sequence of offsets. - */ - uint referenced_field_no; - /* The remaining structure fields are used as containers for temp values */ - uint blob_length; /**< length of the blob to be copied */ - uint offset; /**< field offset to be saved in cache buffer */ -} CACHE_FIELD; - - -class JOIN_TAB_SCAN; - -class EXPLAIN_BKA_TYPE; - -/* - JOIN_CACHE is the base class to support the implementations of - - Block Nested Loop (BNL) Join Algorithm, - - Block Nested Loop Hash (BNLH) Join Algorithm, - - Batched Key Access (BKA) Join Algorithm. - - The first algorithm is supported by the derived class JOIN_CACHE_BNL, - the second algorithm is supported by the derived class JOIN_CACHE_BNLH, - while the third algorithm is implemented in two variant supported by - the classes JOIN_CACHE_BKA and JOIN_CACHE_BKAH. - These three algorithms have a lot in common. Each of them first accumulates - the records of the left join operand in a join buffer and then searches for - matching rows of the second operand for all accumulated records. - For the first two algorithms this strategy saves on logical I/O operations: - the entire set of records from the join buffer requires only one look-through - of the records provided by the second operand. - For the third algorithm the accumulation of records allows to optimize - fetching rows of the second operand from disk for some engines (MyISAM, - InnoDB), or to minimize the number of round-trips between the Server and - the engine nodes. -*/ - -class JOIN_CACHE :public Sql_alloc -{ - -private: - - /* Size of the offset of a record from the cache */ - uint size_of_rec_ofs; - /* Size of the length of a record in the cache */ - uint size_of_rec_len; - /* Size of the offset of a field within a record in the cache */ - uint size_of_fld_ofs; - - /* This structure is used only for explain, not for execution */ - bool for_explain_only; - -protected: - - /* 3 functions below actually do not use the hidden parameter 'this' */ - - /* Calculate the number of bytes used to store an offset value */ - uint offset_size(size_t len) - { return (len < 256 ? 1 : len < 256*256 ? 2 : 4); } - - /* Get the offset value that takes ofs_sz bytes at the position ptr */ - ulong get_offset(uint ofs_sz, uchar *ptr) - { - switch (ofs_sz) { - case 1: return uint(*ptr); - case 2: return uint2korr(ptr); - case 4: return uint4korr(ptr); - } - return 0; - } - - /* Set the offset value ofs that takes ofs_sz bytes at the position ptr */ - void store_offset(uint ofs_sz, uchar *ptr, ulong ofs) - { - switch (ofs_sz) { - case 1: *ptr= (uchar) ofs; return; - case 2: int2store(ptr, (uint16) ofs); return; - case 4: int4store(ptr, (uint32) ofs); return; - } - } - - /* - The maximum total length of the fields stored for a record in the cache. - For blob fields only the sizes of the blob lengths are taken into account. - */ - uint length; - - /* - Representation of the executed multi-way join through which all needed - context can be accessed. - */ - JOIN *join; - - /* - JOIN_TAB of the first table that can have it's fields in the join cache. - That is, tables in the [start_tab, tab) range can have their fields in the - join cache. - If a join tab in the range represents an SJM-nest, then all tables from the - nest can have their fields in the join cache, too. - */ - JOIN_TAB *start_tab; - - /* - The total number of flag and data fields that can appear in a record - written into the cache. Fields with null values are always skipped - to save space. - */ - uint fields; - - /* - The total number of flag fields in a record put into the cache. They are - used for table null bitmaps, table null row flags, and an optional match - flag. Flag fields go before other fields in a cache record with the match - flag field placed always at the very beginning of the record. - */ - uint flag_fields; - - /* The total number of blob fields that are written into the cache */ - uint blobs; - - /* - The total number of fields referenced from field descriptors for other join - caches. These fields are used to construct key values. - When BKA join algorithm is employed the constructed key values serve to - access matching rows with index lookups. - The key values are put into a hash table when the BNLH join algorithm - is employed and when BKAH is used for the join operation. - */ - uint referenced_fields; - - /* - The current number of already created data field descriptors. - This number can be useful for implementations of the init methods. - */ - uint data_field_count; - - /* - The current number of already created pointers to the data field - descriptors. This number can be useful for implementations of - the init methods. - */ - uint data_field_ptr_count; - - /* - Array of the descriptors of fields containing 'fields' elements. - These are all fields that are stored for a record in the cache. - */ - CACHE_FIELD *field_descr; - - /* - Array of pointers to the blob descriptors that contains 'blobs' elements. - */ - CACHE_FIELD **blob_ptr; - - /* - This flag indicates that records written into the join buffer contain - a match flag field. The flag must be set by the init method. - */ - bool with_match_flag; - /* - This flag indicates that any record is prepended with the length of the - record which allows us to skip the record or part of it without reading. - */ - bool with_length; - - /* - The maximal number of bytes used for a record representation in - the cache excluding the space for blob data. - For future derived classes this representation may contains some - redundant info such as a key value associated with the record. - */ - uint pack_length; - /* - The value of pack_length incremented by the total size of all - pointers of a record in the cache to the blob data. - */ - uint pack_length_with_blob_ptrs; - - /* - The total size of the record base prefix. The base prefix of record may - include the following components: - - the length of the record - - the link to a record in a previous buffer. - Each record in the buffer are supplied with the same set of the components. - */ - uint base_prefix_length; - - /* - The expected length of a record in the join buffer together with - all prefixes and postfixes - */ - size_t avg_record_length; - - /* The expected size of the space per record in the auxiliary buffer */ - size_t avg_aux_buffer_incr; - - /* Expected join buffer space used for one record */ - size_t space_per_record; - - /* Pointer to the beginning of the join buffer */ - uchar *buff; - /* - Size of the entire memory allocated for the join buffer. - Part of this memory may be reserved for the auxiliary buffer. - */ - size_t buff_size; - /* The minimal join buffer size when join buffer still makes sense to use */ - size_t min_buff_size; - /* The maximum expected size if the join buffer to be used */ - size_t max_buff_size; - /* Size of the auxiliary buffer */ - size_t aux_buff_size; - - /* The number of records put into the join buffer */ - size_t records; - /* - The number of records in the fully refilled join buffer of - the minimal size equal to min_buff_size - */ - size_t min_records; - /* - The maximum expected number of records to be put in the join buffer - at one refill - */ - size_t max_records; - - /* - Pointer to the current position in the join buffer. - This member is used both when writing to buffer and - when reading from it. - */ - uchar *pos; - /* - Pointer to the first free position in the join buffer, - right after the last record into it. - */ - uchar *end_pos; - - /* - Pointer to the beginning of the first field of the current read/write - record from the join buffer. The value is adjusted by the - get_record/put_record functions. - */ - uchar *curr_rec_pos; - /* - Pointer to the beginning of the first field of the last record - from the join buffer. - */ - uchar *last_rec_pos; - - /* - Flag is set if the blob data for the last record in the join buffer - is in record buffers rather than in the join cache. - */ - bool last_rec_blob_data_is_in_rec_buff; - - /* - Pointer to the position to the current record link. - Record links are used only with linked caches. Record links allow to set - connections between parts of one join record that are stored in different - join buffers. - In the simplest case a record link is just a pointer to the beginning of - the record stored in the buffer. - In a more general case a link could be a reference to an array of pointers - to records in the buffer. - */ - uchar *curr_rec_link; - - /* - This flag is set to TRUE if join_tab is the first inner table of an outer - join and the latest record written to the join buffer is detected to be - null complemented after checking on conditions over the outer tables for - this outer join operation - */ - bool last_written_is_null_compl; - - /* - The number of fields put in the join buffer of the join cache that are - used in building keys to access the table join_tab - */ - uint local_key_arg_fields; - /* - The total number of the fields in the previous caches that are used - in building keys to access the table join_tab - */ - uint external_key_arg_fields; - - /* - This flag indicates that the key values will be read directly from the join - buffer. It will save us building key values in the key buffer. - */ - bool use_emb_key; - /* The length of an embedded key value */ - uint emb_key_length; - - /* - This object provides the methods to iterate over records of - the joined table join_tab when looking for join matches between - records from join buffer and records from join_tab. - BNL and BNLH join algorithms retrieve all records from join_tab, - while BKA/BKAH algorithm iterates only over those records from - join_tab that can be accessed by look-ups with join keys built - from records in join buffer. - */ - JOIN_TAB_SCAN *join_tab_scan; - - void calc_record_fields(); - void collect_info_on_key_args(); - int alloc_fields(); - void create_flag_fields(); - void create_key_arg_fields(); - void create_remaining_fields(); - void set_constants(); - int alloc_buffer(); - - /* Shall reallocate the join buffer */ - virtual int realloc_buffer(); - - /* Check the possibility to read the access keys directly from join buffer */ - bool check_emb_key_usage(); - - uint get_size_of_rec_offset() { return size_of_rec_ofs; } - uint get_size_of_rec_length() { return size_of_rec_len; } - uint get_size_of_fld_offset() { return size_of_fld_ofs; } - - uchar *get_rec_ref(uchar *ptr) - { - return buff+get_offset(size_of_rec_ofs, ptr-size_of_rec_ofs); - } - ulong get_rec_length(uchar *ptr) - { - return (ulong) get_offset(size_of_rec_len, ptr); - } - ulong get_fld_offset(uchar *ptr) - { - return (ulong) get_offset(size_of_fld_ofs, ptr); - } - - void store_rec_ref(uchar *ptr, uchar* ref) - { - store_offset(size_of_rec_ofs, ptr-size_of_rec_ofs, (ulong) (ref-buff)); - } - void store_rec_length(uchar *ptr, ulong len) - { - store_offset(size_of_rec_len, ptr, len); - } - void store_fld_offset(uchar *ptr, ulong ofs) - { - store_offset(size_of_fld_ofs, ptr, ofs); - } - - /* Write record fields and their required offsets into the join buffer */ - uint write_record_data(uchar *link, bool *is_full); - - /* Get the total length of all prefixes of a record in the join buffer */ - virtual uint get_prefix_length() { return base_prefix_length; } - /* Get maximum total length of all affixes of a record in the join buffer */ - virtual uint get_record_max_affix_length(); - - /* - Shall get maximum size of the additional space per record used for - record keys - */ - virtual uint get_max_key_addon_space_per_record() { return 0; } - - /* - This method must determine for how much the auxiliary buffer should be - incremented when a new record is added to the join buffer. - If no auxiliary buffer is needed the function should return 0. - */ - virtual uint aux_buffer_incr(size_t recno); - - /* Shall calculate how much space is remaining in the join buffer */ - virtual size_t rem_space() - { - return MY_MAX(buff_size-(end_pos-buff)-aux_buff_size,0); - } - - /* - Shall calculate how much space is taken by allocation of the key - for a record in the join buffer - */ - virtual uint extra_key_length() { return 0; } - - /* Read all flag and data fields of a record from the join buffer */ - uint read_all_record_fields(); - - /* Read all flag fields of a record from the join buffer */ - uint read_flag_fields(); - - /* Read a data record field from the join buffer */ - uint read_record_field(CACHE_FIELD *copy, bool last_record); - - /* Read a referenced field from the join buffer */ - bool read_referenced_field(CACHE_FIELD *copy, uchar *rec_ptr, uint *len); - - /* - Shall skip record from the join buffer if its match flag - is set to MATCH_FOUND - */ - virtual bool skip_if_matched(); - - /* - Shall skip record from the join buffer if its match flag - commands to do so - */ - virtual bool skip_if_not_needed_match(); - - /* - True if rec_ptr points to the record whose blob data stay in - record buffers - */ - bool blob_data_is_in_rec_buff(uchar *rec_ptr) - { - return rec_ptr == last_rec_pos && last_rec_blob_data_is_in_rec_buff; - } - - /* Find matches from the next table for records from the join buffer */ - virtual enum_nested_loop_state join_matching_records(bool skip_last); - - /* Shall set an auxiliary buffer up (currently used only by BKA joins) */ - virtual int setup_aux_buffer(HANDLER_BUFFER &aux_buff) - { - DBUG_ASSERT(0); - return 0; - } - - /* - Shall get the number of ranges in the cache buffer passed - to the MRR interface - */ - virtual uint get_number_of_ranges_for_mrr() { return 0; }; - - /* - Shall prepare to look for records from the join cache buffer that would - match the record of the joined table read into the record buffer - */ - virtual bool prepare_look_for_matches(bool skip_last)= 0; - /* - Shall return a pointer to the record from join buffer that is checked - as the next candidate for a match with the current record from join_tab. - Each implementation of this virtual function should bare in mind - that the record position it returns shall be exactly the position - passed as the parameter to the implementations of the virtual functions - skip_next_candidate_for_match and read_next_candidate_for_match. - */ - virtual uchar *get_next_candidate_for_match()= 0; - /* - Shall check whether the given record from the join buffer has its match - flag settings commands to skip the record in the buffer. - */ - virtual bool skip_next_candidate_for_match(uchar *rec_ptr)= 0; - /* - Shall read the given record from the join buffer into the - the corresponding record buffer - */ - virtual void read_next_candidate_for_match(uchar *rec_ptr)= 0; - - /* - Shall return the location of the association label returned by - the multi_read_range_next function for the current record loaded - into join_tab's record buffer - */ - virtual uchar **get_curr_association_ptr() { return 0; }; - - /* Add null complements for unmatched outer records from the join buffer */ - virtual enum_nested_loop_state join_null_complements(bool skip_last); - - /* Restore the fields of the last record from the join buffer */ - virtual void restore_last_record(); - - /* Set match flag for a record in join buffer if it has not been set yet */ - bool set_match_flag_if_none(JOIN_TAB *first_inner, uchar *rec_ptr); - - enum_nested_loop_state generate_full_extensions(uchar *rec_ptr); - - /* Check matching to a partial join record from the join buffer */ - bool check_match(uchar *rec_ptr); - - /* - This constructor creates an unlinked join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. - */ - JOIN_CACHE(JOIN *j, JOIN_TAB *tab) - { - join= j; - join_tab= tab; - prev_cache= next_cache= 0; - buff= 0; - } - - /* - This constructor creates a linked join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. The parameter 'prev' specifies the previous - cache object to which this cache is linked. - */ - JOIN_CACHE(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) - { - join= j; - join_tab= tab; - next_cache= 0; - prev_cache= prev; - buff= 0; - if (prev) - prev->next_cache= this; - } - -public: - - /* - The enumeration type Join_algorithm includes a mnemonic constant for - each join algorithm that employs join buffers - */ - - enum Join_algorithm - { - BNL_JOIN_ALG, /* Block Nested Loop Join algorithm */ - BNLH_JOIN_ALG, /* Block Nested Loop Hash Join algorithm */ - BKA_JOIN_ALG, /* Batched Key Access Join algorithm */ - BKAH_JOIN_ALG /* Batched Key Access with Hash Table Join Algorithm */ - }; - - /* - The enumeration type Match_flag describes possible states of the match flag - field stored for the records of the first inner tables of outer joins and - semi-joins in the cases when the first match strategy is used for them. - When a record with match flag field is written into the join buffer the - state of the field usually is MATCH_NOT_FOUND unless this is a record of the - first inner table of the outer join for which the on precondition (the - condition from on expression over outer tables) has turned out not to be - true. In the last case the state of the match flag is MATCH_IMPOSSIBLE. - The state of the match flag field is changed to MATCH_FOUND as soon as - the first full matching combination of inner tables of the outer join or - the semi-join is discovered. - */ - enum Match_flag { MATCH_NOT_FOUND, MATCH_FOUND, MATCH_IMPOSSIBLE }; - - /* Table to be joined with the partial join records from the cache */ - JOIN_TAB *join_tab; - - /* Pointer to the previous join cache if there is any */ - JOIN_CACHE *prev_cache; - /* Pointer to the next join cache if there is any */ - JOIN_CACHE *next_cache; - - /* Shall initialize the join cache structure */ - virtual int init(bool for_explain); - - /* Get the current size of the cache join buffer */ - size_t get_join_buffer_size() { return buff_size; } - /* Set the size of the cache join buffer to a new value */ - void set_join_buffer_size(size_t sz) { buff_size= sz; } - - /* Get the minimum possible size of the cache join buffer */ - virtual size_t get_min_join_buffer_size(); - /* Get the maximum possible size of the cache join buffer */ - virtual size_t get_max_join_buffer_size(bool optimize_buff_size); - - /* Shrink the size if the cache join buffer in a given ratio */ - bool shrink_join_buffer_in_ratio(ulonglong n, ulonglong d); - - /* Shall return the type of the employed join algorithm */ - virtual enum Join_algorithm get_join_alg()= 0; - - /* - The function shall return TRUE only when there is a key access - to the join table - */ - virtual bool is_key_access()= 0; - - /* Shall reset the join buffer for reading/writing */ - virtual void reset(bool for_writing); - - /* - This function shall add a record into the join buffer and return TRUE - if it has been decided that it should be the last record in the buffer. - */ - virtual bool put_record(); - - /* - This function shall read the next record into the join buffer and return - TRUE if there is no more next records. - */ - virtual bool get_record(); - - /* - This function shall read the record at the position rec_ptr - in the join buffer - */ - virtual void get_record_by_pos(uchar *rec_ptr); - - /* Shall return the value of the match flag for the positioned record */ - virtual enum Match_flag get_match_flag_by_pos(uchar *rec_ptr); - - /* Shall return the position of the current record */ - virtual uchar *get_curr_rec() { return curr_rec_pos; } - - /* Shall set the current record link */ - virtual void set_curr_rec_link(uchar *link) { curr_rec_link= link; } - - /* Shall return the current record link */ - virtual uchar *get_curr_rec_link() - { - return (curr_rec_link ? curr_rec_link : get_curr_rec()); - } - - /* Join records from the join buffer with records from the next join table */ - enum_nested_loop_state join_records(bool skip_last); - - /* Add a comment on the join algorithm employed by the join cache */ - virtual bool save_explain_data(EXPLAIN_BKA_TYPE *explain); - - THD *thd(); - - virtual ~JOIN_CACHE() {} - void reset_join(JOIN *j) { join= j; } - void free() - { - my_free(buff); - buff= 0; - } - - friend class JOIN_CACHE_HASHED; - friend class JOIN_CACHE_BNL; - friend class JOIN_CACHE_BKA; - friend class JOIN_TAB_SCAN; - friend class JOIN_TAB_SCAN_MRR; - -}; - - -/* - The class JOIN_CACHE_HASHED is the base class for the classes - JOIN_CACHE_HASHED_BNL and JOIN_CACHE_HASHED_BKA. The first of them supports - an implementation of Block Nested Loop Hash (BNLH) Join Algorithm, - while the second is used for a variant of the BKA Join algorithm that performs - only one lookup for any records from join buffer with the same key value. - For a join cache of this class the records from the join buffer that have - the same access key are linked into a chain attached to a key entry structure - that either itself contains the key value, or, in the case when the keys are - embedded, refers to its occurrence in one of the records from the chain. - To build the chains with the same keys a hash table is employed. It is placed - at the very end of the join buffer. The array of hash entries is allocated - first at the very bottom of the join buffer, while key entries are placed - before this array. - A hash entry contains a header of the list of the key entries with the same - hash value. - Each key entry is a structure of the following type: - struct st_join_cache_key_entry { - union { - uchar[] value; - cache_ref *value_ref; // offset from the beginning of the buffer - } hash_table_key; - key_ref next_key; // offset backward from the beginning of hash table - cache_ref *last_rec // offset from the beginning of the buffer - } - The references linking the records in a chain are always placed at the very - beginning of the record info stored in the join buffer. The records are - linked in a circular list. A new record is always added to the end of this - list. - - The following picture represents a typical layout for the info stored in the - join buffer of a join cache object of the JOIN_CACHE_HASHED class. - - buff - V - +----------------------------------------------------------------------------+ - | |[*]record_1_1| | - | ^ | | - | | +--------------------------------------------------+ | - | | |[*]record_2_1| | | - | | ^ | V | - | | | +------------------+ |[*]record_1_2| | - | | +--------------------+-+ | | - |+--+ +---------------------+ | | +-------------+ | - || | | V | | | - |||[*]record_3_1| |[*]record_1_3| |[*]record_2_2| | | - ||^ ^ ^ | | - ||+----------+ | | | | - ||^ | |<---------------------------+-------------------+ | - |++ | | ... mrr | buffer ... ... | | | - | | | | | - | +-----+--------+ | +-----|-------+ | - | V | | | V | | | - ||key_3|[/]|[*]| | | |key_2|[/]|[*]| | | - | +-+---|-----------------------+ | | - | V | | | | | - | |key_1|[*]|[*]| | | ... |[*]| ... |[*]| ... | | - +----------------------------------------------------------------------------+ - ^ ^ ^ - | i-th entry j-th entry - hash table - - i-th hash entry: - circular record chain for key_1: - record_1_1 - record_1_2 - record_1_3 (points to record_1_1) - circular record chain for key_3: - record_3_1 (points to itself) - - j-th hash entry: - circular record chain for key_2: - record_2_1 - record_2_2 (points to record_2_1) - -*/ - -class JOIN_CACHE_HASHED: public JOIN_CACHE -{ - - typedef uint (JOIN_CACHE_HASHED::*Hash_func) (uchar *key, uint key_len); - typedef bool (JOIN_CACHE_HASHED::*Hash_cmp_func) (uchar *key1, uchar *key2, - uint key_len); - -private: - - /* Size of the offset of a key entry in the hash table */ - uint size_of_key_ofs; - - /* - Length of the key entry in the hash table. - A key entry either contains the key value, or it contains a reference - to the key value if use_emb_key flag is set for the cache. - */ - uint key_entry_length; - - /* The beginning of the hash table in the join buffer */ - uchar *hash_table; - /* Number of hash entries in the hash table */ - uint hash_entries; - - - /* The position of the currently retrieved key entry in the hash table */ - uchar *curr_key_entry; - - /* The offset of the data fields from the beginning of the record fields */ - uint data_fields_offset; - - inline uint get_hash_idx_simple(uchar *key, uint key_len); - inline uint get_hash_idx_complex(uchar *key, uint key_len); - - inline bool equal_keys_simple(uchar *key1, uchar *key2, uint key_len); - inline bool equal_keys_complex(uchar *key1, uchar *key2, uint key_len); - - int init_hash_table(); - void cleanup_hash_table(); - -protected: - - /* - Index info on the TABLE_REF object used by the hash join - to look for matching records - */ - KEY *ref_key_info; - /* - Number of the key parts the TABLE_REF object used by the hash join - to look for matching records - */ - uint ref_used_key_parts; - - /* - The hash function used in the hash table, - usually set by the init() method - */ - Hash_func hash_func; - /* - The function to check whether two key entries in the hash table - are equal or not, usually set by the init() method - */ - Hash_cmp_func hash_cmp_func; - - /* - Length of a key value. - It is assumed that all key values have the same length. - */ - uint key_length; - /* Buffer to store key values for probing */ - uchar *key_buff; - - /* Number of key entries in the hash table (number of distinct keys) */ - uint key_entries; - - /* The position of the last key entry in the hash table */ - uchar *last_key_entry; - - /* - The offset of the record fields from the beginning of the record - representation. The record representation starts with a reference to - the next record in the key record chain followed by the length of - the trailing record data followed by a reference to the record segment - in the previous cache, if any, followed by the record fields. - */ - uint rec_fields_offset; - - uint get_size_of_key_offset() { return size_of_key_ofs; } - - /* - Get the position of the next_key_ptr field pointed to by - a linking reference stored at the position key_ref_ptr. - This reference is actually the offset backward from the - beginning of hash table. - */ - uchar *get_next_key_ref(uchar *key_ref_ptr) - { - return hash_table-get_offset(size_of_key_ofs, key_ref_ptr); - } - - /* - Store the linking reference to the next_key_ptr field at - the position key_ref_ptr. The position of the next_key_ptr - field is pointed to by ref. The stored reference is actually - the offset backward from the beginning of the hash table. - */ - void store_next_key_ref(uchar *key_ref_ptr, uchar *ref) - { - store_offset(size_of_key_ofs, key_ref_ptr, (ulong) (hash_table-ref)); - } - - /* - Check whether the reference to the next_key_ptr field at the position - key_ref_ptr contains a nil value. - */ - bool is_null_key_ref(uchar *key_ref_ptr) - { - ulong nil= 0; - return memcmp(key_ref_ptr, &nil, size_of_key_ofs ) == 0; - } - - /* - Set the reference to the next_key_ptr field at the position - key_ref_ptr equal to nil. - */ - void store_null_key_ref(uchar *key_ref_ptr) - { - ulong nil= 0; - store_offset(size_of_key_ofs, key_ref_ptr, nil); - } - - uchar *get_next_rec_ref(uchar *ref_ptr) - { - return buff+get_offset(get_size_of_rec_offset(), ref_ptr); - } - - void store_next_rec_ref(uchar *ref_ptr, uchar *ref) - { - store_offset(get_size_of_rec_offset(), ref_ptr, (ulong) (ref-buff)); - } - - /* - Get the position of the embedded key value for the current - record pointed to by get_curr_rec(). - */ - uchar *get_curr_emb_key() - { - return get_curr_rec()+data_fields_offset; - } - - /* - Get the position of the embedded key value pointed to by a reference - stored at ref_ptr. The stored reference is actually the offset from - the beginning of the join buffer. - */ - uchar *get_emb_key(uchar *ref_ptr) - { - return buff+get_offset(get_size_of_rec_offset(), ref_ptr); - } - - /* - Store the reference to an embedded key at the position key_ref_ptr. - The position of the embedded key is pointed to by ref. The stored - reference is actually the offset from the beginning of the join buffer. - */ - void store_emb_key_ref(uchar *ref_ptr, uchar *ref) - { - store_offset(get_size_of_rec_offset(), ref_ptr, (ulong) (ref-buff)); - } - - /* Get the total length of all prefixes of a record in hashed join buffer */ - uint get_prefix_length() - { - return base_prefix_length + get_size_of_rec_offset(); - } - - /* - Get maximum size of the additional space per record used for - the hash table with record keys - */ - uint get_max_key_addon_space_per_record(); - - /* - Calculate how much space in the buffer would not be occupied by - records, key entries and additional memory for the MMR buffer. - */ - size_t rem_space() - { - return MY_MAX(last_key_entry-end_pos-aux_buff_size,0); - } - - /* - Calculate how much space is taken by allocation of the key - entry for a record in the join buffer - */ - uint extra_key_length() { return key_entry_length; } - - /* - Skip record from a hashed join buffer if its match flag - is set to MATCH_FOUND - */ - bool skip_if_matched(); - - /* - Skip record from a hashed join buffer if its match flag setting - commands to do so - */ - bool skip_if_not_needed_match(); - - /* Search for a key in the hash table of the join buffer */ - bool key_search(uchar *key, uint key_len, uchar **key_ref_ptr); - - /* Reallocate the join buffer of a hashed join cache */ - int realloc_buffer(); - - /* - This constructor creates an unlinked hashed join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. - */ - JOIN_CACHE_HASHED(JOIN *j, JOIN_TAB *tab) :JOIN_CACHE(j, tab) {} - - /* - This constructor creates a linked hashed join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. The parameter 'prev' specifies the previous - cache object to which this cache is linked. - */ - JOIN_CACHE_HASHED(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) - :JOIN_CACHE(j, tab, prev) {} - -public: - - /* Initialize a hashed join cache */ - int init(bool for_explain); - - /* Reset the buffer of a hashed join cache for reading/writing */ - void reset(bool for_writing); - - /* Add a record into the buffer of a hashed join cache */ - bool put_record(); - - /* Read the next record from the buffer of a hashed join cache */ - bool get_record(); - - /* - Shall check whether all records in a key chain have - their match flags set on - */ - virtual bool check_all_match_flags_for_key(uchar *key_chain_ptr); - - uint get_next_key(uchar **key); - - /* Get the head of the record chain attached to the current key entry */ - uchar *get_curr_key_chain() - { - return get_next_rec_ref(curr_key_entry+key_entry_length- - get_size_of_rec_offset()); - } - -}; - - -/* - The class JOIN_TAB_SCAN is a companion class for the classes JOIN_CACHE_BNL - and JOIN_CACHE_BNLH. Actually the class implements the iterator over the - table joinded by BNL/BNLH join algorithm. - The virtual functions open, next and close are called for any iteration over - the table. The function open is called to initiate the process of the - iteration. The function next shall read the next record from the joined - table. The record is read into the record buffer of the joined table. - The record is to be matched with records from the join cache buffer. - The function close shall perform the finalizing actions for the iteration. -*/ - -class JOIN_TAB_SCAN: public Sql_alloc -{ - -private: - /* TRUE if this is the first record from the joined table to iterate over */ - bool is_first_record; - -protected: - - /* The joined table to be iterated over */ - JOIN_TAB *join_tab; - /* The join cache used to join the table join_tab */ - JOIN_CACHE *cache; - /* - Representation of the executed multi-way join through which - all needed context can be accessed. - */ - JOIN *join; - -public: - - JOIN_TAB_SCAN(JOIN *j, JOIN_TAB *tab) - { - join= j; - join_tab= tab; - cache= join_tab->cache; - } - - virtual ~JOIN_TAB_SCAN() {} - - /* - Shall calculate the increment of the auxiliary buffer for a record - write if such a buffer is used by the table scan object - */ - virtual uint aux_buffer_incr(size_t recno) { return 0; } - - /* Initiate the process of iteration over the joined table */ - virtual int open(); - /* - Shall read the next candidate for matches with records from - the join buffer. - */ - virtual int next(); - /* - Perform the finalizing actions for the process of iteration - over the joined_table. - */ - virtual void close(); - -}; - -/* - The class JOIN_CACHE_BNL is used when the BNL join algorithm is - employed to perform a join operation -*/ - -class JOIN_CACHE_BNL :public JOIN_CACHE -{ -private: - /* - The number of the records in the join buffer that have to be - checked yet for a match with the current record of join_tab - read into the record buffer. - */ - uint rem_records; - -protected: - - bool prepare_look_for_matches(bool skip_last); - - uchar *get_next_candidate_for_match(); - - bool skip_next_candidate_for_match(uchar *rec_ptr); - - void read_next_candidate_for_match(uchar *rec_ptr); - -public: - - /* - This constructor creates an unlinked BNL join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. - */ - JOIN_CACHE_BNL(JOIN *j, JOIN_TAB *tab) :JOIN_CACHE(j, tab) {} - - /* - This constructor creates a linked BNL join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. The parameter 'prev' specifies the previous - cache object to which this cache is linked. - */ - JOIN_CACHE_BNL(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) - :JOIN_CACHE(j, tab, prev) {} - - /* Initialize the BNL cache */ - int init(bool for_explain); - - enum Join_algorithm get_join_alg() { return BNL_JOIN_ALG; } - - bool is_key_access() { return FALSE; } - -}; - - -/* - The class JOIN_CACHE_BNLH is used when the BNLH join algorithm is - employed to perform a join operation -*/ - -class JOIN_CACHE_BNLH :public JOIN_CACHE_HASHED -{ - -protected: - - /* - The pointer to the last record from the circular list of the records - that match the join key built out of the record in the join buffer for - the join_tab table - */ - uchar *last_matching_rec_ref_ptr; - /* - The pointer to the next current record from the circular list of the - records that match the join key built out of the record in the join buffer - for the join_tab table. This pointer is used by the class method - get_next_candidate_for_match to iterate over records from the circular - list. - */ - uchar *next_matching_rec_ref_ptr; - - /* - Get the chain of records from buffer matching the current candidate - record for join - */ - uchar *get_matching_chain_by_join_key(); - - bool prepare_look_for_matches(bool skip_last); - - uchar *get_next_candidate_for_match(); - - bool skip_next_candidate_for_match(uchar *rec_ptr); - - void read_next_candidate_for_match(uchar *rec_ptr); - -public: - - /* - This constructor creates an unlinked BNLH join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. - */ - JOIN_CACHE_BNLH(JOIN *j, JOIN_TAB *tab) : JOIN_CACHE_HASHED(j, tab) {} - - /* - This constructor creates a linked BNLH join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. The parameter 'prev' specifies the previous - cache object to which this cache is linked. - */ - JOIN_CACHE_BNLH(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) - : JOIN_CACHE_HASHED(j, tab, prev) {} - - /* Initialize the BNLH cache */ - int init(bool for_explain); - - enum Join_algorithm get_join_alg() { return BNLH_JOIN_ALG; } - - bool is_key_access() { return TRUE; } - -}; - - -/* - The class JOIN_TAB_SCAN_MRR is a companion class for the classes - JOIN_CACHE_BKA and JOIN_CACHE_BKAH. Actually the class implements the - iterator over the records from join_tab selected by BKA/BKAH join - algorithm as the candidates to be joined. - The virtual functions open, next and close are called for any iteration over - join_tab record candidates. The function open is called to initiate the - process of the iteration. The function next shall read the next record from - the set of the record candidates. The record is read into the record buffer - of the joined table. The function close shall perform the finalizing actions - for the iteration. -*/ - -class JOIN_TAB_SCAN_MRR: public JOIN_TAB_SCAN -{ - /* Interface object to generate key ranges for MRR */ - RANGE_SEQ_IF range_seq_funcs; - - /* Number of ranges to be processed by the MRR interface */ - uint ranges; - - /* Flag to to be passed to the MRR interface */ - uint mrr_mode; - - /* MRR buffer assotiated with this join cache */ - HANDLER_BUFFER mrr_buff; - - /* Shall initialize the MRR buffer */ - virtual void init_mrr_buff() - { - cache->setup_aux_buffer(mrr_buff); - } - -public: - - JOIN_TAB_SCAN_MRR(JOIN *j, JOIN_TAB *tab, uint flags, RANGE_SEQ_IF rs_funcs) - :JOIN_TAB_SCAN(j, tab), range_seq_funcs(rs_funcs), mrr_mode(flags) {} - - uint aux_buffer_incr(size_t recno); - - int open(); - - int next(); - - friend class JOIN_CACHE_BKA; /* it needs to add an mrr_mode flag after JOIN_CACHE::init() call */ -}; - -/* - The class JOIN_CACHE_BKA is used when the BKA join algorithm is - employed to perform a join operation -*/ - -class JOIN_CACHE_BKA :public JOIN_CACHE -{ -private: - - /* Flag to to be passed to the companion JOIN_TAB_SCAN_MRR object */ - uint mrr_mode; - - /* - This value is set to 1 by the class prepare_look_for_matches method - and back to 0 by the class get_next_candidate_for_match method - */ - uint rem_records; - - /* - This field contains the current association label set by a call of - the multi_range_read_next handler function. - See the function JOIN_CACHE_BKA::get_curr_key_association() - */ - uchar *curr_association; - -protected: - - /* - Get the number of ranges in the cache buffer passed to the MRR - interface. For each record its own range is passed. - */ - uint get_number_of_ranges_for_mrr() { return (uint)records; } - - /* - Setup the MRR buffer as the space between the last record put - into the join buffer and the very end of the join buffer - */ - int setup_aux_buffer(HANDLER_BUFFER &aux_buff) - { - aux_buff.buffer= end_pos; - aux_buff.buffer_end= buff+buff_size; - return 0; - } - - bool prepare_look_for_matches(bool skip_last); - - uchar *get_next_candidate_for_match(); - - bool skip_next_candidate_for_match(uchar *rec_ptr); - - void read_next_candidate_for_match(uchar *rec_ptr); - -public: - - /* - This constructor creates an unlinked BKA join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. - The MRR mode initially is set to 'flags'. - */ - JOIN_CACHE_BKA(JOIN *j, JOIN_TAB *tab, uint flags) - :JOIN_CACHE(j, tab), mrr_mode(flags) {} - /* - This constructor creates a linked BKA join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. The parameter 'prev' specifies the previous - cache object to which this cache is linked. - The MRR mode initially is set to 'flags'. - */ - JOIN_CACHE_BKA(JOIN *j, JOIN_TAB *tab, uint flags, JOIN_CACHE *prev) - :JOIN_CACHE(j, tab, prev), mrr_mode(flags) {} - - JOIN_CACHE_BKA(JOIN_CACHE_BKA *bka) - :JOIN_CACHE(bka->join, bka->join_tab, bka->prev_cache), - mrr_mode(bka->mrr_mode) {} - - uchar **get_curr_association_ptr() { return &curr_association; } - - /* Initialize the BKA cache */ - int init(bool for_explain); - - enum Join_algorithm get_join_alg() { return BKA_JOIN_ALG; } - - bool is_key_access() { return TRUE; } - - /* Get the key built over the next record from the join buffer */ - uint get_next_key(uchar **key); - - /* Check index condition of the joined table for a record from BKA cache */ - bool skip_index_tuple(range_id_t range_info); - - bool save_explain_data(EXPLAIN_BKA_TYPE *explain); -}; - - - -/* - The class JOIN_CACHE_BKAH is used when the BKAH join algorithm is - employed to perform a join operation -*/ - -class JOIN_CACHE_BKAH :public JOIN_CACHE_BNLH -{ - -private: - /* Flag to to be passed to the companion JOIN_TAB_SCAN_MRR object */ - uint mrr_mode; - - /* - This flag is set to TRUE if the implementation of the MRR interface cannot - handle range association labels and does not return them to the caller of - the multi_range_read_next handler function. E.g. the implementation of - the MRR inteface for the Falcon engine could not return association - labels to the caller of multi_range_read_next. - The flag is set by JOIN_CACHE_BKA::init() and is not ever changed. - */ - bool no_association; - - /* - This field contains the association label returned by the - multi_range_read_next function. - See the function JOIN_CACHE_BKAH::get_curr_key_association() - */ - uchar *curr_matching_chain; - -protected: - - uint get_number_of_ranges_for_mrr() { return key_entries; } - - /* - Initialize the MRR buffer allocating some space within the join buffer. - The entire space between the last record put into the join buffer and the - last key entry added to the hash table is used for the MRR buffer. - */ - int setup_aux_buffer(HANDLER_BUFFER &aux_buff) - { - aux_buff.buffer= end_pos; - aux_buff.buffer_end= last_key_entry; - return 0; - } - - bool prepare_look_for_matches(bool skip_last); - - /* - The implementations of the methods - - get_next_candidate_for_match - - skip_recurrent_candidate_for_match - - read_next_candidate_for_match - are inherited from the JOIN_CACHE_BNLH class - */ - -public: - - /* - This constructor creates an unlinked BKAH join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. - The MRR mode initially is set to 'flags'. - */ - JOIN_CACHE_BKAH(JOIN *j, JOIN_TAB *tab, uint flags) - :JOIN_CACHE_BNLH(j, tab), mrr_mode(flags) {} - - /* - This constructor creates a linked BKAH join cache. The cache is to be - used to join table 'tab' to the result of joining the previous tables - specified by the 'j' parameter. The parameter 'prev' specifies the previous - cache object to which this cache is linked. - The MRR mode initially is set to 'flags'. - */ - JOIN_CACHE_BKAH(JOIN *j, JOIN_TAB *tab, uint flags, JOIN_CACHE *prev) - :JOIN_CACHE_BNLH(j, tab, prev), mrr_mode(flags) {} - - JOIN_CACHE_BKAH(JOIN_CACHE_BKAH *bkah) - :JOIN_CACHE_BNLH(bkah->join, bkah->join_tab, bkah->prev_cache), - mrr_mode(bkah->mrr_mode) {} - - uchar **get_curr_association_ptr() { return &curr_matching_chain; } - - /* Initialize the BKAH cache */ - int init(bool for_explain); - - enum Join_algorithm get_join_alg() { return BKAH_JOIN_ALG; } - - /* Check index condition of the joined table for a record from BKAH cache */ - bool skip_index_tuple(range_id_t range_info); - - bool save_explain_data(EXPLAIN_BKA_TYPE *explain); -}; diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_lex.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_lex.h deleted file mode 100644 index 3e59ad3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_lex.h +++ /dev/null @@ -1,5037 +0,0 @@ -/* Copyright (c) 2000, 2019, Oracle and/or its affiliates. - Copyright (c) 2010, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @defgroup Semantic_Analysis Semantic Analysis -*/ - -#ifndef SQL_LEX_INCLUDED -#define SQL_LEX_INCLUDED - -#include "violite.h" /* SSL_type */ -#include "sql_trigger.h" -#include "thr_lock.h" /* thr_lock_type, TL_UNLOCK */ -#include "mem_root_array.h" -#include "grant.h" -#include "sql_cmd.h" -#include "sql_alter.h" // Alter_info -#include "sql_window.h" -#include "sql_trigger.h" -#include "sp.h" // enum enum_sp_type -#include "sql_tvc.h" -#include "item.h" -#include "sql_limit.h" // Select_limit_counters -#include "sql_schema.h" - -/* Used for flags of nesting constructs */ -#define SELECT_NESTING_MAP_SIZE 64 -typedef Bitmap nesting_map; - -/* YACC and LEX Definitions */ - - -/** - A string with metadata. Usually points to a string in the client - character set, but unlike Lex_ident_cli_st (see below) it does not - necessarily point to a query fragment. It can also point to memory - of other kinds (e.g. an additional THD allocated memory buffer - not overlapping with the current query text). - - We'll add more flags here eventually, to know if the string has, e.g.: - - multi-byte characters - - bad byte sequences - - backslash escapes: 'a\nb' - and reuse the original query fragments instead of making the string - copy too early, in Lex_input_stream::get_text(). - This will allow to avoid unnecessary copying, as well as - create more optimal Item types in sql_yacc.yy -*/ -struct Lex_string_with_metadata_st: public LEX_CSTRING -{ -private: - bool m_is_8bit; // True if the string has 8bit characters - char m_quote; // Quote character, or 0 if not quoted -public: - void set_8bit(bool is_8bit) { m_is_8bit= is_8bit; } - void set_metadata(bool is_8bit, char quote) - { - m_is_8bit= is_8bit; - m_quote= quote; - } - void set(const char *s, size_t len, bool is_8bit, char quote) - { - str= s; - length= len; - set_metadata(is_8bit, quote); - } - void set(const LEX_CSTRING *s, bool is_8bit, char quote) - { - ((LEX_CSTRING &)*this)= *s; - set_metadata(is_8bit, quote); - } - bool is_8bit() const { return m_is_8bit; } - bool is_quoted() const { return m_quote != '\0'; } - char quote() const { return m_quote; } - // Get string repertoire by the 8-bit flag and the character set - my_repertoire_t repertoire(CHARSET_INFO *cs) const - { - return !m_is_8bit && my_charset_is_ascii_based(cs) ? - MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; - } - // Get string repertoire by the 8-bit flag, for ASCII-based character sets - my_repertoire_t repertoire() const - { - return !m_is_8bit ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; - } -}; - - -/* - Used to store identifiers in the client character set. - Points to a query fragment. -*/ -struct Lex_ident_cli_st: public Lex_string_with_metadata_st -{ -public: - void set_keyword(const char *s, size_t len) - { - set(s, len, false, '\0'); - } - void set_ident(const char *s, size_t len, bool is_8bit) - { - set(s, len, is_8bit, '\0'); - } - void set_ident_quoted(const char *s, size_t len, bool is_8bit, char quote) - { - set(s, len, is_8bit, quote); - } - void set_unquoted(const LEX_CSTRING *s, bool is_8bit) - { - set(s, is_8bit, '\0'); - } - const char *pos() const { return str - is_quoted(); } - const char *end() const { return str + length + is_quoted(); } -}; - - -class Lex_ident_cli: public Lex_ident_cli_st -{ -public: - Lex_ident_cli(const LEX_CSTRING *s, bool is_8bit) - { - set_unquoted(s, is_8bit); - } - Lex_ident_cli(const char *s, size_t len) - { - set_ident(s, len, false); - } -}; - - -struct Lex_ident_sys_st: public LEX_CSTRING -{ -public: - bool copy_ident_cli(THD *thd, const Lex_ident_cli_st *str); - bool copy_keyword(THD *thd, const Lex_ident_cli_st *str); - bool copy_sys(THD *thd, const LEX_CSTRING *str); - bool convert(THD *thd, const LEX_CSTRING *str, CHARSET_INFO *cs); - bool copy_or_convert(THD *thd, const Lex_ident_cli_st *str, CHARSET_INFO *cs); - bool is_null() const { return str == NULL; } - bool to_size_number(ulonglong *to) const; - void set_valid_utf8(const LEX_CSTRING *name) - { - DBUG_ASSERT(Well_formed_prefix(system_charset_info, name->str, - name->length).length() == name->length); - str= name->str ; length= name->length; - } -}; - - -class Lex_ident_sys: public Lex_ident_sys_st -{ -public: - Lex_ident_sys(THD *thd, const Lex_ident_cli_st *str) - { - if (copy_ident_cli(thd, str)) - ((LEX_CSTRING &) *this)= null_clex_str; - } - Lex_ident_sys() - { - ((LEX_CSTRING &) *this)= null_clex_str; - } - Lex_ident_sys(const char *name, size_t length) - { - LEX_CSTRING tmp= {name, length}; - set_valid_utf8(&tmp); - } - Lex_ident_sys & operator=(const Lex_ident_sys_st &name) - { - Lex_ident_sys_st::operator=(name); - return *this; - } -}; - - -struct Lex_column_list_privilege_st -{ - List *m_columns; - privilege_t m_privilege; -}; - - -class Lex_column_list_privilege: public Lex_column_list_privilege_st -{ -public: - Lex_column_list_privilege(List *columns, privilege_t privilege) - { - m_columns= columns; - m_privilege= privilege; - } -}; - - -/** - ORDER BY ... LIMIT parameters; -*/ -class Lex_order_limit_lock: public Sql_alloc -{ -public: - SQL_I_List *order_list; /* ORDER clause */ - Lex_select_lock lock; - Lex_select_limit limit; - - Lex_order_limit_lock() :order_list(NULL) - {} - - bool set_to(st_select_lex *sel); -}; - - -enum sub_select_type -{ - UNSPECIFIED_TYPE, - /* following 3 enums should be as they are*/ - UNION_TYPE, INTERSECT_TYPE, EXCEPT_TYPE, - GLOBAL_OPTIONS_TYPE, DERIVED_TABLE_TYPE, OLAP_TYPE -}; - -enum set_op_type -{ - UNSPECIFIED, - UNION_DISTINCT, UNION_ALL, - EXCEPT_DISTINCT, EXCEPT_ALL, - INTERSECT_DISTINCT, INTERSECT_ALL -}; - -inline int cmp_unit_op(enum sub_select_type op1, enum sub_select_type op2) -{ - DBUG_ASSERT(op1 >= UNION_TYPE && op1 <= EXCEPT_TYPE); - DBUG_ASSERT(op2 >= UNION_TYPE && op2 <= EXCEPT_TYPE); - return (op1 == INTERSECT_TYPE ? 1 : 0) - (op2 == INTERSECT_TYPE ? 1 : 0); -} - -enum unit_common_op {OP_MIX, OP_UNION, OP_INTERSECT, OP_EXCEPT}; - -enum enum_view_suid -{ - VIEW_SUID_INVOKER= 0, - VIEW_SUID_DEFINER= 1, - VIEW_SUID_DEFAULT= 2 -}; - - -enum plsql_cursor_attr_t -{ - PLSQL_CURSOR_ATTR_ISOPEN, - PLSQL_CURSOR_ATTR_FOUND, - PLSQL_CURSOR_ATTR_NOTFOUND, - PLSQL_CURSOR_ATTR_ROWCOUNT -}; - - -enum enum_sp_suid_behaviour -{ - SP_IS_DEFAULT_SUID= 0, - SP_IS_NOT_SUID, - SP_IS_SUID -}; - - -enum enum_sp_aggregate_type -{ - DEFAULT_AGGREGATE= 0, - NOT_AGGREGATE, - GROUP_AGGREGATE -}; - - -/* These may not be declared yet */ -class Table_ident; -class sql_exchange; -class LEX_COLUMN; -class sp_head; -class sp_name; -class sp_instr; -class sp_pcontext; -class sp_variable; -class sp_expr_lex; -class sp_assignment_lex; -class st_alter_tablespace; -class partition_info; -class Event_parse_data; -class set_var_base; -class sys_var; -class Item_func_match; -class File_parser; -class Key_part_spec; -class Item_window_func; -struct sql_digest_state; -class With_clause; -class my_var; -class select_handler; -class Pushdown_select; - -#define ALLOC_ROOT_SET 1024 - -#ifdef MYSQL_SERVER -/* - There are 8 different type of table access so there is no more than - combinations 2^8 = 256: - - . STMT_READS_TRANS_TABLE - - . STMT_READS_NON_TRANS_TABLE - - . STMT_READS_TEMP_TRANS_TABLE - - . STMT_READS_TEMP_NON_TRANS_TABLE - - . STMT_WRITES_TRANS_TABLE - - . STMT_WRITES_NON_TRANS_TABLE - - . STMT_WRITES_TEMP_TRANS_TABLE - - . STMT_WRITES_TEMP_NON_TRANS_TABLE - - The unsafe conditions for each combination is represented within a byte - and stores the status of the option --binlog-direct-non-trans-updates, - whether the trx-cache is empty or not, and whether the isolation level - is lower than ISO_REPEATABLE_READ: - - . option (OFF/ON) - . trx-cache (empty/not empty) - . isolation (>= ISO_REPEATABLE_READ / < ISO_REPEATABLE_READ) - - bits 0 : . OFF, . empty, . >= ISO_REPEATABLE_READ - bits 1 : . OFF, . empty, . < ISO_REPEATABLE_READ - bits 2 : . OFF, . not empty, . >= ISO_REPEATABLE_READ - bits 3 : . OFF, . not empty, . < ISO_REPEATABLE_READ - bits 4 : . ON, . empty, . >= ISO_REPEATABLE_READ - bits 5 : . ON, . empty, . < ISO_REPEATABLE_READ - bits 6 : . ON, . not empty, . >= ISO_REPEATABLE_READ - bits 7 : . ON, . not empty, . < ISO_REPEATABLE_READ -*/ -extern uint binlog_unsafe_map[256]; -/* - Initializes the array with unsafe combinations and its respective - conditions. -*/ -void binlog_unsafe_map_init(); -#endif - -#ifdef MYSQL_SERVER -/* - The following hack is needed because mysql_yacc.cc does not define - YYSTYPE before including this file -*/ -#ifdef MYSQL_YACC -#define LEX_YYSTYPE void * -#else -#include "lex_symbol.h" -#ifdef MYSQL_LEX -#include "item_func.h" /* Cast_target used in sql_yacc.hh */ -#include "sql_get_diagnostics.h" /* Types used in sql_yacc.hh */ -#include "sp_pcontext.h" -#include "sql_yacc.hh" -#define LEX_YYSTYPE YYSTYPE * -#else -#define LEX_YYSTYPE void * -#endif -#endif -#endif - -// describe/explain types -#define DESCRIBE_NORMAL 1 -#define DESCRIBE_EXTENDED 2 -/* - This is not within #ifdef because we want "EXPLAIN PARTITIONS ..." to produce - additional "partitions" column even if partitioning is not compiled in. -*/ -#define DESCRIBE_PARTITIONS 4 -#define DESCRIBE_EXTENDED2 8 - -#ifdef MYSQL_SERVER - -extern const LEX_STRING empty_lex_str; -extern MYSQL_PLUGIN_IMPORT const LEX_CSTRING empty_clex_str; -extern const LEX_CSTRING star_clex_str; -extern const LEX_CSTRING param_clex_str; - -enum enum_sp_data_access -{ - SP_DEFAULT_ACCESS= 0, - SP_CONTAINS_SQL, - SP_NO_SQL, - SP_READS_SQL_DATA, - SP_MODIFIES_SQL_DATA -}; - -const LEX_CSTRING sp_data_access_name[]= -{ - { STRING_WITH_LEN("") }, - { STRING_WITH_LEN("CONTAINS SQL") }, - { STRING_WITH_LEN("NO SQL") }, - { STRING_WITH_LEN("READS SQL DATA") }, - { STRING_WITH_LEN("MODIFIES SQL DATA") } -}; - -#define DERIVED_SUBQUERY 1 -#define DERIVED_VIEW 2 -#define DERIVED_WITH 4 - -enum enum_view_create_mode -{ - VIEW_CREATE_NEW, // check that there are not such VIEW/table - VIEW_ALTER, // check that VIEW .frm with such name exists - VIEW_CREATE_OR_REPLACE // check only that there are not such table -}; - - -class Create_view_info: public Sql_alloc -{ -public: - LEX_CSTRING select; // The SELECT statement of CREATE VIEW - enum enum_view_create_mode mode; - uint16 algorithm; - uint8 check; - enum enum_view_suid suid; - Create_view_info(enum_view_create_mode mode_arg, - uint16 algorithm_arg, - enum_view_suid suid_arg) - :select(null_clex_str), - mode(mode_arg), - algorithm(algorithm_arg), - check(VIEW_CHECK_NONE), - suid(suid_arg) - { } -}; - - -enum enum_drop_mode -{ - DROP_DEFAULT, // mode is not specified - DROP_CASCADE, // CASCADE option - DROP_RESTRICT // RESTRICT option -}; - -/* Options to add_table_to_list() */ -#define TL_OPTION_UPDATING 1 -#define TL_OPTION_FORCE_INDEX 2 -#define TL_OPTION_IGNORE_LEAVES 4 -#define TL_OPTION_ALIAS 8 -#define TL_OPTION_SEQUENCE 16 - -typedef List List_item; -typedef Mem_root_array Group_list_ptrs; - -/* SERVERS CACHE CHANGES */ -typedef struct st_lex_server_options -{ - long port; - LEX_CSTRING server_name, host, db, username, password, scheme, socket, owner; - void reset(LEX_CSTRING name) - { - server_name= name; - host= db= username= password= scheme= socket= owner= null_clex_str; - port= -1; - } -} LEX_SERVER_OPTIONS; - - -/** - Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE. - - Remark: this should not be confused with Master_info (and perhaps - would better be renamed to st_lex_replication_info). Some fields, - e.g., delay, are saved in Relay_log_info, not in Master_info. -*/ -struct LEX_MASTER_INFO -{ - DYNAMIC_ARRAY repl_ignore_server_ids; - DYNAMIC_ARRAY repl_do_domain_ids; - DYNAMIC_ARRAY repl_ignore_domain_ids; - const char *host, *user, *password, *log_file_name; - const char *ssl_key, *ssl_cert, *ssl_ca, *ssl_capath, *ssl_cipher; - const char *ssl_crl, *ssl_crlpath; - const char *relay_log_name; - LEX_CSTRING connection_name; - /* Value in START SLAVE UNTIL master_gtid_pos=xxx */ - LEX_CSTRING gtid_pos_str; - ulonglong pos; - ulong relay_log_pos; - ulong server_id; - uint port, connect_retry; - float heartbeat_period; - int sql_delay; - /* - Enum is used for making it possible to detect if the user - changed variable or if it should be left at old value - */ - enum {LEX_MI_UNCHANGED= 0, LEX_MI_DISABLE, LEX_MI_ENABLE} - ssl, ssl_verify_server_cert, heartbeat_opt, repl_ignore_server_ids_opt, - repl_do_domain_ids_opt, repl_ignore_domain_ids_opt; - enum { - LEX_GTID_UNCHANGED, LEX_GTID_NO, LEX_GTID_CURRENT_POS, LEX_GTID_SLAVE_POS - } use_gtid_opt; - - void init() - { - bzero(this, sizeof(*this)); - my_init_dynamic_array(PSI_INSTRUMENT_ME, &repl_ignore_server_ids, - sizeof(::server_id), 0, 16, MYF(0)); - my_init_dynamic_array(PSI_INSTRUMENT_ME, &repl_do_domain_ids, - sizeof(ulong), 0, 16, MYF(0)); - my_init_dynamic_array(PSI_INSTRUMENT_ME, &repl_ignore_domain_ids, - sizeof(ulong), 0, 16, MYF(0)); - sql_delay= -1; - } - void reset(bool is_change_master) - { - if (unlikely(is_change_master)) - { - delete_dynamic(&repl_ignore_server_ids); - /* Free all the array elements. */ - delete_dynamic(&repl_do_domain_ids); - delete_dynamic(&repl_ignore_domain_ids); - } - - host= user= password= log_file_name= ssl_key= ssl_cert= ssl_ca= - ssl_capath= ssl_cipher= relay_log_name= 0; - pos= relay_log_pos= server_id= port= connect_retry= 0; - heartbeat_period= 0; - ssl= ssl_verify_server_cert= heartbeat_opt= - repl_ignore_server_ids_opt= repl_do_domain_ids_opt= - repl_ignore_domain_ids_opt= LEX_MI_UNCHANGED; - gtid_pos_str= null_clex_str; - use_gtid_opt= LEX_GTID_UNCHANGED; - sql_delay= -1; - } -}; - -typedef struct st_lex_reset_slave -{ - bool all; -} LEX_RESET_SLAVE; - -enum olap_type -{ - UNSPECIFIED_OLAP_TYPE, CUBE_TYPE, ROLLUP_TYPE -}; - -/* - String names used to print a statement with index hints. - Keep in sync with index_hint_type. -*/ -extern const char * index_hint_type_name[]; -typedef uchar index_clause_map; - -/* - Bits in index_clause_map : one for each possible FOR clause in - USE/FORCE/IGNORE INDEX index hint specification -*/ -#define INDEX_HINT_MASK_JOIN (1) -#define INDEX_HINT_MASK_GROUP (1 << 1) -#define INDEX_HINT_MASK_ORDER (1 << 2) - -#define INDEX_HINT_MASK_ALL (INDEX_HINT_MASK_JOIN | INDEX_HINT_MASK_GROUP | \ - INDEX_HINT_MASK_ORDER) - -class select_result_sink; - -/* Single element of an USE/FORCE/IGNORE INDEX list specified as a SQL hint */ -class Index_hint : public Sql_alloc -{ -public: - /* The type of the hint : USE/FORCE/IGNORE */ - enum index_hint_type type; - /* Where the hit applies to. A bitmask of INDEX_HINT_MASK_ values */ - index_clause_map clause; - /* - The index name. Empty (str=NULL) name represents an empty list - USE INDEX () clause - */ - LEX_CSTRING key_name; - - Index_hint (enum index_hint_type type_arg, index_clause_map clause_arg, - const char *str, size_t length) : - type(type_arg), clause(clause_arg) - { - key_name.str= str; - key_name.length= length; - } - - void print(THD *thd, String *str); -}; - -/* - The state of the lex parsing for selects - - master and slaves are pointers to select_lex. - master is pointer to upper level node. - slave is pointer to lower level node - select_lex is a SELECT without union - unit is container of either - - One SELECT - - UNION of selects - select_lex and unit are both inherited form st_select_lex_node - neighbors are two select_lex or units on the same level - - All select describing structures linked with following pointers: - - list of neighbors (next/prev) (prev of first element point to slave - pointer of upper structure) - - For select this is a list of UNION's (or one element list) - - For units this is a list of sub queries for the upper level select - - - pointer to master (master), which is - If this is a unit - - pointer to outer select_lex - If this is a select_lex - - pointer to outer unit structure for select - - - pointer to slave (slave), which is either: - If this is a unit: - - first SELECT that belong to this unit - If this is a select_lex - - first unit that belong to this SELECT (subquries or derived tables) - - - list of all select_lex (link_next/link_prev) - This is to be used for things like derived tables creation, where we - go through this list and create the derived tables. - - If unit contain several selects (UNION now, INTERSECT etc later) - then it have special select_lex called fake_select_lex. It used for - storing global parameters (like ORDER BY, LIMIT) and executing union. - Subqueries used in global ORDER BY clause will be attached to this - fake_select_lex, which will allow them correctly resolve fields of - 'upper' UNION and outer selects. - - For example for following query: - - select * - from table1 - where table1.field IN (select * from table1_1_1 union - select * from table1_1_2) - union - select * - from table2 - where table2.field=(select (select f1 from table2_1_1_1_1 - where table2_1_1_1_1.f2=table2_1_1.f3) - from table2_1_1 - where table2_1_1.f1=table2.f2) - union - select * from table3; - - we will have following structure: - - select1: (select * from table1 ...) - select2: (select * from table2 ...) - select3: (select * from table3) - select1.1.1: (select * from table1_1_1) - ... - - main unit - fake0 - select1 select2 select3 - |^^ |^ - s||| ||master - l||| |+---------------------------------+ - a||| +---------------------------------+| - v|||master slave || - e||+-------------------------+ || - V| neighbor | V| - unit1.1<+==================>unit1.2 unit2.1 - fake1.1 - select1.1.1 select 1.1.2 select1.2.1 select2.1.1 - |^ - || - V| - unit2.1.1.1 - select2.1.1.1.1 - - - relation in main unit will be following: - (bigger picture for: - main unit - fake0 - select1 select2 select3 - in the above picture) - - main unit - |^^^^|fake_select_lex - |||||+--------------------------------------------+ - ||||+--------------------------------------------+| - |||+------------------------------+ || - ||+--------------+ | || - slave||master | | || - V| neighbor | neighbor | master|V - select1<========>select2<========>select3 fake0 - - list of all select_lex will be following (as it will be constructed by - parser): - - select1->select2->select3->select2.1.1->select 2.1.2->select2.1.1.1.1-+ - | - +---------------------------------------------------------------------+ - | - +->select1.1.1->select1.1.2 - -*/ - -/* - Base class for st_select_lex (SELECT_LEX) & - st_select_lex_unit (SELECT_LEX_UNIT) -*/ -struct LEX; -class st_select_lex; -class st_select_lex_unit; - - -class st_select_lex_node { -protected: - st_select_lex_node *next, **prev, /* neighbor list */ - *master, *slave, /* vertical links */ - *link_next, **link_prev; /* list of whole SELECT_LEX */ - - void init_query_common(); -public: - - ulonglong options; - - /* - result of this query can't be cached, bit field, can be : - UNCACHEABLE_DEPENDENT_GENERATED - UNCACHEABLE_DEPENDENT_INJECTED - UNCACHEABLE_RAND - UNCACHEABLE_SIDEEFFECT - UNCACHEABLE_EXPLAIN - UNCACHEABLE_PREPARE - */ - uint8 uncacheable; -private: - enum sub_select_type linkage; -public: - bool is_linkage_set() const - { - return linkage == UNION_TYPE || linkage == INTERSECT_TYPE || linkage == EXCEPT_TYPE; - } - enum sub_select_type get_linkage() { return linkage; } - bool distinct; - bool no_table_names_allowed; /* used for global order by */ - - static void *operator new(size_t size, MEM_ROOT *mem_root) throw () - { return (void*) alloc_root(mem_root, (uint) size); } - static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); } - static void operator delete(void *ptr, MEM_ROOT *mem_root) {} - - // Ensures that at least all members used during cleanup() are initialized. - st_select_lex_node() - : next(NULL), prev(NULL), - master(NULL), slave(NULL), - link_next(NULL), link_prev(NULL), - linkage(UNSPECIFIED_TYPE) - { - } - - inline st_select_lex_node* get_master() { return master; } - inline st_select_lex_node* get_slave() { return slave; } - void include_down(st_select_lex_node *upper); - void add_slave(st_select_lex_node *slave_arg); - void include_neighbour(st_select_lex_node *before); - void link_chain_down(st_select_lex_node *first); - void link_neighbour(st_select_lex_node *neighbour) - { - DBUG_ASSERT(next == NULL); - DBUG_ASSERT(neighbour != NULL); - next= neighbour; - neighbour->prev= &next; - } - void cut_next() { next= NULL; } - void include_standalone(st_select_lex_node *sel, st_select_lex_node **ref); - void include_global(st_select_lex_node **plink); - void exclude(); - void exclude_from_tree(); - void exclude_from_global() - { - if (!link_prev) - return; - if (((*link_prev)= link_next)) - link_next->link_prev= link_prev; - link_next= NULL; - link_prev= NULL; - } - - - void set_slave(st_select_lex_node *slave_arg) { slave= slave_arg; } - void move_node(st_select_lex_node *where_to_move) - { - if (where_to_move == this) - return; - if (next) - next->prev= prev; - *prev= next; - *where_to_move->prev= this; - next= where_to_move; - } - st_select_lex_node *insert_chain_before(st_select_lex_node **ptr_pos_to_insert, - st_select_lex_node *end_chain_node); - void move_as_slave(st_select_lex_node *new_master); - void set_linkage(enum sub_select_type l) - { - DBUG_ENTER("st_select_lex_node::set_linkage"); - DBUG_PRINT("info", ("node: %p linkage: %d->%d", this, linkage, l)); - linkage= l; - DBUG_VOID_RETURN; - } - /* - This method created for reiniting LEX in mysql_admin_table() and can be - used only if you are going remove all SELECT_LEX & units except belonger - to LEX (LEX::unit & LEX::select, for other purposes there are - SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree. - - It is also used in parsing to detach builtin select. - */ - void cut_subtree() { slave= 0; } - friend class st_select_lex_unit; - friend bool mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *sel); - friend bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table, - bool open_view_no_parse); - friend class st_select_lex; -private: - void fast_exclude(); -}; -typedef class st_select_lex_node SELECT_LEX_NODE; - -/* - SELECT_LEX_UNIT - unit of selects (UNION, INTERSECT, ...) group - SELECT_LEXs -*/ -class THD; -class select_result; -class JOIN; -class select_unit; -class Procedure; -class Explain_query; - -void delete_explain_query(LEX *lex); -void create_explain_query(LEX *lex, MEM_ROOT *mem_root); -void create_explain_query_if_not_exists(LEX *lex, MEM_ROOT *mem_root); -bool print_explain_for_slow_log(LEX *lex, THD *thd, String *str); - - -class st_select_lex_unit: public st_select_lex_node { -protected: - TABLE_LIST result_table_list; - select_unit *union_result; - ulonglong found_rows_for_union; - bool saved_error; - - bool prepare_join(THD *thd, SELECT_LEX *sl, select_result *result, - ulonglong additional_options, - bool is_union_select); - bool join_union_type_handlers(THD *thd, - class Type_holder *holders, uint count); - bool join_union_type_attributes(THD *thd, - class Type_holder *holders, uint count); -public: - bool join_union_item_types(THD *thd, List &types, uint count); -public: - // Ensures that at least all members used during cleanup() are initialized. - st_select_lex_unit() - : union_result(NULL), table(NULL), result(NULL), - cleaned(false), bag_set_op_optimized(false), - have_except_all_or_intersect_all(false), fake_select_lex(NULL) - { - } - - TABLE *table; /* temporary table using for appending UNION results */ - select_result *result; - st_select_lex *pre_last_parse; - bool prepared, // prepare phase already performed for UNION (unit) - optimized, // optimize phase already performed for UNION (unit) - optimized_2, - executed, // already executed - cleaned, - bag_set_op_optimized; - - bool optimize_started; - bool have_except_all_or_intersect_all; - - // list of fields which points to temporary table for union - List item_list; - /* - list of types of items inside union (used for union & derived tables) - - Item_type_holders from which this list consist may have pointers to Field, - pointers is valid only after preparing SELECTS of this unit and before - any SELECT of this unit execution - */ - List types; - /** - TRUE if the unit contained TVC at the top level that has been wrapped - into SELECT: - VALUES (v1) ... (vn) => SELECT * FROM (VALUES (v1) ... (vn)) as tvc - */ - bool with_wrapped_tvc; - /** - Pointer to 'last' select, or pointer to select where we stored - global parameters for union. - - If this is a union of multiple selects, the parser puts the global - parameters in fake_select_lex. If the union doesn't use a - temporary table, st_select_lex_unit::prepare() nulls out - fake_select_lex, but saves a copy in saved_fake_select_lex in - order to preserve the global parameters. - - If it is not a union, first_select() is the last select. - - @return select containing the global parameters - */ - inline st_select_lex *global_parameters() - { - if (fake_select_lex != NULL) - return fake_select_lex; - else if (saved_fake_select_lex != NULL) - return saved_fake_select_lex; - return first_select(); - }; - //node on which we should return current_select pointer after parsing subquery - st_select_lex *return_to; - /* LIMIT clause runtime counters */ - Select_limit_counters lim; - /* not NULL if unit used in subselect, point to subselect item */ - Item_subselect *item; - /* - TABLE_LIST representing this union in the embedding select. Used for - derived tables/views handling. - */ - TABLE_LIST *derived; - bool is_view; - /* With clause attached to this unit (if any) */ - With_clause *with_clause; - /* With element where this unit is used as the specification (if any) */ - With_element *with_element; - /* thread handler */ - THD *thd; - /* - SELECT_LEX for hidden SELECT in union which process global - ORDER BY and LIMIT - */ - st_select_lex *fake_select_lex; - /** - SELECT_LEX that stores LIMIT and OFFSET for UNION ALL when noq - fake_select_lex is used. - */ - st_select_lex *saved_fake_select_lex; - - /* pointer to the last node before last subsequence of UNION ALL */ - st_select_lex *union_distinct; - bool describe; /* union exec() called for EXPLAIN */ - Procedure *last_procedure; /* Pointer to procedure, if such exists */ - - bool columns_are_renamed; - - void init_query(); - st_select_lex* outer_select(); - st_select_lex* first_select() - { - return reinterpret_cast(slave); - } - void set_with_clause(With_clause *with_cl); - st_select_lex_unit* next_unit() - { - return reinterpret_cast(next); - } - st_select_lex* return_after_parsing() { return return_to; } - void exclude_level(); - // void exclude_tree(); // it is not used for long time - bool is_excluded() { return prev == NULL; } - - /* UNION methods */ - bool prepare(TABLE_LIST *derived_arg, select_result *sel_result, - ulonglong additional_options); - bool optimize(); - void optimize_bag_operation(bool is_outer_distinct); - bool exec(); - bool exec_recursive(); - bool cleanup(); - inline void unclean() { cleaned= 0; } - void reinit_exec_mechanism(); - - void print(String *str, enum_query_type query_type); - - bool add_fake_select_lex(THD *thd); - void init_prepare_fake_select_lex(THD *thd, bool first_execution); - inline bool is_prepared() { return prepared; } - bool change_result(select_result_interceptor *result, - select_result_interceptor *old_result); - void set_limit(st_select_lex *values); - void set_thd(THD *thd_arg) { thd= thd_arg; } - inline bool is_unit_op (); - bool union_needs_tmp_table(); - - void set_unique_exclude(); - bool check_distinct_in_union(); - - friend struct LEX; - friend int subselect_union_engine::exec(); - - List *get_column_types(bool for_cursor); - - select_unit *get_union_result() { return union_result; } - int save_union_explain(Explain_query *output); - int save_union_explain_part2(Explain_query *output); - unit_common_op common_op(); - - bool explainable() const - { - /* - EXPLAIN/ANALYZE unit, when: - (1) if it's a subquery - it's not part of eliminated WHERE/ON clause. - (2) if it's a CTE - it's not hanging (needed for execution) - (3) if it's a derived - it's not merged - if it's not 1/2/3 - it's some weird internal thing, ignore it - */ - return item ? !item->eliminated : // (1) - with_element ? derived && derived->derived_result : // (2) - derived ? derived->is_materialized_derived() : // (3) - false; - } - - void reset_distinct(); - void fix_distinct(); - - void register_select_chain(SELECT_LEX *first_sel); - - bool set_nest_level(int new_nest_level); - bool check_parameters(SELECT_LEX *main_select); - - bool set_lock_to_the_last_select(Lex_select_lock l); - - friend class st_select_lex; -}; - -typedef class st_select_lex_unit SELECT_LEX_UNIT; -typedef Bounds_checked_array Ref_ptr_array; - - -/** - Structure which consists of the field and the item that - corresponds to this field. -*/ - -class Field_pair :public Sql_alloc -{ -public: - Field *field; - Item *corresponding_item; - Field_pair(Field *fld, Item *item) - :field(fld), corresponding_item(item) {} -}; - -Field_pair *get_corresponding_field_pair(Item *item, - List pair_list); -Field_pair *find_matching_field_pair(Item *item, List pair_list); - - -#define TOUCHED_SEL_COND 1/* WHERE/HAVING/ON should be reinited before use */ -#define TOUCHED_SEL_DERIVED (1<<1)/* derived should be reinited before use */ - -#define UNIT_NEST_FL 1 -/* - SELECT_LEX - store information of parsed SELECT statment -*/ -class st_select_lex: public st_select_lex_node -{ -public: - /* - Currently the field first_nested is used only by parser. - It containa either a reference to the first select - of the nest of selects to which 'this' belongs to, or - in the case of priority jump it contains a reference to - the select to which the priority nest has to be attached to. - If there is no priority jump then the first select of the - nest contains the reference to itself in first_nested. - Example: - select1 union select2 intersect select - Here we have a priority jump at select2. - So select2->first_nested points to select1, - while select3->first_nested points to select2 and - select1->first_nested points to select1. - */ - st_select_lex *first_nested; - uint8 nest_flags; - Name_resolution_context context; - LEX_CSTRING db; - Item *where, *having; /* WHERE & HAVING clauses */ - Item *prep_where; /* saved WHERE clause for prepared statement processing */ - Item *prep_having;/* saved HAVING clause for prepared statement processing */ - Item *cond_pushed_into_where; /* condition pushed into the select's WHERE */ - Item *cond_pushed_into_having; /* condition pushed into the select's HAVING */ - List attach_to_conds; - /* Saved values of the WHERE and HAVING clauses*/ - Item::cond_result cond_value, having_value; - /* - Point to the LEX in which it was created, used in view subquery detection. - - TODO: make also st_select_lex::parent_stmt_lex (see LEX::stmt_lex) - and use st_select_lex::parent_lex & st_select_lex::parent_stmt_lex - instead of global (from THD) references where it is possible. - */ - LEX *parent_lex; - enum olap_type olap; - /* FROM clause - points to the beginning of the TABLE_LIST::next_local list. */ - SQL_I_List table_list; - - /* - GROUP BY clause. - This list may be mutated during optimization (by remove_const()), - so for prepared statements, we keep a copy of the ORDER.next pointers in - group_list_ptrs, and re-establish the original list before each execution. - */ - SQL_I_List group_list; - Group_list_ptrs *group_list_ptrs; - - List item_list; /* list of fields & expressions */ - List pre_fix; /* above list before fix_fields */ - bool is_item_list_lookup; - /* - Usualy it is pointer to ftfunc_list_alloc, but in union used to create fake - select_lex for calling mysql_select under results of union - */ - List *ftfunc_list; - List ftfunc_list_alloc; - /* - The list of items to which MIN/MAX optimizations of opt_sum_query() - have been applied. Used to rollback those optimizations if it's needed. - */ - List min_max_opt_list; - JOIN *join; /* after JOIN::prepare it is pointer to corresponding JOIN */ - List top_join_list; /* join list of the top level */ - List *join_list; /* list for the currently parsed join */ - TABLE_LIST *embedding; /* table embedding to the above list */ - List sj_nests; /* Semi-join nests within this join */ - /* - Beginning of the list of leaves in a FROM clause, where the leaves - inlcude all base tables including view tables. The tables are connected - by TABLE_LIST::next_leaf, so leaf_tables points to the left-most leaf. - - List of all base tables local to a subquery including all view - tables. Unlike 'next_local', this in this list views are *not* - leaves. Created in setup_tables() -> make_leaves_list(). - */ - /* - Subqueries that will need to be converted to semi-join nests, including - those converted to jtbm nests. The list is emptied when conversion is done. - */ - List sj_subselects; - /* - List of IN-predicates in this st_select_lex that - can be transformed into IN-subselect defined with TVC. - */ - List in_funcs; - /* - Number of current derived table made with TVC during the - transformation of IN-predicate into IN-subquery for this - st_select_lex. - */ - uint curr_tvc_name; - - /* - Needed to correctly generate 'PRIMARY' or 'SIMPLE' for select_type column - of EXPLAIN - */ - bool have_merged_subqueries; - - List leaf_tables; - List leaf_tables_exec; - List leaf_tables_prep; - enum leaf_list_state {UNINIT, READY, SAVED}; - enum leaf_list_state prep_leaf_list_state; - uint insert_tables; - st_select_lex *merged_into; /* select which this select is merged into */ - /* (not 0 only for views/derived tables) */ - - const char *type; /* type of select for EXPLAIN */ - - SQL_I_List order_list; /* ORDER clause */ - SQL_I_List gorder_list; - Item *select_limit, *offset_limit; /* LIMIT clause parameters */ - bool is_set_query_expr_tail; - - /// Array of pointers to top elements of all_fields list - Ref_ptr_array ref_pointer_array; - - /* - number of items in select_list and HAVING clause used to get number - bigger then can be number of entries that will be added to all item - list during split_sum_func - */ - uint select_n_having_items; - uint cond_count; /* number of sargable Items in where/having/on */ - uint between_count; /* number of between predicates in where/having/on */ - uint max_equal_elems; /* maximal number of elements in multiple equalities */ - /* - Number of fields used in select list or where clause of current select - and all inner subselects. - */ - uint select_n_where_fields; - /* reserved for exists 2 in */ - uint select_n_reserved; - /* - it counts the number of bit fields in the SELECT list. These are used when DISTINCT is - converted to a GROUP BY involving BIT fields. - */ - uint hidden_bit_fields; - /* - Number of fields used in the definition of all the windows functions. - This includes: - 1) Fields in the arguments - 2) Fields in the PARTITION BY clause - 3) Fields in the ORDER BY clause - */ - uint fields_in_window_functions; - enum_parsing_place parsing_place; /* where we are parsing expression */ - enum_parsing_place save_parsing_place; - enum_parsing_place context_analysis_place; /* where we are in prepare */ - bool with_sum_func; /* sum function indicator */ - - ulong table_join_options; - uint in_sum_expr; - uint select_number; /* number of select (used for EXPLAIN) */ - - /* - nest_levels are local to the query or VIEW, - and that view merge procedure does not re-calculate them. - So we also have to remember unit against which we count levels. - */ - SELECT_LEX_UNIT *nest_level_base; - int nest_level; /* nesting level of select */ - Item_sum *inner_sum_func_list; /* list of sum func in nested selects */ - uint with_wild; /* item list contain '*' */ - bool braces; /* SELECT ... UNION (SELECT ... ) <- this braces */ - bool automatic_brackets; /* dummy select for INTERSECT precedence */ - /* TRUE when having fix field called in processing of this SELECT */ - bool having_fix_field; - /* - TRUE when fix field is called for a new condition pushed into the - HAVING clause of this SELECT - */ - bool having_fix_field_for_pushed_cond; - /* List of references to fields referenced from inner selects */ - List inner_refs_list; - /* Number of Item_sum-derived objects in this SELECT */ - uint n_sum_items; - /* Number of Item_sum-derived objects in children and descendant SELECTs */ - uint n_child_sum_items; - - /* explicit LIMIT clause was used */ - bool explicit_limit; - /* - This array is used to note whether we have any candidates for - expression caching in the corresponding clauses - */ - bool expr_cache_may_be_used[PARSING_PLACE_SIZE]; - /* - there are subquery in HAVING clause => we can't close tables before - query processing end even if we use temporary table - */ - bool subquery_in_having; - /* TRUE <=> this SELECT is correlated w.r.t. some ancestor select */ - bool with_all_modifier; /* used for selects in union */ - bool is_correlated; - /* - This variable is required to ensure proper work of subqueries and - stored procedures. Generally, one should use the states of - Query_arena to determine if it's a statement prepare or first - execution of a stored procedure. However, in case when there was an - error during the first execution of a stored procedure, the SP body - is not expelled from the SP cache. Therefore, a deeply nested - subquery might be left unoptimized. So we need this per-subquery - variable to inidicate the optimization/execution state of every - subquery. Prepared statements work OK in that regard, as in - case of an error during prepare the PS is not created. - */ - uint8 changed_elements; // see TOUCHED_SEL_* - /* TODO: add foloowing first_* to bitmap above */ - bool first_natural_join_processing; - bool first_cond_optimization; - /* do not wrap view fields with Item_ref */ - bool no_wrap_view_item; - /* exclude this select from check of unique_table() */ - bool exclude_from_table_unique_test; - /* the select is "service-select" and can not have tables*/ - bool is_service_select; - /* index in the select list of the expression currently being fixed */ - int cur_pos_in_select_list; - - List udf_list; /* udf function calls stack */ - - /* - This is a copy of the original JOIN USING list that comes from - the parser. The parser : - 1. Sets the natural_join of the second TABLE_LIST in the join - and the st_select_lex::prev_join_using. - 2. Makes a parent TABLE_LIST and sets its is_natural_join/ - join_using_fields members. - 3. Uses the wrapper TABLE_LIST as a table in the upper level. - We cannot assign directly to join_using_fields in the parser because - at stage (1.) the parent TABLE_LIST is not constructed yet and - the assignment will override the JOIN USING fields of the lower level - joins on the right. - */ - List *prev_join_using; - - /** - The set of those tables whose fields are referenced in the select list of - this select level. - */ - table_map select_list_tables; - - /* namp of nesting SELECT visibility (for aggregate functions check) */ - nesting_map name_visibility_map; - - table_map with_dep; - /* the structure to store fields that are used in the GROUP BY of this select */ - List grouping_tmp_fields; - - /* it is for correct printing SELECT options */ - thr_lock_type lock_type; - - table_value_constr *tvc; - bool in_tvc; - - /* The object used to organize execution of the query by a foreign engine */ - select_handler *pushdown_select; - - /** System Versioning */ -public: - uint versioned_tables; - int vers_setup_conds(THD *thd, TABLE_LIST *tables); - /* push new Item_field into item_list */ - bool vers_push_field(THD *thd, TABLE_LIST *table, const LEX_CSTRING field_name); - - int period_setup_conds(THD *thd, TABLE_LIST *table); - void init_query(); - void init_select(); - st_select_lex_unit* master_unit() { return (st_select_lex_unit*) master; } - inline void set_master_unit(st_select_lex_unit *master_unit) - { - master= (st_select_lex_node *)master_unit; - } - void set_master(st_select_lex *master_arg) - { - master= master_arg; - } - st_select_lex_unit* first_inner_unit() - { - return (st_select_lex_unit*) slave; - } - st_select_lex* outer_select(); - st_select_lex* next_select() { return (st_select_lex*) next; } - st_select_lex* next_select_in_list() - { - return (st_select_lex*) link_next; - } - st_select_lex_node** next_select_in_list_addr() - { - return &link_next; - } - st_select_lex* return_after_parsing() - { - return master_unit()->return_after_parsing(); - } - inline bool is_subquery_function() { return master_unit()->item != 0; } - - bool mark_as_dependent(THD *thd, st_select_lex *last, Item *dependency); - - void set_braces(bool value) - { - braces= value; - } - bool inc_in_sum_expr(); - uint get_in_sum_expr(); - - bool add_item_to_list(THD *thd, Item *item); - bool add_group_to_list(THD *thd, Item *item, bool asc); - bool add_ftfunc_to_list(THD *thd, Item_func_match *func); - bool add_order_to_list(THD *thd, Item *item, bool asc); - bool add_gorder_to_list(THD *thd, Item *item, bool asc); - TABLE_LIST* add_table_to_list(THD *thd, Table_ident *table, - LEX_CSTRING *alias, - ulong table_options, - thr_lock_type flags= TL_UNLOCK, - enum_mdl_type mdl_type= MDL_SHARED_READ, - List *hints= 0, - List *partition_names= 0, - LEX_STRING *option= 0); - TABLE_LIST* get_table_list(); - bool init_nested_join(THD *thd); - TABLE_LIST *end_nested_join(THD *thd); - TABLE_LIST *nest_last_join(THD *thd); - void add_joined_table(TABLE_LIST *table); - bool add_cross_joined_table(TABLE_LIST *left_op, TABLE_LIST *right_op, - bool straight_fl); - TABLE_LIST *convert_right_join(); - List* get_item_list(); - ulong get_table_join_options(); - void set_lock_for_tables(thr_lock_type lock_type, bool for_update); - /* - This method created for reiniting LEX in mysql_admin_table() and can be - used only if you are going remove all SELECT_LEX & units except belonger - to LEX (LEX::unit & LEX::select, for other purposes there are - SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree - */ - void cut_subtree() { slave= 0; } - bool test_limit(); - /** - Get offset for LIMIT. - - Evaluate offset item if necessary. - - @return Number of rows to skip. - */ - ha_rows get_offset(); - /** - Get limit. - - Evaluate limit item if necessary. - - @return Limit of rows in result. - */ - ha_rows get_limit(); - - friend struct LEX; - st_select_lex() : group_list_ptrs(NULL), braces(0), automatic_brackets(0), - n_sum_items(0), n_child_sum_items(0) - {} - void make_empty_select() - { - init_query(); - init_select(); - } - bool setup_ref_array(THD *thd, uint order_group_num); - void print(THD *thd, String *str, enum_query_type query_type); - static void print_order(String *str, - ORDER *order, - enum_query_type query_type); - void print_limit(THD *thd, String *str, enum_query_type query_type); - void fix_prepare_information(THD *thd, Item **conds, Item **having_conds); - /* - Destroy the used execution plan (JOIN) of this subtree (this - SELECT_LEX and all nested SELECT_LEXes and SELECT_LEX_UNITs). - */ - bool cleanup(); - /* - Recursively cleanup the join of this select lex and of all nested - select lexes. - */ - void cleanup_all_joins(bool full); - - void set_index_hint_type(enum index_hint_type type, index_clause_map clause); - - /* - Add a index hint to the tagged list of hints. The type and clause of the - hint will be the current ones (set by set_index_hint()) - */ - bool add_index_hint (THD *thd, const char *str, size_t length); - - /* make a list to hold index hints */ - void alloc_index_hints (THD *thd); - /* read and clear the index hints */ - List* pop_index_hints(void) - { - List *hints= index_hints; - index_hints= NULL; - return hints; - } - - void clear_index_hints(void) { index_hints= NULL; } - bool is_part_of_union() { return master_unit()->is_unit_op(); } - bool is_top_level_node() - { - return (select_number == 1) && !is_part_of_union(); - } - bool optimize_unflattened_subqueries(bool const_only); - /* Set the EXPLAIN type for this subquery. */ - void set_explain_type(bool on_the_fly); - bool handle_derived(LEX *lex, uint phases); - void append_table_to_list(TABLE_LIST *TABLE_LIST::*link, TABLE_LIST *table); - bool get_free_table_map(table_map *map, uint *tablenr); - void replace_leaf_table(TABLE_LIST *table, List &tbl_list); - void remap_tables(TABLE_LIST *derived, table_map map, - uint tablenr, st_select_lex *parent_lex); - bool merge_subquery(THD *thd, TABLE_LIST *derived, st_select_lex *subq_lex, - uint tablenr, table_map map); - inline bool is_mergeable() - { - return (next_select() == 0 && group_list.elements == 0 && - having == 0 && with_sum_func == 0 && - table_list.elements >= 1 && !(options & SELECT_DISTINCT) && - select_limit == 0); - } - void mark_as_belong_to_derived(TABLE_LIST *derived); - void increase_derived_records(ha_rows records); - void update_used_tables(); - void update_correlated_cache(); - void mark_const_derived(bool empty); - - bool save_leaf_tables(THD *thd); - bool save_prep_leaf_tables(THD *thd); - - bool is_merged_child_of(st_select_lex *ancestor); - - /* - For MODE_ONLY_FULL_GROUP_BY we need to maintain two flags: - - Non-aggregated fields are used in this select. - - Aggregate functions are used in this select. - In MODE_ONLY_FULL_GROUP_BY only one of these may be true. - */ - bool non_agg_field_used() const { return m_non_agg_field_used; } - bool agg_func_used() const { return m_agg_func_used; } - bool custom_agg_func_used() const { return m_custom_agg_func_used; } - - void set_non_agg_field_used(bool val) { m_non_agg_field_used= val; } - void set_agg_func_used(bool val) { m_agg_func_used= val; } - void set_custom_agg_func_used(bool val) { m_custom_agg_func_used= val; } - inline void set_with_clause(With_clause *with_clause); - With_clause *get_with_clause() - { - return master_unit()->with_clause; - } - With_element *get_with_element() - { - return master_unit()->with_element; - } - With_element *find_table_def_in_with_clauses(TABLE_LIST *table); - bool check_unrestricted_recursive(bool only_standard_compliant); - bool check_subqueries_with_recursive_references(); - void collect_grouping_fields_for_derived(THD *thd, ORDER *grouping_list); - bool collect_grouping_fields(THD *thd); - bool collect_fields_equal_to_grouping(THD *thd); - void check_cond_extraction_for_grouping_fields(THD *thd, Item *cond); - Item *build_cond_for_grouping_fields(THD *thd, Item *cond, - bool no_to_clones); - - List window_specs; - void prepare_add_window_spec(THD *thd); - bool add_window_def(THD *thd, LEX_CSTRING *win_name, LEX_CSTRING *win_ref, - SQL_I_List win_partition_list, - SQL_I_List win_order_list, - Window_frame *win_frame); - bool add_window_spec(THD *thd, LEX_CSTRING *win_ref, - SQL_I_List win_partition_list, - SQL_I_List win_order_list, - Window_frame *win_frame); - List window_funcs; - bool add_window_func(Item_window_func *win_func); - - bool have_window_funcs() const { return (window_funcs.elements !=0); } - ORDER *find_common_window_func_partition_fields(THD *thd); - - bool cond_pushdown_is_allowed() const - { return !olap && !explicit_limit && !tvc; } - - bool build_pushable_cond_for_having_pushdown(THD *thd, Item *cond); - void pushdown_cond_into_where_clause(THD *thd, Item *extracted_cond, - Item **remaining_cond, - Item_transformer transformer, - uchar *arg); - Item *pushdown_from_having_into_where(THD *thd, Item *having); - - select_handler *find_select_handler(THD *thd); - - bool is_set_op() - { - return linkage == UNION_TYPE || - linkage == EXCEPT_TYPE || - linkage == INTERSECT_TYPE; - } - -private: - bool m_non_agg_field_used; - bool m_agg_func_used; - bool m_custom_agg_func_used; - - /* current index hint kind. used in filling up index_hints */ - enum index_hint_type current_index_hint_type; - index_clause_map current_index_hint_clause; - /* a list of USE/FORCE/IGNORE INDEX */ - List *index_hints; - -public: - inline void add_where_field(st_select_lex *sel) - { - DBUG_ASSERT(this != sel); - select_n_where_fields+= sel->select_n_where_fields; - } - inline void set_linkage_and_distinct(enum sub_select_type l, bool d) - { - DBUG_ENTER("SELECT_LEX::set_linkage_and_distinct"); - DBUG_PRINT("info", ("select: %p distinct %d", this, d)); - set_linkage(l); - DBUG_ASSERT(l == UNION_TYPE || - l == INTERSECT_TYPE || - l == EXCEPT_TYPE); - if (d && master_unit() && master_unit()->union_distinct != this) - master_unit()->union_distinct= this; - distinct= d; - with_all_modifier= !distinct; - DBUG_VOID_RETURN; - } - bool set_nest_level(int new_nest_level); - bool check_parameters(SELECT_LEX *main_select); - void mark_select() - { - DBUG_ENTER("st_select_lex::mark_select()"); - DBUG_PRINT("info", ("Select #%d", select_number)); - DBUG_VOID_RETURN; - } - void register_unit(SELECT_LEX_UNIT *unit, - Name_resolution_context *outer_context); - SELECT_LEX_UNIT *attach_selects_chain(SELECT_LEX *sel, - Name_resolution_context *context); - void add_statistics(SELECT_LEX_UNIT *unit); - bool make_unique_derived_name(THD *thd, LEX_CSTRING *alias); - void lex_start(LEX *plex); - bool is_unit_nest() { return (nest_flags & UNIT_NEST_FL); } - void mark_as_unit_nest() { nest_flags= UNIT_NEST_FL; } -}; -typedef class st_select_lex SELECT_LEX; - -inline bool st_select_lex_unit::is_unit_op () -{ - if (!first_select()->next_select()) - { - if (first_select()->tvc) - return 1; - else - return 0; - } - - enum sub_select_type linkage= first_select()->next_select()->linkage; - return linkage == UNION_TYPE || linkage == INTERSECT_TYPE || - linkage == EXCEPT_TYPE; -} - - -struct st_sp_chistics -{ - LEX_CSTRING comment; - enum enum_sp_suid_behaviour suid; - bool detistic; - enum enum_sp_data_access daccess; - enum enum_sp_aggregate_type agg_type; - void init() { bzero(this, sizeof(*this)); } - void set(const st_sp_chistics &other) { *this= other; } - bool read_from_mysql_proc_row(THD *thd, TABLE *table); -}; - - -class Sp_chistics: public st_sp_chistics -{ -public: - Sp_chistics() { init(); } -}; - - -struct st_trg_chistics: public st_trg_execution_order -{ - enum trg_action_time_type action_time; - enum trg_event_type event; - - const char *ordering_clause_begin; - const char *ordering_clause_end; - -}; - -enum xa_option_words {XA_NONE, XA_JOIN, XA_RESUME, XA_ONE_PHASE, - XA_SUSPEND, XA_FOR_MIGRATE}; - -class Sroutine_hash_entry; - -/* - Class representing list of all tables used by statement and other - information which is necessary for opening and locking its tables, - like SQL command for this statement. - - Also contains information about stored functions used by statement - since during its execution we may have to add all tables used by its - stored functions/triggers to this list in order to pre-open and lock - them. - - Also used by LEX::reset_n_backup/restore_backup_query_tables_list() - methods to save and restore this information. -*/ - -class Query_tables_list -{ -public: - /** - SQL command for this statement. Part of this class since the - process of opening and locking tables for the statement needs - this information to determine correct type of lock for some of - the tables. - */ - enum_sql_command sql_command; - /* Global list of all tables used by this statement */ - TABLE_LIST *query_tables; - /* Pointer to next_global member of last element in the previous list. */ - TABLE_LIST **query_tables_last; - /* - If non-0 then indicates that query requires prelocking and points to - next_global member of last own element in query table list (i.e. last - table which was not added to it as part of preparation to prelocking). - 0 - indicates that this query does not need prelocking. - */ - TABLE_LIST **query_tables_own_last; - /* - Set of stored routines called by statement. - (Note that we use lazy-initialization for this hash). - */ - enum { START_SROUTINES_HASH_SIZE= 16 }; - HASH sroutines; - /* - List linking elements of 'sroutines' set. Allows you to add new elements - to this set as you iterate through the list of existing elements. - 'sroutines_list_own_last' is pointer to ::next member of last element of - this list which represents routine which is explicitly used by query. - 'sroutines_list_own_elements' number of explicitly used routines. - We use these two members for restoring of 'sroutines_list' to the state - in which it was right after query parsing. - */ - SQL_I_List sroutines_list; - Sroutine_hash_entry **sroutines_list_own_last; - uint sroutines_list_own_elements; - - /** - Number of tables which were open by open_tables() and to be locked - by lock_tables(). - Note that we set this member only in some cases, when this value - needs to be passed from open_tables() to lock_tables() which are - separated by some amount of code. - */ - uint table_count; - - /* - These constructor and destructor serve for creation/destruction - of Query_tables_list instances which are used as backup storage. - */ - Query_tables_list() {} - ~Query_tables_list() {} - - /* Initializes (or resets) Query_tables_list object for "real" use. */ - void reset_query_tables_list(bool init); - void destroy_query_tables_list(); - void set_query_tables_list(Query_tables_list *state) - { - *this= *state; - } - - /* - Direct addition to the list of query tables. - If you are using this function, you must ensure that the table - object, in particular table->db member, is initialized. - */ - void add_to_query_tables(TABLE_LIST *table) - { - *(table->prev_global= query_tables_last)= table; - query_tables_last= &table->next_global; - } - bool requires_prelocking() - { - return MY_TEST(query_tables_own_last); - } - void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last) - { - query_tables_own_last= tables_own_last; - } - /* Return pointer to first not-own table in query-tables or 0 */ - TABLE_LIST* first_not_own_table() - { - return ( query_tables_own_last ? *query_tables_own_last : 0); - } - void chop_off_not_own_tables() - { - if (query_tables_own_last) - { - *query_tables_own_last= 0; - query_tables_last= query_tables_own_last; - query_tables_own_last= 0; - } - } - - /** Return a pointer to the last element in query table list. */ - TABLE_LIST *last_table() - { - /* Don't use offsetof() macro in order to avoid warnings. */ - return query_tables ? - (TABLE_LIST*) ((char*) query_tables_last - - ((char*) &(query_tables->next_global) - - (char*) query_tables)) : - 0; - } - - /** - Enumeration listing of all types of unsafe statement. - - @note The order of elements of this enumeration type must - correspond to the order of the elements of the @c explanations - array defined in the body of @c THD::issue_unsafe_warnings. - */ - enum enum_binlog_stmt_unsafe { - /** - SELECT..LIMIT is unsafe because the set of rows returned cannot - be predicted. - */ - BINLOG_STMT_UNSAFE_LIMIT= 0, - /** - INSERT DELAYED is unsafe because the time when rows are inserted - cannot be predicted. - */ - BINLOG_STMT_UNSAFE_INSERT_DELAYED, - /** - Access to log tables is unsafe because slave and master probably - log different things. - */ - BINLOG_STMT_UNSAFE_SYSTEM_TABLE, - /** - Inserting into an autoincrement column in a stored routine is unsafe. - Even with just one autoincrement column, if the routine is invoked more than - once slave is not guaranteed to execute the statement graph same way as - the master. - And since it's impossible to estimate how many times a routine can be invoked at - the query pre-execution phase (see lock_tables), the statement is marked - pessimistically unsafe. - */ - BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS, - /** - Using a UDF (user-defined function) is unsafe. - */ - BINLOG_STMT_UNSAFE_UDF, - /** - Using most system variables is unsafe, because slave may run - with different options than master. - */ - BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE, - /** - Using some functions is unsafe (e.g., UUID). - */ - BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION, - - /** - Mixing transactional and non-transactional statements are unsafe if - non-transactional reads or writes are occur after transactional - reads or writes inside a transaction. - */ - BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS, - - /** - Mixing self-logging and non-self-logging engines in a statement - is unsafe. - */ - BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE, - - /** - Statements that read from both transactional and non-transactional - tables and write to any of them are unsafe. - */ - BINLOG_STMT_UNSAFE_MIXED_STATEMENT, - - /** - INSERT...IGNORE SELECT is unsafe because which rows are ignored depends - on the order that rows are retrieved by SELECT. This order cannot be - predicted and may differ on master and the slave. - */ - BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT, - - /** - INSERT...SELECT...UPDATE is unsafe because which rows are updated depends - on the order that rows are retrieved by SELECT. This order cannot be - predicted and may differ on master and the slave. - */ - BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE, - - /** - Query that writes to a table with auto_inc column after selecting from - other tables are unsafe as the order in which the rows are retrieved by - select may differ on master and slave. - */ - BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT, - - /** - INSERT...REPLACE SELECT is unsafe because which rows are replaced depends - on the order that rows are retrieved by SELECT. This order cannot be - predicted and may differ on master and the slave. - */ - BINLOG_STMT_UNSAFE_REPLACE_SELECT, - - /** - CREATE TABLE... IGNORE... SELECT is unsafe because which rows are ignored - depends on the order that rows are retrieved by SELECT. This order cannot - be predicted and may differ on master and the slave. - */ - BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT, - - /** - CREATE TABLE...REPLACE... SELECT is unsafe because which rows are replaced - depends on the order that rows are retrieved from SELECT. This order - cannot be predicted and may differ on master and the slave - */ - BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT, - - /** - CREATE TABLE...SELECT on a table with auto-increment column is unsafe - because which rows are replaced depends on the order that rows are - retrieved from SELECT. This order cannot be predicted and may differ on - master and the slave - */ - BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC, - - /** - UPDATE...IGNORE is unsafe because which rows are ignored depends on the - order that rows are updated. This order cannot be predicted and may differ - on master and the slave. - */ - BINLOG_STMT_UNSAFE_UPDATE_IGNORE, - - /** - INSERT... ON DUPLICATE KEY UPDATE on a table with more than one - UNIQUE KEYS is unsafe. - */ - BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS, - - /** - INSERT into auto-inc field which is not the first part of composed - primary key. - */ - BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST, - - /* The last element of this enumeration type. */ - BINLOG_STMT_UNSAFE_COUNT - }; - /** - This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT - (exclusive) set. - */ - static const uint32 BINLOG_STMT_UNSAFE_ALL_FLAGS= - ((1U << BINLOG_STMT_UNSAFE_COUNT) - 1); - - /** - Maps elements of enum_binlog_stmt_unsafe to error codes. - */ - static const int binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT]; - - /** - Determine if this statement is marked as unsafe. - - @retval 0 if the statement is not marked as unsafe. - @retval nonzero if the statement is marked as unsafe. - */ - inline bool is_stmt_unsafe() const { - return get_stmt_unsafe_flags() != 0; - } - - inline bool is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe) - { - return binlog_stmt_flags & (1 << unsafe); - } - - /** - Flag the current (top-level) statement as unsafe. - The flag will be reset after the statement has finished. - - @param unsafe_type The type of unsafety: one of the @c - BINLOG_STMT_FLAG_UNSAFE_* flags in @c enum_binlog_stmt_flag. - */ - inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) { - DBUG_ENTER("set_stmt_unsafe"); - DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT); - binlog_stmt_flags|= (1U << unsafe_type); - DBUG_VOID_RETURN; - } - - /** - Set the bits of binlog_stmt_flags determining the type of - unsafeness of the current statement. No existing bits will be - cleared, but new bits may be set. - - @param flags A binary combination of zero or more bits, (1<= ISO_REPEATABLE_READ */ - - /** - Sets the type of table that is about to be accessed while executing a - statement. - - @param accessed_table Enumeration type that defines the type of table, - e.g. temporary, transactional, non-transactional. - */ - inline void set_stmt_accessed_table(enum_stmt_accessed_table accessed_table) - { - DBUG_ENTER("LEX::set_stmt_accessed_table"); - - DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT); - stmt_accessed_table_flag |= (1U << accessed_table); - - DBUG_VOID_RETURN; - } - - /** - Checks if a type of table is about to be accessed while executing a - statement. - - @param accessed_table Enumeration type that defines the type of table, - e.g. temporary, transactional, non-transactional. - - @return - @retval TRUE if the type of the table is about to be accessed - @retval FALSE otherwise - */ - inline bool stmt_accessed_table(enum_stmt_accessed_table accessed_table) - { - DBUG_ENTER("LEX::stmt_accessed_table"); - - DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT); - - DBUG_RETURN((stmt_accessed_table_flag & (1U << accessed_table)) != 0); - } - - /** - Checks either a trans/non trans temporary table is being accessed while - executing a statement. - - @return - @retval TRUE if a temporary table is being accessed - @retval FALSE otherwise - */ - inline bool stmt_accessed_temp_table() - { - DBUG_ENTER("THD::stmt_accessed_temp_table"); - DBUG_RETURN(stmt_accessed_non_trans_temp_table() || - stmt_accessed_trans_temp_table()); - } - - /** - Checks if a temporary transactional table is being accessed while executing - a statement. - - @return - @retval TRUE if a temporary transactional table is being accessed - @retval FALSE otherwise - */ - inline bool stmt_accessed_trans_temp_table() - { - DBUG_ENTER("THD::stmt_accessed_trans_temp_table"); - - DBUG_RETURN((stmt_accessed_table_flag & - ((1U << STMT_READS_TEMP_TRANS_TABLE) | - (1U << STMT_WRITES_TEMP_TRANS_TABLE))) != 0); - } - inline bool stmt_writes_to_non_temp_table() - { - DBUG_ENTER("THD::stmt_writes_to_non_temp_table"); - - DBUG_RETURN((stmt_accessed_table_flag & - ((1U << STMT_WRITES_TRANS_TABLE) | - (1U << STMT_WRITES_NON_TRANS_TABLE)))); - } - - /** - Checks if a temporary non-transactional table is about to be accessed - while executing a statement. - - @return - @retval TRUE if a temporary non-transactional table is about to be - accessed - @retval FALSE otherwise - */ - inline bool stmt_accessed_non_trans_temp_table() - { - DBUG_ENTER("THD::stmt_accessed_non_trans_temp_table"); - - DBUG_RETURN((stmt_accessed_table_flag & - ((1U << STMT_READS_TEMP_NON_TRANS_TABLE) | - (1U << STMT_WRITES_TEMP_NON_TRANS_TABLE))) != 0); - } - - /* - Checks if a mixed statement is unsafe. - - - @param in_multi_stmt_transaction_mode defines if there is an on-going - multi-transactional statement. - @param binlog_direct defines if --binlog-direct-non-trans-updates is - active. - @param trx_cache_is_not_empty defines if the trx-cache is empty or not. - @param trx_isolation defines the isolation level. - - @return - @retval TRUE if the mixed statement is unsafe - @retval FALSE otherwise - */ - inline bool is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode, - bool binlog_direct, - bool trx_cache_is_not_empty, - uint tx_isolation) - { - bool unsafe= FALSE; - - if (in_multi_stmt_transaction_mode) - { - uint condition= - (binlog_direct ? BINLOG_DIRECT_ON : BINLOG_DIRECT_OFF) & - (trx_cache_is_not_empty ? TRX_CACHE_NOT_EMPTY : TRX_CACHE_EMPTY) & - (tx_isolation >= ISO_REPEATABLE_READ ? IL_GTE_REPEATABLE : IL_LT_REPEATABLE); - - unsafe= (binlog_unsafe_map[stmt_accessed_table_flag] & condition); - -#if !defined(DBUG_OFF) - DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("RESULT %02X %02X %02X", condition, - binlog_unsafe_map[stmt_accessed_table_flag], - (binlog_unsafe_map[stmt_accessed_table_flag] & condition))); - - int type_in= 0; - for (; type_in < STMT_ACCESS_TABLE_COUNT; type_in++) - { - if (stmt_accessed_table((enum_stmt_accessed_table) type_in)) - DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("ACCESSED %s ", - stmt_accessed_table_string((enum_stmt_accessed_table) type_in))); - } -#endif - } - - if (stmt_accessed_table(STMT_WRITES_NON_TRANS_TABLE) && - stmt_accessed_table(STMT_READS_TRANS_TABLE) && - tx_isolation < ISO_REPEATABLE_READ) - unsafe= TRUE; - else if (stmt_accessed_table(STMT_WRITES_TEMP_NON_TRANS_TABLE) && - stmt_accessed_table(STMT_READS_TRANS_TABLE) && - tx_isolation < ISO_REPEATABLE_READ) - unsafe= TRUE; - - return(unsafe); - } - - /** - true if the parsed tree contains references to stored procedures - or functions, false otherwise - */ - bool uses_stored_routines() const - { return sroutines_list.elements != 0; } - -private: - - /** - Enumeration listing special types of statements. - - Currently, the only possible type is ROW_INJECTION. - */ - enum enum_binlog_stmt_type { - /** - The statement is a row injection (i.e., either a BINLOG - statement or a row event executed by the slave SQL thread). - */ - BINLOG_STMT_TYPE_ROW_INJECTION = 0, - - /** The last element of this enumeration type. */ - BINLOG_STMT_TYPE_COUNT - }; - - /** - Bit field indicating the type of statement. - - There are two groups of bits: - - - The low BINLOG_STMT_UNSAFE_COUNT bits indicate the types of - unsafeness that the current statement has. - - - The next BINLOG_STMT_TYPE_COUNT bits indicate if the statement - is of some special type. - - This must be a member of LEX, not of THD: each stored procedure - needs to remember its unsafeness state between calls and each - stored procedure has its own LEX object (but no own THD object). - */ - uint32 binlog_stmt_flags; - - /** - Bit field that determines the type of tables that are about to be - be accessed while executing a statement. - */ - uint32 stmt_accessed_table_flag; -}; - - -/* - st_parsing_options contains the flags for constructions that are - allowed in the current statement. -*/ - -struct st_parsing_options -{ - bool allows_variable; - bool lookup_keywords_after_qualifier; - - st_parsing_options() { reset(); } - void reset(); -}; - - -/** - The state of the lexical parser, when parsing comments. -*/ -enum enum_comment_state -{ - /** - Not parsing comments. - */ - NO_COMMENT, - /** - Parsing comments that need to be preserved. - Typically, these are user comments '/' '*' ... '*' '/'. - */ - PRESERVE_COMMENT, - /** - Parsing comments that need to be discarded. - Typically, these are special comments '/' '*' '!' ... '*' '/', - or '/' '*' '!' 'M' 'M' 'm' 'm' 'm' ... '*' '/', where the comment - markers should not be expanded. - */ - DISCARD_COMMENT -}; - - -/** - @brief This class represents the character input stream consumed during - lexical analysis. - - In addition to consuming the input stream, this class performs some - comment pre processing, by filtering out out of bound special text - from the query input stream. - Two buffers, with pointers inside each buffers, are maintained in - parallel. The 'raw' buffer is the original query text, which may - contain out-of-bound comments. The 'cpp' (for comments pre processor) - is the pre-processed buffer that contains only the query text that - should be seen once out-of-bound data is removed. -*/ - -class Lex_input_stream -{ - size_t unescape(CHARSET_INFO *cs, char *to, - const char *str, const char *end, int sep); - my_charset_conv_wc_mb get_escape_func(THD *thd, my_wc_t sep) const; -public: - Lex_input_stream() - { - } - - ~Lex_input_stream() - { - } - - /** - Object initializer. Must be called before usage. - - @retval FALSE OK - @retval TRUE Error - */ - bool init(THD *thd, char *buff, size_t length); - - void reset(char *buff, size_t length); - - /** - The main method to scan the next token, with token contraction processing - for LALR(2) resolution, e.g. translate "WITH" followed by "ROLLUP" - to a single token WITH_ROLLUP_SYM. - */ - int lex_token(union YYSTYPE *yylval, THD *thd); - - void reduce_digest_token(uint token_left, uint token_right); - -private: - /** - Set the echo mode. - - When echo is true, characters parsed from the raw input stream are - preserved. When false, characters parsed are silently ignored. - @param echo the echo mode. - */ - void set_echo(bool echo) - { - m_echo= echo; - } - - void save_in_comment_state() - { - m_echo_saved= m_echo; - in_comment_saved= in_comment; - } - - void restore_in_comment_state() - { - m_echo= m_echo_saved; - in_comment= in_comment_saved; - } - - /** - Skip binary from the input stream. - @param n number of bytes to accept. - */ - void skip_binary(int n) - { - if (m_echo) - { - memcpy(m_cpp_ptr, m_ptr, n); - m_cpp_ptr += n; - } - m_ptr += n; - } - - /** - Get a character, and advance in the stream. - @return the next character to parse. - */ - unsigned char yyGet() - { - char c= *m_ptr++; - if (m_echo) - *m_cpp_ptr++ = c; - return c; - } - - /** - Get the last character accepted. - @return the last character accepted. - */ - unsigned char yyGetLast() - { - return m_ptr[-1]; - } - - /** - Look at the next character to parse, but do not accept it. - */ - unsigned char yyPeek() - { - return m_ptr[0]; - } - - /** - Look ahead at some character to parse. - @param n offset of the character to look up - */ - unsigned char yyPeekn(int n) - { - return m_ptr[n]; - } - - /** - Cancel the effect of the last yyGet() or yySkip(). - Note that the echo mode should not change between calls to yyGet / yySkip - and yyUnget. The caller is responsible for ensuring that. - */ - void yyUnget() - { - m_ptr--; - if (m_echo) - m_cpp_ptr--; - } - - /** - Accept a character, by advancing the input stream. - */ - void yySkip() - { - if (m_echo) - *m_cpp_ptr++ = *m_ptr++; - else - m_ptr++; - } - - /** - Accept multiple characters at once. - @param n the number of characters to accept. - */ - void yySkipn(int n) - { - if (m_echo) - { - memcpy(m_cpp_ptr, m_ptr, n); - m_cpp_ptr += n; - } - m_ptr += n; - } - - /** - Puts a character back into the stream, canceling - the effect of the last yyGet() or yySkip(). - Note that the echo mode should not change between calls - to unput, get, or skip from the stream. - */ - char *yyUnput(char ch) - { - *--m_ptr= ch; - if (m_echo) - m_cpp_ptr--; - return m_ptr; - } - - /** - End of file indicator for the query text to parse. - @param n number of characters expected - @return true if there are less than n characters to parse - */ - bool eof(int n) - { - return ((m_ptr + n) >= m_end_of_query); - } - - /** Mark the stream position as the start of a new token. */ - void start_token() - { - m_tok_start_prev= m_tok_start; - m_tok_start= m_ptr; - m_tok_end= m_ptr; - - m_cpp_tok_start_prev= m_cpp_tok_start; - m_cpp_tok_start= m_cpp_ptr; - m_cpp_tok_end= m_cpp_ptr; - } - - /** - Adjust the starting position of the current token. - This is used to compensate for starting whitespace. - */ - void restart_token() - { - m_tok_start= m_ptr; - m_cpp_tok_start= m_cpp_ptr; - } - - /** - Get the maximum length of the utf8-body buffer. - The utf8 body can grow because of the character set conversion and escaping. - */ - size_t get_body_utf8_maximum_length(THD *thd); - - /** Get the length of the current token, in the raw buffer. */ - uint yyLength() - { - /* - The assumption is that the lexical analyser is always 1 character ahead, - which the -1 account for. - */ - DBUG_ASSERT(m_ptr > m_tok_start); - return (uint) ((m_ptr - m_tok_start) - 1); - } - - /** - Test if a lookahead token was already scanned by lex_token(), - for LALR(2) resolution. - */ - bool has_lookahead() const - { - return lookahead_token >= 0; - } - -public: - - /** - End of file indicator for the query text to parse. - @return true if there are no more characters to parse - */ - bool eof() - { - return (m_ptr >= m_end_of_query); - } - - /** Get the raw query buffer. */ - const char *get_buf() - { - return m_buf; - } - - /** Get the pre-processed query buffer. */ - const char *get_cpp_buf() - { - return m_cpp_buf; - } - - /** Get the end of the raw query buffer. */ - const char *get_end_of_query() - { - return m_end_of_query; - } - - /** Get the token start position, in the raw buffer. */ - const char *get_tok_start() - { - return has_lookahead() ? m_tok_start_prev : m_tok_start; - } - - void set_cpp_tok_start(const char *pos) - { - m_cpp_tok_start= pos; - } - - /** Get the token end position, in the raw buffer. */ - const char *get_tok_end() - { - return m_tok_end; - } - - /** Get the current stream pointer, in the raw buffer. */ - const char *get_ptr() - { - return m_ptr; - } - - /** Get the token start position, in the pre-processed buffer. */ - const char *get_cpp_tok_start() - { - return has_lookahead() ? m_cpp_tok_start_prev : m_cpp_tok_start; - } - - /** Get the token end position, in the pre-processed buffer. */ - const char *get_cpp_tok_end() - { - return m_cpp_tok_end; - } - - /** - Get the token end position in the pre-processed buffer, - with trailing spaces removed. - */ - const char *get_cpp_tok_end_rtrim() - { - const char *p; - for (p= m_cpp_tok_end; - p > m_cpp_buf && my_isspace(system_charset_info, p[-1]); - p--) - { } - return p; - } - - /** Get the current stream pointer, in the pre-processed buffer. */ - const char *get_cpp_ptr() - { - return m_cpp_ptr; - } - - /** - Get the current stream pointer, in the pre-processed buffer, - with traling spaces removed. - */ - const char *get_cpp_ptr_rtrim() - { - const char *p; - for (p= m_cpp_ptr; - p > m_cpp_buf && my_isspace(system_charset_info, p[-1]); - p--) - { } - return p; - } - /** Get the utf8-body string. */ - const char *get_body_utf8_str() - { - return m_body_utf8; - } - - /** Get the utf8-body length. */ - size_t get_body_utf8_length() - { - return (size_t) (m_body_utf8_ptr - m_body_utf8); - } - - void body_utf8_start(THD *thd, const char *begin_ptr); - void body_utf8_append(const char *ptr); - void body_utf8_append(const char *ptr, const char *end_ptr); - void body_utf8_append_ident(THD *thd, - const Lex_string_with_metadata_st *txt, - const char *end_ptr); - void body_utf8_append_escape(THD *thd, - const LEX_CSTRING *txt, - CHARSET_INFO *txt_cs, - const char *end_ptr, - my_wc_t sep); - -private: - /** - LALR(2) resolution, look ahead token. - Value of the next token to return, if any, - or -1, if no token was parsed in advance. - Note: 0 is a legal token, and represents YYEOF. - */ - int lookahead_token; - - /** LALR(2) resolution, value of the look ahead token.*/ - LEX_YYSTYPE lookahead_yylval; - - bool get_text(Lex_string_with_metadata_st *to, - uint sep, int pre_skip, int post_skip); - - void add_digest_token(uint token, LEX_YYSTYPE yylval); - - bool consume_comment(int remaining_recursions_permitted); - int lex_one_token(union YYSTYPE *yylval, THD *thd); - int find_keyword(Lex_ident_cli_st *str, uint len, bool function); - LEX_CSTRING get_token(uint skip, uint length); - int scan_ident_sysvar(THD *thd, Lex_ident_cli_st *str); - int scan_ident_start(THD *thd, Lex_ident_cli_st *str); - int scan_ident_middle(THD *thd, Lex_ident_cli_st *str, - CHARSET_INFO **cs, my_lex_states *); - int scan_ident_delimited(THD *thd, Lex_ident_cli_st *str, uchar quote_char); - bool get_7bit_or_8bit_ident(THD *thd, uchar *last_char); - - /** Current thread. */ - THD *m_thd; - - /** Pointer to the current position in the raw input stream. */ - char *m_ptr; - - /** Starting position of the last token parsed, in the raw buffer. */ - const char *m_tok_start; - - /** Ending position of the previous token parsed, in the raw buffer. */ - const char *m_tok_end; - - /** End of the query text in the input stream, in the raw buffer. */ - const char *m_end_of_query; - - /** Starting position of the previous token parsed, in the raw buffer. */ - const char *m_tok_start_prev; - - /** Begining of the query text in the input stream, in the raw buffer. */ - const char *m_buf; - - /** Length of the raw buffer. */ - size_t m_buf_length; - - /** Echo the parsed stream to the pre-processed buffer. */ - bool m_echo; - bool m_echo_saved; - - /** Pre-processed buffer. */ - char *m_cpp_buf; - - /** Pointer to the current position in the pre-processed input stream. */ - char *m_cpp_ptr; - - /** - Starting position of the last token parsed, - in the pre-processed buffer. - */ - const char *m_cpp_tok_start; - - /** - Starting position of the previous token parsed, - in the pre-procedded buffer. - */ - const char *m_cpp_tok_start_prev; - - /** - Ending position of the previous token parsed, - in the pre-processed buffer. - */ - const char *m_cpp_tok_end; - - /** UTF8-body buffer created during parsing. */ - char *m_body_utf8; - - /** Pointer to the current position in the UTF8-body buffer. */ - char *m_body_utf8_ptr; - - /** - Position in the pre-processed buffer. The query from m_cpp_buf to - m_cpp_utf_processed_ptr is converted to UTF8-body. - */ - const char *m_cpp_utf8_processed_ptr; - -public: - - /** Current state of the lexical analyser. */ - enum my_lex_states next_state; - - /** - Position of ';' in the stream, to delimit multiple queries. - This delimiter is in the raw buffer. - */ - const char *found_semicolon; - - /** SQL_MODE = IGNORE_SPACE. */ - bool ignore_space; - - /** - TRUE if we're parsing a prepared statement: in this mode - we should allow placeholders. - */ - bool stmt_prepare_mode; - /** - TRUE if we should allow multi-statements. - */ - bool multi_statements; - - /** Current line number. */ - uint yylineno; - - /** - Current statement digest instrumentation. - */ - sql_digest_state* m_digest; - -private: - /** State of the lexical analyser for comments. */ - enum_comment_state in_comment; - enum_comment_state in_comment_saved; - - /** - Starting position of the TEXT_STRING or IDENT in the pre-processed - buffer. - - NOTE: this member must be used within MYSQLlex() function only. - */ - const char *m_cpp_text_start; - - /** - Ending position of the TEXT_STRING or IDENT in the pre-processed - buffer. - - NOTE: this member must be used within MYSQLlex() function only. - */ - const char *m_cpp_text_end; - - /** - Character set specified by the character-set-introducer. - - NOTE: this member must be used within MYSQLlex() function only. - */ - CHARSET_INFO *m_underscore_cs; -}; - - -/** - Abstract representation of a statement. - This class is an interface between the parser and the runtime. - The parser builds the appropriate sub classes of Sql_statement - to represent a SQL statement in the parsed tree. - The execute() method in the sub classes contain the runtime implementation. - Note that this interface is used for SQL statement recently implemented, - the code for older statements tend to load the LEX structure with more - attributes instead. - The recommended way to implement new statements is to sub-class - Sql_statement, as this improves code modularity (see the 'big switch' in - dispatch_command()), and decrease the total size of the LEX structure - (therefore saving memory in stored programs). -*/ -class Sql_statement : public Sql_alloc -{ -public: - /** - Execute this SQL statement. - @param thd the current thread. - @return 0 on success. - */ - virtual bool execute(THD *thd) = 0; - -protected: - /** - Constructor. - @param lex the LEX structure that represents parts of this statement. - */ - Sql_statement(LEX *lex) - : m_lex(lex) - {} - - /** Destructor. */ - virtual ~Sql_statement() - { - /* - Sql_statement objects are allocated in thd->mem_root. - In MySQL, the C++ destructor is never called, the underlying MEM_ROOT is - simply destroyed instead. - Do not rely on the destructor for any cleanup. - */ - DBUG_ASSERT(FALSE); - } - -protected: - /** - The legacy LEX structure for this statement. - The LEX structure contains the existing properties of the parsed tree. - TODO: with time, attributes from LEX should move to sub classes of - Sql_statement, so that the parser only builds Sql_statement objects - with the minimum set of attributes, instead of a LEX structure that - contains the collection of every possible attribute. - */ - LEX *m_lex; -}; - - -class Delete_plan; -class SQL_SELECT; - -class Explain_query; -class Explain_update; -class Explain_delete; - -/* - Query plan of a single-table UPDATE. - (This is actually a plan for single-table DELETE also) -*/ - -class Update_plan -{ -protected: - bool impossible_where; - bool no_partitions; -public: - /* Allocate things there */ - MEM_ROOT *mem_root; - - TABLE *table; - SQL_SELECT *select; - uint index; - ha_rows scanned_rows; - /* - Top-level select_lex. Most of its fields are not used, we need it only to - get to the subqueries. - */ - SELECT_LEX *select_lex; - - key_map possible_keys; - bool using_filesort; - bool using_io_buffer; - - /* Set this plan to be a plan to do nothing because of impossible WHERE */ - void set_impossible_where() { impossible_where= true; } - void set_no_partitions() { no_partitions= true; } - - Explain_update* save_explain_update_data(MEM_ROOT *mem_root, THD *thd); -protected: - bool save_explain_data_intern(MEM_ROOT *mem_root, Explain_update *eu, bool is_analyze); -public: - virtual ~Update_plan() {} - - Update_plan(MEM_ROOT *mem_root_arg) : - impossible_where(false), no_partitions(false), - mem_root(mem_root_arg), - using_filesort(false), using_io_buffer(false) - {} -}; - - -/* Query plan of a single-table DELETE */ -class Delete_plan : public Update_plan -{ - bool deleting_all_rows; -public: - - /* Construction functions */ - Delete_plan(MEM_ROOT *mem_root_arg) : - Update_plan(mem_root_arg), - deleting_all_rows(false) - {} - - /* Set this query plan to be a plan to make a call to h->delete_all_rows() */ - void set_delete_all_rows(ha_rows rows_arg) - { - deleting_all_rows= true; - scanned_rows= rows_arg; - } - void cancel_delete_all_rows() - { - deleting_all_rows= false; - } - - Explain_delete* save_explain_delete_data(MEM_ROOT *mem_root, THD *thd); -}; - -enum account_lock_type -{ - ACCOUNTLOCK_UNSPECIFIED= 0, - ACCOUNTLOCK_LOCKED, - ACCOUNTLOCK_UNLOCKED -}; - -enum password_exp_type -{ - PASSWORD_EXPIRE_UNSPECIFIED= 0, - PASSWORD_EXPIRE_NOW, - PASSWORD_EXPIRE_NEVER, - PASSWORD_EXPIRE_DEFAULT, - PASSWORD_EXPIRE_INTERVAL -}; - -struct Account_options: public USER_RESOURCES -{ - Account_options() { } - - void reset() - { - bzero(this, sizeof(*this)); - ssl_type= SSL_TYPE_NOT_SPECIFIED; - } - - enum SSL_type ssl_type; // defined in violite.h - LEX_CSTRING x509_subject, x509_issuer, ssl_cipher; - account_lock_type account_locked; - password_exp_type password_expire; - longlong num_expiration_days; -}; - -class Query_arena_memroot; -/* The state of the lex parsing. This is saved in the THD struct */ - - -class Lex_prepared_stmt -{ - Lex_ident_sys m_name; // Statement name (in all queries) - Item *m_code; // PREPARE or EXECUTE IMMEDIATE source expression - List m_params; // List of parameters for EXECUTE [IMMEDIATE] -public: - - Lex_prepared_stmt() - :m_code(NULL) - { } - const Lex_ident_sys &name() const - { - return m_name; - } - uint param_count() const - { - return m_params.elements; - } - List ¶ms() - { - return m_params; - } - void set(const Lex_ident_sys_st &ident, Item *code, List *params) - { - DBUG_ASSERT(m_params.elements == 0); - m_name= ident; - m_code= code; - if (params) - m_params= *params; - } - bool params_fix_fields(THD *thd) - { - // Fix Items in the EXECUTE..USING list - List_iterator_fast param_it(m_params); - while (Item *param= param_it++) - { - if (param->fix_fields_if_needed_for_scalar(thd, 0)) - return true; - } - return false; - } - bool get_dynamic_sql_string(THD *thd, LEX_CSTRING *dst, String *buffer); - void lex_start() - { - m_params.empty(); - } -}; - - -class Lex_grant_object_name: public Grant_object_name, public Sql_alloc -{ -public: - Lex_grant_object_name(Table_ident *table_ident) - :Grant_object_name(table_ident) - { } - Lex_grant_object_name(const LEX_CSTRING &db, Type type) - :Grant_object_name(db, type) - { } -}; - - -class Lex_grant_privilege: public Grant_privilege, public Sql_alloc -{ -public: - Lex_grant_privilege() {} - Lex_grant_privilege(privilege_t grant, bool all_privileges= false) - :Grant_privilege(grant, all_privileges) - { } -}; - - -struct LEX: public Query_tables_list -{ - SELECT_LEX_UNIT unit; /* most upper unit */ - inline SELECT_LEX *first_select_lex() {return unit.first_select();} - -private: - SELECT_LEX builtin_select; - -public: - /* current SELECT_LEX in parsing */ - SELECT_LEX *current_select; - /* list of all SELECT_LEX */ - SELECT_LEX *all_selects_list; - /* current with clause in parsing if any, otherwise 0*/ - With_clause *curr_with_clause; - /* pointer to the first with clause in the current statement */ - With_clause *with_clauses_list; - /* - (*with_clauses_list_last_next) contains a pointer to the last - with clause in the current statement - */ - With_clause **with_clauses_list_last_next; - /* - When a copy of a with element is parsed this is set to the offset of - the with element in the input string, otherwise it's set to 0 - */ - my_ptrdiff_t clone_spec_offset; - - Create_view_info *create_view; - - /* Query Plan Footprint of a currently running select */ - Explain_query *explain; - - // type information - CHARSET_INFO *charset; - /* - LEX which represents current statement (conventional, SP or PS) - - For example during view parsing THD::lex will point to the views LEX and - lex::stmt_lex will point to LEX of the statement where the view will be - included - - Currently it is used to have always correct select numbering inside - statement (LEX::current_select_number) without storing and restoring a - global counter which was THD::select_number. - - TODO: make some unified statement representation (now SP has different) - to store such data like LEX::current_select_number. - */ - LEX *stmt_lex; - - LEX_CSTRING name; - const char *help_arg; - const char *backup_dir; /* For RESTORE/BACKUP */ - const char* to_log; /* For PURGE MASTER LOGS TO */ - String *wild; /* Wildcard in SHOW {something} LIKE 'wild'*/ - sql_exchange *exchange; - select_result *result; - /** - @c the two may also hold BINLOG arguments: either comment holds a - base64-char string or both represent the BINLOG fragment user variables. - */ - LEX_CSTRING comment, ident; - LEX_USER *grant_user; - XID *xid; - THD *thd; - - /* maintain a list of used plugins for this LEX */ - DYNAMIC_ARRAY plugins; - plugin_ref plugins_static_buffer[INITIAL_LEX_PLUGIN_LIST_SIZE]; - - /** SELECT of CREATE VIEW statement */ - LEX_STRING create_view_select; - - uint current_select_number; // valid for statment LEX (not view) - - /** Start of 'ON table', in trigger statements. */ - const char* raw_trg_on_table_name_begin; - /** End of 'ON table', in trigger statements. */ - const char* raw_trg_on_table_name_end; - - /* Partition info structure filled in by PARTITION BY parse part */ - partition_info *part_info; - - /* - The definer of the object being created (view, trigger, stored routine). - I.e. the value of DEFINER clause. - */ - LEX_USER *definer; - - /* Used in ALTER/CREATE user to store account locking options */ - Account_options account_options; - - Table_type table_type; /* Used for SHOW CREATE */ - List ref_list; - List users_list; - List *insert_list,field_list,value_list,update_list; - List many_values; - List var_list; - List stmt_var_list; //SET_STATEMENT values - List old_var_list; // SET STATEMENT old values -private: - Query_arena_memroot *arena_for_set_stmt; - MEM_ROOT *mem_root_for_set_stmt; - bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock, - class sp_label **splabel); - bool sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive); - bool sp_exit_block(THD *thd, sp_label *lab); - bool sp_exit_block(THD *thd, sp_label *lab, Item *when); - - bool sp_continue_loop(THD *thd, sp_label *lab); - - bool sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop); - bool sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop); - - /* - Check if Item_field and Item_ref are allowed in the current statement. - @retval false OK (fields are allowed) - @retval true ERROR (fields are not allowed). Error is raised. - */ - bool check_expr_allows_fields_or_error(THD *thd, const char *name) const; - -protected: - bool sp_continue_loop(THD *thd, sp_label *lab, Item *when); - -public: - void parse_error(uint err_number= ER_SYNTAX_ERROR); - inline bool is_arena_for_set_stmt() {return arena_for_set_stmt != 0;} - bool set_arena_for_set_stmt(Query_arena *backup); - void reset_arena_for_set_stmt(Query_arena *backup); - void free_arena_for_set_stmt(); - - void print(String *str, enum_query_type qtype); - List set_var_list; // in-query assignment list - List param_list; - List view_list; // view list (list of field names in view) - List *column_list; // list of column names (in ANALYZE) - List *index_list; // list of index names (in ANALYZE) - /* - A stack of name resolution contexts for the query. This stack is used - at parse time to set local name resolution contexts for various parts - of a query. For example, in a JOIN ... ON (some_condition) clause the - Items in 'some_condition' must be resolved only against the operands - of the the join, and not against the whole clause. Similarly, Items in - subqueries should be resolved against the subqueries (and outer queries). - The stack is used in the following way: when the parser detects that - all Items in some clause need a local context, it creates a new context - and pushes it on the stack. All newly created Items always store the - top-most context in the stack. Once the parser leaves the clause that - required a local context, the parser pops the top-most context. - */ - List context_stack; - SELECT_LEX *select_stack[MAX_SELECT_NESTING + 1]; - uint select_stack_top; - - SQL_I_List proc_list; - SQL_I_List auxiliary_table_list, save_list; - Column_definition *last_field; - Item_sum *in_sum_func; - udf_func udf; - HA_CHECK_OPT check_opt; // check/repair options - Table_specification_st create_info; - Key *last_key; - LEX_MASTER_INFO mi; // used by CHANGE MASTER - LEX_SERVER_OPTIONS server_options; - LEX_CSTRING relay_log_connection_name; - LEX_RESET_SLAVE reset_slave_info; - ulonglong type; - ulong next_binlog_file_number; - /* The following is used by KILL */ - killed_state kill_signal; - killed_type kill_type; - bool is_shutdown_wait_for_slaves; - /* - This variable is used in post-parse stage to declare that sum-functions, - or functions which have sense only if GROUP BY is present, are allowed. - For example in a query - SELECT ... FROM ...WHERE MIN(i) == 1 GROUP BY ... HAVING MIN(i) > 2 - MIN(i) in the WHERE clause is not allowed in the opposite to MIN(i) - in the HAVING clause. Due to possible nesting of select construct - the variable can contain 0 or 1 for each nest level. - */ - nesting_map allow_sum_func; - - Sql_cmd *m_sql_cmd; - - /* - Usually `expr` rule of yacc is quite reused but some commands better - not support subqueries which comes standard with this rule, like - KILL, HA_READ, CREATE/ALTER EVENT etc. Set this to a non-NULL - clause name to get an error. - */ - const char *clause_that_disallows_subselect; - bool selects_allow_into; - bool selects_allow_procedure; - /* - A special command "PARSE_VCOL_EXPR" is defined for the parser - to translate a defining expression of a virtual column into an - Item object. - The following flag is used to prevent other applications to use - this command. - */ - bool parse_vcol_expr; - - enum enum_duplicates duplicates; - enum enum_tx_isolation tx_isolation; - enum enum_ha_read_modes ha_read_mode; - union { - enum ha_rkey_function ha_rkey_mode; - enum xa_option_words xa_opt; - bool with_admin_option; // GRANT role - bool with_persistent_for_clause; // uses PERSISTENT FOR clause (in ANALYZE) - }; - enum enum_var_type option_type; - enum enum_drop_mode drop_mode; - - uint profile_query_id; - uint profile_options; - enum backup_stages backup_stage; - enum Foreign_key::fk_match_opt fk_match_option; - enum_fk_option fk_update_opt; - enum_fk_option fk_delete_opt; - uint slave_thd_opt, start_transaction_opt; - int nest_level; - /* - In LEX representing update which were transformed to multi-update - stores total number of tables. For LEX representing multi-delete - holds number of tables from which we will delete records. - */ - uint table_count; - uint8 describe; - bool analyze_stmt; /* TRUE<=> this is "ANALYZE $stmt" */ - bool explain_json; - /* - A flag that indicates what kinds of derived tables are present in the - query (0 if no derived tables, otherwise a combination of flags - DERIVED_SUBQUERY and DERIVED_VIEW). - */ - uint8 derived_tables; - uint8 context_analysis_only; - bool local_file; - bool check_exists; - bool autocommit; - bool verbose, no_write_to_binlog; - - enum enum_yes_no_unknown tx_chain, tx_release; - bool safe_to_cache_query; - bool ignore; - bool next_is_main; // use "main" SELECT_LEX for nrxt allocation; - bool next_is_down; // use "main" SELECT_LEX for nrxt allocation; - st_parsing_options parsing_options; - uint8 lex_options; // see OPTION_LEX_* - /* - In sql_cache we store SQL_CACHE flag as specified by user to be - able to restore SELECT statement from internal structures. - */ - enum e_sql_cache { SQL_CACHE_UNSPECIFIED, SQL_NO_CACHE, SQL_CACHE }; - e_sql_cache sql_cache; - - Alter_info alter_info; - /* - For CREATE TABLE statement last element of table list which is not - part of SELECT or LIKE part (i.e. either element for table we are - creating or last of tables referenced by foreign keys). - */ - TABLE_LIST *create_last_non_select_table; - Lex_prepared_stmt prepared_stmt; - sp_head *sphead; - sp_name *spname; - bool sp_lex_in_use; // Keep track on lex usage in SPs for error handling - - sp_pcontext *spcont; - - st_sp_chistics sp_chistics; - - Event_parse_data *event_parse_data; - - /* - field_list was created for view and should be removed before PS/SP - rexecuton - */ - bool empty_field_list_on_rset; - /* Characterstics of trigger being created */ - st_trg_chistics trg_chistics; - /* - List of all items (Item_trigger_field objects) representing fields in - old/new version of row in trigger. We use this list for checking whenever - all such fields are valid at trigger creation time and for binding these - fields to TABLE object at table open (altough for latter pointer to table - being opened is probably enough). - */ - SQL_I_List trg_table_fields; - - /* - stmt_definition_begin is intended to point to the next word after - DEFINER-clause in the following statements: - - CREATE TRIGGER (points to "TRIGGER"); - - CREATE PROCEDURE (points to "PROCEDURE"); - - CREATE FUNCTION (points to "FUNCTION" or "AGGREGATE"); - - CREATE EVENT (points to "EVENT") - - This pointer is required to add possibly omitted DEFINER-clause to the - DDL-statement before dumping it to the binlog. - - keyword_delayed_begin_offset is the offset to the beginning of the DELAYED - keyword in INSERT DELAYED statement. keyword_delayed_end_offset is the - offset to the character right after the DELAYED keyword. - */ - union { - const char *stmt_definition_begin; - uint keyword_delayed_begin_offset; - }; - - union { - const char *stmt_definition_end; - uint keyword_delayed_end_offset; - }; - - /** - Collects create options for KEY - */ - engine_option_value *option_list; - - /** - Helper pointer to the end of the list when parsing options for - LEX::create_info.option_list (for table) - LEX::last_field->option_list (for fields) - LEX::option_list (for indexes) - */ - engine_option_value *option_list_last; - - /** - During name resolution search only in the table list given by - Name_resolution_context::first_name_resolution_table and - Name_resolution_context::last_name_resolution_table - (see Item_field::fix_fields()). - */ - bool use_only_table_context; - - /* - Reference to a struct that contains information in various commands - to add/create/drop/change table spaces. - */ - st_alter_tablespace *alter_tablespace_info; - - bool escape_used; - bool default_used; /* using default() function */ - bool is_lex_started; /* If lex_start() did run. For debugging. */ - - /* - The set of those tables whose fields are referenced in all subqueries - of the query. - TODO: possibly this it is incorrect to have used tables in LEX because - with subquery, it is not clear what does the field mean. To fix this - we should aggregate used tables information for selected expressions - into the select_lex. - */ - table_map used_tables; - /** - Maximum number of rows and/or keys examined by the query, both read, - changed or written. This is the argument of LIMIT ROWS EXAMINED. - The limit is represented by two variables - the Item is needed because - in case of parameters we have to delay its evaluation until execution. - Once evaluated, its value is stored in examined_rows_limit_cnt. - */ - Item *limit_rows_examined; - ulonglong limit_rows_examined_cnt; - /** - Holds a set of domain_ids for deletion at FLUSH..DELETE_DOMAIN_ID - */ - DYNAMIC_ARRAY delete_gtid_domain; - static const ulong initial_gtid_domain_buffer_size= 16; - uint32 gtid_domain_static_buffer[initial_gtid_domain_buffer_size]; - - inline void set_limit_rows_examined() - { - if (limit_rows_examined) - limit_rows_examined_cnt= limit_rows_examined->val_uint(); - else - limit_rows_examined_cnt= ULONGLONG_MAX; - } - - - SQL_I_List save_group_list; - SQL_I_List save_order_list; - LEX_CSTRING *win_ref; - Window_frame *win_frame; - Window_frame_bound *frame_top_bound; - Window_frame_bound *frame_bottom_bound; - Window_spec *win_spec; - - /* System Versioning */ - vers_select_conds_t vers_conditions; - vers_select_conds_t period_conditions; - - inline void free_set_stmt_mem_root() - { - DBUG_ASSERT(!is_arena_for_set_stmt()); - if (mem_root_for_set_stmt) - { - free_root(mem_root_for_set_stmt, MYF(0)); - delete mem_root_for_set_stmt; - mem_root_for_set_stmt= 0; - } - } - - LEX(); - - virtual ~LEX() - { - free_set_stmt_mem_root(); - destroy_query_tables_list(); - plugin_unlock_list(NULL, (plugin_ref *)plugins.buffer, plugins.elements); - delete_dynamic(&plugins); - } - - virtual class Query_arena *query_arena() - { - DBUG_ASSERT(0); - return NULL; - } - - void start(THD *thd); - - inline bool is_ps_or_view_context_analysis() - { - return (context_analysis_only & - (CONTEXT_ANALYSIS_ONLY_PREPARE | - CONTEXT_ANALYSIS_ONLY_VCOL_EXPR | - CONTEXT_ANALYSIS_ONLY_VIEW)); - } - - inline bool is_view_context_analysis() - { - return (context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW); - } - - inline void uncacheable(uint8 cause) - { - safe_to_cache_query= 0; - - if (current_select) // initialisation SP variables has no SELECT - { - /* - There are no sense to mark select_lex and union fields of LEX, - but we should merk all subselects as uncacheable from current till - most upper - */ - SELECT_LEX *sl; - SELECT_LEX_UNIT *un; - for (sl= current_select, un= sl->master_unit(); - un && un != &unit; - sl= sl->outer_select(), un= (sl ? sl->master_unit() : NULL)) - { - sl->uncacheable|= cause; - un->uncacheable|= cause; - } - if (sl) - sl->uncacheable|= cause; - } - if (first_select_lex()) - first_select_lex()->uncacheable|= cause; - } - void set_trg_event_type_for_tables(); - - TABLE_LIST *unlink_first_table(bool *link_to_local); - void link_first_table_back(TABLE_LIST *first, bool link_to_local); - void first_lists_tables_same(); - void fix_first_select_number(); - - bool can_be_merged(); - bool can_use_merged(); - bool can_not_use_merged(); - bool only_view_structure(); - bool need_correct_ident(); - uint8 get_effective_with_check(TABLE_LIST *view); - /* - Is this update command where 'WHITH CHECK OPTION' clause is important - - SYNOPSIS - LEX::which_check_option_applicable() - - RETURN - TRUE have to take 'WHITH CHECK OPTION' clause into account - FALSE 'WHITH CHECK OPTION' clause do not need - */ - inline bool which_check_option_applicable() - { - switch (sql_command) { - case SQLCOM_UPDATE: - case SQLCOM_UPDATE_MULTI: - case SQLCOM_DELETE: - case SQLCOM_DELETE_MULTI: - case SQLCOM_INSERT: - case SQLCOM_INSERT_SELECT: - case SQLCOM_REPLACE: - case SQLCOM_REPLACE_SELECT: - case SQLCOM_LOAD: - return TRUE; - default: - return FALSE; - } - } - - void cleanup_after_one_table_open(); - - bool push_context(Name_resolution_context *context); - - Name_resolution_context *pop_context(); - - SELECT_LEX *select_stack_head() - { - if (likely(select_stack_top)) - return select_stack[select_stack_top - 1]; - return NULL; - } - - bool push_select(SELECT_LEX *select_lex) - { - DBUG_ENTER("LEX::push_select"); - DBUG_PRINT("info", ("Top Select was %p (%d) depth: %u pushed: %p (%d)", - select_stack_head(), - select_stack_top, - (select_stack_top ? - select_stack_head()->select_number : - 0), - select_lex, select_lex->select_number)); - if (unlikely(select_stack_top > MAX_SELECT_NESTING)) - { - my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0)); - DBUG_RETURN(TRUE); - } - if (push_context(&select_lex->context)) - DBUG_RETURN(TRUE); - select_stack[select_stack_top++]= select_lex; - current_select= select_lex; - DBUG_RETURN(FALSE); - } - - SELECT_LEX *pop_select() - { - DBUG_ENTER("LEX::pop_select"); - SELECT_LEX *select_lex; - if (likely(select_stack_top)) - select_lex= select_stack[--select_stack_top]; - else - select_lex= 0; - DBUG_PRINT("info", ("Top Select is %p (%d) depth: %u poped: %p (%d)", - select_stack_head(), - select_stack_top, - (select_stack_top ? - select_stack_head()->select_number : - 0), - select_lex, - (select_lex ? select_lex->select_number : 0))); - DBUG_ASSERT(select_lex); - - pop_context(); - - if (unlikely(!select_stack_top)) - { - current_select= &builtin_select; - DBUG_PRINT("info", ("Top Select is empty -> sel builtin: %p service: %u", - current_select, builtin_select.is_service_select)); - builtin_select.is_service_select= false; - } - else - current_select= select_stack[select_stack_top - 1]; - - DBUG_RETURN(select_lex); - } - - SELECT_LEX *current_select_or_default() - { - return current_select ? current_select : &builtin_select; - } - - bool copy_db_to(LEX_CSTRING *to); - - Name_resolution_context *current_context() - { - return context_stack.head(); - } - - /* - Restore the LEX and THD in case of a parse error. - */ - static void cleanup_lex_after_parse_error(THD *thd); - - void reset_n_backup_query_tables_list(Query_tables_list *backup); - void restore_backup_query_tables_list(Query_tables_list *backup); - - bool table_or_sp_used(); - - bool is_partition_management() const; - bool part_values_current(THD *thd); - bool part_values_history(THD *thd); - - /** - @brief check if the statement is a single-level join - @return result of the check - @retval TRUE The statement doesn't contain subqueries, unions and - stored procedure calls. - @retval FALSE There are subqueries, UNIONs or stored procedure calls. - */ - bool is_single_level_stmt() - { - /* - This check exploits the fact that the last added to all_select_list is - on its top. So select_lex (as the first added) will be at the tail - of the list. - */ - if (first_select_lex() == all_selects_list && !sroutines.records) - { - return TRUE; - } - return FALSE; - } - - bool save_prep_leaf_tables(); - - int print_explain(select_result_sink *output, uint8 explain_flags, - bool is_analyze, bool *printed_anything); - void restore_set_statement_var(); - - void init_last_field(Column_definition *field, const LEX_CSTRING *name, - const CHARSET_INFO *cs); - bool last_field_generated_always_as_row_start_or_end(Lex_ident *p, - const char *type, - uint flags); - bool last_field_generated_always_as_row_start(); - bool last_field_generated_always_as_row_end(); - bool set_bincmp(CHARSET_INFO *cs, bool bin); - - bool new_sp_instr_stmt(THD *, const LEX_CSTRING &prefix, - const LEX_CSTRING &suffix); - bool sp_proc_stmt_statement_finalize_buf(THD *, const LEX_CSTRING &qbuf); - bool sp_proc_stmt_statement_finalize(THD *, bool no_lookahead); - - sp_variable *sp_param_init(LEX_CSTRING *name); - bool sp_param_fill_definition(sp_variable *spvar, - const Lex_field_type_st &def); - bool sf_return_fill_definition(const Lex_field_type_st &def); - - int case_stmt_action_then(); - bool setup_select_in_parentheses(); - bool set_trigger_new_row(const LEX_CSTRING *name, Item *val); - bool set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2, - Item *val); - bool set_system_variable(enum_var_type var_type, sys_var *var, - const Lex_ident_sys_st *base_name, Item *val); - bool set_system_variable(enum_var_type var_type, - const Lex_ident_sys_st *name, Item *val); - bool set_system_variable(THD *thd, enum_var_type var_type, - const Lex_ident_sys_st *name1, - const Lex_ident_sys_st *name2, - Item *val); - bool set_default_system_variable(enum_var_type var_type, - const Lex_ident_sys_st *name, - Item *val); - bool set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val); - void set_stmt_init(); - sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name); - sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name1, - const LEX_CSTRING *name2); - sp_name *make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name); - sp_head *make_sp_head(THD *thd, const sp_name *name, const Sp_handler *sph, - enum_sp_aggregate_type agg_type); - sp_head *make_sp_head_no_recursive(THD *thd, const sp_name *name, - const Sp_handler *sph, - enum_sp_aggregate_type agg_type); - bool sp_body_finalize_routine(THD *); - bool sp_body_finalize_trigger(THD *); - bool sp_body_finalize_event(THD *); - bool sp_body_finalize_function(THD *); - bool sp_body_finalize_procedure(THD *); - bool sp_body_finalize_procedure_standalone(THD *, const sp_name *end_name); - sp_package *create_package_start(THD *thd, - enum_sql_command command, - const Sp_handler *sph, - const sp_name *name, - DDL_options_st options); - bool create_package_finalize(THD *thd, - const sp_name *name, - const sp_name *name2, - const char *body_start, - const char *body_end); - bool call_statement_start(THD *thd, sp_name *name); - bool call_statement_start(THD *thd, const Lex_ident_sys_st *name); - bool call_statement_start(THD *thd, const Lex_ident_sys_st *name1, - const Lex_ident_sys_st *name2); - sp_variable *find_variable(const LEX_CSTRING *name, - sp_pcontext **ctx, - const Sp_rcontext_handler **rh) const; - sp_variable *find_variable(const LEX_CSTRING *name, - const Sp_rcontext_handler **rh) const - { - sp_pcontext *not_used_ctx; - return find_variable(name, ¬_used_ctx, rh); - } - bool set_variable(const Lex_ident_sys_st *name, Item *item); - bool set_variable(const Lex_ident_sys_st *name1, - const Lex_ident_sys_st *name2, Item *item); - void sp_variable_declarations_init(THD *thd, int nvars); - bool sp_variable_declarations_finalize(THD *thd, int nvars, - const Column_definition *cdef, - Item *def); - bool sp_variable_declarations_set_default(THD *thd, int nvars, Item *def); - bool sp_variable_declarations_row_finalize(THD *thd, int nvars, - Row_definition_list *row, - Item *def); - bool sp_variable_declarations_with_ref_finalize(THD *thd, int nvars, - Qualified_column_ident *col, - Item *def); - bool sp_variable_declarations_rowtype_finalize(THD *thd, int nvars, - Qualified_column_ident *, - Item *def); - bool sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars, - uint offset, - Item *def); - bool sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars, - const LEX_CSTRING &db, - const LEX_CSTRING &table, - Item *def); - bool sp_variable_declarations_column_type_finalize(THD *thd, int nvars, - Qualified_column_ident *ref, - Item *def); - bool sp_variable_declarations_vartype_finalize(THD *thd, int nvars, - const LEX_CSTRING &name, - Item *def); - bool sp_variable_declarations_copy_type_finalize(THD *thd, int nvars, - const Column_definition &ref, - Row_definition_list *fields, - Item *def); - - LEX_USER *current_user_for_set_password(THD *thd); - bool sp_create_set_password_instr(THD *thd, - LEX_USER *user, - USER_AUTH *auth, - bool no_lookahead); - bool sp_create_set_password_instr(THD *thd, - USER_AUTH *auth, - bool no_lookahead) - { - LEX_USER *user; - return !(user= current_user_for_set_password(thd)) || - sp_create_set_password_instr(thd, user, auth, no_lookahead); - } - - bool sp_handler_declaration_init(THD *thd, int type); - bool sp_handler_declaration_finalize(THD *thd, int type); - - bool sp_declare_cursor(THD *thd, const LEX_CSTRING *name, - class sp_lex_cursor *cursor_stmt, - sp_pcontext *param_ctx, bool add_cpush_instr); - - bool sp_open_cursor(THD *thd, const LEX_CSTRING *name, - List *parameters); - Item_splocal *create_item_for_sp_var(const Lex_ident_cli_st *name, - sp_variable *spvar); - - Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_sys_st *name); - Item *create_item_qualified_asterisk(THD *thd, - const Lex_ident_sys_st *a, - const Lex_ident_sys_st *b); - Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_cli_st *cname) - { - Lex_ident_sys name(thd, cname); - if (name.is_null()) - return NULL; // EOM - return create_item_qualified_asterisk(thd, &name); - } - Item *create_item_qualified_asterisk(THD *thd, - const Lex_ident_cli_st *ca, - const Lex_ident_cli_st *cb) - { - Lex_ident_sys a(thd, ca), b(thd, cb); - if (a.is_null() || b.is_null()) - return NULL; // EOM - return create_item_qualified_asterisk(thd, &a, &b); - } - - Item *create_item_ident_field(THD *thd, - const Lex_ident_sys_st &db, - const Lex_ident_sys_st &table, - const Lex_ident_sys_st &name); - Item *create_item_ident_nosp(THD *thd, Lex_ident_sys_st *name) - { - return create_item_ident_field(thd, Lex_ident_sys(), Lex_ident_sys(), *name); - } - Item *create_item_ident_sp(THD *thd, Lex_ident_sys_st *name, - const char *start, const char *end); - Item *create_item_ident(THD *thd, Lex_ident_cli_st *cname) - { - Lex_ident_sys name(thd, cname); - if (name.is_null()) - return NULL; // EOM - return sphead ? - create_item_ident_sp(thd, &name, cname->pos(), cname->end()) : - create_item_ident_nosp(thd, &name); - } - /* - Create an Item corresponding to a qualified name: a.b - when the parser is out of an SP context. - @param THD - THD, for mem_root - @param a - the first name - @param b - the second name - @retval - a pointer to a created item, or NULL on error. - - Possible Item types that can be created: - - Item_trigger_field - - Item_field - - Item_ref - */ - Item *create_item_ident_nospvar(THD *thd, - const Lex_ident_sys_st *a, - const Lex_ident_sys_st *b); - /* - Create an Item corresponding to a ROW field valiable: var.field - @param THD - THD, for mem_root - @param rh [OUT] - the rcontext handler (local vs package variables) - @param var - the ROW variable name - @param field - the ROW variable field name - @param spvar - the variable that was previously found by name - using "var_name". - @param start - position in the query (for binary log) - @param end - end in the query (for binary log) - */ - Item_splocal *create_item_spvar_row_field(THD *thd, - const Sp_rcontext_handler *rh, - const Lex_ident_sys *var, - const Lex_ident_sys *field, - sp_variable *spvar, - const char *start, - const char *end); - /* - Create an item from its qualified name. - Depending on context, it can be either a ROW variable field, - or trigger, table field, table field reference. - See comments to create_item_spvar_row_field() and - create_item_ident_nospvar(). - @param thd - THD, for mem_root - @param a - the first name - @param b - the second name - @retval - NULL on error, or a pointer to a new Item. - */ - Item *create_item_ident(THD *thd, - const Lex_ident_cli_st *a, - const Lex_ident_cli_st *b); - /* - Create an item from its qualified name. - Depending on context, it can be a table field, a table field reference, - or a sequence NEXTVAL and CURRVAL. - @param thd - THD, for mem_root - @param a - the first name - @param b - the second name - @param c - the third name - @retval - NULL on error, or a pointer to a new Item. - */ - Item *create_item_ident(THD *thd, - const Lex_ident_sys_st *a, - const Lex_ident_sys_st *b, - const Lex_ident_sys_st *c); - - Item *create_item_ident(THD *thd, - const Lex_ident_cli_st *ca, - const Lex_ident_cli_st *cb, - const Lex_ident_cli_st *cc) - { - Lex_ident_sys b(thd, cb), c(thd, cc); - if (b.is_null() || c.is_null()) - return NULL; - if (ca->pos() == cb->pos()) // SELECT .t1.col1 - { - DBUG_ASSERT(ca->length == 0); - Lex_ident_sys none; - return create_item_ident(thd, &none, &b, &c); - } - Lex_ident_sys a(thd, ca); - return a.is_null() ? NULL : create_item_ident(thd, &a, &b, &c); - } - - /* - Create an item for "NEXT VALUE FOR sequence_name" - */ - Item *create_item_func_nextval(THD *thd, Table_ident *ident); - Item *create_item_func_nextval(THD *thd, const LEX_CSTRING *db, - const LEX_CSTRING *name); - /* - Create an item for "PREVIOUS VALUE FOR sequence_name" - */ - Item *create_item_func_lastval(THD *thd, Table_ident *ident); - Item *create_item_func_lastval(THD *thd, const LEX_CSTRING *db, - const LEX_CSTRING *name); - - /* - Create an item for "SETVAL(sequence_name, value [, is_used [, round]]) - */ - Item *create_item_func_setval(THD *thd, Table_ident *ident, longlong value, - ulonglong round, bool is_used); - - /* - Create an item for a name in LIMIT clause: LIMIT var - @param THD - THD, for mem_root - @param var_name - the variable name - @retval - a new Item corresponding to the SP variable, - or NULL on error - (non in SP, unknown variable, wrong data type). - */ - Item *create_item_limit(THD *thd, const Lex_ident_cli_st *var_name); - - /* - Create an item for a qualified name in LIMIT clause: LIMIT var.field - @param THD - THD, for mem_root - @param var_name - the variable name - @param field_name - the variable field name - @param start - start in the query (for binary log) - @param end - end in the query (for binary log) - @retval - a new Item corresponding to the SP variable, - or NULL on error - (non in SP, unknown variable, unknown ROW field, - wrong data type). - */ - Item *create_item_limit(THD *thd, - const Lex_ident_cli_st *var_name, - const Lex_ident_cli_st *field_name); - - Item *create_item_query_expression(THD *thd, st_select_lex_unit *unit); - - Item *make_item_func_replace(THD *thd, Item *org, Item *find, Item *replace); - Item *make_item_func_substr(THD *thd, Item *a, Item *b, Item *c); - Item *make_item_func_substr(THD *thd, Item *a, Item *b); - Item *make_item_func_call_generic(THD *thd, Lex_ident_cli_st *db, - Lex_ident_cli_st *name, List *args); - Item *make_item_func_call_native_or_parse_error(THD *thd, - Lex_ident_cli_st &name, - List *args); - my_var *create_outvar(THD *thd, const LEX_CSTRING *name); - - /* - Create a my_var instance for a ROW field variable that was used - as an OUT SP parameter: CALL p1(var.field); - @param THD - THD, for mem_root - @param var_name - the variable name - @param field_name - the variable field name - */ - my_var *create_outvar(THD *thd, - const LEX_CSTRING *var_name, - const LEX_CSTRING *field_name); - - bool is_trigger_new_or_old_reference(const LEX_CSTRING *name) const; - - Item *create_and_link_Item_trigger_field(THD *thd, const LEX_CSTRING *name, - bool new_row); - // For syntax with colon, e.g. :NEW.a or :OLD.a - Item *make_item_colon_ident_ident(THD *thd, - const Lex_ident_cli_st *a, - const Lex_ident_cli_st *b); - // PLSQL: cursor%ISOPEN etc - Item *make_item_plsql_cursor_attr(THD *thd, const LEX_CSTRING *name, - plsql_cursor_attr_t attr); - - // For "SELECT @@var", "SELECT @@var.field" - Item *make_item_sysvar(THD *thd, - enum_var_type type, - const LEX_CSTRING *name) - { - return make_item_sysvar(thd, type, name, &null_clex_str); - } - Item *make_item_sysvar(THD *thd, - enum_var_type type, - const LEX_CSTRING *name, - const LEX_CSTRING *component); - void sp_block_init(THD *thd, const LEX_CSTRING *label); - void sp_block_init(THD *thd) - { - // Unlabeled blocks get an empty label - sp_block_init(thd, &empty_clex_str); - } - bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock) - { - class sp_label *tmp; - return sp_block_finalize(thd, spblock, &tmp); - } - bool sp_block_finalize(THD *thd) - { - return sp_block_finalize(thd, Lex_spblock()); - } - bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock, - const LEX_CSTRING *end_label); - bool sp_block_finalize(THD *thd, const LEX_CSTRING *end_label) - { - return sp_block_finalize(thd, Lex_spblock(), end_label); - } - bool sp_declarations_join(Lex_spblock_st *res, - const Lex_spblock_st b1, - const Lex_spblock_st b2) const - { - if ((b2.vars || b2.conds) && (b1.curs || b1.hndlrs)) - { - my_error(ER_SP_VARCOND_AFTER_CURSHNDLR, MYF(0)); - return true; - } - if (b2.curs && b1.hndlrs) - { - my_error(ER_SP_CURSOR_AFTER_HANDLER, MYF(0)); - return true; - } - res->join(b1, b2); - return false; - } - bool sp_block_with_exceptions_finalize_declarations(THD *thd); - bool sp_block_with_exceptions_finalize_executable_section(THD *thd, - uint executable_section_ip); - bool sp_block_with_exceptions_finalize_exceptions(THD *thd, - uint executable_section_ip, - uint exception_count); - bool sp_block_with_exceptions_add_empty(THD *thd); - bool sp_exit_statement(THD *thd, Item *when); - bool sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item); - bool sp_leave_statement(THD *thd, const LEX_CSTRING *label_name); - bool sp_goto_statement(THD *thd, const LEX_CSTRING *label_name); - - bool sp_continue_statement(THD *thd); - bool sp_continue_statement(THD *thd, const LEX_CSTRING *label_name); - bool sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name); - - bool maybe_start_compound_statement(THD *thd); - bool sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name); - bool sp_push_loop_empty_label(THD *thd); - bool sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name); - void sp_pop_loop_empty_label(THD *thd); - bool sp_while_loop_expression(THD *thd, Item *expr); - bool sp_while_loop_finalize(THD *thd); - bool sp_if_after_statements(THD *thd); - bool sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name); - - Item_param *add_placeholder(THD *thd, const LEX_CSTRING *name, - const char *start, const char *end); - - /* Integer range FOR LOOP methods */ - sp_variable *sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name, - Item *value); - sp_variable *sp_add_for_loop_target_bound(THD *thd, Item *value) - { - LEX_CSTRING name= { STRING_WITH_LEN("[target_bound]") }; - return sp_add_for_loop_variable(thd, &name, value); - } - bool sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop, - const LEX_CSTRING *index, - const Lex_for_loop_bounds_st &bounds); - bool sp_for_loop_intrange_condition_test(THD *thd, const Lex_for_loop_st &loop); - bool sp_for_loop_intrange_finalize(THD *thd, const Lex_for_loop_st &loop); - - /* Cursor FOR LOOP methods */ - bool sp_for_loop_cursor_declarations(THD *thd, Lex_for_loop_st *loop, - const LEX_CSTRING *index, - const Lex_for_loop_bounds_st &bounds); - sp_variable *sp_add_for_loop_cursor_variable(THD *thd, - const LEX_CSTRING *name, - const class sp_pcursor *cur, - uint coffset, - sp_assignment_lex *param_lex, - Item_args *parameters); - bool sp_for_loop_implicit_cursor_statement(THD *thd, - Lex_for_loop_bounds_st *bounds, - sp_lex_cursor *cur); - bool sp_for_loop_cursor_condition_test(THD *thd, const Lex_for_loop_st &loop); - bool sp_for_loop_cursor_finalize(THD *thd, const Lex_for_loop_st &); - - /* Generic FOR LOOP methods*/ - - /* - Generate FOR loop declarations and - initialize "loop" from "index" and "bounds". - - @param [IN] thd - current THD, for mem_root and error reporting - @param [OUT] loop - the loop generated SP variables are stored here, - together with additional loop characteristics. - @param [IN] index - the loop index variable name - @param [IN] bounds - the loop bounds (in sp_assignment_lex format) - and additional loop characteristics, - as created by the sp_for_loop_bounds rule. - @retval true - on error - @retval false - on success - - This methods adds declarations: - - An explicit integer or cursor%ROWTYPE "index" variable - - An implicit integer upper bound variable, in case of integer range loops - - A CURSOR, in case of an implicit CURSOR loops - The generated variables are stored into "loop". - Additional loop characteristics are copied from "bounds" to "loop". - */ - bool sp_for_loop_declarations(THD *thd, Lex_for_loop_st *loop, - const LEX_CSTRING *index, - const Lex_for_loop_bounds_st &bounds) - { - return bounds.is_for_loop_cursor() ? - sp_for_loop_cursor_declarations(thd, loop, index, bounds) : - sp_for_loop_intrange_declarations(thd, loop, index, bounds); - } - - /* - Generate a conditional jump instruction to leave the loop, - using a proper condition depending on the loop type: - - Item_func_le -- integer range loops - - Item_func_ge -- integer range reverse loops - - Item_func_cursor_found -- cursor loops - */ - bool sp_for_loop_condition_test(THD *thd, const Lex_for_loop_st &loop) - { - return loop.is_for_loop_cursor() ? - sp_for_loop_cursor_condition_test(thd, loop) : - sp_for_loop_intrange_condition_test(thd, loop); - } - - /* - Generate "increment" instructions followed by a jump to the - condition test in the beginnig of the loop. - "Increment" depends on the loop type and can be: - - index:= index + 1; -- integer range loops - - index:= index - 1; -- integer range reverse loops - - FETCH cursor INTO index; -- cursor loops - */ - bool sp_for_loop_finalize(THD *thd, const Lex_for_loop_st &loop) - { - return loop.is_for_loop_cursor() ? - sp_for_loop_cursor_finalize(thd, loop) : - sp_for_loop_intrange_finalize(thd, loop); - } - bool sp_for_loop_outer_block_finalize(THD *thd, const Lex_for_loop_st &loop); - - /* - Make an Item when an identifier is found in the FOR loop bounds: - FOR rec IN cursor - FOR rec IN var1 .. var2 - FOR rec IN row1.field1 .. xxx - */ - Item *create_item_for_loop_bound(THD *thd, - const LEX_CSTRING *a, - const LEX_CSTRING *b, - const LEX_CSTRING *c); - /* End of FOR LOOP methods */ - - bool add_signal_statement(THD *thd, const class sp_condition_value *value); - bool add_resignal_statement(THD *thd, const class sp_condition_value *value); - - // Check if "KEY IF NOT EXISTS name" used outside of ALTER context - bool check_add_key(DDL_options_st ddl) - { - if (ddl.if_not_exists() && sql_command != SQLCOM_ALTER_TABLE) - { - parse_error(); - return true; - } - return false; - } - // Add a key as a part of CREATE TABLE or ALTER TABLE - bool add_key(Key::Keytype key_type, const LEX_CSTRING *key_name, - ha_key_alg algorithm, DDL_options_st ddl) - { - if (check_add_key(ddl) || - !(last_key= new Key(key_type, key_name, algorithm, false, ddl))) - return true; - alter_info.key_list.push_back(last_key); - return false; - } - // Add a key for a CREATE INDEX statement - bool add_create_index(Key::Keytype key_type, const LEX_CSTRING *key_name, - ha_key_alg algorithm, DDL_options_st ddl) - { - if (check_create_options(ddl) || - !(last_key= new Key(key_type, key_name, algorithm, false, ddl))) - return true; - alter_info.key_list.push_back(last_key); - return false; - } - bool add_create_index_prepare(Table_ident *table) - { - sql_command= SQLCOM_CREATE_INDEX; - if (!current_select->add_table_to_list(thd, table, NULL, - TL_OPTION_UPDATING, - TL_READ_NO_INSERT, - MDL_SHARED_UPGRADABLE)) - return true; - alter_info.reset(); - alter_info.flags= ALTER_ADD_INDEX; - option_list= NULL; - return false; - } - /* - Add an UNIQUE or PRIMARY key which is a part of a column definition: - CREATE TABLE t1 (a INT PRIMARY KEY); - */ - void add_key_to_list(LEX_CSTRING *field_name, - enum Key::Keytype type, bool check_exists); - // Add a constraint as a part of CREATE TABLE or ALTER TABLE - bool add_constraint(const LEX_CSTRING &name, Virtual_column_info *constr, - bool if_not_exists) - { - constr->name= name; - constr->flags= if_not_exists ? VCOL_CHECK_CONSTRAINT_IF_NOT_EXISTS : 0; - alter_info.check_constraint_list.push_back(constr); - return false; - } - bool add_alter_list(LEX_CSTRING par_name, Virtual_column_info *expr, - bool par_exists); - bool add_alter_list(LEX_CSTRING name, LEX_CSTRING new_name, bool exists); - void set_command(enum_sql_command command, - DDL_options_st options) - { - sql_command= command; - create_info.set(options); - } - void set_command(enum_sql_command command, - uint scope, - DDL_options_st options) - { - set_command(command, options); - create_info.options|= scope; // HA_LEX_CREATE_TMP_TABLE or 0 - } - bool check_create_options(DDL_options_st options) - { - if (options.or_replace() && options.if_not_exists()) - { - my_error(ER_WRONG_USAGE, MYF(0), "OR REPLACE", "IF NOT EXISTS"); - return true; - } - return false; - } - bool set_create_options_with_check(DDL_options_st options) - { - create_info.set(options); - return check_create_options(create_info); - } - bool add_create_options_with_check(DDL_options_st options) - { - create_info.add(options); - return check_create_options(create_info); - } - bool sp_add_cfetch(THD *thd, const LEX_CSTRING *name); - bool sp_add_agg_cfetch(); - - bool set_command_with_check(enum_sql_command command, - uint scope, - DDL_options_st options) - { - set_command(command, scope, options); - return check_create_options(options); - } - bool set_command_with_check(enum_sql_command command, DDL_options_st options) - { - set_command(command, options); - return check_create_options(options); - } - /* - DROP shares lex->create_info to store TEMPORARY and IF EXISTS options - to save on extra initialization in lex_start(). - Add some wrappers, to avoid direct use of lex->create_info in the - caller code processing DROP statements (which might look confusing). - */ - bool tmp_table() const { return create_info.tmp_table(); } - bool if_exists() const { return create_info.if_exists(); } - - /* - Run specified phases for derived tables/views in the given list - - @param table_list - list of derived tables/view to handle - @param phase - phases to process tables/views through - - @details - This method runs phases specified by the 'phases' on derived - tables/views found in the 'table_list' with help of the - TABLE_LIST::handle_derived function. - 'this' is passed as an argument to the TABLE_LIST::handle_derived. - - @return false - ok - @return true - error - */ - bool handle_list_of_derived(TABLE_LIST *table_list, uint phases) - { - for (TABLE_LIST *tl= table_list; tl; tl= tl->next_local) - { - if (tl->is_view_or_derived() && tl->handle_derived(this, phases)) - return true; - } - return false; - } - - SELECT_LEX *exclude_last_select(); - SELECT_LEX *exclude_not_first_select(SELECT_LEX *exclude); - void check_automatic_up(enum sub_select_type type); - bool create_or_alter_view_finalize(THD *thd, Table_ident *table_ident); - bool add_alter_view(THD *thd, uint16 algorithm, enum_view_suid suid, - Table_ident *table_ident); - bool add_create_view(THD *thd, DDL_options_st ddl, - uint16 algorithm, enum_view_suid suid, - Table_ident *table_ident); - bool add_grant_command(THD *thd, const List &columns); - - bool stmt_grant_table(THD *thd, - Grant_privilege *grant, - const Lex_grant_object_name &ident, - privilege_t grant_option); - - bool stmt_revoke_table(THD *thd, - Grant_privilege *grant, - const Lex_grant_object_name &ident); - - bool stmt_grant_sp(THD *thd, - Grant_privilege *grant, - const Lex_grant_object_name &ident, - const Sp_handler &sph, - privilege_t grant_option); - - bool stmt_revoke_sp(THD *thd, - Grant_privilege *grant, - const Lex_grant_object_name &ident, - const Sp_handler &sph); - - bool stmt_grant_proxy(THD *thd, LEX_USER *user, privilege_t grant_option); - bool stmt_revoke_proxy(THD *thd, LEX_USER *user); - - Vers_parse_info &vers_get_info() - { - return create_info.vers_info; - } - - int add_period(Lex_ident name, Lex_ident_sys_st start, Lex_ident_sys_st end) - { - Table_period_info &info= create_info.period_info; - - if (check_exists && info.name.streq(name)) - return 0; - - if (info.is_set()) - { - my_error(ER_MORE_THAN_ONE_PERIOD, MYF(0)); - return 1; - } - info.set_period(start, end); - info.name= name; - - info.constr= new Virtual_column_info(); - info.constr->expr= lt_creator.create(thd, - create_item_ident_nosp(thd, &start), - create_item_ident_nosp(thd, &end)); - add_constraint(null_clex_str, info.constr, false); - return 0; - } - - sp_package *get_sp_package() const; - - /** - Check if the select is a simple select (not an union). - @retval - 0 ok - @retval - 1 error ; In this case the error messege is sent to the client - */ - bool check_simple_select(const LEX_CSTRING *option) - { - if (current_select != &builtin_select) - { - char command[80]; - strmake(command, option->str, MY_MIN(option->length, sizeof(command)-1)); - my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command); - return true; - } - return false; - } - - void tvc_start() - { - field_list.empty(); - many_values.empty(); - insert_list= 0; - } - - SELECT_LEX_UNIT *alloc_unit(); - SELECT_LEX *alloc_select(bool is_select); - SELECT_LEX_UNIT *create_unit(SELECT_LEX*); - SELECT_LEX *wrap_unit_into_derived(SELECT_LEX_UNIT *unit); - SELECT_LEX *wrap_select_chain_into_derived(SELECT_LEX *sel); - void init_select() - { - current_select->init_select(); - wild= 0; - exchange= 0; - } - bool main_select_push(bool service= false); - bool insert_select_hack(SELECT_LEX *sel); - SELECT_LEX *create_priority_nest(SELECT_LEX *first_in_nest); - - bool set_main_unit(st_select_lex_unit *u) - { - unit.options= u->options; - unit.uncacheable= u->uncacheable; - unit.register_select_chain(u->first_select()); - unit.first_select()->options|= builtin_select.options; - unit.fake_select_lex= u->fake_select_lex; - unit.union_distinct= u->union_distinct; - unit.set_with_clause(u->with_clause); - builtin_select.exclude_from_global(); - return false; - } - bool check_main_unit_semantics(); - - SELECT_LEX_UNIT *parsed_select_expr_start(SELECT_LEX *s1, SELECT_LEX *s2, - enum sub_select_type unit_type, - bool distinct); - SELECT_LEX_UNIT *parsed_select_expr_cont(SELECT_LEX_UNIT *unit, - SELECT_LEX *s2, - enum sub_select_type unit_type, - bool distinct, bool oracle); - bool parsed_multi_operand_query_expression_body(SELECT_LEX_UNIT *unit); - SELECT_LEX_UNIT *add_tail_to_query_expression_body(SELECT_LEX_UNIT *unit, - Lex_order_limit_lock *l); - SELECT_LEX_UNIT * - add_tail_to_query_expression_body_ext_parens(SELECT_LEX_UNIT *unit, - Lex_order_limit_lock *l); - SELECT_LEX_UNIT *parsed_body_ext_parens_primary(SELECT_LEX_UNIT *unit, - SELECT_LEX *primary, - enum sub_select_type unit_type, - bool distinct); - SELECT_LEX_UNIT * - add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit, - SELECT_LEX *sel, - enum sub_select_type unit_type, - bool distinct, - bool oracle); - SELECT_LEX_UNIT * - add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit, - SELECT_LEX *sel, - enum sub_select_type unit_type, - bool distinct); - SELECT_LEX_UNIT * - add_primary_to_query_expression_body_ext_parens( - SELECT_LEX_UNIT *unit, - SELECT_LEX *sel, - enum sub_select_type unit_type, - bool distinct); - SELECT_LEX *parsed_subselect(SELECT_LEX_UNIT *unit); - bool parsed_insert_select(SELECT_LEX *firs_select); - bool parsed_TVC_start(); - SELECT_LEX *parsed_TVC_end(); - TABLE_LIST *parsed_derived_table(SELECT_LEX_UNIT *unit, - int for_system_time, - LEX_CSTRING *alias); - bool parsed_create_view(SELECT_LEX_UNIT *unit, int check); - bool select_finalize(st_select_lex_unit *expr); - bool select_finalize(st_select_lex_unit *expr, Lex_select_lock l); - void relink_hack(st_select_lex *select_lex); - - bool stmt_install_plugin(const DDL_options_st &opt, - const Lex_ident_sys_st &name, - const LEX_CSTRING &soname); - void stmt_install_plugin(const LEX_CSTRING &soname); - - bool stmt_uninstall_plugin_by_name(const DDL_options_st &opt, - const Lex_ident_sys_st &name); - bool stmt_uninstall_plugin_by_soname(const DDL_options_st &opt, - const LEX_CSTRING &soname); - bool stmt_prepare_validate(const char *stmt_type); - bool stmt_prepare(const Lex_ident_sys_st &ident, Item *code); - bool stmt_execute(const Lex_ident_sys_st &ident, List *params); - bool stmt_execute_immediate(Item *code, List *params); - void stmt_deallocate_prepare(const Lex_ident_sys_st &ident); - - bool stmt_alter_table_exchange_partition(Table_ident *table); - - void stmt_purge_to(const LEX_CSTRING &to); - bool stmt_purge_before(Item *item); - - SELECT_LEX *returning() - { return &builtin_select; } - bool has_returning() - { return !builtin_select.item_list.is_empty(); } - -private: - bool stmt_create_routine_start(const DDL_options_st &options) - { - create_info.set(options); - return main_select_push() || check_create_options(options); - } -public: - bool stmt_create_function_start(const DDL_options_st &options) - { - sql_command= SQLCOM_CREATE_SPFUNCTION; - return stmt_create_routine_start(options); - } - bool stmt_create_procedure_start(const DDL_options_st &options) - { - sql_command= SQLCOM_CREATE_PROCEDURE; - return stmt_create_routine_start(options); - } - void stmt_create_routine_finalize() - { - pop_select(); // main select - } - - bool stmt_create_stored_function_start(const DDL_options_st &options, - enum_sp_aggregate_type, - const sp_name *name); - bool stmt_create_stored_function_finalize_standalone(const sp_name *end_name); - - bool stmt_create_udf_function(const DDL_options_st &options, - enum_sp_aggregate_type agg_type, - const Lex_ident_sys_st &name, - Item_result return_type, - const LEX_CSTRING &soname); - - bool stmt_drop_function(const DDL_options_st &options, - const Lex_ident_sys_st &db, - const Lex_ident_sys_st &name); - - bool stmt_drop_function(const DDL_options_st &options, - const Lex_ident_sys_st &name); - - bool stmt_drop_procedure(const DDL_options_st &options, - sp_name *name); - - bool stmt_alter_function_start(sp_name *name); - bool stmt_alter_procedure_start(sp_name *name); - - sp_condition_value *stmt_signal_value(const Lex_ident_sys_st &ident); - - Spvar_definition *row_field_name(THD *thd, const Lex_ident_sys_st &name); - - bool set_field_type_udt(Lex_field_type_st *type, - const LEX_CSTRING &name, - const Lex_length_and_dec_st &attr); - bool set_cast_type_udt(Lex_cast_type_st *type, - const LEX_CSTRING &name); - - bool map_data_type(const Lex_ident_sys_st &schema, - Lex_field_type_st *type) const; - - void mark_first_table_as_inserting(); - - bool fields_are_impossible() - { - // no select or it is last select with no tables (service select) - return !select_stack_head() || - (select_stack_top == 1 && - select_stack[0]->is_service_select); - } - - bool add_table_foreign_key(const LEX_CSTRING *name, - const LEX_CSTRING *constraint_name, - Table_ident *table_name, - DDL_options ddl_options); - bool add_column_foreign_key(const LEX_CSTRING *name, - const LEX_CSTRING *constraint_name, - Table_ident *ref_table_name, - DDL_options ddl_options); -}; - - -/** - Set_signal_information is a container used in the parsed tree to represent - the collection of assignments to condition items in the SIGNAL and RESIGNAL - statements. -*/ -class Set_signal_information -{ -public: - /** Empty default constructor, use clear() */ - Set_signal_information() {} - - /** Copy constructor. */ - Set_signal_information(const Set_signal_information& set); - - /** Destructor. */ - ~Set_signal_information() - {} - - /** Clear all items. */ - void clear(); - - /** - For each condition item assignment, m_item[] contains the parsed tree - that represents the expression assigned, if any. - m_item[] is an array indexed by Diag_condition_item_name. - */ - Item *m_item[LAST_DIAG_SET_PROPERTY+1]; -}; - - -/** - The internal state of the syntax parser. - This object is only available during parsing, - and is private to the syntax parser implementation (sql_yacc.yy). -*/ -class Yacc_state -{ -public: - Yacc_state() : yacc_yyss(NULL), yacc_yyvs(NULL) { reset(); } - - void reset() - { - if (yacc_yyss != NULL) { - my_free(yacc_yyss); - yacc_yyss = NULL; - } - if (yacc_yyvs != NULL) { - my_free(yacc_yyvs); - yacc_yyvs = NULL; - } - m_set_signal_info.clear(); - m_lock_type= TL_READ_DEFAULT; - m_mdl_type= MDL_SHARED_READ; - } - - ~Yacc_state(); - - /** - Reset part of the state which needs resetting before parsing - substatement. - */ - void reset_before_substatement() - { - m_lock_type= TL_READ_DEFAULT; - m_mdl_type= MDL_SHARED_READ; - } - - /** - Bison internal state stack, yyss, when dynamically allocated using - my_yyoverflow(). - */ - uchar *yacc_yyss; - - /** - Bison internal semantic value stack, yyvs, when dynamically allocated using - my_yyoverflow(). - */ - uchar *yacc_yyvs; - - /** - Fragments of parsed tree, - used during the parsing of SIGNAL and RESIGNAL. - */ - Set_signal_information m_set_signal_info; - - /** - Type of lock to be used for tables being added to the statement's - table list in table_factor, table_alias_ref, single_multi and - table_wild_one rules. - Statements which use these rules but require lock type different - from one specified by this member have to override it by using - st_select_lex::set_lock_for_tables() method. - - The default value of this member is TL_READ_DEFAULT. The only two - cases in which we change it are: - - When parsing SELECT HIGH_PRIORITY. - - Rule for DELETE. In which we use this member to pass information - about type of lock from delete to single_multi part of rule. - - We should try to avoid introducing new use cases as we would like - to get rid of this member eventually. - */ - thr_lock_type m_lock_type; - - /** - The type of requested metadata lock for tables added to - the statement table list. - */ - enum_mdl_type m_mdl_type; - - /* - TODO: move more attributes from the LEX structure here. - */ -}; - -/** - Internal state of the parser. - The complete state consist of: - - state data used during lexical parsing, - - state data used during syntactic parsing. -*/ -class Parser_state -{ -public: - Parser_state() - : m_yacc() - {} - - /** - Object initializer. Must be called before usage. - - @retval FALSE OK - @retval TRUE Error - */ - bool init(THD *thd, char *buff, size_t length) - { - return m_lip.init(thd, buff, length); - } - - ~Parser_state() - {} - - Lex_input_stream m_lip; - Yacc_state m_yacc; - - /** - Current performance digest instrumentation. - */ - PSI_digest_locker* m_digest_psi; - - void reset(char *found_semicolon, unsigned int length) - { - m_lip.reset(found_semicolon, length); - m_yacc.reset(); - } -}; - - -extern sql_digest_state * -digest_add_token(sql_digest_state *state, uint token, LEX_YYSTYPE yylval); - -extern sql_digest_state * -digest_reduce_token(sql_digest_state *state, uint token_left, uint token_right); - -struct st_lex_local: public LEX, public Sql_alloc -{ -}; - - -/** - An st_lex_local extension with automatic initialization for SP purposes. - Used to parse sub-expressions and SP sub-statements. - - This class is reused for: - 1. sp_head::reset_lex() based constructs - - SP variable assignments (e.g. SET x=10;) - - FOR loop conditions and index variable increments - - Cursor statements - - SP statements - - SP function RETURN statements - - CASE statements - - REPEAT..UNTIL expressions - - WHILE expressions - - EXIT..WHEN and CONTINUE..WHEN statements - 2. sp_assignment_lex based constructs: - - CURSOR parameter assignments -*/ -class sp_lex_local: public st_lex_local -{ -public: - sp_lex_local(THD *thd, const LEX *oldlex) - { - /* Reset most stuff. */ - start(thd); - /* Keep the parent SP stuff */ - sphead= oldlex->sphead; - spcont= oldlex->spcont; - /* Keep the parent trigger stuff too */ - trg_chistics= oldlex->trg_chistics; - trg_table_fields.empty(); - sp_lex_in_use= false; - } -}; - - -class sp_lex_set_var: public sp_lex_local -{ -public: - sp_lex_set_var(THD *thd, const LEX *oldlex) - :sp_lex_local(thd, oldlex) - { - // Set new LEX as if we at start of set rule - init_select(); - sql_command= SQLCOM_SET_OPTION; - var_list.empty(); - autocommit= 0; - option_type= oldlex->option_type; // Inherit from the outer lex - } -}; - - -class sp_expr_lex: public sp_lex_local -{ - Item *m_item; // The expression -public: - sp_expr_lex(THD *thd, LEX *oldlex) - :sp_lex_local(thd, oldlex), - m_item(NULL) - { } - void set_item(Item *item) - { - m_item= item; - } - Item *get_item() const - { - return m_item; - } - bool sp_continue_when_statement(THD *thd); - bool sp_continue_when_statement(THD *thd, const LEX_CSTRING *label_name); - int case_stmt_action_expr(); - int case_stmt_action_when(bool simple); - bool sp_while_loop_expression(THD *thd) - { - return LEX::sp_while_loop_expression(thd, get_item()); - } - bool sp_repeat_loop_finalize(THD *thd); - bool sp_if_expr(THD *thd); -}; - - -/** - An assignment specific LEX, which additionally has an Item (an expression) - and an associated with the Item free_list, which is usually freed - after the expression is calculated. - - Note, consider changing some of sp_lex_local to sp_assignment_lex, - as the latter allows to use a simpler grammar in sql_yacc.yy (IMO). - - If the expression is simple (e.g. does not have function calls), - then m_item and m_free_list point to the same Item. - - If the expressions is complex (e.g. have function calls), - then m_item points to the leftmost Item, while m_free_list points - to the rightmost item. - For example: - f1(COALESCE(f2(10), f2(20))) - - m_item points to Item_func_sp for f1 (the leftmost Item) - - m_free_list points to Item_int for 20 (the rightmost Item) - - Note, we could avoid storing m_item at all, as we can always reach - the leftmost item from the rightmost item by iterating through m_free_list. - But with a separate m_item the code should be faster. -*/ -class sp_assignment_lex: public sp_lex_local -{ - Item *m_item; // The expression - Item *m_free_list; // The associated free_list (sub-expressions) -public: - sp_assignment_lex(THD *thd, LEX *oldlex) - :sp_lex_local(thd, oldlex), - m_item(NULL), - m_free_list(NULL) - { } - void set_item_and_free_list(Item *item, Item *free_list) - { - m_item= item; - m_free_list= free_list; - } - Item *get_item() const - { - return m_item; - } - Item *get_free_list() const - { - return m_free_list; - } -}; - - -extern void lex_init(void); -extern void lex_free(void); -extern void lex_start(THD *thd); -extern void lex_end(LEX *lex); -extern void lex_end_stage1(LEX *lex); -extern void lex_end_stage2(LEX *lex); -void end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex); -int init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex); -extern int MYSQLlex(union YYSTYPE *yylval, THD *thd); -extern int ORAlex(union YYSTYPE *yylval, THD *thd); - -extern void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length = 0); - -extern bool is_lex_native_function(const LEX_CSTRING *name); -extern bool is_native_function(THD *thd, const LEX_CSTRING *name); -extern bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name); - -/** - @} (End of group Semantic_Analysis) -*/ - -void my_missing_function_error(const LEX_CSTRING &token, const char *name); -bool is_keyword(const char *name, uint len); -int set_statement_var_if_exists(THD *thd, const char *var_name, - size_t var_name_length, ulonglong value); - -Virtual_column_info *add_virtual_expression(THD *thd, Item *expr); -Item* handle_sql2003_note184_exception(THD *thd, Item* left, bool equal, - Item *expr); - -bool sp_create_assignment_lex(THD *thd, const char *pos); -bool sp_create_assignment_instr(THD *thd, bool no_lookahead, - bool need_set_keyword= true); - -void mark_or_conds_to_avoid_pushdown(Item *cond); - -#endif /* MYSQL_SERVER */ -#endif /* SQL_LEX_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_lifo_buffer.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_lifo_buffer.h deleted file mode 100644 index 0347030..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_lifo_buffer.h +++ /dev/null @@ -1,359 +0,0 @@ -/* - Copyright (c) 2010, 2011, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @defgroup Bi-directional LIFO buffers used by DS-MRR implementation - @{ -*/ - -class Forward_lifo_buffer; -class Backward_lifo_buffer; - - -/* - A base class for in-memory buffer used by DS-MRR implementation. Common - properties: - - The buffer is last-in-first-out, i.e. elements that are written last are - read first. - - The buffer contains fixed-size elements. The elements are either atomic - byte sequences or pairs of them. - - The buffer resides in the memory provided by the user. It is possible to - = dynamically (ie. between write operations) add ajacent memory space to - the buffer - = dynamically remove unused space from the buffer. - The intent of this is to allow to have two buffers on adjacent memory - space, one is being read from (and so its space shrinks), while the other - is being written to (and so it needs more and more space). - - There are two concrete classes, Forward_lifo_buffer and Backward_lifo_buffer. -*/ - -class Lifo_buffer -{ -protected: - size_t size1; - size_t size2; - -public: - /** - write() will put into buffer size1 bytes pointed by write_ptr1. If - size2!=0, then they will be accompanied by size2 bytes pointed by - write_ptr2. - */ - uchar *write_ptr1; - uchar *write_ptr2; - - /** - read() will do reading by storing pointers to read data into read_ptr1 or - into (read_ptr1, read_ptr2), depending on whether the buffer was set to - store single objects or pairs. - */ - uchar *read_ptr1; - uchar *read_ptr2; - -protected: - uchar *start; /**< points to start of buffer space */ - uchar *end; /**< points to just beyond the end of buffer space */ -public: - - enum enum_direction { - BACKWARD=-1, /**< buffer is filled/read from bigger to smaller memory addresses */ - FORWARD=1 /**< buffer is filled/read from smaller to bigger memory addresses */ - }; - - virtual enum_direction type() = 0; - - /* Buffer space control functions */ - - /** Let the buffer store data in the given space. */ - void set_buffer_space(uchar *start_arg, uchar *end_arg) - { - start= start_arg; - end= end_arg; - if (end != start) - TRASH_ALLOC(start, size_t(end - start)); - reset(); - } - - /** - Specify where write() should get the source data from, as well as source - data size. - */ - void setup_writing(size_t len1, size_t len2) - { - size1= len1; - size2= len2; - } - - /** - Specify where read() should store pointers to read data, as well as read - data size. The sizes must match those passed to setup_writing(). - */ - void setup_reading(size_t len1, size_t len2) - { - DBUG_ASSERT(len1 == size1); - DBUG_ASSERT(len2 == size2); - } - - bool can_write() - { - return have_space_for(size1 + size2); - } - virtual void write() = 0; - - bool is_empty() { return used_size() == 0; } - virtual bool read() = 0; - - void sort(qsort2_cmp cmp_func, void *cmp_func_arg) - { - size_t elem_size= size1 + size2; - size_t n_elements= used_size() / elem_size; - my_qsort2(used_area(), n_elements, elem_size, cmp_func, cmp_func_arg); - } - - virtual void reset() = 0; - virtual uchar *end_of_space() = 0; -protected: - virtual size_t used_size() = 0; - - /* To be used only by iterator class: */ - virtual uchar *get_pos()= 0; - virtual bool read(uchar **position, uchar **ptr1, uchar **ptr2)= 0; - friend class Lifo_buffer_iterator; -public: - virtual bool have_space_for(size_t bytes) = 0; - - virtual void remove_unused_space(uchar **unused_start, uchar **unused_end)=0; - virtual uchar *used_area() = 0; - virtual ~Lifo_buffer() {}; -}; - - -/** - Forward LIFO buffer - - The buffer that is being written to from start to end and read in the - reverse. 'pos' points to just beyond the end of used space. - - It is possible to grow/shink the buffer at the end bound - - used space unused space - *==============*-----------------* - ^ ^ ^ - | | +--- end - | +---- pos - +--- start -*/ - -class Forward_lifo_buffer: public Lifo_buffer -{ - uchar *pos; -public: - enum_direction type() { return FORWARD; } - size_t used_size() - { - return (size_t)(pos - start); - } - void reset() - { - pos= start; - } - uchar *end_of_space() { return pos; } - bool have_space_for(size_t bytes) - { - return (pos + bytes < end); - } - - void write() - { - write_bytes(write_ptr1, size1); - if (size2) - write_bytes(write_ptr2, size2); - } - void write_bytes(const uchar *data, size_t bytes) - { - DBUG_ASSERT(have_space_for(bytes)); - memcpy(pos, data, bytes); - pos += bytes; - } - bool have_data(uchar *position, size_t bytes) - { - return ((position - start) >= (ptrdiff_t)bytes); - } - uchar *read_bytes(uchar **position, size_t bytes) - { - DBUG_ASSERT(have_data(*position, bytes)); - *position= (*position) - bytes; - return *position; - } - bool read() { return read(&pos, &read_ptr1, &read_ptr2); } - bool read(uchar **position, uchar **ptr1, uchar **ptr2) - { - if (!have_data(*position, size1 + size2)) - return TRUE; - if (size2) - *ptr2= read_bytes(position, size2); - *ptr1= read_bytes(position, size1); - return FALSE; - } - void remove_unused_space(uchar **unused_start, uchar **unused_end) - { - DBUG_ASSERT(0); /* Don't need this yet */ - } - /** - Add more space to the buffer. The caller is responsible that the space - being added is adjacent to the end of the buffer. - - @param unused_start Start of space - @param unused_end End of space - */ - void grow(uchar *unused_start, uchar *unused_end) - { - DBUG_ASSERT(unused_end >= unused_start); - DBUG_ASSERT(end == unused_start); - TRASH_ALLOC(unused_start, size_t(unused_end - unused_start)); - end= unused_end; - } - /* Return pointer to start of the memory area that is occupied by the data */ - uchar *used_area() { return start; } - friend class Lifo_buffer_iterator; - uchar *get_pos() { return pos; } -}; - - - -/** - Backward LIFO buffer - - The buffer that is being written to from start to end and read in the - reverse. 'pos' points to the start of used space. - - It is possible to grow/shink the buffer at the start. - - unused space used space - *--------------*=================* - ^ ^ ^ - | | +--- end - | +---- pos - +--- start -*/ -class Backward_lifo_buffer: public Lifo_buffer -{ - uchar *pos; -public: - enum_direction type() { return BACKWARD; } - - size_t used_size() - { - return (size_t)(end - pos); - } - void reset() - { - pos= end; - } - uchar *end_of_space() { return end; } - bool have_space_for(size_t bytes) - { - return (pos - bytes >= start); - } - void write() - { - if (write_ptr2) - write_bytes(write_ptr2, size2); - write_bytes(write_ptr1, size1); - } - void write_bytes(const uchar *data, size_t bytes) - { - DBUG_ASSERT(have_space_for(bytes)); - pos -= bytes; - memcpy(pos, data, bytes); - } - bool read() - { - return read(&pos, &read_ptr1, &read_ptr2); - } - bool read(uchar **position, uchar **ptr1, uchar **ptr2) - { - if (!have_data(*position, size1 + size2)) - return TRUE; - *ptr1= read_bytes(position, size1); - if (size2) - *ptr2= read_bytes(position, size2); - return FALSE; - } - bool have_data(uchar *position, size_t bytes) - { - return ((end - position) >= (ptrdiff_t)bytes); - } - uchar *read_bytes(uchar **position, size_t bytes) - { - DBUG_ASSERT(have_data(*position, bytes)); - uchar *ret= *position; - *position= *position + bytes; - return ret; - } - /** - Stop using/return the unused part of the space - @param unused_start OUT Start of the unused space - @param unused_end OUT End of the unused space - */ - void remove_unused_space(uchar **unused_start, uchar **unused_end) - { - *unused_start= start; - *unused_end= pos; - start= pos; - } - void grow(uchar *unused_start, uchar *unused_end) - { - DBUG_ASSERT(0); /* Not used for backward buffers */ - } - /* Return pointer to start of the memory area that is occupied by the data */ - uchar *used_area() { return pos; } - friend class Lifo_buffer_iterator; - uchar *get_pos() { return pos; } -}; - - -/** Iterator to walk over contents of the buffer without reading from it */ -class Lifo_buffer_iterator -{ - uchar *pos; - Lifo_buffer *buf; - -public: - /* The data is read to here */ - uchar *read_ptr1; - uchar *read_ptr2; - - void init(Lifo_buffer *buf_arg) - { - buf= buf_arg; - pos= buf->get_pos(); - } - /* - Read the next value. The calling convention is the same as buf->read() - has. - - @retval FALSE - ok - @retval TRUE - EOF, reached the end of the buffer - */ - bool read() - { - return buf->read(&pos, &read_ptr1, &read_ptr2); - } -}; - - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_limit.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_limit.h deleted file mode 100644 index a4fceda..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_limit.h +++ /dev/null @@ -1,72 +0,0 @@ -/* Copyright (c) 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef INCLUDES_MARIADB_SQL_LIMIT_H -#define INCLUDES_MARIADB_SQL_LIMIT_H -/** - LIMIT/OFFSET parameters for execution. -*/ - -class Select_limit_counters -{ - ha_rows select_limit_cnt, offset_limit_cnt; - - public: - Select_limit_counters(): - select_limit_cnt(0), offset_limit_cnt(0) - {}; - Select_limit_counters(Select_limit_counters &orig): - select_limit_cnt(orig.select_limit_cnt), - offset_limit_cnt(orig.offset_limit_cnt) - {}; - - void set_limit(ha_rows limit, ha_rows offset) - { - offset_limit_cnt= offset; - select_limit_cnt= limit; - if (select_limit_cnt + offset_limit_cnt >= - select_limit_cnt) - select_limit_cnt+= offset_limit_cnt; - else - select_limit_cnt= HA_POS_ERROR; - } - - void set_single_row() - { - offset_limit_cnt= 0; - select_limit_cnt= 1; - } - - bool is_unlimited() - { return select_limit_cnt == HA_POS_ERROR; } - bool is_unrestricted() - { return select_limit_cnt == HA_POS_ERROR && offset_limit_cnt == 0; } - void set_unlimited() - { select_limit_cnt= HA_POS_ERROR; offset_limit_cnt= 0; } - - bool check_offset(ha_rows sent) - { - return sent < offset_limit_cnt; - } - void remove_offset() { offset_limit_cnt= 0; } - - ha_rows get_select_limit() - { return select_limit_cnt; } - ha_rows get_offset_limit() - { return offset_limit_cnt; } -}; - -#endif // INCLUDES_MARIADB_SQL_LIMIT_H diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_list.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_list.h deleted file mode 100644 index 91134bc..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_list.h +++ /dev/null @@ -1,875 +0,0 @@ -#ifndef INCLUDES_MYSQL_SQL_LIST_H -#define INCLUDES_MYSQL_SQL_LIST_H -/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_alloc.h" -#include - -/** - Simple intrusive linked list. - - @remark Similar in nature to base_list, but intrusive. It keeps a - a pointer to the first element in the list and a indirect - reference to the last element. -*/ - -template -class SQL_I_List :public Sql_alloc -{ -public: - uint elements; - /** The first element in the list. */ - T *first; - /** A reference to the next element in the list. */ - T **next; - - SQL_I_List() { empty(); } - - SQL_I_List(const SQL_I_List &tmp) : Sql_alloc() - { - elements= tmp.elements; - first= tmp.first; - next= elements ? tmp.next : &first; - } - - SQL_I_List& operator=(const SQL_I_List &tmp) - { - elements= tmp.elements; - first= tmp.first; - next= tmp.next; - return *this; - } - - inline void empty() - { - elements= 0; - first= NULL; - next= &first; - } - - inline void link_in_list(T *element, T **next_ptr) - { - elements++; - (*next)= element; - next= next_ptr; - *next= NULL; - } - - inline void save_and_clear(SQL_I_List *save) - { - *save= *this; - empty(); - } - - inline void push_front(SQL_I_List *save) - { - /* link current list last */ - *save->next= first; - first= save->first; - elements+= save->elements; - } - - inline void push_back(SQL_I_List *save) - { - if (save->first) - { - *next= save->first; - next= save->next; - elements+= save->elements; - } - } -}; - - -/* - Basic single linked list - Used for item and item_buffs. - All list ends with a pointer to the 'end_of_list' element, which - data pointer is a null pointer and the next pointer points to itself. - This makes it very fast to traverse lists as we don't have to - test for a specialend condition for list that can't contain a null - pointer. -*/ - - -/** - list_node - a node of a single-linked list. - @note We never call a destructor for instances of this class. -*/ - -struct list_node :public Sql_alloc -{ - list_node *next; - void *info; - list_node(void *info_par,list_node *next_par) - :next(next_par),info(info_par) - {} - list_node() /* For end_of_list */ - { - info= 0; - next= this; - } -}; - -typedef bool List_eq(void *a, void *b); - -extern MYSQL_PLUGIN_IMPORT list_node end_of_list; - -class base_list :public Sql_alloc -{ -protected: - list_node *first,**last; - -public: - uint elements; - - bool operator==(const base_list &rhs) const - { - return - elements == rhs.elements && - first == rhs.first && - last == rhs.last; - } - base_list& operator=(const base_list &rhs) - { - elements= rhs.elements; - first= rhs.first; - last= elements ? rhs.last : &first; - return *this; - } - - inline void empty() { elements=0; first= &end_of_list; last=&first;} - inline base_list() { empty(); } - /** - This is a shallow copy constructor that implicitly passes the ownership - from the source list to the new instance. The old instance is not - updated, so both objects end up sharing the same nodes. If one of - the instances then adds or removes a node, the other becomes out of - sync ('last' pointer), while still operational. Some old code uses and - relies on this behaviour. This logic is quite tricky: please do not use - it in any new code. - */ - inline base_list(const base_list &tmp) :Sql_alloc() - { - *this= tmp; - } - /** - Construct a deep copy of the argument in memory root mem_root. - The elements themselves are copied by pointer. If you also - need to copy elements by value, you should employ - list_copy_and_replace_each_value after creating a copy. - */ - bool copy(const base_list *rhs, MEM_ROOT *mem_root); - base_list(const base_list &rhs, MEM_ROOT *mem_root) { copy(&rhs, mem_root); } - inline base_list(bool) {} - inline bool push_back(void *info) - { - if (((*last)=new list_node(info, &end_of_list))) - { - last= &(*last)->next; - elements++; - return 0; - } - return 1; - } - inline bool push_back(void *info, MEM_ROOT *mem_root) - { - if (((*last)=new (mem_root) list_node(info, &end_of_list))) - { - last= &(*last)->next; - elements++; - return 0; - } - return 1; - } - bool push_front_impl(list_node *node) - { - if (node) - { - if (last == &first) - last= &node->next; - first=node; - elements++; - return 0; - } - return 1; - } - inline bool push_front(void *info) - { return push_front_impl(new list_node(info, first)); } - inline bool push_front(void *info, MEM_ROOT *mem_root) - { return push_front_impl(new (mem_root) list_node(info,first)); } - void remove(list_node **prev) - { - list_node *node=(*prev)->next; - if (!--elements) - last= &first; - else if (last == &(*prev)->next) - last= prev; - delete *prev; - *prev=node; - } - inline void append(base_list *list) - { - if (!list->is_empty()) - { - if (is_empty()) - { - *this= *list; - return; - } - *last= list->first; - last= list->last; - elements+= list->elements; - } - } - inline void *pop(void) - { - if (first == &end_of_list) return 0; - list_node *tmp=first; - first=first->next; - if (!--elements) - last= &first; - return tmp->info; - } - - /* - Remove from this list elements that are contained in the passed list. - We assume that the passed list is a tail of this list (that is, the whole - list_node* elements are shared). - */ - inline void disjoin(const base_list *list) - { - list_node **prev= &first; - list_node *node= first; - list_node *list_first= list->first; - elements=0; - while (node != &end_of_list && node != list_first) - { - prev= &node->next; - node= node->next; - elements++; - if (node == &end_of_list) - return; - } - *prev= &end_of_list; - last= prev; - } - inline void prepend(base_list *list) - { - if (!list->is_empty()) - { - if (is_empty()) - last= list->last; - *list->last= first; - first= list->first; - elements+= list->elements; - } - } - /** - Swap two lists. - */ - inline void swap(base_list &rhs) - { - list_node **rhs_last=rhs.last; - swap_variables(list_node *, first, rhs.first); - swap_variables(uint, elements, rhs.elements); - rhs.last= last == &first ? &rhs.first : last; - last = rhs_last == &rhs.first ? &first : rhs_last; - } - - inline list_node* last_node() { return *last; } - inline list_node* first_node() { return first;} - inline void *head() { return first->info; } - inline void **head_ref() { return first != &end_of_list ? &first->info : 0; } - inline bool is_empty() { return first == &end_of_list ; } - inline list_node *last_ref() { return &end_of_list; } - inline bool add_unique(void *info, List_eq *eq) - { - list_node *node= first; - for (; - node != &end_of_list && (!(*eq)(node->info, info)); - node= node->next) ; - if (node == &end_of_list) - return push_back(info); - return 1; - } - friend class base_list_iterator; - friend class error_list; - friend class error_list_iterator; - - /* - Return N-th element in the list, or NULL if the list has - less than N elements. - */ - void *elem(uint n) - { - list_node *node= first; - void *data= NULL; - for (uint i= 0; i <= n; i++) - { - if (node == &end_of_list) - { - data= NULL; - break; - } - data= node->info; - node= node->next; - } - return data; - } - -#ifdef LIST_EXTRA_DEBUG - /* - Check list invariants and print results into trace. Invariants are: - - (*last) points to end_of_list - - There are no NULLs in the list. - - base_list::elements is the number of elements in the list. - - SYNOPSIS - check_list() - name Name to print to trace file - - RETURN - 1 The list is Ok. - 0 List invariants are not met. - */ - - bool check_list(const char *name) - { - base_list *list= this; - list_node *node= first; - uint cnt= 0; - - while (node->next != &end_of_list) - { - if (!node->info) - { - DBUG_PRINT("list_invariants",("%s: error: NULL element in the list", - name)); - return FALSE; - } - node= node->next; - cnt++; - } - if (last != &(node->next)) - { - DBUG_PRINT("list_invariants", ("%s: error: wrong last pointer", name)); - return FALSE; - } - if (cnt+1 != elements) - { - DBUG_PRINT("list_invariants", ("%s: error: wrong element count", name)); - return FALSE; - } - DBUG_PRINT("list_invariants", ("%s: list is ok", name)); - return TRUE; - } -#endif // LIST_EXTRA_DEBUG - -protected: - void after(void *info,list_node *node) - { - list_node *new_node=new list_node(info,node->next); - node->next=new_node; - elements++; - if (last == &(node->next)) - last= &new_node->next; - } -}; - - -class base_list_iterator -{ -protected: - base_list *list; - list_node **el,**prev,*current; - void sublist(base_list &ls, uint elm) - { - ls.first= *el; - ls.last= list->last; - ls.elements= elm; - } -public: - base_list_iterator() - :list(0), el(0), prev(0), current(0) - {} - - base_list_iterator(base_list &list_par) - { init(list_par); } - - inline void init(base_list &list_par) - { - list= &list_par; - el= &list_par.first; - prev= 0; - current= 0; - } - - inline void *next(void) - { - prev=el; - current= *el; - el= ¤t->next; - return current->info; - } - /* Get what calling next() would return, without moving the iterator */ - inline void *peek() - { - return (*el)->info; - } - inline void *next_fast(void) - { - list_node *tmp; - tmp= *el; - el= &tmp->next; - return tmp->info; - } - inline void rewind(void) - { - el= &list->first; - } - inline void *replace(void *element) - { // Return old element - void *tmp=current->info; - DBUG_ASSERT(current->info != 0); - current->info=element; - return tmp; - } - void *replace(base_list &new_list) - { - void *ret_value=current->info; - if (!new_list.is_empty()) - { - *new_list.last=current->next; - current->info=new_list.first->info; - current->next=new_list.first->next; - if ((list->last == ¤t->next) && (new_list.elements > 1)) - list->last= new_list.last; - list->elements+=new_list.elements-1; - } - return ret_value; // return old element - } - inline void remove(void) // Remove current - { - list->remove(prev); - el=prev; - current=0; // Safeguard - } - void after(void *element) // Insert element after current - { - list->after(element,current); - current=current->next; - el= ¤t->next; - } - inline void **ref(void) // Get reference pointer - { - return ¤t->info; - } - inline bool is_last(void) - { - return el == &list->last_ref()->next; - } - inline bool at_end() - { - return current == &end_of_list; - } - friend class error_list_iterator; -}; - -template class List :public base_list -{ -public: - inline List() :base_list() {} - inline List(const List &tmp, MEM_ROOT *mem_root) : - base_list(tmp, mem_root) {} - inline bool push_back(T *a) { return base_list::push_back(a); } - inline bool push_back(T *a, MEM_ROOT *mem_root) - { return base_list::push_back((void*) a, mem_root); } - inline bool push_front(T *a) { return base_list::push_front(a); } - inline bool push_front(T *a, MEM_ROOT *mem_root) - { return base_list::push_front((void*) a, mem_root); } - inline T* head() {return (T*) base_list::head(); } - inline T** head_ref() {return (T**) base_list::head_ref(); } - inline T* pop() {return (T*) base_list::pop(); } - inline void append(List *list) { base_list::append(list); } - inline void prepend(List *list) { base_list::prepend(list); } - inline void disjoin(List *list) { base_list::disjoin(list); } - inline bool add_unique(T *a, bool (*eq)(T *a, T *b)) - { return base_list::add_unique(a, (List_eq *)eq); } - inline bool copy(const List *list, MEM_ROOT *root) - { return base_list::copy(list, root); } - void delete_elements(void) - { - list_node *element,*next; - for (element=first; element != &end_of_list; element=next) - { - next=element->next; - delete (T*) element->info; - } - empty(); - } - T *elem(uint n) { return (T*) base_list::elem(n); } - // Create a new list with one element - static List *make(MEM_ROOT *mem_root, T *first) - { - List *res= new (mem_root) List; - return res == NULL || res->push_back(first, mem_root) ? NULL : res; - } - - class Iterator; - using value_type= T; - using iterator= Iterator; - using const_iterator= const Iterator; - - Iterator begin() const { return Iterator(first); } - Iterator end() const { return Iterator(); } - - class Iterator - { - public: - using iterator_category= std::forward_iterator_tag; - using value_type= T; - using difference_type= std::ptrdiff_t; - using pointer= T *; - using reference= T &; - - Iterator(list_node *p= &end_of_list) : node{p} {} - - Iterator &operator++() - { - DBUG_ASSERT(node != &end_of_list); - - node= node->next; - return *this; - } - - T operator++(int) - { - Iterator tmp(*this); - operator++(); - return tmp; - } - - T &operator*() { return *static_cast(node->info); } - T *operator->() { return static_cast(node->info); } - - bool operator==(const typename List::iterator &rhs) - { - return node == rhs.node; - } - - bool operator!=(const typename List::iterator &rhs) - { - return node != rhs.node; - } - - private: - list_node *node{&end_of_list}; - }; -}; - - -template class List_iterator :public base_list_iterator -{ -public: - List_iterator(List &a) : base_list_iterator(a) {} - List_iterator() : base_list_iterator() {} - inline void init(List &a) { base_list_iterator::init(a); } - inline T* operator++(int) { return (T*) base_list_iterator::next(); } - inline T* peek() { return (T*) base_list_iterator::peek(); } - inline T *replace(T *a) { return (T*) base_list_iterator::replace(a); } - inline T *replace(List &a) { return (T*) base_list_iterator::replace(a); } - inline void rewind(void) { base_list_iterator::rewind(); } - inline void remove() { base_list_iterator::remove(); } - inline void after(T *a) { base_list_iterator::after(a); } - inline T** ref(void) { return (T**) base_list_iterator::ref(); } -}; - - -template class List_iterator_fast :public base_list_iterator -{ -protected: - inline T *replace(T *) { return (T*) 0; } - inline T *replace(List &) { return (T*) 0; } - inline void remove(void) {} - inline void after(T *) {} - inline T** ref(void) { return (T**) 0; } - -public: - inline List_iterator_fast(List &a) : base_list_iterator(a) {} - inline List_iterator_fast() : base_list_iterator() {} - inline void init(List &a) { base_list_iterator::init(a); } - inline T* operator++(int) { return (T*) base_list_iterator::next_fast(); } - inline void rewind(void) { base_list_iterator::rewind(); } - void sublist(List &list_arg, uint el_arg) - { - base_list_iterator::sublist(list_arg, el_arg); - } -}; - - -/* - Bubble sort algorithm for List. - This sort function is supposed to be used only for very short list. - Currently it is used for the lists of Item_equal objects and - for some lists in the table elimination algorithms. In both - cases the sorted lists are very short. -*/ - -template -inline void bubble_sort(List *list_to_sort, - int (*sort_func)(T *a, T *b, void *arg), void *arg) -{ - bool swap; - T **ref1= 0; - T **ref2= 0; - List_iterator it(*list_to_sort); - do - { - T **last_ref= ref1; - T *item1= it++; - ref1= it.ref(); - T *item2; - - swap= FALSE; - while ((item2= it++) && (ref2= it.ref()) != last_ref) - { - if (sort_func(item1, item2, arg) > 0) - { - *ref1= item2; - *ref2= item1; - swap= TRUE; - } - else - item1= item2; - ref1= ref2; - } - it.rewind(); - } while (swap); -} - - -/* - A simple intrusive list which automaticly removes element from list - on delete (for THD element) -*/ - -struct ilink -{ - struct ilink **prev,*next; - static void *operator new(size_t size) throw () - { - return (void*)my_malloc(PSI_INSTRUMENT_ME, - (uint)size, MYF(MY_WME | MY_FAE | ME_FATAL)); - } - static void operator delete(void* ptr_arg, size_t) - { - my_free(ptr_arg); - } - - inline ilink() - { - prev=0; next=0; - } - inline void unlink() - { - /* Extra tests because element doesn't have to be linked */ - if (prev) *prev= next; - if (next) next->prev=prev; - prev=0 ; next=0; - } - inline void assert_linked() - { - DBUG_ASSERT(prev != 0 && next != 0); - } - inline void assert_not_linked() - { - DBUG_ASSERT(prev == 0 && next == 0); - } - virtual ~ilink() { unlink(); } /*lint -e1740 */ -}; - - -/* Needed to be able to have an I_List of char* strings in mysqld.cc. */ - -class i_string: public ilink -{ -public: - const char* ptr; - i_string():ptr(0) { } - i_string(const char* s) : ptr(s) {} -}; - -/* needed for linked list of two strings for replicate-rewrite-db */ -class i_string_pair: public ilink -{ -public: - const char* key; - const char* val; - i_string_pair():key(0),val(0) { } - i_string_pair(const char* key_arg, const char* val_arg) : - key(key_arg),val(val_arg) {} -}; - - -template class I_List_iterator; - - -class base_ilist -{ - struct ilink *first; - struct ilink last; -public: - inline void empty() { first= &last; last.prev= &first; } - base_ilist() { empty(); } - inline bool is_empty() { return first == &last; } - // Returns true if p is the last "real" object in the list, - // i.e. p->next points to the sentinel. - inline bool is_last(ilink *p) { return p->next == NULL || p->next == &last; } - inline void append(ilink *a) - { - first->prev= &a->next; - a->next=first; a->prev= &first; first=a; - } - inline void push_back(ilink *a) - { - *last.prev= a; - a->next= &last; - a->prev= last.prev; - last.prev= &a->next; - } - inline struct ilink *get() - { - struct ilink *first_link=first; - if (first_link == &last) - return 0; - first_link->unlink(); // Unlink from list - return first_link; - } - inline struct ilink *head() - { - return (first != &last) ? first : 0; - } - - /** - Moves list elements to new owner, and empties current owner (i.e. this). - - @param[in,out] new_owner The new owner of the list elements. - Should be empty in input. - */ - - void move_elements_to(base_ilist *new_owner) - { - DBUG_ASSERT(new_owner->is_empty()); - new_owner->first= first; - new_owner->last= last; - empty(); - } - - friend class base_ilist_iterator; - private: - /* - We don't want to allow copying of this class, as that would give us - two list heads containing the same elements. - So we declare, but don't define copy CTOR and assignment operator. - */ - base_ilist(const base_ilist&); - void operator=(const base_ilist&); -}; - - -class base_ilist_iterator -{ - base_ilist *list; - struct ilink **el,*current; -public: - base_ilist_iterator(base_ilist &list_par) :list(&list_par), - el(&list_par.first),current(0) {} - void *next(void) - { - /* This is coded to allow push_back() while iterating */ - current= *el; - if (current == &list->last) return 0; - el= ¤t->next; - return current; - } -}; - - -template -class I_List :private base_ilist -{ -public: - I_List() :base_ilist() {} - inline bool is_last(T *p) { return base_ilist::is_last(p); } - inline void empty() { base_ilist::empty(); } - inline bool is_empty() { return base_ilist::is_empty(); } - inline void append(T* a) { base_ilist::append(a); } - inline void push_back(T* a) { base_ilist::push_back(a); } - inline T* get() { return (T*) base_ilist::get(); } - inline T* head() { return (T*) base_ilist::head(); } - inline void move_elements_to(I_List* new_owner) { - base_ilist::move_elements_to(new_owner); - } -#ifndef _lint - friend class I_List_iterator; -#endif -}; - - -template class I_List_iterator :public base_ilist_iterator -{ -public: - I_List_iterator(I_List &a) : base_ilist_iterator(a) {} - inline T* operator++(int) { return (T*) base_ilist_iterator::next(); } -}; - -/** - Make a deep copy of each list element. - - @note A template function and not a template method of class List - is employed because of explicit template instantiation: - in server code there are explicit instantiations of List and - an explicit instantiation of a template requires that any method - of the instantiated class used in the template can be resolved. - Evidently not all template arguments have clone() method with - the right signature. - - @return You must query the error state in THD for out-of-memory - situation after calling this function. -*/ - -template -inline -void -list_copy_and_replace_each_value(List &list, MEM_ROOT *mem_root) -{ - /* Make a deep copy of each element */ - List_iterator it(list); - T *el; - while ((el= it++)) - it.replace(el->clone(mem_root)); -} - -void free_list(I_List *list); -void free_list(I_List *list); - -#endif // INCLUDES_MYSQL_SQL_LIST_H diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_load.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_load.h deleted file mode 100644 index 8413d27..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_load.h +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_LOAD_INCLUDED -#define SQL_LOAD_INCLUDED - -#include "sql_list.h" /* List */ - -class Item; - -#include "sql_class.h" /* enum_duplicates */ - -class sql_exchange; - -int mysql_load(THD *thd, const sql_exchange *ex, TABLE_LIST *table_list, - List &fields_vars, List &set_fields, - List &set_values_list, - enum enum_duplicates handle_duplicates, bool ignore, - bool local_file); - - -#endif /* SQL_LOAD_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_locale.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_locale.h deleted file mode 100644 index b7ce9f7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_locale.h +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_LOCALE_INCLUDED -#define SQL_LOCALE_INCLUDED - -typedef struct my_locale_errmsgs -{ - const char *language; - const char ***errmsgs; -} MY_LOCALE_ERRMSGS; - - -typedef struct st_typelib TYPELIB; - -class MY_LOCALE -{ -public: - uint number; - const char *name; - const char *description; - const bool is_ascii; - TYPELIB *month_names; - TYPELIB *ab_month_names; - TYPELIB *day_names; - TYPELIB *ab_day_names; - uint max_month_name_length; - uint max_day_name_length; - uint decimal_point; - uint thousand_sep; - const char *grouping; - MY_LOCALE_ERRMSGS *errmsgs; - MY_LOCALE(uint number_par, - const char *name_par, const char *descr_par, bool is_ascii_par, - TYPELIB *month_names_par, TYPELIB *ab_month_names_par, - TYPELIB *day_names_par, TYPELIB *ab_day_names_par, - uint max_month_name_length_par, uint max_day_name_length_par, - uint decimal_point_par, uint thousand_sep_par, - const char *grouping_par, MY_LOCALE_ERRMSGS *errmsgs_par) : - number(number_par), - name(name_par), description(descr_par), is_ascii(is_ascii_par), - month_names(month_names_par), ab_month_names(ab_month_names_par), - day_names(day_names_par), ab_day_names(ab_day_names_par), - max_month_name_length(max_month_name_length_par), - max_day_name_length(max_day_name_length_par), - decimal_point(decimal_point_par), - thousand_sep(thousand_sep_par), - grouping(grouping_par), - errmsgs(errmsgs_par) - {} - my_repertoire_t repertoire() const - { return is_ascii ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_EXTENDED; } -}; -/* Exported variables */ - -extern MY_LOCALE my_locale_en_US; -extern MYSQL_PLUGIN_IMPORT MY_LOCALE *my_locales[]; -extern MY_LOCALE *my_default_lc_messages; -extern MY_LOCALE *my_default_lc_time_names; - -/* Exported functions */ - -MY_LOCALE *my_locale_by_name(const char *name); -MY_LOCALE *my_locale_by_number(uint number); -void cleanup_errmsgs(void); - -#endif /* SQL_LOCALE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_manager.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_manager.h deleted file mode 100644 index 9c6c844..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_manager.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_MANAGER_INCLUDED -#define SQL_MANAGER_INCLUDED - -void start_handle_manager(); -void stop_handle_manager(); -bool mysql_manager_submit(void (*action)()); - -#endif /* SQL_MANAGER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_mode.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_mode.h deleted file mode 100644 index fb2b7ce..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_mode.h +++ /dev/null @@ -1,162 +0,0 @@ -#ifndef SQL_MODE_H_INCLUDED -#define SQL_MODE_H_INCLUDED -/* - Copyright (c) 2019, MariaDB. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_basic_types.h" - -/* - class Sql_mode_dependency - - A combination of hard and soft dependency on sql_mode. - Used to watch if a GENERATED ALWAYS AS expression guarantees consitent - data written to its virtual column. - - A virtual column can appear in an index if: - - the generation expression does not depend on any sql_mode flags, or - - the generation expression has a soft dependency on an sql_mode flag, - and the column knows how to handle this dependeny. - - A virtual column cannot appear in an index if: - - its generation expression has a hard dependency - - its generation expression has a soft dependency, but the column - cannot handle it on store. - An error is reported in such cases. - - How dependencies appear: - - When a column return value depends on some sql_mode flag, - its Item_field adds a corresponding bit to m_soft. For example, - Item_field for a CHAR(N) column adds the PAD_CHAR_TO_FULL_LENGTH flag. - - When an SQL function/operator return value depends on some sql_mode flag, - it adds a corresponding bit to m_soft. For example, Item_func_minus - adds the MODE_NO_UNSIGNED_SUBTRACTION in case of unsigned arguments. - - How dependency are processed (see examples below): - - All SQL functions/operators bit-OR all hard dependencies from all arguments. - - Some soft dependencies can be handled by the underlying Field on store, - e.g. CHAR(N) can handle PAD_CHAR_TO_FULL_LENGTH. - - Some soft dependencies can be handled by SQL functions and operators, - e.g. RTRIM(expr) removes expr's soft dependency on PAD_CHAR_TO_FULL_LENGTH. - If a function or operator handles a soft dependency on a certain sql_mode - flag, it removes the corresponding bit from m_soft (see below). - Note, m_hard is not touched in such cases. - - When an expression with a soft dependency on a certain sql_mode flag - goes as an argument to an SQL function/operator which cannot handle - this flag, the dependency escalates from soft to hard - (by moving the corresponding bit from m_soft to m_hard) and cannot be - handled any more on the upper level, neither by a Field on store, - nor by another SQL function/operator. - - There are four kinds of Items: - 1. Items that generate a soft or hard dependency, e.g. - - Item_field for CHAR(N) - generates soft/PAD_CHAR_TO_FULL_LENGTH - - Item_func_minus - generates soft/NO_UNSIGNED_SUBTRACTION - 2. Items that convert a soft dependency to a hard dependency. - This happens e.g. when an Item_func instance gets a soft dependency - from its arguments, and it does not know how to handle this dependency. - Most Item_func descendants do this. - 3. Items that remove soft dependencies, e.g.: - - Item_func_rtrim - removes soft/PAD_CHAR_TO_FULL_LENGTH - that came from args[0] (under certain conditions) - - Item_func_rpad - removes soft/PAD_CJAR_TO_FULL_LENGTH - that came from args[0] (under certain conditions) - 4. Items that repeat soft dependency from its arguments to the caller. - They are not implemented yet. But functions like Item_func_coalesce, - Item_func_case, Item_func_case_abbreviation2 could do this. - - Examples: - - 1. CREATE OR REPLACE TABLE t1 (a CHAR(5), v CHAR(20) AS(a), KEY(v)); - - Here `v` has a soft dependency on `a`. - The value of `a` depends on PAD_CHAR_TO_FULL_LENGTH, it can return: - - 'a' - if PAD_CHAR_TO_FULL_LENGTH is disabled - - 'a' followed by four spaces - if PAD_CHAR_TO_FULL_LENGTH is enabled - But `v` will pad trailing spaces to the full length on store anyway. - So Field_string handles this soft dependency on store. - This combination of the virtial column data type and its generation - expression is safe and provides consistent data in `v`, which is - 'a' followed by four spaces, no matter what PAD_CHAR_TO_FULL_LENGTH is. - - 2. CREATE OR REPLACE TABLE t1 (a CHAR(5), v VARCHAR(20) AS(a), KEY(v)); - - Here `v` has a soft dependency on `a`. But Field_varstring does - not pad spaces on store, so it cannot handle this dependency. - This combination of the virtual column data type and its generation - expression is not safe. An error is returned. - - 3. CREATE OR REPLACE TABLE t1 (a CHAR(5), v INT AS(LENGTH(a)), KEY(v)); - - Here `v` has a hard dependency on `a`, because the value of `a` - is wrapped to the function LENGTH(). - The value of `LENGTH(a)` depends on PAD_CHAR_TO_FULL_LENGTH, it can return: - - 1 - if PAD_CHAR_TO_FULL_LENGTH is disabled - - 4 - if PAD_CHAR_TO_FULL_LENGTH is enabled - This combination cannot provide consistent data stored to `v`, - therefore it's disallowed. -*/ -class Sql_mode_dependency -{ - sql_mode_t m_hard; - sql_mode_t m_soft; -public: - Sql_mode_dependency() - :m_hard(0), m_soft(0) - { } - Sql_mode_dependency(sql_mode_t hard, sql_mode_t soft) - :m_hard(hard), m_soft(soft) - { } - sql_mode_t hard() const { return m_hard; } - sql_mode_t soft() const { return m_soft; } - operator bool () const - { - return m_hard > 0 || m_soft > 0; - } - Sql_mode_dependency operator|(const Sql_mode_dependency &other) const - { - return Sql_mode_dependency(m_hard | other.m_hard, m_soft | other.m_soft); - } - Sql_mode_dependency operator&(const Sql_mode_dependency &other) const - { - return Sql_mode_dependency(m_hard & other.m_hard, m_soft & other.m_soft); - } - Sql_mode_dependency &operator|=(const Sql_mode_dependency &other) - { - m_hard|= other.m_hard; - m_soft|= other.m_soft; - return *this; - } - Sql_mode_dependency &operator&=(const Sql_mode_dependency &other) - { - m_hard&= other.m_hard; - m_soft&= other.m_soft; - return *this; - } - Sql_mode_dependency &soft_to_hard() - { - m_hard|= m_soft; - m_soft= 0; - return *this; - } - void push_dependency_warnings(THD *thd) const; -}; - - -#endif // SQL_MODE_H_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_parse.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_parse.h deleted file mode 100644 index 0e5cc7f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_parse.h +++ /dev/null @@ -1,188 +0,0 @@ -/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_PARSE_INCLUDED -#define SQL_PARSE_INCLUDED - -#include "sql_acl.h" /* GLOBAL_ACLS */ - -class Comp_creator; -class Item; -class Object_creation_ctx; -class Parser_state; -struct TABLE_LIST; -class THD; -class Table_ident; -struct LEX; - -enum enum_mysql_completiontype { - ROLLBACK_RELEASE=-2, ROLLBACK=1, ROLLBACK_AND_CHAIN=7, - COMMIT_RELEASE=-1, COMMIT=0, COMMIT_AND_CHAIN=6 -}; - -extern "C" int path_starts_from_data_home_dir(const char *dir); -int test_if_data_home_dir(const char *dir); -int error_if_data_home_dir(const char *path, const char *what); -my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags); - -bool multi_update_precheck(THD *thd, TABLE_LIST *tables); -bool multi_delete_precheck(THD *thd, TABLE_LIST *tables); -int mysql_multi_update_prepare(THD *thd); -int mysql_multi_delete_prepare(THD *thd); -int mysql_insert_select_prepare(THD *thd,select_result *sel_res); -bool update_precheck(THD *thd, TABLE_LIST *tables); -bool delete_precheck(THD *thd, TABLE_LIST *tables); -bool insert_precheck(THD *thd, TABLE_LIST *tables); -bool create_table_precheck(THD *thd, TABLE_LIST *tables, - TABLE_LIST *create_table); -bool check_fk_parent_table_access(THD *thd, - HA_CREATE_INFO *create_info, - Alter_info *alter_info, - const char* create_db); - -bool parse_sql(THD *thd, Parser_state *parser_state, - Object_creation_ctx *creation_ctx, bool do_pfs_digest=false); - -void free_items(Item *item); -void cleanup_items(Item *item); - -Comp_creator *comp_eq_creator(bool invert); -Comp_creator *comp_ge_creator(bool invert); -Comp_creator *comp_gt_creator(bool invert); -Comp_creator *comp_le_creator(bool invert); -Comp_creator *comp_lt_creator(bool invert); -Comp_creator *comp_ne_creator(bool invert); - -int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident, - enum enum_schema_tables schema_table_idx); -void get_default_definer(THD *thd, LEX_USER *definer, bool role); -LEX_USER *create_default_definer(THD *thd, bool role); -LEX_USER *create_definer(THD *thd, LEX_CSTRING *user_name, LEX_CSTRING *host_name); -LEX_USER *get_current_user(THD *thd, LEX_USER *user, bool lock=true); -bool sp_process_definer(THD *thd); -bool check_string_byte_length(const LEX_CSTRING *str, uint err_msg, - size_t max_byte_length); -bool check_string_char_length(const LEX_CSTRING *str, uint err_msg, - size_t max_char_length, CHARSET_INFO *cs, - bool no_error); -bool check_ident_length(const LEX_CSTRING *ident); -CHARSET_INFO* merge_charset_and_collation(CHARSET_INFO *cs, CHARSET_INFO *cl); -CHARSET_INFO *find_bin_collation(CHARSET_INFO *cs); -bool check_host_name(LEX_CSTRING *str); -bool check_identifier_name(LEX_CSTRING *str, uint max_char_length, - uint err_code, const char *param_for_err_msg); -bool mysql_test_parse_for_slave(THD *thd,char *inBuf,uint length); -bool sqlcom_can_generate_row_events(const THD *thd); -bool stmt_causes_implicit_commit(THD *thd, uint mask); -bool is_update_query(enum enum_sql_command command); -bool is_log_table_write_query(enum enum_sql_command command); -bool alloc_query(THD *thd, const char *packet, size_t packet_length); -void mysql_init_select(LEX *lex); -void mysql_parse(THD *thd, char *rawbuf, uint length, - Parser_state *parser_state, bool is_com_multi, - bool is_next_command); -bool mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *sel); -void create_select_for_variable(THD *thd, LEX_CSTRING *var_name); -void create_table_set_open_action_and_adjust_tables(LEX *lex); -void mysql_init_multi_delete(LEX *lex); -bool multi_delete_set_locks_and_link_aux_tables(LEX *lex); -void create_table_set_open_action_and_adjust_tables(LEX *lex); -int bootstrap(MYSQL_FILE *file); -int mysql_execute_command(THD *thd); -bool do_command(THD *thd); -bool dispatch_command(enum enum_server_command command, THD *thd, - char* packet, uint packet_length, - bool is_com_multi, bool is_next_command); -void log_slow_statement(THD *thd); -bool append_file_to_dir(THD *thd, const char **filename_ptr, - const LEX_CSTRING *table_name); -void execute_init_command(THD *thd, LEX_STRING *init_command, - mysql_rwlock_t *var_lock); -bool add_to_list(THD *thd, SQL_I_List &list, Item *group, bool asc); -void add_join_on(THD *thd, TABLE_LIST *b, Item *expr); -void add_join_natural(TABLE_LIST *a,TABLE_LIST *b,List *using_fields, - SELECT_LEX *lex); -bool add_proc_to_list(THD *thd, Item *item); -bool push_new_name_resolution_context(THD *thd, - TABLE_LIST *left_op, - TABLE_LIST *right_op); -void init_update_queries(void); -Item *normalize_cond(THD *thd, Item *cond); -Item *negate_expression(THD *thd, Item *expr); -bool check_stack_overrun(THD *thd, long margin, uchar *dummy); - -/* Variables */ - -extern const char* any_db; -extern uint sql_command_flags[]; -extern uint server_command_flags[]; -extern const LEX_CSTRING command_name[]; -extern uint server_command_flags[]; - -/* Inline functions */ -inline bool check_identifier_name(LEX_CSTRING *str, uint err_code) -{ - return check_identifier_name(str, NAME_CHAR_LEN, err_code, ""); -} - -inline bool check_identifier_name(LEX_CSTRING *str) -{ - return check_identifier_name(str, NAME_CHAR_LEN, 0, ""); -} - -#ifndef NO_EMBEDDED_ACCESS_CHECKS -bool check_one_table_access(THD *thd, privilege_t privilege, TABLE_LIST *tables); -bool check_single_table_access(THD *thd, privilege_t privilege, - TABLE_LIST *tables, bool no_errors); -bool check_routine_access(THD *thd, privilege_t want_access, - const LEX_CSTRING *db, - const LEX_CSTRING *name, - const Sp_handler *sph, bool no_errors); -bool check_some_access(THD *thd, privilege_t want_access, TABLE_LIST *table); -bool check_some_routine_access(THD *thd, const char *db, const char *name, - const Sp_handler *sph); -bool check_table_access(THD *thd, privilege_t requirements,TABLE_LIST *tables, - bool any_combination_of_privileges_will_do, - uint number, - bool no_errors); -#else -inline bool check_one_table_access(THD *thd, privilege_t privilege, TABLE_LIST *tables) -{ return false; } -inline bool check_single_table_access(THD *thd, privilege_t privilege, - TABLE_LIST *tables, bool no_errors) -{ return false; } -inline bool check_routine_access(THD *thd, privilege_t want_access, - const LEX_CSTRING *db, - const LEX_CSTRING *name, - const Sp_handler *sph, bool no_errors) -{ return false; } -inline bool check_some_access(THD *thd, privilege_t want_access, TABLE_LIST *table) -{ - table->grant.privilege= want_access; - return false; -} -inline bool check_some_routine_access(THD *thd, const char *db, - const char *name, - const Sp_handler *sph) -{ return false; } -inline bool -check_table_access(THD *thd, privilege_t requirements,TABLE_LIST *tables, - bool any_combination_of_privileges_will_do, - uint number, - bool no_errors) -{ return false; } -#endif /*NO_EMBEDDED_ACCESS_CHECKS*/ - -#endif /* SQL_PARSE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_partition.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_partition.h deleted file mode 100644 index 58ba82d..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_partition.h +++ /dev/null @@ -1,321 +0,0 @@ -#ifndef SQL_PARTITION_INCLUDED -#define SQL_PARTITION_INCLUDED - -/* Copyright (c) 2006, 2017, Oracle and/or its affiliates. - Copyright (c) 2011, 2017, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "sql_list.h" /* List */ -#include "table.h" /* TABLE_LIST */ - -class Alter_info; -class Alter_table_ctx; -class Field; -class String; -class handler; -class partition_info; -struct TABLE; -struct TABLE_LIST; -typedef struct st_bitmap MY_BITMAP; -typedef struct st_key KEY; -typedef struct st_key_range key_range; - -/* Flags for partition handlers */ -#define HA_CAN_PARTITION (1 << 0) /* Partition support */ -#define HA_CAN_UPDATE_PARTITION_KEY (1 << 1) -#define HA_CAN_PARTITION_UNIQUE (1 << 2) -#define HA_USE_AUTO_PARTITION (1 << 3) -#define HA_ONLY_VERS_PARTITION (1 << 4) - -#define NORMAL_PART_NAME 0 -#define TEMP_PART_NAME 1 -#define RENAMED_PART_NAME 2 - -typedef struct st_lock_param_type -{ - TABLE_LIST *table_list; - ulonglong copied; - ulonglong deleted; - THD *thd; - HA_CREATE_INFO *create_info; - Alter_info *alter_info; - TABLE *table; - KEY *key_info_buffer; - LEX_CSTRING db; - LEX_CSTRING table_name; - uchar *pack_frm_data; - uint key_count; - uint db_options; - size_t pack_frm_len; - partition_info *part_info; -} ALTER_PARTITION_PARAM_TYPE; - -typedef struct { - longlong list_value; - uint32 partition_id; -} LIST_PART_ENTRY; - -typedef struct { - uint32 start_part; - uint32 end_part; -} part_id_range; - -class String_list; -struct st_partition_iter; -#define NOT_A_PARTITION_ID UINT_MAX32 - -bool is_partition_in_list(char *part_name, List list_part_names); -char *are_partitions_in_table(partition_info *new_part_info, - partition_info *old_part_info); -bool check_reorganise_list(partition_info *new_part_info, - partition_info *old_part_info, - List list_part_names); -handler *get_ha_partition(partition_info *part_info); -int get_part_for_buf(const uchar *buf, const uchar *rec0, - partition_info *part_info, uint32 *part_id); -void prune_partition_set(const TABLE *table, part_id_range *part_spec); -bool check_partition_info(partition_info *part_info,handlerton **eng_type, - TABLE *table, handler *file, HA_CREATE_INFO *info); -void set_linear_hash_mask(partition_info *part_info, uint num_parts); -bool fix_partition_func(THD *thd, TABLE *table, bool create_table_ind); -void get_partition_set(const TABLE *table, uchar *buf, const uint index, - const key_range *key_spec, - part_id_range *part_spec); -uint get_partition_field_store_length(Field *field); -void get_full_part_id_from_key(const TABLE *table, uchar *buf, - KEY *key_info, - const key_range *key_spec, - part_id_range *part_spec); -bool mysql_unpack_partition(THD *thd, char *part_buf, - uint part_info_len, - TABLE *table, bool is_create_table_ind, - handlerton *default_db_type, - bool *work_part_info_used); -void make_used_partitions_str(MEM_ROOT *mem_root, - partition_info *part_info, String *parts_str, - String_list &used_partitions_list); -uint32 get_list_array_idx_for_endpoint(partition_info *part_info, - bool left_endpoint, - bool include_endpoint); -uint32 get_partition_id_range_for_endpoint(partition_info *part_info, - bool left_endpoint, - bool include_endpoint); -bool check_part_func_fields(Field **ptr, bool ok_with_charsets); -bool field_is_partition_charset(Field *field); -Item* convert_charset_partition_constant(Item *item, CHARSET_INFO *cs); -/** - Append all fields in read_set to string - - @param[in,out] str String to append to. - @param[in] row Row to append. - @param[in] table Table containing read_set and fields for the row. -*/ -void append_row_to_str(String &str, const uchar *row, TABLE *table); -void truncate_partition_filename(char *path); - -/* - A "Get next" function for partition iterator. - - SYNOPSIS - partition_iter_func() - part_iter Partition iterator, you call only "iter.get_next(&iter)" - - DESCRIPTION - Depending on whether partitions or sub-partitions are iterated, the - function returns next subpartition id/partition number. The sequence of - returned numbers is not ordered and may contain duplicates. - - When the end of sequence is reached, NOT_A_PARTITION_ID is returned, and - the iterator resets itself (so next get_next() call will start to - enumerate the set all over again). - - RETURN - NOT_A_PARTITION_ID if there are no more partitions. - [sub]partition_id of the next partition -*/ - -typedef uint32 (*partition_iter_func)(st_partition_iter* part_iter); - - -/* - Partition set iterator. Used to enumerate a set of [sub]partitions - obtained in partition interval analysis (see get_partitions_in_range_iter). - - For the user, the only meaningful field is get_next, which may be used as - follows: - part_iterator.get_next(&part_iterator); - - Initialization is done by any of the following calls: - - get_partitions_in_range_iter-type function call - - init_single_partition_iterator() - - init_all_partitions_iterator() - Cleanup is not needed. -*/ - -typedef struct st_partition_iter -{ - partition_iter_func get_next; - /* - Valid for "Interval mapping" in LIST partitioning: if true, let the - iterator also produce id of the partition that contains NULL value. - */ - bool ret_null_part, ret_null_part_orig; - /* - We should return DEFAULT partition. - */ - bool ret_default_part, ret_default_part_orig; - struct st_part_num_range - { - uint32 start; - uint32 cur; - uint32 end; - }; - - struct st_field_value_range - { - longlong start; - longlong cur; - longlong end; - }; - - union - { - struct st_part_num_range part_nums; - struct st_field_value_range field_vals; - }; - partition_info *part_info; -} PARTITION_ITERATOR; - - -/* - Get an iterator for set of partitions that match given field-space interval - - SYNOPSIS - get_partitions_in_range_iter() - part_info Partitioning info - is_subpart - store_length_array Length of fields packed in opt_range_key format - min_val Left edge, field value in opt_range_key format - max_val Right edge, field value in opt_range_key format - min_len Length of minimum value - max_len Length of maximum value - flags Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE, - NO_MAX_RANGE - part_iter Iterator structure to be initialized - - DESCRIPTION - Functions with this signature are used to perform "Partitioning Interval - Analysis". This analysis is applicable for any type of [sub]partitioning - by some function of a single fieldX. The idea is as follows: - Given an interval "const1 <=? fieldX <=? const2", find a set of partitions - that may contain records with value of fieldX within the given interval. - - The min_val, max_val and flags parameters specify the interval. - The set of partitions is returned by initializing an iterator in *part_iter - - NOTES - There are currently three functions of this type: - - get_part_iter_for_interval_via_walking - - get_part_iter_for_interval_cols_via_map - - get_part_iter_for_interval_via_mapping - - RETURN - 0 - No matching partitions, iterator not initialized - 1 - Some partitions would match, iterator intialized for traversing them - -1 - All partitions would match, iterator not initialized -*/ - -typedef int (*get_partitions_in_range_iter)(partition_info *part_info, - bool is_subpart, - uint32 *store_length_array, - uchar *min_val, uchar *max_val, - uint min_len, uint max_len, - uint flags, - PARTITION_ITERATOR *part_iter); - -#include "partition_info.h" - -#ifdef WITH_PARTITION_STORAGE_ENGINE -uint fast_alter_partition_table(THD *thd, TABLE *table, - Alter_info *alter_info, - HA_CREATE_INFO *create_info, - TABLE_LIST *table_list, - const LEX_CSTRING *db, - const LEX_CSTRING *table_name); -bool set_part_state(Alter_info *alter_info, partition_info *tab_part_info, - enum partition_state part_state); -uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info, - HA_CREATE_INFO *create_info, - bool *partition_changed, - bool *fast_alter_table); -char *generate_partition_syntax(THD *thd, partition_info *part_info, - uint *buf_length, - bool show_partition_options, - HA_CREATE_INFO *create_info, - Alter_info *alter_info); -char *generate_partition_syntax_for_frm(THD *thd, partition_info *part_info, - uint *buf_length, - HA_CREATE_INFO *create_info, - Alter_info *alter_info); -bool verify_data_with_partition(TABLE *table, TABLE *part_table, - uint32 part_id); -bool compare_partition_options(HA_CREATE_INFO *table_create_info, - partition_element *part_elem); -bool partition_key_modified(TABLE *table, const MY_BITMAP *fields); -#else -#define partition_key_modified(X,Y) 0 -#endif - -int __attribute__((warn_unused_result)) - create_partition_name(char *out, size_t outlen, const char *in1, const char - *in2, uint name_variant, bool translate); -int __attribute__((warn_unused_result)) - create_subpartition_name(char *out, size_t outlen, const char *in1, const - char *in2, const char *in3, uint name_variant); - -void set_key_field_ptr(KEY *key_info, const uchar *new_buf, - const uchar *old_buf); - -/** Set up table for creating a partition. -Copy info from partition to the table share so the created partition -has the correct info. - @param thd THD object - @param share Table share to be updated. - @param info Create info to be updated. - @param part_elem partition_element containing the info. - - @return status - @retval TRUE Error - @retval FALSE Success - - @details - Set up - 1) Comment on partition - 2) MAX_ROWS, MIN_ROWS on partition - 3) Index file name on partition - 4) Data file name on partition -*/ -bool set_up_table_before_create(THD *thd, - TABLE_SHARE *share, - const char *partition_name_with_path, - HA_CREATE_INFO *info, - partition_element *part_elem); - -#endif /* SQL_PARTITION_INCLUDED */ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_partition_admin.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_partition_admin.h deleted file mode 100644 index 4be9e56..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_partition_admin.h +++ /dev/null @@ -1,269 +0,0 @@ -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_PARTITION_ADMIN_H -#define SQL_PARTITION_ADMIN_H - -#ifndef WITH_PARTITION_STORAGE_ENGINE - -/** - Stub class that returns a error if the partition storage engine is - not supported. -*/ -class Sql_cmd_partition_unsupported : public Sql_cmd -{ -public: - Sql_cmd_partition_unsupported() - {} - - ~Sql_cmd_partition_unsupported() - {} - - /* Override SQLCOM_*, since it is an ALTER command */ - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_TABLE; - } - - bool execute(THD *thd); -}; - - -class Sql_cmd_alter_table_exchange_partition : - public Sql_cmd_partition_unsupported -{ -public: - Sql_cmd_alter_table_exchange_partition() - {} - - ~Sql_cmd_alter_table_exchange_partition() - {} -}; - - -class Sql_cmd_alter_table_analyze_partition : - public Sql_cmd_partition_unsupported -{ -public: - Sql_cmd_alter_table_analyze_partition() - {} - - ~Sql_cmd_alter_table_analyze_partition() - {} -}; - - -class Sql_cmd_alter_table_check_partition : - public Sql_cmd_partition_unsupported -{ -public: - Sql_cmd_alter_table_check_partition() - {} - - ~Sql_cmd_alter_table_check_partition() - {} -}; - - -class Sql_cmd_alter_table_optimize_partition : - public Sql_cmd_partition_unsupported -{ -public: - Sql_cmd_alter_table_optimize_partition() - {} - - ~Sql_cmd_alter_table_optimize_partition() - {} -}; - - -class Sql_cmd_alter_table_repair_partition : - public Sql_cmd_partition_unsupported -{ -public: - Sql_cmd_alter_table_repair_partition() - {} - - ~Sql_cmd_alter_table_repair_partition() - {} -}; - - -class Sql_cmd_alter_table_truncate_partition : - public Sql_cmd_partition_unsupported -{ -public: - Sql_cmd_alter_table_truncate_partition() - {} - - ~Sql_cmd_alter_table_truncate_partition() - {} -}; - -#else - -/** - Class that represents the ALTER TABLE t1 ANALYZE PARTITION p statement. -*/ -class Sql_cmd_alter_table_exchange_partition : public Sql_cmd_common_alter_table -{ -public: - /** - Constructor, used to represent a ALTER TABLE EXCHANGE PARTITION statement. - */ - Sql_cmd_alter_table_exchange_partition() - : Sql_cmd_common_alter_table() - {} - - ~Sql_cmd_alter_table_exchange_partition() - {} - - bool execute(THD *thd); - -private: - bool exchange_partition(THD *thd, TABLE_LIST *, Alter_info *); -}; - - -/** - Class that represents the ALTER TABLE t1 ANALYZE PARTITION p statement. -*/ -class Sql_cmd_alter_table_analyze_partition : public Sql_cmd_analyze_table -{ -public: - /** - Constructor, used to represent a ALTER TABLE ANALYZE PARTITION statement. - */ - Sql_cmd_alter_table_analyze_partition() - : Sql_cmd_analyze_table() - {} - - ~Sql_cmd_alter_table_analyze_partition() - {} - - bool execute(THD *thd); - - /* Override SQLCOM_ANALYZE, since it is an ALTER command */ - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_TABLE; - } -}; - - -/** - Class that represents the ALTER TABLE t1 CHECK PARTITION p statement. -*/ -class Sql_cmd_alter_table_check_partition : public Sql_cmd_check_table -{ -public: - /** - Constructor, used to represent a ALTER TABLE CHECK PARTITION statement. - */ - Sql_cmd_alter_table_check_partition() - : Sql_cmd_check_table() - {} - - ~Sql_cmd_alter_table_check_partition() - {} - - bool execute(THD *thd); - - /* Override SQLCOM_CHECK, since it is an ALTER command */ - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_TABLE; - } -}; - - -/** - Class that represents the ALTER TABLE t1 OPTIMIZE PARTITION p statement. -*/ -class Sql_cmd_alter_table_optimize_partition : public Sql_cmd_optimize_table -{ -public: - /** - Constructor, used to represent a ALTER TABLE OPTIMIZE PARTITION statement. - */ - Sql_cmd_alter_table_optimize_partition() - : Sql_cmd_optimize_table() - {} - - ~Sql_cmd_alter_table_optimize_partition() - {} - - bool execute(THD *thd); - - /* Override SQLCOM_OPTIMIZE, since it is an ALTER command */ - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_TABLE; - } -}; - - -/** - Class that represents the ALTER TABLE t1 REPAIR PARTITION p statement. -*/ -class Sql_cmd_alter_table_repair_partition : public Sql_cmd_repair_table -{ -public: - /** - Constructor, used to represent a ALTER TABLE REPAIR PARTITION statement. - */ - Sql_cmd_alter_table_repair_partition() - : Sql_cmd_repair_table() - {} - - ~Sql_cmd_alter_table_repair_partition() - {} - - bool execute(THD *thd); - - /* Override SQLCOM_REPAIR, since it is an ALTER command */ - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_TABLE; - } -}; - - -/** - Class that represents the ALTER TABLE t1 TRUNCATE PARTITION p statement. -*/ -class Sql_cmd_alter_table_truncate_partition : public Sql_cmd_truncate_table -{ -public: - /** - Constructor, used to represent a ALTER TABLE TRUNCATE PARTITION statement. - */ - Sql_cmd_alter_table_truncate_partition() - {} - - virtual ~Sql_cmd_alter_table_truncate_partition() - {} - - bool execute(THD *thd); - - /* Override SQLCOM_TRUNCATE, since it is an ALTER command */ - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_ALTER_TABLE; - } -}; - -#endif /* WITH_PARTITION_STORAGE_ENGINE */ -#endif /* SQL_PARTITION_ADMIN_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plist.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plist.h deleted file mode 100644 index 7f75208..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plist.h +++ /dev/null @@ -1,297 +0,0 @@ -#ifndef SQL_PLIST_H -#define SQL_PLIST_H -/* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -template -class I_P_List_iterator; -class I_P_List_null_counter; -template class I_P_List_no_push_back; - - -/** - Intrusive parameterized list. - - Unlike I_List does not require its elements to be descendant of ilink - class and therefore allows them to participate in several such lists - simultaneously. - - Unlike List is doubly-linked list and thus supports efficient deletion - of element without iterator. - - @param T Type of elements which will belong to list. - @param B Class which via its methods specifies which members - of T should be used for participating in this list. - Here is typical layout of such class: - - struct B - { - static inline T **next_ptr(T *el) - { - return &el->next; - } - static inline T ***prev_ptr(T *el) - { - return &el->prev; - } - }; - @param C Policy class specifying how counting of elements in the list - should be done. Instance of this class is also used as a place - where information about number of list elements is stored. - @sa I_P_List_null_counter, I_P_List_counter - @param I Policy class specifying whether I_P_List should support - efficient push_back() operation. Instance of this class - is used as place where we store information to support - this operation. - @sa I_P_List_no_push_back, I_P_List_fast_push_back. -*/ - -template > -class I_P_List : public C, public I -{ - T *m_first; - - /* - Do not prohibit copying of I_P_List object to simplify their usage in - backup/restore scenarios. Note that performing any operations on such - is a bad idea. - */ -public: - I_P_List() : I(&m_first), m_first(NULL) {}; - /* - empty() is used in many places in the code instead of a constructor, to - initialize a bzero-ed I_P_List instance. - */ - - inline void empty() { m_first= NULL; C::reset(); I::set_last(&m_first); } - inline bool is_empty() const { return (m_first == NULL); } - inline void push_front(T* a) - { - *B::next_ptr(a)= m_first; - if (m_first) - *B::prev_ptr(m_first)= B::next_ptr(a); - else - I::set_last(B::next_ptr(a)); - m_first= a; - *B::prev_ptr(a)= &m_first; - C::inc(); - } - inline void push_back(T *a) - { - T **last= I::get_last(); - *B::next_ptr(a)= *last; - *last= a; - *B::prev_ptr(a)= last; - I::set_last(B::next_ptr(a)); - C::inc(); - } - inline void insert_after(T *pos, T *a) - { - if (pos == NULL) - push_front(a); - else - { - *B::next_ptr(a)= *B::next_ptr(pos); - *B::prev_ptr(a)= B::next_ptr(pos); - *B::next_ptr(pos)= a; - if (*B::next_ptr(a)) - { - T *old_next= *B::next_ptr(a); - *B::prev_ptr(old_next)= B::next_ptr(a); - } - else - I::set_last(B::next_ptr(a)); - C::inc(); - } - } - inline void remove(T *a) - { - T *next= *B::next_ptr(a); - if (next) - *B::prev_ptr(next)= *B::prev_ptr(a); - else - I::set_last(*B::prev_ptr(a)); - **B::prev_ptr(a)= next; - C::dec(); - } - inline T* front() { return m_first; } - inline const T *front() const { return m_first; } - inline T* pop_front() - { - T *result= front(); - - if (result) - remove(result); - - return result; - } - void swap(I_P_List &rhs) - { - swap_variables(T *, m_first, rhs.m_first); - I::swap(rhs); - if (m_first) - *B::prev_ptr(m_first)= &m_first; - else - I::set_last(&m_first); - if (rhs.m_first) - *B::prev_ptr(rhs.m_first)= &rhs.m_first; - else - I::set_last(&rhs.m_first); - C::swap(rhs); - } - typedef B Adapter; - typedef I_P_List Base; - typedef I_P_List_iterator Iterator; - typedef I_P_List_iterator Const_Iterator; -#ifndef _lint - friend class I_P_List_iterator; - friend class I_P_List_iterator; -#endif -}; - - -/** - Iterator for I_P_List. -*/ - -template -class I_P_List_iterator -{ - const L *list; - T *current; -public: - I_P_List_iterator(const L &a) - : list(&a), current(a.m_first) {} - I_P_List_iterator(const L &a, T* current_arg) - : list(&a), current(current_arg) {} - inline void init(const L &a) - { - list= &a; - current= a.m_first; - } - /** - Operator for it++ - - @note since we save next element pointer, caller may remove current element. - Such modification doesn't invalidate iterator. - */ - inline T* operator++(int) - { - T *result= current; - if (result) - current= *L::Adapter::next_ptr(current); - return result; - } - /* Operator for ++it */ - inline T* operator++() - { - current= *L::Adapter::next_ptr(current); - return current; - } - inline void rewind() - { - current= list->m_first; - } -}; - - -/** - Hook class which via its methods specifies which members - of T should be used for participating in a intrusive list. -*/ - -template -struct I_P_List_adapter -{ - static inline T **next_ptr(T *el) { return &(el->*next); } - static inline const T* const* next_ptr(const T *el) { return &(el->*next); } - static inline T ***prev_ptr(T *el) { return &(el->*prev); } -}; - - -/** - Element counting policy class for I_P_List to be used in - cases when no element counting should be done. -*/ - -class I_P_List_null_counter -{ -protected: - void reset() {} - void inc() {} - void dec() {} - void swap(I_P_List_null_counter &) {} -}; - - -/** - Element counting policy class for I_P_List which provides - basic element counting. -*/ - -class I_P_List_counter -{ - uint m_counter; -protected: - I_P_List_counter() : m_counter (0) {} - void reset() {m_counter= 0;} - void inc() {m_counter++;} - void dec() {m_counter--;} - void swap(I_P_List_counter &rhs) - { swap_variables(uint, m_counter, rhs.m_counter); } -public: - uint elements() const { return m_counter; } -}; - - -/** - A null insertion policy class for I_P_List to be used - in cases when push_back() operation is not necessary. -*/ - -template class I_P_List_no_push_back -{ -protected: - I_P_List_no_push_back(T **) {} - void set_last(T **) {} - /* - T** get_last() const method is intentionally left unimplemented - in order to prohibit usage of push_back() method in lists which - use this policy. - */ - void swap(I_P_List_no_push_back &) {} -}; - - -/** - An insertion policy class for I_P_List which can - be used when fast push_back() operation is required. -*/ - -template class I_P_List_fast_push_back -{ - T **m_last; -protected: - I_P_List_fast_push_back(T **a) : m_last(a) { }; - void set_last(T **a) { m_last= a; } - T** get_last() const { return m_last; } - void swap(I_P_List_fast_push_back &rhs) - { swap_variables(T**, m_last, rhs.m_last); } -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plugin.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plugin.h deleted file mode 100644 index e136079..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plugin.h +++ /dev/null @@ -1,206 +0,0 @@ -/* Copyright (c) 2005, 2012, Oracle and/or its affiliates. - Copyright (c) 2009, 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _sql_plugin_h -#define _sql_plugin_h - -/* - the following #define adds server-only members to enum_mysql_show_type, - that is defined in plugin.h -*/ -#define SHOW_always_last SHOW_KEY_CACHE_LONG, \ - SHOW_LONG_STATUS, SHOW_DOUBLE_STATUS, \ - SHOW_HAVE, SHOW_MY_BOOL, SHOW_HA_ROWS, SHOW_SYS, \ - SHOW_LONG_NOFLUSH, SHOW_LONGLONG_STATUS, SHOW_UINT32_STATUS, \ - SHOW_LEX_STRING, SHOW_ATOMIC_COUNTER_UINT32_T -#include "mariadb.h" -#undef SHOW_always_last - -#include "m_string.h" /* LEX_STRING */ -#include "my_alloc.h" /* MEM_ROOT */ - -class sys_var; -enum SHOW_COMP_OPTION { SHOW_OPTION_YES, SHOW_OPTION_NO, SHOW_OPTION_DISABLED}; -enum enum_plugin_load_option { PLUGIN_OFF, PLUGIN_ON, PLUGIN_FORCE, - PLUGIN_FORCE_PLUS_PERMANENT }; -extern const char *global_plugin_typelib_names[]; - -extern volatile int global_plugin_version; -extern ulong dlopen_count; - -#include -#include "sql_list.h" - -#ifdef DBUG_OFF -#define plugin_ref_to_int(A) A -#define plugin_int_to_ref(A) A -#else -#define plugin_ref_to_int(A) (A ? A[0] : NULL) -#define plugin_int_to_ref(A) &(A) -#endif - -/* - the following flags are valid for plugin_init() -*/ -#define PLUGIN_INIT_SKIP_PLUGIN_TABLE 1U -#define PLUGIN_INIT_SKIP_INITIALIZATION 2U - -#define INITIAL_LEX_PLUGIN_LIST_SIZE 16 - -typedef enum enum_mysql_show_type SHOW_TYPE; -typedef struct st_mysql_show_var SHOW_VAR; - -#define MYSQL_ANY_PLUGIN -1 - -/* - different values of st_plugin_int::state - though they look like a bitmap, plugin may only - be in one of those eigenstates, not in a superposition of them :) - It's a bitmap, because it makes it easier to test - "whether the state is one of those..." -*/ -#define PLUGIN_IS_FREED 1U -#define PLUGIN_IS_DELETED 2U -#define PLUGIN_IS_UNINITIALIZED 4U -#define PLUGIN_IS_READY 8U -#define PLUGIN_IS_DYING 16U -#define PLUGIN_IS_DISABLED 32U - -struct st_ptr_backup { - void **ptr; - void *value; - void save(void **p) { ptr= p; value= *p; } - void save(const char **p) { save((void**)p); } - void restore() { *ptr= value; } -}; - -/* A handle for the dynamic library containing a plugin or plugins. */ - -struct st_plugin_dl -{ - LEX_CSTRING dl; - void *handle; - struct st_maria_plugin *plugins; - st_ptr_backup *ptr_backup; - uint nbackups; - uint ref_count; /* number of plugins loaded from the library */ - int mysqlversion; - int mariaversion; - bool allocated; -}; - -/* A handle of a plugin */ - -struct st_plugin_int -{ - LEX_CSTRING name; - struct st_maria_plugin *plugin; - struct st_plugin_dl *plugin_dl; - st_ptr_backup *ptr_backup; - uint nbackups; - uint state; - uint ref_count; /* number of threads using the plugin */ - uint locks_total; /* how many times the plugin was locked */ - void *data; /* plugin type specific, e.g. handlerton */ - MEM_ROOT mem_root; /* memory for dynamic plugin structures */ - sys_var *system_vars; /* server variables for this plugin */ - enum enum_plugin_load_option load_option; /* OFF, ON, FORCE, F+PERMANENT */ -}; - - -extern mysql_mutex_t LOCK_plugin; - -/* - See intern_plugin_lock() for the explanation for the - conditionally defined plugin_ref type -*/ -#ifdef DBUG_OFF -typedef struct st_plugin_int *plugin_ref; -#define plugin_ref_to_int(A) A -#define plugin_int_to_ref(A) A -#define plugin_decl(pi) ((pi)->plugin) -#define plugin_dlib(pi) ((pi)->plugin_dl) -#define plugin_data(pi,cast) ((cast)((pi)->data)) -#define plugin_name(pi) (&((pi)->name)) -#define plugin_state(pi) ((pi)->state) -#define plugin_load_option(pi) ((pi)->load_option) -#define plugin_equals(p1,p2) ((p1) == (p2)) -#else -typedef struct st_plugin_int **plugin_ref; -#define plugin_ref_to_int(A) (A ? A[0] : NULL) -#define plugin_int_to_ref(A) &(A) -#define plugin_decl(pi) ((pi)[0]->plugin) -#define plugin_dlib(pi) ((pi)[0]->plugin_dl) -#define plugin_data(pi,cast) ((cast)((pi)[0]->data)) -#define plugin_name(pi) (&((pi)[0]->name)) -#define plugin_state(pi) ((pi)[0]->state) -#define plugin_load_option(pi) ((pi)[0]->load_option) -#define plugin_equals(p1,p2) ((p1) && (p2) && (p1)[0] == (p2)[0]) -#endif - -typedef int (*plugin_type_init)(struct st_plugin_int *); - -extern I_List *opt_plugin_load_list_ptr; -extern char *opt_plugin_dir_ptr; -extern MYSQL_PLUGIN_IMPORT char opt_plugin_dir[FN_REFLEN]; -extern const LEX_CSTRING plugin_type_names[]; -extern ulong plugin_maturity; -extern TYPELIB plugin_maturity_values; -extern const char *plugin_maturity_names[]; - -extern int plugin_init(int *argc, char **argv, int init_flags); -extern void plugin_shutdown(void); -void add_plugin_options(DYNAMIC_ARRAY *options, MEM_ROOT *mem_root); -extern bool plugin_is_ready(const LEX_CSTRING *name, int type); -#define my_plugin_lock_by_name(A,B,C) plugin_lock_by_name(A,B,C) -#define my_plugin_lock(A,B) plugin_lock(A,B) -extern plugin_ref plugin_lock(THD *thd, plugin_ref ptr); -extern plugin_ref plugin_lock_by_name(THD *thd, const LEX_CSTRING *name, - int type); -extern void plugin_unlock(THD *thd, plugin_ref plugin); -extern void plugin_unlock_list(THD *thd, plugin_ref *list, uint count); -extern bool mysql_install_plugin(THD *thd, const LEX_CSTRING *name, - const LEX_CSTRING *dl); -extern bool mysql_uninstall_plugin(THD *thd, const LEX_CSTRING *name, - const LEX_CSTRING *dl); -extern bool plugin_register_builtin(struct st_mysql_plugin *plugin); -extern void plugin_thdvar_init(THD *thd); -extern void plugin_thdvar_cleanup(THD *thd); -sys_var *find_plugin_sysvar(st_plugin_int *plugin, st_mysql_sys_var *var); -void plugin_opt_set_limits(struct my_option *, const struct st_mysql_sys_var *); -extern SHOW_COMP_OPTION plugin_status(const char *name, size_t len, int type); -extern bool check_valid_path(const char *path, size_t length); -extern void plugin_mutex_init(); - -typedef my_bool (plugin_foreach_func)(THD *thd, - plugin_ref plugin, - void *arg); -#define plugin_foreach(A,B,C,D) plugin_foreach_with_mask(A,B,C,PLUGIN_IS_READY,D) -extern bool plugin_foreach_with_mask(THD *thd, plugin_foreach_func *func, - int type, uint state_mask, void *arg); -extern void sync_dynamic_session_variables(THD* thd, bool global_lock); - -extern bool plugin_dl_foreach(THD *thd, const LEX_CSTRING *dl, - plugin_foreach_func *func, void *arg); - -extern void sync_dynamic_session_variables(THD* thd, bool global_lock); -#endif - -#ifdef WITH_WSREP -extern void wsrep_plugins_pre_init(); -extern void wsrep_plugins_post_init(); -#endif /* WITH_WSREP */ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plugin_compat.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plugin_compat.h deleted file mode 100644 index 01b79c5..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_plugin_compat.h +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright (C) 2013 Sergei Golubchik and Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* old plugin api structures, used for backward compatibility */ - -#define upgrade_var(X) latest->X= X -#define upgrade_str(X) strmake_buf(latest->X, X) -#define downgrade_var(X) X= latest->X -#define downgrade_str(X) strmake_buf(X, latest->X) - -/**************************************************************/ -/* Authentication API, version 0x0100 *************************/ -#define MIN_AUTHENTICATION_INTERFACE_VERSION 0x0100 - -struct MYSQL_SERVER_AUTH_INFO_0x0100 { - const char *user_name; - unsigned int user_name_length; - const char *auth_string; - unsigned long auth_string_length; - char authenticated_as[49]; - char external_user[512]; - int password_used; - const char *host_or_ip; - unsigned int host_or_ip_length; - - void upgrade(MYSQL_SERVER_AUTH_INFO *latest) - { - upgrade_var(user_name); - upgrade_var(user_name_length); - upgrade_var(auth_string); - upgrade_var(auth_string_length); - upgrade_str(authenticated_as); - upgrade_str(external_user); - upgrade_var(password_used); - upgrade_var(host_or_ip); - upgrade_var(host_or_ip_length); - } - void downgrade(MYSQL_SERVER_AUTH_INFO *latest) - { - downgrade_var(user_name); - downgrade_var(user_name_length); - downgrade_var(auth_string); - downgrade_var(auth_string_length); - downgrade_str(authenticated_as); - downgrade_str(external_user); - downgrade_var(password_used); - downgrade_var(host_or_ip); - downgrade_var(host_or_ip_length); - } -}; - -/**************************************************************/ - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_prepare.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_prepare.h deleted file mode 100644 index 166be95..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_prepare.h +++ /dev/null @@ -1,354 +0,0 @@ -#ifndef SQL_PREPARE_H -#define SQL_PREPARE_H -/* Copyright (c) 1995-2008 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "sql_error.h" - - -#define LAST_STMT_ID 0xFFFFFFFF -#define STMT_ID_MASK 0x7FFFFFFF - -class THD; -struct LEX; - -/** - An interface that is used to take an action when - the locking module notices that a table version has changed - since the last execution. "Table" here may refer to any kind of - table -- a base table, a temporary table, a view or an - information schema table. - - When we open and lock tables for execution of a prepared - statement, we must verify that they did not change - since statement prepare. If some table did change, the statement - parse tree *may* be no longer valid, e.g. in case it contains - optimizations that depend on table metadata. - - This class provides an interface (a method) that is - invoked when such a situation takes place. - The implementation of the method simply reports an error, but - the exact details depend on the nature of the SQL statement. - - At most 1 instance of this class is active at a time, in which - case THD::m_reprepare_observer is not NULL. - - @sa check_and_update_table_version() for details of the - version tracking algorithm - - @sa Open_tables_state::m_reprepare_observer for the life cycle - of metadata observers. -*/ - -class Reprepare_observer -{ -public: - /** - Check if a change of metadata is OK. In future - the signature of this method may be extended to accept the old - and the new versions, but since currently the check is very - simple, we only need the THD to report an error. - */ - bool report_error(THD *thd); - bool is_invalidated() const { return m_invalidated; } - void reset_reprepare_observer() { m_invalidated= FALSE; } -private: - bool m_invalidated; -}; - - -void mysqld_stmt_prepare(THD *thd, const char *packet, uint packet_length); -void mysqld_stmt_execute(THD *thd, char *packet, uint packet_length); -void mysqld_stmt_execute_bulk(THD *thd, char *packet, uint packet_length); -void mysqld_stmt_bulk_execute(THD *thd, char *packet, uint packet_length); -void mysqld_stmt_close(THD *thd, char *packet); -void mysql_sql_stmt_prepare(THD *thd); -void mysql_sql_stmt_execute(THD *thd); -void mysql_sql_stmt_execute_immediate(THD *thd); -void mysql_sql_stmt_close(THD *thd); -void mysqld_stmt_fetch(THD *thd, char *packet, uint packet_length); -void mysqld_stmt_reset(THD *thd, char *packet); -void mysql_stmt_get_longdata(THD *thd, char *pos, ulong packet_length); -void reinit_stmt_before_use(THD *thd, LEX *lex); - -my_bool bulk_parameters_iterations(THD *thd); -my_bool bulk_parameters_set(THD *thd); -/** - Execute a fragment of server code in an isolated context, so that - it doesn't leave any effect on THD. THD must have no open tables. - The code must not leave any open tables around. - The result of execution (if any) is stored in Ed_result. -*/ - -class Server_runnable -{ -public: - virtual bool execute_server_code(THD *thd)= 0; - virtual ~Server_runnable(); -}; - - -/** - Execute direct interface. - - @todo Implement support for prelocked mode. -*/ - -class Ed_row; - -/** - Ed_result_set -- a container with result set rows. - @todo Implement support for result set metadata and - automatic type conversion. -*/ - -class Ed_result_set: public Sql_alloc -{ -public: - operator List&() { return *m_rows; } - unsigned int size() const { return m_rows->elements; } - - Ed_result_set(List *rows_arg, size_t column_count, - MEM_ROOT *mem_root_arg); - - /** We don't call member destructors, they all are POD types. */ - ~Ed_result_set() {} - - size_t get_field_count() const { return m_column_count; } - - static void operator delete(void *ptr, size_t size) throw (); - static void operator delete(void *, MEM_ROOT *){} -private: - Ed_result_set(const Ed_result_set &); /* not implemented */ - Ed_result_set &operator=(Ed_result_set &); /* not implemented */ -private: - MEM_ROOT m_mem_root; - size_t m_column_count; - List *m_rows; - Ed_result_set *m_next_rset; - friend class Ed_connection; -}; - - -class Ed_connection -{ -public: - /** - Construct a new "execute direct" connection. - - The connection can be used to execute SQL statements. - If the connection failed to initialize, the error - will be returned on the attempt to execute a statement. - - @pre thd must have no open tables - while the connection is used. However, - Ed_connection works okay in LOCK TABLES mode. - Other properties of THD, such as the current warning - information, errors, etc. do not matter and are - preserved by Ed_connection. One thread may have many - Ed_connections created for it. - */ - Ed_connection(THD *thd); - - /** - Execute one SQL statement. - - Until this method is executed, no other methods of - Ed_connection can be used. Life cycle of Ed_connection is: - - Initialized -> a statement has been executed -> - look at result, move to next result -> - look at result, move to next result -> - ... - moved beyond the last result == Initialized. - - This method can be called repeatedly. Once it's invoked, - results of the previous execution are lost. - - A result of execute_direct() can be either: - - - success, no result set rows. In this case get_field_count() - returns 0. This happens after execution of INSERT, UPDATE, - DELETE, DROP and similar statements. Some other methods, such - as get_affected_rows() can be used to retrieve additional - result information. - - - success, there are some result set rows (maybe 0). E.g. - happens after SELECT. In this case get_field_count() returns - the number of columns in a result set and store_result() - can be used to retrieve a result set.. - - - an error, methods to retrieve error information can - be used. - - @return execution status - @retval FALSE success, use get_field_count() - to determine what to do next. - @retval TRUE error, use get_last_error() - to see the error number. - */ - bool execute_direct(Protocol *p, LEX_STRING sql_text); - - /** - Same as the previous, but takes an instance of Server_runnable - instead of SQL statement text. - - @return execution status - - @retval FALSE success, use get_field_count() - if your code fragment is supposed to - return a result set - @retval TRUE failure - */ - bool execute_direct(Protocol *p, Server_runnable *server_runnable); - - /** - Get the number of affected (deleted, updated) - rows for the current statement. Can be - used for statements with get_field_count() == 0. - - @sa Documentation for C API function - mysql_affected_rows(). - */ - ulonglong get_affected_rows() const - { - return m_diagnostics_area.affected_rows(); - } - - /** - Get the last insert id, if any. - - @sa Documentation for mysql_insert_id(). - */ - ulonglong get_last_insert_id() const - { - return m_diagnostics_area.last_insert_id(); - } - - /** - Get the total number of warnings for the last executed - statement. Note, that there is only one warning list even - if a statement returns multiple results. - - @sa Documentation for C API function - mysql_num_warnings(). - */ - ulong get_warn_count() const - { - return m_diagnostics_area.warn_count(); - } - - /** - The following members are only valid if execute_direct() - or move_to_next_result() returned an error. - They never fail, but if they are called when there is no - result, or no error, the result is not defined. - */ - const char *get_last_error() const { return m_diagnostics_area.message(); } - unsigned int get_last_errno() const { return m_diagnostics_area.sql_errno(); } - const char *get_last_sqlstate() const { return m_diagnostics_area.get_sqlstate(); } - - /** - Provided get_field_count() is not 0, this never fails. You don't - need to free the result set, this is done automatically when - you advance to the next result set or destroy the connection. - Not returning const because of List iterator not accepting - Should be used when you would like Ed_connection to manage - result set memory for you. - */ - Ed_result_set *use_result_set() { return m_current_rset; } - /** - Provided get_field_count() is not 0, this never fails. You - must free the returned result set. This can be called only - once after execute_direct(). - Should be used when you would like to get the results - and destroy the connection. - */ - Ed_result_set *store_result_set(); - - /** - If the query returns multiple results, this method - can be checked if there is another result beyond the next - one. - Never fails. - */ - bool has_next_result() const { return MY_TEST(m_current_rset->m_next_rset); } - /** - Only valid to call if has_next_result() returned true. - Otherwise the result is undefined. - */ - bool move_to_next_result() - { - m_current_rset= m_current_rset->m_next_rset; - return MY_TEST(m_current_rset); - } - - ~Ed_connection() { free_old_result(); } -private: - Diagnostics_area m_diagnostics_area; - /** - Execute direct interface does not support multi-statements, only - multi-results. So we never have a situation when we have - a mix of result sets and OK or error packets. We either - have a single result set, a single error, or a single OK, - or we have a series of result sets, followed by an OK or error. - */ - THD *m_thd; - Ed_result_set *m_rsets; - Ed_result_set *m_current_rset; -private: - void free_old_result(); - void add_result_set(Ed_result_set *ed_result_set); -private: - Ed_connection(const Ed_connection &); /* not implemented */ - Ed_connection &operator=(Ed_connection &); /* not implemented */ -}; - - -/** One result set column. */ - -struct Ed_column: public LEX_STRING -{ - /** Implementation note: destructor for this class is never called. */ -}; - - -/** One result set record. */ - -class Ed_row: public Sql_alloc -{ -public: - const Ed_column &operator[](const unsigned int column_index) const - { - return *get_column(column_index); - } - const Ed_column *get_column(const unsigned int column_index) const - { - DBUG_ASSERT(column_index < size()); - return m_column_array + column_index; - } - size_t size() const { return m_column_count; } - - Ed_row(Ed_column *column_array_arg, size_t column_count_arg) - :m_column_array(column_array_arg), - m_column_count(column_count_arg) - {} -private: - Ed_column *m_column_array; - size_t m_column_count; /* TODO: change to point to metadata */ -}; - -#endif // SQL_PREPARE_H diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_priv.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_priv.h deleted file mode 100644 index 07f07a7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_priv.h +++ /dev/null @@ -1,435 +0,0 @@ -/* Copyright (c) 2000, 2018, Oracle and/or its affiliates. - Copyright (c) 2010, 2019, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - @details - Mostly this file is used in the server. But a little part of it is used in - mysqlbinlog too (definition of SELECT_DISTINCT and others). - The consequence is that 90% of the file is wrapped in \#ifndef MYSQL_CLIENT, - except the part which must be in the server and in the client. -*/ - -#ifndef SQL_PRIV_INCLUDED -#define SQL_PRIV_INCLUDED - -#ifndef MYSQL_CLIENT - -/* - Generates a warning that a feature is deprecated. After a specified - version asserts that the feature is removed. - - Using it as - - WARN_DEPRECATED(thd, 6,2, "BAD", "'GOOD'"); - - Will result in a warning - - "The syntax 'BAD' is deprecated and will be removed in MySQL 6.2. Please - use 'GOOD' instead" - - Note that in macro arguments BAD is not quoted, while 'GOOD' is. - Note that the version is TWO numbers, separated with a comma - (two macro arguments, that is) -*/ -#define WARN_DEPRECATED(Thd,VerHi,VerLo,Old,New) \ - do { \ - compile_time_assert(MYSQL_VERSION_ID < VerHi * 10000 + VerLo * 100); \ - if (((THD *) Thd) != NULL) \ - push_warning_printf(((THD *) Thd), Sql_condition::WARN_LEVEL_WARN, \ - ER_WARN_DEPRECATED_SYNTAX, \ - ER_THD(((THD *) Thd), ER_WARN_DEPRECATED_SYNTAX), \ - (Old), (New)); \ - else \ - sql_print_warning("The syntax '%s' is deprecated and will be removed " \ - "in a future release. Please use %s instead.", \ - (Old), (New)); \ - } while(0) - - -/* - Generates a warning that a feature is deprecated and there is no replacement. - - Using it as - - WARN_DEPRECATED_NO_REPLACEMENT(thd, "BAD"); - - Will result in a warning - - "'BAD' is deprecated and will be removed in a future release." - - Note that in macro arguments BAD is not quoted. -*/ - -#define WARN_DEPRECATED_NO_REPLACEMENT(Thd,Old) \ - do { \ - THD *thd_= ((THD*) Thd); \ - if (thd_ != NULL) \ - push_warning_printf(thd_, Sql_condition::WARN_LEVEL_WARN, \ - ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT, \ - ER_THD(thd_, ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT), \ - (Old)); \ - else \ - sql_print_warning("'%s' is deprecated and will be removed " \ - "in a future release.", (Old)); \ - } while(0) - -/*************************************************************************/ - -#endif - -/* - This is included in the server and in the client. - Options for select set by the yacc parser (stored in lex->options). - - NOTE - log_event.h defines OPTIONS_WRITTEN_TO_BIN_LOG to specify what THD - options list are written into binlog. These options can NOT change their - values, or it will break replication between version. - - context is encoded as following: - SELECT - SELECT_LEX_NODE::options - THD - THD::options - intern - neither. used only as - func(..., select_node->options | thd->options | OPTION_XXX, ...) - - TODO: separate three contexts above, move them to separate bitfields. -*/ - -#define SELECT_DISTINCT (1ULL << 0) // SELECT, user -#define SELECT_STRAIGHT_JOIN (1ULL << 1) // SELECT, user -#define SELECT_DESCRIBE (1ULL << 2) // SELECT, user -#define SELECT_SMALL_RESULT (1ULL << 3) // SELECT, user -#define SELECT_BIG_RESULT (1ULL << 4) // SELECT, user -#define OPTION_FOUND_ROWS (1ULL << 5) // SELECT, user -#define OPTION_TO_QUERY_CACHE (1ULL << 6) // SELECT, user -#define SELECT_NO_JOIN_CACHE (1ULL << 7) // intern -/** always the opposite of OPTION_NOT_AUTOCOMMIT except when in fix_autocommit() */ -#define OPTION_AUTOCOMMIT (1ULL << 8) // THD, user -#define OPTION_BIG_SELECTS (1ULL << 9) // THD, user -#define OPTION_LOG_OFF (1ULL << 10) // THD, user -#define OPTION_QUOTE_SHOW_CREATE (1ULL << 11) // THD, user -#define TMP_TABLE_ALL_COLUMNS (1ULL << 12) // SELECT, intern -#define OPTION_WARNINGS (1ULL << 13) // THD, user -#define OPTION_AUTO_IS_NULL (1ULL << 14) // THD, user, binlog -#define OPTION_NO_CHECK_CONSTRAINT_CHECKS (1ULL << 15) -#define OPTION_SAFE_UPDATES (1ULL << 16) // THD, user -#define OPTION_BUFFER_RESULT (1ULL << 17) // SELECT, user -#define OPTION_BIN_LOG (1ULL << 18) // THD, user -#define OPTION_NOT_AUTOCOMMIT (1ULL << 19) // THD, user -#define OPTION_BEGIN (1ULL << 20) // THD, intern -#define OPTION_TABLE_LOCK (1ULL << 21) // THD, intern -#define OPTION_QUICK (1ULL << 22) // SELECT (for DELETE) -#define OPTION_KEEP_LOG (1ULL << 23) // THD, user - -/* The following is used to detect a conflict with DISTINCT */ -#define SELECT_ALL (1ULL << 24) // SELECT, user, parser -#define OPTION_GTID_BEGIN (1ULL << 25) // GTID BEGIN found in log - -/** The following can be set when importing tables in a 'wrong order' - to suppress foreign key checks */ -#define OPTION_NO_FOREIGN_KEY_CHECKS (1ULL << 26) // THD, user, binlog -/** The following speeds up inserts to InnoDB tables by suppressing unique - key checks in some cases */ -#define OPTION_RELAXED_UNIQUE_CHECKS (1ULL << 27) // THD, user, binlog -#define OPTION_IF_EXISTS (1ULL << 28) // binlog -#define OPTION_SCHEMA_TABLE (1ULL << 29) // SELECT, intern -/** Flag set if setup_tables already done */ -#define OPTION_SETUP_TABLES_DONE (1ULL << 30) // intern -/** If not set then the thread will ignore all warnings with level notes. */ -#define OPTION_SQL_NOTES (1ULL << 31) // THD, user -/** - Force the used temporary table to be a MyISAM table (because we will use - fulltext functions when reading from it. -*/ -#define TMP_TABLE_FORCE_MYISAM (1ULL << 32) -#define OPTION_PROFILING (1ULL << 33) -/** - Indicates that this is a HIGH_PRIORITY SELECT. - Currently used only for printing of such selects. - Type of locks to be acquired is specified directly. -*/ -#define SELECT_HIGH_PRIORITY (1ULL << 34) // SELECT, user -/** - Is set in slave SQL thread when there was an - error on master, which, when is not reproducible - on slave (i.e. the query succeeds on slave), - is not terminal to the state of repliation, - and should be ignored. The slave SQL thread, - however, needs to rollback the effects of the - succeeded statement to keep replication consistent. -*/ -#define OPTION_MASTER_SQL_ERROR (1ULL << 35) - -#define OPTION_SKIP_REPLICATION (1ULL << 37) // THD, user -#define OPTION_RPL_SKIP_PARALLEL (1ULL << 38) -#define OPTION_NO_QUERY_CACHE (1ULL << 39) // SELECT, user -#define OPTION_PROCEDURE_CLAUSE (1ULL << 40) // Internal usage -#define SELECT_NO_UNLOCK (1ULL << 41) // SELECT, intern -#define SELECT_NO_UNLOCK (1ULL << 41) // SELECT, intern -#define OPTION_BIN_TMP_LOG_OFF (1ULL << 42) // disable binlog, intern -/* Disable commit of binlog. Used to combine many DDL's and DML's as one */ -#define OPTION_BIN_COMMIT_OFF (1ULL << 43) - -#define OPTION_LEX_FOUND_COMMENT (1ULL << 0) // intern, parser - -/* The rest of the file is included in the server only */ -#ifndef MYSQL_CLIENT - -/* @@optimizer_switch flags. These must be in sync with optimizer_switch_typelib */ -#define OPTIMIZER_SWITCH_INDEX_MERGE (1ULL << 0) -#define OPTIMIZER_SWITCH_INDEX_MERGE_UNION (1ULL << 1) -#define OPTIMIZER_SWITCH_INDEX_MERGE_SORT_UNION (1ULL << 2) -#define OPTIMIZER_SWITCH_INDEX_MERGE_INTERSECT (1ULL << 3) -#define OPTIMIZER_SWITCH_INDEX_MERGE_SORT_INTERSECT (1ULL << 4) -#define deprecated_ENGINE_CONDITION_PUSHDOWN (1ULL << 5) -#define OPTIMIZER_SWITCH_INDEX_COND_PUSHDOWN (1ULL << 6) -#define OPTIMIZER_SWITCH_DERIVED_MERGE (1ULL << 7) -#define OPTIMIZER_SWITCH_DERIVED_WITH_KEYS (1ULL << 8) -#define OPTIMIZER_SWITCH_FIRSTMATCH (1ULL << 9) -#define OPTIMIZER_SWITCH_LOOSE_SCAN (1ULL << 10) -#define OPTIMIZER_SWITCH_MATERIALIZATION (1ULL << 11) -#define OPTIMIZER_SWITCH_IN_TO_EXISTS (1ULL << 12) -#define OPTIMIZER_SWITCH_SEMIJOIN (1ULL << 13) -#define OPTIMIZER_SWITCH_PARTIAL_MATCH_ROWID_MERGE (1ULL << 14) -#define OPTIMIZER_SWITCH_PARTIAL_MATCH_TABLE_SCAN (1ULL << 15) -#define OPTIMIZER_SWITCH_SUBQUERY_CACHE (1ULL << 16) -/** If this is off, MRR is never used. */ -#define OPTIMIZER_SWITCH_MRR (1ULL << 17) -/** - If OPTIMIZER_SWITCH_MRR is on and this is on, MRR is used depending on a - cost-based choice ("automatic"). If OPTIMIZER_SWITCH_MRR is on and this is - off, MRR is "forced" (i.e. used as long as the storage engine is capable of - doing it). -*/ -#define OPTIMIZER_SWITCH_MRR_COST_BASED (1ULL << 18) -#define OPTIMIZER_SWITCH_MRR_SORT_KEYS (1ULL << 19) -#define OPTIMIZER_SWITCH_OUTER_JOIN_WITH_CACHE (1ULL << 20) -#define OPTIMIZER_SWITCH_SEMIJOIN_WITH_CACHE (1ULL << 21) -#define OPTIMIZER_SWITCH_JOIN_CACHE_INCREMENTAL (1ULL << 22) -#define OPTIMIZER_SWITCH_JOIN_CACHE_HASHED (1ULL << 23) -#define OPTIMIZER_SWITCH_JOIN_CACHE_BKA (1ULL << 24) -#define OPTIMIZER_SWITCH_OPTIMIZE_JOIN_BUFFER_SIZE (1ULL << 25) -#define OPTIMIZER_SWITCH_TABLE_ELIMINATION (1ULL << 26) -#define OPTIMIZER_SWITCH_EXTENDED_KEYS (1ULL << 27) -#define OPTIMIZER_SWITCH_EXISTS_TO_IN (1ULL << 28) -#define OPTIMIZER_SWITCH_ORDERBY_EQ_PROP (1ULL << 29) -#define OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_DERIVED (1ULL << 30) -#define OPTIMIZER_SWITCH_SPLIT_MATERIALIZED (1ULL << 31) -#define OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_SUBQUERY (1ULL << 32) -#define OPTIMIZER_SWITCH_USE_ROWID_FILTER (1ULL << 33) -#define OPTIMIZER_SWITCH_COND_PUSHDOWN_FROM_HAVING (1ULL << 34) -#define OPTIMIZER_SWITCH_NOT_NULL_RANGE_SCAN (1ULL << 35) - -#define OPTIMIZER_SWITCH_DEFAULT (OPTIMIZER_SWITCH_INDEX_MERGE | \ - OPTIMIZER_SWITCH_INDEX_MERGE_UNION | \ - OPTIMIZER_SWITCH_INDEX_MERGE_SORT_UNION | \ - OPTIMIZER_SWITCH_INDEX_MERGE_INTERSECT | \ - OPTIMIZER_SWITCH_INDEX_COND_PUSHDOWN | \ - OPTIMIZER_SWITCH_DERIVED_MERGE | \ - OPTIMIZER_SWITCH_DERIVED_WITH_KEYS | \ - OPTIMIZER_SWITCH_TABLE_ELIMINATION | \ - OPTIMIZER_SWITCH_EXTENDED_KEYS | \ - OPTIMIZER_SWITCH_IN_TO_EXISTS | \ - OPTIMIZER_SWITCH_MATERIALIZATION | \ - OPTIMIZER_SWITCH_PARTIAL_MATCH_ROWID_MERGE|\ - OPTIMIZER_SWITCH_PARTIAL_MATCH_TABLE_SCAN|\ - OPTIMIZER_SWITCH_OUTER_JOIN_WITH_CACHE | \ - OPTIMIZER_SWITCH_SEMIJOIN_WITH_CACHE | \ - OPTIMIZER_SWITCH_JOIN_CACHE_INCREMENTAL | \ - OPTIMIZER_SWITCH_JOIN_CACHE_HASHED | \ - OPTIMIZER_SWITCH_JOIN_CACHE_BKA | \ - OPTIMIZER_SWITCH_SUBQUERY_CACHE | \ - OPTIMIZER_SWITCH_SEMIJOIN | \ - OPTIMIZER_SWITCH_FIRSTMATCH | \ - OPTIMIZER_SWITCH_LOOSE_SCAN | \ - OPTIMIZER_SWITCH_EXISTS_TO_IN | \ - OPTIMIZER_SWITCH_ORDERBY_EQ_PROP | \ - OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_DERIVED | \ - OPTIMIZER_SWITCH_SPLIT_MATERIALIZED | \ - OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_SUBQUERY | \ - OPTIMIZER_SWITCH_USE_ROWID_FILTER | \ - OPTIMIZER_SWITCH_COND_PUSHDOWN_FROM_HAVING | \ - OPTIMIZER_SWITCH_OPTIMIZE_JOIN_BUFFER_SIZE) - -/* - Replication uses 8 bytes to store SQL_MODE in the binary log. The day you - use strictly more than 64 bits by adding one more define above, you should - contact the replication team because the replication code should then be - updated (to store more bytes on disk). - - NOTE: When adding new SQL_MODE types, make sure to also add them to - the scripts used for creating the MySQL system tables - in scripts/mysql_system_tables.sql and scripts/mysql_system_tables_fix.sql - -*/ - -/* - Flags below are set when we perform - context analysis of the statement and make - subqueries non-const. It prevents subquery - evaluation at context analysis stage. -*/ - -/* - Don't evaluate this subquery during statement prepare even if - it's a constant one. The flag is switched off in the end of - mysqld_stmt_prepare. -*/ -#define CONTEXT_ANALYSIS_ONLY_PREPARE 1 -/* - Special JOIN::prepare mode: changing of query is prohibited. - When creating a view, we need to just check its syntax omitting - any optimizations: afterwards definition of the view will be - reconstructed by means of ::print() methods and written to - to an .frm file. We need this definition to stay untouched. -*/ -#define CONTEXT_ANALYSIS_ONLY_VIEW 2 -/* - Don't evaluate this subquery during derived table prepare even if - it's a constant one. -*/ -#define CONTEXT_ANALYSIS_ONLY_DERIVED 4 -/* - Don't evaluate constant sub-expressions of virtual column - expressions when opening tables -*/ -#define CONTEXT_ANALYSIS_ONLY_VCOL_EXPR 8 - - -/* - Uncachable causes: -*/ -/* This subquery has fields from outer query (put by user) */ -#define UNCACHEABLE_DEPENDENT_GENERATED 1 -/* This subquery contains functions with random result */ -#define UNCACHEABLE_RAND 2 -/* This subquery contains functions with side effect */ -#define UNCACHEABLE_SIDEEFFECT 4 -/* Forcing to save JOIN tables for explain */ -#define UNCACHEABLE_EXPLAIN 8 -/* For uncorrelated SELECT in an UNION with some correlated SELECTs */ -#define UNCACHEABLE_UNITED 16 -#define UNCACHEABLE_CHECKOPTION 32 -/* - This subquery has fields from outer query injected during - transformation process -*/ -#define UNCACHEABLE_DEPENDENT_INJECTED 64 -/* This subquery has fields from outer query (any nature) */ -#define UNCACHEABLE_DEPENDENT (UNCACHEABLE_DEPENDENT_GENERATED | \ - UNCACHEABLE_DEPENDENT_INJECTED) - -/* Used to check GROUP BY list in the MODE_ONLY_FULL_GROUP_BY mode */ -#define UNDEF_POS (-1) - -#define IN_SUBQUERY_CONVERSION_THRESHOLD 1000 - -#endif /* !MYSQL_CLIENT */ - -/* BINLOG_DUMP options */ - -#define BINLOG_DUMP_NON_BLOCK 1 -#define BINLOG_SEND_ANNOTATE_ROWS_EVENT 2 - -#ifndef MYSQL_CLIENT - -/* - Field::is_equal() return codes. -*/ -#define IS_EQUAL_NO 0 -#define IS_EQUAL_YES 1 -/** - new_field has compatible packed representation with old type, - so it is theoretically possible to perform change by only updating - data dictionary without changing table rows -*/ -#define IS_EQUAL_PACK_LENGTH 2 - -enum enum_parsing_place -{ - NO_MATTER, - IN_HAVING, - SELECT_LIST, - IN_WHERE, - IN_ON, - IN_GROUP_BY, - IN_ORDER_BY, - IN_UPDATE_ON_DUP_KEY, - IN_PART_FUNC, - BEFORE_OPT_LIST, - AFTER_LIST, - FOR_LOOP_BOUND, - PARSING_PLACE_SIZE /* always should be the last */ -}; - - -class sys_var; - -enum enum_yes_no_unknown -{ - TVL_YES, TVL_NO, TVL_UNKNOWN -}; - -#ifdef MYSQL_SERVER - -/* - External variables -*/ - - -/* sql_yacc.cc */ -#ifndef DBUG_OFF -extern void turn_parser_debug_on_MYSQLparse(); -extern void turn_parser_debug_on_ORAparse(); - -#endif - -/** - convert a hex digit into number. -*/ - -inline int hexchar_to_int(char c) -{ - if (c <= '9' && c >= '0') - return c-'0'; - c|=32; - if (c <= 'f' && c >= 'a') - return c-'a'+10; - return -1; -} - -/* This must match the path length limit in the ER_NOT_RW_DIR error msg. */ -#define ER_NOT_RW_DIR_PATHSIZE 200 - -#define IS_TABLESPACES_TABLESPACE_NAME 0 -#define IS_TABLESPACES_ENGINE 1 -#define IS_TABLESPACES_TABLESPACE_TYPE 2 -#define IS_TABLESPACES_LOGFILE_GROUP_NAME 3 -#define IS_TABLESPACES_EXTENT_SIZE 4 -#define IS_TABLESPACES_AUTOEXTEND_SIZE 5 -#define IS_TABLESPACES_MAXIMUM_SIZE 6 -#define IS_TABLESPACES_NODEGROUP_ID 7 -#define IS_TABLESPACES_TABLESPACE_COMMENT 8 - -bool db_name_is_in_ignore_db_dirs_list(const char *dbase); - -#endif /* MYSQL_SERVER */ - -#endif /* MYSQL_CLIENT */ - -#endif /* SQL_PRIV_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_profile.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_profile.h deleted file mode 100644 index 85018a2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_profile.h +++ /dev/null @@ -1,336 +0,0 @@ -/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _SQL_PROFILE_H -#define _SQL_PROFILE_H - -class Item; -struct TABLE_LIST; -class THD; -class ST_FIELD_INFO; -typedef struct st_schema_table ST_SCHEMA_TABLE; - -namespace Show { -extern ST_FIELD_INFO query_profile_statistics_info[]; -} // namespace Show - -int fill_query_profile_statistics_info(THD *thd, TABLE_LIST *tables, Item *cond); -int make_profile_table_for_show(THD *thd, ST_SCHEMA_TABLE *schema_table); - - -#define PROFILE_NONE (uint)0 -#define PROFILE_CPU (uint)(1<<0) -#define PROFILE_MEMORY (uint)(1<<1) -#define PROFILE_BLOCK_IO (uint)(1<<2) -#define PROFILE_CONTEXT (uint)(1<<3) -#define PROFILE_PAGE_FAULTS (uint)(1<<4) -#define PROFILE_IPC (uint)(1<<5) -#define PROFILE_SWAPS (uint)(1<<6) -#define PROFILE_SOURCE (uint)(1<<16) -#define PROFILE_ALL (uint)(~0) - - -#if defined(ENABLED_PROFILING) -#include "sql_priv.h" -#include "unireg.h" - -#ifdef __WIN__ -#include -#endif - -#ifdef HAVE_SYS_RESOURCE_H -#include -#endif - -extern PSI_memory_key key_memory_queue_item; - -class PROF_MEASUREMENT; -class QUERY_PROFILE; -class PROFILING; - - -/** - Implements a persistent FIFO using server List method names. Not - thread-safe. Intended to be used on thread-local data only. -*/ -template class Queue -{ -private: - - struct queue_item - { - T *payload; - struct queue_item *next, *previous; - }; - - struct queue_item *first, *last; - -public: - Queue() - { - elements= 0; - first= last= NULL; - } - - void empty() - { - struct queue_item *i, *after_i; - for (i= first; i != NULL; i= after_i) - { - after_i= i->next; - my_free(i); - } - elements= 0; - } - - ulong elements; /* The count of items in the Queue */ - - void push_back(T *payload) - { - struct queue_item *new_item; - - new_item= (struct queue_item *) my_malloc(key_memory_queue_item, - sizeof(struct queue_item), MYF(0)); - - new_item->payload= payload; - - if (first == NULL) - first= new_item; - if (last != NULL) - { - DBUG_ASSERT(last->next == NULL); - last->next= new_item; - } - new_item->previous= last; - new_item->next= NULL; - last= new_item; - - elements++; - } - - T *pop() - { - struct queue_item *old_item= first; - T *ret= NULL; - - if (first == NULL) - { - DBUG_PRINT("warning", ("tried to pop nonexistent item from Queue")); - return NULL; - } - - ret= old_item->payload; - if (first->next != NULL) - first->next->previous= NULL; - else - last= NULL; - first= first->next; - - my_free(old_item); - elements--; - - return ret; - } - - bool is_empty() - { - DBUG_ASSERT(((elements > 0) && (first != NULL)) || ((elements == 0) || (first == NULL))); - return (elements == 0); - } - - void *new_iterator() - { - return first; - } - - void *iterator_next(void *current) - { - return ((struct queue_item *) current)->next; - } - - T *iterator_value(void *current) - { - return ((struct queue_item *) current)->payload; - } - -}; - - -/** - A single entry in a single profile. -*/ -class PROF_MEASUREMENT -{ -private: - friend class QUERY_PROFILE; - friend class PROFILING; - - QUERY_PROFILE *profile; - char *status; -#ifdef HAVE_GETRUSAGE - struct rusage rusage; -#elif defined(_WIN32) - FILETIME ftKernel, ftUser; - IO_COUNTERS io_count; - PROCESS_MEMORY_COUNTERS mem_count; -#endif - - char *function; - char *file; - unsigned int line; - - ulong m_seq; - double time_usecs; - char *allocated_status_memory; - - void set_label(const char *status_arg, const char *function_arg, - const char *file_arg, unsigned int line_arg); - void clean_up(); - - PROF_MEASUREMENT(); - PROF_MEASUREMENT(QUERY_PROFILE *profile_arg, const char *status_arg); - PROF_MEASUREMENT(QUERY_PROFILE *profile_arg, const char *status_arg, - const char *function_arg, - const char *file_arg, unsigned int line_arg); - ~PROF_MEASUREMENT(); - void collect(); -}; - - -/** - The full profile for a single query, and includes multiple PROF_MEASUREMENT - objects. -*/ -class QUERY_PROFILE -{ -private: - friend class PROFILING; - - PROFILING *profiling; - - query_id_t profiling_query_id; /* Session-specific id. */ - char *query_source; - - double m_start_time_usecs; - double m_end_time_usecs; - ulong m_seq_counter; - Queue entries; - - - QUERY_PROFILE(PROFILING *profiling_arg, const char *status_arg); - ~QUERY_PROFILE(); - - void set_query_source(char *query_source_arg, size_t query_length_arg); - - /* Add a profile status change to the current profile. */ - void new_status(const char *status_arg, - const char *function_arg, - const char *file_arg, unsigned int line_arg); - - /* Reset the contents of this profile entry. */ - void reset(); - - /* Show this profile. This is called by PROFILING. */ - bool show(uint options); -}; - - -/** - Profiling state for a single THD; contains multiple QUERY_PROFILE objects. -*/ -class PROFILING -{ -private: - friend class PROF_MEASUREMENT; - friend class QUERY_PROFILE; - - /* - Not the system query_id, but a counter unique to profiling. - */ - query_id_t profile_id_counter; - THD *thd; - bool keeping; - bool enabled; - - QUERY_PROFILE *current; - QUERY_PROFILE *last; - Queue history; - - query_id_t next_profile_id() { return(profile_id_counter++); } - -public: - PROFILING(); - ~PROFILING(); - - /** - At a point in execution where we know the query source, save the text - of it in the query profile. - - This must be called exactly once per descrete statement. - */ - void set_query_source(char *query_source_arg, size_t query_length_arg) - { - if (unlikely(current)) - current->set_query_source(query_source_arg, query_length_arg); - } - - /** - Prepare to start processing a new query. It is an error to do this - if there's a query already in process; nesting is not supported. - - @param initial_state (optional) name of period before first state change - */ - void start_new_query(const char *initial_state= "Starting") - { - DBUG_ASSERT(!current); - if (unlikely(enabled)) - current= new QUERY_PROFILE(this, initial_state); - } - - void discard_current_query(); - - void finish_current_query() - { - if (unlikely(current)) - finish_current_query_impl(); - } - - void finish_current_query_impl(); - - void status_change(const char *status_arg, - const char *function_arg, - const char *file_arg, unsigned int line_arg) - { - if (unlikely(current)) - current->new_status(status_arg, function_arg, file_arg, line_arg); - } - - inline void set_thd(THD *thd_arg) - { - thd= thd_arg; - reset(); - } - - /* SHOW PROFILES */ - bool show_profiles(); - - /* ... from INFORMATION_SCHEMA.PROFILING ... */ - int fill_statistics_info(THD *thd, TABLE_LIST *tables, Item *cond); - void reset(); - void restart(); -}; - -# endif /* ENABLED_PROFILING */ -#endif /* _SQL_PROFILE_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_reload.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_reload.h deleted file mode 100644 index 699912e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_reload.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef SQL_RELOAD_INCLUDED -#define SQL_RELOAD_INCLUDED -/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -class THD; -struct TABLE_LIST; - -bool reload_acl_and_cache(THD *thd, unsigned long long options, - TABLE_LIST *tables, int *write_to_binlog); - -bool flush_tables_with_read_lock(THD *thd, TABLE_LIST *all_tables); - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_rename.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_rename.h deleted file mode 100644 index 1f5f94b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_rename.h +++ /dev/null @@ -1,25 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_RENAME_INCLUDED -#define SQL_RENAME_INCLUDED - -class THD; -struct TABLE_LIST; - -bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent, - bool if_exists); - -#endif /* SQL_RENAME_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_repl.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_repl.h deleted file mode 100644 index 18aa7ea..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_repl.h +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_REPL_INCLUDED -#define SQL_REPL_INCLUDED - -#include "rpl_filter.h" - -#ifdef HAVE_REPLICATION -#include "slave.h" - -struct slave_connection_state; - -extern my_bool opt_show_slave_auth_info; -extern char *master_host, *master_info_file; - -extern int max_binlog_dump_events; -extern my_bool opt_sporadic_binlog_dump_fail; - -int start_slave(THD* thd, Master_info* mi, bool net_report); -int stop_slave(THD* thd, Master_info* mi, bool net_report); -bool change_master(THD* thd, Master_info* mi, bool *master_info_added); -bool mysql_show_binlog_events(THD* thd); -int reset_slave(THD *thd, Master_info* mi); -int reset_master(THD* thd, rpl_gtid *init_state, uint32 init_state_len, - ulong next_log_number); -bool purge_master_logs(THD* thd, const char* to_log); -bool purge_master_logs_before_date(THD* thd, time_t purge_time); -bool log_in_use(const char* log_name); -void adjust_linfo_offsets(my_off_t purge_offset); -void show_binlogs_get_fields(THD *thd, List *field_list); -bool show_binlogs(THD* thd); -extern int init_master_info(Master_info* mi); -void kill_zombie_dump_threads(uint32 slave_server_id); -int check_binlog_magic(IO_CACHE* log, const char** errmsg); - -struct LOAD_FILE_IO_CACHE : public IO_CACHE -{ - THD* thd; - my_off_t last_pos_in_file; - bool wrote_create_file, log_delayed; - int (*real_read_function)(struct st_io_cache *,uchar *,size_t); -}; - -int log_loaded_block(IO_CACHE* file, uchar *Buffer, size_t Count); -int init_replication_sys_vars(); -void mysql_binlog_send(THD* thd, char* log_ident, my_off_t pos, ushort flags); - -#ifdef HAVE_PSI_INTERFACE -extern PSI_mutex_key key_LOCK_slave_state, key_LOCK_binlog_state; -#endif -void rpl_init_gtid_slave_state(); -void rpl_deinit_gtid_slave_state(); -void rpl_init_gtid_waiting(); -void rpl_deinit_gtid_waiting(); -int gtid_state_from_binlog_pos(const char *name, uint32 pos, String *out_str); -int rpl_append_gtid_state(String *dest, bool use_binlog); -int rpl_load_gtid_state(slave_connection_state *state, bool use_binlog); -bool rpl_gtid_pos_check(THD *thd, char *str, size_t len); -bool rpl_gtid_pos_update(THD *thd, char *str, size_t len); -#else - -struct LOAD_FILE_IO_CACHE : public IO_CACHE { }; - -#endif /* HAVE_REPLICATION */ - -#endif /* SQL_REPL_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_schema.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_schema.h deleted file mode 100644 index 886a115..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_schema.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef SQL_SCHEMA_H_INCLUDED -#define SQL_SCHEMA_H_INCLUDED -/* - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "mysqld.h" -#include "lex_string.h" - -class Schema -{ - LEX_CSTRING m_name; -public: - Schema(const LEX_CSTRING &name) - :m_name(name) - { } - virtual ~Schema() { } - const LEX_CSTRING &name() const { return m_name; } - virtual const Type_handler *map_data_type(THD *thd, const Type_handler *src) - const - { - return src; - } - /* - For now we have *hard-coded* compatibility schemas: - schema_mariadb, schema_oracle, schema_maxdb. - But eventually we'll turn then into real databases on disk. - So the code below compares names according to the filesystem - case sensitivity, like it is done for regular databases. - - Note, this is different to information_schema, whose name - is always case insensitive. This is intentional! - The assymetry will be gone when we'll implement SQL standard - regular and delimited identifiers. - */ - bool eq_name(const LEX_CSTRING &name) const - { - return !table_alias_charset->strnncoll(m_name.str, m_name.length, - name.str, name.length); - } - static Schema *find_by_name(const LEX_CSTRING &name); - static Schema *find_implied(THD *thd); -}; - - -extern Schema mariadb_schema; - -#endif // SQL_SCHEMA_H_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_select.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_select.h deleted file mode 100644 index bb9ecf8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_select.h +++ /dev/null @@ -1,2535 +0,0 @@ -#ifndef SQL_SELECT_INCLUDED -#define SQL_SELECT_INCLUDED - -/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. - Copyright (c) 2008, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - - @brief - classes to use when handling where clause -*/ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "procedure.h" -#include "sql_array.h" /* Array */ -#include "records.h" /* READ_RECORD */ -#include "opt_range.h" /* SQL_SELECT, QUICK_SELECT_I */ -#include "filesort.h" - -typedef struct st_join_table JOIN_TAB; -/* Values in optimize */ -#define KEY_OPTIMIZE_EXISTS 1U -#define KEY_OPTIMIZE_REF_OR_NULL 2U -#define KEY_OPTIMIZE_EQ 4U - -inline uint get_hash_join_key_no() { return MAX_KEY; } - -inline bool is_hash_join_key_no(uint key) { return key == MAX_KEY; } - -typedef struct keyuse_t { - TABLE *table; - Item *val; /**< or value if no field */ - table_map used_tables; - uint key, keypart, optimize; - key_part_map keypart_map; - ha_rows ref_table_rows; - /** - If true, the comparison this value was created from will not be - satisfied if val has NULL 'value'. - */ - bool null_rejecting; - /* - !NULL - This KEYUSE was created from an equality that was wrapped into - an Item_func_trig_cond. This means the equality (and validity of - this KEYUSE element) can be turned on and off. The on/off state - is indicted by the pointed value: - *cond_guard == TRUE <=> equality condition is on - *cond_guard == FALSE <=> equality condition is off - - NULL - Otherwise (the source equality can't be turned off) - */ - bool *cond_guard; - /* - 0..64 <=> This was created from semi-join IN-equality # sj_pred_no. - MAX_UINT Otherwise - */ - uint sj_pred_no; - - /* - If this is NULL than KEYUSE is always enabled. - Otherwise it points to the enabling flag for this keyuse (true <=> enabled) - */ - bool *validity_ref; - - bool is_for_hash_join() { return is_hash_join_key_no(key); } -} KEYUSE; - - -struct KEYUSE_EXT: public KEYUSE -{ - /* - This keyuse can be used only when the partial join being extended - contains the tables from this table map - */ - table_map needed_in_prefix; - /* The enabling flag for keyuses usable for splitting */ - bool validity_var; -}; - -/// Used when finding key fields -struct KEY_FIELD { - Field *field; - Item_bool_func *cond; - Item *val; ///< May be empty if diff constant - uint level; - uint optimize; - bool eq_func; - /** - If true, the condition this struct represents will not be satisfied - when val IS NULL. - */ - bool null_rejecting; - bool *cond_guard; /* See KEYUSE::cond_guard */ - uint sj_pred_no; /* See KEYUSE::sj_pred_no */ -}; - - -#define NO_KEYPART ((uint)(-1)) - -class store_key; - -const int NO_REF_PART= uint(-1); - -typedef struct st_table_ref -{ - bool key_err; - /** True if something was read into buffer in join_read_key. */ - bool has_record; - uint key_parts; ///< num of ... - uint key_length; ///< length of key_buff - int key; ///< key no - uchar *key_buff; ///< value to look for with key - uchar *key_buff2; ///< key_buff+key_length - store_key **key_copy; // - - /* - Bitmap of key parts which refer to constants. key_copy only has copiers for - non-const key parts. - */ - key_part_map const_ref_part_map; - - Item **items; ///< val()'s for each keypart - /* - Array of pointers to trigger variables. Some/all of the pointers may be - NULL. The ref access can be used iff - - for each used key part i, (!cond_guards[i] || *cond_guards[i]) - - This array is used by subquery code. The subquery code may inject - triggered conditions, i.e. conditions that can be 'switched off'. A ref - access created from such condition is not valid when at least one of the - underlying conditions is switched off (see subquery code for more details) - */ - bool **cond_guards; - /** - (null_rejecting & (1< disable the "cache" as doing lookup with the same key value may - produce different results (because of Index Condition Pushdown) - - */ - bool disable_cache; - - bool tmp_table_index_lookup_init(THD *thd, KEY *tmp_key, Item_iterator &it, - bool value, uint skip= 0); - bool is_access_triggered(); -} TABLE_REF; - - -/* - The structs which holds the join connections and join states -*/ -enum join_type { JT_UNKNOWN,JT_SYSTEM,JT_CONST,JT_EQ_REF,JT_REF,JT_MAYBE_REF, - JT_ALL, JT_RANGE, JT_NEXT, JT_FT, JT_REF_OR_NULL, - JT_UNIQUE_SUBQUERY, JT_INDEX_SUBQUERY, JT_INDEX_MERGE, - JT_HASH, JT_HASH_RANGE, JT_HASH_NEXT, JT_HASH_INDEX_MERGE}; - -class JOIN; - -enum enum_nested_loop_state -{ - NESTED_LOOP_KILLED= -2, NESTED_LOOP_ERROR= -1, - NESTED_LOOP_OK= 0, NESTED_LOOP_NO_MORE_ROWS= 1, - NESTED_LOOP_QUERY_LIMIT= 3, NESTED_LOOP_CURSOR_LIMIT= 4 -}; - - -/* Possible sj_strategy values */ -enum sj_strategy_enum -{ - SJ_OPT_NONE=0, - SJ_OPT_DUPS_WEEDOUT=1, - SJ_OPT_LOOSE_SCAN =2, - SJ_OPT_FIRST_MATCH =3, - SJ_OPT_MATERIALIZE =4, - SJ_OPT_MATERIALIZE_SCAN=5 -}; - -/* Values for JOIN_TAB::packed_info */ -#define TAB_INFO_HAVE_VALUE 1U -#define TAB_INFO_USING_INDEX 2U -#define TAB_INFO_USING_WHERE 4U -#define TAB_INFO_FULL_SCAN_ON_NULL 8U - -typedef enum_nested_loop_state -(*Next_select_func)(JOIN *, struct st_join_table *, bool); -Next_select_func setup_end_select_func(JOIN *join, JOIN_TAB *tab); -int rr_sequential(READ_RECORD *info); -int rr_sequential_and_unpack(READ_RECORD *info); -Item *remove_pushed_top_conjuncts(THD *thd, Item *cond); -Item *and_new_conditions_to_optimized_cond(THD *thd, Item *cond, - COND_EQUAL **cond_eq, - List &new_conds, - Item::cond_result *cond_value); - -#include "sql_explain.h" - -/************************************************************************************** - * New EXPLAIN structures END - *************************************************************************************/ - -class JOIN_CACHE; -class SJ_TMP_TABLE; -class JOIN_TAB_RANGE; -class AGGR_OP; -class Filesort; -struct SplM_plan_info; -class SplM_opt_info; - -typedef struct st_join_table { - TABLE *table; - TABLE_LIST *tab_list; - KEYUSE *keyuse; /**< pointer to first used key */ - KEY *hj_key; /**< descriptor of the used best hash join key - not supported by any index */ - SQL_SELECT *select; - COND *select_cond; - COND *on_precond; /**< part of on condition to check before - accessing the first inner table */ - QUICK_SELECT_I *quick; - /* - The value of select_cond before we've attempted to do Index Condition - Pushdown. We may need to restore everything back if we first choose one - index but then reconsider (see test_if_skip_sort_order() for such - scenarios). - NULL means no index condition pushdown was performed. - */ - Item *pre_idx_push_select_cond; - /* - Pointer to the associated ON expression. on_expr_ref=!NULL except for - degenerate joins. - - Optimization phase: *on_expr_ref!=NULL for tables that are the single - tables on the inner side of the outer join (t1 LEFT JOIN t2 ON...) - - Execution phase: *on_expr_ref!=NULL for tables that are first inner tables - within an outer join (which may have multiple tables) - */ - Item **on_expr_ref; - COND_EQUAL *cond_equal; /**< multiple equalities for the on expression */ - st_join_table *first_inner; /**< first inner table for including outerjoin */ - bool found; /**< true after all matches or null complement */ - bool not_null_compl;/**< true before null complement is added */ - st_join_table *last_inner; /**< last table table for embedding outer join */ - st_join_table *first_upper; /**< first inner table for embedding outer join */ - st_join_table *first_unmatched; /**< used for optimization purposes only */ - - /* - For join tabs that are inside an SJM bush: root of the bush - */ - st_join_table *bush_root_tab; - - /* TRUE <=> This join_tab is inside an SJM bush and is the last leaf tab here */ - bool last_leaf_in_bush; - - /* - ptr - this is a bush, and ptr points to description of child join_tab - range - NULL - this join tab has no bush children - */ - JOIN_TAB_RANGE *bush_children; - - /* Special content for EXPLAIN 'Extra' column or NULL if none */ - enum explain_extra_tag info; - - Table_access_tracker *tracker; - - Table_access_tracker *jbuf_tracker; - /* - Bitmap of TAB_INFO_* bits that encodes special line for EXPLAIN 'Extra' - column, or 0 if there is no info. - */ - uint packed_info; - - // READ_RECORD::Setup_func materialize_table; - READ_RECORD::Setup_func read_first_record; - Next_select_func next_select; - READ_RECORD read_record; - /* - Currently the following two fields are used only for a [NOT] IN subquery - if it is executed by an alternative full table scan when the left operand of - the subquery predicate is evaluated to NULL. - */ - READ_RECORD::Setup_func save_read_first_record;/* to save read_first_record */ - READ_RECORD::Read_func save_read_record;/* to save read_record.read_record */ - double worst_seeks; - key_map const_keys; /**< Keys with constant part */ - key_map checked_keys; /**< Keys checked in find_best */ - key_map needed_reg; - key_map keys; /**< all keys with can be used */ - - /* Either #rows in the table or 1 for const table. */ - ha_rows records; - /* - Number of records that will be scanned (yes scanned, not returned) by the - best 'independent' access method, i.e. table scan or QUICK_*_SELECT) - */ - ha_rows found_records; - /* - Cost of accessing the table using "ALL" or range/index_merge access - method (but not 'index' for some reason), i.e. this matches method which - E(#records) is in found_records. - */ - double read_time; - - /* Copy of POSITION::records_read, set by get_best_combination() */ - double records_read; - - /* The selectivity of the conditions that can be pushed to the table */ - double cond_selectivity; - - /* Startup cost for execution */ - double startup_cost; - - double partial_join_cardinality; - - table_map dependent,key_dependent; - /* - 1 - use quick select - 2 - use "Range checked for each record" - */ - uint use_quick; - /* - Index to use. Note: this is valid only for 'index' access, but not range or - ref access. - */ - uint index; - uint status; ///< Save status for cache - uint used_fields; - ulong used_fieldlength; - ulong max_used_fieldlength; - uint used_blobs; - uint used_null_fields; - uint used_uneven_bit_fields; - enum join_type type; - bool cached_eq_ref_table,eq_ref_table; - bool shortcut_for_distinct; - bool sorted; - /* - If it's not 0 the number stored this field indicates that the index - scan has been chosen to access the table data and we expect to scan - this number of rows for the table. - */ - ha_rows limit; - TABLE_REF ref; - /* TRUE <=> condition pushdown supports other tables presence */ - bool icp_other_tables_ok; - /* - TRUE <=> condition pushed to the index has to be factored out of - the condition pushed to the table - */ - bool idx_cond_fact_out; - bool use_join_cache; - uint used_join_cache_level; - ulong join_buffer_size_limit; - JOIN_CACHE *cache; - /* - Index condition for BKA access join - */ - Item *cache_idx_cond; - SQL_SELECT *cache_select; - AGGR_OP *aggr; - JOIN *join; - /* - Embedding SJ-nest (may be not the direct parent), or NULL if none. - This variable holds the result of table pullout. - */ - TABLE_LIST *emb_sj_nest; - - /* FirstMatch variables (final QEP) */ - struct st_join_table *first_sj_inner_tab; - struct st_join_table *last_sj_inner_tab; - - /* Variables for semi-join duplicate elimination */ - SJ_TMP_TABLE *flush_weedout_table; - SJ_TMP_TABLE *check_weed_out_table; - /* for EXPLAIN only: */ - SJ_TMP_TABLE *first_weedout_table; - - /** - reference to saved plan and execution statistics - */ - Explain_table_access *explain_plan; - - /* - If set, means we should stop join enumeration after we've got the first - match and return to the specified join tab. May point to - join->join_tab[-1] which means stop join execution after the first - match. - */ - struct st_join_table *do_firstmatch; - - /* - ptr - We're doing a LooseScan, this join tab is the first (i.e. - "driving") join tab), and ptr points to the last join tab - handled by the strategy. loosescan_match_tab->found_match - should be checked to see if the current value group had a match. - NULL - Not doing a loose scan on this join tab. - */ - struct st_join_table *loosescan_match_tab; - - /* TRUE <=> we are inside LooseScan range */ - bool inside_loosescan_range; - - /* Buffer to save index tuple to be able to skip duplicates */ - uchar *loosescan_buf; - - /* - Index used by LooseScan (we store it here separately because ref access - stores it in tab->ref.key, while range scan stores it in tab->index, etc) - */ - uint loosescan_key; - - /* Length of key tuple (depends on #keyparts used) to store in the above */ - uint loosescan_key_len; - - /* Used by LooseScan. TRUE<=> there has been a matching record combination */ - bool found_match; - - /* - Used by DuplicateElimination. tab->table->ref must have the rowid - whenever we have a current record. - */ - int keep_current_rowid; - - /* NestedOuterJoins: Bitmap of nested joins this table is part of */ - nested_join_map embedding_map; - - /* Tmp table info */ - TMP_TABLE_PARAM *tmp_table_param; - - /* Sorting related info */ - Filesort *filesort; - SORT_INFO *filesort_result; - - /* - Non-NULL value means this join_tab must do window function computation - before reading. - */ - Window_funcs_computation* window_funcs_step; - - /** - List of topmost expressions in the select list. The *next* JOIN_TAB - in the plan should use it to obtain correct values. Same applicable to - all_fields. These lists are needed because after tmp tables functions - will be turned to fields. These variables are pointing to - tmp_fields_list[123]. Valid only for tmp tables and the last non-tmp - table in the query plan. - @see JOIN::make_aggr_tables_info() - */ - List *fields; - /** List of all expressions in the select list */ - List *all_fields; - /* - Pointer to the ref array slice which to switch to before sending - records. Valid only for tmp tables. - */ - Ref_ptr_array *ref_array; - - /** Number of records saved in tmp table */ - ha_rows send_records; - - /** HAVING condition for checking prior saving a record into tmp table*/ - Item *having; - - /** TRUE <=> remove duplicates on this table. */ - bool distinct; - - /* - Semi-join strategy to be used for this join table. This is a copy of - POSITION::sj_strategy field. This field is set up by the - fix_semijoin_strategies_for_picked_join_order. - */ - enum sj_strategy_enum sj_strategy; - - uint n_sj_tables; - - bool preread_init_done; - - /* - Cost info to the range filter used when joining this join table - (Defined when the best join order has been already chosen) - */ - Range_rowid_filter_cost_info *range_rowid_filter_info; - /* Rowid filter to be used when joining this join table */ - Rowid_filter *rowid_filter; - /* Becomes true just after the used range filter has been built / filled */ - bool is_rowid_filter_built; - - void build_range_rowid_filter_if_needed(); - - void cleanup(); - inline bool is_using_loose_index_scan() - { - const SQL_SELECT *sel= filesort ? filesort->select : select; - return (sel && sel->quick && - (sel->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)); - } - bool is_using_agg_loose_index_scan () - { - return (is_using_loose_index_scan() && - ((QUICK_GROUP_MIN_MAX_SELECT *)select->quick)->is_agg_distinct()); - } - bool is_inner_table_of_semi_join_with_first_match() - { - return first_sj_inner_tab != NULL; - } - bool is_inner_table_of_semijoin() - { - return emb_sj_nest != NULL; - } - bool is_inner_table_of_outer_join() - { - return first_inner != NULL; - } - bool is_single_inner_of_semi_join_with_first_match() - { - return first_sj_inner_tab == this && last_sj_inner_tab == this; - } - bool is_single_inner_of_outer_join() - { - return first_inner == this && first_inner->last_inner == this; - } - bool is_first_inner_for_outer_join() - { - return first_inner && first_inner == this; - } - bool use_match_flag() - { - return is_first_inner_for_outer_join() || first_sj_inner_tab == this ; - } - bool check_only_first_match() - { - return is_inner_table_of_semi_join_with_first_match() || - (is_inner_table_of_outer_join() && - table->reginfo.not_exists_optimize); - } - bool is_last_inner_table() - { - return (first_inner && first_inner->last_inner == this) || - last_sj_inner_tab == this; - } - /* - Check whether the table belongs to a nest of inner tables of an - outer join or to a nest of inner tables of a semi-join - */ - bool is_nested_inner() - { - if (first_inner && - (first_inner != first_inner->last_inner || first_inner->first_upper)) - return TRUE; - if (first_sj_inner_tab && first_sj_inner_tab != last_sj_inner_tab) - return TRUE; - return FALSE; - } - struct st_join_table *get_first_inner_table() - { - if (first_inner) - return first_inner; - return first_sj_inner_tab; - } - void set_select_cond(COND *to, uint line) - { - DBUG_PRINT("info", ("select_cond changes %p -> %p at line %u tab %p", - select_cond, to, line, this)); - select_cond= to; - } - COND *set_cond(COND *new_cond) - { - COND *tmp_select_cond= select_cond; - set_select_cond(new_cond, __LINE__); - if (select) - select->cond= new_cond; - return tmp_select_cond; - } - void calc_used_field_length(bool max_fl); - ulong get_used_fieldlength() - { - if (!used_fieldlength) - calc_used_field_length(FALSE); - return used_fieldlength; - } - ulong get_max_used_fieldlength() - { - if (!max_used_fieldlength) - calc_used_field_length(TRUE); - return max_used_fieldlength; - } - double get_partial_join_cardinality() { return partial_join_cardinality; } - bool hash_join_is_possible(); - int make_scan_filter(); - bool is_ref_for_hash_join() { return is_hash_join_key_no(ref.key); } - KEY *get_keyinfo_by_key_no(uint key) - { - return (is_hash_join_key_no(key) ? hj_key : table->key_info+key); - } - double scan_time(); - ha_rows get_examined_rows(); - bool preread_init(); - - bool pfs_batch_update(JOIN *join); - - bool is_sjm_nest() { return MY_TEST(bush_children); } - - /* - If this join_tab reads a non-merged semi-join (also called jtbm), return - the select's number. Otherwise, return 0. - */ - int get_non_merged_semijoin_select() const - { - Item_in_subselect *subq; - if (table->pos_in_table_list && - (subq= table->pos_in_table_list->jtbm_subselect)) - { - return subq->unit->first_select()->select_number; - } - return 0; /* Not a merged semi-join */ - } - - bool access_from_tables_is_allowed(table_map used_tables, - table_map sjm_lookup_tables) - { - table_map used_sjm_lookup_tables= used_tables & sjm_lookup_tables; - return !used_sjm_lookup_tables || - (emb_sj_nest && - !(used_sjm_lookup_tables & ~emb_sj_nest->sj_inner_tables)); - } - - bool keyuse_is_valid_for_access_in_chosen_plan(JOIN *join, KEYUSE *keyuse); - - void remove_redundant_bnl_scan_conds(); - - bool save_explain_data(Explain_table_access *eta, table_map prefix_tables, - bool distinct, struct st_join_table *first_top_tab); - - bool use_order() const; ///< Use ordering provided by chosen index? - bool sort_table(); - bool remove_duplicates(); - - void partial_cleanup(); - void add_keyuses_for_splitting(); - SplM_plan_info *choose_best_splitting(double record_count, - table_map remaining_tables); - bool fix_splitting(SplM_plan_info *spl_plan, table_map remaining_tables, - bool is_const_table); -} JOIN_TAB; - - -#include "sql_join_cache.h" - -enum_nested_loop_state -sub_select_cache(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); -enum_nested_loop_state -sub_select(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); -enum_nested_loop_state -sub_select_postjoin_aggr(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); - -enum_nested_loop_state -end_send_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), - bool end_of_records); -enum_nested_loop_state -end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), - bool end_of_records); - - -struct st_position; - -class Semi_join_strategy_picker -{ -public: - /* Called when starting to build a new join prefix */ - virtual void set_empty() = 0; - - /* - Update internal state after another table has been added to the join - prefix - */ - virtual void set_from_prev(struct st_position *prev) = 0; - - virtual bool check_qep(JOIN *join, - uint idx, - table_map remaining_tables, - const JOIN_TAB *new_join_tab, - double *record_count, - double *read_time, - table_map *handled_fanout, - sj_strategy_enum *strategy, - struct st_position *loose_scan_pos) = 0; - - virtual void mark_used() = 0; - - virtual ~Semi_join_strategy_picker() {} -}; - - -/* - Duplicate Weedout strategy optimization state -*/ - -class Duplicate_weedout_picker : public Semi_join_strategy_picker -{ - /* The first table that the strategy will need to handle */ - uint first_dupsweedout_table; - - /* - Tables that we will need to have in the prefix to do the weedout step - (all inner and all outer that the involved semi-joins are correlated with) - */ - table_map dupsweedout_tables; - - bool is_used; -public: - void set_empty() - { - dupsweedout_tables= 0; - first_dupsweedout_table= MAX_TABLES; - is_used= FALSE; - } - void set_from_prev(struct st_position *prev); - - bool check_qep(JOIN *join, - uint idx, - table_map remaining_tables, - const JOIN_TAB *new_join_tab, - double *record_count, - double *read_time, - table_map *handled_fanout, - sj_strategy_enum *stratey, - struct st_position *loose_scan_pos); - - void mark_used() { is_used= TRUE; } - friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); -}; - - -class Firstmatch_picker : public Semi_join_strategy_picker -{ - /* - Index of the first inner table that we intend to handle with this - strategy - */ - uint first_firstmatch_table; - /* - Tables that were not in the join prefix when we've started considering - FirstMatch strategy. - */ - table_map first_firstmatch_rtbl; - /* - Tables that need to be in the prefix before we can calculate the cost - of using FirstMatch strategy. - */ - table_map firstmatch_need_tables; - - bool is_used; - - bool in_firstmatch_prefix() { return (first_firstmatch_table != MAX_TABLES); } - void invalidate_firstmatch_prefix() { first_firstmatch_table= MAX_TABLES; } -public: - void set_empty() - { - invalidate_firstmatch_prefix(); - is_used= FALSE; - } - - void set_from_prev(struct st_position *prev); - bool check_qep(JOIN *join, - uint idx, - table_map remaining_tables, - const JOIN_TAB *new_join_tab, - double *record_count, - double *read_time, - table_map *handled_fanout, - sj_strategy_enum *strategy, - struct st_position *loose_scan_pos); - - void mark_used() { is_used= TRUE; } - friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); -}; - - -class LooseScan_picker : public Semi_join_strategy_picker -{ - /* The first (i.e. driving) table we're doing loose scan for */ - uint first_loosescan_table; - /* - Tables that need to be in the prefix before we can calculate the cost - of using LooseScan strategy. - */ - table_map loosescan_need_tables; - - /* - keyno - Planning to do LooseScan on this key. If keyuse is NULL then - this is a full index scan, otherwise this is a ref+loosescan - scan (and keyno matches the KEUSE's) - MAX_KEY - Not doing a LooseScan - */ - uint loosescan_key; // final (one for strategy instance ) - uint loosescan_parts; /* Number of keyparts to be kept distinct */ - - bool is_used; -public: - void set_empty() - { - first_loosescan_table= MAX_TABLES; - is_used= FALSE; - } - - void set_from_prev(struct st_position *prev); - bool check_qep(JOIN *join, - uint idx, - table_map remaining_tables, - const JOIN_TAB *new_join_tab, - double *record_count, - double *read_time, - table_map *handled_fanout, - sj_strategy_enum *strategy, - struct st_position *loose_scan_pos); - void mark_used() { is_used= TRUE; } - - friend class Loose_scan_opt; - friend void best_access_path(JOIN *join, - JOIN_TAB *s, - table_map remaining_tables, - const struct st_position *join_positions, - uint idx, - bool disable_jbuf, - double record_count, - struct st_position *pos, - struct st_position *loose_scan_pos); - friend bool get_best_combination(JOIN *join); - friend int setup_semijoin_loosescan(JOIN *join); - friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); -}; - - -class Sj_materialization_picker : public Semi_join_strategy_picker -{ - bool is_used; - - /* The last inner table (valid once we're after it) */ - uint sjm_scan_last_inner; - /* - Tables that we need to have in the prefix to calculate the correct cost. - Basically, we need all inner tables and outer tables mentioned in the - semi-join's ON expression so we can correctly account for fanout. - */ - table_map sjm_scan_need_tables; - -public: - void set_empty() - { - sjm_scan_need_tables= 0; - sjm_scan_last_inner= 0; - is_used= FALSE; - } - void set_from_prev(struct st_position *prev); - bool check_qep(JOIN *join, - uint idx, - table_map remaining_tables, - const JOIN_TAB *new_join_tab, - double *record_count, - double *read_time, - table_map *handled_fanout, - sj_strategy_enum *strategy, - struct st_position *loose_scan_pos); - void mark_used() { is_used= TRUE; } - - friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); -}; - - -class Range_rowid_filter_cost_info; -class Rowid_filter; - - -/** - Information about a position of table within a join order. Used in join - optimization. -*/ -typedef struct st_position -{ - /* The table that's put into join order */ - JOIN_TAB *table; - - /* - The "fanout": number of output rows that will be produced (after - pushed down selection condition is applied) per each row combination of - previous tables. - */ - double records_read; - - /* The selectivity of the pushed down conditions */ - double cond_selectivity; - - /* - Cost accessing the table in course of the entire complete join execution, - i.e. cost of one access method use (e.g. 'range' or 'ref' scan ) times - number the access method will be invoked. - */ - double read_time; - - /* Cumulative cost and record count for the join prefix */ - Cost_estimate prefix_cost; - double prefix_record_count; - - /* - NULL - 'index' or 'range' or 'index_merge' or 'ALL' access is used. - Other - [eq_]ref[_or_null] access is used. Pointer to {t.keypart1 = expr} - */ - KEYUSE *key; - - /* If ref-based access is used: bitmap of tables this table depends on */ - table_map ref_depend_map; - - /* - TRUE <=> join buffering will be used. At the moment this is based on - *very* imprecise guesses made in best_access_path(). - */ - bool use_join_buffer; - - /* - Current optimization state: Semi-join strategy to be used for this - and preceding join tables. - - Join optimizer sets this for the *last* join_tab in the - duplicate-generating range. That is, in order to interpret this field, - one needs to traverse join->[best_]positions array from right to left. - When you see a join table with sj_strategy!= SJ_OPT_NONE, some other - field (depending on the strategy) tells how many preceding positions - this applies to. The values of covered_preceding_positions->sj_strategy - must be ignored. - */ - enum sj_strategy_enum sj_strategy; - - /* - Valid only after fix_semijoin_strategies_for_picked_join_order() call: - if sj_strategy!=SJ_OPT_NONE, this is the number of subsequent tables that - are covered by the specified semi-join strategy - */ - uint n_sj_tables; - - /* - Bitmap of semi-join inner tables that are in the join prefix and for - which there's no provision for how to eliminate semi-join duplicates - they produce. - */ - table_map dups_producing_tables; - - table_map inner_tables_handled_with_other_sjs; - - Duplicate_weedout_picker dups_weedout_picker; - Firstmatch_picker firstmatch_picker; - LooseScan_picker loosescan_picker; - Sj_materialization_picker sjmat_picker; - - /* Info on splitting plan used at this position */ - SplM_plan_info *spl_plan; - - /* Cost info for the range filter used at this position */ - Range_rowid_filter_cost_info *range_rowid_filter_info; - -} POSITION; - -typedef Bounds_checked_array Item_null_array; - -typedef struct st_rollup -{ - enum State { STATE_NONE, STATE_INITED, STATE_READY }; - State state; - Item_null_array null_items; - Ref_ptr_array *ref_pointer_arrays; - List *fields; -} ROLLUP; - - -class JOIN_TAB_RANGE: public Sql_alloc -{ -public: - JOIN_TAB *start; - JOIN_TAB *end; -}; - -class Pushdown_query; - -/** - @brief - Class to perform postjoin aggregation operations - - @details - The result records are obtained on the put_record() call. - The aggrgation process is determined by the write_func, it could be: - end_write Simply store all records in tmp table. - end_write_group Perform grouping using join->group_fields, - records are expected to be sorted. - end_update Perform grouping using the key generated on tmp - table. Input records aren't expected to be sorted. - Tmp table uses the heap engine - end_update_unique Same as above, but the engine is myisam. - - Lazy table initialization is used - the table will be instantiated and - rnd/index scan started on the first put_record() call. - -*/ - -class AGGR_OP :public Sql_alloc -{ -public: - JOIN_TAB *join_tab; - - AGGR_OP(JOIN_TAB *tab) : join_tab(tab), write_func(NULL) - {}; - - enum_nested_loop_state put_record() { return put_record(false); }; - /* - Send the result of operation further (to a next operation/client) - This function is called after all records were put into tmp table. - - @return return one of enum_nested_loop_state values. - */ - enum_nested_loop_state end_send(); - /** write_func setter */ - void set_write_func(Next_select_func new_write_func) - { - write_func= new_write_func; - } - -private: - /** Write function that would be used for saving records in tmp table. */ - Next_select_func write_func; - enum_nested_loop_state put_record(bool end_of_records); - bool prepare_tmp_table(); -}; - - -class JOIN :public Sql_alloc -{ -private: - JOIN(const JOIN &rhs); /**< not implemented */ - JOIN& operator=(const JOIN &rhs); /**< not implemented */ - -protected: - - /** - The subset of the state of a JOIN that represents an optimized query - execution plan. Allows saving/restoring different JOIN plans for the same - query. - */ - class Join_plan_state { - public: - DYNAMIC_ARRAY keyuse; /* Copy of the JOIN::keyuse array. */ - POSITION *best_positions; /* Copy of JOIN::best_positions */ - /* Copies of the JOIN_TAB::keyuse pointers for each JOIN_TAB. */ - KEYUSE **join_tab_keyuse; - /* Copies of JOIN_TAB::checked_keys for each JOIN_TAB. */ - key_map *join_tab_checked_keys; - SJ_MATERIALIZATION_INFO **sj_mat_info; - my_bool error; - public: - Join_plan_state(uint tables) : error(0) - { - keyuse.elements= 0; - keyuse.buffer= NULL; - keyuse.malloc_flags= 0; - best_positions= 0; /* To detect errors */ - error= my_multi_malloc(PSI_INSTRUMENT_ME, MYF(MY_WME), - &best_positions, - sizeof(*best_positions) * (tables + 1), - &join_tab_keyuse, - sizeof(*join_tab_keyuse) * tables, - &join_tab_checked_keys, - sizeof(*join_tab_checked_keys) * tables, - &sj_mat_info, - sizeof(sj_mat_info) * tables, - NullS) == 0; - } - Join_plan_state(JOIN *join); - ~Join_plan_state() - { - delete_dynamic(&keyuse); - my_free(best_positions); - } - }; - - /* Results of reoptimizing a JOIN via JOIN::reoptimize(). */ - enum enum_reopt_result { - REOPT_NEW_PLAN, /* there is a new reoptimized plan */ - REOPT_OLD_PLAN, /* no new improved plan can be found, use the old one */ - REOPT_ERROR, /* an irrecovarable error occurred during reoptimization */ - REOPT_NONE /* not yet reoptimized */ - }; - - /* Support for plan reoptimization with rewritten conditions. */ - enum_reopt_result reoptimize(Item *added_where, table_map join_tables, - Join_plan_state *save_to); - /* Choose a subquery plan for a table-less subquery. */ - bool choose_tableless_subquery_plan(); - void handle_implicit_grouping_with_window_funcs(); - -public: - void save_query_plan(Join_plan_state *save_to); - void reset_query_plan(); - void restore_query_plan(Join_plan_state *restore_from); - -public: - JOIN_TAB *join_tab, **best_ref; - - /* List of fields that aren't under an aggregate function */ - List non_agg_fields; - - JOIN_TAB **map2table; ///< mapping between table indexes and JOIN_TABs - List join_tab_ranges; - - /* - Base tables participating in the join. After join optimization is done, the - tables are stored in the join order (but the only really important part is - that const tables are first). - */ - TABLE **table; - /** - The table which has an index that allows to produce the requried ordering. - A special value of 0x1 means that the ordering will be produced by - passing 1st non-const table to filesort(). NULL means no such table exists. - */ - TABLE *sort_by_table; - /* - Number of tables in the join. - (In MySQL, it is named 'tables' and is also the number of elements in - join->join_tab array. In MariaDB, the latter is not true, so we've renamed - the variable) - */ - uint table_count; - uint outer_tables; /**< Number of tables that are not inside semijoin */ - uint const_tables; - /* - Number of tables in the top join_tab array. Normally this matches - (join_tab_ranges.head()->end - join_tab_ranges.head()->start). - - We keep it here so that it is saved/restored with JOIN::restore_tmp. - */ - uint top_join_tab_count; - uint aggr_tables; ///< Number of post-join tmp tables - uint send_group_parts; - /* - True if the query has GROUP BY. - (that is, if group_by != NULL. when DISTINCT is converted into GROUP BY, it - will set this, too. It is not clear why we need a separate var from - group_list) - */ - bool group; - bool need_distinct; - - /** - Indicates that grouping will be performed on the result set during - query execution. This field belongs to query execution. - - @see make_group_fields, alloc_group_fields, JOIN::exec - */ - bool sort_and_group; - bool first_record,full_join, no_field_update; - bool hash_join; - bool do_send_rows; - table_map const_table_map; - /** - Bitmap of semijoin tables that the current partial plan decided - to materialize and access by lookups - */ - table_map sjm_lookup_tables; - /** - Bitmap of semijoin tables that the chosen plan decided - to materialize to scan the results of materialization - */ - table_map sjm_scan_tables; - /* - Constant tables for which we have found a row (as opposed to those for - which we didn't). - */ - table_map found_const_table_map; - - /* Tables removed by table elimination. Set to 0 before the elimination. */ - table_map eliminated_tables; - /* - Bitmap of all inner tables from outer joins (set at start of - make_join_statistics) - */ - table_map outer_join; - /* Bitmap of tables used in the select list items */ - table_map select_list_used_tables; - ha_rows send_records,found_records,join_examined_rows; - - /* - LIMIT for the JOIN operation. When not using aggregation or DISITNCT, this - is the same as select's LIMIT clause specifies. - Note that this doesn't take sql_calc_found_rows into account. - */ - ha_rows row_limit; - - /* - How many output rows should be produced after GROUP BY. - (if sql_calc_found_rows is used, LIMIT is ignored) - */ - ha_rows select_limit; - /* - Number of duplicate rows found in UNION. - */ - ha_rows duplicate_rows; - /** - Used to fetch no more than given amount of rows per one - fetch operation of server side cursor. - The value is checked in end_send and end_send_group in fashion, similar - to offset_limit_cnt: - - fetch_limit= HA_POS_ERROR if there is no cursor. - - when we open a cursor, we set fetch_limit to 0, - - on each fetch iteration we add num_rows to fetch to fetch_limit - NOTE: currently always HA_POS_ERROR. - */ - ha_rows fetch_limit; - - /* Finally picked QEP. This is result of join optimization */ - POSITION *best_positions; - - Pushdown_query *pushdown_query; - JOIN_TAB *original_join_tab; - uint original_table_count; - -/******* Join optimization state members start *******/ - /* - pointer - we're doing optimization for a semi-join materialization nest. - NULL - otherwise - */ - TABLE_LIST *emb_sjm_nest; - - /* Current join optimization state */ - POSITION *positions; - - /* - Bitmap of nested joins embedding the position at the end of the current - partial join (valid only during join optimizer run). - */ - nested_join_map cur_embedding_map; - - /* - Bitmap of inner tables of semi-join nests that have a proper subset of - their tables in the current join prefix. That is, of those semi-join - nests that have their tables both in and outside of the join prefix. - */ - table_map cur_sj_inner_tables; - - /* We also maintain a stack of join optimization states in * join->positions[] */ -/******* Join optimization state members end *******/ - - /* - Tables within complex firstmatch ranges (i.e. those where inner tables are - interleaved with outer tables). Join buffering cannot be used for these. - */ - table_map complex_firstmatch_tables; - - Next_select_func first_select; - /* - The cost of best complete join plan found so far during optimization, - after optimization phase - cost of picked join order (not taking into - account the changes made by test_if_skip_sort_order()). - */ - double best_read; - /* - Estimated result rows (fanout) of the join operation. If this is a subquery - that is reexecuted multiple times, this value includes the estiamted # of - reexecutions. This value is equal to the multiplication of all - join->positions[i].records_read of a JOIN. - */ - double join_record_count; - List *fields; - List group_fields, group_fields_cache; - THD *thd; - Item_sum **sum_funcs, ***sum_funcs_end; - /** second copy of sumfuncs (for queries with 2 temporary tables */ - Item_sum **sum_funcs2, ***sum_funcs_end2; - Procedure *procedure; - Item *having; - Item *tmp_having; ///< To store having when processed temporary table - Item *having_history; ///< Store having for explain - ORDER *group_list_for_estimates; - bool having_is_correlated; - ulonglong select_options; - /* - Bitmap of allowed types of the join caches that - can be used for join operations - */ - uint allowed_join_cache_types; - bool allowed_semijoin_with_cache; - bool allowed_outer_join_with_cache; - /* Maximum level of the join caches that can be used for join operations */ - uint max_allowed_join_cache_level; - select_result *result; - TMP_TABLE_PARAM tmp_table_param; - MYSQL_LOCK *lock; - /// unit structure (with global parameters) for this select - SELECT_LEX_UNIT *unit; - /// select that processed - SELECT_LEX *select_lex; - /** - TRUE <=> optimizer must not mark any table as a constant table. - This is needed for subqueries in form "a IN (SELECT .. UNION SELECT ..): - when we optimize the select that reads the results of the union from a - temporary table, we must not mark the temp. table as constant because - the number of rows in it may vary from one subquery execution to another. - */ - bool no_const_tables; - /* - This flag is set if we call no_rows_in_result() as par of end_group(). - This is used as a simple speed optimization to avoiding calling - restore_no_rows_in_result() in ::reinit() - */ - bool no_rows_in_result_called; - - /** - This is set if SQL_CALC_ROWS was calculated by filesort() - and should be taken from the appropriate JOIN_TAB - */ - bool filesort_found_rows; - - bool subq_exit_fl; - - ROLLUP rollup; ///< Used with rollup - - bool mixed_implicit_grouping; - bool select_distinct; ///< Set if SELECT DISTINCT - /** - If we have the GROUP BY statement in the query, - but the group_list was emptied by optimizer, this - flag is TRUE. - It happens when fields in the GROUP BY are from - constant table - */ - bool group_optimized_away; - - /* - simple_xxxxx is set if ORDER/GROUP BY doesn't include any references - to other tables than the first non-constant table in the JOIN. - It's also set if ORDER/GROUP BY is empty. - Used for deciding for or against using a temporary table to compute - GROUP/ORDER BY. - */ - bool simple_order, simple_group; - - /* - ordered_index_usage is set if an ordered index access - should be used instead of a filesort when computing - ORDER/GROUP BY. - */ - enum - { - ordered_index_void, // No ordered index avail. - ordered_index_group_by, // Use index for GROUP BY - ordered_index_order_by // Use index for ORDER BY - } ordered_index_usage; - - /** - Is set only in case if we have a GROUP BY clause - and no ORDER BY after constant elimination of 'order'. - */ - bool no_order; - /** Is set if we have a GROUP BY and we have ORDER BY on a constant. */ - bool skip_sort_order; - - bool need_tmp; - bool hidden_group_fields; - /* TRUE if there was full cleunap of the JOIN */ - bool cleaned; - DYNAMIC_ARRAY keyuse; - Item::cond_result cond_value, having_value; - /** - Impossible where after reading const tables - (set in make_join_statistics()) - */ - bool impossible_where; - List all_fields; ///< to store all fields that used in query - ///Above list changed to use temporary table - List tmp_all_fields1, tmp_all_fields2, tmp_all_fields3; - ///Part, shared with list above, emulate following list - List tmp_fields_list1, tmp_fields_list2, tmp_fields_list3; - List &fields_list; ///< hold field list passed to mysql_select - List procedure_fields_list; - int error; - - ORDER *order, *group_list, *proc_param; //hold parameters of mysql_select - COND *conds; // ---"--- - Item *conds_history; // store WHERE for explain - COND *outer_ref_cond; /// *join_list; ///< list of joined tables in reverse order - COND_EQUAL *cond_equal; - COND_EQUAL *having_equal; - /* - Constant codition computed during optimization, but evaluated during - join execution. Typically expensive conditions that should not be - evaluated at optimization time. - */ - Item *exec_const_cond; - /* - Constant ORDER and/or GROUP expressions that contain subqueries. Such - expressions need to evaluated to verify that the subquery indeed - returns a single row. The evaluation of such expressions is delayed - until query execution. - */ - List exec_const_order_group_cond; - SQL_SELECT *select; ///ref_pointer_array contains five "slices" of the same length: - |========|========|========|========|========| - ref_ptrs items0 items1 items2 items3 - */ - Ref_ptr_array ref_ptrs; - // Copy of the initial slice above, to be used with different lists - Ref_ptr_array items0, items1, items2, items3; - // Used by rollup, to restore ref_ptrs after overwriting it. - Ref_ptr_array current_ref_ptrs; - - const char *zero_result_cause; ///< not 0 if exec must return zero result - - bool union_part; ///< this subselect is part of union - - enum join_optimization_state { NOT_OPTIMIZED=0, - OPTIMIZATION_IN_PROGRESS=1, - OPTIMIZATION_PHASE_1_DONE=2, - OPTIMIZATION_DONE=3}; - // state of JOIN optimization - enum join_optimization_state optimization_state; - bool initialized; ///< flag to avoid double init_execution calls - - Explain_select *explain; - - enum { QEP_NOT_PRESENT_YET, QEP_AVAILABLE, QEP_DELETED} have_query_plan; - - // if keep_current_rowid=true, whether they should be saved in temporary table - bool tmp_table_keep_current_rowid; - - /* - Additional WHERE and HAVING predicates to be considered for IN=>EXISTS - subquery transformation of a JOIN object. - */ - Item *in_to_exists_where; - Item *in_to_exists_having; - - /* Temporary tables used to weed-out semi-join duplicates */ - List
sj_tmp_tables; - /* SJM nests that are executed with SJ-Materialization strategy */ - List sjm_info_list; - - /** TRUE <=> ref_pointer_array is set to items3. */ - bool set_group_rpa; - /** Exec time only: TRUE <=> current group has been sent */ - bool group_sent; - /** - TRUE if the query contains an aggregate function but has no GROUP - BY clause. - */ - bool implicit_grouping; - - bool with_two_phase_optimization; - - /* Saved execution plan for this join */ - Join_plan_state *save_qep; - /* Info on splittability of the table materialized by this plan*/ - SplM_opt_info *spl_opt_info; - /* Contains info on keyuses usable for splitting */ - Dynamic_array *ext_keyuses_for_splitting; - - JOIN_TAB *sort_and_group_aggr_tab; - /* - Flag is set to true if select_lex was found to be degenerated before - the optimize_cond() call in JOIN::optimize_inner() method. - */ - bool is_orig_degenerated; - - JOIN(THD *thd_arg, List &fields_arg, ulonglong select_options_arg, - select_result *result_arg) - :fields_list(fields_arg) - { - init(thd_arg, fields_arg, select_options_arg, result_arg); - } - - void init(THD *thd_arg, List &fields_arg, ulonglong select_options_arg, - select_result *result_arg) - { - join_tab= 0; - table= 0; - table_count= 0; - top_join_tab_count= 0; - const_tables= 0; - const_table_map= found_const_table_map= 0; - aggr_tables= 0; - eliminated_tables= 0; - join_list= 0; - implicit_grouping= FALSE; - sort_and_group= 0; - first_record= 0; - do_send_rows= 1; - duplicate_rows= send_records= 0; - found_records= 0; - fetch_limit= HA_POS_ERROR; - thd= thd_arg; - sum_funcs= sum_funcs2= 0; - procedure= 0; - having= tmp_having= having_history= 0; - having_is_correlated= false; - group_list_for_estimates= 0; - select_options= select_options_arg; - result= result_arg; - lock= thd_arg->lock; - select_lex= 0; //for safety - select_distinct= MY_TEST(select_options & SELECT_DISTINCT); - no_order= 0; - simple_order= 0; - simple_group= 0; - ordered_index_usage= ordered_index_void; - need_distinct= 0; - skip_sort_order= 0; - with_two_phase_optimization= 0; - save_qep= 0; - spl_opt_info= 0; - ext_keyuses_for_splitting= 0; - spl_opt_info= 0; - need_tmp= 0; - hidden_group_fields= 0; /*safety*/ - error= 0; - select= 0; - return_tab= 0; - ref_ptrs.reset(); - items0.reset(); - items1.reset(); - items2.reset(); - items3.reset(); - zero_result_cause= 0; - optimization_state= JOIN::NOT_OPTIMIZED; - have_query_plan= QEP_NOT_PRESENT_YET; - initialized= 0; - cleaned= 0; - cond_equal= 0; - having_equal= 0; - exec_const_cond= 0; - group_optimized_away= 0; - no_rows_in_result_called= 0; - positions= best_positions= 0; - pushdown_query= 0; - original_join_tab= 0; - explain= NULL; - tmp_table_keep_current_rowid= 0; - - all_fields= fields_arg; - if (&fields_list != &fields_arg) /* Avoid valgrind-warning */ - fields_list= fields_arg; - non_agg_fields.empty(); - bzero((char*) &keyuse,sizeof(keyuse)); - tmp_table_param.init(); - tmp_table_param.end_write_records= HA_POS_ERROR; - rollup.state= ROLLUP::STATE_NONE; - - no_const_tables= FALSE; - first_select= sub_select; - set_group_rpa= false; - group_sent= 0; - - outer_ref_cond= pseudo_bits_cond= NULL; - in_to_exists_where= NULL; - in_to_exists_having= NULL; - emb_sjm_nest= NULL; - sjm_lookup_tables= 0; - sjm_scan_tables= 0; - is_orig_degenerated= false; - } - - /* True if the plan guarantees that it will be returned zero or one row */ - bool only_const_tables() { return const_tables == table_count; } - /* Number of tables actually joined at the top level */ - uint exec_join_tab_cnt() { return tables_list ? top_join_tab_count : 0; } - - /* - Number of tables in the join which also includes the temporary tables - created for GROUP BY, DISTINCT , WINDOW FUNCTION etc. - */ - uint total_join_tab_cnt() - { - return exec_join_tab_cnt() + aggr_tables - 1; - } - - int prepare(TABLE_LIST *tables, COND *conds, uint og_num, ORDER *order, - bool skip_order_by, ORDER *group, Item *having, - ORDER *proc_param, SELECT_LEX *select, SELECT_LEX_UNIT *unit); - bool prepare_stage2(); - int optimize(); - int optimize_inner(); - int optimize_stage2(); - bool build_explain(); - int reinit(); - int init_execution(); - void exec(); - - void exec_inner(); - bool prepare_result(List **columns_list); - int destroy(); - void restore_tmp(); - bool alloc_func_list(); - bool flatten_subqueries(); - bool optimize_unflattened_subqueries(); - bool optimize_constant_subqueries(); - bool make_range_rowid_filters(); - bool init_range_rowid_filters(); - bool make_sum_func_list(List &all_fields, List &send_fields, - bool before_group_by, bool recompute= FALSE); - - /// Initialzes a slice, see comments for ref_ptrs above. - Ref_ptr_array ref_ptr_array_slice(size_t slice_num) - { - size_t slice_sz= select_lex->ref_pointer_array.size() / 5U; - DBUG_ASSERT(select_lex->ref_pointer_array.size() % 5 == 0); - DBUG_ASSERT(slice_num < 5U); - return Ref_ptr_array(&select_lex->ref_pointer_array[slice_num * slice_sz], - slice_sz); - } - - /** - Overwrites one slice with the contents of another slice. - In the normal case, dst and src have the same size(). - However: the rollup slices may have smaller size than slice_sz. - */ - void copy_ref_ptr_array(Ref_ptr_array dst_arr, Ref_ptr_array src_arr) - { - DBUG_ASSERT(dst_arr.size() >= src_arr.size()); - if (src_arr.size() == 0) - return; - - void *dest= dst_arr.array(); - const void *src= src_arr.array(); - memcpy(dest, src, src_arr.size() * src_arr.element_size()); - } - - /// Overwrites 'ref_ptrs' and remembers the the source as 'current'. - void set_items_ref_array(Ref_ptr_array src_arr) - { - copy_ref_ptr_array(ref_ptrs, src_arr); - current_ref_ptrs= src_arr; - } - - /// Initializes 'items0' and remembers that it is 'current'. - void init_items_ref_array() - { - items0= ref_ptr_array_slice(1); - copy_ref_ptr_array(items0, ref_ptrs); - current_ref_ptrs= items0; - } - - bool rollup_init(); - bool rollup_process_const_fields(); - bool rollup_make_fields(List &all_fields, List &fields, - Item_sum ***func); - int rollup_send_data(uint idx); - int rollup_write_data(uint idx, TMP_TABLE_PARAM *tmp_table_param, TABLE *table); - void join_free(); - /** Cleanup this JOIN, possibly for reuse */ - void cleanup(bool full); - void clear(); - bool send_row_on_empty_set() - { - return (do_send_rows && implicit_grouping && !group_optimized_away && - having_value != Item::COND_FALSE); - } - bool empty_result() { return (zero_result_cause && !implicit_grouping); } - bool change_result(select_result *new_result, select_result *old_result); - bool is_top_level_join() const - { - return (unit == &thd->lex->unit && (unit->fake_select_lex == 0 || - select_lex == unit->fake_select_lex)); - } - void cache_const_exprs(); - inline table_map all_tables_map() - { - return (table_map(1) << table_count) - 1; - } - void drop_unused_derived_keys(); - bool get_best_combination(); - bool add_sorting_to_table(JOIN_TAB *tab, ORDER *order); - inline void eval_select_list_used_tables(); - /* - Return the table for which an index scan can be used to satisfy - the sort order needed by the ORDER BY/(implicit) GROUP BY clause - */ - JOIN_TAB *get_sort_by_join_tab() - { - return (need_tmp || !sort_by_table || skip_sort_order || - ((group || tmp_table_param.sum_func_count) && !group_list)) ? - NULL : join_tab+const_tables; - } - bool setup_subquery_caches(); - bool shrink_join_buffers(JOIN_TAB *jt, - ulonglong curr_space, - ulonglong needed_space); - void set_allowed_join_cache_types(); - bool is_allowed_hash_join_access() - { - return MY_TEST(allowed_join_cache_types & JOIN_CACHE_HASHED_BIT) && - max_allowed_join_cache_level > JOIN_CACHE_HASHED_BIT; - } - /* - Check if we need to create a temporary table. - This has to be done if all tables are not already read (const tables) - and one of the following conditions holds: - - We are using DISTINCT (simple distinct's are already optimized away) - - We are using an ORDER BY or GROUP BY on fields not in the first table - - We are using different ORDER BY and GROUP BY orders - - The user wants us to buffer the result. - - We are using WINDOW functions. - When the WITH ROLLUP modifier is present, we cannot skip temporary table - creation for the DISTINCT clause just because there are only const tables. - */ - bool test_if_need_tmp_table() - { - return ((const_tables != table_count && - ((select_distinct || !simple_order || !simple_group) || - (group_list && order) || - MY_TEST(select_options & OPTION_BUFFER_RESULT))) || - (rollup.state != ROLLUP::STATE_NONE && select_distinct) || - select_lex->have_window_funcs()); - } - bool choose_subquery_plan(table_map join_tables); - void get_partial_cost_and_fanout(int end_tab_idx, - table_map filter_map, - double *read_time_arg, - double *record_count_arg); - void get_prefix_cost_and_fanout(uint n_tables, - double *read_time_arg, - double *record_count_arg); - double get_examined_rows(); - /* defined in opt_subselect.cc */ - bool transform_max_min_subquery(); - /* True if this JOIN is a subquery under an IN predicate. */ - bool is_in_subquery() - { - return (unit->item && unit->item->is_in_predicate()); - } - bool save_explain_data(Explain_query *output, bool can_overwrite, - bool need_tmp_table, bool need_order, bool distinct); - int save_explain_data_intern(Explain_query *output, bool need_tmp_table, - bool need_order, bool distinct, - const char *message); - JOIN_TAB *first_breadth_first_tab() { return join_tab; } - bool check_two_phase_optimization(THD *thd); - bool inject_cond_into_where(Item *injected_cond); - bool check_for_splittable_materialized(); - void add_keyuses_for_splitting(); - bool inject_best_splitting_cond(table_map remaining_tables); - bool fix_all_splittings_in_plan(); - void make_notnull_conds_for_range_scans(); - - bool transform_in_predicates_into_in_subq(THD *thd); -private: - /** - Create a temporary table to be used for processing DISTINCT/ORDER - BY/GROUP BY. - - @note Will modify JOIN object wrt sort/group attributes - - @param tab the JOIN_TAB object to attach created table to - @param tmp_table_fields List of items that will be used to define - column types of the table. - @param tmp_table_group Group key to use for temporary table, NULL if none. - @param save_sum_fields If true, do not replace Item_sum items in - @c tmp_fields list with Item_field items referring - to fields in temporary table. - - @returns false on success, true on failure - */ - bool create_postjoin_aggr_table(JOIN_TAB *tab, List *tmp_table_fields, - ORDER *tmp_table_group, - bool save_sum_fields, - bool distinct, - bool keep_row_ordermake); - /** - Optimize distinct when used on a subset of the tables. - - E.g.,: SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b - In this case we can stop scanning t2 when we have found one t1.a - */ - void optimize_distinct(); - - void cleanup_item_list(List &items) const; - bool add_having_as_table_cond(JOIN_TAB *tab); - bool make_aggr_tables_info(); - bool add_fields_for_current_rowid(JOIN_TAB *cur, List *fields); - void init_join_cache_and_keyread(); -}; - -enum enum_with_bush_roots { WITH_BUSH_ROOTS, WITHOUT_BUSH_ROOTS}; -enum enum_with_const_tables { WITH_CONST_TABLES, WITHOUT_CONST_TABLES}; - -JOIN_TAB *first_linear_tab(JOIN *join, - enum enum_with_bush_roots include_bush_roots, - enum enum_with_const_tables const_tbls); -JOIN_TAB *next_linear_tab(JOIN* join, JOIN_TAB* tab, - enum enum_with_bush_roots include_bush_roots); - -JOIN_TAB *first_top_level_tab(JOIN *join, enum enum_with_const_tables with_const); -JOIN_TAB *next_top_level_tab(JOIN *join, JOIN_TAB *tab); - -typedef struct st_select_check { - uint const_ref,reg_ref; -} SELECT_CHECK; - -extern const char *join_type_str[]; - -/* Extern functions in sql_select.cc */ -void count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param, - List &fields, bool reset_with_sum_func); -bool setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param, - Ref_ptr_array ref_pointer_array, - List &new_list1, List &new_list2, - uint elements, List &fields); -void copy_fields(TMP_TABLE_PARAM *param); -bool copy_funcs(Item **func_ptr, const THD *thd); -uint find_shortest_key(TABLE *table, const key_map *usable_keys); -bool is_indexed_agg_distinct(JOIN *join, List *out_args); - -/* functions from opt_sum.cc */ -bool simple_pred(Item_func *func_item, Item **args, bool *inv_order); -int opt_sum_query(THD* thd, - List &tables, List &all_fields, COND *conds); - -/* from sql_delete.cc, used by opt_range.cc */ -extern "C" int refpos_order_cmp(void* arg, const void *a,const void *b); - -/** class to copying an field/item to a key struct */ - -class store_key :public Sql_alloc -{ -public: - bool null_key; /* TRUE <=> the value of the key has a null part */ - enum store_key_result { STORE_KEY_OK, STORE_KEY_FATAL, STORE_KEY_CONV }; - enum Type { FIELD_STORE_KEY, ITEM_STORE_KEY, CONST_ITEM_STORE_KEY }; - store_key(THD *thd, Field *field_arg, uchar *ptr, uchar *null, uint length) - :null_key(0), null_ptr(null), err(0) - { - to_field=field_arg->new_key_field(thd->mem_root, field_arg->table, - ptr, length, null, 1); - } - store_key(store_key &arg) - :Sql_alloc(), null_key(arg.null_key), to_field(arg.to_field), - null_ptr(arg.null_ptr), err(arg.err) - - {} - virtual ~store_key() {} /** Not actually needed */ - virtual enum Type type() const=0; - virtual const char *name() const=0; - virtual bool store_key_is_const() { return false; } - - /** - @brief sets ignore truncation warnings mode and calls the real copy method - - @details this function makes sure truncation warnings when preparing the - key buffers don't end up as errors (because of an enclosing INSERT/UPDATE). - */ - enum store_key_result copy() - { - enum store_key_result result; - THD *thd= to_field->table->in_use; - enum_check_fields saved_count_cuted_fields= thd->count_cuted_fields; - sql_mode_t orig_sql_mode= thd->variables.sql_mode; - thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE); - thd->variables.sql_mode|= MODE_INVALID_DATES; - - thd->count_cuted_fields= CHECK_FIELD_IGNORE; - - result= copy_inner(); - - thd->count_cuted_fields= saved_count_cuted_fields; - thd->variables.sql_mode= orig_sql_mode; - - return result; - } - - protected: - Field *to_field; // Store data here - uchar *null_ptr; - uchar err; - - virtual enum store_key_result copy_inner()=0; -}; - - -class store_key_field: public store_key -{ - Copy_field copy_field; - const char *field_name; - public: - store_key_field(THD *thd, Field *to_field_arg, uchar *ptr, - uchar *null_ptr_arg, - uint length, Field *from_field, const char *name_arg) - :store_key(thd, to_field_arg,ptr, - null_ptr_arg ? null_ptr_arg : from_field->maybe_null() ? &err - : (uchar*) 0, length), field_name(name_arg) - { - if (to_field) - { - copy_field.set(to_field,from_field,0); - } - } - - enum Type type() const { return FIELD_STORE_KEY; } - const char *name() const { return field_name; } - - void change_source_field(Item_field *fld_item) - { - copy_field.set(to_field, fld_item->field, 0); - field_name= fld_item->full_name(); - } - - protected: - enum store_key_result copy_inner() - { - TABLE *table= copy_field.to_field->table; - my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, - table->write_set); - - /* - It looks like the next statement is needed only for a simplified - hash function over key values used now in BNLH join. - When the implementation of this function will be replaced for a proper - full version this statement probably should be removed. - */ - bzero(copy_field.to_ptr,copy_field.to_length); - - copy_field.do_copy(©_field); - dbug_tmp_restore_column_map(table->write_set, old_map); - null_key= to_field->is_null(); - return err != 0 ? STORE_KEY_FATAL : STORE_KEY_OK; - } -}; - - -class store_key_item :public store_key -{ - protected: - Item *item; - /* - Flag that forces usage of save_val() method which save value of the - item instead of save_in_field() method which saves result. - */ - bool use_value; -public: - store_key_item(THD *thd, Field *to_field_arg, uchar *ptr, - uchar *null_ptr_arg, uint length, Item *item_arg, bool val) - :store_key(thd, to_field_arg, ptr, - null_ptr_arg ? null_ptr_arg : item_arg->maybe_null ? - &err : (uchar*) 0, length), item(item_arg), use_value(val) - {} - store_key_item(store_key &arg, Item *new_item, bool val) - :store_key(arg), item(new_item), use_value(val) - {} - - - enum Type type() const { return ITEM_STORE_KEY; } - const char *name() const { return "func"; } - - protected: - enum store_key_result copy_inner() - { - TABLE *table= to_field->table; - my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, - table->write_set); - int res= FALSE; - - /* - It looks like the next statement is needed only for a simplified - hash function over key values used now in BNLH join. - When the implementation of this function will be replaced for a proper - full version this statement probably should be removed. - */ - to_field->reset(); - - if (use_value) - item->save_val(to_field); - else - res= item->save_in_field(to_field, 1); - /* - Item::save_in_field() may call Item::val_xxx(). And if this is a subquery - we need to check for errors executing it and react accordingly - */ - if (!res && table->in_use->is_error()) - res= 1; /* STORE_KEY_FATAL */ - dbug_tmp_restore_column_map(table->write_set, old_map); - null_key= to_field->is_null() || item->null_value; - return ((err != 0 || res < 0 || res > 2) ? STORE_KEY_FATAL : - (store_key_result) res); - } -}; - - -class store_key_const_item :public store_key_item -{ - bool inited; -public: - store_key_const_item(THD *thd, Field *to_field_arg, uchar *ptr, - uchar *null_ptr_arg, uint length, - Item *item_arg) - :store_key_item(thd, to_field_arg, ptr, - null_ptr_arg ? null_ptr_arg : item_arg->maybe_null ? - &err : (uchar*) 0, length, item_arg, FALSE), inited(0) - { - } - store_key_const_item(store_key &arg, Item *new_item) - :store_key_item(arg, new_item, FALSE), inited(0) - {} - - enum Type type() const { return CONST_ITEM_STORE_KEY; } - const char *name() const { return "const"; } - bool store_key_is_const() { return true; } - -protected: - enum store_key_result copy_inner() - { - int res; - if (!inited) - { - inited=1; - TABLE *table= to_field->table; - my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, - table->write_set); - if ((res= item->save_in_field(to_field, 1))) - { - if (!err) - err= res < 0 ? 1 : res; /* 1=STORE_KEY_FATAL */ - } - /* - Item::save_in_field() may call Item::val_xxx(). And if this is a subquery - we need to check for errors executing it and react accordingly - */ - if (!err && to_field->table->in_use->is_error()) - err= 1; /* STORE_KEY_FATAL */ - dbug_tmp_restore_column_map(table->write_set, old_map); - } - null_key= to_field->is_null() || item->null_value; - return (err > 2 ? STORE_KEY_FATAL : (store_key_result) err); - } -}; - -void best_access_path(JOIN *join, JOIN_TAB *s, - table_map remaining_tables, - const POSITION *join_positions, uint idx, - bool disable_jbuf, double record_count, - POSITION *pos, POSITION *loose_scan_pos); -bool cp_buffer_from_ref(THD *thd, TABLE *table, TABLE_REF *ref); -bool error_if_full_join(JOIN *join); -int report_error(TABLE *table, int error); -int safe_index_read(JOIN_TAB *tab); -int get_quick_record(SQL_SELECT *select); -int setup_order(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, - List &fields, List &all_fields, ORDER *order, - bool from_window_spec= false); -int setup_group(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, - List &fields, List &all_fields, ORDER *order, - bool *hidden_group_fields, bool from_window_spec= false); -bool fix_inner_refs(THD *thd, List &all_fields, SELECT_LEX *select, - Ref_ptr_array ref_pointer_array); -int join_read_key2(THD *thd, struct st_join_table *tab, TABLE *table, - struct st_table_ref *table_ref); - -bool handle_select(THD *thd, LEX *lex, select_result *result, - ulong setup_tables_done_option); -bool mysql_select(THD *thd, TABLE_LIST *tables, List &list, - COND *conds, uint og_num, ORDER *order, ORDER *group, - Item *having, ORDER *proc_param, ulonglong select_type, - select_result *result, SELECT_LEX_UNIT *unit, - SELECT_LEX *select_lex); -void free_underlaid_joins(THD *thd, SELECT_LEX *select); -bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, - select_result *result); - -/* - General routine to change field->ptr of a NULL-terminated array of Field - objects. Useful when needed to call val_int, val_str or similar and the - field data is not in table->record[0] but in some other structure. - set_key_field_ptr changes all fields of an index using a key_info object. - All methods presume that there is at least one field to change. -*/ - - -class Virtual_tmp_table: public TABLE -{ - /** - Destruct collected fields. This method can be called on errors, - when we could not make the virtual temporary table completely, - e.g. when some of the fields could not be created or added. - - This is needed to avoid memory leaks, as some fields can be BLOB - variants and thus can have String onboard. Strings must be destructed - as they store data on the heap (not on MEM_ROOT). - */ - void destruct_fields() - { - for (uint i= 0; i < s->fields; i++) - { - field[i]->free(); - delete field[i]; // to invoke the field destructor - } - s->fields= 0; // safety - } - -protected: - /** - The number of the fields that are going to be in the table. - We remember the number of the fields at init() time, and - at open() we check that all of the fields were really added. - */ - uint m_alloced_field_count; - - /** - Setup field pointers and null-bit pointers. - */ - void setup_field_pointers(); - -public: - /** - Create a new empty virtual temporary table on the thread mem_root. - After creation, the caller must: - - call init() - - populate the table with new fields using add(). - - call open(). - @param thd - Current thread. - */ - static void *operator new(size_t size, THD *thd) throw(); - static void operator delete(void *ptr, size_t size) { TRASH_FREE(ptr, size); } - static void operator delete(void *, THD *) throw(){} - - Virtual_tmp_table(THD *thd) : m_alloced_field_count(0) - { - reset(); - temp_pool_slot= MY_BIT_NONE; - in_use= thd; - copy_blobs= true; - alias.set("", 0, &my_charset_bin); - } - - ~Virtual_tmp_table() - { - if (s) - destruct_fields(); - } - - /** - Allocate components for the given number of fields. - - fields[] - - s->blob_fields[], - - bitmaps: def_read_set, def_write_set, tmp_set, eq_join_set, cond_set. - @param field_count - The number of fields we plan to add to the table. - @returns false - on success. - @returns true - on error. - */ - bool init(uint field_count); - - /** - Add one Field to the end of the field array, update members: - s->reclength, s->fields, s->blob_fields, s->null_fuelds. - */ - bool add(Field *new_field) - { - DBUG_ASSERT(s->fields < m_alloced_field_count); - new_field->init(this); - field[s->fields]= new_field; - s->reclength+= new_field->pack_length(); - if (!(new_field->flags & NOT_NULL_FLAG)) - s->null_fields++; - if (new_field->flags & BLOB_FLAG) - { - // Note, s->blob_fields was incremented in Field_blob::Field_blob - DBUG_ASSERT(s->blob_fields); - DBUG_ASSERT(s->blob_fields <= m_alloced_field_count); - s->blob_field[s->blob_fields - 1]= s->fields; - } - new_field->field_index= s->fields++; - return false; - } - - /** - Add fields from a Spvar_definition list - @returns false - on success. - @returns true - on error. - */ - bool add(List &field_list); - - /** - Open a virtual table for read/write: - - Setup end markers in TABLE::field and TABLE_SHARE::blob_fields, - - Allocate a buffer in TABLE::record[0]. - - Set field pointers (Field::ptr, Field::null_pos, Field::null_bit) to - the allocated record. - This method is called when all of the fields have been added to the table. - After calling this method the table is ready for read and write operations. - @return false - on success - @return true - on error (e.g. could not allocate the record buffer). - */ - bool open(); - - void set_all_fields_to_null() - { - for (uint i= 0; i < s->fields; i++) - field[i]->set_null(); - } - /** - Set all fields from a compatible item list. - The number of fields in "this" must be equal to the number - of elements in "value". - */ - bool sp_set_all_fields_from_item_list(THD *thd, List &items); - - /** - Set all fields from a compatible item. - The number of fields in "this" must be the same with the number - of elements in "value". - */ - bool sp_set_all_fields_from_item(THD *thd, Item *value); - - /** - Find a ROW element index by its name - Assumes that "this" is used as a storage for a ROW-type SP variable. - @param [OUT] idx - the index of the found field is returned here - @param [IN] field_name - find a field with this name - @return true - on error (the field was not found) - @return false - on success (idx[0] was set to the field index) - */ - bool sp_find_field_by_name(uint *idx, const LEX_CSTRING &name) const; - - /** - Find a ROW element index by its name. - If the element is not found, and error is issued. - @param [OUT] idx - the index of the found field is returned here - @param [IN] var_name - the name of the ROW variable (for error reporting) - @param [IN] field_name - find a field with this name - @return true - on error (the field was not found) - @return false - on success (idx[0] was set to the field index) - */ - bool sp_find_field_by_name_or_error(uint *idx, - const LEX_CSTRING &var_name, - const LEX_CSTRING &field_name) const; -}; - - -/** - Create a reduced TABLE object with properly set up Field list from a - list of field definitions. - - The created table doesn't have a table handler associated with - it, has no keys, no group/distinct, no copy_funcs array. - The sole purpose of this TABLE object is to use the power of Field - class to read/write data to/from table->record[0]. Then one can store - the record in any container (RB tree, hash, etc). - The table is created in THD mem_root, so are the table's fields. - Consequently, if you don't BLOB fields, you don't need to free it. - - @param thd connection handle - @param field_list list of column definitions - - @return - 0 if out of memory, or a - TABLE object ready for read and write in case of success -*/ - -inline Virtual_tmp_table * -create_virtual_tmp_table(THD *thd, List &field_list) -{ - Virtual_tmp_table *table; - if (!(table= new(thd) Virtual_tmp_table(thd))) - return NULL; - - /* - If "simulate_create_virtual_tmp_table_out_of_memory" debug option - is enabled, we now enable "simulate_out_of_memory". This effectively - makes table->init() fail on OOM inside multi_alloc_root(). - This is done to test that ~Virtual_tmp_table() called from the "delete" - below correcly handles OOM. - */ - DBUG_EXECUTE_IF("simulate_create_virtual_tmp_table_out_of_memory", - DBUG_SET("+d,simulate_out_of_memory");); - - if (table->init(field_list.elements) || - table->add(field_list) || - table->open()) - { - delete table; - return NULL; - } - return table; -} - - -/** - Create a new virtual temporary table consisting of a single field. - SUM(DISTINCT expr) and similar numeric aggregate functions use this. - @param thd - Current thread - @param field - The field that will be added into the table. - @return NULL - On error. - @return !NULL - A pointer to the created table that is ready - for read and write. -*/ -inline TABLE * -create_virtual_tmp_table(THD *thd, Field *field) -{ - Virtual_tmp_table *table; - DBUG_ASSERT(field); - if (!(table= new(thd) Virtual_tmp_table(thd))) - return NULL; - if (table->init(1) || - table->add(field) || - table->open()) - { - delete table; - return NULL; - } - return table; -} - - -int test_if_item_cache_changed(List &list); -int join_init_read_record(JOIN_TAB *tab); -int join_read_record_no_init(JOIN_TAB *tab); -void set_position(JOIN *join,uint idx,JOIN_TAB *table,KEYUSE *key); -inline Item * and_items(THD *thd, Item* cond, Item *item) -{ - return (cond ? (new (thd->mem_root) Item_cond_and(thd, cond, item)) : item); -} -inline Item * or_items(THD *thd, Item* cond, Item *item) -{ - return (cond ? (new (thd->mem_root) Item_cond_or(thd, cond, item)) : item); -} -bool choose_plan(JOIN *join, table_map join_tables); -void optimize_wo_join_buffering(JOIN *join, uint first_tab, uint last_tab, - table_map last_remaining_tables, - bool first_alt, uint no_jbuf_before, - double *outer_rec_count, double *reopt_cost); -Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, - bool *inherited_fl); -extern bool test_if_ref(Item *, - Item_field *left_item,Item *right_item); - -inline bool optimizer_flag(THD *thd, ulonglong flag) -{ - return (thd->variables.optimizer_switch & flag); -} - -/* -int print_fake_select_lex_join(select_result_sink *result, bool on_the_fly, - SELECT_LEX *select_lex, uint8 select_options); -*/ - -uint get_index_for_order(ORDER *order, TABLE *table, SQL_SELECT *select, - ha_rows limit, ha_rows *scanned_limit, - bool *need_sort, bool *reverse); -ORDER *simple_remove_const(ORDER *order, COND *where); -bool const_expression_in_where(COND *cond, Item *comp_item, - Field *comp_field= NULL, - Item **const_item= NULL); -bool cond_is_datetime_is_null(Item *cond); -bool cond_has_datetime_is_null(Item *cond); - -/* Table elimination entry point function */ -void eliminate_tables(JOIN *join); - -/* Index Condition Pushdown entry point function */ -void push_index_cond(JOIN_TAB *tab, uint keyno); - -#define OPT_LINK_EQUAL_FIELDS 1 - -/* EXPLAIN-related utility functions */ -int print_explain_message_line(select_result_sink *result, - uint8 options, bool is_analyze, - uint select_number, - const char *select_type, - ha_rows *rows, - const char *message); -void explain_append_mrr_info(QUICK_RANGE_SELECT *quick, String *res); -int append_possible_keys(MEM_ROOT *alloc, String_list &list, TABLE *table, - key_map possible_keys); - -/**************************************************************************** - Temporary table support for SQL Runtime - ***************************************************************************/ - -#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128 -#define AVG_STRING_LENGTH_TO_PACK_ROWS 64 -#define RATIO_TO_PACK_ROWS 2 -#define MIN_STRING_LENGTH_TO_PACK_ROWS 10 - -void calc_group_buffer(TMP_TABLE_PARAM *param, ORDER *group); -TABLE *create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List &fields, - ORDER *group, bool distinct, bool save_sum_fields, - ulonglong select_options, ha_rows rows_limit, - const LEX_CSTRING *alias, bool do_not_open=FALSE, - bool keep_row_order= FALSE); -TABLE *create_tmp_table_for_schema(THD *thd, TMP_TABLE_PARAM *param, - const ST_SCHEMA_TABLE &schema_table, - longlong select_options, - const LEX_CSTRING &alias, - bool do_not_open, bool keep_row_order); - -void free_tmp_table(THD *thd, TABLE *entry); -bool create_internal_tmp_table_from_heap(THD *thd, TABLE *table, - TMP_ENGINE_COLUMNDEF *start_recinfo, - TMP_ENGINE_COLUMNDEF **recinfo, - int error, bool ignore_last_dupp_key_error, - bool *is_duplicate); -bool create_internal_tmp_table(TABLE *table, KEY *keyinfo, - TMP_ENGINE_COLUMNDEF *start_recinfo, - TMP_ENGINE_COLUMNDEF **recinfo, - ulonglong options); -bool instantiate_tmp_table(TABLE *table, KEY *keyinfo, - TMP_ENGINE_COLUMNDEF *start_recinfo, - TMP_ENGINE_COLUMNDEF **recinfo, - ulonglong options); -bool open_tmp_table(TABLE *table); -void setup_tmp_table_column_bitmaps(TABLE *table, uchar *bitmaps); -double prev_record_reads(const POSITION *positions, uint idx, table_map found_ref); -void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List *tlist); -double get_tmp_table_lookup_cost(THD *thd, double row_count, uint row_size); -double get_tmp_table_write_cost(THD *thd, double row_count, uint row_size); -void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array); -bool sort_and_filter_keyuse(THD *thd, DYNAMIC_ARRAY *keyuse, - bool skip_unprefixed_keyparts); - -struct st_cond_statistic -{ - Item *cond; - Field *field_arg; - ulong positive; -}; -typedef struct st_cond_statistic COND_STATISTIC; - -ulong check_selectivity(THD *thd, - ulong rows_to_read, - TABLE *table, - List *conds); - -class Pushdown_query: public Sql_alloc -{ -public: - SELECT_LEX *select_lex; - bool store_data_in_temp_table; - group_by_handler *handler; - Item *having; - - Pushdown_query(SELECT_LEX *select_lex_arg, group_by_handler *handler_arg) - : select_lex(select_lex_arg), store_data_in_temp_table(0), - handler(handler_arg), having(0) {} - - ~Pushdown_query() { delete handler; } - - /* Function that calls the above scan functions */ - int execute(JOIN *); -}; - -class derived_handler; - -class Pushdown_derived: public Sql_alloc -{ -private: - bool is_analyze; -public: - TABLE_LIST *derived; - derived_handler *handler; - - Pushdown_derived(TABLE_LIST *tbl, derived_handler *h); - - ~Pushdown_derived(); - - int execute(); -}; - - -class select_handler; - - -bool test_if_order_compatible(SQL_I_List &a, SQL_I_List &b); -int test_if_group_changed(List &list); -int create_sort_index(THD *thd, JOIN *join, JOIN_TAB *tab, Filesort *fsort); - -JOIN_TAB *first_explain_order_tab(JOIN* join); -JOIN_TAB *next_explain_order_tab(JOIN* join, JOIN_TAB* tab); - -bool check_simple_equality(THD *thd, const Item::Context &ctx, - Item *left_item, Item *right_item, - COND_EQUAL *cond_equal); - -void propagate_new_equalities(THD *thd, Item *cond, - List *new_equalities, - COND_EQUAL *inherited, - bool *is_simplifiable_cond); - -#endif /* SQL_SELECT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_sequence.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_sequence.h deleted file mode 100644 index 2d609d8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_sequence.h +++ /dev/null @@ -1,167 +0,0 @@ -/* Copyright (c) 2017, MariaDB corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef SQL_SEQUENCE_INCLUDED -#define SQL_SEQUENCE_INCLUDED - -#define seq_field_used_min_value 1 -#define seq_field_used_max_value 2 -#define seq_field_used_start 4 -#define seq_field_used_increment 8 -#define seq_field_used_cache 16 -#define seq_field_used_cycle 32 -#define seq_field_used_restart 64 -#define seq_field_used_restart_value 128 - -/* Field position in sequence table for some fields we refer to directly */ -#define NEXT_FIELD_NO 0 -#define MIN_VALUE_FIELD_NO 1 -#define ROUND_FIELD_NO 7 - -/** - sequence_definition is used when defining a sequence as part of create -*/ - -class sequence_definition :public Sql_alloc -{ -public: - sequence_definition(): - min_value(1), max_value(LONGLONG_MAX-1), start(1), increment(1), - cache(1000), round(0), restart(0), cycle(0), used_fields(0) - {} - longlong reserved_until; - longlong min_value; - longlong max_value; - longlong start; - longlong increment; - longlong cache; - ulonglong round; - longlong restart; // alter sequence restart value - bool cycle; - uint used_fields; // Which fields where used in CREATE - - bool check_and_adjust(bool set_reserved_until); - void store_fields(TABLE *table); - void read_fields(TABLE *table); - int write_initial_sequence(TABLE *table); - int write(TABLE *table, bool all_fields); - /* This must be called after sequence data has been updated */ - void adjust_values(longlong next_value); - inline void print_dbug() - { - DBUG_PRINT("sequence", ("reserved: %lld start: %lld increment: %lld min_value: %lld max_value: %lld cache: %lld round: %lld", - reserved_until, start, increment, min_value, - max_value, cache, round)); - } -protected: - /* - The following values are the values from sequence_definition - merged with global auto_increment_offset and auto_increment_increment - */ - longlong real_increment; - longlong next_free_value; -}; - -/** - SEQUENCE is in charge of managing the sequence values. - It's also responsible to generate new values and updating the sequence - table (engine=SQL_SEQUENCE) trough it's specialized handler interface. - - If increment is 0 then the sequence will be be using - auto_increment_increment and auto_increment_offset variables, just like - AUTO_INCREMENT is using. -*/ - -class SEQUENCE :public sequence_definition -{ -public: - enum seq_init { SEQ_UNINTIALIZED, SEQ_IN_PREPARE, SEQ_IN_ALTER, - SEQ_READY_TO_USE }; - SEQUENCE(); - ~SEQUENCE(); - int read_initial_values(TABLE *table); - int read_stored_values(TABLE *table); - void write_lock(TABLE *table); - void write_unlock(TABLE *table); - void read_lock(TABLE *table); - void read_unlock(TABLE *table); - void copy(sequence_definition *seq) - { - sequence_definition::operator= (*seq); - adjust_values(reserved_until); - all_values_used= 0; - } - longlong next_value(TABLE *table, bool second_round, int *error); - int set_value(TABLE *table, longlong next_value, ulonglong round_arg, - bool is_used); - longlong increment_value(longlong value) - { - if (real_increment > 0) - { - if (value + real_increment > max_value || - value > max_value - real_increment) - value= max_value + 1; - else - value+= real_increment; - } - else - { - if (value + real_increment < min_value || - value < min_value - real_increment) - value= min_value - 1; - else - value+= real_increment; - } - return value; - } - - bool all_values_used; - seq_init initialized; - -private: - mysql_rwlock_t mutex; -}; - - -/** - Class to cache last value of NEXT VALUE from the sequence -*/ - -class SEQUENCE_LAST_VALUE -{ -public: - SEQUENCE_LAST_VALUE(uchar *key_arg, uint length_arg) - :key(key_arg), length(length_arg) - {} - ~SEQUENCE_LAST_VALUE() - { my_free((void*) key); } - /* Returns 1 if table hasn't been dropped or re-created */ - bool check_version(TABLE *table); - void set_version(TABLE *table); - - const uchar *key; - uint length; - bool null_value; - longlong value; - uchar table_version[MY_UUID_SIZE]; -}; - - -class Create_field; -extern bool prepare_sequence_fields(THD *thd, List *fields); -extern bool check_sequence_fields(LEX *lex, List *fields); -extern bool sequence_insert(THD *thd, LEX *lex, TABLE_LIST *table_list); -#endif /* SQL_SEQUENCE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_servers.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_servers.h deleted file mode 100644 index cb5703e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_servers.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef SQL_SERVERS_INCLUDED -#define SQL_SERVERS_INCLUDED - -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "slave.h" // for tables_ok(), rpl_filter - -class THD; -typedef struct st_lex_server_options LEX_SERVER_OPTIONS; -typedef struct st_mem_root MEM_ROOT; - -/* structs */ -typedef struct st_federated_server -{ - const char *server_name; - long port; - size_t server_name_length; - const char *db, *scheme, *username, *password, *socket, *owner, *host, *sport; -} FOREIGN_SERVER; - -/* cache handlers */ -bool servers_init(bool dont_read_server_table); -bool servers_reload(THD *thd); -void servers_free(bool end=0); - -/* insert functions */ -int create_server(THD *thd, LEX_SERVER_OPTIONS *server_options); - -/* drop functions */ -int drop_server(THD *thd, LEX_SERVER_OPTIONS *server_options); - -/* update functions */ -int alter_server(THD *thd, LEX_SERVER_OPTIONS *server_options); - -/* lookup functions */ -FOREIGN_SERVER *get_server_by_name(MEM_ROOT *mem, const char *server_name, - FOREIGN_SERVER *server_buffer); - -#endif /* SQL_SERVERS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_show.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_show.h deleted file mode 100644 index 80588cd..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_show.h +++ /dev/null @@ -1,258 +0,0 @@ -/* Copyright (c) 2005, 2010, Oracle and/or its affiliates. - Copyright (c) 2012, 2016, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_SHOW_H -#define SQL_SHOW_H - -#include "sql_list.h" /* List */ -#include "handler.h" /* enum_schema_tables */ -#include "table.h" /* enum_schema_table_state */ -#include "my_apc.h" - -/* Forward declarations */ -class JOIN; -class String; -class THD; -class sp_name; -struct TABLE_LIST; -typedef class st_select_lex SELECT_LEX; -struct LEX; -typedef struct st_mysql_show_var SHOW_VAR; -typedef struct st_schema_table ST_SCHEMA_TABLE; -struct TABLE; -typedef struct system_status_var STATUS_VAR; - -/* Used by handlers to store things in schema tables */ -#define IS_FILES_FILE_ID 0 -#define IS_FILES_FILE_NAME 1 -#define IS_FILES_FILE_TYPE 2 -#define IS_FILES_TABLESPACE_NAME 3 -#define IS_FILES_TABLE_CATALOG 4 -#define IS_FILES_TABLE_SCHEMA 5 -#define IS_FILES_TABLE_NAME 6 -#define IS_FILES_LOGFILE_GROUP_NAME 7 -#define IS_FILES_LOGFILE_GROUP_NUMBER 8 -#define IS_FILES_ENGINE 9 -#define IS_FILES_FULLTEXT_KEYS 10 -#define IS_FILES_DELETED_ROWS 11 -#define IS_FILES_UPDATE_COUNT 12 -#define IS_FILES_FREE_EXTENTS 13 -#define IS_FILES_TOTAL_EXTENTS 14 -#define IS_FILES_EXTENT_SIZE 15 -#define IS_FILES_INITIAL_SIZE 16 -#define IS_FILES_MAXIMUM_SIZE 17 -#define IS_FILES_AUTOEXTEND_SIZE 18 -#define IS_FILES_CREATION_TIME 19 -#define IS_FILES_LAST_UPDATE_TIME 20 -#define IS_FILES_LAST_ACCESS_TIME 21 -#define IS_FILES_RECOVER_TIME 22 -#define IS_FILES_TRANSACTION_COUNTER 23 -#define IS_FILES_VERSION 24 -#define IS_FILES_ROW_FORMAT 25 -#define IS_FILES_TABLE_ROWS 26 -#define IS_FILES_AVG_ROW_LENGTH 27 -#define IS_FILES_DATA_LENGTH 28 -#define IS_FILES_MAX_DATA_LENGTH 29 -#define IS_FILES_INDEX_LENGTH 30 -#define IS_FILES_DATA_FREE 31 -#define IS_FILES_CREATE_TIME 32 -#define IS_FILES_UPDATE_TIME 33 -#define IS_FILES_CHECK_TIME 34 -#define IS_FILES_CHECKSUM 35 -#define IS_FILES_STATUS 36 -#define IS_FILES_EXTRA 37 - -typedef enum { WITHOUT_DB_NAME, WITH_DB_NAME } enum_with_db_name; - -int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond); - -int show_create_table(THD *thd, TABLE_LIST *table_list, String *packet, - Table_specification_st *create_info_arg, - enum_with_db_name with_db_name); - -int show_create_table_ex(THD *thd, TABLE_LIST *table_list, - const char * forced_db, const char *forced_name, - String *packet, - Table_specification_st *create_info_arg, - enum_with_db_name with_db_name); - -int copy_event_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table); - -bool append_identifier(THD *thd, String *packet, const char *name, size_t length); -static inline bool append_identifier(THD *thd, String *packet, const LEX_CSTRING *name) -{ - return append_identifier(thd, packet, name->str, name->length); -} -void mysqld_list_fields(THD *thd,TABLE_LIST *table, const char *wild); -int mysqld_dump_create_info(THD *thd, TABLE_LIST *table_list, int fd); -bool mysqld_show_create_get_fields(THD *thd, TABLE_LIST *table_list, - List *field_list, String *buffer); -bool mysqld_show_create(THD *thd, TABLE_LIST *table_list); -void mysqld_show_create_db_get_fields(THD *thd, List *field_list); -bool mysqld_show_create_db(THD *thd, LEX_CSTRING *db_name, - LEX_CSTRING *orig_db_name, - const DDL_options_st &options); - -void mysqld_list_processes(THD *thd,const char *user,bool verbose); -int mysqld_show_status(THD *thd); -int mysqld_show_variables(THD *thd,const char *wild); -bool mysqld_show_storage_engines(THD *thd); -bool mysqld_show_authors(THD *thd); -bool mysqld_show_contributors(THD *thd); -bool mysqld_show_privileges(THD *thd); -char *make_backup_log_name(char *buff, const char *name, const char* log_ext); -uint calc_sum_of_all_status(STATUS_VAR *to); -bool append_definer(THD *thd, String *buffer, const LEX_CSTRING *definer_user, - const LEX_CSTRING *definer_host); -int add_status_vars(SHOW_VAR *list); -void remove_status_vars(SHOW_VAR *list); -ulonglong get_status_vars_version(void); -void init_status_vars(); -void free_status_vars(); -void reset_status_vars(); -bool show_create_trigger(THD *thd, const sp_name *trg_name); -void view_store_options(THD *thd, TABLE_LIST *table, String *buff); - -void init_fill_schema_files_row(TABLE* table); -void initialize_information_schema_acl(); - -ST_SCHEMA_TABLE *find_schema_table(THD *thd, const LEX_CSTRING *table_name, - bool *in_plugin); -static inline ST_SCHEMA_TABLE *find_schema_table(THD *thd, const LEX_CSTRING *table_name) -{ bool unused; return find_schema_table(thd, table_name, &unused); } - -ST_SCHEMA_TABLE *get_schema_table(enum enum_schema_tables schema_table_idx); -int make_schema_select(THD *thd, SELECT_LEX *sel, - ST_SCHEMA_TABLE *schema_table); -int mysql_schema_table(THD *thd, LEX *lex, TABLE_LIST *table_list); -bool get_schema_tables_result(JOIN *join, - enum enum_schema_table_state executed_place); -enum enum_schema_tables get_schema_table_idx(ST_SCHEMA_TABLE *schema_table); -TABLE *create_schema_table(THD *thd, TABLE_LIST *table_list); - -const char* get_one_variable(THD *thd, const SHOW_VAR *variable, - enum_var_type value_type, SHOW_TYPE show_type, - system_status_var *status_var, - const CHARSET_INFO **charset, char *buff, - size_t *length); - -/* These functions were under INNODB_COMPATIBILITY_HOOKS */ -int get_quote_char_for_identifier(THD *thd, const char *name, size_t length); -THD *find_thread_by_id(longlong id, bool query_id= false); - -class select_result_explain_buffer; -/* - SHOW EXPLAIN request object. -*/ - -class Show_explain_request : public Apc_target::Apc_call -{ -public: - THD *target_thd; /* thd that we're running SHOW EXPLAIN for */ - THD *request_thd; /* thd that run SHOW EXPLAIN command */ - - /* If true, there was some error when producing EXPLAIN output. */ - bool failed_to_produce; - - /* SHOW EXPLAIN will be stored here */ - select_result_explain_buffer *explain_buf; - - /* Query that we've got SHOW EXPLAIN for */ - String query_str; - - /* Overloaded virtual function */ - void call_in_target_thread(); -}; - -/** - Condition pushdown used for INFORMATION_SCHEMA / SHOW queries. - This structure is to implement an optimization when - accessing data dictionary data in the INFORMATION_SCHEMA - or SHOW commands. - When the query contain a TABLE_SCHEMA or TABLE_NAME clause, - narrow the search for data based on the constraints given. -*/ -typedef struct st_lookup_field_values -{ - /** - Value of a TABLE_SCHEMA clause. - Note that this value length may exceed @c NAME_LEN. - @sa wild_db_value - */ - LEX_CSTRING db_value; - /** - Value of a TABLE_NAME clause. - Note that this value length may exceed @c NAME_LEN. - @sa wild_table_value - */ - LEX_CSTRING table_value; - /** - True when @c db_value is a LIKE clause, - false when @c db_value is an '=' clause. - */ - bool wild_db_value; - /** - True when @c table_value is a LIKE clause, - false when @c table_value is an '=' clause. - */ - bool wild_table_value; -} LOOKUP_FIELD_VALUES; - -/* - INFORMATION_SCHEMA: Execution plan for get_all_tables() call -*/ - -class IS_table_read_plan : public Sql_alloc -{ -public: - IS_table_read_plan() : no_rows(false), trivial_show_command(FALSE) {} - - bool no_rows; - /* - For EXPLAIN only: For SHOW KEYS and SHOW COLUMNS, we know which - db_name.table_name will be read, however for some reason we don't - set the fields in this->lookup_field_vals. - In order to not have JOIN::save_explain_data() walking over uninitialized - data, we set trivial_show_command=true. - */ - bool trivial_show_command; - - LOOKUP_FIELD_VALUES lookup_field_vals; - Item *partial_cond; - - bool has_db_lookup_value() - { - return (lookup_field_vals.db_value.length && - !lookup_field_vals.wild_db_value); - } - bool has_table_lookup_value() - { - return (lookup_field_vals.table_value.length && - !lookup_field_vals.wild_table_value); - } -}; - -bool optimize_schema_tables_reads(JOIN *join); - -/* Handle the ignored database directories list for SHOW/I_S. */ -bool ignore_db_dirs_init(); -void ignore_db_dirs_free(); -void ignore_db_dirs_reset(); -bool ignore_db_dirs_process_additions(); -bool push_ignored_db_dir(char *path); -extern char *opt_ignore_db_dirs; - -#endif /* SQL_SHOW_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_signal.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_signal.h deleted file mode 100644 index bf42cdb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_signal.h +++ /dev/null @@ -1,126 +0,0 @@ -/* Copyright (c) 2008 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_SIGNAL_H -#define SQL_SIGNAL_H - -/** - Sql_cmd_common_signal represents the common properties of the - SIGNAL and RESIGNAL statements. -*/ -class Sql_cmd_common_signal : public Sql_cmd -{ -protected: - /** - Constructor. - @param cond the condition signaled if any, or NULL. - @param set collection of signal condition item assignments. - */ - Sql_cmd_common_signal(const sp_condition_value *cond, - const Set_signal_information& set) - : Sql_cmd(), - m_cond(cond), - m_set_signal_information(set) - {} - - virtual ~Sql_cmd_common_signal() - {} - - /** - Evaluate each signal condition items for this statement. - @param thd the current thread. - @param cond the condition to update. - @return 0 on success. - */ - int eval_signal_informations(THD *thd, Sql_condition *cond); - - /** - Raise a SQL condition. - @param thd the current thread. - @param cond the condition to raise. - @return false on success. - */ - bool raise_condition(THD *thd, Sql_condition *cond); - - /** - The condition to signal or resignal. - This member is optional and can be NULL (RESIGNAL). - */ - const sp_condition_value *m_cond; - - /** - Collection of 'SET item = value' assignments in the - SIGNAL/RESIGNAL statement. - */ - Set_signal_information m_set_signal_information; -}; - -/** - Sql_cmd_signal represents a SIGNAL statement. -*/ -class Sql_cmd_signal : public Sql_cmd_common_signal -{ -public: - /** - Constructor, used to represent a SIGNAL statement. - @param cond the SQL condition to signal (required). - @param set the collection of signal informations to signal. - */ - Sql_cmd_signal(const sp_condition_value *cond, - const Set_signal_information& set) - : Sql_cmd_common_signal(cond, set) - {} - - virtual ~Sql_cmd_signal() - {} - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_SIGNAL; - } - - virtual bool execute(THD *thd); -}; - -/** - Sql_cmd_resignal represents a RESIGNAL statement. -*/ -class Sql_cmd_resignal : public Sql_cmd_common_signal -{ -public: - /** - Constructor, used to represent a RESIGNAL statement. - @param cond the SQL condition to resignal (optional, may be NULL). - @param set the collection of signal informations to resignal. - */ - Sql_cmd_resignal(const sp_condition_value *cond, - const Set_signal_information& set) - : Sql_cmd_common_signal(cond, set) - {} - - virtual ~Sql_cmd_resignal() - {} - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_RESIGNAL; - } - - virtual bool execute(THD *thd); -}; - -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_sort.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_sort.h deleted file mode 100644 index a474d7c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_sort.h +++ /dev/null @@ -1,712 +0,0 @@ -#ifndef SQL_SORT_INCLUDED -#define SQL_SORT_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "my_base.h" /* ha_rows */ -#include /* qsort2_cmp */ -#include "queues.h" -#include "sql_class.h" - -class Field; -struct TABLE; - -/* Defines used by filesort and uniques */ - -#define MERGEBUFF 7 -#define MERGEBUFF2 15 - -/* - The structure SORT_ADDON_FIELD describes a fixed layout - for field values appended to sorted values in records to be sorted - in the sort buffer. - Only fixed layout is supported now. - Null bit maps for the appended values is placed before the values - themselves. Offsets are from the last sorted field, that is from the - record referefence, which is still last component of sorted records. - It is preserved for backward compatiblility. - The structure is used tp store values of the additional fields - in the sort buffer. It is used also when these values are read - from a temporary file/buffer. As the reading procedures are beyond the - scope of the 'filesort' code the values have to be retrieved via - the callback function 'unpack_addon_fields'. -*/ - -typedef struct st_sort_addon_field -{ - /* Sort addon packed field */ - Field *field; /* Original field */ - uint offset; /* Offset from the last sorted field */ - uint null_offset; /* Offset to to null bit from the last sorted field */ - uint length; /* Length in the sort buffer */ - uint8 null_bit; /* Null bit mask for the field */ -} SORT_ADDON_FIELD; - -struct BUFFPEK_COMPARE_CONTEXT -{ - qsort_cmp2 key_compare; - void *key_compare_arg; -}; - - -/** - Descriptor for a merge chunk to be sort-merged. - A merge chunk is a sequence of pre-sorted records, written to a - temporary file. A Merge_chunk instance describes where this chunk is stored - in the file, and where it is located when it is in memory. - - It is a POD because - - we read/write them from/to files. - - We have accessors (getters/setters) for all struct members. - */ - -struct Merge_chunk { -public: - my_off_t file_position() const { return m_file_position; } - void set_file_position(my_off_t val) { m_file_position= val; } - void advance_file_position(my_off_t val) { m_file_position+= val; } - - uchar *buffer_start() { return m_buffer_start; } - const uchar *buffer_end() const { return m_buffer_end; } - - void set_buffer(uchar *start, uchar *end) - { - m_buffer_start= start; - m_buffer_end= end; - } - void set_buffer_start(uchar *start) - { - m_buffer_start= start; - } - void set_buffer_end(uchar *end) - { - DBUG_ASSERT(m_buffer_end == NULL || end <= m_buffer_end); - m_buffer_end= end; - } - - void init_current_key() { m_current_key= m_buffer_start; } - uchar *current_key() { return m_current_key; } - void advance_current_key(uint val) { m_current_key+= val; } - - void decrement_rowcount(ha_rows val) { m_rowcount-= val; } - void set_rowcount(ha_rows val) { m_rowcount= val; } - ha_rows rowcount() const { return m_rowcount; } - - ha_rows mem_count() const { return m_mem_count; } - void set_mem_count(ha_rows val) { m_mem_count= val; } - ha_rows decrement_mem_count() { return --m_mem_count; } - - ha_rows max_keys() const { return m_max_keys; } - void set_max_keys(ha_rows val) { m_max_keys= val; } - - size_t buffer_size() const { return m_buffer_end - m_buffer_start; } - - /** - Tries to merge *this with *mc, returns true if successful. - The assumption is that *this is no longer in use, - and the space it has been allocated can be handed over to a - buffer which is adjacent to it. - */ - bool merge_freed_buff(Merge_chunk *mc) const - { - if (mc->m_buffer_end == m_buffer_start) - { - mc->m_buffer_end= m_buffer_end; - mc->m_max_keys+= m_max_keys; - return true; - } - else if (mc->m_buffer_start == m_buffer_end) - { - mc->m_buffer_start= m_buffer_start; - mc->m_max_keys+= m_max_keys; - return true; - } - return false; - } - - /// The current key for this chunk - uchar *m_current_key= nullptr; - /// Current position in the file to be sorted. - my_off_t m_file_position= 0; - /// Start of main-memory buffer for this chunk. - uchar *m_buffer_start= nullptr; - /// End of main-memory buffer for this chunk. - uchar *m_buffer_end= nullptr; - /// Number of unread rows in this chunk. - ha_rows m_rowcount= 0; - /// Number of rows in the main-memory buffer. - ha_rows m_mem_count= 0; - /// If we have fixed-size rows: max number of rows in buffer. - ha_rows m_max_keys= 0; -}; - -typedef Bounds_checked_array Addon_fields_array; -typedef Bounds_checked_array Sort_keys_array; - -/** - This class wraps information about usage of addon fields. - An Addon_fields object is used both during packing of data in the filesort - buffer, and later during unpacking in 'Filesort_info::unpack_addon_fields'. - - @see documentation for the Sort_addon_field struct. - @see documentation for get_addon_fields() - */ -class Addon_fields { -public: - Addon_fields(Addon_fields_array arr) - : m_field_descriptors(arr), - m_addon_buf(), - m_addon_buf_length(), - m_using_packed_addons(false) - { - DBUG_ASSERT(!arr.is_null()); - } - - SORT_ADDON_FIELD *begin() { return m_field_descriptors.begin(); } - SORT_ADDON_FIELD *end() { return m_field_descriptors.end(); } - - /// rr_unpack_from_tempfile needs an extra buffer when unpacking. - uchar *allocate_addon_buf(uint sz) - { - m_addon_buf= (uchar *)my_malloc(PSI_INSTRUMENT_ME, sz, MYF(MY_WME | MY_THREAD_SPECIFIC)); - if (m_addon_buf) - m_addon_buf_length= sz; - return m_addon_buf; - } - - void free_addon_buff() - { - my_free(m_addon_buf); - m_addon_buf= NULL; - m_addon_buf_length= 0; - } - - uchar *get_addon_buf() { return m_addon_buf; } - uint get_addon_buf_length() const { return m_addon_buf_length; } - - void set_using_packed_addons(bool val) - { - m_using_packed_addons= val; - } - - bool using_packed_addons() const - { - return m_using_packed_addons; - } - - static bool can_pack_addon_fields(uint record_length) - { - return (record_length <= (0xFFFF)); - } - - /** - @returns Total number of bytes used for packed addon fields. - the size of the length field + size of null bits + sum of field sizes. - */ - static uint read_addon_length(uchar *p) - { - return size_of_length_field + uint2korr(p); - } - - /** - Stores the number of bytes used for packed addon fields. - */ - static void store_addon_length(uchar *p, uint sz) - { - // We actually store the length of everything *after* the length field. - int2store(p, sz - size_of_length_field); - } - - static const uint size_of_length_field= 2; - -private: - Addon_fields_array m_field_descriptors; - - uchar *m_addon_buf; ///< Buffer for unpacking addon fields. - uint m_addon_buf_length; ///< Length of the buffer. - bool m_using_packed_addons; ///< Are we packing the addon fields? -}; - -/** - This class wraps information about usage of sort keys. - A Sort_keys object is used both during packing of data in the filesort - buffer, and later during unpacking in 'Filesort_info::unpack_addon_fields'. - - @see SORT_FIELD struct. -*/ - -class Sort_keys :public Sql_alloc, - public Sort_keys_array -{ -public: - Sort_keys(SORT_FIELD* arr, size_t count): - Sort_keys_array(arr, count), - m_using_packed_sortkeys(false), - size_of_packable_fields(0), - sort_length_with_original_values(0), - sort_length_with_memcmp_values(0), - parameters_computed(false) - { - DBUG_ASSERT(!is_null()); - } - - bool using_packed_sortkeys() const - { return m_using_packed_sortkeys; } - - void set_using_packed_sortkeys(bool val) - { - m_using_packed_sortkeys= val; - } - void set_size_of_packable_fields(uint len) - { - size_of_packable_fields= len; - } - - uint get_size_of_packable_fields() - { - return size_of_packable_fields; - } - - void set_sort_length_with_original_values(uint len) - { - sort_length_with_original_values= len; - } - - uint get_sort_length_with_original_values() - { - return sort_length_with_original_values; - } - - void set_sort_length_with_memcmp_values(uint len) - { - sort_length_with_memcmp_values= len; - } - - uint get_sort_length_with_memcmp_values() - { - return sort_length_with_memcmp_values; - } - - static void store_sortkey_length(uchar *p, uint sz) - { - int4store(p, sz - size_of_length_field); - } - - static uint read_sortkey_length(uchar *p) - { - return size_of_length_field + uint4korr(p); - } - - void increment_size_of_packable_fields(uint len) - { - size_of_packable_fields+= len; - } - - void increment_original_sort_length(uint len) - { - sort_length_with_original_values+= len; - } - - bool is_parameters_computed() { return parameters_computed; } - void set_parameters_computed(bool val) { parameters_computed= val; } - - static const uint size_of_length_field= 4; - -private: - bool m_using_packed_sortkeys; // Are we packing sort keys - uint size_of_packable_fields; // Total length bytes for packable columns - - /* - The sort length for all the keyparts storing the original values - */ - uint sort_length_with_original_values; - - /* - The sort length for all the keyparts storing the mem-comparable images - */ - uint sort_length_with_memcmp_values; - - /* - TRUE parameters(like sort_length_* , size_of_packable_field) - are computed - FALSE otherwise. - */ - bool parameters_computed; -}; - - -/** -PACKED SORT KEYS - -Description - -In this optimization where we would like the pack the values of the sort key -inside the sort buffer for each record. - -Contents: -1. Background -1.1 Implementation details -2. Solution : Packed Sort Keys -2.1 Packed key format -2.2 Which format to use -3. Special cases -3.1 Handling very long strings -3.2 Handling for long binary strings -3.3 Handling very long strings with Packed sort keys -4. Sort key columns in addon_fields - -1. Background -Before this optimization of using packed sort keys, filesort() sorted the -data using mem-comparable keys. - -That is, if we wanted to sort by - - ORDER BY col1, col2, ... colN -then the filesort code would for each row generate one "Sort Key" -and then sort the rows by their Sort Keys. - -The Sort Keys are mem-comparable (that is, are compared by memcmp()) and -they are of FIXED SIZE. The sort key has the same length regardless of -what value it represents. This causes INEFFICIENT MEMORY USAGE. - -1.1 Implementation details - -make_sortkey() is the function that produces a sort key -from a record. - -The function treats Field and Item objects differently. - -class Field has: - -a) void make_sort_key(uchar *buff, uint length); - make_sort_key is a non-virtual function which handles encoding of - SQL null values. - -b) virtual void sort_string(uchar *buff,uint length)=0; - sort_string produces mem-comparable image of the field value - for each datatype. - -For Items, Type_handler has a virtual function: - - virtual void make_sort_key(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const= 0; - which various datatypes overload. - - -2. SOLUTION: PACKED SORT KEYS - -Note that one can have mem-comparable keys are that are not fixed-size. -MyRocks uses such encoding for example. - -However for this optimization it was decided to store the original -(non-mem-comparable) values instead and use a datatype-aware -key comparison function. - -2.1 Packed key format -The keys are stored in a new variable-size data format called "packed". - -The format is as follows: - - ....... - - format for a n-part sort key - - is the length of the whole key. -Each packed value is encoded as follows: - - // This is a an SQL NULL - [] // this a non-NULL value -null_byte is present if the field/item is NULLable. -SQL NULL is encoded as just one NULL-indicator byte. The value itself is omitted. - -The format of the packed_value depends on the datatype. -For "non-packable" datatypes it is just their mem-comparable form, as before. - -The "packable" datatypes are currently variable-length strings and the -packed format for them is (for binary blobs, see a note below): - - -2.2 Which format to use - -The advantage of Packed Key Format is potential space savings for -variable-length fields. - -The disadvantages are: - -a) It may actually take more space, because of sort_key_length and - length fields. -b) The comparison function is more expensive. - -Currently the logic is: use Packed Key Format if we would save 128 or more -bytes when constructing a sort key from values that have empty string -for each packable component. - -3. SPECIAL CASES -3.1 HANDLING VERY LONG STRINGS -the size of sort key part was limited by @@max_sort_length variable. -It is defined as: - -The number of bytes to use when sorting data values. The server uses only the -first max_sort_length bytes of each value and ignores the rest. - -3.2 HANDLING VERY LONG BINARY STRINGS -Long binary strings receive special treatment. A sort key for the long -binary string is truncated at max_sort_length bytes like described above, -but then a "suffix" is appended which contains the total length of the -value before the truncation. - -3.3 HANDLING VERY LONG STRINGS WITH PACKED SORT KEY -Truncating multi-byte string at N bytes is not safe because one can cut in the -middle of a character. One is tempted to solve this by discarding the partial -character but that's also not a good idea as in some collations multiple -characters may produce one weight (this is called "contraction"). - -This combination of circumstances: - -The string value is very long, so truncation is necessary -The collation is "complex", so truncation is dangerous -is deemed to be relatively rare so it was decided to just use -the non-packed sort keys in this case. - -4. SORT KEY COLUMNS IN ADDON FIELDS -Currently, each sort key column is actually stored twice -1. as part of the sort key -2. in the addon_fields -This made total sense when sort key stored the mem-comparable image -(from which one cannot restore the original value in general case). -But since we now store the original value, we could also remove it from the -addon_fields and further save space. This is still a limitation and needs -to be fixed later - -@see Sort_keys - -**/ - -/** - The sort record format may use one of two formats for the non-sorted part of - the record: - - 1. Use the rowid - - || | - / / ref_length / - - 2. Use "addon fields" - - |||...| - / / addon_length / - - The packed format for "addon fields" - - ||||...| - / / addon_length / - - The key may use one of the two formats: - A. fixed-size mem-comparable form. The record is always - sort_length bytes long. - B. "PackedKeyFormat" - the records are variable-size. - - Fields are fixed-size, specially encoded with - Field::make_sort_key() so we can do byte-by-byte compare. - - Contains the *actual* packed length (after packing) of - everything after the sort keys. - The size of the length field is 2 bytes, - which should cover most use cases: addon data <= 65535 bytes. - This is the same as max record size in MySQL. - One bit for each nullable field, indicating whether the field - is null or not. May have size zero if no fields are nullable. - Are stored with field->pack(), and retrieved with - field->unpack(). Addon fields within a record are stored - consecutively, with no "holes" or padding. They will have zero - size for NULL values. - -*/ - -class Sort_param { -public: - uint rec_length; // Length of sorted records. - uint sort_length; // Length of sorted columns. - uint ref_length; // Length of record ref. - uint addon_length; // Length of addon_fields - uint res_length; // Length of records in final sorted file/buffer. - uint max_keys_per_buffer; // Max keys / buffer. - uint min_dupl_count; - ha_rows max_rows; // Select limit, or HA_POS_ERROR if unlimited. - ha_rows examined_rows; // Number of examined rows. - TABLE *sort_form; // For quicker make_sortkey. - /** - ORDER BY list with some precalculated info for filesort. - Array is created and owned by a Filesort instance. - */ - Bounds_checked_array local_sortorder; - Addon_fields *addon_fields; // Descriptors for companion fields. - Sort_keys *sort_keys; - bool using_pq; - - uchar *unique_buff; - bool not_killable; - String tmp_buffer; - // The fields below are used only by Unique class. - qsort2_cmp compare; - BUFFPEK_COMPARE_CONTEXT cmp_context; - - Sort_param() - { - memset(reinterpret_cast(this), 0, sizeof(*this)); - tmp_buffer.set_thread_specific(); - /* - Fix memset() clearing the charset. - TODO: The constructor should be eventually rewritten not to use memset(). - */ - tmp_buffer.set_charset(&my_charset_bin); - } - void init_for_filesort(uint sortlen, TABLE *table, - ha_rows maxrows, bool sort_positions); - /// Enables the packing of addons if possible. - void try_to_pack_addons(ulong max_length_for_sort_data); - - /// Are we packing the "addon fields"? - bool using_packed_addons() const - { - DBUG_ASSERT(m_using_packed_addons == - (addon_fields != NULL && - addon_fields->using_packed_addons())); - return m_using_packed_addons; - } - - bool using_packed_sortkeys() const - { - DBUG_ASSERT(m_using_packed_sortkeys == - (sort_keys != NULL && sort_keys->using_packed_sortkeys())); - return m_using_packed_sortkeys; - } - - /// Are we using "addon fields"? - bool using_addon_fields() const - { - return addon_fields != NULL; - } - - uint32 get_result_length(uchar *plen) - { - if (!m_using_packed_addons) - return res_length; - return Addon_fields::read_addon_length(plen); - } - - uint32 get_addon_length(uchar *plen) - { - if (using_packed_addons()) - return Addon_fields::read_addon_length(plen); - else - return addon_length; - } - - uint32 get_sort_length(uchar *plen) - { - if (using_packed_sortkeys()) - return Sort_keys::read_sortkey_length(plen) + - /* - when addon fields are not present, then the sort_length also - includes the res_length. For packed keys here we add - the res_length - */ - (using_addon_fields() ? 0: res_length); - else - return sort_length; - } - - uint get_record_length(uchar *plen) - { - if (m_packed_format) - { - uint sort_len= get_sort_length(plen); - return sort_len + get_addon_length(plen + sort_len); - } - else - return rec_length; - } - - /** - Getter for record length and result length. - @param record_start Pointer to record. - @param [out] recl Store record length here. - @param [out] resl Store result length here. - */ - void get_rec_and_res_len(uchar *record_start, uint *recl, uint *resl) - { - if (m_packed_format) - { - uint sort_len= get_sort_length(record_start); - uint addon_len= get_addon_length(record_start + sort_len); - *recl= sort_len + addon_len; - *resl= using_addon_fields() ? addon_len : res_length; - } - else - { - *recl= rec_length; - *resl= res_length; - } - } - - void try_to_pack_sortkeys(); - - qsort2_cmp get_compare_function() const - { - return using_packed_sortkeys() ? - get_packed_keys_compare_ptr() : - get_ptr_compare(sort_length); - } - void* get_compare_argument(size_t *sort_len) const - { - return using_packed_sortkeys() ? - (void*) this : - (void*) sort_len; - } - - bool is_packed_format() const - { - return m_packed_format; - } - -private: - uint m_packable_length; - bool m_using_packed_addons; ///< caches the value of using_packed_addons() - /* caches the value of using_packed_sortkeys() */ - bool m_using_packed_sortkeys; - bool m_packed_format; -}; - -typedef Bounds_checked_array Sort_buffer; - -int merge_many_buff(Sort_param *param, Sort_buffer sort_buffer, - Merge_chunk *buffpek, uint *maxbuffer, IO_CACHE *t_file); -ulong read_to_buffer(IO_CACHE *fromfile, Merge_chunk *buffpek, - Sort_param *param, bool packing_format); -bool merge_buffers(Sort_param *param,IO_CACHE *from_file, - IO_CACHE *to_file, Sort_buffer sort_buffer, - Merge_chunk *lastbuff, Merge_chunk *Fb, - Merge_chunk *Tb, int flag); -int merge_index(Sort_param *param, Sort_buffer sort_buffer, - Merge_chunk *buffpek, uint maxbuffer, - IO_CACHE *tempfile, IO_CACHE *outfile); -void reuse_freed_buff(QUEUE *queue, Merge_chunk *reuse, uint key_length); - -#endif /* SQL_SORT_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_statistics.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_statistics.h deleted file mode 100644 index 20ecf06..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_statistics.h +++ /dev/null @@ -1,473 +0,0 @@ -/* Copyright 2006-2008 MySQL AB, 2008 Sun Microsystems, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_STATISTICS_H -#define SQL_STATISTICS_H - -/* - For COMPLEMENTARY_FOR_QUERIES and PREFERABLY_FOR_QUERIES they are - similar to the COMPLEMENTARY and PREFERABLY respectively except that - with these values we would not be collecting EITS for queries like - ANALYZE TABLE t1; - To collect EITS with these values, we have to use PERSISITENT FOR - analyze table t1 persistent for - columns (col1,col2...) index (idx1, idx2...) - or - analyze table t1 persistent for all -*/ - -typedef -enum enum_use_stat_tables_mode -{ - NEVER, - COMPLEMENTARY, - PREFERABLY, - COMPLEMENTARY_FOR_QUERIES, - PREFERABLY_FOR_QUERIES -} Use_stat_tables_mode; - -typedef -enum enum_histogram_type -{ - SINGLE_PREC_HB, - DOUBLE_PREC_HB -} Histogram_type; - -enum enum_stat_tables -{ - TABLE_STAT, - COLUMN_STAT, - INDEX_STAT, -}; - - -/* - These enumeration types comprise the dictionary of three - statistical tables table_stat, column_stat and index_stat - as they defined in ../scripts/mysql_system_tables.sql. - - It would be nice if the declarations of these types were - generated automatically by the table definitions. -*/ - -enum enum_table_stat_col -{ - TABLE_STAT_DB_NAME, - TABLE_STAT_TABLE_NAME, - TABLE_STAT_CARDINALITY, - TABLE_STAT_N_FIELDS -}; - -enum enum_column_stat_col -{ - COLUMN_STAT_DB_NAME, - COLUMN_STAT_TABLE_NAME, - COLUMN_STAT_COLUMN_NAME, - COLUMN_STAT_MIN_VALUE, - COLUMN_STAT_MAX_VALUE, - COLUMN_STAT_NULLS_RATIO, - COLUMN_STAT_AVG_LENGTH, - COLUMN_STAT_AVG_FREQUENCY, - COLUMN_STAT_HIST_SIZE, - COLUMN_STAT_HIST_TYPE, - COLUMN_STAT_HISTOGRAM, - COLUMN_STAT_N_FIELDS -}; - -enum enum_index_stat_col -{ - INDEX_STAT_DB_NAME, - INDEX_STAT_TABLE_NAME, - INDEX_STAT_INDEX_NAME, - INDEX_STAT_PREFIX_ARITY, - INDEX_STAT_AVG_FREQUENCY, - INDEX_STAT_N_FIELDS -}; - -inline -Use_stat_tables_mode get_use_stat_tables_mode(THD *thd) -{ - return (Use_stat_tables_mode) (thd->variables.use_stat_tables); -} -inline -bool check_eits_collection_allowed(THD *thd) -{ - return (get_use_stat_tables_mode(thd) == COMPLEMENTARY || - get_use_stat_tables_mode(thd) == PREFERABLY); -} - -inline -bool check_eits_preferred(THD *thd) -{ - return (get_use_stat_tables_mode(thd) == PREFERABLY || - get_use_stat_tables_mode(thd) == PREFERABLY_FOR_QUERIES); -} - -int read_statistics_for_tables_if_needed(THD *thd, TABLE_LIST *tables); -int read_statistics_for_tables(THD *thd, TABLE_LIST *tables); -int collect_statistics_for_table(THD *thd, TABLE *table); -void delete_stat_values_for_table_share(TABLE_SHARE *table_share); -int alloc_statistics_for_table(THD *thd, TABLE *table); -int update_statistics_for_table(THD *thd, TABLE *table); -int delete_statistics_for_table(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *tab); -int delete_statistics_for_column(THD *thd, TABLE *tab, Field *col); -int delete_statistics_for_index(THD *thd, TABLE *tab, KEY *key_info, - bool ext_prefixes_only); -int rename_table_in_stat_tables(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *tab, - const LEX_CSTRING *new_db, const LEX_CSTRING *new_tab); -int rename_column_in_stat_tables(THD *thd, TABLE *tab, Field *col, - const char *new_name); -void set_statistics_for_table(THD *thd, TABLE *table); - -double get_column_avg_frequency(Field * field); - -double get_column_range_cardinality(Field *field, - key_range *min_endp, - key_range *max_endp, - uint range_flag); -bool is_stat_table(const LEX_CSTRING *db, LEX_CSTRING *table); -bool is_eits_usable(Field* field); - -class Histogram -{ - -private: - Histogram_type type; - uint8 size; /* Size of values array, in bytes */ - uchar *values; - - uint prec_factor() - { - switch (type) { - case SINGLE_PREC_HB: - return ((uint) (1 << 8) - 1); - case DOUBLE_PREC_HB: - return ((uint) (1 << 16) - 1); - } - return 1; - } - -public: - uint get_width() - { - switch (type) { - case SINGLE_PREC_HB: - return size; - case DOUBLE_PREC_HB: - return size / 2; - } - return 0; - } - -private: - uint get_value(uint i) - { - DBUG_ASSERT(i < get_width()); - switch (type) { - case SINGLE_PREC_HB: - return (uint) (((uint8 *) values)[i]); - case DOUBLE_PREC_HB: - return (uint) uint2korr(values + i * 2); - } - return 0; - } - - /* Find the bucket which value 'pos' falls into. */ - uint find_bucket(double pos, bool first) - { - uint val= (uint) (pos * prec_factor()); - int lp= 0; - int rp= get_width() - 1; - int d= get_width() / 2; - uint i= lp + d; - for ( ; d; d= (rp - lp) / 2, i= lp + d) - { - if (val == get_value(i)) - break; - if (val < get_value(i)) - rp= i; - else if (val > get_value(i + 1)) - lp= i + 1; - else - break; - } - - if (val > get_value(i) && i < (get_width() - 1)) - i++; - - if (val == get_value(i)) - { - if (first) - { - while(i && val == get_value(i - 1)) - i--; - } - else - { - while(i + 1 < get_width() && val == get_value(i + 1)) - i++; - } - } - return i; - } - -public: - - uint get_size() { return (uint) size; } - - Histogram_type get_type() { return type; } - - uchar *get_values() { return (uchar *) values; } - - void set_size (ulonglong sz) { size= (uint8) sz; } - - void set_type (Histogram_type t) { type= t; } - - void set_values (uchar *vals) { values= (uchar *) vals; } - - bool is_available() { return get_size() > 0 && get_values(); } - - void set_value(uint i, double val) - { - switch (type) { - case SINGLE_PREC_HB: - ((uint8 *) values)[i]= (uint8) (val * prec_factor()); - return; - case DOUBLE_PREC_HB: - int2store(values + i * 2, val * prec_factor()); - return; - } - } - - void set_prev_value(uint i) - { - switch (type) { - case SINGLE_PREC_HB: - ((uint8 *) values)[i]= ((uint8 *) values)[i-1]; - return; - case DOUBLE_PREC_HB: - int2store(values + i * 2, uint2korr(values + i * 2 - 2)); - return; - } - } - - double range_selectivity(double min_pos, double max_pos) - { - double sel; - double bucket_sel= 1.0/(get_width() + 1); - uint min= find_bucket(min_pos, TRUE); - uint max= find_bucket(max_pos, FALSE); - sel= bucket_sel * (max - min + 1); - return sel; - } - - /* - Estimate selectivity of "col=const" using a histogram - */ - double point_selectivity(double pos, double avg_sel); -}; - - -class Columns_statistics; -class Index_statistics; - -/* Statistical data on a table */ - -class Table_statistics -{ - -public: - my_bool cardinality_is_null; /* TRUE if the cardinality is unknown */ - ha_rows cardinality; /* Number of rows in the table */ - uchar *min_max_record_buffers; /* Record buffers for min/max values */ - Column_statistics *column_stats; /* Array of statistical data for columns */ - Index_statistics *index_stats; /* Array of statistical data for indexes */ - - /* Array of records per key for index prefixes */ - ulonglong *idx_avg_frequency; - uchar *histograms; /* Sequence of histograms */ -}; - - -/* - Statistical data on a column - - Note: objects of this class may be "empty", where they have almost all fields - as zeros, for example, get_avg_frequency() will return 0. - - objects are allocated in alloc_statistics_for_table[_share]. -*/ - -class Column_statistics -{ - -private: - static const uint Scale_factor_nulls_ratio= 100000; - static const uint Scale_factor_avg_length= 100000; - static const uint Scale_factor_avg_frequency= 100000; - -public: - /* - Bitmap indicating what statistical characteristics - are available for the column - */ - uint32 column_stat_nulls; - - /* For the below two, see comments in get_column_range_cardinality() */ - /* Minimum value for the column */ - Field *min_value; - /* Maximum value for the column */ - Field *max_value; - -private: - - /* - The ratio Z/N multiplied by the scale factor Scale_factor_nulls_ratio, - where - N is the total number of rows, - Z is the number of nulls in the column - */ - ulong nulls_ratio; - - /* - Average number of bytes occupied by the representation of a - value of the column in memory buffers such as join buffer - multiplied by the scale factor Scale_factor_avg_length. - CHAR values are stripped of trailing spaces. - Flexible values are stripped of their length prefixes. - */ - ulonglong avg_length; - - /* - The ratio N/D multiplied by the scale factor Scale_factor_avg_frequency, - where - N is the number of rows with not null value in the column, - D the number of distinct values among them - */ - ulonglong avg_frequency; - -public: - - Histogram histogram; - - uint32 no_values_provided_bitmap() - { - return - ((1 << (COLUMN_STAT_HISTOGRAM-COLUMN_STAT_COLUMN_NAME))-1) << - (COLUMN_STAT_COLUMN_NAME+1); - } - - void set_all_nulls() - { - column_stat_nulls= no_values_provided_bitmap(); - } - - void set_not_null(uint stat_field_no) - { - column_stat_nulls&= ~(1 << stat_field_no); - } - - bool is_null(uint stat_field_no) - { - return MY_TEST(column_stat_nulls & (1 << stat_field_no)); - } - - double get_nulls_ratio() - { - return (double) nulls_ratio / Scale_factor_nulls_ratio; - } - - double get_avg_length() - { - return (double) avg_length / Scale_factor_avg_length; - } - - double get_avg_frequency() - { - return (double) avg_frequency / Scale_factor_avg_frequency; - } - - void set_nulls_ratio (double val) - { - nulls_ratio= (ulong) (val * Scale_factor_nulls_ratio); - } - - void set_avg_length (double val) - { - avg_length= (ulonglong) (val * Scale_factor_avg_length); - } - - void set_avg_frequency (double val) - { - avg_frequency= (ulonglong) (val * Scale_factor_avg_frequency); - } - - bool min_max_values_are_provided() - { - return !is_null(COLUMN_STAT_MIN_VALUE) && - !is_null(COLUMN_STAT_MAX_VALUE); - } - /* - This function checks whether the values for the fields of the statistical - tables that were NULL by DEFAULT for a column have changed or not. - - @retval - TRUE: Statistics are not present for a column - FALSE: Statisitics are present for a column - */ - bool no_stat_values_provided() - { - if (column_stat_nulls == no_values_provided_bitmap()) - return true; - return false; - } -}; - - -/* Statistical data on an index prefixes */ - -class Index_statistics -{ - -private: - static const uint Scale_factor_avg_frequency= 100000; - /* - The k-th element of this array contains the ratio N/D - multiplied by the scale factor Scale_factor_avg_frequency, - where N is the number of index entries without nulls - in the first k components, and D is the number of distinct - k-component prefixes among them - */ - ulonglong *avg_frequency; - -public: - - void init_avg_frequency(ulonglong *ptr) { avg_frequency= ptr; } - - bool avg_frequency_is_inited() { return avg_frequency != NULL; } - - double get_avg_frequency(uint i) - { - return (double) avg_frequency[i] / Scale_factor_avg_frequency; - } - - void set_avg_frequency(uint i, double val) - { - avg_frequency[i]= (ulonglong) (val * Scale_factor_avg_frequency); - } - -}; - -#endif /* SQL_STATISTICS_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_string.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_string.h deleted file mode 100644 index b3eca11..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_string.h +++ /dev/null @@ -1,1069 +0,0 @@ -#ifndef SQL_STRING_INCLUDED -#define SQL_STRING_INCLUDED - -/* - Copyright (c) 2000, 2013, Oracle and/or its affiliates. - Copyright (c) 2008, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* This file is originally from the mysql distribution. Coded by monty */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include "m_ctype.h" /* my_charset_bin */ -#include /* alloc_root, my_free, my_realloc */ -#include "m_string.h" /* TRASH */ -#include "sql_list.h" - -class String; -#ifdef MYSQL_SERVER -extern PSI_memory_key key_memory_String_value; -#define STRING_PSI_MEMORY_KEY key_memory_String_value -#else -#define STRING_PSI_MEMORY_KEY PSI_NOT_INSTRUMENTED -#endif - -typedef struct st_io_cache IO_CACHE; -typedef struct st_mem_root MEM_ROOT; - -#include "pack.h" -int sortcmp(const String *a,const String *b, CHARSET_INFO *cs); -String *copy_if_not_alloced(String *a,String *b,uint32 arg_length); -inline uint32 copy_and_convert(char *to, size_t to_length, - CHARSET_INFO *to_cs, - const char *from, size_t from_length, - CHARSET_INFO *from_cs, uint *errors) -{ - return my_convert(to, (uint)to_length, to_cs, from, (uint)from_length, from_cs, errors); -} - - -class String_copy_status: protected MY_STRCOPY_STATUS -{ -public: - const char *source_end_pos() const - { return m_source_end_pos; } - const char *well_formed_error_pos() const - { return m_well_formed_error_pos; } -}; - - -class Well_formed_prefix_status: public String_copy_status -{ -public: - Well_formed_prefix_status(CHARSET_INFO *cs, - const char *str, const char *end, size_t nchars) - { cs->well_formed_char_length(str, end, nchars, this); } -}; - - -class Well_formed_prefix: public Well_formed_prefix_status -{ - const char *m_str; // The beginning of the string -public: - Well_formed_prefix(CHARSET_INFO *cs, const char *str, const char *end, - size_t nchars) - :Well_formed_prefix_status(cs, str, end, nchars), m_str(str) - { } - Well_formed_prefix(CHARSET_INFO *cs, const char *str, size_t length, - size_t nchars) - :Well_formed_prefix_status(cs, str, str + length, nchars), m_str(str) - { } - Well_formed_prefix(CHARSET_INFO *cs, const char *str, size_t length) - :Well_formed_prefix_status(cs, str, str + length, length), m_str(str) - { } - Well_formed_prefix(CHARSET_INFO *cs, LEX_CSTRING str, size_t nchars) - :Well_formed_prefix_status(cs, str.str, str.str + str.length, nchars), - m_str(str.str) - { } - size_t length() const { return m_source_end_pos - m_str; } -}; - - -class String_copier: public String_copy_status, - protected MY_STRCONV_STATUS -{ -public: - const char *cannot_convert_error_pos() const - { return m_cannot_convert_error_pos; } - const char *most_important_error_pos() const - { - return well_formed_error_pos() ? well_formed_error_pos() : - cannot_convert_error_pos(); - } - /* - Convert a string between character sets. - "dstcs" and "srccs" cannot be &my_charset_bin. - */ - size_t convert_fix(CHARSET_INFO *dstcs, char *dst, size_t dst_length, - CHARSET_INFO *srccs, const char *src, size_t src_length, size_t nchars) - { - return my_convert_fix(dstcs, dst, dst_length, - srccs, src, src_length, nchars, this, this); - } - /* - Copy a string. Fix bad bytes/characters to '?'. - */ - uint well_formed_copy(CHARSET_INFO *to_cs, char *to, size_t to_length, - CHARSET_INFO *from_cs, const char *from, size_t from_length, size_t nchars); - // Same as above, but without the "nchars" limit. - uint well_formed_copy(CHARSET_INFO *to_cs, char *to, size_t to_length, - CHARSET_INFO *from_cs, const char *from, size_t from_length) - { - return well_formed_copy(to_cs, to, to_length, - from_cs, from, from_length, - from_length /* No limit on "nchars"*/); - } -}; - - -size_t my_copy_with_hex_escaping(CHARSET_INFO *cs, - char *dst, size_t dstlen, - const char *src, size_t srclen); -uint convert_to_printable(char *to, size_t to_len, - const char *from, size_t from_len, - CHARSET_INFO *from_cs, size_t nbytes= 0); -size_t convert_to_printable_required_length(uint len); - - -class Charset -{ - CHARSET_INFO *m_charset; -public: - Charset() :m_charset(&my_charset_bin) { } - Charset(CHARSET_INFO *cs) :m_charset(cs) { } - - CHARSET_INFO *charset() const { return m_charset; } - bool use_mb() const { return m_charset->use_mb(); } - uint mbminlen() const { return m_charset->mbminlen; } - uint mbmaxlen() const { return m_charset->mbmaxlen; } - bool is_good_for_ft() const - { - // Binary and UCS2/UTF16/UTF32 are not supported - return m_charset != &my_charset_bin && m_charset->mbminlen == 1; - } - - size_t numchars(const char *str, const char *end) const - { - return m_charset->numchars(str, end); - } - size_t lengthsp(const char *str, size_t length) const - { - return m_charset->lengthsp(str, length); - } - size_t charpos(const char *str, const char *end, size_t pos) const - { - return m_charset->charpos(str, end, pos); - } - void set_charset(CHARSET_INFO *charset_arg) - { - m_charset= charset_arg; - } - void set_charset(const Charset &other) - { - m_charset= other.m_charset; - } - void swap(Charset &other) - { - swap_variables(CHARSET_INFO*, m_charset, other.m_charset); - } - bool same_encoding(const Charset &other) const - { - return !strcmp(m_charset->csname, other.m_charset->csname); - } - /* - Collation name without the character set name. - For example, in case of "latin1_swedish_ci", - this method returns "_swedish_ci". - */ - LEX_CSTRING collation_specific_name() const; - bool encoding_allows_reinterpret_as(CHARSET_INFO *cs) const; - bool eq_collation_specific_names(CHARSET_INFO *cs) const; -}; - - -/* - A storage for String. - Should be eventually derived from LEX_STRING. -*/ -class Static_binary_string : public Sql_alloc -{ -protected: - char *Ptr; - uint32 str_length; -public: - Static_binary_string() - :Ptr(NULL), - str_length(0) - { } - Static_binary_string(char *str, size_t length_arg) - :Ptr(str), - str_length((uint32) length_arg) - { - DBUG_ASSERT(length_arg < UINT_MAX32); - } - inline uint32 length() const { return str_length;} - inline char& operator [] (size_t i) const { return Ptr[i]; } - inline void length(size_t len) { str_length=(uint32)len ; } - inline bool is_empty() const { return (str_length == 0); } - inline const char *ptr() const { return Ptr; } - inline const char *end() const { return Ptr + str_length; } - bool has_8bit_bytes() const - { - for (const char *c= ptr(), *c_end= end(); c < c_end; c++) - { - if (!my_isascii(*c)) - return true; - } - return false; - } - - bool bin_eq(const Static_binary_string *other) const - { - return length() == other->length() && - !memcmp(ptr(), other->ptr(), length()); - } - - void set(char *str, size_t len) - { - Ptr= str; - str_length= (uint32) len; - } - - void swap(Static_binary_string &s) - { - swap_variables(char *, Ptr, s.Ptr); - swap_variables(uint32, str_length, s.str_length); - } - - /* - PMG 2004.11.12 - This is a method that works the same as perl's "chop". It simply - drops the last character of a string. This is useful in the case - of the federated storage handler where I'm building a unknown - number, list of values and fields to be used in a sql insert - statement to be run on the remote server, and have a comma after each. - When the list is complete, I "chop" off the trailing comma - - ex. - String stringobj; - stringobj.append("VALUES ('foo', 'fi', 'fo',"); - stringobj.chop(); - stringobj.append(")"); - - In this case, the value of string was: - - VALUES ('foo', 'fi', 'fo', - VALUES ('foo', 'fi', 'fo' - VALUES ('foo', 'fi', 'fo') - */ - inline void chop() - { - str_length--; - Ptr[str_length]= '\0'; - DBUG_ASSERT(strlen(Ptr) == str_length); - } - - // Returns offset to substring or -1 - int strstr(const Static_binary_string &search, uint32 offset=0); - // Returns offset to substring or -1 - int strrstr(const Static_binary_string &search, uint32 offset=0); - - /* - The following append operations do NOT check alloced memory - q_*** methods writes values of parameters itself - qs_*** methods writes string representation of value - */ - void q_append(const char c) - { - Ptr[str_length++] = c; - } - void q_append2b(const uint32 n) - { - int2store(Ptr + str_length, n); - str_length += 2; - } - void q_append(const uint32 n) - { - int4store(Ptr + str_length, n); - str_length += 4; - } - void q_append(double d) - { - float8store(Ptr + str_length, d); - str_length += 8; - } - void q_append(double *d) - { - float8store(Ptr + str_length, *d); - str_length += 8; - } - void q_append(const char *data, size_t data_len) - { - if (data_len) - memcpy(Ptr + str_length, data, data_len); - DBUG_ASSERT(str_length <= UINT_MAX32 - data_len); - str_length += (uint)data_len; - } - void q_append(const LEX_CSTRING *ls) - { - DBUG_ASSERT(ls->length < UINT_MAX32 && - ((ls->length == 0 && !ls->str) || - ls->length == strlen(ls->str))); - q_append(ls->str, (uint32) ls->length); - } - - void write_at_position(int position, uint32 value) - { - int4store(Ptr + position,value); - } - - void qs_append(const char *str) - { - qs_append(str, (uint32)strlen(str)); - } - void qs_append(const LEX_CSTRING *ls) - { - DBUG_ASSERT(ls->length < UINT_MAX32 && - ((ls->length == 0 && !ls->str) || - ls->length == strlen(ls->str))); - qs_append(ls->str, (uint32)ls->length); - } - void qs_append(const char *str, size_t len); - void qs_append_hex(const char *str, uint32 len); - void qs_append(double d); - void qs_append(const double *d); - inline void qs_append(const char c) - { - Ptr[str_length]= c; - str_length++; - } - void qs_append(int i); - void qs_append(uint i) - { - qs_append((ulonglong)i); - } - void qs_append(ulong i) - { - qs_append((ulonglong)i); - } - void qs_append(ulonglong i); - void qs_append(longlong i, int radix) - { - char *buff= Ptr + str_length; - char *end= ll2str(i, buff, radix, 0); - str_length+= uint32(end-buff); - } -}; - - -class Binary_string: public Static_binary_string -{ - uint32 Alloced_length, extra_alloc; - bool alloced, thread_specific; - void init_private_data() - { - Alloced_length= extra_alloc= 0; - alloced= thread_specific= false; - } -public: - Binary_string() - { - init_private_data(); - } - explicit Binary_string(size_t length_arg) - { - init_private_data(); - (void) real_alloc(length_arg); - } - explicit Binary_string(const char *str) - :Binary_string(str, strlen(str)) - { } - /* - NOTE: If one intend to use the c_ptr() method, the following two - contructors need the size of memory for STR to be at least LEN+1 (to make - room for zero termination). - */ - Binary_string(const char *str, size_t len) - :Static_binary_string((char *) str, len) - { - init_private_data(); - } - Binary_string(char *str, size_t len) - :Static_binary_string(str, len) - { - Alloced_length= (uint32) len; - extra_alloc= 0; - alloced= thread_specific= 0; - } - explicit Binary_string(const Binary_string &str) - :Static_binary_string(str) - { - Alloced_length= str.Alloced_length; - extra_alloc= 0; - alloced= thread_specific= 0; - } - - ~Binary_string() { free(); } - - /* Mark variable thread specific it it's not allocated already */ - inline void set_thread_specific() - { - if (!alloced) - thread_specific= 1; - } - bool is_alloced() const { return alloced; } - inline uint32 alloced_length() const { return Alloced_length;} - inline uint32 extra_allocation() const { return extra_alloc;} - inline void extra_allocation(size_t len) { extra_alloc= (uint32)len; } - inline void mark_as_const() { Alloced_length= 0;} - - inline bool uses_buffer_owned_by(const Binary_string *s) const - { - return (s->alloced && Ptr >= s->Ptr && Ptr < s->Ptr + s->str_length); - } - - /* Swap two string objects. Efficient way to exchange data without memcpy. */ - void swap(Binary_string &s) - { - Static_binary_string::swap(s); - swap_variables(uint32, Alloced_length, s.Alloced_length); - swap_variables(bool, alloced, s.alloced); - } - - /** - Points the internal buffer to the supplied one. The old buffer is freed. - @param str Pointer to the new buffer. - @param arg_length Length of the new buffer in characters, excluding any - null character. - @note The new buffer will not be null terminated. - */ - void set_alloced(char *str, size_t length_arg, size_t alloced_length_arg) - { - free(); - Static_binary_string::set(str, length_arg); - DBUG_ASSERT(alloced_length_arg < UINT_MAX32); - Alloced_length= (uint32) alloced_length_arg; - } - inline void set(char *str, size_t arg_length) - { - set_alloced(str, arg_length, arg_length); - } - inline void set(const char *str, size_t arg_length) - { - free(); - Static_binary_string::set((char *) str, arg_length); - } - - void set(Binary_string &str, size_t offset, size_t arg_length) - { - DBUG_ASSERT(&str != this); - free(); - Static_binary_string::set((char*) str.ptr() + offset, arg_length); - if (str.Alloced_length) - Alloced_length= (uint32) (str.Alloced_length - offset); - } - inline LEX_CSTRING *get_value(LEX_CSTRING *res) - { - res->str= Ptr; - res->length= str_length; - return res; - } - - /* Take over handling of buffer from some other object */ - void reset(char *ptr_arg, size_t length_arg, size_t alloced_length_arg) - { - set_alloced(ptr_arg, length_arg, alloced_length_arg); - alloced= ptr_arg != 0; - } - - /* Forget about the buffer, let some other object handle it */ - char *release() - { - char *old= Ptr; - Static_binary_string::set(NULL, 0); - init_private_data(); - return old; - } - - inline void set_quick(char *str, size_t arg_length) - { - if (!alloced) - { - Static_binary_string::set(str, arg_length); - Alloced_length= (uint32) arg_length; - } - } - - inline Binary_string& operator=(const Binary_string &s) - { - if (&s != this) - { - /* - It is forbidden to do assignments like - some_string = substring_of_that_string - */ - DBUG_ASSERT(!s.uses_buffer_owned_by(this)); - set_alloced((char *) s.Ptr, s.str_length, s.Alloced_length); - } - return *this; - } - - bool set_hex(ulonglong num); - bool set_hex(const char *str, uint32 len); - bool set_fcvt(double num, uint decimals); - - bool copy(); // Alloc string if not alloced - bool copy(const Binary_string &s); // Allocate new string - bool copy(const char *s, size_t arg_length); // Allocate new string - bool copy_or_move(const char *s,size_t arg_length); - - /** - Convert a string to a printable format. - All non-convertable and control characters are replaced to 5-character - sequences '\hhhh'. - */ - bool copy_printable_hhhh(CHARSET_INFO *to_cs, - CHARSET_INFO *from_cs, - const char *from, size_t from_length); - - bool append_ulonglong(ulonglong val); - bool append_longlong(longlong val); - - bool append(const char *s, size_t size) - { - if (!size) - return false; - if (realloc_with_extra_if_needed(str_length + size)) - return true; - q_append(s, size); - return false; - } - bool append(const LEX_CSTRING &s) - { - return append(s.str, s.length); - } - bool append(const Binary_string &s) - { - return append(s.ptr(), s.length()); - } - bool append(IO_CACHE* file, uint32 arg_length); - - inline bool append_char(char chr) - { - if (str_length < Alloced_length) - { - Ptr[str_length++]= chr; - } - else - { - if (unlikely(realloc_with_extra(str_length + 1))) - return true; - Ptr[str_length++]= chr; - } - return false; - } - bool append_hex(const char *src, uint32 srclen) - { - for (const char *src_end= src + srclen ; src != src_end ; src++) - { - if (unlikely(append_char(_dig_vec_lower[((uchar) *src) >> 4])) || - unlikely(append_char(_dig_vec_lower[((uchar) *src) & 0x0F]))) - return true; - } - return false; - } - - bool append_with_step(const char *s, uint32 arg_length, uint32 step_alloc) - { - uint32 new_length= arg_length + str_length; - if (new_length > Alloced_length && - unlikely(realloc(new_length + step_alloc))) - return true; - q_append(s, arg_length); - return false; - } - - inline char *c_ptr() - { - DBUG_ASSERT(!alloced || !Ptr || !Alloced_length || - (Alloced_length >= (str_length + 1))); - - if (!Ptr || Ptr[str_length]) // Should be safe - (void) realloc(str_length); - return Ptr; - } - inline char *c_ptr_quick() - { - if (Ptr && str_length < Alloced_length) - Ptr[str_length]=0; - return Ptr; - } - inline char *c_ptr_safe() - { - if (Ptr && str_length < Alloced_length) - Ptr[str_length]=0; - else - (void) realloc(str_length); - return Ptr; - } - - inline void free() - { - if (alloced) - { - alloced=0; - my_free(Ptr); - } - Alloced_length= extra_alloc= 0; - Static_binary_string::set(NULL, 0); // Safety - } - inline bool alloc(size_t arg_length) - { - if (arg_length < Alloced_length) - return 0; - return real_alloc(arg_length); - } - bool real_alloc(size_t arg_length); // Empties old string - bool realloc_raw(size_t arg_length); - bool realloc(size_t arg_length) - { - if (realloc_raw(arg_length)) - return TRUE; - Ptr[arg_length]= 0; // This make other funcs shorter - return FALSE; - } - bool realloc_with_extra(size_t arg_length) - { - if (extra_alloc < 4096) - extra_alloc= extra_alloc*2+128; - if (realloc_raw(arg_length + extra_alloc)) - return TRUE; - Ptr[arg_length]=0; // This make other funcs shorter - return FALSE; - } - bool realloc_with_extra_if_needed(size_t arg_length) - { - if (arg_length < Alloced_length) - { - Ptr[arg_length]=0; // behave as if realloc was called. - return 0; - } - return realloc_with_extra(arg_length); - } - // Shrink the buffer, but only if it is allocated on the heap. - void shrink(size_t arg_length); - - void move(Binary_string &s) - { - set_alloced(s.Ptr, s.str_length, s.Alloced_length); - extra_alloc= s.extra_alloc; - alloced= s.alloced; - thread_specific= s.thread_specific; - s.alloced= 0; - } - bool fill(uint32 max_length,char fill); - /* - Replace substring with string - If wrong parameter or not enough memory, do nothing - */ - bool replace(uint32 offset,uint32 arg_length, const char *to, uint32 length); - bool replace(uint32 offset,uint32 arg_length, const Static_binary_string &to) - { - return replace(offset,arg_length,to.ptr(),to.length()); - } - - int reserve(size_t space_needed) - { - DBUG_ASSERT((ulonglong) str_length + space_needed < UINT_MAX32); - return realloc(str_length + space_needed); - } - int reserve(size_t space_needed, size_t grow_by); - - inline char *prep_append(uint32 arg_length, uint32 step_alloc) - { - uint32 new_length= arg_length + str_length; - if (new_length > Alloced_length) - { - if (unlikely(realloc(new_length + step_alloc))) - return 0; - } - uint32 old_length= str_length; - str_length+= arg_length; - return Ptr + old_length; // Area to use - } - - - void q_net_store_length(ulonglong length) - { - DBUG_ASSERT(Alloced_length >= (str_length + net_length_size(length))); - char *pos= (char *) net_store_length((uchar *)(Ptr + str_length), length); - str_length= uint32(pos - Ptr); - } - void q_net_store_data(const uchar *from, size_t length) - { - DBUG_ASSERT(length < UINT_MAX32); - DBUG_ASSERT(Alloced_length >= (str_length + length + - net_length_size(length))); - q_net_store_length(length); - q_append((const char *)from, (uint32) length); - } -}; - - -class String: public Charset, public Binary_string -{ -public: - String() { } - String(size_t length_arg) - :Binary_string(length_arg) - { } - String(const char *str, CHARSET_INFO *cs) - :Charset(cs), - Binary_string(str) - { } - /* - NOTE: If one intend to use the c_ptr() method, the following two - contructors need the size of memory for STR to be at least LEN+1 (to make - room for zero termination). - */ - String(const char *str, size_t len, CHARSET_INFO *cs) - :Charset(cs), - Binary_string((char *) str, len) - { } - String(char *str, size_t len, CHARSET_INFO *cs) - :Charset(cs), - Binary_string(str, len) - { } - String(const String &str) - :Charset(str), - Binary_string(str) - { } - - void set(String &str,size_t offset,size_t arg_length) - { - Binary_string::set(str, offset, arg_length); - set_charset(str); - } - inline void set(char *str,size_t arg_length, CHARSET_INFO *cs) - { - Binary_string::set(str, arg_length); - set_charset(cs); - } - inline void set(const char *str,size_t arg_length, CHARSET_INFO *cs) - { - Binary_string::set(str, arg_length); - set_charset(cs); - } - bool set_ascii(const char *str, size_t arg_length); - inline void set_quick(char *str,size_t arg_length, CHARSET_INFO *cs) - { - Binary_string::set_quick(str, arg_length); - set_charset(cs); - } - bool set_int(longlong num, bool unsigned_flag, CHARSET_INFO *cs); - bool set(int num, CHARSET_INFO *cs) { return set_int(num, false, cs); } - bool set(uint num, CHARSET_INFO *cs) { return set_int(num, true, cs); } - bool set(long num, CHARSET_INFO *cs) { return set_int(num, false, cs); } - bool set(ulong num, CHARSET_INFO *cs) { return set_int(num, true, cs); } - bool set(longlong num, CHARSET_INFO *cs) { return set_int(num, false, cs); } - bool set(ulonglong num, CHARSET_INFO *cs) { return set_int((longlong)num, true, cs); } - bool set_real(double num,uint decimals, CHARSET_INFO *cs); - bool set_fcvt(double num, uint decimals) - { - set_charset(&my_charset_latin1); - return Binary_string::set_fcvt(num, decimals); - } - - bool set_hex(ulonglong num) - { - set_charset(&my_charset_latin1); - return Binary_string::set_hex(num); - } - bool set_hex(const char *str, uint32 len) - { - set_charset(&my_charset_latin1); - return Binary_string::set_hex(str, len); - } - - /* Take over handling of buffer from some other object */ - void reset(char *ptr_arg, size_t length_arg, size_t alloced_length_arg, - CHARSET_INFO *cs) - { - Binary_string::reset(ptr_arg, length_arg, alloced_length_arg); - set_charset(cs); - } - - inline String& operator = (const String &s) - { - if (&s != this) - { - set_charset(s); - Binary_string::operator=(s); - } - return *this; - } - - bool copy() - { - return Binary_string::copy(); - } - bool copy(const String &s) - { - set_charset(s); - return Binary_string::copy(s); - } - bool copy(const char *s, size_t arg_length, CHARSET_INFO *cs) - { - set_charset(cs); - return Binary_string::copy(s, arg_length); - } - bool copy_or_move(const char *s, size_t arg_length, CHARSET_INFO *cs) - { - set_charset(cs); - return Binary_string::copy_or_move(s, arg_length); - } - static bool needs_conversion(size_t arg_length, - CHARSET_INFO *cs_from, CHARSET_INFO *cs_to, - uint32 *offset); - static bool needs_conversion_on_storage(size_t arg_length, - CHARSET_INFO *cs_from, - CHARSET_INFO *cs_to); - bool copy_aligned(const char *s, size_t arg_length, size_t offset, - CHARSET_INFO *cs); - bool set_or_copy_aligned(const char *s, size_t arg_length, CHARSET_INFO *cs); - bool can_be_safely_converted_to(CHARSET_INFO *tocs) const - { - if (charset() == &my_charset_bin) - return Well_formed_prefix(tocs, ptr(), length()).length() == length(); - String try_val; - uint try_conv_error= 0; - try_val.copy(ptr(), length(), charset(), tocs, &try_conv_error); - return try_conv_error == 0; - } - bool copy(const char*s, size_t arg_length, CHARSET_INFO *csfrom, - CHARSET_INFO *csto, uint *errors); - bool copy(const String *str, CHARSET_INFO *tocs, uint *errors) - { - return copy(str->ptr(), str->length(), str->charset(), tocs, errors); - } - bool copy(CHARSET_INFO *tocs, - CHARSET_INFO *fromcs, const char *src, size_t src_length, - size_t nchars, String_copier *copier) - { - if (unlikely(alloc(tocs->mbmaxlen * src_length))) - return true; - str_length= copier->well_formed_copy(tocs, Ptr, alloced_length(), - fromcs, src, (uint)src_length, (uint)nchars); - set_charset(tocs); - return false; - } - // Append without character set conversion - bool append(const String &s) - { - return Binary_string::append(s); - } - inline bool append(char chr) - { - return Binary_string::append_char(chr); - } - bool append_hex(const char *src, uint32 srclen) - { - return Binary_string::append_hex(src, srclen); - } - bool append_hex(const uchar *src, uint32 srclen) - { - return Binary_string::append_hex((const char*)src, srclen); - } - bool append_introducer_and_hex(const String *str) - { - return - append(STRING_WITH_LEN("_")) || - append(str->charset()->csname) || - append(STRING_WITH_LEN(" 0x")) || - append_hex(str->ptr(), (uint32) str->length()); - } - bool append(IO_CACHE* file, uint32 arg_length) - { - return Binary_string::append(file, arg_length); - } - inline bool append(const char *s, uint32 arg_length, uint32 step_alloc) - { - return append_with_step(s, arg_length, step_alloc); - } - - // Append with optional character set conversion from ASCII (e.g. to UCS2) - bool append(const char *s) - { - return append(s, strlen(s)); - } - bool append(const LEX_STRING *ls) - { - DBUG_ASSERT(ls->length < UINT_MAX32 && - ((ls->length == 0 && !ls->str) || - ls->length == strlen(ls->str))); - return append(ls->str, (uint32) ls->length); - } - bool append(const LEX_CSTRING *ls) - { - DBUG_ASSERT(ls->length < UINT_MAX32 && - ((ls->length == 0 && !ls->str) || - ls->length == strlen(ls->str))); - return append(ls->str, (uint32) ls->length); - } - bool append(const LEX_CSTRING &ls) - { - return append(&ls); - } - bool append(const char *s, size_t size); - bool append_with_prefill(const char *s, uint32 arg_length, - uint32 full_length, char fill_char); - bool append_parenthesized(long nr, int radix= 10); - - // Append with optional character set conversion from cs to charset() - bool append(const char *s, size_t arg_length, CHARSET_INFO *cs); - bool append(const LEX_CSTRING &s, CHARSET_INFO *cs) - { - return append(s.str, s.length, cs); - } - - void strip_sp(); - friend int sortcmp(const String *a,const String *b, CHARSET_INFO *cs); - friend int stringcmp(const String *a,const String *b); - friend String *copy_if_not_alloced(String *a,String *b,uint32 arg_length); - friend class Field; - uint32 numchars() const - { - return (uint32) Charset::numchars(ptr(), end()); - } - int charpos(longlong i, uint32 offset=0) - { - if (i <= 0) - return (int) i; - return (int) Charset::charpos(ptr() + offset, end(), (size_t) i); - } - size_t lengthsp() const - { - return Charset::lengthsp(Ptr, str_length); - } - - void print(String *to) const; - void print_with_conversion(String *to, CHARSET_INFO *cs) const; - void print(String *to, CHARSET_INFO *cs) const - { - if (my_charset_same(charset(), cs)) - print(to); - else - print_with_conversion(to, cs); - } - - bool append_for_single_quote(const char *st, size_t len); - bool append_for_single_quote(const String *s) - { - return append_for_single_quote(s->ptr(), s->length()); - } - bool append_for_single_quote(const char *st) - { - size_t len= strlen(st); - DBUG_ASSERT(len < UINT_MAX32); - return append_for_single_quote(st, (uint32) len); - } - - void swap(String &s) - { - Charset::swap(s); - Binary_string::swap(s); - } - - uint well_formed_length() const - { - return (uint) Well_formed_prefix(charset(), ptr(), length()).length(); - } - bool is_ascii() const - { - if (length() == 0) - return TRUE; - if (charset()->mbminlen > 1) - return FALSE; - return !has_8bit_bytes(); - } - bool eq(const String *other, CHARSET_INFO *cs) const - { - return !sortcmp(this, other, cs); - } -private: - bool append_semi_hex(const char *s, uint len, CHARSET_INFO *cs); -}; - - -// The following class is a backport from MySQL 5.6: -/** - String class wrapper with a preallocated buffer of size buff_sz - - This class allows to replace sequences of: - char buff[12345]; - String str(buff, sizeof(buff)); - str.length(0); - with a simple equivalent declaration: - StringBuffer<12345> str; -*/ - -template -class StringBuffer : public String -{ - char buff[buff_sz]; - -public: - StringBuffer() : String(buff, buff_sz, &my_charset_bin) { length(0); } - explicit StringBuffer(CHARSET_INFO *cs) : String(buff, buff_sz, cs) - { - length(0); - } -}; - - -template -class BinaryStringBuffer : public Binary_string -{ - char buff[buff_sz]; -public: - BinaryStringBuffer() : Binary_string(buff, buff_sz) { length(0); } -}; - - -class String_space: public String -{ -public: - String_space(uint n) - { - if (fill(n, ' ')) - set("", 0, &my_charset_bin); - } -}; - - -static inline bool check_if_only_end_space(CHARSET_INFO *cs, - const char *str, - const char *end) -{ - return str + cs->scan(str, end, MY_SEQ_SPACES) == end; -} - -int append_query_string(CHARSET_INFO *csinfo, String *to, - const char *str, size_t len, bool no_backslash); - -#endif /* SQL_STRING_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_table.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_table.h deleted file mode 100644 index d67ceb6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_table.h +++ /dev/null @@ -1,296 +0,0 @@ -/* Copyright (c) 2006, 2014, Oracle and/or its affiliates. - Copyright (c) 2011, 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_TABLE_INCLUDED -#define SQL_TABLE_INCLUDED - -#include // pthread_mutex_t -#include "m_string.h" // LEX_CUSTRING - -class Alter_info; -class Alter_table_ctx; -class Column_definition; -class Create_field; -struct TABLE_LIST; -class THD; -struct TABLE; -struct handlerton; -class handler; -class String; -typedef struct st_ha_check_opt HA_CHECK_OPT; -struct HA_CREATE_INFO; -struct Table_specification_st; -typedef struct st_key KEY; -typedef struct st_key_cache KEY_CACHE; -typedef struct st_lock_param_type ALTER_PARTITION_PARAM_TYPE; -typedef struct st_order ORDER; - -enum ddl_log_entry_code -{ - /* - DDL_LOG_EXECUTE_CODE: - This is a code that indicates that this is a log entry to - be executed, from this entry a linked list of log entries - can be found and executed. - DDL_LOG_ENTRY_CODE: - An entry to be executed in a linked list from an execute log - entry. - DDL_IGNORE_LOG_ENTRY_CODE: - An entry that is to be ignored - */ - DDL_LOG_EXECUTE_CODE = 'e', - DDL_LOG_ENTRY_CODE = 'l', - DDL_IGNORE_LOG_ENTRY_CODE = 'i' -}; - -enum ddl_log_action_code -{ - /* - The type of action that a DDL_LOG_ENTRY_CODE entry is to - perform. - DDL_LOG_DELETE_ACTION: - Delete an entity - DDL_LOG_RENAME_ACTION: - Rename an entity - DDL_LOG_REPLACE_ACTION: - Rename an entity after removing the previous entry with the - new name, that is replace this entry. - DDL_LOG_EXCHANGE_ACTION: - Exchange two entities by renaming them a -> tmp, b -> a, tmp -> b. - */ - DDL_LOG_DELETE_ACTION = 'd', - DDL_LOG_RENAME_ACTION = 'r', - DDL_LOG_REPLACE_ACTION = 's', - DDL_LOG_EXCHANGE_ACTION = 'e' -}; - -enum enum_ddl_log_exchange_phase { - EXCH_PHASE_NAME_TO_TEMP= 0, - EXCH_PHASE_FROM_TO_NAME= 1, - EXCH_PHASE_TEMP_TO_FROM= 2 -}; - - -typedef struct st_ddl_log_entry -{ - const char *name; - const char *from_name; - const char *handler_name; - const char *tmp_name; - uint next_entry; - uint entry_pos; - enum ddl_log_entry_code entry_type; - enum ddl_log_action_code action_type; - /* - Most actions have only one phase. REPLACE does however have two - phases. The first phase removes the file with the new name if - there was one there before and the second phase renames the - old name to the new name. - */ - char phase; -} DDL_LOG_ENTRY; - -typedef struct st_ddl_log_memory_entry -{ - uint entry_pos; - struct st_ddl_log_memory_entry *next_log_entry; - struct st_ddl_log_memory_entry *prev_log_entry; - struct st_ddl_log_memory_entry *next_active_log_entry; -} DDL_LOG_MEMORY_ENTRY; - - -enum enum_explain_filename_mode -{ - EXPLAIN_ALL_VERBOSE= 0, - EXPLAIN_PARTITIONS_VERBOSE, - EXPLAIN_PARTITIONS_AS_COMMENT -}; - - -/* depends on errmsg.txt Database `db`, Table `t` ... */ -#define EXPLAIN_FILENAME_MAX_EXTRA_LENGTH 63 - -#define WFRM_WRITE_SHADOW 1 -#define WFRM_INSTALL_SHADOW 2 -#define WFRM_KEEP_SHARE 4 - -/* Flags for conversion functions. */ -static const uint FN_FROM_IS_TMP= 1 << 0; -static const uint FN_TO_IS_TMP= 1 << 1; -static const uint FN_IS_TMP= FN_FROM_IS_TMP | FN_TO_IS_TMP; -static const uint NO_FRM_RENAME= 1 << 2; -static const uint FRM_ONLY= 1 << 3; -/** Don't remove table in engine. Remove only .FRM and maybe .PAR files. */ -static const uint NO_HA_TABLE= 1 << 4; -/** Don't resolve MySQL's fake "foo.sym" symbolic directory names. */ -static const uint SKIP_SYMDIR_ACCESS= 1 << 5; -/** Don't check foreign key constraints while renaming table */ -static const uint NO_FK_CHECKS= 1 << 6; -/* Don't delete .par table in quick_rm_table() */ -static const uint NO_PAR_TABLE= 1 << 7; - -uint filename_to_tablename(const char *from, char *to, size_t to_length, - bool stay_quiet = false); -uint tablename_to_filename(const char *from, char *to, size_t to_length); -uint check_n_cut_mysql50_prefix(const char *from, char *to, size_t to_length); -bool check_mysql50_prefix(const char *name); -uint build_table_filename(char *buff, size_t bufflen, const char *db, - const char *table, const char *ext, uint flags); -uint build_table_shadow_filename(char *buff, size_t bufflen, - ALTER_PARTITION_PARAM_TYPE *lpt); -uint build_tmptable_filename(THD* thd, char *buff, size_t bufflen); -bool mysql_create_table(THD *thd, TABLE_LIST *create_table, - Table_specification_st *create_info, - Alter_info *alter_info); -bool add_keyword_to_query(THD *thd, String *result, const LEX_CSTRING *keyword, - const LEX_CSTRING *add); - -/* - mysql_create_table_no_lock can be called in one of the following - mutually exclusive situations: - - - Just a normal ordinary CREATE TABLE statement that explicitly - defines the table structure. - - - CREATE TABLE ... SELECT. It is special, because only in this case, - the list of fields is allowed to have duplicates, as long as one of the - duplicates comes from the select list, and the other doesn't. For - example in - - CREATE TABLE t1 (a int(5) NOT NUL) SELECT b+10 as a FROM t2; - - the list in alter_info->create_list will have two fields `a`. - - - ALTER TABLE, that creates a temporary table #sql-xxx, which will be later - renamed to replace the original table. - - - ALTER TABLE as above, but which only modifies the frm file, it only - creates an frm file for the #sql-xxx, the table in the engine is not - created. - - - Assisted discovery, CREATE TABLE statement without the table structure. - - These situations are distinguished by the following "create table mode" - values, where a CREATE ... SELECT is denoted by any non-negative number - (which should be the number of fields in the SELECT ... part), and other - cases use constants as defined below. -*/ -#define C_CREATE_SELECT(X) ((X) > 0 ? (X) : 0) -#define C_ORDINARY_CREATE 0 -#define C_ALTER_TABLE -1 -#define C_ALTER_TABLE_FRM_ONLY -2 -#define C_ASSISTED_DISCOVERY -3 - -int mysql_create_table_no_lock(THD *thd, const LEX_CSTRING *db, - const LEX_CSTRING *table_name, - Table_specification_st *create_info, - Alter_info *alter_info, bool *is_trans, - int create_table_mode, TABLE_LIST *table); - -handler *mysql_create_frm_image(THD *thd, - const LEX_CSTRING &db, - const LEX_CSTRING &table_name, - HA_CREATE_INFO *create_info, - Alter_info *alter_info, - int create_table_mode, - KEY **key_info, - uint *key_count, - LEX_CUSTRING *frm); - -int mysql_discard_or_import_tablespace(THD *thd, - TABLE_LIST *table_list, - bool discard); - -bool mysql_prepare_alter_table(THD *thd, TABLE *table, - HA_CREATE_INFO *create_info, - Alter_info *alter_info, - Alter_table_ctx *alter_ctx); -bool mysql_trans_prepare_alter_copy_data(THD *thd); -bool mysql_trans_commit_alter_copy_data(THD *thd); -bool mysql_alter_table(THD *thd, const LEX_CSTRING *new_db, - const LEX_CSTRING *new_name, - HA_CREATE_INFO *create_info, - TABLE_LIST *table_list, - Alter_info *alter_info, - uint order_num, ORDER *order, bool ignore, - bool if_exists); -bool mysql_compare_tables(TABLE *table, - Alter_info *alter_info, - HA_CREATE_INFO *create_info, - bool *metadata_equal); -bool mysql_recreate_table(THD *thd, TABLE_LIST *table_list, bool table_copy); -bool mysql_create_like_table(THD *thd, TABLE_LIST *table, - TABLE_LIST *src_table, - Table_specification_st *create_info); -bool mysql_rename_table(handlerton *base, const LEX_CSTRING *old_db, - const LEX_CSTRING *old_name, const LEX_CSTRING *new_db, - const LEX_CSTRING *new_name, uint flags); - -bool mysql_backup_table(THD* thd, TABLE_LIST* table_list); -bool mysql_restore_table(THD* thd, TABLE_LIST* table_list); - -bool mysql_checksum_table(THD* thd, TABLE_LIST* table_list, - HA_CHECK_OPT* check_opt); -bool mysql_rm_table(THD *thd,TABLE_LIST *tables, bool if_exists, - bool drop_temporary, bool drop_sequence, - bool dont_log_query); -int mysql_rm_table_no_locks(THD *thd, TABLE_LIST *tables, bool if_exists, - bool drop_temporary, bool drop_view, - bool drop_sequence, - bool dont_log_query, bool dont_free_locks); -bool log_drop_table(THD *thd, const LEX_CSTRING *db_name, - const LEX_CSTRING *table_name, bool temporary_table); -bool quick_rm_table(THD *thd, handlerton *base, const LEX_CSTRING *db, - const LEX_CSTRING *table_name, uint flags, - const char *table_path=0); -void close_cached_table(THD *thd, TABLE *table); -void sp_prepare_create_field(THD *thd, Column_definition *sql_field); -CHARSET_INFO* get_sql_field_charset(Column_definition *sql_field, - HA_CREATE_INFO *create_info); -bool mysql_write_frm(ALTER_PARTITION_PARAM_TYPE *lpt, uint flags); -int write_bin_log(THD *thd, bool clear_error, - char const *query, ulong query_length, - bool is_trans= FALSE); -int write_bin_log_with_if_exists(THD *thd, bool clear_error, - bool is_trans, bool add_if_exists); -bool write_ddl_log_entry(DDL_LOG_ENTRY *ddl_log_entry, - DDL_LOG_MEMORY_ENTRY **active_entry); -bool write_execute_ddl_log_entry(uint first_entry, - bool complete, - DDL_LOG_MEMORY_ENTRY **active_entry); -bool deactivate_ddl_log_entry(uint entry_no); -void release_ddl_log_memory_entry(DDL_LOG_MEMORY_ENTRY *log_entry); -bool sync_ddl_log(); -void release_ddl_log(); -void execute_ddl_log_recovery(); -bool execute_ddl_log_entry(THD *thd, uint first_entry); - -template class List; -void promote_first_timestamp_column(List *column_definitions); - -/* - These prototypes where under INNODB_COMPATIBILITY_HOOKS. -*/ -uint explain_filename(THD* thd, const char *from, char *to, uint to_length, - enum_explain_filename_mode explain_mode); - - -extern MYSQL_PLUGIN_IMPORT const char *primary_key_name; -extern mysql_mutex_t LOCK_gdl; - -bool check_engine(THD *, const char *, const char *, HA_CREATE_INFO *); - -#endif /* SQL_TABLE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_tablespace.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_tablespace.h deleted file mode 100644 index 0760935..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_tablespace.h +++ /dev/null @@ -1,24 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_TABLESPACE_INCLUDED -#define SQL_TABLESPACE_INCLUDED - -class THD; -class st_alter_tablespace; - -int mysql_alter_tablespace(THD* thd, st_alter_tablespace *ts_info); - -#endif /* SQL_TABLESPACE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_test.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_test.h deleted file mode 100644 index 2ab305a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_test.h +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_TEST_INCLUDED -#define SQL_TEST_INCLUDED - -#include "mysqld.h" -#include "opt_trace_context.h" - -class JOIN; -struct TABLE_LIST; -typedef class Item COND; -typedef class st_select_lex SELECT_LEX; -struct SORT_FIELD; - -#ifndef DBUG_OFF -void print_where(COND *cond,const char *info, enum_query_type query_type); -void TEST_filesort(SORT_FIELD *sortorder,uint s_length); -void TEST_join(JOIN *join); -void print_plan(JOIN* join,uint idx, double record_count, double read_time, - double current_read_time, const char *info); -void print_keyuse_array(DYNAMIC_ARRAY *keyuse_array); -void print_sjm(SJ_MATERIALIZATION_INFO *sjm); -void dump_TABLE_LIST_graph(SELECT_LEX *select_lex, TABLE_LIST* tl); -#endif -void print_keyuse_array_for_trace(THD *thd, DYNAMIC_ARRAY *keyuse_array); -void mysql_print_status(); - -#endif /* SQL_TEST_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_time.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_time.h deleted file mode 100644 index c918eb6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_time.h +++ /dev/null @@ -1,190 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. - Copyright (c) 2011, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_TIME_INCLUDED -#define SQL_TIME_INCLUDED - -#include "sql_basic_types.h" -#include "my_time.h" -#include "mysql_time.h" /* timestamp_type */ -#include "sql_error.h" /* Sql_condition */ -#include "structs.h" /* INTERVAL */ - -typedef enum enum_mysql_timestamp_type timestamp_type; -typedef struct st_date_time_format DATE_TIME_FORMAT; -typedef struct st_known_date_time_format KNOWN_DATE_TIME_FORMAT; - -/* Flags for calc_week() function. */ -#define WEEK_MONDAY_FIRST 1 -#define WEEK_YEAR 2 -#define WEEK_FIRST_WEEKDAY 4 - -ulong convert_period_to_month(ulong period); -ulong convert_month_to_period(ulong month); -void set_current_date(THD *thd, MYSQL_TIME *to); -bool time_to_datetime(MYSQL_TIME *ltime); -bool get_date_from_daynr(long daynr,uint *year, uint *month, uint *day); -my_time_t TIME_to_timestamp(THD *thd, const MYSQL_TIME *t, uint *error_code); -bool str_to_datetime_with_warn(THD *thd, - CHARSET_INFO *cs, const char *str, size_t length, - MYSQL_TIME *l_time, - date_mode_t flags); -bool double_to_datetime_with_warn(THD *thd, double value, MYSQL_TIME *ltime, - date_mode_t fuzzydate, - const TABLE_SHARE *s, const char *name); -bool decimal_to_datetime_with_warn(THD *thd, - const my_decimal *value, MYSQL_TIME *ltime, - date_mode_t fuzzydate, - const TABLE_SHARE *s, const char *name); -bool int_to_datetime_with_warn(THD *thd, const Longlong_hybrid &nr, - MYSQL_TIME *ltime, - date_mode_t fuzzydate, - const TABLE_SHARE *s, const char *name); - -bool time_to_datetime(THD *thd, const MYSQL_TIME *tm, MYSQL_TIME *dt); -bool time_to_datetime_with_warn(THD *thd, - const MYSQL_TIME *tm, MYSQL_TIME *dt, - date_conv_mode_t fuzzydate); - -inline void datetime_to_date(MYSQL_TIME *ltime) -{ - DBUG_ASSERT(ltime->time_type == MYSQL_TIMESTAMP_DATE || - ltime->time_type == MYSQL_TIMESTAMP_DATETIME); - DBUG_ASSERT(ltime->neg == 0); - ltime->second_part= ltime->hour= ltime->minute= ltime->second= 0; - ltime->time_type= MYSQL_TIMESTAMP_DATE; -} -inline void date_to_datetime(MYSQL_TIME *ltime) -{ - DBUG_ASSERT(ltime->time_type == MYSQL_TIMESTAMP_DATE || - ltime->time_type == MYSQL_TIMESTAMP_DATETIME); - DBUG_ASSERT(ltime->neg == 0); - ltime->time_type= MYSQL_TIMESTAMP_DATETIME; -} -void make_truncated_value_warning(THD *thd, - Sql_condition::enum_warning_level level, - const ErrConv *str_val, - timestamp_type time_type, - const char *db_name, const char *table_name, - const char *field_name); - -extern DATE_TIME_FORMAT *date_time_format_make(timestamp_type format_type, - const char *format_str, - uint format_length); -extern DATE_TIME_FORMAT *date_time_format_copy(THD *thd, - DATE_TIME_FORMAT *format); -const char *get_date_time_format_str(KNOWN_DATE_TIME_FORMAT *format, - timestamp_type type); -bool my_TIME_to_str(const MYSQL_TIME *ltime, String *str, uint dec); - -/* MYSQL_TIME operations */ -bool date_add_interval(THD *thd, MYSQL_TIME *ltime, interval_type int_type, - const INTERVAL &interval, bool push_warn= true); -bool calc_time_diff(const MYSQL_TIME *l_time1, const MYSQL_TIME *l_time2, - int l_sign, ulonglong *seconds_out, ulong *microseconds_out); -int append_interval(String *str, interval_type int_type, - const INTERVAL &interval); -/** - Calculate time difference between two MYSQL_TIME values and - store the result as an out MYSQL_TIME value in MYSQL_TIMESTAMP_TIME format. - - The result can be outside of the supported TIME range. - For example, calc_time_diff('2002-01-01 00:00:00', '2001-01-01 00:00:00') - returns '8760:00:00'. So the caller might want to do check_time_range() or - adjust_time_range_with_warn() on the result of a calc_time_diff() call. - - @param l_time1 - the minuend (TIME/DATE/DATETIME value) - @param l_time2 - the subtrahend TIME/DATE/DATETIME value - @param l_sign - +1 if absolute values are to be subtracted, - or -1 if absolute values are to be added. - @param[out] l_time3 - the result - @param fuzzydate - flags - - @return true - if TIME_NO_ZERO_DATE was passed in flags and - the result appeared to be '00:00:00.000000'. - This is important when calc_time_diff() is called - when calculating DATE_ADD(TIMEDIFF(...),...) - @return false - otherwise -*/ -bool calc_time_diff(const MYSQL_TIME *l_time1, const MYSQL_TIME *l_time2, - int lsign, MYSQL_TIME *l_time3, date_mode_t fuzzydate); -int my_time_compare(const MYSQL_TIME *a, const MYSQL_TIME *b); -void localtime_to_TIME(MYSQL_TIME *to, struct tm *from); - -void calc_time_from_sec(MYSQL_TIME *to, ulong seconds, ulong microseconds); -uint calc_week(const MYSQL_TIME *l_time, uint week_behaviour, uint *year); - -int calc_weekday(long daynr,bool sunday_first_day_of_week); -bool parse_date_time_format(timestamp_type format_type, - const char *format, uint format_length, - DATE_TIME_FORMAT *date_time_format); - -/* convenience wrapper */ -inline bool parse_date_time_format(timestamp_type format_type, - DATE_TIME_FORMAT *date_time_format) -{ - return parse_date_time_format(format_type, - date_time_format->format.str, - (uint) date_time_format->format.length, - date_time_format); -} - - -extern DATE_TIME_FORMAT global_date_format; -extern DATE_TIME_FORMAT global_datetime_format; -extern DATE_TIME_FORMAT global_time_format; -extern KNOWN_DATE_TIME_FORMAT known_date_time_formats[]; -extern LEX_CSTRING interval_type_to_name[]; - -static inline bool -non_zero_hhmmssuu(const MYSQL_TIME *ltime) -{ - return ltime->hour || ltime->minute || ltime->second || ltime->second_part; -} -static inline bool -non_zero_YYMMDD(const MYSQL_TIME *ltime) -{ - return ltime->year || ltime->month || ltime->day; -} -static inline bool -non_zero_date(const MYSQL_TIME *ltime) -{ - return non_zero_YYMMDD(ltime) || - (ltime->time_type == MYSQL_TIMESTAMP_DATETIME && - non_zero_hhmmssuu(ltime)); -} -static inline bool -check_date(const MYSQL_TIME *ltime, date_conv_mode_t flags, int *was_cut) -{ - return check_date(ltime, non_zero_date(ltime), - ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), was_cut); -} -bool check_date_with_warn(THD *thd, const MYSQL_TIME *ltime, - date_conv_mode_t fuzzy_date, timestamp_type ts_type); -static inline bool -check_date_with_warn(THD *thd, const MYSQL_TIME *ltime, - date_mode_t fuzzydate, timestamp_type ts_type) -{ - return check_date_with_warn(thd, ltime, date_conv_mode_t(fuzzydate), ts_type); -} - -bool adjust_time_range_with_warn(THD *thd, MYSQL_TIME *ltime, uint dec); - -longlong pack_time(const MYSQL_TIME *my_time); -void unpack_time(longlong packed, MYSQL_TIME *my_time, - enum_mysql_timestamp_type ts_type); - -#endif /* SQL_TIME_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_trigger.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_trigger.h deleted file mode 100644 index 040d8eb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_trigger.h +++ /dev/null @@ -1,331 +0,0 @@ -#ifndef SQL_TRIGGER_INCLUDED -#define SQL_TRIGGER_INCLUDED - -/* - Copyright (c) 2004, 2011, Oracle and/or its affiliates. - Copyright (c) 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include - -/* Forward declarations */ - -class Item_trigger_field; -class sp_head; -class sp_name; -class Query_tables_list; -struct TABLE_LIST; -class Query_tables_list; - -/** Event on which trigger is invoked. */ -enum trg_event_type -{ - TRG_EVENT_INSERT= 0, - TRG_EVENT_UPDATE= 1, - TRG_EVENT_DELETE= 2, - TRG_EVENT_MAX -}; - -static inline uint8 trg2bit(enum trg_event_type trg) -{ return static_cast(1 << static_cast(trg)); } - -#include "table.h" /* GRANT_INFO */ - -/* - We need this two enums here instead of sql_lex.h because - at least one of them is used by Item_trigger_field interface. - - Time when trigger is invoked (i.e. before or after row actually - inserted/updated/deleted). -*/ -enum trg_action_time_type -{ - TRG_ACTION_BEFORE= 0, TRG_ACTION_AFTER= 1, TRG_ACTION_MAX -}; - -enum trigger_order_type -{ - TRG_ORDER_NONE= 0, - TRG_ORDER_FOLLOWS= 1, - TRG_ORDER_PRECEDES= 2 -}; - - -struct st_trg_execution_order -{ - /** - FOLLOWS or PRECEDES as specified in the CREATE TRIGGER statement. - */ - enum trigger_order_type ordering_clause; - - /** - Trigger name referenced in the FOLLOWS/PRECEDES clause of the - CREATE TRIGGER statement. - */ - LEX_CSTRING anchor_trigger_name; -}; - - -class Table_triggers_list; - -/** - The trigger object -*/ - -class Trigger :public Sql_alloc -{ -public: - Trigger(Table_triggers_list *base_arg, sp_head *code): - base(base_arg), body(code), next(0), trigger_fields(0), action_order(0) - { - bzero((char *)&subject_table_grants, sizeof(subject_table_grants)); - } - ~Trigger(); - Table_triggers_list *base; - sp_head *body; - Trigger *next; /* Next trigger of same type */ - - /** - Heads of the lists linking items for all fields used in triggers - grouped by event and action_time. - */ - Item_trigger_field *trigger_fields; - LEX_CSTRING name; - LEX_CSTRING on_table_name; /* Raw table name */ - LEX_CSTRING definition; - LEX_CSTRING definer; - - /* Character sets used */ - LEX_CSTRING client_cs_name; - LEX_CSTRING connection_cl_name; - LEX_CSTRING db_cl_name; - - GRANT_INFO subject_table_grants; - sql_mode_t sql_mode; - /* Store create time. Can't be mysql_time_t as this holds also sub seconds */ - ulonglong create_time; - trg_event_type event; - trg_action_time_type action_time; - uint action_order; - - bool is_fields_updated_in_trigger(MY_BITMAP *used_fields); - void get_trigger_info(LEX_CSTRING *stmt, LEX_CSTRING *body, - LEX_STRING *definer); - /* Functions executed over each active trigger */ - bool change_on_table_name(void* param_arg); - bool change_table_name(void* param_arg); - bool add_to_file_list(void* param_arg); -}; - -typedef bool (Trigger::*Triggers_processor)(void *arg); - -/** - This class holds all information about triggers of table. -*/ - -class Table_triggers_list: public Sql_alloc -{ - friend class Trigger; - - /* Points to first trigger for a certain type */ - Trigger *triggers[TRG_EVENT_MAX][TRG_ACTION_MAX]; - /** - Copy of TABLE::Field array which all fields made nullable - (using extra_null_bitmap, if needed). Used for NEW values in - BEFORE INSERT/UPDATE triggers. - */ - Field **record0_field; - uchar *extra_null_bitmap; - /** - Copy of TABLE::Field array with field pointers set to TABLE::record[1] - buffer instead of TABLE::record[0] (used for OLD values in on UPDATE - trigger and DELETE trigger when it is called for REPLACE). - */ - Field **record1_field; - /** - During execution of trigger new_field and old_field should point to the - array of fields representing new or old version of row correspondingly - (so it can point to TABLE::field or to Tale_triggers_list::record1_field) - */ - Field **new_field; - Field **old_field; - - /* TABLE instance for which this triggers list object was created */ - TABLE *trigger_table; - - /** - This flag indicates that one of the triggers was not parsed successfully, - and as a precaution the object has entered a state where all trigger - access results in errors until all such triggers are dropped. It is not - safe to add triggers since we don't know if the broken trigger has the - same name or event type. Nor is it safe to invoke any trigger for the - aforementioned reasons. The only safe operations are drop_trigger and - drop_all_triggers. - - @see Table_triggers_list::set_parse_error - */ - bool m_has_unparseable_trigger; - - /** - This error will be displayed when the user tries to manipulate or invoke - triggers on a table that has broken triggers. It will get set only once - per statement and thus will contain the first parse error encountered in - the trigger file. - */ - char m_parse_error_message[MYSQL_ERRMSG_SIZE]; - uint count; /* Number of triggers */ - -public: - /** - Field responsible for storing triggers definitions in file. - It have to be public because we are using it directly from parser. - */ - List definitions_list; - /** - List of sql modes for triggers - */ - List definition_modes_list; - /** Create times for triggers */ - List create_times; - - List definers_list; - - /* Character set context, used for parsing and executing triggers. */ - - List client_cs_names; - List connection_cl_names; - List db_cl_names; - - /* End of character ser context. */ - - Table_triggers_list(TABLE *table_arg) - :record0_field(0), extra_null_bitmap(0), record1_field(0), - trigger_table(table_arg), - m_has_unparseable_trigger(false), count(0) - { - bzero((char *) triggers, sizeof(triggers)); - } - ~Table_triggers_list(); - - bool create_trigger(THD *thd, TABLE_LIST *table, String *stmt_query); - bool drop_trigger(THD *thd, TABLE_LIST *table, String *stmt_query); - bool process_triggers(THD *thd, trg_event_type event, - trg_action_time_type time_type, - bool old_row_is_record1); - void empty_lists(); - bool create_lists_needed_for_files(MEM_ROOT *root); - bool save_trigger_file(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table_name); - - static bool check_n_load(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table_name, - TABLE *table, bool names_only); - static bool drop_all_triggers(THD *thd, const LEX_CSTRING *db, - const LEX_CSTRING *table_name, myf MyFlags); - static bool change_table_name(THD *thd, const LEX_CSTRING *db, - const LEX_CSTRING *old_alias, - const LEX_CSTRING *old_table, - const LEX_CSTRING *new_db, - const LEX_CSTRING *new_table); - void add_trigger(trg_event_type event_type, - trg_action_time_type action_time, - trigger_order_type ordering_clause, - LEX_CSTRING *anchor_trigger_name, - Trigger *trigger); - Trigger *get_trigger(trg_event_type event_type, - trg_action_time_type action_time) - { - return triggers[event_type][action_time]; - } - /* Simpler version of the above, to avoid casts in the code */ - Trigger *get_trigger(uint event_type, uint action_time) - { - return get_trigger((trg_event_type) event_type, - (trg_action_time_type) action_time); - } - - bool has_triggers(trg_event_type event_type, - trg_action_time_type action_time) - { - return get_trigger(event_type,action_time) != 0; - } - bool has_delete_triggers() - { - return (has_triggers(TRG_EVENT_DELETE,TRG_ACTION_BEFORE) || - has_triggers(TRG_EVENT_DELETE,TRG_ACTION_AFTER)); - } - - void mark_fields_used(trg_event_type event); - - void set_parse_error_message(char *error_message); - - friend class Item_trigger_field; - - bool add_tables_and_routines_for_triggers(THD *thd, - Query_tables_list *prelocking_ctx, - TABLE_LIST *table_list); - - Field **nullable_fields() { return record0_field; } - void reset_extra_null_bitmap() - { - size_t null_bytes= (trigger_table->s->fields - - trigger_table->s->null_fields + 7)/8; - bzero(extra_null_bitmap, null_bytes); - } - - Trigger *find_trigger(const LEX_CSTRING *name, bool remove_from_list); - - Trigger* for_all_triggers(Triggers_processor func, void *arg); - -private: - bool prepare_record_accessors(TABLE *table); - Trigger *change_table_name_in_trignames(const LEX_CSTRING *old_db_name, - const LEX_CSTRING *new_db_name, - const LEX_CSTRING *new_table_name, - Trigger *trigger); - bool change_table_name_in_triggers(THD *thd, - const LEX_CSTRING *old_db_name, - const LEX_CSTRING *new_db_name, - const LEX_CSTRING *old_table_name, - const LEX_CSTRING *new_table_name); - - bool check_for_broken_triggers() - { - if (m_has_unparseable_trigger) - { - my_message(ER_PARSE_ERROR, m_parse_error_message, MYF(0)); - return true; - } - return false; - } -}; - -bool add_table_for_trigger(THD *thd, - const sp_name *trg_name, - bool continue_if_not_exist, - TABLE_LIST **table); - -void build_trn_path(THD *thd, const sp_name *trg_name, LEX_STRING *trn_path); - -bool check_trn_exists(const LEX_CSTRING *trn_path); - -bool load_table_name_for_trigger(THD *thd, - const sp_name *trg_name, - const LEX_CSTRING *trn_path, - LEX_CSTRING *tbl_name); -bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create); - -extern const char * const TRG_EXT; -extern const char * const TRN_EXT; - -#endif /* SQL_TRIGGER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_truncate.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_truncate.h deleted file mode 100644 index 7d2ff4b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_truncate.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef SQL_TRUNCATE_INCLUDED -#define SQL_TRUNCATE_INCLUDED -/* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -class THD; -struct TABLE_LIST; - -/** - Sql_cmd_truncate_table represents the TRUNCATE statement. -*/ -class Sql_cmd_truncate_table : public Sql_cmd -{ -private: - /* Set if a lock must be downgraded after truncate is done. */ - MDL_ticket *m_ticket_downgrade; - -public: - /** - Constructor, used to represent a TRUNCATE statement. - */ - Sql_cmd_truncate_table() - {} - - virtual ~Sql_cmd_truncate_table() - {} - - /** - Execute a TRUNCATE statement at runtime. - @param thd the current thread. - @return false on success. - */ - bool execute(THD *thd); - - virtual enum_sql_command sql_command_code() const - { - return SQLCOM_TRUNCATE; - } - -protected: - enum truncate_result{ - TRUNCATE_OK=0, - TRUNCATE_FAILED_BUT_BINLOG, - TRUNCATE_FAILED_SKIP_BINLOG - }; - - /** Handle locking a base table for truncate. */ - bool lock_table(THD *, TABLE_LIST *, bool *); - - /** Truncate table via the handler method. */ - enum truncate_result handler_truncate(THD *, TABLE_LIST *, bool); - - /** - Optimized delete of all rows by doing a full regenerate of the table. - Depending on the storage engine, it can be accomplished through a - drop and recreate or via the handler truncate method. - */ - bool truncate_table(THD *, TABLE_LIST *); -}; - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_tvc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_tvc.h deleted file mode 100644 index b5b8b97..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_tvc.h +++ /dev/null @@ -1,74 +0,0 @@ -/* Copyright (c) 2017, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef SQL_TVC_INCLUDED -#define SQL_TVC_INCLUDED -#include "sql_type.h" - -typedef List List_item; -typedef bool (Item::*Item_processor) (void *arg); -class select_result; -class Explain_select; -class Explain_query; -class Item_func_in; -class st_select_lex_unit; -typedef class st_select_lex SELECT_LEX; - -/** - @class table_value_constr - @brief Definition of a Table Value Construction(TVC) - - It contains a list of lists of values which this TVC is defined by and - reference on SELECT where this TVC is defined. -*/ -class table_value_constr : public Sql_alloc -{ -public: - List lists_of_values; - select_result *result; - SELECT_LEX *select_lex; - - enum { QEP_NOT_PRESENT_YET, QEP_AVAILABLE} have_query_plan; - - Explain_select *explain; - ulonglong select_options; - - table_value_constr(List tvc_values, SELECT_LEX *sl, - ulonglong select_options_arg) : - lists_of_values(tvc_values), result(0), select_lex(sl), - have_query_plan(QEP_NOT_PRESENT_YET), explain(0), - select_options(select_options_arg) - { }; - - ha_rows get_records() { return lists_of_values.elements; } - - bool prepare(THD *thd_arg, SELECT_LEX *sl, - select_result *tmp_result, - st_select_lex_unit *unit_arg); - - bool to_be_wrapped_as_with_tail(); - - int save_explain_data_intern(THD *thd_arg, - Explain_query *output); - bool optimize(THD *thd_arg); - bool exec(SELECT_LEX *sl); - - void print(THD *thd_arg, String *str, enum_query_type query_type); - bool walk_values(Item_processor processor, bool walk_subquery, void *arg); -}; - -st_select_lex *wrap_tvc_with_tail(THD *thd, st_select_lex *tvc_sl); - -#endif /* SQL_TVC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type.h deleted file mode 100644 index db4f67e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type.h +++ /dev/null @@ -1,7519 +0,0 @@ -#ifndef SQL_TYPE_H_INCLUDED -#define SQL_TYPE_H_INCLUDED -/* - Copyright (c) 2015 MariaDB Foundation. - Copyright (c) 2015, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - - -#include "mysqld.h" -#include "lex_string.h" -#include "sql_array.h" -#include "sql_const.h" -#include "sql_time.h" -#include "sql_type_string.h" -#include "sql_type_real.h" -#include "compat56.h" -C_MODE_START -#include -C_MODE_END - -class Field; -class Column_definition; -class Column_definition_attributes; -class Key_part_spec; -class Item; -class Item_const; -class Item_literal; -class Item_param; -class Item_cache; -class Item_copy; -class Item_func_or_sum; -class Item_sum_hybrid; -class Item_sum_sum; -class Item_sum_avg; -class Item_sum_variance; -class Item_func_hex; -class Item_hybrid_func; -class Item_func_min_max; -class Item_func_hybrid_field_type; -class Item_bool_func2; -class Item_func_between; -class Item_func_in; -class Item_func_round; -class Item_func_int_val; -class Item_func_abs; -class Item_func_neg; -class Item_func_signed; -class Item_func_unsigned; -class Item_double_typecast; -class Item_float_typecast; -class Item_decimal_typecast; -class Item_char_typecast; -class Item_time_typecast; -class Item_date_typecast; -class Item_datetime_typecast; -class Item_func_plus; -class Item_func_minus; -class Item_func_mul; -class Item_func_div; -class Item_func_mod; -class cmp_item; -class in_vector; -class Type_handler_data; -class Type_handler_hybrid_field_type; -class Sort_param; -class Arg_comparator; -class Spvar_definition; -struct st_value; -class Protocol; -class handler; -struct Schema_specification_st; -struct TABLE; -struct SORT_FIELD_ATTR; -struct SORT_FIELD; -class Vers_history_point; -class Virtual_column_info; -class Conv_source; -class ST_FIELD_INFO; -class Type_collection; -class Create_func; - -#define my_charset_numeric my_charset_latin1 - -enum protocol_send_type_t -{ - PROTOCOL_SEND_STRING, - PROTOCOL_SEND_FLOAT, - PROTOCOL_SEND_DOUBLE, - PROTOCOL_SEND_TINY, - PROTOCOL_SEND_SHORT, - PROTOCOL_SEND_LONG, - PROTOCOL_SEND_LONGLONG, - PROTOCOL_SEND_DATETIME, - PROTOCOL_SEND_DATE, - PROTOCOL_SEND_TIME -}; - - -enum scalar_comparison_op -{ - SCALAR_CMP_EQ, - SCALAR_CMP_EQUAL, - SCALAR_CMP_LT, - SCALAR_CMP_LE, - SCALAR_CMP_GE, - SCALAR_CMP_GT -}; - - -enum partition_value_print_mode_t -{ - PARTITION_VALUE_PRINT_MODE_SHOW= 0, - PARTITION_VALUE_PRINT_MODE_FRM= 1 -}; - - -enum column_definition_type_t -{ - COLUMN_DEFINITION_TABLE_FIELD, - COLUMN_DEFINITION_ROUTINE_PARAM, - COLUMN_DEFINITION_ROUTINE_LOCAL, - COLUMN_DEFINITION_FUNCTION_RETURN -}; - - -class Send_field_extended_metadata -{ - LEX_CSTRING m_attr[MARIADB_FIELD_ATTR_LAST+1]; -public: - Send_field_extended_metadata() - { - bzero(this, sizeof(*this)); - } - bool set_data_type_name(const LEX_CSTRING &str) - { - m_attr[MARIADB_FIELD_ATTR_DATA_TYPE_NAME]= str; - return false; - } - bool set_format_name(const LEX_CSTRING &str) - { - m_attr[MARIADB_FIELD_ATTR_FORMAT_NAME]= str; - return false; - } - bool has_extended_metadata() const - { - for (uint i= 0; i <= MARIADB_FIELD_ATTR_LAST; i++) - { - if (m_attr[i].str) - return true; - } - return false; - } - const LEX_CSTRING &attr(uint i) const - { - DBUG_ASSERT(i <= MARIADB_FIELD_ATTR_LAST); - return m_attr[i]; - } -}; - - -class Data_type_statistics -{ -public: - uint m_uneven_bit_length; - uint m_fixed_string_total_length; - uint m_fixed_string_count; - uint m_variable_string_total_length; - uint m_variable_string_count; - uint m_blob_count; - Data_type_statistics() - :m_uneven_bit_length(0), - m_fixed_string_total_length(0), - m_fixed_string_count(0), - m_variable_string_total_length(0), - m_variable_string_count(0), - m_blob_count(0) - { } - uint string_count() const - { - return m_fixed_string_count + m_variable_string_count; - } - uint string_total_length() const - { - return m_fixed_string_total_length + m_variable_string_total_length; - } -}; - - -class Typelib: public TYPELIB -{ -public: - Typelib(uint count, const char **type_names, unsigned int *type_lengths) - { - TYPELIB::count= count; - TYPELIB::name= ""; - TYPELIB::type_names= type_names; - TYPELIB::type_lengths= type_lengths; - } - uint max_octet_length() const - { - uint max_length= 0; - for (uint i= 0; i < TYPELIB::count; i++) - { - const uint length= TYPELIB::type_lengths[i]; - set_if_bigger(max_length, length); - } - return max_length; - } -}; - - -template -class TypelibBuffer: public Typelib -{ - const char *m_type_names[sz + 1]; - uint m_type_lengths[sz + 1]; -public: - TypelibBuffer(uint count, const LEX_CSTRING *values) - :Typelib(count, m_type_names, m_type_lengths) - { - DBUG_ASSERT(sz >= count); - for (uint i= 0; i < count; i++) - { - DBUG_ASSERT(values[i].str != NULL); - m_type_names[i]= values[i].str; - m_type_lengths[i]= (uint) values[i].length; - } - m_type_names[sz]= NullS; // End marker - m_type_lengths[sz]= 0; // End marker - } - TypelibBuffer(const LEX_CSTRING *values) - :TypelibBuffer(sz, values) - { } -}; - - -class Native: public Binary_string -{ -public: - Native(char *str, size_t len) - :Binary_string(str, len) - { } -}; - - -template -class NativeBuffer: public Native -{ - char buff[buff_sz]; -public: - NativeBuffer() : Native(buff, buff_sz) { length(0); } -}; - - -class String_ptr -{ -protected: - String *m_string_ptr; -public: - String_ptr(String *str) - :m_string_ptr(str) - { } - String_ptr(Item *item, String *buffer); - const String *string() const - { - DBUG_ASSERT(m_string_ptr); - return m_string_ptr; - } - bool is_null() const { return m_string_ptr == NULL; } -}; - - -class Ascii_ptr: public String_ptr -{ -public: - Ascii_ptr(Item *item, String *buffer); -}; - - -template -class String_ptr_and_buffer: public StringBuffer, - public String_ptr -{ -public: - String_ptr_and_buffer(Item *item) - :String_ptr(item, this) - { } -}; - - -template -class Ascii_ptr_and_buffer: public StringBuffer, - public Ascii_ptr -{ -public: - Ascii_ptr_and_buffer(Item *item) - :Ascii_ptr(item, this) - { } -}; - - -class Dec_ptr -{ -protected: - my_decimal *m_ptr; - Dec_ptr() { } -public: - Dec_ptr(my_decimal *ptr) :m_ptr(ptr) { } - bool is_null() const { return m_ptr == NULL; } - const my_decimal *ptr() const { return m_ptr; } - const my_decimal *ptr_or(const my_decimal *def) const - { - return m_ptr ? m_ptr : def; - } - my_decimal *to_decimal(my_decimal *to) const - { - if (!m_ptr) - return NULL; - *to= *m_ptr; - return to; - } - double to_double() const { return m_ptr ? m_ptr->to_double() : 0.0; } - longlong to_longlong(bool unsigned_flag) - { return m_ptr ? m_ptr->to_longlong(unsigned_flag) : 0; } - Longlong_null to_xlonglong_null() - { - return m_ptr ? Longlong_null(m_ptr->to_xlonglong()) : Longlong_null(); - } - bool to_bool() const { return m_ptr ? m_ptr->to_bool() : false; } - String *to_string(String *to) const - { - return m_ptr ? m_ptr->to_string(to) : NULL; - } - String *to_string(String *to, uint prec, uint dec, char filler) - { - return m_ptr ? m_ptr->to_string(to, prec, dec, filler) : NULL; - } - int to_binary(uchar *bin, int prec, int scale) const - { - return (m_ptr ? m_ptr : &decimal_zero)->to_binary(bin, prec, scale); - } - int cmp(const my_decimal *dec) const - { - DBUG_ASSERT(m_ptr); - DBUG_ASSERT(dec); - return m_ptr->cmp(dec); - } - int cmp(const Dec_ptr &other) const - { - return cmp(other.m_ptr); - } -}; - - -// A helper class to handle results of val_decimal(), date_op(), etc. -class Dec_ptr_and_buffer: public Dec_ptr -{ -protected: - my_decimal m_buffer; -public: - int round_to(my_decimal *to, int scale, decimal_round_mode mode) - { - DBUG_ASSERT(m_ptr); - return m_ptr->round_to(to, scale, mode); - } - int round_self(uint scale, decimal_round_mode mode) - { - return round_to(&m_buffer, scale, mode); - } - int round_self_if_needed(int scale, decimal_round_mode mode) - { - if (scale >= m_ptr->frac) - return E_DEC_OK; - int res= m_ptr->round_to(&m_buffer, scale, mode); - m_ptr= &m_buffer; - return res; - } - String *to_string_round(String *to, uint dec) - { - /* - decimal_round() allows from==to - So it's save even if m_ptr points to m_buffer before this call: - */ - return m_ptr ? m_ptr->to_string_round(to, dec, &m_buffer) : NULL; - } -}; - - -// A helper class to handle val_decimal() results. -class VDec: public Dec_ptr_and_buffer -{ -public: - VDec(): Dec_ptr_and_buffer() { } - VDec(Item *item); - void set(Item *a); -}; - - -// A helper class to handler decimal_op() results. -class VDec_op: public Dec_ptr_and_buffer -{ -public: - VDec_op(Item_func_hybrid_field_type *item); -}; - - -/* - Get and cache val_decimal() values for two items. - If the first value appears to be NULL, the second value is not evaluated. -*/ -class VDec2_lazy -{ -public: - VDec m_a; - VDec m_b; - VDec2_lazy(Item *a, Item *b) :m_a(a) - { - if (!m_a.is_null()) - m_b.set(b); - } - bool has_null() const - { - return m_a.is_null() || m_b.is_null(); - } -}; - - -/** - Class Sec6 represents a fixed point value with 6 fractional digits. - Used e.g. to convert double and my_decimal values to TIME/DATETIME. -*/ - -class Sec6 -{ -protected: - ulonglong m_sec; // The integer part, between 0 and LONGLONG_MAX - ulong m_usec; // The fractional part, between 0 and 999999 - bool m_neg; // false if positive, true of negative - bool m_truncated; // Indicates if the constructor truncated the value - void make_from_decimal(const my_decimal *d, ulong *nanoseconds); - void make_from_double(double d, ulong *nanoseconds); - void make_from_int(const Longlong_hybrid &nr) - { - m_neg= nr.neg(); - m_sec= nr.abs(); - m_usec= 0; - m_truncated= false; - } - void reset() - { - m_sec= m_usec= m_neg= m_truncated= 0; - } - Sec6() { } - bool add_nanoseconds(uint nanoseconds) - { - DBUG_ASSERT(nanoseconds <= 1000000000); - if (nanoseconds < 500) - return false; - m_usec+= (nanoseconds + 500) / 1000; - if (m_usec < 1000000) - return false; - m_usec%= 1000000; - return true; - } -public: - explicit Sec6(double nr) - { - ulong nanoseconds; - make_from_double(nr, &nanoseconds); - } - explicit Sec6(const my_decimal *d) - { - ulong nanoseconds; - make_from_decimal(d, &nanoseconds); - } - explicit Sec6(const Longlong_hybrid &nr) - { - make_from_int(nr); - } - explicit Sec6(longlong nr, bool unsigned_val) - { - make_from_int(Longlong_hybrid(nr, unsigned_val)); - } - bool neg() const { return m_neg; } - bool truncated() const { return m_truncated; } - ulonglong sec() const { return m_sec; } - long usec() const { return m_usec; } - /** - Converts Sec6 to MYSQL_TIME - @param thd current thd - @param [out] warn conversion warnings will be written here - @param [out] ltime converted value will be written here - @param fuzzydate conversion flags (TIME_INVALID_DATE, etc) - @returns false for success, true for a failure - */ - bool convert_to_mysql_time(THD *thd, - int *warn, - MYSQL_TIME *ltime, - date_mode_t fuzzydate) const; - -protected: - - bool to_interval_hhmmssff_only(MYSQL_TIME *to, int *warn) const - { - return number_to_time_only(m_neg, m_sec, m_usec, - TIME_MAX_INTERVAL_HOUR, to, warn); - } - bool to_datetime_or_to_interval_hhmmssff(MYSQL_TIME *to, int *warn) const - { - /* - Convert a number to a time interval. - The following formats are understood: - - 0 <= x <= 999999995959 - parse as hhhhmmss - - 999999995959 < x <= 99991231235959 - parse as YYYYMMDDhhmmss - (YYMMDDhhmmss) (YYYYMMDDhhmmss) - - Note, these formats are NOT understood: - - YYMMDD - overlaps with INTERVAL range - - YYYYMMDD - overlaps with INTERVAL range - - YYMMDDhhmmss - overlaps with INTERVAL range, partially - (see TIME_MAX_INTERVAL_HOUR) - - If we ever need wider intervals, this code switching between - full datetime and interval-only should be rewised. - */ - DBUG_ASSERT(TIME_MAX_INTERVAL_HOUR <= 999999995959); - /* (YYMMDDhhmmss) */ - if (m_sec > 999999995959ULL && - m_sec <= 99991231235959ULL && m_neg == 0) - return to_datetime_or_date(to, warn, TIME_INVALID_DATES); - if (m_sec / 10000 > TIME_MAX_INTERVAL_HOUR) - { - *warn= MYSQL_TIME_WARN_OUT_OF_RANGE; - return true; - } - return to_interval_hhmmssff_only(to, warn); - } -public: - // [-][DD]hhhmmss.ff, YYMMDDhhmmss.ff, YYYYMMDDhhmmss.ff - bool to_datetime_or_time(MYSQL_TIME *to, int *warn, - date_conv_mode_t mode) const - { - bool rc= m_sec > 9999999 && m_sec <= 99991231235959ULL && !m_neg ? - ::number_to_datetime_or_date(m_sec, m_usec, to, - ulonglong(mode & TIME_MODE_FOR_XXX_TO_DATE), warn) < 0 : - ::number_to_time_only(m_neg, m_sec, m_usec, TIME_MAX_HOUR, to, warn); - DBUG_ASSERT(*warn || !rc); - return rc; - } - /* - Convert a number in formats YYYYMMDDhhmmss.ff or YYMMDDhhmmss.ff to - TIMESTAMP'YYYY-MM-DD hh:mm:ss.ff' - */ - bool to_datetime_or_date(MYSQL_TIME *to, int *warn, - date_conv_mode_t flags) const - { - if (m_neg) - { - *warn= MYSQL_TIME_WARN_OUT_OF_RANGE; - return true; - } - bool rc= number_to_datetime_or_date(m_sec, m_usec, to, - ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), - warn) == -1; - DBUG_ASSERT(*warn || !rc); - return rc; - } - // Convert elapsed seconds to TIME - bool sec_to_time(MYSQL_TIME *ltime, uint dec) const - { - set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); - ltime->neg= m_neg; - if (m_sec > TIME_MAX_VALUE_SECONDS) - { - // use check_time_range() to set ltime to the max value depending on dec - int unused; - ltime->hour= TIME_MAX_HOUR + 1; - check_time_range(ltime, dec, &unused); - return true; - } - DBUG_ASSERT(usec() <= TIME_MAX_SECOND_PART); - ltime->hour= (uint) (m_sec / 3600); - ltime->minute= (uint) (m_sec % 3600) / 60; - ltime->second= (uint) m_sec % 60; - ltime->second_part= m_usec; - return false; - } - Sec6 &trunc(uint dec) - { - m_usec-= my_time_fraction_remainder(m_usec, dec); - return *this; - } - size_t to_string(char *to, size_t nbytes) const - { - return m_usec ? - my_snprintf(to, nbytes, "%s%llu.%06lu", - m_neg ? "-" : "", m_sec, (uint) m_usec) : - my_snprintf(to, nbytes, "%s%llu", m_neg ? "-" : "", m_sec); - } - void make_truncated_warning(THD *thd, const char *type_str) const; -}; - - -class Sec9: public Sec6 -{ -protected: - ulong m_nsec; // Nanoseconds 0..999 - void make_from_int(const Longlong_hybrid &nr) - { - Sec6::make_from_int(nr); - m_nsec= 0; - } - Sec9() { } -public: - Sec9(const my_decimal *d) - { - Sec6::make_from_decimal(d, &m_nsec); - } - Sec9(double d) - { - Sec6::make_from_double(d, &m_nsec); - } - ulong nsec() const { return m_nsec; } - Sec9 &trunc(uint dec) - { - m_nsec= 0; - Sec6::trunc(dec); - return *this; - } - Sec9 &round(uint dec); - Sec9 &round(uint dec, time_round_mode_t mode) - { - return mode == TIME_FRAC_TRUNCATE ? trunc(dec) : round(dec); - } -}; - - -class VSec9: protected Sec9 -{ - bool m_is_null; - Sec9& to_sec9() - { - DBUG_ASSERT(!is_null()); - return *this; - } -public: - VSec9(THD *thd, Item *item, const char *type_str, ulonglong limit); - bool is_null() const { return m_is_null; } - const Sec9& to_const_sec9() const - { - DBUG_ASSERT(!is_null()); - return *this; - } - bool neg() const { return to_const_sec9().neg(); } - bool truncated() const { return to_const_sec9().truncated(); } - ulonglong sec() const { return to_const_sec9().sec(); } - long usec() const { return to_const_sec9().usec(); } - bool sec_to_time(MYSQL_TIME *ltime, uint dec) const - { - return to_const_sec9().sec_to_time(ltime, dec); - } - void make_truncated_warning(THD *thd, const char *type_str) const - { - return to_const_sec9().make_truncated_warning(thd, type_str); - } - Sec9 &round(uint dec) - { - return to_sec9().round(dec); - } - Sec9 &round(uint dec, time_round_mode_t mode) - { - return to_sec9().round(dec, mode); - } -}; - - -/* - A heler class to perform additive operations between - two MYSQL_TIME structures and return the result as a - combination of seconds, microseconds and sign. -*/ -class Sec6_add -{ - ulonglong m_sec; // number of seconds - ulong m_usec; // number of microseconds - bool m_neg; // false if positive, true if negative - bool m_error; // false if the value is OK, true otherwise - void to_hh24mmssff(MYSQL_TIME *ltime, timestamp_type tstype) const - { - bzero(ltime, sizeof(*ltime)); - ltime->neg= m_neg; - calc_time_from_sec(ltime, (ulong) (m_sec % SECONDS_IN_24H), m_usec); - ltime->time_type= tstype; - } -public: - /* - @param ltime1 - the first value to add (must be a valid DATE,TIME,DATETIME) - @param ltime2 - the second value to add (must be a valid TIME) - @param sign - the sign of the operation - (+1 for addition, -1 for subtraction) - */ - Sec6_add(const MYSQL_TIME *ltime1, const MYSQL_TIME *ltime2, int sign) - { - DBUG_ASSERT(sign == -1 || sign == 1); - DBUG_ASSERT(!ltime1->neg || ltime1->time_type == MYSQL_TIMESTAMP_TIME); - if (!(m_error= (ltime2->time_type != MYSQL_TIMESTAMP_TIME))) - { - if (ltime1->neg != ltime2->neg) - sign= -sign; - m_neg= calc_time_diff(ltime1, ltime2, -sign, &m_sec, &m_usec); - if (ltime1->neg && (m_sec || m_usec)) - m_neg= !m_neg; // Swap sign - } - } - bool to_time(THD *thd, MYSQL_TIME *ltime, uint decimals) const - { - if (m_error) - return true; - to_hh24mmssff(ltime, MYSQL_TIMESTAMP_TIME); - ltime->hour+= static_cast(to_days_abs() * 24); - return adjust_time_range_with_warn(thd, ltime, decimals); - } - bool to_datetime(MYSQL_TIME *ltime) const - { - if (m_error || m_neg) - return true; - to_hh24mmssff(ltime, MYSQL_TIMESTAMP_DATETIME); - return get_date_from_daynr(to_days_abs(), - <ime->year, <ime->month, <ime->day) || - !ltime->day; - } - long to_days_abs() const { return (long) (m_sec / SECONDS_IN_24H); } -}; - - -class Year -{ -protected: - uint m_year; - bool m_truncated; - uint year_precision(const Item *item) const; -public: - Year(): m_year(0), m_truncated(false) { } - Year(longlong value, bool unsigned_flag, uint length); - uint year() const { return m_year; } - uint to_YYYYMMDD() const { return m_year * 10000; } - bool truncated() const { return m_truncated; } -}; - - -class Year_null: public Year, public Null_flag -{ -public: - Year_null(const Longlong_null &nr, bool unsigned_flag, uint length) - :Year(nr.is_null() ? 0 : nr.value(), unsigned_flag, length), - Null_flag(nr.is_null()) - { } -}; - - -class VYear: public Year_null -{ -public: - VYear(Item *item); -}; - - -class VYear_op: public Year_null -{ -public: - VYear_op(Item_func_hybrid_field_type *item); -}; - - -class Double_null: public Null_flag -{ -protected: - double m_value; -public: - Double_null(double value, bool is_null) - :Null_flag(is_null), m_value(value) - { } - double value() const { return m_value; } -}; - - -class Temporal: protected MYSQL_TIME -{ -public: - class Status: public MYSQL_TIME_STATUS - { - public: - Status() { my_time_status_init(this); } - }; - - class Warn: public ErrBuff, - public Status - { - public: - void push_conversion_warnings(THD *thd, bool totally_useless_value, - date_mode_t mode, timestamp_type tstype, - const char *db_name, const char *table_name, - const char *name) - { - const char *typestr= tstype >= 0 ? type_name_by_timestamp_type(tstype) : - mode & (TIME_INTERVAL_hhmmssff | TIME_INTERVAL_DAY) ? - "interval" : - mode & TIME_TIME_ONLY ? "time" : "datetime"; - Temporal::push_conversion_warnings(thd, totally_useless_value, warnings, - typestr, db_name, table_name, name, - ptr()); - } - }; - - class Warn_push: public Warn - { - THD * const m_thd; - const char * const m_db_name; - const char * const m_table_name; - const char * const m_name; - const MYSQL_TIME * const m_ltime; - const date_mode_t m_mode; - public: - Warn_push(THD *thd, const char *db_name, const char *table_name, - const char *name, const MYSQL_TIME *ltime, date_mode_t mode) - : m_thd(thd), m_db_name(db_name), m_table_name(table_name), m_name(name), - m_ltime(ltime), m_mode(mode) - { } - ~Warn_push() - { - if (warnings) - push_conversion_warnings(m_thd, m_ltime->time_type < 0, - m_mode, m_ltime->time_type, - m_db_name, m_table_name, m_name); - } - }; - -public: - static date_conv_mode_t sql_mode_for_dates(THD *thd); - static time_round_mode_t default_round_mode(THD *thd); - class Options: public date_mode_t - { - public: - explicit Options(date_mode_t flags) - :date_mode_t(flags) - { } - Options(date_conv_mode_t flags, time_round_mode_t round_mode) - :date_mode_t(flags | round_mode) - { - DBUG_ASSERT(ulonglong(flags) <= UINT_MAX32); - } - Options(date_conv_mode_t flags, THD *thd) - :Options(flags, default_round_mode(thd)) - { } - }; - - bool is_valid_temporal() const - { - DBUG_ASSERT(time_type != MYSQL_TIMESTAMP_ERROR); - return time_type != MYSQL_TIMESTAMP_NONE; - } - static const char *type_name_by_timestamp_type(timestamp_type time_type) - { - switch (time_type) { - case MYSQL_TIMESTAMP_DATE: return "date"; - case MYSQL_TIMESTAMP_TIME: return "time"; - case MYSQL_TIMESTAMP_DATETIME: // FALLTHROUGH - default: - break; - } - return "datetime"; - } - static void push_conversion_warnings(THD *thd, bool totally_useless_value, int warn, - const char *type_name, - const char *db_name, - const char *table_name, - const char *field_name, - const char *value); - /* - This method is used if the item was not null but convertion to - TIME/DATE/DATETIME failed. We return a zero date if allowed, - otherwise - null. - */ - void make_fuzzy_date(int *warn, date_conv_mode_t fuzzydate) - { - /* - In the following scenario: - - The caller expected to get a TIME value - - Item returned a not NULL string or numeric value - - But then conversion from string or number to TIME failed - we need to change the default time_type from MYSQL_TIMESTAMP_DATE - (which was set in bzero) to MYSQL_TIMESTAMP_TIME and therefore - return TIME'00:00:00' rather than DATE'0000-00-00'. - If we don't do this, methods like Item::get_time_with_conversion() - will erroneously subtract CURRENT_DATE from '0000-00-00 00:00:00' - and return TIME'-838:59:59' instead of TIME'00:00:00' as a result. - */ - timestamp_type tstype= !(fuzzydate & TIME_FUZZY_DATES) ? - MYSQL_TIMESTAMP_NONE : - fuzzydate & TIME_TIME_ONLY ? - MYSQL_TIMESTAMP_TIME : - MYSQL_TIMESTAMP_DATETIME; - set_zero_time(this, tstype); - } - -protected: - my_decimal *bad_to_decimal(my_decimal *to) const; - my_decimal *to_decimal(my_decimal *to) const; - static double to_double(bool negate, ulonglong num, ulong frac) - { - double d= static_cast(num) + static_cast(frac) / - TIME_SECOND_PART_FACTOR; - return negate ? -d : d; - } - longlong to_packed() const { return ::pack_time(this); } - void make_from_out_of_range(int *warn) - { - *warn= MYSQL_TIME_WARN_OUT_OF_RANGE; - time_type= MYSQL_TIMESTAMP_NONE; - } - void make_from_sec6(THD *thd, MYSQL_TIME_STATUS *st, - const Sec6 &nr, date_mode_t mode) - { - if (nr.convert_to_mysql_time(thd, &st->warnings, this, mode)) - make_fuzzy_date(&st->warnings, date_conv_mode_t(mode)); - } - void make_from_sec9(THD *thd, MYSQL_TIME_STATUS *st, - const Sec9 &nr, date_mode_t mode) - { - if (nr.convert_to_mysql_time(thd, &st->warnings, this, mode) || - add_nanoseconds(thd, &st->warnings, mode, nr.nsec())) - make_fuzzy_date(&st->warnings, date_conv_mode_t(mode)); - } - void make_from_str(THD *thd, Warn *warn, - const char *str, size_t length, CHARSET_INFO *cs, - date_mode_t fuzzydate); - void make_from_double(THD *thd, Warn *warn, double nr, date_mode_t mode) - { - make_from_sec9(thd, warn, Sec9(nr), mode); - if (warn->warnings) - warn->set_double(nr); - } - void make_from_longlong_hybrid(THD *thd, Warn *warn, - const Longlong_hybrid &nr, date_mode_t mode) - { - /* - Note: conversion from an integer to TIME can overflow to - '838:59:59.999999', so the conversion result can have fractional digits. - */ - make_from_sec6(thd, warn, Sec6(nr), mode); - if (warn->warnings) - warn->set_longlong(nr); - } - void make_from_decimal(THD *thd, Warn *warn, - const my_decimal *nr, date_mode_t mode) - { - make_from_sec9(thd, warn, Sec9(nr), mode); - if (warn->warnings) - warn->set_decimal(nr); - } - bool ascii_to_temporal(MYSQL_TIME_STATUS *st, - const char *str, size_t length, - date_mode_t mode) - { - if (mode & (TIME_INTERVAL_hhmmssff | TIME_INTERVAL_DAY)) - return ascii_to_datetime_or_date_or_interval_DDhhmmssff(st, str, length, - mode); - if (mode & TIME_TIME_ONLY) - return ascii_to_datetime_or_date_or_time(st, str, length, mode); - return ascii_to_datetime_or_date(st, str, length, mode); - } - bool ascii_to_datetime_or_date_or_interval_DDhhmmssff(MYSQL_TIME_STATUS *st, - const char *str, - size_t length, - date_mode_t mode) - { - longlong cflags= ulonglong(mode & TIME_MODE_FOR_XXX_TO_DATE); - bool rc= mode & TIME_INTERVAL_DAY ? - ::str_to_datetime_or_date_or_interval_day(str, length, this, cflags, st, - TIME_MAX_INTERVAL_HOUR, - TIME_MAX_INTERVAL_HOUR) : - ::str_to_datetime_or_date_or_interval_hhmmssff(str, length, this, - cflags, st, - TIME_MAX_INTERVAL_HOUR, - TIME_MAX_INTERVAL_HOUR); - DBUG_ASSERT(!rc || st->warnings); - return rc; - } - bool ascii_to_datetime_or_date_or_time(MYSQL_TIME_STATUS *status, - const char *str, size_t length, - date_mode_t fuzzydate) - { - ulonglong cflags= ulonglong(fuzzydate & TIME_MODE_FOR_XXX_TO_DATE); - bool rc= ::str_to_datetime_or_date_or_time(str, length, this, - cflags, status, - TIME_MAX_HOUR, UINT_MAX32); - DBUG_ASSERT(!rc || status->warnings); - return rc; - } - bool ascii_to_datetime_or_date(MYSQL_TIME_STATUS *status, - const char *str, size_t length, - date_mode_t fuzzydate) - { - DBUG_ASSERT(bool(fuzzydate & TIME_TIME_ONLY) == false); - bool rc= ::str_to_datetime_or_date(str, length, this, - ulonglong(fuzzydate & TIME_MODE_FOR_XXX_TO_DATE), - status); - DBUG_ASSERT(!rc || status->warnings); - return rc; - } - // Character set aware versions for string conversion routines - bool str_to_temporal(THD *thd, MYSQL_TIME_STATUS *st, - const char *str, size_t length, - CHARSET_INFO *cs, date_mode_t fuzzydate); - bool str_to_datetime_or_date_or_time(THD *thd, MYSQL_TIME_STATUS *st, - const char *str, size_t length, - CHARSET_INFO *cs, date_mode_t mode); - bool str_to_datetime_or_date(THD *thd, MYSQL_TIME_STATUS *st, - const char *str, size_t length, - CHARSET_INFO *cs, date_mode_t mode); - - bool has_valid_mmssff() const - { - return minute <= TIME_MAX_MINUTE && - second <= TIME_MAX_SECOND && - second_part <= TIME_MAX_SECOND_PART; - } - bool has_zero_YYYYMM() const - { - return year == 0 && month == 0; - } - bool has_zero_YYYYMMDD() const - { - return year == 0 && month == 0 && day == 0; - } - bool check_date(date_conv_mode_t flags, int *warn) const - { - return ::check_date(this, flags, warn); - } - void time_hhmmssff_set_max(uint max_hour) - { - hour= max_hour; - minute= TIME_MAX_MINUTE; - second= TIME_MAX_SECOND; - second_part= TIME_MAX_SECOND_PART; - } - /* - Add nanoseconds to ssff - retval true if seconds overflowed (the caller should increment minutes) - false if no overflow happened - */ - bool add_nanoseconds_ssff(uint nanoseconds) - { - DBUG_ASSERT(nanoseconds <= 1000000000); - if (nanoseconds < 500) - return false; - second_part+= (nanoseconds + 500) / 1000; - if (second_part < 1000000) - return false; - second_part%= 1000000; - if (second < 59) - { - second++; - return false; - } - second= 0; - return true; - } - /* - Add nanoseconds to mmssff - retval true if hours overflowed (the caller should increment hours) - false if no overflow happened - */ - bool add_nanoseconds_mmssff(uint nanoseconds) - { - if (!add_nanoseconds_ssff(nanoseconds)) - return false; - if (minute < 59) - { - minute++; - return false; - } - minute= 0; - return true; - } - void time_round_or_set_max(uint dec, int *warn, ulong max_hour, ulong nsec); - bool datetime_add_nanoseconds_or_invalidate(THD *thd, int *warn, ulong nsec); - bool datetime_round_or_invalidate(THD *thd, uint dec, int *warn, ulong nsec); - bool add_nanoseconds_with_round(THD *thd, int *warn, - date_conv_mode_t mode, ulong nsec); - bool add_nanoseconds(THD *thd, int *warn, date_mode_t mode, ulong nsec) - { - date_conv_mode_t cmode= date_conv_mode_t(mode); - return time_round_mode_t(mode) == TIME_FRAC_ROUND ? - add_nanoseconds_with_round(thd, warn, cmode, nsec) : false; - } -public: - static void *operator new(size_t size, MYSQL_TIME *ltime) throw() - { - DBUG_ASSERT(size == sizeof(MYSQL_TIME)); - return ltime; - } - static void operator delete(void *ptr, MYSQL_TIME *ltime) { } - - long fraction_remainder(uint dec) const - { - return my_time_fraction_remainder(second_part, dec); - } -}; - - -/* - Use this class when you need to get a MYSQL_TIME from an Item - using Item's native timestamp type, without automatic timestamp - type conversion. -*/ -class Temporal_hybrid: public Temporal -{ -public: - class Options: public Temporal::Options - { - public: - Options(THD *thd) - :Temporal::Options(sql_mode_for_dates(thd), default_round_mode(thd)) - { } - Options(date_conv_mode_t flags, time_round_mode_t round_mode) - :Temporal::Options(flags, round_mode) - { } - explicit Options(const Temporal::Options &opt) - :Temporal::Options(opt) - { } - explicit Options(date_mode_t fuzzydate) - :Temporal::Options(fuzzydate) - { } - }; - -public: - // Contructors for Item - Temporal_hybrid(THD *thd, Item *item, date_mode_t fuzzydate); - Temporal_hybrid(THD *thd, Item *item) - :Temporal_hybrid(thd, item, Options(thd)) - { } - Temporal_hybrid(Item *item) - :Temporal_hybrid(current_thd, item) - { } - - // Constructors for non-NULL values - Temporal_hybrid(THD *thd, Warn *warn, - const char *str, size_t length, CHARSET_INFO *cs, - date_mode_t fuzzydate) - { - make_from_str(thd, warn, str, length, cs, fuzzydate); - } - Temporal_hybrid(THD *thd, Warn *warn, - const Longlong_hybrid &nr, date_mode_t fuzzydate) - { - make_from_longlong_hybrid(thd, warn, nr, fuzzydate); - } - Temporal_hybrid(THD *thd, Warn *warn, double nr, date_mode_t fuzzydate) - { - make_from_double(thd, warn, nr, fuzzydate); - } - - // Constructors for nullable values - Temporal_hybrid(THD *thd, Warn *warn, const String *str, date_mode_t mode) - { - if (!str) - time_type= MYSQL_TIMESTAMP_NONE; - else - make_from_str(thd, warn, str->ptr(), str->length(), str->charset(), mode); - } - Temporal_hybrid(THD *thd, Warn *warn, - const Longlong_hybrid_null &nr, date_mode_t fuzzydate) - { - if (nr.is_null()) - time_type= MYSQL_TIMESTAMP_NONE; - else - make_from_longlong_hybrid(thd, warn, nr, fuzzydate); - } - Temporal_hybrid(THD *thd, Warn *warn, const Double_null &nr, date_mode_t mode) - { - if (nr.is_null()) - time_type= MYSQL_TIMESTAMP_NONE; - else - make_from_double(thd, warn, nr.value(), mode); - } - Temporal_hybrid(THD *thd, Warn *warn, const my_decimal *nr, date_mode_t mode) - { - if (!nr) - time_type= MYSQL_TIMESTAMP_NONE; - else - make_from_decimal(thd, warn, nr, mode); - } - // End of constuctors - - bool copy_valid_value_to_mysql_time(MYSQL_TIME *ltime) const - { - DBUG_ASSERT(is_valid_temporal()); - *ltime= *this; - return false; - } - - longlong to_longlong() const - { - if (!is_valid_temporal()) - return 0; - ulonglong v= TIME_to_ulonglong(this); - return neg ? -(longlong) v : (longlong) v; - } - double to_double() const - { - return is_valid_temporal() ? TIME_to_double(this) : 0; - } - my_decimal *to_decimal(my_decimal *to) - { - return is_valid_temporal() ? Temporal::to_decimal(to) : bad_to_decimal(to); - } - String *to_string(String *str, uint dec) const - { - if (!is_valid_temporal()) - return NULL; - str->set_charset(&my_charset_numeric); - if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) - str->length(my_TIME_to_str(this, const_cast(str->ptr()), dec)); - return str; - } - const MYSQL_TIME *get_mysql_time() const - { - DBUG_ASSERT(is_valid_temporal()); - return this; - } -}; - - -/* - This class resembles the SQL standard , - used in extract expressions, e.g: EXTRACT(DAY FROM dt) - ::= - EXTRACT FROM - ::= | -*/ -class Extract_source: public Temporal_hybrid -{ - /* - Convert a TIME value to DAY-TIME interval, e.g. for extraction: - EXTRACT(DAY FROM x), EXTRACT(HOUR FROM x), etc. - Moves full days from ltime->hour to ltime->day. - */ - void time_to_daytime_interval() - { - DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_TIME); - DBUG_ASSERT(has_zero_YYYYMMDD()); - MYSQL_TIME::day= MYSQL_TIME::hour / 24; - MYSQL_TIME::hour%= 24; - } - bool is_valid_extract_source_slow() const - { - return is_valid_temporal() && MYSQL_TIME::hour < 24 && - (has_zero_YYYYMM() || time_type != MYSQL_TIMESTAMP_TIME); - } - bool is_valid_value_slow() const - { - return time_type == MYSQL_TIMESTAMP_NONE || is_valid_extract_source_slow(); - } -public: - Extract_source(THD *thd, Item *item, date_mode_t mode) - :Temporal_hybrid(thd, item, mode) - { - if (MYSQL_TIME::time_type == MYSQL_TIMESTAMP_TIME) - time_to_daytime_interval(); - DBUG_ASSERT(is_valid_value_slow()); - } - inline const MYSQL_TIME *get_mysql_time() const - { - DBUG_ASSERT(is_valid_extract_source_slow()); - return this; - } - bool is_valid_extract_source() const { return is_valid_temporal(); } - int sign() const { return get_mysql_time()->neg ? -1 : 1; } - uint year() const { return get_mysql_time()->year; } - uint month() const { return get_mysql_time()->month; } - int day() const { return (int) get_mysql_time()->day * sign(); } - int hour() const { return (int) get_mysql_time()->hour * sign(); } - int minute() const { return (int) get_mysql_time()->minute * sign(); } - int second() const { return (int) get_mysql_time()->second * sign(); } - int microsecond() const { return (int) get_mysql_time()->second_part * sign(); } - - uint year_month() const { return year() * 100 + month(); } - uint quarter() const { return (month() + 2)/3; } - uint week(THD *thd) const; - - longlong second_microsecond() const - { - return (second() * 1000000LL + microsecond()); - } - - // DAY TO XXX - longlong day_hour() const - { - return (longlong) day() * 100LL + hour(); - } - longlong day_minute() const - { - return day_hour() * 100LL + minute(); - } - longlong day_second() const - { - return day_minute() * 100LL + second(); - } - longlong day_microsecond() const - { - return day_second() * 1000000LL + microsecond(); - } - - // HOUR TO XXX - int hour_minute() const - { - return hour() * 100 + minute(); - } - int hour_second() const - { - return hour_minute() * 100 + second(); - } - longlong hour_microsecond() const - { - return hour_second() * 1000000LL + microsecond(); - } - - // MINUTE TO XXX - int minute_second() const - { - return minute() * 100 + second(); - } - longlong minute_microsecond() const - { - return minute_second() * 1000000LL + microsecond(); - } -}; - - -/* - This class is used for the "time_interval" argument of these SQL functions: - TIMESTAMP(tm,time_interval) - ADDTIME(tm,time_interval) - Features: - - DATE and DATETIME formats are treated as errors - - Preserves hours for TIME format as is, without limiting to TIME_MAX_HOUR -*/ -class Interval_DDhhmmssff: public Temporal -{ - static const LEX_CSTRING m_type_name; - bool str_to_DDhhmmssff(MYSQL_TIME_STATUS *status, - const char *str, size_t length, CHARSET_INFO *cs, - ulong max_hour); - void push_warning_wrong_or_truncated_value(THD *thd, - const ErrConv &str, - int warnings); - bool is_valid_interval_DDhhmmssff_slow() const - { - return time_type == MYSQL_TIMESTAMP_TIME && - has_zero_YYYYMMDD() && has_valid_mmssff(); - } - bool is_valid_value_slow() const - { - return time_type == MYSQL_TIMESTAMP_NONE || - is_valid_interval_DDhhmmssff_slow(); - } -public: - // Get fractional second precision from an Item - static uint fsp(THD *thd, Item *item); - /* - Maximum useful HOUR value: - TIMESTAMP'0001-01-01 00:00:00' + '87649415:59:59' = '9999-12-31 23:59:59' - This gives maximum possible interval values: - - '87649415:59:59.999999' (in 'hh:mm:ss.ff' format) - - '3652058 23:59:59.999999' (in 'DD hh:mm:ss.ff' format) - */ - static uint max_useful_hour() - { - return TIME_MAX_INTERVAL_HOUR; - } - static uint max_int_part_char_length() - { - // e.g. '+3652058 23:59:59' - return 1/*sign*/ + TIME_MAX_INTERVAL_DAY_CHAR_LENGTH + 1 + 8/*hh:mm:ss*/; - } - static uint max_char_length(uint fsp) - { - DBUG_ASSERT(fsp <= TIME_SECOND_PART_DIGITS); - return max_int_part_char_length() + (fsp ? 1 : 0) + fsp; - } - -public: - Interval_DDhhmmssff(THD *thd, Status *st, bool push_warnings, - Item *item, ulong max_hour, - time_round_mode_t mode, uint dec); - Interval_DDhhmmssff(THD *thd, Item *item, uint dec) - { - Status st; - new(this) Interval_DDhhmmssff(thd, &st, true, item, max_useful_hour(), - default_round_mode(thd), dec); - } - Interval_DDhhmmssff(THD *thd, Item *item) - :Interval_DDhhmmssff(thd, item, TIME_SECOND_PART_DIGITS) - { } - const MYSQL_TIME *get_mysql_time() const - { - DBUG_ASSERT(is_valid_interval_DDhhmmssff_slow()); - return this; - } - bool is_valid_interval_DDhhmmssff() const - { - return time_type == MYSQL_TIMESTAMP_TIME; - } - bool is_valid_value() const - { - return time_type == MYSQL_TIMESTAMP_NONE || is_valid_interval_DDhhmmssff(); - } - String *to_string(String *str, uint dec) const - { - if (!is_valid_interval_DDhhmmssff()) - return NULL; - str->set_charset(&my_charset_numeric); - if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) - str->length(my_interval_DDhhmmssff_to_str(this, - const_cast(str->ptr()), - dec)); - return str; - } -}; - -class Schema; - - -/** - Class Time is designed to store valid TIME values. - - 1. Valid value: - a. MYSQL_TIMESTAMP_TIME - a valid TIME within the supported TIME range - b. MYSQL_TIMESTAMP_NONE - an undefined value - - 2. Invalid value (internally only): - a. MYSQL_TIMESTAMP_TIME outside of the supported TIME range - a. MYSQL_TIMESTAMP_{DATE|DATETIME|ERROR} - - Temporarily Time is allowed to have an invalid value, but only internally, - during initialization time. All constructors and modification methods must - leave the Time value as described above (see "Valid values"). - - Time derives from MYSQL_TIME privately to make sure it is accessed - externally only in the valid state. -*/ -class Time: public Temporal -{ - static uint binary_length_to_precision(uint length); -public: - enum datetime_to_time_mode_t - { - DATETIME_TO_TIME_DISALLOW, - DATETIME_TO_TIME_YYYYMMDD_000000DD_MIX_TO_HOURS, - DATETIME_TO_TIME_YYYYMMDD_TRUNCATE, - DATETIME_TO_TIME_YYYYMMDD_00000000_ONLY, - DATETIME_TO_TIME_MINUS_CURRENT_DATE - }; - class Options: public Temporal::Options - { - datetime_to_time_mode_t m_datetime_to_time_mode; - public: - Options(THD *thd) - :Temporal::Options(default_flags_for_get_date(), default_round_mode(thd)), - m_datetime_to_time_mode(default_datetime_to_time_mode()) - { } - Options(date_conv_mode_t flags, THD *thd) - :Temporal::Options(flags, default_round_mode(thd)), - m_datetime_to_time_mode(default_datetime_to_time_mode()) - { } - Options(date_conv_mode_t flags, THD *thd, datetime_to_time_mode_t dtmode) - :Temporal::Options(flags, default_round_mode(thd)), - m_datetime_to_time_mode(dtmode) - { } - Options(date_conv_mode_t fuzzydate, time_round_mode_t round_mode, - datetime_to_time_mode_t datetime_to_time_mode) - :Temporal::Options(fuzzydate, round_mode), - m_datetime_to_time_mode(datetime_to_time_mode) - { } - - datetime_to_time_mode_t datetime_to_time_mode() const - { return m_datetime_to_time_mode; } - - static datetime_to_time_mode_t default_datetime_to_time_mode() - { - return DATETIME_TO_TIME_YYYYMMDD_000000DD_MIX_TO_HOURS; - } - }; - /* - CAST(AS TIME) historically does not mix days to hours. - This is different comparing to how implicit conversion - in Field::store_time_dec() works (e.g. on INSERT). - */ - class Options_for_cast: public Options - { - public: - Options_for_cast(THD *thd) - :Options(default_flags_for_get_date(), default_round_mode(thd), - DATETIME_TO_TIME_YYYYMMDD_TRUNCATE) - { } - Options_for_cast(date_mode_t mode, THD *thd) - :Options(default_flags_for_get_date() | (mode & TIME_FUZZY_DATES), - default_round_mode(thd), - DATETIME_TO_TIME_YYYYMMDD_TRUNCATE) - { } - }; - - class Options_for_round: public Options - { - public: - Options_for_round(time_round_mode_t round_mode= TIME_FRAC_TRUNCATE) - :Options(Time::default_flags_for_get_date(), round_mode, - Time::DATETIME_TO_TIME_DISALLOW) - { } - }; - class Options_cmp: public Options - { - public: - Options_cmp(THD *thd) - :Options(comparison_flags_for_get_date(), thd) - { } - Options_cmp(THD *thd, datetime_to_time_mode_t dtmode) - :Options(comparison_flags_for_get_date(), - default_round_mode(thd), dtmode) - { } - }; -private: - bool is_valid_value_slow() const - { - return time_type == MYSQL_TIMESTAMP_NONE || is_valid_time_slow(); - } - bool is_valid_time_slow() const - { - return time_type == MYSQL_TIMESTAMP_TIME && - has_zero_YYYYMMDD() && has_valid_mmssff(); - } - void hhmmssff_copy(const MYSQL_TIME *from) - { - hour= from->hour; - minute= from->minute; - second= from->second; - second_part= from->second_part; - } - void datetime_to_time_YYYYMMDD_000000DD_mix_to_hours(int *warn, - uint from_year, - uint from_month, - uint from_day) - { - if (from_year != 0 || from_month != 0) - *warn|= MYSQL_TIME_NOTE_TRUNCATED; - else - hour+= from_day * 24; - } - /* - The result is calculated effectively similar to: - TIMEDIFF(dt, CAST(CURRENT_DATE AS DATETIME)) - If the difference does not fit to the supported TIME range, it's truncated. - */ - void datetime_to_time_minus_current_date(THD *thd) - { - MYSQL_TIME current_date, tmp; - set_current_date(thd, ¤t_date); - calc_time_diff(this, ¤t_date, 1, &tmp, date_mode_t(0)); - static_cast(this)[0]= tmp; - int warnings= 0; - (void) check_time_range(this, TIME_SECOND_PART_DIGITS, &warnings); - DBUG_ASSERT(is_valid_time()); - } - /* - Convert a valid DATE or DATETIME to TIME. - Before this call, "this" must be a valid DATE or DATETIME value, - e.g. returned from Item::get_date(), str_to_xxx(), number_to_xxx(). - After this call, "this" is a valid TIME value. - */ - void valid_datetime_to_valid_time(THD *thd, int *warn, const Options opt) - { - DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_DATE || - time_type == MYSQL_TIMESTAMP_DATETIME); - /* - We're dealing with a DATE or DATETIME returned from - str_to_xxx(), number_to_xxx() or unpack_time(). - Do some asserts to make sure the result hour value - after mixing days to hours does not go out of the valid TIME range. - The maximum hour value after mixing days will be 31*24+23=767, - which is within the supported TIME range. - Thus no adjust_time_range_or_invalidate() is needed here. - */ - DBUG_ASSERT(day < 32); - DBUG_ASSERT(hour < 24); - if (opt.datetime_to_time_mode() == DATETIME_TO_TIME_MINUS_CURRENT_DATE) - { - datetime_to_time_minus_current_date(thd); - } - else - { - if (opt.datetime_to_time_mode() == - DATETIME_TO_TIME_YYYYMMDD_000000DD_MIX_TO_HOURS) - datetime_to_time_YYYYMMDD_000000DD_mix_to_hours(warn, year, month, day); - year= month= day= 0; - time_type= MYSQL_TIMESTAMP_TIME; - } - DBUG_ASSERT(is_valid_time_slow()); - } - /** - Convert valid DATE/DATETIME to valid TIME if needed. - This method is called after Item::get_date(), - str_to_xxx(), number_to_xxx(). - which can return only valid TIME/DATE/DATETIME values. - Before this call, "this" is: - - either a valid TIME/DATE/DATETIME value - (within the supported range for the corresponding type), - - or MYSQL_TIMESTAMP_NONE - After this call, "this" is: - - either a valid TIME (within the supported TIME range), - - or MYSQL_TIMESTAMP_NONE - */ - void valid_MYSQL_TIME_to_valid_value(THD *thd, int *warn, const Options opt) - { - switch (time_type) { - case MYSQL_TIMESTAMP_DATE: - case MYSQL_TIMESTAMP_DATETIME: - if (opt.datetime_to_time_mode() == - DATETIME_TO_TIME_YYYYMMDD_00000000_ONLY && - (year || month || day)) - make_from_out_of_range(warn); - else if (opt.datetime_to_time_mode() == DATETIME_TO_TIME_DISALLOW) - make_from_out_of_range(warn); - else - valid_datetime_to_valid_time(thd, warn, opt); - break; - case MYSQL_TIMESTAMP_NONE: - break; - case MYSQL_TIMESTAMP_ERROR: - set_zero_time(this, MYSQL_TIMESTAMP_TIME); - break; - case MYSQL_TIMESTAMP_TIME: - DBUG_ASSERT(is_valid_time_slow()); - break; - } - } - - /* - This method is called after number_to_xxx() and str_to_xxx(), - which can return DATE or DATETIME values. Convert to TIME if needed. - We trust that xxx_to_time() returns a valid TIME/DATE/DATETIME value, - so here we need to do only simple validation. - */ - void xxx_to_time_result_to_valid_value(THD *thd, int *warn, const Options opt) - { - // str_to_xxx(), number_to_xxx() never return MYSQL_TIMESTAMP_ERROR - DBUG_ASSERT(time_type != MYSQL_TIMESTAMP_ERROR); - valid_MYSQL_TIME_to_valid_value(thd, warn, opt); - } - void adjust_time_range_or_invalidate(int *warn) - { - if (check_time_range(this, TIME_SECOND_PART_DIGITS, warn)) - time_type= MYSQL_TIMESTAMP_NONE; - DBUG_ASSERT(is_valid_value_slow()); - } -public: - void round_or_set_max(uint dec, int *warn, ulong nsec); -private: - void round_or_set_max(uint dec, int *warn); - - /* - All make_from_xxx() methods initialize *warn. - The old value gets lost. - */ - void make_from_datetime_move_day_to_hour(int *warn, const MYSQL_TIME *from); - void make_from_datetime_with_days_diff(int *warn, const MYSQL_TIME *from, - long curdays); - void make_from_time(int *warn, const MYSQL_TIME *from); - void make_from_datetime(int *warn, const MYSQL_TIME *from, long curdays); - void make_from_item(THD *thd, int *warn, Item *item, const Options opt); -public: - /* - All constructors that accept an "int *warn" parameter initialize *warn. - The old value gets lost. - */ - Time(int *warn, bool neg, ulonglong hour, uint minute, const Sec6 &second); - Time() { time_type= MYSQL_TIMESTAMP_NONE; } - Time(const Native &native); - Time(THD *thd, const MYSQL_TIME *ltime, const Options opt) - { - *(static_cast(this))= *ltime; - DBUG_ASSERT(is_valid_temporal()); - int warn= 0; - valid_MYSQL_TIME_to_valid_value(thd, &warn, opt); - } - Time(Item *item) - :Time(current_thd, item) - { } - Time(THD *thd, Item *item, const Options opt) - { - int warn; - make_from_item(thd, &warn, item, opt); - } - Time(THD *thd, Item *item) - :Time(thd, item, Options(thd)) - { } - Time(int *warn, const MYSQL_TIME *from, long curdays); - Time(THD *thd, MYSQL_TIME_STATUS *status, - const char *str, size_t len, CHARSET_INFO *cs, - const Options opt) - { - if (str_to_datetime_or_date_or_time(thd, status, str, len, cs, opt)) - time_type= MYSQL_TIMESTAMP_NONE; - // The below call will optionally add notes to already collected warnings: - else - xxx_to_time_result_to_valid_value(thd, &status->warnings, opt); - } - -protected: - Time(THD *thd, int *warn, const Sec6 &nr, const Options opt) - { - if (nr.to_datetime_or_time(this, warn, TIME_INVALID_DATES)) - time_type= MYSQL_TIMESTAMP_NONE; - xxx_to_time_result_to_valid_value(thd, warn, opt); - } - Time(THD *thd, int *warn, const Sec9 &nr, const Options &opt) - :Time(thd, warn, static_cast(nr), opt) - { - if (is_valid_time() && time_round_mode_t(opt) == TIME_FRAC_ROUND) - round_or_set_max(6, warn, nr.nsec()); - } - -public: - Time(THD *thd, int *warn, const Longlong_hybrid &nr, const Options &opt) - :Time(thd, warn, Sec6(nr), opt) - { } - Time(THD *thd, int *warn, double nr, const Options &opt) - :Time(thd, warn, Sec9(nr), opt) - { } - Time(THD *thd, int *warn, const my_decimal *d, const Options &opt) - :Time(thd, warn, Sec9(d), opt) - { } - - Time(THD *thd, Item *item, const Options opt, uint dec) - :Time(thd, item, opt) - { - round(dec, time_round_mode_t(opt)); - } - Time(int *warn, const MYSQL_TIME *from, long curdays, - const Time::Options &opt, uint dec) - :Time(warn, from, curdays) - { - round(dec, time_round_mode_t(opt), warn); - } - Time(int *warn, bool neg, ulonglong hour, uint minute, const Sec9 &second, - time_round_mode_t mode, uint dec) - :Time(warn, neg, hour, minute, second) - { - DBUG_ASSERT(is_valid_time()); - if ((ulonglong) mode == (ulonglong) TIME_FRAC_ROUND) - round_or_set_max(6, warn, second.nsec()); - round(dec, mode, warn); - } - Time(THD *thd, MYSQL_TIME_STATUS *status, - const char *str, size_t len, CHARSET_INFO *cs, - const Options &opt, uint dec) - :Time(thd, status, str, len, cs, opt) - { - round(dec, time_round_mode_t(opt), &status->warnings); - } - Time(THD *thd, int *warn, const Longlong_hybrid &nr, - const Options &opt, uint dec) - :Time(thd, warn, nr, opt) - { - /* - Decimal digit truncation is needed here in case if nr was out - of the supported TIME range, so "this" was set to '838:59:59.999999'. - We always do truncation (not rounding) here, independently from "opt". - */ - trunc(dec); - } - Time(THD *thd, int *warn, double nr, const Options &opt, uint dec) - :Time(thd, warn, nr, opt) - { - round(dec, time_round_mode_t(opt), warn); - } - Time(THD *thd, int *warn, const my_decimal *d, const Options &opt, uint dec) - :Time(thd, warn, d, opt) - { - round(dec, time_round_mode_t(opt), warn); - } - - static date_conv_mode_t default_flags_for_get_date() - { return TIME_TIME_ONLY | TIME_INVALID_DATES; } - static date_conv_mode_t comparison_flags_for_get_date() - { return TIME_TIME_ONLY | TIME_INVALID_DATES | TIME_FUZZY_DATES; } - bool is_valid_time() const - { - DBUG_ASSERT(is_valid_value_slow()); - return time_type == MYSQL_TIMESTAMP_TIME; - } - const MYSQL_TIME *get_mysql_time() const - { - DBUG_ASSERT(is_valid_time_slow()); - return this; - } - bool copy_to_mysql_time(MYSQL_TIME *ltime) const - { - if (time_type == MYSQL_TIMESTAMP_NONE) - { - ltime->time_type= MYSQL_TIMESTAMP_NONE; - return true; - } - DBUG_ASSERT(is_valid_time_slow()); - *ltime= *this; - return false; - } - int cmp(const Time *other) const - { - DBUG_ASSERT(is_valid_time_slow()); - DBUG_ASSERT(other->is_valid_time_slow()); - longlong p0= to_packed(); - longlong p1= other->to_packed(); - if (p0 < p1) - return -1; - if (p0 > p1) - return 1; - return 0; - } - longlong to_seconds_abs() const - { - DBUG_ASSERT(is_valid_time_slow()); - return hour * 3600L + minute * 60 + second; - } - longlong to_seconds() const - { - return neg ? -to_seconds_abs() : to_seconds_abs(); - } - longlong to_longlong() const - { - if (!is_valid_time()) - return 0; - ulonglong v= TIME_to_ulonglong_time(this); - return neg ? -(longlong) v : (longlong) v; - } - double to_double() const - { - return !is_valid_time() ? 0 : - Temporal::to_double(neg, TIME_to_ulonglong_time(this), second_part); - } - bool to_native(Native *to, uint decimals) const; - String *to_string(String *str, uint dec) const - { - if (!is_valid_time()) - return NULL; - str->set_charset(&my_charset_numeric); - if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) - str->length(my_time_to_str(this, const_cast(str->ptr()), dec)); - return str; - } - my_decimal *to_decimal(my_decimal *to) - { - return is_valid_time() ? Temporal::to_decimal(to) : bad_to_decimal(to); - } - longlong to_packed() const - { - return is_valid_time() ? Temporal::to_packed() : 0; - } - longlong valid_time_to_packed() const - { - DBUG_ASSERT(is_valid_time_slow()); - return Temporal::to_packed(); - } - long fraction_remainder(uint dec) const - { - DBUG_ASSERT(is_valid_time()); - return Temporal::fraction_remainder(dec); - } - - Time &trunc(uint dec) - { - if (is_valid_time()) - my_time_trunc(this, dec); - DBUG_ASSERT(is_valid_value_slow()); - return *this; - } - Time &ceiling(int *warn) - { - if (is_valid_time()) - { - if (neg) - my_time_trunc(this, 0); - else if (second_part) - round_or_set_max(0, warn, 999999999); - } - DBUG_ASSERT(is_valid_value_slow()); - return *this; - } - Time &ceiling() - { - int warn= 0; - return ceiling(&warn); - } - Time &floor(int *warn) - { - if (is_valid_time()) - { - if (!neg) - my_time_trunc(this, 0); - else if (second_part) - round_or_set_max(0, warn, 999999999); - } - DBUG_ASSERT(is_valid_value_slow()); - return *this; - } - Time &floor() - { - int warn= 0; - return floor(&warn); - } - Time &round(uint dec, int *warn) - { - if (is_valid_time()) - round_or_set_max(dec, warn); - DBUG_ASSERT(is_valid_value_slow()); - return *this; - } - Time &round(uint dec, time_round_mode_t mode, int *warn) - { - switch (mode.mode()) { - case time_round_mode_t::FRAC_NONE: - DBUG_ASSERT(fraction_remainder(dec) == 0); - return trunc(dec); - case time_round_mode_t::FRAC_TRUNCATE: - return trunc(dec); - case time_round_mode_t::FRAC_ROUND: - return round(dec, warn); - } - return *this; - } - Time &round(uint dec, time_round_mode_t mode) - { - int warn= 0; - return round(dec, mode, &warn); - } - -}; - - -/** - Class Temporal_with_date is designed to store valid DATE or DATETIME values. - See also class Time. - - 1. Valid value: - a. MYSQL_TIMESTAMP_{DATE|DATETIME} - a valid DATE or DATETIME value - b. MYSQL_TIMESTAMP_NONE - an undefined value - - 2. Invalid value (internally only): - a. MYSQL_TIMESTAMP_{DATE|DATETIME} - a DATE or DATETIME value, but with - MYSQL_TIME members outside of the - valid/supported range - b. MYSQL_TIMESTAMP_TIME - a TIME value - c. MYSQL_TIMESTAMP_ERROR - error - - Temporarily is allowed to have an invalid value, but only internally, - during initialization time. All constructors and modification methods must - leave the value as described above (see "Valid value"). - - Derives from MYSQL_TIME using "protected" inheritance to make sure - it is accessed externally only in the valid state. -*/ - -class Temporal_with_date: public Temporal -{ -public: - class Options: public Temporal::Options - { - public: - Options(date_conv_mode_t fuzzydate, time_round_mode_t mode): - Temporal::Options(fuzzydate, mode) - {} - explicit Options(const Temporal::Options &opt) - :Temporal::Options(opt) - { } - explicit Options(date_mode_t mode) - :Temporal::Options(mode) - { } - }; -protected: - void check_date_or_invalidate(int *warn, date_conv_mode_t flags); - void make_from_item(THD *thd, Item *item, date_mode_t flags); - - ulong daynr() const - { - return (ulong) ::calc_daynr((uint) year, (uint) month, (uint) day); - } - int weekday(bool sunday_first_day_of_week) const - { - return ::calc_weekday(daynr(), sunday_first_day_of_week); - } - ulong dayofyear() const - { - return (ulong) (daynr() - ::calc_daynr(year, 1, 1) + 1); - } - uint quarter() const - { - return (month + 2) / 3; - } - uint week(uint week_behaviour) const - { - uint year; - return calc_week(this, week_behaviour, &year); - } - uint yearweek(uint week_behaviour) const - { - uint year; - uint week= calc_week(this, week_behaviour, &year); - return week + year * 100; - } -public: - Temporal_with_date() - { - time_type= MYSQL_TIMESTAMP_NONE; - } - Temporal_with_date(THD *thd, Item *item, date_mode_t fuzzydate) - { - make_from_item(thd, item, fuzzydate); - } - Temporal_with_date(int *warn, const Sec6 &nr, date_mode_t flags) - { - DBUG_ASSERT(bool(flags & TIME_TIME_ONLY) == false); - if (nr.to_datetime_or_date(this, warn, date_conv_mode_t(flags))) - time_type= MYSQL_TIMESTAMP_NONE; - } - Temporal_with_date(THD *thd, MYSQL_TIME_STATUS *status, - const char *str, size_t len, CHARSET_INFO *cs, - date_mode_t flags) - { - DBUG_ASSERT(bool(flags & TIME_TIME_ONLY) == false); - if (str_to_datetime_or_date(thd, status, str, len, cs, flags)) - time_type= MYSQL_TIMESTAMP_NONE; - } -public: - bool check_date_with_warn(THD *thd, date_conv_mode_t flags) - { - return ::check_date_with_warn(thd, this, flags, MYSQL_TIMESTAMP_ERROR); - } - bool check_date_with_warn(THD *thd) - { - return ::check_date_with_warn(thd, this, Temporal::sql_mode_for_dates(thd), - MYSQL_TIMESTAMP_ERROR); - } - static date_conv_mode_t comparison_flags_for_get_date() - { return TIME_INVALID_DATES | TIME_FUZZY_DATES; } -}; - - -/** - Class Date is designed to store valid DATE values. - All constructors and modification methods leave instances - of this class in one of the following valid states: - a. MYSQL_TIMESTAMP_DATE - a DATE with all MYSQL_TIME members properly set - b. MYSQL_TIMESTAMP_NONE - an undefined value. - Other MYSQL_TIMESTAMP_XXX are not possible. - MYSQL_TIMESTAMP_DATE with MYSQL_TIME members improperly set is not possible. -*/ -class Date: public Temporal_with_date -{ - bool is_valid_value_slow() const - { - return time_type == MYSQL_TIMESTAMP_NONE || is_valid_date_slow(); - } - bool is_valid_date_slow() const - { - DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_DATE); - return !check_datetime_range(this); - } -public: - class Options: public Temporal_with_date::Options - { - public: - explicit Options(date_conv_mode_t fuzzydate) - :Temporal_with_date::Options(fuzzydate, TIME_FRAC_TRUNCATE) - { } - Options(THD *thd, time_round_mode_t mode) - :Temporal_with_date::Options(sql_mode_for_dates(thd), mode) - { } - explicit Options(THD *thd) - :Temporal_with_date::Options(sql_mode_for_dates(thd), TIME_FRAC_TRUNCATE) - { } - explicit Options(date_mode_t fuzzydate) - :Temporal_with_date::Options(fuzzydate) - { } - }; -public: - Date(Item *item, date_mode_t fuzzydate) - :Date(current_thd, item, fuzzydate) - { } - Date(THD *thd, Item *item, date_mode_t fuzzydate) - :Temporal_with_date(thd, item, fuzzydate) - { - if (time_type == MYSQL_TIMESTAMP_DATETIME) - datetime_to_date(this); - DBUG_ASSERT(is_valid_value_slow()); - } - Date(THD *thd, Item *item, date_conv_mode_t fuzzydate) - :Date(thd, item, Options(fuzzydate)) - { } - Date(THD *thd, Item *item) - :Temporal_with_date(Date(thd, item, Options(thd, TIME_FRAC_TRUNCATE))) - { } - Date(Item *item) - :Temporal_with_date(Date(current_thd, item)) - { } - Date(const Temporal_with_date *d) - :Temporal_with_date(*d) - { - datetime_to_date(this); - DBUG_ASSERT(is_valid_date_slow()); - } - explicit Date(const Temporal_hybrid *from) - { - from->copy_valid_value_to_mysql_time(this); - DBUG_ASSERT(is_valid_date_slow()); - } - bool is_valid_date() const - { - DBUG_ASSERT(is_valid_value_slow()); - return time_type == MYSQL_TIMESTAMP_DATE; - } - bool check_date(date_conv_mode_t flags, int *warnings) const - { - DBUG_ASSERT(is_valid_date_slow()); - return ::check_date(this, (year || month || day), - ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), - warnings); - } - bool check_date(THD *thd, int *warnings) const - { - return check_date(Temporal::sql_mode_for_dates(thd), warnings); - } - bool check_date(date_conv_mode_t flags) const - { - int dummy; /* unused */ - return check_date(flags, &dummy); - } - bool check_date(THD *thd) const - { - int dummy; - return check_date(Temporal::sql_mode_for_dates(thd), &dummy); - } - const MYSQL_TIME *get_mysql_time() const - { - DBUG_ASSERT(is_valid_date_slow()); - return this; - } - bool copy_to_mysql_time(MYSQL_TIME *ltime) const - { - if (time_type == MYSQL_TIMESTAMP_NONE) - { - ltime->time_type= MYSQL_TIMESTAMP_NONE; - return true; - } - DBUG_ASSERT(is_valid_date_slow()); - *ltime= *this; - return false; - } - ulong daynr() const - { - DBUG_ASSERT(is_valid_date_slow()); - return Temporal_with_date::daynr(); - } - ulong dayofyear() const - { - DBUG_ASSERT(is_valid_date_slow()); - return Temporal_with_date::dayofyear(); - } - uint quarter() const - { - DBUG_ASSERT(is_valid_date_slow()); - return Temporal_with_date::quarter(); - } - uint week(uint week_behaviour) const - { - DBUG_ASSERT(is_valid_date_slow()); - return Temporal_with_date::week(week_behaviour); - } - uint yearweek(uint week_behaviour) const - { - DBUG_ASSERT(is_valid_date_slow()); - return Temporal_with_date::yearweek(week_behaviour); - } - - longlong valid_date_to_packed() const - { - DBUG_ASSERT(is_valid_date_slow()); - return Temporal::to_packed(); - } - longlong to_longlong() const - { - return is_valid_date() ? (longlong) TIME_to_ulonglong_date(this) : 0LL; - } - double to_double() const - { - return (double) to_longlong(); - } - String *to_string(String *str) const - { - if (!is_valid_date()) - return NULL; - str->set_charset(&my_charset_numeric); - if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) - str->length(my_date_to_str(this, const_cast(str->ptr()))); - return str; - } - my_decimal *to_decimal(my_decimal *to) - { - return is_valid_date() ? Temporal::to_decimal(to) : bad_to_decimal(to); - } -}; - - -/** - Class Datetime is designed to store valid DATETIME values. - All constructors and modification methods leave instances - of this class in one of the following valid states: - a. MYSQL_TIMESTAMP_DATETIME - a DATETIME with all members properly set - b. MYSQL_TIMESTAMP_NONE - an undefined value. - Other MYSQL_TIMESTAMP_XXX are not possible. - MYSQL_TIMESTAMP_DATETIME with MYSQL_TIME members - improperly set is not possible. -*/ -class Datetime: public Temporal_with_date -{ - bool is_valid_value_slow() const - { - return time_type == MYSQL_TIMESTAMP_NONE || is_valid_datetime_slow(); - } - bool is_valid_datetime_slow() const - { - DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_DATETIME); - return !check_datetime_range(this); - } - bool add_nanoseconds_or_invalidate(THD *thd, int *warn, ulong nsec) - { - DBUG_ASSERT(is_valid_datetime_slow()); - bool rc= Temporal::datetime_add_nanoseconds_or_invalidate(thd, warn, nsec); - DBUG_ASSERT(is_valid_value_slow()); - return rc; - } - void date_to_datetime_if_needed() - { - if (time_type == MYSQL_TIMESTAMP_DATE) - date_to_datetime(this); - } - void make_from_time(THD *thd, int *warn, const MYSQL_TIME *from, - date_conv_mode_t flags); - void make_from_datetime(THD *thd, int *warn, const MYSQL_TIME *from, - date_conv_mode_t flags); - bool round_or_invalidate(THD *thd, uint dec, int *warn); - bool round_or_invalidate(THD *thd, uint dec, int *warn, ulong nsec) - { - DBUG_ASSERT(is_valid_datetime_slow()); - bool rc= Temporal::datetime_round_or_invalidate(thd, dec, warn, nsec); - DBUG_ASSERT(is_valid_value_slow()); - return rc; - } -public: - - class Options: public Temporal_with_date::Options - { - public: - Options(date_conv_mode_t fuzzydate, time_round_mode_t nanosecond_rounding) - :Temporal_with_date::Options(fuzzydate, nanosecond_rounding) - { } - Options(THD *thd) - :Temporal_with_date::Options(sql_mode_for_dates(thd), default_round_mode(thd)) - { } - Options(THD *thd, time_round_mode_t rounding_mode) - :Temporal_with_date::Options(sql_mode_for_dates(thd), rounding_mode) - { } - Options(date_conv_mode_t fuzzydate, THD *thd) - :Temporal_with_date::Options(fuzzydate, default_round_mode(thd)) - { } - }; - - class Options_cmp: public Options - { - public: - Options_cmp(THD *thd) - :Options(comparison_flags_for_get_date(), thd) - { } - }; - - static Datetime zero() - { - int warn; - static Longlong_hybrid nr(0, false); - return Datetime(&warn, nr, date_mode_t(0)); - } -public: - Datetime() // NULL value - :Temporal_with_date() - { } - Datetime(THD *thd, Item *item, date_mode_t fuzzydate) - :Temporal_with_date(thd, item, fuzzydate) - { - date_to_datetime_if_needed(); - DBUG_ASSERT(is_valid_value_slow()); - } - Datetime(THD *thd, Item *item) - :Temporal_with_date(Datetime(thd, item, Options(thd))) - { } - Datetime(Item *item) - :Datetime(current_thd, item) - { } - - Datetime(THD *thd, int *warn, const MYSQL_TIME *from, date_conv_mode_t flags); - Datetime(THD *thd, MYSQL_TIME_STATUS *status, - const char *str, size_t len, CHARSET_INFO *cs, - const date_mode_t fuzzydate) - :Temporal_with_date(thd, status, str, len, cs, fuzzydate) - { - date_to_datetime_if_needed(); - DBUG_ASSERT(is_valid_value_slow()); - } - -protected: - Datetime(int *warn, const Sec6 &nr, date_mode_t flags) - :Temporal_with_date(warn, nr, flags) - { - date_to_datetime_if_needed(); - DBUG_ASSERT(is_valid_value_slow()); - } - Datetime(THD *thd, int *warn, const Sec9 &nr, date_mode_t fuzzydate) - :Datetime(warn, static_cast(nr), fuzzydate) - { - if (is_valid_datetime() && - time_round_mode_t(fuzzydate) == TIME_FRAC_ROUND) - round_or_invalidate(thd, 6, warn, nr.nsec()); - DBUG_ASSERT(is_valid_value_slow()); - } - -public: - Datetime(int *warn, const Longlong_hybrid &nr, date_mode_t mode) - :Datetime(warn, Sec6(nr), mode) - { } - Datetime(THD *thd, int *warn, double nr, date_mode_t fuzzydate) - :Datetime(thd, warn, Sec9(nr), fuzzydate) - { } - Datetime(THD *thd, int *warn, const my_decimal *d, date_mode_t fuzzydate) - :Datetime(thd, warn, Sec9(d), fuzzydate) - { } - Datetime(THD *thd, const timeval &tv); - - Datetime(THD *thd, Item *item, date_mode_t fuzzydate, uint dec) - :Datetime(thd, item, fuzzydate) - { - int warn= 0; - round(thd, dec, time_round_mode_t(fuzzydate), &warn); - } - Datetime(THD *thd, MYSQL_TIME_STATUS *status, - const char *str, size_t len, CHARSET_INFO *cs, - date_mode_t fuzzydate, uint dec) - :Datetime(thd, status, str, len, cs, fuzzydate) - { - round(thd, dec, time_round_mode_t(fuzzydate), &status->warnings); - } - Datetime(THD *thd, int *warn, double nr, date_mode_t fuzzydate, uint dec) - :Datetime(thd, warn, nr, fuzzydate) - { - round(thd, dec, time_round_mode_t(fuzzydate), warn); - } - Datetime(THD *thd, int *warn, const my_decimal *d, date_mode_t fuzzydate, uint dec) - :Datetime(thd, warn, d, fuzzydate) - { - round(thd, dec, time_round_mode_t(fuzzydate), warn); - } - Datetime(THD *thd, int *warn, const MYSQL_TIME *from, - date_mode_t fuzzydate, uint dec) - :Datetime(thd, warn, from, date_conv_mode_t(fuzzydate) & ~TIME_TIME_ONLY) - { - round(thd, dec, time_round_mode_t(fuzzydate), warn); - } - explicit Datetime(const Temporal_hybrid *from) - { - from->copy_valid_value_to_mysql_time(this); - DBUG_ASSERT(is_valid_datetime_slow()); - } - explicit Datetime(const MYSQL_TIME *from) - { - *(static_cast(this))= *from; - DBUG_ASSERT(is_valid_datetime_slow()); - } - - bool is_valid_datetime() const - { - /* - Here we quickly check for the type only. - If the type is valid, the rest of value must also be valid. - */ - DBUG_ASSERT(is_valid_value_slow()); - return time_type == MYSQL_TIMESTAMP_DATETIME; - } - bool check_date(date_conv_mode_t flags, int *warnings) const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return ::check_date(this, (year || month || day), - ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), - warnings); - } - bool check_date(date_conv_mode_t flags) const - { - int dummy; /* unused */ - return check_date(flags, &dummy); - } - bool check_date(THD *thd) const - { - return check_date(Temporal::sql_mode_for_dates(thd)); - } - bool hhmmssff_is_zero() const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return hour == 0 && minute == 0 && second == 0 && second_part == 0; - } - ulong daynr() const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return Temporal_with_date::daynr(); - } - int weekday(bool sunday_first_day_of_week) const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return Temporal_with_date::weekday(sunday_first_day_of_week); - } - ulong dayofyear() const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return Temporal_with_date::dayofyear(); - } - uint quarter() const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return Temporal_with_date::quarter(); - } - uint week(uint week_behaviour) const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return Temporal_with_date::week(week_behaviour); - } - uint yearweek(uint week_behaviour) const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return Temporal_with_date::yearweek(week_behaviour); - } - - longlong hhmmss_to_seconds_abs() const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return hour * 3600L + minute * 60 + second; - } - longlong hhmmss_to_seconds() const - { - return neg ? -hhmmss_to_seconds_abs() : hhmmss_to_seconds_abs(); - } - longlong to_seconds() const - { - return hhmmss_to_seconds() + (longlong) daynr() * 24L * 3600L; - } - - const MYSQL_TIME *get_mysql_time() const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return this; - } - bool copy_to_mysql_time(MYSQL_TIME *ltime) const - { - if (time_type == MYSQL_TIMESTAMP_NONE) - { - ltime->time_type= MYSQL_TIMESTAMP_NONE; - return true; - } - DBUG_ASSERT(is_valid_datetime_slow()); - *ltime= *this; - return false; - } - /** - Copy without data loss, with an optional DATETIME to DATE conversion. - If the value of the "type" argument is MYSQL_TIMESTAMP_DATE, - then "this" must be a datetime with a zero hhmmssff part. - */ - bool copy_to_mysql_time(MYSQL_TIME *ltime, timestamp_type type) - { - DBUG_ASSERT(type == MYSQL_TIMESTAMP_DATE || - type == MYSQL_TIMESTAMP_DATETIME); - if (copy_to_mysql_time(ltime)) - return true; - DBUG_ASSERT(type != MYSQL_TIMESTAMP_DATE || hhmmssff_is_zero()); - ltime->time_type= type; - return false; - } - longlong to_longlong() const - { - return is_valid_datetime() ? - (longlong) TIME_to_ulonglong_datetime(this) : 0LL; - } - double to_double() const - { - return !is_valid_datetime() ? 0 : - Temporal::to_double(neg, TIME_to_ulonglong_datetime(this), second_part); - } - String *to_string(String *str, uint dec) const - { - if (!is_valid_datetime()) - return NULL; - str->set_charset(&my_charset_numeric); - if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) - str->length(my_datetime_to_str(this, const_cast(str->ptr()), dec)); - return str; - } - my_decimal *to_decimal(my_decimal *to) - { - return is_valid_datetime() ? Temporal::to_decimal(to) : bad_to_decimal(to); - } - longlong to_packed() const - { - return is_valid_datetime() ? Temporal::to_packed() : 0; - } - longlong valid_datetime_to_packed() const - { - DBUG_ASSERT(is_valid_datetime_slow()); - return Temporal::to_packed(); - } - long fraction_remainder(uint dec) const - { - DBUG_ASSERT(is_valid_datetime()); - return Temporal::fraction_remainder(dec); - } - - Datetime &trunc(uint dec) - { - if (is_valid_datetime()) - my_datetime_trunc(this, dec); - DBUG_ASSERT(is_valid_value_slow()); - return *this; - } - Datetime &ceiling(THD *thd, int *warn) - { - if (is_valid_datetime() && second_part) - round_or_invalidate(thd, 0, warn, 999999999); - DBUG_ASSERT(is_valid_value_slow()); - return *this; - } - Datetime &ceiling(THD *thd) - { - int warn= 0; - return ceiling(thd, &warn); - } - Datetime &round(THD *thd, uint dec, int *warn) - { - if (is_valid_datetime()) - round_or_invalidate(thd, dec, warn); - DBUG_ASSERT(is_valid_value_slow()); - return *this; - } - Datetime &round(THD *thd, uint dec, time_round_mode_t mode, int *warn) - { - switch (mode.mode()) { - case time_round_mode_t::FRAC_NONE: - DBUG_ASSERT(fraction_remainder(dec) == 0); - return trunc(dec); - case time_round_mode_t::FRAC_TRUNCATE: - return trunc(dec); - case time_round_mode_t::FRAC_ROUND: - return round(thd, dec, warn); - } - return *this; - } - Datetime &round(THD *thd, uint dec, time_round_mode_t mode) - { - int warn= 0; - return round(thd, dec, mode, &warn); - } - -}; - - -/* - Datetime to be created from an Item who is known to be of a temporal - data type. For temporal data types we don't need nanosecond rounding - or truncation, as their precision is limited. -*/ -class Datetime_from_temporal: public Datetime -{ -public: - // The constructor DBUG_ASSERTs on a proper Item data type. - Datetime_from_temporal(THD *thd, Item *temporal, date_conv_mode_t flags); -}; - - -/* - Datetime to be created from an Item who is known not to have digits outside - of the specified scale. So it's not important which rounding method to use. - TRUNCATE should work. - Typically, Item is of a temporal data type, but this is not strictly required. -*/ -class Datetime_truncation_not_needed: public Datetime -{ -public: - Datetime_truncation_not_needed(THD *thd, Item *item, date_conv_mode_t mode); - Datetime_truncation_not_needed(THD *thd, Item *item, date_mode_t mode) - :Datetime_truncation_not_needed(thd, item, date_conv_mode_t(mode)) - { } -}; - - -class Timestamp: protected Timeval -{ - static uint binary_length_to_precision(uint length); -protected: - void round_or_set_max(uint dec, int *warn); - bool add_nanoseconds_usec(uint nanoseconds) - { - DBUG_ASSERT(nanoseconds <= 1000000000); - if (nanoseconds < 500) - return false; - tv_usec+= (nanoseconds + 500) / 1000; - if (tv_usec < 1000000) - return false; - tv_usec%= 1000000; - return true; - } -public: - static date_conv_mode_t sql_mode_for_timestamp(THD *thd); - static time_round_mode_t default_round_mode(THD *thd); - class DatetimeOptions: public date_mode_t - { - public: - DatetimeOptions(date_conv_mode_t fuzzydate, time_round_mode_t round_mode) - :date_mode_t(fuzzydate | round_mode) - { } - DatetimeOptions(THD *thd) - :DatetimeOptions(sql_mode_for_timestamp(thd), default_round_mode(thd)) - { } - }; -public: - Timestamp(my_time_t timestamp, ulong sec_part) - :Timeval(timestamp, sec_part) - { } - explicit Timestamp(const timeval &tv) - :Timeval(tv) - { } - explicit Timestamp(const Native &native); - Timestamp(THD *thd, const MYSQL_TIME *ltime, uint *error_code); - const struct timeval &tv() const { return *this; } - int cmp(const Timestamp &other) const - { - return tv_sec < other.tv_sec ? -1 : - tv_sec > other.tv_sec ? +1 : - tv_usec < other.tv_usec ? -1 : - tv_usec > other.tv_usec ? +1 : 0; - } - bool to_TIME(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) const; - bool to_native(Native *to, uint decimals) const; - Datetime to_datetime(THD *thd) const - { - return Datetime(thd, *this); - } - long fraction_remainder(uint dec) const - { - return my_time_fraction_remainder(tv_usec, dec); - } - Timestamp &trunc(uint dec) - { - my_timeval_trunc(this, dec); - return *this; - } - Timestamp &round(uint dec, int *warn) - { - round_or_set_max(dec, warn); - return *this; - } - Timestamp &round(uint dec, time_round_mode_t mode, int *warn) - { - switch (mode.mode()) { - case time_round_mode_t::FRAC_NONE: - DBUG_ASSERT(fraction_remainder(dec) == 0); - return trunc(dec); - case time_round_mode_t::FRAC_TRUNCATE: - return trunc(dec); - case time_round_mode_t::FRAC_ROUND: - return round(dec, warn); - } - return *this; - } - Timestamp &round(uint dec, time_round_mode_t mode) - { - int warn= 0; - return round(dec, mode, &warn); - } -}; - - -/** - A helper class to store MariaDB TIMESTAMP values, which can be: - - real TIMESTAMP (seconds and microseconds since epoch), or - - zero datetime '0000-00-00 00:00:00.000000' -*/ -class Timestamp_or_zero_datetime: protected Timestamp -{ - bool m_is_zero_datetime; -public: - Timestamp_or_zero_datetime() - :Timestamp(0,0), m_is_zero_datetime(true) - { } - Timestamp_or_zero_datetime(const Native &native) - :Timestamp(native.length() ? Timestamp(native) : Timestamp(0,0)), - m_is_zero_datetime(native.length() == 0) - { } - Timestamp_or_zero_datetime(const Timestamp &tm, bool is_zero_datetime) - :Timestamp(tm), m_is_zero_datetime(is_zero_datetime) - { } - Timestamp_or_zero_datetime(THD *thd, const MYSQL_TIME *ltime, uint *err_code); - Datetime to_datetime(THD *thd) const - { - if (is_zero_datetime()) - return Datetime::zero(); - return Timestamp::to_datetime(thd); - } - bool is_zero_datetime() const { return m_is_zero_datetime; } - void trunc(uint decimals) - { - if (!is_zero_datetime()) - Timestamp::trunc(decimals); - } - int cmp(const Timestamp_or_zero_datetime &other) const - { - if (is_zero_datetime()) - return other.is_zero_datetime() ? 0 : -1; - if (other.is_zero_datetime()) - return 1; - return Timestamp::cmp(other); - } - bool to_TIME(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate) const; - /* - Convert to native format: - - Real timestamps are encoded in the same way how Field_timestamp2 stores - values (big endian seconds followed by big endian microseconds) - - Zero datetime '0000-00-00 00:00:00.000000' is encoded as empty string. - Two native values are binary comparable. - */ - bool to_native(Native *to, uint decimals) const; -}; - - -/** - A helper class to store non-null MariaDB TIMESTAMP values in - the native binary encoded representation. -*/ -class Timestamp_or_zero_datetime_native: - public NativeBuffer -{ -public: - Timestamp_or_zero_datetime_native() { } - Timestamp_or_zero_datetime_native(const Timestamp_or_zero_datetime &ts, - uint decimals) - { - if (ts.to_native(this, decimals)) - length(0); // safety - } - int save_in_field(Field *field, uint decimals) const; - Datetime to_datetime(THD *thd) const - { - return is_zero_datetime() ? - Datetime::zero() : - Datetime(thd, Timestamp(*this).tv()); - } - bool is_zero_datetime() const - { - return length() == 0; - } -}; - - -/** - A helper class to store nullable MariaDB TIMESTAMP values in - the native binary encoded representation. -*/ -class Timestamp_or_zero_datetime_native_null: public Timestamp_or_zero_datetime_native, - public Null_flag -{ -public: - // With optional data type conversion - Timestamp_or_zero_datetime_native_null(THD *thd, Item *item, bool conv); - // Without data type conversion: item is known to be of the TIMESTAMP type - Timestamp_or_zero_datetime_native_null(THD *thd, Item *item) - :Timestamp_or_zero_datetime_native_null(thd, item, false) - { } - Datetime to_datetime(THD *thd) const - { - return is_null() ? Datetime() : - Timestamp_or_zero_datetime_native::to_datetime(thd); - } - void to_TIME(THD *thd, MYSQL_TIME *to) - { - DBUG_ASSERT(!is_null()); - Datetime::Options opt(TIME_CONV_NONE, TIME_FRAC_NONE); - Timestamp_or_zero_datetime(*this).to_TIME(thd, to, opt); - } - bool is_zero_datetime() const - { - DBUG_ASSERT(!is_null()); - return Timestamp_or_zero_datetime_native::is_zero_datetime(); - } -}; - - -/* - Flags for collation aggregation modes, used in TDCollation::agg(): - - MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset - MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value - (i.e. constant). - MY_COLL_ALLOW_CONV - allow any kind of conversion - (combination of the above two) - MY_COLL_ALLOW_NUMERIC_CONV - if all items were numbers, convert to - @@character_set_connection - MY_COLL_DISALLOW_NONE - don't allow return DERIVATION_NONE - (e.g. when aggregating for comparison) - MY_COLL_CMP_CONV - combination of MY_COLL_ALLOW_CONV - and MY_COLL_DISALLOW_NONE -*/ - -#define MY_COLL_ALLOW_SUPERSET_CONV 1 -#define MY_COLL_ALLOW_COERCIBLE_CONV 2 -#define MY_COLL_DISALLOW_NONE 4 -#define MY_COLL_ALLOW_NUMERIC_CONV 8 - -#define MY_COLL_ALLOW_CONV (MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV) -#define MY_COLL_CMP_CONV (MY_COLL_ALLOW_CONV | MY_COLL_DISALLOW_NONE) - - -#define MY_REPERTOIRE_NUMERIC MY_REPERTOIRE_ASCII - - -static inline my_repertoire_t operator|(const my_repertoire_t a, - const my_repertoire_t b) -{ - return (my_repertoire_t) ((uint) a | (uint) b); -} - -static inline my_repertoire_t &operator|=(my_repertoire_t &a, - const my_repertoire_t b) -{ - return a= (my_repertoire_t) ((uint) a | (uint) b); -} - - -enum Derivation -{ - DERIVATION_IGNORABLE= 6, - DERIVATION_NUMERIC= 5, - DERIVATION_COERCIBLE= 4, - DERIVATION_SYSCONST= 3, - DERIVATION_IMPLICIT= 2, - DERIVATION_NONE= 1, - DERIVATION_EXPLICIT= 0 -}; - - -/** - "Declared Type Collation" - A combination of collation and its derivation. -*/ - -class DTCollation { -public: - CHARSET_INFO *collation; - enum Derivation derivation; - my_repertoire_t repertoire; - - void set_repertoire_from_charset(CHARSET_INFO *cs) - { - repertoire= cs->state & MY_CS_PUREASCII ? - MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; - } - DTCollation() - { - collation= &my_charset_bin; - derivation= DERIVATION_NONE; - repertoire= MY_REPERTOIRE_UNICODE30; - } - DTCollation(CHARSET_INFO *collation_arg) - { - /* - This constructor version is used in combination with Field constructors, - to pass "CHARSET_INFO" instead of the full DTCollation. - Therefore, derivation is set to DERIVATION_IMPLICIT, which is the - proper derivation for table fields. - We should eventually remove all code pieces that pass "CHARSET_INFO" - (e.g. in storage engine sources) and fix to pass the full DTCollation - instead. Then, this constructor can be removed. - */ - collation= collation_arg; - derivation= DERIVATION_IMPLICIT; - repertoire= my_charset_repertoire(collation_arg); - } - DTCollation(CHARSET_INFO *collation_arg, Derivation derivation_arg) - { - collation= collation_arg; - derivation= derivation_arg; - set_repertoire_from_charset(collation_arg); - } - DTCollation(CHARSET_INFO *collation_arg, - Derivation derivation_arg, - my_repertoire_t repertoire_arg) - :collation(collation_arg), - derivation(derivation_arg), - repertoire(repertoire_arg) - { } - void set(const DTCollation &dt) - { - *this= dt; - } - void set(CHARSET_INFO *collation_arg, Derivation derivation_arg) - { - collation= collation_arg; - derivation= derivation_arg; - set_repertoire_from_charset(collation_arg); - } - void set(CHARSET_INFO *collation_arg, - Derivation derivation_arg, - my_repertoire_t repertoire_arg) - { - collation= collation_arg; - derivation= derivation_arg; - repertoire= repertoire_arg; - } - void set(CHARSET_INFO *collation_arg) - { - collation= collation_arg; - set_repertoire_from_charset(collation_arg); - } - void set(Derivation derivation_arg) - { derivation= derivation_arg; } - bool aggregate(const DTCollation &dt, uint flags= 0); - bool set(DTCollation &dt1, DTCollation &dt2, uint flags= 0) - { set(dt1); return aggregate(dt2, flags); } - const char *derivation_name() const - { - switch(derivation) - { - case DERIVATION_NUMERIC: return "NUMERIC"; - case DERIVATION_IGNORABLE: return "IGNORABLE"; - case DERIVATION_COERCIBLE: return "COERCIBLE"; - case DERIVATION_IMPLICIT: return "IMPLICIT"; - case DERIVATION_SYSCONST: return "SYSCONST"; - case DERIVATION_EXPLICIT: return "EXPLICIT"; - case DERIVATION_NONE: return "NONE"; - default: return "UNKNOWN"; - } - } - int sortcmp(const Binary_string *s, const Binary_string *t) const - { - return collation->strnncollsp(s->ptr(), s->length(), - t->ptr(), t->length()); - } -}; - - -class DTCollation_numeric: public DTCollation -{ -public: - DTCollation_numeric() - :DTCollation(charset_info(), DERIVATION_NUMERIC, MY_REPERTOIRE_NUMERIC) - { } - static const CHARSET_INFO *charset_info() { return &my_charset_numeric; } - static const DTCollation & singleton(); -}; - - -static inline uint32 -char_to_byte_length_safe(size_t char_length_arg, uint32 mbmaxlen_arg) -{ - ulonglong tmp= ((ulonglong) char_length_arg) * mbmaxlen_arg; - return tmp > UINT_MAX32 ? (uint32) UINT_MAX32 : static_cast(tmp); -} - - -class Type_numeric_attributes -{ -public: - static uint count_unsigned(Item **item, uint nitems); - static uint32 find_max_char_length(Item **item, uint nitems); - static uint32 find_max_octet_length(Item **item, uint nitems); - static int find_max_decimal_int_part(Item **item, uint nitems); - static uint find_max_decimals(Item **item, uint nitems); -public: - /* - The maximum value length in characters multiplied by collation->mbmaxlen. - Almost always it's the maximum value length in bytes. - */ - uint32 max_length; - uint decimals; - bool unsigned_flag; -public: - Type_numeric_attributes() - :max_length(0), decimals(0), unsigned_flag(false) - { } - Type_numeric_attributes(uint32 max_length_arg, uint decimals_arg, - bool unsigned_flag_arg) - :max_length(max_length_arg), - decimals(decimals_arg), - unsigned_flag(unsigned_flag_arg) - { } -protected: - void aggregate_numeric_attributes_real(Item **item, uint nitems); - void aggregate_numeric_attributes_decimal(Item **item, uint nitems, - bool unsigned_arg); -}; - - - -class Type_temporal_attributes: public Type_numeric_attributes -{ -public: - Type_temporal_attributes(uint int_part_length, uint dec, bool unsigned_arg) - :Type_numeric_attributes(int_part_length + (dec ? 1 : 0), - MY_MIN(dec, TIME_SECOND_PART_DIGITS), - unsigned_arg) - { - max_length+= decimals; - } -}; - - -class Type_temporal_attributes_not_fixed_dec: public Type_numeric_attributes -{ -public: - Type_temporal_attributes_not_fixed_dec(uint32 int_part_length, uint dec, - bool unsigned_flag) - :Type_numeric_attributes(int_part_length, dec, unsigned_flag) - { - if (decimals == NOT_FIXED_DEC) - max_length+= TIME_SECOND_PART_DIGITS + 1; - else if (decimals) - { - set_if_smaller(decimals, TIME_SECOND_PART_DIGITS); - max_length+= decimals + 1; - } - } -}; - - -/** - A class to store type attributes for the standard data types. - Does not include attributes for the extended data types - such as ENUM, SET, GEOMETRY. -*/ -class Type_std_attributes: public Type_numeric_attributes -{ -public: - DTCollation collation; - Type_std_attributes() - :collation(&my_charset_bin, DERIVATION_COERCIBLE) - { } - Type_std_attributes(const Type_numeric_attributes &nattr, - const DTCollation &dtc) - :Type_numeric_attributes(nattr), collation(dtc) - { } - void set(const Type_std_attributes *other) - { - *this= *other; - } - void set(const Type_std_attributes &other) - { - *this= other; - } - void set(const Type_numeric_attributes &nattr, const DTCollation &dtc) - { - *this= Type_std_attributes(nattr, dtc); - } - uint32 max_char_length() const - { return max_length / collation.collation->mbmaxlen; } - void fix_length_and_charset(uint32 max_char_length_arg, CHARSET_INFO *cs) - { - max_length= char_to_byte_length_safe(max_char_length_arg, cs->mbmaxlen); - collation.collation= cs; - } - void fix_char_length(uint32 max_char_length_arg) - { - max_length= char_to_byte_length_safe(max_char_length_arg, - collation.collation->mbmaxlen); - } - void fix_attributes_temporal(uint32 int_part_length, uint dec) - { - *this= Type_std_attributes( - Type_temporal_attributes(int_part_length, dec, false), - DTCollation_numeric()); - } - void fix_attributes_date() - { - fix_attributes_temporal(MAX_DATE_WIDTH, 0); - } - void fix_attributes_time(uint dec) - { - fix_attributes_temporal(MIN_TIME_WIDTH, dec); - } - void fix_attributes_datetime(uint dec) - { - fix_attributes_temporal(MAX_DATETIME_WIDTH, dec); - } - - void aggregate_attributes_int(Item **items, uint nitems) - { - collation= DTCollation_numeric(); - fix_char_length(find_max_char_length(items, nitems)); - unsigned_flag= count_unsigned(items, nitems) > 0; - decimals= 0; - } - void aggregate_attributes_real(Item **items, uint nitems) - { - collation= DTCollation_numeric(); - aggregate_numeric_attributes_real(items, nitems); - } - void aggregate_attributes_decimal(Item **items, uint nitems, - bool unsigned_arg) - { - collation= DTCollation_numeric(); - aggregate_numeric_attributes_decimal(items, nitems, - (unsigned_flag= unsigned_arg)); - } - bool aggregate_attributes_string(const char *func_name, - Item **item, uint nitems); - void aggregate_attributes_temporal(uint int_part_length, - Item **item, uint nitems) - { - fix_attributes_temporal(int_part_length, find_max_decimals(item, nitems)); - } - - bool agg_item_collations(DTCollation &c, const char *name, - Item **items, uint nitems, - uint flags, int item_sep); - bool agg_item_set_converter(const DTCollation &coll, const char *fname, - Item **args, uint nargs, - uint flags, int item_sep); - - /* - Collect arguments' character sets together. - We allow to apply automatic character set conversion in some cases. - The conditions when conversion is possible are: - - arguments A and B have different charsets - - A wins according to coercibility rules - (i.e. a column is stronger than a string constant, - an explicit COLLATE clause is stronger than a column) - - character set of A is either superset for character set of B, - or B is a string constant which can be converted into the - character set of A without data loss. - - If all of the above is true, then it's possible to convert - B into the character set of A, and then compare according - to the collation of A. - - For functions with more than two arguments: - - collect(A,B,C) ::= collect(collect(A,B),C) - - Since this function calls THD::change_item_tree() on the passed Item ** - pointers, it is necessary to pass the original Item **'s, not copies. - Otherwise their values will not be properly restored (see BUG#20769). - If the items are not consecutive (eg. args[2] and args[5]), use the - item_sep argument, ie. - - agg_item_charsets(coll, fname, &args[2], 2, flags, 3) - */ - bool agg_arg_charsets(DTCollation &c, const char *func_name, - Item **items, uint nitems, - uint flags, int item_sep) - { - if (agg_item_collations(c, func_name, items, nitems, flags, item_sep)) - return true; - return agg_item_set_converter(c, func_name, items, nitems, flags, item_sep); - } - /* - Aggregate arguments for string result, e.g: CONCAT(a,b) - - convert to @@character_set_connection if all arguments are numbers - - allow DERIVATION_NONE - */ - bool agg_arg_charsets_for_string_result(DTCollation &c, const char *func_name, - Item **items, uint nitems, - int item_sep) - { - uint flags= MY_COLL_ALLOW_SUPERSET_CONV | - MY_COLL_ALLOW_COERCIBLE_CONV | - MY_COLL_ALLOW_NUMERIC_CONV; - return agg_arg_charsets(c, func_name, items, nitems, flags, item_sep); - } - /* - Aggregate arguments for string result, when some comparison - is involved internally, e.g: REPLACE(a,b,c) - - convert to @@character_set_connection if all arguments are numbers - - disallow DERIVATION_NONE - */ - bool agg_arg_charsets_for_string_result_with_comparison(DTCollation &c, - const char *func_name, - Item **items, - uint nitems, - int item_sep) - { - uint flags= MY_COLL_ALLOW_SUPERSET_CONV | - MY_COLL_ALLOW_COERCIBLE_CONV | - MY_COLL_ALLOW_NUMERIC_CONV | - MY_COLL_DISALLOW_NONE; - return agg_arg_charsets(c, func_name, items, nitems, flags, item_sep); - } - - /* - Aggregate arguments for comparison, e.g: a=b, a LIKE b, a RLIKE b - - don't convert to @@character_set_connection if all arguments are numbers - - don't allow DERIVATION_NONE - */ - bool agg_arg_charsets_for_comparison(DTCollation &c, - const char *func_name, - Item **items, uint nitems, - int item_sep) - { - uint flags= MY_COLL_ALLOW_SUPERSET_CONV | - MY_COLL_ALLOW_COERCIBLE_CONV | - MY_COLL_DISALLOW_NONE; - return agg_arg_charsets(c, func_name, items, nitems, flags, item_sep); - } - -}; - - -class Type_all_attributes: public Type_std_attributes -{ -public: - Type_all_attributes() - :Type_std_attributes() - { } - Type_all_attributes(const Type_all_attributes &other) - :Type_std_attributes(other) - { } - virtual ~Type_all_attributes() {} - virtual void set_maybe_null(bool maybe_null_arg)= 0; - // Returns total number of decimal digits - virtual uint decimal_precision() const= 0; - virtual const TYPELIB *get_typelib() const= 0; - virtual void set_typelib(const TYPELIB *typelib)= 0; -}; - - -class Type_cmp_attributes -{ -public: - virtual ~Type_cmp_attributes() { } - virtual CHARSET_INFO *compare_collation() const= 0; -}; - - -class Type_cast_attributes -{ - CHARSET_INFO *m_charset; - ulonglong m_length; - ulonglong m_decimals; - bool m_length_specified; - bool m_decimals_specified; -public: - Type_cast_attributes(const char *c_len, const char *c_dec, CHARSET_INFO *cs) - :m_charset(cs), m_length(0), m_decimals(0), - m_length_specified(false), m_decimals_specified(false) - { - set_length_and_dec(c_len, c_dec); - } - Type_cast_attributes(CHARSET_INFO *cs) - :m_charset(cs), m_length(0), m_decimals(0), - m_length_specified(false), m_decimals_specified(false) - { } - void set_length_and_dec(const char *c_len, const char *c_dec) - { - int error; - /* - We don't have to check for error here as sql_yacc.yy has guaranteed - that the values are in range of ulonglong - */ - if ((m_length_specified= (c_len != NULL))) - m_length= (ulonglong) my_strtoll10(c_len, NULL, &error); - if ((m_decimals_specified= (c_dec != NULL))) - m_decimals= (ulonglong) my_strtoll10(c_dec, NULL, &error); - } - CHARSET_INFO *charset() const { return m_charset; } - bool length_specified() const { return m_length_specified; } - bool decimals_specified() const { return m_decimals_specified; } - ulonglong length() const { return m_length; } - ulonglong decimals() const { return m_decimals; } -}; - - -class Name: private LEX_CSTRING -{ -public: - Name(const char *str_arg, uint length_arg) - { - DBUG_ASSERT(length_arg < UINT_MAX32); - LEX_CSTRING::str= str_arg; - LEX_CSTRING::length= length_arg; - } - Name(const LEX_CSTRING &lcs) - { - LEX_CSTRING::str= lcs.str; - LEX_CSTRING::length= lcs.length; - } - const char *ptr() const { return LEX_CSTRING::str; } - uint length() const { return (uint) LEX_CSTRING::length; } - const LEX_CSTRING &lex_cstring() const { return *this; } - bool eq(const LEX_CSTRING &other) const - { - return !system_charset_info->strnncoll(LEX_CSTRING::str, LEX_CSTRING::length, - other.str, other.length); - } -}; - - -class Bit_addr -{ - /** - Byte where the bit is stored inside a record. - If the corresponding Field is a NOT NULL field, this member is NULL. - */ - uchar *m_ptr; - /** - Offset of the bit inside m_ptr[0], in the range 0..7. - */ - uchar m_offs; -public: - Bit_addr() - :m_ptr(NULL), - m_offs(0) - { } - Bit_addr(uchar *ptr, uchar offs) - :m_ptr(ptr), m_offs(offs) - { - DBUG_ASSERT(ptr || offs == 0); - DBUG_ASSERT(offs < 8); - } - Bit_addr(bool maybe_null) - :m_ptr(maybe_null ? (uchar *) "" : NULL), - m_offs(0) - { } - uchar *ptr() const { return m_ptr; } - uchar offs() const { return m_offs; } - uchar bit() const { return static_cast(m_ptr ? 1U << m_offs : 0); } - void inc() - { - DBUG_ASSERT(m_ptr); - m_ptr+= (m_offs == 7); - m_offs= (m_offs + 1) & 7; - } -}; - - -class Record_addr -{ - uchar *m_ptr; // Position of the field in the record - Bit_addr m_null; // Position and offset of the null bit -public: - Record_addr(uchar *ptr_arg, - uchar *null_ptr_arg, - uchar null_bit_arg) - :m_ptr(ptr_arg), - m_null(null_ptr_arg, null_bit_arg) - { } - Record_addr(uchar *ptr, const Bit_addr &null) - :m_ptr(ptr), - m_null(null) - { } - Record_addr(bool maybe_null) - :m_ptr(NULL), - m_null(maybe_null) - { } - uchar *ptr() const { return m_ptr; } - const Bit_addr &null() const { return m_null; } - uchar *null_ptr() const { return m_null.ptr(); } - uchar null_bit() const { return m_null.bit(); } -}; - - -class Information_schema_numeric_attributes -{ - enum enum_attr - { - ATTR_NONE= 0, - ATTR_PRECISION= 1, - ATTR_SCALE= 2, - ATTR_PRECISION_AND_SCALE= (ATTR_PRECISION|ATTR_SCALE) - }; - uint m_precision; - uint m_scale; - enum_attr m_available_attributes; -public: - Information_schema_numeric_attributes() - :m_precision(0), m_scale(0), - m_available_attributes(ATTR_NONE) - { } - Information_schema_numeric_attributes(uint precision) - :m_precision(precision), m_scale(0), - m_available_attributes(ATTR_PRECISION) - { } - Information_schema_numeric_attributes(uint precision, uint scale) - :m_precision(precision), m_scale(scale), - m_available_attributes(ATTR_PRECISION_AND_SCALE) - { } - bool has_precision() const { return m_available_attributes & ATTR_PRECISION; } - bool has_scale() const { return m_available_attributes & ATTR_SCALE; } - uint precision() const - { - DBUG_ASSERT(has_precision()); - return (uint) m_precision; - } - uint scale() const - { - DBUG_ASSERT(has_scale()); - return (uint) m_scale; - } -}; - - -class Information_schema_character_attributes -{ - uint32 m_octet_length; - uint32 m_char_length; - bool m_is_set; -public: - Information_schema_character_attributes() - :m_octet_length(0), m_char_length(0), m_is_set(false) - { } - Information_schema_character_attributes(uint32 octet_length, - uint32 char_length) - :m_octet_length(octet_length), m_char_length(char_length), m_is_set(true) - { } - bool has_octet_length() const { return m_is_set; } - bool has_char_length() const { return m_is_set; } - uint32 octet_length() const - { - DBUG_ASSERT(has_octet_length()); - return m_octet_length; - } - uint char_length() const - { - DBUG_ASSERT(has_char_length()); - return m_char_length; - } -}; - - -enum vers_kind_t -{ - VERS_UNDEFINED= 0, - VERS_TIMESTAMP, - VERS_TRX_ID -}; - - -class Vers_type_handler -{ -protected: - Vers_type_handler() {} -public: - virtual ~Vers_type_handler() {} - virtual vers_kind_t kind() const - { - DBUG_ASSERT(0); - return VERS_UNDEFINED; - } - virtual bool check_sys_fields(const LEX_CSTRING &table_name, - const Column_definition *row_start, - const Column_definition *row_end) const= 0; -}; - - -class Vers_type_timestamp: public Vers_type_handler -{ -public: - virtual vers_kind_t kind() const - { - return VERS_TIMESTAMP; - } - bool check_sys_fields(const LEX_CSTRING &table_name, - const Column_definition *row_start, - const Column_definition *row_end) const; -}; -extern Vers_type_timestamp vers_type_timestamp; - - -class Vers_type_trx: public Vers_type_handler -{ -public: - virtual vers_kind_t kind() const - { - return VERS_TRX_ID; - } - bool check_sys_fields(const LEX_CSTRING &table_name, - const Column_definition *row_start, - const Column_definition *row_end) const; -}; -extern MYSQL_PLUGIN_IMPORT Vers_type_trx vers_type_trx; - - -class Type_handler -{ - Name m_name; -protected: - String *print_item_value_csstr(THD *thd, Item *item, String *str) const; - String *print_item_value_temporal(THD *thd, Item *item, String *str, - const Name &type_name, String *buf) const; - void make_sort_key_longlong(uchar *to, - bool maybe_null, bool null_value, - bool unsigned_flag, - longlong value) const; - void store_sort_key_longlong(uchar *to, bool unsigned_flag, - longlong value) const; - - uint make_packed_sort_key_longlong(uchar *to, bool maybe_null, - bool null_value, bool unsigned_flag, - longlong value, - const SORT_FIELD_ATTR *sort_field) const; - - bool Item_func_or_sum_illegal_param(const char *name) const; - bool Item_func_or_sum_illegal_param(const Item_func_or_sum *) const; - bool check_null(const Item *item, st_value *value) const; - bool Item_send_str(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_tiny(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_short(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_long(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_longlong(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_float(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_double(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_time(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_date(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_timestamp(Item *item, Protocol *protocol, st_value *buf) const; - bool Item_send_datetime(Item *item, Protocol *protocol, st_value *buf) const; - bool Column_definition_prepare_stage2_legacy(Column_definition *c, - enum_field_types type) - const; - bool Column_definition_prepare_stage2_legacy_num(Column_definition *c, - enum_field_types type) - const; - bool Column_definition_prepare_stage2_legacy_real(Column_definition *c, - enum_field_types type) - const; -public: - static const Type_handler *handler_by_name(THD *thd, const LEX_CSTRING &name); - static const Type_handler *handler_by_name_or_error(THD *thd, - const LEX_CSTRING &name); - static const Type_handler *odbc_literal_type_handler(const LEX_CSTRING *str); - static const Type_handler *blob_type_handler(uint max_octet_length); - static const Type_handler *string_type_handler(uint max_octet_length); - static const Type_handler *bit_and_int_mixture_handler(uint max_char_len); - static const Type_handler *type_handler_long_or_longlong(uint max_char_len, - bool unsigned_flag); - /** - Return a string type handler for Item - If too_big_for_varchar() returns a BLOB variant, according to length. - If max_length > 0 create a VARCHAR(n) - If max_length == 0 create a CHAR(0) - @param item - the Item to get the handler to. - */ - static const Type_handler *varstring_type_handler(const Item *item); - static const Type_handler *blob_type_handler(const Item *item); - static const Type_handler *get_handler_by_field_type(enum_field_types type); - static const Type_handler *get_handler_by_real_type(enum_field_types type); - static const Type_handler *get_handler_by_cmp_type(Item_result type); - static const Type_collection * - type_collection_for_aggregation(const Type_handler *h1, - const Type_handler *h2); - virtual const Type_collection *type_collection() const; - static const - Type_handler *aggregate_for_result_traditional(const Type_handler *h1, - const Type_handler *h2); - virtual Schema *schema() const; - static void partition_field_type_not_allowed(const LEX_CSTRING &field_name); - static bool partition_field_check_result_type(Item *item, - Item_result expected_type); - static const Name & version_mysql56(); - static const Name & version_mariadb53(); - - void set_name(Name n) { DBUG_ASSERT(!m_name.ptr()); m_name= n; } - const Name name() const { return m_name; } - virtual const Name version() const; - virtual const Name &default_value() const= 0; - virtual uint32 flags() const { return 0; } - virtual ulong KEY_pack_flags(uint column_nr) const { return 0; } - bool is_unsigned() const { return flags() & UNSIGNED_FLAG; } - virtual enum_field_types field_type() const= 0; - virtual enum_field_types real_field_type() const { return field_type(); } - /** - Type code which is used for merging of traditional data types for result - (for UNION and for hybrid functions such as COALESCE). - Mapping can be done both ways: old->new, new->old, depending - on the particular data type implementation: - - type_handler_var_string (MySQL-4.1 old VARCHAR) is converted to - new VARCHAR before merging. - field_type_merge_rules[][] returns new VARCHAR. - - type_handler_newdate is converted to old DATE before merging. - field_type_merge_rules[][] returns NEWDATE. - - Temporal type_handler_xxx2 (new MySQL-5.6 types) are converted to - corresponding old type codes before merging (e.g. TIME2->TIME). - field_type_merge_rules[][] returns old type codes (e.g. TIME). - Then old types codes are supposed to convert to new type codes somehow, - but they do not. So UNION and COALESCE create old columns. - This is a bug and should be fixed eventually. - */ - virtual enum_field_types traditional_merge_field_type() const - { - DBUG_ASSERT(is_traditional_scalar_type()); - return field_type(); - } - virtual enum_field_types type_code_for_protocol() const - { - return field_type(); - } - virtual protocol_send_type_t protocol_send_type() const= 0; - virtual bool Item_append_extended_type_info(Send_field_extended_metadata *to, - const Item *item) const - { - return false; - } - virtual Item_result result_type() const= 0; - virtual Item_result cmp_type() const= 0; - virtual enum_dynamic_column_type - dyncol_type(const Type_all_attributes *attr) const= 0; - virtual enum_mysql_timestamp_type mysql_timestamp_type() const - { - return MYSQL_TIMESTAMP_ERROR; - } - /* - Return true if the native format is fully implemented for a data type: - - Field_xxx::val_native() - - Item_xxx::val_native() for all classes supporting this data type - - Type_handler_xxx::cmp_native() - */ - virtual bool is_val_native_ready() const - { - return false; - } - /* - If operations such as: - UPDATE t1 SET binary_string_field=this_type_field; - should store this_type_field->val_native() rather than - this_type_field->val_str(). - */ - virtual bool convert_to_binary_using_val_native() const - { - return false; - } - virtual bool is_timestamp_type() const - { - return false; - } - virtual bool is_order_clause_position_type() const - { - return false; - } - virtual bool is_limit_clause_valid_type() const - { - return false; - } - /* - Returns true if this data type supports a hack that - WHERE notnull_column IS NULL - finds zero values, e.g.: - WHERE date_notnull_column IS NULL -> - WHERE date_notnull_column = '0000-00-00' - */ - virtual bool cond_notnull_field_isnull_to_field_eq_zero() const - { - return false; - } - /** - Check whether a field type can be partially indexed by a key. - @param type field type - @retval true Type can have a prefixed key - @retval false Type can not have a prefixed key - */ - virtual bool type_can_have_key_part() const - { - return false; - } - virtual bool type_can_have_auto_increment_attribute() const - { - return false; - } - virtual uint max_octet_length() const { return 0; } - /** - Prepared statement long data: - Check whether this parameter data type is compatible with long data. - Used to detect whether a long data stream has been supplied to a - incompatible data type. - */ - virtual bool is_param_long_data_type() const { return false; } - virtual const Type_handler *type_handler_for_comparison() const= 0; - virtual const Type_handler *type_handler_for_native_format() const - { - return this; - } - virtual const Type_handler *type_handler_for_item_field() const - { - return this; - } - virtual const Type_handler *type_handler_for_tmp_table(const Item *) const - { - return this; - } - virtual const Type_handler *type_handler_for_union(const Item *) const - { - return this; - } - virtual const Type_handler *cast_to_int_type_handler() const - { - return this; - } - virtual const Type_handler *type_handler_unsigned() const - { - return this; - } - virtual const Type_handler *type_handler_signed() const - { - return this; - } - virtual bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const - { - partition_field_type_not_allowed(field_name); - return true; - } - virtual bool partition_field_append_value(String *str, - Item *item_expr, - CHARSET_INFO *field_cs, - partition_value_print_mode_t mode) - const; - virtual int - stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const= 0; - virtual CHARSET_INFO *charset_for_protocol(const Item *item) const; - virtual const Type_handler* - type_handler_adjusted_to_max_octet_length(uint max_octet_length, - CHARSET_INFO *cs) const - { return this; } - virtual bool adjust_spparam_type(Spvar_definition *def, Item *from) const - { - return false; - } - Type_handler() : m_name(0,0) {} - virtual ~Type_handler() {} - /** - Determines MariaDB traditional scalar data types that always present - in the server. - */ - bool is_traditional_scalar_type() const; - virtual bool is_scalar_type() const { return true; } - virtual bool can_return_int() const { return true; } - virtual bool can_return_decimal() const { return true; } - virtual bool can_return_real() const { return true; } - virtual bool can_return_str() const { return true; } - virtual bool can_return_text() const { return true; } - virtual bool can_return_date() const { return true; } - virtual bool can_return_time() const { return true; } - virtual bool can_return_extract_source(interval_type type) const; - virtual bool is_bool_type() const { return false; } - virtual bool is_general_purpose_string_type() const { return false; } - virtual uint Item_time_precision(THD *thd, Item *item) const; - virtual uint Item_datetime_precision(THD *thd, Item *item) const; - virtual uint Item_decimal_scale(const Item *item) const; - virtual uint Item_decimal_precision(const Item *item) const= 0; - /* - Returns how many digits a divisor adds into a division result. - See Item::divisor_precision_increment() in item.h for more comments. - */ - virtual uint Item_divisor_precision_increment(const Item *) const; - /** - Makes a temporary table Field to handle numeric aggregate functions, - e.g. SUM(DISTINCT expr), AVG(DISTINCT expr), etc. - */ - virtual Field *make_num_distinct_aggregator_field(MEM_ROOT *, - const Item *) const; - /** - Makes a temporary table Field to handle RBR replication type conversion. - @param TABLE - The conversion table the field is going to be added to. - It's used to access to table->in_use->mem_root, - to create the new field on the table memory root, - as well as to increment statistics in table->share - (e.g. table->s->blob_count). - @param metadata - Metadata from the binary log. - @param target - The field in the target table on the slave. - - Note, the data types of "target" and of "this" are not necessarily - always the same, in general case it's possible that: - this->field_type() != target->field_type() - and/or - this->real_type( ) != target->real_type() - - This method decodes metadata according to this->real_type() - and creates a new field also according to this->real_type(). - - In some cases it lurks into "target", to get some extra information, e.g.: - - unsigned_flag for numeric fields - - charset() for string fields - - typelib and field_length for SET and ENUM - - geom_type and srid for GEOMETRY - This information is not available in the binary log, so - we assume that these fields are the same on the master and on the slave. - */ - virtual Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, - uint metadata, - const Field *target) const= 0; - virtual void show_binlog_type(const Conv_source &src, const Field &dst, - String *str) const; - virtual uint32 max_display_length_for_field(const Conv_source &src) const= 0; - /* - Performs the final data type validation for a UNION element, - after the regular "aggregation for result" was done. - */ - virtual bool union_element_finalize(const Item * item) const - { - return false; - } - virtual uint Column_definition_gis_options_image(uchar *buff, - const Column_definition &def) - const - { - return 0; - } - virtual bool Column_definition_data_type_info_image(Binary_string *to, - const Column_definition &def) - const; - // Check if the implicit default value is Ok in the current sql_mode - virtual bool validate_implicit_default_value(THD *thd, - const Column_definition &def) - const; - // Automatic upgrade, e.g. for ALTER TABLE t1 FORCE - virtual void Column_definition_implicit_upgrade(Column_definition *c) const - { } - // Validate CHECK constraint after the parser - virtual bool Column_definition_validate_check_constraint(THD *thd, - Column_definition *c) - const; - // Set attributes in the parser - virtual bool Column_definition_set_attributes(THD *thd, - Column_definition *def, - const Lex_field_type_st &attr, - CHARSET_INFO *cs, - column_definition_type_t type) - const; - // Fix attributes after the parser - virtual bool Column_definition_fix_attributes(Column_definition *c) const= 0; - /* - Fix attributes from an existing field. Used for: - - ALTER TABLE (for columns that do not change) - - DECLARE var TYPE OF t1.col1; (anchored SP variables) - */ - virtual void Column_definition_reuse_fix_attributes(THD *thd, - Column_definition *c, - const Field *field) const - { } - virtual bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) const; - /* - This method is called on queries like: - CREATE TABLE t2 (a INT) AS SELECT a FROM t1; - I.e. column "a" is queried from another table, - but its data type is redefined. - @param OUT def - The column definition to be redefined - @param IN dup - The column definition to take the data type from - (i.e. "a INT" in the above example). - @param IN file - Table owner handler. If it does not support certain - data types, some conversion can be applied. - I.g. true BIT to BIT-AS-CHAR. - @param IN schema - the owner schema definition, e.g. for the default - character set and collation. - @retval true - on error - @retval false - on success - */ - virtual bool Column_definition_redefine_stage1(Column_definition *def, - const Column_definition *dup, - const handler *file, - const Schema_specification_st * - schema) - const; - virtual bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const= 0; - virtual bool Key_part_spec_init_primary(Key_part_spec *part, - const Column_definition &def, - const handler *file) const; - virtual bool Key_part_spec_init_unique(Key_part_spec *part, - const Column_definition &def, - const handler *file, - bool *has_key_needed) const; - virtual bool Key_part_spec_init_multiple(Key_part_spec *part, - const Column_definition &def, - const handler *file) const; - virtual bool Key_part_spec_init_foreign(Key_part_spec *part, - const Column_definition &def, - const handler *file) const; - virtual bool Key_part_spec_init_spatial(Key_part_spec *part, - const Column_definition &def) const; - virtual bool Key_part_spec_init_ft(Key_part_spec *part, - const Column_definition &def) const - { - return true; // Error - } - virtual Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const= 0; - Field *make_and_init_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE *table) const; - virtual Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const - { - DBUG_ASSERT(0); - return NULL; - } - virtual Field * - make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const= 0; - virtual void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const; - virtual const Type_handler *type_handler_frm_unpack(const uchar *buffer) const - { - return this; - } - virtual bool - Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, - TABLE_SHARE *share, - const uchar *buffer, - LEX_CUSTRING *gis_options) const; - - /* - Create a fixed size key part for a sort key - */ - virtual void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const= 0; - - /* - create a compact size key part for a sort key - */ - virtual uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const=0; - - virtual void sort_length(THD *thd, - const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const= 0; - virtual bool is_packable() const { return false; } - - virtual uint32 max_display_length(const Item *item) const= 0; - virtual uint32 Item_decimal_notation_int_digits(const Item *item) const { return 0; } - virtual uint32 calc_pack_length(uint32 length) const= 0; - virtual uint calc_key_length(const Column_definition &def) const; - virtual void Item_update_null_value(Item *item) const= 0; - virtual bool Item_save_in_value(THD *thd, Item *item, st_value *value) const= 0; - virtual void Item_param_setup_conversion(THD *thd, Item_param *) const {} - virtual void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const; - virtual bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const= 0; - virtual bool Item_param_val_native(THD *thd, - Item_param *item, - Native *to) const; - virtual bool Item_send(Item *item, Protocol *p, st_value *buf) const= 0; - virtual int Item_save_in_field(Item *item, Field *field, - bool no_conversions) const= 0; - - /** - Return a string representation of the Item value. - - @param thd thread handle - @param str string buffer for representation of the value - - @note - If the item has a string result type, the string is escaped - according to its character set. - - @retval - NULL on error - @retval - non-NULL a pointer to a a valid string on success - */ - virtual String *print_item_value(THD *thd, Item *item, String *str) const= 0; - - /** - Check if - WHERE expr=value AND expr=const - can be rewritten as: - WHERE const=value AND expr=const - - "this" is the comparison handler that is used by "target". - - @param target - the predicate expr=value, - whose "expr" argument will be replaced to "const". - @param target_expr - the target's "expr" which will be replaced to "const". - @param target_value - the target's second argument, it will remain unchanged. - @param source - the equality predicate expr=const (or expr<=>const) - that can be used to rewrite the "target" part - (under certain conditions, see the code). - @param source_expr - the source's "expr". It should be exactly equal to - the target's "expr" to make condition rewrite possible. - @param source_const - the source's "const" argument, it will be inserted - into "target" instead of "expr". - */ - virtual bool - can_change_cond_ref_to_const(Item_bool_func2 *target, - Item *target_expr, Item *target_value, - Item_bool_func2 *source, - Item *source_expr, Item *source_const) const= 0; - virtual bool - subquery_type_allows_materialization(const Item *inner, - const Item *outer) const= 0; - /** - Make a simple constant replacement item for a constant "src", - so the new item can futher be used for comparison with "cmp", e.g.: - src = cmp -> replacement = cmp - - "this" is the type handler that is used to compare "src" and "cmp". - - @param thd - current thread, for mem_root - @param src - The item that we want to replace. It's a const item, - but it can be complex enough to calculate on every row. - @param cmp - The src's comparand. - @retval - a pointer to the created replacement Item - @retval - NULL, if could not create a replacement (e.g. on EOM). - NULL is also returned for ROWs, because instead of replacing - a Item_row to a new Item_row, Type_handler_row just replaces - its elements. - */ - virtual Item *make_const_item_for_comparison(THD *thd, - Item *src, - const Item *cmp) const= 0; - virtual Item_cache *Item_get_cache(THD *thd, const Item *item) const= 0; - virtual Item *make_constructor_item(THD *thd, List *args) const - { - return NULL; - } - /** - A builder for literals with data type name prefix, e.g.: - TIME'00:00:00', DATE'2001-01-01', TIMESTAMP'2001-01-01 00:00:00'. - @param thd The current thread - @param str Character literal - @param length Length of str - @param cs Character set of the string - @param send_error Whether to generate an error on failure - - @retval A pointer to a new Item on success - NULL on error (wrong literal value, EOM) - */ - virtual Item_literal *create_literal_item(THD *thd, - const char *str, size_t length, - CHARSET_INFO *cs, - bool send_error) const - { - DBUG_ASSERT(0); - return NULL; - } - Item_literal *create_literal_item(THD *thd, const String *str, - bool send_error) const - { - return create_literal_item(thd, str->ptr(), str->length(), str->charset(), - send_error); - } - virtual Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const - { - return NULL; - } - virtual Item_copy *create_item_copy(THD *thd, Item *item) const; - virtual int cmp_native(const Native &a, const Native &b) const - { - DBUG_ASSERT(0); - return 0; - } - virtual bool set_comparator_func(Arg_comparator *cmp) const= 0; - virtual bool Item_const_eq(const Item_const *a, const Item_const *b, - bool binary_cmp) const - { - return false; - } - virtual bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const= 0; - virtual bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, - uint nitems) const= 0; - virtual bool Item_func_min_max_fix_attributes(THD *thd, - Item_func_min_max *func, - Item **items, - uint nitems) const; - virtual bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const= 0; - virtual bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const= 0; - virtual bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const= 0; - virtual - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const= 0; - - virtual bool Item_val_native_with_conversion(THD *thd, Item *item, - Native *to) const - { - return true; - } - virtual bool Item_val_native_with_conversion_result(THD *thd, Item *item, - Native *to) const - { - return true; - } - - virtual bool Item_val_bool(Item *item) const= 0; - virtual void Item_get_date(THD *thd, Item *item, - Temporal::Warn *buff, MYSQL_TIME *ltime, - date_mode_t fuzzydate) const= 0; - bool Item_get_date_with_warn(THD *thd, Item *item, MYSQL_TIME *ltime, - date_mode_t fuzzydate) const; - virtual longlong Item_val_int_signed_typecast(Item *item) const= 0; - virtual longlong Item_val_int_unsigned_typecast(Item *item) const= 0; - - virtual String *Item_func_hex_val_str_ascii(Item_func_hex *item, - String *str) const= 0; - - virtual - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const= 0; - virtual - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const= 0; - virtual - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const= 0; - virtual - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const= 0; - virtual - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *, - date_mode_t fuzzydate) const= 0; - bool Item_func_hybrid_field_type_get_date_with_warn(THD *thd, - Item_func_hybrid_field_type *, - MYSQL_TIME *, - date_mode_t) const; - virtual - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const= 0; - virtual - double Item_func_min_max_val_real(Item_func_min_max *) const= 0; - virtual - longlong Item_func_min_max_val_int(Item_func_min_max *) const= 0; - virtual - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, - my_decimal *) const= 0; - virtual - bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, - MYSQL_TIME *, date_mode_t fuzzydate) const= 0; - virtual bool - Item_func_between_fix_length_and_dec(Item_func_between *func) const= 0; - virtual longlong - Item_func_between_val_int(Item_func_between *func) const= 0; - - virtual cmp_item * - make_cmp_item(THD *thd, CHARSET_INFO *cs) const= 0; - - virtual in_vector * - make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const= 0; - - virtual bool - Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) - const= 0; - - virtual bool - Item_func_round_fix_length_and_dec(Item_func_round *round) const= 0; - - virtual bool - Item_func_int_val_fix_length_and_dec(Item_func_int_val *func) const= 0; - - virtual bool - Item_func_abs_fix_length_and_dec(Item_func_abs *func) const= 0; - - virtual bool - Item_func_neg_fix_length_and_dec(Item_func_neg *func) const= 0; - - virtual bool - Item_func_signed_fix_length_and_dec(Item_func_signed *item) const; - virtual bool - Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const; - virtual bool - Item_double_typecast_fix_length_and_dec(Item_double_typecast *item) const; - virtual bool - Item_float_typecast_fix_length_and_dec(Item_float_typecast *item) const; - virtual bool - Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *item) const; - virtual bool - Item_char_typecast_fix_length_and_dec(Item_char_typecast *item) const; - virtual bool - Item_time_typecast_fix_length_and_dec(Item_time_typecast *item) const; - virtual bool - Item_date_typecast_fix_length_and_dec(Item_date_typecast *item) const; - virtual bool - Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *item) const; - - virtual bool - Item_func_plus_fix_length_and_dec(Item_func_plus *func) const= 0; - virtual bool - Item_func_minus_fix_length_and_dec(Item_func_minus *func) const= 0; - virtual bool - Item_func_mul_fix_length_and_dec(Item_func_mul *func) const= 0; - virtual bool - Item_func_div_fix_length_and_dec(Item_func_div *func) const= 0; - virtual bool - Item_func_mod_fix_length_and_dec(Item_func_mod *func) const= 0; - - virtual const Vers_type_handler *vers() const { return NULL; } -}; - - -/* - Special handler for ROW -*/ -class Type_handler_row: public Type_handler -{ -public: - virtual ~Type_handler_row() {} - const Name &default_value() const override; - bool validate_implicit_default_value(THD *thd, - const Column_definition &def) const - override - { - DBUG_ASSERT(0); - return true; - } - const Type_collection *type_collection() const override; - bool is_scalar_type() const override { return false; } - bool can_return_int() const override { return false; } - bool can_return_decimal() const override { return false; } - bool can_return_real() const override { return false; } - bool can_return_str() const override { return false; } - bool can_return_text() const override { return false; } - bool can_return_date() const override { return false; } - bool can_return_time() const override { return false; } - enum_field_types field_type() const override - { - DBUG_ASSERT(0); - return MYSQL_TYPE_NULL; - }; - protocol_send_type_t protocol_send_type() const override - { - DBUG_ASSERT(0); - return PROTOCOL_SEND_STRING; - } - Item_result result_type() const override - { - return ROW_RESULT; - } - Item_result cmp_type() const override - { - return ROW_RESULT; - } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - DBUG_ASSERT(0); - return DYN_COL_NULL; - } - const Type_handler *type_handler_for_comparison() const override; - int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override - { - DBUG_ASSERT(0); - return 0; - } - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) const override - { - DBUG_ASSERT(0); - return false; - } - Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const override - { - DBUG_ASSERT(0); - return NULL; - } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, - uint metadata, - const Field *target) const override - { - DBUG_ASSERT(0); - return NULL; - } - bool Column_definition_fix_attributes(Column_definition *c) const override - { - return false; - } - void Column_definition_reuse_fix_attributes(THD *thd, - Column_definition *c, - const Field *field) - const override - { - DBUG_ASSERT(0); - } - bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Column_definition_redefine_stage1(Column_definition *def, - const Column_definition *dup, - const handler *file, - const Schema_specification_st *schema) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { - return false; - } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override - { - DBUG_ASSERT(0); - return NULL; - } - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override - { - DBUG_ASSERT(0); - } - uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override - { - DBUG_ASSERT(0); - return 0; - } - void sort_length(THD *thd, const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const override - { - DBUG_ASSERT(0); - } - uint32 max_display_length(const Item *item) const override - { - DBUG_ASSERT(0); - return 0; - } - uint32 max_display_length_for_field(const Conv_source &src) const override - { - DBUG_ASSERT(0); - return 0; - } - uint32 calc_pack_length(uint32 length) const override - { - DBUG_ASSERT(0); - return 0; - } - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override; - uint Item_decimal_precision(const Item *item) const override - { - DBUG_ASSERT(0); - return DECIMAL_MAX_PRECISION; - } - bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; - bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - DBUG_ASSERT(0); - return true; - } - void Item_update_null_value(Item *item) const override; - int Item_save_in_field(Item *item, Field *field, bool no_conversions) - const override - { - DBUG_ASSERT(0); - return 1; - } - String *print_item_value(THD *thd, Item *item, String *str) const override; - bool can_change_cond_ref_to_const(Item_bool_func2 *target, - Item *target_expr, Item *target_value, - Item_bool_func2 *source, - Item *source_expr, Item *source_const) - const override - { - DBUG_ASSERT(0); - return false; - } - Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) - const override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - Item_copy *create_item_copy(THD *thd, Item *item) const override - { - DBUG_ASSERT(0); - return NULL; - } - bool set_comparator_func(Arg_comparator *cmp) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_val_bool(Item *item) const override - { - DBUG_ASSERT(0); - return false; - } - void Item_get_date(THD *thd, Item *item, - Temporal::Warn *warn, MYSQL_TIME *ltime, - date_mode_t fuzzydate) const override - { - DBUG_ASSERT(0); - set_zero_time(ltime, MYSQL_TIMESTAMP_NONE); - } - longlong Item_val_int_signed_typecast(Item *item) const override - { - DBUG_ASSERT(0); - return 0; - } - longlong Item_val_int_unsigned_typecast(Item *item) const override - { - DBUG_ASSERT(0); - return 0; - } - String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) - const override - { - DBUG_ASSERT(0); - return NULL; - } - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override - { - DBUG_ASSERT(0); - return NULL; - } - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const override - { - DBUG_ASSERT(0); - return 0.0; - } - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const override - { - DBUG_ASSERT(0); - return 0; - } - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const override - { - DBUG_ASSERT(0); - return NULL; - } - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *ltime, - date_mode_t fuzzydate) - const override - { - DBUG_ASSERT(0); - set_zero_time(ltime, MYSQL_TIMESTAMP_NONE); - } - - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override - { - DBUG_ASSERT(0); - return NULL; - } - double Item_func_min_max_val_real(Item_func_min_max *) const override - { - DBUG_ASSERT(0); - return 0; - } - longlong Item_func_min_max_val_int(Item_func_min_max *) const override - { - DBUG_ASSERT(0); - return 0; - } - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, - my_decimal *) const override - { - DBUG_ASSERT(0); - return NULL; - } - bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, - MYSQL_TIME *, date_mode_t fuzzydate) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_func_between_fix_length_and_dec(Item_func_between *func) - const override - { - DBUG_ASSERT(0); - return true; - } - longlong Item_func_between_val_int(Item_func_between *func) const override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *thd, const Item_func_in *f, uint nargs) - const override; - bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) - const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; - bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; - bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; - - bool Item_func_signed_fix_length_and_dec(Item_func_signed *) const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *) const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_double_typecast_fix_length_and_dec(Item_double_typecast *) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_float_typecast_fix_length_and_dec(Item_float_typecast *) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_time_typecast_fix_length_and_dec(Item_time_typecast *) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_date_typecast_fix_length_and_dec(Item_date_typecast *) - const override - { - DBUG_ASSERT(0); - return true; - } - bool Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *) - const override - { - DBUG_ASSERT(0); - return true; - } - - bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; - bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; - bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; - bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; - bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; -}; - - -/* - A common parent class for numeric data type handlers -*/ -class Type_handler_numeric: public Type_handler -{ -public: - const Name &default_value() const override; - String *print_item_value(THD *thd, Item *item, String *str) const override; - double Item_func_min_max_val_real(Item_func_min_max *) const override; - longlong Item_func_min_max_val_int(Item_func_min_max *) const override; - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, - my_decimal *) const override; - bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, - MYSQL_TIME *, date_mode_t fuzzydate) - const override; - virtual ~Type_handler_numeric() { } - bool can_change_cond_ref_to_const(Item_bool_func2 *target, - Item *target_expr, Item *target_value, - Item_bool_func2 *source, - Item *source_expr, Item *source_const) - const override; - bool Item_func_between_fix_length_and_dec(Item_func_between *func) const override; - bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) const override; -}; - - -/*** Abstract classes for every XXX_RESULT */ - -class Type_handler_real_result: public Type_handler_numeric -{ -public: - Item_result result_type() const override{ return REAL_RESULT; } - Item_result cmp_type() const override { return REAL_RESULT; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - return DYN_COL_DOUBLE; - } - virtual ~Type_handler_real_result() {} - const Type_handler *type_handler_for_comparison() const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - void Column_definition_reuse_fix_attributes(THD *thd, - Column_definition *c, - const Field *field) - const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - bool - Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, - TABLE_SHARE *share, - const uchar *buffer, - LEX_CUSTRING *gis_options) - const override; - int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) - const override; - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) - const override; - void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - void sort_length(THD *thd, - const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const override; - bool Item_const_eq(const Item_const *a, const Item_const *b, - bool binary_cmp) const override; - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override; - uint Item_decimal_precision(const Item *item) const override; - bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; - bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const override; - void Item_update_null_value(Item *item) const override; - int Item_save_in_field(Item *item, Field *field, bool no_conversions) - const override; - Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) - const override; - bool set_comparator_func(Arg_comparator *cmp) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) - const override; - bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, - Item **items, uint nitems) - const override; - bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override; - bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; - bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; - bool Item_func_signed_fix_length_and_dec(Item_func_signed *item) - const override; - bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) - const override; - bool Item_val_bool(Item *item) const override; - void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, - MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; - longlong Item_val_int_signed_typecast(Item *item) const override; - longlong Item_val_int_unsigned_typecast(Item *item) const override; - String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) - const override; - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const override; - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const override; - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const override; - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *, - date_mode_t fuzzydate) - const override; - longlong Item_func_between_val_int(Item_func_between *func) const override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) - const override; - bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) - const override; - - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; - bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; - bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; - bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; - bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; - bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; - bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; - bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; -}; - - -class Type_handler_decimal_result: public Type_handler_numeric -{ -public: - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_STRING; - } - Item_result result_type() const override { return DECIMAL_RESULT; } - Item_result cmp_type() const override { return DECIMAL_RESULT; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *) const - override - { - return DYN_COL_DECIMAL; - } - virtual ~Type_handler_decimal_result() {}; - const Type_handler *type_handler_for_comparison() const override; - int stored_field_cmp_to_item(THD *, Field *field, Item *item) const override - { - VDec item_val(item); - return item_val.is_null() ? 0 : my_decimal(field).cmp(item_val.ptr()); - } - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) const override; - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) - const override; - void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - bool - Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, - TABLE_SHARE *share, - const uchar *buffer, - LEX_CUSTRING *gis_options) - const override; - void sort_length(THD *thd, - const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const override; - uint32 max_display_length(const Item *item) const override; - uint32 Item_decimal_notation_int_digits(const Item *item) const override; - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const override; - bool Item_const_eq(const Item_const *a, const Item_const *b, - bool binary_cmp) const override; - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override - { - VDec va(a), vb(b); - return va.ptr() && vb.ptr() && !va.cmp(vb); - } - uint Item_decimal_precision(const Item *item) const override; - bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; - bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_str(item, protocol, buf); - } - void Item_update_null_value(Item *item) const override; - int Item_save_in_field(Item *item, Field *field, bool no_conversions) const - override; - Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const - override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - bool set_comparator_func(Arg_comparator *cmp) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) - const override; - bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const override; - bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; - bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance*) const override; - bool Item_val_bool(Item *item) const override - { - return VDec(item).to_bool(); - } - void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, - MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; - longlong Item_val_int_signed_typecast(Item *item) const override; - longlong Item_val_int_unsigned_typecast(Item *item) const override - { - return VDec(item).to_longlong(true); - } - String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) - const override; - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override; - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const override; - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const override; - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const override; - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *, - date_mode_t fuzzydate) - const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) - const override; - longlong Item_func_between_val_int(Item_func_between *func) const override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) - const override; - bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) - const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; - bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; - bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; - bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; - bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; - bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; - bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; - bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; -}; - - -class Type_limits_int -{ -private: - uint32 m_precision; - uint32 m_char_length; -public: - Type_limits_int(uint32 prec, uint32 nchars) - :m_precision(prec), m_char_length(nchars) - { } - uint32 precision() const { return m_precision; } - uint32 char_length() const { return m_char_length; } -}; - - -/* - UNDIGNED TINYINT: 0..255 digits=3 nchars=3 - SIGNED TINYINT : -128..127 digits=3 nchars=4 -*/ -class Type_limits_uint8: public Type_limits_int -{ -public: - Type_limits_uint8() - :Type_limits_int(MAX_TINYINT_WIDTH, MAX_TINYINT_WIDTH) - { } -}; - - -class Type_limits_sint8: public Type_limits_int -{ -public: - Type_limits_sint8() - :Type_limits_int(MAX_TINYINT_WIDTH, MAX_TINYINT_WIDTH + 1) - { } -}; - - -/* - UNDIGNED SMALLINT: 0..65535 digits=5 nchars=5 - SIGNED SMALLINT: -32768..32767 digits=5 nchars=6 -*/ -class Type_limits_uint16: public Type_limits_int -{ -public: - Type_limits_uint16() - :Type_limits_int(MAX_SMALLINT_WIDTH, MAX_SMALLINT_WIDTH) - { } -}; - - -class Type_limits_sint16: public Type_limits_int -{ -public: - Type_limits_sint16() - :Type_limits_int(MAX_SMALLINT_WIDTH, MAX_SMALLINT_WIDTH + 1) - { } -}; - - -/* - MEDIUMINT UNSIGNED 0 .. 16777215 digits=8 char_length=8 - MEDIUMINT SIGNED: -8388608 .. 8388607 digits=7 char_length=8 -*/ -class Type_limits_uint24: public Type_limits_int -{ -public: - Type_limits_uint24() - :Type_limits_int(MAX_MEDIUMINT_WIDTH, MAX_MEDIUMINT_WIDTH) - { } -}; - - -class Type_limits_sint24: public Type_limits_int -{ -public: - Type_limits_sint24() - :Type_limits_int(MAX_MEDIUMINT_WIDTH - 1, MAX_MEDIUMINT_WIDTH) - { } -}; - - -/* - UNSIGNED INT: 0..4294967295 digits=10 nchars=10 - SIGNED INT: -2147483648..2147483647 digits=10 nchars=11 -*/ -class Type_limits_uint32: public Type_limits_int -{ -public: - Type_limits_uint32() - :Type_limits_int(MAX_INT_WIDTH, MAX_INT_WIDTH) - { } -}; - - - -class Type_limits_sint32: public Type_limits_int -{ -public: - Type_limits_sint32() - :Type_limits_int(MAX_INT_WIDTH, MAX_INT_WIDTH + 1) - { } -}; - - -/* - UNSIGNED BIGINT: 0..18446744073709551615 digits=20 nchars=20 - SIGNED BIGINT: -9223372036854775808..9223372036854775807 digits=19 nchars=20 -*/ -class Type_limits_uint64: public Type_limits_int -{ -public: - Type_limits_uint64(): Type_limits_int(MAX_BIGINT_WIDTH, MAX_BIGINT_WIDTH) - { } -}; - - -class Type_limits_sint64: public Type_limits_int -{ -public: - Type_limits_sint64() - :Type_limits_int(MAX_BIGINT_WIDTH - 1, MAX_BIGINT_WIDTH) - { } -}; - - - -class Type_handler_int_result: public Type_handler_numeric -{ -public: - Item_result result_type() const override { return INT_RESULT; } - Item_result cmp_type() const override { return INT_RESULT; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override - { - return attr->unsigned_flag ? DYN_COL_UINT : DYN_COL_INT; - } - bool is_order_clause_position_type() const override { return true; } - bool is_limit_clause_valid_type() const override { return true; } - virtual ~Type_handler_int_result() {} - const Type_handler *type_handler_for_comparison() const override; - int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override; - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) const override; - Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - void sort_length(THD *thd, - const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const override; - bool Item_const_eq(const Item_const *a, const Item_const *b, - bool binary_cmp) const override; - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override; - uint Item_decimal_precision(const Item *item) const override; - bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; - bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const override; - void Item_update_null_value(Item *item) const override; - int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; - Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - bool set_comparator_func(Arg_comparator *cmp) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) const override; - bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override; - bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; - bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; - bool Item_val_bool(Item *item) const override; - void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, - MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; - longlong Item_val_int_signed_typecast(Item *item) const override; - longlong Item_val_int_unsigned_typecast(Item *item) const override; - String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const override; - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override; - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const override; - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const override; - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const override; - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *, - date_mode_t fuzzydate) const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; - longlong Item_func_between_val_int(Item_func_between *func) const override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const override; - bool Item_func_in_fix_comparator_compatible_types(THD *thd, - Item_func_in *) const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; - bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; - bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; - bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; - bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; - bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; - bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; - bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; - const Vers_type_handler *vers() const override { return &vers_type_trx; } -}; - - -class Type_handler_general_purpose_int: public Type_handler_int_result -{ -public: - bool type_can_have_auto_increment_attribute() const override { return true; } - virtual const Type_limits_int *type_limits_int() const= 0; - uint32 max_display_length(const Item *item) const override - { - return type_limits_int()->char_length(); - } - uint32 Item_decimal_notation_int_digits(const Item *item) const override; - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override - { - return partition_field_check_result_type(item_expr, INT_RESULT); - } - bool partition_field_append_value(String *str, - Item *item_expr, - CHARSET_INFO *field_cs, - partition_value_print_mode_t) - const override; - const Vers_type_handler *vers() const override { return &vers_type_trx; } -}; - - -class Type_handler_temporal_result: public Type_handler -{ -protected: - uint Item_decimal_scale_with_seconds(const Item *item) const; - uint Item_divisor_precision_increment_with_seconds(const Item *) const; -public: - Item_result result_type() const override { return STRING_RESULT; } - Item_result cmp_type() const override { return TIME_RESULT; } - virtual ~Type_handler_temporal_result() {} - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - void sort_length(THD *thd, - const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const override; - bool Item_const_eq(const Item_const *a, const Item_const *b, - bool binary_cmp) const override; - bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const override; - uint32 max_display_length(const Item *item) const override; - uint32 Item_decimal_notation_int_digits(const Item *item) const override; - bool can_change_cond_ref_to_const(Item_bool_func2 *target, - Item *target_expr, Item *target_value, - Item_bool_func2 *source, - Item *source_expr, Item *source_const) - const override; - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) const override; - bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, - Item **items, uint nitems) - const override; - bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const override; - bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; - bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *)const override; - bool Item_val_bool(Item *item) const override; - void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, - MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; - longlong Item_val_int_signed_typecast(Item *item) const override; - longlong Item_val_int_unsigned_typecast(Item *item) const override; - String *Item_func_hex_val_str_ascii(Item_func_hex *, String *)const override; - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override; - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const override; - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const override; - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const override; - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *, - date_mode_t) const override; - bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, - MYSQL_TIME *, date_mode_t) const override; - bool Item_func_between_fix_length_and_dec(Item_func_between *)const override; - bool Item_func_in_fix_comparator_compatible_types(THD *, Item_func_in *) - const override; - bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; - bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; - bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; - bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; - bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; - bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; - bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; - const Vers_type_handler *vers() const override; -}; - - -class Type_handler_string_result: public Type_handler -{ - uint Item_temporal_precision(THD *thd, Item *item, bool is_time) const; -public: - const Name &default_value() const override; - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_STRING; - } - Item_result result_type() const override { return STRING_RESULT; } - Item_result cmp_type() const override { return STRING_RESULT; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *) const - override - { - return DYN_COL_STRING; - } - CHARSET_INFO *charset_for_protocol(const Item *item) const override; - virtual ~Type_handler_string_result() {} - const Type_handler *type_handler_for_comparison() const override; - int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const - override; - const Type_handler * - type_handler_adjusted_to_max_octet_length(uint max_octet_length, - CHARSET_INFO *cs) const override; - void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - void sort_length(THD *thd, - const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const override; - bool is_packable() const override { return true; } - bool union_element_finalize(const Item * item) const override; - uint calc_key_length(const Column_definition &def) const override; - bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Column_definition_redefine_stage1(Column_definition *def, - const Column_definition *dup, - const handler *file, - const Schema_specification_st *schema) - const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - uint32 max_display_length(const Item *item) const override; - /* - The next method returns 309 for long stringified doubles in scientific - notation, e.g. FORMAT('1e308', 2). - */ - uint32 Item_decimal_notation_int_digits(const Item *item) const override - { return 309; } - bool Item_const_eq(const Item_const *a, const Item_const *b, - bool binary_cmp) const override; - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override; - uint Item_time_precision(THD *thd, Item *item) const override - { - return Item_temporal_precision(thd, item, true); - } - uint Item_datetime_precision(THD *thd, Item *item) const override - { - return Item_temporal_precision(thd, item, false); - } - uint Item_decimal_precision(const Item *item) const override; - void Item_update_null_value(Item *item) const override; - bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; - void Item_param_setup_conversion(THD *thd, Item_param *) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; - bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_str(item, protocol, buf); - } - int Item_save_in_field(Item *item, Field *field, bool no_conversions) const - override; - String *print_item_value(THD *thd, Item *item, String *str) const override - { - return print_item_value_csstr(thd, item, str); - } - bool can_change_cond_ref_to_const(Item_bool_func2 *target, - Item *target_expr, Item *target_value, - Item_bool_func2 *source, - Item *source_expr, Item *source_const) const - override; - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) const override; - Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const - override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - bool set_comparator_func(Arg_comparator *cmp) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) const - override; - bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override; - bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; - bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; - bool Item_func_signed_fix_length_and_dec(Item_func_signed *item) const - override; - bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const - override; - bool Item_val_bool(Item *item) const override; - void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, - MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; - longlong Item_val_int_signed_typecast(Item *item) const override; - longlong Item_val_int_unsigned_typecast(Item *item) const override; - String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const - override; - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override; - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const override; - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const override; - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const override; - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *, - date_mode_t fuzzydate) - const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const - override; - double Item_func_min_max_val_real(Item_func_min_max *) const override; - longlong Item_func_min_max_val_int(Item_func_min_max *) const override; - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, - my_decimal *) const override; - bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, - MYSQL_TIME *, date_mode_t fuzzydate) const - override; - bool Item_func_between_fix_length_and_dec(Item_func_between *func) const - override; - longlong Item_func_between_val_int(Item_func_between *func) const override; - bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) const - override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const - override; - bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) - const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; - bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; - bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; - bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; - bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; - bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; - bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; - bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; - const Vers_type_handler *vers() const override; -}; - - -class Type_handler_general_purpose_string: public Type_handler_string_result -{ -public: - bool is_general_purpose_string_type() const override { return true; } -}; - - -/*** - Instantiable classes for every MYSQL_TYPE_XXX - - There are no Type_handler_xxx for the following types: - - MYSQL_TYPE_VAR_STRING (old VARCHAR) - mapped to MYSQL_TYPE_VARSTRING - - MYSQL_TYPE_ENUM - mapped to MYSQL_TYPE_VARSTRING - - MYSQL_TYPE_SET: - mapped to MYSQL_TYPE_VARSTRING - - because the functionality that currently uses Type_handler - (e.g. hybrid type functions) does not need to distinguish between - these types and VARCHAR. - For example: - CREATE TABLE t2 AS SELECT COALESCE(enum_column) FROM t1; - creates a VARCHAR column. - - There most likely be Type_handler_enum and Type_handler_set later, - when the Type_handler infrastructure gets used in more pieces of the code. -*/ - - -class Type_handler_tiny: public Type_handler_general_purpose_int -{ -public: - virtual ~Type_handler_tiny() {} - enum_field_types field_type() const override { return MYSQL_TYPE_TINY; } - const Type_handler *type_handler_unsigned() const override; - const Type_handler *type_handler_signed() const override; - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_TINY; - } - const Type_limits_int *type_limits_int() const override; - uint32 calc_pack_length(uint32 length) const override { return 1; } - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 4; } - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_tiny(item, protocol, buf); - } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_TINY); } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; -}; - - -class Type_handler_utiny: public Type_handler_tiny -{ -public: - uint flags() const override { return UNSIGNED_FLAG; } - const Type_limits_int *type_limits_int() const override; -}; - - -class Type_handler_short: public Type_handler_general_purpose_int -{ -public: - virtual ~Type_handler_short() {} - enum_field_types field_type() const override { return MYSQL_TYPE_SHORT; } - const Type_handler *type_handler_unsigned() const override; - const Type_handler *type_handler_signed() const override; - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_SHORT; - } - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_short(item, protocol, buf); - } - const Type_limits_int *type_limits_int() const override; - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 6; } - uint32 calc_pack_length(uint32 length) const override{ return 2; } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_SHORT); } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; -}; - - -class Type_handler_ushort: public Type_handler_short -{ -public: - uint flags() const override { return UNSIGNED_FLAG; } - const Type_limits_int *type_limits_int() const override; -}; - - -class Type_handler_long: public Type_handler_general_purpose_int -{ -public: - virtual ~Type_handler_long() {} - enum_field_types field_type() const override { return MYSQL_TYPE_LONG; } - const Type_handler *type_handler_unsigned() const override; - const Type_handler *type_handler_signed() const override; - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_LONG; - } - const Type_limits_int *type_limits_int() const override; - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 11; } - uint32 calc_pack_length(uint32 length) const override { return 4; } - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_long(item, protocol, buf); - } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_LONG); } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; -}; - - -class Type_handler_ulong: public Type_handler_long -{ -public: - uint flags() const override { return UNSIGNED_FLAG; } - const Type_limits_int *type_limits_int() const override; -}; - - -class Type_handler_bool: public Type_handler_long -{ -public: - bool is_bool_type() const override { return true; } - const Type_handler *type_handler_unsigned() const override; - const Type_handler *type_handler_signed() const override; - void Item_update_null_value(Item *item) const override; - bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const override; -}; - - -class Type_handler_longlong: public Type_handler_general_purpose_int -{ -public: - virtual ~Type_handler_longlong() {} - enum_field_types field_type() const override{ return MYSQL_TYPE_LONGLONG; } - const Type_handler *type_handler_unsigned() const override; - const Type_handler *type_handler_signed() const override; - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_LONGLONG; - } - const Type_limits_int *type_limits_int() const override; - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 20; } - uint32 calc_pack_length(uint32 length) const override { return 8; } - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_longlong(item, protocol, buf); - } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { - return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_LONGLONG); - } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; -}; - - -class Type_handler_ulonglong: public Type_handler_longlong -{ -public: - uint flags() const override { return UNSIGNED_FLAG; } - const Type_limits_int *type_limits_int() const override; -}; - - -class Type_handler_vers_trx_id: public Type_handler_ulonglong -{ -public: - virtual ~Type_handler_vers_trx_id() {} - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; -}; - - -class Type_handler_int24: public Type_handler_general_purpose_int -{ -public: - virtual ~Type_handler_int24() {} - enum_field_types field_type() const override { return MYSQL_TYPE_INT24; } - const Type_handler *type_handler_unsigned() const override; - const Type_handler *type_handler_signed() const override; - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_LONG; - } - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_long(item, protocol, buf); - } - const Type_limits_int *type_limits_int() const override; - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 9; } - uint32 calc_pack_length(uint32 length) const override { return 3; } - Field *make_conversion_table_field(MEM_ROOT *mem_root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_INT24); } - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_uint24: public Type_handler_int24 -{ -public: - uint flags() const override { return UNSIGNED_FLAG; } - const Type_limits_int *type_limits_int() const override; -}; - - -class Type_handler_year: public Type_handler_int_result -{ -public: - virtual ~Type_handler_year() {} - enum_field_types field_type() const override { return MYSQL_TYPE_YEAR; } - uint flags() const override { return UNSIGNED_FLAG; } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_SHORT; - } - uint32 max_display_length(const Item *item) const override; - uint32 Item_decimal_notation_int_digits(const Item *item) const override - { return 4; }; - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 4; } - uint32 calc_pack_length(uint32 length) const override { return 1; } - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_short(item, protocol, buf); - } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - void Column_definition_reuse_fix_attributes(THD *thd, - Column_definition *c, - const Field *field) - const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_YEAR); } - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *)const override; - void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, - MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *item, - Temporal::Warn *, - MYSQL_TIME *to, - date_mode_t fuzzydate) - const override; - const Vers_type_handler *vers() const override { return NULL; } -}; - - -class Type_handler_bit: public Type_handler_int_result -{ -public: - virtual ~Type_handler_bit() {} - enum_field_types field_type() const override { return MYSQL_TYPE_BIT; } - uint flags() const override { return UNSIGNED_FLAG; } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_STRING; - } - uint32 max_display_length(const Item *item) const override; - uint32 Item_decimal_notation_int_digits(const Item *item) const override; - static uint32 Bit_decimal_notation_int_digits_by_nbits(uint nbits); - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override { return length / 8; } - uint calc_key_length(const Column_definition &def) const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_str(item, protocol, buf); - } - String *print_item_value(THD *thd, Item *item, String *str) const override - { - return print_item_value_csstr(thd, item, str); - } - void show_binlog_type(const Conv_source &src, const Field &, String *str) - const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Column_definition_redefine_stage1(Column_definition *def, - const Column_definition *dup, - const handler *file, - const Schema_specification_st *schema) - const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_float: public Type_handler_real_result -{ -public: - virtual ~Type_handler_float() {} - enum_field_types field_type() const override { return MYSQL_TYPE_FLOAT; } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_FLOAT; - } - bool type_can_have_auto_increment_attribute() const override { return true; } - uint32 max_display_length(const Item *item) const override { return 25; } - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 12; } - uint32 Item_decimal_notation_int_digits(const Item *item) const override - { return 39; } - uint32 calc_pack_length(uint32 length) const override { return sizeof(float); } - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_float(item, protocol, buf); - } - Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) - const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_real(c, MYSQL_TYPE_FLOAT); } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; - - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) - const override; -}; - - -class Type_handler_double: public Type_handler_real_result -{ -public: - virtual ~Type_handler_double() {} - enum_field_types field_type() const override { return MYSQL_TYPE_DOUBLE; } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_DOUBLE; - } - bool type_can_have_auto_increment_attribute() const override { return true; } - uint32 max_display_length(const Item *item) const override { return 53; } - uint32 Item_decimal_notation_int_digits(const Item *item) const override - { return 309; } - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 22; } - uint32 calc_pack_length(uint32 length) const override - { - return sizeof(double); - } - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_double(item, protocol, buf); - } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_real(c, MYSQL_TYPE_DOUBLE); } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; - - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) - const override; -}; - - -class Type_handler_time_common: public Type_handler_temporal_result -{ -public: - virtual ~Type_handler_time_common() { } - const Name &default_value() const override; - enum_field_types field_type() const override { return MYSQL_TYPE_TIME; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - return DYN_COL_TIME; - } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_TIME; - } - enum_mysql_timestamp_type mysql_timestamp_type() const override - { - return MYSQL_TIMESTAMP_TIME; - } - bool is_val_native_ready() const override { return true; } - const Type_handler *type_handler_for_native_format() const override; - int cmp_native(const Native &a, const Native &b) const override; - bool Item_val_native_with_conversion(THD *thd, Item *, Native *to) - const override; - bool Item_val_native_with_conversion_result(THD *thd, Item *, Native *to) - const override; - bool Item_param_val_native(THD *thd, Item_param *item, Native *to) - const override; - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override - { - return partition_field_check_result_type(item_expr, STRING_RESULT); - } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Item_literal *create_literal_item(THD *thd, const char *str, size_t length, - CHARSET_INFO *cs, bool send_error) - const override; - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) - const override; - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override; - uint Item_decimal_scale(const Item *item) const override - { - return Item_decimal_scale_with_seconds(item); - } - uint Item_decimal_precision(const Item *item) const override; - uint Item_divisor_precision_increment(const Item *item) const override - { - return Item_divisor_precision_increment_with_seconds(item); - } - const Type_handler *type_handler_for_comparison() const override; - int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) - const override; - void Column_definition_implicit_upgrade(Column_definition *c) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool - Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, - TABLE_SHARE *share, - const uchar *buffer, - LEX_CUSTRING *gis_options) - const override; - bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_time(item, protocol, buf); - } - void Item_update_null_value(Item *item) const override; - int Item_save_in_field(Item *item, Field *field, bool no_conversions) - const override; - String *print_item_value(THD *thd, Item *item, String *str) const override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - longlong Item_val_int_unsigned_typecast(Item *item) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) - const override; - String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, - String *) const override; - double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) - const override; - longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) - const override; - my_decimal *Item_func_hybrid_field_type_val_decimal( - Item_func_hybrid_field_type *, - my_decimal *) const override; - void Item_func_hybrid_field_type_get_date(THD *, - Item_func_hybrid_field_type *, - Temporal::Warn *, - MYSQL_TIME *, - date_mode_t fuzzydate) - const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; - double Item_func_min_max_val_real(Item_func_min_max *) const override; - longlong Item_func_min_max_val_int(Item_func_min_max *) const override; - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, - my_decimal *) const override; - bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, - MYSQL_TIME *, date_mode_t fuzzydate) - const override; - longlong Item_func_between_val_int(Item_func_between *func) const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; - Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) - const override; - bool set_comparator_func(Arg_comparator *cmp) const override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) - const override; - void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) - const override; -}; - - -class Type_handler_time: public Type_handler_time_common -{ - /* number of bytes to store TIME(N) */ - static uint m_hires_bytes[MAX_DATETIME_PRECISION+1]; -public: - static uint hires_bytes(uint dec) { return m_hires_bytes[dec]; } - virtual ~Type_handler_time() {} - const Name version() const override { return version_mariadb53(); } - uint32 max_display_length_for_field(const Conv_source &src) const override - { return MIN_TIME_WIDTH; } - uint32 calc_pack_length(uint32 length) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_TIME); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_time2: public Type_handler_time_common -{ -public: - virtual ~Type_handler_time2() {} - const Name version() const override { return version_mysql56(); } - enum_field_types real_field_type() const override { return MYSQL_TYPE_TIME2; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_TIME2); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_temporal_with_date: public Type_handler_temporal_result -{ -public: - virtual ~Type_handler_temporal_with_date() {} - Item_literal *create_literal_item(THD *thd, const char *str, size_t length, - CHARSET_INFO *cs, bool send_error) - const override; - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override; - int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) - const override; - bool Item_save_in_value(THD *thd, Item *item, st_value *value) - const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_date(item, protocol, buf); - } - void Item_update_null_value(Item *item) const override; - int Item_save_in_field(Item *item, Field *field, bool no_conversions) - const override; - Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) - const override; - bool set_comparator_func(Arg_comparator *cmp) const override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) - const override; - longlong Item_func_between_val_int(Item_func_between *func) const override; -}; - - -class Type_handler_date_common: public Type_handler_temporal_with_date -{ -public: - virtual ~Type_handler_date_common() {} - const Name &default_value() const override; - const Type_handler *type_handler_for_comparison() const override; - enum_field_types field_type() const override { return MYSQL_TYPE_DATE; } - uint32 max_display_length_for_field(const Conv_source &src) const override - { return 3; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - return DYN_COL_DATE; - } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_DATE; - } - enum_mysql_timestamp_type mysql_timestamp_type() const override - { - return MYSQL_TIMESTAMP_DATE; - } - bool cond_notnull_field_isnull_to_field_eq_zero() const override - { - return true; - } - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override - { - return partition_field_check_result_type(item_expr, STRING_RESULT); - } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Item_literal *create_literal_item(THD *thd, const char *str, size_t length, - CHARSET_INFO *cs, bool send_error) - const override; - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) - const override; - bool validate_implicit_default_value(THD *thd, - const Column_definition &def) - const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - uint Item_decimal_precision(const Item *item) const override; - String *print_item_value(THD *thd, Item *item, String *str) const override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; - double Item_func_min_max_val_real(Item_func_min_max *) const override; - longlong Item_func_min_max_val_int(Item_func_min_max *) const override; - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, - my_decimal *) const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) const - override; - bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, - Item **items, uint nitems) const - override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; -}; - -class Type_handler_date: public Type_handler_date_common -{ -public: - virtual ~Type_handler_date() {} - uint32 calc_pack_length(uint32 length) const override { return 4; } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_DATE); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_newdate: public Type_handler_date_common -{ -public: - virtual ~Type_handler_newdate() {} - enum_field_types real_field_type() const override - { - return MYSQL_TYPE_NEWDATE; - } - uint32 calc_pack_length(uint32 length) const override { return 3; } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_NEWDATE); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_datetime_common: public Type_handler_temporal_with_date -{ -public: - virtual ~Type_handler_datetime_common() {} - const Name &default_value() const override; - const Type_handler *type_handler_for_comparison() const override; - enum_field_types field_type() const override - { - return MYSQL_TYPE_DATETIME; - } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - return DYN_COL_DATETIME; - } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_DATETIME; - } - enum_mysql_timestamp_type mysql_timestamp_type() const override - { - return MYSQL_TIMESTAMP_DATETIME; - } - bool cond_notnull_field_isnull_to_field_eq_zero() const override - { - return true; - } - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override - { - return partition_field_check_result_type(item_expr, STRING_RESULT); - } - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const override; - bool validate_implicit_default_value(THD *thd, const Column_definition &def) - const override; - void Column_definition_implicit_upgrade(Column_definition *c) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool - Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, - TABLE_SHARE *share, - const uchar *buffer, - LEX_CUSTRING *gis_options) - const override; - uint Item_decimal_scale(const Item *item) const override - { - return Item_decimal_scale_with_seconds(item); - } - uint Item_decimal_precision(const Item *item) const override; - uint Item_divisor_precision_increment(const Item *item) const override - { - return Item_divisor_precision_increment_with_seconds(item); - } - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_datetime(item, protocol, buf); - } - String *print_item_value(THD *thd, Item *item, String *str) const override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; - double Item_func_min_max_val_real(Item_func_min_max *) const override; - longlong Item_func_min_max_val_int(Item_func_min_max *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) - const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) - const override; - void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) - const override; -}; - - -class Type_handler_datetime: public Type_handler_datetime_common -{ - /* number of bytes to store DATETIME(N) */ - static uint m_hires_bytes[MAX_DATETIME_PRECISION + 1]; -public: - static uint hires_bytes(uint dec) { return m_hires_bytes[dec]; } - virtual ~Type_handler_datetime() {} - const Name version() const override { return version_mariadb53(); } - uint32 max_display_length_for_field(const Conv_source &src) const override - { return MAX_DATETIME_WIDTH; } - uint32 calc_pack_length(uint32 length) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_DATETIME); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_datetime2: public Type_handler_datetime_common -{ -public: - virtual ~Type_handler_datetime2() {} - const Name version() const override { return version_mysql56(); } - enum_field_types real_field_type() const override - { - return MYSQL_TYPE_DATETIME2; - } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_DATETIME2); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_timestamp_common: public Type_handler_temporal_with_date -{ -protected: - bool TIME_to_native(THD *, const MYSQL_TIME *from, Native *to, uint dec) const; -public: - virtual ~Type_handler_timestamp_common() {} - const Name &default_value() const override; - const Type_handler *type_handler_for_comparison() const override; - const Type_handler *type_handler_for_native_format() const override; - enum_field_types field_type() const override { return MYSQL_TYPE_TIMESTAMP; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - return DYN_COL_DATETIME; - } - protocol_send_type_t protocol_send_type() const override - { - return PROTOCOL_SEND_DATETIME; - } - enum_mysql_timestamp_type mysql_timestamp_type() const override - { - return MYSQL_TIMESTAMP_DATETIME; - } - bool is_val_native_ready() const override - { - return true; - } - bool is_timestamp_type() const override - { - return true; - } - void Column_definition_implicit_upgrade(Column_definition *c) const override; - bool - Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, - TABLE_SHARE *share, - const uchar *buffer, - LEX_CUSTRING *gis_options) - const override; - bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, - Item *a, Item *b) const override; - bool Item_val_native_with_conversion(THD *thd, Item *, Native *to) - const override; - bool Item_val_native_with_conversion_result(THD *thd, Item *, Native *to) - const override; - bool Item_param_val_native(THD *thd, Item_param *item, Native *to) - const override; - int cmp_native(const Native &a, const Native &b) const override; - longlong Item_func_between_val_int(Item_func_between *func) const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; - cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; - in_vector *make_in_vector(THD *thd, const Item_func_in *f, uint nargs) - const override; - void make_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - uint make_packed_sort_key_part(uchar *to, Item *item, - const SORT_FIELD_ATTR *sort_field, - Sort_param *param) const override; - void sort_length(THD *thd, - const Type_std_attributes *item, - SORT_FIELD_ATTR *attr) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - uint Item_decimal_scale(const Item *item) const override - { - return Item_decimal_scale_with_seconds(item); - } - uint Item_decimal_precision(const Item *item) const override; - uint Item_divisor_precision_increment(const Item *item) const override - { - return Item_divisor_precision_increment_with_seconds(item); - } - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override - { - return Item_send_timestamp(item, protocol, buf); - } - int Item_save_in_field(Item *item, Field *field, bool no_conversions) - const override; - String *print_item_value(THD *thd, Item *item, String *str) const override; - Item_cache *Item_get_cache(THD *thd, const Item *item) const override; - Item_copy *create_item_copy(THD *thd, Item *item) const override; - String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; - double Item_func_min_max_val_real(Item_func_min_max *) const override; - longlong Item_func_min_max_val_int(Item_func_min_max *) const override; - my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, - my_decimal *) const override; - bool set_comparator_func(Arg_comparator *cmp) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) - const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; - bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, - MYSQL_TIME *, date_mode_t fuzzydate) - const override; - bool Column_definition_set_attributes(THD *thd, - Column_definition *def, - const Lex_field_type_st &attr, - CHARSET_INFO *cs, - column_definition_type_t type) - const override; -}; - - -class Type_handler_timestamp: public Type_handler_timestamp_common -{ - /* number of bytes to store second_part part of the TIMESTAMP(N) */ - static uint m_sec_part_bytes[MAX_DATETIME_PRECISION + 1]; -public: - static uint sec_part_bytes(uint dec) { return m_sec_part_bytes[dec]; } - virtual ~Type_handler_timestamp() {} - const Name version() const override { return version_mariadb53(); } - uint32 max_display_length_for_field(const Conv_source &src) const override - { return MAX_DATETIME_WIDTH; } - uint32 calc_pack_length(uint32 length) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_TIMESTAMP); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_timestamp2: public Type_handler_timestamp_common -{ -public: - virtual ~Type_handler_timestamp2() {} - const Name version() const override { return version_mysql56(); } - enum_field_types real_field_type() const override - { - return MYSQL_TYPE_TIMESTAMP2; - } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { - return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_TIMESTAMP2); - } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_olddecimal: public Type_handler_decimal_result -{ -public: - virtual ~Type_handler_olddecimal() {} - enum_field_types field_type() const override { return MYSQL_TYPE_DECIMAL; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override { return length; } - const Type_handler *type_handler_for_tmp_table(const Item *item) const override; - const Type_handler *type_handler_for_union(const Item *item) const override; - void show_binlog_type(const Conv_source &src, const Field &, String *str) - const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_DECIMAL); } - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_newdecimal: public Type_handler_decimal_result -{ -public: - virtual ~Type_handler_newdecimal() {} - enum_field_types field_type() const override { return MYSQL_TYPE_NEWDECIMAL; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - uint calc_key_length(const Column_definition &def) const override; - void show_binlog_type(const Conv_source &src, const Field &, String *str) - const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Column_definition_redefine_stage1(Column_definition *def, - const Column_definition *dup, - const handler *file, - const Schema_specification_st *schema) - const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_null: public Type_handler_general_purpose_string -{ -public: - virtual ~Type_handler_null() {} - enum_field_types field_type() const override { return MYSQL_TYPE_NULL; } - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - return DYN_COL_NULL; - } - const Type_handler *type_handler_for_comparison() const override; - const Type_handler *type_handler_for_tmp_table(const Item *item) const override; - const Type_handler *type_handler_for_union(const Item *) const override; - uint32 max_display_length(const Item *item) const override { return 0; } - uint32 max_display_length_for_field(const Conv_source &src) const override - { - return 0; - } - uint32 calc_pack_length(uint32 length) const override { return 0; } - bool Item_const_eq(const Item_const *a, const Item_const *b, - bool binary_cmp) const override; - bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; - bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Column_definition_redefine_stage1(Column_definition *def, - const Column_definition *dup, - const handler *file, - const Schema_specification_st *schema) - const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_NULL); } - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -class Type_handler_longstr: public Type_handler_general_purpose_string -{ -public: - bool type_can_have_key_part() const override - { - return true; - } -}; - - -class Type_handler_string: public Type_handler_longstr -{ -public: - virtual ~Type_handler_string() {} - enum_field_types field_type() const override { return MYSQL_TYPE_STRING; } - ulong KEY_pack_flags(uint column_nr) const override - { - return HA_PACK_KEY; - } - bool is_param_long_data_type() const override { return true; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override { return length; } - const Type_handler *type_handler_for_tmp_table(const Item *item) const override - { - return varstring_type_handler(item); - } - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override - { - return partition_field_check_result_type(item_expr, STRING_RESULT); - } - void show_binlog_type(const Conv_source &src, const Field &dst, String *str) - const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_set_attributes(THD *thd, - Column_definition *def, - const Lex_field_type_st &attr, - CHARSET_INFO *cs, - column_definition_type_t type) - const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Key_part_spec_init_ft(Key_part_spec *part, - const Column_definition &def) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -/* Old varchar */ -class Type_handler_var_string: public Type_handler_string -{ -public: - virtual ~Type_handler_var_string() {} - enum_field_types field_type() const override { return MYSQL_TYPE_VAR_STRING; } - enum_field_types real_field_type() const override { return MYSQL_TYPE_STRING; } - enum_field_types traditional_merge_field_type() const override - { - return MYSQL_TYPE_VARCHAR; - } - const Type_handler *type_handler_for_tmp_table(const Item *item) const override - { - return varstring_type_handler(item); - } - uint32 max_display_length_for_field(const Conv_source &src) const override; - void show_binlog_type(const Conv_source &src, const Field &dst, String *str) - const override; - void Column_definition_implicit_upgrade(Column_definition *c) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override - { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_STRING); } - const Type_handler *type_handler_for_union(const Item *item) const override - { - return varstring_type_handler(item); - } -}; - - -class Type_handler_varchar: public Type_handler_longstr -{ -public: - virtual ~Type_handler_varchar() {} - enum_field_types field_type() const override { return MYSQL_TYPE_VARCHAR; } - ulong KEY_pack_flags(uint column_nr) const override - { - if (column_nr == 0) - return HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY; - return HA_PACK_KEY; - } - enum_field_types type_code_for_protocol() const override - { - return MYSQL_TYPE_VAR_STRING; // Keep things compatible for old clients - } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override - { - return (length + (length < 256 ? 1: 2)); - } - const Type_handler *type_handler_for_tmp_table(const Item *item) const override - { - return varstring_type_handler(item); - } - const Type_handler *type_handler_for_union(const Item *item) const override - { - return varstring_type_handler(item); - } - bool is_param_long_data_type() const override { return true; } - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override - { - return partition_field_check_result_type(item_expr, STRING_RESULT); - } - void show_binlog_type(const Conv_source &src, const Field &dst, String *str) - const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - bool Column_definition_set_attributes(THD *thd, - Column_definition *def, - const Lex_field_type_st &attr, - CHARSET_INFO *cs, - column_definition_type_t type) - const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Key_part_spec_init_ft(Key_part_spec *part, - const Column_definition &def) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - bool adjust_spparam_type(Spvar_definition *def, Item *from) const override; -}; - - -class Type_handler_hex_hybrid: public Type_handler_varchar -{ -public: - virtual ~Type_handler_hex_hybrid() {} - const Type_handler *cast_to_int_type_handler() const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; -}; - - -class Type_handler_varchar_compressed: public Type_handler_varchar -{ -public: - enum_field_types real_field_type() const override - { - return MYSQL_TYPE_VARCHAR_COMPRESSED; - } - ulong KEY_pack_flags(uint column_nr) const override - { - DBUG_ASSERT(0); - return 0; - } - uint32 max_display_length_for_field(const Conv_source &src) const override; - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override - { - partition_field_type_not_allowed(field_name); - return true; - } - void show_binlog_type(const Conv_source &src, const Field &dst, String *str) - const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - DBUG_ASSERT(0); - return DYN_COL_STRING; - } -}; - - -class Type_handler_blob_common: public Type_handler_longstr -{ -public: - virtual ~Type_handler_blob_common() { } - virtual uint length_bytes() const= 0; - ulong KEY_pack_flags(uint column_nr) const override - { - if (column_nr == 0) - return HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY; - return HA_PACK_KEY; - } - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - const Type_handler *type_handler_for_tmp_table(const Item *item) const - override - { - return blob_type_handler(item); - } - const Type_handler *type_handler_for_union(const Item *item) const override - { - return blob_type_handler(item); - } - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) const override - { - return false; // Materialization does not work with BLOB columns - } - bool is_param_long_data_type() const override { return true; } - uint calc_key_length(const Column_definition &def) const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - bool Key_part_spec_init_ft(Key_part_spec *part, - const Column_definition &def) const override; - bool Key_part_spec_init_primary(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Key_part_spec_init_unique(Key_part_spec *part, - const Column_definition &def, - const handler *file, - bool *has_key_needed) const override; - bool Key_part_spec_init_multiple(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Key_part_spec_init_foreign(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) const - override; - void Item_param_setup_conversion(THD *thd, Item_param *) const override; - - bool partition_field_check(const LEX_CSTRING &field_name, - Item *item_expr) const override; - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - const Vers_type_handler *vers() const override; -}; - - -class Type_handler_tiny_blob: public Type_handler_blob_common -{ -public: - virtual ~Type_handler_tiny_blob() {} - uint length_bytes() const override { return 1; } - enum_field_types field_type() const override { return MYSQL_TYPE_TINY_BLOB; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - uint max_octet_length() const override { return UINT_MAX8; } -}; - - -class Type_handler_medium_blob: public Type_handler_blob_common -{ -public: - virtual ~Type_handler_medium_blob() {} - uint length_bytes() const override { return 3; } - enum_field_types field_type() const override { return MYSQL_TYPE_MEDIUM_BLOB; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - uint max_octet_length() const override { return UINT_MAX24; } -}; - - -class Type_handler_long_blob: public Type_handler_blob_common -{ -public: - virtual ~Type_handler_long_blob() {} - uint length_bytes() const override { return 4; } - enum_field_types field_type() const override { return MYSQL_TYPE_LONG_BLOB; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - uint max_octet_length() const override { return UINT_MAX32; } -}; - - -class Type_handler_blob: public Type_handler_blob_common -{ -public: - virtual ~Type_handler_blob() {} - uint length_bytes() const override { return 2; } - enum_field_types field_type() const override { return MYSQL_TYPE_BLOB; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - uint max_octet_length() const override { return UINT_MAX16; } -}; - - -class Type_handler_blob_compressed: public Type_handler_blob -{ -public: - enum_field_types real_field_type() const override - { - return MYSQL_TYPE_BLOB_COMPRESSED; - } - ulong KEY_pack_flags(uint column_nr) const override - { - DBUG_ASSERT(0); - return 0; - } - uint32 max_display_length_for_field(const Conv_source &src) const override; - void show_binlog_type(const Conv_source &src, const Field &, String *str) - const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) - const override - { - DBUG_ASSERT(0); - return DYN_COL_STRING; - } -}; - - -class Type_handler_typelib: public Type_handler_general_purpose_string -{ -public: - virtual ~Type_handler_typelib() { } - enum_field_types field_type() const override { return MYSQL_TYPE_STRING; } - const Type_handler *type_handler_for_item_field() const override; - const Type_handler *cast_to_int_type_handler() const override; - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; - uint32 max_display_length_for_field(const Conv_source &src) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *, - Type_all_attributes *atrr, - Item **items, uint nitems) - const override; - void Column_definition_reuse_fix_attributes(THD *thd, - Column_definition *c, - const Field *field) - const override; - bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) - const override; - bool Column_definition_redefine_stage1(Column_definition *def, - const Column_definition *dup, - const handler *file, - const Schema_specification_st *schema) - const override; - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; - const Vers_type_handler *vers() const override { return NULL; } -}; - - -class Type_handler_enum: public Type_handler_typelib -{ -public: - virtual ~Type_handler_enum() {} - enum_field_types real_field_type() const override { return MYSQL_TYPE_ENUM; } - enum_field_types traditional_merge_field_type() const override - { - return MYSQL_TYPE_ENUM; - } - uint32 calc_pack_length(uint32 length) const override; - uint calc_key_length(const Column_definition &def) const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) - const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - Field *make_schema_field(MEM_ROOT *root, - TABLE *table, - const Record_addr &addr, - const ST_FIELD_INFO &def) const override; -}; - - -class Type_handler_set: public Type_handler_typelib -{ -public: - virtual ~Type_handler_set() {} - enum_field_types real_field_type() const override { return MYSQL_TYPE_SET; } - enum_field_types traditional_merge_field_type() const override - { - return MYSQL_TYPE_SET; - } - uint32 calc_pack_length(uint32 length) const override; - uint calc_key_length(const Column_definition &def) const override; - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) - const override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; -}; - - -// A pseudo type handler, mostly for test purposes for now -class Type_handler_interval_DDhhmmssff: public Type_handler_long_blob -{ -public: - Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) const override; -}; - - -class Function_collection -{ -public: - virtual ~Function_collection() {} - virtual bool init()= 0; - virtual void cleanup()= 0; - virtual Create_func *find_native_function_builder(THD *thd, - const LEX_CSTRING &name) - const= 0; -}; - - -class Type_collection -{ -public: - virtual ~Type_collection() {} - virtual bool init(Type_handler_data *data) - { - return false; - } - virtual const Type_handler *handler_by_name(const LEX_CSTRING &name) const= 0; - virtual const Type_handler *aggregate_for_result(const Type_handler *h1, - const Type_handler *h2) - const= 0; - virtual const Type_handler *aggregate_for_comparison(const Type_handler *h1, - const Type_handler *h2) - const= 0; - virtual const Type_handler *aggregate_for_min_max(const Type_handler *h1, - const Type_handler *h2) - const= 0; - virtual const Type_handler *aggregate_for_num_op(const Type_handler *h1, - const Type_handler *h2) - const= 0; -}; - - -/** - A handler for hybrid type functions, e.g. - COALESCE(), IF(), IFNULL(), NULLIF(), CASE, - numeric operators, - UNIX_TIMESTAMP(), TIME_TO_SEC(). - - Makes sure that field_type(), cmp_type() and result_type() - are always in sync to each other for hybrid functions. -*/ -class Type_handler_hybrid_field_type -{ - const Type_handler *m_type_handler; - bool aggregate_for_min_max(const Type_handler *other); - -public: - Type_handler_hybrid_field_type(); - Type_handler_hybrid_field_type(const Type_handler *handler) - :m_type_handler(handler) - { } - Type_handler_hybrid_field_type(const Type_handler_hybrid_field_type *other) - :m_type_handler(other->m_type_handler) - { } - void swap(Type_handler_hybrid_field_type &other) - { - swap_variables(const Type_handler *, m_type_handler, other.m_type_handler); - } - const Type_handler *type_handler() const { return m_type_handler; } - enum_field_types real_field_type() const - { - return m_type_handler->real_field_type(); - } - Item_result cmp_type() const { return m_type_handler->cmp_type(); } - enum_mysql_timestamp_type mysql_timestamp_type() const - { - return m_type_handler->mysql_timestamp_type(); - } - bool is_timestamp_type() const - { - return m_type_handler->is_timestamp_type(); - } - void set_handler(const Type_handler *other) - { - m_type_handler= other; - } - const Type_handler *set_handler_by_field_type(enum_field_types type) - { - return (m_type_handler= Type_handler::get_handler_by_field_type(type)); - } - const Type_handler *set_handler_by_real_type(enum_field_types type) - { - return (m_type_handler= Type_handler::get_handler_by_real_type(type)); - } - bool aggregate_for_comparison(const Type_handler *other); - bool aggregate_for_comparison(const char *funcname, - Item **items, uint nitems, - bool treat_int_to_uint_as_decimal); - bool aggregate_for_result(const Type_handler *other); - bool aggregate_for_result(const char *funcname, - Item **item, uint nitems, bool treat_bit_as_number); - bool aggregate_for_min_max(const char *funcname, Item **item, uint nitems); - - bool aggregate_for_num_op(const class Type_aggregator *aggregator, - const Type_handler *h0, const Type_handler *h1); -}; - -/* - Helper template to simplify creating builtin types with names. - Plugin types inherit from Type_handler_xxx types that do not set the name in - the constructor, as sql_plugin.cc sets the type name from the plugin name. -*/ -template -class Named_type_handler : public TypeHandler -{ - public: - Named_type_handler(const char *n) : TypeHandler() - { Type_handler::set_name(Name(n, static_cast(strlen(n)))); } -}; - -extern Named_type_handler type_handler_row; -extern Named_type_handler type_handler_null; - -extern Named_type_handler type_handler_float; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_double; - -extern Named_type_handler type_handler_bit; - -extern Named_type_handler type_handler_enum; -extern Named_type_handler type_handler_set; - -extern Named_type_handler type_handler_string; -extern Named_type_handler type_handler_var_string; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_varchar; -extern Named_type_handler type_handler_varchar_compressed; -extern Named_type_handler type_handler_hex_hybrid; - -extern Named_type_handler type_handler_tiny_blob; -extern Named_type_handler type_handler_medium_blob; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_long_blob; -extern Named_type_handler type_handler_blob; -extern Named_type_handler type_handler_blob_compressed; - -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_bool; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_stiny; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_sshort; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_sint24; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_slong; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_slonglong; - -extern Named_type_handler type_handler_utiny; -extern Named_type_handler type_handler_ushort; -extern Named_type_handler type_handler_uint24; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_ulong; -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_ulonglong; -extern Named_type_handler type_handler_vers_trx_id; - -extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_newdecimal; -extern Named_type_handler type_handler_olddecimal; - -extern Named_type_handler type_handler_year; -extern Named_type_handler type_handler_year2; -extern Named_type_handler type_handler_newdate; -extern Named_type_handler type_handler_date; -extern Named_type_handler type_handler_time; -extern Named_type_handler type_handler_time2; -extern Named_type_handler type_handler_datetime; -extern Named_type_handler type_handler_datetime2; -extern Named_type_handler type_handler_timestamp; -extern Named_type_handler type_handler_timestamp2; - -extern Type_handler_interval_DDhhmmssff type_handler_interval_DDhhmmssff; - -class Type_aggregator -{ - bool m_is_commutative; -public: - class Pair - { - public: - const Type_handler *m_handler1; - const Type_handler *m_handler2; - const Type_handler *m_result; - Pair() { } - Pair(const Type_handler *handler1, - const Type_handler *handler2, - const Type_handler *result) - :m_handler1(handler1), m_handler2(handler2), m_result(result) - { } - bool eq(const Type_handler *handler1, const Type_handler *handler2) const - { - return m_handler1 == handler1 && m_handler2 == handler2; - } - }; - static const Type_handler * - find_handler_in_array(const Type_aggregator::Pair *pairs, - const Type_handler *h1, - const Type_handler *h2, - bool commutative) - { - for (const Type_aggregator::Pair *p= pairs; p->m_result; p++) - { - if (p->eq(h1, h2)) - return p->m_result; - if (commutative && p->eq(h2, h1)) - return p->m_result; - } - return NULL; - } - -private: - Dynamic_array m_array; - const Pair* find_pair(const Type_handler *handler1, - const Type_handler *handler2) const; -public: - Type_aggregator(bool is_commutative= false) - :m_is_commutative(is_commutative), m_array(PSI_INSTRUMENT_MEM) - { } - bool add(const Type_handler *handler1, - const Type_handler *handler2, - const Type_handler *result) - { - return m_array.append(Pair(handler1, handler2, result)); - } - const Type_handler *find_handler(const Type_handler *handler1, - const Type_handler *handler2) const - { - const Pair* el= find_pair(handler1, handler2); - return el ? el->m_result : NULL; - } - bool is_commutative() const { return m_is_commutative; } -}; - - -class Type_aggregator_commutative: public Type_aggregator -{ -public: - Type_aggregator_commutative() - :Type_aggregator(true) - { } -}; - - -class Type_handler_data -{ -public: - Type_aggregator_commutative m_type_aggregator_for_result; - Type_aggregator_commutative m_type_aggregator_for_comparison; - - Type_aggregator_commutative m_type_aggregator_for_plus; - Type_aggregator_commutative m_type_aggregator_for_mul; - - Type_aggregator m_type_aggregator_for_minus; - Type_aggregator m_type_aggregator_for_div; - Type_aggregator m_type_aggregator_for_mod; -#ifndef DBUG_OFF - // This is used for mtr purposes in debug builds - Type_aggregator m_type_aggregator_non_commutative_test; -#endif - bool init(); -}; - -extern Type_handler_data *type_handler_data; - -#endif /* SQL_TYPE_H_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_geom.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_geom.h deleted file mode 100644 index 74290e4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_geom.h +++ /dev/null @@ -1,436 +0,0 @@ -#ifndef SQL_TYPE_GEOM_H_INCLUDED -#define SQL_TYPE_GEOM_H_INCLUDED -/* - Copyright (c) 2015 MariaDB Foundation - Copyright (c) 2019 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ - -#ifdef USE_PRAGMA_IMPLEMENTATION -#pragma implementation // gcc: Class implementation -#endif - -#include "mariadb.h" -#include "sql_type.h" - -#ifdef HAVE_SPATIAL -class Type_handler_geometry: public Type_handler_string_result -{ -public: - enum geometry_types - { - GEOM_GEOMETRY = 0, GEOM_POINT = 1, GEOM_LINESTRING = 2, GEOM_POLYGON = 3, - GEOM_MULTIPOINT = 4, GEOM_MULTILINESTRING = 5, GEOM_MULTIPOLYGON = 6, - GEOM_GEOMETRYCOLLECTION = 7 - }; - static bool check_type_geom_or_binary(const char *opname, const Item *item); - static bool check_types_geom_or_binary(const char *opname, - Item * const *args, - uint start, uint end); - static const Type_handler_geometry *type_handler_geom_by_type(uint type); - LEX_CSTRING extended_metadata_data_type_name() const; -public: - virtual ~Type_handler_geometry() {} - enum_field_types field_type() const override { return MYSQL_TYPE_GEOMETRY; } - bool Item_append_extended_type_info(Send_field_extended_metadata *to, - const Item *item) const override - { - LEX_CSTRING tmp= extended_metadata_data_type_name(); - return tmp.length ? to->set_data_type_name(tmp) : false; - } - bool is_param_long_data_type() const override { return true; } - uint32 max_display_length_for_field(const Conv_source &src) const override; - uint32 calc_pack_length(uint32 length) const override; - const Type_collection *type_collection() const override; - const Type_handler *type_handler_for_comparison() const override; - virtual geometry_types geometry_type() const { return GEOM_GEOMETRY; } - virtual Item *create_typecast_item(THD *thd, Item *item, - const Type_cast_attributes &attr) - const override; - const Type_handler *type_handler_frm_unpack(const uchar *buffer) - const override; - bool is_binary_compatible_geom_super_type_for(const Type_handler_geometry *th) - const - { - return geometry_type() == GEOM_GEOMETRY || - geometry_type() == th->geometry_type(); - } - bool type_can_have_key_part() const override { return true; } - bool subquery_type_allows_materialization(const Item *inner, - const Item *outer) const override - { - return false; // Materialization does not work with GEOMETRY columns - } - void Item_param_set_param_func(Item_param *param, - uchar **pos, ulong len) const override; - bool Item_param_set_from_value(THD *thd, - Item_param *param, - const Type_all_attributes *attr, - const st_value *value) const override; - Field *make_conversion_table_field(MEM_ROOT *root, - TABLE *table, uint metadata, - const Field *target) const override; - uint Column_definition_gis_options_image(uchar *buff, - const Column_definition &def) - const override; - bool Column_definition_data_type_info_image(Binary_string *to, - const Column_definition &def) - const override - { - return false; - } - void - Column_definition_attributes_frm_pack(const Column_definition_attributes *at, - uchar *buff) const override; - bool - Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, - TABLE_SHARE *share, - const uchar *buffer, - LEX_CUSTRING *gis_options) const - override; - bool Column_definition_fix_attributes(Column_definition *c) const override; - void Column_definition_reuse_fix_attributes(THD *thd, - Column_definition *c, - const Field *field) const - override; - bool Column_definition_prepare_stage1(THD *thd, - MEM_ROOT *mem_root, - Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Column_definition_prepare_stage2(Column_definition *c, - handler *file, - ulonglong table_flags) const override; - bool Key_part_spec_init_primary(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Key_part_spec_init_unique(Key_part_spec *part, - const Column_definition &def, - const handler *file, - bool *has_key_needed) const override; - bool Key_part_spec_init_multiple(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Key_part_spec_init_foreign(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Key_part_spec_init_spatial(Key_part_spec *part, - const Column_definition &def) const override; - Field *make_table_field(MEM_ROOT *root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Type_all_attributes &attr, - TABLE_SHARE *share) const override; - - Field *make_table_field_from_def(TABLE_SHARE *share, - MEM_ROOT *mem_root, - const LEX_CSTRING *name, - const Record_addr &addr, - const Bit_addr &bit, - const Column_definition_attributes *attr, - uint32 flags) const override; - - bool can_return_int() const override { return false; } - bool can_return_decimal() const override { return false; } - bool can_return_real() const override { return false; } - bool can_return_text() const override { return false; } - bool can_return_date() const override { return false; } - bool can_return_time() const override { return false; } - bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; - bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; - bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; - bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; - bool Item_hybrid_func_fix_attributes(THD *thd, - const char *name, - Type_handler_hybrid_field_type *h, - Type_all_attributes *attr, - Item **items, uint nitems) const - override; - bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; - bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; - bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; - - bool Item_func_signed_fix_length_and_dec(Item_func_signed *) const override; - bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *) const - override; - bool Item_double_typecast_fix_length_and_dec(Item_double_typecast *) const - override; - bool Item_float_typecast_fix_length_and_dec(Item_float_typecast *) const - override; - bool Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *) const - override; - bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) const - override; - bool Item_time_typecast_fix_length_and_dec(Item_time_typecast *) const - override; - bool Item_date_typecast_fix_length_and_dec(Item_date_typecast *) const - override; - bool Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *) const - override; -}; - - -class Type_handler_point: public Type_handler_geometry -{ - // Binary length of a POINT value: 4 byte SRID + 21 byte WKB POINT - static uint octet_length() { return 25; } -public: - geometry_types geometry_type() const override { return GEOM_POINT; } - Item *make_constructor_item(THD *thd, List *args) const override; - bool Key_part_spec_init_primary(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Key_part_spec_init_unique(Key_part_spec *part, - const Column_definition &def, - const handler *file, - bool *has_key_needed) const override; - bool Key_part_spec_init_multiple(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; - bool Key_part_spec_init_foreign(Key_part_spec *part, - const Column_definition &def, - const handler *file) const override; -}; - - -class Type_handler_linestring: public Type_handler_geometry -{ -public: - geometry_types geometry_type() const override { return GEOM_LINESTRING; } - Item *make_constructor_item(THD *thd, List *args) const override; -}; - - -class Type_handler_polygon: public Type_handler_geometry -{ -public: - geometry_types geometry_type() const override { return GEOM_POLYGON; } - Item *make_constructor_item(THD *thd, List *args) const override; -}; - - -class Type_handler_multipoint: public Type_handler_geometry -{ -public: - geometry_types geometry_type() const override { return GEOM_MULTIPOINT; } - Item *make_constructor_item(THD *thd, List *args) const override; -}; - - -class Type_handler_multilinestring: public Type_handler_geometry -{ -public: - geometry_types geometry_type() const override { return GEOM_MULTILINESTRING; } - Item *make_constructor_item(THD *thd, List *args) const override; -}; - - -class Type_handler_multipolygon: public Type_handler_geometry -{ -public: - geometry_types geometry_type() const override { return GEOM_MULTIPOLYGON; } - Item *make_constructor_item(THD *thd, List *args) const override; -}; - - -class Type_handler_geometrycollection: public Type_handler_geometry -{ -public: - geometry_types geometry_type() const override { return GEOM_GEOMETRYCOLLECTION; } - Item *make_constructor_item(THD *thd, List *args) const override; -}; - -extern Named_type_handler type_handler_geometry; -extern Named_type_handler type_handler_point; -extern Named_type_handler type_handler_linestring; -extern Named_type_handler type_handler_polygon; -extern Named_type_handler type_handler_multipoint; -extern Named_type_handler type_handler_multilinestring; -extern Named_type_handler type_handler_multipolygon; -extern Named_type_handler type_handler_geometrycollection; - -class Type_collection_geometry: public Type_collection -{ - const Type_handler *aggregate_common(const Type_handler *a, - const Type_handler *b) const - { - if (a == b) - return a; - if (dynamic_cast(a) && - dynamic_cast(b)) - return &type_handler_geometry; - return NULL; - } - const Type_handler *aggregate_if_null(const Type_handler *a, - const Type_handler *b) const - { - return a == &type_handler_null ? b : - b == &type_handler_null ? a : - NULL; - } - const Type_handler *aggregate_if_long_blob(const Type_handler *a, - const Type_handler *b) const - { - return a == &type_handler_long_blob ? &type_handler_long_blob : - b == &type_handler_long_blob ? &type_handler_long_blob : - NULL; - } - const Type_handler *aggregate_if_string(const Type_handler *a, - const Type_handler *b) const; -#ifndef DBUG_OFF - bool init_aggregators(Type_handler_data *data, const Type_handler *geom) const; -#endif -public: - bool init(Type_handler_data *data) override; - const Type_handler *handler_by_name(const LEX_CSTRING &name) const override; - const Type_handler *aggregate_for_result(const Type_handler *a, - const Type_handler *b) - const override; - const Type_handler *aggregate_for_comparison(const Type_handler *a, - const Type_handler *b) - const override; - const Type_handler *aggregate_for_min_max(const Type_handler *a, - const Type_handler *b) - const override; - const Type_handler *aggregate_for_num_op(const Type_handler *a, - const Type_handler *b) - const override - { - return NULL; - } -}; - -extern Type_collection_geometry type_collection_geometry; - -#include "field.h" - -class Field_geom :public Field_blob -{ - const Type_handler_geometry *m_type_handler; -public: - uint srid; - uint precision; - enum storage_type { GEOM_STORAGE_WKB= 0, GEOM_STORAGE_BINARY= 1}; - enum storage_type storage; - - Field_geom(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, - enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, - TABLE_SHARE *share, uint blob_pack_length, - const Type_handler_geometry *gth, - uint field_srid) - :Field_blob(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, - field_name_arg, share, blob_pack_length, &my_charset_bin), - m_type_handler(gth) - { srid= field_srid; } - enum_conv_type rpl_conv_type_from(const Conv_source &source, - const Relay_log_info *rli, - const Conv_param ¶m) const override; - enum ha_base_keytype key_type() const override - { - return HA_KEYTYPE_VARBINARY2; - } - const Type_handler *type_handler() const override - { - return m_type_handler; - } - const Type_handler_geometry *type_handler_geom() const - { - return m_type_handler; - } - void set_type_handler(const Type_handler_geometry *th) - { - m_type_handler= th; - } - enum_field_types type() const override - { - return MYSQL_TYPE_GEOMETRY; - } - enum_field_types real_type() const override - { - return MYSQL_TYPE_GEOMETRY; - } - Information_schema_character_attributes - information_schema_character_attributes() const override - { - return Information_schema_character_attributes(); - } - void make_send_field(Send_field *to) override - { - Field_longstr::make_send_field(to); - LEX_CSTRING tmp= m_type_handler->extended_metadata_data_type_name(); - if (tmp.length) - to->set_data_type_name(tmp); - } - bool can_optimize_range(const Item_bool_func *cond, - const Item *item, - bool is_eq_func) const override; - void sql_type(String &str) const override; - Copy_func *get_copy_func(const Field *from) const override - { - const Type_handler_geometry *fth= - dynamic_cast(from->type_handler()); - if (fth && m_type_handler->is_binary_compatible_geom_super_type_for(fth)) - return get_identical_copy_func(); - return do_conv_blob; - } - bool memcpy_field_possible(const Field *from) const override - { - const Type_handler_geometry *fth= - dynamic_cast(from->type_handler()); - return fth && - m_type_handler->is_binary_compatible_geom_super_type_for(fth) && - !table->copy_blobs; - } - bool is_equal(const Column_definition &new_field) const override; - bool can_be_converted_by_engine(const Column_definition &new_type) - const override - { - return false; // Override the Field_blob behavior - } - - int store(const char *to, size_t length, CHARSET_INFO *charset) override; - int store(double nr) override; - int store(longlong nr, bool unsigned_val) override; - int store_decimal(const my_decimal *) override; - uint size_of() const override{ return sizeof(*this); } - /** - Key length is provided only to support hash joins. (compared byte for byte) - Ex: SELECT .. FROM t1,t2 WHERE t1.field_geom1=t2.field_geom2. - - The comparison is not very relevant, as identical geometry might be - represented differently, but we need to support it either way. - */ - uint32 key_length() const override{ return packlength; } - uint get_key_image(uchar *buff,uint length, - const uchar *ptr_arg, imagetype type_arg) const override; - - /** - Non-nullable GEOMETRY types cannot have defaults, - but the underlying blob must still be reset. - */ - int reset(void) override{ return Field_blob::reset() || !maybe_null(); } - bool load_data_set_null(THD *thd) override; - bool load_data_set_no_data(THD *thd, bool fixed_format) override; - - uint get_srid() const { return srid; } - void print_key_value(String *out, uint32 length) override - { - out->append(STRING_WITH_LEN("unprintable_geometry_value")); - } - Binlog_type_info binlog_type_info() const override; -}; - -#endif // HAVE_SPATIAL - -#endif // SQL_TYPE_GEOM_H_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_int.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_int.h deleted file mode 100644 index 9fd4f0c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_int.h +++ /dev/null @@ -1,200 +0,0 @@ -/* Copyright (c) 2018, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_TYPE_INT_INCLUDED -#define SQL_TYPE_INT_INCLUDED - -#include "my_bit.h" // my_count_bits() - - -class Null_flag -{ -protected: - bool m_is_null; -public: - bool is_null() const { return m_is_null; } - Null_flag(bool is_null) :m_is_null(is_null) { } -}; - - -class Longlong -{ -protected: - longlong m_value; -public: - longlong value() const { return m_value; } - Longlong(longlong nr) :m_value(nr) { } -}; - - -class Longlong_null: public Longlong, public Null_flag -{ -public: - Longlong_null(longlong nr, bool is_null) - :Longlong(nr), Null_flag(is_null) - { } - explicit Longlong_null() - :Longlong(0), Null_flag(true) - { } - explicit Longlong_null(longlong nr) - :Longlong(nr), Null_flag(false) - { } - Longlong_null operator|(const Longlong_null &other) const - { - if (is_null() || other.is_null()) - return Longlong_null(); - return Longlong_null(value() | other.value()); - } - Longlong_null operator&(const Longlong_null &other) const - { - if (is_null() || other.is_null()) - return Longlong_null(); - return Longlong_null(value() & other.value()); - } - Longlong_null operator^(const Longlong_null &other) const - { - if (is_null() || other.is_null()) - return Longlong_null(); - return Longlong_null((longlong) (value() ^ other.value())); - } - Longlong_null operator~() const - { - if (is_null()) - return *this; - return Longlong_null((longlong) ~ (ulonglong) value()); - } - Longlong_null operator<<(const Longlong_null &llshift) const - { - if (is_null() || llshift.is_null()) - return Longlong_null(); - uint shift= (uint) llshift.value(); - ulonglong res= ((ulonglong) value()) << shift; - return Longlong_null(shift < sizeof(longlong) * 8 ? (longlong) res : 0); - } - Longlong_null operator>>(const Longlong_null &llshift) const - { - if (is_null() || llshift.is_null()) - return Longlong_null(); - uint shift= (uint) llshift.value(); - ulonglong res= ((ulonglong) value()) >> shift; - return Longlong_null(shift < sizeof(longlong) * 8 ? (longlong) res : 0); - } - Longlong_null bit_count() const - { - if (is_null()) - return *this; - return Longlong_null((longlong) my_count_bits((ulonglong) value())); - } -}; - - -// A longlong/ulonglong hybrid. Good to store results of val_int(). -class Longlong_hybrid: public Longlong -{ -protected: - bool m_unsigned; - int cmp_signed(const Longlong_hybrid& other) const - { - return m_value < other.m_value ? -1 : m_value == other.m_value ? 0 : 1; - } - int cmp_unsigned(const Longlong_hybrid& other) const - { - return (ulonglong) m_value < (ulonglong) other.m_value ? -1 : - m_value == other.m_value ? 0 : 1; - } -public: - Longlong_hybrid(longlong nr, bool unsigned_flag) - :Longlong(nr), m_unsigned(unsigned_flag) - { } - bool is_unsigned() const { return m_unsigned; } - bool is_unsigned_outside_of_signed_range() const - { - return m_unsigned && ((ulonglong) m_value) > (ulonglong) LONGLONG_MAX; - } - bool neg() const { return m_value < 0 && !m_unsigned; } - ulonglong abs() const - { - if (m_unsigned) - return (ulonglong) m_value; - if (m_value == LONGLONG_MIN) // avoid undefined behavior - return ((ulonglong) LONGLONG_MAX) + 1; - return m_value < 0 ? -m_value : m_value; - } - /* - Convert to an unsigned number: - - Negative numbers are converted to 0. - - Positive numbers bigger than upper_bound are converted to upper_bound. - - Other numbers are returned as is. - */ - ulonglong to_ulonglong(ulonglong upper_bound) const - { - return neg() ? 0 : - (ulonglong) m_value > upper_bound ? upper_bound : - (ulonglong) m_value; - } - uint to_uint(uint upper_bound) const - { - return (uint) to_ulonglong(upper_bound); - } - int cmp(const Longlong_hybrid& other) const - { - if (m_unsigned == other.m_unsigned) - return m_unsigned ? cmp_unsigned(other) : cmp_signed(other); - if (is_unsigned_outside_of_signed_range()) - return 1; - if (other.is_unsigned_outside_of_signed_range()) - return -1; - /* - The unsigned argument is in the range 0..LONGLONG_MAX. - The signed argument is in the range LONGLONG_MIN..LONGLONG_MAX. - Safe to compare as signed. - */ - return cmp_signed(other); - } - bool operator==(const Longlong_hybrid &nr) const - { - return cmp(nr) == 0; - } - bool operator==(ulonglong nr) const - { - return cmp(Longlong_hybrid((longlong) nr, true)) == 0; - } - bool operator==(uint nr) const - { - return cmp(Longlong_hybrid((longlong) nr, true)) == 0; - } - bool operator==(longlong nr) const - { - return cmp(Longlong_hybrid(nr, false)) == 0; - } - bool operator==(int nr) const - { - return cmp(Longlong_hybrid(nr, false)) == 0; - } -}; - - -class Longlong_hybrid_null: public Longlong_hybrid, - public Null_flag -{ -public: - Longlong_hybrid_null(const Longlong_null &nr, bool unsigned_flag) - :Longlong_hybrid(nr.value(), unsigned_flag), - Null_flag(nr.is_null()) - { } -}; - - -#endif // SQL_TYPE_INT_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_json.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_json.h deleted file mode 100644 index 6c4ee8c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_json.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef SQL_TYPE_JSON_INCLUDED -#define SQL_TYPE_JSON_INCLUDED -/* - Copyright (c) 2019, MariaDB - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; version 2 of - the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "mariadb.h" -#include "sql_type.h" - -class Type_handler_json_longtext: public Type_handler_long_blob -{ - Virtual_column_info *make_json_valid_expr(THD *thd, - const LEX_CSTRING *field_name) - const; -public: - virtual ~Type_handler_json_longtext() {} - bool Column_definition_validate_check_constraint(THD *thd, - Column_definition *c) const; -}; - -extern MYSQL_PLUGIN_IMPORT - Type_handler_json_longtext type_handler_json_longtext; - -#endif // SQL_TYPE_JSON_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_real.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_real.h deleted file mode 100644 index 5a484fb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_real.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 2019 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef SQL_TYPE_REAL_INCLUDED -#define SQL_TYPE_REAL_INCLUDED - -#include - -class Float -{ - float m_value; -public: - Float(float nr) - :m_value(nr) - { - DBUG_ASSERT(!std::isnan(nr)); - DBUG_ASSERT(!std::isinf(nr)); - } - Float(double nr) - :m_value((float) nr) - { - DBUG_ASSERT(!std::isnan(nr)); - DBUG_ASSERT(!std::isinf(nr)); - DBUG_ASSERT(nr <= FLT_MAX); - DBUG_ASSERT(nr >= -FLT_MAX); - } - Float(const uchar *ptr) - { - float4get(m_value, ptr); - } - bool to_string(String *to, uint dec) const; -}; - - -#endif // SQL_TYPE_REAL_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_string.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_string.h deleted file mode 100644 index fca46e9..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_type_string.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (c) 2019 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef SQL_TYPE_STRING_INCLUDED -#define SQL_TYPE_STRING_INCLUDED - -class StringPack -{ - CHARSET_INFO *m_cs; - uint32 m_octet_length; - CHARSET_INFO *charset() const { return m_cs; } - uint mbmaxlen() const { return m_cs->mbmaxlen; }; - uint32 char_length() const { return m_octet_length / mbmaxlen(); } -public: - StringPack(CHARSET_INFO *cs, uint32 octet_length) - :m_cs(cs), - m_octet_length(octet_length) - { } - uchar *pack(uchar *to, const uchar *from, uint max_length) const; - const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, - uint param_data) const; -public: - static uint max_packed_col_length(uint max_length) - { - return (max_length > 255 ? 2 : 1) + max_length; - } - static uint packed_col_length(const uchar *data_ptr, uint length) - { - if (length > 255) - return uint2korr(data_ptr)+2; - return (uint) *data_ptr + 1; - } -}; - - -#endif // SQL_TYPE_STRING_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_udf.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_udf.h deleted file mode 100644 index cb19543..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_udf.h +++ /dev/null @@ -1,169 +0,0 @@ -#ifndef SQL_UDF_INCLUDED -#define SQL_UDF_INCLUDED - -/* Copyright (c) 2000, 2003-2007 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -/* This file defines structures needed by udf functions */ - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface -#endif - -enum Item_udftype {UDFTYPE_FUNCTION=1,UDFTYPE_AGGREGATE}; - -typedef void (*Udf_func_clear)(UDF_INIT *, uchar *, uchar *); -typedef void (*Udf_func_add)(UDF_INIT *, UDF_ARGS *, uchar *, uchar *); -typedef void (*Udf_func_deinit)(UDF_INIT*); -typedef my_bool (*Udf_func_init)(UDF_INIT *, UDF_ARGS *, char *); -typedef void (*Udf_func_any)(); -typedef double (*Udf_func_double)(UDF_INIT *, UDF_ARGS *, uchar *, uchar *); -typedef longlong (*Udf_func_longlong)(UDF_INIT *, UDF_ARGS *, uchar *, - uchar *); - -typedef struct st_udf_func -{ - LEX_CSTRING name; - Item_result returns; - Item_udftype type; - const char *dl; - void *dlhandle; - Udf_func_any func; - Udf_func_init func_init; - Udf_func_deinit func_deinit; - Udf_func_clear func_clear; - Udf_func_add func_add; - Udf_func_add func_remove; - ulong usage_count; -} udf_func; - -class Item_result_field; - -class udf_handler :public Sql_alloc -{ - protected: - udf_func *u_d; - String *buffers; - UDF_ARGS f_args; - UDF_INIT initid; - char *num_buffer; - uchar error, is_null; - bool initialized; - Item **args; - - public: - bool not_original; - udf_handler(udf_func *udf_arg) :u_d(udf_arg), buffers(0), error(0), - is_null(0), initialized(0), not_original(0) - {} - ~udf_handler(); - const char *name() const { return u_d ? u_d->name.str : "?"; } - Item_result result_type () const - { return u_d ? u_d->returns : STRING_RESULT;} - bool get_arguments(); - bool fix_fields(THD *thd, Item_func_or_sum *item, - uint arg_count, Item **args); - void cleanup(); - double val(my_bool *null_value) - { - is_null= 0; - if (get_arguments()) - { - *null_value=1; - return 0.0; - } - Udf_func_double func= (Udf_func_double) u_d->func; - double tmp=func(&initid, &f_args, &is_null, &error); - if (is_null || error) - { - *null_value=1; - return 0.0; - } - *null_value=0; - return tmp; - } - longlong val_int(my_bool *null_value) - { - is_null= 0; - if (get_arguments()) - { - *null_value=1; - return 0; - } - Udf_func_longlong func= (Udf_func_longlong) u_d->func; - longlong tmp=func(&initid, &f_args, &is_null, &error); - if (is_null || error) - { - *null_value=1; - return 0; - } - *null_value=0; - return tmp; - } - my_decimal *val_decimal(my_bool *null_value, my_decimal *dec_buf); - void clear() - { - is_null= 0; - Udf_func_clear func= u_d->func_clear; - func(&initid, &is_null, &error); - } - void add(my_bool *null_value) - { - if (get_arguments()) - { - *null_value=1; - return; - } - Udf_func_add func= u_d->func_add; - func(&initid, &f_args, &is_null, &error); - *null_value= (my_bool) (is_null || error); - } - bool supports_removal() const - { return MY_TEST(u_d->func_remove); } - void remove(my_bool *null_value) - { - DBUG_ASSERT(u_d->func_remove); - if (get_arguments()) - { - *null_value=1; - return; - } - Udf_func_add func= u_d->func_remove; - func(&initid, &f_args, &is_null, &error); - *null_value= (my_bool) (is_null || error); - } - String *val_str(String *str,String *save_str); -}; - - -#ifdef HAVE_DLOPEN -void udf_init(void),udf_free(void); -udf_func *find_udf(const char *name, size_t size, bool mark_used=0); -void free_udf(udf_func *udf); -int mysql_create_function(THD *thd,udf_func *udf); -enum drop_udf_result -{ - UDF_DEL_RESULT_ABSENT, - UDF_DEL_RESULT_DELETED, - UDF_DEL_RESULT_ERROR -}; -enum drop_udf_result mysql_drop_function(THD *thd, const LEX_CSTRING *name); -#else -static inline void udf_init(void) { } -static inline void udf_free(void) { } -#endif -#endif /* SQL_UDF_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_union.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_union.h deleted file mode 100644 index 3776831..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_union.h +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_UNION_INCLUDED -#define SQL_UNION_INCLUDED - -class THD; -class select_result; -struct LEX; - -typedef class st_select_lex_unit SELECT_LEX_UNIT; - -bool mysql_union(THD *thd, LEX *lex, select_result *result, - SELECT_LEX_UNIT *unit, ulong setup_tables_done_option); - - -#endif /* SQL_UNION_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_update.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_update.h deleted file mode 100644 index 65e44d1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_update.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef SQL_UPDATE_INCLUDED -#define SQL_UPDATE_INCLUDED - -#include "sql_class.h" /* enum_duplicates */ - -class Item; -struct TABLE_LIST; -class THD; - -typedef class st_select_lex SELECT_LEX; -typedef class st_select_lex_unit SELECT_LEX_UNIT; - -bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list, - Item **conds, uint order_num, ORDER *order); -bool check_unique_table(THD *thd, TABLE_LIST *table_list); -int mysql_update(THD *thd,TABLE_LIST *tables,List &fields, - List &values,COND *conds, - uint order_num, ORDER *order, ha_rows limit, - bool ignore, ha_rows *found_return, ha_rows *updated_return); -bool mysql_multi_update(THD *thd, TABLE_LIST *table_list, - List *fields, List *values, - COND *conds, ulonglong options, - enum enum_duplicates handle_duplicates, bool ignore, - SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex, - multi_update **result); -bool records_are_comparable(const TABLE *table); -bool compare_record(const TABLE *table); - -#endif /* SQL_UPDATE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_view.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_view.h deleted file mode 100644 index c1e5dc4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_view.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef SQL_VIEW_INCLUDED -#define SQL_VIEW_INCLUDED - -/* -*- C++ -*- */ -/* Copyright (c) 2004, 2010, Oracle and/or its affiliates. - Copyright (c) 2015, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -#include "sql_class.h" /* Required by sql_lex.h */ -#include "sql_lex.h" /* enum_view_create_mode, enum_drop_mode */ - -/* Forward declarations */ - -class File_parser; - - -/* Function declarations */ - -bool create_view_precheck(THD *thd, TABLE_LIST *tables, TABLE_LIST *view, - enum_view_create_mode mode); - -bool mysql_create_view(THD *thd, TABLE_LIST *view, - enum_view_create_mode mode); - -bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table, - bool open_view_no_parse); - - -bool mysql_drop_view(THD *thd, TABLE_LIST *view, enum_drop_mode drop_mode); - -bool check_key_in_view(THD *thd, TABLE_LIST * view); - -bool insert_view_fields(THD *thd, List *list, TABLE_LIST *view); - -int view_checksum(THD *thd, TABLE_LIST *view); -int view_check(THD *thd, TABLE_LIST *view, HA_CHECK_OPT *check_opt); -int view_repair(THD *thd, TABLE_LIST *view, HA_CHECK_OPT *check_opt); - -extern TYPELIB updatable_views_with_limit_typelib; - -bool check_duplicate_names(THD *thd, List& item_list, - bool gen_unique_view_names); -bool mysql_rename_view(THD *thd, const LEX_CSTRING *new_db, const LEX_CSTRING *new_name, - TABLE_LIST *view); - -void make_valid_column_names(THD *thd, List &item_list); - -#define VIEW_ANY_ACL (SELECT_ACL | UPDATE_ACL | INSERT_ACL | DELETE_ACL) - -extern const LEX_CSTRING view_type; - -void make_valid_column_names(List &item_list); - -#endif /* SQL_VIEW_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_window.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_window.h deleted file mode 100644 index 373b367..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sql_window.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - Copyright (c) 2016, 2017 MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef SQL_WINDOW_INCLUDED -#define SQL_WINDOW_INCLUDED - -#include "filesort.h" - -class Item_window_func; - -/* - Window functions module. - - Each instance of window function has its own element in SELECT_LEX::window_specs. -*/ - - -class Window_frame_bound : public Sql_alloc -{ - -public: - - enum Bound_precedence_type - { - PRECEDING, - CURRENT, // Used for CURRENT ROW window frame bounds - FOLLOWING - }; - - Bound_precedence_type precedence_type; - - - /* - For UNBOUNDED PRECEDING / UNBOUNDED FOLLOWING window frame bounds - precedence type is seto to PRECEDING / FOLLOWING and - offset is set to NULL. - The offset is not meaningful with precedence type CURRENT - */ - Item *offset; - - Window_frame_bound(Bound_precedence_type prec_type, - Item *offset_val) - : precedence_type(prec_type), offset(offset_val) {} - - bool is_unbounded() { return offset == NULL; } - - void print(String *str, enum_query_type query_type); - -}; - - -class Window_frame : public Sql_alloc -{ - -public: - - enum Frame_units - { - UNITS_ROWS, - UNITS_RANGE - }; - - enum Frame_exclusion - { - EXCL_NONE, - EXCL_CURRENT_ROW, - EXCL_GROUP, - EXCL_TIES - }; - - Frame_units units; - - Window_frame_bound *top_bound; - - Window_frame_bound *bottom_bound; - - Frame_exclusion exclusion; - - Window_frame(Frame_units win_frame_units, - Window_frame_bound *win_frame_top_bound, - Window_frame_bound *win_frame_bottom_bound, - Frame_exclusion win_frame_exclusion) - : units(win_frame_units), top_bound(win_frame_top_bound), - bottom_bound(win_frame_bottom_bound), exclusion(win_frame_exclusion) {} - - bool check_frame_bounds(); - - void print(String *str, enum_query_type query_type); - -}; - -class Window_spec : public Sql_alloc -{ - bool window_names_are_checked; - public: - virtual ~Window_spec() {} - - LEX_CSTRING *window_ref; - - SQL_I_List *partition_list; - - SQL_I_List *order_list; - - Window_frame *window_frame; - - Window_spec *referenced_win_spec; - - Window_spec(LEX_CSTRING *win_ref, - SQL_I_List *part_list, - SQL_I_List *ord_list, - Window_frame *win_frame) - : window_names_are_checked(false), window_ref(win_ref), - partition_list(part_list), order_list(ord_list), - window_frame(win_frame), referenced_win_spec(NULL) {} - - virtual const char *name() { return NULL; } - - bool check_window_names(List_iterator_fast &it); - - const char *window_reference() - { - return window_ref ? window_ref->str : NULL; - } - - void join_partition_and_order_lists() - { - *(partition_list->next)= order_list->first; - } - - void disjoin_partition_and_order_lists() - { - *(partition_list->next)= NULL; - } - - void print(String *str, enum_query_type query_type); - void print_order(String *str, enum_query_type query_type); - void print_partition(String *str, enum_query_type query_type); - -}; - -class Window_def : public Window_spec -{ - public: - - LEX_CSTRING *window_name; - - Window_def(LEX_CSTRING *win_name, - LEX_CSTRING *win_ref, - SQL_I_List *part_list, - SQL_I_List *ord_list, - Window_frame *win_frame) - : Window_spec(win_ref, part_list, ord_list, win_frame), - window_name(win_name) {} - - const char *name() { return window_name->str; } - -}; - -int setup_windows(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, - List &fields, List &all_fields, - List &win_specs, List &win_funcs); - - -////////////////////////////////////////////////////////////////////////////// -// Classes that make window functions computation a part of SELECT's query plan -////////////////////////////////////////////////////////////////////////////// - -class Frame_cursor; -/* - This handles computation of one window function. - - Currently, we make a spearate filesort() call for each window function. -*/ - -class Window_func_runner : public Sql_alloc -{ -public: - /* Add the function to be computed during the execution pass */ - bool add_function_to_run(Item_window_func *win_func); - - /* Compute and fill the fields in the table. */ - bool exec(THD *thd, TABLE *tbl, SORT_INFO *filesort_result); - -private: - /* A list of window functions for which this Window_func_runner will compute - values during the execution phase. */ - List window_functions; -}; - - -/* - Represents a group of window functions that require the same sorting of - rows and so share the filesort() call. - -*/ - -class Window_funcs_sort : public Sql_alloc -{ -public: - bool setup(THD *thd, SQL_SELECT *sel, List_iterator &it, - st_join_table *join_tab); - bool exec(JOIN *join, bool keep_filesort_result); - void cleanup() { delete filesort; } - - friend class Window_funcs_computation; - -private: - Window_func_runner runner; - - /* Window functions can be computed over this sorting */ - Filesort *filesort; -}; - - -struct st_join_table; -class Explain_aggr_window_funcs; - -/* - This is a "window function computation phase": a single object of this class - takes care of computing all window functions in a SELECT. - - - JOIN optimizer is exected to call setup() during query optimization. - - JOIN::exec() should call exec() once it has collected join output in a - temporary table. -*/ - -class Window_funcs_computation : public Sql_alloc -{ - List win_func_sorts; -public: - bool setup(THD *thd, List *window_funcs, st_join_table *tab); - bool exec(JOIN *join, bool keep_last_filesort_result); - - Explain_aggr_window_funcs *save_explain_plan(MEM_ROOT *mem_root, bool is_analyze); - void cleanup(); -}; - - -#endif /* SQL_WINDOW_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ssl_compat.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/ssl_compat.h deleted file mode 100644 index 8cc0e6a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/ssl_compat.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright (c) 2016, 2017 MariaDB Corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#include - -/* OpenSSL version specific definitions */ -#if defined(OPENSSL_VERSION_NUMBER) - -#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER) -#define HAVE_OPENSSL11 1 -#define SSL_LIBRARY OpenSSL_version(OPENSSL_VERSION) -#define ERR_remove_state(X) ERR_clear_error() -#define EVP_CIPHER_CTX_SIZE 176 -#define EVP_MD_CTX_SIZE 48 -#undef EVP_MD_CTX_init -#define EVP_MD_CTX_init(X) do { memset((X), 0, EVP_MD_CTX_SIZE); EVP_MD_CTX_reset(X); } while(0) -#undef EVP_CIPHER_CTX_init -#define EVP_CIPHER_CTX_init(X) do { memset((X), 0, EVP_CIPHER_CTX_SIZE); EVP_CIPHER_CTX_reset(X); } while(0) - -/* - Macros below are deprecated. OpenSSL 1.1 may define them or not, - depending on how it was built. -*/ -#undef ERR_free_strings -#define ERR_free_strings() -#undef EVP_cleanup -#define EVP_cleanup() -#undef CRYPTO_cleanup_all_ex_data -#define CRYPTO_cleanup_all_ex_data() -#undef SSL_load_error_strings -#define SSL_load_error_strings() - -#else -#define HAVE_OPENSSL10 1 -#ifdef HAVE_WOLFSSL -#define SSL_LIBRARY "WolfSSL " WOLFSSL_VERSION -#else -#define SSL_LIBRARY SSLeay_version(SSLEAY_VERSION) -#endif - -#ifdef HAVE_WOLFSSL -#undef ERR_remove_state -#define ERR_remove_state(x) do {} while(0) -#elif defined (HAVE_ERR_remove_thread_state) -#define ERR_remove_state(X) ERR_remove_thread_state(NULL) -#endif /* HAVE_ERR_remove_thread_state */ - -#endif /* HAVE_OPENSSL11 */ -#endif - -#ifdef HAVE_WOLFSSL -#define EVP_MD_CTX_SIZE sizeof(wc_Md5) -#endif - -#ifndef HAVE_OPENSSL11 -#ifndef ASN1_STRING_get0_data -#define ASN1_STRING_get0_data(X) ASN1_STRING_data(X) -#endif -#ifndef EVP_MD_CTX_SIZE -#define EVP_MD_CTX_SIZE sizeof(EVP_MD_CTX) -#endif - -#define OPENSSL_init_ssl(X,Y) SSL_library_init() -#define DH_set0_pqg(D,P,Q,G) ((D)->p= (P), (D)->g= (G)) -#define EVP_CIPHER_CTX_buf_noconst(ctx) ((ctx)->buf) -#define EVP_CIPHER_CTX_encrypting(ctx) ((ctx)->encrypt) -#define EVP_CIPHER_CTX_SIZE sizeof(EVP_CIPHER_CTX) - -#ifndef HAVE_WOLFSSL -#define EVP_MD_CTX_reset(X) EVP_MD_CTX_cleanup(X) -#define EVP_CIPHER_CTX_reset(X) EVP_CIPHER_CTX_cleanup(X) -#endif -#define X509_get0_notBefore(X) X509_get_notBefore(X) -#define X509_get0_notAfter(X) X509_get_notAfter(X) -#endif - -#ifndef TLS1_3_VERSION -#define SSL_CTX_set_ciphersuites(X,Y) 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -int check_openssl_compatibility(); - -#ifdef __cplusplus -} -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/strfunc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/strfunc.h deleted file mode 100644 index b2b293e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/strfunc.h +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef STRFUNC_INCLUDED -#define STRFUNC_INCLUDED - -typedef struct st_typelib TYPELIB; - -ulonglong find_set(const TYPELIB *lib, - const char *x, size_t length, CHARSET_INFO *cs, - char **err_pos, uint *err_len, bool *set_warning); -ulonglong find_set_from_flags(TYPELIB *lib, uint default_name, - ulonglong cur_set, ulonglong default_set, - const char *str, uint length, CHARSET_INFO *cs, - char **err_pos, uint *err_len, bool *set_warning); -uint find_type(const TYPELIB *lib, const char *find, size_t length, - bool part_match); -uint find_type2(const TYPELIB *lib, const char *find, size_t length, - CHARSET_INFO *cs); -void unhex_type2(TYPELIB *lib); -uint check_word(TYPELIB *lib, const char *val, const char *end, - const char **end_of_word); -int find_string_in_array(LEX_CSTRING * const haystack, - LEX_CSTRING * const needle, - CHARSET_INFO * const cs); -const char *flagset_to_string(THD *thd, LEX_CSTRING *result, ulonglong set, - const char *lib[]); -const char *set_to_string(THD *thd, LEX_CSTRING *result, ulonglong set, - const char *lib[]); - -/* - These functions were protected by INNODB_COMPATIBILITY_HOOKS - */ -uint strconvert(CHARSET_INFO *from_cs, const char *from, size_t from_length, - CHARSET_INFO *to_cs, char *to, size_t to_length, uint *errors); - -#endif /* STRFUNC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/structs.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/structs.h deleted file mode 100644 index 27acb9e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/structs.h +++ /dev/null @@ -1,885 +0,0 @@ -#ifndef STRUCTS_INCLUDED -#define STRUCTS_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. - Copyright (c) 2009, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - - -/* The old structures from unireg */ - -#include "sql_plugin.h" /* plugin_ref */ -#include "sql_const.h" /* MAX_REFLENGTH */ -#include "my_time.h" /* enum_mysql_timestamp_type */ -#include "thr_lock.h" /* thr_lock_type */ -#include "my_base.h" /* ha_rows, ha_key_alg */ -#include /* USERNAME_LENGTH */ -#include "sql_bitmap.h" - -struct TABLE; -class Type_handler; -class Field; -class Index_statistics; - -class THD; - -typedef struct st_date_time_format { - uchar positions[8]; - char time_separator; /* Separator between hour and minute */ - uint flag; /* For future */ - LEX_CSTRING format; -} DATE_TIME_FORMAT; - - -typedef struct st_keyfile_info { /* used with ha_info() */ - uchar ref[MAX_REFLENGTH]; /* Pointer to current row */ - uchar dupp_ref[MAX_REFLENGTH]; /* Pointer to dupp row */ - uint ref_length; /* Length of ref (1-8) */ - uint block_size; /* index block size */ - File filenr; /* (uniq) filenr for table */ - ha_rows records; /* Records i datafilen */ - ha_rows deleted; /* Deleted records */ - ulonglong data_file_length; /* Length off data file */ - ulonglong max_data_file_length; /* Length off data file */ - ulonglong index_file_length; - ulonglong max_index_file_length; - ulonglong delete_length; /* Free bytes */ - ulonglong auto_increment_value; - int errkey,sortkey; /* Last errorkey and sorted by */ - time_t create_time; /* When table was created */ - time_t check_time; - time_t update_time; - ulong mean_rec_length; /* physical reclength */ -} KEYFILE_INFO; - - -typedef struct st_key_part_info { /* Info about a key part */ - Field *field; /* the Field object for the indexed - prefix of the original table Field. - NOT necessarily the original Field */ - uint offset; /* Offset in record (from 0) */ - uint null_offset; /* Offset to null_bit in record */ - /* Length of key part in bytes, excluding NULL flag and length bytes */ - uint16 length; - /* - Number of bytes required to store the keypart value. This may be - different from the "length" field as it also counts - - possible NULL-flag byte (see HA_KEY_NULL_LENGTH) - - possible HA_KEY_BLOB_LENGTH bytes needed to store actual value length. - */ - uint16 store_length; - uint16 key_type; - uint16 fieldnr; /* Fieldnr begins counting from 1 */ - uint16 key_part_flag; /* 0 or HA_REVERSE_SORT */ - uint8 type; - uint8 null_bit; /* Position to null_bit */ -} KEY_PART_INFO ; - -class engine_option_value; -struct ha_index_option_struct; - -typedef struct st_key { - uint key_length; /* Tot length of key */ - ulong flags; /* dupp key and pack flags */ - uint user_defined_key_parts; /* How many key_parts */ - uint usable_key_parts; /* Should normally be = user_defined_key_parts */ - uint ext_key_parts; /* Number of key parts in extended key */ - ulong ext_key_flags; /* Flags for extended key */ - /* - Parts of primary key that are in the extension of this index. - - Example: if this structure describes idx1, which is defined as - INDEX idx1 (pk2, col2) - and pk is defined as: - PRIMARY KEY (pk1, pk2) - then - pk1 is in the extension idx1, ext_key_part_map.is_set(0) == true - pk2 is explicitly present in idx1, it is not in the extension, so - ext_key_part_map.is_set(1) == false - */ - key_part_map ext_key_part_map; - /* - Bitmap of indexes having common parts with this index - (only key parts from key definitions are taken into account) - */ - key_map overlapped; - /* Set of keys constraint correlated with this key */ - key_map constraint_correlated; - LEX_CSTRING name; - uint block_size; - enum ha_key_alg algorithm; - /* - The flag is on if statistical data for the index prefixes - has to be taken from the system statistical tables. - */ - bool is_statistics_from_stat_tables; - /* - Note that parser is used when the table is opened for use, and - parser_name is used when the table is being created. - */ - union - { - plugin_ref parser; /* Fulltext [pre]parser */ - LEX_CSTRING *parser_name; /* Fulltext [pre]parser name */ - }; - KEY_PART_INFO *key_part; - /* Unique name for cache; db + \0 + table_name + \0 + key_name + \0 */ - uchar *cache_name; - /* - Array of AVG(#records with the same field value) for 1st ... Nth key part. - 0 means 'not known'. - For temporary heap tables this member is NULL. - */ - ulong *rec_per_key; - - /* - This structure is used for statistical data on the index - that has been read from the statistical table index_stat - */ - Index_statistics *read_stats; - /* - This structure is used for statistical data on the index that - is collected by the function collect_statistics_for_table - */ - Index_statistics *collected_stats; - - TABLE *table; - LEX_CSTRING comment; - /** reference to the list of options or NULL */ - engine_option_value *option_list; - ha_index_option_struct *option_struct; /* structure with parsed options */ - - double actual_rec_per_key(uint i); - - bool without_overlaps; -} KEY; - - -struct st_join_table; - -typedef struct st_reginfo { /* Extra info about reg */ - struct st_join_table *join_tab; /* Used by SELECT() */ - enum thr_lock_type lock_type; /* How database is used */ - bool not_exists_optimize; - /* - TRUE <=> range optimizer found that there is no rows satisfying - table conditions. - */ - bool impossible_range; -} REGINFO; - - -/* - Originally MySQL used MYSQL_TIME structure inside server only, but since - 4.1 it's exported to user in the new client API. Define aliases for - new names to keep existing code simple. -*/ - -typedef enum enum_mysql_timestamp_type timestamp_type; - - -typedef struct { - ulong year,month,day,hour; - ulonglong minute,second,second_part; - bool neg; -} INTERVAL; - - -typedef struct st_known_date_time_format { - const char *format_name; - const char *date_format; - const char *datetime_format; - const char *time_format; -} KNOWN_DATE_TIME_FORMAT; - -extern const char *show_comp_option_name[]; - -typedef int *(*update_var)(THD *, struct st_mysql_show_var *); - -struct USER_AUTH : public Sql_alloc -{ - LEX_CSTRING plugin, auth_str, pwtext; - USER_AUTH *next; - USER_AUTH() : next(NULL) - { - plugin.str= auth_str.str= ""; - pwtext.str= NULL; - plugin.length= auth_str.length= pwtext.length= 0; - } -}; - -struct AUTHID -{ - LEX_CSTRING user, host; - void init() { memset(this, 0, sizeof(*this)); } - void copy(MEM_ROOT *root, const LEX_CSTRING *usr, const LEX_CSTRING *host); - bool is_role() const { return user.str[0] && !host.str[0]; } - void set_lex_string(LEX_CSTRING *l, char *buf) - { - if (is_role()) - *l= user; - else - { - l->str= buf; - l->length= strxmov(buf, user.str, "@", host.str, NullS) - buf; - } - } - void parse(const char *str, size_t length); - bool read_from_mysql_proc_row(THD *thd, TABLE *table); -}; - - -struct LEX_USER: public AUTHID -{ - USER_AUTH *auth; - bool has_auth() - { - return auth && (auth->plugin.length || auth->auth_str.length || auth->pwtext.length); - } -}; - -/* - This structure specifies the maximum amount of resources which - can be consumed by each account. Zero value of a member means - there is no limit. -*/ -typedef struct user_resources { - /* Maximum number of queries/statements per hour. */ - uint questions; - /* - Maximum number of updating statements per hour (which statements are - updating is defined by sql_command_flags array). - */ - uint updates; - /* Maximum number of connections established per hour. */ - uint conn_per_hour; - /* - Maximum number of concurrent connections. If -1 then no new - connections allowed - */ - int user_conn; - /* Max query timeout */ - double max_statement_time; - - /* - Values of this enum and specified_limits member are used by the - parser to store which user limits were specified in GRANT statement. - */ - enum {QUERIES_PER_HOUR= 1, UPDATES_PER_HOUR= 2, CONNECTIONS_PER_HOUR= 4, - USER_CONNECTIONS= 8, MAX_STATEMENT_TIME= 16}; - uint specified_limits; -} USER_RESOURCES; - - -/* - This structure is used for counting resources consumed and for checking - them against specified user limits. -*/ -typedef struct user_conn { - /* - Pointer to user+host key (pair separated by '\0') defining the entity - for which resources are counted (By default it is user account thus - priv_user/priv_host pair is used. If --old-style-user-limits option - is enabled, resources are counted for each user+host separately). - */ - char *user; - /* Pointer to host part of the key. */ - char *host; - /** - The moment of time when per hour counters were reset last time - (i.e. start of "hour" for conn_per_hour, updates, questions counters). - */ - ulonglong reset_utime; - /* Total length of the key. */ - uint len; - /* Current amount of concurrent connections for this account. */ - int connections; - /* - Current number of connections per hour, number of updating statements - per hour and total number of statements per hour for this account. - */ - uint conn_per_hour, updates, questions; - /* Maximum amount of resources which account is allowed to consume. */ - USER_RESOURCES user_resources; -} USER_CONN; - -typedef struct st_user_stats -{ - char user[MY_MAX(USERNAME_LENGTH, LIST_PROCESS_HOST_LEN) + 1]; - // Account name the user is mapped to when this is a user from mapped_user. - // Otherwise, the same value as user. - char priv_user[MY_MAX(USERNAME_LENGTH, LIST_PROCESS_HOST_LEN) + 1]; - uint user_name_length; - uint total_connections; - uint total_ssl_connections; - uint concurrent_connections; - time_t connected_time; // in seconds - ha_rows rows_read, rows_sent; - ha_rows rows_updated, rows_deleted, rows_inserted; - ulonglong bytes_received; - ulonglong bytes_sent; - ulonglong binlog_bytes_written; - ulonglong select_commands, update_commands, other_commands; - ulonglong commit_trans, rollback_trans; - ulonglong denied_connections, lost_connections, max_statement_time_exceeded; - ulonglong access_denied_errors; - ulonglong empty_queries; - double busy_time; // in seconds - double cpu_time; // in seconds -} USER_STATS; - -typedef struct st_table_stats -{ - char table[NAME_LEN * 2 + 2]; // [db] + '\0' + [table] + '\0' - size_t table_name_length; - ulonglong rows_read, rows_changed; - ulonglong rows_changed_x_indexes; - /* Stores enum db_type, but forward declarations cannot be done */ - int engine_type; -} TABLE_STATS; - -typedef struct st_index_stats -{ - // [db] + '\0' + [table] + '\0' + [index] + '\0' - char index[NAME_LEN * 3 + 3]; - size_t index_name_length; /* Length of 'index' */ - ulonglong rows_read; -} INDEX_STATS; - - - /* Bits in form->update */ -#define REG_MAKE_DUPP 1U /* Make a copy of record when read */ -#define REG_NEW_RECORD 2U /* Write a new record if not found */ -#define REG_UPDATE 4U /* Uppdate record */ -#define REG_DELETE 8U /* Delete found record */ -#define REG_PROG 16U /* User is updating database */ -#define REG_CLEAR_AFTER_WRITE 32U -#define REG_MAY_BE_UPDATED 64U -#define REG_AUTO_UPDATE 64U /* Used in D-forms for scroll-tables */ -#define REG_OVERWRITE 128U -#define REG_SKIP_DUP 256U - - /* Bits in form->status */ -#define STATUS_NO_RECORD (1U+2U) /* Record isn't usable */ -#define STATUS_GARBAGE 1U -#define STATUS_NOT_FOUND 2U /* No record in database when needed */ -#define STATUS_NO_PARENT 4U /* Parent record wasn't found */ -#define STATUS_NOT_READ 8U /* Record isn't read */ -#define STATUS_UPDATED 16U /* Record is updated by formula */ -#define STATUS_NULL_ROW 32U /* table->null_row is set */ -#define STATUS_DELETED 64U - -/* - Such interval is "discrete": it is the set of - { auto_inc_interval_min + k * increment, - 0 <= k <= (auto_inc_interval_values-1) } - Where "increment" is maintained separately by the user of this class (and is - currently only thd->variables.auto_increment_increment). - It mustn't derive from Sql_alloc, because SET INSERT_ID needs to - allocate memory which must stay allocated for use by the next statement. -*/ -class Discrete_interval { -private: - ulonglong interval_min; - ulonglong interval_values; - ulonglong interval_max; // excluded bound. Redundant. -public: - Discrete_interval *next; // used when linked into Discrete_intervals_list - void replace(ulonglong start, ulonglong val, ulonglong incr) - { - interval_min= start; - interval_values= val; - interval_max= (val == ULONGLONG_MAX) ? val : start + val * incr; - } - Discrete_interval(ulonglong start, ulonglong val, ulonglong incr) : - next(NULL) { replace(start, val, incr); }; - Discrete_interval() : next(NULL) { replace(0, 0, 0); }; - ulonglong minimum() const { return interval_min; }; - ulonglong values() const { return interval_values; }; - ulonglong maximum() const { return interval_max; }; - /* - If appending [3,5] to [1,2], we merge both in [1,5] (they should have the - same increment for that, user of the class has to ensure that). That is - just a space optimization. Returns 0 if merge succeeded. - */ - bool merge_if_contiguous(ulonglong start, ulonglong val, ulonglong incr) - { - if (interval_max == start) - { - if (val == ULONGLONG_MAX) - { - interval_values= interval_max= val; - } - else - { - interval_values+= val; - interval_max= start + val * incr; - } - return 0; - } - return 1; - }; -}; - -/* List of Discrete_interval objects */ -class Discrete_intervals_list { -private: - Discrete_interval *head; - Discrete_interval *tail; - /* - When many intervals are provided at the beginning of the execution of a - statement (in a replication slave or SET INSERT_ID), "current" points to - the interval being consumed by the thread now (so "current" goes from - "head" to "tail" then to NULL). - */ - Discrete_interval *current; - uint elements; // number of elements - void set_members(Discrete_interval *h, Discrete_interval *t, - Discrete_interval *c, uint el) - { - head= h; - tail= t; - current= c; - elements= el; - } - void operator=(Discrete_intervals_list &); /* prevent use of these */ - Discrete_intervals_list(const Discrete_intervals_list &); - -public: - Discrete_intervals_list() : head(NULL), current(NULL), elements(0) {}; - void empty_no_free() - { - set_members(NULL, NULL, NULL, 0); - } - void empty() - { - for (Discrete_interval *i= head; i;) - { - Discrete_interval *next= i->next; - delete i; - i= next; - } - empty_no_free(); - } - void copy_shallow(const Discrete_intervals_list * dli) - { - head= dli->get_head(); - tail= dli->get_tail(); - current= dli->get_current(); - elements= dli->nb_elements(); - } - void swap (Discrete_intervals_list * dli) - { - Discrete_interval *h, *t, *c; - uint el; - h= dli->get_head(); - t= dli->get_tail(); - c= dli->get_current(); - el= dli->nb_elements(); - dli->copy_shallow(this); - set_members(h, t, c, el); - } - const Discrete_interval* get_next() - { - Discrete_interval *tmp= current; - if (current != NULL) - current= current->next; - return tmp; - } - ~Discrete_intervals_list() { empty(); }; - bool append(ulonglong start, ulonglong val, ulonglong incr); - bool append(Discrete_interval *interval); - ulonglong minimum() const { return (head ? head->minimum() : 0); }; - ulonglong maximum() const { return (head ? tail->maximum() : 0); }; - uint nb_elements() const { return elements; } - Discrete_interval* get_head() const { return head; }; - Discrete_interval* get_tail() const { return tail; }; - Discrete_interval* get_current() const { return current; }; -}; - - -/* - DDL options: - - CREATE IF NOT EXISTS - - DROP IF EXISTS - - CREATE LIKE - - REPLACE -*/ -struct DDL_options_st -{ -public: - enum Options - { - OPT_NONE= 0, - OPT_IF_NOT_EXISTS= 2, // CREATE TABLE IF NOT EXISTS - OPT_LIKE= 4, // CREATE TABLE LIKE - OPT_OR_REPLACE= 16, // CREATE OR REPLACE TABLE - OPT_OR_REPLACE_SLAVE_GENERATED= 32,// REPLACE was added on slave, it was - // not in the original query on master. - OPT_IF_EXISTS= 64 - }; - -private: - Options m_options; - -public: - Options create_like_options() const - { - return (DDL_options_st::Options) - (((uint) m_options) & (OPT_IF_NOT_EXISTS | OPT_OR_REPLACE)); - } - void init() { m_options= OPT_NONE; } - void init(Options options) { m_options= options; } - void set(Options other) - { - m_options= other; - } - void set(const DDL_options_st other) - { - m_options= other.m_options; - } - bool if_not_exists() const { return m_options & OPT_IF_NOT_EXISTS; } - bool or_replace() const { return m_options & OPT_OR_REPLACE; } - bool or_replace_slave_generated() const - { return m_options & OPT_OR_REPLACE_SLAVE_GENERATED; } - bool like() const { return m_options & OPT_LIKE; } - bool if_exists() const { return m_options & OPT_IF_EXISTS; } - void add(const DDL_options_st::Options other) - { - m_options= (Options) ((uint) m_options | (uint) other); - } - void add(const DDL_options_st &other) - { - add(other.m_options); - } - DDL_options_st operator|(const DDL_options_st &other) - { - add(other.m_options); - return *this; - } - DDL_options_st operator|=(DDL_options_st::Options other) - { - add(other); - return *this; - } -}; - - -class DDL_options: public DDL_options_st -{ -public: - DDL_options() { init(); } - DDL_options(Options options) { init(options); } - DDL_options(const DDL_options_st &options) - { DDL_options_st::operator=(options); } -}; - - -struct Lex_length_and_dec_st -{ -private: - const char *m_length; - const char *m_dec; -public: - void set(const char *length, const char *dec) - { - m_length= length; - m_dec= dec; - } - const char *length() const { return m_length; } - const char *dec() const { return m_dec; } -}; - - -struct Lex_field_type_st: public Lex_length_and_dec_st -{ -private: - const Type_handler *m_handler; - void set(const Type_handler *handler, const char *length, const char *dec) - { - m_handler= handler; - Lex_length_and_dec_st::set(length, dec); - } -public: - void set(const Type_handler *handler, Lex_length_and_dec_st length_and_dec) - { - m_handler= handler; - Lex_length_and_dec_st::operator=(length_and_dec); - } - void set_handler_length_flags(const Type_handler *handler, const char *length, - uint32 flags); - void set(const Type_handler *handler, const char *length) - { - set(handler, length, 0); - } - void set(const Type_handler *handler) - { - set(handler, 0, 0); - } - void set_handler(const Type_handler *handler) - { - m_handler= handler; - } - const Type_handler *type_handler() const { return m_handler; } -}; - - -struct Lex_dyncol_type_st: public Lex_length_and_dec_st -{ -private: - int m_type; // enum_dynamic_column_type is not visible here, so use int -public: - void set(int type, const char *length, const char *dec) - { - m_type= type; - Lex_length_and_dec_st::set(length, dec); - } - void set(int type, Lex_length_and_dec_st length_and_dec) - { - m_type= type; - Lex_length_and_dec_st::operator=(length_and_dec); - } - void set(int type, const char *length) - { - set(type, length, 0); - } - void set(int type) - { - set(type, 0, 0); - } - int dyncol_type() const { return m_type; } -}; - - -struct Lex_spblock_handlers_st -{ -public: - int hndlrs; - void init(int count) { hndlrs= count; } -}; - - -struct Lex_spblock_st: public Lex_spblock_handlers_st -{ -public: - int vars; - int conds; - int curs; - void init() - { - vars= conds= hndlrs= curs= 0; - } - void init_using_vars(uint nvars) - { - vars= nvars; - conds= hndlrs= curs= 0; - } - void join(const Lex_spblock_st &b1, const Lex_spblock_st &b2) - { - vars= b1.vars + b2.vars; - conds= b1.conds + b2.conds; - hndlrs= b1.hndlrs + b2.hndlrs; - curs= b1.curs + b2.curs; - } -}; - - -class Lex_spblock: public Lex_spblock_st -{ -public: - Lex_spblock() { init(); } - Lex_spblock(const Lex_spblock_handlers_st &other) - { - vars= conds= curs= 0; - hndlrs= other.hndlrs; - } -}; - - -struct Lex_for_loop_bounds_st -{ -public: - class sp_assignment_lex *m_index; // The first iteration value (or cursor) - class sp_assignment_lex *m_target_bound; // The last iteration value - int8 m_direction; - bool m_implicit_cursor; - bool is_for_loop_cursor() const { return m_target_bound == NULL; } -}; - - -class Lex_for_loop_bounds_intrange: public Lex_for_loop_bounds_st -{ -public: - Lex_for_loop_bounds_intrange(int8 direction, - class sp_assignment_lex *left_expr, - class sp_assignment_lex *right_expr) - { - m_direction= direction; - m_index= direction > 0 ? left_expr : right_expr; - m_target_bound= direction > 0 ? right_expr : left_expr; - m_implicit_cursor= false; - } -}; - - -struct Lex_for_loop_st -{ -public: - class sp_variable *m_index; // The first iteration value (or cursor) - class sp_variable *m_target_bound; // The last iteration value - int m_cursor_offset; - int8 m_direction; - bool m_implicit_cursor; - void init() - { - m_index= 0; - m_target_bound= 0; - m_direction= 0; - m_implicit_cursor= false; - } - void init(const Lex_for_loop_st &other) - { - *this= other; - } - bool is_for_loop_cursor() const { return m_target_bound == NULL; } - bool is_for_loop_explicit_cursor() const - { - return is_for_loop_cursor() && !m_implicit_cursor; - } -}; - - -enum trim_spec { TRIM_LEADING, TRIM_TRAILING, TRIM_BOTH }; - -struct Lex_trim_st -{ - Item *m_remove; - Item *m_source; - trim_spec m_spec; -public: - void set(trim_spec spec, Item *remove, Item *source) - { - m_spec= spec; - m_remove= remove; - m_source= source; - } - void set(trim_spec spec, Item *source) - { - set(spec, NULL, source); - } - Item *make_item_func_trim_std(THD *thd) const; - Item *make_item_func_trim_oracle(THD *thd) const; - Item *make_item_func_trim(THD *thd) const; -}; - - -class Lex_trim: public Lex_trim_st -{ -public: - Lex_trim(trim_spec spec, Item *source) { set(spec, source); } -}; - - -class st_select_lex; - -class Lex_select_lock -{ -public: - struct - { - uint defined_lock:1; - uint update_lock:1; - uint defined_timeout:1; - }; - ulong timeout; - - - void empty() - { - defined_lock= update_lock= defined_timeout= FALSE; - timeout= 0; - } - void set_to(st_select_lex *sel); -}; - -class Lex_select_limit -{ -public: - bool explicit_limit; - Item *select_limit, *offset_limit; - - void empty() - { - explicit_limit= FALSE; - select_limit= offset_limit= NULL; - } -}; - -struct st_order; - -class Load_data_param -{ -protected: - CHARSET_INFO *m_charset; // Character set of the file - ulonglong m_fixed_length; // Sum of target field lengths for fixed format - bool m_is_fixed_length; - bool m_use_blobs; -public: - Load_data_param(CHARSET_INFO *cs, bool is_fixed_length): - m_charset(cs), - m_fixed_length(0), - m_is_fixed_length(is_fixed_length), - m_use_blobs(false) - { } - bool add_outvar_field(THD *thd, const Field *field); - bool add_outvar_user_var(THD *thd); - CHARSET_INFO *charset() const { return m_charset; } - bool is_fixed_length() const { return m_is_fixed_length; } - bool use_blobs() const { return m_use_blobs; } -}; - - -class Load_data_outvar -{ -public: - virtual ~Load_data_outvar() {} - virtual bool load_data_set_null(THD *thd, const Load_data_param *param)= 0; - virtual bool load_data_set_value(THD *thd, const char *pos, uint length, - const Load_data_param *param)= 0; - virtual bool load_data_set_no_data(THD *thd, const Load_data_param *param)= 0; - virtual void load_data_print_for_log_event(THD *thd, class String *to) const= 0; - virtual bool load_data_add_outvar(THD *thd, Load_data_param *param) const= 0; - virtual uint load_data_fixed_length() const= 0; -}; - - -class Timeval: public timeval -{ -protected: - Timeval() { } -public: - Timeval(my_time_t sec, ulong usec) - { - tv_sec= sec; - tv_usec= usec; - } - explicit Timeval(const timeval &tv) - :timeval(tv) - { } -}; - - -#endif /* STRUCTS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sys_vars_shared.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/sys_vars_shared.h deleted file mode 100644 index bc48d1f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/sys_vars_shared.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef SYS_VARS_SHARED_INCLUDED -#define SYS_VARS_SHARED_INCLUDED - -/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/** - @file - "protected" interface to sys_var - server configuration variables. - - This header is included by files implementing support and utility - functions of sys_var's (set_var.cc) and files implementing - classes in the sys_var hierarchy (sql_plugin.cc) -*/ - -#include -#include "set_var.h" - -extern bool throw_bounds_warning(THD *thd, const char *name,const char *v); -extern bool throw_bounds_warning(THD *thd, const char *name, - bool fixed, bool is_unsigned, longlong v); -extern bool throw_bounds_warning(THD *thd, const char *name, bool fixed, - double v); -extern sys_var *intern_find_sys_var(const char *str, size_t length); - -extern sys_var_chain all_sys_vars; - -/** wrapper to hide a mutex and an rwlock under a common interface */ -class PolyLock -{ -public: - virtual void rdlock()= 0; - virtual void wrlock()= 0; - virtual void unlock()= 0; - virtual ~PolyLock() {} -}; - -class PolyLock_mutex: public PolyLock -{ - mysql_mutex_t *mutex; -public: - PolyLock_mutex(mysql_mutex_t *arg): mutex(arg) {} - void rdlock() { mysql_mutex_lock(mutex); } - void wrlock() { mysql_mutex_lock(mutex); } - void unlock() { mysql_mutex_unlock(mutex); } -}; - -class PolyLock_rwlock: public PolyLock -{ - mysql_rwlock_t *rwlock; -public: - PolyLock_rwlock(mysql_rwlock_t *arg): rwlock(arg) {} - void rdlock() { mysql_rwlock_rdlock(rwlock); } - void wrlock() { mysql_rwlock_wrlock(rwlock); } - void unlock() { mysql_rwlock_unlock(rwlock); } -}; - -class AutoWLock -{ - PolyLock *lock; -public: - AutoWLock(PolyLock *l) : lock(l) { if (lock) lock->wrlock(); } - ~AutoWLock() { if (lock) lock->unlock(); } -}; - -class AutoRLock -{ - PolyLock *lock; -public: - AutoRLock(PolyLock *l) : lock(l) { if (lock) lock->rdlock(); } - ~AutoRLock() { if (lock) lock->unlock(); } -}; - - -#endif /* SYS_VARS_SHARED_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/t_ctype.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/t_ctype.h deleted file mode 100644 index 9164c62..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/t_ctype.h +++ /dev/null @@ -1,255 +0,0 @@ -/* Copyright (C) 2000 MySQL AB - Use is subject to license terms - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Copyright (C) 1998, 1999 by Pruet Boonma, all rights reserved. - Copyright (C) 1998 by Theppitak Karoonboonyanan, all rights reserved. - Permission to use, copy, modify, distribute and sell this software - and its documentation for any purpose is hereby granted without fee, - provided that the above copyright notice appear in all copies. - Smaphan Raruenrom and Pruet Boonma makes no representations about - the suitability of this software for any purpose. It is provided - "as is" without express or implied warranty. -*/ - -/* LC_COLLATE category + Level information */ - -#ifndef _t_ctype_h -#define _t_ctype_h - -#define TOT_LEVELS 5 -#define LAST_LEVEL 4 /* TOT_LEVELS - 1 */ - -#define IGNORE 0 - - -/* level 1 symbols & order */ -enum l1_symbols { - L1_08 = TOT_LEVELS, - L1_18, - L1_28, - L1_38, - L1_48, - L1_58, - L1_68, - L1_78, - L1_88, - L1_98, - L1_A8, - L1_B8, - L1_C8, - L1_D8, - L1_E8, - L1_F8, - L1_G8, - L1_H8, - L1_I8, - L1_J8, - L1_K8, - L1_L8, - L1_M8, - L1_N8, - L1_O8, - L1_P8, - L1_Q8, - L1_R8, - L1_S8, - L1_T8, - L1_U8, - L1_V8, - L1_W8, - L1_X8, - L1_Y8, - L1_Z8, - L1_KO_KAI, - L1_KHO_KHAI, - L1_KHO_KHUAT, - L1_KHO_KHWAI, - L1_KHO_KHON, - L1_KHO_RAKHANG, - L1_NGO_NGU, - L1_CHO_CHAN, - L1_CHO_CHING, - L1_CHO_CHANG, - L1_SO_SO, - L1_CHO_CHOE, - L1_YO_YING, - L1_DO_CHADA, - L1_TO_PATAK, - L1_THO_THAN, - L1_THO_NANGMONTHO, - L1_THO_PHUTHAO, - L1_NO_NEN, - L1_DO_DEK, - L1_TO_TAO, - L1_THO_THUNG, - L1_THO_THAHAN, - L1_THO_THONG, - L1_NO_NU, - L1_BO_BAIMAI, - L1_PO_PLA, - L1_PHO_PHUNG, - L1_FO_FA, - L1_PHO_PHAN, - L1_FO_FAN, - L1_PHO_SAMPHAO, - L1_MO_MA, - L1_YO_YAK, - L1_RO_RUA, - L1_RU, - L1_LO_LING, - L1_LU, - L1_WO_WAEN, - L1_SO_SALA, - L1_SO_RUSI, - L1_SO_SUA, - L1_HO_HIP, - L1_LO_CHULA, - L1_O_ANG, - L1_HO_NOKHUK, - L1_NKHIT, - L1_SARA_A, - L1_MAI_HAN_AKAT, - L1_SARA_AA, - L1_SARA_AM, - L1_SARA_I, - L1_SARA_II, - L1_SARA_UE, - L1_SARA_UEE, - L1_SARA_U, - L1_SARA_UU, - L1_SARA_E, - L1_SARA_AE, - L1_SARA_O, - L1_SARA_AI_MAIMUAN, - L1_SARA_AI_MAIMALAI -}; - -/* level 2 symbols & order */ -enum l2_symbols { - L2_BLANK = TOT_LEVELS, - L2_THAII, - L2_YAMAK, - L2_PINTHU, - L2_GARAN, - L2_TYKHU, - L2_TONE1, - L2_TONE2, - L2_TONE3, - L2_TONE4 -}; - -/* level 3 symbols & order */ -enum l3_symbols { - L3_BLANK = TOT_LEVELS, - L3_SPACE, - L3_NB_SACE, - L3_LOW_LINE, - L3_HYPHEN, - L3_COMMA, - L3_SEMICOLON, - L3_COLON, - L3_EXCLAMATION, - L3_QUESTION, - L3_SOLIDUS, - L3_FULL_STOP, - L3_PAIYAN_NOI, - L3_MAI_YAMOK, - L3_GRAVE, - L3_CIRCUMFLEX, - L3_TILDE, - L3_APOSTROPHE, - L3_QUOTATION, - L3_L_PARANTHESIS, - L3_L_BRACKET, - L3_L_BRACE, - L3_R_BRACE, - L3_R_BRACKET, - L3_R_PARENTHESIS, - L3_AT, - L3_BAHT, - L3_DOLLAR, - L3_FONGMAN, - L3_ANGKHANKHU, - L3_KHOMUT, - L3_ASTERISK, - L3_BK_SOLIDUS, - L3_AMPERSAND, - L3_NUMBER, - L3_PERCENT, - L3_PLUS, - L3_LESS_THAN, - L3_EQUAL, - L3_GREATER_THAN, - L3_V_LINE -}; - -/* level 4 symbols & order */ -enum l4_symbols { - L4_BLANK = TOT_LEVELS, - L4_MIN, - L4_CAP, - L4_EXT -}; - -enum level_symbols { - L_UPRUPR = TOT_LEVELS, - L_UPPER, - L_MIDDLE, - L_LOWER -}; - -#define _is(c) (t_ctype[(c)][LAST_LEVEL]) -#define _level 8 -#define _consnt 16 -#define _ldvowel 32 -#define _fllwvowel 64 -#define _uprvowel 128 -#define _lwrvowel 256 -#define _tone 512 -#define _diacrt1 1024 -#define _diacrt2 2048 -#define _combine 4096 -#define _stone 8192 -#define _tdig 16384 -#define _rearvowel (_fllwvowel | _uprvowel | _lwrvowel) -#define _diacrt (_diacrt1 | _diacrt2) -#define levelof(c) ( _is(c) & _level ) -#define isthai(c) ( (c) >= 128 ) -#define istalpha(c) ( _is(c) & (_consnt|_ldvowel|_rearvowel|\ - _tone|_diacrt1|_diacrt2) ) -#define isconsnt(c) ( _is(c) & _consnt ) -#define isldvowel(c) ( _is(c) & _ldvowel ) -#define isfllwvowel(c) ( _is(c) & _fllwvowel ) -#define ismidvowel(c) ( _is(c) & (_ldvowel|_fllwvowel) ) -#define isuprvowel(c) ( _is(c) & _uprvowel ) -#define islwrvowel(c) ( _is(c) & _lwrvowel ) -#define isuprlwrvowel(c) ( _is(c) & (_lwrvowel | _uprvowel)) -#define isrearvowel(c) ( _is(c) & _rearvowel ) -#define isvowel(c) ( _is(c) & (_ldvowel|_rearvowel) ) -#define istone(c) ( _is(c) & _tone ) -#define isunldable(c) ( _is(c) & (_rearvowel|_tone|_diacrt1|_diacrt2) ) -#define iscombinable(c) ( _is(c) & _combine ) -#define istdigit(c) ( _is(c) & _tdig ) -#define isstone(c) ( _is(c) & _stone ) -#define isdiacrt1(c) ( _is(c) & _diacrt1) -#define isdiacrt2(c) ( _is(c) & _diacrt2) -#define isdiacrt(c) ( _is(c) & _diacrt) - -/* Function prototype called by sql/field.cc */ -void ThNormalize(uchar* ptr, uint field_length, const uchar* from, uint length); - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/table.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/table.h deleted file mode 100644 index ec865f2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/table.h +++ /dev/null @@ -1,3348 +0,0 @@ -#ifndef TABLE_INCLUDED -#define TABLE_INCLUDED -/* Copyright (c) 2000, 2017, Oracle and/or its affiliates. - Copyright (c) 2009, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#include "sql_plist.h" -#include "sql_list.h" /* Sql_alloc */ -#include "mdl.h" -#include "datadict.h" -#include "sql_string.h" /* String */ -#include "lex_string.h" - -#ifndef MYSQL_CLIENT - -#include "my_cpu.h" /* LF_BACKOFF() */ -#include "hash.h" /* HASH */ -#include "handler.h" /* row_type, ha_choice, handler */ -#include "mysql_com.h" /* enum_field_types */ -#include "thr_lock.h" /* thr_lock_type */ -#include "filesort_utils.h" -#include "parse_file.h" -#include "sql_i_s.h" -#include "sql_type.h" /* vers_kind_t */ -#include "privilege.h" /* privilege_t */ - -/* Structs that defines the TABLE */ - -class Item; /* Needed by ORDER */ -typedef Item (*Item_ptr); -class Item_subselect; -class Item_field; -class GRANT_TABLE; -class st_select_lex_unit; -class st_select_lex; -class partition_info; -class COND_EQUAL; -class Security_context; -struct TABLE_LIST; -class ACL_internal_schema_access; -class ACL_internal_table_access; -class Field; -class Table_statistics; -class With_element; -struct TDC_element; -class Virtual_column_info; -class Table_triggers_list; -class TMP_TABLE_PARAM; -class SEQUENCE; -class Range_rowid_filter_cost_info; -class derived_handler; -class Pushdown_derived; -struct Name_resolution_context; - -/* - Used to identify NESTED_JOIN structures within a join (applicable only to - structures that have not been simplified away and embed more the one - element) -*/ -typedef ulonglong nested_join_map; - - -#define tmp_file_prefix "#sql" /**< Prefix for tmp tables */ -#define tmp_file_prefix_length 4 -#define TMP_TABLE_KEY_EXTRA 8 - -/** - Enumerate possible types of a table from re-execution - standpoint. - TABLE_LIST class has a member of this type. - At prepared statement prepare, this member is assigned a value - as of the current state of the database. Before (re-)execution - of a prepared statement, we check that the value recorded at - prepare matches the type of the object we obtained from the - table definition cache. - - @sa check_and_update_table_version() - @sa Execute_observer - @sa Prepared_statement::reprepare() -*/ - -enum enum_table_ref_type -{ - /** Initial value set by the parser */ - TABLE_REF_NULL= 0, - TABLE_REF_VIEW, - TABLE_REF_BASE_TABLE, - TABLE_REF_I_S_TABLE, - TABLE_REF_TMP_TABLE -}; - - -/*************************************************************************/ - -/** - Object_creation_ctx -- interface for creation context of database objects - (views, stored routines, events, triggers). Creation context -- is a set - of attributes, that should be fixed at the creation time and then be used - each time the object is parsed or executed. -*/ - -class Object_creation_ctx -{ -public: - Object_creation_ctx *set_n_backup(THD *thd); - - void restore_env(THD *thd, Object_creation_ctx *backup_ctx); - -protected: - Object_creation_ctx() {} - virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0; - - virtual void change_env(THD *thd) const = 0; - -public: - virtual ~Object_creation_ctx() - { } -}; - -/*************************************************************************/ - -/** - Default_object_creation_ctx -- default implementation of - Object_creation_ctx. -*/ - -class Default_object_creation_ctx : public Object_creation_ctx -{ -public: - CHARSET_INFO *get_client_cs() - { - return m_client_cs; - } - - CHARSET_INFO *get_connection_cl() - { - return m_connection_cl; - } - -protected: - Default_object_creation_ctx(THD *thd); - - Default_object_creation_ctx(CHARSET_INFO *client_cs, - CHARSET_INFO *connection_cl); - -protected: - virtual Object_creation_ctx *create_backup_ctx(THD *thd) const; - - virtual void change_env(THD *thd) const; - -protected: - /** - client_cs stores the value of character_set_client session variable. - The only character set attribute is used. - - Client character set is included into query context, because we save - query in the original character set, which is client character set. So, - in order to parse the query properly we have to switch client character - set on parsing. - */ - CHARSET_INFO *m_client_cs; - - /** - connection_cl stores the value of collation_connection session - variable. Both character set and collation attributes are used. - - Connection collation is included into query context, becase it defines - the character set and collation of text literals in internal - representation of query (item-objects). - */ - CHARSET_INFO *m_connection_cl; -}; - -class Query_arena; - -/*************************************************************************/ - -/** - View_creation_ctx -- creation context of view objects. -*/ - -class View_creation_ctx : public Default_object_creation_ctx, - public Sql_alloc -{ -public: - static View_creation_ctx *create(THD *thd); - - static View_creation_ctx *create(THD *thd, - TABLE_LIST *view); - -private: - View_creation_ctx(THD *thd) - : Default_object_creation_ctx(thd) - { } -}; - -/*************************************************************************/ - -/* Order clause list element */ - -typedef int (*fast_field_copier)(Field *to, Field *from); - - -typedef struct st_order { - struct st_order *next; - Item **item; /* Point at item in select fields */ - Item *item_ptr; /* Storage for initial item */ - /* - Reference to the function we are trying to optimize copy to - a temporary table - */ - fast_field_copier fast_field_copier_func; - /* Field for which above optimizer function setup */ - Field *fast_field_copier_setup; - int counter; /* position in SELECT list, correct - only if counter_used is true*/ - enum enum_order { - ORDER_NOT_RELEVANT, - ORDER_ASC, - ORDER_DESC - }; - - enum_order direction; /* Requested direction of ordering */ - bool in_field_list; /* true if in select field list */ - bool counter_used; /* parameter was counter of columns */ - Field *field; /* If tmp-table group */ - char *buff; /* If tmp-table group */ - table_map used; /* NOTE: the below is only set to 0 but is still used by eq_ref_table */ - table_map depend_map; -} ORDER; - -/** - State information for internal tables grants. - This structure is part of the TABLE_LIST, and is updated - during the ACL check process. - @sa GRANT_INFO -*/ -struct st_grant_internal_info -{ - /** True if the internal lookup by schema name was done. */ - bool m_schema_lookup_done; - /** Cached internal schema access. */ - const ACL_internal_schema_access *m_schema_access; - /** True if the internal lookup by table name was done. */ - bool m_table_lookup_done; - /** Cached internal table access. */ - const ACL_internal_table_access *m_table_access; -}; -typedef struct st_grant_internal_info GRANT_INTERNAL_INFO; - -/** - @brief The current state of the privilege checking process for the current - user, SQL statement and SQL object. - - @details The privilege checking process is divided into phases depending on - the level of the privilege to be checked and the type of object to be - accessed. Due to the mentioned scattering of privilege checking - functionality, it is necessary to keep track of the state of the - process. This information is stored in privilege, want_privilege, and - orig_want_privilege. - - A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant - members are grant_table and version. - */ -typedef struct st_grant_info -{ - /** - @brief A copy of the privilege information regarding the current host, - database, object and user. - - @details The version of this copy is found in GRANT_INFO::version. - */ - GRANT_TABLE *grant_table_user; - GRANT_TABLE *grant_table_role; - /** - @brief Used for cache invalidation when caching privilege information. - - @details The privilege information is stored on disk, with dedicated - caches residing in memory: table-level and column-level privileges, - respectively, have their own dedicated caches. - - The GRANT_INFO works as a level 1 cache with this member updated to the - current value of the global variable @c grant_version (@c static variable - in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from - the level 2 cache. The level 2 cache is the @c column_priv_hash structure - (@c static variable in sql_acl.cc) - - @see grant_version - */ - uint version; - /** - @brief The set of privileges that the current user has fulfilled for a - certain host, database, and object. - - @details This field is continually updated throughout the access checking - process. In each step the "wanted privilege" is checked against the - fulfilled privileges. When/if the intersection of these sets is empty, - access is granted. - - The set is implemented as a bitmap, with the bits defined in sql_acl.h. - */ - privilege_t privilege; - /** - @brief the set of privileges that the current user needs to fulfil in - order to carry out the requested operation. - */ - privilege_t want_privilege; - /** - Stores the requested access acl of top level tables list. Is used to - check access rights to the underlying tables of a view. - */ - privilege_t orig_want_privilege; - /** The grant state for internal tables. */ - GRANT_INTERNAL_INFO m_internal; - - st_grant_info() - :privilege(NO_ACL), - want_privilege(NO_ACL), - orig_want_privilege(NO_ACL) - { } -} GRANT_INFO; - -enum tmp_table_type -{ - NO_TMP_TABLE= 0, NON_TRANSACTIONAL_TMP_TABLE, TRANSACTIONAL_TMP_TABLE, - INTERNAL_TMP_TABLE, SYSTEM_TMP_TABLE -}; -enum release_type { RELEASE_NORMAL, RELEASE_WAIT_FOR_DROP }; - - -enum vcol_init_mode -{ - VCOL_INIT_DEPENDENCY_FAILURE_IS_WARNING= 1, - VCOL_INIT_DEPENDENCY_FAILURE_IS_ERROR= 2 - /* - There may be new flags here. - e.g. to automatically remove sql_mode dependency: - GENERATED ALWAYS AS (char_col) -> - GENERATED ALWAYS AS (RTRIM(char_col)) - */ -}; - - -enum enum_vcol_update_mode -{ - VCOL_UPDATE_FOR_READ= 0, - VCOL_UPDATE_FOR_WRITE, - VCOL_UPDATE_FOR_DELETE, - VCOL_UPDATE_INDEXED, - VCOL_UPDATE_INDEXED_FOR_UPDATE, - VCOL_UPDATE_FOR_REPLACE -}; - -/* Field visibility enums */ - -enum field_visibility_t { - VISIBLE= 0, - INVISIBLE_USER, - /* automatically added by the server. Can be queried explicitly - in SELECT, otherwise invisible from anything" */ - INVISIBLE_SYSTEM, - INVISIBLE_FULL -}; - -#define INVISIBLE_MAX_BITS 3 -#define HA_HASH_FIELD_LENGTH 8 -#define HA_HASH_KEY_LENGTH_WITHOUT_NULL 8 -#define HA_HASH_KEY_LENGTH_WITH_NULL 9 - - -int fields_in_hash_keyinfo(KEY *keyinfo); - -void setup_keyinfo_hash(KEY *key_info); - -void re_setup_keyinfo_hash(KEY *key_info); - -/** - Category of table found in the table share. -*/ -enum enum_table_category -{ - /** - Unknown value. - */ - TABLE_UNKNOWN_CATEGORY=0, - - /** - Temporary table. - The table is visible only in the session. - Therefore, - - FLUSH TABLES WITH READ LOCK - - SET GLOBAL READ_ONLY = ON - do not apply to this table. - Note that LOCK TABLE t FOR READ/WRITE - can be used on temporary tables. - Temporary tables are not part of the table cache. - */ - TABLE_CATEGORY_TEMPORARY=1, - - /** - User table. - These tables do honor: - - LOCK TABLE t FOR READ/WRITE - - FLUSH TABLES WITH READ LOCK - - SET GLOBAL READ_ONLY = ON - User tables are cached in the table cache. - */ - TABLE_CATEGORY_USER=2, - - /** - System table, maintained by the server. - These tables do honor: - - LOCK TABLE t FOR READ/WRITE - - FLUSH TABLES WITH READ LOCK - - SET GLOBAL READ_ONLY = ON - Typically, writes to system tables are performed by - the server implementation, not explicitly be a user. - System tables are cached in the table cache. - */ - TABLE_CATEGORY_SYSTEM=3, - - /** - Log tables. - These tables are an interface provided by the system - to inspect the system logs. - These tables do *not* honor: - - LOCK TABLE t FOR READ/WRITE - - FLUSH TABLES WITH READ LOCK - - SET GLOBAL READ_ONLY = ON - as there is no point in locking explicitly - a LOG table. - An example of LOG tables are: - - mysql.slow_log - - mysql.general_log, - which *are* updated even when there is either - a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect. - User queries do not write directly to these tables - (there are exceptions for log tables). - The server implementation perform writes. - Log tables are cached in the table cache. - */ - TABLE_CATEGORY_LOG=4, - - /* - Types below are read only tables, not affected by FLUSH TABLES or - MDL locks. - */ - /** - Information schema tables. - These tables are an interface provided by the system - to inspect the system metadata. - These tables do *not* honor: - - LOCK TABLE t FOR READ/WRITE - - FLUSH TABLES WITH READ LOCK - - SET GLOBAL READ_ONLY = ON - as there is no point in locking explicitly - an INFORMATION_SCHEMA table. - Nothing is directly written to information schema tables. - Note that this value is not used currently, - since information schema tables are not shared, - but implemented as session specific temporary tables. - */ - /* - TODO: Fixing the performance issues of I_S will lead - to I_S tables in the table cache, which should use - this table type. - */ - TABLE_CATEGORY_INFORMATION=5, - - /** - Performance schema tables. - These tables are an interface provided by the system - to inspect the system performance data. - These tables do *not* honor: - - LOCK TABLE t FOR READ/WRITE - - FLUSH TABLES WITH READ LOCK - - SET GLOBAL READ_ONLY = ON - as there is no point in locking explicitly - a PERFORMANCE_SCHEMA table. - An example of PERFORMANCE_SCHEMA tables are: - - performance_schema.* - which *are* updated (but not using the handler interface) - even when there is either - a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect. - User queries do not write directly to these tables - (there are exceptions for SETUP_* tables). - The server implementation perform writes. - Performance tables are cached in the table cache. - */ - TABLE_CATEGORY_PERFORMANCE=6 -}; - -typedef enum enum_table_category TABLE_CATEGORY; - -TABLE_CATEGORY get_table_category(const LEX_CSTRING *db, - const LEX_CSTRING *name); - - -typedef struct st_table_field_type -{ - LEX_CSTRING name; - LEX_CSTRING type; - LEX_CSTRING cset; -} TABLE_FIELD_TYPE; - - -typedef struct st_table_field_def -{ - uint count; - const TABLE_FIELD_TYPE *field; - uint primary_key_parts; - const uint *primary_key_columns; -} TABLE_FIELD_DEF; - - -class Table_check_intact -{ -protected: - bool has_keys; - virtual void report_error(uint code, const char *fmt, ...)= 0; - -public: - Table_check_intact(bool keys= false) : has_keys(keys) {} - virtual ~Table_check_intact() {} - - /** Checks whether a table is intact. */ - bool check(TABLE *table, const TABLE_FIELD_DEF *table_def); -}; - - -/* - If the table isn't valid, report the error to the server log only. -*/ -class Table_check_intact_log_error : public Table_check_intact -{ -protected: - void report_error(uint, const char *fmt, ...); -public: - Table_check_intact_log_error() : Table_check_intact(true) {} -}; - - -/** - Class representing the fact that some thread waits for table - share to be flushed. Is used to represent information about - such waits in MDL deadlock detector. -*/ - -class Wait_for_flush : public MDL_wait_for_subgraph -{ - MDL_context *m_ctx; - TABLE_SHARE *m_share; - uint m_deadlock_weight; -public: - Wait_for_flush(MDL_context *ctx_arg, TABLE_SHARE *share_arg, - uint deadlock_weight_arg) - : m_ctx(ctx_arg), m_share(share_arg), - m_deadlock_weight(deadlock_weight_arg) - {} - - MDL_context *get_ctx() const { return m_ctx; } - - virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor); - - virtual uint get_deadlock_weight() const; - - /** - Pointers for participating in the list of waiters for table share. - */ - Wait_for_flush *next_in_share; - Wait_for_flush **prev_in_share; -}; - - -typedef I_P_List > - Wait_for_flush_list; - - -enum open_frm_error { - OPEN_FRM_OK = 0, - OPEN_FRM_OPEN_ERROR, - OPEN_FRM_READ_ERROR, - OPEN_FRM_CORRUPTED, - OPEN_FRM_DISCOVER, - OPEN_FRM_ERROR_ALREADY_ISSUED, - OPEN_FRM_NOT_A_VIEW, - OPEN_FRM_NOT_A_TABLE, - OPEN_FRM_NEEDS_REBUILD -}; - -/** - Control block to access table statistics loaded - from persistent statistical tables -*/ - -class TABLE_STATISTICS_CB -{ - class Statistics_state - { - enum state_codes - { - EMPTY, /** data is not loaded */ - LOADING, /** data is being loaded in some connection */ - READY /** data is loaded and available for use */ - }; - int32 state; - - public: - /** No state copy */ - Statistics_state &operator=(const Statistics_state &) { return *this; } - - /** Checks if data loading have been completed */ - bool is_ready() const - { - return my_atomic_load32_explicit(const_cast(&state), - MY_MEMORY_ORDER_ACQUIRE) == READY; - } - - /** - Sets mutual exclusion for data loading - - If stats are in LOADING state, waits until state change. - - @return - @retval true atomic EMPTY -> LOADING transfer completed, ok to load - @retval false stats are in READY state, no need to load - */ - bool start_load() - { - for (;;) - { - int32 expected= EMPTY; - if (my_atomic_cas32_weak_explicit(&state, &expected, LOADING, - MY_MEMORY_ORDER_RELAXED, - MY_MEMORY_ORDER_RELAXED)) - return true; - if (expected == READY) - return false; - (void) LF_BACKOFF(); - } - } - - /** Marks data available for subsequent use */ - void end_load() - { - DBUG_ASSERT(my_atomic_load32_explicit(&state, MY_MEMORY_ORDER_RELAXED) == - LOADING); - my_atomic_store32_explicit(&state, READY, MY_MEMORY_ORDER_RELEASE); - } - - /** Restores empty state on error (e.g. OOM) */ - void abort_load() - { - DBUG_ASSERT(my_atomic_load32_explicit(&state, MY_MEMORY_ORDER_RELAXED) == - LOADING); - my_atomic_store32_explicit(&state, EMPTY, MY_MEMORY_ORDER_RELAXED); - } - }; - - class Statistics_state stats_state; - class Statistics_state hist_state; - -public: - MEM_ROOT mem_root; /* MEM_ROOT to allocate statistical data for the table */ - Table_statistics *table_stats; /* Structure to access the statistical data */ - ulong total_hist_size; /* Total size of all histograms */ - - bool histograms_are_ready() const - { - return !total_hist_size || hist_state.is_ready(); - } - - bool start_histograms_load() - { - return total_hist_size && hist_state.start_load(); - } - - void end_histograms_load() { hist_state.end_load(); } - void abort_histograms_load() { hist_state.abort_load(); } - bool stats_are_ready() const { return stats_state.is_ready(); } - bool start_stats_load() { return stats_state.start_load(); } - void end_stats_load() { stats_state.end_load(); } - void abort_stats_load() { stats_state.abort_load(); } -}; - -/** - This structure is shared between different table objects. There is one - instance of table share per one table in the database. -*/ - -struct TABLE_SHARE -{ - TABLE_SHARE() {} /* Remove gcc warning */ - - /** Category of this table. */ - TABLE_CATEGORY table_category; - - /* hash of field names (contains pointers to elements of field array) */ - HASH name_hash; /* hash of field names */ - MEM_ROOT mem_root; - TYPELIB keynames; /* Pointers to keynames */ - TYPELIB fieldnames; /* Pointer to fieldnames */ - TYPELIB *intervals; /* pointer to interval info */ - mysql_mutex_t LOCK_ha_data; /* To protect access to ha_data */ - mysql_mutex_t LOCK_share; /* To protect TABLE_SHARE */ - - TDC_element *tdc; - - LEX_CUSTRING tabledef_version; - - engine_option_value *option_list; /* text options for table */ - ha_table_option_struct *option_struct; /* structure with parsed options */ - - /* The following is copied to each TABLE on OPEN */ - Field **field; - Field **found_next_number_field; - KEY *key_info; /* data of keys in database */ - Virtual_column_info **check_constraints; - uint *blob_field; /* Index to blobs in Field arrray*/ - LEX_CUSTRING vcol_defs; /* definitions of generated columns */ - - TABLE_STATISTICS_CB stats_cb; - - uchar *default_values; /* row with default values */ - LEX_CSTRING comment; /* Comment about table */ - CHARSET_INFO *table_charset; /* Default charset of string fields */ - - MY_BITMAP *check_set; /* Fields used by check constrant */ - MY_BITMAP all_set; - /* - Key which is used for looking-up table in table cache and in the list - of thread's temporary tables. Has the form of: - "database_name\0table_name\0" + optional part for temporary tables. - - Note that all three 'table_cache_key', 'db' and 'table_name' members - must be set (and be non-zero) for tables in table cache. They also - should correspond to each other. - To ensure this one can use set_table_cache() methods. - */ - LEX_CSTRING table_cache_key; - LEX_CSTRING db; /* Pointer to db */ - LEX_CSTRING table_name; /* Table name (for open) */ - LEX_CSTRING path; /* Path to .frm file (from datadir) */ - LEX_CSTRING normalized_path; /* unpack_filename(path) */ - LEX_CSTRING connect_string; - - /* - Set of keys in use, implemented as a Bitmap. - Excludes keys disabled by ALTER TABLE ... DISABLE KEYS. - */ - key_map keys_in_use; - key_map keys_for_keyread; - ha_rows min_rows, max_rows; /* create information */ - ulong avg_row_length; /* create information */ - ulong mysql_version; /* 0 if .frm is created before 5.0 */ - ulong reclength; /* Recordlength */ - /* Stored record length. No generated-only virtual fields are included */ - ulong stored_rec_length; - - plugin_ref db_plugin; /* storage engine plugin */ - inline handlerton *db_type() const /* table_type for handler */ - { - return is_view ? view_pseudo_hton : - db_plugin ? plugin_hton(db_plugin) : NULL; - } - enum row_type row_type; /* How rows are stored */ - enum Table_type table_type; - enum tmp_table_type tmp_table; - - /** Transactional or not. */ - enum ha_choice transactional; - /** Per-page checksums or not. */ - enum ha_choice page_checksum; - - uint key_block_size; /* create key_block_size, if used */ - uint stats_sample_pages; /* number of pages to sample during - stats estimation, if used, otherwise 0. */ - enum_stats_auto_recalc stats_auto_recalc; /* Automatic recalc of stats. */ - uint null_bytes, last_null_bit_pos; - /* - Same as null_bytes, except that if there is only a 'delete-marker' in - the record then this value is 0. - */ - uint null_bytes_for_compare; - uint fields; /* number of fields */ - /* number of stored fields, purely virtual not included */ - uint stored_fields; - uint virtual_fields; /* number of purely virtual fields */ - /* number of purely virtual not stored blobs */ - uint virtual_not_stored_blob_fields; - uint null_fields; /* number of null fields */ - uint blob_fields; /* number of blob fields */ - uint varchar_fields; /* number of varchar fields */ - uint default_fields; /* number of default fields */ - uint visible_fields; /* number of visible fields */ - - uint default_expressions; - uint table_check_constraints, field_check_constraints; - - uint rec_buff_length; /* Size of table->record[] buffer */ - uint keys, key_parts; - uint ext_key_parts; /* Total number of key parts in extended keys */ - uint max_key_length, max_unique_length, total_key_length; - uint uniques; /* Number of UNIQUE index */ - uint db_create_options; /* Create options from database */ - uint db_options_in_use; /* Options in use */ - uint db_record_offset; /* if HA_REC_IN_SEQ */ - uint rowid_field_offset; /* Field_nr +1 to rowid field */ - /* Primary key index number, used in TABLE::key_info[] */ - uint primary_key; - uint next_number_index; /* autoincrement key number */ - uint next_number_key_offset; /* autoinc keypart offset in a key */ - uint next_number_keypart; /* autoinc keypart number in a key */ - enum open_frm_error error; /* error from open_table_def() */ - uint open_errno; /* error from open_table_def() */ - uint column_bitmap_size; - uchar frm_version; - - enum enum_v_keys { NOT_INITIALIZED=0, NO_V_KEYS, V_KEYS }; - enum_v_keys check_set_initialized; - - bool use_ext_keys; /* Extended keys can be used */ - bool null_field_first; - bool system; /* Set if system table (one record) */ - bool not_usable_by_query_cache; - bool online_backup; /* Set if on-line backup supported */ - /* - This is used by log tables, for tables that have their own internal - binary logging or for tables that doesn't support statement or row logging - */ - bool no_replicate; - bool crashed; - bool is_view; - bool can_cmp_whole_record; - /* This is set for temporary tables where CREATE was binary logged */ - bool table_creation_was_logged; - bool non_determinstic_insert; - bool vcols_need_refixing; - bool has_update_default_function; - bool can_do_row_logging; /* 1 if table supports RBR */ - bool long_unique_table; - - ulong table_map_id; /* for row-based replication */ - - /* - Things that are incompatible between the stored version and the - current version. This is a set of HA_CREATE... bits that can be used - to modify create_info->used_fields for ALTER TABLE. - */ - ulong incompatible_version; - - /** - For shares representing views File_parser object with view - definition read from .FRM file. - */ - const File_parser *view_def; - - /* For sequence tables, the current sequence state */ - SEQUENCE *sequence; - -#ifdef WITH_PARTITION_STORAGE_ENGINE - /* filled in when reading from frm */ - bool auto_partitioned; - char *partition_info_str; - uint partition_info_str_len; - uint partition_info_buffer_size; - plugin_ref default_part_plugin; -#endif - - /** - System versioning and application-time periods support. - */ - struct period_info_t - { - uint16 start_fieldno; - uint16 end_fieldno; - Lex_ident name; - Lex_ident constr_name; - uint unique_keys; - Field *start_field(TABLE_SHARE *s) const - { - return s->field[start_fieldno]; - } - Field *end_field(TABLE_SHARE *s) const - { - return s->field[end_fieldno]; - } - }; - - vers_kind_t versioned; - period_info_t vers; - period_info_t period; - - bool init_period_from_extra2(period_info_t *period, const uchar *data, - const uchar *end); - - Field *vers_start_field() - { - DBUG_ASSERT(versioned); - return field[vers.start_fieldno]; - } - - Field *vers_end_field() - { - DBUG_ASSERT(versioned); - return field[vers.end_fieldno]; - } - - Field *period_start_field() const - { - DBUG_ASSERT(period.name); - return field[period.start_fieldno]; - } - - Field *period_end_field() const - { - DBUG_ASSERT(period.name); - return field[period.end_fieldno]; - } - - /** - Cache the checked structure of this table. - - The pointer data is used to describe the structure that - a instance of the table must have. Each element of the - array specifies a field that must exist on the table. - - The pointer is cached in order to perform the check only - once -- when the table is loaded from the disk. - */ - const TABLE_FIELD_DEF *table_field_def_cache; - - /** Main handler's share */ - Handler_share *ha_share; - - /** Instrumentation for this table share. */ - PSI_table_share *m_psi; - - inline void reset() { bzero((void*)this, sizeof(*this)); } - - /* - Set share's table cache key and update its db and table name appropriately. - - SYNOPSIS - set_table_cache_key() - key_buff Buffer with already built table cache key to be - referenced from share. - key_length Key length. - - NOTES - Since 'key_buff' buffer will be referenced from share it should has same - life-time as share itself. - This method automatically ensures that TABLE_SHARE::table_name/db have - appropriate values by using table cache key as their source. - */ - - void set_table_cache_key(char *key_buff, uint key_length) - { - table_cache_key.str= key_buff; - table_cache_key.length= key_length; - /* - Let us use the fact that the key is "db/0/table_name/0" + optional - part for temporary tables. - */ - db.str= table_cache_key.str; - db.length= strlen(db.str); - table_name.str= db.str + db.length + 1; - table_name.length= strlen(table_name.str); - } - - - /* - Set share's table cache key and update its db and table name appropriately. - - SYNOPSIS - set_table_cache_key() - key_buff Buffer to be used as storage for table cache key - (should be at least key_length bytes). - key Value for table cache key. - key_length Key length. - - NOTE - Since 'key_buff' buffer will be used as storage for table cache key - it should has same life-time as share itself. - */ - - void set_table_cache_key(char *key_buff, const char *key, uint key_length) - { - memcpy(key_buff, key, key_length); - set_table_cache_key(key_buff, key_length); - } - - inline bool require_write_privileges() - { - return (table_category == TABLE_CATEGORY_LOG); - } - - inline ulong get_table_def_version() - { - return table_map_id; - } - - /** - Convert unrelated members of TABLE_SHARE to one enum - representing its type. - - @todo perhaps we need to have a member instead of a function. - */ - enum enum_table_ref_type get_table_ref_type() const - { - if (is_view) - return TABLE_REF_VIEW; - switch (tmp_table) { - case NO_TMP_TABLE: - return TABLE_REF_BASE_TABLE; - case SYSTEM_TMP_TABLE: - return TABLE_REF_I_S_TABLE; - default: - return TABLE_REF_TMP_TABLE; - } - } - /** - Return a table metadata version. - * for base tables and views, we return table_map_id. - It is assigned from a global counter incremented for each - new table loaded into the table definition cache (TDC). - * for temporary tables it's table_map_id again. But for - temporary tables table_map_id is assigned from - thd->query_id. The latter is assigned from a thread local - counter incremented for every new SQL statement. Since - temporary tables are thread-local, each temporary table - gets a unique id. - * for everything else (e.g. information schema tables), - the version id is zero. - - This choice of version id is a large compromise - to have a working prepared statement validation in 5.1. In - future version ids will be persistent, as described in WL#4180. - - Let's try to explain why and how this limited solution allows - to validate prepared statements. - - Firstly, sets (in mathematical sense) of version numbers - never intersect for different table types. Therefore, - version id of a temporary table is never compared with - a version id of a view, and vice versa. - - Secondly, for base tables and views, we know that each DDL flushes - the respective share from the TDC. This ensures that whenever - a table is altered or dropped and recreated, it gets a new - version id. - Unfortunately, since elements of the TDC are also flushed on - LRU basis, this choice of version ids leads to false positives. - E.g. when the TDC size is too small, we may have a SELECT - * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which - in turn will lead to a validation error and a subsequent - reprepare of all prepared statements. This is - considered acceptable, since as long as prepared statements are - automatically reprepared, spurious invalidation is only - a performance hit. Besides, no better simple solution exists. - - For temporary tables, using thd->query_id ensures that if - a temporary table was altered or recreated, a new version id is - assigned. This suits validation needs very well and will perhaps - never change. - - Metadata of information schema tables never changes. - Thus we can safely assume 0 for a good enough version id. - - Finally, by taking into account table type, we always - track that a change has taken place when a view is replaced - with a base table, a base table is replaced with a temporary - table and so on. - - @sa TABLE_LIST::is_table_ref_id_equal() - */ - ulong get_table_ref_version() const - { - return (tmp_table == SYSTEM_TMP_TABLE) ? 0 : table_map_id; - } - - bool visit_subgraph(Wait_for_flush *waiting_ticket, - MDL_wait_for_graph_visitor *gvisitor); - - bool wait_for_old_version(THD *thd, struct timespec *abstime, - uint deadlock_weight); - /** Release resources and free memory occupied by the table share. */ - void destroy(); - - void set_use_ext_keys_flag(bool fl) - { - use_ext_keys= fl; - } - - uint actual_n_key_parts(THD *thd); - - LEX_CUSTRING *frm_image; ///< only during CREATE TABLE (@sa ha_create_table) - - /* - populates TABLE_SHARE from the table description in the binary frm image. - if 'write' is true, this frm image is also written into a corresponding - frm file, that serves as a persistent metadata cache to avoid - discovering the table over and over again - */ - int init_from_binary_frm_image(THD *thd, bool write, - const uchar *frm_image, size_t frm_length, - const uchar *par_image=0, - size_t par_length=0); - - /* - populates TABLE_SHARE from the table description, specified as the - complete CREATE TABLE sql statement. - if 'write' is true, this frm image is also written into a corresponding - frm file, that serves as a persistent metadata cache to avoid - discovering the table over and over again - */ - int init_from_sql_statement_string(THD *thd, bool write, - const char *sql, size_t sql_length); - /* - writes the frm image to an frm file, corresponding to this table - */ - bool write_frm_image(const uchar *frm_image, size_t frm_length); - bool write_par_image(const uchar *par_image, size_t par_length); - - /* Only used by tokudb */ - bool write_frm_image(void) - { return frm_image ? write_frm_image(frm_image->str, frm_image->length) : 0; } - - /* - returns an frm image for this table. - the memory is allocated and must be freed later - */ - bool read_frm_image(const uchar **frm_image, size_t *frm_length); - - /* frees the memory allocated in read_frm_image */ - void free_frm_image(const uchar *frm); - - void set_overlapped_keys(); -}; - -/* not NULL, but cannot be dereferenced */ -#define UNUSABLE_TABLE_SHARE ((TABLE_SHARE*)1) - -/** - Class is used as a BLOB field value storage for - intermediate GROUP_CONCAT results. Used only for - GROUP_CONCAT with DISTINCT or ORDER BY options. - */ - -class Blob_mem_storage: public Sql_alloc -{ -private: - MEM_ROOT storage; - /** - Sign that some values were cut - during saving into the storage. - */ - bool truncated_value; -public: - Blob_mem_storage() :truncated_value(false) - { - init_alloc_root(key_memory_blob_mem_storage, - &storage, MAX_FIELD_VARCHARLENGTH, 0, MYF(0)); - } - ~ Blob_mem_storage() - { - free_root(&storage, MYF(0)); - } - void reset() - { - free_root(&storage, MYF(MY_MARK_BLOCKS_FREE)); - truncated_value= false; - } - /** - Fuction creates duplicate of 'from' - string in 'storage' MEM_ROOT. - - @param from string to copy - @param length string length - - @retval Pointer to the copied string. - @retval 0 if an error occurred. - */ - char *store(const char *from, size_t length) - { - return (char*) memdup_root(&storage, from, length); - } - void set_truncated_value(bool is_truncated_value) - { - truncated_value= is_truncated_value; - } - bool is_truncated_value() { return truncated_value; } -}; - - -/* Information for one open table */ -enum index_hint_type -{ - INDEX_HINT_IGNORE, - INDEX_HINT_USE, - INDEX_HINT_FORCE -}; - -struct st_cond_statistic; - -#define CHECK_ROW_FOR_NULLS_TO_REJECT (1 << 0) -#define REJECT_ROW_DUE_TO_NULL_FIELDS (1 << 1) - -class SplM_opt_info; - -struct vers_select_conds_t; - -struct TABLE -{ - TABLE() {} /* Remove gcc warning */ - - TABLE_SHARE *s; - handler *file; - TABLE *next, *prev; - -private: - /** - Links for the list of all TABLE objects for this share. - Declared as private to avoid direct manipulation with those objects. - One should use methods of I_P_List template instead. - */ - TABLE *share_all_next, **share_all_prev; - TABLE *global_free_next, **global_free_prev; - friend struct All_share_tables; - friend struct Table_cache_instance; - -public: - - uint32 instance; /** Table cache instance this TABLE is belonging to */ - THD *in_use; /* Which thread uses this */ - - uchar *record[3]; /* Pointer to records */ - uchar *write_row_record; /* Used as optimisation in - THD::write_row */ - uchar *insert_values; /* used by INSERT ... UPDATE */ - /* - Map of keys that can be used to retrieve all data from this table - needed by the query without reading the row. - */ - key_map covering_keys, intersect_keys; - /* - A set of keys that can be used in the query that references this - table. - - All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be - subtracted from this set upon instantiation. Thus for any TABLE t it holds - that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we - must not introduce any new keys here (see setup_tables). - - The set is implemented as a bitmap. - */ - key_map keys_in_use_for_query; - /* Map of keys that can be used to calculate GROUP BY without sorting */ - key_map keys_in_use_for_group_by; - /* Map of keys that can be used to calculate ORDER BY without sorting */ - key_map keys_in_use_for_order_by; - /* Map of keys dependent on some constraint */ - key_map constraint_dependent_keys; - KEY *key_info; /* data of keys in database */ - - Field **field; /* Pointer to fields */ - Field **vfield; /* Pointer to virtual fields*/ - Field **default_field; /* Fields with non-constant DEFAULT */ - Field *next_number_field; /* Set if next_number is activated */ - Field *found_next_number_field; /* Set on open */ - Virtual_column_info **check_constraints; - - /* Table's triggers, 0 if there are no of them */ - Table_triggers_list *triggers; - TABLE_LIST *pos_in_table_list;/* Element referring to this table */ - /* Position in thd->locked_table_list under LOCK TABLES */ - TABLE_LIST *pos_in_locked_tables; - /* Tables used in DEFAULT and CHECK CONSTRAINT (normally sequence tables) */ - TABLE_LIST *internal_tables; - - /* - Not-null for temporary tables only. Non-null values means this table is - used to compute GROUP BY, it has a unique of GROUP BY columns. - (set by create_tmp_table) - */ - ORDER *group; - String alias; /* alias or table name */ - uchar *null_flags; - MY_BITMAP def_read_set, def_write_set, tmp_set; - MY_BITMAP def_rpl_write_set; - MY_BITMAP eq_join_set; /* used to mark equi-joined fields */ - MY_BITMAP cond_set; /* used to mark fields from sargable conditions*/ - /* Active column sets */ - MY_BITMAP *read_set, *write_set, *rpl_write_set; - /* On INSERT: fields that the user specified a value for */ - MY_BITMAP has_value_set; - - /* - The ID of the query that opened and is using this table. Has different - meanings depending on the table type. - - Temporary tables: - - table->query_id is set to thd->query_id for the duration of a statement - and is reset to 0 once it is closed by the same statement. A non-zero - table->query_id means that a statement is using the table even if it's - not the current statement (table is in use by some outer statement). - - Non-temporary tables: - - Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id - for the duration of a statement and is reset to 0 once it is closed by - the same statement. A non-zero query_id is used to control which tables - in the list of pre-opened and locked tables are actually being used. - */ - query_id_t query_id; - - /* - This structure is used for statistical data on the table that - is collected by the function collect_statistics_for_table - */ - Table_statistics *collected_stats; - - /* The estimate of the number of records in the table used by optimizer */ - ha_rows used_stat_records; - - key_map opt_range_keys; - /* - The following structure is filled for each key that has - opt_range_keys.is_set(key) == TRUE - */ - struct OPT_RANGE - { - uint key_parts; - uint ranges; - ha_rows rows; - double cost; - /* - If there is a range access by i-th index then the cost of - index only access for it is stored in index_only_costs[i] - */ - double index_only_cost; - } *opt_range; - /* - Bitmaps of key parts that =const for the duration of join execution. If - we're in a subquery, then the constant may be different across subquery - re-executions. - */ - key_part_map *const_key_parts; - - /* - Estimate of number of records that satisfy SARGable part of the table - condition, or table->file->records if no SARGable condition could be - constructed. - This value is used by join optimizer as an estimate of number of records - that will pass the table condition (condition that depends on fields of - this table and constants) - */ - ha_rows opt_range_condition_rows; - - double cond_selectivity; - List *cond_selectivity_sampling_explain; - - table_map map; /* ID bit of table (1,2,4,8,16...) */ - - uint lock_position; /* Position in MYSQL_LOCK.table */ - uint lock_data_start; /* Start pos. in MYSQL_LOCK.locks */ - uint lock_count; /* Number of locks */ - uint tablenr,used_fields; - uint temp_pool_slot; /* Used by intern temp tables */ - uint status; /* What's in record[0] */ - uint db_stat; /* mode of file as in handler.h */ - /* number of select if it is derived table */ - uint derived_select_number; - /* - Possible values: - - 0 by default - - JOIN_TYPE_{LEFT|RIGHT} if the table is inner w.r.t an outer join - operation - - 1 if the SELECT has mixed_implicit_grouping=1. example: - select max(col1), col2 from t1. In this case, the query produces - one row with all columns having NULL values. - - Interpetation: If maybe_null!=0, all fields of the table are considered - NULLable (and have NULL values when null_row=true) - */ - uint maybe_null; - int current_lock; /* Type of lock on table */ - bool copy_blobs; /* copy_blobs when storing */ - /* - Set if next_number_field is in the UPDATE fields of INSERT ... ON DUPLICATE - KEY UPDATE. - */ - bool next_number_field_updated; - - /* - If true, the current table row is considered to have all columns set to - NULL, including columns declared as "not null" (see maybe_null). - */ - bool null_row; - /* - No rows that contain null values can be placed into this table. - Currently this flag can be set to true only for a temporary table - that used to store the result of materialization of a subquery. - */ - bool no_rows_with_nulls; - /* - This field can contain two bit flags: - CHECK_ROW_FOR_NULLS_TO_REJECT - REJECT_ROW_DUE_TO_NULL_FIELDS - The first flag is set for the dynamic contexts where it is prohibited - to write any null into the table. - The second flag is set only if the first flag is set on. - The informs the outer scope that there was an attept to write null - into a field of the table in the context where it is prohibited. - This flag should be set off as soon as the first flag is set on. - Currently these flags are used only the tables tno_rows_with_nulls set - to true. - */ - uint8 null_catch_flags; - - /* - TODO: Each of the following flags take up 8 bits. They can just as easily - be put into one single unsigned long and instead of taking up 18 - bytes, it would take up 4. - */ - bool force_index; - - /** - Flag set when the statement contains FORCE INDEX FOR ORDER BY - See TABLE_LIST::process_index_hints(). - */ - bool force_index_order; - - /** - Flag set when the statement contains FORCE INDEX FOR GROUP BY - See TABLE_LIST::process_index_hints(). - */ - bool force_index_group; - /* - TRUE<=> this table was created with create_tmp_table(... distinct=TRUE..) - call - */ - bool distinct; - bool const_table,no_rows, used_for_duplicate_elimination; - /** - Forces DYNAMIC Aria row format for internal temporary tables. - */ - bool keep_row_order; - - bool no_keyread; - /** - If set, indicate that the table is not replicated by the server. - */ - bool locked_by_logger; - bool locked_by_name; - bool fulltext_searched; - bool no_cache; - /* To signal that the table is associated with a HANDLER statement */ - bool open_by_handler; - /* - To indicate that a non-null value of the auto_increment field - was provided by the user or retrieved from the current record. - Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode. - */ - bool auto_increment_field_not_null; - bool insert_or_update; /* Can be used by the handler */ - bool alias_name_used; /* true if table_name is alias */ - bool get_fields_in_item_tree; /* Signal to fix_field */ -private: - bool m_needs_reopen; - bool created; /* For tmp tables. TRUE <=> tmp table was actually created.*/ -public: -#ifdef HAVE_REPLICATION - /* used in RBR Triggers */ - bool master_had_triggers; -#endif - - REGINFO reginfo; /* field connections */ - MEM_ROOT mem_root; - /** - Initialized in Item_func_group_concat::setup for appropriate - temporary table if GROUP_CONCAT is used with ORDER BY | DISTINCT - and BLOB field count > 0. - */ - Blob_mem_storage *blob_storage; - GRANT_INFO grant; - /* - The arena which the items for expressions from the table definition - are associated with. - Currently only the items of the expressions for virtual columns are - associated with this arena. - TODO: To attach the partitioning expressions to this arena. - */ - Query_arena *expr_arena; -#ifdef WITH_PARTITION_STORAGE_ENGINE - partition_info *part_info; /* Partition related information */ - /* If true, all partitions have been pruned away */ - bool all_partitions_pruned_away; -#endif - uint max_keys; /* Size of allocated key_info array. */ - bool stats_is_read; /* Persistent statistics is read for the table */ - bool histograms_are_read; - MDL_ticket *mdl_ticket; - - /* - This is used only for potentially splittable materialized tables and it - points to the info used by the optimizer to apply splitting optimization - */ - SplM_opt_info *spl_opt_info; - key_map keys_usable_for_splitting; - - /* - Conjunction of the predicates of the form IS NOT NULL(f) where f refers to - a column of this TABLE such that they can be inferred from the condition - of the WHERE clause or from some ON expression of the processed select - and can be useful for range optimizer. - */ - Item *notnull_cond; - - inline void reset() { bzero((void*)this, sizeof(*this)); } - void init(THD *thd, TABLE_LIST *tl); - bool fill_item_list(List *item_list) const; - void reset_item_list(List *item_list, uint skip) const; - void clear_column_bitmaps(void); - void prepare_for_position(void); - MY_BITMAP *prepare_for_keyread(uint index, MY_BITMAP *map); - MY_BITMAP *prepare_for_keyread(uint index) - { return prepare_for_keyread(index, &tmp_set); } - void mark_columns_used_by_index(uint index, MY_BITMAP *map); - void mark_columns_used_by_index_no_reset(uint index, MY_BITMAP *map); - void restore_column_maps_after_keyread(MY_BITMAP *backup); - void mark_auto_increment_column(void); - void mark_columns_needed_for_update(void); - void mark_columns_needed_for_delete(void); - void mark_columns_needed_for_insert(void); - void mark_columns_per_binlog_row_image(void); - inline bool mark_column_with_deps(Field *field); - inline bool mark_virtual_column_with_deps(Field *field); - inline void mark_virtual_column_deps(Field *field); - bool mark_virtual_columns_for_write(bool insert_fl); - bool check_virtual_columns_marked_for_read(); - bool check_virtual_columns_marked_for_write(); - void mark_default_fields_for_write(bool insert_fl); - void mark_columns_used_by_virtual_fields(void); - void mark_check_constraint_columns_for_read(void); - int verify_constraints(bool ignore_failure); - inline void column_bitmaps_set(MY_BITMAP *read_set_arg) - { - read_set= read_set_arg; - if (file) - file->column_bitmaps_signal(); - } - inline void column_bitmaps_set(MY_BITMAP *read_set_arg, - MY_BITMAP *write_set_arg) - { - read_set= read_set_arg; - write_set= write_set_arg; - if (file) - file->column_bitmaps_signal(); - } - inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg, - MY_BITMAP *write_set_arg) - { - read_set= read_set_arg; - write_set= write_set_arg; - } - inline void use_all_columns() - { - column_bitmaps_set(&s->all_set, &s->all_set); - } - inline void use_all_stored_columns(); - inline void default_column_bitmaps() - { - read_set= &def_read_set; - write_set= &def_write_set; - rpl_write_set= 0; - } - /** Should this instance of the table be reopened? */ - inline bool needs_reopen() - { return !db_stat || m_needs_reopen; } - /* - Mark that all current connection instances of the table should be - reopen at end of statement - */ - void mark_table_for_reopen(); - /* Should only be called from Locked_tables_list::mark_table_for_reopen() */ - void internal_set_needs_reopen(bool value) - { - m_needs_reopen= value; - } - - bool alloc_keys(uint key_count); - bool check_tmp_key(uint key, uint key_parts, - uint (*next_field_no) (uchar *), uchar *arg); - bool add_tmp_key(uint key, uint key_parts, - uint (*next_field_no) (uchar *), uchar *arg, - bool unique); - void create_key_part_by_field(KEY_PART_INFO *key_part_info, - Field *field, uint fieldnr); - void use_index(int key_to_save); - void set_table_map(table_map map_arg, uint tablenr_arg) - { - map= map_arg; - tablenr= tablenr_arg; - } - - /// Return true if table is instantiated, and false otherwise. - bool is_created() const { return created; } - - /** - Set the table as "created", and enable flags in storage engine - that could not be enabled without an instantiated table. - */ - void set_created() - { - if (created) - return; - if (file->keyread_enabled()) - file->extra(HA_EXTRA_KEYREAD); - created= true; - } - - /* - Returns TRUE if the table is filled at execution phase (and so, the - optimizer must not do anything that depends on the contents of the table, - like range analysis or constant table detection) - */ - bool is_filled_at_execution(); - - bool update_const_key_parts(COND *conds); - - inline void initialize_opt_range_structures(); - - my_ptrdiff_t default_values_offset() const - { return (my_ptrdiff_t) (s->default_values - record[0]); } - - void move_fields(Field **ptr, const uchar *to, const uchar *from); - void remember_blob_values(String *blob_storage); - void restore_blob_values(String *blob_storage); - - uint actual_n_key_parts(KEY *keyinfo); - ulong actual_key_flags(KEY *keyinfo); - int update_virtual_field(Field *vf); - int update_virtual_fields(handler *h, enum_vcol_update_mode update_mode); - int update_default_fields(bool ignore_errors); - void evaluate_update_default_function(); - void reset_default_fields(); - inline ha_rows stat_records() { return used_stat_records; } - - void prepare_triggers_for_insert_stmt_or_event(); - bool prepare_triggers_for_delete_stmt_or_event(); - bool prepare_triggers_for_update_stmt_or_event(); - - Field **field_to_fill(); - bool validate_default_values_of_unset_fields(THD *thd) const; - - bool insert_all_rows_into_tmp_table(THD *thd, - TABLE *tmp_table, - TMP_TABLE_PARAM *tmp_table_param, - bool with_cleanup); - int fix_vcol_exprs(THD *thd); - Field *find_field_by_name(LEX_CSTRING *str) const; - bool export_structure(THD *thd, class Row_definition_list *defs); - bool is_splittable() { return spl_opt_info != NULL; } - void set_spl_opt_info(SplM_opt_info *spl_info); - void deny_splitting(); - double get_materialization_cost(); // Now used only if is_splittable()==true - void add_splitting_info_for_key_field(struct KEY_FIELD *key_field); - - key_map with_impossible_ranges; - - /* Number of cost info elements for possible range filters */ - uint range_rowid_filter_cost_info_elems; - /* Pointer to the array of cost info elements for range filters */ - Range_rowid_filter_cost_info *range_rowid_filter_cost_info; - /* The array of pointers to cost info elements for range filters */ - Range_rowid_filter_cost_info **range_rowid_filter_cost_info_ptr; - - void init_cost_info_for_usable_range_rowid_filters(THD *thd); - void prune_range_rowid_filters(); - void trace_range_rowid_filters(THD *thd) const; - Range_rowid_filter_cost_info * - best_range_rowid_filter_for_partial_join(uint access_key_no, - double records, - double access_cost_factor); - - /** - System Versioning support - */ - bool vers_write; - - bool versioned() const - { - return s->versioned; - } - - bool versioned(vers_kind_t type) const - { - DBUG_ASSERT(type); - return s->versioned == type; - } - - bool versioned_write() const - { - DBUG_ASSERT(versioned() || !vers_write); - return versioned() ? vers_write : false; - } - - bool versioned_write(vers_kind_t type) const - { - DBUG_ASSERT(type); - DBUG_ASSERT(versioned() || !vers_write); - return versioned(type) ? vers_write : false; - } - - Field *vers_start_field() const - { - DBUG_ASSERT(s->versioned); - return field[s->vers.start_fieldno]; - } - - Field *vers_end_field() const - { - DBUG_ASSERT(s->versioned); - return field[s->vers.end_fieldno]; - } - - Field *period_start_field() const - { - DBUG_ASSERT(s->period.name); - return field[s->period.start_fieldno]; - } - - Field *period_end_field() const - { - DBUG_ASSERT(s->period.name); - return field[s->period.end_fieldno]; - } - - - ulonglong vers_start_id() const; - ulonglong vers_end_id() const; - - int update_generated_fields(); - int period_make_insert(Item *src, Field *dst); - int insert_portion_of_time(THD *thd, const vers_select_conds_t &period_conds, - ha_rows *rows_inserted); - bool vers_check_update(List &items); - static bool check_period_overlaps(const KEY &key, const uchar *lhs, const uchar *rhs); - int delete_row(); - void vers_update_fields(); - void vers_update_end(); - void find_constraint_correlated_indexes(); - -/** Number of additional fields used in versioned tables */ -#define VERSIONING_FIELDS 2 -}; - - -/** - Helper class which specifies which members of TABLE are used for - participation in the list of used/unused TABLE objects for the share. -*/ - -struct TABLE_share -{ - static inline TABLE **next_ptr(TABLE *l) - { - return &l->next; - } - static inline TABLE ***prev_ptr(TABLE *l) - { - return (TABLE ***) &l->prev; - } -}; - -struct All_share_tables -{ - static inline TABLE **next_ptr(TABLE *l) - { - return &l->share_all_next; - } - static inline TABLE ***prev_ptr(TABLE *l) - { - return &l->share_all_prev; - } -}; - -typedef I_P_List All_share_tables_list; - -enum enum_schema_table_state -{ - NOT_PROCESSED= 0, - PROCESSED_BY_CREATE_SORT_INDEX, - PROCESSED_BY_JOIN_EXEC -}; - -enum enum_fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_CASCADE, - FK_OPTION_SET_NULL, FK_OPTION_NO_ACTION, FK_OPTION_SET_DEFAULT}; - -typedef struct st_foreign_key_info -{ - LEX_CSTRING *foreign_id; - LEX_CSTRING *foreign_db; - LEX_CSTRING *foreign_table; - LEX_CSTRING *referenced_db; - LEX_CSTRING *referenced_table; - enum_fk_option update_method; - enum_fk_option delete_method; - LEX_CSTRING *referenced_key_name; - List foreign_fields; - List referenced_fields; -} FOREIGN_KEY_INFO; - -LEX_CSTRING *fk_option_name(enum_fk_option opt); -bool fk_modifies_child(enum_fk_option opt); - -class IS_table_read_plan; - -/* - Types of derived tables. The ending part is a bitmap of phases that are - applicable to a derived table of the type. -*/ -#define DTYPE_ALGORITHM_UNDEFINED 0U -#define DTYPE_VIEW 1U -#define DTYPE_TABLE 2U -#define DTYPE_MERGE 4U -#define DTYPE_MATERIALIZE 8U -#define DTYPE_MULTITABLE 16U -#define DTYPE_MASK (DTYPE_VIEW|DTYPE_TABLE|DTYPE_MULTITABLE) - -/* - Phases of derived tables/views handling, see sql_derived.cc - Values are used as parts of a bitmap attached to derived table types. -*/ -#define DT_INIT 1U -#define DT_PREPARE 2U -#define DT_OPTIMIZE 4U -#define DT_MERGE 8U -#define DT_MERGE_FOR_INSERT 16U -#define DT_CREATE 32U -#define DT_FILL 64U -#define DT_REINIT 128U -#define DT_PHASES 8U -/* Phases that are applicable to all derived tables. */ -#define DT_COMMON (DT_INIT + DT_PREPARE + DT_REINIT + DT_OPTIMIZE) -/* Phases that are applicable only to materialized derived tables. */ -#define DT_MATERIALIZE (DT_CREATE + DT_FILL) - -#define DT_PHASES_MERGE (DT_COMMON | DT_MERGE | DT_MERGE_FOR_INSERT) -#define DT_PHASES_MATERIALIZE (DT_COMMON | DT_MATERIALIZE) - -#define VIEW_ALGORITHM_UNDEFINED 0 -/* Special value for ALTER VIEW: inherit original algorithm. */ -#define VIEW_ALGORITHM_INHERIT DTYPE_VIEW -#define VIEW_ALGORITHM_MERGE (DTYPE_VIEW | DTYPE_MERGE) -#define VIEW_ALGORITHM_TMPTABLE (DTYPE_VIEW | DTYPE_MATERIALIZE) - -/* - View algorithm values as stored in the FRM. Values differ from in-memory - representation for backward compatibility. -*/ - -#define VIEW_ALGORITHM_UNDEFINED_FRM 0U -#define VIEW_ALGORITHM_MERGE_FRM 1U -#define VIEW_ALGORITHM_TMPTABLE_FRM 2U - -#define JOIN_TYPE_LEFT 1U -#define JOIN_TYPE_RIGHT 2U -#define JOIN_TYPE_OUTER 4U /* Marker that this is an outer join */ - -/* view WITH CHECK OPTION parameter options */ -#define VIEW_CHECK_NONE 0 -#define VIEW_CHECK_LOCAL 1 -#define VIEW_CHECK_CASCADED 2 - -/* result of view WITH CHECK OPTION parameter check */ -#define VIEW_CHECK_OK 0 -#define VIEW_CHECK_ERROR 1 -#define VIEW_CHECK_SKIP 2 - -/** The threshold size a blob field buffer before it is freed */ -#define MAX_TDC_BLOB_SIZE 65536 - -/** number of bytes used by field positional indexes in frm */ -constexpr uint frm_fieldno_size= 2; -/** number of bytes used by key position number in frm */ -constexpr uint frm_keyno_size= 2; -static inline uint16 read_frm_fieldno(const uchar *data) -{ return uint2korr(data); } -static inline void store_frm_fieldno(uchar *data, uint16 fieldno) -{ int2store(data, fieldno); } -static inline uint16 read_frm_keyno(const uchar *data) -{ return uint2korr(data); } -static inline void store_frm_keyno(uchar *data, uint16 fieldno) -{ int2store(data, fieldno); } -static inline size_t extra2_str_size(size_t len) -{ return (len > 255 ? 3 : 1) + len; } - -class select_unit; -class TMP_TABLE_PARAM; - -Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref, - LEX_CSTRING *name); - -struct Field_translator -{ - Item *item; - LEX_CSTRING name; -}; - - -/* - Column reference of a NATURAL/USING join. Since column references in - joins can be both from views and stored tables, may point to either a - Field (for tables), or a Field_translator (for views). -*/ - -class Natural_join_column: public Sql_alloc -{ -public: - Field_translator *view_field; /* Column reference of merge view. */ - Item_field *table_field; /* Column reference of table or temp view. */ - TABLE_LIST *table_ref; /* Original base table/view reference. */ - /* - True if a common join column of two NATURAL/USING join operands. Notice - that when we have a hierarchy of nested NATURAL/USING joins, a column can - be common at some level of nesting but it may not be common at higher - levels of nesting. Thus this flag may change depending on at which level - we are looking at some column. - */ - bool is_common; -public: - Natural_join_column(Field_translator *field_param, TABLE_LIST *tab); - Natural_join_column(Item_field *field_param, TABLE_LIST *tab); - LEX_CSTRING *name(); - Item *create_item(THD *thd); - Field *field(); - const char *safe_table_name(); - const char *safe_db_name(); - GRANT_INFO *grant(); -}; - - -/** - Type of table which can be open for an element of table list. -*/ - -enum enum_open_type -{ - OT_TEMPORARY_OR_BASE= 0, OT_TEMPORARY_ONLY, OT_BASE_ONLY -}; - - -class SJ_MATERIALIZATION_INFO; -class Index_hint; -class Item_in_subselect; - -/* trivial class, for %union in sql_yacc.yy */ -struct vers_history_point_t -{ - vers_kind_t unit; - Item *item; -}; - -class Vers_history_point : public vers_history_point_t -{ - void fix_item(); - -public: - Vers_history_point() { empty(); } - Vers_history_point(vers_kind_t unit_arg, Item *item_arg) - { - unit= unit_arg; - item= item_arg; - fix_item(); - } - Vers_history_point(vers_history_point_t p) - { - unit= p.unit; - item= p.item; - fix_item(); - } - void empty() { unit= VERS_TIMESTAMP; item= NULL; } - void print(String *str, enum_query_type, const char *prefix, size_t plen) const; - bool check_unit(THD *thd); - void bad_expression_data_type_error(const char *type) const; - bool eq(const vers_history_point_t &point) const; -}; - -struct vers_select_conds_t -{ - vers_system_time_t type; - vers_system_time_t orig_type; - bool used:1; - bool delete_history:1; - Vers_history_point start; - Vers_history_point end; - Lex_ident name; - - Item_field *field_start; - Item_field *field_end; - - const TABLE_SHARE::period_info_t *period; - - void empty() - { - type= SYSTEM_TIME_UNSPECIFIED; - orig_type= SYSTEM_TIME_UNSPECIFIED; - used= false; - delete_history= false; - start.empty(); - end.empty(); - } - - void init(vers_system_time_t _type, - Vers_history_point _start= Vers_history_point(), - Vers_history_point _end= Vers_history_point(), - Lex_ident _name= "SYSTEM_TIME") - { - type= _type; - orig_type= _type; - used= false; - delete_history= (type == SYSTEM_TIME_HISTORY || - type == SYSTEM_TIME_BEFORE); - start= _start; - end= _end; - name= _name; - } - - void set_all() - { - type= SYSTEM_TIME_ALL; - name= "SYSTEM_TIME"; - } - - void print(String *str, enum_query_type query_type) const; - - bool init_from_sysvar(THD *thd); - - bool is_set() const - { - return type != SYSTEM_TIME_UNSPECIFIED; - } - bool check_units(THD *thd); - bool was_set() const - { - return orig_type != SYSTEM_TIME_UNSPECIFIED; - } - bool need_setup() const - { - return type != SYSTEM_TIME_UNSPECIFIED && type != SYSTEM_TIME_ALL; - } - bool eq(const vers_select_conds_t &conds) const; -}; - -/* - Table reference in the FROM clause. - - These table references can be of several types that correspond to - different SQL elements. Below we list all types of TABLE_LISTs with - the necessary conditions to determine when a TABLE_LIST instance - belongs to a certain type. - - 1) table (TABLE_LIST::view == NULL) - - base table - (TABLE_LIST::derived == NULL) - - FROM-clause subquery - TABLE_LIST::table is a temp table - (TABLE_LIST::derived != NULL) - - information schema table - (TABLE_LIST::schema_table != NULL) - NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL - 2) view (TABLE_LIST::view != NULL) - - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE) - also (TABLE_LIST::field_translation != NULL) - - tmptable (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TMPTABLE) - also (TABLE_LIST::field_translation == NULL) - 2.5) TODO: Add derived tables description here - 3) nested table reference (TABLE_LIST::nested_join != NULL) - - table sequence - e.g. (t1, t2, t3) - TODO: how to distinguish from a JOIN? - - general JOIN - TODO: how to distinguish from a table sequence? - - NATURAL JOIN - (TABLE_LIST::natural_join != NULL) - - JOIN ... USING - (TABLE_LIST::join_using_fields != NULL) - - semi-join nest (sj_on_expr!= NULL && sj_subq_pred!=NULL) - 4) jtbm semi-join (jtbm_subselect != NULL) -*/ - -/** last_leaf_for_name_resolutioning support. */ - -struct LEX; -class Index_hint; -struct TABLE_LIST -{ - TABLE_LIST() {} /* Remove gcc warning */ - - enum prelocking_types - { - PRELOCK_NONE, PRELOCK_ROUTINE, PRELOCK_FK - }; - - /** - Prepare TABLE_LIST that consists of one table instance to use in - open_and_lock_tables - */ - inline void reset() { bzero((void*)this, sizeof(*this)); } - inline void init_one_table(const LEX_CSTRING *db_arg, - const LEX_CSTRING *table_name_arg, - const LEX_CSTRING *alias_arg, - enum thr_lock_type lock_type_arg) - { - enum enum_mdl_type mdl_type; - if (lock_type_arg >= TL_WRITE_ALLOW_WRITE) - mdl_type= MDL_SHARED_WRITE; - else if (lock_type_arg == TL_READ_NO_INSERT) - mdl_type= MDL_SHARED_NO_WRITE; - else - mdl_type= MDL_SHARED_READ; - - reset(); - DBUG_ASSERT(!db_arg->str || strlen(db_arg->str) == db_arg->length); - DBUG_ASSERT(!table_name_arg->str || strlen(table_name_arg->str) == table_name_arg->length); - DBUG_ASSERT(!alias_arg || strlen(alias_arg->str) == alias_arg->length); - db= *db_arg; - table_name= *table_name_arg; - alias= (alias_arg ? *alias_arg : *table_name_arg); - lock_type= lock_type_arg; - updating= lock_type >= TL_WRITE_ALLOW_WRITE; - MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db.str, table_name.str, - mdl_type, MDL_TRANSACTION); - } - - TABLE_LIST(TABLE *table_arg, thr_lock_type lock_type) - { - DBUG_ASSERT(table_arg->s); - init_one_table(&table_arg->s->db, &table_arg->s->table_name, - NULL, lock_type); - table= table_arg; - vers_conditions.name= table->s->vers.name; - } - - inline void init_one_table_for_prelocking(const LEX_CSTRING *db_arg, - const LEX_CSTRING *table_name_arg, - const LEX_CSTRING *alias_arg, - enum thr_lock_type lock_type_arg, - prelocking_types prelocking_type, - TABLE_LIST *belong_to_view_arg, - uint8 trg_event_map_arg, - TABLE_LIST ***last_ptr, - my_bool insert_data) - - { - init_one_table(db_arg, table_name_arg, alias_arg, lock_type_arg); - cacheable_table= 1; - prelocking_placeholder= prelocking_type; - open_type= (prelocking_type == PRELOCK_ROUTINE ? - OT_TEMPORARY_OR_BASE : - OT_BASE_ONLY); - belong_to_view= belong_to_view_arg; - trg_event_map= trg_event_map_arg; - /* MDL is enough for read-only FK checks, we don't need the table */ - if (prelocking_type == PRELOCK_FK && lock_type < TL_WRITE_ALLOW_WRITE) - open_strategy= OPEN_STUB; - - **last_ptr= this; - prev_global= *last_ptr; - *last_ptr= &next_global; - for_insert_data= insert_data; - } - - - /* - List of tables local to a subquery (used by SQL_I_List). Considers - views as leaves (unlike 'next_leaf' below). Created at parse time - in st_select_lex::add_table_to_list() -> table_list.link_in_list(). - */ - TABLE_LIST *next_local; - /* link in a global list of all queries tables */ - TABLE_LIST *next_global, **prev_global; - LEX_CSTRING db; - LEX_CSTRING table_name; - LEX_CSTRING schema_table_name; - LEX_CSTRING alias; - const char *option; /* Used by cache index */ - Item *on_expr; /* Used with outer join */ - Name_resolution_context *on_context; /* For ON expressions */ - - Item *sj_on_expr; - /* - (Valid only for semi-join nests) Bitmap of tables that are within the - semi-join (this is different from bitmap of all nest's children because - tables that were pulled out of the semi-join nest remain listed as - nest's children). - */ - table_map sj_inner_tables; - /* Number of IN-compared expressions */ - uint sj_in_exprs; - - /* If this is a non-jtbm semi-join nest: corresponding subselect predicate */ - Item_in_subselect *sj_subq_pred; - - table_map original_subq_pred_used_tables; - - /* If this is a jtbm semi-join object: corresponding subselect predicate */ - Item_in_subselect *jtbm_subselect; - /* TODO: check if this can be joined with tablenr_exec */ - uint jtbm_table_no; - - SJ_MATERIALIZATION_INFO *sj_mat_info; - - /* - The structure of ON expression presented in the member above - can be changed during certain optimizations. This member - contains a snapshot of AND-OR structure of the ON expression - made after permanent transformations of the parse tree, and is - used to restore ON clause before every reexecution of a prepared - statement or stored procedure. - */ - Item *prep_on_expr; - COND_EQUAL *cond_equal; /* Used with outer join */ - /* - During parsing - left operand of NATURAL/USING join where 'this' is - the right operand. After parsing (this->natural_join == this) iff - 'this' represents a NATURAL or USING join operation. Thus after - parsing 'this' is a NATURAL/USING join iff (natural_join != NULL). - */ - TABLE_LIST *natural_join; - /* - True if 'this' represents a nested join that is a NATURAL JOIN. - For one of the operands of 'this', the member 'natural_join' points - to the other operand of 'this'. - */ - bool is_natural_join; - /* Field names in a USING clause for JOIN ... USING. */ - List *join_using_fields; - /* - Explicitly store the result columns of either a NATURAL/USING join or - an operand of such a join. - */ - List *join_columns; - /* TRUE if join_columns contains all columns of this table reference. */ - bool is_join_columns_complete; - - /* - List of nodes in a nested join tree, that should be considered as - leaves with respect to name resolution. The leaves are: views, - top-most nodes representing NATURAL/USING joins, subqueries, and - base tables. All of these TABLE_LIST instances contain a - materialized list of columns. The list is local to a subquery. - */ - TABLE_LIST *next_name_resolution_table; - /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */ - List *index_hints; - TABLE *table; /* opened table */ - ulonglong table_id; /* table id (from binlog) for opened table */ - /* - select_result for derived table to pass it from table creation to table - filling procedure - */ - select_unit *derived_result; - /* Stub used for materialized derived tables. */ - table_map map; /* ID bit of table (1,2,4,8,16...) */ - table_map get_map() - { - return jtbm_subselect? table_map(1) << jtbm_table_no : table->map; - } - uint get_tablenr() - { - return jtbm_subselect? jtbm_table_no : table->tablenr; - } - void set_tablenr(uint new_tablenr) - { - if (jtbm_subselect) - { - jtbm_table_no= new_tablenr; - } - if (table) - { - table->tablenr= new_tablenr; - table->map= table_map(1) << new_tablenr; - } - } - /* - Reference from aux_tables to local list entry of main select of - multi-delete statement: - delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b; - here it will be reference of first occurrence of t1 to second (as you - can see this lists can't be merged) - */ - TABLE_LIST *correspondent_table; - /** - @brief Normally, this field is non-null for anonymous derived tables only. - - @details This field is set to non-null for - - - Anonymous derived tables, In this case it points to the SELECT_LEX_UNIT - representing the derived table. E.g. for a query - - @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim - - For the @c TABLE_LIST representing the derived table @c b, @c derived - points to the SELECT_LEX_UNIT representing the result of the query within - parenteses. - - - Views. This is set for views with @verbatim ALGORITHM = TEMPTABLE - @endverbatim by mysql_make_view(). - - @note Inside views, a subquery in the @c FROM clause is not allowed. - @note Do not use this field to separate views/base tables/anonymous - derived tables. Use TABLE_LIST::is_anonymous_derived_table(). - */ - st_select_lex_unit *derived; /* SELECT_LEX_UNIT of derived table */ - With_element *with; /* With element defining this table (if any) */ - /* Bitmap of the defining with element */ - table_map with_internal_reference_map; - TABLE_LIST * next_with_rec_ref; - bool is_derived_with_recursive_reference; - bool block_handle_derived; - /* The interface employed to materialize the table by a foreign engine */ - derived_handler *dt_handler; - /* The text of the query specifying the derived table */ - LEX_CSTRING derived_spec; - /* - The object used to organize execution of the query that specifies - the derived table by a foreign engine - */ - Pushdown_derived *pushdown_derived; - ST_SCHEMA_TABLE *schema_table; /* Information_schema table */ - st_select_lex *schema_select_lex; - /* - True when the view field translation table is used to convert - schema table fields for backwards compatibility with SHOW command. - */ - bool schema_table_reformed; - TMP_TABLE_PARAM *schema_table_param; - /* link to select_lex where this table was used */ - st_select_lex *select_lex; - LEX *view; /* link on VIEW lex for merging */ - Field_translator *field_translation; /* array of VIEW fields */ - /* pointer to element after last one in translation table above */ - Field_translator *field_translation_end; - bool field_translation_updated; - /* - List (based on next_local) of underlying tables of this view. I.e. it - does not include the tables of subqueries used in the view. Is set only - for merged views. - */ - TABLE_LIST *merge_underlying_list; - /* - - 0 for base tables - - in case of the view it is the list of all (not only underlying - tables but also used in subquery ones) tables of the view. - */ - List *view_tables; - /* most upper view this table belongs to */ - TABLE_LIST *belong_to_view; - /* A derived table this table belongs to */ - TABLE_LIST *belong_to_derived; - /* - The view directly referencing this table - (non-zero only for merged underlying tables of a view). - */ - TABLE_LIST *referencing_view; - - table_map view_used_tables; - table_map map_exec; - /* TODO: check if this can be joined with jtbm_table_no */ - uint tablenr_exec; - uint maybe_null_exec; - - /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */ - TABLE_LIST *parent_l; - /* - Security context (non-zero only for tables which belong - to view with SQL SECURITY DEFINER) - */ - Security_context *security_ctx; - /* - This view security context (non-zero only for views with - SQL SECURITY DEFINER) - */ - Security_context *view_sctx; - bool allowed_show; - Item *where; /* VIEW WHERE clause condition */ - Item *check_option; /* WITH CHECK OPTION condition */ - LEX_STRING select_stmt; /* text of (CREATE/SELECT) statement */ - LEX_CSTRING md5; /* md5 of query text */ - LEX_CSTRING source; /* source of CREATE VIEW */ - LEX_CSTRING view_db; /* saved view database */ - LEX_CSTRING view_name; /* saved view name */ - LEX_STRING timestamp; /* GMT time stamp of last operation */ - LEX_USER definer; /* definer of view */ - ulonglong file_version; /* version of file's field set */ - ulonglong mariadb_version; /* version of server on creation */ - ulonglong updatable_view; /* VIEW can be updated */ - /** - @brief The declared algorithm, if this is a view. - @details One of - - VIEW_ALGORITHM_UNDEFINED - - VIEW_ALGORITHM_TMPTABLE - - VIEW_ALGORITHM_MERGE - @to do Replace with an enum - */ - ulonglong algorithm; - ulonglong view_suid; /* view is suid (TRUE dy default) */ - ulonglong with_check; /* WITH CHECK OPTION */ - /* - effective value of WITH CHECK OPTION (differ for temporary table - algorithm) - */ - uint8 effective_with_check; - /** - @brief The view algorithm that is actually used, if this is a view. - @details One of - - VIEW_ALGORITHM_UNDEFINED - - VIEW_ALGORITHM_TMPTABLE - - VIEW_ALGORITHM_MERGE - @to do Replace with an enum - */ - uint8 derived_type; - GRANT_INFO grant; - /* data need by some engines in query cache*/ - ulonglong engine_data; - /* call back function for asking handler about caching in query cache */ - qc_engine_callback callback_func; - thr_lock_type lock_type; - uint outer_join; /* Which join type */ - uint shared; /* Used in multi-upd */ - bool updatable; /* VIEW/TABLE can be updated now */ - bool straight; /* optimize with prev table */ - bool updating; /* for replicate-do/ignore table */ - bool force_index; /* prefer index over table scan */ - bool ignore_leaves; /* preload only non-leaf nodes */ - bool crashed; /* Table was found crashed */ - table_map dep_tables; /* tables the table depends on */ - table_map on_expr_dep_tables; /* tables on expression depends on */ - struct st_nested_join *nested_join; /* if the element is a nested join */ - TABLE_LIST *embedding; /* nested join containing the table */ - List *join_list;/* join list the table belongs to */ - bool lifted; /* set to true when the table is moved to - the upper level at the parsing stage */ - bool cacheable_table; /* stop PS caching */ - /* used in multi-upd/views privilege check */ - bool table_in_first_from_clause; - /** - Specifies which kind of table should be open for this element - of table list. - */ - enum enum_open_type open_type; - /* TRUE if this merged view contain auto_increment field */ - bool contain_auto_increment; - bool compact_view_format; /* Use compact format for SHOW CREATE VIEW */ - /* view where processed */ - bool where_processed; - /* TRUE <=> VIEW CHECK OPTION expression has been processed */ - bool check_option_processed; - /* TABLE_TYPE_UNKNOWN if any type is acceptable */ - Table_type required_type; - handlerton *db_type; /* table_type for handler */ - char timestamp_buffer[MAX_DATETIME_WIDTH + 1]; - /* - This TABLE_LIST object is just placeholder for prelocking, it will be - used for implicit LOCK TABLES only and won't be used in real statement. - */ - prelocking_types prelocking_placeholder; - /** - Indicates that if TABLE_LIST object corresponds to the table/view - which requires special handling. - */ - enum enum_open_strategy - { - /* Normal open. */ - OPEN_NORMAL= 0, - /* Associate a table share only if the the table exists. */ - OPEN_IF_EXISTS, - /* Don't associate a table share. */ - OPEN_STUB - } open_strategy; - /** TRUE if an alias for this table was specified in the SQL. */ - bool is_alias; - /** TRUE if the table is referred to in the statement using a fully - qualified name (.). - */ - bool is_fqtn; - - /* TRUE <=> derived table should be filled right after optimization. */ - bool fill_me; - /* TRUE <=> view/DT is merged. */ - /* TODO: replace with derived_type */ - bool merged; - bool merged_for_insert; - bool sequence; /* Part of NEXTVAL/CURVAL/LASTVAL */ - - /* - Items created by create_view_field and collected to change them in case - of materialization of the view/derived table - */ - List used_items; - /* Sublist (tail) of persistent used_items */ - List persistent_used_items; - - /* View creation context. */ - - View_creation_ctx *view_creation_ctx; - - /* - Attributes to save/load view creation context in/from frm-file. - - Ther are required only to be able to use existing parser to load - view-definition file. As soon as the parser parsed the file, view - creation context is initialized and the attributes become redundant. - - These attributes MUST NOT be used for any purposes but the parsing. - */ - - LEX_CSTRING view_client_cs_name; - LEX_CSTRING view_connection_cl_name; - - /* - View definition (SELECT-statement) in the UTF-form. - */ - - LEX_CSTRING view_body_utf8; - - /* End of view definition context. */ - - /** - Indicates what triggers we need to pre-load for this TABLE_LIST - when opening an associated TABLE. This is filled after - the parsed tree is created. - */ - uint8 trg_event_map; - /* TRUE <=> this table is a const one and was optimized away. */ - bool optimized_away; - - /** - TRUE <=> already materialized. Valid only for materialized derived - tables/views. - */ - bool materialized; - /* I_S: Flags to open_table (e.g. OPEN_TABLE_ONLY or OPEN_VIEW_ONLY) */ - uint i_s_requested_object; - - bool prohibit_cond_pushdown; - - /* - I_S: how to read the tables (SKIP_OPEN_TABLE/OPEN_FRM_ONLY/OPEN_FULL_TABLE) - */ - uint table_open_method; - /* - I_S: where the schema table was filled - (this is a hack. The code should be able to figure out whether reading - from I_S should be done by create_sort_index() or by JOIN::exec.) - */ - enum enum_schema_table_state schema_table_state; - - /* Something like a "query plan" for reading INFORMATION_SCHEMA table */ - IS_table_read_plan *is_table_read_plan; - - MDL_request mdl_request; - -#ifdef WITH_PARTITION_STORAGE_ENGINE - /* List to carry partition names from PARTITION (...) clause in statement */ - List *partition_names; -#endif /* WITH_PARTITION_STORAGE_ENGINE */ - - void calc_md5(const char *buffer); - int view_check_option(THD *thd, bool ignore_failure); - bool create_field_translation(THD *thd); - bool setup_underlying(THD *thd); - void cleanup_items(); - bool placeholder() - { - return derived || view || schema_table || !table; - } - void print(THD *thd, table_map eliminated_tables, String *str, - enum_query_type query_type); - bool check_single_table(TABLE_LIST **table, table_map map, - TABLE_LIST *view); - bool set_insert_values(MEM_ROOT *mem_root); - void hide_view_error(THD *thd); - TABLE_LIST *find_underlying_table(TABLE *table); - TABLE_LIST *first_leaf_for_name_resolution(); - TABLE_LIST *last_leaf_for_name_resolution(); - - /* System Versioning */ - vers_select_conds_t vers_conditions; - vers_select_conds_t period_conditions; - - bool has_period() const - { - return period_conditions.is_set(); - } - - my_bool for_insert_data; - - /** - @brief - Find the bottom in the chain of embedded table VIEWs. - - @detail - This is used for single-table UPDATE/DELETE when they are modifying a - single-table VIEW. - */ - TABLE_LIST *find_table_for_update() - { - TABLE_LIST *tbl= this; - while(!tbl->is_multitable() && tbl->single_table_updatable() && - tbl->merge_underlying_list) - { - tbl= tbl->merge_underlying_list; - } - return tbl; - } - TABLE *get_real_join_table(); - bool is_leaf_for_name_resolution(); - inline TABLE_LIST *top_table() - { return belong_to_view ? belong_to_view : this; } - inline bool prepare_check_option(THD *thd) - { - bool res= FALSE; - if (effective_with_check) - res= prep_check_option(thd, effective_with_check); - return res; - } - inline bool prepare_where(THD *thd, Item **conds, - bool no_where_clause) - { - if (!view || is_merged_derived()) - return prep_where(thd, conds, no_where_clause); - return FALSE; - } - - void register_want_access(privilege_t want_access); - bool prepare_security(THD *thd); -#ifndef NO_EMBEDDED_ACCESS_CHECKS - Security_context *find_view_security_context(THD *thd); - bool prepare_view_security_context(THD *thd); -#endif - /* - Cleanup for re-execution in a prepared statement or a stored - procedure. - */ - void reinit_before_use(THD *thd); - Item_subselect *containing_subselect(); - - /* - Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query, - TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by, - TABLE::force_index and TABLE::covering_keys. - */ - bool process_index_hints(TABLE *table); - - /** - Compare the version of metadata from the previous execution - (if any) with values obtained from the current table - definition cache element. - - @sa check_and_update_table_version() - */ - inline bool is_table_ref_id_equal(TABLE_SHARE *s) const - { - return (m_table_ref_type == s->get_table_ref_type() && - m_table_ref_version == s->get_table_ref_version()); - } - - /** - Record the value of metadata version of the corresponding - table definition cache element in this parse tree node. - - @sa check_and_update_table_version() - */ - inline void set_table_ref_id(TABLE_SHARE *s) - { set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version()); } - - inline void set_table_ref_id(enum_table_ref_type table_ref_type_arg, - ulong table_ref_version_arg) - { - m_table_ref_type= table_ref_type_arg; - m_table_ref_version= table_ref_version_arg; - } - - /* Set of functions returning/setting state of a derived table/view. */ - bool is_non_derived() const { return (!derived_type); } - bool is_view_or_derived() const { return derived_type; } - bool is_view() const { return (derived_type & DTYPE_VIEW); } - bool is_derived() const { return (derived_type & DTYPE_TABLE); } - bool is_with_table(); - bool is_recursive_with_table(); - bool is_with_table_recursive_reference(); - void register_as_derived_with_rec_ref(With_element *rec_elem); - bool is_nonrecursive_derived_with_rec_ref(); - bool fill_recursive(THD *thd); - - inline void set_view() - { - derived_type= DTYPE_VIEW; - } - inline void set_derived() - { - derived_type= DTYPE_TABLE; - } - bool is_merged_derived() const { return (derived_type & DTYPE_MERGE); } - inline void set_merged_derived() - { - DBUG_ENTER("set_merged_derived"); - DBUG_PRINT("enter", ("Alias: '%s' Unit: %p", - (alias.str ? alias.str : ""), - get_unit())); - derived_type= static_cast((derived_type & DTYPE_MASK) | - DTYPE_TABLE | DTYPE_MERGE); - set_check_merged(); - DBUG_VOID_RETURN; - } - bool is_materialized_derived() const - { - return (derived_type & DTYPE_MATERIALIZE); - } - void set_materialized_derived() - { - DBUG_ENTER("set_materialized_derived"); - DBUG_PRINT("enter", ("Alias: '%s' Unit: %p", - (alias.str ? alias.str : ""), - get_unit())); - derived= get_unit(); - derived_type= static_cast((derived_type & - (derived ? DTYPE_MASK : DTYPE_VIEW)) | - DTYPE_TABLE | DTYPE_MATERIALIZE); - set_check_materialized(); - DBUG_VOID_RETURN; - } - bool is_multitable() const { return (derived_type & DTYPE_MULTITABLE); } - inline void set_multitable() - { - derived_type|= DTYPE_MULTITABLE; - } - bool set_as_with_table(THD *thd, With_element *with_elem); - void reset_const_table(); - bool handle_derived(LEX *lex, uint phases); - - /** - @brief True if this TABLE_LIST represents an anonymous derived table, - i.e. the result of a subquery. - */ - bool is_anonymous_derived_table() const { return derived && !view; } - - /** - @brief Returns the name of the database that the referenced table belongs - to. - */ - const char *get_db_name() const { return view != NULL ? view_db.str : db.str; } - - /** - @brief Returns the name of the table that this TABLE_LIST represents. - - @details The unqualified table name or view name for a table or view, - respectively. - */ - const char *get_table_name() const { return view != NULL ? view_name.str : table_name.str; } - bool is_active_sjm(); - bool is_jtbm() { return MY_TEST(jtbm_subselect != NULL); } - st_select_lex_unit *get_unit(); - st_select_lex *get_single_select(); - void wrap_into_nested_join(List &join_list); - bool init_derived(THD *thd, bool init_view); - int fetch_number_of_rows(); - bool change_refs_to_fields(); - - bool single_table_updatable(); - - bool is_inner_table_of_outer_join() - { - for (TABLE_LIST *tbl= this; tbl; tbl= tbl->embedding) - { - if (tbl->outer_join) - return true; - } - return false; - } - void set_lock_type(THD* thd, enum thr_lock_type lock); - - derived_handler *find_derived_handler(THD *thd); - TABLE_LIST *get_first_table(); - - void remove_join_columns() - { - if (join_columns) - { - join_columns->empty(); - join_columns= NULL; - is_join_columns_complete= FALSE; - } - } - -private: - bool prep_check_option(THD *thd, uint8 check_opt_type); - bool prep_where(THD *thd, Item **conds, bool no_where_clause); - void set_check_materialized(); -#ifndef DBUG_OFF - void set_check_merged(); -#else - inline void set_check_merged() {} -#endif - /** See comments for set_table_ref_id() */ - enum enum_table_ref_type m_table_ref_type; - /** See comments for set_table_ref_id() */ - ulong m_table_ref_version; -}; - -class Item; - -/* - Iterator over the fields of a generic table reference. -*/ - -class Field_iterator: public Sql_alloc -{ -public: - Field_iterator() {} /* Remove gcc warning */ - virtual ~Field_iterator() {} - virtual void set(TABLE_LIST *)= 0; - virtual void next()= 0; - virtual bool end_of_fields()= 0; /* Return 1 at end of list */ - virtual LEX_CSTRING *name()= 0; - virtual Item *create_item(THD *)= 0; - virtual Field *field()= 0; -}; - - -/* - Iterator over the fields of a base table, view with temporary - table, or subquery. -*/ - -class Field_iterator_table: public Field_iterator -{ - Field **ptr; -public: - Field_iterator_table() :ptr(0) {} - void set(TABLE_LIST *table) { ptr= table->table->field; } - void set_table(TABLE *table) { ptr= table->field; } - void next() { ptr++; } - bool end_of_fields() { return *ptr == 0; } - LEX_CSTRING *name(); - Item *create_item(THD *thd); - Field *field() { return *ptr; } -}; - - -/* Iterator over the fields of a merge view. */ - -class Field_iterator_view: public Field_iterator -{ - Field_translator *ptr, *array_end; - TABLE_LIST *view; -public: - Field_iterator_view() :ptr(0), array_end(0) {} - void set(TABLE_LIST *table); - void next() { ptr++; } - bool end_of_fields() { return ptr == array_end; } - LEX_CSTRING *name(); - Item *create_item(THD *thd); - Item **item_ptr() {return &ptr->item; } - Field *field() { return 0; } - inline Item *item() { return ptr->item; } - Field_translator *field_translator() { return ptr; } -}; - - -/* - Field_iterator interface to the list of materialized fields of a - NATURAL/USING join. -*/ - -class Field_iterator_natural_join: public Field_iterator -{ - List_iterator_fast column_ref_it; - Natural_join_column *cur_column_ref; -public: - Field_iterator_natural_join() :cur_column_ref(NULL) {} - ~Field_iterator_natural_join() {} - void set(TABLE_LIST *table); - void next(); - bool end_of_fields() { return !cur_column_ref; } - LEX_CSTRING *name() { return cur_column_ref->name(); } - Item *create_item(THD *thd) { return cur_column_ref->create_item(thd); } - Field *field() { return cur_column_ref->field(); } - Natural_join_column *column_ref() { return cur_column_ref; } -}; - - -/* - Generic iterator over the fields of an arbitrary table reference. - - DESCRIPTION - This class unifies the various ways of iterating over the columns - of a table reference depending on the type of SQL entity it - represents. If such an entity represents a nested table reference, - this iterator encapsulates the iteration over the columns of the - members of the table reference. - - IMPLEMENTATION - The implementation assumes that all underlying NATURAL/USING table - references already contain their result columns and are linked into - the list TABLE_LIST::next_name_resolution_table. -*/ - -class Field_iterator_table_ref: public Field_iterator -{ - TABLE_LIST *table_ref, *first_leaf, *last_leaf; - Field_iterator_table table_field_it; - Field_iterator_view view_field_it; - Field_iterator_natural_join natural_join_it; - Field_iterator *field_it; - void set_field_iterator(); -public: - Field_iterator_table_ref() :field_it(NULL) {} - void set(TABLE_LIST *table); - void next(); - bool end_of_fields() - { return (table_ref == last_leaf && field_it->end_of_fields()); } - LEX_CSTRING *name() { return field_it->name(); } - const char *get_table_name(); - const char *get_db_name(); - GRANT_INFO *grant(); - Item *create_item(THD *thd) { return field_it->create_item(thd); } - Field *field() { return field_it->field(); } - Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref); - Natural_join_column *get_natural_column_ref(); -}; - - -#define JOIN_OP_NEST 1 -#define REBALANCED_NEST 2 - -typedef struct st_nested_join -{ - List join_list; /* list of elements in the nested join */ - /* - Currently the valid values for nest type are: - JOIN_OP_NEST - for nest created for JOIN operation used as an operand in - a join expression, contains 2 elements; - JOIN_OP_NEST | REBALANCED_NEST - nest created after tree re-balancing - in st_select_lex::add_cross_joined_table(), contains 1 element; - 0 - for all other nests. - Examples: - 1. SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a; - Here the nest created for LEFT JOIN at first has nest_type==JOIN_OP_NEST. - After re-balancing in st_select_lex::add_cross_joined_table() this nest - has nest_type==JOIN_OP_NEST | REBALANCED_NEST. The nest for JOIN created - in st_select_lex::add_cross_joined_table() has nest_type== JOIN_OP_NEST. - 2. SELECT * FROM t1 JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a) - Here the nest created for LEFT JOIN has nest_type==0, because it's not - an operand in a join expression. The nest created for JOIN has nest_type - set to JOIN_OP_NEST. - */ - uint nest_type; - /* - Bitmap of tables within this nested join (including those embedded within - its children), including tables removed by table elimination. - */ - table_map used_tables; - table_map not_null_tables; /* tables that rejects nulls */ - /** - Used for pointing out the first table in the plan being covered by this - join nest. It is used exclusively within make_outerjoin_info(). - */ - struct st_join_table *first_nested; - /* - Used to count tables in the nested join in 2 isolated places: - 1. In make_outerjoin_info(). - 2. check_interleaving_with_nj/restore_prev_nj_state (these are called - by the join optimizer. - Before each use the counters are zeroed by reset_nj_counters. - */ - uint counter; - - /* - Number of elements in join_list that participate in the join plan choice: - - Base tables that were not removed by table elimination - - Join nests that were not removed by mark_join_nest_as_const - */ - uint n_tables; - nested_join_map nj_map; /* Bit used to identify this nested join*/ - /* - (Valid only for semi-join nests) Bitmap of tables outside the semi-join - that are used within the semi-join's ON condition. - */ - table_map sj_depends_on; - /* Outer non-trivially correlated tables */ - table_map sj_corr_tables; - List sj_outer_expr_list; - /** - True if this join nest node is completely covered by the query execution - plan. This means two things. - - 1. All tables on its @c join_list are covered by the plan. - - 2. All child join nest nodes are fully covered. - */ - bool is_fully_covered() const { return n_tables == counter; } -} NESTED_JOIN; - - -typedef struct st_changed_table_list -{ - struct st_changed_table_list *next; - char *key; - size_t key_length; -} CHANGED_TABLE_LIST; - - -typedef struct st_open_table_list{ - struct st_open_table_list *next; - char *db,*table; - uint32 in_use,locked; -} OPEN_TABLE_LIST; - - -static inline my_bitmap_map *tmp_use_all_columns(TABLE *table, - MY_BITMAP *bitmap) -{ - my_bitmap_map *old= bitmap->bitmap; - bitmap->bitmap= table->s->all_set.bitmap; - return old; -} - - -static inline void tmp_restore_column_map(MY_BITMAP *bitmap, - my_bitmap_map *old) -{ - bitmap->bitmap= old; -} - -/* The following is only needed for debugging */ - -static inline my_bitmap_map *dbug_tmp_use_all_columns(TABLE *table, - MY_BITMAP *bitmap) -{ -#ifdef DBUG_ASSERT_EXISTS - return tmp_use_all_columns(table, bitmap); -#else - return 0; -#endif -} - -static inline void dbug_tmp_restore_column_map(MY_BITMAP *bitmap, - my_bitmap_map *old) -{ -#ifdef DBUG_ASSERT_EXISTS - tmp_restore_column_map(bitmap, old); -#endif -} - - -/* - Variant of the above : handle both read and write sets. - Provide for the possiblity of the read set being the same as the write set -*/ -static inline void dbug_tmp_use_all_columns(TABLE *table, - my_bitmap_map **save, - MY_BITMAP *read_set, - MY_BITMAP *write_set) -{ -#ifdef DBUG_ASSERT_EXISTS - save[0]= read_set->bitmap; - save[1]= write_set->bitmap; - (void) tmp_use_all_columns(table, read_set); - (void) tmp_use_all_columns(table, write_set); -#endif -} - - -static inline void dbug_tmp_restore_column_maps(MY_BITMAP *read_set, - MY_BITMAP *write_set, - my_bitmap_map **old) -{ -#ifdef DBUG_ASSERT_EXISTS - tmp_restore_column_map(read_set, old[0]); - tmp_restore_column_map(write_set, old[1]); -#endif -} - -bool ok_for_lower_case_names(const char *names); - -enum get_table_share_flags { - GTS_TABLE = 1, - GTS_VIEW = 2, - GTS_NOLOCK = 4, - GTS_USE_DISCOVERY = 8, - GTS_FORCE_DISCOVERY = 16 -}; - -size_t max_row_length(TABLE *table, MY_BITMAP const *cols, const uchar *data); - -void init_mdl_requests(TABLE_LIST *table_list); - -enum open_frm_error open_table_from_share(THD *thd, TABLE_SHARE *share, - const LEX_CSTRING *alias, uint db_stat, uint prgflag, - uint ha_open_flags, TABLE *outparam, - bool is_create_table, - List *partitions_to_open= NULL); -bool copy_keys_from_share(TABLE *outparam, MEM_ROOT *root); -bool fix_session_vcol_expr(THD *thd, Virtual_column_info *vcol); -bool fix_session_vcol_expr_for_read(THD *thd, Field *field, - Virtual_column_info *vcol); -bool parse_vcol_defs(THD *thd, MEM_ROOT *mem_root, TABLE *table, - bool *error_reported, vcol_init_mode expr); -TABLE_SHARE *alloc_table_share(const char *db, const char *table_name, - const char *key, uint key_length); -void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key, - uint key_length, - const char *table_name, const char *path); -void free_table_share(TABLE_SHARE *share); -enum open_frm_error open_table_def(THD *thd, TABLE_SHARE *share, - uint flags = GTS_TABLE); - -void open_table_error(TABLE_SHARE *share, enum open_frm_error error, - int db_errno); -void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form); -bool check_db_name(LEX_STRING *db); -bool check_column_name(const char *name); -bool check_table_name(const char *name, size_t length, bool check_for_path_chars); -int rename_file_ext(const char * from,const char * to,const char * ext); -char *get_field(MEM_ROOT *mem, Field *field); -bool get_field(MEM_ROOT *mem, Field *field, class String *res); - -bool validate_comment_length(THD *thd, LEX_CSTRING *comment, size_t max_len, - uint err_code, const char *name); - -int closefrm(TABLE *table); -void free_blobs(TABLE *table); -void free_field_buffers_larger_than(TABLE *table, uint32 size); -ulong get_form_pos(File file, uchar *head, TYPELIB *save_names); -void append_unescaped(String *res, const char *pos, size_t length); -void prepare_frm_header(THD *thd, uint reclength, uchar *fileinfo, - HA_CREATE_INFO *create_info, uint keys, KEY *key_info); -const char *fn_frm_ext(const char *name); - -/* Check that the integer is in the internal */ -static inline int set_zone(int nr,int min_zone,int max_zone) -{ - if (nr <= min_zone) - return min_zone; - if (nr >= max_zone) - return max_zone; - return nr; -} - -/* performance schema */ -extern LEX_CSTRING PERFORMANCE_SCHEMA_DB_NAME; - -extern LEX_CSTRING GENERAL_LOG_NAME; -extern LEX_CSTRING SLOW_LOG_NAME; -extern LEX_CSTRING TRANSACTION_REG_NAME; - -/* information schema */ -extern LEX_CSTRING INFORMATION_SCHEMA_NAME; -extern LEX_CSTRING MYSQL_SCHEMA_NAME; - -/* table names */ -extern LEX_CSTRING MYSQL_PROC_NAME; - -inline bool is_infoschema_db(const LEX_CSTRING *name) -{ - return lex_string_eq(&INFORMATION_SCHEMA_NAME, name); -} - -inline bool is_perfschema_db(const LEX_CSTRING *name) -{ - return lex_string_eq(&PERFORMANCE_SCHEMA_DB_NAME, name); -} - -inline void mark_as_null_row(TABLE *table) -{ - table->null_row=1; - table->status|=STATUS_NULL_ROW; - bfill(table->null_flags,table->s->null_bytes,255); -} - -bool is_simple_order(ORDER *order); - -class Open_tables_backup; - -/** Transaction Registry Table (TRT) - - This table holds transaction IDs, their corresponding times and other - transaction-related data which is used for transaction order resolution. - When versioned table marks its records lifetime with transaction IDs, - TRT is used to get their actual timestamps. */ - -class TR_table: public TABLE_LIST -{ - THD *thd; - Open_tables_backup *open_tables_backup; - -public: - enum field_id_t { - FLD_TRX_ID= 0, - FLD_COMMIT_ID, - FLD_BEGIN_TS, - FLD_COMMIT_TS, - FLD_ISO_LEVEL, - FIELD_COUNT - }; - - enum enabled {NO, MAYBE, YES}; - static enum enabled use_transaction_registry; - - /** - @param[in,out] Thread handle - @param[in] Current transaction is read-write. - */ - TR_table(THD *_thd, bool rw= false); - /** - Opens a transaction_registry table. - - @retval true on error, false otherwise. - */ - bool open(); - ~TR_table(); - /** - @retval current thd - */ - THD *get_thd() const { return thd; } - /** - Stores value to internal transaction_registry TABLE object. - - @param[in] field number in a TABLE - @param[in] value to store - */ - void store(uint field_id, ulonglong val); - /** - Stores value to internal transaction_registry TABLE object. - - @param[in] field number in a TABLE - @param[in] value to store - */ - void store(uint field_id, timeval ts); - /** - Update the transaction_registry right before commit. - @param start_id transaction identifier at start - @param end_id transaction identifier at commit - - @retval false on success - @retval true on error (the transaction must be rolled back) - */ - bool update(ulonglong start_id, ulonglong end_id); - // return true if found; false if not found or error - bool query(ulonglong trx_id); - /** - Gets a row from transaction_registry with the closest commit_timestamp to - first argument. We can search for a value which a lesser or greater than - first argument. Also loads a row into an internal TABLE object. - - @param[in] timestamp - @param[in] true if we search for a lesser timestamp, false if greater - @retval true if exists, false it not exists or an error occurred - */ - bool query(MYSQL_TIME &commit_time, bool backwards); - /** - Checks whether transaction1 sees transaction0. - - @param[out] true if transaction1 sees transaction0, undefined on error and - when transaction1=transaction0 and false otherwise - @param[in] transaction_id of transaction1 - @param[in] transaction_id of transaction0 - @param[in] commit time of transaction1 or 0 if we want it to be queried - @param[in] isolation level (from handler.h) of transaction1 - @param[in] commit time of transaction0 or 0 if we want it to be queried - @retval true on error, false otherwise - */ - bool query_sees(bool &result, ulonglong trx_id1, ulonglong trx_id0, - ulonglong commit_id1= 0, - enum_tx_isolation iso_level1= ISO_READ_UNCOMMITTED, - ulonglong commit_id0= 0); - - /** - @retval transaction isolation level of a row from internal TABLE object. - */ - enum_tx_isolation iso_level() const; - /** - Stores transactioin isolation level to internal TABLE object. - */ - void store_iso_level(enum_tx_isolation iso_level) - { - DBUG_ASSERT(iso_level <= ISO_SERIALIZABLE); - store(FLD_ISO_LEVEL, iso_level + 1); - } - - /** - Writes a message to MariaDB log about incorrect transaction_registry schema. - - @param[in] a message explained what's incorrect in schema - */ - void warn_schema_incorrect(const char *reason); - /** - Checks whether transaction_registry table has a correct schema. - - @retval true if schema is incorrect and false otherwise - */ - bool check(bool error); - - TABLE * operator-> () const - { - return table; - } - Field * operator[] (uint field_id) const - { - DBUG_ASSERT(field_id < FIELD_COUNT); - return table->field[field_id]; - } - operator bool () const - { - return table; - } - bool operator== (const TABLE_LIST &subj) const - { - return (!cmp(&db, &subj.db) && !cmp(&table_name, &subj.table_name)); - } - bool operator!= (const TABLE_LIST &subj) const - { - return !(*this == subj); - } -}; - -#endif /* MYSQL_CLIENT */ - -#endif /* TABLE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/table_cache.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/table_cache.h deleted file mode 100644 index 433df5e..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/table_cache.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef TABLE_CACHE_H_INCLUDED -#define TABLE_CACHE_H_INCLUDED -/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 2010, 2011 Monty Program Ab - Copyright (C) 2013 Sergey Vojtovich and MariaDB Foundation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -struct Share_free_tables -{ - typedef I_P_List List; - List list; - /** Avoid false sharing between instances */ - char pad[CPU_LEVEL1_DCACHE_LINESIZE]; -}; - - -struct TDC_element -{ - uchar m_key[NAME_LEN + 1 + NAME_LEN + 1]; - uint m_key_length; - bool flushed; - TABLE_SHARE *share; - - /** - Protects ref_count, m_flush_tickets, all_tables, flushed, all_tables_refs. - */ - mysql_mutex_t LOCK_table_share; - mysql_cond_t COND_release; - TDC_element *next, **prev; /* Link to unused shares */ - uint ref_count; /* How many TABLE objects uses this */ - uint all_tables_refs; /* Number of refs to all_tables */ - /** - List of tickets representing threads waiting for the share to be flushed. - */ - Wait_for_flush_list m_flush_tickets; - /* - Doubly-linked (back-linked) lists of used and unused TABLE objects - for this share. - */ - All_share_tables_list all_tables; - /** Avoid false sharing between TDC_element and free_tables */ - char pad[CPU_LEVEL1_DCACHE_LINESIZE]; - Share_free_tables free_tables[1]; - - inline void wait_for_refs(uint my_refs); - void flush(THD *thd, bool mark_flushed); - void flush_unused(bool mark_flushed); -}; - - -extern ulong tdc_size; -extern ulong tc_size; -extern uint32 tc_instances; - -extern bool tdc_init(void); -extern void tdc_start_shutdown(void); -extern void tdc_deinit(void); -extern ulong tdc_records(void); -extern void tdc_purge(bool all); -extern TDC_element *tdc_lock_share(THD *thd, const char *db, - const char *table_name); -extern void tdc_unlock_share(TDC_element *element); -int tdc_share_is_cached(THD *thd, const char *db, const char *table_name); -extern TABLE_SHARE *tdc_acquire_share(THD *thd, TABLE_LIST *tl, uint flags, - TABLE **out_table= 0); -extern void tdc_release_share(TABLE_SHARE *share); -void tdc_remove_referenced_share(THD *thd, TABLE_SHARE *share); -void tdc_remove_table(THD *thd, const char *db, const char *table_name); - -extern int tdc_wait_for_old_version(THD *thd, const char *db, - const char *table_name, - ulong wait_timeout, uint deadlock_weight); -extern int tdc_iterate(THD *thd, my_hash_walk_action action, void *argument, - bool no_dups= false); - -extern uint tc_records(void); -int show_tc_active_instances(THD *thd, SHOW_VAR *var, char *buff, - enum enum_var_type scope); -extern void tc_purge(); -extern void tc_add_table(THD *thd, TABLE *table); -extern void tc_release_table(TABLE *table); -extern TABLE *tc_acquire_table(THD *thd, TDC_element *element); - -/** - Create a table cache key for non-temporary table. - - @param key Buffer for key (must be at least NAME_LEN*2+2 bytes). - @param db Database name. - @param table_name Table name. - - @return Length of key. -*/ - -inline uint tdc_create_key(char *key, const char *db, const char *table_name) -{ - /* - In theory caller should ensure that both db and table_name are - not longer than NAME_LEN bytes. In practice we play safe to avoid - buffer overruns. - */ - return (uint) (strmake(strmake(key, db, NAME_LEN) + 1, table_name, - NAME_LEN) - key + 1); -} -#endif /* TABLE_CACHE_H_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_alarm.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_alarm.h deleted file mode 100644 index 250590a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_alarm.h +++ /dev/null @@ -1,115 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Prototypes when using thr_alarm library functions */ - -#ifndef _thr_alarm_h -#define _thr_alarm_h -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef USE_ALARM_THREAD -#define USE_ONE_SIGNAL_HAND /* One must call process_alarm */ -#endif -#ifdef HAVE_rts_threads -#undef USE_ONE_SIGNAL_HAND -#define USE_ALARM_THREAD -#define THR_SERVER_ALARM SIGUSR1 -#else -#define THR_SERVER_ALARM SIGALRM -#endif - -typedef struct st_alarm_info -{ - time_t next_alarm_time; - uint active_alarms; - uint max_used_alarms; -} ALARM_INFO; - -void thr_alarm_info(ALARM_INFO *info); -extern my_bool my_disable_thr_alarm; - -#ifdef _WIN32 -#define DONT_USE_THR_ALARM -#endif -#if defined(DONT_USE_THR_ALARM) - -#define USE_ALARM_THREAD -#undef USE_ONE_SIGNAL_HAND - -typedef my_bool thr_alarm_t; -typedef my_bool ALARM; - -#define thr_alarm_init(A) (*(A))=0 -#define thr_alarm_in_use(A) (*(A) != 0) -#define thr_end_alarm(A) -#define thr_alarm(A,B,C) ((*(A)=1)-1) -/* The following should maybe be (*(A)) */ -#define thr_got_alarm(A) 0 -#define init_thr_alarm(A) -#define thr_alarm_kill(A) -#define resize_thr_alarm(N) -#define end_thr_alarm(A) - -#else -#if defined(__WIN__) -typedef struct st_thr_alarm_entry -{ - UINT_PTR crono; -} thr_alarm_entry; - -#else /* System with posix threads */ - -typedef int thr_alarm_entry; - -#define thr_got_alarm(thr_alarm) (**(thr_alarm)) - -#endif /* __WIN__ */ - -typedef thr_alarm_entry* thr_alarm_t; - -typedef struct st_alarm { - time_t expire_time; - thr_alarm_entry alarmed; /* set when alarm is due */ - pthread_t thread; - my_thread_id thread_id; - uint index_in_queue; - my_bool malloced; -} ALARM; - -extern uint thr_client_alarm; -extern pthread_t alarm_thread; - -#define thr_alarm_init(A) (*(A))=0 -#define thr_alarm_in_use(A) (*(A)!= 0) -void init_thr_alarm(uint max_alarm); -void resize_thr_alarm(uint max_alarms); -my_bool thr_alarm(thr_alarm_t *alarmed, uint sec, ALARM *buff); -void thr_alarm_kill(my_thread_id thread_id); -void thr_end_alarm(thr_alarm_t *alarmed); -void end_thr_alarm(my_bool free_structures); -sig_handler process_alarm(int); -#ifndef thr_got_alarm -my_bool thr_got_alarm(thr_alarm_t *alrm); -#endif - - -#endif /* DONT_USE_THR_ALARM */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* _thr_alarm_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_lock.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_lock.h deleted file mode 100644 index 1ea2413..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_lock.h +++ /dev/null @@ -1,182 +0,0 @@ -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* For use with thr_lock:s */ - -#ifndef _thr_lock_h -#define _thr_lock_h -#ifdef __cplusplus -extern "C" { -#endif -#include -#include - -struct st_thr_lock; -extern ulong locks_immediate,locks_waited ; - -/* - Important: if a new lock type is added, a matching lock description - must be added to sql_test.cc's lock_descriptions array. -*/ -enum thr_lock_type { TL_IGNORE=-1, - TL_UNLOCK, /* UNLOCK ANY LOCK */ - /* - Parser only! At open_tables() becomes TL_READ or - TL_READ_NO_INSERT depending on the binary log format - (SBR/RBR) and on the table category (log table). - Used for tables that are read by statements which - modify tables. - */ - TL_READ_DEFAULT, - TL_READ, /* Read lock */ - TL_READ_WITH_SHARED_LOCKS, - /* High prior. than TL_WRITE. Allow concurrent insert */ - TL_READ_HIGH_PRIORITY, - /* READ, Don't allow concurrent insert */ - TL_READ_NO_INSERT, - /* - Write lock, but allow other threads to read / write. - Used by BDB tables in MySQL to mark that someone is - reading/writing to the table. - */ - TL_WRITE_ALLOW_WRITE, - /* - WRITE lock used by concurrent insert. Will allow - READ, if one could use concurrent insert on table. - */ - TL_WRITE_CONCURRENT_INSERT, - /* Write used by INSERT DELAYED. Allows READ locks */ - TL_WRITE_DELAYED, - /* - parser only! Late bound low_priority flag. - At open_tables() becomes thd->update_lock_default. - */ - TL_WRITE_DEFAULT, - /* WRITE lock that has lower priority than TL_READ */ - TL_WRITE_LOW_PRIORITY, - /* Normal WRITE lock */ - TL_WRITE, - /* Abort new lock request with an error */ - TL_WRITE_ONLY}; - -enum enum_thr_lock_result { THR_LOCK_SUCCESS= 0, THR_LOCK_ABORTED= 1, - THR_LOCK_WAIT_TIMEOUT= 2, THR_LOCK_DEADLOCK= 3 }; - - -/* Priority for locks */ -#define THR_LOCK_LATE_PRIV 1U /* For locks to be merged with org lock */ -#define THR_LOCK_MERGE_PRIV 2U /* For merge tables */ - -#define THR_UNLOCK_UPDATE_STATUS 1U - -extern ulong max_write_lock_count; -extern my_bool thr_lock_inited; -extern enum thr_lock_type thr_upgraded_concurrent_insert_lock; - -/* - A description of the thread which owns the lock. The address - of an instance of this structure is used to uniquely identify the thread. -*/ - -typedef struct st_thr_lock_info -{ - pthread_t thread; - my_thread_id thread_id; - void *mysql_thd; // THD pointer -} THR_LOCK_INFO; - - -typedef struct st_thr_lock_data { - THR_LOCK_INFO *owner; - struct st_thr_lock_data *next,**prev; - struct st_thr_lock *lock; - mysql_cond_t *cond; - void *status_param; /* Param to status functions */ - void *debug_print_param; /* For error messages */ - struct PSI_table *m_psi; - enum thr_lock_type type; - enum thr_lock_type org_type; /* Cache for MariaDB */ - uint priority; -} THR_LOCK_DATA; - -struct st_lock_list { - THR_LOCK_DATA *data,**last; -}; - -typedef struct st_thr_lock { - LIST list; - mysql_mutex_t mutex; - struct st_lock_list read_wait; - struct st_lock_list read; - struct st_lock_list write_wait; - struct st_lock_list write; - /* write_lock_count is incremented for write locks and reset on read locks */ - ulong write_lock_count; - uint read_no_write_count; - my_bool (*get_status)(void*, my_bool);/* Called when one gets a lock */ - void (*copy_status)(void*,void*); - void (*update_status)(void*); /* Before release of write */ - void (*restore_status)(void*); /* Before release of read */ - my_bool (*start_trans)(void*); /* When all locks are taken */ - my_bool (*check_status)(void *); - void (*fix_status)(void *, void *);/* For thr_merge_locks() */ - const char *name; /* Used for error reporting */ - my_bool allow_multiple_concurrent_insert; -} THR_LOCK; - - -extern LIST *thr_lock_thread_list; -extern mysql_mutex_t THR_LOCK_lock; -struct st_my_thread_var; - -my_bool init_thr_lock(void); /* Must be called once/thread */ -void thr_lock_info_init(THR_LOCK_INFO *info, struct st_my_thread_var *tmp); -void thr_lock_init(THR_LOCK *lock); -void thr_lock_delete(THR_LOCK *lock); -void thr_lock_data_init(THR_LOCK *lock,THR_LOCK_DATA *data, - void *status_param); -void thr_unlock(THR_LOCK_DATA *data, uint unlock_flags); -enum enum_thr_lock_result thr_multi_lock(THR_LOCK_DATA **data, - uint count, THR_LOCK_INFO *owner, - ulong lock_wait_timeout); -void thr_multi_unlock(THR_LOCK_DATA **data,uint count, uint unlock_flags); -void thr_merge_locks(THR_LOCK_DATA **data, uint org_count, uint new_count); -void thr_abort_locks(THR_LOCK *lock, my_bool upgrade_lock); -my_bool thr_abort_locks_for_thread(THR_LOCK *lock, my_thread_id thread); -void thr_print_locks(void); /* For debugging */ -my_bool thr_upgrade_write_delay_lock(THR_LOCK_DATA *data, - enum thr_lock_type new_lock_type, - ulong lock_wait_timeout); -void thr_downgrade_write_lock(THR_LOCK_DATA *data, - enum thr_lock_type new_lock_type); -my_bool thr_reschedule_write_lock(THR_LOCK_DATA *data, - ulong lock_wait_timeout); -void thr_set_lock_wait_callback(void (*before_wait)(void), - void (*after_wait)(void)); - -#ifdef WITH_WSREP - typedef my_bool (* wsrep_thd_is_brute_force_fun)(const MYSQL_THD, my_bool); - typedef my_bool(* wsrep_abort_thd_fun)(MYSQL_THD, MYSQL_THD, my_bool); - typedef my_bool (* wsrep_on_fun)(const MYSQL_THD); - void wsrep_thr_lock_init( - wsrep_thd_is_brute_force_fun bf_fun, wsrep_abort_thd_fun abort_fun, - my_bool debug, my_bool convert_LOCK_to_trx, wsrep_on_fun on_fun); -#endif - -#ifdef __cplusplus -} -#endif -#endif /* _thr_lock_h */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_malloc.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_malloc.h deleted file mode 100644 index cc56666..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_malloc.h +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef THR_MALLOC_INCLUDED -#define THR_MALLOC_INCLUDED - -typedef struct st_mem_root MEM_ROOT; - -void init_sql_alloc(PSI_memory_key key, MEM_ROOT *root, uint block_size, uint - pre_alloc_size, myf my_flags); -char *sql_strmake_with_convert(THD *thd, const char *str, size_t arg_length, - CHARSET_INFO *from_cs, - size_t max_res_length, - CHARSET_INFO *to_cs, size_t *result_length); - -#endif /* THR_MALLOC_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_timer.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_timer.h deleted file mode 100644 index 6bca815..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thr_timer.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 2014 Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 or later of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* Prototypes when using thr_timer functions */ - -#ifndef THR_TIMER_INCLUDED -#define THR_TIMER_INCLUDED -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct st_timer { - struct timespec expire_time; - ulonglong period; - my_bool expired; - uint index_in_queue; - void (*func)(void*); - void *func_arg; -} thr_timer_t; - -/* Main functions for library */ -my_bool init_thr_timer(uint init_size_for_timer_queue); -void end_thr_timer(); - -/* Functions for handling one timer */ -void thr_timer_init(thr_timer_t *timer_data, void(*function)(void*), - void *arg); -void thr_timer_set_period(thr_timer_t* timer_data, ulonglong microseconds); -my_bool thr_timer_settime(thr_timer_t *timer_data, ulonglong microseconds); -void thr_timer_end(thr_timer_t *timer_data); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* THR_TIMER_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thread_cache.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/thread_cache.h deleted file mode 100644 index 5cb6c0f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thread_cache.h +++ /dev/null @@ -1,210 +0,0 @@ -/* - Copyright (C) 2020 MariaDB Foundation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - - -/** - MariaDB thread cache for "one thread per connection" scheduler. - - Thread cache allows to re-use threads (as well as THD objects) for - subsequent connections. -*/ -class Thread_cache -{ - mutable mysql_cond_t COND_thread_cache; - mutable mysql_cond_t COND_flush_thread_cache; - mutable mysql_mutex_t LOCK_thread_cache; - /** Queue of new connection requests. */ - I_List list; - /** Number of threads parked in the cache. */ - ulong cached_thread_count; - /** Number of active flush requests. */ - uint32_t kill_cached_threads; - /** - PFS stuff, only used during initialization. - Unfortunately needs to survive till destruction. - */ - PSI_cond_key key_COND_thread_cache, key_COND_flush_thread_cache; - PSI_mutex_key key_LOCK_thread_cache; - -public: - void init() - { -#ifdef HAVE_PSI_INTERFACE - PSI_cond_info conds[]= - { - { &key_COND_thread_cache, "COND_thread_cache", PSI_FLAG_GLOBAL }, - { &key_COND_flush_thread_cache, "COND_flush_thread_cache", - PSI_FLAG_GLOBAL } - }; - PSI_mutex_info mutexes[]= - { - { &key_LOCK_thread_cache, "LOCK_thread_cache", PSI_FLAG_GLOBAL } - }; - mysql_mutex_register("sql", mutexes, array_elements(mutexes)); - mysql_cond_register("sql", conds, array_elements(conds)); -#endif - mysql_mutex_init(key_LOCK_thread_cache, &LOCK_thread_cache, - MY_MUTEX_INIT_FAST); - mysql_cond_init(key_COND_thread_cache, &COND_thread_cache, 0); - mysql_cond_init(key_COND_flush_thread_cache, &COND_flush_thread_cache, 0); - list.empty(); - kill_cached_threads= 0; - cached_thread_count= 0; - } - - - void destroy() - { - DBUG_ASSERT(cached_thread_count == 0); - DBUG_ASSERT(list.is_empty()); - mysql_cond_destroy(&COND_flush_thread_cache); - mysql_cond_destroy(&COND_thread_cache); - mysql_mutex_destroy(&LOCK_thread_cache); - } - - - /** - Flushes thread cache. - - Awakes parked threads and requests them to shutdown. - Waits until last parked thread leaves the cache. - */ - void flush() - { - mysql_mutex_lock(&LOCK_thread_cache); - kill_cached_threads++; - while (cached_thread_count) - { - mysql_cond_broadcast(&COND_thread_cache); - mysql_cond_wait(&COND_flush_thread_cache, &LOCK_thread_cache); - } - kill_cached_threads--; - mysql_mutex_unlock(&LOCK_thread_cache); - } - - - /** - Flushes thread cache and forbids threads parking in the cache. - - This is a pre-shutdown hook. - */ - void final_flush() - { - kill_cached_threads++; - flush(); - } - - - /** - Requests parked thread to serve new connection. - - @return - @retval true connection is enqueued and parked thread is about to serve it - @retval false thread cache is empty - */ - bool enqueue(CONNECT *connect) - { - mysql_mutex_lock(&LOCK_thread_cache); - if (cached_thread_count) - { - list.push_back(connect); - cached_thread_count--; - mysql_mutex_unlock(&LOCK_thread_cache); - mysql_cond_signal(&COND_thread_cache); - return true; - } - mysql_mutex_unlock(&LOCK_thread_cache); - return false; - } - - - /** - Parks thread in the cache. - - Thread execution is suspended until either of the following occurs: - - thread is requested to serve new connection; - - thread cache is flushed; - - THREAD_CACHE_TIMEOUT elapsed. - - @return - @retval pointer to CONNECT if requested to serve new connection - @retval 0 if thread cache is flushed or on timeout - */ - CONNECT *park() - { - struct timespec abstime; - CONNECT *connect; - bool flushed= false; - DBUG_ENTER("Thread_cache::park"); - set_timespec(abstime, THREAD_CACHE_TIMEOUT); - - /* - Delete the instrumentation for the job that just completed, - before parking this pthread in the cache (blocked on COND_thread_cache). - */ - PSI_CALL_delete_current_thread(); - -#ifndef DBUG_OFF - while (_db_is_pushed_()) - _db_pop_(); -#endif - - mysql_mutex_lock(&LOCK_thread_cache); - if ((connect= list.get())) - cached_thread_count++; - else if (cached_thread_count < thread_cache_size && !kill_cached_threads) - { - /* Don't kill the thread, just put it in cache for reuse */ - DBUG_PRINT("info", ("Adding thread to cache")); - cached_thread_count++; - for (;;) - { - int error= mysql_cond_timedwait(&COND_thread_cache, &LOCK_thread_cache, - &abstime); - flushed= kill_cached_threads; - if ((connect= list.get())) - break; - else if (flushed || error == ETIMEDOUT || error == ETIME) - { - /* - If timeout, end thread. - If a new thread is requested, we will handle the call, even if we - got a timeout (as we are already awake and free) - */ - cached_thread_count--; - break; - } - } - } - mysql_mutex_unlock(&LOCK_thread_cache); - if (flushed) - mysql_cond_signal(&COND_flush_thread_cache); - DBUG_RETURN(connect); - } - - - /** Returns the number of parked threads. */ - ulong size() const - { - mysql_mutex_lock(&LOCK_thread_cache); - ulong r= cached_thread_count; - mysql_mutex_unlock(&LOCK_thread_cache); - return r; - } -}; - -extern Thread_cache thread_cache; diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thread_pool_priv.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/thread_pool_priv.h deleted file mode 100644 index 769c4a7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/thread_pool_priv.h +++ /dev/null @@ -1,109 +0,0 @@ -#error don't use -/* - Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA -*/ - -#ifndef THREAD_POOL_PRIV_INCLUDED -#define THREAD_POOL_PRIV_INCLUDED - -/* - The thread pool requires access to some MySQL server error codes, this is - accessed from mysqld_error.h. - We need access to the struct that defines the thread pool plugin interface - which is accessed through scheduler.h. - All accesses to THD variables and functions are defined in this header file. - A thread pool can also use DEBUG_SYNC and must thus include - debug_sync.h - To handle definitions of Information Schema plugins it is also required - to include sql_profile.h and table.h. -*/ -#include /* To get ER_ERROR_ON_READ */ -#define MYSQL_SERVER 1 -#include -#include -#include -#include -#include - -/* Interface to THD variables and functions */ -void thd_set_killed(THD *thd); -void thd_clear_errors(THD *thd); -void thd_set_thread_stack(THD *thd, char *stack_start); -void thd_lock_thread_count(THD *thd); -void thd_close_connection(THD *thd); -THD *thd_get_current_thd(); -void thd_lock_data(THD *thd); -void thd_unlock_data(THD *thd); -bool thd_is_transaction_active(THD *thd); -int thd_connection_has_data(THD *thd); -void thd_set_net_read_write(THD *thd, uint val); -uint thd_get_net_read_write(THD *thd); -void thd_set_mysys_var(THD *thd, st_my_thread_var *mysys_var); -my_socket thd_get_fd(THD *thd); -int thd_store_globals(THD* thd); - -/* Print to the MySQL error log */ -void sql_print_error(const char *format, ...); - -/* Store a table record */ -bool schema_table_store_record(THD *thd, TABLE *table); - -/* - The thread pool must be able to execute statements using the connection - state in THD object. This is the main objective of the thread pool to - schedule the start of these commands. -*/ -bool do_command(THD *thd); - -/* - The thread pool requires an interface to the connection logic in the - MySQL Server since the thread pool will maintain the event logic on - the TCP connection of the MySQL Server. Thus new connections, dropped - connections will be discovered by the thread pool and it needs to - ensure that the proper MySQL Server logic attached to these events is - executed. -*/ -/* Set up connection thread before use as execution thread */ -bool setup_connection_thread_globals(THD *thd); -/* Prepare connection as part of connection set-up */ -bool thd_prepare_connection(THD *thd); -/* Release auditing before executing statement */ -void mysql_audit_release(THD *thd); -/* Check if connection is still alive */ -bool thd_is_connection_alive(THD *thd); -/* Close connection with possible error code */ -void close_connection(THD *thd, uint errcode); -/* Destroy THD object */ -void delete_thd(THD *thd); - -/* - thread_created is maintained by thread pool when activated since - user threads are created by the thread pool (and also special - threads to maintain the thread pool). This is done through - inc_thread_created. - - max_connections is needed to calculate the maximum number of threads - that is allowed to be started by the thread pool. The method - get_max_connections() gets reference to this variable. - - connection_attrib is the thread attributes for connection threads, - the method get_connection_attrib provides a reference to these - attributes. -*/ -void inc_thread_created(void); -ulong get_max_connections(void); -pthread_attr_t *get_connection_attrib(void); -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/threadpool.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/threadpool.h deleted file mode 100644 index 27da872..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/threadpool.h +++ /dev/null @@ -1,161 +0,0 @@ -/* Copyright (C) 2012, 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#pragma once -#ifdef HAVE_POOL_OF_THREADS -#define MAX_THREAD_GROUPS 100000 - -/* Threadpool parameters */ -extern uint threadpool_min_threads; /* Minimum threads in pool */ -extern uint threadpool_idle_timeout; /* Shutdown idle worker threads after this timeout */ -extern uint threadpool_size; /* Number of parallel executing threads */ -extern uint threadpool_max_size; -extern uint threadpool_stall_limit; /* time interval in milliseconds for stall checks*/ -extern uint threadpool_max_threads; /* Maximum threads in pool */ -extern uint threadpool_oversubscribe; /* Maximum active threads in group */ -extern uint threadpool_prio_kickup_timer; /* Time before low prio item gets prio boost */ -extern my_bool threadpool_exact_stats; /* Better queueing time stats for information_schema, at small performance cost */ -extern my_bool threadpool_dedicated_listener; /* Listener thread does not pick up work items. */ -#ifdef _WIN32 -extern uint threadpool_mode; /* Thread pool implementation , windows or generic */ -#define TP_MODE_WINDOWS 0 -#define TP_MODE_GENERIC 1 -#endif - -#define DEFAULT_THREADPOOL_STALL_LIMIT 500U - -struct TP_connection; -extern void tp_callback(TP_connection *c); -extern void tp_timeout_handler(TP_connection *c); - - - -/* - Threadpool statistics -*/ -struct TP_STATISTICS -{ - /* Current number of worker thread. */ - Atomic_counter num_worker_threads; -}; - -extern TP_STATISTICS tp_stats; - - -/* Functions to set threadpool parameters */ -extern void tp_set_min_threads(uint val); -extern void tp_set_max_threads(uint val); -extern void tp_set_threadpool_size(uint val); -extern void tp_set_threadpool_stall_limit(uint val); -extern int tp_get_idle_thread_count(); -extern int tp_get_thread_count(); - - -enum TP_PRIORITY { - TP_PRIORITY_HIGH, - TP_PRIORITY_LOW, - TP_PRIORITY_AUTO -}; - - -enum TP_STATE -{ - TP_STATE_IDLE, - TP_STATE_RUNNING, - TP_STATE_PENDING -}; - -/* - Connection structure, encapsulates THD + structures for asynchronous - IO and pool. - - Platform specific parts are specified in subclasses called connection_t, - inside threadpool_win.cc and threadpool_unix.cc -*/ - -class CONNECT; - -struct TP_connection -{ - THD* thd; - CONNECT* connect; - TP_STATE state; - TP_PRIORITY priority; - TP_connection(CONNECT *c) : - thd(0), - connect(c), - state(TP_STATE_IDLE), - priority(TP_PRIORITY_HIGH) - {} - - virtual ~TP_connection() - {}; - - /* Initialize io structures windows threadpool, epoll etc */ - virtual int init() = 0; - - virtual void set_io_timeout(int sec) = 0; - - /* Read for the next client command (async) with specified timeout */ - virtual int start_io() = 0; - - virtual void wait_begin(int type)= 0; - virtual void wait_end() = 0; - -}; - - -struct TP_pool -{ - virtual ~TP_pool(){}; - virtual int init()= 0; - virtual TP_connection *new_connection(CONNECT *)= 0; - virtual void add(TP_connection *c)= 0; - virtual int set_max_threads(uint){ return 0; } - virtual int set_min_threads(uint){ return 0; } - virtual int set_pool_size(uint){ return 0; } - virtual int set_idle_timeout(uint){ return 0; } - virtual int set_oversubscribe(uint){ return 0; } - virtual int set_stall_limit(uint){ return 0; } - virtual int get_thread_count() { return tp_stats.num_worker_threads; } - virtual int get_idle_thread_count(){ return 0; } -}; - -#ifdef _WIN32 -struct TP_pool_win:TP_pool -{ - TP_pool_win(); - virtual int init(); - virtual ~TP_pool_win(); - virtual TP_connection *new_connection(CONNECT *c); - virtual void add(TP_connection *); - virtual int set_max_threads(uint); - virtual int set_min_threads(uint); -}; -#endif - -struct TP_pool_generic :TP_pool -{ - TP_pool_generic(); - ~TP_pool_generic(); - virtual int init(); - virtual TP_connection *new_connection(CONNECT *c); - virtual void add(TP_connection *); - virtual int set_pool_size(uint); - virtual int set_stall_limit(uint); - virtual int get_idle_thread_count(); -}; - -#endif /* HAVE_POOL_OF_THREADS */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/threadpool_generic.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/threadpool_generic.h deleted file mode 100644 index acf5ec6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/threadpool_generic.h +++ /dev/null @@ -1,156 +0,0 @@ -/* Copyright(C) 2019, 2020, MariaDB - * - * This program is free software; you can redistribute itand /or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111 - 1301 USA*/ - -#if defined (HAVE_POOL_OF_THREADS) -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -/* AIX may define this, too ?*/ -#define HAVE_IOCP -#endif - - -#ifdef _WIN32 -typedef HANDLE TP_file_handle; -#else -typedef int TP_file_handle; -#define INVALID_HANDLE_VALUE -1 -#endif - -#ifdef __linux__ -#include -typedef struct epoll_event native_event; -#elif defined(HAVE_KQUEUE) -#include -typedef struct kevent native_event; -#elif defined (__sun) -#include -typedef port_event_t native_event; -#elif defined (HAVE_IOCP) -typedef OVERLAPPED_ENTRY native_event; -#else -#error threadpool is not available on this platform -#endif - -struct thread_group_t; - -/* Per-thread structure for workers */ -struct worker_thread_t -{ - ulonglong event_count; /* number of request handled by this thread */ - thread_group_t* thread_group; - worker_thread_t* next_in_list; - worker_thread_t** prev_in_list; - mysql_cond_t cond; - bool woken; -}; - -typedef I_P_List, - I_P_List_counter -> -worker_list_t; - -struct TP_connection_generic :public TP_connection -{ - TP_connection_generic(CONNECT* c); - ~TP_connection_generic(); - - virtual int init() { return 0; }; - virtual void set_io_timeout(int sec); - virtual int start_io(); - virtual void wait_begin(int type); - virtual void wait_end(); - - thread_group_t* thread_group; - TP_connection_generic* next_in_queue; - TP_connection_generic** prev_in_queue; - ulonglong abs_wait_timeout; - ulonglong enqueue_time; - TP_file_handle fd; - bool bound_to_poll_descriptor; - int waiting; - bool fix_group; -#ifdef HAVE_IOCP - OVERLAPPED overlapped; -#endif -#ifdef _WIN32 - enum_vio_type vio_type; -#endif -}; - - -typedef I_P_List, - I_P_List_counter, - I_P_List_fast_push_back > - connection_queue_t; - -const int NQUEUES = 2; /* We have high and low priority queues*/ - -enum class operation_origin -{ - WORKER, - LISTENER -}; - -struct thread_group_counters_t -{ - ulonglong thread_creations; - ulonglong thread_creations_due_to_stall; - ulonglong wakes; - ulonglong wakes_due_to_stall; - ulonglong throttles; - ulonglong stalls; - ulonglong dequeues[2]; - ulonglong polls[2]; -}; - -struct thread_group_t -{ - mysql_mutex_t mutex; - connection_queue_t queues[NQUEUES]; - worker_list_t waiting_threads; - worker_thread_t* listener; - pthread_attr_t* pthread_attr; - TP_file_handle pollfd; - int thread_count; - int active_thread_count; - int connection_count; - /* Stats for the deadlock detection timer routine.*/ - int io_event_count; - int queue_event_count; - ulonglong last_thread_creation_time; - int shutdown_pipe[2]; - bool shutdown; - bool stalled; - thread_group_counters_t counters; - char pad[CPU_LEVEL1_DCACHE_LINESIZE]; -}; - -#define TP_INCREMENT_GROUP_COUNTER(group,var) do {group->counters.var++;}while(0) - -extern thread_group_t* all_groups; -#endif - diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/transaction.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/transaction.h deleted file mode 100644 index fe0129f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/transaction.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef TRANSACTION_H -#define TRANSACTION_H - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class implementation */ -#endif - -#include - -class THD; - -void trans_track_end_trx(THD *thd); - -bool trans_begin(THD *thd, uint flags= 0); -bool trans_commit(THD *thd); -bool trans_commit_implicit(THD *thd); -bool trans_rollback(THD *thd); -bool trans_rollback_implicit(THD *thd); - -bool trans_commit_stmt(THD *thd); -bool trans_rollback_stmt(THD *thd); - -bool trans_savepoint(THD *thd, LEX_CSTRING name); -bool trans_rollback_to_savepoint(THD *thd, LEX_CSTRING name); -bool trans_release_savepoint(THD *thd, LEX_CSTRING name); - -void trans_reset_one_shot_chistics(THD *thd); - -#endif /* TRANSACTION_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/tzfile.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/tzfile.h deleted file mode 100644 index aa03086..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/tzfile.h +++ /dev/null @@ -1,142 +0,0 @@ -#ifndef TZFILE_INCLUDED -#define TZFILE_INCLUDED - -/* Copyright (c) 2004, 2006, 2007 MySQL AB, 2009 Sun Microsystems, Inc. - Use is subject to license terms. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - This file is based on public domain code from ftp://elsie.ncih.nist.gov/ - Initial source code is in the public domain, so clarified as of - 1996-06-05 by Arthur David Olson (arthur_david_olson@nih.gov). -*/ - -/* - Information about time zone files. -*/ - -#ifndef TZDIR -#define TZDIR "/usr/share/zoneinfo" /* Time zone object file directory */ -#endif /* !defined TZDIR */ - -/* - Each file begins with. . . -*/ - -#define TZ_MAGIC "TZif" - -struct tzhead { - uchar tzh_magic[4]; /* TZ_MAGIC */ - uchar tzh_reserved[16]; /* reserved for future use */ - uchar tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */ - uchar tzh_ttisstdcnt[4]; /* coded number of trans. time flags */ - uchar tzh_leapcnt[4]; /* coded number of leap seconds */ - uchar tzh_timecnt[4]; /* coded number of transition times */ - uchar tzh_typecnt[4]; /* coded number of local time types */ - uchar tzh_charcnt[4]; /* coded number of abbr. chars */ -}; - -/* - . . .followed by. . . - - tzh_timecnt (char [4])s coded transition times a la time(2) - tzh_timecnt (unsigned char)s types of local time starting at above - tzh_typecnt repetitions of - one (char [4]) coded UTC offset in seconds - one (unsigned char) used to set tm_isdst - one (unsigned char) that's an abbreviation list index - tzh_charcnt (char)s '\0'-terminated zone abbreviations - tzh_leapcnt repetitions of - one (char [4]) coded leap second transition times - one (char [4]) total correction after above - tzh_ttisstdcnt (char)s indexed by type; if TRUE, transition - time is standard time, if FALSE, - transition time is wall clock time - if absent, transition times are - assumed to be wall clock time - tzh_ttisgmtcnt (char)s indexed by type; if TRUE, transition - time is UTC, if FALSE, - transition time is local time - if absent, transition times are - assumed to be local time -*/ - -/* - In the current implementation, we refuse to deal with files that - exceed any of the limits below. -*/ - -#ifndef TZ_MAX_TIMES -/* - The TZ_MAX_TIMES value below is enough to handle a bit more than a - year's worth of solar time (corrected daily to the nearest second) or - 138 years of Pacific Presidential Election time - (where there are three time zone transitions every fourth year). -*/ -#define TZ_MAX_TIMES 370 -#endif /* !defined TZ_MAX_TIMES */ - -#ifndef TZ_MAX_TYPES -#ifdef SOLAR -#define TZ_MAX_TYPES 256 /* Limited by what (unsigned char)'s can hold */ -#else -/* - Must be at least 14 for Europe/Riga as of Jan 12 1995, - as noted by Earl Chew . -*/ -#define TZ_MAX_TYPES 20 /* Maximum number of local time types */ -#endif /* defined SOLAR */ -#endif /* !defined TZ_MAX_TYPES */ - -#ifndef TZ_MAX_CHARS -#define TZ_MAX_CHARS 50 /* Maximum number of abbreviation characters */ - /* (limited by what unsigned chars can hold) */ -#endif /* !defined TZ_MAX_CHARS */ - -#ifndef TZ_MAX_LEAPS -#define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */ -#endif /* !defined TZ_MAX_LEAPS */ - -#ifndef TZ_MAX_REV_RANGES -#ifdef SOLAR -/* Solar (Asia/RiyadhXX) zones need significantly bigger TZ_MAX_REV_RANGES */ -#define TZ_MAX_REV_RANGES (TZ_MAX_TIMES*2+TZ_MAX_LEAPS*2+2) -#else -#define TZ_MAX_REV_RANGES (TZ_MAX_TIMES+TZ_MAX_LEAPS+2) -#endif -#endif - -#define SECS_PER_MIN 60 -#define MINS_PER_HOUR 60 -#define HOURS_PER_DAY 24 -#define DAYS_PER_WEEK 7 -#define DAYS_PER_NYEAR 365 -#define DAYS_PER_LYEAR 366 -#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR) -#define SECS_PER_DAY ((long) SECS_PER_HOUR * HOURS_PER_DAY) -#define MONS_PER_YEAR 12 - -#define TM_YEAR_BASE 1900 - -#define EPOCH_YEAR 1970 - -/* - Accurate only for the past couple of centuries, - that will probably do. -*/ - -#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/tztime.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/tztime.h deleted file mode 100644 index 9e5d469..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/tztime.h +++ /dev/null @@ -1,93 +0,0 @@ -#ifndef TZTIME_INCLUDED -#define TZTIME_INCLUDED - -/* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifdef USE_PRAGMA_INTERFACE -#pragma interface /* gcc class interface */ -#endif - -#include "my_time.h" /* my_time_t */ -#include "mysql_time.h" /* MYSQL_TIME */ -#include "sql_list.h" /* Sql_alloc */ -#include "sql_string.h" /* String */ - -class THD; - -#if !defined(TESTTIME) && !defined(TZINFO2SQL) - -class THD; - -/** - This class represents abstract time zone and provides - basic interface for MYSQL_TIME <-> my_time_t conversion. - Actual time zones which are specified by DB, or via offset - or use system functions are its descendants. -*/ -class Time_zone: public Sql_alloc -{ -public: - Time_zone() {} /* Remove gcc warning */ - /** - Converts local time in broken down MYSQL_TIME representation to - my_time_t (UTC seconds since Epoch) represenation. - Returns 0 in case of error. May set error_code to ER_WARN_DATA_OUT_OF_RANGE - or ER_WARN_INVALID_TIMESTAMP, see TIME_to_timestamp()) - */ - virtual my_time_t TIME_to_gmt_sec(const MYSQL_TIME *t, - uint *error_code) const = 0; - /** - Converts time in my_time_t representation to local time in - broken down MYSQL_TIME representation. - */ - virtual void gmt_sec_to_TIME(MYSQL_TIME *tmp, my_time_t t) const = 0; - /** - Because of constness of String returned by get_name() time zone name - have to be already zeroended to be able to use String::ptr() instead - of c_ptr(). - */ - virtual const String * get_name() const = 0; - - /** - We need this only for surpressing warnings, objects of this type are - allocated on MEM_ROOT and should not require destruction. - */ - virtual ~Time_zone() {}; - -protected: - static inline void adjust_leap_second(MYSQL_TIME *t); -}; - -extern Time_zone * my_tz_UTC; -extern MYSQL_PLUGIN_IMPORT Time_zone * my_tz_SYSTEM; -extern Time_zone * my_tz_OFFSET0; -extern Time_zone * my_tz_find(THD *thd, const String *name); -extern my_bool my_tz_init(THD *org_thd, const char *default_tzname, my_bool bootstrap); -extern void my_tz_free(); -extern my_time_t sec_since_epoch_TIME(MYSQL_TIME *t); - -/** - Number of elements in table list produced by my_tz_get_table_list() - (this table list contains tables which are needed for dynamical loading - of time zone descriptions). Actually it is imlementation detail that - should not be used anywhere outside of tztime.h and tztime.cc. -*/ - -static const int MY_TZ_TABLES_COUNT= 4; - -#endif /* !defined(TESTTIME) && !defined(TZINFO2SQL) */ -#endif /* TZTIME_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/uniques.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/uniques.h deleted file mode 100644 index 7e12a39..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/uniques.h +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (c) 2016 MariaDB corporation - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef UNIQUE_INCLUDED -#define UNIQUE_INCLUDED - -#include "filesort.h" - -/* - Unique -- class for unique (removing of duplicates). - Puts all values to the TREE. If the tree becomes too big, - it's dumped to the file. User can request sorted values, or - just iterate through them. In the last case tree merging is performed in - memory simultaneously with iteration, so it should be ~2-3x faster. - */ - -class Unique :public Sql_alloc -{ - DYNAMIC_ARRAY file_ptrs; - ulong max_elements; /* Total number of elements that will be stored in-memory */ - size_t max_in_memory_size; - IO_CACHE file; - TREE tree; - /* Number of elements filtered out due to min_dupl_count when storing results - to table. See Unique::get */ - ulong filtered_out_elems; - uint size; - - uint full_size; /* Size of element + space needed to store the number of - duplicates found for the element. */ - uint min_dupl_count; /* Minimum number of occurences of element required for - it to be written to record_pointers. - always 0 for unions, > 0 for intersections */ - bool with_counters; - - bool merge(TABLE *table, uchar *buff, size_t size, bool without_last_merge); - bool flush(); - -public: - ulong elements; - SORT_INFO sort; - Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg, - uint size_arg, size_t max_in_memory_size_arg, - uint min_dupl_count_arg= 0); - ~Unique(); - ulong elements_in_tree() { return tree.elements_in_tree; } - inline bool unique_add(void *ptr) - { - DBUG_ENTER("unique_add"); - DBUG_PRINT("info", ("tree %u - %lu", tree.elements_in_tree, max_elements)); - if (!(tree.flag & TREE_ONLY_DUPS) && - tree.elements_in_tree >= max_elements && flush()) - DBUG_RETURN(1); - DBUG_RETURN(!tree_insert(&tree, ptr, 0, tree.custom_arg)); - } - - bool is_in_memory() { return (my_b_tell(&file) == 0); } - void close_for_expansion() { tree.flag= TREE_ONLY_DUPS; } - - bool get(TABLE *table); - - /* Cost of searching for an element in the tree */ - inline static double get_search_cost(ulonglong tree_elems, - double compare_factor) - { - return log((double) tree_elems) / (compare_factor * M_LN2); - } - - static double get_use_cost(uint *buffer, size_t nkeys, uint key_size, - size_t max_in_memory_size, double compare_factor, - bool intersect_fl, bool *in_memory); - inline static int get_cost_calc_buff_size(size_t nkeys, uint key_size, - size_t max_in_memory_size) - { - size_t max_elems_in_tree= - max_in_memory_size / ALIGN_SIZE(sizeof(TREE_ELEMENT)+key_size); - - if (max_elems_in_tree == 0) - max_elems_in_tree= 1; - return (int) (sizeof(uint)*(1 + nkeys/max_elems_in_tree)); - } - - void reset(); - bool walk(TABLE *table, tree_walk_action action, void *walk_action_arg); - - uint get_size() const { return size; } - size_t get_max_in_memory_size() const { return max_in_memory_size; } - - friend int unique_write_to_file(uchar* key, element_count count, Unique *unique); - friend int unique_write_to_ptrs(uchar* key, element_count count, Unique *unique); - - friend int unique_write_to_file_with_count(uchar* key, element_count count, - Unique *unique); - friend int unique_intersect_write_to_ptrs(uchar* key, element_count count, - Unique *unique); -}; - -#endif /* UNIQUE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/unireg.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/unireg.h deleted file mode 100644 index 873d6f6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/unireg.h +++ /dev/null @@ -1,205 +0,0 @@ -#ifndef UNIREG_INCLUDED -#define UNIREG_INCLUDED - -/* - Copyright (c) 2000, 2011, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#include /* FRM_VER */ - -/* Extra functions used by unireg library */ - -#ifndef NO_ALARM_LOOP -#define NO_ALARM_LOOP /* lib5 and popen can't use alarm */ -#endif - -/* These paths are converted to other systems (WIN95) before use */ - -#define LANGUAGE "english/" -#define ERRMSG_FILE "errmsg.sys" -#define TEMP_PREFIX "MY" -#define LOG_PREFIX "ML" -#define PROGDIR "bin/" -#ifndef MYSQL_DATADIR -#define MYSQL_DATADIR "data/" -#endif -#ifndef SHAREDIR -#define SHAREDIR "share/" -#endif -#ifndef PLUGINDIR -#define PLUGINDIR "lib/plugin" -#endif - -#define MAX_ERROR_RANGES 4 /* 1000-2000, 2000-3000, 3000-4000, 4000-5000 */ -#define ERRORS_PER_RANGE 1000 - -#define DEFAULT_ERRMSGS my_default_lc_messages->errmsgs->errmsgs -#define CURRENT_THD_ERRMSGS (current_thd)->variables.errmsgs - -#ifndef mysqld_error_find_printf_error_used -#define ER_DEFAULT(X) DEFAULT_ERRMSGS[((X)-ER_ERROR_FIRST) / ERRORS_PER_RANGE][(X)% ERRORS_PER_RANGE] -#define ER_THD(thd,X) ((thd)->variables.errmsgs[((X)-ER_ERROR_FIRST) / ERRORS_PER_RANGE][(X) % ERRORS_PER_RANGE]) -#define ER(X) ER_THD(current_thd, (X)) -#endif -#define ER_THD_OR_DEFAULT(thd,X) ((thd) ? ER_THD(thd, (X)) : ER_DEFAULT(X)) - -#define SPECIAL_USE_LOCKS 1 /* Lock used databases */ -#define SPECIAL_NO_NEW_FUNC 2 /* Skip new functions */ -#define SPECIAL_SKIP_SHOW_DB 4 /* Don't allow 'show db' */ -#define SPECIAL_WAIT_IF_LOCKED 8 /* Wait if locked database */ -#define SPECIAL_SAME_DB_NAME 16 /* form name = file name */ -#define SPECIAL_ENGLISH 32 /* English error messages */ -#define SPECIAL_NO_RESOLVE 64 /* Don't use gethostname */ -#define SPECIAL_NO_PRIOR 128 /* Obsolete */ -#define SPECIAL_BIG_SELECTS 256 /* Don't use heap tables */ -#define SPECIAL_NO_HOST_CACHE 512 /* Don't cache hosts */ -#define SPECIAL_SHORT_LOG_FORMAT 1024 -#define SPECIAL_SAFE_MODE 2048 -#define SPECIAL_LOG_QUERIES_NOT_USING_INDEXES 4096 /* Obsolete */ - - /* Extern defines */ -#define store_record(A,B) memcpy((A)->B,(A)->record[0],(size_t) (A)->s->reclength) -#define restore_record(A,B) memcpy((A)->record[0],(A)->B,(size_t) (A)->s->reclength) -#define cmp_record(A,B) memcmp((A)->record[0],(A)->B,(size_t) (A)->s->reclength) -#define empty_record(A) { \ - restore_record((A),s->default_values); \ - bfill((A)->null_flags,(A)->s->null_bytes,255);\ - } - - /* Defines for use with openfrm, openprt and openfrd */ - -#define READ_ALL (1 << 0) /* openfrm: Read all parameters */ -#define EXTRA_RECORD (1 << 3) /* Reserve space for an extra record */ -#define DELAYED_OPEN (1 << 12) /* Open table later */ -#define OPEN_VIEW_NO_PARSE (1 << 14) /* Open frm only if it's a view, - but do not parse view itself */ -/** - This flag is used in function get_all_tables() which fills - I_S tables with data which are retrieved from frm files and storage engine - The flag means that we need to open FRM file only to get necessary data. -*/ -#define OPEN_FRM_FILE_ONLY (1 << 15) -/** - This flag is used in function get_all_tables() which fills - I_S tables with data which are retrieved from frm files and storage engine - The flag means that we need to process tables only to get necessary data. - Views are not processed. -*/ -#define OPEN_TABLE_ONLY (1 << 16) -/** - This flag is used in function get_all_tables() which fills - I_S tables with data which are retrieved from frm files and storage engine - The flag means that we need to process views only to get necessary data. - Tables are not processed. -*/ -#define OPEN_VIEW_ONLY (1 << 17) -/** - This flag is used in function get_all_tables() which fills - I_S tables with data which are retrieved from frm files and storage engine. - The flag means that we need to open a view using - open_normal_and_derived_tables() function. -*/ -#define OPEN_VIEW_FULL (1 << 18) -/** - This flag is used in function get_all_tables() which fills - I_S tables with data which are retrieved from frm files and storage engine. - The flag means that I_S table uses optimization algorithm. -*/ -#define OPTIMIZE_I_S_TABLE (1 << 19) -/** - This flag is used to instruct tdc_open_view() to check metadata version. -*/ -#define CHECK_METADATA_VERSION (1 << 20) - -/* - The flag means that we need to process trigger files only. -*/ -#define OPEN_TRIGGER_ONLY (1 << 21) - -/* - Minimum length pattern before Turbo Boyer-Moore is used - for SELECT "text" LIKE "%pattern%", excluding the two - wildcards in class Item_func_like. -*/ -#define MIN_TURBOBM_PATTERN_LEN 3 - -/* - Defines for binary logging. - Do not decrease the value of BIN_LOG_HEADER_SIZE. - Do not even increase it before checking code. -*/ - -#define BIN_LOG_HEADER_SIZE 4 - -#define DEFAULT_KEY_CACHE_NAME "default" - - -/* Include prototypes for unireg */ - -#include "mysqld_error.h" -#include "structs.h" /* All structs we need */ -#include "sql_list.h" /* List<> */ -#include "field.h" /* Create_field */ - -/* - Types of values in the MariaDB extra2 frm segment. - Each value is written as - type: 1 byte - length: 1 byte (1..255) or \0 and 2 bytes. - binary value of the 'length' bytes. - - Older MariaDB servers can ignore values of unknown types if - the type code is less than 128 (EXTRA2_ENGINE_IMPORTANT). - Otherwise older (but newer than 10.0.1) servers are required - to report an error. -*/ -enum extra2_frm_value_type { - EXTRA2_TABLEDEF_VERSION=0, - EXTRA2_DEFAULT_PART_ENGINE=1, - EXTRA2_GIS=2, - EXTRA2_APPLICATION_TIME_PERIOD=3, - EXTRA2_PERIOD_FOR_SYSTEM_TIME=4, - -#define EXTRA2_ENGINE_IMPORTANT 128 - - EXTRA2_ENGINE_TABLEOPTS=128, - EXTRA2_FIELD_FLAGS=129, - EXTRA2_FIELD_DATA_TYPE_INFO=130, - EXTRA2_PERIOD_WITHOUT_OVERLAPS=131, -}; - -enum extra2_field_flags { - VERS_OPTIMIZED_UPDATE= 1 << INVISIBLE_MAX_BITS, -}; - -LEX_CUSTRING build_frm_image(THD *thd, const LEX_CSTRING &table, - HA_CREATE_INFO *create_info, - List &create_fields, - uint keys, KEY *key_info, handler *db_file); - -#define FRM_HEADER_SIZE 64 -#define FRM_FORMINFO_SIZE 288 -#define FRM_MAX_SIZE (1024*1024) - -static inline bool is_binary_frm_header(uchar *head) -{ - return head[0] == 254 - && head[1] == 1 - && head[2] >= FRM_VER - && head[2] <= FRM_VER_CURRENT; -} - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/vers_string.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/vers_string.h deleted file mode 100644 index 4e173f8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/vers_string.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright (c) 2018, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef VERS_STRING_INCLUDED -#define VERS_STRING_INCLUDED - -#include "lex_string.h" - -/* - LEX_CSTRING with comparison semantics. -*/ - -// db and table names: case sensitive (or insensitive) in table_alias_charset -struct Compare_table_names -{ - int operator()(const LEX_CSTRING& a, const LEX_CSTRING& b) const - { - DBUG_ASSERT(a.str[a.length] == 0); - DBUG_ASSERT(b.str[b.length] == 0); - return table_alias_charset->strnncoll(a.str, a.length, - b.str, b.length); - } -}; - -// column names and other identifiers: case insensitive in system_charset_info -struct Compare_identifiers -{ - int operator()(const LEX_CSTRING& a, const LEX_CSTRING& b) const - { - DBUG_ASSERT(a.str[a.length] == 0); - DBUG_ASSERT(b.str[b.length] == 0); - return my_strcasecmp(system_charset_info, a.str, b.str); - } -}; - - -template -struct Lex_cstring_with_compare : public Lex_cstring -{ -public: - Lex_cstring_with_compare() {} - Lex_cstring_with_compare(const char *_str, size_t _len) : - Lex_cstring(_str, _len) - { } - Lex_cstring_with_compare(const LEX_STRING src) : - Lex_cstring(src.str, src.length) - { } - Lex_cstring_with_compare(const LEX_CSTRING src) : Lex_cstring(src.str, src.length) - { } - Lex_cstring_with_compare(const char *_str) : Lex_cstring(_str, strlen(_str)) - { } - bool streq(const Lex_cstring_with_compare& b) const - { - return Lex_cstring::length == b.length && 0 == Compare()(*this, b); - } - operator const char* () const - { - return str; - } - operator bool () const - { - return str != NULL; - } -}; - -typedef Lex_cstring_with_compare Lex_ident; -typedef Lex_cstring_with_compare Lex_table_name; - -#endif // VERS_STRING_INCLUDED diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/violite.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/violite.h deleted file mode 100644 index 28e3ca0..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/violite.h +++ /dev/null @@ -1,284 +0,0 @@ -/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. - Copyright (c) 2012, 2020, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - * Vio Lite. - * Purpose: include file for Vio that will work with C and C++ - */ - -#ifndef vio_violite_h_ -#define vio_violite_h_ - -#include "my_net.h" /* needed because of struct in_addr */ -#include - -/* Simple vio interface in C; The functions are implemented in violite.c */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifdef __cplusplus -typedef struct st_vio Vio; -#endif /* __cplusplus */ - -enum enum_vio_type -{ - VIO_CLOSED, VIO_TYPE_TCPIP, VIO_TYPE_SOCKET, VIO_TYPE_NAMEDPIPE, - VIO_TYPE_SSL - /* see also vio_type_names[] */ -}; -#define FIRST_VIO_TYPE VIO_CLOSED -#define LAST_VIO_TYPE VIO_TYPE_SSL - -/** - VIO I/O events. -*/ -enum enum_vio_io_event -{ - VIO_IO_EVENT_READ, - VIO_IO_EVENT_WRITE, - VIO_IO_EVENT_CONNECT -}; - -struct vio_keepalive_opts -{ - int interval; - int idle; - int probes; -}; - - -#define VIO_TLSv1_0 1 -#define VIO_TLSv1_1 2 -#define VIO_TLSv1_2 4 -#define VIO_TLSv1_3 8 - -#define VIO_LOCALHOST 1U /* a localhost connection */ -#define VIO_BUFFERED_READ 2U /* use buffered read */ -#define VIO_READ_BUFFER_SIZE 16384U /* size of read buffer */ -#define VIO_DESCRIPTION_SIZE 30 /* size of description */ - -Vio* vio_new(my_socket sd, enum enum_vio_type type, uint flags); -Vio* mysql_socket_vio_new(MYSQL_SOCKET mysql_socket, enum enum_vio_type type, uint flags); -#ifdef __WIN__ -Vio* vio_new_win32pipe(HANDLE hPipe); -#else -#define HANDLE void * -#endif /* __WIN__ */ - -void vio_delete(Vio* vio); -int vio_close(Vio* vio); -my_bool vio_reset(Vio* vio, enum enum_vio_type type, - my_socket sd, void *ssl, uint flags); -size_t vio_read(Vio *vio, uchar * buf, size_t size); -size_t vio_read_buff(Vio *vio, uchar * buf, size_t size); -size_t vio_write(Vio *vio, const uchar * buf, size_t size); -int vio_blocking(Vio *vio, my_bool onoff, my_bool *old_mode); -my_bool vio_is_blocking(Vio *vio); -/* setsockopt TCP_NODELAY at IPPROTO_TCP level, when possible */ -int vio_nodelay(Vio *vio, my_bool on); -int vio_fastsend(Vio *vio); -/* setsockopt SO_KEEPALIVE at SOL_SOCKET level, when possible */ -int vio_keepalive(Vio *vio, my_bool onoff); -int vio_set_keepalive_options(Vio * vio, const struct vio_keepalive_opts *opts); -/* Whenever we should retry the last read/write operation. */ -my_bool vio_should_retry(Vio *vio); -/* Check that operation was timed out */ -my_bool vio_was_timeout(Vio *vio); -/* Short text description of the socket for those, who are curious.. */ -const char* vio_description(Vio *vio); -/* Return the type of the connection */ -enum enum_vio_type vio_type(Vio* vio); -/* Return last error number */ -int vio_errno(Vio*vio); -/* Get socket number */ -my_socket vio_fd(Vio*vio); -/* Remote peer's address and name in text form */ -my_bool vio_peer_addr(Vio *vio, char *buf, uint16 *port, size_t buflen); -/* Wait for an I/O event notification. */ -int vio_io_wait(Vio *vio, enum enum_vio_io_event event, int timeout); -my_bool vio_is_connected(Vio *vio); -ssize_t vio_pending(Vio *vio); -/* Set timeout for a network operation. */ -extern int vio_timeout(Vio *vio, uint which, int timeout_sec); -extern void vio_set_wait_callback(void (*before_wait)(void), - void (*after_wait)(void)); -/* Connect to a peer. */ -my_bool vio_socket_connect(Vio *vio, struct sockaddr *addr, socklen_t len, - int timeout); - -void vio_get_normalized_ip(const struct sockaddr *src, size_t src_length, struct sockaddr *dst); - -my_bool vio_get_normalized_ip_string(const struct sockaddr *addr, size_t addr_length, - char *ip_string, size_t ip_string_size); - -my_bool vio_is_no_name_error(int err_code); - -int vio_getnameinfo(const struct sockaddr *sa, - char *hostname, size_t hostname_size, - char *port, size_t port_size, - int flags); - -#ifdef HAVE_OPENSSL -/* apple deprecated openssl in MacOSX Lion */ -#ifdef __APPLE__ -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - -#define HEADER_DES_LOCL_H dummy_something -#define YASSL_MYSQL_COMPATIBLE -#ifndef YASSL_PREFIX -#define YASSL_PREFIX -#endif -/* Set yaSSL to use same type as MySQL do for socket handles */ -typedef my_socket YASSL_SOCKET_T; -#define YASSL_SOCKET_T_DEFINED -#define template _template /* bug in WolfSSL 4.4.0, see also my_crypt.cc */ -#include -#undef template -#include -#ifdef DEPRECATED -#undef DEPRECATED -#endif - -enum enum_ssl_init_error -{ - SSL_INITERR_NOERROR= 0, SSL_INITERR_CERT, SSL_INITERR_KEY, - SSL_INITERR_NOMATCH, SSL_INITERR_BAD_PATHS, SSL_INITERR_CIPHERS, - SSL_INITERR_MEMFAIL, SSL_INITERR_DH, SSL_INITERR_PROTOCOL, - SSL_INITERR_LASTERR -}; -const char* sslGetErrString(enum enum_ssl_init_error err); - -struct st_VioSSLFd -{ - SSL_CTX *ssl_context; -}; - -int sslaccept(struct st_VioSSLFd*, Vio *, long timeout, unsigned long *errptr); -int sslconnect(struct st_VioSSLFd*, Vio *, long timeout, unsigned long *errptr); - -void vio_check_ssl_init(); - -struct st_VioSSLFd -*new_VioSSLConnectorFd(const char *key_file, const char *cert_file, - const char *ca_file, const char *ca_path, - const char *cipher, enum enum_ssl_init_error *error, - const char *crl_file, const char *crl_path); -struct st_VioSSLFd -*new_VioSSLAcceptorFd(const char *key_file, const char *cert_file, - const char *ca_file,const char *ca_path, - const char *cipher, enum enum_ssl_init_error *error, - const char *crl_file, const char *crl_path, - ulonglong tls_version); -void free_vio_ssl_acceptor_fd(struct st_VioSSLFd *fd); -#endif /* HAVE_OPENSSL */ - -void vio_end(void); - -const char *vio_type_name(enum enum_vio_type vio_type, size_t *len); - -#ifdef __cplusplus -} -#endif - -#if !defined(DONT_MAP_VIO) -#define vio_delete(vio) (vio)->viodelete(vio) -#define vio_errno(vio) (vio)->vioerrno(vio) -#define vio_read(vio, buf, size) ((vio)->read)(vio,buf,size) -#define vio_write(vio, buf, size) ((vio)->write)(vio, buf, size) -#define vio_blocking(vio, set_blocking_mode, old_mode)\ - (vio)->vioblocking(vio, set_blocking_mode, old_mode) -#define vio_is_blocking(vio) (vio)->is_blocking(vio) -#define vio_fastsend(vio) (vio)->fastsend(vio) -#define vio_keepalive(vio, set_keep_alive) (vio)->viokeepalive(vio, set_keep_alive) -#define vio_should_retry(vio) (vio)->should_retry(vio) -#define vio_was_timeout(vio) (vio)->was_timeout(vio) -#define vio_close(vio) ((vio)->vioclose)(vio) -#define vio_shutdown(vio,how) ((vio)->shutdown)(vio,how) -#define vio_peer_addr(vio, buf, prt, buflen) (vio)->peer_addr(vio, buf, prt, buflen) -#define vio_io_wait(vio, event, timeout) (vio)->io_wait(vio, event, timeout) -#define vio_is_connected(vio) (vio)->is_connected(vio) -#endif /* !defined(DONT_MAP_VIO) */ - -#ifdef _WIN32 - -/* shutdown(2) flags */ -#ifndef SHUT_RD -#define SHUT_RD SD_RECEIVE -#endif - -#endif - -/* This enumerator is used in parser - should be always visible */ -enum SSL_type -{ - SSL_TYPE_NOT_SPECIFIED= -1, - SSL_TYPE_NONE, - SSL_TYPE_ANY, - SSL_TYPE_X509, - SSL_TYPE_SPECIFIED -}; - -/* HFTODO - hide this if we don't want client in embedded server */ -/* This structure is for every connection on both sides */ -struct st_vio -{ - MYSQL_SOCKET mysql_socket; /* Instrumented socket */ - my_bool localhost; /* Are we from localhost? */ - int fcntl_mode; /* Buffered fcntl(sd,F_GETFL) */ - struct sockaddr_storage local; /* Local internet address */ - struct sockaddr_storage remote; /* Remote internet address */ - enum enum_vio_type type; /* Type of connection */ - const char *desc; /* String description */ - char *read_buffer; /* buffer for vio_read_buff */ - char *read_pos; /* start of unfetched data in the - read buffer */ - char *read_end; /* end of unfetched data */ - struct mysql_async_context *async_context; /* For non-blocking API */ - int read_timeout; /* Timeout value (ms) for read ops. */ - int write_timeout; /* Timeout value (ms) for write ops. */ - /* function pointers. They are similar for socket/SSL/whatever */ - void (*viodelete)(Vio*); - int (*vioerrno)(Vio*); - size_t (*read)(Vio*, uchar *, size_t); - size_t (*write)(Vio*, const uchar *, size_t); - int (*timeout)(Vio*, uint, my_bool); - int (*vioblocking)(Vio*, my_bool, my_bool *); - my_bool (*is_blocking)(Vio*); - int (*viokeepalive)(Vio*, my_bool); - int (*fastsend)(Vio*); - my_bool (*peer_addr)(Vio*, char *, uint16*, size_t); - void (*in_addr)(Vio*, struct sockaddr_storage*); - my_bool (*should_retry)(Vio*); - my_bool (*was_timeout)(Vio*); - int (*vioclose)(Vio*); - my_bool (*is_connected)(Vio*); - int (*shutdown)(Vio *, int); - my_bool (*has_data) (Vio*); - int (*io_wait)(Vio*, enum enum_vio_io_event, int); - my_bool (*connect)(Vio*, struct sockaddr *, socklen_t, int); -#ifdef HAVE_OPENSSL - void *ssl_arg; -#endif -#ifdef _WIN32 - HANDLE hPipe; - OVERLAPPED overlapped; - int shutdown_flag; -#endif -}; -#endif /* vio_violite_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/waiting_threads.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/waiting_threads.h deleted file mode 100644 index f785cc8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/waiting_threads.h +++ /dev/null @@ -1,129 +0,0 @@ -/* Copyright (C) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _waiting_threads_h -#define _waiting_threads_h - -#include - -#include - -C_MODE_START - -typedef struct st_wt_resource_id WT_RESOURCE_ID; -typedef struct st_wt_resource WT_RESOURCE; - -typedef struct st_wt_resource_type { - my_bool (*compare)(const void *a, const void *b); - const void *(*make_key)(const WT_RESOURCE_ID *id, uint *len); /* not used */ -} WT_RESOURCE_TYPE; - -struct st_wt_resource_id { - ulonglong value; - const WT_RESOURCE_TYPE *type; -}; -/* the below differs from sizeof(WT_RESOURCE_ID) by the amount of padding */ -#define sizeof_WT_RESOURCE_ID (sizeof(ulonglong)+sizeof(void*)) - -#define WT_WAIT_STATS 24 -#define WT_CYCLE_STATS 32 -extern ulonglong wt_wait_table[WT_WAIT_STATS]; -extern uint32 wt_wait_stats[WT_WAIT_STATS+1]; -extern uint32 wt_cycle_stats[2][WT_CYCLE_STATS+1]; -extern uint32 wt_success_stats; - -typedef struct st_wt_thd { - /* - XXX - there's no protection (mutex) against concurrent access of the - dynarray below. it is assumed that a caller will have it anyway - (not to protect this array but to protect its own - caller's - - data structures), and we'll get it for free. A caller needs to - ensure that a blocker won't release a resource before a blocked - thread starts waiting, which is usually done with a mutex. - - If the above assumption is wrong, we'll need to add a mutex here. - */ - DYNAMIC_ARRAY my_resources; - /* - 'waiting_for' is modified under waiting_for->lock, and only by thd itself - 'waiting_for' is read lock-free (using pinning protocol), but a thd object - can read its own 'waiting_for' without any locks or tricks. - */ - WT_RESOURCE *waiting_for; - LF_PINS *pins; - - /* pointers to values */ - const ulong *timeout_short; - const ulong *deadlock_search_depth_short; - const ulong *timeout_long; - const ulong *deadlock_search_depth_long; - - /* - weight relates to the desirability of a transaction being killed if it's - part of a deadlock. In a deadlock situation transactions with lower weights - are killed first. - - Examples of using the weight to implement different selection strategies: - - 1. Latest - Keep all weights equal. - 2. Random - Assight weights at random. - (variant: modify a weight randomly before every lock request) - 3. Youngest - Set weight to -NOW() - 4. Minimum locks - count locks granted in your lock manager, store the value as a weight - 5. Minimum work - depends on the definition of "work". For example, store the number - of rows modifies in this transaction (or a length of REDO log for a - transaction) as a weight. - - It is only statistically relevant and is not protected by any locks. - */ - ulong volatile weight; - /* - 'killed' is indirectly protected by waiting_for->lock because - a killed thread needs to clear its 'waiting_for' and thus needs a lock. - That is a thread needs an exclusive lock to read 'killed' reliably. - But other threads may change 'killed' from 0 to 1, a shared - lock is enough for that. - */ - my_bool killed; -#ifndef DBUG_OFF - const char *name; -#endif -} WT_THD; - -#define WT_TIMEOUT ETIMEDOUT -#define WT_OK 0 -#define WT_DEADLOCK -1 -#define WT_DEPTH_EXCEEDED -2 -#define WT_FREE_TO_GO -3 - -void wt_init(void); -void wt_end(void); -void wt_thd_lazy_init(WT_THD *, const ulong *, const ulong *, const ulong *, const ulong *); -void wt_thd_destroy(WT_THD *); -int wt_thd_will_wait_for(WT_THD *, WT_THD *, const WT_RESOURCE_ID *); -int wt_thd_cond_timedwait(WT_THD *, mysql_mutex_t *); -void wt_thd_release(WT_THD *, const WT_RESOURCE_ID *); -#define wt_thd_release_all(THD) wt_thd_release((THD), 0) -my_bool wt_resource_id_memcmp(const void *, const void *); - -C_MODE_END - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/welcome_copyright_notice.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/welcome_copyright_notice.h deleted file mode 100644 index 22d8d20..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/welcome_copyright_notice.h +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright (c) 2011, 2017, Oracle and/or its affiliates. - Copyright (c) 2011, 2017, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef _welcome_copyright_notice_h_ -#define _welcome_copyright_notice_h_ - -#define COPYRIGHT_NOTICE_CURRENT_YEAR "2018" - -/* - This define specifies copyright notice which is displayed by every MySQL - program on start, or on help screen. -*/ -#define ORACLE_WELCOME_COPYRIGHT_NOTICE(first_year) \ - "Copyright (c) " first_year ", " COPYRIGHT_NOTICE_CURRENT_YEAR \ - ", Oracle, MariaDB Corporation Ab and others.\n" - -#endif /* _welcome_copyright_notice_h_ */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/win_tzname_data.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/win_tzname_data.h deleted file mode 100644 index 0319722..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/win_tzname_data.h +++ /dev/null @@ -1,138 +0,0 @@ -/* This file was generated using gen_win_tzname_data.ps1 */ -{L"Dateline Standard Time","Etc/GMT+12"}, -{L"UTC-11","Etc/GMT+11"}, -{L"Aleutian Standard Time","America/Adak"}, -{L"Hawaiian Standard Time","Pacific/Honolulu"}, -{L"Marquesas Standard Time","Pacific/Marquesas"}, -{L"Alaskan Standard Time","America/Anchorage"}, -{L"UTC-09","Etc/GMT+9"}, -{L"Pacific Standard Time (Mexico)","America/Tijuana"}, -{L"UTC-08","Etc/GMT+8"}, -{L"Pacific Standard Time","America/Los_Angeles"}, -{L"US Mountain Standard Time","America/Phoenix"}, -{L"Mountain Standard Time (Mexico)","America/Chihuahua"}, -{L"Mountain Standard Time","America/Denver"}, -{L"Central America Standard Time","America/Guatemala"}, -{L"Central Standard Time","America/Chicago"}, -{L"Easter Island Standard Time","Pacific/Easter"}, -{L"Central Standard Time (Mexico)","America/Mexico_City"}, -{L"Canada Central Standard Time","America/Regina"}, -{L"SA Pacific Standard Time","America/Bogota"}, -{L"Eastern Standard Time (Mexico)","America/Cancun"}, -{L"Eastern Standard Time","America/New_York"}, -{L"Haiti Standard Time","America/Port-au-Prince"}, -{L"Cuba Standard Time","America/Havana"}, -{L"US Eastern Standard Time","America/Indianapolis"}, -{L"Turks And Caicos Standard Time","America/Grand_Turk"}, -{L"Paraguay Standard Time","America/Asuncion"}, -{L"Atlantic Standard Time","America/Halifax"}, -{L"Venezuela Standard Time","America/Caracas"}, -{L"Central Brazilian Standard Time","America/Cuiaba"}, -{L"SA Western Standard Time","America/La_Paz"}, -{L"Pacific SA Standard Time","America/Santiago"}, -{L"Newfoundland Standard Time","America/St_Johns"}, -{L"Tocantins Standard Time","America/Araguaina"}, -{L"E. South America Standard Time","America/Sao_Paulo"}, -{L"SA Eastern Standard Time","America/Cayenne"}, -{L"Argentina Standard Time","America/Buenos_Aires"}, -{L"Greenland Standard Time","America/Godthab"}, -{L"Montevideo Standard Time","America/Montevideo"}, -{L"Magallanes Standard Time","America/Punta_Arenas"}, -{L"Saint Pierre Standard Time","America/Miquelon"}, -{L"Bahia Standard Time","America/Bahia"}, -{L"UTC-02","Etc/GMT+2"}, -{L"Azores Standard Time","Atlantic/Azores"}, -{L"Cape Verde Standard Time","Atlantic/Cape_Verde"}, -{L"UTC","Etc/GMT"}, -{L"GMT Standard Time","Europe/London"}, -{L"Greenwich Standard Time","Atlantic/Reykjavik"}, -{L"Sao Tome Standard Time","Africa/Sao_Tome"}, -{L"Morocco Standard Time","Africa/Casablanca"}, -{L"W. Europe Standard Time","Europe/Berlin"}, -{L"Central Europe Standard Time","Europe/Budapest"}, -{L"Romance Standard Time","Europe/Paris"}, -{L"Central European Standard Time","Europe/Warsaw"}, -{L"W. Central Africa Standard Time","Africa/Lagos"}, -{L"Jordan Standard Time","Asia/Amman"}, -{L"GTB Standard Time","Europe/Bucharest"}, -{L"Middle East Standard Time","Asia/Beirut"}, -{L"Egypt Standard Time","Africa/Cairo"}, -{L"E. Europe Standard Time","Europe/Chisinau"}, -{L"Syria Standard Time","Asia/Damascus"}, -{L"West Bank Standard Time","Asia/Hebron"}, -{L"South Africa Standard Time","Africa/Johannesburg"}, -{L"FLE Standard Time","Europe/Kiev"}, -{L"Israel Standard Time","Asia/Jerusalem"}, -{L"Kaliningrad Standard Time","Europe/Kaliningrad"}, -{L"Sudan Standard Time","Africa/Khartoum"}, -{L"Libya Standard Time","Africa/Tripoli"}, -{L"Namibia Standard Time","Africa/Windhoek"}, -{L"Arabic Standard Time","Asia/Baghdad"}, -{L"Turkey Standard Time","Europe/Istanbul"}, -{L"Arab Standard Time","Asia/Riyadh"}, -{L"Belarus Standard Time","Europe/Minsk"}, -{L"Russian Standard Time","Europe/Moscow"}, -{L"E. Africa Standard Time","Africa/Nairobi"}, -{L"Iran Standard Time","Asia/Tehran"}, -{L"Arabian Standard Time","Asia/Dubai"}, -{L"Astrakhan Standard Time","Europe/Astrakhan"}, -{L"Azerbaijan Standard Time","Asia/Baku"}, -{L"Russia Time Zone 3","Europe/Samara"}, -{L"Mauritius Standard Time","Indian/Mauritius"}, -{L"Saratov Standard Time","Europe/Saratov"}, -{L"Georgian Standard Time","Asia/Tbilisi"}, -{L"Volgograd Standard Time","Europe/Volgograd"}, -{L"Caucasus Standard Time","Asia/Yerevan"}, -{L"Afghanistan Standard Time","Asia/Kabul"}, -{L"West Asia Standard Time","Asia/Tashkent"}, -{L"Ekaterinburg Standard Time","Asia/Yekaterinburg"}, -{L"Pakistan Standard Time","Asia/Karachi"}, -{L"Qyzylorda Standard Time","Asia/Qyzylorda"}, -{L"India Standard Time","Asia/Calcutta"}, -{L"Sri Lanka Standard Time","Asia/Colombo"}, -{L"Nepal Standard Time","Asia/Katmandu"}, -{L"Central Asia Standard Time","Asia/Almaty"}, -{L"Bangladesh Standard Time","Asia/Dhaka"}, -{L"Omsk Standard Time","Asia/Omsk"}, -{L"Myanmar Standard Time","Asia/Rangoon"}, -{L"SE Asia Standard Time","Asia/Bangkok"}, -{L"Altai Standard Time","Asia/Barnaul"}, -{L"W. Mongolia Standard Time","Asia/Hovd"}, -{L"North Asia Standard Time","Asia/Krasnoyarsk"}, -{L"N. Central Asia Standard Time","Asia/Novosibirsk"}, -{L"Tomsk Standard Time","Asia/Tomsk"}, -{L"China Standard Time","Asia/Shanghai"}, -{L"North Asia East Standard Time","Asia/Irkutsk"}, -{L"Singapore Standard Time","Asia/Singapore"}, -{L"W. Australia Standard Time","Australia/Perth"}, -{L"Taipei Standard Time","Asia/Taipei"}, -{L"Ulaanbaatar Standard Time","Asia/Ulaanbaatar"}, -{L"Aus Central W. Standard Time","Australia/Eucla"}, -{L"Transbaikal Standard Time","Asia/Chita"}, -{L"Tokyo Standard Time","Asia/Tokyo"}, -{L"North Korea Standard Time","Asia/Pyongyang"}, -{L"Korea Standard Time","Asia/Seoul"}, -{L"Yakutsk Standard Time","Asia/Yakutsk"}, -{L"Cen. Australia Standard Time","Australia/Adelaide"}, -{L"AUS Central Standard Time","Australia/Darwin"}, -{L"E. Australia Standard Time","Australia/Brisbane"}, -{L"AUS Eastern Standard Time","Australia/Sydney"}, -{L"West Pacific Standard Time","Pacific/Port_Moresby"}, -{L"Tasmania Standard Time","Australia/Hobart"}, -{L"Vladivostok Standard Time","Asia/Vladivostok"}, -{L"Lord Howe Standard Time","Australia/Lord_Howe"}, -{L"Bougainville Standard Time","Pacific/Bougainville"}, -{L"Russia Time Zone 10","Asia/Srednekolymsk"}, -{L"Magadan Standard Time","Asia/Magadan"}, -{L"Norfolk Standard Time","Pacific/Norfolk"}, -{L"Sakhalin Standard Time","Asia/Sakhalin"}, -{L"Central Pacific Standard Time","Pacific/Guadalcanal"}, -{L"Russia Time Zone 11","Asia/Kamchatka"}, -{L"New Zealand Standard Time","Pacific/Auckland"}, -{L"UTC+12","Etc/GMT-12"}, -{L"Fiji Standard Time","Pacific/Fiji"}, -{L"Chatham Islands Standard Time","Pacific/Chatham"}, -{L"UTC+13","Etc/GMT-13"}, -{L"Tonga Standard Time","Pacific/Tongatapu"}, -{L"Samoa Standard Time","Pacific/Apia"}, -{L"Line Islands Standard Time","Pacific/Kiritimati"}, diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/winservice.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/winservice.h deleted file mode 100644 index f9ab3ed..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/winservice.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright (c) 2011, 2012, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -/* - Extract properties of a windows service binary path -*/ -#ifdef __cplusplus -extern "C" { -#endif - -#include -typedef struct mysqld_service_properties_st -{ - char mysqld_exe[MAX_PATH]; - char inifile[MAX_PATH]; - char datadir[MAX_PATH]; - int version_major; - int version_minor; - int version_patch; -} mysqld_service_properties; - -extern int get_mysql_service_properties(const wchar_t *bin_path, - mysqld_service_properties *props); - -#ifdef __cplusplus -} -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wqueue.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wqueue.h deleted file mode 100644 index de7a717..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wqueue.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright (c) 2007, 2008, Sun Microsystems, Inc, - Copyright (c) 2011, 2012, Monty Program Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef WQUEUE_INCLUDED -#define WQUEUE_INCLUDED - -#include - -/* info about requests in a waiting queue */ -typedef struct st_pagecache_wqueue -{ - struct st_my_thread_var *last_thread; /* circular list of waiting - threads */ -} WQUEUE; - -void wqueue_link_into_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); -void wqueue_unlink_from_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); -void wqueue_add_to_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); -void wqueue_add_and_wait(WQUEUE *wqueue, - struct st_my_thread_var *thread, - mysql_mutex_t *lock); -void wqueue_release_queue(WQUEUE *wqueue); -void wqueue_release_one_locktype_from_queue(WQUEUE *wqueue); - -#endif diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep.h deleted file mode 100644 index f8a1863..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep.h +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright 2014 Codership Oy & SkySQL Ab - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef WSREP_INCLUDED -#define WSREP_INCLUDED - -#include - -#ifdef WITH_WSREP - -#define IF_WSREP(A,B) A - -#define DBUG_ASSERT_IF_WSREP(A) DBUG_ASSERT(A) - -#define WSREP_MYSQL_DB (char *)"mysql" - -#define WSREP_TO_ISOLATION_BEGIN(db_, table_, table_list_) \ - if (WSREP(thd) && wsrep_to_isolation_begin(thd, db_, table_, table_list_)) \ - goto wsrep_error_label; - -#define WSREP_TO_ISOLATION_BEGIN_CREATE(db_, table_, table_list_, create_info_) \ - if (WSREP(thd) && \ - wsrep_to_isolation_begin(thd, db_, table_, \ - table_list_, NULL, create_info_)) \ - goto wsrep_error_label; - -#define WSREP_TO_ISOLATION_BEGIN_ALTER(db_, table_, table_list_, alter_info_, create_info_) \ - if (WSREP(thd) && wsrep_thd_is_local(thd) && \ - wsrep_to_isolation_begin(thd, db_, table_, \ - table_list_, alter_info_, create_info_)) \ - goto wsrep_error_label; - -#define WSREP_TO_ISOLATION_END \ - if ((WSREP(thd) && wsrep_thd_is_local_toi(thd)) || \ - wsrep_thd_is_in_rsu(thd)) \ - wsrep_to_isolation_end(thd); - -/* - Checks if lex->no_write_to_binlog is set for statements that use LOCAL or - NO_WRITE_TO_BINLOG. -*/ -#define WSREP_TO_ISOLATION_BEGIN_WRTCHK(db_, table_, table_list_) \ - if (WSREP(thd) && !thd->lex->no_write_to_binlog \ - && wsrep_to_isolation_begin(thd, db_, table_, table_list_)) goto wsrep_error_label; - -#define WSREP_SYNC_WAIT(thd_, before_) \ - { if (WSREP_CLIENT(thd_) && \ - wsrep_sync_wait(thd_, before_)) goto wsrep_error_label; } - -#else /* !WITH_WSREP */ - -/* These macros are needed to compile MariaDB without WSREP support - * (e.g. embedded) */ - -#define IF_WSREP(A,B) B -#define WSREP_DEBUG(...) -#define WSREP_ERROR(...) -#define WSREP_TO_ISOLATION_BEGIN(db_, table_, table_list_) do { } while(0) -#define WSREP_TO_ISOLATION_BEGIN_ALTER(db_, table_, table_list_, alter_info_, create_info_) -#define WSREP_TO_ISOLATION_END -#define WSREP_TO_ISOLATION_BEGIN_CREATE(db_, table_, table_list_, create_info_) -#define WSREP_TO_ISOLATION_BEGIN_WRTCHK(db_, table_, table_list_) -#define WSREP_SYNC_WAIT(thd_, before_) -#endif /* WITH_WSREP */ - -#endif /* WSREP_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_applier.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_applier.h deleted file mode 100644 index fefca30..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_applier.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright 2013-2019 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef WSREP_APPLIER_H -#define WSREP_APPLIER_H - -#include "sql_class.h" // THD class -#include "rpl_rli.h" // Relay_log_info -#include "log_event.h" // Format_description_log_event - -int wsrep_apply_events(THD* thd, - Relay_log_info* rli, - const void* events_buf, - size_t buf_len); - -/* Applier error codes, when nothing better is available. */ -#define WSREP_RET_SUCCESS 0 // Success -#define WSREP_ERR_GENERIC 1 // When in doubt (MySQL default error code) -#define WSREP_ERR_BAD_EVENT 2 // Can't parse event -#define WSREP_ERR_NOT_FOUND 3 // Key. table, schema not found -#define WSREP_ERR_EXISTS 4 // Key, table, schema already exists -#define WSREP_ERR_WRONG_TYPE 5 // Incompatible data type -#define WSREP_ERR_FAILED 6 // Operation failed for some internal reason -#define WSREP_ERR_ABORTED 7 // Operation was aborted externally - -void wsrep_store_error(const THD* thd, wsrep::mutable_buffer& buf); - -class Format_description_log_event; -void wsrep_set_apply_format(THD*, Format_description_log_event*); -Format_description_log_event* wsrep_get_apply_format(THD* thd); - -#endif /* WSREP_APPLIER_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_binlog.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_binlog.h deleted file mode 100644 index 252fbe6..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_binlog.h +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright (C) 2013 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ - -#ifndef WSREP_BINLOG_H -#define WSREP_BINLOG_H - -#include "my_global.h" -#include "sql_class.h" // THD, IO_CACHE - -#define HEAP_PAGE_SIZE 65536 /* 64K */ -#define WSREP_MAX_WS_SIZE 2147483647 /* 2GB */ - -/* - Write the contents of a cache to a memory buffer. - - This function quite the same as MYSQL_BIN_LOG::write_cache(), - with the exception that here we write in buffer instead of log file. - */ -int wsrep_write_cache_buf(IO_CACHE *cache, uchar **buf, size_t *buf_len); - -/* - Write the contents of a cache to wsrep provider. - - This function quite the same as MYSQL_BIN_LOG::write_cache(), - with the exception that here we write in buffer instead of log file. - - @param len total amount of data written - @return wsrep error status - */ -int wsrep_write_cache(THD* thd, - IO_CACHE* cache, - size_t* len); - -/* Dump replication buffer to disk */ -void wsrep_dump_rbr_buf(THD *thd, const void* rbr_buf, size_t buf_len); - -/* Dump replication buffer along with header to a file */ -void wsrep_dump_rbr_buf_with_header(THD *thd, const void *rbr_buf, - size_t buf_len); - -/** - Write a skip event into binlog. - - @param thd Thread object pointer - @return Zero in case of success, non-zero on failure. -*/ -int wsrep_write_skip_event(THD* thd); - -/* - Write dummy event into binlog in place of unused GTID. - The binlog write is done in thd context. -*/ -int wsrep_write_dummy_event_low(THD *thd, const char *msg); -/* - Write dummy event to binlog in place of unused GTID and - commit. The binlog write and commit are done in temporary - thd context, the original thd state is not altered. -*/ -int wsrep_write_dummy_event(THD* thd, const char *msg); - -void wsrep_register_binlog_handler(THD *thd, bool trx); - -/** - Return true if committing THD will write to binlog during commit. - This is the case for: - - Local THD, binlog is open - - Replaying THD, binlog is open - - Applier THD, log-slave-updates is enabled -*/ -bool wsrep_commit_will_write_binlog(THD *thd); - -/** - Register THD for group commit. The wsrep_trx must be in committing state, - i.e. the call must be done after wsrep_before_commit() but before - commit order is released. - - This call will release commit order critical section if it is - determined that the commit will go through binlog group commit. - */ -void wsrep_register_for_group_commit(THD *thd); - -/** - Deregister THD from group commit. The wsrep_trx must be in committing state, - as for wsrep_register_for_group_commit() above. - - This call must be used only for THDs which will not go through - binlog group commit. -*/ -void wsrep_unregister_from_group_commit(THD *thd); - -#endif /* WSREP_BINLOG_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_client_service.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_client_service.h deleted file mode 100644 index aa58d99..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_client_service.h +++ /dev/null @@ -1,63 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -/** @file wsrep_client_service.h - - This file provides declaratios for client service implementation. - See wsrep/client_service.hpp for interface documentation. -*/ - -#ifndef WSREP_CLIENT_SERVICE_H -#define WSREP_CLIENT_SERVICE_H - -/* wsrep-lib */ -#include "wsrep/client_service.hpp" -#include "wsrep/client_state.hpp" -#include "wsrep/exception.hpp" /* not_implemented_error, remove when finished */ - -class THD; -class Wsrep_client_state; -class Wsrep_high_priority_context; - -class Wsrep_client_service : public wsrep::client_service -{ -public: - Wsrep_client_service(THD*, Wsrep_client_state&); - - bool interrupted(wsrep::unique_lock&) const; - void reset_globals(); - void store_globals(); - int prepare_data_for_replication(); - void cleanup_transaction(); - bool statement_allowed_for_streaming() const; - size_t bytes_generated() const; - int prepare_fragment_for_replication(wsrep::mutable_buffer&, size_t&); - int remove_fragments(); - void emergency_shutdown() - { throw wsrep::not_implemented_error(); } - void will_replay(); - enum wsrep::provider::status replay(); - void wait_for_replayers(wsrep::unique_lock&); - void debug_sync(const char*); - void debug_crash(const char*); - int bf_rollback(); -private: - friend class Wsrep_server_service; - THD* m_thd; - Wsrep_client_state& m_client_state; -}; - - -#endif /* WSREP_CLIENT_SERVICE_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_client_state.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_client_state.h deleted file mode 100644 index 403bfa8..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_client_state.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef WSREP_CLIENT_STATE_H -#define WSREP_CLIENT_STATE_H - -/* wsrep-lib */ -#include "wsrep/client_state.hpp" -#include "my_global.h" - -class THD; - -class Wsrep_client_state : public wsrep::client_state -{ -public: - Wsrep_client_state(THD* thd, - wsrep::mutex& mutex, - wsrep::condition_variable& cond, - wsrep::server_state& server_state, - wsrep::client_service& client_service, - const wsrep::client_id& id) - : wsrep::client_state(mutex, - cond, - server_state, - client_service, - id, - wsrep::client_state::m_local) - , m_thd(thd) - { } - THD* thd() { return m_thd; } -private: - THD* m_thd; -}; - -#endif /* WSREP_CLIENT_STATE_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_condition_variable.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_condition_variable.h deleted file mode 100644 index 4412154..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_condition_variable.h +++ /dev/null @@ -1,54 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef WSREP_CONDITION_VARIABLE_H -#define WSREP_CONDITION_VARIABLE_H - -/* wsrep-lib */ -#include "wsrep/condition_variable.hpp" - -/* implementation */ -#include "my_pthread.h" - -class Wsrep_condition_variable : public wsrep::condition_variable -{ -public: - - Wsrep_condition_variable(mysql_cond_t& cond) - : m_cond(cond) - { } - ~Wsrep_condition_variable() - { } - - void notify_one() - { - mysql_cond_signal(&m_cond); - } - - void notify_all() - { - mysql_cond_broadcast(&m_cond); - } - - void wait(wsrep::unique_lock& lock) - { - mysql_mutex_t* mutex= static_cast(lock.mutex().native()); - mysql_cond_wait(&m_cond, mutex); - } -private: - mysql_cond_t& m_cond; -}; - -#endif /* WSREP_CONDITION_VARIABLE_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_high_priority_service.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_high_priority_service.h deleted file mode 100644 index c275c35..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_high_priority_service.h +++ /dev/null @@ -1,134 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef WSREP_HIGH_PRIORITY_SERVICE_H -#define WSREP_HIGH_PRIORITY_SERVICE_H - -#include "wsrep/high_priority_service.hpp" -#include "my_global.h" -#include "sql_error.h" /* Diagnostics area */ -#include "sql_class.h" /* rpl_group_info */ - -class THD; -class Relay_log_info; -class Wsrep_server_service; - -class Wsrep_high_priority_service : - public wsrep::high_priority_service, - public wsrep::high_priority_context -{ -public: - Wsrep_high_priority_service(THD*); - ~Wsrep_high_priority_service(); - int start_transaction(const wsrep::ws_handle&, - const wsrep::ws_meta&); - int next_fragment(const wsrep::ws_meta&); - const wsrep::transaction& transaction() const; - int adopt_transaction(const wsrep::transaction&); - int apply_write_set(const wsrep::ws_meta&, const wsrep::const_buffer&, - wsrep::mutable_buffer&) = 0; - int append_fragment_and_commit(const wsrep::ws_handle&, - const wsrep::ws_meta&, - const wsrep::const_buffer&, - const wsrep::xid&); - int remove_fragments(const wsrep::ws_meta&); - int commit(const wsrep::ws_handle&, const wsrep::ws_meta&); - int rollback(const wsrep::ws_handle&, const wsrep::ws_meta&); - int apply_toi(const wsrep::ws_meta&, const wsrep::const_buffer&, - wsrep::mutable_buffer&); - void store_globals(); - void reset_globals(); - void switch_execution_context(wsrep::high_priority_service&); - int log_dummy_write_set(const wsrep::ws_handle&, - const wsrep::ws_meta&, - wsrep::mutable_buffer&); - void adopt_apply_error(wsrep::mutable_buffer&); - - virtual bool check_exit_status() const = 0; - void debug_crash(const char*); -protected: - friend Wsrep_server_service; - THD* m_thd; - Relay_log_info* m_rli; - rpl_group_info* m_rgi; - struct shadow - { - ulonglong option_bits; - uint server_status; - struct st_vio* vio; - ulong tx_isolation; - char* db; - size_t db_length; - //struct timeval user_time; - my_hrtime_t user_time; - longlong row_count_func; - bool wsrep_applier; - } m_shadow; -}; - -class Wsrep_applier_service : public Wsrep_high_priority_service -{ -public: - Wsrep_applier_service(THD*); - ~Wsrep_applier_service(); - int apply_write_set(const wsrep::ws_meta&, const wsrep::const_buffer&, - wsrep::mutable_buffer&); - int apply_nbo_begin(const wsrep::ws_meta&, const wsrep::const_buffer& data, - wsrep::mutable_buffer& err); - void after_apply(); - bool is_replaying() const { return false; } - bool check_exit_status() const; -}; - -class Wsrep_replayer_service : public Wsrep_high_priority_service -{ -public: - Wsrep_replayer_service(THD* replayer_thd, THD* orig_thd); - ~Wsrep_replayer_service(); - int apply_write_set(const wsrep::ws_meta&, const wsrep::const_buffer&, - wsrep::mutable_buffer&); - int apply_nbo_begin(const wsrep::ws_meta&, const wsrep::const_buffer& data, - wsrep::mutable_buffer& err) - { - DBUG_ASSERT(0); /* DDL should never cause replaying */ - return 0; - } - void after_apply() { } - bool is_replaying() const { return true; } - void replay_status(enum wsrep::provider::status status) - { m_replay_status = status; } - enum wsrep::provider::status replay_status() const - { return m_replay_status; } - /* Replayer should never be forced to exit */ - bool check_exit_status() const { return false; } -private: - THD* m_orig_thd; - struct da_shadow - { - enum Diagnostics_area::enum_diagnostics_status status; - ulonglong affected_rows; - ulonglong last_insert_id; - char message[MYSQL_ERRMSG_SIZE]; - da_shadow() - : status() - , affected_rows() - , last_insert_id() - , message() - { } - } m_da_shadow; - enum wsrep::provider::status m_replay_status; -}; - -#endif /* WSREP_HIGH_PRIORITY_SERVICE_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mutex.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mutex.h deleted file mode 100644 index 3454b44..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mutex.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef WSREP_MUTEX_H -#define WSREP_MUTEX_H - -/* wsrep-lib */ -#include "wsrep/mutex.hpp" - -/* implementation */ -#include "my_pthread.h" - -class Wsrep_mutex : public wsrep::mutex -{ -public: - Wsrep_mutex(mysql_mutex_t& mutex) - : m_mutex(mutex) - { } - - void lock() - { - mysql_mutex_lock(&m_mutex); - } - - void unlock() - { - mysql_mutex_unlock(&m_mutex); - } - - void* native() - { - return &m_mutex; - } -private: - mysql_mutex_t& m_mutex; -}; - -#endif /* WSREP_MUTEX_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mysqld.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mysqld.h deleted file mode 100644 index 4461d73..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mysqld.h +++ /dev/null @@ -1,635 +0,0 @@ -/* Copyright 2008-2017 Codership Oy - Copyright (c) 2020, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef WSREP_MYSQLD_H -#define WSREP_MYSQLD_H - -#include - -#ifdef WITH_WSREP -extern bool WSREP_ON_; - -#include -#include "mysql/service_wsrep.h" - -#include -#include -#include "log.h" -#include "mysqld.h" - -typedef struct st_mysql_show_var SHOW_VAR; -#include -#include "mdl.h" -#include "sql_table.h" -#include "wsrep_mysqld_c.h" - -#include "wsrep/provider.hpp" -#include "wsrep/streaming_context.hpp" -#include "wsrep_api.h" -#include -#include -#include "wsrep_server_state.h" - -#define WSREP_UNDEFINED_TRX_ID ULONGLONG_MAX - -class set_var; -class THD; - -enum wsrep_consistency_check_mode { - NO_CONSISTENCY_CHECK, - CONSISTENCY_CHECK_DECLARED, - CONSISTENCY_CHECK_RUNNING, -}; - -// Global wsrep parameters - -// MySQL wsrep options -extern const char* wsrep_provider; -extern const char* wsrep_provider_options; -extern const char* wsrep_cluster_name; -extern const char* wsrep_cluster_address; -extern const char* wsrep_node_name; -extern const char* wsrep_node_address; -extern const char* wsrep_node_incoming_address; -extern const char* wsrep_data_home_dir; -extern const char* wsrep_dbug_option; -extern long wsrep_slave_threads; -extern int wsrep_slave_count_change; -extern ulong wsrep_debug; -extern my_bool wsrep_convert_LOCK_to_trx; -extern ulong wsrep_retry_autocommit; -extern my_bool wsrep_auto_increment_control; -extern my_bool wsrep_drupal_282555_workaround; -extern my_bool wsrep_incremental_data_collection; -extern const char* wsrep_start_position; -extern ulong wsrep_max_ws_size; -extern ulong wsrep_max_ws_rows; -extern const char* wsrep_notify_cmd; -extern my_bool wsrep_certify_nonPK; -extern long int wsrep_protocol_version; -extern ulong wsrep_forced_binlog_format; -extern my_bool wsrep_desync; -extern ulong wsrep_reject_queries; -extern my_bool wsrep_recovery; -extern my_bool wsrep_replicate_myisam; -extern my_bool wsrep_log_conflicts; -extern ulong wsrep_mysql_replication_bundle; -extern my_bool wsrep_load_data_splitting; -extern my_bool wsrep_restart_slave; -extern my_bool wsrep_restart_slave_activated; -extern my_bool wsrep_slave_FK_checks; -extern my_bool wsrep_slave_UK_checks; -extern ulong wsrep_trx_fragment_unit; -extern ulong wsrep_SR_store_type; -extern uint wsrep_ignore_apply_errors; -extern ulong wsrep_running_threads; -extern ulong wsrep_running_applier_threads; -extern ulong wsrep_running_rollbacker_threads; -extern bool wsrep_new_cluster; -extern bool wsrep_gtid_mode; -extern my_bool wsrep_strict_ddl; - -enum enum_wsrep_reject_types { - WSREP_REJECT_NONE, /* nothing rejected */ - WSREP_REJECT_ALL, /* reject all queries, with UNKNOWN_COMMAND error */ - WSREP_REJECT_ALL_KILL /* kill existing connections and reject all queries*/ -}; - -enum enum_wsrep_OSU_method { - WSREP_OSU_TOI, - WSREP_OSU_RSU, - WSREP_OSU_NONE -}; - -enum enum_wsrep_sync_wait { - WSREP_SYNC_WAIT_NONE= 0x0, - // select, begin - WSREP_SYNC_WAIT_BEFORE_READ= 0x1, - WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE= 0x2, - WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE= 0x4, - WSREP_SYNC_WAIT_BEFORE_SHOW= 0x8, - WSREP_SYNC_WAIT_MAX= 0xF -}; - -enum enum_wsrep_ignore_apply_error { - WSREP_IGNORE_ERRORS_NONE= 0x0, - WSREP_IGNORE_ERRORS_ON_RECONCILING_DDL= 0x1, - WSREP_IGNORE_ERRORS_ON_RECONCILING_DML= 0x2, - WSREP_IGNORE_ERRORS_ON_DDL= 0x4, - WSREP_IGNORE_ERRORS_MAX= 0x7 -}; - -// Streaming Replication -#define WSREP_FRAG_BYTES 0 -#define WSREP_FRAG_ROWS 1 -#define WSREP_FRAG_STATEMENTS 2 - -#define WSREP_SR_STORE_NONE 0 -#define WSREP_SR_STORE_TABLE 1 - -extern const char *wsrep_fragment_units[]; -extern const char *wsrep_SR_store_types[]; - -// MySQL status variables -extern my_bool wsrep_connected; -extern my_bool wsrep_ready; -extern const char* wsrep_cluster_state_uuid; -extern long long wsrep_cluster_conf_id; -extern const char* wsrep_cluster_status; -extern long wsrep_cluster_size; -extern long wsrep_local_index; -extern long long wsrep_local_bf_aborts; -extern const char* wsrep_provider_name; -extern const char* wsrep_provider_version; -extern const char* wsrep_provider_vendor; -extern char* wsrep_provider_capabilities; -extern char* wsrep_cluster_capabilities; - -int wsrep_show_status(THD *thd, SHOW_VAR *var, void *buff, - system_status_var *status_var, enum_var_type scope); -int wsrep_show_ready(THD *thd, SHOW_VAR *var, char *buff); -void wsrep_free_status(THD *thd); -void wsrep_update_cluster_state_uuid(const char* str); - -/* Filters out --wsrep-new-cluster oprtion from argv[] - * should be called in the very beginning of main() */ -void wsrep_filter_new_cluster (int* argc, char* argv[]); - -int wsrep_init(); -void wsrep_deinit(bool free_options); - -/* Initialize wsrep thread LOCKs and CONDs */ -void wsrep_thr_init(); -/* Destroy wsrep thread LOCKs and CONDs */ -void wsrep_thr_deinit(); - -void wsrep_recover(); -bool wsrep_before_SE(); // initialize wsrep before storage - // engines (true) or after (false) -/* wsrep initialization sequence at startup - * @param before wsrep_before_SE() value */ -void wsrep_init_startup(bool before); - -/* Recover streaming transactions from fragment storage */ -void wsrep_recover_sr_from_storage(THD *); - -// Other wsrep global variables -extern my_bool wsrep_inited; // whether wsrep is initialized ? -extern bool wsrep_service_started; - -extern "C" void wsrep_fire_rollbacker(THD *thd); -extern "C" uint32 wsrep_thd_wsrep_rand(THD *thd); -extern "C" time_t wsrep_thd_query_start(THD *thd); -extern void wsrep_close_client_connections(my_bool wait_to_end, - THD *except_caller_thd= NULL); -extern "C" query_id_t wsrep_thd_wsrep_last_query_id(THD *thd); -extern "C" void wsrep_thd_set_wsrep_last_query_id(THD *thd, query_id_t id); - -extern int wsrep_wait_committing_connections_close(int wait_time); -extern void wsrep_close_applier(THD *thd); -extern void wsrep_wait_appliers_close(THD *thd); -extern void wsrep_close_applier_threads(int count); - - -/* new defines */ -extern void wsrep_stop_replication(THD *thd); -extern bool wsrep_start_replication(); -extern void wsrep_shutdown_replication(); -extern bool wsrep_must_sync_wait (THD* thd, uint mask= WSREP_SYNC_WAIT_BEFORE_READ); -extern bool wsrep_sync_wait (THD* thd, uint mask= WSREP_SYNC_WAIT_BEFORE_READ); -extern enum wsrep::provider::status -wsrep_sync_wait_upto (THD* thd, wsrep_gtid_t* upto, int timeout); -extern void wsrep_last_committed_id (wsrep_gtid_t* gtid); -extern int wsrep_check_opts(); -extern void wsrep_prepend_PATH (const char* path); - -/* Other global variables */ -extern wsrep_seqno_t wsrep_locked_seqno; -#define WSREP_ON unlikely(WSREP_ON_) - -/* use xxxxxx_NNULL macros when thd pointer is guaranteed to be non-null to - * avoid compiler warnings (GCC 6 and later) */ - -#define WSREP_NNULL(thd) (WSREP_ON && thd->variables.wsrep_on) - -#define WSREP(thd) \ - (thd && WSREP_NNULL(thd)) - -#define WSREP_CLIENT_NNULL(thd) \ - (WSREP_NNULL(thd) && thd->wsrep_client_thread) - -#define WSREP_CLIENT(thd) \ - (WSREP(thd) && thd->wsrep_client_thread) - -#define WSREP_EMULATE_BINLOG_NNULL(thd) \ - (WSREP_NNULL(thd) && wsrep_emulate_bin_log) - -#define WSREP_EMULATE_BINLOG(thd) \ - (WSREP(thd) && wsrep_emulate_bin_log) - -#define WSREP_BINLOG_FORMAT(my_format) \ - ((wsrep_forced_binlog_format != BINLOG_FORMAT_UNSPEC) ? \ - wsrep_forced_binlog_format : my_format) - -/* A wrapper function for MySQL log functions. The call will prefix - the log message with WSREP and forward the result buffer to fun. */ -void WSREP_LOG(void (*fun)(const char* fmt, ...), const char* fmt, ...); - -#define WSREP_DEBUG(...) \ - if (wsrep_debug) sql_print_information( "WSREP: " __VA_ARGS__) -#define WSREP_INFO(...) sql_print_information( "WSREP: " __VA_ARGS__) -#define WSREP_WARN(...) sql_print_warning( "WSREP: " __VA_ARGS__) -#define WSREP_ERROR(...) sql_print_error( "WSREP: " __VA_ARGS__) - -#define WSREP_LOG_CONFLICT_THD(thd, role) \ - sql_print_information( \ - "WSREP: %s: \n " \ - " THD: %lu, mode: %s, state: %s, conflict: %s, seqno: %lld\n " \ - " SQL: %s", \ - role, \ - thd_get_thread_id(thd), \ - wsrep_thd_client_mode_str(thd), \ - wsrep_thd_client_state_str(thd), \ - wsrep_thd_transaction_state_str(thd), \ - wsrep_thd_trx_seqno(thd), \ - wsrep_thd_query(thd) \ - ); - -#define WSREP_LOG_CONFLICT(bf_thd, victim_thd, bf_abort) \ - if (wsrep_debug || wsrep_log_conflicts) \ - { \ - sql_print_information( "WSREP: cluster conflict due to %s for threads:", \ - (bf_abort) ? "high priority abort" : "certification failure" \ - ); \ - if (bf_thd) WSREP_LOG_CONFLICT_THD(bf_thd, "Winning thread"); \ - if (victim_thd) WSREP_LOG_CONFLICT_THD(victim_thd, "Victim thread"); \ - sql_print_information("WSREP: context: %s:%d", __FILE__, __LINE__); \ - } - -#define WSREP_PROVIDER_EXISTS \ - (wsrep_provider && strncasecmp(wsrep_provider, WSREP_NONE, FN_REFLEN)) - -#define WSREP_QUERY(thd) (thd->query()) - -extern my_bool wsrep_ready_get(); -extern void wsrep_ready_wait(); - -class Ha_trx_info; -struct THD_TRANS; - -extern mysql_mutex_t LOCK_wsrep_ready; -extern mysql_cond_t COND_wsrep_ready; -extern mysql_mutex_t LOCK_wsrep_sst; -extern mysql_cond_t COND_wsrep_sst; -extern mysql_mutex_t LOCK_wsrep_sst_init; -extern mysql_cond_t COND_wsrep_sst_init; -extern int wsrep_replaying; -extern mysql_mutex_t LOCK_wsrep_replaying; -extern mysql_cond_t COND_wsrep_replaying; -extern mysql_mutex_t LOCK_wsrep_slave_threads; -extern mysql_cond_t COND_wsrep_slave_threads; -extern mysql_mutex_t LOCK_wsrep_gtid_wait_upto; -extern mysql_mutex_t LOCK_wsrep_cluster_config; -extern mysql_mutex_t LOCK_wsrep_desync; -extern mysql_mutex_t LOCK_wsrep_SR_pool; -extern mysql_mutex_t LOCK_wsrep_SR_store; -extern mysql_mutex_t LOCK_wsrep_config_state; -extern mysql_mutex_t LOCK_wsrep_group_commit; -extern mysql_mutex_t LOCK_wsrep_joiner_monitor; -extern mysql_mutex_t LOCK_wsrep_donor_monitor; -extern mysql_cond_t COND_wsrep_joiner_monitor; -extern mysql_cond_t COND_wsrep_donor_monitor; - -extern my_bool wsrep_emulate_bin_log; -extern int wsrep_to_isolation; -extern my_bool wsrep_preordered_opt; - -#ifdef HAVE_PSI_INTERFACE - -extern PSI_cond_key key_COND_wsrep_thd; - -extern PSI_mutex_key key_LOCK_wsrep_ready; -extern PSI_mutex_key key_COND_wsrep_ready; -extern PSI_mutex_key key_LOCK_wsrep_sst; -extern PSI_cond_key key_COND_wsrep_sst; -extern PSI_mutex_key key_LOCK_wsrep_sst_init; -extern PSI_cond_key key_COND_wsrep_sst_init; -extern PSI_mutex_key key_LOCK_wsrep_sst_thread; -extern PSI_cond_key key_COND_wsrep_sst_thread; -extern PSI_mutex_key key_LOCK_wsrep_replaying; -extern PSI_cond_key key_COND_wsrep_replaying; -extern PSI_mutex_key key_LOCK_wsrep_slave_threads; -extern PSI_cond_key key_COND_wsrep_slave_threads; -extern PSI_mutex_key key_LOCK_wsrep_gtid_wait_upto; -extern PSI_cond_key key_COND_wsrep_gtid_wait_upto; -extern PSI_mutex_key key_LOCK_wsrep_cluster_config; -extern PSI_mutex_key key_LOCK_wsrep_desync; -extern PSI_mutex_key key_LOCK_wsrep_SR_pool; -extern PSI_mutex_key key_LOCK_wsrep_SR_store; -extern PSI_mutex_key key_LOCK_wsrep_global_seqno; -extern PSI_mutex_key key_LOCK_wsrep_thd_queue; -extern PSI_cond_key key_COND_wsrep_thd_queue; -extern PSI_mutex_key key_LOCK_wsrep_joiner_monitor; -extern PSI_mutex_key key_LOCK_wsrep_donor_monitor; - -extern PSI_file_key key_file_wsrep_gra_log; - -extern PSI_thread_key key_wsrep_sst_joiner; -extern PSI_thread_key key_wsrep_sst_donor; -extern PSI_thread_key key_wsrep_rollbacker; -extern PSI_thread_key key_wsrep_applier; -extern PSI_thread_key key_wsrep_sst_joiner_monitor; -extern PSI_thread_key key_wsrep_sst_donor_monitor; -#endif /* HAVE_PSI_INTERFACE */ - - -struct TABLE_LIST; -class Alter_info; -struct HA_CREATE_INFO; - -int wsrep_to_isolation_begin(THD *thd, const char *db_, const char *table_, - const TABLE_LIST* table_list, - const Alter_info* alter_info= NULL, - const HA_CREATE_INFO* create_info= NULL); - -bool wsrep_should_replicate_ddl(THD* thd, const enum legacy_db_type db_type); -bool wsrep_should_replicate_ddl_iterate(THD* thd, const TABLE_LIST* table_list); - -void wsrep_to_isolation_end(THD *thd); - -bool wsrep_append_SR_keys(THD *thd); -int wsrep_to_buf_helper( - THD* thd, const char *query, uint query_len, uchar** buf, size_t* buf_len); -int wsrep_create_trigger_query(THD *thd, uchar** buf, size_t* buf_len); -int wsrep_create_event_query(THD *thd, uchar** buf, size_t* buf_len); - -bool wsrep_stmt_rollback_is_safe(THD* thd); - -void wsrep_init_sidno(const wsrep_uuid_t&); -bool wsrep_node_is_donor(); -bool wsrep_node_is_synced(); - -void wsrep_init_SR(); -void wsrep_verify_SE_checkpoint(const wsrep_uuid_t& uuid, wsrep_seqno_t seqno); -int wsrep_replay_from_SR_store(THD*, const wsrep_trx_meta_t&); -void wsrep_node_uuid(wsrep_uuid_t&); - -class Log_event; -int wsrep_ignored_error_code(Log_event* ev, int error); -int wsrep_must_ignore_error(THD* thd); - -struct wsrep_server_gtid_t -{ - uint32 domain_id; - uint32 server_id; - uint64 seqno; -}; -class Wsrep_gtid_server -{ -public: - uint32 domain_id; - uint32 server_id; - Wsrep_gtid_server() - : m_force_signal(false) - , m_seqno(0) - , m_committed_seqno(0) - { } - void gtid(const wsrep_server_gtid_t& gtid) - { - domain_id= gtid.domain_id; - server_id= gtid.server_id; - m_seqno= gtid.seqno; - } - wsrep_server_gtid_t gtid() - { - wsrep_server_gtid_t gtid; - gtid.domain_id= domain_id; - gtid.server_id= server_id; - gtid.seqno= m_seqno; - return gtid; - } - void seqno(const uint64 seqno) { m_seqno= seqno; } - uint64 seqno() const { return m_seqno; } - uint64 seqno_committed() const { return m_committed_seqno; } - uint64 seqno_inc() - { - m_seqno++; - return m_seqno; - } - const wsrep_server_gtid_t& undefined() - { - return m_undefined; - } - int wait_gtid_upto(const uint64_t seqno, uint timeout) - { - int wait_result= 0; - struct timespec wait_time; - int ret= 0; - mysql_cond_t wait_cond; - mysql_cond_init(key_COND_wsrep_gtid_wait_upto, &wait_cond, NULL); - set_timespec(wait_time, timeout); - mysql_mutex_lock(&LOCK_wsrep_gtid_wait_upto); - std::multimap::iterator it; - if (seqno > m_seqno) - { - try - { - it= m_wait_map.insert(std::make_pair(seqno, &wait_cond)); - } - catch (std::bad_alloc& e) - { - ret= ENOMEM; - } - while (!ret && (m_committed_seqno < seqno) && !m_force_signal) - { - wait_result= mysql_cond_timedwait(&wait_cond, - &LOCK_wsrep_gtid_wait_upto, - &wait_time); - if (wait_result == ETIMEDOUT || wait_result == ETIME) - { - ret= wait_result; - break; - } - } - if (ret != ENOMEM) - { - m_wait_map.erase(it); - } - } - mysql_mutex_unlock(&LOCK_wsrep_gtid_wait_upto); - mysql_cond_destroy(&wait_cond); - return ret; - } - void signal_waiters(uint64 seqno, bool signal_all) - { - mysql_mutex_lock(&LOCK_wsrep_gtid_wait_upto); - if (!signal_all && (m_committed_seqno >= seqno)) - { - mysql_mutex_unlock(&LOCK_wsrep_gtid_wait_upto); - return; - } - m_force_signal= true; - std::multimap::iterator it_end; - std::multimap::iterator it_begin; - if (signal_all) - { - it_end= m_wait_map.end(); - } - else - { - it_end= m_wait_map.upper_bound(seqno); - } - if (m_committed_seqno < seqno) - { - m_committed_seqno= seqno; - } - for (it_begin = m_wait_map.begin(); it_begin != it_end; ++it_begin) - { - mysql_cond_signal(it_begin->second); - } - m_force_signal= false; - mysql_mutex_unlock(&LOCK_wsrep_gtid_wait_upto); - } -private: - const wsrep_server_gtid_t m_undefined= {0,0,0}; - std::multimap m_wait_map; - bool m_force_signal; - Atomic_counter m_seqno; - Atomic_counter m_committed_seqno; -}; -extern Wsrep_gtid_server wsrep_gtid_server; -void wsrep_init_gtid(); -bool wsrep_check_gtid_seqno(const uint32&, const uint32&, uint64&); -bool wsrep_get_binlog_gtid_seqno(wsrep_server_gtid_t&); - -typedef struct wsrep_key_arr -{ - wsrep_key_t* keys; - size_t keys_len; -} wsrep_key_arr_t; -bool wsrep_prepare_keys_for_isolation(THD* thd, - const char* db, - const char* table, - const TABLE_LIST* table_list, - wsrep_key_arr_t* ka); -void wsrep_keys_free(wsrep_key_arr_t* key_arr); - -extern void -wsrep_handle_mdl_conflict(MDL_context *requestor_ctx, - const MDL_ticket *ticket, - const MDL_key *key); - -enum wsrep_thread_type { - WSREP_APPLIER_THREAD=1, - WSREP_ROLLBACKER_THREAD=2 -}; - -typedef void (*wsrep_thd_processor_fun)(THD*, void *); -class Wsrep_thd_args -{ - public: - Wsrep_thd_args(wsrep_thd_processor_fun fun, - wsrep_thread_type thread_type, - pthread_t thread_id) - : - fun_ (fun), - thread_type_ (thread_type), - thread_id_ (thread_id) - { } - - wsrep_thd_processor_fun fun() { return fun_; } - pthread_t* thread_id() {return &thread_id_; } - enum wsrep_thread_type thread_type() {return thread_type_;} - - private: - - Wsrep_thd_args(const Wsrep_thd_args&); - Wsrep_thd_args& operator=(const Wsrep_thd_args&); - - wsrep_thd_processor_fun fun_; - enum wsrep_thread_type thread_type_; - pthread_t thread_id_; -}; - -void* start_wsrep_THD(void*); - -void wsrep_close_threads(THD *thd); -bool wsrep_is_show_query(enum enum_sql_command command); -void wsrep_replay_transaction(THD *thd); -bool wsrep_create_like_table(THD* thd, TABLE_LIST* table, - TABLE_LIST* src_table, - HA_CREATE_INFO *create_info); -bool wsrep_node_is_donor(); -bool wsrep_node_is_synced(); - -/** - * Check if the wsrep provider (ie the Galera library) is capable of - * doing streaming replication. - * @return true if SR capable - */ -bool wsrep_provider_is_SR_capable(); - -/** - * Initialize WSREP server instance. - * - * @return Zero on success, non-zero on error. - */ -int wsrep_init_server(); - -/** - * Initialize WSREP globals. This should be done after server initialization - * is complete and the server has joined to the cluster. - * - */ -void wsrep_init_globals(); - -/** - * Deinit and release WSREP resources. - */ -void wsrep_deinit_server(); - -/** - * Convert streaming fragment unit (WSREP_FRAG_BYTES, WSREP_FRAG_ROWS...) - * to corresponding wsrep-lib fragment_unit - */ -enum wsrep::streaming_context::fragment_unit wsrep_fragment_unit(ulong unit); - -#else /* !WITH_WSREP */ - -/* These macros are needed to compile MariaDB without WSREP support - * (e.g. embedded) */ - -#define WSREP_ON false -#define WSREP(T) (0) -#define WSREP_NNULL(T) (0) -#define WSREP_EMULATE_BINLOG(thd) (0) -#define WSREP_EMULATE_BINLOG_NNULL(thd) (0) -#define WSREP_BINLOG_FORMAT(my_format) ((ulong)my_format) -#define WSREP_PROVIDER_EXISTS (0) -#define wsrep_emulate_bin_log (0) -#define wsrep_to_isolation (0) -#define wsrep_before_SE() (0) -#define wsrep_init_startup(X) -#define wsrep_check_opts() (0) -#define wsrep_thr_init() do {} while(0) -#define wsrep_thr_deinit() do {} while(0) -#define wsrep_init_globals() do {} while(0) -#define wsrep_create_appliers(X) do {} while(0) -#define wsrep_should_replicate_ddl(X,Y) (1) - -#endif /* WITH_WSREP */ - -#endif /* WSREP_MYSQLD_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mysqld_c.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mysqld_c.h deleted file mode 100644 index 603f2c2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_mysqld_c.h +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright 2018-2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifndef WSREP_MYSQLD_C_H -#define WSREP_MYSQLD_C_H - -enum enum_wsrep_certification_rules { - WSREP_CERTIFICATION_RULES_STRICT, - WSREP_CERTIFICATION_RULES_OPTIMIZED -}; - -/* This is intentionally declared as a weak global symbol, so that -the same ha_innodb.so can be used with the embedded server -(which does not link to the definition of this variable) -and with the regular server built WITH_WSREP. */ -extern ulong wsrep_certification_rules __attribute__((weak)); - -#endif /* WSREP_MYSQLD_C_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_priv.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_priv.h deleted file mode 100644 index e480331..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_priv.h +++ /dev/null @@ -1,51 +0,0 @@ -/* Copyright 2010 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA - */ - -//! @file declares symbols private to wsrep integration layer - -#ifndef WSREP_PRIV_H -#define WSREP_PRIV_H - -#include -#include "wsrep_mysqld.h" -#include "wsrep_schema.h" - -#include -#include -#include - -my_bool wsrep_ready_set (my_bool x); - -ssize_t wsrep_sst_prepare (void** msg); -wsrep_cb_status wsrep_sst_donate_cb (void* app_ctx, - void* recv_ctx, - const wsrep_buf_t* msg, - const wsrep_gtid_t* state_id, - const wsrep_buf_t* state, - bool bypass); - -extern wsrep_uuid_t local_uuid; -extern wsrep_seqno_t local_seqno; -extern Wsrep_schema* wsrep_schema; - -// a helper function -void wsrep_sst_received(THD*, const wsrep_uuid_t&, wsrep_seqno_t, - const void*, size_t); - -void wsrep_notify_status(enum wsrep::server_state::state status, - const wsrep::view* view= 0); - -#endif /* WSREP_PRIV_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_schema.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_schema.h deleted file mode 100644 index 36e2399..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_schema.h +++ /dev/null @@ -1,144 +0,0 @@ -/* Copyright (C) 2015-2019 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ - - -#ifndef WSREP_SCHEMA_H -#define WSREP_SCHEMA_H - -/* wsrep-lib */ -#include "wsrep_types.h" - -#include "mysqld.h" -#include "wsrep_mysqld.h" - -/* - Forward decls -*/ -class THD; -class Relay_log_info; -struct TABLE; -struct TABLE_LIST; -struct st_mysql_lex_string; -typedef struct st_mysql_lex_string LEX_STRING; - -/** Name of the table in `wsrep_schema_str` used for storing streaming -replication data. In an InnoDB full format, e.g. "database/tablename". */ -extern const char* wsrep_sr_table_name_full; - -class Wsrep_schema -{ - public: - - Wsrep_schema(); - ~Wsrep_schema(); - - /* - Initialize wsrep schema. Storage engines must be running before - calling this function. - */ - int init(); - - /* - Store wsrep view info into wsrep schema. - */ - int store_view(THD*, const Wsrep_view& view); - - /* - Restore view info from stable storage. - */ - Wsrep_view restore_view(THD* thd, const Wsrep_id& own_id) const; - - /** - Append transaction fragment to fragment storage. - Transaction must have been started for THD before this call. - In order to make changes durable, transaction must be committed - separately after this call. - - @param thd THD object - @param server_id Wsrep server identifier - @param transaction_id Transaction identifier - @param flags Flags for the fragment - @param data Fragment data buffer - - @return Zero in case of success, non-zero on failure. - */ - int append_fragment(THD* thd, - const wsrep::id& server_id, - wsrep::transaction_id transaction_id, - wsrep::seqno seqno, - int flags, - const wsrep::const_buffer& data); - /** - Update existing fragment meta data. The fragment must have been - inserted before using append_fragment(). - - @param thd THD object - @param ws_meta Wsrep meta data - - @return Zero in case of success, non-zero on failure. - */ - int update_fragment_meta(THD* thd, - const wsrep::ws_meta& ws_meta); - - /** - Remove fragments from storage. This method must be called - inside active transaction. Fragment removal will be committed - once the transaction commits. - - @param thd Pointer to THD object - @param server_id Identifier of the running server - @param transaction_id Identifier of the current transaction - @param fragments Vector of fragment seqnos to be removed - */ - int remove_fragments(THD* thd, - const wsrep::id& server_id, - wsrep::transaction_id transaction_id, - const std::vector& fragments); - - /** - Replay a transaction from stored fragments. The caller must have - started a transaction for a thd. - - @param thd Pointer to THD object - @param ws_meta Write set meta data for commit fragment. - @param fragments Vector of fragments to be replayed - - @return Zero on success, non-zero on failure. - */ - int replay_transaction(THD* thd, - Relay_log_info* rli, - const wsrep::ws_meta& ws_meta, - const std::vector& fragments); - - /** - Recover streaming transactions from SR table. - This method should be called after storage enignes are initialized. - It will scan SR table and replay found streaming transactions. - - @param orig_thd The THD object of the calling thread. - - @return Zero on success, non-zero on failure. - */ - int recover_sr_transactions(THD* orig_thd); - - private: - /* Non-copyable */ - Wsrep_schema(const Wsrep_schema&); - Wsrep_schema& operator=(const Wsrep_schema&); -}; - -extern Wsrep_schema* wsrep_schema; - -#endif /* !WSREP_SCHEMA_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_server_service.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_server_service.h deleted file mode 100644 index 168e982..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_server_service.h +++ /dev/null @@ -1,101 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef WSREP_SERVER_SERVICE_H -#define WSREP_SERVER_SERVICE_H - -/* wsrep-lib */ -#include "wsrep/server_service.hpp" -#include "wsrep/exception.hpp" // not_impemented_error(), remove when finished -#include "wsrep/storage_service.hpp" - -class Wsrep_server_state; - - -/* wsrep::server_service interface implementation */ -class Wsrep_server_service : public wsrep::server_service -{ -public: - Wsrep_server_service(Wsrep_server_state& server_state) - : m_server_state(server_state) - { } - - wsrep::storage_service* storage_service(wsrep::client_service&); - - wsrep::storage_service* storage_service(wsrep::high_priority_service&); - - void release_storage_service(wsrep::storage_service*); - - wsrep::high_priority_service* - streaming_applier_service(wsrep::client_service&); - - wsrep::high_priority_service* - streaming_applier_service(wsrep::high_priority_service&); - - void release_high_priority_service(wsrep::high_priority_service*); - - void background_rollback(wsrep::client_state&); - - void bootstrap(); - void log_message(enum wsrep::log::level, const char*); - - void log_dummy_write_set(wsrep::client_state&, const wsrep::ws_meta&) - { throw wsrep::not_implemented_error(); } - - void log_view(wsrep::high_priority_service*, const wsrep::view&); - - void recover_streaming_appliers(wsrep::client_service&); - void recover_streaming_appliers(wsrep::high_priority_service&); - wsrep::view get_view(wsrep::client_service&, const wsrep::id& own_id); - - wsrep::gtid get_position(wsrep::client_service&); - void set_position(wsrep::client_service&, const wsrep::gtid&); - - void log_state_change(enum wsrep::server_state::state, - enum wsrep::server_state::state); - - bool sst_before_init() const; - - std::string sst_request(); - int start_sst(const std::string&, const wsrep::gtid&, bool); - - int wait_committing_transactions(int); - - void debug_sync(const char*); -private: - Wsrep_server_state& m_server_state; -}; - -/** - Helper method to create new streaming applier. - - @param orig_thd Original thd context to copy operation context from. - @param ctx Context string for debug logging. - */ -class Wsrep_applier_service; -Wsrep_applier_service* -wsrep_create_streaming_applier(THD *orig_thd, const char *ctx); - -/** - Helper method to create new storage service. - - @param orig_thd Original thd context to copy operation context from. - @param ctx Context string for debug logging. -*/ -class Wsrep_storage_service; -Wsrep_storage_service* -wsrep_create_storage_service(THD *orig_thd, const char *ctx); - -#endif /* WSREP_SERVER_SERVICE */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_server_state.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_server_state.h deleted file mode 100644 index 1ef9373..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_server_state.h +++ /dev/null @@ -1,74 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef WSREP_SERVER_STATE_H -#define WSREP_SERVER_STATE_H - -/* wsrep-lib */ -#include "wsrep/server_state.hpp" -#include "wsrep/provider.hpp" - -/* implementation */ -#include "wsrep_server_service.h" -#include "wsrep_mutex.h" -#include "wsrep_condition_variable.h" - -class Wsrep_server_state : public wsrep::server_state -{ -public: - static void init_once(const std::string& name, - const std::string& incoming_address, - const std::string& address, - const std::string& working_dir, - const wsrep::gtid& initial_position, - int max_protocol_version); - static void destroy(); - - static Wsrep_server_state& instance() - { - return *m_instance; - } - - static bool is_inited() - { - return (m_instance != NULL); - } - - static wsrep::provider& get_provider() - { - return instance().provider(); - } - - static bool has_capability(int capability) - { - return (get_provider().capabilities() & capability); - } - -private: - Wsrep_server_state(const std::string& name, - const std::string& incoming_address, - const std::string& address, - const std::string& working_dir, - const wsrep::gtid& initial_position, - int max_protocol_version); - ~Wsrep_server_state(); - Wsrep_mutex m_mutex; - Wsrep_condition_variable m_cond; - Wsrep_server_service m_service; - static Wsrep_server_state* m_instance; - -}; - -#endif // WSREP_SERVER_STATE_H diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_sst.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_sst.h deleted file mode 100644 index 2389db4..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_sst.h +++ /dev/null @@ -1,106 +0,0 @@ -/* Copyright (C) 2013-2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ - -#ifndef WSREP_SST_H -#define WSREP_SST_H - -#include - -#include "wsrep/gtid.hpp" -#include -#include - -#define WSREP_SST_OPT_ROLE "--role" -#define WSREP_SST_OPT_ADDR "--address" -#define WSREP_SST_OPT_AUTH "--auth" -#define WSREP_SST_OPT_DATA "--datadir" -#define WSREP_SST_OPT_CONF "--defaults-file" -#define WSREP_SST_OPT_CONF_SUFFIX "--defaults-group-suffix" -#define WSREP_SST_OPT_CONF_EXTRA "--defaults-extra-file" -#define WSREP_SST_OPT_PARENT "--parent" -#define WSREP_SST_OPT_BINLOG "--binlog" -#define WSREP_SST_OPT_BINLOG_INDEX "--binlog-index" -#define WSREP_SST_OPT_MYSQLD "--mysqld-args" - -// mysqldump-specific options -#define WSREP_SST_OPT_USER "--user" -#define WSREP_SST_OPT_PSWD "--password" -#define WSREP_SST_OPT_HOST "--host" -#define WSREP_SST_OPT_PORT "--port" -#define WSREP_SST_OPT_LPORT "--local-port" - -// donor-specific -#define WSREP_SST_OPT_SOCKET "--socket" -#define WSREP_SST_OPT_GTID "--gtid" -#define WSREP_SST_OPT_BYPASS "--bypass" -#define WSREP_SST_OPT_GTID_DOMAIN_ID "--gtid-domain-id" - -#define WSREP_SST_MYSQLDUMP "mysqldump" -#define WSREP_SST_RSYNC "rsync" -#define WSREP_SST_SKIP "skip" -#define WSREP_SST_MARIABACKUP "mariabackup" -#define WSREP_SST_XTRABACKUP "xtrabackup" -#define WSREP_SST_XTRABACKUPV2 "xtrabackupv2" -#define WSREP_SST_DEFAULT WSREP_SST_RSYNC -#define WSREP_SST_ADDRESS_AUTO "AUTO" -#define WSREP_SST_AUTH_MASK "********" - -/* system variables */ -extern const char* wsrep_sst_method; -extern const char* wsrep_sst_receive_address; -extern const char* wsrep_sst_donor; -extern const char* wsrep_sst_auth; -extern my_bool wsrep_sst_donor_rejects_queries; - -/*! Synchronizes applier thread start with init thread */ -extern void wsrep_sst_grab(); -/*! Init thread waits for SST completion */ -extern bool wsrep_sst_wait(); -/*! Signals wsrep that initialization is complete, writesets can be applied */ -extern bool wsrep_sst_continue(); -extern void wsrep_sst_auth_init(); -extern void wsrep_sst_auth_free(); - -extern void wsrep_SE_init_grab(); /*! grab init critical section */ -extern void wsrep_SE_init_wait(); /*! wait for SE init to complete */ -extern void wsrep_SE_init_done(); /*! signal that SE init is complte */ -extern void wsrep_SE_initialized(); /*! mark SE initialization complete */ - -/** - Return a string containing the state transfer request string. - Note that the string may contain a '\0' in the middle. -*/ -std::string wsrep_sst_prepare(); - -/** - Donate a SST. - - @param request SST request string received from the joiner. Note that - the string may contain a '\0' in the middle. - @param gtid Current position of the donor - @param bypass If true, full SST is not needed. Joiner needs to be - notified that it can continue starting from gtid. - */ -int wsrep_sst_donate(const std::string& request, - const wsrep::gtid& gtid, - bool bypass); - -#else -#define wsrep_SE_initialized() do { } while(0) -#define wsrep_SE_init_grab() do { } while(0) -#define wsrep_SE_init_done() do { } while(0) -#define wsrep_sst_continue() (0) - -#endif /* WSREP_SST_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_storage_service.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_storage_service.h deleted file mode 100644 index f39543a..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_storage_service.h +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -#ifndef WSREP_STORAGE_SERVICE_H -#define WSREP_STORAGE_SERVICE_H - -#include "wsrep/storage_service.hpp" -#include "wsrep/client_state.hpp" - -class THD; -class Wsrep_server_service; -class Wsrep_storage_service : - public wsrep::storage_service, - public wsrep::high_priority_context -{ -public: - Wsrep_storage_service(THD*); - ~Wsrep_storage_service(); - int start_transaction(const wsrep::ws_handle&); - void adopt_transaction(const wsrep::transaction&); - int append_fragment(const wsrep::id&, - wsrep::transaction_id, - int flags, - const wsrep::const_buffer&, - const wsrep::xid&); - int update_fragment_meta(const wsrep::ws_meta&); - int remove_fragments(); - int commit(const wsrep::ws_handle&, const wsrep::ws_meta&); - int rollback(const wsrep::ws_handle&, const wsrep::ws_meta&); - void store_globals(); - void reset_globals(); -private: - friend class Wsrep_server_service; - THD* m_thd; -}; - -#endif /* WSREP_STORAGE_SERVICE_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_thd.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_thd.h deleted file mode 100644 index c7350c7..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_thd.h +++ /dev/null @@ -1,302 +0,0 @@ -/* Copyright (C) 2013 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ - -#ifndef WSREP_THD_H -#define WSREP_THD_H - -#include - -#include "mysql/service_wsrep.h" -#include "wsrep/client_state.hpp" -#include "sql_class.h" -#include "wsrep_utils.h" -#include -class Wsrep_thd_queue -{ -public: - Wsrep_thd_queue(THD* t) : thd(t) - { - mysql_mutex_init(key_LOCK_wsrep_thd_queue, - &LOCK_wsrep_thd_queue, - MY_MUTEX_INIT_FAST); - mysql_cond_init(key_COND_wsrep_thd_queue, &COND_wsrep_thd_queue, NULL); - } - ~Wsrep_thd_queue() - { - mysql_mutex_destroy(&LOCK_wsrep_thd_queue); - mysql_cond_destroy(&COND_wsrep_thd_queue); - } - bool push_back(THD* thd) - { - DBUG_ASSERT(thd); - wsp::auto_lock lock(&LOCK_wsrep_thd_queue); - std::deque::iterator it = queue.begin(); - while (it != queue.end()) - { - if (*it == thd) - { - return true; - } - it++; - } - queue.push_back(thd); - mysql_cond_signal(&COND_wsrep_thd_queue); - return false; - } - THD* pop_front() - { - wsp::auto_lock lock(&LOCK_wsrep_thd_queue); - while (queue.empty()) - { - if (thd->killed != NOT_KILLED) - return NULL; - - thd->mysys_var->current_mutex= &LOCK_wsrep_thd_queue; - thd->mysys_var->current_cond= &COND_wsrep_thd_queue; - - mysql_cond_wait(&COND_wsrep_thd_queue, &LOCK_wsrep_thd_queue); - - thd->mysys_var->current_mutex= 0; - thd->mysys_var->current_cond= 0; - } - THD* ret= queue.front(); - queue.pop_front(); - return ret; - } -private: - THD* thd; - std::deque queue; - mysql_mutex_t LOCK_wsrep_thd_queue; - mysql_cond_t COND_wsrep_thd_queue; -}; - -int wsrep_show_bf_aborts (THD *thd, SHOW_VAR *var, char *buff, - enum enum_var_type scope); -bool wsrep_create_appliers(long threads, bool mutex_protected=false); -void wsrep_create_rollbacker(); - -bool wsrep_bf_abort(const THD*, THD*); -int wsrep_abort_thd(THD *bf_thd_ptr, THD *victim_thd_ptr, my_bool signal); - -extern void wsrep_thd_set_PA_safe(void *thd_ptr, my_bool safe); - -/* - Helper methods to deal with thread local storage. - The purpose of these methods is to hide the details of thread - local storage handling when operating with wsrep storage access - and streaming applier THDs - - With one-thread-per-connection thread handling thread specific - variables are allocated when the thread is started and deallocated - before thread exits (my_thread_init(), my_thread_end()). However, - with pool-of-threads thread handling new thread specific variables - are allocated for each THD separately (see threadpool_add_connection()), - and the variables in thread local storage are assigned from - currently active thread (see thread_attach()). This must be taken into - account when storing/resetting thread local storage and when creating - streaming applier THDs. -*/ - -/** - Create new variables for thread local storage. With - one-thread-per-connection thread handling this is a no op, - with pool-of-threads new variables are created via my_thread_init(). - It is assumed that the caller has called wsrep_reset_threadvars() to clear - the thread local storage before this call. - - @return Zero in case of success, non-zero otherwise. -*/ -int wsrep_create_threadvars(); - -/** - Delete variables which were created by wsrep_create_threadvars(). - The caller must store variables into thread local storage before - this call via wsrep_store_threadvars(). -*/ -void wsrep_delete_threadvars(); - -/** - Assign variables from current thread local storage into THD. - This should be called for THDs whose lifetime is limited to single - thread execution or which may share the operation context with some - parent THD (e.g. storage access) and thus don't require separately - allocated globals. - - With one-thread-per-connection thread handling this is a no-op, - with pool-of-threads the variables which are currently stored into - thread local storage are assigned to THD. -*/ -void wsrep_assign_from_threadvars(THD *); - -/** - Helper struct to save variables from thread local storage. - */ -struct Wsrep_threadvars -{ - THD* cur_thd; - st_my_thread_var* mysys_var; -}; - -/** - Save variables from thread local storage into Wsrep_threadvars struct. - */ -Wsrep_threadvars wsrep_save_threadvars(); - -/** - Restore variables into thread local storage from Wsrep_threadvars struct. -*/ -void wsrep_restore_threadvars(const Wsrep_threadvars&); - -/** - Store variables into thread local storage. -*/ -void wsrep_store_threadvars(THD *); - -/** - Reset thread local storage. -*/ -void wsrep_reset_threadvars(THD *); - -/** - Helper functions to override error status - - In many contexts it is desirable to mask the original error status - set for THD or it is necessary to change OK status to error. - This function implements the common logic for the most - of the cases. - - Rules: - * If the diagnostics are has OK or EOF status, override it unconditionally - * If the error is either ER_ERROR_DURING_COMMIT or ER_LOCK_DEADLOCK - it is usually the correct error status to be returned to client, - so don't override those by default - */ - -static inline void wsrep_override_error(THD *thd, uint error) -{ - DBUG_ASSERT(error != ER_ERROR_DURING_COMMIT); - Diagnostics_area *da= thd->get_stmt_da(); - if (da->is_ok() || - da->is_eof() || - !da->is_set() || - (da->is_error() && - da->sql_errno() != error && - da->sql_errno() != ER_ERROR_DURING_COMMIT && - da->sql_errno() != ER_LOCK_DEADLOCK)) - { - da->reset_diagnostics_area(); - my_error(error, MYF(0)); - } -} - -/** - Override error with additional wsrep status. - */ -static inline void wsrep_override_error(THD *thd, uint error, - enum wsrep::provider::status status) -{ - Diagnostics_area *da= thd->get_stmt_da(); - if (da->is_ok() || - !da->is_set() || - (da->is_error() && - da->sql_errno() != error && - da->sql_errno() != ER_ERROR_DURING_COMMIT && - da->sql_errno() != ER_LOCK_DEADLOCK)) - { - da->reset_diagnostics_area(); - my_error(error, MYF(0), status); - } -} - -static inline void wsrep_override_error(THD* thd, - wsrep::client_error ce, - enum wsrep::provider::status status) -{ - DBUG_ASSERT(ce != wsrep::e_success); - switch (ce) - { - case wsrep::e_error_during_commit: - wsrep_override_error(thd, ER_ERROR_DURING_COMMIT, status); - break; - case wsrep::e_deadlock_error: - wsrep_override_error(thd, ER_LOCK_DEADLOCK); - break; - case wsrep::e_interrupted_error: - wsrep_override_error(thd, ER_QUERY_INTERRUPTED); - break; - case wsrep::e_size_exceeded_error: - wsrep_override_error(thd, ER_ERROR_DURING_COMMIT, status); - break; - case wsrep::e_append_fragment_error: - /* TODO: Figure out better error number */ - wsrep_override_error(thd, ER_ERROR_DURING_COMMIT, status); - break; - case wsrep::e_not_supported_error: - wsrep_override_error(thd, ER_NOT_SUPPORTED_YET); - break; - case wsrep::e_timeout_error: - wsrep_override_error(thd, ER_LOCK_WAIT_TIMEOUT); - break; - default: - wsrep_override_error(thd, ER_UNKNOWN_ERROR); - break; - } -} - -/** - Helper function to log THD wsrep context. - - @param thd Pointer to THD - @param message Optional message - @param function Function where the call was made from - */ -static inline void wsrep_log_thd(const THD *thd, - const char *message, - const char *function) -{ - WSREP_DEBUG("%s %s\n" - " thd: %llu thd_ptr: %p client_mode: %s client_state: %s trx_state: %s\n" - " next_trx_id: %lld trx_id: %lld seqno: %lld\n" - " is_streaming: %d fragments: %zu\n" - " sql_errno: %u message: %s\n" -#define WSREP_THD_LOG_QUERIES -#ifdef WSREP_THD_LOG_QUERIES - " command: %d query: %.72s" -#endif /* WSREP_OBSERVER_LOG_QUERIES */ - , - function, - message ? message : "", - thd->thread_id, - thd, - wsrep_thd_client_mode_str(thd), - wsrep_thd_client_state_str(thd), - wsrep_thd_transaction_state_str(thd), - (long long)thd->wsrep_next_trx_id(), - (long long)thd->wsrep_trx_id(), - (long long)wsrep_thd_trx_seqno(thd), - thd->wsrep_trx().is_streaming(), - thd->wsrep_sr().fragments().size(), - (thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->sql_errno() : 0), - (thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->message() : "") -#ifdef WSREP_THD_LOG_QUERIES - , thd->lex->sql_command, - WSREP_QUERY(thd) -#endif /* WSREP_OBSERVER_LOG_QUERIES */ - ); -} - -#define WSREP_LOG_THD(thd_, message_) wsrep_log_thd(thd_, message_, __FUNCTION__) - -#endif /* WSREP_THD_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_trans_observer.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_trans_observer.h deleted file mode 100644 index 35b93cb..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_trans_observer.h +++ /dev/null @@ -1,526 +0,0 @@ -/* Copyright 2016-2019 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ - -#ifndef WSREP_TRANS_OBSERVER_H -#define WSREP_TRANS_OBSERVER_H - -#include "my_global.h" -#include "mysql/service_wsrep.h" -#include "wsrep_applier.h" /* wsrep_apply_error */ -#include "wsrep_xid.h" -#include "wsrep_thd.h" -#include "wsrep_binlog.h" /* register/deregister group commit */ -#include "my_dbug.h" - -class THD; - -void wsrep_commit_empty(THD* thd, bool all); - -/* - Return true if THD has active wsrep transaction. - */ -static inline bool wsrep_is_active(THD* thd) -{ - return (thd->wsrep_cs().state() != wsrep::client_state::s_none && - thd->wsrep_cs().transaction().active() && - !thd->internal_transaction()); -} - -/* - Return true if transaction is ordered. - */ -static inline bool wsrep_is_ordered(THD* thd) -{ - return thd->wsrep_trx().ordered(); -} - -/* - Return true if transaction has been BF aborted but has not been - rolled back yet. - - It is required that the caller holds thd->LOCK_thd_data. -*/ -static inline bool wsrep_must_abort(THD* thd) -{ - mysql_mutex_assert_owner(&thd->LOCK_thd_data); - return (thd->wsrep_trx().state() == wsrep::transaction::s_must_abort); -} - -/* - Return true if the transaction must be replayed. - */ -static inline bool wsrep_must_replay(THD* thd) -{ - return (thd->wsrep_trx().state() == wsrep::transaction::s_must_replay); -} -/* - Return true if transaction has not been committed. - - Note that we don't require thd->LOCK_thd_data here. Calling this method - makes sense only from codepaths which are past ordered_commit state - and the wsrep transaction is immune to BF aborts at that point. -*/ -static inline bool wsrep_not_committed(THD* thd) -{ - return (thd->wsrep_trx().state() != wsrep::transaction::s_committed); -} - -/* - Return true if THD is either committing a transaction or statement - is autocommit. - */ -static inline bool wsrep_is_real(THD* thd, bool all) -{ - return (all || thd->transaction->all.ha_list == 0); -} - -/* - Check if a transaction has generated changes. - */ -static inline bool wsrep_has_changes(THD* thd) -{ - return (thd->wsrep_trx().is_empty() == false); -} - -/* - Check if an active transaction has been BF aborted. - */ -static inline bool wsrep_is_bf_aborted(THD* thd) -{ - return (thd->wsrep_trx().active() && thd->wsrep_trx().bf_aborted()); -} - -static inline int wsrep_check_pk(THD* thd) -{ - if (!wsrep_certify_nonPK) - { - for (TABLE* table= thd->open_tables; table != NULL; table= table->next) - { - if (table->key_info == NULL || table->s->primary_key == MAX_KEY) - { - WSREP_DEBUG("No primary key found for table %s.%s", - table->s->db.str, table->s->table_name.str); - wsrep_override_error(thd, ER_LOCK_DEADLOCK); - return 1; - } - } - } - return 0; -} - -static inline bool wsrep_streaming_enabled(THD* thd) -{ - return (thd->wsrep_sr().fragment_size() > 0); -} - -/* - Return number of fragments successfully certified for the - current statement. - */ -static inline size_t wsrep_fragments_certified_for_stmt(THD* thd) -{ - return thd->wsrep_trx().fragments_certified_for_statement(); -} - -static inline int wsrep_start_transaction(THD* thd, wsrep_trx_id_t trx_id) -{ - if (thd->wsrep_cs().state() != wsrep::client_state::s_none) { - if (wsrep_is_active(thd) == false) - return thd->wsrep_cs().start_transaction(wsrep::transaction_id(trx_id)); - } - return 0; -} - -/**/ -static inline int wsrep_start_trx_if_not_started(THD* thd) -{ - int ret= 0; - DBUG_ASSERT(thd->wsrep_next_trx_id() != WSREP_UNDEFINED_TRX_ID); - DBUG_ASSERT(thd->wsrep_cs().mode() == Wsrep_client_state::m_local); - if (thd->wsrep_trx().active() == false) - { - ret= wsrep_start_transaction(thd, thd->wsrep_next_trx_id()); - } - return ret; -} - -/* - Called after each row operation. - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_after_row_internal(THD* thd) -{ - if (thd->wsrep_cs().state() != wsrep::client_state::s_none && - wsrep_thd_is_local(thd)) - { - if (wsrep_check_pk(thd)) - { - return 1; - } - else if (wsrep_streaming_enabled(thd)) - { - return thd->wsrep_cs().after_row(); - } - } - return 0; -} - -/* - Helper method to determine whether commit time hooks - should be run for the transaction. - - Commit hooks must be run in the following cases: - - The transaction is local and has generated write set and is committing. - - The transaction has been BF aborted - - Is running in high priority mode and is ordered. This can be replayer, - applier or storage access. - */ -static inline bool wsrep_run_commit_hook(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_run_commit_hook"); - DBUG_PRINT("wsrep", ("Is_active: %d is_real %d has_changes %d is_applying %d " - "is_ordered: %d", - wsrep_is_active(thd), wsrep_is_real(thd, all), - wsrep_has_changes(thd), wsrep_thd_is_applying(thd), - wsrep_is_ordered(thd))); - /* Is MST commit or autocommit? */ - bool ret= wsrep_is_active(thd) && wsrep_is_real(thd, all); - /* Do not commit if we are aborting */ - ret= ret && (thd->wsrep_trx().state() != wsrep::transaction::s_aborting); - if (ret && !(wsrep_has_changes(thd) || /* Has generated write set */ - /* Is high priority (replay, applier, storage) and the - transaction is scheduled for commit ordering */ - (wsrep_thd_is_applying(thd) && wsrep_is_ordered(thd)))) - { - mysql_mutex_lock(&thd->LOCK_thd_data); - DBUG_PRINT("wsrep", ("state: %s", - wsrep::to_c_string(thd->wsrep_trx().state()))); - /* Transaction is local but has no changes, the commit hooks will - be skipped and the wsrep transaction is terminated in - wsrep_commit_empty() */ - if (thd->wsrep_trx().state() == wsrep::transaction::s_executing) - { - ret= false; - } - mysql_mutex_unlock(&thd->LOCK_thd_data); - } - DBUG_PRINT("wsrep", ("return: %d", ret)); - DBUG_RETURN(ret); -} - -/* - Called before the transaction is prepared. - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_before_prepare(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_before_prepare"); - WSREP_DEBUG("wsrep_before_prepare: %d", wsrep_is_real(thd, all)); - int ret= 0; - DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); - if ((ret= thd->wsrep_cs().before_prepare()) == 0) - { - DBUG_ASSERT(!thd->wsrep_trx().ws_meta().gtid().is_undefined()); - wsrep_xid_init(&thd->wsrep_xid, - thd->wsrep_trx().ws_meta().gtid(), - wsrep_gtid_server.gtid()); - } - DBUG_RETURN(ret); -} - -/* - Called after the transaction has been prepared. - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_after_prepare(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_after_prepare"); - WSREP_DEBUG("wsrep_after_prepare: %d", wsrep_is_real(thd, all)); - DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); - int ret= thd->wsrep_cs().after_prepare(); - DBUG_ASSERT(ret == 0 || thd->wsrep_cs().current_error() || - thd->wsrep_cs().transaction().state() == wsrep::transaction::s_must_replay); - DBUG_RETURN(ret); -} - -/* - Called before the transaction is committed. - - This function must be called from both client and - applier contexts before commit. - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_before_commit(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_before_commit"); - WSREP_DEBUG("wsrep_before_commit: %d, %lld", - wsrep_is_real(thd, all), - (long long)wsrep_thd_trx_seqno(thd)); - int ret= 0; - DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); - if ((ret= thd->wsrep_cs().before_commit()) == 0) - { - DBUG_ASSERT(!thd->wsrep_trx().ws_meta().gtid().is_undefined()); - if (!thd->variables.gtid_seq_no && - (thd->wsrep_trx().ws_meta().flags() & wsrep::provider::flag::commit)) - { - uint64 seqno= 0; - if (thd->variables.wsrep_gtid_seq_no && - thd->variables.wsrep_gtid_seq_no > wsrep_gtid_server.seqno()) - { - seqno= thd->variables.wsrep_gtid_seq_no; - wsrep_gtid_server.seqno(thd->variables.wsrep_gtid_seq_no); - } - else - { - seqno= wsrep_gtid_server.seqno_inc(); - } - thd->variables.wsrep_gtid_seq_no= 0; - thd->wsrep_current_gtid_seqno= seqno; - if (mysql_bin_log.is_open() && wsrep_gtid_mode) - { - thd->variables.gtid_seq_no= seqno; - thd->variables.gtid_domain_id= wsrep_gtid_server.domain_id; - thd->variables.server_id= wsrep_gtid_server.server_id; - } - } - - wsrep_xid_init(&thd->wsrep_xid, - thd->wsrep_trx().ws_meta().gtid(), - wsrep_gtid_server.gtid()); - wsrep_register_for_group_commit(thd); - } - DBUG_RETURN(ret); -} - -/* - Called after the transaction has been ordered for commit. - - This function must be called from both client and - applier contexts after the commit has been ordered. - - @param thd Pointer to THD - @param all - @param err Error buffer in case of applying error - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_ordered_commit(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_ordered_commit"); - WSREP_DEBUG("wsrep_ordered_commit: %d", wsrep_is_real(thd, all)); - DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); - DBUG_RETURN(thd->wsrep_cs().ordered_commit()); -} - -/* - Called after the transaction has been committed. - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_after_commit(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_after_commit"); - WSREP_DEBUG("wsrep_after_commit: %d, %d, %lld, %d", - wsrep_is_real(thd, all), - wsrep_is_active(thd), - (long long)wsrep_thd_trx_seqno(thd), - wsrep_has_changes(thd)); - DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); - if (thd->internal_transaction()) - DBUG_RETURN(0); - int ret= 0; - if (thd->wsrep_trx().state() == wsrep::transaction::s_committing) - { - ret= thd->wsrep_cs().ordered_commit(); - } - wsrep_unregister_from_group_commit(thd); - thd->wsrep_xid.null(); - DBUG_RETURN(ret || thd->wsrep_cs().after_commit()); -} - -/* - Called before the transaction is rolled back. - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_before_rollback(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_before_rollback"); - int ret= 0; - if (wsrep_is_active(thd)) - { - if (!all && thd->in_active_multi_stmt_transaction()) - { - if (wsrep_emulate_bin_log) - { - wsrep_thd_binlog_stmt_rollback(thd); - } - - if (thd->wsrep_trx().is_streaming() && - !wsrep_stmt_rollback_is_safe(thd)) - { - /* Non-safe statement rollback during SR multi statement - transasction. Self abort the transaction, the actual rollback - and error handling will be done in after statement phase. */ - wsrep_thd_self_abort(thd); - ret= 0; - } - } - else if (wsrep_is_real(thd, all) && - thd->wsrep_trx().state() != wsrep::transaction::s_aborted) - { - /* Real transaction rolling back and wsrep abort not completed - yet */ - /* Reset XID so that it does not trigger writing serialization - history in InnoDB. This needs to be avoided because rollback - may happen out of order and replay may follow. */ - thd->wsrep_xid.null(); - ret= thd->wsrep_cs().before_rollback(); - } - } - DBUG_RETURN(ret); -} - -/* - Called after the transaction has been rolled back. - - Return zero on succes, non-zero on failure. - */ -static inline int wsrep_after_rollback(THD* thd, bool all) -{ - DBUG_ENTER("wsrep_after_rollback"); - DBUG_RETURN((wsrep_is_real(thd, all) && wsrep_is_active(thd) && - thd->wsrep_cs().transaction().state() != - wsrep::transaction::s_aborted) ? - thd->wsrep_cs().after_rollback() : 0); -} - -static inline int wsrep_before_statement(THD* thd) -{ - return (thd->wsrep_cs().state() != wsrep::client_state::s_none && - !thd->internal_transaction() ? - thd->wsrep_cs().before_statement() : 0); -} - -static inline -int wsrep_after_statement(THD* thd) -{ - DBUG_ENTER("wsrep_after_statement"); - DBUG_RETURN(thd->wsrep_cs().state() != wsrep::client_state::s_none && - !thd->internal_transaction() ? - thd->wsrep_cs().after_statement() : 0); -} - -static inline void wsrep_after_apply(THD* thd) -{ - DBUG_ASSERT(wsrep_thd_is_applying(thd)); - WSREP_DEBUG("wsrep_after_apply %lld", thd->thread_id); - if (!thd->internal_transaction()) - thd->wsrep_cs().after_applying(); -} - -static inline void wsrep_open(THD* thd) -{ - DBUG_ENTER("wsrep_open"); - if (WSREP(thd)) - { - thd->wsrep_cs().open(wsrep::client_id(thd->thread_id)); - thd->wsrep_cs().debug_log_level(wsrep_debug); - if (!thd->wsrep_applier && thd->variables.wsrep_trx_fragment_size) - { - thd->wsrep_cs().enable_streaming( - wsrep_fragment_unit(thd->variables.wsrep_trx_fragment_unit), - size_t(thd->variables.wsrep_trx_fragment_size)); - } - } - DBUG_VOID_RETURN; -} - -static inline void wsrep_close(THD* thd) -{ - DBUG_ENTER("wsrep_close"); - if (thd->wsrep_cs().state() != wsrep::client_state::s_none && - !thd->internal_transaction()) - { - thd->wsrep_cs().close(); - } - DBUG_VOID_RETURN; -} - -static inline void -wsrep_wait_rollback_complete_and_acquire_ownership(THD *thd) -{ - DBUG_ENTER("wsrep_wait_rollback_complete_and_acquire_ownership"); - if (thd->wsrep_cs().state() != wsrep::client_state::s_none && - !thd->internal_transaction()) - { - thd->wsrep_cs().wait_rollback_complete_and_acquire_ownership(); - } - DBUG_VOID_RETURN; -} - -static inline int wsrep_before_command(THD* thd) -{ - return (thd->wsrep_cs().state() != wsrep::client_state::s_none && - !thd->internal_transaction() ? - thd->wsrep_cs().before_command() : 0); -} -/* - Called after each command. - - Return zero on success, non-zero on failure. -*/ -static inline void wsrep_after_command_before_result(THD* thd) -{ - if (thd->wsrep_cs().state() != wsrep::client_state::s_none && - !thd->internal_transaction()) - { - thd->wsrep_cs().after_command_before_result(); - } -} - -static inline void wsrep_after_command_after_result(THD* thd) -{ - if (thd->wsrep_cs().state() != wsrep::client_state::s_none && - !thd->internal_transaction()) - { - thd->wsrep_cs().after_command_after_result(); - } -} - -static inline void wsrep_after_command_ignore_result(THD* thd) -{ - wsrep_after_command_before_result(thd); - DBUG_ASSERT(!thd->wsrep_cs().current_error()); - wsrep_after_command_after_result(thd); -} - -static inline enum wsrep::client_error wsrep_current_error(THD* thd) -{ - return thd->wsrep_cs().current_error(); -} - -static inline enum wsrep::provider::status -wsrep_current_error_status(THD* thd) -{ - return thd->wsrep_cs().current_error_status(); -} - -#endif /* WSREP_TRANS_OBSERVER */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_types.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_types.h deleted file mode 100644 index 9da00e3..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_types.h +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright 2018 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - -/* - Wsrep typedefs to better conform to coding style. - */ -#ifndef WSREP_TYPES_H -#define WSREP_TYPES_H - -#include "wsrep/seqno.hpp" -#include "wsrep/view.hpp" - -typedef wsrep::id Wsrep_id; -typedef wsrep::seqno Wsrep_seqno; -typedef wsrep::view Wsrep_view; - -#endif /* WSREP_TYPES_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_utils.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_utils.h deleted file mode 100644 index 974c623..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_utils.h +++ /dev/null @@ -1,442 +0,0 @@ -/* Copyright (C) 2013-2015 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ - -#ifndef WSREP_UTILS_H -#define WSREP_UTILS_H - -#include "wsrep_priv.h" -#include "wsrep_mysqld.h" - -unsigned int wsrep_check_ip (const char* const addr, bool *is_ipv6); -size_t wsrep_guess_ip (char* buf, size_t buf_len); -namespace wsp { -class node_status -{ -public: - node_status() : status(wsrep::server_state::s_disconnected) {} - void set(enum wsrep::server_state::state new_status, - const wsrep::view* view= 0) - { - if (status != new_status || 0 != view) - { - wsrep_notify_status(new_status, view); - status= new_status; - } - } - enum wsrep::server_state::state get() const { return status; } -private: - enum wsrep::server_state::state status; -}; -} /* namespace wsp */ - -extern wsp::node_status local_status; - -/* returns the length of the host part of the address string */ -size_t wsrep_host_len(const char* addr, size_t addr_len); - -namespace wsp { - -class Address { -public: - Address() - : m_address_len(0), m_family(UNSPEC), m_port(0), m_valid(false) - { - memset(m_address, 0, sizeof(m_address)); - } - Address(const char *addr_in) - : m_address_len(0), m_family(UNSPEC), m_port(0), m_valid(false) - { - memset(m_address, 0, sizeof(m_address)); - parse_addr(addr_in); - } - bool is_valid() { return m_valid; } - bool is_ipv6() { return (m_family == INET6); } - - const char* get_address() { return m_address; } - size_t get_address_len() { return m_address_len; } - int get_port() { return m_port; } - -private: - enum family { - UNSPEC= 0, - INET, /* IPv4 */ - INET6, /* IPv6 */ - }; - - char m_address[256]; - size_t m_address_len; - family m_family; - int m_port; - bool m_valid; - - void parse_addr(const char *addr_in) { - const char *start; - const char *end; - const char *port; - const char* open_bracket= strchr(const_cast(addr_in), '['); - const char* close_bracket= strchr(const_cast(addr_in), ']'); - const char* colon= strchr(const_cast(addr_in), ':'); - const char* dot= strchr(const_cast(addr_in), '.'); - - int cc= colon_count(addr_in); - - if (open_bracket != NULL || - dot == NULL || - (colon != NULL && (dot == NULL || colon < dot))) - { - // This could be an IPv6 address or a hostname - if (open_bracket != NULL) { - /* Sanity check: Address with '[' must include ']' */ - if (close_bracket == NULL && - open_bracket < close_bracket) /* Error: malformed address */ - { - m_valid= false; - return; - } - - start= open_bracket + 1; - end= close_bracket; - - /* Check for port */ - port= strchr(close_bracket, ':'); - if ((port != NULL) && parse_port(port + 1)) - { - return; /* Error: invalid port */ - } - m_family= INET6; - } - else - { - switch (cc) { - case 0: - /* Hostname with no port */ - start= addr_in; - end= addr_in + strlen(addr_in); - break; - case 1: - /* Hostname with port (host:port) */ - start= addr_in; - end= colon; - if (parse_port(colon + 1)) - return; /* Error: invalid port */ - break; - default: - /* IPv6 address */ - start= addr_in; - end= addr_in + strlen(addr_in); - m_family= INET6; - break; - } - } - } else { /* IPv4 address or hostname */ - start= addr_in; - if (colon != NULL) { /* Port */ - end= colon; - if (parse_port(colon + 1)) - return; /* Error: invalid port */ - } else { - end= addr_in + strlen(addr_in); - } - } - - size_t len= end - start; - - /* Safety */ - if (len >= sizeof(m_address)) - { - // The supplied address is too large to fit into the internal buffer. - m_valid= false; - return; - } - - memcpy(m_address, start, len); - m_address[len]= '\0'; - m_address_len= ++ len; - m_valid= true; - return; - } - - int colon_count(const char *addr) { - int count= 0, i= 0; - - while(addr[i] != '\0') - { - if (addr[i] == ':') ++count; - ++ i; - } - return count; - } - - bool parse_port(const char *port) { - errno= 0; /* Reset the errno */ - m_port= strtol(port, NULL, 10); - if (errno == EINVAL || errno == ERANGE) - { - m_port= 0; /* Error: invalid port */ - m_valid= false; - return true; - } - return false; - } -}; - -class Config_state -{ -public: - Config_state() : view_(), status_(wsrep::server_state::s_disconnected) - {} - - void set(const wsrep::view& view) - { - wsrep_notify_status(status_, &view); - - lock(); - view_= view; - unlock(); - } - - void set(enum wsrep::server_state::state status) - { - wsrep_notify_status(status); - - lock(); - status_= status; - unlock(); - } - - const wsrep::view& get_view_info() const - { - return view_; - } - - enum wsrep::server_state::state get_status() const - { - return status_; - } - - int lock() - { - return mysql_mutex_lock(&LOCK_wsrep_config_state); - } - - int unlock() - { - return mysql_mutex_unlock(&LOCK_wsrep_config_state); - } - -private: - wsrep::view view_; - enum wsrep::server_state::state status_; -}; - -} /* namespace wsp */ - -extern wsp::Config_state *wsrep_config_state; - -namespace wsp { -/* a class to manage env vars array */ -class env -{ -private: - size_t len_; - char** env_; - int errno_; - bool ctor_common(char** e); - void dtor(); - env& operator =(env); -public: - explicit env(char** env); - explicit env(const env&); - ~env(); - int append(const char* var); /* add a new env. var */ - int error() const { return errno_; } - char** operator()() { return env_; } -}; - -/* A small class to run external programs. */ -class process -{ -private: - const char* const str_; - FILE* io_; - int err_; - pid_t pid_; - -public: -/*! @arg type is a pointer to a null-terminated string which must contain - either the letter 'r' for reading or the letter 'w' for writing. - @arg env optional null-terminated vector of environment variables - */ - process (const char* cmd, const char* type, char** env); - ~process (); - - FILE* pipe () { return io_; } - int error() { return err_; } - int wait (); - const char* cmd() { return str_; } -}; - -class thd -{ - class thd_init - { - public: - thd_init() { my_thread_init(); } - ~thd_init() { my_thread_end(); } - } - init; - - thd (const thd&); - thd& operator= (const thd&); - -public: - - thd(my_bool wsrep_on, bool system_thread=false); - ~thd(); - THD* const ptr; -}; - -class string -{ -public: - string() : string_(0) {} - explicit string(size_t s) : string_(static_cast(malloc(s))) {} - char* operator()() { return string_; } - void set(char* str) { if (string_) free (string_); string_= str; } - ~string() { set (0); } -private: - char* string_; -}; - -/* scope level lock */ -class auto_lock -{ -public: - auto_lock(mysql_mutex_t* m) : m_(m) { mysql_mutex_lock(m_); } - ~auto_lock() { mysql_mutex_unlock(m_); } -private: - mysql_mutex_t& operator =(mysql_mutex_t&); - mysql_mutex_t* const m_; -}; - -#ifdef REMOVED -class lock -{ - pthread_mutex_t* const mtx_; - -public: - - lock (pthread_mutex_t* mtx) : mtx_(mtx) - { - int err= pthread_mutex_lock (mtx_); - - if (err) - { - WSREP_ERROR("Mutex lock failed: %s", strerror(err)); - abort(); - } - } - - virtual ~lock () - { - int err= pthread_mutex_unlock (mtx_); - - if (err) - { - WSREP_ERROR("Mutex unlock failed: %s", strerror(err)); - abort(); - } - } - - inline void wait (pthread_cond_t* cond) - { - pthread_cond_wait (cond, mtx_); - } - -private: - - lock (const lock&); - lock& operator=(const lock&); - -}; - -class monitor -{ - int mutable refcnt; - pthread_mutex_t mutable mtx; - pthread_cond_t mutable cond; - -public: - - monitor() : refcnt(0) - { - pthread_mutex_init (&mtx, NULL); - pthread_cond_init (&cond, NULL); - } - - ~monitor() - { - pthread_mutex_destroy (&mtx); - pthread_cond_destroy (&cond); - } - - void enter() const - { - lock l(&mtx); - - while (refcnt) - { - l.wait(&cond); - } - refcnt++; - } - - void leave() const - { - lock l(&mtx); - - refcnt--; - if (refcnt == 0) - { - pthread_cond_signal (&cond); - } - } - -private: - - monitor (const monitor&); - monitor& operator= (const monitor&); -}; - -class critical -{ - const monitor& mon; - -public: - - critical(const monitor& m) : mon(m) { mon.enter(); } - - ~critical() { mon.leave(); } - -private: - - critical (const critical&); - critical& operator= (const critical&); -}; -#endif - -} // namespace wsrep - -#endif /* WSREP_UTILS_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_var.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_var.h deleted file mode 100644 index 810ed4f..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_var.h +++ /dev/null @@ -1,115 +0,0 @@ -/* Copyright (C) 2013 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ - -#ifndef WSREP_VAR_H -#define WSREP_VAR_H - -#include - -#ifdef WITH_WSREP - -#define WSREP_CLUSTER_NAME "my_wsrep_cluster" -#define WSREP_NODE_INCOMING_AUTO "AUTO" -#define WSREP_START_POSITION_ZERO "00000000-0000-0000-0000-000000000000:-1" -#define WSREP_START_POSITION_ZERO_GTID "00000000-0000-0000-0000-000000000000:-1,0-0-0" - -// MySQL variables funcs - -#include "sql_priv.h" -#include -#include - -class sys_var; -class set_var; -class THD; - -int wsrep_init_vars(); - -#define CHECK_ARGS (sys_var *self, THD* thd, set_var *var) -#define UPDATE_ARGS (sys_var *self, THD* thd, enum_var_type type) -#define DEFAULT_ARGS (THD* thd, enum_var_type var_type) -#define INIT_ARGS (const char* opt) - -extern bool wsrep_causal_reads_update UPDATE_ARGS; -extern bool wsrep_on_check CHECK_ARGS; -extern bool wsrep_on_update UPDATE_ARGS; -extern bool wsrep_sync_wait_update UPDATE_ARGS; -extern bool wsrep_start_position_check CHECK_ARGS; -extern bool wsrep_start_position_update UPDATE_ARGS; -extern bool wsrep_start_position_init INIT_ARGS; - -extern bool wsrep_provider_check CHECK_ARGS; -extern bool wsrep_provider_update UPDATE_ARGS; -extern void wsrep_provider_init INIT_ARGS; - -extern bool wsrep_provider_options_check CHECK_ARGS; -extern bool wsrep_provider_options_update UPDATE_ARGS; -extern void wsrep_provider_options_init INIT_ARGS; - -extern bool wsrep_cluster_address_check CHECK_ARGS; -extern bool wsrep_cluster_address_update UPDATE_ARGS; -extern void wsrep_cluster_address_init INIT_ARGS; - -extern bool wsrep_cluster_name_check CHECK_ARGS; -extern bool wsrep_cluster_name_update UPDATE_ARGS; - -extern bool wsrep_node_name_check CHECK_ARGS; -extern bool wsrep_node_name_update UPDATE_ARGS; - -extern bool wsrep_node_address_check CHECK_ARGS; -extern bool wsrep_node_address_update UPDATE_ARGS; -extern void wsrep_node_address_init INIT_ARGS; - -extern bool wsrep_sst_method_check CHECK_ARGS; -extern bool wsrep_sst_method_update UPDATE_ARGS; -extern void wsrep_sst_method_init INIT_ARGS; - -extern bool wsrep_sst_receive_address_check CHECK_ARGS; -extern bool wsrep_sst_receive_address_update UPDATE_ARGS; - -extern bool wsrep_sst_auth_check CHECK_ARGS; -extern bool wsrep_sst_auth_update UPDATE_ARGS; - -extern bool wsrep_sst_donor_check CHECK_ARGS; -extern bool wsrep_sst_donor_update UPDATE_ARGS; - -extern bool wsrep_slave_threads_check CHECK_ARGS; -extern bool wsrep_slave_threads_update UPDATE_ARGS; - -extern bool wsrep_desync_check CHECK_ARGS; -extern bool wsrep_desync_update UPDATE_ARGS; - -extern bool wsrep_trx_fragment_size_check CHECK_ARGS; -extern bool wsrep_trx_fragment_size_update UPDATE_ARGS; - -extern bool wsrep_trx_fragment_unit_update UPDATE_ARGS; - -extern bool wsrep_max_ws_size_check CHECK_ARGS; -extern bool wsrep_max_ws_size_update UPDATE_ARGS; - -extern bool wsrep_reject_queries_update UPDATE_ARGS; - -extern bool wsrep_debug_update UPDATE_ARGS; - -extern bool wsrep_gtid_seq_no_check CHECK_ARGS; - -#else /* WITH_WSREP */ - -#define wsrep_provider_init(X) -#define wsrep_init_vars() (0) -#define wsrep_start_position_init(X) - -#endif /* WITH_WSREP */ -#endif /* WSREP_VAR_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_xid.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_xid.h deleted file mode 100644 index 45ba6ff..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/wsrep_xid.h +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright (C) 2015 Codership Oy - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ - -#ifndef WSREP_XID_H -#define WSREP_XID_H - -#include - -#ifdef WITH_WSREP - -#include "wsrep_mysqld.h" -#include "wsrep/gtid.hpp" -#include "handler.h" // XID typedef - -void wsrep_xid_init(xid_t*, const wsrep::gtid&, const wsrep_server_gtid_t&); -const wsrep::id& wsrep_xid_uuid(const XID&); -wsrep::seqno wsrep_xid_seqno(const XID&); - -template T wsrep_get_SE_checkpoint(); -bool wsrep_set_SE_checkpoint(const wsrep::gtid& gtid, const wsrep_server_gtid_t&); -//void wsrep_get_SE_checkpoint(XID&); /* uncomment if needed */ -//void wsrep_set_SE_checkpoint(XID&); /* uncomment if needed */ - -void wsrep_sort_xid_array(XID *array, int len); - -#endif /* WITH_WSREP */ -#endif /* WSREP_UTILS_H */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/private/xa.h b/VCMP-LUA/modules/mariadb/include/mysql/server/private/xa.h deleted file mode 100644 index 0b2d069..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/private/xa.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef XA_INCLUDED -#define XA_INCLUDED -/* - Copyright (c) 2000, 2016, Oracle and/or its affiliates. - Copyright (c) 2009, 2019, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -*/ - -class XID_cache_element; -enum xa_states -{ - XA_ACTIVE= 0, - XA_IDLE, - XA_PREPARED, - XA_ROLLBACK_ONLY, - XA_NO_STATE -}; - -struct XID_STATE { - XID_cache_element *xid_cache_element; - - bool check_has_uncommitted_xa() const; - bool is_explicit_XA() const { return xid_cache_element != 0; } - void set_error(uint error); - void er_xaer_rmfail() const; - XID *get_xid() const; - enum xa_states get_state_code() const; -}; - -void xid_cache_init(void); -void xid_cache_free(void); -bool xid_cache_insert(XID *xid); -bool xid_cache_insert(THD *thd, XID_STATE *xid_state, XID *xid); -void xid_cache_delete(THD *thd, XID_STATE *xid_state); - -bool trans_xa_start(THD *thd); -bool trans_xa_end(THD *thd); -bool trans_xa_prepare(THD *thd); -bool trans_xa_commit(THD *thd); -bool trans_xa_rollback(THD *thd); -bool trans_xa_detach(THD *thd); -bool mysql_xa_recover(THD *thd); - -#endif /* XA_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/sql_common.h b/VCMP-LUA/modules/mariadb/include/mysql/server/sql_common.h deleted file mode 100644 index 9836d0c..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/sql_common.h +++ /dev/null @@ -1,138 +0,0 @@ -#ifndef SQL_COMMON_INCLUDED -#define SQL_COMMON_INCLUDED -/* Copyright (c) 2003, 2018, Oracle and/or its affiliates. - Copyright (c) 2010, 2018, MariaDB - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -extern const char *unknown_sqlstate; -extern const char *cant_connect_sqlstate; -extern const char *not_error_sqlstate; - - -struct mysql_async_context; - -struct st_mysql_options_extention { - char *plugin_dir; - char *default_auth; - char *ssl_crl; /* PEM CRL file */ - char *ssl_crlpath; /* PEM directory of CRL-s? */ - void (*report_progress)(const MYSQL *mysql, - unsigned int stage, - unsigned int max_stage, - double progress, - const char *proc_info, - uint proc_info_length); - struct mysql_async_context *async_context; - HASH connection_attributes; - size_t connection_attributes_length; -}; - -typedef struct st_mysql_methods -{ - my_bool (*read_query_result)(MYSQL *mysql); - my_bool (*advanced_command)(MYSQL *mysql, - enum enum_server_command command, - const unsigned char *header, - unsigned long header_length, - const unsigned char *arg, - unsigned long arg_length, - my_bool skip_check, - MYSQL_STMT *stmt); - MYSQL_DATA *(*read_rows)(MYSQL *mysql,MYSQL_FIELD *mysql_fields, - unsigned int fields); - MYSQL_RES * (*use_result)(MYSQL *mysql); - void (*fetch_lengths)(unsigned long *to, - MYSQL_ROW column, unsigned int field_count); - void (*flush_use_result)(MYSQL *mysql, my_bool flush_all_results); - int (*read_change_user_result)(MYSQL *mysql); -#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) - MYSQL_FIELD * (*list_fields)(MYSQL *mysql); - my_bool (*read_prepare_result)(MYSQL *mysql, MYSQL_STMT *stmt); - int (*stmt_execute)(MYSQL_STMT *stmt); - int (*read_binary_rows)(MYSQL_STMT *stmt); - int (*unbuffered_fetch)(MYSQL *mysql, char **row); - void (*free_embedded_thd)(MYSQL *mysql); - const char *(*read_statistics)(MYSQL *mysql); - my_bool (*next_result)(MYSQL *mysql); - int (*read_rows_from_cursor)(MYSQL_STMT *stmt); -#endif -} MYSQL_METHODS; - -#ifdef LIBMARIADB -#define simple_command(mysql, command, arg, length, skip_check) ma_simple_command(mysql, command, (char *)arg, length, skip_check, NULL) -#else -#define simple_command(mysql, command, arg, length, skip_check) \ - (*(mysql)->methods->advanced_command)(mysql, command, 0, \ - 0, arg, length, skip_check, NULL) -#endif -#define stmt_command(mysql, command, arg, length, stmt) \ - (*(mysql)->methods->advanced_command)(mysql, command, 0, \ - 0, arg, length, 1, stmt) - -extern CHARSET_INFO *default_client_charset_info; -MYSQL_FIELD *unpack_fields(MYSQL *mysql, MYSQL_DATA *data,MEM_ROOT *alloc, - uint fields, my_bool default_value, - uint server_capabilities); -void free_rows(MYSQL_DATA *cur); -void free_old_query(MYSQL *mysql); -void end_server(MYSQL *mysql); -my_bool mysql_reconnect(MYSQL *mysql); -void mysql_read_default_options(struct st_mysql_options *options, - const char *filename,const char *group); -my_bool -cli_advanced_command(MYSQL *mysql, enum enum_server_command command, - const unsigned char *header, ulong header_length, - const unsigned char *arg, ulong arg_length, - my_bool skip_check, MYSQL_STMT *stmt); -unsigned long cli_safe_read(MYSQL *mysql); -unsigned long cli_safe_read_reallen(MYSQL *mysql, ulong* reallen); -void net_clear_error(NET *net); -void set_stmt_errmsg(MYSQL_STMT *stmt, NET *net); -void set_stmt_error(MYSQL_STMT *stmt, int errcode, const char *sqlstate, - const char *err); -void set_mysql_error(MYSQL *mysql, int errcode, const char *sqlstate); -void set_mysql_extended_error(MYSQL *mysql, int errcode, const char *sqlstate, - const char *format, ...); - -/* client side of the pluggable authentication */ -struct st_vio; -struct st_plugin_vio_info; -void mpvio_info(struct st_vio *vio, struct st_plugin_vio_info *info); -int run_plugin_auth(MYSQL *mysql, char *data, uint data_len, - const char *data_plugin, const char *db); -int mysql_client_plugin_init(); -void mysql_client_plugin_deinit(); -struct st_mysql_client_plugin; -extern struct st_mysql_client_plugin *mysql_client_builtins[]; -uchar * send_client_connect_attrs(MYSQL *mysql, uchar *buf); - -/* Non-blocking client API. */ -void my_context_install_suspend_resume_hook(struct mysql_async_context *b, - void (*)(my_bool, void *), void *); - -#ifdef __cplusplus -} -#endif - -#define protocol_41(A) ((A)->server_capabilities & CLIENT_PROTOCOL_41) - -#endif /* SQL_COMMON_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/sql_state.h b/VCMP-LUA/modules/mariadb/include/mysql/server/sql_state.h deleted file mode 100644 index d015970..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/sql_state.h +++ /dev/null @@ -1,255 +0,0 @@ -/* Autogenerated file, please don't edit */ - -{ ER_DUP_KEY ,"23000", "" }, -{ ER_OUTOFMEMORY ,"HY001", "S1001" }, -{ ER_OUT_OF_SORTMEMORY ,"HY001", "S1001" }, -{ ER_CON_COUNT_ERROR ,"08004", "" }, -{ ER_BAD_HOST_ERROR ,"08S01", "" }, -{ ER_HANDSHAKE_ERROR ,"08S01", "" }, -{ ER_DBACCESS_DENIED_ERROR ,"42000", "" }, -{ ER_ACCESS_DENIED_ERROR ,"28000", "" }, -{ ER_NO_DB_ERROR ,"3D000", "" }, -{ ER_UNKNOWN_COM_ERROR ,"08S01", "" }, -{ ER_BAD_NULL_ERROR ,"23000", "" }, -{ ER_BAD_DB_ERROR ,"42000", "" }, -{ ER_TABLE_EXISTS_ERROR ,"42S01", "" }, -{ ER_BAD_TABLE_ERROR ,"42S02", "" }, -{ ER_NON_UNIQ_ERROR ,"23000", "" }, -{ ER_SERVER_SHUTDOWN ,"08S01", "" }, -{ ER_BAD_FIELD_ERROR ,"42S22", "S0022" }, -{ ER_WRONG_FIELD_WITH_GROUP ,"42000", "S1009" }, -{ ER_WRONG_GROUP_FIELD ,"42000", "S1009" }, -{ ER_WRONG_SUM_SELECT ,"42000", "S1009" }, -{ ER_WRONG_VALUE_COUNT ,"21S01", "" }, -{ ER_TOO_LONG_IDENT ,"42000", "S1009" }, -{ ER_DUP_FIELDNAME ,"42S21", "S1009" }, -{ ER_DUP_KEYNAME ,"42000", "S1009" }, -{ ER_DUP_ENTRY ,"23000", "S1009" }, -{ ER_WRONG_FIELD_SPEC ,"42000", "S1009" }, -{ ER_PARSE_ERROR ,"42000", "s1009" }, -{ ER_EMPTY_QUERY ,"42000", "" }, -{ ER_NONUNIQ_TABLE ,"42000", "S1009" }, -{ ER_INVALID_DEFAULT ,"42000", "S1009" }, -{ ER_MULTIPLE_PRI_KEY ,"42000", "S1009" }, -{ ER_TOO_MANY_KEYS ,"42000", "S1009" }, -{ ER_TOO_MANY_KEY_PARTS ,"42000", "S1009" }, -{ ER_TOO_LONG_KEY ,"42000", "S1009" }, -{ ER_KEY_COLUMN_DOES_NOT_EXITS ,"42000", "S1009" }, -{ ER_BLOB_USED_AS_KEY ,"42000", "S1009" }, -{ ER_TOO_BIG_FIELDLENGTH ,"42000", "S1009" }, -{ ER_WRONG_AUTO_KEY ,"42000", "S1009" }, -{ ER_FORCING_CLOSE ,"08S01", "" }, -{ ER_IPSOCK_ERROR ,"08S01", "" }, -{ ER_NO_SUCH_INDEX ,"42S12", "S1009" }, -{ ER_WRONG_FIELD_TERMINATORS ,"42000", "S1009" }, -{ ER_BLOBS_AND_NO_TERMINATED ,"42000", "S1009" }, -{ ER_CANT_REMOVE_ALL_FIELDS ,"42000", "" }, -{ ER_CANT_DROP_FIELD_OR_KEY ,"42000", "" }, -{ ER_WRONG_DB_NAME ,"42000", "" }, -{ ER_WRONG_TABLE_NAME ,"42000", "" }, -{ ER_TOO_BIG_SELECT ,"42000", "" }, -{ ER_UNKNOWN_PROCEDURE ,"42000", "" }, -{ ER_WRONG_PARAMCOUNT_TO_PROCEDURE ,"42000", "" }, -{ ER_UNKNOWN_TABLE ,"42S02", "" }, -{ ER_FIELD_SPECIFIED_TWICE ,"42000", "" }, -{ ER_UNSUPPORTED_EXTENSION ,"42000", "" }, -{ ER_TABLE_MUST_HAVE_COLUMNS ,"42000", "" }, -{ ER_UNKNOWN_CHARACTER_SET ,"42000", "" }, -{ ER_TOO_BIG_ROWSIZE ,"42000", "" }, -{ ER_WRONG_OUTER_JOIN ,"42000", "" }, -{ ER_NULL_COLUMN_IN_INDEX ,"42000", "" }, -{ ER_PASSWORD_ANONYMOUS_USER ,"42000", "" }, -{ ER_PASSWORD_NOT_ALLOWED ,"42000", "" }, -{ ER_PASSWORD_NO_MATCH ,"28000", "" }, -{ ER_WRONG_VALUE_COUNT_ON_ROW ,"21S01", "" }, -{ ER_INVALID_USE_OF_NULL ,"22004", "" }, -{ ER_REGEXP_ERROR ,"42000", "" }, -{ ER_MIX_OF_GROUP_FUNC_AND_FIELDS ,"42000", "" }, -{ ER_NONEXISTING_GRANT ,"42000", "" }, -{ ER_TABLEACCESS_DENIED_ERROR ,"42000", "" }, -{ ER_COLUMNACCESS_DENIED_ERROR ,"42000", "" }, -{ ER_ILLEGAL_GRANT_FOR_TABLE ,"42000", "" }, -{ ER_GRANT_WRONG_HOST_OR_USER ,"42000", "" }, -{ ER_NO_SUCH_TABLE ,"42S02", "" }, -{ ER_NONEXISTING_TABLE_GRANT ,"42000", "" }, -{ ER_NOT_ALLOWED_COMMAND ,"42000", "" }, -{ ER_SYNTAX_ERROR ,"42000", "" }, -{ ER_ABORTING_CONNECTION ,"08S01", "" }, -{ ER_NET_PACKET_TOO_LARGE ,"08S01", "" }, -{ ER_NET_READ_ERROR_FROM_PIPE ,"08S01", "" }, -{ ER_NET_FCNTL_ERROR ,"08S01", "" }, -{ ER_NET_PACKETS_OUT_OF_ORDER ,"08S01", "" }, -{ ER_NET_UNCOMPRESS_ERROR ,"08S01", "" }, -{ ER_NET_READ_ERROR ,"08S01", "" }, -{ ER_NET_READ_INTERRUPTED ,"08S01", "" }, -{ ER_NET_ERROR_ON_WRITE ,"08S01", "" }, -{ ER_NET_WRITE_INTERRUPTED ,"08S01", "" }, -{ ER_TOO_LONG_STRING ,"42000", "" }, -{ ER_TABLE_CANT_HANDLE_BLOB ,"42000", "" }, -{ ER_TABLE_CANT_HANDLE_AUTO_INCREMENT ,"42000", "" }, -{ ER_WRONG_COLUMN_NAME ,"42000", "" }, -{ ER_WRONG_KEY_COLUMN ,"42000", "" }, -{ ER_DUP_UNIQUE ,"23000", "" }, -{ ER_BLOB_KEY_WITHOUT_LENGTH ,"42000", "" }, -{ ER_PRIMARY_CANT_HAVE_NULL ,"42000", "" }, -{ ER_TOO_MANY_ROWS ,"42000", "" }, -{ ER_REQUIRES_PRIMARY_KEY ,"42000", "" }, -{ ER_KEY_DOES_NOT_EXISTS ,"42000", "S1009" }, -{ ER_CHECK_NO_SUCH_TABLE ,"42000", "" }, -{ ER_CHECK_NOT_IMPLEMENTED ,"42000", "" }, -{ ER_CANT_DO_THIS_DURING_AN_TRANSACTION ,"25000", "" }, -{ ER_NEW_ABORTING_CONNECTION ,"08S01", "" }, -{ ER_MASTER_NET_READ ,"08S01", "" }, -{ ER_MASTER_NET_WRITE ,"08S01", "" }, -{ ER_TOO_MANY_USER_CONNECTIONS ,"42000", "" }, -{ ER_READ_ONLY_TRANSACTION ,"25000", "" }, -{ ER_NO_PERMISSION_TO_CREATE_USER ,"42000", "" }, -{ ER_LOCK_DEADLOCK ,"40001", "" }, -{ ER_NO_REFERENCED_ROW ,"23000", "" }, -{ ER_ROW_IS_REFERENCED ,"23000", "" }, -{ ER_CONNECT_TO_MASTER ,"08S01", "" }, -{ ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT ,"21000", "" }, -{ ER_USER_LIMIT_REACHED ,"42000", "" }, -{ ER_SPECIFIC_ACCESS_DENIED_ERROR ,"42000", "" }, -{ ER_NO_DEFAULT ,"42000", "" }, -{ ER_WRONG_VALUE_FOR_VAR ,"42000", "" }, -{ ER_WRONG_TYPE_FOR_VAR ,"42000", "" }, -{ ER_CANT_USE_OPTION_HERE ,"42000", "" }, -{ ER_NOT_SUPPORTED_YET ,"42000", "" }, -{ ER_WRONG_FK_DEF ,"42000", "" }, -{ ER_OPERAND_COLUMNS ,"21000", "" }, -{ ER_SUBQUERY_NO_1_ROW ,"21000", "" }, -{ ER_ILLEGAL_REFERENCE ,"42S22", "" }, -{ ER_DERIVED_MUST_HAVE_ALIAS ,"42000", "" }, -{ ER_SELECT_REDUCED ,"01000", "" }, -{ ER_TABLENAME_NOT_ALLOWED_HERE ,"42000", "" }, -{ ER_NOT_SUPPORTED_AUTH_MODE ,"08004", "" }, -{ ER_SPATIAL_CANT_HAVE_NULL ,"42000", "" }, -{ ER_COLLATION_CHARSET_MISMATCH ,"42000", "" }, -{ ER_WARN_TOO_FEW_RECORDS ,"01000", "" }, -{ ER_WARN_TOO_MANY_RECORDS ,"01000", "" }, -{ ER_WARN_NULL_TO_NOTNULL ,"22004", "" }, -{ ER_WARN_DATA_OUT_OF_RANGE ,"22003", "" }, -{ WARN_DATA_TRUNCATED ,"01000", "" }, -{ ER_WRONG_NAME_FOR_INDEX ,"42000", "" }, -{ ER_WRONG_NAME_FOR_CATALOG ,"42000", "" }, -{ ER_UNKNOWN_STORAGE_ENGINE ,"42000", "" }, -{ ER_TRUNCATED_WRONG_VALUE ,"22007", "" }, -{ ER_SP_NO_RECURSIVE_CREATE ,"2F003", "" }, -{ ER_SP_ALREADY_EXISTS ,"42000", "" }, -{ ER_SP_DOES_NOT_EXIST ,"42000", "" }, -{ ER_SP_LILABEL_MISMATCH ,"42000", "" }, -{ ER_SP_LABEL_REDEFINE ,"42000", "" }, -{ ER_SP_LABEL_MISMATCH ,"42000", "" }, -{ ER_SP_UNINIT_VAR ,"01000", "" }, -{ ER_SP_BADSELECT ,"0A000", "" }, -{ ER_SP_BADRETURN ,"42000", "" }, -{ ER_SP_BADSTATEMENT ,"0A000", "" }, -{ ER_UPDATE_LOG_DEPRECATED_IGNORED ,"42000", "" }, -{ ER_UPDATE_LOG_DEPRECATED_TRANSLATED ,"42000", "" }, -{ ER_QUERY_INTERRUPTED ,"70100", "" }, -{ ER_SP_WRONG_NO_OF_ARGS ,"42000", "" }, -{ ER_SP_COND_MISMATCH ,"42000", "" }, -{ ER_SP_NORETURN ,"42000", "" }, -{ ER_SP_NORETURNEND ,"2F005", "" }, -{ ER_SP_BAD_CURSOR_QUERY ,"42000", "" }, -{ ER_SP_BAD_CURSOR_SELECT ,"42000", "" }, -{ ER_SP_CURSOR_MISMATCH ,"42000", "" }, -{ ER_SP_CURSOR_ALREADY_OPEN ,"24000", "" }, -{ ER_SP_CURSOR_NOT_OPEN ,"24000", "" }, -{ ER_SP_UNDECLARED_VAR ,"42000", "" }, -{ ER_SP_FETCH_NO_DATA ,"02000", "" }, -{ ER_SP_DUP_PARAM ,"42000", "" }, -{ ER_SP_DUP_VAR ,"42000", "" }, -{ ER_SP_DUP_COND ,"42000", "" }, -{ ER_SP_DUP_CURS ,"42000", "" }, -{ ER_SP_SUBSELECT_NYI ,"0A000", "" }, -{ ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG ,"0A000", "" }, -{ ER_SP_VARCOND_AFTER_CURSHNDLR ,"42000", "" }, -{ ER_SP_CURSOR_AFTER_HANDLER ,"42000", "" }, -{ ER_SP_CASE_NOT_FOUND ,"20000", "" }, -{ ER_DIVISION_BY_ZERO ,"22012", "" }, -{ ER_TRUNCATED_WRONG_VALUE_FOR_FIELD ,"22007", "" }, -{ ER_ILLEGAL_VALUE_FOR_TYPE ,"22007", "" }, -{ ER_VIEW_CHECK_FAILED ,"44000", "" }, -{ ER_PROCACCESS_DENIED_ERROR ,"42000", "" }, -{ ER_XAER_NOTA ,"XAE04", "" }, -{ ER_XAER_INVAL ,"XAE05", "" }, -{ ER_XAER_RMFAIL ,"XAE07", "" }, -{ ER_XAER_OUTSIDE ,"XAE09", "" }, -{ ER_XAER_RMERR ,"XAE03", "" }, -{ ER_XA_RBROLLBACK ,"XA100", "" }, -{ ER_NONEXISTING_PROC_GRANT ,"42000", "" }, -{ ER_DATA_TOO_LONG ,"22001", "" }, -{ ER_SP_BAD_SQLSTATE ,"42000", "" }, -{ ER_CANT_CREATE_USER_WITH_GRANT ,"42000", "" }, -{ ER_SP_DUP_HANDLER ,"42000", "" }, -{ ER_SP_NOT_VAR_ARG ,"42000", "" }, -{ ER_SP_NO_RETSET ,"0A000", "" }, -{ ER_CANT_CREATE_GEOMETRY_OBJECT ,"22003", "" }, -{ ER_TOO_BIG_SCALE ,"42000", "S1009" }, -{ ER_TOO_BIG_PRECISION ,"42000", "S1009" }, -{ ER_M_BIGGER_THAN_D ,"42000", "S1009" }, -{ ER_TOO_LONG_BODY ,"42000", "S1009" }, -{ ER_TOO_BIG_DISPLAYWIDTH ,"42000", "S1009" }, -{ ER_XAER_DUPID ,"XAE08", "" }, -{ ER_DATETIME_FUNCTION_OVERFLOW ,"22008", "" }, -{ ER_MALFORMED_DEFINER ,"0L000", "" }, -{ ER_ROW_IS_REFERENCED_2 ,"23000", "" }, -{ ER_NO_REFERENCED_ROW_2 ,"23000", "" }, -{ ER_SP_BAD_VAR_SHADOW ,"42000", "" }, -{ ER_SP_WRONG_NAME ,"42000", "" }, -{ ER_SP_NO_AGGREGATE ,"42000", "" }, -{ ER_MAX_PREPARED_STMT_COUNT_REACHED ,"42000", "" }, -{ ER_NON_GROUPING_FIELD_USED ,"42000", "" }, -{ ER_CANT_CHANGE_TX_CHARACTERISTICS ,"25001", "" }, -{ ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT ,"42000", "" }, -{ ER_WRONG_PARAMETERS_TO_NATIVE_FCT ,"42000", "" }, -{ ER_WRONG_PARAMETERS_TO_STORED_FCT ,"42000", "" }, -{ ER_DUP_ENTRY_WITH_KEY_NAME ,"23000", "S1009" }, -{ ER_XA_RBTIMEOUT ,"XA106", "" }, -{ ER_XA_RBDEADLOCK ,"XA102", "" }, -{ ER_FUNC_INEXISTENT_NAME_COLLISION ,"42000", "" }, -{ ER_DUP_SIGNAL_SET ,"42000", "" }, -{ ER_SIGNAL_WARN ,"01000", "" }, -{ ER_SIGNAL_NOT_FOUND ,"02000", "" }, -{ ER_SIGNAL_EXCEPTION ,"HY000", "" }, -{ ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER ,"0K000", "" }, -{ ER_SPATIAL_MUST_HAVE_GEOM_COL ,"42000", "" }, -{ ER_DATA_OUT_OF_RANGE ,"22003", "" }, -{ ER_ACCESS_DENIED_NO_PASSWORD_ERROR ,"28000", "" }, -{ ER_TRUNCATE_ILLEGAL_FK ,"42000", "" }, -{ ER_DA_INVALID_CONDITION_NUMBER ,"35000", "" }, -{ ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO,"23000", "S1009" }, -{ ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO,"23000", "S1009" }, -{ ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION,"25006", "" }, -{ ER_ALTER_OPERATION_NOT_SUPPORTED ,"0A000", "" }, -{ ER_ALTER_OPERATION_NOT_SUPPORTED_REASON ,"0A000", "" }, -{ ER_DUP_UNKNOWN_IN_INDEX ,"23000", "" }, -{ ER_ACCESS_DENIED_CHANGE_USER_ERROR ,"28000", "" }, -{ ER_DATA_OVERFLOW ,"22003", "" }, -{ ER_DATA_TRUNCATED ,"22003", "" }, -{ ER_BAD_DATA ,"22007", "" }, -{ ER_DYN_COL_DATA ,"22007", "" }, -{ ER_CONNECTION_KILLED ,"70100", "" }, -{ ER_NO_SUCH_TABLE_IN_ENGINE ,"42S02", "" }, -{ ER_INVALID_ROLE ,"OP000", "" }, -{ ER_INVALID_CURRENT_USER ,"0L000", "" }, -{ ER_IT_IS_A_VIEW ,"42S02", "" }, -{ ER_STATEMENT_TIMEOUT ,"70100", "" }, -{ ER_SUBQUERIES_NOT_SUPPORTED ,"42000", "" }, -{ ER_SET_STATEMENT_NOT_SUPPORTED ,"42000", "" }, -{ ER_INVALID_DEFAULT_VALUE_FOR_FIELD ,"22007", "" }, -{ ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER,"0Z002", "" }, -{ ER_INVALID_ARGUMENT_FOR_LOGARITHM ,"2201E", "" }, -{ ER_GIS_INVALID_DATA ,"22023", "" }, -{ ER_USER_LOCK_WRONG_NAME ,"42000", "" }, -{ ER_COMMULTI_BADCONTEXT ,"0A000", "" }, -{ ER_CONSTRAINT_FAILED ,"23000", "" }, -{ ER_EXPRESSION_REFERS_TO_UNINIT_FIELD ,"01000", "" }, -{ ER_WRONG_PARAMCOUNT_TO_CURSOR ,"42000", "" }, -{ ER_NOT_SEQUENCE ,"42S02", "" }, -{ ER_NOT_SEQUENCE2 ,"42S02", "" }, -{ ER_UNKNOWN_SEQUENCES ,"42S02", "" }, -{ ER_UNKNOWN_VIEW ,"42S02", "" }, -{ ER_TOO_LONG_KEYPART ,"42000", "S1009" }, diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-case.h b/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-case.h deleted file mode 100644 index 72881a2..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-case.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef SSLOPT_CASE_INCLUDED -#define SSLOPT_CASE_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) - case OPT_SSL_KEY: - case OPT_SSL_CERT: - case OPT_SSL_CA: - case OPT_SSL_CAPATH: - case OPT_SSL_CIPHER: - case OPT_SSL_CRL: - case OPT_SSL_CRLPATH: - /* - Enable use of SSL if we are using any ssl option - One can disable SSL later by using --skip-ssl or --ssl=0 - */ - opt_use_ssl= 1; -#if defined (HAVE_WOLFSSL) && (!defined (_WIN32) || defined (MYSQL_SERVER)) - /* CRL does not work with WolfSSL */ - opt_ssl_crl= NULL; - opt_ssl_crlpath= NULL; -#endif - break; -#endif -#endif /* SSLOPT_CASE_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-longopts.h b/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-longopts.h deleted file mode 100644 index d0278a1..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-longopts.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef SSLOPT_LONGOPTS_INCLUDED -#define SSLOPT_LONGOPTS_INCLUDED - -/* - Copyright (c) 2000, 2010, Oracle and/or its affiliates. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) - - {"ssl", OPT_SSL_SSL, - "Enable SSL for connection (automatically enabled with other flags).", - &opt_use_ssl, &opt_use_ssl, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, - {"ssl-ca", OPT_SSL_CA, - "CA file in PEM format (check OpenSSL docs, implies --ssl).", - &opt_ssl_ca, &opt_ssl_ca, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - {"ssl-capath", OPT_SSL_CAPATH, - "CA directory (check OpenSSL docs, implies --ssl).", - &opt_ssl_capath, &opt_ssl_capath, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - {"ssl-cert", OPT_SSL_CERT, "X509 cert in PEM format (implies --ssl).", - &opt_ssl_cert, &opt_ssl_cert, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - {"ssl-cipher", OPT_SSL_CIPHER, "SSL cipher to use (implies --ssl).", - &opt_ssl_cipher, &opt_ssl_cipher, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - {"ssl-key", OPT_SSL_KEY, "X509 key in PEM format (implies --ssl).", - &opt_ssl_key, &opt_ssl_key, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - {"ssl-crl", OPT_SSL_KEY, "Certificate revocation list (implies --ssl).", - &opt_ssl_crl, &opt_ssl_crl, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - {"ssl-crlpath", OPT_SSL_KEY, - "Certificate revocation list path (implies --ssl).", - &opt_ssl_crlpath, &opt_ssl_crlpath, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - {"tls-version", OPT_TLS_VERSION, - "TLS protocol version for secure connection.", - &opt_tls_version, &opt_tls_version, 0, GET_STR, REQUIRED_ARG, - 0, 0, 0, 0, 0, 0}, - -#ifdef MYSQL_CLIENT - {"ssl-verify-server-cert", OPT_SSL_VERIFY_SERVER_CERT, - "Verify server's \"Common Name\" in its cert against hostname used " - "when connecting. This option is disabled by default.", - &opt_ssl_verify_server_cert, &opt_ssl_verify_server_cert, - 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, -#endif -#endif /* HAVE_OPENSSL */ -#endif /* SSLOPT_LONGOPTS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-vars.h b/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-vars.h deleted file mode 100644 index e28f19b..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/sslopt-vars.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef SSLOPT_VARS_INCLUDED -#define SSLOPT_VARS_INCLUDED - -/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ - -#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) -#ifdef SSL_VARS_NOT_STATIC -#define SSL_STATIC -#else -#define SSL_STATIC static -#endif -SSL_STATIC my_bool opt_use_ssl = 0; -SSL_STATIC char *opt_ssl_ca = 0; -SSL_STATIC char *opt_ssl_capath = 0; -SSL_STATIC char *opt_ssl_cert = 0; -SSL_STATIC char *opt_ssl_cipher = 0; -SSL_STATIC char *opt_ssl_key = 0; -SSL_STATIC char *opt_ssl_crl = 0; -SSL_STATIC char *opt_ssl_crlpath = 0; -SSL_STATIC char *opt_tls_version = 0; -#ifdef MYSQL_CLIENT -SSL_STATIC my_bool opt_ssl_verify_server_cert= 0; -#endif -#endif -#endif /* SSLOPT_VARS_INCLUDED */ diff --git a/VCMP-LUA/modules/mariadb/include/mysql/server/typelib.h b/VCMP-LUA/modules/mariadb/include/mysql/server/typelib.h deleted file mode 100644 index 23df737..0000000 --- a/VCMP-LUA/modules/mariadb/include/mysql/server/typelib.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - Copyright (c) 2017, MariaDB Corporation. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; version 2 of the License. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ - - -#ifndef _typelib_h -#define _typelib_h - -#include "my_alloc.h" - -typedef struct st_typelib { /* Different types saved here */ - unsigned int count; /* How many types */ - const char *name; /* Name of typelib */ - const char **type_names; - unsigned int *type_lengths; -} TYPELIB; - -extern my_ulonglong find_typeset(char *x, TYPELIB *typelib,int *error_position); -extern int find_type_with_warning(const char *x, TYPELIB *typelib, - const char *option); -#define FIND_TYPE_BASIC 0 -/** makes @c find_type() require the whole name, no prefix */ -#define FIND_TYPE_NO_PREFIX (1U << 0) -/** always implicitly on, so unused, but old code may pass it */ -#define FIND_TYPE_NO_OVERWRITE 0 -/** makes @c find_type() accept a number. Not used either */ -#define FIND_TYPE_ALLOW_NUMBER 0 -/** makes @c find_type() treat ',' and '=' as terminators */ -#define FIND_TYPE_COMMA_TERM (1U << 3) - -extern int find_type(const char *x, const TYPELIB *typelib, unsigned int flags); -extern void make_type(char *to,unsigned int nr,TYPELIB *typelib); -extern const char *get_type(TYPELIB *typelib,unsigned int nr); -extern TYPELIB *copy_typelib(MEM_ROOT *root, const TYPELIB *from); - -extern TYPELIB sql_protocol_typelib; - -my_ulonglong find_set_from_flags(const TYPELIB *lib, unsigned int default_name, - my_ulonglong cur_set, my_ulonglong default_set, - const char *str, unsigned int length, - char **err_pos, unsigned int *err_len); - -#endif /* _typelib_h */ diff --git a/VCMP-LUA/modules/mariadb/lib/libcrypto_static.lib b/VCMP-LUA/modules/mariadb/lib/libcrypto_static.lib deleted file mode 100644 index c68231a..0000000 Binary files a/VCMP-LUA/modules/mariadb/lib/libcrypto_static.lib and /dev/null differ diff --git a/VCMP-LUA/modules/mariadb/lib/libmariadbclient.a b/VCMP-LUA/modules/mariadb/lib/libmariadbclient.a deleted file mode 100644 index 6edfa9c..0000000 Binary files a/VCMP-LUA/modules/mariadb/lib/libmariadbclient.a and /dev/null differ diff --git a/VCMP-LUA/modules/mariadb/lib/libmariadbclient32.a b/VCMP-LUA/modules/mariadb/lib/libmariadbclient32.a deleted file mode 100644 index 376b5ee..0000000 Binary files a/VCMP-LUA/modules/mariadb/lib/libmariadbclient32.a and /dev/null differ diff --git a/VCMP-LUA/modules/mariadb/lib/libssl_static.lib b/VCMP-LUA/modules/mariadb/lib/libssl_static.lib deleted file mode 100644 index 0db37e8..0000000 Binary files a/VCMP-LUA/modules/mariadb/lib/libssl_static.lib and /dev/null differ diff --git a/VCMP-LUA/modules/mariadb/lib/mysqlclient.lib b/VCMP-LUA/modules/mariadb/lib/mysqlclient.lib deleted file mode 100644 index 776e460..0000000 Binary files a/VCMP-LUA/modules/mariadb/lib/mysqlclient.lib and /dev/null differ diff --git a/VCMP-LUA/modules/mariadb/premake5.lua b/VCMP-LUA/modules/mariadb/premake5.lua deleted file mode 100644 index fe54923..0000000 --- a/VCMP-LUA/modules/mariadb/premake5.lua +++ /dev/null @@ -1,31 +0,0 @@ -files -{ - "include/**.hpp", - "include/**.h", - "src/**.hpp", - "**.cpp" -} - -includedirs -{ - "include", - "include/mysql", -} - -filter {"system:windows"} - libdirs { "lib" } - --- filter {"system:windows", "Release32"} --- links { "MariaDBClient32.lib" } - -filter {"system:windows", "Release"} - -- MySQL cancer crap keeps depending on dynamic libssl and libcrypto so even though I link with the static versions, it first looks for the DLLs causing an Error 126 /facepalm - links { "mysqlclient.lib" } - -filter {"system:not windows", "Release32"} - linkoptions { "-L modules/mariadb/lib/mariadbclient32.a" } - -filter {"system:not windows", "Release"} - linkoptions { "-L modules/mariadb/lib/mariadbclient.a" } - -filter {} \ No newline at end of file diff --git a/VCMP-LUA/modules/mariadb/src/account.cpp b/VCMP-LUA/modules/mariadb/src/account.cpp deleted file mode 100644 index d64ca1a..0000000 --- a/VCMP-LUA/modules/mariadb/src/account.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include - -using namespace mariadb; - -account::account(const std::string &host_name, const std::string &user_name, - const std::string &password, const std::string &schema, u32 port, - const std::string &unix_socket) - : m_auto_commit(true), - m_port(port), - m_host_name(host_name), - m_user_name(user_name), - m_password(password), - m_schema(schema), - m_unix_socket(unix_socket) {} - -const std::string &account::host_name() const { return m_host_name; } - -const std::string &account::user_name() const { return m_user_name; } - -const std::string &account::password() const { return m_password; } - -const std::string &account::unix_socket() const { return m_unix_socket; } - -u32 account::port() const { return m_port; } - -const std::string &account::ssl_key() const { return m_ssl_key; } - -const std::string &account::ssl_certificate() const { return m_ssl_certificate; } - -const std::string &account::ssl_ca() const { return m_ssl_ca; } - -const std::string &account::ssl_ca_path() const { return m_ssl_ca_path; } - -const std::string &account::ssl_cipher() const { return m_ssl_cipher; } - -const std::string &account::schema() const { return m_schema; } - -void account::set_schema(const std::string &schema) { m_schema = schema; } - -void account::set_ssl(const std::string &key, const std::string &certificate, const std::string &ca, - const std::string &ca_path, const std::string &cipher) { - m_ssl_key = key; - m_ssl_certificate = certificate; - m_ssl_ca = ca; - m_ssl_ca_path = ca_path; - m_ssl_cipher = cipher; -} - -bool account::auto_commit() const { return m_auto_commit; } - -void account::set_auto_commit(bool auto_commit) { m_auto_commit = auto_commit; } - -bool account::store_result() const { return m_store_result; } - -void account::set_store_result(bool store_result) { m_store_result = store_result; } - -const account::map_options_t &account::options() const { return m_options; } - -const std::string account::option(const std::string &name) const { - const map_options_t::const_iterator value = m_options.find(name); - - // return option value if found - return value == m_options.end() ? "" : value->second; -} - -void account::set_option(const std::string &name, const std::string &value) { - m_options[name] = value; -} - -void account::clear_options() { m_options.clear(); } - -const account::map_connect_options_t &account::connect_options() const { return m_connect_options; } - -void account::clear_connect_options() { m_connect_options.clear(); } - -void account::set_connect_option(mysql_option option, bool arg) { - m_connect_options[option] = std::unique_ptr(new option_arg_bool(arg)); -} - -void account::set_connect_option(mysql_option option, int arg) { - m_connect_options[option] = std::unique_ptr(new option_arg_int(arg)); -} - -void account::set_connect_option(mysql_option option, const std::string &arg) { - m_connect_options[option] = std::unique_ptr(new option_arg_string(arg)); -} - - -account_ref account::create(const std::string &host_name, const std::string &user_name, - const std::string &password, const std::string &schema, u32 port, - const std::string &unix_socket) { - return account_ref(new account(host_name, user_name, password, schema, port, unix_socket)); -} diff --git a/VCMP-LUA/modules/mariadb/src/bind.cpp b/VCMP-LUA/modules/mariadb/src/bind.cpp deleted file mode 100644 index ccaa632..0000000 --- a/VCMP-LUA/modules/mariadb/src/bind.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include - -using namespace mariadb; - -bind::bind(MYSQL_BIND* b) : m_bind(b), m_is_null(0), m_error(0) { - // clear bind - memset(b, 0, sizeof(MYSQL_BIND)); - - // set default data - m_bind->buffer = &m_unsigned64; - m_bind->buffer_length = 0; - m_bind->buffer_type = MYSQL_TYPE_NULL; - m_bind->is_null = &m_is_null; - m_bind->error = &m_error; - m_bind->length = &m_bind->buffer_length; -} - -bind::bind(MYSQL_BIND* b, MYSQL_FIELD* f) : bind(b) { - set(f->type, nullptr, f->max_length, (f->flags & UNSIGNED_FLAG) == UNSIGNED_FLAG); -} - -char* bind::buffer() const { - if (m_data) return m_data->get(); - - return const_cast(reinterpret_cast(&m_unsigned64)); -} - -unsigned long bind::length() const { return m_bind->buffer_length; } - -bool bind::is_null() const { return (m_is_null != 0); } - -void bind::set(enum_field_types type, const char* buffer, unsigned long length, bool us) { - m_bind->buffer_type = type; - m_bind->is_unsigned = us ? 1 : 0; - - switch (type) { - case MYSQL_TYPE_NULL: - m_bind->buffer_length = 1; - break; - - case MYSQL_TYPE_TINY: - case MYSQL_TYPE_BIT: - m_bind->buffer_length = 1; - break; - - case MYSQL_TYPE_YEAR: - case MYSQL_TYPE_SHORT: - m_bind->buffer_length = sizeof(s16); - break; - - case MYSQL_TYPE_INT24: - case MYSQL_TYPE_LONG: - m_bind->buffer_length = sizeof(s32); - break; - - case MYSQL_TYPE_LONGLONG: - m_bind->buffer_length = sizeof(s64); - break; - - case MYSQL_TYPE_FLOAT: - m_bind->buffer_length = sizeof(f32); - break; - - case MYSQL_TYPE_DOUBLE: - m_bind->buffer_length = sizeof(f64); - break; - - case MYSQL_TYPE_NEWDATE: - case MYSQL_TYPE_DATE: - case MYSQL_TYPE_TIME: - case MYSQL_TYPE_TIMESTAMP: - case MYSQL_TYPE_DATETIME: - m_bind->buffer = &m_time; - m_bind->buffer_length = sizeof(MYSQL_TIME); - break; - - default: - case MYSQL_TYPE_DECIMAL: - case MYSQL_TYPE_NEWDECIMAL: - case MYSQL_TYPE_TINY_BLOB: - case MYSQL_TYPE_MEDIUM_BLOB: - case MYSQL_TYPE_LONG_BLOB: - case MYSQL_TYPE_BLOB: - case MYSQL_TYPE_ENUM: - case MYSQL_TYPE_VARCHAR: - case MYSQL_TYPE_VAR_STRING: - case MYSQL_TYPE_STRING: - m_data = data_ref(new data(length)); - m_bind->buffer = m_data->get(); - m_bind->buffer_length = m_data->size(); - - if (buffer) memcpy(m_bind->buffer, buffer, length); - break; - } -} \ No newline at end of file diff --git a/VCMP-LUA/modules/mariadb/src/concurrency.cpp b/VCMP-LUA/modules/mariadb/src/concurrency.cpp deleted file mode 100644 index 3c3881d..0000000 --- a/VCMP-LUA/modules/mariadb/src/concurrency.cpp +++ /dev/null @@ -1,205 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include - -#include -#include -#include - -#define LOCK_MUTEX() std::lock_guard lock(g_mutex) - -#include "worker.hpp" -#include "private.hpp" - -using namespace mariadb; -using namespace mariadb::concurrency; - -namespace { -handle g_next_handle(0); -account_ref g_account; -std::mutex g_mutex; -std::vector g_querys_in; -std::map g_querys_out; -bool g_thread_running(false); - -typedef std::map map_t; - -// -// Worker thread -// -void worker_thread() { - g_thread_running = true; - - mysql_thread_init(); - - // breaking in infinite loop because checking g_querys_in would result in a race condition - while (true) { - worker* w = NULL; - { - LOCK_MUTEX(); - auto possible_w = g_querys_in.begin(); - if (possible_w == g_querys_in.end()) break; - - w = *possible_w; - g_querys_in.erase(possible_w); - } - - w->execute(); - - if (!w->keep_handle()) delete w; - } - - g_thread_running = false; - mysql_thread_end(); -} - -// -// Start thread if no thread is running -// -void start_thread() { - if (!g_thread_running) { - std::thread t(worker_thread); - t.detach(); - } -} - -// -// Get worker from handle -// -const worker& get_worker(handle h) { - LOCK_MUTEX(); - const map_t::const_iterator w = g_querys_out.find(h); - - if (w != g_querys_out.end()) return *w->second; - - static worker removed; - return removed; -} - -// -// Add / remove a new query / command to the thread -// -handle add(const std::string& query, command::type command, bool keep_handle) { - LOCK_MUTEX(); - worker* w = new worker(g_account, ++g_next_handle, keep_handle, command, query); - g_querys_in.push_back(w); - - if (keep_handle) g_querys_out[g_next_handle] = w; - - start_thread(); - - return g_next_handle; -} - -handle add(statement_ref& statement, command::type command, bool keep_handle) { - LOCK_MUTEX(); - worker* w = new worker(g_account, ++g_next_handle, keep_handle, command, statement); - g_querys_in.push_back(w); - - if (keep_handle) g_querys_out[g_next_handle] = w; - - start_thread(); - - return g_next_handle; -} -} - -// -// Set account for connection -// -void concurrency::set_account(account_ref& account) { g_account = account; } - -// -// Query status -// -status::type concurrency::worker_status(handle h) { - const worker& w = get_worker(h); - return w.status(); -} - -// -// Query executed, result ready to be used -// -u64 concurrency::get_execute_result(handle h) { - const worker& w = get_worker(h); - return w.status() == status::removed ? 0 : w.result(); -} - -u64 concurrency::get_insert_result(handle h) { - const worker& w = get_worker(h); - return w.status() == status::removed ? 0 : w.result(); -} - -result_set_ref concurrency::get_query_result(handle h) { - const worker& w = get_worker(h); - return w.status() == status::removed ? result_set_ref() : w.result_set(); -} - -// -// Execute a query -// -handle concurrency::execute(const std::string& query, bool keep_handle) { - return add(query, command::execute, keep_handle); -} - -handle concurrency::insert(const std::string& query, bool keep_handle) { - return add(query, command::insert, keep_handle); -} - -handle concurrency::query(const std::string& query, bool keep_handle) { - return add(query, command::query, keep_handle); -} - -// -// Execute a query using a statement -// -statement_ref concurrency::create_statement(const std::string& query) { - connection_ref connection = connection::create(g_account); - statement_ref statement = connection->create_statement(query); - statement->set_connection(connection); - return statement; -} - -handle concurrency::execute(statement_ref& statement, bool keep_handle) { - return add(statement, command::execute, keep_handle); -} - -handle concurrency::insert(statement_ref& statement, bool keep_handle) { - return add(statement, command::insert, keep_handle); -} - -handle concurrency::query(statement_ref& statement, bool keep_handle) { - return add(statement, command::query, keep_handle); -} - -// -// Remove a query -// -// Please note, if a result_set is used, it must be done after the result_set is used... -// -void concurrency::release_handle(handle h) { - LOCK_MUTEX(); - map_t::iterator w = g_querys_out.find(h); - - if (w == g_querys_out.end()) return; - - delete w->second; - g_querys_out.erase(w); -} - -bool concurrency::wait_handle(handle h, u64 wait_time_ms) { - while (worker_status(h) < status::succeed) { - std::this_thread::sleep_for(std::chrono::milliseconds(wait_time_ms)); - } - - return worker_status(h) == status::succeed; -} diff --git a/VCMP-LUA/modules/mariadb/src/connection.cpp b/VCMP-LUA/modules/mariadb/src/connection.cpp deleted file mode 100644 index 024e807..0000000 --- a/VCMP-LUA/modules/mariadb/src/connection.cpp +++ /dev/null @@ -1,200 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include "private.hpp" - -using namespace mariadb; - -#define MYSQL_ERROR_DISCONNECT(mysql) \ - { \ - m_last_error_no = mysql_errno(mysql); \ - m_last_error = mysql_error(mysql); \ - disconnect(); \ - MARIADB_ERROR(m_last_error_no, m_last_error); \ - } - -connection::connection(const account_ref& account) - : m_mysql(NULL), m_auto_commit(true), m_account(account) {} - -connection_ref connection::create(const account_ref& account) { - return connection_ref(new connection(account)); -} - -connection::~connection() { disconnect(); } - -const std::string& connection::schema() const { return m_schema; } - -bool connection::set_schema(const std::string& schema) { - if (!connect()) return false; - - if (mysql_select_db(m_mysql, schema.c_str())) MYSQL_ERROR(m_mysql); - - m_schema = schema; - return true; -} - -const std::string& connection::charset() const { return m_charset; } - -bool connection::set_charset(const std::string& value) { - if (!connect()) return false; - - if (mysql_set_character_set(m_mysql, value.c_str())) MYSQL_ERROR(m_mysql); - - m_charset = value; - return true; -} - -bool connection::connected() const { - if (m_mysql == nullptr) - return false; - else - return !mysql_ping(m_mysql); -} - -account_ref connection::account() const { return m_account; } - -bool connection::auto_commit() const { return m_auto_commit; } - -bool connection::set_auto_commit(bool auto_commit) { - if (m_auto_commit == auto_commit) return true; - - if (!connect()) return false; - - if (mysql_autocommit(m_mysql, auto_commit)) MYSQL_ERROR(m_mysql); - - m_auto_commit = auto_commit; - return true; -} - -bool connection::connect() { - if (connected()) return true; - - if (m_mysql == nullptr) { - m_mysql = mysql_init(nullptr); - - if (!m_mysql) { - MARIADB_ERROR(0, "Cannot create MYSQL object."); - } - } - - if (!m_account->ssl_key().empty()) { - if (mysql_ssl_set(m_mysql, m_account->ssl_key().c_str(), - m_account->ssl_certificate().c_str(), m_account->ssl_ca().c_str(), - m_account->ssl_ca_path().c_str(), m_account->ssl_cipher().c_str())) - MYSQL_ERROR(m_mysql); - } - - // - // set connect options - // - for (auto& pair : m_account->connect_options()) { - if (0 != mysql_options(m_mysql, pair.first, pair.second->value())) - MYSQL_ERROR_DISCONNECT(m_mysql); - } - - if (!mysql_real_connect( - m_mysql, m_account->host_name().c_str(), m_account->user_name().c_str(), - m_account->password().c_str(), nullptr, m_account->port(), - m_account->unix_socket().empty() ? nullptr : m_account->unix_socket().c_str(), - CLIENT_MULTI_STATEMENTS)) - MYSQL_ERROR(m_mysql); - - if (!set_auto_commit(m_account->auto_commit())) MYSQL_ERROR_DISCONNECT(m_mysql); - - if (!m_account->schema().empty()) { - if (!set_schema(m_account->schema().c_str())) MYSQL_ERROR_DISCONNECT(m_mysql); - } - - // - // Set options - // - for (auto& pair : m_account->options()) { - if (1 != execute("SET OPTION " + pair.first + "=" + pair.second)) - MYSQL_ERROR_DISCONNECT(m_mysql); - } - - return true; -} - -void connection::disconnect() { - if (!m_mysql) return; - - mysql_close(m_mysql); - mysql_thread_end(); // mysql_init() call mysql_thread_init therefor it needed to clear memory - // when closed msql handle - m_mysql = nullptr; -} - -result_set_ref connection::query(const std::string& query) { - result_set_ref rs; - - if (!connect()) return rs; - - if (mysql_real_query(m_mysql, query.c_str(), query.size())) { - MYSQL_ERROR_NO_BRAKET(m_mysql); - } - - rs.reset(new result_set(this)); - return rs; -} - -u64 connection::execute(const std::string& query) { - if (!connect()) return 0; - - u64 affected_rows = 0; - - if (mysql_real_query(m_mysql, query.c_str(), query.size())) { - MYSQL_ERROR_NO_BRAKET(m_mysql); - } - - int status; - do { - MYSQL_RES* result = mysql_store_result(m_mysql); - - if (result) - mysql_free_result(result); - else if (mysql_field_count(m_mysql) == 0) - affected_rows += mysql_affected_rows(m_mysql); - else { - MYSQL_ERROR_NO_BRAKET(m_mysql); - } - - status = mysql_next_result(m_mysql); - if (status > 0) { - MYSQL_ERROR_NO_BRAKET(m_mysql); - } - } while (status == 0); - - return affected_rows; -} - -u64 connection::insert(const std::string& query) { - if (!connect()) return 0; - - if (mysql_real_query(m_mysql, query.c_str(), query.size())) { - MYSQL_ERROR_NO_BRAKET(m_mysql); - } - - return mysql_insert_id(m_mysql); -} - -statement_ref connection::create_statement(const std::string& query) { - if (!connect()) return statement_ref(); - - return statement_ref(new statement(this, query)); -} - -transaction_ref connection::create_transaction(isolation::level level, bool consistent_snapshot) { - if (!connect()) return transaction_ref(); - - return transaction_ref(new transaction(this, level, consistent_snapshot)); -} diff --git a/VCMP-LUA/modules/mariadb/src/date_time.cpp b/VCMP-LUA/modules/mariadb/src/date_time.cpp deleted file mode 100644 index c4e1c3a..0000000 --- a/VCMP-LUA/modules/mariadb/src/date_time.cpp +++ /dev/null @@ -1,590 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2020. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include -#include -#include -#include -#include "private.hpp" - -using namespace mariadb; - -namespace { -const u8 g_month_lengths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; -} - -#define MS_PER_SEC 1000 -#define MS_PER_MIN (MS_PER_SEC * 60) -#define MS_PER_HOUR (MS_PER_MIN * 60) -#define MS_PER_DAY (MS_PER_HOUR * 24) - -date_time::date_time(u16 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond) : time() { - set(year, month, day, hour, minute, second, millisecond); -} - -date_time::date_time(const date_time& dt) : time() { - set(dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute(), dt.second(), dt.millisecond()); -} - -date_time::date_time(const time& t) : time() { - set(1900, 1, 1, t.hour(), t.minute(), t.second(), t.millisecond()); -} - -date_time::date_time(const tm& t) : time() { - set(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, 0); -} - -date_time::date_time(const time_t& time) : mariadb::time() { - tm t; - localtime_safe(&t, &time); - - set(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, 0); -} - -date_time::date_time(const MYSQL_TIME& t) : time() { - set(t.year, t.month, t.day, t.hour, t.minute, t.second, t.second_part / 1000); -} - -date_time::date_time(const std::string& dt) : time() { set(dt); } - -int date_time::compare(const date_time& dt) const { - if (year() < dt.year()) return -1; - - if (year() > dt.year()) return 1; - - if (month() < dt.month()) return -1; - - if (month() > dt.month()) return 1; - - if (day() < dt.day()) return -1; - - if (day() > dt.day()) return 1; - - return time::compare(dt); -} - -date_time& date_time::operator=(const date_time& dt) { - set(dt.year(), dt.month(), dt.day(), dt.hour(), dt.minute(), dt.second(), dt.millisecond()); - return *this; -} - -bool date_time::operator==(const date_time& dt) const { return compare(dt) == 0; } - -bool date_time::operator!=(const date_time& dt) const { return compare(dt) != 0; } - -bool date_time::operator<(const date_time& dt) const { return compare(dt) < 0; } - -bool date_time::operator<=(const date_time& dt) const { return compare(dt) <= 0; } - -bool date_time::operator>(const date_time& dt) const { return compare(dt) > 0; } - -bool date_time::operator>=(const date_time& dt) const { return compare(dt) >= 0; } - -bool date_time::set(u16 year, u8 month, u8 day) { - m_year = year; - m_month = month; - m_day = day; - return true; -} - -bool date_time::set(u16 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond) { - m_year = year; - m_month = month; - m_day = day; - - return time::set(hour, minute, second, millisecond); -} - -u16 date_time::year() const { return m_year; } - -u16 date_time::year(u16 year) { - if (year == 0) - MARIADB_ERROR_THROW_DATE(year, month(), day(), hour(), minute(), second(), millisecond()); - - m_year = year; - - if (!valid_date(year, month(), day())) { - m_month = 1; - m_day = 1; - } - - return m_year; -} - -u8 date_time::month() const { return m_month; } - -u8 date_time::month(u8 month) { - if (month == 0 || month > 12) - MARIADB_ERROR_THROW_DATE(year(), month, day(), hour(), minute(), second(), millisecond()); - - m_month = month; - - u8 days_inmonth = days_in_month(year(), month); - - if (day() > days_inmonth) m_day = 1; - - return m_month; -} - -u8 date_time::day() const { return m_day; } - -u8 date_time::day(u8 day) { - u8 days_inmonth = days_in_month(year(), month()); - - if (day == 0 || day > days_inmonth) - MARIADB_ERROR_THROW_DATE(year(), month(), day, hour(), minute(), second(), millisecond()); - - m_day = day; - - return m_day; -} - -u16 date_time::day_of_year() const { return day_of_year(year(), month(), day()); } - -u16 date_time::day_of_year(u16 day_of_year) { - date_time new_date = reverse_day_of_year(year(), day_of_year); - - month(new_date.month()); - day(new_date.day()); - - return day_of_year; -} - -date_time date_time::add_years(s32 years) const { - date_time tmp = *this; - - if (!years) return tmp; - - tmp.year(m_year + years); - return tmp; -} - -date_time date_time::add_months(s32 months) const { - date_time tmp = *this; - - if (!months) return tmp; - - s32 years = months / 12; - - months = (months % 12) + month(); - - if (months >= 12) { - ++years; - months %= 12; - } else if (months < 0) { - --years; - months = 12 - months; - } - - if (years) tmp = tmp.add_years(years); - - tmp.month(months); - return tmp; -} - -date_time date_time::add_days(s32 days) const { - date_time tmp = *this; - - if (!days) return tmp; - - s32 dir = days > 0 ? 1 : -1; - u16 y = year(); - s32 days_in = days_in_year(y); - s32 day_of = day_of_year() + days; - - while (day_of > days_in || day_of < 0) { - day_of -= days_in * dir; - y += dir; - days_in = days_in_year(y); - } - - tmp.year(y); - tmp.day_of_year(day_of); - return tmp; -} - -date_time date_time::add_hours(s32 hours) const { - date_time tmp = *this; - - if (!hours) return tmp; - - s32 days = hours / 24; - - hours = (hours % 24) + hour(); - - if (hours >= 24) { - ++days; - hours %= 24; - } else if (hours < 0) { - --days; - hours = 24 - hours; - } - - if (days) tmp = tmp.add_days(days); - - tmp.hour(hours); - return tmp; -} - -date_time date_time::add_minutes(s32 minutes) const { - date_time tmp = *this; - - if (!minutes) return tmp; - - s32 hours = minutes / 60; - - minutes = (minutes % 60) + minute(); - - if (minutes >= 60) { - ++hours; - minutes %= 60; - } else if (minutes < 0) { - --hours; - minutes = 60 - minutes; - } - - if (hours > 0) tmp = tmp.add_hours(hours); - - tmp.minute(minutes); - return tmp; -} - -date_time date_time::add_seconds(s32 seconds) const { - date_time tmp = *this; - - if (!seconds) return tmp; - - s32 minutes = seconds / 60; - - seconds = (seconds % 60) + second(); - - if (seconds >= 60) { - ++minutes; - seconds %= 60; - } else if (seconds < 0) { - --minutes; - seconds = 60 - seconds; - } - - if (minutes > 0) tmp = tmp.add_minutes(minutes); - - tmp.second(seconds); - return tmp; -} - -date_time date_time::add_milliseconds(s32 milliseconds) const { - date_time tmp = *this; - - if (!milliseconds) return tmp; - - s32 seconds = milliseconds / 1000; - - milliseconds = (milliseconds % 1000) + millisecond(); - - if (milliseconds >= 1000) { - ++seconds; - milliseconds %= 1000; - } else if (milliseconds < 0) { - --seconds; - milliseconds = 1000 - milliseconds; - } - - if (seconds > 0) tmp = tmp.add_seconds(seconds); - - tmp.millisecond(milliseconds); - return tmp; -} - -date_time date_time::subtract(const time_span& dur) const { - bool negative = !dur.negative(); - - time_span tmp = dur; - tmp.negative(negative); - return add(tmp); -} - -date_time date_time::add(const time_span& dur) const { - s32 negate = dur.negative() ? -1 : 1; - date_time tmp = *this; - - tmp = tmp.add_days(negate * dur.days()); - tmp = tmp.add_hours(negate * dur.hours()); - tmp = tmp.add_minutes(negate * dur.minutes()); - tmp = tmp.add_seconds(negate * dur.seconds()); - tmp = tmp.add_milliseconds(negate * dur.milliseconds()); - return tmp; -} - -date_time date_time::add(const time& t) const { - date_time tmp = *this; - - tmp = tmp.add_hours(t.hour()); - tmp = tmp.add_minutes(t.minute()); - tmp = tmp.add_seconds(t.second()); - tmp = tmp.add_milliseconds(t.millisecond()); - return tmp; -} - -date_time date_time::substract(const time& t) const { - date_time tmp = *this; - - tmp = tmp.add_hours(-1 * t.hour()); - tmp = tmp.add_minutes(-1 * t.minute()); - tmp = tmp.add_seconds(-1 * t.second()); - tmp = tmp.add_milliseconds(-1 * t.millisecond()); - return tmp; -} - -time_span date_time::time_between(const date_time& dt) const { - if (dt == *this) return time_span(); - - if (dt > *this) { - time_span dur = dt.time_between(*this); - dur.negative(true); - return dur; - } - - s64 ms = - (hour() * MS_PER_HOUR) + (minute() * MS_PER_MIN) + (second() * MS_PER_SEC) + millisecond(); - s64 dt_ms = (dt.hour() * MS_PER_HOUR) + (dt.minute() * MS_PER_MIN) + - (dt.second() * MS_PER_SEC) + dt.millisecond(); - s64 total_ms = 0; - date_time stop_date_time; - - // - // Need to stop one day after in this case - // - if (dt_ms > ms) { - stop_date_time = dt.add_days(1); - total_ms = MS_PER_DAY - (dt_ms - ms); - } else { - stop_date_time = dt; - total_ms = ms - dt_ms; - } - - u32 hours = static_cast(total_ms / MS_PER_HOUR); - total_ms = total_ms % MS_PER_HOUR; - - u32 minutes = static_cast(total_ms / MS_PER_MIN); - total_ms = total_ms % MS_PER_MIN; - - u32 seconds = static_cast(total_ms / MS_PER_SEC); - total_ms = total_ms % MS_PER_SEC; - - u32 milliseconds = static_cast(total_ms); - - u32 totaldays = 0; - u16 currentyear = year(); - - while (currentyear > stop_date_time.year()) { - if (currentyear == year()) - totaldays += day_of_year(); - else - totaldays += days_in_year(currentyear); - - currentyear--; - } - - if (year() == stop_date_time.year()) - totaldays += day_of_year() - stop_date_time.day_of_year(); - else - totaldays += days_in_year(currentyear) - stop_date_time.day_of_year(); - - /*while (currentday > stop_date_time.day_of_year()) - { - totaldays++; - currentday--; - }*/ - - return time_span(totaldays, hours, minutes, seconds, milliseconds, false); -} - -bool date_time::is_valid() const { - return valid_date(year(), month(), day()) && time::is_valid(); -} - -bool date_time::is_leap_year(u16 year) { - /* - * Leap year rule: - * every year divisible by 400 is a leap year - * every year divisible by 4 is a leap year if its not divisible by 100 - */ - return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); -} - -bool date_time::valid_date(u16 year, u8 month, u8 day) { - if (year == 0 || month == 0 || day == 0) return false; - - if (month > 12) return false; - - return day <= days_in_month(year, month); -} - -u16 date_time::days_in_year(u16 year) { return is_leap_year(year) ? u16(366) : u16(365); } - -u8 date_time::days_in_month(u16 year, u8 month) { - u8 days_in_month = g_month_lengths[month - 1]; - - if (month == 2 && is_leap_year(year)) days_in_month++; - - return days_in_month; -} - -u16 date_time::day_of_year(u16 year, u8 _month, u8 day) { - u16 day_of_year = 0; - - for (u8 month = 1; month < _month; month++) - day_of_year += date_time::days_in_month(year, month); - - day_of_year += day; - - return day_of_year; -} - -date_time date_time::reverse_day_of_year(u16 year, u16 day_of_year) { - u8 month; - - for (month = 1; month < 12; month++) { - u32 days = date_time::days_in_month(year, month); - - if (days >= day_of_year) break; - - day_of_year -= days; - } - - return date_time(year, month, static_cast(day_of_year)); -} - -time_t date_time::mktime() const { - tm t; - - t.tm_year = year() - 1900; - t.tm_mon = month() - 1; - t.tm_mday = day(); - t.tm_hour = hour(); - t.tm_min = minute(); - t.tm_sec = second(); - - return ::mktime(&t); -} - -MYSQL_TIME date_time::mysql_time() const { - MYSQL_TIME t; - - t.year = year(); - t.month = month(); - t.day = day(); - t.hour = hour(); - t.minute = minute(); - t.second = second(); - t.second_part = millisecond() * 1000u; - t.neg = false; - t.time_type = - !t.hour && !t.minute && !t.second ? MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME; - - return t; -} - -double date_time::diff_time(const date_time& dt) const { - time_t time_val = mktime(); - time_t dt_time_val = dt.mktime(); - - return ::difftime(time_val, dt_time_val); -} - -date_time date_time::date() const { return date_time(year(), month(), day()); } - -date_time date_time::now() { - using namespace std::chrono; - auto now = system_clock::now(); - - time_t local_time = system_clock::to_time_t(now); - tm ts; - localtime_safe(&ts, &local_time); - - auto millis = duration_cast(now.time_since_epoch()).count() % 1000; - return date_time(ts).add_milliseconds(static_cast(millis)); -} - -date_time date_time::now_utc() { - using namespace std::chrono; - auto now = system_clock::now(); - - time_t utc_time = system_clock::to_time_t(now); - tm ts; - gmtime_safe(&ts, &utc_time); - - auto millis = duration_cast(now.time_since_epoch()).count() % 1000; - return date_time(ts).add_milliseconds(static_cast(millis)); -} - -bool date_time::set(const std::string& dt) { - std::stringstream stream(dt); - - u8 m, d; - u16 s_y = 0, s_m = 0, s_d = 0; - char delim; - - // read formatted years, check overflow before cast - if (stream >> s_y) { - if (stream.eof()) return set(s_y, 0, 0); - - // read formatted months, check overflow before cast - if (stream >> delim && stream >> s_m && s_m < 13) { - m = static_cast(s_m); - if (stream.eof()) return set(s_y, m, 0); - - // read formatted days, check overflow before cast - if (stream >> delim && stream >> s_d && s_d < 32) { - d = static_cast(s_d); - if (stream.eof()) return set(s_y, m, d); - - // extract remaining string - std::string rest; - std::getline(stream, rest); - - // set time from string - return set(s_y, m, d) && time::set(rest); - } - } - } - - throw std::invalid_argument("invalid date format"); -} - -const std::string date_time::str(bool with_millisecond) const { - std::stringstream stream; - stream.fill('0'); - - stream << str_date() << " " << time::str_time(with_millisecond); - return stream.str(); -} - -const std::string date_time::str_date() const { - std::stringstream stream; - stream.fill('0'); - - /* - * Note: the magic unary + forces conversion of unsigned char (u8) to a numeric printing type, - * otherwise it will - * be printed as char - */ - stream << std::setw(4) << year() << "-" << std::setw(2) << +month() << "-" << std::setw(2) - << +day(); - return stream.str(); -} - -std::ostream& mariadb::operator<<(std::ostream& os, const date_time& dt) { - os << dt.str(true); - return os; -} diff --git a/VCMP-LUA/modules/mariadb/src/exceptions.cpp b/VCMP-LUA/modules/mariadb/src/exceptions.cpp deleted file mode 100644 index 20faa44..0000000 --- a/VCMP-LUA/modules/mariadb/src/exceptions.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include - -using namespace mariadb; - -// -// Constructors -// -exception::date_time::date_time(u16 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, - u16 millisecond) throw() : base() { - std::ostringstream oss; - oss << "Invalid date time: " << std::setfill('0') << std::setw(4) << year - << "-" << std::setw(2) << int(month) - << "-" << std::setw(2) << int(day) - << "T" << std::setw(2) << int(hour) - << ":" << std::setw(2) << int(minute) - << ":" << std::setw(2) << int(second) - << "." << std::setw(3) << millisecond; - - m_error = oss.str(); -} - -exception::time::time(u8 hour, u8 minute, u8 second, u16 millisecond) throw() : base() { - std::ostringstream oss; - oss << "Invalid time: " << std::setfill('0') << std::setw(2) << int(hour) - << ":" << std::setw(2) << int(minute) - << ":" << std::setw(2) << int(second) - << "." << std::setw(3) << millisecond; - - m_error = oss.str(); -} diff --git a/VCMP-LUA/modules/mariadb/src/last_error.cpp b/VCMP-LUA/modules/mariadb/src/last_error.cpp deleted file mode 100644 index 379dd57..0000000 --- a/VCMP-LUA/modules/mariadb/src/last_error.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include - -using namespace mariadb; - -// -// Constructor -// -last_error::last_error() : m_last_error_no(0) {} - -// -// Get last error -// -u32 last_error::error_no() const { return m_last_error_no; } - -const std::string& last_error::error() const { return m_last_error; } diff --git a/VCMP-LUA/modules/mariadb/src/private.hpp b/VCMP-LUA/modules/mariadb/src/private.hpp deleted file mode 100644 index ed35e78..0000000 --- a/VCMP-LUA/modules/mariadb/src/private.hpp +++ /dev/null @@ -1,73 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_PRIVATE_HPP_ -#define _MARIADB_PRIVATE_HPP_ - -#include -#include - -namespace mariadb { -#if _WIN32 -inline int localtime_safe(struct tm* _tm, const time_t* _time) { return localtime_s(_tm, _time); } - -inline int gmtime_safe(struct tm* _tm, const time_t* _time) { return gmtime_s(_tm, _time); } -#else -inline int localtime_safe(struct tm* _tm, const time_t* _time) { - return localtime_r(_time, _tm) ? 0 : -1; -} - -inline int gmtime_safe(struct tm* _tm, const time_t* _time) { - return gmtime_r(_time, _tm) ? 0 : -1; -} -#endif -} -#if _WIN32 - -#if __MINGW32__ -// this is needed because on mingw sprintf_s is broken (due to msvcrt not following c99 standard -// with sprintf...) -#define snprintf(buffer, szbuffer, format, ...) __mingw_sprintf(buffer, format, ##__VA_ARGS__) -#else -#define snprintf sprintf_s -#endif - -#endif - -#define MARIADB_ERROR_THROW_CONNECTION(error_id, error) \ - throw exception::connection(error_id, error); -#define MARIADB_ERROR_THROW_DATE(_year, _month, _day, _hour, _minute, _second, _millisecond) \ - throw exception::date_time(_year, _month, _day, _hour, _minute, _second, _millisecond); -#define MARIADB_ERROR_THROW_TIME(_hour, _minute, _second, _millisecond) \ - throw exception::time(_hour, _minute, _second, _millisecond); - -#define MARIADB_ERROR(error_id, error) \ - std::cerr << "MariaDB Error(" << error_id << "): " << error \ - << "\nIn function: " << __FUNCTION__ << "\nIn file " << __FILE__ << "\nOn line " \ - << __LINE__ << '\n'; \ - MARIADB_ERROR_THROW_CONNECTION(error_id, error) - -#define MYSQL_ERROR_NO_BRAKET(mysql) \ - m_last_error_no = mysql_errno(mysql); \ - m_last_error = mysql_error(mysql); \ - MARIADB_ERROR(m_last_error_no, m_last_error); - -#define MYSQL_ERROR(mysql) \ - { MYSQL_ERROR_NO_BRAKET(mysql) } - -#define STMT_ERROR_NO_BRAKET(statement) \ - m_last_error_no = mysql_stmt_errno(statement); \ - m_last_error = mysql_stmt_error(statement); \ - MARIADB_ERROR(m_last_error_no, m_last_error); - -#define STMT_ERROR(statement) \ - { STMT_ERROR_NO_BRAKET(statement) } - -#endif diff --git a/VCMP-LUA/modules/mariadb/src/result_set.cpp b/VCMP-LUA/modules/mariadb/src/result_set.cpp deleted file mode 100644 index 1c51eb4..0000000 --- a/VCMP-LUA/modules/mariadb/src/result_set.cpp +++ /dev/null @@ -1,388 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include -#include -#include -#include "private.hpp" - -using namespace mariadb; - -result_set::result_set(connection *conn) - : m_result_set((conn->account()->store_result() ? mysql_store_result : mysql_use_result)(conn->m_mysql)), - m_fields(nullptr), - m_row(nullptr), - m_raw_binds(nullptr), - m_stmt_data(nullptr), - m_lengths(nullptr), - m_field_count(0), - m_was_fetched(false) { - - if (m_result_set) { - m_field_count = mysql_num_fields(m_result_set); - m_fields = mysql_fetch_fields(m_result_set); - - for (u32 i = 0; i < m_field_count; ++i) m_indexes[m_fields[i].name] = i; - } -} - -result_set::result_set(connection* conn, const statement_data_ref &stmt_data) - : m_result_set(nullptr), - m_fields(nullptr), - m_row(nullptr), - m_raw_binds(nullptr), - m_stmt_data(stmt_data), - m_lengths(nullptr), - m_field_count(0), - m_was_fetched(false) { - - int max_length = 1; - mysql_stmt_attr_set(stmt_data->m_statement, STMT_ATTR_UPDATE_MAX_LENGTH, &max_length); - - if (conn->account()->store_result() && mysql_stmt_store_result(stmt_data->m_statement)) - STMT_ERROR(stmt_data->m_statement) - else { - m_field_count = mysql_stmt_field_count(stmt_data->m_statement); - m_result_set = mysql_stmt_result_metadata(stmt_data->m_statement); - - if (m_field_count > 0) { - m_fields = mysql_fetch_fields(m_result_set); - m_raw_binds = new MYSQL_BIND[m_field_count]; - m_row = new char *[m_field_count]; - - for (u32 i = 0; i < m_field_count; ++i) { - m_indexes[m_fields[i].name] = i; - m_binds.emplace_back(new bind(&m_raw_binds[i], &m_fields[i])); - m_row[i] = m_binds[i]->buffer(); - } - - mysql_stmt_bind_result(stmt_data->m_statement, m_raw_binds); - } - } -} - -statement_data::~statement_data() { - delete[] m_raw_binds; - - if (m_statement) mysql_stmt_close(m_statement); -} - -result_set::~result_set() { - if (m_result_set) mysql_free_result(m_result_set); - - delete[] m_raw_binds; - - if (m_stmt_data) { - delete[] m_row; - - mysql_stmt_free_result(m_stmt_data->m_statement); - } -} - -u32 result_set::column_count() const { return m_field_count; } - -value::type result_set::column_type(u32 index) const { - if (index >= m_field_count) throw std::out_of_range("Column index out of range"); - - bool is_unsigned = (m_fields[index].flags & UNSIGNED_FLAG) == UNSIGNED_FLAG; - - switch (m_fields[index].type) { - case MYSQL_TYPE_NULL: - return value::null; - - case MYSQL_TYPE_BIT: - return value::boolean; - - case MYSQL_TYPE_FLOAT: - return value::float32; - - case MYSQL_TYPE_DECIMAL: - case MYSQL_TYPE_NEWDECIMAL: - return value::decimal; - - case MYSQL_TYPE_DOUBLE: - return value::double64; - - case MYSQL_TYPE_NEWDATE: - case MYSQL_TYPE_DATE: - return value::date; - - case MYSQL_TYPE_TIME: - return value::time; - - case MYSQL_TYPE_TIMESTAMP: - case MYSQL_TYPE_DATETIME: - return value::date_time; - - case MYSQL_TYPE_TINY: - return (is_unsigned ? value::unsigned8 : value::signed8); - - case MYSQL_TYPE_YEAR: - case MYSQL_TYPE_SHORT: - return (is_unsigned ? value::unsigned16 : value::signed16); - - case MYSQL_TYPE_INT24: - case MYSQL_TYPE_LONG: - return (is_unsigned ? value::unsigned32 : value::signed32); - - case MYSQL_TYPE_LONGLONG: - return (is_unsigned ? value::unsigned64 : value::signed64); - - case MYSQL_TYPE_TINY_BLOB: - case MYSQL_TYPE_MEDIUM_BLOB: - case MYSQL_TYPE_LONG_BLOB: - case MYSQL_TYPE_BLOB: - return value::blob; - - case MYSQL_TYPE_ENUM: - return value::enumeration; - - default: - case MYSQL_TYPE_VARCHAR: - case MYSQL_TYPE_VAR_STRING: - case MYSQL_TYPE_STRING: - return value::string; - } -} - -const std::string result_set::column_name(u32 index) { - if (index >= m_field_count) throw std::out_of_range("Column index out of range"); - - return m_fields[index].name; -} - -u32 result_set::column_index(const std::string &name) const { - const map_indexes_t::const_iterator i = m_indexes.find(name); - - if (i == m_indexes.end()) return 0xffffffff; - - return i->second; -} - -unsigned long result_set::column_size(u32 index) const { - if (index >= m_field_count) throw std::out_of_range("Column index out of range"); - - return m_stmt_data ? m_binds.at(index)->length() : m_lengths[index]; -} - -bool result_set::set_row_index(u64 index) { - if (m_stmt_data) - mysql_stmt_data_seek(m_stmt_data->m_statement, index); - else - mysql_data_seek(m_result_set, index); - return next(); -} - -bool result_set::next() { - if (!m_result_set) return (m_was_fetched = false); - - if (m_stmt_data) return (m_was_fetched = !mysql_stmt_fetch(m_stmt_data->m_statement)); - - m_row = mysql_fetch_row(m_result_set); - m_lengths = mysql_fetch_lengths(m_result_set); - - // make sure no access to results is possible until a result is successfully fetched - return (m_was_fetched = m_row != nullptr); -} - -u64 result_set::row_index() const { - if (m_stmt_data) return reinterpret_cast(mysql_stmt_row_tell(m_stmt_data->m_statement)); - - return reinterpret_cast(mysql_row_tell(m_result_set)); -} - -u64 result_set::row_count() const { - if (m_stmt_data) return mysql_stmt_num_rows(m_stmt_data->m_statement); - - return mysql_num_rows(m_result_set); -} - -void result_set::check_row_fetched() const { - if (!m_was_fetched) throw std::out_of_range("No row was fetched"); -} - -void result_set::check_type(u32 index, value::type requested) const { - value::type actual = column_type(index); - bool type_error; - - // check requested type vs actual type. - switch (requested) { - // these types require exact type match - case value::type::float32: - case value::type::double64: - case value::type::decimal: - - case value::type::time: - case value::type::date_time: - case value::type::date: - - case value::type::enumeration: - type_error = actual != requested; - break; - - // these types require size match - case value::type::unsigned8: - case value::type::signed8: - type_error = actual != value::type::signed8 && actual != value::type::unsigned8; - break; - case value::type::unsigned16: - case value::type::signed16: - type_error = actual != value::type::signed16 && actual != value::type::unsigned16; - break; - case value::type::unsigned32: - case value::type::signed32: - type_error = actual != value::type::signed32 && actual != value::type::unsigned32; - break; - case value::type::unsigned64: - case value::type::signed64: - type_error = actual != value::type::signed64 && actual != value::type::unsigned64; - break; - - // bool can also be a signed8 - case value::type::boolean: - type_error = actual != requested && actual != value::type::signed8; - break; - - // only string, blob, data and null are interchangeable - case value::type::string: - case value::type::blob: - case value::type::data: - type_error = actual != value::type::string && - actual != value::type::blob && - actual != value::type::data && - actual != value::type::null; - break; - - default: - type_error = false; - } - - if (type_error) { - printf("requested type %d does not match actual type %d", +requested, +actual); - MARIADB_ERROR_THROW_CONNECTION(12, "type error"); - } -} - -MAKE_GETTER(blob, stream_ref, value::type::blob) - size_t len = column_size(index); - - if (len == 0) return stream_ref(); - - auto *ss = new std::istringstream(); - ss->rdbuf()->pubsetbuf(m_row[index], len); - return stream_ref(ss); -} - -MAKE_GETTER(data, data_ref, value::type::data) - size_t len = column_size(index); - - return len == 0 ? data_ref() : data_ref(new data(m_row[index], len)); -} - -MAKE_GETTER(string, std::string, value::type::string) - return std::string(m_row[index], column_size(index)); -} - -MAKE_GETTER(date, date_time, value::type::date) - if (m_stmt_data) return mariadb::date_time(m_binds[index]->m_time); - - return date_time(std::string(m_row[index], column_size(index))).date(); -} - -MAKE_GETTER(date_time, date_time, value::type::date_time) - if (m_stmt_data) return mariadb::date_time(m_binds[index]->m_time); - - return date_time(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(time, mariadb::time, value::type::time) - if (m_stmt_data) return mariadb::time(m_binds[index]->m_time); - - return mariadb::time(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(decimal, decimal, value::type::decimal) - return decimal(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(boolean, bool, value::type::boolean) - if (m_stmt_data) return (m_binds[index]->m_uchar8[0] != 0); - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(unsigned8, u8, value::type::unsigned8) - if (m_stmt_data) return checked_cast(0x00000000000000ff & m_binds[index]->m_unsigned64); - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(signed8, s8, value::type::signed8) - if (m_stmt_data) return checked_cast(0x00000000000000ff & m_binds[index]->m_signed64); - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(unsigned16, u16, value::type::unsigned16) - if (m_stmt_data) return checked_cast(0x000000000000ffff & m_binds[index]->m_unsigned64); - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(signed16, s16, value::type::signed16) - if (m_stmt_data) return checked_cast(0x000000000000ffff & m_binds[index]->m_signed64); - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(unsigned32, u32, value::type::unsigned32) - if (m_stmt_data) return checked_cast(0x00000000ffffffff & m_binds[index]->m_unsigned64); - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(signed32, s32, value::type::signed32) - if (m_stmt_data) return m_binds[index]->m_signed32[0]; - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(unsigned64, u64, value::type::unsigned64) - if (m_stmt_data) return m_binds[index]->m_unsigned64; - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(signed64, s64, value::type::signed64) - if (m_stmt_data) return m_binds[index]->m_signed64; - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(float, f32, value::type::float32) - if (m_stmt_data) return m_binds[index]->m_float32[0]; - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(double, f64, value::type::double64) - if (m_stmt_data) return checked_cast(m_binds[index]->m_double64); - - return string_cast(std::string(m_row[index], column_size(index))); -} - -MAKE_GETTER(is_null, bool, value::type::null) - if (m_stmt_data) return m_binds[index]->is_null(); - - return !m_row[index]; -} diff --git a/VCMP-LUA/modules/mariadb/src/save_point.cpp b/VCMP-LUA/modules/mariadb/src/save_point.cpp deleted file mode 100644 index 50d11ff..0000000 --- a/VCMP-LUA/modules/mariadb/src/save_point.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include - -using namespace mariadb; - -namespace { -handle g_save_point_id = 0; - -const char* g_save_point_create = "SAVEPOINT "; -const char* g_save_point_rollback = "ROLLBACK TO SAVEPOINT "; -const char* g_save_point_release = "RELEASE SAVEPOINT "; -} - -// -// Constructor -// -save_point::save_point(transaction* trans) : m_transaction(trans) { - m_name = "SP" + std::to_string(++g_save_point_id); - m_transaction->m_connection->execute(g_save_point_create + m_name); -} - -// -// Destructor -// -save_point::~save_point() { - if (!m_transaction) return; - - m_transaction->remove_save_point(this); - m_transaction->m_connection->execute(g_save_point_rollback + m_name); -} - -// -// Commit the change -// -void save_point::commit() { - if (!m_transaction) return; - - m_transaction->remove_save_point(this); - m_transaction->m_connection->execute(g_save_point_release + m_name); - m_transaction = NULL; -} diff --git a/VCMP-LUA/modules/mariadb/src/statement.cpp b/VCMP-LUA/modules/mariadb/src/statement.cpp deleted file mode 100644 index 014f869..0000000 --- a/VCMP-LUA/modules/mariadb/src/statement.cpp +++ /dev/null @@ -1,176 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include -#include -#include -#include "private.hpp" - -using namespace mariadb; - -#define STMT_ERROR_RETURN_RS(statement) \ - { \ - STMT_ERROR_NO_BRAKET(statement) \ - } - -statement::statement(connection* conn, const std::string& query) - : m_parent(conn), m_data(statement_data_ref(new statement_data(mysql_stmt_init(conn->m_mysql)))) { - if (!m_data->m_statement) - MYSQL_ERROR(conn->m_mysql) - else if (mysql_stmt_prepare(m_data->m_statement, query.c_str(), query.size())) - STMT_ERROR(m_data->m_statement) - else { - m_data->m_bind_count = mysql_stmt_param_count(m_data->m_statement); - - if (m_data->m_bind_count > 0) { - m_data->m_raw_binds = new MYSQL_BIND[m_data->m_bind_count]; - - for (uint32_t i = 0; i < m_data->m_bind_count; i++) - m_data->m_binds.emplace_back(new bind(&m_data->m_raw_binds[i])); - } - } -} - -void statement::set_connection(connection_ref& connection) { m_connection = connection; } - -u64 statement::execute() { - if (m_data->m_raw_binds && mysql_stmt_bind_param(m_data->m_statement, m_data->m_raw_binds)) - STMT_ERROR(m_data->m_statement); - - if (mysql_stmt_execute(m_data->m_statement)) STMT_ERROR(m_data->m_statement); - - return mysql_stmt_affected_rows(m_data->m_statement); -} - -u64 statement::insert() { - if (m_data->m_raw_binds && mysql_stmt_bind_param(m_data->m_statement, m_data->m_raw_binds)) - STMT_ERROR(m_data->m_statement); - - if (mysql_stmt_execute(m_data->m_statement)) STMT_ERROR(m_data->m_statement); - - return mysql_stmt_insert_id(m_data->m_statement); -} - -result_set_ref statement::query() { - result_set_ref rs; - - if (m_data->m_raw_binds && mysql_stmt_bind_param(m_data->m_statement, m_data->m_raw_binds)) - STMT_ERROR_RETURN_RS(m_data->m_statement); - - if (mysql_stmt_execute(m_data->m_statement)) STMT_ERROR_RETURN_RS(m_data->m_statement); - - rs.reset(new result_set(m_parent, m_data)); - return rs; -} - -MAKE_SETTER(blob, stream_ref) - if (!value) return; - - value->seekg(0, std::ios_base::end); - u64 size = value->tellg(); - value->seekg(0); - - // allocate empty buffer - bind.set(MYSQL_TYPE_BLOB, nullptr, static_cast(size)); - // copy stream over - value->read(bind.buffer(), bind.length()); -} - -MAKE_SETTER(data, const data_ref&) - if (!value) return; - bind.set(MYSQL_TYPE_BLOB, value->get(), value->size()); -} - -MAKE_SETTER(date_time, const date_time&) - bind.m_time = value.mysql_time(); - bind.set(MYSQL_TYPE_DATETIME); -} - -MAKE_SETTER(date, const date_time&) - bind.m_time = value.date().mysql_time(); - bind.set(MYSQL_TYPE_DATE); -} - -MAKE_SETTER(time, const mariadb::time&) - bind.m_time = value.mysql_time(); - bind.set(MYSQL_TYPE_TIME); -} - -MAKE_SETTER(decimal, const decimal&) - std::string str = value.str(); - bind.set(MYSQL_TYPE_STRING, str.c_str(), str.size()); -} - -MAKE_SETTER(string, const std::string&) - bind.set(MYSQL_TYPE_STRING, value.c_str(), value.size()); -} - -MAKE_SETTER(boolean, bool) - bind.m_unsigned64 = value; - bind.set(MYSQL_TYPE_TINY); -} - -MAKE_SETTER(unsigned8, u8) - bind.m_unsigned64 = value; - bind.set(MYSQL_TYPE_TINY, nullptr, 0, true); -} - -MAKE_SETTER(signed8, s8) - bind.m_signed64 = value; - bind.set(MYSQL_TYPE_TINY); -} - -MAKE_SETTER(unsigned16, u16) - bind.m_unsigned64 = value; - bind.set(MYSQL_TYPE_SHORT, nullptr, 0, true); -} - -MAKE_SETTER(signed16, s16) - bind.m_signed64 = value; - bind.set(MYSQL_TYPE_SHORT); -} - -MAKE_SETTER(unsigned32, u32) - bind.m_unsigned64 = value; - bind.set(MYSQL_TYPE_LONG, nullptr, 0, true); -} - -MAKE_SETTER(signed32, s32) - bind.m_signed64 = value; - bind.set(MYSQL_TYPE_LONG); -} - -MAKE_SETTER(unsigned64, u64) - bind.m_unsigned64 = value; - bind.set(MYSQL_TYPE_LONGLONG, nullptr, 0, true); -} - -MAKE_SETTER(signed64, s64) - bind.m_signed64 = value; - bind.set(MYSQL_TYPE_LONGLONG); -} - -MAKE_SETTER(float, f32) - bind.m_float32[0] = value; - bind.set(MYSQL_TYPE_FLOAT); -} - -MAKE_SETTER(double, f64) - bind.m_double64 = value; - bind.set(MYSQL_TYPE_DOUBLE); -} - -void statement::set_null(u32 index) { - MAKE_SETTER_BODY - bind.set(MYSQL_TYPE_NULL); -} diff --git a/VCMP-LUA/modules/mariadb/src/time.cpp b/VCMP-LUA/modules/mariadb/src/time.cpp deleted file mode 100644 index 7fdab19..0000000 --- a/VCMP-LUA/modules/mariadb/src/time.cpp +++ /dev/null @@ -1,377 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2020. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include -#include -#include -#include -#include -#include -#include "private.hpp" - -#define MS_PER_SEC 1000 -#define MS_PER_MIN (MS_PER_SEC * 60) -#define MS_PER_HOUR (MS_PER_MIN * 60) -#define MS_PER_DAY (MS_PER_HOUR * 24) - -mariadb::time::time(u8 hour, u8 minute, u8 second, u16 millisecond) { - set(hour, minute, second, millisecond); -} - -mariadb::time::time(const time& t) { set(t.hour(), t.minute(), t.second(), t.millisecond()); } - -mariadb::time::time(const tm& t) { set(t.tm_hour, t.tm_min, t.tm_sec, 0); } - -mariadb::time::time(const time_t& t) { - tm ts; - localtime_safe(&ts, &t); - - set(ts.tm_hour, ts.tm_min, ts.tm_sec, 0); -} - -mariadb::time::time(const MYSQL_TIME& t) { set(t.hour, t.minute, t.second, t.second_part / 1000); } - -mariadb::time::time(const std::string& t) { set(t); } - -int mariadb::time::compare(const time& t) const { - if (hour() < t.hour()) return -1; - - if (hour() > t.hour()) return 1; - - if (minute() < t.minute()) return -1; - - if (minute() > t.minute()) return 1; - - if (second() < t.second()) return -1; - - if (second() > t.second()) return 1; - - if (millisecond() < t.millisecond()) return -1; - - return millisecond() == t.millisecond() ? 0 : 1; -} - -mariadb::time& mariadb::time::operator=(const time& t) { - set(t.hour(), t.minute(), t.second(), t.millisecond()); - return *this; -} - -bool mariadb::time::operator==(const time& t) const { return compare(t) == 0; } - -bool mariadb::time::operator!=(const time& t) const { return compare(t) != 0; } - -bool mariadb::time::operator<(const time& t) const { return compare(t) < 0; } - -bool mariadb::time::operator<=(const time& t) const { return compare(t) <= 0; } - -bool mariadb::time::operator>(const time& t) const { return compare(t) > 0; } - -bool mariadb::time::operator>=(const time& t) const { return compare(t) >= 0; } - -bool mariadb::time::set(u8 hour, u8 minute, u8 second, u16 millisecond) { - m_hour = hour; - m_minute = minute; - m_second = second; - m_millisecond = millisecond; - return true; -} - -mariadb::u8 mariadb::time::hour() const { return m_hour; } - -mariadb::u8 mariadb::time::hour(u8 hour) { - if (hour > 23) - MARIADB_ERROR_THROW_TIME(hour, minute(), second(), millisecond()); - - m_hour = hour; - - return m_hour; -} - -mariadb::u8 mariadb::time::minute() const { return m_minute; } - -mariadb::u8 mariadb::time::minute(u8 minute) { - if (minute > 59) - MARIADB_ERROR_THROW_TIME(hour(), minute, second(), millisecond()); - - m_minute = minute; - - return m_minute; -} - -mariadb::u8 mariadb::time::second() const { return m_second; } - -mariadb::u8 mariadb::time::second(u8 second) { - if (second > 61) - MARIADB_ERROR_THROW_TIME(hour(), minute(), second, millisecond()); - - m_second = second; - - return m_second; -} - -mariadb::u16 mariadb::time::millisecond() const { return m_millisecond; } - -mariadb::u16 mariadb::time::millisecond(u16 millisecond) { - if (millisecond > 999) - MARIADB_ERROR_THROW_TIME(hour(), minute(), second(), millisecond); - - m_millisecond = millisecond; - - return m_millisecond; -} - -mariadb::time mariadb::time::add_hours(s32 hours) const { - mariadb::time tmp = *this; - - if (hours == 0) return tmp; - - // hour overflow does not matter, as we dont care about days - hours = (hours + hour() + 24) % 24; - tmp.hour(hours); - return tmp; -} - -mariadb::time mariadb::time::add_minutes(s32 minutes) const { - mariadb::time tmp = *this; - - if (minutes == 0) return tmp; - - s32 hours = minutes / 60; - minutes = (minutes % 60) + minute(); - - if (minutes >= 60) - ++hours; - else if (minutes < 0) - --hours; - - if (hours != 0) tmp = tmp.add_hours(hours); - - tmp.minute((minutes + 60) % 60); - return tmp; -} - -mariadb::time mariadb::time::add_seconds(s32 seconds) const { - mariadb::time tmp = *this; - - if (seconds == 0) return tmp; - - s32 minutes = seconds / 60; - seconds = (seconds % 60) + second(); - - if (seconds >= 60) - ++minutes; - else if (seconds < 0) - --minutes; - - if (minutes != 0) tmp = tmp.add_minutes(minutes); - - tmp.second((seconds + 60) % 60); - return tmp; -} - -mariadb::time mariadb::time::add_milliseconds(s32 milliseconds) const { - mariadb::time tmp = *this; - - if (milliseconds == 0) return tmp; - - s32 seconds = milliseconds / 1000; - milliseconds = (milliseconds % 1000) + millisecond(); - - if (milliseconds > 999) - ++seconds; - else if (milliseconds < 0) - --seconds; - - if (seconds != 0) tmp = tmp.add_seconds(seconds); - - tmp.millisecond((milliseconds + 1000) % 1000); - return tmp; -} - -mariadb::time mariadb::time::subtract(const time_span& dur) const { - // copy and negate timespan - time_span tmp = dur; - tmp.negative(!dur.negative()); - - // add negated - return add(tmp); -} - -mariadb::time mariadb::time::add(const time_span& dur) const { - // negate if needed - s32 negative = dur.negative() ? -1 : 1; - time tmp = *this; - - tmp.add_hours(negative * dur.hours()); - tmp.add_minutes(negative * dur.minutes()); - tmp.add_seconds(negative * dur.seconds()); - tmp.add_milliseconds(negative * dur.milliseconds()); - return tmp; -} - -mariadb::time_span mariadb::time::time_between(const time& t) const { - // equal - if (t == *this) return time_span(0, 0, 0, 0, 0); - - // recursive call with negation - if (t > *this) { - time_span dur = t.time_between(*this); - dur.negative(true); - return dur; - } - - // calculate the ms representation of both - s64 ms = - (hour() * MS_PER_HOUR) + (minute() * MS_PER_MIN) + (second() * MS_PER_SEC) + millisecond(); - s64 t_ms = (t.hour() * MS_PER_HOUR) + (t.minute() * MS_PER_MIN) + (t.second() * MS_PER_SEC) + - t.millisecond(); - s64 total_ms = 0; - - // subtract the lesser from greater // TODO: is this case ever reached since we have recusive - // call on t > this? - if (t_ms > ms) - total_ms = MS_PER_DAY - (t_ms - ms); - else - total_ms = ms - t_ms; - - u32 hours = static_cast(total_ms / MS_PER_HOUR); - total_ms = total_ms % MS_PER_HOUR; - - u32 minutes = static_cast(total_ms / MS_PER_MIN); - total_ms = total_ms % MS_PER_MIN; - - u32 seconds = static_cast(total_ms / MS_PER_SEC); - total_ms = total_ms % MS_PER_SEC; - - return time_span(0, hours, minutes, seconds, static_cast(total_ms), false); -} - -time_t mariadb::time::mktime() const { - tm time_struct; - - time_struct.tm_year = 1900; - time_struct.tm_mon = 0; - time_struct.tm_mday = 1; - time_struct.tm_hour = hour(); - time_struct.tm_min = minute(); - time_struct.tm_sec = second(); - - return ::mktime(&time_struct); -} - -MYSQL_TIME mariadb::time::mysql_time() const { - MYSQL_TIME t; - - t.year = 0; - t.month = 0; - t.day = 0; - t.hour = hour(); - t.minute = minute(); - t.second = second(); - t.second_part = millisecond() * 1000u; - t.neg = false; - t.time_type = MYSQL_TIMESTAMP_TIME; - return t; -} - -double mariadb::time::diff_time(const time& t) const { - time_t time_val = mktime(); - time_t t_time_val = t.mktime(); - - return ::difftime(time_val, t_time_val); -} - -bool mariadb::time::is_valid() const { - return time::valid_time(hour(), minute(), second(), millisecond()); -} - -bool mariadb::time::valid_time(u8 hour, u8 minute, u8 second, u16 millisecond) { - // seconds go up to 61 to allow for leap seconds - return hour < 24 && minute < 60 && second <= 61 && millisecond < 1000; -} - -mariadb::time mariadb::time::now() { - using namespace std::chrono; - auto now = system_clock::now(); - - time_t local_time = system_clock::to_time_t(now); - tm ts; - localtime_safe(&ts, &local_time); - - auto millis = duration_cast(now.time_since_epoch()).count() % 1000; - return mariadb::time(ts).add_milliseconds(static_cast(millis)); -} - -mariadb::time mariadb::time::now_utc() { - using namespace std::chrono; - auto now = system_clock::now(); - - time_t utc_time = system_clock::to_time_t(now); - tm ts; - gmtime_safe(&ts, &utc_time); - - auto millis = duration_cast(now.time_since_epoch()).count() % 1000; - return mariadb::time(ts).add_milliseconds(static_cast(millis)); -} - -bool mariadb::time::set(const std::string& t) { - std::stringstream stream(t); - - u8 h, m, s; - u16 s_h = 0, s_m = 0, s_s = 0, s_ms = 0; - char delim; - - // read formatted hours, check overflow before cast - if (stream >> s_h && s_h < 24) { - h = static_cast(s_h); - if (stream.eof()) return set(h, 0, 0, 0); - - // read formatted minutes, check overflow before cast - if (stream >> delim && stream >> s_m && s_m < 60) { - m = static_cast(s_m); - if (stream.eof()) return set(h, m, 0, 0); - - // read formatted seconds, check overflow before cast - if (stream >> delim && stream >> s_s && s_s < 62) { - s = static_cast(s_s); - if (stream.eof()) return set(h, m, s, 0); - - // read formatted millis - if (stream >> delim && stream >> s_ms) return set(h, m, s, s_ms); - } - } - } - - throw std::invalid_argument("invalid time format"); -} - -const std::string mariadb::time::str_time(bool with_millisecond) const { - std::stringstream stream; - stream.fill('0'); - - /* - * Note: the magic unary + forces conversion of unsigned char (u8) to a numeric printing type, - * otherwise it will - * be printed as char - */ - stream << std::setw(2) << +hour() << ":" << std::setw(2) << +minute() << ":" << std::setw(2) - << +second(); - - if (with_millisecond) stream << "." << std::setw(3) << millisecond(); - - return stream.str(); -} - -std::ostream& mariadb::operator<<(std::ostream& os, const time& t) { - os << t.str_time(true); - return os; -} diff --git a/VCMP-LUA/modules/mariadb/src/time_span.cpp b/VCMP-LUA/modules/mariadb/src/time_span.cpp deleted file mode 100644 index 7db0a10..0000000 --- a/VCMP-LUA/modules/mariadb/src/time_span.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include - -using namespace mariadb; - -time_span::time_span(u32 days, u8 hours, u8 minutes, u8 seconds, u16 milliseconds, bool negative) { - set(days, hours, minutes, seconds, milliseconds, negative); -} - -time_span::time_span(const time_span& dur) { - set(dur.days(), dur.hours(), dur.minutes(), dur.seconds(), dur.milliseconds(), dur.negative()); -} - -int time_span::compare(const time_span& ts) const { - if (negative() && !ts.negative()) return -1; - - if (!negative() && ts.negative()) return 1; - - if (zero() && ts.zero()) return 0; - - if (days() < ts.days()) return -1; - - if (days() > ts.days()) return 1; - - if (hours() < ts.hours()) return -1; - - if (hours() > ts.hours()) return 1; - - if (minutes() < ts.minutes()) return -1; - - if (minutes() > ts.minutes()) return 1; - - if (seconds() < ts.seconds()) return -1; - - if (seconds() > ts.seconds()) return 1; - - if (milliseconds() < ts.milliseconds()) return -1; - - return milliseconds() == ts.milliseconds() ? 0 : 1; -} - -time_span& time_span::operator=(const time_span& ts) { - set(ts.days(), ts.hours(), ts.minutes(), ts.seconds(), ts.milliseconds(), ts.negative()); - - return *this; -} - -bool time_span::operator==(const time_span& ts) const { return compare(ts) == 0; } - -bool time_span::operator!=(const time_span& ts) const { return compare(ts) != 0; } - -bool time_span::operator<(const time_span& ts) const { return compare(ts) < 0; } - -bool time_span::operator<=(const time_span& ts) const { return compare(ts) <= 0; } - -bool time_span::operator>(const time_span& ts) const { return compare(ts) > 0; } - -bool time_span::operator>=(const time_span& ts) const { return compare(ts) >= 0; } - -void time_span::set(u32 _days, u8 _hours, u8 _minutes, u8 _seconds, u16 _milliseconds, - bool _negative) { - negative(_negative); - days(_days); - hours(_hours); - minutes(_minutes); - seconds(_seconds); - milliseconds(_milliseconds); -} - -bool time_span::zero() const { - return m_days == 0 && m_hours == 0 && m_minutes == 0 && m_seconds == 0 && m_milliseconds == 0; -} - -u32 time_span::days() const { return m_days; } - -u32 time_span::days(u32 days) { return (m_days = days); } - -u8 time_span::hours() const { return m_hours; } - -u8 time_span::hours(u8 hours) { - if (hours > 23) throw std::invalid_argument("Hours must be < 24"); - - return (m_hours = hours); -} - -u8 time_span::minutes() const { return m_minutes; } - -u8 time_span::minutes(u8 minutes) { - if (minutes > 59) throw std::invalid_argument("Hours must be < 60"); - - return (m_minutes = minutes); -} - -u8 time_span::seconds() const { return m_seconds; } - -u8 time_span::seconds(u8 seconds) { - if (seconds > 60) throw std::invalid_argument("Hours must be < 61"); - - return (m_seconds = seconds); -} - -u16 time_span::milliseconds() const { return m_milliseconds; } - -u16 time_span::milliseconds(u16 milliseconds) { - if (milliseconds > 999) throw std::invalid_argument("Hours must be < 1000"); - - return (m_milliseconds = milliseconds); -} - -bool time_span::negative() const { return m_negative; } - -bool time_span::negative(bool negative) { return (m_negative = negative); } - -u64 time_span::total_hours() const { return m_days * 24u + m_hours; } - -u64 time_span::total_minutes() const { return total_hours() * 60u + m_minutes; } - -u64 time_span::total_seconds() const { return total_minutes() * 60u + m_seconds; } - -u64 time_span::total_milliseconds() const { return total_seconds() * 1000u + m_milliseconds; } - -std::ostream& mariadb::operator<<(std::ostream& os, const time_span& ts) { - if (ts.negative()) os << "negative "; - - os << ts.days() << " days, " << +ts.hours() << " hours, " << +ts.minutes() << " minutes, " - << +ts.seconds() << " seconds, " << ts.milliseconds() << " milliseconds"; - - return os; -} diff --git a/VCMP-LUA/modules/mariadb/src/transaction.cpp b/VCMP-LUA/modules/mariadb/src/transaction.cpp deleted file mode 100644 index 0ca8d9a..0000000 --- a/VCMP-LUA/modules/mariadb/src/transaction.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include - -using namespace mariadb; - -namespace { -const char* g_isolation_level[] = { - "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;", - "SET TRANSACTION ISOLATION LEVEL READ COMMITTED;", - "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;", - "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;", -}; - -const char* g_consistent_snapshot[] = { - "START TRANSACTION;", "START TRANSACTION WITH CONSISTENT SNAPSHOT;", -}; -} - -transaction::transaction(connection* conn, isolation::level level, bool consistent_snapshot) - : m_connection(conn) { - conn->execute(g_isolation_level[level]); - conn->execute(g_consistent_snapshot[consistent_snapshot]); -} - -transaction::~transaction() { - if (!m_connection) return; - - mysql_rollback(m_connection->m_mysql); - cleanup(); -} - -void transaction::cleanup() { - for (save_point* save_point : m_save_points) save_point->m_transaction = nullptr; - - m_save_points.clear(); -} - -void transaction::commit() { - if (!m_connection) return; - - mysql_commit(m_connection->m_mysql); - cleanup(); - m_connection = nullptr; -} - -save_point_ref transaction::create_save_point() { - if (!m_connection) return save_point_ref(); - - save_point* sp = new save_point(this); - m_save_points.push_back(sp); - return save_point_ref(sp); -} - -void transaction::remove_save_point(save_point* sv_point) { - m_save_points.erase(std::remove(m_save_points.begin(), m_save_points.end(), sv_point)); -} diff --git a/VCMP-LUA/modules/mariadb/src/worker.cpp b/VCMP-LUA/modules/mariadb/src/worker.cpp deleted file mode 100644 index 4a770ac..0000000 --- a/VCMP-LUA/modules/mariadb/src/worker.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#include "worker.hpp" -#include - -using namespace mariadb; -using namespace mariadb::concurrency; - -// -// Constructors -// -worker::worker() - : m_keep_handle(false), - m_handle(0), - m_status(status::removed), - m_command(command::query), - m_result(0) {} - -worker::worker(account_ref& account, handle handle, bool keep_handle, command::type command, - const std::string& query) - : m_keep_handle(keep_handle), - m_handle(handle), - m_status(handle > 0 ? status::waiting : status::removed), - m_command(command), - m_result(0), - m_query(query), - m_account(account) {} - -worker::worker(account_ref& account, handle handle, bool keep_handle, command::type command, - statement_ref& statement) - : m_keep_handle(keep_handle), - m_handle(handle), - m_status(handle > 0 ? status::waiting : status::removed), - m_command(command), - m_result(0), - m_account(account), - m_statement(statement) {} - -// -// Get informations -// -status::type worker::status() const { return m_status; } - -bool worker::keep_handle() const { return m_keep_handle; } - -mariadb::handle worker::get_handle() const { return m_handle; } - -// -// Get result / result_set -// -u64 worker::result() const { return m_result; } - -result_set_ref worker::result_set() const { return m_result_set; } - -// -// Do the actual job -// -void worker::execute() { - m_status = status::executing; - - try { - connection_ref connection = - m_statement ? m_statement->m_connection : connection::create(m_account); - - // - // Make sure auto commit mode is on before continuing... - // - connection->set_auto_commit(true); - connection->connect(); - - switch (m_command) { - case command::execute: - if (m_statement) - m_result = m_statement->execute(); - else - m_result = connection->execute(m_query.c_str()); - break; - - case command::insert: - if (m_statement) - m_result = m_statement->insert(); - else - m_result = connection->insert(m_query.c_str()); - break; - - case command::query: - if (m_statement) - m_result_set = m_statement->query(); - else - m_result_set = connection->query(m_query.c_str()); - break; - } - - m_status = status::succeed; - } catch (const std::exception& e) { - std::cout << e.what() << std::endl; - m_status = status::failed; - } -} diff --git a/VCMP-LUA/modules/mariadb/src/worker.hpp b/VCMP-LUA/modules/mariadb/src/worker.hpp deleted file mode 100644 index bc5b02f..0000000 --- a/VCMP-LUA/modules/mariadb/src/worker.hpp +++ /dev/null @@ -1,69 +0,0 @@ -// -// M A R I A D B + + -// -// Copyright Sylvain Rochette Langlois 2013, -// Frantisek Boranek 2015, -// The ViaDuck Project 2016 - 2018. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _MARIADB_WORKER_HPP_ -#define _MARIADB_WORKER_HPP_ - -#include -#include - -namespace mariadb { -using namespace concurrency; - -namespace command { -enum type { execute, insert, query }; -} - -// -// Worker entity used by concurrency namespace -// -class worker { - public: - // - // Constructor - // - worker(); - worker(account_ref& account, handle hnd, bool keep_handle, command::type command, - const std::string& query); - worker(account_ref& account, handle hnd, bool keep_handle, command::type command, - statement_ref& statement); - - // - // Get informations - // - status::type status() const; - handle get_handle() const; - bool keep_handle() const; - - // - // Get result / result_set - // - u64 result() const; - result_set_ref result_set() const; - - // - // Do the actual job - // - void execute(); - - private: - bool m_keep_handle; - handle m_handle; - status::type m_status; - command::type m_command; - u64 m_result; - std::string m_query; - account_ref m_account; - result_set_ref m_result_set; - statement_ref m_statement; -}; -} - -#endif diff --git a/VCMP-LUA/modules/requests/Makefile b/VCMP-LUA/modules/requests/Makefile deleted file mode 100644 index 1a388d3..0000000 --- a/VCMP-LUA/modules/requests/Makefile +++ /dev/null @@ -1,194 +0,0 @@ -# GNU Make project makefile autogenerated by Premake - -ifndef config - config=release32 -endif - -ifndef verbose - SILENT = @ -endif - -.PHONY: clean prebuild prelink - -ifeq ($(config),release32) - RESCOMP = windres - TARGETDIR = ../../../bin/Release32-windows-x86/module-cpr - TARGET = $(TARGETDIR)/module-cpr_x86.lib - OBJDIR = ../../../bin/interm/Release32-windows-x86/module-cpr - DEFINES += -D_x32 -DCURL_STATICLIB - INCLUDES += -Icpr/include - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += -lcpr.lib -lmongoose.lib -llibcurl.lib - LDDEPS += - ALL_LDFLAGS += $(LDFLAGS) -Lcpr/lib -L/usr/lib32 -m32 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -ifeq ($(config),release) - RESCOMP = windres - TARGETDIR = ../../../bin/Release-windows-x86_64/module-cpr - TARGET = $(TARGETDIR)/module-cpr_x64.lib - OBJDIR = ../../../bin/interm/Release-windows-x86_64/module-cpr - DEFINES += -DCURL_STATICLIB - INCLUDES += -Icpr/include - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += -lcpr.lib -lmongoose.lib -llibcurl.lib - LDDEPS += - ALL_LDFLAGS += $(LDFLAGS) -Lcpr/lib -L/usr/lib64 -m64 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -OBJECTS := \ - $(OBJDIR)/auth.o \ - $(OBJDIR)/bearer.o \ - $(OBJDIR)/cookies.o \ - $(OBJDIR)/cprtypes.o \ - $(OBJDIR)/curl_container.o \ - $(OBJDIR)/curlholder.o \ - $(OBJDIR)/error.o \ - $(OBJDIR)/multipart.o \ - $(OBJDIR)/parameters.o \ - $(OBJDIR)/payload.o \ - $(OBJDIR)/proxies.o \ - $(OBJDIR)/response.o \ - $(OBJDIR)/session.o \ - $(OBJDIR)/timeout.o \ - $(OBJDIR)/unix_socket.o \ - $(OBJDIR)/util.o \ - -RESOURCES := \ - -CUSTOMFILES := \ - -SHELLTYPE := posix -ifeq (.exe,$(findstring .exe,$(ComSpec))) - SHELLTYPE := msdos -endif - -$(TARGET): $(GCH) ${CUSTOMFILES} $(OBJECTS) $(LDDEPS) $(RESOURCES) | $(TARGETDIR) - @echo Linking module-cpr - $(SILENT) $(LINKCMD) - $(POSTBUILDCMDS) - -$(CUSTOMFILES): | $(OBJDIR) - -$(TARGETDIR): - @echo Creating $(TARGETDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(TARGETDIR) -else - $(SILENT) mkdir $(subst /,\\,$(TARGETDIR)) -endif - -$(OBJDIR): - @echo Creating $(OBJDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(OBJDIR) -else - $(SILENT) mkdir $(subst /,\\,$(OBJDIR)) -endif - -clean: - @echo Cleaning module-cpr -ifeq (posix,$(SHELLTYPE)) - $(SILENT) rm -f $(TARGET) - $(SILENT) rm -rf $(OBJDIR) -else - $(SILENT) if exist $(subst /,\\,$(TARGET)) del $(subst /,\\,$(TARGET)) - $(SILENT) if exist $(subst /,\\,$(OBJDIR)) rmdir /s /q $(subst /,\\,$(OBJDIR)) -endif - -prebuild: - $(PREBUILDCMDS) - -prelink: - $(PRELINKCMDS) - -ifneq (,$(PCH)) -$(OBJECTS): $(GCH) $(PCH) | $(OBJDIR) -$(GCH): $(PCH) | $(OBJDIR) - @echo $(notdir $<) - $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" -else -$(OBJECTS): | $(OBJDIR) -endif - -$(OBJDIR)/auth.o: cpr/src/auth.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/bearer.o: cpr/src/bearer.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/cookies.o: cpr/src/cookies.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/cprtypes.o: cpr/src/cprtypes.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/curl_container.o: cpr/src/curl_container.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/curlholder.o: cpr/src/curlholder.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/error.o: cpr/src/error.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/multipart.o: cpr/src/multipart.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/parameters.o: cpr/src/parameters.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/payload.o: cpr/src/payload.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/proxies.o: cpr/src/proxies.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/response.o: cpr/src/response.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/session.o: cpr/src/session.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/timeout.o: cpr/src/timeout.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/unix_socket.o: cpr/src/unix_socket.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/util.o: cpr/src/util.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" - --include $(OBJECTS:%.o=%.d) -ifneq (,$(PCH)) - -include $(OBJDIR)/$(notdir $(PCH)).d -endif \ No newline at end of file diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/api.h b/VCMP-LUA/modules/requests/cpr/include/cpr/api.h deleted file mode 100644 index cabea7c..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/api.h +++ /dev/null @@ -1,222 +0,0 @@ -#ifndef CPR_API_H -#define CPR_API_H - -#include -#include -#include -#include -#include - -#include "cpr/auth.h" -#include "cpr/bearer.h" -#include "cpr/cprtypes.h" -#include "cpr/digest.h" -#include "cpr/multipart.h" -#include "cpr/ntlm.h" -#include "cpr/payload.h" -#include "cpr/response.h" -#include "cpr/session.h" -#include - -namespace cpr { - -using AsyncResponse = std::future; - -namespace priv { - -template -void set_option(Session& session, T&& t) { - session.SetOption(std::forward(t)); -} - -template -void set_option(Session& session, T&& t, Ts&&... ts) { - set_option(session, std::forward(t)); - set_option(session, std::forward(ts)...); -} - -} // namespace priv - -// Get methods -template -Response Get(Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Get(); -} - -// Get async methods -template -AsyncResponse GetAsync(Ts... ts) { - return std::async( - std::launch::async, [](Ts... ts) { return Get(std::move(ts)...); }, std::move(ts)...); -} - -// Get callback methods -template -auto GetCallback(Then then, Ts... ts) -> std::future { - return std::async( - std::launch::async, [](Then then, Ts... ts) { return then(Get(std::move(ts)...)); }, - std::move(then), std::move(ts)...); -} - -// Post methods -template -Response Post(Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Post(); -} - -// Post async methods -template -AsyncResponse PostAsync(Ts... ts) { - return std::async( - std::launch::async, [](Ts... ts) { return Post(std::move(ts)...); }, std::move(ts)...); -} - -// Post callback methods -template -auto PostCallback(Then then, Ts... ts) -> std::future { - return std::async( - std::launch::async, [](Then then, Ts... ts) { return then(Post(std::move(ts)...)); }, - std::move(then), std::move(ts)...); -} - -// Put methods -template -Response Put(Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Put(); -} - -// Put async methods -template -AsyncResponse PutAsync(Ts... ts) { - return std::async( - std::launch::async, [](Ts... ts) { return Put(std::move(ts)...); }, std::move(ts)...); -} - -// Put callback methods -template -auto PutCallback(Then then, Ts... ts) -> std::future { - return std::async( - std::launch::async, [](Then then, Ts... ts) { return then(Put(std::move(ts)...)); }, - std::move(then), std::move(ts)...); -} - -// Head methods -template -Response Head(Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Head(); -} - -// Head async methods -template -AsyncResponse HeadAsync(Ts... ts) { - return std::async( - std::launch::async, [](Ts... ts) { return Head(std::move(ts)...); }, std::move(ts)...); -} - -// Head callback methods -template -auto HeadCallback(Then then, Ts... ts) -> std::future { - return std::async( - std::launch::async, [](Then then, Ts... ts) { return then(Head(std::move(ts)...)); }, - std::move(then), std::move(ts)...); -} - -// Delete methods -template -Response Delete(Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Delete(); -} - -// Delete async methods -template -AsyncResponse DeleteAsync(Ts... ts) { - return std::async( - std::launch::async, [](Ts... ts) { return Delete(std::move(ts)...); }, - std::move(ts)...); -} - -// Delete callback methods -template -auto DeleteCallback(Then then, Ts... ts) -> std::future { - return std::async( - std::launch::async, [](Then then, Ts... ts) { return then(Delete(std::move(ts)...)); }, - std::move(then), std::move(ts)...); -} - -// Options methods -template -Response Options(Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Options(); -} - -// Options async methods -template -AsyncResponse OptionsAsync(Ts... ts) { - return std::async( - std::launch::async, [](Ts... ts) { return Options(std::move(ts)...); }, - std::move(ts)...); -} - -// Options callback methods -template -auto OptionsCallback(Then then, Ts... ts) - -> std::future { - return std::async( - std::launch::async, [](Then then, Ts... ts) { return then(Options(std::move(ts)...)); }, - std::move(then), std::move(ts)...); -} - -// Patch methods -template -Response Patch(Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Patch(); -} - -// Patch async methods -template -AsyncResponse PatchAsync(Ts... ts) { - return std::async( - std::launch::async, [](Ts... ts) { return Patch(std::move(ts)...); }, std::move(ts)...); -} - -// Patch callback methods -template -auto PatchCallback(Then then, Ts... ts) -> std::future { - return std::async( - std::launch::async, [](Then then, Ts... ts) { return then(Patch(std::move(ts)...)); }, - std::move(then), std::move(ts)...); -} - -// Download methods -template -Response Download(std::ofstream& file, Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Download(file); -} - -// Download with user callback -template -Response Download(const WriteCallback& write, Ts&&... ts) { - Session session; - priv::set_option(session, std::forward(ts)...); - return session.Download(write); -} - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/auth.h b/VCMP-LUA/modules/requests/cpr/include/cpr/auth.h deleted file mode 100644 index a1b5fde..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/auth.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef CPR_AUTH_H -#define CPR_AUTH_H - -#include - -#include - -namespace cpr { - -class Authentication { - public: - Authentication(const std::string& username, const std::string& password) - : auth_string_{username + ":" + password} {} - Authentication(std::string&& username, std::string&& password) - : auth_string_{std::move(username) + ":" + std::move(password)} {} - virtual ~Authentication() = default; - - virtual const char* GetAuthString() const noexcept; - - protected: - std::string auth_string_; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/bearer.h b/VCMP-LUA/modules/requests/cpr/include/cpr/bearer.h deleted file mode 100644 index 617326b..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/bearer.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef CPR_BEARER_H -#define CPR_BEARER_H - -#include - -#include - -namespace cpr { - -class Bearer { - public: - Bearer(const std::string& token) - : token_string_{token} {} - Bearer(std::string&& token) - : token_string_{std::move(token)} {} - virtual ~Bearer() = default; - - virtual const char* GetToken() const noexcept; - - protected: - std::string token_string_; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/body.h b/VCMP-LUA/modules/requests/cpr/include/cpr/body.h deleted file mode 100644 index 96ca259..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/body.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef CPR_BODY_H -#define CPR_BODY_H - -#include -#include - -#include "cpr/cprtypes.h" - -namespace cpr { - -class Body : public StringHolder { - public: - Body() : StringHolder() {} - Body(const std::string& body) : StringHolder(body) {} - Body(std::string&& body) : StringHolder(std::move(body)) {} - Body(const char* body) : StringHolder(body) {} - Body(const char* str, size_t len) : StringHolder(str, len) {} - Body(const std::initializer_list args) : StringHolder(args) {} - ~Body() override = default; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/callback.h b/VCMP-LUA/modules/requests/cpr/include/cpr/callback.h deleted file mode 100644 index 131f519..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/callback.h +++ /dev/null @@ -1,71 +0,0 @@ -#ifndef CPR_CALLBACK_H -#define CPR_CALLBACK_H - -#include "cprtypes.h" - -#include - -namespace cpr { - -class ReadCallback { - public: - ReadCallback() {} - ReadCallback(std::function callback) - : size{-1}, callback{callback} {} - ReadCallback(cpr_off_t size, std::function callback) - : size{size}, callback{callback} {} - - cpr_off_t size; - std::function callback; -}; - -class HeaderCallback { - public: - HeaderCallback() {} - HeaderCallback(std::function callback) : callback(callback) {} - - std::function callback; -}; - -class WriteCallback { - public: - WriteCallback() {} - WriteCallback(std::function callback) : callback(callback) {} - - std::function callback; -}; - -class ProgressCallback { - public: - ProgressCallback() {} - ProgressCallback(std::function - callback) - : callback(callback) {} - - std::function - callback; -}; - -class DebugCallback { - public: - enum class InfoType { - TEXT = 0, - HEADER_IN = 1, - HEADER_OUT = 2, - DATA_IN = 3, - DATA_OUT = 4, - SSL_DATA_IN = 5, - SSL_DATA_OUT = 6, - }; - DebugCallback() {} - DebugCallback(std::function callback) - : callback(callback) {} - - std::function callback; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/connect_timeout.h b/VCMP-LUA/modules/requests/cpr/include/cpr/connect_timeout.h deleted file mode 100644 index d608b98..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/connect_timeout.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef CPR_CONNECT_TIMEOUT_H -#define CPR_CONNECT_TIMEOUT_H - -#include "cpr/timeout.h" - -namespace cpr { - -class ConnectTimeout : public Timeout { - public: - ConnectTimeout(const std::chrono::milliseconds& duration) : Timeout{duration} {} - ConnectTimeout(const std::int32_t& milliseconds) : Timeout{milliseconds} {} -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/cookies.h b/VCMP-LUA/modules/requests/cpr/include/cpr/cookies.h deleted file mode 100644 index 2b236f1..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/cookies.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef CPR_COOKIES_H -#define CPR_COOKIES_H - -#include "cpr/curlholder.h" -#include -#include -#include -#include - -namespace cpr { - -class Cookies { - public: - /** - * Should we URL-encode cookies when making a request. - * Based on RFC6265, it is recommended but not mandatory to encode cookies. - * - * ------- - * To maximize compatibility with user agents, servers that wish to - * store arbitrary data in a cookie-value SHOULD encode that data, for - * example, using Base64 [RFC4648]. - * ------- - * Source: RFC6265 (https://www.ietf.org/rfc/rfc6265.txt) - **/ - bool encode{true}; - - Cookies(bool encode = true) : encode(encode) {} - Cookies(const std::initializer_list>& pairs, - bool encode = true) - : encode(encode), map_{pairs} {} - Cookies(const std::map& map, bool encode = true) - : encode(encode), map_{map} {} - - std::string& operator[](const std::string& key); - std::string GetEncoded(const CurlHolder& holder) const; - - using iterator = std::map::iterator; - using const_iterator = std::map::const_iterator; - - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - const_iterator cbegin() const; - const_iterator cend() const; - - private: - std::map map_; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/cpr.h b/VCMP-LUA/modules/requests/cpr/include/cpr/cpr.h deleted file mode 100644 index 2828d38..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/cpr.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef CPR_CPR_H -#define CPR_CPR_H - -#include "cpr/api.h" -#include "cpr/auth.h" -#include "cpr/cprtypes.h" -#include "cpr/response.h" -#include "cpr/session.h" -#include "cpr/status_codes.h" - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/cprtypes.h b/VCMP-LUA/modules/requests/cpr/include/cpr/cprtypes.h deleted file mode 100644 index 12fe3fe..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/cprtypes.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef CPR_CPR_TYPES_H -#define CPR_CPR_TYPES_H - -#include -#include -#include -#include -#include -#include - -namespace cpr { - -/** - * Wrapper around "curl_off_t" to prevent applications from having to link against libcurl. - **/ -using cpr_off_t = curl_off_t; - -template -class StringHolder { - public: - StringHolder() {} - explicit StringHolder(const std::string& str) : str_(str) {} - explicit StringHolder(std::string&& str) : str_(std::move(str)) {} - explicit StringHolder(const char* str) : str_(str) {} - StringHolder(const char* str, size_t len) : str_(str, len) {} - StringHolder(const std::initializer_list args) { - str_ = std::accumulate(args.begin(), args.end(), str_); - } - virtual ~StringHolder() = default; - - operator std::string() const { - return str_; - } - - T operator+(const char* rhs) const { - return T(str_ + rhs); - } - T operator+(const std::string& rhs) const { - return T(str_ + rhs); - } - T operator+(const StringHolder& rhs) const { - return T(str_ + rhs.str_); - } - - void operator+=(const char* rhs) { - str_ += rhs; - } - void operator+=(const std::string& rhs) { - str_ += rhs; - } - void operator+=(const StringHolder& rhs) { - str_ += rhs; - } - - bool operator==(const char* rhs) const { - return str_.compare(rhs) == 0; - } - bool operator==(const std::string& rhs) const { - return str_ == rhs; - } - bool operator==(const StringHolder& rhs) const { - return str_ == rhs.str_; - } - - bool operator!=(const char* rhs) const { - return str_.c_str() != rhs; - } - bool operator!=(const std::string& rhs) const { - return str_ != rhs; - } - bool operator!=(const StringHolder& rhs) const { - return str_ != rhs.str_; - } - - const std::string& str() { - return str_; - } - const std::string& str() const { - return str_; - } - const char* c_str() const { - return str_.c_str(); - } - const char* data() const { - return str_.data(); - } - - protected: - std::string str_{}; -}; - -template -std::ostream& operator<<(std::ostream& os, const StringHolder& s) { - os << s.str(); - return os; -} - -class Url : public StringHolder { - public: - Url() : StringHolder() {} - Url(const std::string& url) : StringHolder(url) {} - Url(std::string&& url) : StringHolder(std::move(url)) {} - Url(const char* url) : StringHolder(url) {} - Url(const char* str, size_t len) : StringHolder(std::string(str, len)) {} - Url(const std::initializer_list args) : StringHolder(args) {} - ~Url() override = default; -}; - -struct CaseInsensitiveCompare { - bool operator()(const std::string& a, const std::string& b) const noexcept; -}; - -using Header = std::map; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/curl_container.h b/VCMP-LUA/modules/requests/cpr/include/cpr/curl_container.h deleted file mode 100644 index 0740ead..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/curl_container.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef CURL_CONTAINER_H -#define CURL_CONTAINER_H - -#include -#include -#include -#include - -#include "cpr/curlholder.h" - - -namespace cpr { - -struct Parameter { - Parameter(const std::string& key, const std::string& value) - : key{key}, value{value} {} - Parameter(std::string&& key, std::string&& value) - : key{std::move(key)}, value{std::move(value)} {} - - std::string key; - std::string value; -}; - -struct Pair { - Pair(const std::string& p_key, const std::string& p_value) - : key(p_key), value(p_value) {} - Pair(std::string&& p_key, std::string&& p_value) - : key(std::move(p_key)), value(std::move(p_value)) {} - - std::string key; - std::string value; -}; - - -template -class CurlContainer { - public: - CurlContainer() = default; - CurlContainer(const std::initializer_list&); - - public: - void Add(const std::initializer_list&); - void Add(const T&); - - public: - const std::string GetContent(const CurlHolder&) const; - - protected: - std::vector containerList_; -}; - -} // namespace cpr - -#endif // diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/curlholder.h b/VCMP-LUA/modules/requests/cpr/include/cpr/curlholder.h deleted file mode 100644 index 6fd97ec..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/curlholder.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef CPR_CURL_HOLDER_H -#define CPR_CURL_HOLDER_H - -#include -#include - -#include - -namespace cpr { -struct CurlHolder { - private: - /** - * Mutex for curl_easy_init(). - * curl_easy_init() is not thread save. - * References: - * https://curl.haxx.se/libcurl/c/curl_easy_init.html - * https://curl.haxx.se/libcurl/c/threadsafe.html - **/ - static std::mutex curl_easy_init_mutex_; - - public: - CURL* handle{nullptr}; - struct curl_slist* chunk{nullptr}; - struct curl_httppost* formpost{nullptr}; - char error[CURL_ERROR_SIZE]; - - CurlHolder(); - ~CurlHolder(); - - /** - * Uses curl_easy_escape(...) for escaping the given string. - **/ - std::string urlEncode(const std::string& s) const; - - /** - * Uses curl_easy_unescape(...) for unescaping the given string. - **/ - std::string urlDecode(const std::string& s) const; -}; -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/digest.h b/VCMP-LUA/modules/requests/cpr/include/cpr/digest.h deleted file mode 100644 index 50cefdf..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/digest.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef CPR_DIGEST_H -#define CPR_DIGEST_H - -#include "cpr/auth.h" - -namespace cpr { - -class Digest : public Authentication { - public: - Digest(const std::string& username, const std::string& password) - : Authentication{username, password} {} -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/error.h b/VCMP-LUA/modules/requests/cpr/include/cpr/error.h deleted file mode 100644 index d82dab2..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/error.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef CPR_ERROR_H -#define CPR_ERROR_H - -#include -#include - -#include "cpr/cprtypes.h" -#include - -namespace cpr { - -enum class ErrorCode { - OK = 0, - CONNECTION_FAILURE, - EMPTY_RESPONSE, - HOST_RESOLUTION_FAILURE, - INTERNAL_ERROR, - INVALID_URL_FORMAT, - NETWORK_RECEIVE_ERROR, - NETWORK_SEND_FAILURE, - OPERATION_TIMEDOUT, - PROXY_RESOLUTION_FAILURE, - SSL_CONNECT_ERROR, - SSL_LOCAL_CERTIFICATE_ERROR, - SSL_REMOTE_CERTIFICATE_ERROR, - SSL_CACERT_ERROR, - GENERIC_SSL_ERROR, - UNSUPPORTED_PROTOCOL, - REQUEST_CANCELLED, - UNKNOWN_ERROR = 1000, -}; - -class Error { - public: - Error() : code{ErrorCode::OK} {} - - template - Error(const std::int32_t& curl_code, TextType&& p_error_message) - : code{getErrorCodeForCurlError(curl_code)}, - message(std::forward(p_error_message)) {} - - explicit operator bool() const { - return code != ErrorCode::OK; - } - - ErrorCode code; - std::string message; - - private: - static ErrorCode getErrorCodeForCurlError(std::int32_t curl_code); -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/limit_rate.h b/VCMP-LUA/modules/requests/cpr/include/cpr/limit_rate.h deleted file mode 100644 index 9d3931d..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/limit_rate.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef CPR_SPEED_LIMIT_H -#define CPR_SPEED_LIMIT_H - -#include - -namespace cpr { - -class LimitRate { - public: - LimitRate(const std::int64_t downrate, const std::int64_t uprate) : downrate(downrate), uprate(uprate) {} - - std::int64_t downrate = 0; - std::int64_t uprate = 0; -}; - -} // namespace cpr - -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/low_speed.h b/VCMP-LUA/modules/requests/cpr/include/cpr/low_speed.h deleted file mode 100644 index 394a438..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/low_speed.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef CPR_LOW_SPEED_H -#define CPR_LOW_SPEED_H - -#include - -namespace cpr { - -class LowSpeed { - public: - LowSpeed(const std::int32_t limit, const std::int32_t time) : limit(limit), time(time) {} - - std::int32_t limit; - std::int32_t time; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/max_redirects.h b/VCMP-LUA/modules/requests/cpr/include/cpr/max_redirects.h deleted file mode 100644 index 4d3dea4..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/max_redirects.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef CPR_MAX_REDIRECTS_H -#define CPR_MAX_REDIRECTS_H - -#include - -namespace cpr { - -class MaxRedirects { - public: - explicit MaxRedirects(const std::int32_t number_of_redirects) - : number_of_redirects(number_of_redirects) {} - - std::int32_t number_of_redirects; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/multipart.h b/VCMP-LUA/modules/requests/cpr/include/cpr/multipart.h deleted file mode 100644 index 2bc81ed..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/multipart.h +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef CPR_MULTIPART_H -#define CPR_MULTIPART_H - -#include -#include -#include -#include -#include - -namespace cpr { - -struct File { - explicit File(std::string&& filepath) : filepath(std::move(filepath)) {} - explicit File(const std::string& filepath) : filepath(filepath) {} - const std::string filepath; -}; - -struct Buffer { - typedef const unsigned char* data_t; - - template - explicit Buffer(Iterator begin, Iterator end, std::string&& filename) - : data{reinterpret_cast(&(*begin))}, datalen{static_cast( - std::distance(begin, end))}, - filename(std::move(filename)) { - is_random_access_iterator(begin, end); - static_assert(sizeof(*begin) == 1, "only byte buffers can be used"); - } - - template - typename std::enable_if::iterator_category, - std::random_access_iterator_tag>::value>::type - is_random_access_iterator(Iterator /* begin */, Iterator /* end */) {} - - data_t data; - unsigned long datalen; - const std::string filename; -}; - -struct Part { - Part(const std::string& name, const std::string& value, const std::string& content_type = {}) - : name{name}, value{value}, - content_type{content_type}, is_file{false}, is_buffer{false} {} - Part(const std::string& name, const std::int32_t& value, const std::string& content_type = {}) - : name{name}, value{std::to_string(value)}, - content_type{content_type}, is_file{false}, is_buffer{false} {} - Part(const std::string& name, const File& file, const std::string& content_type = {}) - : name{name}, value{file.filepath}, - content_type{content_type}, is_file{true}, is_buffer{false} {} - Part(const std::string& name, const Buffer& buffer, const std::string& content_type = {}) - : name{name}, value{buffer.filename}, content_type{content_type}, data{buffer.data}, - datalen{buffer.datalen}, is_file{false}, is_buffer{true} {} - - std::string name; - std::string value; - std::string content_type; - Buffer::data_t data; - unsigned long datalen; - bool is_file; - bool is_buffer; -}; - -class Multipart { - public: - Multipart(const std::initializer_list& parts); - - std::vector parts; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/ntlm.h b/VCMP-LUA/modules/requests/cpr/include/cpr/ntlm.h deleted file mode 100644 index db6ca5e..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/ntlm.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef CPR_NTLM_H -#define CPR_NTLM_H - -#include "auth.h" -#include - -namespace cpr { - -class NTLM : public Authentication { - public: - NTLM(const std::string& username, const std::string& password) - : Authentication{username, password} {} -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/parameters.h b/VCMP-LUA/modules/requests/cpr/include/cpr/parameters.h deleted file mode 100644 index 8cc2ec7..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/parameters.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef CPR_PARAMETERS_H -#define CPR_PARAMETERS_H - -#include -#include -#include -#include - -#include "cpr/curl_container.h" - -namespace cpr { - -class Parameters : public CurlContainer { - public: - Parameters() = default; - Parameters(const std::initializer_list& parameters); -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/payload.h b/VCMP-LUA/modules/requests/cpr/include/cpr/payload.h deleted file mode 100644 index fa10b0e..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/payload.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef CPR_PAYLOAD_H -#define CPR_PAYLOAD_H - -#include -#include -#include -#include - -#include "cpr/curl_container.h" -#include - -namespace cpr { - - -class Payload : public CurlContainer { - public: - template - Payload(const It begin, const It end) { - for (It pair = begin; pair != end; ++pair) { - Add(*pair); - } - } - Payload(const std::initializer_list& pairs); -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/proxies.h b/VCMP-LUA/modules/requests/cpr/include/cpr/proxies.h deleted file mode 100644 index ba68fa5..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/proxies.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef CPR_PROXIES_H -#define CPR_PROXIES_H - -#include -#include -#include -#include - -namespace cpr { - -class Proxies { - public: - Proxies() {} - Proxies(const std::initializer_list>& hosts); - - bool has(const std::string& protocol) const; - const std::string& operator[](const std::string& protocol); - - private: - std::map hosts_; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/response.h b/VCMP-LUA/modules/requests/cpr/include/cpr/response.h deleted file mode 100644 index 912283a..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/response.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef CPR_RESPONSE_H -#define CPR_RESPONSE_H - -#include -#include -#include -#include -#include -#include -#include - -#include "cpr/cookies.h" -#include "cpr/cprtypes.h" -#include "cpr/error.h" -#include "cpr/ssl_options.h" -#include "cpr/util.h" - -namespace cpr { - -class Response { - private: - std::shared_ptr curl_; - - public: - long status_code; - std::string text; - Header header; - Url url; - double elapsed; - Cookies cookies; - Error error; - std::string raw_header; - std::string status_line; - std::string reason; - cpr_off_t uploaded_bytes; - cpr_off_t downloaded_bytes; - long redirect_count; - - public: - Response() = default; - Response(std::shared_ptr curl, std::string&& p_text, std::string&& p_header_string, - Cookies&& p_cookies, Error&& p_error); - std::vector GetCertInfo(); -}; -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/session.h b/VCMP-LUA/modules/requests/cpr/include/cpr/session.h deleted file mode 100644 index 6f96e4d..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/session.h +++ /dev/null @@ -1,125 +0,0 @@ -#ifndef CPR_SESSION_H -#define CPR_SESSION_H - -#include -#include -#include - -#include "cpr/auth.h" -#include "cpr/bearer.h" -#include "cpr/body.h" -#include "cpr/connect_timeout.h" -#include "cpr/cookies.h" -#include "cpr/cprtypes.h" -#include "cpr/digest.h" -#include "cpr/limit_rate.h" -#include "cpr/low_speed.h" -#include "cpr/max_redirects.h" -#include "cpr/multipart.h" -#include "cpr/ntlm.h" -#include "cpr/parameters.h" -#include "cpr/payload.h" -#include "cpr/proxies.h" -#include "cpr/response.h" -#include "cpr/ssl_options.h" -#include "cpr/timeout.h" -#include "cpr/unix_socket.h" -#include "cpr/user_agent.h" -#include "cpr/verbose.h" -#include "cpr/callback.h" - -namespace cpr { - -class Session { - public: - Session(); - ~Session(); - - Session(Session&& other); - Session& operator=(Session&& other); - - void SetUrl(const Url& url); - void SetParameters(const Parameters& parameters); - void SetParameters(Parameters&& parameters); - void SetHeader(const Header& header); - void SetTimeout(const Timeout& timeout); - void SetConnectTimeout(const ConnectTimeout& timeout); - void SetAuth(const Authentication& auth); - void SetDigest(const Digest& auth); - void SetUserAgent(const UserAgent& ua); - void SetPayload(Payload&& payload); - void SetPayload(const Payload& payload); - void SetProxies(Proxies&& proxies); - void SetProxies(const Proxies& proxies); - void SetMultipart(Multipart&& multipart); - void SetMultipart(const Multipart& multipart); - void SetNTLM(const NTLM& auth); - void SetRedirect(const bool& redirect); - void SetMaxRedirects(const MaxRedirects& max_redirects); - void SetCookies(const Cookies& cookies); - void SetBody(Body&& body); - void SetBody(const Body& body); - void SetLowSpeed(const LowSpeed& low_speed); - void SetVerifySsl(const VerifySsl& verify); - void SetUnixSocket(const UnixSocket& unix_socket); - void SetSslOptions(const SslOptions& options); - void SetReadCallback(const ReadCallback& read); - void SetHeaderCallback(const HeaderCallback& header); - void SetWriteCallback(const WriteCallback& write); - void SetProgressCallback(const ProgressCallback& progress); - void SetDebugCallback(const DebugCallback& debug); - void SetVerbose(const Verbose& verbose); - - // Used in templated functions - void SetOption(const Url& url); - void SetOption(const Parameters& parameters); - void SetOption(Parameters&& parameters); - void SetOption(const Header& header); - void SetOption(const Timeout& timeout); - void SetOption(const ConnectTimeout& timeout); - void SetOption(const Authentication& auth); - void SetOption(const Bearer& auth); - void SetOption(const Digest& auth); - void SetOption(const UserAgent& ua); - void SetOption(Payload&& payload); - void SetOption(const Payload& payload); - void SetOption(const LimitRate& limit_rate); - void SetOption(Proxies&& proxies); - void SetOption(const Proxies& proxies); - void SetOption(Multipart&& multipart); - void SetOption(const Multipart& multipart); - void SetOption(const NTLM& auth); - void SetOption(const bool& redirect); - void SetOption(const MaxRedirects& max_redirects); - void SetOption(const Cookies& cookies); - void SetOption(Body&& body); - void SetOption(const Body& body); - void SetOption(const ReadCallback& read); - void SetOption(const HeaderCallback& header); - void SetOption(const WriteCallback& write); - void SetOption(const ProgressCallback& progress); - void SetOption(const DebugCallback& debug); - void SetOption(const LowSpeed& low_speed); - void SetOption(const VerifySsl& verify); - void SetOption(const Verbose& verbose); - void SetOption(const UnixSocket& unix_socket); - void SetOption(const SslOptions& options); - - Response Delete(); - Response Download(const WriteCallback& write); - Response Download(std::ofstream& file); - Response Get(); - Response Head(); - Response Options(); - Response Patch(); - Response Post(); - Response Put(); - - private: - class Impl; - std::unique_ptr pimpl_; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/ssl_options.h b/VCMP-LUA/modules/requests/cpr/include/cpr/ssl_options.h deleted file mode 100644 index 541e018..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/ssl_options.h +++ /dev/null @@ -1,494 +0,0 @@ -#ifndef CPR_SSLOPTIONS_H -#define CPR_SSLOPTIONS_H - -#include - -#include - -#include - -#define __LIBCURL_VERSION_GTE(major, minor) \ - ((LIBCURL_VERSION_MAJOR > (major)) || \ - ((LIBCURL_VERSION_MAJOR == (major)) && (LIBCURL_VERSION_MINOR >= (minor)))) -#define __LIBCURL_VERSION_LT(major, minor) \ - ((LIBCURL_VERSION_MAJOR < (major)) || \ - ((LIBCURL_VERSION_MAJOR == (major)) && (LIBCURL_VERSION_MINOR < (minor)))) - -#ifndef SUPPORT_ALPN -#define SUPPORT_ALPN __LIBCURL_VERSION_GTE(7, 36) -#endif -#ifndef SUPPORT_NPN -#define SUPPORT_NPN __LIBCURL_VERSION_GTE(7, 36) -#endif - -#ifndef SUPPORT_SSLv2 -#define SUPPORT_SSLv2 __LIBCURL_VERSION_LT(7, 19) -#endif -#ifndef SUPPORT_SSLv3 -#define SUPPORT_SSLv3 __LIBCURL_VERSION_LT(7, 39) -#endif -#ifndef SUPPORT_TLSv1_0 -#define SUPPORT_TLSv1_0 __LIBCURL_VERSION_GTE(7, 34) -#endif -#ifndef SUPPORT_TLSv1_1 -#define SUPPORT_TLSv1_1 __LIBCURL_VERSION_GTE(7, 34) -#endif -#ifndef SUPPORT_TLSv1_2 -#define SUPPORT_TLSv1_2 __LIBCURL_VERSION_GTE(7, 34) -#endif -#ifndef SUPPORT_TLSv1_3 -#define SUPPORT_TLSv1_3 __LIBCURL_VERSION_GTE(7, 52) -#endif -#ifndef SUPPORT_MAX_TLS_VERSION -#define SUPPORT_MAX_TLS_VERSION __LIBCURL_VERSION_GTE(7, 54) -#endif -#ifndef SUPPORT_MAX_TLSv1_1 -#define SUPPORT_MAX_TLSv1_1 __LIBCURL_VERSION_GTE(7, 54) -#endif -#ifndef SUPPORT_MAX_TLSv1_2 -#define SUPPORT_MAX_TLSv1_2 __LIBCURL_VERSION_GTE(7, 54) -#endif -#ifndef SUPPORT_MAX_TLSv1_3 -#define SUPPORT_MAX_TLSv1_3 __LIBCURL_VERSION_GTE(7, 54) -#endif -#ifndef SUPPORT_TLSv13_CIPHERS -#define SUPPORT_TLSv13_CIPHERS __LIBCURL_VERSION_GTE(7, 61) -#endif -#ifndef SUPPORT_SESSIONID_CACHE -#define SUPPORT_SESSIONID_CACHE __LIBCURL_VERSION_GTE(7, 16) -#endif -#ifndef SUPPORT_SSL_FALSESTART -#define SUPPORT_SSL_FALSESTART __LIBCURL_VERSION_GTE(7, 42) -#endif - -namespace cpr { - -class VerifySsl { - public: - VerifySsl() {} - VerifySsl(bool verify) : verify(verify) {} - - operator bool() const { - return verify; - } - - bool verify = true; -}; - -namespace ssl { - -// set SSL client certificate -class CertFile { - public: - CertFile(std::string&& p_filename) : filename(std::move(p_filename)) {} - - const std::string filename; - - virtual const char* GetCertType(void) const { - return "PEM"; - } -}; - -typedef CertFile PemCert; - -class DerCert : public CertFile { - public: - DerCert(std::string&& p_filename) : CertFile(std::move(p_filename)) {} - - virtual const char* GetCertType(void) const { - return "DER"; - } -}; - -// specify private keyfile for TLS and SSL client cert -class KeyFile { - public: - KeyFile(std::string&& p_filename) : filename(std::move(p_filename)) {} - - template - KeyFile(FileType&& p_filename, PassType p_password) - : filename(std::move(p_filename)), password(std::move(p_password)) {} - - std::string filename; - std::string password; - - virtual const char* GetKeyType(void) const { - return "PEM"; - } -}; - -typedef KeyFile PemKey; - -class DerKey : public KeyFile { - public: - DerKey(std::string&& p_filename) : KeyFile(std::move(p_filename)) {} - - template - DerKey(FileType&& p_filename, PassType p_password) - : KeyFile(std::move(p_filename), std::move(p_password)) {} - - virtual const char* GetKeyType(void) const { - return "DER"; - } -}; - -#if SUPPORT_ALPN -// This option enables/disables ALPN in the SSL handshake (if the SSL backend libcurl is built to -// use supports it), which can be used to negotiate http2. -class ALPN { - public: - ALPN() {} - ALPN(bool enabled) : enabled(enabled) {} - - operator bool() const { - return enabled; - } - - bool enabled = true; -}; -#endif // SUPPORT_ALPN - -#if SUPPORT_NPN -// This option enables/disables NPN in the SSL handshake (if the SSL backend libcurl is built to -// use supports it), which can be used to negotiate http2. -class NPN { - public: - NPN() {} - NPN(bool enabled) : enabled(enabled) {} - - operator bool() const { - return enabled; - } - - bool enabled = true; -}; -#endif // SUPPORT_NPN - -// This option determines whether libcurl verifies that the server cert is for the server it is -// known as. -class VerifyHost { - public: - VerifyHost() {} - VerifyHost(bool enabled) : enabled(enabled) {} - - operator bool() const { - return enabled; - } - - bool enabled = true; -}; - -// This option determines whether libcurl verifies the authenticity of the peer's certificate. -class VerifyPeer { - public: - VerifyPeer() {} - VerifyPeer(bool enabled) : enabled(enabled) {} - - operator bool() const { - return enabled; - } - - bool enabled = true; -}; - -// This option determines whether libcurl verifies the status of the server cert using the -// "Certificate Status Request" TLS extension (aka. OCSP stapling). -class VerifyStatus { - public: - VerifyStatus(bool enabled) : enabled(enabled) {} - - operator bool() const { - return enabled; - } - - bool enabled = false; -}; - -// TLS v1.0 or later -struct TLSv1 {}; -#if SUPPORT_SSLv2 -// SSL v2 (but not SSLv3) -struct SSLv2 {}; -#endif -#if SUPPORT_SSLv3 -// SSL v3 (but not SSLv2) -struct SSLv3 {}; -#endif -#if SUPPORT_TLSv1_0 -// TLS v1.0 or later (Added in 7.34.0) -struct TLSv1_0 {}; -#endif -#if SUPPORT_TLSv1_1 -// TLS v1.1 or later (Added in 7.34.0) -struct TLSv1_1 {}; -#endif -#if SUPPORT_TLSv1_2 -// TLS v1.2 or later (Added in 7.34.0) -struct TLSv1_2 {}; -#endif -#if SUPPORT_TLSv1_3 -// TLS v1.3 or later (Added in 7.52.0) -struct TLSv1_3 {}; -#endif -#if SUPPORT_MAX_TLS_VERSION -// The flag defines the maximum supported TLS version by libcurl, or the default value from the SSL -// library is used. -struct MaxTLSVersion {}; -#endif -#if SUPPORT_MAX_TLSv1_0 -// The flag defines maximum supported TLS version as TLSv1.0. (Added in 7.54.0) -struct MaxTLSv1_0 {}; -#endif -#if SUPPORT_MAX_TLSv1_1 -// The flag defines maximum supported TLS version as TLSv1.1. (Added in 7.54.0) -struct MaxTLSv1_1 {}; -#endif -#if SUPPORT_MAX_TLSv1_2 -// The flag defines maximum supported TLS version as TLSv1.2. (Added in 7.54.0) -struct MaxTLSv1_2 {}; -#endif -#if SUPPORT_MAX_TLSv1_3 -// The flag defines maximum supported TLS version as TLSv1.3. (Added in 7.54.0) -struct MaxTLSv1_3 {}; -#endif - -// path to Certificate Authority (CA) bundle -class CaInfo { - public: - CaInfo(std::string&& p_filename) : filename(std::move(p_filename)) {} - - std::string filename; -}; - -// specify directory holding CA certificates -class CaPath { - public: - CaPath(std::string&& p_filename) : filename(std::move(p_filename)) {} - - std::string filename; -}; - -// specify a Certificate Revocation List file -class Crl { - public: - Crl(std::string&& p_filename) : filename(std::move(p_filename)) {} - - std::string filename; -}; - -// specify ciphers to use for TLS -class Ciphers { - public: - template - Ciphers(T&& p_ciphers) : ciphers(std::move(p_ciphers)) {} - - std::string ciphers; -}; - -#if SUPPORT_TLSv13_CIPHERS -// specify ciphers suites to use for TLS 1.3 -class TLS13_Ciphers { - public: - template - TLS13_Ciphers(T&& p_ciphers) : ciphers(std::move(p_ciphers)) {} - - std::string ciphers; -}; -#endif - -#if SUPPORT_SESSIONID_CACHE -// enable/disable use of the SSL session-ID cache -class SessionIdCache { - public: - SessionIdCache() {} - SessionIdCache(bool enabled) : enabled(enabled) {} - - operator bool() const { - return enabled; - } - - bool enabled = true; -}; -#endif - -#if SUPPORT_SSL_FALSESTART -class SslFastStart { - public: - SslFastStart() {} - SslFastStart(bool enabled) : enabled(enabled) {} - - operator bool() const { - return enabled; - } - - bool enabled = false; -}; -#endif - -} // namespace ssl - -struct SslOptions { - std::string cert_file; - std::string cert_type; - std::string key_file; - std::string key_type; - std::string key_pass; -#if SUPPORT_ALPN - bool enable_alpn = true; -#endif // SUPPORT_ALPN -#if SUPPORT_NPN - bool enable_npn = true; -#endif // SUPPORT_ALPN - bool verify_host = true; - bool verify_peer = true; - bool verify_status = false; - int ssl_version = CURL_SSLVERSION_DEFAULT; -#if SUPPORT_MAX_TLS_VERSION - int max_version = CURL_SSLVERSION_MAX_DEFAULT; -#endif - std::string ca_info; - std::string ca_path; - std::string crl_file; - std::string ciphers; -#if SUPPORT_TLSv13_CIPHERS - std::string tls13_ciphers; -#endif -#if SUPPORT_SESSIONID_CACHE - bool session_id_cache = true; -#endif - - void SetOption(const ssl::CertFile& opt) { - cert_file = opt.filename; - cert_type = opt.GetCertType(); - } - void SetOption(const ssl::KeyFile& opt) { - key_file = opt.filename; - key_type = opt.GetKeyType(); - key_pass = opt.password; - } -#if SUPPORT_ALPN - void SetOption(const ssl::ALPN& opt) { - enable_alpn = opt.enabled; - } -#endif // SUPPORT_ALPN -#if SUPPORT_NPN - void SetOption(const ssl::NPN& opt) { - enable_npn = opt.enabled; - } -#endif // SUPPORT_NPN - void SetOption(const ssl::VerifyHost& opt) { - verify_host = opt.enabled; - } - void SetOption(const ssl::VerifyPeer& opt) { - verify_peer = opt.enabled; - } - void SetOption(const ssl::VerifyStatus& opt) { - verify_status = opt.enabled; - } - void SetOption(const ssl::TLSv1& /*opt*/) { - ssl_version = CURL_SSLVERSION_TLSv1; - } -#if SUPPORT_SSLv2 - void SetOption(const ssl::SSLv2& /*opt*/) { - ssl_version = CURL_SSLVERSION_SSLv2; - } -#endif -#if SUPPORT_SSLv3 - void SetOption(const ssl::SSLv3& /*opt*/) { - ssl_version = CURL_SSLVERSION_SSLv3; - } -#endif -#if SUPPORT_TLSv1_0 - void SetOption(const ssl::TLSv1_0& /*opt*/) { - ssl_version = CURL_SSLVERSION_TLSv1_0; - } -#endif -#if SUPPORT_TLSv1_1 - void SetOption(const ssl::TLSv1_1& /*opt*/) { - ssl_version = CURL_SSLVERSION_TLSv1_1; - } -#endif -#if SUPPORT_TLSv1_2 - void SetOption(const ssl::TLSv1_2& /*opt*/) { - ssl_version = CURL_SSLVERSION_TLSv1_2; - } -#endif -#if SUPPORT_TLSv1_3 - void SetOption(const ssl::TLSv1_3& /*opt*/) { - ssl_version = CURL_SSLVERSION_TLSv1_3; - } -#endif -#if SUPPORT_MAX_TLS_VERSION - void SetOption(const ssl::MaxTLSVersion& /*opt*/) { - max_version = CURL_SSLVERSION_DEFAULT; - } -#endif -#if SUPPORT_MAX_TLSv1_0 - void SetOption(const ssl::MaxTLSv1_0& opt) { - max_version = CURL_SSLVERSION_MAX_TLSv1_0; - } -#endif -#if SUPPORT_MAX_TLSv1_1 - void SetOption(const ssl::MaxTLSv1_1& /*opt*/) { - max_version = CURL_SSLVERSION_MAX_TLSv1_1; - } -#endif -#if SUPPORT_MAX_TLSv1_2 - void SetOption(const ssl::MaxTLSv1_2& /*opt*/) { - max_version = CURL_SSLVERSION_MAX_TLSv1_2; - } -#endif -#if SUPPORT_MAX_TLSv1_3 - void SetOption(const ssl::MaxTLSv1_3& /*opt*/) { - max_version = CURL_SSLVERSION_MAX_TLSv1_3; - } -#endif - void SetOption(const ssl::CaInfo& opt) { - ca_info = opt.filename; - } - void SetOption(const ssl::CaPath& opt) { - ca_path = opt.filename; - } - void SetOption(const ssl::Crl& opt) { - crl_file = opt.filename; - } - void SetOption(const ssl::Ciphers& opt) { - ciphers = opt.ciphers; - } -#if SUPPORT_TLSv13_CIPHERS - void SetOption(const ssl::TLS13_Ciphers& opt) { - tls13_ciphers = opt.ciphers; - } -#endif -#if SUPPORT_SESSIONID_CACHE - void SetOption(const ssl::SessionIdCache& opt) { - session_id_cache = opt.enabled; - } -#endif -}; - -namespace priv { - -template -void set_ssl_option(SslOptions& opts, T&& t) { - opts.SetOption(std::move(t)); -} - -template -void set_ssl_option(SslOptions& opts, T&& t, Ts&&... ts) { - set_ssl_option(opts, std::move(t)); - set_ssl_option(opts, std::move(ts)...); -} - -} // namespace priv - -template -SslOptions Ssl(Ts&&... ts) { - SslOptions opts; - priv::set_ssl_option(opts, std::move(ts)...); - return opts; -} - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/status_codes.h b/VCMP-LUA/modules/requests/cpr/include/cpr/status_codes.h deleted file mode 100644 index 9575ec2..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/status_codes.h +++ /dev/null @@ -1,93 +0,0 @@ -#ifndef _CPR_STATUS_CODES -#define _CPR_STATUS_CODES -#include -namespace cpr { -namespace status { -// Information responses -constexpr std::int32_t HTTP_CONTINUE = 100; -constexpr std::int32_t HTTP_SWITCHING_PROTOCOL = 101; -constexpr std::int32_t HTTP_PROCESSING = 102; -constexpr std::int32_t HTTP_EARLY_HINTS = 103; -// Sucessful responses -constexpr std::int32_t HTTP_OK = 200; -constexpr std::int32_t HTTP_CREATED = 201; -constexpr std::int32_t HTTP_ACCEPTED = 202; -constexpr std::int32_t HTTP_NON_AUTHORITATIVE_INFORMATION = 203; -constexpr std::int32_t HTTP_NO_CONTENT = 204; -constexpr std::int32_t HTTP_RESET_CONTENT = 205; -constexpr std::int32_t HTTP_PARTIAL_CONTENT = 206; -constexpr std::int32_t HTTP_MULTI_STATUS = 207; -constexpr std::int32_t HTTP_ALREADY_REPORTED = 208; -constexpr std::int32_t HTTP_IM_USED = 226; -// Redirection messages -constexpr std::int32_t HTTP_MULTIPLE_CHOICE = 300; -constexpr std::int32_t HTTP_MOVED_PERMANENTLY = 301; -constexpr std::int32_t HTTP_FOUND = 302; -constexpr std::int32_t HTTP_SEE_OTHER = 303; -constexpr std::int32_t HTTP_NOT_MODIFIED = 304; -constexpr std::int32_t HTTP_USE_PROXY = 305; -constexpr std::int32_t HTTP_UNUSED = 306; -constexpr std::int32_t HTTP_TEMPORARY_REDIRECT = 307; -constexpr std::int32_t HTTP_PERMANENT_REDIRECT = 308; -// Client error responses -constexpr std::int32_t HTTP_BAD_REQUEST = 400; -constexpr std::int32_t HTTP_UNAUTHORIZED = 401; -constexpr std::int32_t HTTP_PAYMENT_REQUIRED = 402; -constexpr std::int32_t HTTP_FORBIDDEN = 403; -constexpr std::int32_t HTTP_NOT_FOUND = 404; -constexpr std::int32_t HTTP_METHOD_NOT_ALLOWED = 405; -constexpr std::int32_t HTTP_NOT_ACCEPTABLE = 406; -constexpr std::int32_t HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; -constexpr std::int32_t HTTP_REQUEST_TIMEOUT = 408; -constexpr std::int32_t HTTP_CONFLICT = 409; -constexpr std::int32_t HTTP_GONE = 410; -constexpr std::int32_t HTTP_LENGTH_REQUIRED = 411; -constexpr std::int32_t HTTP_PRECONDITION_FAILED = 412; -constexpr std::int32_t HTTP_PAYLOAD_TOO_LARGE = 413; -constexpr std::int32_t HTTP_URI_TOO_LONG = 414; -constexpr std::int32_t HTTP_UNSUPPORTED_MEDIA_TYPE = 415; -constexpr std::int32_t HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; -constexpr std::int32_t HTTP_EXPECTATION_FAILED = 417; -constexpr std::int32_t HTTP_IM_A_TEAPOT = 418; -constexpr std::int32_t HTTP_MISDIRECTED_REQUEST = 421; -constexpr std::int32_t HTTP_UNPROCESSABLE_ENTITY = 422; -constexpr std::int32_t HTTP_LOCKED = 423; -constexpr std::int32_t HTTP_FAILED_DEPENDENCY = 424; -constexpr std::int32_t HTTP_TOO_EARLY = 425; -constexpr std::int32_t HTTP_UPGRADE_REQUIRED = 426; -constexpr std::int32_t HTTP_PRECONDITION_REQUIRED = 428; -constexpr std::int32_t HTTP_TOO_MANY_REQUESTS = 429; -constexpr std::int32_t HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; -constexpr std::int32_t HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; -// Server response errors -constexpr std::int32_t HTTP_INTERNAL_SERVER_ERROR = 500; -constexpr std::int32_t HTTP_NOT_IMPLEMENTED = 501; -constexpr std::int32_t HTTP_BAD_GATEWAY = 502; -constexpr std::int32_t HTTP_SERVICE_UNAVAILABLE = 503; -constexpr std::int32_t HTTP_GATEWAY_TIMEOUT = 504; -constexpr std::int32_t HTTP_HTTP_VERSION_NOT_SUPPORTED = 505; -constexpr std::int32_t HTTP_VARIANT_ALSO_NEGOTIATES = 506; -constexpr std::int32_t HTTP_INSUFFICIENT_STORAGE = 507; -constexpr std::int32_t HTTP_LOOP_DETECTED = 508; -constexpr std::int32_t HTTP_NOT_EXTENDED = 510; -constexpr std::int32_t HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; - -constexpr bool is_informational(const std::int32_t code) { - return (code >= 100 && code < 200); -} -constexpr bool is_success(const std::int32_t code) { - return (code >= 200 && code < 300); -} -constexpr bool is_redirect(const std::int32_t code) { - return (code >= 300 && code < 400); -} -constexpr bool is_client_error(const std::int32_t code) { - return (code >= 400 && code < 500); -} -constexpr bool is_server_error(const std::int32_t code) { - return (code >= 500 && code < 600); -} - -} // namespace status -} // namespace cpr -#endif \ No newline at end of file diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/timeout.h b/VCMP-LUA/modules/requests/cpr/include/cpr/timeout.h deleted file mode 100644 index 6e6fb79..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/timeout.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef CPR_TIMEOUT_H -#define CPR_TIMEOUT_H - -#include -#include - -namespace cpr { - -class Timeout { - public: - Timeout(const std::chrono::milliseconds& duration) : ms{duration} {} - Timeout(const std::int32_t& milliseconds) : Timeout{std::chrono::milliseconds(milliseconds)} {} - - long Milliseconds() const; - - std::chrono::milliseconds ms; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/unix_socket.h b/VCMP-LUA/modules/requests/cpr/include/cpr/unix_socket.h deleted file mode 100644 index a668195..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/unix_socket.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef CPR_UNIX_SOCKET_H -#define CPR_UNIX_SOCKET_H - -#include - -namespace cpr { - -class UnixSocket { - public: - UnixSocket(std::string&& unix_socket) : unix_socket_(std::move(unix_socket)) {} - - const char* GetUnixSocketString() const noexcept; - - private: - const std::string unix_socket_; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/user_agent.h b/VCMP-LUA/modules/requests/cpr/include/cpr/user_agent.h deleted file mode 100644 index f587f2f..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/user_agent.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef CPR_USERAGENT_H -#define CPR_USERAGENT_H - -#include -#include - -#include "cpr/cprtypes.h" - -namespace cpr { -class UserAgent : public StringHolder { - public: - UserAgent() : StringHolder() {} - UserAgent(const std::string& useragent) : StringHolder(useragent) {} - UserAgent(std::string&& useragent) : StringHolder(std::move(useragent)) {} - UserAgent(const char* useragent) : StringHolder(useragent) {} - UserAgent(const char* str, size_t len) : StringHolder(str, len) {} - UserAgent(const std::initializer_list args) : StringHolder(args) {} - ~UserAgent() override = default; -}; - -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/util.h b/VCMP-LUA/modules/requests/cpr/include/cpr/util.h deleted file mode 100644 index a5204fa..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/util.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef CPR_UTIL_H -#define CPR_UTIL_H - -#include -#include -#include - -#include "cpr/callback.h" -#include "cpr/cookies.h" -#include "cpr/cprtypes.h" -#include "cpr/curlholder.h" - -namespace cpr { -namespace util { - -Header parseHeader(const std::string& headers, std::string* status_line = nullptr, - std::string* reason = nullptr); -Cookies parseCookies(curl_slist* raw_cookies); -size_t readUserFunction(char * ptr, size_t size, size_t nitems, const ReadCallback* read); -size_t headerUserFunction(char* ptr, size_t size, size_t nmemb, const HeaderCallback* header); -size_t writeFunction(char* ptr, size_t size, size_t nmemb, std::string* data); -size_t writeFileFunction(char* ptr, size_t size, size_t nmemb, std::ofstream* write); -size_t writeUserFunction(char * ptr, size_t size, size_t nmemb, const WriteCallback* write); -#if LIBCURL_VERSION_NUM < 0x072000 -int progressUserFunction(const ProgressCallback * progress, double dltotal, double dlnow, double ultotal, double ulnow); -#else -int progressUserFunction(const ProgressCallback * progress, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow); -#endif -int debugUserFunction(CURL *handle, curl_infotype type, char * data, size_t size, const DebugCallback * debug); -std::vector split(const std::string& to_split, char delimiter); -std::string urlEncode(const std::string& s); -std::string urlDecode(const std::string& s); - -} // namespace util -} // namespace cpr - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/cpr/verbose.h b/VCMP-LUA/modules/requests/cpr/include/cpr/verbose.h deleted file mode 100644 index 22fa6c1..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/cpr/verbose.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef CPR_VERBOSE_H_ -#define CPR_VERBOSE_H_ - -namespace cpr { - -class Verbose { - public: - Verbose() {} - Verbose(const bool verbose) : verbose{verbose} {} - - bool verbose = true; -}; - -} // namespace cpr - - -#endif /* CPR_VERBOSE_H_ */ diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/curl.h b/VCMP-LUA/modules/requests/cpr/include/curl/curl.h deleted file mode 100644 index b7cb30a..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/curl.h +++ /dev/null @@ -1,2889 +0,0 @@ -#ifndef CURLINC_CURL_H -#define CURLINC_CURL_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* - * If you have libcurl problems, all docs and details are found here: - * https://curl.haxx.se/libcurl/ - * - * curl-library mailing list subscription and unsubscription web interface: - * https://cool.haxx.se/mailman/listinfo/curl-library/ - */ - -#ifdef CURL_NO_OLDIES -#define CURL_STRICTER -#endif - -#include "curlver.h" /* libcurl version defines */ -#include "system.h" /* determine things run-time */ - -/* - * Define CURL_WIN32 when build target is Win32 API - */ - -#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && \ - !defined(__SYMBIAN32__) -#define CURL_WIN32 -#endif - -#include -#include - -#if defined(__FreeBSD__) && (__FreeBSD__ >= 2) -/* Needed for __FreeBSD_version symbol definition */ -#include -#endif - -/* The include stuff here below is mainly for time_t! */ -#include -#include - -#if defined(CURL_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) -#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \ - defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)) -/* The check above prevents the winsock2 inclusion if winsock.h already was - included, since they can't co-exist without problems */ -#include -#include -#endif -#endif - -/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish - libc5-based Linux systems. Only include it on systems that are known to - require it! */ -#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ - defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ - defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \ - defined(__CYGWIN__) || \ - (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) -#include -#endif - -#if !defined(CURL_WIN32) && !defined(_WIN32_WCE) -#include -#endif - -#if !defined(CURL_WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__) -#include -#endif - -#ifdef __BEOS__ -#include -#endif - -/* Compatibility for non-Clang compilers */ -#ifndef __has_declspec_attribute -# define __has_declspec_attribute(x) 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) -typedef struct Curl_easy CURL; -typedef struct Curl_share CURLSH; -#else -typedef void CURL; -typedef void CURLSH; -#endif - -/* - * libcurl external API function linkage decorations. - */ - -#ifdef CURL_STATICLIB -# define CURL_EXTERN -#elif defined(CURL_WIN32) || defined(__SYMBIAN32__) || \ - (__has_declspec_attribute(dllexport) && \ - __has_declspec_attribute(dllimport)) -# if defined(BUILDING_LIBCURL) -# define CURL_EXTERN __declspec(dllexport) -# else -# define CURL_EXTERN __declspec(dllimport) -# endif -#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS) -# define CURL_EXTERN CURL_EXTERN_SYMBOL -#else -# define CURL_EXTERN -#endif - -#ifndef curl_socket_typedef -/* socket typedef */ -#if defined(CURL_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) -typedef SOCKET curl_socket_t; -#define CURL_SOCKET_BAD INVALID_SOCKET -#else -typedef int curl_socket_t; -#define CURL_SOCKET_BAD -1 -#endif -#define curl_socket_typedef -#endif /* curl_socket_typedef */ - -/* enum for the different supported SSL backends */ -typedef enum { - CURLSSLBACKEND_NONE = 0, - CURLSSLBACKEND_OPENSSL = 1, - CURLSSLBACKEND_GNUTLS = 2, - CURLSSLBACKEND_NSS = 3, - CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ - CURLSSLBACKEND_GSKIT = 5, - CURLSSLBACKEND_POLARSSL = 6, - CURLSSLBACKEND_WOLFSSL = 7, - CURLSSLBACKEND_SCHANNEL = 8, - CURLSSLBACKEND_SECURETRANSPORT = 9, - CURLSSLBACKEND_AXTLS = 10, /* never used since 7.63.0 */ - CURLSSLBACKEND_MBEDTLS = 11, - CURLSSLBACKEND_MESALINK = 12, - CURLSSLBACKEND_BEARSSL = 13 -} curl_sslbackend; - -/* aliases for library clones and renames */ -#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL -#define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL - -/* deprecated names: */ -#define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL -#define CURLSSLBACKEND_DARWINSSL CURLSSLBACKEND_SECURETRANSPORT - -struct curl_httppost { - struct curl_httppost *next; /* next entry in the list */ - char *name; /* pointer to allocated name */ - long namelength; /* length of name length */ - char *contents; /* pointer to allocated data contents */ - long contentslength; /* length of contents field, see also - CURL_HTTPPOST_LARGE */ - char *buffer; /* pointer to allocated buffer contents */ - long bufferlength; /* length of buffer field */ - char *contenttype; /* Content-Type */ - struct curl_slist *contentheader; /* list of extra headers for this form */ - struct curl_httppost *more; /* if one field name has more than one - file, this link should link to following - files */ - long flags; /* as defined below */ - -/* specified content is a file name */ -#define CURL_HTTPPOST_FILENAME (1<<0) -/* specified content is a file name */ -#define CURL_HTTPPOST_READFILE (1<<1) -/* name is only stored pointer do not free in formfree */ -#define CURL_HTTPPOST_PTRNAME (1<<2) -/* contents is only stored pointer do not free in formfree */ -#define CURL_HTTPPOST_PTRCONTENTS (1<<3) -/* upload file from buffer */ -#define CURL_HTTPPOST_BUFFER (1<<4) -/* upload file from pointer contents */ -#define CURL_HTTPPOST_PTRBUFFER (1<<5) -/* upload file contents by using the regular read callback to get the data and - pass the given pointer as custom pointer */ -#define CURL_HTTPPOST_CALLBACK (1<<6) -/* use size in 'contentlen', added in 7.46.0 */ -#define CURL_HTTPPOST_LARGE (1<<7) - - char *showfilename; /* The file name to show. If not set, the - actual file name will be used (if this - is a file part) */ - void *userp; /* custom pointer used for - HTTPPOST_CALLBACK posts */ - curl_off_t contentlen; /* alternative length of contents - field. Used if CURL_HTTPPOST_LARGE is - set. Added in 7.46.0 */ -}; - - -/* This is a return code for the progress callback that, when returned, will - signal libcurl to continue executing the default progress function */ -#define CURL_PROGRESSFUNC_CONTINUE 0x10000001 - -/* This is the CURLOPT_PROGRESSFUNCTION callback prototype. It is now - considered deprecated but was the only choice up until 7.31.0 */ -typedef int (*curl_progress_callback)(void *clientp, - double dltotal, - double dlnow, - double ultotal, - double ulnow); - -/* This is the CURLOPT_XFERINFOFUNCTION callback prototype. It was introduced - in 7.32.0, avoids the use of floating point numbers and provides more - detailed information. */ -typedef int (*curl_xferinfo_callback)(void *clientp, - curl_off_t dltotal, - curl_off_t dlnow, - curl_off_t ultotal, - curl_off_t ulnow); - -#ifndef CURL_MAX_READ_SIZE - /* The maximum receive buffer size configurable via CURLOPT_BUFFERSIZE. */ -#define CURL_MAX_READ_SIZE 524288 -#endif - -#ifndef CURL_MAX_WRITE_SIZE - /* Tests have proven that 20K is a very bad buffer size for uploads on - Windows, while 16K for some odd reason performed a lot better. - We do the ifndef check to allow this value to easier be changed at build - time for those who feel adventurous. The practical minimum is about - 400 bytes since libcurl uses a buffer of this size as a scratch area - (unrelated to network send operations). */ -#define CURL_MAX_WRITE_SIZE 16384 -#endif - -#ifndef CURL_MAX_HTTP_HEADER -/* The only reason to have a max limit for this is to avoid the risk of a bad - server feeding libcurl with a never-ending header that will cause reallocs - infinitely */ -#define CURL_MAX_HTTP_HEADER (100*1024) -#endif - -/* This is a magic return code for the write callback that, when returned, - will signal libcurl to pause receiving on the current transfer. */ -#define CURL_WRITEFUNC_PAUSE 0x10000001 - -typedef size_t (*curl_write_callback)(char *buffer, - size_t size, - size_t nitems, - void *outstream); - -/* This callback will be called when a new resolver request is made */ -typedef int (*curl_resolver_start_callback)(void *resolver_state, - void *reserved, void *userdata); - -/* enumeration of file types */ -typedef enum { - CURLFILETYPE_FILE = 0, - CURLFILETYPE_DIRECTORY, - CURLFILETYPE_SYMLINK, - CURLFILETYPE_DEVICE_BLOCK, - CURLFILETYPE_DEVICE_CHAR, - CURLFILETYPE_NAMEDPIPE, - CURLFILETYPE_SOCKET, - CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ - - CURLFILETYPE_UNKNOWN /* should never occur */ -} curlfiletype; - -#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0) -#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1) -#define CURLFINFOFLAG_KNOWN_TIME (1<<2) -#define CURLFINFOFLAG_KNOWN_PERM (1<<3) -#define CURLFINFOFLAG_KNOWN_UID (1<<4) -#define CURLFINFOFLAG_KNOWN_GID (1<<5) -#define CURLFINFOFLAG_KNOWN_SIZE (1<<6) -#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7) - -/* Information about a single file, used when doing FTP wildcard matching */ -struct curl_fileinfo { - char *filename; - curlfiletype filetype; - time_t time; /* always zero! */ - unsigned int perm; - int uid; - int gid; - curl_off_t size; - long int hardlinks; - - struct { - /* If some of these fields is not NULL, it is a pointer to b_data. */ - char *time; - char *perm; - char *user; - char *group; - char *target; /* pointer to the target filename of a symlink */ - } strings; - - unsigned int flags; - - /* used internally */ - char *b_data; - size_t b_size; - size_t b_used; -}; - -/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ -#define CURL_CHUNK_BGN_FUNC_OK 0 -#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ -#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ - -/* if splitting of data transfer is enabled, this callback is called before - download of an individual chunk started. Note that parameter "remains" works - only for FTP wildcard downloading (for now), otherwise is not used */ -typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, - void *ptr, - int remains); - -/* return codes for CURLOPT_CHUNK_END_FUNCTION */ -#define CURL_CHUNK_END_FUNC_OK 0 -#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ - -/* If splitting of data transfer is enabled this callback is called after - download of an individual chunk finished. - Note! After this callback was set then it have to be called FOR ALL chunks. - Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. - This is the reason why we don't need "transfer_info" parameter in this - callback and we are not interested in "remains" parameter too. */ -typedef long (*curl_chunk_end_callback)(void *ptr); - -/* return codes for FNMATCHFUNCTION */ -#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ -#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ -#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ - -/* callback type for wildcard downloading pattern matching. If the - string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ -typedef int (*curl_fnmatch_callback)(void *ptr, - const char *pattern, - const char *string); - -/* These are the return codes for the seek callbacks */ -#define CURL_SEEKFUNC_OK 0 -#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ -#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so - libcurl might try other means instead */ -typedef int (*curl_seek_callback)(void *instream, - curl_off_t offset, - int origin); /* 'whence' */ - -/* This is a return code for the read callback that, when returned, will - signal libcurl to immediately abort the current transfer. */ -#define CURL_READFUNC_ABORT 0x10000000 -/* This is a return code for the read callback that, when returned, will - signal libcurl to pause sending data on the current transfer. */ -#define CURL_READFUNC_PAUSE 0x10000001 - -/* Return code for when the trailing headers' callback has terminated - without any errors*/ -#define CURL_TRAILERFUNC_OK 0 -/* Return code for when was an error in the trailing header's list and we - want to abort the request */ -#define CURL_TRAILERFUNC_ABORT 1 - -typedef size_t (*curl_read_callback)(char *buffer, - size_t size, - size_t nitems, - void *instream); - -typedef int (*curl_trailer_callback)(struct curl_slist **list, - void *userdata); - -typedef enum { - CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ - CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */ - CURLSOCKTYPE_LAST /* never use */ -} curlsocktype; - -/* The return code from the sockopt_callback can signal information back - to libcurl: */ -#define CURL_SOCKOPT_OK 0 -#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return - CURLE_ABORTED_BY_CALLBACK */ -#define CURL_SOCKOPT_ALREADY_CONNECTED 2 - -typedef int (*curl_sockopt_callback)(void *clientp, - curl_socket_t curlfd, - curlsocktype purpose); - -struct curl_sockaddr { - int family; - int socktype; - int protocol; - unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it - turned really ugly and painful on the systems that - lack this type */ - struct sockaddr addr; -}; - -typedef curl_socket_t -(*curl_opensocket_callback)(void *clientp, - curlsocktype purpose, - struct curl_sockaddr *address); - -typedef int -(*curl_closesocket_callback)(void *clientp, curl_socket_t item); - -typedef enum { - CURLIOE_OK, /* I/O operation successful */ - CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ - CURLIOE_FAILRESTART, /* failed to restart the read */ - CURLIOE_LAST /* never use */ -} curlioerr; - -typedef enum { - CURLIOCMD_NOP, /* no operation */ - CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ - CURLIOCMD_LAST /* never use */ -} curliocmd; - -typedef curlioerr (*curl_ioctl_callback)(CURL *handle, - int cmd, - void *clientp); - -#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS -/* - * The following typedef's are signatures of malloc, free, realloc, strdup and - * calloc respectively. Function pointers of these types can be passed to the - * curl_global_init_mem() function to set user defined memory management - * callback routines. - */ -typedef void *(*curl_malloc_callback)(size_t size); -typedef void (*curl_free_callback)(void *ptr); -typedef void *(*curl_realloc_callback)(void *ptr, size_t size); -typedef char *(*curl_strdup_callback)(const char *str); -typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); - -#define CURL_DID_MEMORY_FUNC_TYPEDEFS -#endif - -/* the kind of data that is passed to information_callback*/ -typedef enum { - CURLINFO_TEXT = 0, - CURLINFO_HEADER_IN, /* 1 */ - CURLINFO_HEADER_OUT, /* 2 */ - CURLINFO_DATA_IN, /* 3 */ - CURLINFO_DATA_OUT, /* 4 */ - CURLINFO_SSL_DATA_IN, /* 5 */ - CURLINFO_SSL_DATA_OUT, /* 6 */ - CURLINFO_END -} curl_infotype; - -typedef int (*curl_debug_callback) - (CURL *handle, /* the handle/transfer this concerns */ - curl_infotype type, /* what kind of data */ - char *data, /* points to the data */ - size_t size, /* size of the data pointed to */ - void *userptr); /* whatever the user please */ - -/* All possible error codes from all sorts of curl functions. Future versions - may return other values, stay prepared. - - Always add new return codes last. Never *EVER* remove any. The return - codes must remain the same! - */ - -typedef enum { - CURLE_OK = 0, - CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ - CURLE_FAILED_INIT, /* 2 */ - CURLE_URL_MALFORMAT, /* 3 */ - CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for - 7.17.0, reused in April 2011 for 7.21.5] */ - CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ - CURLE_COULDNT_RESOLVE_HOST, /* 6 */ - CURLE_COULDNT_CONNECT, /* 7 */ - CURLE_WEIRD_SERVER_REPLY, /* 8 */ - CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server - due to lack of access - when login fails - this is not returned. */ - CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for - 7.15.4, reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ - CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server - [was obsoleted in August 2007 for 7.17.0, - reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ - CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ - CURLE_FTP_CANT_GET_HOST, /* 15 */ - CURLE_HTTP2, /* 16 - A problem in the http2 framing layer. - [was obsoleted in August 2007 for 7.17.0, - reused in July 2014 for 7.38.0] */ - CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ - CURLE_PARTIAL_FILE, /* 18 */ - CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ - CURLE_OBSOLETE20, /* 20 - NOT USED */ - CURLE_QUOTE_ERROR, /* 21 - quote command failure */ - CURLE_HTTP_RETURNED_ERROR, /* 22 */ - CURLE_WRITE_ERROR, /* 23 */ - CURLE_OBSOLETE24, /* 24 - NOT USED */ - CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ - CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ - CURLE_OUT_OF_MEMORY, /* 27 */ - /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error - instead of a memory allocation error if CURL_DOES_CONVERSIONS - is defined - */ - CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ - CURLE_OBSOLETE29, /* 29 - NOT USED */ - CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ - CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ - CURLE_OBSOLETE32, /* 32 - NOT USED */ - CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ - CURLE_HTTP_POST_ERROR, /* 34 */ - CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ - CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ - CURLE_FILE_COULDNT_READ_FILE, /* 37 */ - CURLE_LDAP_CANNOT_BIND, /* 38 */ - CURLE_LDAP_SEARCH_FAILED, /* 39 */ - CURLE_OBSOLETE40, /* 40 - NOT USED */ - CURLE_FUNCTION_NOT_FOUND, /* 41 - NOT USED starting with 7.53.0 */ - CURLE_ABORTED_BY_CALLBACK, /* 42 */ - CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ - CURLE_OBSOLETE44, /* 44 - NOT USED */ - CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ - CURLE_OBSOLETE46, /* 46 - NOT USED */ - CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */ - CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ - CURLE_TELNET_OPTION_SYNTAX, /* 49 - Malformed telnet option */ - CURLE_OBSOLETE50, /* 50 - NOT USED */ - CURLE_OBSOLETE51, /* 51 - NOT USED */ - CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ - CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ - CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as - default */ - CURLE_SEND_ERROR, /* 55 - failed sending network data */ - CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ - CURLE_OBSOLETE57, /* 57 - NOT IN USE */ - CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ - CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ - CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint - wasn't verified fine */ - CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ - CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */ - CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ - CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ - CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind - that failed */ - CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */ - CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not - accepted and we failed to login */ - CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ - CURLE_TFTP_PERM, /* 69 - permission problem on server */ - CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ - CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ - CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ - CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ - CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ - CURLE_CONV_FAILED, /* 75 - conversion failed */ - CURLE_CONV_REQD, /* 76 - caller must register conversion - callbacks using curl_easy_setopt options - CURLOPT_CONV_FROM_NETWORK_FUNCTION, - CURLOPT_CONV_TO_NETWORK_FUNCTION, and - CURLOPT_CONV_FROM_UTF8_FUNCTION */ - CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing - or wrong format */ - CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ - CURLE_SSH, /* 79 - error from the SSH layer, somewhat - generic so the error message will be of - interest when this has happened */ - - CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL - connection */ - CURLE_AGAIN, /* 81 - socket is not ready for send/recv, - wait till it's ready and try again (Added - in 7.18.2) */ - CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or - wrong format (Added in 7.19.0) */ - CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in - 7.19.0) */ - CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ - CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ - CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ - CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ - CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ - CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the - session will be queued */ - CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not - match */ - CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */ - CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer - */ - CURLE_RECURSIVE_API_CALL, /* 93 - an api function was called from - inside a callback */ - CURLE_AUTH_ERROR, /* 94 - an authentication function returned an - error */ - CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */ - CURLE_QUIC_CONNECT_ERROR, /* 96 - QUIC connection error */ - CURL_LAST /* never use! */ -} CURLcode; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Previously obsolete error code re-used in 7.38.0 */ -#define CURLE_OBSOLETE16 CURLE_HTTP2 - -/* Previously obsolete error codes re-used in 7.24.0 */ -#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED -#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT - -/* compatibility with older names */ -#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING -#define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY - -/* The following were added in 7.62.0 */ -#define CURLE_SSL_CACERT CURLE_PEER_FAILED_VERIFICATION - -/* The following were added in 7.21.5, April 2011 */ -#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION - -/* The following were added in 7.17.1 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION - -/* The following were added in 7.17.0 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ -#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 -#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 -#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 -#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 -#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 -#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 -#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 -#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 -#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 -#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 -#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 -#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN - -#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED -#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE -#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR -#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL -#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS -#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR -#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED - -/* The following were added earlier */ - -#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT - -#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR -#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED -#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED - -#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE -#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME - -/* This was the error code 50 in 7.7.3 and a few earlier versions, this - is no longer used by libcurl but is instead #defined here only to not - make programs break */ -#define CURLE_ALREADY_COMPLETE 99999 - -/* Provide defines for really old option names */ -#define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */ -#define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */ -#define CURLOPT_WRITEHEADER CURLOPT_HEADERDATA - -/* Since long deprecated options with no code in the lib that does anything - with them. */ -#define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40 -#define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72 - -#endif /*!CURL_NO_OLDIES*/ - -/* This prototype applies to all conversion callbacks */ -typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); - -typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ - void *ssl_ctx, /* actually an OpenSSL - or WolfSSL SSL_CTX, - or an mbedTLS - mbedtls_ssl_config */ - void *userptr); - -typedef enum { - CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use - CONNECT HTTP/1.1 */ - CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT - HTTP/1.0 */ - CURLPROXY_HTTPS = 2, /* added in 7.52.0 */ - CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already - in 7.10 */ - CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ - CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ - CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the - host name rather than the IP address. added - in 7.18.0 */ -} curl_proxytype; /* this enum was added in 7.10 */ - -/* - * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: - * - * CURLAUTH_NONE - No HTTP authentication - * CURLAUTH_BASIC - HTTP Basic authentication (default) - * CURLAUTH_DIGEST - HTTP Digest authentication - * CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication - * CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated) - * CURLAUTH_NTLM - HTTP NTLM authentication - * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour - * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper - * CURLAUTH_BEARER - HTTP Bearer token authentication - * CURLAUTH_ONLY - Use together with a single other type to force no - * authentication or just that single type - * CURLAUTH_ANY - All fine types set - * CURLAUTH_ANYSAFE - All fine types except Basic - */ - -#define CURLAUTH_NONE ((unsigned long)0) -#define CURLAUTH_BASIC (((unsigned long)1)<<0) -#define CURLAUTH_DIGEST (((unsigned long)1)<<1) -#define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2) -/* Deprecated since the advent of CURLAUTH_NEGOTIATE */ -#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE -/* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */ -#define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE -#define CURLAUTH_NTLM (((unsigned long)1)<<3) -#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) -#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) -#define CURLAUTH_BEARER (((unsigned long)1)<<6) -#define CURLAUTH_ONLY (((unsigned long)1)<<31) -#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) -#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE)) - -#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */ -#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */ -#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */ -#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */ -#define CURLSSH_AUTH_HOST (1<<2) /* host key files */ -#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */ -#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */ -#define CURLSSH_AUTH_GSSAPI (1<<5) /* gssapi (kerberos, ...) */ -#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY - -#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */ -#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */ -#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */ - -#define CURL_ERROR_SIZE 256 - -enum curl_khtype { - CURLKHTYPE_UNKNOWN, - CURLKHTYPE_RSA1, - CURLKHTYPE_RSA, - CURLKHTYPE_DSS, - CURLKHTYPE_ECDSA, - CURLKHTYPE_ED25519 -}; - -struct curl_khkey { - const char *key; /* points to a zero-terminated string encoded with base64 - if len is zero, otherwise to the "raw" data */ - size_t len; - enum curl_khtype keytype; -}; - -/* this is the set of return values expected from the curl_sshkeycallback - callback */ -enum curl_khstat { - CURLKHSTAT_FINE_ADD_TO_FILE, - CURLKHSTAT_FINE, - CURLKHSTAT_REJECT, /* reject the connection, return an error */ - CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so - this causes a CURLE_DEFER error but otherwise the - connection will be left intact etc */ - CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ -}; - -/* this is the set of status codes pass in to the callback */ -enum curl_khmatch { - CURLKHMATCH_OK, /* match */ - CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ - CURLKHMATCH_MISSING, /* no matching host/key found */ - CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ -}; - -typedef int - (*curl_sshkeycallback) (CURL *easy, /* easy handle */ - const struct curl_khkey *knownkey, /* known */ - const struct curl_khkey *foundkey, /* found */ - enum curl_khmatch, /* libcurl's view on the keys */ - void *clientp); /* custom pointer passed from app */ - -/* parameter for the CURLOPT_USE_SSL option */ -typedef enum { - CURLUSESSL_NONE, /* do not attempt to use SSL */ - CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */ - CURLUSESSL_CONTROL, /* SSL for the control connection or fail */ - CURLUSESSL_ALL, /* SSL for all communication or fail */ - CURLUSESSL_LAST /* not an option, never use */ -} curl_usessl; - -/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ - -/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the - name of improving interoperability with older servers. Some SSL libraries - have introduced work-arounds for this flaw but those work-arounds sometimes - make the SSL communication fail. To regain functionality with those broken - servers, a user can this way allow the vulnerability back. */ -#define CURLSSLOPT_ALLOW_BEAST (1<<0) - -/* - NO_REVOKE tells libcurl to disable certificate revocation checks for those - SSL backends where such behavior is present. */ -#define CURLSSLOPT_NO_REVOKE (1<<1) - -/* - NO_PARTIALCHAIN tells libcurl to *NOT* accept a partial certificate chain - if possible. The OpenSSL backend has this ability. */ -#define CURLSSLOPT_NO_PARTIALCHAIN (1<<2) - -/* The default connection attempt delay in milliseconds for happy eyeballs. - CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS.3 and happy-eyeballs-timeout-ms.d document - this value, keep them in sync. */ -#define CURL_HET_DEFAULT 200L - -/* The default connection upkeep interval in milliseconds. */ -#define CURL_UPKEEP_INTERVAL_DEFAULT 60000L - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2009 */ - -#define CURLFTPSSL_NONE CURLUSESSL_NONE -#define CURLFTPSSL_TRY CURLUSESSL_TRY -#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL -#define CURLFTPSSL_ALL CURLUSESSL_ALL -#define CURLFTPSSL_LAST CURLUSESSL_LAST -#define curl_ftpssl curl_usessl -#endif /*!CURL_NO_OLDIES*/ - -/* parameter for the CURLOPT_FTP_SSL_CCC option */ -typedef enum { - CURLFTPSSL_CCC_NONE, /* do not send CCC */ - CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */ - CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */ - CURLFTPSSL_CCC_LAST /* not an option, never use */ -} curl_ftpccc; - -/* parameter for the CURLOPT_FTPSSLAUTH option */ -typedef enum { - CURLFTPAUTH_DEFAULT, /* let libcurl decide */ - CURLFTPAUTH_SSL, /* use "AUTH SSL" */ - CURLFTPAUTH_TLS, /* use "AUTH TLS" */ - CURLFTPAUTH_LAST /* not an option, never use */ -} curl_ftpauth; - -/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ -typedef enum { - CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */ - CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD - again if MKD succeeded, for SFTP this does - similar magic */ - CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD - again even if MKD failed! */ - CURLFTP_CREATE_DIR_LAST /* not an option, never use */ -} curl_ftpcreatedir; - -/* parameter for the CURLOPT_FTP_FILEMETHOD option */ -typedef enum { - CURLFTPMETHOD_DEFAULT, /* let libcurl pick */ - CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */ - CURLFTPMETHOD_NOCWD, /* no CWD at all */ - CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */ - CURLFTPMETHOD_LAST /* not an option, never use */ -} curl_ftpmethod; - -/* bitmask defines for CURLOPT_HEADEROPT */ -#define CURLHEADER_UNIFIED 0 -#define CURLHEADER_SEPARATE (1<<0) - -/* CURLALTSVC_* are bits for the CURLOPT_ALTSVC_CTRL option */ -#define CURLALTSVC_IMMEDIATELY (1<<0) - -#define CURLALTSVC_READONLYFILE (1<<2) -#define CURLALTSVC_H1 (1<<3) -#define CURLALTSVC_H2 (1<<4) -#define CURLALTSVC_H3 (1<<5) - -/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */ -#define CURLPROTO_HTTP (1<<0) -#define CURLPROTO_HTTPS (1<<1) -#define CURLPROTO_FTP (1<<2) -#define CURLPROTO_FTPS (1<<3) -#define CURLPROTO_SCP (1<<4) -#define CURLPROTO_SFTP (1<<5) -#define CURLPROTO_TELNET (1<<6) -#define CURLPROTO_LDAP (1<<7) -#define CURLPROTO_LDAPS (1<<8) -#define CURLPROTO_DICT (1<<9) -#define CURLPROTO_FILE (1<<10) -#define CURLPROTO_TFTP (1<<11) -#define CURLPROTO_IMAP (1<<12) -#define CURLPROTO_IMAPS (1<<13) -#define CURLPROTO_POP3 (1<<14) -#define CURLPROTO_POP3S (1<<15) -#define CURLPROTO_SMTP (1<<16) -#define CURLPROTO_SMTPS (1<<17) -#define CURLPROTO_RTSP (1<<18) -#define CURLPROTO_RTMP (1<<19) -#define CURLPROTO_RTMPT (1<<20) -#define CURLPROTO_RTMPE (1<<21) -#define CURLPROTO_RTMPTE (1<<22) -#define CURLPROTO_RTMPS (1<<23) -#define CURLPROTO_RTMPTS (1<<24) -#define CURLPROTO_GOPHER (1<<25) -#define CURLPROTO_SMB (1<<26) -#define CURLPROTO_SMBS (1<<27) -#define CURLPROTO_ALL (~0) /* enable everything */ - -/* long may be 32 or 64 bits, but we should never depend on anything else - but 32 */ -#define CURLOPTTYPE_LONG 0 -#define CURLOPTTYPE_OBJECTPOINT 10000 -#define CURLOPTTYPE_FUNCTIONPOINT 20000 -#define CURLOPTTYPE_OFF_T 30000 - -/* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the - string options from the header file */ - - -#define CURLOPT(na,t,nu) na = t + nu - -/* handy aliases that make no run-time difference */ -#define CURLOPTTYPE_STRINGPOINT CURLOPTTYPE_OBJECTPOINT -#define CURLOPTTYPE_SLISTPOINT CURLOPTTYPE_OBJECTPOINT - -/* - * All CURLOPT_* values. - */ - -typedef enum { - /* This is the FILE * or void * the regular output should be written to. */ - CURLOPT(CURLOPT_WRITEDATA, CURLOPTTYPE_OBJECTPOINT, 1), - - /* The full URL to get/put */ - CURLOPT(CURLOPT_URL, CURLOPTTYPE_STRINGPOINT, 2), - - /* Port number to connect to, if other than default. */ - CURLOPT(CURLOPT_PORT, CURLOPTTYPE_LONG, 3), - - /* Name of proxy to use. */ - CURLOPT(CURLOPT_PROXY, CURLOPTTYPE_STRINGPOINT, 4), - - /* "user:password;options" to use when fetching. */ - CURLOPT(CURLOPT_USERPWD, CURLOPTTYPE_STRINGPOINT, 5), - - /* "user:password" to use with proxy. */ - CURLOPT(CURLOPT_PROXYUSERPWD, CURLOPTTYPE_STRINGPOINT, 6), - - /* Range to get, specified as an ASCII string. */ - CURLOPT(CURLOPT_RANGE, CURLOPTTYPE_STRINGPOINT, 7), - - /* not used */ - - /* Specified file stream to upload from (use as input): */ - CURLOPT(CURLOPT_READDATA, CURLOPTTYPE_OBJECTPOINT, 9), - - /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE - * bytes big. */ - CURLOPT(CURLOPT_ERRORBUFFER, CURLOPTTYPE_OBJECTPOINT, 10), - - /* Function that will be called to store the output (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CURLOPT(CURLOPT_WRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 11), - - /* Function that will be called to read the input (instead of fread). The - * parameters will use fread() syntax, make sure to follow them. */ - CURLOPT(CURLOPT_READFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 12), - - /* Time-out the read operation after this amount of seconds */ - CURLOPT(CURLOPT_TIMEOUT, CURLOPTTYPE_LONG, 13), - - /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about - * how large the file being sent really is. That allows better error - * checking and better verifies that the upload was successful. -1 means - * unknown size. - * - * For large file support, there is also a _LARGE version of the key - * which takes an off_t type, allowing platforms with larger off_t - * sizes to handle larger files. See below for INFILESIZE_LARGE. - */ - CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14), - - /* POST static input fields. */ - CURLOPT(CURLOPT_POSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 15), - - /* Set the referrer page (needed by some CGIs) */ - CURLOPT(CURLOPT_REFERER, CURLOPTTYPE_STRINGPOINT, 16), - - /* Set the FTP PORT string (interface name, named or numerical IP address) - Use i.e '-' to use default address. */ - CURLOPT(CURLOPT_FTPPORT, CURLOPTTYPE_STRINGPOINT, 17), - - /* Set the User-Agent string (examined by some CGIs) */ - CURLOPT(CURLOPT_USERAGENT, CURLOPTTYPE_STRINGPOINT, 18), - - /* If the download receives less than "low speed limit" bytes/second - * during "low speed time" seconds, the operations is aborted. - * You could i.e if you have a pretty high speed connection, abort if - * it is less than 2000 bytes/sec during 20 seconds. - */ - - /* Set the "low speed limit" */ - CURLOPT(CURLOPT_LOW_SPEED_LIMIT, CURLOPTTYPE_LONG, 19), - - /* Set the "low speed time" */ - CURLOPT(CURLOPT_LOW_SPEED_TIME, CURLOPTTYPE_LONG, 20), - - /* Set the continuation offset. - * - * Note there is also a _LARGE version of this key which uses - * off_t types, allowing for large file offsets on platforms which - * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. - */ - CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21), - - /* Set cookie in request: */ - CURLOPT(CURLOPT_COOKIE, CURLOPTTYPE_STRINGPOINT, 22), - - /* This points to a linked list of headers, struct curl_slist kind. This - list is also used for RTSP (in spite of its name) */ - CURLOPT(CURLOPT_HTTPHEADER, CURLOPTTYPE_SLISTPOINT, 23), - - /* This points to a linked list of post entries, struct curl_httppost */ - CURLOPT(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24), - - /* name of the file keeping your private SSL-certificate */ - CURLOPT(CURLOPT_SSLCERT, CURLOPTTYPE_STRINGPOINT, 25), - - /* password for the SSL or SSH private key */ - CURLOPT(CURLOPT_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 26), - - /* send TYPE parameter? */ - CURLOPT(CURLOPT_CRLF, CURLOPTTYPE_LONG, 27), - - /* send linked-list of QUOTE commands */ - CURLOPT(CURLOPT_QUOTE, CURLOPTTYPE_SLISTPOINT, 28), - - /* send FILE * or void * to store headers to, if you use a callback it - is simply passed to the callback unmodified */ - CURLOPT(CURLOPT_HEADERDATA, CURLOPTTYPE_OBJECTPOINT, 29), - - /* point to a file to read the initial cookies from, also enables - "cookie awareness" */ - CURLOPT(CURLOPT_COOKIEFILE, CURLOPTTYPE_STRINGPOINT, 31), - - /* What version to specifically try to use. - See CURL_SSLVERSION defines below. */ - CURLOPT(CURLOPT_SSLVERSION, CURLOPTTYPE_LONG, 32), - - /* What kind of HTTP time condition to use, see defines */ - CURLOPT(CURLOPT_TIMECONDITION, CURLOPTTYPE_LONG, 33), - - /* Time to use with the above condition. Specified in number of seconds - since 1 Jan 1970 */ - CURLOPT(CURLOPT_TIMEVALUE, CURLOPTTYPE_LONG, 34), - - /* 35 = OBSOLETE */ - - /* Custom request, for customizing the get command like - HTTP: DELETE, TRACE and others - FTP: to use a different list command - */ - CURLOPT(CURLOPT_CUSTOMREQUEST, CURLOPTTYPE_STRINGPOINT, 36), - - /* FILE handle to use instead of stderr */ - CURLOPT(CURLOPT_STDERR, CURLOPTTYPE_OBJECTPOINT, 37), - - /* 38 is not used */ - - /* send linked-list of post-transfer QUOTE commands */ - CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39), - - /* OBSOLETE, do not use! */ - CURLOPT(CURLOPT_OBSOLETE40, CURLOPTTYPE_OBJECTPOINT, 40), - - /* talk a lot */ - CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41), - - /* throw the header out too */ - CURLOPT(CURLOPT_HEADER, CURLOPTTYPE_LONG, 42), - - /* shut off the progress meter */ - CURLOPT(CURLOPT_NOPROGRESS, CURLOPTTYPE_LONG, 43), - - /* use HEAD to get http document */ - CURLOPT(CURLOPT_NOBODY, CURLOPTTYPE_LONG, 44), - - /* no output on http error codes >= 400 */ - CURLOPT(CURLOPT_FAILONERROR, CURLOPTTYPE_LONG, 45), - - /* this is an upload */ - CURLOPT(CURLOPT_UPLOAD, CURLOPTTYPE_LONG, 46), - - /* HTTP POST method */ - CURLOPT(CURLOPT_POST, CURLOPTTYPE_LONG, 47), - - /* bare names when listing directories */ - CURLOPT(CURLOPT_DIRLISTONLY, CURLOPTTYPE_LONG, 48), - - /* Append instead of overwrite on upload! */ - CURLOPT(CURLOPT_APPEND, CURLOPTTYPE_LONG, 50), - - /* Specify whether to read the user+password from the .netrc or the URL. - * This must be one of the CURL_NETRC_* enums below. */ - CURLOPT(CURLOPT_NETRC, CURLOPTTYPE_LONG, 51), - - /* use Location: Luke! */ - CURLOPT(CURLOPT_FOLLOWLOCATION, CURLOPTTYPE_LONG, 52), - - /* transfer data in text/ASCII format */ - CURLOPT(CURLOPT_TRANSFERTEXT, CURLOPTTYPE_LONG, 53), - - /* HTTP PUT */ - CURLOPT(CURLOPT_PUT, CURLOPTTYPE_LONG, 54), - - /* 55 = OBSOLETE */ - - /* DEPRECATED - * Function that will be called instead of the internal progress display - * function. This function should be defined as the curl_progress_callback - * prototype defines. */ - CURLOPT(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56), - - /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION - callbacks */ - CURLOPT(CURLOPT_PROGRESSDATA, CURLOPTTYPE_OBJECTPOINT, 57), -#define CURLOPT_XFERINFODATA CURLOPT_PROGRESSDATA - - /* We want the referrer field set automatically when following locations */ - CURLOPT(CURLOPT_AUTOREFERER, CURLOPTTYPE_LONG, 58), - - /* Port of the proxy, can be set in the proxy string as well with: - "[host]:[port]" */ - CURLOPT(CURLOPT_PROXYPORT, CURLOPTTYPE_LONG, 59), - - /* size of the POST input data, if strlen() is not good to use */ - CURLOPT(CURLOPT_POSTFIELDSIZE, CURLOPTTYPE_LONG, 60), - - /* tunnel non-http operations through a HTTP proxy */ - CURLOPT(CURLOPT_HTTPPROXYTUNNEL, CURLOPTTYPE_LONG, 61), - - /* Set the interface string to use as outgoing network interface */ - CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62), - - /* Set the krb4/5 security level, this also enables krb4/5 awareness. This - * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string - * is set but doesn't match one of these, 'private' will be used. */ - CURLOPT(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63), - - /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ - CURLOPT(CURLOPT_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 64), - - /* The CApath or CAfile used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_CAINFO, CURLOPTTYPE_STRINGPOINT, 65), - - /* 66 = OBSOLETE */ - /* 67 = OBSOLETE */ - - /* Maximum number of http redirects to follow */ - CURLOPT(CURLOPT_MAXREDIRS, CURLOPTTYPE_LONG, 68), - - /* Pass a long set to 1 to get the date of the requested document (if - possible)! Pass a zero to shut it off. */ - CURLOPT(CURLOPT_FILETIME, CURLOPTTYPE_LONG, 69), - - /* This points to a linked list of telnet options */ - CURLOPT(CURLOPT_TELNETOPTIONS, CURLOPTTYPE_SLISTPOINT, 70), - - /* Max amount of cached alive connections */ - CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71), - - /* OBSOLETE, do not use! */ - CURLOPT(CURLOPT_OBSOLETE72, CURLOPTTYPE_LONG, 72), - - /* 73 = OBSOLETE */ - - /* Set to explicitly use a new connection for the upcoming transfer. - Do not use this unless you're absolutely sure of this, as it makes the - operation slower and is less friendly for the network. */ - CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74), - - /* Set to explicitly forbid the upcoming transfer's connection to be re-used - when done. Do not use this unless you're absolutely sure of this, as it - makes the operation slower and is less friendly for the network. */ - CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75), - - /* Set to a file name that contains random data for libcurl to use to - seed the random engine when doing SSL connects. */ - CURLOPT(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76), - - /* Set to the Entropy Gathering Daemon socket pathname */ - CURLOPT(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77), - - /* Time-out connect operations after this amount of seconds, if connects are - OK within this time, then fine... This only aborts the connect phase. */ - CURLOPT(CURLOPT_CONNECTTIMEOUT, CURLOPTTYPE_LONG, 78), - - /* Function that will be called to store headers (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CURLOPT(CURLOPT_HEADERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 79), - - /* Set this to force the HTTP request to get back to GET. Only really usable - if POST, PUT or a custom request have been used first. - */ - CURLOPT(CURLOPT_HTTPGET, CURLOPTTYPE_LONG, 80), - - /* Set if we should verify the Common name from the peer certificate in ssl - * handshake, set 1 to check existence, 2 to ensure that it matches the - * provided hostname. */ - CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81), - - /* Specify which file name to write all known cookies in after completed - operation. Set file name to "-" (dash) to make it go to stdout. */ - CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82), - - /* Specify which SSL ciphers to use */ - CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83), - - /* Specify which HTTP version to use! This must be set to one of the - CURL_HTTP_VERSION* enums set below. */ - CURLOPT(CURLOPT_HTTP_VERSION, CURLOPTTYPE_LONG, 84), - - /* Specifically switch on or off the FTP engine's use of the EPSV command. By - default, that one will always be attempted before the more traditional - PASV command. */ - CURLOPT(CURLOPT_FTP_USE_EPSV, CURLOPTTYPE_LONG, 85), - - /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ - CURLOPT(CURLOPT_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 86), - - /* name of the file keeping your private SSL-key */ - CURLOPT(CURLOPT_SSLKEY, CURLOPTTYPE_STRINGPOINT, 87), - - /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ - CURLOPT(CURLOPT_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 88), - - /* crypto engine for the SSL-sub system */ - CURLOPT(CURLOPT_SSLENGINE, CURLOPTTYPE_STRINGPOINT, 89), - - /* set the crypto engine for the SSL-sub system as default - the param has no meaning... - */ - CURLOPT(CURLOPT_SSLENGINE_DEFAULT, CURLOPTTYPE_LONG, 90), - - /* Non-zero value means to use the global dns cache */ - /* DEPRECATED, do not use! */ - CURLOPT(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91), - - /* DNS cache timeout */ - CURLOPT(CURLOPT_DNS_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 92), - - /* send linked-list of pre-transfer QUOTE commands */ - CURLOPT(CURLOPT_PREQUOTE, CURLOPTTYPE_SLISTPOINT, 93), - - /* set the debug function */ - CURLOPT(CURLOPT_DEBUGFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 94), - - /* set the data for the debug function */ - CURLOPT(CURLOPT_DEBUGDATA, CURLOPTTYPE_OBJECTPOINT, 95), - - /* mark this as start of a cookie session */ - CURLOPT(CURLOPT_COOKIESESSION, CURLOPTTYPE_LONG, 96), - - /* The CApath directory used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_CAPATH, CURLOPTTYPE_STRINGPOINT, 97), - - /* Instruct libcurl to use a smaller receive buffer */ - CURLOPT(CURLOPT_BUFFERSIZE, CURLOPTTYPE_LONG, 98), - - /* Instruct libcurl to not use any signal/alarm handlers, even when using - timeouts. This option is useful for multi-threaded applications. - See libcurl-the-guide for more background information. */ - CURLOPT(CURLOPT_NOSIGNAL, CURLOPTTYPE_LONG, 99), - - /* Provide a CURLShare for mutexing non-ts data */ - CURLOPT(CURLOPT_SHARE, CURLOPTTYPE_OBJECTPOINT, 100), - - /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), - CURLPROXY_HTTPS, CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and - CURLPROXY_SOCKS5. */ - CURLOPT(CURLOPT_PROXYTYPE, CURLOPTTYPE_LONG, 101), - - /* Set the Accept-Encoding string. Use this to tell a server you would like - the response to be compressed. Before 7.21.6, this was known as - CURLOPT_ENCODING */ - CURLOPT(CURLOPT_ACCEPT_ENCODING, CURLOPTTYPE_STRINGPOINT, 102), - - /* Set pointer to private data */ - CURLOPT(CURLOPT_PRIVATE, CURLOPTTYPE_OBJECTPOINT, 103), - - /* Set aliases for HTTP 200 in the HTTP Response header */ - CURLOPT(CURLOPT_HTTP200ALIASES, CURLOPTTYPE_SLISTPOINT, 104), - - /* Continue to send authentication (user+password) when following locations, - even when hostname changed. This can potentially send off the name - and password to whatever host the server decides. */ - CURLOPT(CURLOPT_UNRESTRICTED_AUTH, CURLOPTTYPE_LONG, 105), - - /* Specifically switch on or off the FTP engine's use of the EPRT command ( - it also disables the LPRT attempt). By default, those ones will always be - attempted before the good old traditional PORT command. */ - CURLOPT(CURLOPT_FTP_USE_EPRT, CURLOPTTYPE_LONG, 106), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_USERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_LONG, 107), - - /* Set the ssl context callback function, currently only for OpenSSL or - WolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument. - The function must match the curl_ssl_ctx_callback prototype. */ - CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108), - - /* Set the userdata for the ssl context callback function's third - argument */ - CURLOPT(CURLOPT_SSL_CTX_DATA, CURLOPTTYPE_OBJECTPOINT, 109), - - /* FTP Option that causes missing dirs to be created on the remote server. - In 7.19.4 we introduced the convenience enums for this option using the - CURLFTP_CREATE_DIR prefix. - */ - CURLOPT(CURLOPT_FTP_CREATE_MISSING_DIRS, CURLOPTTYPE_LONG, 110), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_LONG, 111), - - /* FTP option that changes the timeout, in seconds, associated with - getting a response. This is different from transfer timeout time and - essentially places a demand on the FTP server to acknowledge commands - in a timely manner. */ - CURLOPT(CURLOPT_FTP_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112), -#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT - - /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to - tell libcurl to resolve names to those IP versions only. This only has - affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */ - CURLOPT(CURLOPT_IPRESOLVE, CURLOPTTYPE_LONG, 113), - - /* Set this option to limit the size of a file that will be downloaded from - an HTTP or FTP server. - - Note there is also _LARGE version which adds large file support for - platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ - CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114), - - /* See the comment for INFILESIZE above, but in short, specifies - * the size of the file being uploaded. -1 means unknown. - */ - CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115), - - /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version - * of this; look above for RESUME_FROM. - */ - CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116), - - /* Sets the maximum size of data that will be downloaded from - * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. - */ - CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117), - - /* Set this option to the file name of your .netrc file you want libcurl - to parse (using the CURLOPT_NETRC option). If not set, libcurl will do - a poor attempt to find the user's home directory and check for a .netrc - file in there. */ - CURLOPT(CURLOPT_NETRC_FILE, CURLOPTTYPE_STRINGPOINT, 118), - - /* Enable SSL/TLS for FTP, pick one of: - CURLUSESSL_TRY - try using SSL, proceed anyway otherwise - CURLUSESSL_CONTROL - SSL for the control connection or fail - CURLUSESSL_ALL - SSL for all communication or fail - */ - CURLOPT(CURLOPT_USE_SSL, CURLOPTTYPE_LONG, 119), - - /* The _LARGE version of the standard POSTFIELDSIZE option */ - CURLOPT(CURLOPT_POSTFIELDSIZE_LARGE, CURLOPTTYPE_OFF_T, 120), - - /* Enable/disable the TCP Nagle algorithm */ - CURLOPT(CURLOPT_TCP_NODELAY, CURLOPTTYPE_LONG, 121), - - /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 123 OBSOLETE. Gone in 7.16.0 */ - /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 127 OBSOLETE. Gone in 7.16.0 */ - /* 128 OBSOLETE. Gone in 7.16.0 */ - - /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option - can be used to change libcurl's default action which is to first try - "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK - response has been received. - - Available parameters are: - CURLFTPAUTH_DEFAULT - let libcurl decide - CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS - CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL - */ - CURLOPT(CURLOPT_FTPSSLAUTH, CURLOPTTYPE_LONG, 129), - - CURLOPT(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130), - CURLOPT(CURLOPT_IOCTLDATA, CURLOPTTYPE_OBJECTPOINT, 131), - - /* 132 OBSOLETE. Gone in 7.16.0 */ - /* 133 OBSOLETE. Gone in 7.16.0 */ - - /* zero terminated string for pass on to the FTP server when asked for - "account" info */ - CURLOPT(CURLOPT_FTP_ACCOUNT, CURLOPTTYPE_STRINGPOINT, 134), - - /* feed cookie into cookie engine */ - CURLOPT(CURLOPT_COOKIELIST, CURLOPTTYPE_STRINGPOINT, 135), - - /* ignore Content-Length */ - CURLOPT(CURLOPT_IGNORE_CONTENT_LENGTH, CURLOPTTYPE_LONG, 136), - - /* Set to non-zero to skip the IP address received in a 227 PASV FTP server - response. Typically used for FTP-SSL purposes but is not restricted to - that. libcurl will then instead use the same IP address it used for the - control connection. */ - CURLOPT(CURLOPT_FTP_SKIP_PASV_IP, CURLOPTTYPE_LONG, 137), - - /* Select "file method" to use when doing FTP, see the curl_ftpmethod - above. */ - CURLOPT(CURLOPT_FTP_FILEMETHOD, CURLOPTTYPE_LONG, 138), - - /* Local port number to bind the socket to */ - CURLOPT(CURLOPT_LOCALPORT, CURLOPTTYPE_LONG, 139), - - /* Number of ports to try, including the first one set with LOCALPORT. - Thus, setting it to 1 will make no additional attempts but the first. - */ - CURLOPT(CURLOPT_LOCALPORTRANGE, CURLOPTTYPE_LONG, 140), - - /* no transfer, set up connection and let application use the socket by - extracting it with CURLINFO_LASTSOCKET */ - CURLOPT(CURLOPT_CONNECT_ONLY, CURLOPTTYPE_LONG, 141), - - /* Function that will be called to convert from the - network encoding (instead of using the iconv calls in libcurl) */ - CURLOPT(CURLOPT_CONV_FROM_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 142), - - /* Function that will be called to convert to the - network encoding (instead of using the iconv calls in libcurl) */ - CURLOPT(CURLOPT_CONV_TO_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 143), - - /* Function that will be called to convert from UTF8 - (instead of using the iconv calls in libcurl) - Note that this is used only for SSL certificate processing */ - CURLOPT(CURLOPT_CONV_FROM_UTF8_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 144), - - /* if the connection proceeds too quickly then need to slow it down */ - /* limit-rate: maximum number of bytes per second to send or receive */ - CURLOPT(CURLOPT_MAX_SEND_SPEED_LARGE, CURLOPTTYPE_OFF_T, 145), - CURLOPT(CURLOPT_MAX_RECV_SPEED_LARGE, CURLOPTTYPE_OFF_T, 146), - - /* Pointer to command string to send if USER/PASS fails. */ - CURLOPT(CURLOPT_FTP_ALTERNATIVE_TO_USER, CURLOPTTYPE_STRINGPOINT, 147), - - /* callback function for setting socket options */ - CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148), - CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_OBJECTPOINT, 149), - - /* set to 0 to disable session ID re-use for this transfer, default is - enabled (== 1) */ - CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150), - - /* allowed SSH authentication methods */ - CURLOPT(CURLOPT_SSH_AUTH_TYPES, CURLOPTTYPE_LONG, 151), - - /* Used by scp/sftp to do public/private key authentication */ - CURLOPT(CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPTTYPE_STRINGPOINT, 152), - CURLOPT(CURLOPT_SSH_PRIVATE_KEYFILE, CURLOPTTYPE_STRINGPOINT, 153), - - /* Send CCC (Clear Command Channel) after authentication */ - CURLOPT(CURLOPT_FTP_SSL_CCC, CURLOPTTYPE_LONG, 154), - - /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ - CURLOPT(CURLOPT_TIMEOUT_MS, CURLOPTTYPE_LONG, 155), - CURLOPT(CURLOPT_CONNECTTIMEOUT_MS, CURLOPTTYPE_LONG, 156), - - /* set to zero to disable the libcurl's decoding and thus pass the raw body - data to the application even when it is encoded/compressed */ - CURLOPT(CURLOPT_HTTP_TRANSFER_DECODING, CURLOPTTYPE_LONG, 157), - CURLOPT(CURLOPT_HTTP_CONTENT_DECODING, CURLOPTTYPE_LONG, 158), - - /* Permission used when creating new files and directories on the remote - server for protocols that support it, SFTP/SCP/FILE */ - CURLOPT(CURLOPT_NEW_FILE_PERMS, CURLOPTTYPE_LONG, 159), - CURLOPT(CURLOPT_NEW_DIRECTORY_PERMS, CURLOPTTYPE_LONG, 160), - - /* Set the behaviour of POST when redirecting. Values must be set to one - of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ - CURLOPT(CURLOPT_POSTREDIR, CURLOPTTYPE_LONG, 161), - - /* used by scp/sftp to verify the host's public key */ - CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, CURLOPTTYPE_STRINGPOINT, 162), - - /* Callback function for opening socket (instead of socket(2)). Optionally, - callback is able change the address or refuse to connect returning - CURL_SOCKET_BAD. The callback should have type - curl_opensocket_callback */ - CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163), - CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 164), - - /* POST volatile input fields. */ - CURLOPT(CURLOPT_COPYPOSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 165), - - /* set transfer mode (;type=) when doing FTP via an HTTP proxy */ - CURLOPT(CURLOPT_PROXY_TRANSFER_MODE, CURLOPTTYPE_LONG, 166), - - /* Callback function for seeking in the input stream */ - CURLOPT(CURLOPT_SEEKFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 167), - CURLOPT(CURLOPT_SEEKDATA, CURLOPTTYPE_OBJECTPOINT, 168), - - /* CRL file */ - CURLOPT(CURLOPT_CRLFILE, CURLOPTTYPE_STRINGPOINT, 169), - - /* Issuer certificate */ - CURLOPT(CURLOPT_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 170), - - /* (IPv6) Address scope */ - CURLOPT(CURLOPT_ADDRESS_SCOPE, CURLOPTTYPE_LONG, 171), - - /* Collect certificate chain info and allow it to get retrievable with - CURLINFO_CERTINFO after the transfer is complete. */ - CURLOPT(CURLOPT_CERTINFO, CURLOPTTYPE_LONG, 172), - - /* "name" and "pwd" to use when fetching. */ - CURLOPT(CURLOPT_USERNAME, CURLOPTTYPE_STRINGPOINT, 173), - CURLOPT(CURLOPT_PASSWORD, CURLOPTTYPE_STRINGPOINT, 174), - - /* "name" and "pwd" to use with Proxy when fetching. */ - CURLOPT(CURLOPT_PROXYUSERNAME, CURLOPTTYPE_STRINGPOINT, 175), - CURLOPT(CURLOPT_PROXYPASSWORD, CURLOPTTYPE_STRINGPOINT, 176), - - /* Comma separated list of hostnames defining no-proxy zones. These should - match both hostnames directly, and hostnames within a domain. For - example, local.com will match local.com and www.local.com, but NOT - notlocal.com or www.notlocal.com. For compatibility with other - implementations of this, .local.com will be considered to be the same as - local.com. A single * is the only valid wildcard, and effectively - disables the use of proxy. */ - CURLOPT(CURLOPT_NOPROXY, CURLOPTTYPE_STRINGPOINT, 177), - - /* block size for TFTP transfers */ - CURLOPT(CURLOPT_TFTP_BLKSIZE, CURLOPTTYPE_LONG, 178), - - /* Socks Service */ - /* DEPRECATED, do not use! */ - CURLOPT(CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOPTTYPE_STRINGPOINT, 179), - - /* Socks Service */ - CURLOPT(CURLOPT_SOCKS5_GSSAPI_NEC, CURLOPTTYPE_LONG, 180), - - /* set the bitmask for the protocols that are allowed to be used for the - transfer, which thus helps the app which takes URLs from users or other - external inputs and want to restrict what protocol(s) to deal - with. Defaults to CURLPROTO_ALL. */ - CURLOPT(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181), - - /* set the bitmask for the protocols that libcurl is allowed to follow to, - as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs - to be set in both bitmasks to be allowed to get redirected to. */ - CURLOPT(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182), - - /* set the SSH knownhost file name to use */ - CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183), - - /* set the SSH host key callback, must point to a curl_sshkeycallback - function */ - CURLOPT(CURLOPT_SSH_KEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 184), - - /* set the SSH host key callback custom pointer */ - CURLOPT(CURLOPT_SSH_KEYDATA, CURLOPTTYPE_OBJECTPOINT, 185), - - /* set the SMTP mail originator */ - CURLOPT(CURLOPT_MAIL_FROM, CURLOPTTYPE_STRINGPOINT, 186), - - /* set the list of SMTP mail receiver(s) */ - CURLOPT(CURLOPT_MAIL_RCPT, CURLOPTTYPE_SLISTPOINT, 187), - - /* FTP: send PRET before PASV */ - CURLOPT(CURLOPT_FTP_USE_PRET, CURLOPTTYPE_LONG, 188), - - /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ - CURLOPT(CURLOPT_RTSP_REQUEST, CURLOPTTYPE_LONG, 189), - - /* The RTSP session identifier */ - CURLOPT(CURLOPT_RTSP_SESSION_ID, CURLOPTTYPE_STRINGPOINT, 190), - - /* The RTSP stream URI */ - CURLOPT(CURLOPT_RTSP_STREAM_URI, CURLOPTTYPE_STRINGPOINT, 191), - - /* The Transport: header to use in RTSP requests */ - CURLOPT(CURLOPT_RTSP_TRANSPORT, CURLOPTTYPE_STRINGPOINT, 192), - - /* Manually initialize the client RTSP CSeq for this handle */ - CURLOPT(CURLOPT_RTSP_CLIENT_CSEQ, CURLOPTTYPE_LONG, 193), - - /* Manually initialize the server RTSP CSeq for this handle */ - CURLOPT(CURLOPT_RTSP_SERVER_CSEQ, CURLOPTTYPE_LONG, 194), - - /* The stream to pass to INTERLEAVEFUNCTION. */ - CURLOPT(CURLOPT_INTERLEAVEDATA, CURLOPTTYPE_OBJECTPOINT, 195), - - /* Let the application define a custom write method for RTP data */ - CURLOPT(CURLOPT_INTERLEAVEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 196), - - /* Turn on wildcard matching */ - CURLOPT(CURLOPT_WILDCARDMATCH, CURLOPTTYPE_LONG, 197), - - /* Directory matching callback called before downloading of an - individual file (chunk) started */ - CURLOPT(CURLOPT_CHUNK_BGN_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 198), - - /* Directory matching callback called after the file (chunk) - was downloaded, or skipped */ - CURLOPT(CURLOPT_CHUNK_END_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 199), - - /* Change match (fnmatch-like) callback for wildcard matching */ - CURLOPT(CURLOPT_FNMATCH_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 200), - - /* Let the application define custom chunk data pointer */ - CURLOPT(CURLOPT_CHUNK_DATA, CURLOPTTYPE_OBJECTPOINT, 201), - - /* FNMATCH_FUNCTION user pointer */ - CURLOPT(CURLOPT_FNMATCH_DATA, CURLOPTTYPE_OBJECTPOINT, 202), - - /* send linked-list of name:port:address sets */ - CURLOPT(CURLOPT_RESOLVE, CURLOPTTYPE_SLISTPOINT, 203), - - /* Set a username for authenticated TLS */ - CURLOPT(CURLOPT_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 204), - - /* Set a password for authenticated TLS */ - CURLOPT(CURLOPT_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 205), - - /* Set authentication type for authenticated TLS */ - CURLOPT(CURLOPT_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 206), - - /* Set to 1 to enable the "TE:" header in HTTP requests to ask for - compressed transfer-encoded responses. Set to 0 to disable the use of TE: - in outgoing requests. The current default is 0, but it might change in a - future libcurl release. - - libcurl will ask for the compressed methods it knows of, and if that - isn't any, it will not ask for transfer-encoding at all even if this - option is set to 1. - - */ - CURLOPT(CURLOPT_TRANSFER_ENCODING, CURLOPTTYPE_LONG, 207), - - /* Callback function for closing socket (instead of close(2)). The callback - should have type curl_closesocket_callback */ - CURLOPT(CURLOPT_CLOSESOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 208), - CURLOPT(CURLOPT_CLOSESOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 209), - - /* allow GSSAPI credential delegation */ - CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_LONG, 210), - - /* Set the name servers to use for DNS resolution */ - CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211), - - /* Time-out accept operations (currently for FTP only) after this amount - of milliseconds. */ - CURLOPT(CURLOPT_ACCEPTTIMEOUT_MS, CURLOPTTYPE_LONG, 212), - - /* Set TCP keepalive */ - CURLOPT(CURLOPT_TCP_KEEPALIVE, CURLOPTTYPE_LONG, 213), - - /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ - CURLOPT(CURLOPT_TCP_KEEPIDLE, CURLOPTTYPE_LONG, 214), - CURLOPT(CURLOPT_TCP_KEEPINTVL, CURLOPTTYPE_LONG, 215), - - /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ - CURLOPT(CURLOPT_SSL_OPTIONS, CURLOPTTYPE_LONG, 216), - - /* Set the SMTP auth originator */ - CURLOPT(CURLOPT_MAIL_AUTH, CURLOPTTYPE_STRINGPOINT, 217), - - /* Enable/disable SASL initial response */ - CURLOPT(CURLOPT_SASL_IR, CURLOPTTYPE_LONG, 218), - - /* Function that will be called instead of the internal progress display - * function. This function should be defined as the curl_xferinfo_callback - * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */ - CURLOPT(CURLOPT_XFERINFOFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 219), - - /* The XOAUTH2 bearer token */ - CURLOPT(CURLOPT_XOAUTH2_BEARER, CURLOPTTYPE_STRINGPOINT, 220), - - /* Set the interface string to use as outgoing network - * interface for DNS requests. - * Only supported by the c-ares DNS backend */ - CURLOPT(CURLOPT_DNS_INTERFACE, CURLOPTTYPE_STRINGPOINT, 221), - - /* Set the local IPv4 address to use for outgoing DNS requests. - * Only supported by the c-ares DNS backend */ - CURLOPT(CURLOPT_DNS_LOCAL_IP4, CURLOPTTYPE_STRINGPOINT, 222), - - /* Set the local IPv6 address to use for outgoing DNS requests. - * Only supported by the c-ares DNS backend */ - CURLOPT(CURLOPT_DNS_LOCAL_IP6, CURLOPTTYPE_STRINGPOINT, 223), - - /* Set authentication options directly */ - CURLOPT(CURLOPT_LOGIN_OPTIONS, CURLOPTTYPE_STRINGPOINT, 224), - - /* Enable/disable TLS NPN extension (http2 over ssl might fail without) */ - CURLOPT(CURLOPT_SSL_ENABLE_NPN, CURLOPTTYPE_LONG, 225), - - /* Enable/disable TLS ALPN extension (http2 over ssl might fail without) */ - CURLOPT(CURLOPT_SSL_ENABLE_ALPN, CURLOPTTYPE_LONG, 226), - - /* Time to wait for a response to a HTTP request containing an - * Expect: 100-continue header before sending the data anyway. */ - CURLOPT(CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPTTYPE_LONG, 227), - - /* This points to a linked list of headers used for proxy requests only, - struct curl_slist kind */ - CURLOPT(CURLOPT_PROXYHEADER, CURLOPTTYPE_SLISTPOINT, 228), - - /* Pass in a bitmask of "header options" */ - CURLOPT(CURLOPT_HEADEROPT, CURLOPTTYPE_LONG, 229), - - /* The public key in DER form used to validate the peer public key - this option is used only if SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 230), - - /* Path to Unix domain socket */ - CURLOPT(CURLOPT_UNIX_SOCKET_PATH, CURLOPTTYPE_STRINGPOINT, 231), - - /* Set if we should verify the certificate status. */ - CURLOPT(CURLOPT_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 232), - - /* Set if we should enable TLS false start. */ - CURLOPT(CURLOPT_SSL_FALSESTART, CURLOPTTYPE_LONG, 233), - - /* Do not squash dot-dot sequences */ - CURLOPT(CURLOPT_PATH_AS_IS, CURLOPTTYPE_LONG, 234), - - /* Proxy Service Name */ - CURLOPT(CURLOPT_PROXY_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 235), - - /* Service Name */ - CURLOPT(CURLOPT_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 236), - - /* Wait/don't wait for pipe/mutex to clarify */ - CURLOPT(CURLOPT_PIPEWAIT, CURLOPTTYPE_LONG, 237), - - /* Set the protocol used when curl is given a URL without a protocol */ - CURLOPT(CURLOPT_DEFAULT_PROTOCOL, CURLOPTTYPE_STRINGPOINT, 238), - - /* Set stream weight, 1 - 256 (default is 16) */ - CURLOPT(CURLOPT_STREAM_WEIGHT, CURLOPTTYPE_LONG, 239), - - /* Set stream dependency on another CURL handle */ - CURLOPT(CURLOPT_STREAM_DEPENDS, CURLOPTTYPE_OBJECTPOINT, 240), - - /* Set E-xclusive stream dependency on another CURL handle */ - CURLOPT(CURLOPT_STREAM_DEPENDS_E, CURLOPTTYPE_OBJECTPOINT, 241), - - /* Do not send any tftp option requests to the server */ - CURLOPT(CURLOPT_TFTP_NO_OPTIONS, CURLOPTTYPE_LONG, 242), - - /* Linked-list of host:port:connect-to-host:connect-to-port, - overrides the URL's host:port (only for the network layer) */ - CURLOPT(CURLOPT_CONNECT_TO, CURLOPTTYPE_SLISTPOINT, 243), - - /* Set TCP Fast Open */ - CURLOPT(CURLOPT_TCP_FASTOPEN, CURLOPTTYPE_LONG, 244), - - /* Continue to send data if the server responds early with an - * HTTP status code >= 300 */ - CURLOPT(CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPTTYPE_LONG, 245), - - /* The CApath or CAfile used to validate the proxy certificate - this option is used only if PROXY_SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PROXY_CAINFO, CURLOPTTYPE_STRINGPOINT, 246), - - /* The CApath directory used to validate the proxy certificate - this option is used only if PROXY_SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PROXY_CAPATH, CURLOPTTYPE_STRINGPOINT, 247), - - /* Set if we should verify the proxy in ssl handshake, - set 1 to verify. */ - CURLOPT(CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 248), - - /* Set if we should verify the Common name from the proxy certificate in ssl - * handshake, set 1 to check existence, 2 to ensure that it matches - * the provided hostname. */ - CURLOPT(CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 249), - - /* What version to specifically try to use for proxy. - See CURL_SSLVERSION defines below. */ - CURLOPT(CURLOPT_PROXY_SSLVERSION, CURLOPTTYPE_LONG, 250), - - /* Set a username for authenticated TLS for proxy */ - CURLOPT(CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 251), - - /* Set a password for authenticated TLS for proxy */ - CURLOPT(CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 252), - - /* Set authentication type for authenticated TLS for proxy */ - CURLOPT(CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 253), - - /* name of the file keeping your private SSL-certificate for proxy */ - CURLOPT(CURLOPT_PROXY_SSLCERT, CURLOPTTYPE_STRINGPOINT, 254), - - /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") for - proxy */ - CURLOPT(CURLOPT_PROXY_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 255), - - /* name of the file keeping your private SSL-key for proxy */ - CURLOPT(CURLOPT_PROXY_SSLKEY, CURLOPTTYPE_STRINGPOINT, 256), - - /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") for - proxy */ - CURLOPT(CURLOPT_PROXY_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 257), - - /* password for the SSL private key for proxy */ - CURLOPT(CURLOPT_PROXY_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 258), - - /* Specify which SSL ciphers to use for proxy */ - CURLOPT(CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 259), - - /* CRL file for proxy */ - CURLOPT(CURLOPT_PROXY_CRLFILE, CURLOPTTYPE_STRINGPOINT, 260), - - /* Enable/disable specific SSL features with a bitmask for proxy, see - CURLSSLOPT_* */ - CURLOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLOPTTYPE_LONG, 261), - - /* Name of pre proxy to use. */ - CURLOPT(CURLOPT_PRE_PROXY, CURLOPTTYPE_STRINGPOINT, 262), - - /* The public key in DER form used to validate the proxy public key - this option is used only if PROXY_SSL_VERIFYPEER is true */ - CURLOPT(CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 263), - - /* Path to an abstract Unix domain socket */ - CURLOPT(CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPTTYPE_STRINGPOINT, 264), - - /* Suppress proxy CONNECT response headers from user callbacks */ - CURLOPT(CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPTTYPE_LONG, 265), - - /* The request target, instead of extracted from the URL */ - CURLOPT(CURLOPT_REQUEST_TARGET, CURLOPTTYPE_STRINGPOINT, 266), - - /* bitmask of allowed auth methods for connections to SOCKS5 proxies */ - CURLOPT(CURLOPT_SOCKS5_AUTH, CURLOPTTYPE_LONG, 267), - - /* Enable/disable SSH compression */ - CURLOPT(CURLOPT_SSH_COMPRESSION, CURLOPTTYPE_LONG, 268), - - /* Post MIME data. */ - CURLOPT(CURLOPT_MIMEPOST, CURLOPTTYPE_OBJECTPOINT, 269), - - /* Time to use with the CURLOPT_TIMECONDITION. Specified in number of - seconds since 1 Jan 1970. */ - CURLOPT(CURLOPT_TIMEVALUE_LARGE, CURLOPTTYPE_OFF_T, 270), - - /* Head start in milliseconds to give happy eyeballs. */ - CURLOPT(CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPTTYPE_LONG, 271), - - /* Function that will be called before a resolver request is made */ - CURLOPT(CURLOPT_RESOLVER_START_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 272), - - /* User data to pass to the resolver start callback. */ - CURLOPT(CURLOPT_RESOLVER_START_DATA, CURLOPTTYPE_OBJECTPOINT, 273), - - /* send HAProxy PROXY protocol header? */ - CURLOPT(CURLOPT_HAPROXYPROTOCOL, CURLOPTTYPE_LONG, 274), - - /* shuffle addresses before use when DNS returns multiple */ - CURLOPT(CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPTTYPE_LONG, 275), - - /* Specify which TLS 1.3 ciphers suites to use */ - CURLOPT(CURLOPT_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 276), - CURLOPT(CURLOPT_PROXY_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 277), - - /* Disallow specifying username/login in URL. */ - CURLOPT(CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPTTYPE_LONG, 278), - - /* DNS-over-HTTPS URL */ - CURLOPT(CURLOPT_DOH_URL, CURLOPTTYPE_STRINGPOINT, 279), - - /* Preferred buffer size to use for uploads */ - CURLOPT(CURLOPT_UPLOAD_BUFFERSIZE, CURLOPTTYPE_LONG, 280), - - /* Time in ms between connection upkeep calls for long-lived connections. */ - CURLOPT(CURLOPT_UPKEEP_INTERVAL_MS, CURLOPTTYPE_LONG, 281), - - /* Specify URL using CURL URL API. */ - CURLOPT(CURLOPT_CURLU, CURLOPTTYPE_OBJECTPOINT, 282), - - /* add trailing data just after no more data is available */ - CURLOPT(CURLOPT_TRAILERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 283), - - /* pointer to be passed to HTTP_TRAILER_FUNCTION */ - CURLOPT(CURLOPT_TRAILERDATA, CURLOPTTYPE_OBJECTPOINT, 284), - - /* set this to 1L to allow HTTP/0.9 responses or 0L to disallow */ - CURLOPT(CURLOPT_HTTP09_ALLOWED, CURLOPTTYPE_LONG, 285), - - /* alt-svc control bitmask */ - CURLOPT(CURLOPT_ALTSVC_CTRL, CURLOPTTYPE_LONG, 286), - - /* alt-svc cache file name to possibly read from/write to */ - CURLOPT(CURLOPT_ALTSVC, CURLOPTTYPE_STRINGPOINT, 287), - - /* maximum age of a connection to consider it for reuse (in seconds) */ - CURLOPT(CURLOPT_MAXAGE_CONN, CURLOPTTYPE_LONG, 288), - - /* SASL authorisation identity */ - CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289), - - /* allow RCPT TO command to fail for some recipients */ - CURLOPT(CURLOPT_MAIL_RCPT_ALLLOWFAILS, CURLOPTTYPE_LONG, 290), - - CURLOPT_LASTENTRY /* the last unused */ -} CURLoption; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2011 */ - -/* This was added in version 7.19.1 */ -#define CURLOPT_POST301 CURLOPT_POSTREDIR - -/* These are scheduled to disappear by 2009 */ - -/* The following were added in 7.17.0 */ -#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_FTPAPPEND CURLOPT_APPEND -#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY -#define CURLOPT_FTP_SSL CURLOPT_USE_SSL - -/* The following were added earlier */ - -#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL - -#else -/* This is set if CURL_NO_OLDIES is defined at compile-time */ -#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ -#endif - - - /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host - name resolves addresses using more than one IP protocol version, this - option might be handy to force libcurl to use a specific IP version. */ -#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP - versions that your system allows */ -#define CURL_IPRESOLVE_V4 1 /* resolve to IPv4 addresses */ -#define CURL_IPRESOLVE_V6 2 /* resolve to IPv6 addresses */ - - /* three convenient "aliases" that follow the name scheme better */ -#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER - - /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ -enum { - CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd - like the library to choose the best possible - for us! */ - CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ - CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ - CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */ - CURL_HTTP_VERSION_2TLS, /* use version 2 for HTTPS, version 1.1 for HTTP */ - CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, /* please use HTTP 2 without HTTP/1.1 - Upgrade */ - CURL_HTTP_VERSION_3 = 30, /* Makes use of explicit HTTP/3 without fallback. - Use CURLOPT_ALTSVC to enable HTTP/3 upgrade */ - CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ -}; - -/* Convenience definition simple because the name of the version is HTTP/2 and - not 2.0. The 2_0 version of the enum name was set while the version was - still planned to be 2.0 and we stick to it for compatibility. */ -#define CURL_HTTP_VERSION_2 CURL_HTTP_VERSION_2_0 - -/* - * Public API enums for RTSP requests - */ -enum { - CURL_RTSPREQ_NONE, /* first in list */ - CURL_RTSPREQ_OPTIONS, - CURL_RTSPREQ_DESCRIBE, - CURL_RTSPREQ_ANNOUNCE, - CURL_RTSPREQ_SETUP, - CURL_RTSPREQ_PLAY, - CURL_RTSPREQ_PAUSE, - CURL_RTSPREQ_TEARDOWN, - CURL_RTSPREQ_GET_PARAMETER, - CURL_RTSPREQ_SET_PARAMETER, - CURL_RTSPREQ_RECORD, - CURL_RTSPREQ_RECEIVE, - CURL_RTSPREQ_LAST /* last in list */ -}; - - /* These enums are for use with the CURLOPT_NETRC option. */ -enum CURL_NETRC_OPTION { - CURL_NETRC_IGNORED, /* The .netrc will never be read. - * This is the default. */ - CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred - * to one in the .netrc. */ - CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored. - * Unless one is set programmatically, the .netrc - * will be queried. */ - CURL_NETRC_LAST -}; - -enum { - CURL_SSLVERSION_DEFAULT, - CURL_SSLVERSION_TLSv1, /* TLS 1.x */ - CURL_SSLVERSION_SSLv2, - CURL_SSLVERSION_SSLv3, - CURL_SSLVERSION_TLSv1_0, - CURL_SSLVERSION_TLSv1_1, - CURL_SSLVERSION_TLSv1_2, - CURL_SSLVERSION_TLSv1_3, - - CURL_SSLVERSION_LAST /* never use, keep last */ -}; - -enum { - CURL_SSLVERSION_MAX_NONE = 0, - CURL_SSLVERSION_MAX_DEFAULT = (CURL_SSLVERSION_TLSv1 << 16), - CURL_SSLVERSION_MAX_TLSv1_0 = (CURL_SSLVERSION_TLSv1_0 << 16), - CURL_SSLVERSION_MAX_TLSv1_1 = (CURL_SSLVERSION_TLSv1_1 << 16), - CURL_SSLVERSION_MAX_TLSv1_2 = (CURL_SSLVERSION_TLSv1_2 << 16), - CURL_SSLVERSION_MAX_TLSv1_3 = (CURL_SSLVERSION_TLSv1_3 << 16), - - /* never use, keep last */ - CURL_SSLVERSION_MAX_LAST = (CURL_SSLVERSION_LAST << 16) -}; - -enum CURL_TLSAUTH { - CURL_TLSAUTH_NONE, - CURL_TLSAUTH_SRP, - CURL_TLSAUTH_LAST /* never use, keep last */ -}; - -/* symbols to use with CURLOPT_POSTREDIR. - CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 - can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 - | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ - -#define CURL_REDIR_GET_ALL 0 -#define CURL_REDIR_POST_301 1 -#define CURL_REDIR_POST_302 2 -#define CURL_REDIR_POST_303 4 -#define CURL_REDIR_POST_ALL \ - (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303) - -typedef enum { - CURL_TIMECOND_NONE, - - CURL_TIMECOND_IFMODSINCE, - CURL_TIMECOND_IFUNMODSINCE, - CURL_TIMECOND_LASTMOD, - - CURL_TIMECOND_LAST -} curl_TimeCond; - -/* Special size_t value signaling a zero-terminated string. */ -#define CURL_ZERO_TERMINATED ((size_t) -1) - -/* curl_strequal() and curl_strnequal() are subject for removal in a future - release */ -CURL_EXTERN int curl_strequal(const char *s1, const char *s2); -CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n); - -/* Mime/form handling support. */ -typedef struct curl_mime_s curl_mime; /* Mime context. */ -typedef struct curl_mimepart_s curl_mimepart; /* Mime part context. */ - -/* - * NAME curl_mime_init() - * - * DESCRIPTION - * - * Create a mime context and return its handle. The easy parameter is the - * target handle. - */ -CURL_EXTERN curl_mime *curl_mime_init(CURL *easy); - -/* - * NAME curl_mime_free() - * - * DESCRIPTION - * - * release a mime handle and its substructures. - */ -CURL_EXTERN void curl_mime_free(curl_mime *mime); - -/* - * NAME curl_mime_addpart() - * - * DESCRIPTION - * - * Append a new empty part to the given mime context and return a handle to - * the created part. - */ -CURL_EXTERN curl_mimepart *curl_mime_addpart(curl_mime *mime); - -/* - * NAME curl_mime_name() - * - * DESCRIPTION - * - * Set mime/form part name. - */ -CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name); - -/* - * NAME curl_mime_filename() - * - * DESCRIPTION - * - * Set mime part remote file name. - */ -CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part, - const char *filename); - -/* - * NAME curl_mime_type() - * - * DESCRIPTION - * - * Set mime part type. - */ -CURL_EXTERN CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype); - -/* - * NAME curl_mime_encoder() - * - * DESCRIPTION - * - * Set mime data transfer encoder. - */ -CURL_EXTERN CURLcode curl_mime_encoder(curl_mimepart *part, - const char *encoding); - -/* - * NAME curl_mime_data() - * - * DESCRIPTION - * - * Set mime part data source from memory data, - */ -CURL_EXTERN CURLcode curl_mime_data(curl_mimepart *part, - const char *data, size_t datasize); - -/* - * NAME curl_mime_filedata() - * - * DESCRIPTION - * - * Set mime part data source from named file. - */ -CURL_EXTERN CURLcode curl_mime_filedata(curl_mimepart *part, - const char *filename); - -/* - * NAME curl_mime_data_cb() - * - * DESCRIPTION - * - * Set mime part data source from callback function. - */ -CURL_EXTERN CURLcode curl_mime_data_cb(curl_mimepart *part, - curl_off_t datasize, - curl_read_callback readfunc, - curl_seek_callback seekfunc, - curl_free_callback freefunc, - void *arg); - -/* - * NAME curl_mime_subparts() - * - * DESCRIPTION - * - * Set mime part data source from subparts. - */ -CURL_EXTERN CURLcode curl_mime_subparts(curl_mimepart *part, - curl_mime *subparts); -/* - * NAME curl_mime_headers() - * - * DESCRIPTION - * - * Set mime part headers. - */ -CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part, - struct curl_slist *headers, - int take_ownership); - -typedef enum { - CURLFORM_NOTHING, /********* the first one is unused ************/ - CURLFORM_COPYNAME, - CURLFORM_PTRNAME, - CURLFORM_NAMELENGTH, - CURLFORM_COPYCONTENTS, - CURLFORM_PTRCONTENTS, - CURLFORM_CONTENTSLENGTH, - CURLFORM_FILECONTENT, - CURLFORM_ARRAY, - CURLFORM_OBSOLETE, - CURLFORM_FILE, - - CURLFORM_BUFFER, - CURLFORM_BUFFERPTR, - CURLFORM_BUFFERLENGTH, - - CURLFORM_CONTENTTYPE, - CURLFORM_CONTENTHEADER, - CURLFORM_FILENAME, - CURLFORM_END, - CURLFORM_OBSOLETE2, - - CURLFORM_STREAM, - CURLFORM_CONTENTLEN, /* added in 7.46.0, provide a curl_off_t length */ - - CURLFORM_LASTENTRY /* the last unused */ -} CURLformoption; - -/* structure to be used as parameter for CURLFORM_ARRAY */ -struct curl_forms { - CURLformoption option; - const char *value; -}; - -/* use this for multipart formpost building */ -/* Returns code for curl_formadd() - * - * Returns: - * CURL_FORMADD_OK on success - * CURL_FORMADD_MEMORY if the FormInfo allocation fails - * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form - * CURL_FORMADD_NULL if a null pointer was given for a char - * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed - * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used - * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) - * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated - * CURL_FORMADD_MEMORY if some allocation for string copying failed. - * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array - * - ***************************************************************************/ -typedef enum { - CURL_FORMADD_OK, /* first, no error */ - - CURL_FORMADD_MEMORY, - CURL_FORMADD_OPTION_TWICE, - CURL_FORMADD_NULL, - CURL_FORMADD_UNKNOWN_OPTION, - CURL_FORMADD_INCOMPLETE, - CURL_FORMADD_ILLEGAL_ARRAY, - CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */ - - CURL_FORMADD_LAST /* last */ -} CURLFORMcode; - -/* - * NAME curl_formadd() - * - * DESCRIPTION - * - * Pretty advanced function for building multi-part formposts. Each invoke - * adds one part that together construct a full post. Then use - * CURLOPT_HTTPPOST to send it off to libcurl. - */ -CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost, - struct curl_httppost **last_post, - ...); - -/* - * callback function for curl_formget() - * The void *arg pointer will be the one passed as second argument to - * curl_formget(). - * The character buffer passed to it must not be freed. - * Should return the buffer length passed to it as the argument "len" on - * success. - */ -typedef size_t (*curl_formget_callback)(void *arg, const char *buf, - size_t len); - -/* - * NAME curl_formget() - * - * DESCRIPTION - * - * Serialize a curl_httppost struct built with curl_formadd(). - * Accepts a void pointer as second argument which will be passed to - * the curl_formget_callback function. - * Returns 0 on success. - */ -CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg, - curl_formget_callback append); -/* - * NAME curl_formfree() - * - * DESCRIPTION - * - * Free a multipart formpost previously built with curl_formadd(). - */ -CURL_EXTERN void curl_formfree(struct curl_httppost *form); - -/* - * NAME curl_getenv() - * - * DESCRIPTION - * - * Returns a malloc()'ed string that MUST be curl_free()ed after usage is - * complete. DEPRECATED - see lib/README.curlx - */ -CURL_EXTERN char *curl_getenv(const char *variable); - -/* - * NAME curl_version() - * - * DESCRIPTION - * - * Returns a static ascii string of the libcurl version. - */ -CURL_EXTERN char *curl_version(void); - -/* - * NAME curl_easy_escape() - * - * DESCRIPTION - * - * Escapes URL strings (converts all letters consider illegal in URLs to their - * %XX versions). This function returns a new allocated string or NULL if an - * error occurred. - */ -CURL_EXTERN char *curl_easy_escape(CURL *handle, - const char *string, - int length); - -/* the previous version: */ -CURL_EXTERN char *curl_escape(const char *string, - int length); - - -/* - * NAME curl_easy_unescape() - * - * DESCRIPTION - * - * Unescapes URL encoding in strings (converts all %XX codes to their 8bit - * versions). This function returns a new allocated string or NULL if an error - * occurred. - * Conversion Note: On non-ASCII platforms the ASCII %XX codes are - * converted into the host encoding. - */ -CURL_EXTERN char *curl_easy_unescape(CURL *handle, - const char *string, - int length, - int *outlength); - -/* the previous version */ -CURL_EXTERN char *curl_unescape(const char *string, - int length); - -/* - * NAME curl_free() - * - * DESCRIPTION - * - * Provided for de-allocation in the same translation unit that did the - * allocation. Added in libcurl 7.10 - */ -CURL_EXTERN void curl_free(void *p); - -/* - * NAME curl_global_init() - * - * DESCRIPTION - * - * curl_global_init() should be invoked exactly once for each application that - * uses libcurl and before any call of other libcurl functions. - * - * This function is not thread-safe! - */ -CURL_EXTERN CURLcode curl_global_init(long flags); - -/* - * NAME curl_global_init_mem() - * - * DESCRIPTION - * - * curl_global_init() or curl_global_init_mem() should be invoked exactly once - * for each application that uses libcurl. This function can be used to - * initialize libcurl and set user defined memory management callback - * functions. Users can implement memory management routines to check for - * memory leaks, check for mis-use of the curl library etc. User registered - * callback routines with be invoked by this library instead of the system - * memory management routines like malloc, free etc. - */ -CURL_EXTERN CURLcode curl_global_init_mem(long flags, - curl_malloc_callback m, - curl_free_callback f, - curl_realloc_callback r, - curl_strdup_callback s, - curl_calloc_callback c); - -/* - * NAME curl_global_cleanup() - * - * DESCRIPTION - * - * curl_global_cleanup() should be invoked exactly once for each application - * that uses libcurl - */ -CURL_EXTERN void curl_global_cleanup(void); - -/* linked-list structure for the CURLOPT_QUOTE option (and other) */ -struct curl_slist { - char *data; - struct curl_slist *next; -}; - -/* - * NAME curl_global_sslset() - * - * DESCRIPTION - * - * When built with multiple SSL backends, curl_global_sslset() allows to - * choose one. This function can only be called once, and it must be called - * *before* curl_global_init(). - * - * The backend can be identified by the id (e.g. CURLSSLBACKEND_OPENSSL). The - * backend can also be specified via the name parameter (passing -1 as id). - * If both id and name are specified, the name will be ignored. If neither id - * nor name are specified, the function will fail with - * CURLSSLSET_UNKNOWN_BACKEND and set the "avail" pointer to the - * NULL-terminated list of available backends. - * - * Upon success, the function returns CURLSSLSET_OK. - * - * If the specified SSL backend is not available, the function returns - * CURLSSLSET_UNKNOWN_BACKEND and sets the "avail" pointer to a NULL-terminated - * list of available SSL backends. - * - * The SSL backend can be set only once. If it has already been set, a - * subsequent attempt to change it will result in a CURLSSLSET_TOO_LATE. - */ - -typedef struct { - curl_sslbackend id; - const char *name; -} curl_ssl_backend; - -typedef enum { - CURLSSLSET_OK = 0, - CURLSSLSET_UNKNOWN_BACKEND, - CURLSSLSET_TOO_LATE, - CURLSSLSET_NO_BACKENDS /* libcurl was built without any SSL support */ -} CURLsslset; - -CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, - const curl_ssl_backend ***avail); - -/* - * NAME curl_slist_append() - * - * DESCRIPTION - * - * Appends a string to a linked list. If no list exists, it will be created - * first. Returns the new list, after appending. - */ -CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *, - const char *); - -/* - * NAME curl_slist_free_all() - * - * DESCRIPTION - * - * free a previously built curl_slist. - */ -CURL_EXTERN void curl_slist_free_all(struct curl_slist *); - -/* - * NAME curl_getdate() - * - * DESCRIPTION - * - * Returns the time, in seconds since 1 Jan 1970 of the time string given in - * the first argument. The time argument in the second parameter is unused - * and should be set to NULL. - */ -CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); - -/* info about the certificate chain, only for OpenSSL, GnuTLS, Schannel, NSS - and GSKit builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ -struct curl_certinfo { - int num_of_certs; /* number of certificates with information */ - struct curl_slist **certinfo; /* for each index in this array, there's a - linked list with textual information in the - format "name: value" */ -}; - -/* Information about the SSL library used and the respective internal SSL - handle, which can be used to obtain further information regarding the - connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */ -struct curl_tlssessioninfo { - curl_sslbackend backend; - void *internals; -}; - -#define CURLINFO_STRING 0x100000 -#define CURLINFO_LONG 0x200000 -#define CURLINFO_DOUBLE 0x300000 -#define CURLINFO_SLIST 0x400000 -#define CURLINFO_PTR 0x400000 /* same as SLIST */ -#define CURLINFO_SOCKET 0x500000 -#define CURLINFO_OFF_T 0x600000 -#define CURLINFO_MASK 0x0fffff -#define CURLINFO_TYPEMASK 0xf00000 - -typedef enum { - CURLINFO_NONE, /* first, never use this */ - CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, - CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, - CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, - CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, - CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, - CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, - CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7, - CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7, - CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8, - CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8, - CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9, - CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9, - CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10, - CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10, - CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, - CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, - CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, - CURLINFO_FILETIME = CURLINFO_LONG + 14, - CURLINFO_FILETIME_T = CURLINFO_OFF_T + 14, - CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15, - CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15, - CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16, - CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16, - CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, - CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, - CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, - CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, - CURLINFO_PRIVATE = CURLINFO_STRING + 21, - CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, - CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, - CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, - CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, - CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, - CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, - CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, - CURLINFO_LASTSOCKET = CURLINFO_LONG + 29, - CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, - CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, - CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, - CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, - CURLINFO_CERTINFO = CURLINFO_PTR + 34, - CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, - CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, - CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, - CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, - CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, - CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, - CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, - CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, - CURLINFO_TLS_SESSION = CURLINFO_PTR + 43, - CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44, - CURLINFO_TLS_SSL_PTR = CURLINFO_PTR + 45, - CURLINFO_HTTP_VERSION = CURLINFO_LONG + 46, - CURLINFO_PROXY_SSL_VERIFYRESULT = CURLINFO_LONG + 47, - CURLINFO_PROTOCOL = CURLINFO_LONG + 48, - CURLINFO_SCHEME = CURLINFO_STRING + 49, - /* Fill in new entries below here! */ - - /* Preferably these would be defined conditionally based on the - sizeof curl_off_t being 64-bits */ - CURLINFO_TOTAL_TIME_T = CURLINFO_OFF_T + 50, - CURLINFO_NAMELOOKUP_TIME_T = CURLINFO_OFF_T + 51, - CURLINFO_CONNECT_TIME_T = CURLINFO_OFF_T + 52, - CURLINFO_PRETRANSFER_TIME_T = CURLINFO_OFF_T + 53, - CURLINFO_STARTTRANSFER_TIME_T = CURLINFO_OFF_T + 54, - CURLINFO_REDIRECT_TIME_T = CURLINFO_OFF_T + 55, - CURLINFO_APPCONNECT_TIME_T = CURLINFO_OFF_T + 56, - CURLINFO_RETRY_AFTER = CURLINFO_OFF_T + 57, - - CURLINFO_LASTONE = 57 -} CURLINFO; - -/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as - CURLINFO_HTTP_CODE */ -#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE - -typedef enum { - CURLCLOSEPOLICY_NONE, /* first, never use this */ - - CURLCLOSEPOLICY_OLDEST, - CURLCLOSEPOLICY_LEAST_RECENTLY_USED, - CURLCLOSEPOLICY_LEAST_TRAFFIC, - CURLCLOSEPOLICY_SLOWEST, - CURLCLOSEPOLICY_CALLBACK, - - CURLCLOSEPOLICY_LAST /* last, never use this */ -} curl_closepolicy; - -#define CURL_GLOBAL_SSL (1<<0) /* no purpose since since 7.57.0 */ -#define CURL_GLOBAL_WIN32 (1<<1) -#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) -#define CURL_GLOBAL_NOTHING 0 -#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL -#define CURL_GLOBAL_ACK_EINTR (1<<2) - - -/***************************************************************************** - * Setup defines, protos etc for the sharing stuff. - */ - -/* Different data locks for a single share */ -typedef enum { - CURL_LOCK_DATA_NONE = 0, - /* CURL_LOCK_DATA_SHARE is used internally to say that - * the locking is just made to change the internal state of the share - * itself. - */ - CURL_LOCK_DATA_SHARE, - CURL_LOCK_DATA_COOKIE, - CURL_LOCK_DATA_DNS, - CURL_LOCK_DATA_SSL_SESSION, - CURL_LOCK_DATA_CONNECT, - CURL_LOCK_DATA_PSL, - CURL_LOCK_DATA_LAST -} curl_lock_data; - -/* Different lock access types */ -typedef enum { - CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ - CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ - CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ - CURL_LOCK_ACCESS_LAST /* never use */ -} curl_lock_access; - -typedef void (*curl_lock_function)(CURL *handle, - curl_lock_data data, - curl_lock_access locktype, - void *userptr); -typedef void (*curl_unlock_function)(CURL *handle, - curl_lock_data data, - void *userptr); - - -typedef enum { - CURLSHE_OK, /* all is fine */ - CURLSHE_BAD_OPTION, /* 1 */ - CURLSHE_IN_USE, /* 2 */ - CURLSHE_INVALID, /* 3 */ - CURLSHE_NOMEM, /* 4 out of memory */ - CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ - CURLSHE_LAST /* never use */ -} CURLSHcode; - -typedef enum { - CURLSHOPT_NONE, /* don't use */ - CURLSHOPT_SHARE, /* specify a data type to share */ - CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ - CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ - CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ - CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock - callback functions */ - CURLSHOPT_LAST /* never use */ -} CURLSHoption; - -CURL_EXTERN CURLSH *curl_share_init(void); -CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...); -CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *); - -/**************************************************************************** - * Structures for querying information about the curl library at runtime. - */ - -typedef enum { - CURLVERSION_FIRST, - CURLVERSION_SECOND, - CURLVERSION_THIRD, - CURLVERSION_FOURTH, - CURLVERSION_FIFTH, - CURLVERSION_SIXTH, - CURLVERSION_LAST /* never actually use this */ -} CURLversion; - -/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by - basically all programs ever that want to get version information. It is - meant to be a built-in version number for what kind of struct the caller - expects. If the struct ever changes, we redefine the NOW to another enum - from above. */ -#define CURLVERSION_NOW CURLVERSION_SIXTH - -typedef struct { - CURLversion age; /* age of the returned struct */ - const char *version; /* LIBCURL_VERSION */ - unsigned int version_num; /* LIBCURL_VERSION_NUM */ - const char *host; /* OS/host/cpu/machine when configured */ - int features; /* bitmask, see defines below */ - const char *ssl_version; /* human readable string */ - long ssl_version_num; /* not used anymore, always 0 */ - const char *libz_version; /* human readable string */ - /* protocols is terminated by an entry with a NULL protoname */ - const char * const *protocols; - - /* The fields below this were added in CURLVERSION_SECOND */ - const char *ares; - int ares_num; - - /* This field was added in CURLVERSION_THIRD */ - const char *libidn; - - /* These field were added in CURLVERSION_FOURTH */ - - /* Same as '_libiconv_version' if built with HAVE_ICONV */ - int iconv_ver_num; - - const char *libssh_version; /* human readable string */ - - /* These fields were added in CURLVERSION_FIFTH */ - unsigned int brotli_ver_num; /* Numeric Brotli version - (MAJOR << 24) | (MINOR << 12) | PATCH */ - const char *brotli_version; /* human readable string. */ - - /* These fields were added in CURLVERSION_SIXTH */ - unsigned int nghttp2_ver_num; /* Numeric nghttp2 version - (MAJOR << 16) | (MINOR << 8) | PATCH */ - const char *nghttp2_version; /* human readable string. */ - const char *quic_version; /* human readable quic (+ HTTP/3) library + - version or NULL */ -} curl_version_info_data; - -#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ -#define CURL_VERSION_KERBEROS4 (1<<1) /* Kerberos V4 auth is supported - (deprecated) */ -#define CURL_VERSION_SSL (1<<2) /* SSL options are present */ -#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ -#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ -#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth is supported - (deprecated) */ -#define CURL_VERSION_DEBUG (1<<6) /* Built with debug capabilities */ -#define CURL_VERSION_ASYNCHDNS (1<<7) /* Asynchronous DNS resolves */ -#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth is supported */ -#define CURL_VERSION_LARGEFILE (1<<9) /* Supports files larger than 2GB */ -#define CURL_VERSION_IDN (1<<10) /* Internationized Domain Names are - supported */ -#define CURL_VERSION_SSPI (1<<11) /* Built against Windows SSPI */ -#define CURL_VERSION_CONV (1<<12) /* Character conversions supported */ -#define CURL_VERSION_CURLDEBUG (1<<13) /* Debug memory tracking supported */ -#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ -#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegation to winbind helper - is supported */ -#define CURL_VERSION_HTTP2 (1<<16) /* HTTP2 support built-in */ -#define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */ -#define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */ -#define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */ -#define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used - for cookie domain verification */ -#define CURL_VERSION_HTTPS_PROXY (1<<21) /* HTTPS-proxy support built-in */ -#define CURL_VERSION_MULTI_SSL (1<<22) /* Multiple SSL backends available */ -#define CURL_VERSION_BROTLI (1<<23) /* Brotli features are present. */ -#define CURL_VERSION_ALTSVC (1<<24) /* Alt-Svc handling built-in */ -#define CURL_VERSION_HTTP3 (1<<25) /* HTTP3 support built-in */ - -#define CURL_VERSION_ESNI (1<<26) /* ESNI support */ - - /* - * NAME curl_version_info() - * - * DESCRIPTION - * - * This function returns a pointer to a static copy of the version info - * struct. See above. - */ -CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); - -/* - * NAME curl_easy_strerror() - * - * DESCRIPTION - * - * The curl_easy_strerror function may be used to turn a CURLcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_easy_strerror(CURLcode); - -/* - * NAME curl_share_strerror() - * - * DESCRIPTION - * - * The curl_share_strerror function may be used to turn a CURLSHcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_share_strerror(CURLSHcode); - -/* - * NAME curl_easy_pause() - * - * DESCRIPTION - * - * The curl_easy_pause function pauses or unpauses transfers. Select the new - * state by setting the bitmask, use the convenience defines below. - * - */ -CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); - -#define CURLPAUSE_RECV (1<<0) -#define CURLPAUSE_RECV_CONT (0) - -#define CURLPAUSE_SEND (1<<2) -#define CURLPAUSE_SEND_CONT (0) - -#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND) -#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT) - -#ifdef __cplusplus -} -#endif - -/* unfortunately, the easy.h and multi.h include files need options and info - stuff before they can be included! */ -#include "easy.h" /* nothing in curl is fun without the easy stuff */ -#include "multi.h" -#include "urlapi.h" - -/* the typechecker doesn't work in C++ (yet) */ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ - ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ - !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) -#include "typecheck-gcc.h" -#else -#if defined(__STDC__) && (__STDC__ >= 1) -/* This preprocessor magic that replaces a call with the exact same call is - only done to make sure application authors pass exactly three arguments - to these functions. */ -#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param) -#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg) -#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) -#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) -#endif /* __STDC__ >= 1 */ -#endif /* gcc >= 4.3 && !__cplusplus */ - -#endif /* CURLINC_CURL_H */ diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/curlver.h b/VCMP-LUA/modules/requests/cpr/include/curl/curlver.h deleted file mode 100644 index 5fc49d4..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/curlver.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef CURLINC_CURLVER_H -#define CURLINC_CURLVER_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* This header file contains nothing but libcurl version info, generated by - a script at release-time. This was made its own header file in 7.11.2 */ - -/* This is the global package copyright */ -#define LIBCURL_COPYRIGHT "1996 - 2020 Daniel Stenberg, ." - -/* This is the version number of the libcurl package from which this header - file origins: */ -#define LIBCURL_VERSION "7.69.1" - -/* The numeric version number is also available "in parts" by using these - defines: */ -#define LIBCURL_VERSION_MAJOR 7 -#define LIBCURL_VERSION_MINOR 69 -#define LIBCURL_VERSION_PATCH 1 - -/* This is the numeric version of the libcurl version number, meant for easier - parsing and comparions by programs. The LIBCURL_VERSION_NUM define will - always follow this syntax: - - 0xXXYYZZ - - Where XX, YY and ZZ are the main version, release and patch numbers in - hexadecimal (using 8 bits each). All three numbers are always represented - using two digits. 1.2 would appear as "0x010200" while version 9.11.7 - appears as "0x090b07". - - This 6-digit (24 bits) hexadecimal number does not show pre-release number, - and it is always a greater number in a more recent release. It makes - comparisons with greater than and less than work. - - Note: This define is the full hex number and _does not_ use the - CURL_VERSION_BITS() macro since curl's own configure script greps for it - and needs it to contain the full number. -*/ -#define LIBCURL_VERSION_NUM 0x074501 - -/* - * This is the date and time when the full source package was created. The - * timestamp is not stored in git, as the timestamp is properly set in the - * tarballs by the maketgz script. - * - * The format of the date follows this template: - * - * "2007-11-23" - */ -#define LIBCURL_TIMESTAMP "2020-03-11" - -#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) -#define CURL_AT_LEAST_VERSION(x,y,z) \ - (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) - -#endif /* CURLINC_CURLVER_H */ diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/easy.h b/VCMP-LUA/modules/requests/cpr/include/curl/easy.h deleted file mode 100644 index 592f5d3..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/easy.h +++ /dev/null @@ -1,112 +0,0 @@ -#ifndef CURLINC_EASY_H -#define CURLINC_EASY_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2019, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ -#ifdef __cplusplus -extern "C" { -#endif - -CURL_EXTERN CURL *curl_easy_init(void); -CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); -CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); -CURL_EXTERN void curl_easy_cleanup(CURL *curl); - -/* - * NAME curl_easy_getinfo() - * - * DESCRIPTION - * - * Request internal information from the curl session with this function. The - * third argument MUST be a pointer to a long, a pointer to a char * or a - * pointer to a double (as the documentation describes elsewhere). The data - * pointed to will be filled in accordingly and can be relied upon only if the - * function returns CURLE_OK. This function is intended to get used *AFTER* a - * performed transfer, all results from this function are undefined until the - * transfer is completed. - */ -CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); - - -/* - * NAME curl_easy_duphandle() - * - * DESCRIPTION - * - * Creates a new curl session handle with the same options set for the handle - * passed in. Duplicating a handle could only be a matter of cloning data and - * options, internal state info and things like persistent connections cannot - * be transferred. It is useful in multithreaded applications when you can run - * curl_easy_duphandle() for each new thread to avoid a series of identical - * curl_easy_setopt() invokes in every thread. - */ -CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl); - -/* - * NAME curl_easy_reset() - * - * DESCRIPTION - * - * Re-initializes a CURL handle to the default values. This puts back the - * handle to the same state as it was in when it was just created. - * - * It does keep: live connections, the Session ID cache, the DNS cache and the - * cookies. - */ -CURL_EXTERN void curl_easy_reset(CURL *curl); - -/* - * NAME curl_easy_recv() - * - * DESCRIPTION - * - * Receives data from the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, - size_t *n); - -/* - * NAME curl_easy_send() - * - * DESCRIPTION - * - * Sends data over the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, - size_t buflen, size_t *n); - - -/* - * NAME curl_easy_upkeep() - * - * DESCRIPTION - * - * Performs connection upkeep for the given session handle. - */ -CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/mprintf.h b/VCMP-LUA/modules/requests/cpr/include/curl/mprintf.h deleted file mode 100644 index f615ed7..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/mprintf.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef CURLINC_MPRINTF_H -#define CURLINC_MPRINTF_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2019, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include -#include /* needed for FILE */ -#include "curl.h" /* for CURL_EXTERN */ - -#ifdef __cplusplus -extern "C" { -#endif - -CURL_EXTERN int curl_mprintf(const char *format, ...); -CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); -CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); -CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, - const char *format, ...); -CURL_EXTERN int curl_mvprintf(const char *format, va_list args); -CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); -CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); -CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, - const char *format, va_list args); -CURL_EXTERN char *curl_maprintf(const char *format, ...); -CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); - -#ifdef __cplusplus -} -#endif - -#endif /* CURLINC_MPRINTF_H */ diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/multi.h b/VCMP-LUA/modules/requests/cpr/include/curl/multi.h deleted file mode 100644 index bda9bb7..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/multi.h +++ /dev/null @@ -1,456 +0,0 @@ -#ifndef CURLINC_MULTI_H -#define CURLINC_MULTI_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ -/* - This is an "external" header file. Don't give away any internals here! - - GOALS - - o Enable a "pull" interface. The application that uses libcurl decides where - and when to ask libcurl to get/send data. - - o Enable multiple simultaneous transfers in the same thread without making it - complicated for the application. - - o Enable the application to select() on its own file descriptors and curl's - file descriptors simultaneous easily. - -*/ - -/* - * This header file should not really need to include "curl.h" since curl.h - * itself includes this file and we expect user applications to do #include - * without the need for especially including multi.h. - * - * For some reason we added this include here at one point, and rather than to - * break existing (wrongly written) libcurl applications, we leave it as-is - * but with this warning attached. - */ -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) -typedef struct Curl_multi CURLM; -#else -typedef void CURLM; -#endif - -typedef enum { - CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or - curl_multi_socket*() soon */ - CURLM_OK, - CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ - CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ - CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ - CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ - CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ - CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ - CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was - attempted to get added - again */ - CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a - callback */ - CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */ - CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */ - CURLM_LAST -} CURLMcode; - -/* just to make code nicer when using curl_multi_socket() you can now check - for CURLM_CALL_MULTI_SOCKET too in the same style it works for - curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ -#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM - -/* bitmask bits for CURLMOPT_PIPELINING */ -#define CURLPIPE_NOTHING 0L -#define CURLPIPE_HTTP1 1L -#define CURLPIPE_MULTIPLEX 2L - -typedef enum { - CURLMSG_NONE, /* first, not used */ - CURLMSG_DONE, /* This easy handle has completed. 'result' contains - the CURLcode of the transfer */ - CURLMSG_LAST /* last, not used */ -} CURLMSG; - -struct CURLMsg { - CURLMSG msg; /* what this message means */ - CURL *easy_handle; /* the handle it concerns */ - union { - void *whatever; /* message-specific data */ - CURLcode result; /* return code for transfer */ - } data; -}; -typedef struct CURLMsg CURLMsg; - -/* Based on poll(2) structure and values. - * We don't use pollfd and POLL* constants explicitly - * to cover platforms without poll(). */ -#define CURL_WAIT_POLLIN 0x0001 -#define CURL_WAIT_POLLPRI 0x0002 -#define CURL_WAIT_POLLOUT 0x0004 - -struct curl_waitfd { - curl_socket_t fd; - short events; - short revents; /* not supported yet */ -}; - -/* - * Name: curl_multi_init() - * - * Desc: inititalize multi-style curl usage - * - * Returns: a new CURLM handle to use in all 'curl_multi' functions. - */ -CURL_EXTERN CURLM *curl_multi_init(void); - -/* - * Name: curl_multi_add_handle() - * - * Desc: add a standard curl handle to the multi stack - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_remove_handle() - * - * Desc: removes a curl handle from the multi stack again - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_fdset() - * - * Desc: Ask curl for its fd_set sets. The app can use these to select() or - * poll() on. We want curl_multi_perform() called as soon as one of - * them are ready. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle, - fd_set *read_fd_set, - fd_set *write_fd_set, - fd_set *exc_fd_set, - int *max_fd); - -/* - * Name: curl_multi_wait() - * - * Desc: Poll on all fds within a CURLM set as well as any - * additional fds passed to the function. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle, - struct curl_waitfd extra_fds[], - unsigned int extra_nfds, - int timeout_ms, - int *ret); - -/* - * Name: curl_multi_poll() - * - * Desc: Poll on all fds within a CURLM set as well as any - * additional fds passed to the function. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_poll(CURLM *multi_handle, - struct curl_waitfd extra_fds[], - unsigned int extra_nfds, - int timeout_ms, - int *ret); - -/* - * Name: curl_multi_wakeup() - * - * Desc: wakes up a sleeping curl_multi_poll call. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *multi_handle); - - /* - * Name: curl_multi_perform() - * - * Desc: When the app thinks there's data available for curl it calls this - * function to read/write whatever there is right now. This returns - * as soon as the reads and writes are done. This function does not - * require that there actually is data available for reading or that - * data can be written, it can be called just in case. It returns - * the number of handles that still transfer data in the second - * argument's integer-pointer. - * - * Returns: CURLMcode type, general multi error code. *NOTE* that this only - * returns errors etc regarding the whole multi stack. There might - * still have occurred problems on individual transfers even when - * this returns OK. - */ -CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle, - int *running_handles); - - /* - * Name: curl_multi_cleanup() - * - * Desc: Cleans up and removes a whole multi stack. It does not free or - * touch any individual easy handles in any way. We need to define - * in what state those handles will be if this function is called - * in the middle of a transfer. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); - -/* - * Name: curl_multi_info_read() - * - * Desc: Ask the multi handle if there's any messages/informationals from - * the individual transfers. Messages include informationals such as - * error code from the transfer or just the fact that a transfer is - * completed. More details on these should be written down as well. - * - * Repeated calls to this function will return a new struct each - * time, until a special "end of msgs" struct is returned as a signal - * that there is no more to get at this point. - * - * The data the returned pointer points to will not survive calling - * curl_multi_cleanup(). - * - * The 'CURLMsg' struct is meant to be very simple and only contain - * very basic information. If more involved information is wanted, - * we will provide the particular "transfer handle" in that struct - * and that should/could/would be used in subsequent - * curl_easy_getinfo() calls (or similar). The point being that we - * must never expose complex structs to applications, as then we'll - * undoubtably get backwards compatibility problems in the future. - * - * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out - * of structs. It also writes the number of messages left in the - * queue (after this read) in the integer the second argument points - * to. - */ -CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, - int *msgs_in_queue); - -/* - * Name: curl_multi_strerror() - * - * Desc: The curl_multi_strerror function may be used to turn a CURLMcode - * value into the equivalent human readable error string. This is - * useful for printing meaningful error messages. - * - * Returns: A pointer to a zero-terminated error message. - */ -CURL_EXTERN const char *curl_multi_strerror(CURLMcode); - -/* - * Name: curl_multi_socket() and - * curl_multi_socket_all() - * - * Desc: An alternative version of curl_multi_perform() that allows the - * application to pass in one of the file descriptors that have been - * detected to have "action" on them and let libcurl perform. - * See man page for details. - */ -#define CURL_POLL_NONE 0 -#define CURL_POLL_IN 1 -#define CURL_POLL_OUT 2 -#define CURL_POLL_INOUT 3 -#define CURL_POLL_REMOVE 4 - -#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD - -#define CURL_CSELECT_IN 0x01 -#define CURL_CSELECT_OUT 0x02 -#define CURL_CSELECT_ERR 0x04 - -typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ - curl_socket_t s, /* socket */ - int what, /* see above */ - void *userp, /* private callback - pointer */ - void *socketp); /* private socket - pointer */ -/* - * Name: curl_multi_timer_callback - * - * Desc: Called by libcurl whenever the library detects a change in the - * maximum number of milliseconds the app is allowed to wait before - * curl_multi_socket() or curl_multi_perform() must be called - * (to allow libcurl's timed events to take place). - * - * Returns: The callback should return zero. - */ -typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */ - long timeout_ms, /* see above */ - void *userp); /* private callback - pointer */ - -CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle, - curl_socket_t s, - int ev_bitmask, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle, - int *running_handles); - -#ifndef CURL_ALLOW_OLD_MULTI_SOCKET -/* This macro below was added in 7.16.3 to push users who recompile to use - the new curl_multi_socket_action() instead of the old curl_multi_socket() -*/ -#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z) -#endif - -/* - * Name: curl_multi_timeout() - * - * Desc: Returns the maximum number of milliseconds the app is allowed to - * wait before curl_multi_socket() or curl_multi_perform() must be - * called (to allow libcurl's timed events to take place). - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle, - long *milliseconds); - -typedef enum { - /* This is the socket callback function pointer */ - CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1), - - /* This is the argument passed to the socket callback */ - CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2), - - /* set to 1 to enable pipelining for this multi handle */ - CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3), - - /* This is the timer callback function pointer */ - CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4), - - /* This is the argument passed to the timer callback */ - CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5), - - /* maximum number of entries in the connection cache */ - CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6), - - /* maximum number of (pipelining) connections to one host */ - CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7), - - /* maximum number of requests in a pipeline */ - CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8), - - /* a connection with a content-length longer than this - will not be considered for pipelining */ - CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9), - - /* a connection with a chunk length longer than this - will not be considered for pipelining */ - CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10), - - /* a list of site names(+port) that are blacklisted from - pipelining */ - CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11), - - /* a list of server types that are blacklisted from - pipelining */ - CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12), - - /* maximum number of open connections in total */ - CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13), - - /* This is the server push callback function pointer */ - CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14), - - /* This is the argument passed to the server push callback */ - CURLOPT(CURLMOPT_PUSHDATA, CURLOPTTYPE_OBJECTPOINT, 15), - - /* maximum number of concurrent streams to support on a connection */ - CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16), - - CURLMOPT_LASTENTRY /* the last unused */ -} CURLMoption; - - -/* - * Name: curl_multi_setopt() - * - * Desc: Sets options for the multi handle. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, - CURLMoption option, ...); - - -/* - * Name: curl_multi_assign() - * - * Desc: This function sets an association in the multi handle between the - * given socket and a private pointer of the application. This is - * (only) useful for curl_multi_socket uses. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, - curl_socket_t sockfd, void *sockp); - - -/* - * Name: curl_push_callback - * - * Desc: This callback gets called when a new stream is being pushed by the - * server. It approves or denies the new stream. - * - * Returns: CURL_PUSH_OK or CURL_PUSH_DENY. - */ -#define CURL_PUSH_OK 0 -#define CURL_PUSH_DENY 1 - -struct curl_pushheaders; /* forward declaration only */ - -CURL_EXTERN char *curl_pushheader_bynum(struct curl_pushheaders *h, - size_t num); -CURL_EXTERN char *curl_pushheader_byname(struct curl_pushheaders *h, - const char *name); - -typedef int (*curl_push_callback)(CURL *parent, - CURL *easy, - size_t num_headers, - struct curl_pushheaders *headers, - void *userp); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/stdcheaders.h b/VCMP-LUA/modules/requests/cpr/include/curl/stdcheaders.h deleted file mode 100644 index a6bdc1a..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/stdcheaders.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef CURLINC_STDCHEADERS_H -#define CURLINC_STDCHEADERS_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2019, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include - -size_t fread(void *, size_t, size_t, FILE *); -size_t fwrite(const void *, size_t, size_t, FILE *); - -int strcasecmp(const char *, const char *); -int strncasecmp(const char *, const char *, size_t); - -#endif /* CURLINC_STDCHEADERS_H */ diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/system.h b/VCMP-LUA/modules/requests/cpr/include/curl/system.h deleted file mode 100644 index 867af61..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/system.h +++ /dev/null @@ -1,504 +0,0 @@ -#ifndef CURLINC_SYSTEM_H -#define CURLINC_SYSTEM_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2019, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* - * Try to keep one section per platform, compiler and architecture, otherwise, - * if an existing section is reused for a different one and later on the - * original is adjusted, probably the piggybacking one can be adversely - * changed. - * - * In order to differentiate between platforms/compilers/architectures use - * only compiler built in predefined preprocessor symbols. - * - * curl_off_t - * ---------- - * - * For any given platform/compiler curl_off_t must be typedef'ed to a 64-bit - * wide signed integral data type. The width of this data type must remain - * constant and independent of any possible large file support settings. - * - * As an exception to the above, curl_off_t shall be typedef'ed to a 32-bit - * wide signed integral data type if there is no 64-bit type. - * - * As a general rule, curl_off_t shall not be mapped to off_t. This rule shall - * only be violated if off_t is the only 64-bit data type available and the - * size of off_t is independent of large file support settings. Keep your - * build on the safe side avoiding an off_t gating. If you have a 64-bit - * off_t then take for sure that another 64-bit data type exists, dig deeper - * and you will find it. - * - */ - -#if defined(__DJGPP__) || defined(__GO32__) -# if defined(__DJGPP__) && (__DJGPP__ > 1) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__SALFORDC__) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__BORLANDC__) -# if (__BORLANDC__ < 0x520) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__TURBOC__) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__WATCOMC__) -# if defined(__386__) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__POCC__) -# if (__POCC__ < 280) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# elif defined(_MSC_VER) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# else -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__LCC__) -# if defined(__e2k__) /* MCST eLbrus C Compiler */ -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# else /* Local (or Little) C Compiler */ -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int -# endif - -#elif defined(__SYMBIAN32__) -# if defined(__EABI__) /* Treat all ARM compilers equally */ -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__CW32__) -# pragma longlong on -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__VC32__) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int - -#elif defined(__MWERKS__) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(_WIN32_WCE) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__MINGW32__) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_WS2TCPIP_H 1 - -#elif defined(__VMS) -# if defined(__VAX) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int - -#elif defined(__OS400__) -# if defined(__ILEC400__) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# endif - -#elif defined(__MVS__) -# if defined(__IBMC__) || defined(__IBMCPP__) -# if defined(_ILP32) -# elif defined(_LP64) -# endif -# if defined(_LONG_LONG) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(_LP64) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# endif - -#elif defined(__370__) -# if defined(__IBMC__) || defined(__IBMCPP__) -# if defined(_ILP32) -# elif defined(_LP64) -# endif -# if defined(_LONG_LONG) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(_LP64) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 -# endif - -#elif defined(TPF) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -#elif defined(__TINYC__) /* also known as tcc */ -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio */ -# if !defined(__LP64) && (defined(__ILP32) || \ - defined(__i386) || \ - defined(__sparcv8) || \ - defined(__sparcv8plus)) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__LP64) || \ - defined(__amd64) || defined(__sparcv9) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -#elif defined(__xlc__) /* IBM xlc compiler */ -# if !defined(_LP64) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -/* ===================================== */ -/* KEEP MSVC THE PENULTIMATE ENTRY */ -/* ===================================== */ - -#elif defined(_MSC_VER) -# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) -# define CURL_TYPEOF_CURL_OFF_T __int64 -# define CURL_FORMAT_CURL_OFF_T "I64d" -# define CURL_FORMAT_CURL_OFF_TU "I64u" -# define CURL_SUFFIX_CURL_OFF_T i64 -# define CURL_SUFFIX_CURL_OFF_TU ui64 -# else -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T int - -/* ===================================== */ -/* KEEP GENERIC GCC THE LAST ENTRY */ -/* ===================================== */ - -#elif defined(__GNUC__) && !defined(_SCO_DS) -# if !defined(__LP64__) && \ - (defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \ - defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \ - defined(__sparc__) || defined(__mips__) || defined(__sh__) || \ - defined(__XTENSA__) || \ - (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \ - (defined(__LONG_MAX__) && __LONG_MAX__ == 2147483647L)) -# define CURL_TYPEOF_CURL_OFF_T long long -# define CURL_FORMAT_CURL_OFF_T "lld" -# define CURL_FORMAT_CURL_OFF_TU "llu" -# define CURL_SUFFIX_CURL_OFF_T LL -# define CURL_SUFFIX_CURL_OFF_TU ULL -# elif defined(__LP64__) || \ - defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \ - defined(__e2k__) || \ - (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \ - (defined(__LONG_MAX__) && __LONG_MAX__ == 9223372036854775807L) -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# endif -# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t -# define CURL_PULL_SYS_TYPES_H 1 -# define CURL_PULL_SYS_SOCKET_H 1 - -#else -/* generic "safe guess" on old 32 bit style */ -# define CURL_TYPEOF_CURL_OFF_T long -# define CURL_FORMAT_CURL_OFF_T "ld" -# define CURL_FORMAT_CURL_OFF_TU "lu" -# define CURL_SUFFIX_CURL_OFF_T L -# define CURL_SUFFIX_CURL_OFF_TU UL -# define CURL_TYPEOF_CURL_SOCKLEN_T int -#endif - -#ifdef _AIX -/* AIX needs */ -#define CURL_PULL_SYS_POLL_H -#endif - - -/* CURL_PULL_WS2TCPIP_H is defined above when inclusion of header file */ -/* ws2tcpip.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_WS2TCPIP_H -# include -# include -# include -#endif - -/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */ -/* sys/types.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_SYS_TYPES_H -# include -#endif - -/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */ -/* sys/socket.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_SYS_SOCKET_H -# include -#endif - -/* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file */ -/* sys/poll.h is required here to properly make type definitions below. */ -#ifdef CURL_PULL_SYS_POLL_H -# include -#endif - -/* Data type definition of curl_socklen_t. */ -#ifdef CURL_TYPEOF_CURL_SOCKLEN_T - typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; -#endif - -/* Data type definition of curl_off_t. */ - -#ifdef CURL_TYPEOF_CURL_OFF_T - typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; -#endif - -/* - * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow - * these to be visible and exported by the external libcurl interface API, - * while also making them visible to the library internals, simply including - * curl_setup.h, without actually needing to include curl.h internally. - * If some day this section would grow big enough, all this should be moved - * to its own header file. - */ - -/* - * Figure out if we can use the ## preprocessor operator, which is supported - * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__ - * or __cplusplus so we need to carefully check for them too. - */ - -#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \ - defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \ - defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \ - defined(__ILEC400__) - /* This compiler is believed to have an ISO compatible preprocessor */ -#define CURL_ISOCPP -#else - /* This compiler is believed NOT to have an ISO compatible preprocessor */ -#undef CURL_ISOCPP -#endif - -/* - * Macros for minimum-width signed and unsigned curl_off_t integer constants. - */ - -#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551) -# define CURLINC_OFF_T_C_HLPR2(x) x -# define CURLINC_OFF_T_C_HLPR1(x) CURLINC_OFF_T_C_HLPR2(x) -# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ - CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ - CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU) -#else -# ifdef CURL_ISOCPP -# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix -# else -# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix -# endif -# define CURLINC_OFF_T_C_HLPR1(Val,Suffix) CURLINC_OFF_T_C_HLPR2(Val,Suffix) -# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU) -#endif - -#endif /* CURLINC_SYSTEM_H */ diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/typecheck-gcc.h b/VCMP-LUA/modules/requests/cpr/include/curl/typecheck-gcc.h deleted file mode 100644 index 03c84fc..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/typecheck-gcc.h +++ /dev/null @@ -1,699 +0,0 @@ -#ifndef CURLINC_TYPECHECK_GCC_H -#define CURLINC_TYPECHECK_GCC_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2019, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* wraps curl_easy_setopt() with typechecking */ - -/* To add a new kind of warning, add an - * if(curlcheck_sometype_option(_curl_opt)) - * if(!curlcheck_sometype(value)) - * _curl_easy_setopt_err_sometype(); - * block and define curlcheck_sometype_option, curlcheck_sometype and - * _curl_easy_setopt_err_sometype below - * - * NOTE: We use two nested 'if' statements here instead of the && operator, in - * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x - * when compiling with -Wlogical-op. - * - * To add an option that uses the same type as an existing option, you'll just - * need to extend the appropriate _curl_*_option macro - */ -#define curl_easy_setopt(handle, option, value) \ - __extension__({ \ - __typeof__(option) _curl_opt = option; \ - if(__builtin_constant_p(_curl_opt)) { \ - if(curlcheck_long_option(_curl_opt)) \ - if(!curlcheck_long(value)) \ - _curl_easy_setopt_err_long(); \ - if(curlcheck_off_t_option(_curl_opt)) \ - if(!curlcheck_off_t(value)) \ - _curl_easy_setopt_err_curl_off_t(); \ - if(curlcheck_string_option(_curl_opt)) \ - if(!curlcheck_string(value)) \ - _curl_easy_setopt_err_string(); \ - if(curlcheck_write_cb_option(_curl_opt)) \ - if(!curlcheck_write_cb(value)) \ - _curl_easy_setopt_err_write_callback(); \ - if((_curl_opt) == CURLOPT_RESOLVER_START_FUNCTION) \ - if(!curlcheck_resolver_start_callback(value)) \ - _curl_easy_setopt_err_resolver_start_callback(); \ - if((_curl_opt) == CURLOPT_READFUNCTION) \ - if(!curlcheck_read_cb(value)) \ - _curl_easy_setopt_err_read_cb(); \ - if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \ - if(!curlcheck_ioctl_cb(value)) \ - _curl_easy_setopt_err_ioctl_cb(); \ - if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \ - if(!curlcheck_sockopt_cb(value)) \ - _curl_easy_setopt_err_sockopt_cb(); \ - if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \ - if(!curlcheck_opensocket_cb(value)) \ - _curl_easy_setopt_err_opensocket_cb(); \ - if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \ - if(!curlcheck_progress_cb(value)) \ - _curl_easy_setopt_err_progress_cb(); \ - if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \ - if(!curlcheck_debug_cb(value)) \ - _curl_easy_setopt_err_debug_cb(); \ - if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \ - if(!curlcheck_ssl_ctx_cb(value)) \ - _curl_easy_setopt_err_ssl_ctx_cb(); \ - if(curlcheck_conv_cb_option(_curl_opt)) \ - if(!curlcheck_conv_cb(value)) \ - _curl_easy_setopt_err_conv_cb(); \ - if((_curl_opt) == CURLOPT_SEEKFUNCTION) \ - if(!curlcheck_seek_cb(value)) \ - _curl_easy_setopt_err_seek_cb(); \ - if(curlcheck_cb_data_option(_curl_opt)) \ - if(!curlcheck_cb_data(value)) \ - _curl_easy_setopt_err_cb_data(); \ - if((_curl_opt) == CURLOPT_ERRORBUFFER) \ - if(!curlcheck_error_buffer(value)) \ - _curl_easy_setopt_err_error_buffer(); \ - if((_curl_opt) == CURLOPT_STDERR) \ - if(!curlcheck_FILE(value)) \ - _curl_easy_setopt_err_FILE(); \ - if(curlcheck_postfields_option(_curl_opt)) \ - if(!curlcheck_postfields(value)) \ - _curl_easy_setopt_err_postfields(); \ - if((_curl_opt) == CURLOPT_HTTPPOST) \ - if(!curlcheck_arr((value), struct curl_httppost)) \ - _curl_easy_setopt_err_curl_httpost(); \ - if((_curl_opt) == CURLOPT_MIMEPOST) \ - if(!curlcheck_ptr((value), curl_mime)) \ - _curl_easy_setopt_err_curl_mimepost(); \ - if(curlcheck_slist_option(_curl_opt)) \ - if(!curlcheck_arr((value), struct curl_slist)) \ - _curl_easy_setopt_err_curl_slist(); \ - if((_curl_opt) == CURLOPT_SHARE) \ - if(!curlcheck_ptr((value), CURLSH)) \ - _curl_easy_setopt_err_CURLSH(); \ - } \ - curl_easy_setopt(handle, _curl_opt, value); \ - }) - -/* wraps curl_easy_getinfo() with typechecking */ -#define curl_easy_getinfo(handle, info, arg) \ - __extension__({ \ - __typeof__(info) _curl_info = info; \ - if(__builtin_constant_p(_curl_info)) { \ - if(curlcheck_string_info(_curl_info)) \ - if(!curlcheck_arr((arg), char *)) \ - _curl_easy_getinfo_err_string(); \ - if(curlcheck_long_info(_curl_info)) \ - if(!curlcheck_arr((arg), long)) \ - _curl_easy_getinfo_err_long(); \ - if(curlcheck_double_info(_curl_info)) \ - if(!curlcheck_arr((arg), double)) \ - _curl_easy_getinfo_err_double(); \ - if(curlcheck_slist_info(_curl_info)) \ - if(!curlcheck_arr((arg), struct curl_slist *)) \ - _curl_easy_getinfo_err_curl_slist(); \ - if(curlcheck_tlssessioninfo_info(_curl_info)) \ - if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \ - _curl_easy_getinfo_err_curl_tlssesssioninfo(); \ - if(curlcheck_certinfo_info(_curl_info)) \ - if(!curlcheck_arr((arg), struct curl_certinfo *)) \ - _curl_easy_getinfo_err_curl_certinfo(); \ - if(curlcheck_socket_info(_curl_info)) \ - if(!curlcheck_arr((arg), curl_socket_t)) \ - _curl_easy_getinfo_err_curl_socket(); \ - if(curlcheck_off_t_info(_curl_info)) \ - if(!curlcheck_arr((arg), curl_off_t)) \ - _curl_easy_getinfo_err_curl_off_t(); \ - } \ - curl_easy_getinfo(handle, _curl_info, arg); \ - }) - -/* - * For now, just make sure that the functions are called with three arguments - */ -#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) -#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) - - -/* the actual warnings, triggered by calling the _curl_easy_setopt_err* - * functions */ - -/* To define a new warning, use _CURL_WARNING(identifier, "message") */ -#define CURLWARNING(id, message) \ - static void __attribute__((__warning__(message))) \ - __attribute__((__unused__)) __attribute__((__noinline__)) \ - id(void) { __asm__(""); } - -CURLWARNING(_curl_easy_setopt_err_long, - "curl_easy_setopt expects a long argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_off_t, - "curl_easy_setopt expects a curl_off_t argument for this option") -CURLWARNING(_curl_easy_setopt_err_string, - "curl_easy_setopt expects a " - "string ('char *' or char[]) argument for this option" - ) -CURLWARNING(_curl_easy_setopt_err_write_callback, - "curl_easy_setopt expects a curl_write_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_resolver_start_callback, - "curl_easy_setopt expects a " - "curl_resolver_start_callback argument for this option" - ) -CURLWARNING(_curl_easy_setopt_err_read_cb, - "curl_easy_setopt expects a curl_read_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_ioctl_cb, - "curl_easy_setopt expects a curl_ioctl_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_sockopt_cb, - "curl_easy_setopt expects a curl_sockopt_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_opensocket_cb, - "curl_easy_setopt expects a " - "curl_opensocket_callback argument for this option" - ) -CURLWARNING(_curl_easy_setopt_err_progress_cb, - "curl_easy_setopt expects a curl_progress_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_debug_cb, - "curl_easy_setopt expects a curl_debug_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_ssl_ctx_cb, - "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_conv_cb, - "curl_easy_setopt expects a curl_conv_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_seek_cb, - "curl_easy_setopt expects a curl_seek_callback argument for this option") -CURLWARNING(_curl_easy_setopt_err_cb_data, - "curl_easy_setopt expects a " - "private data pointer as argument for this option") -CURLWARNING(_curl_easy_setopt_err_error_buffer, - "curl_easy_setopt expects a " - "char buffer of CURL_ERROR_SIZE as argument for this option") -CURLWARNING(_curl_easy_setopt_err_FILE, - "curl_easy_setopt expects a 'FILE *' argument for this option") -CURLWARNING(_curl_easy_setopt_err_postfields, - "curl_easy_setopt expects a 'void *' or 'char *' argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_httpost, - "curl_easy_setopt expects a 'struct curl_httppost *' " - "argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_mimepost, - "curl_easy_setopt expects a 'curl_mime *' " - "argument for this option") -CURLWARNING(_curl_easy_setopt_err_curl_slist, - "curl_easy_setopt expects a 'struct curl_slist *' argument for this option") -CURLWARNING(_curl_easy_setopt_err_CURLSH, - "curl_easy_setopt expects a CURLSH* argument for this option") - -CURLWARNING(_curl_easy_getinfo_err_string, - "curl_easy_getinfo expects a pointer to 'char *' for this info") -CURLWARNING(_curl_easy_getinfo_err_long, - "curl_easy_getinfo expects a pointer to long for this info") -CURLWARNING(_curl_easy_getinfo_err_double, - "curl_easy_getinfo expects a pointer to double for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_slist, - "curl_easy_getinfo expects a pointer to 'struct curl_slist *' for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_tlssesssioninfo, - "curl_easy_getinfo expects a pointer to " - "'struct curl_tlssessioninfo *' for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_certinfo, - "curl_easy_getinfo expects a pointer to " - "'struct curl_certinfo *' for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_socket, - "curl_easy_getinfo expects a pointer to curl_socket_t for this info") -CURLWARNING(_curl_easy_getinfo_err_curl_off_t, - "curl_easy_getinfo expects a pointer to curl_off_t for this info") - -/* groups of curl_easy_setops options that take the same type of argument */ - -/* To add a new option to one of the groups, just add - * (option) == CURLOPT_SOMETHING - * to the or-expression. If the option takes a long or curl_off_t, you don't - * have to do anything - */ - -/* evaluates to true if option takes a long argument */ -#define curlcheck_long_option(option) \ - (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT) - -#define curlcheck_off_t_option(option) \ - ((option) > CURLOPTTYPE_OFF_T) - -/* evaluates to true if option takes a char* argument */ -#define curlcheck_string_option(option) \ - ((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \ - (option) == CURLOPT_ACCEPT_ENCODING || \ - (option) == CURLOPT_ALTSVC || \ - (option) == CURLOPT_CAINFO || \ - (option) == CURLOPT_CAPATH || \ - (option) == CURLOPT_COOKIE || \ - (option) == CURLOPT_COOKIEFILE || \ - (option) == CURLOPT_COOKIEJAR || \ - (option) == CURLOPT_COOKIELIST || \ - (option) == CURLOPT_CRLFILE || \ - (option) == CURLOPT_CUSTOMREQUEST || \ - (option) == CURLOPT_DEFAULT_PROTOCOL || \ - (option) == CURLOPT_DNS_INTERFACE || \ - (option) == CURLOPT_DNS_LOCAL_IP4 || \ - (option) == CURLOPT_DNS_LOCAL_IP6 || \ - (option) == CURLOPT_DNS_SERVERS || \ - (option) == CURLOPT_DOH_URL || \ - (option) == CURLOPT_EGDSOCKET || \ - (option) == CURLOPT_FTPPORT || \ - (option) == CURLOPT_FTP_ACCOUNT || \ - (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ - (option) == CURLOPT_INTERFACE || \ - (option) == CURLOPT_ISSUERCERT || \ - (option) == CURLOPT_KEYPASSWD || \ - (option) == CURLOPT_KRBLEVEL || \ - (option) == CURLOPT_LOGIN_OPTIONS || \ - (option) == CURLOPT_MAIL_AUTH || \ - (option) == CURLOPT_MAIL_FROM || \ - (option) == CURLOPT_NETRC_FILE || \ - (option) == CURLOPT_NOPROXY || \ - (option) == CURLOPT_PASSWORD || \ - (option) == CURLOPT_PINNEDPUBLICKEY || \ - (option) == CURLOPT_PRE_PROXY || \ - (option) == CURLOPT_PROXY || \ - (option) == CURLOPT_PROXYPASSWORD || \ - (option) == CURLOPT_PROXYUSERNAME || \ - (option) == CURLOPT_PROXYUSERPWD || \ - (option) == CURLOPT_PROXY_CAINFO || \ - (option) == CURLOPT_PROXY_CAPATH || \ - (option) == CURLOPT_PROXY_CRLFILE || \ - (option) == CURLOPT_PROXY_KEYPASSWD || \ - (option) == CURLOPT_PROXY_PINNEDPUBLICKEY || \ - (option) == CURLOPT_PROXY_SERVICE_NAME || \ - (option) == CURLOPT_PROXY_SSLCERT || \ - (option) == CURLOPT_PROXY_SSLCERTTYPE || \ - (option) == CURLOPT_PROXY_SSLKEY || \ - (option) == CURLOPT_PROXY_SSLKEYTYPE || \ - (option) == CURLOPT_PROXY_SSL_CIPHER_LIST || \ - (option) == CURLOPT_PROXY_TLS13_CIPHERS || \ - (option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \ - (option) == CURLOPT_PROXY_TLSAUTH_TYPE || \ - (option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \ - (option) == CURLOPT_RANDOM_FILE || \ - (option) == CURLOPT_RANGE || \ - (option) == CURLOPT_REFERER || \ - (option) == CURLOPT_REQUEST_TARGET || \ - (option) == CURLOPT_RTSP_SESSION_ID || \ - (option) == CURLOPT_RTSP_STREAM_URI || \ - (option) == CURLOPT_RTSP_TRANSPORT || \ - (option) == CURLOPT_SASL_AUTHZID || \ - (option) == CURLOPT_SERVICE_NAME || \ - (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ - (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ - (option) == CURLOPT_SSH_KNOWNHOSTS || \ - (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ - (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ - (option) == CURLOPT_SSLCERT || \ - (option) == CURLOPT_SSLCERTTYPE || \ - (option) == CURLOPT_SSLENGINE || \ - (option) == CURLOPT_SSLKEY || \ - (option) == CURLOPT_SSLKEYTYPE || \ - (option) == CURLOPT_SSL_CIPHER_LIST || \ - (option) == CURLOPT_TLS13_CIPHERS || \ - (option) == CURLOPT_TLSAUTH_PASSWORD || \ - (option) == CURLOPT_TLSAUTH_TYPE || \ - (option) == CURLOPT_TLSAUTH_USERNAME || \ - (option) == CURLOPT_UNIX_SOCKET_PATH || \ - (option) == CURLOPT_URL || \ - (option) == CURLOPT_USERAGENT || \ - (option) == CURLOPT_USERNAME || \ - (option) == CURLOPT_USERPWD || \ - (option) == CURLOPT_XOAUTH2_BEARER || \ - 0) - -/* evaluates to true if option takes a curl_write_callback argument */ -#define curlcheck_write_cb_option(option) \ - ((option) == CURLOPT_HEADERFUNCTION || \ - (option) == CURLOPT_WRITEFUNCTION) - -/* evaluates to true if option takes a curl_conv_callback argument */ -#define curlcheck_conv_cb_option(option) \ - ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \ - (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \ - (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION) - -/* evaluates to true if option takes a data argument to pass to a callback */ -#define curlcheck_cb_data_option(option) \ - ((option) == CURLOPT_CHUNK_DATA || \ - (option) == CURLOPT_CLOSESOCKETDATA || \ - (option) == CURLOPT_DEBUGDATA || \ - (option) == CURLOPT_FNMATCH_DATA || \ - (option) == CURLOPT_HEADERDATA || \ - (option) == CURLOPT_INTERLEAVEDATA || \ - (option) == CURLOPT_IOCTLDATA || \ - (option) == CURLOPT_OPENSOCKETDATA || \ - (option) == CURLOPT_PRIVATE || \ - (option) == CURLOPT_PROGRESSDATA || \ - (option) == CURLOPT_READDATA || \ - (option) == CURLOPT_SEEKDATA || \ - (option) == CURLOPT_SOCKOPTDATA || \ - (option) == CURLOPT_SSH_KEYDATA || \ - (option) == CURLOPT_SSL_CTX_DATA || \ - (option) == CURLOPT_WRITEDATA || \ - (option) == CURLOPT_RESOLVER_START_DATA || \ - (option) == CURLOPT_TRAILERDATA || \ - 0) - -/* evaluates to true if option takes a POST data argument (void* or char*) */ -#define curlcheck_postfields_option(option) \ - ((option) == CURLOPT_POSTFIELDS || \ - (option) == CURLOPT_COPYPOSTFIELDS || \ - 0) - -/* evaluates to true if option takes a struct curl_slist * argument */ -#define curlcheck_slist_option(option) \ - ((option) == CURLOPT_HTTP200ALIASES || \ - (option) == CURLOPT_HTTPHEADER || \ - (option) == CURLOPT_MAIL_RCPT || \ - (option) == CURLOPT_POSTQUOTE || \ - (option) == CURLOPT_PREQUOTE || \ - (option) == CURLOPT_PROXYHEADER || \ - (option) == CURLOPT_QUOTE || \ - (option) == CURLOPT_RESOLVE || \ - (option) == CURLOPT_TELNETOPTIONS || \ - (option) == CURLOPT_CONNECT_TO || \ - 0) - -/* groups of curl_easy_getinfo infos that take the same type of argument */ - -/* evaluates to true if info expects a pointer to char * argument */ -#define curlcheck_string_info(info) \ - (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG) - -/* evaluates to true if info expects a pointer to long argument */ -#define curlcheck_long_info(info) \ - (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE) - -/* evaluates to true if info expects a pointer to double argument */ -#define curlcheck_double_info(info) \ - (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST) - -/* true if info expects a pointer to struct curl_slist * argument */ -#define curlcheck_slist_info(info) \ - (((info) == CURLINFO_SSL_ENGINES) || ((info) == CURLINFO_COOKIELIST)) - -/* true if info expects a pointer to struct curl_tlssessioninfo * argument */ -#define curlcheck_tlssessioninfo_info(info) \ - (((info) == CURLINFO_TLS_SSL_PTR) || ((info) == CURLINFO_TLS_SESSION)) - -/* true if info expects a pointer to struct curl_certinfo * argument */ -#define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO) - -/* true if info expects a pointer to struct curl_socket_t argument */ -#define curlcheck_socket_info(info) \ - (CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T) - -/* true if info expects a pointer to curl_off_t argument */ -#define curlcheck_off_t_info(info) \ - (CURLINFO_OFF_T < (info)) - - -/* typecheck helpers -- check whether given expression has requested type*/ - -/* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros, - * otherwise define a new macro. Search for __builtin_types_compatible_p - * in the GCC manual. - * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is - * the actual expression passed to the curl_easy_setopt macro. This - * means that you can only apply the sizeof and __typeof__ operators, no - * == or whatsoever. - */ - -/* XXX: should evaluate to true if expr is a pointer */ -#define curlcheck_any_ptr(expr) \ - (sizeof(expr) == sizeof(void *)) - -/* evaluates to true if expr is NULL */ -/* XXX: must not evaluate expr, so this check is not accurate */ -#define curlcheck_NULL(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL))) - -/* evaluates to true if expr is type*, const type* or NULL */ -#define curlcheck_ptr(expr, type) \ - (curlcheck_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), type *) || \ - __builtin_types_compatible_p(__typeof__(expr), const type *)) - -/* evaluates to true if expr is one of type[], type*, NULL or const type* */ -#define curlcheck_arr(expr, type) \ - (curlcheck_ptr((expr), type) || \ - __builtin_types_compatible_p(__typeof__(expr), type [])) - -/* evaluates to true if expr is a string */ -#define curlcheck_string(expr) \ - (curlcheck_arr((expr), char) || \ - curlcheck_arr((expr), signed char) || \ - curlcheck_arr((expr), unsigned char)) - -/* evaluates to true if expr is a long (no matter the signedness) - * XXX: for now, int is also accepted (and therefore short and char, which - * are promoted to int when passed to a variadic function) */ -#define curlcheck_long(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), long) || \ - __builtin_types_compatible_p(__typeof__(expr), signed long) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \ - __builtin_types_compatible_p(__typeof__(expr), int) || \ - __builtin_types_compatible_p(__typeof__(expr), signed int) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \ - __builtin_types_compatible_p(__typeof__(expr), short) || \ - __builtin_types_compatible_p(__typeof__(expr), signed short) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \ - __builtin_types_compatible_p(__typeof__(expr), char) || \ - __builtin_types_compatible_p(__typeof__(expr), signed char) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned char)) - -/* evaluates to true if expr is of type curl_off_t */ -#define curlcheck_off_t(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), curl_off_t)) - -/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */ -/* XXX: also check size of an char[] array? */ -#define curlcheck_error_buffer(expr) \ - (curlcheck_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), char *) || \ - __builtin_types_compatible_p(__typeof__(expr), char[])) - -/* evaluates to true if expr is of type (const) void* or (const) FILE* */ -#if 0 -#define curlcheck_cb_data(expr) \ - (curlcheck_ptr((expr), void) || \ - curlcheck_ptr((expr), FILE)) -#else /* be less strict */ -#define curlcheck_cb_data(expr) \ - curlcheck_any_ptr(expr) -#endif - -/* evaluates to true if expr is of type FILE* */ -#define curlcheck_FILE(expr) \ - (curlcheck_NULL(expr) || \ - (__builtin_types_compatible_p(__typeof__(expr), FILE *))) - -/* evaluates to true if expr can be passed as POST data (void* or char*) */ -#define curlcheck_postfields(expr) \ - (curlcheck_ptr((expr), void) || \ - curlcheck_arr((expr), char) || \ - curlcheck_arr((expr), unsigned char)) - -/* helper: __builtin_types_compatible_p distinguishes between functions and - * function pointers, hide it */ -#define curlcheck_cb_compatible(func, type) \ - (__builtin_types_compatible_p(__typeof__(func), type) || \ - __builtin_types_compatible_p(__typeof__(func) *, type)) - -/* evaluates to true if expr is of type curl_resolver_start_callback */ -#define curlcheck_resolver_start_callback(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_resolver_start_callback)) - -/* evaluates to true if expr is of type curl_read_callback or "similar" */ -#define curlcheck_read_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), __typeof__(fread) *) || \ - curlcheck_cb_compatible((expr), curl_read_callback) || \ - curlcheck_cb_compatible((expr), _curl_read_callback1) || \ - curlcheck_cb_compatible((expr), _curl_read_callback2) || \ - curlcheck_cb_compatible((expr), _curl_read_callback3) || \ - curlcheck_cb_compatible((expr), _curl_read_callback4) || \ - curlcheck_cb_compatible((expr), _curl_read_callback5) || \ - curlcheck_cb_compatible((expr), _curl_read_callback6)) -typedef size_t (*_curl_read_callback1)(char *, size_t, size_t, void *); -typedef size_t (*_curl_read_callback2)(char *, size_t, size_t, const void *); -typedef size_t (*_curl_read_callback3)(char *, size_t, size_t, FILE *); -typedef size_t (*_curl_read_callback4)(void *, size_t, size_t, void *); -typedef size_t (*_curl_read_callback5)(void *, size_t, size_t, const void *); -typedef size_t (*_curl_read_callback6)(void *, size_t, size_t, FILE *); - -/* evaluates to true if expr is of type curl_write_callback or "similar" */ -#define curlcheck_write_cb(expr) \ - (curlcheck_read_cb(expr) || \ - curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \ - curlcheck_cb_compatible((expr), curl_write_callback) || \ - curlcheck_cb_compatible((expr), _curl_write_callback1) || \ - curlcheck_cb_compatible((expr), _curl_write_callback2) || \ - curlcheck_cb_compatible((expr), _curl_write_callback3) || \ - curlcheck_cb_compatible((expr), _curl_write_callback4) || \ - curlcheck_cb_compatible((expr), _curl_write_callback5) || \ - curlcheck_cb_compatible((expr), _curl_write_callback6)) -typedef size_t (*_curl_write_callback1)(const char *, size_t, size_t, void *); -typedef size_t (*_curl_write_callback2)(const char *, size_t, size_t, - const void *); -typedef size_t (*_curl_write_callback3)(const char *, size_t, size_t, FILE *); -typedef size_t (*_curl_write_callback4)(const void *, size_t, size_t, void *); -typedef size_t (*_curl_write_callback5)(const void *, size_t, size_t, - const void *); -typedef size_t (*_curl_write_callback6)(const void *, size_t, size_t, FILE *); - -/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */ -#define curlcheck_ioctl_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_ioctl_callback) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback1) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback2) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback3) || \ - curlcheck_cb_compatible((expr), _curl_ioctl_callback4)) -typedef curlioerr (*_curl_ioctl_callback1)(CURL *, int, void *); -typedef curlioerr (*_curl_ioctl_callback2)(CURL *, int, const void *); -typedef curlioerr (*_curl_ioctl_callback3)(CURL *, curliocmd, void *); -typedef curlioerr (*_curl_ioctl_callback4)(CURL *, curliocmd, const void *); - -/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */ -#define curlcheck_sockopt_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_sockopt_callback) || \ - curlcheck_cb_compatible((expr), _curl_sockopt_callback1) || \ - curlcheck_cb_compatible((expr), _curl_sockopt_callback2)) -typedef int (*_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype); -typedef int (*_curl_sockopt_callback2)(const void *, curl_socket_t, - curlsocktype); - -/* evaluates to true if expr is of type curl_opensocket_callback or - "similar" */ -#define curlcheck_opensocket_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_opensocket_callback) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback1) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback2) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback3) || \ - curlcheck_cb_compatible((expr), _curl_opensocket_callback4)) -typedef curl_socket_t (*_curl_opensocket_callback1) - (void *, curlsocktype, struct curl_sockaddr *); -typedef curl_socket_t (*_curl_opensocket_callback2) - (void *, curlsocktype, const struct curl_sockaddr *); -typedef curl_socket_t (*_curl_opensocket_callback3) - (const void *, curlsocktype, struct curl_sockaddr *); -typedef curl_socket_t (*_curl_opensocket_callback4) - (const void *, curlsocktype, const struct curl_sockaddr *); - -/* evaluates to true if expr is of type curl_progress_callback or "similar" */ -#define curlcheck_progress_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_progress_callback) || \ - curlcheck_cb_compatible((expr), _curl_progress_callback1) || \ - curlcheck_cb_compatible((expr), _curl_progress_callback2)) -typedef int (*_curl_progress_callback1)(void *, - double, double, double, double); -typedef int (*_curl_progress_callback2)(const void *, - double, double, double, double); - -/* evaluates to true if expr is of type curl_debug_callback or "similar" */ -#define curlcheck_debug_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_debug_callback) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback1) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback2) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback3) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback4) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback5) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback6) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback7) || \ - curlcheck_cb_compatible((expr), _curl_debug_callback8)) -typedef int (*_curl_debug_callback1) (CURL *, - curl_infotype, char *, size_t, void *); -typedef int (*_curl_debug_callback2) (CURL *, - curl_infotype, char *, size_t, const void *); -typedef int (*_curl_debug_callback3) (CURL *, - curl_infotype, const char *, size_t, void *); -typedef int (*_curl_debug_callback4) (CURL *, - curl_infotype, const char *, size_t, const void *); -typedef int (*_curl_debug_callback5) (CURL *, - curl_infotype, unsigned char *, size_t, void *); -typedef int (*_curl_debug_callback6) (CURL *, - curl_infotype, unsigned char *, size_t, const void *); -typedef int (*_curl_debug_callback7) (CURL *, - curl_infotype, const unsigned char *, size_t, void *); -typedef int (*_curl_debug_callback8) (CURL *, - curl_infotype, const unsigned char *, size_t, const void *); - -/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */ -/* this is getting even messier... */ -#define curlcheck_ssl_ctx_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback1) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback2) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback3) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback4) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback5) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback6) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback7) || \ - curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback8)) -typedef CURLcode (*_curl_ssl_ctx_callback1)(CURL *, void *, void *); -typedef CURLcode (*_curl_ssl_ctx_callback2)(CURL *, void *, const void *); -typedef CURLcode (*_curl_ssl_ctx_callback3)(CURL *, const void *, void *); -typedef CURLcode (*_curl_ssl_ctx_callback4)(CURL *, const void *, - const void *); -#ifdef HEADER_SSL_H -/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX - * this will of course break if we're included before OpenSSL headers... - */ -typedef CURLcode (*_curl_ssl_ctx_callback5)(CURL *, SSL_CTX, void *); -typedef CURLcode (*_curl_ssl_ctx_callback6)(CURL *, SSL_CTX, const void *); -typedef CURLcode (*_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX, void *); -typedef CURLcode (*_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX, - const void *); -#else -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8; -#endif - -/* evaluates to true if expr is of type curl_conv_callback or "similar" */ -#define curlcheck_conv_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_conv_callback) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback1) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback2) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback3) || \ - curlcheck_cb_compatible((expr), _curl_conv_callback4)) -typedef CURLcode (*_curl_conv_callback1)(char *, size_t length); -typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length); -typedef CURLcode (*_curl_conv_callback3)(void *, size_t length); -typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length); - -/* evaluates to true if expr is of type curl_seek_callback or "similar" */ -#define curlcheck_seek_cb(expr) \ - (curlcheck_NULL(expr) || \ - curlcheck_cb_compatible((expr), curl_seek_callback) || \ - curlcheck_cb_compatible((expr), _curl_seek_callback1) || \ - curlcheck_cb_compatible((expr), _curl_seek_callback2)) -typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int); -typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int); - - -#endif /* CURLINC_TYPECHECK_GCC_H */ diff --git a/VCMP-LUA/modules/requests/cpr/include/curl/urlapi.h b/VCMP-LUA/modules/requests/cpr/include/curl/urlapi.h deleted file mode 100644 index f2d0677..0000000 --- a/VCMP-LUA/modules/requests/cpr/include/curl/urlapi.h +++ /dev/null @@ -1,125 +0,0 @@ -#ifndef CURLINC_URLAPI_H -#define CURLINC_URLAPI_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 2018 - 2019, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at https://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* the error codes for the URL API */ -typedef enum { - CURLUE_OK, - CURLUE_BAD_HANDLE, /* 1 */ - CURLUE_BAD_PARTPOINTER, /* 2 */ - CURLUE_MALFORMED_INPUT, /* 3 */ - CURLUE_BAD_PORT_NUMBER, /* 4 */ - CURLUE_UNSUPPORTED_SCHEME, /* 5 */ - CURLUE_URLDECODE, /* 6 */ - CURLUE_OUT_OF_MEMORY, /* 7 */ - CURLUE_USER_NOT_ALLOWED, /* 8 */ - CURLUE_UNKNOWN_PART, /* 9 */ - CURLUE_NO_SCHEME, /* 10 */ - CURLUE_NO_USER, /* 11 */ - CURLUE_NO_PASSWORD, /* 12 */ - CURLUE_NO_OPTIONS, /* 13 */ - CURLUE_NO_HOST, /* 14 */ - CURLUE_NO_PORT, /* 15 */ - CURLUE_NO_QUERY, /* 16 */ - CURLUE_NO_FRAGMENT /* 17 */ -} CURLUcode; - -typedef enum { - CURLUPART_URL, - CURLUPART_SCHEME, - CURLUPART_USER, - CURLUPART_PASSWORD, - CURLUPART_OPTIONS, - CURLUPART_HOST, - CURLUPART_PORT, - CURLUPART_PATH, - CURLUPART_QUERY, - CURLUPART_FRAGMENT, - CURLUPART_ZONEID /* added in 7.65.0 */ -} CURLUPart; - -#define CURLU_DEFAULT_PORT (1<<0) /* return default port number */ -#define CURLU_NO_DEFAULT_PORT (1<<1) /* act as if no port number was set, - if the port number matches the - default for the scheme */ -#define CURLU_DEFAULT_SCHEME (1<<2) /* return default scheme if - missing */ -#define CURLU_NON_SUPPORT_SCHEME (1<<3) /* allow non-supported scheme */ -#define CURLU_PATH_AS_IS (1<<4) /* leave dot sequences */ -#define CURLU_DISALLOW_USER (1<<5) /* no user+password allowed */ -#define CURLU_URLDECODE (1<<6) /* URL decode on get */ -#define CURLU_URLENCODE (1<<7) /* URL encode on set */ -#define CURLU_APPENDQUERY (1<<8) /* append a form style part */ -#define CURLU_GUESS_SCHEME (1<<9) /* legacy curl-style guessing */ -#define CURLU_NO_AUTHORITY (1<<10) /* Allow empty authority when the - scheme is unknown. */ - -typedef struct Curl_URL CURLU; - -/* - * curl_url() creates a new CURLU handle and returns a pointer to it. - * Must be freed with curl_url_cleanup(). - */ -CURL_EXTERN CURLU *curl_url(void); - -/* - * curl_url_cleanup() frees the CURLU handle and related resources used for - * the URL parsing. It will not free strings previously returned with the URL - * API. - */ -CURL_EXTERN void curl_url_cleanup(CURLU *handle); - -/* - * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new - * handle must also be freed with curl_url_cleanup(). - */ -CURL_EXTERN CURLU *curl_url_dup(CURLU *in); - -/* - * curl_url_get() extracts a specific part of the URL from a CURLU - * handle. Returns error code. The returned pointer MUST be freed with - * curl_free() afterwards. - */ -CURL_EXTERN CURLUcode curl_url_get(CURLU *handle, CURLUPart what, - char **part, unsigned int flags); - -/* - * curl_url_set() sets a specific part of the URL in a CURLU handle. Returns - * error code. The passed in string will be copied. Passing a NULL instead of - * a part string, clears that part. - */ -CURL_EXTERN CURLUcode curl_url_set(CURLU *handle, CURLUPart what, - const char *part, unsigned int flags); - - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif /* CURLINC_URLAPI_H */ diff --git a/VCMP-LUA/modules/requests/cpr/lib/cpr.lib b/VCMP-LUA/modules/requests/cpr/lib/cpr.lib deleted file mode 100644 index bae06ba..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/cpr.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/lib/gmock.lib b/VCMP-LUA/modules/requests/cpr/lib/gmock.lib deleted file mode 100644 index 7c9efd0..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/gmock.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/lib/gmock_main.lib b/VCMP-LUA/modules/requests/cpr/lib/gmock_main.lib deleted file mode 100644 index 7655ae6..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/gmock_main.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/lib/gtest.lib b/VCMP-LUA/modules/requests/cpr/lib/gtest.lib deleted file mode 100644 index fbf99ba..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/gtest.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/lib/gtest_main.lib b/VCMP-LUA/modules/requests/cpr/lib/gtest_main.lib deleted file mode 100644 index 8cb29c9..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/gtest_main.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/lib/libcurl.lib b/VCMP-LUA/modules/requests/cpr/lib/libcurl.lib deleted file mode 100644 index f87dace..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/libcurl.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/lib/mongoose.lib b/VCMP-LUA/modules/requests/cpr/lib/mongoose.lib deleted file mode 100644 index b188719..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/mongoose.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/lib/test_server.lib b/VCMP-LUA/modules/requests/cpr/lib/test_server.lib deleted file mode 100644 index bc32e1d..0000000 Binary files a/VCMP-LUA/modules/requests/cpr/lib/test_server.lib and /dev/null differ diff --git a/VCMP-LUA/modules/requests/cpr/src/auth.cpp b/VCMP-LUA/modules/requests/cpr/src/auth.cpp deleted file mode 100644 index 7bd3573..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/auth.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "cpr/auth.h" - -namespace cpr { - -const char* Authentication::GetAuthString() const noexcept { - return auth_string_.c_str(); -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/bearer.cpp b/VCMP-LUA/modules/requests/cpr/src/bearer.cpp deleted file mode 100644 index 5526c6b..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/bearer.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "cpr/bearer.h" - -namespace cpr { - -const char* Bearer::GetToken() const noexcept { - return token_string_.c_str(); -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/cookies.cpp b/VCMP-LUA/modules/requests/cpr/src/cookies.cpp deleted file mode 100644 index 4bd5855..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/cookies.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "cpr/cookies.h" - -namespace cpr { -std::string Cookies::GetEncoded(const CurlHolder& holder) const { - std::stringstream stream; - for (const std::pair& item : map_) { - // Depending on if encoding is set to "true", we will URL-encode cookies - stream << (encode ? holder.urlEncode(item.first) : item.first) << "="; - - // special case version 1 cookies, which can be distinguished by - // beginning and trailing quotes - if (!item.second.empty() && item.second.front() == '"' && item.second.back() == '"') { - stream << item.second; - } else { - // Depending on if encoding is set to "true", we will URL-encode cookies - stream << (encode ? holder.urlEncode(item.second) : item.second); - } - stream << "; "; - } - return stream.str(); -} - -std::string& Cookies::operator[](const std::string& key) { - return map_[key]; -} - -Cookies::iterator Cookies::begin() { - return map_.begin(); -} - -Cookies::iterator Cookies::end() { - return map_.end(); -} - -Cookies::const_iterator Cookies::begin() const { - return map_.begin(); -} - -Cookies::const_iterator Cookies::end() const { - return map_.end(); -} - -Cookies::const_iterator Cookies::cbegin() const { - return map_.cbegin(); -} - -Cookies::const_iterator Cookies::cend() const { - return map_.cend(); -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/cprtypes.cpp b/VCMP-LUA/modules/requests/cpr/src/cprtypes.cpp deleted file mode 100644 index 4daf6de..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/cprtypes.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "cpr/cprtypes.h" - -#include -#include - -namespace cpr { - -bool CaseInsensitiveCompare::operator()(const std::string& a, const std::string& b) const noexcept { - return std::lexicographical_compare( - a.begin(), a.end(), b.begin(), b.end(), - [](unsigned char ac, unsigned char bc) { return std::tolower(ac) < std::tolower(bc); }); -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/curl_container.cpp b/VCMP-LUA/modules/requests/cpr/src/curl_container.cpp deleted file mode 100644 index b114b4f..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/curl_container.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "cpr/curl_container.h" - - -namespace cpr { - - -template -CurlContainer::CurlContainer(const std::initializer_list& containerList) - : containerList_(containerList) {} - - -template -void CurlContainer::Add(const std::initializer_list& containerList) { - for (const T& element : containerList) { - containerList_.push_back(std::move(element)); - } -} - -template -void CurlContainer::Add(const T& element) { - containerList_.push_back(std::move(element)); -} - -template <> -const std::string CurlContainer::GetContent(const CurlHolder& holder) const { - std::string content{}; - for (const Parameter& parameter : containerList_) { - if (!content.empty()) { - content += "&"; - } - - std::string escapedKey = holder.urlEncode(parameter.key); - if (parameter.value.empty()) { - content += escapedKey; - } else { - std::string escapedValue = holder.urlEncode(parameter.value); - content += escapedKey + "=" + escapedValue; - } - }; - - return content; -} - -template <> -const std::string CurlContainer::GetContent(const CurlHolder& holder) const { - std::string content{}; - for (const cpr::Pair& element : containerList_) { - if (!content.empty()) { - content += "&"; - } - std::string escaped = holder.urlEncode(element.value); - content += element.key + "=" + escaped; - } - - return content; -} - -template class CurlContainer; -template class CurlContainer; - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/curlholder.cpp b/VCMP-LUA/modules/requests/cpr/src/curlholder.cpp deleted file mode 100644 index 0fedb46..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/curlholder.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include "cpr/curlholder.h" -#include - -namespace cpr { -std::mutex CurlHolder::curl_easy_init_mutex_{}; - -#ifndef _WIN32 // There is no thread sanitizer on windows -__attribute__((no_sanitize("thread"))) -#endif -CurlHolder::CurlHolder() { - /** - * Allow multithreaded access to CPR by locking curl_easy_init(). - * curl_easy_init() is not thread safe. - * References: - * https://curl.haxx.se/libcurl/c/curl_easy_init.html - * https://curl.haxx.se/libcurl/c/threadsafe.html - **/ - curl_easy_init_mutex_.lock(); - handle = curl_easy_init(); - curl_easy_init_mutex_.unlock(); - - assert(handle); -} // namespace cpr - -CurlHolder::~CurlHolder() { - curl_easy_cleanup(handle); - curl_slist_free_all(chunk); - curl_formfree(formpost); -} - -std::string CurlHolder::urlEncode(const std::string& s) const { - assert(handle); - char* output = curl_easy_escape(handle, s.c_str(), s.length()); - if (output) { - std::string result = output; - curl_free(output); - return result; - } - return ""; -} - -std::string CurlHolder::urlDecode(const std::string& s) const { - assert(handle); - char* output = curl_easy_unescape(handle, s.c_str(), s.length(), nullptr); - if (output) { - std::string result = output; - curl_free(output); - return result; - } - return ""; -} -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/error.cpp b/VCMP-LUA/modules/requests/cpr/src/error.cpp deleted file mode 100644 index e8b785a..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/error.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include "cpr/error.h" - -#include - -namespace cpr { - -ErrorCode Error::getErrorCodeForCurlError(std::int32_t curl_code) { - switch (curl_code) { - case CURLE_OK: - return ErrorCode::OK; - case CURLE_UNSUPPORTED_PROTOCOL: - return ErrorCode::UNSUPPORTED_PROTOCOL; - case CURLE_URL_MALFORMAT: - return ErrorCode::INVALID_URL_FORMAT; - case CURLE_COULDNT_RESOLVE_PROXY: - return ErrorCode::PROXY_RESOLUTION_FAILURE; - case CURLE_COULDNT_RESOLVE_HOST: - return ErrorCode::HOST_RESOLUTION_FAILURE; - case CURLE_COULDNT_CONNECT: - return ErrorCode::CONNECTION_FAILURE; - case CURLE_OPERATION_TIMEDOUT: - return ErrorCode::OPERATION_TIMEDOUT; - case CURLE_SSL_CONNECT_ERROR: - return ErrorCode::SSL_CONNECT_ERROR; -#if LIBCURL_VERSION_NUM < 0x073e00 - case CURLE_PEER_FAILED_VERIFICATION: - return ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR; -#endif - case CURLE_ABORTED_BY_CALLBACK: - return ErrorCode::REQUEST_CANCELLED; - case CURLE_WRITE_ERROR: - return ErrorCode::REQUEST_CANCELLED; - case CURLE_GOT_NOTHING: - return ErrorCode::EMPTY_RESPONSE; - case CURLE_SSL_ENGINE_NOTFOUND: - return ErrorCode::GENERIC_SSL_ERROR; - case CURLE_SSL_ENGINE_SETFAILED: - return ErrorCode::GENERIC_SSL_ERROR; - case CURLE_SEND_ERROR: - return ErrorCode::NETWORK_SEND_FAILURE; - case CURLE_RECV_ERROR: - return ErrorCode::NETWORK_RECEIVE_ERROR; - case CURLE_SSL_CERTPROBLEM: - return ErrorCode::SSL_LOCAL_CERTIFICATE_ERROR; - case CURLE_SSL_CIPHER: - return ErrorCode::GENERIC_SSL_ERROR; -#if LIBCURL_VERSION_NUM >= 0x073e00 - case CURLE_PEER_FAILED_VERIFICATION: - return ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR; -#else - case CURLE_SSL_CACERT: - return ErrorCode::SSL_CACERT_ERROR; -#endif - case CURLE_USE_SSL_FAILED: - return ErrorCode::GENERIC_SSL_ERROR; - case CURLE_SSL_ENGINE_INITFAILED: - return ErrorCode::GENERIC_SSL_ERROR; - case CURLE_SSL_CACERT_BADFILE: - return ErrorCode::SSL_CACERT_ERROR; - case CURLE_SSL_SHUTDOWN_FAILED: - return ErrorCode::GENERIC_SSL_ERROR; - case CURLE_SSL_CRL_BADFILE: - return ErrorCode::SSL_CACERT_ERROR; - case CURLE_SSL_ISSUER_ERROR: - return ErrorCode::SSL_CACERT_ERROR; - case CURLE_TOO_MANY_REDIRECTS: - return ErrorCode::OK; - default: - return ErrorCode::INTERNAL_ERROR; - } -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/multipart.cpp b/VCMP-LUA/modules/requests/cpr/src/multipart.cpp deleted file mode 100644 index c2e030a..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/multipart.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "cpr/multipart.h" - -namespace cpr { - -Multipart::Multipart(const std::initializer_list& parts) : parts{parts} {} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/parameters.cpp b/VCMP-LUA/modules/requests/cpr/src/parameters.cpp deleted file mode 100644 index 061a6a2..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/parameters.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "cpr/parameters.h" - -#include -#include - -#include "cpr/util.h" - -namespace cpr { - -Parameters::Parameters(const std::initializer_list& parameters) : CurlContainer(parameters) { - -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/payload.cpp b/VCMP-LUA/modules/requests/cpr/src/payload.cpp deleted file mode 100644 index a907fdd..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/payload.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "cpr/payload.h" - -#include -#include - -#include "cpr/util.h" - -namespace cpr { - -Payload::Payload(const std::initializer_list& pairs) : CurlContainer(pairs) { - -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/proxies.cpp b/VCMP-LUA/modules/requests/cpr/src/proxies.cpp deleted file mode 100644 index 446f7d7..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/proxies.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "cpr/proxies.h" - -#include -#include -#include -#include - -namespace cpr { - -Proxies::Proxies(const std::initializer_list>& hosts) - : hosts_{hosts} {} - -bool Proxies::has(const std::string& protocol) const { - return hosts_.count(protocol) > 0; -} - -const std::string& Proxies::operator[](const std::string& protocol) { - return hosts_[protocol]; -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/response.cpp b/VCMP-LUA/modules/requests/cpr/src/response.cpp deleted file mode 100644 index e1460f9..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/response.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include "cpr/response.h" - -namespace cpr { -Response::Response(std::shared_ptr curl, std::string&& p_text, - std::string&& p_header_string, Cookies&& p_cookies = Cookies{}, - Error&& p_error = Error{}) - : curl_(std::move(curl)), text(std::move(p_text)), cookies(std::move(p_cookies)), - error(std::move(p_error)) { - header = cpr::util::parseHeader(p_header_string, &status_line, &reason); - assert(curl_->handle); - curl_easy_getinfo(curl_->handle, CURLINFO_RESPONSE_CODE, &status_code); - curl_easy_getinfo(curl_->handle, CURLINFO_TOTAL_TIME, &elapsed); - char* url_string{nullptr}; - curl_easy_getinfo(curl_->handle, CURLINFO_EFFECTIVE_URL, &url_string); - url = Url(url_string); -#if LIBCURL_VERSION_NUM >= 0x073700 - curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_DOWNLOAD_T, &downloaded_bytes); - curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_UPLOAD_T, &uploaded_bytes); -#else - double downloaded_bytes_double, uploaded_bytes_double; - curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_DOWNLOAD, &downloaded_bytes_double); - curl_easy_getinfo(curl_->handle, CURLINFO_SIZE_UPLOAD, &uploaded_bytes_double); - downloaded_bytes = downloaded_bytes_double; - uploaded_bytes = uploaded_bytes_double; -#endif - curl_easy_getinfo(curl_->handle, CURLINFO_REDIRECT_COUNT, &redirect_count); -} - -std::vector Response::GetCertInfo() { - assert(curl_->handle); - curl_certinfo* ci; - curl_easy_getinfo(curl_->handle, CURLINFO_CERTINFO, &ci); - - std::vector info; - info.resize(ci->num_of_certs); - for (size_t i = 0; i < ci->num_of_certs; i++) { - info[i] = std::string{ci->certinfo[i]->data}; - } - - return info; -} -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/session.cpp b/VCMP-LUA/modules/requests/cpr/src/session.cpp deleted file mode 100644 index 4fee4db..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/session.cpp +++ /dev/null @@ -1,654 +0,0 @@ -#include "cpr/session.h" - -#include -#include -#include -#include -#include - -#include - -#include "cpr/curlholder.h" -#include "cpr/util.h" - -namespace cpr { - -constexpr long ON = 1L; -constexpr long OFF = 0L; - -class Session::Impl { - public: - Impl(); - - void SetUrl(const Url& url); - void SetParameters(const Parameters& parameters); - void SetParameters(Parameters&& parameters); - void SetHeader(const Header& header); - void SetTimeout(const Timeout& timeout); - void SetConnectTimeout(const ConnectTimeout& timeout); - void SetAuth(const Authentication& auth); - void SetBearer(const Bearer& token); - void SetDigest(const Digest& auth); - void SetUserAgent(const UserAgent& ua); - void SetPayload(Payload&& payload); - void SetPayload(const Payload& payload); - void SetProxies(Proxies&& proxies); - void SetProxies(const Proxies& proxies); - void SetMultipart(Multipart&& multipart); - void SetMultipart(const Multipart& multipart); - void SetNTLM(const NTLM& auth); - void SetRedirect(const bool& redirect); - void SetMaxRedirects(const MaxRedirects& max_redirects); - void SetCookies(const Cookies& cookies); - void SetBody(Body&& body); - void SetBody(const Body& body); - void SetReadCallback(const ReadCallback& read); - void SetHeaderCallback(const HeaderCallback& header); - void SetWriteCallback(const WriteCallback& write); - void SetProgressCallback(const ProgressCallback& progress); - void SetDebugCallback(const DebugCallback& debug); - void SetLowSpeed(const LowSpeed& low_speed); - void SetVerifySsl(const VerifySsl& verify); - void SetLimitRate(const LimitRate& limit_rate); - void SetUnixSocket(const UnixSocket& unix_socket); - void SetVerbose(const Verbose& verbose); - void SetSslOptions(const SslOptions& options); - - Response Delete(); - Response Download(const WriteCallback& write); - Response Download(std::ofstream& file); - Response Get(); - Response Head(); - Response Options(); - Response Patch(); - Response Post(); - Response Put(); - - private: - bool hasBodyOrPayload_{false}; - - std::shared_ptr curl_; - Url url_; - Parameters parameters_; - Proxies proxies_; - - ReadCallback readcb_; - HeaderCallback headercb_; - WriteCallback writecb_; - ProgressCallback progresscb_; - DebugCallback debugcb_; - - Response makeDownloadRequest(); - Response makeRequest(); - static void freeHolder(CurlHolder* holder); -}; - -Session::Impl::Impl() : curl_(new CurlHolder()) { - // Set up some sensible defaults - curl_version_info_data* version_info = curl_version_info(CURLVERSION_NOW); - std::string version = "curl/" + std::string{version_info->version}; - curl_easy_setopt(curl_->handle, CURLOPT_USERAGENT, version.c_str()); - curl_easy_setopt(curl_->handle, CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(curl_->handle, CURLOPT_NOPROGRESS, 1L); - curl_easy_setopt(curl_->handle, CURLOPT_MAXREDIRS, 50L); - curl_easy_setopt(curl_->handle, CURLOPT_ERRORBUFFER, curl_->error); - curl_easy_setopt(curl_->handle, CURLOPT_COOKIEFILE, ""); -#ifdef CPR_CURL_NOSIGNAL - curl_easy_setopt(curl_->handle, CURLOPT_NOSIGNAL, 1L); -#endif - -#if LIBCURL_VERSION_MAJOR >= 7 -#if LIBCURL_VERSION_MINOR >= 25 -#if LIBCURL_VERSION_PATCH >= 0 - curl_easy_setopt(curl_->handle, CURLOPT_TCP_KEEPALIVE, 1L); -#endif -#endif -#endif -} - -void Session::Impl::SetUrl(const Url& url) { - url_ = url; -} - -void Session::Impl::SetParameters(const Parameters& parameters) { - parameters_ = parameters; -} - -void Session::Impl::SetParameters(Parameters&& parameters) { - parameters_ = std::move(parameters); -} - -void Session::Impl::SetHeader(const Header& header) { - curl_slist* chunk = nullptr; - for (Header::const_iterator item = header.cbegin(); item != header.cend(); ++item) { - std::string header_string = item->first; - if (item->second.empty()) { - header_string += ";"; - } else { - header_string += ": " + item->second; - } - - curl_slist* temp = curl_slist_append(chunk, header_string.c_str()); - if (temp) { - chunk = temp; - } - } - curl_easy_setopt(curl_->handle, CURLOPT_HTTPHEADER, chunk); - - curl_slist_free_all(curl_->chunk); - curl_->chunk = chunk; -} - -void Session::Impl::SetTimeout(const Timeout& timeout) { - curl_easy_setopt(curl_->handle, CURLOPT_TIMEOUT_MS, timeout.Milliseconds()); -} - -void Session::Impl::SetConnectTimeout(const ConnectTimeout& timeout) { - curl_easy_setopt(curl_->handle, CURLOPT_CONNECTTIMEOUT_MS, timeout.Milliseconds()); -} - -void Session::Impl::SetVerbose(const Verbose& verbose) { - curl_easy_setopt(curl_->handle, CURLOPT_VERBOSE, verbose.verbose ? ON : OFF); -} - -void Session::Impl::SetAuth(const Authentication& auth) { - curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); - curl_easy_setopt(curl_->handle, CURLOPT_USERPWD, auth.GetAuthString()); -} - -void Session::Impl::SetBearer(const Bearer& token) { - curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); - curl_easy_setopt(curl_->handle, CURLOPT_XOAUTH2_BEARER, token.GetToken()); -} - -void Session::Impl::SetDigest(const Digest& auth) { - curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); - curl_easy_setopt(curl_->handle, CURLOPT_USERPWD, auth.GetAuthString()); -} - -void Session::Impl::SetUserAgent(const UserAgent& ua) { - curl_easy_setopt(curl_->handle, CURLOPT_USERAGENT, ua.c_str()); -} - -void Session::Impl::SetPayload(Payload&& payload) { - hasBodyOrPayload_ = true; - const std::string content = payload.GetContent(*curl_); - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, - static_cast(content.length())); - curl_easy_setopt(curl_->handle, CURLOPT_COPYPOSTFIELDS, content.c_str()); -} - -void Session::Impl::SetPayload(const Payload& payload) { - hasBodyOrPayload_ = true; - const std::string content = payload.GetContent(*curl_); - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, - static_cast(content.length())); - curl_easy_setopt(curl_->handle, CURLOPT_COPYPOSTFIELDS, std::move(content.c_str())); -} - -void Session::Impl::SetProxies(const Proxies& proxies) { - proxies_ = proxies; -} - -void Session::Impl::SetProxies(Proxies&& proxies) { - proxies_ = std::move(proxies); -} - -void Session::Impl::SetMultipart(Multipart&& multipart) { - curl_httppost* formpost = nullptr; - curl_httppost* lastptr = nullptr; - - for (const Part& part : multipart.parts) { - std::vector formdata; - formdata.push_back({CURLFORM_COPYNAME, part.name.c_str()}); - if (part.is_buffer) { - formdata.push_back({CURLFORM_BUFFER, part.value.c_str()}); - formdata.push_back({CURLFORM_COPYCONTENTS, reinterpret_cast(part.data)}); - formdata.push_back( - {CURLFORM_CONTENTSLENGTH, reinterpret_cast(part.datalen)}); - } else if (part.is_file) { - formdata.push_back({CURLFORM_FILE, part.value.c_str()}); - } else { - formdata.push_back({CURLFORM_COPYCONTENTS, part.value.c_str()}); - } - if (!part.content_type.empty()) { - formdata.push_back({CURLFORM_CONTENTTYPE, part.content_type.c_str()}); - } - formdata.push_back({CURLFORM_END, nullptr}); - curl_formadd(&formpost, &lastptr, CURLFORM_ARRAY, formdata.data(), CURLFORM_END); - } - curl_easy_setopt(curl_->handle, CURLOPT_HTTPPOST, formpost); - hasBodyOrPayload_ = true; - - curl_formfree(curl_->formpost); - curl_->formpost = formpost; -} - -void Session::Impl::SetMultipart(const Multipart& multipart) { - curl_httppost* formpost = nullptr; - curl_httppost* lastptr = nullptr; - - for (const Part& part : multipart.parts) { - std::vector formdata; - formdata.push_back({CURLFORM_PTRNAME, part.name.c_str()}); - if (part.is_buffer) { - formdata.push_back({CURLFORM_BUFFER, part.value.c_str()}); - formdata.push_back({CURLFORM_BUFFERPTR, reinterpret_cast(part.data)}); - formdata.push_back( - {CURLFORM_BUFFERLENGTH, reinterpret_cast(part.datalen)}); - } else if (part.is_file) { - formdata.push_back({CURLFORM_FILE, part.value.c_str()}); - } else { - formdata.push_back({CURLFORM_PTRCONTENTS, part.value.c_str()}); - } - if (!part.content_type.empty()) { - formdata.push_back({CURLFORM_CONTENTTYPE, part.content_type.c_str()}); - } - formdata.push_back({CURLFORM_END, nullptr}); - curl_formadd(&formpost, &lastptr, CURLFORM_ARRAY, formdata.data(), CURLFORM_END); - } - curl_easy_setopt(curl_->handle, CURLOPT_HTTPPOST, formpost); - hasBodyOrPayload_ = true; - - curl_formfree(curl_->formpost); - curl_->formpost = formpost; -} - -void Session::Impl::SetLimitRate(const LimitRate& limit_rate) { - curl_easy_setopt(curl_->handle, CURLOPT_MAX_RECV_SPEED_LARGE, limit_rate.downrate); - curl_easy_setopt(curl_->handle, CURLOPT_MAX_SEND_SPEED_LARGE, limit_rate.uprate); -} - -void Session::Impl::SetNTLM(const NTLM& auth) { - curl_easy_setopt(curl_->handle, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); - curl_easy_setopt(curl_->handle, CURLOPT_USERPWD, auth.GetAuthString()); -} - -void Session::Impl::SetRedirect(const bool& redirect) { - curl_easy_setopt(curl_->handle, CURLOPT_FOLLOWLOCATION, std::int32_t(redirect)); -} - -void Session::Impl::SetMaxRedirects(const MaxRedirects& max_redirects) { - curl_easy_setopt(curl_->handle, CURLOPT_MAXREDIRS, max_redirects.number_of_redirects); -} - -void Session::Impl::SetCookies(const Cookies& cookies) { - curl_easy_setopt(curl_->handle, CURLOPT_COOKIELIST, "ALL"); - curl_easy_setopt(curl_->handle, CURLOPT_COOKIE, cookies.GetEncoded(*curl_).c_str()); -} - -void Session::Impl::SetBody(Body&& body) { - hasBodyOrPayload_ = true; - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, - static_cast(body.str().length())); - curl_easy_setopt(curl_->handle, CURLOPT_COPYPOSTFIELDS, body.c_str()); -} - -void Session::Impl::SetBody(const Body& body) { - hasBodyOrPayload_ = true; - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, - static_cast(body.str().length())); - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDS, body.c_str()); -} - -void Session::Impl::SetReadCallback(const ReadCallback& read) { - readcb_ = read; - curl_easy_setopt(curl_->handle, CURLOPT_INFILESIZE_LARGE, read.size); - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDSIZE_LARGE, read.size); - curl_easy_setopt(curl_->handle, CURLOPT_READFUNCTION, cpr::util::readUserFunction); - curl_easy_setopt(curl_->handle, CURLOPT_READDATA, &readcb_); - if (read.size == -1) { - SetHeader({{"Transfer-Encoding", "chunked"}}); - } -} - -void Session::Impl::SetHeaderCallback(const HeaderCallback& header) { - curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::headerUserFunction); - headercb_ = header; - curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &headercb_); -} - -void Session::Impl::SetWriteCallback(const WriteCallback& write) { - curl_easy_setopt(curl_->handle, CURLOPT_WRITEFUNCTION, cpr::util::writeUserFunction); - writecb_ = write; - curl_easy_setopt(curl_->handle, CURLOPT_WRITEDATA, &writecb_); -} - -void Session::Impl::SetProgressCallback(const ProgressCallback& progress) { - progresscb_ = progress; -#if LIBCURL_VERSION_NUM < 0x072000 - curl_easy_setopt(curl_->handle, CURLOPT_PROGRESSFUNCTION, cpr::util::progressUserFunction); - curl_easy_setopt(curl_->handle, CURLOPT_PROGRESSDATA, &progresscb_); -#else - curl_easy_setopt(curl_->handle, CURLOPT_XFERINFOFUNCTION, cpr::util::progressUserFunction); - curl_easy_setopt(curl_->handle, CURLOPT_XFERINFODATA, &progresscb_); -#endif - curl_easy_setopt(curl_->handle, CURLOPT_NOPROGRESS, 0L); -} - -void Session::Impl::SetDebugCallback(const DebugCallback& debug) { - curl_easy_setopt(curl_->handle, CURLOPT_DEBUGFUNCTION, cpr::util::debugUserFunction); - debugcb_ = debug; - curl_easy_setopt(curl_->handle, CURLOPT_DEBUGDATA, &debugcb_); - curl_easy_setopt(curl_->handle, CURLOPT_VERBOSE, 1L); -} - -void Session::Impl::SetLowSpeed(const LowSpeed& low_speed) { - curl_easy_setopt(curl_->handle, CURLOPT_LOW_SPEED_LIMIT, low_speed.limit); - curl_easy_setopt(curl_->handle, CURLOPT_LOW_SPEED_TIME, low_speed.time); -} - -void Session::Impl::SetVerifySsl(const VerifySsl& verify) { - curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYPEER, verify ? ON : OFF); - curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYHOST, verify ? 2L : 0L); -} - -void Session::Impl::SetUnixSocket(const UnixSocket& unix_socket) { - curl_easy_setopt(curl_->handle, CURLOPT_UNIX_SOCKET_PATH, unix_socket.GetUnixSocketString()); -} - -void Session::Impl::SetSslOptions(const SslOptions& opts) { - if (!opts.cert_file.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_SSLCERT, opts.cert_file.c_str()); - if (!opts.cert_type.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_SSLCERTTYPE, opts.cert_type.c_str()); - } - } - if (!opts.key_file.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_SSLKEY, opts.key_file.c_str()); - if (!opts.key_type.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_SSLKEYTYPE, opts.key_type.c_str()); - } - if (!opts.key_pass.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_KEYPASSWD, opts.key_pass.c_str()); - } - } -#if SUPPORT_ALPN - curl_easy_setopt(curl_->handle, CURLOPT_SSL_ENABLE_ALPN, opts.enable_alpn ? ON : OFF); -#endif -#if SUPPORT_NPN - curl_easy_setopt(curl_->handle, CURLOPT_SSL_ENABLE_NPN, opts.enable_npn ? ON : OFF); -#endif - curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYPEER, opts.verify_peer ? ON : OFF); - curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYHOST, opts.verify_host ? 2L : 0L); -#if LIBCURL_VERSION_NUM >= 0x072900 - curl_easy_setopt(curl_->handle, CURLOPT_SSL_VERIFYSTATUS, opts.verify_status ? ON : OFF); -#endif - curl_easy_setopt(curl_->handle, CURLOPT_SSLVERSION, - opts.ssl_version -#if SUPPORT_MAX_TLS_VERSION - | opts.max_version -#endif - ); - if (!opts.ca_info.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_CAINFO, opts.ca_info.c_str()); - } - if (!opts.ca_path.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_CAPATH, opts.ca_path.c_str()); - } - if (!opts.crl_file.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_CRLFILE, opts.crl_file.c_str()); - } - if (!opts.ciphers.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_SSL_CIPHER_LIST, opts.ciphers.c_str()); - } -#if SUPPORT_TLSv13_CIPHERS - if (!opts.tls13_ciphers.empty()) { - curl_easy_setopt(curl_->handle, CURLOPT_TLS13_CIPHERS, opts.ciphers.c_str()); - } -#endif -#if SUPPORT_SESSIONID_CACHE - curl_easy_setopt(curl_->handle, CURLOPT_SSL_SESSIONID_CACHE, opts.session_id_cache ? ON : OFF); -#endif -} - -Response Session::Impl::Delete() { - curl_easy_setopt(curl_->handle, CURLOPT_HTTPGET, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "DELETE"); - - return makeRequest(); -} - -Response Session::Impl::Download(const WriteCallback& write) { - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "GET"); - - SetWriteCallback(write); - - return makeDownloadRequest(); -} - -Response Session::Impl::Download(std::ofstream& file) { - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "GET"); - curl_easy_setopt(curl_->handle, CURLOPT_WRITEFUNCTION, cpr::util::writeFileFunction); - curl_easy_setopt(curl_->handle, CURLOPT_WRITEDATA, &file); - - return makeDownloadRequest(); -} - -Response Session::Impl::Get() { - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "GET"); - - return makeRequest(); -} - -Response Session::Impl::Head() { - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, nullptr); - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 1L); - - return makeRequest(); -} - -Response Session::Impl::Options() { - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "OPTIONS"); - - return makeRequest(); -} - -Response Session::Impl::Patch() { - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "PATCH"); - - return makeRequest(); -} - -Response Session::Impl::Post() { - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "POST"); - - // In case there is no body or payload set it to an empty post: - if (!hasBodyOrPayload_) { - if (!readcb_.callback) { - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDS, ""); - } else { - curl_easy_setopt(curl_->handle, CURLOPT_POSTFIELDS, 0); - } - } - - return makeRequest(); -} - -Response Session::Impl::Put() { - curl_easy_setopt(curl_->handle, CURLOPT_NOBODY, 0L); - curl_easy_setopt(curl_->handle, CURLOPT_CUSTOMREQUEST, "PUT"); - - return makeRequest(); -} - -Response Session::Impl::makeDownloadRequest() { - assert(curl_->handle); - const std::string parametersContent = parameters_.GetContent(*curl_); - if (!parametersContent.empty()) { - Url new_url{url_ + "?" + parametersContent}; - curl_easy_setopt(curl_->handle, CURLOPT_URL, new_url.c_str()); - } else { - curl_easy_setopt(curl_->handle, CURLOPT_URL, url_.c_str()); - } - - std::string protocol = url_.str().substr(0, url_.str().find(':')); - if (proxies_.has(protocol)) { - curl_easy_setopt(curl_->handle, CURLOPT_PROXY, proxies_[protocol].c_str()); - } else { - curl_easy_setopt(curl_->handle, CURLOPT_PROXY, ""); - } - - curl_->error[0] = '\0'; - - std::string header_string; - if (headercb_.callback) { - curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::headerUserFunction); - curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &headercb_); - } else { - curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::writeFunction); - curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &header_string); - } - - CURLcode curl_error = curl_easy_perform(curl_->handle); - - curl_slist* raw_cookies; - curl_easy_getinfo(curl_->handle, CURLINFO_COOKIELIST, &raw_cookies); - Cookies cookies = util::parseCookies(raw_cookies); - curl_slist_free_all(raw_cookies); - - return Response(curl_, "", std::move(header_string), std::move(cookies), - Error(curl_error, curl_->error)); -} - -Response Session::Impl::makeRequest() { - assert(curl_->handle); - const std::string parametersContent = parameters_.GetContent(*curl_); - if (!parametersContent.empty()) { - Url new_url{url_ + "?" + parametersContent}; - curl_easy_setopt(curl_->handle, CURLOPT_URL, new_url.c_str()); - } else { - curl_easy_setopt(curl_->handle, CURLOPT_URL, url_.c_str()); - } - - std::string protocol = url_.str().substr(0, url_.str().find(':')); - if (proxies_.has(protocol)) { - curl_easy_setopt(curl_->handle, CURLOPT_PROXY, proxies_[protocol].c_str()); - } else { - curl_easy_setopt(curl_->handle, CURLOPT_PROXY, nullptr); - } - -#if LIBCURL_VERSION_MAJOR >= 7 -#if LIBCURL_VERSION_MINOR >= 21 - /* enable all supported built-in compressions */ - curl_easy_setopt(curl_->handle, CURLOPT_ACCEPT_ENCODING, ""); -#endif -#endif - - curl_->error[0] = '\0'; - - std::string response_string; - std::string header_string; - if (!this->writecb_.callback) { - curl_easy_setopt(curl_->handle, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction); - curl_easy_setopt(curl_->handle, CURLOPT_WRITEDATA, &response_string); - } - if (!this->headercb_.callback) { - curl_easy_setopt(curl_->handle, CURLOPT_HEADERFUNCTION, cpr::util::writeFunction); - curl_easy_setopt(curl_->handle, CURLOPT_HEADERDATA, &header_string); - } - - // Enable so we are able to retrive certificate information: - curl_easy_setopt(curl_->handle, CURLOPT_CERTINFO, 1L); - - CURLcode curl_error = curl_easy_perform(curl_->handle); - - curl_slist* raw_cookies; - curl_easy_getinfo(curl_->handle, CURLINFO_COOKIELIST, &raw_cookies); - Cookies cookies = util::parseCookies(raw_cookies); - curl_slist_free_all(raw_cookies); - - // Reset the has no body property: - hasBodyOrPayload_ = false; - - return Response(curl_, std::move(response_string), std::move(header_string), std::move(cookies), - Error(curl_error, curl_->error)); -} - -// clang-format off -Session::Session() : pimpl_{ new Impl{} } {} -Session::Session(Session&& other) : pimpl_{ std::move(other.pimpl_) } {} -Session& Session::operator=(Session&& other) { pimpl_ = std::move(other.pimpl_); return *this; } -Session::~Session() {} -void Session::SetReadCallback(const ReadCallback& read) { pimpl_->SetReadCallback(read); } -void Session::SetHeaderCallback(const HeaderCallback& header) { pimpl_->SetHeaderCallback(header); } -void Session::SetWriteCallback(const WriteCallback& write) { pimpl_->SetWriteCallback(write); } -void Session::SetProgressCallback(const ProgressCallback& progress) { pimpl_->SetProgressCallback(progress); } -void Session::SetUrl(const Url& url) { pimpl_->SetUrl(url); } -void Session::SetParameters(const Parameters& parameters) { pimpl_->SetParameters(parameters); } -void Session::SetParameters(Parameters&& parameters) { pimpl_->SetParameters(std::move(parameters)); } -void Session::SetHeader(const Header& header) { pimpl_->SetHeader(header); } -void Session::SetTimeout(const Timeout& timeout) { pimpl_->SetTimeout(timeout); } -void Session::SetConnectTimeout(const ConnectTimeout& timeout) { pimpl_->SetConnectTimeout(timeout); } -void Session::SetAuth(const Authentication& auth) { pimpl_->SetAuth(auth); } -void Session::SetDigest(const Digest& auth) { pimpl_->SetDigest(auth); } -void Session::SetUserAgent(const UserAgent& ua) { pimpl_->SetUserAgent(ua); } -void Session::SetPayload(const Payload& payload) { pimpl_->SetPayload(payload); } -void Session::SetPayload(Payload&& payload) { pimpl_->SetPayload(std::move(payload)); } -void Session::SetProxies(const Proxies& proxies) { pimpl_->SetProxies(proxies); } -void Session::SetProxies(Proxies&& proxies) { pimpl_->SetProxies(std::move(proxies)); } -void Session::SetMultipart(const Multipart& multipart) { pimpl_->SetMultipart(multipart); } -void Session::SetMultipart(Multipart&& multipart) { pimpl_->SetMultipart(std::move(multipart)); } -void Session::SetNTLM(const NTLM& auth) { pimpl_->SetNTLM(auth); } -void Session::SetRedirect(const bool& redirect) { pimpl_->SetRedirect(redirect); } -void Session::SetMaxRedirects(const MaxRedirects& max_redirects) { pimpl_->SetMaxRedirects(max_redirects); } -void Session::SetCookies(const Cookies& cookies) { pimpl_->SetCookies(cookies); } -void Session::SetBody(const Body& body) { pimpl_->SetBody(body); } -void Session::SetBody(Body&& body) { pimpl_->SetBody(std::move(body)); } -void Session::SetLowSpeed(const LowSpeed& low_speed) { pimpl_->SetLowSpeed(low_speed); } -void Session::SetVerifySsl(const VerifySsl& verify) { pimpl_->SetVerifySsl(verify); } -void Session::SetUnixSocket(const UnixSocket& unix_socket) { pimpl_->SetUnixSocket(unix_socket); } -void Session::SetSslOptions(const SslOptions& options) { pimpl_->SetSslOptions(options); } -void Session::SetVerbose(const Verbose& verbose) { pimpl_->SetVerbose(verbose); } -void Session::SetOption(const ReadCallback& read) { pimpl_->SetReadCallback(read); } -void Session::SetOption(const HeaderCallback& header) { pimpl_->SetHeaderCallback(header); } -void Session::SetOption(const WriteCallback& write) { pimpl_->SetWriteCallback(write); } -void Session::SetOption(const ProgressCallback& progress) { pimpl_->SetProgressCallback(progress); } -void Session::SetOption(const DebugCallback& debug) { pimpl_->SetDebugCallback(debug); } -void Session::SetOption(const Url& url) { pimpl_->SetUrl(url); } -void Session::SetOption(const Parameters& parameters) { pimpl_->SetParameters(parameters); } -void Session::SetOption(Parameters&& parameters) { pimpl_->SetParameters(std::move(parameters)); } -void Session::SetOption(const Header& header) { pimpl_->SetHeader(header); } -void Session::SetOption(const Timeout& timeout) { pimpl_->SetTimeout(timeout); } -void Session::SetOption(const ConnectTimeout& timeout) { pimpl_->SetConnectTimeout(timeout); } -void Session::SetOption(const Authentication& auth) { pimpl_->SetAuth(auth); } -void Session::SetOption(const Bearer& auth) { pimpl_->SetBearer(auth); } -void Session::SetOption(const Digest& auth) { pimpl_->SetDigest(auth); } -void Session::SetOption(const UserAgent& ua) { pimpl_->SetUserAgent(ua); } -void Session::SetOption(const Payload& payload) { pimpl_->SetPayload(payload); } -void Session::SetOption(Payload&& payload) { pimpl_->SetPayload(std::move(payload)); } -void Session::SetOption(const Proxies& proxies) { pimpl_->SetProxies(proxies); } -void Session::SetOption(Proxies&& proxies) { pimpl_->SetProxies(std::move(proxies)); } -void Session::SetOption(const Multipart& multipart) { pimpl_->SetMultipart(multipart); } -void Session::SetOption(Multipart&& multipart) { pimpl_->SetMultipart(std::move(multipart)); } -void Session::SetOption(const NTLM& auth) { pimpl_->SetNTLM(auth); } -void Session::SetOption(const bool& redirect) { pimpl_->SetRedirect(redirect); } -void Session::SetOption(const MaxRedirects& max_redirects) { pimpl_->SetMaxRedirects(max_redirects); } -void Session::SetOption(const Cookies& cookies) { pimpl_->SetCookies(cookies); } -void Session::SetOption(const Body& body) { pimpl_->SetBody(body); } -void Session::SetOption(Body&& body) { pimpl_->SetBody(std::move(body)); } -void Session::SetOption(const LowSpeed& low_speed) { pimpl_->SetLowSpeed(low_speed); } -void Session::SetOption(const VerifySsl& verify) { pimpl_->SetVerifySsl(verify); } -void Session::SetOption(const Verbose& verbose) { pimpl_->SetVerbose(verbose); } -void Session::SetOption(const UnixSocket& unix_socket) { pimpl_->SetUnixSocket(unix_socket); } -void Session::SetOption(const SslOptions& options) { pimpl_->SetSslOptions(options); } - -Response Session::Delete() { return pimpl_->Delete(); } -Response Session::Download(const WriteCallback& write) { return pimpl_->Download(write); } -Response Session::Download(std::ofstream& file) { return pimpl_->Download(file); } -Response Session::Get() { return pimpl_->Get(); } -Response Session::Head() { return pimpl_->Head(); } -Response Session::Options() { return pimpl_->Options(); } -Response Session::Patch() { return pimpl_->Patch(); } -Response Session::Post() { return pimpl_->Post(); } -Response Session::Put() { return pimpl_->Put(); } -// clang-format on - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/timeout.cpp b/VCMP-LUA/modules/requests/cpr/src/timeout.cpp deleted file mode 100644 index 1d646dd..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/timeout.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "cpr/timeout.h" - -#include -#include -#include -#include - -namespace cpr { - -long Timeout::Milliseconds() const { - static_assert(std::is_same::value, - "Following casting expects milliseconds."); - - if (ms.count() > std::numeric_limits::max()) { - throw std::overflow_error( - "cpr::Timeout: timeout value overflow: " + std::to_string(ms.count()) + " ms."); - } - if (ms.count() < std::numeric_limits::min()) { - throw std::underflow_error( - "cpr::Timeout: timeout value underflow: " + std::to_string(ms.count()) + " ms."); - } - - return static_cast(ms.count()); -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/unix_socket.cpp b/VCMP-LUA/modules/requests/cpr/src/unix_socket.cpp deleted file mode 100644 index 7f0884e..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/unix_socket.cpp +++ /dev/null @@ -1,10 +0,0 @@ - -#include "cpr/unix_socket.h" - -namespace cpr { - -const char* UnixSocket::GetUnixSocketString() const noexcept { - return unix_socket_.data(); -} - -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/cpr/src/util.cpp b/VCMP-LUA/modules/requests/cpr/src/util.cpp deleted file mode 100644 index 73fc5f6..0000000 --- a/VCMP-LUA/modules/requests/cpr/src/util.cpp +++ /dev/null @@ -1,163 +0,0 @@ -#include "cpr/util.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cpr { -namespace util { - -Cookies parseCookies(curl_slist* raw_cookies) { - Cookies cookies; - for (curl_slist* nc = raw_cookies; nc; nc = nc->next) { - std::vector tokens = cpr::util::split(nc->data, '\t'); - std::string value = tokens.back(); - tokens.pop_back(); - cookies[tokens.back()] = value; - } - return cookies; -} - -Header parseHeader(const std::string& headers, std::string* status_line, std::string* reason) { - Header header; - std::vector lines; - std::istringstream stream(headers); - { - std::string line; - while (std::getline(stream, line, '\n')) { - lines.push_back(line); - } - } - - for (std::string& line : lines) { - if (line.substr(0, 5) == "HTTP/") { - // set the status_line if it was given - if ((status_line != nullptr) || (reason != nullptr)) { - line.resize(std::min(line.size(), line.find_last_not_of("\t\n\r ") + 1)); - if (status_line != nullptr) { - *status_line = line; - } - - // set the reason if it was given - if (reason != nullptr) { - size_t pos1 = line.find_first_of("\t "); - size_t pos2 = std::string::npos; - if (pos1 != std::string::npos) { - pos2 = line.find_first_of("\t ", pos1 + 1); - } - if (pos2 != std::string::npos) { - line.erase(0, pos2 + 1); - *reason = line; - } - } - } - header.clear(); - } - - if (line.length() > 0) { - size_t found = line.find(":"); - if (found != std::string::npos) { - std::string value = line.substr(found + 1); - value.erase(0, value.find_first_not_of("\t ")); - value.resize(std::min(value.size(), value.find_last_not_of("\t\n\r ") + 1)); - header[line.substr(0, found)] = value; - } - } - } - - return header; -} - -std::vector split(const std::string& to_split, char delimiter) { - std::vector tokens; - - std::stringstream stream(to_split); - std::string item; - while (std::getline(stream, item, delimiter)) { - tokens.push_back(item); - } - - return tokens; -} - -size_t readUserFunction(char* ptr, size_t size, size_t nitems, const ReadCallback* read) { - size *= nitems; - return read->callback(ptr, size) ? size : CURL_READFUNC_ABORT; -} - -size_t headerUserFunction(char* ptr, size_t size, size_t nmemb, const HeaderCallback* header) { - size *= nmemb; - return header->callback({ptr, size}) ? size : 0; -} - -size_t writeFunction(char* ptr, size_t size, size_t nmemb, std::string* data) { - size *= nmemb; - data->append(ptr, size); - return size; -} - -size_t writeFileFunction(char* ptr, size_t size, size_t nmemb, std::ofstream* file) { - size *= nmemb; - file->write(ptr, size); - return size; -} - -size_t writeUserFunction(char* ptr, size_t size, size_t nmemb, const WriteCallback* write) { - size *= nmemb; - return write->callback({ptr, size}) ? size : 0; -} - -#if LIBCURL_VERSION_NUM < 0x072000 -int progressUserFunction(const ProgressCallback* progress, double dltotal, double dlnow, - double ultotal, double ulnow) { -#else -int progressUserFunction(const ProgressCallback* progress, curl_off_t dltotal, curl_off_t dlnow, - curl_off_t ultotal, curl_off_t ulnow) { -#endif - return progress->callback(dltotal, dlnow, ultotal, ulnow) ? 0 : 1; -} - -int debugUserFunction(CURL* handle, curl_infotype type, char* data, size_t size, - const DebugCallback* debug) { - debug->callback(DebugCallback::InfoType(type), std::string(data, size)); - return 0; -} - -/** - * Creates a temporary CurlHolder object and uses it to escape the given string. - * If you plan to use this methode on a regular basis think about creating a CurlHolder - * object and calling urlEncode(std::string) on it. - * - * Example: - * CurlHolder holder; - * std::string input = "Hello World!"; - * std::string result = holder.urlEncode(input); - **/ -std::string urlEncode(const std::string& s) { - CurlHolder holder; // Create a temporary new holder for URL encoding - return holder.urlEncode(s); -} - -/** - * Creates a temporary CurlHolder object and uses it to unescape the given string. - * If you plan to use this methode on a regular basis think about creating a CurlHolder - * object and calling urlDecode(std::string) on it. - * - * Example: - * CurlHolder holder; - * std::string input = "Hello%20World%21"; - * std::string result = holder.urlDecode(input); - **/ -std::string urlDecode(const std::string& s) { - CurlHolder holder; // Create a temporary new holder for URL decoding - return holder.urlDecode(s); -} - -} // namespace util -} // namespace cpr diff --git a/VCMP-LUA/modules/requests/premake5.lua b/VCMP-LUA/modules/requests/premake5.lua deleted file mode 100644 index fda5917..0000000 --- a/VCMP-LUA/modules/requests/premake5.lua +++ /dev/null @@ -1,28 +0,0 @@ -project "module-cpr" - kind "StaticLib" - language "C++" - cppdialect "C++17" - pic "On" - - targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") - objdir ("%{wks.location}/bin/interm/" .. outputdir .. "/%{prj.name}") - - files - { - "cpr/include/**.h", - "cpr/src/**.cpp", - } - - includedirs - { - "cpr/include" - } - - libdirs - { - "cpr/lib" - } - - defines "CURL_STATICLIB" - - links {"cpr.lib", "mongoose.lib", "libcurl.lib"} \ No newline at end of file diff --git a/VCMP-LUA/modules/sqlite3/module-sqlite3.make b/VCMP-LUA/modules/sqlite3/module-sqlite3.make deleted file mode 100644 index 6858dde..0000000 --- a/VCMP-LUA/modules/sqlite3/module-sqlite3.make +++ /dev/null @@ -1,138 +0,0 @@ -# GNU Make project makefile autogenerated by Premake - -ifndef config - config=release32 -endif - -ifndef verbose - SILENT = @ -endif - -.PHONY: clean prebuild prelink - -ifeq ($(config),release32) - RESCOMP = windres - TARGETDIR = ../../../bin/Release32-windows-x86/module-sqlite3 - TARGET = $(TARGETDIR)/module-sqlite3_x86.lib - OBJDIR = ../../../bin/interm/Release32-windows-x86/module-sqlite3 - DEFINES += -D_x32 - INCLUDES += - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += - LDDEPS += - ALL_LDFLAGS += $(LDFLAGS) -L/usr/lib32 -m32 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -ifeq ($(config),release) - RESCOMP = windres - TARGETDIR = ../../../bin/Release-windows-x86_64/module-sqlite3 - TARGET = $(TARGETDIR)/module-sqlite3_x64.lib - OBJDIR = ../../../bin/interm/Release-windows-x86_64/module-sqlite3 - DEFINES += - INCLUDES += - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += - LDDEPS += - ALL_LDFLAGS += $(LDFLAGS) -L/usr/lib64 -m64 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -OBJECTS := \ - $(OBJDIR)/shell.o \ - $(OBJDIR)/sqlite3.o \ - -RESOURCES := \ - -CUSTOMFILES := \ - -SHELLTYPE := posix -ifeq (.exe,$(findstring .exe,$(ComSpec))) - SHELLTYPE := msdos -endif - -$(TARGET): $(GCH) ${CUSTOMFILES} $(OBJECTS) $(LDDEPS) $(RESOURCES) | $(TARGETDIR) - @echo Linking module-sqlite3 - $(SILENT) $(LINKCMD) - $(POSTBUILDCMDS) - -$(CUSTOMFILES): | $(OBJDIR) - -$(TARGETDIR): - @echo Creating $(TARGETDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(TARGETDIR) -else - $(SILENT) mkdir $(subst /,\\,$(TARGETDIR)) -endif - -$(OBJDIR): - @echo Creating $(OBJDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(OBJDIR) -else - $(SILENT) mkdir $(subst /,\\,$(OBJDIR)) -endif - -clean: - @echo Cleaning module-sqlite3 -ifeq (posix,$(SHELLTYPE)) - $(SILENT) rm -f $(TARGET) - $(SILENT) rm -rf $(OBJDIR) -else - $(SILENT) if exist $(subst /,\\,$(TARGET)) del $(subst /,\\,$(TARGET)) - $(SILENT) if exist $(subst /,\\,$(OBJDIR)) rmdir /s /q $(subst /,\\,$(OBJDIR)) -endif - -prebuild: - $(PREBUILDCMDS) - -prelink: - $(PRELINKCMDS) - -ifneq (,$(PCH)) -$(OBJECTS): $(GCH) $(PCH) | $(OBJDIR) -$(GCH): $(PCH) | $(OBJDIR) - @echo $(notdir $<) - $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" -else -$(OBJECTS): | $(OBJDIR) -endif - -$(OBJDIR)/shell.o: sqlite3/shell.c - @echo $(notdir $<) - $(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/sqlite3.o: sqlite3/sqlite3.c - @echo $(notdir $<) - $(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" - --include $(OBJECTS:%.o=%.d) -ifneq (,$(PCH)) - -include $(OBJDIR)/$(notdir $(PCH)).d -endif \ No newline at end of file diff --git a/VCMP-LUA/modules/sqlite3/module-sqliteCpp.make b/VCMP-LUA/modules/sqlite3/module-sqliteCpp.make deleted file mode 100644 index 45389da..0000000 --- a/VCMP-LUA/modules/sqlite3/module-sqliteCpp.make +++ /dev/null @@ -1,154 +0,0 @@ -# GNU Make project makefile autogenerated by Premake - -ifndef config - config=release32 -endif - -ifndef verbose - SILENT = @ -endif - -.PHONY: clean prebuild prelink - -ifeq ($(config),release32) - RESCOMP = windres - TARGETDIR = ../../../bin/Release32-windows-x86/module-sqliteCpp - TARGET = $(TARGETDIR)/module-sqliteCpp_x86.lib - OBJDIR = ../../../bin/interm/Release32-windows-x86/module-sqliteCpp - DEFINES += -D_x32 - INCLUDES += -Isqlite3 -IsqliteCpp/include - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m32 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += ../../../bin/Release32-windows-x86/module-sqlite3/module-sqlite3_x86.lib - LDDEPS += ../../../bin/Release32-windows-x86/module-sqlite3/module-sqlite3_x86.lib - ALL_LDFLAGS += $(LDFLAGS) -L/usr/lib32 -m32 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -ifeq ($(config),release) - RESCOMP = windres - TARGETDIR = ../../../bin/Release-windows-x86_64/module-sqliteCpp - TARGET = $(TARGETDIR)/module-sqliteCpp_x64.lib - OBJDIR = ../../../bin/interm/Release-windows-x86_64/module-sqliteCpp - DEFINES += - INCLUDES += -Isqlite3 -IsqliteCpp/include - FORCE_INCLUDE += - ALL_CPPFLAGS += $(CPPFLAGS) -MMD -MP $(DEFINES) $(INCLUDES) - ALL_CFLAGS += $(CFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC - ALL_CXXFLAGS += $(CXXFLAGS) $(ALL_CPPFLAGS) -m64 -O2 -fPIC -std=c++17 - ALL_RESFLAGS += $(RESFLAGS) $(DEFINES) $(INCLUDES) - LIBS += ../../../bin/Release-windows-x86_64/module-sqlite3/module-sqlite3_x64.lib - LDDEPS += ../../../bin/Release-windows-x86_64/module-sqlite3/module-sqlite3_x64.lib - ALL_LDFLAGS += $(LDFLAGS) -L/usr/lib64 -m64 -s - LINKCMD = $(AR) -rcs "$@" $(OBJECTS) - define PREBUILDCMDS - endef - define PRELINKCMDS - endef - define POSTBUILDCMDS - endef -all: prebuild prelink $(TARGET) - @: - -endif - -OBJECTS := \ - $(OBJDIR)/Backup.o \ - $(OBJDIR)/Column.o \ - $(OBJDIR)/Database.o \ - $(OBJDIR)/Exception.o \ - $(OBJDIR)/Statement.o \ - $(OBJDIR)/Transaction.o \ - -RESOURCES := \ - -CUSTOMFILES := \ - -SHELLTYPE := posix -ifeq (.exe,$(findstring .exe,$(ComSpec))) - SHELLTYPE := msdos -endif - -$(TARGET): $(GCH) ${CUSTOMFILES} $(OBJECTS) $(LDDEPS) $(RESOURCES) | $(TARGETDIR) - @echo Linking module-sqliteCpp - $(SILENT) $(LINKCMD) - $(POSTBUILDCMDS) - -$(CUSTOMFILES): | $(OBJDIR) - -$(TARGETDIR): - @echo Creating $(TARGETDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(TARGETDIR) -else - $(SILENT) mkdir $(subst /,\\,$(TARGETDIR)) -endif - -$(OBJDIR): - @echo Creating $(OBJDIR) -ifeq (posix,$(SHELLTYPE)) - $(SILENT) mkdir -p $(OBJDIR) -else - $(SILENT) mkdir $(subst /,\\,$(OBJDIR)) -endif - -clean: - @echo Cleaning module-sqliteCpp -ifeq (posix,$(SHELLTYPE)) - $(SILENT) rm -f $(TARGET) - $(SILENT) rm -rf $(OBJDIR) -else - $(SILENT) if exist $(subst /,\\,$(TARGET)) del $(subst /,\\,$(TARGET)) - $(SILENT) if exist $(subst /,\\,$(OBJDIR)) rmdir /s /q $(subst /,\\,$(OBJDIR)) -endif - -prebuild: - $(PREBUILDCMDS) - -prelink: - $(PRELINKCMDS) - -ifneq (,$(PCH)) -$(OBJECTS): $(GCH) $(PCH) | $(OBJDIR) -$(GCH): $(PCH) | $(OBJDIR) - @echo $(notdir $<) - $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" -else -$(OBJECTS): | $(OBJDIR) -endif - -$(OBJDIR)/Backup.o: sqliteCpp/src/Backup.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Column.o: sqliteCpp/src/Column.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Database.o: sqliteCpp/src/Database.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Exception.o: sqliteCpp/src/Exception.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Statement.o: sqliteCpp/src/Statement.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" -$(OBJDIR)/Transaction.o: sqliteCpp/src/Transaction.cpp - @echo $(notdir $<) - $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" - --include $(OBJECTS:%.o=%.d) -ifneq (,$(PCH)) - -include $(OBJDIR)/$(notdir $(PCH)).d -endif \ No newline at end of file diff --git a/VCMP-LUA/modules/sqlite3/premake5.lua b/VCMP-LUA/modules/sqlite3/premake5.lua deleted file mode 100644 index cc5d0bb..0000000 --- a/VCMP-LUA/modules/sqlite3/premake5.lua +++ /dev/null @@ -1,37 +0,0 @@ -project "module-sqlite3" - kind "StaticLib" - language "C++" - cppdialect "C++17" - pic "On" - - targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") - objdir ("%{wks.location}/bin/interm/" .. outputdir .. "/%{prj.name}") - - files - { - "sqlite3/**.h", - "sqlite3/**.c", - } - -project "module-sqliteCpp" - kind "StaticLib" - language "C++" - cppdialect "C++17" - pic "On" - - targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") - objdir ("%{wks.location}/bin/interm/" .. outputdir .. "/%{prj.name}") - - files - { - "sqliteCpp/**.h", - "sqliteCpp/**.cpp", - } - - includedirs - { - "sqlite3", - "sqliteCpp/include", - } - - links {"module-sqlite3"} \ No newline at end of file diff --git a/VCMP-LUA/modules/sqlite3/sqlite3/shell.c b/VCMP-LUA/modules/sqlite3/sqlite3/shell.c deleted file mode 100644 index a1a77e4..0000000 --- a/VCMP-LUA/modules/sqlite3/sqlite3/shell.c +++ /dev/null @@ -1,20838 +0,0 @@ -/* DO NOT EDIT! -** This file is automatically generated by the script in the canonical -** SQLite source tree at tool/mkshellc.tcl. That script combines source -** code from various constituent source files of SQLite into this single -** "shell.c" file used to implement the SQLite command-line shell. -** -** Most of the code found below comes from the "src/shell.c.in" file in -** the canonical SQLite source tree. That main file contains "INCLUDE" -** lines that specify other files in the canonical source tree that are -** inserted to getnerate this complete program source file. -** -** The code from multiple files is combined into this single "shell.c" -** source file to help make the command-line program easier to compile. -** -** To modify this program, get a copy of the canonical SQLite source tree, -** edit the src/shell.c.in" and/or some of the other files that are included -** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script. -*/ -/* -** 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 the "sqlite" command line -** utility for accessing SQLite databases. -*/ -#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) -/* This needs to come before any includes for MSVC compiler */ -#define _CRT_SECURE_NO_WARNINGS -#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 - -/* -** Warning pragmas copied from msvc.h in the core. -*/ -#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) */ - -/* -** No support for loadable extensions in VxWorks. -*/ -#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION -# define SQLITE_OMIT_LOAD_EXTENSION 1 -#endif - -/* -** Enable large-file support for fopen() and friends on unix. -*/ -#ifndef SQLITE_DISABLE_LFS -# define _LARGE_FILE 1 -# ifndef _FILE_OFFSET_BITS -# define _FILE_OFFSET_BITS 64 -# endif -# define _LARGEFILE_SOURCE 1 -#endif - -#include -#include -#include -#include -#include "sqlite3.h" -typedef sqlite3_int64 i64; -typedef sqlite3_uint64 u64; -typedef unsigned char u8; -#if SQLITE_USER_AUTHENTICATION -# include "sqlite3userauth.h" -#endif -#include -#include - -#if !defined(_WIN32) && !defined(WIN32) -# include -# if !defined(__RTP__) && !defined(_WRS_KERNEL) -# include -# endif -#endif -#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) -# include -# include -# define GETPID getpid -# if defined(__MINGW32__) -# define DIRENT dirent -# ifndef S_ISLNK -# define S_ISLNK(mode) (0) -# endif -# endif -#else -# define GETPID (int)GetCurrentProcessId -#endif -#include -#include - -#if HAVE_READLINE -# include -# include -#endif - -#if HAVE_EDITLINE -# include -#endif - -#if HAVE_EDITLINE || HAVE_READLINE - -# define shell_add_history(X) add_history(X) -# define shell_read_history(X) read_history(X) -# define shell_write_history(X) write_history(X) -# define shell_stifle_history(X) stifle_history(X) -# define shell_readline(X) readline(X) - -#elif HAVE_LINENOISE - -# include "linenoise.h" -# define shell_add_history(X) linenoiseHistoryAdd(X) -# define shell_read_history(X) linenoiseHistoryLoad(X) -# define shell_write_history(X) linenoiseHistorySave(X) -# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) -# define shell_readline(X) linenoise(X) - -#else - -# define shell_read_history(X) -# define shell_write_history(X) -# define shell_stifle_history(X) - -# define SHELL_USE_LOCAL_GETLINE 1 -#endif - - -#if defined(_WIN32) || defined(WIN32) -# if SQLITE_OS_WINRT -# define SQLITE_OMIT_POPEN 1 -# else -# include -# include -# define isatty(h) _isatty(h) -# ifndef access -# define access(f,m) _access((f),(m)) -# endif -# ifndef unlink -# define unlink _unlink -# endif -# ifndef strdup -# define strdup _strdup -# endif -# undef popen -# define popen _popen -# undef pclose -# define pclose _pclose -# endif -#else - /* Make sure isatty() has a prototype. */ - extern int isatty(int); - -# if !defined(__RTP__) && !defined(_WRS_KERNEL) - /* popen and pclose are not C89 functions and so are - ** sometimes omitted from the header */ - extern FILE *popen(const char*,const char*); - extern int pclose(FILE*); -# else -# define SQLITE_OMIT_POPEN 1 -# endif -#endif - -#if defined(_WIN32_WCE) -/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() - * thus we always assume that we have a console. That can be - * overridden with the -batch command line option. - */ -#define isatty(x) 1 -#endif - -/* ctype macros that work with signed characters */ -#define IsSpace(X) isspace((unsigned char)X) -#define IsDigit(X) isdigit((unsigned char)X) -#define ToLower(X) (char)tolower((unsigned char)X) - -#if defined(_WIN32) || defined(WIN32) -#if SQLITE_OS_WINRT -#include -#endif -#include - -/* string conversion routines only needed on Win32 */ -extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); -extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); -extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); -extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); -#endif - -/* On Windows, we normally run with output mode of TEXT so that \n characters -** are automatically translated into \r\n. However, this behavior needs -** to be disabled in some cases (ex: when generating CSV output and when -** rendering quoted strings that contain \n characters). The following -** routines take care of that. -*/ -#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT -static void setBinaryMode(FILE *file, int isOutput){ - if( isOutput ) fflush(file); - _setmode(_fileno(file), _O_BINARY); -} -static void setTextMode(FILE *file, int isOutput){ - if( isOutput ) fflush(file); - _setmode(_fileno(file), _O_TEXT); -} -#else -# define setBinaryMode(X,Y) -# define setTextMode(X,Y) -#endif - - -/* True if the timer is enabled */ -static int enableTimer = 0; - -/* Return the current wall-clock time */ -static sqlite3_int64 timeOfDay(void){ - static sqlite3_vfs *clockVfs = 0; - sqlite3_int64 t; - if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); - if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ - clockVfs->xCurrentTimeInt64(clockVfs, &t); - }else{ - double r; - clockVfs->xCurrentTime(clockVfs, &r); - t = (sqlite3_int64)(r*86400000.0); - } - return t; -} - -#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) -#include -#include - -/* VxWorks does not support getrusage() as far as we can determine */ -#if defined(_WRS_KERNEL) || defined(__RTP__) -struct rusage { - struct timeval ru_utime; /* user CPU time used */ - struct timeval ru_stime; /* system CPU time used */ -}; -#define getrusage(A,B) memset(B,0,sizeof(*B)) -#endif - -/* Saved resource information for the beginning of an operation */ -static struct rusage sBegin; /* CPU time at start */ -static sqlite3_int64 iBegin; /* Wall-clock time at start */ - -/* -** Begin timing an operation -*/ -static void beginTimer(void){ - if( enableTimer ){ - getrusage(RUSAGE_SELF, &sBegin); - iBegin = timeOfDay(); - } -} - -/* Return the difference of two time_structs in seconds */ -static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ - return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + - (double)(pEnd->tv_sec - pStart->tv_sec); -} - -/* -** Print the timing results. -*/ -static void endTimer(void){ - if( enableTimer ){ - sqlite3_int64 iEnd = timeOfDay(); - struct rusage sEnd; - getrusage(RUSAGE_SELF, &sEnd); - printf("Run Time: real %.3f user %f sys %f\n", - (iEnd - iBegin)*0.001, - timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), - timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); - } -} - -#define BEGIN_TIMER beginTimer() -#define END_TIMER endTimer() -#define HAS_TIMER 1 - -#elif (defined(_WIN32) || defined(WIN32)) - -/* Saved resource information for the beginning of an operation */ -static HANDLE hProcess; -static FILETIME ftKernelBegin; -static FILETIME ftUserBegin; -static sqlite3_int64 ftWallBegin; -typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, - LPFILETIME, LPFILETIME); -static GETPROCTIMES getProcessTimesAddr = NULL; - -/* -** Check to see if we have timer support. Return 1 if necessary -** support found (or found previously). -*/ -static int hasTimer(void){ - if( getProcessTimesAddr ){ - return 1; - } else { -#if !SQLITE_OS_WINRT - /* GetProcessTimes() isn't supported in WIN95 and some other Windows - ** versions. See if the version we are running on has it, and if it - ** does, save off a pointer to it and the current process handle. - */ - hProcess = GetCurrentProcess(); - if( hProcess ){ - HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); - if( NULL != hinstLib ){ - getProcessTimesAddr = - (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); - if( NULL != getProcessTimesAddr ){ - return 1; - } - FreeLibrary(hinstLib); - } - } -#endif - } - return 0; -} - -/* -** Begin timing an operation -*/ -static void beginTimer(void){ - if( enableTimer && getProcessTimesAddr ){ - FILETIME ftCreation, ftExit; - getProcessTimesAddr(hProcess,&ftCreation,&ftExit, - &ftKernelBegin,&ftUserBegin); - ftWallBegin = timeOfDay(); - } -} - -/* Return the difference of two FILETIME structs in seconds */ -static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ - sqlite_int64 i64Start = *((sqlite_int64 *) pStart); - sqlite_int64 i64End = *((sqlite_int64 *) pEnd); - return (double) ((i64End - i64Start) / 10000000.0); -} - -/* -** Print the timing results. -*/ -static void endTimer(void){ - if( enableTimer && getProcessTimesAddr){ - FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; - sqlite3_int64 ftWallEnd = timeOfDay(); - getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); - printf("Run Time: real %.3f user %f sys %f\n", - (ftWallEnd - ftWallBegin)*0.001, - timeDiff(&ftUserBegin, &ftUserEnd), - timeDiff(&ftKernelBegin, &ftKernelEnd)); - } -} - -#define BEGIN_TIMER beginTimer() -#define END_TIMER endTimer() -#define HAS_TIMER hasTimer() - -#else -#define BEGIN_TIMER -#define END_TIMER -#define HAS_TIMER 0 -#endif - -/* -** Used to prevent warnings about unused parameters -*/ -#define UNUSED_PARAMETER(x) (void)(x) - -/* -** Number of elements in an array -*/ -#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) - -/* -** If the following flag is set, then command execution stops -** at an error if we are not interactive. -*/ -static int bail_on_error = 0; - -/* -** Threat stdin as an interactive input if the following variable -** is true. Otherwise, assume stdin is connected to a file or pipe. -*/ -static int stdin_is_interactive = 1; - -/* -** On Windows systems we have to know if standard output is a console -** in order to translate UTF-8 into MBCS. The following variable is -** true if translation is required. -*/ -static int stdout_is_console = 1; - -/* -** The following is the open SQLite database. We make a pointer -** to this database a static variable so that it can be accessed -** by the SIGINT handler to interrupt database processing. -*/ -static sqlite3 *globalDb = 0; - -/* -** True if an interrupt (Control-C) has been received. -*/ -static volatile int seenInterrupt = 0; - -#ifdef SQLITE_DEBUG -/* -** Out-of-memory simulator variables -*/ -static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */ -static unsigned int oomRepeat = 0; /* Number of OOMs in a row */ -static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */ -#endif /* SQLITE_DEBUG */ - -/* -** This is the name of our program. It is set in main(), used -** in a number of other places, mostly for error messages. -*/ -static char *Argv0; - -/* -** Prompt strings. Initialized in main. Settable with -** .prompt main continue -*/ -static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ -static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ - -/* -** Render output like fprintf(). Except, if the output is going to the -** console and if this is running on a Windows machine, translate the -** output from UTF-8 into MBCS. -*/ -#if defined(_WIN32) || defined(WIN32) -void utf8_printf(FILE *out, const char *zFormat, ...){ - va_list ap; - va_start(ap, zFormat); - if( stdout_is_console && (out==stdout || out==stderr) ){ - char *z1 = sqlite3_vmprintf(zFormat, ap); - char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); - sqlite3_free(z1); - fputs(z2, out); - sqlite3_free(z2); - }else{ - vfprintf(out, zFormat, ap); - } - va_end(ap); -} -#elif !defined(utf8_printf) -# define utf8_printf fprintf -#endif - -/* -** Render output like fprintf(). This should not be used on anything that -** includes string formatting (e.g. "%s"). -*/ -#if !defined(raw_printf) -# define raw_printf fprintf -#endif - -/* Indicate out-of-memory and exit. */ -static void shell_out_of_memory(void){ - raw_printf(stderr,"Error: out of memory\n"); - exit(1); -} - -#ifdef SQLITE_DEBUG -/* This routine is called when a simulated OOM occurs. It is broken -** out as a separate routine to make it easy to set a breakpoint on -** the OOM -*/ -void shellOomFault(void){ - if( oomRepeat>0 ){ - oomRepeat--; - }else{ - oomCounter--; - } -} -#endif /* SQLITE_DEBUG */ - -#ifdef SQLITE_DEBUG -/* This routine is a replacement malloc() that is used to simulate -** Out-Of-Memory (OOM) errors for testing purposes. -*/ -static void *oomMalloc(int nByte){ - if( oomCounter ){ - if( oomCounter==1 ){ - shellOomFault(); - return 0; - }else{ - oomCounter--; - } - } - return defaultMalloc(nByte); -} -#endif /* SQLITE_DEBUG */ - -#ifdef SQLITE_DEBUG -/* Register the OOM simulator. This must occur before any memory -** allocations */ -static void registerOomSimulator(void){ - sqlite3_mem_methods mem; - sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem); - defaultMalloc = mem.xMalloc; - mem.xMalloc = oomMalloc; - sqlite3_config(SQLITE_CONFIG_MALLOC, &mem); -} -#endif - -/* -** Write I/O traces to the following stream. -*/ -#ifdef SQLITE_ENABLE_IOTRACE -static FILE *iotrace = 0; -#endif - -/* -** This routine works like printf in that its first argument is a -** format string and subsequent arguments are values to be substituted -** in place of % fields. The result of formatting this string -** is written to iotrace. -*/ -#ifdef SQLITE_ENABLE_IOTRACE -static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ - va_list ap; - char *z; - if( iotrace==0 ) return; - va_start(ap, zFormat); - z = sqlite3_vmprintf(zFormat, ap); - va_end(ap); - utf8_printf(iotrace, "%s", z); - sqlite3_free(z); -} -#endif - -/* -** Output string zUtf to stream pOut as w characters. If w is negative, -** then right-justify the text. W is the width in UTF-8 characters, not -** in bytes. This is different from the %*.*s specification in printf -** since with %*.*s the width is measured in bytes, not characters. -*/ -static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ - int i; - int n; - int aw = w<0 ? -w : w; - char zBuf[1000]; - if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3; - for(i=n=0; zUtf[i]; i++){ - if( (zUtf[i]&0xc0)!=0x80 ){ - n++; - if( n==aw ){ - do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); - break; - } - } - } - if( n>=aw ){ - utf8_printf(pOut, "%.*s", i, zUtf); - }else if( w<0 ){ - utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); - }else{ - utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); - } -} - - -/* -** Determines if a string is a number of not. -*/ -static int isNumber(const char *z, int *realnum){ - if( *z=='-' || *z=='+' ) z++; - if( !IsDigit(*z) ){ - return 0; - } - z++; - if( realnum ) *realnum = 0; - while( IsDigit(*z) ){ z++; } - if( *z=='.' ){ - z++; - if( !IsDigit(*z) ) return 0; - while( IsDigit(*z) ){ z++; } - if( realnum ) *realnum = 1; - } - if( *z=='e' || *z=='E' ){ - z++; - if( *z=='+' || *z=='-' ) z++; - if( !IsDigit(*z) ) return 0; - while( IsDigit(*z) ){ z++; } - if( realnum ) *realnum = 1; - } - return *z==0; -} - -/* -** Compute a string length that is limited to what can be stored in -** lower 30 bits of a 32-bit signed integer. -*/ -static int strlen30(const char *z){ - const char *z2 = z; - while( *z2 ){ z2++; } - return 0x3fffffff & (int)(z2 - z); -} - -/* -** Return the length of a string in characters. Multibyte UTF8 characters -** count as a single character. -*/ -static int strlenChar(const char *z){ - int n = 0; - while( *z ){ - if( (0xc0&*(z++))!=0x80 ) n++; - } - return n; -} - -/* -** Return true if zFile does not exist or if it is not an ordinary file. -*/ -#ifdef _WIN32 -# define notNormalFile(X) 0 -#else -static int notNormalFile(const char *zFile){ - struct stat x; - int rc; - memset(&x, 0, sizeof(x)); - rc = stat(zFile, &x); - return rc || !S_ISREG(x.st_mode); -} -#endif - -/* -** This routine reads a line of text from FILE in, stores -** the text in memory obtained from malloc() and returns a pointer -** to the text. NULL is returned at end of file, or if malloc() -** fails. -** -** If zLine is not NULL then it is a malloced buffer returned from -** a previous call to this routine that may be reused. -*/ -static char *local_getline(char *zLine, FILE *in){ - int nLine = zLine==0 ? 0 : 100; - int n = 0; - - while( 1 ){ - if( n+100>nLine ){ - nLine = nLine*2 + 100; - zLine = realloc(zLine, nLine); - if( zLine==0 ) shell_out_of_memory(); - } - if( fgets(&zLine[n], nLine - n, in)==0 ){ - if( n==0 ){ - free(zLine); - return 0; - } - zLine[n] = 0; - break; - } - while( zLine[n] ) n++; - if( n>0 && zLine[n-1]=='\n' ){ - n--; - if( n>0 && zLine[n-1]=='\r' ) n--; - zLine[n] = 0; - break; - } - } -#if defined(_WIN32) || defined(WIN32) - /* For interactive input on Windows systems, translate the - ** multi-byte characterset characters into UTF-8. */ - if( stdin_is_interactive && in==stdin ){ - char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); - if( zTrans ){ - int nTrans = strlen30(zTrans)+1; - if( nTrans>nLine ){ - zLine = realloc(zLine, nTrans); - if( zLine==0 ) shell_out_of_memory(); - } - memcpy(zLine, zTrans, nTrans); - sqlite3_free(zTrans); - } - } -#endif /* defined(_WIN32) || defined(WIN32) */ - return zLine; -} - -/* -** Retrieve a single line of input text. -** -** If in==0 then read from standard input and prompt before each line. -** If isContinuation is true, then a continuation prompt is appropriate. -** If isContinuation is zero, then the main prompt should be used. -** -** If zPrior is not NULL then it is a buffer from a prior call to this -** routine that can be reused. -** -** The result is stored in space obtained from malloc() and must either -** be freed by the caller or else passed back into this routine via the -** zPrior argument for reuse. -*/ -static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ - char *zPrompt; - char *zResult; - if( in!=0 ){ - zResult = local_getline(zPrior, in); - }else{ - zPrompt = isContinuation ? continuePrompt : mainPrompt; -#if SHELL_USE_LOCAL_GETLINE - printf("%s", zPrompt); - fflush(stdout); - zResult = local_getline(zPrior, stdin); -#else - free(zPrior); - zResult = shell_readline(zPrompt); - if( zResult && *zResult ) shell_add_history(zResult); -#endif - } - return zResult; -} - - -/* -** Return the value of a hexadecimal digit. Return -1 if the input -** is not a hex digit. -*/ -static int hexDigitValue(char c){ - if( c>='0' && c<='9' ) return c - '0'; - if( c>='a' && c<='f' ) return c - 'a' + 10; - if( c>='A' && c<='F' ) return c - 'A' + 10; - return -1; -} - -/* -** Interpret zArg as an integer value, possibly with suffixes. -*/ -static sqlite3_int64 integerValue(const char *zArg){ - sqlite3_int64 v = 0; - static const struct { char *zSuffix; int iMult; } aMult[] = { - { "KiB", 1024 }, - { "MiB", 1024*1024 }, - { "GiB", 1024*1024*1024 }, - { "KB", 1000 }, - { "MB", 1000000 }, - { "GB", 1000000000 }, - { "K", 1000 }, - { "M", 1000000 }, - { "G", 1000000000 }, - }; - int i; - int isNeg = 0; - if( zArg[0]=='-' ){ - isNeg = 1; - zArg++; - }else if( zArg[0]=='+' ){ - zArg++; - } - if( zArg[0]=='0' && zArg[1]=='x' ){ - int x; - zArg += 2; - while( (x = hexDigitValue(zArg[0]))>=0 ){ - v = (v<<4) + x; - zArg++; - } - }else{ - while( IsDigit(zArg[0]) ){ - v = v*10 + zArg[0] - '0'; - zArg++; - } - } - for(i=0; iz); - initText(p); -} - -/* zIn is either a pointer to a NULL-terminated string in memory obtained -** from malloc(), or a NULL pointer. The string pointed to by zAppend is -** added to zIn, and the result returned in memory obtained from malloc(). -** zIn, if it was not NULL, is freed. -** -** If the third argument, quote, is not '\0', then it is used as a -** quote character for zAppend. -*/ -static void appendText(ShellText *p, char const *zAppend, char quote){ - int len; - int i; - int nAppend = strlen30(zAppend); - - len = nAppend+p->n+1; - if( quote ){ - len += 2; - for(i=0; in+len>=p->nAlloc ){ - p->nAlloc = p->nAlloc*2 + len + 20; - p->z = realloc(p->z, p->nAlloc); - if( p->z==0 ) shell_out_of_memory(); - } - - if( quote ){ - char *zCsr = p->z+p->n; - *zCsr++ = quote; - for(i=0; in = (int)(zCsr - p->z); - *zCsr = '\0'; - }else{ - memcpy(p->z+p->n, zAppend, nAppend); - p->n += nAppend; - p->z[p->n] = '\0'; - } -} - -/* -** Attempt to determine if identifier zName needs to be quoted, either -** because it contains non-alphanumeric characters, or because it is an -** SQLite keyword. Be conservative in this estimate: When in doubt assume -** that quoting is required. -** -** Return '"' if quoting is required. Return 0 if no quoting is required. -*/ -static char quoteChar(const char *zName){ - int i; - if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; - for(i=0; zName[i]; i++){ - if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; - } - return sqlite3_keyword_check(zName, i) ? '"' : 0; -} - -/* -** Construct a fake object name and column list to describe the structure -** of the view, virtual table, or table valued function zSchema.zName. -*/ -static char *shellFakeSchema( - sqlite3 *db, /* The database connection containing the vtab */ - const char *zSchema, /* Schema of the database holding the vtab */ - const char *zName /* The name of the virtual table */ -){ - sqlite3_stmt *pStmt = 0; - char *zSql; - ShellText s; - char cQuote; - char *zDiv = "("; - int nRow = 0; - - zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", - zSchema ? zSchema : "main", zName); - sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - initText(&s); - if( zSchema ){ - cQuote = quoteChar(zSchema); - if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; - appendText(&s, zSchema, cQuote); - appendText(&s, ".", 0); - } - cQuote = quoteChar(zName); - appendText(&s, zName, cQuote); - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); - nRow++; - appendText(&s, zDiv, 0); - zDiv = ","; - cQuote = quoteChar(zCol); - appendText(&s, zCol, cQuote); - } - appendText(&s, ")", 0); - sqlite3_finalize(pStmt); - if( nRow==0 ){ - freeText(&s); - s.z = 0; - } - return s.z; -} - -/* -** SQL function: shell_module_schema(X) -** -** Return a fake schema for the table-valued function or eponymous virtual -** table X. -*/ -static void shellModuleSchema( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - const char *zName = (const char*)sqlite3_value_text(apVal[0]); - char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName); - UNUSED_PARAMETER(nVal); - if( zFake ){ - sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), - -1, sqlite3_free); - free(zFake); - } -} - -/* -** SQL function: shell_add_schema(S,X) -** -** Add the schema name X to the CREATE statement in S and return the result. -** Examples: -** -** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); -** -** Also works on -** -** CREATE INDEX -** CREATE UNIQUE INDEX -** CREATE VIEW -** CREATE TRIGGER -** CREATE VIRTUAL TABLE -** -** This UDF is used by the .schema command to insert the schema name of -** attached databases into the middle of the sqlite_schema.sql field. -*/ -static void shellAddSchemaName( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - static const char *aPrefix[] = { - "TABLE", - "INDEX", - "UNIQUE INDEX", - "VIEW", - "TRIGGER", - "VIRTUAL TABLE" - }; - int i = 0; - const char *zIn = (const char*)sqlite3_value_text(apVal[0]); - const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); - const char *zName = (const char*)sqlite3_value_text(apVal[2]); - sqlite3 *db = sqlite3_context_db_handle(pCtx); - UNUSED_PARAMETER(nVal); - if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ - for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){ - int n = strlen30(aPrefix[i]); - if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ - char *z = 0; - char *zFake = 0; - if( zSchema ){ - char cQuote = quoteChar(zSchema); - if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ - z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); - }else{ - z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); - } - } - if( zName - && aPrefix[i][0]=='V' - && (zFake = shellFakeSchema(db, zSchema, zName))!=0 - ){ - if( z==0 ){ - z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); - }else{ - z = sqlite3_mprintf("%z\n/* %s */", z, zFake); - } - free(zFake); - } - if( z ){ - sqlite3_result_text(pCtx, z, -1, sqlite3_free); - return; - } - } - } - } - sqlite3_result_value(pCtx, apVal[0]); -} - -/* -** The source code for several run-time loadable extensions is inserted -** below by the ../tool/mkshellc.tcl script. Before processing that included -** code, we need to override some macros to make the included program code -** work here in the middle of this regular program. -*/ -#define SQLITE_EXTENSION_INIT1 -#define SQLITE_EXTENSION_INIT2(X) (void)(X) - -#if defined(_WIN32) && defined(_MSC_VER) -/************************* Begin test_windirent.h ******************/ -/* -** 2015 November 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. -** -************************************************************************* -** This file contains declarations for most of the opendir() family of -** POSIX functions on Win32 using the MSVCRT. -*/ - -#if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H) -#define SQLITE_WINDIRENT_H - -/* -** We need several data types from the Windows SDK header. -*/ - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -#include "windows.h" - -/* -** We need several support functions from the SQLite core. -*/ - -/* #include "sqlite3.h" */ - -/* -** We need several things from the ANSI and MSVCRT headers. -*/ - -#include -#include -#include -#include -#include -#include -#include - -/* -** We may need several defines that should have been in "sys/stat.h". -*/ - -#ifndef S_ISREG -#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) -#endif - -#ifndef S_ISDIR -#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) -#endif - -#ifndef S_ISLNK -#define S_ISLNK(mode) (0) -#endif - -/* -** We may need to provide the "mode_t" type. -*/ - -#ifndef MODE_T_DEFINED - #define MODE_T_DEFINED - typedef unsigned short mode_t; -#endif - -/* -** We may need to provide the "ino_t" type. -*/ - -#ifndef INO_T_DEFINED - #define INO_T_DEFINED - typedef unsigned short ino_t; -#endif - -/* -** We need to define "NAME_MAX" if it was not present in "limits.h". -*/ - -#ifndef NAME_MAX -# ifdef FILENAME_MAX -# define NAME_MAX (FILENAME_MAX) -# else -# define NAME_MAX (260) -# endif -#endif - -/* -** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T". -*/ - -#ifndef NULL_INTPTR_T -# define NULL_INTPTR_T ((intptr_t)(0)) -#endif - -#ifndef BAD_INTPTR_T -# define BAD_INTPTR_T ((intptr_t)(-1)) -#endif - -/* -** We need to provide the necessary structures and related types. -*/ - -#ifndef DIRENT_DEFINED -#define DIRENT_DEFINED -typedef struct DIRENT DIRENT; -typedef DIRENT *LPDIRENT; -struct DIRENT { - ino_t d_ino; /* Sequence number, do not use. */ - unsigned d_attributes; /* Win32 file attributes. */ - char d_name[NAME_MAX + 1]; /* Name within the directory. */ -}; -#endif - -#ifndef DIR_DEFINED -#define DIR_DEFINED -typedef struct DIR DIR; -typedef DIR *LPDIR; -struct DIR { - intptr_t d_handle; /* Value returned by "_findfirst". */ - DIRENT d_first; /* DIRENT constructed based on "_findfirst". */ - DIRENT d_next; /* DIRENT constructed based on "_findnext". */ -}; -#endif - -/* -** Provide a macro, for use by the implementation, to determine if a -** particular directory entry should be skipped over when searching for -** the next directory entry that should be returned by the readdir() or -** readdir_r() functions. -*/ - -#ifndef is_filtered -# define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM)) -#endif - -/* -** Provide the function prototype for the POSIX compatiable getenv() -** function. This function is not thread-safe. -*/ - -extern const char *windirent_getenv(const char *name); - -/* -** Finally, we can provide the function prototypes for the opendir(), -** readdir(), readdir_r(), and closedir() POSIX functions. -*/ - -extern LPDIR opendir(const char *dirname); -extern LPDIRENT readdir(LPDIR dirp); -extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result); -extern INT closedir(LPDIR dirp); - -#endif /* defined(WIN32) && defined(_MSC_VER) */ - -/************************* End test_windirent.h ********************/ -/************************* Begin test_windirent.c ******************/ -/* -** 2015 November 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. -** -************************************************************************* -** This file contains code to implement most of the opendir() family of -** POSIX functions on Win32 using the MSVCRT. -*/ - -#if defined(_WIN32) && defined(_MSC_VER) -/* #include "test_windirent.h" */ - -/* -** Implementation of the POSIX getenv() function using the Win32 API. -** This function is not thread-safe. -*/ -const char *windirent_getenv( - const char *name -){ - static char value[32768]; /* Maximum length, per MSDN */ - DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */ - DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */ - - memset(value, 0, sizeof(value)); - dwRet = GetEnvironmentVariableA(name, value, dwSize); - if( dwRet==0 || dwRet>dwSize ){ - /* - ** The function call to GetEnvironmentVariableA() failed -OR- - ** the buffer is not large enough. Either way, return NULL. - */ - return 0; - }else{ - /* - ** The function call to GetEnvironmentVariableA() succeeded - ** -AND- the buffer contains the entire value. - */ - return value; - } -} - -/* -** Implementation of the POSIX opendir() function using the MSVCRT. -*/ -LPDIR opendir( - const char *dirname -){ - struct _finddata_t data; - LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR)); - SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]); - - if( dirp==NULL ) return NULL; - memset(dirp, 0, sizeof(DIR)); - - /* TODO: Remove this if Unix-style root paths are not used. */ - if( sqlite3_stricmp(dirname, "/")==0 ){ - dirname = windirent_getenv("SystemDrive"); - } - - memset(&data, 0, sizeof(struct _finddata_t)); - _snprintf(data.name, namesize, "%s\\*", dirname); - dirp->d_handle = _findfirst(data.name, &data); - - if( dirp->d_handle==BAD_INTPTR_T ){ - closedir(dirp); - return NULL; - } - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ){ -next: - - memset(&data, 0, sizeof(struct _finddata_t)); - if( _findnext(dirp->d_handle, &data)==-1 ){ - closedir(dirp); - return NULL; - } - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ) goto next; - } - - dirp->d_first.d_attributes = data.attrib; - strncpy(dirp->d_first.d_name, data.name, NAME_MAX); - dirp->d_first.d_name[NAME_MAX] = '\0'; - - return dirp; -} - -/* -** Implementation of the POSIX readdir() function using the MSVCRT. -*/ -LPDIRENT readdir( - LPDIR dirp -){ - struct _finddata_t data; - - if( dirp==NULL ) return NULL; - - if( dirp->d_first.d_ino==0 ){ - dirp->d_first.d_ino++; - dirp->d_next.d_ino++; - - return &dirp->d_first; - } - -next: - - memset(&data, 0, sizeof(struct _finddata_t)); - if( _findnext(dirp->d_handle, &data)==-1 ) return NULL; - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ) goto next; - - dirp->d_next.d_ino++; - dirp->d_next.d_attributes = data.attrib; - strncpy(dirp->d_next.d_name, data.name, NAME_MAX); - dirp->d_next.d_name[NAME_MAX] = '\0'; - - return &dirp->d_next; -} - -/* -** Implementation of the POSIX readdir_r() function using the MSVCRT. -*/ -INT readdir_r( - LPDIR dirp, - LPDIRENT entry, - LPDIRENT *result -){ - struct _finddata_t data; - - if( dirp==NULL ) return EBADF; - - if( dirp->d_first.d_ino==0 ){ - dirp->d_first.d_ino++; - dirp->d_next.d_ino++; - - entry->d_ino = dirp->d_first.d_ino; - entry->d_attributes = dirp->d_first.d_attributes; - strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX); - entry->d_name[NAME_MAX] = '\0'; - - *result = entry; - return 0; - } - -next: - - memset(&data, 0, sizeof(struct _finddata_t)); - if( _findnext(dirp->d_handle, &data)==-1 ){ - *result = NULL; - return ENOENT; - } - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ) goto next; - - entry->d_ino = (ino_t)-1; /* not available */ - entry->d_attributes = data.attrib; - strncpy(entry->d_name, data.name, NAME_MAX); - entry->d_name[NAME_MAX] = '\0'; - - *result = entry; - return 0; -} - -/* -** Implementation of the POSIX closedir() function using the MSVCRT. -*/ -INT closedir( - LPDIR dirp -){ - INT result = 0; - - if( dirp==NULL ) return EINVAL; - - if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){ - result = _findclose(dirp->d_handle); - } - - sqlite3_free(dirp); - return result; -} - -#endif /* defined(WIN32) && defined(_MSC_VER) */ - -/************************* End test_windirent.c ********************/ -#define dirent DIRENT -#endif -/************************* Begin ../ext/misc/shathree.c ******************/ -/* -** 2017-03-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 SQLite extension implements functions that compute SHA3 hashes. -** Two SQL functions are implemented: -** -** sha3(X,SIZE) -** sha3_query(Y,SIZE) -** -** The sha3(X) function computes the SHA3 hash of the input X, or NULL if -** X is NULL. -** -** The sha3_query(Y) function evalutes all queries in the SQL statements of Y -** and returns a hash of their results. -** -** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm -** is used. If SIZE is included it must be one of the integers 224, 256, -** 384, or 512, to determine SHA3 hash variant that is computed. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include -/* typedef sqlite3_uint64 u64; */ - -/****************************************************************************** -** The Hash Engine -*/ -/* -** 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 -** -DSHA3_BYTEORDER=0 is set, then byte-order is determined -** at run-time. -*/ -#ifndef SHA3_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(__arm__) -# define SHA3_BYTEORDER 1234 -# elif defined(sparc) || defined(__ppc__) -# define SHA3_BYTEORDER 4321 -# else -# define SHA3_BYTEORDER 0 -# endif -#endif - - -/* -** State structure for a SHA3 hash in progress -*/ -typedef struct SHA3Context SHA3Context; -struct SHA3Context { - union { - u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */ - unsigned char x[1600]; /* ... or 1600 bytes */ - } u; - unsigned nRate; /* Bytes of input accepted per Keccak iteration */ - unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */ - unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */ -}; - -/* -** A single step of the Keccak mixing function for a 1600-bit state -*/ -static void KeccakF1600Step(SHA3Context *p){ - int i; - u64 b0, b1, b2, b3, b4; - u64 c0, c1, c2, c3, c4; - u64 d0, d1, d2, d3, d4; - static const u64 RC[] = { - 0x0000000000000001ULL, 0x0000000000008082ULL, - 0x800000000000808aULL, 0x8000000080008000ULL, - 0x000000000000808bULL, 0x0000000080000001ULL, - 0x8000000080008081ULL, 0x8000000000008009ULL, - 0x000000000000008aULL, 0x0000000000000088ULL, - 0x0000000080008009ULL, 0x000000008000000aULL, - 0x000000008000808bULL, 0x800000000000008bULL, - 0x8000000000008089ULL, 0x8000000000008003ULL, - 0x8000000000008002ULL, 0x8000000000000080ULL, - 0x000000000000800aULL, 0x800000008000000aULL, - 0x8000000080008081ULL, 0x8000000000008080ULL, - 0x0000000080000001ULL, 0x8000000080008008ULL - }; -# define a00 (p->u.s[0]) -# define a01 (p->u.s[1]) -# define a02 (p->u.s[2]) -# define a03 (p->u.s[3]) -# define a04 (p->u.s[4]) -# define a10 (p->u.s[5]) -# define a11 (p->u.s[6]) -# define a12 (p->u.s[7]) -# define a13 (p->u.s[8]) -# define a14 (p->u.s[9]) -# define a20 (p->u.s[10]) -# define a21 (p->u.s[11]) -# define a22 (p->u.s[12]) -# define a23 (p->u.s[13]) -# define a24 (p->u.s[14]) -# define a30 (p->u.s[15]) -# define a31 (p->u.s[16]) -# define a32 (p->u.s[17]) -# define a33 (p->u.s[18]) -# define a34 (p->u.s[19]) -# define a40 (p->u.s[20]) -# define a41 (p->u.s[21]) -# define a42 (p->u.s[22]) -# define a43 (p->u.s[23]) -# define a44 (p->u.s[24]) -# define ROL64(a,x) ((a<>(64-x))) - - for(i=0; i<24; i+=4){ - c0 = a00^a10^a20^a30^a40; - c1 = a01^a11^a21^a31^a41; - c2 = a02^a12^a22^a32^a42; - c3 = a03^a13^a23^a33^a43; - c4 = a04^a14^a24^a34^a44; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a11^d1), 44); - b2 = ROL64((a22^d2), 43); - b3 = ROL64((a33^d3), 21); - b4 = ROL64((a44^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i]; - a11 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a20^d0), 3); - b3 = ROL64((a31^d1), 45); - b4 = ROL64((a42^d2), 61); - b0 = ROL64((a03^d3), 28); - b1 = ROL64((a14^d4), 20); - a20 = b0 ^((~b1)& b2 ); - a31 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a40^d0), 18); - b0 = ROL64((a01^d1), 1); - b1 = ROL64((a12^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a34^d4), 8); - a40 = b0 ^((~b1)& b2 ); - a01 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a10^d0), 36); - b2 = ROL64((a21^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a43^d3), 56); - b0 = ROL64((a04^d4), 27); - a10 = b0 ^((~b1)& b2 ); - a21 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a30^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a02^d2), 62); - b1 = ROL64((a13^d3), 55); - b2 = ROL64((a24^d4), 39); - a30 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - c0 = a00^a20^a40^a10^a30; - c1 = a11^a31^a01^a21^a41; - c2 = a22^a42^a12^a32^a02; - c3 = a33^a03^a23^a43^a13; - c4 = a44^a14^a34^a04^a24; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a31^d1), 44); - b2 = ROL64((a12^d2), 43); - b3 = ROL64((a43^d3), 21); - b4 = ROL64((a24^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i+1]; - a31 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a40^d0), 3); - b3 = ROL64((a21^d1), 45); - b4 = ROL64((a02^d2), 61); - b0 = ROL64((a33^d3), 28); - b1 = ROL64((a14^d4), 20); - a40 = b0 ^((~b1)& b2 ); - a21 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a30^d0), 18); - b0 = ROL64((a11^d1), 1); - b1 = ROL64((a42^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a04^d4), 8); - a30 = b0 ^((~b1)& b2 ); - a11 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a20^d0), 36); - b2 = ROL64((a01^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a13^d3), 56); - b0 = ROL64((a44^d4), 27); - a20 = b0 ^((~b1)& b2 ); - a01 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a10^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a22^d2), 62); - b1 = ROL64((a03^d3), 55); - b2 = ROL64((a34^d4), 39); - a10 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - c0 = a00^a40^a30^a20^a10; - c1 = a31^a21^a11^a01^a41; - c2 = a12^a02^a42^a32^a22; - c3 = a43^a33^a23^a13^a03; - c4 = a24^a14^a04^a44^a34; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a21^d1), 44); - b2 = ROL64((a42^d2), 43); - b3 = ROL64((a13^d3), 21); - b4 = ROL64((a34^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i+2]; - a21 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a30^d0), 3); - b3 = ROL64((a01^d1), 45); - b4 = ROL64((a22^d2), 61); - b0 = ROL64((a43^d3), 28); - b1 = ROL64((a14^d4), 20); - a30 = b0 ^((~b1)& b2 ); - a01 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a10^d0), 18); - b0 = ROL64((a31^d1), 1); - b1 = ROL64((a02^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a44^d4), 8); - a10 = b0 ^((~b1)& b2 ); - a31 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a40^d0), 36); - b2 = ROL64((a11^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a03^d3), 56); - b0 = ROL64((a24^d4), 27); - a40 = b0 ^((~b1)& b2 ); - a11 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a20^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a12^d2), 62); - b1 = ROL64((a33^d3), 55); - b2 = ROL64((a04^d4), 39); - a20 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - c0 = a00^a30^a10^a40^a20; - c1 = a21^a01^a31^a11^a41; - c2 = a42^a22^a02^a32^a12; - c3 = a13^a43^a23^a03^a33; - c4 = a34^a14^a44^a24^a04; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a01^d1), 44); - b2 = ROL64((a02^d2), 43); - b3 = ROL64((a03^d3), 21); - b4 = ROL64((a04^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i+3]; - a01 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a10^d0), 3); - b3 = ROL64((a11^d1), 45); - b4 = ROL64((a12^d2), 61); - b0 = ROL64((a13^d3), 28); - b1 = ROL64((a14^d4), 20); - a10 = b0 ^((~b1)& b2 ); - a11 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a20^d0), 18); - b0 = ROL64((a21^d1), 1); - b1 = ROL64((a22^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a24^d4), 8); - a20 = b0 ^((~b1)& b2 ); - a21 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a30^d0), 36); - b2 = ROL64((a31^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a33^d3), 56); - b0 = ROL64((a34^d4), 27); - a30 = b0 ^((~b1)& b2 ); - a31 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a40^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a42^d2), 62); - b1 = ROL64((a43^d3), 55); - b2 = ROL64((a44^d4), 39); - a40 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - } -} - -/* -** Initialize a new hash. iSize determines the size of the hash -** in bits and should be one of 224, 256, 384, or 512. Or iSize -** can be zero to use the default hash size of 256 bits. -*/ -static void SHA3Init(SHA3Context *p, int iSize){ - memset(p, 0, sizeof(*p)); - if( iSize>=128 && iSize<=512 ){ - p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; - }else{ - p->nRate = (1600 - 2*256)/8; - } -#if SHA3_BYTEORDER==1234 - /* Known to be little-endian at compile-time. No-op */ -#elif SHA3_BYTEORDER==4321 - p->ixMask = 7; /* Big-endian */ -#else - { - static unsigned int one = 1; - if( 1==*(unsigned char*)&one ){ - /* Little endian. No byte swapping. */ - p->ixMask = 0; - }else{ - /* Big endian. Byte swap. */ - p->ixMask = 7; - } - } -#endif -} - -/* -** Make consecutive calls to the SHA3Update function to add new content -** to the hash -*/ -static void SHA3Update( - SHA3Context *p, - const unsigned char *aData, - unsigned int nData -){ - unsigned int i = 0; -#if SHA3_BYTEORDER==1234 - if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ - for(; i+7u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; - p->nLoaded += 8; - if( p->nLoaded>=p->nRate ){ - KeccakF1600Step(p); - p->nLoaded = 0; - } - } - } -#endif - for(; iu.x[p->nLoaded] ^= aData[i]; -#elif SHA3_BYTEORDER==4321 - p->u.x[p->nLoaded^0x07] ^= aData[i]; -#else - p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; -#endif - p->nLoaded++; - if( p->nLoaded==p->nRate ){ - KeccakF1600Step(p); - p->nLoaded = 0; - } - } -} - -/* -** After all content has been added, invoke SHA3Final() to compute -** the final hash. The function returns a pointer to the binary -** hash value. -*/ -static unsigned char *SHA3Final(SHA3Context *p){ - unsigned int i; - if( p->nLoaded==p->nRate-1 ){ - const unsigned char c1 = 0x86; - SHA3Update(p, &c1, 1); - }else{ - const unsigned char c2 = 0x06; - const unsigned char c3 = 0x80; - SHA3Update(p, &c2, 1); - p->nLoaded = p->nRate - 1; - SHA3Update(p, &c3, 1); - } - for(i=0; inRate; i++){ - p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; - } - return &p->u.x[p->nRate]; -} -/* End of the hashing logic -*****************************************************************************/ - -/* -** Implementation of the sha3(X,SIZE) function. -** -** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default -** size is 256. If X is a BLOB, it is hashed as is. -** For all other non-NULL types of input, X is converted into a UTF-8 string -** and the string is hashed without the trailing 0x00 terminator. The hash -** of a NULL value is NULL. -*/ -static void sha3Func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - SHA3Context cx; - int eType = sqlite3_value_type(argv[0]); - int nByte = sqlite3_value_bytes(argv[0]); - int iSize; - if( argc==1 ){ - iSize = 256; - }else{ - iSize = sqlite3_value_int(argv[1]); - if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ - sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " - "384 512", -1); - return; - } - } - if( eType==SQLITE_NULL ) return; - SHA3Init(&cx, iSize); - if( eType==SQLITE_BLOB ){ - SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte); - }else{ - SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte); - } - sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); -} - -/* Compute a string using sqlite3_vsnprintf() with a maximum length -** of 50 bytes and add it to the hash. -*/ -static void hash_step_vformat( - SHA3Context *p, /* Add content to this context */ - const char *zFormat, - ... -){ - va_list ap; - int n; - char zBuf[50]; - va_start(ap, zFormat); - sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap); - va_end(ap); - n = (int)strlen(zBuf); - SHA3Update(p, (unsigned char*)zBuf, n); -} - -/* -** Implementation of the sha3_query(SQL,SIZE) function. -** -** This function compiles and runs the SQL statement(s) given in the -** argument. The results are hashed using a SIZE-bit SHA3. The default -** size is 256. -** -** The format of the byte stream that is hashed is summarized as follows: -** -** S: -** R -** N -** I -** F -** B: -** T: -** -** is the original SQL text for each statement run and is -** the size of that text. The SQL text is UTF-8. A single R character -** occurs before the start of each row. N means a NULL value. -** I mean an 8-byte little-endian integer . F is a floating point -** number with an 8-byte little-endian IEEE floating point value . -** B means blobs of bytes. T means text rendered as -** bytes of UTF-8. The and values are expressed as an ASCII -** text integers. -** -** For each SQL statement in the X input, there is one S segment. Each -** S segment is followed by zero or more R segments, one for each row in the -** result set. After each R, there are one or more N, I, F, B, or T segments, -** one for each column in the result set. Segments are concatentated directly -** with no delimiters of any kind. -*/ -static void sha3QueryFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - const char *zSql = (const char*)sqlite3_value_text(argv[0]); - sqlite3_stmt *pStmt = 0; - int nCol; /* Number of columns in the result set */ - int i; /* Loop counter */ - int rc; - int n; - const char *z; - SHA3Context cx; - int iSize; - - if( argc==1 ){ - iSize = 256; - }else{ - iSize = sqlite3_value_int(argv[1]); - if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ - sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " - "384 512", -1); - return; - } - } - if( zSql==0 ) return; - SHA3Init(&cx, iSize); - while( zSql[0] ){ - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); - if( rc ){ - char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s", - zSql, sqlite3_errmsg(db)); - sqlite3_finalize(pStmt); - sqlite3_result_error(context, zMsg, -1); - sqlite3_free(zMsg); - return; - } - if( !sqlite3_stmt_readonly(pStmt) ){ - char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); - sqlite3_finalize(pStmt); - sqlite3_result_error(context, zMsg, -1); - sqlite3_free(zMsg); - return; - } - nCol = sqlite3_column_count(pStmt); - z = sqlite3_sql(pStmt); - n = (int)strlen(z); - hash_step_vformat(&cx,"S%d:",n); - SHA3Update(&cx,(unsigned char*)z,n); - - /* Compute a hash over the result of the query */ - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - SHA3Update(&cx,(const unsigned char*)"R",1); - for(i=0; i=1; j--){ - x[j] = u & 0xff; - u >>= 8; - } - x[0] = 'I'; - SHA3Update(&cx, x, 9); - break; - } - case SQLITE_FLOAT: { - sqlite3_uint64 u; - int j; - unsigned char x[9]; - double r = sqlite3_column_double(pStmt,i); - memcpy(&u, &r, 8); - for(j=8; j>=1; j--){ - x[j] = u & 0xff; - u >>= 8; - } - x[0] = 'F'; - SHA3Update(&cx,x,9); - break; - } - case SQLITE_TEXT: { - int n2 = sqlite3_column_bytes(pStmt, i); - const unsigned char *z2 = sqlite3_column_text(pStmt, i); - hash_step_vformat(&cx,"T%d:",n2); - SHA3Update(&cx, z2, n2); - break; - } - case SQLITE_BLOB: { - int n2 = sqlite3_column_bytes(pStmt, i); - const unsigned char *z2 = sqlite3_column_blob(pStmt, i); - hash_step_vformat(&cx,"B%d:",n2); - SHA3Update(&cx, z2, n2); - break; - } - } - } - } - sqlite3_finalize(pStmt); - } - sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); -} - - -#ifdef _WIN32 - -#endif -int sqlite3_shathree_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - rc = sqlite3_create_function(db, "sha3", 1, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - 0, sha3Func, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3", 2, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - 0, sha3Func, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3_query", 1, - SQLITE_UTF8 | SQLITE_DIRECTONLY, - 0, sha3QueryFunc, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3_query", 2, - SQLITE_UTF8 | SQLITE_DIRECTONLY, - 0, sha3QueryFunc, 0, 0); - } - return rc; -} - -/************************* End ../ext/misc/shathree.c ********************/ -/************************* Begin ../ext/misc/fileio.c ******************/ -/* -** 2014-06-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 SQLite extension implements SQL functions readfile() and -** writefile(), and eponymous virtual type "fsdir". -** -** WRITEFILE(FILE, DATA [, MODE [, MTIME]]): -** -** If neither of the optional arguments is present, then this UDF -** function writes blob DATA to file FILE. If successful, the number -** of bytes written is returned. If an error occurs, NULL is returned. -** -** If the first option argument - MODE - is present, then it must -** be passed an integer value that corresponds to a POSIX mode -** value (file type + permissions, as returned in the stat.st_mode -** field by the stat() system call). Three types of files may -** be written/created: -** -** regular files: (mode & 0170000)==0100000 -** symbolic links: (mode & 0170000)==0120000 -** directories: (mode & 0170000)==0040000 -** -** For a directory, the DATA is ignored. For a symbolic link, it is -** interpreted as text and used as the target of the link. For a -** regular file, it is interpreted as a blob and written into the -** named file. Regardless of the type of file, its permissions are -** set to (mode & 0777) before returning. -** -** If the optional MTIME argument is present, then it is interpreted -** as an integer - the number of seconds since the unix epoch. The -** modification-time of the target file is set to this value before -** returning. -** -** If three or more arguments are passed to this function and an -** error is encountered, an exception is raised. -** -** READFILE(FILE): -** -** Read and return the contents of file FILE (type blob) from disk. -** -** FSDIR: -** -** Used as follows: -** -** SELECT * FROM fsdir($path [, $dir]); -** -** Parameter $path is an absolute or relative pathname. If the file that it -** refers to does not exist, it is an error. If the path refers to a regular -** file or symbolic link, it returns a single row. Or, if the path refers -** to a directory, it returns one row for the directory, and one row for each -** file within the hierarchy rooted at $path. -** -** Each row has the following columns: -** -** name: Path to file or directory (text value). -** mode: Value of stat.st_mode for directory entry (an integer). -** mtime: Value of stat.st_mtime for directory entry (an integer). -** data: For a regular file, a blob containing the file data. For a -** symlink, a text value containing the text of the link. For a -** directory, NULL. -** -** If a non-NULL value is specified for the optional $dir parameter and -** $path is a relative path, then $path is interpreted relative to $dir. -** And the paths returned in the "name" column of the table are also -** relative to directory $dir. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#include -#include -#include -#if !defined(_WIN32) && !defined(WIN32) -# include -# include -# include -# include -#else -# include "windows.h" -# include -# include -/* # include "test_windirent.h" */ -# define dirent DIRENT -# ifndef chmod -# define chmod _chmod -# endif -# ifndef stat -# define stat _stat -# endif -# define mkdir(path,mode) _mkdir(path) -# define lstat(path,buf) stat(path,buf) -#endif -#include -#include - - -/* -** Structure of the fsdir() table-valued function -*/ - /* 0 1 2 3 4 5 */ -#define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)" -#define FSDIR_COLUMN_NAME 0 /* Name of the file */ -#define FSDIR_COLUMN_MODE 1 /* Access mode */ -#define FSDIR_COLUMN_MTIME 2 /* Last modification time */ -#define FSDIR_COLUMN_DATA 3 /* File content */ -#define FSDIR_COLUMN_PATH 4 /* Path to top of search */ -#define FSDIR_COLUMN_DIR 5 /* Path is relative to this directory */ - - -/* -** Set the result stored by context ctx to a blob containing the -** contents of file zName. Or, leave the result unchanged (NULL) -** if the file does not exist or is unreadable. -** -** If the file exceeds the SQLite blob size limit, through an -** SQLITE_TOOBIG error. -** -** Throw an SQLITE_IOERR if there are difficulties pulling the file -** off of disk. -*/ -static void readFileContents(sqlite3_context *ctx, const char *zName){ - FILE *in; - sqlite3_int64 nIn; - void *pBuf; - sqlite3 *db; - int mxBlob; - - in = fopen(zName, "rb"); - if( in==0 ){ - /* File does not exist or is unreadable. Leave the result set to NULL. */ - return; - } - fseek(in, 0, SEEK_END); - nIn = ftell(in); - rewind(in); - db = sqlite3_context_db_handle(ctx); - mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1); - if( nIn>mxBlob ){ - sqlite3_result_error_code(ctx, SQLITE_TOOBIG); - fclose(in); - return; - } - pBuf = sqlite3_malloc64( nIn ? nIn : 1 ); - if( pBuf==0 ){ - sqlite3_result_error_nomem(ctx); - fclose(in); - return; - } - if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){ - sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free); - }else{ - sqlite3_result_error_code(ctx, SQLITE_IOERR); - sqlite3_free(pBuf); - } - fclose(in); -} - -/* -** Implementation of the "readfile(X)" SQL function. The entire content -** of the file named X is read and returned as a BLOB. NULL is returned -** if the file does not exist or is unreadable. -*/ -static void readfileFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zName; - (void)(argc); /* Unused parameter */ - zName = (const char*)sqlite3_value_text(argv[0]); - if( zName==0 ) return; - readFileContents(context, zName); -} - -/* -** Set the error message contained in context ctx to the results of -** vprintf(zFmt, ...). -*/ -static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ - char *zMsg = 0; - va_list ap; - va_start(ap, zFmt); - zMsg = sqlite3_vmprintf(zFmt, ap); - sqlite3_result_error(ctx, zMsg, -1); - sqlite3_free(zMsg); - va_end(ap); -} - -#if defined(_WIN32) -/* -** This function is designed to convert a Win32 FILETIME structure into the -** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC). -*/ -static sqlite3_uint64 fileTimeToUnixTime( - LPFILETIME pFileTime -){ - SYSTEMTIME epochSystemTime; - ULARGE_INTEGER epochIntervals; - FILETIME epochFileTime; - ULARGE_INTEGER fileIntervals; - - memset(&epochSystemTime, 0, sizeof(SYSTEMTIME)); - epochSystemTime.wYear = 1970; - epochSystemTime.wMonth = 1; - epochSystemTime.wDay = 1; - SystemTimeToFileTime(&epochSystemTime, &epochFileTime); - epochIntervals.LowPart = epochFileTime.dwLowDateTime; - epochIntervals.HighPart = epochFileTime.dwHighDateTime; - - fileIntervals.LowPart = pFileTime->dwLowDateTime; - fileIntervals.HighPart = pFileTime->dwHighDateTime; - - return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000; -} - -/* -** This function attempts to normalize the time values found in the stat() -** buffer to UTC. This is necessary on Win32, where the runtime library -** appears to return these values as local times. -*/ -static void statTimesToUtc( - const char *zPath, - struct stat *pStatBuf -){ - HANDLE hFindFile; - WIN32_FIND_DATAW fd; - LPWSTR zUnicodeName; - extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); - zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath); - if( zUnicodeName ){ - memset(&fd, 0, sizeof(WIN32_FIND_DATAW)); - hFindFile = FindFirstFileW(zUnicodeName, &fd); - if( hFindFile!=NULL ){ - pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime); - pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime); - pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime); - FindClose(hFindFile); - } - sqlite3_free(zUnicodeName); - } -} -#endif - -/* -** This function is used in place of stat(). On Windows, special handling -** is required in order for the included time to be returned as UTC. On all -** other systems, this function simply calls stat(). -*/ -static int fileStat( - const char *zPath, - struct stat *pStatBuf -){ -#if defined(_WIN32) - int rc = stat(zPath, pStatBuf); - if( rc==0 ) statTimesToUtc(zPath, pStatBuf); - return rc; -#else - return stat(zPath, pStatBuf); -#endif -} - -/* -** This function is used in place of lstat(). On Windows, special handling -** is required in order for the included time to be returned as UTC. On all -** other systems, this function simply calls lstat(). -*/ -static int fileLinkStat( - const char *zPath, - struct stat *pStatBuf -){ -#if defined(_WIN32) - int rc = lstat(zPath, pStatBuf); - if( rc==0 ) statTimesToUtc(zPath, pStatBuf); - return rc; -#else - return lstat(zPath, pStatBuf); -#endif -} - -/* -** Argument zFile is the name of a file that will be created and/or written -** by SQL function writefile(). This function ensures that the directory -** zFile will be written to exists, creating it if required. The permissions -** for any path components created by this function are set in accordance -** with the current umask. -** -** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise, -** SQLITE_OK is returned if the directory is successfully created, or -** SQLITE_ERROR otherwise. -*/ -static int makeDirectory( - const char *zFile -){ - char *zCopy = sqlite3_mprintf("%s", zFile); - int rc = SQLITE_OK; - - if( zCopy==0 ){ - rc = SQLITE_NOMEM; - }else{ - int nCopy = (int)strlen(zCopy); - int i = 1; - - while( rc==SQLITE_OK ){ - struct stat sStat; - int rc2; - - for(; zCopy[i]!='/' && i=0 ){ -#if defined(_WIN32) -#if !SQLITE_OS_WINRT - /* Windows */ - FILETIME lastAccess; - FILETIME lastWrite; - SYSTEMTIME currentTime; - LONGLONG intervals; - HANDLE hFile; - LPWSTR zUnicodeName; - extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); - - GetSystemTime(¤tTime); - SystemTimeToFileTime(¤tTime, &lastAccess); - intervals = Int32x32To64(mtime, 10000000) + 116444736000000000; - lastWrite.dwLowDateTime = (DWORD)intervals; - lastWrite.dwHighDateTime = intervals >> 32; - zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile); - if( zUnicodeName==0 ){ - return 1; - } - hFile = CreateFileW( - zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL - ); - sqlite3_free(zUnicodeName); - if( hFile!=INVALID_HANDLE_VALUE ){ - BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite); - CloseHandle(hFile); - return !bResult; - }else{ - return 1; - } -#endif -#elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */ - /* Recent unix */ - struct timespec times[2]; - times[0].tv_nsec = times[1].tv_nsec = 0; - times[0].tv_sec = time(0); - times[1].tv_sec = mtime; - if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){ - return 1; - } -#else - /* Legacy unix */ - struct timeval times[2]; - times[0].tv_usec = times[1].tv_usec = 0; - times[0].tv_sec = time(0); - times[1].tv_sec = mtime; - if( utimes(zFile, times) ){ - return 1; - } -#endif - } - - return 0; -} - -/* -** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function. -** Refer to header comments at the top of this file for details. -*/ -static void writefileFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zFile; - mode_t mode = 0; - int res; - sqlite3_int64 mtime = -1; - - if( argc<2 || argc>4 ){ - sqlite3_result_error(context, - "wrong number of arguments to function writefile()", -1 - ); - return; - } - - zFile = (const char*)sqlite3_value_text(argv[0]); - if( zFile==0 ) return; - if( argc>=3 ){ - mode = (mode_t)sqlite3_value_int(argv[2]); - } - if( argc==4 ){ - mtime = sqlite3_value_int64(argv[3]); - } - - res = writeFile(context, zFile, argv[1], mode, mtime); - if( res==1 && errno==ENOENT ){ - if( makeDirectory(zFile)==SQLITE_OK ){ - res = writeFile(context, zFile, argv[1], mode, mtime); - } - } - - if( argc>2 && res!=0 ){ - if( S_ISLNK(mode) ){ - ctxErrorMsg(context, "failed to create symlink: %s", zFile); - }else if( S_ISDIR(mode) ){ - ctxErrorMsg(context, "failed to create directory: %s", zFile); - }else{ - ctxErrorMsg(context, "failed to write file: %s", zFile); - } - } -} - -/* -** SQL function: lsmode(MODE) -** -** Given a numberic st_mode from stat(), convert it into a human-readable -** text string in the style of "ls -l". -*/ -static void lsModeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int i; - int iMode = sqlite3_value_int(argv[0]); - char z[16]; - (void)argc; - if( S_ISLNK(iMode) ){ - z[0] = 'l'; - }else if( S_ISREG(iMode) ){ - z[0] = '-'; - }else if( S_ISDIR(iMode) ){ - z[0] = 'd'; - }else{ - z[0] = '?'; - } - for(i=0; i<3; i++){ - int m = (iMode >> ((2-i)*3)); - char *a = &z[1 + i*3]; - a[0] = (m & 0x4) ? 'r' : '-'; - a[1] = (m & 0x2) ? 'w' : '-'; - a[2] = (m & 0x1) ? 'x' : '-'; - } - z[10] = '\0'; - sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); -} - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* -** Cursor type for recursively iterating through a directory structure. -*/ -typedef struct fsdir_cursor fsdir_cursor; -typedef struct FsdirLevel FsdirLevel; - -struct FsdirLevel { - DIR *pDir; /* From opendir() */ - char *zDir; /* Name of directory (nul-terminated) */ -}; - -struct fsdir_cursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - - int nLvl; /* Number of entries in aLvl[] array */ - int iLvl; /* Index of current entry */ - FsdirLevel *aLvl; /* Hierarchy of directories being traversed */ - - const char *zBase; - int nBase; - - struct stat sStat; /* Current lstat() results */ - char *zPath; /* Path to current entry */ - sqlite3_int64 iRowid; /* Current rowid */ -}; - -typedef struct fsdir_tab fsdir_tab; -struct fsdir_tab { - sqlite3_vtab base; /* Base class - must be first */ -}; - -/* -** Construct a new fsdir virtual table object. -*/ -static int fsdirConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - fsdir_tab *pNew = 0; - int rc; - (void)pAux; - (void)argc; - (void)argv; - (void)pzErr; - rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA); - if( rc==SQLITE_OK ){ - pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) ); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); - sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); - } - *ppVtab = (sqlite3_vtab*)pNew; - return rc; -} - -/* -** This method is the destructor for fsdir vtab objects. -*/ -static int fsdirDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* -** Constructor for a new fsdir_cursor object. -*/ -static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - fsdir_cursor *pCur; - (void)p; - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - pCur->iLvl = -1; - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* -** Reset a cursor back to the state it was in when first returned -** by fsdirOpen(). -*/ -static void fsdirResetCursor(fsdir_cursor *pCur){ - int i; - for(i=0; i<=pCur->iLvl; i++){ - FsdirLevel *pLvl = &pCur->aLvl[i]; - if( pLvl->pDir ) closedir(pLvl->pDir); - sqlite3_free(pLvl->zDir); - } - sqlite3_free(pCur->zPath); - sqlite3_free(pCur->aLvl); - pCur->aLvl = 0; - pCur->zPath = 0; - pCur->zBase = 0; - pCur->nBase = 0; - pCur->nLvl = 0; - pCur->iLvl = -1; - pCur->iRowid = 1; -} - -/* -** Destructor for an fsdir_cursor. -*/ -static int fsdirClose(sqlite3_vtab_cursor *cur){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - - fsdirResetCursor(pCur); - sqlite3_free(pCur); - return SQLITE_OK; -} - -/* -** Set the error message for the virtual table associated with cursor -** pCur to the results of vprintf(zFmt, ...). -*/ -static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){ - va_list ap; - va_start(ap, zFmt); - pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); - va_end(ap); -} - - -/* -** Advance an fsdir_cursor to its next row of output. -*/ -static int fsdirNext(sqlite3_vtab_cursor *cur){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - mode_t m = pCur->sStat.st_mode; - - pCur->iRowid++; - if( S_ISDIR(m) ){ - /* Descend into this directory */ - int iNew = pCur->iLvl + 1; - FsdirLevel *pLvl; - if( iNew>=pCur->nLvl ){ - int nNew = iNew+1; - sqlite3_int64 nByte = nNew*sizeof(FsdirLevel); - FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte); - if( aNew==0 ) return SQLITE_NOMEM; - memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl)); - pCur->aLvl = aNew; - pCur->nLvl = nNew; - } - pCur->iLvl = iNew; - pLvl = &pCur->aLvl[iNew]; - - pLvl->zDir = pCur->zPath; - pCur->zPath = 0; - pLvl->pDir = opendir(pLvl->zDir); - if( pLvl->pDir==0 ){ - fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath); - return SQLITE_ERROR; - } - } - - while( pCur->iLvl>=0 ){ - FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl]; - struct dirent *pEntry = readdir(pLvl->pDir); - if( pEntry ){ - if( pEntry->d_name[0]=='.' ){ - if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue; - if( pEntry->d_name[1]=='\0' ) continue; - } - sqlite3_free(pCur->zPath); - pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name); - if( pCur->zPath==0 ) return SQLITE_NOMEM; - if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ - fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); - return SQLITE_ERROR; - } - return SQLITE_OK; - } - closedir(pLvl->pDir); - sqlite3_free(pLvl->zDir); - pLvl->pDir = 0; - pLvl->zDir = 0; - pCur->iLvl--; - } - - /* EOF */ - sqlite3_free(pCur->zPath); - pCur->zPath = 0; - return SQLITE_OK; -} - -/* -** Return values of columns for the row at which the series_cursor -** is currently pointing. -*/ -static int fsdirColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - switch( i ){ - case FSDIR_COLUMN_NAME: { - sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT); - break; - } - - case FSDIR_COLUMN_MODE: - sqlite3_result_int64(ctx, pCur->sStat.st_mode); - break; - - case FSDIR_COLUMN_MTIME: - sqlite3_result_int64(ctx, pCur->sStat.st_mtime); - break; - - case FSDIR_COLUMN_DATA: { - mode_t m = pCur->sStat.st_mode; - if( S_ISDIR(m) ){ - sqlite3_result_null(ctx); -#if !defined(_WIN32) && !defined(WIN32) - }else if( S_ISLNK(m) ){ - char aStatic[64]; - char *aBuf = aStatic; - sqlite3_int64 nBuf = 64; - int n; - - while( 1 ){ - n = readlink(pCur->zPath, aBuf, nBuf); - if( nzPath); - } - } - case FSDIR_COLUMN_PATH: - default: { - /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters. - ** always return their values as NULL */ - break; - } - } - return SQLITE_OK; -} - -/* -** Return the rowid for the current row. In this implementation, the -** first row returned is assigned rowid value 1, and each subsequent -** row a value 1 more than that of the previous. -*/ -static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - *pRowid = pCur->iRowid; - return SQLITE_OK; -} - -/* -** Return TRUE if the cursor has been moved off of the last -** row of output. -*/ -static int fsdirEof(sqlite3_vtab_cursor *cur){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - return (pCur->zPath==0); -} - -/* -** xFilter callback. -** -** idxNum==1 PATH parameter only -** idxNum==2 Both PATH and DIR supplied -*/ -static int fsdirFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - const char *zDir = 0; - fsdir_cursor *pCur = (fsdir_cursor*)cur; - (void)idxStr; - fsdirResetCursor(pCur); - - if( idxNum==0 ){ - fsdirSetErrmsg(pCur, "table function fsdir requires an argument"); - return SQLITE_ERROR; - } - - assert( argc==idxNum && (argc==1 || argc==2) ); - zDir = (const char*)sqlite3_value_text(argv[0]); - if( zDir==0 ){ - fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument"); - return SQLITE_ERROR; - } - if( argc==2 ){ - pCur->zBase = (const char*)sqlite3_value_text(argv[1]); - } - if( pCur->zBase ){ - pCur->nBase = (int)strlen(pCur->zBase)+1; - pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir); - }else{ - pCur->zPath = sqlite3_mprintf("%s", zDir); - } - - if( pCur->zPath==0 ){ - return SQLITE_NOMEM; - } - if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ - fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); - return SQLITE_ERROR; - } - - return SQLITE_OK; -} - -/* -** SQLite will invoke this method one or more times while planning a query -** that uses the generate_series virtual table. This routine needs to create -** a query plan for each invocation and compute an estimated cost for that -** plan. -** -** In this implementation idxNum is used to represent the -** query plan. idxStr is unused. -** -** The query plan is represented by values of idxNum: -** -** (1) The path value is supplied by argv[0] -** (2) Path is in argv[0] and dir is in argv[1] -*/ -static int fsdirBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; /* Loop over constraints */ - int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */ - int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */ - int seenPath = 0; /* True if an unusable PATH= constraint is seen */ - int seenDir = 0; /* True if an unusable DIR= constraint is seen */ - const struct sqlite3_index_constraint *pConstraint; - - (void)tab; - pConstraint = pIdxInfo->aConstraint; - for(i=0; inConstraint; i++, pConstraint++){ - if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; - switch( pConstraint->iColumn ){ - case FSDIR_COLUMN_PATH: { - if( pConstraint->usable ){ - idxPath = i; - seenPath = 0; - }else if( idxPath<0 ){ - seenPath = 1; - } - break; - } - case FSDIR_COLUMN_DIR: { - if( pConstraint->usable ){ - idxDir = i; - seenDir = 0; - }else if( idxDir<0 ){ - seenDir = 1; - } - break; - } - } - } - if( seenPath || seenDir ){ - /* If input parameters are unusable, disallow this plan */ - return SQLITE_CONSTRAINT; - } - - if( idxPath<0 ){ - pIdxInfo->idxNum = 0; - /* The pIdxInfo->estimatedCost should have been initialized to a huge - ** number. Leave it unchanged. */ - pIdxInfo->estimatedRows = 0x7fffffff; - }else{ - pIdxInfo->aConstraintUsage[idxPath].omit = 1; - pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1; - if( idxDir>=0 ){ - pIdxInfo->aConstraintUsage[idxDir].omit = 1; - pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2; - pIdxInfo->idxNum = 2; - pIdxInfo->estimatedCost = 10.0; - }else{ - pIdxInfo->idxNum = 1; - pIdxInfo->estimatedCost = 100.0; - } - } - - return SQLITE_OK; -} - -/* -** Register the "fsdir" virtual table. -*/ -static int fsdirRegister(sqlite3 *db){ - static sqlite3_module fsdirModule = { - 0, /* iVersion */ - 0, /* xCreate */ - fsdirConnect, /* xConnect */ - fsdirBestIndex, /* xBestIndex */ - fsdirDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - fsdirOpen, /* xOpen - open a cursor */ - fsdirClose, /* xClose - close a cursor */ - fsdirFilter, /* xFilter - configure scan constraints */ - fsdirNext, /* xNext - advance a cursor */ - fsdirEof, /* xEof - check for end of scan */ - fsdirColumn, /* xColumn - read data */ - fsdirRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - }; - - int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0); - return rc; -} -#else /* SQLITE_OMIT_VIRTUALTABLE */ -# define fsdirRegister(x) SQLITE_OK -#endif - -#ifdef _WIN32 - -#endif -int sqlite3_fileio_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - rc = sqlite3_create_function(db, "readfile", 1, - SQLITE_UTF8|SQLITE_DIRECTONLY, 0, - readfileFunc, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "writefile", -1, - SQLITE_UTF8|SQLITE_DIRECTONLY, 0, - writefileFunc, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0, - lsModeFunc, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = fsdirRegister(db); - } - return rc; -} - -/************************* End ../ext/misc/fileio.c ********************/ -/************************* Begin ../ext/misc/completion.c ******************/ -/* -** 2017-07-10 -** -** 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 eponymous virtual table that returns suggested -** completions for a partial SQL input. -** -** Suggested usage: -** -** SELECT DISTINCT candidate COLLATE nocase -** FROM completion($prefix,$wholeline) -** ORDER BY 1; -** -** The two query parameters are optional. $prefix is the text of the -** current word being typed and that is to be completed. $wholeline is -** the complete input line, used for context. -** -** The raw completion() table might return the same candidate multiple -** times, for example if the same column name is used to two or more -** tables. And the candidates are returned in an arbitrary order. Hence, -** the DISTINCT and ORDER BY are recommended. -** -** This virtual table operates at the speed of human typing, and so there -** is no attempt to make it fast. Even a slow implementation will be much -** faster than any human can type. -** -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* completion_vtab is a subclass of sqlite3_vtab which will -** serve as the underlying representation of a completion virtual table -*/ -typedef struct completion_vtab completion_vtab; -struct completion_vtab { - sqlite3_vtab base; /* Base class - must be first */ - sqlite3 *db; /* Database connection for this completion vtab */ -}; - -/* completion_cursor is a subclass of sqlite3_vtab_cursor which will -** serve as the underlying representation of a cursor that scans -** over rows of the result -*/ -typedef struct completion_cursor completion_cursor; -struct completion_cursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - sqlite3 *db; /* Database connection for this cursor */ - int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */ - char *zPrefix; /* The prefix for the word we want to complete */ - char *zLine; /* The whole that we want to complete */ - const char *zCurrentRow; /* Current output row */ - int szRow; /* Length of the zCurrentRow string */ - sqlite3_stmt *pStmt; /* Current statement */ - sqlite3_int64 iRowid; /* The rowid */ - int ePhase; /* Current phase */ - int j; /* inter-phase counter */ -}; - -/* Values for ePhase: -*/ -#define COMPLETION_FIRST_PHASE 1 -#define COMPLETION_KEYWORDS 1 -#define COMPLETION_PRAGMAS 2 -#define COMPLETION_FUNCTIONS 3 -#define COMPLETION_COLLATIONS 4 -#define COMPLETION_INDEXES 5 -#define COMPLETION_TRIGGERS 6 -#define COMPLETION_DATABASES 7 -#define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */ -#define COMPLETION_COLUMNS 9 -#define COMPLETION_MODULES 10 -#define COMPLETION_EOF 11 - -/* -** The completionConnect() method is invoked to create a new -** completion_vtab that describes the completion virtual table. -** -** Think of this routine as the constructor for completion_vtab objects. -** -** All this routine needs to do is: -** -** (1) Allocate the completion_vtab object and initialize all fields. -** -** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the -** result set of queries against completion will look like. -*/ -static int completionConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - completion_vtab *pNew; - int rc; - - (void)(pAux); /* Unused parameter */ - (void)(argc); /* Unused parameter */ - (void)(argv); /* Unused parameter */ - (void)(pzErr); /* Unused parameter */ - -/* Column numbers */ -#define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */ -#define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */ -#define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */ -#define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */ - - sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); - rc = sqlite3_declare_vtab(db, - "CREATE TABLE x(" - " candidate TEXT," - " prefix TEXT HIDDEN," - " wholeline TEXT HIDDEN," - " phase INT HIDDEN" /* Used for debugging only */ - ")"); - if( rc==SQLITE_OK ){ - pNew = sqlite3_malloc( sizeof(*pNew) ); - *ppVtab = (sqlite3_vtab*)pNew; - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); - pNew->db = db; - } - return rc; -} - -/* -** This method is the destructor for completion_cursor objects. -*/ -static int completionDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* -** Constructor for a new completion_cursor object. -*/ -static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - completion_cursor *pCur; - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - pCur->db = ((completion_vtab*)p)->db; - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* -** Reset the completion_cursor. -*/ -static void completionCursorReset(completion_cursor *pCur){ - sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0; - sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0; - sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0; - pCur->j = 0; -} - -/* -** Destructor for a completion_cursor. -*/ -static int completionClose(sqlite3_vtab_cursor *cur){ - completionCursorReset((completion_cursor*)cur); - sqlite3_free(cur); - return SQLITE_OK; -} - -/* -** Advance a completion_cursor to its next row of output. -** -** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object -** record the current state of the scan. This routine sets ->zCurrentRow -** to the current row of output and then returns. If no more rows remain, -** then ->ePhase is set to COMPLETION_EOF which will signal the virtual -** table that has reached the end of its scan. -** -** The current implementation just lists potential identifiers and -** keywords and filters them by zPrefix. Future enhancements should -** take zLine into account to try to restrict the set of identifiers and -** keywords based on what would be legal at the current point of input. -*/ -static int completionNext(sqlite3_vtab_cursor *cur){ - completion_cursor *pCur = (completion_cursor*)cur; - int eNextPhase = 0; /* Next phase to try if current phase reaches end */ - int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */ - pCur->iRowid++; - while( pCur->ePhase!=COMPLETION_EOF ){ - switch( pCur->ePhase ){ - case COMPLETION_KEYWORDS: { - if( pCur->j >= sqlite3_keyword_count() ){ - pCur->zCurrentRow = 0; - pCur->ePhase = COMPLETION_DATABASES; - }else{ - sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow); - } - iCol = -1; - break; - } - case COMPLETION_DATABASES: { - if( pCur->pStmt==0 ){ - sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, - &pCur->pStmt, 0); - } - iCol = 1; - eNextPhase = COMPLETION_TABLES; - break; - } - case COMPLETION_TABLES: { - if( pCur->pStmt==0 ){ - sqlite3_stmt *pS2; - char *zSql = 0; - const char *zSep = ""; - sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); - while( sqlite3_step(pS2)==SQLITE_ROW ){ - const char *zDb = (const char*)sqlite3_column_text(pS2, 1); - zSql = sqlite3_mprintf( - "%z%s" - "SELECT name FROM \"%w\".sqlite_schema", - zSql, zSep, zDb - ); - if( zSql==0 ) return SQLITE_NOMEM; - zSep = " UNION "; - } - sqlite3_finalize(pS2); - sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); - sqlite3_free(zSql); - } - iCol = 0; - eNextPhase = COMPLETION_COLUMNS; - break; - } - case COMPLETION_COLUMNS: { - if( pCur->pStmt==0 ){ - sqlite3_stmt *pS2; - char *zSql = 0; - const char *zSep = ""; - sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); - while( sqlite3_step(pS2)==SQLITE_ROW ){ - const char *zDb = (const char*)sqlite3_column_text(pS2, 1); - zSql = sqlite3_mprintf( - "%z%s" - "SELECT pti.name FROM \"%w\".sqlite_schema AS sm" - " JOIN pragma_table_info(sm.name,%Q) AS pti" - " WHERE sm.type='table'", - zSql, zSep, zDb, zDb - ); - if( zSql==0 ) return SQLITE_NOMEM; - zSep = " UNION "; - } - sqlite3_finalize(pS2); - sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); - sqlite3_free(zSql); - } - iCol = 0; - eNextPhase = COMPLETION_EOF; - break; - } - } - if( iCol<0 ){ - /* This case is when the phase presets zCurrentRow */ - if( pCur->zCurrentRow==0 ) continue; - }else{ - if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){ - /* Extract the next row of content */ - pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol); - pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol); - }else{ - /* When all rows are finished, advance to the next phase */ - sqlite3_finalize(pCur->pStmt); - pCur->pStmt = 0; - pCur->ePhase = eNextPhase; - continue; - } - } - if( pCur->nPrefix==0 ) break; - if( pCur->nPrefix<=pCur->szRow - && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 - ){ - break; - } - } - - return SQLITE_OK; -} - -/* -** Return values of columns for the row at which the completion_cursor -** is currently pointing. -*/ -static int completionColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - completion_cursor *pCur = (completion_cursor*)cur; - switch( i ){ - case COMPLETION_COLUMN_CANDIDATE: { - sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT); - break; - } - case COMPLETION_COLUMN_PREFIX: { - sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT); - break; - } - case COMPLETION_COLUMN_WHOLELINE: { - sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT); - break; - } - case COMPLETION_COLUMN_PHASE: { - sqlite3_result_int(ctx, pCur->ePhase); - break; - } - } - return SQLITE_OK; -} - -/* -** Return the rowid for the current row. In this implementation, the -** rowid is the same as the output value. -*/ -static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - completion_cursor *pCur = (completion_cursor*)cur; - *pRowid = pCur->iRowid; - return SQLITE_OK; -} - -/* -** Return TRUE if the cursor has been moved off of the last -** row of output. -*/ -static int completionEof(sqlite3_vtab_cursor *cur){ - completion_cursor *pCur = (completion_cursor*)cur; - return pCur->ePhase >= COMPLETION_EOF; -} - -/* -** This method is called to "rewind" the completion_cursor object back -** to the first row of output. This method is always called at least -** once prior to any call to completionColumn() or completionRowid() or -** completionEof(). -*/ -static int completionFilter( - sqlite3_vtab_cursor *pVtabCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - completion_cursor *pCur = (completion_cursor *)pVtabCursor; - int iArg = 0; - (void)(idxStr); /* Unused parameter */ - (void)(argc); /* Unused parameter */ - completionCursorReset(pCur); - if( idxNum & 1 ){ - pCur->nPrefix = sqlite3_value_bytes(argv[iArg]); - if( pCur->nPrefix>0 ){ - pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); - if( pCur->zPrefix==0 ) return SQLITE_NOMEM; - } - iArg = 1; - } - if( idxNum & 2 ){ - pCur->nLine = sqlite3_value_bytes(argv[iArg]); - if( pCur->nLine>0 ){ - pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); - if( pCur->zLine==0 ) return SQLITE_NOMEM; - } - } - if( pCur->zLine!=0 && pCur->zPrefix==0 ){ - int i = pCur->nLine; - while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){ - i--; - } - pCur->nPrefix = pCur->nLine - i; - if( pCur->nPrefix>0 ){ - pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i); - if( pCur->zPrefix==0 ) return SQLITE_NOMEM; - } - } - pCur->iRowid = 0; - pCur->ePhase = COMPLETION_FIRST_PHASE; - return completionNext(pVtabCursor); -} - -/* -** SQLite will invoke this method one or more times while planning a query -** that uses the completion virtual table. This routine needs to create -** a query plan for each invocation and compute an estimated cost for that -** plan. -** -** There are two hidden parameters that act as arguments to the table-valued -** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix" -** is available and bit 1 is set if "wholeline" is available. -*/ -static int completionBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; /* Loop over constraints */ - int idxNum = 0; /* The query plan bitmask */ - int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */ - int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */ - int nArg = 0; /* Number of arguments that completeFilter() expects */ - const struct sqlite3_index_constraint *pConstraint; - - (void)(tab); /* Unused parameter */ - pConstraint = pIdxInfo->aConstraint; - for(i=0; inConstraint; i++, pConstraint++){ - if( pConstraint->usable==0 ) continue; - if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; - switch( pConstraint->iColumn ){ - case COMPLETION_COLUMN_PREFIX: - prefixIdx = i; - idxNum |= 1; - break; - case COMPLETION_COLUMN_WHOLELINE: - wholelineIdx = i; - idxNum |= 2; - break; - } - } - if( prefixIdx>=0 ){ - pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg; - pIdxInfo->aConstraintUsage[prefixIdx].omit = 1; - } - if( wholelineIdx>=0 ){ - pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg; - pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1; - } - pIdxInfo->idxNum = idxNum; - pIdxInfo->estimatedCost = (double)5000 - 1000*nArg; - pIdxInfo->estimatedRows = 500 - 100*nArg; - return SQLITE_OK; -} - -/* -** This following structure defines all the methods for the -** completion virtual table. -*/ -static sqlite3_module completionModule = { - 0, /* iVersion */ - 0, /* xCreate */ - completionConnect, /* xConnect */ - completionBestIndex, /* xBestIndex */ - completionDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - completionOpen, /* xOpen - open a cursor */ - completionClose, /* xClose - close a cursor */ - completionFilter, /* xFilter - configure scan constraints */ - completionNext, /* xNext - advance a cursor */ - completionEof, /* xEof - check for end of scan */ - completionColumn, /* xColumn - read data */ - completionRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0 /* xShadowName */ -}; - -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -int sqlite3CompletionVtabInit(sqlite3 *db){ - int rc = SQLITE_OK; -#ifndef SQLITE_OMIT_VIRTUALTABLE - rc = sqlite3_create_module(db, "completion", &completionModule, 0); -#endif - return rc; -} - -#ifdef _WIN32 - -#endif -int sqlite3_completion_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)(pzErrMsg); /* Unused parameter */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - rc = sqlite3CompletionVtabInit(db); -#endif - return rc; -} - -/************************* End ../ext/misc/completion.c ********************/ -/************************* Begin ../ext/misc/appendvfs.c ******************/ -/* -** 2017-10-20 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file implements a VFS shim that allows an SQLite database to be -** appended onto the end of some other file, such as an executable. -** -** A special record must appear at the end of the file that identifies the -** file as an appended database and provides an offset to page 1. For -** best performance page 1 should be located at a disk page boundary, though -** that is not required. -** -** When opening a database using this VFS, the connection might treat -** the file as an ordinary SQLite database, or it might treat is as a -** database appended onto some other file. Here are the rules: -** -** (1) When opening a new empty file, that file is treated as an ordinary -** database. -** -** (2) When opening a file that begins with the standard SQLite prefix -** string "SQLite format 3", that file is treated as an ordinary -** database. -** -** (3) When opening a file that ends with the appendvfs trailer string -** "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended -** database. -** -** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is -** set, then a new database is appended to the already existing file. -** -** (5) Otherwise, SQLITE_CANTOPEN is returned. -** -** To avoid unnecessary complications with the PENDING_BYTE, the size of -** the file containing the database is limited to 1GB. This VFS will refuse -** to read or write past the 1GB mark. This restriction might be lifted in -** future versions. For now, if you need a large database, then keep the -** database in a separate file. -** -** If the file being opened is not an appended database, then this shim is -** a pass-through into the default underlying VFS. -**/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include - -/* The append mark at the end of the database is: -** -** Start-Of-SQLite3-NNNNNNNN -** 123456789 123456789 12345 -** -** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is -** the offset to page 1. -*/ -#define APND_MARK_PREFIX "Start-Of-SQLite3-" -#define APND_MARK_PREFIX_SZ 17 -#define APND_MARK_SIZE 25 - -/* -** Maximum size of the combined prefix + database + append-mark. This -** must be less than 0x40000000 to avoid locking issues on Windows. -*/ -#define APND_MAX_SIZE (65536*15259) - -/* -** Forward declaration of objects used by this utility -*/ -typedef struct sqlite3_vfs ApndVfs; -typedef struct ApndFile ApndFile; - -/* Access to a lower-level VFS that (might) implement dynamic loading, -** access to randomness, etc. -*/ -#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData)) -#define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1)) - -/* An open file */ -struct ApndFile { - sqlite3_file base; /* IO methods */ - sqlite3_int64 iPgOne; /* File offset to page 1 */ - sqlite3_int64 iMark; /* Start of the append-mark */ -}; - -/* -** Methods for ApndFile -*/ -static int apndClose(sqlite3_file*); -static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); -static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); -static int apndTruncate(sqlite3_file*, sqlite3_int64 size); -static int apndSync(sqlite3_file*, int flags); -static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize); -static int apndLock(sqlite3_file*, int); -static int apndUnlock(sqlite3_file*, int); -static int apndCheckReservedLock(sqlite3_file*, int *pResOut); -static int apndFileControl(sqlite3_file*, int op, void *pArg); -static int apndSectorSize(sqlite3_file*); -static int apndDeviceCharacteristics(sqlite3_file*); -static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**); -static int apndShmLock(sqlite3_file*, int offset, int n, int flags); -static void apndShmBarrier(sqlite3_file*); -static int apndShmUnmap(sqlite3_file*, int deleteFlag); -static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); -static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p); - -/* -** Methods for ApndVfs -*/ -static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); -static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir); -static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *); -static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); -static void *apndDlOpen(sqlite3_vfs*, const char *zFilename); -static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg); -static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void); -static void apndDlClose(sqlite3_vfs*, void*); -static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut); -static int apndSleep(sqlite3_vfs*, int microseconds); -static int apndCurrentTime(sqlite3_vfs*, double*); -static int apndGetLastError(sqlite3_vfs*, int, char *); -static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); -static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr); -static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z); -static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName); - -static sqlite3_vfs apnd_vfs = { - 3, /* iVersion (set when registered) */ - 0, /* szOsFile (set when registered) */ - 1024, /* mxPathname */ - 0, /* pNext */ - "apndvfs", /* zName */ - 0, /* pAppData (set when registered) */ - apndOpen, /* xOpen */ - apndDelete, /* xDelete */ - apndAccess, /* xAccess */ - apndFullPathname, /* xFullPathname */ - apndDlOpen, /* xDlOpen */ - apndDlError, /* xDlError */ - apndDlSym, /* xDlSym */ - apndDlClose, /* xDlClose */ - apndRandomness, /* xRandomness */ - apndSleep, /* xSleep */ - apndCurrentTime, /* xCurrentTime */ - apndGetLastError, /* xGetLastError */ - apndCurrentTimeInt64, /* xCurrentTimeInt64 */ - apndSetSystemCall, /* xSetSystemCall */ - apndGetSystemCall, /* xGetSystemCall */ - apndNextSystemCall /* xNextSystemCall */ -}; - -static const sqlite3_io_methods apnd_io_methods = { - 3, /* iVersion */ - apndClose, /* xClose */ - apndRead, /* xRead */ - apndWrite, /* xWrite */ - apndTruncate, /* xTruncate */ - apndSync, /* xSync */ - apndFileSize, /* xFileSize */ - apndLock, /* xLock */ - apndUnlock, /* xUnlock */ - apndCheckReservedLock, /* xCheckReservedLock */ - apndFileControl, /* xFileControl */ - apndSectorSize, /* xSectorSize */ - apndDeviceCharacteristics, /* xDeviceCharacteristics */ - apndShmMap, /* xShmMap */ - apndShmLock, /* xShmLock */ - apndShmBarrier, /* xShmBarrier */ - apndShmUnmap, /* xShmUnmap */ - apndFetch, /* xFetch */ - apndUnfetch /* xUnfetch */ -}; - - - -/* -** Close an apnd-file. -*/ -static int apndClose(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xClose(pFile); -} - -/* -** Read data from an apnd-file. -*/ -static int apndRead( - sqlite3_file *pFile, - void *zBuf, - int iAmt, - sqlite_int64 iOfst -){ - ApndFile *p = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne); -} - -/* -** Add the append-mark onto the end of the file. -*/ -static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){ - int i; - unsigned char a[APND_MARK_SIZE]; - memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ); - for(i=0; i<8; i++){ - a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff; - } - return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark); -} - -/* -** Write data to an apnd-file. -*/ -static int apndWrite( - sqlite3_file *pFile, - const void *zBuf, - int iAmt, - sqlite_int64 iOfst -){ - int rc; - ApndFile *p = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL; - rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne); - if( rc==SQLITE_OK && iOfst + iAmt + p->iPgOne > p->iMark ){ - sqlite3_int64 sz = 0; - rc = pFile->pMethods->xFileSize(pFile, &sz); - if( rc==SQLITE_OK ){ - p->iMark = sz - APND_MARK_SIZE; - if( iOfst + iAmt + p->iPgOne > p->iMark ){ - p->iMark = p->iPgOne + iOfst + iAmt; - rc = apndWriteMark(p, pFile); - } - } - } - return rc; -} - -/* -** Truncate an apnd-file. -*/ -static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){ - int rc; - ApndFile *p = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE); - if( rc==SQLITE_OK ){ - p->iMark = p->iPgOne+size; - rc = apndWriteMark(p, pFile); - } - return rc; -} - -/* -** Sync an apnd-file. -*/ -static int apndSync(sqlite3_file *pFile, int flags){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xSync(pFile, flags); -} - -/* -** Return the current file-size of an apnd-file. -*/ -static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ - ApndFile *p = (ApndFile *)pFile; - int rc; - pFile = ORIGFILE(p); - rc = pFile->pMethods->xFileSize(pFile, pSize); - if( rc==SQLITE_OK && p->iPgOne ){ - *pSize -= p->iPgOne + APND_MARK_SIZE; - } - return rc; -} - -/* -** Lock an apnd-file. -*/ -static int apndLock(sqlite3_file *pFile, int eLock){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xLock(pFile, eLock); -} - -/* -** Unlock an apnd-file. -*/ -static int apndUnlock(sqlite3_file *pFile, int eLock){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xUnlock(pFile, eLock); -} - -/* -** Check if another file-handle holds a RESERVED lock on an apnd-file. -*/ -static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xCheckReservedLock(pFile, pResOut); -} - -/* -** File control method. For custom operations on an apnd-file. -*/ -static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){ - ApndFile *p = (ApndFile *)pFile; - int rc; - pFile = ORIGFILE(pFile); - rc = pFile->pMethods->xFileControl(pFile, op, pArg); - if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){ - *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg); - } - return rc; -} - -/* -** Return the sector-size in bytes for an apnd-file. -*/ -static int apndSectorSize(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xSectorSize(pFile); -} - -/* -** Return the device characteristic flags supported by an apnd-file. -*/ -static int apndDeviceCharacteristics(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xDeviceCharacteristics(pFile); -} - -/* Create a shared memory file mapping */ -static int apndShmMap( - sqlite3_file *pFile, - int iPg, - int pgsz, - int bExtend, - void volatile **pp -){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp); -} - -/* Perform locking on a shared-memory segment */ -static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xShmLock(pFile,offset,n,flags); -} - -/* Memory barrier operation on shared memory */ -static void apndShmBarrier(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - pFile->pMethods->xShmBarrier(pFile); -} - -/* Unmap a shared memory segment */ -static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xShmUnmap(pFile,deleteFlag); -} - -/* Fetch a page of a memory-mapped file */ -static int apndFetch( - sqlite3_file *pFile, - sqlite3_int64 iOfst, - int iAmt, - void **pp -){ - ApndFile *p = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp); -} - -/* Release a memory-mapped page */ -static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){ - ApndFile *p = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage); -} - -/* -** Check to see if the file is an ordinary SQLite database file. -*/ -static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){ - int rc; - char zHdr[16]; - static const char aSqliteHdr[] = "SQLite format 3"; - if( sz<512 ) return 0; - rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0); - if( rc ) return 0; - return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0; -} - -/* -** Try to read the append-mark off the end of a file. Return the -** start of the appended database if the append-mark is present. If -** there is no append-mark, return -1; -*/ -static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){ - int rc, i; - sqlite3_int64 iMark; - unsigned char a[APND_MARK_SIZE]; - - if( sz<=APND_MARK_SIZE ) return -1; - rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE); - if( rc ) return -1; - if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1; - iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56; - for(i=1; i<8; i++){ - iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i); - } - return iMark; -} - -/* -** Open an apnd file handle. -*/ -static int apndOpen( - sqlite3_vfs *pVfs, - const char *zName, - sqlite3_file *pFile, - int flags, - int *pOutFlags -){ - ApndFile *p; - sqlite3_file *pSubFile; - sqlite3_vfs *pSubVfs; - int rc; - sqlite3_int64 sz; - pSubVfs = ORIGVFS(pVfs); - if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){ - return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags); - } - p = (ApndFile*)pFile; - memset(p, 0, sizeof(*p)); - pSubFile = ORIGFILE(pFile); - pFile->pMethods = &apnd_io_methods; - rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags); - if( rc ) goto apnd_open_done; - rc = pSubFile->pMethods->xFileSize(pSubFile, &sz); - if( rc ){ - pSubFile->pMethods->xClose(pSubFile); - goto apnd_open_done; - } - if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){ - memmove(pFile, pSubFile, pSubVfs->szOsFile); - return SQLITE_OK; - } - p->iMark = 0; - p->iPgOne = apndReadMark(sz, pFile); - if( p->iPgOne>0 ){ - return SQLITE_OK; - } - if( (flags & SQLITE_OPEN_CREATE)==0 ){ - pSubFile->pMethods->xClose(pSubFile); - rc = SQLITE_CANTOPEN; - } - p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff; -apnd_open_done: - if( rc ) pFile->pMethods = 0; - return rc; -} - -/* -** All other VFS methods are pass-thrus. -*/ -static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ - return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync); -} -static int apndAccess( - sqlite3_vfs *pVfs, - const char *zPath, - int flags, - int *pResOut -){ - return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut); -} -static int apndFullPathname( - sqlite3_vfs *pVfs, - const char *zPath, - int nOut, - char *zOut -){ - return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut); -} -static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){ - return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath); -} -static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ - ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg); -} -static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ - return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym); -} -static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){ - ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle); -} -static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ - return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut); -} -static int apndSleep(sqlite3_vfs *pVfs, int nMicro){ - return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro); -} -static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ - return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut); -} -static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){ - return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b); -} -static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){ - return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p); -} -static int apndSetSystemCall( - sqlite3_vfs *pVfs, - const char *zName, - sqlite3_syscall_ptr pCall -){ - return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall); -} -static sqlite3_syscall_ptr apndGetSystemCall( - sqlite3_vfs *pVfs, - const char *zName -){ - return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName); -} -static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){ - return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName); -} - - -#ifdef _WIN32 - -#endif -/* -** This routine is called when the extension is loaded. -** Register the new VFS. -*/ -int sqlite3_appendvfs_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - sqlite3_vfs *pOrig; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; - (void)db; - pOrig = sqlite3_vfs_find(0); - apnd_vfs.iVersion = pOrig->iVersion; - apnd_vfs.pAppData = pOrig; - apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile); - rc = sqlite3_vfs_register(&apnd_vfs, 0); -#ifdef APPENDVFS_TEST - if( rc==SQLITE_OK ){ - rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister); - } -#endif - if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY; - return rc; -} - -/************************* End ../ext/misc/appendvfs.c ********************/ -/************************* Begin ../ext/misc/memtrace.c ******************/ -/* -** 2019-01-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 implements an extension that uses the SQLITE_CONFIG_MALLOC -** mechanism to add a tracing layer on top of SQLite. If this extension -** is registered prior to sqlite3_initialize(), it will cause all memory -** allocation activities to be logged on standard output, or to some other -** FILE specified by the initializer. -** -** This file needs to be compiled into the application that uses it. -** -** This extension is used to implement the --memtrace option of the -** command-line shell. -*/ -#include -#include -#include - -/* The original memory allocation routines */ -static sqlite3_mem_methods memtraceBase; -static FILE *memtraceOut; - -/* Methods that trace memory allocations */ -static void *memtraceMalloc(int n){ - if( memtraceOut ){ - fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n", - memtraceBase.xRoundup(n)); - } - return memtraceBase.xMalloc(n); -} -static void memtraceFree(void *p){ - if( p==0 ) return; - if( memtraceOut ){ - fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p)); - } - memtraceBase.xFree(p); -} -static void *memtraceRealloc(void *p, int n){ - if( p==0 ) return memtraceMalloc(n); - if( n==0 ){ - memtraceFree(p); - return 0; - } - if( memtraceOut ){ - fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n", - memtraceBase.xSize(p), memtraceBase.xRoundup(n)); - } - return memtraceBase.xRealloc(p, n); -} -static int memtraceSize(void *p){ - return memtraceBase.xSize(p); -} -static int memtraceRoundup(int n){ - return memtraceBase.xRoundup(n); -} -static int memtraceInit(void *p){ - return memtraceBase.xInit(p); -} -static void memtraceShutdown(void *p){ - memtraceBase.xShutdown(p); -} - -/* The substitute memory allocator */ -static sqlite3_mem_methods ersaztMethods = { - memtraceMalloc, - memtraceFree, - memtraceRealloc, - memtraceSize, - memtraceRoundup, - memtraceInit, - memtraceShutdown, - 0 -}; - -/* Begin tracing memory allocations to out. */ -int sqlite3MemTraceActivate(FILE *out){ - int rc = SQLITE_OK; - if( memtraceBase.xMalloc==0 ){ - rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase); - if( rc==SQLITE_OK ){ - rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods); - } - } - memtraceOut = out; - return rc; -} - -/* Deactivate memory tracing */ -int sqlite3MemTraceDeactivate(void){ - int rc = SQLITE_OK; - if( memtraceBase.xMalloc!=0 ){ - rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase); - if( rc==SQLITE_OK ){ - memset(&memtraceBase, 0, sizeof(memtraceBase)); - } - } - memtraceOut = 0; - return rc; -} - -/************************* End ../ext/misc/memtrace.c ********************/ -/************************* Begin ../ext/misc/uint.c ******************/ -/* -** 2020-04-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 SQLite extension implements the UINT collating sequence. -** -** UINT works like BINARY for text, except that embedded strings -** of digits compare in numeric order. -** -** * Leading zeros are handled properly, in the sense that -** they do not mess of the maginitude comparison of embedded -** strings of digits. "x00123y" is equal to "x123y". -** -** * Only unsigned integers are recognized. Plus and minus -** signs are ignored. Decimal points and exponential notation -** are ignored. -** -** * Embedded integers can be of arbitrary length. Comparison -** is *not* limited integers that can be expressed as a -** 64-bit machine integer. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -/* -** Compare text in lexicographic order, except strings of digits -** compare in numeric order. -*/ -static int uintCollFunc( - void *notUsed, - int nKey1, const void *pKey1, - int nKey2, const void *pKey2 -){ - const unsigned char *zA = (const unsigned char*)pKey1; - const unsigned char *zB = (const unsigned char*)pKey2; - int i=0, j=0, x; - (void)notUsed; - while( i -#include -#include -#include - -/* Mark a function parameter as unused, to suppress nuisance compiler -** warnings. */ -#ifndef UNUSED_PARAMETER -# define UNUSED_PARAMETER(X) (void)(X) -#endif - - -/* A decimal object */ -typedef struct Decimal Decimal; -struct Decimal { - char sign; /* 0 for positive, 1 for negative */ - char oom; /* True if an OOM is encountered */ - char isNull; /* True if holds a NULL rather than a number */ - char isInit; /* True upon initialization */ - int nDigit; /* Total number of digits */ - int nFrac; /* Number of digits to the right of the decimal point */ - signed char *a; /* Array of digits. Most significant first. */ -}; - -/* -** Release memory held by a Decimal, but do not free the object itself. -*/ -static void decimal_clear(Decimal *p){ - sqlite3_free(p->a); -} - -/* -** Destroy a Decimal object -*/ -static void decimal_free(Decimal *p){ - if( p ){ - decimal_clear(p); - sqlite3_free(p); - } -} - -/* -** Allocate a new Decimal object. Initialize it to the number given -** by the input string. -*/ -static Decimal *decimal_new( - sqlite3_context *pCtx, - sqlite3_value *pIn, - int nAlt, - const unsigned char *zAlt -){ - Decimal *p; - int n, i; - const unsigned char *zIn; - int iExp = 0; - p = sqlite3_malloc( sizeof(*p) ); - if( p==0 ) goto new_no_mem; - p->sign = 0; - p->oom = 0; - p->isInit = 1; - p->isNull = 0; - p->nDigit = 0; - p->nFrac = 0; - if( zAlt ){ - n = nAlt, - zIn = zAlt; - }else{ - if( sqlite3_value_type(pIn)==SQLITE_NULL ){ - p->a = 0; - p->isNull = 1; - return p; - } - n = sqlite3_value_bytes(pIn); - zIn = sqlite3_value_text(pIn); - } - p->a = sqlite3_malloc64( n+1 ); - if( p->a==0 ) goto new_no_mem; - for(i=0; isspace(zIn[i]); i++){} - if( zIn[i]=='-' ){ - p->sign = 1; - i++; - }else if( zIn[i]=='+' ){ - i++; - } - while( i='0' && c<='9' ){ - p->a[p->nDigit++] = c - '0'; - }else if( c=='.' ){ - p->nFrac = p->nDigit + 1; - }else if( c=='e' || c=='E' ){ - int j = i+1; - int neg = 0; - if( j>=n ) break; - if( zIn[j]=='-' ){ - neg = 1; - j++; - }else if( zIn[j]=='+' ){ - j++; - } - while( j='0' && zIn[j]<='9' ){ - iExp = iExp*10 + zIn[j] - '0'; - } - j++; - } - if( neg ) iExp = -iExp; - break; - } - i++; - } - if( p->nFrac ){ - p->nFrac = p->nDigit - (p->nFrac - 1); - } - if( iExp>0 ){ - if( p->nFrac>0 ){ - if( iExp<=p->nFrac ){ - p->nFrac -= iExp; - iExp = 0; - }else{ - iExp -= p->nFrac; - p->nFrac = 0; - } - } - if( iExp>0 ){ - p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); - if( p->a==0 ) goto new_no_mem; - memset(p->a+p->nDigit, 0, iExp); - p->nDigit += iExp; - } - }else if( iExp<0 ){ - int nExtra; - iExp = -iExp; - nExtra = p->nDigit - p->nFrac - 1; - if( nExtra ){ - if( nExtra>=iExp ){ - p->nFrac += iExp; - iExp = 0; - }else{ - iExp -= nExtra; - p->nFrac = p->nDigit - 1; - } - } - if( iExp>0 ){ - p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); - if( p->a==0 ) goto new_no_mem; - memmove(p->a+iExp, p->a, p->nDigit); - memset(p->a, 0, iExp); - p->nDigit += iExp; - p->nFrac += iExp; - } - } - return p; - -new_no_mem: - if( pCtx ) sqlite3_result_error_nomem(pCtx); - sqlite3_free(p); - return 0; -} - -/* -** Make the given Decimal the result. -*/ -static void decimal_result(sqlite3_context *pCtx, Decimal *p){ - char *z; - int i, j; - int n; - if( p==0 || p->oom ){ - sqlite3_result_error_nomem(pCtx); - return; - } - if( p->isNull ){ - sqlite3_result_null(pCtx); - return; - } - z = sqlite3_malloc( p->nDigit+4 ); - if( z==0 ){ - sqlite3_result_error_nomem(pCtx); - return; - } - i = 0; - if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){ - p->sign = 0; - } - if( p->sign ){ - z[0] = '-'; - i = 1; - } - n = p->nDigit - p->nFrac; - if( n<=0 ){ - z[i++] = '0'; - } - j = 0; - while( n>1 && p->a[j]==0 ){ - j++; - n--; - } - while( n>0 ){ - z[i++] = p->a[j] + '0'; - j++; - n--; - } - if( p->nFrac ){ - z[i++] = '.'; - do{ - z[i++] = p->a[j] + '0'; - j++; - }while( jnDigit ); - } - z[i] = 0; - sqlite3_result_text(pCtx, z, i, sqlite3_free); -} - -/* -** SQL Function: decimal(X) -** -** Convert input X into decimal and then back into text -*/ -static void decimalFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *p = decimal_new(context, argv[0], 0, 0); - UNUSED_PARAMETER(argc); - decimal_result(context, p); - decimal_free(p); -} - -/* -** Compare to Decimal objects. Return negative, 0, or positive if the -** first object is less than, equal to, or greater than the second. -** -** Preconditions for this routine: -** -** pA!=0 -** pA->isNull==0 -** pB!=0 -** pB->isNull==0 -*/ -static int decimal_cmp(const Decimal *pA, const Decimal *pB){ - int nASig, nBSig, rc, n; - if( pA->sign!=pB->sign ){ - return pA->sign ? -1 : +1; - } - if( pA->sign ){ - const Decimal *pTemp = pA; - pA = pB; - pB = pTemp; - } - nASig = pA->nDigit - pA->nFrac; - nBSig = pB->nDigit - pB->nFrac; - if( nASig!=nBSig ){ - return nASig - nBSig; - } - n = pA->nDigit; - if( n>pB->nDigit ) n = pB->nDigit; - rc = memcmp(pA->a, pB->a, n); - if( rc==0 ){ - rc = pA->nDigit - pB->nDigit; - } - return rc; -} - -/* -** SQL Function: decimal_cmp(X, Y) -** -** Return negative, zero, or positive if X is less then, equal to, or -** greater than Y. -*/ -static void decimalCmpFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = 0, *pB = 0; - int rc; - - UNUSED_PARAMETER(argc); - pA = decimal_new(context, argv[0], 0, 0); - if( pA==0 || pA->isNull ) goto cmp_done; - pB = decimal_new(context, argv[1], 0, 0); - if( pB==0 || pB->isNull ) goto cmp_done; - rc = decimal_cmp(pA, pB); - if( rc<0 ) rc = -1; - else if( rc>0 ) rc = +1; - sqlite3_result_int(context, rc); -cmp_done: - decimal_free(pA); - decimal_free(pB); -} - -/* -** Expand the Decimal so that it has a least nDigit digits and nFrac -** digits to the right of the decimal point. -*/ -static void decimal_expand(Decimal *p, int nDigit, int nFrac){ - int nAddSig; - int nAddFrac; - if( p==0 ) return; - nAddFrac = nFrac - p->nFrac; - nAddSig = (nDigit - p->nDigit) - nAddFrac; - if( nAddFrac==0 && nAddSig==0 ) return; - p->a = sqlite3_realloc64(p->a, nDigit+1); - if( p->a==0 ){ - p->oom = 1; - return; - } - if( nAddSig ){ - memmove(p->a+nAddSig, p->a, p->nDigit); - memset(p->a, 0, nAddSig); - p->nDigit += nAddSig; - } - if( nAddFrac ){ - memset(p->a+p->nDigit, 0, nAddFrac); - p->nDigit += nAddFrac; - p->nFrac += nAddFrac; - } -} - -/* -** Add the value pB into pA. -** -** Both pA and pB might become denormalized by this routine. -*/ -static void decimal_add(Decimal *pA, Decimal *pB){ - int nSig, nFrac, nDigit; - int i, rc; - if( pA==0 ){ - return; - } - if( pA->oom || pB==0 || pB->oom ){ - pA->oom = 1; - return; - } - if( pA->isNull || pB->isNull ){ - pA->isNull = 1; - return; - } - nSig = pA->nDigit - pA->nFrac; - if( nSig && pA->a[0]==0 ) nSig--; - if( nSignDigit-pB->nFrac ){ - nSig = pB->nDigit - pB->nFrac; - } - nFrac = pA->nFrac; - if( nFracnFrac ) nFrac = pB->nFrac; - nDigit = nSig + nFrac + 1; - decimal_expand(pA, nDigit, nFrac); - decimal_expand(pB, nDigit, nFrac); - if( pA->oom || pB->oom ){ - pA->oom = 1; - }else{ - if( pA->sign==pB->sign ){ - int carry = 0; - for(i=nDigit-1; i>=0; i--){ - int x = pA->a[i] + pB->a[i] + carry; - if( x>=10 ){ - carry = 1; - pA->a[i] = x - 10; - }else{ - carry = 0; - pA->a[i] = x; - } - } - }else{ - signed char *aA, *aB; - int borrow = 0; - rc = memcmp(pA->a, pB->a, nDigit); - if( rc<0 ){ - aA = pB->a; - aB = pA->a; - pA->sign = !pA->sign; - }else{ - aA = pA->a; - aB = pB->a; - } - for(i=nDigit-1; i>=0; i--){ - int x = aA[i] - aB[i] - borrow; - if( x<0 ){ - pA->a[i] = x+10; - borrow = 1; - }else{ - pA->a[i] = x; - borrow = 0; - } - } - } - } -} - -/* -** Compare text in decimal order. -*/ -static int decimalCollFunc( - void *notUsed, - int nKey1, const void *pKey1, - int nKey2, const void *pKey2 -){ - const unsigned char *zA = (const unsigned char*)pKey1; - const unsigned char *zB = (const unsigned char*)pKey2; - Decimal *pA = decimal_new(0, 0, nKey1, zA); - Decimal *pB = decimal_new(0, 0, nKey2, zB); - int rc; - UNUSED_PARAMETER(notUsed); - if( pA==0 || pB==0 ){ - rc = 0; - }else{ - rc = decimal_cmp(pA, pB); - } - decimal_free(pA); - decimal_free(pB); - return rc; -} - - -/* -** SQL Function: decimal_add(X, Y) -** decimal_sub(X, Y) -** -** Return the sum or difference of X and Y. -*/ -static void decimalAddFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = decimal_new(context, argv[0], 0, 0); - Decimal *pB = decimal_new(context, argv[1], 0, 0); - UNUSED_PARAMETER(argc); - decimal_add(pA, pB); - decimal_result(context, pA); - decimal_free(pA); - decimal_free(pB); -} -static void decimalSubFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = decimal_new(context, argv[0], 0, 0); - Decimal *pB = decimal_new(context, argv[1], 0, 0); - UNUSED_PARAMETER(argc); - if( pB==0 ) return; - pB->sign = !pB->sign; - decimal_add(pA, pB); - decimal_result(context, pA); - decimal_free(pA); - decimal_free(pB); -} - -/* Aggregate funcion: decimal_sum(X) -** -** Works like sum() except that it uses decimal arithmetic for unlimited -** precision. -*/ -static void decimalSumStep( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *p; - Decimal *pArg; - UNUSED_PARAMETER(argc); - p = sqlite3_aggregate_context(context, sizeof(*p)); - if( p==0 ) return; - if( !p->isInit ){ - p->isInit = 1; - p->a = sqlite3_malloc(2); - if( p->a==0 ){ - p->oom = 1; - }else{ - p->a[0] = 0; - } - p->nDigit = 1; - p->nFrac = 0; - } - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - pArg = decimal_new(context, argv[0], 0, 0); - decimal_add(p, pArg); - decimal_free(pArg); -} -static void decimalSumInverse( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *p; - Decimal *pArg; - UNUSED_PARAMETER(argc); - p = sqlite3_aggregate_context(context, sizeof(*p)); - if( p==0 ) return; - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - pArg = decimal_new(context, argv[0], 0, 0); - if( pArg ) pArg->sign = !pArg->sign; - decimal_add(p, pArg); - decimal_free(pArg); -} -static void decimalSumValue(sqlite3_context *context){ - Decimal *p = sqlite3_aggregate_context(context, 0); - if( p==0 ) return; - decimal_result(context, p); -} -static void decimalSumFinalize(sqlite3_context *context){ - Decimal *p = sqlite3_aggregate_context(context, 0); - if( p==0 ) return; - decimal_result(context, p); - decimal_clear(p); -} - -/* -** SQL Function: decimal_mul(X, Y) -** -** Return the product of X and Y. -** -** All significant digits after the decimal point are retained. -** Trailing zeros after the decimal point are omitted as long as -** the number of digits after the decimal point is no less than -** either the number of digits in either input. -*/ -static void decimalMulFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = decimal_new(context, argv[0], 0, 0); - Decimal *pB = decimal_new(context, argv[1], 0, 0); - signed char *acc = 0; - int i, j, k; - int minFrac; - UNUSED_PARAMETER(argc); - if( pA==0 || pA->oom || pA->isNull - || pB==0 || pB->oom || pB->isNull - ){ - goto mul_end; - } - acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 ); - if( acc==0 ){ - sqlite3_result_error_nomem(context); - goto mul_end; - } - memset(acc, 0, pA->nDigit + pB->nDigit + 2); - minFrac = pA->nFrac; - if( pB->nFracnFrac; - for(i=pA->nDigit-1; i>=0; i--){ - signed char f = pA->a[i]; - int carry = 0, x; - for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){ - x = acc[k] + f*pB->a[j] + carry; - acc[k] = x%10; - carry = x/10; - } - x = acc[k] + carry; - acc[k] = x%10; - acc[k-1] += x/10; - } - sqlite3_free(pA->a); - pA->a = acc; - acc = 0; - pA->nDigit += pB->nDigit + 2; - pA->nFrac += pB->nFrac; - pA->sign ^= pB->sign; - while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){ - pA->nFrac--; - pA->nDigit--; - } - decimal_result(context, pA); - -mul_end: - sqlite3_free(acc); - decimal_free(pA); - decimal_free(pB); -} - -#ifdef _WIN32 - -#endif -int sqlite3_decimal_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - static const struct { - const char *zFuncName; - int nArg; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } aFunc[] = { - { "decimal", 1, decimalFunc }, - { "decimal_cmp", 2, decimalCmpFunc }, - { "decimal_add", 2, decimalAddFunc }, - { "decimal_sub", 2, decimalSubFunc }, - { "decimal_mul", 2, decimalMulFunc }, - }; - unsigned int i; - (void)pzErrMsg; /* Unused parameter */ - - SQLITE_EXTENSION_INIT2(pApi); - - for(i=0; i 'ieee754(2,0)' -** ieee754(45.25) -> 'ieee754(181,-2)' -** ieee754(2, 0) -> 2.0 -** ieee754(181, -2) -> 45.25 -** -** Two additional functions break apart the one-argument ieee754() -** result into separate integer values: -** -** ieee754_mantissa(45.25) -> 181 -** ieee754_exponent(45.25) -> -2 -** -** These functions convert binary64 numbers into blobs and back again. -** -** ieee754_from_blob(x'3ff0000000000000') -> 1.0 -** ieee754_to_blob(1.0) -> x'3ff0000000000000' -** -** In all single-argument functions, if the argument is an 8-byte blob -** then that blob is interpreted as a big-endian binary64 value. -** -** -** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES -** ----------------------------------------------- -** -** This extension in combination with the separate 'decimal' extension -** can be used to compute the exact decimal representation of binary64 -** values. To begin, first compute a table of exponent values: -** -** CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT); -** WITH RECURSIVE c(x,v) AS ( -** VALUES(0,'1') -** UNION ALL -** SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971 -** ) INSERT INTO pow2(x,v) SELECT x, v FROM c; -** WITH RECURSIVE c(x,v) AS ( -** VALUES(-1,'0.5') -** UNION ALL -** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075 -** ) INSERT INTO pow2(x,v) SELECT x, v FROM c; -** -** Then, to compute the exact decimal representation of a floating -** point value (the value 47.49 is used in the example) do: -** -** WITH c(n) AS (VALUES(47.49)) -** ---------------^^^^^---- Replace with whatever you want -** SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v) -** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n); -** -** Here is a query to show various boundry values for the binary64 -** number format: -** -** WITH c(name,bin) AS (VALUES -** ('minimum positive value', x'0000000000000001'), -** ('maximum subnormal value', x'000fffffffffffff'), -** ('mininum positive nornal value', x'0010000000000000'), -** ('maximum value', x'7fefffffffffffff')) -** SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v) -** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin); -** -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include - -/* Mark a function parameter as unused, to suppress nuisance compiler -** warnings. */ -#ifndef UNUSED_PARAMETER -# define UNUSED_PARAMETER(X) (void)(X) -#endif - -/* -** Implementation of the ieee754() function -*/ -static void ieee754func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - if( argc==1 ){ - sqlite3_int64 m, a; - double r; - int e; - int isNeg; - char zResult[100]; - assert( sizeof(m)==sizeof(r) ); - if( sqlite3_value_type(argv[0])==SQLITE_BLOB - && sqlite3_value_bytes(argv[0])==sizeof(r) - ){ - const unsigned char *x = sqlite3_value_blob(argv[0]); - unsigned int i; - sqlite3_uint64 v = 0; - for(i=0; i>52; - m = a & ((((sqlite3_int64)1)<<52)-1); - if( e==0 ){ - m <<= 1; - }else{ - m |= ((sqlite3_int64)1)<<52; - } - while( e<1075 && m>0 && (m&1)==0 ){ - m >>= 1; - e++; - } - if( isNeg ) m = -m; - } - switch( *(int*)sqlite3_user_data(context) ){ - case 0: - sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)", - m, e-1075); - sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT); - break; - case 1: - sqlite3_result_int64(context, m); - break; - case 2: - sqlite3_result_int(context, e-1075); - break; - } - }else{ - sqlite3_int64 m, e, a; - double r; - int isNeg = 0; - m = sqlite3_value_int64(argv[0]); - e = sqlite3_value_int64(argv[1]); - if( m<0 ){ - isNeg = 1; - m = -m; - if( m<0 ) return; - }else if( m==0 && e>-1000 && e<1000 ){ - sqlite3_result_double(context, 0.0); - return; - } - while( (m>>32)&0xffe00000 ){ - m >>= 1; - e++; - } - while( m!=0 && ((m>>32)&0xfff00000)==0 ){ - m <<= 1; - e--; - } - e += 1075; - if( e<=0 ){ - /* Subnormal */ - m >>= 1-e; - e = 0; - }else if( e>0x7ff ){ - e = 0x7ff; - } - a = m & ((((sqlite3_int64)1)<<52)-1); - a |= e<<52; - if( isNeg ) a |= ((sqlite3_uint64)1)<<63; - memcpy(&r, &a, sizeof(r)); - sqlite3_result_double(context, r); - } -} - -/* -** Functions to convert between blobs and floats. -*/ -static void ieee754func_from_blob( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - UNUSED_PARAMETER(argc); - if( sqlite3_value_type(argv[0])==SQLITE_BLOB - && sqlite3_value_bytes(argv[0])==sizeof(double) - ){ - double r; - const unsigned char *x = sqlite3_value_blob(argv[0]); - unsigned int i; - sqlite3_uint64 v = 0; - for(i=0; i>= 8; - } - sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT); - } -} - - -#ifdef _WIN32 - -#endif -int sqlite3_ieee_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - static const struct { - char *zFName; - int nArg; - int iAux; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } aFunc[] = { - { "ieee754", 1, 0, ieee754func }, - { "ieee754", 2, 0, ieee754func }, - { "ieee754_mantissa", 1, 1, ieee754func }, - { "ieee754_exponent", 1, 2, ieee754func }, - { "ieee754_to_blob", 1, 0, ieee754func_to_blob }, - { "ieee754_from_blob", 1, 0, ieee754func_from_blob }, - - }; - unsigned int i; - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - for(i=0; i -#include -#include - -#include - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -#ifndef SQLITE_AMALGAMATION - -/* typedef sqlite3_int64 i64; */ -/* typedef unsigned char u8; */ -typedef unsigned short u16; -typedef unsigned long u32; -#define MIN(a,b) ((a)<(b) ? (a) : (b)) - -#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 - -#endif /* SQLITE_AMALGAMATION */ - -/* -** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. -** -** In some ways it would be better to obtain these values from system -** header files. But, the dependency is undesirable and (a) these -** have been stable for decades, (b) the values are part of POSIX and -** are also made explicit in [man stat], and (c) are part of the -** file format for zip archives. -*/ -#ifndef S_IFDIR -# define S_IFDIR 0040000 -#endif -#ifndef S_IFREG -# define S_IFREG 0100000 -#endif -#ifndef S_IFLNK -# define S_IFLNK 0120000 -#endif - -static const char ZIPFILE_SCHEMA[] = - "CREATE TABLE y(" - "name PRIMARY KEY," /* 0: Name of file in zip archive */ - "mode," /* 1: POSIX mode for file */ - "mtime," /* 2: Last modification time (secs since 1970)*/ - "sz," /* 3: Size of object */ - "rawdata," /* 4: Raw data */ - "data," /* 5: Uncompressed data */ - "method," /* 6: Compression method (integer) */ - "z HIDDEN" /* 7: Name of zip file */ - ") WITHOUT ROWID;"; - -#define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ -#define ZIPFILE_BUFFER_SIZE (64*1024) - - -/* -** Magic numbers used to read and write zip files. -** -** ZIPFILE_NEWENTRY_MADEBY: -** Use this value for the "version-made-by" field in new zip file -** entries. The upper byte indicates "unix", and the lower byte -** indicates that the zip file matches pkzip specification 3.0. -** This is what info-zip seems to do. -** -** ZIPFILE_NEWENTRY_REQUIRED: -** Value for "version-required-to-extract" field of new entries. -** Version 2.0 is required to support folders and deflate compression. -** -** ZIPFILE_NEWENTRY_FLAGS: -** Value for "general-purpose-bit-flags" field of new entries. Bit -** 11 means "utf-8 filename and comment". -** -** ZIPFILE_SIGNATURE_CDS: -** First 4 bytes of a valid CDS record. -** -** ZIPFILE_SIGNATURE_LFH: -** First 4 bytes of a valid LFH record. -** -** ZIPFILE_SIGNATURE_EOCD -** First 4 bytes of a valid EOCD record. -*/ -#define ZIPFILE_EXTRA_TIMESTAMP 0x5455 -#define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) -#define ZIPFILE_NEWENTRY_REQUIRED 20 -#define ZIPFILE_NEWENTRY_FLAGS 0x800 -#define ZIPFILE_SIGNATURE_CDS 0x02014b50 -#define ZIPFILE_SIGNATURE_LFH 0x04034b50 -#define ZIPFILE_SIGNATURE_EOCD 0x06054b50 - -/* -** The sizes of the fixed-size part of each of the three main data -** structures in a zip archive. -*/ -#define ZIPFILE_LFH_FIXED_SZ 30 -#define ZIPFILE_EOCD_FIXED_SZ 22 -#define ZIPFILE_CDS_FIXED_SZ 46 - -/* -*** 4.3.16 End of central directory record: -*** -*** end of central dir signature 4 bytes (0x06054b50) -*** number of this disk 2 bytes -*** number of the disk with the -*** start of the central directory 2 bytes -*** total number of entries in the -*** central directory on this disk 2 bytes -*** total number of entries in -*** the central directory 2 bytes -*** size of the central directory 4 bytes -*** offset of start of central -*** directory with respect to -*** the starting disk number 4 bytes -*** .ZIP file comment length 2 bytes -*** .ZIP file comment (variable size) -*/ -typedef struct ZipfileEOCD ZipfileEOCD; -struct ZipfileEOCD { - u16 iDisk; - u16 iFirstDisk; - u16 nEntry; - u16 nEntryTotal; - u32 nSize; - u32 iOffset; -}; - -/* -*** 4.3.12 Central directory structure: -*** -*** ... -*** -*** central file header signature 4 bytes (0x02014b50) -*** version made by 2 bytes -*** version needed to extract 2 bytes -*** general purpose bit flag 2 bytes -*** compression method 2 bytes -*** last mod file time 2 bytes -*** last mod file date 2 bytes -*** crc-32 4 bytes -*** compressed size 4 bytes -*** uncompressed size 4 bytes -*** file name length 2 bytes -*** extra field length 2 bytes -*** file comment length 2 bytes -*** disk number start 2 bytes -*** internal file attributes 2 bytes -*** external file attributes 4 bytes -*** relative offset of local header 4 bytes -*/ -typedef struct ZipfileCDS ZipfileCDS; -struct ZipfileCDS { - u16 iVersionMadeBy; - u16 iVersionExtract; - u16 flags; - u16 iCompression; - u16 mTime; - u16 mDate; - u32 crc32; - u32 szCompressed; - u32 szUncompressed; - u16 nFile; - u16 nExtra; - u16 nComment; - u16 iDiskStart; - u16 iInternalAttr; - u32 iExternalAttr; - u32 iOffset; - char *zFile; /* Filename (sqlite3_malloc()) */ -}; - -/* -*** 4.3.7 Local file header: -*** -*** local file header signature 4 bytes (0x04034b50) -*** version needed to extract 2 bytes -*** general purpose bit flag 2 bytes -*** compression method 2 bytes -*** last mod file time 2 bytes -*** last mod file date 2 bytes -*** crc-32 4 bytes -*** compressed size 4 bytes -*** uncompressed size 4 bytes -*** file name length 2 bytes -*** extra field length 2 bytes -*** -*/ -typedef struct ZipfileLFH ZipfileLFH; -struct ZipfileLFH { - u16 iVersionExtract; - u16 flags; - u16 iCompression; - u16 mTime; - u16 mDate; - u32 crc32; - u32 szCompressed; - u32 szUncompressed; - u16 nFile; - u16 nExtra; -}; - -typedef struct ZipfileEntry ZipfileEntry; -struct ZipfileEntry { - ZipfileCDS cds; /* Parsed CDS record */ - u32 mUnixTime; /* Modification time, in UNIX format */ - u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ - i64 iDataOff; /* Offset to data in file (if aData==0) */ - u8 *aData; /* cds.szCompressed bytes of compressed data */ - ZipfileEntry *pNext; /* Next element in in-memory CDS */ -}; - -/* -** Cursor type for zipfile tables. -*/ -typedef struct ZipfileCsr ZipfileCsr; -struct ZipfileCsr { - sqlite3_vtab_cursor base; /* Base class - must be first */ - i64 iId; /* Cursor ID */ - u8 bEof; /* True when at EOF */ - u8 bNoop; /* If next xNext() call is no-op */ - - /* Used outside of write transactions */ - FILE *pFile; /* Zip file */ - i64 iNextOff; /* Offset of next record in central directory */ - ZipfileEOCD eocd; /* Parse of central directory record */ - - ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ - ZipfileEntry *pCurrent; /* Current entry */ - ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ -}; - -typedef struct ZipfileTab ZipfileTab; -struct ZipfileTab { - sqlite3_vtab base; /* Base class - must be first */ - char *zFile; /* Zip file this table accesses (may be NULL) */ - sqlite3 *db; /* Host database connection */ - u8 *aBuffer; /* Temporary buffer used for various tasks */ - - ZipfileCsr *pCsrList; /* List of cursors */ - i64 iNextCsrid; - - /* The following are used by write transactions only */ - ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ - ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ - FILE *pWriteFd; /* File handle open on zip archive */ - i64 szCurrent; /* Current size of zip archive */ - i64 szOrig; /* Size of archive at start of transaction */ -}; - -/* -** Set the error message contained in context ctx to the results of -** vprintf(zFmt, ...). -*/ -static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ - char *zMsg = 0; - va_list ap; - va_start(ap, zFmt); - zMsg = sqlite3_vmprintf(zFmt, ap); - sqlite3_result_error(ctx, zMsg, -1); - sqlite3_free(zMsg); - va_end(ap); -} - -/* -** If string zIn is quoted, dequote it in place. Otherwise, if the string -** is not quoted, do nothing. -*/ -static void zipfileDequote(char *zIn){ - char q = zIn[0]; - if( q=='"' || q=='\'' || q=='`' || q=='[' ){ - int iIn = 1; - int iOut = 0; - if( q=='[' ) q = ']'; - while( ALWAYS(zIn[iIn]) ){ - char c = zIn[iIn++]; - if( c==q && zIn[iIn++]!=q ) break; - zIn[iOut++] = c; - } - zIn[iOut] = '\0'; - } -} - -/* -** Construct a new ZipfileTab virtual table object. -** -** argv[0] -> module name ("zipfile") -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> "column name" and other module argument fields. -*/ -static int zipfileConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; - int nFile = 0; - const char *zFile = 0; - ZipfileTab *pNew = 0; - int rc; - - /* If the table name is not "zipfile", require that the argument be - ** specified. This stops zipfile tables from being created as: - ** - ** CREATE VIRTUAL TABLE zzz USING zipfile(); - ** - ** It does not prevent: - ** - ** CREATE VIRTUAL TABLE zipfile USING zipfile(); - */ - assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); - if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ - *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); - return SQLITE_ERROR; - } - - if( argc>3 ){ - zFile = argv[3]; - nFile = (int)strlen(zFile)+1; - } - - rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); - if( rc==SQLITE_OK ){ - pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, nByte+nFile); - pNew->db = db; - pNew->aBuffer = (u8*)&pNew[1]; - if( zFile ){ - pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; - memcpy(pNew->zFile, zFile, nFile); - zipfileDequote(pNew->zFile); - } - } - sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); - *ppVtab = (sqlite3_vtab*)pNew; - return rc; -} - -/* -** Free the ZipfileEntry structure indicated by the only argument. -*/ -static void zipfileEntryFree(ZipfileEntry *p){ - if( p ){ - sqlite3_free(p->cds.zFile); - sqlite3_free(p); - } -} - -/* -** Release resources that should be freed at the end of a write -** transaction. -*/ -static void zipfileCleanupTransaction(ZipfileTab *pTab){ - ZipfileEntry *pEntry; - ZipfileEntry *pNext; - - if( pTab->pWriteFd ){ - fclose(pTab->pWriteFd); - pTab->pWriteFd = 0; - } - for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ - pNext = pEntry->pNext; - zipfileEntryFree(pEntry); - } - pTab->pFirstEntry = 0; - pTab->pLastEntry = 0; - pTab->szCurrent = 0; - pTab->szOrig = 0; -} - -/* -** This method is the destructor for zipfile vtab objects. -*/ -static int zipfileDisconnect(sqlite3_vtab *pVtab){ - zipfileCleanupTransaction((ZipfileTab*)pVtab); - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* -** Constructor for a new ZipfileCsr object. -*/ -static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ - ZipfileTab *pTab = (ZipfileTab*)p; - ZipfileCsr *pCsr; - pCsr = sqlite3_malloc(sizeof(*pCsr)); - *ppCsr = (sqlite3_vtab_cursor*)pCsr; - if( pCsr==0 ){ - return SQLITE_NOMEM; - } - memset(pCsr, 0, sizeof(*pCsr)); - pCsr->iId = ++pTab->iNextCsrid; - pCsr->pCsrNext = pTab->pCsrList; - pTab->pCsrList = pCsr; - return SQLITE_OK; -} - -/* -** Reset a cursor back to the state it was in when first returned -** by zipfileOpen(). -*/ -static void zipfileResetCursor(ZipfileCsr *pCsr){ - ZipfileEntry *p; - ZipfileEntry *pNext; - - pCsr->bEof = 0; - if( pCsr->pFile ){ - fclose(pCsr->pFile); - pCsr->pFile = 0; - zipfileEntryFree(pCsr->pCurrent); - pCsr->pCurrent = 0; - } - - for(p=pCsr->pFreeEntry; p; p=pNext){ - pNext = p->pNext; - zipfileEntryFree(p); - } -} - -/* -** Destructor for an ZipfileCsr. -*/ -static int zipfileClose(sqlite3_vtab_cursor *cur){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); - ZipfileCsr **pp; - zipfileResetCursor(pCsr); - - /* Remove this cursor from the ZipfileTab.pCsrList list. */ - for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); - *pp = pCsr->pCsrNext; - - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Set the error message for the virtual table associated with cursor -** pCsr to the results of vprintf(zFmt, ...). -*/ -static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ - va_list ap; - va_start(ap, zFmt); - sqlite3_free(pTab->base.zErrMsg); - pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); - va_end(ap); -} -static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ - va_list ap; - va_start(ap, zFmt); - sqlite3_free(pCsr->base.pVtab->zErrMsg); - pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); - va_end(ap); -} - -/* -** Read nRead bytes of data from offset iOff of file pFile into buffer -** aRead[]. Return SQLITE_OK if successful, or an SQLite error code -** otherwise. -** -** If an error does occur, output variable (*pzErrmsg) may be set to point -** to an English language error message. It is the responsibility of the -** caller to eventually free this buffer using -** sqlite3_free(). -*/ -static int zipfileReadData( - FILE *pFile, /* Read from this file */ - u8 *aRead, /* Read into this buffer */ - int nRead, /* Number of bytes to read */ - i64 iOff, /* Offset to read from */ - char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ -){ - size_t n; - fseek(pFile, (long)iOff, SEEK_SET); - n = fread(aRead, 1, nRead, pFile); - if( (int)n!=nRead ){ - *pzErrmsg = sqlite3_mprintf("error in fread()"); - return SQLITE_ERROR; - } - return SQLITE_OK; -} - -static int zipfileAppendData( - ZipfileTab *pTab, - const u8 *aWrite, - int nWrite -){ - size_t n; - fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); - n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); - if( (int)n!=nWrite ){ - pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); - return SQLITE_ERROR; - } - pTab->szCurrent += nWrite; - return SQLITE_OK; -} - -/* -** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. -*/ -static u16 zipfileGetU16(const u8 *aBuf){ - return (aBuf[1] << 8) + aBuf[0]; -} - -/* -** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. -*/ -static u32 zipfileGetU32(const u8 *aBuf){ - return ((u32)(aBuf[3]) << 24) - + ((u32)(aBuf[2]) << 16) - + ((u32)(aBuf[1]) << 8) - + ((u32)(aBuf[0]) << 0); -} - -/* -** Write a 16-bit little endiate integer into buffer aBuf. -*/ -static void zipfilePutU16(u8 *aBuf, u16 val){ - aBuf[0] = val & 0xFF; - aBuf[1] = (val>>8) & 0xFF; -} - -/* -** Write a 32-bit little endiate integer into buffer aBuf. -*/ -static void zipfilePutU32(u8 *aBuf, u32 val){ - aBuf[0] = val & 0xFF; - aBuf[1] = (val>>8) & 0xFF; - aBuf[2] = (val>>16) & 0xFF; - aBuf[3] = (val>>24) & 0xFF; -} - -#define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) -#define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) - -#define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } -#define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } - -/* -** Magic numbers used to read CDS records. -*/ -#define ZIPFILE_CDS_NFILE_OFF 28 -#define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 - -/* -** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR -** if the record is not well-formed, or SQLITE_OK otherwise. -*/ -static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ - u8 *aRead = aBuf; - u32 sig = zipfileRead32(aRead); - int rc = SQLITE_OK; - if( sig!=ZIPFILE_SIGNATURE_CDS ){ - rc = SQLITE_ERROR; - }else{ - pCDS->iVersionMadeBy = zipfileRead16(aRead); - pCDS->iVersionExtract = zipfileRead16(aRead); - pCDS->flags = zipfileRead16(aRead); - pCDS->iCompression = zipfileRead16(aRead); - pCDS->mTime = zipfileRead16(aRead); - pCDS->mDate = zipfileRead16(aRead); - pCDS->crc32 = zipfileRead32(aRead); - pCDS->szCompressed = zipfileRead32(aRead); - pCDS->szUncompressed = zipfileRead32(aRead); - assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); - pCDS->nFile = zipfileRead16(aRead); - pCDS->nExtra = zipfileRead16(aRead); - pCDS->nComment = zipfileRead16(aRead); - pCDS->iDiskStart = zipfileRead16(aRead); - pCDS->iInternalAttr = zipfileRead16(aRead); - pCDS->iExternalAttr = zipfileRead32(aRead); - pCDS->iOffset = zipfileRead32(aRead); - assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); - } - - return rc; -} - -/* -** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR -** if the record is not well-formed, or SQLITE_OK otherwise. -*/ -static int zipfileReadLFH( - u8 *aBuffer, - ZipfileLFH *pLFH -){ - u8 *aRead = aBuffer; - int rc = SQLITE_OK; - - u32 sig = zipfileRead32(aRead); - if( sig!=ZIPFILE_SIGNATURE_LFH ){ - rc = SQLITE_ERROR; - }else{ - pLFH->iVersionExtract = zipfileRead16(aRead); - pLFH->flags = zipfileRead16(aRead); - pLFH->iCompression = zipfileRead16(aRead); - pLFH->mTime = zipfileRead16(aRead); - pLFH->mDate = zipfileRead16(aRead); - pLFH->crc32 = zipfileRead32(aRead); - pLFH->szCompressed = zipfileRead32(aRead); - pLFH->szUncompressed = zipfileRead32(aRead); - pLFH->nFile = zipfileRead16(aRead); - pLFH->nExtra = zipfileRead16(aRead); - } - return rc; -} - - -/* -** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. -** Scan through this buffer to find an "extra-timestamp" field. If one -** exists, extract the 32-bit modification-timestamp from it and store -** the value in output parameter *pmTime. -** -** Zero is returned if no extra-timestamp record could be found (and so -** *pmTime is left unchanged), or non-zero otherwise. -** -** The general format of an extra field is: -** -** Header ID 2 bytes -** Data Size 2 bytes -** Data N bytes -*/ -static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ - int ret = 0; - u8 *p = aExtra; - u8 *pEnd = &aExtra[nExtra]; - - while( p modtime is present */ - *pmTime = zipfileGetU32(&p[1]); - ret = 1; - } - break; - } - } - - p += nByte; - } - return ret; -} - -/* -** Convert the standard MS-DOS timestamp stored in the mTime and mDate -** fields of the CDS structure passed as the only argument to a 32-bit -** UNIX seconds-since-the-epoch timestamp. Return the result. -** -** "Standard" MS-DOS time format: -** -** File modification time: -** Bits 00-04: seconds divided by 2 -** Bits 05-10: minute -** Bits 11-15: hour -** File modification date: -** Bits 00-04: day -** Bits 05-08: month (1-12) -** Bits 09-15: years from 1980 -** -** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx -*/ -static u32 zipfileMtime(ZipfileCDS *pCDS){ - int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); - int M = ((pCDS->mDate >> 5) & 0x0F); - int D = (pCDS->mDate & 0x1F); - int B = -13; - - int sec = (pCDS->mTime & 0x1F)*2; - int min = (pCDS->mTime >> 5) & 0x3F; - int hr = (pCDS->mTime >> 11) & 0x1F; - i64 JD; - - /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */ - - /* Calculate the JD in seconds for noon on the day in question */ - if( M<3 ){ - Y = Y-1; - M = M+12; - } - JD = (i64)(24*60*60) * ( - (int)(365.25 * (Y + 4716)) - + (int)(30.6001 * (M + 1)) - + D + B - 1524 - ); - - /* Correct the JD for the time within the day */ - JD += (hr-12) * 3600 + min * 60 + sec; - - /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */ - return (u32)(JD - (i64)(24405875) * 24*60*6); -} - -/* -** The opposite of zipfileMtime(). This function populates the mTime and -** mDate fields of the CDS structure passed as the first argument according -** to the UNIX timestamp value passed as the second. -*/ -static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ - /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */ - i64 JD = (i64)2440588 + mUnixTime / (24*60*60); - - int A, B, C, D, E; - int yr, mon, day; - int hr, min, sec; - - A = (int)((JD - 1867216.25)/36524.25); - A = (int)(JD + 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); - - day = B - D - (int)(30.6001*E); - mon = (E<14 ? E-1 : E-13); - yr = mon>2 ? C-4716 : C-4715; - - hr = (mUnixTime % (24*60*60)) / (60*60); - min = (mUnixTime % (60*60)) / 60; - sec = (mUnixTime % 60); - - if( yr>=1980 ){ - pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); - pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); - }else{ - pCds->mDate = pCds->mTime = 0; - } - - assert( mUnixTime<315507600 - || mUnixTime==zipfileMtime(pCds) - || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) - /* || (mUnixTime % 2) */ - ); -} - -/* -** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in -** size) containing an entire zip archive image. Or, if aBlob is NULL, -** then pFile is a file-handle open on a zip file. In either case, this -** function creates a ZipfileEntry object based on the zip archive entry -** for which the CDS record is at offset iOff. -** -** If successful, SQLITE_OK is returned and (*ppEntry) set to point to -** the new object. Otherwise, an SQLite error code is returned and the -** final value of (*ppEntry) undefined. -*/ -static int zipfileGetEntry( - ZipfileTab *pTab, /* Store any error message here */ - const u8 *aBlob, /* Pointer to in-memory file image */ - int nBlob, /* Size of aBlob[] in bytes */ - FILE *pFile, /* If aBlob==0, read from this file */ - i64 iOff, /* Offset of CDS record */ - ZipfileEntry **ppEntry /* OUT: Pointer to new object */ -){ - u8 *aRead; - char **pzErr = &pTab->base.zErrMsg; - int rc = SQLITE_OK; - - if( aBlob==0 ){ - aRead = pTab->aBuffer; - rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); - }else{ - aRead = (u8*)&aBlob[iOff]; - } - - if( rc==SQLITE_OK ){ - sqlite3_int64 nAlloc; - ZipfileEntry *pNew; - - int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); - int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); - nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); - - nAlloc = sizeof(ZipfileEntry) + nExtra; - if( aBlob ){ - nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); - } - - pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc); - if( pNew==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pNew, 0, sizeof(ZipfileEntry)); - rc = zipfileReadCDS(aRead, &pNew->cds); - if( rc!=SQLITE_OK ){ - *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff); - }else if( aBlob==0 ){ - rc = zipfileReadData( - pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr - ); - }else{ - aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; - } - } - - if( rc==SQLITE_OK ){ - u32 *pt = &pNew->mUnixTime; - pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); - pNew->aExtra = (u8*)&pNew[1]; - memcpy(pNew->aExtra, &aRead[nFile], nExtra); - if( pNew->cds.zFile==0 ){ - rc = SQLITE_NOMEM; - }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ - pNew->mUnixTime = zipfileMtime(&pNew->cds); - } - } - - if( rc==SQLITE_OK ){ - static const int szFix = ZIPFILE_LFH_FIXED_SZ; - ZipfileLFH lfh; - if( pFile ){ - rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); - }else{ - aRead = (u8*)&aBlob[pNew->cds.iOffset]; - } - - rc = zipfileReadLFH(aRead, &lfh); - if( rc==SQLITE_OK ){ - pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; - pNew->iDataOff += lfh.nFile + lfh.nExtra; - if( aBlob && pNew->cds.szCompressed ){ - pNew->aData = &pNew->aExtra[nExtra]; - memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); - } - }else{ - *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", - (int)pNew->cds.iOffset - ); - } - } - - if( rc!=SQLITE_OK ){ - zipfileEntryFree(pNew); - }else{ - *ppEntry = pNew; - } - } - - return rc; -} - -/* -** Advance an ZipfileCsr to its next row of output. -*/ -static int zipfileNext(sqlite3_vtab_cursor *cur){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - int rc = SQLITE_OK; - - if( pCsr->pFile ){ - i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; - zipfileEntryFree(pCsr->pCurrent); - pCsr->pCurrent = 0; - if( pCsr->iNextOff>=iEof ){ - pCsr->bEof = 1; - }else{ - ZipfileEntry *p = 0; - ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); - rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); - if( rc==SQLITE_OK ){ - pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; - pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; - } - pCsr->pCurrent = p; - } - }else{ - if( !pCsr->bNoop ){ - pCsr->pCurrent = pCsr->pCurrent->pNext; - } - if( pCsr->pCurrent==0 ){ - pCsr->bEof = 1; - } - } - - pCsr->bNoop = 0; - return rc; -} - -static void zipfileFree(void *p) { - sqlite3_free(p); -} - -/* -** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the -** size is nOut bytes. This function uncompresses the data and sets the -** return value in context pCtx to the result (a blob). -** -** If an error occurs, an error code is left in pCtx instead. -*/ -static void zipfileInflate( - sqlite3_context *pCtx, /* Store result here */ - const u8 *aIn, /* Compressed data */ - int nIn, /* Size of buffer aIn[] in bytes */ - int nOut /* Expected output size */ -){ - u8 *aRes = sqlite3_malloc(nOut); - if( aRes==0 ){ - sqlite3_result_error_nomem(pCtx); - }else{ - int err; - z_stream str; - memset(&str, 0, sizeof(str)); - - str.next_in = (Byte*)aIn; - str.avail_in = nIn; - str.next_out = (Byte*)aRes; - str.avail_out = nOut; - - err = inflateInit2(&str, -15); - if( err!=Z_OK ){ - zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); - }else{ - err = inflate(&str, Z_NO_FLUSH); - if( err!=Z_STREAM_END ){ - zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); - }else{ - sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree); - aRes = 0; - } - } - sqlite3_free(aRes); - inflateEnd(&str); - } -} - -/* -** Buffer aIn (size nIn bytes) contains uncompressed data. This function -** compresses it and sets (*ppOut) to point to a buffer containing the -** compressed data. The caller is responsible for eventually calling -** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) -** is set to the size of buffer (*ppOut) in bytes. -** -** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error -** code is returned and an error message left in virtual-table handle -** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this -** case. -*/ -static int zipfileDeflate( - const u8 *aIn, int nIn, /* Input */ - u8 **ppOut, int *pnOut, /* Output */ - char **pzErr /* OUT: Error message */ -){ - int rc = SQLITE_OK; - sqlite3_int64 nAlloc; - z_stream str; - u8 *aOut; - - memset(&str, 0, sizeof(str)); - str.next_in = (Bytef*)aIn; - str.avail_in = nIn; - deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); - - nAlloc = deflateBound(&str, nIn); - aOut = (u8*)sqlite3_malloc64(nAlloc); - if( aOut==0 ){ - rc = SQLITE_NOMEM; - }else{ - int res; - str.next_out = aOut; - str.avail_out = nAlloc; - res = deflate(&str, Z_FINISH); - if( res==Z_STREAM_END ){ - *ppOut = aOut; - *pnOut = (int)str.total_out; - }else{ - sqlite3_free(aOut); - *pzErr = sqlite3_mprintf("zipfile: deflate() error"); - rc = SQLITE_ERROR; - } - deflateEnd(&str); - } - - return rc; -} - - -/* -** Return values of columns for the row at which the series_cursor -** is currently pointing. -*/ -static int zipfileColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - ZipfileCDS *pCDS = &pCsr->pCurrent->cds; - int rc = SQLITE_OK; - switch( i ){ - case 0: /* name */ - sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); - break; - case 1: /* mode */ - /* TODO: Whether or not the following is correct surely depends on - ** the platform on which the archive was created. */ - sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); - break; - case 2: { /* mtime */ - sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); - break; - } - case 3: { /* sz */ - if( sqlite3_vtab_nochange(ctx)==0 ){ - sqlite3_result_int64(ctx, pCDS->szUncompressed); - } - break; - } - case 4: /* rawdata */ - if( sqlite3_vtab_nochange(ctx) ) break; - case 5: { /* data */ - if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ - int sz = pCDS->szCompressed; - int szFinal = pCDS->szUncompressed; - if( szFinal>0 ){ - u8 *aBuf; - u8 *aFree = 0; - if( pCsr->pCurrent->aData ){ - aBuf = pCsr->pCurrent->aData; - }else{ - aBuf = aFree = sqlite3_malloc64(sz); - if( aBuf==0 ){ - rc = SQLITE_NOMEM; - }else{ - FILE *pFile = pCsr->pFile; - if( pFile==0 ){ - pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; - } - rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, - &pCsr->base.pVtab->zErrMsg - ); - } - } - if( rc==SQLITE_OK ){ - if( i==5 && pCDS->iCompression ){ - zipfileInflate(ctx, aBuf, sz, szFinal); - }else{ - sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); - } - } - sqlite3_free(aFree); - }else{ - /* Figure out if this is a directory or a zero-sized file. Consider - ** it to be a directory either if the mode suggests so, or if - ** the final character in the name is '/'. */ - u32 mode = pCDS->iExternalAttr >> 16; - if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){ - sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); - } - } - } - break; - } - case 6: /* method */ - sqlite3_result_int(ctx, pCDS->iCompression); - break; - default: /* z */ - assert( i==7 ); - sqlite3_result_int64(ctx, pCsr->iId); - break; - } - - return rc; -} - -/* -** Return TRUE if the cursor is at EOF. -*/ -static int zipfileEof(sqlite3_vtab_cursor *cur){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - return pCsr->bEof; -} - -/* -** If aBlob is not NULL, then it points to a buffer nBlob bytes in size -** containing an entire zip archive image. Or, if aBlob is NULL, then pFile -** is guaranteed to be a file-handle open on a zip file. -** -** This function attempts to locate the EOCD record within the zip archive -** and populate *pEOCD with the results of decoding it. SQLITE_OK is -** returned if successful. Otherwise, an SQLite error code is returned and -** an English language error message may be left in virtual-table pTab. -*/ -static int zipfileReadEOCD( - ZipfileTab *pTab, /* Return errors here */ - const u8 *aBlob, /* Pointer to in-memory file image */ - int nBlob, /* Size of aBlob[] in bytes */ - FILE *pFile, /* Read from this file if aBlob==0 */ - ZipfileEOCD *pEOCD /* Object to populate */ -){ - u8 *aRead = pTab->aBuffer; /* Temporary buffer */ - int nRead; /* Bytes to read from file */ - int rc = SQLITE_OK; - - if( aBlob==0 ){ - i64 iOff; /* Offset to read from */ - i64 szFile; /* Total size of file in bytes */ - fseek(pFile, 0, SEEK_END); - szFile = (i64)ftell(pFile); - if( szFile==0 ){ - memset(pEOCD, 0, sizeof(ZipfileEOCD)); - return SQLITE_OK; - } - nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); - iOff = szFile - nRead; - rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); - }else{ - nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); - aRead = (u8*)&aBlob[nBlob-nRead]; - } - - if( rc==SQLITE_OK ){ - int i; - - /* Scan backwards looking for the signature bytes */ - for(i=nRead-20; i>=0; i--){ - if( aRead[i]==0x50 && aRead[i+1]==0x4b - && aRead[i+2]==0x05 && aRead[i+3]==0x06 - ){ - break; - } - } - if( i<0 ){ - pTab->base.zErrMsg = sqlite3_mprintf( - "cannot find end of central directory record" - ); - return SQLITE_ERROR; - } - - aRead += i+4; - pEOCD->iDisk = zipfileRead16(aRead); - pEOCD->iFirstDisk = zipfileRead16(aRead); - pEOCD->nEntry = zipfileRead16(aRead); - pEOCD->nEntryTotal = zipfileRead16(aRead); - pEOCD->nSize = zipfileRead32(aRead); - pEOCD->iOffset = zipfileRead32(aRead); - } - - return rc; -} - -/* -** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry -** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added -** to the end of the list. Otherwise, it is added to the list immediately -** before pBefore (which is guaranteed to be a part of said list). -*/ -static void zipfileAddEntry( - ZipfileTab *pTab, - ZipfileEntry *pBefore, - ZipfileEntry *pNew -){ - assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); - assert( pNew->pNext==0 ); - if( pBefore==0 ){ - if( pTab->pFirstEntry==0 ){ - pTab->pFirstEntry = pTab->pLastEntry = pNew; - }else{ - assert( pTab->pLastEntry->pNext==0 ); - pTab->pLastEntry->pNext = pNew; - pTab->pLastEntry = pNew; - } - }else{ - ZipfileEntry **pp; - for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); - pNew->pNext = pBefore; - *pp = pNew; - } -} - -static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){ - ZipfileEOCD eocd; - int rc; - int i; - i64 iOff; - - rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); - iOff = eocd.iOffset; - for(i=0; rc==SQLITE_OK && ipWriteFd, iOff, &pNew); - - if( rc==SQLITE_OK ){ - zipfileAddEntry(pTab, 0, pNew); - iOff += ZIPFILE_CDS_FIXED_SZ; - iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; - } - } - return rc; -} - -/* -** xFilter callback. -*/ -static int zipfileFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - const char *zFile = 0; /* Zip file to scan */ - int rc = SQLITE_OK; /* Return Code */ - int bInMemory = 0; /* True for an in-memory zipfile */ - - zipfileResetCursor(pCsr); - - if( pTab->zFile ){ - zFile = pTab->zFile; - }else if( idxNum==0 ){ - zipfileCursorErr(pCsr, "zipfile() function requires an argument"); - return SQLITE_ERROR; - }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ - const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); - int nBlob = sqlite3_value_bytes(argv[0]); - assert( pTab->pFirstEntry==0 ); - rc = zipfileLoadDirectory(pTab, aBlob, nBlob); - pCsr->pFreeEntry = pTab->pFirstEntry; - pTab->pFirstEntry = pTab->pLastEntry = 0; - if( rc!=SQLITE_OK ) return rc; - bInMemory = 1; - }else{ - zFile = (const char*)sqlite3_value_text(argv[0]); - } - - if( 0==pTab->pWriteFd && 0==bInMemory ){ - pCsr->pFile = fopen(zFile, "rb"); - if( pCsr->pFile==0 ){ - zipfileCursorErr(pCsr, "cannot open file: %s", zFile); - rc = SQLITE_ERROR; - }else{ - rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); - if( rc==SQLITE_OK ){ - if( pCsr->eocd.nEntry==0 ){ - pCsr->bEof = 1; - }else{ - pCsr->iNextOff = pCsr->eocd.iOffset; - rc = zipfileNext(cur); - } - } - } - }else{ - pCsr->bNoop = 1; - pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; - rc = zipfileNext(cur); - } - - return rc; -} - -/* -** xBestIndex callback. -*/ -static int zipfileBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; - int idx = -1; - int unusable = 0; - - for(i=0; inConstraint; i++){ - const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; - if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; - if( pCons->usable==0 ){ - unusable = 1; - }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - idx = i; - } - } - pIdxInfo->estimatedCost = 1000.0; - if( idx>=0 ){ - pIdxInfo->aConstraintUsage[idx].argvIndex = 1; - pIdxInfo->aConstraintUsage[idx].omit = 1; - pIdxInfo->idxNum = 1; - }else if( unusable ){ - return SQLITE_CONSTRAINT; - } - return SQLITE_OK; -} - -static ZipfileEntry *zipfileNewEntry(const char *zPath){ - ZipfileEntry *pNew; - pNew = sqlite3_malloc(sizeof(ZipfileEntry)); - if( pNew ){ - memset(pNew, 0, sizeof(ZipfileEntry)); - pNew->cds.zFile = sqlite3_mprintf("%s", zPath); - if( pNew->cds.zFile==0 ){ - sqlite3_free(pNew); - pNew = 0; - } - } - return pNew; -} - -static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ - ZipfileCDS *pCds = &pEntry->cds; - u8 *a = aBuf; - - pCds->nExtra = 9; - - /* Write the LFH itself */ - zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); - zipfileWrite16(a, pCds->iVersionExtract); - zipfileWrite16(a, pCds->flags); - zipfileWrite16(a, pCds->iCompression); - zipfileWrite16(a, pCds->mTime); - zipfileWrite16(a, pCds->mDate); - zipfileWrite32(a, pCds->crc32); - zipfileWrite32(a, pCds->szCompressed); - zipfileWrite32(a, pCds->szUncompressed); - zipfileWrite16(a, (u16)pCds->nFile); - zipfileWrite16(a, pCds->nExtra); - assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); - - /* Add the file name */ - memcpy(a, pCds->zFile, (int)pCds->nFile); - a += (int)pCds->nFile; - - /* The "extra" data */ - zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); - zipfileWrite16(a, 5); - *a++ = 0x01; - zipfileWrite32(a, pEntry->mUnixTime); - - return a-aBuf; -} - -static int zipfileAppendEntry( - ZipfileTab *pTab, - ZipfileEntry *pEntry, - const u8 *pData, - int nData -){ - u8 *aBuf = pTab->aBuffer; - int nBuf; - int rc; - - nBuf = zipfileSerializeLFH(pEntry, aBuf); - rc = zipfileAppendData(pTab, aBuf, nBuf); - if( rc==SQLITE_OK ){ - pEntry->iDataOff = pTab->szCurrent; - rc = zipfileAppendData(pTab, pData, nData); - } - - return rc; -} - -static int zipfileGetMode( - sqlite3_value *pVal, - int bIsDir, /* If true, default to directory */ - u32 *pMode, /* OUT: Mode value */ - char **pzErr /* OUT: Error message */ -){ - const char *z = (const char*)sqlite3_value_text(pVal); - u32 mode = 0; - if( z==0 ){ - mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); - }else if( z[0]>='0' && z[0]<='9' ){ - mode = (unsigned int)sqlite3_value_int(pVal); - }else{ - const char zTemplate[11] = "-rwxrwxrwx"; - int i; - if( strlen(z)!=10 ) goto parse_error; - switch( z[0] ){ - case '-': mode |= S_IFREG; break; - case 'd': mode |= S_IFDIR; break; - case 'l': mode |= S_IFLNK; break; - default: goto parse_error; - } - for(i=1; i<10; i++){ - if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); - else if( z[i]!='-' ) goto parse_error; - } - } - if( ((mode & S_IFDIR)==0)==bIsDir ){ - /* The "mode" attribute is a directory, but data has been specified. - ** Or vice-versa - no data but "mode" is a file or symlink. */ - *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); - return SQLITE_CONSTRAINT; - } - *pMode = mode; - return SQLITE_OK; - - parse_error: - *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); - return SQLITE_ERROR; -} - -/* -** Both (const char*) arguments point to nul-terminated strings. Argument -** nB is the value of strlen(zB). This function returns 0 if the strings are -** identical, ignoring any trailing '/' character in either path. */ -static int zipfileComparePath(const char *zA, const char *zB, int nB){ - int nA = (int)strlen(zA); - if( nA>0 && zA[nA-1]=='/' ) nA--; - if( nB>0 && zB[nB-1]=='/' ) nB--; - if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; - return 1; -} - -static int zipfileBegin(sqlite3_vtab *pVtab){ - ZipfileTab *pTab = (ZipfileTab*)pVtab; - int rc = SQLITE_OK; - - assert( pTab->pWriteFd==0 ); - if( pTab->zFile==0 || pTab->zFile[0]==0 ){ - pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename"); - return SQLITE_ERROR; - } - - /* Open a write fd on the file. Also load the entire central directory - ** structure into memory. During the transaction any new file data is - ** appended to the archive file, but the central directory is accumulated - ** in main-memory until the transaction is committed. */ - pTab->pWriteFd = fopen(pTab->zFile, "ab+"); - if( pTab->pWriteFd==0 ){ - pTab->base.zErrMsg = sqlite3_mprintf( - "zipfile: failed to open file %s for writing", pTab->zFile - ); - rc = SQLITE_ERROR; - }else{ - fseek(pTab->pWriteFd, 0, SEEK_END); - pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); - rc = zipfileLoadDirectory(pTab, 0, 0); - } - - if( rc!=SQLITE_OK ){ - zipfileCleanupTransaction(pTab); - } - - return rc; -} - -/* -** Return the current time as a 32-bit timestamp in UNIX epoch format (like -** time(2)). -*/ -static u32 zipfileTime(void){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(0); - u32 ret; - if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ - i64 ms; - pVfs->xCurrentTimeInt64(pVfs, &ms); - ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); - }else{ - double day; - pVfs->xCurrentTime(pVfs, &day); - ret = (u32)((day - 2440587.5) * 86400); - } - return ret; -} - -/* -** Return a 32-bit timestamp in UNIX epoch format. -** -** If the value passed as the only argument is either NULL or an SQL NULL, -** return the current time. Otherwise, return the value stored in (*pVal) -** cast to a 32-bit unsigned integer. -*/ -static u32 zipfileGetTime(sqlite3_value *pVal){ - if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ - return zipfileTime(); - } - return (u32)sqlite3_value_int64(pVal); -} - -/* -** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry -** linked list. Remove it from the list and free the object. -*/ -static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ - if( pOld ){ - ZipfileEntry **pp; - for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext)); - *pp = (*pp)->pNext; - zipfileEntryFree(pOld); - } -} - -/* -** xUpdate method. -*/ -static int zipfileUpdate( - sqlite3_vtab *pVtab, - int nVal, - sqlite3_value **apVal, - sqlite_int64 *pRowid -){ - ZipfileTab *pTab = (ZipfileTab*)pVtab; - int rc = SQLITE_OK; /* Return Code */ - ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ - - u32 mode = 0; /* Mode for new entry */ - u32 mTime = 0; /* Modification time for new entry */ - i64 sz = 0; /* Uncompressed size */ - const char *zPath = 0; /* Path for new entry */ - int nPath = 0; /* strlen(zPath) */ - const u8 *pData = 0; /* Pointer to buffer containing content */ - int nData = 0; /* Size of pData buffer in bytes */ - int iMethod = 0; /* Compression method for new entry */ - u8 *pFree = 0; /* Free this */ - char *zFree = 0; /* Also free this */ - ZipfileEntry *pOld = 0; - ZipfileEntry *pOld2 = 0; - int bUpdate = 0; /* True for an update that modifies "name" */ - int bIsDir = 0; - u32 iCrc32 = 0; - - if( pTab->pWriteFd==0 ){ - rc = zipfileBegin(pVtab); - if( rc!=SQLITE_OK ) return rc; - } - - /* If this is a DELETE or UPDATE, find the archive entry to delete. */ - if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ - const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); - int nDelete = (int)strlen(zDelete); - if( nVal>1 ){ - const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); - if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ - bUpdate = 1; - } - } - for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ - if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ - break; - } - assert( pOld->pNext ); - } - } - - if( nVal>1 ){ - /* Check that "sz" and "rawdata" are both NULL: */ - if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ - zipfileTableErr(pTab, "sz must be NULL"); - rc = SQLITE_CONSTRAINT; - } - if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ - zipfileTableErr(pTab, "rawdata must be NULL"); - rc = SQLITE_CONSTRAINT; - } - - if( rc==SQLITE_OK ){ - if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ - /* data=NULL. A directory */ - bIsDir = 1; - }else{ - /* Value specified for "data", and possibly "method". This must be - ** a regular file or a symlink. */ - const u8 *aIn = sqlite3_value_blob(apVal[7]); - int nIn = sqlite3_value_bytes(apVal[7]); - int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; - - iMethod = sqlite3_value_int(apVal[8]); - sz = nIn; - pData = aIn; - nData = nIn; - if( iMethod!=0 && iMethod!=8 ){ - zipfileTableErr(pTab, "unknown compression method: %d", iMethod); - rc = SQLITE_CONSTRAINT; - }else{ - if( bAuto || iMethod ){ - int nCmp; - rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); - if( rc==SQLITE_OK ){ - if( iMethod || nCmpbase.zErrMsg); - } - - if( rc==SQLITE_OK ){ - zPath = (const char*)sqlite3_value_text(apVal[2]); - if( zPath==0 ) zPath = ""; - nPath = (int)strlen(zPath); - mTime = zipfileGetTime(apVal[4]); - } - - if( rc==SQLITE_OK && bIsDir ){ - /* For a directory, check that the last character in the path is a - ** '/'. This appears to be required for compatibility with info-zip - ** (the unzip command on unix). It does not create directories - ** otherwise. */ - if( nPath<=0 || zPath[nPath-1]!='/' ){ - zFree = sqlite3_mprintf("%s/", zPath); - zPath = (const char*)zFree; - if( zFree==0 ){ - rc = SQLITE_NOMEM; - nPath = 0; - }else{ - nPath = (int)strlen(zPath); - } - } - } - - /* Check that we're not inserting a duplicate entry -OR- updating an - ** entry with a path, thereby making it into a duplicate. */ - if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ - ZipfileEntry *p; - for(p=pTab->pFirstEntry; p; p=p->pNext){ - if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ - switch( sqlite3_vtab_on_conflict(pTab->db) ){ - case SQLITE_IGNORE: { - goto zipfile_update_done; - } - case SQLITE_REPLACE: { - pOld2 = p; - break; - } - default: { - zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); - rc = SQLITE_CONSTRAINT; - break; - } - } - break; - } - } - } - - if( rc==SQLITE_OK ){ - /* Create the new CDS record. */ - pNew = zipfileNewEntry(zPath); - if( pNew==0 ){ - rc = SQLITE_NOMEM; - }else{ - pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; - pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; - pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; - pNew->cds.iCompression = (u16)iMethod; - zipfileMtimeToDos(&pNew->cds, mTime); - pNew->cds.crc32 = iCrc32; - pNew->cds.szCompressed = nData; - pNew->cds.szUncompressed = (u32)sz; - pNew->cds.iExternalAttr = (mode<<16); - pNew->cds.iOffset = (u32)pTab->szCurrent; - pNew->cds.nFile = (u16)nPath; - pNew->mUnixTime = (u32)mTime; - rc = zipfileAppendEntry(pTab, pNew, pData, nData); - zipfileAddEntry(pTab, pOld, pNew); - } - } - } - - if( rc==SQLITE_OK && (pOld || pOld2) ){ - ZipfileCsr *pCsr; - for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ - if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ - pCsr->pCurrent = pCsr->pCurrent->pNext; - pCsr->bNoop = 1; - } - } - - zipfileRemoveEntryFromList(pTab, pOld); - zipfileRemoveEntryFromList(pTab, pOld2); - } - -zipfile_update_done: - sqlite3_free(pFree); - sqlite3_free(zFree); - return rc; -} - -static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ - u8 *a = aBuf; - zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); - zipfileWrite16(a, p->iDisk); - zipfileWrite16(a, p->iFirstDisk); - zipfileWrite16(a, p->nEntry); - zipfileWrite16(a, p->nEntryTotal); - zipfileWrite32(a, p->nSize); - zipfileWrite32(a, p->iOffset); - zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ - - return a-aBuf; -} - -static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ - int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); - assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); - return zipfileAppendData(pTab, pTab->aBuffer, nBuf); -} - -/* -** Serialize the CDS structure into buffer aBuf[]. Return the number -** of bytes written. -*/ -static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ - u8 *a = aBuf; - ZipfileCDS *pCDS = &pEntry->cds; - - if( pEntry->aExtra==0 ){ - pCDS->nExtra = 9; - } - - zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); - zipfileWrite16(a, pCDS->iVersionMadeBy); - zipfileWrite16(a, pCDS->iVersionExtract); - zipfileWrite16(a, pCDS->flags); - zipfileWrite16(a, pCDS->iCompression); - zipfileWrite16(a, pCDS->mTime); - zipfileWrite16(a, pCDS->mDate); - zipfileWrite32(a, pCDS->crc32); - zipfileWrite32(a, pCDS->szCompressed); - zipfileWrite32(a, pCDS->szUncompressed); - assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); - zipfileWrite16(a, pCDS->nFile); - zipfileWrite16(a, pCDS->nExtra); - zipfileWrite16(a, pCDS->nComment); - zipfileWrite16(a, pCDS->iDiskStart); - zipfileWrite16(a, pCDS->iInternalAttr); - zipfileWrite32(a, pCDS->iExternalAttr); - zipfileWrite32(a, pCDS->iOffset); - - memcpy(a, pCDS->zFile, pCDS->nFile); - a += pCDS->nFile; - - if( pEntry->aExtra ){ - int n = (int)pCDS->nExtra + (int)pCDS->nComment; - memcpy(a, pEntry->aExtra, n); - a += n; - }else{ - assert( pCDS->nExtra==9 ); - zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); - zipfileWrite16(a, 5); - *a++ = 0x01; - zipfileWrite32(a, pEntry->mUnixTime); - } - - return a-aBuf; -} - -static int zipfileCommit(sqlite3_vtab *pVtab){ - ZipfileTab *pTab = (ZipfileTab*)pVtab; - int rc = SQLITE_OK; - if( pTab->pWriteFd ){ - i64 iOffset = pTab->szCurrent; - ZipfileEntry *p; - ZipfileEOCD eocd; - int nEntry = 0; - - /* Write out all entries */ - for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ - int n = zipfileSerializeCDS(p, pTab->aBuffer); - rc = zipfileAppendData(pTab, pTab->aBuffer, n); - nEntry++; - } - - /* Write out the EOCD record */ - eocd.iDisk = 0; - eocd.iFirstDisk = 0; - eocd.nEntry = (u16)nEntry; - eocd.nEntryTotal = (u16)nEntry; - eocd.nSize = (u32)(pTab->szCurrent - iOffset); - eocd.iOffset = (u32)iOffset; - rc = zipfileAppendEOCD(pTab, &eocd); - - zipfileCleanupTransaction(pTab); - } - return rc; -} - -static int zipfileRollback(sqlite3_vtab *pVtab){ - return zipfileCommit(pVtab); -} - -static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ - ZipfileCsr *pCsr; - for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ - if( iId==pCsr->iId ) break; - } - return pCsr; -} - -static void zipfileFunctionCds( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - ZipfileCsr *pCsr; - ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); - assert( argc>0 ); - - pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); - if( pCsr ){ - ZipfileCDS *p = &pCsr->pCurrent->cds; - char *zRes = sqlite3_mprintf("{" - "\"version-made-by\" : %u, " - "\"version-to-extract\" : %u, " - "\"flags\" : %u, " - "\"compression\" : %u, " - "\"time\" : %u, " - "\"date\" : %u, " - "\"crc32\" : %u, " - "\"compressed-size\" : %u, " - "\"uncompressed-size\" : %u, " - "\"file-name-length\" : %u, " - "\"extra-field-length\" : %u, " - "\"file-comment-length\" : %u, " - "\"disk-number-start\" : %u, " - "\"internal-attr\" : %u, " - "\"external-attr\" : %u, " - "\"offset\" : %u }", - (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, - (u32)p->flags, (u32)p->iCompression, - (u32)p->mTime, (u32)p->mDate, - (u32)p->crc32, (u32)p->szCompressed, - (u32)p->szUncompressed, (u32)p->nFile, - (u32)p->nExtra, (u32)p->nComment, - (u32)p->iDiskStart, (u32)p->iInternalAttr, - (u32)p->iExternalAttr, (u32)p->iOffset - ); - - if( zRes==0 ){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); - sqlite3_free(zRes); - } - } -} - -/* -** xFindFunction method. -*/ -static int zipfileFindFunction( - sqlite3_vtab *pVtab, /* Virtual table handle */ - int nArg, /* Number of SQL function arguments */ - const char *zName, /* Name of SQL function */ - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ - void **ppArg /* OUT: User data for *pxFunc */ -){ - if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ - *pxFunc = zipfileFunctionCds; - *ppArg = (void*)pVtab; - return 1; - } - return 0; -} - -typedef struct ZipfileBuffer ZipfileBuffer; -struct ZipfileBuffer { - u8 *a; /* Pointer to buffer */ - int n; /* Size of buffer in bytes */ - int nAlloc; /* Byte allocated at a[] */ -}; - -typedef struct ZipfileCtx ZipfileCtx; -struct ZipfileCtx { - int nEntry; - ZipfileBuffer body; - ZipfileBuffer cds; -}; - -static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){ - if( pBuf->n+nByte>pBuf->nAlloc ){ - u8 *aNew; - sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; - int nReq = pBuf->n + nByte; - - while( nNewa, nNew); - if( aNew==0 ) return SQLITE_NOMEM; - pBuf->a = aNew; - pBuf->nAlloc = (int)nNew; - } - return SQLITE_OK; -} - -/* -** xStep() callback for the zipfile() aggregate. This can be called in -** any of the following ways: -** -** SELECT zipfile(name,data) ... -** SELECT zipfile(name,mode,mtime,data) ... -** SELECT zipfile(name,mode,mtime,data,method) ... -*/ -void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ - ZipfileCtx *p; /* Aggregate function context */ - ZipfileEntry e; /* New entry to add to zip archive */ - - sqlite3_value *pName = 0; - sqlite3_value *pMode = 0; - sqlite3_value *pMtime = 0; - sqlite3_value *pData = 0; - sqlite3_value *pMethod = 0; - - int bIsDir = 0; - u32 mode; - int rc = SQLITE_OK; - char *zErr = 0; - - int iMethod = -1; /* Compression method to use (0 or 8) */ - - const u8 *aData = 0; /* Possibly compressed data for new entry */ - int nData = 0; /* Size of aData[] in bytes */ - int szUncompressed = 0; /* Size of data before compression */ - u8 *aFree = 0; /* Free this before returning */ - u32 iCrc32 = 0; /* crc32 of uncompressed data */ - - char *zName = 0; /* Path (name) of new entry */ - int nName = 0; /* Size of zName in bytes */ - char *zFree = 0; /* Free this before returning */ - int nByte; - - memset(&e, 0, sizeof(e)); - p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); - if( p==0 ) return; - - /* Martial the arguments into stack variables */ - if( nVal!=2 && nVal!=4 && nVal!=5 ){ - zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - pName = apVal[0]; - if( nVal==2 ){ - pData = apVal[1]; - }else{ - pMode = apVal[1]; - pMtime = apVal[2]; - pData = apVal[3]; - if( nVal==5 ){ - pMethod = apVal[4]; - } - } - - /* Check that the 'name' parameter looks ok. */ - zName = (char*)sqlite3_value_text(pName); - nName = sqlite3_value_bytes(pName); - if( zName==0 ){ - zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - - /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use - ** deflate compression) or NULL (choose automatically). */ - if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ - iMethod = (int)sqlite3_value_int64(pMethod); - if( iMethod!=0 && iMethod!=8 ){ - zErr = sqlite3_mprintf("illegal method value: %d", iMethod); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - } - - /* Now inspect the data. If this is NULL, then the new entry must be a - ** directory. Otherwise, figure out whether or not the data should - ** be deflated or simply stored in the zip archive. */ - if( sqlite3_value_type(pData)==SQLITE_NULL ){ - bIsDir = 1; - iMethod = 0; - }else{ - aData = sqlite3_value_blob(pData); - szUncompressed = nData = sqlite3_value_bytes(pData); - iCrc32 = crc32(0, aData, nData); - if( iMethod<0 || iMethod==8 ){ - int nOut = 0; - rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); - if( rc!=SQLITE_OK ){ - goto zipfile_step_out; - } - if( iMethod==8 || nOut0 && zName[nName-1]=='/' ){ - zErr = sqlite3_mprintf("non-directory name must not end with /"); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - }else{ - if( nName==0 || zName[nName-1]!='/' ){ - zName = zFree = sqlite3_mprintf("%s/", zName); - if( zName==0 ){ - rc = SQLITE_NOMEM; - goto zipfile_step_out; - } - nName = (int)strlen(zName); - }else{ - while( nName>1 && zName[nName-2]=='/' ) nName--; - } - } - - /* Assemble the ZipfileEntry object for the new zip archive entry */ - e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; - e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; - e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; - e.cds.iCompression = (u16)iMethod; - zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); - e.cds.crc32 = iCrc32; - e.cds.szCompressed = nData; - e.cds.szUncompressed = szUncompressed; - e.cds.iExternalAttr = (mode<<16); - e.cds.iOffset = p->body.n; - e.cds.nFile = (u16)nName; - e.cds.zFile = zName; - - /* Append the LFH to the body of the new archive */ - nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; - if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; - p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); - - /* Append the data to the body of the new archive */ - if( nData>0 ){ - if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; - memcpy(&p->body.a[p->body.n], aData, nData); - p->body.n += nData; - } - - /* Append the CDS record to the directory of the new archive */ - nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; - if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; - p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); - - /* Increment the count of entries in the archive */ - p->nEntry++; - - zipfile_step_out: - sqlite3_free(aFree); - sqlite3_free(zFree); - if( rc ){ - if( zErr ){ - sqlite3_result_error(pCtx, zErr, -1); - }else{ - sqlite3_result_error_code(pCtx, rc); - } - } - sqlite3_free(zErr); -} - -/* -** xFinalize() callback for zipfile aggregate function. -*/ -void zipfileFinal(sqlite3_context *pCtx){ - ZipfileCtx *p; - ZipfileEOCD eocd; - sqlite3_int64 nZip; - u8 *aZip; - - p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); - if( p==0 ) return; - if( p->nEntry>0 ){ - memset(&eocd, 0, sizeof(eocd)); - eocd.nEntry = (u16)p->nEntry; - eocd.nEntryTotal = (u16)p->nEntry; - eocd.nSize = p->cds.n; - eocd.iOffset = p->body.n; - - nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; - aZip = (u8*)sqlite3_malloc64(nZip); - if( aZip==0 ){ - sqlite3_result_error_nomem(pCtx); - }else{ - memcpy(aZip, p->body.a, p->body.n); - memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); - zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); - sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree); - } - } - - sqlite3_free(p->body.a); - sqlite3_free(p->cds.a); -} - - -/* -** Register the "zipfile" virtual table. -*/ -static int zipfileRegister(sqlite3 *db){ - static sqlite3_module zipfileModule = { - 1, /* iVersion */ - zipfileConnect, /* xCreate */ - zipfileConnect, /* xConnect */ - zipfileBestIndex, /* xBestIndex */ - zipfileDisconnect, /* xDisconnect */ - zipfileDisconnect, /* xDestroy */ - zipfileOpen, /* xOpen - open a cursor */ - zipfileClose, /* xClose - close a cursor */ - zipfileFilter, /* xFilter - configure scan constraints */ - zipfileNext, /* xNext - advance a cursor */ - zipfileEof, /* xEof - check for end of scan */ - zipfileColumn, /* xColumn - read data */ - 0, /* xRowid - read data */ - zipfileUpdate, /* xUpdate */ - zipfileBegin, /* xBegin */ - 0, /* xSync */ - zipfileCommit, /* xCommit */ - zipfileRollback, /* xRollback */ - zipfileFindFunction, /* xFindMethod */ - 0, /* xRename */ - }; - - int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); - if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, - zipfileStep, zipfileFinal - ); - } - return rc; -} -#else /* SQLITE_OMIT_VIRTUALTABLE */ -# define zipfileRegister(x) SQLITE_OK -#endif - -#ifdef _WIN32 - -#endif -int sqlite3_zipfile_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - return zipfileRegister(db); -} - -/************************* End ../ext/misc/zipfile.c ********************/ -/************************* Begin ../ext/misc/sqlar.c ******************/ -/* -** 2017-12-17 -** -** 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 sqlar_compress() and sqlar_uncompress(). Useful -** for working with sqlar archives and used by the shell tool's built-in -** sqlar support. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include - -/* -** Implementation of the "sqlar_compress(X)" SQL function. -** -** If the type of X is SQLITE_BLOB, and compressing that blob using -** zlib utility function compress() yields a smaller blob, return the -** compressed blob. Otherwise, return a copy of X. -** -** SQLar uses the "zlib format" for compressed content. The zlib format -** contains a two-byte identification header and a four-byte checksum at -** the end. This is different from ZIP which uses the raw deflate format. -** -** Future enhancements to SQLar might add support for new compression formats. -** If so, those new formats will be identified by alternative headers in the -** compressed data. -*/ -static void sqlarCompressFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - assert( argc==1 ); - if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ - const Bytef *pData = sqlite3_value_blob(argv[0]); - uLong nData = sqlite3_value_bytes(argv[0]); - uLongf nOut = compressBound(nData); - Bytef *pOut; - - pOut = (Bytef*)sqlite3_malloc(nOut); - if( pOut==0 ){ - sqlite3_result_error_nomem(context); - return; - }else{ - if( Z_OK!=compress(pOut, &nOut, pData, nData) ){ - sqlite3_result_error(context, "error in compress()", -1); - }else if( nOut -#include -#include - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* typedef sqlite3_int64 i64; */ -/* typedef sqlite3_uint64 u64; */ - -typedef struct IdxColumn IdxColumn; -typedef struct IdxConstraint IdxConstraint; -typedef struct IdxScan IdxScan; -typedef struct IdxStatement IdxStatement; -typedef struct IdxTable IdxTable; -typedef struct IdxWrite IdxWrite; - -#define STRLEN (int)strlen - -/* -** A temp table name that we assume no user database will actually use. -** If this assumption proves incorrect triggers on the table with the -** conflicting name will be ignored. -*/ -#define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776" - -/* -** A single constraint. Equivalent to either "col = ?" or "col < ?" (or -** any other type of single-ended range constraint on a column). -** -** pLink: -** Used to temporarily link IdxConstraint objects into lists while -** creating candidate indexes. -*/ -struct IdxConstraint { - char *zColl; /* Collation sequence */ - int bRange; /* True for range, false for eq */ - int iCol; /* Constrained table column */ - int bFlag; /* Used by idxFindCompatible() */ - int bDesc; /* True if ORDER BY DESC */ - IdxConstraint *pNext; /* Next constraint in pEq or pRange list */ - IdxConstraint *pLink; /* See above */ -}; - -/* -** A single scan of a single table. -*/ -struct IdxScan { - IdxTable *pTab; /* Associated table object */ - int iDb; /* Database containing table zTable */ - i64 covering; /* Mask of columns required for cov. index */ - IdxConstraint *pOrder; /* ORDER BY columns */ - IdxConstraint *pEq; /* List of == constraints */ - IdxConstraint *pRange; /* List of < constraints */ - IdxScan *pNextScan; /* Next IdxScan object for same analysis */ -}; - -/* -** Information regarding a single database table. Extracted from -** "PRAGMA table_info" by function idxGetTableInfo(). -*/ -struct IdxColumn { - char *zName; - char *zColl; - int iPk; -}; -struct IdxTable { - int nCol; - char *zName; /* Table name */ - IdxColumn *aCol; - IdxTable *pNext; /* Next table in linked list of all tables */ -}; - -/* -** An object of the following type is created for each unique table/write-op -** seen. The objects are stored in a singly-linked list beginning at -** sqlite3expert.pWrite. -*/ -struct IdxWrite { - IdxTable *pTab; - int eOp; /* SQLITE_UPDATE, DELETE or INSERT */ - IdxWrite *pNext; -}; - -/* -** Each statement being analyzed is represented by an instance of this -** structure. -*/ -struct IdxStatement { - int iId; /* Statement number */ - char *zSql; /* SQL statement */ - char *zIdx; /* Indexes */ - char *zEQP; /* Plan */ - IdxStatement *pNext; -}; - - -/* -** A hash table for storing strings. With space for a payload string -** with each entry. Methods are: -** -** idxHashInit() -** idxHashClear() -** idxHashAdd() -** idxHashSearch() -*/ -#define IDX_HASH_SIZE 1023 -typedef struct IdxHashEntry IdxHashEntry; -typedef struct IdxHash IdxHash; -struct IdxHashEntry { - char *zKey; /* nul-terminated key */ - char *zVal; /* nul-terminated value string */ - char *zVal2; /* nul-terminated value string 2 */ - IdxHashEntry *pHashNext; /* Next entry in same hash bucket */ - IdxHashEntry *pNext; /* Next entry in hash */ -}; -struct IdxHash { - IdxHashEntry *pFirst; - IdxHashEntry *aHash[IDX_HASH_SIZE]; -}; - -/* -** sqlite3expert object. -*/ -struct sqlite3expert { - int iSample; /* Percentage of tables to sample for stat1 */ - sqlite3 *db; /* User database */ - sqlite3 *dbm; /* In-memory db for this analysis */ - sqlite3 *dbv; /* Vtab schema for this analysis */ - IdxTable *pTable; /* List of all IdxTable objects */ - IdxScan *pScan; /* List of scan objects */ - IdxWrite *pWrite; /* List of write objects */ - IdxStatement *pStatement; /* List of IdxStatement objects */ - int bRun; /* True once analysis has run */ - char **pzErrmsg; - int rc; /* Error code from whereinfo hook */ - IdxHash hIdx; /* Hash containing all candidate indexes */ - char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */ -}; - - -/* -** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). -** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL. -*/ -static void *idxMalloc(int *pRc, int nByte){ - void *pRet; - assert( *pRc==SQLITE_OK ); - assert( nByte>0 ); - pRet = sqlite3_malloc(nByte); - if( pRet ){ - memset(pRet, 0, nByte); - }else{ - *pRc = SQLITE_NOMEM; - } - return pRet; -} - -/* -** Initialize an IdxHash hash table. -*/ -static void idxHashInit(IdxHash *pHash){ - memset(pHash, 0, sizeof(IdxHash)); -} - -/* -** Reset an IdxHash hash table. -*/ -static void idxHashClear(IdxHash *pHash){ - int i; - for(i=0; iaHash[i]; pEntry; pEntry=pNext){ - pNext = pEntry->pHashNext; - sqlite3_free(pEntry->zVal2); - sqlite3_free(pEntry); - } - } - memset(pHash, 0, sizeof(IdxHash)); -} - -/* -** Return the index of the hash bucket that the string specified by the -** arguments to this function belongs. -*/ -static int idxHashString(const char *z, int n){ - unsigned int ret = 0; - int i; - for(i=0; i=0 ); - for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ - if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ - return 1; - } - } - pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1); - if( pEntry ){ - pEntry->zKey = (char*)&pEntry[1]; - memcpy(pEntry->zKey, zKey, nKey); - if( zVal ){ - pEntry->zVal = &pEntry->zKey[nKey+1]; - memcpy(pEntry->zVal, zVal, nVal); - } - pEntry->pHashNext = pHash->aHash[iHash]; - pHash->aHash[iHash] = pEntry; - - pEntry->pNext = pHash->pFirst; - pHash->pFirst = pEntry; - } - return 0; -} - -/* -** If zKey/nKey is present in the hash table, return a pointer to the -** hash-entry object. -*/ -static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){ - int iHash; - IdxHashEntry *pEntry; - if( nKey<0 ) nKey = STRLEN(zKey); - iHash = idxHashString(zKey, nKey); - assert( iHash>=0 ); - for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ - if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ - return pEntry; - } - } - return 0; -} - -/* -** If the hash table contains an entry with a key equal to the string -** passed as the final two arguments to this function, return a pointer -** to the payload string. Otherwise, if zKey/nKey is not present in the -** hash table, return NULL. -*/ -static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){ - IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey); - if( pEntry ) return pEntry->zVal; - return 0; -} - -/* -** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl -** variable to point to a copy of nul-terminated string zColl. -*/ -static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){ - IdxConstraint *pNew; - int nColl = STRLEN(zColl); - - assert( *pRc==SQLITE_OK ); - pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1); - if( pNew ){ - pNew->zColl = (char*)&pNew[1]; - memcpy(pNew->zColl, zColl, nColl+1); - } - return pNew; -} - -/* -** An error associated with database handle db has just occurred. Pass -** the error message to callback function xOut. -*/ -static void idxDatabaseError( - sqlite3 *db, /* Database handle */ - char **pzErrmsg /* Write error here */ -){ - *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); -} - -/* -** Prepare an SQL statement. -*/ -static int idxPrepareStmt( - sqlite3 *db, /* Database handle to compile against */ - sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ - char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ - const char *zSql /* SQL statement to compile */ -){ - int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); - if( rc!=SQLITE_OK ){ - *ppStmt = 0; - idxDatabaseError(db, pzErrmsg); - } - return rc; -} - -/* -** Prepare an SQL statement using the results of a printf() formatting. -*/ -static int idxPrintfPrepareStmt( - sqlite3 *db, /* Database handle to compile against */ - sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ - char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ - const char *zFmt, /* printf() format of SQL statement */ - ... /* Trailing printf() arguments */ -){ - va_list ap; - int rc; - char *zSql; - va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql); - sqlite3_free(zSql); - } - va_end(ap); - return rc; -} - - -/************************************************************************* -** Beginning of virtual table implementation. -*/ -typedef struct ExpertVtab ExpertVtab; -struct ExpertVtab { - sqlite3_vtab base; - IdxTable *pTab; - sqlite3expert *pExpert; -}; - -typedef struct ExpertCsr ExpertCsr; -struct ExpertCsr { - sqlite3_vtab_cursor base; - sqlite3_stmt *pData; -}; - -static char *expertDequote(const char *zIn){ - int n = STRLEN(zIn); - char *zRet = sqlite3_malloc(n); - - assert( zIn[0]=='\'' ); - assert( zIn[n-1]=='\'' ); - - if( zRet ){ - int iOut = 0; - int iIn = 0; - for(iIn=1; iIn<(n-1); iIn++){ - if( zIn[iIn]=='\'' ){ - assert( zIn[iIn+1]=='\'' ); - iIn++; - } - zRet[iOut++] = zIn[iIn]; - } - zRet[iOut] = '\0'; - } - - return zRet; -} - -/* -** This function is the implementation of both the xConnect and xCreate -** methods of the r-tree virtual table. -** -** argv[0] -> module name -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> column names... -*/ -static int expertConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - sqlite3expert *pExpert = (sqlite3expert*)pAux; - ExpertVtab *p = 0; - int rc; - - if( argc!=4 ){ - *pzErr = sqlite3_mprintf("internal error!"); - rc = SQLITE_ERROR; - }else{ - char *zCreateTable = expertDequote(argv[3]); - if( zCreateTable ){ - rc = sqlite3_declare_vtab(db, zCreateTable); - if( rc==SQLITE_OK ){ - p = idxMalloc(&rc, sizeof(ExpertVtab)); - } - if( rc==SQLITE_OK ){ - p->pExpert = pExpert; - p->pTab = pExpert->pTable; - assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 ); - } - sqlite3_free(zCreateTable); - }else{ - rc = SQLITE_NOMEM; - } - } - - *ppVtab = (sqlite3_vtab*)p; - return rc; -} - -static int expertDisconnect(sqlite3_vtab *pVtab){ - ExpertVtab *p = (ExpertVtab*)pVtab; - sqlite3_free(p); - return SQLITE_OK; -} - -static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){ - ExpertVtab *p = (ExpertVtab*)pVtab; - int rc = SQLITE_OK; - int n = 0; - IdxScan *pScan; - const int opmask = - SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT | - SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE | - SQLITE_INDEX_CONSTRAINT_LE; - - pScan = idxMalloc(&rc, sizeof(IdxScan)); - if( pScan ){ - int i; - - /* Link the new scan object into the list */ - pScan->pTab = p->pTab; - pScan->pNextScan = p->pExpert->pScan; - p->pExpert->pScan = pScan; - - /* Add the constraints to the IdxScan object */ - for(i=0; inConstraint; i++){ - struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; - if( pCons->usable - && pCons->iColumn>=0 - && p->pTab->aCol[pCons->iColumn].iPk==0 - && (pCons->op & opmask) - ){ - IdxConstraint *pNew; - const char *zColl = sqlite3_vtab_collation(pIdxInfo, i); - pNew = idxNewConstraint(&rc, zColl); - if( pNew ){ - pNew->iCol = pCons->iColumn; - if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - pNew->pNext = pScan->pEq; - pScan->pEq = pNew; - }else{ - pNew->bRange = 1; - pNew->pNext = pScan->pRange; - pScan->pRange = pNew; - } - } - n++; - pIdxInfo->aConstraintUsage[i].argvIndex = n; - } - } - - /* Add the ORDER BY to the IdxScan object */ - for(i=pIdxInfo->nOrderBy-1; i>=0; i--){ - int iCol = pIdxInfo->aOrderBy[i].iColumn; - if( iCol>=0 ){ - IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl); - if( pNew ){ - pNew->iCol = iCol; - pNew->bDesc = pIdxInfo->aOrderBy[i].desc; - pNew->pNext = pScan->pOrder; - pNew->pLink = pScan->pOrder; - pScan->pOrder = pNew; - n++; - } - } - } - } - - pIdxInfo->estimatedCost = 1000000.0 / (n+1); - return rc; -} - -static int expertUpdate( - sqlite3_vtab *pVtab, - int nData, - sqlite3_value **azData, - sqlite_int64 *pRowid -){ - (void)pVtab; - (void)nData; - (void)azData; - (void)pRowid; - return SQLITE_OK; -} - -/* -** Virtual table module xOpen method. -*/ -static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ - int rc = SQLITE_OK; - ExpertCsr *pCsr; - (void)pVTab; - pCsr = idxMalloc(&rc, sizeof(ExpertCsr)); - *ppCursor = (sqlite3_vtab_cursor*)pCsr; - return rc; -} - -/* -** Virtual table module xClose method. -*/ -static int expertClose(sqlite3_vtab_cursor *cur){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - sqlite3_finalize(pCsr->pData); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Virtual table module xEof method. -** -** Return non-zero if the cursor does not currently point to a valid -** record (i.e if the scan has finished), or zero otherwise. -*/ -static int expertEof(sqlite3_vtab_cursor *cur){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - return pCsr->pData==0; -} - -/* -** Virtual table module xNext method. -*/ -static int expertNext(sqlite3_vtab_cursor *cur){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - int rc = SQLITE_OK; - - assert( pCsr->pData ); - rc = sqlite3_step(pCsr->pData); - if( rc!=SQLITE_ROW ){ - rc = sqlite3_finalize(pCsr->pData); - pCsr->pData = 0; - }else{ - rc = SQLITE_OK; - } - - return rc; -} - -/* -** Virtual table module xRowid method. -*/ -static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - (void)cur; - *pRowid = 0; - return SQLITE_OK; -} - -/* -** Virtual table module xColumn method. -*/ -static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - sqlite3_value *pVal; - pVal = sqlite3_column_value(pCsr->pData, i); - if( pVal ){ - sqlite3_result_value(ctx, pVal); - } - return SQLITE_OK; -} - -/* -** Virtual table module xFilter method. -*/ -static int expertFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab); - sqlite3expert *pExpert = pVtab->pExpert; - int rc; - - (void)idxNum; - (void)idxStr; - (void)argc; - (void)argv; - rc = sqlite3_finalize(pCsr->pData); - pCsr->pData = 0; - if( rc==SQLITE_OK ){ - rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg, - "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName - ); - } - - if( rc==SQLITE_OK ){ - rc = expertNext(cur); - } - return rc; -} - -static int idxRegisterVtab(sqlite3expert *p){ - static sqlite3_module expertModule = { - 2, /* iVersion */ - expertConnect, /* xCreate - create a table */ - expertConnect, /* xConnect - connect to an existing table */ - expertBestIndex, /* xBestIndex - Determine search strategy */ - expertDisconnect, /* xDisconnect - Disconnect from a table */ - expertDisconnect, /* xDestroy - Drop a table */ - expertOpen, /* xOpen - open a cursor */ - expertClose, /* xClose - close a cursor */ - expertFilter, /* xFilter - configure scan constraints */ - expertNext, /* xNext - advance a cursor */ - expertEof, /* xEof */ - expertColumn, /* xColumn - read data */ - expertRowid, /* xRowid - read data */ - expertUpdate, /* xUpdate - write data */ - 0, /* xBegin - begin transaction */ - 0, /* xSync - sync transaction */ - 0, /* xCommit - commit transaction */ - 0, /* xRollback - rollback transaction */ - 0, /* xFindFunction - function overloading */ - 0, /* xRename - rename the table */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - }; - - return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p); -} -/* -** End of virtual table implementation. -*************************************************************************/ -/* -** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function -** is called, set it to the return value of sqlite3_finalize() before -** returning. Otherwise, discard the sqlite3_finalize() return value. -*/ -static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){ - int rc = sqlite3_finalize(pStmt); - if( *pRc==SQLITE_OK ) *pRc = rc; -} - -/* -** Attempt to allocate an IdxTable structure corresponding to table zTab -** in the main database of connection db. If successful, set (*ppOut) to -** point to the new object and return SQLITE_OK. Otherwise, return an -** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be -** set to point to an error string. -** -** It is the responsibility of the caller to eventually free either the -** IdxTable object or error message using sqlite3_free(). -*/ -static int idxGetTableInfo( - sqlite3 *db, /* Database connection to read details from */ - const char *zTab, /* Table name */ - IdxTable **ppOut, /* OUT: New object (if successful) */ - char **pzErrmsg /* OUT: Error message (if not) */ -){ - sqlite3_stmt *p1 = 0; - int nCol = 0; - int nTab = STRLEN(zTab); - int nByte = sizeof(IdxTable) + nTab + 1; - IdxTable *pNew = 0; - int rc, rc2; - char *pCsr = 0; - - rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ - const char *zCol = (const char*)sqlite3_column_text(p1, 1); - nByte += 1 + STRLEN(zCol); - rc = sqlite3_table_column_metadata( - db, "main", zTab, zCol, 0, &zCol, 0, 0, 0 - ); - nByte += 1 + STRLEN(zCol); - nCol++; - } - rc2 = sqlite3_reset(p1); - if( rc==SQLITE_OK ) rc = rc2; - - nByte += sizeof(IdxColumn) * nCol; - if( rc==SQLITE_OK ){ - pNew = idxMalloc(&rc, nByte); - } - if( rc==SQLITE_OK ){ - pNew->aCol = (IdxColumn*)&pNew[1]; - pNew->nCol = nCol; - pCsr = (char*)&pNew->aCol[nCol]; - } - - nCol = 0; - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ - const char *zCol = (const char*)sqlite3_column_text(p1, 1); - int nCopy = STRLEN(zCol) + 1; - pNew->aCol[nCol].zName = pCsr; - pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5); - memcpy(pCsr, zCol, nCopy); - pCsr += nCopy; - - rc = sqlite3_table_column_metadata( - db, "main", zTab, zCol, 0, &zCol, 0, 0, 0 - ); - if( rc==SQLITE_OK ){ - nCopy = STRLEN(zCol) + 1; - pNew->aCol[nCol].zColl = pCsr; - memcpy(pCsr, zCol, nCopy); - pCsr += nCopy; - } - - nCol++; - } - idxFinalize(&rc, p1); - - if( rc!=SQLITE_OK ){ - sqlite3_free(pNew); - pNew = 0; - }else{ - pNew->zName = pCsr; - memcpy(pNew->zName, zTab, nTab+1); - } - - *ppOut = pNew; - return rc; -} - -/* -** This function is a no-op if *pRc is set to anything other than -** SQLITE_OK when it is called. -** -** If *pRc is initially set to SQLITE_OK, then the text specified by -** the printf() style arguments is appended to zIn and the result returned -** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on -** zIn before returning. -*/ -static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){ - va_list ap; - char *zAppend = 0; - char *zRet = 0; - int nIn = zIn ? STRLEN(zIn) : 0; - int nAppend = 0; - va_start(ap, zFmt); - if( *pRc==SQLITE_OK ){ - zAppend = sqlite3_vmprintf(zFmt, ap); - if( zAppend ){ - nAppend = STRLEN(zAppend); - zRet = (char*)sqlite3_malloc(nIn + nAppend + 1); - } - if( zAppend && zRet ){ - if( nIn ) memcpy(zRet, zIn, nIn); - memcpy(&zRet[nIn], zAppend, nAppend+1); - }else{ - sqlite3_free(zRet); - zRet = 0; - *pRc = SQLITE_NOMEM; - } - sqlite3_free(zAppend); - sqlite3_free(zIn); - } - va_end(ap); - return zRet; -} - -/* -** Return true if zId must be quoted in order to use it as an SQL -** identifier, or false otherwise. -*/ -static int idxIdentifierRequiresQuotes(const char *zId){ - int i; - for(i=0; zId[i]; i++){ - if( !(zId[i]=='_') - && !(zId[i]>='0' && zId[i]<='9') - && !(zId[i]>='a' && zId[i]<='z') - && !(zId[i]>='A' && zId[i]<='Z') - ){ - return 1; - } - } - return 0; -} - -/* -** This function appends an index column definition suitable for constraint -** pCons to the string passed as zIn and returns the result. -*/ -static char *idxAppendColDefn( - int *pRc, /* IN/OUT: Error code */ - char *zIn, /* Column defn accumulated so far */ - IdxTable *pTab, /* Table index will be created on */ - IdxConstraint *pCons -){ - char *zRet = zIn; - IdxColumn *p = &pTab->aCol[pCons->iCol]; - if( zRet ) zRet = idxAppendText(pRc, zRet, ", "); - - if( idxIdentifierRequiresQuotes(p->zName) ){ - zRet = idxAppendText(pRc, zRet, "%Q", p->zName); - }else{ - zRet = idxAppendText(pRc, zRet, "%s", p->zName); - } - - if( sqlite3_stricmp(p->zColl, pCons->zColl) ){ - if( idxIdentifierRequiresQuotes(pCons->zColl) ){ - zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl); - }else{ - zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl); - } - } - - if( pCons->bDesc ){ - zRet = idxAppendText(pRc, zRet, " DESC"); - } - return zRet; -} - -/* -** Search database dbm for an index compatible with the one idxCreateFromCons() -** would create from arguments pScan, pEq and pTail. If no error occurs and -** such an index is found, return non-zero. Or, if no such index is found, -** return zero. -** -** If an error occurs, set *pRc to an SQLite error code and return zero. -*/ -static int idxFindCompatible( - int *pRc, /* OUT: Error code */ - sqlite3* dbm, /* Database to search */ - IdxScan *pScan, /* Scan for table to search for index on */ - IdxConstraint *pEq, /* List of == constraints */ - IdxConstraint *pTail /* List of range constraints */ -){ - const char *zTbl = pScan->pTab->zName; - sqlite3_stmt *pIdxList = 0; - IdxConstraint *pIter; - int nEq = 0; /* Number of elements in pEq */ - int rc; - - /* Count the elements in list pEq */ - for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++; - - rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl); - while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){ - int bMatch = 1; - IdxConstraint *pT = pTail; - sqlite3_stmt *pInfo = 0; - const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1); - - /* Zero the IdxConstraint.bFlag values in the pEq list */ - for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0; - - rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx); - while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){ - int iIdx = sqlite3_column_int(pInfo, 0); - int iCol = sqlite3_column_int(pInfo, 1); - const char *zColl = (const char*)sqlite3_column_text(pInfo, 4); - - if( iIdxpLink){ - if( pIter->bFlag ) continue; - if( pIter->iCol!=iCol ) continue; - if( sqlite3_stricmp(pIter->zColl, zColl) ) continue; - pIter->bFlag = 1; - break; - } - if( pIter==0 ){ - bMatch = 0; - break; - } - }else{ - if( pT ){ - if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){ - bMatch = 0; - break; - } - pT = pT->pLink; - } - } - } - idxFinalize(&rc, pInfo); - - if( rc==SQLITE_OK && bMatch ){ - sqlite3_finalize(pIdxList); - return 1; - } - } - idxFinalize(&rc, pIdxList); - - *pRc = rc; - return 0; -} - -static int idxCreateFromCons( - sqlite3expert *p, - IdxScan *pScan, - IdxConstraint *pEq, - IdxConstraint *pTail -){ - sqlite3 *dbm = p->dbm; - int rc = SQLITE_OK; - if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){ - IdxTable *pTab = pScan->pTab; - char *zCols = 0; - char *zIdx = 0; - IdxConstraint *pCons; - unsigned int h = 0; - const char *zFmt; - - for(pCons=pEq; pCons; pCons=pCons->pLink){ - zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); - } - for(pCons=pTail; pCons; pCons=pCons->pLink){ - zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); - } - - if( rc==SQLITE_OK ){ - /* Hash the list of columns to come up with a name for the index */ - const char *zTable = pScan->pTab->zName; - char *zName; /* Index name */ - int i; - for(i=0; zCols[i]; i++){ - h += ((h<<3) + zCols[i]); - } - zName = sqlite3_mprintf("%s_idx_%08x", zTable, h); - if( zName==0 ){ - rc = SQLITE_NOMEM; - }else{ - if( idxIdentifierRequiresQuotes(zTable) ){ - zFmt = "CREATE INDEX '%q' ON %Q(%s)"; - }else{ - zFmt = "CREATE INDEX %s ON %s(%s)"; - } - zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols); - if( !zIdx ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg); - idxHashAdd(&rc, &p->hIdx, zName, zIdx); - } - sqlite3_free(zName); - sqlite3_free(zIdx); - } - } - - sqlite3_free(zCols); - } - return rc; -} - -/* -** Return true if list pList (linked by IdxConstraint.pLink) contains -** a constraint compatible with *p. Otherwise return false. -*/ -static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){ - IdxConstraint *pCmp; - for(pCmp=pList; pCmp; pCmp=pCmp->pLink){ - if( p->iCol==pCmp->iCol ) return 1; - } - return 0; -} - -static int idxCreateFromWhere( - sqlite3expert *p, - IdxScan *pScan, /* Create indexes for this scan */ - IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */ -){ - IdxConstraint *p1 = 0; - IdxConstraint *pCon; - int rc; - - /* Gather up all the == constraints. */ - for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){ - if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ - pCon->pLink = p1; - p1 = pCon; - } - } - - /* Create an index using the == constraints collected above. And the - ** range constraint/ORDER BY terms passed in by the caller, if any. */ - rc = idxCreateFromCons(p, pScan, p1, pTail); - - /* If no range/ORDER BY passed by the caller, create a version of the - ** index for each range constraint. */ - if( pTail==0 ){ - for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){ - assert( pCon->pLink==0 ); - if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ - rc = idxCreateFromCons(p, pScan, p1, pCon); - } - } - } - - return rc; -} - -/* -** Create candidate indexes in database [dbm] based on the data in -** linked-list pScan. -*/ -static int idxCreateCandidates(sqlite3expert *p){ - int rc = SQLITE_OK; - IdxScan *pIter; - - for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){ - rc = idxCreateFromWhere(p, pIter, 0); - if( rc==SQLITE_OK && pIter->pOrder ){ - rc = idxCreateFromWhere(p, pIter, pIter->pOrder); - } - } - - return rc; -} - -/* -** Free all elements of the linked list starting at pConstraint. -*/ -static void idxConstraintFree(IdxConstraint *pConstraint){ - IdxConstraint *pNext; - IdxConstraint *p; - - for(p=pConstraint; p; p=pNext){ - pNext = p->pNext; - sqlite3_free(p); - } -} - -/* -** Free all elements of the linked list starting from pScan up until pLast -** (pLast is not freed). -*/ -static void idxScanFree(IdxScan *pScan, IdxScan *pLast){ - IdxScan *p; - IdxScan *pNext; - for(p=pScan; p!=pLast; p=pNext){ - pNext = p->pNextScan; - idxConstraintFree(p->pOrder); - idxConstraintFree(p->pEq); - idxConstraintFree(p->pRange); - sqlite3_free(p); - } -} - -/* -** Free all elements of the linked list starting from pStatement up -** until pLast (pLast is not freed). -*/ -static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){ - IdxStatement *p; - IdxStatement *pNext; - for(p=pStatement; p!=pLast; p=pNext){ - pNext = p->pNext; - sqlite3_free(p->zEQP); - sqlite3_free(p->zIdx); - sqlite3_free(p); - } -} - -/* -** Free the linked list of IdxTable objects starting at pTab. -*/ -static void idxTableFree(IdxTable *pTab){ - IdxTable *pIter; - IdxTable *pNext; - for(pIter=pTab; pIter; pIter=pNext){ - pNext = pIter->pNext; - sqlite3_free(pIter); - } -} - -/* -** Free the linked list of IdxWrite objects starting at pTab. -*/ -static void idxWriteFree(IdxWrite *pTab){ - IdxWrite *pIter; - IdxWrite *pNext; - for(pIter=pTab; pIter; pIter=pNext){ - pNext = pIter->pNext; - sqlite3_free(pIter); - } -} - - - -/* -** This function is called after candidate indexes have been created. It -** runs all the queries to see which indexes they prefer, and populates -** IdxStatement.zIdx and IdxStatement.zEQP with the results. -*/ -int idxFindIndexes( - sqlite3expert *p, - char **pzErr /* OUT: Error message (sqlite3_malloc) */ -){ - IdxStatement *pStmt; - sqlite3 *dbm = p->dbm; - int rc = SQLITE_OK; - - IdxHash hIdx; - idxHashInit(&hIdx); - - for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){ - IdxHashEntry *pEntry; - sqlite3_stmt *pExplain = 0; - idxHashClear(&hIdx); - rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr, - "EXPLAIN QUERY PLAN %s", pStmt->zSql - ); - while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){ - /* int iId = sqlite3_column_int(pExplain, 0); */ - /* int iParent = sqlite3_column_int(pExplain, 1); */ - /* int iNotUsed = sqlite3_column_int(pExplain, 2); */ - const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3); - int nDetail; - int i; - - if( !zDetail ) continue; - nDetail = STRLEN(zDetail); - - for(i=0; ihIdx, zIdx, nIdx); - if( zSql ){ - idxHashAdd(&rc, &hIdx, zSql, 0); - if( rc ) goto find_indexes_out; - } - break; - } - } - - if( zDetail[0]!='-' ){ - pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail); - } - } - - for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ - pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey); - } - - idxFinalize(&rc, pExplain); - } - - find_indexes_out: - idxHashClear(&hIdx); - return rc; -} - -static int idxAuthCallback( - void *pCtx, - int eOp, - const char *z3, - const char *z4, - const char *zDb, - const char *zTrigger -){ - int rc = SQLITE_OK; - (void)z4; - (void)zTrigger; - if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){ - if( sqlite3_stricmp(zDb, "main")==0 ){ - sqlite3expert *p = (sqlite3expert*)pCtx; - IdxTable *pTab; - for(pTab=p->pTable; pTab; pTab=pTab->pNext){ - if( 0==sqlite3_stricmp(z3, pTab->zName) ) break; - } - if( pTab ){ - IdxWrite *pWrite; - for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){ - if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break; - } - if( pWrite==0 ){ - pWrite = idxMalloc(&rc, sizeof(IdxWrite)); - if( rc==SQLITE_OK ){ - pWrite->pTab = pTab; - pWrite->eOp = eOp; - pWrite->pNext = p->pWrite; - p->pWrite = pWrite; - } - } - } - } - } - return rc; -} - -static int idxProcessOneTrigger( - sqlite3expert *p, - IdxWrite *pWrite, - char **pzErr -){ - static const char *zInt = UNIQUE_TABLE_NAME; - static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME; - IdxTable *pTab = pWrite->pTab; - const char *zTab = pTab->zName; - const char *zSql = - "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema " - "WHERE tbl_name = %Q AND type IN ('table', 'trigger') " - "ORDER BY type;"; - sqlite3_stmt *pSelect = 0; - int rc = SQLITE_OK; - char *zWrite = 0; - - /* Create the table and its triggers in the temp schema */ - rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){ - const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0); - rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr); - } - idxFinalize(&rc, pSelect); - - /* Rename the table in the temp schema to zInt */ - if( rc==SQLITE_OK ){ - char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt); - if( z==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr); - sqlite3_free(z); - } - } - - switch( pWrite->eOp ){ - case SQLITE_INSERT: { - int i; - zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt); - for(i=0; inCol; i++){ - zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", "); - } - zWrite = idxAppendText(&rc, zWrite, ")"); - break; - } - case SQLITE_UPDATE: { - int i; - zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt); - for(i=0; inCol; i++){ - zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", - pTab->aCol[i].zName - ); - } - break; - } - default: { - assert( pWrite->eOp==SQLITE_DELETE ); - if( rc==SQLITE_OK ){ - zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt); - if( zWrite==0 ) rc = SQLITE_NOMEM; - } - } - } - - if( rc==SQLITE_OK ){ - sqlite3_stmt *pX = 0; - rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0); - idxFinalize(&rc, pX); - if( rc!=SQLITE_OK ){ - idxDatabaseError(p->dbv, pzErr); - } - } - sqlite3_free(zWrite); - - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr); - } - - return rc; -} - -static int idxProcessTriggers(sqlite3expert *p, char **pzErr){ - int rc = SQLITE_OK; - IdxWrite *pEnd = 0; - IdxWrite *pFirst = p->pWrite; - - while( rc==SQLITE_OK && pFirst!=pEnd ){ - IdxWrite *pIter; - for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){ - rc = idxProcessOneTrigger(p, pIter, pzErr); - } - pEnd = pFirst; - pFirst = p->pWrite; - } - - return rc; -} - - -static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){ - int rc = idxRegisterVtab(p); - sqlite3_stmt *pSchema = 0; - - /* For each table in the main db schema: - ** - ** 1) Add an entry to the p->pTable list, and - ** 2) Create the equivalent virtual table in dbv. - */ - rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg, - "SELECT type, name, sql, 1 FROM sqlite_schema " - "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' " - " UNION ALL " - "SELECT type, name, sql, 2 FROM sqlite_schema " - "WHERE type = 'trigger'" - " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') " - "ORDER BY 4, 1" - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){ - const char *zType = (const char*)sqlite3_column_text(pSchema, 0); - const char *zName = (const char*)sqlite3_column_text(pSchema, 1); - const char *zSql = (const char*)sqlite3_column_text(pSchema, 2); - - if( zType[0]=='v' || zType[1]=='r' ){ - rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg); - }else{ - IdxTable *pTab; - rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg); - if( rc==SQLITE_OK ){ - int i; - char *zInner = 0; - char *zOuter = 0; - pTab->pNext = p->pTable; - p->pTable = pTab; - - /* The statement the vtab will pass to sqlite3_declare_vtab() */ - zInner = idxAppendText(&rc, 0, "CREATE TABLE x("); - for(i=0; inCol; i++){ - zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", - (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl - ); - } - zInner = idxAppendText(&rc, zInner, ")"); - - /* The CVT statement to create the vtab */ - zOuter = idxAppendText(&rc, 0, - "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner - ); - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg); - } - sqlite3_free(zInner); - sqlite3_free(zOuter); - } - } - } - idxFinalize(&rc, pSchema); - return rc; -} - -struct IdxSampleCtx { - int iTarget; - double target; /* Target nRet/nRow value */ - double nRow; /* Number of rows seen */ - double nRet; /* Number of rows returned */ -}; - -static void idxSampleFunc( - sqlite3_context *pCtx, - int argc, - sqlite3_value **argv -){ - struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx); - int bRet; - - (void)argv; - assert( argc==0 ); - if( p->nRow==0.0 ){ - bRet = 1; - }else{ - bRet = (p->nRet / p->nRow) <= p->target; - if( bRet==0 ){ - unsigned short rnd; - sqlite3_randomness(2, (void*)&rnd); - bRet = ((int)rnd % 100) <= p->iTarget; - } - } - - sqlite3_result_int(pCtx, bRet); - p->nRow += 1.0; - p->nRet += (double)bRet; -} - -struct IdxRemCtx { - int nSlot; - struct IdxRemSlot { - int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */ - i64 iVal; /* SQLITE_INTEGER value */ - double rVal; /* SQLITE_FLOAT value */ - int nByte; /* Bytes of space allocated at z */ - int n; /* Size of buffer z */ - char *z; /* SQLITE_TEXT/BLOB value */ - } aSlot[1]; -}; - -/* -** Implementation of scalar function rem(). -*/ -static void idxRemFunc( - sqlite3_context *pCtx, - int argc, - sqlite3_value **argv -){ - struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx); - struct IdxRemSlot *pSlot; - int iSlot; - assert( argc==2 ); - - iSlot = sqlite3_value_int(argv[0]); - assert( iSlot<=p->nSlot ); - pSlot = &p->aSlot[iSlot]; - - switch( pSlot->eType ){ - case SQLITE_NULL: - /* no-op */ - break; - - case SQLITE_INTEGER: - sqlite3_result_int64(pCtx, pSlot->iVal); - break; - - case SQLITE_FLOAT: - sqlite3_result_double(pCtx, pSlot->rVal); - break; - - case SQLITE_BLOB: - sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); - break; - - case SQLITE_TEXT: - sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); - break; - } - - pSlot->eType = sqlite3_value_type(argv[1]); - switch( pSlot->eType ){ - case SQLITE_NULL: - /* no-op */ - break; - - case SQLITE_INTEGER: - pSlot->iVal = sqlite3_value_int64(argv[1]); - break; - - case SQLITE_FLOAT: - pSlot->rVal = sqlite3_value_double(argv[1]); - break; - - case SQLITE_BLOB: - case SQLITE_TEXT: { - int nByte = sqlite3_value_bytes(argv[1]); - if( nByte>pSlot->nByte ){ - char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2); - if( zNew==0 ){ - sqlite3_result_error_nomem(pCtx); - return; - } - pSlot->nByte = nByte*2; - pSlot->z = zNew; - } - pSlot->n = nByte; - if( pSlot->eType==SQLITE_BLOB ){ - memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte); - }else{ - memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte); - } - break; - } - } -} - -static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){ - int rc = SQLITE_OK; - const char *zMax = - "SELECT max(i.seqno) FROM " - " sqlite_schema AS s, " - " pragma_index_list(s.name) AS l, " - " pragma_index_info(l.name) AS i " - "WHERE s.type = 'table'"; - sqlite3_stmt *pMax = 0; - - *pnMax = 0; - rc = idxPrepareStmt(db, &pMax, pzErr, zMax); - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ - *pnMax = sqlite3_column_int(pMax, 0) + 1; - } - idxFinalize(&rc, pMax); - - return rc; -} - -static int idxPopulateOneStat1( - sqlite3expert *p, - sqlite3_stmt *pIndexXInfo, - sqlite3_stmt *pWriteStat, - const char *zTab, - const char *zIdx, - char **pzErr -){ - char *zCols = 0; - char *zOrder = 0; - char *zQuery = 0; - int nCol = 0; - int i; - sqlite3_stmt *pQuery = 0; - int *aStat = 0; - int rc = SQLITE_OK; - - assert( p->iSample>0 ); - - /* Formulate the query text */ - sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC); - while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){ - const char *zComma = zCols==0 ? "" : ", "; - const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0); - const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1); - zCols = idxAppendText(&rc, zCols, - "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl - ); - zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol); - } - sqlite3_reset(pIndexXInfo); - if( rc==SQLITE_OK ){ - if( p->iSample==100 ){ - zQuery = sqlite3_mprintf( - "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder - ); - }else{ - zQuery = sqlite3_mprintf( - "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder - ); - } - } - sqlite3_free(zCols); - sqlite3_free(zOrder); - - /* Formulate the query text */ - if( rc==SQLITE_OK ){ - sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); - rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery); - } - sqlite3_free(zQuery); - - if( rc==SQLITE_OK ){ - aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1)); - } - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ - IdxHashEntry *pEntry; - char *zStat = 0; - for(i=0; i<=nCol; i++) aStat[i] = 1; - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ - aStat[0]++; - for(i=0; ihIdx, zIdx, STRLEN(zIdx)); - if( pEntry ){ - assert( pEntry->zVal2==0 ); - pEntry->zVal2 = zStat; - }else{ - sqlite3_free(zStat); - } - } - sqlite3_free(aStat); - idxFinalize(&rc, pQuery); - - return rc; -} - -static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){ - int rc; - char *zSql; - - rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); - if( rc!=SQLITE_OK ) return rc; - - zSql = sqlite3_mprintf( - "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab - ); - if( zSql==0 ) return SQLITE_NOMEM; - rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0); - sqlite3_free(zSql); - - return rc; -} - -/* -** This function is called as part of sqlite3_expert_analyze(). Candidate -** indexes have already been created in database sqlite3expert.dbm, this -** function populates sqlite_stat1 table in the same database. -** -** The stat1 data is generated by querying the -*/ -static int idxPopulateStat1(sqlite3expert *p, char **pzErr){ - int rc = SQLITE_OK; - int nMax =0; - struct IdxRemCtx *pCtx = 0; - struct IdxSampleCtx samplectx; - int i; - i64 iPrev = -100000; - sqlite3_stmt *pAllIndex = 0; - sqlite3_stmt *pIndexXInfo = 0; - sqlite3_stmt *pWrite = 0; - - const char *zAllIndex = - "SELECT s.rowid, s.name, l.name FROM " - " sqlite_schema AS s, " - " pragma_index_list(s.name) AS l " - "WHERE s.type = 'table'"; - const char *zIndexXInfo = - "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key"; - const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)"; - - /* If iSample==0, no sqlite_stat1 data is required. */ - if( p->iSample==0 ) return SQLITE_OK; - - rc = idxLargestIndex(p->dbm, &nMax, pzErr); - if( nMax<=0 || rc!=SQLITE_OK ) return rc; - - rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0); - - if( rc==SQLITE_OK ){ - int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax); - pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte); - } - - if( rc==SQLITE_OK ){ - sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); - rc = sqlite3_create_function( - dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0 - ); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function( - p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0 - ); - } - - if( rc==SQLITE_OK ){ - pCtx->nSlot = nMax+1; - rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex); - } - if( rc==SQLITE_OK ){ - rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo); - } - if( rc==SQLITE_OK ){ - rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite); - } - - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){ - i64 iRowid = sqlite3_column_int64(pAllIndex, 0); - const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1); - const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2); - if( p->iSample<100 && iPrev!=iRowid ){ - samplectx.target = (double)p->iSample / 100.0; - samplectx.iTarget = p->iSample; - samplectx.nRow = 0.0; - samplectx.nRet = 0.0; - rc = idxBuildSampleTable(p, zTab); - if( rc!=SQLITE_OK ) break; - } - rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr); - iPrev = iRowid; - } - if( rc==SQLITE_OK && p->iSample<100 ){ - rc = sqlite3_exec(p->dbv, - "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0 - ); - } - - idxFinalize(&rc, pAllIndex); - idxFinalize(&rc, pIndexXInfo); - idxFinalize(&rc, pWrite); - - for(i=0; inSlot; i++){ - sqlite3_free(pCtx->aSlot[i].z); - } - sqlite3_free(pCtx); - - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0); - } - - sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); - return rc; -} - -/* -** Allocate a new sqlite3expert object. -*/ -sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){ - int rc = SQLITE_OK; - sqlite3expert *pNew; - - pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert)); - - /* Open two in-memory databases to work with. The "vtab database" (dbv) - ** will contain a virtual table corresponding to each real table in - ** the user database schema, and a copy of each view. It is used to - ** collect information regarding the WHERE, ORDER BY and other clauses - ** of the user's query. - */ - if( rc==SQLITE_OK ){ - pNew->db = db; - pNew->iSample = 100; - rc = sqlite3_open(":memory:", &pNew->dbv); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_open(":memory:", &pNew->dbm); - if( rc==SQLITE_OK ){ - sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); - } - } - - - /* Copy the entire schema of database [db] into [dbm]. */ - if( rc==SQLITE_OK ){ - sqlite3_stmt *pSql; - rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, - "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'" - " AND sql NOT LIKE 'CREATE VIRTUAL %%'" - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ - const char *zSql = (const char*)sqlite3_column_text(pSql, 0); - rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg); - } - idxFinalize(&rc, pSql); - } - - /* Create the vtab schema */ - if( rc==SQLITE_OK ){ - rc = idxCreateVtabSchema(pNew, pzErrmsg); - } - - /* Register the auth callback with dbv */ - if( rc==SQLITE_OK ){ - sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew); - } - - /* If an error has occurred, free the new object and reutrn NULL. Otherwise, - ** return the new sqlite3expert handle. */ - if( rc!=SQLITE_OK ){ - sqlite3_expert_destroy(pNew); - pNew = 0; - } - return pNew; -} - -/* -** Configure an sqlite3expert object. -*/ -int sqlite3_expert_config(sqlite3expert *p, int op, ...){ - int rc = SQLITE_OK; - va_list ap; - va_start(ap, op); - switch( op ){ - case EXPERT_CONFIG_SAMPLE: { - int iVal = va_arg(ap, int); - if( iVal<0 ) iVal = 0; - if( iVal>100 ) iVal = 100; - p->iSample = iVal; - break; - } - default: - rc = SQLITE_NOTFOUND; - break; - } - - va_end(ap); - return rc; -} - -/* -** Add an SQL statement to the analysis. -*/ -int sqlite3_expert_sql( - sqlite3expert *p, /* From sqlite3_expert_new() */ - const char *zSql, /* SQL statement to add */ - char **pzErr /* OUT: Error message (if any) */ -){ - IdxScan *pScanOrig = p->pScan; - IdxStatement *pStmtOrig = p->pStatement; - int rc = SQLITE_OK; - const char *zStmt = zSql; - - if( p->bRun ) return SQLITE_MISUSE; - - while( rc==SQLITE_OK && zStmt && zStmt[0] ){ - sqlite3_stmt *pStmt = 0; - rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt); - if( rc==SQLITE_OK ){ - if( pStmt ){ - IdxStatement *pNew; - const char *z = sqlite3_sql(pStmt); - int n = STRLEN(z); - pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1); - if( rc==SQLITE_OK ){ - pNew->zSql = (char*)&pNew[1]; - memcpy(pNew->zSql, z, n+1); - pNew->pNext = p->pStatement; - if( p->pStatement ) pNew->iId = p->pStatement->iId+1; - p->pStatement = pNew; - } - sqlite3_finalize(pStmt); - } - }else{ - idxDatabaseError(p->dbv, pzErr); - } - } - - if( rc!=SQLITE_OK ){ - idxScanFree(p->pScan, pScanOrig); - idxStatementFree(p->pStatement, pStmtOrig); - p->pScan = pScanOrig; - p->pStatement = pStmtOrig; - } - - return rc; -} - -int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){ - int rc; - IdxHashEntry *pEntry; - - /* Do trigger processing to collect any extra IdxScan structures */ - rc = idxProcessTriggers(p, pzErr); - - /* Create candidate indexes within the in-memory database file */ - if( rc==SQLITE_OK ){ - rc = idxCreateCandidates(p); - } - - /* Generate the stat1 data */ - if( rc==SQLITE_OK ){ - rc = idxPopulateStat1(p, pzErr); - } - - /* Formulate the EXPERT_REPORT_CANDIDATES text */ - for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ - p->zCandidates = idxAppendText(&rc, p->zCandidates, - "%s;%s%s\n", pEntry->zVal, - pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2 - ); - } - - /* Figure out which of the candidate indexes are preferred by the query - ** planner and report the results to the user. */ - if( rc==SQLITE_OK ){ - rc = idxFindIndexes(p, pzErr); - } - - if( rc==SQLITE_OK ){ - p->bRun = 1; - } - return rc; -} - -/* -** Return the total number of statements that have been added to this -** sqlite3expert using sqlite3_expert_sql(). -*/ -int sqlite3_expert_count(sqlite3expert *p){ - int nRet = 0; - if( p->pStatement ) nRet = p->pStatement->iId+1; - return nRet; -} - -/* -** Return a component of the report. -*/ -const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){ - const char *zRet = 0; - IdxStatement *pStmt; - - if( p->bRun==0 ) return 0; - for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext); - switch( eReport ){ - case EXPERT_REPORT_SQL: - if( pStmt ) zRet = pStmt->zSql; - break; - case EXPERT_REPORT_INDEXES: - if( pStmt ) zRet = pStmt->zIdx; - break; - case EXPERT_REPORT_PLAN: - if( pStmt ) zRet = pStmt->zEQP; - break; - case EXPERT_REPORT_CANDIDATES: - zRet = p->zCandidates; - break; - } - return zRet; -} - -/* -** Free an sqlite3expert object. -*/ -void sqlite3_expert_destroy(sqlite3expert *p){ - if( p ){ - sqlite3_close(p->dbm); - sqlite3_close(p->dbv); - idxScanFree(p->pScan, 0); - idxStatementFree(p->pStatement, 0); - idxTableFree(p->pTable); - idxWriteFree(p->pWrite); - idxHashClear(&p->hIdx); - sqlite3_free(p->zCandidates); - sqlite3_free(p); - } -} - -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ - -/************************* End ../ext/expert/sqlite3expert.c ********************/ - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) -/************************* Begin ../ext/misc/dbdata.c ******************/ -/* -** 2019-04-17 -** -** 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 an implementation of two eponymous virtual tables, -** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the -** "sqlite_dbpage" eponymous virtual table be available. -** -** SQLITE_DBDATA: -** sqlite_dbdata is used to extract data directly from a database b-tree -** page and its associated overflow pages, bypassing the b-tree layer. -** The table schema is equivalent to: -** -** CREATE TABLE sqlite_dbdata( -** pgno INTEGER, -** cell INTEGER, -** field INTEGER, -** value ANY, -** schema TEXT HIDDEN -** ); -** -** IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE -** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND -** "schema". -** -** Each page of the database is inspected. If it cannot be interpreted as -** a b-tree page, or if it is a b-tree page containing 0 entries, the -** sqlite_dbdata table contains no rows for that page. Otherwise, the -** table contains one row for each field in the record associated with -** each cell on the page. For intkey b-trees, the key value is stored in -** field -1. -** -** For example, for the database: -** -** CREATE TABLE t1(a, b); -- root page is page 2 -** INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five'); -** INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten'); -** -** the sqlite_dbdata table contains, as well as from entries related to -** page 1, content equivalent to: -** -** INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES -** (2, 0, -1, 5 ), -** (2, 0, 0, 'v' ), -** (2, 0, 1, 'five'), -** (2, 1, -1, 10 ), -** (2, 1, 0, 'x' ), -** (2, 1, 1, 'ten' ); -** -** If database corruption is encountered, this module does not report an -** error. Instead, it attempts to extract as much data as possible and -** ignores the corruption. -** -** SQLITE_DBPTR: -** The sqlite_dbptr table has the following schema: -** -** CREATE TABLE sqlite_dbptr( -** pgno INTEGER, -** child INTEGER, -** schema TEXT HIDDEN -** ); -** -** It contains one entry for each b-tree pointer between a parent and -** child page in the database. -*/ -#if !defined(SQLITEINT_H) -/* #include "sqlite3ext.h" */ - -/* typedef unsigned char u8; */ - -#endif -SQLITE_EXTENSION_INIT1 -#include -#include - -#define DBDATA_PADDING_BYTES 100 - -typedef struct DbdataTable DbdataTable; -typedef struct DbdataCursor DbdataCursor; - -/* Cursor object */ -struct DbdataCursor { - sqlite3_vtab_cursor base; /* Base class. Must be first */ - sqlite3_stmt *pStmt; /* For fetching database pages */ - - int iPgno; /* Current page number */ - u8 *aPage; /* Buffer containing page */ - int nPage; /* Size of aPage[] in bytes */ - int nCell; /* Number of cells on aPage[] */ - int iCell; /* Current cell number */ - int bOnePage; /* True to stop after one page */ - int szDb; - sqlite3_int64 iRowid; - - /* Only for the sqlite_dbdata table */ - u8 *pRec; /* Buffer containing current record */ - int nRec; /* Size of pRec[] in bytes */ - int nHdr; /* Size of header in bytes */ - int iField; /* Current field number */ - u8 *pHdrPtr; - u8 *pPtr; - - sqlite3_int64 iIntkey; /* Integer key value */ -}; - -/* Table object */ -struct DbdataTable { - sqlite3_vtab base; /* Base class. Must be first */ - sqlite3 *db; /* The database connection */ - sqlite3_stmt *pStmt; /* For fetching database pages */ - int bPtr; /* True for sqlite3_dbptr table */ -}; - -/* Column and schema definitions for sqlite_dbdata */ -#define DBDATA_COLUMN_PGNO 0 -#define DBDATA_COLUMN_CELL 1 -#define DBDATA_COLUMN_FIELD 2 -#define DBDATA_COLUMN_VALUE 3 -#define DBDATA_COLUMN_SCHEMA 4 -#define DBDATA_SCHEMA \ - "CREATE TABLE x(" \ - " pgno INTEGER," \ - " cell INTEGER," \ - " field INTEGER," \ - " value ANY," \ - " schema TEXT HIDDEN" \ - ")" - -/* Column and schema definitions for sqlite_dbptr */ -#define DBPTR_COLUMN_PGNO 0 -#define DBPTR_COLUMN_CHILD 1 -#define DBPTR_COLUMN_SCHEMA 2 -#define DBPTR_SCHEMA \ - "CREATE TABLE x(" \ - " pgno INTEGER," \ - " child INTEGER," \ - " schema TEXT HIDDEN" \ - ")" - -/* -** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual -** table. -*/ -static int dbdataConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - DbdataTable *pTab = 0; - int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA); - - if( rc==SQLITE_OK ){ - pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable)); - if( pTab==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pTab, 0, sizeof(DbdataTable)); - pTab->db = db; - pTab->bPtr = (pAux!=0); - } - } - - *ppVtab = (sqlite3_vtab*)pTab; - return rc; -} - -/* -** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table. -*/ -static int dbdataDisconnect(sqlite3_vtab *pVtab){ - DbdataTable *pTab = (DbdataTable*)pVtab; - if( pTab ){ - sqlite3_finalize(pTab->pStmt); - sqlite3_free(pVtab); - } - return SQLITE_OK; -} - -/* -** This function interprets two types of constraints: -** -** schema=? -** pgno=? -** -** If neither are present, idxNum is set to 0. If schema=? is present, -** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit -** in idxNum is set. -** -** If both parameters are present, schema is in position 0 and pgno in -** position 1. -*/ -static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){ - DbdataTable *pTab = (DbdataTable*)tab; - int i; - int iSchema = -1; - int iPgno = -1; - int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA); - - for(i=0; inConstraint; i++){ - struct sqlite3_index_constraint *p = &pIdx->aConstraint[i]; - if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - if( p->iColumn==colSchema ){ - if( p->usable==0 ) return SQLITE_CONSTRAINT; - iSchema = i; - } - if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){ - iPgno = i; - } - } - } - - if( iSchema>=0 ){ - pIdx->aConstraintUsage[iSchema].argvIndex = 1; - pIdx->aConstraintUsage[iSchema].omit = 1; - } - if( iPgno>=0 ){ - pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0); - pIdx->aConstraintUsage[iPgno].omit = 1; - pIdx->estimatedCost = 100; - pIdx->estimatedRows = 50; - - if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){ - int iCol = pIdx->aOrderBy[0].iColumn; - if( pIdx->nOrderBy==1 ){ - pIdx->orderByConsumed = (iCol==0 || iCol==1); - }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){ - pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1); - } - } - - }else{ - pIdx->estimatedCost = 100000000; - pIdx->estimatedRows = 1000000000; - } - pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00); - return SQLITE_OK; -} - -/* -** Open a new sqlite_dbdata or sqlite_dbptr cursor. -*/ -static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ - DbdataCursor *pCsr; - - pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor)); - if( pCsr==0 ){ - return SQLITE_NOMEM; - }else{ - memset(pCsr, 0, sizeof(DbdataCursor)); - pCsr->base.pVtab = pVTab; - } - - *ppCursor = (sqlite3_vtab_cursor *)pCsr; - return SQLITE_OK; -} - -/* -** Restore a cursor object to the state it was in when first allocated -** by dbdataOpen(). -*/ -static void dbdataResetCursor(DbdataCursor *pCsr){ - DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab); - if( pTab->pStmt==0 ){ - pTab->pStmt = pCsr->pStmt; - }else{ - sqlite3_finalize(pCsr->pStmt); - } - pCsr->pStmt = 0; - pCsr->iPgno = 1; - pCsr->iCell = 0; - pCsr->iField = 0; - pCsr->bOnePage = 0; - sqlite3_free(pCsr->aPage); - sqlite3_free(pCsr->pRec); - pCsr->pRec = 0; - pCsr->aPage = 0; -} - -/* -** Close an sqlite_dbdata or sqlite_dbptr cursor. -*/ -static int dbdataClose(sqlite3_vtab_cursor *pCursor){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - dbdataResetCursor(pCsr); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Utility methods to decode 16 and 32-bit big-endian unsigned integers. -*/ -static unsigned int get_uint16(unsigned char *a){ - return (a[0]<<8)|a[1]; -} -static unsigned int get_uint32(unsigned char *a){ - return ((unsigned int)a[0]<<24) - | ((unsigned int)a[1]<<16) - | ((unsigned int)a[2]<<8) - | ((unsigned int)a[3]); -} - -/* -** Load page pgno from the database via the sqlite_dbpage virtual table. -** If successful, set (*ppPage) to point to a buffer containing the page -** data, (*pnPage) to the size of that buffer in bytes and return -** SQLITE_OK. In this case it is the responsibility of the caller to -** eventually free the buffer using sqlite3_free(). -** -** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and -** return an SQLite error code. -*/ -static int dbdataLoadPage( - DbdataCursor *pCsr, /* Cursor object */ - unsigned int pgno, /* Page number of page to load */ - u8 **ppPage, /* OUT: pointer to page buffer */ - int *pnPage /* OUT: Size of (*ppPage) in bytes */ -){ - int rc2; - int rc = SQLITE_OK; - sqlite3_stmt *pStmt = pCsr->pStmt; - - *ppPage = 0; - *pnPage = 0; - sqlite3_bind_int64(pStmt, 2, pgno); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - int nCopy = sqlite3_column_bytes(pStmt, 0); - if( nCopy>0 ){ - u8 *pPage; - pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES); - if( pPage==0 ){ - rc = SQLITE_NOMEM; - }else{ - const u8 *pCopy = sqlite3_column_blob(pStmt, 0); - memcpy(pPage, pCopy, nCopy); - memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES); - } - *ppPage = pPage; - *pnPage = nCopy; - } - } - rc2 = sqlite3_reset(pStmt); - if( rc==SQLITE_OK ) rc = rc2; - - return rc; -} - -/* -** Read a varint. Put the value in *pVal and return the number of bytes. -*/ -static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){ - sqlite3_int64 v = 0; - int i; - for(i=0; i<8; i++){ - v = (v<<7) + (z[i]&0x7f); - if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; } - } - v = (v<<8) + (z[i]&0xff); - *pVal = v; - return 9; -} - -/* -** Return the number of bytes of space used by an SQLite value of type -** eType. -*/ -static int dbdataValueBytes(int eType){ - switch( eType ){ - case 0: case 8: case 9: - case 10: case 11: - return 0; - case 1: - return 1; - case 2: - return 2; - case 3: - return 3; - case 4: - return 4; - case 5: - return 6; - case 6: - case 7: - return 8; - default: - if( eType>0 ){ - return ((eType-12) / 2); - } - return 0; - } -} - -/* -** Load a value of type eType from buffer pData and use it to set the -** result of context object pCtx. -*/ -static void dbdataValue( - sqlite3_context *pCtx, - int eType, - u8 *pData, - int nData -){ - if( eType>=0 && dbdataValueBytes(eType)<=nData ){ - switch( eType ){ - case 0: - case 10: - case 11: - sqlite3_result_null(pCtx); - break; - - case 8: - sqlite3_result_int(pCtx, 0); - break; - case 9: - sqlite3_result_int(pCtx, 1); - break; - - case 1: case 2: case 3: case 4: case 5: case 6: case 7: { - sqlite3_uint64 v = (signed char)pData[0]; - pData++; - switch( eType ){ - case 7: - case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; - case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; - case 4: v = (v<<8) + pData[0]; pData++; - case 3: v = (v<<8) + pData[0]; pData++; - case 2: v = (v<<8) + pData[0]; pData++; - } - - if( eType==7 ){ - double r; - memcpy(&r, &v, sizeof(r)); - sqlite3_result_double(pCtx, r); - }else{ - sqlite3_result_int64(pCtx, (sqlite3_int64)v); - } - break; - } - - default: { - int n = ((eType-12) / 2); - if( eType % 2 ){ - sqlite3_result_text(pCtx, (const char*)pData, n, SQLITE_TRANSIENT); - }else{ - sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT); - } - } - } - } -} - -/* -** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry. -*/ -static int dbdataNext(sqlite3_vtab_cursor *pCursor){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; - - pCsr->iRowid++; - while( 1 ){ - int rc; - int iOff = (pCsr->iPgno==1 ? 100 : 0); - int bNextPage = 0; - - if( pCsr->aPage==0 ){ - while( 1 ){ - if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK; - rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage); - if( rc!=SQLITE_OK ) return rc; - if( pCsr->aPage ) break; - pCsr->iPgno++; - } - pCsr->iCell = pTab->bPtr ? -2 : 0; - pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]); - } - - if( pTab->bPtr ){ - if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){ - pCsr->iCell = pCsr->nCell; - } - pCsr->iCell++; - if( pCsr->iCell>=pCsr->nCell ){ - sqlite3_free(pCsr->aPage); - pCsr->aPage = 0; - if( pCsr->bOnePage ) return SQLITE_OK; - pCsr->iPgno++; - }else{ - return SQLITE_OK; - } - }else{ - /* If there is no record loaded, load it now. */ - if( pCsr->pRec==0 ){ - int bHasRowid = 0; - int nPointer = 0; - sqlite3_int64 nPayload = 0; - sqlite3_int64 nHdr = 0; - int iHdr; - int U, X; - int nLocal; - - switch( pCsr->aPage[iOff] ){ - case 0x02: - nPointer = 4; - break; - case 0x0a: - break; - case 0x0d: - bHasRowid = 1; - break; - default: - /* This is not a b-tree page with records on it. Continue. */ - pCsr->iCell = pCsr->nCell; - break; - } - - if( pCsr->iCell>=pCsr->nCell ){ - bNextPage = 1; - }else{ - - iOff += 8 + nPointer + pCsr->iCell*2; - if( iOff>pCsr->nPage ){ - bNextPage = 1; - }else{ - iOff = get_uint16(&pCsr->aPage[iOff]); - } - - /* For an interior node cell, skip past the child-page number */ - iOff += nPointer; - - /* Load the "byte of payload including overflow" field */ - if( bNextPage || iOff>pCsr->nPage ){ - bNextPage = 1; - }else{ - iOff += dbdataGetVarint(&pCsr->aPage[iOff], &nPayload); - } - - /* If this is a leaf intkey cell, load the rowid */ - if( bHasRowid && !bNextPage && iOffnPage ){ - iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey); - } - - /* Figure out how much data to read from the local page */ - U = pCsr->nPage; - if( bHasRowid ){ - X = U-35; - }else{ - X = ((U-12)*64/255)-23; - } - if( nPayload<=X ){ - nLocal = nPayload; - }else{ - int M, K; - M = ((U-12)*32/255)-23; - K = M+((nPayload-M)%(U-4)); - if( K<=X ){ - nLocal = K; - }else{ - nLocal = M; - } - } - - if( bNextPage || nLocal+iOff>pCsr->nPage ){ - bNextPage = 1; - }else{ - - /* Allocate space for payload. And a bit more to catch small buffer - ** overruns caused by attempting to read a varint or similar from - ** near the end of a corrupt record. */ - pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES); - if( pCsr->pRec==0 ) return SQLITE_NOMEM; - memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES); - pCsr->nRec = nPayload; - - /* Load the nLocal bytes of payload */ - memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal); - iOff += nLocal; - - /* Load content from overflow pages */ - if( nPayload>nLocal ){ - sqlite3_int64 nRem = nPayload - nLocal; - unsigned int pgnoOvfl = get_uint32(&pCsr->aPage[iOff]); - while( nRem>0 ){ - u8 *aOvfl = 0; - int nOvfl = 0; - int nCopy; - rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl); - assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage ); - if( rc!=SQLITE_OK ) return rc; - if( aOvfl==0 ) break; - - nCopy = U-4; - if( nCopy>nRem ) nCopy = nRem; - memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy); - nRem -= nCopy; - - pgnoOvfl = get_uint32(aOvfl); - sqlite3_free(aOvfl); - } - } - - iHdr = dbdataGetVarint(pCsr->pRec, &nHdr); - pCsr->nHdr = nHdr; - pCsr->pHdrPtr = &pCsr->pRec[iHdr]; - pCsr->pPtr = &pCsr->pRec[pCsr->nHdr]; - pCsr->iField = (bHasRowid ? -1 : 0); - } - } - }else{ - pCsr->iField++; - if( pCsr->iField>0 ){ - sqlite3_int64 iType; - if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){ - bNextPage = 1; - }else{ - pCsr->pHdrPtr += dbdataGetVarint(pCsr->pHdrPtr, &iType); - pCsr->pPtr += dbdataValueBytes(iType); - } - } - } - - if( bNextPage ){ - sqlite3_free(pCsr->aPage); - sqlite3_free(pCsr->pRec); - pCsr->aPage = 0; - pCsr->pRec = 0; - if( pCsr->bOnePage ) return SQLITE_OK; - pCsr->iPgno++; - }else{ - if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){ - return SQLITE_OK; - } - - /* Advance to the next cell. The next iteration of the loop will load - ** the record and so on. */ - sqlite3_free(pCsr->pRec); - pCsr->pRec = 0; - pCsr->iCell++; - } - } - } - - assert( !"can't get here" ); - return SQLITE_OK; -} - -/* -** Return true if the cursor is at EOF. -*/ -static int dbdataEof(sqlite3_vtab_cursor *pCursor){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - return pCsr->aPage==0; -} - -/* -** Determine the size in pages of database zSchema (where zSchema is -** "main", "temp" or the name of an attached database) and set -** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise, -** an SQLite error code. -*/ -static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){ - DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab; - char *zSql = 0; - int rc, rc2; - sqlite3_stmt *pStmt = 0; - - zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema); - if( zSql==0 ) return SQLITE_NOMEM; - rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - pCsr->szDb = sqlite3_column_int(pStmt, 0); - } - rc2 = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ) rc = rc2; - return rc; -} - -/* -** xFilter method for sqlite_dbdata and sqlite_dbptr. -*/ -static int dbdataFilter( - sqlite3_vtab_cursor *pCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; - int rc = SQLITE_OK; - const char *zSchema = "main"; - - dbdataResetCursor(pCsr); - assert( pCsr->iPgno==1 ); - if( idxNum & 0x01 ){ - zSchema = (const char*)sqlite3_value_text(argv[0]); - } - if( idxNum & 0x02 ){ - pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]); - pCsr->bOnePage = 1; - }else{ - pCsr->nPage = dbdataDbsize(pCsr, zSchema); - rc = dbdataDbsize(pCsr, zSchema); - } - - if( rc==SQLITE_OK ){ - if( pTab->pStmt ){ - pCsr->pStmt = pTab->pStmt; - pTab->pStmt = 0; - }else{ - rc = sqlite3_prepare_v2(pTab->db, - "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1, - &pCsr->pStmt, 0 - ); - } - } - if( rc==SQLITE_OK ){ - rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT); - }else{ - pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); - } - if( rc==SQLITE_OK ){ - rc = dbdataNext(pCursor); - } - return rc; -} - -/* -** Return a column for the sqlite_dbdata or sqlite_dbptr table. -*/ -static int dbdataColumn( - sqlite3_vtab_cursor *pCursor, - sqlite3_context *ctx, - int i -){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; - if( pTab->bPtr ){ - switch( i ){ - case DBPTR_COLUMN_PGNO: - sqlite3_result_int64(ctx, pCsr->iPgno); - break; - case DBPTR_COLUMN_CHILD: { - int iOff = pCsr->iPgno==1 ? 100 : 0; - if( pCsr->iCell<0 ){ - iOff += 8; - }else{ - iOff += 12 + pCsr->iCell*2; - if( iOff>pCsr->nPage ) return SQLITE_OK; - iOff = get_uint16(&pCsr->aPage[iOff]); - } - if( iOff<=pCsr->nPage ){ - sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff])); - } - break; - } - } - }else{ - switch( i ){ - case DBDATA_COLUMN_PGNO: - sqlite3_result_int64(ctx, pCsr->iPgno); - break; - case DBDATA_COLUMN_CELL: - sqlite3_result_int(ctx, pCsr->iCell); - break; - case DBDATA_COLUMN_FIELD: - sqlite3_result_int(ctx, pCsr->iField); - break; - case DBDATA_COLUMN_VALUE: { - if( pCsr->iField<0 ){ - sqlite3_result_int64(ctx, pCsr->iIntkey); - }else{ - sqlite3_int64 iType; - dbdataGetVarint(pCsr->pHdrPtr, &iType); - dbdataValue( - ctx, iType, pCsr->pPtr, &pCsr->pRec[pCsr->nRec] - pCsr->pPtr - ); - } - break; - } - } - } - return SQLITE_OK; -} - -/* -** Return the rowid for an sqlite_dbdata or sqlite_dptr table. -*/ -static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - *pRowid = pCsr->iRowid; - return SQLITE_OK; -} - - -/* -** Invoke this routine to register the "sqlite_dbdata" virtual table module -*/ -static int sqlite3DbdataRegister(sqlite3 *db){ - static sqlite3_module dbdata_module = { - 0, /* iVersion */ - 0, /* xCreate */ - dbdataConnect, /* xConnect */ - dbdataBestIndex, /* xBestIndex */ - dbdataDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - dbdataOpen, /* xOpen - open a cursor */ - dbdataClose, /* xClose - close a cursor */ - dbdataFilter, /* xFilter - configure scan constraints */ - dbdataNext, /* xNext - advance a cursor */ - dbdataEof, /* xEof - check for end of scan */ - dbdataColumn, /* xColumn - read data */ - dbdataRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0 /* xShadowName */ - }; - - int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1); - } - return rc; -} - -#ifdef _WIN32 - -#endif -int sqlite3_dbdata_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - SQLITE_EXTENSION_INIT2(pApi); - return sqlite3DbdataRegister(db); -} - -/************************* End ../ext/misc/dbdata.c ********************/ -#endif - -#if defined(SQLITE_ENABLE_SESSION) -/* -** State information for a single open session -*/ -typedef struct OpenSession OpenSession; -struct OpenSession { - char *zName; /* Symbolic name for this session */ - int nFilter; /* Number of xFilter rejection GLOB patterns */ - char **azFilter; /* Array of xFilter rejection GLOB patterns */ - sqlite3_session *p; /* The open session */ -}; -#endif - -typedef struct ExpertInfo ExpertInfo; -struct ExpertInfo { - sqlite3expert *pExpert; - int bVerbose; -}; - -/* A single line in the EQP output */ -typedef struct EQPGraphRow EQPGraphRow; -struct EQPGraphRow { - int iEqpId; /* ID for this row */ - int iParentId; /* ID of the parent row */ - EQPGraphRow *pNext; /* Next row in sequence */ - char zText[1]; /* Text to display for this row */ -}; - -/* All EQP output is collected into an instance of the following */ -typedef struct EQPGraph EQPGraph; -struct EQPGraph { - EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ - EQPGraphRow *pLast; /* Last element of the pRow list */ - char zPrefix[100]; /* Graph prefix */ -}; - -/* -** State information about the database connection is contained in an -** instance of the following structure. -*/ -typedef struct ShellState ShellState; -struct ShellState { - sqlite3 *db; /* The database */ - u8 autoExplain; /* Automatically turn on .explain mode */ - u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ - u8 autoEQPtest; /* autoEQP is in test mode */ - u8 autoEQPtrace; /* autoEQP is in trace mode */ - u8 statsOn; /* True to display memory stats before each finalize */ - u8 scanstatsOn; /* True to display scan stats before each finalize */ - u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ - u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ - u8 nEqpLevel; /* Depth of the EQP output graph */ - u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ - unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ - int outCount; /* Revert to stdout when reaching zero */ - int cnt; /* Number of records displayed so far */ - int lineno; /* Line number of last line read from in */ - int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ - FILE *in; /* Read commands from this stream */ - FILE *out; /* Write results here */ - FILE *traceOut; /* Output for sqlite3_trace() */ - int nErr; /* Number of errors seen */ - int mode; /* An output mode setting */ - int modePrior; /* Saved mode */ - int cMode; /* temporary output mode for the current query */ - int normalMode; /* Output mode before ".explain on" */ - int writableSchema; /* True if PRAGMA writable_schema=ON */ - int showHeader; /* True to show column names in List or Column mode */ - int nCheck; /* Number of ".check" commands run */ - unsigned nProgress; /* Number of progress callbacks encountered */ - unsigned mxProgress; /* Maximum progress callbacks before failing */ - unsigned flgProgress; /* Flags for the progress callback */ - unsigned shellFlgs; /* Various flags */ - unsigned priorShFlgs; /* Saved copy of flags */ - sqlite3_int64 szMax; /* --maxsize argument to .open */ - char *zDestTable; /* Name of destination table when MODE_Insert */ - char *zTempFile; /* Temporary file that might need deleting */ - char zTestcase[30]; /* Name of current test case */ - char colSeparator[20]; /* Column separator character for several modes */ - char rowSeparator[20]; /* Row separator character for MODE_Ascii */ - char colSepPrior[20]; /* Saved column separator */ - char rowSepPrior[20]; /* Saved row separator */ - int *colWidth; /* Requested width of each column in columnar modes */ - int *actualWidth; /* Actual width of each column */ - int nWidth; /* Number of slots in colWidth[] and actualWidth[] */ - char nullValue[20]; /* The text to print when a NULL comes back from - ** the database */ - char outfile[FILENAME_MAX]; /* Filename for *out */ - const char *zDbFilename; /* name of the database file */ - char *zFreeOnClose; /* Filename to free when closing */ - const char *zVfs; /* Name of VFS to use */ - sqlite3_stmt *pStmt; /* Current statement if any. */ - FILE *pLog; /* Write log output here */ - int *aiIndent; /* Array of indents used in MODE_Explain */ - int nIndent; /* Size of array aiIndent[] */ - int iIndent; /* Index of current op in aiIndent[] */ - EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ -#if defined(SQLITE_ENABLE_SESSION) - int nSession; /* Number of active sessions */ - OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ -#endif - ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ -}; - - -/* Allowed values for ShellState.autoEQP -*/ -#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ -#define AUTOEQP_on 1 /* Automatic EQP is on */ -#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ -#define AUTOEQP_full 3 /* Show full EXPLAIN */ - -/* Allowed values for ShellState.openMode -*/ -#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ -#define SHELL_OPEN_NORMAL 1 /* Normal database file */ -#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ -#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ -#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ -#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ -#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ - -/* Allowed values for ShellState.eTraceType -*/ -#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ -#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ -#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ - -/* Bits in the ShellState.flgProgress variable */ -#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ -#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres - ** callback limit is reached, and for each - ** top-level SQL statement */ -#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ - -/* -** These are the allowed shellFlgs values -*/ -#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ -#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ -#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ -#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ -#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ -#define SHFLG_CountChanges 0x00000020 /* .changes setting */ -#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ -#define SHFLG_HeaderSet 0x00000080 /* .header has been used */ - -/* -** Macros for testing and setting shellFlgs -*/ -#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) -#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) -#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) - -/* -** These are the allowed modes. -*/ -#define MODE_Line 0 /* One column per line. Blank line between records */ -#define MODE_Column 1 /* One record per line in neat columns */ -#define MODE_List 2 /* One record per line with a separator */ -#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ -#define MODE_Html 4 /* Generate an XHTML table */ -#define MODE_Insert 5 /* Generate SQL "insert" statements */ -#define MODE_Quote 6 /* Quote values as for SQL */ -#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ -#define MODE_Csv 8 /* Quote strings, numbers are plain */ -#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ -#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ -#define MODE_Pretty 11 /* Pretty-print schemas */ -#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ -#define MODE_Json 13 /* Output JSON */ -#define MODE_Markdown 14 /* Markdown formatting */ -#define MODE_Table 15 /* MySQL-style table formatting */ -#define MODE_Box 16 /* Unicode box-drawing characters */ - -static const char *modeDescr[] = { - "line", - "column", - "list", - "semi", - "html", - "insert", - "quote", - "tcl", - "csv", - "explain", - "ascii", - "prettyprint", - "eqp", - "json", - "markdown", - "table", - "box" -}; - -/* -** These are the column/row/line separators used by the various -** import/export modes. -*/ -#define SEP_Column "|" -#define SEP_Row "\n" -#define SEP_Tab "\t" -#define SEP_Space " " -#define SEP_Comma "," -#define SEP_CrLf "\r\n" -#define SEP_Unit "\x1F" -#define SEP_Record "\x1E" - -/* -** A callback for the sqlite3_log() interface. -*/ -static void shellLog(void *pArg, int iErrCode, const char *zMsg){ - ShellState *p = (ShellState*)pArg; - if( p->pLog==0 ) return; - utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); - fflush(p->pLog); -} - -/* -** SQL function: shell_putsnl(X) -** -** Write the text X to the screen (or whatever output is being directed) -** adding a newline at the end, and then return X. -*/ -static void shellPutsFunc( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - ShellState *p = (ShellState*)sqlite3_user_data(pCtx); - (void)nVal; - utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); - sqlite3_result_value(pCtx, apVal[0]); -} - -/* -** SQL function: edit(VALUE) -** edit(VALUE,EDITOR) -** -** These steps: -** -** (1) Write VALUE into a temporary file. -** (2) Run program EDITOR on that temporary file. -** (3) Read the temporary file back and return its content as the result. -** (4) Delete the temporary file -** -** If the EDITOR argument is omitted, use the value in the VISUAL -** environment variable. If still there is no EDITOR, through an error. -** -** Also throw an error if the EDITOR program returns a non-zero exit code. -*/ -#ifndef SQLITE_NOHAVE_SYSTEM -static void editFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zEditor; - char *zTempFile = 0; - sqlite3 *db; - char *zCmd = 0; - int bBin; - int rc; - int hasCRNL = 0; - FILE *f = 0; - sqlite3_int64 sz; - sqlite3_int64 x; - unsigned char *p = 0; - - if( argc==2 ){ - zEditor = (const char*)sqlite3_value_text(argv[1]); - }else{ - zEditor = getenv("VISUAL"); - } - if( zEditor==0 ){ - sqlite3_result_error(context, "no editor for edit()", -1); - return; - } - if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ - sqlite3_result_error(context, "NULL input to edit()", -1); - return; - } - db = sqlite3_context_db_handle(context); - zTempFile = 0; - sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); - if( zTempFile==0 ){ - sqlite3_uint64 r = 0; - sqlite3_randomness(sizeof(r), &r); - zTempFile = sqlite3_mprintf("temp%llx", r); - if( zTempFile==0 ){ - sqlite3_result_error_nomem(context); - return; - } - } - bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; - /* When writing the file to be edited, do \n to \r\n conversions on systems - ** that want \r\n line endings */ - f = fopen(zTempFile, bBin ? "wb" : "w"); - if( f==0 ){ - sqlite3_result_error(context, "edit() cannot open temp file", -1); - goto edit_func_end; - } - sz = sqlite3_value_bytes(argv[0]); - if( bBin ){ - x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); - }else{ - const char *z = (const char*)sqlite3_value_text(argv[0]); - /* Remember whether or not the value originally contained \r\n */ - if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; - x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); - } - fclose(f); - f = 0; - if( x!=sz ){ - sqlite3_result_error(context, "edit() could not write the whole file", -1); - goto edit_func_end; - } - zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); - if( zCmd==0 ){ - sqlite3_result_error_nomem(context); - goto edit_func_end; - } - rc = system(zCmd); - sqlite3_free(zCmd); - if( rc ){ - sqlite3_result_error(context, "EDITOR returned non-zero", -1); - goto edit_func_end; - } - f = fopen(zTempFile, "rb"); - if( f==0 ){ - sqlite3_result_error(context, - "edit() cannot reopen temp file after edit", -1); - goto edit_func_end; - } - fseek(f, 0, SEEK_END); - sz = ftell(f); - rewind(f); - p = sqlite3_malloc64( sz+1 ); - if( p==0 ){ - sqlite3_result_error_nomem(context); - goto edit_func_end; - } - x = fread(p, 1, (size_t)sz, f); - fclose(f); - f = 0; - if( x!=sz ){ - sqlite3_result_error(context, "could not read back the whole file", -1); - goto edit_func_end; - } - if( bBin ){ - sqlite3_result_blob64(context, p, sz, sqlite3_free); - }else{ - sqlite3_int64 i, j; - if( hasCRNL ){ - /* If the original contains \r\n then do no conversions back to \n */ - j = sz; - }else{ - /* If the file did not originally contain \r\n then convert any new - ** \r\n back into \n */ - for(i=j=0; imodePrior = p->mode; - p->priorShFlgs = p->shellFlgs; - memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); - memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); -} -static void outputModePop(ShellState *p){ - p->mode = p->modePrior; - p->shellFlgs = p->priorShFlgs; - memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); - memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); -} - -/* -** Output the given string as a hex-encoded blob (eg. X'1234' ) -*/ -static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ - int i; - char *zBlob = (char *)pBlob; - raw_printf(out,"X'"); - for(i=0; i0 ){ - utf8_printf(out,"%.*s",i,z); - } - if( z[i]=='<' ){ - raw_printf(out,"<"); - }else if( z[i]=='&' ){ - raw_printf(out,"&"); - }else if( z[i]=='>' ){ - raw_printf(out,">"); - }else if( z[i]=='\"' ){ - raw_printf(out,"""); - }else if( z[i]=='\'' ){ - raw_printf(out,"'"); - }else{ - break; - } - z += i + 1; - } -} - -/* -** If a field contains any character identified by a 1 in the following -** array, then the string must be quoted for CSV. -*/ -static const char needCsvQuote[] = { - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -}; - -/* -** Output a single term of CSV. Actually, p->colSeparator is used for -** the separator, which may or may not be a comma. p->nullValue is -** the null value. Strings are quoted if necessary. The separator -** is only issued if bSep is true. -*/ -static void output_csv(ShellState *p, const char *z, int bSep){ - FILE *out = p->out; - if( z==0 ){ - utf8_printf(out,"%s",p->nullValue); - }else{ - int i; - int nSep = strlen30(p->colSeparator); - for(i=0; z[i]; i++){ - if( needCsvQuote[((unsigned char*)z)[i]] - || (z[i]==p->colSeparator[0] && - (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ - i = 0; - break; - } - } - if( i==0 ){ - char *zQuoted = sqlite3_mprintf("\"%w\"", z); - utf8_printf(out, "%s", zQuoted); - sqlite3_free(zQuoted); - }else{ - utf8_printf(out, "%s", z); - } - } - if( bSep ){ - utf8_printf(p->out, "%s", p->colSeparator); - } -} - -/* -** This routine runs when the user presses Ctrl-C -*/ -static void interrupt_handler(int NotUsed){ - UNUSED_PARAMETER(NotUsed); - seenInterrupt++; - if( seenInterrupt>2 ) exit(1); - if( globalDb ) sqlite3_interrupt(globalDb); -} - -#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) -/* -** This routine runs for console events (e.g. Ctrl-C) on Win32 -*/ -static BOOL WINAPI ConsoleCtrlHandler( - DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ -){ - if( dwCtrlType==CTRL_C_EVENT ){ - interrupt_handler(0); - return TRUE; - } - return FALSE; -} -#endif - -#ifndef SQLITE_OMIT_AUTHORIZATION -/* -** When the ".auth ON" is set, the following authorizer callback is -** invoked. It always returns SQLITE_OK. -*/ -static int shellAuth( - void *pClientData, - int op, - const char *zA1, - const char *zA2, - const char *zA3, - const char *zA4 -){ - ShellState *p = (ShellState*)pClientData; - static const char *azAction[] = { 0, - "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", - "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", - "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", - "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", - "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", - "DROP_TRIGGER", "DROP_VIEW", "INSERT", - "PRAGMA", "READ", "SELECT", - "TRANSACTION", "UPDATE", "ATTACH", - "DETACH", "ALTER_TABLE", "REINDEX", - "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", - "FUNCTION", "SAVEPOINT", "RECURSIVE" - }; - int i; - const char *az[4]; - az[0] = zA1; - az[1] = zA2; - az[2] = zA3; - az[3] = zA4; - utf8_printf(p->out, "authorizer: %s", azAction[op]); - for(i=0; i<4; i++){ - raw_printf(p->out, " "); - if( az[i] ){ - output_c_string(p->out, az[i]); - }else{ - raw_printf(p->out, "NULL"); - } - } - raw_printf(p->out, "\n"); - return SQLITE_OK; -} -#endif - -/* -** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. -** -** This routine converts some CREATE TABLE statements for shadow tables -** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. -*/ -static void printSchemaLine(FILE *out, const char *z, const char *zTail){ - if( z==0 ) return; - if( zTail==0 ) return; - if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ - utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); - }else{ - utf8_printf(out, "%s%s", z, zTail); - } -} -static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ - char c = z[n]; - z[n] = 0; - printSchemaLine(out, z, zTail); - z[n] = c; -} - -/* -** Return true if string z[] has nothing but whitespace and comments to the -** end of the first line. -*/ -static int wsToEol(const char *z){ - int i; - for(i=0; z[i]; i++){ - if( z[i]=='\n' ) return 1; - if( IsSpace(z[i]) ) continue; - if( z[i]=='-' && z[i+1]=='-' ) return 1; - return 0; - } - return 1; -} - -/* -** Add a new entry to the EXPLAIN QUERY PLAN data -*/ -static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ - EQPGraphRow *pNew; - int nText = strlen30(zText); - if( p->autoEQPtest ){ - utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); - } - pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); - if( pNew==0 ) shell_out_of_memory(); - pNew->iEqpId = iEqpId; - pNew->iParentId = p2; - memcpy(pNew->zText, zText, nText+1); - pNew->pNext = 0; - if( p->sGraph.pLast ){ - p->sGraph.pLast->pNext = pNew; - }else{ - p->sGraph.pRow = pNew; - } - p->sGraph.pLast = pNew; -} - -/* -** Free and reset the EXPLAIN QUERY PLAN data that has been collected -** in p->sGraph. -*/ -static void eqp_reset(ShellState *p){ - EQPGraphRow *pRow, *pNext; - for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ - pNext = pRow->pNext; - sqlite3_free(pRow); - } - memset(&p->sGraph, 0, sizeof(p->sGraph)); -} - -/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after -** pOld, or return the first such line if pOld is NULL -*/ -static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ - EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; - while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; - return pRow; -} - -/* Render a single level of the graph that has iEqpId as its parent. Called -** recursively to render sublevels. -*/ -static void eqp_render_level(ShellState *p, int iEqpId){ - EQPGraphRow *pRow, *pNext; - int n = strlen30(p->sGraph.zPrefix); - char *z; - for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ - pNext = eqp_next_row(p, iEqpId, pRow); - z = pRow->zText; - utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, - pNext ? "|--" : "`--", z); - if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ - memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); - eqp_render_level(p, pRow->iEqpId); - p->sGraph.zPrefix[n] = 0; - } - } -} - -/* -** Display and reset the EXPLAIN QUERY PLAN data -*/ -static void eqp_render(ShellState *p){ - EQPGraphRow *pRow = p->sGraph.pRow; - if( pRow ){ - if( pRow->zText[0]=='-' ){ - if( pRow->pNext==0 ){ - eqp_reset(p); - return; - } - utf8_printf(p->out, "%s\n", pRow->zText+3); - p->sGraph.pRow = pRow->pNext; - sqlite3_free(pRow); - }else{ - utf8_printf(p->out, "QUERY PLAN\n"); - } - p->sGraph.zPrefix[0] = 0; - eqp_render_level(p, 0); - eqp_reset(p); - } -} - -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK -/* -** Progress handler callback. -*/ -static int progress_handler(void *pClientData) { - ShellState *p = (ShellState*)pClientData; - p->nProgress++; - if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ - raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); - if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; - if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; - return 1; - } - if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ - raw_printf(p->out, "Progress %u\n", p->nProgress); - } - return 0; -} -#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ - -/* -** Print N dashes -*/ -static void print_dashes(FILE *out, int N){ - const char zDash[] = "--------------------------------------------------"; - const int nDash = sizeof(zDash) - 1; - while( N>nDash ){ - fputs(zDash, out); - N -= nDash; - } - raw_printf(out, "%.*s", N, zDash); -} - -/* -** Print a markdown or table-style row separator using ascii-art -*/ -static void print_row_separator( - ShellState *p, - int nArg, - const char *zSep -){ - int i; - if( nArg>0 ){ - fputs(zSep, p->out); - print_dashes(p->out, p->actualWidth[0]+2); - for(i=1; iout); - print_dashes(p->out, p->actualWidth[i]+2); - } - fputs(zSep, p->out); - } - fputs("\n", p->out); -} - -/* -** This is the callback routine that the shell -** invokes for each row of a query result. -*/ -static int shell_callback( - void *pArg, - int nArg, /* Number of result columns */ - char **azArg, /* Text of each result column */ - char **azCol, /* Column names */ - int *aiType /* Column types. Might be NULL */ -){ - int i; - ShellState *p = (ShellState*)pArg; - - if( azArg==0 ) return 0; - switch( p->cMode ){ - case MODE_Line: { - int w = 5; - if( azArg==0 ) break; - for(i=0; iw ) w = len; - } - if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); - for(i=0; iout,"%*s = %s%s", w, azCol[i], - azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); - } - break; - } - case MODE_Explain: { - static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13}; - if( nArg>ArraySize(aExplainWidth) ){ - nArg = ArraySize(aExplainWidth); - } - if( p->cnt++==0 ){ - for(i=0; iout, w, azCol[i]); - fputs(i==nArg-1 ? "\n" : " ", p->out); - } - for(i=0; iout, w); - fputs(i==nArg-1 ? "\n" : " ", p->out); - } - } - if( azArg==0 ) break; - for(i=0; iw ){ - w = strlenChar(azArg[i]); - } - if( i==1 && p->aiIndent && p->pStmt ){ - if( p->iIndentnIndent ){ - utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); - } - p->iIndent++; - } - utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); - fputs(i==nArg-1 ? "\n" : " ", p->out); - } - break; - } - case MODE_Semi: { /* .schema and .fullschema output */ - printSchemaLine(p->out, azArg[0], ";\n"); - break; - } - case MODE_Pretty: { /* .schema and .fullschema with --indent */ - char *z; - int j; - int nParen = 0; - char cEnd = 0; - char c; - int nLine = 0; - assert( nArg==1 ); - if( azArg[0]==0 ) break; - if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 - || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 - ){ - utf8_printf(p->out, "%s;\n", azArg[0]); - break; - } - z = sqlite3_mprintf("%s", azArg[0]); - j = 0; - for(i=0; IsSpace(z[i]); i++){} - for(; (c = z[i])!=0; i++){ - if( IsSpace(c) ){ - if( z[j-1]=='\r' ) z[j-1] = '\n'; - if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; - }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ - j--; - } - z[j++] = c; - } - while( j>0 && IsSpace(z[j-1]) ){ j--; } - z[j] = 0; - if( strlen30(z)>=79 ){ - for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ - if( c==cEnd ){ - cEnd = 0; - }else if( c=='"' || c=='\'' || c=='`' ){ - cEnd = c; - }else if( c=='[' ){ - cEnd = ']'; - }else if( c=='-' && z[i+1]=='-' ){ - cEnd = '\n'; - }else if( c=='(' ){ - nParen++; - }else if( c==')' ){ - nParen--; - if( nLine>0 && nParen==0 && j>0 ){ - printSchemaLineN(p->out, z, j, "\n"); - j = 0; - } - } - z[j++] = c; - if( nParen==1 && cEnd==0 - && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) - ){ - if( c=='\n' ) j--; - printSchemaLineN(p->out, z, j, "\n "); - j = 0; - nLine++; - while( IsSpace(z[i+1]) ){ i++; } - } - } - z[j] = 0; - } - printSchemaLine(p->out, z, ";\n"); - sqlite3_free(z); - break; - } - case MODE_List: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; iout,"%s%s",azCol[i], - i==nArg-1 ? p->rowSeparator : p->colSeparator); - } - } - if( azArg==0 ) break; - for(i=0; inullValue; - utf8_printf(p->out, "%s", z); - if( iout, "%s", p->colSeparator); - }else{ - utf8_printf(p->out, "%s", p->rowSeparator); - } - } - break; - } - case MODE_Html: { - if( p->cnt++==0 && p->showHeader ){ - raw_printf(p->out,""); - for(i=0; iout,"\n"); - } - raw_printf(p->out,"\n"); - } - if( azArg==0 ) break; - raw_printf(p->out,""); - for(i=0; iout,"\n"); - } - raw_printf(p->out,"\n"); - break; - } - case MODE_Tcl: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; iout,azCol[i] ? azCol[i] : ""); - if(iout, "%s", p->colSeparator); - } - utf8_printf(p->out, "%s", p->rowSeparator); - } - if( azArg==0 ) break; - for(i=0; iout, azArg[i] ? azArg[i] : p->nullValue); - if(iout, "%s", p->colSeparator); - } - utf8_printf(p->out, "%s", p->rowSeparator); - break; - } - case MODE_Csv: { - setBinaryMode(p->out, 1); - if( p->cnt++==0 && p->showHeader ){ - for(i=0; iout, "%s", p->rowSeparator); - } - if( nArg>0 ){ - for(i=0; iout, "%s", p->rowSeparator); - } - setTextMode(p->out, 1); - break; - } - case MODE_Insert: { - if( azArg==0 ) break; - utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); - if( p->showHeader ){ - raw_printf(p->out,"("); - for(i=0; i0 ) raw_printf(p->out, ","); - if( quoteChar(azCol[i]) ){ - char *z = sqlite3_mprintf("\"%w\"", azCol[i]); - utf8_printf(p->out, "%s", z); - sqlite3_free(z); - }else{ - raw_printf(p->out, "%s", azCol[i]); - } - } - raw_printf(p->out,")"); - } - p->cnt++; - for(i=0; iout, i>0 ? "," : " VALUES("); - if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ - utf8_printf(p->out,"NULL"); - }else if( aiType && aiType[i]==SQLITE_TEXT ){ - if( ShellHasFlag(p, SHFLG_Newlines) ){ - output_quoted_string(p->out, azArg[i]); - }else{ - output_quoted_escaped_string(p->out, azArg[i]); - } - }else if( aiType && aiType[i]==SQLITE_INTEGER ){ - utf8_printf(p->out,"%s", azArg[i]); - }else if( aiType && aiType[i]==SQLITE_FLOAT ){ - char z[50]; - double r = sqlite3_column_double(p->pStmt, i); - sqlite3_uint64 ur; - memcpy(&ur,&r,sizeof(r)); - if( ur==0x7ff0000000000000LL ){ - raw_printf(p->out, "1e999"); - }else if( ur==0xfff0000000000000LL ){ - raw_printf(p->out, "-1e999"); - }else{ - sqlite3_snprintf(50,z,"%!.20g", r); - raw_printf(p->out, "%s", z); - } - }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ - const void *pBlob = sqlite3_column_blob(p->pStmt, i); - int nBlob = sqlite3_column_bytes(p->pStmt, i); - output_hex_blob(p->out, pBlob, nBlob); - }else if( isNumber(azArg[i], 0) ){ - utf8_printf(p->out,"%s", azArg[i]); - }else if( ShellHasFlag(p, SHFLG_Newlines) ){ - output_quoted_string(p->out, azArg[i]); - }else{ - output_quoted_escaped_string(p->out, azArg[i]); - } - } - raw_printf(p->out,");\n"); - break; - } - case MODE_Json: { - if( azArg==0 ) break; - if( p->cnt==0 ){ - fputs("[{", p->out); - }else{ - fputs(",\n{", p->out); - } - p->cnt++; - for(i=0; iout, azCol[i], -1); - putc(':', p->out); - if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ - fputs("null",p->out); - }else if( aiType && aiType[i]==SQLITE_FLOAT ){ - char z[50]; - double r = sqlite3_column_double(p->pStmt, i); - sqlite3_uint64 ur; - memcpy(&ur,&r,sizeof(r)); - if( ur==0x7ff0000000000000LL ){ - raw_printf(p->out, "1e999"); - }else if( ur==0xfff0000000000000LL ){ - raw_printf(p->out, "-1e999"); - }else{ - sqlite3_snprintf(50,z,"%!.20g", r); - raw_printf(p->out, "%s", z); - } - }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ - const void *pBlob = sqlite3_column_blob(p->pStmt, i); - int nBlob = sqlite3_column_bytes(p->pStmt, i); - output_json_string(p->out, pBlob, nBlob); - }else if( aiType && aiType[i]==SQLITE_TEXT ){ - output_json_string(p->out, azArg[i], -1); - }else{ - utf8_printf(p->out,"%s", azArg[i]); - } - if( iout); - } - } - putc('}', p->out); - break; - } - case MODE_Quote: { - if( azArg==0 ) break; - if( p->cnt==0 && p->showHeader ){ - for(i=0; i0 ) fputs(p->colSeparator, p->out); - output_quoted_string(p->out, azCol[i]); - } - fputs(p->rowSeparator, p->out); - } - p->cnt++; - for(i=0; i0 ) fputs(p->colSeparator, p->out); - if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ - utf8_printf(p->out,"NULL"); - }else if( aiType && aiType[i]==SQLITE_TEXT ){ - output_quoted_string(p->out, azArg[i]); - }else if( aiType && aiType[i]==SQLITE_INTEGER ){ - utf8_printf(p->out,"%s", azArg[i]); - }else if( aiType && aiType[i]==SQLITE_FLOAT ){ - char z[50]; - double r = sqlite3_column_double(p->pStmt, i); - sqlite3_snprintf(50,z,"%!.20g", r); - raw_printf(p->out, "%s", z); - }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ - const void *pBlob = sqlite3_column_blob(p->pStmt, i); - int nBlob = sqlite3_column_bytes(p->pStmt, i); - output_hex_blob(p->out, pBlob, nBlob); - }else if( isNumber(azArg[i], 0) ){ - utf8_printf(p->out,"%s", azArg[i]); - }else{ - output_quoted_string(p->out, azArg[i]); - } - } - fputs(p->rowSeparator, p->out); - break; - } - case MODE_Ascii: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; i0 ) utf8_printf(p->out, "%s", p->colSeparator); - utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); - } - utf8_printf(p->out, "%s", p->rowSeparator); - } - if( azArg==0 ) break; - for(i=0; i0 ) utf8_printf(p->out, "%s", p->colSeparator); - utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); - } - utf8_printf(p->out, "%s", p->rowSeparator); - break; - } - case MODE_EQP: { - eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); - break; - } - } - return 0; -} - -/* -** This is the callback routine that the SQLite library -** invokes for each row of a query result. -*/ -static int callback(void *pArg, int nArg, char **azArg, char **azCol){ - /* since we don't have type info, call the shell_callback with a NULL value */ - return shell_callback(pArg, nArg, azArg, azCol, NULL); -} - -/* -** This is the callback routine from sqlite3_exec() that appends all -** output onto the end of a ShellText object. -*/ -static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ - ShellText *p = (ShellText*)pArg; - int i; - UNUSED_PARAMETER(az); - if( azArg==0 ) return 0; - if( p->n ) appendText(p, "|", 0); - for(i=0; idb, - "SAVEPOINT selftest_init;\n" - "CREATE TABLE IF NOT EXISTS selftest(\n" - " tno INTEGER PRIMARY KEY,\n" /* Test number */ - " op TEXT,\n" /* Operator: memo run */ - " cmd TEXT,\n" /* Command text */ - " ans TEXT\n" /* Desired answer */ - ");" - "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" - "INSERT INTO [_shell$self](rowid,op,cmd)\n" - " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" - " 'memo','Tests generated by --init');\n" - "INSERT INTO [_shell$self]\n" - " SELECT 'run',\n" - " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " - "FROM sqlite_schema ORDER BY 2'',224))',\n" - " hex(sha3_query('SELECT type,name,tbl_name,sql " - "FROM sqlite_schema ORDER BY 2',224));\n" - "INSERT INTO [_shell$self]\n" - " SELECT 'run'," - " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" - " printf('%w',name) || '\" NOT INDEXED'',224))',\n" - " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" - " FROM (\n" - " SELECT name FROM sqlite_schema\n" - " WHERE type='table'\n" - " AND name<>'selftest'\n" - " AND coalesce(rootpage,0)>0\n" - " )\n" - " ORDER BY name;\n" - "INSERT INTO [_shell$self]\n" - " VALUES('run','PRAGMA integrity_check','ok');\n" - "INSERT INTO selftest(tno,op,cmd,ans)" - " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" - "DROP TABLE [_shell$self];" - ,0,0,&zErrMsg); - if( zErrMsg ){ - utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - } - sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); -} - - -/* -** Set the destination table field of the ShellState structure to -** the name of the table given. Escape any quote characters in the -** table name. -*/ -static void set_table_name(ShellState *p, const char *zName){ - int i, n; - char cQuote; - char *z; - - if( p->zDestTable ){ - free(p->zDestTable); - p->zDestTable = 0; - } - if( zName==0 ) return; - cQuote = quoteChar(zName); - n = strlen30(zName); - if( cQuote ) n += n+2; - z = p->zDestTable = malloc( n+1 ); - if( z==0 ) shell_out_of_memory(); - n = 0; - if( cQuote ) z[n++] = cQuote; - for(i=0; zName[i]; i++){ - z[n++] = zName[i]; - if( zName[i]==cQuote ) z[n++] = cQuote; - } - if( cQuote ) z[n++] = cQuote; - z[n] = 0; -} - - -/* -** Execute a query statement that will generate SQL output. Print -** the result columns, comma-separated, on a line and then add a -** semicolon terminator to the end of that line. -** -** If the number of columns is 1 and that column contains text "--" -** then write the semicolon on a separate line. That way, if a -** "--" comment occurs at the end of the statement, the comment -** won't consume the semicolon terminator. -*/ -static int run_table_dump_query( - ShellState *p, /* Query context */ - const char *zSelect /* SELECT statement to extract content */ -){ - sqlite3_stmt *pSelect; - int rc; - int nResult; - int i; - const char *z; - rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); - if( rc!=SQLITE_OK || !pSelect ){ - utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, - sqlite3_errmsg(p->db)); - if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; - return rc; - } - rc = sqlite3_step(pSelect); - nResult = sqlite3_column_count(pSelect); - while( rc==SQLITE_ROW ){ - z = (const char*)sqlite3_column_text(pSelect, 0); - utf8_printf(p->out, "%s", z); - for(i=1; iout, ",%s", sqlite3_column_text(pSelect, i)); - } - if( z==0 ) z = ""; - while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; - if( z[0] ){ - raw_printf(p->out, "\n;\n"); - }else{ - raw_printf(p->out, ";\n"); - } - rc = sqlite3_step(pSelect); - } - rc = sqlite3_finalize(pSelect); - if( rc!=SQLITE_OK ){ - utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, - sqlite3_errmsg(p->db)); - if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; - } - return rc; -} - -/* -** Allocate space and save off current error string. -*/ -static char *save_err_msg( - sqlite3 *db /* Database to query */ -){ - int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); - char *zErrMsg = sqlite3_malloc64(nErrMsg); - if( zErrMsg ){ - memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); - } - return zErrMsg; -} - -#ifdef __linux__ -/* -** Attempt to display I/O stats on Linux using /proc/PID/io -*/ -static void displayLinuxIoStats(FILE *out){ - FILE *in; - char z[200]; - sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); - in = fopen(z, "rb"); - if( in==0 ) return; - while( fgets(z, sizeof(z), in)!=0 ){ - static const struct { - const char *zPattern; - const char *zDesc; - } aTrans[] = { - { "rchar: ", "Bytes received by read():" }, - { "wchar: ", "Bytes sent to write():" }, - { "syscr: ", "Read() system calls:" }, - { "syscw: ", "Write() system calls:" }, - { "read_bytes: ", "Bytes read from storage:" }, - { "write_bytes: ", "Bytes written to storage:" }, - { "cancelled_write_bytes: ", "Cancelled write bytes:" }, - }; - int i; - for(i=0; i1 ){ - sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); - }else{ - sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); - } - raw_printf(p->out, "%-36s %s\n", zLabel, zLine); -} - -/* -** Display memory stats. -*/ -static int display_stats( - sqlite3 *db, /* Database to query */ - ShellState *pArg, /* Pointer to ShellState */ - int bReset /* True to reset the stats */ -){ - int iCur; - int iHiwtr; - FILE *out; - if( pArg==0 || pArg->out==0 ) return 0; - out = pArg->out; - - if( pArg->pStmt && (pArg->statsOn & 2) ){ - int nCol, i, x; - sqlite3_stmt *pStmt = pArg->pStmt; - char z[100]; - nCol = sqlite3_column_count(pStmt); - raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); - for(i=0; ishellFlgs & SHFLG_Pagecache ){ - displayStatLine(pArg, "Number of Pcache Pages Used:", - "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); - } - displayStatLine(pArg, "Number of Pcache Overflow Bytes:", - "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); - displayStatLine(pArg, "Largest Allocation:", - "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); - displayStatLine(pArg, "Largest Pcache Allocation:", - "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); -#ifdef YYTRACKMAXSTACKDEPTH - displayStatLine(pArg, "Deepest Parser Stack:", - "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); -#endif - - if( db ){ - if( pArg->shellFlgs & SHFLG_Lookaside ){ - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, - &iCur, &iHiwtr, bReset); - raw_printf(pArg->out, - "Lookaside Slots Used: %d (max %d)\n", - iCur, iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, - &iCur, &iHiwtr, bReset); - raw_printf(pArg->out, "Successful lookaside attempts: %d\n", - iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, - &iCur, &iHiwtr, bReset); - raw_printf(pArg->out, "Lookaside failures due to size: %d\n", - iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, - &iCur, &iHiwtr, bReset); - raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", - iHiwtr); - } - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); - raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", - iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); - raw_printf(pArg->out, "Page cache hits: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); - raw_printf(pArg->out, "Page cache misses: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); - raw_printf(pArg->out, "Page cache writes: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); - raw_printf(pArg->out, "Page cache spills: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); - raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", - iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); - raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", - iCur); - } - - if( pArg->pStmt ){ - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, - bReset); - raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); - raw_printf(pArg->out, "Sort Operations: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); - raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); - raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); - raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); - raw_printf(pArg->out, "Number of times run: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); - raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); - } - -#ifdef __linux__ - displayLinuxIoStats(pArg->out); -#endif - - /* Do not remove this machine readable comment: extra-stats-output-here */ - - return 0; -} - -/* -** Display scan stats. -*/ -static void display_scanstats( - sqlite3 *db, /* Database to query */ - ShellState *pArg /* Pointer to ShellState */ -){ -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS - UNUSED_PARAMETER(db); - UNUSED_PARAMETER(pArg); -#else - int i, k, n, mx; - raw_printf(pArg->out, "-------- scanstats --------\n"); - mx = 0; - for(k=0; k<=mx; k++){ - double rEstLoop = 1.0; - for(i=n=0; 1; i++){ - sqlite3_stmt *p = pArg->pStmt; - sqlite3_int64 nLoop, nVisit; - double rEst; - int iSid; - const char *zExplain; - if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ - break; - } - sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); - if( iSid>mx ) mx = iSid; - if( iSid!=k ) continue; - if( n==0 ){ - rEstLoop = (double)nLoop; - if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); - } - n++; - sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); - sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); - sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); - utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); - rEstLoop *= rEst; - raw_printf(pArg->out, - " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", - nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst - ); - } - } - raw_printf(pArg->out, "---------------------------\n"); -#endif -} - -/* -** Parameter azArray points to a zero-terminated array of strings. zStr -** points to a single nul-terminated string. Return non-zero if zStr -** is equal, according to strcmp(), to any of the strings in the array. -** Otherwise, return zero. -*/ -static int str_in_array(const char *zStr, const char **azArray){ - int i; - for(i=0; azArray[i]; i++){ - if( 0==strcmp(zStr, azArray[i]) ) return 1; - } - return 0; -} - -/* -** If compiled statement pSql appears to be an EXPLAIN statement, allocate -** and populate the ShellState.aiIndent[] array with the number of -** spaces each opcode should be indented before it is output. -** -** The indenting rules are: -** -** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent -** all opcodes that occur between the p2 jump destination and the opcode -** itself by 2 spaces. -** -** * For each "Goto", if the jump destination is earlier in the program -** and ends on one of: -** Yield SeekGt SeekLt RowSetRead Rewind -** or if the P1 parameter is one instead of zero, -** then indent all opcodes between the earlier instruction -** and "Goto" by 2 spaces. -*/ -static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ - const char *zSql; /* The text of the SQL statement */ - const char *z; /* Used to check if this is an EXPLAIN */ - int *abYield = 0; /* True if op is an OP_Yield */ - int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ - int iOp; /* Index of operation in p->aiIndent[] */ - - const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; - const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", - "Rewind", 0 }; - const char *azGoto[] = { "Goto", 0 }; - - /* Try to figure out if this is really an EXPLAIN statement. If this - ** cannot be verified, return early. */ - if( sqlite3_column_count(pSql)!=8 ){ - p->cMode = p->mode; - return; - } - zSql = sqlite3_sql(pSql); - if( zSql==0 ) return; - for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); - if( sqlite3_strnicmp(z, "explain", 7) ){ - p->cMode = p->mode; - return; - } - - for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ - int i; - int iAddr = sqlite3_column_int(pSql, 0); - const char *zOp = (const char*)sqlite3_column_text(pSql, 1); - - /* Set p2 to the P2 field of the current opcode. Then, assuming that - ** p2 is an instruction address, set variable p2op to the index of that - ** instruction in the aiIndent[] array. p2 and p2op may be different if - ** the current instruction is part of a sub-program generated by an - ** SQL trigger or foreign key. */ - int p2 = sqlite3_column_int(pSql, 3); - int p2op = (p2 + (iOp-iAddr)); - - /* Grow the p->aiIndent array as required */ - if( iOp>=nAlloc ){ - if( iOp==0 ){ - /* Do further verfication that this is explain output. Abort if - ** it is not */ - static const char *explainCols[] = { - "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; - int jj; - for(jj=0; jjcMode = p->mode; - sqlite3_reset(pSql); - return; - } - } - } - nAlloc += 100; - p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); - if( p->aiIndent==0 ) shell_out_of_memory(); - abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); - if( abYield==0 ) shell_out_of_memory(); - } - abYield[iOp] = str_in_array(zOp, azYield); - p->aiIndent[iOp] = 0; - p->nIndent = iOp+1; - - if( str_in_array(zOp, azNext) ){ - for(i=p2op; iaiIndent[i] += 2; - } - if( str_in_array(zOp, azGoto) && p2opnIndent - && (abYield[p2op] || sqlite3_column_int(pSql, 2)) - ){ - for(i=p2op; iaiIndent[i] += 2; - } - } - - p->iIndent = 0; - sqlite3_free(abYield); - sqlite3_reset(pSql); -} - -/* -** Free the array allocated by explain_data_prepare(). -*/ -static void explain_data_delete(ShellState *p){ - sqlite3_free(p->aiIndent); - p->aiIndent = 0; - p->nIndent = 0; - p->iIndent = 0; -} - -/* -** Disable and restore .wheretrace and .selecttrace settings. -*/ -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) -extern unsigned int sqlite3_unsupported_selecttrace; -static int savedSelectTrace; -#endif -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) -extern int sqlite3WhereTrace; -static int savedWhereTrace; -#endif -static void disable_debug_trace_modes(void){ -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) - savedSelectTrace = sqlite3_unsupported_selecttrace; - sqlite3_unsupported_selecttrace = 0; -#endif -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) - savedWhereTrace = sqlite3WhereTrace; - sqlite3WhereTrace = 0; -#endif -} -static void restore_debug_trace_modes(void){ -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) - sqlite3_unsupported_selecttrace = savedSelectTrace; -#endif -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) - sqlite3WhereTrace = savedWhereTrace; -#endif -} - -/* Create the TEMP table used to store parameter bindings */ -static void bind_table_init(ShellState *p){ - int wrSchema = 0; - int defensiveMode = 0; - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); - sqlite3_exec(p->db, - "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" - " key TEXT PRIMARY KEY,\n" - " value ANY\n" - ") WITHOUT ROWID;", - 0, 0, 0); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); -} - -/* -** Bind parameters on a prepared statement. -** -** Parameter bindings are taken from a TEMP table of the form: -** -** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) -** WITHOUT ROWID; -** -** No bindings occur if this table does not exist. The name of the table -** begins with "sqlite_" so that it will not collide with ordinary application -** tables. The table must be in the TEMP schema. -*/ -static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ - int nVar; - int i; - int rc; - sqlite3_stmt *pQ = 0; - - nVar = sqlite3_bind_parameter_count(pStmt); - if( nVar==0 ) return; /* Nothing to do */ - if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", - "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ - return; /* Parameter table does not exist */ - } - rc = sqlite3_prepare_v2(pArg->db, - "SELECT value FROM temp.sqlite_parameters" - " WHERE key=?1", -1, &pQ, 0); - if( rc || pQ==0 ) return; - for(i=1; i<=nVar; i++){ - char zNum[30]; - const char *zVar = sqlite3_bind_parameter_name(pStmt, i); - if( zVar==0 ){ - sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); - zVar = zNum; - } - sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); - if( sqlite3_step(pQ)==SQLITE_ROW ){ - sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); - }else{ - sqlite3_bind_null(pStmt, i); - } - sqlite3_reset(pQ); - } - sqlite3_finalize(pQ); -} - -/* -** UTF8 box-drawing characters. Imagine box lines like this: -** -** 1 -** | -** 4 --+-- 2 -** | -** 3 -** -** Each box characters has between 2 and 4 of the lines leading from -** the center. The characters are here identified by the numbers of -** their corresponding lines. -*/ -#define BOX_24 "\342\224\200" /* U+2500 --- */ -#define BOX_13 "\342\224\202" /* U+2502 | */ -#define BOX_23 "\342\224\214" /* U+250c ,- */ -#define BOX_34 "\342\224\220" /* U+2510 -, */ -#define BOX_12 "\342\224\224" /* U+2514 '- */ -#define BOX_14 "\342\224\230" /* U+2518 -' */ -#define BOX_123 "\342\224\234" /* U+251c |- */ -#define BOX_134 "\342\224\244" /* U+2524 -| */ -#define BOX_234 "\342\224\254" /* U+252c -,- */ -#define BOX_124 "\342\224\264" /* U+2534 -'- */ -#define BOX_1234 "\342\224\274" /* U+253c -|- */ - -/* Draw horizontal line N characters long using unicode box -** characters -*/ -static void print_box_line(FILE *out, int N){ - const char zDash[] = - BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 - BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24; - const int nDash = sizeof(zDash) - 1; - N *= 3; - while( N>nDash ){ - utf8_printf(out, zDash); - N -= nDash; - } - utf8_printf(out, "%.*s", N, zDash); -} - -/* -** Draw a horizontal separator for a MODE_Box table. -*/ -static void print_box_row_separator( - ShellState *p, - int nArg, - const char *zSep1, - const char *zSep2, - const char *zSep3 -){ - int i; - if( nArg>0 ){ - utf8_printf(p->out, "%s", zSep1); - print_box_line(p->out, p->actualWidth[0]+2); - for(i=1; iout, "%s", zSep2); - print_box_line(p->out, p->actualWidth[i]+2); - } - utf8_printf(p->out, "%s", zSep3); - } - fputs("\n", p->out); -} - - - -/* -** Run a prepared statement and output the result in one of the -** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table, -** or MODE_Box. -** -** This is different from ordinary exec_prepared_stmt() in that -** it has to run the entire query and gather the results into memory -** first, in order to determine column widths, before providing -** any output. -*/ -static void exec_prepared_stmt_columnar( - ShellState *p, /* Pointer to ShellState */ - sqlite3_stmt *pStmt /* Statment to run */ -){ - sqlite3_int64 nRow = 0; - int nColumn = 0; - char **azData = 0; - sqlite3_int64 nAlloc = 0; - const char *z; - int rc; - sqlite3_int64 i, nData; - int j, nTotal, w, n; - const char *colSep = 0; - const char *rowSep = 0; - - rc = sqlite3_step(pStmt); - if( rc!=SQLITE_ROW ) return; - nColumn = sqlite3_column_count(pStmt); - nAlloc = nColumn*4; - azData = sqlite3_malloc64( nAlloc*sizeof(char*) ); - if( azData==0 ) shell_out_of_memory(); - for(i=0; i= nAlloc ){ - nAlloc *= 2; - azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*)); - if( azData==0 ) shell_out_of_memory(); - } - nRow++; - for(i=0; ip->nWidth ){ - p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int)); - if( p->colWidth==0 ) shell_out_of_memory(); - for(i=p->nWidth; icolWidth[i] = 0; - p->nWidth = nColumn; - p->actualWidth = &p->colWidth[nColumn]; - } - memset(p->actualWidth, 0, nColumn*sizeof(int)); - for(i=0; icolWidth[i]; - if( w<0 ) w = -w; - p->actualWidth[i] = w; - } - nTotal = nColumn*(nRow+1); - for(i=0; inullValue; - n = strlenChar(z); - j = i%nColumn; - if( n>p->actualWidth[j] ) p->actualWidth[j] = n; - } - if( seenInterrupt ) goto columnar_end; - switch( p->cMode ){ - case MODE_Column: { - colSep = " "; - rowSep = "\n"; - if( p->showHeader ){ - for(i=0; iactualWidth[i]; - if( p->colWidth[i]<0 ) w = -w; - utf8_width_print(p->out, w, azData[i]); - fputs(i==nColumn-1?"\n":" ", p->out); - } - for(i=0; iout, p->actualWidth[i]); - fputs(i==nColumn-1?"\n":" ", p->out); - } - } - break; - } - case MODE_Table: { - colSep = " | "; - rowSep = " |\n"; - print_row_separator(p, nColumn, "+"); - fputs("| ", p->out); - for(i=0; iactualWidth[i]; - n = strlenChar(azData[i]); - utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); - fputs(i==nColumn-1?" |\n":" | ", p->out); - } - print_row_separator(p, nColumn, "+"); - break; - } - case MODE_Markdown: { - colSep = " | "; - rowSep = " |\n"; - fputs("| ", p->out); - for(i=0; iactualWidth[i]; - n = strlenChar(azData[i]); - utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); - fputs(i==nColumn-1?" |\n":" | ", p->out); - } - print_row_separator(p, nColumn, "|"); - break; - } - case MODE_Box: { - colSep = " " BOX_13 " "; - rowSep = " " BOX_13 "\n"; - print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34); - utf8_printf(p->out, BOX_13 " "); - for(i=0; iactualWidth[i]; - n = strlenChar(azData[i]); - utf8_printf(p->out, "%*s%s%*s%s", - (w-n)/2, "", azData[i], (w-n+1)/2, "", - i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); - } - print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); - break; - } - } - for(i=nColumn, j=0; icMode!=MODE_Column ){ - utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| "); - } - z = azData[i]; - if( z==0 ) z = p->nullValue; - w = p->actualWidth[j]; - if( p->colWidth[j]<0 ) w = -w; - utf8_width_print(p->out, w, z); - if( j==nColumn-1 ){ - utf8_printf(p->out, "%s", rowSep); - j = -1; - if( seenInterrupt ) goto columnar_end; - }else{ - utf8_printf(p->out, "%s", colSep); - } - } - if( p->cMode==MODE_Table ){ - print_row_separator(p, nColumn, "+"); - }else if( p->cMode==MODE_Box ){ - print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14); - } -columnar_end: - if( seenInterrupt ){ - utf8_printf(p->out, "Interrupt\n"); - } - nData = (nRow+1)*nColumn; - for(i=0; icMode==MODE_Column - || pArg->cMode==MODE_Table - || pArg->cMode==MODE_Box - || pArg->cMode==MODE_Markdown - ){ - exec_prepared_stmt_columnar(pArg, pStmt); - return; - } - - /* perform the first step. this will tell us if we - ** have a result set or not and how wide it is. - */ - rc = sqlite3_step(pStmt); - /* if we have a result set... */ - if( SQLITE_ROW == rc ){ - /* allocate space for col name ptr, value ptr, and type */ - int nCol = sqlite3_column_count(pStmt); - void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); - if( !pData ){ - rc = SQLITE_NOMEM; - }else{ - char **azCols = (char **)pData; /* Names of result columns */ - char **azVals = &azCols[nCol]; /* Results */ - int *aiTypes = (int *)&azVals[nCol]; /* Result types */ - int i, x; - assert(sizeof(int) <= sizeof(char *)); - /* save off ptrs to column names */ - for(i=0; icMode==MODE_Insert ){ - azVals[i] = ""; - }else{ - azVals[i] = (char*)sqlite3_column_text(pStmt, i); - } - if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ - rc = SQLITE_NOMEM; - break; /* from for */ - } - } /* end for */ - - /* if data and types extracted successfully... */ - if( SQLITE_ROW == rc ){ - /* call the supplied callback with the result row data */ - if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ - rc = SQLITE_ABORT; - }else{ - rc = sqlite3_step(pStmt); - } - } - } while( SQLITE_ROW == rc ); - sqlite3_free(pData); - if( pArg->cMode==MODE_Json ){ - fputs("]\n", pArg->out); - } - } - } -} - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** This function is called to process SQL if the previous shell command -** was ".expert". It passes the SQL in the second argument directly to -** the sqlite3expert object. -** -** If successful, SQLITE_OK is returned. Otherwise, an SQLite error -** code. In this case, (*pzErr) may be set to point to a buffer containing -** an English language error message. It is the responsibility of the -** caller to eventually free this buffer using sqlite3_free(). -*/ -static int expertHandleSQL( - ShellState *pState, - const char *zSql, - char **pzErr -){ - assert( pState->expert.pExpert ); - assert( pzErr==0 || *pzErr==0 ); - return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); -} - -/* -** This function is called either to silently clean up the object -** created by the ".expert" command (if bCancel==1), or to generate a -** report from it and then clean it up (if bCancel==0). -** -** If successful, SQLITE_OK is returned. Otherwise, an SQLite error -** code. In this case, (*pzErr) may be set to point to a buffer containing -** an English language error message. It is the responsibility of the -** caller to eventually free this buffer using sqlite3_free(). -*/ -static int expertFinish( - ShellState *pState, - int bCancel, - char **pzErr -){ - int rc = SQLITE_OK; - sqlite3expert *p = pState->expert.pExpert; - assert( p ); - assert( bCancel || pzErr==0 || *pzErr==0 ); - if( bCancel==0 ){ - FILE *out = pState->out; - int bVerbose = pState->expert.bVerbose; - - rc = sqlite3_expert_analyze(p, pzErr); - if( rc==SQLITE_OK ){ - int nQuery = sqlite3_expert_count(p); - int i; - - if( bVerbose ){ - const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); - raw_printf(out, "-- Candidates -----------------------------\n"); - raw_printf(out, "%s\n", zCand); - } - for(i=0; iexpert.pExpert = 0; - return rc; -} - -/* -** Implementation of ".expert" dot command. -*/ -static int expertDotCommand( - ShellState *pState, /* Current shell tool state */ - char **azArg, /* Array of arguments passed to dot command */ - int nArg /* Number of entries in azArg[] */ -){ - int rc = SQLITE_OK; - char *zErr = 0; - int i; - int iSample = 0; - - assert( pState->expert.pExpert==0 ); - memset(&pState->expert, 0, sizeof(ExpertInfo)); - - for(i=1; rc==SQLITE_OK && i=2 && 0==strncmp(z, "-verbose", n) ){ - pState->expert.bVerbose = 1; - } - else if( n>=2 && 0==strncmp(z, "-sample", n) ){ - if( i==(nArg-1) ){ - raw_printf(stderr, "option requires an argument: %s\n", z); - rc = SQLITE_ERROR; - }else{ - iSample = (int)integerValue(azArg[++i]); - if( iSample<0 || iSample>100 ){ - raw_printf(stderr, "value out of range: %s\n", azArg[i]); - rc = SQLITE_ERROR; - } - } - } - else{ - raw_printf(stderr, "unknown option: %s\n", z); - rc = SQLITE_ERROR; - } - } - - if( rc==SQLITE_OK ){ - pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); - if( pState->expert.pExpert==0 ){ - raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr); - rc = SQLITE_ERROR; - }else{ - sqlite3_expert_config( - pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample - ); - } - } - - return rc; -} -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ - -/* -** Execute a statement or set of statements. Print -** any result rows/columns depending on the current mode -** set via the supplied callback. -** -** This is very similar to SQLite's built-in sqlite3_exec() -** function except it takes a slightly different callback -** and callback data argument. -*/ -static int shell_exec( - ShellState *pArg, /* Pointer to ShellState */ - const char *zSql, /* SQL to be evaluated */ - char **pzErrMsg /* Error msg written here */ -){ - sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ - int rc = SQLITE_OK; /* Return Code */ - int rc2; - const char *zLeftover; /* Tail of unprocessed SQL */ - sqlite3 *db = pArg->db; - - if( pzErrMsg ){ - *pzErrMsg = NULL; - } - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( pArg->expert.pExpert ){ - rc = expertHandleSQL(pArg, zSql, pzErrMsg); - return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); - } -#endif - - while( zSql[0] && (SQLITE_OK == rc) ){ - static const char *zStmtSql; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); - if( SQLITE_OK != rc ){ - if( pzErrMsg ){ - *pzErrMsg = save_err_msg(db); - } - }else{ - if( !pStmt ){ - /* this happens for a comment or white-space */ - zSql = zLeftover; - while( IsSpace(zSql[0]) ) zSql++; - continue; - } - zStmtSql = sqlite3_sql(pStmt); - if( zStmtSql==0 ) zStmtSql = ""; - while( IsSpace(zStmtSql[0]) ) zStmtSql++; - - /* save off the prepared statment handle and reset row count */ - if( pArg ){ - pArg->pStmt = pStmt; - pArg->cnt = 0; - } - - /* echo the sql statement if echo on */ - if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ - utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); - } - - /* Show the EXPLAIN QUERY PLAN if .eqp is on */ - if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ - sqlite3_stmt *pExplain; - char *zEQP; - int triggerEQP = 0; - disable_debug_trace_modes(); - sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); - if( pArg->autoEQP>=AUTOEQP_trigger ){ - sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); - } - zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); - rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); - if( rc==SQLITE_OK ){ - while( sqlite3_step(pExplain)==SQLITE_ROW ){ - const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); - int iEqpId = sqlite3_column_int(pExplain, 0); - int iParentId = sqlite3_column_int(pExplain, 1); - if( zEQPLine==0 ) zEQPLine = ""; - if( zEQPLine[0]=='-' ) eqp_render(pArg); - eqp_append(pArg, iEqpId, iParentId, zEQPLine); - } - eqp_render(pArg); - } - sqlite3_finalize(pExplain); - sqlite3_free(zEQP); - if( pArg->autoEQP>=AUTOEQP_full ){ - /* Also do an EXPLAIN for ".eqp full" mode */ - zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); - rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); - if( rc==SQLITE_OK ){ - pArg->cMode = MODE_Explain; - explain_data_prepare(pArg, pExplain); - exec_prepared_stmt(pArg, pExplain); - explain_data_delete(pArg); - } - sqlite3_finalize(pExplain); - sqlite3_free(zEQP); - } - if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ - sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); - /* Reprepare pStmt before reactiving trace modes */ - sqlite3_finalize(pStmt); - sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( pArg ) pArg->pStmt = pStmt; - } - restore_debug_trace_modes(); - } - - if( pArg ){ - pArg->cMode = pArg->mode; - if( pArg->autoExplain ){ - if( sqlite3_stmt_isexplain(pStmt)==1 ){ - pArg->cMode = MODE_Explain; - } - if( sqlite3_stmt_isexplain(pStmt)==2 ){ - pArg->cMode = MODE_EQP; - } - } - - /* If the shell is currently in ".explain" mode, gather the extra - ** data required to add indents to the output.*/ - if( pArg->cMode==MODE_Explain ){ - explain_data_prepare(pArg, pStmt); - } - } - - bind_prepared_stmt(pArg, pStmt); - exec_prepared_stmt(pArg, pStmt); - explain_data_delete(pArg); - eqp_render(pArg); - - /* print usage stats if stats on */ - if( pArg && pArg->statsOn ){ - display_stats(db, pArg, 0); - } - - /* print loop-counters if required */ - if( pArg && pArg->scanstatsOn ){ - display_scanstats(db, pArg); - } - - /* Finalize the statement just executed. If this fails, save a - ** copy of the error message. Otherwise, set zSql to point to the - ** next statement to execute. */ - rc2 = sqlite3_finalize(pStmt); - if( rc!=SQLITE_NOMEM ) rc = rc2; - if( rc==SQLITE_OK ){ - zSql = zLeftover; - while( IsSpace(zSql[0]) ) zSql++; - }else if( pzErrMsg ){ - *pzErrMsg = save_err_msg(db); - } - - /* clear saved stmt handle */ - if( pArg ){ - pArg->pStmt = NULL; - } - } - } /* end while */ - - return rc; -} - -/* -** Release memory previously allocated by tableColumnList(). -*/ -static void freeColumnList(char **azCol){ - int i; - for(i=1; azCol[i]; i++){ - sqlite3_free(azCol[i]); - } - /* azCol[0] is a static string */ - sqlite3_free(azCol); -} - -/* -** Return a list of pointers to strings which are the names of all -** columns in table zTab. The memory to hold the names is dynamically -** allocated and must be released by the caller using a subsequent call -** to freeColumnList(). -** -** The azCol[0] entry is usually NULL. However, if zTab contains a rowid -** value that needs to be preserved, then azCol[0] is filled in with the -** name of the rowid column. -** -** The first regular column in the table is azCol[1]. The list is terminated -** by an entry with azCol[i]==0. -*/ -static char **tableColumnList(ShellState *p, const char *zTab){ - char **azCol = 0; - sqlite3_stmt *pStmt; - char *zSql; - int nCol = 0; - int nAlloc = 0; - int nPK = 0; /* Number of PRIMARY KEY columns seen */ - int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ - int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); - int rc; - - zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc ) return 0; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - if( nCol>=nAlloc-2 ){ - nAlloc = nAlloc*2 + nCol + 10; - azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); - if( azCol==0 ) shell_out_of_memory(); - } - azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); - if( sqlite3_column_int(pStmt, 5) ){ - nPK++; - if( nPK==1 - && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), - "INTEGER")==0 - ){ - isIPK = 1; - }else{ - isIPK = 0; - } - } - } - sqlite3_finalize(pStmt); - if( azCol==0 ) return 0; - azCol[0] = 0; - azCol[nCol+1] = 0; - - /* The decision of whether or not a rowid really needs to be preserved - ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table - ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve - ** rowids on tables where the rowid is inaccessible because there are other - ** columns in the table named "rowid", "_rowid_", and "oid". - */ - if( preserveRowid && isIPK ){ - /* If a single PRIMARY KEY column with type INTEGER was seen, then it - ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID - ** table or a INTEGER PRIMARY KEY DESC column, neither of which are - ** ROWID aliases. To distinguish these cases, check to see if - ** there is a "pk" entry in "PRAGMA index_list". There will be - ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. - */ - zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" - " WHERE origin='pk'", zTab); - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc ){ - freeColumnList(azCol); - return 0; - } - rc = sqlite3_step(pStmt); - sqlite3_finalize(pStmt); - preserveRowid = rc==SQLITE_ROW; - } - if( preserveRowid ){ - /* Only preserve the rowid if we can find a name to use for the - ** rowid */ - static char *azRowid[] = { "rowid", "_rowid_", "oid" }; - int i, j; - for(j=0; j<3; j++){ - for(i=1; i<=nCol; i++){ - if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; - } - if( i>nCol ){ - /* At this point, we know that azRowid[j] is not the name of any - ** ordinary column in the table. Verify that azRowid[j] is a valid - ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID - ** tables will fail this last check */ - rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); - if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; - break; - } - } - } - return azCol; -} - -/* -** Toggle the reverse_unordered_selects setting. -*/ -static void toggleSelectOrder(sqlite3 *db){ - sqlite3_stmt *pStmt = 0; - int iSetting = 0; - char zStmt[100]; - sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); - if( sqlite3_step(pStmt)==SQLITE_ROW ){ - iSetting = sqlite3_column_int(pStmt, 0); - } - sqlite3_finalize(pStmt); - sqlite3_snprintf(sizeof(zStmt), zStmt, - "PRAGMA reverse_unordered_selects(%d)", !iSetting); - sqlite3_exec(db, zStmt, 0, 0, 0); -} - -/* -** This is a different callback routine used for dumping the database. -** Each row received by this callback consists of a table name, -** the table type ("index" or "table") and SQL to create the table. -** This routine should print text sufficient to recreate the table. -*/ -static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ - int rc; - const char *zTable; - const char *zType; - const char *zSql; - ShellState *p = (ShellState *)pArg; - - UNUSED_PARAMETER(azNotUsed); - if( nArg!=3 || azArg==0 ) return 0; - zTable = azArg[0]; - zType = azArg[1]; - zSql = azArg[2]; - - if( strcmp(zTable, "sqlite_sequence")==0 ){ - raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); - }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ - raw_printf(p->out, "ANALYZE sqlite_schema;\n"); - }else if( strncmp(zTable, "sqlite_", 7)==0 ){ - return 0; - }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ - char *zIns; - if( !p->writableSchema ){ - raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); - p->writableSchema = 1; - } - zIns = sqlite3_mprintf( - "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" - "VALUES('table','%q','%q',0,'%q');", - zTable, zTable, zSql); - utf8_printf(p->out, "%s\n", zIns); - sqlite3_free(zIns); - return 0; - }else{ - printSchemaLine(p->out, zSql, ";\n"); - } - - if( strcmp(zType, "table")==0 ){ - ShellText sSelect; - ShellText sTable; - char **azCol; - int i; - char *savedDestTable; - int savedMode; - - azCol = tableColumnList(p, zTable); - if( azCol==0 ){ - p->nErr++; - return 0; - } - - /* Always quote the table name, even if it appears to be pure ascii, - ** in case it is a keyword. Ex: INSERT INTO "table" ... */ - initText(&sTable); - appendText(&sTable, zTable, quoteChar(zTable)); - /* If preserving the rowid, add a column list after the table name. - ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" - ** instead of the usual "INSERT INTO tab VALUES(...)". - */ - if( azCol[0] ){ - appendText(&sTable, "(", 0); - appendText(&sTable, azCol[0], 0); - for(i=1; azCol[i]; i++){ - appendText(&sTable, ",", 0); - appendText(&sTable, azCol[i], quoteChar(azCol[i])); - } - appendText(&sTable, ")", 0); - } - - /* Build an appropriate SELECT statement */ - initText(&sSelect); - appendText(&sSelect, "SELECT ", 0); - if( azCol[0] ){ - appendText(&sSelect, azCol[0], 0); - appendText(&sSelect, ",", 0); - } - for(i=1; azCol[i]; i++){ - appendText(&sSelect, azCol[i], quoteChar(azCol[i])); - if( azCol[i+1] ){ - appendText(&sSelect, ",", 0); - } - } - freeColumnList(azCol); - appendText(&sSelect, " FROM ", 0); - appendText(&sSelect, zTable, quoteChar(zTable)); - - savedDestTable = p->zDestTable; - savedMode = p->mode; - p->zDestTable = sTable.z; - p->mode = p->cMode = MODE_Insert; - rc = shell_exec(p, sSelect.z, 0); - if( (rc&0xff)==SQLITE_CORRUPT ){ - raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); - toggleSelectOrder(p->db); - shell_exec(p, sSelect.z, 0); - toggleSelectOrder(p->db); - } - p->zDestTable = savedDestTable; - p->mode = savedMode; - freeText(&sTable); - freeText(&sSelect); - if( rc ) p->nErr++; - } - return 0; -} - -/* -** Run zQuery. Use dump_callback() as the callback routine so that -** the contents of the query are output as SQL statements. -** -** If we get a SQLITE_CORRUPT error, rerun the query after appending -** "ORDER BY rowid DESC" to the end. -*/ -static int run_schema_dump_query( - ShellState *p, - const char *zQuery -){ - int rc; - char *zErr = 0; - rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); - if( rc==SQLITE_CORRUPT ){ - char *zQ2; - int len = strlen30(zQuery); - raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); - if( zErr ){ - utf8_printf(p->out, "/****** %s ******/\n", zErr); - sqlite3_free(zErr); - zErr = 0; - } - zQ2 = malloc( len+100 ); - if( zQ2==0 ) return rc; - sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); - rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); - if( rc ){ - utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); - }else{ - rc = SQLITE_CORRUPT; - } - sqlite3_free(zErr); - free(zQ2); - } - return rc; -} - -/* -** Text of help messages. -** -** The help text for each individual command begins with a line that starts -** with ".". Subsequent lines are supplimental information. -** -** There must be two or more spaces between the end of the command and the -** start of the description of what that command does. -*/ -static const char *(azHelp[]) = { -#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) - ".archive ... Manage SQL archives", - " Each command must have exactly one of the following options:", - " -c, --create Create a new archive", - " -u, --update Add or update files with changed mtime", - " -i, --insert Like -u but always add even if unchanged", - " -t, --list List contents of archive", - " -x, --extract Extract files from archive", - " Optional arguments:", - " -v, --verbose Print each filename as it is processed", - " -f FILE, --file FILE Use archive FILE (default is current db)", - " -a FILE, --append FILE Open FILE using the apndvfs VFS", - " -C DIR, --directory DIR Read/extract files from directory DIR", - " -n, --dryrun Show the SQL that would have occurred", - " Examples:", - " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar", - " .ar -tf ARCHIVE # List members of ARCHIVE", - " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE", - " See also:", - " http://sqlite.org/cli.html#sqlar_archive_support", -#endif -#ifndef SQLITE_OMIT_AUTHORIZATION - ".auth ON|OFF Show authorizer callbacks", -#endif - ".backup ?DB? FILE Backup DB (default \"main\") to FILE", - " --append Use the appendvfs", - " --async Write to FILE without journal and fsync()", - ".bail on|off Stop after hitting an error. Default OFF", - ".binary on|off Turn binary output on or off. Default OFF", - ".cd DIRECTORY Change the working directory to DIRECTORY", - ".changes on|off Show number of rows changed by SQL", - ".check GLOB Fail if output since .testcase does not match", - ".clone NEWDB Clone data into NEWDB from the existing database", - ".databases List names and files of attached databases", - ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", - ".dbinfo ?DB? Show status information about the database", - ".dump ?TABLE? Render database content as SQL", - " Options:", - " --preserve-rowids Include ROWID values in the output", - " --newlines Allow unescaped newline characters in output", - " TABLE is a LIKE pattern for the tables to dump", - " Additional LIKE patterns can be given in subsequent arguments", - ".echo on|off Turn command echo on or off", - ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", - " Other Modes:", -#ifdef SQLITE_DEBUG - " test Show raw EXPLAIN QUERY PLAN output", - " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"", -#endif - " trigger Like \"full\" but also show trigger bytecode", - ".excel Display the output of next command in spreadsheet", - " --bom Put a UTF8 byte-order mark on intermediate file", - ".exit ?CODE? Exit this program with return-code CODE", - ".expert EXPERIMENTAL. Suggest indexes for queries", - ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto", - ".filectrl CMD ... Run various sqlite3_file_control() operations", - " --schema SCHEMA Use SCHEMA instead of \"main\"", - " --help Show CMD details", - ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", - ".headers on|off Turn display of headers on or off", - ".help ?-all? ?PATTERN? Show help text for PATTERN", - ".import FILE TABLE Import data from FILE into TABLE", - " Options:", - " --ascii Use \\037 and \\036 as column and row separators", - " --csv Use , and \\n as column and row separators", - " --skip N Skip the first N rows of input", - " -v \"Verbose\" - increase auxiliary output", - " Notes:", - " * If TABLE does not exist, it is created. The first row of input", - " determines the column names.", - " * If neither --csv or --ascii are used, the input mode is derived", - " from the \".mode\" output mode", - " * If FILE begins with \"|\" then it is a command that generates the", - " input text.", -#ifndef SQLITE_OMIT_TEST_CONTROL - ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", -#endif - ".indexes ?TABLE? Show names of indexes", - " If TABLE is specified, only show indexes for", - " tables matching TABLE using the LIKE operator.", -#ifdef SQLITE_ENABLE_IOTRACE - ".iotrace FILE Enable I/O diagnostic logging to FILE", -#endif - ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", - ".lint OPTIONS Report potential schema issues.", - " Options:", - " fkey-indexes Find missing foreign key indexes", -#ifndef SQLITE_OMIT_LOAD_EXTENSION - ".load FILE ?ENTRY? Load an extension library", -#endif - ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", - ".mode MODE ?TABLE? Set output mode", - " MODE is one of:", - " ascii Columns/rows delimited by 0x1F and 0x1E", - " box Tables using unicode box-drawing characters", - " csv Comma-separated values", - " column Output in columns. (See .width)", - " html HTML
"); - output_html_string(p->out, azCol[i]); - raw_printf(p->out,"
"); - output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); - raw_printf(p->out,"
code", - " insert SQL insert statements for TABLE", - " json Results in a JSON array", - " line One value per line", - " list Values delimited by \"|\"", - " markdown Markdown table format", - " quote Escape answers as for SQL", - " table ASCII-art table", - " tabs Tab-separated values", - " tcl TCL list elements", - ".nullvalue STRING Use STRING in place of NULL values", - ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE", - " If FILE begins with '|' then open as a pipe", - " --bom Put a UTF8 byte-order mark at the beginning", - " -e Send output to the system text editor", - " -x Send output as CSV to a spreadsheet (same as \".excel\")", -#ifdef SQLITE_DEBUG - ".oom ?--repeat M? ?N? Simulate an OOM error on the N-th allocation", -#endif - ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", - " Options:", - " --append Use appendvfs to append database to the end of FILE", -#ifdef SQLITE_ENABLE_DESERIALIZE - " --deserialize Load into memory useing sqlite3_deserialize()", - " --hexdb Load the output of \"dbtotxt\" as an in-memory db", - " --maxsize N Maximum size for --hexdb or --deserialized database", -#endif - " --new Initialize FILE to an empty database", - " --nofollow Do not follow symbolic links", - " --readonly Open FILE readonly", - " --zip FILE is a ZIP archive", - ".output ?FILE? Send output to FILE or stdout if FILE is omitted", - " If FILE begins with '|' then open it as a pipe.", - " Options:", - " --bom Prefix output with a UTF8 byte-order mark", - " -e Send output to the system text editor", - " -x Send output as CSV to a spreadsheet", - ".parameter CMD ... Manage SQL parameter bindings", - " clear Erase all bindings", - " init Initialize the TEMP table that holds bindings", - " list List the current parameter bindings", - " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", - " PARAMETER should start with one of: $ : @ ?", - " unset PARAMETER Remove PARAMETER from the binding table", - ".print STRING... Print literal STRING", -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - ".progress N Invoke progress handler after every N opcodes", - " --limit N Interrupt after N progress callbacks", - " --once Do no more than one progress interrupt", - " --quiet|-q No output except at interrupts", - " --reset Reset the count for each input and interrupt", -#endif - ".prompt MAIN CONTINUE Replace the standard prompts", - ".quit Exit this program", - ".read FILE Read input from FILE", -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) - ".recover Recover as much data as possible from corrupt db.", - " --freelist-corrupt Assume the freelist is corrupt", - " --recovery-db NAME Store recovery metadata in database file NAME", - " --lost-and-found TABLE Alternative name for the lost-and-found table", - " --no-rowids Do not attempt to recover rowid values", - " that are not also INTEGER PRIMARY KEYs", -#endif - ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", - ".save FILE Write in-memory database into FILE", - ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", - ".schema ?PATTERN? Show the CREATE statements matching PATTERN", - " Options:", - " --indent Try to pretty-print the schema", - ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", - " Options:", - " --init Create a new SELFTEST table", - " -v Verbose output", - ".separator COL ?ROW? Change the column and row separators", -#if defined(SQLITE_ENABLE_SESSION) - ".session ?NAME? CMD ... Create or control sessions", - " Subcommands:", - " attach TABLE Attach TABLE", - " changeset FILE Write a changeset into FILE", - " close Close one session", - " enable ?BOOLEAN? Set or query the enable bit", - " filter GLOB... Reject tables matching GLOBs", - " indirect ?BOOLEAN? Mark or query the indirect status", - " isempty Query whether the session is empty", - " list List currently open session names", - " open DB NAME Open a new session on DB", - " patchset FILE Write a patchset into FILE", - " If ?NAME? is omitted, the first defined session is used.", -#endif - ".sha3sum ... Compute a SHA3 hash of database content", - " Options:", - " --schema Also hash the sqlite_schema table", - " --sha3-224 Use the sha3-224 algorithm", - " --sha3-256 Use the sha3-256 algorithm (default)", - " --sha3-384 Use the sha3-384 algorithm", - " --sha3-512 Use the sha3-512 algorithm", - " Any other argument is a LIKE pattern for tables to hash", -#ifndef SQLITE_NOHAVE_SYSTEM - ".shell CMD ARGS... Run CMD ARGS... in a system shell", -#endif - ".show Show the current values for various settings", - ".stats ?on|off? Show stats or turn stats on or off", -#ifndef SQLITE_NOHAVE_SYSTEM - ".system CMD ARGS... Run CMD ARGS... in a system shell", -#endif - ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", - ".testcase NAME Begin redirecting output to 'testcase-out.txt'", - ".testctrl CMD ... Run various sqlite3_test_control() operations", - " Run \".testctrl\" with no arguments for details", - ".timeout MS Try opening locked tables for MS milliseconds", - ".timer on|off Turn SQL timer on or off", -#ifndef SQLITE_OMIT_TRACE - ".trace ?OPTIONS? Output each SQL statement as it is run", - " FILE Send output to FILE", - " stdout Send output to stdout", - " stderr Send output to stderr", - " off Disable tracing", - " --expanded Expand query parameters", -#ifdef SQLITE_ENABLE_NORMALIZE - " --normalized Normal the SQL statements", -#endif - " --plain Show SQL as it is input", - " --stmt Trace statement execution (SQLITE_TRACE_STMT)", - " --profile Profile statements (SQLITE_TRACE_PROFILE)", - " --row Trace each row (SQLITE_TRACE_ROW)", - " --close Trace connection close (SQLITE_TRACE_CLOSE)", -#endif /* SQLITE_OMIT_TRACE */ -#ifdef SQLITE_DEBUG - ".unmodule NAME ... Unregister virtual table modules", - " --allexcept Unregister everything except those named", -#endif - ".vfsinfo ?AUX? Information about the top-level VFS", - ".vfslist List all available VFSes", - ".vfsname ?AUX? Print the name of the VFS stack", - ".width NUM1 NUM2 ... Set minimum column widths for columnar output", - " Negative values right-justify", -}; - -/* -** Output help text. -** -** zPattern describes the set of commands for which help text is provided. -** If zPattern is NULL, then show all commands, but only give a one-line -** description of each. -** -** Return the number of matches. -*/ -static int showHelp(FILE *out, const char *zPattern){ - int i = 0; - int j = 0; - int n = 0; - char *zPat; - if( zPattern==0 - || zPattern[0]=='0' - || strcmp(zPattern,"-a")==0 - || strcmp(zPattern,"-all")==0 - || strcmp(zPattern,"--all")==0 - ){ - /* Show all commands, but only one line per command */ - if( zPattern==0 ) zPattern = ""; - for(i=0; ip); - sqlite3_free(pSession->zName); - for(i=0; inFilter; i++){ - sqlite3_free(pSession->azFilter[i]); - } - sqlite3_free(pSession->azFilter); - memset(pSession, 0, sizeof(OpenSession)); -} -#endif - -/* -** Close all OpenSession objects and release all associated resources. -*/ -#if defined(SQLITE_ENABLE_SESSION) -static void session_close_all(ShellState *p){ - int i; - for(i=0; inSession; i++){ - session_close(&p->aSession[i]); - } - p->nSession = 0; -} -#else -# define session_close_all(X) -#endif - -/* -** Implementation of the xFilter function for an open session. Omit -** any tables named by ".session filter" but let all other table through. -*/ -#if defined(SQLITE_ENABLE_SESSION) -static int session_filter(void *pCtx, const char *zTab){ - OpenSession *pSession = (OpenSession*)pCtx; - int i; - for(i=0; inFilter; i++){ - if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; - } - return 1; -} -#endif - -/* -** Try to deduce the type of file for zName based on its content. Return -** one of the SHELL_OPEN_* constants. -** -** If the file does not exist or is empty but its name looks like a ZIP -** archive and the dfltZip flag is true, then assume it is a ZIP archive. -** Otherwise, assume an ordinary database regardless of the filename if -** the type cannot be determined from content. -*/ -int deduceDatabaseType(const char *zName, int dfltZip){ - FILE *f = fopen(zName, "rb"); - size_t n; - int rc = SHELL_OPEN_UNSPEC; - char zBuf[100]; - if( f==0 ){ - if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ - return SHELL_OPEN_ZIPFILE; - }else{ - return SHELL_OPEN_NORMAL; - } - } - n = fread(zBuf, 16, 1, f); - if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ - fclose(f); - return SHELL_OPEN_NORMAL; - } - fseek(f, -25, SEEK_END); - n = fread(zBuf, 25, 1, f); - if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ - rc = SHELL_OPEN_APPENDVFS; - }else{ - fseek(f, -22, SEEK_END); - n = fread(zBuf, 22, 1, f); - if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 - && zBuf[3]==0x06 ){ - rc = SHELL_OPEN_ZIPFILE; - }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ - rc = SHELL_OPEN_ZIPFILE; - } - } - fclose(f); - return rc; -} - -#ifdef SQLITE_ENABLE_DESERIALIZE -/* -** Reconstruct an in-memory database using the output from the "dbtotxt" -** program. Read content from the file in p->zDbFilename. If p->zDbFilename -** is 0, then read from standard input. -*/ -static unsigned char *readHexDb(ShellState *p, int *pnData){ - unsigned char *a = 0; - int nLine; - int n = 0; - int pgsz = 0; - int iOffset = 0; - int j, k; - int rc; - FILE *in; - unsigned int x[16]; - char zLine[1000]; - if( p->zDbFilename ){ - in = fopen(p->zDbFilename, "r"); - if( in==0 ){ - utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename); - return 0; - } - nLine = 0; - }else{ - in = p->in; - nLine = p->lineno; - if( in==0 ) in = stdin; - } - *pnData = 0; - nLine++; - if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; - rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); - if( rc!=2 ) goto readHexDb_error; - if( n<0 ) goto readHexDb_error; - if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; - n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ - a = sqlite3_malloc( n ? n : 1 ); - if( a==0 ){ - utf8_printf(stderr, "Out of memory!\n"); - goto readHexDb_error; - } - memset(a, 0, n); - if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ - utf8_printf(stderr, "invalid pagesize\n"); - goto readHexDb_error; - } - for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ - rc = sscanf(zLine, "| page %d offset %d", &j, &k); - if( rc==2 ){ - iOffset = k; - continue; - } - if( strncmp(zLine, "| end ", 6)==0 ){ - break; - } - rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", - &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], - &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); - if( rc==17 ){ - k = iOffset+j; - if( k+16<=n ){ - int ii; - for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; - } - } - } - *pnData = n; - if( in!=p->in ){ - fclose(in); - }else{ - p->lineno = nLine; - } - return a; - -readHexDb_error: - if( in!=p->in ){ - fclose(in); - }else{ - while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ - nLine++; - if(strncmp(zLine, "| end ", 6)==0 ) break; - } - p->lineno = nLine; - } - sqlite3_free(a); - utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); - return 0; -} -#endif /* SQLITE_ENABLE_DESERIALIZE */ - -/* -** Scalar function "shell_int32". The first argument to this function -** must be a blob. The second a non-negative integer. This function -** reads and returns a 32-bit big-endian integer from byte -** offset (4*) of the blob. -*/ -static void shellInt32( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *pBlob; - int nBlob; - int iInt; - - UNUSED_PARAMETER(argc); - nBlob = sqlite3_value_bytes(argv[0]); - pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); - iInt = sqlite3_value_int(argv[1]); - - if( iInt>=0 && (iInt+1)*4<=nBlob ){ - const unsigned char *a = &pBlob[iInt*4]; - sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) - + ((sqlite3_int64)a[1]<<16) - + ((sqlite3_int64)a[2]<< 8) - + ((sqlite3_int64)a[3]<< 0); - sqlite3_result_int64(context, iVal); - } -} - -/* -** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, -** using "..." with internal double-quote characters doubled. -*/ -static void shellIdQuote( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zName = (const char*)sqlite3_value_text(argv[0]); - UNUSED_PARAMETER(argc); - if( zName ){ - char *z = sqlite3_mprintf("\"%w\"", zName); - sqlite3_result_text(context, z, -1, sqlite3_free); - } -} - -/* -** Scalar function "shell_escape_crnl" used by the .recover command. -** The argument passed to this function is the output of built-in -** function quote(). If the first character of the input is "'", -** indicating that the value passed to quote() was a text value, -** then this function searches the input for "\n" and "\r" characters -** and adds a wrapper similar to the following: -** -** replace(replace(, '\n', char(10), '\r', char(13)); -** -** Or, if the first character of the input is not "'", then a copy -** of the input is returned. -*/ -static void shellEscapeCrnl( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zText = (const char*)sqlite3_value_text(argv[0]); - UNUSED_PARAMETER(argc); - if( zText[0]=='\'' ){ - int nText = sqlite3_value_bytes(argv[0]); - int i; - char zBuf1[20]; - char zBuf2[20]; - const char *zNL = 0; - const char *zCR = 0; - int nCR = 0; - int nNL = 0; - - for(i=0; zText[i]; i++){ - if( zNL==0 && zText[i]=='\n' ){ - zNL = unused_string(zText, "\\n", "\\012", zBuf1); - nNL = (int)strlen(zNL); - } - if( zCR==0 && zText[i]=='\r' ){ - zCR = unused_string(zText, "\\r", "\\015", zBuf2); - nCR = (int)strlen(zCR); - } - } - - if( zNL || zCR ){ - int iOut = 0; - i64 nMax = (nNL > nCR) ? nNL : nCR; - i64 nAlloc = nMax * nText + (nMax+64)*2; - char *zOut = (char*)sqlite3_malloc64(nAlloc); - if( zOut==0 ){ - sqlite3_result_error_nomem(context); - return; - } - - if( zNL && zCR ){ - memcpy(&zOut[iOut], "replace(replace(", 16); - iOut += 16; - }else{ - memcpy(&zOut[iOut], "replace(", 8); - iOut += 8; - } - for(i=0; zText[i]; i++){ - if( zText[i]=='\n' ){ - memcpy(&zOut[iOut], zNL, nNL); - iOut += nNL; - }else if( zText[i]=='\r' ){ - memcpy(&zOut[iOut], zCR, nCR); - iOut += nCR; - }else{ - zOut[iOut] = zText[i]; - iOut++; - } - } - - if( zNL ){ - memcpy(&zOut[iOut], ",'", 2); iOut += 2; - memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; - memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; - } - if( zCR ){ - memcpy(&zOut[iOut], ",'", 2); iOut += 2; - memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; - memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; - } - - sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); - sqlite3_free(zOut); - return; - } - } - - sqlite3_result_value(context, argv[0]); -} - -/* Flags for open_db(). -** -** The default behavior of open_db() is to exit(1) if the database fails to -** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error -** but still returns without calling exit. -** -** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a -** ZIP archive if the file does not exist or is empty and its name matches -** the *.zip pattern. -*/ -#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ -#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ - -/* -** Make sure the database is open. If it is not, then open it. If -** the database fails to open, print an error message and exit. -*/ -static void open_db(ShellState *p, int openFlags){ - if( p->db==0 ){ - if( p->openMode==SHELL_OPEN_UNSPEC ){ - if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){ - p->openMode = SHELL_OPEN_NORMAL; - }else{ - p->openMode = (u8)deduceDatabaseType(p->zDbFilename, - (openFlags & OPEN_DB_ZIPFILE)!=0); - } - } - switch( p->openMode ){ - case SHELL_OPEN_APPENDVFS: { - sqlite3_open_v2(p->zDbFilename, &p->db, - SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); - break; - } - case SHELL_OPEN_HEXDB: - case SHELL_OPEN_DESERIALIZE: { - sqlite3_open(0, &p->db); - break; - } - case SHELL_OPEN_ZIPFILE: { - sqlite3_open(":memory:", &p->db); - break; - } - case SHELL_OPEN_READONLY: { - sqlite3_open_v2(p->zDbFilename, &p->db, - SQLITE_OPEN_READONLY|p->openFlags, 0); - break; - } - case SHELL_OPEN_UNSPEC: - case SHELL_OPEN_NORMAL: { - sqlite3_open_v2(p->zDbFilename, &p->db, - SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); - break; - } - } - globalDb = p->db; - if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ - utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", - p->zDbFilename, sqlite3_errmsg(p->db)); - if( openFlags & OPEN_DB_KEEPALIVE ){ - sqlite3_open(":memory:", &p->db); - return; - } - exit(1); - } -#ifndef SQLITE_OMIT_LOAD_EXTENSION - sqlite3_enable_load_extension(p->db, 1); -#endif - sqlite3_fileio_init(p->db, 0, 0); - sqlite3_shathree_init(p->db, 0, 0); - sqlite3_completion_init(p->db, 0, 0); - sqlite3_uint_init(p->db, 0, 0); - sqlite3_decimal_init(p->db, 0, 0); - sqlite3_ieee_init(p->db, 0, 0); -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) - sqlite3_dbdata_init(p->db, 0, 0); -#endif -#ifdef SQLITE_HAVE_ZLIB - sqlite3_zipfile_init(p->db, 0, 0); - sqlite3_sqlar_init(p->db, 0, 0); -#endif - sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, - shellAddSchemaName, 0, 0); - sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, - shellModuleSchema, 0, 0); - sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, - shellPutsFunc, 0, 0); - sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, - shellEscapeCrnl, 0, 0); - sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, - shellInt32, 0, 0); - sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, - shellIdQuote, 0, 0); -#ifndef SQLITE_NOHAVE_SYSTEM - sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, - editFunc, 0, 0); - sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, - editFunc, 0, 0); -#endif - if( p->openMode==SHELL_OPEN_ZIPFILE ){ - char *zSql = sqlite3_mprintf( - "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename); - sqlite3_exec(p->db, zSql, 0, 0, 0); - sqlite3_free(zSql); - } -#ifdef SQLITE_ENABLE_DESERIALIZE - else - if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ - int rc; - int nData = 0; - unsigned char *aData; - if( p->openMode==SHELL_OPEN_DESERIALIZE ){ - aData = (unsigned char*)readFile(p->zDbFilename, &nData); - }else{ - aData = readHexDb(p, &nData); - if( aData==0 ){ - return; - } - } - rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, - SQLITE_DESERIALIZE_RESIZEABLE | - SQLITE_DESERIALIZE_FREEONCLOSE); - if( rc ){ - utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); - } - if( p->szMax>0 ){ - sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); - } - } -#endif - } -} - -/* -** Attempt to close the databaes connection. Report errors. -*/ -void close_db(sqlite3 *db){ - int rc = sqlite3_close(db); - if( rc ){ - utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", - rc, sqlite3_errmsg(db)); - } -} - -#if HAVE_READLINE || HAVE_EDITLINE -/* -** Readline completion callbacks -*/ -static char *readline_completion_generator(const char *text, int state){ - static sqlite3_stmt *pStmt = 0; - char *zRet; - if( state==0 ){ - char *zSql; - sqlite3_finalize(pStmt); - zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" - " FROM completion(%Q) ORDER BY 1", text); - sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - } - if( sqlite3_step(pStmt)==SQLITE_ROW ){ - zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); - }else{ - sqlite3_finalize(pStmt); - pStmt = 0; - zRet = 0; - } - return zRet; -} -static char **readline_completion(const char *zText, int iStart, int iEnd){ - rl_attempted_completion_over = 1; - return rl_completion_matches(zText, readline_completion_generator); -} - -#elif HAVE_LINENOISE -/* -** Linenoise completion callback -*/ -static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ - int nLine = strlen30(zLine); - int i, iStart; - sqlite3_stmt *pStmt = 0; - char *zSql; - char zBuf[1000]; - - if( nLine>sizeof(zBuf)-30 ) return; - if( zLine[0]=='.' || zLine[0]=='#') return; - for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} - if( i==nLine-1 ) return; - iStart = i+1; - memcpy(zBuf, zLine, iStart); - zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" - " FROM completion(%Q,%Q) ORDER BY 1", - &zLine[iStart], zLine); - sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); - int nCompletion = sqlite3_column_bytes(pStmt, 0); - if( iStart+nCompletion < sizeof(zBuf)-1 ){ - memcpy(zBuf+iStart, zCompletion, nCompletion+1); - linenoiseAddCompletion(lc, zBuf); - } - } - sqlite3_finalize(pStmt); -} -#endif - -/* -** Do C-language style dequoting. -** -** \a -> alarm -** \b -> backspace -** \t -> tab -** \n -> newline -** \v -> vertical tab -** \f -> form feed -** \r -> carriage return -** \s -> space -** \" -> " -** \' -> ' -** \\ -> backslash -** \NNN -> ascii character NNN in octal -*/ -static void resolve_backslashes(char *z){ - int i, j; - char c; - while( *z && *z!='\\' ) z++; - for(i=j=0; (c = z[i])!=0; i++, j++){ - if( c=='\\' && z[i+1]!=0 ){ - c = z[++i]; - if( c=='a' ){ - c = '\a'; - }else if( c=='b' ){ - c = '\b'; - }else if( c=='t' ){ - c = '\t'; - }else if( c=='n' ){ - c = '\n'; - }else if( c=='v' ){ - c = '\v'; - }else if( c=='f' ){ - c = '\f'; - }else if( c=='r' ){ - c = '\r'; - }else if( c=='"' ){ - c = '"'; - }else if( c=='\'' ){ - c = '\''; - }else if( c=='\\' ){ - c = '\\'; - }else if( c>='0' && c<='7' ){ - c -= '0'; - if( z[i+1]>='0' && z[i+1]<='7' ){ - i++; - c = (c<<3) + z[i] - '0'; - if( z[i+1]>='0' && z[i+1]<='7' ){ - i++; - c = (c<<3) + z[i] - '0'; - } - } - } - } - z[j] = c; - } - if( j=0; i++){} - }else{ - for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} - } - if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); - if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ - return 1; - } - if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ - return 0; - } - utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", - zArg); - return 0; -} - -/* -** Set or clear a shell flag according to a boolean value. -*/ -static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ - if( booleanValue(zArg) ){ - ShellSetFlag(p, mFlag); - }else{ - ShellClearFlag(p, mFlag); - } -} - -/* -** Close an output file, assuming it is not stderr or stdout -*/ -static void output_file_close(FILE *f){ - if( f && f!=stdout && f!=stderr ) fclose(f); -} - -/* -** Try to open an output file. The names "stdout" and "stderr" are -** recognized and do the right thing. NULL is returned if the output -** filename is "off". -*/ -static FILE *output_file_open(const char *zFile, int bTextMode){ - FILE *f; - if( strcmp(zFile,"stdout")==0 ){ - f = stdout; - }else if( strcmp(zFile, "stderr")==0 ){ - f = stderr; - }else if( strcmp(zFile, "off")==0 ){ - f = 0; - }else{ - f = fopen(zFile, bTextMode ? "w" : "wb"); - if( f==0 ){ - utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); - } - } - return f; -} - -#ifndef SQLITE_OMIT_TRACE -/* -** A routine for handling output from sqlite3_trace(). -*/ -static int sql_trace_callback( - unsigned mType, /* The trace type */ - void *pArg, /* The ShellState pointer */ - void *pP, /* Usually a pointer to sqlite_stmt */ - void *pX /* Auxiliary output */ -){ - ShellState *p = (ShellState*)pArg; - sqlite3_stmt *pStmt; - const char *zSql; - int nSql; - if( p->traceOut==0 ) return 0; - if( mType==SQLITE_TRACE_CLOSE ){ - utf8_printf(p->traceOut, "-- closing database connection\n"); - return 0; - } - if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ - zSql = (const char*)pX; - }else{ - pStmt = (sqlite3_stmt*)pP; - switch( p->eTraceType ){ - case SHELL_TRACE_EXPANDED: { - zSql = sqlite3_expanded_sql(pStmt); - break; - } -#ifdef SQLITE_ENABLE_NORMALIZE - case SHELL_TRACE_NORMALIZED: { - zSql = sqlite3_normalized_sql(pStmt); - break; - } -#endif - default: { - zSql = sqlite3_sql(pStmt); - break; - } - } - } - if( zSql==0 ) return 0; - nSql = strlen30(zSql); - while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } - switch( mType ){ - case SQLITE_TRACE_ROW: - case SQLITE_TRACE_STMT: { - utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); - break; - } - case SQLITE_TRACE_PROFILE: { - sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; - utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); - break; - } - } - return 0; -} -#endif - -/* -** A no-op routine that runs with the ".breakpoint" doc-command. This is -** a useful spot to set a debugger breakpoint. -*/ -static void test_breakpoint(void){ - static int nCall = 0; - nCall++; -} - -/* -** An object used to read a CSV and other files for import. -*/ -typedef struct ImportCtx ImportCtx; -struct ImportCtx { - const char *zFile; /* Name of the input file */ - FILE *in; /* Read the CSV text from this input stream */ - int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */ - char *z; /* Accumulated text for a field */ - int n; /* Number of bytes in z */ - int nAlloc; /* Space allocated for z[] */ - int nLine; /* Current line number */ - int nRow; /* Number of rows imported */ - int nErr; /* Number of errors encountered */ - int bNotFirst; /* True if one or more bytes already read */ - int cTerm; /* Character that terminated the most recent field */ - int cColSep; /* The column separator character. (Usually ",") */ - int cRowSep; /* The row separator character. (Usually "\n") */ -}; - -/* Clean up resourced used by an ImportCtx */ -static void import_cleanup(ImportCtx *p){ - if( p->in!=0 && p->xCloser!=0 ){ - p->xCloser(p->in); - p->in = 0; - } - sqlite3_free(p->z); - p->z = 0; -} - -/* Append a single byte to z[] */ -static void import_append_char(ImportCtx *p, int c){ - if( p->n+1>=p->nAlloc ){ - p->nAlloc += p->nAlloc + 100; - p->z = sqlite3_realloc64(p->z, p->nAlloc); - if( p->z==0 ) shell_out_of_memory(); - } - p->z[p->n++] = (char)c; -} - -/* Read a single field of CSV text. Compatible with rfc4180 and extended -** with the option of having a separator other than ",". -** -** + Input comes from p->in. -** + Store results in p->z of length p->n. Space to hold p->z comes -** from sqlite3_malloc64(). -** + Use p->cSep as the column separator. The default is ",". -** + Use p->rSep as the row separator. The default is "\n". -** + Keep track of the line number in p->nLine. -** + Store the character that terminates the field in p->cTerm. Store -** EOF on end-of-file. -** + Report syntax errors on stderr -*/ -static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ - int c; - int cSep = p->cColSep; - int rSep = p->cRowSep; - p->n = 0; - c = fgetc(p->in); - if( c==EOF || seenInterrupt ){ - p->cTerm = EOF; - return 0; - } - if( c=='"' ){ - int pc, ppc; - int startLine = p->nLine; - int cQuote = c; - pc = ppc = 0; - while( 1 ){ - c = fgetc(p->in); - if( c==rSep ) p->nLine++; - if( c==cQuote ){ - if( pc==cQuote ){ - pc = 0; - continue; - } - } - if( (c==cSep && pc==cQuote) - || (c==rSep && pc==cQuote) - || (c==rSep && pc=='\r' && ppc==cQuote) - || (c==EOF && pc==cQuote) - ){ - do{ p->n--; }while( p->z[p->n]!=cQuote ); - p->cTerm = c; - break; - } - if( pc==cQuote && c!='\r' ){ - utf8_printf(stderr, "%s:%d: unescaped %c character\n", - p->zFile, p->nLine, cQuote); - } - if( c==EOF ){ - utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", - p->zFile, startLine, cQuote); - p->cTerm = c; - break; - } - import_append_char(p, c); - ppc = pc; - pc = c; - } - }else{ - /* If this is the first field being parsed and it begins with the - ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ - if( (c&0xff)==0xef && p->bNotFirst==0 ){ - import_append_char(p, c); - c = fgetc(p->in); - if( (c&0xff)==0xbb ){ - import_append_char(p, c); - c = fgetc(p->in); - if( (c&0xff)==0xbf ){ - p->bNotFirst = 1; - p->n = 0; - return csv_read_one_field(p); - } - } - } - while( c!=EOF && c!=cSep && c!=rSep ){ - import_append_char(p, c); - c = fgetc(p->in); - } - if( c==rSep ){ - p->nLine++; - if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; - } - p->cTerm = c; - } - if( p->z ) p->z[p->n] = 0; - p->bNotFirst = 1; - return p->z; -} - -/* Read a single field of ASCII delimited text. -** -** + Input comes from p->in. -** + Store results in p->z of length p->n. Space to hold p->z comes -** from sqlite3_malloc64(). -** + Use p->cSep as the column separator. The default is "\x1F". -** + Use p->rSep as the row separator. The default is "\x1E". -** + Keep track of the row number in p->nLine. -** + Store the character that terminates the field in p->cTerm. Store -** EOF on end-of-file. -** + Report syntax errors on stderr -*/ -static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ - int c; - int cSep = p->cColSep; - int rSep = p->cRowSep; - p->n = 0; - c = fgetc(p->in); - if( c==EOF || seenInterrupt ){ - p->cTerm = EOF; - return 0; - } - while( c!=EOF && c!=cSep && c!=rSep ){ - import_append_char(p, c); - c = fgetc(p->in); - } - if( c==rSep ){ - p->nLine++; - } - p->cTerm = c; - if( p->z ) p->z[p->n] = 0; - return p->z; -} - -/* -** Try to transfer data for table zTable. If an error is seen while -** moving forward, try to go backwards. The backwards movement won't -** work for WITHOUT ROWID tables. -*/ -static void tryToCloneData( - ShellState *p, - sqlite3 *newDb, - const char *zTable -){ - sqlite3_stmt *pQuery = 0; - sqlite3_stmt *pInsert = 0; - char *zQuery = 0; - char *zInsert = 0; - int rc; - int i, j, n; - int nTable = strlen30(zTable); - int k = 0; - int cnt = 0; - const int spinRate = 10000; - - zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); - rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); - if( rc ){ - utf8_printf(stderr, "Error %d: %s on [%s]\n", - sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), - zQuery); - goto end_data_xfer; - } - n = sqlite3_column_count(pQuery); - zInsert = sqlite3_malloc64(200 + nTable + n*3); - if( zInsert==0 ) shell_out_of_memory(); - sqlite3_snprintf(200+nTable,zInsert, - "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); - i = strlen30(zInsert); - for(j=1; jdb, zQuery, -1, &pQuery, 0); - if( rc ){ - utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); - break; - } - } /* End for(k=0...) */ - -end_data_xfer: - sqlite3_finalize(pQuery); - sqlite3_finalize(pInsert); - sqlite3_free(zQuery); - sqlite3_free(zInsert); -} - - -/* -** Try to transfer all rows of the schema that match zWhere. For -** each row, invoke xForEach() on the object defined by that row. -** If an error is encountered while moving forward through the -** sqlite_schema table, try again moving backwards. -*/ -static void tryToCloneSchema( - ShellState *p, - sqlite3 *newDb, - const char *zWhere, - void (*xForEach)(ShellState*,sqlite3*,const char*) -){ - sqlite3_stmt *pQuery = 0; - char *zQuery = 0; - int rc; - const unsigned char *zName; - const unsigned char *zSql; - char *zErrMsg = 0; - - zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" - " WHERE %s", zWhere); - rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); - if( rc ){ - utf8_printf(stderr, "Error: (%d) %s on [%s]\n", - sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), - zQuery); - goto end_schema_xfer; - } - while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ - zName = sqlite3_column_text(pQuery, 0); - zSql = sqlite3_column_text(pQuery, 1); - printf("%s... ", zName); fflush(stdout); - sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); - if( zErrMsg ){ - utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); - sqlite3_free(zErrMsg); - zErrMsg = 0; - } - if( xForEach ){ - xForEach(p, newDb, (const char*)zName); - } - printf("done\n"); - } - if( rc!=SQLITE_DONE ){ - sqlite3_finalize(pQuery); - sqlite3_free(zQuery); - zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" - " WHERE %s ORDER BY rowid DESC", zWhere); - rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); - if( rc ){ - utf8_printf(stderr, "Error: (%d) %s on [%s]\n", - sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), - zQuery); - goto end_schema_xfer; - } - while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ - zName = sqlite3_column_text(pQuery, 0); - zSql = sqlite3_column_text(pQuery, 1); - printf("%s... ", zName); fflush(stdout); - sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); - if( zErrMsg ){ - utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); - sqlite3_free(zErrMsg); - zErrMsg = 0; - } - if( xForEach ){ - xForEach(p, newDb, (const char*)zName); - } - printf("done\n"); - } - } -end_schema_xfer: - sqlite3_finalize(pQuery); - sqlite3_free(zQuery); -} - -/* -** Open a new database file named "zNewDb". Try to recover as much information -** as possible out of the main database (which might be corrupt) and write it -** into zNewDb. -*/ -static void tryToClone(ShellState *p, const char *zNewDb){ - int rc; - sqlite3 *newDb = 0; - if( access(zNewDb,0)==0 ){ - utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); - return; - } - rc = sqlite3_open(zNewDb, &newDb); - if( rc ){ - utf8_printf(stderr, "Cannot create output database: %s\n", - sqlite3_errmsg(newDb)); - }else{ - sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); - sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); - tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); - tryToCloneSchema(p, newDb, "type!='table'", 0); - sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); - sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); - } - close_db(newDb); -} - -/* -** Change the output file back to stdout. -** -** If the p->doXdgOpen flag is set, that means the output was being -** redirected to a temporary file named by p->zTempFile. In that case, -** launch start/open/xdg-open on that temporary file. -*/ -static void output_reset(ShellState *p){ - if( p->outfile[0]=='|' ){ -#ifndef SQLITE_OMIT_POPEN - pclose(p->out); -#endif - }else{ - output_file_close(p->out); -#ifndef SQLITE_NOHAVE_SYSTEM - if( p->doXdgOpen ){ - const char *zXdgOpenCmd = -#if defined(_WIN32) - "start"; -#elif defined(__APPLE__) - "open"; -#else - "xdg-open"; -#endif - char *zCmd; - zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); - if( system(zCmd) ){ - utf8_printf(stderr, "Failed: [%s]\n", zCmd); - }else{ - /* Give the start/open/xdg-open command some time to get - ** going before we continue, and potential delete the - ** p->zTempFile data file out from under it */ - sqlite3_sleep(2000); - } - sqlite3_free(zCmd); - outputModePop(p); - p->doXdgOpen = 0; - } -#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ - } - p->outfile[0] = 0; - p->out = stdout; -} - -/* -** Run an SQL command and return the single integer result. -*/ -static int db_int(ShellState *p, const char *zSql){ - sqlite3_stmt *pStmt; - int res = 0; - sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ - res = sqlite3_column_int(pStmt,0); - } - sqlite3_finalize(pStmt); - return res; -} - -/* -** Convert a 2-byte or 4-byte big-endian integer into a native integer -*/ -static unsigned int get2byteInt(unsigned char *a){ - return (a[0]<<8) + a[1]; -} -static unsigned int get4byteInt(unsigned char *a){ - return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; -} - -/* -** Implementation of the ".dbinfo" command. -** -** Return 1 on error, 2 to exit, and 0 otherwise. -*/ -static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ - static const struct { const char *zName; int ofst; } aField[] = { - { "file change counter:", 24 }, - { "database page count:", 28 }, - { "freelist page count:", 36 }, - { "schema cookie:", 40 }, - { "schema format:", 44 }, - { "default cache size:", 48 }, - { "autovacuum top root:", 52 }, - { "incremental vacuum:", 64 }, - { "text encoding:", 56 }, - { "user version:", 60 }, - { "application id:", 68 }, - { "software version:", 96 }, - }; - static const struct { const char *zName; const char *zSql; } aQuery[] = { - { "number of tables:", - "SELECT count(*) FROM %s WHERE type='table'" }, - { "number of indexes:", - "SELECT count(*) FROM %s WHERE type='index'" }, - { "number of triggers:", - "SELECT count(*) FROM %s WHERE type='trigger'" }, - { "number of views:", - "SELECT count(*) FROM %s WHERE type='view'" }, - { "schema size:", - "SELECT total(length(sql)) FROM %s" }, - }; - int i, rc; - unsigned iDataVersion; - char *zSchemaTab; - char *zDb = nArg>=2 ? azArg[1] : "main"; - sqlite3_stmt *pStmt = 0; - unsigned char aHdr[100]; - open_db(p, 0); - if( p->db==0 ) return 1; - rc = sqlite3_prepare_v2(p->db, - "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", - -1, &pStmt, 0); - if( rc ){ - utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); - sqlite3_finalize(pStmt); - return 1; - } - sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); - if( sqlite3_step(pStmt)==SQLITE_ROW - && sqlite3_column_bytes(pStmt,0)>100 - ){ - memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); - sqlite3_finalize(pStmt); - }else{ - raw_printf(stderr, "unable to read database header\n"); - sqlite3_finalize(pStmt); - return 1; - } - i = get2byteInt(aHdr+16); - if( i==1 ) i = 65536; - utf8_printf(p->out, "%-20s %d\n", "database page size:", i); - utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); - utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); - utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); - for(i=0; iout, "%-20s %u", aField[i].zName, val); - switch( ofst ){ - case 56: { - if( val==1 ) raw_printf(p->out, " (utf8)"); - if( val==2 ) raw_printf(p->out, " (utf16le)"); - if( val==3 ) raw_printf(p->out, " (utf16be)"); - } - } - raw_printf(p->out, "\n"); - } - if( zDb==0 ){ - zSchemaTab = sqlite3_mprintf("main.sqlite_schema"); - }else if( strcmp(zDb,"temp")==0 ){ - zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema"); - }else{ - zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb); - } - for(i=0; iout, "%-20s %d\n", aQuery[i].zName, val); - } - sqlite3_free(zSchemaTab); - sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); - utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); - return 0; -} - -/* -** Print the current sqlite3_errmsg() value to stderr and return 1. -*/ -static int shellDatabaseError(sqlite3 *db){ - const char *zErr = sqlite3_errmsg(db); - utf8_printf(stderr, "Error: %s\n", zErr); - return 1; -} - -/* -** Compare the pattern in zGlob[] against the text in z[]. Return TRUE -** if they match and FALSE (0) if they do not match. -** -** Globbing rules: -** -** '*' Matches any sequence of zero or more characters. -** -** '?' Matches exactly one character. -** -** [...] Matches one character from the enclosed list of -** characters. -** -** [^...] Matches one character not in the enclosed list. -** -** '#' Matches any sequence of one or more digits with an -** optional + or - sign in front -** -** ' ' Any span of whitespace matches any other span of -** whitespace. -** -** Extra whitespace at the end of z[] is ignored. -*/ -static int testcase_glob(const char *zGlob, const char *z){ - int c, c2; - int invert; - int seen; - - while( (c = (*(zGlob++)))!=0 ){ - if( IsSpace(c) ){ - if( !IsSpace(*z) ) return 0; - while( IsSpace(*zGlob) ) zGlob++; - while( IsSpace(*z) ) z++; - }else if( c=='*' ){ - while( (c=(*(zGlob++))) == '*' || c=='?' ){ - if( c=='?' && (*(z++))==0 ) return 0; - } - if( c==0 ){ - return 1; - }else if( c=='[' ){ - while( *z && testcase_glob(zGlob-1,z)==0 ){ - z++; - } - return (*z)!=0; - } - while( (c2 = (*(z++)))!=0 ){ - while( c2!=c ){ - c2 = *(z++); - if( c2==0 ) return 0; - } - if( testcase_glob(zGlob,z) ) return 1; - } - return 0; - }else if( c=='?' ){ - if( (*(z++))==0 ) return 0; - }else if( c=='[' ){ - int prior_c = 0; - seen = 0; - invert = 0; - c = *(z++); - if( c==0 ) return 0; - c2 = *(zGlob++); - if( c2=='^' ){ - invert = 1; - c2 = *(zGlob++); - } - if( c2==']' ){ - if( c==']' ) seen = 1; - c2 = *(zGlob++); - } - while( c2 && c2!=']' ){ - if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ - c2 = *(zGlob++); - if( c>=prior_c && c<=c2 ) seen = 1; - prior_c = 0; - }else{ - if( c==c2 ){ - seen = 1; - } - prior_c = c2; - } - c2 = *(zGlob++); - } - if( c2==0 || (seen ^ invert)==0 ) return 0; - }else if( c=='#' ){ - if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; - if( !IsDigit(z[0]) ) return 0; - z++; - while( IsDigit(z[0]) ){ z++; } - }else{ - if( c!=(*(z++)) ) return 0; - } - } - while( IsSpace(*z) ){ z++; } - return *z==0; -} - - -/* -** Compare the string as a command-line option with either one or two -** initial "-" characters. -*/ -static int optionMatch(const char *zStr, const char *zOpt){ - if( zStr[0]!='-' ) return 0; - zStr++; - if( zStr[0]=='-' ) zStr++; - return strcmp(zStr, zOpt)==0; -} - -/* -** Delete a file. -*/ -int shellDeleteFile(const char *zFilename){ - int rc; -#ifdef _WIN32 - wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); - rc = _wunlink(z); - sqlite3_free(z); -#else - rc = unlink(zFilename); -#endif - return rc; -} - -/* -** Try to delete the temporary file (if there is one) and free the -** memory used to hold the name of the temp file. -*/ -static void clearTempFile(ShellState *p){ - if( p->zTempFile==0 ) return; - if( p->doXdgOpen ) return; - if( shellDeleteFile(p->zTempFile) ) return; - sqlite3_free(p->zTempFile); - p->zTempFile = 0; -} - -/* -** Create a new temp file name with the given suffix. -*/ -static void newTempFile(ShellState *p, const char *zSuffix){ - clearTempFile(p); - sqlite3_free(p->zTempFile); - p->zTempFile = 0; - if( p->db ){ - sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); - } - if( p->zTempFile==0 ){ - /* If p->db is an in-memory database then the TEMPFILENAME file-control - ** will not work and we will need to fallback to guessing */ - char *zTemp; - sqlite3_uint64 r; - sqlite3_randomness(sizeof(r), &r); - zTemp = getenv("TEMP"); - if( zTemp==0 ) zTemp = getenv("TMP"); - if( zTemp==0 ){ -#ifdef _WIN32 - zTemp = "\\tmp"; -#else - zTemp = "/tmp"; -#endif - } - p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); - }else{ - p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); - } - if( p->zTempFile==0 ){ - raw_printf(stderr, "out of memory\n"); - exit(1); - } -} - - -/* -** The implementation of SQL scalar function fkey_collate_clause(), used -** by the ".lint fkey-indexes" command. This scalar function is always -** called with four arguments - the parent table name, the parent column name, -** the child table name and the child column name. -** -** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') -** -** If either of the named tables or columns do not exist, this function -** returns an empty string. An empty string is also returned if both tables -** and columns exist but have the same default collation sequence. Or, -** if both exist but the default collation sequences are different, this -** function returns the string " COLLATE ", where -** is the default collation sequence of the parent column. -*/ -static void shellFkeyCollateClause( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - sqlite3 *db = sqlite3_context_db_handle(pCtx); - const char *zParent; - const char *zParentCol; - const char *zParentSeq; - const char *zChild; - const char *zChildCol; - const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ - int rc; - - assert( nVal==4 ); - zParent = (const char*)sqlite3_value_text(apVal[0]); - zParentCol = (const char*)sqlite3_value_text(apVal[1]); - zChild = (const char*)sqlite3_value_text(apVal[2]); - zChildCol = (const char*)sqlite3_value_text(apVal[3]); - - sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); - rc = sqlite3_table_column_metadata( - db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 - ); - if( rc==SQLITE_OK ){ - rc = sqlite3_table_column_metadata( - db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 - ); - } - - if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ - char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); - sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); - sqlite3_free(z); - } -} - - -/* -** The implementation of dot-command ".lint fkey-indexes". -*/ -static int lintFkeyIndexes( - ShellState *pState, /* Current shell tool state */ - char **azArg, /* Array of arguments passed to dot command */ - int nArg /* Number of entries in azArg[] */ -){ - sqlite3 *db = pState->db; /* Database handle to query "main" db of */ - FILE *out = pState->out; /* Stream to write non-error output to */ - int bVerbose = 0; /* If -verbose is present */ - int bGroupByParent = 0; /* If -groupbyparent is present */ - int i; /* To iterate through azArg[] */ - const char *zIndent = ""; /* How much to indent CREATE INDEX by */ - int rc; /* Return code */ - sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ - - /* - ** This SELECT statement returns one row for each foreign key constraint - ** in the schema of the main database. The column values are: - ** - ** 0. The text of an SQL statement similar to: - ** - ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" - ** - ** This SELECT is similar to the one that the foreign keys implementation - ** needs to run internally on child tables. If there is an index that can - ** be used to optimize this query, then it can also be used by the FK - ** implementation to optimize DELETE or UPDATE statements on the parent - ** table. - ** - ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by - ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema - ** contains an index that can be used to optimize the query. - ** - ** 2. Human readable text that describes the child table and columns. e.g. - ** - ** "child_table(child_key1, child_key2)" - ** - ** 3. Human readable text that describes the parent table and columns. e.g. - ** - ** "parent_table(parent_key1, parent_key2)" - ** - ** 4. A full CREATE INDEX statement for an index that could be used to - ** optimize DELETE or UPDATE statements on the parent table. e.g. - ** - ** "CREATE INDEX child_table_child_key ON child_table(child_key)" - ** - ** 5. The name of the parent table. - ** - ** These six values are used by the C logic below to generate the report. - */ - const char *zSql = - "SELECT " - " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" - " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " - " || fkey_collate_clause(" - " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" - ", " - " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('" - " || group_concat('*=?', ' AND ') || ')'" - ", " - " s.name || '(' || group_concat(f.[from], ', ') || ')'" - ", " - " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" - ", " - " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" - " || ' ON ' || quote(s.name) || '('" - " || group_concat(quote(f.[from]) ||" - " fkey_collate_clause(" - " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" - " || ');'" - ", " - " f.[table] " - "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f " - "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " - "GROUP BY s.name, f.id " - "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" - ; - const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)"; - - for(i=2; i1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ - bVerbose = 1; - } - else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ - bGroupByParent = 1; - zIndent = " "; - } - else{ - raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", - azArg[0], azArg[1] - ); - return SQLITE_ERROR; - } - } - - /* Register the fkey_collate_clause() SQL function */ - rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, - 0, shellFkeyCollateClause, 0, 0 - ); - - - if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); - } - if( rc==SQLITE_OK ){ - sqlite3_bind_int(pSql, 1, bGroupByParent); - } - - if( rc==SQLITE_OK ){ - int rc2; - char *zPrev = 0; - while( SQLITE_ROW==sqlite3_step(pSql) ){ - int res = -1; - sqlite3_stmt *pExplain = 0; - const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); - const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); - const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); - const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); - const char *zCI = (const char*)sqlite3_column_text(pSql, 4); - const char *zParent = (const char*)sqlite3_column_text(pSql, 5); - - rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); - if( rc!=SQLITE_OK ) break; - if( SQLITE_ROW==sqlite3_step(pExplain) ){ - const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); - res = ( - 0==sqlite3_strglob(zGlob, zPlan) - || 0==sqlite3_strglob(zGlobIPK, zPlan) - ); - } - rc = sqlite3_finalize(pExplain); - if( rc!=SQLITE_OK ) break; - - if( res<0 ){ - raw_printf(stderr, "Error: internal error"); - break; - }else{ - if( bGroupByParent - && (bVerbose || res==0) - && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) - ){ - raw_printf(out, "-- Parent table %s\n", zParent); - sqlite3_free(zPrev); - zPrev = sqlite3_mprintf("%s", zParent); - } - - if( res==0 ){ - raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); - }else if( bVerbose ){ - raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", - zIndent, zFrom, zTarget - ); - } - } - } - sqlite3_free(zPrev); - - if( rc!=SQLITE_OK ){ - raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); - } - - rc2 = sqlite3_finalize(pSql); - if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ - rc = rc2; - raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); - } - }else{ - raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); - } - - return rc; -} - -/* -** Implementation of ".lint" dot command. -*/ -static int lintDotCommand( - ShellState *pState, /* Current shell tool state */ - char **azArg, /* Array of arguments passed to dot command */ - int nArg /* Number of entries in azArg[] */ -){ - int n; - n = (nArg>=2 ? strlen30(azArg[1]) : 0); - if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; - return lintFkeyIndexes(pState, azArg, nArg); - - usage: - raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); - raw_printf(stderr, "Where sub-commands are:\n"); - raw_printf(stderr, " fkey-indexes\n"); - return SQLITE_ERROR; -} - -#if !defined SQLITE_OMIT_VIRTUALTABLE -static void shellPrepare( - sqlite3 *db, - int *pRc, - const char *zSql, - sqlite3_stmt **ppStmt -){ - *ppStmt = 0; - if( *pRc==SQLITE_OK ){ - int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); - if( rc!=SQLITE_OK ){ - raw_printf(stderr, "sql error: %s (%d)\n", - sqlite3_errmsg(db), sqlite3_errcode(db) - ); - *pRc = rc; - } - } -} - -/* -** Create a prepared statement using printf-style arguments for the SQL. -** -** This routine is could be marked "static". But it is not always used, -** depending on compile-time options. By omitting the "static", we avoid -** nuisance compiler warnings about "defined but not used". -*/ -void shellPreparePrintf( - sqlite3 *db, - int *pRc, - sqlite3_stmt **ppStmt, - const char *zFmt, - ... -){ - *ppStmt = 0; - if( *pRc==SQLITE_OK ){ - va_list ap; - char *z; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - if( z==0 ){ - *pRc = SQLITE_NOMEM; - }else{ - shellPrepare(db, pRc, z, ppStmt); - sqlite3_free(z); - } - } -} - -/* Finalize the prepared statement created using shellPreparePrintf(). -** -** This routine is could be marked "static". But it is not always used, -** depending on compile-time options. By omitting the "static", we avoid -** nuisance compiler warnings about "defined but not used". -*/ -void shellFinalize( - int *pRc, - sqlite3_stmt *pStmt -){ - if( pStmt ){ - sqlite3 *db = sqlite3_db_handle(pStmt); - int rc = sqlite3_finalize(pStmt); - if( *pRc==SQLITE_OK ){ - if( rc!=SQLITE_OK ){ - raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); - } - *pRc = rc; - } - } -} - -/* Reset the prepared statement created using shellPreparePrintf(). -** -** This routine is could be marked "static". But it is not always used, -** depending on compile-time options. By omitting the "static", we avoid -** nuisance compiler warnings about "defined but not used". -*/ -void shellReset( - int *pRc, - sqlite3_stmt *pStmt -){ - int rc = sqlite3_reset(pStmt); - if( *pRc==SQLITE_OK ){ - if( rc!=SQLITE_OK ){ - sqlite3 *db = sqlite3_db_handle(pStmt); - raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); - } - *pRc = rc; - } -} -#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) -/****************************************************************************** -** The ".archive" or ".ar" command. -*/ -/* -** Structure representing a single ".ar" command. -*/ -typedef struct ArCommand ArCommand; -struct ArCommand { - u8 eCmd; /* An AR_CMD_* value */ - u8 bVerbose; /* True if --verbose */ - u8 bZip; /* True if the archive is a ZIP */ - u8 bDryRun; /* True if --dry-run */ - u8 bAppend; /* True if --append */ - u8 fromCmdLine; /* Run from -A instead of .archive */ - int nArg; /* Number of command arguments */ - char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ - const char *zFile; /* --file argument, or NULL */ - const char *zDir; /* --directory argument, or NULL */ - char **azArg; /* Array of command arguments */ - ShellState *p; /* Shell state */ - sqlite3 *db; /* Database containing the archive */ -}; - -/* -** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. -*/ -static int arUsage(FILE *f){ - showHelp(f,"archive"); - return SQLITE_ERROR; -} - -/* -** Print an error message for the .ar command to stderr and return -** SQLITE_ERROR. -*/ -static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ - va_list ap; - char *z; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - utf8_printf(stderr, "Error: %s\n", z); - if( pAr->fromCmdLine ){ - utf8_printf(stderr, "Use \"-A\" for more help\n"); - }else{ - utf8_printf(stderr, "Use \".archive --help\" for more help\n"); - } - sqlite3_free(z); - return SQLITE_ERROR; -} - -/* -** Values for ArCommand.eCmd. -*/ -#define AR_CMD_CREATE 1 -#define AR_CMD_UPDATE 2 -#define AR_CMD_INSERT 3 -#define AR_CMD_EXTRACT 4 -#define AR_CMD_LIST 5 -#define AR_CMD_HELP 6 - -/* -** Other (non-command) switches. -*/ -#define AR_SWITCH_VERBOSE 7 -#define AR_SWITCH_FILE 8 -#define AR_SWITCH_DIRECTORY 9 -#define AR_SWITCH_APPEND 10 -#define AR_SWITCH_DRYRUN 11 - -static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ - switch( eSwitch ){ - case AR_CMD_CREATE: - case AR_CMD_EXTRACT: - case AR_CMD_LIST: - case AR_CMD_UPDATE: - case AR_CMD_INSERT: - case AR_CMD_HELP: - if( pAr->eCmd ){ - return arErrorMsg(pAr, "multiple command options"); - } - pAr->eCmd = eSwitch; - break; - - case AR_SWITCH_DRYRUN: - pAr->bDryRun = 1; - break; - case AR_SWITCH_VERBOSE: - pAr->bVerbose = 1; - break; - case AR_SWITCH_APPEND: - pAr->bAppend = 1; - /* Fall thru into --file */ - case AR_SWITCH_FILE: - pAr->zFile = zArg; - break; - case AR_SWITCH_DIRECTORY: - pAr->zDir = zArg; - break; - } - - return SQLITE_OK; -} - -/* -** Parse the command line for an ".ar" command. The results are written into -** structure (*pAr). SQLITE_OK is returned if the command line is parsed -** successfully, otherwise an error message is written to stderr and -** SQLITE_ERROR returned. -*/ -static int arParseCommand( - char **azArg, /* Array of arguments passed to dot command */ - int nArg, /* Number of entries in azArg[] */ - ArCommand *pAr /* Populate this object */ -){ - struct ArSwitch { - const char *zLong; - char cShort; - u8 eSwitch; - u8 bArg; - } aSwitch[] = { - { "create", 'c', AR_CMD_CREATE, 0 }, - { "extract", 'x', AR_CMD_EXTRACT, 0 }, - { "insert", 'i', AR_CMD_INSERT, 0 }, - { "list", 't', AR_CMD_LIST, 0 }, - { "update", 'u', AR_CMD_UPDATE, 0 }, - { "help", 'h', AR_CMD_HELP, 0 }, - { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, - { "file", 'f', AR_SWITCH_FILE, 1 }, - { "append", 'a', AR_SWITCH_APPEND, 1 }, - { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, - { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, - }; - int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); - struct ArSwitch *pEnd = &aSwitch[nSwitch]; - - if( nArg<=1 ){ - utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); - return arUsage(stderr); - }else{ - char *z = azArg[1]; - if( z[0]!='-' ){ - /* Traditional style [tar] invocation */ - int i; - int iArg = 2; - for(i=0; z[i]; i++){ - const char *zArg = 0; - struct ArSwitch *pOpt; - for(pOpt=&aSwitch[0]; pOptcShort ) break; - } - if( pOpt==pEnd ){ - return arErrorMsg(pAr, "unrecognized option: %c", z[i]); - } - if( pOpt->bArg ){ - if( iArg>=nArg ){ - return arErrorMsg(pAr, "option requires an argument: %c",z[i]); - } - zArg = azArg[iArg++]; - } - if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; - } - pAr->nArg = nArg-iArg; - if( pAr->nArg>0 ){ - pAr->azArg = &azArg[iArg]; - } - }else{ - /* Non-traditional invocation */ - int iArg; - for(iArg=1; iArgazArg = &azArg[iArg]; - pAr->nArg = nArg-iArg; - break; - } - n = strlen30(z); - - if( z[1]!='-' ){ - int i; - /* One or more short options */ - for(i=1; icShort ) break; - } - if( pOpt==pEnd ){ - return arErrorMsg(pAr, "unrecognized option: %c", z[i]); - } - if( pOpt->bArg ){ - if( i<(n-1) ){ - zArg = &z[i+1]; - i = n; - }else{ - if( iArg>=(nArg-1) ){ - return arErrorMsg(pAr, "option requires an argument: %c", - z[i]); - } - zArg = azArg[++iArg]; - } - } - if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; - } - }else if( z[2]=='\0' ){ - /* A -- option, indicating that all remaining command line words - ** are command arguments. */ - pAr->azArg = &azArg[iArg+1]; - pAr->nArg = nArg-iArg-1; - break; - }else{ - /* A long option */ - const char *zArg = 0; /* Argument for option, if any */ - struct ArSwitch *pMatch = 0; /* Matching option */ - struct ArSwitch *pOpt; /* Iterator */ - for(pOpt=&aSwitch[0]; pOptzLong; - if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ - if( pMatch ){ - return arErrorMsg(pAr, "ambiguous option: %s",z); - }else{ - pMatch = pOpt; - } - } - } - - if( pMatch==0 ){ - return arErrorMsg(pAr, "unrecognized option: %s", z); - } - if( pMatch->bArg ){ - if( iArg>=(nArg-1) ){ - return arErrorMsg(pAr, "option requires an argument: %s", z); - } - zArg = azArg[++iArg]; - } - if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; - } - } - } - } - - return SQLITE_OK; -} - -/* -** This function assumes that all arguments within the ArCommand.azArg[] -** array refer to archive members, as for the --extract or --list commands. -** It checks that each of them are present. If any specified file is not -** present in the archive, an error is printed to stderr and an error -** code returned. Otherwise, if all specified arguments are present in -** the archive, SQLITE_OK is returned. -** -** This function strips any trailing '/' characters from each argument. -** This is consistent with the way the [tar] command seems to work on -** Linux. -*/ -static int arCheckEntries(ArCommand *pAr){ - int rc = SQLITE_OK; - if( pAr->nArg ){ - int i, j; - sqlite3_stmt *pTest = 0; - - shellPreparePrintf(pAr->db, &rc, &pTest, - "SELECT name FROM %s WHERE name=$name", - pAr->zSrcTable - ); - j = sqlite3_bind_parameter_index(pTest, "$name"); - for(i=0; inArg && rc==SQLITE_OK; i++){ - char *z = pAr->azArg[i]; - int n = strlen30(z); - int bOk = 0; - while( n>0 && z[n-1]=='/' ) n--; - z[n] = '\0'; - sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pTest) ){ - bOk = 1; - } - shellReset(&rc, pTest); - if( rc==SQLITE_OK && bOk==0 ){ - utf8_printf(stderr, "not found in archive: %s\n", z); - rc = SQLITE_ERROR; - } - } - shellFinalize(&rc, pTest); - } - return rc; -} - -/* -** Format a WHERE clause that can be used against the "sqlar" table to -** identify all archive members that match the command arguments held -** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. -** The caller is responsible for eventually calling sqlite3_free() on -** any non-NULL (*pzWhere) value. -*/ -static void arWhereClause( - int *pRc, - ArCommand *pAr, - char **pzWhere /* OUT: New WHERE clause */ -){ - char *zWhere = 0; - if( *pRc==SQLITE_OK ){ - if( pAr->nArg==0 ){ - zWhere = sqlite3_mprintf("1"); - }else{ - int i; - const char *zSep = ""; - for(i=0; inArg; i++){ - const char *z = pAr->azArg[i]; - zWhere = sqlite3_mprintf( - "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", - zWhere, zSep, z, strlen30(z)+1, z - ); - if( zWhere==0 ){ - *pRc = SQLITE_NOMEM; - break; - } - zSep = " OR "; - } - } - } - *pzWhere = zWhere; -} - -/* -** Implementation of .ar "lisT" command. -*/ -static int arListCommand(ArCommand *pAr){ - const char *zSql = "SELECT %s FROM %s WHERE %s"; - const char *azCols[] = { - "name", - "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" - }; - - char *zWhere = 0; - sqlite3_stmt *pSql = 0; - int rc; - - rc = arCheckEntries(pAr); - arWhereClause(&rc, pAr, &zWhere); - - shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], - pAr->zSrcTable, zWhere); - if( pAr->bDryRun ){ - utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); - }else{ - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ - if( pAr->bVerbose ){ - utf8_printf(pAr->p->out, "%s % 10d %s %s\n", - sqlite3_column_text(pSql, 0), - sqlite3_column_int(pSql, 1), - sqlite3_column_text(pSql, 2), - sqlite3_column_text(pSql, 3) - ); - }else{ - utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); - } - } - } - shellFinalize(&rc, pSql); - sqlite3_free(zWhere); - return rc; -} - - -/* -** Implementation of .ar "eXtract" command. -*/ -static int arExtractCommand(ArCommand *pAr){ - const char *zSql1 = - "SELECT " - " ($dir || name)," - " writefile(($dir || name), %s, mode, mtime) " - "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" - " AND name NOT GLOB '*..[/\\]*'"; - - const char *azExtraArg[] = { - "sqlar_uncompress(data, sz)", - "data" - }; - - sqlite3_stmt *pSql = 0; - int rc = SQLITE_OK; - char *zDir = 0; - char *zWhere = 0; - int i, j; - - /* If arguments are specified, check that they actually exist within - ** the archive before proceeding. And formulate a WHERE clause to - ** match them. */ - rc = arCheckEntries(pAr); - arWhereClause(&rc, pAr, &zWhere); - - if( rc==SQLITE_OK ){ - if( pAr->zDir ){ - zDir = sqlite3_mprintf("%s/", pAr->zDir); - }else{ - zDir = sqlite3_mprintf(""); - } - if( zDir==0 ) rc = SQLITE_NOMEM; - } - - shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, - azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere - ); - - if( rc==SQLITE_OK ){ - j = sqlite3_bind_parameter_index(pSql, "$dir"); - sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); - - /* Run the SELECT statement twice. The first time, writefile() is called - ** for all archive members that should be extracted. The second time, - ** only for the directories. This is because the timestamps for - ** extracted directories must be reset after they are populated (as - ** populating them changes the timestamp). */ - for(i=0; i<2; i++){ - j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); - sqlite3_bind_int(pSql, j, i); - if( pAr->bDryRun ){ - utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); - }else{ - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ - if( i==0 && pAr->bVerbose ){ - utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); - } - } - } - shellReset(&rc, pSql); - } - shellFinalize(&rc, pSql); - } - - sqlite3_free(zDir); - sqlite3_free(zWhere); - return rc; -} - -/* -** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. -*/ -static int arExecSql(ArCommand *pAr, const char *zSql){ - int rc; - if( pAr->bDryRun ){ - utf8_printf(pAr->p->out, "%s\n", zSql); - rc = SQLITE_OK; - }else{ - char *zErr = 0; - rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); - if( zErr ){ - utf8_printf(stdout, "ERROR: %s\n", zErr); - sqlite3_free(zErr); - } - } - return rc; -} - - -/* -** Implementation of .ar "create", "insert", and "update" commands. -** -** create -> Create a new SQL archive -** insert -> Insert or reinsert all files listed -** update -> Insert files that have changed or that were not -** previously in the archive -** -** Create the "sqlar" table in the database if it does not already exist. -** Then add each file in the azFile[] array to the archive. Directories -** are added recursively. If argument bVerbose is non-zero, a message is -** printed on stdout for each file archived. -** -** The create command is the same as update, except that it drops -** any existing "sqlar" table before beginning. The "insert" command -** always overwrites every file named on the command-line, where as -** "update" only overwrites if the size or mtime or mode has changed. -*/ -static int arCreateOrUpdateCommand( - ArCommand *pAr, /* Command arguments and options */ - int bUpdate, /* true for a --create. */ - int bOnlyIfChanged /* Only update if file has changed */ -){ - const char *zCreate = - "CREATE TABLE IF NOT EXISTS sqlar(\n" - " name TEXT PRIMARY KEY, -- name of the file\n" - " mode INT, -- access permissions\n" - " mtime INT, -- last modification time\n" - " sz INT, -- original file size\n" - " data BLOB -- compressed content\n" - ")"; - const char *zDrop = "DROP TABLE IF EXISTS sqlar"; - const char *zInsertFmt[2] = { - "REPLACE INTO %s(name,mode,mtime,sz,data)\n" - " SELECT\n" - " %s,\n" - " mode,\n" - " mtime,\n" - " CASE substr(lsmode(mode),1,1)\n" - " WHEN '-' THEN length(data)\n" - " WHEN 'd' THEN 0\n" - " ELSE -1 END,\n" - " sqlar_compress(data)\n" - " FROM fsdir(%Q,%Q) AS disk\n" - " WHERE lsmode(mode) NOT LIKE '?%%'%s;" - , - "REPLACE INTO %s(name,mode,mtime,data)\n" - " SELECT\n" - " %s,\n" - " mode,\n" - " mtime,\n" - " data\n" - " FROM fsdir(%Q,%Q) AS disk\n" - " WHERE lsmode(mode) NOT LIKE '?%%'%s;" - }; - int i; /* For iterating through azFile[] */ - int rc; /* Return code */ - const char *zTab = 0; /* SQL table into which to insert */ - char *zSql; - char zTemp[50]; - char *zExists = 0; - - arExecSql(pAr, "PRAGMA page_size=512"); - rc = arExecSql(pAr, "SAVEPOINT ar;"); - if( rc!=SQLITE_OK ) return rc; - zTemp[0] = 0; - if( pAr->bZip ){ - /* Initialize the zipfile virtual table, if necessary */ - if( pAr->zFile ){ - sqlite3_uint64 r; - sqlite3_randomness(sizeof(r),&r); - sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); - zTab = zTemp; - zSql = sqlite3_mprintf( - "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", - zTab, pAr->zFile - ); - rc = arExecSql(pAr, zSql); - sqlite3_free(zSql); - }else{ - zTab = "zip"; - } - }else{ - /* Initialize the table for an SQLAR */ - zTab = "sqlar"; - if( bUpdate==0 ){ - rc = arExecSql(pAr, zDrop); - if( rc!=SQLITE_OK ) goto end_ar_transaction; - } - rc = arExecSql(pAr, zCreate); - } - if( bOnlyIfChanged ){ - zExists = sqlite3_mprintf( - " AND NOT EXISTS(" - "SELECT 1 FROM %s AS mem" - " WHERE mem.name=disk.name" - " AND mem.mtime=disk.mtime" - " AND mem.mode=disk.mode)", zTab); - }else{ - zExists = sqlite3_mprintf(""); - } - if( zExists==0 ) rc = SQLITE_NOMEM; - for(i=0; inArg && rc==SQLITE_OK; i++){ - char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, - pAr->bVerbose ? "shell_putsnl(name)" : "name", - pAr->azArg[i], pAr->zDir, zExists); - rc = arExecSql(pAr, zSql2); - sqlite3_free(zSql2); - } -end_ar_transaction: - if( rc!=SQLITE_OK ){ - sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); - }else{ - rc = arExecSql(pAr, "RELEASE ar;"); - if( pAr->bZip && pAr->zFile ){ - zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); - arExecSql(pAr, zSql); - sqlite3_free(zSql); - } - } - sqlite3_free(zExists); - return rc; -} - -/* -** Implementation of ".ar" dot command. -*/ -static int arDotCommand( - ShellState *pState, /* Current shell tool state */ - int fromCmdLine, /* True if -A command-line option, not .ar cmd */ - char **azArg, /* Array of arguments passed to dot command */ - int nArg /* Number of entries in azArg[] */ -){ - ArCommand cmd; - int rc; - memset(&cmd, 0, sizeof(cmd)); - cmd.fromCmdLine = fromCmdLine; - rc = arParseCommand(azArg, nArg, &cmd); - if( rc==SQLITE_OK ){ - int eDbType = SHELL_OPEN_UNSPEC; - cmd.p = pState; - cmd.db = pState->db; - if( cmd.zFile ){ - eDbType = deduceDatabaseType(cmd.zFile, 1); - }else{ - eDbType = pState->openMode; - } - if( eDbType==SHELL_OPEN_ZIPFILE ){ - if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ - if( cmd.zFile==0 ){ - cmd.zSrcTable = sqlite3_mprintf("zip"); - }else{ - cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); - } - } - cmd.bZip = 1; - }else if( cmd.zFile ){ - int flags; - if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; - if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT - || cmd.eCmd==AR_CMD_UPDATE ){ - flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; - }else{ - flags = SQLITE_OPEN_READONLY; - } - cmd.db = 0; - if( cmd.bDryRun ){ - utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, - eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); - } - rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, - eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); - if( rc!=SQLITE_OK ){ - utf8_printf(stderr, "cannot open file: %s (%s)\n", - cmd.zFile, sqlite3_errmsg(cmd.db) - ); - goto end_ar_command; - } - sqlite3_fileio_init(cmd.db, 0, 0); - sqlite3_sqlar_init(cmd.db, 0, 0); - sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, - shellPutsFunc, 0, 0); - - } - if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ - if( cmd.eCmd!=AR_CMD_CREATE - && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) - ){ - utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); - rc = SQLITE_ERROR; - goto end_ar_command; - } - cmd.zSrcTable = sqlite3_mprintf("sqlar"); - } - - switch( cmd.eCmd ){ - case AR_CMD_CREATE: - rc = arCreateOrUpdateCommand(&cmd, 0, 0); - break; - - case AR_CMD_EXTRACT: - rc = arExtractCommand(&cmd); - break; - - case AR_CMD_LIST: - rc = arListCommand(&cmd); - break; - - case AR_CMD_HELP: - arUsage(pState->out); - break; - - case AR_CMD_INSERT: - rc = arCreateOrUpdateCommand(&cmd, 1, 0); - break; - - default: - assert( cmd.eCmd==AR_CMD_UPDATE ); - rc = arCreateOrUpdateCommand(&cmd, 1, 1); - break; - } - } -end_ar_command: - if( cmd.db!=pState->db ){ - close_db(cmd.db); - } - sqlite3_free(cmd.zSrcTable); - - return rc; -} -/* End of the ".archive" or ".ar" command logic -*******************************************************************************/ -#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) -/* -** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. -** Otherwise, the SQL statement or statements in zSql are executed using -** database connection db and the error code written to *pRc before -** this function returns. -*/ -static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ - int rc = *pRc; - if( rc==SQLITE_OK ){ - char *zErr = 0; - rc = sqlite3_exec(db, zSql, 0, 0, &zErr); - if( rc!=SQLITE_OK ){ - raw_printf(stderr, "SQL error: %s\n", zErr); - } - *pRc = rc; - } -} - -/* -** Like shellExec(), except that zFmt is a printf() style format string. -*/ -static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ - char *z = 0; - if( *pRc==SQLITE_OK ){ - va_list ap; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - if( z==0 ){ - *pRc = SQLITE_NOMEM; - }else{ - shellExec(db, pRc, z); - } - sqlite3_free(z); - } -} - -/* -** If *pRc is not SQLITE_OK when this function is called, it is a no-op. -** Otherwise, an attempt is made to allocate, zero and return a pointer -** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set -** to SQLITE_NOMEM and NULL returned. -*/ -static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ - void *pRet = 0; - if( *pRc==SQLITE_OK ){ - pRet = sqlite3_malloc64(nByte); - if( pRet==0 ){ - *pRc = SQLITE_NOMEM; - }else{ - memset(pRet, 0, nByte); - } - } - return pRet; -} - -/* -** If *pRc is not SQLITE_OK when this function is called, it is a no-op. -** Otherwise, zFmt is treated as a printf() style string. The result of -** formatting it along with any trailing arguments is written into a -** buffer obtained from sqlite3_malloc(), and pointer to which is returned. -** It is the responsibility of the caller to eventually free this buffer -** using a call to sqlite3_free(). -** -** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL -** pointer returned. -*/ -static char *shellMPrintf(int *pRc, const char *zFmt, ...){ - char *z = 0; - if( *pRc==SQLITE_OK ){ - va_list ap; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - if( z==0 ){ - *pRc = SQLITE_NOMEM; - } - } - return z; -} - -/* -** When running the ".recover" command, each output table, and the special -** orphaned row table if it is required, is represented by an instance -** of the following struct. -*/ -typedef struct RecoverTable RecoverTable; -struct RecoverTable { - char *zQuoted; /* Quoted version of table name */ - int nCol; /* Number of columns in table */ - char **azlCol; /* Array of column lists */ - int iPk; /* Index of IPK column */ -}; - -/* -** Free a RecoverTable object allocated by recoverFindTable() or -** recoverOrphanTable(). -*/ -static void recoverFreeTable(RecoverTable *pTab){ - if( pTab ){ - sqlite3_free(pTab->zQuoted); - if( pTab->azlCol ){ - int i; - for(i=0; i<=pTab->nCol; i++){ - sqlite3_free(pTab->azlCol[i]); - } - sqlite3_free(pTab->azlCol); - } - sqlite3_free(pTab); - } -} - -/* -** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. -** Otherwise, it allocates and returns a RecoverTable object based on the -** final four arguments passed to this function. It is the responsibility -** of the caller to eventually free the returned object using -** recoverFreeTable(). -*/ -static RecoverTable *recoverNewTable( - int *pRc, /* IN/OUT: Error code */ - const char *zName, /* Name of table */ - const char *zSql, /* CREATE TABLE statement */ - int bIntkey, - int nCol -){ - sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ - int rc = *pRc; - RecoverTable *pTab = 0; - - pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); - if( rc==SQLITE_OK ){ - int nSqlCol = 0; - int bSqlIntkey = 0; - sqlite3_stmt *pStmt = 0; - - rc = sqlite3_open("", &dbtmp); - if( rc==SQLITE_OK ){ - sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0, - shellIdQuote, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); - if( rc==SQLITE_ERROR ){ - rc = SQLITE_OK; - goto finished; - } - } - shellPreparePrintf(dbtmp, &rc, &pStmt, - "SELECT count(*) FROM pragma_table_info(%Q)", zName - ); - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - nSqlCol = sqlite3_column_int(pStmt, 0); - } - shellFinalize(&rc, pStmt); - - if( rc!=SQLITE_OK || nSqlColiPk to the index - ** of the column, where columns are 0-numbered from left to right. - ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, - ** leave zPk as "_rowid_" and pTab->iPk at -2. */ - pTab->iPk = -2; - if( bIntkey ){ - shellPreparePrintf(dbtmp, &rc, &pPkFinder, - "SELECT cid, name FROM pragma_table_info(%Q) " - " WHERE pk=1 AND type='integer' COLLATE nocase" - " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" - , zName, zName - ); - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ - pTab->iPk = sqlite3_column_int(pPkFinder, 0); - zPk = (const char*)sqlite3_column_text(pPkFinder, 1); - } - } - - pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName); - pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); - pTab->nCol = nSqlCol; - - if( bIntkey ){ - pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk); - }else{ - pTab->azlCol[0] = shellMPrintf(&rc, ""); - } - i = 1; - shellPreparePrintf(dbtmp, &rc, &pStmt, - "SELECT %Q || group_concat(shell_idquote(name), ', ') " - " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " - "FROM pragma_table_info(%Q)", - bIntkey ? ", " : "", pTab->iPk, - bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", - zName - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zText = (const char*)sqlite3_column_text(pStmt, 0); - pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); - i++; - } - shellFinalize(&rc, pStmt); - - shellFinalize(&rc, pPkFinder); - } - } - - finished: - sqlite3_close(dbtmp); - *pRc = rc; - if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ - recoverFreeTable(pTab); - pTab = 0; - } - return pTab; -} - -/* -** This function is called to search the schema recovered from the -** sqlite_schema table of the (possibly) corrupt database as part -** of a ".recover" command. Specifically, for a table with root page -** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the -** table must be a WITHOUT ROWID table, or if non-zero, not one of -** those. -** -** If a table is found, a (RecoverTable*) object is returned. Or, if -** no such table is found, but bIntkey is false and iRoot is the -** root page of an index in the recovered schema, then (*pbNoop) is -** set to true and NULL returned. Or, if there is no such table or -** index, NULL is returned and (*pbNoop) set to 0, indicating that -** the caller should write data to the orphans table. -*/ -static RecoverTable *recoverFindTable( - ShellState *pState, /* Shell state object */ - int *pRc, /* IN/OUT: Error code */ - int iRoot, /* Root page of table */ - int bIntkey, /* True for an intkey table */ - int nCol, /* Number of columns in table */ - int *pbNoop /* OUT: True if iRoot is root of index */ -){ - sqlite3_stmt *pStmt = 0; - RecoverTable *pRet = 0; - int bNoop = 0; - const char *zSql = 0; - const char *zName = 0; - - /* Search the recovered schema for an object with root page iRoot. */ - shellPreparePrintf(pState->db, pRc, &pStmt, - "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot - ); - while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zType = (const char*)sqlite3_column_text(pStmt, 0); - if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ - bNoop = 1; - break; - } - if( sqlite3_stricmp(zType, "table")==0 ){ - zName = (const char*)sqlite3_column_text(pStmt, 1); - zSql = (const char*)sqlite3_column_text(pStmt, 2); - pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); - break; - } - } - - shellFinalize(pRc, pStmt); - *pbNoop = bNoop; - return pRet; -} - -/* -** Return a RecoverTable object representing the orphans table. -*/ -static RecoverTable *recoverOrphanTable( - ShellState *pState, /* Shell state object */ - int *pRc, /* IN/OUT: Error code */ - const char *zLostAndFound, /* Base name for orphans table */ - int nCol /* Number of user data columns */ -){ - RecoverTable *pTab = 0; - if( nCol>=0 && *pRc==SQLITE_OK ){ - int i; - - /* This block determines the name of the orphan table. The prefered - ** name is zLostAndFound. But if that clashes with another name - ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 - ** and so on until a non-clashing name is found. */ - int iTab = 0; - char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); - sqlite3_stmt *pTest = 0; - shellPrepare(pState->db, pRc, - "SELECT 1 FROM recovery.schema WHERE name=?", &pTest - ); - if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); - while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ - shellReset(pRc, pTest); - sqlite3_free(zTab); - zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); - sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); - } - shellFinalize(pRc, pTest); - - pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); - if( pTab ){ - pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab); - pTab->nCol = nCol; - pTab->iPk = -2; - if( nCol>0 ){ - pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); - if( pTab->azlCol ){ - pTab->azlCol[nCol] = shellMPrintf(pRc, ""); - for(i=nCol-1; i>=0; i--){ - pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); - } - } - } - - if( *pRc!=SQLITE_OK ){ - recoverFreeTable(pTab); - pTab = 0; - }else{ - raw_printf(pState->out, - "CREATE TABLE %s(rootpgno INTEGER, " - "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted - ); - for(i=0; iout, ", c%d", i); - } - raw_printf(pState->out, ");\n"); - } - } - sqlite3_free(zTab); - } - return pTab; -} - -/* -** This function is called to recover data from the database. A script -** to construct a new database containing all recovered data is output -** on stream pState->out. -*/ -static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ - int rc = SQLITE_OK; - sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ - sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ - sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ - const char *zRecoveryDb = ""; /* Name of "recovery" database */ - const char *zLostAndFound = "lost_and_found"; - int i; - int nOrphan = -1; - RecoverTable *pOrphan = 0; - - int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ - int bRowids = 1; /* 0 if --no-rowids */ - for(i=1; iout, azArg[0]); - return 1; - } - } - - shellExecPrintf(pState->db, &rc, - /* Attach an in-memory database named 'recovery'. Create an indexed - ** cache of the sqlite_dbptr virtual table. */ - "PRAGMA writable_schema = on;" - "ATTACH %Q AS recovery;" - "DROP TABLE IF EXISTS recovery.dbptr;" - "DROP TABLE IF EXISTS recovery.freelist;" - "DROP TABLE IF EXISTS recovery.map;" - "DROP TABLE IF EXISTS recovery.schema;" - "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb - ); - - if( bFreelist ){ - shellExec(pState->db, &rc, - "WITH trunk(pgno) AS (" - " SELECT shell_int32(" - " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " - " WHERE x>0" - " UNION" - " SELECT shell_int32(" - " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " - " FROM trunk WHERE x>0" - ")," - "freelist(data, n, freepgno) AS (" - " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " - " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" - " UNION ALL" - " SELECT data, n-1, shell_int32(data, 2+n) " - " FROM freelist WHERE n>=0" - ")" - "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" - ); - } - - /* If this is an auto-vacuum database, add all pointer-map pages to - ** the freelist table. Do this regardless of whether or not - ** --freelist-corrupt was specified. */ - shellExec(pState->db, &rc, - "WITH ptrmap(pgno) AS (" - " SELECT 2 WHERE shell_int32(" - " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13" - " )" - " UNION ALL " - " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp " - " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)" - ")" - "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap" - ); - - shellExec(pState->db, &rc, - "CREATE TABLE recovery.dbptr(" - " pgno, child, PRIMARY KEY(child, pgno)" - ") WITHOUT ROWID;" - "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " - " SELECT * FROM sqlite_dbptr" - " WHERE pgno NOT IN freelist AND child NOT IN freelist;" - - /* Delete any pointer to page 1. This ensures that page 1 is considered - ** a root page, regardless of how corrupt the db is. */ - "DELETE FROM recovery.dbptr WHERE child = 1;" - - /* Delete all pointers to any pages that have more than one pointer - ** to them. Such pages will be treated as root pages when recovering - ** data. */ - "DELETE FROM recovery.dbptr WHERE child IN (" - " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" - ");" - - /* Create the "map" table that will (eventually) contain instructions - ** for dealing with each page in the db that contains one or more - ** records. */ - "CREATE TABLE recovery.map(" - "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" - ");" - - /* Populate table [map]. If there are circular loops of pages in the - ** database, the following adds all pages in such a loop to the map - ** as individual root pages. This could be handled better. */ - "WITH pages(i, maxlen) AS (" - " SELECT page_count, (" - " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" - " ) FROM pragma_page_count WHERE page_count>0" - " UNION ALL" - " SELECT i-1, (" - " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" - " ) FROM pages WHERE i>=2" - ")" - "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " - " SELECT i, maxlen, NULL, (" - " WITH p(orig, pgno, parent) AS (" - " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" - " UNION " - " SELECT i, p.parent, " - " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" - " )" - " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" - ") " - "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;" - "UPDATE recovery.map AS o SET intkey = (" - " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" - ");" - - /* Extract data from page 1 and any linked pages into table - ** recovery.schema. With the same schema as an sqlite_schema table. */ - "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" - "INSERT INTO recovery.schema SELECT " - " max(CASE WHEN field=0 THEN value ELSE NULL END)," - " max(CASE WHEN field=1 THEN value ELSE NULL END)," - " max(CASE WHEN field=2 THEN value ELSE NULL END)," - " max(CASE WHEN field=3 THEN value ELSE NULL END)," - " max(CASE WHEN field=4 THEN value ELSE NULL END)" - "FROM sqlite_dbdata WHERE pgno IN (" - " SELECT pgno FROM recovery.map WHERE root=1" - ")" - "GROUP BY pgno, cell;" - "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" - ); - - /* Open a transaction, then print out all non-virtual, non-"sqlite_%" - ** CREATE TABLE statements that extracted from the existing schema. */ - if( rc==SQLITE_OK ){ - sqlite3_stmt *pStmt = 0; - /* ".recover" might output content in an order which causes immediate - ** foreign key constraints to be violated. So disable foreign-key - ** constraint enforcement to prevent problems when running the output - ** script. */ - raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n"); - raw_printf(pState->out, "BEGIN;\n"); - raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); - shellPrepare(pState->db, &rc, - "SELECT sql FROM recovery.schema " - "WHERE type='table' AND sql LIKE 'create table%'", &pStmt - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); - raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", - &zCreateTable[12] - ); - } - shellFinalize(&rc, pStmt); - } - - /* Figure out if an orphan table will be required. And if so, how many - ** user columns it should contain */ - shellPrepare(pState->db, &rc, - "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" - , &pLoop - ); - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ - nOrphan = sqlite3_column_int(pLoop, 0); - } - shellFinalize(&rc, pLoop); - pLoop = 0; - - shellPrepare(pState->db, &rc, - "SELECT pgno FROM recovery.map WHERE root=?", &pPages - ); - - shellPrepare(pState->db, &rc, - "SELECT max(field), group_concat(shell_escape_crnl(quote" - "(case when (? AND field<0) then NULL else value end)" - "), ', ')" - ", min(field) " - "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" - "GROUP BY cell", &pCells - ); - - /* Loop through each root page. */ - shellPrepare(pState->db, &rc, - "SELECT root, intkey, max(maxlen) FROM recovery.map" - " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" - " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" - ")", &pLoop - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ - int iRoot = sqlite3_column_int(pLoop, 0); - int bIntkey = sqlite3_column_int(pLoop, 1); - int nCol = sqlite3_column_int(pLoop, 2); - int bNoop = 0; - RecoverTable *pTab; - - assert( bIntkey==0 || bIntkey==1 ); - pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); - if( bNoop || rc ) continue; - if( pTab==0 ){ - if( pOrphan==0 ){ - pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); - } - pTab = pOrphan; - if( pTab==0 ) break; - } - - if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){ - raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); - } - sqlite3_bind_int(pPages, 1, iRoot); - if( bRowids==0 && pTab->iPk<0 ){ - sqlite3_bind_int(pCells, 1, 1); - }else{ - sqlite3_bind_int(pCells, 1, 0); - } - sqlite3_bind_int(pCells, 3, pTab->iPk); - - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ - int iPgno = sqlite3_column_int(pPages, 0); - sqlite3_bind_int(pCells, 2, iPgno); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ - int nField = sqlite3_column_int(pCells, 0); - int iMin = sqlite3_column_int(pCells, 2); - const char *zVal = (const char*)sqlite3_column_text(pCells, 1); - - RecoverTable *pTab2 = pTab; - if( pTab!=pOrphan && (iMin<0)!=bIntkey ){ - if( pOrphan==0 ){ - pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); - } - pTab2 = pOrphan; - if( pTab2==0 ) break; - } - - nField = nField+1; - if( pTab2==pOrphan ){ - raw_printf(pState->out, - "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", - pTab2->zQuoted, iRoot, iPgno, nField, - iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField] - ); - }else{ - raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", - pTab2->zQuoted, pTab2->azlCol[nField], zVal - ); - } - } - shellReset(&rc, pCells); - } - shellReset(&rc, pPages); - if( pTab!=pOrphan ) recoverFreeTable(pTab); - } - shellFinalize(&rc, pLoop); - shellFinalize(&rc, pPages); - shellFinalize(&rc, pCells); - recoverFreeTable(pOrphan); - - /* The rest of the schema */ - if( rc==SQLITE_OK ){ - sqlite3_stmt *pStmt = 0; - shellPrepare(pState->db, &rc, - "SELECT sql, name FROM recovery.schema " - "WHERE sql NOT LIKE 'create table%'", &pStmt - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); - if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ - const char *zName = (const char*)sqlite3_column_text(pStmt, 1); - char *zPrint = shellMPrintf(&rc, - "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)", - zName, zName, zSql - ); - raw_printf(pState->out, "%s;\n", zPrint); - sqlite3_free(zPrint); - }else{ - raw_printf(pState->out, "%s;\n", zSql); - } - } - shellFinalize(&rc, pStmt); - } - - if( rc==SQLITE_OK ){ - raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); - raw_printf(pState->out, "COMMIT;\n"); - } - sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); - return rc; -} -#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ - - -/* -** If an input line begins with "." then invoke this routine to -** process that line. -** -** Return 1 on error, 2 to exit, and 0 otherwise. -*/ -static int do_meta_command(char *zLine, ShellState *p){ - int h = 1; - int nArg = 0; - int n, c; - int rc = 0; - char *azArg[52]; - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( p->expert.pExpert ){ - expertFinish(p, 1, 0); - } -#endif - - /* Parse the input line into tokens. - */ - while( zLine[h] && nArgdb, shellAuth, p); - }else{ - sqlite3_set_authorizer(p->db, 0, 0); - } - }else -#endif - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) - if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ - open_db(p, 0); - rc = arDotCommand(p, 0, azArg, nArg); - }else -#endif - - if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) - || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) - ){ - const char *zDestFile = 0; - const char *zDb = 0; - sqlite3 *pDest; - sqlite3_backup *pBackup; - int j; - int bAsync = 0; - const char *zVfs = 0; - for(j=1; jdb, zDb); - if( pBackup==0 ){ - utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); - close_db(pDest); - return 1; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = 0; - }else{ - utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); - rc = 1; - } - close_db(pDest); - }else - - if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ - if( nArg==2 ){ - bail_on_error = booleanValue(azArg[1]); - }else{ - raw_printf(stderr, "Usage: .bail on|off\n"); - rc = 1; - } - }else - - if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ - if( nArg==2 ){ - if( booleanValue(azArg[1]) ){ - setBinaryMode(p->out, 1); - }else{ - setTextMode(p->out, 1); - } - }else{ - raw_printf(stderr, "Usage: .binary on|off\n"); - rc = 1; - } - }else - - if( c=='c' && strcmp(azArg[0],"cd")==0 ){ - if( nArg==2 ){ -#if defined(_WIN32) || defined(WIN32) - wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); - rc = !SetCurrentDirectoryW(z); - sqlite3_free(z); -#else - rc = chdir(azArg[1]); -#endif - if( rc ){ - utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); - rc = 1; - } - }else{ - raw_printf(stderr, "Usage: .cd DIRECTORY\n"); - rc = 1; - } - }else - - /* The undocumented ".breakpoint" command causes a call to the no-op - ** routine named test_breakpoint(). - */ - if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ - test_breakpoint(); - }else - - if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ - if( nArg==2 ){ - setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); - }else{ - raw_printf(stderr, "Usage: .changes on|off\n"); - rc = 1; - } - }else - - /* Cancel output redirection, if it is currently set (by .testcase) - ** Then read the content of the testcase-out.txt file and compare against - ** azArg[1]. If there are differences, report an error and exit. - */ - if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ - char *zRes = 0; - output_reset(p); - if( nArg!=2 ){ - raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); - rc = 2; - }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ - raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); - rc = 2; - }else if( testcase_glob(azArg[1],zRes)==0 ){ - utf8_printf(stderr, - "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", - p->zTestcase, azArg[1], zRes); - rc = 1; - }else{ - utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); - p->nCheck++; - } - sqlite3_free(zRes); - }else - - if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ - if( nArg==2 ){ - tryToClone(p, azArg[1]); - }else{ - raw_printf(stderr, "Usage: .clone FILENAME\n"); - rc = 1; - } - }else - - if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ - ShellState data; - char *zErrMsg = 0; - open_db(p, 0); - memcpy(&data, p, sizeof(data)); - data.showHeader = 0; - data.cMode = data.mode = MODE_List; - sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": "); - data.cnt = 0; - sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list", - callback, &data, &zErrMsg); - if( zErrMsg ){ - utf8_printf(stderr,"Error: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - } - }else - - if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ - static const struct DbConfigChoices { - const char *zName; - int op; - } aDbConfig[] = { - { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, - { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, - { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, - { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, - { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, - { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, - { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, - { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, - { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, - { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, - { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, - { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, - { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, - { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, - { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, - { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, - }; - int ii, v; - open_db(p, 0); - for(ii=0; ii1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; - if( nArg>=3 ){ - sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); - } - sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); - utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); - if( nArg>1 ) break; - } - if( nArg>1 && ii==ArraySize(aDbConfig) ){ - utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); - utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); - } - }else - - if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ - rc = shell_dbinfo_command(p, nArg, azArg); - }else - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) - if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ - open_db(p, 0); - rc = recoverDatabaseCmd(p, nArg, azArg); - }else -#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ - - if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ - char *zLike = 0; - char *zSql; - int i; - int savedShowHeader = p->showHeader; - int savedShellFlags = p->shellFlgs; - ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo); - for(i=1; iout, "PRAGMA foreign_keys=OFF;\n"); - raw_printf(p->out, "BEGIN TRANSACTION;\n"); - p->writableSchema = 0; - p->showHeader = 0; - /* Set writable_schema=ON since doing so forces SQLite to initialize - ** as much of the schema as it can even if the sqlite_schema table is - ** corrupt. */ - sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); - p->nErr = 0; - if( zLike==0 ) zLike = sqlite3_mprintf("true"); - zSql = sqlite3_mprintf( - "SELECT name, type, sql FROM sqlite_schema " - "WHERE (%s) AND type=='table'" - " AND sql NOT NULL" - " ORDER BY tbl_name='sqlite_sequence', rowid", - zLike - ); - run_schema_dump_query(p,zSql); - sqlite3_free(zSql); - zSql = sqlite3_mprintf( - "SELECT sql FROM sqlite_schema " - "WHERE (%s) AND sql NOT NULL" - " AND type IN ('index','trigger','view')", - zLike - ); - run_table_dump_query(p, zSql); - sqlite3_free(zSql); - sqlite3_free(zLike); - if( p->writableSchema ){ - raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); - p->writableSchema = 0; - } - sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); - sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); - raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); - p->showHeader = savedShowHeader; - p->shellFlgs = savedShellFlags; - }else - - if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ - if( nArg==2 ){ - setOrClearFlag(p, SHFLG_Echo, azArg[1]); - }else{ - raw_printf(stderr, "Usage: .echo on|off\n"); - rc = 1; - } - }else - - if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ - if( nArg==2 ){ - p->autoEQPtest = 0; - if( p->autoEQPtrace ){ - if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); - p->autoEQPtrace = 0; - } - if( strcmp(azArg[1],"full")==0 ){ - p->autoEQP = AUTOEQP_full; - }else if( strcmp(azArg[1],"trigger")==0 ){ - p->autoEQP = AUTOEQP_trigger; -#ifdef SQLITE_DEBUG - }else if( strcmp(azArg[1],"test")==0 ){ - p->autoEQP = AUTOEQP_on; - p->autoEQPtest = 1; - }else if( strcmp(azArg[1],"trace")==0 ){ - p->autoEQP = AUTOEQP_full; - p->autoEQPtrace = 1; - open_db(p, 0); - sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); - sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); -#endif - }else{ - p->autoEQP = (u8)booleanValue(azArg[1]); - } - }else{ - raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); - rc = 1; - } - }else - - if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ - if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); - rc = 2; - }else - - /* The ".explain" command is automatic now. It is largely pointless. It - ** retained purely for backwards compatibility */ - if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ - int val = 1; - if( nArg>=2 ){ - if( strcmp(azArg[1],"auto")==0 ){ - val = 99; - }else{ - val = booleanValue(azArg[1]); - } - } - if( val==1 && p->mode!=MODE_Explain ){ - p->normalMode = p->mode; - p->mode = MODE_Explain; - p->autoExplain = 0; - }else if( val==0 ){ - if( p->mode==MODE_Explain ) p->mode = p->normalMode; - p->autoExplain = 0; - }else if( val==99 ){ - if( p->mode==MODE_Explain ) p->mode = p->normalMode; - p->autoExplain = 1; - } - }else - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ - open_db(p, 0); - expertDotCommand(p, azArg, nArg); - }else -#endif - - if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){ - static const struct { - const char *zCtrlName; /* Name of a test-control option */ - int ctrlCode; /* Integer code for that option */ - const char *zUsage; /* Usage notes */ - } aCtrl[] = { - { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, - { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, - /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ - { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, - { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, - /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ - { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, - { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, - { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, - { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" }, - }; - int filectrl = -1; - int iCtrl = -1; - sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ - int isOk = 0; /* 0: usage 1: %lld 2: no-result */ - int n2, i; - const char *zCmd = 0; - const char *zSchema = 0; - - open_db(p, 0); - zCmd = nArg>=2 ? azArg[1] : "help"; - - if( zCmd[0]=='-' - && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0) - && nArg>=4 - ){ - zSchema = azArg[2]; - for(i=3; iout, "Available file-controls:\n"); - for(i=0; iout, " .filectrl %s %s\n", - aCtrl[i].zCtrlName, aCtrl[i].zUsage); - } - rc = 1; - goto meta_command_exit; - } - - /* convert filectrl text option to value. allow any unique prefix - ** of the option name, or a numerical value. */ - n2 = strlen30(zCmd); - for(i=0; idb, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); - isOk = 1; - break; - } - case SQLITE_FCNTL_LOCK_TIMEOUT: - case SQLITE_FCNTL_CHUNK_SIZE: { - int x; - if( nArg!=3 ) break; - x = (int)integerValue(azArg[2]); - sqlite3_file_control(p->db, zSchema, filectrl, &x); - isOk = 2; - break; - } - case SQLITE_FCNTL_PERSIST_WAL: - case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { - int x; - if( nArg!=2 && nArg!=3 ) break; - x = nArg==3 ? booleanValue(azArg[2]) : -1; - sqlite3_file_control(p->db, zSchema, filectrl, &x); - iRes = x; - isOk = 1; - break; - } - case SQLITE_FCNTL_HAS_MOVED: { - int x; - if( nArg!=2 ) break; - sqlite3_file_control(p->db, zSchema, filectrl, &x); - iRes = x; - isOk = 1; - break; - } - case SQLITE_FCNTL_TEMPFILENAME: { - char *z = 0; - if( nArg!=2 ) break; - sqlite3_file_control(p->db, zSchema, filectrl, &z); - if( z ){ - utf8_printf(p->out, "%s\n", z); - sqlite3_free(z); - } - isOk = 2; - break; - } - case SQLITE_FCNTL_RESERVE_BYTES: { - int x; - if( nArg>=3 ){ - x = atoi(azArg[2]); - sqlite3_file_control(p->db, zSchema, filectrl, &x); - } - x = -1; - sqlite3_file_control(p->db, zSchema, filectrl, &x); - utf8_printf(p->out,"%d\n", x); - isOk = 2; - break; - } - } - } - if( isOk==0 && iCtrl>=0 ){ - utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); - rc = 1; - }else if( isOk==1 ){ - char zBuf[100]; - sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); - raw_printf(p->out, "%s\n", zBuf); - } - }else - - if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ - ShellState data; - char *zErrMsg = 0; - int doStats = 0; - memcpy(&data, p, sizeof(data)); - data.showHeader = 0; - data.cMode = data.mode = MODE_Semi; - if( nArg==2 && optionMatch(azArg[1], "indent") ){ - data.cMode = data.mode = MODE_Pretty; - nArg = 1; - } - if( nArg!=1 ){ - raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - rc = sqlite3_exec(p->db, - "SELECT sql FROM" - " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" - " FROM sqlite_schema UNION ALL" - " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) " - "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " - "ORDER BY rowid", - callback, &data, &zErrMsg - ); - if( rc==SQLITE_OK ){ - sqlite3_stmt *pStmt; - rc = sqlite3_prepare_v2(p->db, - "SELECT rowid FROM sqlite_schema" - " WHERE name GLOB 'sqlite_stat[134]'", - -1, &pStmt, 0); - doStats = sqlite3_step(pStmt)==SQLITE_ROW; - sqlite3_finalize(pStmt); - } - if( doStats==0 ){ - raw_printf(p->out, "/* No STAT tables available */\n"); - }else{ - raw_printf(p->out, "ANALYZE sqlite_schema;\n"); - sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'", - callback, &data, &zErrMsg); - data.cMode = data.mode = MODE_Insert; - data.zDestTable = "sqlite_stat1"; - shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg); - data.zDestTable = "sqlite_stat4"; - shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg); - raw_printf(p->out, "ANALYZE sqlite_schema;\n"); - } - }else - - if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ - if( nArg==2 ){ - p->showHeader = booleanValue(azArg[1]); - p->shellFlgs |= SHFLG_HeaderSet; - }else{ - raw_printf(stderr, "Usage: .headers on|off\n"); - rc = 1; - } - }else - - if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ - if( nArg>=2 ){ - n = showHelp(p->out, azArg[1]); - if( n==0 ){ - utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); - } - }else{ - showHelp(p->out, 0); - } - }else - - if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ - char *zTable = 0; /* Insert data into this table */ - char *zFile = 0; /* Name of file to extra content from */ - sqlite3_stmt *pStmt = NULL; /* A statement */ - int nCol; /* Number of columns in the table */ - int nByte; /* Number of bytes in an SQL string */ - int i, j; /* Loop counters */ - int needCommit; /* True to COMMIT or ROLLBACK at end */ - int nSep; /* Number of bytes in p->colSeparator[] */ - char *zSql; /* An SQL statement */ - ImportCtx sCtx; /* Reader context */ - char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ - int eVerbose = 0; /* Larger for more console output */ - int nSkip = 0; /* Initial lines to skip */ - int useOutputMode = 1; /* Use output mode to determine separators */ - - memset(&sCtx, 0, sizeof(sCtx)); - if( p->mode==MODE_Ascii ){ - xRead = ascii_read_one_field; - }else{ - xRead = csv_read_one_field; - } - for(i=1; iout, "ERROR: extra argument: \"%s\". Usage:\n", z); - showHelp(p->out, "import"); - rc = 1; - goto meta_command_exit; - } - }else if( strcmp(z,"-v")==0 ){ - eVerbose++; - }else if( strcmp(z,"-skip")==0 && iout, "ERROR: unknown option: \"%s\". Usage:\n", z); - showHelp(p->out, "import"); - rc = 1; - goto meta_command_exit; - } - } - if( zTable==0 ){ - utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n", - zFile==0 ? "FILE" : "TABLE"); - showHelp(p->out, "import"); - rc = 1; - goto meta_command_exit; - } - seenInterrupt = 0; - open_db(p, 0); - if( useOutputMode ){ - /* If neither the --csv or --ascii options are specified, then set - ** the column and row separator characters from the output mode. */ - nSep = strlen30(p->colSeparator); - if( nSep==0 ){ - raw_printf(stderr, - "Error: non-null column separator required for import\n"); - rc = 1; - goto meta_command_exit; - } - if( nSep>1 ){ - raw_printf(stderr, - "Error: multi-character column separators not allowed" - " for import\n"); - rc = 1; - goto meta_command_exit; - } - nSep = strlen30(p->rowSeparator); - if( nSep==0 ){ - raw_printf(stderr, - "Error: non-null row separator required for import\n"); - rc = 1; - goto meta_command_exit; - } - if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){ - /* When importing CSV (only), if the row separator is set to the - ** default output row separator, change it to the default input - ** row separator. This avoids having to maintain different input - ** and output row separators. */ - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - nSep = strlen30(p->rowSeparator); - } - if( nSep>1 ){ - raw_printf(stderr, "Error: multi-character row separators not allowed" - " for import\n"); - rc = 1; - goto meta_command_exit; - } - sCtx.cColSep = p->colSeparator[0]; - sCtx.cRowSep = p->rowSeparator[0]; - } - sCtx.zFile = zFile; - sCtx.nLine = 1; - if( sCtx.zFile[0]=='|' ){ -#ifdef SQLITE_OMIT_POPEN - raw_printf(stderr, "Error: pipes are not supported in this OS\n"); - rc = 1; - goto meta_command_exit; -#else - sCtx.in = popen(sCtx.zFile+1, "r"); - sCtx.zFile = ""; - sCtx.xCloser = pclose; -#endif - }else{ - sCtx.in = fopen(sCtx.zFile, "rb"); - sCtx.xCloser = fclose; - } - if( sCtx.in==0 ){ - utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); - rc = 1; - goto meta_command_exit; - } - if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){ - char zSep[2]; - zSep[1] = 0; - zSep[0] = sCtx.cColSep; - utf8_printf(p->out, "Column separator "); - output_c_string(p->out, zSep); - utf8_printf(p->out, ", row separator "); - zSep[0] = sCtx.cRowSep; - output_c_string(p->out, zSep); - utf8_printf(p->out, "\n"); - } - while( (nSkip--)>0 ){ - while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} - } - zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); - if( zSql==0 ){ - import_cleanup(&sCtx); - shell_out_of_memory(); - } - nByte = strlen30(zSql); - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ - if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ - char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); - char cSep = '('; - while( xRead(&sCtx) ){ - zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); - cSep = ','; - if( sCtx.cTerm!=sCtx.cColSep ) break; - } - if( cSep=='(' ){ - sqlite3_free(zCreate); - import_cleanup(&sCtx); - utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); - rc = 1; - goto meta_command_exit; - } - zCreate = sqlite3_mprintf("%z\n)", zCreate); - if( eVerbose>=1 ){ - utf8_printf(p->out, "%s\n", zCreate); - } - rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); - sqlite3_free(zCreate); - if( rc ){ - utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, - sqlite3_errmsg(p->db)); - import_cleanup(&sCtx); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - } - sqlite3_free(zSql); - if( rc ){ - if (pStmt) sqlite3_finalize(pStmt); - utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); - import_cleanup(&sCtx); - rc = 1; - goto meta_command_exit; - } - nCol = sqlite3_column_count(pStmt); - sqlite3_finalize(pStmt); - pStmt = 0; - if( nCol==0 ) return 0; /* no columns, no error */ - zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); - if( zSql==0 ){ - import_cleanup(&sCtx); - shell_out_of_memory(); - } - sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); - j = strlen30(zSql); - for(i=1; i=2 ){ - utf8_printf(p->out, "Insert using: %s\n", zSql); - } - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc ){ - utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); - if (pStmt) sqlite3_finalize(pStmt); - import_cleanup(&sCtx); - rc = 1; - goto meta_command_exit; - } - needCommit = sqlite3_get_autocommit(p->db); - if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); - do{ - int startLine = sCtx.nLine; - for(i=0; imode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; - sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); - if( i=nCol ){ - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); - if( rc!=SQLITE_OK ){ - utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, - startLine, sqlite3_errmsg(p->db)); - sCtx.nErr++; - }else{ - sCtx.nRow++; - } - } - }while( sCtx.cTerm!=EOF ); - - import_cleanup(&sCtx); - sqlite3_finalize(pStmt); - if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); - if( eVerbose>0 ){ - utf8_printf(p->out, - "Added %d rows with %d errors using %d lines of input\n", - sCtx.nRow, sCtx.nErr, sCtx.nLine-1); - } - }else - -#ifndef SQLITE_UNTESTABLE - if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ - char *zSql; - char *zCollist = 0; - sqlite3_stmt *pStmt; - int tnum = 0; - int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ - int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ - int i; - if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ - utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" - " .imposter off\n"); - /* Also allowed, but not documented: - ** - ** .imposter TABLE IMPOSTER - ** - ** where TABLE is a WITHOUT ROWID table. In that case, the - ** imposter is another WITHOUT ROWID table with the columns in - ** storage order. */ - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - if( nArg==2 ){ - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); - goto meta_command_exit; - } - zSql = sqlite3_mprintf( - "SELECT rootpage, 0 FROM sqlite_schema" - " WHERE name='%q' AND type='index'" - "UNION ALL " - "SELECT rootpage, 1 FROM sqlite_schema" - " WHERE name='%q' AND type='table'" - " AND sql LIKE '%%without%%rowid%%'", - azArg[1], azArg[1] - ); - sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( sqlite3_step(pStmt)==SQLITE_ROW ){ - tnum = sqlite3_column_int(pStmt, 0); - isWO = sqlite3_column_int(pStmt, 1); - } - sqlite3_finalize(pStmt); - zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - i = 0; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - char zLabel[20]; - const char *zCol = (const char*)sqlite3_column_text(pStmt,2); - i++; - if( zCol==0 ){ - if( sqlite3_column_int(pStmt,1)==-1 ){ - zCol = "_ROWID_"; - }else{ - sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); - zCol = zLabel; - } - } - if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ - lenPK = (int)strlen(zCollist); - } - if( zCollist==0 ){ - zCollist = sqlite3_mprintf("\"%w\"", zCol); - }else{ - zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); - } - } - sqlite3_finalize(pStmt); - if( i==0 || tnum==0 ){ - utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); - rc = 1; - sqlite3_free(zCollist); - goto meta_command_exit; - } - if( lenPK==0 ) lenPK = 100000; - zSql = sqlite3_mprintf( - "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", - azArg[2], zCollist, lenPK, zCollist); - sqlite3_free(zCollist); - rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->db, zSql, 0, 0, 0); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); - if( rc ){ - utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); - }else{ - utf8_printf(stdout, "%s;\n", zSql); - raw_printf(stdout, - "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n", - azArg[1], isWO ? "table" : "index" - ); - } - }else{ - raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); - rc = 1; - } - sqlite3_free(zSql); - }else -#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ - -#ifdef SQLITE_ENABLE_IOTRACE - if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ - SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); - if( iotrace && iotrace!=stdout ) fclose(iotrace); - iotrace = 0; - if( nArg<2 ){ - sqlite3IoTrace = 0; - }else if( strcmp(azArg[1], "-")==0 ){ - sqlite3IoTrace = iotracePrintf; - iotrace = stdout; - }else{ - iotrace = fopen(azArg[1], "w"); - if( iotrace==0 ){ - utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); - sqlite3IoTrace = 0; - rc = 1; - }else{ - sqlite3IoTrace = iotracePrintf; - } - } - }else -#endif - - if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ - static const struct { - const char *zLimitName; /* Name of a limit */ - int limitCode; /* Integer code for that limit */ - } aLimit[] = { - { "length", SQLITE_LIMIT_LENGTH }, - { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, - { "column", SQLITE_LIMIT_COLUMN }, - { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, - { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, - { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, - { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, - { "attached", SQLITE_LIMIT_ATTACHED }, - { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, - { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, - { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, - { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, - }; - int i, n2; - open_db(p, 0); - if( nArg==1 ){ - for(i=0; idb, aLimit[i].limitCode, -1)); - } - }else if( nArg>3 ){ - raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); - rc = 1; - goto meta_command_exit; - }else{ - int iLimit = -1; - n2 = strlen30(azArg[1]); - for(i=0; idb, aLimit[iLimit].limitCode, - (int)integerValue(azArg[2])); - } - printf("%20s %d\n", aLimit[iLimit].zLimitName, - sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); - } - }else - - if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ - open_db(p, 0); - lintDotCommand(p, azArg, nArg); - }else - -#ifndef SQLITE_OMIT_LOAD_EXTENSION - if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ - const char *zFile, *zProc; - char *zErrMsg = 0; - if( nArg<2 ){ - raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); - rc = 1; - goto meta_command_exit; - } - zFile = azArg[1]; - zProc = nArg>=3 ? azArg[2] : 0; - open_db(p, 0); - rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); - if( rc!=SQLITE_OK ){ - utf8_printf(stderr, "Error: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - } - }else -#endif - - if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ - if( nArg!=2 ){ - raw_printf(stderr, "Usage: .log FILENAME\n"); - rc = 1; - }else{ - const char *zFile = azArg[1]; - output_file_close(p->pLog); - p->pLog = output_file_open(zFile, 0); - } - }else - - if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ - const char *zMode = nArg>=2 ? azArg[1] : ""; - int n2 = strlen30(zMode); - int c2 = zMode[0]; - if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ - p->mode = MODE_Line; - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ - p->mode = MODE_Column; - if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ - p->showHeader = 1; - } - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ - p->mode = MODE_List; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ - p->mode = MODE_Html; - }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ - p->mode = MODE_Tcl; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ - p->mode = MODE_Csv; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); - }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ - p->mode = MODE_List; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); - }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ - p->mode = MODE_Insert; - set_table_name(p, nArg>=3 ? azArg[2] : "table"); - }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ - p->mode = MODE_Quote; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ - p->mode = MODE_Ascii; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); - }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){ - p->mode = MODE_Markdown; - }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){ - p->mode = MODE_Table; - }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){ - p->mode = MODE_Box; - }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){ - p->mode = MODE_Json; - }else if( nArg==1 ){ - raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); - }else{ - raw_printf(stderr, "Error: mode should be one of: " - "ascii box column csv html insert json line list markdown " - "quote table tabs tcl\n"); - rc = 1; - } - p->cMode = p->mode; - }else - - if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ - if( nArg==2 ){ - sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, - "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); - }else{ - raw_printf(stderr, "Usage: .nullvalue STRING\n"); - rc = 1; - } - }else - -#ifdef SQLITE_DEBUG - if( c=='o' && strcmp(azArg[0],"oom")==0 ){ - int i; - for(i=1; iout, "missing argument on \"%s\"\n", azArg[i]); - rc = 1; - }else{ - oomRepeat = (int)integerValue(azArg[++i]); - } - }else if( IsDigit(z[0]) ){ - oomCounter = (int)integerValue(azArg[i]); - }else{ - raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]); - raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n"); - rc = 1; - } - } - if( rc==0 ){ - raw_printf(p->out, "oomCounter = %d\n", oomCounter); - raw_printf(p->out, "oomRepeat = %d\n", oomRepeat); - } - }else -#endif /* SQLITE_DEBUG */ - - if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ - char *zNewFilename; /* Name of the database file to open */ - int iName = 1; /* Index in azArg[] of the filename */ - int newFlag = 0; /* True to delete file before opening */ - /* Close the existing database */ - session_close_all(p); - close_db(p->db); - p->db = 0; - p->zDbFilename = 0; - sqlite3_free(p->zFreeOnClose); - p->zFreeOnClose = 0; - p->openMode = SHELL_OPEN_UNSPEC; - p->openFlags = 0; - p->szMax = 0; - /* Check for command-line arguments */ - for(iName=1; iNameopenMode = SHELL_OPEN_ZIPFILE; -#endif - }else if( optionMatch(z, "append") ){ - p->openMode = SHELL_OPEN_APPENDVFS; - }else if( optionMatch(z, "readonly") ){ - p->openMode = SHELL_OPEN_READONLY; - }else if( optionMatch(z, "nofollow") ){ - p->openFlags |= SQLITE_OPEN_NOFOLLOW; -#ifdef SQLITE_ENABLE_DESERIALIZE - }else if( optionMatch(z, "deserialize") ){ - p->openMode = SHELL_OPEN_DESERIALIZE; - }else if( optionMatch(z, "hexdb") ){ - p->openMode = SHELL_OPEN_HEXDB; - }else if( optionMatch(z, "maxsize") && iName+1szMax = integerValue(azArg[++iName]); -#endif /* SQLITE_ENABLE_DESERIALIZE */ - }else if( z[0]=='-' ){ - utf8_printf(stderr, "unknown option: %s\n", z); - rc = 1; - goto meta_command_exit; - } - } - /* If a filename is specified, try to open it first */ - zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0; - if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){ - if( newFlag ) shellDeleteFile(zNewFilename); - p->zDbFilename = zNewFilename; - open_db(p, OPEN_DB_KEEPALIVE); - if( p->db==0 ){ - utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); - sqlite3_free(zNewFilename); - }else{ - p->zFreeOnClose = zNewFilename; - } - } - if( p->db==0 ){ - /* As a fall-back open a TEMP database */ - p->zDbFilename = 0; - open_db(p, 0); - } - }else - - if( (c=='o' - && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) - || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) - ){ - const char *zFile = 0; - int bTxtMode = 0; - int i; - int eMode = 0; - int bBOM = 0; - int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */ - - if( c=='e' ){ - eMode = 'x'; - bOnce = 2; - }else if( strncmp(azArg[0],"once",n)==0 ){ - bOnce = 1; - } - for(i=1; iout, "ERROR: unknown option: \"%s\". Usage:\n", - azArg[i]); - showHelp(p->out, azArg[0]); - rc = 1; - goto meta_command_exit; - } - }else if( zFile==0 ){ - zFile = z; - }else{ - utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n", - azArg[i]); - showHelp(p->out, azArg[0]); - rc = 1; - goto meta_command_exit; - } - } - if( zFile==0 ) zFile = "stdout"; - if( bOnce ){ - p->outCount = 2; - }else{ - p->outCount = 0; - } - output_reset(p); -#ifndef SQLITE_NOHAVE_SYSTEM - if( eMode=='e' || eMode=='x' ){ - p->doXdgOpen = 1; - outputModePush(p); - if( eMode=='x' ){ - /* spreadsheet mode. Output as CSV. */ - newTempFile(p, "csv"); - ShellClearFlag(p, SHFLG_Echo); - p->mode = MODE_Csv; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); - }else{ - /* text editor mode */ - newTempFile(p, "txt"); - bTxtMode = 1; - } - zFile = p->zTempFile; - } -#endif /* SQLITE_NOHAVE_SYSTEM */ - if( zFile[0]=='|' ){ -#ifdef SQLITE_OMIT_POPEN - raw_printf(stderr, "Error: pipes are not supported in this OS\n"); - rc = 1; - p->out = stdout; -#else - p->out = popen(zFile + 1, "w"); - if( p->out==0 ){ - utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); - p->out = stdout; - rc = 1; - }else{ - if( bBOM ) fprintf(p->out,"\357\273\277"); - sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); - } -#endif - }else{ - p->out = output_file_open(zFile, bTxtMode); - if( p->out==0 ){ - if( strcmp(zFile,"off")!=0 ){ - utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); - } - p->out = stdout; - rc = 1; - } else { - if( bBOM ) fprintf(p->out,"\357\273\277"); - sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); - } - } - }else - - if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ - open_db(p,0); - if( nArg<=1 ) goto parameter_syntax_error; - - /* .parameter clear - ** Clear all bind parameters by dropping the TEMP table that holds them. - */ - if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ - sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", - 0, 0, 0); - }else - - /* .parameter list - ** List all bind parameters. - */ - if( nArg==2 && strcmp(azArg[1],"list")==0 ){ - sqlite3_stmt *pStmt = 0; - int rx; - int len = 0; - rx = sqlite3_prepare_v2(p->db, - "SELECT max(length(key)) " - "FROM temp.sqlite_parameters;", -1, &pStmt, 0); - if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - len = sqlite3_column_int(pStmt, 0); - if( len>40 ) len = 40; - } - sqlite3_finalize(pStmt); - pStmt = 0; - if( len ){ - rx = sqlite3_prepare_v2(p->db, - "SELECT key, quote(value) " - "FROM temp.sqlite_parameters;", -1, &pStmt, 0); - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), - sqlite3_column_text(pStmt,1)); - } - sqlite3_finalize(pStmt); - } - }else - - /* .parameter init - ** Make sure the TEMP table used to hold bind parameters exists. - ** Create it if necessary. - */ - if( nArg==2 && strcmp(azArg[1],"init")==0 ){ - bind_table_init(p); - }else - - /* .parameter set NAME VALUE - ** Set or reset a bind parameter. NAME should be the full parameter - ** name exactly as it appears in the query. (ex: $abc, @def). The - ** VALUE can be in either SQL literal notation, or if not it will be - ** understood to be a text string. - */ - if( nArg==4 && strcmp(azArg[1],"set")==0 ){ - int rx; - char *zSql; - sqlite3_stmt *pStmt; - const char *zKey = azArg[2]; - const char *zValue = azArg[3]; - bind_table_init(p); - zSql = sqlite3_mprintf( - "REPLACE INTO temp.sqlite_parameters(key,value)" - "VALUES(%Q,%s);", zKey, zValue); - if( zSql==0 ) shell_out_of_memory(); - pStmt = 0; - rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rx!=SQLITE_OK ){ - sqlite3_finalize(pStmt); - pStmt = 0; - zSql = sqlite3_mprintf( - "REPLACE INTO temp.sqlite_parameters(key,value)" - "VALUES(%Q,%Q);", zKey, zValue); - if( zSql==0 ) shell_out_of_memory(); - rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rx!=SQLITE_OK ){ - utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); - sqlite3_finalize(pStmt); - pStmt = 0; - rc = 1; - } - } - sqlite3_step(pStmt); - sqlite3_finalize(pStmt); - }else - - /* .parameter unset NAME - ** Remove the NAME binding from the parameter binding table, if it - ** exists. - */ - if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ - char *zSql = sqlite3_mprintf( - "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); - if( zSql==0 ) shell_out_of_memory(); - sqlite3_exec(p->db, zSql, 0, 0, 0); - sqlite3_free(zSql); - }else - /* If no command name matches, show a syntax error */ - parameter_syntax_error: - showHelp(p->out, "parameter"); - }else - - if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ - int i; - for(i=1; i1 ) raw_printf(p->out, " "); - utf8_printf(p->out, "%s", azArg[i]); - } - raw_printf(p->out, "\n"); - }else - -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ - int i; - int nn = 0; - p->flgProgress = 0; - p->mxProgress = 0; - p->nProgress = 0; - for(i=1; iflgProgress |= SHELL_PROGRESS_QUIET; - continue; - } - if( strcmp(z,"reset")==0 ){ - p->flgProgress |= SHELL_PROGRESS_RESET; - continue; - } - if( strcmp(z,"once")==0 ){ - p->flgProgress |= SHELL_PROGRESS_ONCE; - continue; - } - if( strcmp(z,"limit")==0 ){ - if( i+1>=nArg ){ - utf8_printf(stderr, "Error: missing argument on --limit\n"); - rc = 1; - goto meta_command_exit; - }else{ - p->mxProgress = (int)integerValue(azArg[++i]); - } - continue; - } - utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); - rc = 1; - goto meta_command_exit; - }else{ - nn = (int)integerValue(z); - } - } - open_db(p, 0); - sqlite3_progress_handler(p->db, nn, progress_handler, p); - }else -#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ - - if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ - if( nArg >= 2) { - strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); - } - if( nArg >= 3) { - strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); - } - }else - - if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ - rc = 2; - }else - - if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ - FILE *inSaved = p->in; - int savedLineno = p->lineno; - if( nArg!=2 ){ - raw_printf(stderr, "Usage: .read FILE\n"); - rc = 1; - goto meta_command_exit; - } - if( notNormalFile(azArg[1]) - || (p->in = fopen(azArg[1], "rb"))==0 - ){ - utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); - rc = 1; - }else{ - rc = process_input(p); - fclose(p->in); - } - p->in = inSaved; - p->lineno = savedLineno; - }else - - if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ - const char *zSrcFile; - const char *zDb; - sqlite3 *pSrc; - sqlite3_backup *pBackup; - int nTimeout = 0; - - if( nArg==2 ){ - zSrcFile = azArg[1]; - zDb = "main"; - }else if( nArg==3 ){ - zSrcFile = azArg[2]; - zDb = azArg[1]; - }else{ - raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_open(zSrcFile, &pSrc); - if( rc!=SQLITE_OK ){ - utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); - close_db(pSrc); - return 1; - } - open_db(p, 0); - pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); - if( pBackup==0 ){ - utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); - close_db(pSrc); - return 1; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK - || rc==SQLITE_BUSY ){ - if( rc==SQLITE_BUSY ){ - if( nTimeout++ >= 3 ) break; - sqlite3_sleep(100); - } - } - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = 0; - }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ - raw_printf(stderr, "Error: source database is busy\n"); - rc = 1; - }else{ - utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); - rc = 1; - } - close_db(pSrc); - }else - - if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ - if( nArg==2 ){ - p->scanstatsOn = (u8)booleanValue(azArg[1]); -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS - raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); -#endif - }else{ - raw_printf(stderr, "Usage: .scanstats on|off\n"); - rc = 1; - } - }else - - if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ - ShellText sSelect; - ShellState data; - char *zErrMsg = 0; - const char *zDiv = "("; - const char *zName = 0; - int iSchema = 0; - int bDebug = 0; - int ii; - - open_db(p, 0); - memcpy(&data, p, sizeof(data)); - data.showHeader = 0; - data.cMode = data.mode = MODE_Semi; - initText(&sSelect); - for(ii=1; iidb, "SELECT name FROM pragma_database_list", - -1, &pStmt, 0); - if( rc ){ - utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); - sqlite3_finalize(pStmt); - rc = 1; - goto meta_command_exit; - } - appendText(&sSelect, "SELECT sql FROM", 0); - iSchema = 0; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); - char zScNum[30]; - sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); - appendText(&sSelect, zDiv, 0); - zDiv = " UNION ALL "; - appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); - if( sqlite3_stricmp(zDb, "main")!=0 ){ - appendText(&sSelect, zDb, '\''); - }else{ - appendText(&sSelect, "NULL", 0); - } - appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); - appendText(&sSelect, zScNum, 0); - appendText(&sSelect, " AS snum, ", 0); - appendText(&sSelect, zDb, '\''); - appendText(&sSelect, " AS sname FROM ", 0); - appendText(&sSelect, zDb, quoteChar(zDb)); - appendText(&sSelect, ".sqlite_schema", 0); - } - sqlite3_finalize(pStmt); -#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS - if( zName ){ - appendText(&sSelect, - " UNION ALL SELECT shell_module_schema(name)," - " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", - 0); - } -#endif - appendText(&sSelect, ") WHERE ", 0); - if( zName ){ - char *zQarg = sqlite3_mprintf("%Q", zName); - int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || - strchr(zName, '[') != 0; - if( strchr(zName, '.') ){ - appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); - }else{ - appendText(&sSelect, "lower(tbl_name)", 0); - } - appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); - appendText(&sSelect, zQarg, 0); - if( !bGlob ){ - appendText(&sSelect, " ESCAPE '\\' ", 0); - } - appendText(&sSelect, " AND ", 0); - sqlite3_free(zQarg); - } - appendText(&sSelect, "type!='meta' AND sql IS NOT NULL" - " ORDER BY snum, rowid", 0); - if( bDebug ){ - utf8_printf(p->out, "SQL: %s;\n", sSelect.z); - }else{ - rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); - } - freeText(&sSelect); - } - if( zErrMsg ){ - utf8_printf(stderr,"Error: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - }else if( rc != SQLITE_OK ){ - raw_printf(stderr,"Error: querying schema information\n"); - rc = 1; - }else{ - rc = 0; - } - }else - -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) - if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ - sqlite3_unsupported_selecttrace = nArg>=2 ? (int)integerValue(azArg[1]) : 0xffff; - }else -#endif - -#if defined(SQLITE_ENABLE_SESSION) - if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ - OpenSession *pSession = &p->aSession[0]; - char **azCmd = &azArg[1]; - int iSes = 0; - int nCmd = nArg - 1; - int i; - if( nArg<=1 ) goto session_syntax_error; - open_db(p, 0); - if( nArg>=3 ){ - for(iSes=0; iSesnSession; iSes++){ - if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; - } - if( iSesnSession ){ - pSession = &p->aSession[iSes]; - azCmd++; - nCmd--; - }else{ - pSession = &p->aSession[0]; - iSes = 0; - } - } - - /* .session attach TABLE - ** Invoke the sqlite3session_attach() interface to attach a particular - ** table so that it is never filtered. - */ - if( strcmp(azCmd[0],"attach")==0 ){ - if( nCmd!=2 ) goto session_syntax_error; - if( pSession->p==0 ){ - session_not_open: - raw_printf(stderr, "ERROR: No sessions are open\n"); - }else{ - rc = sqlite3session_attach(pSession->p, azCmd[1]); - if( rc ){ - raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); - rc = 0; - } - } - }else - - /* .session changeset FILE - ** .session patchset FILE - ** Write a changeset or patchset into a file. The file is overwritten. - */ - if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ - FILE *out = 0; - if( nCmd!=2 ) goto session_syntax_error; - if( pSession->p==0 ) goto session_not_open; - out = fopen(azCmd[1], "wb"); - if( out==0 ){ - utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", - azCmd[1]); - }else{ - int szChng; - void *pChng; - if( azCmd[0][0]=='c' ){ - rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); - }else{ - rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); - } - if( rc ){ - printf("Error: error code %d\n", rc); - rc = 0; - } - if( pChng - && fwrite(pChng, szChng, 1, out)!=1 ){ - raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", - szChng); - } - sqlite3_free(pChng); - fclose(out); - } - }else - - /* .session close - ** Close the identified session - */ - if( strcmp(azCmd[0], "close")==0 ){ - if( nCmd!=1 ) goto session_syntax_error; - if( p->nSession ){ - session_close(pSession); - p->aSession[iSes] = p->aSession[--p->nSession]; - } - }else - - /* .session enable ?BOOLEAN? - ** Query or set the enable flag - */ - if( strcmp(azCmd[0], "enable")==0 ){ - int ii; - if( nCmd>2 ) goto session_syntax_error; - ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); - if( p->nSession ){ - ii = sqlite3session_enable(pSession->p, ii); - utf8_printf(p->out, "session %s enable flag = %d\n", - pSession->zName, ii); - } - }else - - /* .session filter GLOB .... - ** Set a list of GLOB patterns of table names to be excluded. - */ - if( strcmp(azCmd[0], "filter")==0 ){ - int ii, nByte; - if( nCmd<2 ) goto session_syntax_error; - if( p->nSession ){ - for(ii=0; iinFilter; ii++){ - sqlite3_free(pSession->azFilter[ii]); - } - sqlite3_free(pSession->azFilter); - nByte = sizeof(pSession->azFilter[0])*(nCmd-1); - pSession->azFilter = sqlite3_malloc( nByte ); - if( pSession->azFilter==0 ){ - raw_printf(stderr, "Error: out or memory\n"); - exit(1); - } - for(ii=1; iiazFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); - } - pSession->nFilter = ii-1; - } - }else - - /* .session indirect ?BOOLEAN? - ** Query or set the indirect flag - */ - if( strcmp(azCmd[0], "indirect")==0 ){ - int ii; - if( nCmd>2 ) goto session_syntax_error; - ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); - if( p->nSession ){ - ii = sqlite3session_indirect(pSession->p, ii); - utf8_printf(p->out, "session %s indirect flag = %d\n", - pSession->zName, ii); - } - }else - - /* .session isempty - ** Determine if the session is empty - */ - if( strcmp(azCmd[0], "isempty")==0 ){ - int ii; - if( nCmd!=1 ) goto session_syntax_error; - if( p->nSession ){ - ii = sqlite3session_isempty(pSession->p); - utf8_printf(p->out, "session %s isempty flag = %d\n", - pSession->zName, ii); - } - }else - - /* .session list - ** List all currently open sessions - */ - if( strcmp(azCmd[0],"list")==0 ){ - for(i=0; inSession; i++){ - utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); - } - }else - - /* .session open DB NAME - ** Open a new session called NAME on the attached database DB. - ** DB is normally "main". - */ - if( strcmp(azCmd[0],"open")==0 ){ - char *zName; - if( nCmd!=3 ) goto session_syntax_error; - zName = azCmd[2]; - if( zName[0]==0 ) goto session_syntax_error; - for(i=0; inSession; i++){ - if( strcmp(p->aSession[i].zName,zName)==0 ){ - utf8_printf(stderr, "Session \"%s\" already exists\n", zName); - goto meta_command_exit; - } - } - if( p->nSession>=ArraySize(p->aSession) ){ - raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); - goto meta_command_exit; - } - pSession = &p->aSession[p->nSession]; - rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); - if( rc ){ - raw_printf(stderr, "Cannot open session: error code=%d\n", rc); - rc = 0; - goto meta_command_exit; - } - pSession->nFilter = 0; - sqlite3session_table_filter(pSession->p, session_filter, pSession); - p->nSession++; - pSession->zName = sqlite3_mprintf("%s", zName); - }else - /* If no command name matches, show a syntax error */ - session_syntax_error: - showHelp(p->out, "session"); - }else -#endif - -#ifdef SQLITE_DEBUG - /* Undocumented commands for internal testing. Subject to change - ** without notice. */ - if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ - if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ - int i, v; - for(i=1; iout, "%s: %d 0x%x\n", azArg[i], v, v); - } - } - if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ - int i; sqlite3_int64 v; - for(i=1; iout, "%s", zBuf); - } - } - }else -#endif - - if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ - int bIsInit = 0; /* True to initialize the SELFTEST table */ - int bVerbose = 0; /* Verbose output */ - int bSelftestExists; /* True if SELFTEST already exists */ - int i, k; /* Loop counters */ - int nTest = 0; /* Number of tests runs */ - int nErr = 0; /* Number of errors seen */ - ShellText str; /* Answer for a query */ - sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ - - open_db(p,0); - for(i=1; idb,"main","selftest",0,0,0,0,0,0) - != SQLITE_OK ){ - bSelftestExists = 0; - }else{ - bSelftestExists = 1; - } - if( bIsInit ){ - createSelftestTable(p); - bSelftestExists = 1; - } - initText(&str); - appendText(&str, "x", 0); - for(k=bSelftestExists; k>=0; k--){ - if( k==1 ){ - rc = sqlite3_prepare_v2(p->db, - "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", - -1, &pStmt, 0); - }else{ - rc = sqlite3_prepare_v2(p->db, - "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," - " (1,'run','PRAGMA integrity_check','ok')", - -1, &pStmt, 0); - } - if( rc ){ - raw_printf(stderr, "Error querying the selftest table\n"); - rc = 1; - sqlite3_finalize(pStmt); - goto meta_command_exit; - } - for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ - int tno = sqlite3_column_int(pStmt, 0); - const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); - const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); - const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); - - k = 0; - if( bVerbose>0 ){ - char *zQuote = sqlite3_mprintf("%q", zSql); - printf("%d: %s %s\n", tno, zOp, zSql); - sqlite3_free(zQuote); - } - if( strcmp(zOp,"memo")==0 ){ - utf8_printf(p->out, "%s\n", zSql); - }else - if( strcmp(zOp,"run")==0 ){ - char *zErrMsg = 0; - str.n = 0; - str.z[0] = 0; - rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); - nTest++; - if( bVerbose ){ - utf8_printf(p->out, "Result: %s\n", str.z); - } - if( rc || zErrMsg ){ - nErr++; - rc = 1; - utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); - sqlite3_free(zErrMsg); - }else if( strcmp(zAns,str.z)!=0 ){ - nErr++; - rc = 1; - utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); - utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); - } - }else - { - utf8_printf(stderr, - "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); - rc = 1; - break; - } - } /* End loop over rows of content from SELFTEST */ - sqlite3_finalize(pStmt); - } /* End loop over k */ - freeText(&str); - utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); - }else - - if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ - if( nArg<2 || nArg>3 ){ - raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); - rc = 1; - } - if( nArg>=2 ){ - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, - "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); - } - if( nArg>=3 ){ - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, - "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); - } - }else - - if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ - const char *zLike = 0; /* Which table to checksum. 0 means everything */ - int i; /* Loop counter */ - int bSchema = 0; /* Also hash the schema */ - int bSeparate = 0; /* Hash each table separately */ - int iSize = 224; /* Hash algorithm to use */ - int bDebug = 0; /* Only show the query that would have run */ - sqlite3_stmt *pStmt; /* For querying tables names */ - char *zSql; /* SQL to be run */ - char *zSep; /* Separator */ - ShellText sSql; /* Complete SQL for the query to run the hash */ - ShellText sQuery; /* Set of queries used to read all content */ - open_db(p, 0); - for(i=1; iout, azArg[0]); - rc = 1; - goto meta_command_exit; - } - }else if( zLike ){ - raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); - rc = 1; - goto meta_command_exit; - }else{ - zLike = z; - bSeparate = 1; - if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; - } - } - if( bSchema ){ - zSql = "SELECT lower(name) FROM sqlite_schema" - " WHERE type='table' AND coalesce(rootpage,0)>1" - " UNION ALL SELECT 'sqlite_schema'" - " ORDER BY 1 collate nocase"; - }else{ - zSql = "SELECT lower(name) FROM sqlite_schema" - " WHERE type='table' AND coalesce(rootpage,0)>1" - " AND name NOT LIKE 'sqlite_%'" - " ORDER BY 1 collate nocase"; - } - sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - initText(&sQuery); - initText(&sSql); - appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); - zSep = "VALUES("; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zTab = (const char*)sqlite3_column_text(pStmt,0); - if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; - if( strncmp(zTab, "sqlite_",7)!=0 ){ - appendText(&sQuery,"SELECT * FROM ", 0); - appendText(&sQuery,zTab,'"'); - appendText(&sQuery," NOT INDEXED;", 0); - }else if( strcmp(zTab, "sqlite_schema")==0 ){ - appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema" - " ORDER BY name;", 0); - }else if( strcmp(zTab, "sqlite_sequence")==0 ){ - appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" - " ORDER BY name;", 0); - }else if( strcmp(zTab, "sqlite_stat1")==0 ){ - appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" - " ORDER BY tbl,idx;", 0); - }else if( strcmp(zTab, "sqlite_stat4")==0 ){ - appendText(&sQuery, "SELECT * FROM ", 0); - appendText(&sQuery, zTab, 0); - appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); - } - appendText(&sSql, zSep, 0); - appendText(&sSql, sQuery.z, '\''); - sQuery.n = 0; - appendText(&sSql, ",", 0); - appendText(&sSql, zTab, '\''); - zSep = "),("; - } - sqlite3_finalize(pStmt); - if( bSeparate ){ - zSql = sqlite3_mprintf( - "%s))" - " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" - " FROM [sha3sum$query]", - sSql.z, iSize); - }else{ - zSql = sqlite3_mprintf( - "%s))" - " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" - " FROM [sha3sum$query]", - sSql.z, iSize); - } - freeText(&sQuery); - freeText(&sSql); - if( bDebug ){ - utf8_printf(p->out, "%s\n", zSql); - }else{ - shell_exec(p, zSql, 0); - } - sqlite3_free(zSql); - }else - -#ifndef SQLITE_NOHAVE_SYSTEM - if( c=='s' - && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) - ){ - char *zCmd; - int i, x; - if( nArg<2 ){ - raw_printf(stderr, "Usage: .system COMMAND\n"); - rc = 1; - goto meta_command_exit; - } - zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); - for(i=2; iout, "%12.12s: %s\n","echo", - azBool[ShellHasFlag(p, SHFLG_Echo)]); - utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); - utf8_printf(p->out, "%12.12s: %s\n","explain", - p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); - utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); - utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); - utf8_printf(p->out, "%12.12s: ", "nullvalue"); - output_c_string(p->out, p->nullValue); - raw_printf(p->out, "\n"); - utf8_printf(p->out,"%12.12s: %s\n","output", - strlen30(p->outfile) ? p->outfile : "stdout"); - utf8_printf(p->out,"%12.12s: ", "colseparator"); - output_c_string(p->out, p->colSeparator); - raw_printf(p->out, "\n"); - utf8_printf(p->out,"%12.12s: ", "rowseparator"); - output_c_string(p->out, p->rowSeparator); - raw_printf(p->out, "\n"); - utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); - utf8_printf(p->out, "%12.12s: ", "width"); - for (i=0;inWidth;i++) { - raw_printf(p->out, "%d ", p->colWidth[i]); - } - raw_printf(p->out, "\n"); - utf8_printf(p->out, "%12.12s: %s\n", "filename", - p->zDbFilename ? p->zDbFilename : ""); - }else - - if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ - if( nArg==2 ){ - p->statsOn = (u8)booleanValue(azArg[1]); - }else if( nArg==1 ){ - display_stats(p->db, p, 0); - }else{ - raw_printf(stderr, "Usage: .stats ?on|off?\n"); - rc = 1; - } - }else - - if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) - || (c=='i' && (strncmp(azArg[0], "indices", n)==0 - || strncmp(azArg[0], "indexes", n)==0) ) - ){ - sqlite3_stmt *pStmt; - char **azResult; - int nRow, nAlloc; - int ii; - ShellText s; - initText(&s); - open_db(p, 0); - rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); - if( rc ){ - sqlite3_finalize(pStmt); - return shellDatabaseError(p->db); - } - - if( nArg>2 && c=='i' ){ - /* It is an historical accident that the .indexes command shows an error - ** when called with the wrong number of arguments whereas the .tables - ** command does not. */ - raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); - rc = 1; - sqlite3_finalize(pStmt); - goto meta_command_exit; - } - for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ - const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); - if( zDbName==0 ) continue; - if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); - if( sqlite3_stricmp(zDbName, "main")==0 ){ - appendText(&s, "SELECT name FROM ", 0); - }else{ - appendText(&s, "SELECT ", 0); - appendText(&s, zDbName, '\''); - appendText(&s, "||'.'||name FROM ", 0); - } - appendText(&s, zDbName, '"'); - appendText(&s, ".sqlite_schema ", 0); - if( c=='t' ){ - appendText(&s," WHERE type IN ('table','view')" - " AND name NOT LIKE 'sqlite_%'" - " AND name LIKE ?1", 0); - }else{ - appendText(&s," WHERE type='index'" - " AND tbl_name LIKE ?1", 0); - } - } - rc = sqlite3_finalize(pStmt); - appendText(&s, " ORDER BY 1", 0); - rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); - freeText(&s); - if( rc ) return shellDatabaseError(p->db); - - /* Run the SQL statement prepared by the above block. Store the results - ** as an array of nul-terminated strings in azResult[]. */ - nRow = nAlloc = 0; - azResult = 0; - if( nArg>1 ){ - sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); - }else{ - sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); - } - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - if( nRow>=nAlloc ){ - char **azNew; - int n2 = nAlloc*2 + 10; - azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); - if( azNew==0 ) shell_out_of_memory(); - nAlloc = n2; - azResult = azNew; - } - azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); - if( 0==azResult[nRow] ) shell_out_of_memory(); - nRow++; - } - if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ - rc = shellDatabaseError(p->db); - } - - /* Pretty-print the contents of array azResult[] to the output */ - if( rc==0 && nRow>0 ){ - int len, maxlen = 0; - int i, j; - int nPrintCol, nPrintRow; - for(i=0; imaxlen ) maxlen = len; - } - nPrintCol = 80/(maxlen+2); - if( nPrintCol<1 ) nPrintCol = 1; - nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; - for(i=0; iout, "%s%-*s", zSp, maxlen, - azResult[j] ? azResult[j]:""); - } - raw_printf(p->out, "\n"); - } - } - - for(ii=0; iiout = output_file_open("testcase-out.txt", 0); - if( p->out==0 ){ - raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); - } - if( nArg>=2 ){ - sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); - }else{ - sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); - } - }else - -#ifndef SQLITE_UNTESTABLE - if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ - static const struct { - const char *zCtrlName; /* Name of a test-control option */ - int ctrlCode; /* Integer code for that option */ - const char *zUsage; /* Usage notes */ - } aCtrl[] = { - { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, - { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, - /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ - /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ - { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, - { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" }, - /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" },*/ - { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, - { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" }, - { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, - { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, - { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, -#ifdef YYCOVERAGE - { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, -#endif - { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, - { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, - { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, - { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" }, - }; - int testctrl = -1; - int iCtrl = -1; - int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ - int isOk = 0; - int i, n2; - const char *zCmd = 0; - - open_db(p, 0); - zCmd = nArg>=2 ? azArg[1] : "help"; - - /* The argument can optionally begin with "-" or "--" */ - if( zCmd[0]=='-' && zCmd[1] ){ - zCmd++; - if( zCmd[0]=='-' && zCmd[1] ) zCmd++; - } - - /* --help lists all test-controls */ - if( strcmp(zCmd,"help")==0 ){ - utf8_printf(p->out, "Available test-controls:\n"); - for(i=0; iout, " .testctrl %s %s\n", - aCtrl[i].zCtrlName, aCtrl[i].zUsage); - } - rc = 1; - goto meta_command_exit; - } - - /* convert testctrl text option to value. allow any unique prefix - ** of the option name, or a numerical value. */ - n2 = strlen30(zCmd); - for(i=0; idb, opt); - isOk = 3; - } - break; - - /* sqlite3_test_control(int) */ - case SQLITE_TESTCTRL_PRNG_SAVE: - case SQLITE_TESTCTRL_PRNG_RESTORE: - case SQLITE_TESTCTRL_PRNG_RESET: - case SQLITE_TESTCTRL_BYTEORDER: - if( nArg==2 ){ - rc2 = sqlite3_test_control(testctrl); - isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; - } - break; - - /* sqlite3_test_control(int, uint) */ - case SQLITE_TESTCTRL_PENDING_BYTE: - if( nArg==3 ){ - unsigned int opt = (unsigned int)integerValue(azArg[2]); - rc2 = sqlite3_test_control(testctrl, opt); - isOk = 3; - } - break; - - /* sqlite3_test_control(int, int, sqlite3*) */ - case SQLITE_TESTCTRL_PRNG_SEED: - if( nArg==3 || nArg==4 ){ - int ii = (int)integerValue(azArg[2]); - sqlite3 *db; - if( ii==0 && strcmp(azArg[2],"random")==0 ){ - sqlite3_randomness(sizeof(ii),&ii); - printf("-- random seed: %d\n", ii); - } - if( nArg==3 ){ - db = 0; - }else{ - db = p->db; - /* Make sure the schema has been loaded */ - sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); - } - rc2 = sqlite3_test_control(testctrl, ii, db); - isOk = 3; - } - break; - - /* sqlite3_test_control(int, int) */ - case SQLITE_TESTCTRL_ASSERT: - case SQLITE_TESTCTRL_ALWAYS: - if( nArg==3 ){ - int opt = booleanValue(azArg[2]); - rc2 = sqlite3_test_control(testctrl, opt); - isOk = 1; - } - break; - - /* sqlite3_test_control(int, int) */ - case SQLITE_TESTCTRL_LOCALTIME_FAULT: - case SQLITE_TESTCTRL_NEVER_CORRUPT: - if( nArg==3 ){ - int opt = booleanValue(azArg[2]); - rc2 = sqlite3_test_control(testctrl, opt); - isOk = 3; - } - break; - - /* sqlite3_test_control(sqlite3*) */ - case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: - rc2 = sqlite3_test_control(testctrl, p->db); - isOk = 3; - break; - - case SQLITE_TESTCTRL_IMPOSTER: - if( nArg==5 ){ - rc2 = sqlite3_test_control(testctrl, p->db, - azArg[2], - integerValue(azArg[3]), - integerValue(azArg[4])); - isOk = 3; - } - break; - -#ifdef YYCOVERAGE - case SQLITE_TESTCTRL_PARSER_COVERAGE: - if( nArg==2 ){ - sqlite3_test_control(testctrl, p->out); - isOk = 3; - } -#endif - } - } - if( isOk==0 && iCtrl>=0 ){ - utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); - rc = 1; - }else if( isOk==1 ){ - raw_printf(p->out, "%d\n", rc2); - }else if( isOk==2 ){ - raw_printf(p->out, "0x%08x\n", rc2); - } - }else -#endif /* !defined(SQLITE_UNTESTABLE) */ - - if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ - open_db(p, 0); - sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); - }else - - if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ - if( nArg==2 ){ - enableTimer = booleanValue(azArg[1]); - if( enableTimer && !HAS_TIMER ){ - raw_printf(stderr, "Error: timer not available on this system.\n"); - enableTimer = 0; - } - }else{ - raw_printf(stderr, "Usage: .timer on|off\n"); - rc = 1; - } - }else - -#ifndef SQLITE_OMIT_TRACE - if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ - int mType = 0; - int jj; - open_db(p, 0); - for(jj=1; jjeTraceType = SHELL_TRACE_EXPANDED; - } -#ifdef SQLITE_ENABLE_NORMALIZE - else if( optionMatch(z, "normalized") ){ - p->eTraceType = SHELL_TRACE_NORMALIZED; - } -#endif - else if( optionMatch(z, "plain") ){ - p->eTraceType = SHELL_TRACE_PLAIN; - } - else if( optionMatch(z, "profile") ){ - mType |= SQLITE_TRACE_PROFILE; - } - else if( optionMatch(z, "row") ){ - mType |= SQLITE_TRACE_ROW; - } - else if( optionMatch(z, "stmt") ){ - mType |= SQLITE_TRACE_STMT; - } - else if( optionMatch(z, "close") ){ - mType |= SQLITE_TRACE_CLOSE; - } - else { - raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); - rc = 1; - goto meta_command_exit; - } - }else{ - output_file_close(p->traceOut); - p->traceOut = output_file_open(azArg[1], 0); - } - } - if( p->traceOut==0 ){ - sqlite3_trace_v2(p->db, 0, 0, 0); - }else{ - if( mType==0 ) mType = SQLITE_TRACE_STMT; - sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); - } - }else -#endif /* !defined(SQLITE_OMIT_TRACE) */ - -#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) - if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){ - int ii; - int lenOpt; - char *zOpt; - if( nArg<2 ){ - raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n"); - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - zOpt = azArg[1]; - if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; - lenOpt = (int)strlen(zOpt); - if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){ - assert( azArg[nArg]==0 ); - sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); - }else{ - for(ii=1; iidb, azArg[ii], 0, 0); - } - } - }else -#endif - -#if SQLITE_USER_AUTHENTICATION - if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ - if( nArg<2 ){ - raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - if( strcmp(azArg[1],"login")==0 ){ - if( nArg!=4 ){ - raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], - strlen30(azArg[3])); - if( rc ){ - utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); - rc = 1; - } - }else if( strcmp(azArg[1],"add")==0 ){ - if( nArg!=5 ){ - raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), - booleanValue(azArg[4])); - if( rc ){ - raw_printf(stderr, "User-Add failed: %d\n", rc); - rc = 1; - } - }else if( strcmp(azArg[1],"edit")==0 ){ - if( nArg!=5 ){ - raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), - booleanValue(azArg[4])); - if( rc ){ - raw_printf(stderr, "User-Edit failed: %d\n", rc); - rc = 1; - } - }else if( strcmp(azArg[1],"delete")==0 ){ - if( nArg!=3 ){ - raw_printf(stderr, "Usage: .user delete USER\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_delete(p->db, azArg[2]); - if( rc ){ - raw_printf(stderr, "User-Delete failed: %d\n", rc); - rc = 1; - } - }else{ - raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); - rc = 1; - goto meta_command_exit; - } - }else -#endif /* SQLITE_USER_AUTHENTICATION */ - - if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ - utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, - sqlite3_libversion(), sqlite3_sourceid()); -#if SQLITE_HAVE_ZLIB - utf8_printf(p->out, "zlib version %s\n", zlibVersion()); -#endif -#define CTIMEOPT_VAL_(opt) #opt -#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) -#if defined(__clang__) && defined(__clang_major__) - utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." - CTIMEOPT_VAL(__clang_minor__) "." - CTIMEOPT_VAL(__clang_patchlevel__) "\n"); -#elif defined(_MSC_VER) - utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); -#elif defined(__GNUC__) && defined(__VERSION__) - utf8_printf(p->out, "gcc-" __VERSION__ "\n"); -#endif - }else - - if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ - const char *zDbName = nArg==2 ? azArg[1] : "main"; - sqlite3_vfs *pVfs = 0; - if( p->db ){ - sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); - if( pVfs ){ - utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); - raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); - raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); - raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); - } - } - }else - - if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ - sqlite3_vfs *pVfs; - sqlite3_vfs *pCurrent = 0; - if( p->db ){ - sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); - } - for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ - utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, - pVfs==pCurrent ? " <--- CURRENT" : ""); - raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); - raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); - raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); - if( pVfs->pNext ){ - raw_printf(p->out, "-----------------------------------\n"); - } - } - }else - - if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ - const char *zDbName = nArg==2 ? azArg[1] : "main"; - char *zVfsName = 0; - if( p->db ){ - sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); - if( zVfsName ){ - utf8_printf(p->out, "%s\n", zVfsName); - sqlite3_free(zVfsName); - } - } - }else - -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) - if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ - sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; - }else -#endif - - if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ - int j; - assert( nArg<=ArraySize(azArg) ); - p->nWidth = nArg-1; - p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2); - if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); - if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; - for(j=1; jcolWidth[j-1] = (int)integerValue(azArg[j]); - } - }else - - { - utf8_printf(stderr, "Error: unknown command or invalid arguments: " - " \"%s\". Enter \".help\" for help\n", azArg[0]); - rc = 1; - } - -meta_command_exit: - if( p->outCount ){ - p->outCount--; - if( p->outCount==0 ) output_reset(p); - } - return rc; -} - -/* -** Return TRUE if a semicolon occurs anywhere in the first N characters -** of string z[]. -*/ -static int line_contains_semicolon(const char *z, int N){ - int i; - for(i=0; iflgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; - BEGIN_TIMER; - rc = shell_exec(p, zSql, &zErrMsg); - END_TIMER; - if( rc || zErrMsg ){ - char zPrefix[100]; - if( in!=0 || !stdin_is_interactive ){ - sqlite3_snprintf(sizeof(zPrefix), zPrefix, - "Error: near line %d:", startline); - }else{ - sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); - } - if( zErrMsg!=0 ){ - utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); - sqlite3_free(zErrMsg); - zErrMsg = 0; - }else{ - utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); - } - return 1; - }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ - raw_printf(p->out, "changes: %3d total_changes: %d\n", - sqlite3_changes(p->db), sqlite3_total_changes(p->db)); - } - return 0; -} - - -/* -** Read input from *in and process it. If *in==0 then input -** is interactive - the user is typing it it. Otherwise, input -** is coming from a file or device. A prompt is issued and history -** is saved only if input is interactive. An interrupt signal will -** cause this routine to exit immediately, unless input is interactive. -** -** Return the number of errors. -*/ -static int process_input(ShellState *p){ - char *zLine = 0; /* A single input line */ - char *zSql = 0; /* Accumulated SQL text */ - int nLine; /* Length of current line */ - int nSql = 0; /* Bytes of zSql[] used */ - int nAlloc = 0; /* Allocated zSql[] space */ - int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ - int rc; /* Error code */ - int errCnt = 0; /* Number of errors seen */ - int startline = 0; /* Line number for start of current input */ - - p->lineno = 0; - while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ - fflush(p->out); - zLine = one_input_line(p->in, zLine, nSql>0); - if( zLine==0 ){ - /* End of input */ - if( p->in==0 && stdin_is_interactive ) printf("\n"); - break; - } - if( seenInterrupt ){ - if( p->in!=0 ) break; - seenInterrupt = 0; - } - p->lineno++; - if( nSql==0 && _all_whitespace(zLine) ){ - if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); - continue; - } - if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ - if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); - if( zLine[0]=='.' ){ - rc = do_meta_command(zLine, p); - if( rc==2 ){ /* exit requested */ - break; - }else if( rc ){ - errCnt++; - } - } - continue; - } - if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ - memcpy(zLine,";",2); - } - nLine = strlen30(zLine); - if( nSql+nLine+2>=nAlloc ){ - nAlloc = nSql+nLine+100; - zSql = realloc(zSql, nAlloc); - if( zSql==0 ) shell_out_of_memory(); - } - nSqlPrior = nSql; - if( nSql==0 ){ - int i; - for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} - assert( nAlloc>0 && zSql!=0 ); - memcpy(zSql, zLine+i, nLine+1-i); - startline = p->lineno; - nSql = nLine-i; - }else{ - zSql[nSql++] = '\n'; - memcpy(zSql+nSql, zLine, nLine+1); - nSql += nLine; - } - if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) - && sqlite3_complete(zSql) ){ - errCnt += runOneSqlLine(p, zSql, p->in, startline); - nSql = 0; - if( p->outCount ){ - output_reset(p); - p->outCount = 0; - }else{ - clearTempFile(p); - } - }else if( nSql && _all_whitespace(zSql) ){ - if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); - nSql = 0; - } - } - if( nSql && !_all_whitespace(zSql) ){ - errCnt += runOneSqlLine(p, zSql, p->in, startline); - } - free(zSql); - free(zLine); - return errCnt>0; -} - -/* -** Return a pathname which is the user's home directory. A -** 0 return indicates an error of some kind. -*/ -static char *find_home_dir(int clearFlag){ - static char *home_dir = NULL; - if( clearFlag ){ - free(home_dir); - home_dir = 0; - return 0; - } - if( home_dir ) return home_dir; - -#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ - && !defined(__RTP__) && !defined(_WRS_KERNEL) - { - struct passwd *pwent; - uid_t uid = getuid(); - if( (pwent=getpwuid(uid)) != NULL) { - home_dir = pwent->pw_dir; - } - } -#endif - -#if defined(_WIN32_WCE) - /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() - */ - home_dir = "/"; -#else - -#if defined(_WIN32) || defined(WIN32) - if (!home_dir) { - home_dir = getenv("USERPROFILE"); - } -#endif - - if (!home_dir) { - home_dir = getenv("HOME"); - } - -#if defined(_WIN32) || defined(WIN32) - if (!home_dir) { - char *zDrive, *zPath; - int n; - zDrive = getenv("HOMEDRIVE"); - zPath = getenv("HOMEPATH"); - if( zDrive && zPath ){ - n = strlen30(zDrive) + strlen30(zPath) + 1; - home_dir = malloc( n ); - if( home_dir==0 ) return 0; - sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); - return home_dir; - } - home_dir = "c:\\"; - } -#endif - -#endif /* !_WIN32_WCE */ - - if( home_dir ){ - int n = strlen30(home_dir) + 1; - char *z = malloc( n ); - if( z ) memcpy(z, home_dir, n); - home_dir = z; - } - - return home_dir; -} - -/* -** Read input from the file given by sqliterc_override. Or if that -** parameter is NULL, take input from ~/.sqliterc -** -** Returns the number of errors. -*/ -static void process_sqliterc( - ShellState *p, /* Configuration data */ - const char *sqliterc_override /* Name of config file. NULL to use default */ -){ - char *home_dir = NULL; - const char *sqliterc = sqliterc_override; - char *zBuf = 0; - FILE *inSaved = p->in; - int savedLineno = p->lineno; - - if (sqliterc == NULL) { - home_dir = find_home_dir(0); - if( home_dir==0 ){ - raw_printf(stderr, "-- warning: cannot find home directory;" - " cannot read ~/.sqliterc\n"); - return; - } - zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); - sqliterc = zBuf; - } - p->in = fopen(sqliterc,"rb"); - if( p->in ){ - if( stdin_is_interactive ){ - utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); - } - process_input(p); - fclose(p->in); - } - p->in = inSaved; - p->lineno = savedLineno; - sqlite3_free(zBuf); -} - -/* -** Show available command line options -*/ -static const char zOptions[] = -#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) - " -A ARGS... run \".archive ARGS\" and exit\n" -#endif - " -append append the database to the end of the file\n" - " -ascii set output mode to 'ascii'\n" - " -bail stop after hitting an error\n" - " -batch force batch I/O\n" - " -box set output mode to 'box'\n" - " -column set output mode to 'column'\n" - " -cmd COMMAND run \"COMMAND\" before reading stdin\n" - " -csv set output mode to 'csv'\n" -#if defined(SQLITE_ENABLE_DESERIALIZE) - " -deserialize open the database using sqlite3_deserialize()\n" -#endif - " -echo print commands before execution\n" - " -init FILENAME read/process named file\n" - " -[no]header turn headers on or off\n" -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) - " -heap SIZE Size of heap for memsys3 or memsys5\n" -#endif - " -help show this message\n" - " -html set output mode to HTML\n" - " -interactive force interactive I/O\n" - " -json set output mode to 'json'\n" - " -line set output mode to 'line'\n" - " -list set output mode to 'list'\n" - " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" - " -markdown set output mode to 'markdown'\n" -#if defined(SQLITE_ENABLE_DESERIALIZE) - " -maxsize N maximum size for a --deserialize database\n" -#endif - " -memtrace trace all memory allocations and deallocations\n" - " -mmap N default mmap size set to N\n" -#ifdef SQLITE_ENABLE_MULTIPLEX - " -multiplex enable the multiplexor VFS\n" -#endif - " -newline SEP set output row separator. Default: '\\n'\n" - " -nofollow refuse to open symbolic links to database files\n" - " -nullvalue TEXT set text string for NULL values. Default ''\n" - " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" - " -quote set output mode to 'quote'\n" - " -readonly open the database read-only\n" - " -separator SEP set output column separator. Default: '|'\n" -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - " -sorterref SIZE sorter references threshold size\n" -#endif - " -stats print memory stats before each finalize\n" - " -table set output mode to 'table'\n" - " -version show SQLite version\n" - " -vfs NAME use NAME as the default VFS\n" -#ifdef SQLITE_ENABLE_VFSTRACE - " -vfstrace enable tracing of all VFS calls\n" -#endif -#ifdef SQLITE_HAVE_ZLIB - " -zip open the file as a ZIP Archive\n" -#endif -; -static void usage(int showDetail){ - utf8_printf(stderr, - "Usage: %s [OPTIONS] FILENAME [SQL]\n" - "FILENAME is the name of an SQLite database. A new database is created\n" - "if the file does not previously exist.\n", Argv0); - if( showDetail ){ - utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); - }else{ - raw_printf(stderr, "Use the -help option for additional information\n"); - } - exit(1); -} - -/* -** Internal check: Verify that the SQLite is uninitialized. Print a -** error message if it is initialized. -*/ -static void verify_uninitialized(void){ - if( sqlite3_config(-1)==SQLITE_MISUSE ){ - utf8_printf(stdout, "WARNING: attempt to configure SQLite after" - " initialization.\n"); - } -} - -/* -** Initialize the state information in data -*/ -static void main_init(ShellState *data) { - memset(data, 0, sizeof(*data)); - data->normalMode = data->cMode = data->mode = MODE_List; - data->autoExplain = 1; - memcpy(data->colSeparator,SEP_Column, 2); - memcpy(data->rowSeparator,SEP_Row, 2); - data->showHeader = 0; - data->shellFlgs = SHFLG_Lookaside; - verify_uninitialized(); - sqlite3_config(SQLITE_CONFIG_URI, 1); - sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); - sqlite3_config(SQLITE_CONFIG_MULTITHREAD); - sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); - sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); -} - -/* -** Output text to the console in a font that attracts extra attention. -*/ -#ifdef _WIN32 -static void printBold(const char *zText){ -#if !SQLITE_OS_WINRT - HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); - CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; - GetConsoleScreenBufferInfo(out, &defaultScreenInfo); - SetConsoleTextAttribute(out, - FOREGROUND_RED|FOREGROUND_INTENSITY - ); -#endif - printf("%s", zText); -#if !SQLITE_OS_WINRT - SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); -#endif -} -#else -static void printBold(const char *zText){ - printf("\033[1m%s\033[0m", zText); -} -#endif - -/* -** Get the argument to an --option. Throw an error and die if no argument -** is available. -*/ -static char *cmdline_option_value(int argc, char **argv, int i){ - if( i==argc ){ - utf8_printf(stderr, "%s: Error: missing argument to %s\n", - argv[0], argv[argc-1]); - exit(1); - } - return argv[i]; -} - -#ifndef SQLITE_SHELL_IS_UTF8 -# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) -# define SQLITE_SHELL_IS_UTF8 (0) -# else -# define SQLITE_SHELL_IS_UTF8 (1) -# endif -#endif - -#if SQLITE_SHELL_IS_UTF8 -int SQLITE_CDECL main(int argc, char **argv){ -#else -int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ - char **argv; -#endif - char *zErrMsg = 0; - ShellState data; - const char *zInitFile = 0; - int i; - int rc = 0; - int warnInmemoryDb = 0; - int readStdin = 1; - int nCmd = 0; - char **azCmd = 0; - const char *zVfs = 0; /* Value of -vfs command-line option */ -#if !SQLITE_SHELL_IS_UTF8 - char **argvToFree = 0; - int argcToFree = 0; -#endif - - setBinaryMode(stdin, 0); - setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ - stdin_is_interactive = isatty(0); - stdout_is_console = isatty(1); - -#ifdef SQLITE_DEBUG - registerOomSimulator(); -#endif - -#if !defined(_WIN32_WCE) - if( getenv("SQLITE_DEBUG_BREAK") ){ - if( isatty(0) && isatty(2) ){ - fprintf(stderr, - "attach debugger to process %d and press any key to continue.\n", - GETPID()); - fgetc(stdin); - }else{ -#if defined(_WIN32) || defined(WIN32) -#if SQLITE_OS_WINRT - __debugbreak(); -#else - DebugBreak(); -#endif -#elif defined(SIGTRAP) - raise(SIGTRAP); -#endif - } - } -#endif - -#if USE_SYSTEM_SQLITE+0!=1 - if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ - utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", - sqlite3_sourceid(), SQLITE_SOURCE_ID); - exit(1); - } -#endif - main_init(&data); - - /* On Windows, we must translate command-line arguments into UTF-8. - ** The SQLite memory allocator subsystem has to be enabled in order to - ** do this. But we want to run an sqlite3_shutdown() afterwards so that - ** subsequent sqlite3_config() calls will work. So copy all results into - ** memory that does not come from the SQLite memory allocator. - */ -#if !SQLITE_SHELL_IS_UTF8 - sqlite3_initialize(); - argvToFree = malloc(sizeof(argv[0])*argc*2); - argcToFree = argc; - argv = argvToFree + argc; - if( argv==0 ) shell_out_of_memory(); - for(i=0; i=1 && argv && argv[0] ); - Argv0 = argv[0]; - - /* Make sure we have a valid signal handler early, before anything - ** else is done. - */ -#ifdef SIGINT - signal(SIGINT, interrupt_handler); -#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) - SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); -#endif - -#ifdef SQLITE_SHELL_DBNAME_PROC - { - /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name - ** of a C-function that will provide the name of the database file. Use - ** this compile-time option to embed this shell program in larger - ** applications. */ - extern void SQLITE_SHELL_DBNAME_PROC(const char**); - SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); - warnInmemoryDb = 0; - } -#endif - - /* Do an initial pass through the command-line argument to locate - ** the name of the database file, the name of the initialization file, - ** the size of the alternative malloc heap, - ** and the first command to execute. - */ - verify_uninitialized(); - for(i=1; i0x7fff0000 ) szHeap = 0x7fff0000; - sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); -#else - (void)cmdline_option_value(argc, argv, ++i); -#endif - }else if( strcmp(z,"-pagecache")==0 ){ - int n, sz; - sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); - if( sz>70000 ) sz = 70000; - if( sz<0 ) sz = 0; - n = (int)integerValue(cmdline_option_value(argc,argv,++i)); - sqlite3_config(SQLITE_CONFIG_PAGECACHE, - (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); - data.shellFlgs |= SHFLG_Pagecache; - }else if( strcmp(z,"-lookaside")==0 ){ - int n, sz; - sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); - if( sz<0 ) sz = 0; - n = (int)integerValue(cmdline_option_value(argc,argv,++i)); - if( n<0 ) n = 0; - sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); - if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; -#ifdef SQLITE_ENABLE_VFSTRACE - }else if( strcmp(z,"-vfstrace")==0 ){ - extern int vfstrace_register( - const char *zTraceName, - const char *zOldVfsName, - int (*xOut)(const char*,void*), - void *pOutArg, - int makeDefault - ); - vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); -#endif -#ifdef SQLITE_ENABLE_MULTIPLEX - }else if( strcmp(z,"-multiplex")==0 ){ - extern int sqlite3_multiple_initialize(const char*,int); - sqlite3_multiplex_initialize(0, 1); -#endif - }else if( strcmp(z,"-mmap")==0 ){ - sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); - sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - }else if( strcmp(z,"-sorterref")==0 ){ - sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); - sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); -#endif - }else if( strcmp(z,"-vfs")==0 ){ - zVfs = cmdline_option_value(argc, argv, ++i); -#ifdef SQLITE_HAVE_ZLIB - }else if( strcmp(z,"-zip")==0 ){ - data.openMode = SHELL_OPEN_ZIPFILE; -#endif - }else if( strcmp(z,"-append")==0 ){ - data.openMode = SHELL_OPEN_APPENDVFS; -#ifdef SQLITE_ENABLE_DESERIALIZE - }else if( strcmp(z,"-deserialize")==0 ){ - data.openMode = SHELL_OPEN_DESERIALIZE; - }else if( strcmp(z,"-maxsize")==0 && i+10 ){ - utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" - " with \"%s\"\n", z); - return 1; - } - open_db(&data, OPEN_DB_ZIPFILE); - if( z[2] ){ - argv[i] = &z[2]; - arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); - }else{ - arDotCommand(&data, 1, argv+i, argc-i); - } - readStdin = 0; - break; -#endif - }else{ - utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); - raw_printf(stderr,"Use -help for a list of options.\n"); - return 1; - } - data.cMode = data.mode; - } - - if( !readStdin ){ - /* Run all arguments that do not begin with '-' as if they were separate - ** command-line inputs, except for the argToSkip argument which contains - ** the database filename. - */ - for(i=0; i -#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 - -/* -** Macro to disable warnings about missing "break" at the end of a "case". -*/ -#if GCC_VERSION>=7000000 -# define deliberate_fall_through __attribute__((fallthrough)); -#else -# define deliberate_fall_through -#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.33.0" -#define SQLITE_VERSION_NUMBER 3033000 -#define SQLITE_SOURCE_ID "2020-08-14 13:23:32 fca8dc8b578f215a969cd899336378966156154710873e68b3d9ac5881b0ff3f" - -/* -** 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. -** -** Ideally, 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 the database connection is associated with unfinalized prepared -** statements, BLOB handlers, and/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, unclosed BLOB handlers, and/or unfinished sqlite3_backups, -** it returns [SQLITE_OK] regardless, but instead of deallocating the database -** connection immediately, it marks the database connection as an unusable -** "zombie" and makes arrangements to automatically deallocate the database -** connection after all prepared statements are finalized, all BLOB handles -** are closed, and all backups have 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. -** -** ^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_IOERR_DATA (SQLITE_IOERR | (32<<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_BUSY_TIMEOUT (SQLITE_BUSY | (3<<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_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8)) -#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) -#define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8)) -#define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<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_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<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)) -#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) - -/* -** CAPI3REF: Flags For File Open Operations -** -** These bit values are intended for use in the -** 3rd parameter to the [sqlite3_open_v2()] interface and -** in the 4th parameter to the [sqlite3_vfs.xOpen] method. -*/ -#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ -#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ -#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ -#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_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_SUPER_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 */ -#define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */ - -/* Reserved: 0x00F00000 */ -/* Legacy compatibility: */ -#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ - - -/* -** 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 super-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 connection's 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 connection's -** 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]] -** ^Applications 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 is used to configure a VFS -** to block for up to M milliseconds before failing when attempting to -** obtain a file lock using the xLock or xShmLock methods of the VFS. -** The parameter is a pointer to a 32-bit signed integer that contains -** the value that M is to be set to. Before returning, the 32-bit signed -** integer is overwritten with the previous value of M. -** -**
  • [[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 provides 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. -** -**
  • [[SQLITE_FCNTL_CKPT_START]] -** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint -** in wal mode before the client starts to copy pages from the wal -** file to the database file. -** -**
  • [[SQLITE_FCNTL_CKPT_DONE]] -** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint -** in wal mode after the client has finished copying pages from the wal -** file to the database file, but before the *-shm file is updated to -** record the fact that the pages have been checkpointed. -**
-*/ -#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 -#define SQLITE_FCNTL_CKPT_DONE 37 -#define SQLITE_FCNTL_RESERVE_BYTES 38 -#define SQLITE_FCNTL_CKPT_START 39 - -/* 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 due to an oversight, the structure -** of the sqlite3_vfs object changed 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 increased. -** -** 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_SUPER_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 required 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_MAIN] 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_hard_heap_limit64()] -**
  • [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-defined 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_VIEW]] -**
SQLITE_DBCONFIG_ENABLE_VIEW
-**
^This option is used to enable or disable [CREATE VIEW | views]. -** There should be two additional arguments. -** The first argument is an integer which is 0 to disable views, -** positive to enable views 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 views are disabled or enabled -** following this call. The second parameter may be a NULL pointer, in -** which case the view 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: -**
    -**
  1. 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. -**
  2. sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); -**
  3. [sqlite3_exec](db, "[VACUUM]", 0, 0, 0); -**
  4. 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 statements -** 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. -**
-** -** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]] -**
SQLITE_DBCONFIG_TRUSTED_SCHEMA -**
The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to -** assume that database schemas are untainted by malicious content. -** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite -** takes additional defensive steps to protect the application from harm -** including: -**
    -**
  • Prohibit the use of SQL functions inside triggers, views, -** CHECK constraints, DEFAULT clauses, expression indexes, -** partial indexes, or generated columns -** unless those functions are tagged with [SQLITE_INNOCUOUS]. -**
  • Prohibit the use of virtual tables inside of triggers or views -** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS]. -**
-** This setting defaults to "on" for legacy compatibility, however -** all applications are advised to turn it off if possible. This setting -** can also be controlled using the [PRAGMA trusted_schema] statement. -**
-** -** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]] -**
SQLITE_DBCONFIG_LEGACY_FILE_FORMAT -**
The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates -** the legacy file format flag. When activated, this flag causes all newly -** created database file to have a schema format version number (the 4-byte -** integer found at offset 44 into the database header) of 1. This in turn -** means that the resulting database file will be readable and writable by -** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting, -** newly created databases are generally not understandable by SQLite versions -** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there -** is now scarcely any need to generated database files that are compatible -** all the way back to version 3.0.0, and so this setting is of little -** practical use, but is provided so that SQLite can continue to claim the -** ability to generate new database files that are compatible with version -** 3.0.0. -**

Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on, -** the [VACUUM] command will fail with an obscure error when attempting to -** process a table with generated columns and a descending index. This is -** not considered a bug since SQLite versions 3.3.0 and earlier do not support -** either generated columns or decending indexes. -**

-**
-*/ -#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_ENABLE_VIEW 1015 /* int int* */ -#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */ -#define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */ -#define SQLITE_DBCONFIG_MAX 1017 /* 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 statement count 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 columns (M==2) and three rows (N==3). Thus the -** result table has 8 entries. Suppose the result table is stored -** in an array named 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. -** -** 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 built-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() must include, at a minimum, one of the following -** three flag combinations:)^ -** -**
-** ^(
[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().
)^ -**
-** -** In addition to the required flags, the following optional flags are -** also supported: -** -**
-** ^(
[SQLITE_OPEN_URI]
-**
The filename can be interpreted as a URI if this flag is set.
)^ -** -** ^(
[SQLITE_OPEN_MEMORY]
-**
The database will be opened as an in-memory database. The database -** is named by the "filename" argument for the purposes of cache-sharing, -** if shared cache mode is enabled, but the "filename" is otherwise ignored. -**
)^ -** -** ^(
[SQLITE_OPEN_NOMUTEX]
-**
The new database connection will use the "multi-thread" -** [threading mode].)^ This means that separate threads are allowed -** to use SQLite at the same time, as long as each thread is using -** a different [database connection]. -** -** ^(
[SQLITE_OPEN_FULLMUTEX]
-**
The new database connection will use the "serialized" -** [threading mode].)^ This means the multiple threads can safely -** attempt to use the same database connection at the same time. -** (Mutexes will block any actual concurrency, but in this mode -** there is no harm in trying.) -** -** ^(
[SQLITE_OPEN_SHAREDCACHE]
-**
The database is opened [shared cache] enabled, overriding -** the default shared cache setting provided by -** [sqlite3_enable_shared_cache()].)^ -** -** ^(
[SQLITE_OPEN_PRIVATECACHE]
-**
The database is opened [shared cache] disabled, overriding -** the default shared cache setting provided by -** [sqlite3_enable_shared_cache()].)^ -** -** [[OPEN_NOFOLLOW]] ^(
[SQLITE_OPEN_NOFOLLOW]
-**
The database filename is not allowed to be a symbolic link
-**
)^ -** -** If the 3rd parameter to sqlite3_open_v2() is not one of the -** required combinations shown above optionally combined with other -** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] -** then the behavior is undefined. -** -** ^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|custom VFS implementations], -** that check if a database file was a URI that contained a specific query -** parameter, and if so obtains the value of that query parameter. -** -** The first parameter to these interfaces (hereafter referred to -** as F) must be one of: -**
    -**
  • A database filename pointer created by the SQLite core and -** passed into the xOpen() method of a VFS implemention, or -**
  • A filename obtained from [sqlite3_db_filename()], or -**
  • A new filename constructed using [sqlite3_create_filename()]. -**
-** If the F parameter is not one of the above, then the behavior is -** undefined and probably undesirable. Older versions of SQLite were -** more tolerant of invalid F parameters than newer versions. -** -** If F is a suitable filename (as described in the previous paragraph) -** and if 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 and it -** 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 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. -** -** The sqlite3_uri_key(F,N) returns a pointer to the name (not -** the value) of the N-th query parameter for filename F, or a NULL -** pointer if N is less than zero or greater than the number of query -** parameters minus 1. The N value is zero-based so N should be 0 to obtain -** the name of the first query parameter, 1 for the second parameter, and -** so forth. -** -** 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 the SQLite core passed -** into the xOpen VFS method, then the behavior of this routine is undefined -** and probably undesirable. -** -** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F -** parameter can also be the name of a rollback journal file or WAL file -** in addition to the main database file. Prior to version 3.31.0, these -** routines would only work if F was the name of the main database file. -** When the F parameter is the name of the rollback journal or WAL file, -** it has access to all the same query parameters as were found on the -** main database file. -** -** 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); -SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N); - -/* -** CAPI3REF: Translate filenames -** -** These routines are available to [VFS|custom VFS implementations] for -** translating filenames between the main database file, the journal file, -** and the WAL file. -** -** If F is the name of an sqlite database file, journal file, or WAL file -** passed by the SQLite core into the VFS, then sqlite3_filename_database(F) -** returns the name of the corresponding database file. -** -** If F is the name of an sqlite database file, journal file, or WAL file -** passed by the SQLite core into the VFS, or if F is a database filename -** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F) -** returns the name of the corresponding rollback journal file. -** -** If F is the name of an sqlite database file, journal file, or WAL file -** that was passed by the SQLite core into the VFS, or if F is a database -** filename obtained from [sqlite3_db_filename()], then -** sqlite3_filename_wal(F) returns the name of the corresponding -** WAL file. -** -** In all of the above, if F is not the name of a database, journal or WAL -** filename passed into the VFS from the SQLite core and F is not the -** return value from [sqlite3_db_filename()], then the result is -** undefined and is likely a memory access violation. -*/ -SQLITE_API const char *sqlite3_filename_database(const char*); -SQLITE_API const char *sqlite3_filename_journal(const char*); -SQLITE_API const char *sqlite3_filename_wal(const char*); - -/* -** CAPI3REF: Database File Corresponding To A Journal -** -** ^If X is the name of a rollback or WAL-mode journal file that is -** passed into the xOpen method of [sqlite3_vfs], then -** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file] -** object that represents the main database file. -** -** This routine is intended for use in custom [VFS] implementations -** only. It is not a general-purpose interface. -** The argument sqlite3_file_object(X) must be a filename pointer that -** has been passed into [sqlite3_vfs].xOpen method where the -** flags parameter to xOpen contains one of the bits -** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use -** of this routine results in undefined and probably undesirable -** behavior. -*/ -SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*); - -/* -** CAPI3REF: Create and Destroy VFS Filenames -** -** These interfces are provided for use by [VFS shim] implementations and -** are not useful outside of that context. -** -** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of -** database filename D with corresponding journal file J and WAL file W and -** with N URI parameters key/values pairs in the array P. The result from -** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that -** is safe to pass to routines like: -**
    -**
  • [sqlite3_uri_parameter()], -**
  • [sqlite3_uri_boolean()], -**
  • [sqlite3_uri_int64()], -**
  • [sqlite3_uri_key()], -**
  • [sqlite3_filename_database()], -**
  • [sqlite3_filename_journal()], or -**
  • [sqlite3_filename_wal()]. -**
-** If a memory allocation error occurs, sqlite3_create_filename() might -** return a NULL pointer. The memory obtained from sqlite3_create_filename(X) -** must be released by a corresponding call to sqlite3_free_filename(Y). -** -** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array -** of 2*N pointers to strings. Each pair of pointers in this array corresponds -** to a key and value for a query parameter. The P parameter may be a NULL -** pointer if N is zero. None of the 2*N pointers in the P array may be -** NULL pointers and key pointers should not be empty strings. -** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may -** be NULL pointers, though they can be empty strings. -** -** The sqlite3_free_filename(Y) routine releases a memory allocation -** previously obtained from sqlite3_create_filename(). Invoking -** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op. -** -** If the Y parameter to sqlite3_free_filename(Y) is anything other -** than a NULL pointer or a pointer previously acquired from -** sqlite3_create_filename(), then bad things such as heap -** corruption or segfaults may occur. The value Y should be -** used again after sqlite3_free_filename(Y) has been called. This means -** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y, -** then the corresponding [sqlite3_module.xClose() method should also be -** invoked prior to calling sqlite3_free_filename(Y). -*/ -SQLITE_API char *sqlite3_create_filename( - const char *zDatabase, - const char *zJournal, - const char *zWal, - int nParam, - const char **azParam -); -SQLITE_API void sqlite3_free_filename(char*); - -/* -** 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: -** -**
    -**
  1. Create the prepared statement object using [sqlite3_prepare_v2()]. -**
  2. Bind values to [parameters] using the sqlite3_bind_*() -** interfaces. -**
  3. Run the SQL by calling [sqlite3_step()] one or more times. -**
  4. Reset the prepared statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -**
  5. 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: -** -**
    -**
  1. -** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it -** always used to do, [sqlite3_step()] will automatically recompile the SQL -** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY] -** retries will occur before sqlite3_step() gives up and returns an error. -**
  2. -** -**
  3. -** ^When an error occurs, [sqlite3_step()] will return one of the detailed -** [error codes] or [extended error codes]. ^The legacy behavior was that -** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code -** and the application would have to make a second call to [sqlite3_reset()] -** in order to find the underlying cause of the problem. With the "v2" prepare -** interfaces, the underlying reason for the error is returned immediately. -**
  4. -** -**
  5. -** ^If the specific value bound to a [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 a 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_STAT4] compile-time option is enabled. -**
  6. -**
-** -**

^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: 32766). -** -** ^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(). -** ^If the third parameter to sqlite3_bind_text() is not NULL, then -** it should be a pointer to well-formed UTF8 text. -** ^If the third parameter to sqlite3_bind_text16() is not NULL, then -** it should be a pointer to well-formed UTF16 text. -** ^If the third parameter to sqlite3_bind_text64() is not NULL, then -** it should be a pointer to a well-formed unicode string that is -** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16 -** otherwise. -** -** [[byte-order determination rules]] ^The byte-order of -** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF) -** found in first character, which is removed, or in the absence of a BOM -** the byte order is the native byte order of the host -** machine for sqlite3_bind_text16() or the byte order specified in -** the 6th parameter for sqlite3_bind_text64().)^ -** ^If UTF16 input text contains invalid unicode -** characters, then SQLite might change those invalid characters -** into the unicode replacement character: U+FFFD. -** -** ^(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 occurs 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 routines 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 -** [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()] family 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} -** 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 fourth parameter may also optionally include the [SQLITE_DIRECTONLY] -** flag, which if present prevents the function from being invoked from -** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions, -** index expressions, or the WHERE clause of partial indexes. -** -** -** For best security, the [SQLITE_DIRECTONLY] flag is recommended for -** all application-defined SQL functions that do not need to be -** used inside of triggers, view, CHECK constraints, or other elements of -** the database schema. This flags is especially recommended for SQL -** functions that have side effects or reveal internal application state. -** Without this flag, an attacker might be able to modify the schema of -** a database file to include invocations of the function with parameters -** chosen by the attacker, which the application will then execute when -** the database file is opened and read. -** -** -** ^(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()]. -** -**
-** [[SQLITE_DETERMINISTIC]]
SQLITE_DETERMINISTIC
-** The SQLITE_DETERMINISTIC flag means that the new function always gives -** the same output when the input parameters are the same. -** The [abs|abs() function] is deterministic, for example, but -** [randomblob|randomblob()] is not. Functions must -** be deterministic in order to be used in certain contexts such as -** with the WHERE clause of [partial indexes] or in [generated columns]. -** SQLite might also optimize deterministic functions by factoring them -** out of inner loops. -**
-** -** [[SQLITE_DIRECTONLY]]
SQLITE_DIRECTONLY
-** The SQLITE_DIRECTONLY flag means that the function may only be invoked -** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in -** schema structures such as [CHECK constraints], [DEFAULT clauses], -** [expression indexes], [partial indexes], or [generated columns]. -** The SQLITE_DIRECTONLY flags is a security feature which is recommended -** for all [application-defined SQL functions], and especially for functions -** that have side-effects or that could potentially leak sensitive -** information. -**
-** -** [[SQLITE_INNOCUOUS]]
SQLITE_INNOCUOUS
-** The SQLITE_INNOCUOUS flag means that the function is unlikely -** to cause problems even if misused. An innocuous function should have -** no side effects and should not depend on any values other than its -** input parameters. The [abs|abs() function] is an example of an -** innocuous function. -** The [load_extension() SQL function] is not innocuous because of its -** side effects. -**

SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not -** exactly the same. The [random|random() function] is an example of a -** function that is innocuous but not deterministic. -**

Some heightened security settings -** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF]) -** disable the use of SQL functions inside views and triggers and in -** schema structures such as [CHECK constraints], [DEFAULT clauses], -** [expression indexes], [partial indexes], and [generated columns] unless -** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions -** are innocuous. Developers are advised to avoid using the -** SQLITE_INNOCUOUS flag for application-defined functions unless the -** function has been carefully audited and found to be free of potentially -** security-adverse side-effects and information-leaks. -**

-** -** [[SQLITE_SUBTYPE]]
SQLITE_SUBTYPE
-** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call -** [sqlite3_value_subtype()] to inspect the sub-types of its arguments. -** Specifying this flag makes no difference for scalar or aggregate user -** functions. However, if it is not specified for a user-defined window -** function, then any sub-types belonging to arguments passed to the window -** function may be discarded before the window function is called (i.e. -** sqlite3_value_subtype() will always return 0). -**
-**
-*/ -#define SQLITE_DETERMINISTIC 0x000000800 -#define SQLITE_DIRECTONLY 0x000080000 -#define SQLITE_SUBTYPE 0x000100000 -#define SQLITE_INNOCUOUS 0x000200000 - -/* -** 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 the functions that -** implement [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, -** or an 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 bytes 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 any 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 using -** the same [byte-order determination rules] as [sqlite3_bind_text16()]. -** ^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. -** -** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and -** sqlite3_result_text16be() routines, and for sqlite3_result_text64() -** when the encoding is not UTF8, if the input UTF16 begins with a -** byte-order mark (BOM, U+FEFF) then the BOM is removed from the -** string and the rest of the string is interpreted according to the -** byte-order specified by the BOM. ^The byte-order specified by -** the BOM at the beginning of the text overrides the byte-order -** specified by the interface procedure. ^So, for example, if -** sqlite3_result_text16le() is invoked with text that begins -** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the -** first two bytes of input are skipped and the remaining input -** is interpreted as UTF16BE text. -** -** ^For UTF16 input text to the sqlite3_result_text16(), -** sqlite3_result_text16be(), sqlite3_result_text16le(), and -** sqlite3_result_text64() routines, if the text contains invalid -** UTF16 characters, the invalid characters might be converted -** into the unicode replacement character, U+FFFD. -** -** ^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, xCompare. -** ^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, xCompare, 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 xCompare 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 two integer parameters to the collating -** function callback are the length of the two strings, in bytes. The collating -** function must return an integer that is negative, zero, or positive -** if the first string is less than, equal to, or greater than the second, -** respectively. A collating function must always return the same answer -** given the same inputs. If two or more collating functions are registered -** to the same collation name (using different eTextRep values) then all -** must give an equivalent answer when invoked with equivalent strings. -** The collating function must obey the following properties for all -** strings A, B, and C: -** -**
    -**
  1. If A==B then B==A. -**
  2. If A==B and B==C then A==C. -**
  3. If A<B THEN B>A. -**
  4. If A<B and B<C then A<C. -**
-** -** If a collating function fails any of the above constraints and that -** collating function is registered and used, then the behavior of SQLite -** is undefined. -** -** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** with the addition that the xDestroy callback is invoked on pArg when -** the collating function is deleted. -** ^Collating functions are deleted when they are overridden by later -** calls to the collation creation functions or when the -** [database connection] is closed using [sqlite3_close()]. -** -** ^The xDestroy callback is not called if the -** sqlite3_create_collation_v2() function fails. Applications that invoke -** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should -** check the return code and dispose of the application data pointer -** themselves rather than expecting SQLite to deal with it for them. -** This is different from every other SQLite interface. The inconsistency -** is unfortunate but cannot be changed without breaking backwards -** compatibility. -** -** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. -*/ -SQLITE_API int sqlite3_create_collation( - sqlite3*, - 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_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 the filename -** associated with database N of connection D. -** ^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 string value returned by this routine is owned and managed by -** the database connection. ^The value will be valid until the database N -** is [DETACH]-ed or until the database connection closes. -** -** ^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. -** -** If the filename pointer returned by this routine is not NULL, then it -** can be used as the filename input parameter to these routines: -**
    -**
  • [sqlite3_uri_parameter()] -**
  • [sqlite3_uri_boolean()] -**
  • [sqlite3_uri_int64()] -**
  • [sqlite3_filename_database()] -**
  • [sqlite3_filename_journal()] -**
  • [sqlite3_filename_wal()] -**
-*/ -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_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 to 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. It is recommended that it stay -** that way. In other words, do not use this routine. This interface -** continues to be provided for historical compatibility, but its use is -** discouraged. Any use of shared cache is discouraged. If shared cache -** must be used, it is recommended that shared cache only be enabled for -** individual database connections using the [sqlite3_open_v2()] interface -** with the [SQLITE_OPEN_SHAREDCACHE] flag. -** -** 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 -** -** These interfaces impose limits on the amount of heap memory that will be -** by all database connections within a single process. -** -** ^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 sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of -** N bytes on the amount of memory that will be allocated. ^The -** sqlite3_hard_heap_limit64(N) interface is similar to -** sqlite3_soft_heap_limit64(N) except that memory allocations will fail -** when the hard heap limit is reached. -** -** ^The return value from both sqlite3_soft_heap_limit64() and -** sqlite3_hard_heap_limit64() is the size of -** the 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 heap limit. Hence, the current -** size of heap limits can be determined by invoking -** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1). -** -** ^Setting the heap limits to zero disables the heap limiter mechanism. -** -** ^The soft heap limit may not be greater than the hard heap limit. -** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N) -** is invoked with a value of N that is greater than the hard heap limit, -** the the soft heap limit is set to the value of the hard heap limit. -** ^The soft heap limit is automatically enabled whenever the hard heap -** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and -** the soft heap limit is outside the range of 1..N, then the soft heap -** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the -** hard heap limit is enabled makes the soft heap limit equal to the -** hard heap limit. -** -** The memory allocation limits can also be adjusted using -** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit]. -** -** ^(The heap limits are not enforced in the current implementation -** if one or more of following conditions are true: -** -**
    -**
  • The limit value 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. -**
)^ -** -** The circumstances under which SQLite will enforce the heap limits may -** changes in future releases of SQLite. -*/ -SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); -SQLITE_API sqlite3_int64 sqlite3_hard_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 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 enabled 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 table]. -** 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 might not be checked again by the byte code.)^ ^(The -** aConstraintUsage[].omit flag is an optimization hint. When the omit flag -** is left in its default setting of false, the constraint will always be -** checked separately in byte code. If the omit flag is change to true, then -** the constraint may or may not be checked in byte code. In other words, -** when the omit flag is true there is no guarantee that the constraint will -** not be checked again using byte code.)^ -** -** ^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 include 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 define 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. -** -** ^If the third parameter (the pointer to the sqlite3_module object) is -** NULL then no new module is create and any existing modules with the -** same name are dropped. -** -** See also: [sqlite3_drop_modules()] -*/ -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: Remove Unnecessary Virtual Table Implementations -** METHOD: sqlite3 -** -** ^The sqlite3_drop_modules(D,L) interface removes all virtual -** table modules from database connection D except those named on list L. -** The L parameter must be either NULL or a pointer to an array of pointers -** to strings where the array is terminated by a single NULL pointer. -** ^If the L parameter is NULL, then all virtual table modules are removed. -** -** See also: [sqlite3_create_module()] -*/ -SQLITE_API int sqlite3_drop_modules( - sqlite3 *db, /* Remove modules from this connection */ - const char **azKeep /* Except, do not remove the ones named here */ -); - -/* -** 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_MAIN -**
  • 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_MAIN 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 */ - -/* Legacy compatibility: */ -#define SQLITE_MUTEX_STATIC_MASTER 2 - - -/* -** 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 /* NOT USED */ -#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 /* NOT USED */ -#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_PRNG_SEED 28 -#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29 -#define SQLITE_TESTCTRL_LAST 29 /* 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: -**
    -**
  1. ^The sqlite3_str object is created using [sqlite3_str_new()]. -**
  2. ^Text is appended to the sqlite3_str object using various -** methods, such as [sqlite3_str_appendf()]. -**
  3. ^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 the [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 of 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 resolved 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 changes 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 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: -**
    -**
  1. sqlite3_backup_init() is called once to initialize the -** backup, -**
  2. sqlite3_backup_step() is called one or more times to transfer -** the data between the two databases, and finally -**
  3. sqlite3_backup_finish() is called to release all resources -** associated with the backup operation. -**
)^ -** There should be exactly one call to sqlite3_backup_finish() for each -** successful call to sqlite3_backup_init(). -** -** [[sqlite3_backup_init()]] sqlite3_backup_init() -** -** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the -** [database connection] associated with the destination database -** and the database name, respectively. -** ^The database name is "main" for the main database, "temp" for the -** temporary database, or the name specified after the AS keyword in -** an [ATTACH] statement for an attached database. -** ^The S and M arguments passed to -** sqlite3_backup_init(D,N,S,M) identify the [database connection] -** and database name of the source database, respectively. -** ^The source and destination [database connections] (parameters S and D) -** must be different or else sqlite3_backup_init(D,N,S,M) will fail with -** an error. -** -** ^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 -**
    -**
  1. the destination database was opened read-only, or -**
  2. the destination database is using write-ahead-log journaling -** and the destination and source page sizes differ, or -**
  3. the destination database is an in-memory database and the -** destination and source page sizes differ. -**
)^ -** -** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then -** the [sqlite3_busy_handler | busy-handler function] -** is invoked (if one is specified). ^If the -** busy-handler returns non-zero before the lock is available, then -** [SQLITE_BUSY] is returned to the caller. ^In this case the call to -** sqlite3_backup_step() can be retried later. ^If the source -** [database connection] -** is being used to write to the source database when sqlite3_backup_step() -** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this -** case the call to sqlite3_backup_step() can be retried later on. ^(If -** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or -** [SQLITE_READONLY] is returned, then -** there is no point in retrying the call to sqlite3_backup_step(). These -** errors are considered fatal.)^ The application must accept -** that the backup operation has failed and pass the backup operation handle -** to the sqlite3_backup_finish() to release associated resources. -** -** ^The first call to sqlite3_backup_step() obtains an exclusive lock -** on the destination file. ^The exclusive lock is not released until either -** sqlite3_backup_finish() is called or the backup operation is complete -** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to -** sqlite3_backup_step() obtains a [shared lock] on the source database that -** lasts for the duration of the sqlite3_backup_step() call. -** ^Because the source database is not locked between calls to -** sqlite3_backup_step(), the source database may be modified mid-way -** through the backup process. ^If the source database is modified by an -** external process or via a database connection other than the one being -** used by the backup operation, then the backup will be automatically -** restarted by the next call to sqlite3_backup_step(). ^If the source -** database is modified by the using the same database connection as is used -** by the backup operation, then the backup database is automatically -** updated at the same time. -** -** [[sqlite3_backup_finish()]] sqlite3_backup_finish() -** -** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the -** application wishes to abandon the backup operation, the application -** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). -** ^The sqlite3_backup_finish() interfaces releases all -** resources associated with the [sqlite3_backup] object. -** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any -** active write-transaction on the destination database is rolled back. -** The [sqlite3_backup] object is invalid -** and may not be used following a call to sqlite3_backup_finish(). -** -** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no -** sqlite3_backup_step() errors occurred, regardless or whether or not -** sqlite3_backup_step() completed. -** ^If an out-of-memory condition or IO error occurred during any prior -** sqlite3_backup_step() call on the same [sqlite3_backup] object, then -** sqlite3_backup_finish() returns the corresponding [error code]. -** -** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() -** is not a permanent error and does not affect the return value of -** sqlite3_backup_finish(). -** -** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]] -** sqlite3_backup_remaining() and sqlite3_backup_pagecount() -** -** ^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 connection's 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 connection's 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. -** -** In the call sqlite3_vtab_config(D,C,...) the D parameter is the -** [database connection] in which the virtual table is being created and -** which is passed in as the first argument to the [xConnect] or [xCreate] -** method that is invoking sqlite3_vtab_config(). The C parameter is one -** of the [virtual table configuration options]. The presence and meaning -** of parameters after C depend on which [virtual table configuration option] -** is used. -*/ -SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); - -/* -** CAPI3REF: Virtual Table Configuration Options -** KEYWORDS: {virtual table configuration options} -** KEYWORDS: {virtual table configuration option} -** -** 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. -**
-** -** [[SQLITE_VTAB_DIRECTONLY]]
SQLITE_VTAB_DIRECTONLY
-**
Calls of the form -** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the -** the [xConnect] or [xCreate] methods of a [virtual table] implmentation -** prohibits that virtual table from being used from within triggers and -** views. -**
-** -** [[SQLITE_VTAB_INNOCUOUS]]
SQLITE_VTAB_INNOCUOUS
-**
Calls of the form -** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the -** the [xConnect] or [xCreate] methods of a [virtual table] implmentation -** identify that virtual table as being safe to use from within triggers -** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the -** virtual table can do no serious harm even if it is controlled by a -** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS -** flag unless absolutely necessary. -**
-**
-*/ -#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 -#define SQLITE_VTAB_INNOCUOUS 2 -#define SQLITE_VTAB_DIRECTONLY 3 - -/* -** 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 V 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 V 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 V 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 V 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 V 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 V 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_sequence 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 are 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 is 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 the 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 state -** of 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 application's 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: -** -**
    -**
  1. An sqlite3_rebaser object is created by calling -** sqlite3rebaser_create(). -**
  2. 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. -**
  3. Each local changeset is rebased by calling sqlite3rebaser_rebase(). -**
  4. 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 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 functionNon-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 function's -** "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: -** -**
  1. By mapping all synonyms to a single token. In this case, using -** 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. -** -**
  2. 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. -** -**
  3. 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. -** If the value exceeds 32767 then extra space is required for the Expr -** structure. But otherwise, we believe that the number can be as large -** as a signed 32-bit integer can hold. -*/ -#ifndef SQLITE_MAX_VARIABLE_NUMBER -# define SQLITE_MAX_VARIABLE_NUMBER 32766 -#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 - -/* -** WAL mode depends on atomic aligned 32-bit loads and stores in a few -** places. The following macros try to make this explicit. -*/ -#ifndef __has_extension -# define __has_extension(x) 0 /* compatibility with non-clang compilers */ -#endif -#if GCC_VERSION>=4007000 || __has_extension(c_atomic) -# define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED) -# define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED) -#else -# define AtomicLoad(PTR) (*(PTR)) -# define AtomicStore(PTR,VAL) (*(PTR) = (VAL)) -#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(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)) -#elif 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)) -#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 - -/* -** The harmless(X) macro indicates that expression X is usually false -** but can be true without causing any problems, but we don't know of -** any way to cause X to be true. -** -** In debugging and testing builds, this macro will abort if X is ever -** true. In this way, developers are alerted to a possible test case -** that causes X to be true. If a harmless macro ever fails, that is -** an opportunity to change the macro into a testcase() and add a new -** test case to the test suite. -** -** For normal production builds, harmless(X) is a no-op, since it does -** not matter whether expression X is true or false. -*/ -#ifdef SQLITE_DEBUG -# define harmless(X) assert(!(X)); -#else -# define harmless(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_NULLS 82 -#define TK_FIRST 83 -#define TK_LAST 84 -#define TK_CURRENT 85 -#define TK_FOLLOWING 86 -#define TK_PARTITION 87 -#define TK_PRECEDING 88 -#define TK_RANGE 89 -#define TK_UNBOUNDED 90 -#define TK_EXCLUDE 91 -#define TK_GROUPS 92 -#define TK_OTHERS 93 -#define TK_TIES 94 -#define TK_GENERATED 95 -#define TK_ALWAYS 96 -#define TK_REINDEX 97 -#define TK_RENAME 98 -#define TK_CTIME_KW 99 -#define TK_ANY 100 -#define TK_BITAND 101 -#define TK_BITOR 102 -#define TK_LSHIFT 103 -#define TK_RSHIFT 104 -#define TK_PLUS 105 -#define TK_MINUS 106 -#define TK_STAR 107 -#define TK_SLASH 108 -#define TK_REM 109 -#define TK_CONCAT 110 -#define TK_COLLATE 111 -#define TK_BITNOT 112 -#define TK_ON 113 -#define TK_INDEXED 114 -#define TK_STRING 115 -#define TK_JOIN_KW 116 -#define TK_CONSTRAINT 117 -#define TK_DEFAULT 118 -#define TK_NULL 119 -#define TK_PRIMARY 120 -#define TK_UNIQUE 121 -#define TK_CHECK 122 -#define TK_REFERENCES 123 -#define TK_AUTOINCR 124 -#define TK_INSERT 125 -#define TK_DELETE 126 -#define TK_UPDATE 127 -#define TK_SET 128 -#define TK_DEFERRABLE 129 -#define TK_FOREIGN 130 -#define TK_DROP 131 -#define TK_UNION 132 -#define TK_ALL 133 -#define TK_EXCEPT 134 -#define TK_INTERSECT 135 -#define TK_SELECT 136 -#define TK_VALUES 137 -#define TK_DISTINCT 138 -#define TK_DOT 139 -#define TK_FROM 140 -#define TK_JOIN 141 -#define TK_USING 142 -#define TK_ORDER 143 -#define TK_GROUP 144 -#define TK_HAVING 145 -#define TK_LIMIT 146 -#define TK_WHERE 147 -#define TK_INTO 148 -#define TK_NOTHING 149 -#define TK_FLOAT 150 -#define TK_BLOB 151 -#define TK_INTEGER 152 -#define TK_VARIABLE 153 -#define TK_CASE 154 -#define TK_WHEN 155 -#define TK_THEN 156 -#define TK_ELSE 157 -#define TK_INDEX 158 -#define TK_ALTER 159 -#define TK_ADD 160 -#define TK_WINDOW 161 -#define TK_OVER 162 -#define TK_FILTER 163 -#define TK_COLUMN 164 -#define TK_AGG_FUNCTION 165 -#define TK_AGG_COLUMN 166 -#define TK_TRUEFALSE 167 -#define TK_ISNOT 168 -#define TK_FUNCTION 169 -#define TK_UMINUS 170 -#define TK_UPLUS 171 -#define TK_TRUTH 172 -#define TK_REGISTER 173 -#define TK_VECTOR 174 -#define TK_SELECT_COLUMN 175 -#define TK_IF_NULL_ROW 176 -#define TK_ASTERISK 177 -#define TK_SPAN 178 -#define TK_SPACE 179 -#define TK_ILLEGAL 180 - -/************** 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 LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<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 - -/* -** 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 -#if defined(SQLITE_ENABLE_SELECTTRACE) -# define SELECTTRACE_ENABLED 1 -# define SELECTTRACE(K,P,S,X) \ - if(sqlite3_unsupported_selecttrace&(K)) \ - sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\ - sqlite3DebugPrintf X -#else -# define SELECTTRACE(K,P,S,X) -# 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 */ -}; - -/* -** Name of table that holds the database schema. -*/ -#define DFLT_SCHEMA_TABLE "sqlite_master" -#define DFLT_TEMP_SCHEMA_TABLE "sqlite_temp_master" -#define ALT_SCHEMA_TABLE "sqlite_schema" -#define ALT_TEMP_SCHEMA_TABLE "sqlite_temp_schema" - - -/* -** The root-page of the schema table. -*/ -#define SCHEMA_ROOT 1 - -/* -** The name of the schema table. The name is different for TEMP. -*/ -#define SCHEMA_TABLE(x) \ - ((!OMIT_TEMPDB)&&(x==1)?DFLT_TEMP_SCHEMA_TABLE:DFLT_SCHEMA_TABLE) - -/* -** 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)sqlite3OomFault) - -/* -** 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 MASKBIT64(n) (((u64)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 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 super-journal name - there are no more pages to -** roll back. See comments for function writeSuperJournal() 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); -SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager*, Pgno); -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 *zSuper, int); -SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); -SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper); -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*, sqlite3_snapshot **ppSnapshot); -SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager*, 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 - -#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT) -SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager*, int); -SQLITE_PRIVATE void sqlite3PagerWalDb(Pager*, sqlite3*); -#else -# define sqlite3PagerWalWriteLock(y,z) SQLITE_OK -# define sqlite3PagerWalDb(x,y) -#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(const 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 *); - -/* Functions used to truncate the database file. */ -SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); - -SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16); - -/* 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 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 Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno); -SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(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*); -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*, Pgno*, 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 */ - Pgno 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*); -SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*); -SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(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(sqlite3*,Btree*,Pgno*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*); - -SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*); - -#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 */ - u32 *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_IfNotOpen 26 /* jump, synopsis: if( !csr[P1] ) goto P2 */ -#define OP_IfNoHope 27 /* jump, synopsis: key=r[P3@P4] */ -#define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */ -#define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */ -#define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */ -#define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */ -#define OP_Last 33 /* jump */ -#define OP_IfSmaller 34 /* jump */ -#define OP_SorterSort 35 /* jump */ -#define OP_Sort 36 /* jump */ -#define OP_Rewind 37 /* jump */ -#define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */ -#define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */ -#define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */ -#define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */ -#define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */ -#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_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */ -#define OP_Program 46 /* jump */ -#define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */ -#define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ -#define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, 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_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */ -#define OP_IncrVacuum 60 /* jump */ -#define OP_VNext 61 /* jump */ -#define OP_Init 62 /* jump, synopsis: Start at P2 */ -#define OP_PureFunc 63 /* synopsis: r[P3]=func(r[P2@NP]) */ -#define OP_Function 64 /* synopsis: r[P3]=func(r[P2@NP]) */ -#define OP_Return 65 -#define OP_EndCoroutine 66 -#define OP_HaltIfNull 67 /* synopsis: if r[P3]=null halt */ -#define OP_Halt 68 -#define OP_Integer 69 /* synopsis: r[P2]=P1 */ -#define OP_Int64 70 /* synopsis: r[P2]=P4 */ -#define OP_String 71 /* synopsis: r[P2]='P4' (len=P1) */ -#define OP_Null 72 /* synopsis: r[P2..P3]=NULL */ -#define OP_SoftNull 73 /* synopsis: r[P1]=NULL */ -#define OP_Blob 74 /* synopsis: r[P2]=P4 (len=P1) */ -#define OP_Variable 75 /* synopsis: r[P2]=parameter(P1,P4) */ -#define OP_Move 76 /* synopsis: r[P2@P3]=r[P1@P3] */ -#define OP_Copy 77 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ -#define OP_SCopy 78 /* synopsis: r[P2]=r[P1] */ -#define OP_IntCopy 79 /* synopsis: r[P2]=r[P1] */ -#define OP_ResultRow 80 /* synopsis: output=r[P1@P2] */ -#define OP_CollSeq 81 -#define OP_AddImm 82 /* synopsis: r[P1]=r[P1]+P2 */ -#define OP_RealAffinity 83 -#define OP_Cast 84 /* synopsis: affinity(r[P1]) */ -#define OP_Permutation 85 -#define OP_Compare 86 /* synopsis: r[P1@P3] <-> r[P2@P3] */ -#define OP_IsTrue 87 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */ -#define OP_Offset 88 /* synopsis: r[P3] = sqlite_offset(P1) */ -#define OP_Column 89 /* synopsis: r[P3]=PX */ -#define OP_Affinity 90 /* synopsis: affinity(r[P1@P2]) */ -#define OP_MakeRecord 91 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ -#define OP_Count 92 /* synopsis: r[P2]=count() */ -#define OP_ReadCookie 93 -#define OP_SetCookie 94 -#define OP_ReopenIdx 95 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenRead 96 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenWrite 97 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenDup 98 -#define OP_OpenAutoindex 99 /* synopsis: nColumn=P2 */ -#define OP_OpenEphemeral 100 /* synopsis: nColumn=P2 */ -#define OP_BitAnd 101 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ -#define OP_BitOr 102 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ -#define OP_ShiftLeft 103 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<>r[P1] */ -#define OP_Add 105 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ -#define OP_Subtract 106 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ -#define OP_Multiply 107 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ -#define OP_Divide 108 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ -#define OP_Remainder 109 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ -#define OP_Concat 110 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ -#define OP_SorterOpen 111 -#define OP_BitNot 112 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */ -#define OP_SequenceTest 113 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ -#define OP_OpenPseudo 114 /* synopsis: P3 columns in r[P2] */ -#define OP_String8 115 /* same as TK_STRING, synopsis: r[P2]='P4' */ -#define OP_Close 116 -#define OP_ColumnsUsed 117 -#define OP_SeekHit 118 /* synopsis: seekHit=P2 */ -#define OP_Sequence 119 /* synopsis: r[P2]=cursor[P1].ctr++ */ -#define OP_NewRowid 120 /* synopsis: r[P2]=rowid */ -#define OP_Insert 121 /* synopsis: intkey=r[P3] data=r[P2] */ -#define OP_Delete 122 -#define OP_ResetCount 123 -#define OP_SorterCompare 124 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ -#define OP_SorterData 125 /* synopsis: r[P2]=data */ -#define OP_RowData 126 /* synopsis: r[P2]=data */ -#define OP_Rowid 127 /* synopsis: r[P2]=rowid */ -#define OP_NullRow 128 -#define OP_SeekEnd 129 -#define OP_IdxInsert 130 /* synopsis: key=r[P2] */ -#define OP_SorterInsert 131 /* synopsis: key=r[P2] */ -#define OP_IdxDelete 132 /* synopsis: key=r[P2@P3] */ -#define OP_DeferredSeek 133 /* synopsis: Move P3 to P1.rowid if needed */ -#define OP_IdxRowid 134 /* synopsis: r[P2]=rowid */ -#define OP_FinishSeek 135 -#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_DropTrigger 145 -#define OP_IntegrityCk 146 -#define OP_RowSetAdd 147 /* synopsis: rowset(P1)=r[P2] */ -#define OP_Param 148 -#define OP_FkCounter 149 /* synopsis: fkctr[P1]+=P2 */ -#define OP_Real 150 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ -#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_CursorLock 159 -#define OP_CursorUnlock 160 -#define OP_TableLock 161 /* synopsis: iDb=P1 root=P2 write=P3 */ -#define OP_VBegin 162 -#define OP_VCreate 163 -#define OP_VDestroy 164 -#define OP_VOpen 165 -#define OP_VColumn 166 /* synopsis: r[P3]=vcolumn(P2) */ -#define OP_VRename 167 -#define OP_Pagecount 168 -#define OP_MaxPgcnt 169 -#define OP_Trace 170 -#define OP_CursorHint 171 -#define OP_ReleaseReg 172 /* synopsis: release r[P1@P2] mask P3 */ -#define OP_Noop 173 -#define OP_Explain 174 -#define OP_Abortable 175 - -/* 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, 0x01, 0x09, 0x09, 0x09, 0x09, 0x09,\ -/* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\ -/* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\ -/* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\ -/* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00,\ -/* 64 */ 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\ -/* 72 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\ -/* 80 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12,\ -/* 88 */ 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\ -/* 96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26, 0x26,\ -/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\ -/* 112 */ 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,\ -/* 120 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\ -/* 128 */ 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10, 0x00,\ -/* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\ -/* 144 */ 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x10, 0x04,\ -/* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 168 */ 0x10, 0x10, 0x00, 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 62 /* 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 Parse *sqlite3VdbeParser(Vdbe*); -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 int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,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*, int addr, u8); -SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); -SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); -SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5); -SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); -SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr); -SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr); -SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op); -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int); -#else -# define sqlite3VdbeReleaseRegisters(P,A,N,M,F) -#endif -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*); - -SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); -SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*); - -SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*); -#ifdef SQLITE_ENABLE_BYTECODE_VTAB -SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*); -#endif - -/* 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 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 -SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); -#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_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. -** -** New lookaside allocations are only allowed if bDisable==0. When -** bDisable is greater than zero, sz is set to zero which effectively -** disables lookaside without adding a new test for the bDisable flag -** in a performance-critical path. sz should be set by to szTrue whenever -** bDisable changes back to zero. -** -** Lookaside buffers are initially held on the pInit list. As they are -** used and freed, they are added back to the pFree list. New allocations -** come off of pFree first, then pInit as a fallback. This dual-list -** allows use to compute a high-water mark - the maximum number of allocations -** outstanding at any point in the past - by subtracting the number of -** allocations on the pInit list from the total number of allocations. -** -** Enhancement on 2019-12-12: Two-size-lookaside -** The default lookaside configuration is 100 slots of 1200 bytes each. -** The larger slot sizes are important for performance, but they waste -** a lot of space, as most lookaside allocations are less than 128 bytes. -** The two-size-lookaside enhancement breaks up the lookaside allocation -** into two pools: One of 128-byte slots and the other of the default size -** (1200-byte) slots. Allocations are filled from the small-pool first, -** failing over to the full-size pool if that does not work. Thus more -** lookaside slots are available while also using less memory. -** This enhancement can be omitted by compiling with -** SQLITE_OMIT_TWOSIZE_LOOKASIDE. -*/ -struct Lookaside { - u32 bDisable; /* Only operate the lookaside when zero */ - u16 sz; /* Size of each buffer in bytes */ - u16 szTrue; /* True value of sz, even if disabled */ - 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 */ -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - LookasideSlot *pSmallInit; /* List of small buffers not prediously used */ - LookasideSlot *pSmallFree; /* List of available small buffers */ - void *pMiddle; /* First byte past end of full-size buffers and - ** the first byte of LOOKASIDE_SMALL buffers */ -#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ - 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 */ -}; - -#define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0 -#define EnableLookaside db->lookaside.bDisable--;\ - db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue - -/* Size of the smaller allocations in two-size lookside */ -#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE -# define LOOKASIDE_SMALL 0 -#else -# define LOOKASIDE_SMALL 128 -#endif - -/* -** 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; /* BINARY collseq for the database encoding */ - 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 */ - Pgno 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 */ - char **azInit; /* "type", "name", and "tbl_name" columns */ - } 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 */ - union { - void (*xLegacy)(void*,const char*); /* Legacy trace function */ - int (*xV2)(u32,void*,void*,void*); /* V2 Trace function */ - } trace; - 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 nAnalysisLimit; /* Number of index rows to ANALYZE */ - 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_MAIN - ** 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) - -/* -** A u64 constant where the lower 32 bits are all zeros. Only the -** upper 32 bits are included in the argument. Necessary because some -** C-compilers still do not accept LL integer literals. -*/ -#define HI(X) ((u64)(X)<<32) - -/* -** 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_SCHEMA */ -#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_TrustedSchema 0x00000080 /* Allow unsafe functions and - ** vtabs in the schema definition */ -#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*/ -#define SQLITE_EnableView 0x80000000 /* Enable the use of views */ -#define SQLITE_CountRows HI(0x00001) /* Count rows changed by INSERT, */ - /* DELETE, or UPDATE and return */ - /* the count using a callback. */ - -/* Flags used only if debugging */ -#ifdef SQLITE_DEBUG -#define SQLITE_SqlTrace HI(0x0100000) /* Debug print SQL as it executes */ -#define SQLITE_VdbeListing HI(0x0200000) /* Debug listings of VDBE progs */ -#define SQLITE_VdbeTrace HI(0x0400000) /* True to trace VDBE execution */ -#define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */ -#define SQLITE_VdbeEQP HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */ -#define SQLITE_ParserTrace HI(0x2000000) /* 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 */ -#define DBFLAG_InternalFunc 0x0020 /* Allow use of internal functions */ -#define DBFLAG_EncodingFixed 0x0040 /* No longer possible to change enc. */ - -/* -** 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_Stat4 0x0800 /* Use STAT4 data */ - /* TH3 expects the Stat4 ^^^^^^ 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_DIRECT == SQLITE_DIRECTONLY from the API -** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS -** 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 */ -/* 0x0200 -- available for reuse */ -#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_TEST 0x4000 /* Built-in testing functions */ -#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 */ -#define SQLITE_FUNC_DIRECT 0x00080000 /* Not for use in TRIGGERs or VIEWs */ -#define SQLITE_FUNC_SUBTYPE 0x00100000 /* Result likely to have sub-type */ -#define SQLITE_FUNC_UNSAFE 0x00200000 /* Function has side effects */ -#define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */ - -/* Identifier numbers for each in-line function */ -#define INLINEFUNC_coalesce 0 -#define INLINEFUNC_implies_nonnull_row 1 -#define INLINEFUNC_expr_implies_expr 2 -#define INLINEFUNC_expr_compare 3 -#define INLINEFUNC_affinity 4 -#define INLINEFUNC_iif 5 -#define INLINEFUNC_unlikely 99 /* Default case */ - -/* -** 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. -** -** SFUNCTION(zName, nArg, iArg, bNC, xFunc) -** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and -** adds the SQLITE_DIRECTONLY flag. -** -** INLINE_FUNC(zName, nArg, iFuncId, mFlags) -** zName is the name of a function that is implemented by in-line -** byte code rather than by the usual callbacks. The iFuncId -** parameter determines the function id. The mFlags parameter is -** optional SQLITE_FUNC_ flags for this function. -** -** TEST_FUNC(zName, nArg, iFuncId, mFlags) -** zName is the name of a test-only function implemented by in-line -** byte code rather than by the usual callbacks. The iFuncId -** parameter determines the function id. The mFlags parameter is -** optional SQLITE_FUNC_ flags for this function. -** -** 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 SFUNCTION(zName, nArg, iArg, bNC, xFunc) \ - {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} } -#define INLINE_FUNC(zName, nArg, iArg, mFlags) \ - {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \ - SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} } -#define TEST_FUNC(zName, nArg, iArg, mFlags) \ - {nArg, SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \ - SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \ - SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 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 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() */ - int nRefModule; /* Number of pointers to this object */ - 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 the Column structure, in the Table.aCol[] array. -** -** Definitions: -** -** "table column index" This is the index of the column in the -** Table.aCol[] array, and also the index of -** the column in the original CREATE TABLE stmt. -** -** "storage column index" This is the index of the column in the -** record BLOB generated by the OP_MakeRecord -** opcode. The storage column index is less than -** or equal to the table column index. It is -** equal if and only if there are no VIRTUAL -** columns to the left. -*/ -struct Column { - char *zName; /* Name of this column, \000, then the type */ - Expr *pDflt; /* Default value or GENERATED ALWAYS AS value */ - 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 hName; /* Column name hash for faster lookup */ - u16 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 */ -#define COLFLAG_VIRTUAL 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */ -#define COLFLAG_STORED 0x0040 /* GENERATED ALWAYS AS ... STORED */ -#define COLFLAG_NOTAVAIL 0x0080 /* STORED column not yet calculated */ -#define COLFLAG_BUSY 0x0100 /* Blocks recursion on GENERATED columns */ -#define COLFLAG_GENERATED 0x0060 /* Combo: _STORED, _VIRTUAL */ -#define COLFLAG_NOINSERT 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */ - -/* -** 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_NONE 0x40 /* '@' */ -#define SQLITE_AFF_BLOB 0x41 /* 'A' */ -#define SQLITE_AFF_TEXT 0x42 /* 'B' */ -#define SQLITE_AFF_NUMERIC 0x43 /* 'C' */ -#define SQLITE_AFF_INTEGER 0x44 /* 'D' */ -#define SQLITE_AFF_REAL 0x45 /* '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 */ - u8 eVtabRisk; /* Riskiness of allowing hacker access */ - int iSavepoint; /* Depth of the SAVEPOINT stack */ - VTable *pNext; /* Next in linked list (see above) */ -}; - -/* Allowed values for VTable.eVtabRisk -*/ -#define SQLITE_VTABRISK_Low 0 -#define SQLITE_VTABRISK_Normal 1 -#define SQLITE_VTABRISK_High 2 - -/* -** 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 */ - Pgno 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 */ - i16 nNVCol; /* Number of columns that are not VIRTUAL */ - 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. The "OOO" means "Out Of Order". -** -** Constraints: -** -** TF_HasVirtual == COLFLAG_Virtual -** TF_HasStored == COLFLAG_Stored -*/ -#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_HasVirtual 0x0020 /* Has one or more VIRTUAL columns */ -#define TF_HasStored 0x0040 /* Has one or more STORED columns */ -#define TF_HasGenerated 0x0060 /* Combo: HasVirtual + HasStored */ -#define TF_WithoutRowid 0x0080 /* No rowid. PRIMARY KEY is the key */ -#define TF_StatsUsed 0x0100 /* Query planner decisions affected by - ** Index.aiRowLogEst[] values */ -#define TF_NoVisibleRowid 0x0200 /* No user-visible "rowid" column */ -#define TF_OOOHidden 0x0400 /* Out-of-Order hidden columns */ -#define TF_HasNotNull 0x0800 /* Contains NOT NULL constraints */ -#define TF_Shadow 0x1000 /* 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) -# define ExprIsVtab(X) \ - ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->nModuleArg) -#else -# define IsVirtual(X) 0 -# define ExprIsVtab(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 *aSortFlags; /* Sort order for each column. */ - CollSeq *aColl[1]; /* Collating sequence for each term of the key */ -}; - -/* -** Allowed bit values for entries in the KeyInfo.aSortFlags[] array. -*/ -#define KEYINFO_ORDER_DESC 0x01 /* DESC sort order */ -#define KEYINFO_ORDER_BIGNULL 0x02 /* NULL is larger than any other value */ - -/* -** 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_schema -** 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 */ - Pgno 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 */ - unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */ -#ifdef SQLITE_ENABLE_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_stat4 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.iAgg 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 */ - Expr *pCExpr; /* The original expression */ - int iTable; /* Cursor number of the source table */ - int iMem; /* Memory location that acts as accumulator */ - i16 iColumn; /* Column number within the source table */ - i16 iSorterColumn; /* Column number in the sorting index */ - } *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 *pFExpr; /* 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[] */ - u32 selId; /* Select to which this AggInfo belongs */ - AggInfo *pNext; /* Next in list of them all */ -}; - -/* -** 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 32766 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 affExpr; /* affinity, or RAISE type */ - 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 - ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */ -#ifdef SQLITE_DEBUG - u8 vvaFlags; /* Verification flags. */ -#endif - 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_IN: ephemerial table holding RHS - ** TK_SELECT_COLUMN: Number of columns on the LHS - ** 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 */ - 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; /* EP_WinFunc: Window/Filter defn for a function */ - 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_Commuted 0x000200 /* Comparison operator has been commuted */ -#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 */ - /* 0x020000 // available for reuse */ -#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 */ -#define EP_FromDDL 0x40000000 /* Originates from sqlite_schema */ - /* 0x80000000 // Available */ - -/* -** 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) - - -/* Flags for use with Expr.vvaFlags -*/ -#define EP_NoReduce 0x01 /* Cannot EXPRDUP_REDUCE this Expr */ -#define EP_Immutable 0x02 /* Do not change this Expr node */ - -/* 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)->vvaFlags|=(P) -# define ExprHasVVAProperty(E,P) (((E)->vvaFlags&(P))!=0) -# define ExprClearVVAProperties(E) (E)->vvaFlags = 0 -#else -# define ExprSetVVAProperty(E,P) -# define ExprHasVVAProperty(E,P) 0 -# define ExprClearVVAProperties(E) -#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 */ - -/* -** True if the expression passed as an argument was a function with -** an OVER() clause (a window function). -*/ -#ifdef SQLITE_OMIT_WINDOWFUNC -# define IsWindowFunc(p) 0 -#else -# define IsWindowFunc(p) ( \ - ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \ - ) -#endif - -/* -** 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. -** -** In order to try to keep memory usage down, the Expr.a.zEName field -** is used for multiple purposes: -** -** eEName Usage -** ---------- ------------------------- -** ENAME_NAME (1) the AS of result set column -** (2) COLUMN= of an UPDATE -** -** ENAME_TAB DB.TABLE.NAME used to resolve names -** of subqueries -** -** ENAME_SPAN Text of the original result set -** expression. -*/ -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 *zEName; /* Token associated with this expression */ - u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */ - unsigned eEName :2; /* Meaning of zEName */ - unsigned done :1; /* A flag to indicate when processing is finished */ - unsigned reusable :1; /* Constant expression is reusable */ - unsigned bSorterRef :1; /* Defer evaluation until after sorting */ - unsigned bNulls: 1; /* True if explicit "NULLS FIRST/LAST" */ - 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 */ -}; - -/* -** Allowed values for Expr.a.eEName -*/ -#define ENAME_NAME 0 /* The AS clause of a result set */ -#define ENAME_SPAN 1 /* Complete text of the result set expression */ -#define ENAME_TAB 2 /* "DB.TABLE.NAME" for the result set */ - -/* -** 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 */ - unsigned fromDDL :1; /* Comes from sqlite_schema */ - } 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 0x00001 /* Aggregate functions are allowed here */ -#define NC_PartIdx 0x00002 /* True if resolving a partial index WHERE */ -#define NC_IsCheck 0x00004 /* True if resolving a CHECK constraint */ -#define NC_GenCol 0x00008 /* True for a GENERATED ALWAYS AS clause */ -#define NC_HasAgg 0x00010 /* One or more aggregate functions seen */ -#define NC_IdxExpr 0x00020 /* True if resolving columns of CREATE INDEX */ -#define NC_SelfRef 0x0002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */ -#define NC_VarSelect 0x00040 /* A correlated subquery has been seen */ -#define NC_UEList 0x00080 /* True if uNC.pEList is used */ -#define NC_UAggInfo 0x00100 /* True if uNC.pAggInfo is used */ -#define NC_UUpsert 0x00200 /* True if uNC.pUpsert is used */ -#define NC_MinMaxAgg 0x01000 /* min/max aggregates seen. See note above */ -#define NC_Complex 0x02000 /* True if a function or subquery seen */ -#define NC_AllowWin 0x04000 /* Window functions are allowed here */ -#define NC_HasWin 0x08000 /* One or more window functions seen */ -#define NC_IsDDL 0x10000 /* Resolving names in a CREATE statement */ -#define NC_InAggFunc 0x20000 /* True if analyzing arguments to an agg func */ -#define NC_FromDDL 0x40000 /* SQL text comes from sqlite_schema */ - -/* -** 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 { - 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 */ - ExprList *pEList; /* The fields of the result */ - 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 0x0000001 /* Output should be DISTINCT */ -#define SF_All 0x0000002 /* Includes the ALL keyword */ -#define SF_Resolved 0x0000004 /* Identifiers have been resolved */ -#define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */ -#define SF_HasAgg 0x0000010 /* Contains aggregate functions */ -#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */ -#define SF_Expanded 0x0000040 /* sqlite3SelectExpand() called on this */ -#define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */ -#define SF_Compound 0x0000100 /* Part of a compound query */ -#define SF_Values 0x0000200 /* Synthesized from VALUES clause */ -#define SF_MultiValue 0x0000400 /* Single VALUES term with multiple rows */ -#define SF_NestedFrom 0x0000800 /* Part of a parenthesized FROM clause */ -#define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */ -#define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */ -#define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */ -#define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */ -#define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */ -#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */ -#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */ -#define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */ -#define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */ -#define SF_View 0x0200000 /* SELECT statement is a view */ -#define SF_NoopOrderBy 0x0400000 /* ORDER BY is ignored for this query */ -#define SF_UpdateFrom 0x0800000 /* Statement is an UPDATE...FROM */ - -/* -** 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. -** -** SRT_Upfrom Store results in the temporary table already opened by -** pDest->iSDParm. If (pDest->iSDParm<0), then the temp -** table is an intkey table - in this case the first -** column returned by the SELECT is used as the integer -** key. If (pDest->iSDParm>0), then the table is an index -** table. (pDest->iSDParm) is the number of key columns in -** each index record in this case. -*/ -#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 */ -#define SRT_Upfrom 15 /* Store result as data with 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. One of SRT_* above. */ - int iSDParm; /* A parameter used by the eDest disposal method */ - int iSDParm2; /* A second parameter for 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 */ - AggInfo *pAggList; /* List of all AggInfo objects */ - 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 */ - u8 eParseMode; /* PARSE_MODE_XXX constant */ -#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 2 -#define PARSE_MODE_UNMAP 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) -#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 */ - SrcList *pFrom; /* FROM clause for UPDATE statement (if any) */ - 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 */ - u8 bTemp; /* True for TEMP schema entries */ - 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 */ - Pgno mxPage; /* Maximum page number. 0 for no limit. */ -} 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 */ - u8 bCoreMutex; /* True to enable core mutexing */ - u8 bFullMutex; /* True to enable full mutexing */ - u8 bOpenUri; /* True to interpret filenames as URIs */ - u8 bUseCis; /* Use covering indices for full-scans */ - u8 bSmallMalloc; /* Avoid large memory allocations if true */ - u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */ - 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 iOnceResetThreshold; /* When to reset OP_Once counters */ - u32 szSorterRef; /* Min size in bytes to use sorter-refs */ - unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */ -}; - -/* -** 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 */ - u16 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 */ - struct Table *pTab; /* Table of generated column */ - struct SrcList_item *pSrcItem; /* A single FROM clause item */ - } 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*); -SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*); -SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(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, most (but not all) related to window -** functions. -** -** (1) A single instance of this structure is attached to the -** the Expr.y.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. -** -** (4) For an aggregate function with a FILTER clause, an instance -** of this object is stored in Expr.y.pWin with eFrmType set to -** TK_FILTER. In this case the only field used is Window.pFilter. -** -** 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 **ppThis; /* Pointer to this object in Select.pWin list */ - 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; /* Accumulator */ - int regResult; /* Interim result */ - 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; - u8 bExprArgs; /* Defer evaluation of window function arguments - ** due to the SQLITE_SUBTYPE flag */ -}; - -#ifndef SQLITE_OMIT_WINDOWFUNC -SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*); -SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(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 void sqlite3WindowLink(Select *pSel, Window *pWin); -SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*, int); -SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*); -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); -# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__) -# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__) -#else -# define SQLITE_NOMEM_BKPT SQLITE_NOMEM -# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM -#endif -#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO) -SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno); -# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P)) -#else -# 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 sqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*); -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,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*,char); -SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char); -SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int); -SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*); -SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16); -#ifdef SQLITE_OMIT_GENERATED_COLUMNS -# define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */ -# define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */ -#else -SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table*, i16); -SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table*, i16); -#endif -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 sqlite3AddGenerated(Parse*,Expr*,Token*); -SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*); -SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*, - sqlite3_vfs**,char**,char **); -#define sqlite3CodecQueryParameters(A,B,C) 0 -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*); -#ifndef SQLITE_OMIT_GENERATED_COLUMNS -SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(Parse*, int, Table*); -#endif -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 *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2); -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 int sqlite3WhereUsesDeferredSeek(WhereInfo*); -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); -#ifndef SQLITE_OMIT_GENERATED_COLUMNS -SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Column*, int); -#endif -SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int); -SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int); -SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); -SQLITE_PRIVATE int sqlite3ExprCodeTarget(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 sqlite3AggInfoPersistWalkerInit(Walker*,Parse*); -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 u32 sqlite3IsTrueOrFalse(const char*); -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*,SrcList*,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); -SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*); -# 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 -# define sqlite3TriggerStepSrc(A,B) 0 -#endif - -SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); -SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int); -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 int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName); -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 void sqlite3Int64ToText(i64,char*); -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8); -SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*); -SQLITE_PRIVATE int sqlite3GetUInt32(const char*, u32*); -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_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 getVarint32NR(A,B) \ - B=(u32)*(A);if(B>=0x80)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(const Expr *pExpr, char aff2); -SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity); -SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int); -SQLITE_PRIVATE char sqlite3ExprAffinity(const 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 void sqlite3SetTextEncoding(sqlite3 *db, u8); -SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr); -SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr); -SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const 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 Expr *sqlite3ExprSkipCollateAndLikely(Expr*); -SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *); -SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*); -SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,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 SQLITE_WSD struct Sqlite3Config sqlite3Config; -SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; -SQLITE_API extern u32 sqlite3_unsupported_selecttrace; -#ifndef SQLITE_OMIT_WSD -SQLITE_PRIVATE int sqlite3PendingByte; -#endif -#endif /* SQLITE_AMALGAMATION */ -#ifdef VDBE_PROFILE -SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt; -#endif -SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno); -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 sqlite3MatchEName( - const struct ExprList_item*, - const char*, - const char*, - const char* -); -SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*); -SQLITE_PRIVATE u8 sqlite3StrIHash(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*); -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); -SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*); - -#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_STAT4 -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, Pgno, 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 sqlite3VtabModuleUnref(D,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 sqlite3VtabModuleUnref(sqlite3*,Module*); -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 sqlite3ReadOnlyShadowTables(sqlite3 *db); -#ifndef SQLITE_OMIT_VIRTUALTABLE -SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName); -SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*); -#else -# define sqlite3ShadowTableName(A,B) 0 -# define sqlite3IsShadowTableOf(A,B,C) 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 *sqlite3ExprCompareCollSeq(Parse*,const Expr*); -SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const 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. -*/ -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 ........ */ -}; - -/* 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. -*/ -#ifndef SQLITE_USE_URI -# define SQLITE_USE_URI 0 -#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); -** -** With the two-size-lookaside enhancement, less lookaside is required. -** The default configuration of 1200,40 actually provides 30 1200-byte slots -** and 93 128-byte slots, which is more lookaside than is available -** using the older 1200,100 configuration without two-size-lookaside. -*/ -#ifndef SQLITE_DEFAULT_LOOKASIDE -# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE -# define SQLITE_DEFAULT_LOOKASIDE 1200,100 /* 120KB of memory */ -# else -# define SQLITE_DEFAULT_LOOKASIDE 1200,40 /* 48KB of memory */ -# endif -#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 */ - 1, /* bExtraSchemaChecks */ - 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 */ - 0x7ffffffe, /* iOnceResetThreshold */ - SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */ - 0, /* iPrngSeed */ -}; - -/* -** Hash table for global functions - functions common to all -** database connections. After initialization, this table is -** read-only. -*/ -SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; - -#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 - -/* -** Flags for select tracing and the ".selecttrace" macro of the CLI -*/ -SQLITE_API u32 sqlite3_unsupported_selecttrace = 0; - -/* #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) \ - || defined(SQLITE_ENABLE_BYTECODE_VTAB) -# 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 */ - u32 *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_TypeMask)==(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 */ - u8 doingRerun; /* True if rerunning after an auto-reprepare */ - bft expired:2; /* 1: recompile VM immediately 2: when convenient */ - bft explain:2; /* True if EXPLAIN present on SQL command */ - 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 SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor*); -SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, u32*); -SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*); -SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32); -SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8); -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*); -#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB) -SQLITE_PRIVATE int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**); -SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3*,Op*); -#endif -#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) -SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*); -#endif -#if !defined(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 int sqlite3VdbeMemCast(Mem*,u8,u8); -SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,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 -#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB) -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, StrAccum *pStr); -#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); -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - nInit += countLookasideSlots(db->lookaside.pSmallInit); - nFree += countLookasideSlots(db->lookaside.pSmallFree); -#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ - 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; - } -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - p = db->lookaside.pSmallFree; - if( p ){ - while( p->pNext ) p = p->pNext; - p->pNext = db->lookaside.pSmallInit; - db->lookaside.pSmallInit = db->lookaside.pSmallFree; - db->lookaside.pSmallFree = 0; - } -#endif - } - 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; - /* no break */ deliberate_fall_through - 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_MAIN); -#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, 1000.0 }, - { 0, 6, "minute", 7737817680.0, 60000.0 }, - { 0, 4, "hour", 128963628.0, 3600000.0 }, - { 0, 3, "day", 5373485.0, 86400000.0 }, - { 1, 5, "month", 176546.0, 2592000000.0 }, - { 2, 4, "year", 14713.0, 31536000000.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 + 0.5); - 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': { - i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000); - sqlite3Int64ToText(iS, &z[j]); - 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_MAIN)); - pTm = gmtime(&t); - if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)); -#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 & 0x1087f7f, 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){ - if( sqlite3Config.iPrngSeed ){ - memset(zBufOut, 0, nByte); - if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int); - memcpy(zBufOut, &sqlite3Config.iPrngSeed, nByte); - return SQLITE_OK; - }else{ - 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_MAIN); -#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_MAIN)) ); - 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_MAIN); ) - 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_MAIN); ) - 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.xFree==sqlite3MemFree ){ - 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.xFree==sqlite3MemFree ){ - 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.xFree==sqlite3MemFree ){ - 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.iKeyBlk free chunk. -** Return a pointer to the new allocation. Or, if the key chunk -** is not large enough, return 0. -*/ -static void *memsys3FromKeyBlk(u32 nBlock){ - assert( sqlite3_mutex_held(mem3.mutex) ); - assert( mem3.szKeyBlk>=nBlock ); - if( nBlock>=mem3.szKeyBlk-1 ){ - /* Use the entire key chunk */ - void *p = memsys3Checkout(mem3.iKeyBlk, mem3.szKeyBlk); - mem3.iKeyBlk = 0; - mem3.szKeyBlk = 0; - mem3.mnKeyBlk = 0; - return p; - }else{ - /* Split the key block. Return the tail. */ - u32 newi, x; - newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock; - assert( newi > mem3.iKeyBlk+1 ); - mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock; - mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2; - mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; - mem3.szKeyBlk -= nBlock; - mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk; - x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; - mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; - if( mem3.szKeyBlk < mem3.mnKeyBlk ){ - mem3.mnKeyBlk = mem3.szKeyBlk; - } - 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.iKeyBlk, it replaces -** the current mem3.iKeyBlk with the new larger chunk. In order for -** this mem3.iKeyBlk replacement to work, the key chunk must be -** linked into the hash tables. That is not the normal state of -** affairs, of course. The calling routine must link the key -** chunk before invoking this routine, then must unlink the (possibly -** changed) key 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.szKeyBlk ){ - mem3.iKeyBlk = i; - mem3.szKeyBlk = 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 key chunk. This step usually works if step 1 fails. - */ - if( mem3.szKeyBlk>=nBlock ){ - return memsys3FromKeyBlk(nBlock); - } - - - /* STEP 3: - ** Loop through the entire memory pool. Coalesce adjacent free - ** chunks. Recompute the key chunk as the largest free chunk. - ** Then try again to satisfy the allocation by carving a piece off - ** of the end of the key chunk. This step happens very - ** rarely (we hope!) - */ - for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){ - memsys3OutOfMemory(toFree); - if( mem3.iKeyBlk ){ - memsys3Link(mem3.iKeyBlk); - mem3.iKeyBlk = 0; - mem3.szKeyBlk = 0; - } - for(i=0; i=nBlock ){ - return memsys3FromKeyBlk(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 key using the newly freed chunk */ - if( mem3.iKeyBlk ){ - while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){ - size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize; - mem3.iKeyBlk -= size; - mem3.szKeyBlk += size; - memsys3Unlink(mem3.iKeyBlk); - x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; - mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; - mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk; - } - x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; - while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){ - memsys3Unlink(mem3.iKeyBlk+mem3.szKeyBlk); - mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4; - mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; - mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk; - } - } -} - -/* -** 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.iKeyBlk ? " **key**" : ""); - } - } - 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, "key=%d\n", mem3.iKeyBlk); - fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8); - fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*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 - - sqlite3MemoryBarrier(); - 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_MAIN -**
  • 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 and x86_64 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(__STRICT_ANSI__) && \ - (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(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif !defined(__STRICT_ANSI__) && (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 - - /* - ** asm() is needed for hardware timing support. Without asm(), - ** disable the sqlite3Hwtime() routine. - ** - ** sqlite3Hwtime() is only used for some obscure debugging - ** and analysis configurations, not in any deliverable, so this - ** should not be a great loss. - */ -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_MAIN -**
  • 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 -} - -/* -** Default value of the hard heap limit. 0 means "no limit". -*/ -#ifndef SQLITE_MAX_MEMORY -# define SQLITE_MAX_MEMORY 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 */ - sqlite3_int64 hardLimit; /* The hard upper bound on memory */ - - /* - ** True if heap is nearly "full" where "full" is defined by the - ** sqlite3_soft_heap_limit() setting. - */ - int nearlyFull; -} mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 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. An argument of -** zero disables the limit. A negative argument is a no-op used to -** obtain the return value. -** -** The return value is the value of the heap limit just before this -** interface was called. -** -** If the hard heap limit is enabled, then the soft heap limit cannot -** be disabled nor raised above the hard heap 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; - } - if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){ - n = mem0.hardLimit; - } - mem0.alarmThreshold = n; - nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); - AtomicStore(&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); -} - -/* -** Set the hard heap-size limit for the library. An argument of zero -** disables the hard heap limit. A negative argument is a no-op used -** to obtain the return value without affecting the hard heap limit. -** -** The return value is the value of the hard heap limit just prior to -** calling this interface. -** -** Setting the hard heap limit will also activate the soft heap limit -** and constrain the soft heap limit to be no more than the hard heap -** limit. -*/ -SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){ - sqlite3_int64 priorLimit; -#ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); - if( rc ) return -1; -#endif - sqlite3_mutex_enter(mem0.mutex); - priorLimit = mem0.hardLimit; - if( n>=0 ){ - mem0.hardLimit = n; - if( n0 ); - - /* 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); - - sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n); - if( mem0.alarmThreshold>0 ){ - sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); - if( nUsed >= mem0.alarmThreshold - nFull ){ - AtomicStore(&mem0.nearlyFull, 1); - sqlite3MallocAlarm(nFull); - if( mem0.hardLimit ){ - nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); - if( nUsed >= mem0.hardLimit - nFull ){ - *pp = 0; - return; - } - } - }else{ - AtomicStore(&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); -} -static int lookasideMallocSize(sqlite3 *db, void *p){ -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - return plookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL; -#else - return db->lookaside.szTrue; -#endif -} -SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){ - assert( p!=0 ); -#ifdef SQLITE_DEBUG - if( db==0 || !isLookaside(db,p) ){ - 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 - if( db ){ - if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ - assert( sqlite3_mutex_held(db->mutex) ); - return LOOKASIDE_SMALL; - } -#endif - if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ - assert( sqlite3_mutex_held(db->mutex) ); - return db->lookaside.szTrue; - } - } - } - return sqlite3GlobalConfig.m.xSize(p); -} -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( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ - LookasideSlot *pBuf = (LookasideSlot*)p; -#ifdef SQLITE_DEBUG - memset(p, 0xaa, LOOKASIDE_SMALL); /* Trash freed content */ -#endif - pBuf->pNext = db->lookaside.pSmallFree; - db->lookaside.pSmallFree = pBuf; - return; - } -#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ - if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ - LookasideSlot *pBuf = (LookasideSlot*)p; -#ifdef SQLITE_DEBUG - memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */ -#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); -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT - if( pNew==0 && mem0.alarmThreshold>0 ){ - sqlite3MallocAlarm((int)nBytes); - pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); - } -#endif - 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( n>db->lookaside.sz ){ - if( !db->lookaside.bDisable ){ - db->lookaside.anStat[1]++; - }else if( db->mallocFailed ){ - return 0; - } - return dbMallocRawFinish(db, n); - } -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - if( n<=LOOKASIDE_SMALL ){ - if( (pBuf = db->lookaside.pSmallFree)!=0 ){ - db->lookaside.pSmallFree = pBuf->pNext; - db->lookaside.anStat[0]++; - return (void*)pBuf; - }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){ - db->lookaside.pSmallInit = pBuf->pNext; - db->lookaside.anStat[0]++; - return (void*)pBuf; - } - } -#endif - 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 - 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( ((uptr)p)<(uptr)db->lookaside.pEnd ){ -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){ - if( n<=LOOKASIDE_SMALL ) return p; - }else -#endif - if( ((uptr)p)>=(uptr)db->lookaside.pStart ){ - if( n<=db->lookaside.szTrue ) 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, lookasideMallocSize(db, p)); - sqlite3DbFree(db, p); - } - }else{ - assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - pNew = sqlite3Realloc(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 ); - assert( z!=0 || n==0 ); - assert( (n&0x7fffffff)==n ); - zNew = z ? sqlite3DbMallocRawNN(db, n+1) : 0; - 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 ){ - AtomicStore(&db->u1.isInterrupted, 1); - } - DisableLookaside; - 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; - AtomicStore(&db->u1.isInterrupted, 0); - assert( db->lookaside.bDisable>0 ); - EnableLookaside; - } -} - -/* -** 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 */ - -/* -** Hard limit on the precision of floating-point conversions. -*/ -#ifndef SQLITE_PRINTF_PRECISION_LIMIT -# define SQLITE_FP_PRECISION_LIMIT 100000000 -#endif - -/* -** 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. - */ - assert( width>=0 ); - assert( precision>=(-1) ); - switch( xtype ){ - case etPOINTER: - flag_long = sizeof(char*)==sizeof(i64) ? 2 : - sizeof(char*)==sizeof(long int) ? 1 : 0; - /* no break */ deliberate_fall_through - case etORDINAL: - case etRADIX: - cThousand = 0; - /* no break */ deliberate_fall_through - 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 */ -#ifdef SQLITE_FP_PRECISION_LIMIT - if( precision>SQLITE_FP_PRECISION_LIMIT ){ - precision = SQLITE_FP_PRECISION_LIMIT; - } -#endif - 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 bytes (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 = sqlite3Realloc(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[SQLITE_PRINT_BUF_SIZE*10]; - 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 || acc.accError ); - 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].zEName); - 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 used=%llx", - pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed); - } - if( pItem->zAlias ){ - sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias); - } - if( pItem->fg.jointype & JT_LEFT ){ - sqlite3_str_appendf(&x, " LEFT-JOIN"); - } - if( pItem->fg.fromDDL ){ - sqlite3_str_appendf(&x, " DDL"); - } - 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{ - if( p->selFlags & SF_WhereBegin ){ - sqlite3TreeViewLine(pView, "sqlite3WhereBegin()"); - }else{ - 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 - } - if( p->pEList ){ - sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set"); - } - n--; -#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[200]; - pView = sqlite3TreeViewPush(pView, moreToFollow); - if( pExpr==0 ){ - sqlite3TreeViewLine(pView, "nil"); - sqlite3TreeViewPop(pView); - return; - } - if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags ){ - StrAccum x; - sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0); - sqlite3_str_appendf(&x, " fg.af=%x.%c", - pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n'); - if( ExprHasProperty(pExpr, EP_FromJoin) ){ - sqlite3_str_appendf(&x, " iRJT=%d", pExpr->iRightJoinTable); - } - if( ExprHasProperty(pExpr, EP_FromDDL) ){ - sqlite3_str_appendf(&x, " DDL"); - } - if( ExprHasVVAProperty(pExpr, EP_Immutable) ){ - sqlite3_str_appendf(&x, " IMMUTABLE"); - } - sqlite3StrAccumFinish(&x); - }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 */ - char zOp2[16]; - if( pExpr->op2 ){ - sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2); - }else{ - zOp2[0] = 0; - } - sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s", - pExpr->iColumn, zFlgs, zOp2); - }else{ - sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s", - pExpr->iTable, pExpr->iColumn, - pExpr->y.pTab, 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_LIMIT: zBinOp = "LIMIT"; 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: { - /* COLLATE operators without the EP_Collate flag are intended to - ** emulate collation associated with a table column. These show - ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE - ** operators that appear in the original SQL always have the - ** EP_Collate bit set and appear in treeview output as just "COLLATE" */ - sqlite3TreeViewLine(pView, "%sCOLLATE %Q%s", - !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "", - pExpr->u.zToken, zFlgs); - 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 = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0; -#else - pWin = 0; -#endif - } - if( pExpr->op==TK_AGG_FUNCTION ){ - sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s agg=%d[%d]/%p", - pExpr->op2, pExpr->u.zToken, zFlgs, - pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0, - pExpr->iAgg, pExpr->pAggInfo); - }else if( pExpr->op2!=0 ){ - const char *zOp2; - char zBuf[8]; - sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2); - zOp2 = zBuf; - if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck"; - if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr"; - if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx"; - if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol"; - sqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s", - pExpr->u.zToken, zFlgs, zOp2); - }else{ - sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs); - } - 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, "subquery-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->affExpr ){ - 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: { - char *z = sqlite3_mprintf("VECTOR%s",zFlgs); - sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z); - sqlite3_free(z); - 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].zEName; - int moreToFollow = inExpr - 1; - if( pList->a[i].eEName!=ENAME_NAME ) zName = 0; - 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); \ - } \ -} - -/* -** 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) - { - StrAccum acc; - char zBuf[1000]; - sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); - sqlite3VdbeMemPrettyPrint(pMem, &acc); - fprintf(stderr, "INPUT: %s\n", sqlite3StrAccumFinish(&acc)); - } -#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=0xd800 && c<0xe000 ){ -#ifdef SQLITE_REPLACE_INVALID_UTF - if( c>=0xdc00 || zIn>=zTerm ){ - c = 0xfffd; - }else{ - int c2 = *(zIn++); - c2 += (*(zIn++))<<8; - if( c2<0xdc00 || c2>=0xe000 ){ - zIn -= 2; - c = 0xfffd; - }else{ - c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000; - } - } -#else - if( zIn UTF-8 */ - while( zIn=0xd800 && c<0xe000 ){ -#ifdef SQLITE_REPLACE_INVALID_UTF - if( c>=0xdc00 || zIn>=zTerm ){ - c = 0xfffd; - }else{ - int c2 = (*(zIn++))<<8; - c2 += *(zIn++); - if( c2<0xdc00 || c2>=0xe000 ){ - zIn -= 2; - c = 0xfffd; - }else{ - c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000; - } - } -#else - if( zInn = (int)(z - zOut); - } - *z = 0; - assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); - - c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype)); - sqlite3VdbeMemRelease(pMem); - pMem->flags = c; - 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) - { - StrAccum acc; - char zBuf[1000]; - sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); - sqlite3VdbeMemPrettyPrint(pMem, &acc); - fprintf(stderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc)); - } -#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_UTF16LE ) z++; - while( n=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2; - n++; - } - return (int)(z-(unsigned char const *)zIn) - - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE); -} - -#if defined(SQLITE_TEST) -/* -** This routine is called from the TCL test function "translate_selftest". -** It checks that the primitives for serializing and deserializing -** characters in each encoding are inverses of each other. -*/ -SQLITE_PRIVATE void sqlite3UtfSelfTest(void){ - unsigned int i, t; - unsigned char zBuf[20]; - unsigned char *z; - int n; - unsigned int c; - - for(i=0; i<0x00110000; i++){ - z = zBuf; - WRITE_UTF8(z, i); - n = (int)(z-zBuf); - assert( n>0 && 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 ); - } -} -#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 */ -#ifndef SQLITE_OMIT_FLOATING_POINT -#include -#endif - -/* -** 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; - pParse->pWith = 0; - } -} - -/* -** 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 an 8-bit hash on a string that is insensitive to case differences -*/ -SQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){ - u8 h = 0; - if( z==0 ) return 0; - while( z[0] ){ - h += UpperToLower[(unsigned char)z[0]]; - z++; - } - return h; -} - -/* -** 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. -*/ -#if defined(_MSC_VER) -#pragma warning(disable : 4756) -#endif -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ -#ifndef SQLITE_OMIT_FLOATING_POINT - int incr; - const char *zEnd; - /* 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( length==0 ) return 0; - - if( enc==SQLITE_UTF8 ){ - incr = 1; - zEnd = z + length; - }else{ - int i; - incr = 2; - length &= ~1; - 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 */ -} -#if defined(_MSC_VER) -#pragma warning(default : 4756) -#endif - -/* -** Render an signed 64-bit integer as text. Store the result in zOut[]. -** -** The caller must ensure that zOut[] is at least 21 bytes in size. -*/ -SQLITE_PRIVATE void sqlite3Int64ToText(i64 v, char *zOut){ - int i; - u64 x; - char zTemp[22]; - if( v<0 ){ - x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v; - }else{ - x = v; - } - i = sizeof(zTemp)-2; - zTemp[sizeof(zTemp)-1] = 0; - do{ - zTemp[i--] = (x%10) + '0'; - x = x/10; - }while( x ); - if( v<0 ) zTemp[i--] = '-'; - memcpy(zOut, &zTemp[i+1], sizeof(zTemp)-1-i); -} - -/* -** 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; - sqlite3GetInt32(z, &x); - return x; -} - -/* -** Try to convert z into an unsigned 32-bit integer. Return true on -** success and false if there is an error. -** -** Only decimal notation is accepted. -*/ -SQLITE_PRIVATE int sqlite3GetUInt32(const char *z, u32 *pI){ - u64 v = 0; - int i; - for(i=0; sqlite3Isdigit(z[i]); i++){ - v = v*10 + z[i] - '0'; - if( v>4294967296LL ){ *pI = 0; return 0; } - } - if( i==0 || z[i]!=0 ){ *pI = 0; return 0; } - *pI = (u32)v; - return 1; -} - -/* -** 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; - - n = sqlite3GetVarint(p-2, &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) -/* -** 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_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_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 */ "IfNotOpen" OpHelp("if( !csr[P1] ) goto P2"), - /* 27 */ "IfNoHope" OpHelp("key=r[P3@P4]"), - /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"), - /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"), - /* 30 */ "Found" OpHelp("key=r[P3@P4]"), - /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"), - /* 32 */ "NotExists" OpHelp("intkey=r[P3]"), - /* 33 */ "Last" OpHelp(""), - /* 34 */ "IfSmaller" OpHelp(""), - /* 35 */ "SorterSort" OpHelp(""), - /* 36 */ "Sort" OpHelp(""), - /* 37 */ "Rewind" OpHelp(""), - /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"), - /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"), - /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"), - /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"), - /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), - /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"), - /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"), - /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), - /* 46 */ "Program" OpHelp(""), - /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), - /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), - /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, 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 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), - /* 60 */ "IncrVacuum" OpHelp(""), - /* 61 */ "VNext" OpHelp(""), - /* 62 */ "Init" OpHelp("Start at P2"), - /* 63 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"), - /* 64 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"), - /* 65 */ "Return" OpHelp(""), - /* 66 */ "EndCoroutine" OpHelp(""), - /* 67 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), - /* 68 */ "Halt" OpHelp(""), - /* 69 */ "Integer" OpHelp("r[P2]=P1"), - /* 70 */ "Int64" OpHelp("r[P2]=P4"), - /* 71 */ "String" OpHelp("r[P2]='P4' (len=P1)"), - /* 72 */ "Null" OpHelp("r[P2..P3]=NULL"), - /* 73 */ "SoftNull" OpHelp("r[P1]=NULL"), - /* 74 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), - /* 75 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"), - /* 76 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), - /* 77 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), - /* 78 */ "SCopy" OpHelp("r[P2]=r[P1]"), - /* 79 */ "IntCopy" OpHelp("r[P2]=r[P1]"), - /* 80 */ "ResultRow" OpHelp("output=r[P1@P2]"), - /* 81 */ "CollSeq" OpHelp(""), - /* 82 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), - /* 83 */ "RealAffinity" OpHelp(""), - /* 84 */ "Cast" OpHelp("affinity(r[P1])"), - /* 85 */ "Permutation" OpHelp(""), - /* 86 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), - /* 87 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"), - /* 88 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"), - /* 89 */ "Column" OpHelp("r[P3]=PX"), - /* 90 */ "Affinity" OpHelp("affinity(r[P1@P2])"), - /* 91 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), - /* 92 */ "Count" OpHelp("r[P2]=count()"), - /* 93 */ "ReadCookie" OpHelp(""), - /* 94 */ "SetCookie" OpHelp(""), - /* 95 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), - /* 96 */ "OpenRead" OpHelp("root=P2 iDb=P3"), - /* 97 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), - /* 98 */ "OpenDup" OpHelp(""), - /* 99 */ "OpenAutoindex" OpHelp("nColumn=P2"), - /* 100 */ "OpenEphemeral" OpHelp("nColumn=P2"), - /* 101 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), - /* 102 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), - /* 103 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<>r[P1]"), - /* 105 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"), - /* 106 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), - /* 107 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"), - /* 108 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), - /* 109 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), - /* 110 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), - /* 111 */ "SorterOpen" OpHelp(""), - /* 112 */ "BitNot" OpHelp("r[P2]= ~r[P1]"), - /* 113 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), - /* 114 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), - /* 115 */ "String8" OpHelp("r[P2]='P4'"), - /* 116 */ "Close" OpHelp(""), - /* 117 */ "ColumnsUsed" OpHelp(""), - /* 118 */ "SeekHit" OpHelp("seekHit=P2"), - /* 119 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), - /* 120 */ "NewRowid" OpHelp("r[P2]=rowid"), - /* 121 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), - /* 122 */ "Delete" OpHelp(""), - /* 123 */ "ResetCount" OpHelp(""), - /* 124 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), - /* 125 */ "SorterData" OpHelp("r[P2]=data"), - /* 126 */ "RowData" OpHelp("r[P2]=data"), - /* 127 */ "Rowid" OpHelp("r[P2]=rowid"), - /* 128 */ "NullRow" OpHelp(""), - /* 129 */ "SeekEnd" OpHelp(""), - /* 130 */ "IdxInsert" OpHelp("key=r[P2]"), - /* 131 */ "SorterInsert" OpHelp("key=r[P2]"), - /* 132 */ "IdxDelete" OpHelp("key=r[P2@P3]"), - /* 133 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"), - /* 134 */ "IdxRowid" OpHelp("r[P2]=rowid"), - /* 135 */ "FinishSeek" OpHelp(""), - /* 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 */ "DropTrigger" OpHelp(""), - /* 146 */ "IntegrityCk" OpHelp(""), - /* 147 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), - /* 148 */ "Param" OpHelp(""), - /* 149 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), - /* 150 */ "Real" OpHelp("r[P2]=P4"), - /* 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 */ "CursorLock" OpHelp(""), - /* 160 */ "CursorUnlock" OpHelp(""), - /* 161 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), - /* 162 */ "VBegin" OpHelp(""), - /* 163 */ "VCreate" OpHelp(""), - /* 164 */ "VDestroy" OpHelp(""), - /* 165 */ "VOpen" OpHelp(""), - /* 166 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), - /* 167 */ "VRename" OpHelp(""), - /* 168 */ "Pagecount" OpHelp(""), - /* 169 */ "MaxPgcnt" OpHelp(""), - /* 170 */ "Trace" OpHelp(""), - /* 171 */ "CursorHint" OpHelp(""), - /* 172 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"), - /* 173 */ "Noop" OpHelp(""), - /* 174 */ "Explain" OpHelp(""), - /* 175 */ "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 */ - -/* -** Try to determine if gethostuuid() is available based on standard -** macros. This might sometimes compute the wrong value for some -** obscure platforms. For those cases, simply compile with one of -** the following: -** -** -DHAVE_GETHOSTUUID=0 -** -DHAVE_GETHOSTUUID=1 -** -** None if this matters except when building on Apple products with -** -DSQLITE_ENABLE_LOCKING_STYLE. -*/ -#ifndef HAVE_GETHOSTUUID -# define HAVE_GETHOSTUUID 0 -# 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)) -# undef HAVE_GETHOSTUUID -# define HAVE_GETHOSTUUID 1 -# else -# warning "gethostuuid() is disabled." -# endif -# 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 and x86_64 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(__STRICT_ANSI__) && \ - (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(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif !defined(__STRICT_ANSI__) && (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 - - /* - ** asm() is needed for hardware timing support. Without asm(), - ** disable the sqlite3Hwtime() routine. - ** - ** sqlite3Hwtime() is only used for some obscure debugging - ** and analysis configurations, not in any deliverable, so this - ** should not be a great loss. - */ -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 }, -#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent) -# else - { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 }, -#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent) -# endif -#else - { "ioctl", (sqlite3_syscall_ptr)0, 0 }, -#endif - -}; /* 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", O_RDONLY, 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 tm = pFile->iBusyTimeout; - int rc = osFcntl(h,F_SETLK,pLock); - while( rc<0 && tm>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); - tm--; - } - 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, super-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, super-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: { - int iOld = pFile->iBusyTimeout; - pFile->iBusyTimeout = *(int*)pArg; - *(int*)pArg = iOld; - 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 ){ - int res; - /* Initialize the locking parameters */ - f.l_type = lockType; - f.l_whence = SEEK_SET; - f.l_start = ofst; - f.l_len = n; - res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile); - if( res==-1 ){ -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT - rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY); -#else - rc = SQLITE_BUSY; -#endif - } - } - - /* 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|O_NOFOLLOW, - (sStat.st_mode&0777)); - } - if( pShmNode->hShm<0 ){ - pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW, - (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 ); - - /* Check that, if this to be a blocking lock, no locks that occur later - ** in the following list than the lock being obtained are already held: - ** - ** 1. Checkpointer lock (ofst==1). - ** 2. Write lock (ofst==0). - ** 3. Read locks (ofst>=3 && ofstiBusyTimeout==0 || ( - (ofst!=2) /* not RECOVER */ - && (ofst!=1 || (p->exclMask|p->sharedMask)==0) - && (ofst!=0 || (p->exclMask|p->sharedMask)<3) - && (ofst<3 || (p->exclMask|p->sharedMask)<(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{ - pId->pMethods = 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 super-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); - flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE); - 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. In 8_3_NAMES mode, leave *pMode set to zero. -*/ -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 super-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&0x0FFF00; /* 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 super- 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_SUPER_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 super-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_SUPER_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_SUPER_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|O_NOFOLLOW); - - 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; - } - - /* The owner of the rollback journal or WAL file should always be the - ** same as the owner of the database file. Try to ensure that this is - ** the case. The chown() system call will be a no-op if the current - ** process lacks root privileges, be we should at least try. Without - ** this step, if a root process opens a database file, it can leave - ** behinds a journal/WAL that is owned by root and hence make the - ** database inaccessible to unprivileged processes. - ** - ** If openMode==0, then that means uid and gid are not set correctly - ** (probably because SQLite is configured to use 8+3 filename mode) and - ** in that case we do not want to attempt the chown(). - */ - if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){ - robustFchown(fd, uid, gid); - } - } - assert( fd>=0 ); - if( pOutFlags ){ - *pOutFlags = flags; - } - - if( p->pPreallocatedUnused ){ - p->pPreallocatedUnused->fd = fd; - p->pPreallocatedUnused->flags = - flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE); - } - - 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_SUPER_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) && - (!S_ISREG(buf.st_mode) || 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 = 0; /* 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 ){ - nLink++; - 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); - if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK; - 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 | O_NOFOLLOW; - 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 | O_NOFOLLOW; - 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 */ - -#if 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); -#if 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*/ assert(0); - 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 and x86_64 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(__STRICT_ANSI__) && \ - (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(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif !defined(__STRICT_ANSI__) && (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 - - /* - ** asm() is needed for hardware timing support. Without asm(), - ** disable the sqlite3Hwtime() routine. - ** - ** sqlite3Hwtime() is only used for some obscure debugging - ** and analysis configurations, not in any deliverable, so this - ** should not be a great loss. - */ -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 winIsLongPathPrefix(const char *); -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; - assert( pShm!=0 ); - } - 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 ){ - assert( pFd->pMapRegion!=0 ); - *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_SUPER_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 super-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_SUPER_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_SUPER_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); - id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod; - pFile->pVfs = pVfs; - pFile->h = h; - if( isReadonly ){ - pFile->ctrlFlags |= WINFILE_RDONLY; - } - if( (flags & SQLITE_OPEN_MAIN_DB) - && 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 the "long path" -** prefix. -*/ -static BOOL winIsLongPathPrefix( - const char *zPathname -){ - return ( zPathname[0]=='\\' && zPathname[1]=='\\' - && zPathname[2]=='?' && zPathname[3]=='\\' ); -} - -/* -** 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:" or "\\?\", where "X" is any - ** alphabetic character, discard the initial "/" from the pathname. - */ - if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1) - || winIsLongPathPrefix(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 = sqlite3Realloc(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; - pFile->pMethods = &memdb_io_methods; - p->szMax = sqlite3GlobalConfig.mxMemdbSize; - return SQLITE_OK; -} - -#if 0 /* Only used to delete rollback journals, super-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; - /* The following conditional can only be true when compiled for - ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0. We always leave - ** it in, to be safe, but it is marked as NO_TEST since there - ** is no way to reach it under most builds. */ - if( 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(); - assert( sqlite3GlobalConfig.pcache2.xInit!=0 ); - } - 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)) ){ - assert( pCache->pFree!=0 ); - 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); -#endif - if( benignMalloc ){ sqlite3EndBenignMalloc(); } -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT - pcache1EnterMutex(pCache->pGroup); -#endif - if( pPg==0 ) return 0; -#ifndef SQLITE_PCACHE_SEPARATE_HEADER - p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; -#endif - 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 -** object. -** -** 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->vv ) pTail = pTail->pRight = pA; - pA = pA->pRight; - if( pA==0 ){ - pTail->pRight = pB; - break; - } - }else{ - pTail = pTail->pRight = pB; - pB = pB->pRight; - if( pB==0 ){ - pTail->pRight = pA; - break; - } - } - } - return head.pRight; -} - -/* -** Sort all elements on the list of RowSetEntry objects into order of -** increasing v. -*/ -static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){ - unsigned int i; - struct RowSetEntry *pNext, *aBucket[40]; - - memset(aBucket, 0, sizeof(aBucket)); - while( pIn ){ - pNext = pIn->pRight; - pIn->pRight = 0; - for(i=0; aBucket[i]; i++){ - pIn = rowSetEntryMerge(aBucket[i], pIn); - aBucket[i] = 0; - } - aBucket[i] = pIn; - pIn = pNext; - } - pIn = aBucket[0]; - for(i=1; ipLeft ){ - struct RowSetEntry *p; - rowSetTreeToList(pIn->pLeft, ppFirst, &p); - p->pRight = pIn; - }else{ - *ppFirst = pIn; - } - if( pIn->pRight ){ - rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast); - }else{ - *ppLast = pIn; - } - assert( (*ppLast)->pRight==0 ); -} - - -/* -** Convert a sorted list of elements (connected by pRight) into a binary -** tree with depth of iDepth. A depth of 1 means the tree contains a single -** node taken from the head of *ppList. A depth of 2 means a tree with -** three nodes. And so forth. -** -** Use as many entries from the input list as required and update the -** *ppList to point to the unused elements of the list. If the input -** list contains too few elements, then construct an incomplete tree -** and leave *ppList set to NULL. -** -** Return a pointer to the root of the constructed binary tree. -*/ -static struct RowSetEntry *rowSetNDeepTree( - struct RowSetEntry **ppList, - int iDepth -){ - struct RowSetEntry *p; /* Root of the new tree */ - struct RowSetEntry *pLeft; /* Left subtree */ - if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/ - /* Prevent unnecessary deep recursion when we run out of entries */ - return 0; - } - if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/ - /* This branch causes a *balanced* tree to be generated. A valid tree - ** is still generated without this branch, but the tree is wildly - ** unbalanced and inefficient. */ - pLeft = rowSetNDeepTree(ppList, iDepth-1); - p = *ppList; - if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/ - /* It is safe to always return here, but the resulting tree - ** would be unbalanced */ - return pLeft; - } - p->pLeft = pLeft; - *ppList = p->pRight; - p->pRight = rowSetNDeepTree(ppList, iDepth-1); - }else{ - p = *ppList; - *ppList = p->pRight; - p->pLeft = p->pRight = 0; - } - return p; -} - -/* -** Convert a sorted list of elements into a binary tree. Make the tree -** as deep as it needs to be in order to contain the entire list. -*/ -static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ - int iDepth; /* Depth of the tree so far */ - struct RowSetEntry *p; /* Current tree root */ - struct RowSetEntry *pLeft; /* Left subtree */ - - assert( pList!=0 ); - p = pList; - pList = p->pRight; - p->pLeft = p->pRight = 0; - for(iDepth=1; pList; iDepth++){ - pLeft = p; - p = pList; - pList = p->pRight; - p->pLeft = pLeft; - p->pRight = rowSetNDeepTree(&pList, iDepth); - } - return p; -} - -/* -** Extract the smallest element from the RowSet. -** Write the element into *pRowid. Return 1 on success. Return -** 0 if the RowSet is already empty. -** -** After this routine has been called, the sqlite3RowSetInsert() -** routine may not be called again. -** -** This routine may not be called after sqlite3RowSetTest() has -** been used. Older versions of RowSet allowed that, but as the -** capability was not used by the code generator, it was removed -** for code economy. -*/ -SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ - assert( p!=0 ); - assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */ - - /* Merge the forest into a single sorted list on first call */ - if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/ - if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/ - p->pEntry = rowSetEntrySort(p->pEntry); - } - p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT; - } - - /* Return the next entry on the list */ - if( p->pEntry ){ - *pRowid = p->pEntry->v; - p->pEntry = p->pEntry->pRight; - if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/ - /* Free memory immediately, rather than waiting on sqlite3_finalize() */ - sqlite3RowSetClear(p); - } - return 1; - }else{ - return 0; - } -} - -/* -** Check to see if element iRowid was inserted into the rowset as -** part of any insert batch prior to iBatch. Return 1 or 0. -** -** If this is the first test of a new batch and if there exist entries -** on pRowSet->pEntry, then sort those entries into the forest at -** pRowSet->pForest so that they can be tested. -*/ -SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){ - struct RowSetEntry *p, *pTree; - - /* This routine is never called after sqlite3RowSetNext() */ - assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 ); - - /* Sort entries into the forest on the first test of a new batch. - ** To save unnecessary work, only do this when the batch number changes. - */ - if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/ - p = pRowSet->pEntry; - if( p ){ - struct RowSetEntry **ppPrevTree = &pRowSet->pForest; - if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/ - /* Only sort the current set of entries if they need it */ - p = rowSetEntrySort(p); - } - for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ - ppPrevTree = &pTree->pRight; - if( pTree->pLeft==0 ){ - pTree->pLeft = rowSetListToTree(p); - break; - }else{ - struct RowSetEntry *pAux, *pTail; - rowSetTreeToList(pTree->pLeft, &pAux, &pTail); - pTree->pLeft = 0; - p = rowSetEntryMerge(pAux, p); - } - } - if( pTree==0 ){ - *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet); - if( pTree ){ - pTree->v = 0; - pTree->pRight = 0; - pTree->pLeft = rowSetListToTree(p); - } - } - pRowSet->pEntry = 0; - pRowSet->pLast = 0; - pRowSet->rsFlags |= ROWSET_SORTED; - } - pRowSet->iBatch = iBatch; - } - - /* Test to see if the iRowid value appears anywhere in the forest. - ** Return 1 if it does and 0 if not. - */ - for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ - p = pTree->pLeft; - while( p ){ - if( p->vpRight; - }else if( p->v>iRowid ){ - p = p->pLeft; - }else{ - return 1; - } - } - } - return 0; -} - -/************** End of rowset.c **********************************************/ -/************** Begin file pager.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 is the implementation of the page cache subsystem or "pager". -** -** The pager is used to access a database disk file. It implements -** atomic commit and rollback through the use of a journal file that -** is separate from the database file. The pager also implements file -** locking to prevent two processes from writing the same database -** file simultaneously, or one process from reading the database while -** another is writing. -*/ -#ifndef SQLITE_OMIT_DISKIO -/* #include "sqliteInt.h" */ -/************** Include wal.h in the middle of pager.c ***********************/ -/************** Begin file wal.h *********************************************/ -/* -** 2010 February 1 -** -** 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 to the write-ahead logging -** system. Refer to the comments below and the header comment attached to -** the implementation of each function in log.c for further details. -*/ - -#ifndef SQLITE_WAL_H -#define SQLITE_WAL_H - -/* #include "sqliteInt.h" */ - -/* Macros for extracting appropriate sync flags for either transaction -** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)): -*/ -#define WAL_SYNC_FLAGS(X) ((X)&0x03) -#define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03) - -#ifdef SQLITE_OMIT_WAL -# define sqlite3WalOpen(x,y,z) 0 -# define sqlite3WalLimit(x,y) -# define sqlite3WalClose(v,w,x,y,z) 0 -# define sqlite3WalBeginReadTransaction(y,z) 0 -# define sqlite3WalEndReadTransaction(z) -# define sqlite3WalDbsize(y) 0 -# define sqlite3WalBeginWriteTransaction(y) 0 -# define sqlite3WalEndWriteTransaction(x) 0 -# define sqlite3WalUndo(x,y,z) 0 -# define sqlite3WalSavepoint(y,z) -# define sqlite3WalSavepointUndo(y,z) 0 -# define sqlite3WalFrames(u,v,w,x,y,z) 0 -# define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0 -# define sqlite3WalCallback(z) 0 -# define sqlite3WalExclusiveMode(y,z) 0 -# define sqlite3WalHeapMemory(z) 0 -# define sqlite3WalFramesize(z) 0 -# define sqlite3WalFindFrame(x,y,z) 0 -# define sqlite3WalFile(x) 0 -#else - -#define WAL_SAVEPOINT_NDATA 4 - -/* Connection to a write-ahead log (WAL) file. -** There is one object of this type for each pager. -*/ -typedef struct Wal Wal; - -/* Open and close a connection to a write-ahead log. */ -SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**); -SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *); - -/* Set the limiting size of a WAL file. */ -SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64); - -/* Used by readers to open (lock) and close (unlock) a snapshot. A -** snapshot is like a read-transaction. It is the state of the database -** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and -** preserves the current state even if the other threads or processes -** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the -** transaction and releases the lock. -*/ -SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *); -SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal); - -/* Read a page from the write-ahead log, if it is present. */ -SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *); -SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *); - -/* If the WAL is not empty, return the size of the database. */ -SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal); - -/* Obtain or release the WRITER lock. */ -SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal); -SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal); - -/* Undo any frames written (but not committed) to the log */ -SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx); - -/* Return an integer that records the current (uncommitted) write -** position in the WAL */ -SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData); - -/* Move the write position of the WAL back to iFrame. Called in -** response to a ROLLBACK TO command. */ -SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData); - -/* Write a frame or frames to the log. */ -SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int); - -/* Copy pages from the log to the database file */ -SQLITE_PRIVATE int sqlite3WalCheckpoint( - Wal *pWal, /* Write-ahead log connection */ - sqlite3 *db, /* Check this handle's interrupt flag */ - int eMode, /* One of PASSIVE, FULL and RESTART */ - int (*xBusy)(void*), /* Function to call when busy */ - void *pBusyArg, /* Context argument for xBusyHandler */ - int sync_flags, /* Flags to sync db file with (or 0) */ - int nBuf, /* Size of buffer nBuf */ - u8 *zBuf, /* Temporary buffer to use */ - int *pnLog, /* OUT: Number of frames in WAL */ - int *pnCkpt /* OUT: Number of backfilled frames in WAL */ -); - -/* Return the value to pass to a sqlite3_wal_hook callback, the -** number of frames in the WAL at the point of the last commit since -** sqlite3WalCallback() was called. If no commits have occurred since -** the last call, then return 0. -*/ -SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal); - -/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released) -** by the pager layer on the database file. -*/ -SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op); - -/* Return true if the argument is non-NULL and the WAL module is using -** heap-memory for the wal-index. Otherwise, if the argument is NULL or the -** WAL module is using shared-memory, return false. -*/ -SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal); - -#ifdef SQLITE_ENABLE_SNAPSHOT -SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot); -SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot); -SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal); -SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot); -SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal); -#endif - -#ifdef SQLITE_ENABLE_ZIPVFS -/* If the WAL file is not empty, return the number of bytes of content -** stored in each frame (i.e. the db page-size when the WAL was created). -*/ -SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal); -#endif - -/* Return the sqlite3_file object for the WAL file */ -SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal); - -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT -SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock); -SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db); -#endif - -#endif /* ifndef SQLITE_OMIT_WAL */ -#endif /* SQLITE_WAL_H */ - -/************** End of wal.h *************************************************/ -/************** Continuing where we left off in pager.c **********************/ - - -/******************* NOTES ON THE DESIGN OF THE PAGER ************************ -** -** This comment block describes invariants that hold when using a rollback -** journal. These invariants do not apply for journal_mode=WAL, -** journal_mode=MEMORY, or journal_mode=OFF. -** -** Within this comment block, a page is deemed to have been synced -** automatically as soon as it is written when PRAGMA synchronous=OFF. -** Otherwise, the page is not synced until the xSync method of the VFS -** is called successfully on the file containing the page. -** -** Definition: A page of the database file is said to be "overwriteable" if -** one or more of the following are true about the page: -** -** (a) The original content of the page as it was at the beginning of -** the transaction has been written into the rollback journal and -** synced. -** -** (b) The page was a freelist leaf page at the start of the transaction. -** -** (c) The page number is greater than the largest page that existed in -** the database file at the start of the transaction. -** -** (1) A page of the database file is never overwritten unless one of the -** following are true: -** -** (a) The page and all other pages on the same sector are overwriteable. -** -** (b) The atomic page write optimization is enabled, and the entire -** transaction other than the update of the transaction sequence -** number consists of a single page change. -** -** (2) The content of a page written into the rollback journal exactly matches -** both the content in the database when the rollback journal was written -** and the content in the database at the beginning of the current -** transaction. -** -** (3) Writes to the database file are an integer multiple of the page size -** in length and are aligned on a page boundary. -** -** (4) Reads from the database file are either aligned on a page boundary and -** an integer multiple of the page size in length or are taken from the -** first 100 bytes of the database file. -** -** (5) All writes to the database file are synced prior to the rollback journal -** being deleted, truncated, or zeroed. -** -** (6) If a super-journal file is used, then all writes to the database file -** are synced prior to the super-journal being deleted. -** -** Definition: Two databases (or the same database at two points it time) -** are said to be "logically equivalent" if they give the same answer to -** all queries. Note in particular the content of freelist leaf -** pages can be changed arbitrarily without affecting the logical equivalence -** of the database. -** -** (7) At any time, if any subset, including the empty set and the total set, -** of the unsynced changes to a rollback journal are removed and the -** journal is rolled back, the resulting database file will be logically -** equivalent to the database file at the beginning of the transaction. -** -** (8) When a transaction is rolled back, the xTruncate method of the VFS -** is called to restore the database file to the same size it was at -** the beginning of the transaction. (In some VFSes, the xTruncate -** method is a no-op, but that does not change the fact the SQLite will -** invoke it.) -** -** (9) Whenever the database file is modified, at least one bit in the range -** of bytes from 24 through 39 inclusive will be changed prior to releasing -** the EXCLUSIVE lock, thus signaling other connections on the same -** database to flush their caches. -** -** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less -** than one billion transactions. -** -** (11) A database file is well-formed at the beginning and at the conclusion -** of every transaction. -** -** (12) An EXCLUSIVE lock is held on the database file when writing to -** the database file. -** -** (13) A SHARED lock is held on the database file while reading any -** content out of the database file. -** -******************************************************************************/ - -/* -** Macros for troubleshooting. Normally turned off -*/ -#if 0 -int sqlite3PagerTrace=1; /* True to enable tracing */ -#define sqlite3DebugPrintf printf -#define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; } -#else -#define PAGERTRACE(X) -#endif - -/* -** The following two macros are used within the PAGERTRACE() macros above -** to print out file-descriptors. -** -** PAGERID() takes a pointer to a Pager struct as its argument. The -** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file -** struct as its argument. -*/ -#define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd)) -#define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd)) - -/* -** The Pager.eState variable stores the current 'state' of a pager. A -** pager may be in any one of the seven states shown in the following -** state diagram. -** -** OPEN <------+------+ -** | | | -** V | | -** +---------> READER-------+ | -** | | | -** | V | -** |<-------WRITER_LOCKED------> ERROR -** | | ^ -** | V | -** |<------WRITER_CACHEMOD-------->| -** | | | -** | V | -** |<-------WRITER_DBMOD---------->| -** | | | -** | V | -** +<------WRITER_FINISHED-------->+ -** -** -** List of state transitions and the C [function] that performs each: -** -** OPEN -> READER [sqlite3PagerSharedLock] -** READER -> OPEN [pager_unlock] -** -** READER -> WRITER_LOCKED [sqlite3PagerBegin] -** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal] -** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal] -** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne] -** WRITER_*** -> READER [pager_end_transaction] -** -** WRITER_*** -> ERROR [pager_error] -** ERROR -> OPEN [pager_unlock] -** -** -** OPEN: -** -** The pager starts up in this state. Nothing is guaranteed in this -** state - the file may or may not be locked and the database size is -** unknown. The database may not be read or written. -** -** * No read or write transaction is active. -** * Any lock, or no lock at all, may be held on the database file. -** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted. -** -** READER: -** -** In this state all the requirements for reading the database in -** rollback (non-WAL) mode are met. Unless the pager is (or recently -** was) in exclusive-locking mode, a user-level read transaction is -** open. The database size is known in this state. -** -** A connection running with locking_mode=normal enters this state when -** it opens a read-transaction on the database and returns to state -** OPEN after the read-transaction is completed. However a connection -** running in locking_mode=exclusive (including temp databases) remains in -** this state even after the read-transaction is closed. The only way -** a locking_mode=exclusive connection can transition from READER to OPEN -** is via the ERROR state (see below). -** -** * A read transaction may be active (but a write-transaction cannot). -** * A SHARED or greater lock is held on the database file. -** * The dbSize variable may be trusted (even if a user-level read -** transaction is not active). The dbOrigSize and dbFileSize variables -** may not be trusted at this point. -** * If the database is a WAL database, then the WAL connection is open. -** * Even if a read-transaction is not open, it is guaranteed that -** there is no hot-journal in the file-system. -** -** WRITER_LOCKED: -** -** The pager moves to this state from READER when a write-transaction -** is first opened on the database. In WRITER_LOCKED state, all locks -** required to start a write-transaction are held, but no actual -** modifications to the cache or database have taken place. -** -** In rollback mode, a RESERVED or (if the transaction was opened with -** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when -** moving to this state, but the journal file is not written to or opened -** to in this state. If the transaction is committed or rolled back while -** in WRITER_LOCKED state, all that is required is to unlock the database -** file. -** -** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file. -** If the connection is running with locking_mode=exclusive, an attempt -** is made to obtain an EXCLUSIVE lock on the database file. -** -** * A write transaction is active. -** * If the connection is open in rollback-mode, a RESERVED or greater -** lock is held on the database file. -** * If the connection is open in WAL-mode, a WAL write transaction -** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully -** called). -** * The dbSize, dbOrigSize and dbFileSize variables are all valid. -** * The contents of the pager cache have not been modified. -** * The journal file may or may not be open. -** * Nothing (not even the first header) has been written to the journal. -** -** WRITER_CACHEMOD: -** -** A pager moves from WRITER_LOCKED state to this state when a page is -** first modified by the upper layer. In rollback mode the journal file -** is opened (if it is not already open) and a header written to the -** start of it. The database file on disk has not been modified. -** -** * A write transaction is active. -** * A RESERVED or greater lock is held on the database file. -** * The journal file is open and the first header has been written -** to it, but the header has not been synced to disk. -** * The contents of the page cache have been modified. -** -** WRITER_DBMOD: -** -** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state -** when it modifies the contents of the database file. WAL connections -** never enter this state (since they do not modify the database file, -** just the log file). -** -** * A write transaction is active. -** * An EXCLUSIVE or greater lock is held on the database file. -** * The journal file is open and the first header has been written -** and synced to disk. -** * The contents of the page cache have been modified (and possibly -** written to disk). -** -** WRITER_FINISHED: -** -** It is not possible for a WAL connection to enter this state. -** -** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD -** state after the entire transaction has been successfully written into the -** database file. In this state the transaction may be committed simply -** by finalizing the journal file. Once in WRITER_FINISHED state, it is -** not possible to modify the database further. At this point, the upper -** layer must either commit or rollback the transaction. -** -** * A write transaction is active. -** * An EXCLUSIVE or greater lock is held on the database file. -** * All writing and syncing of journal and database data has finished. -** If no error occurred, all that remains is to finalize the journal to -** commit the transaction. If an error did occur, the caller will need -** to rollback the transaction. -** -** ERROR: -** -** The ERROR state is entered when an IO or disk-full error (including -** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it -** difficult to be sure that the in-memory pager state (cache contents, -** db size etc.) are consistent with the contents of the file-system. -** -** Temporary pager files may enter the ERROR state, but in-memory pagers -** cannot. -** -** For example, if an IO error occurs while performing a rollback, -** the contents of the page-cache may be left in an inconsistent state. -** At this point it would be dangerous to change back to READER state -** (as usually happens after a rollback). Any subsequent readers might -** report database corruption (due to the inconsistent cache), and if -** they upgrade to writers, they may inadvertently corrupt the database -** file. To avoid this hazard, the pager switches into the ERROR state -** instead of READER following such an error. -** -** Once it has entered the ERROR state, any attempt to use the pager -** to read or write data returns an error. Eventually, once all -** outstanding transactions have been abandoned, the pager is able to -** transition back to OPEN state, discarding the contents of the -** page-cache and any other in-memory state at the same time. Everything -** is reloaded from disk (and, if necessary, hot-journal rollback peformed) -** when a read-transaction is next opened on the pager (transitioning -** the pager into READER state). At that point the system has recovered -** from the error. -** -** Specifically, the pager jumps into the ERROR state if: -** -** 1. An error occurs while attempting a rollback. This happens in -** function sqlite3PagerRollback(). -** -** 2. An error occurs while attempting to finalize a journal file -** following a commit in function sqlite3PagerCommitPhaseTwo(). -** -** 3. An error occurs while attempting to write to the journal or -** database file in function pagerStress() in order to free up -** memory. -** -** In other cases, the error is returned to the b-tree layer. The b-tree -** layer then attempts a rollback operation. If the error condition -** persists, the pager enters the ERROR state via condition (1) above. -** -** Condition (3) is necessary because it can be triggered by a read-only -** statement executed within a transaction. In this case, if the error -** code were simply returned to the user, the b-tree layer would not -** automatically attempt a rollback, as it assumes that an error in a -** read-only statement cannot leave the pager in an internally inconsistent -** state. -** -** * The Pager.errCode variable is set to something other than SQLITE_OK. -** * There are one or more outstanding references to pages (after the -** last reference is dropped the pager should move back to OPEN state). -** * The pager is not an in-memory pager. -** -** -** Notes: -** -** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the -** connection is open in WAL mode. A WAL connection is always in one -** of the first four states. -** -** * Normally, a connection open in exclusive mode is never in PAGER_OPEN -** state. There are two exceptions: immediately after exclusive-mode has -** been turned on (and before any read or write transactions are -** executed), and when the pager is leaving the "error state". -** -** * See also: assert_pager_state(). -*/ -#define PAGER_OPEN 0 -#define PAGER_READER 1 -#define PAGER_WRITER_LOCKED 2 -#define PAGER_WRITER_CACHEMOD 3 -#define PAGER_WRITER_DBMOD 4 -#define PAGER_WRITER_FINISHED 5 -#define PAGER_ERROR 6 - -/* -** The Pager.eLock variable is almost always set to one of the -** following locking-states, according to the lock currently held on -** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. -** This variable is kept up to date as locks are taken and released by -** the pagerLockDb() and pagerUnlockDb() wrappers. -** -** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY -** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not -** the operation was successful. In these circumstances pagerLockDb() and -** pagerUnlockDb() take a conservative approach - eLock is always updated -** when unlocking the file, and only updated when locking the file if the -** VFS call is successful. This way, the Pager.eLock variable may be set -** to a less exclusive (lower) value than the lock that is actually held -** at the system level, but it is never set to a more exclusive value. -** -** This is usually safe. If an xUnlock fails or appears to fail, there may -** be a few redundant xLock() calls or a lock may be held for longer than -** required, but nothing really goes wrong. -** -** The exception is when the database file is unlocked as the pager moves -** from ERROR to OPEN state. At this point there may be a hot-journal file -** in the file-system that needs to be rolled back (as part of an OPEN->SHARED -** transition, by the same pager or any other). If the call to xUnlock() -** fails at this point and the pager is left holding an EXCLUSIVE lock, this -** can confuse the call to xCheckReservedLock() call made later as part -** of hot-journal detection. -** -** xCheckReservedLock() is defined as returning true "if there is a RESERVED -** lock held by this process or any others". So xCheckReservedLock may -** return true because the caller itself is holding an EXCLUSIVE lock (but -** doesn't know it because of a previous error in xUnlock). If this happens -** a hot-journal may be mistaken for a journal being created by an active -** transaction in another process, causing SQLite to read from the database -** without rolling it back. -** -** To work around this, if a call to xUnlock() fails when unlocking the -** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It -** is only changed back to a real locking state after a successful call -** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition -** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK -** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE -** lock on the database file before attempting to roll it back. See function -** PagerSharedLock() for more detail. -** -** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in -** PAGER_OPEN state. -*/ -#define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1) - -/* -** The maximum allowed sector size. 64KiB. If the xSectorsize() method -** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. -** This could conceivably cause corruption following a power failure on -** such a system. This is currently an undocumented limit. -*/ -#define MAX_SECTOR_SIZE 0x10000 - - -/* -** An instance of the following structure is allocated for each active -** savepoint and statement transaction in the system. All such structures -** are stored in the Pager.aSavepoint[] array, which is allocated and -** resized using sqlite3Realloc(). -** -** When a savepoint is created, the PagerSavepoint.iHdrOffset field is -** set to 0. If a journal-header is written into the main journal while -** the savepoint is active, then iHdrOffset is set to the byte offset -** immediately following the last journal record written into the main -** journal before the journal-header. This is required during savepoint -** rollback (see pagerPlaybackSavepoint()). -*/ -typedef struct PagerSavepoint PagerSavepoint; -struct PagerSavepoint { - i64 iOffset; /* Starting offset in main journal */ - i64 iHdrOffset; /* See above */ - Bitvec *pInSavepoint; /* Set of pages in this savepoint */ - Pgno nOrig; /* Original number of pages in file */ - Pgno iSubRec; /* Index of first record in sub-journal */ -#ifndef SQLITE_OMIT_WAL - u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */ -#endif -}; - -/* -** Bits of the Pager.doNotSpill flag. See further description below. -*/ -#define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */ -#define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */ -#define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */ - -/* -** An open page cache is an instance of struct Pager. A description of -** some of the more important member variables follows: -** -** eState -** -** The current 'state' of the pager object. See the comment and state -** diagram above for a description of the pager state. -** -** eLock -** -** For a real on-disk database, the current lock held on the database file - -** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK. -** -** For a temporary or in-memory database (neither of which require any -** locks), this variable is always set to EXCLUSIVE_LOCK. Since such -** databases always have Pager.exclusiveMode==1, this tricks the pager -** logic into thinking that it already has all the locks it will ever -** need (and no reason to release them). -** -** In some (obscure) circumstances, this variable may also be set to -** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for -** details. -** -** changeCountDone -** -** This boolean variable is used to make sure that the change-counter -** (the 4-byte header field at byte offset 24 of the database file) is -** not updated more often than necessary. -** -** It is set to true when the change-counter field is updated, which -** can only happen if an exclusive lock is held on the database file. -** It is cleared (set to false) whenever an exclusive lock is -** relinquished on the database file. Each time a transaction is committed, -** The changeCountDone flag is inspected. If it is true, the work of -** updating the change-counter is omitted for the current transaction. -** -** This mechanism means that when running in exclusive mode, a connection -** need only update the change-counter once, for the first transaction -** committed. -** -** setSuper -** -** When PagerCommitPhaseOne() is called to commit a transaction, it may -** (or may not) specify a super-journal name to be written into the -** journal file before it is synced to disk. -** -** Whether or not a journal file contains a super-journal pointer affects -** the way in which the journal file is finalized after the transaction is -** committed or rolled back when running in "journal_mode=PERSIST" mode. -** If a journal file does not contain a super-journal pointer, it is -** finalized by overwriting the first journal header with zeroes. If -** it does contain a super-journal pointer the journal file is finalized -** by truncating it to zero bytes, just as if the connection were -** running in "journal_mode=truncate" mode. -** -** Journal files that contain super-journal pointers cannot be finalized -** simply by overwriting the first journal-header with zeroes, as the -** super-journal pointer could interfere with hot-journal rollback of any -** subsequently interrupted transaction that reuses the journal file. -** -** The flag is cleared as soon as the journal file is finalized (either -** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the -** journal file from being successfully finalized, the setSuper flag -** is cleared anyway (and the pager will move to ERROR state). -** -** doNotSpill -** -** This variables control the behavior of cache-spills (calls made by -** the pcache module to the pagerStress() routine to write cached data -** to the file-system in order to free up memory). -** -** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set, -** writing to the database from pagerStress() is disabled altogether. -** The SPILLFLAG_ROLLBACK case is done in a very obscure case that -** comes up during savepoint rollback that requires the pcache module -** to allocate a new page to prevent the journal file from being written -** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF -** case is a user preference. -** -** If the SPILLFLAG_NOSYNC bit is set, writing to the database from -** pagerStress() is permitted, but syncing the journal file is not. -** This flag is set by sqlite3PagerWrite() when the file-system sector-size -** is larger than the database page-size in order to prevent a journal sync -** from happening in between the journalling of two pages on the same sector. -** -** subjInMemory -** -** This is a boolean variable. If true, then any required sub-journal -** is opened as an in-memory journal file. If false, then in-memory -** sub-journals are only used for in-memory pager files. -** -** This variable is updated by the upper layer each time a new -** write-transaction is opened. -** -** dbSize, dbOrigSize, dbFileSize -** -** Variable dbSize is set to the number of pages in the database file. -** It is valid in PAGER_READER and higher states (all states except for -** OPEN and ERROR). -** -** dbSize is set based on the size of the database file, which may be -** larger than the size of the database (the value stored at offset -** 28 of the database header by the btree). If the size of the file -** is not an integer multiple of the page-size, the value stored in -** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2). -** Except, any file that is greater than 0 bytes in size is considered -** to have at least one page. (i.e. a 1KB file with 2K page-size leads -** to dbSize==1). -** -** During a write-transaction, if pages with page-numbers greater than -** dbSize are modified in the cache, dbSize is updated accordingly. -** Similarly, if the database is truncated using PagerTruncateImage(), -** dbSize is updated. -** -** Variables dbOrigSize and dbFileSize are valid in states -** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize -** variable at the start of the transaction. It is used during rollback, -** and to determine whether or not pages need to be journalled before -** being modified. -** -** Throughout a write-transaction, dbFileSize contains the size of -** the file on disk in pages. It is set to a copy of dbSize when the -** write-transaction is first opened, and updated when VFS calls are made -** to write or truncate the database file on disk. -** -** The only reason the dbFileSize variable is required is to suppress -** unnecessary calls to xTruncate() after committing a transaction. If, -** when a transaction is committed, the dbFileSize variable indicates -** that the database file is larger than the database image (Pager.dbSize), -** pager_truncate() is called. The pager_truncate() call uses xFilesize() -** to measure the database file on disk, and then truncates it if required. -** dbFileSize is not used when rolling back a transaction. In this case -** pager_truncate() is called unconditionally (which means there may be -** a call to xFilesize() that is not strictly required). In either case, -** pager_truncate() may cause the file to become smaller or larger. -** -** dbHintSize -** -** The dbHintSize variable is used to limit the number of calls made to -** the VFS xFileControl(FCNTL_SIZE_HINT) method. -** -** dbHintSize is set to a copy of the dbSize variable when a -** write-transaction is opened (at the same time as dbFileSize and -** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called, -** dbHintSize is increased to the number of pages that correspond to the -** size-hint passed to the method call. See pager_write_pagelist() for -** details. -** -** errCode -** -** The Pager.errCode variable is only ever used in PAGER_ERROR state. It -** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode -** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX -** sub-codes. -** -** syncFlags, walSyncFlags -** -** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03). -** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode -** and contains the flags used to sync the checkpoint operations in the -** lower two bits, and sync flags used for transaction commits in the WAL -** file in bits 0x04 and 0x08. In other words, to get the correct sync flags -** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct -** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note -** that with synchronous=NORMAL in WAL mode, transaction commit is not synced -** meaning that the 0x04 and 0x08 bits are both zero. -*/ -struct Pager { - sqlite3_vfs *pVfs; /* OS functions to use for IO */ - u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */ - u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */ - u8 useJournal; /* Use a rollback journal on this file */ - u8 noSync; /* Do not sync the journal if true */ - u8 fullSync; /* Do extra syncs of the journal for robustness */ - u8 extraSync; /* sync directory after journal delete */ - u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */ - u8 walSyncFlags; /* See description above */ - u8 tempFile; /* zFilename is a temporary or immutable file */ - u8 noLock; /* Do not lock (except in WAL mode) */ - u8 readOnly; /* True for a read-only database */ - u8 memDb; /* True to inhibit all file I/O */ - - /************************************************************************** - ** The following block contains those class members that change during - ** routine operation. Class members not in this block are either fixed - ** when the pager is first created or else only change when there is a - ** significant mode change (such as changing the page_size, locking_mode, - ** or the journal_mode). From another view, these class members describe - ** the "state" of the pager, while other class members describe the - ** "configuration" of the pager. - */ - u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */ - u8 eLock; /* Current lock held on database file */ - u8 changeCountDone; /* Set after incrementing the change-counter */ - u8 setSuper; /* Super-jrnl name is written into jrnl */ - u8 doNotSpill; /* Do not spill the cache when non-zero */ - u8 subjInMemory; /* True to use in-memory sub-journals */ - u8 bUseFetch; /* True to use xFetch() */ - u8 hasHeldSharedLock; /* True if a shared lock has ever been held */ - Pgno dbSize; /* Number of pages in the database */ - Pgno dbOrigSize; /* dbSize before the current transaction */ - Pgno dbFileSize; /* Number of pages in the database file */ - Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */ - int errCode; /* One of several kinds of errors */ - int nRec; /* Pages journalled since last j-header written */ - u32 cksumInit; /* Quasi-random value added to every checksum */ - u32 nSubRec; /* Number of records written to sub-journal */ - Bitvec *pInJournal; /* One bit for each page in the database file */ - sqlite3_file *fd; /* File descriptor for database */ - sqlite3_file *jfd; /* File descriptor for main journal */ - sqlite3_file *sjfd; /* File descriptor for sub-journal */ - i64 journalOff; /* Current write offset in the journal file */ - i64 journalHdr; /* Byte offset to previous journal header */ - sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */ - PagerSavepoint *aSavepoint; /* Array of active savepoints */ - int nSavepoint; /* Number of elements in aSavepoint[] */ - u32 iDataVersion; /* Changes whenever database content changes */ - char dbFileVers[16]; /* Changes whenever database file changes */ - - int nMmapOut; /* Number of mmap pages currently outstanding */ - sqlite3_int64 szMmap; /* Desired maximum mmap size */ - PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */ - /* - ** End of the routinely-changing class members - ***************************************************************************/ - - u16 nExtra; /* Add this many bytes to each in-memory page */ - i16 nReserve; /* Number of unused bytes at end of each page */ - u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */ - u32 sectorSize; /* Assumed sector size during rollback */ - int pageSize; /* Number of bytes in a page */ - Pgno mxPgno; /* Maximum allowed size of the database */ - i64 journalSizeLimit; /* Size limit for persistent journal files */ - char *zFilename; /* Name of the database file */ - char *zJournal; /* Name of the journal file */ - int (*xBusyHandler)(void*); /* Function to call when busy */ - void *pBusyHandlerArg; /* Context argument for xBusyHandler */ - int aStat[4]; /* Total cache hits, misses, writes, spills */ -#ifdef SQLITE_TEST - int nRead; /* Database pages read */ -#endif - void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */ - int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */ - char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */ - PCache *pPCache; /* Pointer to page cache object */ -#ifndef SQLITE_OMIT_WAL - Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */ - char *zWal; /* File name for write-ahead log */ -#endif -}; - -/* -** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains -** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS -** or CACHE_WRITE to sqlite3_db_status(). -*/ -#define PAGER_STAT_HIT 0 -#define PAGER_STAT_MISS 1 -#define PAGER_STAT_WRITE 2 -#define PAGER_STAT_SPILL 3 - -/* -** The following global variables hold counters used for -** testing purposes only. These variables do not exist in -** a non-testing build. These variables are not thread-safe. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */ -SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */ -SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */ -# define PAGER_INCR(v) v++ -#else -# define PAGER_INCR(v) -#endif - - - -/* -** Journal files begin with the following magic string. The data -** was obtained from /dev/random. It is used only as a sanity check. -** -** Since version 2.8.0, the journal format contains additional sanity -** checking information. If the power fails while the journal is being -** written, semi-random garbage data might appear in the journal -** file after power is restored. If an attempt is then made -** to roll the journal back, the database could be corrupted. The additional -** sanity checking data is an attempt to discover the garbage in the -** journal and ignore it. -** -** The sanity checking information for the new journal format consists -** of a 32-bit checksum on each page of data. The checksum covers both -** the page number and the pPager->pageSize bytes of data for the page. -** This cksum is initialized to a 32-bit random value that appears in the -** journal file right after the header. The random initializer is important, -** because garbage data that appears at the end of a journal is likely -** data that was once in other files that have now been deleted. If the -** garbage data came from an obsolete journal file, the checksums might -** be correct. But by initializing the checksum to random value which -** is different for every journal, we minimize that risk. -*/ -static const unsigned char aJournalMagic[] = { - 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7, -}; - -/* -** The size of the of each page record in the journal is given by -** the following macro. -*/ -#define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8) - -/* -** The journal header size for this pager. This is usually the same -** size as a single disk sector. See also setSectorSize(). -*/ -#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize) - -/* -** The macro MEMDB is true if we are dealing with an in-memory database. -** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set, -** the value of MEMDB will be a constant and the compiler will optimize -** out code that would never execute. -*/ -#ifdef SQLITE_OMIT_MEMORYDB -# define MEMDB 0 -#else -# define MEMDB pPager->memDb -#endif - -/* -** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch -** interfaces to access the database using memory-mapped I/O. -*/ -#if SQLITE_MAX_MMAP_SIZE>0 -# define USEFETCH(x) ((x)->bUseFetch) -#else -# define USEFETCH(x) 0 -#endif - -/* -** The argument to this macro is a file descriptor (type sqlite3_file*). -** Return 0 if it is not open, or non-zero (but not 1) if it is. -** -** This is so that expressions can be written as: -** -** if( isOpen(pPager->jfd) ){ ... -** -** instead of -** -** if( pPager->jfd->pMethods ){ ... -*/ -#define isOpen(pFd) ((pFd)->pMethods!=0) - -#ifdef SQLITE_DIRECT_OVERFLOW_READ -/* -** Return true if page pgno can be read directly from the database file -** by the b-tree layer. This is the case if: -** -** * the database file is open, -** * there are no dirty pages in the cache, and -** * the desired page is not currently in the wal file. -*/ -SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){ - if( pPager->fd->pMethods==0 ) return 0; - if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0; -#ifndef SQLITE_OMIT_WAL - if( pPager->pWal ){ - u32 iRead = 0; - int rc; - rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead); - return (rc==SQLITE_OK && iRead==0); - } -#endif - return 1; -} -#endif - -#ifndef SQLITE_OMIT_WAL -# define pagerUseWal(x) ((x)->pWal!=0) -#else -# define pagerUseWal(x) 0 -# define pagerRollbackWal(x) 0 -# define pagerWalFrames(v,w,x,y) 0 -# define pagerOpenWalIfPresent(z) SQLITE_OK -# define pagerBeginReadTransaction(z) SQLITE_OK -#endif - -#ifndef NDEBUG -/* -** Usage: -** -** assert( assert_pager_state(pPager) ); -** -** This function runs many asserts to try to find inconsistencies in -** the internal state of the Pager object. -*/ -static int assert_pager_state(Pager *p){ - Pager *pPager = p; - - /* State must be valid. */ - assert( p->eState==PAGER_OPEN - || p->eState==PAGER_READER - || p->eState==PAGER_WRITER_LOCKED - || p->eState==PAGER_WRITER_CACHEMOD - || p->eState==PAGER_WRITER_DBMOD - || p->eState==PAGER_WRITER_FINISHED - || p->eState==PAGER_ERROR - ); - - /* Regardless of the current state, a temp-file connection always behaves - ** as if it has an exclusive lock on the database file. It never updates - ** the change-counter field, so the changeCountDone flag is always set. - */ - assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK ); - assert( p->tempFile==0 || pPager->changeCountDone ); - - /* If the useJournal flag is clear, the journal-mode must be "OFF". - ** And if the journal-mode is "OFF", the journal file must not be open. - */ - assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal ); - assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) ); - - /* Check that MEMDB implies noSync. And an in-memory journal. Since - ** this means an in-memory pager performs no IO at all, it cannot encounter - ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing - ** a journal file. (although the in-memory journal implementation may - ** return SQLITE_IOERR_NOMEM while the journal file is being written). It - ** is therefore not possible for an in-memory pager to enter the ERROR - ** state. - */ - if( MEMDB ){ - assert( !isOpen(p->fd) ); - assert( p->noSync ); - assert( p->journalMode==PAGER_JOURNALMODE_OFF - || p->journalMode==PAGER_JOURNALMODE_MEMORY - ); - assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN ); - assert( pagerUseWal(p)==0 ); - } - - /* If changeCountDone is set, a RESERVED lock or greater must be held - ** on the file. - */ - assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK ); - assert( p->eLock!=PENDING_LOCK ); - - switch( p->eState ){ - case PAGER_OPEN: - assert( !MEMDB ); - assert( pPager->errCode==SQLITE_OK ); - assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile ); - break; - - case PAGER_READER: - assert( pPager->errCode==SQLITE_OK ); - assert( p->eLock!=UNKNOWN_LOCK ); - assert( p->eLock>=SHARED_LOCK ); - break; - - case PAGER_WRITER_LOCKED: - assert( p->eLock!=UNKNOWN_LOCK ); - assert( pPager->errCode==SQLITE_OK ); - if( !pagerUseWal(pPager) ){ - assert( p->eLock>=RESERVED_LOCK ); - } - assert( pPager->dbSize==pPager->dbOrigSize ); - assert( pPager->dbOrigSize==pPager->dbFileSize ); - assert( pPager->dbOrigSize==pPager->dbHintSize ); - assert( pPager->setSuper==0 ); - break; - - case PAGER_WRITER_CACHEMOD: - assert( p->eLock!=UNKNOWN_LOCK ); - assert( pPager->errCode==SQLITE_OK ); - if( !pagerUseWal(pPager) ){ - /* It is possible that if journal_mode=wal here that neither the - ** journal file nor the WAL file are open. This happens during - ** a rollback transaction that switches from journal_mode=off - ** to journal_mode=wal. - */ - assert( p->eLock>=RESERVED_LOCK ); - assert( isOpen(p->jfd) - || p->journalMode==PAGER_JOURNALMODE_OFF - || p->journalMode==PAGER_JOURNALMODE_WAL - ); - } - assert( pPager->dbOrigSize==pPager->dbFileSize ); - assert( pPager->dbOrigSize==pPager->dbHintSize ); - break; - - case PAGER_WRITER_DBMOD: - assert( p->eLock==EXCLUSIVE_LOCK ); - assert( pPager->errCode==SQLITE_OK ); - assert( !pagerUseWal(pPager) ); - assert( p->eLock>=EXCLUSIVE_LOCK ); - assert( isOpen(p->jfd) - || p->journalMode==PAGER_JOURNALMODE_OFF - || p->journalMode==PAGER_JOURNALMODE_WAL - || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC) - ); - assert( pPager->dbOrigSize<=pPager->dbHintSize ); - break; - - case PAGER_WRITER_FINISHED: - assert( p->eLock==EXCLUSIVE_LOCK ); - assert( pPager->errCode==SQLITE_OK ); - assert( !pagerUseWal(pPager) ); - assert( isOpen(p->jfd) - || p->journalMode==PAGER_JOURNALMODE_OFF - || p->journalMode==PAGER_JOURNALMODE_WAL - || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC) - ); - break; - - case PAGER_ERROR: - /* There must be at least one outstanding reference to the pager if - ** in ERROR state. Otherwise the pager should have already dropped - ** back to OPEN state. - */ - assert( pPager->errCode!=SQLITE_OK ); - assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile ); - break; - } - - return 1; -} -#endif /* ifndef NDEBUG */ - -#ifdef SQLITE_DEBUG -/* -** Return a pointer to a human readable string in a static buffer -** containing the state of the Pager object passed as an argument. This -** is intended to be used within debuggers. For example, as an alternative -** to "print *pPager" in gdb: -** -** (gdb) printf "%s", print_pager_state(pPager) -** -** This routine has external linkage in order to suppress compiler warnings -** about an unused function. It is enclosed within SQLITE_DEBUG and so does -** not appear in normal builds. -*/ -char *print_pager_state(Pager *p){ - static char zRet[1024]; - - sqlite3_snprintf(1024, zRet, - "Filename: %s\n" - "State: %s errCode=%d\n" - "Lock: %s\n" - "Locking mode: locking_mode=%s\n" - "Journal mode: journal_mode=%s\n" - "Backing store: tempFile=%d memDb=%d useJournal=%d\n" - "Journal: journalOff=%lld journalHdr=%lld\n" - "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n" - , p->zFilename - , p->eState==PAGER_OPEN ? "OPEN" : - p->eState==PAGER_READER ? "READER" : - p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" : - p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" : - p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" : - p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" : - p->eState==PAGER_ERROR ? "ERROR" : "?error?" - , (int)p->errCode - , p->eLock==NO_LOCK ? "NO_LOCK" : - p->eLock==RESERVED_LOCK ? "RESERVED" : - p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" : - p->eLock==SHARED_LOCK ? "SHARED" : - p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?" - , p->exclusiveMode ? "exclusive" : "normal" - , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" : - p->journalMode==PAGER_JOURNALMODE_OFF ? "off" : - p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" : - p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" : - p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" : - p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?" - , (int)p->tempFile, (int)p->memDb, (int)p->useJournal - , p->journalOff, p->journalHdr - , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize - ); - - return zRet; -} -#endif - -/* Forward references to the various page getters */ -static int getPageNormal(Pager*,Pgno,DbPage**,int); -static int getPageError(Pager*,Pgno,DbPage**,int); -#if SQLITE_MAX_MMAP_SIZE>0 -static int getPageMMap(Pager*,Pgno,DbPage**,int); -#endif - -/* -** Set the Pager.xGet method for the appropriate routine used to fetch -** content from the pager. -*/ -static void setGetterMethod(Pager *pPager){ - if( pPager->errCode ){ - pPager->xGet = getPageError; -#if SQLITE_MAX_MMAP_SIZE>0 - }else if( USEFETCH(pPager) ){ - pPager->xGet = getPageMMap; -#endif /* SQLITE_MAX_MMAP_SIZE>0 */ - }else{ - pPager->xGet = getPageNormal; - } -} - -/* -** Return true if it is necessary to write page *pPg into the sub-journal. -** A page needs to be written into the sub-journal if there exists one -** or more open savepoints for which: -** -** * The page-number is less than or equal to PagerSavepoint.nOrig, and -** * The bit corresponding to the page-number is not set in -** PagerSavepoint.pInSavepoint. -*/ -static int subjRequiresPage(PgHdr *pPg){ - Pager *pPager = pPg->pPager; - PagerSavepoint *p; - Pgno pgno = pPg->pgno; - int i; - for(i=0; inSavepoint; i++){ - p = &pPager->aSavepoint[i]; - if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){ - return 1; - } - } - return 0; -} - -#ifdef SQLITE_DEBUG -/* -** Return true if the page is already in the journal file. -*/ -static int pageInJournal(Pager *pPager, PgHdr *pPg){ - return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno); -} -#endif - -/* -** Read a 32-bit integer from the given file descriptor. Store the integer -** that is read in *pRes. Return SQLITE_OK if everything worked, or an -** error code is something goes wrong. -** -** All values are stored on disk as big-endian. -*/ -static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){ - unsigned char ac[4]; - int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset); - if( rc==SQLITE_OK ){ - *pRes = sqlite3Get4byte(ac); - } - return rc; -} - -/* -** Write a 32-bit integer into a string buffer in big-endian byte order. -*/ -#define put32bits(A,B) sqlite3Put4byte((u8*)A,B) - - -/* -** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK -** on success or an error code is something goes wrong. -*/ -static int write32bits(sqlite3_file *fd, i64 offset, u32 val){ - char ac[4]; - put32bits(ac, val); - return sqlite3OsWrite(fd, ac, 4, offset); -} - -/* -** Unlock the database file to level eLock, which must be either NO_LOCK -** or SHARED_LOCK. Regardless of whether or not the call to xUnlock() -** succeeds, set the Pager.eLock variable to match the (attempted) new lock. -** -** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is -** called, do not modify it. See the comment above the #define of -** UNKNOWN_LOCK for an explanation of this. -*/ -static int pagerUnlockDb(Pager *pPager, int eLock){ - int rc = SQLITE_OK; - - assert( !pPager->exclusiveMode || pPager->eLock==eLock ); - assert( eLock==NO_LOCK || eLock==SHARED_LOCK ); - assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 ); - if( isOpen(pPager->fd) ){ - assert( pPager->eLock>=eLock ); - rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock); - if( pPager->eLock!=UNKNOWN_LOCK ){ - pPager->eLock = (u8)eLock; - } - IOTRACE(("UNLOCK %p %d\n", pPager, eLock)) - } - pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */ - return rc; -} - -/* -** Lock the database file to level eLock, which must be either SHARED_LOCK, -** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the -** Pager.eLock variable to the new locking state. -** -** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is -** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. -** See the comment above the #define of UNKNOWN_LOCK for an explanation -** of this. -*/ -static int pagerLockDb(Pager *pPager, int eLock){ - int rc = SQLITE_OK; - - assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK ); - if( pPager->eLockeLock==UNKNOWN_LOCK ){ - rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock); - if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){ - pPager->eLock = (u8)eLock; - IOTRACE(("LOCK %p %d\n", pPager, eLock)) - } - } - return rc; -} - -/* -** This function determines whether or not the atomic-write or -** atomic-batch-write optimizations can be used with this pager. The -** atomic-write optimization can be used if: -** -** (a) the value returned by OsDeviceCharacteristics() indicates that -** a database page may be written atomically, and -** (b) the value returned by OsSectorSize() is less than or equal -** to the page size. -** -** If it can be used, then the value returned is the size of the journal -** file when it contains rollback data for exactly one page. -** -** The atomic-batch-write optimization can be used if OsDeviceCharacteristics() -** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is -** returned in this case. -** -** If neither optimization can be used, 0 is returned. -*/ -static int jrnlBufferSize(Pager *pPager){ - assert( !MEMDB ); - -#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ - || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) - int dc; /* Device characteristics */ - - assert( isOpen(pPager->fd) ); - dc = sqlite3OsDeviceCharacteristics(pPager->fd); -#else - UNUSED_PARAMETER(pPager); -#endif - -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){ - return -1; - } -#endif - -#ifdef SQLITE_ENABLE_ATOMIC_WRITE - { - int nSector = pPager->sectorSize; - int szPage = pPager->pageSize; - - assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); - assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); - if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){ - return 0; - } - } - - return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager); -#endif - - return 0; -} - -/* -** If SQLITE_CHECK_PAGES is defined then we do some sanity checking -** on the cache using a hash function. This is used for testing -** and debugging only. -*/ -#ifdef SQLITE_CHECK_PAGES -/* -** Return a 32-bit hash of the page data for pPage. -*/ -static u32 pager_datahash(int nByte, unsigned char *pData){ - u32 hash = 0; - int i; - for(i=0; ipPager->pageSize, (unsigned char *)pPage->pData); -} -static void pager_set_pagehash(PgHdr *pPage){ - pPage->pageHash = pager_pagehash(pPage); -} - -/* -** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES -** is defined, and NDEBUG is not defined, an assert() statement checks -** that the page is either dirty or still matches the calculated page-hash. -*/ -#define CHECK_PAGE(x) checkPage(x) -static void checkPage(PgHdr *pPg){ - Pager *pPager = pPg->pPager; - assert( pPager->eState!=PAGER_ERROR ); - assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) ); -} - -#else -#define pager_datahash(X,Y) 0 -#define pager_pagehash(X) 0 -#define pager_set_pagehash(X) -#define CHECK_PAGE(x) -#endif /* SQLITE_CHECK_PAGES */ - -/* -** When this is called the journal file for pager pPager must be open. -** This function attempts to read a super-journal file name from the -** end of the file and, if successful, copies it into memory supplied -** by the caller. See comments above writeSuperJournal() for the format -** used to store a super-journal file name at the end of a journal file. -** -** zSuper must point to a buffer of at least nSuper bytes allocated by -** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is -** enough space to write the super-journal name). If the super-journal -** name in the journal is longer than nSuper bytes (including a -** nul-terminator), then this is handled as if no super-journal name -** were present in the journal. -** -** If a super-journal file name is present at the end of the journal -** file, then it is copied into the buffer pointed to by zSuper. A -** nul-terminator byte is appended to the buffer following the -** super-journal file name. -** -** If it is determined that no super-journal file name is present -** zSuper[0] is set to 0 and SQLITE_OK returned. -** -** If an error occurs while reading from the journal file, an SQLite -** error code is returned. -*/ -static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){ - int rc; /* Return code */ - u32 len; /* Length in bytes of super-journal name */ - i64 szJ; /* Total size in bytes of journal file pJrnl */ - u32 cksum; /* MJ checksum value read from journal */ - u32 u; /* Unsigned loop counter */ - unsigned char aMagic[8]; /* A buffer to hold the magic header */ - zSuper[0] = '\0'; - - if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) - || szJ<16 - || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) - || len>=nSuper - || len>szJ-16 - || len==0 - || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum)) - || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) - || memcmp(aMagic, aJournalMagic, 8) - || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len)) - ){ - return rc; - } - - /* See if the checksum matches the super-journal name */ - for(u=0; ujournalOff, assuming a sector -** size of pPager->sectorSize bytes. -** -** i.e for a sector size of 512: -** -** Pager.journalOff Return value -** --------------------------------------- -** 0 0 -** 512 512 -** 100 512 -** 2000 2048 -** -*/ -static i64 journalHdrOffset(Pager *pPager){ - i64 offset = 0; - i64 c = pPager->journalOff; - if( c ){ - offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager); - } - assert( offset%JOURNAL_HDR_SZ(pPager)==0 ); - assert( offset>=c ); - assert( (offset-c)jfd) ); - assert( !sqlite3JournalIsInMemory(pPager->jfd) ); - if( pPager->journalOff ){ - const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */ - - IOTRACE(("JZEROHDR %p\n", pPager)) - if( doTruncate || iLimit==0 ){ - rc = sqlite3OsTruncate(pPager->jfd, 0); - }else{ - static const char zeroHdr[28] = {0}; - rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0); - } - if( rc==SQLITE_OK && !pPager->noSync ){ - rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags); - } - - /* At this point the transaction is committed but the write lock - ** is still held on the file. If there is a size limit configured for - ** the persistent journal and the journal file currently consumes more - ** space than that limit allows for, truncate it now. There is no need - ** to sync the file following this operation. - */ - if( rc==SQLITE_OK && iLimit>0 ){ - i64 sz; - rc = sqlite3OsFileSize(pPager->jfd, &sz); - if( rc==SQLITE_OK && sz>iLimit ){ - rc = sqlite3OsTruncate(pPager->jfd, iLimit); - } - } - } - return rc; -} - -/* -** The journal file must be open when this routine is called. A journal -** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the -** current location. -** -** The format for the journal header is as follows: -** - 8 bytes: Magic identifying journal format. -** - 4 bytes: Number of records in journal, or -1 no-sync mode is on. -** - 4 bytes: Random number used for page hash. -** - 4 bytes: Initial database page count. -** - 4 bytes: Sector size used by the process that wrote this journal. -** - 4 bytes: Database page size. -** -** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space. -*/ -static int writeJournalHdr(Pager *pPager){ - int rc = SQLITE_OK; /* Return code */ - char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */ - u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */ - u32 nWrite; /* Bytes of header sector written */ - int ii; /* Loop counter */ - - assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ - - if( nHeader>JOURNAL_HDR_SZ(pPager) ){ - nHeader = JOURNAL_HDR_SZ(pPager); - } - - /* If there are active savepoints and any of them were created - ** since the most recent journal header was written, update the - ** PagerSavepoint.iHdrOffset fields now. - */ - for(ii=0; iinSavepoint; ii++){ - if( pPager->aSavepoint[ii].iHdrOffset==0 ){ - pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff; - } - } - - pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager); - - /* - ** Write the nRec Field - the number of page records that follow this - ** journal header. Normally, zero is written to this value at this time. - ** After the records are added to the journal (and the journal synced, - ** if in full-sync mode), the zero is overwritten with the true number - ** of records (see syncJournal()). - ** - ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When - ** reading the journal this value tells SQLite to assume that the - ** rest of the journal file contains valid page records. This assumption - ** is dangerous, as if a failure occurred whilst writing to the journal - ** file it may contain some garbage data. There are two scenarios - ** where this risk can be ignored: - ** - ** * When the pager is in no-sync mode. Corruption can follow a - ** power failure in this case anyway. - ** - ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees - ** that garbage data is never appended to the journal file. - */ - assert( isOpen(pPager->fd) || pPager->noSync ); - if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY) - || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) - ){ - memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); - put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff); - }else{ - memset(zHeader, 0, sizeof(aJournalMagic)+4); - } - - /* The random check-hash initializer */ - sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit); - put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit); - /* The initial database size */ - put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize); - /* The assumed sector size for this process */ - put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize); - - /* The page size */ - put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize); - - /* Initializing the tail of the buffer is not necessary. Everything - ** works find if the following memset() is omitted. But initializing - ** the memory prevents valgrind from complaining, so we are willing to - ** take the performance hit. - */ - memset(&zHeader[sizeof(aJournalMagic)+20], 0, - nHeader-(sizeof(aJournalMagic)+20)); - - /* In theory, it is only necessary to write the 28 bytes that the - ** journal header consumes to the journal file here. Then increment the - ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next - ** record is written to the following sector (leaving a gap in the file - ** that will be implicitly filled in by the OS). - ** - ** However it has been discovered that on some systems this pattern can - ** be significantly slower than contiguously writing data to the file, - ** even if that means explicitly writing data to the block of - ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what - ** is done. - ** - ** The loop is required here in case the sector-size is larger than the - ** database page size. Since the zHeader buffer is only Pager.pageSize - ** bytes in size, more than one call to sqlite3OsWrite() may be required - ** to populate the entire journal header sector. - */ - for(nWrite=0; rc==SQLITE_OK&&nWritejournalHdr, nHeader)) - rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff); - assert( pPager->journalHdr <= pPager->journalOff ); - pPager->journalOff += nHeader; - } - - return rc; -} - -/* -** The journal file must be open when this is called. A journal header file -** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal -** file. The current location in the journal file is given by -** pPager->journalOff. See comments above function writeJournalHdr() for -** a description of the journal header format. -** -** If the header is read successfully, *pNRec is set to the number of -** page records following this header and *pDbSize is set to the size of the -** database before the transaction began, in pages. Also, pPager->cksumInit -** is set to the value read from the journal header. SQLITE_OK is returned -** in this case. -** -** If the journal header file appears to be corrupted, SQLITE_DONE is -** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes -** cannot be read from the journal file an error code is returned. -*/ -static int readJournalHdr( - Pager *pPager, /* Pager object */ - int isHot, - i64 journalSize, /* Size of the open journal file in bytes */ - u32 *pNRec, /* OUT: Value read from the nRec field */ - u32 *pDbSize /* OUT: Value of original database size field */ -){ - int rc; /* Return code */ - unsigned char aMagic[8]; /* A buffer to hold the magic header */ - i64 iHdrOff; /* Offset of journal header being read */ - - assert( isOpen(pPager->jfd) ); /* Journal file must be open. */ - - /* Advance Pager.journalOff to the start of the next sector. If the - ** journal file is too small for there to be a header stored at this - ** point, return SQLITE_DONE. - */ - pPager->journalOff = journalHdrOffset(pPager); - if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){ - return SQLITE_DONE; - } - iHdrOff = pPager->journalOff; - - /* Read in the first 8 bytes of the journal header. If they do not match - ** the magic string found at the start of each journal header, return - ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise, - ** proceed. - */ - if( isHot || iHdrOff!=pPager->journalHdr ){ - rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff); - if( rc ){ - return rc; - } - if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){ - return SQLITE_DONE; - } - } - - /* Read the first three 32-bit fields of the journal header: The nRec - ** field, the checksum-initializer and the database size at the start - ** of the transaction. Return an error code if anything goes wrong. - */ - if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec)) - || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit)) - || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize)) - ){ - return rc; - } - - if( pPager->journalOff==0 ){ - u32 iPageSize; /* Page-size field of journal header */ - u32 iSectorSize; /* Sector-size field of journal header */ - - /* Read the page-size and sector-size journal header fields. */ - if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize)) - || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize)) - ){ - return rc; - } - - /* Versions of SQLite prior to 3.5.8 set the page-size field of the - ** journal header to zero. In this case, assume that the Pager.pageSize - ** variable is already set to the correct page size. - */ - if( iPageSize==0 ){ - iPageSize = pPager->pageSize; - } - - /* Check that the values read from the page-size and sector-size fields - ** are within range. To be 'in range', both values need to be a power - ** of two greater than or equal to 512 or 32, and not greater than their - ** respective compile time maximum limits. - */ - if( iPageSize<512 || iSectorSize<32 - || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE - || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0 - ){ - /* If the either the page-size or sector-size in the journal-header is - ** invalid, then the process that wrote the journal-header must have - ** crashed before the header was synced. In this case stop reading - ** the journal file here. - */ - return SQLITE_DONE; - } - - /* Update the page-size to match the value read from the journal. - ** Use a testcase() macro to make sure that malloc failure within - ** PagerSetPagesize() is tested. - */ - rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1); - testcase( rc!=SQLITE_OK ); - - /* Update the assumed sector-size to match the value used by - ** the process that created this journal. If this journal was - ** created by a process other than this one, then this routine - ** is being called from within pager_playback(). The local value - ** of Pager.sectorSize is restored at the end of that routine. - */ - pPager->sectorSize = iSectorSize; - } - - pPager->journalOff += JOURNAL_HDR_SZ(pPager); - return rc; -} - - -/* -** Write the supplied super-journal name into the journal file for pager -** pPager at the current location. The super-journal name must be the last -** thing written to a journal file. If the pager is in full-sync mode, the -** journal file descriptor is advanced to the next sector boundary before -** anything is written. The format is: -** -** + 4 bytes: PAGER_MJ_PGNO. -** + N bytes: super-journal filename in utf-8. -** + 4 bytes: N (length of super-journal name in bytes, no nul-terminator). -** + 4 bytes: super-journal name checksum. -** + 8 bytes: aJournalMagic[]. -** -** The super-journal page checksum is the sum of the bytes in thesuper-journal -** name, where each byte is interpreted as a signed 8-bit integer. -** -** If zSuper is a NULL pointer (occurs for a single database transaction), -** this call is a no-op. -*/ -static int writeSuperJournal(Pager *pPager, const char *zSuper){ - int rc; /* Return code */ - int nSuper; /* Length of string zSuper */ - i64 iHdrOff; /* Offset of header in journal file */ - i64 jrnlSize; /* Size of journal file on disk */ - u32 cksum = 0; /* Checksum of string zSuper */ - - assert( pPager->setSuper==0 ); - assert( !pagerUseWal(pPager) ); - - if( !zSuper - || pPager->journalMode==PAGER_JOURNALMODE_MEMORY - || !isOpen(pPager->jfd) - ){ - return SQLITE_OK; - } - pPager->setSuper = 1; - assert( pPager->journalHdr <= pPager->journalOff ); - - /* Calculate the length in bytes and the checksum of zSuper */ - for(nSuper=0; zSuper[nSuper]; nSuper++){ - cksum += zSuper[nSuper]; - } - - /* If in full-sync mode, advance to the next disk sector before writing - ** the super-journal name. This is in case the previous page written to - ** the journal has already been synced. - */ - if( pPager->fullSync ){ - pPager->journalOff = journalHdrOffset(pPager); - } - iHdrOff = pPager->journalOff; - - /* Write the super-journal data to the end of the journal file. If - ** an error occurs, return the error code to the caller. - */ - if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))) - || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4))) - || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper))) - || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum))) - || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, - iHdrOff+4+nSuper+8))) - ){ - return rc; - } - pPager->journalOff += (nSuper+20); - - /* If the pager is in peristent-journal mode, then the physical - ** journal-file may extend past the end of the super-journal name - ** and 8 bytes of magic data just written to the file. This is - ** dangerous because the code to rollback a hot-journal file - ** will not be able to find the super-journal name to determine - ** whether or not the journal is hot. - ** - ** Easiest thing to do in this scenario is to truncate the journal - ** file to the required size. - */ - if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize)) - && jrnlSize>pPager->journalOff - ){ - rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff); - } - return rc; -} - -/* -** Discard the entire contents of the in-memory page-cache. -*/ -static void pager_reset(Pager *pPager){ - pPager->iDataVersion++; - sqlite3BackupRestart(pPager->pBackup); - sqlite3PcacheClear(pPager->pPCache); -} - -/* -** Return the pPager->iDataVersion value -*/ -SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){ - return pPager->iDataVersion; -} - -/* -** Free all structures in the Pager.aSavepoint[] array and set both -** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal -** if it is open and the pager is not in exclusive mode. -*/ -static void releaseAllSavepoints(Pager *pPager){ - int ii; /* Iterator for looping through Pager.aSavepoint */ - for(ii=0; iinSavepoint; ii++){ - sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); - } - if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){ - sqlite3OsClose(pPager->sjfd); - } - sqlite3_free(pPager->aSavepoint); - pPager->aSavepoint = 0; - pPager->nSavepoint = 0; - pPager->nSubRec = 0; -} - -/* -** Set the bit number pgno in the PagerSavepoint.pInSavepoint -** bitvecs of all open savepoints. Return SQLITE_OK if successful -** or SQLITE_NOMEM if a malloc failure occurs. -*/ -static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){ - int ii; /* Loop counter */ - int rc = SQLITE_OK; /* Result code */ - - for(ii=0; iinSavepoint; ii++){ - PagerSavepoint *p = &pPager->aSavepoint[ii]; - if( pgno<=p->nOrig ){ - rc |= sqlite3BitvecSet(p->pInSavepoint, pgno); - testcase( rc==SQLITE_NOMEM ); - assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); - } - } - return rc; -} - -/* -** This function is a no-op if the pager is in exclusive mode and not -** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN -** state. -** -** If the pager is not in exclusive-access mode, the database file is -** completely unlocked. If the file is unlocked and the file-system does -** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is -** closed (if it is open). -** -** If the pager is in ERROR state when this function is called, the -** contents of the pager cache are discarded before switching back to -** the OPEN state. Regardless of whether the pager is in exclusive-mode -** or not, any journal file left in the file-system will be treated -** as a hot-journal and rolled back the next time a read-transaction -** is opened (by this or by any other connection). -*/ -static void pager_unlock(Pager *pPager){ - - assert( pPager->eState==PAGER_READER - || pPager->eState==PAGER_OPEN - || pPager->eState==PAGER_ERROR - ); - - sqlite3BitvecDestroy(pPager->pInJournal); - pPager->pInJournal = 0; - releaseAllSavepoints(pPager); - - if( pagerUseWal(pPager) ){ - assert( !isOpen(pPager->jfd) ); - sqlite3WalEndReadTransaction(pPager->pWal); - pPager->eState = PAGER_OPEN; - }else if( !pPager->exclusiveMode ){ - int rc; /* Error code returned by pagerUnlockDb() */ - int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0; - - /* If the operating system support deletion of open files, then - ** close the journal file when dropping the database lock. Otherwise - ** another connection with journal_mode=delete might delete the file - ** out from under us. - */ - assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 ); - assert( (PAGER_JOURNALMODE_OFF & 5)!=1 ); - assert( (PAGER_JOURNALMODE_WAL & 5)!=1 ); - assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 ); - assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); - assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); - if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN) - || 1!=(pPager->journalMode & 5) - ){ - sqlite3OsClose(pPager->jfd); - } - - /* If the pager is in the ERROR state and the call to unlock the database - ** file fails, set the current lock to UNKNOWN_LOCK. See the comment - ** above the #define for UNKNOWN_LOCK for an explanation of why this - ** is necessary. - */ - rc = pagerUnlockDb(pPager, NO_LOCK); - if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){ - pPager->eLock = UNKNOWN_LOCK; - } - - /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here - ** without clearing the error code. This is intentional - the error - ** code is cleared and the cache reset in the block below. - */ - assert( pPager->errCode || pPager->eState!=PAGER_ERROR ); - pPager->eState = PAGER_OPEN; - } - - /* If Pager.errCode is set, the contents of the pager cache cannot be - ** trusted. Now that there are no outstanding references to the pager, - ** it can safely move back to PAGER_OPEN state. This happens in both - ** normal and exclusive-locking mode. - */ - assert( pPager->errCode==SQLITE_OK || !MEMDB ); - if( pPager->errCode ){ - if( pPager->tempFile==0 ){ - pager_reset(pPager); - pPager->changeCountDone = 0; - pPager->eState = PAGER_OPEN; - }else{ - pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER); - } - if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); - pPager->errCode = SQLITE_OK; - setGetterMethod(pPager); - } - - pPager->journalOff = 0; - pPager->journalHdr = 0; - pPager->setSuper = 0; -} - -/* -** This function is called whenever an IOERR or FULL error that requires -** the pager to transition into the ERROR state may ahve occurred. -** The first argument is a pointer to the pager structure, the second -** the error-code about to be returned by a pager API function. The -** value returned is a copy of the second argument to this function. -** -** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the -** IOERR sub-codes, the pager enters the ERROR state and the error code -** is stored in Pager.errCode. While the pager remains in the ERROR state, -** all major API calls on the Pager will immediately return Pager.errCode. -** -** The ERROR state indicates that the contents of the pager-cache -** cannot be trusted. This state can be cleared by completely discarding -** the contents of the pager-cache. If a transaction was active when -** the persistent error occurred, then the rollback journal may need -** to be replayed to restore the contents of the database file (as if -** it were a hot-journal). -*/ -static int pager_error(Pager *pPager, int rc){ - int rc2 = rc & 0xff; - assert( rc==SQLITE_OK || !MEMDB ); - assert( - pPager->errCode==SQLITE_FULL || - pPager->errCode==SQLITE_OK || - (pPager->errCode & 0xff)==SQLITE_IOERR - ); - if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){ - pPager->errCode = rc; - pPager->eState = PAGER_ERROR; - setGetterMethod(pPager); - } - return rc; -} - -static int pager_truncate(Pager *pPager, Pgno nPage); - -/* -** The write transaction open on pPager is being committed (bCommit==1) -** or rolled back (bCommit==0). -** -** Return TRUE if and only if all dirty pages should be flushed to disk. -** -** Rules: -** -** * For non-TEMP databases, always sync to disk. This is necessary -** for transactions to be durable. -** -** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing -** file has been created already (via a spill on pagerStress()) and -** when the number of dirty pages in memory exceeds 25% of the total -** cache size. -*/ -static int pagerFlushOnCommit(Pager *pPager, int bCommit){ - if( pPager->tempFile==0 ) return 1; - if( !bCommit ) return 0; - if( !isOpen(pPager->fd) ) return 0; - return (sqlite3PCachePercentDirty(pPager->pPCache)>=25); -} - -/* -** This routine ends a transaction. A transaction is usually ended by -** either a COMMIT or a ROLLBACK operation. This routine may be called -** after rollback of a hot-journal, or if an error occurs while opening -** the journal file or writing the very first journal-header of a -** database transaction. -** -** This routine is never called in PAGER_ERROR state. If it is called -** in PAGER_NONE or PAGER_SHARED state and the lock held is less -** exclusive than a RESERVED lock, it is a no-op. -** -** Otherwise, any active savepoints are released. -** -** If the journal file is open, then it is "finalized". Once a journal -** file has been finalized it is not possible to use it to roll back a -** transaction. Nor will it be considered to be a hot-journal by this -** or any other database connection. Exactly how a journal is finalized -** depends on whether or not the pager is running in exclusive mode and -** the current journal-mode (Pager.journalMode value), as follows: -** -** journalMode==MEMORY -** Journal file descriptor is simply closed. This destroys an -** in-memory journal. -** -** journalMode==TRUNCATE -** Journal file is truncated to zero bytes in size. -** -** journalMode==PERSIST -** The first 28 bytes of the journal file are zeroed. This invalidates -** the first journal header in the file, and hence the entire journal -** file. An invalid journal file cannot be rolled back. -** -** journalMode==DELETE -** The journal file is closed and deleted using sqlite3OsDelete(). -** -** If the pager is running in exclusive mode, this method of finalizing -** the journal file is never used. Instead, if the journalMode is -** DELETE and the pager is in exclusive mode, the method described under -** journalMode==PERSIST is used instead. -** -** After the journal is finalized, the pager moves to PAGER_READER state. -** If running in non-exclusive rollback mode, the lock on the file is -** downgraded to a SHARED_LOCK. -** -** SQLITE_OK is returned if no error occurs. If an error occurs during -** any of the IO operations to finalize the journal file or unlock the -** database then the IO error code is returned to the user. If the -** operation to finalize the journal file fails, then the code still -** tries to unlock the database file if not in exclusive mode. If the -** unlock operation fails as well, then the first error code related -** to the first error encountered (the journal finalization one) is -** returned. -*/ -static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){ - int rc = SQLITE_OK; /* Error code from journal finalization operation */ - int rc2 = SQLITE_OK; /* Error code from db file unlock operation */ - - /* Do nothing if the pager does not have an open write transaction - ** or at least a RESERVED lock. This function may be called when there - ** is no write-transaction active but a RESERVED or greater lock is - ** held under two circumstances: - ** - ** 1. After a successful hot-journal rollback, it is called with - ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK. - ** - ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE - ** lock switches back to locking_mode=normal and then executes a - ** read-transaction, this function is called with eState==PAGER_READER - ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed. - */ - assert( assert_pager_state(pPager) ); - assert( pPager->eState!=PAGER_ERROR ); - if( pPager->eStateeLockjfd) || pPager->pInJournal==0 - || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC) - ); - if( isOpen(pPager->jfd) ){ - assert( !pagerUseWal(pPager) ); - - /* Finalize the journal file. */ - if( sqlite3JournalIsInMemory(pPager->jfd) ){ - /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */ - sqlite3OsClose(pPager->jfd); - }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){ - if( pPager->journalOff==0 ){ - rc = SQLITE_OK; - }else{ - rc = sqlite3OsTruncate(pPager->jfd, 0); - if( rc==SQLITE_OK && pPager->fullSync ){ - /* Make sure the new file size is written into the inode right away. - ** Otherwise the journal might resurrect following a power loss and - ** cause the last transaction to roll back. See - ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773 - */ - rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); - } - } - pPager->journalOff = 0; - }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST - || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL) - ){ - rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile); - pPager->journalOff = 0; - }else{ - /* This branch may be executed with Pager.journalMode==MEMORY if - ** a hot-journal was just rolled back. In this case the journal - ** file should be closed and deleted. If this connection writes to - ** the database file, it will do so using an in-memory journal. - */ - int bDelete = !pPager->tempFile; - assert( sqlite3JournalIsInMemory(pPager->jfd)==0 ); - assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE - || pPager->journalMode==PAGER_JOURNALMODE_MEMORY - || pPager->journalMode==PAGER_JOURNALMODE_WAL - ); - sqlite3OsClose(pPager->jfd); - if( bDelete ){ - rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync); - } - } - } - -#ifdef SQLITE_CHECK_PAGES - sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash); - if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){ - PgHdr *p = sqlite3PagerLookup(pPager, 1); - if( p ){ - p->pageHash = 0; - sqlite3PagerUnrefNotNull(p); - } - } -#endif - - sqlite3BitvecDestroy(pPager->pInJournal); - pPager->pInJournal = 0; - pPager->nRec = 0; - if( rc==SQLITE_OK ){ - if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){ - sqlite3PcacheCleanAll(pPager->pPCache); - }else{ - sqlite3PcacheClearWritable(pPager->pPCache); - } - sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize); - } - - if( pagerUseWal(pPager) ){ - /* Drop the WAL write-lock, if any. Also, if the connection was in - ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE - ** lock held on the database file. - */ - rc2 = sqlite3WalEndWriteTransaction(pPager->pWal); - assert( rc2==SQLITE_OK ); - }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){ - /* This branch is taken when committing a transaction in rollback-journal - ** mode if the database file on disk is larger than the database image. - ** At this point the journal has been finalized and the transaction - ** successfully committed, but the EXCLUSIVE lock is still held on the - ** file. So it is safe to truncate the database file to its minimum - ** required size. */ - assert( pPager->eLock==EXCLUSIVE_LOCK ); - rc = pager_truncate(pPager, pPager->dbSize); - } - - if( rc==SQLITE_OK && bCommit ){ - rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0); - if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; - } - - if( !pPager->exclusiveMode - && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0)) - ){ - rc2 = pagerUnlockDb(pPager, SHARED_LOCK); - } - pPager->eState = PAGER_READER; - pPager->setSuper = 0; - - return (rc==SQLITE_OK?rc2:rc); -} - -/* -** Execute a rollback if a transaction is active and unlock the -** database file. -** -** If the pager has already entered the ERROR state, do not attempt -** the rollback at this time. Instead, pager_unlock() is called. The -** call to pager_unlock() will discard all in-memory pages, unlock -** the database file and move the pager back to OPEN state. If this -** means that there is a hot-journal left in the file-system, the next -** connection to obtain a shared lock on the pager (which may be this one) -** will roll it back. -** -** If the pager has not already entered the ERROR state, but an IO or -** malloc error occurs during a rollback, then this will itself cause -** the pager to enter the ERROR state. Which will be cleared by the -** call to pager_unlock(), as described above. -*/ -static void pagerUnlockAndRollback(Pager *pPager){ - if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){ - assert( assert_pager_state(pPager) ); - if( pPager->eState>=PAGER_WRITER_LOCKED ){ - sqlite3BeginBenignMalloc(); - sqlite3PagerRollback(pPager); - sqlite3EndBenignMalloc(); - }else if( !pPager->exclusiveMode ){ - assert( pPager->eState==PAGER_READER ); - pager_end_transaction(pPager, 0, 0); - } - } - pager_unlock(pPager); -} - -/* -** Parameter aData must point to a buffer of pPager->pageSize bytes -** of data. Compute and return a checksum based ont the contents of the -** page of data and the current value of pPager->cksumInit. -** -** This is not a real checksum. It is really just the sum of the -** random initial value (pPager->cksumInit) and every 200th byte -** of the page data, starting with byte offset (pPager->pageSize%200). -** Each byte is interpreted as an 8-bit unsigned integer. -** -** Changing the formula used to compute this checksum results in an -** incompatible journal file format. -** -** If journal corruption occurs due to a power failure, the most likely -** scenario is that one end or the other of the record will be changed. -** It is much less likely that the two ends of the journal record will be -** correct and the middle be corrupt. Thus, this "checksum" scheme, -** though fast and simple, catches the mostly likely kind of corruption. -*/ -static u32 pager_cksum(Pager *pPager, const u8 *aData){ - u32 cksum = pPager->cksumInit; /* Checksum value to return */ - int i = pPager->pageSize-200; /* Loop counter */ - while( i>0 ){ - cksum += aData[i]; - i -= 200; - } - return cksum; -} - -/* -** Read a single page from either the journal file (if isMainJrnl==1) or -** from the sub-journal (if isMainJrnl==0) and playback that page. -** The page begins at offset *pOffset into the file. The *pOffset -** value is increased to the start of the next page in the journal. -** -** The main rollback journal uses checksums - the statement journal does -** not. -** -** If the page number of the page record read from the (sub-)journal file -** is greater than the current value of Pager.dbSize, then playback is -** skipped and SQLITE_OK is returned. -** -** If pDone is not NULL, then it is a record of pages that have already -** been played back. If the page at *pOffset has already been played back -** (if the corresponding pDone bit is set) then skip the playback. -** Make sure the pDone bit corresponding to the *pOffset page is set -** prior to returning. -** -** If the page record is successfully read from the (sub-)journal file -** and played back, then SQLITE_OK is returned. If an IO error occurs -** while reading the record from the (sub-)journal file or while writing -** to the database file, then the IO error code is returned. If data -** is successfully read from the (sub-)journal file but appears to be -** corrupted, SQLITE_DONE is returned. Data is considered corrupted in -** two circumstances: -** -** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or -** * If the record is being rolled back from the main journal file -** and the checksum field does not match the record content. -** -** Neither of these two scenarios are possible during a savepoint rollback. -** -** If this is a savepoint rollback, then memory may have to be dynamically -** allocated by this function. If this is the case and an allocation fails, -** SQLITE_NOMEM is returned. -*/ -static int pager_playback_one_page( - Pager *pPager, /* The pager being played back */ - i64 *pOffset, /* Offset of record to playback */ - Bitvec *pDone, /* Bitvec of pages already played back */ - int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */ - int isSavepnt /* True for a savepoint rollback */ -){ - int rc; - PgHdr *pPg; /* An existing page in the cache */ - Pgno pgno; /* The page number of a page in journal */ - u32 cksum; /* Checksum used for sanity checking */ - char *aData; /* Temporary storage for the page */ - sqlite3_file *jfd; /* The file descriptor for the journal file */ - int isSynced; /* True if journal page is synced */ - - assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */ - assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */ - assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */ - assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */ - - aData = pPager->pTmpSpace; - assert( aData ); /* Temp storage must have already been allocated */ - assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) ); - - /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction - ** or savepoint rollback done at the request of the caller) or this is - ** a hot-journal rollback. If it is a hot-journal rollback, the pager - ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback - ** only reads from the main journal, not the sub-journal. - */ - assert( pPager->eState>=PAGER_WRITER_CACHEMOD - || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK) - ); - assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl ); - - /* Read the page number and page data from the journal or sub-journal - ** file. Return an error code to the caller if an IO error occurs. - */ - jfd = isMainJrnl ? pPager->jfd : pPager->sjfd; - rc = read32bits(jfd, *pOffset, &pgno); - if( rc!=SQLITE_OK ) return rc; - rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4); - if( rc!=SQLITE_OK ) return rc; - *pOffset += pPager->pageSize + 4 + isMainJrnl*4; - - /* Sanity checking on the page. This is more important that I originally - ** thought. If a power failure occurs while the journal is being written, - ** it could cause invalid data to be written into the journal. We need to - ** detect this invalid data (with high probability) and ignore it. - */ - if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ - assert( !isSavepnt ); - return SQLITE_DONE; - } - if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){ - return SQLITE_OK; - } - if( isMainJrnl ){ - rc = read32bits(jfd, (*pOffset)-4, &cksum); - if( rc ) return rc; - if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){ - return SQLITE_DONE; - } - } - - /* If this page has already been played back before during the current - ** rollback, then don't bother to play it back again. - */ - if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){ - return rc; - } - - /* When playing back page 1, restore the nReserve setting - */ - if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){ - pPager->nReserve = ((u8*)aData)[20]; - } - - /* If the pager is in CACHEMOD state, then there must be a copy of this - ** page in the pager cache. In this case just update the pager cache, - ** not the database file. The page is left marked dirty in this case. - ** - ** An exception to the above rule: If the database is in no-sync mode - ** and a page is moved during an incremental vacuum then the page may - ** not be in the pager cache. Later: if a malloc() or IO error occurs - ** during a Movepage() call, then the page may not be in the cache - ** either. So the condition described in the above paragraph is not - ** assert()able. - ** - ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the - ** pager cache if it exists and the main file. The page is then marked - ** not dirty. Since this code is only executed in PAGER_OPEN state for - ** a hot-journal rollback, it is guaranteed that the page-cache is empty - ** if the pager is in OPEN state. - ** - ** Ticket #1171: The statement journal might contain page content that is - ** different from the page content at the start of the transaction. - ** This occurs when a page is changed prior to the start of a statement - ** then changed again within the statement. When rolling back such a - ** statement we must not write to the original database unless we know - ** for certain that original page contents are synced into the main rollback - ** journal. Otherwise, a power loss might leave modified data in the - ** database file without an entry in the rollback journal that can - ** restore the database to its original form. Two conditions must be - ** met before writing to the database files. (1) the database must be - ** locked. (2) we know that the original page content is fully synced - ** in the main journal either because the page is not in cache or else - ** the page is marked as needSync==0. - ** - ** 2008-04-14: When attempting to vacuum a corrupt database file, it - ** is possible to fail a statement on a database that does not yet exist. - ** Do not attempt to write if database file has never been opened. - */ - if( pagerUseWal(pPager) ){ - pPg = 0; - }else{ - pPg = sqlite3PagerLookup(pPager, pgno); - } - assert( pPg || !MEMDB ); - assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile ); - PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n", - PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData), - (isMainJrnl?"main-journal":"sub-journal") - )); - if( isMainJrnl ){ - isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr); - }else{ - isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC)); - } - if( isOpen(pPager->fd) - && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) - && isSynced - ){ - i64 ofst = (pgno-1)*(i64)pPager->pageSize; - testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 ); - assert( !pagerUseWal(pPager) ); - - /* Write the data read from the journal back into the database file. - ** This is usually safe even for an encrypted database - as the data - ** was encrypted before it was written to the journal file. The exception - ** is if the data was just read from an in-memory sub-journal. In that - ** case it must be encrypted here before it is copied into the database - ** file. */ - rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); - - if( pgno>pPager->dbFileSize ){ - pPager->dbFileSize = pgno; - } - if( pPager->pBackup ){ - sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); - } - }else if( !isMainJrnl && pPg==0 ){ - /* If this is a rollback of a savepoint and data was not written to - ** the database and the page is not in-memory, there is a potential - ** problem. When the page is next fetched by the b-tree layer, it - ** will be read from the database file, which may or may not be - ** current. - ** - ** There are a couple of different ways this can happen. All are quite - ** obscure. When running in synchronous mode, this can only happen - ** if the page is on the free-list at the start of the transaction, then - ** populated, then moved using sqlite3PagerMovepage(). - ** - ** The solution is to add an in-memory page to the cache containing - ** the data just read from the sub-journal. Mark the page as dirty - ** and if the pager requires a journal-sync, then mark the page as - ** requiring a journal-sync before it is written. - */ - assert( isSavepnt ); - assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 ); - pPager->doNotSpill |= SPILLFLAG_ROLLBACK; - rc = sqlite3PagerGet(pPager, pgno, &pPg, 1); - assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 ); - pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK; - if( rc!=SQLITE_OK ) return rc; - sqlite3PcacheMakeDirty(pPg); - } - if( pPg ){ - /* No page should ever be explicitly rolled back that is in use, except - ** for page 1 which is held in use in order to keep the lock on the - ** database active. However such a page may be rolled back as a result - ** of an internal error resulting in an automatic call to - ** sqlite3PagerRollback(). - */ - void *pData; - pData = pPg->pData; - memcpy(pData, (u8*)aData, pPager->pageSize); - pPager->xReiniter(pPg); - /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But - ** that call was dangerous and had no detectable benefit since the cache - ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so - ** has been removed. */ - pager_set_pagehash(pPg); - - /* If this was page 1, then restore the value of Pager.dbFileVers. - ** Do this before any decoding. */ - if( pgno==1 ){ - memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers)); - } - sqlite3PcacheRelease(pPg); - } - return rc; -} - -/* -** Parameter zSuper is the name of a super-journal file. A single journal -** file that referred to the super-journal file has just been rolled back. -** This routine checks if it is possible to delete the super-journal file, -** and does so if it is. -** -** Argument zSuper may point to Pager.pTmpSpace. So that buffer is not -** available for use within this function. -** -** When a super-journal file is created, it is populated with the names -** of all of its child journals, one after another, formatted as utf-8 -** encoded text. The end of each child journal file is marked with a -** nul-terminator byte (0x00). i.e. the entire contents of a super-journal -** file for a transaction involving two databases might be: -** -** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" -** -** A super-journal file may only be deleted once all of its child -** journals have been rolled back. -** -** This function reads the contents of the super-journal file into -** memory and loops through each of the child journal names. For -** each child journal, it checks if: -** -** * if the child journal exists, and if so -** * if the child journal contains a reference to super-journal -** file zSuper -** -** If a child journal can be found that matches both of the criteria -** above, this function returns without doing anything. Otherwise, if -** no such child journal can be found, file zSuper is deleted from -** the file-system using sqlite3OsDelete(). -** -** If an IO error within this function, an error code is returned. This -** function allocates memory by calling sqlite3Malloc(). If an allocation -** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors -** occur, SQLITE_OK is returned. -** -** TODO: This function allocates a single block of memory to load -** the entire contents of the super-journal file. This could be -** a couple of kilobytes or so - potentially larger than the page -** size. -*/ -static int pager_delsuper(Pager *pPager, const char *zSuper){ - sqlite3_vfs *pVfs = pPager->pVfs; - int rc; /* Return code */ - sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */ - sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ - char *zSuperJournal = 0; /* Contents of super-journal file */ - i64 nSuperJournal; /* Size of super-journal file */ - char *zJournal; /* Pointer to one journal within MJ file */ - char *zSuperPtr; /* Space to hold super-journal filename */ - int nSuperPtr; /* Amount of space allocated to zSuperPtr[] */ - - /* Allocate space for both the pJournal and pSuper file descriptors. - ** If successful, open the super-journal file for reading. - */ - pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); - if( !pSuper ){ - rc = SQLITE_NOMEM_BKPT; - pJournal = 0; - }else{ - const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL); - rc = sqlite3OsOpen(pVfs, zSuper, pSuper, flags, 0); - pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile); - } - if( rc!=SQLITE_OK ) goto delsuper_out; - - /* Load the entire super-journal file into space obtained from - ** sqlite3_malloc() and pointed to by zSuperJournal. Also obtain - ** sufficient space (in zSuperPtr) to hold the names of super-journal - ** files extracted from regular rollback-journals. - */ - rc = sqlite3OsFileSize(pSuper, &nSuperJournal); - if( rc!=SQLITE_OK ) goto delsuper_out; - nSuperPtr = pVfs->mxPathname+1; - zSuperJournal = sqlite3Malloc(nSuperJournal + nSuperPtr + 2); - if( !zSuperJournal ){ - rc = SQLITE_NOMEM_BKPT; - goto delsuper_out; - } - zSuperPtr = &zSuperJournal[nSuperJournal+2]; - rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0); - if( rc!=SQLITE_OK ) goto delsuper_out; - zSuperJournal[nSuperJournal] = 0; - zSuperJournal[nSuperJournal+1] = 0; - - zJournal = zSuperJournal; - while( (zJournal-zSuperJournal)pageSize bytes). -** If the file on disk is currently larger than nPage pages, then use the VFS -** xTruncate() method to truncate it. -** -** Or, it might be the case that the file on disk is smaller than -** nPage pages. Some operating system implementations can get confused if -** you try to truncate a file to some size that is larger than it -** currently is, so detect this case and write a single zero byte to -** the end of the new file instead. -** -** If successful, return SQLITE_OK. If an IO error occurs while modifying -** the database file, return the error code to the caller. -*/ -static int pager_truncate(Pager *pPager, Pgno nPage){ - int rc = SQLITE_OK; - assert( pPager->eState!=PAGER_ERROR ); - assert( pPager->eState!=PAGER_READER ); - - if( isOpen(pPager->fd) - && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) - ){ - i64 currentSize, newSize; - int szPage = pPager->pageSize; - assert( pPager->eLock==EXCLUSIVE_LOCK ); - /* TODO: Is it safe to use Pager.dbFileSize here? */ - rc = sqlite3OsFileSize(pPager->fd, ¤tSize); - newSize = szPage*(i64)nPage; - if( rc==SQLITE_OK && currentSize!=newSize ){ - if( currentSize>newSize ){ - rc = sqlite3OsTruncate(pPager->fd, newSize); - }else if( (currentSize+szPage)<=newSize ){ - char *pTmp = pPager->pTmpSpace; - memset(pTmp, 0, szPage); - testcase( (newSize-szPage) == currentSize ); - testcase( (newSize-szPage) > currentSize ); - rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage); - } - if( rc==SQLITE_OK ){ - pPager->dbFileSize = nPage; - } - } - } - return rc; -} - -/* -** Return a sanitized version of the sector-size of OS file pFile. The -** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE. -*/ -SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){ - int iRet = sqlite3OsSectorSize(pFile); - if( iRet<32 ){ - iRet = 512; - }else if( iRet>MAX_SECTOR_SIZE ){ - assert( MAX_SECTOR_SIZE>=512 ); - iRet = MAX_SECTOR_SIZE; - } - return iRet; -} - -/* -** Set the value of the Pager.sectorSize variable for the given -** pager based on the value returned by the xSectorSize method -** of the open database file. The sector size will be used -** to determine the size and alignment of journal header and -** super-journal pointers within created journal files. -** -** For temporary files the effective sector size is always 512 bytes. -** -** Otherwise, for non-temporary files, the effective sector size is -** the value returned by the xSectorSize() method rounded up to 32 if -** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it -** is greater than MAX_SECTOR_SIZE. -** -** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set -** the effective sector size to its minimum value (512). The purpose of -** pPager->sectorSize is to define the "blast radius" of bytes that -** might change if a crash occurs while writing to a single byte in -** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero -** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector -** size. For backwards compatibility of the rollback journal file format, -** we cannot reduce the effective sector size below 512. -*/ -static void setSectorSize(Pager *pPager){ - assert( isOpen(pPager->fd) || pPager->tempFile ); - - if( pPager->tempFile - || (sqlite3OsDeviceCharacteristics(pPager->fd) & - SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0 - ){ - /* Sector size doesn't matter for temporary files. Also, the file - ** may not have been opened yet, in which case the OsSectorSize() - ** call will segfault. */ - pPager->sectorSize = 512; - }else{ - pPager->sectorSize = sqlite3SectorSize(pPager->fd); - } -} - -/* -** Playback the journal and thus restore the database file to -** the state it was in before we started making changes. -** -** The journal file format is as follows: -** -** (1) 8 byte prefix. A copy of aJournalMagic[]. -** (2) 4 byte big-endian integer which is the number of valid page records -** in the journal. If this value is 0xffffffff, then compute the -** number of page records from the journal size. -** (3) 4 byte big-endian integer which is the initial value for the -** sanity checksum. -** (4) 4 byte integer which is the number of pages to truncate the -** database to during a rollback. -** (5) 4 byte big-endian integer which is the sector size. The header -** is this many bytes in size. -** (6) 4 byte big-endian integer which is the page size. -** (7) zero padding out to the next sector size. -** (8) Zero or more pages instances, each as follows: -** + 4 byte page number. -** + pPager->pageSize bytes of data. -** + 4 byte checksum -** -** When we speak of the journal header, we mean the first 7 items above. -** Each entry in the journal is an instance of the 8th item. -** -** Call the value from the second bullet "nRec". nRec is the number of -** valid page entries in the journal. In most cases, you can compute the -** value of nRec from the size of the journal file. But if a power -** failure occurred while the journal was being written, it could be the -** case that the size of the journal file had already been increased but -** the extra entries had not yet made it safely to disk. In such a case, -** the value of nRec computed from the file size would be too large. For -** that reason, we always use the nRec value in the header. -** -** If the nRec value is 0xffffffff it means that nRec should be computed -** from the file size. This value is used when the user selects the -** no-sync option for the journal. A power failure could lead to corruption -** in this case. But for things like temporary table (which will be -** deleted when the power is restored) we don't care. -** -** If the file opened as the journal file is not a well-formed -** journal file then all pages up to the first corrupted page are rolled -** back (or no pages if the journal header is corrupted). The journal file -** is then deleted and SQLITE_OK returned, just as if no corruption had -** been encountered. -** -** If an I/O or malloc() error occurs, the journal-file is not deleted -** and an error code is returned. -** -** The isHot parameter indicates that we are trying to rollback a journal -** that might be a hot journal. Or, it could be that the journal is -** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE. -** If the journal really is hot, reset the pager cache prior rolling -** back any content. If the journal is merely persistent, no reset is -** needed. -*/ -static int pager_playback(Pager *pPager, int isHot){ - sqlite3_vfs *pVfs = pPager->pVfs; - i64 szJ; /* Size of the journal file in bytes */ - u32 nRec; /* Number of Records in the journal */ - u32 u; /* Unsigned loop counter */ - Pgno mxPg = 0; /* Size of the original file in pages */ - int rc; /* Result code of a subroutine */ - int res = 1; /* Value returned by sqlite3OsAccess() */ - char *zSuper = 0; /* Name of super-journal file if any */ - int needPagerReset; /* True to reset page prior to first page rollback */ - int nPlayback = 0; /* Total number of pages restored from journal */ - u32 savedPageSize = pPager->pageSize; - - /* Figure out how many records are in the journal. Abort early if - ** the journal is empty. - */ - assert( isOpen(pPager->jfd) ); - rc = sqlite3OsFileSize(pPager->jfd, &szJ); - if( rc!=SQLITE_OK ){ - goto end_playback; - } - - /* Read the super-journal name from the journal, if it is present. - ** If a super-journal file name is specified, but the file is not - ** present on disk, then the journal is not hot and does not need to be - ** played back. - ** - ** TODO: Technically the following is an error because it assumes that - ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that - ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, - ** mxPathname is 512, which is the same as the minimum allowable value - ** for pageSize. - */ - zSuper = pPager->pTmpSpace; - rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1); - if( rc==SQLITE_OK && zSuper[0] ){ - rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res); - } - zSuper = 0; - if( rc!=SQLITE_OK || !res ){ - goto end_playback; - } - pPager->journalOff = 0; - needPagerReset = isHot; - - /* This loop terminates either when a readJournalHdr() or - ** pager_playback_one_page() call returns SQLITE_DONE or an IO error - ** occurs. - */ - while( 1 ){ - /* Read the next journal header from the journal file. If there are - ** not enough bytes left in the journal file for a complete header, or - ** it is corrupted, then a process must have failed while writing it. - ** This indicates nothing more needs to be rolled back. - */ - rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_DONE ){ - rc = SQLITE_OK; - } - goto end_playback; - } - - /* If nRec is 0xffffffff, then this journal was created by a process - ** working in no-sync mode. This means that the rest of the journal - ** file consists of pages, there are no more journal headers. Compute - ** the value of nRec based on this assumption. - */ - if( nRec==0xffffffff ){ - assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ); - nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager)); - } - - /* If nRec is 0 and this rollback is of a transaction created by this - ** process and if this is the final header in the journal, then it means - ** that this part of the journal was being filled but has not yet been - ** synced to disk. Compute the number of pages based on the remaining - ** size of the file. - ** - ** The third term of the test was added to fix ticket #2565. - ** When rolling back a hot journal, nRec==0 always means that the next - ** chunk of the journal contains zero pages to be rolled back. But - ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in - ** the journal, it means that the journal might contain additional - ** pages that need to be rolled back and that the number of pages - ** should be computed based on the journal file size. - */ - if( nRec==0 && !isHot && - pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ - nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager)); - } - - /* If this is the first header read from the journal, truncate the - ** database file back to its original size. - */ - if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){ - rc = pager_truncate(pPager, mxPg); - if( rc!=SQLITE_OK ){ - goto end_playback; - } - pPager->dbSize = mxPg; - } - - /* Copy original pages out of the journal and back into the - ** database file and/or page cache. - */ - for(u=0; ujournalOff,0,1,0); - if( rc==SQLITE_OK ){ - nPlayback++; - }else{ - if( rc==SQLITE_DONE ){ - pPager->journalOff = szJ; - break; - }else if( rc==SQLITE_IOERR_SHORT_READ ){ - /* If the journal has been truncated, simply stop reading and - ** processing the journal. This might happen if the journal was - ** not completely written and synced prior to a crash. In that - ** case, the database should have never been written in the - ** first place so it is OK to simply abandon the rollback. */ - rc = SQLITE_OK; - goto end_playback; - }else{ - /* If we are unable to rollback, quit and return the error - ** code. This will cause the pager to enter the error state - ** so that no further harm will be done. Perhaps the next - ** process to come along will be able to rollback the database. - */ - goto end_playback; - } - } - } - } - /*NOTREACHED*/ - assert( 0 ); - -end_playback: - if( rc==SQLITE_OK ){ - rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1); - } - /* Following a rollback, the database file should be back in its original - ** state prior to the start of the transaction, so invoke the - ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the - ** assertion that the transaction counter was modified. - */ -#ifdef SQLITE_DEBUG - sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0); -#endif - - /* If this playback is happening automatically as a result of an IO or - ** malloc error that occurred after the change-counter was updated but - ** before the transaction was committed, then the change-counter - ** modification may just have been reverted. If this happens in exclusive - ** mode, then subsequent transactions performed by the connection will not - ** update the change-counter at all. This may lead to cache inconsistency - ** problems for other processes at some point in the future. So, just - ** in case this has happened, clear the changeCountDone flag now. - */ - pPager->changeCountDone = pPager->tempFile; - - if( rc==SQLITE_OK ){ - zSuper = pPager->pTmpSpace; - rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1); - testcase( rc!=SQLITE_OK ); - } - if( rc==SQLITE_OK - && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) - ){ - rc = sqlite3PagerSync(pPager, 0); - } - if( rc==SQLITE_OK ){ - rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0); - testcase( rc!=SQLITE_OK ); - } - if( rc==SQLITE_OK && zSuper[0] && res ){ - /* If there was a super-journal and this routine will return success, - ** see if it is possible to delete the super-journal. - */ - rc = pager_delsuper(pPager, zSuper); - testcase( rc!=SQLITE_OK ); - } - if( isHot && nPlayback ){ - sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s", - nPlayback, pPager->zJournal); - } - - /* The Pager.sectorSize variable may have been updated while rolling - ** back a journal created by a process with a different sector size - ** value. Reset it to the correct value for this process. - */ - setSectorSize(pPager); - return rc; -} - - -/* -** Read the content for page pPg out of the database file (or out of -** the WAL if that is where the most recent copy if found) into -** pPg->pData. A shared lock or greater must be held on the database -** file before this function is called. -** -** If page 1 is read, then the value of Pager.dbFileVers[] is set to -** the value read from the database file. -** -** If an IO error occurs, then the IO error is returned to the caller. -** Otherwise, SQLITE_OK is returned. -*/ -static int readDbPage(PgHdr *pPg){ - Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */ - int rc = SQLITE_OK; /* Return code */ - -#ifndef SQLITE_OMIT_WAL - u32 iFrame = 0; /* Frame of WAL containing pgno */ - - assert( pPager->eState>=PAGER_READER && !MEMDB ); - assert( isOpen(pPager->fd) ); - - if( pagerUseWal(pPager) ){ - rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame); - if( rc ) return rc; - } - if( iFrame ){ - rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData); - }else -#endif - { - i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize; - rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset); - if( rc==SQLITE_IOERR_SHORT_READ ){ - rc = SQLITE_OK; - } - } - - if( pPg->pgno==1 ){ - if( rc ){ - /* If the read is unsuccessful, set the dbFileVers[] to something - ** that will never be a valid file version. dbFileVers[] is a copy - ** of bytes 24..39 of the database. Bytes 28..31 should always be - ** zero or the size of the database in page. Bytes 32..35 and 35..39 - ** should be page numbers which are never 0xffffffff. So filling - ** pPager->dbFileVers[] with all 0xff bytes should suffice. - ** - ** For an encrypted database, the situation is more complex: bytes - ** 24..39 of the database are white noise. But the probability of - ** white noise equaling 16 bytes of 0xff is vanishingly small so - ** we should still be ok. - */ - memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); - }else{ - u8 *dbFileVers = &((u8*)pPg->pData)[24]; - memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); - } - } - PAGER_INCR(sqlite3_pager_readdb_count); - PAGER_INCR(pPager->nRead); - IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno)); - PAGERTRACE(("FETCH %d page %d hash(%08x)\n", - PAGERID(pPager), pPg->pgno, pager_pagehash(pPg))); - - return rc; -} - -/* -** Update the value of the change-counter at offsets 24 and 92 in -** the header and the sqlite version number at offset 96. -** -** This is an unconditional update. See also the pager_incr_changecounter() -** routine which only updates the change-counter if the update is actually -** needed, as determined by the pPager->changeCountDone state variable. -*/ -static void pager_write_changecounter(PgHdr *pPg){ - u32 change_counter; - - /* Increment the value just read and write it back to byte 24. */ - change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1; - put32bits(((char*)pPg->pData)+24, change_counter); - - /* Also store the SQLite version number in bytes 96..99 and in - ** bytes 92..95 store the change counter for which the version number - ** is valid. */ - put32bits(((char*)pPg->pData)+92, change_counter); - put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER); -} - -#ifndef SQLITE_OMIT_WAL -/* -** This function is invoked once for each page that has already been -** written into the log file when a WAL transaction is rolled back. -** Parameter iPg is the page number of said page. The pCtx argument -** is actually a pointer to the Pager structure. -** -** If page iPg is present in the cache, and has no outstanding references, -** it is discarded. Otherwise, if there are one or more outstanding -** references, the page content is reloaded from the database. If the -** attempt to reload content from the database is required and fails, -** return an SQLite error code. Otherwise, SQLITE_OK. -*/ -static int pagerUndoCallback(void *pCtx, Pgno iPg){ - int rc = SQLITE_OK; - Pager *pPager = (Pager *)pCtx; - PgHdr *pPg; - - assert( pagerUseWal(pPager) ); - pPg = sqlite3PagerLookup(pPager, iPg); - if( pPg ){ - if( sqlite3PcachePageRefcount(pPg)==1 ){ - sqlite3PcacheDrop(pPg); - }else{ - rc = readDbPage(pPg); - if( rc==SQLITE_OK ){ - pPager->xReiniter(pPg); - } - sqlite3PagerUnrefNotNull(pPg); - } - } - - /* Normally, if a transaction is rolled back, any backup processes are - ** updated as data is copied out of the rollback journal and into the - ** database. This is not generally possible with a WAL database, as - ** rollback involves simply truncating the log file. Therefore, if one - ** or more frames have already been written to the log (and therefore - ** also copied into the backup databases) as part of this transaction, - ** the backups must be restarted. - */ - sqlite3BackupRestart(pPager->pBackup); - - return rc; -} - -/* -** This function is called to rollback a transaction on a WAL database. -*/ -static int pagerRollbackWal(Pager *pPager){ - int rc; /* Return Code */ - PgHdr *pList; /* List of dirty pages to revert */ - - /* For all pages in the cache that are currently dirty or have already - ** been written (but not committed) to the log file, do one of the - ** following: - ** - ** + Discard the cached page (if refcount==0), or - ** + Reload page content from the database (if refcount>0). - */ - pPager->dbSize = pPager->dbOrigSize; - rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager); - pList = sqlite3PcacheDirtyList(pPager->pPCache); - while( pList && rc==SQLITE_OK ){ - PgHdr *pNext = pList->pDirty; - rc = pagerUndoCallback((void *)pPager, pList->pgno); - pList = pNext; - } - - return rc; -} - -/* -** This function is a wrapper around sqlite3WalFrames(). As well as logging -** the contents of the list of pages headed by pList (connected by pDirty), -** this function notifies any active backup processes that the pages have -** changed. -** -** The list of pages passed into this routine is always sorted by page number. -** Hence, if page 1 appears anywhere on the list, it will be the first page. -*/ -static int pagerWalFrames( - Pager *pPager, /* Pager object */ - PgHdr *pList, /* List of frames to log */ - Pgno nTruncate, /* Database size after this commit */ - int isCommit /* True if this is a commit */ -){ - int rc; /* Return code */ - int nList; /* Number of pages in pList */ - PgHdr *p; /* For looping over pages */ - - assert( pPager->pWal ); - assert( pList ); -#ifdef SQLITE_DEBUG - /* Verify that the page list is in accending order */ - for(p=pList; p && p->pDirty; p=p->pDirty){ - assert( p->pgno < p->pDirty->pgno ); - } -#endif - - assert( pList->pDirty==0 || isCommit ); - if( isCommit ){ - /* If a WAL transaction is being committed, there is no point in writing - ** any pages with page numbers greater than nTruncate into the WAL file. - ** They will never be read by any client. So remove them from the pDirty - ** list here. */ - PgHdr **ppNext = &pList; - nList = 0; - for(p=pList; (*ppNext = p)!=0; p=p->pDirty){ - if( p->pgno<=nTruncate ){ - ppNext = &p->pDirty; - nList++; - } - } - assert( pList ); - }else{ - nList = 1; - } - pPager->aStat[PAGER_STAT_WRITE] += nList; - - if( pList->pgno==1 ) pager_write_changecounter(pList); - rc = sqlite3WalFrames(pPager->pWal, - pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags - ); - if( rc==SQLITE_OK && pPager->pBackup ){ - for(p=pList; p; p=p->pDirty){ - sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData); - } - } - -#ifdef SQLITE_CHECK_PAGES - pList = sqlite3PcacheDirtyList(pPager->pPCache); - for(p=pList; p; p=p->pDirty){ - pager_set_pagehash(p); - } -#endif - - return rc; -} - -/* -** Begin a read transaction on the WAL. -** -** This routine used to be called "pagerOpenSnapshot()" because it essentially -** makes a snapshot of the database at the current point in time and preserves -** that snapshot for use by the reader in spite of concurrently changes by -** other writers or checkpointers. -*/ -static int pagerBeginReadTransaction(Pager *pPager){ - int rc; /* Return code */ - int changed = 0; /* True if cache must be reset */ - - assert( pagerUseWal(pPager) ); - assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); - - /* sqlite3WalEndReadTransaction() was not called for the previous - ** transaction in locking_mode=EXCLUSIVE. So call it now. If we - ** are in locking_mode=NORMAL and EndRead() was previously called, - ** the duplicate call is harmless. - */ - sqlite3WalEndReadTransaction(pPager->pWal); - - rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed); - if( rc!=SQLITE_OK || changed ){ - pager_reset(pPager); - if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0); - } - - return rc; -} -#endif - -/* -** This function is called as part of the transition from PAGER_OPEN -** to PAGER_READER state to determine the size of the database file -** in pages (assuming the page size currently stored in Pager.pageSize). -** -** If no error occurs, SQLITE_OK is returned and the size of the database -** in pages is stored in *pnPage. Otherwise, an error code (perhaps -** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified. -*/ -static int pagerPagecount(Pager *pPager, Pgno *pnPage){ - Pgno nPage; /* Value to return via *pnPage */ - - /* Query the WAL sub-system for the database size. The WalDbsize() - ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or - ** if the database size is not available. The database size is not - ** available from the WAL sub-system if the log file is empty or - ** contains no valid committed transactions. - */ - assert( pPager->eState==PAGER_OPEN ); - assert( pPager->eLock>=SHARED_LOCK ); - assert( isOpen(pPager->fd) ); - assert( pPager->tempFile==0 ); - nPage = sqlite3WalDbsize(pPager->pWal); - - /* If the number of pages in the database is not available from the - ** WAL sub-system, determine the page count based on the size of - ** the database file. If the size of the database file is not an - ** integer multiple of the page-size, round up the result. - */ - if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){ - i64 n = 0; /* Size of db file in bytes */ - int rc = sqlite3OsFileSize(pPager->fd, &n); - if( rc!=SQLITE_OK ){ - return rc; - } - nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize); - } - - /* If the current number of pages in the file is greater than the - ** configured maximum pager number, increase the allowed limit so - ** that the file can be read. - */ - if( nPage>pPager->mxPgno ){ - pPager->mxPgno = (Pgno)nPage; - } - - *pnPage = nPage; - return SQLITE_OK; -} - -#ifndef SQLITE_OMIT_WAL -/* -** Check if the *-wal file that corresponds to the database opened by pPager -** exists if the database is not empy, or verify that the *-wal file does -** not exist (by deleting it) if the database file is empty. -** -** If the database is not empty and the *-wal file exists, open the pager -** in WAL mode. If the database is empty or if no *-wal file exists and -** if no error occurs, make sure Pager.journalMode is not set to -** PAGER_JOURNALMODE_WAL. -** -** Return SQLITE_OK or an error code. -** -** The caller must hold a SHARED lock on the database file to call this -** function. Because an EXCLUSIVE lock on the db file is required to delete -** a WAL on a none-empty database, this ensures there is no race condition -** between the xAccess() below and an xDelete() being executed by some -** other connection. -*/ -static int pagerOpenWalIfPresent(Pager *pPager){ - int rc = SQLITE_OK; - assert( pPager->eState==PAGER_OPEN ); - assert( pPager->eLock>=SHARED_LOCK ); - - if( !pPager->tempFile ){ - int isWal; /* True if WAL file exists */ - rc = sqlite3OsAccess( - pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal - ); - if( rc==SQLITE_OK ){ - if( isWal ){ - Pgno nPage; /* Size of the database file */ - - rc = pagerPagecount(pPager, &nPage); - if( rc ) return rc; - if( nPage==0 ){ - rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0); - }else{ - testcase( sqlite3PcachePagecount(pPager->pPCache)==0 ); - rc = sqlite3PagerOpenWal(pPager, 0); - } - }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){ - pPager->journalMode = PAGER_JOURNALMODE_DELETE; - } - } - } - return rc; -} -#endif - -/* -** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback -** the entire super-journal file. The case pSavepoint==NULL occurs when -** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction -** savepoint. -** -** When pSavepoint is not NULL (meaning a non-transaction savepoint is -** being rolled back), then the rollback consists of up to three stages, -** performed in the order specified: -** -** * Pages are played back from the main journal starting at byte -** offset PagerSavepoint.iOffset and continuing to -** PagerSavepoint.iHdrOffset, or to the end of the main journal -** file if PagerSavepoint.iHdrOffset is zero. -** -** * If PagerSavepoint.iHdrOffset is not zero, then pages are played -** back starting from the journal header immediately following -** PagerSavepoint.iHdrOffset to the end of the main journal file. -** -** * Pages are then played back from the sub-journal file, starting -** with the PagerSavepoint.iSubRec and continuing to the end of -** the journal file. -** -** Throughout the rollback process, each time a page is rolled back, the -** corresponding bit is set in a bitvec structure (variable pDone in the -** implementation below). This is used to ensure that a page is only -** rolled back the first time it is encountered in either journal. -** -** If pSavepoint is NULL, then pages are only played back from the main -** journal file. There is no need for a bitvec in this case. -** -** In either case, before playback commences the Pager.dbSize variable -** is reset to the value that it held at the start of the savepoint -** (or transaction). No page with a page-number greater than this value -** is played back. If one is encountered it is simply skipped. -*/ -static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ - i64 szJ; /* Effective size of the main journal */ - i64 iHdrOff; /* End of first segment of main-journal records */ - int rc = SQLITE_OK; /* Return code */ - Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */ - - assert( pPager->eState!=PAGER_ERROR ); - assert( pPager->eState>=PAGER_WRITER_LOCKED ); - - /* Allocate a bitvec to use to store the set of pages rolled back */ - if( pSavepoint ){ - pDone = sqlite3BitvecCreate(pSavepoint->nOrig); - if( !pDone ){ - return SQLITE_NOMEM_BKPT; - } - } - - /* Set the database size back to the value it was before the savepoint - ** being reverted was opened. - */ - pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize; - pPager->changeCountDone = pPager->tempFile; - - if( !pSavepoint && pagerUseWal(pPager) ){ - return pagerRollbackWal(pPager); - } - - /* Use pPager->journalOff as the effective size of the main rollback - ** journal. The actual file might be larger than this in - ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything - ** past pPager->journalOff is off-limits to us. - */ - szJ = pPager->journalOff; - assert( pagerUseWal(pPager)==0 || szJ==0 ); - - /* Begin by rolling back records from the main journal starting at - ** PagerSavepoint.iOffset and continuing to the next journal header. - ** There might be records in the main journal that have a page number - ** greater than the current database size (pPager->dbSize) but those - ** will be skipped automatically. Pages are added to pDone as they - ** are played back. - */ - if( pSavepoint && !pagerUseWal(pPager) ){ - iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ; - pPager->journalOff = pSavepoint->iOffset; - while( rc==SQLITE_OK && pPager->journalOffjournalOff, pDone, 1, 1); - } - assert( rc!=SQLITE_DONE ); - }else{ - pPager->journalOff = 0; - } - - /* Continue rolling back records out of the main journal starting at - ** the first journal header seen and continuing until the effective end - ** of the main journal file. Continue to skip out-of-range pages and - ** continue adding pages rolled back to pDone. - */ - while( rc==SQLITE_OK && pPager->journalOffjournalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff" - ** test is related to ticket #2565. See the discussion in the - ** pager_playback() function for additional information. - */ - if( nJRec==0 - && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff - ){ - nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager)); - } - for(ii=0; rc==SQLITE_OK && iijournalOffjournalOff, pDone, 1, 1); - } - assert( rc!=SQLITE_DONE ); - } - assert( rc!=SQLITE_OK || pPager->journalOff>=szJ ); - - /* Finally, rollback pages from the sub-journal. Page that were - ** previously rolled back out of the main journal (and are hence in pDone) - ** will be skipped. Out-of-range pages are also skipped. - */ - if( pSavepoint ){ - u32 ii; /* Loop counter */ - i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize); - - if( pagerUseWal(pPager) ){ - rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData); - } - for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && iinSubRec; ii++){ - assert( offset==(i64)ii*(4+pPager->pageSize) ); - rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1); - } - assert( rc!=SQLITE_DONE ); - } - - sqlite3BitvecDestroy(pDone); - if( rc==SQLITE_OK ){ - pPager->journalOff = szJ; - } - - return rc; -} - -/* -** Change the maximum number of in-memory pages that are allowed -** before attempting to recycle clean and unused pages. -*/ -SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){ - sqlite3PcacheSetCachesize(pPager->pPCache, mxPage); -} - -/* -** Change the maximum number of in-memory pages that are allowed -** before attempting to spill pages to journal. -*/ -SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){ - return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage); -} - -/* -** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap. -*/ -static void pagerFixMaplimit(Pager *pPager){ -#if SQLITE_MAX_MMAP_SIZE>0 - sqlite3_file *fd = pPager->fd; - if( isOpen(fd) && fd->pMethods->iVersion>=3 ){ - sqlite3_int64 sz; - sz = pPager->szMmap; - pPager->bUseFetch = (sz>0); - setGetterMethod(pPager); - sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz); - } -#endif -} - -/* -** Change the maximum size of any memory mapping made of the database file. -*/ -SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){ - pPager->szMmap = szMmap; - pagerFixMaplimit(pPager); -} - -/* -** Free as much memory as possible from the pager. -*/ -SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){ - sqlite3PcacheShrink(pPager->pPCache); -} - -/* -** Adjust settings of the pager to those specified in the pgFlags parameter. -** -** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness -** of the database to damage due to OS crashes or power failures by -** changing the number of syncs()s when writing the journals. -** There are four levels: -** -** OFF sqlite3OsSync() is never called. This is the default -** for temporary and transient files. -** -** NORMAL The journal is synced once before writes begin on the -** database. This is normally adequate protection, but -** it is theoretically possible, though very unlikely, -** that an inopertune power failure could leave the journal -** in a state which would cause damage to the database -** when it is rolled back. -** -** FULL The journal is synced twice before writes begin on the -** database (with some additional information - the nRec field -** of the journal header - being written in between the two -** syncs). If we assume that writing a -** single disk sector is atomic, then this mode provides -** assurance that the journal will not be corrupted to the -** point of causing damage to the database during rollback. -** -** EXTRA This is like FULL except that is also syncs the directory -** that contains the rollback journal after the rollback -** journal is unlinked. -** -** The above is for a rollback-journal mode. For WAL mode, OFF continues -** to mean that no syncs ever occur. NORMAL means that the WAL is synced -** prior to the start of checkpoint and that the database file is synced -** at the conclusion of the checkpoint if the entire content of the WAL -** was written back into the database. But no sync operations occur for -** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL -** file is synced following each commit operation, in addition to the -** syncs associated with NORMAL. There is no difference between FULL -** and EXTRA for WAL mode. -** -** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The -** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync -** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an -** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL -** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the -** synchronous=FULL versus synchronous=NORMAL setting determines when -** the xSync primitive is called and is relevant to all platforms. -** -** Numeric values associated with these states are OFF==1, NORMAL=2, -** and FULL=3. -*/ -#ifndef SQLITE_OMIT_PAGER_PRAGMAS -SQLITE_PRIVATE void sqlite3PagerSetFlags( - Pager *pPager, /* The pager to set safety level for */ - unsigned pgFlags /* Various flags */ -){ - unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK; - if( pPager->tempFile ){ - pPager->noSync = 1; - pPager->fullSync = 0; - pPager->extraSync = 0; - }else{ - pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0; - pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0; - pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0; - } - if( pPager->noSync ){ - pPager->syncFlags = 0; - }else if( pgFlags & PAGER_FULLFSYNC ){ - pPager->syncFlags = SQLITE_SYNC_FULL; - }else{ - pPager->syncFlags = SQLITE_SYNC_NORMAL; - } - pPager->walSyncFlags = (pPager->syncFlags<<2); - if( pPager->fullSync ){ - pPager->walSyncFlags |= pPager->syncFlags; - } - if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){ - pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2); - } - if( pgFlags & PAGER_CACHESPILL ){ - pPager->doNotSpill &= ~SPILLFLAG_OFF; - }else{ - pPager->doNotSpill |= SPILLFLAG_OFF; - } -} -#endif - -/* -** The following global variable is incremented whenever the library -** attempts to open a temporary file. This information is used for -** testing and analysis only. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_opentemp_count = 0; -#endif - -/* -** Open a temporary file. -** -** Write the file descriptor into *pFile. Return SQLITE_OK on success -** or some other error code if we fail. The OS will automatically -** delete the temporary file when it is closed. -** -** The flags passed to the VFS layer xOpen() call are those specified -** by parameter vfsFlags ORed with the following: -** -** SQLITE_OPEN_READWRITE -** SQLITE_OPEN_CREATE -** SQLITE_OPEN_EXCLUSIVE -** SQLITE_OPEN_DELETEONCLOSE -*/ -static int pagerOpentemp( - Pager *pPager, /* The pager object */ - sqlite3_file *pFile, /* Write the file descriptor here */ - int vfsFlags /* Flags passed through to the VFS */ -){ - int rc; /* Return code */ - -#ifdef SQLITE_TEST - sqlite3_opentemp_count++; /* Used for testing and analysis only */ -#endif - - vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | - SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE; - rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0); - assert( rc!=SQLITE_OK || isOpen(pFile) ); - return rc; -} - -/* -** Set the busy handler function. -** -** The pager invokes the busy-handler if sqlite3OsLock() returns -** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock, -** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE -** lock. It does *not* invoke the busy handler when upgrading from -** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE -** (which occurs during hot-journal rollback). Summary: -** -** Transition | Invokes xBusyHandler -** -------------------------------------------------------- -** NO_LOCK -> SHARED_LOCK | Yes -** SHARED_LOCK -> RESERVED_LOCK | No -** SHARED_LOCK -> EXCLUSIVE_LOCK | No -** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes -** -** If the busy-handler callback returns non-zero, the lock is -** retried. If it returns zero, then the SQLITE_BUSY error is -** returned to the caller of the pager API function. -*/ -SQLITE_PRIVATE void sqlite3PagerSetBusyHandler( - Pager *pPager, /* Pager object */ - int (*xBusyHandler)(void *), /* Pointer to busy-handler function */ - void *pBusyHandlerArg /* Argument to pass to xBusyHandler */ -){ - void **ap; - pPager->xBusyHandler = xBusyHandler; - pPager->pBusyHandlerArg = pBusyHandlerArg; - ap = (void **)&pPager->xBusyHandler; - assert( ((int(*)(void *))(ap[0]))==xBusyHandler ); - assert( ap[1]==pBusyHandlerArg ); - sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap); -} - -/* -** Change the page size used by the Pager object. The new page size -** is passed in *pPageSize. -** -** If the pager is in the error state when this function is called, it -** is a no-op. The value returned is the error state error code (i.e. -** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL). -** -** Otherwise, if all of the following are true: -** -** * the new page size (value of *pPageSize) is valid (a power -** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and -** -** * there are no outstanding page references, and -** -** * the database is either not an in-memory database or it is -** an in-memory database that currently consists of zero pages. -** -** then the pager object page size is set to *pPageSize. -** -** If the page size is changed, then this function uses sqlite3PagerMalloc() -** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt -** fails, SQLITE_NOMEM is returned and the page size remains unchanged. -** In all other cases, SQLITE_OK is returned. -** -** If the page size is not changed, either because one of the enumerated -** conditions above is not true, the pager was in error state when this -** function was called, or because the memory allocation attempt failed, -** then *pPageSize is set to the old, retained page size before returning. -*/ -SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){ - int rc = SQLITE_OK; - - /* It is not possible to do a full assert_pager_state() here, as this - ** function may be called from within PagerOpen(), before the state - ** of the Pager object is internally consistent. - ** - ** At one point this function returned an error if the pager was in - ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that - ** there is at least one outstanding page reference, this function - ** is a no-op for that case anyhow. - */ - - u32 pageSize = *pPageSize; - assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) ); - if( (pPager->memDb==0 || pPager->dbSize==0) - && sqlite3PcacheRefCount(pPager->pPCache)==0 - && pageSize && pageSize!=(u32)pPager->pageSize - ){ - char *pNew = NULL; /* New temp space */ - i64 nByte = 0; - - if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){ - rc = sqlite3OsFileSize(pPager->fd, &nByte); - } - if( rc==SQLITE_OK ){ - /* 8 bytes of zeroed overrun space is sufficient so that the b-tree - * cell header parser will never run off the end of the allocation */ - pNew = (char *)sqlite3PageMalloc(pageSize+8); - if( !pNew ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - memset(pNew+pageSize, 0, 8); - } - } - - if( rc==SQLITE_OK ){ - pager_reset(pPager); - rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize); - } - if( rc==SQLITE_OK ){ - sqlite3PageFree(pPager->pTmpSpace); - pPager->pTmpSpace = pNew; - pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize); - pPager->pageSize = pageSize; - }else{ - sqlite3PageFree(pNew); - } - } - - *pPageSize = pPager->pageSize; - if( rc==SQLITE_OK ){ - if( nReserve<0 ) nReserve = pPager->nReserve; - assert( nReserve>=0 && nReserve<1000 ); - pPager->nReserve = (i16)nReserve; - pagerFixMaplimit(pPager); - } - return rc; -} - -/* -** Return a pointer to the "temporary page" buffer held internally -** by the pager. This is a buffer that is big enough to hold the -** entire content of a database page. This buffer is used internally -** during rollback and will be overwritten whenever a rollback -** occurs. But other modules are free to use it too, as long as -** no rollbacks are happening. -*/ -SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){ - return pPager->pTmpSpace; -} - -/* -** Attempt to set the maximum database page count if mxPage is positive. -** Make no changes if mxPage is zero or negative. And never reduce the -** maximum page count below the current size of the database. -** -** Regardless of mxPage, return the current maximum page count. -*/ -SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager *pPager, Pgno mxPage){ - if( mxPage>0 ){ - pPager->mxPgno = mxPage; - } - assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ - /* assert( pPager->mxPgno>=pPager->dbSize ); */ - /* OP_MaxPgcnt ensures that the parameter passed to this function is not - ** less than the total number of valid pages in the database. But this - ** may be less than Pager.dbSize, and so the assert() above is not valid */ - return pPager->mxPgno; -} - -/* -** The following set of routines are used to disable the simulated -** I/O error mechanism. These routines are used to avoid simulated -** errors in places where we do not care about errors. -** -** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops -** and generate no code. -*/ -#ifdef SQLITE_TEST -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_hit; -static int saved_cnt; -void disable_simulated_io_errors(void){ - saved_cnt = sqlite3_io_error_pending; - sqlite3_io_error_pending = -1; -} -void enable_simulated_io_errors(void){ - sqlite3_io_error_pending = saved_cnt; -} -#else -# define disable_simulated_io_errors() -# define enable_simulated_io_errors() -#endif - -/* -** Read the first N bytes from the beginning of the file into memory -** that pDest points to. -** -** If the pager was opened on a transient file (zFilename==""), or -** opened on a file less than N bytes in size, the output buffer is -** zeroed and SQLITE_OK returned. The rationale for this is that this -** function is used to read database headers, and a new transient or -** zero sized database has a header than consists entirely of zeroes. -** -** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered, -** the error code is returned to the caller and the contents of the -** output buffer undefined. -*/ -SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){ - int rc = SQLITE_OK; - memset(pDest, 0, N); - assert( isOpen(pPager->fd) || pPager->tempFile ); - - /* This routine is only called by btree immediately after creating - ** the Pager object. There has not been an opportunity to transition - ** to WAL mode yet. - */ - assert( !pagerUseWal(pPager) ); - - if( isOpen(pPager->fd) ){ - IOTRACE(("DBHDR %p 0 %d\n", pPager, N)) - rc = sqlite3OsRead(pPager->fd, pDest, N, 0); - if( rc==SQLITE_IOERR_SHORT_READ ){ - rc = SQLITE_OK; - } - } - return rc; -} - -/* -** This function may only be called when a read-transaction is open on -** the pager. It returns the total number of pages in the database. -** -** However, if the file is between 1 and bytes in size, then -** this is considered a 1 page file. -*/ -SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){ - assert( pPager->eState>=PAGER_READER ); - assert( pPager->eState!=PAGER_WRITER_FINISHED ); - *pnPage = (int)pPager->dbSize; -} - - -/* -** Try to obtain a lock of type locktype on the database file. If -** a similar or greater lock is already held, this function is a no-op -** (returning SQLITE_OK immediately). -** -** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke -** the busy callback if the lock is currently not available. Repeat -** until the busy callback returns false or until the attempt to -** obtain the lock succeeds. -** -** Return SQLITE_OK on success and an error code if we cannot obtain -** the lock. If the lock is obtained successfully, set the Pager.state -** variable to locktype before returning. -*/ -static int pager_wait_on_lock(Pager *pPager, int locktype){ - int rc; /* Return code */ - - /* Check that this is either a no-op (because the requested lock is - ** already held), or one of the transitions that the busy-handler - ** may be invoked during, according to the comment above - ** sqlite3PagerSetBusyhandler(). - */ - assert( (pPager->eLock>=locktype) - || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK) - || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK) - ); - - do { - rc = pagerLockDb(pPager, locktype); - }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) ); - return rc; -} - -/* -** Function assertTruncateConstraint(pPager) checks that one of the -** following is true for all dirty pages currently in the page-cache: -** -** a) The page number is less than or equal to the size of the -** current database image, in pages, OR -** -** b) if the page content were written at this time, it would not -** be necessary to write the current content out to the sub-journal -** (as determined by function subjRequiresPage()). -** -** If the condition asserted by this function were not true, and the -** dirty page were to be discarded from the cache via the pagerStress() -** routine, pagerStress() would not write the current page content to -** the database file. If a savepoint transaction were rolled back after -** this happened, the correct behavior would be to restore the current -** content of the page. However, since this content is not present in either -** the database file or the portion of the rollback journal and -** sub-journal rolled back the content could not be restored and the -** database image would become corrupt. It is therefore fortunate that -** this circumstance cannot arise. -*/ -#if defined(SQLITE_DEBUG) -static void assertTruncateConstraintCb(PgHdr *pPg){ - assert( pPg->flags&PGHDR_DIRTY ); - assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize ); -} -static void assertTruncateConstraint(Pager *pPager){ - sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb); -} -#else -# define assertTruncateConstraint(pPager) -#endif - -/* -** Truncate the in-memory database file image to nPage pages. This -** function does not actually modify the database file on disk. It -** just sets the internal state of the pager object so that the -** truncation will be done when the current transaction is committed. -** -** This function is only called right before committing a transaction. -** Once this function has been called, the transaction must either be -** rolled back or committed. It is not safe to call this function and -** then continue writing to the database. -*/ -SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){ - assert( pPager->dbSize>=nPage ); - assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); - pPager->dbSize = nPage; - - /* At one point the code here called assertTruncateConstraint() to - ** ensure that all pages being truncated away by this operation are, - ** if one or more savepoints are open, present in the savepoint - ** journal so that they can be restored if the savepoint is rolled - ** back. This is no longer necessary as this function is now only - ** called right before committing a transaction. So although the - ** Pager object may still have open savepoints (Pager.nSavepoint!=0), - ** they cannot be rolled back. So the assertTruncateConstraint() call - ** is no longer correct. */ -} - - -/* -** This function is called before attempting a hot-journal rollback. It -** syncs the journal file to disk, then sets pPager->journalHdr to the -** size of the journal file so that the pager_playback() routine knows -** that the entire journal file has been synced. -** -** Syncing a hot-journal to disk before attempting to roll it back ensures -** that if a power-failure occurs during the rollback, the process that -** attempts rollback following system recovery sees the same journal -** content as this process. -** -** If everything goes as planned, SQLITE_OK is returned. Otherwise, -** an SQLite error code. -*/ -static int pagerSyncHotJournal(Pager *pPager){ - int rc = SQLITE_OK; - if( !pPager->noSync ){ - rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL); - } - if( rc==SQLITE_OK ){ - rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr); - } - return rc; -} - -#if SQLITE_MAX_MMAP_SIZE>0 -/* -** Obtain a reference to a memory mapped page object for page number pgno. -** The new object will use the pointer pData, obtained from xFetch(). -** If successful, set *ppPage to point to the new page reference -** and return SQLITE_OK. Otherwise, return an SQLite error code and set -** *ppPage to zero. -** -** Page references obtained by calling this function should be released -** by calling pagerReleaseMapPage(). -*/ -static int pagerAcquireMapPage( - Pager *pPager, /* Pager object */ - Pgno pgno, /* Page number */ - void *pData, /* xFetch()'d data for this page */ - PgHdr **ppPage /* OUT: Acquired page object */ -){ - PgHdr *p; /* Memory mapped page to return */ - - if( pPager->pMmapFreelist ){ - *ppPage = p = pPager->pMmapFreelist; - pPager->pMmapFreelist = p->pDirty; - p->pDirty = 0; - assert( pPager->nExtra>=8 ); - memset(p->pExtra, 0, 8); - }else{ - *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra); - if( p==0 ){ - sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData); - return SQLITE_NOMEM_BKPT; - } - p->pExtra = (void *)&p[1]; - p->flags = PGHDR_MMAP; - p->nRef = 1; - p->pPager = pPager; - } - - assert( p->pExtra==(void *)&p[1] ); - assert( p->pPage==0 ); - assert( p->flags==PGHDR_MMAP ); - assert( p->pPager==pPager ); - assert( p->nRef==1 ); - - p->pgno = pgno; - p->pData = pData; - pPager->nMmapOut++; - - return SQLITE_OK; -} -#endif - -/* -** Release a reference to page pPg. pPg must have been returned by an -** earlier call to pagerAcquireMapPage(). -*/ -static void pagerReleaseMapPage(PgHdr *pPg){ - Pager *pPager = pPg->pPager; - pPager->nMmapOut--; - pPg->pDirty = pPager->pMmapFreelist; - pPager->pMmapFreelist = pPg; - - assert( pPager->fd->pMethods->iVersion>=3 ); - sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData); -} - -/* -** Free all PgHdr objects stored in the Pager.pMmapFreelist list. -*/ -static void pagerFreeMapHdrs(Pager *pPager){ - PgHdr *p; - PgHdr *pNext; - for(p=pPager->pMmapFreelist; p; p=pNext){ - pNext = p->pDirty; - sqlite3_free(p); - } -} - -/* Verify that the database file has not be deleted or renamed out from -** under the pager. Return SQLITE_OK if the database is still where it ought -** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error -** code from sqlite3OsAccess()) if the database has gone missing. -*/ -static int databaseIsUnmoved(Pager *pPager){ - int bHasMoved = 0; - int rc; - - if( pPager->tempFile ) return SQLITE_OK; - if( pPager->dbSize==0 ) return SQLITE_OK; - assert( pPager->zFilename && pPager->zFilename[0] ); - rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved); - if( rc==SQLITE_NOTFOUND ){ - /* If the HAS_MOVED file-control is unimplemented, assume that the file - ** has not been moved. That is the historical behavior of SQLite: prior to - ** version 3.8.3, it never checked */ - rc = SQLITE_OK; - }else if( rc==SQLITE_OK && bHasMoved ){ - rc = SQLITE_READONLY_DBMOVED; - } - return rc; -} - - -/* -** Shutdown the page cache. Free all memory and close all files. -** -** If a transaction was in progress when this routine is called, that -** transaction is rolled back. All outstanding pages are invalidated -** and their memory is freed. Any attempt to use a page associated -** with this page cache after this function returns will likely -** result in a coredump. -** -** This function always succeeds. If a transaction is active an attempt -** is made to roll it back. If an error occurs during the rollback -** a hot journal may be left in the filesystem but no error is returned -** to the caller. -*/ -SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){ - u8 *pTmp = (u8*)pPager->pTmpSpace; - assert( db || pagerUseWal(pPager)==0 ); - assert( assert_pager_state(pPager) ); - disable_simulated_io_errors(); - sqlite3BeginBenignMalloc(); - pagerFreeMapHdrs(pPager); - /* pPager->errCode = 0; */ - pPager->exclusiveMode = 0; -#ifndef SQLITE_OMIT_WAL - { - u8 *a = 0; - assert( db || pPager->pWal==0 ); - if( db && 0==(db->flags & SQLITE_NoCkptOnClose) - && SQLITE_OK==databaseIsUnmoved(pPager) - ){ - a = pTmp; - } - sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a); - pPager->pWal = 0; - } -#endif - pager_reset(pPager); - if( MEMDB ){ - pager_unlock(pPager); - }else{ - /* If it is open, sync the journal file before calling UnlockAndRollback. - ** If this is not done, then an unsynced portion of the open journal - ** file may be played back into the database. If a power failure occurs - ** while this is happening, the database could become corrupt. - ** - ** If an error occurs while trying to sync the journal, shift the pager - ** into the ERROR state. This causes UnlockAndRollback to unlock the - ** database and close the journal file without attempting to roll it - ** back or finalize it. The next database user will have to do hot-journal - ** rollback before accessing the database file. - */ - if( isOpen(pPager->jfd) ){ - pager_error(pPager, pagerSyncHotJournal(pPager)); - } - pagerUnlockAndRollback(pPager); - } - sqlite3EndBenignMalloc(); - enable_simulated_io_errors(); - PAGERTRACE(("CLOSE %d\n", PAGERID(pPager))); - IOTRACE(("CLOSE %p\n", pPager)) - sqlite3OsClose(pPager->jfd); - sqlite3OsClose(pPager->fd); - sqlite3PageFree(pTmp); - sqlite3PcacheClose(pPager->pPCache); - assert( !pPager->aSavepoint && !pPager->pInJournal ); - assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ); - - sqlite3_free(pPager); - return SQLITE_OK; -} - -#if !defined(NDEBUG) || defined(SQLITE_TEST) -/* -** Return the page number for page pPg. -*/ -SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){ - return pPg->pgno; -} -#endif - -/* -** Increment the reference count for page pPg. -*/ -SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){ - sqlite3PcacheRef(pPg); -} - -/* -** Sync the journal. In other words, make sure all the pages that have -** been written to the journal have actually reached the surface of the -** disk and can be restored in the event of a hot-journal rollback. -** -** If the Pager.noSync flag is set, then this function is a no-op. -** Otherwise, the actions required depend on the journal-mode and the -** device characteristics of the file-system, as follows: -** -** * If the journal file is an in-memory journal file, no action need -** be taken. -** -** * Otherwise, if the device does not support the SAFE_APPEND property, -** then the nRec field of the most recently written journal header -** is updated to contain the number of journal records that have -** been written following it. If the pager is operating in full-sync -** mode, then the journal file is synced before this field is updated. -** -** * If the device does not support the SEQUENTIAL property, then -** journal file is synced. -** -** Or, in pseudo-code: -** -** if( NOT ){ -** if( NOT SAFE_APPEND ){ -** if( ) xSync(); -** -** } -** if( NOT SEQUENTIAL ) xSync(); -** } -** -** If successful, this routine clears the PGHDR_NEED_SYNC flag of every -** page currently held in memory before returning SQLITE_OK. If an IO -** error is encountered, then the IO error code is returned to the caller. -*/ -static int syncJournal(Pager *pPager, int newHdr){ - int rc; /* Return code */ - - assert( pPager->eState==PAGER_WRITER_CACHEMOD - || pPager->eState==PAGER_WRITER_DBMOD - ); - assert( assert_pager_state(pPager) ); - assert( !pagerUseWal(pPager) ); - - rc = sqlite3PagerExclusiveLock(pPager); - if( rc!=SQLITE_OK ) return rc; - - if( !pPager->noSync ){ - assert( !pPager->tempFile ); - if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){ - const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); - assert( isOpen(pPager->jfd) ); - - if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ - /* This block deals with an obscure problem. If the last connection - ** that wrote to this database was operating in persistent-journal - ** mode, then the journal file may at this point actually be larger - ** than Pager.journalOff bytes. If the next thing in the journal - ** file happens to be a journal-header (written as part of the - ** previous connection's transaction), and a crash or power-failure - ** occurs after nRec is updated but before this connection writes - ** anything else to the journal file (or commits/rolls back its - ** transaction), then SQLite may become confused when doing the - ** hot-journal rollback following recovery. It may roll back all - ** of this connections data, then proceed to rolling back the old, - ** out-of-date data that follows it. Database corruption. - ** - ** To work around this, if the journal file does appear to contain - ** a valid header following Pager.journalOff, then write a 0x00 - ** byte to the start of it to prevent it from being recognized. - ** - ** Variable iNextHdrOffset is set to the offset at which this - ** problematic header will occur, if it exists. aMagic is used - ** as a temporary buffer to inspect the first couple of bytes of - ** the potential journal header. - */ - i64 iNextHdrOffset; - u8 aMagic[8]; - u8 zHeader[sizeof(aJournalMagic)+4]; - - memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic)); - put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec); - - iNextHdrOffset = journalHdrOffset(pPager); - rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset); - if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){ - static const u8 zerobyte = 0; - rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset); - } - if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){ - return rc; - } - - /* Write the nRec value into the journal file header. If in - ** full-synchronous mode, sync the journal first. This ensures that - ** all data has really hit the disk before nRec is updated to mark - ** it as a candidate for rollback. - ** - ** This is not required if the persistent media supports the - ** SAFE_APPEND property. Because in this case it is not possible - ** for garbage data to be appended to the file, the nRec field - ** is populated with 0xFFFFFFFF when the journal header is written - ** and never needs to be updated. - */ - if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ - PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); - IOTRACE(("JSYNC %p\n", pPager)) - rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags); - if( rc!=SQLITE_OK ) return rc; - } - IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr)); - rc = sqlite3OsWrite( - pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr - ); - if( rc!=SQLITE_OK ) return rc; - } - if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){ - PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager))); - IOTRACE(("JSYNC %p\n", pPager)) - rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| - (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0) - ); - if( rc!=SQLITE_OK ) return rc; - } - - pPager->journalHdr = pPager->journalOff; - if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){ - pPager->nRec = 0; - rc = writeJournalHdr(pPager); - if( rc!=SQLITE_OK ) return rc; - } - }else{ - pPager->journalHdr = pPager->journalOff; - } - } - - /* Unless the pager is in noSync mode, the journal file was just - ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on - ** all pages. - */ - sqlite3PcacheClearSyncFlags(pPager->pPCache); - pPager->eState = PAGER_WRITER_DBMOD; - assert( assert_pager_state(pPager) ); - return SQLITE_OK; -} - -/* -** The argument is the first in a linked list of dirty pages connected -** by the PgHdr.pDirty pointer. This function writes each one of the -** in-memory pages in the list to the database file. The argument may -** be NULL, representing an empty list. In this case this function is -** a no-op. -** -** The pager must hold at least a RESERVED lock when this function -** is called. Before writing anything to the database file, this lock -** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained, -** SQLITE_BUSY is returned and no data is written to the database file. -** -** If the pager is a temp-file pager and the actual file-system file -** is not yet open, it is created and opened before any data is -** written out. -** -** Once the lock has been upgraded and, if necessary, the file opened, -** the pages are written out to the database file in list order. Writing -** a page is skipped if it meets either of the following criteria: -** -** * The page number is greater than Pager.dbSize, or -** * The PGHDR_DONT_WRITE flag is set on the page. -** -** If writing out a page causes the database file to grow, Pager.dbFileSize -** is updated accordingly. If page 1 is written out, then the value cached -** in Pager.dbFileVers[] is updated to match the new value stored in -** the database file. -** -** If everything is successful, SQLITE_OK is returned. If an IO error -** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot -** be obtained, SQLITE_BUSY is returned. -*/ -static int pager_write_pagelist(Pager *pPager, PgHdr *pList){ - int rc = SQLITE_OK; /* Return code */ - - /* This function is only called for rollback pagers in WRITER_DBMOD state. */ - assert( !pagerUseWal(pPager) ); - assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD ); - assert( pPager->eLock==EXCLUSIVE_LOCK ); - assert( isOpen(pPager->fd) || pList->pDirty==0 ); - - /* If the file is a temp-file has not yet been opened, open it now. It - ** is not possible for rc to be other than SQLITE_OK if this branch - ** is taken, as pager_wait_on_lock() is a no-op for temp-files. - */ - if( !isOpen(pPager->fd) ){ - assert( pPager->tempFile && rc==SQLITE_OK ); - rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags); - } - - /* Before the first write, give the VFS a hint of what the final - ** file size will be. - */ - assert( rc!=SQLITE_OK || isOpen(pPager->fd) ); - if( rc==SQLITE_OK - && pPager->dbHintSizedbSize - && (pList->pDirty || pList->pgno>pPager->dbHintSize) - ){ - sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize; - sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile); - pPager->dbHintSize = pPager->dbSize; - } - - while( rc==SQLITE_OK && pList ){ - Pgno pgno = pList->pgno; - - /* If there are dirty pages in the page cache with page numbers greater - ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to - ** make the file smaller (presumably by auto-vacuum code). Do not write - ** any such pages to the file. - ** - ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag - ** set (set by sqlite3PagerDontWrite()). - */ - if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ - i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ - char *pData; /* Data to write */ - - assert( (pList->flags&PGHDR_NEED_SYNC)==0 ); - if( pList->pgno==1 ) pager_write_changecounter(pList); - - pData = pList->pData; - - /* Write out the page data. */ - rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset); - - /* If page 1 was just written, update Pager.dbFileVers to match - ** the value now stored in the database file. If writing this - ** page caused the database file to grow, update dbFileSize. - */ - if( pgno==1 ){ - memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers)); - } - if( pgno>pPager->dbFileSize ){ - pPager->dbFileSize = pgno; - } - pPager->aStat[PAGER_STAT_WRITE]++; - - /* Update any backup objects copying the contents of this pager. */ - sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData); - - PAGERTRACE(("STORE %d page %d hash(%08x)\n", - PAGERID(pPager), pgno, pager_pagehash(pList))); - IOTRACE(("PGOUT %p %d\n", pPager, pgno)); - PAGER_INCR(sqlite3_pager_writedb_count); - }else{ - PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno)); - } - pager_set_pagehash(pList); - pList = pList->pDirty; - } - - return rc; -} - -/* -** Ensure that the sub-journal file is open. If it is already open, this -** function is a no-op. -** -** SQLITE_OK is returned if everything goes according to plan. An -** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() -** fails. -*/ -static int openSubJournal(Pager *pPager){ - int rc = SQLITE_OK; - if( !isOpen(pPager->sjfd) ){ - const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE - | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE - | SQLITE_OPEN_DELETEONCLOSE; - int nStmtSpill = sqlite3Config.nStmtSpill; - if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){ - nStmtSpill = -1; - } - rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill); - } - return rc; -} - -/* -** Append a record of the current state of page pPg to the sub-journal. -** -** If successful, set the bit corresponding to pPg->pgno in the bitvecs -** for all open savepoints before returning. -** -** This function returns SQLITE_OK if everything is successful, an IO -** error code if the attempt to write to the sub-journal fails, or -** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint -** bitvec. -*/ -static int subjournalPage(PgHdr *pPg){ - int rc = SQLITE_OK; - Pager *pPager = pPg->pPager; - if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ - - /* Open the sub-journal, if it has not already been opened */ - assert( pPager->useJournal ); - assert( isOpen(pPager->jfd) || pagerUseWal(pPager) ); - assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 ); - assert( pagerUseWal(pPager) - || pageInJournal(pPager, pPg) - || pPg->pgno>pPager->dbOrigSize - ); - rc = openSubJournal(pPager); - - /* If the sub-journal was opened successfully (or was already open), - ** write the journal record into the file. */ - if( rc==SQLITE_OK ){ - void *pData = pPg->pData; - i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize); - char *pData2; - pData2 = pData; - PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno)); - rc = write32bits(pPager->sjfd, offset, pPg->pgno); - if( rc==SQLITE_OK ){ - rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4); - } - } - } - if( rc==SQLITE_OK ){ - pPager->nSubRec++; - assert( pPager->nSavepoint>0 ); - rc = addToSavepointBitvecs(pPager, pPg->pgno); - } - return rc; -} -static int subjournalPageIfRequired(PgHdr *pPg){ - if( subjRequiresPage(pPg) ){ - return subjournalPage(pPg); - }else{ - return SQLITE_OK; - } -} - -/* -** This function is called by the pcache layer when it has reached some -** soft memory limit. The first argument is a pointer to a Pager object -** (cast as a void*). The pager is always 'purgeable' (not an in-memory -** database). The second argument is a reference to a page that is -** currently dirty but has no outstanding references. The page -** is always associated with the Pager object passed as the first -** argument. -** -** The job of this function is to make pPg clean by writing its contents -** out to the database file, if possible. This may involve syncing the -** journal file. -** -** If successful, sqlite3PcacheMakeClean() is called on the page and -** SQLITE_OK returned. If an IO error occurs while trying to make the -** page clean, the IO error code is returned. If the page cannot be -** made clean for some other reason, but no error occurs, then SQLITE_OK -** is returned by sqlite3PcacheMakeClean() is not called. -*/ -static int pagerStress(void *p, PgHdr *pPg){ - Pager *pPager = (Pager *)p; - int rc = SQLITE_OK; - - assert( pPg->pPager==pPager ); - assert( pPg->flags&PGHDR_DIRTY ); - - /* The doNotSpill NOSYNC bit is set during times when doing a sync of - ** journal (and adding a new header) is not allowed. This occurs - ** during calls to sqlite3PagerWrite() while trying to journal multiple - ** pages belonging to the same sector. - ** - ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling - ** regardless of whether or not a sync is required. This is set during - ** a rollback or by user request, respectively. - ** - ** Spilling is also prohibited when in an error state since that could - ** lead to database corruption. In the current implementation it - ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3 - ** while in the error state, hence it is impossible for this routine to - ** be called in the error state. Nevertheless, we include a NEVER() - ** test for the error state as a safeguard against future changes. - */ - if( NEVER(pPager->errCode) ) return SQLITE_OK; - testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK ); - testcase( pPager->doNotSpill & SPILLFLAG_OFF ); - testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC ); - if( pPager->doNotSpill - && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0 - || (pPg->flags & PGHDR_NEED_SYNC)!=0) - ){ - return SQLITE_OK; - } - - pPager->aStat[PAGER_STAT_SPILL]++; - pPg->pDirty = 0; - if( pagerUseWal(pPager) ){ - /* Write a single frame for this page to the log. */ - rc = subjournalPageIfRequired(pPg); - if( rc==SQLITE_OK ){ - rc = pagerWalFrames(pPager, pPg, 0, 0); - } - }else{ - -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - if( pPager->tempFile==0 ){ - rc = sqlite3JournalCreate(pPager->jfd); - if( rc!=SQLITE_OK ) return pager_error(pPager, rc); - } -#endif - - /* Sync the journal file if required. */ - if( pPg->flags&PGHDR_NEED_SYNC - || pPager->eState==PAGER_WRITER_CACHEMOD - ){ - rc = syncJournal(pPager, 1); - } - - /* Write the contents of the page out to the database file. */ - if( rc==SQLITE_OK ){ - assert( (pPg->flags&PGHDR_NEED_SYNC)==0 ); - rc = pager_write_pagelist(pPager, pPg); - } - } - - /* Mark the page as clean. */ - if( rc==SQLITE_OK ){ - PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno)); - sqlite3PcacheMakeClean(pPg); - } - - return pager_error(pPager, rc); -} - -/* -** Flush all unreferenced dirty pages to disk. -*/ -SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){ - int rc = pPager->errCode; - if( !MEMDB ){ - PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); - assert( assert_pager_state(pPager) ); - while( rc==SQLITE_OK && pList ){ - PgHdr *pNext = pList->pDirty; - if( pList->nRef==0 ){ - rc = pagerStress((void*)pPager, pList); - } - pList = pNext; - } - } - - return rc; -} - -/* -** Allocate and initialize a new Pager object and put a pointer to it -** in *ppPager. The pager should eventually be freed by passing it -** to sqlite3PagerClose(). -** -** The zFilename argument is the path to the database file to open. -** If zFilename is NULL then a randomly-named temporary file is created -** and used as the file to be cached. Temporary files are be deleted -** automatically when they are closed. If zFilename is ":memory:" then -** all information is held in cache. It is never written to disk. -** This can be used to implement an in-memory database. -** -** The nExtra parameter specifies the number of bytes of space allocated -** along with each page reference. This space is available to the user -** via the sqlite3PagerGetExtra() API. When a new page is allocated, the -** first 8 bytes of this space are zeroed but the remainder is uninitialized. -** (The extra space is used by btree as the MemPage object.) -** -** The flags argument is used to specify properties that affect the -** operation of the pager. It should be passed some bitwise combination -** of the PAGER_* flags. -** -** The vfsFlags parameter is a bitmask to pass to the flags parameter -** of the xOpen() method of the supplied VFS when opening files. -** -** If the pager object is allocated and the specified file opened -** successfully, SQLITE_OK is returned and *ppPager set to point to -** the new pager object. If an error occurs, *ppPager is set to NULL -** and error code returned. This function may return SQLITE_NOMEM -** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or -** various SQLITE_IO_XXX errors. -*/ -SQLITE_PRIVATE int sqlite3PagerOpen( - sqlite3_vfs *pVfs, /* The virtual file system to use */ - Pager **ppPager, /* OUT: Return the Pager structure here */ - const char *zFilename, /* Name of the database file to open */ - int nExtra, /* Extra bytes append to each in-memory page */ - int flags, /* flags controlling this file */ - int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */ - void (*xReinit)(DbPage*) /* Function to reinitialize pages */ -){ - u8 *pPtr; - Pager *pPager = 0; /* Pager object to allocate and return */ - int rc = SQLITE_OK; /* Return code */ - int tempFile = 0; /* True for temp files (incl. in-memory files) */ - int memDb = 0; /* True if this is an in-memory file */ -#ifdef SQLITE_ENABLE_DESERIALIZE - int memJM = 0; /* Memory journal mode */ -#else -# define memJM 0 -#endif - int readOnly = 0; /* True if this is a read-only file */ - int journalFileSize; /* Bytes to allocate for each journal fd */ - char *zPathname = 0; /* Full path to database file */ - int nPathname = 0; /* Number of bytes in zPathname */ - int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */ - int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */ - u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */ - const char *zUri = 0; /* URI args to copy */ - int nUriByte = 1; /* Number of bytes of URI args at *zUri */ - int nUri = 0; /* Number of URI parameters */ - - /* Figure out how much space is required for each journal file-handle - ** (there are two of them, the main journal and the sub-journal). */ - journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); - - /* Set the output variable to NULL in case an error occurs. */ - *ppPager = 0; - -#ifndef SQLITE_OMIT_MEMORYDB - if( flags & PAGER_MEMORY ){ - memDb = 1; - if( zFilename && zFilename[0] ){ - zPathname = sqlite3DbStrDup(0, zFilename); - if( zPathname==0 ) return SQLITE_NOMEM_BKPT; - nPathname = sqlite3Strlen30(zPathname); - zFilename = 0; - } - } -#endif - - /* Compute and store the full pathname in an allocated buffer pointed - ** to by zPathname, length nPathname. Or, if this is a temporary file, - ** leave both nPathname and zPathname set to 0. - */ - if( zFilename && zFilename[0] ){ - const char *z; - nPathname = pVfs->mxPathname+1; - zPathname = sqlite3DbMallocRaw(0, nPathname*2); - if( zPathname==0 ){ - return SQLITE_NOMEM_BKPT; - } - zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */ - rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_OK_SYMLINK ){ - if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){ - rc = SQLITE_CANTOPEN_SYMLINK; - }else{ - rc = SQLITE_OK; - } - } - } - nPathname = sqlite3Strlen30(zPathname); - z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; - while( *z ){ - z += strlen(z)+1; - z += strlen(z)+1; - nUri++; - } - nUriByte = (int)(&z[1] - zUri); - assert( nUriByte>=1 ); - if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ - /* This branch is taken when the journal path required by - ** the database being opened will be more than pVfs->mxPathname - ** bytes in length. This means the database cannot be opened, - ** as it will not be possible to open the journal file or even - ** check for a hot-journal before reading. - */ - rc = SQLITE_CANTOPEN_BKPT; - } - if( rc!=SQLITE_OK ){ - sqlite3DbFree(0, zPathname); - return rc; - } - } - - /* Allocate memory for the Pager structure, PCache object, the - ** three file descriptors, the database file name and the journal - ** file name. The layout in memory is as follows: - ** - ** Pager object (sizeof(Pager) bytes) - ** PCache object (sqlite3PcacheSize() bytes) - ** Database file handle (pVfs->szOsFile bytes) - ** Sub-journal file handle (journalFileSize bytes) - ** Main journal file handle (journalFileSize bytes) - ** Ptr back to the Pager (sizeof(Pager*) bytes) - ** \0\0\0\0 database prefix (4 bytes) - ** Database file name (nPathname+1 bytes) - ** URI query parameters (nUriByte bytes) - ** Journal filename (nPathname+8+1 bytes) - ** WAL filename (nPathname+4+1 bytes) - ** \0\0\0 terminator (3 bytes) - ** - ** Some 3rd-party software, over which we have no control, depends on - ** the specific order of the filenames and the \0 separators between them - ** so that it can (for example) find the database filename given the WAL - ** filename without using the sqlite3_filename_database() API. This is a - ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party - ** software is in widespread use, so we try to avoid changing the filename - ** order and formatting if possible. In particular, the details of the - ** filename format expected by 3rd-party software should be as follows: - ** - ** - Main Database Path - ** - \0 - ** - Multiple URI components consisting of: - ** - Key - ** - \0 - ** - Value - ** - \0 - ** - \0 - ** - Journal Path - ** - \0 - ** - WAL Path (zWALName) - ** - \0 - ** - ** The sqlite3_create_filename() interface and the databaseFilename() utility - ** that is used by sqlite3_filename_database() and kin also depend on the - ** specific formatting and order of the various filenames, so if the format - ** changes here, be sure to change it there as well. - */ - pPtr = (u8 *)sqlite3MallocZero( - ROUND8(sizeof(*pPager)) + /* Pager structure */ - ROUND8(pcacheSize) + /* PCache object */ - ROUND8(pVfs->szOsFile) + /* The main db file */ - journalFileSize * 2 + /* The two journal files */ - sizeof(pPager) + /* Space to hold a pointer */ - 4 + /* Database prefix */ - nPathname + 1 + /* database filename */ - nUriByte + /* query parameters */ - nPathname + 8 + 1 + /* Journal filename */ -#ifndef SQLITE_OMIT_WAL - nPathname + 4 + 1 + /* WAL filename */ -#endif - 3 /* Terminator */ - ); - assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) ); - if( !pPtr ){ - sqlite3DbFree(0, zPathname); - return SQLITE_NOMEM_BKPT; - } - pPager = (Pager*)pPtr; pPtr += ROUND8(sizeof(*pPager)); - pPager->pPCache = (PCache*)pPtr; pPtr += ROUND8(pcacheSize); - pPager->fd = (sqlite3_file*)pPtr; pPtr += ROUND8(pVfs->szOsFile); - pPager->sjfd = (sqlite3_file*)pPtr; pPtr += journalFileSize; - pPager->jfd = (sqlite3_file*)pPtr; pPtr += journalFileSize; - assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); - memcpy(pPtr, &pPager, sizeof(pPager)); pPtr += sizeof(pPager); - - /* Fill in the Pager.zFilename and pPager.zQueryParam fields */ - pPtr += 4; /* Skip zero prefix */ - pPager->zFilename = (char*)pPtr; - if( nPathname>0 ){ - memcpy(pPtr, zPathname, nPathname); pPtr += nPathname + 1; - if( zUri ){ - memcpy(pPtr, zUri, nUriByte); pPtr += nUriByte; - }else{ - pPtr++; - } - } - - - /* Fill in Pager.zJournal */ - if( nPathname>0 ){ - pPager->zJournal = (char*)pPtr; - memcpy(pPtr, zPathname, nPathname); pPtr += nPathname; - memcpy(pPtr, "-journal",8); pPtr += 8 + 1; -#ifdef SQLITE_ENABLE_8_3_NAMES - sqlite3FileSuffix3(zFilename,pPager->zJournal); - pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1); -#endif - }else{ - pPager->zJournal = 0; - } - -#ifndef SQLITE_OMIT_WAL - /* Fill in Pager.zWal */ - if( nPathname>0 ){ - pPager->zWal = (char*)pPtr; - memcpy(pPtr, zPathname, nPathname); pPtr += nPathname; - memcpy(pPtr, "-wal", 4); pPtr += 4 + 1; -#ifdef SQLITE_ENABLE_8_3_NAMES - sqlite3FileSuffix3(zFilename, pPager->zWal); - pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1); -#endif - }else{ - pPager->zWal = 0; - } -#endif - - if( nPathname ) sqlite3DbFree(0, zPathname); - pPager->pVfs = pVfs; - pPager->vfsFlags = vfsFlags; - - /* Open the pager file. - */ - if( zFilename && zFilename[0] ){ - int fout = 0; /* VFS flags returned by xOpen() */ - rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); - assert( !memDb ); -#ifdef SQLITE_ENABLE_DESERIALIZE - memJM = (fout&SQLITE_OPEN_MEMORY)!=0; -#endif - readOnly = (fout&SQLITE_OPEN_READONLY)!=0; - - /* If the file was successfully opened for read/write access, - ** choose a default page size in case we have to create the - ** database file. The default page size is the maximum of: - ** - ** + SQLITE_DEFAULT_PAGE_SIZE, - ** + The value returned by sqlite3OsSectorSize() - ** + The largest page size that can be written atomically. - */ - if( rc==SQLITE_OK ){ - int iDc = sqlite3OsDeviceCharacteristics(pPager->fd); - if( !readOnly ){ - setSectorSize(pPager); - assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE); - if( szPageDfltsectorSize ){ - if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){ - szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE; - }else{ - szPageDflt = (u32)pPager->sectorSize; - } - } -#ifdef SQLITE_ENABLE_ATOMIC_WRITE - { - int ii; - assert(SQLITE_IOCAP_ATOMIC512==(512>>8)); - assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8)); - assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536); - for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){ - if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){ - szPageDflt = ii; - } - } - } -#endif - } - pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0); - if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0 - || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){ - vfsFlags |= SQLITE_OPEN_READONLY; - goto act_like_temp_file; - } - } - }else{ - /* If a temporary file is requested, it is not opened immediately. - ** In this case we accept the default page size and delay actually - ** opening the file until the first call to OsWrite(). - ** - ** This branch is also run for an in-memory database. An in-memory - ** database is the same as a temp-file that is never written out to - ** disk and uses an in-memory rollback journal. - ** - ** This branch also runs for files marked as immutable. - */ -act_like_temp_file: - tempFile = 1; - pPager->eState = PAGER_READER; /* Pretend we already have a lock */ - pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */ - pPager->noLock = 1; /* Do no locking */ - readOnly = (vfsFlags&SQLITE_OPEN_READONLY); - } - - /* The following call to PagerSetPagesize() serves to set the value of - ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer. - */ - if( rc==SQLITE_OK ){ - assert( pPager->memDb==0 ); - rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1); - testcase( rc!=SQLITE_OK ); - } - - /* Initialize the PCache object. */ - if( rc==SQLITE_OK ){ - nExtra = ROUND8(nExtra); - assert( nExtra>=8 && nExtra<1000 ); - rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb, - !memDb?pagerStress:0, (void *)pPager, pPager->pPCache); - } - - /* If an error occurred above, free the Pager structure and close the file. - */ - if( rc!=SQLITE_OK ){ - sqlite3OsClose(pPager->fd); - sqlite3PageFree(pPager->pTmpSpace); - sqlite3_free(pPager); - return rc; - } - - PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename)); - IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename)) - - pPager->useJournal = (u8)useJournal; - /* pPager->stmtOpen = 0; */ - /* pPager->stmtInUse = 0; */ - /* pPager->nRef = 0; */ - /* pPager->stmtSize = 0; */ - /* pPager->stmtJSize = 0; */ - /* pPager->nPage = 0; */ - pPager->mxPgno = SQLITE_MAX_PAGE_COUNT; - /* pPager->state = PAGER_UNLOCK; */ - /* pPager->errMask = 0; */ - pPager->tempFile = (u8)tempFile; - assert( tempFile==PAGER_LOCKINGMODE_NORMAL - || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE ); - assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 ); - pPager->exclusiveMode = (u8)tempFile; - pPager->changeCountDone = pPager->tempFile; - pPager->memDb = (u8)memDb; - pPager->readOnly = (u8)readOnly; - assert( useJournal || pPager->tempFile ); - pPager->noSync = pPager->tempFile; - if( pPager->noSync ){ - assert( pPager->fullSync==0 ); - assert( pPager->extraSync==0 ); - assert( pPager->syncFlags==0 ); - assert( pPager->walSyncFlags==0 ); - }else{ - pPager->fullSync = 1; - pPager->extraSync = 0; - pPager->syncFlags = SQLITE_SYNC_NORMAL; - pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2); - } - /* pPager->pFirst = 0; */ - /* pPager->pFirstSynced = 0; */ - /* pPager->pLast = 0; */ - pPager->nExtra = (u16)nExtra; - pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT; - assert( isOpen(pPager->fd) || tempFile ); - setSectorSize(pPager); - if( !useJournal ){ - pPager->journalMode = PAGER_JOURNALMODE_OFF; - }else if( memDb || memJM ){ - pPager->journalMode = PAGER_JOURNALMODE_MEMORY; - } - /* pPager->xBusyHandler = 0; */ - /* pPager->pBusyHandlerArg = 0; */ - pPager->xReiniter = xReinit; - setGetterMethod(pPager); - /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ - /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */ - - *ppPager = pPager; - return SQLITE_OK; -} - -/* -** Return the sqlite3_file for the main database given the name -** of the corresonding WAL or Journal name as passed into -** xOpen. -*/ -SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){ - Pager *pPager; - while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){ - zName--; - } - pPager = *(Pager**)(zName - 4 - sizeof(Pager*)); - return pPager->fd; -} - - -/* -** This function is called after transitioning from PAGER_UNLOCK to -** PAGER_SHARED state. It tests if there is a hot journal present in -** the file-system for the given pager. A hot journal is one that -** needs to be played back. According to this function, a hot-journal -** file exists if the following criteria are met: -** -** * The journal file exists in the file system, and -** * No process holds a RESERVED or greater lock on the database file, and -** * The database file itself is greater than 0 bytes in size, and -** * The first byte of the journal file exists and is not 0x00. -** -** If the current size of the database file is 0 but a journal file -** exists, that is probably an old journal left over from a prior -** database with the same name. In this case the journal file is -** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK -** is returned. -** -** This routine does not check if there is a super-journal filename -** at the end of the file. If there is, and that super-journal file -** does not exist, then the journal file is not really hot. In this -** case this routine will return a false-positive. The pager_playback() -** routine will discover that the journal file is not really hot and -** will not roll it back. -** -** If a hot-journal file is found to exist, *pExists is set to 1 and -** SQLITE_OK returned. If no hot-journal file is present, *pExists is -** set to 0 and SQLITE_OK returned. If an IO error occurs while trying -** to determine whether or not a hot-journal file exists, the IO error -** code is returned and the value of *pExists is undefined. -*/ -static int hasHotJournal(Pager *pPager, int *pExists){ - sqlite3_vfs * const pVfs = pPager->pVfs; - int rc = SQLITE_OK; /* Return code */ - int exists = 1; /* True if a journal file is present */ - int jrnlOpen = !!isOpen(pPager->jfd); - - assert( pPager->useJournal ); - assert( isOpen(pPager->fd) ); - assert( pPager->eState==PAGER_OPEN ); - - assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) & - SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN - )); - - *pExists = 0; - if( !jrnlOpen ){ - rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists); - } - if( rc==SQLITE_OK && exists ){ - int locked = 0; /* True if some process holds a RESERVED lock */ - - /* Race condition here: Another process might have been holding the - ** the RESERVED lock and have a journal open at the sqlite3OsAccess() - ** call above, but then delete the journal and drop the lock before - ** we get to the following sqlite3OsCheckReservedLock() call. If that - ** is the case, this routine might think there is a hot journal when - ** in fact there is none. This results in a false-positive which will - ** be dealt with by the playback routine. Ticket #3883. - */ - rc = sqlite3OsCheckReservedLock(pPager->fd, &locked); - if( rc==SQLITE_OK && !locked ){ - Pgno nPage; /* Number of pages in database file */ - - assert( pPager->tempFile==0 ); - rc = pagerPagecount(pPager, &nPage); - if( rc==SQLITE_OK ){ - /* If the database is zero pages in size, that means that either (1) the - ** journal is a remnant from a prior database with the same name where - ** the database file but not the journal was deleted, or (2) the initial - ** transaction that populates a new database is being rolled back. - ** In either case, the journal file can be deleted. However, take care - ** not to delete the journal file if it is already open due to - ** journal_mode=PERSIST. - */ - if( nPage==0 && !jrnlOpen ){ - sqlite3BeginBenignMalloc(); - if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){ - sqlite3OsDelete(pVfs, pPager->zJournal, 0); - if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); - } - sqlite3EndBenignMalloc(); - }else{ - /* The journal file exists and no other connection has a reserved - ** or greater lock on the database file. Now check that there is - ** at least one non-zero bytes at the start of the journal file. - ** If there is, then we consider this journal to be hot. If not, - ** it can be ignored. - */ - if( !jrnlOpen ){ - int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL; - rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f); - } - if( rc==SQLITE_OK ){ - u8 first = 0; - rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0); - if( rc==SQLITE_IOERR_SHORT_READ ){ - rc = SQLITE_OK; - } - if( !jrnlOpen ){ - sqlite3OsClose(pPager->jfd); - } - *pExists = (first!=0); - }else if( rc==SQLITE_CANTOPEN ){ - /* If we cannot open the rollback journal file in order to see if - ** it has a zero header, that might be due to an I/O error, or - ** it might be due to the race condition described above and in - ** ticket #3883. Either way, assume that the journal is hot. - ** This might be a false positive. But if it is, then the - ** automatic journal playback and recovery mechanism will deal - ** with it under an EXCLUSIVE lock where we do not need to - ** worry so much with race conditions. - */ - *pExists = 1; - rc = SQLITE_OK; - } - } - } - } - } - - return rc; -} - -/* -** This function is called to obtain a shared lock on the database file. -** It is illegal to call sqlite3PagerGet() until after this function -** has been successfully called. If a shared-lock is already held when -** this function is called, it is a no-op. -** -** The following operations are also performed by this function. -** -** 1) If the pager is currently in PAGER_OPEN state (no lock held -** on the database file), then an attempt is made to obtain a -** SHARED lock on the database file. Immediately after obtaining -** the SHARED lock, the file-system is checked for a hot-journal, -** which is played back if present. Following any hot-journal -** rollback, the contents of the cache are validated by checking -** the 'change-counter' field of the database file header and -** discarded if they are found to be invalid. -** -** 2) If the pager is running in exclusive-mode, and there are currently -** no outstanding references to any pages, and is in the error state, -** then an attempt is made to clear the error state by discarding -** the contents of the page cache and rolling back any open journal -** file. -** -** If everything is successful, SQLITE_OK is returned. If an IO error -** occurs while locking the database, checking for a hot-journal file or -** rolling back a journal file, the IO error code is returned. -*/ -SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){ - int rc = SQLITE_OK; /* Return code */ - - /* This routine is only called from b-tree and only when there are no - ** outstanding pages. This implies that the pager state should either - ** be OPEN or READER. READER is only possible if the pager is or was in - ** exclusive access mode. */ - assert( sqlite3PcacheRefCount(pPager->pPCache)==0 ); - assert( assert_pager_state(pPager) ); - assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER ); - assert( pPager->errCode==SQLITE_OK ); - - if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){ - int bHotJournal = 1; /* True if there exists a hot journal-file */ - - assert( !MEMDB ); - assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK ); - - rc = pager_wait_on_lock(pPager, SHARED_LOCK); - if( rc!=SQLITE_OK ){ - assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK ); - goto failed; - } - - /* If a journal file exists, and there is no RESERVED lock on the - ** database file, then it either needs to be played back or deleted. - */ - if( pPager->eLock<=SHARED_LOCK ){ - rc = hasHotJournal(pPager, &bHotJournal); - } - if( rc!=SQLITE_OK ){ - goto failed; - } - if( bHotJournal ){ - if( pPager->readOnly ){ - rc = SQLITE_READONLY_ROLLBACK; - goto failed; - } - - /* Get an EXCLUSIVE lock on the database file. At this point it is - ** important that a RESERVED lock is not obtained on the way to the - ** EXCLUSIVE lock. If it were, another process might open the - ** database file, detect the RESERVED lock, and conclude that the - ** database is safe to read while this process is still rolling the - ** hot-journal back. - ** - ** Because the intermediate RESERVED lock is not requested, any - ** other process attempting to access the database file will get to - ** this point in the code and fail to obtain its own EXCLUSIVE lock - ** on the database file. - ** - ** Unless the pager is in locking_mode=exclusive mode, the lock is - ** downgraded to SHARED_LOCK before this function returns. - */ - rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); - if( rc!=SQLITE_OK ){ - goto failed; - } - - /* If it is not already open and the file exists on disk, open the - ** journal for read/write access. Write access is required because - ** in exclusive-access mode the file descriptor will be kept open - ** and possibly used for a transaction later on. Also, write-access - ** is usually required to finalize the journal in journal_mode=persist - ** mode (and also for journal_mode=truncate on some systems). - ** - ** If the journal does not exist, it usually means that some - ** other connection managed to get in and roll it back before - ** this connection obtained the exclusive lock above. Or, it - ** may mean that the pager was in the error-state when this - ** function was called and the journal file does not exist. - */ - if( !isOpen(pPager->jfd) ){ - sqlite3_vfs * const pVfs = pPager->pVfs; - int bExists; /* True if journal file exists */ - rc = sqlite3OsAccess( - pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists); - if( rc==SQLITE_OK && bExists ){ - int fout = 0; - int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; - assert( !pPager->tempFile ); - rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); - assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); - if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ - rc = SQLITE_CANTOPEN_BKPT; - sqlite3OsClose(pPager->jfd); - } - } - } - - /* Playback and delete the journal. Drop the database write - ** lock and reacquire the read lock. Purge the cache before - ** playing back the hot-journal so that we don't end up with - ** an inconsistent cache. Sync the hot journal before playing - ** it back since the process that crashed and left the hot journal - ** probably did not sync it and we are required to always sync - ** the journal before playing it back. - */ - if( isOpen(pPager->jfd) ){ - assert( rc==SQLITE_OK ); - rc = pagerSyncHotJournal(pPager); - if( rc==SQLITE_OK ){ - rc = pager_playback(pPager, !pPager->tempFile); - pPager->eState = PAGER_OPEN; - } - }else if( !pPager->exclusiveMode ){ - pagerUnlockDb(pPager, SHARED_LOCK); - } - - if( rc!=SQLITE_OK ){ - /* This branch is taken if an error occurs while trying to open - ** or roll back a hot-journal while holding an EXCLUSIVE lock. The - ** pager_unlock() routine will be called before returning to unlock - ** the file. If the unlock attempt fails, then Pager.eLock must be - ** set to UNKNOWN_LOCK (see the comment above the #define for - ** UNKNOWN_LOCK above for an explanation). - ** - ** In order to get pager_unlock() to do this, set Pager.eState to - ** PAGER_ERROR now. This is not actually counted as a transition - ** to ERROR state in the state diagram at the top of this file, - ** since we know that the same call to pager_unlock() will very - ** shortly transition the pager object to the OPEN state. Calling - ** assert_pager_state() would fail now, as it should not be possible - ** to be in ERROR state when there are zero outstanding page - ** references. - */ - pager_error(pPager, rc); - goto failed; - } - - assert( pPager->eState==PAGER_OPEN ); - assert( (pPager->eLock==SHARED_LOCK) - || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK) - ); - } - - if( !pPager->tempFile && pPager->hasHeldSharedLock ){ - /* The shared-lock has just been acquired then check to - ** see if the database has been modified. If the database has changed, - ** flush the cache. The hasHeldSharedLock flag prevents this from - ** occurring on the very first access to a file, in order to save a - ** single unnecessary sqlite3OsRead() call at the start-up. - ** - ** Database changes are detected by looking at 15 bytes beginning - ** at offset 24 into the file. The first 4 of these 16 bytes are - ** a 32-bit counter that is incremented with each change. The - ** other bytes change randomly with each file change when - ** a codec is in use. - ** - ** There is a vanishingly small chance that a change will not be - ** detected. The chance of an undetected change is so small that - ** it can be neglected. - */ - char dbFileVers[sizeof(pPager->dbFileVers)]; - - IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers))); - rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24); - if( rc!=SQLITE_OK ){ - if( rc!=SQLITE_IOERR_SHORT_READ ){ - goto failed; - } - memset(dbFileVers, 0, sizeof(dbFileVers)); - } - - if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){ - pager_reset(pPager); - - /* Unmap the database file. It is possible that external processes - ** may have truncated the database file and then extended it back - ** to its original size while this process was not holding a lock. - ** In this case there may exist a Pager.pMap mapping that appears - ** to be the right size but is not actually valid. Avoid this - ** possibility by unmapping the db here. */ - if( USEFETCH(pPager) ){ - sqlite3OsUnfetch(pPager->fd, 0, 0); - } - } - } - - /* If there is a WAL file in the file-system, open this database in WAL - ** mode. Otherwise, the following function call is a no-op. - */ - rc = pagerOpenWalIfPresent(pPager); -#ifndef SQLITE_OMIT_WAL - assert( pPager->pWal==0 || rc==SQLITE_OK ); -#endif - } - - if( pagerUseWal(pPager) ){ - assert( rc==SQLITE_OK ); - rc = pagerBeginReadTransaction(pPager); - } - - if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){ - rc = pagerPagecount(pPager, &pPager->dbSize); - } - - failed: - if( rc!=SQLITE_OK ){ - assert( !MEMDB ); - pager_unlock(pPager); - assert( pPager->eState==PAGER_OPEN ); - }else{ - pPager->eState = PAGER_READER; - pPager->hasHeldSharedLock = 1; - } - return rc; -} - -/* -** If the reference count has reached zero, rollback any active -** transaction and unlock the pager. -** -** Except, in locking_mode=EXCLUSIVE when there is nothing to in -** the rollback journal, the unlock is not performed and there is -** nothing to rollback, so this routine is a no-op. -*/ -static void pagerUnlockIfUnused(Pager *pPager){ - if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){ - assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */ - pagerUnlockAndRollback(pPager); - } -} - -/* -** The page getter methods each try to acquire a reference to a -** page with page number pgno. If the requested reference is -** successfully obtained, it is copied to *ppPage and SQLITE_OK returned. -** -** There are different implementations of the getter method depending -** on the current state of the pager. -** -** getPageNormal() -- The normal getter -** getPageError() -- Used if the pager is in an error state -** getPageMmap() -- Used if memory-mapped I/O is enabled -** -** If the requested page is already in the cache, it is returned. -** Otherwise, a new page object is allocated and populated with data -** read from the database file. In some cases, the pcache module may -** choose not to allocate a new page object and may reuse an existing -** object with no outstanding references. -** -** The extra data appended to a page is always initialized to zeros the -** first time a page is loaded into memory. If the page requested is -** already in the cache when this function is called, then the extra -** data is left as it was when the page object was last used. -** -** If the database image is smaller than the requested page or if -** the flags parameter contains the PAGER_GET_NOCONTENT bit and the -** requested page is not already stored in the cache, then no -** actual disk read occurs. In this case the memory image of the -** page is initialized to all zeros. -** -** If PAGER_GET_NOCONTENT is true, it means that we do not care about -** the contents of the page. This occurs in two scenarios: -** -** a) When reading a free-list leaf page from the database, and -** -** b) When a savepoint is being rolled back and we need to load -** a new page into the cache to be filled with the data read -** from the savepoint journal. -** -** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead -** of being read from the database. Additionally, the bits corresponding -** to pgno in Pager.pInJournal (bitvec of pages already written to the -** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open -** savepoints are set. This means if the page is made writable at any -** point in the future, using a call to sqlite3PagerWrite(), its contents -** will not be journaled. This saves IO. -** -** The acquisition might fail for several reasons. In all cases, -** an appropriate error code is returned and *ppPage is set to NULL. -** -** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt -** to find a page in the in-memory cache first. If the page is not already -** in memory, this routine goes to disk to read it in whereas Lookup() -** just returns 0. This routine acquires a read-lock the first time it -** has to go to disk, and could also playback an old journal if necessary. -** Since Lookup() never goes to disk, it never has to deal with locks -** or journal files. -*/ -static int getPageNormal( - Pager *pPager, /* The pager open on the database file */ - Pgno pgno, /* Page number to fetch */ - DbPage **ppPage, /* Write a pointer to the page here */ - int flags /* PAGER_GET_XXX flags */ -){ - int rc = SQLITE_OK; - PgHdr *pPg; - u8 noContent; /* True if PAGER_GET_NOCONTENT is set */ - sqlite3_pcache_page *pBase; - - assert( pPager->errCode==SQLITE_OK ); - assert( pPager->eState>=PAGER_READER ); - assert( assert_pager_state(pPager) ); - assert( pPager->hasHeldSharedLock==1 ); - - if( pgno==0 ) return SQLITE_CORRUPT_BKPT; - pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3); - if( pBase==0 ){ - pPg = 0; - rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase); - if( rc!=SQLITE_OK ) goto pager_acquire_err; - if( pBase==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto pager_acquire_err; - } - } - pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase); - assert( pPg==(*ppPage) ); - assert( pPg->pgno==pgno ); - assert( pPg->pPager==pPager || pPg->pPager==0 ); - - noContent = (flags & PAGER_GET_NOCONTENT)!=0; - if( pPg->pPager && !noContent ){ - /* In this case the pcache already contains an initialized copy of - ** the page. Return without further ado. */ - assert( pgno!=PAGER_MJ_PGNO(pPager) ); - pPager->aStat[PAGER_STAT_HIT]++; - return SQLITE_OK; - - }else{ - /* The pager cache has created a new page. Its content needs to - ** be initialized. But first some error checks: - ** - ** (*) obsolete. Was: maximum page number is 2^31 - ** (2) Never try to fetch the locking page - */ - if( pgno==PAGER_MJ_PGNO(pPager) ){ - rc = SQLITE_CORRUPT_BKPT; - goto pager_acquire_err; - } - - pPg->pPager = pPager; - - assert( !isOpen(pPager->fd) || !MEMDB ); - if( !isOpen(pPager->fd) || pPager->dbSizepPager->mxPgno ){ - rc = SQLITE_FULL; - goto pager_acquire_err; - } - if( noContent ){ - /* Failure to set the bits in the InJournal bit-vectors is benign. - ** It merely means that we might do some extra work to journal a - ** page that does not need to be journaled. Nevertheless, be sure - ** to test the case where a malloc error occurs while trying to set - ** a bit in a bit vector. - */ - sqlite3BeginBenignMalloc(); - if( pgno<=pPager->dbOrigSize ){ - TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno); - testcase( rc==SQLITE_NOMEM ); - } - TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno); - testcase( rc==SQLITE_NOMEM ); - sqlite3EndBenignMalloc(); - } - memset(pPg->pData, 0, pPager->pageSize); - IOTRACE(("ZERO %p %d\n", pPager, pgno)); - }else{ - assert( pPg->pPager==pPager ); - pPager->aStat[PAGER_STAT_MISS]++; - rc = readDbPage(pPg); - if( rc!=SQLITE_OK ){ - goto pager_acquire_err; - } - } - pager_set_pagehash(pPg); - } - return SQLITE_OK; - -pager_acquire_err: - assert( rc!=SQLITE_OK ); - if( pPg ){ - sqlite3PcacheDrop(pPg); - } - pagerUnlockIfUnused(pPager); - *ppPage = 0; - return rc; -} - -#if SQLITE_MAX_MMAP_SIZE>0 -/* The page getter for when memory-mapped I/O is enabled */ -static int getPageMMap( - Pager *pPager, /* The pager open on the database file */ - Pgno pgno, /* Page number to fetch */ - DbPage **ppPage, /* Write a pointer to the page here */ - int flags /* PAGER_GET_XXX flags */ -){ - int rc = SQLITE_OK; - PgHdr *pPg = 0; - u32 iFrame = 0; /* Frame to read from WAL file */ - - /* It is acceptable to use a read-only (mmap) page for any page except - ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY - ** flag was specified by the caller. And so long as the db is not a - ** temporary or in-memory database. */ - const int bMmapOk = (pgno>1 - && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY)) - ); - - assert( USEFETCH(pPager) ); - - /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here - ** allows the compiler optimizer to reuse the results of the "pgno>1" - ** test in the previous statement, and avoid testing pgno==0 in the - ** common case where pgno is large. */ - if( pgno<=1 && pgno==0 ){ - return SQLITE_CORRUPT_BKPT; - } - assert( pPager->eState>=PAGER_READER ); - assert( assert_pager_state(pPager) ); - assert( pPager->hasHeldSharedLock==1 ); - assert( pPager->errCode==SQLITE_OK ); - - if( bMmapOk && pagerUseWal(pPager) ){ - rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame); - if( rc!=SQLITE_OK ){ - *ppPage = 0; - return rc; - } - } - if( bMmapOk && iFrame==0 ){ - void *pData = 0; - rc = sqlite3OsFetch(pPager->fd, - (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData - ); - if( rc==SQLITE_OK && pData ){ - if( pPager->eState>PAGER_READER || pPager->tempFile ){ - pPg = sqlite3PagerLookup(pPager, pgno); - } - if( pPg==0 ){ - rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg); - }else{ - sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData); - } - if( pPg ){ - assert( rc==SQLITE_OK ); - *ppPage = pPg; - return SQLITE_OK; - } - } - if( rc!=SQLITE_OK ){ - *ppPage = 0; - return rc; - } - } - return getPageNormal(pPager, pgno, ppPage, flags); -} -#endif /* SQLITE_MAX_MMAP_SIZE>0 */ - -/* The page getter method for when the pager is an error state */ -static int getPageError( - Pager *pPager, /* The pager open on the database file */ - Pgno pgno, /* Page number to fetch */ - DbPage **ppPage, /* Write a pointer to the page here */ - int flags /* PAGER_GET_XXX flags */ -){ - UNUSED_PARAMETER(pgno); - UNUSED_PARAMETER(flags); - assert( pPager->errCode!=SQLITE_OK ); - *ppPage = 0; - return pPager->errCode; -} - - -/* Dispatch all page fetch requests to the appropriate getter method. -*/ -SQLITE_PRIVATE int sqlite3PagerGet( - Pager *pPager, /* The pager open on the database file */ - Pgno pgno, /* Page number to fetch */ - DbPage **ppPage, /* Write a pointer to the page here */ - int flags /* PAGER_GET_XXX flags */ -){ - return pPager->xGet(pPager, pgno, ppPage, flags); -} - -/* -** Acquire a page if it is already in the in-memory cache. Do -** not read the page from disk. Return a pointer to the page, -** or 0 if the page is not in cache. -** -** See also sqlite3PagerGet(). The difference between this routine -** and sqlite3PagerGet() is that _get() will go to the disk and read -** in the page if the page is not already in cache. This routine -** returns NULL if the page is not in cache or if a disk I/O error -** has ever happened. -*/ -SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){ - sqlite3_pcache_page *pPage; - assert( pPager!=0 ); - assert( pgno!=0 ); - assert( pPager->pPCache!=0 ); - pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0); - assert( pPage==0 || pPager->hasHeldSharedLock ); - if( pPage==0 ) return 0; - return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage); -} - -/* -** Release a page reference. -** -** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be -** used if we know that the page being released is not the last page. -** The btree layer always holds page1 open until the end, so these first -** to routines can be used to release any page other than BtShared.pPage1. -** -** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine -** checks the total number of outstanding pages and if the number of -** pages reaches zero it drops the database lock. -*/ -SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){ - TESTONLY( Pager *pPager = pPg->pPager; ) - assert( pPg!=0 ); - if( pPg->flags & PGHDR_MMAP ){ - assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */ - pagerReleaseMapPage(pPg); - }else{ - sqlite3PcacheRelease(pPg); - } - /* Do not use this routine to release the last reference to page1 */ - assert( sqlite3PcacheRefCount(pPager->pPCache)>0 ); -} -SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){ - if( pPg ) sqlite3PagerUnrefNotNull(pPg); -} -SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){ - Pager *pPager; - assert( pPg!=0 ); - assert( pPg->pgno==1 ); - assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */ - pPager = pPg->pPager; - sqlite3PcacheRelease(pPg); - pagerUnlockIfUnused(pPager); -} - -/* -** This function is called at the start of every write transaction. -** There must already be a RESERVED or EXCLUSIVE lock on the database -** file when this routine is called. -** -** Open the journal file for pager pPager and write a journal header -** to the start of it. If there are active savepoints, open the sub-journal -** as well. This function is only used when the journal file is being -** opened to write a rollback log for a transaction. It is not used -** when opening a hot journal file to roll it back. -** -** If the journal file is already open (as it may be in exclusive mode), -** then this function just writes a journal header to the start of the -** already open file. -** -** Whether or not the journal file is opened by this function, the -** Pager.pInJournal bitvec structure is allocated. -** -** Return SQLITE_OK if everything is successful. Otherwise, return -** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or -** an IO error code if opening or writing the journal file fails. -*/ -static int pager_open_journal(Pager *pPager){ - int rc = SQLITE_OK; /* Return code */ - sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */ - - assert( pPager->eState==PAGER_WRITER_LOCKED ); - assert( assert_pager_state(pPager) ); - assert( pPager->pInJournal==0 ); - - /* If already in the error state, this function is a no-op. But on - ** the other hand, this routine is never called if we are already in - ** an error state. */ - if( NEVER(pPager->errCode) ) return pPager->errCode; - - if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){ - pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize); - if( pPager->pInJournal==0 ){ - return SQLITE_NOMEM_BKPT; - } - - /* Open the journal file if it is not already open. */ - if( !isOpen(pPager->jfd) ){ - if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){ - sqlite3MemJournalOpen(pPager->jfd); - }else{ - int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; - int nSpill; - - if( pPager->tempFile ){ - flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL); - nSpill = sqlite3Config.nStmtSpill; - }else{ - flags |= SQLITE_OPEN_MAIN_JOURNAL; - nSpill = jrnlBufferSize(pPager); - } - - /* Verify that the database still has the same name as it did when - ** it was originally opened. */ - rc = databaseIsUnmoved(pPager); - if( rc==SQLITE_OK ){ - rc = sqlite3JournalOpen ( - pVfs, pPager->zJournal, pPager->jfd, flags, nSpill - ); - } - } - assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); - } - - - /* Write the first journal header to the journal file and open - ** the sub-journal if necessary. - */ - if( rc==SQLITE_OK ){ - /* TODO: Check if all of these are really required. */ - pPager->nRec = 0; - pPager->journalOff = 0; - pPager->setSuper = 0; - pPager->journalHdr = 0; - rc = writeJournalHdr(pPager); - } - } - - if( rc!=SQLITE_OK ){ - sqlite3BitvecDestroy(pPager->pInJournal); - pPager->pInJournal = 0; - }else{ - assert( pPager->eState==PAGER_WRITER_LOCKED ); - pPager->eState = PAGER_WRITER_CACHEMOD; - } - - return rc; -} - -/* -** Begin a write-transaction on the specified pager object. If a -** write-transaction has already been opened, this function is a no-op. -** -** If the exFlag argument is false, then acquire at least a RESERVED -** lock on the database file. If exFlag is true, then acquire at least -** an EXCLUSIVE lock. If such a lock is already held, no locking -** functions need be called. -** -** If the subjInMemory argument is non-zero, then any sub-journal opened -** within this transaction will be opened as an in-memory file. This -** has no effect if the sub-journal is already opened (as it may be when -** running in exclusive mode) or if the transaction does not require a -** sub-journal. If the subjInMemory argument is zero, then any required -** sub-journal is implemented in-memory if pPager is an in-memory database, -** or using a temporary file otherwise. -*/ -SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){ - int rc = SQLITE_OK; - - if( pPager->errCode ) return pPager->errCode; - assert( pPager->eState>=PAGER_READER && pPager->eStatesubjInMemory = (u8)subjInMemory; - - if( ALWAYS(pPager->eState==PAGER_READER) ){ - assert( pPager->pInJournal==0 ); - - if( pagerUseWal(pPager) ){ - /* If the pager is configured to use locking_mode=exclusive, and an - ** exclusive lock on the database is not already held, obtain it now. - */ - if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){ - rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); - if( rc!=SQLITE_OK ){ - return rc; - } - (void)sqlite3WalExclusiveMode(pPager->pWal, 1); - } - - /* Grab the write lock on the log file. If successful, upgrade to - ** PAGER_RESERVED state. Otherwise, return an error code to the caller. - ** The busy-handler is not invoked if another connection already - ** holds the write-lock. If possible, the upper layer will call it. - */ - rc = sqlite3WalBeginWriteTransaction(pPager->pWal); - }else{ - /* Obtain a RESERVED lock on the database file. If the exFlag parameter - ** is true, then immediately upgrade this to an EXCLUSIVE lock. The - ** busy-handler callback can be used when upgrading to the EXCLUSIVE - ** lock, but not when obtaining the RESERVED lock. - */ - rc = pagerLockDb(pPager, RESERVED_LOCK); - if( rc==SQLITE_OK && exFlag ){ - rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); - } - } - - if( rc==SQLITE_OK ){ - /* Change to WRITER_LOCKED state. - ** - ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD - ** when it has an open transaction, but never to DBMOD or FINISHED. - ** This is because in those states the code to roll back savepoint - ** transactions may copy data from the sub-journal into the database - ** file as well as into the page cache. Which would be incorrect in - ** WAL mode. - */ - pPager->eState = PAGER_WRITER_LOCKED; - pPager->dbHintSize = pPager->dbSize; - pPager->dbFileSize = pPager->dbSize; - pPager->dbOrigSize = pPager->dbSize; - pPager->journalOff = 0; - } - - assert( rc==SQLITE_OK || pPager->eState==PAGER_READER ); - assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED ); - assert( assert_pager_state(pPager) ); - } - - PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager))); - return rc; -} - -/* -** Write page pPg onto the end of the rollback journal. -*/ -static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){ - Pager *pPager = pPg->pPager; - int rc; - u32 cksum; - char *pData2; - i64 iOff = pPager->journalOff; - - /* We should never write to the journal file the page that - ** contains the database locks. The following assert verifies - ** that we do not. */ - assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) ); - - assert( pPager->journalHdr<=pPager->journalOff ); - pData2 = pPg->pData; - cksum = pager_cksum(pPager, (u8*)pData2); - - /* Even if an IO or diskfull error occurs while journalling the - ** page in the block above, set the need-sync flag for the page. - ** Otherwise, when the transaction is rolled back, the logic in - ** playback_one_page() will think that the page needs to be restored - ** in the database file. And if an IO error occurs while doing so, - ** then corruption may follow. - */ - pPg->flags |= PGHDR_NEED_SYNC; - - rc = write32bits(pPager->jfd, iOff, pPg->pgno); - if( rc!=SQLITE_OK ) return rc; - rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4); - if( rc!=SQLITE_OK ) return rc; - rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum); - if( rc!=SQLITE_OK ) return rc; - - IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, - pPager->journalOff, pPager->pageSize)); - PAGER_INCR(sqlite3_pager_writej_count); - PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n", - PAGERID(pPager), pPg->pgno, - ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg))); - - pPager->journalOff += 8 + pPager->pageSize; - pPager->nRec++; - assert( pPager->pInJournal!=0 ); - rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno); - testcase( rc==SQLITE_NOMEM ); - assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); - rc |= addToSavepointBitvecs(pPager, pPg->pgno); - assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); - return rc; -} - -/* -** Mark a single data page as writeable. The page is written into the -** main journal or sub-journal as required. If the page is written into -** one of the journals, the corresponding bit is set in the -** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs -** of any open savepoints as appropriate. -*/ -static int pager_write(PgHdr *pPg){ - Pager *pPager = pPg->pPager; - int rc = SQLITE_OK; - - /* This routine is not called unless a write-transaction has already - ** been started. The journal file may or may not be open at this point. - ** It is never called in the ERROR state. - */ - assert( pPager->eState==PAGER_WRITER_LOCKED - || pPager->eState==PAGER_WRITER_CACHEMOD - || pPager->eState==PAGER_WRITER_DBMOD - ); - assert( assert_pager_state(pPager) ); - assert( pPager->errCode==0 ); - assert( pPager->readOnly==0 ); - CHECK_PAGE(pPg); - - /* The journal file needs to be opened. Higher level routines have already - ** obtained the necessary locks to begin the write-transaction, but the - ** rollback journal might not yet be open. Open it now if this is the case. - ** - ** This is done before calling sqlite3PcacheMakeDirty() on the page. - ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then - ** an error might occur and the pager would end up in WRITER_LOCKED state - ** with pages marked as dirty in the cache. - */ - if( pPager->eState==PAGER_WRITER_LOCKED ){ - rc = pager_open_journal(pPager); - if( rc!=SQLITE_OK ) return rc; - } - assert( pPager->eState>=PAGER_WRITER_CACHEMOD ); - assert( assert_pager_state(pPager) ); - - /* Mark the page that is about to be modified as dirty. */ - sqlite3PcacheMakeDirty(pPg); - - /* If a rollback journal is in use, them make sure the page that is about - ** to change is in the rollback journal, or if the page is a new page off - ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC. - */ - assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) ); - if( pPager->pInJournal!=0 - && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0 - ){ - assert( pagerUseWal(pPager)==0 ); - if( pPg->pgno<=pPager->dbOrigSize ){ - rc = pagerAddPageToRollbackJournal(pPg); - if( rc!=SQLITE_OK ){ - return rc; - } - }else{ - if( pPager->eState!=PAGER_WRITER_DBMOD ){ - pPg->flags |= PGHDR_NEED_SYNC; - } - PAGERTRACE(("APPEND %d page %d needSync=%d\n", - PAGERID(pPager), pPg->pgno, - ((pPg->flags&PGHDR_NEED_SYNC)?1:0))); - } - } - - /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list - ** and before writing the page into the rollback journal. Wait until now, - ** after the page has been successfully journalled, before setting the - ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified. - */ - pPg->flags |= PGHDR_WRITEABLE; - - /* If the statement journal is open and the page is not in it, - ** then write the page into the statement journal. - */ - if( pPager->nSavepoint>0 ){ - rc = subjournalPageIfRequired(pPg); - } - - /* Update the database size and return. */ - if( pPager->dbSizepgno ){ - pPager->dbSize = pPg->pgno; - } - return rc; -} - -/* -** This is a variant of sqlite3PagerWrite() that runs when the sector size -** is larger than the page size. SQLite makes the (reasonable) assumption that -** all bytes of a sector are written together by hardware. Hence, all bytes of -** a sector need to be journalled in case of a power loss in the middle of -** a write. -** -** Usually, the sector size is less than or equal to the page size, in which -** case pages can be individually written. This routine only runs in the -** exceptional case where the page size is smaller than the sector size. -*/ -static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){ - int rc = SQLITE_OK; /* Return code */ - Pgno nPageCount; /* Total number of pages in database file */ - Pgno pg1; /* First page of the sector pPg is located on. */ - int nPage = 0; /* Number of pages starting at pg1 to journal */ - int ii; /* Loop counter */ - int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */ - Pager *pPager = pPg->pPager; /* The pager that owns pPg */ - Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize); - - /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow - ** a journal header to be written between the pages journaled by - ** this function. - */ - assert( !MEMDB ); - assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 ); - pPager->doNotSpill |= SPILLFLAG_NOSYNC; - - /* This trick assumes that both the page-size and sector-size are - ** an integer power of 2. It sets variable pg1 to the identifier - ** of the first page of the sector pPg is located on. - */ - pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1; - - nPageCount = pPager->dbSize; - if( pPg->pgno>nPageCount ){ - nPage = (pPg->pgno - pg1)+1; - }else if( (pg1+nPagePerSector-1)>nPageCount ){ - nPage = nPageCount+1-pg1; - }else{ - nPage = nPagePerSector; - } - assert(nPage>0); - assert(pg1<=pPg->pgno); - assert((pg1+nPage)>pPg->pgno); - - for(ii=0; iipgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){ - if( pg!=PAGER_MJ_PGNO(pPager) ){ - rc = sqlite3PagerGet(pPager, pg, &pPage, 0); - if( rc==SQLITE_OK ){ - rc = pager_write(pPage); - if( pPage->flags&PGHDR_NEED_SYNC ){ - needSync = 1; - } - sqlite3PagerUnrefNotNull(pPage); - } - } - }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){ - if( pPage->flags&PGHDR_NEED_SYNC ){ - needSync = 1; - } - sqlite3PagerUnrefNotNull(pPage); - } - } - - /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages - ** starting at pg1, then it needs to be set for all of them. Because - ** writing to any of these nPage pages may damage the others, the - ** journal file must contain sync()ed copies of all of them - ** before any of them can be written out to the database file. - */ - if( rc==SQLITE_OK && needSync ){ - assert( !MEMDB ); - for(ii=0; iiflags |= PGHDR_NEED_SYNC; - sqlite3PagerUnrefNotNull(pPage); - } - } - } - - assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 ); - pPager->doNotSpill &= ~SPILLFLAG_NOSYNC; - return rc; -} - -/* -** Mark a data page as writeable. This routine must be called before -** making changes to a page. The caller must check the return value -** of this function and be careful not to change any page data unless -** this routine returns SQLITE_OK. -** -** The difference between this function and pager_write() is that this -** function also deals with the special case where 2 or more pages -** fit on a single disk sector. In this case all co-resident pages -** must have been written to the journal file before returning. -** -** If an error occurs, SQLITE_NOMEM or an IO error code is returned -** as appropriate. Otherwise, SQLITE_OK. -*/ -SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){ - Pager *pPager = pPg->pPager; - assert( (pPg->flags & PGHDR_MMAP)==0 ); - assert( pPager->eState>=PAGER_WRITER_LOCKED ); - assert( assert_pager_state(pPager) ); - if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){ - if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg); - return SQLITE_OK; - }else if( pPager->errCode ){ - return pPager->errCode; - }else if( pPager->sectorSize > (u32)pPager->pageSize ){ - assert( pPager->tempFile==0 ); - return pagerWriteLargeSector(pPg); - }else{ - return pager_write(pPg); - } -} - -/* -** Return TRUE if the page given in the argument was previously passed -** to sqlite3PagerWrite(). In other words, return TRUE if it is ok -** to change the content of the page. -*/ -#ifndef NDEBUG -SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ - return pPg->flags & PGHDR_WRITEABLE; -} -#endif - -/* -** A call to this routine tells the pager that it is not necessary to -** write the information on page pPg back to the disk, even though -** that page might be marked as dirty. This happens, for example, when -** the page has been added as a leaf of the freelist and so its -** content no longer matters. -** -** The overlying software layer calls this routine when all of the data -** on the given page is unused. The pager marks the page as clean so -** that it does not get written to disk. -** -** Tests show that this optimization can quadruple the speed of large -** DELETE operations. -** -** This optimization cannot be used with a temp-file, as the page may -** have been dirty at the start of the transaction. In that case, if -** memory pressure forces page pPg out of the cache, the data does need -** to be written out to disk so that it may be read back in if the -** current transaction is rolled back. -*/ -SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){ - Pager *pPager = pPg->pPager; - if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){ - PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager))); - IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) - pPg->flags |= PGHDR_DONT_WRITE; - pPg->flags &= ~PGHDR_WRITEABLE; - testcase( pPg->flags & PGHDR_NEED_SYNC ); - pager_set_pagehash(pPg); - } -} - -/* -** This routine is called to increment the value of the database file -** change-counter, stored as a 4-byte big-endian integer starting at -** byte offset 24 of the pager file. The secondary change counter at -** 92 is also updated, as is the SQLite version number at offset 96. -** -** But this only happens if the pPager->changeCountDone flag is false. -** To avoid excess churning of page 1, the update only happens once. -** See also the pager_write_changecounter() routine that does an -** unconditional update of the change counters. -** -** If the isDirectMode flag is zero, then this is done by calling -** sqlite3PagerWrite() on page 1, then modifying the contents of the -** page data. In this case the file will be updated when the current -** transaction is committed. -** -** The isDirectMode flag may only be non-zero if the library was compiled -** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case, -** if isDirect is non-zero, then the database file is updated directly -** by writing an updated version of page 1 using a call to the -** sqlite3OsWrite() function. -*/ -static int pager_incr_changecounter(Pager *pPager, int isDirectMode){ - int rc = SQLITE_OK; - - assert( pPager->eState==PAGER_WRITER_CACHEMOD - || pPager->eState==PAGER_WRITER_DBMOD - ); - assert( assert_pager_state(pPager) ); - - /* Declare and initialize constant integer 'isDirect'. If the - ** atomic-write optimization is enabled in this build, then isDirect - ** is initialized to the value passed as the isDirectMode parameter - ** to this function. Otherwise, it is always set to zero. - ** - ** The idea is that if the atomic-write optimization is not - ** enabled at compile time, the compiler can omit the tests of - ** 'isDirect' below, as well as the block enclosed in the - ** "if( isDirect )" condition. - */ -#ifndef SQLITE_ENABLE_ATOMIC_WRITE -# define DIRECT_MODE 0 - assert( isDirectMode==0 ); - UNUSED_PARAMETER(isDirectMode); -#else -# define DIRECT_MODE isDirectMode -#endif - - if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){ - PgHdr *pPgHdr; /* Reference to page 1 */ - - assert( !pPager->tempFile && isOpen(pPager->fd) ); - - /* Open page 1 of the file for writing. */ - rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0); - assert( pPgHdr==0 || rc==SQLITE_OK ); - - /* If page one was fetched successfully, and this function is not - ** operating in direct-mode, make page 1 writable. When not in - ** direct mode, page 1 is always held in cache and hence the PagerGet() - ** above is always successful - hence the ALWAYS on rc==SQLITE_OK. - */ - if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){ - rc = sqlite3PagerWrite(pPgHdr); - } - - if( rc==SQLITE_OK ){ - /* Actually do the update of the change counter */ - pager_write_changecounter(pPgHdr); - - /* If running in direct mode, write the contents of page 1 to the file. */ - if( DIRECT_MODE ){ - const void *zBuf; - assert( pPager->dbFileSize>0 ); - zBuf = pPgHdr->pData; - if( rc==SQLITE_OK ){ - rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0); - pPager->aStat[PAGER_STAT_WRITE]++; - } - if( rc==SQLITE_OK ){ - /* Update the pager's copy of the change-counter. Otherwise, the - ** next time a read transaction is opened the cache will be - ** flushed (as the change-counter values will not match). */ - const void *pCopy = (const void *)&((const char *)zBuf)[24]; - memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers)); - pPager->changeCountDone = 1; - } - }else{ - pPager->changeCountDone = 1; - } - } - - /* Release the page reference. */ - sqlite3PagerUnref(pPgHdr); - } - return rc; -} - -/* -** Sync the database file to disk. This is a no-op for in-memory databases -** or pages with the Pager.noSync flag set. -** -** If successful, or if called on a pager for which it is a no-op, this -** function returns SQLITE_OK. Otherwise, an IO error code is returned. -*/ -SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper){ - int rc = SQLITE_OK; - void *pArg = (void*)zSuper; - rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg); - if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; - if( rc==SQLITE_OK && !pPager->noSync ){ - assert( !MEMDB ); - rc = sqlite3OsSync(pPager->fd, pPager->syncFlags); - } - return rc; -} - -/* -** This function may only be called while a write-transaction is active in -** rollback. If the connection is in WAL mode, this call is a no-op. -** Otherwise, if the connection does not already have an EXCLUSIVE lock on -** the database file, an attempt is made to obtain one. -** -** If the EXCLUSIVE lock is already held or the attempt to obtain it is -** successful, or the connection is in WAL mode, SQLITE_OK is returned. -** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is -** returned. -*/ -SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){ - int rc = pPager->errCode; - assert( assert_pager_state(pPager) ); - if( rc==SQLITE_OK ){ - assert( pPager->eState==PAGER_WRITER_CACHEMOD - || pPager->eState==PAGER_WRITER_DBMOD - || pPager->eState==PAGER_WRITER_LOCKED - ); - assert( assert_pager_state(pPager) ); - if( 0==pagerUseWal(pPager) ){ - rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK); - } - } - return rc; -} - -/* -** Sync the database file for the pager pPager. zSuper points to the name -** of a super-journal file that should be written into the individual -** journal file. zSuper may be NULL, which is interpreted as no -** super-journal (a single database transaction). -** -** This routine ensures that: -** -** * The database file change-counter is updated, -** * the journal is synced (unless the atomic-write optimization is used), -** * all dirty pages are written to the database file, -** * the database file is truncated (if required), and -** * the database file synced. -** -** The only thing that remains to commit the transaction is to finalize -** (delete, truncate or zero the first part of) the journal file (or -** delete the super-journal file if specified). -** -** Note that if zSuper==NULL, this does not overwrite a previous value -** passed to an sqlite3PagerCommitPhaseOne() call. -** -** If the final parameter - noSync - is true, then the database file itself -** is not synced. The caller must call sqlite3PagerSync() directly to -** sync the database file before calling CommitPhaseTwo() to delete the -** journal file in this case. -*/ -SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( - Pager *pPager, /* Pager object */ - const char *zSuper, /* If not NULL, the super-journal name */ - int noSync /* True to omit the xSync on the db file */ -){ - int rc = SQLITE_OK; /* Return code */ - - assert( pPager->eState==PAGER_WRITER_LOCKED - || pPager->eState==PAGER_WRITER_CACHEMOD - || pPager->eState==PAGER_WRITER_DBMOD - || pPager->eState==PAGER_ERROR - ); - assert( assert_pager_state(pPager) ); - - /* If a prior error occurred, report that error again. */ - if( NEVER(pPager->errCode) ) return pPager->errCode; - - /* Provide the ability to easily simulate an I/O error during testing */ - if( sqlite3FaultSim(400) ) return SQLITE_IOERR; - - PAGERTRACE(("DATABASE SYNC: File=%s zSuper=%s nSize=%d\n", - pPager->zFilename, zSuper, pPager->dbSize)); - - /* If no database changes have been made, return early. */ - if( pPager->eStatetempFile ); - assert( isOpen(pPager->fd) || pPager->tempFile ); - if( 0==pagerFlushOnCommit(pPager, 1) ){ - /* If this is an in-memory db, or no pages have been written to, or this - ** function has already been called, it is mostly a no-op. However, any - ** backup in progress needs to be restarted. */ - sqlite3BackupRestart(pPager->pBackup); - }else{ - PgHdr *pList; - if( pagerUseWal(pPager) ){ - PgHdr *pPageOne = 0; - pList = sqlite3PcacheDirtyList(pPager->pPCache); - if( pList==0 ){ - /* Must have at least one page for the WAL commit flag. - ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */ - rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0); - pList = pPageOne; - pList->pDirty = 0; - } - assert( rc==SQLITE_OK ); - if( ALWAYS(pList) ){ - rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1); - } - sqlite3PagerUnref(pPageOne); - if( rc==SQLITE_OK ){ - sqlite3PcacheCleanAll(pPager->pPCache); - } - }else{ - /* The bBatch boolean is true if the batch-atomic-write commit method - ** should be used. No rollback journal is created if batch-atomic-write - ** is enabled. - */ -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - sqlite3_file *fd = pPager->fd; - int bBatch = zSuper==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */ - && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC) - && !pPager->noSync - && sqlite3JournalIsInMemory(pPager->jfd); -#else -# define bBatch 0 -#endif - -#ifdef SQLITE_ENABLE_ATOMIC_WRITE - /* The following block updates the change-counter. Exactly how it - ** does this depends on whether or not the atomic-update optimization - ** was enabled at compile time, and if this transaction meets the - ** runtime criteria to use the operation: - ** - ** * The file-system supports the atomic-write property for - ** blocks of size page-size, and - ** * This commit is not part of a multi-file transaction, and - ** * Exactly one page has been modified and store in the journal file. - ** - ** If the optimization was not enabled at compile time, then the - ** pager_incr_changecounter() function is called to update the change - ** counter in 'indirect-mode'. If the optimization is compiled in but - ** is not applicable to this transaction, call sqlite3JournalCreate() - ** to make sure the journal file has actually been created, then call - ** pager_incr_changecounter() to update the change-counter in indirect - ** mode. - ** - ** Otherwise, if the optimization is both enabled and applicable, - ** then call pager_incr_changecounter() to update the change-counter - ** in 'direct' mode. In this case the journal file will never be - ** created for this transaction. - */ - if( bBatch==0 ){ - PgHdr *pPg; - assert( isOpen(pPager->jfd) - || pPager->journalMode==PAGER_JOURNALMODE_OFF - || pPager->journalMode==PAGER_JOURNALMODE_WAL - ); - if( !zSuper && isOpen(pPager->jfd) - && pPager->journalOff==jrnlBufferSize(pPager) - && pPager->dbSize>=pPager->dbOrigSize - && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty) - ){ - /* Update the db file change counter via the direct-write method. The - ** following call will modify the in-memory representation of page 1 - ** to include the updated change counter and then write page 1 - ** directly to the database file. Because of the atomic-write - ** property of the host file-system, this is safe. - */ - rc = pager_incr_changecounter(pPager, 1); - }else{ - rc = sqlite3JournalCreate(pPager->jfd); - if( rc==SQLITE_OK ){ - rc = pager_incr_changecounter(pPager, 0); - } - } - } -#else /* SQLITE_ENABLE_ATOMIC_WRITE */ -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - if( zSuper ){ - rc = sqlite3JournalCreate(pPager->jfd); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - assert( bBatch==0 ); - } -#endif - rc = pager_incr_changecounter(pPager, 0); -#endif /* !SQLITE_ENABLE_ATOMIC_WRITE */ - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - - /* Write the super-journal name into the journal file. If a - ** super-journal file name has already been written to the journal file, - ** or if zSuper is NULL (no super-journal), then this call is a no-op. - */ - rc = writeSuperJournal(pPager, zSuper); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - - /* Sync the journal file and write all dirty pages to the database. - ** If the atomic-update optimization is being used, this sync will not - ** create the journal file or perform any real IO. - ** - ** Because the change-counter page was just modified, unless the - ** atomic-update optimization is used it is almost certain that the - ** journal requires a sync here. However, in locking_mode=exclusive - ** on a system under memory pressure it is just possible that this is - ** not the case. In this case it is likely enough that the redundant - ** xSync() call will be changed to a no-op by the OS anyhow. - */ - rc = syncJournal(pPager, 0); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - - pList = sqlite3PcacheDirtyList(pPager->pPCache); -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - if( bBatch ){ - rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0); - if( rc==SQLITE_OK ){ - rc = pager_write_pagelist(pPager, pList); - if( rc==SQLITE_OK ){ - rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0); - } - if( rc!=SQLITE_OK ){ - sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0); - } - } - - if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){ - rc = sqlite3JournalCreate(pPager->jfd); - if( rc!=SQLITE_OK ){ - sqlite3OsClose(pPager->jfd); - goto commit_phase_one_exit; - } - bBatch = 0; - }else{ - sqlite3OsClose(pPager->jfd); - } - } -#endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ - - if( bBatch==0 ){ - rc = pager_write_pagelist(pPager, pList); - } - if( rc!=SQLITE_OK ){ - assert( rc!=SQLITE_IOERR_BLOCKED ); - goto commit_phase_one_exit; - } - sqlite3PcacheCleanAll(pPager->pPCache); - - /* If the file on disk is smaller than the database image, use - ** pager_truncate to grow the file here. This can happen if the database - ** image was extended as part of the current transaction and then the - ** last page in the db image moved to the free-list. In this case the - ** last page is never written out to disk, leaving the database file - ** undersized. Fix this now if it is the case. */ - if( pPager->dbSize>pPager->dbFileSize ){ - Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager)); - assert( pPager->eState==PAGER_WRITER_DBMOD ); - rc = pager_truncate(pPager, nNew); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - } - - /* Finally, sync the database file. */ - if( !noSync ){ - rc = sqlite3PagerSync(pPager, zSuper); - } - IOTRACE(("DBSYNC %p\n", pPager)) - } - } - -commit_phase_one_exit: - if( rc==SQLITE_OK && !pagerUseWal(pPager) ){ - pPager->eState = PAGER_WRITER_FINISHED; - } - return rc; -} - - -/* -** When this function is called, the database file has been completely -** updated to reflect the changes made by the current transaction and -** synced to disk. The journal file still exists in the file-system -** though, and if a failure occurs at this point it will eventually -** be used as a hot-journal and the current transaction rolled back. -** -** This function finalizes the journal file, either by deleting, -** truncating or partially zeroing it, so that it cannot be used -** for hot-journal rollback. Once this is done the transaction is -** irrevocably committed. -** -** If an error occurs, an IO error code is returned and the pager -** moves into the error state. Otherwise, SQLITE_OK is returned. -*/ -SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){ - int rc = SQLITE_OK; /* Return code */ - - /* This routine should not be called if a prior error has occurred. - ** But if (due to a coding error elsewhere in the system) it does get - ** called, just return the same error code without doing anything. */ - if( NEVER(pPager->errCode) ) return pPager->errCode; - pPager->iDataVersion++; - - assert( pPager->eState==PAGER_WRITER_LOCKED - || pPager->eState==PAGER_WRITER_FINISHED - || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD) - ); - assert( assert_pager_state(pPager) ); - - /* An optimization. If the database was not actually modified during - ** this transaction, the pager is running in exclusive-mode and is - ** using persistent journals, then this function is a no-op. - ** - ** The start of the journal file currently contains a single journal - ** header with the nRec field set to 0. If such a journal is used as - ** a hot-journal during hot-journal rollback, 0 changes will be made - ** to the database file. So there is no need to zero the journal - ** header. Since the pager is in exclusive mode, there is no need - ** to drop any locks either. - */ - if( pPager->eState==PAGER_WRITER_LOCKED - && pPager->exclusiveMode - && pPager->journalMode==PAGER_JOURNALMODE_PERSIST - ){ - assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff ); - pPager->eState = PAGER_READER; - return SQLITE_OK; - } - - PAGERTRACE(("COMMIT %d\n", PAGERID(pPager))); - rc = pager_end_transaction(pPager, pPager->setSuper, 1); - return pager_error(pPager, rc); -} - -/* -** If a write transaction is open, then all changes made within the -** transaction are reverted and the current write-transaction is closed. -** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR -** state if an error occurs. -** -** If the pager is already in PAGER_ERROR state when this function is called, -** it returns Pager.errCode immediately. No work is performed in this case. -** -** Otherwise, in rollback mode, this function performs two functions: -** -** 1) It rolls back the journal file, restoring all database file and -** in-memory cache pages to the state they were in when the transaction -** was opened, and -** -** 2) It finalizes the journal file, so that it is not used for hot -** rollback at any point in the future. -** -** Finalization of the journal file (task 2) is only performed if the -** rollback is successful. -** -** In WAL mode, all cache-entries containing data modified within the -** current transaction are either expelled from the cache or reverted to -** their pre-transaction state by re-reading data from the database or -** WAL files. The WAL transaction is then closed. -*/ -SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){ - int rc = SQLITE_OK; /* Return code */ - PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager))); - - /* PagerRollback() is a no-op if called in READER or OPEN state. If - ** the pager is already in the ERROR state, the rollback is not - ** attempted here. Instead, the error code is returned to the caller. - */ - assert( assert_pager_state(pPager) ); - if( pPager->eState==PAGER_ERROR ) return pPager->errCode; - if( pPager->eState<=PAGER_READER ) return SQLITE_OK; - - if( pagerUseWal(pPager) ){ - int rc2; - rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1); - rc2 = pager_end_transaction(pPager, pPager->setSuper, 0); - if( rc==SQLITE_OK ) rc = rc2; - }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){ - int eState = pPager->eState; - rc = pager_end_transaction(pPager, 0, 0); - if( !MEMDB && eState>PAGER_WRITER_LOCKED ){ - /* This can happen using journal_mode=off. Move the pager to the error - ** state to indicate that the contents of the cache may not be trusted. - ** Any active readers will get SQLITE_ABORT. - */ - pPager->errCode = SQLITE_ABORT; - pPager->eState = PAGER_ERROR; - setGetterMethod(pPager); - return rc; - } - }else{ - rc = pager_playback(pPager, 0); - } - - assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK ); - assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT - || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR - || rc==SQLITE_CANTOPEN - ); - - /* If an error occurs during a ROLLBACK, we can no longer trust the pager - ** cache. So call pager_error() on the way out to make any error persistent. - */ - return pager_error(pPager, rc); -} - -/* -** Return TRUE if the database file is opened read-only. Return FALSE -** if the database is (in theory) writable. -*/ -SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){ - return pPager->readOnly; -} - -#ifdef SQLITE_DEBUG -/* -** Return the sum of the reference counts for all pages held by pPager. -*/ -SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){ - return sqlite3PcacheRefCount(pPager->pPCache); -} -#endif - -/* -** Return the approximate number of bytes of memory currently -** used by the pager and its associated cache. -*/ -SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){ - int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr) - + 5*sizeof(void*); - return perPageSize*sqlite3PcachePagecount(pPager->pPCache) - + sqlite3MallocSize(pPager) - + pPager->pageSize; -} - -/* -** Return the number of references to the specified page. -*/ -SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){ - return sqlite3PcachePageRefcount(pPage); -} - -#ifdef SQLITE_TEST -/* -** This routine is used for testing and analysis only. -*/ -SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){ - static int a[11]; - a[0] = sqlite3PcacheRefCount(pPager->pPCache); - a[1] = sqlite3PcachePagecount(pPager->pPCache); - a[2] = sqlite3PcacheGetCachesize(pPager->pPCache); - a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize; - a[4] = pPager->eState; - a[5] = pPager->errCode; - a[6] = pPager->aStat[PAGER_STAT_HIT]; - a[7] = pPager->aStat[PAGER_STAT_MISS]; - a[8] = 0; /* Used to be pPager->nOvfl */ - a[9] = pPager->nRead; - a[10] = pPager->aStat[PAGER_STAT_WRITE]; - return a; -} -#endif - -/* -** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE, -** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation -** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because -** it was added later. -** -** Before returning, *pnVal is incremented by the -** current cache hit or miss count, according to the value of eStat. If the -** reset parameter is non-zero, the cache hit or miss count is zeroed before -** returning. -*/ -SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){ - - assert( eStat==SQLITE_DBSTATUS_CACHE_HIT - || eStat==SQLITE_DBSTATUS_CACHE_MISS - || eStat==SQLITE_DBSTATUS_CACHE_WRITE - || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1 - ); - - assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS ); - assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE ); - assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 - && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 ); - - eStat -= SQLITE_DBSTATUS_CACHE_HIT; - *pnVal += pPager->aStat[eStat]; - if( reset ){ - pPager->aStat[eStat] = 0; - } -} - -/* -** Return true if this is an in-memory or temp-file backed pager. -*/ -SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){ - return pPager->tempFile; -} - -/* -** Check that there are at least nSavepoint savepoints open. If there are -** currently less than nSavepoints open, then open one or more savepoints -** to make up the difference. If the number of savepoints is already -** equal to nSavepoint, then this function is a no-op. -** -** If a memory allocation fails, SQLITE_NOMEM is returned. If an error -** occurs while opening the sub-journal file, then an IO error code is -** returned. Otherwise, SQLITE_OK. -*/ -static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){ - int rc = SQLITE_OK; /* Return code */ - int nCurrent = pPager->nSavepoint; /* Current number of savepoints */ - int ii; /* Iterator variable */ - PagerSavepoint *aNew; /* New Pager.aSavepoint array */ - - assert( pPager->eState>=PAGER_WRITER_LOCKED ); - assert( assert_pager_state(pPager) ); - assert( nSavepoint>nCurrent && pPager->useJournal ); - - /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM - ** if the allocation fails. Otherwise, zero the new portion in case a - ** malloc failure occurs while populating it in the for(...) loop below. - */ - aNew = (PagerSavepoint *)sqlite3Realloc( - pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint - ); - if( !aNew ){ - return SQLITE_NOMEM_BKPT; - } - memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint)); - pPager->aSavepoint = aNew; - - /* Populate the PagerSavepoint structures just allocated. */ - for(ii=nCurrent; iidbSize; - if( isOpen(pPager->jfd) && pPager->journalOff>0 ){ - aNew[ii].iOffset = pPager->journalOff; - }else{ - aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager); - } - aNew[ii].iSubRec = pPager->nSubRec; - aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize); - if( !aNew[ii].pInSavepoint ){ - return SQLITE_NOMEM_BKPT; - } - if( pagerUseWal(pPager) ){ - sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData); - } - pPager->nSavepoint = ii+1; - } - assert( pPager->nSavepoint==nSavepoint ); - assertTruncateConstraint(pPager); - return rc; -} -SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){ - assert( pPager->eState>=PAGER_WRITER_LOCKED ); - assert( assert_pager_state(pPager) ); - - if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){ - return pagerOpenSavepoint(pPager, nSavepoint); - }else{ - return SQLITE_OK; - } -} - - -/* -** This function is called to rollback or release (commit) a savepoint. -** The savepoint to release or rollback need not be the most recently -** created savepoint. -** -** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE. -** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with -** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes -** that have occurred since the specified savepoint was created. -** -** The savepoint to rollback or release is identified by parameter -** iSavepoint. A value of 0 means to operate on the outermost savepoint -** (the first created). A value of (Pager.nSavepoint-1) means operate -** on the most recently created savepoint. If iSavepoint is greater than -** (Pager.nSavepoint-1), then this function is a no-op. -** -** If a negative value is passed to this function, then the current -** transaction is rolled back. This is different to calling -** sqlite3PagerRollback() because this function does not terminate -** the transaction or unlock the database, it just restores the -** contents of the database to its original state. -** -** In any case, all savepoints with an index greater than iSavepoint -** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE), -** then savepoint iSavepoint is also destroyed. -** -** This function may return SQLITE_NOMEM if a memory allocation fails, -** or an IO error code if an IO error occurs while rolling back a -** savepoint. If no errors occur, SQLITE_OK is returned. -*/ -SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){ - int rc = pPager->errCode; - -#ifdef SQLITE_ENABLE_ZIPVFS - if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK; -#endif - - assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); - assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK ); - - if( rc==SQLITE_OK && iSavepointnSavepoint ){ - int ii; /* Iterator variable */ - int nNew; /* Number of remaining savepoints after this op. */ - - /* Figure out how many savepoints will still be active after this - ** operation. Store this value in nNew. Then free resources associated - ** with any savepoints that are destroyed by this operation. - */ - nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1); - for(ii=nNew; iinSavepoint; ii++){ - sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); - } - pPager->nSavepoint = nNew; - - /* If this is a release of the outermost savepoint, truncate - ** the sub-journal to zero bytes in size. */ - if( op==SAVEPOINT_RELEASE ){ - if( nNew==0 && isOpen(pPager->sjfd) ){ - /* Only truncate if it is an in-memory sub-journal. */ - if( sqlite3JournalIsInMemory(pPager->sjfd) ){ - rc = sqlite3OsTruncate(pPager->sjfd, 0); - assert( rc==SQLITE_OK ); - } - pPager->nSubRec = 0; - } - } - /* Else this is a rollback operation, playback the specified savepoint. - ** If this is a temp-file, it is possible that the journal file has - ** not yet been opened. In this case there have been no changes to - ** the database file, so the playback operation can be skipped. - */ - else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){ - PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; - rc = pagerPlaybackSavepoint(pPager, pSavepoint); - assert(rc!=SQLITE_DONE); - } - -#ifdef SQLITE_ENABLE_ZIPVFS - /* If the cache has been modified but the savepoint cannot be rolled - ** back journal_mode=off, put the pager in the error state. This way, - ** if the VFS used by this pager includes ZipVFS, the entire transaction - ** can be rolled back at the ZipVFS level. */ - else if( - pPager->journalMode==PAGER_JOURNALMODE_OFF - && pPager->eState>=PAGER_WRITER_CACHEMOD - ){ - pPager->errCode = SQLITE_ABORT; - pPager->eState = PAGER_ERROR; - setGetterMethod(pPager); - } -#endif - } - - return rc; -} - -/* -** Return the full pathname of the database file. -** -** Except, if the pager is in-memory only, then return an empty string if -** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when -** used to report the filename to the user, for compatibility with legacy -** behavior. But when the Btree needs to know the filename for matching to -** shared cache, it uses nullIfMemDb==0 so that in-memory databases can -** participate in shared-cache. -** -** The return value to this routine is always safe to use with -** sqlite3_uri_parameter() and sqlite3_filename_database() and friends. -*/ -SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){ - static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; - return (nullIfMemDb && pPager->memDb) ? &zFake[4] : pPager->zFilename; -} - -/* -** Return the VFS structure for the pager. -*/ -SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){ - return pPager->pVfs; -} - -/* -** Return the file handle for the database file associated -** with the pager. This might return NULL if the file has -** not yet been opened. -*/ -SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){ - return pPager->fd; -} - -/* -** Return the file handle for the journal file (if it exists). -** This will be either the rollback journal or the WAL file. -*/ -SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){ -#if SQLITE_OMIT_WAL - return pPager->jfd; -#else - return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd; -#endif -} - -/* -** Return the full pathname of the journal file. -*/ -SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){ - return pPager->zJournal; -} - -#ifndef SQLITE_OMIT_AUTOVACUUM -/* -** Move the page pPg to location pgno in the file. -** -** There must be no references to the page previously located at -** pgno (which we call pPgOld) though that page is allowed to be -** in cache. If the page previously located at pgno is not already -** in the rollback journal, it is not put there by by this routine. -** -** References to the page pPg remain valid. Updating any -** meta-data associated with pPg (i.e. data stored in the nExtra bytes -** allocated along with the page) is the responsibility of the caller. -** -** A transaction must be active when this routine is called. It used to be -** required that a statement transaction was not active, but this restriction -** has been removed (CREATE INDEX needs to move a page when a statement -** transaction is active). -** -** If the fourth argument, isCommit, is non-zero, then this page is being -** moved as part of a database reorganization just before the transaction -** is being committed. In this case, it is guaranteed that the database page -** pPg refers to will not be written to again within this transaction. -** -** This function may return SQLITE_NOMEM or an IO error code if an error -** occurs. Otherwise, it returns SQLITE_OK. -*/ -SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){ - PgHdr *pPgOld; /* The page being overwritten. */ - Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */ - int rc; /* Return code */ - Pgno origPgno; /* The original page number */ - - assert( pPg->nRef>0 ); - assert( pPager->eState==PAGER_WRITER_CACHEMOD - || pPager->eState==PAGER_WRITER_DBMOD - ); - assert( assert_pager_state(pPager) ); - - /* In order to be able to rollback, an in-memory database must journal - ** the page we are moving from. - */ - assert( pPager->tempFile || !MEMDB ); - if( pPager->tempFile ){ - rc = sqlite3PagerWrite(pPg); - if( rc ) return rc; - } - - /* If the page being moved is dirty and has not been saved by the latest - ** savepoint, then save the current contents of the page into the - ** sub-journal now. This is required to handle the following scenario: - ** - ** BEGIN; - ** - ** SAVEPOINT one; - ** - ** ROLLBACK TO one; - ** - ** If page X were not written to the sub-journal here, it would not - ** be possible to restore its contents when the "ROLLBACK TO one" - ** statement were is processed. - ** - ** subjournalPage() may need to allocate space to store pPg->pgno into - ** one or more savepoint bitvecs. This is the reason this function - ** may return SQLITE_NOMEM. - */ - if( (pPg->flags & PGHDR_DIRTY)!=0 - && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg)) - ){ - return rc; - } - - PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", - PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno)); - IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno)) - - /* If the journal needs to be sync()ed before page pPg->pgno can - ** be written to, store pPg->pgno in local variable needSyncPgno. - ** - ** If the isCommit flag is set, there is no need to remember that - ** the journal needs to be sync()ed before database page pPg->pgno - ** can be written to. The caller has already promised not to write to it. - */ - if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){ - needSyncPgno = pPg->pgno; - assert( pPager->journalMode==PAGER_JOURNALMODE_OFF || - pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize ); - assert( pPg->flags&PGHDR_DIRTY ); - } - - /* If the cache contains a page with page-number pgno, remove it - ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for - ** page pgno before the 'move' operation, it needs to be retained - ** for the page moved there. - */ - pPg->flags &= ~PGHDR_NEED_SYNC; - pPgOld = sqlite3PagerLookup(pPager, pgno); - assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB ); - if( pPgOld ){ - if( pPgOld->nRef>1 ){ - sqlite3PagerUnrefNotNull(pPgOld); - return SQLITE_CORRUPT_BKPT; - } - pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC); - if( pPager->tempFile ){ - /* Do not discard pages from an in-memory database since we might - ** need to rollback later. Just move the page out of the way. */ - sqlite3PcacheMove(pPgOld, pPager->dbSize+1); - }else{ - sqlite3PcacheDrop(pPgOld); - } - } - - origPgno = pPg->pgno; - sqlite3PcacheMove(pPg, pgno); - sqlite3PcacheMakeDirty(pPg); - - /* For an in-memory database, make sure the original page continues - ** to exist, in case the transaction needs to roll back. Use pPgOld - ** as the original page since it has already been allocated. - */ - if( pPager->tempFile && pPgOld ){ - sqlite3PcacheMove(pPgOld, origPgno); - sqlite3PagerUnrefNotNull(pPgOld); - } - - if( needSyncPgno ){ - /* If needSyncPgno is non-zero, then the journal file needs to be - ** sync()ed before any data is written to database file page needSyncPgno. - ** Currently, no such page exists in the page-cache and the - ** "is journaled" bitvec flag has been set. This needs to be remedied by - ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC - ** flag. - ** - ** If the attempt to load the page into the page-cache fails, (due - ** to a malloc() or IO failure), clear the bit in the pInJournal[] - ** array. Otherwise, if the page is loaded and written again in - ** this transaction, it may be written to the database file before - ** it is synced into the journal file. This way, it may end up in - ** the journal file twice, but that is not a problem. - */ - PgHdr *pPgHdr; - rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0); - if( rc!=SQLITE_OK ){ - if( needSyncPgno<=pPager->dbOrigSize ){ - assert( pPager->pTmpSpace!=0 ); - sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace); - } - return rc; - } - pPgHdr->flags |= PGHDR_NEED_SYNC; - sqlite3PcacheMakeDirty(pPgHdr); - sqlite3PagerUnrefNotNull(pPgHdr); - } - - return SQLITE_OK; -} -#endif - -/* -** The page handle passed as the first argument refers to a dirty page -** with a page number other than iNew. This function changes the page's -** page number to iNew and sets the value of the PgHdr.flags field to -** the value passed as the third parameter. -*/ -SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){ - assert( pPg->pgno!=iNew ); - pPg->flags = flags; - sqlite3PcacheMove(pPg, iNew); -} - -/* -** Return a pointer to the data for the specified page. -*/ -SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){ - assert( pPg->nRef>0 || pPg->pPager->memDb ); - return pPg->pData; -} - -/* -** Return a pointer to the Pager.nExtra bytes of "extra" space -** allocated along with the specified page. -*/ -SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){ - return pPg->pExtra; -} - -/* -** Get/set the locking-mode for this pager. Parameter eMode must be one -** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or -** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then -** the locking-mode is set to the value specified. -** -** The returned value is either PAGER_LOCKINGMODE_NORMAL or -** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated) -** locking-mode. -*/ -SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){ - assert( eMode==PAGER_LOCKINGMODE_QUERY - || eMode==PAGER_LOCKINGMODE_NORMAL - || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); - assert( PAGER_LOCKINGMODE_QUERY<0 ); - assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 ); - assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) ); - if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){ - pPager->exclusiveMode = (u8)eMode; - } - return (int)pPager->exclusiveMode; -} - -/* -** Set the journal-mode for this pager. Parameter eMode must be one of: -** -** PAGER_JOURNALMODE_DELETE -** PAGER_JOURNALMODE_TRUNCATE -** PAGER_JOURNALMODE_PERSIST -** PAGER_JOURNALMODE_OFF -** PAGER_JOURNALMODE_MEMORY -** PAGER_JOURNALMODE_WAL -** -** The journalmode is set to the value specified if the change is allowed. -** The change may be disallowed for the following reasons: -** -** * An in-memory database can only have its journal_mode set to _OFF -** or _MEMORY. -** -** * Temporary databases cannot have _WAL journalmode. -** -** The returned indicate the current (possibly updated) journal-mode. -*/ -SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){ - u8 eOld = pPager->journalMode; /* Prior journalmode */ - - /* The eMode parameter is always valid */ - assert( eMode==PAGER_JOURNALMODE_DELETE - || eMode==PAGER_JOURNALMODE_TRUNCATE - || eMode==PAGER_JOURNALMODE_PERSIST - || eMode==PAGER_JOURNALMODE_OFF - || eMode==PAGER_JOURNALMODE_WAL - || eMode==PAGER_JOURNALMODE_MEMORY ); - - /* This routine is only called from the OP_JournalMode opcode, and - ** the logic there will never allow a temporary file to be changed - ** to WAL mode. - */ - assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL ); - - /* Do allow the journalmode of an in-memory database to be set to - ** anything other than MEMORY or OFF - */ - if( MEMDB ){ - assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF ); - if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){ - eMode = eOld; - } - } - - if( eMode!=eOld ){ - - /* Change the journal mode. */ - assert( pPager->eState!=PAGER_ERROR ); - pPager->journalMode = (u8)eMode; - - /* When transistioning from TRUNCATE or PERSIST to any other journal - ** mode except WAL, unless the pager is in locking_mode=exclusive mode, - ** delete the journal file. - */ - assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 ); - assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 ); - assert( (PAGER_JOURNALMODE_DELETE & 5)==0 ); - assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 ); - assert( (PAGER_JOURNALMODE_OFF & 5)==0 ); - assert( (PAGER_JOURNALMODE_WAL & 5)==5 ); - - assert( isOpen(pPager->fd) || pPager->exclusiveMode ); - if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){ - - /* In this case we would like to delete the journal file. If it is - ** not possible, then that is not a problem. Deleting the journal file - ** here is an optimization only. - ** - ** Before deleting the journal file, obtain a RESERVED lock on the - ** database file. This ensures that the journal file is not deleted - ** while it is in use by some other client. - */ - sqlite3OsClose(pPager->jfd); - if( pPager->eLock>=RESERVED_LOCK ){ - sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); - }else{ - int rc = SQLITE_OK; - int state = pPager->eState; - assert( state==PAGER_OPEN || state==PAGER_READER ); - if( state==PAGER_OPEN ){ - rc = sqlite3PagerSharedLock(pPager); - } - if( pPager->eState==PAGER_READER ){ - assert( rc==SQLITE_OK ); - rc = pagerLockDb(pPager, RESERVED_LOCK); - } - if( rc==SQLITE_OK ){ - sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0); - } - if( rc==SQLITE_OK && state==PAGER_READER ){ - pagerUnlockDb(pPager, SHARED_LOCK); - }else if( state==PAGER_OPEN ){ - pager_unlock(pPager); - } - assert( state==pPager->eState ); - } - }else if( eMode==PAGER_JOURNALMODE_OFF ){ - sqlite3OsClose(pPager->jfd); - } - } - - /* Return the new journal mode */ - return (int)pPager->journalMode; -} - -/* -** Return the current journal mode. -*/ -SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){ - return (int)pPager->journalMode; -} - -/* -** Return TRUE if the pager is in a state where it is OK to change the -** journalmode. Journalmode changes can only happen when the database -** is unmodified. -*/ -SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){ - assert( assert_pager_state(pPager) ); - if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0; - if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0; - return 1; -} - -/* -** Get/set the size-limit used for persistent journal files. -** -** Setting the size limit to -1 means no limit is enforced. -** An attempt to set a limit smaller than -1 is a no-op. -*/ -SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){ - if( iLimit>=-1 ){ - pPager->journalSizeLimit = iLimit; - sqlite3WalLimit(pPager->pWal, iLimit); - } - return pPager->journalSizeLimit; -} - -/* -** Return a pointer to the pPager->pBackup variable. The backup module -** in backup.c maintains the content of this variable. This module -** uses it opaquely as an argument to sqlite3BackupRestart() and -** sqlite3BackupUpdate() only. -*/ -SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){ - return &pPager->pBackup; -} - -#ifndef SQLITE_OMIT_VACUUM -/* -** Unless this is an in-memory or temporary database, clear the pager cache. -*/ -SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){ - assert( MEMDB==0 || pPager->tempFile ); - if( pPager->tempFile==0 ) pager_reset(pPager); -} -#endif - - -#ifndef SQLITE_OMIT_WAL -/* -** This function is called when the user invokes "PRAGMA wal_checkpoint", -** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint() -** or wal_blocking_checkpoint() API functions. -** -** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. -*/ -SQLITE_PRIVATE int sqlite3PagerCheckpoint( - Pager *pPager, /* Checkpoint on this pager */ - sqlite3 *db, /* Db handle used to check for interrupts */ - int eMode, /* Type of checkpoint */ - int *pnLog, /* OUT: Final number of frames in log */ - int *pnCkpt /* OUT: Final number of checkpointed frames */ -){ - int rc = SQLITE_OK; - if( pPager->pWal ){ - rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode, - (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler), - pPager->pBusyHandlerArg, - pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, - pnLog, pnCkpt - ); - } - return rc; -} - -SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){ - return sqlite3WalCallback(pPager->pWal); -} - -/* -** Return true if the underlying VFS for the given pager supports the -** primitives necessary for write-ahead logging. -*/ -SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){ - const sqlite3_io_methods *pMethods = pPager->fd->pMethods; - if( pPager->noLock ) return 0; - return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap); -} - -/* -** Attempt to take an exclusive lock on the database file. If a PENDING lock -** is obtained instead, immediately release it. -*/ -static int pagerExclusiveLock(Pager *pPager){ - int rc; /* Return code */ - - assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); - rc = pagerLockDb(pPager, EXCLUSIVE_LOCK); - if( rc!=SQLITE_OK ){ - /* If the attempt to grab the exclusive lock failed, release the - ** pending lock that may have been obtained instead. */ - pagerUnlockDb(pPager, SHARED_LOCK); - } - - return rc; -} - -/* -** Call sqlite3WalOpen() to open the WAL handle. If the pager is in -** exclusive-locking mode when this function is called, take an EXCLUSIVE -** lock on the database file and use heap-memory to store the wal-index -** in. Otherwise, use the normal shared-memory. -*/ -static int pagerOpenWal(Pager *pPager){ - int rc = SQLITE_OK; - - assert( pPager->pWal==0 && pPager->tempFile==0 ); - assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK ); - - /* If the pager is already in exclusive-mode, the WAL module will use - ** heap-memory for the wal-index instead of the VFS shared-memory - ** implementation. Take the exclusive lock now, before opening the WAL - ** file, to make sure this is safe. - */ - if( pPager->exclusiveMode ){ - rc = pagerExclusiveLock(pPager); - } - - /* Open the connection to the log file. If this operation fails, - ** (e.g. due to malloc() failure), return an error code. - */ - if( rc==SQLITE_OK ){ - rc = sqlite3WalOpen(pPager->pVfs, - pPager->fd, pPager->zWal, pPager->exclusiveMode, - pPager->journalSizeLimit, &pPager->pWal - ); - } - pagerFixMaplimit(pPager); - - return rc; -} - - -/* -** The caller must be holding a SHARED lock on the database file to call -** this function. -** -** If the pager passed as the first argument is open on a real database -** file (not a temp file or an in-memory database), and the WAL file -** is not already open, make an attempt to open it now. If successful, -** return SQLITE_OK. If an error occurs or the VFS used by the pager does -** not support the xShmXXX() methods, return an error code. *pbOpen is -** not modified in either case. -** -** If the pager is open on a temp-file (or in-memory database), or if -** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK -** without doing anything. -*/ -SQLITE_PRIVATE int sqlite3PagerOpenWal( - Pager *pPager, /* Pager object */ - int *pbOpen /* OUT: Set to true if call is a no-op */ -){ - int rc = SQLITE_OK; /* Return code */ - - assert( assert_pager_state(pPager) ); - assert( pPager->eState==PAGER_OPEN || pbOpen ); - assert( pPager->eState==PAGER_READER || !pbOpen ); - assert( pbOpen==0 || *pbOpen==0 ); - assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) ); - - if( !pPager->tempFile && !pPager->pWal ){ - if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN; - - /* Close any rollback journal previously open */ - sqlite3OsClose(pPager->jfd); - - rc = pagerOpenWal(pPager); - if( rc==SQLITE_OK ){ - pPager->journalMode = PAGER_JOURNALMODE_WAL; - pPager->eState = PAGER_OPEN; - } - }else{ - *pbOpen = 1; - } - - return rc; -} - -/* -** This function is called to close the connection to the log file prior -** to switching from WAL to rollback mode. -** -** Before closing the log file, this function attempts to take an -** EXCLUSIVE lock on the database file. If this cannot be obtained, an -** error (SQLITE_BUSY) is returned and the log connection is not closed. -** If successful, the EXCLUSIVE lock is not released before returning. -*/ -SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){ - int rc = SQLITE_OK; - - assert( pPager->journalMode==PAGER_JOURNALMODE_WAL ); - - /* If the log file is not already open, but does exist in the file-system, - ** it may need to be checkpointed before the connection can switch to - ** rollback mode. Open it now so this can happen. - */ - if( !pPager->pWal ){ - int logexists = 0; - rc = pagerLockDb(pPager, SHARED_LOCK); - if( rc==SQLITE_OK ){ - rc = sqlite3OsAccess( - pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists - ); - } - if( rc==SQLITE_OK && logexists ){ - rc = pagerOpenWal(pPager); - } - } - - /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on - ** the database file, the log and log-summary files will be deleted. - */ - if( rc==SQLITE_OK && pPager->pWal ){ - rc = pagerExclusiveLock(pPager); - if( rc==SQLITE_OK ){ - rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, - pPager->pageSize, (u8*)pPager->pTmpSpace); - pPager->pWal = 0; - pagerFixMaplimit(pPager); - if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK); - } - } - return rc; -} - -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT -/* -** If pager pPager is a wal-mode database not in exclusive locking mode, -** invoke the sqlite3WalWriteLock() function on the associated Wal object -** with the same db and bLock parameters as were passed to this function. -** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise. -*/ -SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){ - int rc = SQLITE_OK; - if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){ - rc = sqlite3WalWriteLock(pPager->pWal, bLock); - } - return rc; -} - -/* -** Set the database handle used by the wal layer to determine if -** blocking locks are required. -*/ -SQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){ - if( pagerUseWal(pPager) ){ - sqlite3WalDb(pPager->pWal, db); - } -} -#endif - -#ifdef SQLITE_ENABLE_SNAPSHOT -/* -** If this is a WAL database, obtain a snapshot handle for the snapshot -** currently open. Otherwise, return an error. -*/ -SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){ - int rc = SQLITE_ERROR; - if( pPager->pWal ){ - rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot); - } - return rc; -} - -/* -** If this is a WAL database, store a pointer to pSnapshot. Next time a -** read transaction is opened, attempt to read from the snapshot it -** identifies. If this is not a WAL database, return an error. -*/ -SQLITE_PRIVATE int sqlite3PagerSnapshotOpen( - Pager *pPager, - sqlite3_snapshot *pSnapshot -){ - int rc = SQLITE_OK; - if( pPager->pWal ){ - sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot); - }else{ - rc = SQLITE_ERROR; - } - return rc; -} - -/* -** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this -** is not a WAL database, return an error. -*/ -SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){ - int rc; - if( pPager->pWal ){ - rc = sqlite3WalSnapshotRecover(pPager->pWal); - }else{ - rc = SQLITE_ERROR; - } - return rc; -} - -/* -** The caller currently has a read transaction open on the database. -** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise, -** this function takes a SHARED lock on the CHECKPOINTER slot and then -** checks if the snapshot passed as the second argument is still -** available. If so, SQLITE_OK is returned. -** -** If the snapshot is not available, SQLITE_ERROR is returned. Or, if -** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error -** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER -** lock is released before returning. -*/ -SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){ - int rc; - if( pPager->pWal ){ - rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot); - }else{ - rc = SQLITE_ERROR; - } - return rc; -} - -/* -** Release a lock obtained by an earlier successful call to -** sqlite3PagerSnapshotCheck(). -*/ -SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){ - assert( pPager->pWal ); - sqlite3WalSnapshotUnlock(pPager->pWal); -} - -#endif /* SQLITE_ENABLE_SNAPSHOT */ -#endif /* !SQLITE_OMIT_WAL */ - -#ifdef SQLITE_ENABLE_ZIPVFS -/* -** A read-lock must be held on the pager when this function is called. If -** the pager is in WAL mode and the WAL file currently contains one or more -** frames, return the size in bytes of the page images stored within the -** WAL frames. Otherwise, if this is not a WAL database or the WAL file -** is empty, return 0. -*/ -SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){ - assert( pPager->eState>=PAGER_READER ); - return sqlite3WalFramesize(pPager->pWal); -} -#endif - -#endif /* SQLITE_OMIT_DISKIO */ - -/************** End of pager.c ***********************************************/ -/************** Begin file wal.c *********************************************/ -/* -** 2010 February 1 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains the implementation of a write-ahead log (WAL) used in -** "journal_mode=WAL" mode. -** -** WRITE-AHEAD LOG (WAL) FILE FORMAT -** -** A WAL file consists of a header followed by zero or more "frames". -** Each frame records the revised content of a single page from the -** database file. All changes to the database are recorded by writing -** frames into the WAL. Transactions commit when a frame is written that -** contains a commit marker. A single WAL can and usually does record -** multiple transactions. Periodically, the content of the WAL is -** transferred back into the database file in an operation called a -** "checkpoint". -** -** A single WAL file can be used multiple times. In other words, the -** WAL can fill up with frames and then be checkpointed and then new -** frames can overwrite the old ones. A WAL always grows from beginning -** toward the end. Checksums and counters attached to each frame are -** used to determine which frames within the WAL are valid and which -** are leftovers from prior checkpoints. -** -** The WAL header is 32 bytes in size and consists of the following eight -** big-endian 32-bit unsigned integer values: -** -** 0: Magic number. 0x377f0682 or 0x377f0683 -** 4: File format version. Currently 3007000 -** 8: Database page size. Example: 1024 -** 12: Checkpoint sequence number -** 16: Salt-1, random integer incremented with each checkpoint -** 20: Salt-2, a different random integer changing with each ckpt -** 24: Checksum-1 (first part of checksum for first 24 bytes of header). -** 28: Checksum-2 (second part of checksum for first 24 bytes of header). -** -** Immediately following the wal-header are zero or more frames. Each -** frame consists of a 24-byte frame-header followed by a bytes -** of page data. The frame-header is six big-endian 32-bit unsigned -** integer values, as follows: -** -** 0: Page number. -** 4: For commit records, the size of the database image in pages -** after the commit. For all other records, zero. -** 8: Salt-1 (copied from the header) -** 12: Salt-2 (copied from the header) -** 16: Checksum-1. -** 20: Checksum-2. -** -** A frame is considered valid if and only if the following conditions are -** true: -** -** (1) The salt-1 and salt-2 values in the frame-header match -** salt values in the wal-header -** -** (2) The checksum values in the final 8 bytes of the frame-header -** exactly match the checksum computed consecutively on the -** WAL header and the first 8 bytes and the content of all frames -** up to and including the current frame. -** -** The checksum is computed using 32-bit big-endian integers if the -** magic number in the first 4 bytes of the WAL is 0x377f0683 and it -** is computed using little-endian if the magic number is 0x377f0682. -** The checksum values are always stored in the frame header in a -** big-endian format regardless of which byte order is used to compute -** the checksum. The checksum is computed by interpreting the input as -** an even number of unsigned 32-bit integers: x[0] through x[N]. The -** algorithm used for the checksum is as follows: -** -** for i from 0 to n-1 step 2: -** s0 += x[i] + s1; -** s1 += x[i+1] + s0; -** endfor -** -** Note that s0 and s1 are both weighted checksums using fibonacci weights -** in reverse order (the largest fibonacci weight occurs on the first element -** of the sequence being summed.) The s1 value spans all 32-bit -** terms of the sequence whereas s0 omits the final term. -** -** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the -** WAL is transferred into the database, then the database is VFS.xSync-ed. -** The VFS.xSync operations serve as write barriers - all writes launched -** before the xSync must complete before any write that launches after the -** xSync begins. -** -** After each checkpoint, the salt-1 value is incremented and the salt-2 -** value is randomized. This prevents old and new frames in the WAL from -** being considered valid at the same time and being checkpointing together -** following a crash. -** -** READER ALGORITHM -** -** To read a page from the database (call it page number P), a reader -** first checks the WAL to see if it contains page P. If so, then the -** last valid instance of page P that is a followed by a commit frame -** or is a commit frame itself becomes the value read. If the WAL -** contains no copies of page P that are valid and which are a commit -** frame or are followed by a commit frame, then page P is read from -** the database file. -** -** To start a read transaction, the reader records the index of the last -** valid frame in the WAL. The reader uses this recorded "mxFrame" value -** for all subsequent read operations. New transactions can be appended -** to the WAL, but as long as the reader uses its original mxFrame value -** and ignores the newly appended content, it will see a consistent snapshot -** of the database from a single point in time. This technique allows -** multiple concurrent readers to view different versions of the database -** content simultaneously. -** -** The reader algorithm in the previous paragraphs works correctly, but -** because frames for page P can appear anywhere within the WAL, the -** reader has to scan the entire WAL looking for page P frames. If the -** WAL is large (multiple megabytes is typical) that scan can be slow, -** and read performance suffers. To overcome this problem, a separate -** data structure called the wal-index is maintained to expedite the -** search for frames of a particular page. -** -** WAL-INDEX FORMAT -** -** Conceptually, the wal-index is shared memory, though VFS implementations -** might choose to implement the wal-index using a mmapped file. Because -** the wal-index is shared memory, SQLite does not support journal_mode=WAL -** on a network filesystem. All users of the database must be able to -** share memory. -** -** In the default unix and windows implementation, the wal-index is a mmapped -** file whose name is the database name with a "-shm" suffix added. For that -** reason, the wal-index is sometimes called the "shm" file. -** -** The wal-index is transient. After a crash, the wal-index can (and should -** be) reconstructed from the original WAL file. In fact, the VFS is required -** to either truncate or zero the header of the wal-index when the last -** connection to it closes. Because the wal-index is transient, it can -** use an architecture-specific format; it does not have to be cross-platform. -** Hence, unlike the database and WAL file formats which store all values -** as big endian, the wal-index can store multi-byte values in the native -** byte order of the host computer. -** -** The purpose of the wal-index is to answer this question quickly: Given -** a page number P and a maximum frame index M, return the index of the -** last frame in the wal before frame M for page P in the WAL, or return -** NULL if there are no frames for page P in the WAL prior to M. -** -** The wal-index consists of a header region, followed by an one or -** more index blocks. -** -** The wal-index header contains the total number of frames within the WAL -** in the mxFrame field. -** -** Each index block except for the first contains information on -** HASHTABLE_NPAGE frames. The first index block contains information on -** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and -** HASHTABLE_NPAGE are selected so that together the wal-index header and -** first index block are the same size as all other index blocks in the -** wal-index. -** -** Each index block contains two sections, a page-mapping that contains the -** database page number associated with each wal frame, and a hash-table -** that allows readers to query an index block for a specific page number. -** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE -** for the first index block) 32-bit page numbers. The first entry in the -** first index-block contains the database page number corresponding to the -** first frame in the WAL file. The first entry in the second index block -** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in -** the log, and so on. -** -** The last index block in a wal-index usually contains less than the full -** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers, -** depending on the contents of the WAL file. This does not change the -** allocated size of the page-mapping array - the page-mapping array merely -** contains unused entries. -** -** Even without using the hash table, the last frame for page P -** can be found by scanning the page-mapping sections of each index block -** starting with the last index block and moving toward the first, and -** within each index block, starting at the end and moving toward the -** beginning. The first entry that equals P corresponds to the frame -** holding the content for that page. -** -** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers. -** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the -** hash table for each page number in the mapping section, so the hash -** table is never more than half full. The expected number of collisions -** prior to finding a match is 1. Each entry of the hash table is an -** 1-based index of an entry in the mapping section of the same -** index block. Let K be the 1-based index of the largest entry in -** the mapping section. (For index blocks other than the last, K will -** always be exactly HASHTABLE_NPAGE (4096) and for the last index block -** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table -** contain a value of 0. -** -** To look for page P in the hash table, first compute a hash iKey on -** P as follows: -** -** iKey = (P * 383) % HASHTABLE_NSLOT -** -** Then start scanning entries of the hash table, starting with iKey -** (wrapping around to the beginning when the end of the hash table is -** reached) until an unused hash slot is found. Let the first unused slot -** be at index iUnused. (iUnused might be less than iKey if there was -** wrap-around.) Because the hash table is never more than half full, -** the search is guaranteed to eventually hit an unused entry. Let -** iMax be the value between iKey and iUnused, closest to iUnused, -** where aHash[iMax]==P. If there is no iMax entry (if there exists -** no hash slot such that aHash[i]==p) then page P is not in the -** current index block. Otherwise the iMax-th mapping entry of the -** current index block corresponds to the last entry that references -** page P. -** -** A hash search begins with the last index block and moves toward the -** first index block, looking for entries corresponding to page P. On -** average, only two or three slots in each index block need to be -** examined in order to either find the last entry for page P, or to -** establish that no such entry exists in the block. Each index block -** holds over 4000 entries. So two or three index blocks are sufficient -** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10 -** comparisons (on average) suffice to either locate a frame in the -** WAL or to establish that the frame does not exist in the WAL. This -** is much faster than scanning the entire 10MB WAL. -** -** Note that entries are added in order of increasing K. Hence, one -** reader might be using some value K0 and a second reader that started -** at a later time (after additional transactions were added to the WAL -** and to the wal-index) might be using a different value K1, where K1>K0. -** Both readers can use the same hash table and mapping section to get -** the correct result. There may be entries in the hash table with -** K>K0 but to the first reader, those entries will appear to be unused -** slots in the hash table and so the first reader will get an answer as -** if no values greater than K0 had ever been inserted into the hash table -** in the first place - which is what reader one wants. Meanwhile, the -** second reader using K1 will see additional values that were inserted -** later, which is exactly what reader two wants. -** -** When a rollback occurs, the value of K is decreased. Hash table entries -** that correspond to frames greater than the new K value are removed -** from the hash table at this point. -*/ -#ifndef SQLITE_OMIT_WAL - -/* #include "wal.h" */ - -/* -** Trace output macros -*/ -#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) -SQLITE_PRIVATE int sqlite3WalTrace = 0; -# define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X -#else -# define WALTRACE(X) -#endif - -/* -** The maximum (and only) versions of the wal and wal-index formats -** that may be interpreted by this version of SQLite. -** -** If a client begins recovering a WAL file and finds that (a) the checksum -** values in the wal-header are correct and (b) the version field is not -** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN. -** -** Similarly, if a client successfully reads a wal-index header (i.e. the -** checksum test is successful) and finds that the version field is not -** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite -** returns SQLITE_CANTOPEN. -*/ -#define WAL_MAX_VERSION 3007000 -#define WALINDEX_MAX_VERSION 3007000 - -/* -** Index numbers for various locking bytes. WAL_NREADER is the number -** of available reader locks and should be at least 3. The default -** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5. -** -** Technically, the various VFSes are free to implement these locks however -** they see fit. However, compatibility is encouraged so that VFSes can -** interoperate. The standard implemention used on both unix and windows -** is for the index number to indicate a byte offset into the -** WalCkptInfo.aLock[] array in the wal-index header. In other words, all -** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which -** should be 120) is the location in the shm file for the first locking -** byte. -*/ -#define WAL_WRITE_LOCK 0 -#define WAL_ALL_BUT_WRITE 1 -#define WAL_CKPT_LOCK 1 -#define WAL_RECOVER_LOCK 2 -#define WAL_READ_LOCK(I) (3+(I)) -#define WAL_NREADER (SQLITE_SHM_NLOCK-3) - - -/* Object declarations */ -typedef struct WalIndexHdr WalIndexHdr; -typedef struct WalIterator WalIterator; -typedef struct WalCkptInfo WalCkptInfo; - - -/* -** The following object holds a copy of the wal-index header content. -** -** The actual header in the wal-index consists of two copies of this -** object followed by one instance of the WalCkptInfo object. -** For all versions of SQLite through 3.10.0 and probably beyond, -** the locking bytes (WalCkptInfo.aLock) start at offset 120 and -** the total header size is 136 bytes. -** -** The szPage value can be any power of 2 between 512 and 32768, inclusive. -** Or it can be 1 to represent a 65536-byte page. The latter case was -** added in 3.7.1 when support for 64K pages was added. -*/ -struct WalIndexHdr { - u32 iVersion; /* Wal-index version */ - u32 unused; /* Unused (padding) field */ - u32 iChange; /* Counter incremented each transaction */ - u8 isInit; /* 1 when initialized */ - u8 bigEndCksum; /* True if checksums in WAL are big-endian */ - u16 szPage; /* Database page size in bytes. 1==64K */ - u32 mxFrame; /* Index of last valid frame in the WAL */ - u32 nPage; /* Size of database in pages */ - u32 aFrameCksum[2]; /* Checksum of last frame in log */ - u32 aSalt[2]; /* Two salt values copied from WAL header */ - u32 aCksum[2]; /* Checksum over all prior fields */ -}; - -/* -** A copy of the following object occurs in the wal-index immediately -** following the second copy of the WalIndexHdr. This object stores -** information used by checkpoint. -** -** nBackfill is the number of frames in the WAL that have been written -** back into the database. (We call the act of moving content from WAL to -** database "backfilling".) The nBackfill number is never greater than -** WalIndexHdr.mxFrame. nBackfill can only be increased by threads -** holding the WAL_CKPT_LOCK lock (which includes a recovery thread). -** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from -** mxFrame back to zero when the WAL is reset. -** -** nBackfillAttempted is the largest value of nBackfill that a checkpoint -** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however -** the nBackfillAttempted is set before any backfilling is done and the -** nBackfill is only set after all backfilling completes. So if a checkpoint -** crashes, nBackfillAttempted might be larger than nBackfill. The -** WalIndexHdr.mxFrame must never be less than nBackfillAttempted. -** -** The aLock[] field is a set of bytes used for locking. These bytes should -** never be read or written. -** -** There is one entry in aReadMark[] for each reader lock. If a reader -** holds read-lock K, then the value in aReadMark[K] is no greater than -** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff) -** for any aReadMark[] means that entry is unused. aReadMark[0] is -** a special case; its value is never used and it exists as a place-holder -** to avoid having to offset aReadMark[] indexs by one. Readers holding -** WAL_READ_LOCK(0) always ignore the entire WAL and read all content -** directly from the database. -** -** The value of aReadMark[K] may only be changed by a thread that -** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of -** aReadMark[K] cannot changed while there is a reader is using that mark -** since the reader will be holding a shared lock on WAL_READ_LOCK(K). -** -** The checkpointer may only transfer frames from WAL to database where -** the frame numbers are less than or equal to every aReadMark[] that is -** in use (that is, every aReadMark[j] for which there is a corresponding -** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the -** largest value and will increase an unused aReadMark[] to mxFrame if there -** is not already an aReadMark[] equal to mxFrame. The exception to the -** previous sentence is when nBackfill equals mxFrame (meaning that everything -** in the WAL has been backfilled into the database) then new readers -** will choose aReadMark[0] which has value 0 and hence such reader will -** get all their all content directly from the database file and ignore -** the WAL. -** -** Writers normally append new frames to the end of the WAL. However, -** if nBackfill equals mxFrame (meaning that all WAL content has been -** written back into the database) and if no readers are using the WAL -** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then -** the writer will first "reset" the WAL back to the beginning and start -** writing new content beginning at frame 1. -** -** We assume that 32-bit loads are atomic and so no locks are needed in -** order to read from any aReadMark[] entries. -*/ -struct WalCkptInfo { - u32 nBackfill; /* Number of WAL frames backfilled into DB */ - u32 aReadMark[WAL_NREADER]; /* Reader marks */ - u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */ - u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */ - u32 notUsed0; /* Available for future enhancements */ -}; -#define READMARK_NOT_USED 0xffffffff - - -/* A block of WALINDEX_LOCK_RESERVED bytes beginning at -** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems -** only support mandatory file-locks, we do not read or write data -** from the region of the file on which locks are applied. -*/ -#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock)) -#define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo)) - -/* Size of header before each frame in wal */ -#define WAL_FRAME_HDRSIZE 24 - -/* Size of write ahead log header, including checksum. */ -#define WAL_HDRSIZE 32 - -/* WAL magic value. Either this value, or the same value with the least -** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit -** big-endian format in the first 4 bytes of a WAL file. -** -** If the LSB is set, then the checksums for each frame within the WAL -** file are calculated by treating all data as an array of 32-bit -** big-endian words. Otherwise, they are calculated by interpreting -** all data as 32-bit little-endian words. -*/ -#define WAL_MAGIC 0x377f0682 - -/* -** Return the offset of frame iFrame in the write-ahead log file, -** assuming a database page size of szPage bytes. The offset returned -** is to the start of the write-ahead log frame-header. -*/ -#define walFrameOffset(iFrame, szPage) ( \ - WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \ -) - -/* -** An open write-ahead log file is represented by an instance of the -** following object. -*/ -struct Wal { - sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ - sqlite3_file *pDbFd; /* File handle for the database file */ - sqlite3_file *pWalFd; /* File handle for WAL file */ - u32 iCallback; /* Value to pass to log callback (or 0) */ - i64 mxWalSize; /* Truncate WAL to this size upon reset */ - int nWiData; /* Size of array apWiData */ - int szFirstBlock; /* Size of first block written to WAL file */ - volatile u32 **apWiData; /* Pointer to wal-index content in memory */ - u32 szPage; /* Database page size */ - i16 readLock; /* Which read lock is being held. -1 for none */ - u8 syncFlags; /* Flags to use to sync header writes */ - u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */ - u8 writeLock; /* True if in a write transaction */ - u8 ckptLock; /* True if holding a checkpoint lock */ - u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */ - u8 truncateOnCommit; /* True to truncate WAL file on commit */ - u8 syncHeader; /* Fsync the WAL header if true */ - u8 padToSectorBoundary; /* Pad transactions out to the next sector */ - u8 bShmUnreliable; /* SHM content is read-only and unreliable */ - WalIndexHdr hdr; /* Wal-index header for current transaction */ - u32 minFrame; /* Ignore wal frames before this one */ - u32 iReCksum; /* On commit, recalculate checksums from here */ - const char *zWalName; /* Name of WAL file */ - u32 nCkpt; /* Checkpoint sequence counter in the wal-header */ -#ifdef SQLITE_DEBUG - u8 lockError; /* True if a locking error has occurred */ -#endif -#ifdef SQLITE_ENABLE_SNAPSHOT - WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */ -#endif -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT - sqlite3 *db; -#endif -}; - -/* -** Candidate values for Wal.exclusiveMode. -*/ -#define WAL_NORMAL_MODE 0 -#define WAL_EXCLUSIVE_MODE 1 -#define WAL_HEAPMEMORY_MODE 2 - -/* -** Possible values for WAL.readOnly -*/ -#define WAL_RDWR 0 /* Normal read/write connection */ -#define WAL_RDONLY 1 /* The WAL file is readonly */ -#define WAL_SHM_RDONLY 2 /* The SHM file is readonly */ - -/* -** Each page of the wal-index mapping contains a hash-table made up of -** an array of HASHTABLE_NSLOT elements of the following type. -*/ -typedef u16 ht_slot; - -/* -** This structure is used to implement an iterator that loops through -** all frames in the WAL in database page order. Where two or more frames -** correspond to the same database page, the iterator visits only the -** frame most recently written to the WAL (in other words, the frame with -** the largest index). -** -** The internals of this structure are only accessed by: -** -** walIteratorInit() - Create a new iterator, -** walIteratorNext() - Step an iterator, -** walIteratorFree() - Free an iterator. -** -** This functionality is used by the checkpoint code (see walCheckpoint()). -*/ -struct WalIterator { - u32 iPrior; /* Last result returned from the iterator */ - int nSegment; /* Number of entries in aSegment[] */ - struct WalSegment { - int iNext; /* Next slot in aIndex[] not yet returned */ - ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */ - u32 *aPgno; /* Array of page numbers. */ - int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */ - int iZero; /* Frame number associated with aPgno[0] */ - } aSegment[1]; /* One for every 32KB page in the wal-index */ -}; - -/* -** Define the parameters of the hash tables in the wal-index file. There -** is a hash-table following every HASHTABLE_NPAGE page numbers in the -** wal-index. -** -** Changing any of these constants will alter the wal-index format and -** create incompatibilities. -*/ -#define HASHTABLE_NPAGE 4096 /* Must be power of 2 */ -#define HASHTABLE_HASH_1 383 /* Should be prime */ -#define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */ - -/* -** The block of page numbers associated with the first hash-table in a -** wal-index is smaller than usual. This is so that there is a complete -** hash-table on each aligned 32KB page of the wal-index. -*/ -#define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32))) - -/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */ -#define WALINDEX_PGSZ ( \ - sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \ -) - -/* -** Obtain a pointer to the iPage'th page of the wal-index. The wal-index -** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are -** numbered from zero. -** -** If the wal-index is currently smaller the iPage pages then the size -** of the wal-index might be increased, but only if it is safe to do -** so. It is safe to enlarge the wal-index if pWal->writeLock is true -** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE. -** -** If this call is successful, *ppPage is set to point to the wal-index -** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs, -** then an SQLite error code is returned and *ppPage is set to 0. -*/ -static SQLITE_NOINLINE int walIndexPageRealloc( - Wal *pWal, /* The WAL context */ - int iPage, /* The page we seek */ - volatile u32 **ppPage /* Write the page pointer here */ -){ - int rc = SQLITE_OK; - - /* Enlarge the pWal->apWiData[] array if required */ - if( pWal->nWiData<=iPage ){ - sqlite3_int64 nByte = sizeof(u32*)*(iPage+1); - volatile u32 **apNew; - apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte); - if( !apNew ){ - *ppPage = 0; - return SQLITE_NOMEM_BKPT; - } - memset((void*)&apNew[pWal->nWiData], 0, - sizeof(u32*)*(iPage+1-pWal->nWiData)); - pWal->apWiData = apNew; - pWal->nWiData = iPage+1; - } - - /* Request a pointer to the required page from the VFS */ - assert( pWal->apWiData[iPage]==0 ); - if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ - pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ); - if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT; - }else{ - rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, - pWal->writeLock, (void volatile **)&pWal->apWiData[iPage] - ); - assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 ); - testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK ); - if( rc==SQLITE_OK ){ - if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM; - }else if( (rc&0xff)==SQLITE_READONLY ){ - pWal->readOnly |= WAL_SHM_RDONLY; - if( rc==SQLITE_READONLY ){ - rc = SQLITE_OK; - } - } - } - - *ppPage = pWal->apWiData[iPage]; - assert( iPage==0 || *ppPage || rc!=SQLITE_OK ); - return rc; -} -static int walIndexPage( - Wal *pWal, /* The WAL context */ - int iPage, /* The page we seek */ - volatile u32 **ppPage /* Write the page pointer here */ -){ - if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){ - return walIndexPageRealloc(pWal, iPage, ppPage); - } - return SQLITE_OK; -} - -/* -** Return a pointer to the WalCkptInfo structure in the wal-index. -*/ -static volatile WalCkptInfo *walCkptInfo(Wal *pWal){ - assert( pWal->nWiData>0 && pWal->apWiData[0] ); - return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]); -} - -/* -** Return a pointer to the WalIndexHdr structure in the wal-index. -*/ -static volatile WalIndexHdr *walIndexHdr(Wal *pWal){ - assert( pWal->nWiData>0 && pWal->apWiData[0] ); - return (volatile WalIndexHdr*)pWal->apWiData[0]; -} - -/* -** The argument to this macro must be of type u32. On a little-endian -** architecture, it returns the u32 value that results from interpreting -** the 4 bytes as a big-endian value. On a big-endian architecture, it -** returns the value that would be produced by interpreting the 4 bytes -** of the input value as a little-endian integer. -*/ -#define BYTESWAP32(x) ( \ - (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \ - + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \ -) - -/* -** Generate or extend an 8 byte checksum based on the data in -** array aByte[] and the initial values of aIn[0] and aIn[1] (or -** initial values of 0 and 0 if aIn==NULL). -** -** The checksum is written back into aOut[] before returning. -** -** nByte must be a positive multiple of 8. -*/ -static void walChecksumBytes( - int nativeCksum, /* True for native byte-order, false for non-native */ - u8 *a, /* Content to be checksummed */ - int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */ - const u32 *aIn, /* Initial checksum value input */ - u32 *aOut /* OUT: Final checksum value output */ -){ - u32 s1, s2; - u32 *aData = (u32 *)a; - u32 *aEnd = (u32 *)&a[nByte]; - - if( aIn ){ - s1 = aIn[0]; - s2 = aIn[1]; - }else{ - s1 = s2 = 0; - } - - assert( nByte>=8 ); - assert( (nByte&0x00000007)==0 ); - assert( nByte<=65536 ); - - if( nativeCksum ){ - do { - s1 += *aData++ + s2; - s2 += *aData++ + s1; - }while( aDataexclusiveMode!=WAL_HEAPMEMORY_MODE ){ - sqlite3OsShmBarrier(pWal->pDbFd); - } -} - -/* -** Add the SQLITE_NO_TSAN as part of the return-type of a function -** definition as a hint that the function contains constructs that -** might give false-positive TSAN warnings. -** -** See tag-20200519-1. -*/ -#if defined(__clang__) && !defined(SQLITE_NO_TSAN) -# define SQLITE_NO_TSAN __attribute__((no_sanitize_thread)) -#else -# define SQLITE_NO_TSAN -#endif - -/* -** Write the header information in pWal->hdr into the wal-index. -** -** The checksum on pWal->hdr is updated before it is written. -*/ -static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){ - volatile WalIndexHdr *aHdr = walIndexHdr(pWal); - const int nCksum = offsetof(WalIndexHdr, aCksum); - - assert( pWal->writeLock ); - pWal->hdr.isInit = 1; - pWal->hdr.iVersion = WALINDEX_MAX_VERSION; - walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum); - /* Possible TSAN false-positive. See tag-20200519-1 */ - memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); - walShmBarrier(pWal); - memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr)); -} - -/* -** This function encodes a single frame header and writes it to a buffer -** supplied by the caller. A frame-header is made up of a series of -** 4-byte big-endian integers, as follows: -** -** 0: Page number. -** 4: For commit records, the size of the database image in pages -** after the commit. For all other records, zero. -** 8: Salt-1 (copied from the wal-header) -** 12: Salt-2 (copied from the wal-header) -** 16: Checksum-1. -** 20: Checksum-2. -*/ -static void walEncodeFrame( - Wal *pWal, /* The write-ahead log */ - u32 iPage, /* Database page number for frame */ - u32 nTruncate, /* New db size (or 0 for non-commit frames) */ - u8 *aData, /* Pointer to page data */ - u8 *aFrame /* OUT: Write encoded frame here */ -){ - int nativeCksum; /* True for native byte-order checksums */ - u32 *aCksum = pWal->hdr.aFrameCksum; - assert( WAL_FRAME_HDRSIZE==24 ); - sqlite3Put4byte(&aFrame[0], iPage); - sqlite3Put4byte(&aFrame[4], nTruncate); - if( pWal->iReCksum==0 ){ - memcpy(&aFrame[8], pWal->hdr.aSalt, 8); - - nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); - walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); - walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); - - sqlite3Put4byte(&aFrame[16], aCksum[0]); - sqlite3Put4byte(&aFrame[20], aCksum[1]); - }else{ - memset(&aFrame[8], 0, 16); - } -} - -/* -** Check to see if the frame with header in aFrame[] and content -** in aData[] is valid. If it is a valid frame, fill *piPage and -** *pnTruncate and return true. Return if the frame is not valid. -*/ -static int walDecodeFrame( - Wal *pWal, /* The write-ahead log */ - u32 *piPage, /* OUT: Database page number for frame */ - u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */ - u8 *aData, /* Pointer to page data (for checksum) */ - u8 *aFrame /* Frame data */ -){ - int nativeCksum; /* True for native byte-order checksums */ - u32 *aCksum = pWal->hdr.aFrameCksum; - u32 pgno; /* Page number of the frame */ - assert( WAL_FRAME_HDRSIZE==24 ); - - /* A frame is only valid if the salt values in the frame-header - ** match the salt values in the wal-header. - */ - if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){ - return 0; - } - - /* A frame is only valid if the page number is creater than zero. - */ - pgno = sqlite3Get4byte(&aFrame[0]); - if( pgno==0 ){ - return 0; - } - - /* A frame is only valid if a checksum of the WAL header, - ** all prior frams, the first 16 bytes of this frame-header, - ** and the frame-data matches the checksum in the last 8 - ** bytes of this frame-header. - */ - nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN); - walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum); - walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum); - if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) - || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) - ){ - /* Checksum failed. */ - return 0; - } - - /* If we reach this point, the frame is valid. Return the page number - ** and the new database size. - */ - *piPage = pgno; - *pnTruncate = sqlite3Get4byte(&aFrame[4]); - return 1; -} - - -#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) -/* -** Names of locks. This routine is used to provide debugging output and is not -** a part of an ordinary build. -*/ -static const char *walLockName(int lockIdx){ - if( lockIdx==WAL_WRITE_LOCK ){ - return "WRITE-LOCK"; - }else if( lockIdx==WAL_CKPT_LOCK ){ - return "CKPT-LOCK"; - }else if( lockIdx==WAL_RECOVER_LOCK ){ - return "RECOVER-LOCK"; - }else{ - static char zName[15]; - sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]", - lockIdx-WAL_READ_LOCK(0)); - return zName; - } -} -#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */ - - -/* -** Set or release locks on the WAL. Locks are either shared or exclusive. -** A lock cannot be moved directly between shared and exclusive - it must go -** through the unlocked state first. -** -** In locking_mode=EXCLUSIVE, all of these routines become no-ops. -*/ -static int walLockShared(Wal *pWal, int lockIdx){ - int rc; - if( pWal->exclusiveMode ) return SQLITE_OK; - rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, - SQLITE_SHM_LOCK | SQLITE_SHM_SHARED); - WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal, - walLockName(lockIdx), rc ? "failed" : "ok")); - VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); ) - return rc; -} -static void walUnlockShared(Wal *pWal, int lockIdx){ - if( pWal->exclusiveMode ) return; - (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1, - SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED); - WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx))); -} -static int walLockExclusive(Wal *pWal, int lockIdx, int n){ - int rc; - if( pWal->exclusiveMode ) return SQLITE_OK; - rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, - SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE); - WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal, - walLockName(lockIdx), n, rc ? "failed" : "ok")); - VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); ) - return rc; -} -static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ - if( pWal->exclusiveMode ) return; - (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n, - SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE); - WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal, - walLockName(lockIdx), n)); -} - -/* -** Compute a hash on a page number. The resulting hash value must land -** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances -** the hash to the next value in the event of a collision. -*/ -static int walHash(u32 iPage){ - assert( iPage>0 ); - assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 ); - return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1); -} -static int walNextHash(int iPriorHash){ - return (iPriorHash+1)&(HASHTABLE_NSLOT-1); -} - -/* -** An instance of the WalHashLoc object is used to describe the location -** of a page hash table in the wal-index. This becomes the return value -** from walHashGet(). -*/ -typedef struct WalHashLoc WalHashLoc; -struct WalHashLoc { - volatile ht_slot *aHash; /* Start of the wal-index hash table */ - volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */ - u32 iZero; /* One less than the frame number of first indexed*/ -}; - -/* -** Return pointers to the hash table and page number array stored on -** page iHash of the wal-index. The wal-index is broken into 32KB pages -** numbered starting from 0. -** -** Set output variable pLoc->aHash to point to the start of the hash table -** in the wal-index file. Set pLoc->iZero to one less than the frame -** number of the first frame indexed by this hash table. If a -** slot in the hash table is set to N, it refers to frame number -** (pLoc->iZero+N) in the log. -** -** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the -** first frame indexed by the hash table, frame (pLoc->iZero+1). -*/ -static int walHashGet( - Wal *pWal, /* WAL handle */ - int iHash, /* Find the iHash'th table */ - WalHashLoc *pLoc /* OUT: Hash table location */ -){ - int rc; /* Return code */ - - rc = walIndexPage(pWal, iHash, &pLoc->aPgno); - assert( rc==SQLITE_OK || iHash>0 ); - - if( rc==SQLITE_OK ){ - pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE]; - if( iHash==0 ){ - pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; - pLoc->iZero = 0; - }else{ - pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; - } - pLoc->aPgno = &pLoc->aPgno[-1]; - } - return rc; -} - -/* -** Return the number of the wal-index page that contains the hash-table -** and page-number array that contain entries corresponding to WAL frame -** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages -** are numbered starting from 0. -*/ -static int walFramePage(u32 iFrame){ - int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE; - assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE) - && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE) - && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)) - && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE) - && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE)) - ); - assert( iHash>=0 ); - return iHash; -} - -/* -** Return the page number associated with frame iFrame in this WAL. -*/ -static u32 walFramePgno(Wal *pWal, u32 iFrame){ - int iHash = walFramePage(iFrame); - if( iHash==0 ){ - return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1]; - } - return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE]; -} - -/* -** Remove entries from the hash table that point to WAL slots greater -** than pWal->hdr.mxFrame. -** -** This function is called whenever pWal->hdr.mxFrame is decreased due -** to a rollback or savepoint. -** -** At most only the hash table containing pWal->hdr.mxFrame needs to be -** updated. Any later hash tables will be automatically cleared when -** pWal->hdr.mxFrame advances to the point where those hash tables are -** actually needed. -*/ -static void walCleanupHash(Wal *pWal){ - WalHashLoc sLoc; /* Hash table location */ - int iLimit = 0; /* Zero values greater than this */ - int nByte; /* Number of bytes to zero in aPgno[] */ - int i; /* Used to iterate through aHash[] */ - int rc; /* Return code form walHashGet() */ - - assert( pWal->writeLock ); - testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 ); - testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE ); - testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 ); - - if( pWal->hdr.mxFrame==0 ) return; - - /* Obtain pointers to the hash-table and page-number array containing - ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed - ** that the page said hash-table and array reside on is already mapped.(1) - */ - assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) ); - assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] ); - rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc); - if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */ - - /* Zero all hash-table entries that correspond to frame numbers greater - ** than pWal->hdr.mxFrame. - */ - iLimit = pWal->hdr.mxFrame - sLoc.iZero; - assert( iLimit>0 ); - for(i=0; iiLimit ){ - sLoc.aHash[i] = 0; - } - } - - /* Zero the entries in the aPgno array that correspond to frames with - ** frame numbers greater than pWal->hdr.mxFrame. - */ - nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]); - memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte); - -#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT - /* Verify that the every entry in the mapping region is still reachable - ** via the hash table even after the cleanup. - */ - if( iLimit ){ - int j; /* Loop counter */ - int iKey; /* Hash key */ - for(j=1; j<=iLimit; j++){ - for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){ - if( sLoc.aHash[iKey]==j ) break; - } - assert( sLoc.aHash[iKey]==j ); - } - } -#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */ -} - - -/* -** Set an entry in the wal-index that will map database page number -** pPage into WAL frame iFrame. -*/ -static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ - int rc; /* Return code */ - WalHashLoc sLoc; /* Wal-index hash table location */ - - rc = walHashGet(pWal, walFramePage(iFrame), &sLoc); - - /* Assuming the wal-index file was successfully mapped, populate the - ** page number array and hash table entry. - */ - if( rc==SQLITE_OK ){ - int iKey; /* Hash table key */ - int idx; /* Value to write to hash-table slot */ - int nCollide; /* Number of hash collisions */ - - idx = iFrame - sLoc.iZero; - assert( idx <= HASHTABLE_NSLOT/2 + 1 ); - - /* If this is the first entry to be added to this hash-table, zero the - ** entire hash table and aPgno[] array before proceeding. - */ - if( idx==1 ){ - int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT] - - (u8 *)&sLoc.aPgno[1]); - memset((void*)&sLoc.aPgno[1], 0, nByte); - } - - /* If the entry in aPgno[] is already set, then the previous writer - ** must have exited unexpectedly in the middle of a transaction (after - ** writing one or more dirty pages to the WAL to free up memory). - ** Remove the remnants of that writers uncommitted transaction from - ** the hash-table before writing any new entries. - */ - if( sLoc.aPgno[idx] ){ - walCleanupHash(pWal); - assert( !sLoc.aPgno[idx] ); - } - - /* Write the aPgno[] array entry and the hash-table slot. */ - nCollide = idx; - for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){ - if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; - } - sLoc.aPgno[idx] = iPage; - AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx); - -#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT - /* Verify that the number of entries in the hash table exactly equals - ** the number of entries in the mapping region. - */ - { - int i; /* Loop counter */ - int nEntry = 0; /* Number of entries in the hash table */ - for(i=0; ickptLock==1 || pWal->ckptLock==0 ); - assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 ); - assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE ); - assert( pWal->writeLock ); - iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock; - rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock); - if( rc ){ - return rc; - } - - WALTRACE(("WAL%p: recovery begin...\n", pWal)); - - memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); - - rc = sqlite3OsFileSize(pWal->pWalFd, &nSize); - if( rc!=SQLITE_OK ){ - goto recovery_error; - } - - if( nSize>WAL_HDRSIZE ){ - u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */ - u32 *aPrivate = 0; /* Heap copy of *-shm hash being populated */ - u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ - int szFrame; /* Number of bytes in buffer aFrame[] */ - u8 *aData; /* Pointer to data part of aFrame buffer */ - int szPage; /* Page size according to the log */ - u32 magic; /* Magic value read from WAL header */ - u32 version; /* Magic value read from WAL header */ - int isValid; /* True if this frame is valid */ - u32 iPg; /* Current 32KB wal-index page */ - u32 iLastFrame; /* Last frame in wal, based on nSize alone */ - - /* Read in the WAL header. */ - rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); - if( rc!=SQLITE_OK ){ - goto recovery_error; - } - - /* If the database page size is not a power of two, or is greater than - ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid - ** data. Similarly, if the 'magic' value is invalid, ignore the whole - ** WAL file. - */ - magic = sqlite3Get4byte(&aBuf[0]); - szPage = sqlite3Get4byte(&aBuf[8]); - if( (magic&0xFFFFFFFE)!=WAL_MAGIC - || szPage&(szPage-1) - || szPage>SQLITE_MAX_PAGE_SIZE - || szPage<512 - ){ - goto finished; - } - pWal->hdr.bigEndCksum = (u8)(magic&0x00000001); - pWal->szPage = szPage; - pWal->nCkpt = sqlite3Get4byte(&aBuf[12]); - memcpy(&pWal->hdr.aSalt, &aBuf[16], 8); - - /* Verify that the WAL header checksum is correct */ - walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, - aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum - ); - if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24]) - || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28]) - ){ - goto finished; - } - - /* Verify that the version number on the WAL format is one that - ** are able to understand */ - version = sqlite3Get4byte(&aBuf[4]); - if( version!=WAL_MAX_VERSION ){ - rc = SQLITE_CANTOPEN_BKPT; - goto finished; - } - - /* Malloc a buffer to read frames into. */ - szFrame = szPage + WAL_FRAME_HDRSIZE; - aFrame = (u8 *)sqlite3_malloc64(szFrame + WALINDEX_PGSZ); - if( !aFrame ){ - rc = SQLITE_NOMEM_BKPT; - goto recovery_error; - } - aData = &aFrame[WAL_FRAME_HDRSIZE]; - aPrivate = (u32*)&aData[szPage]; - - /* Read all frames from the log file. */ - iLastFrame = (nSize - WAL_HDRSIZE) / szFrame; - for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){ - u32 *aShare; - u32 iFrame; /* Index of last frame read */ - u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE); - u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE); - u32 nHdr, nHdr32; - rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare); - if( rc ) break; - pWal->apWiData[iPg] = aPrivate; - - for(iFrame=iFirst; iFrame<=iLast; iFrame++){ - i64 iOffset = walFrameOffset(iFrame, szPage); - u32 pgno; /* Database page number for frame */ - u32 nTruncate; /* dbsize field from frame header */ - - /* Read and decode the next log frame. */ - rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); - if( rc!=SQLITE_OK ) break; - isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame); - if( !isValid ) break; - rc = walIndexAppend(pWal, iFrame, pgno); - if( NEVER(rc!=SQLITE_OK) ) break; - - /* If nTruncate is non-zero, this is a commit record. */ - if( nTruncate ){ - pWal->hdr.mxFrame = iFrame; - pWal->hdr.nPage = nTruncate; - pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); - testcase( szPage<=32768 ); - testcase( szPage>=65536 ); - aFrameCksum[0] = pWal->hdr.aFrameCksum[0]; - aFrameCksum[1] = pWal->hdr.aFrameCksum[1]; - } - } - pWal->apWiData[iPg] = aShare; - nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0); - nHdr32 = nHdr / sizeof(u32); -#ifndef SQLITE_SAFER_WALINDEX_RECOVERY - /* Memcpy() should work fine here, on all reasonable implementations. - ** Technically, memcpy() might change the destination to some - ** intermediate value before setting to the final value, and that might - ** cause a concurrent reader to malfunction. Memcpy() is allowed to - ** do that, according to the spec, but no memcpy() implementation that - ** we know of actually does that, which is why we say that memcpy() - ** is safe for this. Memcpy() is certainly a lot faster. - */ - memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr); -#else - /* In the event that some platform is found for which memcpy() - ** changes the destination to some intermediate value before - ** setting the final value, this alternative copy routine is - ** provided. - */ - { - int i; - for(i=nHdr32; ihdr.aFrameCksum[0] = aFrameCksum[0]; - pWal->hdr.aFrameCksum[1] = aFrameCksum[1]; - walIndexWriteHdr(pWal); - - /* Reset the checkpoint-header. This is safe because this thread is - ** currently holding locks that exclude all other writers and - ** checkpointers. Then set the values of read-mark slots 1 through N. - */ - pInfo = walCkptInfo(pWal); - pInfo->nBackfill = 0; - pInfo->nBackfillAttempted = pWal->hdr.mxFrame; - pInfo->aReadMark[0] = 0; - for(i=1; ihdr.mxFrame ){ - pInfo->aReadMark[i] = pWal->hdr.mxFrame; - }else{ - pInfo->aReadMark[i] = READMARK_NOT_USED; - } - walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); - }else if( rc!=SQLITE_BUSY ){ - goto recovery_error; - } - } - - /* If more than one frame was recovered from the log file, report an - ** event via sqlite3_log(). This is to help with identifying performance - ** problems caused by applications routinely shutting down without - ** checkpointing the log file. - */ - if( pWal->hdr.nPage ){ - sqlite3_log(SQLITE_NOTICE_RECOVER_WAL, - "recovered %d frames from WAL file %s", - pWal->hdr.mxFrame, pWal->zWalName - ); - } - } - -recovery_error: - WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok")); - walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock); - return rc; -} - -/* -** Close an open wal-index. -*/ -static void walIndexClose(Wal *pWal, int isDelete){ - if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){ - int i; - for(i=0; inWiData; i++){ - sqlite3_free((void *)pWal->apWiData[i]); - pWal->apWiData[i] = 0; - } - } - if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){ - sqlite3OsShmUnmap(pWal->pDbFd, isDelete); - } -} - -/* -** Open a connection to the WAL file zWalName. The database file must -** already be opened on connection pDbFd. The buffer that zWalName points -** to must remain valid for the lifetime of the returned Wal* handle. -** -** A SHARED lock should be held on the database file when this function -** is called. The purpose of this SHARED lock is to prevent any other -** client from unlinking the WAL or wal-index file. If another process -** were to do this just after this client opened one of these files, the -** system would be badly broken. -** -** If the log file is successfully opened, SQLITE_OK is returned and -** *ppWal is set to point to a new WAL handle. If an error occurs, -** an SQLite error code is returned and *ppWal is left unmodified. -*/ -SQLITE_PRIVATE int sqlite3WalOpen( - sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */ - sqlite3_file *pDbFd, /* The open database file */ - const char *zWalName, /* Name of the WAL file */ - int bNoShm, /* True to run in heap-memory mode */ - i64 mxWalSize, /* Truncate WAL to this size on reset */ - Wal **ppWal /* OUT: Allocated Wal handle */ -){ - int rc; /* Return Code */ - Wal *pRet; /* Object to allocate and return */ - int flags; /* Flags passed to OsOpen() */ - - assert( zWalName && zWalName[0] ); - assert( pDbFd ); - - /* In the amalgamation, the os_unix.c and os_win.c source files come before - ** this source file. Verify that the #defines of the locking byte offsets - ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value. - ** For that matter, if the lock offset ever changes from its initial design - ** value of 120, we need to know that so there is an assert() to check it. - */ - assert( 120==WALINDEX_LOCK_OFFSET ); - assert( 136==WALINDEX_HDR_SIZE ); -#ifdef WIN_SHM_BASE - assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET ); -#endif -#ifdef UNIX_SHM_BASE - assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET ); -#endif - - - /* Allocate an instance of struct Wal to return. */ - *ppWal = 0; - pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile); - if( !pRet ){ - return SQLITE_NOMEM_BKPT; - } - - pRet->pVfs = pVfs; - pRet->pWalFd = (sqlite3_file *)&pRet[1]; - pRet->pDbFd = pDbFd; - pRet->readLock = -1; - pRet->mxWalSize = mxWalSize; - pRet->zWalName = zWalName; - pRet->syncHeader = 1; - pRet->padToSectorBoundary = 1; - pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE); - - /* Open file handle on the write-ahead log file. */ - flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL); - rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags); - if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){ - pRet->readOnly = WAL_RDONLY; - } - - if( rc!=SQLITE_OK ){ - walIndexClose(pRet, 0); - sqlite3OsClose(pRet->pWalFd); - sqlite3_free(pRet); - }else{ - int iDC = sqlite3OsDeviceCharacteristics(pDbFd); - if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; } - if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){ - pRet->padToSectorBoundary = 0; - } - *ppWal = pRet; - WALTRACE(("WAL%d: opened\n", pRet)); - } - return rc; -} - -/* -** Change the size to which the WAL file is trucated on each reset. -*/ -SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){ - if( pWal ) pWal->mxWalSize = iLimit; -} - -/* -** Find the smallest page number out of all pages held in the WAL that -** has not been returned by any prior invocation of this method on the -** same WalIterator object. Write into *piFrame the frame index where -** that page was last written into the WAL. Write into *piPage the page -** number. -** -** Return 0 on success. If there are no pages in the WAL with a page -** number larger than *piPage, then return 1. -*/ -static int walIteratorNext( - WalIterator *p, /* Iterator */ - u32 *piPage, /* OUT: The page number of the next page */ - u32 *piFrame /* OUT: Wal frame index of next page */ -){ - u32 iMin; /* Result pgno must be greater than iMin */ - u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */ - int i; /* For looping through segments */ - - iMin = p->iPrior; - assert( iMin<0xffffffff ); - for(i=p->nSegment-1; i>=0; i--){ - struct WalSegment *pSegment = &p->aSegment[i]; - while( pSegment->iNextnEntry ){ - u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; - if( iPg>iMin ){ - if( iPgiZero + pSegment->aIndex[pSegment->iNext]; - } - break; - } - pSegment->iNext++; - } - } - - *piPage = p->iPrior = iRet; - return (iRet==0xFFFFFFFF); -} - -/* -** This function merges two sorted lists into a single sorted list. -** -** aLeft[] and aRight[] are arrays of indices. The sort key is -** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following -** is guaranteed for all J0 && nRight>0 ); - while( iRight=nRight || aContent[aLeft[iLeft]]=nLeft || aContent[aLeft[iLeft]]>dbpage ); - assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage ); - } - - *paRight = aLeft; - *pnRight = iOut; - memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut); -} - -/* -** Sort the elements in list aList using aContent[] as the sort key. -** Remove elements with duplicate keys, preferring to keep the -** larger aList[] values. -** -** The aList[] entries are indices into aContent[]. The values in -** aList[] are to be sorted so that for all J0 ); - assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) ); - - for(iList=0; iListaList && p->nList<=(1<aList==&aList[iList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); - } - aSub[iSub].aList = aMerge; - aSub[iSub].nList = nMerge; - } - - for(iSub++; iSubnList<=(1<aList==&aList[nList&~((2<aList, p->nList, &aMerge, &nMerge, aBuffer); - } - } - assert( aMerge==aList ); - *pnList = nMerge; - -#ifdef SQLITE_DEBUG - { - int i; - for(i=1; i<*pnList; i++){ - assert( aContent[aList[i]] > aContent[aList[i-1]] ); - } - } -#endif -} - -/* -** Free an iterator allocated by walIteratorInit(). -*/ -static void walIteratorFree(WalIterator *p){ - sqlite3_free(p); -} - -/* -** Construct a WalInterator object that can be used to loop over all -** pages in the WAL following frame nBackfill in ascending order. Frames -** nBackfill or earlier may be included - excluding them is an optimization -** only. The caller must hold the checkpoint lock. -** -** On success, make *pp point to the newly allocated WalInterator object -** return SQLITE_OK. Otherwise, return an error code. If this routine -** returns an error, the value of *pp is undefined. -** -** The calling routine should invoke walIteratorFree() to destroy the -** WalIterator object when it has finished with it. -*/ -static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){ - WalIterator *p; /* Return value */ - int nSegment; /* Number of segments to merge */ - u32 iLast; /* Last frame in log */ - sqlite3_int64 nByte; /* Number of bytes to allocate */ - int i; /* Iterator variable */ - ht_slot *aTmp; /* Temp space used by merge-sort */ - int rc = SQLITE_OK; /* Return Code */ - - /* This routine only runs while holding the checkpoint lock. And - ** it only runs if there is actually content in the log (mxFrame>0). - */ - assert( pWal->ckptLock && pWal->hdr.mxFrame>0 ); - iLast = pWal->hdr.mxFrame; - - /* Allocate space for the WalIterator object. */ - nSegment = walFramePage(iLast) + 1; - nByte = sizeof(WalIterator) - + (nSegment-1)*sizeof(struct WalSegment) - + iLast*sizeof(ht_slot); - p = (WalIterator *)sqlite3_malloc64(nByte); - if( !p ){ - return SQLITE_NOMEM_BKPT; - } - memset(p, 0, nByte); - p->nSegment = nSegment; - - /* Allocate temporary space used by the merge-sort routine. This block - ** of memory will be freed before this function returns. - */ - aTmp = (ht_slot *)sqlite3_malloc64( - sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast) - ); - if( !aTmp ){ - rc = SQLITE_NOMEM_BKPT; - } - - for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && iaSegment[p->nSegment])[sLoc.iZero]; - sLoc.iZero++; - - for(j=0; jaSegment[i].iZero = sLoc.iZero; - p->aSegment[i].nEntry = nEntry; - p->aSegment[i].aIndex = aIndex; - p->aSegment[i].aPgno = (u32 *)sLoc.aPgno; - } - } - sqlite3_free(aTmp); - - if( rc!=SQLITE_OK ){ - walIteratorFree(p); - p = 0; - } - *pp = p; - return rc; -} - -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT -/* -** Attempt to enable blocking locks. Blocking locks are enabled only if (a) -** they are supported by the VFS, and (b) the database handle is configured -** with a busy-timeout. Return 1 if blocking locks are successfully enabled, -** or 0 otherwise. -*/ -static int walEnableBlocking(Wal *pWal){ - int res = 0; - if( pWal->db ){ - int tmout = pWal->db->busyTimeout; - if( tmout ){ - int rc; - rc = sqlite3OsFileControl( - pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout - ); - res = (rc==SQLITE_OK); - } - } - return res; -} - -/* -** Disable blocking locks. -*/ -static void walDisableBlocking(Wal *pWal){ - int tmout = 0; - sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout); -} - -/* -** If parameter bLock is true, attempt to enable blocking locks, take -** the WRITER lock, and then disable blocking locks. If blocking locks -** cannot be enabled, no attempt to obtain the WRITER lock is made. Return -** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not -** an error if blocking locks can not be enabled. -** -** If the bLock parameter is false and the WRITER lock is held, release it. -*/ -SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock){ - int rc = SQLITE_OK; - assert( pWal->readLock<0 || bLock==0 ); - if( bLock ){ - assert( pWal->db ); - if( walEnableBlocking(pWal) ){ - rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1); - if( rc==SQLITE_OK ){ - pWal->writeLock = 1; - } - walDisableBlocking(pWal); - } - }else if( pWal->writeLock ){ - walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); - pWal->writeLock = 0; - } - return rc; -} - -/* -** Set the database handle used to determine if blocking locks are required. -*/ -SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db){ - pWal->db = db; -} - -/* -** Take an exclusive WRITE lock. Blocking if so configured. -*/ -static int walLockWriter(Wal *pWal){ - int rc; - walEnableBlocking(pWal); - rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1); - walDisableBlocking(pWal); - return rc; -} -#else -# define walEnableBlocking(x) 0 -# define walDisableBlocking(x) -# define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1) -# define sqlite3WalDb(pWal, db) -#endif /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */ - - -/* -** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and -** n. If the attempt fails and parameter xBusy is not NULL, then it is a -** busy-handler function. Invoke it and retry the lock until either the -** lock is successfully obtained or the busy-handler returns 0. -*/ -static int walBusyLock( - Wal *pWal, /* WAL connection */ - int (*xBusy)(void*), /* Function to call when busy */ - void *pBusyArg, /* Context argument for xBusyHandler */ - int lockIdx, /* Offset of first byte to lock */ - int n /* Number of bytes to lock */ -){ - int rc; - do { - rc = walLockExclusive(pWal, lockIdx, n); - }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) ); -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT - if( rc==SQLITE_BUSY_TIMEOUT ){ - walDisableBlocking(pWal); - rc = SQLITE_BUSY; - } -#endif - return rc; -} - -/* -** The cache of the wal-index header must be valid to call this function. -** Return the page-size in bytes used by the database. -*/ -static int walPagesize(Wal *pWal){ - return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); -} - -/* -** The following is guaranteed when this function is called: -** -** a) the WRITER lock is held, -** b) the entire log file has been checkpointed, and -** c) any existing readers are reading exclusively from the database -** file - there are no readers that may attempt to read a frame from -** the log file. -** -** This function updates the shared-memory structures so that the next -** client to write to the database (which may be this one) does so by -** writing frames into the start of the log file. -** -** The value of parameter salt1 is used as the aSalt[1] value in the -** new wal-index header. It should be passed a pseudo-random value (i.e. -** one obtained from sqlite3_randomness()). -*/ -static void walRestartHdr(Wal *pWal, u32 salt1){ - volatile WalCkptInfo *pInfo = walCkptInfo(pWal); - int i; /* Loop counter */ - u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */ - pWal->nCkpt++; - pWal->hdr.mxFrame = 0; - sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0])); - memcpy(&pWal->hdr.aSalt[1], &salt1, 4); - walIndexWriteHdr(pWal); - AtomicStore(&pInfo->nBackfill, 0); - pInfo->nBackfillAttempted = 0; - pInfo->aReadMark[1] = 0; - for(i=2; iaReadMark[i] = READMARK_NOT_USED; - assert( pInfo->aReadMark[0]==0 ); -} - -/* -** Copy as much content as we can from the WAL back into the database file -** in response to an sqlite3_wal_checkpoint() request or the equivalent. -** -** The amount of information copies from WAL to database might be limited -** by active readers. This routine will never overwrite a database page -** that a concurrent reader might be using. -** -** All I/O barrier operations (a.k.a fsyncs) occur in this routine when -** SQLite is in WAL-mode in synchronous=NORMAL. That means that if -** checkpoints are always run by a background thread or background -** process, foreground threads will never block on a lengthy fsync call. -** -** Fsync is called on the WAL before writing content out of the WAL and -** into the database. This ensures that if the new content is persistent -** in the WAL and can be recovered following a power-loss or hard reset. -** -** Fsync is also called on the database file if (and only if) the entire -** WAL content is copied into the database file. This second fsync makes -** it safe to delete the WAL since the new content will persist in the -** database file. -** -** This routine uses and updates the nBackfill field of the wal-index header. -** This is the only routine that will increase the value of nBackfill. -** (A WAL reset or recovery will revert nBackfill to zero, but not increase -** its value.) -** -** The caller must be holding sufficient locks to ensure that no other -** checkpoint is running (in any other thread or process) at the same -** time. -*/ -static int walCheckpoint( - Wal *pWal, /* Wal connection */ - sqlite3 *db, /* Check for interrupts on this handle */ - int eMode, /* One of PASSIVE, FULL or RESTART */ - int (*xBusy)(void*), /* Function to call when busy */ - void *pBusyArg, /* Context argument for xBusyHandler */ - int sync_flags, /* Flags for OsSync() (or 0) */ - u8 *zBuf /* Temporary buffer to use */ -){ - int rc = SQLITE_OK; /* Return code */ - int szPage; /* Database page-size */ - WalIterator *pIter = 0; /* Wal iterator context */ - u32 iDbpage = 0; /* Next database page to write */ - u32 iFrame = 0; /* Wal frame containing data for iDbpage */ - u32 mxSafeFrame; /* Max frame that can be backfilled */ - u32 mxPage; /* Max database page to write */ - int i; /* Loop counter */ - volatile WalCkptInfo *pInfo; /* The checkpoint status information */ - - szPage = walPagesize(pWal); - testcase( szPage<=32768 ); - testcase( szPage>=65536 ); - pInfo = walCkptInfo(pWal); - if( pInfo->nBackfillhdr.mxFrame ){ - - /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked - ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ - assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); - - /* Compute in mxSafeFrame the index of the last frame of the WAL that is - ** safe to write into the database. Frames beyond mxSafeFrame might - ** overwrite database pages that are in use by active readers and thus - ** cannot be backfilled from the WAL. - */ - mxSafeFrame = pWal->hdr.mxFrame; - mxPage = pWal->hdr.nPage; - for(i=1; iaReadMark+i); - if( mxSafeFrame>y ){ - assert( y<=pWal->hdr.mxFrame ); - rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1); - if( rc==SQLITE_OK ){ - u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED); - AtomicStore(pInfo->aReadMark+i, iMark); - walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); - }else if( rc==SQLITE_BUSY ){ - mxSafeFrame = y; - xBusy = 0; - }else{ - goto walcheckpoint_out; - } - } - } - - /* Allocate the iterator */ - if( pInfo->nBackfillnBackfill, &pIter); - assert( rc==SQLITE_OK || pIter==0 ); - } - - if( pIter - && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK - ){ - u32 nBackfill = pInfo->nBackfill; - - pInfo->nBackfillAttempted = mxSafeFrame; - - /* Sync the WAL to disk */ - rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)); - - /* If the database may grow as a result of this checkpoint, hint - ** about the eventual size of the db file to the VFS layer. - */ - if( rc==SQLITE_OK ){ - i64 nReq = ((i64)mxPage * szPage); - i64 nSize; /* Current size of database file */ - sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0); - rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); - if( rc==SQLITE_OK && nSizehdr.mxFrame*szPage)pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq); - } - } - - } - - /* Iterate through the contents of the WAL, copying data to the db file */ - while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ - i64 iOffset; - assert( walFramePgno(pWal, iFrame)==iDbpage ); - if( AtomicLoad(&db->u1.isInterrupted) ){ - rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; - break; - } - if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){ - continue; - } - iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; - /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ - rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); - if( rc!=SQLITE_OK ) break; - iOffset = (iDbpage-1)*(i64)szPage; - testcase( IS_BIG_INT(iOffset) ); - rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); - if( rc!=SQLITE_OK ) break; - } - sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0); - - /* If work was actually accomplished... */ - if( rc==SQLITE_OK ){ - if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ - i64 szDb = pWal->hdr.nPage*(i64)szPage; - testcase( IS_BIG_INT(szDb) ); - rc = sqlite3OsTruncate(pWal->pDbFd, szDb); - if( rc==SQLITE_OK ){ - rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags)); - } - } - if( rc==SQLITE_OK ){ - AtomicStore(&pInfo->nBackfill, mxSafeFrame); - } - } - - /* Release the reader lock held while backfilling */ - walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1); - } - - if( rc==SQLITE_BUSY ){ - /* Reset the return code so as not to report a checkpoint failure - ** just because there are active readers. */ - rc = SQLITE_OK; - } - } - - /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the - ** entire wal file has been copied into the database file, then block - ** until all readers have finished using the wal file. This ensures that - ** the next process to write to the database restarts the wal file. - */ - if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){ - assert( pWal->writeLock ); - if( pInfo->nBackfillhdr.mxFrame ){ - rc = SQLITE_BUSY; - }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){ - u32 salt1; - sqlite3_randomness(4, &salt1); - assert( pInfo->nBackfill==pWal->hdr.mxFrame ); - rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1); - if( rc==SQLITE_OK ){ - if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){ - /* IMPLEMENTATION-OF: R-44699-57140 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. - ** - ** In theory, it might be safe to do this without updating the - ** wal-index header in shared memory, as all subsequent reader or - ** writer clients should see that the entire log file has been - ** checkpointed and behave accordingly. This seems unsafe though, - ** as it would leave the system in a state where the contents of - ** the wal-index header do not match the contents of the - ** file-system. To avoid this, update the wal-index header to - ** indicate that the log file contains zero valid frames. */ - walRestartHdr(pWal, salt1); - rc = sqlite3OsTruncate(pWal->pWalFd, 0); - } - walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); - } - } - } - - walcheckpoint_out: - walIteratorFree(pIter); - return rc; -} - -/* -** If the WAL file is currently larger than nMax bytes in size, truncate -** it to exactly nMax bytes. If an error occurs while doing so, ignore it. -*/ -static void walLimitSize(Wal *pWal, i64 nMax){ - i64 sz; - int rx; - sqlite3BeginBenignMalloc(); - rx = sqlite3OsFileSize(pWal->pWalFd, &sz); - if( rx==SQLITE_OK && (sz > nMax ) ){ - rx = sqlite3OsTruncate(pWal->pWalFd, nMax); - } - sqlite3EndBenignMalloc(); - if( rx ){ - sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName); - } -} - -/* -** Close a connection to a log file. -*/ -SQLITE_PRIVATE int sqlite3WalClose( - Wal *pWal, /* Wal to close */ - sqlite3 *db, /* For interrupt flag */ - int sync_flags, /* Flags to pass to OsSync() (or 0) */ - int nBuf, - u8 *zBuf /* Buffer of at least nBuf bytes */ -){ - int rc = SQLITE_OK; - if( pWal ){ - int isDelete = 0; /* True to unlink wal and wal-index files */ - - /* If an EXCLUSIVE lock can be obtained on the database file (using the - ** ordinary, rollback-mode locking methods, this guarantees that the - ** connection associated with this log file is the only connection to - ** the database. In this case checkpoint the database and unlink both - ** the wal and wal-index files. - ** - ** The EXCLUSIVE lock is not released before returning. - */ - if( zBuf!=0 - && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE)) - ){ - if( pWal->exclusiveMode==WAL_NORMAL_MODE ){ - pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; - } - rc = sqlite3WalCheckpoint(pWal, db, - SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0 - ); - if( rc==SQLITE_OK ){ - int bPersist = -1; - sqlite3OsFileControlHint( - pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist - ); - if( bPersist!=1 ){ - /* Try to delete the WAL file if the checkpoint completed and - ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal - ** mode (!bPersist) */ - isDelete = 1; - }else if( pWal->mxWalSize>=0 ){ - /* Try to truncate the WAL file to zero bytes if the checkpoint - ** completed and fsynced (rc==SQLITE_OK) and we are in persistent - ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a - ** non-negative value (pWal->mxWalSize>=0). Note that we truncate - ** to zero bytes as truncating to the journal_size_limit might - ** leave a corrupt WAL file on disk. */ - walLimitSize(pWal, 0); - } - } - } - - walIndexClose(pWal, isDelete); - sqlite3OsClose(pWal->pWalFd); - if( isDelete ){ - sqlite3BeginBenignMalloc(); - sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0); - sqlite3EndBenignMalloc(); - } - WALTRACE(("WAL%p: closed\n", pWal)); - sqlite3_free((void *)pWal->apWiData); - sqlite3_free(pWal); - } - return rc; -} - -/* -** Try to read the wal-index header. Return 0 on success and 1 if -** there is a problem. -** -** The wal-index is in shared memory. Another thread or process might -** be writing the header at the same time this procedure is trying to -** read it, which might result in inconsistency. A dirty read is detected -** by verifying that both copies of the header are the same and also by -** a checksum on the header. -** -** If and only if the read is consistent and the header is different from -** pWal->hdr, then pWal->hdr is updated to the content of the new header -** and *pChanged is set to 1. -** -** If the checksum cannot be verified return non-zero. If the header -** is read successfully and the checksum verified, return zero. -*/ -static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){ - u32 aCksum[2]; /* Checksum on the header content */ - WalIndexHdr h1, h2; /* Two copies of the header content */ - WalIndexHdr volatile *aHdr; /* Header in shared memory */ - - /* The first page of the wal-index must be mapped at this point. */ - assert( pWal->nWiData>0 && pWal->apWiData[0] ); - - /* Read the header. This might happen concurrently with a write to the - ** same area of shared memory on a different CPU in a SMP, - ** meaning it is possible that an inconsistent snapshot is read - ** from the file. If this happens, return non-zero. - ** - ** tag-20200519-1: - ** There are two copies of the header at the beginning of the wal-index. - ** When reading, read [0] first then [1]. Writes are in the reverse order. - ** Memory barriers are used to prevent the compiler or the hardware from - ** reordering the reads and writes. TSAN and similar tools can sometimes - ** give false-positive warnings about these accesses because the tools do not - ** account for the double-read and the memory barrier. The use of mutexes - ** here would be problematic as the memory being accessed is potentially - ** shared among multiple processes and not all mutex implementions work - ** reliably in that environment. - */ - aHdr = walIndexHdr(pWal); - memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */ - walShmBarrier(pWal); - memcpy(&h2, (void *)&aHdr[1], sizeof(h2)); - - if( memcmp(&h1, &h2, sizeof(h1))!=0 ){ - return 1; /* Dirty read */ - } - if( h1.isInit==0 ){ - return 1; /* Malformed header - probably all zeros */ - } - walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum); - if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){ - return 1; /* Checksum does not match */ - } - - if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){ - *pChanged = 1; - memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr)); - pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16); - testcase( pWal->szPage<=32768 ); - testcase( pWal->szPage>=65536 ); - } - - /* The header was successfully read. Return zero. */ - return 0; -} - -/* -** This is the value that walTryBeginRead returns when it needs to -** be retried. -*/ -#define WAL_RETRY (-1) - -/* -** Read the wal-index header from the wal-index and into pWal->hdr. -** If the wal-header appears to be corrupt, try to reconstruct the -** wal-index from the WAL before returning. -** -** Set *pChanged to 1 if the wal-index header value in pWal->hdr is -** changed by this operation. If pWal->hdr is unchanged, set *pChanged -** to 0. -** -** If the wal-index header is successfully read, return SQLITE_OK. -** Otherwise an SQLite error code. -*/ -static int walIndexReadHdr(Wal *pWal, int *pChanged){ - int rc; /* Return code */ - int badHdr; /* True if a header read failed */ - volatile u32 *page0; /* Chunk of wal-index containing header */ - - /* Ensure that page 0 of the wal-index (the page that contains the - ** wal-index header) is mapped. Return early if an error occurs here. - */ - assert( pChanged ); - rc = walIndexPage(pWal, 0, &page0); - if( rc!=SQLITE_OK ){ - assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */ - if( rc==SQLITE_READONLY_CANTINIT ){ - /* The SQLITE_READONLY_CANTINIT return means that the shared-memory - ** was openable but is not writable, and this thread is unable to - ** confirm that another write-capable connection has the shared-memory - ** open, and hence the content of the shared-memory is unreliable, - ** since the shared-memory might be inconsistent with the WAL file - ** and there is no writer on hand to fix it. */ - assert( page0==0 ); - assert( pWal->writeLock==0 ); - assert( pWal->readOnly & WAL_SHM_RDONLY ); - pWal->bShmUnreliable = 1; - pWal->exclusiveMode = WAL_HEAPMEMORY_MODE; - *pChanged = 1; - }else{ - return rc; /* Any other non-OK return is just an error */ - } - }else{ - /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock - ** is zero, which prevents the SHM from growing */ - testcase( page0!=0 ); - } - assert( page0!=0 || pWal->writeLock==0 ); - - /* If the first page of the wal-index has been mapped, try to read the - ** wal-index header immediately, without holding any lock. This usually - ** works, but may fail if the wal-index header is corrupt or currently - ** being modified by another thread or process. - */ - badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1); - - /* If the first attempt failed, it might have been due to a race - ** with a writer. So get a WRITE lock and try again. - */ - if( badHdr ){ - if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){ - if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){ - walUnlockShared(pWal, WAL_WRITE_LOCK); - rc = SQLITE_READONLY_RECOVERY; - } - }else{ - int bWriteLock = pWal->writeLock; - if( bWriteLock || SQLITE_OK==(rc = walLockWriter(pWal)) ){ - pWal->writeLock = 1; - if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){ - badHdr = walIndexTryHdr(pWal, pChanged); - if( badHdr ){ - /* If the wal-index header is still malformed even while holding - ** a WRITE lock, it can only mean that the header is corrupted and - ** needs to be reconstructed. So run recovery to do exactly that. - */ - rc = walIndexRecover(pWal); - *pChanged = 1; - } - } - if( bWriteLock==0 ){ - pWal->writeLock = 0; - walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); - } - } - } - } - - /* If the header is read successfully, check the version number to make - ** sure the wal-index was not constructed with some future format that - ** this version of SQLite cannot understand. - */ - if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){ - rc = SQLITE_CANTOPEN_BKPT; - } - if( pWal->bShmUnreliable ){ - if( rc!=SQLITE_OK ){ - walIndexClose(pWal, 0); - pWal->bShmUnreliable = 0; - assert( pWal->nWiData>0 && pWal->apWiData[0]==0 ); - /* walIndexRecover() might have returned SHORT_READ if a concurrent - ** writer truncated the WAL out from under it. If that happens, it - ** indicates that a writer has fixed the SHM file for us, so retry */ - if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY; - } - pWal->exclusiveMode = WAL_NORMAL_MODE; - } - - return rc; -} - -/* -** Open a transaction in a connection where the shared-memory is read-only -** and where we cannot verify that there is a separate write-capable connection -** on hand to keep the shared-memory up-to-date with the WAL file. -** -** This can happen, for example, when the shared-memory is implemented by -** memory-mapping a *-shm file, where a prior writer has shut down and -** left the *-shm file on disk, and now the present connection is trying -** to use that database but lacks write permission on the *-shm file. -** Other scenarios are also possible, depending on the VFS implementation. -** -** Precondition: -** -** The *-wal file has been read and an appropriate wal-index has been -** constructed in pWal->apWiData[] using heap memory instead of shared -** memory. -** -** If this function returns SQLITE_OK, then the read transaction has -** been successfully opened. In this case output variable (*pChanged) -** is set to true before returning if the caller should discard the -** contents of the page cache before proceeding. Or, if it returns -** WAL_RETRY, then the heap memory wal-index has been discarded and -** the caller should retry opening the read transaction from the -** beginning (including attempting to map the *-shm file). -** -** If an error occurs, an SQLite error code is returned. -*/ -static int walBeginShmUnreliable(Wal *pWal, int *pChanged){ - i64 szWal; /* Size of wal file on disk in bytes */ - i64 iOffset; /* Current offset when reading wal file */ - u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */ - u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */ - int szFrame; /* Number of bytes in buffer aFrame[] */ - u8 *aData; /* Pointer to data part of aFrame buffer */ - volatile void *pDummy; /* Dummy argument for xShmMap */ - int rc; /* Return code */ - u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */ - - assert( pWal->bShmUnreliable ); - assert( pWal->readOnly & WAL_SHM_RDONLY ); - assert( pWal->nWiData>0 && pWal->apWiData[0] ); - - /* Take WAL_READ_LOCK(0). This has the effect of preventing any - ** writers from running a checkpoint, but does not stop them - ** from running recovery. */ - rc = walLockShared(pWal, WAL_READ_LOCK(0)); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_BUSY ) rc = WAL_RETRY; - goto begin_unreliable_shm_out; - } - pWal->readLock = 0; - - /* Check to see if a separate writer has attached to the shared-memory area, - ** thus making the shared-memory "reliable" again. Do this by invoking - ** the xShmMap() routine of the VFS and looking to see if the return - ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT. - ** - ** If the shared-memory is now "reliable" return WAL_RETRY, which will - ** cause the heap-memory WAL-index to be discarded and the actual - ** shared memory to be used in its place. - ** - ** This step is important because, even though this connection is holding - ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might - ** have already checkpointed the WAL file and, while the current - ** is active, wrap the WAL and start overwriting frames that this - ** process wants to use. - ** - ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has - ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY - ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations, - ** even if some external agent does a "chmod" to make the shared-memory - ** writable by us, until sqlite3OsShmUnmap() has been called. - ** This is a requirement on the VFS implementation. - */ - rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy); - assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */ - if( rc!=SQLITE_READONLY_CANTINIT ){ - rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc); - goto begin_unreliable_shm_out; - } - - /* We reach this point only if the real shared-memory is still unreliable. - ** Assume the in-memory WAL-index substitute is correct and load it - ** into pWal->hdr. - */ - memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr)); - - /* Make sure some writer hasn't come in and changed the WAL file out - ** from under us, then disconnected, while we were not looking. - */ - rc = sqlite3OsFileSize(pWal->pWalFd, &szWal); - if( rc!=SQLITE_OK ){ - goto begin_unreliable_shm_out; - } - if( szWalhdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY); - goto begin_unreliable_shm_out; - } - - /* Check the salt keys at the start of the wal file still match. */ - rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0); - if( rc!=SQLITE_OK ){ - goto begin_unreliable_shm_out; - } - if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){ - /* Some writer has wrapped the WAL file while we were not looking. - ** Return WAL_RETRY which will cause the in-memory WAL-index to be - ** rebuilt. */ - rc = WAL_RETRY; - goto begin_unreliable_shm_out; - } - - /* Allocate a buffer to read frames into */ - szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE; - aFrame = (u8 *)sqlite3_malloc64(szFrame); - if( aFrame==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto begin_unreliable_shm_out; - } - aData = &aFrame[WAL_FRAME_HDRSIZE]; - - /* Check to see if a complete transaction has been appended to the - ** wal file since the heap-memory wal-index was created. If so, the - ** heap-memory wal-index is discarded and WAL_RETRY returned to - ** the caller. */ - aSaveCksum[0] = pWal->hdr.aFrameCksum[0]; - aSaveCksum[1] = pWal->hdr.aFrameCksum[1]; - for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage); - iOffset+szFrame<=szWal; - iOffset+=szFrame - ){ - u32 pgno; /* Database page number for frame */ - u32 nTruncate; /* dbsize field from frame header */ - - /* Read and decode the next log frame. */ - rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset); - if( rc!=SQLITE_OK ) break; - if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break; - - /* If nTruncate is non-zero, then a complete transaction has been - ** appended to this wal file. Set rc to WAL_RETRY and break out of - ** the loop. */ - if( nTruncate ){ - rc = WAL_RETRY; - break; - } - } - pWal->hdr.aFrameCksum[0] = aSaveCksum[0]; - pWal->hdr.aFrameCksum[1] = aSaveCksum[1]; - - begin_unreliable_shm_out: - sqlite3_free(aFrame); - if( rc!=SQLITE_OK ){ - int i; - for(i=0; inWiData; i++){ - sqlite3_free((void*)pWal->apWiData[i]); - pWal->apWiData[i] = 0; - } - pWal->bShmUnreliable = 0; - sqlite3WalEndReadTransaction(pWal); - *pChanged = 1; - } - return rc; -} - -/* -** Attempt to start a read transaction. This might fail due to a race or -** other transient condition. When that happens, it returns WAL_RETRY to -** indicate to the caller that it is safe to retry immediately. -** -** On success return SQLITE_OK. On a permanent failure (such an -** I/O error or an SQLITE_BUSY because another process is running -** recovery) return a positive error code. -** -** The useWal parameter is true to force the use of the WAL and disable -** the case where the WAL is bypassed because it has been completely -** checkpointed. If useWal==0 then this routine calls walIndexReadHdr() -** to make a copy of the wal-index header into pWal->hdr. If the -** wal-index header has changed, *pChanged is set to 1 (as an indication -** to the caller that the local page cache is obsolete and needs to be -** flushed.) When useWal==1, the wal-index header is assumed to already -** be loaded and the pChanged parameter is unused. -** -** The caller must set the cnt parameter to the number of prior calls to -** this routine during the current read attempt that returned WAL_RETRY. -** This routine will start taking more aggressive measures to clear the -** race conditions after multiple WAL_RETRY returns, and after an excessive -** number of errors will ultimately return SQLITE_PROTOCOL. The -** SQLITE_PROTOCOL return indicates that some other process has gone rogue -** and is not honoring the locking protocol. There is a vanishingly small -** chance that SQLITE_PROTOCOL could be returned because of a run of really -** bad luck when there is lots of contention for the wal-index, but that -** possibility is so small that it can be safely neglected, we believe. -** -** On success, this routine obtains a read lock on -** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is -** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1) -** that means the Wal does not hold any read lock. The reader must not -** access any database page that is modified by a WAL frame up to and -** including frame number aReadMark[pWal->readLock]. The reader will -** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0 -** Or if pWal->readLock==0, then the reader will ignore the WAL -** completely and get all content directly from the database file. -** If the useWal parameter is 1 then the WAL will never be ignored and -** this routine will always set pWal->readLock>0 on success. -** When the read transaction is completed, the caller must release the -** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1. -** -** This routine uses the nBackfill and aReadMark[] fields of the header -** to select a particular WAL_READ_LOCK() that strives to let the -** checkpoint process do as much work as possible. This routine might -** update values of the aReadMark[] array in the header, but if it does -** so it takes care to hold an exclusive lock on the corresponding -** WAL_READ_LOCK() while changing values. -*/ -static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){ - volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */ - u32 mxReadMark; /* Largest aReadMark[] value */ - int mxI; /* Index of largest aReadMark[] value */ - int i; /* Loop counter */ - int rc = SQLITE_OK; /* Return code */ - u32 mxFrame; /* Wal frame to lock to */ - - assert( pWal->readLock<0 ); /* Not currently locked */ - - /* useWal may only be set for read/write connections */ - assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 ); - - /* Take steps to avoid spinning forever if there is a protocol error. - ** - ** Circumstances that cause a RETRY should only last for the briefest - ** instances of time. No I/O or other system calls are done while the - ** locks are held, so the locks should not be held for very long. But - ** if we are unlucky, another process that is holding a lock might get - ** paged out or take a page-fault that is time-consuming to resolve, - ** during the few nanoseconds that it is holding the lock. In that case, - ** it might take longer than normal for the lock to free. - ** - ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few - ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this - ** is more of a scheduler yield than an actual delay. But on the 10th - ** an subsequent retries, the delays start becoming longer and longer, - ** so that on the 100th (and last) RETRY we delay for 323 milliseconds. - ** The total delay time before giving up is less than 10 seconds. - */ - if( cnt>5 ){ - int nDelay = 1; /* Pause time in microseconds */ - if( cnt>100 ){ - VVA_ONLY( pWal->lockError = 1; ) - return SQLITE_PROTOCOL; - } - if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39; - sqlite3OsSleep(pWal->pVfs, nDelay); - } - - if( !useWal ){ - assert( rc==SQLITE_OK ); - if( pWal->bShmUnreliable==0 ){ - rc = walIndexReadHdr(pWal, pChanged); - } - if( rc==SQLITE_BUSY ){ - /* If there is not a recovery running in another thread or process - ** then convert BUSY errors to WAL_RETRY. If recovery is known to - ** be running, convert BUSY to BUSY_RECOVERY. There is a race here - ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY - ** would be technically correct. But the race is benign since with - ** WAL_RETRY this routine will be called again and will probably be - ** right on the second iteration. - */ - if( pWal->apWiData[0]==0 ){ - /* This branch is taken when the xShmMap() method returns SQLITE_BUSY. - ** We assume this is a transient condition, so return WAL_RETRY. The - ** xShmMap() implementation used by the default unix and win32 VFS - ** modules may return SQLITE_BUSY due to a race condition in the - ** code that determines whether or not the shared-memory region - ** must be zeroed before the requested page is returned. - */ - rc = WAL_RETRY; - }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){ - walUnlockShared(pWal, WAL_RECOVER_LOCK); - rc = WAL_RETRY; - }else if( rc==SQLITE_BUSY ){ - rc = SQLITE_BUSY_RECOVERY; - } - } - if( rc!=SQLITE_OK ){ - return rc; - } - else if( pWal->bShmUnreliable ){ - return walBeginShmUnreliable(pWal, pChanged); - } - } - - assert( pWal->nWiData>0 ); - assert( pWal->apWiData[0]!=0 ); - pInfo = walCkptInfo(pWal); - if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame -#ifdef SQLITE_ENABLE_SNAPSHOT - && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0) -#endif - ){ - /* The WAL has been completely backfilled (or it is empty). - ** and can be safely ignored. - */ - rc = walLockShared(pWal, WAL_READ_LOCK(0)); - walShmBarrier(pWal); - if( rc==SQLITE_OK ){ - if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ - /* It is not safe to allow the reader to continue here if frames - ** may have been appended to the log before READ_LOCK(0) was obtained. - ** When holding READ_LOCK(0), the reader ignores the entire log file, - ** which implies that the database file contains a trustworthy - ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from - ** happening, this is usually correct. - ** - ** However, if frames have been appended to the log (or if the log - ** is wrapped and written for that matter) before the READ_LOCK(0) - ** is obtained, that is not necessarily true. A checkpointer may - ** have started to backfill the appended frames but crashed before - ** it finished. Leaving a corrupt image in the database file. - */ - walUnlockShared(pWal, WAL_READ_LOCK(0)); - return WAL_RETRY; - } - pWal->readLock = 0; - return SQLITE_OK; - }else if( rc!=SQLITE_BUSY ){ - return rc; - } - } - - /* If we get this far, it means that the reader will want to use - ** the WAL to get at content from recent commits. The job now is - ** to select one of the aReadMark[] entries that is closest to - ** but not exceeding pWal->hdr.mxFrame and lock that entry. - */ - mxReadMark = 0; - mxI = 0; - mxFrame = pWal->hdr.mxFrame; -#ifdef SQLITE_ENABLE_SNAPSHOT - if( pWal->pSnapshot && pWal->pSnapshot->mxFramepSnapshot->mxFrame; - } -#endif - for(i=1; iaReadMark+i); - if( mxReadMark<=thisMark && thisMark<=mxFrame ){ - assert( thisMark!=READMARK_NOT_USED ); - mxReadMark = thisMark; - mxI = i; - } - } - if( (pWal->readOnly & WAL_SHM_RDONLY)==0 - && (mxReadMarkaReadMark+i,mxFrame); - mxReadMark = mxFrame; - mxI = i; - walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); - break; - }else if( rc!=SQLITE_BUSY ){ - return rc; - } - } - } - if( mxI==0 ){ - assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); - return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT; - } - - rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); - if( rc ){ - return rc==SQLITE_BUSY ? WAL_RETRY : rc; - } - /* Now that the read-lock has been obtained, check that neither the - ** value in the aReadMark[] array or the contents of the wal-index - ** header have changed. - ** - ** It is necessary to check that the wal-index header did not change - ** between the time it was read and when the shared-lock was obtained - ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility - ** that the log file may have been wrapped by a writer, or that frames - ** that occur later in the log than pWal->hdr.mxFrame may have been - ** copied into the database by a checkpointer. If either of these things - ** happened, then reading the database with the current value of - ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry - ** instead. - ** - ** Before checking that the live wal-index header has not changed - ** since it was read, set Wal.minFrame to the first frame in the wal - ** file that has not yet been checkpointed. This client will not need - ** to read any frames earlier than minFrame from the wal file - they - ** can be safely read directly from the database file. - ** - ** Because a ShmBarrier() call is made between taking the copy of - ** nBackfill and checking that the wal-header in shared-memory still - ** matches the one cached in pWal->hdr, it is guaranteed that the - ** checkpointer that set nBackfill was not working with a wal-index - ** header newer than that cached in pWal->hdr. If it were, that could - ** cause a problem. The checkpointer could omit to checkpoint - ** a version of page X that lies before pWal->minFrame (call that version - ** A) on the basis that there is a newer version (version B) of the same - ** page later in the wal file. But if version B happens to like past - ** frame pWal->hdr.mxFrame - then the client would incorrectly assume - ** that it can read version A from the database file. However, since - ** we can guarantee that the checkpointer that set nBackfill could not - ** see any pages past pWal->hdr.mxFrame, this problem does not come up. - */ - pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; - walShmBarrier(pWal); - if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark - || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) - ){ - walUnlockShared(pWal, WAL_READ_LOCK(mxI)); - return WAL_RETRY; - }else{ - assert( mxReadMark<=pWal->hdr.mxFrame ); - pWal->readLock = (i16)mxI; - } - return rc; -} - -#ifdef SQLITE_ENABLE_SNAPSHOT -/* -** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted -** variable so that older snapshots can be accessed. To do this, loop -** through all wal frames from nBackfillAttempted to (nBackfill+1), -** comparing their content to the corresponding page with the database -** file, if any. Set nBackfillAttempted to the frame number of the -** first frame for which the wal file content matches the db file. -** -** This is only really safe if the file-system is such that any page -** writes made by earlier checkpointers were atomic operations, which -** is not always true. It is also possible that nBackfillAttempted -** may be left set to a value larger than expected, if a wal frame -** contains content that duplicate of an earlier version of the same -** page. -** -** SQLITE_OK is returned if successful, or an SQLite error code if an -** error occurs. It is not an error if nBackfillAttempted cannot be -** decreased at all. -*/ -SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){ - int rc; - - assert( pWal->readLock>=0 ); - rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); - if( rc==SQLITE_OK ){ - volatile WalCkptInfo *pInfo = walCkptInfo(pWal); - int szPage = (int)pWal->szPage; - i64 szDb; /* Size of db file in bytes */ - - rc = sqlite3OsFileSize(pWal->pDbFd, &szDb); - if( rc==SQLITE_OK ){ - void *pBuf1 = sqlite3_malloc(szPage); - void *pBuf2 = sqlite3_malloc(szPage); - if( pBuf1==0 || pBuf2==0 ){ - rc = SQLITE_NOMEM; - }else{ - u32 i = pInfo->nBackfillAttempted; - for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){ - WalHashLoc sLoc; /* Hash table location */ - u32 pgno; /* Page number in db file */ - i64 iDbOff; /* Offset of db file entry */ - i64 iWalOff; /* Offset of wal file entry */ - - rc = walHashGet(pWal, walFramePage(i), &sLoc); - if( rc!=SQLITE_OK ) break; - pgno = sLoc.aPgno[i-sLoc.iZero]; - iDbOff = (i64)(pgno-1) * szPage; - - if( iDbOff+szPage<=szDb ){ - iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE; - rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff); - - if( rc==SQLITE_OK ){ - rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff); - } - - if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){ - break; - } - } - - pInfo->nBackfillAttempted = i-1; - } - } - - sqlite3_free(pBuf1); - sqlite3_free(pBuf2); - } - walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); - } - - return rc; -} -#endif /* SQLITE_ENABLE_SNAPSHOT */ - -/* -** Begin a read transaction on the database. -** -** This routine used to be called sqlite3OpenSnapshot() and with good reason: -** it takes a snapshot of the state of the WAL and wal-index for the current -** instant in time. The current thread will continue to use this snapshot. -** Other threads might append new content to the WAL and wal-index but -** that extra content is ignored by the current thread. -** -** If the database contents have changes since the previous read -** transaction, then *pChanged is set to 1 before returning. The -** Pager layer will use this to know that its cache is stale and -** needs to be flushed. -*/ -SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ - int rc; /* Return code */ - int cnt = 0; /* Number of TryBeginRead attempts */ -#ifdef SQLITE_ENABLE_SNAPSHOT - int bChanged = 0; - WalIndexHdr *pSnapshot = pWal->pSnapshot; -#endif - - assert( pWal->ckptLock==0 ); - -#ifdef SQLITE_ENABLE_SNAPSHOT - if( pSnapshot ){ - if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ - bChanged = 1; - } - - /* It is possible that there is a checkpointer thread running - ** concurrent with this code. If this is the case, it may be that the - ** checkpointer has already determined that it will checkpoint - ** snapshot X, where X is later in the wal file than pSnapshot, but - ** has not yet set the pInfo->nBackfillAttempted variable to indicate - ** its intent. To avoid the race condition this leads to, ensure that - ** there is no checkpointer process by taking a shared CKPT lock - ** before checking pInfo->nBackfillAttempted. */ - (void)walEnableBlocking(pWal); - rc = walLockShared(pWal, WAL_CKPT_LOCK); - walDisableBlocking(pWal); - - if( rc!=SQLITE_OK ){ - return rc; - } - pWal->ckptLock = 1; - } -#endif - - do{ - rc = walTryBeginRead(pWal, pChanged, 0, ++cnt); - }while( rc==WAL_RETRY ); - testcase( (rc&0xff)==SQLITE_BUSY ); - testcase( (rc&0xff)==SQLITE_IOERR ); - testcase( rc==SQLITE_PROTOCOL ); - testcase( rc==SQLITE_OK ); - -#ifdef SQLITE_ENABLE_SNAPSHOT - if( rc==SQLITE_OK ){ - if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ - /* At this point the client has a lock on an aReadMark[] slot holding - ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr - ** is populated with the wal-index header corresponding to the head - ** of the wal file. Verify that pSnapshot is still valid before - ** continuing. Reasons why pSnapshot might no longer be valid: - ** - ** (1) The WAL file has been reset since the snapshot was taken. - ** In this case, the salt will have changed. - ** - ** (2) A checkpoint as been attempted that wrote frames past - ** pSnapshot->mxFrame into the database file. Note that the - ** checkpoint need not have completed for this to cause problems. - */ - volatile WalCkptInfo *pInfo = walCkptInfo(pWal); - - assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 ); - assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame ); - - /* Check that the wal file has not been wrapped. Assuming that it has - ** not, also check that no checkpointer has attempted to checkpoint any - ** frames beyond pSnapshot->mxFrame. If either of these conditions are - ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr - ** with *pSnapshot and set *pChanged as appropriate for opening the - ** snapshot. */ - if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) - && pSnapshot->mxFrame>=pInfo->nBackfillAttempted - ){ - assert( pWal->readLock>0 ); - memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr)); - *pChanged = bChanged; - }else{ - rc = SQLITE_ERROR_SNAPSHOT; - } - - /* A client using a non-current snapshot may not ignore any frames - ** from the start of the wal file. This is because, for a system - ** where (minFrame < iSnapshot < maxFrame), a checkpointer may - ** have omitted to checkpoint a frame earlier than minFrame in - ** the file because there exists a frame after iSnapshot that - ** is the same database page. */ - pWal->minFrame = 1; - - if( rc!=SQLITE_OK ){ - sqlite3WalEndReadTransaction(pWal); - } - } - } - - /* Release the shared CKPT lock obtained above. */ - if( pWal->ckptLock ){ - assert( pSnapshot ); - walUnlockShared(pWal, WAL_CKPT_LOCK); - pWal->ckptLock = 0; - } -#endif - return rc; -} - -/* -** Finish with a read transaction. All this does is release the -** read-lock. -*/ -SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){ - sqlite3WalEndWriteTransaction(pWal); - if( pWal->readLock>=0 ){ - walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); - pWal->readLock = -1; - } -} - -/* -** Search the wal file for page pgno. If found, set *piRead to the frame that -** contains the page. Otherwise, if pgno is not in the wal file, set *piRead -** to zero. -** -** Return SQLITE_OK if successful, or an error code if an error occurs. If an -** error does occur, the final value of *piRead is undefined. -*/ -SQLITE_PRIVATE int sqlite3WalFindFrame( - Wal *pWal, /* WAL handle */ - Pgno pgno, /* Database page number to read data for */ - u32 *piRead /* OUT: Frame number (or zero) */ -){ - u32 iRead = 0; /* If !=0, WAL frame to return data from */ - u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */ - int iHash; /* Used to loop through N hash tables */ - int iMinHash; - - /* This routine is only be called from within a read transaction. */ - assert( pWal->readLock>=0 || pWal->lockError ); - - /* If the "last page" field of the wal-index header snapshot is 0, then - ** no data will be read from the wal under any circumstances. Return early - ** in this case as an optimization. Likewise, if pWal->readLock==0, - ** then the WAL is ignored by the reader so return early, as if the - ** WAL were empty. - */ - if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){ - *piRead = 0; - return SQLITE_OK; - } - - /* Search the hash table or tables for an entry matching page number - ** pgno. Each iteration of the following for() loop searches one - ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames). - ** - ** This code might run concurrently to the code in walIndexAppend() - ** that adds entries to the wal-index (and possibly to this hash - ** table). This means the value just read from the hash - ** slot (aHash[iKey]) may have been added before or after the - ** current read transaction was opened. Values added after the - ** read transaction was opened may have been written incorrectly - - ** i.e. these slots may contain garbage data. However, we assume - ** that any slots written before the current read transaction was - ** opened remain unmodified. - ** - ** For the reasons above, the if(...) condition featured in the inner - ** loop of the following block is more stringent that would be required - ** if we had exclusive access to the hash-table: - ** - ** (aPgno[iFrame]==pgno): - ** This condition filters out normal hash-table collisions. - ** - ** (iFrame<=iLast): - ** This condition filters out entries that were added to the hash - ** table after the current read-transaction had started. - */ - iMinHash = walFramePage(pWal->minFrame); - for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){ - WalHashLoc sLoc; /* Hash table location */ - int iKey; /* Hash slot index */ - int nCollide; /* Number of hash collisions remaining */ - int rc; /* Error code */ - u32 iH; - - rc = walHashGet(pWal, iHash, &sLoc); - if( rc!=SQLITE_OK ){ - return rc; - } - nCollide = HASHTABLE_NSLOT; - iKey = walHash(pgno); - while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){ - u32 iFrame = iH + sLoc.iZero; - if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){ - assert( iFrame>iRead || CORRUPT_DB ); - iRead = iFrame; - } - if( (nCollide--)==0 ){ - return SQLITE_CORRUPT_BKPT; - } - iKey = walNextHash(iKey); - } - if( iRead ) break; - } - -#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT - /* If expensive assert() statements are available, do a linear search - ** of the wal-index file content. Make sure the results agree with the - ** result obtained using the hash indexes above. */ - { - u32 iRead2 = 0; - u32 iTest; - assert( pWal->bShmUnreliable || pWal->minFrame>0 ); - for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){ - if( walFramePgno(pWal, iTest)==pgno ){ - iRead2 = iTest; - break; - } - } - assert( iRead==iRead2 ); - } -#endif - - *piRead = iRead; - return SQLITE_OK; -} - -/* -** Read the contents of frame iRead from the wal file into buffer pOut -** (which is nOut bytes in size). Return SQLITE_OK if successful, or an -** error code otherwise. -*/ -SQLITE_PRIVATE int sqlite3WalReadFrame( - Wal *pWal, /* WAL handle */ - u32 iRead, /* Frame to read */ - int nOut, /* Size of buffer pOut in bytes */ - u8 *pOut /* Buffer to write page data to */ -){ - int sz; - i64 iOffset; - sz = pWal->hdr.szPage; - sz = (sz&0xfe00) + ((sz&0x0001)<<16); - testcase( sz<=32768 ); - testcase( sz>=65536 ); - iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE; - /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ - return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); -} - -/* -** Return the size of the database in pages (or zero, if unknown). -*/ -SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){ - if( pWal && ALWAYS(pWal->readLock>=0) ){ - return pWal->hdr.nPage; - } - return 0; -} - - -/* -** This function starts a write transaction on the WAL. -** -** A read transaction must have already been started by a prior call -** to sqlite3WalBeginReadTransaction(). -** -** If another thread or process has written into the database since -** the read transaction was started, then it is not possible for this -** thread to write as doing so would cause a fork. So this routine -** returns SQLITE_BUSY in that case and no write transaction is started. -** -** There can only be a single writer active at a time. -*/ -SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){ - int rc; - -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT - /* If the write-lock is already held, then it was obtained before the - ** read-transaction was even opened, making this call a no-op. - ** Return early. */ - if( pWal->writeLock ){ - assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) ); - return SQLITE_OK; - } -#endif - - /* Cannot start a write transaction without first holding a read - ** transaction. */ - assert( pWal->readLock>=0 ); - assert( pWal->writeLock==0 && pWal->iReCksum==0 ); - - if( pWal->readOnly ){ - return SQLITE_READONLY; - } - - /* Only one writer allowed at a time. Get the write lock. Return - ** SQLITE_BUSY if unable. - */ - rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1); - if( rc ){ - return rc; - } - pWal->writeLock = 1; - - /* If another connection has written to the database file since the - ** time the read transaction on this connection was started, then - ** the write is disallowed. - */ - if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){ - walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); - pWal->writeLock = 0; - rc = SQLITE_BUSY_SNAPSHOT; - } - - return rc; -} - -/* -** End a write transaction. The commit has already been done. This -** routine merely releases the lock. -*/ -SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){ - if( pWal->writeLock ){ - walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1); - pWal->writeLock = 0; - pWal->iReCksum = 0; - pWal->truncateOnCommit = 0; - } - return SQLITE_OK; -} - -/* -** If any data has been written (but not committed) to the log file, this -** function moves the write-pointer back to the start of the transaction. -** -** Additionally, the callback function is invoked for each frame written -** to the WAL since the start of the transaction. If the callback returns -** other than SQLITE_OK, it is not invoked again and the error code is -** returned to the caller. -** -** Otherwise, if the callback function does not return an error, this -** function returns SQLITE_OK. -*/ -SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){ - int rc = SQLITE_OK; - if( ALWAYS(pWal->writeLock) ){ - Pgno iMax = pWal->hdr.mxFrame; - Pgno iFrame; - - /* Restore the clients cache of the wal-index header to the state it - ** was in before the client began writing to the database. - */ - memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr)); - - for(iFrame=pWal->hdr.mxFrame+1; - ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; - iFrame++ - ){ - /* This call cannot fail. Unless the page for which the page number - ** is passed as the second argument is (a) in the cache and - ** (b) has an outstanding reference, then xUndo is either a no-op - ** (if (a) is false) or simply expels the page from the cache (if (b) - ** is false). - ** - ** If the upper layer is doing a rollback, it is guaranteed that there - ** are no outstanding references to any page other than page 1. And - ** page 1 is never written to the log until the transaction is - ** committed. As a result, the call to xUndo may not fail. - */ - assert( walFramePgno(pWal, iFrame)!=1 ); - rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame)); - } - if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal); - } - return rc; -} - -/* -** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 -** values. This function populates the array with values required to -** "rollback" the write position of the WAL handle back to the current -** point in the event of a savepoint rollback (via WalSavepointUndo()). -*/ -SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){ - assert( pWal->writeLock ); - aWalData[0] = pWal->hdr.mxFrame; - aWalData[1] = pWal->hdr.aFrameCksum[0]; - aWalData[2] = pWal->hdr.aFrameCksum[1]; - aWalData[3] = pWal->nCkpt; -} - -/* -** Move the write position of the WAL back to the point identified by -** the values in the aWalData[] array. aWalData must point to an array -** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated -** by a call to WalSavepoint(). -*/ -SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ - int rc = SQLITE_OK; - - assert( pWal->writeLock ); - assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame ); - - if( aWalData[3]!=pWal->nCkpt ){ - /* This savepoint was opened immediately after the write-transaction - ** was started. Right after that, the writer decided to wrap around - ** to the start of the log. Update the savepoint values to match. - */ - aWalData[0] = 0; - aWalData[3] = pWal->nCkpt; - } - - if( aWalData[0]hdr.mxFrame ){ - pWal->hdr.mxFrame = aWalData[0]; - pWal->hdr.aFrameCksum[0] = aWalData[1]; - pWal->hdr.aFrameCksum[1] = aWalData[2]; - walCleanupHash(pWal); - } - - return rc; -} - -/* -** This function is called just before writing a set of frames to the log -** file (see sqlite3WalFrames()). It checks to see if, instead of appending -** to the current log file, it is possible to overwrite the start of the -** existing log file with the new frames (i.e. "reset" the log). If so, -** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left -** unchanged. -** -** SQLITE_OK is returned if no error is encountered (regardless of whether -** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned -** if an error occurs. -*/ -static int walRestartLog(Wal *pWal){ - int rc = SQLITE_OK; - int cnt; - - if( pWal->readLock==0 ){ - volatile WalCkptInfo *pInfo = walCkptInfo(pWal); - assert( pInfo->nBackfill==pWal->hdr.mxFrame ); - if( pInfo->nBackfill>0 ){ - u32 salt1; - sqlite3_randomness(4, &salt1); - rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); - if( rc==SQLITE_OK ){ - /* If all readers are using WAL_READ_LOCK(0) (in other words if no - ** readers are currently using the WAL), then the transactions - ** frames will overwrite the start of the existing log. Update the - ** wal-index header to reflect this. - ** - ** In theory it would be Ok to update the cache of the header only - ** at this point. But updating the actual wal-index header is also - ** safe and means there is no special case for sqlite3WalUndo() - ** to handle if this transaction is rolled back. */ - walRestartHdr(pWal, salt1); - walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1); - }else if( rc!=SQLITE_BUSY ){ - return rc; - } - } - walUnlockShared(pWal, WAL_READ_LOCK(0)); - pWal->readLock = -1; - cnt = 0; - do{ - int notUsed; - rc = walTryBeginRead(pWal, ¬Used, 1, ++cnt); - }while( rc==WAL_RETRY ); - assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */ - testcase( (rc&0xff)==SQLITE_IOERR ); - testcase( rc==SQLITE_PROTOCOL ); - testcase( rc==SQLITE_OK ); - } - return rc; -} - -/* -** Information about the current state of the WAL file and where -** the next fsync should occur - passed from sqlite3WalFrames() into -** walWriteToLog(). -*/ -typedef struct WalWriter { - Wal *pWal; /* The complete WAL information */ - sqlite3_file *pFd; /* The WAL file to which we write */ - sqlite3_int64 iSyncPoint; /* Fsync at this offset */ - int syncFlags; /* Flags for the fsync */ - int szPage; /* Size of one page */ -} WalWriter; - -/* -** Write iAmt bytes of content into the WAL file beginning at iOffset. -** Do a sync when crossing the p->iSyncPoint boundary. -** -** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt, -** first write the part before iSyncPoint, then sync, then write the -** rest. -*/ -static int walWriteToLog( - WalWriter *p, /* WAL to write to */ - void *pContent, /* Content to be written */ - int iAmt, /* Number of bytes to write */ - sqlite3_int64 iOffset /* Start writing at this offset */ -){ - int rc; - if( iOffsetiSyncPoint && iOffset+iAmt>=p->iSyncPoint ){ - int iFirstAmt = (int)(p->iSyncPoint - iOffset); - rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset); - if( rc ) return rc; - iOffset += iFirstAmt; - iAmt -= iFirstAmt; - pContent = (void*)(iFirstAmt + (char*)pContent); - assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 ); - rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags)); - if( iAmt==0 || rc ) return rc; - } - rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset); - return rc; -} - -/* -** Write out a single frame of the WAL -*/ -static int walWriteOneFrame( - WalWriter *p, /* Where to write the frame */ - PgHdr *pPage, /* The page of the frame to be written */ - int nTruncate, /* The commit flag. Usually 0. >0 for commit */ - sqlite3_int64 iOffset /* Byte offset at which to write */ -){ - int rc; /* Result code from subfunctions */ - void *pData; /* Data actually written */ - u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */ - pData = pPage->pData; - walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame); - rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset); - if( rc ) return rc; - /* Write the page data */ - rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame)); - return rc; -} - -/* -** This function is called as part of committing a transaction within which -** one or more frames have been overwritten. It updates the checksums for -** all frames written to the wal file by the current transaction starting -** with the earliest to have been overwritten. -** -** SQLITE_OK is returned if successful, or an SQLite error code otherwise. -*/ -static int walRewriteChecksums(Wal *pWal, u32 iLast){ - const int szPage = pWal->szPage;/* Database page size */ - int rc = SQLITE_OK; /* Return code */ - u8 *aBuf; /* Buffer to load data from wal file into */ - u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */ - u32 iRead; /* Next frame to read from wal file */ - i64 iCksumOff; - - aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE); - if( aBuf==0 ) return SQLITE_NOMEM_BKPT; - - /* Find the checksum values to use as input for the recalculating the - ** first checksum. If the first frame is frame 1 (implying that the current - ** transaction restarted the wal file), these values must be read from the - ** wal-file header. Otherwise, read them from the frame header of the - ** previous frame. */ - assert( pWal->iReCksum>0 ); - if( pWal->iReCksum==1 ){ - iCksumOff = 24; - }else{ - iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16; - } - rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff); - pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf); - pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]); - - iRead = pWal->iReCksum; - pWal->iReCksum = 0; - for(; rc==SQLITE_OK && iRead<=iLast; iRead++){ - i64 iOff = walFrameOffset(iRead, szPage); - rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff); - if( rc==SQLITE_OK ){ - u32 iPgno, nDbSize; - iPgno = sqlite3Get4byte(aBuf); - nDbSize = sqlite3Get4byte(&aBuf[4]); - - walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame); - rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff); - } - } - - sqlite3_free(aBuf); - return rc; -} - -/* -** Write a set of frames to the log. The caller must hold the write-lock -** on the log file (obtained using sqlite3WalBeginWriteTransaction()). -*/ -SQLITE_PRIVATE int sqlite3WalFrames( - Wal *pWal, /* Wal handle to write to */ - int szPage, /* Database page-size in bytes */ - PgHdr *pList, /* List of dirty pages to write */ - Pgno nTruncate, /* Database size after this commit */ - int isCommit, /* True if this is a commit */ - int sync_flags /* Flags to pass to OsSync() (or 0) */ -){ - int rc; /* Used to catch return codes */ - u32 iFrame; /* Next frame address */ - PgHdr *p; /* Iterator to run through pList with. */ - PgHdr *pLast = 0; /* Last frame in list */ - int nExtra = 0; /* Number of extra copies of last page */ - int szFrame; /* The size of a single frame */ - i64 iOffset; /* Next byte to write in WAL file */ - WalWriter w; /* The writer */ - u32 iFirst = 0; /* First frame that may be overwritten */ - WalIndexHdr *pLive; /* Pointer to shared header */ - - assert( pList ); - assert( pWal->writeLock ); - - /* If this frame set completes a transaction, then nTruncate>0. If - ** nTruncate==0 then this frame set does not complete the transaction. */ - assert( (isCommit!=0)==(nTruncate!=0) ); - -#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) - { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){} - WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n", - pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill")); - } -#endif - - pLive = (WalIndexHdr*)walIndexHdr(pWal); - if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){ - iFirst = pLive->mxFrame+1; - } - - /* See if it is possible to write these frames into the start of the - ** log file, instead of appending to it at pWal->hdr.mxFrame. - */ - if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){ - return rc; - } - - /* If this is the first frame written into the log, write the WAL - ** header to the start of the WAL file. See comments at the top of - ** this source file for a description of the WAL header format. - */ - iFrame = pWal->hdr.mxFrame; - if( iFrame==0 ){ - u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */ - u32 aCksum[2]; /* Checksum for wal-header */ - - sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN)); - sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION); - sqlite3Put4byte(&aWalHdr[8], szPage); - sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt); - if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt); - memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8); - walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum); - sqlite3Put4byte(&aWalHdr[24], aCksum[0]); - sqlite3Put4byte(&aWalHdr[28], aCksum[1]); - - pWal->szPage = szPage; - pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN; - pWal->hdr.aFrameCksum[0] = aCksum[0]; - pWal->hdr.aFrameCksum[1] = aCksum[1]; - pWal->truncateOnCommit = 1; - - rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0); - WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok")); - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless - ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise - ** an out-of-order write following a WAL restart could result in - ** database corruption. See the ticket: - ** - ** https://sqlite.org/src/info/ff5be73dee - */ - if( pWal->syncHeader ){ - rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)); - if( rc ) return rc; - } - } - assert( (int)pWal->szPage==szPage ); - - /* Setup information needed to write frames into the WAL */ - w.pWal = pWal; - w.pFd = pWal->pWalFd; - w.iSyncPoint = 0; - w.syncFlags = sync_flags; - w.szPage = szPage; - iOffset = walFrameOffset(iFrame+1, szPage); - szFrame = szPage + WAL_FRAME_HDRSIZE; - - /* Write all frames into the log file exactly once */ - for(p=pList; p; p=p->pDirty){ - int nDbSize; /* 0 normally. Positive == commit flag */ - - /* Check if this page has already been written into the wal file by - ** the current transaction. If so, overwrite the existing frame and - ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that - ** checksums must be recomputed when the transaction is committed. */ - if( iFirst && (p->pDirty || isCommit==0) ){ - u32 iWrite = 0; - VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite); - assert( rc==SQLITE_OK || iWrite==0 ); - if( iWrite>=iFirst ){ - i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE; - void *pData; - if( pWal->iReCksum==0 || iWriteiReCksum ){ - pWal->iReCksum = iWrite; - } - pData = p->pData; - rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff); - if( rc ) return rc; - p->flags &= ~PGHDR_WAL_APPEND; - continue; - } - } - - iFrame++; - assert( iOffset==walFrameOffset(iFrame, szPage) ); - nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0; - rc = walWriteOneFrame(&w, p, nDbSize, iOffset); - if( rc ) return rc; - pLast = p; - iOffset += szFrame; - p->flags |= PGHDR_WAL_APPEND; - } - - /* Recalculate checksums within the wal file if required. */ - if( isCommit && pWal->iReCksum ){ - rc = walRewriteChecksums(pWal, iFrame); - if( rc ) return rc; - } - - /* If this is the end of a transaction, then we might need to pad - ** the transaction and/or sync the WAL file. - ** - ** Padding and syncing only occur if this set of frames complete a - ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL - ** or synchronous==OFF, then no padding or syncing are needed. - ** - ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not - ** needed and only the sync is done. If padding is needed, then the - ** final frame is repeated (with its commit mark) until the next sector - ** boundary is crossed. Only the part of the WAL prior to the last - ** sector boundary is synced; the part of the last frame that extends - ** past the sector boundary is written after the sync. - */ - if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){ - int bSync = 1; - if( pWal->padToSectorBoundary ){ - int sectorSize = sqlite3SectorSize(pWal->pWalFd); - w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize; - bSync = (w.iSyncPoint==iOffset); - testcase( bSync ); - while( iOffsettruncateOnCommit && pWal->mxWalSize>=0 ){ - i64 sz = pWal->mxWalSize; - if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){ - sz = walFrameOffset(iFrame+nExtra+1, szPage); - } - walLimitSize(pWal, sz); - pWal->truncateOnCommit = 0; - } - - /* Append data to the wal-index. It is not necessary to lock the - ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index - ** guarantees that there are no other writers, and no data that may - ** be in use by existing readers is being overwritten. - */ - iFrame = pWal->hdr.mxFrame; - for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){ - if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue; - iFrame++; - rc = walIndexAppend(pWal, iFrame, p->pgno); - } - assert( pLast!=0 || nExtra==0 ); - while( rc==SQLITE_OK && nExtra>0 ){ - iFrame++; - nExtra--; - rc = walIndexAppend(pWal, iFrame, pLast->pgno); - } - - if( rc==SQLITE_OK ){ - /* Update the private copy of the header. */ - pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16)); - testcase( szPage<=32768 ); - testcase( szPage>=65536 ); - pWal->hdr.mxFrame = iFrame; - if( isCommit ){ - pWal->hdr.iChange++; - pWal->hdr.nPage = nTruncate; - } - /* If this is a commit, update the wal-index header too. */ - if( isCommit ){ - walIndexWriteHdr(pWal); - pWal->iCallback = iFrame; - } - } - - WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok")); - return rc; -} - -/* -** This routine is called to implement sqlite3_wal_checkpoint() and -** related interfaces. -** -** Obtain a CHECKPOINT lock and then backfill as much information as -** we can from WAL into the database. -** -** If parameter xBusy is not NULL, it is a pointer to a busy-handler -** callback. In this case this function runs a blocking checkpoint. -*/ -SQLITE_PRIVATE int sqlite3WalCheckpoint( - Wal *pWal, /* Wal connection */ - sqlite3 *db, /* Check this handle's interrupt flag */ - int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */ - int (*xBusy)(void*), /* Function to call when busy */ - void *pBusyArg, /* Context argument for xBusyHandler */ - int sync_flags, /* Flags to sync db file with (or 0) */ - int nBuf, /* Size of temporary buffer */ - u8 *zBuf, /* Temporary buffer to use */ - int *pnLog, /* OUT: Number of frames in WAL */ - int *pnCkpt /* OUT: Number of backfilled frames in WAL */ -){ - int rc; /* Return code */ - int isChanged = 0; /* True if a new wal-index header is loaded */ - int eMode2 = eMode; /* Mode to pass to walCheckpoint() */ - int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */ - - assert( pWal->ckptLock==0 ); - assert( pWal->writeLock==0 ); - - /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked - ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ - assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); - - if( pWal->readOnly ) return SQLITE_READONLY; - WALTRACE(("WAL%p: checkpoint begins\n", pWal)); - - /* Enable blocking locks, if possible. If blocking locks are successfully - ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */ - sqlite3WalDb(pWal, db); - (void)walEnableBlocking(pWal); - - /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive - ** "checkpoint" lock on the database file. - ** EVIDENCE-OF: R-10421-19736 If any other process is running a - ** checkpoint operation at the same time, the lock cannot be obtained and - ** SQLITE_BUSY is returned. - ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured, - ** it will not be invoked in this case. - */ - rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); - testcase( rc==SQLITE_BUSY ); - testcase( rc!=SQLITE_OK && xBusy2!=0 ); - if( rc==SQLITE_OK ){ - pWal->ckptLock = 1; - - /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and - ** TRUNCATE modes also obtain the exclusive "writer" lock on the database - ** file. - ** - ** EVIDENCE-OF: R-60642-04082 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. - */ - if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){ - rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1); - if( rc==SQLITE_OK ){ - pWal->writeLock = 1; - }else if( rc==SQLITE_BUSY ){ - eMode2 = SQLITE_CHECKPOINT_PASSIVE; - xBusy2 = 0; - rc = SQLITE_OK; - } - } - } - - - /* Read the wal-index header. */ - if( rc==SQLITE_OK ){ - walDisableBlocking(pWal); - rc = walIndexReadHdr(pWal, &isChanged); - (void)walEnableBlocking(pWal); - if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ - sqlite3OsUnfetch(pWal->pDbFd, 0, 0); - } - } - - /* Copy data from the log to the database file. */ - if( rc==SQLITE_OK ){ - - if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ - rc = SQLITE_CORRUPT_BKPT; - }else{ - rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf); - } - - /* If no error occurred, set the output variables. */ - if( rc==SQLITE_OK || rc==SQLITE_BUSY ){ - if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame; - if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill); - } - } - - if( isChanged ){ - /* If a new wal-index header was loaded before the checkpoint was - ** performed, then the pager-cache associated with pWal is now - ** out of date. So zero the cached wal-index header to ensure that - ** next time the pager opens a snapshot on this database it knows that - ** the cache needs to be reset. - */ - memset(&pWal->hdr, 0, sizeof(WalIndexHdr)); - } - - walDisableBlocking(pWal); - sqlite3WalDb(pWal, 0); - - /* Release the locks. */ - sqlite3WalEndWriteTransaction(pWal); - if( pWal->ckptLock ){ - walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); - pWal->ckptLock = 0; - } - WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT - if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY; -#endif - return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc); -} - -/* Return the value to pass to a sqlite3_wal_hook callback, the -** number of frames in the WAL at the point of the last commit since -** sqlite3WalCallback() was called. If no commits have occurred since -** the last call, then return 0. -*/ -SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){ - u32 ret = 0; - if( pWal ){ - ret = pWal->iCallback; - pWal->iCallback = 0; - } - return (int)ret; -} - -/* -** This function is called to change the WAL subsystem into or out -** of locking_mode=EXCLUSIVE. -** -** If op is zero, then attempt to change from locking_mode=EXCLUSIVE -** into locking_mode=NORMAL. This means that we must acquire a lock -** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL -** or if the acquisition of the lock fails, then return 0. If the -** transition out of exclusive-mode is successful, return 1. This -** operation must occur while the pager is still holding the exclusive -** lock on the main database file. -** -** If op is one, then change from locking_mode=NORMAL into -** locking_mode=EXCLUSIVE. This means that the pWal->readLock must -** be released. Return 1 if the transition is made and 0 if the -** WAL is already in exclusive-locking mode - meaning that this -** routine is a no-op. The pager must already hold the exclusive lock -** on the main database file before invoking this operation. -** -** If op is negative, then do a dry-run of the op==1 case but do -** not actually change anything. The pager uses this to see if it -** should acquire the database exclusive lock prior to invoking -** the op==1 case. -*/ -SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){ - int rc; - assert( pWal->writeLock==0 ); - assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 ); - - /* pWal->readLock is usually set, but might be -1 if there was a - ** prior error while attempting to acquire are read-lock. This cannot - ** happen if the connection is actually in exclusive mode (as no xShmLock - ** locks are taken in this case). Nor should the pager attempt to - ** upgrade to exclusive-mode following such an error. - */ - assert( pWal->readLock>=0 || pWal->lockError ); - assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) ); - - if( op==0 ){ - if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){ - pWal->exclusiveMode = WAL_NORMAL_MODE; - if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){ - pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; - } - rc = pWal->exclusiveMode==WAL_NORMAL_MODE; - }else{ - /* Already in locking_mode=NORMAL */ - rc = 0; - } - }else if( op>0 ){ - assert( pWal->exclusiveMode==WAL_NORMAL_MODE ); - assert( pWal->readLock>=0 ); - walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); - pWal->exclusiveMode = WAL_EXCLUSIVE_MODE; - rc = 1; - }else{ - rc = pWal->exclusiveMode==WAL_NORMAL_MODE; - } - return rc; -} - -/* -** Return true if the argument is non-NULL and the WAL module is using -** heap-memory for the wal-index. Otherwise, if the argument is NULL or the -** WAL module is using shared-memory, return false. -*/ -SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){ - return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ); -} - -#ifdef SQLITE_ENABLE_SNAPSHOT -/* Create a snapshot object. The content of a snapshot is opaque to -** every other subsystem, so the WAL module can put whatever it needs -** in the object. -*/ -SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){ - int rc = SQLITE_OK; - WalIndexHdr *pRet; - static const u32 aZero[4] = { 0, 0, 0, 0 }; - - assert( pWal->readLock>=0 && pWal->writeLock==0 ); - - if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){ - *ppSnapshot = 0; - return SQLITE_ERROR; - } - pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr)); - if( pRet==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr)); - *ppSnapshot = (sqlite3_snapshot*)pRet; - } - - return rc; -} - -/* Try to open on pSnapshot when the next read-transaction starts -*/ -SQLITE_PRIVATE void sqlite3WalSnapshotOpen( - Wal *pWal, - sqlite3_snapshot *pSnapshot -){ - pWal->pSnapshot = (WalIndexHdr*)pSnapshot; -} - -/* -** Return a +ve value if snapshot p1 is newer than p2. A -ve value if -** p1 is older than p2 and zero if p1 and p2 are the same snapshot. -*/ -SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){ - WalIndexHdr *pHdr1 = (WalIndexHdr*)p1; - WalIndexHdr *pHdr2 = (WalIndexHdr*)p2; - - /* aSalt[0] is a copy of the value stored in the wal file header. It - ** is incremented each time the wal file is restarted. */ - if( pHdr1->aSalt[0]aSalt[0] ) return -1; - if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1; - if( pHdr1->mxFramemxFrame ) return -1; - if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1; - return 0; -} - -/* -** The caller currently has a read transaction open on the database. -** This function takes a SHARED lock on the CHECKPOINTER slot and then -** checks if the snapshot passed as the second argument is still -** available. If so, SQLITE_OK is returned. -** -** If the snapshot is not available, SQLITE_ERROR is returned. Or, if -** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error -** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER -** lock is released before returning. -*/ -SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){ - int rc; - rc = walLockShared(pWal, WAL_CKPT_LOCK); - if( rc==SQLITE_OK ){ - WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot; - if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)) - || pNew->mxFramenBackfillAttempted - ){ - rc = SQLITE_ERROR_SNAPSHOT; - walUnlockShared(pWal, WAL_CKPT_LOCK); - } - } - return rc; -} - -/* -** Release a lock obtained by an earlier successful call to -** sqlite3WalSnapshotCheck(). -*/ -SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){ - assert( pWal ); - walUnlockShared(pWal, WAL_CKPT_LOCK); -} - - -#endif /* SQLITE_ENABLE_SNAPSHOT */ - -#ifdef SQLITE_ENABLE_ZIPVFS -/* -** If the argument is not NULL, it points to a Wal object that holds a -** read-lock. This function returns the database page-size if it is known, -** or zero if it is not (or if pWal is NULL). -*/ -SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){ - assert( pWal==0 || pWal->readLock>=0 ); - return (pWal ? pWal->szPage : 0); -} -#endif - -/* Return the sqlite3_file object for the WAL file -*/ -SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){ - return pWal->pWalFd; -} - -#endif /* #ifndef SQLITE_OMIT_WAL */ - -/************** End of wal.c *************************************************/ -/************** Begin file btmutex.c *****************************************/ -/* -** 2007 August 27 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains code used to implement mutexes on Btree objects. -** This code really belongs in btree.c. But btree.c is getting too -** big and we want to break it down some. This packaged seemed like -** a good breakout. -*/ -/************** Include btreeInt.h in the middle of btmutex.c ****************/ -/************** Begin file btreeInt.h ****************************************/ -/* -** 2004 April 6 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file implements an external (disk-based) database using BTrees. -** For a detailed discussion of BTrees, refer to -** -** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: -** "Sorting And Searching", pages 473-480. Addison-Wesley -** Publishing Company, Reading, Massachusetts. -** -** The basic idea is that each page of the file contains N database -** entries and N+1 pointers to subpages. -** -** ---------------------------------------------------------------- -** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) | -** ---------------------------------------------------------------- -** -** All of the keys on the page that Ptr(0) points to have values less -** than Key(0). All of the keys on page Ptr(1) and its subpages have -** values greater than Key(0) and less than Key(1). All of the keys -** on Ptr(N) and its subpages have values greater than Key(N-1). And -** so forth. -** -** Finding a particular key requires reading O(log(M)) pages from the -** disk where M is the number of entries in the tree. -** -** In this implementation, a single file can hold one or more separate -** BTrees. Each BTree is identified by the index of its root page. The -** key and data for any entry are combined to form the "payload". A -** fixed amount of payload can be carried directly on the database -** page. If the payload is larger than the preset amount then surplus -** bytes are stored on overflow pages. The payload for an entry -** and the preceding pointer are combined to form a "Cell". Each -** page has a small header which contains the Ptr(N) pointer and other -** information such as the size of key and data. -** -** FORMAT DETAILS -** -** The file is divided into pages. The first page is called page 1, -** the second is page 2, and so forth. A page number of zero indicates -** "no such page". The page size can be any power of 2 between 512 and 65536. -** Each page can be either a btree page, a freelist page, an overflow -** page, or a pointer-map page. -** -** The first page is always a btree page. The first 100 bytes of the first -** page contain a special header (the "file header") that describes the file. -** The format of the file header is as follows: -** -** OFFSET SIZE DESCRIPTION -** 0 16 Header string: "SQLite format 3\000" -** 16 2 Page size in bytes. (1 means 65536) -** 18 1 File format write version -** 19 1 File format read version -** 20 1 Bytes of unused space at the end of each page -** 21 1 Max embedded payload fraction (must be 64) -** 22 1 Min embedded payload fraction (must be 32) -** 23 1 Min leaf payload fraction (must be 32) -** 24 4 File change counter -** 28 4 Reserved for future use -** 32 4 First freelist page -** 36 4 Number of freelist pages in the file -** 40 60 15 4-byte meta values passed to higher layers -** -** 40 4 Schema cookie -** 44 4 File format of schema layer -** 48 4 Size of page cache -** 52 4 Largest root-page (auto/incr_vacuum) -** 56 4 1=UTF-8 2=UTF16le 3=UTF16be -** 60 4 User version -** 64 4 Incremental vacuum mode -** 68 4 Application-ID -** 72 20 unused -** 92 4 The version-valid-for number -** 96 4 SQLITE_VERSION_NUMBER -** -** All of the integer values are big-endian (most significant byte first). -** -** The file change counter is incremented when the database is changed -** This counter allows other processes to know when the file has changed -** and thus when they need to flush their cache. -** -** The max embedded payload fraction is the amount of the total usable -** space in a page that can be consumed by a single cell for standard -** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default -** is to limit the maximum cell size so that at least 4 cells will fit -** on one page. Thus the default max embedded payload fraction is 64. -** -** If the payload for a cell is larger than the max payload, then extra -** payload is spilled to overflow pages. Once an overflow page is allocated, -** as many bytes as possible are moved into the overflow pages without letting -** the cell size drop below the min embedded payload fraction. -** -** The min leaf payload fraction is like the min embedded payload fraction -** except that it applies to leaf nodes in a LEAFDATA tree. The maximum -** payload fraction for a LEAFDATA tree is always 100% (or 255) and it -** not specified in the header. -** -** Each btree pages is divided into three sections: The header, the -** cell pointer array, and the cell content area. Page 1 also has a 100-byte -** file header that occurs before the page header. -** -** |----------------| -** | file header | 100 bytes. Page 1 only. -** |----------------| -** | page header | 8 bytes for leaves. 12 bytes for interior nodes -** |----------------| -** | cell pointer | | 2 bytes per cell. Sorted order. -** | array | | Grows downward -** | | v -** |----------------| -** | unallocated | -** | space | -** |----------------| ^ Grows upwards -** | cell content | | Arbitrary order interspersed with freeblocks. -** | area | | and free space fragments. -** |----------------| -** -** The page headers looks like this: -** -** OFFSET SIZE DESCRIPTION -** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf -** 1 2 byte offset to the first freeblock -** 3 2 number of cells on this page -** 5 2 first byte of the cell content area -** 7 1 number of fragmented free bytes -** 8 4 Right child (the Ptr(N) value). Omitted on leaves. -** -** The flags define the format of this btree page. The leaf flag means that -** this page has no children. The zerodata flag means that this page carries -** only keys and no data. The intkey flag means that the key is an integer -** which is stored in the key size entry of the cell header rather than in -** the payload area. -** -** The cell pointer array begins on the first byte after the page header. -** The cell pointer array contains zero or more 2-byte numbers which are -** offsets from the beginning of the page to the cell content in the cell -** content area. The cell pointers occur in sorted order. The system strives -** to keep free space after the last cell pointer so that new cells can -** be easily added without having to defragment the page. -** -** Cell content is stored at the very end of the page and grows toward the -** beginning of the page. -** -** Unused space within the cell content area is collected into a linked list of -** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset -** to the first freeblock is given in the header. Freeblocks occur in -** increasing order. Because a freeblock must be at least 4 bytes in size, -** any group of 3 or fewer unused bytes in the cell content area cannot -** exist on the freeblock chain. A group of 3 or fewer free bytes is called -** a fragment. The total number of bytes in all fragments is recorded. -** in the page header at offset 7. -** -** SIZE DESCRIPTION -** 2 Byte offset of the next freeblock -** 2 Bytes in this freeblock -** -** Cells are of variable length. Cells are stored in the cell content area at -** the end of the page. Pointers to the cells are in the cell pointer array -** that immediately follows the page header. Cells is not necessarily -** contiguous or in order, but cell pointers are contiguous and in order. -** -** Cell content makes use of variable length integers. A variable -** length integer is 1 to 9 bytes where the lower 7 bits of each -** byte are used. The integer consists of all bytes that have bit 8 set and -** the first byte with bit 8 clear. The most significant byte of the integer -** appears first. A variable-length integer may not be more than 9 bytes long. -** As a special case, all 8 bytes of the 9th byte are used as data. This -** allows a 64-bit integer to be encoded in 9 bytes. -** -** 0x00 becomes 0x00000000 -** 0x7f becomes 0x0000007f -** 0x81 0x00 becomes 0x00000080 -** 0x82 0x00 becomes 0x00000100 -** 0x80 0x7f becomes 0x0000007f -** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678 -** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081 -** -** Variable length integers are used for rowids and to hold the number of -** bytes of key and data in a btree cell. -** -** The content of a cell looks like this: -** -** SIZE DESCRIPTION -** 4 Page number of the left child. Omitted if leaf flag is set. -** var Number of bytes of data. Omitted if the zerodata flag is set. -** var Number of bytes of key. Or the key itself if intkey flag is set. -** * Payload -** 4 First page of the overflow chain. Omitted if no overflow -** -** Overflow pages form a linked list. Each page except the last is completely -** filled with data (pagesize - 4 bytes). The last page can have as little -** as 1 byte of data. -** -** SIZE DESCRIPTION -** 4 Page number of next overflow page -** * Data -** -** Freelist pages come in two subtypes: trunk pages and leaf pages. The -** file header points to the first in a linked list of trunk page. Each trunk -** page points to multiple leaf pages. The content of a leaf page is -** unspecified. A trunk page looks like this: -** -** SIZE DESCRIPTION -** 4 Page number of next trunk page -** 4 Number of leaf pointers on this page -** * zero or more pages numbers of leaves -*/ -/* #include "sqliteInt.h" */ - - -/* The following value is the maximum cell size assuming a maximum page -** size give above. -*/ -#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8)) - -/* The maximum number of cells on a single page of the database. This -** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself -** plus 2 bytes for the index to the cell in the page header). Such -** small cells will be rare, but they are possible. -*/ -#define MX_CELL(pBt) ((pBt->pageSize-8)/6) - -/* Forward declarations */ -typedef struct MemPage MemPage; -typedef struct BtLock BtLock; -typedef struct CellInfo CellInfo; - -/* -** This is a magic string that appears at the beginning of every -** SQLite database in order to identify the file as a real database. -** -** You can change this value at compile-time by specifying a -** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The -** header must be exactly 16 bytes including the zero-terminator so -** the string itself should be 15 characters long. If you change -** the header, then your custom library will not be able to read -** databases generated by the standard tools and the standard tools -** will not be able to read databases created by your custom library. -*/ -#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */ -# define SQLITE_FILE_HEADER "SQLite format 3" -#endif - -/* -** Page type flags. An ORed combination of these flags appear as the -** first byte of on-disk image of every BTree page. -*/ -#define PTF_INTKEY 0x01 -#define PTF_ZERODATA 0x02 -#define PTF_LEAFDATA 0x04 -#define PTF_LEAF 0x08 - -/* -** An instance of this object stores information about each a single database -** page that has been loaded into memory. The information in this object -** is derived from the raw on-disk page content. -** -** As each database page is loaded into memory, the pager allocats an -** instance of this object and zeros the first 8 bytes. (This is the -** "extra" information associated with each page of the pager.) -** -** Access to all fields of this structure is controlled by the mutex -** stored in MemPage.pBt->mutex. -*/ -struct MemPage { - u8 isInit; /* True if previously initialized. MUST BE FIRST! */ - u8 bBusy; /* Prevent endless loops on corrupt database files */ - u8 intKey; /* True if table b-trees. False for index b-trees */ - u8 intKeyLeaf; /* True if the leaf of an intKey table */ - Pgno pgno; /* Page number for this page */ - /* Only the first 8 bytes (above) are zeroed by pager.c when a new page - ** is allocated. All fields that follow must be initialized before use */ - u8 leaf; /* True if a leaf page */ - u8 hdrOffset; /* 100 for page 1. 0 otherwise */ - u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */ - u8 max1bytePayload; /* min(maxLocal,127) */ - u8 nOverflow; /* Number of overflow cell bodies in aCell[] */ - u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */ - u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */ - u16 cellOffset; /* Index in aData of first cell pointer */ - int nFree; /* Number of free bytes on the page. -1 for unknown */ - u16 nCell; /* Number of cells on this page, local and ovfl */ - u16 maskPage; /* Mask for page offset */ - u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th - ** non-overflow cell */ - u8 *apOvfl[4]; /* Pointers to the body of overflow cells */ - BtShared *pBt; /* Pointer to BtShared that this page is part of */ - u8 *aData; /* Pointer to disk image of the page data */ - u8 *aDataEnd; /* One byte past the end of usable data */ - u8 *aCellIdx; /* The cell index area */ - u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */ - DbPage *pDbPage; /* Pager page handle */ - u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */ - void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */ -}; - -/* -** A linked list of the following structures is stored at BtShared.pLock. -** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor -** is opened on the table with root page BtShared.iTable. Locks are removed -** from this list when a transaction is committed or rolled back, or when -** a btree handle is closed. -*/ -struct BtLock { - Btree *pBtree; /* Btree handle holding this lock */ - Pgno iTable; /* Root page of table */ - u8 eLock; /* READ_LOCK or WRITE_LOCK */ - BtLock *pNext; /* Next in BtShared.pLock list */ -}; - -/* Candidate values for BtLock.eLock */ -#define READ_LOCK 1 -#define WRITE_LOCK 2 - -/* A Btree handle -** -** A database connection contains a pointer to an instance of -** this object for every database file that it has open. This structure -** is opaque to the database connection. The database connection cannot -** see the internals of this structure and only deals with pointers to -** this structure. -** -** For some database files, the same underlying database cache might be -** shared between multiple connections. In that case, each connection -** has it own instance of this object. But each instance of this object -** points to the same BtShared object. The database cache and the -** schema associated with the database file are all contained within -** the BtShared object. -** -** All fields in this structure are accessed under sqlite3.mutex. -** The pBt pointer itself may not be changed while there exists cursors -** in the referenced BtShared that point back to this Btree since those -** cursors have to go through this Btree to find their BtShared and -** they often do so without holding sqlite3.mutex. -*/ -struct Btree { - sqlite3 *db; /* The database connection holding this btree */ - BtShared *pBt; /* Sharable content of this btree */ - u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ - u8 sharable; /* True if we can share pBt with another db */ - u8 locked; /* True if db currently has pBt locked */ - u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */ - int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ - int nBackup; /* Number of backup operations reading this btree */ - u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */ - Btree *pNext; /* List of other sharable Btrees from the same db */ - Btree *pPrev; /* Back pointer of the same list */ -#ifndef SQLITE_OMIT_SHARED_CACHE - BtLock lock; /* Object used to lock page 1 */ -#endif -}; - -/* -** Btree.inTrans may take one of the following values. -** -** If the shared-data extension is enabled, there may be multiple users -** of the Btree structure. At most one of these may open a write transaction, -** but any number may have active read transactions. -*/ -#define TRANS_NONE 0 -#define TRANS_READ 1 -#define TRANS_WRITE 2 - -/* -** An instance of this object represents a single database file. -** -** A single database file can be in use at the same time by two -** or more database connections. When two or more connections are -** sharing the same database file, each connection has it own -** private Btree object for the file and each of those Btrees points -** to this one BtShared object. BtShared.nRef is the number of -** connections currently sharing this database file. -** -** Fields in this structure are accessed under the BtShared.mutex -** mutex, except for nRef and pNext which are accessed under the -** global SQLITE_MUTEX_STATIC_MAIN mutex. The pPager field -** may not be modified once it is initially set as long as nRef>0. -** The pSchema field may be set once under BtShared.mutex and -** thereafter is unchanged as long as nRef>0. -** -** isPending: -** -** If a BtShared client fails to obtain a write-lock on a database -** table (because there exists one or more read-locks on the table), -** the shared-cache enters 'pending-lock' state and isPending is -** set to true. -** -** The shared-cache leaves the 'pending lock' state when either of -** the following occur: -** -** 1) The current writer (BtShared.pWriter) concludes its transaction, OR -** 2) The number of locks held by other connections drops to zero. -** -** while in the 'pending-lock' state, no connection may start a new -** transaction. -** -** This feature is included to help prevent writer-starvation. -*/ -struct BtShared { - Pager *pPager; /* The page cache */ - sqlite3 *db; /* Database connection currently using this Btree */ - BtCursor *pCursor; /* A list of all open cursors */ - MemPage *pPage1; /* First page of the database */ - u8 openFlags; /* Flags to sqlite3BtreeOpen() */ -#ifndef SQLITE_OMIT_AUTOVACUUM - u8 autoVacuum; /* True if auto-vacuum is enabled */ - u8 incrVacuum; /* True if incr-vacuum is enabled */ - u8 bDoTruncate; /* True to truncate db on commit */ -#endif - u8 inTransaction; /* Transaction state */ - u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */ - u8 nReserveWanted; /* Desired number of extra bytes per page */ - u16 btsFlags; /* Boolean parameters. See BTS_* macros below */ - u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ - u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */ - u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */ - u16 minLeaf; /* Minimum local payload in a LEAFDATA table */ - u32 pageSize; /* Total number of bytes on a page */ - u32 usableSize; /* Number of usable bytes on each page */ - int nTransaction; /* Number of open transactions (read + write) */ - u32 nPage; /* Number of pages in the database */ - void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ - void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ - sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */ - Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */ -#ifndef SQLITE_OMIT_SHARED_CACHE - int nRef; /* Number of references to this structure */ - BtShared *pNext; /* Next on a list of sharable BtShared structs */ - BtLock *pLock; /* List of locks held on this shared-btree struct */ - Btree *pWriter; /* Btree with currently open write transaction */ -#endif - u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */ -}; - -/* -** Allowed values for BtShared.btsFlags -*/ -#define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */ -#define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */ -#define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */ -#define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */ -#define BTS_FAST_SECURE 0x000c /* Combination of the previous two */ -#define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */ -#define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */ -#define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */ -#define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */ - -/* -** An instance of the following structure is used to hold information -** about a cell. The parseCellPtr() function fills in this structure -** based on information extract from the raw disk page. -*/ -struct CellInfo { - i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */ - u8 *pPayload; /* Pointer to the start of payload */ - u32 nPayload; /* Bytes of payload */ - u16 nLocal; /* Amount of payload held locally, not on overflow */ - u16 nSize; /* Size of the cell content on the main b-tree page */ -}; - -/* -** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than -** this will be declared corrupt. This value is calculated based on a -** maximum database size of 2^31 pages a minimum fanout of 2 for a -** root-node and 3 for all other internal nodes. -** -** If a tree that appears to be taller than this is encountered, it is -** assumed that the database is corrupt. -*/ -#define BTCURSOR_MAX_DEPTH 20 - -/* -** A cursor is a pointer to a particular entry within a particular -** b-tree within a database file. -** -** The entry is identified by its MemPage and the index in -** MemPage.aCell[] of the entry. -** -** A single database file can be shared by two more database connections, -** but cursors cannot be shared. Each cursor is associated with a -** particular database connection identified BtCursor.pBtree.db. -** -** Fields in this structure are accessed under the BtShared.mutex -** found at self->pBt->mutex. -** -** skipNext meaning: -** The meaning of skipNext depends on the value of eState: -** -** eState Meaning of skipNext -** VALID skipNext is meaningless and is ignored -** INVALID skipNext is meaningless and is ignored -** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and -** sqlite3BtreePrevious() is no-op if skipNext<0. -** REQUIRESEEK restoreCursorPosition() restores the cursor to -** eState=SKIPNEXT if skipNext!=0 -** FAULT skipNext holds the cursor fault error code. -*/ -struct BtCursor { - u8 eState; /* One of the CURSOR_XXX constants (see below) */ - u8 curFlags; /* zero or more BTCF_* flags defined below */ - u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */ - u8 hints; /* As configured by CursorSetHints() */ - int skipNext; /* Prev() is noop if negative. Next() is noop if positive. - ** Error code if eState==CURSOR_FAULT */ - Btree *pBtree; /* The Btree to which this cursor belongs */ - Pgno *aOverflow; /* Cache of overflow page locations */ - void *pKey; /* Saved key that was cursor last known position */ - /* All fields above are zeroed when the cursor is allocated. See - ** sqlite3BtreeCursorZero(). Fields that follow must be manually - ** initialized. */ -#define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */ - BtShared *pBt; /* The BtShared this cursor points to */ - BtCursor *pNext; /* Forms a linked list of all cursors */ - CellInfo info; /* A parse of the cell we are pointing at */ - i64 nKey; /* Size of pKey, or last integer key */ - Pgno pgnoRoot; /* The root page of this tree */ - i8 iPage; /* Index of current page in apPage */ - u8 curIntKey; /* Value of apPage[0]->intKey */ - u16 ix; /* Current index for apPage[iPage] */ - u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */ - struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */ - MemPage *pPage; /* Current page */ - MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */ -}; - -/* -** Legal values for BtCursor.curFlags -*/ -#define BTCF_WriteFlag 0x01 /* True if a write cursor */ -#define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */ -#define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */ -#define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */ -#define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */ -#define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */ -#define BTCF_Pinned 0x40 /* Cursor is busy and cannot be moved */ - -/* -** Potential values for BtCursor.eState. -** -** CURSOR_INVALID: -** Cursor does not point to a valid entry. This can happen (for example) -** because the table is empty or because BtreeCursorFirst() has not been -** called. -** -** CURSOR_VALID: -** Cursor points to a valid entry. getPayload() etc. may be called. -** -** CURSOR_SKIPNEXT: -** Cursor is valid except that the Cursor.skipNext field is non-zero -** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious() -** operation should be a no-op. -** -** CURSOR_REQUIRESEEK: -** The table that this cursor was opened on still exists, but has been -** modified since the cursor was last used. The cursor position is saved -** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in -** this state, restoreCursorPosition() can be called to attempt to -** seek the cursor to the saved position. -** -** CURSOR_FAULT: -** An unrecoverable error (an I/O error or a malloc failure) has occurred -** on a different connection that shares the BtShared cache with this -** cursor. The error has left the cache in an inconsistent state. -** Do nothing else with this cursor. Any attempt to use the cursor -** should return the error code stored in BtCursor.skipNext -*/ -#define CURSOR_VALID 0 -#define CURSOR_INVALID 1 -#define CURSOR_SKIPNEXT 2 -#define CURSOR_REQUIRESEEK 3 -#define CURSOR_FAULT 4 - -/* -** The database page the PENDING_BYTE occupies. This page is never used. -*/ -# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt) - -/* -** These macros define the location of the pointer-map entry for a -** database page. The first argument to each is the number of usable -** bytes on each page of the database (often 1024). The second is the -** page number to look up in the pointer map. -** -** PTRMAP_PAGENO returns the database page number of the pointer-map -** page that stores the required pointer. PTRMAP_PTROFFSET returns -** the offset of the requested map entry. -** -** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page, -** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be -** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements -** this test. -*/ -#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno) -#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1)) -#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno)) - -/* -** The pointer map is a lookup table that identifies the parent page for -** each child page in the database file. The parent page is the page that -** contains a pointer to the child. Every page in the database contains -** 0 or 1 parent pages. (In this context 'database page' refers -** to any page that is not part of the pointer map itself.) Each pointer map -** entry consists of a single byte 'type' and a 4 byte parent page number. -** The PTRMAP_XXX identifiers below are the valid types. -** -** The purpose of the pointer map is to facility moving pages from one -** position in the file to another as part of autovacuum. When a page -** is moved, the pointer in its parent must be updated to point to the -** new location. The pointer map is used to locate the parent page quickly. -** -** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not -** used in this case. -** -** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number -** is not used in this case. -** -** PTRMAP_OVERFLOW1: The database page is the first page in a list of -** overflow pages. The page number identifies the page that -** contains the cell with a pointer to this overflow page. -** -** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of -** overflow pages. The page-number identifies the previous -** page in the overflow page list. -** -** PTRMAP_BTREE: The database page is a non-root btree page. The page number -** identifies the parent page in the btree. -*/ -#define PTRMAP_ROOTPAGE 1 -#define PTRMAP_FREEPAGE 2 -#define PTRMAP_OVERFLOW1 3 -#define PTRMAP_OVERFLOW2 4 -#define PTRMAP_BTREE 5 - -/* A bunch of assert() statements to check the transaction state variables -** of handle p (type Btree*) are internally consistent. -*/ -#define btreeIntegrity(p) \ - assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \ - assert( p->pBt->inTransaction>=p->inTrans ); - - -/* -** The ISAUTOVACUUM macro is used within balance_nonroot() to determine -** if the database supports auto-vacuum or not. Because it is used -** within an expression that is an argument to another macro -** (sqliteMallocRaw), it is not possible to use conditional compilation. -** So, this macro is defined instead. -*/ -#ifndef SQLITE_OMIT_AUTOVACUUM -#define ISAUTOVACUUM (pBt->autoVacuum) -#else -#define ISAUTOVACUUM 0 -#endif - - -/* -** This structure is passed around through all the sanity checking routines -** in order to keep track of some global state information. -** -** The aRef[] array is allocated so that there is 1 bit for each page in -** the database. As the integrity-check proceeds, for each page used in -** the database the corresponding bit is set. This allows integrity-check to -** detect pages that are used twice and orphaned pages (both of which -** indicate corruption). -*/ -typedef struct IntegrityCk IntegrityCk; -struct IntegrityCk { - BtShared *pBt; /* The tree being checked out */ - Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */ - u8 *aPgRef; /* 1 bit per page in the db (see above) */ - Pgno nPage; /* Number of pages in the database */ - int mxErr; /* Stop accumulating errors when this reaches zero */ - int nErr; /* Number of messages written to zErrMsg so far */ - int bOomFault; /* A memory allocation error has occurred */ - const char *zPfx; /* Error message prefix */ - Pgno v1; /* Value for first %u substitution in zPfx */ - int v2; /* Value for second %d substitution in zPfx */ - StrAccum errMsg; /* Accumulate the error message text here */ - u32 *heap; /* Min-heap used for analyzing cell coverage */ - sqlite3 *db; /* Database connection running the check */ -}; - -/* -** Routines to read or write a two- and four-byte big-endian integer values. -*/ -#define get2byte(x) ((x)[0]<<8 | (x)[1]) -#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v)) -#define get4byte sqlite3Get4byte -#define put4byte sqlite3Put4byte - -/* -** get2byteAligned(), unlike get2byte(), requires that its argument point to a -** two-byte aligned address. get2bytea() is only used for accessing the -** cell addresses in a btree header. -*/ -#if SQLITE_BYTEORDER==4321 -# define get2byteAligned(x) (*(u16*)(x)) -#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000 -# define get2byteAligned(x) __builtin_bswap16(*(u16*)(x)) -#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 -# define get2byteAligned(x) _byteswap_ushort(*(u16*)(x)) -#else -# define get2byteAligned(x) ((x)[0]<<8 | (x)[1]) -#endif - -/************** End of btreeInt.h ********************************************/ -/************** Continuing where we left off in btmutex.c ********************/ -#ifndef SQLITE_OMIT_SHARED_CACHE -#if SQLITE_THREADSAFE - -/* -** Obtain the BtShared mutex associated with B-Tree handle p. Also, -** set BtShared.db to the database handle associated with p and the -** p->locked boolean to true. -*/ -static void lockBtreeMutex(Btree *p){ - assert( p->locked==0 ); - assert( sqlite3_mutex_notheld(p->pBt->mutex) ); - assert( sqlite3_mutex_held(p->db->mutex) ); - - sqlite3_mutex_enter(p->pBt->mutex); - p->pBt->db = p->db; - p->locked = 1; -} - -/* -** Release the BtShared mutex associated with B-Tree handle p and -** clear the p->locked boolean. -*/ -static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){ - BtShared *pBt = p->pBt; - assert( p->locked==1 ); - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( sqlite3_mutex_held(p->db->mutex) ); - assert( p->db==pBt->db ); - - sqlite3_mutex_leave(pBt->mutex); - p->locked = 0; -} - -/* Forward reference */ -static void SQLITE_NOINLINE btreeLockCarefully(Btree *p); - -/* -** Enter a mutex on the given BTree object. -** -** If the object is not sharable, then no mutex is ever required -** and this routine is a no-op. The underlying mutex is non-recursive. -** But we keep a reference count in Btree.wantToLock so the behavior -** of this interface is recursive. -** -** To avoid deadlocks, multiple Btrees are locked in the same order -** by all database connections. The p->pNext is a list of other -** Btrees belonging to the same database connection as the p Btree -** which need to be locked after p. If we cannot get a lock on -** p, then first unlock all of the others on p->pNext, then wait -** for the lock to become available on p, then relock all of the -** subsequent Btrees that desire a lock. -*/ -SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ - /* Some basic sanity checking on the Btree. The list of Btrees - ** connected by pNext and pPrev should be in sorted order by - ** Btree.pBt value. All elements of the list should belong to - ** the same connection. Only shared Btrees are on the list. */ - assert( p->pNext==0 || p->pNext->pBt>p->pBt ); - assert( p->pPrev==0 || p->pPrev->pBtpBt ); - assert( p->pNext==0 || p->pNext->db==p->db ); - assert( p->pPrev==0 || p->pPrev->db==p->db ); - assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); - - /* Check for locking consistency */ - assert( !p->locked || p->wantToLock>0 ); - assert( p->sharable || p->wantToLock==0 ); - - /* We should already hold a lock on the database connection */ - assert( sqlite3_mutex_held(p->db->mutex) ); - - /* Unless the database is sharable and unlocked, then BtShared.db - ** should already be set correctly. */ - assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); - - if( !p->sharable ) return; - p->wantToLock++; - if( p->locked ) return; - btreeLockCarefully(p); -} - -/* This is a helper function for sqlite3BtreeLock(). By moving -** complex, but seldom used logic, out of sqlite3BtreeLock() and -** into this routine, we avoid unnecessary stack pointer changes -** and thus help the sqlite3BtreeLock() routine to run much faster -** in the common case. -*/ -static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){ - Btree *pLater; - - /* In most cases, we should be able to acquire the lock we - ** want without having to go through the ascending lock - ** procedure that follows. Just be sure not to block. - */ - if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ - p->pBt->db = p->db; - p->locked = 1; - return; - } - - /* To avoid deadlock, first release all locks with a larger - ** BtShared address. Then acquire our lock. Then reacquire - ** the other BtShared locks that we used to hold in ascending - ** order. - */ - for(pLater=p->pNext; pLater; pLater=pLater->pNext){ - assert( pLater->sharable ); - assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); - assert( !pLater->locked || pLater->wantToLock>0 ); - if( pLater->locked ){ - unlockBtreeMutex(pLater); - } - } - lockBtreeMutex(p); - for(pLater=p->pNext; pLater; pLater=pLater->pNext){ - if( pLater->wantToLock ){ - lockBtreeMutex(pLater); - } - } -} - - -/* -** Exit the recursive mutex on a Btree. -*/ -SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){ - assert( sqlite3_mutex_held(p->db->mutex) ); - if( p->sharable ){ - assert( p->wantToLock>0 ); - p->wantToLock--; - if( p->wantToLock==0 ){ - unlockBtreeMutex(p); - } - } -} - -#ifndef NDEBUG -/* -** Return true if the BtShared mutex is held on the btree, or if the -** B-Tree is not marked as sharable. -** -** This routine is used only from within assert() statements. -*/ -SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){ - assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); - assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); - assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); - assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); - - return (p->sharable==0 || p->locked); -} -#endif - - -/* -** Enter the mutex on every Btree associated with a database -** connection. This is needed (for example) prior to parsing -** a statement since we will be comparing table and column names -** against all schemas and we do not want those schemas being -** reset out from under us. -** -** There is a corresponding leave-all procedures. -** -** Enter the mutexes in accending order by BtShared pointer address -** to avoid the possibility of deadlock when two threads with -** two or more btrees in common both try to lock all their btrees -** at the same instant. -*/ -static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){ - int i; - int skipOk = 1; - Btree *p; - assert( sqlite3_mutex_held(db->mutex) ); - for(i=0; inDb; i++){ - p = db->aDb[i].pBt; - if( p && p->sharable ){ - sqlite3BtreeEnter(p); - skipOk = 0; - } - } - db->noSharedCache = skipOk; -} -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ - if( db->noSharedCache==0 ) btreeEnterAll(db); -} -static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){ - int i; - Btree *p; - assert( sqlite3_mutex_held(db->mutex) ); - for(i=0; inDb; i++){ - p = db->aDb[i].pBt; - if( p ) sqlite3BtreeLeave(p); - } -} -SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){ - if( db->noSharedCache==0 ) btreeLeaveAll(db); -} - -#ifndef NDEBUG -/* -** Return true if the current thread holds the database connection -** mutex and all required BtShared mutexes. -** -** This routine is used inside assert() statements only. -*/ -SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ - int i; - if( !sqlite3_mutex_held(db->mutex) ){ - return 0; - } - for(i=0; inDb; i++){ - Btree *p; - p = db->aDb[i].pBt; - if( p && p->sharable && - (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ - return 0; - } - } - return 1; -} -#endif /* NDEBUG */ - -#ifndef NDEBUG -/* -** Return true if the correct mutexes are held for accessing the -** db->aDb[iDb].pSchema structure. The mutexes required for schema -** access are: -** -** (1) The mutex on db -** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. -** -** If pSchema is not NULL, then iDb is computed from pSchema and -** db using sqlite3SchemaToIndex(). -*/ -SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ - Btree *p; - assert( db!=0 ); - if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); - assert( iDb>=0 && iDbnDb ); - if( !sqlite3_mutex_held(db->mutex) ) return 0; - if( iDb==1 ) return 1; - p = db->aDb[iDb].pBt; - assert( p!=0 ); - return p->sharable==0 || p->locked==1; -} -#endif /* NDEBUG */ - -#else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ -/* -** The following are special cases for mutex enter routines for use -** in single threaded applications that use shared cache. Except for -** these two routines, all mutex operations are no-ops in that case and -** are null #defines in btree.h. -** -** If shared cache is disabled, then all btree mutex routines, including -** the ones below, are no-ops and are null #defines in btree.h. -*/ - -SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){ - p->pBt->db = p->db; -} -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ - int i; - for(i=0; inDb; i++){ - Btree *p = db->aDb[i].pBt; - if( p ){ - p->pBt->db = p->db; - } - } -} -#endif /* if SQLITE_THREADSAFE */ - -#ifndef SQLITE_OMIT_INCRBLOB -/* -** Enter a mutex on a Btree given a cursor owned by that Btree. -** -** These entry points are used by incremental I/O only. Enter() is required -** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not -** the build is threadsafe. Leave() is only required by threadsafe builds. -*/ -SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){ - sqlite3BtreeEnter(pCur->pBtree); -} -# if SQLITE_THREADSAFE -SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){ - sqlite3BtreeLeave(pCur->pBtree); -} -# endif -#endif /* ifndef SQLITE_OMIT_INCRBLOB */ - -#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */ - -/************** End of btmutex.c *********************************************/ -/************** Begin file btree.c *******************************************/ -/* -** 2004 April 6 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file implements an external (disk-based) database using BTrees. -** See the header comment on "btreeInt.h" for additional information. -** Including a description of file format and an overview of operation. -*/ -/* #include "btreeInt.h" */ - -/* -** The header string that appears at the beginning of every -** SQLite database. -*/ -static const char zMagicHeader[] = SQLITE_FILE_HEADER; - -/* -** Set this global variable to 1 to enable tracing using the TRACE -** macro. -*/ -#if 0 -int sqlite3BtreeTrace=1; /* True to enable tracing */ -# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);} -#else -# define TRACE(X) -#endif - -/* -** Extract a 2-byte big-endian integer from an array of unsigned bytes. -** But if the value is zero, make it 65536. -** -** This routine is used to extract the "offset to cell content area" value -** from the header of a btree page. If the page size is 65536 and the page -** is empty, the offset should be 65536, but the 2-byte value stores zero. -** This routine makes the necessary adjustment to 65536. -*/ -#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) - -/* -** Values passed as the 5th argument to allocateBtreePage() -*/ -#define BTALLOC_ANY 0 /* Allocate any page */ -#define BTALLOC_EXACT 1 /* Allocate exact page if possible */ -#define BTALLOC_LE 2 /* Allocate any page <= the parameter */ - -/* -** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not -** defined, or 0 if it is. For example: -** -** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); -*/ -#ifndef SQLITE_OMIT_AUTOVACUUM -#define IfNotOmitAV(expr) (expr) -#else -#define IfNotOmitAV(expr) 0 -#endif - -#ifndef SQLITE_OMIT_SHARED_CACHE -/* -** A list of BtShared objects that are eligible for participation -** in shared cache. This variable has file scope during normal builds, -** but the test harness needs to access it so we make it global for -** test builds. -** -** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN. -*/ -#ifdef SQLITE_TEST -SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; -#else -static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0; -#endif -#endif /* SQLITE_OMIT_SHARED_CACHE */ - -#ifndef SQLITE_OMIT_SHARED_CACHE -/* -** Enable or disable the shared pager and schema features. -** -** This routine has no effect on existing database connections. -** The shared cache setting effects only future calls to -** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). -*/ -SQLITE_API int sqlite3_enable_shared_cache(int enable){ - sqlite3GlobalConfig.sharedCacheEnabled = enable; - return SQLITE_OK; -} -#endif - - - -#ifdef SQLITE_OMIT_SHARED_CACHE - /* - ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(), - ** and clearAllSharedCacheTableLocks() - ** manipulate entries in the BtShared.pLock linked list used to store - ** shared-cache table level locks. If the library is compiled with the - ** shared-cache feature disabled, then there is only ever one user - ** of each BtShared structure and so this locking is not necessary. - ** So define the lock related functions as no-ops. - */ - #define querySharedCacheTableLock(a,b,c) SQLITE_OK - #define setSharedCacheTableLock(a,b,c) SQLITE_OK - #define clearAllSharedCacheTableLocks(a) - #define downgradeAllSharedCacheTableLocks(a) - #define hasSharedCacheTableLock(a,b,c,d) 1 - #define hasReadConflicts(a, b) 0 -#endif - -/* -** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single -** (MemPage*) as an argument. The (MemPage*) must not be NULL. -** -** If SQLITE_DEBUG is not defined, then this macro is equivalent to -** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message -** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented -** with the page number and filename associated with the (MemPage*). -*/ -#ifdef SQLITE_DEBUG -int corruptPageError(int lineno, MemPage *p){ - char *zMsg; - sqlite3BeginBenignMalloc(); - zMsg = sqlite3_mprintf("database corruption page %d of %s", - (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0) - ); - sqlite3EndBenignMalloc(); - if( zMsg ){ - sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg); - } - sqlite3_free(zMsg); - return SQLITE_CORRUPT_BKPT; -} -# define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage) -#else -# define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno) -#endif - -#ifndef SQLITE_OMIT_SHARED_CACHE - -#ifdef SQLITE_DEBUG -/* -**** This function is only used as part of an assert() statement. *** -** -** Check to see if pBtree holds the required locks to read or write to the -** table with root page iRoot. Return 1 if it does and 0 if not. -** -** For example, when writing to a table with root-page iRoot via -** Btree connection pBtree: -** -** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) ); -** -** When writing to an index that resides in a sharable database, the -** caller should have first obtained a lock specifying the root page of -** the corresponding table. This makes things a bit more complicated, -** as this module treats each table as a separate structure. To determine -** the table corresponding to the index being written, this -** function has to search through the database schema. -** -** Instead of a lock on the table/index rooted at page iRoot, the caller may -** hold a write-lock on the schema table (root page 1). This is also -** acceptable. -*/ -static int hasSharedCacheTableLock( - Btree *pBtree, /* Handle that must hold lock */ - Pgno iRoot, /* Root page of b-tree */ - int isIndex, /* True if iRoot is the root of an index b-tree */ - int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */ -){ - Schema *pSchema = (Schema *)pBtree->pBt->pSchema; - Pgno iTab = 0; - BtLock *pLock; - - /* If this database is not shareable, or if the client is reading - ** and has the read-uncommitted flag set, then no lock is required. - ** Return true immediately. - */ - if( (pBtree->sharable==0) - || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit)) - ){ - return 1; - } - - /* If the client is reading or writing an index and the schema is - ** not loaded, then it is too difficult to actually check to see if - ** the correct locks are held. So do not bother - just return true. - ** This case does not come up very often anyhow. - */ - if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){ - return 1; - } - - /* Figure out the root-page that the lock should be held on. For table - ** b-trees, this is just the root page of the b-tree being read or - ** written. For index b-trees, it is the root page of the associated - ** table. */ - if( isIndex ){ - HashElem *p; - int bSeen = 0; - for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ - Index *pIdx = (Index *)sqliteHashData(p); - if( pIdx->tnum==(int)iRoot ){ - if( bSeen ){ - /* Two or more indexes share the same root page. There must - ** be imposter tables. So just return true. The assert is not - ** useful in that case. */ - return 1; - } - iTab = pIdx->pTable->tnum; - bSeen = 1; - } - } - }else{ - iTab = iRoot; - } - - /* Search for the required lock. Either a write-lock on root-page iTab, a - ** write-lock on the schema table, or (if the client is reading) a - ** read-lock on iTab will suffice. Return 1 if any of these are found. */ - for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){ - if( pLock->pBtree==pBtree - && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1)) - && pLock->eLock>=eLockType - ){ - return 1; - } - } - - /* Failed to find the required lock. */ - return 0; -} -#endif /* SQLITE_DEBUG */ - -#ifdef SQLITE_DEBUG -/* -**** This function may be used as part of assert() statements only. **** -** -** Return true if it would be illegal for pBtree to write into the -** table or index rooted at iRoot because other shared connections are -** simultaneously reading that same table or index. -** -** It is illegal for pBtree to write if some other Btree object that -** shares the same BtShared object is currently reading or writing -** the iRoot table. Except, if the other Btree object has the -** read-uncommitted flag set, then it is OK for the other object to -** have a read cursor. -** -** For example, before writing to any part of the table or index -** rooted at page iRoot, one should call: -** -** assert( !hasReadConflicts(pBtree, iRoot) ); -*/ -static int hasReadConflicts(Btree *pBtree, Pgno iRoot){ - BtCursor *p; - for(p=pBtree->pBt->pCursor; p; p=p->pNext){ - if( p->pgnoRoot==iRoot - && p->pBtree!=pBtree - && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit) - ){ - return 1; - } - } - return 0; -} -#endif /* #ifdef SQLITE_DEBUG */ - -/* -** Query to see if Btree handle p may obtain a lock of type eLock -** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return -** SQLITE_OK if the lock may be obtained (by calling -** setSharedCacheTableLock()), or SQLITE_LOCKED if not. -*/ -static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){ - BtShared *pBt = p->pBt; - BtLock *pIter; - - assert( sqlite3BtreeHoldsMutex(p) ); - assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); - assert( p->db!=0 ); - assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 ); - - /* If requesting a write-lock, then the Btree must have an open write - ** transaction on this file. And, obviously, for this to be so there - ** must be an open write transaction on the file itself. - */ - assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) ); - assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); - - /* This routine is a no-op if the shared-cache is not enabled */ - if( !p->sharable ){ - return SQLITE_OK; - } - - /* If some other connection is holding an exclusive lock, the - ** requested lock may not be obtained. - */ - if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ - sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); - return SQLITE_LOCKED_SHAREDCACHE; - } - - for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ - /* The condition (pIter->eLock!=eLock) in the following if(...) - ** statement is a simplification of: - ** - ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) - ** - ** since we know that if eLock==WRITE_LOCK, then no other connection - ** may hold a WRITE_LOCK on any table in this file (since there can - ** only be a single writer). - */ - assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); - assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); - if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ - sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); - if( eLock==WRITE_LOCK ){ - assert( p==pBt->pWriter ); - pBt->btsFlags |= BTS_PENDING; - } - return SQLITE_LOCKED_SHAREDCACHE; - } - } - return SQLITE_OK; -} -#endif /* !SQLITE_OMIT_SHARED_CACHE */ - -#ifndef SQLITE_OMIT_SHARED_CACHE -/* -** Add a lock on the table with root-page iTable to the shared-btree used -** by Btree handle p. Parameter eLock must be either READ_LOCK or -** WRITE_LOCK. -** -** This function assumes the following: -** -** (a) The specified Btree object p is connected to a sharable -** database (one with the BtShared.sharable flag set), and -** -** (b) No other Btree objects hold a lock that conflicts -** with the requested lock (i.e. querySharedCacheTableLock() has -** already been called and returned SQLITE_OK). -** -** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM -** is returned if a malloc attempt fails. -*/ -static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){ - BtShared *pBt = p->pBt; - BtLock *pLock = 0; - BtLock *pIter; - - assert( sqlite3BtreeHoldsMutex(p) ); - assert( eLock==READ_LOCK || eLock==WRITE_LOCK ); - assert( p->db!=0 ); - - /* A connection with the read-uncommitted flag set will never try to - ** obtain a read-lock using this function. The only read-lock obtained - ** by a connection in read-uncommitted mode is on the sqlite_schema - ** table, and that lock is obtained in BtreeBeginTrans(). */ - assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK ); - - /* This function should only be called on a sharable b-tree after it - ** has been determined that no other b-tree holds a conflicting lock. */ - assert( p->sharable ); - assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) ); - - /* First search the list for an existing lock on this table. */ - for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ - if( pIter->iTable==iTable && pIter->pBtree==p ){ - pLock = pIter; - break; - } - } - - /* If the above search did not find a BtLock struct associating Btree p - ** with table iTable, allocate one and link it into the list. - */ - if( !pLock ){ - pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); - if( !pLock ){ - return SQLITE_NOMEM_BKPT; - } - pLock->iTable = iTable; - pLock->pBtree = p; - pLock->pNext = pBt->pLock; - pBt->pLock = pLock; - } - - /* Set the BtLock.eLock variable to the maximum of the current lock - ** and the requested lock. This means if a write-lock was already held - ** and a read-lock requested, we don't incorrectly downgrade the lock. - */ - assert( WRITE_LOCK>READ_LOCK ); - if( eLock>pLock->eLock ){ - pLock->eLock = eLock; - } - - return SQLITE_OK; -} -#endif /* !SQLITE_OMIT_SHARED_CACHE */ - -#ifndef SQLITE_OMIT_SHARED_CACHE -/* -** Release all the table locks (locks obtained via calls to -** the setSharedCacheTableLock() procedure) held by Btree object p. -** -** This function assumes that Btree p has an open read or write -** transaction. If it does not, then the BTS_PENDING flag -** may be incorrectly cleared. -*/ -static void clearAllSharedCacheTableLocks(Btree *p){ - BtShared *pBt = p->pBt; - BtLock **ppIter = &pBt->pLock; - - assert( sqlite3BtreeHoldsMutex(p) ); - assert( p->sharable || 0==*ppIter ); - assert( p->inTrans>0 ); - - while( *ppIter ){ - BtLock *pLock = *ppIter; - assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); - assert( pLock->pBtree->inTrans>=pLock->eLock ); - if( pLock->pBtree==p ){ - *ppIter = pLock->pNext; - assert( pLock->iTable!=1 || pLock==&p->lock ); - if( pLock->iTable!=1 ){ - sqlite3_free(pLock); - } - }else{ - ppIter = &pLock->pNext; - } - } - - assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); - if( pBt->pWriter==p ){ - pBt->pWriter = 0; - pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); - }else if( pBt->nTransaction==2 ){ - /* This function is called when Btree p is concluding its - ** transaction. If there currently exists a writer, and p is not - ** that writer, then the number of locks held by connections other - ** than the writer must be about to drop to zero. In this case - ** set the BTS_PENDING flag to 0. - ** - ** If there is not currently a writer, then BTS_PENDING must - ** be zero already. So this next line is harmless in that case. - */ - pBt->btsFlags &= ~BTS_PENDING; - } -} - -/* -** This function changes all write-locks held by Btree p into read-locks. -*/ -static void downgradeAllSharedCacheTableLocks(Btree *p){ - BtShared *pBt = p->pBt; - if( pBt->pWriter==p ){ - BtLock *pLock; - pBt->pWriter = 0; - pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); - for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ - assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); - pLock->eLock = READ_LOCK; - } - } -} - -#endif /* SQLITE_OMIT_SHARED_CACHE */ - -static void releasePage(MemPage *pPage); /* Forward reference */ -static void releasePageOne(MemPage *pPage); /* Forward reference */ -static void releasePageNotNull(MemPage *pPage); /* Forward reference */ - -/* -***** This routine is used inside of assert() only **** -** -** Verify that the cursor holds the mutex on its BtShared -*/ -#ifdef SQLITE_DEBUG -static int cursorHoldsMutex(BtCursor *p){ - return sqlite3_mutex_held(p->pBt->mutex); -} - -/* Verify that the cursor and the BtShared agree about what is the current -** database connetion. This is important in shared-cache mode. If the database -** connection pointers get out-of-sync, it is possible for routines like -** btreeInitPage() to reference an stale connection pointer that references a -** a connection that has already closed. This routine is used inside assert() -** statements only and for the purpose of double-checking that the btree code -** does keep the database connection pointers up-to-date. -*/ -static int cursorOwnsBtShared(BtCursor *p){ - assert( cursorHoldsMutex(p) ); - return (p->pBtree->db==p->pBt->db); -} -#endif - -/* -** Invalidate the overflow cache of the cursor passed as the first argument. -** on the shared btree structure pBt. -*/ -#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl) - -/* -** Invalidate the overflow page-list cache for all cursors opened -** on the shared btree structure pBt. -*/ -static void invalidateAllOverflowCache(BtShared *pBt){ - BtCursor *p; - assert( sqlite3_mutex_held(pBt->mutex) ); - for(p=pBt->pCursor; p; p=p->pNext){ - invalidateOverflowCache(p); - } -} - -#ifndef SQLITE_OMIT_INCRBLOB -/* -** This function is called before modifying the contents of a table -** to invalidate any incrblob cursors that are open on the -** row or one of the rows being modified. -** -** If argument isClearTable is true, then the entire contents of the -** table is about to be deleted. In this case invalidate all incrblob -** cursors open on any row within the table with root-page pgnoRoot. -** -** Otherwise, if argument isClearTable is false, then the row with -** rowid iRow is being replaced or deleted. In this case invalidate -** only those incrblob cursors open on that specific row. -*/ -static void invalidateIncrblobCursors( - Btree *pBtree, /* The database file to check */ - Pgno pgnoRoot, /* The table that might be changing */ - i64 iRow, /* The rowid that might be changing */ - int isClearTable /* True if all rows are being deleted */ -){ - BtCursor *p; - if( pBtree->hasIncrblobCur==0 ) return; - assert( sqlite3BtreeHoldsMutex(pBtree) ); - pBtree->hasIncrblobCur = 0; - for(p=pBtree->pBt->pCursor; p; p=p->pNext){ - if( (p->curFlags & BTCF_Incrblob)!=0 ){ - pBtree->hasIncrblobCur = 1; - if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){ - p->eState = CURSOR_INVALID; - } - } - } -} - -#else - /* Stub function when INCRBLOB is omitted */ - #define invalidateIncrblobCursors(w,x,y,z) -#endif /* SQLITE_OMIT_INCRBLOB */ - -/* -** Set bit pgno of the BtShared.pHasContent bitvec. This is called -** when a page that previously contained data becomes a free-list leaf -** page. -** -** The BtShared.pHasContent bitvec exists to work around an obscure -** bug caused by the interaction of two useful IO optimizations surrounding -** free-list leaf pages: -** -** 1) When all data is deleted from a page and the page becomes -** a free-list leaf page, the page is not written to the database -** (as free-list leaf pages contain no meaningful data). Sometimes -** such a page is not even journalled (as it will not be modified, -** why bother journalling it?). -** -** 2) When a free-list leaf page is reused, its content is not read -** from the database or written to the journal file (why should it -** be, if it is not at all meaningful?). -** -** By themselves, these optimizations work fine and provide a handy -** performance boost to bulk delete or insert operations. However, if -** a page is moved to the free-list and then reused within the same -** transaction, a problem comes up. If the page is not journalled when -** it is moved to the free-list and it is also not journalled when it -** is extracted from the free-list and reused, then the original data -** may be lost. In the event of a rollback, it may not be possible -** to restore the database to its original configuration. -** -** The solution is the BtShared.pHasContent bitvec. Whenever a page is -** moved to become a free-list leaf page, the corresponding bit is -** set in the bitvec. Whenever a leaf page is extracted from the free-list, -** optimization 2 above is omitted if the corresponding bit is already -** set in BtShared.pHasContent. The contents of the bitvec are cleared -** at the end of every transaction. -*/ -static int btreeSetHasContent(BtShared *pBt, Pgno pgno){ - int rc = SQLITE_OK; - if( !pBt->pHasContent ){ - assert( pgno<=pBt->nPage ); - pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage); - if( !pBt->pHasContent ){ - rc = SQLITE_NOMEM_BKPT; - } - } - if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){ - rc = sqlite3BitvecSet(pBt->pHasContent, pgno); - } - return rc; -} - -/* -** Query the BtShared.pHasContent vector. -** -** This function is called when a free-list leaf page is removed from the -** free-list for reuse. It returns false if it is safe to retrieve the -** page from the pager layer with the 'no-content' flag set. True otherwise. -*/ -static int btreeGetHasContent(BtShared *pBt, Pgno pgno){ - Bitvec *p = pBt->pHasContent; - return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno)); -} - -/* -** Clear (destroy) the BtShared.pHasContent bitvec. This should be -** invoked at the conclusion of each write-transaction. -*/ -static void btreeClearHasContent(BtShared *pBt){ - sqlite3BitvecDestroy(pBt->pHasContent); - pBt->pHasContent = 0; -} - -/* -** Release all of the apPage[] pages for a cursor. -*/ -static void btreeReleaseAllCursorPages(BtCursor *pCur){ - int i; - if( pCur->iPage>=0 ){ - for(i=0; iiPage; i++){ - releasePageNotNull(pCur->apPage[i]); - } - releasePageNotNull(pCur->pPage); - pCur->iPage = -1; - } -} - -/* -** The cursor passed as the only argument must point to a valid entry -** when this function is called (i.e. have eState==CURSOR_VALID). This -** function saves the current cursor key in variables pCur->nKey and -** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error -** code otherwise. -** -** If the cursor is open on an intkey table, then the integer key -** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to -** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is -** set to point to a malloced buffer pCur->nKey bytes in size containing -** the key. -*/ -static int saveCursorKey(BtCursor *pCur){ - int rc = SQLITE_OK; - assert( CURSOR_VALID==pCur->eState ); - assert( 0==pCur->pKey ); - assert( cursorHoldsMutex(pCur) ); - - if( pCur->curIntKey ){ - /* Only the rowid is required for a table btree */ - pCur->nKey = sqlite3BtreeIntegerKey(pCur); - }else{ - /* For an index btree, save the complete key content. It is possible - ** that the current key is corrupt. In that case, it is possible that - ** the sqlite3VdbeRecordUnpack() function may overread the buffer by - ** up to the size of 1 varint plus 1 8-byte value when the cursor - ** position is restored. Hence the 17 bytes of padding allocated - ** below. */ - void *pKey; - pCur->nKey = sqlite3BtreePayloadSize(pCur); - pKey = sqlite3Malloc( pCur->nKey + 9 + 8 ); - if( pKey ){ - rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); - if( rc==SQLITE_OK ){ - memset(((u8*)pKey)+pCur->nKey, 0, 9+8); - pCur->pKey = pKey; - }else{ - sqlite3_free(pKey); - } - }else{ - rc = SQLITE_NOMEM_BKPT; - } - } - assert( !pCur->curIntKey || !pCur->pKey ); - return rc; -} - -/* -** Save the current cursor position in the variables BtCursor.nKey -** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. -** -** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) -** prior to calling this routine. -*/ -static int saveCursorPosition(BtCursor *pCur){ - int rc; - - assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState ); - assert( 0==pCur->pKey ); - assert( cursorHoldsMutex(pCur) ); - - if( pCur->curFlags & BTCF_Pinned ){ - return SQLITE_CONSTRAINT_PINNED; - } - if( pCur->eState==CURSOR_SKIPNEXT ){ - pCur->eState = CURSOR_VALID; - }else{ - pCur->skipNext = 0; - } - - rc = saveCursorKey(pCur); - if( rc==SQLITE_OK ){ - btreeReleaseAllCursorPages(pCur); - pCur->eState = CURSOR_REQUIRESEEK; - } - - pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast); - return rc; -} - -/* Forward reference */ -static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); - -/* -** Save the positions of all cursors (except pExcept) that are open on -** the table with root-page iRoot. "Saving the cursor position" means that -** the location in the btree is remembered in such a way that it can be -** moved back to the same spot after the btree has been modified. This -** routine is called just before cursor pExcept is used to modify the -** table, for example in BtreeDelete() or BtreeInsert(). -** -** If there are two or more cursors on the same btree, then all such -** cursors should have their BTCF_Multiple flag set. The btreeCursor() -** routine enforces that rule. This routine only needs to be called in -** the uncommon case when pExpect has the BTCF_Multiple flag set. -** -** If pExpect!=NULL and if no other cursors are found on the same root-page, -** then the BTCF_Multiple flag on pExpect is cleared, to avoid another -** pointless call to this routine. -** -** Implementation note: This routine merely checks to see if any cursors -** need to be saved. It calls out to saveCursorsOnList() in the (unusual) -** event that cursors are in need to being saved. -*/ -static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ - BtCursor *p; - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( pExcept==0 || pExcept->pBt==pBt ); - for(p=pBt->pCursor; p; p=p->pNext){ - if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; - } - if( p ) return saveCursorsOnList(p, iRoot, pExcept); - if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple; - return SQLITE_OK; -} - -/* This helper routine to saveAllCursors does the actual work of saving -** the cursors if and when a cursor is found that actually requires saving. -** The common case is that no cursors need to be saved, so this routine is -** broken out from its caller to avoid unnecessary stack pointer movement. -*/ -static int SQLITE_NOINLINE saveCursorsOnList( - BtCursor *p, /* The first cursor that needs saving */ - Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ - BtCursor *pExcept /* Do not save this cursor */ -){ - do{ - if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ - if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ - int rc = saveCursorPosition(p); - if( SQLITE_OK!=rc ){ - return rc; - } - }else{ - testcase( p->iPage>=0 ); - btreeReleaseAllCursorPages(p); - } - } - p = p->pNext; - }while( p ); - return SQLITE_OK; -} - -/* -** Clear the current cursor position. -*/ -SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){ - assert( cursorHoldsMutex(pCur) ); - sqlite3_free(pCur->pKey); - pCur->pKey = 0; - pCur->eState = CURSOR_INVALID; -} - -/* -** In this version of BtreeMoveto, pKey is a packed index record -** such as is generated by the OP_MakeRecord opcode. Unpack the -** record and then call BtreeMovetoUnpacked() to do the work. -*/ -static int btreeMoveto( - BtCursor *pCur, /* Cursor open on the btree to be searched */ - const void *pKey, /* Packed key if the btree is an index */ - i64 nKey, /* Integer key for tables. Size of pKey for indices */ - int bias, /* Bias search to the high end */ - int *pRes /* Write search results here */ -){ - int rc; /* Status code */ - UnpackedRecord *pIdxKey; /* Unpacked index key */ - - if( pKey ){ - KeyInfo *pKeyInfo = pCur->pKeyInfo; - assert( nKey==(i64)(int)nKey ); - pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); - if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; - sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey); - if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){ - rc = SQLITE_CORRUPT_BKPT; - goto moveto_done; - } - }else{ - pIdxKey = 0; - } - rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); -moveto_done: - if( pIdxKey ){ - sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey); - } - return rc; -} - -/* -** Restore the cursor to the position it was in (or as close to as possible) -** when saveCursorPosition() was called. Note that this call deletes the -** saved position info stored by saveCursorPosition(), so there can be -** at most one effective restoreCursorPosition() call after each -** saveCursorPosition(). -*/ -static int btreeRestoreCursorPosition(BtCursor *pCur){ - int rc; - int skipNext = 0; - assert( cursorOwnsBtShared(pCur) ); - assert( pCur->eState>=CURSOR_REQUIRESEEK ); - if( pCur->eState==CURSOR_FAULT ){ - return pCur->skipNext; - } - pCur->eState = CURSOR_INVALID; - if( sqlite3FaultSim(410) ){ - rc = SQLITE_IOERR; - }else{ - rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); - } - if( rc==SQLITE_OK ){ - sqlite3_free(pCur->pKey); - pCur->pKey = 0; - assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); - if( skipNext ) pCur->skipNext = skipNext; - if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ - pCur->eState = CURSOR_SKIPNEXT; - } - } - return rc; -} - -#define restoreCursorPosition(p) \ - (p->eState>=CURSOR_REQUIRESEEK ? \ - btreeRestoreCursorPosition(p) : \ - SQLITE_OK) - -/* -** Determine whether or not a cursor has moved from the position where -** it was last placed, or has been invalidated for any other reason. -** Cursors can move when the row they are pointing at is deleted out -** from under them, for example. Cursor might also move if a btree -** is rebalanced. -** -** Calling this routine with a NULL cursor pointer returns false. -** -** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor -** back to where it ought to be if this routine returns true. -*/ -SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ - assert( EIGHT_BYTE_ALIGNMENT(pCur) - || pCur==sqlite3BtreeFakeValidCursor() ); - assert( offsetof(BtCursor, eState)==0 ); - assert( sizeof(pCur->eState)==1 ); - return CURSOR_VALID != *(u8*)pCur; -} - -/* -** Return a pointer to a fake BtCursor object that will always answer -** false to the sqlite3BtreeCursorHasMoved() routine above. The fake -** cursor returned must not be used with any other Btree interface. -*/ -SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){ - static u8 fakeCursor = CURSOR_VALID; - assert( offsetof(BtCursor, eState)==0 ); - return (BtCursor*)&fakeCursor; -} - -/* -** This routine restores a cursor back to its original position after it -** has been moved by some outside activity (such as a btree rebalance or -** a row having been deleted out from under the cursor). -** -** On success, the *pDifferentRow parameter is false if the cursor is left -** pointing at exactly the same row. *pDifferntRow is the row the cursor -** was pointing to has been deleted, forcing the cursor to point to some -** nearby row. -** -** This routine should only be called for a cursor that just returned -** TRUE from sqlite3BtreeCursorHasMoved(). -*/ -SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ - int rc; - - assert( pCur!=0 ); - assert( pCur->eState!=CURSOR_VALID ); - rc = restoreCursorPosition(pCur); - if( rc ){ - *pDifferentRow = 1; - return rc; - } - if( pCur->eState!=CURSOR_VALID ){ - *pDifferentRow = 1; - }else{ - *pDifferentRow = 0; - } - return SQLITE_OK; -} - -#ifdef SQLITE_ENABLE_CURSOR_HINTS -/* -** Provide hints to the cursor. The particular hint given (and the type -** and number of the varargs parameters) is determined by the eHintType -** parameter. See the definitions of the BTREE_HINT_* macros for details. -*/ -SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ - /* Used only by system that substitute their own storage engine */ -} -#endif - -/* -** Provide flag hints to the cursor. -*/ -SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ - assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 ); - pCur->hints = x; -} - - -#ifndef SQLITE_OMIT_AUTOVACUUM -/* -** Given a page number of a regular database page, return the page -** number for the pointer-map page that contains the entry for the -** input page number. -** -** Return 0 (not a valid page) for pgno==1 since there is -** no pointer map associated with page 1. The integrity_check logic -** requires that ptrmapPageno(*,1)!=1. -*/ -static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ - int nPagesPerMapPage; - Pgno iPtrMap, ret; - assert( sqlite3_mutex_held(pBt->mutex) ); - if( pgno<2 ) return 0; - nPagesPerMapPage = (pBt->usableSize/5)+1; - iPtrMap = (pgno-2)/nPagesPerMapPage; - ret = (iPtrMap*nPagesPerMapPage) + 2; - if( ret==PENDING_BYTE_PAGE(pBt) ){ - ret++; - } - return ret; -} - -/* -** Write an entry into the pointer map. -** -** This routine updates the pointer map entry for page number 'key' -** so that it maps to type 'eType' and parent page number 'pgno'. -** -** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is -** a no-op. If an error occurs, the appropriate error code is written -** into *pRC. -*/ -static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){ - DbPage *pDbPage; /* The pointer map page */ - u8 *pPtrmap; /* The pointer map data */ - Pgno iPtrmap; /* The pointer map page number */ - int offset; /* Offset in pointer map page */ - int rc; /* Return code from subfunctions */ - - if( *pRC ) return; - - assert( sqlite3_mutex_held(pBt->mutex) ); - /* The super-journal page number must never be used as a pointer map page */ - assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); - - assert( pBt->autoVacuum ); - if( key==0 ){ - *pRC = SQLITE_CORRUPT_BKPT; - return; - } - iPtrmap = PTRMAP_PAGENO(pBt, key); - rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); - if( rc!=SQLITE_OK ){ - *pRC = rc; - return; - } - if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){ - /* The first byte of the extra data is the MemPage.isInit byte. - ** If that byte is set, it means this page is also being used - ** as a btree page. */ - *pRC = SQLITE_CORRUPT_BKPT; - goto ptrmap_exit; - } - offset = PTRMAP_PTROFFSET(iPtrmap, key); - if( offset<0 ){ - *pRC = SQLITE_CORRUPT_BKPT; - goto ptrmap_exit; - } - assert( offset <= (int)pBt->usableSize-5 ); - pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); - - if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ - TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); - *pRC= rc = sqlite3PagerWrite(pDbPage); - if( rc==SQLITE_OK ){ - pPtrmap[offset] = eType; - put4byte(&pPtrmap[offset+1], parent); - } - } - -ptrmap_exit: - sqlite3PagerUnref(pDbPage); -} - -/* -** Read an entry from the pointer map. -** -** This routine retrieves the pointer map entry for page 'key', writing -** the type and parent page number to *pEType and *pPgno respectively. -** An error code is returned if something goes wrong, otherwise SQLITE_OK. -*/ -static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ - DbPage *pDbPage; /* The pointer map page */ - int iPtrmap; /* Pointer map page index */ - u8 *pPtrmap; /* Pointer map page data */ - int offset; /* Offset of entry in pointer map */ - int rc; - - assert( sqlite3_mutex_held(pBt->mutex) ); - - iPtrmap = PTRMAP_PAGENO(pBt, key); - rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0); - if( rc!=0 ){ - return rc; - } - pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); - - offset = PTRMAP_PTROFFSET(iPtrmap, key); - if( offset<0 ){ - sqlite3PagerUnref(pDbPage); - return SQLITE_CORRUPT_BKPT; - } - assert( offset <= (int)pBt->usableSize-5 ); - assert( pEType!=0 ); - *pEType = pPtrmap[offset]; - if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); - - sqlite3PagerUnref(pDbPage); - if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap); - return SQLITE_OK; -} - -#else /* if defined SQLITE_OMIT_AUTOVACUUM */ - #define ptrmapPut(w,x,y,z,rc) - #define ptrmapGet(w,x,y,z) SQLITE_OK - #define ptrmapPutOvflPtr(x, y, z, rc) -#endif - -/* -** Given a btree page and a cell index (0 means the first cell on -** the page, 1 means the second cell, and so forth) return a pointer -** to the cell content. -** -** findCellPastPtr() does the same except it skips past the initial -** 4-byte child pointer found on interior pages, if there is one. -** -** This routine works only for pages that do not contain overflow cells. -*/ -#define findCell(P,I) \ - ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) -#define findCellPastPtr(P,I) \ - ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)]))) - - -/* -** This is common tail processing for btreeParseCellPtr() and -** btreeParseCellPtrIndex() for the case when the cell does not fit entirely -** on a single B-tree page. Make necessary adjustments to the CellInfo -** structure. -*/ -static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow( - MemPage *pPage, /* Page containing the cell */ - u8 *pCell, /* Pointer to the cell text. */ - CellInfo *pInfo /* Fill in this structure */ -){ - /* If the payload will not fit completely on the local page, we have - ** to decide how much to store locally and how much to spill onto - ** overflow pages. The strategy is to minimize the amount of unused - ** space on overflow pages while keeping the amount of local storage - ** in between minLocal and maxLocal. - ** - ** Warning: changing the way overflow payload is distributed in any - ** way will result in an incompatible file format. - */ - int minLocal; /* Minimum amount of payload held locally */ - int maxLocal; /* Maximum amount of payload held locally */ - int surplus; /* Overflow payload available for local storage */ - - minLocal = pPage->minLocal; - maxLocal = pPage->maxLocal; - surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4); - testcase( surplus==maxLocal ); - testcase( surplus==maxLocal+1 ); - if( surplus <= maxLocal ){ - pInfo->nLocal = (u16)surplus; - }else{ - pInfo->nLocal = (u16)minLocal; - } - pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4; -} - -/* -** The following routines are implementations of the MemPage.xParseCell() -** method. -** -** Parse a cell content block and fill in the CellInfo structure. -** -** btreeParseCellPtr() => table btree leaf nodes -** btreeParseCellNoPayload() => table btree internal nodes -** btreeParseCellPtrIndex() => index btree nodes -** -** There is also a wrapper function btreeParseCell() that works for -** all MemPage types and that references the cell by index rather than -** by pointer. -*/ -static void btreeParseCellPtrNoPayload( - MemPage *pPage, /* Page containing the cell */ - u8 *pCell, /* Pointer to the cell text. */ - CellInfo *pInfo /* Fill in this structure */ -){ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( pPage->leaf==0 ); - assert( pPage->childPtrSize==4 ); -#ifndef SQLITE_DEBUG - UNUSED_PARAMETER(pPage); -#endif - pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); - pInfo->nPayload = 0; - pInfo->nLocal = 0; - pInfo->pPayload = 0; - return; -} -static void btreeParseCellPtr( - MemPage *pPage, /* Page containing the cell */ - u8 *pCell, /* Pointer to the cell text. */ - CellInfo *pInfo /* Fill in this structure */ -){ - u8 *pIter; /* For scanning through pCell */ - u32 nPayload; /* Number of bytes of cell payload */ - u64 iKey; /* Extracted Key value */ - - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( pPage->leaf==0 || pPage->leaf==1 ); - assert( pPage->intKeyLeaf ); - assert( pPage->childPtrSize==0 ); - pIter = pCell; - - /* The next block of code is equivalent to: - ** - ** pIter += getVarint32(pIter, nPayload); - ** - ** The code is inlined to avoid a function call. - */ - nPayload = *pIter; - if( nPayload>=0x80 ){ - u8 *pEnd = &pIter[8]; - nPayload &= 0x7f; - do{ - nPayload = (nPayload<<7) | (*++pIter & 0x7f); - }while( (*pIter)>=0x80 && pIternKey); - ** - ** The code is inlined to avoid a function call. - */ - iKey = *pIter; - if( iKey>=0x80 ){ - u8 *pEnd = &pIter[7]; - iKey &= 0x7f; - while(1){ - iKey = (iKey<<7) | (*++pIter & 0x7f); - if( (*pIter)<0x80 ) break; - if( pIter>=pEnd ){ - iKey = (iKey<<8) | *++pIter; - break; - } - } - } - pIter++; - - pInfo->nKey = *(i64*)&iKey; - pInfo->nPayload = nPayload; - pInfo->pPayload = pIter; - testcase( nPayload==pPage->maxLocal ); - testcase( nPayload==pPage->maxLocal+1 ); - if( nPayload<=pPage->maxLocal ){ - /* This is the (easy) common case where the entire payload fits - ** on the local page. No overflow is required. - */ - pInfo->nSize = nPayload + (u16)(pIter - pCell); - if( pInfo->nSize<4 ) pInfo->nSize = 4; - pInfo->nLocal = (u16)nPayload; - }else{ - btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); - } -} -static void btreeParseCellPtrIndex( - MemPage *pPage, /* Page containing the cell */ - u8 *pCell, /* Pointer to the cell text. */ - CellInfo *pInfo /* Fill in this structure */ -){ - u8 *pIter; /* For scanning through pCell */ - u32 nPayload; /* Number of bytes of cell payload */ - - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( pPage->leaf==0 || pPage->leaf==1 ); - assert( pPage->intKeyLeaf==0 ); - pIter = pCell + pPage->childPtrSize; - nPayload = *pIter; - if( nPayload>=0x80 ){ - u8 *pEnd = &pIter[8]; - nPayload &= 0x7f; - do{ - nPayload = (nPayload<<7) | (*++pIter & 0x7f); - }while( *(pIter)>=0x80 && pIternKey = nPayload; - pInfo->nPayload = nPayload; - pInfo->pPayload = pIter; - testcase( nPayload==pPage->maxLocal ); - testcase( nPayload==pPage->maxLocal+1 ); - if( nPayload<=pPage->maxLocal ){ - /* This is the (easy) common case where the entire payload fits - ** on the local page. No overflow is required. - */ - pInfo->nSize = nPayload + (u16)(pIter - pCell); - if( pInfo->nSize<4 ) pInfo->nSize = 4; - pInfo->nLocal = (u16)nPayload; - }else{ - btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo); - } -} -static void btreeParseCell( - MemPage *pPage, /* Page containing the cell */ - int iCell, /* The cell index. First cell is 0 */ - CellInfo *pInfo /* Fill in this structure */ -){ - pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo); -} - -/* -** The following routines are implementations of the MemPage.xCellSize -** method. -** -** Compute the total number of bytes that a Cell needs in the cell -** data area of the btree-page. The return number includes the cell -** data header and the local payload, but not any overflow page or -** the space used by the cell pointer. -** -** cellSizePtrNoPayload() => table internal nodes -** cellSizePtr() => all index nodes & table leaf nodes -*/ -static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ - u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */ - u8 *pEnd; /* End mark for a varint */ - u32 nSize; /* Size value to return */ - -#ifdef SQLITE_DEBUG - /* The value returned by this function should always be the same as - ** the (CellInfo.nSize) value found by doing a full parse of the - ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of - ** this function verifies that this invariant is not violated. */ - CellInfo debuginfo; - pPage->xParseCell(pPage, pCell, &debuginfo); -#endif - - nSize = *pIter; - if( nSize>=0x80 ){ - pEnd = &pIter[8]; - nSize &= 0x7f; - do{ - nSize = (nSize<<7) | (*++pIter & 0x7f); - }while( *(pIter)>=0x80 && pIterintKey ){ - /* pIter now points at the 64-bit integer key value, a variable length - ** integer. The following block moves pIter to point at the first byte - ** past the end of the key value. */ - pEnd = &pIter[9]; - while( (*pIter++)&0x80 && pItermaxLocal ); - testcase( nSize==pPage->maxLocal+1 ); - if( nSize<=pPage->maxLocal ){ - nSize += (u32)(pIter - pCell); - if( nSize<4 ) nSize = 4; - }else{ - int minLocal = pPage->minLocal; - nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); - testcase( nSize==pPage->maxLocal ); - testcase( nSize==pPage->maxLocal+1 ); - if( nSize>pPage->maxLocal ){ - nSize = minLocal; - } - nSize += 4 + (u16)(pIter - pCell); - } - assert( nSize==debuginfo.nSize || CORRUPT_DB ); - return (u16)nSize; -} -static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){ - u8 *pIter = pCell + 4; /* For looping over bytes of pCell */ - u8 *pEnd; /* End mark for a varint */ - -#ifdef SQLITE_DEBUG - /* The value returned by this function should always be the same as - ** the (CellInfo.nSize) value found by doing a full parse of the - ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of - ** this function verifies that this invariant is not violated. */ - CellInfo debuginfo; - pPage->xParseCell(pPage, pCell, &debuginfo); -#else - UNUSED_PARAMETER(pPage); -#endif - - assert( pPage->childPtrSize==4 ); - pEnd = pIter + 9; - while( (*pIter++)&0x80 && pIterxCellSize(pPage, findCell(pPage, iCell)); -} -#endif - -#ifndef SQLITE_OMIT_AUTOVACUUM -/* -** The cell pCell is currently part of page pSrc but will ultimately be part -** of pPage. (pSrc and pPager are often the same.) If pCell contains a -** pointer to an overflow page, insert an entry into the pointer-map for -** the overflow page that will be valid after pCell has been moved to pPage. -*/ -static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){ - CellInfo info; - if( *pRC ) return; - assert( pCell!=0 ); - pPage->xParseCell(pPage, pCell, &info); - if( info.nLocalaDataEnd, pCell, pCell+info.nLocal) ){ - testcase( pSrc!=pPage ); - *pRC = SQLITE_CORRUPT_BKPT; - return; - } - ovfl = get4byte(&pCell[info.nSize-4]); - ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); - } -} -#endif - - -/* -** Defragment the page given. This routine reorganizes cells within the -** page so that there are no free-blocks on the free-block list. -** -** Parameter nMaxFrag is the maximum amount of fragmented space that may be -** present in the page after this routine returns. -** -** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a -** b-tree page so that there are no freeblocks or fragment bytes, all -** unused bytes are contained in the unallocated space region, and all -** cells are packed tightly at the end of the page. -*/ -static int defragmentPage(MemPage *pPage, int nMaxFrag){ - int i; /* Loop counter */ - int pc; /* Address of the i-th cell */ - int hdr; /* Offset to the page header */ - int size; /* Size of a cell */ - int usableSize; /* Number of usable bytes on a page */ - int cellOffset; /* Offset to the cell pointer array */ - int cbrk; /* Offset to the cell content area */ - int nCell; /* Number of cells on the page */ - unsigned char *data; /* The page data */ - unsigned char *temp; /* Temp area for cell content */ - unsigned char *src; /* Source of content */ - int iCellFirst; /* First allowable cell index */ - int iCellLast; /* Last possible cell index */ - - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - assert( pPage->pBt!=0 ); - assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); - assert( pPage->nOverflow==0 ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - temp = 0; - src = data = pPage->aData; - hdr = pPage->hdrOffset; - cellOffset = pPage->cellOffset; - nCell = pPage->nCell; - assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB ); - iCellFirst = cellOffset + 2*nCell; - usableSize = pPage->pBt->usableSize; - - /* This block handles pages with two or fewer free blocks and nMaxFrag - ** or fewer fragmented bytes. In this case it is faster to move the - ** two (or one) blocks of cells using memmove() and add the required - ** offsets to each pointer in the cell-pointer array than it is to - ** reconstruct the entire page. */ - if( (int)data[hdr+7]<=nMaxFrag ){ - int iFree = get2byte(&data[hdr+1]); - if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); - if( iFree ){ - int iFree2 = get2byte(&data[iFree]); - if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage); - if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){ - u8 *pEnd = &data[cellOffset + nCell*2]; - u8 *pAddr; - int sz2 = 0; - int sz = get2byte(&data[iFree+2]); - int top = get2byte(&data[hdr+5]); - if( top>=iFree ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - if( iFree2 ){ - if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage); - sz2 = get2byte(&data[iFree2+2]); - if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage); - memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz)); - sz += sz2; - }else if( NEVER(iFree+sz>usableSize) ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - - cbrk = top+sz; - assert( cbrk+(iFree-top) <= usableSize ); - memmove(&data[cbrk], &data[top], iFree-top); - for(pAddr=&data[cellOffset]; pAddriCellLast ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - assert( pc>=iCellFirst && pc<=iCellLast ); - size = pPage->xCellSize(pPage, &src[pc]); - cbrk -= size; - if( cbrkusableSize ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - assert( cbrk+size<=usableSize && cbrk>=iCellFirst ); - testcase( cbrk+size==usableSize ); - testcase( pc+size==usableSize ); - put2byte(pAddr, cbrk); - if( temp==0 ){ - int x; - if( cbrk==pc ) continue; - temp = sqlite3PagerTempSpace(pPage->pBt->pPager); - x = get2byte(&data[hdr+5]); - memcpy(&temp[x], &data[x], (cbrk+size) - x); - src = temp; - } - memcpy(&data[cbrk], &src[pc], size); - } - data[hdr+7] = 0; - - defragment_out: - assert( pPage->nFree>=0 ); - if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - assert( cbrk>=iCellFirst ); - put2byte(&data[hdr+5], cbrk); - data[hdr+1] = 0; - data[hdr+2] = 0; - memset(&data[iCellFirst], 0, cbrk-iCellFirst); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - return SQLITE_OK; -} - -/* -** Search the free-list on page pPg for space to store a cell nByte bytes in -** size. If one can be found, return a pointer to the space and remove it -** from the free-list. -** -** If no suitable space can be found on the free-list, return NULL. -** -** This function may detect corruption within pPg. If corruption is -** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned. -** -** Slots on the free list that are between 1 and 3 bytes larger than nByte -** will be ignored if adding the extra space to the fragmentation count -** causes the fragmentation count to exceed 60. -*/ -static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){ - const int hdr = pPg->hdrOffset; /* Offset to page header */ - u8 * const aData = pPg->aData; /* Page data */ - int iAddr = hdr + 1; /* Address of ptr to pc */ - int pc = get2byte(&aData[iAddr]); /* Address of a free slot */ - int x; /* Excess size of the slot */ - int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */ - int size; /* Size of the free slot */ - - assert( pc>0 ); - while( pc<=maxPC ){ - /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each - ** freeblock form a big-endian integer which is the size of the freeblock - ** in bytes, including the 4-byte header. */ - size = get2byte(&aData[pc+2]); - if( (x = size - nByte)>=0 ){ - testcase( x==4 ); - testcase( x==3 ); - if( x<4 ){ - /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total - ** number of bytes in fragments may not exceed 60. */ - if( aData[hdr+7]>57 ) return 0; - - /* Remove the slot from the free-list. Update the number of - ** fragmented bytes within the page. */ - memcpy(&aData[iAddr], &aData[pc], 2); - aData[hdr+7] += (u8)x; - }else if( x+pc > maxPC ){ - /* This slot extends off the end of the usable part of the page */ - *pRc = SQLITE_CORRUPT_PAGE(pPg); - return 0; - }else{ - /* The slot remains on the free-list. Reduce its size to account - ** for the portion used by the new allocation. */ - put2byte(&aData[pc+2], x); - } - return &aData[pc + x]; - } - iAddr = pc; - pc = get2byte(&aData[pc]); - if( pc<=iAddr+size ){ - if( pc ){ - /* The next slot in the chain is not past the end of the current slot */ - *pRc = SQLITE_CORRUPT_PAGE(pPg); - } - return 0; - } - } - if( pc>maxPC+nByte-4 ){ - /* The free slot chain extends off the end of the page */ - *pRc = SQLITE_CORRUPT_PAGE(pPg); - } - return 0; -} - -/* -** Allocate nByte bytes of space from within the B-Tree page passed -** as the first argument. Write into *pIdx the index into pPage->aData[] -** of the first byte of allocated space. Return either SQLITE_OK or -** an error code (usually SQLITE_CORRUPT). -** -** The caller guarantees that there is sufficient space to make the -** allocation. This routine might need to defragment in order to bring -** all the space together, however. This routine will avoid using -** the first two bytes past the cell pointer area since presumably this -** allocation is being made in order to insert a new cell, so we will -** also end up needing a new cell pointer. -*/ -static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ - const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ - u8 * const data = pPage->aData; /* Local cache of pPage->aData */ - int top; /* First byte of cell content area */ - int rc = SQLITE_OK; /* Integer return code */ - int gap; /* First byte of gap between cell pointers and cell content */ - - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - assert( pPage->pBt ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( nByte>=0 ); /* Minimum cell size is 4 */ - assert( pPage->nFree>=nByte ); - assert( pPage->nOverflow==0 ); - assert( nByte < (int)(pPage->pBt->usableSize-8) ); - - assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); - gap = pPage->cellOffset + 2*pPage->nCell; - assert( gap<=65536 ); - /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size - ** and the reserved space is zero (the usual value for reserved space) - ** then the cell content offset of an empty page wants to be 65536. - ** However, that integer is too large to be stored in a 2-byte unsigned - ** integer, so a value of 0 is used in its place. */ - top = get2byte(&data[hdr+5]); - assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */ - if( gap>top ){ - if( top==0 && pPage->pBt->usableSize==65536 ){ - top = 65536; - }else{ - return SQLITE_CORRUPT_PAGE(pPage); - } - } - - /* If there is enough space between gap and top for one more cell pointer, - ** and if the freelist is not empty, then search the - ** freelist looking for a slot big enough to satisfy the request. - */ - testcase( gap+2==top ); - testcase( gap+1==top ); - testcase( gap==top ); - if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){ - u8 *pSpace = pageFindSlot(pPage, nByte, &rc); - if( pSpace ){ - int g2; - assert( pSpace+nByte<=data+pPage->pBt->usableSize ); - *pIdx = g2 = (int)(pSpace-data); - if( NEVER(g2<=gap) ){ - return SQLITE_CORRUPT_PAGE(pPage); - }else{ - return SQLITE_OK; - } - }else if( rc ){ - return rc; - } - } - - /* The request could not be fulfilled using a freelist slot. Check - ** to see if defragmentation is necessary. - */ - testcase( gap+2+nByte==top ); - if( gap+2+nByte>top ){ - assert( pPage->nCell>0 || CORRUPT_DB ); - assert( pPage->nFree>=0 ); - rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte))); - if( rc ) return rc; - top = get2byteNotZero(&data[hdr+5]); - assert( gap+2+nByte<=top ); - } - - - /* Allocate memory from the gap in between the cell pointer array - ** and the cell content area. The btreeComputeFreeSpace() call has already - ** validated the freelist. Given that the freelist is valid, there - ** is no way that the allocation can extend off the end of the page. - ** The assert() below verifies the previous sentence. - */ - top -= nByte; - put2byte(&data[hdr+5], top); - assert( top+nByte <= (int)pPage->pBt->usableSize ); - *pIdx = top; - return SQLITE_OK; -} - -/* -** Return a section of the pPage->aData to the freelist. -** The first byte of the new free block is pPage->aData[iStart] -** and the size of the block is iSize bytes. -** -** Adjacent freeblocks are coalesced. -** -** Even though the freeblock list was checked by btreeComputeFreeSpace(), -** that routine will not detect overlap between cells or freeblocks. Nor -** does it detect cells or freeblocks that encrouch into the reserved bytes -** at the end of the page. So do additional corruption checks inside this -** routine and return SQLITE_CORRUPT if any problems are found. -*/ -static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ - u16 iPtr; /* Address of ptr to next freeblock */ - u16 iFreeBlk; /* Address of the next freeblock */ - u8 hdr; /* Page header size. 0 or 100 */ - u8 nFrag = 0; /* Reduction in fragmentation */ - u16 iOrigSize = iSize; /* Original value of iSize */ - u16 x; /* Offset to cell content area */ - u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ - unsigned char *data = pPage->aData; /* Page content */ - - assert( pPage->pBt!=0 ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); - assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( iSize>=4 ); /* Minimum cell size is 4 */ - assert( iStart<=pPage->pBt->usableSize-4 ); - - /* The list of freeblocks must be in ascending order. Find the - ** spot on the list where iStart should be inserted. - */ - hdr = pPage->hdrOffset; - iPtr = hdr + 1; - if( data[iPtr+1]==0 && data[iPtr]==0 ){ - iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ - }else{ - while( (iFreeBlk = get2byte(&data[iPtr]))pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */ - return SQLITE_CORRUPT_PAGE(pPage); - } - assert( iFreeBlk>iPtr || iFreeBlk==0 ); - - /* At this point: - ** iFreeBlk: First freeblock after iStart, or zero if none - ** iPtr: The address of a pointer to iFreeBlk - ** - ** Check to see if iFreeBlk should be coalesced onto the end of iStart. - */ - if( iFreeBlk && iEnd+3>=iFreeBlk ){ - nFrag = iFreeBlk - iEnd; - if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage); - iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); - if( iEnd > pPage->pBt->usableSize ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - iSize = iEnd - iStart; - iFreeBlk = get2byte(&data[iFreeBlk]); - } - - /* If iPtr is another freeblock (that is, if iPtr is not the freelist - ** pointer in the page header) then check to see if iStart should be - ** coalesced onto the end of iPtr. - */ - if( iPtr>hdr+1 ){ - int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); - if( iPtrEnd+3>=iStart ){ - if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage); - nFrag += iStart - iPtrEnd; - iSize = iEnd - iPtr; - iStart = iPtr; - } - } - if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage); - data[hdr+7] -= nFrag; - } - x = get2byte(&data[hdr+5]); - if( iStart<=x ){ - /* The new freeblock is at the beginning of the cell content area, - ** so just extend the cell content area rather than create another - ** freelist entry */ - if( iStartpBt->btsFlags & BTS_FAST_SECURE ){ - /* Overwrite deleted information with zeros when the secure_delete - ** option is enabled */ - memset(&data[iStart], 0, iSize); - } - put2byte(&data[iStart], iFreeBlk); - put2byte(&data[iStart+2], iSize); - pPage->nFree += iOrigSize; - return SQLITE_OK; -} - -/* -** Decode the flags byte (the first byte of the header) for a page -** and initialize fields of the MemPage structure accordingly. -** -** Only the following combinations are supported. Anything different -** indicates a corrupt database files: -** -** PTF_ZERODATA -** PTF_ZERODATA | PTF_LEAF -** PTF_LEAFDATA | PTF_INTKEY -** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF -*/ -static int decodeFlags(MemPage *pPage, int flagByte){ - BtShared *pBt; /* A copy of pPage->pBt */ - - assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); - flagByte &= ~PTF_LEAF; - pPage->childPtrSize = 4-4*pPage->leaf; - pPage->xCellSize = cellSizePtr; - pBt = pPage->pBt; - if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ - /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an - ** interior table b-tree page. */ - assert( (PTF_LEAFDATA|PTF_INTKEY)==5 ); - /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a - ** leaf table b-tree page. */ - assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 ); - pPage->intKey = 1; - if( pPage->leaf ){ - pPage->intKeyLeaf = 1; - pPage->xParseCell = btreeParseCellPtr; - }else{ - pPage->intKeyLeaf = 0; - pPage->xCellSize = cellSizePtrNoPayload; - pPage->xParseCell = btreeParseCellPtrNoPayload; - } - pPage->maxLocal = pBt->maxLeaf; - pPage->minLocal = pBt->minLeaf; - }else if( flagByte==PTF_ZERODATA ){ - /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an - ** interior index b-tree page. */ - assert( (PTF_ZERODATA)==2 ); - /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a - ** leaf index b-tree page. */ - assert( (PTF_ZERODATA|PTF_LEAF)==10 ); - pPage->intKey = 0; - pPage->intKeyLeaf = 0; - pPage->xParseCell = btreeParseCellPtrIndex; - pPage->maxLocal = pBt->maxLocal; - pPage->minLocal = pBt->minLocal; - }else{ - /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is - ** an error. */ - return SQLITE_CORRUPT_PAGE(pPage); - } - pPage->max1bytePayload = pBt->max1bytePayload; - return SQLITE_OK; -} - -/* -** Compute the amount of freespace on the page. In other words, fill -** in the pPage->nFree field. -*/ -static int btreeComputeFreeSpace(MemPage *pPage){ - int pc; /* Address of a freeblock within pPage->aData[] */ - u8 hdr; /* Offset to beginning of page header */ - u8 *data; /* Equal to pPage->aData */ - int usableSize; /* Amount of usable space on each page */ - int nFree; /* Number of unused bytes on the page */ - int top; /* First byte of the cell content area */ - int iCellFirst; /* First allowable cell or freeblock offset */ - int iCellLast; /* Last possible cell or freeblock offset */ - - assert( pPage->pBt!=0 ); - assert( pPage->pBt->db!=0 ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); - assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); - assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); - assert( pPage->isInit==1 ); - assert( pPage->nFree<0 ); - - usableSize = pPage->pBt->usableSize; - hdr = pPage->hdrOffset; - data = pPage->aData; - /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates - ** the start of the cell content area. A zero value for this integer is - ** interpreted as 65536. */ - top = get2byteNotZero(&data[hdr+5]); - iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell; - iCellLast = usableSize - 4; - - /* Compute the total free space on the page - ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the - ** start of the first freeblock on the page, or is zero if there are no - ** freeblocks. */ - pc = get2byte(&data[hdr+1]); - nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */ - if( pc>0 ){ - u32 next, size; - if( pciCellLast ){ - /* Freeblock off the end of the page */ - return SQLITE_CORRUPT_PAGE(pPage); - } - next = get2byte(&data[pc]); - size = get2byte(&data[pc+2]); - nFree = nFree + size; - if( next<=pc+size+3 ) break; - pc = next; - } - if( next>0 ){ - /* Freeblock not in ascending order */ - return SQLITE_CORRUPT_PAGE(pPage); - } - if( pc+size>(unsigned int)usableSize ){ - /* Last freeblock extends past page end */ - return SQLITE_CORRUPT_PAGE(pPage); - } - } - - /* At this point, nFree contains the sum of the offset to the start - ** of the cell-content area plus the number of free bytes within - ** the cell-content area. If this is greater than the usable-size - ** of the page, then the page must be corrupted. This check also - ** serves to verify that the offset to the start of the cell-content - ** area, according to the page header, lies within the page. - */ - if( nFree>usableSize || nFreenFree = (u16)(nFree - iCellFirst); - return SQLITE_OK; -} - -/* -** Do additional sanity check after btreeInitPage() if -** PRAGMA cell_size_check=ON -*/ -static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){ - int iCellFirst; /* First allowable cell or freeblock offset */ - int iCellLast; /* Last possible cell or freeblock offset */ - int i; /* Index into the cell pointer array */ - int sz; /* Size of a cell */ - int pc; /* Address of a freeblock within pPage->aData[] */ - u8 *data; /* Equal to pPage->aData */ - int usableSize; /* Maximum usable space on the page */ - int cellOffset; /* Start of cell content area */ - - iCellFirst = pPage->cellOffset + 2*pPage->nCell; - usableSize = pPage->pBt->usableSize; - iCellLast = usableSize - 4; - data = pPage->aData; - cellOffset = pPage->cellOffset; - if( !pPage->leaf ) iCellLast--; - for(i=0; inCell; i++){ - pc = get2byteAligned(&data[cellOffset+i*2]); - testcase( pc==iCellFirst ); - testcase( pc==iCellLast ); - if( pciCellLast ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - sz = pPage->xCellSize(pPage, &data[pc]); - testcase( pc+sz==usableSize ); - if( pc+sz>usableSize ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - } - return SQLITE_OK; -} - -/* -** Initialize the auxiliary information for a disk block. -** -** Return SQLITE_OK on success. If we see that the page does -** not contain a well-formed database page, then return -** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not -** guarantee that the page is well-formed. It only shows that -** we failed to detect any corruption. -*/ -static int btreeInitPage(MemPage *pPage){ - u8 *data; /* Equal to pPage->aData */ - BtShared *pBt; /* The main btree structure */ - - assert( pPage->pBt!=0 ); - assert( pPage->pBt->db!=0 ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); - assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); - assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); - assert( pPage->isInit==0 ); - - pBt = pPage->pBt; - data = pPage->aData + pPage->hdrOffset; - /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating - ** the b-tree page type. */ - if( decodeFlags(pPage, data[0]) ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); - pPage->maskPage = (u16)(pBt->pageSize - 1); - pPage->nOverflow = 0; - pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize; - pPage->aCellIdx = data + pPage->childPtrSize + 8; - pPage->aDataEnd = pPage->aData + pBt->usableSize; - pPage->aDataOfst = pPage->aData + pPage->childPtrSize; - /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the - ** number of cells on the page. */ - pPage->nCell = get2byte(&data[3]); - if( pPage->nCell>MX_CELL(pBt) ){ - /* To many cells for a single page. The page must be corrupt */ - return SQLITE_CORRUPT_PAGE(pPage); - } - testcase( pPage->nCell==MX_CELL(pBt) ); - /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only - ** possible for a root page of a table that contains no rows) then the - ** offset to the cell content area will equal the page size minus the - ** bytes of reserved space. */ - assert( pPage->nCell>0 - || get2byteNotZero(&data[5])==(int)pBt->usableSize - || CORRUPT_DB ); - pPage->nFree = -1; /* Indicate that this value is yet uncomputed */ - pPage->isInit = 1; - if( pBt->db->flags & SQLITE_CellSizeCk ){ - return btreeCellSizeCheck(pPage); - } - return SQLITE_OK; -} - -/* -** Set up a raw page so that it looks like a database page holding -** no entries. -*/ -static void zeroPage(MemPage *pPage, int flags){ - unsigned char *data = pPage->aData; - BtShared *pBt = pPage->pBt; - u8 hdr = pPage->hdrOffset; - u16 first; - - assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); - assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); - assert( sqlite3PagerGetData(pPage->pDbPage) == data ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - assert( sqlite3_mutex_held(pBt->mutex) ); - if( pBt->btsFlags & BTS_FAST_SECURE ){ - memset(&data[hdr], 0, pBt->usableSize - hdr); - } - data[hdr] = (char)flags; - first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8); - memset(&data[hdr+1], 0, 4); - data[hdr+7] = 0; - put2byte(&data[hdr+5], pBt->usableSize); - pPage->nFree = (u16)(pBt->usableSize - first); - decodeFlags(pPage, flags); - pPage->cellOffset = first; - pPage->aDataEnd = &data[pBt->usableSize]; - pPage->aCellIdx = &data[first]; - pPage->aDataOfst = &data[pPage->childPtrSize]; - pPage->nOverflow = 0; - assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); - pPage->maskPage = (u16)(pBt->pageSize - 1); - pPage->nCell = 0; - pPage->isInit = 1; -} - - -/* -** Convert a DbPage obtained from the pager into a MemPage used by -** the btree layer. -*/ -static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){ - MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); - if( pgno!=pPage->pgno ){ - pPage->aData = sqlite3PagerGetData(pDbPage); - pPage->pDbPage = pDbPage; - pPage->pBt = pBt; - pPage->pgno = pgno; - pPage->hdrOffset = pgno==1 ? 100 : 0; - } - assert( pPage->aData==sqlite3PagerGetData(pDbPage) ); - return pPage; -} - -/* -** Get a page from the pager. Initialize the MemPage.pBt and -** MemPage.aData elements if needed. See also: btreeGetUnusedPage(). -** -** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care -** about the content of the page at this time. So do not go to the disk -** to fetch the content. Just fill in the content with zeros for now. -** If in the future we call sqlite3PagerWrite() on this page, that -** means we have started to be concerned about content and the disk -** read should occur at that point. -*/ -static int btreeGetPage( - BtShared *pBt, /* The btree */ - Pgno pgno, /* Number of the page to fetch */ - MemPage **ppPage, /* Return the page in this parameter */ - int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ -){ - int rc; - DbPage *pDbPage; - - assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); - assert( sqlite3_mutex_held(pBt->mutex) ); - rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); - if( rc ) return rc; - *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); - return SQLITE_OK; -} - -/* -** Retrieve a page from the pager cache. If the requested page is not -** already in the pager cache return NULL. Initialize the MemPage.pBt and -** MemPage.aData elements if needed. -*/ -static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){ - DbPage *pDbPage; - assert( sqlite3_mutex_held(pBt->mutex) ); - pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); - if( pDbPage ){ - return btreePageFromDbPage(pDbPage, pgno, pBt); - } - return 0; -} - -/* -** Return the size of the database file in pages. If there is any kind of -** error, return ((unsigned int)-1). -*/ -static Pgno btreePagecount(BtShared *pBt){ - return pBt->nPage; -} -SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree *p){ - assert( sqlite3BtreeHoldsMutex(p) ); - return btreePagecount(p->pBt); -} - -/* -** Get a page from the pager and initialize it. -** -** If pCur!=0 then the page is being fetched as part of a moveToChild() -** call. Do additional sanity checking on the page in this case. -** And if the fetch fails, this routine must decrement pCur->iPage. -** -** The page is fetched as read-write unless pCur is not NULL and is -** a read-only cursor. -** -** If an error occurs, then *ppPage is undefined. It -** may remain unchanged, or it may be set to an invalid value. -*/ -static int getAndInitPage( - BtShared *pBt, /* The database file */ - Pgno pgno, /* Number of the page to get */ - MemPage **ppPage, /* Write the page pointer here */ - BtCursor *pCur, /* Cursor to receive the page, or NULL */ - int bReadOnly /* True for a read-only page */ -){ - int rc; - DbPage *pDbPage; - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( pCur==0 || ppPage==&pCur->pPage ); - assert( pCur==0 || bReadOnly==pCur->curPagerFlags ); - assert( pCur==0 || pCur->iPage>0 ); - - if( pgno>btreePagecount(pBt) ){ - rc = SQLITE_CORRUPT_BKPT; - goto getAndInitPage_error1; - } - rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); - if( rc ){ - goto getAndInitPage_error1; - } - *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); - if( (*ppPage)->isInit==0 ){ - btreePageFromDbPage(pDbPage, pgno, pBt); - rc = btreeInitPage(*ppPage); - if( rc!=SQLITE_OK ){ - goto getAndInitPage_error2; - } - } - assert( (*ppPage)->pgno==pgno ); - assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) ); - - /* If obtaining a child page for a cursor, we must verify that the page is - ** compatible with the root page. */ - if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){ - rc = SQLITE_CORRUPT_PGNO(pgno); - goto getAndInitPage_error2; - } - return SQLITE_OK; - -getAndInitPage_error2: - releasePage(*ppPage); -getAndInitPage_error1: - if( pCur ){ - pCur->iPage--; - pCur->pPage = pCur->apPage[pCur->iPage]; - } - testcase( pgno==0 ); - assert( pgno!=0 || rc==SQLITE_CORRUPT ); - return rc; -} - -/* -** Release a MemPage. This should be called once for each prior -** call to btreeGetPage. -** -** Page1 is a special case and must be released using releasePageOne(). -*/ -static void releasePageNotNull(MemPage *pPage){ - assert( pPage->aData ); - assert( pPage->pBt ); - assert( pPage->pDbPage!=0 ); - assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); - assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - sqlite3PagerUnrefNotNull(pPage->pDbPage); -} -static void releasePage(MemPage *pPage){ - if( pPage ) releasePageNotNull(pPage); -} -static void releasePageOne(MemPage *pPage){ - assert( pPage!=0 ); - assert( pPage->aData ); - assert( pPage->pBt ); - assert( pPage->pDbPage!=0 ); - assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); - assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - sqlite3PagerUnrefPageOne(pPage->pDbPage); -} - -/* -** Get an unused page. -** -** This works just like btreeGetPage() with the addition: -** -** * If the page is already in use for some other purpose, immediately -** release it and return an SQLITE_CURRUPT error. -** * Make sure the isInit flag is clear -*/ -static int btreeGetUnusedPage( - BtShared *pBt, /* The btree */ - Pgno pgno, /* Number of the page to fetch */ - MemPage **ppPage, /* Return the page in this parameter */ - int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ -){ - int rc = btreeGetPage(pBt, pgno, ppPage, flags); - if( rc==SQLITE_OK ){ - if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ - releasePage(*ppPage); - *ppPage = 0; - return SQLITE_CORRUPT_BKPT; - } - (*ppPage)->isInit = 0; - }else{ - *ppPage = 0; - } - return rc; -} - - -/* -** During a rollback, when the pager reloads information into the cache -** so that the cache is restored to its original state at the start of -** the transaction, for each page restored this routine is called. -** -** This routine needs to reset the extra data section at the end of the -** page to agree with the restored data. -*/ -static void pageReinit(DbPage *pData){ - MemPage *pPage; - pPage = (MemPage *)sqlite3PagerGetExtra(pData); - assert( sqlite3PagerPageRefcount(pData)>0 ); - if( pPage->isInit ){ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - pPage->isInit = 0; - if( sqlite3PagerPageRefcount(pData)>1 ){ - /* pPage might not be a btree page; it might be an overflow page - ** or ptrmap page or a free page. In those cases, the following - ** call to btreeInitPage() will likely return SQLITE_CORRUPT. - ** But no harm is done by this. And it is very important that - ** btreeInitPage() be called on every btree page so we make - ** the call for every page that comes in for re-initing. */ - btreeInitPage(pPage); - } - } -} - -/* -** Invoke the busy handler for a btree. -*/ -static int btreeInvokeBusyHandler(void *pArg){ - BtShared *pBt = (BtShared*)pArg; - assert( pBt->db ); - assert( sqlite3_mutex_held(pBt->db->mutex) ); - return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); -} - -/* -** Open a database file. -** -** zFilename is the name of the database file. If zFilename is NULL -** then an ephemeral database is created. The ephemeral database might -** be exclusively in memory, or it might use a disk-based memory cache. -** Either way, the ephemeral database will be automatically deleted -** when sqlite3BtreeClose() is called. -** -** If zFilename is ":memory:" then an in-memory database is created -** that is automatically destroyed when it is closed. -** -** The "flags" parameter is a bitmask that might contain bits like -** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. -** -** If the database is already opened in the same database connection -** and we are in shared cache mode, then the open will fail with an -** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared -** objects in the same database connection since doing so will lead -** to problems with locking. -*/ -SQLITE_PRIVATE int sqlite3BtreeOpen( - sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ - const char *zFilename, /* Name of the file containing the BTree database */ - sqlite3 *db, /* Associated database handle */ - Btree **ppBtree, /* Pointer to new Btree object written here */ - int flags, /* Options */ - int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ -){ - BtShared *pBt = 0; /* Shared part of btree structure */ - Btree *p; /* Handle to return */ - sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ - int rc = SQLITE_OK; /* Result code from this function */ - u8 nReserve; /* Byte of unused space on each page */ - unsigned char zDbHeader[100]; /* Database header content */ - - /* True if opening an ephemeral, temporary database */ - const int isTempDb = zFilename==0 || zFilename[0]==0; - - /* Set the variable isMemdb to true for an in-memory database, or - ** false for a file-based database. - */ -#ifdef SQLITE_OMIT_MEMORYDB - const int isMemdb = 0; -#else - const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) - || (isTempDb && sqlite3TempInMemory(db)) - || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; -#endif - - assert( db!=0 ); - assert( pVfs!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); - assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ - - /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ - assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); - - /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ - assert( (flags & BTREE_SINGLE)==0 || isTempDb ); - - if( isMemdb ){ - flags |= BTREE_MEMORY; - } - if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ - vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; - } - p = sqlite3MallocZero(sizeof(Btree)); - if( !p ){ - return SQLITE_NOMEM_BKPT; - } - p->inTrans = TRANS_NONE; - p->db = db; -#ifndef SQLITE_OMIT_SHARED_CACHE - p->lock.pBtree = p; - p->lock.iTable = 1; -#endif - -#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) - /* - ** If this Btree is a candidate for shared cache, try to find an - ** existing BtShared object that we can share with - */ - if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ - if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ - int nFilename = sqlite3Strlen30(zFilename)+1; - int nFullPathname = pVfs->mxPathname+1; - char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename)); - MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) - - p->sharable = 1; - if( !zFullPathname ){ - sqlite3_free(p); - return SQLITE_NOMEM_BKPT; - } - if( isMemdb ){ - memcpy(zFullPathname, zFilename, nFilename); - }else{ - rc = sqlite3OsFullPathname(pVfs, zFilename, - nFullPathname, zFullPathname); - if( rc ){ - if( rc==SQLITE_OK_SYMLINK ){ - rc = SQLITE_OK; - }else{ - sqlite3_free(zFullPathname); - sqlite3_free(p); - return rc; - } - } - } -#if SQLITE_THREADSAFE - mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); - sqlite3_mutex_enter(mutexOpen); - mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); - sqlite3_mutex_enter(mutexShared); -#endif - for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ - assert( pBt->nRef>0 ); - if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) - && sqlite3PagerVfs(pBt->pPager)==pVfs ){ - int iDb; - for(iDb=db->nDb-1; iDb>=0; iDb--){ - Btree *pExisting = db->aDb[iDb].pBt; - if( pExisting && pExisting->pBt==pBt ){ - sqlite3_mutex_leave(mutexShared); - sqlite3_mutex_leave(mutexOpen); - sqlite3_free(zFullPathname); - sqlite3_free(p); - return SQLITE_CONSTRAINT; - } - } - p->pBt = pBt; - pBt->nRef++; - break; - } - } - sqlite3_mutex_leave(mutexShared); - sqlite3_free(zFullPathname); - } -#ifdef SQLITE_DEBUG - else{ - /* In debug mode, we mark all persistent databases as sharable - ** even when they are not. This exercises the locking code and - ** gives more opportunity for asserts(sqlite3_mutex_held()) - ** statements to find locking problems. - */ - p->sharable = 1; - } -#endif - } -#endif - if( pBt==0 ){ - /* - ** The following asserts make sure that structures used by the btree are - ** the right size. This is to guard against size changes that result - ** when compiling on a different architecture. - */ - assert( sizeof(i64)==8 ); - assert( sizeof(u64)==8 ); - assert( sizeof(u32)==4 ); - assert( sizeof(u16)==2 ); - assert( sizeof(Pgno)==4 ); - - pBt = sqlite3MallocZero( sizeof(*pBt) ); - if( pBt==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto btree_open_out; - } - rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, - sizeof(MemPage), flags, vfsFlags, pageReinit); - if( rc==SQLITE_OK ){ - sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); - rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); - } - if( rc!=SQLITE_OK ){ - goto btree_open_out; - } - pBt->openFlags = (u8)flags; - pBt->db = db; - sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt); - p->pBt = pBt; - - pBt->pCursor = 0; - pBt->pPage1 = 0; - if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; -#if defined(SQLITE_SECURE_DELETE) - pBt->btsFlags |= BTS_SECURE_DELETE; -#elif defined(SQLITE_FAST_SECURE_DELETE) - pBt->btsFlags |= BTS_OVERWRITE; -#endif - /* EVIDENCE-OF: R-51873-39618 The page size for a database file is - ** determined by the 2-byte integer located at an offset of 16 bytes from - ** the beginning of the database file. */ - pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); - if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE - || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ - pBt->pageSize = 0; -#ifndef SQLITE_OMIT_AUTOVACUUM - /* If the magic name ":memory:" will create an in-memory database, then - ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if - ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if - ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a - ** regular file-name. In this case the auto-vacuum applies as per normal. - */ - if( zFilename && !isMemdb ){ - pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); - pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); - } -#endif - nReserve = 0; - }else{ - /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is - ** determined by the one-byte unsigned integer found at an offset of 20 - ** into the database file header. */ - nReserve = zDbHeader[20]; - pBt->btsFlags |= BTS_PAGESIZE_FIXED; -#ifndef SQLITE_OMIT_AUTOVACUUM - pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); - pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); -#endif - } - rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); - if( rc ) goto btree_open_out; - pBt->usableSize = pBt->pageSize - nReserve; - assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ - -#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) - /* Add the new BtShared object to the linked list sharable BtShareds. - */ - pBt->nRef = 1; - if( p->sharable ){ - MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) - MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);) - if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ - pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); - if( pBt->mutex==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto btree_open_out; - } - } - sqlite3_mutex_enter(mutexShared); - pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); - GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt; - sqlite3_mutex_leave(mutexShared); - } -#endif - } - -#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) - /* If the new Btree uses a sharable pBtShared, then link the new - ** Btree into the list of all sharable Btrees for the same connection. - ** The list is kept in ascending order by pBt address. - */ - if( p->sharable ){ - int i; - Btree *pSib; - for(i=0; inDb; i++){ - if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ - while( pSib->pPrev ){ pSib = pSib->pPrev; } - if( (uptr)p->pBt<(uptr)pSib->pBt ){ - p->pNext = pSib; - p->pPrev = 0; - pSib->pPrev = p; - }else{ - while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){ - pSib = pSib->pNext; - } - p->pNext = pSib->pNext; - p->pPrev = pSib; - if( p->pNext ){ - p->pNext->pPrev = p; - } - pSib->pNext = p; - } - break; - } - } - } -#endif - *ppBtree = p; - -btree_open_out: - if( rc!=SQLITE_OK ){ - if( pBt && pBt->pPager ){ - sqlite3PagerClose(pBt->pPager, 0); - } - sqlite3_free(pBt); - sqlite3_free(p); - *ppBtree = 0; - }else{ - sqlite3_file *pFile; - - /* If the B-Tree was successfully opened, set the pager-cache size to the - ** default value. Except, when opening on an existing shared pager-cache, - ** do not change the pager-cache size. - */ - if( sqlite3BtreeSchema(p, 0, 0)==0 ){ - sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE); - } - - pFile = sqlite3PagerFile(pBt->pPager); - if( pFile->pMethods ){ - sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db); - } - } - if( mutexOpen ){ - assert( sqlite3_mutex_held(mutexOpen) ); - sqlite3_mutex_leave(mutexOpen); - } - assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 ); - return rc; -} - -/* -** Decrement the BtShared.nRef counter. When it reaches zero, -** remove the BtShared structure from the sharing list. Return -** true if the BtShared.nRef counter reaches zero and return -** false if it is still positive. -*/ -static int removeFromSharingList(BtShared *pBt){ -#ifndef SQLITE_OMIT_SHARED_CACHE - MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) - BtShared *pList; - int removed = 0; - - assert( sqlite3_mutex_notheld(pBt->mutex) ); - MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); ) - sqlite3_mutex_enter(pMainMtx); - pBt->nRef--; - if( pBt->nRef<=0 ){ - if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ - GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; - }else{ - pList = GLOBAL(BtShared*,sqlite3SharedCacheList); - while( ALWAYS(pList) && pList->pNext!=pBt ){ - pList=pList->pNext; - } - if( ALWAYS(pList) ){ - pList->pNext = pBt->pNext; - } - } - if( SQLITE_THREADSAFE ){ - sqlite3_mutex_free(pBt->mutex); - } - removed = 1; - } - sqlite3_mutex_leave(pMainMtx); - return removed; -#else - return 1; -#endif -} - -/* -** Make sure pBt->pTmpSpace points to an allocation of -** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child -** pointer. -*/ -static void allocateTempSpace(BtShared *pBt){ - if( !pBt->pTmpSpace ){ - pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); - - /* One of the uses of pBt->pTmpSpace is to format cells before - ** inserting them into a leaf page (function fillInCell()). If - ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes - ** by the various routines that manipulate binary cells. Which - ** can mean that fillInCell() only initializes the first 2 or 3 - ** bytes of pTmpSpace, but that the first 4 bytes are copied from - ** it into a database page. This is not actually a problem, but it - ** does cause a valgrind error when the 1 or 2 bytes of unitialized - ** data is passed to system call write(). So to avoid this error, - ** zero the first 4 bytes of temp space here. - ** - ** Also: Provide four bytes of initialized space before the - ** beginning of pTmpSpace as an area available to prepend the - ** left-child pointer to the beginning of a cell. - */ - if( pBt->pTmpSpace ){ - memset(pBt->pTmpSpace, 0, 8); - pBt->pTmpSpace += 4; - } - } -} - -/* -** Free the pBt->pTmpSpace allocation -*/ -static void freeTempSpace(BtShared *pBt){ - if( pBt->pTmpSpace ){ - pBt->pTmpSpace -= 4; - sqlite3PageFree(pBt->pTmpSpace); - pBt->pTmpSpace = 0; - } -} - -/* -** Close an open database and invalidate all cursors. -*/ -SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ - BtShared *pBt = p->pBt; - BtCursor *pCur; - - /* Close all cursors opened via this handle. */ - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - pCur = pBt->pCursor; - while( pCur ){ - BtCursor *pTmp = pCur; - pCur = pCur->pNext; - if( pTmp->pBtree==p ){ - sqlite3BtreeCloseCursor(pTmp); - } - } - - /* Rollback any active transaction and free the handle structure. - ** The call to sqlite3BtreeRollback() drops any table-locks held by - ** this handle. - */ - sqlite3BtreeRollback(p, SQLITE_OK, 0); - sqlite3BtreeLeave(p); - - /* If there are still other outstanding references to the shared-btree - ** structure, return now. The remainder of this procedure cleans - ** up the shared-btree. - */ - assert( p->wantToLock==0 && p->locked==0 ); - if( !p->sharable || removeFromSharingList(pBt) ){ - /* The pBt is no longer on the sharing list, so we can access - ** it without having to hold the mutex. - ** - ** Clean out and delete the BtShared object. - */ - assert( !pBt->pCursor ); - sqlite3PagerClose(pBt->pPager, p->db); - if( pBt->xFreeSchema && pBt->pSchema ){ - pBt->xFreeSchema(pBt->pSchema); - } - sqlite3DbFree(0, pBt->pSchema); - freeTempSpace(pBt); - sqlite3_free(pBt); - } - -#ifndef SQLITE_OMIT_SHARED_CACHE - assert( p->wantToLock==0 ); - assert( p->locked==0 ); - if( p->pPrev ) p->pPrev->pNext = p->pNext; - if( p->pNext ) p->pNext->pPrev = p->pPrev; -#endif - - sqlite3_free(p); - return SQLITE_OK; -} - -/* -** Change the "soft" limit on the number of pages in the cache. -** Unused and unmodified pages will be recycled when the number of -** pages in the cache exceeds this soft limit. But the size of the -** cache is allowed to grow larger than this limit if it contains -** dirty pages or pages still in active use. -*/ -SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ - BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - sqlite3PagerSetCachesize(pBt->pPager, mxPage); - sqlite3BtreeLeave(p); - return SQLITE_OK; -} - -/* -** Change the "spill" limit on the number of pages in the cache. -** If the number of pages exceeds this limit during a write transaction, -** the pager might attempt to "spill" pages to the journal early in -** order to free up memory. -** -** The value returned is the current spill size. If zero is passed -** as an argument, no changes are made to the spill size setting, so -** using mxPage of 0 is a way to query the current spill size. -*/ -SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){ - BtShared *pBt = p->pBt; - int res; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage); - sqlite3BtreeLeave(p); - return res; -} - -#if SQLITE_MAX_MMAP_SIZE>0 -/* -** Change the limit on the amount of the database file that may be -** memory mapped. -*/ -SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ - BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); - sqlite3BtreeLeave(p); - return SQLITE_OK; -} -#endif /* SQLITE_MAX_MMAP_SIZE>0 */ - -/* -** Change the way data is synced to disk in order to increase or decrease -** how well the database resists damage due to OS crashes and power -** failures. Level 1 is the same as asynchronous (no syncs() occur and -** there is a high probability of damage) Level 2 is the default. There -** is a very low but non-zero probability of damage. Level 3 reduces the -** probability of damage to near zero but with a write performance reduction. -*/ -#ifndef SQLITE_OMIT_PAGER_PRAGMAS -SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags( - Btree *p, /* The btree to set the safety level on */ - unsigned pgFlags /* Various PAGER_* flags */ -){ - BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - sqlite3PagerSetFlags(pBt->pPager, pgFlags); - sqlite3BtreeLeave(p); - return SQLITE_OK; -} -#endif - -/* -** Change the default pages size and the number of reserved bytes per page. -** Or, if the page size has already been fixed, return SQLITE_READONLY -** without changing anything. -** -** The page size must be a power of 2 between 512 and 65536. If the page -** size supplied does not meet this constraint then the page size is not -** changed. -** -** Page sizes are constrained to be a power of two so that the region -** of the database file used for locking (beginning at PENDING_BYTE, -** the first byte past the 1GB boundary, 0x40000000) needs to occur -** at the beginning of a page. -** -** If parameter nReserve is less than zero, then the number of reserved -** bytes per page is left unchanged. -** -** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size -** and autovacuum mode can no longer be changed. -*/ -SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ - int rc = SQLITE_OK; - int x; - BtShared *pBt = p->pBt; - assert( nReserve>=0 && nReserve<=255 ); - sqlite3BtreeEnter(p); - pBt->nReserveWanted = nReserve; - x = pBt->pageSize - pBt->usableSize; - if( nReservebtsFlags & BTS_PAGESIZE_FIXED ){ - sqlite3BtreeLeave(p); - return SQLITE_READONLY; - } - assert( nReserve>=0 && nReserve<=255 ); - if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && - ((pageSize-1)&pageSize)==0 ){ - assert( (pageSize & 7)==0 ); - assert( !pBt->pCursor ); - pBt->pageSize = (u32)pageSize; - freeTempSpace(pBt); - } - rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); - pBt->usableSize = pBt->pageSize - (u16)nReserve; - if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; - sqlite3BtreeLeave(p); - return rc; -} - -/* -** Return the currently defined page size -*/ -SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){ - return p->pBt->pageSize; -} - -/* -** This function is similar to sqlite3BtreeGetReserve(), except that it -** may only be called if it is guaranteed that the b-tree mutex is already -** held. -** -** This is useful in one special case in the backup API code where it is -** known that the shared b-tree mutex is held, but the mutex on the -** database handle that owns *p is not. In this case if sqlite3BtreeEnter() -** were to be called, it might collide with some other operation on the -** database handle that owns *p, causing undefined behavior. -*/ -SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){ - int n; - assert( sqlite3_mutex_held(p->pBt->mutex) ); - n = p->pBt->pageSize - p->pBt->usableSize; - return n; -} - -/* -** Return the number of bytes of space at the end of every page that -** are intentually left unused. This is the "reserved" space that is -** sometimes used by extensions. -** -** The value returned is the larger of the current reserve size and -** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES. -** The amount of reserve can only grow - never shrink. -*/ -SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree *p){ - int n1, n2; - sqlite3BtreeEnter(p); - n1 = (int)p->pBt->nReserveWanted; - n2 = sqlite3BtreeGetReserveNoMutex(p); - sqlite3BtreeLeave(p); - return n1>n2 ? n1 : n2; -} - - -/* -** Set the maximum page count for a database if mxPage is positive. -** No changes are made if mxPage is 0 or negative. -** Regardless of the value of mxPage, return the maximum page count. -*/ -SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){ - Pgno n; - sqlite3BtreeEnter(p); - n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); - sqlite3BtreeLeave(p); - return n; -} - -/* -** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags: -** -** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared -** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared -** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set -** newFlag==(-1) No changes -** -** This routine acts as a query if newFlag is less than zero -** -** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but -** freelist leaf pages are not written back to the database. Thus in-page -** deleted content is cleared, but freelist deleted content is not. -** -** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition -** that freelist leaf pages are written back into the database, increasing -** the amount of disk I/O. -*/ -SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ - int b; - if( p==0 ) return 0; - sqlite3BtreeEnter(p); - assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 ); - assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) ); - if( newFlag>=0 ){ - p->pBt->btsFlags &= ~BTS_FAST_SECURE; - p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag; - } - b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE; - sqlite3BtreeLeave(p); - return b; -} - -/* -** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' -** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it -** is disabled. The default value for the auto-vacuum property is -** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. -*/ -SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ -#ifdef SQLITE_OMIT_AUTOVACUUM - return SQLITE_READONLY; -#else - BtShared *pBt = p->pBt; - int rc = SQLITE_OK; - u8 av = (u8)autoVacuum; - - sqlite3BtreeEnter(p); - if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ - rc = SQLITE_READONLY; - }else{ - pBt->autoVacuum = av ?1:0; - pBt->incrVacuum = av==2 ?1:0; - } - sqlite3BtreeLeave(p); - return rc; -#endif -} - -/* -** Return the value of the 'auto-vacuum' property. If auto-vacuum is -** enabled 1 is returned. Otherwise 0. -*/ -SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){ -#ifdef SQLITE_OMIT_AUTOVACUUM - return BTREE_AUTOVACUUM_NONE; -#else - int rc; - sqlite3BtreeEnter(p); - rc = ( - (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: - (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: - BTREE_AUTOVACUUM_INCR - ); - sqlite3BtreeLeave(p); - return rc; -#endif -} - -/* -** If the user has not set the safety-level for this database connection -** using "PRAGMA synchronous", and if the safety-level is not already -** set to the value passed to this function as the second parameter, -** set it so. -*/ -#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \ - && !defined(SQLITE_OMIT_WAL) -static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){ - sqlite3 *db; - Db *pDb; - if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){ - while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; } - if( pDb->bSyncSet==0 - && pDb->safety_level!=safety_level - && pDb!=&db->aDb[1] - ){ - pDb->safety_level = safety_level; - sqlite3PagerSetFlags(pBt->pPager, - pDb->safety_level | (db->flags & PAGER_FLAGS_MASK)); - } - } -} -#else -# define setDefaultSyncFlag(pBt,safety_level) -#endif - -/* Forward declaration */ -static int newDatabase(BtShared*); - - -/* -** Get a reference to pPage1 of the database file. This will -** also acquire a readlock on that file. -** -** SQLITE_OK is returned on success. If the file is not a -** well-formed database file, then SQLITE_CORRUPT is returned. -** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM -** is returned if we run out of memory. -*/ -static int lockBtree(BtShared *pBt){ - int rc; /* Result code from subfunctions */ - MemPage *pPage1; /* Page 1 of the database file */ - u32 nPage; /* Number of pages in the database */ - u32 nPageFile = 0; /* Number of pages in the database file */ - u32 nPageHeader; /* Number of pages in the database according to hdr */ - - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( pBt->pPage1==0 ); - rc = sqlite3PagerSharedLock(pBt->pPager); - if( rc!=SQLITE_OK ) return rc; - rc = btreeGetPage(pBt, 1, &pPage1, 0); - if( rc!=SQLITE_OK ) return rc; - - /* Do some checking to help insure the file we opened really is - ** a valid database file. - */ - nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData); - sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile); - if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ - nPage = nPageFile; - } - if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){ - nPage = 0; - } - if( nPage>0 ){ - u32 pageSize; - u32 usableSize; - u8 *page1 = pPage1->aData; - rc = SQLITE_NOTADB; - /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins - ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d - ** 61 74 20 33 00. */ - if( memcmp(page1, zMagicHeader, 16)!=0 ){ - goto page1_init_failed; - } - -#ifdef SQLITE_OMIT_WAL - if( page1[18]>1 ){ - pBt->btsFlags |= BTS_READ_ONLY; - } - if( page1[19]>1 ){ - goto page1_init_failed; - } -#else - if( page1[18]>2 ){ - pBt->btsFlags |= BTS_READ_ONLY; - } - if( page1[19]>2 ){ - goto page1_init_failed; - } - - /* If the write version is set to 2, this database should be accessed - ** in WAL mode. If the log is not already open, open it now. Then - ** return SQLITE_OK and return without populating BtShared.pPage1. - ** The caller detects this and calls this function again. This is - ** required as the version of page 1 currently in the page1 buffer - ** may not be the latest version - there may be a newer one in the log - ** file. - */ - if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ - int isOpen = 0; - rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); - if( rc!=SQLITE_OK ){ - goto page1_init_failed; - }else{ - setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1); - if( isOpen==0 ){ - releasePageOne(pPage1); - return SQLITE_OK; - } - } - rc = SQLITE_NOTADB; - }else{ - setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1); - } -#endif - - /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload - ** fractions and the leaf payload fraction values must be 64, 32, and 32. - ** - ** The original design allowed these amounts to vary, but as of - ** version 3.6.0, we require them to be fixed. - */ - if( memcmp(&page1[21], "\100\040\040",3)!=0 ){ - goto page1_init_failed; - } - /* EVIDENCE-OF: R-51873-39618 The page size for a database file is - ** determined by the 2-byte integer located at an offset of 16 bytes from - ** the beginning of the database file. */ - pageSize = (page1[16]<<8) | (page1[17]<<16); - /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two - ** between 512 and 65536 inclusive. */ - if( ((pageSize-1)&pageSize)!=0 - || pageSize>SQLITE_MAX_PAGE_SIZE - || pageSize<=256 - ){ - goto page1_init_failed; - } - pBt->btsFlags |= BTS_PAGESIZE_FIXED; - assert( (pageSize & 7)==0 ); - /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte - ** integer at offset 20 is the number of bytes of space at the end of - ** each page to reserve for extensions. - ** - ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is - ** determined by the one-byte unsigned integer found at an offset of 20 - ** into the database file header. */ - usableSize = pageSize - page1[20]; - if( (u32)pageSize!=pBt->pageSize ){ - /* After reading the first page of the database assuming a page size - ** of BtShared.pageSize, we have discovered that the page-size is - ** actually pageSize. Unlock the database, leave pBt->pPage1 at - ** zero and return SQLITE_OK. The caller will call this function - ** again with the correct page-size. - */ - releasePageOne(pPage1); - pBt->usableSize = usableSize; - pBt->pageSize = pageSize; - freeTempSpace(pBt); - rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, - pageSize-usableSize); - return rc; - } - if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){ - rc = SQLITE_CORRUPT_BKPT; - goto page1_init_failed; - } - /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to - ** be less than 480. In other words, if the page size is 512, then the - ** reserved space size cannot exceed 32. */ - if( usableSize<480 ){ - goto page1_init_failed; - } - pBt->pageSize = pageSize; - pBt->usableSize = usableSize; -#ifndef SQLITE_OMIT_AUTOVACUUM - pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); - pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); -#endif - } - - /* maxLocal is the maximum amount of payload to store locally for - ** a cell. Make sure it is small enough so that at least minFanout - ** cells can will fit on one page. We assume a 10-byte page header. - ** Besides the payload, the cell must store: - ** 2-byte pointer to the cell - ** 4-byte child pointer - ** 9-byte nKey value - ** 4-byte nData value - ** 4-byte overflow page pointer - ** So a cell consists of a 2-byte pointer, a header which is as much as - ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow - ** page pointer. - */ - pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); - pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); - pBt->maxLeaf = (u16)(pBt->usableSize - 35); - pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); - if( pBt->maxLocal>127 ){ - pBt->max1bytePayload = 127; - }else{ - pBt->max1bytePayload = (u8)pBt->maxLocal; - } - assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); - pBt->pPage1 = pPage1; - pBt->nPage = nPage; - return SQLITE_OK; - -page1_init_failed: - releasePageOne(pPage1); - pBt->pPage1 = 0; - return rc; -} - -#ifndef NDEBUG -/* -** Return the number of cursors open on pBt. This is for use -** in assert() expressions, so it is only compiled if NDEBUG is not -** defined. -** -** Only write cursors are counted if wrOnly is true. If wrOnly is -** false then all cursors are counted. -** -** For the purposes of this routine, a cursor is any cursor that -** is capable of reading or writing to the database. Cursors that -** have been tripped into the CURSOR_FAULT state are not counted. -*/ -static int countValidCursors(BtShared *pBt, int wrOnly){ - BtCursor *pCur; - int r = 0; - for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ - if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0) - && pCur->eState!=CURSOR_FAULT ) r++; - } - return r; -} -#endif - -/* -** If there are no outstanding cursors and we are not in the middle -** of a transaction but there is a read lock on the database, then -** this routine unrefs the first page of the database file which -** has the effect of releasing the read lock. -** -** If there is a transaction in progress, this routine is a no-op. -*/ -static void unlockBtreeIfUnused(BtShared *pBt){ - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); - if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ - MemPage *pPage1 = pBt->pPage1; - assert( pPage1->aData ); - assert( sqlite3PagerRefcount(pBt->pPager)==1 ); - pBt->pPage1 = 0; - releasePageOne(pPage1); - } -} - -/* -** If pBt points to an empty file then convert that empty file -** into a new empty database by initializing the first page of -** the database. -*/ -static int newDatabase(BtShared *pBt){ - MemPage *pP1; - unsigned char *data; - int rc; - - assert( sqlite3_mutex_held(pBt->mutex) ); - if( pBt->nPage>0 ){ - return SQLITE_OK; - } - pP1 = pBt->pPage1; - assert( pP1!=0 ); - data = pP1->aData; - rc = sqlite3PagerWrite(pP1->pDbPage); - if( rc ) return rc; - memcpy(data, zMagicHeader, sizeof(zMagicHeader)); - assert( sizeof(zMagicHeader)==16 ); - data[16] = (u8)((pBt->pageSize>>8)&0xff); - data[17] = (u8)((pBt->pageSize>>16)&0xff); - data[18] = 1; - data[19] = 1; - assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); - data[20] = (u8)(pBt->pageSize - pBt->usableSize); - data[21] = 64; - data[22] = 32; - data[23] = 32; - memset(&data[24], 0, 100-24); - zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); - pBt->btsFlags |= BTS_PAGESIZE_FIXED; -#ifndef SQLITE_OMIT_AUTOVACUUM - assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); - assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); - put4byte(&data[36 + 4*4], pBt->autoVacuum); - put4byte(&data[36 + 7*4], pBt->incrVacuum); -#endif - pBt->nPage = 1; - data[31] = 1; - return SQLITE_OK; -} - -/* -** Initialize the first page of the database file (creating a database -** consisting of a single page and no schema objects). Return SQLITE_OK -** if successful, or an SQLite error code otherwise. -*/ -SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){ - int rc; - sqlite3BtreeEnter(p); - p->pBt->nPage = 0; - rc = newDatabase(p->pBt); - sqlite3BtreeLeave(p); - return rc; -} - -/* -** Attempt to start a new transaction. A write-transaction -** is started if the second argument is nonzero, otherwise a read- -** transaction. If the second argument is 2 or more and exclusive -** transaction is started, meaning that no other process is allowed -** to access the database. A preexisting transaction may not be -** upgraded to exclusive by calling this routine a second time - the -** exclusivity flag only works for a new transaction. -** -** A write-transaction must be started before attempting any -** changes to the database. None of the following routines -** will work unless a transaction is started first: -** -** sqlite3BtreeCreateTable() -** sqlite3BtreeCreateIndex() -** sqlite3BtreeClearTable() -** sqlite3BtreeDropTable() -** sqlite3BtreeInsert() -** sqlite3BtreeDelete() -** sqlite3BtreeUpdateMeta() -** -** If an initial attempt to acquire the lock fails because of lock contention -** and the database was previously unlocked, then invoke the busy handler -** if there is one. But if there was previously a read-lock, do not -** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is -** returned when there is already a read-lock in order to avoid a deadlock. -** -** Suppose there are two processes A and B. A has a read lock and B has -** a reserved lock. B tries to promote to exclusive but is blocked because -** of A's read lock. A tries to promote to reserved but is blocked by B. -** One or the other of the two processes must give way or there can be -** no progress. By returning SQLITE_BUSY and not invoking the busy callback -** when A already has a read lock, we encourage A to give up and let B -** proceed. -*/ -SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){ - BtShared *pBt = p->pBt; - Pager *pPager = pBt->pPager; - int rc = SQLITE_OK; - - sqlite3BtreeEnter(p); - btreeIntegrity(p); - - /* If the btree is already in a write-transaction, or it - ** is already in a read-transaction and a read-transaction - ** is requested, this is a no-op. - */ - if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ - goto trans_begun; - } - assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); - - if( (p->db->flags & SQLITE_ResetDatabase) - && sqlite3PagerIsreadonly(pPager)==0 - ){ - pBt->btsFlags &= ~BTS_READ_ONLY; - } - - /* Write transactions are not possible on a read-only database */ - if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ - rc = SQLITE_READONLY; - goto trans_begun; - } - -#ifndef SQLITE_OMIT_SHARED_CACHE - { - sqlite3 *pBlock = 0; - /* If another database handle has already opened a write transaction - ** on this shared-btree structure and a second write transaction is - ** requested, return SQLITE_LOCKED. - */ - if( (wrflag && pBt->inTransaction==TRANS_WRITE) - || (pBt->btsFlags & BTS_PENDING)!=0 - ){ - pBlock = pBt->pWriter->db; - }else if( wrflag>1 ){ - BtLock *pIter; - for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ - if( pIter->pBtree!=p ){ - pBlock = pIter->pBtree->db; - break; - } - } - } - if( pBlock ){ - sqlite3ConnectionBlocked(p->db, pBlock); - rc = SQLITE_LOCKED_SHAREDCACHE; - goto trans_begun; - } - } -#endif - - /* Any read-only or read-write transaction implies a read-lock on - ** page 1. So if some other shared-cache client already has a write-lock - ** on page 1, the transaction cannot be opened. */ - rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK); - if( SQLITE_OK!=rc ) goto trans_begun; - - pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; - if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; - do { - sqlite3PagerWalDb(pPager, p->db); - -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT - /* If transitioning from no transaction directly to a write transaction, - ** block for the WRITER lock first if possible. */ - if( pBt->pPage1==0 && wrflag ){ - assert( pBt->inTransaction==TRANS_NONE ); - rc = sqlite3PagerWalWriteLock(pPager, 1); - if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break; - } -#endif - - /* Call lockBtree() until either pBt->pPage1 is populated or - ** lockBtree() returns something other than SQLITE_OK. lockBtree() - ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after - ** reading page 1 it discovers that the page-size of the database - ** file is not pBt->pageSize. In this case lockBtree() will update - ** pBt->pageSize to the page-size of the file on disk. - */ - while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); - - if( rc==SQLITE_OK && wrflag ){ - if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ - rc = SQLITE_READONLY; - }else{ - rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db)); - if( rc==SQLITE_OK ){ - rc = newDatabase(pBt); - }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){ - /* if there was no transaction opened when this function was - ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error - ** code to SQLITE_BUSY. */ - rc = SQLITE_BUSY; - } - } - } - - if( rc!=SQLITE_OK ){ - (void)sqlite3PagerWalWriteLock(pPager, 0); - unlockBtreeIfUnused(pBt); - } - }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && - btreeInvokeBusyHandler(pBt) ); - sqlite3PagerWalDb(pPager, 0); -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT - if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY; -#endif - - if( rc==SQLITE_OK ){ - if( p->inTrans==TRANS_NONE ){ - pBt->nTransaction++; -#ifndef SQLITE_OMIT_SHARED_CACHE - if( p->sharable ){ - assert( p->lock.pBtree==p && p->lock.iTable==1 ); - p->lock.eLock = READ_LOCK; - p->lock.pNext = pBt->pLock; - pBt->pLock = &p->lock; - } -#endif - } - p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); - if( p->inTrans>pBt->inTransaction ){ - pBt->inTransaction = p->inTrans; - } - if( wrflag ){ - MemPage *pPage1 = pBt->pPage1; -#ifndef SQLITE_OMIT_SHARED_CACHE - assert( !pBt->pWriter ); - pBt->pWriter = p; - pBt->btsFlags &= ~BTS_EXCLUSIVE; - if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; -#endif - - /* If the db-size header field is incorrect (as it may be if an old - ** client has been writing the database file), update it now. Doing - ** this sooner rather than later means the database size can safely - ** re-read the database size from page 1 if a savepoint or transaction - ** rollback occurs within the transaction. - */ - if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ - rc = sqlite3PagerWrite(pPage1->pDbPage); - if( rc==SQLITE_OK ){ - put4byte(&pPage1->aData[28], pBt->nPage); - } - } - } - } - -trans_begun: - if( rc==SQLITE_OK ){ - if( pSchemaVersion ){ - *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]); - } - if( wrflag ){ - /* This call makes sure that the pager has the correct number of - ** open savepoints. If the second parameter is greater than 0 and - ** the sub-journal is not already open, then it will be opened here. - */ - rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint); - } - } - - btreeIntegrity(p); - sqlite3BtreeLeave(p); - return rc; -} - -#ifndef SQLITE_OMIT_AUTOVACUUM - -/* -** Set the pointer-map entries for all children of page pPage. Also, if -** pPage contains cells that point to overflow pages, set the pointer -** map entries for the overflow pages as well. -*/ -static int setChildPtrmaps(MemPage *pPage){ - int i; /* Counter variable */ - int nCell; /* Number of cells in page pPage */ - int rc; /* Return code */ - BtShared *pBt = pPage->pBt; - Pgno pgno = pPage->pgno; - - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); - if( rc!=SQLITE_OK ) return rc; - nCell = pPage->nCell; - - for(i=0; ileaf ){ - Pgno childPgno = get4byte(pCell); - ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); - } - } - - if( !pPage->leaf ){ - Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); - ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc); - } - - return rc; -} - -/* -** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so -** that it points to iTo. Parameter eType describes the type of pointer to -** be modified, as follows: -** -** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child -** page of pPage. -** -** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow -** page pointed to by one of the cells on pPage. -** -** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next -** overflow page in the list. -*/ -static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - if( eType==PTRMAP_OVERFLOW2 ){ - /* The pointer is always the first 4 bytes of the page in this case. */ - if( get4byte(pPage->aData)!=iFrom ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - put4byte(pPage->aData, iTo); - }else{ - int i; - int nCell; - int rc; - - rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage); - if( rc ) return rc; - nCell = pPage->nCell; - - for(i=0; ixParseCell(pPage, pCell, &info); - if( info.nLocal pPage->aData+pPage->pBt->usableSize ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - if( iFrom==get4byte(pCell+info.nSize-4) ){ - put4byte(pCell+info.nSize-4, iTo); - break; - } - } - }else{ - if( get4byte(pCell)==iFrom ){ - put4byte(pCell, iTo); - break; - } - } - } - - if( i==nCell ){ - if( eType!=PTRMAP_BTREE || - get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); - } - } - return SQLITE_OK; -} - - -/* -** Move the open database page pDbPage to location iFreePage in the -** database. The pDbPage reference remains valid. -** -** The isCommit flag indicates that there is no need to remember that -** the journal needs to be sync()ed before database page pDbPage->pgno -** can be written to. The caller has already promised not to write to that -** page. -*/ -static int relocatePage( - BtShared *pBt, /* Btree */ - MemPage *pDbPage, /* Open page to move */ - u8 eType, /* Pointer map 'type' entry for pDbPage */ - Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ - Pgno iFreePage, /* The location to move pDbPage to */ - int isCommit /* isCommit flag passed to sqlite3PagerMovepage */ -){ - MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ - Pgno iDbPage = pDbPage->pgno; - Pager *pPager = pBt->pPager; - int rc; - - assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || - eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( pDbPage->pBt==pBt ); - if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT; - - /* Move page iDbPage from its current location to page number iFreePage */ - TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", - iDbPage, iFreePage, iPtrPage, eType)); - rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit); - if( rc!=SQLITE_OK ){ - return rc; - } - pDbPage->pgno = iFreePage; - - /* If pDbPage was a btree-page, then it may have child pages and/or cells - ** that point to overflow pages. The pointer map entries for all these - ** pages need to be changed. - ** - ** If pDbPage is an overflow page, then the first 4 bytes may store a - ** pointer to a subsequent overflow page. If this is the case, then - ** the pointer map needs to be updated for the subsequent overflow page. - */ - if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ - rc = setChildPtrmaps(pDbPage); - if( rc!=SQLITE_OK ){ - return rc; - } - }else{ - Pgno nextOvfl = get4byte(pDbPage->aData); - if( nextOvfl!=0 ){ - ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc); - if( rc!=SQLITE_OK ){ - return rc; - } - } - } - - /* Fix the database pointer on page iPtrPage that pointed at iDbPage so - ** that it points at iFreePage. Also fix the pointer map entry for - ** iPtrPage. - */ - if( eType!=PTRMAP_ROOTPAGE ){ - rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - rc = sqlite3PagerWrite(pPtrPage->pDbPage); - if( rc!=SQLITE_OK ){ - releasePage(pPtrPage); - return rc; - } - rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); - releasePage(pPtrPage); - if( rc==SQLITE_OK ){ - ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); - } - } - return rc; -} - -/* Forward declaration required by incrVacuumStep(). */ -static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); - -/* -** Perform a single step of an incremental-vacuum. If successful, return -** SQLITE_OK. If there is no work to do (and therefore no point in -** calling this function again), return SQLITE_DONE. Or, if an error -** occurs, return some other error code. -** -** More specifically, this function attempts to re-organize the database so -** that the last page of the file currently in use is no longer in use. -** -** Parameter nFin is the number of pages that this database would contain -** were this function called until it returns SQLITE_DONE. -** -** If the bCommit parameter is non-zero, this function assumes that the -** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE -** or an error. bCommit is passed true for an auto-vacuum-on-commit -** operation, or false for an incremental vacuum. -*/ -static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ - Pgno nFreeList; /* Number of pages still on the free-list */ - int rc; - - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( iLastPg>nFin ); - - if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ - u8 eType; - Pgno iPtrPage; - - nFreeList = get4byte(&pBt->pPage1->aData[36]); - if( nFreeList==0 ){ - return SQLITE_DONE; - } - - rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); - if( rc!=SQLITE_OK ){ - return rc; - } - if( eType==PTRMAP_ROOTPAGE ){ - return SQLITE_CORRUPT_BKPT; - } - - if( eType==PTRMAP_FREEPAGE ){ - if( bCommit==0 ){ - /* Remove the page from the files free-list. This is not required - ** if bCommit is non-zero. In that case, the free-list will be - ** truncated to zero after this function returns, so it doesn't - ** matter if it still contains some garbage entries. - */ - Pgno iFreePg; - MemPage *pFreePg; - rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); - if( rc!=SQLITE_OK ){ - return rc; - } - assert( iFreePg==iLastPg ); - releasePage(pFreePg); - } - } else { - Pgno iFreePg; /* Index of free page to move pLastPg to */ - MemPage *pLastPg; - u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ - Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ - - rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - - /* If bCommit is zero, this loop runs exactly once and page pLastPg - ** is swapped with the first free page pulled off the free list. - ** - ** On the other hand, if bCommit is greater than zero, then keep - ** looping until a free-page located within the first nFin pages - ** of the file is found. - */ - if( bCommit==0 ){ - eMode = BTALLOC_LE; - iNear = nFin; - } - do { - MemPage *pFreePg; - rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); - if( rc!=SQLITE_OK ){ - releasePage(pLastPg); - return rc; - } - releasePage(pFreePg); - }while( bCommit && iFreePg>nFin ); - assert( iFreePgbDoTruncate = 1; - pBt->nPage = iLastPg; - } - return SQLITE_OK; -} - -/* -** The database opened by the first argument is an auto-vacuum database -** nOrig pages in size containing nFree free pages. Return the expected -** size of the database in pages following an auto-vacuum operation. -*/ -static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ - int nEntry; /* Number of entries on one ptrmap page */ - Pgno nPtrmap; /* Number of PtrMap pages to be freed */ - Pgno nFin; /* Return value */ - - nEntry = pBt->usableSize/5; - nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; - nFin = nOrig - nFree - nPtrmap; - if( nOrig>PENDING_BYTE_PAGE(pBt) && nFinpBt; - - sqlite3BtreeEnter(p); - assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); - if( !pBt->autoVacuum ){ - rc = SQLITE_DONE; - }else{ - Pgno nOrig = btreePagecount(pBt); - Pgno nFree = get4byte(&pBt->pPage1->aData[36]); - Pgno nFin = finalDbSize(pBt, nOrig, nFree); - - if( nOrig=nOrig ){ - rc = SQLITE_CORRUPT_BKPT; - }else if( nFree>0 ){ - rc = saveAllCursors(pBt, 0, 0); - if( rc==SQLITE_OK ){ - invalidateAllOverflowCache(pBt); - rc = incrVacuumStep(pBt, nFin, nOrig, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); - put4byte(&pBt->pPage1->aData[28], pBt->nPage); - } - }else{ - rc = SQLITE_DONE; - } - } - sqlite3BtreeLeave(p); - return rc; -} - -/* -** This routine is called prior to sqlite3PagerCommit when a transaction -** is committed for an auto-vacuum database. -** -** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages -** the database file should be truncated to during the commit process. -** i.e. the database has been reorganized so that only the first *pnTrunc -** pages are in use. -*/ -static int autoVacuumCommit(BtShared *pBt){ - int rc = SQLITE_OK; - Pager *pPager = pBt->pPager; - VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); ) - - assert( sqlite3_mutex_held(pBt->mutex) ); - invalidateAllOverflowCache(pBt); - assert(pBt->autoVacuum); - if( !pBt->incrVacuum ){ - Pgno nFin; /* Number of pages in database after autovacuuming */ - Pgno nFree; /* Number of pages on the freelist initially */ - Pgno iFree; /* The next page to be freed */ - Pgno nOrig; /* Database size before freeing */ - - nOrig = btreePagecount(pBt); - if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ - /* It is not possible to create a database for which the final page - ** is either a pointer-map page or the pending-byte page. If one - ** is encountered, this indicates corruption. - */ - return SQLITE_CORRUPT_BKPT; - } - - nFree = get4byte(&pBt->pPage1->aData[36]); - nFin = finalDbSize(pBt, nOrig, nFree); - if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; - if( nFinnFin && rc==SQLITE_OK; iFree--){ - rc = incrVacuumStep(pBt, nFin, iFree, 1); - } - if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); - put4byte(&pBt->pPage1->aData[32], 0); - put4byte(&pBt->pPage1->aData[36], 0); - put4byte(&pBt->pPage1->aData[28], nFin); - pBt->bDoTruncate = 1; - pBt->nPage = nFin; - } - if( rc!=SQLITE_OK ){ - sqlite3PagerRollback(pPager); - } - } - - assert( nRef>=sqlite3PagerRefcount(pPager) ); - return rc; -} - -#else /* ifndef SQLITE_OMIT_AUTOVACUUM */ -# define setChildPtrmaps(x) SQLITE_OK -#endif - -/* -** This routine does the first phase of a two-phase commit. This routine -** causes a rollback journal to be created (if it does not already exist) -** and populated with enough information so that if a power loss occurs -** the database can be restored to its original state by playing back -** the journal. Then the contents of the journal are flushed out to -** the disk. After the journal is safely on oxide, the changes to the -** database are written into the database file and flushed to oxide. -** At the end of this call, the rollback journal still exists on the -** disk and we are still holding all locks, so the transaction has not -** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the -** commit process. -** -** This call is a no-op if no write-transaction is currently active on pBt. -** -** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to -** the name of a super-journal file that should be written into the -** individual journal file, or is NULL, indicating no super-journal file -** (single database transaction). -** -** When this is called, the super-journal should already have been -** created, populated with this journal pointer and synced to disk. -** -** Once this is routine has returned, the only thing required to commit -** the write-transaction for this database file is to delete the journal. -*/ -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){ - int rc = SQLITE_OK; - if( p->inTrans==TRANS_WRITE ){ - BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pBt->autoVacuum ){ - rc = autoVacuumCommit(pBt); - if( rc!=SQLITE_OK ){ - sqlite3BtreeLeave(p); - return rc; - } - } - if( pBt->bDoTruncate ){ - sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); - } -#endif - rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0); - sqlite3BtreeLeave(p); - } - return rc; -} - -/* -** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() -** at the conclusion of a transaction. -*/ -static void btreeEndTransaction(Btree *p){ - BtShared *pBt = p->pBt; - sqlite3 *db = p->db; - assert( sqlite3BtreeHoldsMutex(p) ); - -#ifndef SQLITE_OMIT_AUTOVACUUM - pBt->bDoTruncate = 0; -#endif - if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ - /* If there are other active statements that belong to this database - ** handle, downgrade to a read-only transaction. The other statements - ** may still be reading from the database. */ - downgradeAllSharedCacheTableLocks(p); - p->inTrans = TRANS_READ; - }else{ - /* If the handle had any kind of transaction open, decrement the - ** transaction count of the shared btree. If the transaction count - ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() - ** call below will unlock the pager. */ - if( p->inTrans!=TRANS_NONE ){ - clearAllSharedCacheTableLocks(p); - pBt->nTransaction--; - if( 0==pBt->nTransaction ){ - pBt->inTransaction = TRANS_NONE; - } - } - - /* Set the current transaction state to TRANS_NONE and unlock the - ** pager if this call closed the only read or write transaction. */ - p->inTrans = TRANS_NONE; - unlockBtreeIfUnused(pBt); - } - - btreeIntegrity(p); -} - -/* -** Commit the transaction currently in progress. -** -** This routine implements the second phase of a 2-phase commit. The -** sqlite3BtreeCommitPhaseOne() routine does the first phase and should -** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne() -** routine did all the work of writing information out to disk and flushing the -** contents so that they are written onto the disk platter. All this -** routine has to do is delete or truncate or zero the header in the -** the rollback journal (which causes the transaction to commit) and -** drop locks. -** -** Normally, if an error occurs while the pager layer is attempting to -** finalize the underlying journal file, this function returns an error and -** the upper layer will attempt a rollback. However, if the second argument -** is non-zero then this b-tree transaction is part of a multi-file -** transaction. In this case, the transaction has already been committed -** (by deleting a super-journal file) and the caller will ignore this -** functions return code. So, even if an error occurs in the pager layer, -** reset the b-tree objects internal state to indicate that the write -** transaction has been closed. This is quite safe, as the pager will have -** transitioned to the error state. -** -** This will release the write lock on the database file. If there -** are no active cursors, it also releases the read lock. -*/ -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){ - - if( p->inTrans==TRANS_NONE ) return SQLITE_OK; - sqlite3BtreeEnter(p); - btreeIntegrity(p); - - /* If the handle has a write-transaction open, commit the shared-btrees - ** transaction and set the shared state to TRANS_READ. - */ - if( p->inTrans==TRANS_WRITE ){ - int rc; - BtShared *pBt = p->pBt; - assert( pBt->inTransaction==TRANS_WRITE ); - assert( pBt->nTransaction>0 ); - rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); - if( rc!=SQLITE_OK && bCleanup==0 ){ - sqlite3BtreeLeave(p); - return rc; - } - p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */ - pBt->inTransaction = TRANS_READ; - btreeClearHasContent(pBt); - } - - btreeEndTransaction(p); - sqlite3BtreeLeave(p); - return SQLITE_OK; -} - -/* -** Do both phases of a commit. -*/ -SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){ - int rc; - sqlite3BtreeEnter(p); - rc = sqlite3BtreeCommitPhaseOne(p, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeCommitPhaseTwo(p, 0); - } - sqlite3BtreeLeave(p); - return rc; -} - -/* -** This routine sets the state to CURSOR_FAULT and the error -** code to errCode for every cursor on any BtShared that pBtree -** references. Or if the writeOnly flag is set to 1, then only -** trip write cursors and leave read cursors unchanged. -** -** Every cursor is a candidate to be tripped, including cursors -** that belong to other database connections that happen to be -** sharing the cache with pBtree. -** -** This routine gets called when a rollback occurs. If the writeOnly -** flag is true, then only write-cursors need be tripped - read-only -** cursors save their current positions so that they may continue -** following the rollback. Or, if writeOnly is false, all cursors are -** tripped. In general, writeOnly is false if the transaction being -** rolled back modified the database schema. In this case b-tree root -** pages may be moved or deleted from the database altogether, making -** it unsafe for read cursors to continue. -** -** If the writeOnly flag is true and an error is encountered while -** saving the current position of a read-only cursor, all cursors, -** including all read-cursors are tripped. -** -** SQLITE_OK is returned if successful, or if an error occurs while -** saving a cursor position, an SQLite error code. -*/ -SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ - BtCursor *p; - int rc = SQLITE_OK; - - assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); - if( pBtree ){ - sqlite3BtreeEnter(pBtree); - for(p=pBtree->pBt->pCursor; p; p=p->pNext){ - if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ - if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){ - rc = saveCursorPosition(p); - if( rc!=SQLITE_OK ){ - (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); - break; - } - } - }else{ - sqlite3BtreeClearCursor(p); - p->eState = CURSOR_FAULT; - p->skipNext = errCode; - } - btreeReleaseAllCursorPages(p); - } - sqlite3BtreeLeave(pBtree); - } - return rc; -} - -/* -** Set the pBt->nPage field correctly, according to the current -** state of the database. Assume pBt->pPage1 is valid. -*/ -static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){ - int nPage = get4byte(&pPage1->aData[28]); - testcase( nPage==0 ); - if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); - testcase( pBt->nPage!=nPage ); - pBt->nPage = nPage; -} - -/* -** Rollback the transaction in progress. -** -** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). -** Only write cursors are tripped if writeOnly is true but all cursors are -** tripped if writeOnly is false. Any attempt to use -** a tripped cursor will result in an error. -** -** This will release the write lock on the database file. If there -** are no active cursors, it also releases the read lock. -*/ -SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ - int rc; - BtShared *pBt = p->pBt; - MemPage *pPage1; - - assert( writeOnly==1 || writeOnly==0 ); - assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); - sqlite3BtreeEnter(p); - if( tripCode==SQLITE_OK ){ - rc = tripCode = saveAllCursors(pBt, 0, 0); - if( rc ) writeOnly = 0; - }else{ - rc = SQLITE_OK; - } - if( tripCode ){ - int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); - assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); - if( rc2!=SQLITE_OK ) rc = rc2; - } - btreeIntegrity(p); - - if( p->inTrans==TRANS_WRITE ){ - int rc2; - - assert( TRANS_WRITE==pBt->inTransaction ); - rc2 = sqlite3PagerRollback(pBt->pPager); - if( rc2!=SQLITE_OK ){ - rc = rc2; - } - - /* The rollback may have destroyed the pPage1->aData value. So - ** call btreeGetPage() on page 1 again to make - ** sure pPage1->aData is set correctly. */ - if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ - btreeSetNPage(pBt, pPage1); - releasePageOne(pPage1); - } - assert( countValidCursors(pBt, 1)==0 ); - pBt->inTransaction = TRANS_READ; - btreeClearHasContent(pBt); - } - - btreeEndTransaction(p); - sqlite3BtreeLeave(p); - return rc; -} - -/* -** Start a statement subtransaction. The subtransaction can be rolled -** back independently of the main transaction. You must start a transaction -** before starting a subtransaction. The subtransaction is ended automatically -** if the main transaction commits or rolls back. -** -** Statement subtransactions are used around individual SQL statements -** that are contained within a BEGIN...COMMIT block. If a constraint -** error occurs within the statement, the effect of that one statement -** can be rolled back without having to rollback the entire transaction. -** -** A statement sub-transaction is implemented as an anonymous savepoint. The -** value passed as the second parameter is the total number of savepoints, -** including the new anonymous savepoint, open on the B-Tree. i.e. if there -** are no active savepoints and no other statement-transactions open, -** iStatement is 1. This anonymous savepoint can be released or rolled back -** using the sqlite3BtreeSavepoint() function. -*/ -SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ - int rc; - BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); - assert( p->inTrans==TRANS_WRITE ); - assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); - assert( iStatement>0 ); - assert( iStatement>p->db->nSavepoint ); - assert( pBt->inTransaction==TRANS_WRITE ); - /* At the pager level, a statement transaction is a savepoint with - ** an index greater than all savepoints created explicitly using - ** SQL statements. It is illegal to open, release or rollback any - ** such savepoints while the statement transaction savepoint is active. - */ - rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); - sqlite3BtreeLeave(p); - return rc; -} - -/* -** The second argument to this function, op, is always SAVEPOINT_ROLLBACK -** or SAVEPOINT_RELEASE. This function either releases or rolls back the -** savepoint identified by parameter iSavepoint, depending on the value -** of op. -** -** Normally, iSavepoint is greater than or equal to zero. However, if op is -** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the -** contents of the entire transaction are rolled back. This is different -** from a normal transaction rollback, as no locks are released and the -** transaction remains open. -*/ -SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ - int rc = SQLITE_OK; - if( p && p->inTrans==TRANS_WRITE ){ - BtShared *pBt = p->pBt; - assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); - assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); - sqlite3BtreeEnter(p); - if( op==SAVEPOINT_ROLLBACK ){ - rc = saveAllCursors(pBt, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); - } - if( rc==SQLITE_OK ){ - if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ - pBt->nPage = 0; - } - rc = newDatabase(pBt); - btreeSetNPage(pBt, pBt->pPage1); - - /* pBt->nPage might be zero if the database was corrupt when - ** the transaction was started. Otherwise, it must be at least 1. */ - assert( CORRUPT_DB || pBt->nPage>0 ); - } - sqlite3BtreeLeave(p); - } - return rc; -} - -/* -** Create a new cursor for the BTree whose root is on the page -** iTable. If a read-only cursor is requested, it is assumed that -** the caller already has at least a read-only transaction open -** on the database already. If a write-cursor is requested, then -** the caller is assumed to have an open write transaction. -** -** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only -** be used for reading. If the BTREE_WRCSR bit is set, then the cursor -** can be used for reading or for writing if other conditions for writing -** are also met. These are the conditions that must be met in order -** for writing to be allowed: -** -** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR -** -** 2: Other database connections that share the same pager cache -** but which are not in the READ_UNCOMMITTED state may not have -** cursors open with wrFlag==0 on the same table. Otherwise -** the changes made by this write cursor would be visible to -** the read cursors in the other database connection. -** -** 3: The database must be writable (not on read-only media) -** -** 4: There must be an active transaction. -** -** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR -** is set. If FORDELETE is set, that is a hint to the implementation that -** this cursor will only be used to seek to and delete entries of an index -** as part of a larger DELETE statement. The FORDELETE hint is not used by -** this implementation. But in a hypothetical alternative storage engine -** in which index entries are automatically deleted when corresponding table -** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE -** operations on this cursor can be no-ops and all READ operations can -** return a null row (2-bytes: 0x01 0x00). -** -** No checking is done to make sure that page iTable really is the -** root page of a b-tree. If it is not, then the cursor acquired -** will not work correctly. -** -** It is assumed that the sqlite3BtreeCursorZero() has been called -** on pCur to initialize the memory space prior to invoking this routine. -*/ -static int btreeCursor( - Btree *p, /* The btree */ - Pgno iTable, /* Root page of table to open */ - int wrFlag, /* 1 to write. 0 read-only */ - struct KeyInfo *pKeyInfo, /* First arg to comparison function */ - BtCursor *pCur /* Space for new cursor */ -){ - BtShared *pBt = p->pBt; /* Shared b-tree handle */ - BtCursor *pX; /* Looping over other all cursors */ - - assert( sqlite3BtreeHoldsMutex(p) ); - assert( wrFlag==0 - || wrFlag==BTREE_WRCSR - || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) - ); - - /* The following assert statements verify that if this is a sharable - ** b-tree database, the connection is holding the required table locks, - ** and that no other connection has any open cursor that conflicts with - ** this lock. The iTable<1 term disables the check for corrupt schemas. */ - assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) - || iTable<1 ); - assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); - - /* Assert that the caller has opened the required transaction. */ - assert( p->inTrans>TRANS_NONE ); - assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); - assert( pBt->pPage1 && pBt->pPage1->aData ); - assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 ); - - if( wrFlag ){ - allocateTempSpace(pBt); - if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT; - } - if( iTable<=1 ){ - if( iTable<1 ){ - return SQLITE_CORRUPT_BKPT; - }else if( btreePagecount(pBt)==0 ){ - assert( wrFlag==0 ); - iTable = 0; - } - } - - /* Now that no other errors can occur, finish filling in the BtCursor - ** variables and link the cursor into the BtShared list. */ - pCur->pgnoRoot = iTable; - pCur->iPage = -1; - pCur->pKeyInfo = pKeyInfo; - pCur->pBtree = p; - pCur->pBt = pBt; - pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0; - pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY; - /* If there are two or more cursors on the same btree, then all such - ** cursors *must* have the BTCF_Multiple flag set. */ - for(pX=pBt->pCursor; pX; pX=pX->pNext){ - if( pX->pgnoRoot==iTable ){ - pX->curFlags |= BTCF_Multiple; - pCur->curFlags |= BTCF_Multiple; - } - } - pCur->pNext = pBt->pCursor; - pBt->pCursor = pCur; - pCur->eState = CURSOR_INVALID; - return SQLITE_OK; -} -static int btreeCursorWithLock( - Btree *p, /* The btree */ - Pgno iTable, /* Root page of table to open */ - int wrFlag, /* 1 to write. 0 read-only */ - struct KeyInfo *pKeyInfo, /* First arg to comparison function */ - BtCursor *pCur /* Space for new cursor */ -){ - int rc; - sqlite3BtreeEnter(p); - rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); - sqlite3BtreeLeave(p); - return rc; -} -SQLITE_PRIVATE int sqlite3BtreeCursor( - Btree *p, /* The btree */ - Pgno iTable, /* Root page of table to open */ - int wrFlag, /* 1 to write. 0 read-only */ - struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ - BtCursor *pCur /* Write new cursor here */ -){ - if( p->sharable ){ - return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur); - }else{ - return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); - } -} - -/* -** Return the size of a BtCursor object in bytes. -** -** This interfaces is needed so that users of cursors can preallocate -** sufficient storage to hold a cursor. The BtCursor object is opaque -** to users so they cannot do the sizeof() themselves - they must call -** this routine. -*/ -SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){ - return ROUND8(sizeof(BtCursor)); -} - -/* -** Initialize memory that will be converted into a BtCursor object. -** -** The simple approach here would be to memset() the entire object -** to zero. But it turns out that the apPage[] and aiIdx[] arrays -** do not need to be zeroed and they are large, so we can save a lot -** of run-time by skipping the initialization of those elements. -*/ -SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){ - memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT)); -} - -/* -** Close a cursor. The read lock on the database file is released -** when the last cursor is closed. -*/ -SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ - Btree *pBtree = pCur->pBtree; - if( pBtree ){ - BtShared *pBt = pCur->pBt; - sqlite3BtreeEnter(pBtree); - assert( pBt->pCursor!=0 ); - if( pBt->pCursor==pCur ){ - pBt->pCursor = pCur->pNext; - }else{ - BtCursor *pPrev = pBt->pCursor; - do{ - if( pPrev->pNext==pCur ){ - pPrev->pNext = pCur->pNext; - break; - } - pPrev = pPrev->pNext; - }while( ALWAYS(pPrev) ); - } - btreeReleaseAllCursorPages(pCur); - unlockBtreeIfUnused(pBt); - sqlite3_free(pCur->aOverflow); - sqlite3_free(pCur->pKey); - sqlite3BtreeLeave(pBtree); - pCur->pBtree = 0; - } - return SQLITE_OK; -} - -/* -** Make sure the BtCursor* given in the argument has a valid -** BtCursor.info structure. If it is not already valid, call -** btreeParseCell() to fill it in. -** -** BtCursor.info is a cache of the information in the current cell. -** Using this cache reduces the number of calls to btreeParseCell(). -*/ -#ifndef NDEBUG - static int cellInfoEqual(CellInfo *a, CellInfo *b){ - if( a->nKey!=b->nKey ) return 0; - if( a->pPayload!=b->pPayload ) return 0; - if( a->nPayload!=b->nPayload ) return 0; - if( a->nLocal!=b->nLocal ) return 0; - if( a->nSize!=b->nSize ) return 0; - return 1; - } - static void assertCellInfo(BtCursor *pCur){ - CellInfo info; - memset(&info, 0, sizeof(info)); - btreeParseCell(pCur->pPage, pCur->ix, &info); - assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) ); - } -#else - #define assertCellInfo(x) -#endif -static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){ - if( pCur->info.nSize==0 ){ - pCur->curFlags |= BTCF_ValidNKey; - btreeParseCell(pCur->pPage,pCur->ix,&pCur->info); - }else{ - assertCellInfo(pCur); - } -} - -#ifndef NDEBUG /* The next routine used only within assert() statements */ -/* -** Return true if the given BtCursor is valid. A valid cursor is one -** that is currently pointing to a row in a (non-empty) table. -** This is a verification routine is used only within assert() statements. -*/ -SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){ - return pCur && pCur->eState==CURSOR_VALID; -} -#endif /* NDEBUG */ -SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){ - assert( pCur!=0 ); - return pCur->eState==CURSOR_VALID; -} - -/* -** Return the value of the integer key or "rowid" for a table btree. -** This routine is only valid for a cursor that is pointing into a -** ordinary table btree. If the cursor points to an index btree or -** is invalid, the result of this routine is undefined. -*/ -SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){ - assert( cursorHoldsMutex(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - assert( pCur->curIntKey ); - getCellInfo(pCur); - return pCur->info.nKey; -} - -/* -** Pin or unpin a cursor. -*/ -SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor *pCur){ - assert( (pCur->curFlags & BTCF_Pinned)==0 ); - pCur->curFlags |= BTCF_Pinned; -} -SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor *pCur){ - assert( (pCur->curFlags & BTCF_Pinned)!=0 ); - pCur->curFlags &= ~BTCF_Pinned; -} - -#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC -/* -** Return the offset into the database file for the start of the -** payload to which the cursor is pointing. -*/ -SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){ - assert( cursorHoldsMutex(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - getCellInfo(pCur); - return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) + - (i64)(pCur->info.pPayload - pCur->pPage->aData); -} -#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */ - -/* -** Return the number of bytes of payload for the entry that pCur is -** currently pointing to. For table btrees, this will be the amount -** of data. For index btrees, this will be the size of the key. -** -** The caller must guarantee that the cursor is pointing to a non-NULL -** valid entry. In other words, the calling procedure must guarantee -** that the cursor has Cursor.eState==CURSOR_VALID. -*/ -SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){ - assert( cursorHoldsMutex(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - getCellInfo(pCur); - return pCur->info.nPayload; -} - -/* -** Return an upper bound on the size of any record for the table -** that the cursor is pointing into. -** -** This is an optimization. Everything will still work if this -** routine always returns 2147483647 (which is the largest record -** that SQLite can handle) or more. But returning a smaller value might -** prevent large memory allocations when trying to interpret a -** corrupt datrabase. -** -** The current implementation merely returns the size of the underlying -** database file. -*/ -SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){ - assert( cursorHoldsMutex(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage; -} - -/* -** Given the page number of an overflow page in the database (parameter -** ovfl), this function finds the page number of the next page in the -** linked list of overflow pages. If possible, it uses the auto-vacuum -** pointer-map data instead of reading the content of page ovfl to do so. -** -** If an error occurs an SQLite error code is returned. Otherwise: -** -** The page number of the next overflow page in the linked list is -** written to *pPgnoNext. If page ovfl is the last page in its linked -** list, *pPgnoNext is set to zero. -** -** If ppPage is not NULL, and a reference to the MemPage object corresponding -** to page number pOvfl was obtained, then *ppPage is set to point to that -** reference. It is the responsibility of the caller to call releasePage() -** on *ppPage to free the reference. In no reference was obtained (because -** the pointer-map was used to obtain the value for *pPgnoNext), then -** *ppPage is set to zero. -*/ -static int getOverflowPage( - BtShared *pBt, /* The database file */ - Pgno ovfl, /* Current overflow page number */ - MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */ - Pgno *pPgnoNext /* OUT: Next overflow page number */ -){ - Pgno next = 0; - MemPage *pPage = 0; - int rc = SQLITE_OK; - - assert( sqlite3_mutex_held(pBt->mutex) ); - assert(pPgnoNext); - -#ifndef SQLITE_OMIT_AUTOVACUUM - /* Try to find the next page in the overflow list using the - ** autovacuum pointer-map pages. Guess that the next page in - ** the overflow list is page number (ovfl+1). If that guess turns - ** out to be wrong, fall back to loading the data of page - ** number ovfl to determine the next page number. - */ - if( pBt->autoVacuum ){ - Pgno pgno; - Pgno iGuess = ovfl+1; - u8 eType; - - while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ - iGuess++; - } - - if( iGuess<=btreePagecount(pBt) ){ - rc = ptrmapGet(pBt, iGuess, &eType, &pgno); - if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ - next = iGuess; - rc = SQLITE_DONE; - } - } - } -#endif - - assert( next==0 || rc==SQLITE_DONE ); - if( rc==SQLITE_OK ){ - rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); - assert( rc==SQLITE_OK || pPage==0 ); - if( rc==SQLITE_OK ){ - next = get4byte(pPage->aData); - } - } - - *pPgnoNext = next; - if( ppPage ){ - *ppPage = pPage; - }else{ - releasePage(pPage); - } - return (rc==SQLITE_DONE ? SQLITE_OK : rc); -} - -/* -** Copy data from a buffer to a page, or from a page to a buffer. -** -** pPayload is a pointer to data stored on database page pDbPage. -** If argument eOp is false, then nByte bytes of data are copied -** from pPayload to the buffer pointed at by pBuf. If eOp is true, -** then sqlite3PagerWrite() is called on pDbPage and nByte bytes -** of data are copied from the buffer pBuf to pPayload. -** -** SQLITE_OK is returned on success, otherwise an error code. -*/ -static int copyPayload( - void *pPayload, /* Pointer to page data */ - void *pBuf, /* Pointer to buffer */ - int nByte, /* Number of bytes to copy */ - int eOp, /* 0 -> copy from page, 1 -> copy to page */ - DbPage *pDbPage /* Page containing pPayload */ -){ - if( eOp ){ - /* Copy data from buffer to page (a write operation) */ - int rc = sqlite3PagerWrite(pDbPage); - if( rc!=SQLITE_OK ){ - return rc; - } - memcpy(pPayload, pBuf, nByte); - }else{ - /* Copy data from page to buffer (a read operation) */ - memcpy(pBuf, pPayload, nByte); - } - return SQLITE_OK; -} - -/* -** This function is used to read or overwrite payload information -** for the entry that the pCur cursor is pointing to. The eOp -** argument is interpreted as follows: -** -** 0: The operation is a read. Populate the overflow cache. -** 1: The operation is a write. Populate the overflow cache. -** -** A total of "amt" bytes are read or written beginning at "offset". -** Data is read to or from the buffer pBuf. -** -** The content being read or written might appear on the main page -** or be scattered out on multiple overflow pages. -** -** If the current cursor entry uses one or more overflow pages -** this function may allocate space for and lazily populate -** the overflow page-list cache array (BtCursor.aOverflow). -** Subsequent calls use this cache to make seeking to the supplied offset -** more efficient. -** -** Once an overflow page-list cache has been allocated, it must be -** invalidated if some other cursor writes to the same table, or if -** the cursor is moved to a different row. Additionally, in auto-vacuum -** mode, the following events may invalidate an overflow page-list cache. -** -** * An incremental vacuum, -** * A commit in auto_vacuum="full" mode, -** * Creating a table (may require moving an overflow page). -*/ -static int accessPayload( - BtCursor *pCur, /* Cursor pointing to entry to read from */ - u32 offset, /* Begin reading this far into payload */ - u32 amt, /* Read this many bytes */ - unsigned char *pBuf, /* Write the bytes into this buffer */ - int eOp /* zero to read. non-zero to write. */ -){ - unsigned char *aPayload; - int rc = SQLITE_OK; - int iIdx = 0; - MemPage *pPage = pCur->pPage; /* Btree page of current entry */ - BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ -#ifdef SQLITE_DIRECT_OVERFLOW_READ - unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ -#endif - - assert( pPage ); - assert( eOp==0 || eOp==1 ); - assert( pCur->eState==CURSOR_VALID ); - assert( pCur->ixnCell ); - assert( cursorHoldsMutex(pCur) ); - - getCellInfo(pCur); - aPayload = pCur->info.pPayload; - assert( offset+amt <= pCur->info.nPayload ); - - assert( aPayload > pPage->aData ); - if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ - /* Trying to read or write past the end of the data is an error. The - ** conditional above is really: - ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] - ** but is recast into its current form to avoid integer overflow problems - */ - return SQLITE_CORRUPT_PAGE(pPage); - } - - /* Check if data must be read/written to/from the btree page itself. */ - if( offsetinfo.nLocal ){ - int a = amt; - if( a+offset>pCur->info.nLocal ){ - a = pCur->info.nLocal - offset; - } - rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); - offset = 0; - pBuf += a; - amt -= a; - }else{ - offset -= pCur->info.nLocal; - } - - - if( rc==SQLITE_OK && amt>0 ){ - const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ - Pgno nextPage; - - nextPage = get4byte(&aPayload[pCur->info.nLocal]); - - /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. - ** - ** The aOverflow[] array is sized at one entry for each overflow page - ** in the overflow chain. The page number of the first overflow page is - ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array - ** means "not yet known" (the cache is lazily populated). - */ - if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ - int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; - if( pCur->aOverflow==0 - || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) - ){ - Pgno *aNew = (Pgno*)sqlite3Realloc( - pCur->aOverflow, nOvfl*2*sizeof(Pgno) - ); - if( aNew==0 ){ - return SQLITE_NOMEM_BKPT; - }else{ - pCur->aOverflow = aNew; - } - } - memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); - pCur->curFlags |= BTCF_ValidOvfl; - }else{ - /* If the overflow page-list cache has been allocated and the - ** entry for the first required overflow page is valid, skip - ** directly to it. - */ - if( pCur->aOverflow[offset/ovflSize] ){ - iIdx = (offset/ovflSize); - nextPage = pCur->aOverflow[iIdx]; - offset = (offset%ovflSize); - } - } - - assert( rc==SQLITE_OK && amt>0 ); - while( nextPage ){ - /* If required, populate the overflow page-list cache. */ - if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT; - assert( pCur->aOverflow[iIdx]==0 - || pCur->aOverflow[iIdx]==nextPage - || CORRUPT_DB ); - pCur->aOverflow[iIdx] = nextPage; - - if( offset>=ovflSize ){ - /* The only reason to read this page is to obtain the page - ** number for the next page in the overflow chain. The page - ** data is not required. So first try to lookup the overflow - ** page-list cache, if any, then fall back to the getOverflowPage() - ** function. - */ - assert( pCur->curFlags & BTCF_ValidOvfl ); - assert( pCur->pBtree->db==pBt->db ); - if( pCur->aOverflow[iIdx+1] ){ - nextPage = pCur->aOverflow[iIdx+1]; - }else{ - rc = getOverflowPage(pBt, nextPage, 0, &nextPage); - } - offset -= ovflSize; - }else{ - /* Need to read this page properly. It contains some of the - ** range of data that is being read (eOp==0) or written (eOp!=0). - */ - int a = amt; - if( a + offset > ovflSize ){ - a = ovflSize - offset; - } - -#ifdef SQLITE_DIRECT_OVERFLOW_READ - /* If all the following are true: - ** - ** 1) this is a read operation, and - ** 2) data is required from the start of this overflow page, and - ** 3) there are no dirty pages in the page-cache - ** 4) the database is file-backed, and - ** 5) the page is not in the WAL file - ** 6) at least 4 bytes have already been read into the output buffer - ** - ** then data can be read directly from the database file into the - ** output buffer, bypassing the page-cache altogether. This speeds - ** up loading large records that span many overflow pages. - */ - if( eOp==0 /* (1) */ - && offset==0 /* (2) */ - && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */ - && &pBuf[-4]>=pBufStart /* (6) */ - ){ - sqlite3_file *fd = sqlite3PagerFile(pBt->pPager); - u8 aSave[4]; - u8 *aWrite = &pBuf[-4]; - assert( aWrite>=pBufStart ); /* due to (6) */ - memcpy(aSave, aWrite, 4); - rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); - if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT; - nextPage = get4byte(aWrite); - memcpy(aWrite, aSave, 4); - }else -#endif - - { - DbPage *pDbPage; - rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, - (eOp==0 ? PAGER_GET_READONLY : 0) - ); - if( rc==SQLITE_OK ){ - aPayload = sqlite3PagerGetData(pDbPage); - nextPage = get4byte(aPayload); - rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); - sqlite3PagerUnref(pDbPage); - offset = 0; - } - } - amt -= a; - if( amt==0 ) return rc; - pBuf += a; - } - if( rc ) break; - iIdx++; - } - } - - if( rc==SQLITE_OK && amt>0 ){ - /* Overflow chain ends prematurely */ - return SQLITE_CORRUPT_PAGE(pPage); - } - return rc; -} - -/* -** Read part of the payload for the row at which that cursor pCur is currently -** pointing. "amt" bytes will be transferred into pBuf[]. The transfer -** begins at "offset". -** -** pCur can be pointing to either a table or an index b-tree. -** If pointing to a table btree, then the content section is read. If -** pCur is pointing to an index b-tree then the key section is read. -** -** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing -** to a valid row in the table. For sqlite3BtreePayloadChecked(), the -** cursor might be invalid or might need to be restored before being read. -** -** Return SQLITE_OK on success or an error code if anything goes -** wrong. An error is returned if "offset+amt" is larger than -** the available payload. -*/ -SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ - assert( cursorHoldsMutex(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - assert( pCur->iPage>=0 && pCur->pPage ); - assert( pCur->ixpPage->nCell ); - return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0); -} - -/* -** This variant of sqlite3BtreePayload() works even if the cursor has not -** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read() -** interface. -*/ -#ifndef SQLITE_OMIT_INCRBLOB -static SQLITE_NOINLINE int accessPayloadChecked( - BtCursor *pCur, - u32 offset, - u32 amt, - void *pBuf -){ - int rc; - if ( pCur->eState==CURSOR_INVALID ){ - return SQLITE_ABORT; - } - assert( cursorOwnsBtShared(pCur) ); - rc = btreeRestoreCursorPosition(pCur); - return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0); -} -SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ - if( pCur->eState==CURSOR_VALID ){ - assert( cursorOwnsBtShared(pCur) ); - return accessPayload(pCur, offset, amt, pBuf, 0); - }else{ - return accessPayloadChecked(pCur, offset, amt, pBuf); - } -} -#endif /* SQLITE_OMIT_INCRBLOB */ - -/* -** Return a pointer to payload information from the entry that the -** pCur cursor is pointing to. The pointer is to the beginning of -** the key if index btrees (pPage->intKey==0) and is the data for -** table btrees (pPage->intKey==1). The number of bytes of available -** key/data is written into *pAmt. If *pAmt==0, then the value -** returned will not be a valid pointer. -** -** This routine is an optimization. It is common for the entire key -** and data to fit on the local page and for there to be no overflow -** pages. When that is so, this routine can be used to access the -** key and data without making a copy. If the key and/or data spills -** onto overflow pages, then accessPayload() must be used to reassemble -** the key/data and copy it into a preallocated buffer. -** -** The pointer returned by this routine looks directly into the cached -** page of the database. The data might change or move the next time -** any btree routine is called. -*/ -static const void *fetchPayload( - BtCursor *pCur, /* Cursor pointing to entry to read from */ - u32 *pAmt /* Write the number of available bytes here */ -){ - int amt; - assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage); - assert( pCur->eState==CURSOR_VALID ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); - assert( cursorOwnsBtShared(pCur) ); - assert( pCur->ixpPage->nCell ); - assert( pCur->info.nSize>0 ); - assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB ); - assert( pCur->info.pPayloadpPage->aDataEnd ||CORRUPT_DB); - amt = pCur->info.nLocal; - if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){ - /* There is too little space on the page for the expected amount - ** of local content. Database must be corrupt. */ - assert( CORRUPT_DB ); - amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload)); - } - *pAmt = (u32)amt; - return (void*)pCur->info.pPayload; -} - - -/* -** For the entry that cursor pCur is point to, return as -** many bytes of the key or data as are available on the local -** b-tree page. Write the number of available bytes into *pAmt. -** -** The pointer returned is ephemeral. The key/data may move -** or be destroyed on the next call to any Btree routine, -** including calls from other threads against the same cache. -** Hence, a mutex on the BtShared should be held prior to calling -** this routine. -** -** These routines is used to get quick access to key and data -** in the common case where no overflow pages are used. -*/ -SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){ - return fetchPayload(pCur, pAmt); -} - - -/* -** Move the cursor down to a new child page. The newPgno argument is the -** page number of the child page to move to. -** -** This function returns SQLITE_CORRUPT if the page-header flags field of -** the new child page does not match the flags field of the parent (i.e. -** if an intkey page appears to be the parent of a non-intkey page, or -** vice-versa). -*/ -static int moveToChild(BtCursor *pCur, u32 newPgno){ - BtShared *pBt = pCur->pBt; - - assert( cursorOwnsBtShared(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - assert( pCur->iPageiPage>=0 ); - if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ - return SQLITE_CORRUPT_BKPT; - } - pCur->info.nSize = 0; - pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); - pCur->aiIdx[pCur->iPage] = pCur->ix; - pCur->apPage[pCur->iPage] = pCur->pPage; - pCur->ix = 0; - pCur->iPage++; - return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags); -} - -#ifdef SQLITE_DEBUG -/* -** Page pParent is an internal (non-leaf) tree page. This function -** asserts that page number iChild is the left-child if the iIdx'th -** cell in page pParent. Or, if iIdx is equal to the total number of -** cells in pParent, that page number iChild is the right-child of -** the page. -*/ -static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ - if( CORRUPT_DB ) return; /* The conditions tested below might not be true - ** in a corrupt database */ - assert( iIdx<=pParent->nCell ); - if( iIdx==pParent->nCell ){ - assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild ); - }else{ - assert( get4byte(findCell(pParent, iIdx))==iChild ); - } -} -#else -# define assertParentIndex(x,y,z) -#endif - -/* -** Move the cursor up to the parent page. -** -** pCur->idx is set to the cell index that contains the pointer -** to the page we are coming from. If we are coming from the -** right-most child page then pCur->idx is set to one more than -** the largest cell index. -*/ -static void moveToParent(BtCursor *pCur){ - MemPage *pLeaf; - assert( cursorOwnsBtShared(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - assert( pCur->iPage>0 ); - assert( pCur->pPage ); - assertParentIndex( - pCur->apPage[pCur->iPage-1], - pCur->aiIdx[pCur->iPage-1], - pCur->pPage->pgno - ); - testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); - pCur->info.nSize = 0; - pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); - pCur->ix = pCur->aiIdx[pCur->iPage-1]; - pLeaf = pCur->pPage; - pCur->pPage = pCur->apPage[--pCur->iPage]; - releasePageNotNull(pLeaf); -} - -/* -** Move the cursor to point to the root page of its b-tree structure. -** -** If the table has a virtual root page, then the cursor is moved to point -** to the virtual root page instead of the actual root page. A table has a -** virtual root page when the actual root page contains no cells and a -** single child page. This can only happen with the table rooted at page 1. -** -** If the b-tree structure is empty, the cursor state is set to -** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise, -** the cursor is set to point to the first cell located on the root -** (or virtual root) page and the cursor state is set to CURSOR_VALID. -** -** If this function returns successfully, it may be assumed that the -** page-header flags indicate that the [virtual] root-page is the expected -** kind of b-tree page (i.e. if when opening the cursor the caller did not -** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, -** indicating a table b-tree, or if the caller did specify a KeyInfo -** structure the flags byte is set to 0x02 or 0x0A, indicating an index -** b-tree). -*/ -static int moveToRoot(BtCursor *pCur){ - MemPage *pRoot; - int rc = SQLITE_OK; - - assert( cursorOwnsBtShared(pCur) ); - assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); - assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); - assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); - assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 ); - assert( pCur->pgnoRoot>0 || pCur->iPage<0 ); - - if( pCur->iPage>=0 ){ - if( pCur->iPage ){ - releasePageNotNull(pCur->pPage); - while( --pCur->iPage ){ - releasePageNotNull(pCur->apPage[pCur->iPage]); - } - pCur->pPage = pCur->apPage[0]; - goto skip_init; - } - }else if( pCur->pgnoRoot==0 ){ - pCur->eState = CURSOR_INVALID; - return SQLITE_EMPTY; - }else{ - assert( pCur->iPage==(-1) ); - if( pCur->eState>=CURSOR_REQUIRESEEK ){ - if( pCur->eState==CURSOR_FAULT ){ - assert( pCur->skipNext!=SQLITE_OK ); - return pCur->skipNext; - } - sqlite3BtreeClearCursor(pCur); - } - rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage, - 0, pCur->curPagerFlags); - if( rc!=SQLITE_OK ){ - pCur->eState = CURSOR_INVALID; - return rc; - } - pCur->iPage = 0; - pCur->curIntKey = pCur->pPage->intKey; - } - pRoot = pCur->pPage; - assert( pRoot->pgno==pCur->pgnoRoot ); - - /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor - ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is - ** NULL, the caller expects a table b-tree. If this is not the case, - ** return an SQLITE_CORRUPT error. - ** - ** Earlier versions of SQLite assumed that this test could not fail - ** if the root page was already loaded when this function was called (i.e. - ** if pCur->iPage>=0). But this is not so if the database is corrupted - ** in such a way that page pRoot is linked into a second b-tree table - ** (or the freelist). */ - assert( pRoot->intKey==1 || pRoot->intKey==0 ); - if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ - return SQLITE_CORRUPT_PAGE(pCur->pPage); - } - -skip_init: - pCur->ix = 0; - pCur->info.nSize = 0; - pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); - - pRoot = pCur->pPage; - if( pRoot->nCell>0 ){ - pCur->eState = CURSOR_VALID; - }else if( !pRoot->leaf ){ - Pgno subpage; - if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; - subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); - pCur->eState = CURSOR_VALID; - rc = moveToChild(pCur, subpage); - }else{ - pCur->eState = CURSOR_INVALID; - rc = SQLITE_EMPTY; - } - return rc; -} - -/* -** Move the cursor down to the left-most leaf entry beneath the -** entry to which it is currently pointing. -** -** The left-most leaf is the one with the smallest key - the first -** in ascending order. -*/ -static int moveToLeftmost(BtCursor *pCur){ - Pgno pgno; - int rc = SQLITE_OK; - MemPage *pPage; - - assert( cursorOwnsBtShared(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){ - assert( pCur->ixnCell ); - pgno = get4byte(findCell(pPage, pCur->ix)); - rc = moveToChild(pCur, pgno); - } - return rc; -} - -/* -** Move the cursor down to the right-most leaf entry beneath the -** page to which it is currently pointing. Notice the difference -** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() -** finds the left-most entry beneath the *entry* whereas moveToRightmost() -** finds the right-most entry beneath the *page*. -** -** The right-most entry is the one with the largest key - the last -** key in ascending order. -*/ -static int moveToRightmost(BtCursor *pCur){ - Pgno pgno; - int rc = SQLITE_OK; - MemPage *pPage = 0; - - assert( cursorOwnsBtShared(pCur) ); - assert( pCur->eState==CURSOR_VALID ); - while( !(pPage = pCur->pPage)->leaf ){ - pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); - pCur->ix = pPage->nCell; - rc = moveToChild(pCur, pgno); - if( rc ) return rc; - } - pCur->ix = pPage->nCell-1; - assert( pCur->info.nSize==0 ); - assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); - return SQLITE_OK; -} - -/* Move the cursor to the first entry in the table. Return SQLITE_OK -** on success. Set *pRes to 0 if the cursor actually points to something -** or set *pRes to 1 if the table is empty. -*/ -SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ - int rc; - - assert( cursorOwnsBtShared(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); - rc = moveToRoot(pCur); - if( rc==SQLITE_OK ){ - assert( pCur->pPage->nCell>0 ); - *pRes = 0; - rc = moveToLeftmost(pCur); - }else if( rc==SQLITE_EMPTY ){ - assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); - *pRes = 1; - rc = SQLITE_OK; - } - return rc; -} - -/* Move the cursor to the last entry in the table. Return SQLITE_OK -** on success. Set *pRes to 0 if the cursor actually points to something -** or set *pRes to 1 if the table is empty. -*/ -SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ - int rc; - - assert( cursorOwnsBtShared(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); - - /* If the cursor already points to the last entry, this is a no-op. */ - if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ -#ifdef SQLITE_DEBUG - /* This block serves to assert() that the cursor really does point - ** to the last entry in the b-tree. */ - int ii; - for(ii=0; iiiPage; ii++){ - assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); - } - assert( pCur->ix==pCur->pPage->nCell-1 ); - assert( pCur->pPage->leaf ); -#endif - *pRes = 0; - return SQLITE_OK; - } - - rc = moveToRoot(pCur); - if( rc==SQLITE_OK ){ - assert( pCur->eState==CURSOR_VALID ); - *pRes = 0; - rc = moveToRightmost(pCur); - if( rc==SQLITE_OK ){ - pCur->curFlags |= BTCF_AtLast; - }else{ - pCur->curFlags &= ~BTCF_AtLast; - } - }else if( rc==SQLITE_EMPTY ){ - assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); - *pRes = 1; - rc = SQLITE_OK; - } - return rc; -} - -/* Move the cursor so that it points to an entry near the key -** specified by pIdxKey or intKey. Return a success code. -** -** For INTKEY tables, the intKey parameter is used. pIdxKey -** must be NULL. For index tables, pIdxKey is used and intKey -** is ignored. -** -** If an exact match is not found, then the cursor is always -** left pointing at a leaf page which would hold the entry if it -** were present. The cursor might point to an entry that comes -** before or after the key. -** -** An integer is written into *pRes which is the result of -** comparing the key with the entry to which the cursor is -** pointing. The meaning of the integer written into -** *pRes is as follows: -** -** *pRes<0 The cursor is left pointing at an entry that -** is smaller than intKey/pIdxKey or if the table is empty -** and the cursor is therefore left point to nothing. -** -** *pRes==0 The cursor is left pointing at an entry that -** exactly matches intKey/pIdxKey. -** -** *pRes>0 The cursor is left pointing at an entry that -** is larger than intKey/pIdxKey. -** -** For index tables, the pIdxKey->eqSeen field is set to 1 if there -** exists an entry in the table that exactly matches pIdxKey. -*/ -SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( - BtCursor *pCur, /* The cursor to be moved */ - UnpackedRecord *pIdxKey, /* Unpacked index key */ - i64 intKey, /* The table key */ - int biasRight, /* If true, bias the search to the high end */ - int *pRes /* Write search results here */ -){ - int rc; - RecordCompare xRecordCompare; - - assert( cursorOwnsBtShared(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); - assert( pRes ); - assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); - assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) ); - - /* If the cursor is already positioned at the point we are trying - ** to move to, then just return without doing any work */ - if( pIdxKey==0 - && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 - ){ - if( pCur->info.nKey==intKey ){ - *pRes = 0; - return SQLITE_OK; - } - if( pCur->info.nKeycurFlags & BTCF_AtLast)!=0 ){ - *pRes = -1; - return SQLITE_OK; - } - /* If the requested key is one more than the previous key, then - ** try to get there using sqlite3BtreeNext() rather than a full - ** binary search. This is an optimization only. The correct answer - ** is still obtained without this case, only a little more slowely */ - if( pCur->info.nKey+1==intKey ){ - *pRes = 0; - rc = sqlite3BtreeNext(pCur, 0); - if( rc==SQLITE_OK ){ - getCellInfo(pCur); - if( pCur->info.nKey==intKey ){ - return SQLITE_OK; - } - }else if( rc==SQLITE_DONE ){ - rc = SQLITE_OK; - }else{ - return rc; - } - } - } - } - - if( pIdxKey ){ - xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); - pIdxKey->errCode = 0; - assert( pIdxKey->default_rc==1 - || pIdxKey->default_rc==0 - || pIdxKey->default_rc==-1 - ); - }else{ - xRecordCompare = 0; /* All keys are integers */ - } - - rc = moveToRoot(pCur); - if( rc ){ - if( rc==SQLITE_EMPTY ){ - assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 ); - *pRes = -1; - return SQLITE_OK; - } - return rc; - } - assert( pCur->pPage ); - assert( pCur->pPage->isInit ); - assert( pCur->eState==CURSOR_VALID ); - assert( pCur->pPage->nCell > 0 ); - assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey ); - assert( pCur->curIntKey || pIdxKey ); - for(;;){ - int lwr, upr, idx, c; - Pgno chldPg; - MemPage *pPage = pCur->pPage; - u8 *pCell; /* Pointer to current cell in pPage */ - - /* pPage->nCell must be greater than zero. If this is the root-page - ** the cursor would have been INVALID above and this for(;;) loop - ** not run. If this is not the root-page, then the moveToChild() routine - ** would have already detected db corruption. Similarly, pPage must - ** be the right kind (index or table) of b-tree page. Otherwise - ** a moveToChild() or moveToRoot() call would have detected corruption. */ - assert( pPage->nCell>0 ); - assert( pPage->intKey==(pIdxKey==0) ); - lwr = 0; - upr = pPage->nCell-1; - assert( biasRight==0 || biasRight==1 ); - idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ - pCur->ix = (u16)idx; - if( xRecordCompare==0 ){ - for(;;){ - i64 nCellKey; - pCell = findCellPastPtr(pPage, idx); - if( pPage->intKeyLeaf ){ - while( 0x80 <= *(pCell++) ){ - if( pCell>=pPage->aDataEnd ){ - return SQLITE_CORRUPT_PAGE(pPage); - } - } - } - getVarint(pCell, (u64*)&nCellKey); - if( nCellKeyupr ){ c = -1; break; } - }else if( nCellKey>intKey ){ - upr = idx-1; - if( lwr>upr ){ c = +1; break; } - }else{ - assert( nCellKey==intKey ); - pCur->ix = (u16)idx; - if( !pPage->leaf ){ - lwr = idx; - goto moveto_next_layer; - }else{ - pCur->curFlags |= BTCF_ValidNKey; - pCur->info.nKey = nCellKey; - pCur->info.nSize = 0; - *pRes = 0; - return SQLITE_OK; - } - } - assert( lwr+upr>=0 ); - idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ - } - }else{ - for(;;){ - int nCell; /* Size of the pCell cell in bytes */ - pCell = findCellPastPtr(pPage, idx); - - /* The maximum supported page-size is 65536 bytes. This means that - ** the maximum number of record bytes stored on an index B-Tree - ** page is less than 16384 bytes and may be stored as a 2-byte - ** varint. This information is used to attempt to avoid parsing - ** the entire cell by checking for the cases where the record is - ** stored entirely within the b-tree page by inspecting the first - ** 2 bytes of the cell. - */ - nCell = pCell[0]; - if( nCell<=pPage->max1bytePayload ){ - /* This branch runs if the record-size field of the cell is a - ** single byte varint and the record fits entirely on the main - ** b-tree page. */ - testcase( pCell+nCell+1==pPage->aDataEnd ); - c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); - }else if( !(pCell[1] & 0x80) - && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal - ){ - /* The record-size field is a 2 byte varint and the record - ** fits entirely on the main b-tree page. */ - testcase( pCell+nCell+2==pPage->aDataEnd ); - c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); - }else{ - /* The record flows over onto one or more overflow pages. In - ** this case the whole cell needs to be parsed, a buffer allocated - ** and accessPayload() used to retrieve the record into the - ** buffer before VdbeRecordCompare() can be called. - ** - ** If the record is corrupt, the xRecordCompare routine may read - ** up to two varints past the end of the buffer. An extra 18 - ** bytes of padding is allocated at the end of the buffer in - ** case this happens. */ - void *pCellKey; - u8 * const pCellBody = pCell - pPage->childPtrSize; - const int nOverrun = 18; /* Size of the overrun padding */ - pPage->xParseCell(pPage, pCellBody, &pCur->info); - nCell = (int)pCur->info.nKey; - testcase( nCell<0 ); /* True if key size is 2^32 or more */ - testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */ - testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */ - testcase( nCell==2 ); /* Minimum legal index key size */ - if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){ - rc = SQLITE_CORRUPT_PAGE(pPage); - goto moveto_finish; - } - pCellKey = sqlite3Malloc( nCell+nOverrun ); - if( pCellKey==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto moveto_finish; - } - pCur->ix = (u16)idx; - rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); - memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */ - pCur->curFlags &= ~BTCF_ValidOvfl; - if( rc ){ - sqlite3_free(pCellKey); - goto moveto_finish; - } - c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); - sqlite3_free(pCellKey); - } - assert( - (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) - && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed) - ); - if( c<0 ){ - lwr = idx+1; - }else if( c>0 ){ - upr = idx-1; - }else{ - assert( c==0 ); - *pRes = 0; - rc = SQLITE_OK; - pCur->ix = (u16)idx; - if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT; - goto moveto_finish; - } - if( lwr>upr ) break; - assert( lwr+upr>=0 ); - idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ - } - } - assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); - assert( pPage->isInit ); - if( pPage->leaf ){ - assert( pCur->ixpPage->nCell ); - pCur->ix = (u16)idx; - *pRes = c; - rc = SQLITE_OK; - goto moveto_finish; - } -moveto_next_layer: - if( lwr>=pPage->nCell ){ - chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); - }else{ - chldPg = get4byte(findCell(pPage, lwr)); - } - pCur->ix = (u16)lwr; - rc = moveToChild(pCur, chldPg); - if( rc ) break; - } -moveto_finish: - pCur->info.nSize = 0; - assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); - return rc; -} - - -/* -** Return TRUE if the cursor is not pointing at an entry of the table. -** -** TRUE will be returned after a call to sqlite3BtreeNext() moves -** past the last entry in the table or sqlite3BtreePrev() moves past -** the first entry. TRUE is also returned if the table is empty. -*/ -SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){ - /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries - ** have been deleted? This API will need to change to return an error code - ** as well as the boolean result value. - */ - return (CURSOR_VALID!=pCur->eState); -} - -/* -** Return an estimate for the number of rows in the table that pCur is -** pointing to. Return a negative number if no estimate is currently -** available. -*/ -SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){ - i64 n; - u8 i; - - assert( cursorOwnsBtShared(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); - - /* Currently this interface is only called by the OP_IfSmaller - ** opcode, and it that case the cursor will always be valid and - ** will always point to a leaf node. */ - if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1; - if( NEVER(pCur->pPage->leaf==0) ) return -1; - - n = pCur->pPage->nCell; - for(i=0; iiPage; i++){ - n *= pCur->apPage[i]->nCell; - } - return n; -} - -/* -** Advance the cursor to the next entry in the database. -** Return value: -** -** SQLITE_OK success -** SQLITE_DONE cursor is already pointing at the last element -** otherwise some kind of error occurred -** -** The main entry point is sqlite3BtreeNext(). That routine is optimized -** for the common case of merely incrementing the cell counter BtCursor.aiIdx -** to the next cell on the current page. The (slower) btreeNext() helper -** routine is called when it is necessary to move to a different page or -** to restore the cursor. -** -** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the -** cursor corresponds to an SQL index and this routine could have been -** skipped if the SQL index had been a unique index. The F argument -** is a hint to the implement. SQLite btree implementation does not use -** this hint, but COMDB2 does. -*/ -static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){ - int rc; - int idx; - MemPage *pPage; - - assert( cursorOwnsBtShared(pCur) ); - if( pCur->eState!=CURSOR_VALID ){ - assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); - rc = restoreCursorPosition(pCur); - if( rc!=SQLITE_OK ){ - return rc; - } - if( CURSOR_INVALID==pCur->eState ){ - return SQLITE_DONE; - } - if( pCur->eState==CURSOR_SKIPNEXT ){ - pCur->eState = CURSOR_VALID; - if( pCur->skipNext>0 ) return SQLITE_OK; - } - } - - pPage = pCur->pPage; - idx = ++pCur->ix; - if( !pPage->isInit ){ - /* The only known way for this to happen is for there to be a - ** recursive SQL function that does a DELETE operation as part of a - ** SELECT which deletes content out from under an active cursor - ** in a corrupt database file where the table being DELETE-ed from - ** has pages in common with the table being queried. See TH3 - ** module cov1/btree78.test testcase 220 (2018-06-08) for an - ** example. */ - return SQLITE_CORRUPT_BKPT; - } - - /* If the database file is corrupt, it is possible for the value of idx - ** to be invalid here. This can only occur if a second cursor modifies - ** the page while cursor pCur is holding a reference to it. Which can - ** only happen if the database is corrupt in such a way as to link the - ** page into more than one b-tree structure. - ** - ** Update 2019-12-23: appears to long longer be possible after the - ** addition of anotherValidCursor() condition on balance_deeper(). */ - harmless( idx>pPage->nCell ); - - if( idx>=pPage->nCell ){ - if( !pPage->leaf ){ - rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); - if( rc ) return rc; - return moveToLeftmost(pCur); - } - do{ - if( pCur->iPage==0 ){ - pCur->eState = CURSOR_INVALID; - return SQLITE_DONE; - } - moveToParent(pCur); - pPage = pCur->pPage; - }while( pCur->ix>=pPage->nCell ); - if( pPage->intKey ){ - return sqlite3BtreeNext(pCur, 0); - }else{ - return SQLITE_OK; - } - } - if( pPage->leaf ){ - return SQLITE_OK; - }else{ - return moveToLeftmost(pCur); - } -} -SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){ - MemPage *pPage; - UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ - assert( cursorOwnsBtShared(pCur) ); - assert( flags==0 || flags==1 ); - pCur->info.nSize = 0; - pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); - if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur); - pPage = pCur->pPage; - if( (++pCur->ix)>=pPage->nCell ){ - pCur->ix--; - return btreeNext(pCur); - } - if( pPage->leaf ){ - return SQLITE_OK; - }else{ - return moveToLeftmost(pCur); - } -} - -/* -** Step the cursor to the back to the previous entry in the database. -** Return values: -** -** SQLITE_OK success -** SQLITE_DONE the cursor is already on the first element of the table -** otherwise some kind of error occurred -** -** The main entry point is sqlite3BtreePrevious(). That routine is optimized -** for the common case of merely decrementing the cell counter BtCursor.aiIdx -** to the previous cell on the current page. The (slower) btreePrevious() -** helper routine is called when it is necessary to move to a different page -** or to restore the cursor. -** -** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then -** the cursor corresponds to an SQL index and this routine could have been -** skipped if the SQL index had been a unique index. The F argument is a -** hint to the implement. The native SQLite btree implementation does not -** use this hint, but COMDB2 does. -*/ -static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){ - int rc; - MemPage *pPage; - - assert( cursorOwnsBtShared(pCur) ); - assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); - assert( pCur->info.nSize==0 ); - if( pCur->eState!=CURSOR_VALID ){ - rc = restoreCursorPosition(pCur); - if( rc!=SQLITE_OK ){ - return rc; - } - if( CURSOR_INVALID==pCur->eState ){ - return SQLITE_DONE; - } - if( CURSOR_SKIPNEXT==pCur->eState ){ - pCur->eState = CURSOR_VALID; - if( pCur->skipNext<0 ) return SQLITE_OK; - } - } - - pPage = pCur->pPage; - assert( pPage->isInit ); - if( !pPage->leaf ){ - int idx = pCur->ix; - rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); - if( rc ) return rc; - rc = moveToRightmost(pCur); - }else{ - while( pCur->ix==0 ){ - if( pCur->iPage==0 ){ - pCur->eState = CURSOR_INVALID; - return SQLITE_DONE; - } - moveToParent(pCur); - } - assert( pCur->info.nSize==0 ); - assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 ); - - pCur->ix--; - pPage = pCur->pPage; - if( pPage->intKey && !pPage->leaf ){ - rc = sqlite3BtreePrevious(pCur, 0); - }else{ - rc = SQLITE_OK; - } - } - return rc; -} -SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){ - assert( cursorOwnsBtShared(pCur) ); - assert( flags==0 || flags==1 ); - UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */ - pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); - pCur->info.nSize = 0; - if( pCur->eState!=CURSOR_VALID - || pCur->ix==0 - || pCur->pPage->leaf==0 - ){ - return btreePrevious(pCur); - } - pCur->ix--; - return SQLITE_OK; -} - -/* -** Allocate a new page from the database file. -** -** The new page is marked as dirty. (In other words, sqlite3PagerWrite() -** has already been called on the new page.) The new page has also -** been referenced and the calling routine is responsible for calling -** sqlite3PagerUnref() on the new page when it is done. -** -** SQLITE_OK is returned on success. Any other return value indicates -** an error. *ppPage is set to NULL in the event of an error. -** -** If the "nearby" parameter is not 0, then an effort is made to -** locate a page close to the page number "nearby". This can be used in an -** attempt to keep related pages close to each other in the database file, -** which in turn can make database access faster. -** -** If the eMode parameter is BTALLOC_EXACT and the nearby page exists -** anywhere on the free-list, then it is guaranteed to be returned. If -** eMode is BTALLOC_LT then the page returned will be less than or equal -** to nearby if any such page exists. If eMode is BTALLOC_ANY then there -** are no restrictions on which page is returned. -*/ -static int allocateBtreePage( - BtShared *pBt, /* The btree */ - MemPage **ppPage, /* Store pointer to the allocated page here */ - Pgno *pPgno, /* Store the page number here */ - Pgno nearby, /* Search for a page near this one */ - u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ -){ - MemPage *pPage1; - int rc; - u32 n; /* Number of pages on the freelist */ - u32 k; /* Number of leaves on the trunk of the freelist */ - MemPage *pTrunk = 0; - MemPage *pPrevTrunk = 0; - Pgno mxPage; /* Total size of the database file */ - - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); - pPage1 = pBt->pPage1; - mxPage = btreePagecount(pBt); - /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36 - ** stores stores the total number of pages on the freelist. */ - n = get4byte(&pPage1->aData[36]); - testcase( n==mxPage-1 ); - if( n>=mxPage ){ - return SQLITE_CORRUPT_BKPT; - } - if( n>0 ){ - /* There are pages on the freelist. Reuse one of those pages. */ - Pgno iTrunk; - u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ - u32 nSearch = 0; /* Count of the number of search attempts */ - - /* If eMode==BTALLOC_EXACT and a query of the pointer-map - ** shows that the page 'nearby' is somewhere on the free-list, then - ** the entire-list will be searched for that page. - */ -#ifndef SQLITE_OMIT_AUTOVACUUM - if( eMode==BTALLOC_EXACT ){ - if( nearby<=mxPage ){ - u8 eType; - assert( nearby>0 ); - assert( pBt->autoVacuum ); - rc = ptrmapGet(pBt, nearby, &eType, 0); - if( rc ) return rc; - if( eType==PTRMAP_FREEPAGE ){ - searchList = 1; - } - } - }else if( eMode==BTALLOC_LE ){ - searchList = 1; - } -#endif - - /* Decrement the free-list count by 1. Set iTrunk to the index of the - ** first free-list trunk page. iPrevTrunk is initially 1. - */ - rc = sqlite3PagerWrite(pPage1->pDbPage); - if( rc ) return rc; - put4byte(&pPage1->aData[36], n-1); - - /* The code within this loop is run only once if the 'searchList' variable - ** is not true. Otherwise, it runs once for each trunk-page on the - ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) - ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) - */ - do { - pPrevTrunk = pTrunk; - if( pPrevTrunk ){ - /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page - ** is the page number of the next freelist trunk page in the list or - ** zero if this is the last freelist trunk page. */ - iTrunk = get4byte(&pPrevTrunk->aData[0]); - }else{ - /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32 - ** stores the page number of the first page of the freelist, or zero if - ** the freelist is empty. */ - iTrunk = get4byte(&pPage1->aData[32]); - } - testcase( iTrunk==mxPage ); - if( iTrunk>mxPage || nSearch++ > n ){ - rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1); - }else{ - rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0); - } - if( rc ){ - pTrunk = 0; - goto end_allocate_page; - } - assert( pTrunk!=0 ); - assert( pTrunk->aData!=0 ); - /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page - ** is the number of leaf page pointers to follow. */ - k = get4byte(&pTrunk->aData[4]); - if( k==0 && !searchList ){ - /* The trunk has no leaves and the list is not being searched. - ** So extract the trunk page itself and use it as the newly - ** allocated page */ - assert( pPrevTrunk==0 ); - rc = sqlite3PagerWrite(pTrunk->pDbPage); - if( rc ){ - goto end_allocate_page; - } - *pPgno = iTrunk; - memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); - *ppPage = pTrunk; - pTrunk = 0; - TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); - }else if( k>(u32)(pBt->usableSize/4 - 2) ){ - /* Value of k is out of range. Database corruption */ - rc = SQLITE_CORRUPT_PGNO(iTrunk); - goto end_allocate_page; -#ifndef SQLITE_OMIT_AUTOVACUUM - }else if( searchList - && (nearby==iTrunk || (iTrunkpDbPage); - if( rc ){ - goto end_allocate_page; - } - if( k==0 ){ - if( !pPrevTrunk ){ - memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); - }else{ - rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); - if( rc!=SQLITE_OK ){ - goto end_allocate_page; - } - memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); - } - }else{ - /* The trunk page is required by the caller but it contains - ** pointers to free-list leaves. The first leaf becomes a trunk - ** page in this case. - */ - MemPage *pNewTrunk; - Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); - if( iNewTrunk>mxPage ){ - rc = SQLITE_CORRUPT_PGNO(iTrunk); - goto end_allocate_page; - } - testcase( iNewTrunk==mxPage ); - rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0); - if( rc!=SQLITE_OK ){ - goto end_allocate_page; - } - rc = sqlite3PagerWrite(pNewTrunk->pDbPage); - if( rc!=SQLITE_OK ){ - releasePage(pNewTrunk); - goto end_allocate_page; - } - memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); - put4byte(&pNewTrunk->aData[4], k-1); - memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); - releasePage(pNewTrunk); - if( !pPrevTrunk ){ - assert( sqlite3PagerIswriteable(pPage1->pDbPage) ); - put4byte(&pPage1->aData[32], iNewTrunk); - }else{ - rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); - if( rc ){ - goto end_allocate_page; - } - put4byte(&pPrevTrunk->aData[0], iNewTrunk); - } - } - pTrunk = 0; - TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); -#endif - }else if( k>0 ){ - /* Extract a leaf from the trunk */ - u32 closest; - Pgno iPage; - unsigned char *aData = pTrunk->aData; - if( nearby>0 ){ - u32 i; - closest = 0; - if( eMode==BTALLOC_LE ){ - for(i=0; imxPage ){ - rc = SQLITE_CORRUPT_PGNO(iTrunk); - goto end_allocate_page; - } - testcase( iPage==mxPage ); - if( !searchList - || (iPage==nearby || (iPagepgno, n-1)); - rc = sqlite3PagerWrite(pTrunk->pDbPage); - if( rc ) goto end_allocate_page; - if( closestpDbPage); - if( rc!=SQLITE_OK ){ - releasePage(*ppPage); - *ppPage = 0; - } - } - searchList = 0; - } - } - releasePage(pPrevTrunk); - pPrevTrunk = 0; - }while( searchList ); - }else{ - /* There are no pages on the freelist, so append a new page to the - ** database image. - ** - ** Normally, new pages allocated by this block can be requested from the - ** pager layer with the 'no-content' flag set. This prevents the pager - ** from trying to read the pages content from disk. However, if the - ** current transaction has already run one or more incremental-vacuum - ** steps, then the page we are about to allocate may contain content - ** that is required in the event of a rollback. In this case, do - ** not set the no-content flag. This causes the pager to load and journal - ** the current page content before overwriting it. - ** - ** Note that the pager will not actually attempt to load or journal - ** content for any page that really does lie past the end of the database - ** file on disk. So the effects of disabling the no-content optimization - ** here are confined to those pages that lie between the end of the - ** database image and the end of the database file. - */ - int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; - - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); - if( rc ) return rc; - pBt->nPage++; - if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; - -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ - /* If *pPgno refers to a pointer-map page, allocate two new pages - ** at the end of the file instead of one. The first allocated page - ** becomes a new pointer-map page, the second is used by the caller. - */ - MemPage *pPg = 0; - TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); - assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); - rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent); - if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pPg->pDbPage); - releasePage(pPg); - } - if( rc ) return rc; - pBt->nPage++; - if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } - } -#endif - put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); - *pPgno = pBt->nPage; - - assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); - rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent); - if( rc ) return rc; - rc = sqlite3PagerWrite((*ppPage)->pDbPage); - if( rc!=SQLITE_OK ){ - releasePage(*ppPage); - *ppPage = 0; - } - TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); - } - - assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) ); - -end_allocate_page: - releasePage(pTrunk); - releasePage(pPrevTrunk); - assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 ); - assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 ); - return rc; -} - -/* -** This function is used to add page iPage to the database file free-list. -** It is assumed that the page is not already a part of the free-list. -** -** The value passed as the second argument to this function is optional. -** If the caller happens to have a pointer to the MemPage object -** corresponding to page iPage handy, it may pass it as the second value. -** Otherwise, it may pass NULL. -** -** If a pointer to a MemPage object is passed as the second argument, -** its reference count is not altered by this function. -*/ -static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){ - MemPage *pTrunk = 0; /* Free-list trunk page */ - Pgno iTrunk = 0; /* Page number of free-list trunk page */ - MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */ - MemPage *pPage; /* Page being freed. May be NULL. */ - int rc; /* Return Code */ - u32 nFree; /* Initial number of pages on free-list */ - - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( CORRUPT_DB || iPage>1 ); - assert( !pMemPage || pMemPage->pgno==iPage ); - - if( iPage<2 || iPage>pBt->nPage ){ - return SQLITE_CORRUPT_BKPT; - } - if( pMemPage ){ - pPage = pMemPage; - sqlite3PagerRef(pPage->pDbPage); - }else{ - pPage = btreePageLookup(pBt, iPage); - } - - /* Increment the free page count on pPage1 */ - rc = sqlite3PagerWrite(pPage1->pDbPage); - if( rc ) goto freepage_out; - nFree = get4byte(&pPage1->aData[36]); - put4byte(&pPage1->aData[36], nFree+1); - - if( pBt->btsFlags & BTS_SECURE_DELETE ){ - /* If the secure_delete option is enabled, then - ** always fully overwrite deleted information with zeros. - */ - if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) - || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) - ){ - goto freepage_out; - } - memset(pPage->aData, 0, pPage->pBt->pageSize); - } - - /* If the database supports auto-vacuum, write an entry in the pointer-map - ** to indicate that the page is free. - */ - if( ISAUTOVACUUM ){ - ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); - if( rc ) goto freepage_out; - } - - /* Now manipulate the actual database free-list structure. There are two - ** possibilities. If the free-list is currently empty, or if the first - ** trunk page in the free-list is full, then this page will become a - ** new free-list trunk page. Otherwise, it will become a leaf of the - ** first trunk page in the current free-list. This block tests if it - ** is possible to add the page as a new free-list leaf. - */ - if( nFree!=0 ){ - u32 nLeaf; /* Initial number of leaf cells on trunk page */ - - iTrunk = get4byte(&pPage1->aData[32]); - if( iTrunk>btreePagecount(pBt) ){ - rc = SQLITE_CORRUPT_BKPT; - goto freepage_out; - } - rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); - if( rc!=SQLITE_OK ){ - goto freepage_out; - } - - nLeaf = get4byte(&pTrunk->aData[4]); - assert( pBt->usableSize>32 ); - if( nLeaf > (u32)pBt->usableSize/4 - 2 ){ - rc = SQLITE_CORRUPT_BKPT; - goto freepage_out; - } - if( nLeaf < (u32)pBt->usableSize/4 - 8 ){ - /* In this case there is room on the trunk page to insert the page - ** being freed as a new leaf. - ** - ** Note that the trunk page is not really full until it contains - ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have - ** coded. But due to a coding error in versions of SQLite prior to - ** 3.6.0, databases with freelist trunk pages holding more than - ** usableSize/4 - 8 entries will be reported as corrupt. In order - ** to maintain backwards compatibility with older versions of SQLite, - ** we will continue to restrict the number of entries to usableSize/4 - 8 - ** for now. At some point in the future (once everyone has upgraded - ** to 3.6.0 or later) we should consider fixing the conditional above - ** to read "usableSize/4-2" instead of "usableSize/4-8". - ** - ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still - ** avoid using the last six entries in the freelist trunk page array in - ** order that database files created by newer versions of SQLite can be - ** read by older versions of SQLite. - */ - rc = sqlite3PagerWrite(pTrunk->pDbPage); - if( rc==SQLITE_OK ){ - put4byte(&pTrunk->aData[4], nLeaf+1); - put4byte(&pTrunk->aData[8+nLeaf*4], iPage); - if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ - sqlite3PagerDontWrite(pPage->pDbPage); - } - rc = btreeSetHasContent(pBt, iPage); - } - TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); - goto freepage_out; - } - } - - /* If control flows to this point, then it was not possible to add the - ** the page being freed as a leaf page of the first trunk in the free-list. - ** Possibly because the free-list is empty, or possibly because the - ** first trunk in the free-list is full. Either way, the page being freed - ** will become the new first trunk page in the free-list. - */ - if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){ - goto freepage_out; - } - rc = sqlite3PagerWrite(pPage->pDbPage); - if( rc!=SQLITE_OK ){ - goto freepage_out; - } - put4byte(pPage->aData, iTrunk); - put4byte(&pPage->aData[4], 0); - put4byte(&pPage1->aData[32], iPage); - TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk)); - -freepage_out: - if( pPage ){ - pPage->isInit = 0; - } - releasePage(pPage); - releasePage(pTrunk); - return rc; -} -static void freePage(MemPage *pPage, int *pRC){ - if( (*pRC)==SQLITE_OK ){ - *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); - } -} - -/* -** Free any overflow pages associated with the given Cell. Store -** size information about the cell in pInfo. -*/ -static int clearCell( - MemPage *pPage, /* The page that contains the Cell */ - unsigned char *pCell, /* First byte of the Cell */ - CellInfo *pInfo /* Size information about the cell */ -){ - BtShared *pBt; - Pgno ovflPgno; - int rc; - int nOvfl; - u32 ovflPageSize; - - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - pPage->xParseCell(pPage, pCell, pInfo); - if( pInfo->nLocal==pInfo->nPayload ){ - return SQLITE_OK; /* No overflow pages. Return without doing anything */ - } - testcase( pCell + pInfo->nSize == pPage->aDataEnd ); - testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd ); - if( pCell + pInfo->nSize > pPage->aDataEnd ){ - /* Cell extends past end of page */ - return SQLITE_CORRUPT_PAGE(pPage); - } - ovflPgno = get4byte(pCell + pInfo->nSize - 4); - pBt = pPage->pBt; - assert( pBt->usableSize > 4 ); - ovflPageSize = pBt->usableSize - 4; - nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize; - assert( nOvfl>0 || - (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)btreePagecount(pBt) ){ - /* 0 is not a legal page number and page 1 cannot be an - ** overflow page. Therefore if ovflPgno<2 or past the end of the - ** file the database must be corrupt. */ - return SQLITE_CORRUPT_BKPT; - } - if( nOvfl ){ - rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); - if( rc ) return rc; - } - - if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) - && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 - ){ - /* There is no reason any cursor should have an outstanding reference - ** to an overflow page belonging to a cell that is being deleted/updated. - ** So if there exists more than one reference to this page, then it - ** must not really be an overflow page and the database must be corrupt. - ** It is helpful to detect this before calling freePage2(), as - ** freePage2() may zero the page contents if secure-delete mode is - ** enabled. If this 'overflow' page happens to be a page that the - ** caller is iterating through or using in some other way, this - ** can be problematic. - */ - rc = SQLITE_CORRUPT_BKPT; - }else{ - rc = freePage2(pBt, pOvfl, ovflPgno); - } - - if( pOvfl ){ - sqlite3PagerUnref(pOvfl->pDbPage); - } - if( rc ) return rc; - ovflPgno = iNext; - } - return SQLITE_OK; -} - -/* -** Create the byte sequence used to represent a cell on page pPage -** and write that byte sequence into pCell[]. Overflow pages are -** allocated and filled in as necessary. The calling procedure -** is responsible for making sure sufficient space has been allocated -** for pCell[]. -** -** Note that pCell does not necessary need to point to the pPage->aData -** area. pCell might point to some temporary storage. The cell will -** be constructed in this temporary area then copied into pPage->aData -** later. -*/ -static int fillInCell( - MemPage *pPage, /* The page that contains the cell */ - unsigned char *pCell, /* Complete text of the cell */ - const BtreePayload *pX, /* Payload with which to construct the cell */ - int *pnSize /* Write cell size here */ -){ - int nPayload; - const u8 *pSrc; - int nSrc, n, rc, mn; - int spaceLeft; - MemPage *pToRelease; - unsigned char *pPrior; - unsigned char *pPayload; - BtShared *pBt; - Pgno pgnoOvfl; - int nHeader; - - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - - /* pPage is not necessarily writeable since pCell might be auxiliary - ** buffer space that is separate from the pPage buffer area */ - assert( pCellaData || pCell>=&pPage->aData[pPage->pBt->pageSize] - || sqlite3PagerIswriteable(pPage->pDbPage) ); - - /* Fill in the header. */ - nHeader = pPage->childPtrSize; - if( pPage->intKey ){ - nPayload = pX->nData + pX->nZero; - pSrc = pX->pData; - nSrc = pX->nData; - assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */ - nHeader += putVarint32(&pCell[nHeader], nPayload); - nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey); - }else{ - assert( pX->nKey<=0x7fffffff && pX->pKey!=0 ); - nSrc = nPayload = (int)pX->nKey; - pSrc = pX->pKey; - nHeader += putVarint32(&pCell[nHeader], nPayload); - } - - /* Fill in the payload */ - pPayload = &pCell[nHeader]; - if( nPayload<=pPage->maxLocal ){ - /* This is the common case where everything fits on the btree page - ** and no overflow pages are required. */ - n = nHeader + nPayload; - testcase( n==3 ); - testcase( n==4 ); - if( n<4 ) n = 4; - *pnSize = n; - assert( nSrc<=nPayload ); - testcase( nSrcminLocal; - n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); - testcase( n==pPage->maxLocal ); - testcase( n==pPage->maxLocal+1 ); - if( n > pPage->maxLocal ) n = mn; - spaceLeft = n; - *pnSize = n + nHeader + 4; - pPrior = &pCell[nHeader+n]; - pToRelease = 0; - pgnoOvfl = 0; - pBt = pPage->pBt; - - /* At this point variables should be set as follows: - ** - ** nPayload Total payload size in bytes - ** pPayload Begin writing payload here - ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, - ** that means content must spill into overflow pages. - ** *pnSize Size of the local cell (not counting overflow pages) - ** pPrior Where to write the pgno of the first overflow page - ** - ** Use a call to btreeParseCellPtr() to verify that the values above - ** were computed correctly. - */ -#ifdef SQLITE_DEBUG - { - CellInfo info; - pPage->xParseCell(pPage, pCell, &info); - assert( nHeader==(int)(info.pPayload - pCell) ); - assert( info.nKey==pX->nKey ); - assert( *pnSize == info.nSize ); - assert( spaceLeft == info.nLocal ); - } -#endif - - /* Write the payload into the local Cell and any extra into overflow pages */ - while( 1 ){ - n = nPayload; - if( n>spaceLeft ) n = spaceLeft; - - /* If pToRelease is not zero than pPayload points into the data area - ** of pToRelease. Make sure pToRelease is still writeable. */ - assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); - - /* If pPayload is part of the data area of pPage, then make sure pPage - ** is still writeable */ - assert( pPayloadaData || pPayload>=&pPage->aData[pBt->pageSize] - || sqlite3PagerIswriteable(pPage->pDbPage) ); - - if( nSrc>=n ){ - memcpy(pPayload, pSrc, n); - }else if( nSrc>0 ){ - n = nSrc; - memcpy(pPayload, pSrc, n); - }else{ - memset(pPayload, 0, n); - } - nPayload -= n; - if( nPayload<=0 ) break; - pPayload += n; - pSrc += n; - nSrc -= n; - spaceLeft -= n; - if( spaceLeft==0 ){ - MemPage *pOvfl = 0; -#ifndef SQLITE_OMIT_AUTOVACUUM - Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ - if( pBt->autoVacuum ){ - do{ - pgnoOvfl++; - } while( - PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) - ); - } -#endif - rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); -#ifndef SQLITE_OMIT_AUTOVACUUM - /* If the database supports auto-vacuum, and the second or subsequent - ** overflow page is being allocated, add an entry to the pointer-map - ** for that page now. - ** - ** If this is the first overflow page, then write a partial entry - ** to the pointer-map. If we write nothing to this pointer-map slot, - ** then the optimistic overflow chain processing in clearCell() - ** may misinterpret the uninitialized values and delete the - ** wrong pages from the database. - */ - if( pBt->autoVacuum && rc==SQLITE_OK ){ - u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); - ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); - if( rc ){ - releasePage(pOvfl); - } - } -#endif - if( rc ){ - releasePage(pToRelease); - return rc; - } - - /* If pToRelease is not zero than pPrior points into the data area - ** of pToRelease. Make sure pToRelease is still writeable. */ - assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) ); - - /* If pPrior is part of the data area of pPage, then make sure pPage - ** is still writeable */ - assert( pPrioraData || pPrior>=&pPage->aData[pBt->pageSize] - || sqlite3PagerIswriteable(pPage->pDbPage) ); - - put4byte(pPrior, pgnoOvfl); - releasePage(pToRelease); - pToRelease = pOvfl; - pPrior = pOvfl->aData; - put4byte(pPrior, 0); - pPayload = &pOvfl->aData[4]; - spaceLeft = pBt->usableSize - 4; - } - } - releasePage(pToRelease); - return SQLITE_OK; -} - -/* -** Remove the i-th cell from pPage. This routine effects pPage only. -** The cell content is not freed or deallocated. It is assumed that -** the cell content has been copied someplace else. This routine just -** removes the reference to the cell from pPage. -** -** "sz" must be the number of bytes in the cell. -*/ -static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ - u32 pc; /* Offset to cell content of cell being deleted */ - u8 *data; /* pPage->aData */ - u8 *ptr; /* Used to move bytes around within data[] */ - int rc; /* The return code */ - int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ - - if( *pRC ) return; - assert( idx>=0 && idxnCell ); - assert( CORRUPT_DB || sz==cellSize(pPage, idx) ); - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( pPage->nFree>=0 ); - data = pPage->aData; - ptr = &pPage->aCellIdx[2*idx]; - pc = get2byte(ptr); - hdr = pPage->hdrOffset; - testcase( pc==get2byte(&data[hdr+5]) ); - testcase( pc+sz==pPage->pBt->usableSize ); - if( pc+sz > pPage->pBt->usableSize ){ - *pRC = SQLITE_CORRUPT_BKPT; - return; - } - rc = freeSpace(pPage, pc, sz); - if( rc ){ - *pRC = rc; - return; - } - pPage->nCell--; - if( pPage->nCell==0 ){ - memset(&data[hdr+1], 0, 4); - data[hdr+7] = 0; - put2byte(&data[hdr+5], pPage->pBt->usableSize); - pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset - - pPage->childPtrSize - 8; - }else{ - memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); - put2byte(&data[hdr+3], pPage->nCell); - pPage->nFree += 2; - } -} - -/* -** Insert a new cell on pPage at cell index "i". pCell points to the -** content of the cell. -** -** If the cell content will fit on the page, then put it there. If it -** will not fit, then make a copy of the cell content into pTemp if -** pTemp is not null. Regardless of pTemp, allocate a new entry -** in pPage->apOvfl[] and make it point to the cell content (either -** in pTemp or the original pCell) and also record its index. -** Allocating a new entry in pPage->aCell[] implies that -** pPage->nOverflow is incremented. -** -** *pRC must be SQLITE_OK when this routine is called. -*/ -static void insertCell( - MemPage *pPage, /* Page into which we are copying */ - int i, /* New cell becomes the i-th cell of the page */ - u8 *pCell, /* Content of the new cell */ - int sz, /* Bytes of content in pCell */ - u8 *pTemp, /* Temp storage space for pCell, if needed */ - Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ - int *pRC /* Read and write return code from here */ -){ - int idx = 0; /* Where to write new cell content in data[] */ - int j; /* Loop counter */ - u8 *data; /* The content of the whole page */ - u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */ - - assert( *pRC==SQLITE_OK ); - assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); - assert( MX_CELL(pPage->pBt)<=10921 ); - assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); - assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); - assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB ); - assert( pPage->nFree>=0 ); - if( pPage->nOverflow || sz+2>pPage->nFree ){ - if( pTemp ){ - memcpy(pTemp, pCell, sz); - pCell = pTemp; - } - if( iChild ){ - put4byte(pCell, iChild); - } - j = pPage->nOverflow++; - /* Comparison against ArraySize-1 since we hold back one extra slot - ** as a contingency. In other words, never need more than 3 overflow - ** slots but 4 are allocated, just to be safe. */ - assert( j < ArraySize(pPage->apOvfl)-1 ); - pPage->apOvfl[j] = pCell; - pPage->aiOvfl[j] = (u16)i; - - /* When multiple overflows occur, they are always sequential and in - ** sorted order. This invariants arise because multiple overflows can - ** only occur when inserting divider cells into the parent page during - ** balancing, and the dividers are adjacent and sorted. - */ - assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */ - assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */ - }else{ - int rc = sqlite3PagerWrite(pPage->pDbPage); - if( rc!=SQLITE_OK ){ - *pRC = rc; - return; - } - assert( sqlite3PagerIswriteable(pPage->pDbPage) ); - data = pPage->aData; - assert( &data[pPage->cellOffset]==pPage->aCellIdx ); - rc = allocateSpace(pPage, sz, &idx); - if( rc ){ *pRC = rc; return; } - /* The allocateSpace() routine guarantees the following properties - ** if it returns successfully */ - assert( idx >= 0 ); - assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB ); - assert( idx+sz <= (int)pPage->pBt->usableSize ); - pPage->nFree -= (u16)(2 + sz); - if( iChild ){ - /* In a corrupt database where an entry in the cell index section of - ** a btree page has a value of 3 or less, the pCell value might point - ** as many as 4 bytes in front of the start of the aData buffer for - ** the source page. Make sure this does not cause problems by not - ** reading the first 4 bytes */ - memcpy(&data[idx+4], pCell+4, sz-4); - put4byte(&data[idx], iChild); - }else{ - memcpy(&data[idx], pCell, sz); - } - pIns = pPage->aCellIdx + i*2; - memmove(pIns+2, pIns, 2*(pPage->nCell - i)); - put2byte(pIns, idx); - pPage->nCell++; - /* increment the cell count */ - if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++; - assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB ); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pPage->pBt->autoVacuum ){ - /* The cell may contain a pointer to an overflow page. If so, write - ** the entry for the overflow page into the pointer map. - */ - ptrmapPutOvflPtr(pPage, pPage, pCell, pRC); - } -#endif - } -} - -/* -** The following parameters determine how many adjacent pages get involved -** in a balancing operation. NN is the number of neighbors on either side -** of the page that participate in the balancing operation. NB is the -** total number of pages that participate, including the target page and -** NN neighbors on either side. -** -** The minimum value of NN is 1 (of course). Increasing NN above 1 -** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance -** in exchange for a larger degradation in INSERT and UPDATE performance. -** The value of NN appears to give the best results overall. -** -** (Later:) The description above makes it seem as if these values are -** tunable - as if you could change them and recompile and it would all work. -** But that is unlikely. NB has been 3 since the inception of SQLite and -** we have never tested any other value. -*/ -#define NN 1 /* Number of neighbors on either side of pPage */ -#define NB 3 /* (NN*2+1): Total pages involved in the balance */ - -/* -** A CellArray object contains a cache of pointers and sizes for a -** consecutive sequence of cells that might be held on multiple pages. -** -** The cells in this array are the divider cell or cells from the pParent -** page plus up to three child pages. There are a total of nCell cells. -** -** pRef is a pointer to one of the pages that contributes cells. This is -** used to access information such as MemPage.intKey and MemPage.pBt->pageSize -** which should be common to all pages that contribute cells to this array. -** -** apCell[] and szCell[] hold, respectively, pointers to the start of each -** cell and the size of each cell. Some of the apCell[] pointers might refer -** to overflow cells. In other words, some apCel[] pointers might not point -** to content area of the pages. -** -** A szCell[] of zero means the size of that cell has not yet been computed. -** -** The cells come from as many as four different pages: -** -** ----------- -** | Parent | -** ----------- -** / | \ -** / | \ -** --------- --------- --------- -** |Child-1| |Child-2| |Child-3| -** --------- --------- --------- -** -** The order of cells is in the array is for an index btree is: -** -** 1. All cells from Child-1 in order -** 2. The first divider cell from Parent -** 3. All cells from Child-2 in order -** 4. The second divider cell from Parent -** 5. All cells from Child-3 in order -** -** For a table-btree (with rowids) the items 2 and 4 are empty because -** content exists only in leaves and there are no divider cells. -** -** For an index btree, the apEnd[] array holds pointer to the end of page -** for Child-1, the Parent, Child-2, the Parent (again), and Child-3, -** respectively. The ixNx[] array holds the number of cells contained in -** each of these 5 stages, and all stages to the left. Hence: -** -** ixNx[0] = Number of cells in Child-1. -** ixNx[1] = Number of cells in Child-1 plus 1 for first divider. -** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider. -** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells -** ixNx[4] = Total number of cells. -** -** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2] -** are used and they point to the leaf pages only, and the ixNx value are: -** -** ixNx[0] = Number of cells in Child-1. -** ixNx[1] = Number of cells in Child-1 and Child-2. -** ixNx[2] = Total number of cells. -** -** Sometimes when deleting, a child page can have zero cells. In those -** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[] -** entries, shift down. The end result is that each ixNx[] entry should -** be larger than the previous -*/ -typedef struct CellArray CellArray; -struct CellArray { - int nCell; /* Number of cells in apCell[] */ - MemPage *pRef; /* Reference page */ - u8 **apCell; /* All cells begin balanced */ - u16 *szCell; /* Local size of all cells in apCell[] */ - u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */ - int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */ -}; - -/* -** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been -** computed. -*/ -static void populateCellCache(CellArray *p, int idx, int N){ - assert( idx>=0 && idx+N<=p->nCell ); - while( N>0 ){ - assert( p->apCell[idx]!=0 ); - if( p->szCell[idx]==0 ){ - p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]); - }else{ - assert( CORRUPT_DB || - p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) ); - } - idx++; - N--; - } -} - -/* -** Return the size of the Nth element of the cell array -*/ -static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){ - assert( N>=0 && NnCell ); - assert( p->szCell[N]==0 ); - p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]); - return p->szCell[N]; -} -static u16 cachedCellSize(CellArray *p, int N){ - assert( N>=0 && NnCell ); - if( p->szCell[N] ) return p->szCell[N]; - return computeCellSize(p, N); -} - -/* -** Array apCell[] contains pointers to nCell b-tree page cells. The -** szCell[] array contains the size in bytes of each cell. This function -** replaces the current contents of page pPg with the contents of the cell -** array. -** -** Some of the cells in apCell[] may currently be stored in pPg. This -** function works around problems caused by this by making a copy of any -** such cells before overwriting the page data. -** -** The MemPage.nFree field is invalidated by this function. It is the -** responsibility of the caller to set it correctly. -*/ -static int rebuildPage( - CellArray *pCArray, /* Content to be added to page pPg */ - int iFirst, /* First cell in pCArray to use */ - int nCell, /* Final number of cells on page */ - MemPage *pPg /* The page to be reconstructed */ -){ - const int hdr = pPg->hdrOffset; /* Offset of header on pPg */ - u8 * const aData = pPg->aData; /* Pointer to data for pPg */ - const int usableSize = pPg->pBt->usableSize; - u8 * const pEnd = &aData[usableSize]; - int i = iFirst; /* Which cell to copy from pCArray*/ - u32 j; /* Start of cell content area */ - int iEnd = i+nCell; /* Loop terminator */ - u8 *pCellptr = pPg->aCellIdx; - u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); - u8 *pData; - int k; /* Current slot in pCArray->apEnd[] */ - u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */ - - assert( i(u32)usableSize) ){ j = 0; } - memcpy(&pTmp[j], &aData[j], usableSize - j); - - for(k=0; pCArray->ixNx[k]<=i && ALWAYS(kapEnd[k]; - - pData = pEnd; - while( 1/*exit by break*/ ){ - u8 *pCell = pCArray->apCell[i]; - u16 sz = pCArray->szCell[i]; - assert( sz>0 ); - if( SQLITE_WITHIN(pCell,aData,pEnd) ){ - if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT; - pCell = &pTmp[pCell - aData]; - }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd - && (uptr)(pCell)<(uptr)pSrcEnd - ){ - return SQLITE_CORRUPT_BKPT; - } - - pData -= sz; - put2byte(pCellptr, (pData - aData)); - pCellptr += 2; - if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT; - memcpy(pData, pCell, sz); - assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB ); - testcase( sz!=pPg->xCellSize(pPg,pCell) ) - i++; - if( i>=iEnd ) break; - if( pCArray->ixNx[k]<=i ){ - k++; - pSrcEnd = pCArray->apEnd[k]; - } - } - - /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ - pPg->nCell = nCell; - pPg->nOverflow = 0; - - put2byte(&aData[hdr+1], 0); - put2byte(&aData[hdr+3], pPg->nCell); - put2byte(&aData[hdr+5], pData - aData); - aData[hdr+7] = 0x00; - return SQLITE_OK; -} - -/* -** The pCArray objects contains pointers to b-tree cells and the cell sizes. -** This function attempts to add the cells stored in the array to page pPg. -** If it cannot (because the page needs to be defragmented before the cells -** will fit), non-zero is returned. Otherwise, if the cells are added -** successfully, zero is returned. -** -** Argument pCellptr points to the first entry in the cell-pointer array -** (part of page pPg) to populate. After cell apCell[0] is written to the -** page body, a 16-bit offset is written to pCellptr. And so on, for each -** cell in the array. It is the responsibility of the caller to ensure -** that it is safe to overwrite this part of the cell-pointer array. -** -** When this function is called, *ppData points to the start of the -** content area on page pPg. If the size of the content area is extended, -** *ppData is updated to point to the new start of the content area -** before returning. -** -** Finally, argument pBegin points to the byte immediately following the -** end of the space required by this page for the cell-pointer area (for -** all cells - not just those inserted by the current call). If the content -** area must be extended to before this point in order to accomodate all -** cells in apCell[], then the cells do not fit and non-zero is returned. -*/ -static int pageInsertArray( - MemPage *pPg, /* Page to add cells to */ - u8 *pBegin, /* End of cell-pointer array */ - u8 **ppData, /* IN/OUT: Page content-area pointer */ - u8 *pCellptr, /* Pointer to cell-pointer area */ - int iFirst, /* Index of first cell to add */ - int nCell, /* Number of cells to add to pPg */ - CellArray *pCArray /* Array of cells */ -){ - int i = iFirst; /* Loop counter - cell index to insert */ - u8 *aData = pPg->aData; /* Complete page */ - u8 *pData = *ppData; /* Content area. A subset of aData[] */ - int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */ - int k; /* Current slot in pCArray->apEnd[] */ - u8 *pEnd; /* Maximum extent of cell data */ - assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ - if( iEnd<=iFirst ) return 0; - for(k=0; pCArray->ixNx[k]<=i && ALWAYS(kapEnd[k]; - while( 1 /*Exit by break*/ ){ - int sz, rc; - u8 *pSlot; - assert( pCArray->szCell[i]!=0 ); - sz = pCArray->szCell[i]; - if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){ - if( (pData - pBegin)apCell[i] will never overlap on a well-formed - ** database. But they might for a corrupt database. Hence use memmove() - ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */ - assert( (pSlot+sz)<=pCArray->apCell[i] - || pSlot>=(pCArray->apCell[i]+sz) - || CORRUPT_DB ); - if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd - && (uptr)(pCArray->apCell[i])<(uptr)pEnd - ){ - assert( CORRUPT_DB ); - (void)SQLITE_CORRUPT_BKPT; - return 1; - } - memmove(pSlot, pCArray->apCell[i], sz); - put2byte(pCellptr, (pSlot - aData)); - pCellptr += 2; - i++; - if( i>=iEnd ) break; - if( pCArray->ixNx[k]<=i ){ - k++; - pEnd = pCArray->apEnd[k]; - } - } - *ppData = pData; - return 0; -} - -/* -** The pCArray object contains pointers to b-tree cells and their sizes. -** -** This function adds the space associated with each cell in the array -** that is currently stored within the body of pPg to the pPg free-list. -** The cell-pointers and other fields of the page are not updated. -** -** This function returns the total number of cells added to the free-list. -*/ -static int pageFreeArray( - MemPage *pPg, /* Page to edit */ - int iFirst, /* First cell to delete */ - int nCell, /* Cells to delete */ - CellArray *pCArray /* Array of cells */ -){ - u8 * const aData = pPg->aData; - u8 * const pEnd = &aData[pPg->pBt->usableSize]; - u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize]; - int nRet = 0; - int i; - int iEnd = iFirst + nCell; - u8 *pFree = 0; - int szFree = 0; - - for(i=iFirst; iapCell[i]; - if( SQLITE_WITHIN(pCell, pStart, pEnd) ){ - int sz; - /* No need to use cachedCellSize() here. The sizes of all cells that - ** are to be freed have already been computing while deciding which - ** cells need freeing */ - sz = pCArray->szCell[i]; assert( sz>0 ); - if( pFree!=(pCell + sz) ){ - if( pFree ){ - assert( pFree>aData && (pFree - aData)<65536 ); - freeSpace(pPg, (u16)(pFree - aData), szFree); - } - pFree = pCell; - szFree = sz; - if( pFree+sz>pEnd ) return 0; - }else{ - pFree = pCell; - szFree += sz; - } - nRet++; - } - } - if( pFree ){ - assert( pFree>aData && (pFree - aData)<65536 ); - freeSpace(pPg, (u16)(pFree - aData), szFree); - } - return nRet; -} - -/* -** pCArray contains pointers to and sizes of all cells in the page being -** balanced. The current page, pPg, has pPg->nCell cells starting with -** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells -** starting at apCell[iNew]. -** -** This routine makes the necessary adjustments to pPg so that it contains -** the correct cells after being balanced. -** -** The pPg->nFree field is invalid when this function returns. It is the -** responsibility of the caller to set it correctly. -*/ -static int editPage( - MemPage *pPg, /* Edit this page */ - int iOld, /* Index of first cell currently on page */ - int iNew, /* Index of new first cell on page */ - int nNew, /* Final number of cells on page */ - CellArray *pCArray /* Array of cells and sizes */ -){ - u8 * const aData = pPg->aData; - const int hdr = pPg->hdrOffset; - u8 *pBegin = &pPg->aCellIdx[nNew * 2]; - int nCell = pPg->nCell; /* Cells stored on pPg */ - u8 *pData; - u8 *pCellptr; - int i; - int iOldEnd = iOld + pPg->nCell + pPg->nOverflow; - int iNewEnd = iNew + nNew; - -#ifdef SQLITE_DEBUG - u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); - memcpy(pTmp, aData, pPg->pBt->usableSize); -#endif - - /* Remove cells from the start and end of the page */ - assert( nCell>=0 ); - if( iOldnCell) ) return SQLITE_CORRUPT_BKPT; - memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); - nCell -= nShift; - } - if( iNewEnd < iOldEnd ){ - int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); - assert( nCell>=nTail ); - nCell -= nTail; - } - - pData = &aData[get2byteNotZero(&aData[hdr+5])]; - if( pData=0 ); - pCellptr = pPg->aCellIdx; - memmove(&pCellptr[nAdd*2], pCellptr, nCell*2); - if( pageInsertArray( - pPg, pBegin, &pData, pCellptr, - iNew, nAdd, pCArray - ) ) goto editpage_fail; - nCell += nAdd; - } - - /* Add any overflow cells */ - for(i=0; inOverflow; i++){ - int iCell = (iOld + pPg->aiOvfl[i]) - iNew; - if( iCell>=0 && iCellaCellIdx[iCell * 2]; - if( nCell>iCell ){ - memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); - } - nCell++; - cachedCellSize(pCArray, iCell+iNew); - if( pageInsertArray( - pPg, pBegin, &pData, pCellptr, - iCell+iNew, 1, pCArray - ) ) goto editpage_fail; - } - } - - /* Append cells to the end of the page */ - assert( nCell>=0 ); - pCellptr = &pPg->aCellIdx[nCell*2]; - if( pageInsertArray( - pPg, pBegin, &pData, pCellptr, - iNew+nCell, nNew-nCell, pCArray - ) ) goto editpage_fail; - - pPg->nCell = nNew; - pPg->nOverflow = 0; - - put2byte(&aData[hdr+3], pPg->nCell); - put2byte(&aData[hdr+5], pData - aData); - -#ifdef SQLITE_DEBUG - for(i=0; iapCell[i+iNew]; - int iOff = get2byteAligned(&pPg->aCellIdx[i*2]); - if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){ - pCell = &pTmp[pCell - aData]; - } - assert( 0==memcmp(pCell, &aData[iOff], - pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) ); - } -#endif - - return SQLITE_OK; - editpage_fail: - /* Unable to edit this page. Rebuild it from scratch instead. */ - populateCellCache(pCArray, iNew, nNew); - return rebuildPage(pCArray, iNew, nNew, pPg); -} - - -#ifndef SQLITE_OMIT_QUICKBALANCE -/* -** This version of balance() handles the common special case where -** a new entry is being inserted on the extreme right-end of the -** tree, in other words, when the new entry will become the largest -** entry in the tree. -** -** Instead of trying to balance the 3 right-most leaf pages, just add -** a new page to the right-hand side and put the one new entry in -** that page. This leaves the right side of the tree somewhat -** unbalanced. But odds are that we will be inserting new entries -** at the end soon afterwards so the nearly empty page will quickly -** fill up. On average. -** -** pPage is the leaf page which is the right-most page in the tree. -** pParent is its parent. pPage must have a single overflow entry -** which is also the right-most entry on the page. -** -** The pSpace buffer is used to store a temporary copy of the divider -** cell that will be inserted into pParent. Such a cell consists of a 4 -** byte page number followed by a variable length integer. In other -** words, at most 13 bytes. Hence the pSpace buffer must be at -** least 13 bytes in size. -*/ -static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){ - BtShared *const pBt = pPage->pBt; /* B-Tree Database */ - MemPage *pNew; /* Newly allocated page */ - int rc; /* Return Code */ - Pgno pgnoNew; /* Page number of pNew */ - - assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); - assert( pPage->nOverflow==1 ); - - if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */ - assert( pPage->nFree>=0 ); - assert( pParent->nFree>=0 ); - - /* Allocate a new page. This page will become the right-sibling of - ** pPage. Make the parent page writable, so that the new divider cell - ** may be inserted. If both these operations are successful, proceed. - */ - rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); - - if( rc==SQLITE_OK ){ - - u8 *pOut = &pSpace[4]; - u8 *pCell = pPage->apOvfl[0]; - u16 szCell = pPage->xCellSize(pPage, pCell); - u8 *pStop; - CellArray b; - - assert( sqlite3PagerIswriteable(pNew->pDbPage) ); - assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); - zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); - b.nCell = 1; - b.pRef = pPage; - b.apCell = &pCell; - b.szCell = &szCell; - b.apEnd[0] = pPage->aDataEnd; - b.ixNx[0] = 2; - rc = rebuildPage(&b, 0, 1, pNew); - if( NEVER(rc) ){ - releasePage(pNew); - return rc; - } - pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell; - - /* If this is an auto-vacuum database, update the pointer map - ** with entries for the new page, and any pointer from the - ** cell on the page to an overflow page. If either of these - ** operations fails, the return code is set, but the contents - ** of the parent page are still manipulated by thh code below. - ** That is Ok, at this point the parent page is guaranteed to - ** be marked as dirty. Returning an error code will cause a - ** rollback, undoing any changes made to the parent page. - */ - if( ISAUTOVACUUM ){ - ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc); - if( szCell>pNew->minLocal ){ - ptrmapPutOvflPtr(pNew, pNew, pCell, &rc); - } - } - - /* Create a divider cell to insert into pParent. The divider cell - ** consists of a 4-byte page number (the page number of pPage) and - ** a variable length key value (which must be the same value as the - ** largest key on pPage). - ** - ** To find the largest key value on pPage, first find the right-most - ** cell on pPage. The first two fields of this cell are the - ** record-length (a variable length integer at most 32-bits in size) - ** and the key value (a variable length integer, may have any value). - ** The first of the while(...) loops below skips over the record-length - ** field. The second while(...) loop copies the key value from the - ** cell on pPage into the pSpace buffer. - */ - pCell = findCell(pPage, pPage->nCell-1); - pStop = &pCell[9]; - while( (*(pCell++)&0x80) && pCellnCell, pSpace, (int)(pOut-pSpace), - 0, pPage->pgno, &rc); - } - - /* Set the right-child pointer of pParent to point to the new page. */ - put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); - - /* Release the reference to the new page. */ - releasePage(pNew); - } - - return rc; -} -#endif /* SQLITE_OMIT_QUICKBALANCE */ - -#if 0 -/* -** This function does not contribute anything to the operation of SQLite. -** it is sometimes activated temporarily while debugging code responsible -** for setting pointer-map entries. -*/ -static int ptrmapCheckPages(MemPage **apPage, int nPage){ - int i, j; - for(i=0; ipBt; - assert( pPage->isInit ); - - for(j=0; jnCell; j++){ - CellInfo info; - u8 *z; - - z = findCell(pPage, j); - pPage->xParseCell(pPage, z, &info); - if( info.nLocalpgno && e==PTRMAP_OVERFLOW1 ); - } - if( !pPage->leaf ){ - Pgno child = get4byte(z); - ptrmapGet(pBt, child, &e, &n); - assert( n==pPage->pgno && e==PTRMAP_BTREE ); - } - } - if( !pPage->leaf ){ - Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]); - ptrmapGet(pBt, child, &e, &n); - assert( n==pPage->pgno && e==PTRMAP_BTREE ); - } - } - return 1; -} -#endif - -/* -** This function is used to copy the contents of the b-tree node stored -** on page pFrom to page pTo. If page pFrom was not a leaf page, then -** the pointer-map entries for each child page are updated so that the -** parent page stored in the pointer map is page pTo. If pFrom contained -** any cells with overflow page pointers, then the corresponding pointer -** map entries are also updated so that the parent page is page pTo. -** -** If pFrom is currently carrying any overflow cells (entries in the -** MemPage.apOvfl[] array), they are not copied to pTo. -** -** Before returning, page pTo is reinitialized using btreeInitPage(). -** -** The performance of this function is not critical. It is only used by -** the balance_shallower() and balance_deeper() procedures, neither of -** which are called often under normal circumstances. -*/ -static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ - if( (*pRC)==SQLITE_OK ){ - BtShared * const pBt = pFrom->pBt; - u8 * const aFrom = pFrom->aData; - u8 * const aTo = pTo->aData; - int const iFromHdr = pFrom->hdrOffset; - int const iToHdr = ((pTo->pgno==1) ? 100 : 0); - int rc; - int iData; - - - assert( pFrom->isInit ); - assert( pFrom->nFree>=iToHdr ); - assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize ); - - /* Copy the b-tree node content from page pFrom to page pTo. */ - iData = get2byte(&aFrom[iFromHdr+5]); - memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData); - memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell); - - /* Reinitialize page pTo so that the contents of the MemPage structure - ** match the new data. The initialization of pTo can actually fail under - ** fairly obscure circumstances, even though it is a copy of initialized - ** page pFrom. - */ - pTo->isInit = 0; - rc = btreeInitPage(pTo); - if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo); - if( rc!=SQLITE_OK ){ - *pRC = rc; - return; - } - - /* If this is an auto-vacuum database, update the pointer-map entries - ** for any b-tree or overflow pages that pTo now contains the pointers to. - */ - if( ISAUTOVACUUM ){ - *pRC = setChildPtrmaps(pTo); - } - } -} - -/* -** This routine redistributes cells on the iParentIdx'th child of pParent -** (hereafter "the page") and up to 2 siblings so that all pages have about the -** same amount of free space. Usually a single sibling on either side of the -** page are used in the balancing, though both siblings might come from one -** side if the page is the first or last child of its parent. If the page -** has fewer than 2 siblings (something which can only happen if the page -** is a root page or a child of a root page) then all available siblings -** participate in the balancing. -** -** The number of siblings of the page might be increased or decreased by -** one or two in an effort to keep pages nearly full but not over full. -** -** Note that when this routine is called, some of the cells on the page -** might not actually be stored in MemPage.aData[]. This can happen -** if the page is overfull. This routine ensures that all cells allocated -** to the page and its siblings fit into MemPage.aData[] before returning. -** -** In the course of balancing the page and its siblings, cells may be -** inserted into or removed from the parent page (pParent). Doing so -** may cause the parent page to become overfull or underfull. If this -** happens, it is the responsibility of the caller to invoke the correct -** balancing routine to fix this problem (see the balance() routine). -** -** If this routine fails for any reason, it might leave the database -** in a corrupted state. So if this routine fails, the database should -** be rolled back. -** -** The third argument to this function, aOvflSpace, is a pointer to a -** buffer big enough to hold one page. If while inserting cells into the parent -** page (pParent) the parent page becomes overfull, this buffer is -** used to store the parent's overflow cells. Because this function inserts -** a maximum of four divider cells into the parent page, and the maximum -** size of a cell stored within an internal node is always less than 1/4 -** of the page-size, the aOvflSpace[] buffer is guaranteed to be large -** enough for all overflow cells. -** -** If aOvflSpace is set to a null pointer, this function returns -** SQLITE_NOMEM. -*/ -static int balance_nonroot( - MemPage *pParent, /* Parent page of siblings being balanced */ - int iParentIdx, /* Index of "the page" in pParent */ - u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ - int isRoot, /* True if pParent is a root-page */ - int bBulk /* True if this call is part of a bulk load */ -){ - BtShared *pBt; /* The whole database */ - int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ - int nNew = 0; /* Number of pages in apNew[] */ - int nOld; /* Number of pages in apOld[] */ - int i, j, k; /* Loop counters */ - int nxDiv; /* Next divider slot in pParent->aCell[] */ - int rc = SQLITE_OK; /* The return code */ - u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ - int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ - int usableSpace; /* Bytes in pPage beyond the header */ - int pageFlags; /* Value of pPage->aData[0] */ - int iSpace1 = 0; /* First unused byte of aSpace1[] */ - int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ - int szScratch; /* Size of scratch memory requested */ - MemPage *apOld[NB]; /* pPage and up to two siblings */ - MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ - u8 *pRight; /* Location in parent of right-sibling pointer */ - u8 *apDiv[NB-1]; /* Divider cells in pParent */ - int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */ - int cntOld[NB+2]; /* Old index in b.apCell[] */ - int szNew[NB+2]; /* Combined size of cells placed on i-th page */ - u8 *aSpace1; /* Space for copies of dividers cells */ - Pgno pgno; /* Temp var to store a page number in */ - u8 abDone[NB+2]; /* True after i'th new page is populated */ - Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */ - Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */ - u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */ - CellArray b; /* Parsed information on cells being balanced */ - - memset(abDone, 0, sizeof(abDone)); - b.nCell = 0; - b.apCell = 0; - pBt = pParent->pBt; - assert( sqlite3_mutex_held(pBt->mutex) ); - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); - - /* At this point pParent may have at most one overflow cell. And if - ** this overflow cell is present, it must be the cell with - ** index iParentIdx. This scenario comes about when this function - ** is called (indirectly) from sqlite3BtreeDelete(). - */ - assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); - assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); - - if( !aOvflSpace ){ - return SQLITE_NOMEM_BKPT; - } - assert( pParent->nFree>=0 ); - - /* Find the sibling pages to balance. Also locate the cells in pParent - ** that divide the siblings. An attempt is made to find NN siblings on - ** either side of pPage. More siblings are taken from one side, however, - ** if there are fewer than NN siblings on the other side. If pParent - ** has NB or fewer children then all children of pParent are taken. - ** - ** This loop also drops the divider cells from the parent page. This - ** way, the remainder of the function does not have to deal with any - ** overflow cells in the parent page, since if any existed they will - ** have already been removed. - */ - i = pParent->nOverflow + pParent->nCell; - if( i<2 ){ - nxDiv = 0; - }else{ - assert( bBulk==0 || bBulk==1 ); - if( iParentIdx==0 ){ - nxDiv = 0; - }else if( iParentIdx==i ){ - nxDiv = i-2+bBulk; - }else{ - nxDiv = iParentIdx-1; - } - i = 2-bBulk; - } - nOld = i+1; - if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ - pRight = &pParent->aData[pParent->hdrOffset+8]; - }else{ - pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); - } - pgno = get4byte(pRight); - while( 1 ){ - rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0); - if( rc ){ - memset(apOld, 0, (i+1)*sizeof(MemPage*)); - goto balance_cleanup; - } - if( apOld[i]->nFree<0 ){ - rc = btreeComputeFreeSpace(apOld[i]); - if( rc ){ - memset(apOld, 0, (i)*sizeof(MemPage*)); - goto balance_cleanup; - } - } - if( (i--)==0 ) break; - - if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){ - apDiv[i] = pParent->apOvfl[0]; - pgno = get4byte(apDiv[i]); - szNew[i] = pParent->xCellSize(pParent, apDiv[i]); - pParent->nOverflow = 0; - }else{ - apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); - pgno = get4byte(apDiv[i]); - szNew[i] = pParent->xCellSize(pParent, apDiv[i]); - - /* Drop the cell from the parent page. apDiv[i] still points to - ** the cell within the parent, even though it has been dropped. - ** This is safe because dropping a cell only overwrites the first - ** four bytes of it, and this function does not need the first - ** four bytes of the divider cell. So the pointer is safe to use - ** later on. - ** - ** But not if we are in secure-delete mode. In secure-delete mode, - ** the dropCell() routine will overwrite the entire cell with zeroes. - ** In this case, temporarily copy the cell into the aOvflSpace[] - ** buffer. It will be copied out again as soon as the aSpace[] buffer - ** is allocated. */ - if( pBt->btsFlags & BTS_FAST_SECURE ){ - int iOff; - - iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); - if( (iOff+szNew[i])>(int)pBt->usableSize ){ - rc = SQLITE_CORRUPT_BKPT; - memset(apOld, 0, (i+1)*sizeof(MemPage*)); - goto balance_cleanup; - }else{ - memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); - apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; - } - } - dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); - } - } - - /* Make nMaxCells a multiple of 4 in order to preserve 8-byte - ** alignment */ - nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl)); - nMaxCells = (nMaxCells + 3)&~3; - - /* - ** Allocate space for memory structures - */ - szScratch = - nMaxCells*sizeof(u8*) /* b.apCell */ - + nMaxCells*sizeof(u16) /* b.szCell */ - + pBt->pageSize; /* aSpace1 */ - - assert( szScratch<=7*(int)pBt->pageSize ); - b.apCell = sqlite3StackAllocRaw(0, szScratch ); - if( b.apCell==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto balance_cleanup; - } - b.szCell = (u16*)&b.apCell[nMaxCells]; - aSpace1 = (u8*)&b.szCell[nMaxCells]; - assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); - - /* - ** Load pointers to all cells on sibling pages and the divider cells - ** into the local b.apCell[] array. Make copies of the divider cells - ** into space obtained from aSpace1[]. The divider cells have already - ** been removed from pParent. - ** - ** If the siblings are on leaf pages, then the child pointers of the - ** divider cells are stripped from the cells before they are copied - ** into aSpace1[]. In this way, all cells in b.apCell[] are without - ** child pointers. If siblings are not leaves, then all cell in - ** b.apCell[] include child pointers. Either way, all cells in b.apCell[] - ** are alike. - ** - ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. - ** leafData: 1 if pPage holds key+data and pParent holds only keys. - */ - b.pRef = apOld[0]; - leafCorrection = b.pRef->leaf*4; - leafData = b.pRef->intKeyLeaf; - for(i=0; inCell; - u8 *aData = pOld->aData; - u16 maskPage = pOld->maskPage; - u8 *piCell = aData + pOld->cellOffset; - u8 *piEnd; - VVA_ONLY( int nCellAtStart = b.nCell; ) - - /* Verify that all sibling pages are of the same "type" (table-leaf, - ** table-interior, index-leaf, or index-interior). - */ - if( pOld->aData[0]!=apOld[0]->aData[0] ){ - rc = SQLITE_CORRUPT_BKPT; - goto balance_cleanup; - } - - /* Load b.apCell[] with pointers to all cells in pOld. If pOld - ** contains overflow cells, include them in the b.apCell[] array - ** in the correct spot. - ** - ** Note that when there are multiple overflow cells, it is always the - ** case that they are sequential and adjacent. This invariant arises - ** because multiple overflows can only occurs when inserting divider - ** cells into a parent on a prior balance, and divider cells are always - ** adjacent and are inserted in order. There is an assert() tagged - ** with "NOTE 1" in the overflow cell insertion loop to prove this - ** invariant. - ** - ** This must be done in advance. Once the balance starts, the cell - ** offset section of the btree page will be overwritten and we will no - ** long be able to find the cells if a pointer to each cell is not saved - ** first. - */ - memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow)); - if( pOld->nOverflow>0 ){ - if( NEVER(limitaiOvfl[0]) ){ - rc = SQLITE_CORRUPT_BKPT; - goto balance_cleanup; - } - limit = pOld->aiOvfl[0]; - for(j=0; jnOverflow; k++){ - assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */ - b.apCell[b.nCell] = pOld->apOvfl[k]; - b.nCell++; - } - } - piEnd = aData + pOld->cellOffset + 2*pOld->nCell; - while( piCellnCell+pOld->nOverflow) ); - - cntOld[i] = b.nCell; - if( imaxLocal+23 ); - assert( iSpace1 <= (int)pBt->pageSize ); - memcpy(pTemp, apDiv[i], sz); - b.apCell[b.nCell] = pTemp+leafCorrection; - assert( leafCorrection==0 || leafCorrection==4 ); - b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection; - if( !pOld->leaf ){ - assert( leafCorrection==0 ); - assert( pOld->hdrOffset==0 ); - /* The right pointer of the child page pOld becomes the left - ** pointer of the divider cell */ - memcpy(b.apCell[b.nCell], &pOld->aData[8], 4); - }else{ - assert( leafCorrection==4 ); - while( b.szCell[b.nCell]<4 ){ - /* Do not allow any cells smaller than 4 bytes. If a smaller cell - ** does exist, pad it with 0x00 bytes. */ - assert( b.szCell[b.nCell]==3 || CORRUPT_DB ); - assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB ); - aSpace1[iSpace1++] = 0x00; - b.szCell[b.nCell]++; - } - } - b.nCell++; - } - } - - /* - ** Figure out the number of pages needed to hold all b.nCell cells. - ** Store this number in "k". Also compute szNew[] which is the total - ** size of all cells on the i-th page and cntNew[] which is the index - ** in b.apCell[] of the cell that divides page i from page i+1. - ** cntNew[k] should equal b.nCell. - ** - ** Values computed by this block: - ** - ** k: The total number of sibling pages - ** szNew[i]: Spaced used on the i-th sibling page. - ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to - ** the right of the i-th sibling page. - ** usableSpace: Number of bytes of space available on each sibling. - ** - */ - usableSpace = pBt->usableSize - 12 + leafCorrection; - for(i=k=0; iaDataEnd; - b.ixNx[k] = cntOld[i]; - if( k && b.ixNx[k]==b.ixNx[k-1] ){ - k--; /* Omit b.ixNx[] entry for child pages with no cells */ - } - if( !leafData ){ - k++; - b.apEnd[k] = pParent->aDataEnd; - b.ixNx[k] = cntOld[i]+1; - } - assert( p->nFree>=0 ); - szNew[i] = usableSpace - p->nFree; - for(j=0; jnOverflow; j++){ - szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]); - } - cntNew[i] = cntOld[i]; - } - k = nOld; - for(i=0; iusableSpace ){ - if( i+1>=k ){ - k = i+2; - if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } - szNew[k-1] = 0; - cntNew[k-1] = b.nCell; - } - sz = 2 + cachedCellSize(&b, cntNew[i]-1); - szNew[i] -= sz; - if( !leafData ){ - if( cntNew[i]usableSpace ) break; - szNew[i] += sz; - cntNew[i]++; - if( !leafData ){ - if( cntNew[i]=b.nCell ){ - k = i+1; - }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){ - rc = SQLITE_CORRUPT_BKPT; - goto balance_cleanup; - } - } - - /* - ** The packing computed by the previous block is biased toward the siblings - ** on the left side (siblings with smaller keys). The left siblings are - ** always nearly full, while the right-most sibling might be nearly empty. - ** The next block of code attempts to adjust the packing of siblings to - ** get a better balance. - ** - ** This adjustment is more than an optimization. The packing above might - ** be so out of balance as to be illegal. For example, the right-most - ** sibling might be completely empty. This adjustment is not optional. - */ - for(i=k-1; i>0; i--){ - int szRight = szNew[i]; /* Size of sibling on the right */ - int szLeft = szNew[i-1]; /* Size of sibling on the left */ - int r; /* Index of right-most cell in left sibling */ - int d; /* Index of first cell to the left of right sibling */ - - r = cntNew[i-1] - 1; - d = r + 1 - leafData; - (void)cachedCellSize(&b, d); - do{ - assert( d szLeft-(b.szCell[r]+(i==k-1?0:2)))){ - break; - } - szRight += b.szCell[d] + 2; - szLeft -= b.szCell[r] + 2; - cntNew[i-1] = r; - r--; - d--; - }while( r>=0 ); - szNew[i] = szRight; - szNew[i-1] = szLeft; - if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){ - rc = SQLITE_CORRUPT_BKPT; - goto balance_cleanup; - } - } - - /* Sanity check: For a non-corrupt database file one of the follwing - ** must be true: - ** (1) We found one or more cells (cntNew[0])>0), or - ** (2) pPage is a virtual root page. A virtual root page is when - ** the real root page is page 1 and we are the only child of - ** that page. - */ - assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB); - TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n", - apOld[0]->pgno, apOld[0]->nCell, - nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0, - nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0 - )); - - /* - ** Allocate k new pages. Reuse old pages where possible. - */ - pageFlags = apOld[0]->aData[0]; - for(i=0; ipDbPage); - nNew++; - if( rc ) goto balance_cleanup; - }else{ - assert( i>0 ); - rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); - if( rc ) goto balance_cleanup; - zeroPage(pNew, pageFlags); - apNew[i] = pNew; - nNew++; - cntOld[i] = b.nCell; - - /* Set the pointer-map entry for the new sibling page. */ - if( ISAUTOVACUUM ){ - ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); - if( rc!=SQLITE_OK ){ - goto balance_cleanup; - } - } - } - } - - /* - ** Reassign page numbers so that the new pages are in ascending order. - ** This helps to keep entries in the disk file in order so that a scan - ** of the table is closer to a linear scan through the file. That in turn - ** helps the operating system to deliver pages from the disk more rapidly. - ** - ** An O(n^2) insertion sort algorithm is used, but since n is never more - ** than (NB+2) (a small constant), that should not be a problem. - ** - ** When NB==3, this one optimization makes the database about 25% faster - ** for large insertions and deletions. - */ - for(i=0; ipgno; - aPgFlags[i] = apNew[i]->pDbPage->flags; - for(j=0; ji ){ - sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0); - } - sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]); - apNew[i]->pgno = pgno; - } - } - - TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) " - "%d(%d nc=%d) %d(%d nc=%d)\n", - apNew[0]->pgno, szNew[0], cntNew[0], - nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0, - nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0, - nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0, - nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0, - nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0, - nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0, - nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0, - nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0 - )); - - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); - assert( nNew>=1 && nNew<=ArraySize(apNew) ); - assert( apNew[nNew-1]!=0 ); - put4byte(pRight, apNew[nNew-1]->pgno); - - /* If the sibling pages are not leaves, ensure that the right-child pointer - ** of the right-most new sibling page is set to the value that was - ** originally in the same field of the right-most old sibling page. */ - if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ - MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; - memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); - } - - /* Make any required updates to pointer map entries associated with - ** cells stored on sibling pages following the balance operation. Pointer - ** map entries associated with divider cells are set by the insertCell() - ** routine. The associated pointer map entries are: - ** - ** a) if the cell contains a reference to an overflow chain, the - ** entry associated with the first page in the overflow chain, and - ** - ** b) if the sibling pages are not leaves, the child page associated - ** with the cell. - ** - ** If the sibling pages are not leaves, then the pointer map entry - ** associated with the right-child of each sibling may also need to be - ** updated. This happens below, after the sibling pages have been - ** populated, not here. - */ - if( ISAUTOVACUUM ){ - MemPage *pOld; - MemPage *pNew = pOld = apNew[0]; - int cntOldNext = pNew->nCell + pNew->nOverflow; - int iNew = 0; - int iOld = 0; - - for(i=0; i=0 && iOldnCell + pOld->nOverflow + !leafData; - } - if( i==cntNew[iNew] ){ - pNew = apNew[++iNew]; - if( !leafData ) continue; - } - - /* Cell pCell is destined for new sibling page pNew. Originally, it - ** was either part of sibling page iOld (possibly an overflow cell), - ** or else the divider cell to the left of sibling page iOld. So, - ** if sibling page iOld had the same page number as pNew, and if - ** pCell really was a part of sibling page iOld (not a divider or - ** overflow cell), we can skip updating the pointer map entries. */ - if( iOld>=nNew - || pNew->pgno!=aPgno[iOld] - || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd) - ){ - if( !leafCorrection ){ - ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); - } - if( cachedCellSize(&b,i)>pNew->minLocal ){ - ptrmapPutOvflPtr(pNew, pOld, pCell, &rc); - } - if( rc ) goto balance_cleanup; - } - } - } - - /* Insert new divider cells into pParent. */ - for(i=0; ileaf ){ - memcpy(&pNew->aData[8], pCell, 4); - }else if( leafData ){ - /* If the tree is a leaf-data tree, and the siblings are leaves, - ** then there is no divider cell in b.apCell[]. Instead, the divider - ** cell consists of the integer key for the right-most cell of - ** the sibling-page assembled above only. - */ - CellInfo info; - j--; - pNew->xParseCell(pNew, b.apCell[j], &info); - pCell = pTemp; - sz = 4 + putVarint(&pCell[4], info.nKey); - pTemp = 0; - }else{ - pCell -= 4; - /* Obscure case for non-leaf-data trees: If the cell at pCell was - ** previously stored on a leaf node, and its reported size was 4 - ** bytes, then it may actually be smaller than this - ** (see btreeParseCellPtr(), 4 bytes is the minimum size of - ** any cell). But it is important to pass the correct size to - ** insertCell(), so reparse the cell now. - ** - ** This can only happen for b-trees used to evaluate "IN (SELECT ...)" - ** and WITHOUT ROWID tables with exactly one column which is the - ** primary key. - */ - if( b.szCell[j]==4 ){ - assert(leafCorrection==4); - sz = pParent->xCellSize(pParent, pCell); - } - } - iOvflSpace += sz; - assert( sz<=pBt->maxLocal+23 ); - assert( iOvflSpace <= (int)pBt->pageSize ); - insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc); - if( rc!=SQLITE_OK ) goto balance_cleanup; - assert( sqlite3PagerIswriteable(pParent->pDbPage) ); - } - - /* Now update the actual sibling pages. The order in which they are updated - ** is important, as this code needs to avoid disrupting any page from which - ** cells may still to be read. In practice, this means: - ** - ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1]) - ** then it is not safe to update page apNew[iPg] until after - ** the left-hand sibling apNew[iPg-1] has been updated. - ** - ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1]) - ** then it is not safe to update page apNew[iPg] until after - ** the right-hand sibling apNew[iPg+1] has been updated. - ** - ** If neither of the above apply, the page is safe to update. - ** - ** The iPg value in the following loop starts at nNew-1 goes down - ** to 0, then back up to nNew-1 again, thus making two passes over - ** the pages. On the initial downward pass, only condition (1) above - ** needs to be tested because (2) will always be true from the previous - ** step. On the upward pass, both conditions are always true, so the - ** upwards pass simply processes pages that were missed on the downward - ** pass. - */ - for(i=1-nNew; i=0 && iPg=0 /* On the upwards pass, or... */ - || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */ - ){ - int iNew; - int iOld; - int nNewCell; - - /* Verify condition (1): If cells are moving left, update iPg - ** only after iPg-1 has already been updated. */ - assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] ); - - /* Verify condition (2): If cells are moving right, update iPg - ** only after iPg+1 has already been updated. */ - assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] ); - - if( iPg==0 ){ - iNew = iOld = 0; - nNewCell = cntNew[0]; - }else{ - iOld = iPgnFree = usableSpace-szNew[iPg]; - assert( apNew[iPg]->nOverflow==0 ); - assert( apNew[iPg]->nCell==nNewCell ); - } - } - - /* All pages have been processed exactly once */ - assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 ); - - assert( nOld>0 ); - assert( nNew>0 ); - - if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){ - /* The root page of the b-tree now contains no cells. The only sibling - ** page is the right-child of the parent. Copy the contents of the - ** child page into the parent, decreasing the overall height of the - ** b-tree structure by one. This is described as the "balance-shallower" - ** sub-algorithm in some documentation. - ** - ** If this is an auto-vacuum database, the call to copyNodeContent() - ** sets all pointer-map entries corresponding to database image pages - ** for which the pointer is stored within the content being copied. - ** - ** It is critical that the child page be defragmented before being - ** copied into the parent, because if the parent is page 1 then it will - ** by smaller than the child due to the database header, and so all the - ** free space needs to be up front. - */ - assert( nNew==1 || CORRUPT_DB ); - rc = defragmentPage(apNew[0], -1); - testcase( rc!=SQLITE_OK ); - assert( apNew[0]->nFree == - (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset - - apNew[0]->nCell*2) - || rc!=SQLITE_OK - ); - copyNodeContent(apNew[0], pParent, &rc); - freePage(apNew[0], &rc); - }else if( ISAUTOVACUUM && !leafCorrection ){ - /* Fix the pointer map entries associated with the right-child of each - ** sibling page. All other pointer map entries have already been taken - ** care of. */ - for(i=0; iaData[8]); - ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc); - } - } - - assert( pParent->isInit ); - TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n", - nOld, nNew, b.nCell)); - - /* Free any old pages that were not reused as new pages. - */ - for(i=nNew; iisInit ){ - /* The ptrmapCheckPages() contains assert() statements that verify that - ** all pointer map pages are set correctly. This is helpful while - ** debugging. This is usually disabled because a corrupt database may - ** cause an assert() statement to fail. */ - ptrmapCheckPages(apNew, nNew); - ptrmapCheckPages(&pParent, 1); - } -#endif - - /* - ** Cleanup before returning. - */ -balance_cleanup: - sqlite3StackFree(0, b.apCell); - for(i=0; ipBt; /* The BTree */ - - assert( pRoot->nOverflow>0 ); - assert( sqlite3_mutex_held(pBt->mutex) ); - - /* Make pRoot, the root page of the b-tree, writable. Allocate a new - ** page that will become the new right-child of pPage. Copy the contents - ** of the node stored on pRoot into the new child page. - */ - rc = sqlite3PagerWrite(pRoot->pDbPage); - if( rc==SQLITE_OK ){ - rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0); - copyNodeContent(pRoot, pChild, &rc); - if( ISAUTOVACUUM ){ - ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc); - } - } - if( rc ){ - *ppChild = 0; - releasePage(pChild); - return rc; - } - assert( sqlite3PagerIswriteable(pChild->pDbPage) ); - assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); - assert( pChild->nCell==pRoot->nCell || CORRUPT_DB ); - - TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); - - /* Copy the overflow cells from pRoot to pChild */ - memcpy(pChild->aiOvfl, pRoot->aiOvfl, - pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); - memcpy(pChild->apOvfl, pRoot->apOvfl, - pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); - pChild->nOverflow = pRoot->nOverflow; - - /* Zero the contents of pRoot. Then install pChild as the right-child. */ - zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); - put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); - - *ppChild = pChild; - return SQLITE_OK; -} - -/* -** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid -** on the same B-tree as pCur. -** -** This can if a database is corrupt with two or more SQL tables -** pointing to the same b-tree. If an insert occurs on one SQL table -** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL -** table linked to the same b-tree. If the secondary insert causes a -** rebalance, that can change content out from under the cursor on the -** first SQL table, violating invariants on the first insert. -*/ -static int anotherValidCursor(BtCursor *pCur){ - BtCursor *pOther; - for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){ - if( pOther!=pCur - && pOther->eState==CURSOR_VALID - && pOther->pPage==pCur->pPage - ){ - return SQLITE_CORRUPT_BKPT; - } - } - return SQLITE_OK; -} - -/* -** The page that pCur currently points to has just been modified in -** some way. This function figures out if this modification means the -** tree needs to be balanced, and if so calls the appropriate balancing -** routine. Balancing routines are: -** -** balance_quick() -** balance_deeper() -** balance_nonroot() -*/ -static int balance(BtCursor *pCur){ - int rc = SQLITE_OK; - const int nMin = pCur->pBt->usableSize * 2 / 3; - u8 aBalanceQuickSpace[13]; - u8 *pFree = 0; - - VVA_ONLY( int balance_quick_called = 0 ); - VVA_ONLY( int balance_deeper_called = 0 ); - - do { - int iPage; - MemPage *pPage = pCur->pPage; - - if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break; - if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ - break; - }else if( (iPage = pCur->iPage)==0 ){ - if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){ - /* The root page of the b-tree is overfull. In this case call the - ** balance_deeper() function to create a new child for the root-page - ** and copy the current contents of the root-page to it. The - ** next iteration of the do-loop will balance the child page. - */ - assert( balance_deeper_called==0 ); - VVA_ONLY( balance_deeper_called++ ); - rc = balance_deeper(pPage, &pCur->apPage[1]); - if( rc==SQLITE_OK ){ - pCur->iPage = 1; - pCur->ix = 0; - pCur->aiIdx[0] = 0; - pCur->apPage[0] = pPage; - pCur->pPage = pCur->apPage[1]; - assert( pCur->pPage->nOverflow ); - } - }else{ - break; - } - }else{ - MemPage * const pParent = pCur->apPage[iPage-1]; - int const iIdx = pCur->aiIdx[iPage-1]; - - rc = sqlite3PagerWrite(pParent->pDbPage); - if( rc==SQLITE_OK && pParent->nFree<0 ){ - rc = btreeComputeFreeSpace(pParent); - } - if( rc==SQLITE_OK ){ -#ifndef SQLITE_OMIT_QUICKBALANCE - if( pPage->intKeyLeaf - && pPage->nOverflow==1 - && pPage->aiOvfl[0]==pPage->nCell - && pParent->pgno!=1 - && pParent->nCell==iIdx - ){ - /* Call balance_quick() to create a new sibling of pPage on which - ** to store the overflow cell. balance_quick() inserts a new cell - ** into pParent, which may cause pParent overflow. If this - ** happens, the next iteration of the do-loop will balance pParent - ** use either balance_nonroot() or balance_deeper(). Until this - ** happens, the overflow cell is stored in the aBalanceQuickSpace[] - ** buffer. - ** - ** The purpose of the following assert() is to check that only a - ** single call to balance_quick() is made for each call to this - ** function. If this were not verified, a subtle bug involving reuse - ** of the aBalanceQuickSpace[] might sneak in. - */ - assert( balance_quick_called==0 ); - VVA_ONLY( balance_quick_called++ ); - rc = balance_quick(pParent, pPage, aBalanceQuickSpace); - }else -#endif - { - /* In this case, call balance_nonroot() to redistribute cells - ** between pPage and up to 2 of its sibling pages. This involves - ** modifying the contents of pParent, which may cause pParent to - ** become overfull or underfull. The next iteration of the do-loop - ** will balance the parent page to correct this. - ** - ** If the parent page becomes overfull, the overflow cell or cells - ** are stored in the pSpace buffer allocated immediately below. - ** A subsequent iteration of the do-loop will deal with this by - ** calling balance_nonroot() (balance_deeper() may be called first, - ** but it doesn't deal with overflow cells - just moves them to a - ** different page). Once this subsequent call to balance_nonroot() - ** has completed, it is safe to release the pSpace buffer used by - ** the previous call, as the overflow cell data will have been - ** copied either into the body of a database page or into the new - ** pSpace buffer passed to the latter call to balance_nonroot(). - */ - u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); - rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, - pCur->hints&BTREE_BULKLOAD); - if( pFree ){ - /* If pFree is not NULL, it points to the pSpace buffer used - ** by a previous call to balance_nonroot(). Its contents are - ** now stored either on real database pages or within the - ** new pSpace buffer, so it may be safely freed here. */ - sqlite3PageFree(pFree); - } - - /* The pSpace buffer will be freed after the next call to - ** balance_nonroot(), or just before this function returns, whichever - ** comes first. */ - pFree = pSpace; - } - } - - pPage->nOverflow = 0; - - /* The next iteration of the do-loop balances the parent page. */ - releasePage(pPage); - pCur->iPage--; - assert( pCur->iPage>=0 ); - pCur->pPage = pCur->apPage[pCur->iPage]; - } - }while( rc==SQLITE_OK ); - - if( pFree ){ - sqlite3PageFree(pFree); - } - return rc; -} - -/* Overwrite content from pX into pDest. Only do the write if the -** content is different from what is already there. -*/ -static int btreeOverwriteContent( - MemPage *pPage, /* MemPage on which writing will occur */ - u8 *pDest, /* Pointer to the place to start writing */ - const BtreePayload *pX, /* Source of data to write */ - int iOffset, /* Offset of first byte to write */ - int iAmt /* Number of bytes to be written */ -){ - int nData = pX->nData - iOffset; - if( nData<=0 ){ - /* Overwritting with zeros */ - int i; - for(i=0; ipDbPage); - if( rc ) return rc; - memset(pDest + i, 0, iAmt - i); - } - }else{ - if( nDatapData) + iOffset, iAmt)!=0 ){ - int rc = sqlite3PagerWrite(pPage->pDbPage); - if( rc ) return rc; - /* In a corrupt database, it is possible for the source and destination - ** buffers to overlap. This is harmless since the database is already - ** corrupt but it does cause valgrind and ASAN warnings. So use - ** memmove(). */ - memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt); - } - } - return SQLITE_OK; -} - -/* -** Overwrite the cell that cursor pCur is pointing to with fresh content -** contained in pX. -*/ -static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){ - int iOffset; /* Next byte of pX->pData to write */ - int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */ - int rc; /* Return code */ - MemPage *pPage = pCur->pPage; /* Page being written */ - BtShared *pBt; /* Btree */ - Pgno ovflPgno; /* Next overflow page to write */ - u32 ovflPageSize; /* Size to write on overflow page */ - - if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd - || pCur->info.pPayload < pPage->aData + pPage->cellOffset - ){ - return SQLITE_CORRUPT_BKPT; - } - /* Overwrite the local portion first */ - rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX, - 0, pCur->info.nLocal); - if( rc ) return rc; - if( pCur->info.nLocal==nTotal ) return SQLITE_OK; - - /* Now overwrite the overflow pages */ - iOffset = pCur->info.nLocal; - assert( nTotal>=0 ); - assert( iOffset>=0 ); - ovflPgno = get4byte(pCur->info.pPayload + iOffset); - pBt = pPage->pBt; - ovflPageSize = pBt->usableSize - 4; - do{ - rc = btreeGetPage(pBt, ovflPgno, &pPage, 0); - if( rc ) return rc; - if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){ - rc = SQLITE_CORRUPT_BKPT; - }else{ - if( iOffset+ovflPageSize<(u32)nTotal ){ - ovflPgno = get4byte(pPage->aData); - }else{ - ovflPageSize = nTotal - iOffset; - } - rc = btreeOverwriteContent(pPage, pPage->aData+4, pX, - iOffset, ovflPageSize); - } - sqlite3PagerUnref(pPage->pDbPage); - if( rc ) return rc; - iOffset += ovflPageSize; - }while( iOffset0 then pCur points to a cell -** that is larger than (pKey,nKey). -** -** If seekResult==0, that means pCur is pointing at some unknown location. -** In that case, this routine must seek the cursor to the correct insertion -** point for (pKey,nKey) before doing the insertion. For index btrees, -** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked -** key values and pX->aMem can be used instead of pX->pKey to avoid having -** to decode the key. -*/ -SQLITE_PRIVATE int sqlite3BtreeInsert( - BtCursor *pCur, /* Insert data into the table of this cursor */ - const BtreePayload *pX, /* Content of the row to be inserted */ - int flags, /* True if this is likely an append */ - int seekResult /* Result of prior MovetoUnpacked() call */ -){ - int rc; - int loc = seekResult; /* -1: before desired location +1: after */ - int szNew = 0; - int idx; - MemPage *pPage; - Btree *p = pCur->pBtree; - BtShared *pBt = p->pBt; - unsigned char *oldCell; - unsigned char *newCell = 0; - - assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags ); - - if( pCur->eState==CURSOR_FAULT ){ - assert( pCur->skipNext!=SQLITE_OK ); - return pCur->skipNext; - } - - assert( cursorOwnsBtShared(pCur) ); - assert( (pCur->curFlags & BTCF_WriteFlag)!=0 - && pBt->inTransaction==TRANS_WRITE - && (pBt->btsFlags & BTS_READ_ONLY)==0 ); - assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); - - /* Assert that the caller has been consistent. If this cursor was opened - ** expecting an index b-tree, then the caller should be inserting blob - ** keys with no associated data. If the cursor was opened expecting an - ** intkey table, the caller should be inserting integer keys with a - ** blob of associated data. */ - assert( (pX->pKey==0)==(pCur->pKeyInfo==0) ); - - /* Save the positions of any other cursors open on this table. - ** - ** In some cases, the call to btreeMoveto() below is a no-op. For - ** example, when inserting data into a table with auto-generated integer - ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the - ** integer key to use. It then calls this function to actually insert the - ** data into the intkey B-Tree. In this case btreeMoveto() recognizes - ** that the cursor is already where it needs to be and returns without - ** doing any work. To avoid thwarting these optimizations, it is important - ** not to clear the cursor here. - */ - if( pCur->curFlags & BTCF_Multiple ){ - rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); - if( rc ) return rc; - } - - if( pCur->pKeyInfo==0 ){ - assert( pX->pKey==0 ); - /* If this is an insert into a table b-tree, invalidate any incrblob - ** cursors open on the row being replaced */ - invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0); - - /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing - ** to a row with the same key as the new entry being inserted. - */ -#ifdef SQLITE_DEBUG - if( flags & BTREE_SAVEPOSITION ){ - assert( pCur->curFlags & BTCF_ValidNKey ); - assert( pX->nKey==pCur->info.nKey ); - assert( loc==0 ); - } -#endif - - /* On the other hand, BTREE_SAVEPOSITION==0 does not imply - ** that the cursor is not pointing to a row to be overwritten. - ** So do a complete check. - */ - if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){ - /* The cursor is pointing to the entry that is to be - ** overwritten */ - assert( pX->nData>=0 && pX->nZero>=0 ); - if( pCur->info.nSize!=0 - && pCur->info.nPayload==(u32)pX->nData+pX->nZero - ){ - /* New entry is the same size as the old. Do an overwrite */ - return btreeOverwriteCell(pCur, pX); - } - assert( loc==0 ); - }else if( loc==0 ){ - /* The cursor is *not* pointing to the cell to be overwritten, nor - ** to an adjacent cell. Move the cursor so that it is pointing either - ** to the cell to be overwritten or an adjacent cell. - */ - rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc); - if( rc ) return rc; - } - }else{ - /* This is an index or a WITHOUT ROWID table */ - - /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing - ** to a row with the same key as the new entry being inserted. - */ - assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 ); - - /* If the cursor is not already pointing either to the cell to be - ** overwritten, or if a new cell is being inserted, if the cursor is - ** not pointing to an immediately adjacent cell, then move the cursor - ** so that it does. - */ - if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){ - if( pX->nMem ){ - UnpackedRecord r; - r.pKeyInfo = pCur->pKeyInfo; - r.aMem = pX->aMem; - r.nField = pX->nMem; - r.default_rc = 0; - r.errCode = 0; - r.r1 = 0; - r.r2 = 0; - r.eqSeen = 0; - rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc); - }else{ - rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc); - } - if( rc ) return rc; - } - - /* If the cursor is currently pointing to an entry to be overwritten - ** and the new content is the same as as the old, then use the - ** overwrite optimization. - */ - if( loc==0 ){ - getCellInfo(pCur); - if( pCur->info.nKey==pX->nKey ){ - BtreePayload x2; - x2.pData = pX->pKey; - x2.nData = pX->nKey; - x2.nZero = 0; - return btreeOverwriteCell(pCur, &x2); - } - } - - } - assert( pCur->eState==CURSOR_VALID - || (pCur->eState==CURSOR_INVALID && loc) - || CORRUPT_DB ); - - pPage = pCur->pPage; - assert( pPage->intKey || pX->nKey>=0 ); - assert( pPage->leaf || !pPage->intKey ); - if( pPage->nFree<0 ){ - if( pCur->eState>CURSOR_INVALID ){ - rc = SQLITE_CORRUPT_BKPT; - }else{ - rc = btreeComputeFreeSpace(pPage); - } - if( rc ) return rc; - } - - TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", - pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno, - loc==0 ? "overwrite" : "new entry")); - assert( pPage->isInit ); - newCell = pBt->pTmpSpace; - assert( newCell!=0 ); - rc = fillInCell(pPage, newCell, pX, &szNew); - if( rc ) goto end_insert; - assert( szNew==pPage->xCellSize(pPage, newCell) ); - assert( szNew <= MX_CELL_SIZE(pBt) ); - idx = pCur->ix; - if( loc==0 ){ - CellInfo info; - assert( idxnCell ); - rc = sqlite3PagerWrite(pPage->pDbPage); - if( rc ){ - goto end_insert; - } - oldCell = findCell(pPage, idx); - if( !pPage->leaf ){ - memcpy(newCell, oldCell, 4); - } - rc = clearCell(pPage, oldCell, &info); - testcase( pCur->curFlags & BTCF_ValidOvfl ); - invalidateOverflowCache(pCur); - if( info.nSize==szNew && info.nLocal==info.nPayload - && (!ISAUTOVACUUM || szNewminLocal) - ){ - /* Overwrite the old cell with the new if they are the same size. - ** We could also try to do this if the old cell is smaller, then add - ** the leftover space to the free list. But experiments show that - ** doing that is no faster then skipping this optimization and just - ** calling dropCell() and insertCell(). - ** - ** This optimization cannot be used on an autovacuum database if the - ** new entry uses overflow pages, as the insertCell() call below is - ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */ - assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */ - if( oldCell < pPage->aData+pPage->hdrOffset+10 ){ - return SQLITE_CORRUPT_BKPT; - } - if( oldCell+szNew > pPage->aDataEnd ){ - return SQLITE_CORRUPT_BKPT; - } - memcpy(oldCell, newCell, szNew); - return SQLITE_OK; - } - dropCell(pPage, idx, info.nSize, &rc); - if( rc ) goto end_insert; - }else if( loc<0 && pPage->nCell>0 ){ - assert( pPage->leaf ); - idx = ++pCur->ix; - pCur->curFlags &= ~BTCF_ValidNKey; - }else{ - assert( pPage->leaf ); - } - insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); - assert( pPage->nOverflow==0 || rc==SQLITE_OK ); - assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); - - /* If no error has occurred and pPage has an overflow cell, call balance() - ** to redistribute the cells within the tree. Since balance() may move - ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey - ** variables. - ** - ** Previous versions of SQLite called moveToRoot() to move the cursor - ** back to the root page as balance() used to invalidate the contents - ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, - ** set the cursor state to "invalid". This makes common insert operations - ** slightly faster. - ** - ** There is a subtle but important optimization here too. When inserting - ** multiple records into an intkey b-tree using a single cursor (as can - ** happen while processing an "INSERT INTO ... SELECT" statement), it - ** is advantageous to leave the cursor pointing to the last entry in - ** the b-tree if possible. If the cursor is left pointing to the last - ** entry in the table, and the next row inserted has an integer key - ** larger than the largest existing key, it is possible to insert the - ** row without seeking the cursor. This can be a big performance boost. - */ - pCur->info.nSize = 0; - if( pPage->nOverflow ){ - assert( rc==SQLITE_OK ); - pCur->curFlags &= ~(BTCF_ValidNKey); - rc = balance(pCur); - - /* Must make sure nOverflow is reset to zero even if the balance() - ** fails. Internal data structure corruption will result otherwise. - ** Also, set the cursor state to invalid. This stops saveCursorPosition() - ** from trying to save the current position of the cursor. */ - pCur->pPage->nOverflow = 0; - pCur->eState = CURSOR_INVALID; - if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){ - btreeReleaseAllCursorPages(pCur); - if( pCur->pKeyInfo ){ - assert( pCur->pKey==0 ); - pCur->pKey = sqlite3Malloc( pX->nKey ); - if( pCur->pKey==0 ){ - rc = SQLITE_NOMEM; - }else{ - memcpy(pCur->pKey, pX->pKey, pX->nKey); - } - } - pCur->eState = CURSOR_REQUIRESEEK; - pCur->nKey = pX->nKey; - } - } - assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 ); - -end_insert: - return rc; -} - -/* -** Delete the entry that the cursor is pointing to. -** -** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then -** the cursor is left pointing at an arbitrary location after the delete. -** But if that bit is set, then the cursor is left in a state such that -** the next call to BtreeNext() or BtreePrev() moves it to the same row -** as it would have been on if the call to BtreeDelete() had been omitted. -** -** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes -** associated with a single table entry and its indexes. Only one of those -** deletes is considered the "primary" delete. The primary delete occurs -** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete -** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag. -** The BTREE_AUXDELETE bit is a hint that is not used by this implementation, -** but which might be used by alternative storage engines. -*/ -SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ - Btree *p = pCur->pBtree; - BtShared *pBt = p->pBt; - int rc; /* Return code */ - MemPage *pPage; /* Page to delete cell from */ - unsigned char *pCell; /* Pointer to cell to delete */ - int iCellIdx; /* Index of cell to delete */ - int iCellDepth; /* Depth of node containing pCell */ - CellInfo info; /* Size of the cell being deleted */ - int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */ - u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */ - - assert( cursorOwnsBtShared(pCur) ); - assert( pBt->inTransaction==TRANS_WRITE ); - assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); - assert( pCur->curFlags & BTCF_WriteFlag ); - assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); - assert( !hasReadConflicts(p, pCur->pgnoRoot) ); - assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 ); - if( pCur->eState==CURSOR_REQUIRESEEK ){ - rc = btreeRestoreCursorPosition(pCur); - if( rc ) return rc; - } - assert( pCur->eState==CURSOR_VALID ); - - iCellDepth = pCur->iPage; - iCellIdx = pCur->ix; - pPage = pCur->pPage; - pCell = findCell(pPage, iCellIdx); - if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT; - - /* If the bPreserve flag is set to true, then the cursor position must - ** be preserved following this delete operation. If the current delete - ** will cause a b-tree rebalance, then this is done by saving the cursor - ** key and leaving the cursor in CURSOR_REQUIRESEEK state before - ** returning. - ** - ** Or, if the current delete will not cause a rebalance, then the cursor - ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately - ** before or after the deleted entry. In this case set bSkipnext to true. */ - if( bPreserve ){ - if( !pPage->leaf - || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3) - || pPage->nCell==1 /* See dbfuzz001.test for a test case */ - ){ - /* A b-tree rebalance will be required after deleting this entry. - ** Save the cursor key. */ - rc = saveCursorKey(pCur); - if( rc ) return rc; - }else{ - bSkipnext = 1; - } - } - - /* If the page containing the entry to delete is not a leaf page, move - ** the cursor to the largest entry in the tree that is smaller than - ** the entry being deleted. This cell will replace the cell being deleted - ** from the internal node. The 'previous' entry is used for this instead - ** of the 'next' entry, as the previous entry is always a part of the - ** sub-tree headed by the child page of the cell being deleted. This makes - ** balancing the tree following the delete operation easier. */ - if( !pPage->leaf ){ - rc = sqlite3BtreePrevious(pCur, 0); - assert( rc!=SQLITE_DONE ); - if( rc ) return rc; - } - - /* Save the positions of any other cursors open on this table before - ** making any modifications. */ - if( pCur->curFlags & BTCF_Multiple ){ - rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); - if( rc ) return rc; - } - - /* If this is a delete operation to remove a row from a table b-tree, - ** invalidate any incrblob cursors open on the row being deleted. */ - if( pCur->pKeyInfo==0 ){ - invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0); - } - - /* Make the page containing the entry to be deleted writable. Then free any - ** overflow pages associated with the entry and finally remove the cell - ** itself from within the page. */ - rc = sqlite3PagerWrite(pPage->pDbPage); - if( rc ) return rc; - rc = clearCell(pPage, pCell, &info); - dropCell(pPage, iCellIdx, info.nSize, &rc); - if( rc ) return rc; - - /* If the cell deleted was not located on a leaf page, then the cursor - ** is currently pointing to the largest entry in the sub-tree headed - ** by the child-page of the cell that was just deleted from an internal - ** node. The cell from the leaf node needs to be moved to the internal - ** node to replace the deleted cell. */ - if( !pPage->leaf ){ - MemPage *pLeaf = pCur->pPage; - int nCell; - Pgno n; - unsigned char *pTmp; - - if( pLeaf->nFree<0 ){ - rc = btreeComputeFreeSpace(pLeaf); - if( rc ) return rc; - } - if( iCellDepthiPage-1 ){ - n = pCur->apPage[iCellDepth+1]->pgno; - }else{ - n = pCur->pPage->pgno; - } - pCell = findCell(pLeaf, pLeaf->nCell-1); - if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT; - nCell = pLeaf->xCellSize(pLeaf, pCell); - assert( MX_CELL_SIZE(pBt) >= nCell ); - pTmp = pBt->pTmpSpace; - assert( pTmp!=0 ); - rc = sqlite3PagerWrite(pLeaf->pDbPage); - if( rc==SQLITE_OK ){ - insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); - } - dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); - if( rc ) return rc; - } - - /* Balance the tree. If the entry deleted was located on a leaf page, - ** then the cursor still points to that page. In this case the first - ** call to balance() repairs the tree, and the if(...) condition is - ** never true. - ** - ** Otherwise, if the entry deleted was on an internal node page, then - ** pCur is pointing to the leaf page from which a cell was removed to - ** replace the cell deleted from the internal node. This is slightly - ** tricky as the leaf node may be underfull, and the internal node may - ** be either under or overfull. In this case run the balancing algorithm - ** on the leaf node first. If the balance proceeds far enough up the - ** tree that we can be sure that any problem in the internal node has - ** been corrected, so be it. Otherwise, after balancing the leaf node, - ** walk the cursor up the tree to the internal node and balance it as - ** well. */ - rc = balance(pCur); - if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){ - releasePageNotNull(pCur->pPage); - pCur->iPage--; - while( pCur->iPage>iCellDepth ){ - releasePage(pCur->apPage[pCur->iPage--]); - } - pCur->pPage = pCur->apPage[pCur->iPage]; - rc = balance(pCur); - } - - if( rc==SQLITE_OK ){ - if( bSkipnext ){ - assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) ); - assert( pPage==pCur->pPage || CORRUPT_DB ); - assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell ); - pCur->eState = CURSOR_SKIPNEXT; - if( iCellIdx>=pPage->nCell ){ - pCur->skipNext = -1; - pCur->ix = pPage->nCell-1; - }else{ - pCur->skipNext = 1; - } - }else{ - rc = moveToRoot(pCur); - if( bPreserve ){ - btreeReleaseAllCursorPages(pCur); - pCur->eState = CURSOR_REQUIRESEEK; - } - if( rc==SQLITE_EMPTY ) rc = SQLITE_OK; - } - } - return rc; -} - -/* -** Create a new BTree table. Write into *piTable the page -** number for the root page of the new table. -** -** The type of type is determined by the flags parameter. Only the -** following values of flags are currently in use. Other values for -** flags might not work: -** -** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys -** BTREE_ZERODATA Used for SQL indices -*/ -static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){ - BtShared *pBt = p->pBt; - MemPage *pRoot; - Pgno pgnoRoot; - int rc; - int ptfFlags; /* Page-type flage for the root page of new table */ - - assert( sqlite3BtreeHoldsMutex(p) ); - assert( pBt->inTransaction==TRANS_WRITE ); - assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); - -#ifdef SQLITE_OMIT_AUTOVACUUM - rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); - if( rc ){ - return rc; - } -#else - if( pBt->autoVacuum ){ - Pgno pgnoMove; /* Move a page here to make room for the root-page */ - MemPage *pPageMove; /* The page to move to. */ - - /* Creating a new table may probably require moving an existing database - ** to make room for the new tables root page. In case this page turns - ** out to be an overflow page, delete all overflow page-map caches - ** held by open cursors. - */ - invalidateAllOverflowCache(pBt); - - /* Read the value of meta[3] from the database to determine where the - ** root page of the new table should go. meta[3] is the largest root-page - ** created so far, so the new root-page is (meta[3]+1). - */ - sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot); - if( pgnoRoot>btreePagecount(pBt) ){ - return SQLITE_CORRUPT_BKPT; - } - pgnoRoot++; - - /* The new root-page may not be allocated on a pointer-map page, or the - ** PENDING_BYTE page. - */ - while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || - pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ - pgnoRoot++; - } - assert( pgnoRoot>=3 ); - - /* Allocate a page. The page that currently resides at pgnoRoot will - ** be moved to the allocated page (unless the allocated page happens - ** to reside at pgnoRoot). - */ - rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); - if( rc!=SQLITE_OK ){ - return rc; - } - - if( pgnoMove!=pgnoRoot ){ - /* pgnoRoot is the page that will be used for the root-page of - ** the new table (assuming an error did not occur). But we were - ** allocated pgnoMove. If required (i.e. if it was not allocated - ** by extending the file), the current page at position pgnoMove - ** is already journaled. - */ - u8 eType = 0; - Pgno iPtrPage = 0; - - /* Save the positions of any open cursors. This is required in - ** case they are holding a reference to an xFetch reference - ** corresponding to page pgnoRoot. */ - rc = saveAllCursors(pBt, 0, 0); - releasePage(pPageMove); - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Move the page currently at pgnoRoot to pgnoMove. */ - rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); - if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ - rc = SQLITE_CORRUPT_BKPT; - } - if( rc!=SQLITE_OK ){ - releasePage(pRoot); - return rc; - } - assert( eType!=PTRMAP_ROOTPAGE ); - assert( eType!=PTRMAP_FREEPAGE ); - rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0); - releasePage(pRoot); - - /* Obtain the page at pgnoRoot */ - if( rc!=SQLITE_OK ){ - return rc; - } - rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - rc = sqlite3PagerWrite(pRoot->pDbPage); - if( rc!=SQLITE_OK ){ - releasePage(pRoot); - return rc; - } - }else{ - pRoot = pPageMove; - } - - /* Update the pointer-map and meta-data with the new root-page number. */ - ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc); - if( rc ){ - releasePage(pRoot); - return rc; - } - - /* When the new root page was allocated, page 1 was made writable in - ** order either to increase the database filesize, or to decrement the - ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail. - */ - assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) ); - rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); - if( NEVER(rc) ){ - releasePage(pRoot); - return rc; - } - - }else{ - rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); - if( rc ) return rc; - } -#endif - assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); - if( createTabFlags & BTREE_INTKEY ){ - ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF; - }else{ - ptfFlags = PTF_ZERODATA | PTF_LEAF; - } - zeroPage(pRoot, ptfFlags); - sqlite3PagerUnref(pRoot->pDbPage); - assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 ); - *piTable = pgnoRoot; - return SQLITE_OK; -} -SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){ - int rc; - sqlite3BtreeEnter(p); - rc = btreeCreateTable(p, piTable, flags); - sqlite3BtreeLeave(p); - return rc; -} - -/* -** Erase the given database page and all its children. Return -** the page to the freelist. -*/ -static int clearDatabasePage( - BtShared *pBt, /* The BTree that contains the table */ - Pgno pgno, /* Page number to clear */ - int freePageFlag, /* Deallocate page if true */ - int *pnChange /* Add number of Cells freed to this counter */ -){ - MemPage *pPage; - int rc; - unsigned char *pCell; - int i; - int hdr; - CellInfo info; - - assert( sqlite3_mutex_held(pBt->mutex) ); - if( pgno>btreePagecount(pBt) ){ - return SQLITE_CORRUPT_BKPT; - } - rc = getAndInitPage(pBt, pgno, &pPage, 0, 0); - if( rc ) return rc; - if( pPage->bBusy ){ - rc = SQLITE_CORRUPT_BKPT; - goto cleardatabasepage_out; - } - pPage->bBusy = 1; - hdr = pPage->hdrOffset; - for(i=0; inCell; i++){ - pCell = findCell(pPage, i); - if( !pPage->leaf ){ - rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); - if( rc ) goto cleardatabasepage_out; - } - rc = clearCell(pPage, pCell, &info); - if( rc ) goto cleardatabasepage_out; - } - if( !pPage->leaf ){ - rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); - if( rc ) goto cleardatabasepage_out; - }else if( pnChange ){ - assert( pPage->intKey || CORRUPT_DB ); - testcase( !pPage->intKey ); - *pnChange += pPage->nCell; - } - if( freePageFlag ){ - freePage(pPage, &rc); - }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ - zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); - } - -cleardatabasepage_out: - pPage->bBusy = 0; - releasePage(pPage); - return rc; -} - -/* -** Delete all information from a single table in the database. iTable is -** the page number of the root of the table. After this routine returns, -** the root page is empty, but still exists. -** -** This routine will fail with SQLITE_LOCKED if there are any open -** read cursors on the table. Open write cursors are moved to the -** root of the table. -** -** If pnChange is not NULL, then table iTable must be an intkey table. The -** integer value pointed to by pnChange is incremented by the number of -** entries in the table. -*/ -SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ - int rc; - BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); - assert( p->inTrans==TRANS_WRITE ); - - rc = saveAllCursors(pBt, (Pgno)iTable, 0); - - if( SQLITE_OK==rc ){ - /* Invalidate all incrblob cursors open on table iTable (assuming iTable - ** is the root of a table b-tree - if it is not, the following call is - ** a no-op). */ - invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1); - rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); - } - sqlite3BtreeLeave(p); - return rc; -} - -/* -** Delete all information from the single table that pCur is open on. -** -** This routine only work for pCur on an ephemeral table. -*/ -SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ - return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); -} - -/* -** Erase all information in a table and add the root of the table to -** the freelist. Except, the root of the principle table (the one on -** page 1) is never added to the freelist. -** -** This routine will fail with SQLITE_LOCKED if there are any open -** cursors on the table. -** -** If AUTOVACUUM is enabled and the page at iTable is not the last -** root page in the database file, then the last root page -** in the database file is moved into the slot formerly occupied by -** iTable and that last slot formerly occupied by the last root page -** is added to the freelist instead of iTable. In this say, all -** root pages are kept at the beginning of the database file, which -** is necessary for AUTOVACUUM to work right. *piMoved is set to the -** page number that used to be the last root page in the file before -** the move. If no page gets moved, *piMoved is set to 0. -** The last root page is recorded in meta[3] and the value of -** meta[3] is updated by this procedure. -*/ -static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ - int rc; - MemPage *pPage = 0; - BtShared *pBt = p->pBt; - - assert( sqlite3BtreeHoldsMutex(p) ); - assert( p->inTrans==TRANS_WRITE ); - assert( iTable>=2 ); - if( iTable>btreePagecount(pBt) ){ - return SQLITE_CORRUPT_BKPT; - } - - rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0); - if( rc ) return rc; - rc = sqlite3BtreeClearTable(p, iTable, 0); - if( rc ){ - releasePage(pPage); - return rc; - } - - *piMoved = 0; - -#ifdef SQLITE_OMIT_AUTOVACUUM - freePage(pPage, &rc); - releasePage(pPage); -#else - if( pBt->autoVacuum ){ - Pgno maxRootPgno; - sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno); - - if( iTable==maxRootPgno ){ - /* If the table being dropped is the table with the largest root-page - ** number in the database, put the root page on the free list. - */ - freePage(pPage, &rc); - releasePage(pPage); - if( rc!=SQLITE_OK ){ - return rc; - } - }else{ - /* The table being dropped does not have the largest root-page - ** number in the database. So move the page that does into the - ** gap left by the deleted root-page. - */ - MemPage *pMove; - releasePage(pPage); - rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0); - releasePage(pMove); - if( rc!=SQLITE_OK ){ - return rc; - } - pMove = 0; - rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); - freePage(pMove, &rc); - releasePage(pMove); - if( rc!=SQLITE_OK ){ - return rc; - } - *piMoved = maxRootPgno; - } - - /* Set the new 'max-root-page' value in the database header. This - ** is the old value less one, less one more if that happens to - ** be a root-page number, less one again if that is the - ** PENDING_BYTE_PAGE. - */ - maxRootPgno--; - while( maxRootPgno==PENDING_BYTE_PAGE(pBt) - || PTRMAP_ISPAGE(pBt, maxRootPgno) ){ - maxRootPgno--; - } - assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); - - rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); - }else{ - freePage(pPage, &rc); - releasePage(pPage); - } -#endif - return rc; -} -SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ - int rc; - sqlite3BtreeEnter(p); - rc = btreeDropTable(p, iTable, piMoved); - sqlite3BtreeLeave(p); - return rc; -} - - -/* -** This function may only be called if the b-tree connection already -** has a read or write transaction open on the database. -** -** Read the meta-information out of a database file. Meta[0] -** is the number of free pages currently in the database. Meta[1] -** through meta[15] are available for use by higher layers. Meta[0] -** is read-only, the others are read/write. -** -** The schema layer numbers meta values differently. At the schema -** layer (and the SetCookie and ReadCookie opcodes) the number of -** free pages is not visible. So Cookie[0] is the same as Meta[1]. -** -** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead -** of reading the value out of the header, it instead loads the "DataVersion" -** from the pager. The BTREE_DATA_VERSION value is not actually stored in the -** database file. It is a number computed by the pager. But its access -** pattern is the same as header meta values, and so it is convenient to -** read it from this routine. -*/ -SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ - BtShared *pBt = p->pBt; - - sqlite3BtreeEnter(p); - assert( p->inTrans>TRANS_NONE ); - assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) ); - assert( pBt->pPage1 ); - assert( idx>=0 && idx<=15 ); - - if( idx==BTREE_DATA_VERSION ){ - *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion; - }else{ - *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); - } - - /* If auto-vacuum is disabled in this build and this is an auto-vacuum - ** database, mark the database as read-only. */ -#ifdef SQLITE_OMIT_AUTOVACUUM - if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ - pBt->btsFlags |= BTS_READ_ONLY; - } -#endif - - sqlite3BtreeLeave(p); -} - -/* -** Write meta-information back into the database. Meta[0] is -** read-only and may not be written. -*/ -SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ - BtShared *pBt = p->pBt; - unsigned char *pP1; - int rc; - assert( idx>=1 && idx<=15 ); - sqlite3BtreeEnter(p); - assert( p->inTrans==TRANS_WRITE ); - assert( pBt->pPage1!=0 ); - pP1 = pBt->pPage1->aData; - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); - if( rc==SQLITE_OK ){ - put4byte(&pP1[36 + idx*4], iMeta); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( idx==BTREE_INCR_VACUUM ){ - assert( pBt->autoVacuum || iMeta==0 ); - assert( iMeta==0 || iMeta==1 ); - pBt->incrVacuum = (u8)iMeta; - } -#endif - } - sqlite3BtreeLeave(p); - return rc; -} - -/* -** The first argument, pCur, is a cursor opened on some b-tree. Count the -** number of entries in the b-tree and write the result to *pnEntry. -** -** SQLITE_OK is returned if the operation is successfully executed. -** Otherwise, if an error is encountered (i.e. an IO error or database -** corruption) an SQLite error code is returned. -*/ -SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){ - i64 nEntry = 0; /* Value to return in *pnEntry */ - int rc; /* Return code */ - - rc = moveToRoot(pCur); - if( rc==SQLITE_EMPTY ){ - *pnEntry = 0; - return SQLITE_OK; - } - - /* Unless an error occurs, the following loop runs one iteration for each - ** page in the B-Tree structure (not including overflow pages). - */ - while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){ - int iIdx; /* Index of child node in parent */ - MemPage *pPage; /* Current page of the b-tree */ - - /* If this is a leaf page or the tree is not an int-key tree, then - ** this page contains countable entries. Increment the entry counter - ** accordingly. - */ - pPage = pCur->pPage; - if( pPage->leaf || !pPage->intKey ){ - nEntry += pPage->nCell; - } - - /* pPage is a leaf node. This loop navigates the cursor so that it - ** points to the first interior cell that it points to the parent of - ** the next page in the tree that has not yet been visited. The - ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell - ** of the page, or to the number of cells in the page if the next page - ** to visit is the right-child of its parent. - ** - ** If all pages in the tree have been visited, return SQLITE_OK to the - ** caller. - */ - if( pPage->leaf ){ - do { - if( pCur->iPage==0 ){ - /* All pages of the b-tree have been visited. Return successfully. */ - *pnEntry = nEntry; - return moveToRoot(pCur); - } - moveToParent(pCur); - }while ( pCur->ix>=pCur->pPage->nCell ); - - pCur->ix++; - pPage = pCur->pPage; - } - - /* Descend to the child node of the cell that the cursor currently - ** points at. This is the right-child if (iIdx==pPage->nCell). - */ - iIdx = pCur->ix; - if( iIdx==pPage->nCell ){ - rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); - }else{ - rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx))); - } - } - - /* An error has occurred. Return an error code. */ - return rc; -} - -/* -** Return the pager associated with a BTree. This routine is used for -** testing and debugging only. -*/ -SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){ - return p->pBt->pPager; -} - -#ifndef SQLITE_OMIT_INTEGRITY_CHECK -/* -** Append a message to the error message string. -*/ -static void checkAppendMsg( - IntegrityCk *pCheck, - const char *zFormat, - ... -){ - va_list ap; - if( !pCheck->mxErr ) return; - pCheck->mxErr--; - pCheck->nErr++; - va_start(ap, zFormat); - if( pCheck->errMsg.nChar ){ - sqlite3_str_append(&pCheck->errMsg, "\n", 1); - } - if( pCheck->zPfx ){ - sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); - } - sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap); - va_end(ap); - if( pCheck->errMsg.accError==SQLITE_NOMEM ){ - pCheck->bOomFault = 1; - } -} -#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ - -#ifndef SQLITE_OMIT_INTEGRITY_CHECK - -/* -** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that -** corresponds to page iPg is already set. -*/ -static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ - assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); - return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); -} - -/* -** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. -*/ -static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ - assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); - pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); -} - - -/* -** Add 1 to the reference count for page iPage. If this is the second -** reference to the page, add an error message to pCheck->zErrMsg. -** Return 1 if there are 2 or more references to the page and 0 if -** if this is the first reference to the page. -** -** Also check that the page number is in bounds. -*/ -static int checkRef(IntegrityCk *pCheck, Pgno iPage){ - if( iPage>pCheck->nPage || iPage==0 ){ - checkAppendMsg(pCheck, "invalid page number %d", iPage); - return 1; - } - if( getPageReferenced(pCheck, iPage) ){ - checkAppendMsg(pCheck, "2nd reference to page %d", iPage); - return 1; - } - if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1; - setPageReferenced(pCheck, iPage); - return 0; -} - -#ifndef SQLITE_OMIT_AUTOVACUUM -/* -** Check that the entry in the pointer-map for page iChild maps to -** page iParent, pointer type ptrType. If not, append an error message -** to pCheck. -*/ -static void checkPtrmap( - IntegrityCk *pCheck, /* Integrity check context */ - Pgno iChild, /* Child page number */ - u8 eType, /* Expected pointer map type */ - Pgno iParent /* Expected pointer map parent page number */ -){ - int rc; - u8 ePtrmapType; - Pgno iPtrmapParent; - - rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1; - checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild); - return; - } - - if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ - checkAppendMsg(pCheck, - "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", - iChild, eType, iParent, ePtrmapType, iPtrmapParent); - } -} -#endif - -/* -** Check the integrity of the freelist or of an overflow page list. -** Verify that the number of pages on the list is N. -*/ -static void checkList( - IntegrityCk *pCheck, /* Integrity checking context */ - int isFreeList, /* True for a freelist. False for overflow page list */ - Pgno iPage, /* Page number for first page in the list */ - u32 N /* Expected number of pages in the list */ -){ - int i; - u32 expected = N; - int nErrAtStart = pCheck->nErr; - while( iPage!=0 && pCheck->mxErr ){ - DbPage *pOvflPage; - unsigned char *pOvflData; - if( checkRef(pCheck, iPage) ) break; - N--; - if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ - checkAppendMsg(pCheck, "failed to get page %d", iPage); - break; - } - pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); - if( isFreeList ){ - u32 n = (u32)get4byte(&pOvflData[4]); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pCheck->pBt->autoVacuum ){ - checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); - } -#endif - if( n>pCheck->pBt->usableSize/4-2 ){ - checkAppendMsg(pCheck, - "freelist leaf count too big on page %d", iPage); - N--; - }else{ - for(i=0; i<(int)n; i++){ - Pgno iFreePage = get4byte(&pOvflData[8+i*4]); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pCheck->pBt->autoVacuum ){ - checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0); - } -#endif - checkRef(pCheck, iFreePage); - } - N -= n; - } - } -#ifndef SQLITE_OMIT_AUTOVACUUM - else{ - /* If this database supports auto-vacuum and iPage is not the last - ** page in this overflow list, check that the pointer-map entry for - ** the following page matches iPage. - */ - if( pCheck->pBt->autoVacuum && N>0 ){ - i = get4byte(pOvflData); - checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage); - } - } -#endif - iPage = get4byte(pOvflData); - sqlite3PagerUnref(pOvflPage); - } - if( N && nErrAtStart==pCheck->nErr ){ - checkAppendMsg(pCheck, - "%s is %d but should be %d", - isFreeList ? "size" : "overflow list length", - expected-N, expected); - } -} -#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ - -/* -** An implementation of a min-heap. -** -** aHeap[0] is the number of elements on the heap. aHeap[1] is the -** root element. The daughter nodes of aHeap[N] are aHeap[N*2] -** and aHeap[N*2+1]. -** -** The heap property is this: Every node is less than or equal to both -** of its daughter nodes. A consequence of the heap property is that the -** root node aHeap[1] is always the minimum value currently in the heap. -** -** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto -** the heap, preserving the heap property. The btreeHeapPull() routine -** removes the root element from the heap (the minimum value in the heap) -** and then moves other nodes around as necessary to preserve the heap -** property. -** -** This heap is used for cell overlap and coverage testing. Each u32 -** entry represents the span of a cell or freeblock on a btree page. -** The upper 16 bits are the index of the first byte of a range and the -** lower 16 bits are the index of the last byte of that range. -*/ -static void btreeHeapInsert(u32 *aHeap, u32 x){ - u32 j, i = ++aHeap[0]; - aHeap[i] = x; - while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){ - x = aHeap[j]; - aHeap[j] = aHeap[i]; - aHeap[i] = x; - i = j; - } -} -static int btreeHeapPull(u32 *aHeap, u32 *pOut){ - u32 j, i, x; - if( (x = aHeap[0])==0 ) return 0; - *pOut = aHeap[1]; - aHeap[1] = aHeap[x]; - aHeap[x] = 0xffffffff; - aHeap[0]--; - i = 1; - while( (j = i*2)<=aHeap[0] ){ - if( aHeap[j]>aHeap[j+1] ) j++; - if( aHeap[i]zPfx; - int saved_v1 = pCheck->v1; - int saved_v2 = pCheck->v2; - u8 savedIsInit = 0; - - /* Check that the page exists - */ - pBt = pCheck->pBt; - usableSize = pBt->usableSize; - if( iPage==0 ) return 0; - if( checkRef(pCheck, iPage) ) return 0; - pCheck->zPfx = "Page %u: "; - pCheck->v1 = iPage; - if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){ - checkAppendMsg(pCheck, - "unable to get the page. error code=%d", rc); - goto end_of_check; - } - - /* Clear MemPage.isInit to make sure the corruption detection code in - ** btreeInitPage() is executed. */ - savedIsInit = pPage->isInit; - pPage->isInit = 0; - if( (rc = btreeInitPage(pPage))!=0 ){ - assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ - checkAppendMsg(pCheck, - "btreeInitPage() returns error code %d", rc); - goto end_of_check; - } - if( (rc = btreeComputeFreeSpace(pPage))!=0 ){ - assert( rc==SQLITE_CORRUPT ); - checkAppendMsg(pCheck, "free space corruption", rc); - goto end_of_check; - } - data = pPage->aData; - hdr = pPage->hdrOffset; - - /* Set up for cell analysis */ - pCheck->zPfx = "On tree page %u cell %d: "; - contentOffset = get2byteNotZero(&data[hdr+5]); - assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ - - /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the - ** number of cells on the page. */ - nCell = get2byte(&data[hdr+3]); - assert( pPage->nCell==nCell ); - - /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page - ** immediately follows the b-tree page header. */ - cellStart = hdr + 12 - 4*pPage->leaf; - assert( pPage->aCellIdx==&data[cellStart] ); - pCellIdx = &data[cellStart + 2*(nCell-1)]; - - if( !pPage->leaf ){ - /* Analyze the right-child page of internal pages */ - pgno = get4byte(&data[hdr+8]); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pBt->autoVacuum ){ - pCheck->zPfx = "On page %u at right child: "; - checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); - } -#endif - depth = checkTreePage(pCheck, pgno, &maxKey, maxKey); - keyCanBeEqual = 0; - }else{ - /* For leaf pages, the coverage check will occur in the same loop - ** as the other cell checks, so initialize the heap. */ - heap = pCheck->heap; - heap[0] = 0; - } - - /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte - ** integer offsets to the cell contents. */ - for(i=nCell-1; i>=0 && pCheck->mxErr; i--){ - CellInfo info; - - /* Check cell size */ - pCheck->v2 = i; - assert( pCellIdx==&data[cellStart + i*2] ); - pc = get2byteAligned(pCellIdx); - pCellIdx -= 2; - if( pcusableSize-4 ){ - checkAppendMsg(pCheck, "Offset %d out of range %d..%d", - pc, contentOffset, usableSize-4); - doCoverageCheck = 0; - continue; - } - pCell = &data[pc]; - pPage->xParseCell(pPage, pCell, &info); - if( pc+info.nSize>usableSize ){ - checkAppendMsg(pCheck, "Extends off end of page"); - doCoverageCheck = 0; - continue; - } - - /* Check for integer primary key out of range */ - if( pPage->intKey ){ - if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){ - checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey); - } - maxKey = info.nKey; - keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */ - } - - /* Check the content overflow list */ - if( info.nPayload>info.nLocal ){ - u32 nPage; /* Number of pages on the overflow chain */ - Pgno pgnoOvfl; /* First page of the overflow chain */ - assert( pc + info.nSize - 4 <= usableSize ); - nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4); - pgnoOvfl = get4byte(&pCell[info.nSize - 4]); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pBt->autoVacuum ){ - checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage); - } -#endif - checkList(pCheck, 0, pgnoOvfl, nPage); - } - - if( !pPage->leaf ){ - /* Check sanity of left child page for internal pages */ - pgno = get4byte(pCell); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pBt->autoVacuum ){ - checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); - } -#endif - d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey); - keyCanBeEqual = 0; - if( d2!=depth ){ - checkAppendMsg(pCheck, "Child page depth differs"); - depth = d2; - } - }else{ - /* Populate the coverage-checking heap for leaf pages */ - btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); - } - } - *piMinKey = maxKey; - - /* Check for complete coverage of the page - */ - pCheck->zPfx = 0; - if( doCoverageCheck && pCheck->mxErr>0 ){ - /* For leaf pages, the min-heap has already been initialized and the - ** cells have already been inserted. But for internal pages, that has - ** not yet been done, so do it now */ - if( !pPage->leaf ){ - heap = pCheck->heap; - heap[0] = 0; - for(i=nCell-1; i>=0; i--){ - u32 size; - pc = get2byteAligned(&data[cellStart+i*2]); - size = pPage->xCellSize(pPage, &data[pc]); - btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); - } - } - /* Add the freeblocks to the min-heap - ** - ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header - ** is the offset of the first freeblock, or zero if there are no - ** freeblocks on the page. - */ - i = get2byte(&data[hdr+1]); - while( i>0 ){ - int size, j; - assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ - size = get2byte(&data[i+2]); - assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */ - btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); - /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a - ** big-endian integer which is the offset in the b-tree page of the next - ** freeblock in the chain, or zero if the freeblock is the last on the - ** chain. */ - j = get2byte(&data[i]); - /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of - ** increasing offset. */ - assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */ - assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ - i = j; - } - /* Analyze the min-heap looking for overlap between cells and/or - ** freeblocks, and counting the number of untracked bytes in nFrag. - ** - ** Each min-heap entry is of the form: (start_address<<16)|end_address. - ** There is an implied first entry the covers the page header, the cell - ** pointer index, and the gap between the cell pointer index and the start - ** of cell content. - ** - ** The loop below pulls entries from the min-heap in order and compares - ** the start_address against the previous end_address. If there is an - ** overlap, that means bytes are used multiple times. If there is a gap, - ** that gap is added to the fragmentation count. - */ - nFrag = 0; - prev = contentOffset - 1; /* Implied first min-heap entry */ - while( btreeHeapPull(heap,&x) ){ - if( (prev&0xffff)>=(x>>16) ){ - checkAppendMsg(pCheck, - "Multiple uses for byte %u of page %u", x>>16, iPage); - break; - }else{ - nFrag += (x>>16) - (prev&0xffff) - 1; - prev = x; - } - } - nFrag += usableSize - (prev&0xffff) - 1; - /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments - ** is stored in the fifth field of the b-tree page header. - ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the - ** number of fragmented free bytes within the cell content area. - */ - if( heap[0]==0 && nFrag!=data[hdr+7] ){ - checkAppendMsg(pCheck, - "Fragmentation of %d bytes reported as %d on page %u", - nFrag, data[hdr+7], iPage); - } - } - -end_of_check: - if( !doCoverageCheck ) pPage->isInit = savedIsInit; - releasePage(pPage); - pCheck->zPfx = saved_zPfx; - pCheck->v1 = saved_v1; - pCheck->v2 = saved_v2; - return depth+1; -} -#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ - -#ifndef SQLITE_OMIT_INTEGRITY_CHECK -/* -** This routine does a complete check of the given BTree file. aRoot[] is -** an array of pages numbers were each page number is the root page of -** a table. nRoot is the number of entries in aRoot. -** -** A read-only or read-write transaction must be opened before calling -** this function. -** -** Write the number of error seen in *pnErr. Except for some memory -** allocation errors, an error message held in memory obtained from -** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is -** returned. If a memory allocation error occurs, NULL is returned. -** -** If the first entry in aRoot[] is 0, that indicates that the list of -** root pages is incomplete. This is a "partial integrity-check". This -** happens when performing an integrity check on a single table. The -** zero is skipped, of course. But in addition, the freelist checks -** and the checks to make sure every page is referenced are also skipped, -** since obviously it is not possible to know which pages are covered by -** the unverified btrees. Except, if aRoot[1] is 1, then the freelist -** checks are still performed. -*/ -SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( - sqlite3 *db, /* Database connection that is running the check */ - Btree *p, /* The btree to be checked */ - Pgno *aRoot, /* An array of root pages numbers for individual trees */ - int nRoot, /* Number of entries in aRoot[] */ - int mxErr, /* Stop reporting errors after this many */ - int *pnErr /* Write number of errors seen to this variable */ -){ - Pgno i; - IntegrityCk sCheck; - BtShared *pBt = p->pBt; - u64 savedDbFlags = pBt->db->flags; - char zErr[100]; - int bPartial = 0; /* True if not checking all btrees */ - int bCkFreelist = 1; /* True to scan the freelist */ - VVA_ONLY( int nRef ); - assert( nRoot>0 ); - - /* aRoot[0]==0 means this is a partial check */ - if( aRoot[0]==0 ){ - assert( nRoot>1 ); - bPartial = 1; - if( aRoot[1]!=1 ) bCkFreelist = 0; - } - - sqlite3BtreeEnter(p); - assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); - VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); - assert( nRef>=0 ); - sCheck.db = db; - sCheck.pBt = pBt; - sCheck.pPager = pBt->pPager; - sCheck.nPage = btreePagecount(sCheck.pBt); - sCheck.mxErr = mxErr; - sCheck.nErr = 0; - sCheck.bOomFault = 0; - sCheck.zPfx = 0; - sCheck.v1 = 0; - sCheck.v2 = 0; - sCheck.aPgRef = 0; - sCheck.heap = 0; - sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); - sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL; - if( sCheck.nPage==0 ){ - goto integrity_ck_cleanup; - } - - sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); - if( !sCheck.aPgRef ){ - sCheck.bOomFault = 1; - goto integrity_ck_cleanup; - } - sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); - if( sCheck.heap==0 ){ - sCheck.bOomFault = 1; - goto integrity_ck_cleanup; - } - - i = PENDING_BYTE_PAGE(pBt); - if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); - - /* Check the integrity of the freelist - */ - if( bCkFreelist ){ - sCheck.zPfx = "Main freelist: "; - checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), - get4byte(&pBt->pPage1->aData[36])); - sCheck.zPfx = 0; - } - - /* Check all the tables. - */ -#ifndef SQLITE_OMIT_AUTOVACUUM - if( !bPartial ){ - if( pBt->autoVacuum ){ - Pgno mx = 0; - Pgno mxInHdr; - for(i=0; (int)ipPage1->aData[52]); - if( mx!=mxInHdr ){ - checkAppendMsg(&sCheck, - "max rootpage (%d) disagrees with header (%d)", - mx, mxInHdr - ); - } - }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){ - checkAppendMsg(&sCheck, - "incremental_vacuum enabled with a max rootpage of zero" - ); - } - } -#endif - testcase( pBt->db->flags & SQLITE_CellSizeCk ); - pBt->db->flags &= ~(u64)SQLITE_CellSizeCk; - for(i=0; (int)iautoVacuum && aRoot[i]>1 && !bPartial ){ - checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0); - } -#endif - checkTreePage(&sCheck, aRoot[i], ¬Used, LARGEST_INT64); - } - pBt->db->flags = savedDbFlags; - - /* Make sure every page in the file is referenced - */ - if( !bPartial ){ - for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ -#ifdef SQLITE_OMIT_AUTOVACUUM - if( getPageReferenced(&sCheck, i)==0 ){ - checkAppendMsg(&sCheck, "Page %d is never used", i); - } -#else - /* If the database supports auto-vacuum, make sure no tables contain - ** references to pointer-map pages. - */ - if( getPageReferenced(&sCheck, i)==0 && - (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ - checkAppendMsg(&sCheck, "Page %d is never used", i); - } - if( getPageReferenced(&sCheck, i)!=0 && - (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ - checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i); - } -#endif - } - } - - /* Clean up and report errors. - */ -integrity_ck_cleanup: - sqlite3PageFree(sCheck.heap); - sqlite3_free(sCheck.aPgRef); - if( sCheck.bOomFault ){ - sqlite3_str_reset(&sCheck.errMsg); - sCheck.nErr++; - } - *pnErr = sCheck.nErr; - if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg); - /* Make sure this analysis did not leave any unref() pages. */ - assert( nRef==sqlite3PagerRefcount(pBt->pPager) ); - sqlite3BtreeLeave(p); - return sqlite3StrAccumFinish(&sCheck.errMsg); -} -#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ - -/* -** Return the full pathname of the underlying database file. Return -** an empty string if the database is in-memory or a TEMP database. -** -** The pager filename is invariant as long as the pager is -** open so it is safe to access without the BtShared mutex. -*/ -SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){ - assert( p->pBt->pPager!=0 ); - return sqlite3PagerFilename(p->pBt->pPager, 1); -} - -/* -** Return the pathname of the journal file for this database. The return -** value of this routine is the same regardless of whether the journal file -** has been created or not. -** -** The pager journal filename is invariant as long as the pager is -** open so it is safe to access without the BtShared mutex. -*/ -SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){ - assert( p->pBt->pPager!=0 ); - return sqlite3PagerJournalname(p->pBt->pPager); -} - -/* -** Return non-zero if a transaction is active. -*/ -SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){ - assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); - return (p && (p->inTrans==TRANS_WRITE)); -} - -#ifndef SQLITE_OMIT_WAL -/* -** Run a checkpoint on the Btree passed as the first argument. -** -** Return SQLITE_LOCKED if this or any other connection has an open -** transaction on the shared-cache the argument Btree is connected to. -** -** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART. -*/ -SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){ - int rc = SQLITE_OK; - if( p ){ - BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); - if( pBt->inTransaction!=TRANS_NONE ){ - rc = SQLITE_LOCKED; - }else{ - rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt); - } - sqlite3BtreeLeave(p); - } - return rc; -} -#endif - -/* -** Return non-zero if a read (or write) transaction is active. -*/ -SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){ - assert( p ); - assert( sqlite3_mutex_held(p->db->mutex) ); - return p->inTrans!=TRANS_NONE; -} - -SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){ - assert( p ); - assert( sqlite3_mutex_held(p->db->mutex) ); - return p->nBackup!=0; -} - -/* -** This function returns a pointer to a blob of memory associated with -** a single shared-btree. The memory is used by client code for its own -** purposes (for example, to store a high-level schema associated with -** the shared-btree). The btree layer manages reference counting issues. -** -** The first time this is called on a shared-btree, nBytes bytes of memory -** are allocated, zeroed, and returned to the caller. For each subsequent -** call the nBytes parameter is ignored and a pointer to the same blob -** of memory returned. -** -** If the nBytes parameter is 0 and the blob of memory has not yet been -** allocated, a null pointer is returned. If the blob has already been -** allocated, it is returned as normal. -** -** Just before the shared-btree is closed, the function passed as the -** xFree argument when the memory allocation was made is invoked on the -** blob of allocated memory. The xFree function should not call sqlite3_free() -** on the memory, the btree layer does that. -*/ -SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ - BtShared *pBt = p->pBt; - sqlite3BtreeEnter(p); - if( !pBt->pSchema && nBytes ){ - pBt->pSchema = sqlite3DbMallocZero(0, nBytes); - pBt->xFreeSchema = xFree; - } - sqlite3BtreeLeave(p); - return pBt->pSchema; -} - -/* -** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared -** btree as the argument handle holds an exclusive lock on the -** sqlite_schema table. Otherwise SQLITE_OK. -*/ -SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ - int rc; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK); - assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE ); - sqlite3BtreeLeave(p); - return rc; -} - - -#ifndef SQLITE_OMIT_SHARED_CACHE -/* -** Obtain a lock on the table whose root page is iTab. The -** lock is a write lock if isWritelock is true or a read lock -** if it is false. -*/ -SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ - int rc = SQLITE_OK; - assert( p->inTrans!=TRANS_NONE ); - if( p->sharable ){ - u8 lockType = READ_LOCK + isWriteLock; - assert( READ_LOCK+1==WRITE_LOCK ); - assert( isWriteLock==0 || isWriteLock==1 ); - - sqlite3BtreeEnter(p); - rc = querySharedCacheTableLock(p, iTab, lockType); - if( rc==SQLITE_OK ){ - rc = setSharedCacheTableLock(p, iTab, lockType); - } - sqlite3BtreeLeave(p); - } - return rc; -} -#endif - -#ifndef SQLITE_OMIT_INCRBLOB -/* -** Argument pCsr must be a cursor opened for writing on an -** INTKEY table currently pointing at a valid table entry. -** This function modifies the data stored as part of that entry. -** -** Only the data content may only be modified, it is not possible to -** change the length of the data stored. If this function is called with -** parameters that attempt to write past the end of the existing data, -** no modifications are made and SQLITE_CORRUPT is returned. -*/ -SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ - int rc; - assert( cursorOwnsBtShared(pCsr) ); - assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); - assert( pCsr->curFlags & BTCF_Incrblob ); - - rc = restoreCursorPosition(pCsr); - if( rc!=SQLITE_OK ){ - return rc; - } - assert( pCsr->eState!=CURSOR_REQUIRESEEK ); - if( pCsr->eState!=CURSOR_VALID ){ - return SQLITE_ABORT; - } - - /* Save the positions of all other cursors open on this table. This is - ** required in case any of them are holding references to an xFetch - ** version of the b-tree page modified by the accessPayload call below. - ** - ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() - ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence - ** saveAllCursors can only return SQLITE_OK. - */ - VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); - assert( rc==SQLITE_OK ); - - /* Check some assumptions: - ** (a) the cursor is open for writing, - ** (b) there is a read/write transaction open, - ** (c) the connection holds a write-lock on the table (if required), - ** (d) there are no conflicting read-locks, and - ** (e) the cursor points at a valid row of an intKey table. - */ - if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){ - return SQLITE_READONLY; - } - assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 - && pCsr->pBt->inTransaction==TRANS_WRITE ); - assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); - assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); - assert( pCsr->pPage->intKey ); - - return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); -} - -/* -** Mark this cursor as an incremental blob cursor. -*/ -SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ - pCur->curFlags |= BTCF_Incrblob; - pCur->pBtree->hasIncrblobCur = 1; -} -#endif - -/* -** Set both the "read version" (single byte at byte offset 18) and -** "write version" (single byte at byte offset 19) fields in the database -** header to iVersion. -*/ -SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ - BtShared *pBt = pBtree->pBt; - int rc; /* Return code */ - - assert( iVersion==1 || iVersion==2 ); - - /* If setting the version fields to 1, do not automatically open the - ** WAL connection, even if the version fields are currently set to 2. - */ - pBt->btsFlags &= ~BTS_NO_WAL; - if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; - - rc = sqlite3BtreeBeginTrans(pBtree, 0, 0); - if( rc==SQLITE_OK ){ - u8 *aData = pBt->pPage1->aData; - if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ - rc = sqlite3BtreeBeginTrans(pBtree, 2, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); - if( rc==SQLITE_OK ){ - aData[18] = (u8)iVersion; - aData[19] = (u8)iVersion; - } - } - } - } - - pBt->btsFlags &= ~BTS_NO_WAL; - return rc; -} - -/* -** Return true if the cursor has a hint specified. This routine is -** only used from within assert() statements -*/ -SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){ - return (pCsr->hints & mask)!=0; -} - -/* -** Return true if the given Btree is read-only. -*/ -SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){ - return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; -} - -/* -** Return the size of the header added to each page by this module. -*/ -SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); } - -#if !defined(SQLITE_OMIT_SHARED_CACHE) -/* -** Return true if the Btree passed as the only argument is sharable. -*/ -SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){ - return p->sharable; -} - -/* -** Return the number of connections to the BtShared object accessed by -** the Btree handle passed as the only argument. For private caches -** this is always 1. For shared caches it may be 1 or greater. -*/ -SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ - testcase( p->sharable ); - return p->pBt->nRef; -} -#endif - -/************** End of btree.c ***********************************************/ -/************** Begin file backup.c ******************************************/ -/* -** 2009 January 28 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the implementation of the sqlite3_backup_XXX() -** API functions and the related features. -*/ -/* #include "sqliteInt.h" */ -/* #include "btreeInt.h" */ - -/* -** Structure allocated for each backup operation. -*/ -struct sqlite3_backup { - sqlite3* pDestDb; /* Destination database handle */ - Btree *pDest; /* Destination b-tree file */ - u32 iDestSchema; /* Original schema cookie in destination */ - int bDestLocked; /* True once a write-transaction is open on pDest */ - - Pgno iNext; /* Page number of the next source page to copy */ - sqlite3* pSrcDb; /* Source database handle */ - Btree *pSrc; /* Source b-tree file */ - - int rc; /* Backup process error code */ - - /* These two variables are set by every call to backup_step(). They are - ** read by calls to backup_remaining() and backup_pagecount(). - */ - Pgno nRemaining; /* Number of pages left to copy */ - Pgno nPagecount; /* Total number of pages to copy */ - - int isAttached; /* True once backup has been registered with pager */ - sqlite3_backup *pNext; /* Next backup associated with source pager */ -}; - -/* -** THREAD SAFETY NOTES: -** -** Once it has been created using backup_init(), a single sqlite3_backup -** structure may be accessed via two groups of thread-safe entry points: -** -** * Via the sqlite3_backup_XXX() API function backup_step() and -** backup_finish(). Both these functions obtain the source database -** handle mutex and the mutex associated with the source BtShared -** structure, in that order. -** -** * Via the BackupUpdate() and BackupRestart() functions, which are -** invoked by the pager layer to report various state changes in -** the page cache associated with the source database. The mutex -** associated with the source database BtShared structure will always -** be held when either of these functions are invoked. -** -** The other sqlite3_backup_XXX() API functions, backup_remaining() and -** backup_pagecount() are not thread-safe functions. If they are called -** while some other thread is calling backup_step() or backup_finish(), -** the values returned may be invalid. There is no way for a call to -** BackupUpdate() or BackupRestart() to interfere with backup_remaining() -** or backup_pagecount(). -** -** Depending on the SQLite configuration, the database handles and/or -** the Btree objects may have their own mutexes that require locking. -** Non-sharable Btrees (in-memory databases for example), do not have -** associated mutexes. -*/ - -/* -** Return a pointer corresponding to database zDb (i.e. "main", "temp") -** in connection handle pDb. If such a database cannot be found, return -** a NULL pointer and write an error message to pErrorDb. -** -** If the "temp" database is requested, it may need to be opened by this -** function. If an error occurs while doing so, return 0 and write an -** error message to pErrorDb. -*/ -static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ - int i = sqlite3FindDbName(pDb, zDb); - - if( i==1 ){ - Parse sParse; - int rc = 0; - memset(&sParse, 0, sizeof(sParse)); - sParse.db = pDb; - if( sqlite3OpenTempDatabase(&sParse) ){ - sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg); - rc = SQLITE_ERROR; - } - sqlite3DbFree(pErrorDb, sParse.zErrMsg); - sqlite3ParserReset(&sParse); - if( rc ){ - return 0; - } - } - - if( i<0 ){ - sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb); - return 0; - } - - return pDb->aDb[i].pBt; -} - -/* -** Attempt to set the page size of the destination to match the page size -** of the source. -*/ -static int setDestPgsz(sqlite3_backup *p){ - int rc; - rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0); - return rc; -} - -/* -** Check that there is no open read-transaction on the b-tree passed as the -** second argument. If there is not, return SQLITE_OK. Otherwise, if there -** is an open read-transaction, return SQLITE_ERROR and leave an error -** message in database handle db. -*/ -static int checkReadTransaction(sqlite3 *db, Btree *p){ - if( sqlite3BtreeIsInReadTrans(p) ){ - sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use"); - return SQLITE_ERROR; - } - return SQLITE_OK; -} - -/* -** Create an sqlite3_backup process to copy the contents of zSrcDb from -** connection handle pSrcDb to zDestDb in pDestDb. If successful, return -** a pointer to the new sqlite3_backup object. -** -** If an error occurs, NULL is returned and an error code and error message -** stored in database handle pDestDb. -*/ -SQLITE_API sqlite3_backup *sqlite3_backup_init( - sqlite3* pDestDb, /* Database to write to */ - const char *zDestDb, /* Name of database within pDestDb */ - sqlite3* pSrcDb, /* Database connection to read from */ - const char *zSrcDb /* Name of database within pSrcDb */ -){ - sqlite3_backup *p; /* Value to return */ - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - - /* Lock the source database handle. The destination database - ** handle is not locked in this routine, but it is locked in - ** sqlite3_backup_step(). The user is required to ensure that no - ** other thread accesses the destination handle for the duration - ** of the backup operation. Any attempt to use the destination - ** database connection while a backup is in progress may cause - ** a malfunction or a deadlock. - */ - sqlite3_mutex_enter(pSrcDb->mutex); - sqlite3_mutex_enter(pDestDb->mutex); - - if( pSrcDb==pDestDb ){ - sqlite3ErrorWithMsg( - pDestDb, SQLITE_ERROR, "source and destination must be distinct" - ); - p = 0; - }else { - /* Allocate space for a new sqlite3_backup object... - ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a - ** call to sqlite3_backup_init() and is destroyed by a call to - ** sqlite3_backup_finish(). */ - p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); - if( !p ){ - sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT); - } - } - - /* If the allocation succeeded, populate the new object. */ - if( p ){ - p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); - p->pDest = findBtree(pDestDb, pDestDb, zDestDb); - p->pDestDb = pDestDb; - p->pSrcDb = pSrcDb; - p->iNext = 1; - p->isAttached = 0; - - if( 0==p->pSrc || 0==p->pDest - || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK - ){ - /* One (or both) of the named databases did not exist or an OOM - ** error was hit. Or there is a transaction open on the destination - ** database. The error has already been written into the pDestDb - ** handle. All that is left to do here is free the sqlite3_backup - ** structure. */ - sqlite3_free(p); - p = 0; - } - } - if( p ){ - p->pSrc->nBackup++; - } - - sqlite3_mutex_leave(pDestDb->mutex); - sqlite3_mutex_leave(pSrcDb->mutex); - return p; -} - -/* -** Argument rc is an SQLite error code. Return true if this error is -** considered fatal if encountered during a backup operation. All errors -** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED. -*/ -static int isFatalError(int rc){ - return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED)); -} - -/* -** Parameter zSrcData points to a buffer containing the data for -** page iSrcPg from the source database. Copy this data into the -** destination database. -*/ -static int backupOnePage( - sqlite3_backup *p, /* Backup handle */ - Pgno iSrcPg, /* Source database page to backup */ - const u8 *zSrcData, /* Source database page data */ - int bUpdate /* True for an update, false otherwise */ -){ - Pager * const pDestPager = sqlite3BtreePager(p->pDest); - const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc); - int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest); - const int nCopy = MIN(nSrcPgsz, nDestPgsz); - const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz; - int rc = SQLITE_OK; - i64 iOff; - - assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 ); - assert( p->bDestLocked ); - assert( !isFatalError(p->rc) ); - assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ); - assert( zSrcData ); - - /* Catch the case where the destination is an in-memory database and the - ** page sizes of the source and destination differ. - */ - if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){ - rc = SQLITE_READONLY; - } - - /* This loop runs once for each destination page spanned by the source - ** page. For each iteration, variable iOff is set to the byte offset - ** of the destination page. - */ - for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOffpDest->pBt) ) continue; - if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0)) - && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg)) - ){ - const u8 *zIn = &zSrcData[iOff%nSrcPgsz]; - u8 *zDestData = sqlite3PagerGetData(pDestPg); - u8 *zOut = &zDestData[iOff%nDestPgsz]; - - /* Copy the data from the source page into the destination page. - ** Then clear the Btree layer MemPage.isInit flag. Both this module - ** and the pager code use this trick (clearing the first byte - ** of the page 'extra' space to invalidate the Btree layers - ** cached parse of the page). MemPage.isInit is marked - ** "MUST BE FIRST" for this purpose. - */ - memcpy(zOut, zIn, nCopy); - ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0; - if( iOff==0 && bUpdate==0 ){ - sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc)); - } - } - sqlite3PagerUnref(pDestPg); - } - - return rc; -} - -/* -** If pFile is currently larger than iSize bytes, then truncate it to -** exactly iSize bytes. If pFile is not larger than iSize bytes, then -** this function is a no-op. -** -** Return SQLITE_OK if everything is successful, or an SQLite error -** code if an error occurs. -*/ -static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){ - i64 iCurrent; - int rc = sqlite3OsFileSize(pFile, &iCurrent); - if( rc==SQLITE_OK && iCurrent>iSize ){ - rc = sqlite3OsTruncate(pFile, iSize); - } - return rc; -} - -/* -** Register this backup object with the associated source pager for -** callbacks when pages are changed or the cache invalidated. -*/ -static void attachBackupObject(sqlite3_backup *p){ - sqlite3_backup **pp; - assert( sqlite3BtreeHoldsMutex(p->pSrc) ); - pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); - p->pNext = *pp; - *pp = p; - p->isAttached = 1; -} - -/* -** Copy nPage pages from the source b-tree to the destination. -*/ -SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ - int rc; - int destMode; /* Destination journal mode */ - int pgszSrc = 0; /* Source page size */ - int pgszDest = 0; /* Destination page size */ - -#ifdef SQLITE_ENABLE_API_ARMOR - if( p==0 ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(p->pSrcDb->mutex); - sqlite3BtreeEnter(p->pSrc); - if( p->pDestDb ){ - sqlite3_mutex_enter(p->pDestDb->mutex); - } - - rc = p->rc; - if( !isFatalError(rc) ){ - Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ - Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ - int ii; /* Iterator variable */ - int nSrcPage = -1; /* Size of source db in pages */ - int bCloseTrans = 0; /* True if src db requires unlocking */ - - /* If the source pager is currently in a write-transaction, return - ** SQLITE_BUSY immediately. - */ - if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){ - rc = SQLITE_BUSY; - }else{ - rc = SQLITE_OK; - } - - /* If there is no open read-transaction on the source database, open - ** one now. If a transaction is opened here, then it will be closed - ** before this function exits. - */ - if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){ - rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0); - bCloseTrans = 1; - } - - /* If the destination database has not yet been locked (i.e. if this - ** is the first call to backup_step() for the current backup operation), - ** try to set its page size to the same as the source database. This - ** is especially important on ZipVFS systems, as in that case it is - ** not possible to create a database file that uses one page size by - ** writing to it with another. */ - if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){ - rc = SQLITE_NOMEM; - } - - /* Lock the destination database, if it is not locked already. */ - if( SQLITE_OK==rc && p->bDestLocked==0 - && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2, - (int*)&p->iDestSchema)) - ){ - p->bDestLocked = 1; - } - - /* Do not allow backup if the destination database is in WAL mode - ** and the page sizes are different between source and destination */ - pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); - pgszDest = sqlite3BtreeGetPageSize(p->pDest); - destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); - if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){ - rc = SQLITE_READONLY; - } - - /* Now that there is a read-lock on the source database, query the - ** source pager for the number of pages in the database. - */ - nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc); - assert( nSrcPage>=0 ); - for(ii=0; (nPage<0 || iiiNext<=(Pgno)nSrcPage && !rc; ii++){ - const Pgno iSrcPg = p->iNext; /* Source page number */ - if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){ - DbPage *pSrcPg; /* Source page object */ - rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY); - if( rc==SQLITE_OK ){ - rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0); - sqlite3PagerUnref(pSrcPg); - } - } - p->iNext++; - } - if( rc==SQLITE_OK ){ - p->nPagecount = nSrcPage; - p->nRemaining = nSrcPage+1-p->iNext; - if( p->iNext>(Pgno)nSrcPage ){ - rc = SQLITE_DONE; - }else if( !p->isAttached ){ - attachBackupObject(p); - } - } - - /* Update the schema version field in the destination database. This - ** is to make sure that the schema-version really does change in - ** the case where the source and destination databases have the - ** same schema version. - */ - if( rc==SQLITE_DONE ){ - if( nSrcPage==0 ){ - rc = sqlite3BtreeNewDb(p->pDest); - nSrcPage = 1; - } - if( rc==SQLITE_OK || rc==SQLITE_DONE ){ - rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1); - } - if( rc==SQLITE_OK ){ - if( p->pDestDb ){ - sqlite3ResetAllSchemasOfConnection(p->pDestDb); - } - if( destMode==PAGER_JOURNALMODE_WAL ){ - rc = sqlite3BtreeSetVersion(p->pDest, 2); - } - } - if( rc==SQLITE_OK ){ - int nDestTruncate; - /* Set nDestTruncate to the final number of pages in the destination - ** database. The complication here is that the destination page - ** size may be different to the source page size. - ** - ** If the source page size is smaller than the destination page size, - ** round up. In this case the call to sqlite3OsTruncate() below will - ** fix the size of the file. However it is important to call - ** sqlite3PagerTruncateImage() here so that any pages in the - ** destination file that lie beyond the nDestTruncate page mark are - ** journalled by PagerCommitPhaseOne() before they are destroyed - ** by the file truncation. - */ - assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) ); - assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) ); - if( pgszSrcpDest->pBt) ){ - nDestTruncate--; - } - }else{ - nDestTruncate = nSrcPage * (pgszSrc/pgszDest); - } - assert( nDestTruncate>0 ); - - if( pgszSrc= iSize || ( - nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1) - && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest - )); - - /* This block ensures that all data required to recreate the original - ** database has been stored in the journal for pDestPager and the - ** journal synced to disk. So at this point we may safely modify - ** the database file in any way, knowing that if a power failure - ** occurs, the original database will be reconstructed from the - ** journal file. */ - sqlite3PagerPagecount(pDestPager, &nDstPage); - for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){ - if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){ - DbPage *pPg; - rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pPg); - sqlite3PagerUnref(pPg); - } - } - } - if( rc==SQLITE_OK ){ - rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1); - } - - /* Write the extra pages and truncate the database file as required */ - iEnd = MIN(PENDING_BYTE + pgszDest, iSize); - for( - iOff=PENDING_BYTE+pgszSrc; - rc==SQLITE_OK && iOffpDest, 0)) - ){ - rc = SQLITE_DONE; - } - } - } - - /* If bCloseTrans is true, then this function opened a read transaction - ** on the source database. Close the read transaction here. There is - ** no need to check the return values of the btree methods here, as - ** "committing" a read-only transaction cannot fail. - */ - if( bCloseTrans ){ - TESTONLY( int rc2 ); - TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0); - TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0); - assert( rc2==SQLITE_OK ); - } - - if( rc==SQLITE_IOERR_NOMEM ){ - rc = SQLITE_NOMEM_BKPT; - } - p->rc = rc; - } - if( p->pDestDb ){ - sqlite3_mutex_leave(p->pDestDb->mutex); - } - sqlite3BtreeLeave(p->pSrc); - sqlite3_mutex_leave(p->pSrcDb->mutex); - return rc; -} - -/* -** Release all resources associated with an sqlite3_backup* handle. -*/ -SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){ - sqlite3_backup **pp; /* Ptr to head of pagers backup list */ - sqlite3 *pSrcDb; /* Source database connection */ - int rc; /* Value to return */ - - /* Enter the mutexes */ - if( p==0 ) return SQLITE_OK; - pSrcDb = p->pSrcDb; - sqlite3_mutex_enter(pSrcDb->mutex); - sqlite3BtreeEnter(p->pSrc); - if( p->pDestDb ){ - sqlite3_mutex_enter(p->pDestDb->mutex); - } - - /* Detach this backup from the source pager. */ - if( p->pDestDb ){ - p->pSrc->nBackup--; - } - if( p->isAttached ){ - pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc)); - assert( pp!=0 ); - while( *pp!=p ){ - pp = &(*pp)->pNext; - assert( pp!=0 ); - } - *pp = p->pNext; - } - - /* If a transaction is still open on the Btree, roll it back. */ - sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0); - - /* Set the error code of the destination database handle. */ - rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc; - if( p->pDestDb ){ - sqlite3Error(p->pDestDb, rc); - - /* Exit the mutexes and free the backup context structure. */ - sqlite3LeaveMutexAndCloseZombie(p->pDestDb); - } - sqlite3BtreeLeave(p->pSrc); - if( p->pDestDb ){ - /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a - ** call to sqlite3_backup_init() and is destroyed by a call to - ** sqlite3_backup_finish(). */ - sqlite3_free(p); - } - sqlite3LeaveMutexAndCloseZombie(pSrcDb); - return rc; -} - -/* -** Return the number of pages still to be backed up as of the most recent -** call to sqlite3_backup_step(). -*/ -SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( p==0 ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - return p->nRemaining; -} - -/* -** Return the total number of pages in the source database as of the most -** recent call to sqlite3_backup_step(). -*/ -SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( p==0 ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - return p->nPagecount; -} - -/* -** This function is called after the contents of page iPage of the -** source database have been modified. If page iPage has already been -** copied into the destination database, then the data written to the -** destination is now invalidated. The destination copy of iPage needs -** to be updated with the new data before the backup operation is -** complete. -** -** It is assumed that the mutex associated with the BtShared object -** corresponding to the source database is held when this function is -** called. -*/ -static SQLITE_NOINLINE void backupUpdate( - sqlite3_backup *p, - Pgno iPage, - const u8 *aData -){ - assert( p!=0 ); - do{ - assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); - if( !isFatalError(p->rc) && iPageiNext ){ - /* The backup process p has already copied page iPage. But now it - ** has been modified by a transaction on the source pager. Copy - ** the new data into the backup. - */ - int rc; - assert( p->pDestDb ); - sqlite3_mutex_enter(p->pDestDb->mutex); - rc = backupOnePage(p, iPage, aData, 1); - sqlite3_mutex_leave(p->pDestDb->mutex); - assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED ); - if( rc!=SQLITE_OK ){ - p->rc = rc; - } - } - }while( (p = p->pNext)!=0 ); -} -SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){ - if( pBackup ) backupUpdate(pBackup, iPage, aData); -} - -/* -** Restart the backup process. This is called when the pager layer -** detects that the database has been modified by an external database -** connection. In this case there is no way of knowing which of the -** pages that have been copied into the destination database are still -** valid and which are not, so the entire process needs to be restarted. -** -** It is assumed that the mutex associated with the BtShared object -** corresponding to the source database is held when this function is -** called. -*/ -SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){ - sqlite3_backup *p; /* Iterator variable */ - for(p=pBackup; p; p=p->pNext){ - assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) ); - p->iNext = 1; - } -} - -#ifndef SQLITE_OMIT_VACUUM -/* -** Copy the complete content of pBtFrom into pBtTo. A transaction -** must be active for both files. -** -** The size of file pTo may be reduced by this operation. If anything -** goes wrong, the transaction on pTo is rolled back. If successful, the -** transaction is committed before returning. -*/ -SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ - int rc; - sqlite3_file *pFd; /* File descriptor for database pTo */ - sqlite3_backup b; - sqlite3BtreeEnter(pTo); - sqlite3BtreeEnter(pFrom); - - assert( sqlite3BtreeIsInTrans(pTo) ); - pFd = sqlite3PagerFile(sqlite3BtreePager(pTo)); - if( pFd->pMethods ){ - i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom); - rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte); - if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; - if( rc ) goto copy_finished; - } - - /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set - ** to 0. This is used by the implementations of sqlite3_backup_step() - ** and sqlite3_backup_finish() to detect that they are being called - ** from this function, not directly by the user. - */ - memset(&b, 0, sizeof(b)); - b.pSrcDb = pFrom->db; - b.pSrc = pFrom; - b.pDest = pTo; - b.iNext = 1; - - /* 0x7FFFFFFF is the hard limit for the number of pages in a database - ** file. By passing this as the number of pages to copy to - ** sqlite3_backup_step(), we can guarantee that the copy finishes - ** within a single call (unless an error occurs). The assert() statement - ** checks this assumption - (p->rc) should be set to either SQLITE_DONE - ** or an error code. */ - sqlite3_backup_step(&b, 0x7FFFFFFF); - assert( b.rc!=SQLITE_OK ); - - rc = sqlite3_backup_finish(&b); - if( rc==SQLITE_OK ){ - pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED; - }else{ - sqlite3PagerClearCache(sqlite3BtreePager(b.pDest)); - } - - assert( sqlite3BtreeIsInTrans(pTo)==0 ); -copy_finished: - sqlite3BtreeLeave(pFrom); - sqlite3BtreeLeave(pTo); - return rc; -} -#endif /* SQLITE_OMIT_VACUUM */ - -/************** End of backup.c **********************************************/ -/************** Begin file vdbemem.c *****************************************/ -/* -** 2004 May 26 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains code use to manipulate "Mem" structure. A "Mem" -** stores a single value in the VDBE. Mem is an opaque structure visible -** only within the VDBE. Interface routines refer to a Mem using the -** name sqlite_value -*/ -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -/* True if X is a power of two. 0 is considered a power of two here. -** In other words, return true if X has at most one bit set. -*/ -#define ISPOWEROF2(X) (((X)&((X)-1))==0) - -#ifdef SQLITE_DEBUG -/* -** Check invariants on a Mem object. -** -** This routine is intended for use inside of assert() statements, like -** this: assert( sqlite3VdbeCheckMemInvariants(pMem) ); -*/ -SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){ - /* If MEM_Dyn is set then Mem.xDel!=0. - ** Mem.xDel might not be initialized if MEM_Dyn is clear. - */ - assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 ); - - /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we - ** ensure that if Mem.szMalloc>0 then it is safe to do - ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn. - ** That saves a few cycles in inner loops. */ - assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 ); - - /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */ - assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) ); - - if( p->flags & MEM_Null ){ - /* Cannot be both MEM_Null and some other type */ - assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 ); - - /* If MEM_Null is set, then either the value is a pure NULL (the usual - ** case) or it is a pointer set using sqlite3_bind_pointer() or - ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be - ** set. - */ - if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){ - /* This is a pointer type. There may be a flag to indicate what to - ** do with the pointer. */ - assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) + - ((p->flags&MEM_Ephem)!=0 ? 1 : 0) + - ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 ); - - /* No other bits set */ - assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind - |MEM_Dyn|MEM_Ephem|MEM_Static))==0 ); - }else{ - /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn, - ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */ - } - }else{ - /* The MEM_Cleared bit is only allowed on NULLs */ - assert( (p->flags & MEM_Cleared)==0 ); - } - - /* The szMalloc field holds the correct memory allocation size */ - assert( p->szMalloc==0 - || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) ); - - /* If p holds a string or blob, the Mem.z must point to exactly - ** one of the following: - ** - ** (1) Memory in Mem.zMalloc and managed by the Mem object - ** (2) Memory to be freed using Mem.xDel - ** (3) An ephemeral string or blob - ** (4) A static string or blob - */ - if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){ - assert( - ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) + - ((p->flags&MEM_Dyn)!=0 ? 1 : 0) + - ((p->flags&MEM_Ephem)!=0 ? 1 : 0) + - ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1 - ); - } - return 1; -} -#endif - -/* -** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal -** into a buffer. -*/ -static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){ - StrAccum acc; - assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) ); - assert( sz>22 ); - if( p->flags & MEM_Int ){ -#if GCC_VERSION>=7000000 - /* Work-around for GCC bug - ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */ - i64 x; - assert( (p->flags&MEM_Int)*2==sizeof(x) ); - memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2); - sqlite3Int64ToText(x, zBuf); -#else - sqlite3Int64ToText(p->u.i, zBuf); -#endif - }else{ - sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0); - sqlite3_str_appendf(&acc, "%!.15g", - (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r); - assert( acc.zText==zBuf && acc.mxAlloc<=0 ); - zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */ - } -} - -#ifdef SQLITE_DEBUG -/* -** Validity checks on pMem. pMem holds a string. -** -** (1) Check that string value of pMem agrees with its integer or real value. -** (2) Check that the string is correctly zero terminated -** -** A single int or real value always converts to the same strings. But -** many different strings can be converted into the same int or real. -** If a table contains a numeric value and an index is based on the -** corresponding string value, then it is important that the string be -** derived from the numeric value, not the other way around, to ensure -** that the index and table are consistent. See ticket -** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for -** an example. -** -** This routine looks at pMem to verify that if it has both a numeric -** representation and a string representation then the string rep has -** been derived from the numeric and not the other way around. It returns -** true if everything is ok and false if there is a problem. -** -** This routine is for use inside of assert() statements only. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){ - char zBuf[100]; - char *z; - int i, j, incr; - if( (p->flags & MEM_Str)==0 ) return 1; - if( p->flags & MEM_Term ){ - /* Insure that the string is properly zero-terminated. Pay particular - ** attention to the case where p->n is odd */ - if( p->szMalloc>0 && p->z==p->zMalloc ){ - assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 ); - assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 ); - } - assert( p->z[p->n]==0 ); - assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 ); - assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 ); - } - if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1; - vdbeMemRenderNum(sizeof(zBuf), zBuf, p); - z = p->z; - i = j = 0; - incr = 1; - if( p->enc!=SQLITE_UTF8 ){ - incr = 2; - if( p->enc==SQLITE_UTF16BE ) z++; - } - while( zBuf[j] ){ - if( zBuf[j++]!=z[i] ) return 0; - i += incr; - } - return 1; -} -#endif /* SQLITE_DEBUG */ - -/* -** If pMem is an object with a valid string representation, this routine -** ensures the internal encoding for the string representation is -** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE. -** -** If pMem is not a string object, or the encoding of the string -** representation is already stored using the requested encoding, then this -** routine is a no-op. -** -** SQLITE_OK is returned if the conversion is successful (or not required). -** SQLITE_NOMEM may be returned if a malloc() fails during conversion -** between formats. -*/ -SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){ -#ifndef SQLITE_OMIT_UTF16 - int rc; -#endif - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE - || desiredEnc==SQLITE_UTF16BE ); - if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){ - return SQLITE_OK; - } - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); -#ifdef SQLITE_OMIT_UTF16 - return SQLITE_ERROR; -#else - - /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned, - ** then the encoding of the value may not have changed. - */ - rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc); - assert(rc==SQLITE_OK || rc==SQLITE_NOMEM); - assert(rc==SQLITE_OK || pMem->enc!=desiredEnc); - assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc); - return rc; -#endif -} - -/* -** Make sure pMem->z points to a writable allocation of at least n bytes. -** -** If the bPreserve argument is true, then copy of the content of -** pMem->z into the new allocation. pMem must be either a string or -** blob if bPreserve is true. If bPreserve is false, any prior content -** in pMem->z is discarded. -*/ -SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){ - assert( sqlite3VdbeCheckMemInvariants(pMem) ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - testcase( pMem->db==0 ); - - /* If the bPreserve flag is set to true, then the memory cell must already - ** contain a valid string or blob value. */ - assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) ); - testcase( bPreserve && pMem->z==0 ); - - assert( pMem->szMalloc==0 - || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) ); - if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){ - if( pMem->db ){ - pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n); - }else{ - pMem->zMalloc = sqlite3Realloc(pMem->z, n); - if( pMem->zMalloc==0 ) sqlite3_free(pMem->z); - pMem->z = pMem->zMalloc; - } - bPreserve = 0; - }else{ - if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc); - pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n); - } - if( pMem->zMalloc==0 ){ - sqlite3VdbeMemSetNull(pMem); - pMem->z = 0; - pMem->szMalloc = 0; - return SQLITE_NOMEM_BKPT; - }else{ - pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); - } - - if( bPreserve && pMem->z ){ - assert( pMem->z!=pMem->zMalloc ); - memcpy(pMem->zMalloc, pMem->z, pMem->n); - } - if( (pMem->flags&MEM_Dyn)!=0 ){ - assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC ); - pMem->xDel((void *)(pMem->z)); - } - - pMem->z = pMem->zMalloc; - pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static); - return SQLITE_OK; -} - -/* -** Change the pMem->zMalloc allocation to be at least szNew bytes. -** If pMem->zMalloc already meets or exceeds the requested size, this -** routine is a no-op. -** -** Any prior string or blob content in the pMem object may be discarded. -** The pMem->xDel destructor is called, if it exists. Though MEM_Str -** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal, -** and MEM_Null values are preserved. -** -** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM) -** if unable to complete the resizing. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){ - assert( CORRUPT_DB || szNew>0 ); - assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 ); - if( pMem->szMallocflags & MEM_Dyn)==0 ); - pMem->z = pMem->zMalloc; - pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal); - return SQLITE_OK; -} - -/* -** It is already known that pMem contains an unterminated string. -** Add the zero terminator. -** -** Three bytes of zero are added. In this way, there is guaranteed -** to be a double-zero byte at an even byte boundary in order to -** terminate a UTF16 string, even if the initial size of the buffer -** is an odd number of bytes. -*/ -static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){ - if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){ - return SQLITE_NOMEM_BKPT; - } - pMem->z[pMem->n] = 0; - pMem->z[pMem->n+1] = 0; - pMem->z[pMem->n+2] = 0; - pMem->flags |= MEM_Term; - return SQLITE_OK; -} - -/* -** Change pMem so that its MEM_Str or MEM_Blob value is stored in -** MEM.zMalloc, where it can be safely written. -** -** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){ - if( ExpandBlob(pMem) ) return SQLITE_NOMEM; - if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){ - int rc = vdbeMemAddTerminator(pMem); - if( rc ) return rc; - } - } - pMem->flags &= ~MEM_Ephem; -#ifdef SQLITE_DEBUG - pMem->pScopyFrom = 0; -#endif - - return SQLITE_OK; -} - -/* -** If the given Mem* has a zero-filled tail, turn it into an ordinary -** blob stored in dynamically allocated space. -*/ -#ifndef SQLITE_OMIT_INCRBLOB -SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){ - int nByte; - assert( pMem->flags & MEM_Zero ); - assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) ); - testcase( sqlite3_value_nochange(pMem) ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - - /* Set nByte to the number of bytes required to store the expanded blob. */ - nByte = pMem->n + pMem->u.nZero; - if( nByte<=0 ){ - if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK; - nByte = 1; - } - if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){ - return SQLITE_NOMEM_BKPT; - } - - memset(&pMem->z[pMem->n], 0, pMem->u.nZero); - pMem->n += pMem->u.nZero; - pMem->flags &= ~(MEM_Zero|MEM_Term); - return SQLITE_OK; -} -#endif - -/* -** Make sure the given Mem is \u0000 terminated. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) ); - testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 ); - if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){ - return SQLITE_OK; /* Nothing to do */ - }else{ - return vdbeMemAddTerminator(pMem); - } -} - -/* -** Add MEM_Str to the set of representations for the given Mem. This -** routine is only called if pMem is a number of some kind, not a NULL -** or a BLOB. -** -** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated -** if bForce is true but are retained if bForce is false. -** -** A MEM_Null value will never be passed to this function. This function is -** used for converting values to text for returning to the user (i.e. via -** sqlite3_value_text()), or for ensuring that values to be used as btree -** keys are strings. In the former case a NULL pointer is returned the -** user and the latter is an internal programming error. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){ - const int nByte = 32; - - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( !(pMem->flags&MEM_Zero) ); - assert( !(pMem->flags&(MEM_Str|MEM_Blob)) ); - assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - - - if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){ - pMem->enc = 0; - return SQLITE_NOMEM_BKPT; - } - - vdbeMemRenderNum(nByte, pMem->z, pMem); - assert( pMem->z!=0 ); - pMem->n = sqlite3Strlen30NN(pMem->z); - pMem->enc = SQLITE_UTF8; - pMem->flags |= MEM_Str|MEM_Term; - if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal); - sqlite3VdbeChangeEncoding(pMem, enc); - return SQLITE_OK; -} - -/* -** Memory cell pMem contains the context of an aggregate function. -** This routine calls the finalize method for that function. The -** result of the aggregate is stored back into pMem. -** -** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK -** otherwise. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){ - sqlite3_context ctx; - Mem t; - assert( pFunc!=0 ); - assert( pFunc->xFinalize!=0 ); - assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - memset(&ctx, 0, sizeof(ctx)); - memset(&t, 0, sizeof(t)); - t.flags = MEM_Null; - t.db = pMem->db; - ctx.pOut = &t; - ctx.pMem = pMem; - ctx.pFunc = pFunc; - pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */ - assert( (pMem->flags & MEM_Dyn)==0 ); - if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc); - memcpy(pMem, &t, sizeof(t)); - return ctx.isError; -} - -/* -** Memory cell pAccum contains the context of an aggregate function. -** This routine calls the xValue method for that function and stores -** the results in memory cell pMem. -** -** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK -** otherwise. -*/ -#ifndef SQLITE_OMIT_WINDOWFUNC -SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){ - sqlite3_context ctx; - assert( pFunc!=0 ); - assert( pFunc->xValue!=0 ); - assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef ); - assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) ); - memset(&ctx, 0, sizeof(ctx)); - sqlite3VdbeMemSetNull(pOut); - ctx.pOut = pOut; - ctx.pMem = pAccum; - ctx.pFunc = pFunc; - pFunc->xValue(&ctx); - return ctx.isError; -} -#endif /* SQLITE_OMIT_WINDOWFUNC */ - -/* -** If the memory cell contains a value that must be freed by -** invoking the external callback in Mem.xDel, then this routine -** will free that value. It also sets Mem.flags to MEM_Null. -** -** This is a helper routine for sqlite3VdbeMemSetNull() and -** for sqlite3VdbeMemRelease(). Use those other routines as the -** entry point for releasing Mem resources. -*/ -static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){ - assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) ); - assert( VdbeMemDynamic(p) ); - if( p->flags&MEM_Agg ){ - sqlite3VdbeMemFinalize(p, p->u.pDef); - assert( (p->flags & MEM_Agg)==0 ); - testcase( p->flags & MEM_Dyn ); - } - if( p->flags&MEM_Dyn ){ - assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 ); - p->xDel((void *)p->z); - } - p->flags = MEM_Null; -} - -/* -** Release memory held by the Mem p, both external memory cleared -** by p->xDel and memory in p->zMalloc. -** -** This is a helper routine invoked by sqlite3VdbeMemRelease() in -** the unusual case where there really is memory in p that needs -** to be freed. -*/ -static SQLITE_NOINLINE void vdbeMemClear(Mem *p){ - if( VdbeMemDynamic(p) ){ - vdbeMemClearExternAndSetNull(p); - } - if( p->szMalloc ){ - sqlite3DbFreeNN(p->db, p->zMalloc); - p->szMalloc = 0; - } - p->z = 0; -} - -/* -** Release any memory resources held by the Mem. Both the memory that is -** free by Mem.xDel and the Mem.zMalloc allocation are freed. -** -** Use this routine prior to clean up prior to abandoning a Mem, or to -** reset a Mem back to its minimum memory utilization. -** -** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space -** prior to inserting new content into the Mem. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){ - assert( sqlite3VdbeCheckMemInvariants(p) ); - if( VdbeMemDynamic(p) || p->szMalloc ){ - vdbeMemClear(p); - } -} - -/* -** Convert a 64-bit IEEE double into a 64-bit signed integer. -** If the double is out of range of a 64-bit signed integer then -** return the closest available 64-bit signed integer. -*/ -static SQLITE_NOINLINE i64 doubleToInt64(double r){ -#ifdef SQLITE_OMIT_FLOATING_POINT - /* When floating-point is omitted, double and int64 are the same thing */ - return r; -#else - /* - ** Many compilers we encounter do not define constants for the - ** minimum and maximum 64-bit integers, or they define them - ** inconsistently. And many do not understand the "LL" notation. - ** So we define our own static constants here using nothing - ** larger than a 32-bit integer constant. - */ - static const i64 maxInt = LARGEST_INT64; - static const i64 minInt = SMALLEST_INT64; - - if( r<=(double)minInt ){ - return minInt; - }else if( r>=(double)maxInt ){ - return maxInt; - }else{ - return (i64)r; - } -#endif -} - -/* -** Return some kind of integer value which is the best we can do -** at representing the value that *pMem describes as an integer. -** If pMem is an integer, then the value is exact. If pMem is -** a floating-point then the value returned is the integer part. -** If pMem is a string or blob, then we make an attempt to convert -** it into an integer and return that. If pMem represents an -** an SQL-NULL value, return 0. -** -** If pMem represents a string value, its encoding might be changed. -*/ -static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){ - i64 value = 0; - sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc); - return value; -} -SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){ - int flags; - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - flags = pMem->flags; - if( flags & (MEM_Int|MEM_IntReal) ){ - testcase( flags & MEM_IntReal ); - return pMem->u.i; - }else if( flags & MEM_Real ){ - return doubleToInt64(pMem->u.r); - }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){ - return memIntValue(pMem); - }else{ - return 0; - } -} - -/* -** Return the best representation of pMem that we can get into a -** double. If pMem is already a double or an integer, return its -** value. If it is a string or blob, try to convert it to a double. -** If it is a NULL, return 0.0. -*/ -static SQLITE_NOINLINE double memRealValue(Mem *pMem){ - /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ - double val = (double)0; - sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); - return val; -} -SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - if( pMem->flags & MEM_Real ){ - return pMem->u.r; - }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){ - testcase( pMem->flags & MEM_IntReal ); - return (double)pMem->u.i; - }else if( pMem->flags & (MEM_Str|MEM_Blob) ){ - return memRealValue(pMem); - }else{ - /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ - return (double)0; - } -} - -/* -** Return 1 if pMem represents true, and return 0 if pMem represents false. -** Return the value ifNull if pMem is NULL. -*/ -SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){ - testcase( pMem->flags & MEM_IntReal ); - if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0; - if( pMem->flags & MEM_Null ) return ifNull; - return sqlite3VdbeRealValue(pMem)!=0.0; -} - -/* -** The MEM structure is already a MEM_Real. Try to also make it a -** MEM_Int if we can. -*/ -SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){ - i64 ix; - assert( pMem->flags & MEM_Real ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - - ix = doubleToInt64(pMem->u.r); - - /* Only mark the value as an integer if - ** - ** (1) the round-trip conversion real->int->real is a no-op, and - ** (2) The integer is neither the largest nor the smallest - ** possible integer (ticket #3922) - ** - ** The second and third terms in the following conditional enforces - ** the second condition under the assumption that addition overflow causes - ** values to wrap around. - */ - if( pMem->u.r==ix && ix>SMALLEST_INT64 && ixu.i = ix; - MemSetTypeFlag(pMem, MEM_Int); - } -} - -/* -** Convert pMem to type integer. Invalidate any prior representations. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - - pMem->u.i = sqlite3VdbeIntValue(pMem); - MemSetTypeFlag(pMem, MEM_Int); - return SQLITE_OK; -} - -/* -** Convert pMem so that it is of type MEM_Real. -** Invalidate any prior representations. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){ - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - - pMem->u.r = sqlite3VdbeRealValue(pMem); - MemSetTypeFlag(pMem, MEM_Real); - return SQLITE_OK; -} - -/* Compare a floating point value to an integer. Return true if the two -** values are the same within the precision of the floating point value. -** -** This function assumes that i was obtained by assignment from r1. -** -** For some versions of GCC on 32-bit machines, if you do the more obvious -** comparison of "r1==(double)i" you sometimes get an answer of false even -** though the r1 and (double)i values are bit-for-bit the same. -*/ -SQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){ - double r2 = (double)i; - return r1==0.0 - || (memcmp(&r1, &r2, sizeof(r1))==0 - && i >= -2251799813685248LL && i < 2251799813685248LL); -} - -/* -** Convert pMem so that it has type MEM_Real or MEM_Int. -** Invalidate any prior representations. -** -** Every effort is made to force the conversion, even if the input -** is a string that does not look completely like a number. Convert -** as much of the string as we can and ignore the rest. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ - testcase( pMem->flags & MEM_Int ); - testcase( pMem->flags & MEM_Real ); - testcase( pMem->flags & MEM_IntReal ); - testcase( pMem->flags & MEM_Null ); - if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){ - int rc; - sqlite3_int64 ix; - assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); - if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1) - || sqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r)) - ){ - pMem->u.i = ix; - MemSetTypeFlag(pMem, MEM_Int); - }else{ - MemSetTypeFlag(pMem, MEM_Real); - } - } - assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 ); - pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero); - return SQLITE_OK; -} - -/* -** Cast the datatype of the value in pMem according to the affinity -** "aff". Casting is different from applying affinity in that a cast -** is forced. In other words, the value is converted into the desired -** affinity even if that results in loss of data. This routine is -** used (for example) to implement the SQL "cast()" operator. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ - if( pMem->flags & MEM_Null ) return SQLITE_OK; - switch( aff ){ - case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */ - if( (pMem->flags & MEM_Blob)==0 ){ - sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); - assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); - if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob); - }else{ - pMem->flags &= ~(MEM_TypeMask&~MEM_Blob); - } - break; - } - case SQLITE_AFF_NUMERIC: { - sqlite3VdbeMemNumerify(pMem); - break; - } - case SQLITE_AFF_INTEGER: { - sqlite3VdbeMemIntegerify(pMem); - break; - } - case SQLITE_AFF_REAL: { - sqlite3VdbeMemRealify(pMem); - break; - } - default: { - assert( aff==SQLITE_AFF_TEXT ); - assert( MEM_Str==(MEM_Blob>>3) ); - pMem->flags |= (pMem->flags&MEM_Blob)>>3; - sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding); - assert( pMem->flags & MEM_Str || pMem->db->mallocFailed ); - pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero); - return sqlite3VdbeChangeEncoding(pMem, encoding); - } - } - return SQLITE_OK; -} - -/* -** Initialize bulk memory to be a consistent Mem object. -** -** The minimum amount of initialization feasible is performed. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){ - assert( (flags & ~MEM_TypeMask)==0 ); - pMem->flags = flags; - pMem->db = db; - pMem->szMalloc = 0; -} - - -/* -** Delete any previous value and set the value stored in *pMem to NULL. -** -** This routine calls the Mem.xDel destructor to dispose of values that -** require the destructor. But it preserves the Mem.zMalloc memory allocation. -** To free all resources, use sqlite3VdbeMemRelease(), which both calls this -** routine to invoke the destructor and deallocates Mem.zMalloc. -** -** Use this routine to reset the Mem prior to insert a new value. -** -** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){ - if( VdbeMemDynamic(pMem) ){ - vdbeMemClearExternAndSetNull(pMem); - }else{ - pMem->flags = MEM_Null; - } -} -SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){ - sqlite3VdbeMemSetNull((Mem*)p); -} - -/* -** Delete any previous value and set the value to be a BLOB of length -** n containing all zeros. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){ - sqlite3VdbeMemRelease(pMem); - pMem->flags = MEM_Blob|MEM_Zero; - pMem->n = 0; - if( n<0 ) n = 0; - pMem->u.nZero = n; - pMem->enc = SQLITE_UTF8; - pMem->z = 0; -} - -/* -** The pMem is known to contain content that needs to be destroyed prior -** to a value change. So invoke the destructor, then set the value to -** a 64-bit integer. -*/ -static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){ - sqlite3VdbeMemSetNull(pMem); - pMem->u.i = val; - pMem->flags = MEM_Int; -} - -/* -** Delete any previous value and set the value stored in *pMem to val, -** manifest type INTEGER. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ - if( VdbeMemDynamic(pMem) ){ - vdbeReleaseAndSetInt64(pMem, val); - }else{ - pMem->u.i = val; - pMem->flags = MEM_Int; - } -} - -/* A no-op destructor */ -SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); } - -/* -** Set the value stored in *pMem should already be a NULL. -** Also store a pointer to go with it. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemSetPointer( - Mem *pMem, - void *pPtr, - const char *zPType, - void (*xDestructor)(void*) -){ - assert( pMem->flags==MEM_Null ); - pMem->u.zPType = zPType ? zPType : ""; - pMem->z = pPtr; - pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term; - pMem->eSubtype = 'p'; - pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor; -} - -#ifndef SQLITE_OMIT_FLOATING_POINT -/* -** Delete any previous value and set the value stored in *pMem to val, -** manifest type REAL. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ - sqlite3VdbeMemSetNull(pMem); - if( !sqlite3IsNaN(val) ){ - pMem->u.r = val; - pMem->flags = MEM_Real; - } -} -#endif - -#ifdef SQLITE_DEBUG -/* -** Return true if the Mem holds a RowSet object. This routine is intended -** for use inside of assert() statements. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){ - return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn) - && pMem->xDel==sqlite3RowSetDelete; -} -#endif - -/* -** Delete any previous value and set the value of pMem to be an -** empty boolean index. -** -** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation -** error occurs. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){ - sqlite3 *db = pMem->db; - RowSet *p; - assert( db!=0 ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - sqlite3VdbeMemRelease(pMem); - p = sqlite3RowSetInit(db); - if( p==0 ) return SQLITE_NOMEM; - pMem->z = (char*)p; - pMem->flags = MEM_Blob|MEM_Dyn; - pMem->xDel = sqlite3RowSetDelete; - return SQLITE_OK; -} - -/* -** Return true if the Mem object contains a TEXT or BLOB that is -** too large - whose size exceeds SQLITE_MAX_LENGTH. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){ - assert( p->db!=0 ); - if( p->flags & (MEM_Str|MEM_Blob) ){ - int n = p->n; - if( p->flags & MEM_Zero ){ - n += p->u.nZero; - } - return n>p->db->aLimit[SQLITE_LIMIT_LENGTH]; - } - return 0; -} - -#ifdef SQLITE_DEBUG -/* -** This routine prepares a memory cell for modification by breaking -** its link to a shallow copy and by marking any current shallow -** copies of this cell as invalid. -** -** This is used for testing and debugging only - to help ensure that shallow -** copies (created by OP_SCopy) are not misused. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ - int i; - Mem *pX; - for(i=1, pX=pVdbe->aMem+1; inMem; i++, pX++){ - if( pX->pScopyFrom==pMem ){ - u16 mFlags; - if( pVdbe->db->flags & SQLITE_VdbeTrace ){ - sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n", - (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem)); - } - /* If pX is marked as a shallow copy of pMem, then try to verify that - ** no significant changes have been made to pX since the OP_SCopy. - ** A significant change would indicated a missed call to this - ** function for pX. Minor changes, such as adding or removing a - ** dual type, are allowed, as long as the underlying value is the - ** same. */ - mFlags = pMem->flags & pX->flags & pX->mScopyFlags; - assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i ); - - /* pMem is the register that is changing. But also mark pX as - ** undefined so that we can quickly detect the shallow-copy error */ - pX->flags = MEM_Undefined; - pX->pScopyFrom = 0; - } - } - pMem->pScopyFrom = 0; -} -#endif /* SQLITE_DEBUG */ - -/* -** Make an shallow copy of pFrom into pTo. Prior contents of -** pTo are freed. The pFrom->z field is not duplicated. If -** pFrom->z is used, then pTo->z points to the same thing as pFrom->z -** and flags gets srcType (either MEM_Ephem or MEM_Static). -*/ -static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){ - vdbeMemClearExternAndSetNull(pTo); - assert( !VdbeMemDynamic(pTo) ); - sqlite3VdbeMemShallowCopy(pTo, pFrom, eType); -} -SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ - assert( !sqlite3VdbeMemIsRowSet(pFrom) ); - assert( pTo->db==pFrom->db ); - if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; } - memcpy(pTo, pFrom, MEMCELLSIZE); - if( (pFrom->flags&MEM_Static)==0 ){ - pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); - assert( srcType==MEM_Ephem || srcType==MEM_Static ); - pTo->flags |= srcType; - } -} - -/* -** Make a full copy of pFrom into pTo. Prior contents of pTo are -** freed before the copy is made. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ - int rc = SQLITE_OK; - - assert( !sqlite3VdbeMemIsRowSet(pFrom) ); - if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo); - memcpy(pTo, pFrom, MEMCELLSIZE); - pTo->flags &= ~MEM_Dyn; - if( pTo->flags&(MEM_Str|MEM_Blob) ){ - if( 0==(pFrom->flags&MEM_Static) ){ - pTo->flags |= MEM_Ephem; - rc = sqlite3VdbeMemMakeWriteable(pTo); - } - } - - return rc; -} - -/* -** Transfer the contents of pFrom to pTo. Any existing value in pTo is -** freed. If pFrom contains ephemeral data, a copy is made. -** -** pFrom contains an SQL NULL when this routine returns. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ - assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) ); - assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) ); - assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); - - sqlite3VdbeMemRelease(pTo); - memcpy(pTo, pFrom, sizeof(Mem)); - pFrom->flags = MEM_Null; - pFrom->szMalloc = 0; -} - -/* -** Change the value of a Mem to be a string or a BLOB. -** -** The memory management strategy depends on the value of the xDel -** parameter. If the value passed is SQLITE_TRANSIENT, then the -** string is copied into a (possibly existing) buffer managed by the -** Mem structure. Otherwise, any existing buffer is freed and the -** pointer copied. -** -** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH -** size limit) then no memory allocation occurs. If the string can be -** stored without allocating memory, then it is. If a memory allocation -** is required to store the string, then value of pMem is unchanged. In -** either case, SQLITE_TOOBIG is returned. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemSetStr( - Mem *pMem, /* Memory cell to set to string value */ - const char *z, /* String pointer */ - int n, /* Bytes in string, or negative */ - u8 enc, /* Encoding of z. 0 for BLOBs */ - void (*xDel)(void*) /* Destructor function */ -){ - int nByte = n; /* New value for pMem->n */ - int iLimit; /* Maximum allowed string or blob size */ - u16 flags = 0; /* New value for pMem->flags */ - - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - - /* If z is a NULL pointer, set pMem to contain an SQL NULL. */ - if( !z ){ - sqlite3VdbeMemSetNull(pMem); - return SQLITE_OK; - } - - if( pMem->db ){ - iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH]; - }else{ - iLimit = SQLITE_MAX_LENGTH; - } - flags = (enc==0?MEM_Blob:MEM_Str); - if( nByte<0 ){ - assert( enc!=0 ); - if( enc==SQLITE_UTF8 ){ - nByte = 0x7fffffff & (int)strlen(z); - }else{ - for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){} - } - flags |= MEM_Term; - } - - /* The following block sets the new values of Mem.z and Mem.xDel. It - ** also sets a flag in local variable "flags" to indicate the memory - ** management (one of MEM_Dyn or MEM_Static). - */ - if( xDel==SQLITE_TRANSIENT ){ - u32 nAlloc = nByte; - if( flags&MEM_Term ){ - nAlloc += (enc==SQLITE_UTF8?1:2); - } - if( nByte>iLimit ){ - return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG); - } - testcase( nAlloc==0 ); - testcase( nAlloc==31 ); - testcase( nAlloc==32 ); - if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){ - return SQLITE_NOMEM_BKPT; - } - memcpy(pMem->z, z, nAlloc); - }else{ - sqlite3VdbeMemRelease(pMem); - pMem->z = (char *)z; - if( xDel==SQLITE_DYNAMIC ){ - pMem->zMalloc = pMem->z; - pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); - }else{ - pMem->xDel = xDel; - flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); - } - } - - pMem->n = nByte; - pMem->flags = flags; - if( enc ){ - pMem->enc = enc; -#ifdef SQLITE_ENABLE_SESSION - }else if( pMem->db==0 ){ - pMem->enc = SQLITE_UTF8; -#endif - }else{ - assert( pMem->db!=0 ); - pMem->enc = ENC(pMem->db); - } - -#ifndef SQLITE_OMIT_UTF16 - if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){ - return SQLITE_NOMEM_BKPT; - } -#endif - - if( nByte>iLimit ){ - return SQLITE_TOOBIG; - } - - return SQLITE_OK; -} - -/* -** Move data out of a btree key or data field and into a Mem structure. -** The data is payload from the entry that pCur is currently pointing -** to. offset and amt determine what portion of the data or key to retrieve. -** The result is written into the pMem element. -** -** The pMem object must have been initialized. This routine will use -** pMem->zMalloc to hold the content from the btree, if possible. New -** pMem->zMalloc space will be allocated if necessary. The calling routine -** is responsible for making sure that the pMem object is eventually -** destroyed. -** -** If this routine fails for any reason (malloc returns NULL or unable -** to read from the disk) then the pMem is left in an inconsistent state. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( - BtCursor *pCur, /* Cursor pointing at record to retrieve. */ - u32 offset, /* Offset from the start of data to return bytes from. */ - u32 amt, /* Number of bytes to return. */ - Mem *pMem /* OUT: Return data in this Mem structure. */ -){ - int rc; - pMem->flags = MEM_Null; - if( sqlite3BtreeMaxRecordSize(pCur)z); - if( rc==SQLITE_OK ){ - pMem->z[amt] = 0; /* Overrun area used when reading malformed records */ - pMem->flags = MEM_Blob; - pMem->n = (int)amt; - }else{ - sqlite3VdbeMemRelease(pMem); - } - } - return rc; -} -SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset( - BtCursor *pCur, /* Cursor pointing at record to retrieve. */ - u32 amt, /* Number of bytes to return. */ - Mem *pMem /* OUT: Return data in this Mem structure. */ -){ - u32 available = 0; /* Number of bytes available on the local btree page */ - int rc = SQLITE_OK; /* Return code */ - - assert( sqlite3BtreeCursorIsValid(pCur) ); - assert( !VdbeMemDynamic(pMem) ); - - /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() - ** that both the BtShared and database handle mutexes are held. */ - assert( !sqlite3VdbeMemIsRowSet(pMem) ); - pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available); - assert( pMem->z!=0 ); - - if( amt<=available ){ - pMem->flags = MEM_Blob|MEM_Ephem; - pMem->n = (int)amt; - }else{ - rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem); - } - - return rc; -} - -/* -** The pVal argument is known to be a value other than NULL. -** Convert it into a string with encoding enc and return a pointer -** to a zero-terminated version of that string. -*/ -static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){ - assert( pVal!=0 ); - assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); - assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); - assert( !sqlite3VdbeMemIsRowSet(pVal) ); - assert( (pVal->flags & (MEM_Null))==0 ); - if( pVal->flags & (MEM_Blob|MEM_Str) ){ - if( ExpandBlob(pVal) ) return 0; - pVal->flags |= MEM_Str; - if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){ - sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED); - } - if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){ - assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 ); - if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){ - return 0; - } - } - sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */ - }else{ - sqlite3VdbeMemStringify(pVal, enc, 0); - assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) ); - } - assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0 - || pVal->db->mallocFailed ); - if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){ - assert( sqlite3VdbeMemValidStrRep(pVal) ); - return pVal->z; - }else{ - return 0; - } -} - -/* This function is only available internally, it is not part of the -** external API. It works in a similar way to sqlite3_value_text(), -** except the data returned is in the encoding specified by the second -** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or -** SQLITE_UTF8. -** -** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED. -** If that is the case, then the result must be aligned on an even byte -** boundary. -*/ -SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){ - if( !pVal ) return 0; - assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) ); - assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) ); - assert( !sqlite3VdbeMemIsRowSet(pVal) ); - if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){ - assert( sqlite3VdbeMemValidStrRep(pVal) ); - return pVal->z; - } - if( pVal->flags&MEM_Null ){ - return 0; - } - return valueToText(pVal, enc); -} - -/* -** Create a new sqlite3_value object. -*/ -SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){ - Mem *p = sqlite3DbMallocZero(db, sizeof(*p)); - if( p ){ - p->flags = MEM_Null; - p->db = db; - } - return p; -} - -/* -** Context object passed by sqlite3Stat4ProbeSetValue() through to -** valueNew(). See comments above valueNew() for details. -*/ -struct ValueNewStat4Ctx { - Parse *pParse; - Index *pIdx; - UnpackedRecord **ppRec; - int iVal; -}; - -/* -** Allocate and return a pointer to a new sqlite3_value object. If -** the second argument to this function is NULL, the object is allocated -** by calling sqlite3ValueNew(). -** -** Otherwise, if the second argument is non-zero, then this function is -** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not -** already been allocated, allocate the UnpackedRecord structure that -** that function will return to its caller here. Then return a pointer to -** an sqlite3_value within the UnpackedRecord.a[] array. -*/ -static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ -#ifdef SQLITE_ENABLE_STAT4 - if( p ){ - UnpackedRecord *pRec = p->ppRec[0]; - - if( pRec==0 ){ - Index *pIdx = p->pIdx; /* Index being probed */ - int nByte; /* Bytes of space to allocate */ - int i; /* Counter variable */ - int nCol = pIdx->nColumn; /* Number of index columns including rowid */ - - nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord)); - pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte); - if( pRec ){ - pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx); - if( pRec->pKeyInfo ){ - assert( pRec->pKeyInfo->nAllField==nCol ); - assert( pRec->pKeyInfo->enc==ENC(db) ); - pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord))); - for(i=0; iaMem[i].flags = MEM_Null; - pRec->aMem[i].db = db; - } - }else{ - sqlite3DbFreeNN(db, pRec); - pRec = 0; - } - } - if( pRec==0 ) return 0; - p->ppRec[0] = pRec; - } - - pRec->nField = p->iVal+1; - return &pRec->aMem[p->iVal]; - } -#else - UNUSED_PARAMETER(p); -#endif /* defined(SQLITE_ENABLE_STAT4) */ - return sqlite3ValueNew(db); -} - -/* -** The expression object indicated by the second argument is guaranteed -** to be a scalar SQL function. If -** -** * all function arguments are SQL literals, -** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and -** * the SQLITE_FUNC_NEEDCOLL function flag is not set, -** -** then this routine attempts to invoke the SQL function. Assuming no -** error occurs, output parameter (*ppVal) is set to point to a value -** object containing the result before returning SQLITE_OK. -** -** Affinity aff is applied to the result of the function before returning. -** If the result is a text value, the sqlite3_value object uses encoding -** enc. -** -** If the conditions above are not met, this function returns SQLITE_OK -** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to -** NULL and an SQLite error code returned. -*/ -#ifdef SQLITE_ENABLE_STAT4 -static int valueFromFunction( - sqlite3 *db, /* The database connection */ - Expr *p, /* The expression to evaluate */ - u8 enc, /* Encoding to use */ - u8 aff, /* Affinity to use */ - sqlite3_value **ppVal, /* Write the new value here */ - struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */ -){ - sqlite3_context ctx; /* Context object for function invocation */ - sqlite3_value **apVal = 0; /* Function arguments */ - int nVal = 0; /* Size of apVal[] array */ - FuncDef *pFunc = 0; /* Function definition */ - sqlite3_value *pVal = 0; /* New value */ - int rc = SQLITE_OK; /* Return code */ - ExprList *pList = 0; /* Function arguments */ - int i; /* Iterator variable */ - - assert( pCtx!=0 ); - assert( (p->flags & EP_TokenOnly)==0 ); - pList = p->x.pList; - if( pList ) nVal = pList->nExpr; - pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0); - assert( pFunc ); - if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 - || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) - ){ - return SQLITE_OK; - } - - if( pList ){ - apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal); - if( apVal==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto value_from_function_out; - } - for(i=0; ia[i].pExpr, enc, aff, &apVal[i]); - if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out; - } - } - - pVal = valueNew(db, pCtx); - if( pVal==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto value_from_function_out; - } - - assert( pCtx->pParse->rc==SQLITE_OK ); - memset(&ctx, 0, sizeof(ctx)); - ctx.pOut = pVal; - ctx.pFunc = pFunc; - pFunc->xSFunc(&ctx, nVal, apVal); - if( ctx.isError ){ - rc = ctx.isError; - sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal)); - }else{ - sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8); - assert( rc==SQLITE_OK ); - rc = sqlite3VdbeChangeEncoding(pVal, enc); - if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){ - rc = SQLITE_TOOBIG; - pCtx->pParse->nErr++; - } - } - pCtx->pParse->rc = rc; - - value_from_function_out: - if( rc!=SQLITE_OK ){ - pVal = 0; - } - if( apVal ){ - for(i=0; iop)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft; -#if defined(SQLITE_ENABLE_STAT4) - if( op==TK_REGISTER ) op = pExpr->op2; -#else - if( NEVER(op==TK_REGISTER) ) op = pExpr->op2; -#endif - - /* Compressed expressions only appear when parsing the DEFAULT clause - ** on a table column definition, and hence only when pCtx==0. This - ** check ensures that an EP_TokenOnly expression is never passed down - ** into valueFromFunction(). */ - assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 ); - - if( op==TK_CAST ){ - u8 aff = sqlite3AffinityType(pExpr->u.zToken,0); - rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx); - testcase( rc!=SQLITE_OK ); - if( *ppVal ){ - sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8); - sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8); - } - return rc; - } - - /* Handle negative integers in a single step. This is needed in the - ** case when the value is -9223372036854775808. - */ - if( op==TK_UMINUS - && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){ - pExpr = pExpr->pLeft; - op = pExpr->op; - negInt = -1; - zNeg = "-"; - } - - if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){ - pVal = valueNew(db, pCtx); - if( pVal==0 ) goto no_mem; - if( ExprHasProperty(pExpr, EP_IntValue) ){ - sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt); - }else{ - zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken); - if( zVal==0 ) goto no_mem; - sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC); - } - if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){ - sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8); - }else{ - sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8); - } - assert( (pVal->flags & MEM_IntReal)==0 ); - if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){ - testcase( pVal->flags & MEM_Int ); - testcase( pVal->flags & MEM_Real ); - pVal->flags &= ~MEM_Str; - } - if( enc!=SQLITE_UTF8 ){ - rc = sqlite3VdbeChangeEncoding(pVal, enc); - } - }else if( op==TK_UMINUS ) { - /* This branch happens for multiple negative signs. Ex: -(-5) */ - if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx) - && pVal!=0 - ){ - sqlite3VdbeMemNumerify(pVal); - if( pVal->flags & MEM_Real ){ - pVal->u.r = -pVal->u.r; - }else if( pVal->u.i==SMALLEST_INT64 ){ -#ifndef SQLITE_OMIT_FLOATING_POINT - pVal->u.r = -(double)SMALLEST_INT64; -#else - pVal->u.r = LARGEST_INT64; -#endif - MemSetTypeFlag(pVal, MEM_Real); - }else{ - pVal->u.i = -pVal->u.i; - } - sqlite3ValueApplyAffinity(pVal, affinity, enc); - } - }else if( op==TK_NULL ){ - pVal = valueNew(db, pCtx); - if( pVal==0 ) goto no_mem; - sqlite3VdbeMemSetNull(pVal); - } -#ifndef SQLITE_OMIT_BLOB_LITERAL - else if( op==TK_BLOB ){ - int nVal; - assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); - assert( pExpr->u.zToken[1]=='\'' ); - pVal = valueNew(db, pCtx); - if( !pVal ) goto no_mem; - zVal = &pExpr->u.zToken[2]; - nVal = sqlite3Strlen30(zVal)-1; - assert( zVal[nVal]=='\'' ); - sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2, - 0, SQLITE_DYNAMIC); - } -#endif -#ifdef SQLITE_ENABLE_STAT4 - else if( op==TK_FUNCTION && pCtx!=0 ){ - rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx); - } -#endif - else if( op==TK_TRUEFALSE ){ - pVal = valueNew(db, pCtx); - if( pVal ){ - pVal->flags = MEM_Int; - pVal->u.i = pExpr->u.zToken[4]==0; - } - } - - *ppVal = pVal; - return rc; - -no_mem: -#ifdef SQLITE_ENABLE_STAT4 - if( pCtx==0 || pCtx->pParse->nErr==0 ) -#endif - sqlite3OomFault(db); - sqlite3DbFree(db, zVal); - assert( *ppVal==0 ); -#ifdef SQLITE_ENABLE_STAT4 - if( pCtx==0 ) sqlite3ValueFree(pVal); -#else - assert( pCtx==0 ); sqlite3ValueFree(pVal); -#endif - return SQLITE_NOMEM_BKPT; -} - -/* -** Create a new sqlite3_value object, containing the value of pExpr. -** -** This only works for very simple expressions that consist of one constant -** token (i.e. "5", "5.1", "'a string'"). If the expression can -** be converted directly into a value, then the value is allocated and -** a pointer written to *ppVal. The caller is responsible for deallocating -** the value by passing it to sqlite3ValueFree() later on. If the expression -** cannot be converted to a value, then *ppVal is set to NULL. -*/ -SQLITE_PRIVATE int sqlite3ValueFromExpr( - sqlite3 *db, /* The database connection */ - Expr *pExpr, /* The expression to evaluate */ - u8 enc, /* Encoding to use */ - u8 affinity, /* Affinity to use */ - sqlite3_value **ppVal /* Write the new value here */ -){ - return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0; -} - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Attempt to extract a value from pExpr and use it to construct *ppVal. -** -** If pAlloc is not NULL, then an UnpackedRecord object is created for -** pAlloc if one does not exist and the new value is added to the -** UnpackedRecord object. -** -** A value is extracted in the following cases: -** -** * (pExpr==0). In this case the value is assumed to be an SQL NULL, -** -** * The expression is a bound variable, and this is a reprepare, or -** -** * The expression is a literal value. -** -** On success, *ppVal is made to point to the extracted value. The caller -** is responsible for ensuring that the value is eventually freed. -*/ -static int stat4ValueFromExpr( - Parse *pParse, /* Parse context */ - Expr *pExpr, /* The expression to extract a value from */ - u8 affinity, /* Affinity to use */ - struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */ - sqlite3_value **ppVal /* OUT: New value object (or NULL) */ -){ - int rc = SQLITE_OK; - sqlite3_value *pVal = 0; - sqlite3 *db = pParse->db; - - /* Skip over any TK_COLLATE nodes */ - pExpr = sqlite3ExprSkipCollate(pExpr); - - assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE ); - if( !pExpr ){ - pVal = valueNew(db, pAlloc); - if( pVal ){ - sqlite3VdbeMemSetNull((Mem*)pVal); - } - }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){ - Vdbe *v; - int iBindVar = pExpr->iColumn; - sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); - if( (v = pParse->pReprepare)!=0 ){ - pVal = valueNew(db, pAlloc); - if( pVal ){ - rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]); - sqlite3ValueApplyAffinity(pVal, affinity, ENC(db)); - pVal->db = pParse->db; - } - } - }else{ - rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc); - } - - assert( pVal==0 || pVal->db==db ); - *ppVal = pVal; - return rc; -} - -/* -** This function is used to allocate and populate UnpackedRecord -** structures intended to be compared against sample index keys stored -** in the sqlite_stat4 table. -** -** A single call to this function populates zero or more fields of the -** record starting with field iVal (fields are numbered from left to -** right starting with 0). A single field is populated if: -** -** * (pExpr==0). In this case the value is assumed to be an SQL NULL, -** -** * The expression is a bound variable, and this is a reprepare, or -** -** * The sqlite3ValueFromExpr() function is able to extract a value -** from the expression (i.e. the expression is a literal value). -** -** Or, if pExpr is a TK_VECTOR, one field is populated for each of the -** vector components that match either of the two latter criteria listed -** above. -** -** Before any value is appended to the record, the affinity of the -** corresponding column within index pIdx is applied to it. Before -** this function returns, output parameter *pnExtract is set to the -** number of values appended to the record. -** -** When this function is called, *ppRec must either point to an object -** allocated by an earlier call to this function, or must be NULL. If it -** is NULL and a value can be successfully extracted, a new UnpackedRecord -** is allocated (and *ppRec set to point to it) before returning. -** -** Unless an error is encountered, SQLITE_OK is returned. It is not an -** error if a value cannot be extracted from pExpr. If an error does -** occur, an SQLite error code is returned. -*/ -SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( - Parse *pParse, /* Parse context */ - Index *pIdx, /* Index being probed */ - UnpackedRecord **ppRec, /* IN/OUT: Probe record */ - Expr *pExpr, /* The expression to extract a value from */ - int nElem, /* Maximum number of values to append */ - int iVal, /* Array element to populate */ - int *pnExtract /* OUT: Values appended to the record */ -){ - int rc = SQLITE_OK; - int nExtract = 0; - - if( pExpr==0 || pExpr->op!=TK_SELECT ){ - int i; - struct ValueNewStat4Ctx alloc; - - alloc.pParse = pParse; - alloc.pIdx = pIdx; - alloc.ppRec = ppRec; - - for(i=0; idb, pIdx, iVal+i); - alloc.iVal = iVal+i; - rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal); - if( !pVal ) break; - nExtract++; - } - } - - *pnExtract = nExtract; - return rc; -} - -/* -** Attempt to extract a value from expression pExpr using the methods -** as described for sqlite3Stat4ProbeSetValue() above. -** -** If successful, set *ppVal to point to a new value object and return -** SQLITE_OK. If no value can be extracted, but no other error occurs -** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error -** does occur, return an SQLite error code. The final value of *ppVal -** is undefined in this case. -*/ -SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr( - Parse *pParse, /* Parse context */ - Expr *pExpr, /* The expression to extract a value from */ - u8 affinity, /* Affinity to use */ - sqlite3_value **ppVal /* OUT: New value object (or NULL) */ -){ - return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal); -} - -/* -** Extract the iCol-th column from the nRec-byte record in pRec. Write -** the column value into *ppVal. If *ppVal is initially NULL then a new -** sqlite3_value object is allocated. -** -** If *ppVal is initially NULL then the caller is responsible for -** ensuring that the value written into *ppVal is eventually freed. -*/ -SQLITE_PRIVATE int sqlite3Stat4Column( - sqlite3 *db, /* Database handle */ - const void *pRec, /* Pointer to buffer containing record */ - int nRec, /* Size of buffer pRec in bytes */ - int iCol, /* Column to extract */ - sqlite3_value **ppVal /* OUT: Extracted value */ -){ - u32 t = 0; /* a column type code */ - int nHdr; /* Size of the header in the record */ - int iHdr; /* Next unread header byte */ - int iField; /* Next unread data byte */ - int szField = 0; /* Size of the current data field */ - int i; /* Column index */ - u8 *a = (u8*)pRec; /* Typecast byte array */ - Mem *pMem = *ppVal; /* Write result into this Mem object */ - - assert( iCol>0 ); - iHdr = getVarint32(a, nHdr); - if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT; - iField = nHdr; - for(i=0; i<=iCol; i++){ - iHdr += getVarint32(&a[iHdr], t); - testcase( iHdr==nHdr ); - testcase( iHdr==nHdr+1 ); - if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT; - szField = sqlite3VdbeSerialTypeLen(t); - iField += szField; - } - testcase( iField==nRec ); - testcase( iField==nRec+1 ); - if( iField>nRec ) return SQLITE_CORRUPT_BKPT; - if( pMem==0 ){ - pMem = *ppVal = sqlite3ValueNew(db); - if( pMem==0 ) return SQLITE_NOMEM_BKPT; - } - sqlite3VdbeSerialGet(&a[iField-szField], t, pMem); - pMem->enc = ENC(db); - return SQLITE_OK; -} - -/* -** Unless it is NULL, the argument must be an UnpackedRecord object returned -** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes -** the object. -*/ -SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){ - if( pRec ){ - int i; - int nCol = pRec->pKeyInfo->nAllField; - Mem *aMem = pRec->aMem; - sqlite3 *db = aMem[0].db; - for(i=0; ipKeyInfo); - sqlite3DbFreeNN(db, pRec); - } -} -#endif /* ifdef SQLITE_ENABLE_STAT4 */ - -/* -** Change the string value of an sqlite3_value object -*/ -SQLITE_PRIVATE void sqlite3ValueSetStr( - sqlite3_value *v, /* Value to be set */ - int n, /* Length of string z */ - const void *z, /* Text of the new string */ - u8 enc, /* Encoding to use */ - void (*xDel)(void*) /* Destructor for the string */ -){ - if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel); -} - -/* -** Free an sqlite3_value object -*/ -SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){ - if( !v ) return; - sqlite3VdbeMemRelease((Mem *)v); - sqlite3DbFreeNN(((Mem*)v)->db, v); -} - -/* -** The sqlite3ValueBytes() routine returns the number of bytes in the -** sqlite3_value object assuming that it uses the encoding "enc". -** The valueBytes() routine is a helper function. -*/ -static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){ - return valueToText(pVal, enc)!=0 ? pVal->n : 0; -} -SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){ - Mem *p = (Mem*)pVal; - assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 ); - if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){ - return p->n; - } - if( (p->flags & MEM_Blob)!=0 ){ - if( p->flags & MEM_Zero ){ - return p->n + p->u.nZero; - }else{ - return p->n; - } - } - if( p->flags & MEM_Null ) return 0; - return valueBytes(pVal, enc); -} - -/************** End of vdbemem.c *********************************************/ -/************** Begin file vdbeaux.c *****************************************/ -/* -** 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 file contains code used for creating, destroying, and populating -** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) -*/ -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -/* Forward references */ -static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef); -static void vdbeFreeOpArray(sqlite3 *, Op *, int); - -/* -** Create a new virtual database engine. -*/ -SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){ - sqlite3 *db = pParse->db; - Vdbe *p; - p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) ); - if( p==0 ) return 0; - memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp)); - p->db = db; - if( db->pVdbe ){ - db->pVdbe->pPrev = p; - } - p->pNext = db->pVdbe; - p->pPrev = 0; - db->pVdbe = p; - p->magic = VDBE_MAGIC_INIT; - p->pParse = pParse; - pParse->pVdbe = p; - assert( pParse->aLabel==0 ); - assert( pParse->nLabel==0 ); - assert( p->nOpAlloc==0 ); - assert( pParse->szOpAlloc==0 ); - sqlite3VdbeAddOp2(p, OP_Init, 0, 1); - return p; -} - -/* -** Return the Parse object that owns a Vdbe object. -*/ -SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe *p){ - return p->pParse; -} - -/* -** Change the error string stored in Vdbe.zErrMsg -*/ -SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){ - va_list ap; - sqlite3DbFree(p->db, p->zErrMsg); - va_start(ap, zFormat); - p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap); - va_end(ap); -} - -/* -** Remember the SQL string for a prepared statement. -*/ -SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){ - if( p==0 ) return; - p->prepFlags = prepFlags; - if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){ - p->expmask = 0; - } - assert( p->zSql==0 ); - p->zSql = sqlite3DbStrNDup(p->db, z, n); -} - -#ifdef SQLITE_ENABLE_NORMALIZE -/* -** Add a new element to the Vdbe->pDblStr list. -*/ -SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){ - if( p ){ - int n = sqlite3Strlen30(z); - DblquoteStr *pStr = sqlite3DbMallocRawNN(db, - sizeof(*pStr)+n+1-sizeof(pStr->z)); - if( pStr ){ - pStr->pNextStr = p->pDblStr; - p->pDblStr = pStr; - memcpy(pStr->z, z, n+1); - } - } -} -#endif - -#ifdef SQLITE_ENABLE_NORMALIZE -/* -** zId of length nId is a double-quoted identifier. Check to see if -** that identifier is really used as a string literal. -*/ -SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString( - Vdbe *pVdbe, /* The prepared statement */ - const char *zId /* The double-quoted identifier, already dequoted */ -){ - DblquoteStr *pStr; - assert( zId!=0 ); - if( pVdbe->pDblStr==0 ) return 0; - for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){ - if( strcmp(zId, pStr->z)==0 ) return 1; - } - return 0; -} -#endif - -/* -** Swap all content between two VDBE structures. -*/ -SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ - Vdbe tmp, *pTmp; - char *zTmp; - assert( pA->db==pB->db ); - tmp = *pA; - *pA = *pB; - *pB = tmp; - pTmp = pA->pNext; - pA->pNext = pB->pNext; - pB->pNext = pTmp; - pTmp = pA->pPrev; - pA->pPrev = pB->pPrev; - pB->pPrev = pTmp; - zTmp = pA->zSql; - pA->zSql = pB->zSql; - pB->zSql = zTmp; -#ifdef SQLITE_ENABLE_NORMALIZE - zTmp = pA->zNormSql; - pA->zNormSql = pB->zNormSql; - pB->zNormSql = zTmp; -#endif - pB->expmask = pA->expmask; - pB->prepFlags = pA->prepFlags; - memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter)); - pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++; -} - -/* -** Resize the Vdbe.aOp array so that it is at least nOp elements larger -** than its current size. nOp is guaranteed to be less than or equal -** to 1024/sizeof(Op). -** -** If an out-of-memory error occurs while resizing the array, return -** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain -** unchanged (this is so that any opcodes already allocated can be -** correctly deallocated along with the rest of the Vdbe). -*/ -static int growOpArray(Vdbe *v, int nOp){ - VdbeOp *pNew; - Parse *p = v->pParse; - - /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force - ** more frequent reallocs and hence provide more opportunities for - ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used - ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array - ** by the minimum* amount required until the size reaches 512. Normal - ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current - ** size of the op array or add 1KB of space, whichever is smaller. */ -#ifdef SQLITE_TEST_REALLOC_STRESS - sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc - : (sqlite3_int64)v->nOpAlloc+nOp); -#else - sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc - : (sqlite3_int64)(1024/sizeof(Op))); - UNUSED_PARAMETER(nOp); -#endif - - /* Ensure that the size of a VDBE does not grow too large */ - if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){ - sqlite3OomFault(p->db); - return SQLITE_NOMEM; - } - - assert( nOp<=(1024/sizeof(Op)) ); - assert( nNew>=(v->nOpAlloc+nOp) ); - pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op)); - if( pNew ){ - p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew); - v->nOpAlloc = p->szOpAlloc/sizeof(Op); - v->aOp = pNew; - } - return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT); -} - -#ifdef SQLITE_DEBUG -/* This routine is just a convenient place to set a breakpoint that will -** fire after each opcode is inserted and displayed using -** "PRAGMA vdbe_addoptrace=on". Parameters "pc" (program counter) and -** pOp are available to make the breakpoint conditional. -** -** Other useful labels for breakpoints include: -** test_trace_breakpoint(pc,pOp) -** sqlite3CorruptError(lineno) -** sqlite3MisuseError(lineno) -** sqlite3CantopenError(lineno) -*/ -static void test_addop_breakpoint(int pc, Op *pOp){ - static int n = 0; - n++; -} -#endif - -/* -** Add a new instruction to the list of instructions current in the -** VDBE. Return the address of the new instruction. -** -** Parameters: -** -** p Pointer to the VDBE -** -** op The opcode for this instruction -** -** p1, p2, p3 Operands -** -** Use the sqlite3VdbeResolveLabel() function to fix an address and -** the sqlite3VdbeChangeP4() function to change the value of the P4 -** operand. -*/ -static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){ - assert( p->nOpAlloc<=p->nOp ); - if( growOpArray(p, 1) ) return 1; - assert( p->nOpAlloc>p->nOp ); - return sqlite3VdbeAddOp3(p, op, p1, p2, p3); -} -SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ - int i; - VdbeOp *pOp; - - i = p->nOp; - assert( p->magic==VDBE_MAGIC_INIT ); - assert( op>=0 && op<0xff ); - if( p->nOpAlloc<=i ){ - return growOp3(p, op, p1, p2, p3); - } - p->nOp++; - pOp = &p->aOp[i]; - pOp->opcode = (u8)op; - pOp->p5 = 0; - pOp->p1 = p1; - pOp->p2 = p2; - pOp->p3 = p3; - pOp->p4.p = 0; - pOp->p4type = P4_NOTUSED; -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - pOp->zComment = 0; -#endif -#ifdef SQLITE_DEBUG - if( p->db->flags & SQLITE_VdbeAddopTrace ){ - sqlite3VdbePrintOp(0, i, &p->aOp[i]); - test_addop_breakpoint(i, &p->aOp[i]); - } -#endif -#ifdef VDBE_PROFILE - pOp->cycles = 0; - pOp->cnt = 0; -#endif -#ifdef SQLITE_VDBE_COVERAGE - pOp->iSrcLine = 0; -#endif - return i; -} -SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){ - return sqlite3VdbeAddOp3(p, op, 0, 0, 0); -} -SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ - return sqlite3VdbeAddOp3(p, op, p1, 0, 0); -} -SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ - return sqlite3VdbeAddOp3(p, op, p1, p2, 0); -} - -/* Generate code for an unconditional jump to instruction iDest -*/ -SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){ - return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0); -} - -/* Generate code to cause the string zStr to be loaded into -** register iDest -*/ -SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){ - return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0); -} - -/* -** Generate code that initializes multiple registers to string or integer -** constants. The registers begin with iDest and increase consecutively. -** One register is initialized for each characgter in zTypes[]. For each -** "s" character in zTypes[], the register is a string if the argument is -** not NULL, or OP_Null if the value is a null pointer. For each "i" character -** in zTypes[], the register is initialized to an integer. -** -** If the input string does not end with "X" then an OP_ResultRow instruction -** is generated for the values inserted. -*/ -SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){ - va_list ap; - int i; - char c; - va_start(ap, zTypes); - for(i=0; (c = zTypes[i])!=0; i++){ - if( c=='s' ){ - const char *z = va_arg(ap, const char*); - sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0); - }else if( c=='i' ){ - sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i); - }else{ - goto skip_op_resultrow; - } - } - sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i); -skip_op_resultrow: - va_end(ap); -} - -/* -** Add an opcode that includes the p4 value as a pointer. -*/ -SQLITE_PRIVATE int sqlite3VdbeAddOp4( - Vdbe *p, /* Add the opcode to this VM */ - int op, /* The new opcode */ - int p1, /* The P1 operand */ - int p2, /* The P2 operand */ - int p3, /* The P3 operand */ - const char *zP4, /* The P4 operand */ - int p4type /* P4 operand type */ -){ - int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); - sqlite3VdbeChangeP4(p, addr, zP4, p4type); - return addr; -} - -/* -** Add an OP_Function or OP_PureFunc opcode. -** -** The eCallCtx argument is information (typically taken from Expr.op2) -** that describes the calling context of the function. 0 means a general -** function call. NC_IsCheck means called by a check constraint, -** NC_IdxExpr means called as part of an index expression. NC_PartIdx -** means in the WHERE clause of a partial index. NC_GenCol means called -** while computing a generated column value. 0 is the usual case. -*/ -SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall( - Parse *pParse, /* Parsing context */ - int p1, /* Constant argument mask */ - int p2, /* First argument register */ - int p3, /* Register into which results are written */ - int nArg, /* Number of argument */ - const FuncDef *pFunc, /* The function to be invoked */ - int eCallCtx /* Calling context */ -){ - Vdbe *v = pParse->pVdbe; - int nByte; - int addr; - sqlite3_context *pCtx; - assert( v ); - nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*); - pCtx = sqlite3DbMallocRawNN(pParse->db, nByte); - if( pCtx==0 ){ - assert( pParse->db->mallocFailed ); - freeEphemeralFunction(pParse->db, (FuncDef*)pFunc); - return 0; - } - pCtx->pOut = 0; - pCtx->pFunc = (FuncDef*)pFunc; - pCtx->pVdbe = 0; - pCtx->isError = 0; - pCtx->argc = nArg; - pCtx->iOp = sqlite3VdbeCurrentAddr(v); - addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function, - p1, p2, p3, (char*)pCtx, P4_FUNCCTX); - sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef); - return addr; -} - -/* -** Add an opcode that includes the p4 value with a P4_INT64 or -** P4_REAL type. -*/ -SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8( - Vdbe *p, /* Add the opcode to this VM */ - int op, /* The new opcode */ - int p1, /* The P1 operand */ - int p2, /* The P2 operand */ - int p3, /* The P3 operand */ - const u8 *zP4, /* The P4 operand */ - int p4type /* P4 operand type */ -){ - char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8); - if( p4copy ) memcpy(p4copy, zP4, 8); - return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type); -} - -#ifndef SQLITE_OMIT_EXPLAIN -/* -** Return the address of the current EXPLAIN QUERY PLAN baseline. -** 0 means "none". -*/ -SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){ - VdbeOp *pOp; - if( pParse->addrExplain==0 ) return 0; - pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain); - return pOp->p2; -} - -/* -** Set a debugger breakpoint on the following routine in order to -** monitor the EXPLAIN QUERY PLAN code generation. -*/ -#if defined(SQLITE_DEBUG) -SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){ - (void)z1; - (void)z2; -} -#endif - -/* -** Add a new OP_Explain opcode. -** -** If the bPush flag is true, then make this opcode the parent for -** subsequent Explains until sqlite3VdbeExplainPop() is called. -*/ -SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){ -#ifndef SQLITE_DEBUG - /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined. - ** But omit them (for performance) during production builds */ - if( pParse->explain==2 ) -#endif - { - char *zMsg; - Vdbe *v; - va_list ap; - int iThis; - va_start(ap, zFmt); - zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap); - va_end(ap); - v = pParse->pVdbe; - iThis = v->nOp; - sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0, - zMsg, P4_DYNAMIC); - sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z); - if( bPush){ - pParse->addrExplain = iThis; - } - } -} - -/* -** Pop the EXPLAIN QUERY PLAN stack one level. -*/ -SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){ - sqlite3ExplainBreakpoint("POP", 0); - pParse->addrExplain = sqlite3VdbeExplainParent(pParse); -} -#endif /* SQLITE_OMIT_EXPLAIN */ - -/* -** Add an OP_ParseSchema opcode. This routine is broken out from -** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees -** as having been used. -** -** The zWhere string must have been obtained from sqlite3_malloc(). -** This routine will take ownership of the allocated memory. -*/ -SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){ - int j; - sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC); - for(j=0; jdb->nDb; j++) sqlite3VdbeUsesBtree(p, j); -} - -/* -** Add an opcode that includes the p4 value as an integer. -*/ -SQLITE_PRIVATE int sqlite3VdbeAddOp4Int( - Vdbe *p, /* Add the opcode to this VM */ - int op, /* The new opcode */ - int p1, /* The P1 operand */ - int p2, /* The P2 operand */ - int p3, /* The P3 operand */ - int p4 /* The P4 operand as an integer */ -){ - int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); - if( p->db->mallocFailed==0 ){ - VdbeOp *pOp = &p->aOp[addr]; - pOp->p4type = P4_INT32; - pOp->p4.i = p4; - } - return addr; -} - -/* Insert the end of a co-routine -*/ -SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){ - sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield); - - /* Clear the temporary register cache, thereby ensuring that each - ** co-routine has its own independent set of registers, because co-routines - ** might expect their registers to be preserved across an OP_Yield, and - ** that could cause problems if two or more co-routines are using the same - ** temporary register. - */ - v->pParse->nTempReg = 0; - v->pParse->nRangeReg = 0; -} - -/* -** Create a new symbolic label for an instruction that has yet to be -** coded. The symbolic label is really just a negative number. The -** label can be used as the P2 value of an operation. Later, when -** the label is resolved to a specific address, the VDBE will scan -** through its operation list and change all values of P2 which match -** the label into the resolved address. -** -** The VDBE knows that a P2 value is a label because labels are -** always negative and P2 values are suppose to be non-negative. -** Hence, a negative P2 value is a label that has yet to be resolved. -** (Later:) This is only true for opcodes that have the OPFLG_JUMP -** property. -** -** Variable usage notes: -** -** Parse.aLabel[x] Stores the address that the x-th label resolves -** into. For testing (SQLITE_DEBUG), unresolved -** labels stores -1, but that is not required. -** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[] -** Parse.nLabel The *negative* of the number of labels that have -** been issued. The negative is stored because -** that gives a performance improvement over storing -** the equivalent positive value. -*/ -SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){ - return --pParse->nLabel; -} - -/* -** Resolve label "x" to be the address of the next instruction to -** be inserted. The parameter "x" must have been obtained from -** a prior call to sqlite3VdbeMakeLabel(). -*/ -static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){ - int nNewSize = 10 - p->nLabel; - p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, - nNewSize*sizeof(p->aLabel[0])); - if( p->aLabel==0 ){ - p->nLabelAlloc = 0; - }else{ -#ifdef SQLITE_DEBUG - int i; - for(i=p->nLabelAlloc; iaLabel[i] = -1; -#endif - p->nLabelAlloc = nNewSize; - p->aLabel[j] = v->nOp; - } -} -SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){ - Parse *p = v->pParse; - int j = ADDR(x); - assert( v->magic==VDBE_MAGIC_INIT ); - assert( j<-p->nLabel ); - assert( j>=0 ); -#ifdef SQLITE_DEBUG - if( p->db->flags & SQLITE_VdbeAddopTrace ){ - printf("RESOLVE LABEL %d to %d\n", x, v->nOp); - } -#endif - if( p->nLabelAlloc + p->nLabel < 0 ){ - resizeResolveLabel(p,v,j); - }else{ - assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */ - p->aLabel[j] = v->nOp; - } -} - -/* -** Mark the VDBE as one that can only be run one time. -*/ -SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){ - p->runOnlyOnce = 1; -} - -/* -** Mark the VDBE as one that can only be run multiple times. -*/ -SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){ - p->runOnlyOnce = 0; -} - -#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ - -/* -** The following type and function are used to iterate through all opcodes -** in a Vdbe main program and each of the sub-programs (triggers) it may -** invoke directly or indirectly. It should be used as follows: -** -** Op *pOp; -** VdbeOpIter sIter; -** -** memset(&sIter, 0, sizeof(sIter)); -** sIter.v = v; // v is of type Vdbe* -** while( (pOp = opIterNext(&sIter)) ){ -** // Do something with pOp -** } -** sqlite3DbFree(v->db, sIter.apSub); -** -*/ -typedef struct VdbeOpIter VdbeOpIter; -struct VdbeOpIter { - Vdbe *v; /* Vdbe to iterate through the opcodes of */ - SubProgram **apSub; /* Array of subprograms */ - int nSub; /* Number of entries in apSub */ - int iAddr; /* Address of next instruction to return */ - int iSub; /* 0 = main program, 1 = first sub-program etc. */ -}; -static Op *opIterNext(VdbeOpIter *p){ - Vdbe *v = p->v; - Op *pRet = 0; - Op *aOp; - int nOp; - - if( p->iSub<=p->nSub ){ - - if( p->iSub==0 ){ - aOp = v->aOp; - nOp = v->nOp; - }else{ - aOp = p->apSub[p->iSub-1]->aOp; - nOp = p->apSub[p->iSub-1]->nOp; - } - assert( p->iAddriAddr]; - p->iAddr++; - if( p->iAddr==nOp ){ - p->iSub++; - p->iAddr = 0; - } - - if( pRet->p4type==P4_SUBPROGRAM ){ - int nByte = (p->nSub+1)*sizeof(SubProgram*); - int j; - for(j=0; jnSub; j++){ - if( p->apSub[j]==pRet->p4.pProgram ) break; - } - if( j==p->nSub ){ - p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte); - if( !p->apSub ){ - pRet = 0; - }else{ - p->apSub[p->nSub++] = pRet->p4.pProgram; - } - } - } - } - - return pRet; -} - -/* -** Check if the program stored in the VM associated with pParse may -** throw an ABORT exception (causing the statement, but not entire transaction -** to be rolled back). This condition is true if the main program or any -** sub-programs contains any of the following: -** -** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort. -** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort. -** * OP_Destroy -** * OP_VUpdate -** * OP_VCreate -** * OP_VRename -** * OP_FkCounter with P2==0 (immediate foreign key constraint) -** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine -** (for CREATE TABLE AS SELECT ...) -** -** Then check that the value of Parse.mayAbort is true if an -** ABORT may be thrown, or false otherwise. Return true if it does -** match, or false otherwise. This function is intended to be used as -** part of an assert statement in the compiler. Similar to: -** -** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) ); -*/ -SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ - int hasAbort = 0; - int hasFkCounter = 0; - int hasCreateTable = 0; - int hasCreateIndex = 0; - int hasInitCoroutine = 0; - Op *pOp; - VdbeOpIter sIter; - memset(&sIter, 0, sizeof(sIter)); - sIter.v = v; - - while( (pOp = opIterNext(&sIter))!=0 ){ - int opcode = pOp->opcode; - if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename - || opcode==OP_VDestroy - || opcode==OP_VCreate - || (opcode==OP_ParseSchema && pOp->p4.z==0) - || ((opcode==OP_Halt || opcode==OP_HaltIfNull) - && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort)) - ){ - hasAbort = 1; - break; - } - if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1; - if( mayAbort ){ - /* hasCreateIndex may also be set for some DELETE statements that use - ** OP_Clear. So this routine may end up returning true in the case - ** where a "DELETE FROM tbl" has a statement-journal but does not - ** require one. This is not so bad - it is an inefficiency, not a bug. */ - if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1; - if( opcode==OP_Clear ) hasCreateIndex = 1; - } - if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1; -#ifndef SQLITE_OMIT_FOREIGN_KEY - if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){ - hasFkCounter = 1; - } -#endif - } - sqlite3DbFree(v->db, sIter.apSub); - - /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred. - ** If malloc failed, then the while() loop above may not have iterated - ** through all opcodes and hasAbort may be set incorrectly. Return - ** true for this case to prevent the assert() in the callers frame - ** from failing. */ - return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter - || (hasCreateTable && hasInitCoroutine) || hasCreateIndex - ); -} -#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */ - -#ifdef SQLITE_DEBUG -/* -** Increment the nWrite counter in the VDBE if the cursor is not an -** ephemeral cursor, or if the cursor argument is NULL. -*/ -SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){ - if( pC==0 - || (pC->eCurType!=CURTYPE_SORTER - && pC->eCurType!=CURTYPE_PSEUDO - && !pC->isEphemeral) - ){ - p->nWrite++; - } -} -#endif - -#ifdef SQLITE_DEBUG -/* -** Assert if an Abort at this point in time might result in a corrupt -** database. -*/ -SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){ - assert( p->nWrite==0 || p->usesStmtJournal ); -} -#endif - -/* -** This routine is called after all opcodes have been inserted. It loops -** through all the opcodes and fixes up some details. -** -** (1) For each jump instruction with a negative P2 value (a label) -** resolve the P2 value to an actual address. -** -** (2) Compute the maximum number of arguments used by any SQL function -** and store that value in *pMaxFuncArgs. -** -** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately -** indicate what the prepared statement actually does. -** -** (4) Initialize the p4.xAdvance pointer on opcodes that use it. -** -** (5) Reclaim the memory allocated for storing labels. -** -** This routine will only function correctly if the mkopcodeh.tcl generator -** script numbers the opcodes correctly. Changes to this routine must be -** coordinated with changes to mkopcodeh.tcl. -*/ -static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ - int nMaxArgs = *pMaxFuncArgs; - Op *pOp; - Parse *pParse = p->pParse; - int *aLabel = pParse->aLabel; - p->readOnly = 1; - p->bIsReader = 0; - pOp = &p->aOp[p->nOp-1]; - while(1){ - - /* Only JUMP opcodes and the short list of special opcodes in the switch - ** below need to be considered. The mkopcodeh.tcl generator script groups - ** all these opcodes together near the front of the opcode list. Skip - ** any opcode that does not need processing by virtual of the fact that - ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization. - */ - if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){ - /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing - ** cases from this switch! */ - switch( pOp->opcode ){ - case OP_Transaction: { - if( pOp->p2!=0 ) p->readOnly = 0; - /* no break */ deliberate_fall_through - } - case OP_AutoCommit: - case OP_Savepoint: { - p->bIsReader = 1; - break; - } -#ifndef SQLITE_OMIT_WAL - case OP_Checkpoint: -#endif - case OP_Vacuum: - case OP_JournalMode: { - p->readOnly = 0; - p->bIsReader = 1; - break; - } - case OP_Next: - case OP_SorterNext: { - pOp->p4.xAdvance = sqlite3BtreeNext; - pOp->p4type = P4_ADVANCE; - /* The code generator never codes any of these opcodes as a jump - ** to a label. They are always coded as a jump backwards to a - ** known address */ - assert( pOp->p2>=0 ); - break; - } - case OP_Prev: { - pOp->p4.xAdvance = sqlite3BtreePrevious; - pOp->p4type = P4_ADVANCE; - /* The code generator never codes any of these opcodes as a jump - ** to a label. They are always coded as a jump backwards to a - ** known address */ - assert( pOp->p2>=0 ); - break; - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - case OP_VUpdate: { - if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; - break; - } - case OP_VFilter: { - int n; - assert( (pOp - p->aOp) >= 3 ); - assert( pOp[-1].opcode==OP_Integer ); - n = pOp[-1].p1; - if( n>nMaxArgs ) nMaxArgs = n; - /* Fall through into the default case */ - /* no break */ deliberate_fall_through - } -#endif - default: { - if( pOp->p2<0 ){ - /* The mkopcodeh.tcl script has so arranged things that the only - ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to - ** have non-negative values for P2. */ - assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ); - assert( ADDR(pOp->p2)<-pParse->nLabel ); - pOp->p2 = aLabel[ADDR(pOp->p2)]; - } - break; - } - } - /* The mkopcodeh.tcl script has so arranged things that the only - ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to - ** have non-negative values for P2. */ - assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0); - } - if( pOp==p->aOp ) break; - pOp--; - } - sqlite3DbFree(p->db, pParse->aLabel); - pParse->aLabel = 0; - pParse->nLabel = 0; - *pMaxFuncArgs = nMaxArgs; - assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) ); -} - -/* -** Return the address of the next instruction to be inserted. -*/ -SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){ - assert( p->magic==VDBE_MAGIC_INIT ); - return p->nOp; -} - -/* -** Verify that at least N opcode slots are available in p without -** having to malloc for more space (except when compiled using -** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing -** to verify that certain calls to sqlite3VdbeAddOpList() can never -** fail due to a OOM fault and hence that the return value from -** sqlite3VdbeAddOpList() will always be non-NULL. -*/ -#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) -SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){ - assert( p->nOp + N <= p->nOpAlloc ); -} -#endif - -/* -** Verify that the VM passed as the only argument does not contain -** an OP_ResultRow opcode. Fail an assert() if it does. This is used -** by code in pragma.c to ensure that the implementation of certain -** pragmas comports with the flags specified in the mkpragmatab.tcl -** script. -*/ -#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) -SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){ - int i; - for(i=0; inOp; i++){ - assert( p->aOp[i].opcode!=OP_ResultRow ); - } -} -#endif - -/* -** Generate code (a single OP_Abortable opcode) that will -** verify that the VDBE program can safely call Abort in the current -** context. -*/ -#if defined(SQLITE_DEBUG) -SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){ - if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable); -} -#endif - -/* -** This function returns a pointer to the array of opcodes associated with -** the Vdbe passed as the first argument. It is the callers responsibility -** to arrange for the returned array to be eventually freed using the -** vdbeFreeOpArray() function. -** -** Before returning, *pnOp is set to the number of entries in the returned -** array. Also, *pnMaxArg is set to the larger of its current value and -** the number of entries in the Vdbe.apArg[] array required to execute the -** returned program. -*/ -SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){ - VdbeOp *aOp = p->aOp; - assert( aOp && !p->db->mallocFailed ); - - /* Check that sqlite3VdbeUsesBtree() was not called on this VM */ - assert( DbMaskAllZero(p->btreeMask) ); - - resolveP2Values(p, pnMaxArg); - *pnOp = p->nOp; - p->aOp = 0; - return aOp; -} - -/* -** Add a whole list of operations to the operation stack. Return a -** pointer to the first operation inserted. -** -** Non-zero P2 arguments to jump instructions are automatically adjusted -** so that the jump target is relative to the first operation inserted. -*/ -SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList( - Vdbe *p, /* Add opcodes to the prepared statement */ - int nOp, /* Number of opcodes to add */ - VdbeOpList const *aOp, /* The opcodes to be added */ - int iLineno /* Source-file line number of first opcode */ -){ - int i; - VdbeOp *pOut, *pFirst; - assert( nOp>0 ); - assert( p->magic==VDBE_MAGIC_INIT ); - if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){ - return 0; - } - pFirst = pOut = &p->aOp[p->nOp]; - for(i=0; iopcode = aOp->opcode; - pOut->p1 = aOp->p1; - pOut->p2 = aOp->p2; - assert( aOp->p2>=0 ); - if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){ - pOut->p2 += p->nOp; - } - pOut->p3 = aOp->p3; - pOut->p4type = P4_NOTUSED; - pOut->p4.p = 0; - pOut->p5 = 0; -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - pOut->zComment = 0; -#endif -#ifdef SQLITE_VDBE_COVERAGE - pOut->iSrcLine = iLineno+i; -#else - (void)iLineno; -#endif -#ifdef SQLITE_DEBUG - if( p->db->flags & SQLITE_VdbeAddopTrace ){ - sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]); - } -#endif - } - p->nOp += nOp; - return pFirst; -} - -#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) -/* -** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus(). -*/ -SQLITE_PRIVATE void sqlite3VdbeScanStatus( - Vdbe *p, /* VM to add scanstatus() to */ - int addrExplain, /* Address of OP_Explain (or 0) */ - int addrLoop, /* Address of loop counter */ - int addrVisit, /* Address of rows visited counter */ - LogEst nEst, /* Estimated number of output rows */ - const char *zName /* Name of table or index being scanned */ -){ - sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus); - ScanStatus *aNew; - aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte); - if( aNew ){ - ScanStatus *pNew = &aNew[p->nScan++]; - pNew->addrExplain = addrExplain; - pNew->addrLoop = addrLoop; - pNew->addrVisit = addrVisit; - pNew->nEst = nEst; - pNew->zName = sqlite3DbStrDup(p->db, zName); - p->aScan = aNew; - } -} -#endif - - -/* -** Change the value of the opcode, or P1, P2, P3, or P5 operands -** for a specific instruction. -*/ -SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){ - sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode; -} -SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){ - sqlite3VdbeGetOp(p,addr)->p1 = val; -} -SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){ - sqlite3VdbeGetOp(p,addr)->p2 = val; -} -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){ - sqlite3VdbeGetOp(p,addr)->p3 = val; -} -SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){ - assert( p->nOp>0 || p->db->mallocFailed ); - if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5; -} - -/* -** Change the P2 operand of instruction addr so that it points to -** the address of the next instruction to be coded. -*/ -SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){ - sqlite3VdbeChangeP2(p, addr, p->nOp); -} - -/* -** Change the P2 operand of the jump instruction at addr so that -** the jump lands on the next opcode. Or if the jump instruction was -** the previous opcode (and is thus a no-op) then simply back up -** the next instruction counter by one slot so that the jump is -** overwritten by the next inserted opcode. -** -** This routine is an optimization of sqlite3VdbeJumpHere() that -** strives to omit useless byte-code like this: -** -** 7 Once 0 8 0 -** 8 ... -*/ -SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){ - if( addr==p->nOp-1 ){ - assert( p->aOp[addr].opcode==OP_Once - || p->aOp[addr].opcode==OP_If - || p->aOp[addr].opcode==OP_FkIfZero ); - assert( p->aOp[addr].p4type==0 ); -#ifdef SQLITE_VDBE_COVERAGE - sqlite3VdbeGetOp(p,-1)->iSrcLine = 0; /* Erase VdbeCoverage() macros */ -#endif - p->nOp--; - }else{ - sqlite3VdbeChangeP2(p, addr, p->nOp); - } -} - - -/* -** If the input FuncDef structure is ephemeral, then free it. If -** the FuncDef is not ephermal, then do nothing. -*/ -static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){ - if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){ - sqlite3DbFreeNN(db, pDef); - } -} - -/* -** Delete a P4 value if necessary. -*/ -static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){ - if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); - sqlite3DbFreeNN(db, p); -} -static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){ - freeEphemeralFunction(db, p->pFunc); - sqlite3DbFreeNN(db, p); -} -static void freeP4(sqlite3 *db, int p4type, void *p4){ - assert( db ); - switch( p4type ){ - case P4_FUNCCTX: { - freeP4FuncCtx(db, (sqlite3_context*)p4); - break; - } - case P4_REAL: - case P4_INT64: - case P4_DYNAMIC: - case P4_DYNBLOB: - case P4_INTARRAY: { - sqlite3DbFree(db, p4); - break; - } - case P4_KEYINFO: { - if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4); - break; - } -#ifdef SQLITE_ENABLE_CURSOR_HINTS - case P4_EXPR: { - sqlite3ExprDelete(db, (Expr*)p4); - break; - } -#endif - case P4_FUNCDEF: { - freeEphemeralFunction(db, (FuncDef*)p4); - break; - } - case P4_MEM: { - if( db->pnBytesFreed==0 ){ - sqlite3ValueFree((sqlite3_value*)p4); - }else{ - freeP4Mem(db, (Mem*)p4); - } - break; - } - case P4_VTAB : { - if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4); - break; - } - } -} - -/* -** Free the space allocated for aOp and any p4 values allocated for the -** opcodes contained within. If aOp is not NULL it is assumed to contain -** nOp entries. -*/ -static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){ - if( aOp ){ - Op *pOp; - for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){ - if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p); -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - sqlite3DbFree(db, pOp->zComment); -#endif - } - sqlite3DbFreeNN(db, aOp); - } -} - -/* -** Link the SubProgram object passed as the second argument into the linked -** list at Vdbe.pSubProgram. This list is used to delete all sub-program -** objects when the VM is no longer required. -*/ -SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){ - p->pNext = pVdbe->pProgram; - pVdbe->pProgram = p; -} - -/* -** Return true if the given Vdbe has any SubPrograms. -*/ -SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){ - return pVdbe->pProgram!=0; -} - -/* -** Change the opcode at addr into OP_Noop -*/ -SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){ - VdbeOp *pOp; - if( p->db->mallocFailed ) return 0; - assert( addr>=0 && addrnOp ); - pOp = &p->aOp[addr]; - freeP4(p->db, pOp->p4type, pOp->p4.p); - pOp->p4type = P4_NOTUSED; - pOp->p4.z = 0; - pOp->opcode = OP_Noop; - return 1; -} - -/* -** If the last opcode is "op" and it is not a jump destination, -** then remove it. Return true if and only if an opcode was removed. -*/ -SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){ - if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){ - return sqlite3VdbeChangeToNoop(p, p->nOp-1); - }else{ - return 0; - } -} - -#ifdef SQLITE_DEBUG -/* -** Generate an OP_ReleaseReg opcode to indicate that a range of -** registers, except any identified by mask, are no longer in use. -*/ -SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters( - Parse *pParse, /* Parsing context */ - int iFirst, /* Index of first register to be released */ - int N, /* Number of registers to release */ - u32 mask, /* Mask of registers to NOT release */ - int bUndefine /* If true, mark registers as undefined */ -){ - if( N==0 ) return; - assert( pParse->pVdbe ); - assert( iFirst>=1 ); - assert( iFirst+N-1<=pParse->nMem ); - if( N<=31 && mask!=0 ){ - while( N>0 && (mask&1)!=0 ){ - mask >>= 1; - iFirst++; - N--; - } - while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){ - mask &= ~MASKBIT32(N-1); - N--; - } - } - if( N>0 ){ - sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask); - if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1); - } -} -#endif /* SQLITE_DEBUG */ - - -/* -** Change the value of the P4 operand for a specific instruction. -** This routine is useful when a large program is loaded from a -** static array using sqlite3VdbeAddOpList but we want to make a -** few minor changes to the program. -** -** If n>=0 then the P4 operand is dynamic, meaning that a copy of -** the string is made into memory obtained from sqlite3_malloc(). -** A value of n==0 means copy bytes of zP4 up to and including the -** first null byte. If n>0 then copy n+1 bytes of zP4. -** -** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points -** to a string or structure that is guaranteed to exist for the lifetime of -** the Vdbe. In these cases we can just copy the pointer. -** -** If addr<0 then change P4 on the most recently inserted instruction. -*/ -static void SQLITE_NOINLINE vdbeChangeP4Full( - Vdbe *p, - Op *pOp, - const char *zP4, - int n -){ - if( pOp->p4type ){ - freeP4(p->db, pOp->p4type, pOp->p4.p); - pOp->p4type = 0; - pOp->p4.p = 0; - } - if( n<0 ){ - sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n); - }else{ - if( n==0 ) n = sqlite3Strlen30(zP4); - pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n); - pOp->p4type = P4_DYNAMIC; - } -} -SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ - Op *pOp; - sqlite3 *db; - assert( p!=0 ); - db = p->db; - assert( p->magic==VDBE_MAGIC_INIT ); - assert( p->aOp!=0 || db->mallocFailed ); - if( db->mallocFailed ){ - if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4); - return; - } - assert( p->nOp>0 ); - assert( addrnOp ); - if( addr<0 ){ - addr = p->nOp - 1; - } - pOp = &p->aOp[addr]; - if( n>=0 || pOp->p4type ){ - vdbeChangeP4Full(p, pOp, zP4, n); - return; - } - if( n==P4_INT32 ){ - /* Note: this cast is safe, because the origin data point was an int - ** that was cast to a (const char *). */ - pOp->p4.i = SQLITE_PTR_TO_INT(zP4); - pOp->p4type = P4_INT32; - }else if( zP4!=0 ){ - assert( n<0 ); - pOp->p4.p = (void*)zP4; - pOp->p4type = (signed char)n; - if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4); - } -} - -/* -** Change the P4 operand of the most recently coded instruction -** to the value defined by the arguments. This is a high-speed -** version of sqlite3VdbeChangeP4(). -** -** The P4 operand must not have been previously defined. And the new -** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of -** those cases. -*/ -SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){ - VdbeOp *pOp; - assert( n!=P4_INT32 && n!=P4_VTAB ); - assert( n<=0 ); - if( p->db->mallocFailed ){ - freeP4(p->db, n, pP4); - }else{ - assert( pP4!=0 ); - assert( p->nOp>0 ); - pOp = &p->aOp[p->nOp-1]; - assert( pOp->p4type==P4_NOTUSED ); - pOp->p4type = n; - pOp->p4.p = pP4; - } -} - -/* -** Set the P4 on the most recently added opcode to the KeyInfo for the -** index given. -*/ -SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){ - Vdbe *v = pParse->pVdbe; - KeyInfo *pKeyInfo; - assert( v!=0 ); - assert( pIdx!=0 ); - pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx); - if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); -} - -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS -/* -** Change the comment on the most recently coded instruction. Or -** insert a No-op and add the comment to that new instruction. This -** makes the code easier to read during debugging. None of this happens -** in a production build. -*/ -static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){ - assert( p->nOp>0 || p->aOp==0 ); - assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed - || p->pParse->nErr>0 ); - if( p->nOp ){ - assert( p->aOp ); - sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); - p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap); - } -} -SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ - va_list ap; - if( p ){ - va_start(ap, zFormat); - vdbeVComment(p, zFormat, ap); - va_end(ap); - } -} -SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){ - va_list ap; - if( p ){ - sqlite3VdbeAddOp0(p, OP_Noop); - va_start(ap, zFormat); - vdbeVComment(p, zFormat, ap); - va_end(ap); - } -} -#endif /* NDEBUG */ - -#ifdef SQLITE_VDBE_COVERAGE -/* -** Set the value if the iSrcLine field for the previously coded instruction. -*/ -SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){ - sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine; -} -#endif /* SQLITE_VDBE_COVERAGE */ - -/* -** Return the opcode for a given address. If the address is -1, then -** return the most recently inserted opcode. -** -** If a memory allocation error has occurred prior to the calling of this -** routine, then a pointer to a dummy VdbeOp will be returned. That opcode -** is readable but not writable, though it is cast to a writable value. -** The return of a dummy opcode allows the call to continue functioning -** after an OOM fault without having to check to see if the return from -** this routine is a valid pointer. But because the dummy.opcode is 0, -** dummy will never be written to. This is verified by code inspection and -** by running with Valgrind. -*/ -SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){ - /* C89 specifies that the constant "dummy" will be initialized to all - ** zeros, which is correct. MSVC generates a warning, nevertheless. */ - static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */ - assert( p->magic==VDBE_MAGIC_INIT ); - if( addr<0 ){ - addr = p->nOp - 1; - } - assert( (addr>=0 && addrnOp) || p->db->mallocFailed ); - if( p->db->mallocFailed ){ - return (VdbeOp*)&dummy; - }else{ - return &p->aOp[addr]; - } -} - -#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) -/* -** Return an integer value for one of the parameters to the opcode pOp -** determined by character c. -*/ -static int translateP(char c, const Op *pOp){ - if( c=='1' ) return pOp->p1; - if( c=='2' ) return pOp->p2; - if( c=='3' ) return pOp->p3; - if( c=='4' ) return pOp->p4.i; - return pOp->p5; -} - -/* -** Compute a string for the "comment" field of a VDBE opcode listing. -** -** The Synopsis: field in comments in the vdbe.c source file gets converted -** to an extra string that is appended to the sqlite3OpcodeName(). In the -** absence of other comments, this synopsis becomes the comment on the opcode. -** Some translation occurs: -** -** "PX" -> "r[X]" -** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1 -** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0 -** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x -*/ -SQLITE_PRIVATE char *sqlite3VdbeDisplayComment( - sqlite3 *db, /* Optional - Oom error reporting only */ - const Op *pOp, /* The opcode to be commented */ - const char *zP4 /* Previously obtained value for P4 */ -){ - const char *zOpName; - const char *zSynopsis; - int nOpName; - int ii; - char zAlt[50]; - StrAccum x; - - sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH); - zOpName = sqlite3OpcodeName(pOp->opcode); - nOpName = sqlite3Strlen30(zOpName); - if( zOpName[nOpName+1] ){ - int seenCom = 0; - char c; - zSynopsis = zOpName += nOpName + 1; - if( strncmp(zSynopsis,"IF ",3)==0 ){ - if( pOp->p5 & SQLITE_STOREP2 ){ - sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3); - }else{ - sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3); - } - zSynopsis = zAlt; - } - for(ii=0; (c = zSynopsis[ii])!=0; ii++){ - if( c=='P' ){ - c = zSynopsis[++ii]; - if( c=='4' ){ - sqlite3_str_appendall(&x, zP4); - }else if( c=='X' ){ - sqlite3_str_appendall(&x, pOp->zComment); - seenCom = 1; - }else{ - int v1 = translateP(c, pOp); - int v2; - if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){ - ii += 3; - v2 = translateP(zSynopsis[ii], pOp); - if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){ - ii += 2; - v2++; - } - if( v2<2 ){ - sqlite3_str_appendf(&x, "%d", v1); - }else{ - sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1); - } - }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){ - sqlite3_context *pCtx = pOp->p4.pCtx; - if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){ - sqlite3_str_appendf(&x, "%d", v1); - }else if( pCtx->argc>1 ){ - sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1); - }else{ - assert( x.nChar>2 ); - x.nChar -= 2; - ii++; - } - ii += 3; - }else{ - sqlite3_str_appendf(&x, "%d", v1); - if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){ - ii += 4; - } - } - } - }else{ - sqlite3_str_appendchar(&x, 1, c); - } - } - if( !seenCom && pOp->zComment ){ - sqlite3_str_appendf(&x, "; %s", pOp->zComment); - } - }else if( pOp->zComment ){ - sqlite3_str_appendall(&x, pOp->zComment); - } - if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){ - sqlite3OomFault(db); - } - return sqlite3StrAccumFinish(&x); -} -#endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */ - -#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) -/* -** Translate the P4.pExpr value for an OP_CursorHint opcode into text -** that can be displayed in the P4 column of EXPLAIN output. -*/ -static void displayP4Expr(StrAccum *p, Expr *pExpr){ - const char *zOp = 0; - switch( pExpr->op ){ - case TK_STRING: - sqlite3_str_appendf(p, "%Q", pExpr->u.zToken); - break; - case TK_INTEGER: - sqlite3_str_appendf(p, "%d", pExpr->u.iValue); - break; - case TK_NULL: - sqlite3_str_appendf(p, "NULL"); - break; - case TK_REGISTER: { - sqlite3_str_appendf(p, "r[%d]", pExpr->iTable); - break; - } - case TK_COLUMN: { - if( pExpr->iColumn<0 ){ - sqlite3_str_appendf(p, "rowid"); - }else{ - sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn); - } - break; - } - case TK_LT: zOp = "LT"; break; - case TK_LE: zOp = "LE"; break; - case TK_GT: zOp = "GT"; break; - case TK_GE: zOp = "GE"; break; - case TK_NE: zOp = "NE"; break; - case TK_EQ: zOp = "EQ"; break; - case TK_IS: zOp = "IS"; break; - case TK_ISNOT: zOp = "ISNOT"; break; - case TK_AND: zOp = "AND"; break; - case TK_OR: zOp = "OR"; break; - case TK_PLUS: zOp = "ADD"; break; - case TK_STAR: zOp = "MUL"; break; - case TK_MINUS: zOp = "SUB"; break; - case TK_REM: zOp = "REM"; break; - case TK_BITAND: zOp = "BITAND"; break; - case TK_BITOR: zOp = "BITOR"; break; - case TK_SLASH: zOp = "DIV"; break; - case TK_LSHIFT: zOp = "LSHIFT"; break; - case TK_RSHIFT: zOp = "RSHIFT"; break; - case TK_CONCAT: zOp = "CONCAT"; break; - case TK_UMINUS: zOp = "MINUS"; break; - case TK_UPLUS: zOp = "PLUS"; break; - case TK_BITNOT: zOp = "BITNOT"; break; - case TK_NOT: zOp = "NOT"; break; - case TK_ISNULL: zOp = "ISNULL"; break; - case TK_NOTNULL: zOp = "NOTNULL"; break; - - default: - sqlite3_str_appendf(p, "%s", "expr"); - break; - } - - if( zOp ){ - sqlite3_str_appendf(p, "%s(", zOp); - displayP4Expr(p, pExpr->pLeft); - if( pExpr->pRight ){ - sqlite3_str_append(p, ",", 1); - displayP4Expr(p, pExpr->pRight); - } - sqlite3_str_append(p, ")", 1); - } -} -#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */ - - -#if VDBE_DISPLAY_P4 -/* -** Compute a string that describes the P4 parameter for an opcode. -** Use zTemp for any required temporary buffer space. -*/ -SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){ - char *zP4 = 0; - StrAccum x; - - sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH); - switch( pOp->p4type ){ - case P4_KEYINFO: { - int j; - KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; - assert( pKeyInfo->aSortFlags!=0 ); - sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField); - for(j=0; jnKeyField; j++){ - CollSeq *pColl = pKeyInfo->aColl[j]; - const char *zColl = pColl ? pColl->zName : ""; - if( strcmp(zColl, "BINARY")==0 ) zColl = "B"; - sqlite3_str_appendf(&x, ",%s%s%s", - (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "", - (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "", - zColl); - } - sqlite3_str_append(&x, ")", 1); - break; - } -#ifdef SQLITE_ENABLE_CURSOR_HINTS - case P4_EXPR: { - displayP4Expr(&x, pOp->p4.pExpr); - break; - } -#endif - case P4_COLLSEQ: { - static const char *const encnames[] = {"?", "8", "16LE", "16BE"}; - CollSeq *pColl = pOp->p4.pColl; - assert( pColl->enc>=0 && pColl->enc<4 ); - sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName, - encnames[pColl->enc]); - break; - } - case P4_FUNCDEF: { - FuncDef *pDef = pOp->p4.pFunc; - sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg); - break; - } - case P4_FUNCCTX: { - FuncDef *pDef = pOp->p4.pCtx->pFunc; - sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg); - break; - } - case P4_INT64: { - sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64); - break; - } - case P4_INT32: { - sqlite3_str_appendf(&x, "%d", pOp->p4.i); - break; - } - case P4_REAL: { - sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal); - break; - } - case P4_MEM: { - Mem *pMem = pOp->p4.pMem; - if( pMem->flags & MEM_Str ){ - zP4 = pMem->z; - }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){ - sqlite3_str_appendf(&x, "%lld", pMem->u.i); - }else if( pMem->flags & MEM_Real ){ - sqlite3_str_appendf(&x, "%.16g", pMem->u.r); - }else if( pMem->flags & MEM_Null ){ - zP4 = "NULL"; - }else{ - assert( pMem->flags & MEM_Blob ); - zP4 = "(blob)"; - } - break; - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - case P4_VTAB: { - sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab; - sqlite3_str_appendf(&x, "vtab:%p", pVtab); - break; - } -#endif - case P4_INTARRAY: { - u32 i; - u32 *ai = pOp->p4.ai; - u32 n = ai[0]; /* The first element of an INTARRAY is always the - ** count of the number of elements to follow */ - for(i=1; i<=n; i++){ - sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]); - } - sqlite3_str_append(&x, "]", 1); - break; - } - case P4_SUBPROGRAM: { - zP4 = "program"; - break; - } - case P4_DYNBLOB: - case P4_ADVANCE: { - break; - } - case P4_TABLE: { - zP4 = pOp->p4.pTab->zName; - break; - } - default: { - zP4 = pOp->p4.z; - } - } - if( zP4 ) sqlite3_str_appendall(&x, zP4); - if( (x.accError & SQLITE_NOMEM)!=0 ){ - sqlite3OomFault(db); - } - return sqlite3StrAccumFinish(&x); -} -#endif /* VDBE_DISPLAY_P4 */ - -/* -** Declare to the Vdbe that the BTree object at db->aDb[i] is used. -** -** The prepared statements need to know in advance the complete set of -** attached databases that will be use. A mask of these databases -** is maintained in p->btreeMask. The p->lockMask value is the subset of -** p->btreeMask of databases that will require a lock. -*/ -SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){ - assert( i>=0 && idb->nDb && i<(int)sizeof(yDbMask)*8 ); - assert( i<(int)sizeof(p->btreeMask)*8 ); - DbMaskSet(p->btreeMask, i); - if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){ - DbMaskSet(p->lockMask, i); - } -} - -#if !defined(SQLITE_OMIT_SHARED_CACHE) -/* -** If SQLite is compiled to support shared-cache mode and to be threadsafe, -** this routine obtains the mutex associated with each BtShared structure -** that may be accessed by the VM passed as an argument. In doing so it also -** sets the BtShared.db member of each of the BtShared structures, ensuring -** that the correct busy-handler callback is invoked if required. -** -** If SQLite is not threadsafe but does support shared-cache mode, then -** sqlite3BtreeEnter() is invoked to set the BtShared.db variables -** of all of BtShared structures accessible via the database handle -** associated with the VM. -** -** If SQLite is not threadsafe and does not support shared-cache mode, this -** function is a no-op. -** -** The p->btreeMask field is a bitmask of all btrees that the prepared -** statement p will ever use. Let N be the number of bits in p->btreeMask -** corresponding to btrees that use shared cache. Then the runtime of -** this routine is N*N. But as N is rarely more than 1, this should not -** be a problem. -*/ -SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){ - int i; - sqlite3 *db; - Db *aDb; - int nDb; - if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ - db = p->db; - aDb = db->aDb; - nDb = db->nDb; - for(i=0; ilockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ - sqlite3BtreeEnter(aDb[i].pBt); - } - } -} -#endif - -#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 -/* -** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter(). -*/ -static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){ - int i; - sqlite3 *db; - Db *aDb; - int nDb; - db = p->db; - aDb = db->aDb; - nDb = db->nDb; - for(i=0; ilockMask,i) && ALWAYS(aDb[i].pBt!=0) ){ - sqlite3BtreeLeave(aDb[i].pBt); - } - } -} -SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){ - if( DbMaskAllZero(p->lockMask) ) return; /* The common case */ - vdbeLeave(p); -} -#endif - -#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) -/* -** Print a single opcode. This routine is used for debugging only. -*/ -SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){ - char *zP4; - char *zCom; - sqlite3 dummyDb; - static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n"; - if( pOut==0 ) pOut = stdout; - sqlite3BeginBenignMalloc(); - dummyDb.mallocFailed = 1; - zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp); -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - zCom = sqlite3VdbeDisplayComment(0, pOp, zP4); -#else - zCom = 0; -#endif - /* NB: The sqlite3OpcodeName() function is implemented by code created - ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the - ** information from the vdbe.c source text */ - fprintf(pOut, zFormat1, pc, - sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, - zP4 ? zP4 : "", pOp->p5, - zCom ? zCom : "" - ); - fflush(pOut); - sqlite3_free(zP4); - sqlite3_free(zCom); - sqlite3EndBenignMalloc(); -} -#endif - -/* -** Initialize an array of N Mem element. -*/ -static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){ - while( (N--)>0 ){ - p->db = db; - p->flags = flags; - p->szMalloc = 0; -#ifdef SQLITE_DEBUG - p->pScopyFrom = 0; -#endif - p++; - } -} - -/* -** Release an array of N Mem elements -*/ -static void releaseMemArray(Mem *p, int N){ - if( p && N ){ - Mem *pEnd = &p[N]; - sqlite3 *db = p->db; - if( db->pnBytesFreed ){ - do{ - if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); - }while( (++p)flags & MEM_Agg ); - testcase( p->flags & MEM_Dyn ); - testcase( p->xDel==sqlite3VdbeFrameMemDel ); - if( p->flags&(MEM_Agg|MEM_Dyn) ){ - sqlite3VdbeMemRelease(p); - }else if( p->szMalloc ){ - sqlite3DbFreeNN(db, p->zMalloc); - p->szMalloc = 0; - } - - p->flags = MEM_Undefined; - }while( (++p)iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0; - return 1; -} -#endif - - -/* -** This is a destructor on a Mem object (which is really an sqlite3_value) -** that deletes the Frame object that is attached to it as a blob. -** -** This routine does not delete the Frame right away. It merely adds the -** frame to a list of frames to be deleted when the Vdbe halts. -*/ -SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){ - VdbeFrame *pFrame = (VdbeFrame*)pArg; - assert( sqlite3VdbeFrameIsValid(pFrame) ); - pFrame->pParent = pFrame->v->pDelFrame; - pFrame->v->pDelFrame = pFrame; -} - -#if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN) -/* -** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN -** QUERY PLAN output. -** -** Return SQLITE_ROW on success. Return SQLITE_DONE if there are no -** more opcodes to be displayed. -*/ -SQLITE_PRIVATE int sqlite3VdbeNextOpcode( - Vdbe *p, /* The statement being explained */ - Mem *pSub, /* Storage for keeping track of subprogram nesting */ - int eMode, /* 0: normal. 1: EQP. 2: TablesUsed */ - int *piPc, /* IN/OUT: Current rowid. Overwritten with next rowid */ - int *piAddr, /* OUT: Write index into (*paOp)[] here */ - Op **paOp /* OUT: Write the opcode array here */ -){ - int nRow; /* Stop when row count reaches this */ - int nSub = 0; /* Number of sub-vdbes seen so far */ - SubProgram **apSub = 0; /* Array of sub-vdbes */ - int i; /* Next instruction address */ - int rc = SQLITE_OK; /* Result code */ - Op *aOp = 0; /* Opcode array */ - int iPc; /* Rowid. Copy of value in *piPc */ - - /* When the number of output rows reaches nRow, that means the - ** listing has finished and sqlite3_step() should return SQLITE_DONE. - ** nRow is the sum of the number of rows in the main program, plus - ** the sum of the number of rows in all trigger subprograms encountered - ** so far. The nRow value will increase as new trigger subprograms are - ** encountered, but p->pc will eventually catch up to nRow. - */ - nRow = p->nOp; - if( pSub!=0 ){ - if( pSub->flags&MEM_Blob ){ - /* pSub is initiallly NULL. It is initialized to a BLOB by - ** the P4_SUBPROGRAM processing logic below */ - nSub = pSub->n/sizeof(Vdbe*); - apSub = (SubProgram **)pSub->z; - } - for(i=0; inOp; - } - } - iPc = *piPc; - while(1){ /* Loop exits via break */ - i = iPc++; - if( i>=nRow ){ - p->rc = SQLITE_OK; - rc = SQLITE_DONE; - break; - } - if( inOp ){ - /* The rowid is small enough that we are still in the - ** main program. */ - aOp = p->aOp; - }else{ - /* We are currently listing subprograms. Figure out which one and - ** pick up the appropriate opcode. */ - int j; - i -= p->nOp; - assert( apSub!=0 ); - assert( nSub>0 ); - for(j=0; i>=apSub[j]->nOp; j++){ - i -= apSub[j]->nOp; - assert( inOp || j+1aOp; - } - - /* When an OP_Program opcode is encounter (the only opcode that has - ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms - ** kept in p->aMem[9].z to hold the new program - assuming this subprogram - ** has not already been seen. - */ - if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){ - int nByte = (nSub+1)*sizeof(SubProgram*); - int j; - for(j=0; jrc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0); - if( p->rc!=SQLITE_OK ){ - rc = SQLITE_ERROR; - break; - } - apSub = (SubProgram **)pSub->z; - apSub[nSub++] = aOp[i].p4.pProgram; - MemSetTypeFlag(pSub, MEM_Blob); - pSub->n = nSub*sizeof(SubProgram*); - nRow += aOp[i].p4.pProgram->nOp; - } - } - if( eMode==0 ) break; -#ifdef SQLITE_ENABLE_BYTECODE_VTAB - if( eMode==2 ){ - Op *pOp = aOp + i; - if( pOp->opcode==OP_OpenRead ) break; - if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break; - if( pOp->opcode==OP_ReopenIdx ) break; - }else -#endif - { - assert( eMode==1 ); - if( aOp[i].opcode==OP_Explain ) break; - if( aOp[i].opcode==OP_Init && iPc>1 ) break; - } - } - *piPc = iPc; - *piAddr = i; - *paOp = aOp; - return rc; -} -#endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */ - - -/* -** Delete a VdbeFrame object and its contents. VdbeFrame objects are -** allocated by the OP_Program opcode in sqlite3VdbeExec(). -*/ -SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){ - int i; - Mem *aMem = VdbeFrameMem(p); - VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem]; - assert( sqlite3VdbeFrameIsValid(p) ); - for(i=0; inChildCsr; i++){ - sqlite3VdbeFreeCursor(p->v, apCsr[i]); - } - releaseMemArray(aMem, p->nChildMem); - sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0); - sqlite3DbFree(p->v->db, p); -} - -#ifndef SQLITE_OMIT_EXPLAIN -/* -** Give a listing of the program in the virtual machine. -** -** The interface is the same as sqlite3VdbeExec(). But instead of -** running the code, it invokes the callback once for each instruction. -** This feature is used to implement "EXPLAIN". -** -** When p->explain==1, each instruction is listed. When -** p->explain==2, only OP_Explain instructions are listed and these -** are shown in a different format. p->explain==2 is used to implement -** EXPLAIN QUERY PLAN. -** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers -** are also shown, so that the boundaries between the main program and -** each trigger are clear. -** -** When p->explain==1, first the main program is listed, then each of -** the trigger subprograms are listed one by one. -*/ -SQLITE_PRIVATE int sqlite3VdbeList( - Vdbe *p /* The VDBE */ -){ - Mem *pSub = 0; /* Memory cell hold array of subprogs */ - sqlite3 *db = p->db; /* The database connection */ - int i; /* Loop counter */ - int rc = SQLITE_OK; /* Return code */ - Mem *pMem = &p->aMem[1]; /* First Mem of result set */ - int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0); - Op *aOp; /* Array of opcodes */ - Op *pOp; /* Current opcode */ - - assert( p->explain ); - assert( p->magic==VDBE_MAGIC_RUN ); - assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM ); - - /* Even though this opcode does not use dynamic strings for - ** the result, result columns may become dynamic if the user calls - ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. - */ - releaseMemArray(pMem, 8); - p->pResultSet = 0; - - if( p->rc==SQLITE_NOMEM ){ - /* This happens if a malloc() inside a call to sqlite3_column_text() or - ** sqlite3_column_text16() failed. */ - sqlite3OomFault(db); - return SQLITE_ERROR; - } - - if( bListSubprogs ){ - /* The first 8 memory cells are used for the result set. So we will - ** commandeer the 9th cell to use as storage for an array of pointers - ** to trigger subprograms. The VDBE is guaranteed to have at least 9 - ** cells. */ - assert( p->nMem>9 ); - pSub = &p->aMem[9]; - }else{ - pSub = 0; - } - - /* Figure out which opcode is next to display */ - rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp); - - if( rc==SQLITE_OK ){ - pOp = aOp + i; - if( AtomicLoad(&db->u1.isInterrupted) ){ - p->rc = SQLITE_INTERRUPT; - rc = SQLITE_ERROR; - sqlite3VdbeError(p, sqlite3ErrStr(p->rc)); - }else{ - char *zP4 = sqlite3VdbeDisplayP4(db, pOp); - if( p->explain==2 ){ - sqlite3VdbeMemSetInt64(pMem, pOp->p1); - sqlite3VdbeMemSetInt64(pMem+1, pOp->p2); - sqlite3VdbeMemSetInt64(pMem+2, pOp->p3); - sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free); - p->nResColumn = 4; - }else{ - sqlite3VdbeMemSetInt64(pMem+0, i); - sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode), - -1, SQLITE_UTF8, SQLITE_STATIC); - sqlite3VdbeMemSetInt64(pMem+2, pOp->p1); - sqlite3VdbeMemSetInt64(pMem+3, pOp->p2); - sqlite3VdbeMemSetInt64(pMem+4, pOp->p3); - /* pMem+5 for p4 is done last */ - sqlite3VdbeMemSetInt64(pMem+6, pOp->p5); -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - { - char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4); - sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free); - } -#else - sqlite3VdbeMemSetNull(pMem+7); -#endif - sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free); - p->nResColumn = 8; - } - p->pResultSet = pMem; - if( db->mallocFailed ){ - p->rc = SQLITE_NOMEM; - rc = SQLITE_ERROR; - }else{ - p->rc = SQLITE_OK; - rc = SQLITE_ROW; - } - } - } - return rc; -} -#endif /* SQLITE_OMIT_EXPLAIN */ - -#ifdef SQLITE_DEBUG -/* -** Print the SQL that was used to generate a VDBE program. -*/ -SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ - const char *z = 0; - if( p->zSql ){ - z = p->zSql; - }else if( p->nOp>=1 ){ - const VdbeOp *pOp = &p->aOp[0]; - if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ - z = pOp->p4.z; - while( sqlite3Isspace(*z) ) z++; - } - } - if( z ) printf("SQL: [%s]\n", z); -} -#endif - -#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) -/* -** Print an IOTRACE message showing SQL content. -*/ -SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ - int nOp = p->nOp; - VdbeOp *pOp; - if( sqlite3IoTrace==0 ) return; - if( nOp<1 ) return; - pOp = &p->aOp[0]; - if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){ - int i, j; - char z[1000]; - sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); - for(i=0; sqlite3Isspace(z[i]); i++){} - for(j=0; z[i]; i++){ - if( sqlite3Isspace(z[i]) ){ - if( z[i-1]!=' ' ){ - z[j++] = ' '; - } - }else{ - z[j++] = z[i]; - } - } - z[j] = 0; - sqlite3IoTrace("SQL %s\n", z); - } -} -#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */ - -/* An instance of this object describes bulk memory available for use -** by subcomponents of a prepared statement. Space is allocated out -** of a ReusableSpace object by the allocSpace() routine below. -*/ -struct ReusableSpace { - u8 *pSpace; /* Available memory */ - sqlite3_int64 nFree; /* Bytes of available memory */ - sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */ -}; - -/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf -** from the ReusableSpace object. Return a pointer to the allocated -** memory on success. If insufficient memory is available in the -** ReusableSpace object, increase the ReusableSpace.nNeeded -** value by the amount needed and return NULL. -** -** If pBuf is not initially NULL, that means that the memory has already -** been allocated by a prior call to this routine, so just return a copy -** of pBuf and leave ReusableSpace unchanged. -** -** This allocator is employed to repurpose unused slots at the end of the -** opcode array of prepared state for other memory needs of the prepared -** statement. -*/ -static void *allocSpace( - struct ReusableSpace *p, /* Bulk memory available for allocation */ - void *pBuf, /* Pointer to a prior allocation */ - sqlite3_int64 nByte /* Bytes of memory needed */ -){ - assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) ); - if( pBuf==0 ){ - nByte = ROUND8(nByte); - if( nByte <= p->nFree ){ - p->nFree -= nByte; - pBuf = &p->pSpace[p->nFree]; - }else{ - p->nNeeded += nByte; - } - } - assert( EIGHT_BYTE_ALIGNMENT(pBuf) ); - return pBuf; -} - -/* -** Rewind the VDBE back to the beginning in preparation for -** running it. -*/ -SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){ -#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) - int i; -#endif - assert( p!=0 ); - assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET ); - - /* There should be at least one opcode. - */ - assert( p->nOp>0 ); - - /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */ - p->magic = VDBE_MAGIC_RUN; - -#ifdef SQLITE_DEBUG - for(i=0; inMem; i++){ - assert( p->aMem[i].db==p->db ); - } -#endif - p->pc = -1; - p->rc = SQLITE_OK; - p->errorAction = OE_Abort; - p->nChange = 0; - p->cacheCtr = 1; - p->minWriteFileFormat = 255; - p->iStatement = 0; - p->nFkConstraint = 0; -#ifdef VDBE_PROFILE - for(i=0; inOp; i++){ - p->aOp[i].cnt = 0; - p->aOp[i].cycles = 0; - } -#endif -} - -/* -** Prepare a virtual machine for execution for the first time after -** creating the virtual machine. This involves things such -** as allocating registers and initializing the program counter. -** After the VDBE has be prepped, it can be executed by one or more -** calls to sqlite3VdbeExec(). -** -** This function may be called exactly once on each virtual machine. -** After this routine is called the VM has been "packaged" and is ready -** to run. After this routine is called, further calls to -** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects -** the Vdbe from the Parse object that helped generate it so that the -** the Vdbe becomes an independent entity and the Parse object can be -** destroyed. -** -** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back -** to its initial state after it has been run. -*/ -SQLITE_PRIVATE void sqlite3VdbeMakeReady( - Vdbe *p, /* The VDBE */ - Parse *pParse /* Parsing context */ -){ - sqlite3 *db; /* The database connection */ - int nVar; /* Number of parameters */ - int nMem; /* Number of VM memory registers */ - int nCursor; /* Number of cursors required */ - int nArg; /* Number of arguments in subprograms */ - int n; /* Loop counter */ - struct ReusableSpace x; /* Reusable bulk memory */ - - assert( p!=0 ); - assert( p->nOp>0 ); - assert( pParse!=0 ); - assert( p->magic==VDBE_MAGIC_INIT ); - assert( pParse==p->pParse ); - db = p->db; - assert( db->mallocFailed==0 ); - nVar = pParse->nVar; - nMem = pParse->nMem; - nCursor = pParse->nTab; - nArg = pParse->nMaxArg; - - /* Each cursor uses a memory cell. The first cursor (cursor 0) can - ** use aMem[0] which is not otherwise used by the VDBE program. Allocate - ** space at the end of aMem[] for cursors 1 and greater. - ** See also: allocateCursor(). - */ - nMem += nCursor; - if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */ - - /* Figure out how much reusable memory is available at the end of the - ** opcode array. This extra memory will be reallocated for other elements - ** of the prepared statement. - */ - n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */ - x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */ - assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) ); - x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */ - assert( x.nFree>=0 ); - assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) ); - - resolveP2Values(p, &nArg); - p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort); - if( pParse->explain ){ - static const char * const azColName[] = { - "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", - "id", "parent", "notused", "detail" - }; - int iFirst, mx, i; - if( nMem<10 ) nMem = 10; - p->explain = pParse->explain; - if( pParse->explain==2 ){ - sqlite3VdbeSetNumCols(p, 4); - iFirst = 8; - mx = 12; - }else{ - sqlite3VdbeSetNumCols(p, 8); - iFirst = 0; - mx = 8; - } - for(i=iFirst; iexpired = 0; - - /* Memory for registers, parameters, cursor, etc, is allocated in one or two - ** passes. On the first pass, we try to reuse unused memory at the - ** end of the opcode array. If we are unable to satisfy all memory - ** requirements by reusing the opcode array tail, then the second - ** pass will fill in the remainder using a fresh memory allocation. - ** - ** This two-pass approach that reuses as much memory as possible from - ** the leftover memory at the end of the opcode array. This can significantly - ** reduce the amount of memory held by a prepared statement. - */ - x.nNeeded = 0; - p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem)); - p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem)); - p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*)); - p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*)); -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64)); -#endif - if( x.nNeeded ){ - x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded); - x.nFree = x.nNeeded; - if( !db->mallocFailed ){ - p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem)); - p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem)); - p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*)); - p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*)); -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64)); -#endif - } - } - - p->pVList = pParse->pVList; - pParse->pVList = 0; - if( db->mallocFailed ){ - p->nVar = 0; - p->nCursor = 0; - p->nMem = 0; - }else{ - p->nCursor = nCursor; - p->nVar = (ynVar)nVar; - initMemArray(p->aVar, nVar, db, MEM_Null); - p->nMem = nMem; - initMemArray(p->aMem, nMem, db, MEM_Undefined); - memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*)); -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - memset(p->anExec, 0, p->nOp*sizeof(i64)); -#endif - } - sqlite3VdbeRewind(p); -} - -/* -** Close a VDBE cursor and release all the resources that cursor -** happens to hold. -*/ -SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){ - if( pCx==0 ){ - return; - } - assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE ); - switch( pCx->eCurType ){ - case CURTYPE_SORTER: { - sqlite3VdbeSorterClose(p->db, pCx); - break; - } - case CURTYPE_BTREE: { - if( pCx->isEphemeral ){ - if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx); - /* The pCx->pCursor will be close automatically, if it exists, by - ** the call above. */ - }else{ - assert( pCx->uc.pCursor!=0 ); - sqlite3BtreeCloseCursor(pCx->uc.pCursor); - } - break; - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - case CURTYPE_VTAB: { - sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur; - const sqlite3_module *pModule = pVCur->pVtab->pModule; - assert( pVCur->pVtab->nRef>0 ); - pVCur->pVtab->nRef--; - pModule->xClose(pVCur); - break; - } -#endif - } -} - -/* -** Close all cursors in the current frame. -*/ -static void closeCursorsInFrame(Vdbe *p){ - if( p->apCsr ){ - int i; - for(i=0; inCursor; i++){ - VdbeCursor *pC = p->apCsr[i]; - if( pC ){ - sqlite3VdbeFreeCursor(p, pC); - p->apCsr[i] = 0; - } - } - } -} - -/* -** Copy the values stored in the VdbeFrame structure to its Vdbe. This -** is used, for example, when a trigger sub-program is halted to restore -** control to the main program. -*/ -SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){ - Vdbe *v = pFrame->v; - closeCursorsInFrame(v); -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - v->anExec = pFrame->anExec; -#endif - v->aOp = pFrame->aOp; - v->nOp = pFrame->nOp; - v->aMem = pFrame->aMem; - v->nMem = pFrame->nMem; - v->apCsr = pFrame->apCsr; - v->nCursor = pFrame->nCursor; - v->db->lastRowid = pFrame->lastRowid; - v->nChange = pFrame->nChange; - v->db->nChange = pFrame->nDbChange; - sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0); - v->pAuxData = pFrame->pAuxData; - pFrame->pAuxData = 0; - return pFrame->pc; -} - -/* -** Close all cursors. -** -** Also release any dynamic memory held by the VM in the Vdbe.aMem memory -** cell array. This is necessary as the memory cell array may contain -** pointers to VdbeFrame objects, which may in turn contain pointers to -** open cursors. -*/ -static void closeAllCursors(Vdbe *p){ - if( p->pFrame ){ - VdbeFrame *pFrame; - for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); - sqlite3VdbeFrameRestore(pFrame); - p->pFrame = 0; - p->nFrame = 0; - } - assert( p->nFrame==0 ); - closeCursorsInFrame(p); - if( p->aMem ){ - releaseMemArray(p->aMem, p->nMem); - } - while( p->pDelFrame ){ - VdbeFrame *pDel = p->pDelFrame; - p->pDelFrame = pDel->pParent; - sqlite3VdbeFrameDelete(pDel); - } - - /* Delete any auxdata allocations made by the VM */ - if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0); - assert( p->pAuxData==0 ); -} - -/* -** Set the number of result columns that will be returned by this SQL -** statement. This is now set at compile time, rather than during -** execution of the vdbe program so that sqlite3_column_count() can -** be called on an SQL statement before sqlite3_step(). -*/ -SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){ - int n; - sqlite3 *db = p->db; - - if( p->nResColumn ){ - releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); - sqlite3DbFree(db, p->aColName); - } - n = nResColumn*COLNAME_N; - p->nResColumn = (u16)nResColumn; - p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n ); - if( p->aColName==0 ) return; - initMemArray(p->aColName, n, db, MEM_Null); -} - -/* -** Set the name of the idx'th column to be returned by the SQL statement. -** zName must be a pointer to a nul terminated string. -** -** This call must be made after a call to sqlite3VdbeSetNumCols(). -** -** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC -** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed -** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed. -*/ -SQLITE_PRIVATE int sqlite3VdbeSetColName( - Vdbe *p, /* Vdbe being configured */ - int idx, /* Index of column zName applies to */ - int var, /* One of the COLNAME_* constants */ - const char *zName, /* Pointer to buffer containing name */ - void (*xDel)(void*) /* Memory management strategy for zName */ -){ - int rc; - Mem *pColName; - assert( idxnResColumn ); - assert( vardb->mallocFailed ){ - assert( !zName || xDel!=SQLITE_DYNAMIC ); - return SQLITE_NOMEM_BKPT; - } - assert( p->aColName!=0 ); - pColName = &(p->aColName[idx+var*p->nResColumn]); - rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); - assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 ); - return rc; -} - -/* -** A read or write transaction may or may not be active on database handle -** db. If a transaction is active, commit it. If there is a -** write-transaction spanning more than one database file, this routine -** takes care of the super-journal trickery. -*/ -static int vdbeCommit(sqlite3 *db, Vdbe *p){ - int i; - int nTrans = 0; /* Number of databases with an active write-transaction - ** that are candidates for a two-phase commit using a - ** super-journal */ - int rc = SQLITE_OK; - int needXcommit = 0; - -#ifdef SQLITE_OMIT_VIRTUALTABLE - /* With this option, sqlite3VtabSync() is defined to be simply - ** SQLITE_OK so p is not used. - */ - UNUSED_PARAMETER(p); -#endif - - /* Before doing anything else, call the xSync() callback for any - ** virtual module tables written in this transaction. This has to - ** be done before determining whether a super-journal file is - ** required, as an xSync() callback may add an attached database - ** to the transaction. - */ - rc = sqlite3VtabSync(db, p); - - /* This loop determines (a) if the commit hook should be invoked and - ** (b) how many database files have open write transactions, not - ** including the temp database. (b) is important because if more than - ** one database file has an open write transaction, a super-journal - ** file is required for an atomic commit. - */ - for(i=0; rc==SQLITE_OK && inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( sqlite3BtreeIsInTrans(pBt) ){ - /* Whether or not a database might need a super-journal depends upon - ** its journal mode (among other things). This matrix determines which - ** journal modes use a super-journal and which do not */ - static const u8 aMJNeeded[] = { - /* DELETE */ 1, - /* PERSIST */ 1, - /* OFF */ 0, - /* TRUNCATE */ 1, - /* MEMORY */ 0, - /* WAL */ 0 - }; - Pager *pPager; /* Pager associated with pBt */ - needXcommit = 1; - sqlite3BtreeEnter(pBt); - pPager = sqlite3BtreePager(pBt); - if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF - && aMJNeeded[sqlite3PagerGetJournalMode(pPager)] - && sqlite3PagerIsMemdb(pPager)==0 - ){ - assert( i!=1 ); - nTrans++; - } - rc = sqlite3PagerExclusiveLock(pPager); - sqlite3BtreeLeave(pBt); - } - } - if( rc!=SQLITE_OK ){ - return rc; - } - - /* If there are any write-transactions at all, invoke the commit hook */ - if( needXcommit && db->xCommitCallback ){ - rc = db->xCommitCallback(db->pCommitArg); - if( rc ){ - return SQLITE_CONSTRAINT_COMMITHOOK; - } - } - - /* The simple case - no more than one database file (not counting the - ** TEMP database) has a transaction active. There is no need for the - ** super-journal. - ** - ** If the return value of sqlite3BtreeGetFilename() is a zero length - ** string, it means the main database is :memory: or a temp file. In - ** that case we do not support atomic multi-file commits, so use the - ** simple case then too. - */ - if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt)) - || nTrans<=1 - ){ - for(i=0; rc==SQLITE_OK && inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - rc = sqlite3BtreeCommitPhaseOne(pBt, 0); - } - } - - /* Do the commit only if all databases successfully complete phase 1. - ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an - ** IO error while deleting or truncating a journal file. It is unlikely, - ** but could happen. In this case abandon processing and return the error. - */ - for(i=0; rc==SQLITE_OK && inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - rc = sqlite3BtreeCommitPhaseTwo(pBt, 0); - } - } - if( rc==SQLITE_OK ){ - sqlite3VtabCommit(db); - } - } - - /* The complex case - There is a multi-file write-transaction active. - ** This requires a super-journal file to ensure the transaction is - ** committed atomically. - */ -#ifndef SQLITE_OMIT_DISKIO - else{ - sqlite3_vfs *pVfs = db->pVfs; - char *zSuper = 0; /* File-name for the super-journal */ - char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt); - sqlite3_file *pSuperJrnl = 0; - i64 offset = 0; - int res; - int retryCount = 0; - int nMainFile; - - /* Select a super-journal file name */ - nMainFile = sqlite3Strlen30(zMainFile); - zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0); - if( zSuper==0 ) return SQLITE_NOMEM_BKPT; - zSuper += 4; - do { - u32 iRandom; - if( retryCount ){ - if( retryCount>100 ){ - sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper); - sqlite3OsDelete(pVfs, zSuper, 0); - break; - }else if( retryCount==1 ){ - sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper); - } - } - retryCount++; - sqlite3_randomness(sizeof(iRandom), &iRandom); - sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X", - (iRandom>>8)&0xffffff, iRandom&0xff); - /* The antipenultimate character of the super-journal name must - ** be "9" to avoid name collisions when using 8+3 filenames. */ - assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' ); - sqlite3FileSuffix3(zMainFile, zSuper); - rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res); - }while( rc==SQLITE_OK && res ); - if( rc==SQLITE_OK ){ - /* Open the super-journal. */ - rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl, - SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| - SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0 - ); - } - if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, zSuper-4); - return rc; - } - - /* Write the name of each database file in the transaction into the new - ** super-journal file. If an error occurs at this point close - ** and delete the super-journal file. All the individual journal files - ** still have 'null' as the super-journal pointer, so they will roll - ** back independently if a failure occurs. - */ - for(i=0; inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( sqlite3BtreeIsInTrans(pBt) ){ - char const *zFile = sqlite3BtreeGetJournalname(pBt); - if( zFile==0 ){ - continue; /* Ignore TEMP and :memory: databases */ - } - assert( zFile[0]!=0 ); - rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset); - offset += sqlite3Strlen30(zFile)+1; - if( rc!=SQLITE_OK ){ - sqlite3OsCloseFree(pSuperJrnl); - sqlite3OsDelete(pVfs, zSuper, 0); - sqlite3DbFree(db, zSuper-4); - return rc; - } - } - } - - /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device - ** flag is set this is not required. - */ - if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL) - && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL)) - ){ - sqlite3OsCloseFree(pSuperJrnl); - sqlite3OsDelete(pVfs, zSuper, 0); - sqlite3DbFree(db, zSuper-4); - return rc; - } - - /* Sync all the db files involved in the transaction. The same call - ** sets the super-journal pointer in each individual journal. If - ** an error occurs here, do not delete the super-journal file. - ** - ** If the error occurs during the first call to - ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the - ** super-journal file will be orphaned. But we cannot delete it, - ** in case the super-journal file name was written into the journal - ** file before the failure occurred. - */ - for(i=0; rc==SQLITE_OK && inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper); - } - } - sqlite3OsCloseFree(pSuperJrnl); - assert( rc!=SQLITE_BUSY ); - if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, zSuper-4); - return rc; - } - - /* Delete the super-journal file. This commits the transaction. After - ** doing this the directory is synced again before any individual - ** transaction files are deleted. - */ - rc = sqlite3OsDelete(pVfs, zSuper, 1); - sqlite3DbFree(db, zSuper-4); - zSuper = 0; - if( rc ){ - return rc; - } - - /* All files and directories have already been synced, so the following - ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and - ** deleting or truncating journals. If something goes wrong while - ** this is happening we don't really care. The integrity of the - ** transaction is already guaranteed, but some stray 'cold' journals - ** may be lying around. Returning an error code won't help matters. - */ - disable_simulated_io_errors(); - sqlite3BeginBenignMalloc(); - for(i=0; inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - sqlite3BtreeCommitPhaseTwo(pBt, 1); - } - } - sqlite3EndBenignMalloc(); - enable_simulated_io_errors(); - - sqlite3VtabCommit(db); - } -#endif - - return rc; -} - -/* -** This routine checks that the sqlite3.nVdbeActive count variable -** matches the number of vdbe's in the list sqlite3.pVdbe that are -** currently active. An assertion fails if the two counts do not match. -** This is an internal self-check only - it is not an essential processing -** step. -** -** This is a no-op if NDEBUG is defined. -*/ -#ifndef NDEBUG -static void checkActiveVdbeCnt(sqlite3 *db){ - Vdbe *p; - int cnt = 0; - int nWrite = 0; - int nRead = 0; - p = db->pVdbe; - while( p ){ - if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){ - cnt++; - if( p->readOnly==0 ) nWrite++; - if( p->bIsReader ) nRead++; - } - p = p->pNext; - } - assert( cnt==db->nVdbeActive ); - assert( nWrite==db->nVdbeWrite ); - assert( nRead==db->nVdbeRead ); -} -#else -#define checkActiveVdbeCnt(x) -#endif - -/* -** If the Vdbe passed as the first argument opened a statement-transaction, -** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or -** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement -** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the -** statement transaction is committed. -** -** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. -** Otherwise SQLITE_OK. -*/ -static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){ - sqlite3 *const db = p->db; - int rc = SQLITE_OK; - int i; - const int iSavepoint = p->iStatement-1; - - assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE); - assert( db->nStatement>0 ); - assert( p->iStatement==(db->nStatement+db->nSavepoint) ); - - for(i=0; inDb; i++){ - int rc2 = SQLITE_OK; - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - if( eOp==SAVEPOINT_ROLLBACK ){ - rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint); - } - if( rc2==SQLITE_OK ){ - rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint); - } - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - db->nStatement--; - p->iStatement = 0; - - if( rc==SQLITE_OK ){ - if( eOp==SAVEPOINT_ROLLBACK ){ - rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint); - } - if( rc==SQLITE_OK ){ - rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint); - } - } - - /* If the statement transaction is being rolled back, also restore the - ** database handles deferred constraint counter to the value it had when - ** the statement transaction was opened. */ - if( eOp==SAVEPOINT_ROLLBACK ){ - db->nDeferredCons = p->nStmtDefCons; - db->nDeferredImmCons = p->nStmtDefImmCons; - } - return rc; -} -SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ - if( p->db->nStatement && p->iStatement ){ - return vdbeCloseStatement(p, eOp); - } - return SQLITE_OK; -} - - -/* -** This function is called when a transaction opened by the database -** handle associated with the VM passed as an argument is about to be -** committed. If there are outstanding deferred foreign key constraint -** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK. -** -** If there are outstanding FK violations and this function returns -** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY -** and write an error message to it. Then return SQLITE_ERROR. -*/ -#ifndef SQLITE_OMIT_FOREIGN_KEY -SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ - sqlite3 *db = p->db; - if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) - || (!deferred && p->nFkConstraint>0) - ){ - p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; - p->errorAction = OE_Abort; - sqlite3VdbeError(p, "FOREIGN KEY constraint failed"); - return SQLITE_ERROR; - } - return SQLITE_OK; -} -#endif - -/* -** This routine is called the when a VDBE tries to halt. If the VDBE -** has made changes and is in autocommit mode, then commit those -** changes. If a rollback is needed, then do the rollback. -** -** This routine is the only way to move the state of a VM from -** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to -** call this on a VM that is in the SQLITE_MAGIC_HALT state. -** -** Return an error code. If the commit could not complete because of -** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it -** means the close did not happen and needs to be repeated. -*/ -SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ - int rc; /* Used to store transient return codes */ - sqlite3 *db = p->db; - - /* This function contains the logic that determines if a statement or - ** transaction will be committed or rolled back as a result of the - ** execution of this virtual machine. - ** - ** If any of the following errors occur: - ** - ** SQLITE_NOMEM - ** SQLITE_IOERR - ** SQLITE_FULL - ** SQLITE_INTERRUPT - ** - ** Then the internal cache might have been left in an inconsistent - ** state. We need to rollback the statement transaction, if there is - ** one, or the complete transaction if there is no statement transaction. - */ - - if( p->magic!=VDBE_MAGIC_RUN ){ - return SQLITE_OK; - } - if( db->mallocFailed ){ - p->rc = SQLITE_NOMEM_BKPT; - } - closeAllCursors(p); - checkActiveVdbeCnt(db); - - /* No commit or rollback needed if the program never started or if the - ** SQL statement does not read or write a database file. */ - if( p->pc>=0 && p->bIsReader ){ - int mrc; /* Primary error code from p->rc */ - int eStatementOp = 0; - int isSpecialError; /* Set to true if a 'special' error */ - - /* Lock all btrees used by the statement */ - sqlite3VdbeEnter(p); - - /* Check for one of the special errors */ - mrc = p->rc & 0xff; - isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR - || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL; - if( isSpecialError ){ - /* If the query was read-only and the error code is SQLITE_INTERRUPT, - ** no rollback is necessary. Otherwise, at least a savepoint - ** transaction must be rolled back to restore the database to a - ** consistent state. - ** - ** Even if the statement is read-only, it is important to perform - ** a statement or transaction rollback operation. If the error - ** occurred while writing to the journal, sub-journal or database - ** file as part of an effort to free up cache space (see function - ** pagerStress() in pager.c), the rollback is required to restore - ** the pager to a consistent state. - */ - if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){ - if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){ - eStatementOp = SAVEPOINT_ROLLBACK; - }else{ - /* We are forced to roll back the active transaction. Before doing - ** so, abort any other statements this handle currently has active. - */ - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); - sqlite3CloseSavepoints(db); - db->autoCommit = 1; - p->nChange = 0; - } - } - } - - /* Check for immediate foreign key violations. */ - if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ - sqlite3VdbeCheckFk(p, 0); - } - - /* If the auto-commit flag is set and this is the only active writer - ** VM, then we do either a commit or rollback of the current transaction. - ** - ** Note: This block also runs if one of the special errors handled - ** above has occurred. - */ - if( !sqlite3VtabInSync(db) - && db->autoCommit - && db->nVdbeWrite==(p->readOnly==0) - ){ - if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ - rc = sqlite3VdbeCheckFk(p, 1); - if( rc!=SQLITE_OK ){ - if( NEVER(p->readOnly) ){ - sqlite3VdbeLeave(p); - return SQLITE_ERROR; - } - rc = SQLITE_CONSTRAINT_FOREIGNKEY; - }else{ - /* The auto-commit flag is true, the vdbe program was successful - ** or hit an 'OR FAIL' constraint and there are no deferred foreign - ** key constraints to hold up the transaction. This means a commit - ** is required. */ - rc = vdbeCommit(db, p); - } - if( rc==SQLITE_BUSY && p->readOnly ){ - sqlite3VdbeLeave(p); - return SQLITE_BUSY; - }else if( rc!=SQLITE_OK ){ - p->rc = rc; - sqlite3RollbackAll(db, SQLITE_OK); - p->nChange = 0; - }else{ - db->nDeferredCons = 0; - db->nDeferredImmCons = 0; - db->flags &= ~(u64)SQLITE_DeferFKs; - sqlite3CommitInternalChanges(db); - } - }else{ - sqlite3RollbackAll(db, SQLITE_OK); - p->nChange = 0; - } - db->nStatement = 0; - }else if( eStatementOp==0 ){ - if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){ - eStatementOp = SAVEPOINT_RELEASE; - }else if( p->errorAction==OE_Abort ){ - eStatementOp = SAVEPOINT_ROLLBACK; - }else{ - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); - sqlite3CloseSavepoints(db); - db->autoCommit = 1; - p->nChange = 0; - } - } - - /* If eStatementOp is non-zero, then a statement transaction needs to - ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to - ** do so. If this operation returns an error, and the current statement - ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the - ** current statement error code. - */ - if( eStatementOp ){ - rc = sqlite3VdbeCloseStatement(p, eStatementOp); - if( rc ){ - if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){ - p->rc = rc; - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = 0; - } - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); - sqlite3CloseSavepoints(db); - db->autoCommit = 1; - p->nChange = 0; - } - } - - /* If this was an INSERT, UPDATE or DELETE and no statement transaction - ** has been rolled back, update the database connection change-counter. - */ - if( p->changeCntOn ){ - if( eStatementOp!=SAVEPOINT_ROLLBACK ){ - sqlite3VdbeSetChanges(db, p->nChange); - }else{ - sqlite3VdbeSetChanges(db, 0); - } - p->nChange = 0; - } - - /* Release the locks */ - sqlite3VdbeLeave(p); - } - - /* We have successfully halted and closed the VM. Record this fact. */ - if( p->pc>=0 ){ - db->nVdbeActive--; - if( !p->readOnly ) db->nVdbeWrite--; - if( p->bIsReader ) db->nVdbeRead--; - assert( db->nVdbeActive>=db->nVdbeRead ); - assert( db->nVdbeRead>=db->nVdbeWrite ); - assert( db->nVdbeWrite>=0 ); - } - p->magic = VDBE_MAGIC_HALT; - checkActiveVdbeCnt(db); - if( db->mallocFailed ){ - p->rc = SQLITE_NOMEM_BKPT; - } - - /* If the auto-commit flag is set to true, then any locks that were held - ** by connection db have now been released. Call sqlite3ConnectionUnlocked() - ** to invoke any required unlock-notify callbacks. - */ - if( db->autoCommit ){ - sqlite3ConnectionUnlocked(db); - } - - assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 ); - return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK); -} - - -/* -** Each VDBE holds the result of the most recent sqlite3_step() call -** in p->rc. This routine sets that result back to SQLITE_OK. -*/ -SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){ - p->rc = SQLITE_OK; -} - -/* -** Copy the error code and error message belonging to the VDBE passed -** as the first argument to its database handle (so that they will be -** returned by calls to sqlite3_errcode() and sqlite3_errmsg()). -** -** This function does not clear the VDBE error code or message, just -** copies them to the database handle. -*/ -SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){ - sqlite3 *db = p->db; - int rc = p->rc; - if( p->zErrMsg ){ - db->bBenignMalloc++; - sqlite3BeginBenignMalloc(); - if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db); - sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); - sqlite3EndBenignMalloc(); - db->bBenignMalloc--; - }else if( db->pErr ){ - sqlite3ValueSetNull(db->pErr); - } - db->errCode = rc; - return rc; -} - -#ifdef SQLITE_ENABLE_SQLLOG -/* -** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, -** invoke it. -*/ -static void vdbeInvokeSqllog(Vdbe *v){ - if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){ - char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql); - assert( v->db->init.busy==0 ); - if( zExpanded ){ - sqlite3GlobalConfig.xSqllog( - sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1 - ); - sqlite3DbFree(v->db, zExpanded); - } - } -} -#else -# define vdbeInvokeSqllog(x) -#endif - -/* -** Clean up a VDBE after execution but do not delete the VDBE just yet. -** Write any error messages into *pzErrMsg. Return the result code. -** -** After this routine is run, the VDBE should be ready to be executed -** again. -** -** To look at it another way, this routine resets the state of the -** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to -** VDBE_MAGIC_INIT. -*/ -SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){ -#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) - int i; -#endif - - sqlite3 *db; - db = p->db; - - /* If the VM did not run to completion or if it encountered an - ** error, then it might not have been halted properly. So halt - ** it now. - */ - sqlite3VdbeHalt(p); - - /* If the VDBE has been run even partially, then transfer the error code - ** and error message from the VDBE into the main database structure. But - ** if the VDBE has just been set to run but has not actually executed any - ** instructions yet, leave the main database error information unchanged. - */ - if( p->pc>=0 ){ - vdbeInvokeSqllog(p); - if( db->pErr || p->zErrMsg ){ - sqlite3VdbeTransferError(p); - }else{ - db->errCode = p->rc; - } - if( p->runOnlyOnce ) p->expired = 1; - }else if( p->rc && p->expired ){ - /* The expired flag was set on the VDBE before the first call - ** to sqlite3_step(). For consistency (since sqlite3_step() was - ** called), set the database error in this case as well. - */ - sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg); - } - - /* Reset register contents and reclaim error message memory. - */ -#ifdef SQLITE_DEBUG - /* Execute assert() statements to ensure that the Vdbe.apCsr[] and - ** Vdbe.aMem[] arrays have already been cleaned up. */ - if( p->apCsr ) for(i=0; inCursor; i++) assert( p->apCsr[i]==0 ); - if( p->aMem ){ - for(i=0; inMem; i++) assert( p->aMem[i].flags==MEM_Undefined ); - } -#endif - if( p->zErrMsg ){ - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = 0; - } - p->pResultSet = 0; -#ifdef SQLITE_DEBUG - p->nWrite = 0; -#endif - - /* Save profiling information from this VDBE run. - */ -#ifdef VDBE_PROFILE - { - FILE *out = fopen("vdbe_profile.out", "a"); - if( out ){ - fprintf(out, "---- "); - for(i=0; inOp; i++){ - fprintf(out, "%02x", p->aOp[i].opcode); - } - fprintf(out, "\n"); - if( p->zSql ){ - char c, pc = 0; - fprintf(out, "-- "); - for(i=0; (c = p->zSql[i])!=0; i++){ - if( pc=='\n' ) fprintf(out, "-- "); - putc(c, out); - pc = c; - } - if( pc!='\n' ) fprintf(out, "\n"); - } - for(i=0; inOp; i++){ - char zHdr[100]; - sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ", - p->aOp[i].cnt, - p->aOp[i].cycles, - p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0 - ); - fprintf(out, "%s", zHdr); - sqlite3VdbePrintOp(out, i, &p->aOp[i]); - } - fclose(out); - } - } -#endif - p->magic = VDBE_MAGIC_RESET; - return p->rc & db->errMask; -} - -/* -** Clean up and delete a VDBE after execution. Return an integer which is -** the result code. Write any error message text into *pzErrMsg. -*/ -SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){ - int rc = SQLITE_OK; - if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){ - rc = sqlite3VdbeReset(p); - assert( (rc & p->db->errMask)==rc ); - } - sqlite3VdbeDelete(p); - return rc; -} - -/* -** If parameter iOp is less than zero, then invoke the destructor for -** all auxiliary data pointers currently cached by the VM passed as -** the first argument. -** -** Or, if iOp is greater than or equal to zero, then the destructor is -** only invoked for those auxiliary data pointers created by the user -** function invoked by the OP_Function opcode at instruction iOp of -** VM pVdbe, and only then if: -** -** * the associated function parameter is the 32nd or later (counting -** from left to right), or -** -** * the corresponding bit in argument mask is clear (where the first -** function parameter corresponds to bit 0 etc.). -*/ -SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){ - while( *pp ){ - AuxData *pAux = *pp; - if( (iOp<0) - || (pAux->iAuxOp==iOp - && pAux->iAuxArg>=0 - && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg)))) - ){ - testcase( pAux->iAuxArg==31 ); - if( pAux->xDeleteAux ){ - pAux->xDeleteAux(pAux->pAux); - } - *pp = pAux->pNextAux; - sqlite3DbFree(db, pAux); - }else{ - pp= &pAux->pNextAux; - } - } -} - -/* -** Free all memory associated with the Vdbe passed as the second argument, -** except for object itself, which is preserved. -** -** The difference between this function and sqlite3VdbeDelete() is that -** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with -** the database connection and frees the object itself. -*/ -SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){ - SubProgram *pSub, *pNext; - assert( p->db==0 || p->db==db ); - releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); - for(pSub=p->pProgram; pSub; pSub=pNext){ - pNext = pSub->pNext; - vdbeFreeOpArray(db, pSub->aOp, pSub->nOp); - sqlite3DbFree(db, pSub); - } - if( p->magic!=VDBE_MAGIC_INIT ){ - releaseMemArray(p->aVar, p->nVar); - sqlite3DbFree(db, p->pVList); - sqlite3DbFree(db, p->pFree); - } - vdbeFreeOpArray(db, p->aOp, p->nOp); - sqlite3DbFree(db, p->aColName); - sqlite3DbFree(db, p->zSql); -#ifdef SQLITE_ENABLE_NORMALIZE - sqlite3DbFree(db, p->zNormSql); - { - DblquoteStr *pThis, *pNext; - for(pThis=p->pDblStr; pThis; pThis=pNext){ - pNext = pThis->pNextStr; - sqlite3DbFree(db, pThis); - } - } -#endif -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - { - int i; - for(i=0; inScan; i++){ - sqlite3DbFree(db, p->aScan[i].zName); - } - sqlite3DbFree(db, p->aScan); - } -#endif -} - -/* -** Delete an entire VDBE. -*/ -SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){ - sqlite3 *db; - - assert( p!=0 ); - db = p->db; - assert( sqlite3_mutex_held(db->mutex) ); - sqlite3VdbeClearObject(db, p); - if( p->pPrev ){ - p->pPrev->pNext = p->pNext; - }else{ - assert( db->pVdbe==p ); - db->pVdbe = p->pNext; - } - if( p->pNext ){ - p->pNext->pPrev = p->pPrev; - } - p->magic = VDBE_MAGIC_DEAD; - p->db = 0; - sqlite3DbFreeNN(db, p); -} - -/* -** The cursor "p" has a pending seek operation that has not yet been -** carried out. Seek the cursor now. If an error occurs, return -** the appropriate error code. -*/ -SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){ - int res, rc; -#ifdef SQLITE_TEST - extern int sqlite3_search_count; -#endif - assert( p->deferredMoveto ); - assert( p->isTable ); - assert( p->eCurType==CURTYPE_BTREE ); - rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res); - if( rc ) return rc; - if( res!=0 ) return SQLITE_CORRUPT_BKPT; -#ifdef SQLITE_TEST - sqlite3_search_count++; -#endif - p->deferredMoveto = 0; - p->cacheStatus = CACHE_STALE; - return SQLITE_OK; -} - -/* -** Something has moved cursor "p" out of place. Maybe the row it was -** pointed to was deleted out from under it. Or maybe the btree was -** rebalanced. Whatever the cause, try to restore "p" to the place it -** is supposed to be pointing. If the row was deleted out from under the -** cursor, set the cursor to point to a NULL row. -*/ -static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){ - int isDifferentRow, rc; - assert( p->eCurType==CURTYPE_BTREE ); - assert( p->uc.pCursor!=0 ); - assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ); - rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow); - p->cacheStatus = CACHE_STALE; - if( isDifferentRow ) p->nullRow = 1; - return rc; -} - -/* -** Check to ensure that the cursor is valid. Restore the cursor -** if need be. Return any I/O error from the restore operation. -*/ -SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){ - assert( p->eCurType==CURTYPE_BTREE ); - if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ - return handleMovedCursor(p); - } - return SQLITE_OK; -} - -/* -** Make sure the cursor p is ready to read or write the row to which it -** was last positioned. Return an error code if an OOM fault or I/O error -** prevents us from positioning the cursor to its correct position. -** -** If a MoveTo operation is pending on the given cursor, then do that -** MoveTo now. If no move is pending, check to see if the row has been -** deleted out from under the cursor and if it has, mark the row as -** a NULL row. -** -** If the cursor is already pointing to the correct row and that row has -** not been deleted out from under the cursor, then this routine is a no-op. -*/ -SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, u32 *piCol){ - VdbeCursor *p = *pp; - assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO ); - if( p->deferredMoveto ){ - u32 iMap; - if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 && !p->nullRow ){ - *pp = p->pAltCursor; - *piCol = iMap - 1; - return SQLITE_OK; - } - return sqlite3VdbeFinishMoveto(p); - } - if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){ - return handleMovedCursor(p); - } - return SQLITE_OK; -} - -/* -** The following functions: -** -** sqlite3VdbeSerialType() -** sqlite3VdbeSerialTypeLen() -** sqlite3VdbeSerialLen() -** sqlite3VdbeSerialPut() -** sqlite3VdbeSerialGet() -** -** encapsulate the code that serializes values for storage in SQLite -** data and index records. Each serialized value consists of a -** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned -** integer, stored as a varint. -** -** In an SQLite index record, the serial type is stored directly before -** the blob of data that it corresponds to. In a table record, all serial -** types are stored at the start of the record, and the blobs of data at -** the end. Hence these functions allow the caller to handle the -** serial-type and data blob separately. -** -** The following table describes the various storage classes for data: -** -** serial type bytes of data type -** -------------- --------------- --------------- -** 0 0 NULL -** 1 1 signed integer -** 2 2 signed integer -** 3 3 signed integer -** 4 4 signed integer -** 5 6 signed integer -** 6 8 signed integer -** 7 8 IEEE float -** 8 0 Integer constant 0 -** 9 0 Integer constant 1 -** 10,11 reserved for expansion -** N>=12 and even (N-12)/2 BLOB -** N>=13 and odd (N-13)/2 text -** -** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions -** of SQLite will not understand those serial types. -*/ - -#if 0 /* Inlined into the OP_MakeRecord opcode */ -/* -** Return the serial-type for the value stored in pMem. -** -** This routine might convert a large MEM_IntReal value into MEM_Real. -** -** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord -** opcode in the byte-code engine. But by moving this routine in-line, we -** can omit some redundant tests and make that opcode a lot faster. So -** this routine is now only used by the STAT3 logic and STAT3 support has -** ended. The code is kept here for historical reference only. -*/ -SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){ - int flags = pMem->flags; - u32 n; - - assert( pLen!=0 ); - if( flags&MEM_Null ){ - *pLen = 0; - return 0; - } - if( flags&(MEM_Int|MEM_IntReal) ){ - /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ -# define MAX_6BYTE ((((i64)0x00008000)<<32)-1) - i64 i = pMem->u.i; - u64 u; - testcase( flags & MEM_Int ); - testcase( flags & MEM_IntReal ); - if( i<0 ){ - u = ~i; - }else{ - u = i; - } - if( u<=127 ){ - if( (i&1)==i && file_format>=4 ){ - *pLen = 0; - return 8+(u32)u; - }else{ - *pLen = 1; - return 1; - } - } - if( u<=32767 ){ *pLen = 2; return 2; } - if( u<=8388607 ){ *pLen = 3; return 3; } - if( u<=2147483647 ){ *pLen = 4; return 4; } - if( u<=MAX_6BYTE ){ *pLen = 6; return 5; } - *pLen = 8; - if( flags&MEM_IntReal ){ - /* If the value is IntReal and is going to take up 8 bytes to store - ** as an integer, then we might as well make it an 8-byte floating - ** point value */ - pMem->u.r = (double)pMem->u.i; - pMem->flags &= ~MEM_IntReal; - pMem->flags |= MEM_Real; - return 7; - } - return 6; - } - if( flags&MEM_Real ){ - *pLen = 8; - return 7; - } - assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) ); - assert( pMem->n>=0 ); - n = (u32)pMem->n; - if( flags & MEM_Zero ){ - n += pMem->u.nZero; - } - *pLen = n; - return ((n*2) + 12 + ((flags&MEM_Str)!=0)); -} -#endif /* inlined into OP_MakeRecord */ - -/* -** The sizes for serial types less than 128 -*/ -static const u8 sqlite3SmallTypeSizes[] = { - /* 0 1 2 3 4 5 6 7 8 9 */ -/* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, -/* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, -/* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, -/* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, -/* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, -/* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, -/* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, -/* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, -/* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, -/* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, -/* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48, -/* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53, -/* 120 */ 54, 54, 55, 55, 56, 56, 57, 57 -}; - -/* -** Return the length of the data corresponding to the supplied serial-type. -*/ -SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){ - if( serial_type>=128 ){ - return (serial_type-12)/2; - }else{ - assert( serial_type<12 - || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 ); - return sqlite3SmallTypeSizes[serial_type]; - } -} -SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){ - assert( serial_type<128 ); - return sqlite3SmallTypeSizes[serial_type]; -} - -/* -** If we are on an architecture with mixed-endian floating -** points (ex: ARM7) then swap the lower 4 bytes with the -** upper 4 bytes. Return the result. -** -** For most architectures, this is a no-op. -** -** (later): It is reported to me that the mixed-endian problem -** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems -** that early versions of GCC stored the two words of a 64-bit -** float in the wrong order. And that error has been propagated -** ever since. The blame is not necessarily with GCC, though. -** GCC might have just copying the problem from a prior compiler. -** I am also told that newer versions of GCC that follow a different -** ABI get the byte order right. -** -** Developers using SQLite on an ARM7 should compile and run their -** application using -DSQLITE_DEBUG=1 at least once. With DEBUG -** enabled, some asserts below will ensure that the byte order of -** floating point values is correct. -** -** (2007-08-30) Frank van Vugt has studied this problem closely -** and has send his findings to the SQLite developers. Frank -** writes that some Linux kernels offer floating point hardware -** emulation that uses only 32-bit mantissas instead of a full -** 48-bits as required by the IEEE standard. (This is the -** CONFIG_FPE_FASTFPE option.) On such systems, floating point -** byte swapping becomes very complicated. To avoid problems, -** the necessary byte swapping is carried out using a 64-bit integer -** rather than a 64-bit float. Frank assures us that the code here -** works for him. We, the developers, have no way to independently -** verify this, but Frank seems to know what he is talking about -** so we trust him. -*/ -#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT -static u64 floatSwap(u64 in){ - union { - u64 r; - u32 i[2]; - } u; - u32 t; - - u.r = in; - t = u.i[0]; - u.i[0] = u.i[1]; - u.i[1] = t; - return u.r; -} -# define swapMixedEndianFloat(X) X = floatSwap(X) -#else -# define swapMixedEndianFloat(X) -#endif - -/* -** Write the serialized data blob for the value stored in pMem into -** buf. It is assumed that the caller has allocated sufficient space. -** Return the number of bytes written. -** -** nBuf is the amount of space left in buf[]. The caller is responsible -** for allocating enough space to buf[] to hold the entire field, exclusive -** of the pMem->u.nZero bytes for a MEM_Zero value. -** -** Return the number of bytes actually written into buf[]. The number -** of bytes in the zero-filled tail is included in the return value only -** if those bytes were zeroed in buf[]. -*/ -SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){ - u32 len; - - /* Integer and Real */ - if( serial_type<=7 && serial_type>0 ){ - u64 v; - u32 i; - if( serial_type==7 ){ - assert( sizeof(v)==sizeof(pMem->u.r) ); - memcpy(&v, &pMem->u.r, sizeof(v)); - swapMixedEndianFloat(v); - }else{ - v = pMem->u.i; - } - len = i = sqlite3SmallTypeSizes[serial_type]; - assert( i>0 ); - do{ - buf[--i] = (u8)(v&0xFF); - v >>= 8; - }while( i ); - return len; - } - - /* String or blob */ - if( serial_type>=12 ){ - assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0) - == (int)sqlite3VdbeSerialTypeLen(serial_type) ); - len = pMem->n; - if( len>0 ) memcpy(buf, pMem->z, len); - return len; - } - - /* NULL or constants 0 or 1 */ - return 0; -} - -/* Input "x" is a sequence of unsigned characters that represent a -** big-endian integer. Return the equivalent native integer -*/ -#define ONE_BYTE_INT(x) ((i8)(x)[0]) -#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1]) -#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2]) -#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) -#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) - -/* -** Deserialize the data blob pointed to by buf as serial type serial_type -** and store the result in pMem. Return the number of bytes read. -** -** This function is implemented as two separate routines for performance. -** The few cases that require local variables are broken out into a separate -** routine so that in most cases the overhead of moving the stack pointer -** is avoided. -*/ -static u32 serialGet( - const unsigned char *buf, /* Buffer to deserialize from */ - u32 serial_type, /* Serial type to deserialize */ - Mem *pMem /* Memory cell to write value into */ -){ - u64 x = FOUR_BYTE_UINT(buf); - u32 y = FOUR_BYTE_UINT(buf+4); - x = (x<<32) + y; - if( serial_type==6 ){ - /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit - ** twos-complement integer. */ - pMem->u.i = *(i64*)&x; - pMem->flags = MEM_Int; - testcase( pMem->u.i<0 ); - }else{ - /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit - ** floating point number. */ -#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT) - /* Verify that integers and floating point values use the same - ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is - ** defined that 64-bit floating point values really are mixed - ** endian. - */ - static const u64 t1 = ((u64)0x3ff00000)<<32; - static const double r1 = 1.0; - u64 t2 = t1; - swapMixedEndianFloat(t2); - assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 ); -#endif - assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 ); - swapMixedEndianFloat(x); - memcpy(&pMem->u.r, &x, sizeof(x)); - pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real; - } - return 8; -} -SQLITE_PRIVATE u32 sqlite3VdbeSerialGet( - const unsigned char *buf, /* Buffer to deserialize from */ - u32 serial_type, /* Serial type to deserialize */ - Mem *pMem /* Memory cell to write value into */ -){ - switch( serial_type ){ - case 10: { /* Internal use only: NULL with virtual table - ** UPDATE no-change flag set */ - pMem->flags = MEM_Null|MEM_Zero; - pMem->n = 0; - pMem->u.nZero = 0; - break; - } - case 11: /* Reserved for future use */ - case 0: { /* Null */ - /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */ - pMem->flags = MEM_Null; - break; - } - case 1: { - /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement - ** integer. */ - pMem->u.i = ONE_BYTE_INT(buf); - pMem->flags = MEM_Int; - testcase( pMem->u.i<0 ); - return 1; - } - case 2: { /* 2-byte signed integer */ - /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit - ** twos-complement integer. */ - pMem->u.i = TWO_BYTE_INT(buf); - pMem->flags = MEM_Int; - testcase( pMem->u.i<0 ); - return 2; - } - case 3: { /* 3-byte signed integer */ - /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit - ** twos-complement integer. */ - pMem->u.i = THREE_BYTE_INT(buf); - pMem->flags = MEM_Int; - testcase( pMem->u.i<0 ); - return 3; - } - case 4: { /* 4-byte signed integer */ - /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit - ** twos-complement integer. */ - pMem->u.i = FOUR_BYTE_INT(buf); -#ifdef __HP_cc - /* Work around a sign-extension bug in the HP compiler for HP/UX */ - if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL; -#endif - pMem->flags = MEM_Int; - testcase( pMem->u.i<0 ); - return 4; - } - case 5: { /* 6-byte signed integer */ - /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit - ** twos-complement integer. */ - pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf); - pMem->flags = MEM_Int; - testcase( pMem->u.i<0 ); - return 6; - } - case 6: /* 8-byte signed integer */ - case 7: { /* IEEE floating point */ - /* These use local variables, so do them in a separate routine - ** to avoid having to move the frame pointer in the common case */ - return serialGet(buf,serial_type,pMem); - } - case 8: /* Integer 0 */ - case 9: { /* Integer 1 */ - /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */ - /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */ - pMem->u.i = serial_type-8; - pMem->flags = MEM_Int; - return 0; - } - default: { - /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in - ** length. - ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and - ** (N-13)/2 bytes in length. */ - static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem }; - pMem->z = (char *)buf; - pMem->n = (serial_type-12)/2; - pMem->flags = aFlag[serial_type&1]; - return pMem->n; - } - } - return 0; -} -/* -** This routine is used to allocate sufficient space for an UnpackedRecord -** structure large enough to be used with sqlite3VdbeRecordUnpack() if -** the first argument is a pointer to KeyInfo structure pKeyInfo. -** -** The space is either allocated using sqlite3DbMallocRaw() or from within -** the unaligned buffer passed via the second and third arguments (presumably -** stack space). If the former, then *ppFree is set to a pointer that should -** be eventually freed by the caller using sqlite3DbFree(). Or, if the -** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL -** before returning. -** -** If an OOM error occurs, NULL is returned. -*/ -SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( - KeyInfo *pKeyInfo /* Description of the record */ -){ - UnpackedRecord *p; /* Unpacked record to return */ - int nByte; /* Number of bytes required for *p */ - nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1); - p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte); - if( !p ) return 0; - p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))]; - assert( pKeyInfo->aSortFlags!=0 ); - p->pKeyInfo = pKeyInfo; - p->nField = pKeyInfo->nKeyField + 1; - return p; -} - -/* -** Given the nKey-byte encoding of a record in pKey[], populate the -** UnpackedRecord structure indicated by the fourth argument with the -** contents of the decoded record. -*/ -SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( - KeyInfo *pKeyInfo, /* Information about the record format */ - int nKey, /* Size of the binary record */ - const void *pKey, /* The binary record */ - UnpackedRecord *p /* Populate this structure before returning. */ -){ - const unsigned char *aKey = (const unsigned char *)pKey; - u32 d; - u32 idx; /* Offset in aKey[] to read from */ - u16 u; /* Unsigned loop counter */ - u32 szHdr; - Mem *pMem = p->aMem; - - p->default_rc = 0; - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - idx = getVarint32(aKey, szHdr); - d = szHdr; - u = 0; - while( idxenc = pKeyInfo->enc; - pMem->db = pKeyInfo->db; - /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */ - pMem->szMalloc = 0; - pMem->z = 0; - d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); - pMem++; - if( (++u)>=p->nField ) break; - } - if( d>(u32)nKey && u ){ - assert( CORRUPT_DB ); - /* In a corrupt record entry, the last pMem might have been set up using - ** uninitialized memory. Overwrite its value with NULL, to prevent - ** warnings from MSAN. */ - sqlite3VdbeMemSetNull(pMem-1); - } - assert( u<=pKeyInfo->nKeyField + 1 ); - p->nField = u; -} - -#ifdef SQLITE_DEBUG -/* -** This function compares two index or table record keys in the same way -** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(), -** this function deserializes and compares values using the -** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used -** in assert() statements to ensure that the optimized code in -** sqlite3VdbeRecordCompare() returns results with these two primitives. -** -** Return true if the result of comparison is equivalent to desiredResult. -** Return false if there is a disagreement. -*/ -static int vdbeRecordCompareDebug( - int nKey1, const void *pKey1, /* Left key */ - const UnpackedRecord *pPKey2, /* Right key */ - int desiredResult /* Correct answer */ -){ - u32 d1; /* Offset into aKey[] of next data element */ - u32 idx1; /* Offset into aKey[] of next header element */ - u32 szHdr1; /* Number of bytes in header */ - int i = 0; - int rc = 0; - const unsigned char *aKey1 = (const unsigned char *)pKey1; - KeyInfo *pKeyInfo; - Mem mem1; - - pKeyInfo = pPKey2->pKeyInfo; - if( pKeyInfo->db==0 ) return 1; - mem1.enc = pKeyInfo->enc; - mem1.db = pKeyInfo->db; - /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */ - VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ - - /* Compilers may complain that mem1.u.i is potentially uninitialized. - ** We could initialize it, as shown here, to silence those complaints. - ** But in fact, mem1.u.i will never actually be used uninitialized, and doing - ** the unnecessary initialization has a measurable negative performance - ** impact, since this routine is a very high runner. And so, we choose - ** to ignore the compiler warnings and leave this variable uninitialized. - */ - /* mem1.u.i = 0; // not needed, here to silence compiler warning */ - - idx1 = getVarint32(aKey1, szHdr1); - if( szHdr1>98307 ) return SQLITE_CORRUPT; - d1 = szHdr1; - assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB ); - assert( pKeyInfo->aSortFlags!=0 ); - assert( pKeyInfo->nKeyField>0 ); - assert( idx1<=szHdr1 || CORRUPT_DB ); - do{ - u32 serial_type1; - - /* Read the serial types for the next element in each key. */ - idx1 += getVarint32( aKey1+idx1, serial_type1 ); - - /* Verify that there is enough key space remaining to avoid - ** a buffer overread. The "d1+serial_type1+2" subexpression will - ** always be greater than or equal to the amount of required key space. - ** Use that approximation to avoid the more expensive call to - ** sqlite3VdbeSerialTypeLen() in the common case. - */ - if( d1+(u64)serial_type1+2>(u64)nKey1 - && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1 - ){ - break; - } - - /* Extract the values to be compared. - */ - d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1); - - /* Do the comparison - */ - rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], - pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0); - if( rc!=0 ){ - assert( mem1.szMalloc==0 ); /* See comment below */ - if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) - && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null)) - ){ - rc = -rc; - } - if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){ - rc = -rc; /* Invert the result for DESC sort order. */ - } - goto debugCompareEnd; - } - i++; - }while( idx1nField ); - - /* No memory allocation is ever used on mem1. Prove this using - ** the following assert(). If the assert() fails, it indicates a - ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). - */ - assert( mem1.szMalloc==0 ); - - /* rc==0 here means that one of the keys ran out of fields and - ** all the fields up to that point were equal. Return the default_rc - ** value. */ - rc = pPKey2->default_rc; - -debugCompareEnd: - if( desiredResult==0 && rc==0 ) return 1; - if( desiredResult<0 && rc<0 ) return 1; - if( desiredResult>0 && rc>0 ) return 1; - if( CORRUPT_DB ) return 1; - if( pKeyInfo->db->mallocFailed ) return 1; - return 0; -} -#endif - -#ifdef SQLITE_DEBUG -/* -** Count the number of fields (a.k.a. columns) in the record given by -** pKey,nKey. The verify that this count is less than or equal to the -** limit given by pKeyInfo->nAllField. -** -** If this constraint is not satisfied, it means that the high-speed -** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will -** not work correctly. If this assert() ever fires, it probably means -** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed -** incorrectly. -*/ -static void vdbeAssertFieldCountWithinLimits( - int nKey, const void *pKey, /* The record to verify */ - const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */ -){ - int nField = 0; - u32 szHdr; - u32 idx; - u32 notUsed; - const unsigned char *aKey = (const unsigned char*)pKey; - - if( CORRUPT_DB ) return; - idx = getVarint32(aKey, szHdr); - assert( nKey>=0 ); - assert( szHdr<=(u32)nKey ); - while( idxnAllField ); -} -#else -# define vdbeAssertFieldCountWithinLimits(A,B,C) -#endif - -/* -** Both *pMem1 and *pMem2 contain string values. Compare the two values -** using the collation sequence pColl. As usual, return a negative , zero -** or positive value if *pMem1 is less than, equal to or greater than -** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);". -*/ -static int vdbeCompareMemString( - const Mem *pMem1, - const Mem *pMem2, - const CollSeq *pColl, - u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */ -){ - if( pMem1->enc==pColl->enc ){ - /* The strings are already in the correct encoding. Call the - ** comparison function directly */ - return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z); - }else{ - int rc; - const void *v1, *v2; - Mem c1; - Mem c2; - sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null); - sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null); - sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); - sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); - v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); - v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); - if( (v1==0 || v2==0) ){ - if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT; - rc = 0; - }else{ - rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2); - } - sqlite3VdbeMemRelease(&c1); - sqlite3VdbeMemRelease(&c2); - return rc; - } -} - -/* -** The input pBlob is guaranteed to be a Blob that is not marked -** with MEM_Zero. Return true if it could be a zero-blob. -*/ -static int isAllZero(const char *z, int n){ - int i; - for(i=0; in; - int n2 = pB2->n; - - /* It is possible to have a Blob value that has some non-zero content - ** followed by zero content. But that only comes up for Blobs formed - ** by the OP_MakeRecord opcode, and such Blobs never get passed into - ** sqlite3MemCompare(). */ - assert( (pB1->flags & MEM_Zero)==0 || n1==0 ); - assert( (pB2->flags & MEM_Zero)==0 || n2==0 ); - - if( (pB1->flags|pB2->flags) & MEM_Zero ){ - if( pB1->flags & pB2->flags & MEM_Zero ){ - return pB1->u.nZero - pB2->u.nZero; - }else if( pB1->flags & MEM_Zero ){ - if( !isAllZero(pB2->z, pB2->n) ) return -1; - return pB1->u.nZero - n2; - }else{ - if( !isAllZero(pB1->z, pB1->n) ) return +1; - return n1 - pB2->u.nZero; - } - } - c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1); - if( c ) return c; - return n1 - n2; -} - -/* -** Do a comparison between a 64-bit signed integer and a 64-bit floating-point -** number. Return negative, zero, or positive if the first (i64) is less than, -** equal to, or greater than the second (double). -*/ -static int sqlite3IntFloatCompare(i64 i, double r){ - if( sizeof(LONGDOUBLE_TYPE)>8 ){ - LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i; - if( xr ) return +1; - return 0; - }else{ - i64 y; - double s; - if( r<-9223372036854775808.0 ) return +1; - if( r>=9223372036854775808.0 ) return -1; - y = (i64)r; - if( iy ) return +1; - s = (double)i; - if( sr ) return +1; - return 0; - } -} - -/* -** Compare the values contained by the two memory cells, returning -** negative, zero or positive if pMem1 is less than, equal to, or greater -** than pMem2. Sorting order is NULL's first, followed by numbers (integers -** and reals) sorted numerically, followed by text ordered by the collating -** sequence pColl and finally blob's ordered by memcmp(). -** -** Two NULL values are considered equal by this function. -*/ -SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){ - int f1, f2; - int combined_flags; - - f1 = pMem1->flags; - f2 = pMem2->flags; - combined_flags = f1|f2; - assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) ); - - /* If one value is NULL, it is less than the other. If both values - ** are NULL, return 0. - */ - if( combined_flags&MEM_Null ){ - return (f2&MEM_Null) - (f1&MEM_Null); - } - - /* At least one of the two values is a number - */ - if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){ - testcase( combined_flags & MEM_Int ); - testcase( combined_flags & MEM_Real ); - testcase( combined_flags & MEM_IntReal ); - if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){ - testcase( f1 & f2 & MEM_Int ); - testcase( f1 & f2 & MEM_IntReal ); - if( pMem1->u.i < pMem2->u.i ) return -1; - if( pMem1->u.i > pMem2->u.i ) return +1; - return 0; - } - if( (f1 & f2 & MEM_Real)!=0 ){ - if( pMem1->u.r < pMem2->u.r ) return -1; - if( pMem1->u.r > pMem2->u.r ) return +1; - return 0; - } - if( (f1&(MEM_Int|MEM_IntReal))!=0 ){ - testcase( f1 & MEM_Int ); - testcase( f1 & MEM_IntReal ); - if( (f2&MEM_Real)!=0 ){ - return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r); - }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){ - if( pMem1->u.i < pMem2->u.i ) return -1; - if( pMem1->u.i > pMem2->u.i ) return +1; - return 0; - }else{ - return -1; - } - } - if( (f1&MEM_Real)!=0 ){ - if( (f2&(MEM_Int|MEM_IntReal))!=0 ){ - testcase( f2 & MEM_Int ); - testcase( f2 & MEM_IntReal ); - return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r); - }else{ - return -1; - } - } - return +1; - } - - /* If one value is a string and the other is a blob, the string is less. - ** If both are strings, compare using the collating functions. - */ - if( combined_flags&MEM_Str ){ - if( (f1 & MEM_Str)==0 ){ - return 1; - } - if( (f2 & MEM_Str)==0 ){ - return -1; - } - - assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed ); - assert( pMem1->enc==SQLITE_UTF8 || - pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE ); - - /* The collation sequence must be defined at this point, even if - ** the user deletes the collation sequence after the vdbe program is - ** compiled (this was not always the case). - */ - assert( !pColl || pColl->xCmp ); - - if( pColl ){ - return vdbeCompareMemString(pMem1, pMem2, pColl, 0); - } - /* If a NULL pointer was passed as the collate function, fall through - ** to the blob case and use memcmp(). */ - } - - /* Both values must be blobs. Compare using memcmp(). */ - return sqlite3BlobCompare(pMem1, pMem2); -} - - -/* -** The first argument passed to this function is a serial-type that -** corresponds to an integer - all values between 1 and 9 inclusive -** except 7. The second points to a buffer containing an integer value -** serialized according to serial_type. This function deserializes -** and returns the value. -*/ -static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){ - u32 y; - assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) ); - switch( serial_type ){ - case 0: - case 1: - testcase( aKey[0]&0x80 ); - return ONE_BYTE_INT(aKey); - case 2: - testcase( aKey[0]&0x80 ); - return TWO_BYTE_INT(aKey); - case 3: - testcase( aKey[0]&0x80 ); - return THREE_BYTE_INT(aKey); - case 4: { - testcase( aKey[0]&0x80 ); - y = FOUR_BYTE_UINT(aKey); - return (i64)*(int*)&y; - } - case 5: { - testcase( aKey[0]&0x80 ); - return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey); - } - case 6: { - u64 x = FOUR_BYTE_UINT(aKey); - testcase( aKey[0]&0x80 ); - x = (x<<32) | FOUR_BYTE_UINT(aKey+4); - return (i64)*(i64*)&x; - } - } - - return (serial_type - 8); -} - -/* -** This function compares the two table rows or index records -** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero -** or positive integer if key1 is less than, equal to or -** greater than key2. The {nKey1, pKey1} key must be a blob -** created by the OP_MakeRecord opcode of the VDBE. The pPKey2 -** key must be a parsed key such as obtained from -** sqlite3VdbeParseRecord. -** -** If argument bSkip is non-zero, it is assumed that the caller has already -** determined that the first fields of the keys are equal. -** -** Key1 and Key2 do not have to contain the same number of fields. If all -** fields that appear in both keys are equal, then pPKey2->default_rc is -** returned. -** -** If database corruption is discovered, set pPKey2->errCode to -** SQLITE_CORRUPT and return 0. If an OOM error is encountered, -** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the -** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db). -*/ -SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( - int nKey1, const void *pKey1, /* Left key */ - UnpackedRecord *pPKey2, /* Right key */ - int bSkip /* If true, skip the first field */ -){ - u32 d1; /* Offset into aKey[] of next data element */ - int i; /* Index of next field to compare */ - u32 szHdr1; /* Size of record header in bytes */ - u32 idx1; /* Offset of first type in header */ - int rc = 0; /* Return value */ - Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */ - KeyInfo *pKeyInfo; - const unsigned char *aKey1 = (const unsigned char *)pKey1; - Mem mem1; - - /* If bSkip is true, then the caller has already determined that the first - ** two elements in the keys are equal. Fix the various stack variables so - ** that this routine begins comparing at the second field. */ - if( bSkip ){ - u32 s1; - idx1 = 1 + getVarint32(&aKey1[1], s1); - szHdr1 = aKey1[0]; - d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1); - i = 1; - pRhs++; - }else{ - idx1 = getVarint32(aKey1, szHdr1); - d1 = szHdr1; - i = 0; - } - if( d1>(unsigned)nKey1 ){ - pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; - return 0; /* Corruption */ - } - - VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ - assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField - || CORRUPT_DB ); - assert( pPKey2->pKeyInfo->aSortFlags!=0 ); - assert( pPKey2->pKeyInfo->nKeyField>0 ); - assert( idx1<=szHdr1 || CORRUPT_DB ); - do{ - u32 serial_type; - - /* RHS is an integer */ - if( pRhs->flags & (MEM_Int|MEM_IntReal) ){ - testcase( pRhs->flags & MEM_Int ); - testcase( pRhs->flags & MEM_IntReal ); - serial_type = aKey1[idx1]; - testcase( serial_type==12 ); - if( serial_type>=10 ){ - rc = +1; - }else if( serial_type==0 ){ - rc = -1; - }else if( serial_type==7 ){ - sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); - rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r); - }else{ - i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]); - i64 rhs = pRhs->u.i; - if( lhsrhs ){ - rc = +1; - } - } - } - - /* RHS is real */ - else if( pRhs->flags & MEM_Real ){ - serial_type = aKey1[idx1]; - if( serial_type>=10 ){ - /* Serial types 12 or greater are strings and blobs (greater than - ** numbers). Types 10 and 11 are currently "reserved for future - ** use", so it doesn't really matter what the results of comparing - ** them to numberic values are. */ - rc = +1; - }else if( serial_type==0 ){ - rc = -1; - }else{ - sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1); - if( serial_type==7 ){ - if( mem1.u.ru.r ){ - rc = -1; - }else if( mem1.u.r>pRhs->u.r ){ - rc = +1; - } - }else{ - rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r); - } - } - } - - /* RHS is a string */ - else if( pRhs->flags & MEM_Str ){ - getVarint32NR(&aKey1[idx1], serial_type); - testcase( serial_type==12 ); - if( serial_type<12 ){ - rc = -1; - }else if( !(serial_type & 0x01) ){ - rc = +1; - }else{ - mem1.n = (serial_type - 12) / 2; - testcase( (d1+mem1.n)==(unsigned)nKey1 ); - testcase( (d1+mem1.n+1)==(unsigned)nKey1 ); - if( (d1+mem1.n) > (unsigned)nKey1 - || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i - ){ - pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; - return 0; /* Corruption */ - }else if( pKeyInfo->aColl[i] ){ - mem1.enc = pKeyInfo->enc; - mem1.db = pKeyInfo->db; - mem1.flags = MEM_Str; - mem1.z = (char*)&aKey1[d1]; - rc = vdbeCompareMemString( - &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode - ); - }else{ - int nCmp = MIN(mem1.n, pRhs->n); - rc = memcmp(&aKey1[d1], pRhs->z, nCmp); - if( rc==0 ) rc = mem1.n - pRhs->n; - } - } - } - - /* RHS is a blob */ - else if( pRhs->flags & MEM_Blob ){ - assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 ); - getVarint32NR(&aKey1[idx1], serial_type); - testcase( serial_type==12 ); - if( serial_type<12 || (serial_type & 0x01) ){ - rc = -1; - }else{ - int nStr = (serial_type - 12) / 2; - testcase( (d1+nStr)==(unsigned)nKey1 ); - testcase( (d1+nStr+1)==(unsigned)nKey1 ); - if( (d1+nStr) > (unsigned)nKey1 ){ - pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; - return 0; /* Corruption */ - }else if( pRhs->flags & MEM_Zero ){ - if( !isAllZero((const char*)&aKey1[d1],nStr) ){ - rc = 1; - }else{ - rc = nStr - pRhs->u.nZero; - } - }else{ - int nCmp = MIN(nStr, pRhs->n); - rc = memcmp(&aKey1[d1], pRhs->z, nCmp); - if( rc==0 ) rc = nStr - pRhs->n; - } - } - } - - /* RHS is null */ - else{ - serial_type = aKey1[idx1]; - rc = (serial_type!=0); - } - - if( rc!=0 ){ - int sortFlags = pPKey2->pKeyInfo->aSortFlags[i]; - if( sortFlags ){ - if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0 - || ((sortFlags & KEYINFO_ORDER_DESC) - !=(serial_type==0 || (pRhs->flags&MEM_Null))) - ){ - rc = -rc; - } - } - assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) ); - assert( mem1.szMalloc==0 ); /* See comment below */ - return rc; - } - - i++; - if( i==pPKey2->nField ) break; - pRhs++; - d1 += sqlite3VdbeSerialTypeLen(serial_type); - idx1 += sqlite3VarintLen(serial_type); - }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 ); - - /* No memory allocation is ever used on mem1. Prove this using - ** the following assert(). If the assert() fails, it indicates a - ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */ - assert( mem1.szMalloc==0 ); - - /* rc==0 here means that one or both of the keys ran out of fields and - ** all the fields up to that point were equal. Return the default_rc - ** value. */ - assert( CORRUPT_DB - || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) - || pPKey2->pKeyInfo->db->mallocFailed - ); - pPKey2->eqSeen = 1; - return pPKey2->default_rc; -} -SQLITE_PRIVATE int sqlite3VdbeRecordCompare( - int nKey1, const void *pKey1, /* Left key */ - UnpackedRecord *pPKey2 /* Right key */ -){ - return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0); -} - - -/* -** This function is an optimized version of sqlite3VdbeRecordCompare() -** that (a) the first field of pPKey2 is an integer, and (b) the -** size-of-header varint at the start of (pKey1/nKey1) fits in a single -** byte (i.e. is less than 128). -** -** To avoid concerns about buffer overreads, this routine is only used -** on schemas where the maximum valid header size is 63 bytes or less. -*/ -static int vdbeRecordCompareInt( - int nKey1, const void *pKey1, /* Left key */ - UnpackedRecord *pPKey2 /* Right key */ -){ - const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F]; - int serial_type = ((const u8*)pKey1)[1]; - int res; - u32 y; - u64 x; - i64 v; - i64 lhs; - - vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo); - assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB ); - switch( serial_type ){ - case 1: { /* 1-byte signed integer */ - lhs = ONE_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 2: { /* 2-byte signed integer */ - lhs = TWO_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 3: { /* 3-byte signed integer */ - lhs = THREE_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 4: { /* 4-byte signed integer */ - y = FOUR_BYTE_UINT(aKey); - lhs = (i64)*(int*)&y; - testcase( lhs<0 ); - break; - } - case 5: { /* 6-byte signed integer */ - lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 6: { /* 8-byte signed integer */ - x = FOUR_BYTE_UINT(aKey); - x = (x<<32) | FOUR_BYTE_UINT(aKey+4); - lhs = *(i64*)&x; - testcase( lhs<0 ); - break; - } - case 8: - lhs = 0; - break; - case 9: - lhs = 1; - break; - - /* This case could be removed without changing the results of running - ** this code. Including it causes gcc to generate a faster switch - ** statement (since the range of switch targets now starts at zero and - ** is contiguous) but does not cause any duplicate code to be generated - ** (as gcc is clever enough to combine the two like cases). Other - ** compilers might be similar. */ - case 0: case 7: - return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); - - default: - return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); - } - - v = pPKey2->aMem[0].u.i; - if( v>lhs ){ - res = pPKey2->r1; - }else if( vr2; - }else if( pPKey2->nField>1 ){ - /* The first fields of the two keys are equal. Compare the trailing - ** fields. */ - res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); - }else{ - /* The first fields of the two keys are equal and there are no trailing - ** fields. Return pPKey2->default_rc in this case. */ - res = pPKey2->default_rc; - pPKey2->eqSeen = 1; - } - - assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) ); - return res; -} - -/* -** This function is an optimized version of sqlite3VdbeRecordCompare() -** that (a) the first field of pPKey2 is a string, that (b) the first field -** uses the collation sequence BINARY and (c) that the size-of-header varint -** at the start of (pKey1/nKey1) fits in a single byte. -*/ -static int vdbeRecordCompareString( - int nKey1, const void *pKey1, /* Left key */ - UnpackedRecord *pPKey2 /* Right key */ -){ - const u8 *aKey1 = (const u8*)pKey1; - int serial_type; - int res; - - assert( pPKey2->aMem[0].flags & MEM_Str ); - vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo); - serial_type = (u8)(aKey1[1]); - if( serial_type >= 0x80 ){ - sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type); - } - if( serial_type<12 ){ - res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */ - }else if( !(serial_type & 0x01) ){ - res = pPKey2->r2; /* (pKey1/nKey1) is a blob */ - }else{ - int nCmp; - int nStr; - int szHdr = aKey1[0]; - - nStr = (serial_type-12) / 2; - if( (szHdr + nStr) > nKey1 ){ - pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; - return 0; /* Corruption */ - } - nCmp = MIN( pPKey2->aMem[0].n, nStr ); - res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp); - - if( res>0 ){ - res = pPKey2->r2; - }else if( res<0 ){ - res = pPKey2->r1; - }else{ - res = nStr - pPKey2->aMem[0].n; - if( res==0 ){ - if( pPKey2->nField>1 ){ - res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1); - }else{ - res = pPKey2->default_rc; - pPKey2->eqSeen = 1; - } - }else if( res>0 ){ - res = pPKey2->r2; - }else{ - res = pPKey2->r1; - } - } - } - - assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) - || CORRUPT_DB - || pPKey2->pKeyInfo->db->mallocFailed - ); - return res; -} - -/* -** Return a pointer to an sqlite3VdbeRecordCompare() compatible function -** suitable for comparing serialized records to the unpacked record passed -** as the only argument. -*/ -SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ - /* varintRecordCompareInt() and varintRecordCompareString() both assume - ** that the size-of-header varint that occurs at the start of each record - ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt() - ** also assumes that it is safe to overread a buffer by at least the - ** maximum possible legal header size plus 8 bytes. Because there is - ** guaranteed to be at least 74 (but not 136) bytes of padding following each - ** buffer passed to varintRecordCompareInt() this makes it convenient to - ** limit the size of the header to 64 bytes in cases where the first field - ** is an integer. - ** - ** The easiest way to enforce this limit is to consider only records with - ** 13 fields or less. If the first field is an integer, the maximum legal - ** header size is (12*5 + 1 + 1) bytes. */ - if( p->pKeyInfo->nAllField<=13 ){ - int flags = p->aMem[0].flags; - if( p->pKeyInfo->aSortFlags[0] ){ - if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){ - return sqlite3VdbeRecordCompare; - } - p->r1 = 1; - p->r2 = -1; - }else{ - p->r1 = -1; - p->r2 = 1; - } - if( (flags & MEM_Int) ){ - return vdbeRecordCompareInt; - } - testcase( flags & MEM_Real ); - testcase( flags & MEM_Null ); - testcase( flags & MEM_Blob ); - if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0 - && p->pKeyInfo->aColl[0]==0 - ){ - assert( flags & MEM_Str ); - return vdbeRecordCompareString; - } - } - - return sqlite3VdbeRecordCompare; -} - -/* -** pCur points at an index entry created using the OP_MakeRecord opcode. -** Read the rowid (the last field in the record) and store it in *rowid. -** Return SQLITE_OK if everything works, or an error code otherwise. -** -** pCur might be pointing to text obtained from a corrupt database file. -** So the content cannot be trusted. Do appropriate checks on the content. -*/ -SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){ - i64 nCellKey = 0; - int rc; - u32 szHdr; /* Size of the header */ - u32 typeRowid; /* Serial type of the rowid */ - u32 lenRowid; /* Size of the rowid */ - Mem m, v; - - /* Get the size of the index entry. Only indices entries of less - ** than 2GiB are support - anything large must be database corruption. - ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so - ** this code can safely assume that nCellKey is 32-bits - */ - assert( sqlite3BtreeCursorIsValid(pCur) ); - nCellKey = sqlite3BtreePayloadSize(pCur); - assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey ); - - /* Read in the complete content of the index entry */ - sqlite3VdbeMemInit(&m, db, 0); - rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m); - if( rc ){ - return rc; - } - - /* The index entry must begin with a header size */ - getVarint32NR((u8*)m.z, szHdr); - testcase( szHdr==3 ); - testcase( szHdr==m.n ); - testcase( szHdr>0x7fffffff ); - assert( m.n>=0 ); - if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){ - goto idx_rowid_corruption; - } - - /* The last field of the index should be an integer - the ROWID. - ** Verify that the last entry really is an integer. */ - getVarint32NR((u8*)&m.z[szHdr-1], typeRowid); - testcase( typeRowid==1 ); - testcase( typeRowid==2 ); - testcase( typeRowid==3 ); - testcase( typeRowid==4 ); - testcase( typeRowid==5 ); - testcase( typeRowid==6 ); - testcase( typeRowid==8 ); - testcase( typeRowid==9 ); - if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){ - goto idx_rowid_corruption; - } - lenRowid = sqlite3SmallTypeSizes[typeRowid]; - testcase( (u32)m.n==szHdr+lenRowid ); - if( unlikely((u32)m.neCurType==CURTYPE_BTREE ); - pCur = pC->uc.pCursor; - assert( sqlite3BtreeCursorIsValid(pCur) ); - nCellKey = sqlite3BtreePayloadSize(pCur); - /* nCellKey will always be between 0 and 0xffffffff because of the way - ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ - if( nCellKey<=0 || nCellKey>0x7fffffff ){ - *res = 0; - return SQLITE_CORRUPT_BKPT; - } - sqlite3VdbeMemInit(&m, db, 0); - rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m); - if( rc ){ - return rc; - } - *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0); - sqlite3VdbeMemRelease(&m); - return SQLITE_OK; -} - -/* -** This routine sets the value to be returned by subsequent calls to -** sqlite3_changes() on the database handle 'db'. -*/ -SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){ - assert( sqlite3_mutex_held(db->mutex) ); - db->nChange = nChange; - db->nTotalChange += nChange; -} - -/* -** Set a flag in the vdbe to update the change counter when it is finalised -** or reset. -*/ -SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){ - v->changeCntOn = 1; -} - -/* -** Mark every prepared statement associated with a database connection -** as expired. -** -** An expired statement means that recompilation of the statement is -** recommend. Statements expire when things happen that make their -** programs obsolete. Removing user-defined functions or collating -** sequences, or changing an authorization function are the types of -** things that make prepared statements obsolete. -** -** If iCode is 1, then expiration is advisory. The statement should -** be reprepared before being restarted, but if it is already running -** it is allowed to run to completion. -** -** Internally, this function just sets the Vdbe.expired flag on all -** prepared statements. The flag is set to 1 for an immediate expiration -** and set to 2 for an advisory expiration. -*/ -SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){ - Vdbe *p; - for(p = db->pVdbe; p; p=p->pNext){ - p->expired = iCode+1; - } -} - -/* -** Return the database associated with the Vdbe. -*/ -SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){ - return v->db; -} - -/* -** Return the SQLITE_PREPARE flags for a Vdbe. -*/ -SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){ - return v->prepFlags; -} - -/* -** Return a pointer to an sqlite3_value structure containing the value bound -** parameter iVar of VM v. Except, if the value is an SQL NULL, return -** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_* -** constants) to the value before returning it. -** -** The returned value must be freed by the caller using sqlite3ValueFree(). -*/ -SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){ - assert( iVar>0 ); - if( v ){ - Mem *pMem = &v->aVar[iVar-1]; - assert( (v->db->flags & SQLITE_EnableQPSG)==0 ); - if( 0==(pMem->flags & MEM_Null) ){ - sqlite3_value *pRet = sqlite3ValueNew(v->db); - if( pRet ){ - sqlite3VdbeMemCopy((Mem *)pRet, pMem); - sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8); - } - return pRet; - } - } - return 0; -} - -/* -** Configure SQL variable iVar so that binding a new value to it signals -** to sqlite3_reoptimize() that re-preparing the statement may result -** in a better query plan. -*/ -SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){ - assert( iVar>0 ); - assert( (v->db->flags & SQLITE_EnableQPSG)==0 ); - if( iVar>=32 ){ - v->expmask |= 0x80000000; - }else{ - v->expmask |= ((u32)1 << (iVar-1)); - } -} - -/* -** Cause a function to throw an error if it was call from OP_PureFunc -** rather than OP_Function. -** -** OP_PureFunc means that the function must be deterministic, and should -** throw an error if it is given inputs that would make it non-deterministic. -** This routine is invoked by date/time functions that use non-deterministic -** features such as 'now'. -*/ -SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){ - const VdbeOp *pOp; -#ifdef SQLITE_ENABLE_STAT4 - if( pCtx->pVdbe==0 ) return 1; -#endif - pOp = pCtx->pVdbe->aOp + pCtx->iOp; - if( pOp->opcode==OP_PureFunc ){ - const char *zContext; - char *zMsg; - if( pOp->p5 & NC_IsCheck ){ - zContext = "a CHECK constraint"; - }else if( pOp->p5 & NC_GenCol ){ - zContext = "a generated column"; - }else{ - zContext = "an index"; - } - zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s", - pCtx->pFunc->zName, zContext); - sqlite3_result_error(pCtx, zMsg, -1); - sqlite3_free(zMsg); - return 0; - } - return 1; -} - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored -** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored -** in memory obtained from sqlite3DbMalloc). -*/ -SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){ - if( pVtab->zErrMsg ){ - sqlite3 *db = p->db; - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg); - sqlite3_free(pVtab->zErrMsg); - pVtab->zErrMsg = 0; - } -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - -/* -** If the second argument is not NULL, release any allocations associated -** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord -** structure itself, using sqlite3DbFree(). -** -** This function is used to free UnpackedRecord structures allocated by -** the vdbeUnpackRecord() function found in vdbeapi.c. -*/ -static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){ - if( p ){ - int i; - for(i=0; iaMem[i]; - if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem); - } - sqlite3DbFreeNN(db, p); - } -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -/* -** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call, -** then cursor passed as the second argument should point to the row about -** to be update or deleted. If the application calls sqlite3_preupdate_old(), -** the required value will be read from the row the cursor points to. -*/ -SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( - Vdbe *v, /* Vdbe pre-update hook is invoked by */ - VdbeCursor *pCsr, /* Cursor to grab old.* values from */ - int op, /* SQLITE_INSERT, UPDATE or DELETE */ - const char *zDb, /* Database name */ - Table *pTab, /* Modified table */ - i64 iKey1, /* Initial key value */ - int iReg /* Register for new.* record */ -){ - sqlite3 *db = v->db; - i64 iKey2; - PreUpdate preupdate; - const char *zTbl = pTab->zName; - static const u8 fakeSortOrder = 0; - - assert( db->pPreUpdate==0 ); - memset(&preupdate, 0, sizeof(PreUpdate)); - if( HasRowid(pTab)==0 ){ - iKey1 = iKey2 = 0; - preupdate.pPk = sqlite3PrimaryKeyIndex(pTab); - }else{ - if( op==SQLITE_UPDATE ){ - iKey2 = v->aMem[iReg].u.i; - }else{ - iKey2 = iKey1; - } - } - - assert( pCsr->nField==pTab->nCol - || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1) - ); - - preupdate.v = v; - preupdate.pCsr = pCsr; - preupdate.op = op; - preupdate.iNewReg = iReg; - preupdate.keyinfo.db = db; - preupdate.keyinfo.enc = ENC(db); - preupdate.keyinfo.nKeyField = pTab->nCol; - preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder; - preupdate.iKey1 = iKey1; - preupdate.iKey2 = iKey2; - preupdate.pTab = pTab; - - db->pPreUpdate = &preupdate; - db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2); - db->pPreUpdate = 0; - sqlite3DbFree(db, preupdate.aRecord); - vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked); - vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked); - if( preupdate.aNew ){ - int i; - for(i=0; inField; i++){ - sqlite3VdbeMemRelease(&preupdate.aNew[i]); - } - sqlite3DbFreeNN(db, preupdate.aNew); - } -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -/************** End of vdbeaux.c *********************************************/ -/************** Begin file vdbeapi.c *****************************************/ -/* -** 2004 May 26 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains code use to implement APIs that are part of the -** VDBE. -*/ -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** Return TRUE (non-zero) of the statement supplied as an argument needs -** to be recompiled. A statement needs to be recompiled whenever the -** execution environment changes in a way that would alter the program -** that sqlite3_prepare() generates. For example, if new functions or -** collating sequences are registered or if an authorizer function is -** added or changed. -*/ -SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ - Vdbe *p = (Vdbe*)pStmt; - return p==0 || p->expired; -} -#endif - -/* -** Check on a Vdbe to make sure it has not been finalized. Log -** an error and return true if it has been finalized (or is otherwise -** invalid). Return false if it is ok. -*/ -static int vdbeSafety(Vdbe *p){ - if( p->db==0 ){ - sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); - return 1; - }else{ - return 0; - } -} -static int vdbeSafetyNotNull(Vdbe *p){ - if( p==0 ){ - sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); - return 1; - }else{ - return vdbeSafety(p); - } -} - -#ifndef SQLITE_OMIT_TRACE -/* -** Invoke the profile callback. This routine is only called if we already -** know that the profile callback is defined and needs to be invoked. -*/ -static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){ - sqlite3_int64 iNow; - sqlite3_int64 iElapse; - assert( p->startTime>0 ); - assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 ); - assert( db->init.busy==0 ); - assert( p->zSql!=0 ); - sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); - iElapse = (iNow - p->startTime)*1000000; -#ifndef SQLITE_OMIT_DEPRECATED - if( db->xProfile ){ - db->xProfile(db->pProfileArg, p->zSql, iElapse); - } -#endif - if( db->mTrace & SQLITE_TRACE_PROFILE ){ - db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse); - } - p->startTime = 0; -} -/* -** The checkProfileCallback(DB,P) macro checks to see if a profile callback -** is needed, and it invokes the callback if it is needed. -*/ -# define checkProfileCallback(DB,P) \ - if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); } -#else -# define checkProfileCallback(DB,P) /*no-op*/ -#endif - -/* -** The following routine destroys a virtual machine that is created by -** the sqlite3_compile() routine. The integer returned is an SQLITE_ -** success/failure code that describes the result of executing the virtual -** machine. -** -** This routine sets the error code and string returned by -** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). -*/ -SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){ - int rc; - if( pStmt==0 ){ - /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL - ** pointer is a harmless no-op. */ - rc = SQLITE_OK; - }else{ - Vdbe *v = (Vdbe*)pStmt; - sqlite3 *db = v->db; - if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT; - sqlite3_mutex_enter(db->mutex); - checkProfileCallback(db, v); - rc = sqlite3VdbeFinalize(v); - rc = sqlite3ApiExit(db, rc); - sqlite3LeaveMutexAndCloseZombie(db); - } - return rc; -} - -/* -** Terminate the current execution of an SQL statement and reset it -** back to its starting state so that it can be reused. A success code from -** the prior execution is returned. -** -** This routine sets the error code and string returned by -** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16(). -*/ -SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){ - int rc; - if( pStmt==0 ){ - rc = SQLITE_OK; - }else{ - Vdbe *v = (Vdbe*)pStmt; - sqlite3 *db = v->db; - sqlite3_mutex_enter(db->mutex); - checkProfileCallback(db, v); - rc = sqlite3VdbeReset(v); - sqlite3VdbeRewind(v); - assert( (rc & (db->errMask))==rc ); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - } - return rc; -} - -/* -** Set all the parameters in the compiled SQL statement to NULL. -*/ -SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ - int i; - int rc = SQLITE_OK; - Vdbe *p = (Vdbe*)pStmt; -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; -#endif - sqlite3_mutex_enter(mutex); - for(i=0; inVar; i++){ - sqlite3VdbeMemRelease(&p->aVar[i]); - p->aVar[i].flags = MEM_Null; - } - assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 ); - if( p->expmask ){ - p->expired = 1; - } - sqlite3_mutex_leave(mutex); - return rc; -} - - -/**************************** sqlite3_value_ ******************************* -** The following routines extract information from a Mem or sqlite3_value -** structure. -*/ -SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){ - Mem *p = (Mem*)pVal; - if( p->flags & (MEM_Blob|MEM_Str) ){ - if( ExpandBlob(p)!=SQLITE_OK ){ - assert( p->flags==MEM_Null && p->z==0 ); - return 0; - } - p->flags |= MEM_Blob; - return p->n ? p->z : 0; - }else{ - return sqlite3_value_text(pVal); - } -} -SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){ - return sqlite3ValueBytes(pVal, SQLITE_UTF8); -} -SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){ - return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE); -} -SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){ - return sqlite3VdbeRealValue((Mem*)pVal); -} -SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){ - return (int)sqlite3VdbeIntValue((Mem*)pVal); -} -SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){ - return sqlite3VdbeIntValue((Mem*)pVal); -} -SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){ - Mem *pMem = (Mem*)pVal; - return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0); -} -SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){ - Mem *p = (Mem*)pVal; - if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) == - (MEM_Null|MEM_Term|MEM_Subtype) - && zPType!=0 - && p->eSubtype=='p' - && strcmp(p->u.zPType, zPType)==0 - ){ - return (void*)p->z; - }else{ - return 0; - } -} -SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){ - return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){ - return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE); -} -SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){ - return sqlite3ValueText(pVal, SQLITE_UTF16BE); -} -SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){ - return sqlite3ValueText(pVal, SQLITE_UTF16LE); -} -#endif /* SQLITE_OMIT_UTF16 */ -/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five -** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating -** point number string BLOB NULL -*/ -SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){ - static const u8 aType[] = { - SQLITE_BLOB, /* 0x00 (not possible) */ - SQLITE_NULL, /* 0x01 NULL */ - SQLITE_TEXT, /* 0x02 TEXT */ - SQLITE_NULL, /* 0x03 (not possible) */ - SQLITE_INTEGER, /* 0x04 INTEGER */ - SQLITE_NULL, /* 0x05 (not possible) */ - SQLITE_INTEGER, /* 0x06 INTEGER + TEXT */ - SQLITE_NULL, /* 0x07 (not possible) */ - SQLITE_FLOAT, /* 0x08 FLOAT */ - SQLITE_NULL, /* 0x09 (not possible) */ - SQLITE_FLOAT, /* 0x0a FLOAT + TEXT */ - SQLITE_NULL, /* 0x0b (not possible) */ - SQLITE_INTEGER, /* 0x0c (not possible) */ - SQLITE_NULL, /* 0x0d (not possible) */ - SQLITE_INTEGER, /* 0x0e (not possible) */ - SQLITE_NULL, /* 0x0f (not possible) */ - SQLITE_BLOB, /* 0x10 BLOB */ - SQLITE_NULL, /* 0x11 (not possible) */ - SQLITE_TEXT, /* 0x12 (not possible) */ - SQLITE_NULL, /* 0x13 (not possible) */ - SQLITE_INTEGER, /* 0x14 INTEGER + BLOB */ - SQLITE_NULL, /* 0x15 (not possible) */ - SQLITE_INTEGER, /* 0x16 (not possible) */ - SQLITE_NULL, /* 0x17 (not possible) */ - SQLITE_FLOAT, /* 0x18 FLOAT + BLOB */ - SQLITE_NULL, /* 0x19 (not possible) */ - SQLITE_FLOAT, /* 0x1a (not possible) */ - SQLITE_NULL, /* 0x1b (not possible) */ - SQLITE_INTEGER, /* 0x1c (not possible) */ - SQLITE_NULL, /* 0x1d (not possible) */ - SQLITE_INTEGER, /* 0x1e (not possible) */ - SQLITE_NULL, /* 0x1f (not possible) */ - SQLITE_FLOAT, /* 0x20 INTREAL */ - SQLITE_NULL, /* 0x21 (not possible) */ - SQLITE_TEXT, /* 0x22 INTREAL + TEXT */ - SQLITE_NULL, /* 0x23 (not possible) */ - SQLITE_FLOAT, /* 0x24 (not possible) */ - SQLITE_NULL, /* 0x25 (not possible) */ - SQLITE_FLOAT, /* 0x26 (not possible) */ - SQLITE_NULL, /* 0x27 (not possible) */ - SQLITE_FLOAT, /* 0x28 (not possible) */ - SQLITE_NULL, /* 0x29 (not possible) */ - SQLITE_FLOAT, /* 0x2a (not possible) */ - SQLITE_NULL, /* 0x2b (not possible) */ - SQLITE_FLOAT, /* 0x2c (not possible) */ - SQLITE_NULL, /* 0x2d (not possible) */ - SQLITE_FLOAT, /* 0x2e (not possible) */ - SQLITE_NULL, /* 0x2f (not possible) */ - SQLITE_BLOB, /* 0x30 (not possible) */ - SQLITE_NULL, /* 0x31 (not possible) */ - SQLITE_TEXT, /* 0x32 (not possible) */ - SQLITE_NULL, /* 0x33 (not possible) */ - SQLITE_FLOAT, /* 0x34 (not possible) */ - SQLITE_NULL, /* 0x35 (not possible) */ - SQLITE_FLOAT, /* 0x36 (not possible) */ - SQLITE_NULL, /* 0x37 (not possible) */ - SQLITE_FLOAT, /* 0x38 (not possible) */ - SQLITE_NULL, /* 0x39 (not possible) */ - SQLITE_FLOAT, /* 0x3a (not possible) */ - SQLITE_NULL, /* 0x3b (not possible) */ - SQLITE_FLOAT, /* 0x3c (not possible) */ - SQLITE_NULL, /* 0x3d (not possible) */ - SQLITE_FLOAT, /* 0x3e (not possible) */ - SQLITE_NULL, /* 0x3f (not possible) */ - }; -#ifdef SQLITE_DEBUG - { - int eType = SQLITE_BLOB; - if( pVal->flags & MEM_Null ){ - eType = SQLITE_NULL; - }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){ - eType = SQLITE_FLOAT; - }else if( pVal->flags & MEM_Int ){ - eType = SQLITE_INTEGER; - }else if( pVal->flags & MEM_Str ){ - eType = SQLITE_TEXT; - } - assert( eType == aType[pVal->flags&MEM_AffMask] ); - } -#endif - return aType[pVal->flags&MEM_AffMask]; -} - -/* Return true if a parameter to xUpdate represents an unchanged column */ -SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){ - return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero); -} - -/* Return true if a parameter value originated from an sqlite3_bind() */ -SQLITE_API int sqlite3_value_frombind(sqlite3_value *pVal){ - return (pVal->flags&MEM_FromBind)!=0; -} - -/* Make a copy of an sqlite3_value object -*/ -SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){ - sqlite3_value *pNew; - if( pOrig==0 ) return 0; - pNew = sqlite3_malloc( sizeof(*pNew) ); - if( pNew==0 ) return 0; - memset(pNew, 0, sizeof(*pNew)); - memcpy(pNew, pOrig, MEMCELLSIZE); - pNew->flags &= ~MEM_Dyn; - pNew->db = 0; - if( pNew->flags&(MEM_Str|MEM_Blob) ){ - pNew->flags &= ~(MEM_Static|MEM_Dyn); - pNew->flags |= MEM_Ephem; - if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){ - sqlite3ValueFree(pNew); - pNew = 0; - } - } - return pNew; -} - -/* Destroy an sqlite3_value object previously obtained from -** sqlite3_value_dup(). -*/ -SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){ - sqlite3ValueFree(pOld); -} - - -/**************************** sqlite3_result_ ******************************* -** The following routines are used by user-defined functions to specify -** the function result. -** -** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the -** result as a string or blob but if the string or blob is too large, it -** then sets the error code to SQLITE_TOOBIG -** -** The invokeValueDestructor(P,X) routine invokes destructor function X() -** on value P is not going to be used and need to be destroyed. -*/ -static void setResultStrOrError( - sqlite3_context *pCtx, /* Function context */ - const char *z, /* String pointer */ - int n, /* Bytes in string, or negative */ - u8 enc, /* Encoding of z. 0 for BLOBs */ - void (*xDel)(void*) /* Destructor function */ -){ - if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){ - sqlite3_result_error_toobig(pCtx); - } -} -static int invokeValueDestructor( - const void *p, /* Value to destroy */ - void (*xDel)(void*), /* The destructor */ - sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */ -){ - assert( xDel!=SQLITE_DYNAMIC ); - if( xDel==0 ){ - /* noop */ - }else if( xDel==SQLITE_TRANSIENT ){ - /* noop */ - }else{ - xDel((void*)p); - } - if( pCtx ) sqlite3_result_error_toobig(pCtx); - return SQLITE_TOOBIG; -} -SQLITE_API void sqlite3_result_blob( - sqlite3_context *pCtx, - const void *z, - int n, - void (*xDel)(void *) -){ - assert( n>=0 ); - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - setResultStrOrError(pCtx, z, n, 0, xDel); -} -SQLITE_API void sqlite3_result_blob64( - sqlite3_context *pCtx, - const void *z, - sqlite3_uint64 n, - void (*xDel)(void *) -){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - assert( xDel!=SQLITE_DYNAMIC ); - if( n>0x7fffffff ){ - (void)invokeValueDestructor(z, xDel, pCtx); - }else{ - setResultStrOrError(pCtx, z, (int)n, 0, xDel); - } -} -SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetDouble(pCtx->pOut, rVal); -} -SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - pCtx->isError = SQLITE_ERROR; - sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - pCtx->isError = SQLITE_ERROR; - sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT); -} -#endif -SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal); -} -SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetInt64(pCtx->pOut, iVal); -} -SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetNull(pCtx->pOut); -} -SQLITE_API void sqlite3_result_pointer( - sqlite3_context *pCtx, - void *pPtr, - const char *zPType, - void (*xDestructor)(void*) -){ - Mem *pOut = pCtx->pOut; - assert( sqlite3_mutex_held(pOut->db->mutex) ); - sqlite3VdbeMemRelease(pOut); - pOut->flags = MEM_Null; - sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor); -} -SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){ - Mem *pOut = pCtx->pOut; - assert( sqlite3_mutex_held(pOut->db->mutex) ); - pOut->eSubtype = eSubtype & 0xff; - pOut->flags |= MEM_Subtype; -} -SQLITE_API void sqlite3_result_text( - sqlite3_context *pCtx, - const char *z, - int n, - void (*xDel)(void *) -){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel); -} -SQLITE_API void sqlite3_result_text64( - sqlite3_context *pCtx, - const char *z, - sqlite3_uint64 n, - void (*xDel)(void *), - unsigned char enc -){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - assert( xDel!=SQLITE_DYNAMIC ); - if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; - if( n>0x7fffffff ){ - (void)invokeValueDestructor(z, xDel, pCtx); - }else{ - setResultStrOrError(pCtx, z, (int)n, enc, xDel); - } -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API void sqlite3_result_text16( - sqlite3_context *pCtx, - const void *z, - int n, - void (*xDel)(void *) -){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel); -} -SQLITE_API void sqlite3_result_text16be( - sqlite3_context *pCtx, - const void *z, - int n, - void (*xDel)(void *) -){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel); -} -SQLITE_API void sqlite3_result_text16le( - sqlite3_context *pCtx, - const void *z, - int n, - void (*xDel)(void *) -){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel); -} -#endif /* SQLITE_OMIT_UTF16 */ -SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemCopy(pCtx->pOut, pValue); -} -SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n); -} -SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){ - Mem *pOut = pCtx->pOut; - assert( sqlite3_mutex_held(pOut->db->mutex) ); - if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){ - return SQLITE_TOOBIG; - } - sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n); - return SQLITE_OK; -} -SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){ - pCtx->isError = errCode ? errCode : -1; -#ifdef SQLITE_DEBUG - if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode; -#endif - if( pCtx->pOut->flags & MEM_Null ){ - sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, - SQLITE_UTF8, SQLITE_STATIC); - } -} - -/* Force an SQLITE_TOOBIG error. */ -SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - pCtx->isError = SQLITE_TOOBIG; - sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, - SQLITE_UTF8, SQLITE_STATIC); -} - -/* An SQLITE_NOMEM error. */ -SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - sqlite3VdbeMemSetNull(pCtx->pOut); - pCtx->isError = SQLITE_NOMEM_BKPT; - sqlite3OomFault(pCtx->pOut->db); -} - -#ifndef SQLITE_UNTESTABLE -/* Force the INT64 value currently stored as the result to be -** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL -** test-control. -*/ -SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){ - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); - if( pCtx->pOut->flags & MEM_Int ){ - pCtx->pOut->flags &= ~MEM_Int; - pCtx->pOut->flags |= MEM_IntReal; - } -} -#endif - - -/* -** This function is called after a transaction has been committed. It -** invokes callbacks registered with sqlite3_wal_hook() as required. -*/ -static int doWalCallbacks(sqlite3 *db){ - int rc = SQLITE_OK; -#ifndef SQLITE_OMIT_WAL - int i; - for(i=0; inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - int nEntry; - sqlite3BtreeEnter(pBt); - nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt)); - sqlite3BtreeLeave(pBt); - if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){ - rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry); - } - } - } -#endif - return rc; -} - - -/* -** Execute the statement pStmt, either until a row of data is ready, the -** statement is completely executed or an error occurs. -** -** This routine implements the bulk of the logic behind the sqlite_step() -** API. The only thing omitted is the automatic recompile if a -** schema change has occurred. That detail is handled by the -** outer sqlite3_step() wrapper procedure. -*/ -static int sqlite3Step(Vdbe *p){ - sqlite3 *db; - int rc; - - assert(p); - if( p->magic!=VDBE_MAGIC_RUN ){ - /* We used to require that sqlite3_reset() be called before retrying - ** sqlite3_step() after any error or after SQLITE_DONE. But beginning - ** with version 3.7.0, we changed this so that sqlite3_reset() would - ** be called automatically instead of throwing the SQLITE_MISUSE error. - ** This "automatic-reset" change is not technically an incompatibility, - ** since any application that receives an SQLITE_MISUSE is broken by - ** definition. - ** - ** Nevertheless, some published applications that were originally written - ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE - ** returns, and those were broken by the automatic-reset change. As a - ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the - ** legacy behavior of returning SQLITE_MISUSE for cases where the - ** previous sqlite3_step() returned something other than a SQLITE_LOCKED - ** or SQLITE_BUSY error. - */ -#ifdef SQLITE_OMIT_AUTORESET - if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){ - sqlite3_reset((sqlite3_stmt*)p); - }else{ - return SQLITE_MISUSE_BKPT; - } -#else - sqlite3_reset((sqlite3_stmt*)p); -#endif - } - - /* Check that malloc() has not failed. If it has, return early. */ - db = p->db; - if( db->mallocFailed ){ - p->rc = SQLITE_NOMEM; - return SQLITE_NOMEM_BKPT; - } - - if( p->pc<0 && p->expired ){ - p->rc = SQLITE_SCHEMA; - rc = SQLITE_ERROR; - if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){ - /* If this statement was prepared using saved SQL and an - ** error has occurred, then return the error code in p->rc to the - ** caller. Set the error code in the database handle to the same value. - */ - rc = sqlite3VdbeTransferError(p); - } - goto end_of_step; - } - if( p->pc<0 ){ - /* If there are no other statements currently running, then - ** reset the interrupt flag. This prevents a call to sqlite3_interrupt - ** from interrupting a statement that has not yet started. - */ - if( db->nVdbeActive==0 ){ - AtomicStore(&db->u1.isInterrupted, 0); - } - - assert( db->nVdbeWrite>0 || db->autoCommit==0 - || (db->nDeferredCons==0 && db->nDeferredImmCons==0) - ); - -#ifndef SQLITE_OMIT_TRACE - if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 - && !db->init.busy && p->zSql ){ - sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime); - }else{ - assert( p->startTime==0 ); - } -#endif - - db->nVdbeActive++; - if( p->readOnly==0 ) db->nVdbeWrite++; - if( p->bIsReader ) db->nVdbeRead++; - p->pc = 0; - } -#ifdef SQLITE_DEBUG - p->rcApp = SQLITE_OK; -#endif -#ifndef SQLITE_OMIT_EXPLAIN - if( p->explain ){ - rc = sqlite3VdbeList(p); - }else -#endif /* SQLITE_OMIT_EXPLAIN */ - { - db->nVdbeExec++; - rc = sqlite3VdbeExec(p); - db->nVdbeExec--; - } - - if( rc!=SQLITE_ROW ){ -#ifndef SQLITE_OMIT_TRACE - /* If the statement completed successfully, invoke the profile callback */ - checkProfileCallback(db, p); -#endif - - if( rc==SQLITE_DONE && db->autoCommit ){ - assert( p->rc==SQLITE_OK ); - p->rc = doWalCallbacks(db); - if( p->rc!=SQLITE_OK ){ - rc = SQLITE_ERROR; - } - }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){ - /* If this statement was prepared using saved SQL and an - ** error has occurred, then return the error code in p->rc to the - ** caller. Set the error code in the database handle to the same value. - */ - rc = sqlite3VdbeTransferError(p); - } - } - - db->errCode = rc; - if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){ - p->rc = SQLITE_NOMEM_BKPT; - if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc; - } -end_of_step: - /* There are only a limited number of result codes allowed from the - ** statements prepared using the legacy sqlite3_prepare() interface */ - assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 - || rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR - || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE - ); - return (rc&db->errMask); -} - -/* -** This is the top-level implementation of sqlite3_step(). Call -** sqlite3Step() to do most of the work. If a schema error occurs, -** call sqlite3Reprepare() and try again. -*/ -SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){ - int rc = SQLITE_OK; /* Result from sqlite3Step() */ - Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */ - int cnt = 0; /* Counter to prevent infinite loop of reprepares */ - sqlite3 *db; /* The database connection */ - - if( vdbeSafetyNotNull(v) ){ - return SQLITE_MISUSE_BKPT; - } - db = v->db; - sqlite3_mutex_enter(db->mutex); - v->doingRerun = 0; - while( (rc = sqlite3Step(v))==SQLITE_SCHEMA - && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){ - int savedPc = v->pc; - rc = sqlite3Reprepare(v); - if( rc!=SQLITE_OK ){ - /* This case occurs after failing to recompile an sql statement. - ** The error message from the SQL compiler has already been loaded - ** into the database handle. This block copies the error message - ** from the database handle into the statement and sets the statement - ** program counter to 0 to ensure that when the statement is - ** finalized or reset the parser error message is available via - ** sqlite3_errmsg() and sqlite3_errcode(). - */ - const char *zErr = (const char *)sqlite3_value_text(db->pErr); - sqlite3DbFree(db, v->zErrMsg); - if( !db->mallocFailed ){ - v->zErrMsg = sqlite3DbStrDup(db, zErr); - v->rc = rc = sqlite3ApiExit(db, rc); - } else { - v->zErrMsg = 0; - v->rc = rc = SQLITE_NOMEM_BKPT; - } - break; - } - sqlite3_reset(pStmt); - if( savedPc>=0 ) v->doingRerun = 1; - assert( v->expired==0 ); - } - sqlite3_mutex_leave(db->mutex); - return rc; -} - - -/* -** Extract the user data from a sqlite3_context structure and return a -** pointer to it. -*/ -SQLITE_API void *sqlite3_user_data(sqlite3_context *p){ - assert( p && p->pFunc ); - return p->pFunc->pUserData; -} - -/* -** Extract the user data from a sqlite3_context structure and return a -** pointer to it. -** -** IMPLEMENTATION-OF: R-46798-50301 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 *p){ - assert( p && p->pOut ); - return p->pOut->db; -} - -/* -** If this routine is invoked from within an xColumn method of a virtual -** table, then it returns true if and only if the the call is during an -** UPDATE operation and the value of the column will not be modified -** by the UPDATE. -** -** If this routine is called from any context other than within the -** xColumn method of a virtual table, then the return value is meaningless -** and arbitrary. -** -** Virtual table implements might use this routine to optimize their -** performance by substituting a NULL result, or some other light-weight -** value, as a signal to the xUpdate routine that the column is unchanged. -*/ -SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){ - assert( p ); - return sqlite3_value_nochange(p->pOut); -} - -/* -** Return the current time for a statement. If the current time -** is requested more than once within the same run of a single prepared -** statement, the exact same time is returned for each invocation regardless -** of the amount of time that elapses between invocations. In other words, -** the time returned is always the time of the first call. -*/ -SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){ - int rc; -#ifndef SQLITE_ENABLE_STAT4 - sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime; - assert( p->pVdbe!=0 ); -#else - sqlite3_int64 iTime = 0; - sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime; -#endif - if( *piTime==0 ){ - rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime); - if( rc ) *piTime = 0; - } - return *piTime; -} - -/* -** Create a new aggregate context for p and return a pointer to -** its pMem->z element. -*/ -static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){ - Mem *pMem = p->pMem; - assert( (pMem->flags & MEM_Agg)==0 ); - if( nByte<=0 ){ - sqlite3VdbeMemSetNull(pMem); - pMem->z = 0; - }else{ - sqlite3VdbeMemClearAndResize(pMem, nByte); - pMem->flags = MEM_Agg; - pMem->u.pDef = p->pFunc; - if( pMem->z ){ - memset(pMem->z, 0, nByte); - } - } - return (void*)pMem->z; -} - -/* -** Allocate or return the aggregate context for a user function. A new -** context is allocated on the first call. Subsequent calls return the -** same context that was returned on prior calls. -*/ -SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){ - assert( p && p->pFunc && p->pFunc->xFinalize ); - assert( sqlite3_mutex_held(p->pOut->db->mutex) ); - testcase( nByte<0 ); - if( (p->pMem->flags & MEM_Agg)==0 ){ - return createAggContext(p, nByte); - }else{ - return (void*)p->pMem->z; - } -} - -/* -** Return the auxiliary data pointer, if any, for the iArg'th argument to -** the user-function defined by pCtx. -** -** The left-most argument is 0. -** -** Undocumented behavior: If iArg is negative then access a cache of -** auxiliary data pointers that is available to all functions within a -** single prepared statement. The iArg values must match. -*/ -SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){ - AuxData *pAuxData; - - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); -#if SQLITE_ENABLE_STAT4 - if( pCtx->pVdbe==0 ) return 0; -#else - assert( pCtx->pVdbe!=0 ); -#endif - for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){ - if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){ - return pAuxData->pAux; - } - } - return 0; -} - -/* -** Set the auxiliary data pointer and delete function, for the iArg'th -** argument to the user-function defined by pCtx. Any previous value is -** deleted by calling the delete function specified when it was set. -** -** The left-most argument is 0. -** -** Undocumented behavior: If iArg is negative then make the data available -** to all functions within the current prepared statement using iArg as an -** access code. -*/ -SQLITE_API void sqlite3_set_auxdata( - sqlite3_context *pCtx, - int iArg, - void *pAux, - void (*xDelete)(void*) -){ - AuxData *pAuxData; - Vdbe *pVdbe = pCtx->pVdbe; - - assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); -#ifdef SQLITE_ENABLE_STAT4 - if( pVdbe==0 ) goto failed; -#else - assert( pVdbe!=0 ); -#endif - - for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){ - if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){ - break; - } - } - if( pAuxData==0 ){ - pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData)); - if( !pAuxData ) goto failed; - pAuxData->iAuxOp = pCtx->iOp; - pAuxData->iAuxArg = iArg; - pAuxData->pNextAux = pVdbe->pAuxData; - pVdbe->pAuxData = pAuxData; - if( pCtx->isError==0 ) pCtx->isError = -1; - }else if( pAuxData->xDeleteAux ){ - pAuxData->xDeleteAux(pAuxData->pAux); - } - - pAuxData->pAux = pAux; - pAuxData->xDeleteAux = xDelete; - return; - -failed: - if( xDelete ){ - xDelete(pAux); - } -} - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** Return the number of times the Step function of an aggregate has been -** called. -** -** This function is deprecated. Do not use it for new code. It is -** provide only to avoid breaking legacy code. New aggregate function -** implementations should keep their own counts within their aggregate -** context. -*/ -SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){ - assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize ); - return p->pMem->n; -} -#endif - -/* -** Return the number of columns in the result set for the statement pStmt. -*/ -SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){ - Vdbe *pVm = (Vdbe *)pStmt; - return pVm ? pVm->nResColumn : 0; -} - -/* -** Return the number of values available from the current row of the -** currently executing statement pStmt. -*/ -SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){ - Vdbe *pVm = (Vdbe *)pStmt; - if( pVm==0 || pVm->pResultSet==0 ) return 0; - return pVm->nResColumn; -} - -/* -** Return a pointer to static memory containing an SQL NULL value. -*/ -static const Mem *columnNullValue(void){ - /* Even though the Mem structure contains an element - ** of type i64, on certain architectures (x86) with certain compiler - ** switches (-Os), gcc may align this Mem object on a 4-byte boundary - ** instead of an 8-byte one. This all works fine, except that when - ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s - ** that a Mem structure is located on an 8-byte boundary. To prevent - ** these assert()s from failing, when building with SQLITE_DEBUG defined - ** using gcc, we force nullMem to be 8-byte aligned using the magical - ** __attribute__((aligned(8))) macro. */ - static const Mem nullMem -#if defined(SQLITE_DEBUG) && defined(__GNUC__) - __attribute__((aligned(8))) -#endif - = { - /* .u = */ {0}, - /* .flags = */ (u16)MEM_Null, - /* .enc = */ (u8)0, - /* .eSubtype = */ (u8)0, - /* .n = */ (int)0, - /* .z = */ (char*)0, - /* .zMalloc = */ (char*)0, - /* .szMalloc = */ (int)0, - /* .uTemp = */ (u32)0, - /* .db = */ (sqlite3*)0, - /* .xDel = */ (void(*)(void*))0, -#ifdef SQLITE_DEBUG - /* .pScopyFrom = */ (Mem*)0, - /* .mScopyFlags= */ 0, -#endif - }; - return &nullMem; -} - -/* -** Check to see if column iCol of the given statement is valid. If -** it is, return a pointer to the Mem for the value of that column. -** If iCol is not valid, return a pointer to a Mem which has a value -** of NULL. -*/ -static Mem *columnMem(sqlite3_stmt *pStmt, int i){ - Vdbe *pVm; - Mem *pOut; - - pVm = (Vdbe *)pStmt; - if( pVm==0 ) return (Mem*)columnNullValue(); - assert( pVm->db ); - sqlite3_mutex_enter(pVm->db->mutex); - if( pVm->pResultSet!=0 && inResColumn && i>=0 ){ - pOut = &pVm->pResultSet[i]; - }else{ - sqlite3Error(pVm->db, SQLITE_RANGE); - pOut = (Mem*)columnNullValue(); - } - return pOut; -} - -/* -** This function is called after invoking an sqlite3_value_XXX function on a -** column value (i.e. a value returned by evaluating an SQL expression in the -** select list of a SELECT statement) that may cause a malloc() failure. If -** malloc() has failed, the threads mallocFailed flag is cleared and the result -** code of statement pStmt set to SQLITE_NOMEM. -** -** Specifically, this is called from within: -** -** sqlite3_column_int() -** sqlite3_column_int64() -** sqlite3_column_text() -** sqlite3_column_text16() -** sqlite3_column_real() -** sqlite3_column_bytes() -** sqlite3_column_bytes16() -** sqiite3_column_blob() -*/ -static void columnMallocFailure(sqlite3_stmt *pStmt) -{ - /* If malloc() failed during an encoding conversion within an - ** sqlite3_column_XXX API, then set the return code of the statement to - ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR - ** and _finalize() will return NOMEM. - */ - Vdbe *p = (Vdbe *)pStmt; - if( p ){ - assert( p->db!=0 ); - assert( sqlite3_mutex_held(p->db->mutex) ); - p->rc = sqlite3ApiExit(p->db, p->rc); - sqlite3_mutex_leave(p->db->mutex); - } -} - -/**************************** sqlite3_column_ ******************************* -** The following routines are used to access elements of the current row -** in the result set. -*/ -SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){ - const void *val; - val = sqlite3_value_blob( columnMem(pStmt,i) ); - /* Even though there is no encoding conversion, value_blob() might - ** need to call malloc() to expand the result of a zeroblob() - ** expression. - */ - columnMallocFailure(pStmt); - return val; -} -SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){ - int val = sqlite3_value_bytes( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return val; -} -SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){ - int val = sqlite3_value_bytes16( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return val; -} -SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){ - double val = sqlite3_value_double( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return val; -} -SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){ - int val = sqlite3_value_int( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return val; -} -SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){ - sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return val; -} -SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){ - const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return val; -} -SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){ - Mem *pOut = columnMem(pStmt, i); - if( pOut->flags&MEM_Static ){ - pOut->flags &= ~MEM_Static; - pOut->flags |= MEM_Ephem; - } - columnMallocFailure(pStmt); - return (sqlite3_value *)pOut; -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){ - const void *val = sqlite3_value_text16( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return val; -} -#endif /* SQLITE_OMIT_UTF16 */ -SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){ - int iType = sqlite3_value_type( columnMem(pStmt,i) ); - columnMallocFailure(pStmt); - return iType; -} - -/* -** Convert the N-th element of pStmt->pColName[] into a string using -** xFunc() then return that string. If N is out of range, return 0. -** -** There are up to 5 names for each column. useType determines which -** name is returned. Here are the names: -** -** 0 The column name as it should be displayed for output -** 1 The datatype name for the column -** 2 The name of the database that the column derives from -** 3 The name of the table that the column derives from -** 4 The name of the table column that the result column derives from -** -** If the result is not a simple column reference (if it is an expression -** or a constant) then useTypes 2, 3, and 4 return NULL. -*/ -static const void *columnName( - sqlite3_stmt *pStmt, /* The statement */ - int N, /* Which column to get the name for */ - int useUtf16, /* True to return the name as UTF16 */ - int useType /* What type of name */ -){ - const void *ret; - Vdbe *p; - int n; - sqlite3 *db; -#ifdef SQLITE_ENABLE_API_ARMOR - if( pStmt==0 ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - ret = 0; - p = (Vdbe *)pStmt; - db = p->db; - assert( db!=0 ); - n = sqlite3_column_count(pStmt); - if( N=0 ){ - N += useType*n; - sqlite3_mutex_enter(db->mutex); - assert( db->mallocFailed==0 ); -#ifndef SQLITE_OMIT_UTF16 - if( useUtf16 ){ - ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]); - }else -#endif - { - ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]); - } - /* A malloc may have failed inside of the _text() call. If this - ** is the case, clear the mallocFailed flag and return NULL. - */ - if( db->mallocFailed ){ - sqlite3OomClear(db); - ret = 0; - } - sqlite3_mutex_leave(db->mutex); - } - return ret; -} - -/* -** Return the name of the Nth column of the result set returned by SQL -** statement pStmt. -*/ -SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 0, COLNAME_NAME); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 1, COLNAME_NAME); -} -#endif - -/* -** Constraint: If you have ENABLE_COLUMN_METADATA then you must -** not define OMIT_DECLTYPE. -*/ -#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA) -# error "Must not define both SQLITE_OMIT_DECLTYPE \ - and SQLITE_ENABLE_COLUMN_METADATA" -#endif - -#ifndef SQLITE_OMIT_DECLTYPE -/* -** Return the column declaration type (if applicable) of the 'i'th column -** of the result set of SQL statement pStmt. -*/ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 0, COLNAME_DECLTYPE); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 1, COLNAME_DECLTYPE); -} -#endif /* SQLITE_OMIT_UTF16 */ -#endif /* SQLITE_OMIT_DECLTYPE */ - -#ifdef SQLITE_ENABLE_COLUMN_METADATA -/* -** Return the name of the database from which a result column derives. -** NULL is returned if the result column is an expression or constant or -** anything else which is not an unambiguous reference to a database column. -*/ -SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 0, COLNAME_DATABASE); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 1, COLNAME_DATABASE); -} -#endif /* SQLITE_OMIT_UTF16 */ - -/* -** Return the name of the table from which a result column derives. -** NULL is returned if the result column is an expression or constant or -** anything else which is not an unambiguous reference to a database column. -*/ -SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 0, COLNAME_TABLE); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 1, COLNAME_TABLE); -} -#endif /* SQLITE_OMIT_UTF16 */ - -/* -** Return the name of the table column from which a result column derives. -** NULL is returned if the result column is an expression or constant or -** anything else which is not an unambiguous reference to a database column. -*/ -SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 0, COLNAME_COLUMN); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){ - return columnName(pStmt, N, 1, COLNAME_COLUMN); -} -#endif /* SQLITE_OMIT_UTF16 */ -#endif /* SQLITE_ENABLE_COLUMN_METADATA */ - - -/******************************* sqlite3_bind_ *************************** -** -** Routines used to attach values to wildcards in a compiled SQL statement. -*/ -/* -** Unbind the value bound to variable i in virtual machine p. This is the -** the same as binding a NULL value to the column. If the "i" parameter is -** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK. -** -** A successful evaluation of this routine acquires the mutex on p. -** the mutex is released if any kind of error occurs. -** -** The error code stored in database p->db is overwritten with the return -** value in any case. -*/ -static int vdbeUnbind(Vdbe *p, int i){ - Mem *pVar; - if( vdbeSafetyNotNull(p) ){ - return SQLITE_MISUSE_BKPT; - } - sqlite3_mutex_enter(p->db->mutex); - if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ - sqlite3Error(p->db, SQLITE_MISUSE); - sqlite3_mutex_leave(p->db->mutex); - sqlite3_log(SQLITE_MISUSE, - "bind on a busy prepared statement: [%s]", p->zSql); - return SQLITE_MISUSE_BKPT; - } - if( i<1 || i>p->nVar ){ - sqlite3Error(p->db, SQLITE_RANGE); - sqlite3_mutex_leave(p->db->mutex); - return SQLITE_RANGE; - } - i--; - pVar = &p->aVar[i]; - sqlite3VdbeMemRelease(pVar); - pVar->flags = MEM_Null; - p->db->errCode = SQLITE_OK; - - /* If the bit corresponding to this variable in Vdbe.expmask is set, then - ** binding a new value to this variable invalidates the current query plan. - ** - ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a 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 bindings of that parameter. - */ - assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 ); - if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<expired = 1; - } - return SQLITE_OK; -} - -/* -** Bind a text or BLOB value. -*/ -static int bindText( - sqlite3_stmt *pStmt, /* The statement to bind against */ - int i, /* Index of the parameter to bind */ - const void *zData, /* Pointer to the data to be bound */ - int nData, /* Number of bytes of data to be bound */ - void (*xDel)(void*), /* Destructor for the data */ - u8 encoding /* Encoding for the data */ -){ - Vdbe *p = (Vdbe *)pStmt; - Mem *pVar; - int rc; - - rc = vdbeUnbind(p, i); - if( rc==SQLITE_OK ){ - if( zData!=0 ){ - pVar = &p->aVar[i-1]; - rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); - if( rc==SQLITE_OK && encoding!=0 ){ - rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db)); - } - if( rc ){ - sqlite3Error(p->db, rc); - rc = sqlite3ApiExit(p->db, rc); - } - } - sqlite3_mutex_leave(p->db->mutex); - }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){ - xDel((void*)zData); - } - return rc; -} - - -/* -** Bind a blob value to an SQL statement variable. -*/ -SQLITE_API int sqlite3_bind_blob( - sqlite3_stmt *pStmt, - int i, - const void *zData, - int nData, - void (*xDel)(void*) -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( nData<0 ) return SQLITE_MISUSE_BKPT; -#endif - return bindText(pStmt, i, zData, nData, xDel, 0); -} -SQLITE_API int sqlite3_bind_blob64( - sqlite3_stmt *pStmt, - int i, - const void *zData, - sqlite3_uint64 nData, - void (*xDel)(void*) -){ - assert( xDel!=SQLITE_DYNAMIC ); - if( nData>0x7fffffff ){ - return invokeValueDestructor(zData, xDel, 0); - }else{ - return bindText(pStmt, i, zData, (int)nData, xDel, 0); - } -} -SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){ - int rc; - Vdbe *p = (Vdbe *)pStmt; - rc = vdbeUnbind(p, i); - if( rc==SQLITE_OK ){ - sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue); - sqlite3_mutex_leave(p->db->mutex); - } - return rc; -} -SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){ - return sqlite3_bind_int64(p, i, (i64)iValue); -} -SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ - int rc; - Vdbe *p = (Vdbe *)pStmt; - rc = vdbeUnbind(p, i); - if( rc==SQLITE_OK ){ - sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); - sqlite3_mutex_leave(p->db->mutex); - } - return rc; -} -SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ - int rc; - Vdbe *p = (Vdbe*)pStmt; - rc = vdbeUnbind(p, i); - if( rc==SQLITE_OK ){ - sqlite3_mutex_leave(p->db->mutex); - } - return rc; -} -SQLITE_API int sqlite3_bind_pointer( - sqlite3_stmt *pStmt, - int i, - void *pPtr, - const char *zPTtype, - void (*xDestructor)(void*) -){ - int rc; - Vdbe *p = (Vdbe*)pStmt; - rc = vdbeUnbind(p, i); - if( rc==SQLITE_OK ){ - sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor); - sqlite3_mutex_leave(p->db->mutex); - }else if( xDestructor ){ - xDestructor(pPtr); - } - return rc; -} -SQLITE_API int sqlite3_bind_text( - sqlite3_stmt *pStmt, - int i, - const char *zData, - int nData, - void (*xDel)(void*) -){ - return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8); -} -SQLITE_API int sqlite3_bind_text64( - sqlite3_stmt *pStmt, - int i, - const char *zData, - sqlite3_uint64 nData, - void (*xDel)(void*), - unsigned char enc -){ - assert( xDel!=SQLITE_DYNAMIC ); - if( nData>0x7fffffff ){ - return invokeValueDestructor(zData, xDel, 0); - }else{ - if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; - return bindText(pStmt, i, zData, (int)nData, xDel, enc); - } -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API int sqlite3_bind_text16( - sqlite3_stmt *pStmt, - int i, - const void *zData, - int nData, - void (*xDel)(void*) -){ - return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE); -} -#endif /* SQLITE_OMIT_UTF16 */ -SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){ - int rc; - switch( sqlite3_value_type((sqlite3_value*)pValue) ){ - case SQLITE_INTEGER: { - rc = sqlite3_bind_int64(pStmt, i, pValue->u.i); - break; - } - case SQLITE_FLOAT: { - rc = sqlite3_bind_double(pStmt, i, pValue->u.r); - break; - } - case SQLITE_BLOB: { - if( pValue->flags & MEM_Zero ){ - rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero); - }else{ - rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT); - } - break; - } - case SQLITE_TEXT: { - rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT, - pValue->enc); - break; - } - default: { - rc = sqlite3_bind_null(pStmt, i); - break; - } - } - return rc; -} -SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){ - int rc; - Vdbe *p = (Vdbe *)pStmt; - rc = vdbeUnbind(p, i); - if( rc==SQLITE_OK ){ - sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n); - sqlite3_mutex_leave(p->db->mutex); - } - return rc; -} -SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){ - int rc; - Vdbe *p = (Vdbe *)pStmt; - sqlite3_mutex_enter(p->db->mutex); - if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){ - rc = SQLITE_TOOBIG; - }else{ - assert( (n & 0x7FFFFFFF)==n ); - rc = sqlite3_bind_zeroblob(pStmt, i, n); - } - rc = sqlite3ApiExit(p->db, rc); - sqlite3_mutex_leave(p->db->mutex); - return rc; -} - -/* -** Return the number of wildcards that can be potentially bound to. -** This routine is added to support DBD::SQLite. -*/ -SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){ - Vdbe *p = (Vdbe*)pStmt; - return p ? p->nVar : 0; -} - -/* -** Return the name of a wildcard parameter. Return NULL if the index -** is out of range or if the wildcard is unnamed. -** -** The result is always UTF-8. -*/ -SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){ - Vdbe *p = (Vdbe*)pStmt; - if( p==0 ) return 0; - return sqlite3VListNumToName(p->pVList, i); -} - -/* -** Given a wildcard parameter name, return the index of the variable -** with that name. If there is no variable with the given name, -** return 0. -*/ -SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){ - if( p==0 || zName==0 ) return 0; - return sqlite3VListNameToNum(p->pVList, zName, nName); -} -SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){ - return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName)); -} - -/* -** Transfer all bindings from the first statement over to the second. -*/ -SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ - Vdbe *pFrom = (Vdbe*)pFromStmt; - Vdbe *pTo = (Vdbe*)pToStmt; - int i; - assert( pTo->db==pFrom->db ); - assert( pTo->nVar==pFrom->nVar ); - sqlite3_mutex_enter(pTo->db->mutex); - for(i=0; inVar; i++){ - sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); - } - sqlite3_mutex_leave(pTo->db->mutex); - return SQLITE_OK; -} - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** Deprecated external interface. Internal/core SQLite code -** should call sqlite3TransferBindings. -** -** It is misuse to call this routine with statements from different -** database connections. But as this is a deprecated interface, we -** will not bother to check for that condition. -** -** If the two statements contain a different number of bindings, then -** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise -** SQLITE_OK is returned. -*/ -SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){ - Vdbe *pFrom = (Vdbe*)pFromStmt; - Vdbe *pTo = (Vdbe*)pToStmt; - if( pFrom->nVar!=pTo->nVar ){ - return SQLITE_ERROR; - } - assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 ); - if( pTo->expmask ){ - pTo->expired = 1; - } - assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 ); - if( pFrom->expmask ){ - pFrom->expired = 1; - } - return sqlite3TransferBindings(pFromStmt, pToStmt); -} -#endif - -/* -** Return the sqlite3* database handle to which the prepared statement given -** in the argument belongs. This is the same database handle that was -** the first argument to the sqlite3_prepare() that was used to create -** the statement in the first place. -*/ -SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){ - return pStmt ? ((Vdbe*)pStmt)->db : 0; -} - -/* -** Return true if the prepared statement is guaranteed to not modify the -** database. -*/ -SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){ - return pStmt ? ((Vdbe*)pStmt)->readOnly : 1; -} - -/* -** Return 1 if the statement is an EXPLAIN and return 2 if the -** statement is an EXPLAIN QUERY PLAN -*/ -SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){ - return pStmt ? ((Vdbe*)pStmt)->explain : 0; -} - -/* -** Return true if the prepared statement is in need of being reset. -*/ -SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){ - Vdbe *v = (Vdbe*)pStmt; - return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0; -} - -/* -** Return a pointer to the next prepared statement after pStmt associated -** with database connection pDb. If pStmt is NULL, return the first -** prepared statement for the database connection. Return NULL if there -** are no more. -*/ -SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){ - sqlite3_stmt *pNext; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(pDb) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - sqlite3_mutex_enter(pDb->mutex); - if( pStmt==0 ){ - pNext = (sqlite3_stmt*)pDb->pVdbe; - }else{ - pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext; - } - sqlite3_mutex_leave(pDb->mutex); - return pNext; -} - -/* -** Return the value of a status counter for a prepared statement -*/ -SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){ - Vdbe *pVdbe = (Vdbe*)pStmt; - u32 v; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !pStmt - || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter))) - ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - if( op==SQLITE_STMTSTATUS_MEMUSED ){ - sqlite3 *db = pVdbe->db; - sqlite3_mutex_enter(db->mutex); - v = 0; - db->pnBytesFreed = (int*)&v; - sqlite3VdbeClearObject(db, pVdbe); - sqlite3DbFree(db, pVdbe); - db->pnBytesFreed = 0; - sqlite3_mutex_leave(db->mutex); - }else{ - v = pVdbe->aCounter[op]; - if( resetFlag ) pVdbe->aCounter[op] = 0; - } - return (int)v; -} - -/* -** Return the SQL associated with a prepared statement -*/ -SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ - Vdbe *p = (Vdbe *)pStmt; - return p ? p->zSql : 0; -} - -/* -** Return the SQL associated with a prepared statement with -** bound parameters expanded. Space to hold the returned string is -** obtained from sqlite3_malloc(). The caller is responsible for -** freeing the returned string by passing it to sqlite3_free(). -** -** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of -** expanded bound parameters. -*/ -SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){ -#ifdef SQLITE_OMIT_TRACE - return 0; -#else - char *z = 0; - const char *zSql = sqlite3_sql(pStmt); - if( zSql ){ - Vdbe *p = (Vdbe *)pStmt; - sqlite3_mutex_enter(p->db->mutex); - z = sqlite3VdbeExpandSql(p, zSql); - sqlite3_mutex_leave(p->db->mutex); - } - return z; -#endif -} - -#ifdef SQLITE_ENABLE_NORMALIZE -/* -** Return the normalized SQL associated with a prepared statement. -*/ -SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){ - Vdbe *p = (Vdbe *)pStmt; - if( p==0 ) return 0; - if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){ - sqlite3_mutex_enter(p->db->mutex); - p->zNormSql = sqlite3Normalize(p, p->zSql); - sqlite3_mutex_leave(p->db->mutex); - } - return p->zNormSql; -} -#endif /* SQLITE_ENABLE_NORMALIZE */ - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -/* -** Allocate and populate an UnpackedRecord structure based on the serialized -** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure -** if successful, or a NULL pointer if an OOM error is encountered. -*/ -static UnpackedRecord *vdbeUnpackRecord( - KeyInfo *pKeyInfo, - int nKey, - const void *pKey -){ - UnpackedRecord *pRet; /* Return value */ - - pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); - if( pRet ){ - memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1)); - sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet); - } - return pRet; -} - -/* -** This function is called from within a pre-update callback to retrieve -** a field of the row currently being updated or deleted. -*/ -SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ - PreUpdate *p = db->pPreUpdate; - Mem *pMem; - int rc = SQLITE_OK; - - /* Test that this call is being made from within an SQLITE_DELETE or - ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */ - if( !p || p->op==SQLITE_INSERT ){ - rc = SQLITE_MISUSE_BKPT; - goto preupdate_old_out; - } - if( p->pPk ){ - iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx); - } - if( iIdx>=p->pCsr->nField || iIdx<0 ){ - rc = SQLITE_RANGE; - goto preupdate_old_out; - } - - /* If the old.* record has not yet been loaded into memory, do so now. */ - if( p->pUnpacked==0 ){ - u32 nRec; - u8 *aRec; - - nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor); - aRec = sqlite3DbMallocRaw(db, nRec); - if( !aRec ) goto preupdate_old_out; - rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec); - if( rc==SQLITE_OK ){ - p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec); - if( !p->pUnpacked ) rc = SQLITE_NOMEM; - } - if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, aRec); - goto preupdate_old_out; - } - p->aRecord = aRec; - } - - pMem = *ppValue = &p->pUnpacked->aMem[iIdx]; - if( iIdx==p->pTab->iPKey ){ - sqlite3VdbeMemSetInt64(pMem, p->iKey1); - }else if( iIdx>=p->pUnpacked->nField ){ - *ppValue = (sqlite3_value *)columnNullValue(); - }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){ - if( pMem->flags & (MEM_Int|MEM_IntReal) ){ - testcase( pMem->flags & MEM_Int ); - testcase( pMem->flags & MEM_IntReal ); - sqlite3VdbeMemRealify(pMem); - } - } - - preupdate_old_out: - sqlite3Error(db, rc); - return sqlite3ApiExit(db, rc); -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -/* -** This function is called from within a pre-update callback to retrieve -** the number of columns in the row being updated, deleted or inserted. -*/ -SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){ - PreUpdate *p = db->pPreUpdate; - return (p ? p->keyinfo.nKeyField : 0); -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -/* -** This function is designed to be called from within a pre-update callback -** only. It returns zero if the change that caused the callback was made -** immediately by a user SQL statement. Or, if the change was made by a -** trigger program, it returns the number of trigger programs currently -** on the stack (1 for a top-level trigger, 2 for a trigger fired by a -** top-level trigger etc.). -** -** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL -** or SET DEFAULT action is considered a trigger. -*/ -SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){ - PreUpdate *p = db->pPreUpdate; - return (p ? p->v->nFrame : 0); -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -/* -** This function is called from within a pre-update callback to retrieve -** a field of the row currently being updated or inserted. -*/ -SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){ - PreUpdate *p = db->pPreUpdate; - int rc = SQLITE_OK; - Mem *pMem; - - if( !p || p->op==SQLITE_DELETE ){ - rc = SQLITE_MISUSE_BKPT; - goto preupdate_new_out; - } - if( p->pPk && p->op!=SQLITE_UPDATE ){ - iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx); - } - if( iIdx>=p->pCsr->nField || iIdx<0 ){ - rc = SQLITE_RANGE; - goto preupdate_new_out; - } - - if( p->op==SQLITE_INSERT ){ - /* For an INSERT, memory cell p->iNewReg contains the serialized record - ** that is being inserted. Deserialize it. */ - UnpackedRecord *pUnpack = p->pNewUnpacked; - if( !pUnpack ){ - Mem *pData = &p->v->aMem[p->iNewReg]; - rc = ExpandBlob(pData); - if( rc!=SQLITE_OK ) goto preupdate_new_out; - pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z); - if( !pUnpack ){ - rc = SQLITE_NOMEM; - goto preupdate_new_out; - } - p->pNewUnpacked = pUnpack; - } - pMem = &pUnpack->aMem[iIdx]; - if( iIdx==p->pTab->iPKey ){ - sqlite3VdbeMemSetInt64(pMem, p->iKey2); - }else if( iIdx>=pUnpack->nField ){ - pMem = (sqlite3_value *)columnNullValue(); - } - }else{ - /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required - ** value. Make a copy of the cell contents and return a pointer to it. - ** It is not safe to return a pointer to the memory cell itself as the - ** caller may modify the value text encoding. - */ - assert( p->op==SQLITE_UPDATE ); - if( !p->aNew ){ - p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField); - if( !p->aNew ){ - rc = SQLITE_NOMEM; - goto preupdate_new_out; - } - } - assert( iIdx>=0 && iIdxpCsr->nField ); - pMem = &p->aNew[iIdx]; - if( pMem->flags==0 ){ - if( iIdx==p->pTab->iPKey ){ - sqlite3VdbeMemSetInt64(pMem, p->iKey2); - }else{ - rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]); - if( rc!=SQLITE_OK ) goto preupdate_new_out; - } - } - } - *ppValue = pMem; - - preupdate_new_out: - sqlite3Error(db, rc); - return sqlite3ApiExit(db, rc); -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS -/* -** Return status data for a single loop within query pStmt. -*/ -SQLITE_API int sqlite3_stmt_scanstatus( - sqlite3_stmt *pStmt, /* Prepared statement being queried */ - int idx, /* Index of loop to report on */ - int iScanStatusOp, /* Which metric to return */ - void *pOut /* OUT: Write the answer here */ -){ - Vdbe *p = (Vdbe*)pStmt; - ScanStatus *pScan; - if( idx<0 || idx>=p->nScan ) return 1; - pScan = &p->aScan[idx]; - switch( iScanStatusOp ){ - case SQLITE_SCANSTAT_NLOOP: { - *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop]; - break; - } - case SQLITE_SCANSTAT_NVISIT: { - *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit]; - break; - } - case SQLITE_SCANSTAT_EST: { - double r = 1.0; - LogEst x = pScan->nEst; - while( x<100 ){ - x += 10; - r *= 0.5; - } - *(double*)pOut = r*sqlite3LogEstToInt(x); - break; - } - case SQLITE_SCANSTAT_NAME: { - *(const char**)pOut = pScan->zName; - break; - } - case SQLITE_SCANSTAT_EXPLAIN: { - if( pScan->addrExplain ){ - *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z; - }else{ - *(const char**)pOut = 0; - } - break; - } - case SQLITE_SCANSTAT_SELECTID: { - if( pScan->addrExplain ){ - *(int*)pOut = p->aOp[ pScan->addrExplain ].p1; - }else{ - *(int*)pOut = -1; - } - break; - } - default: { - return 1; - } - } - return 0; -} - -/* -** Zero all counters associated with the sqlite3_stmt_scanstatus() data. -*/ -SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){ - Vdbe *p = (Vdbe*)pStmt; - memset(p->anExec, 0, p->nOp * sizeof(i64)); -} -#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */ - -/************** End of vdbeapi.c *********************************************/ -/************** Begin file vdbetrace.c ***************************************/ -/* -** 2009 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 used to insert the values of host parameters -** (aka "wildcards") into the SQL text output by sqlite3_trace(). -** -** The Vdbe parse-tree explainer is also found here. -*/ -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -#ifndef SQLITE_OMIT_TRACE - -/* -** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of -** bytes in this text up to but excluding the first character in -** a host parameter. If the text contains no host parameters, return -** the total number of bytes in the text. -*/ -static int findNextHostParameter(const char *zSql, int *pnToken){ - int tokenType; - int nTotal = 0; - int n; - - *pnToken = 0; - while( zSql[0] ){ - n = sqlite3GetToken((u8*)zSql, &tokenType); - assert( n>0 && tokenType!=TK_ILLEGAL ); - if( tokenType==TK_VARIABLE ){ - *pnToken = n; - break; - } - nTotal += n; - zSql += n; - } - return nTotal; -} - -/* -** This function returns a pointer to a nul-terminated string in memory -** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the -** string contains a copy of zRawSql but with host parameters expanded to -** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, -** then the returned string holds a copy of zRawSql with "-- " prepended -** to each line of text. -** -** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then -** then long strings and blobs are truncated to that many bytes. This -** can be used to prevent unreasonably large trace strings when dealing -** with large (multi-megabyte) strings and blobs. -** -** The calling function is responsible for making sure the memory returned -** is eventually freed. -** -** ALGORITHM: Scan the input string looking for host parameters in any of -** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within -** string literals, quoted identifier names, and comments. For text forms, -** the host parameter index is found by scanning the prepared -** statement for the corresponding OP_Variable opcode. Once the host -** parameter index is known, locate the value in p->aVar[]. Then render -** the value as a literal in place of the host parameter name. -*/ -SQLITE_PRIVATE char *sqlite3VdbeExpandSql( - Vdbe *p, /* The prepared statement being evaluated */ - const char *zRawSql /* Raw text of the SQL statement */ -){ - sqlite3 *db; /* The database connection */ - int idx = 0; /* Index of a host parameter */ - int nextIndex = 1; /* Index of next ? host parameter */ - int n; /* Length of a token prefix */ - int nToken; /* Length of the parameter token */ - int i; /* Loop counter */ - Mem *pVar; /* Value of a host parameter */ - StrAccum out; /* Accumulate the output here */ -#ifndef SQLITE_OMIT_UTF16 - Mem utf8; /* Used to convert UTF16 into UTF8 for display */ -#endif - char zBase[100]; /* Initial working space */ - - db = p->db; - sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), - db->aLimit[SQLITE_LIMIT_LENGTH]); - if( db->nVdbeExec>1 ){ - while( *zRawSql ){ - const char *zStart = zRawSql; - while( *(zRawSql++)!='\n' && *zRawSql ); - sqlite3_str_append(&out, "-- ", 3); - assert( (zRawSql - zStart) > 0 ); - sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart)); - } - }else if( p->nVar==0 ){ - sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql)); - }else{ - while( zRawSql[0] ){ - n = findNextHostParameter(zRawSql, &nToken); - assert( n>0 ); - sqlite3_str_append(&out, zRawSql, n); - zRawSql += n; - assert( zRawSql[0] || nToken==0 ); - if( nToken==0 ) break; - if( zRawSql[0]=='?' ){ - if( nToken>1 ){ - assert( sqlite3Isdigit(zRawSql[1]) ); - sqlite3GetInt32(&zRawSql[1], &idx); - }else{ - idx = nextIndex; - } - }else{ - assert( zRawSql[0]==':' || zRawSql[0]=='$' || - zRawSql[0]=='@' || zRawSql[0]=='#' ); - testcase( zRawSql[0]==':' ); - testcase( zRawSql[0]=='$' ); - testcase( zRawSql[0]=='@' ); - testcase( zRawSql[0]=='#' ); - idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken); - assert( idx>0 ); - } - zRawSql += nToken; - nextIndex = idx + 1; - assert( idx>0 && idx<=p->nVar ); - pVar = &p->aVar[idx-1]; - if( pVar->flags & MEM_Null ){ - sqlite3_str_append(&out, "NULL", 4); - }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){ - sqlite3_str_appendf(&out, "%lld", pVar->u.i); - }else if( pVar->flags & MEM_Real ){ - sqlite3_str_appendf(&out, "%!.15g", pVar->u.r); - }else if( pVar->flags & MEM_Str ){ - int nOut; /* Number of bytes of the string text to include in output */ -#ifndef SQLITE_OMIT_UTF16 - u8 enc = ENC(db); - if( enc!=SQLITE_UTF8 ){ - memset(&utf8, 0, sizeof(utf8)); - utf8.db = db; - sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC); - if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){ - out.accError = SQLITE_NOMEM; - out.nAlloc = 0; - } - pVar = &utf8; - } -#endif - nOut = pVar->n; -#ifdef SQLITE_TRACE_SIZE_LIMIT - if( nOut>SQLITE_TRACE_SIZE_LIMIT ){ - nOut = SQLITE_TRACE_SIZE_LIMIT; - while( nOutn && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; } - } -#endif - sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z); -#ifdef SQLITE_TRACE_SIZE_LIMIT - if( nOutn ){ - sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut); - } -#endif -#ifndef SQLITE_OMIT_UTF16 - if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8); -#endif - }else if( pVar->flags & MEM_Zero ){ - sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero); - }else{ - int nOut; /* Number of bytes of the blob to include in output */ - assert( pVar->flags & MEM_Blob ); - sqlite3_str_append(&out, "x'", 2); - nOut = pVar->n; -#ifdef SQLITE_TRACE_SIZE_LIMIT - if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT; -#endif - for(i=0; iz[i]&0xff); - } - sqlite3_str_append(&out, "'", 1); -#ifdef SQLITE_TRACE_SIZE_LIMIT - if( nOutn ){ - sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut); - } -#endif - } - } - } - if( out.accError ) sqlite3_str_reset(&out); - return sqlite3StrAccumFinish(&out); -} - -#endif /* #ifndef SQLITE_OMIT_TRACE */ - -/************** End of vdbetrace.c *******************************************/ -/************** Begin file vdbe.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. -** -************************************************************************* -** The code in this file implements the function that runs the -** bytecode of a prepared statement. -** -** Various scripts scan this source file in order to generate HTML -** documentation, headers files, or other derived files. The formatting -** of the code in this file is, therefore, important. See other comments -** in this file for details. If in doubt, do not deviate from existing -** commenting and indentation practices when changing or adding code. -*/ -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -/* -** Invoke this macro on memory cells just prior to changing the -** value of the cell. This macro verifies that shallow copies are -** not misused. A shallow copy of a string or blob just copies a -** pointer to the string or blob, not the content. If the original -** is changed while the copy is still in use, the string or blob might -** be changed out from under the copy. This macro verifies that nothing -** like that ever happens. -*/ -#ifdef SQLITE_DEBUG -# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M) -#else -# define memAboutToChange(P,M) -#endif - -/* -** The following global variable is incremented every time a cursor -** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test -** procedures use this information to make sure that indices are -** working correctly. This variable has no function other than to -** help verify the correct operation of the library. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_search_count = 0; -#endif - -/* -** When this global variable is positive, it gets decremented once before -** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted -** field of the sqlite3 structure is set in order to simulate an interrupt. -** -** This facility is used for testing purposes only. It does not function -** in an ordinary build. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_interrupt_count = 0; -#endif - -/* -** The next global variable is incremented each type the OP_Sort opcode -** is executed. The test procedures use this information to make sure that -** sorting is occurring or not occurring at appropriate times. This variable -** has no function other than to help verify the correct operation of the -** library. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_sort_count = 0; -#endif - -/* -** The next global variable records the size of the largest MEM_Blob -** or MEM_Str that has been used by a VDBE opcode. The test procedures -** use this information to make sure that the zero-blob functionality -** is working correctly. This variable has no function other than to -** help verify the correct operation of the library. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_max_blobsize = 0; -static void updateMaxBlobsize(Mem *p){ - if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ - sqlite3_max_blobsize = p->n; - } -} -#endif - -/* -** This macro evaluates to true if either the update hook or the preupdate -** hook are enabled for database connect DB. -*/ -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback) -#else -# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback) -#endif - -/* -** The next global variable is incremented each time the OP_Found opcode -** is executed. This is used to test whether or not the foreign key -** operation implemented using OP_FkIsZero is working. This variable -** has no function other than to help verify the correct operation of the -** library. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_found_count = 0; -#endif - -/* -** Test a register to see if it exceeds the current maximum blob size. -** If it does, record the new maximum blob size. -*/ -#if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE) -# define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) -#else -# define UPDATE_MAX_BLOBSIZE(P) -#endif - -#ifdef SQLITE_DEBUG -/* This routine provides a convenient place to set a breakpoint during -** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after -** each opcode is printed. Variables "pc" (program counter) and pOp are -** available to add conditionals to the breakpoint. GDB example: -** -** break test_trace_breakpoint if pc=22 -** -** Other useful labels for breakpoints include: -** test_addop_breakpoint(pc,pOp) -** sqlite3CorruptError(lineno) -** sqlite3MisuseError(lineno) -** sqlite3CantopenError(lineno) -*/ -static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){ - static int n = 0; - n++; -} -#endif - -/* -** Invoke the VDBE coverage callback, if that callback is defined. This -** feature is used for test suite validation only and does not appear an -** production builds. -** -** M is the type of branch. I is the direction taken for this instance of -** the branch. -** -** M: 2 - two-way branch (I=0: fall-thru 1: jump ) -** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL ) -** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3) -** -** In other words, if M is 2, then I is either 0 (for fall-through) or -** 1 (for when the branch is taken). If M is 3, the I is 0 for an -** ordinary fall-through, I is 1 if the branch was taken, and I is 2 -** if the result of comparison is NULL. For M=3, I=2 the jump may or -** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5. -** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2 -** depending on if the operands are less than, equal, or greater than. -** -** iSrcLine is the source code line (from the __LINE__ macro) that -** generated the VDBE instruction combined with flag bits. The source -** code line number is in the lower 24 bits of iSrcLine and the upper -** 8 bytes are flags. The lower three bits of the flags indicate -** values for I that should never occur. For example, if the branch is -** always taken, the flags should be 0x05 since the fall-through and -** alternate branch are never taken. If a branch is never taken then -** flags should be 0x06 since only the fall-through approach is allowed. -** -** Bit 0x08 of the flags indicates an OP_Jump opcode that is only -** interested in equal or not-equal. In other words, I==0 and I==2 -** should be treated as equivalent -** -** Since only a line number is retained, not the filename, this macro -** only works for amalgamation builds. But that is ok, since these macros -** should be no-ops except for special builds used to measure test coverage. -*/ -#if !defined(SQLITE_VDBE_COVERAGE) -# define VdbeBranchTaken(I,M) -#else -# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M) - static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){ - u8 mNever; - assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */ - assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */ - assert( I> 24; - assert( (I & mNever)==0 ); - if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/ - /* Invoke the branch coverage callback with three arguments: - ** iSrcLine - the line number of the VdbeCoverage() macro, with - ** flags removed. - ** I - Mask of bits 0x07 indicating which cases are are - ** fulfilled by this instance of the jump. 0x01 means - ** fall-thru, 0x02 means taken, 0x04 means NULL. Any - ** impossible cases (ex: if the comparison is never NULL) - ** are filled in automatically so that the coverage - ** measurement logic does not flag those impossible cases - ** as missed coverage. - ** M - Type of jump. Same as M argument above - */ - I |= mNever; - if( M==2 ) I |= 0x04; - if( M==4 ){ - I |= 0x08; - if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/ - } - sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg, - iSrcLine&0xffffff, I, M); - } -#endif - -/* -** An ephemeral string value (signified by the MEM_Ephem flag) contains -** a pointer to a dynamically allocated string where some other entity -** is responsible for deallocating that string. Because the register -** does not control the string, it might be deleted without the register -** knowing it. -** -** This routine converts an ephemeral string into a dynamically allocated -** string that the register itself controls. In other words, it -** converts an MEM_Ephem string into a string with P.z==P.zMalloc. -*/ -#define Deephemeralize(P) \ - if( ((P)->flags&MEM_Ephem)!=0 \ - && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} - -/* Return true if the cursor was opened using the OP_OpenSorter opcode. */ -#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER) - -/* -** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL -** if we run out of memory. -*/ -static VdbeCursor *allocateCursor( - Vdbe *p, /* The virtual machine */ - int iCur, /* Index of the new VdbeCursor */ - int nField, /* Number of fields in the table or index */ - int iDb, /* Database the cursor belongs to, or -1 */ - u8 eCurType /* Type of the new cursor */ -){ - /* Find the memory cell that will be used to store the blob of memory - ** required for this VdbeCursor structure. It is convenient to use a - ** vdbe memory cell to manage the memory allocation required for a - ** VdbeCursor structure for the following reasons: - ** - ** * Sometimes cursor numbers are used for a couple of different - ** purposes in a vdbe program. The different uses might require - ** different sized allocations. Memory cells provide growable - ** allocations. - ** - ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can - ** be freed lazily via the sqlite3_release_memory() API. This - ** minimizes the number of malloc calls made by the system. - ** - ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from - ** the top of the register space. Cursor 1 is at Mem[p->nMem-1]. - ** Cursor 2 is at Mem[p->nMem-2]. And so forth. - */ - Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem; - - int nByte; - VdbeCursor *pCx = 0; - nByte = - ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + - (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0); - - assert( iCur>=0 && iCurnCursor ); - if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/ - /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag - ** is clear. Otherwise, if this is an ephemeral cursor created by - ** OP_OpenDup, the cursor will not be closed and will still be part - ** of a BtShared.pCursor list. */ - if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0; - sqlite3VdbeFreeCursor(p, p->apCsr[iCur]); - p->apCsr[iCur] = 0; - } - if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){ - p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z; - memset(pCx, 0, offsetof(VdbeCursor,pAltCursor)); - pCx->eCurType = eCurType; - pCx->iDb = iDb; - pCx->nField = nField; - pCx->aOffset = &pCx->aType[nField]; - if( eCurType==CURTYPE_BTREE ){ - pCx->uc.pCursor = (BtCursor*) - &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField]; - sqlite3BtreeCursorZero(pCx->uc.pCursor); - } - } - return pCx; -} - -/* -** The string in pRec is known to look like an integer and to have a -** floating point value of rValue. Return true and set *piValue to the -** integer value if the string is in range to be an integer. Otherwise, -** return false. -*/ -static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){ - i64 iValue = (double)rValue; - if( sqlite3RealSameAsInt(rValue,iValue) ){ - *piValue = iValue; - return 1; - } - return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc); -} - -/* -** Try to convert a value into a numeric representation if we can -** do so without loss of information. In other words, if the string -** looks like a number, convert it into a number. If it does not -** look like a number, leave it alone. -** -** If the bTryForInt flag is true, then extra effort is made to give -** an integer representation. Strings that look like floating point -** values but which have no fractional component (example: '48.00') -** will have a MEM_Int representation when bTryForInt is true. -** -** If bTryForInt is false, then if the input string contains a decimal -** point or exponential notation, the result is only MEM_Real, even -** if there is an exact integer representation of the quantity. -*/ -static void applyNumericAffinity(Mem *pRec, int bTryForInt){ - double rValue; - u8 enc = pRec->enc; - int rc; - assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str ); - rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc); - if( rc<=0 ) return; - if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){ - pRec->flags |= MEM_Int; - }else{ - pRec->u.r = rValue; - pRec->flags |= MEM_Real; - if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec); - } - /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the - ** string representation after computing a numeric equivalent, because the - ** string representation might not be the canonical representation for the - ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */ - pRec->flags &= ~MEM_Str; -} - -/* -** Processing is determine by the affinity parameter: -** -** SQLITE_AFF_INTEGER: -** SQLITE_AFF_REAL: -** SQLITE_AFF_NUMERIC: -** Try to convert pRec to an integer representation or a -** floating-point representation if an integer representation -** is not possible. Note that the integer representation is -** always preferred, even if the affinity is REAL, because -** an integer representation is more space efficient on disk. -** -** SQLITE_AFF_TEXT: -** Convert pRec to a text representation. -** -** SQLITE_AFF_BLOB: -** SQLITE_AFF_NONE: -** No-op. pRec is unchanged. -*/ -static void applyAffinity( - Mem *pRec, /* The value to apply affinity to */ - char affinity, /* The affinity to be applied */ - u8 enc /* Use this text encoding */ -){ - if( affinity>=SQLITE_AFF_NUMERIC ){ - assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL - || affinity==SQLITE_AFF_NUMERIC ); - if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/ - if( (pRec->flags & MEM_Real)==0 ){ - if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1); - }else{ - sqlite3VdbeIntegerAffinity(pRec); - } - } - }else if( affinity==SQLITE_AFF_TEXT ){ - /* Only attempt the conversion to TEXT if there is an integer or real - ** representation (blob and NULL do not get converted) but no string - ** representation. It would be harmless to repeat the conversion if - ** there is already a string rep, but it is pointless to waste those - ** CPU cycles. */ - if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/ - if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){ - testcase( pRec->flags & MEM_Int ); - testcase( pRec->flags & MEM_Real ); - testcase( pRec->flags & MEM_IntReal ); - sqlite3VdbeMemStringify(pRec, enc, 1); - } - } - pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal); - } -} - -/* -** Try to convert the type of a function argument or a result column -** into a numeric representation. Use either INTEGER or REAL whichever -** is appropriate. But only do the conversion if it is possible without -** loss of information and return the revised type of the argument. -*/ -SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){ - int eType = sqlite3_value_type(pVal); - if( eType==SQLITE_TEXT ){ - Mem *pMem = (Mem*)pVal; - applyNumericAffinity(pMem, 0); - eType = sqlite3_value_type(pVal); - } - return eType; -} - -/* -** Exported version of applyAffinity(). This one works on sqlite3_value*, -** not the internal Mem* type. -*/ -SQLITE_PRIVATE void sqlite3ValueApplyAffinity( - sqlite3_value *pVal, - u8 affinity, - u8 enc -){ - applyAffinity((Mem *)pVal, affinity, enc); -} - -/* -** pMem currently only holds a string type (or maybe a BLOB that we can -** interpret as a string if we want to). Compute its corresponding -** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields -** accordingly. -*/ -static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){ - int rc; - sqlite3_int64 ix; - assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ); - assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ); - ExpandBlob(pMem); - rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); - if( rc<=0 ){ - if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){ - pMem->u.i = ix; - return MEM_Int; - }else{ - return MEM_Real; - } - }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){ - pMem->u.i = ix; - return MEM_Int; - } - return MEM_Real; -} - -/* -** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or -** none. -** -** Unlike applyNumericAffinity(), this routine does not modify pMem->flags. -** But it does set pMem->u.r and pMem->u.i appropriately. -*/ -static u16 numericType(Mem *pMem){ - if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){ - testcase( pMem->flags & MEM_Int ); - testcase( pMem->flags & MEM_Real ); - testcase( pMem->flags & MEM_IntReal ); - return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal); - } - if( pMem->flags & (MEM_Str|MEM_Blob) ){ - testcase( pMem->flags & MEM_Str ); - testcase( pMem->flags & MEM_Blob ); - return computeNumericType(pMem); - } - return 0; -} - -#ifdef SQLITE_DEBUG -/* -** Write a nice string representation of the contents of cell pMem -** into buffer zBuf, length nBuf. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){ - int f = pMem->flags; - static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"}; - if( f&MEM_Blob ){ - int i; - char c; - if( f & MEM_Dyn ){ - c = 'z'; - assert( (f & (MEM_Static|MEM_Ephem))==0 ); - }else if( f & MEM_Static ){ - c = 't'; - assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); - }else if( f & MEM_Ephem ){ - c = 'e'; - assert( (f & (MEM_Static|MEM_Dyn))==0 ); - }else{ - c = 's'; - } - sqlite3_str_appendf(pStr, "%cx[", c); - for(i=0; i<25 && in; i++){ - sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF)); - } - sqlite3_str_appendf(pStr, "|"); - for(i=0; i<25 && in; i++){ - char z = pMem->z[i]; - sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z); - } - sqlite3_str_appendf(pStr,"]"); - if( f & MEM_Zero ){ - sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero); - } - }else if( f & MEM_Str ){ - int j; - u8 c; - if( f & MEM_Dyn ){ - c = 'z'; - assert( (f & (MEM_Static|MEM_Ephem))==0 ); - }else if( f & MEM_Static ){ - c = 't'; - assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); - }else if( f & MEM_Ephem ){ - c = 'e'; - assert( (f & (MEM_Static|MEM_Dyn))==0 ); - }else{ - c = 's'; - } - sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n); - for(j=0; j<25 && jn; j++){ - c = pMem->z[j]; - sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.'); - } - sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]); - } -} -#endif - -#ifdef SQLITE_DEBUG -/* -** Print the value of a register for tracing purposes: -*/ -static void memTracePrint(Mem *p){ - if( p->flags & MEM_Undefined ){ - printf(" undefined"); - }else if( p->flags & MEM_Null ){ - printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL"); - }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ - printf(" si:%lld", p->u.i); - }else if( (p->flags & (MEM_IntReal))!=0 ){ - printf(" ir:%lld", p->u.i); - }else if( p->flags & MEM_Int ){ - printf(" i:%lld", p->u.i); -#ifndef SQLITE_OMIT_FLOATING_POINT - }else if( p->flags & MEM_Real ){ - printf(" r:%.17g", p->u.r); -#endif - }else if( sqlite3VdbeMemIsRowSet(p) ){ - printf(" (rowset)"); - }else{ - StrAccum acc; - char zBuf[1000]; - sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); - sqlite3VdbeMemPrettyPrint(p, &acc); - printf(" %s", sqlite3StrAccumFinish(&acc)); - } - if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype); -} -static void registerTrace(int iReg, Mem *p){ - printf("R[%d] = ", iReg); - memTracePrint(p); - if( p->pScopyFrom ){ - printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg])); - } - printf("\n"); - sqlite3VdbeCheckMemInvariants(p); -} -#endif - -#ifdef SQLITE_DEBUG -/* -** Show the values of all registers in the virtual machine. Used for -** interactive debugging. -*/ -SQLITE_PRIVATE void sqlite3VdbeRegisterDump(Vdbe *v){ - int i; - for(i=1; inMem; i++) registerTrace(i, v->aMem+i); -} -#endif /* SQLITE_DEBUG */ - - -#ifdef SQLITE_DEBUG -# define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M) -#else -# define REGISTER_TRACE(R,M) -#endif - - -#ifdef VDBE_PROFILE - -/* -** hwtime.h contains inline assembler code for implementing -** high-performance timing routines. -*/ -/************** Include hwtime.h in the middle of vdbe.c *********************/ -/************** 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 and x86_64 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(__STRICT_ANSI__) && \ - (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(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif !defined(__STRICT_ANSI__) && (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 - - /* - ** asm() is needed for hardware timing support. Without asm(), - ** disable the sqlite3Hwtime() routine. - ** - ** sqlite3Hwtime() is only used for some obscure debugging - ** and analysis configurations, not in any deliverable, so this - ** should not be a great loss. - */ -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 vdbe.c ***********************/ - -#endif - -#ifndef NDEBUG -/* -** This function is only called from within an assert() expression. It -** checks that the sqlite3.nTransaction variable is correctly set to -** the number of non-transaction savepoints currently in the -** linked list starting at sqlite3.pSavepoint. -** -** Usage: -** -** assert( checkSavepointCount(db) ); -*/ -static int checkSavepointCount(sqlite3 *db){ - int n = 0; - Savepoint *p; - for(p=db->pSavepoint; p; p=p->pNext) n++; - assert( n==(db->nSavepoint + db->isTransactionSavepoint) ); - return 1; -} -#endif - -/* -** Return the register of pOp->p2 after first preparing it to be -** overwritten with an integer value. -*/ -static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){ - sqlite3VdbeMemSetNull(pOut); - pOut->flags = MEM_Int; - return pOut; -} -static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){ - Mem *pOut; - assert( pOp->p2>0 ); - assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); - pOut = &p->aMem[pOp->p2]; - memAboutToChange(p, pOut); - if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/ - return out2PrereleaseWithClear(pOut); - }else{ - pOut->flags = MEM_Int; - return pOut; - } -} - - -/* -** Execute as much of a VDBE program as we can. -** This is the core of sqlite3_step(). -*/ -SQLITE_PRIVATE int sqlite3VdbeExec( - Vdbe *p /* The VDBE */ -){ - Op *aOp = p->aOp; /* Copy of p->aOp */ - Op *pOp = aOp; /* Current operation */ -#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) - Op *pOrigOp; /* Value of pOp at the top of the loop */ -#endif -#ifdef SQLITE_DEBUG - int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */ -#endif - int rc = SQLITE_OK; /* Value to return */ - sqlite3 *db = p->db; /* The database */ - u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */ - u8 encoding = ENC(db); /* The database encoding */ - int iCompare = 0; /* Result of last comparison */ - u64 nVmStep = 0; /* Number of virtual machine steps */ -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - u64 nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */ -#endif - Mem *aMem = p->aMem; /* Copy of p->aMem */ - Mem *pIn1 = 0; /* 1st input operand */ - Mem *pIn2 = 0; /* 2nd input operand */ - Mem *pIn3 = 0; /* 3rd input operand */ - Mem *pOut = 0; /* Output operand */ -#ifdef VDBE_PROFILE - u64 start; /* CPU clock count at start of opcode */ -#endif - /*** INSERT STACK UNION HERE ***/ - - assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ - sqlite3VdbeEnter(p); -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - if( db->xProgress ){ - u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP]; - assert( 0 < db->nProgressOps ); - nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps); - }else{ - nProgressLimit = LARGEST_UINT64; - } -#endif - if( p->rc==SQLITE_NOMEM ){ - /* This happens if a malloc() inside a call to sqlite3_column_text() or - ** sqlite3_column_text16() failed. */ - goto no_mem; - } - assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY ); - testcase( p->rc!=SQLITE_OK ); - p->rc = SQLITE_OK; - assert( p->bIsReader || p->readOnly!=0 ); - p->iCurrentTime = 0; - assert( p->explain==0 ); - p->pResultSet = 0; - db->busyHandler.nBusy = 0; - if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt; - sqlite3VdbeIOTraceSql(p); -#ifdef SQLITE_DEBUG - sqlite3BeginBenignMalloc(); - if( p->pc==0 - && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0 - ){ - int i; - int once = 1; - sqlite3VdbePrintSql(p); - if( p->db->flags & SQLITE_VdbeListing ){ - printf("VDBE Program Listing:\n"); - for(i=0; inOp; i++){ - sqlite3VdbePrintOp(stdout, i, &aOp[i]); - } - } - if( p->db->flags & SQLITE_VdbeEQP ){ - for(i=0; inOp; i++){ - if( aOp[i].opcode==OP_Explain ){ - if( once ) printf("VDBE Query Plan:\n"); - printf("%s\n", aOp[i].p4.z); - once = 0; - } - } - } - if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n"); - } - sqlite3EndBenignMalloc(); -#endif - for(pOp=&aOp[p->pc]; 1; pOp++){ - /* Errors are detected by individual opcodes, with an immediate - ** jumps to abort_due_to_error. */ - assert( rc==SQLITE_OK ); - - assert( pOp>=aOp && pOp<&aOp[p->nOp]); -#ifdef VDBE_PROFILE - start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime(); -#endif - nVmStep++; -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - if( p->anExec ) p->anExec[(int)(pOp-aOp)]++; -#endif - - /* Only allow tracing if SQLITE_DEBUG is defined. - */ -#ifdef SQLITE_DEBUG - if( db->flags & SQLITE_VdbeTrace ){ - sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp); - test_trace_breakpoint((int)(pOp - aOp),pOp,p); - } -#endif - - - /* Check to see if we need to simulate an interrupt. This only happens - ** if we have a special test build. - */ -#ifdef SQLITE_TEST - if( sqlite3_interrupt_count>0 ){ - sqlite3_interrupt_count--; - if( sqlite3_interrupt_count==0 ){ - sqlite3_interrupt(db); - } - } -#endif - - /* Sanity checking on other operands */ -#ifdef SQLITE_DEBUG - { - u8 opProperty = sqlite3OpcodeProperty[pOp->opcode]; - if( (opProperty & OPFLG_IN1)!=0 ){ - assert( pOp->p1>0 ); - assert( pOp->p1<=(p->nMem+1 - p->nCursor) ); - assert( memIsValid(&aMem[pOp->p1]) ); - assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) ); - REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]); - } - if( (opProperty & OPFLG_IN2)!=0 ){ - assert( pOp->p2>0 ); - assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); - assert( memIsValid(&aMem[pOp->p2]) ); - assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) ); - REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]); - } - if( (opProperty & OPFLG_IN3)!=0 ){ - assert( pOp->p3>0 ); - assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); - assert( memIsValid(&aMem[pOp->p3]) ); - assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) ); - REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]); - } - if( (opProperty & OPFLG_OUT2)!=0 ){ - assert( pOp->p2>0 ); - assert( pOp->p2<=(p->nMem+1 - p->nCursor) ); - memAboutToChange(p, &aMem[pOp->p2]); - } - if( (opProperty & OPFLG_OUT3)!=0 ){ - assert( pOp->p3>0 ); - assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); - memAboutToChange(p, &aMem[pOp->p3]); - } - } -#endif -#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) - pOrigOp = pOp; -#endif - - switch( pOp->opcode ){ - -/***************************************************************************** -** What follows is a massive switch statement where each case implements a -** separate instruction in the virtual machine. If we follow the usual -** indentation conventions, each case should be indented by 6 spaces. But -** that is a lot of wasted space on the left margin. So the code within -** the switch statement will break with convention and be flush-left. Another -** big comment (similar to this one) will mark the point in the code where -** we transition back to normal indentation. -** -** The formatting of each case is important. The makefile for SQLite -** generates two C files "opcodes.h" and "opcodes.c" by scanning this -** file looking for lines that begin with "case OP_". The opcodes.h files -** will be filled with #defines that give unique integer values to each -** opcode and the opcodes.c file is filled with an array of strings where -** each string is the symbolic name for the corresponding opcode. If the -** case statement is followed by a comment of the form "/# same as ... #/" -** that comment is used to determine the particular value of the opcode. -** -** Other keywords in the comment that follows each case are used to -** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[]. -** Keywords include: in1, in2, in3, out2, out3. See -** the mkopcodeh.awk script for additional information. -** -** Documentation about VDBE opcodes is generated by scanning this file -** for lines of that contain "Opcode:". That line and all subsequent -** comment lines are used in the generation of the opcode.html documentation -** file. -** -** SUMMARY: -** -** Formatting is important to scripts that scan this file. -** Do not deviate from the formatting style currently in use. -** -*****************************************************************************/ - -/* Opcode: Goto * P2 * * * -** -** An unconditional jump to address P2. -** The next instruction executed will be -** the one at index P2 from the beginning of -** the program. -** -** The P1 parameter is not actually used by this opcode. However, it -** is sometimes set to 1 instead of 0 as a hint to the command-line shell -** that this Goto is the bottom of a loop and that the lines from P2 down -** to the current line should be indented for EXPLAIN output. -*/ -case OP_Goto: { /* jump */ - -#ifdef SQLITE_DEBUG - /* In debuggging mode, when the p5 flags is set on an OP_Goto, that - ** means we should really jump back to the preceeding OP_ReleaseReg - ** instruction. */ - if( pOp->p5 ){ - assert( pOp->p2 < (int)(pOp - aOp) ); - assert( pOp->p2 > 1 ); - pOp = &aOp[pOp->p2 - 2]; - assert( pOp[1].opcode==OP_ReleaseReg ); - goto check_for_interrupt; - } -#endif - -jump_to_p2_and_check_for_interrupt: - pOp = &aOp[pOp->p2 - 1]; - - /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev, - ** OP_VNext, or OP_SorterNext) all jump here upon - ** completion. Check to see if sqlite3_interrupt() has been called - ** or if the progress callback needs to be invoked. - ** - ** This code uses unstructured "goto" statements and does not look clean. - ** But that is not due to sloppy coding habits. The code is written this - ** way for performance, to avoid having to run the interrupt and progress - ** checks on every opcode. This helps sqlite3_step() to run about 1.5% - ** faster according to "valgrind --tool=cachegrind" */ -check_for_interrupt: - if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt; -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - /* Call the progress callback if it is configured and the required number - ** of VDBE ops have been executed (either since this invocation of - ** sqlite3VdbeExec() or since last time the progress callback was called). - ** If the progress callback returns non-zero, exit the virtual machine with - ** a return code SQLITE_ABORT. - */ - while( nVmStep>=nProgressLimit && db->xProgress!=0 ){ - assert( db->nProgressOps!=0 ); - nProgressLimit += db->nProgressOps; - if( db->xProgress(db->pProgressArg) ){ - nProgressLimit = LARGEST_UINT64; - rc = SQLITE_INTERRUPT; - goto abort_due_to_error; - } - } -#endif - - break; -} - -/* Opcode: Gosub P1 P2 * * * -** -** Write the current address onto register P1 -** and then jump to address P2. -*/ -case OP_Gosub: { /* jump */ - assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); - pIn1 = &aMem[pOp->p1]; - assert( VdbeMemDynamic(pIn1)==0 ); - memAboutToChange(p, pIn1); - pIn1->flags = MEM_Int; - pIn1->u.i = (int)(pOp-aOp); - REGISTER_TRACE(pOp->p1, pIn1); - - /* Most jump operations do a goto to this spot in order to update - ** the pOp pointer. */ -jump_to_p2: - pOp = &aOp[pOp->p2 - 1]; - break; -} - -/* Opcode: Return P1 * * * * -** -** Jump to the next instruction after the address in register P1. After -** the jump, register P1 becomes undefined. -*/ -case OP_Return: { /* in1 */ - pIn1 = &aMem[pOp->p1]; - assert( pIn1->flags==MEM_Int ); - pOp = &aOp[pIn1->u.i]; - pIn1->flags = MEM_Undefined; - break; -} - -/* Opcode: InitCoroutine P1 P2 P3 * * -** -** Set up register P1 so that it will Yield to the coroutine -** located at address P3. -** -** If P2!=0 then the coroutine implementation immediately follows -** this opcode. So jump over the coroutine implementation to -** address P2. -** -** See also: EndCoroutine -*/ -case OP_InitCoroutine: { /* jump */ - assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); - assert( pOp->p2>=0 && pOp->p2nOp ); - assert( pOp->p3>=0 && pOp->p3nOp ); - pOut = &aMem[pOp->p1]; - assert( !VdbeMemDynamic(pOut) ); - pOut->u.i = pOp->p3 - 1; - pOut->flags = MEM_Int; - if( pOp->p2 ) goto jump_to_p2; - break; -} - -/* Opcode: EndCoroutine P1 * * * * -** -** The instruction at the address in register P1 is a Yield. -** Jump to the P2 parameter of that Yield. -** After the jump, register P1 becomes undefined. -** -** See also: InitCoroutine -*/ -case OP_EndCoroutine: { /* in1 */ - VdbeOp *pCaller; - pIn1 = &aMem[pOp->p1]; - assert( pIn1->flags==MEM_Int ); - assert( pIn1->u.i>=0 && pIn1->u.inOp ); - pCaller = &aOp[pIn1->u.i]; - assert( pCaller->opcode==OP_Yield ); - assert( pCaller->p2>=0 && pCaller->p2nOp ); - pOp = &aOp[pCaller->p2 - 1]; - pIn1->flags = MEM_Undefined; - break; -} - -/* Opcode: Yield P1 P2 * * * -** -** Swap the program counter with the value in register P1. This -** has the effect of yielding to a coroutine. -** -** If the coroutine that is launched by this instruction ends with -** Yield or Return then continue to the next instruction. But if -** the coroutine launched by this instruction ends with -** EndCoroutine, then jump to P2 rather than continuing with the -** next instruction. -** -** See also: InitCoroutine -*/ -case OP_Yield: { /* in1, jump */ - int pcDest; - pIn1 = &aMem[pOp->p1]; - assert( VdbeMemDynamic(pIn1)==0 ); - pIn1->flags = MEM_Int; - pcDest = (int)pIn1->u.i; - pIn1->u.i = (int)(pOp - aOp); - REGISTER_TRACE(pOp->p1, pIn1); - pOp = &aOp[pcDest]; - break; -} - -/* Opcode: HaltIfNull P1 P2 P3 P4 P5 -** Synopsis: if r[P3]=null halt -** -** Check the value in register P3. If it is NULL then Halt using -** parameter P1, P2, and P4 as if this were a Halt instruction. If the -** value in register P3 is not NULL, then this routine is a no-op. -** The P5 parameter should be 1. -*/ -case OP_HaltIfNull: { /* in3 */ - pIn3 = &aMem[pOp->p3]; -#ifdef SQLITE_DEBUG - if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); } -#endif - if( (pIn3->flags & MEM_Null)==0 ) break; - /* Fall through into OP_Halt */ - /* no break */ deliberate_fall_through -} - -/* Opcode: Halt P1 P2 * P4 P5 -** -** Exit immediately. All open cursors, etc are closed -** automatically. -** -** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), -** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0). -** For errors, it can be some other value. If P1!=0 then P2 will determine -** whether or not to rollback the current transaction. Do not rollback -** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, -** then back out all changes that have occurred during this execution of the -** VDBE, but do not rollback the transaction. -** -** If P4 is not null then it is an error message string. -** -** P5 is a value between 0 and 4, inclusive, that modifies the P4 string. -** -** 0: (no change) -** 1: NOT NULL contraint failed: P4 -** 2: UNIQUE constraint failed: P4 -** 3: CHECK constraint failed: P4 -** 4: FOREIGN KEY constraint failed: P4 -** -** If P5 is not zero and P4 is NULL, then everything after the ":" is -** omitted. -** -** There is an implied "Halt 0 0 0" instruction inserted at the very end of -** every program. So a jump past the last instruction of the program -** is the same as executing Halt. -*/ -case OP_Halt: { - VdbeFrame *pFrame; - int pcx; - - pcx = (int)(pOp - aOp); -#ifdef SQLITE_DEBUG - if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); } -#endif - if( pOp->p1==SQLITE_OK && p->pFrame ){ - /* Halt the sub-program. Return control to the parent frame. */ - pFrame = p->pFrame; - p->pFrame = pFrame->pParent; - p->nFrame--; - sqlite3VdbeSetChanges(db, p->nChange); - pcx = sqlite3VdbeFrameRestore(pFrame); - if( pOp->p2==OE_Ignore ){ - /* Instruction pcx is the OP_Program that invoked the sub-program - ** currently being halted. If the p2 instruction of this OP_Halt - ** instruction is set to OE_Ignore, then the sub-program is throwing - ** an IGNORE exception. In this case jump to the address specified - ** as the p2 of the calling OP_Program. */ - pcx = p->aOp[pcx].p2-1; - } - aOp = p->aOp; - aMem = p->aMem; - pOp = &aOp[pcx]; - break; - } - p->rc = pOp->p1; - p->errorAction = (u8)pOp->p2; - p->pc = pcx; - assert( pOp->p5<=4 ); - if( p->rc ){ - if( pOp->p5 ){ - static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK", - "FOREIGN KEY" }; - testcase( pOp->p5==1 ); - testcase( pOp->p5==2 ); - testcase( pOp->p5==3 ); - testcase( pOp->p5==4 ); - sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]); - if( pOp->p4.z ){ - p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z); - } - }else{ - sqlite3VdbeError(p, "%s", pOp->p4.z); - } - sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg); - } - rc = sqlite3VdbeHalt(p); - assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); - if( rc==SQLITE_BUSY ){ - p->rc = SQLITE_BUSY; - }else{ - assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ); - assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 ); - rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; - } - goto vdbe_return; -} - -/* Opcode: Integer P1 P2 * * * -** Synopsis: r[P2]=P1 -** -** The 32-bit integer value P1 is written into register P2. -*/ -case OP_Integer: { /* out2 */ - pOut = out2Prerelease(p, pOp); - pOut->u.i = pOp->p1; - break; -} - -/* Opcode: Int64 * P2 * P4 * -** Synopsis: r[P2]=P4 -** -** P4 is a pointer to a 64-bit integer value. -** Write that value into register P2. -*/ -case OP_Int64: { /* out2 */ - pOut = out2Prerelease(p, pOp); - assert( pOp->p4.pI64!=0 ); - pOut->u.i = *pOp->p4.pI64; - break; -} - -#ifndef SQLITE_OMIT_FLOATING_POINT -/* Opcode: Real * P2 * P4 * -** Synopsis: r[P2]=P4 -** -** P4 is a pointer to a 64-bit floating point value. -** Write that value into register P2. -*/ -case OP_Real: { /* same as TK_FLOAT, out2 */ - pOut = out2Prerelease(p, pOp); - pOut->flags = MEM_Real; - assert( !sqlite3IsNaN(*pOp->p4.pReal) ); - pOut->u.r = *pOp->p4.pReal; - break; -} -#endif - -/* Opcode: String8 * P2 * P4 * -** Synopsis: r[P2]='P4' -** -** P4 points to a nul terminated UTF-8 string. This opcode is transformed -** into a String opcode before it is executed for the first time. During -** this transformation, the length of string P4 is computed and stored -** as the P1 parameter. -*/ -case OP_String8: { /* same as TK_STRING, out2 */ - assert( pOp->p4.z!=0 ); - pOut = out2Prerelease(p, pOp); - pOp->p1 = sqlite3Strlen30(pOp->p4.z); - -#ifndef SQLITE_OMIT_UTF16 - if( encoding!=SQLITE_UTF8 ){ - rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); - assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG ); - if( rc ) goto too_big; - if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; - assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z ); - assert( VdbeMemDynamic(pOut)==0 ); - pOut->szMalloc = 0; - pOut->flags |= MEM_Static; - if( pOp->p4type==P4_DYNAMIC ){ - sqlite3DbFree(db, pOp->p4.z); - } - pOp->p4type = P4_DYNAMIC; - pOp->p4.z = pOut->z; - pOp->p1 = pOut->n; - } -#endif - if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - pOp->opcode = OP_String; - assert( rc==SQLITE_OK ); - /* Fall through to the next case, OP_String */ - /* no break */ deliberate_fall_through -} - -/* Opcode: String P1 P2 P3 P4 P5 -** Synopsis: r[P2]='P4' (len=P1) -** -** The string value P4 of length P1 (bytes) is stored in register P2. -** -** If P3 is not zero and the content of register P3 is equal to P5, then -** the datatype of the register P2 is converted to BLOB. The content is -** the same sequence of bytes, it is merely interpreted as a BLOB instead -** of a string, as if it had been CAST. In other words: -** -** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB) -*/ -case OP_String: { /* out2 */ - assert( pOp->p4.z!=0 ); - pOut = out2Prerelease(p, pOp); - pOut->flags = MEM_Str|MEM_Static|MEM_Term; - pOut->z = pOp->p4.z; - pOut->n = pOp->p1; - pOut->enc = encoding; - UPDATE_MAX_BLOBSIZE(pOut); -#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS - if( pOp->p3>0 ){ - assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); - pIn3 = &aMem[pOp->p3]; - assert( pIn3->flags & MEM_Int ); - if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term; - } -#endif - break; -} - -/* Opcode: Null P1 P2 P3 * * -** Synopsis: r[P2..P3]=NULL -** -** Write a NULL into registers P2. If P3 greater than P2, then also write -** NULL into register P3 and every register in between P2 and P3. If P3 -** is less than P2 (typically P3 is zero) then only register P2 is -** set to NULL. -** -** If the P1 value is non-zero, then also set the MEM_Cleared flag so that -** NULL values will not compare equal even if SQLITE_NULLEQ is set on -** OP_Ne or OP_Eq. -*/ -case OP_Null: { /* out2 */ - int cnt; - u16 nullFlag; - pOut = out2Prerelease(p, pOp); - cnt = pOp->p3-pOp->p2; - assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); - pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null; - pOut->n = 0; -#ifdef SQLITE_DEBUG - pOut->uTemp = 0; -#endif - while( cnt>0 ){ - pOut++; - memAboutToChange(p, pOut); - sqlite3VdbeMemSetNull(pOut); - pOut->flags = nullFlag; - pOut->n = 0; - cnt--; - } - break; -} - -/* Opcode: SoftNull P1 * * * * -** Synopsis: r[P1]=NULL -** -** Set register P1 to have the value NULL as seen by the OP_MakeRecord -** instruction, but do not free any string or blob memory associated with -** the register, so that if the value was a string or blob that was -** previously copied using OP_SCopy, the copies will continue to be valid. -*/ -case OP_SoftNull: { - assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); - pOut = &aMem[pOp->p1]; - pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null; - break; -} - -/* Opcode: Blob P1 P2 * P4 * -** Synopsis: r[P2]=P4 (len=P1) -** -** P4 points to a blob of data P1 bytes long. Store this -** blob in register P2. -*/ -case OP_Blob: { /* out2 */ - assert( pOp->p1 <= SQLITE_MAX_LENGTH ); - pOut = out2Prerelease(p, pOp); - sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); - pOut->enc = encoding; - UPDATE_MAX_BLOBSIZE(pOut); - break; -} - -/* Opcode: Variable P1 P2 * P4 * -** Synopsis: r[P2]=parameter(P1,P4) -** -** Transfer the values of bound parameter P1 into register P2 -** -** If the parameter is named, then its name appears in P4. -** The P4 value is used by sqlite3_bind_parameter_name(). -*/ -case OP_Variable: { /* out2 */ - Mem *pVar; /* Value being transferred */ - - assert( pOp->p1>0 && pOp->p1<=p->nVar ); - assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) ); - pVar = &p->aVar[pOp->p1 - 1]; - if( sqlite3VdbeMemTooBig(pVar) ){ - goto too_big; - } - pOut = &aMem[pOp->p2]; - if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut); - memcpy(pOut, pVar, MEMCELLSIZE); - pOut->flags &= ~(MEM_Dyn|MEM_Ephem); - pOut->flags |= MEM_Static|MEM_FromBind; - UPDATE_MAX_BLOBSIZE(pOut); - break; -} - -/* Opcode: Move P1 P2 P3 * * -** Synopsis: r[P2@P3]=r[P1@P3] -** -** Move the P3 values in register P1..P1+P3-1 over into -** registers P2..P2+P3-1. Registers P1..P1+P3-1 are -** left holding a NULL. It is an error for register ranges -** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error -** for P3 to be less than 1. -*/ -case OP_Move: { - int n; /* Number of registers left to copy */ - int p1; /* Register to copy from */ - int p2; /* Register to copy to */ - - n = pOp->p3; - p1 = pOp->p1; - p2 = pOp->p2; - assert( n>0 && p1>0 && p2>0 ); - assert( p1+n<=p2 || p2+n<=p1 ); - - pIn1 = &aMem[p1]; - pOut = &aMem[p2]; - do{ - assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] ); - assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] ); - assert( memIsValid(pIn1) ); - memAboutToChange(p, pOut); - sqlite3VdbeMemMove(pOut, pIn1); -#ifdef SQLITE_DEBUG - pIn1->pScopyFrom = 0; - { int i; - for(i=1; inMem; i++){ - if( aMem[i].pScopyFrom==pIn1 ){ - aMem[i].pScopyFrom = pOut; - } - } - } -#endif - Deephemeralize(pOut); - REGISTER_TRACE(p2++, pOut); - pIn1++; - pOut++; - }while( --n ); - break; -} - -/* Opcode: Copy P1 P2 P3 * * -** Synopsis: r[P2@P3+1]=r[P1@P3+1] -** -** Make a copy of registers P1..P1+P3 into registers P2..P2+P3. -** -** This instruction makes a deep copy of the value. A duplicate -** is made of any string or blob constant. See also OP_SCopy. -*/ -case OP_Copy: { - int n; - - n = pOp->p3; - pIn1 = &aMem[pOp->p1]; - pOut = &aMem[pOp->p2]; - assert( pOut!=pIn1 ); - while( 1 ){ - memAboutToChange(p, pOut); - sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); - Deephemeralize(pOut); -#ifdef SQLITE_DEBUG - pOut->pScopyFrom = 0; -#endif - REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut); - if( (n--)==0 ) break; - pOut++; - pIn1++; - } - break; -} - -/* Opcode: SCopy P1 P2 * * * -** Synopsis: r[P2]=r[P1] -** -** Make a shallow copy of register P1 into register P2. -** -** This instruction makes a shallow copy of the value. If the value -** is a string or blob, then the copy is only a pointer to the -** original and hence if the original changes so will the copy. -** Worse, if the original is deallocated, the copy becomes invalid. -** Thus the program must guarantee that the original will not change -** during the lifetime of the copy. Use OP_Copy to make a complete -** copy. -*/ -case OP_SCopy: { /* out2 */ - pIn1 = &aMem[pOp->p1]; - pOut = &aMem[pOp->p2]; - assert( pOut!=pIn1 ); - sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); -#ifdef SQLITE_DEBUG - pOut->pScopyFrom = pIn1; - pOut->mScopyFlags = pIn1->flags; -#endif - break; -} - -/* Opcode: IntCopy P1 P2 * * * -** Synopsis: r[P2]=r[P1] -** -** Transfer the integer value held in register P1 into register P2. -** -** This is an optimized version of SCopy that works only for integer -** values. -*/ -case OP_IntCopy: { /* out2 */ - pIn1 = &aMem[pOp->p1]; - assert( (pIn1->flags & MEM_Int)!=0 ); - pOut = &aMem[pOp->p2]; - sqlite3VdbeMemSetInt64(pOut, pIn1->u.i); - break; -} - -/* Opcode: ResultRow P1 P2 * * * -** Synopsis: output=r[P1@P2] -** -** The registers P1 through P1+P2-1 contain a single row of -** results. This opcode causes the sqlite3_step() call to terminate -** with an SQLITE_ROW return code and it sets up the sqlite3_stmt -** structure to provide access to the r(P1)..r(P1+P2-1) values as -** the result row. -*/ -case OP_ResultRow: { - Mem *pMem; - int i; - assert( p->nResColumn==pOp->p2 ); - assert( pOp->p1>0 ); - assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); - - /* If this statement has violated immediate foreign key constraints, do - ** not return the number of rows modified. And do not RELEASE the statement - ** transaction. It needs to be rolled back. */ - if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){ - assert( db->flags&SQLITE_CountRows ); - assert( p->usesStmtJournal ); - goto abort_due_to_error; - } - - /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then - ** DML statements invoke this opcode to return the number of rows - ** modified to the user. This is the only way that a VM that - ** opens a statement transaction may invoke this opcode. - ** - ** In case this is such a statement, close any statement transaction - ** opened by this VM before returning control to the user. This is to - ** ensure that statement-transactions are always nested, not overlapping. - ** If the open statement-transaction is not closed here, then the user - ** may step another VM that opens its own statement transaction. This - ** may lead to overlapping statement transactions. - ** - ** The statement transaction is never a top-level transaction. Hence - ** the RELEASE call below can never fail. - */ - assert( p->iStatement==0 || db->flags&SQLITE_CountRows ); - rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE); - assert( rc==SQLITE_OK ); - - /* Invalidate all ephemeral cursor row caches */ - p->cacheCtr = (p->cacheCtr + 2)|1; - - /* Make sure the results of the current row are \000 terminated - ** and have an assigned type. The results are de-ephemeralized as - ** a side effect. - */ - pMem = p->pResultSet = &aMem[pOp->p1]; - for(i=0; ip2; i++){ - assert( memIsValid(&pMem[i]) ); - Deephemeralize(&pMem[i]); - assert( (pMem[i].flags & MEM_Ephem)==0 - || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 ); - sqlite3VdbeMemNulTerminate(&pMem[i]); - REGISTER_TRACE(pOp->p1+i, &pMem[i]); -#ifdef SQLITE_DEBUG - /* The registers in the result will not be used again when the - ** prepared statement restarts. This is because sqlite3_column() - ** APIs might have caused type conversions of made other changes to - ** the register values. Therefore, we can go ahead and break any - ** OP_SCopy dependencies. */ - pMem[i].pScopyFrom = 0; -#endif - } - if( db->mallocFailed ) goto no_mem; - - if( db->mTrace & SQLITE_TRACE_ROW ){ - db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0); - } - - - /* Return SQLITE_ROW - */ - p->pc = (int)(pOp - aOp) + 1; - rc = SQLITE_ROW; - goto vdbe_return; -} - -/* Opcode: Concat P1 P2 P3 * * -** Synopsis: r[P3]=r[P2]+r[P1] -** -** Add the text in register P1 onto the end of the text in -** register P2 and store the result in register P3. -** If either the P1 or P2 text are NULL then store NULL in P3. -** -** P3 = P2 || P1 -** -** It is illegal for P1 and P3 to be the same register. Sometimes, -** if P3 is the same register as P2, the implementation is able -** to avoid a memcpy(). -*/ -case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ - i64 nByte; /* Total size of the output string or blob */ - u16 flags1; /* Initial flags for P1 */ - u16 flags2; /* Initial flags for P2 */ - - pIn1 = &aMem[pOp->p1]; - pIn2 = &aMem[pOp->p2]; - pOut = &aMem[pOp->p3]; - testcase( pOut==pIn2 ); - assert( pIn1!=pOut ); - flags1 = pIn1->flags; - testcase( flags1 & MEM_Null ); - testcase( pIn2->flags & MEM_Null ); - if( (flags1 | pIn2->flags) & MEM_Null ){ - sqlite3VdbeMemSetNull(pOut); - break; - } - if( (flags1 & (MEM_Str|MEM_Blob))==0 ){ - if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem; - flags1 = pIn1->flags & ~MEM_Str; - }else if( (flags1 & MEM_Zero)!=0 ){ - if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem; - flags1 = pIn1->flags & ~MEM_Str; - } - flags2 = pIn2->flags; - if( (flags2 & (MEM_Str|MEM_Blob))==0 ){ - if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem; - flags2 = pIn2->flags & ~MEM_Str; - }else if( (flags2 & MEM_Zero)!=0 ){ - if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem; - flags2 = pIn2->flags & ~MEM_Str; - } - nByte = pIn1->n + pIn2->n; - if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - if( sqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){ - goto no_mem; - } - MemSetTypeFlag(pOut, MEM_Str); - if( pOut!=pIn2 ){ - memcpy(pOut->z, pIn2->z, pIn2->n); - assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) ); - pIn2->flags = flags2; - } - memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); - assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); - pIn1->flags = flags1; - pOut->z[nByte]=0; - pOut->z[nByte+1] = 0; - pOut->z[nByte+2] = 0; - pOut->flags |= MEM_Term; - pOut->n = (int)nByte; - pOut->enc = encoding; - UPDATE_MAX_BLOBSIZE(pOut); - break; -} - -/* Opcode: Add P1 P2 P3 * * -** Synopsis: r[P3]=r[P1]+r[P2] -** -** Add the value in register P1 to the value in register P2 -** and store the result in register P3. -** If either input is NULL, the result is NULL. -*/ -/* Opcode: Multiply P1 P2 P3 * * -** Synopsis: r[P3]=r[P1]*r[P2] -** -** -** Multiply the value in register P1 by the value in register P2 -** and store the result in register P3. -** If either input is NULL, the result is NULL. -*/ -/* Opcode: Subtract P1 P2 P3 * * -** Synopsis: r[P3]=r[P2]-r[P1] -** -** Subtract the value in register P1 from the value in register P2 -** and store the result in register P3. -** If either input is NULL, the result is NULL. -*/ -/* Opcode: Divide P1 P2 P3 * * -** Synopsis: r[P3]=r[P2]/r[P1] -** -** Divide the value in register P1 by the value in register P2 -** and store the result in register P3 (P3=P2/P1). If the value in -** register P1 is zero, then the result is NULL. If either input is -** NULL, the result is NULL. -*/ -/* Opcode: Remainder P1 P2 P3 * * -** Synopsis: r[P3]=r[P2]%r[P1] -** -** Compute the remainder after integer register P2 is divided by -** register P1 and store the result in register P3. -** If the value in register P1 is zero the result is NULL. -** If either operand is NULL, the result is NULL. -*/ -case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ -case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ -case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ -case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ -case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ - u16 flags; /* Combined MEM_* flags from both inputs */ - u16 type1; /* Numeric type of left operand */ - u16 type2; /* Numeric type of right operand */ - i64 iA; /* Integer value of left operand */ - i64 iB; /* Integer value of right operand */ - double rA; /* Real value of left operand */ - double rB; /* Real value of right operand */ - - pIn1 = &aMem[pOp->p1]; - type1 = numericType(pIn1); - pIn2 = &aMem[pOp->p2]; - type2 = numericType(pIn2); - pOut = &aMem[pOp->p3]; - flags = pIn1->flags | pIn2->flags; - if( (type1 & type2 & MEM_Int)!=0 ){ - iA = pIn1->u.i; - iB = pIn2->u.i; - switch( pOp->opcode ){ - case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break; - case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break; - case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break; - case OP_Divide: { - if( iA==0 ) goto arithmetic_result_is_null; - if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math; - iB /= iA; - break; - } - default: { - if( iA==0 ) goto arithmetic_result_is_null; - if( iA==-1 ) iA = 1; - iB %= iA; - break; - } - } - pOut->u.i = iB; - MemSetTypeFlag(pOut, MEM_Int); - }else if( (flags & MEM_Null)!=0 ){ - goto arithmetic_result_is_null; - }else{ -fp_math: - rA = sqlite3VdbeRealValue(pIn1); - rB = sqlite3VdbeRealValue(pIn2); - switch( pOp->opcode ){ - case OP_Add: rB += rA; break; - case OP_Subtract: rB -= rA; break; - case OP_Multiply: rB *= rA; break; - case OP_Divide: { - /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ - if( rA==(double)0 ) goto arithmetic_result_is_null; - rB /= rA; - break; - } - default: { - iA = sqlite3VdbeIntValue(pIn1); - iB = sqlite3VdbeIntValue(pIn2); - if( iA==0 ) goto arithmetic_result_is_null; - if( iA==-1 ) iA = 1; - rB = (double)(iB % iA); - break; - } - } -#ifdef SQLITE_OMIT_FLOATING_POINT - pOut->u.i = rB; - MemSetTypeFlag(pOut, MEM_Int); -#else - if( sqlite3IsNaN(rB) ){ - goto arithmetic_result_is_null; - } - pOut->u.r = rB; - MemSetTypeFlag(pOut, MEM_Real); -#endif - } - break; - -arithmetic_result_is_null: - sqlite3VdbeMemSetNull(pOut); - break; -} - -/* Opcode: CollSeq P1 * * P4 -** -** P4 is a pointer to a CollSeq object. If the next call to a user function -** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will -** be returned. This is used by the built-in min(), max() and nullif() -** functions. -** -** If P1 is not zero, then it is a register that a subsequent min() or -** max() aggregate will set to 1 if the current row is not the minimum or -** maximum. The P1 register is initialized to 0 by this instruction. -** -** The interface used by the implementation of the aforementioned functions -** to retrieve the collation sequence set by this opcode is not available -** publicly. Only built-in functions have access to this feature. -*/ -case OP_CollSeq: { - assert( pOp->p4type==P4_COLLSEQ ); - if( pOp->p1 ){ - sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0); - } - break; -} - -/* Opcode: BitAnd P1 P2 P3 * * -** Synopsis: r[P3]=r[P1]&r[P2] -** -** Take the bit-wise AND of the values in register P1 and P2 and -** store the result in register P3. -** If either input is NULL, the result is NULL. -*/ -/* Opcode: BitOr P1 P2 P3 * * -** Synopsis: r[P3]=r[P1]|r[P2] -** -** Take the bit-wise OR of the values in register P1 and P2 and -** store the result in register P3. -** If either input is NULL, the result is NULL. -*/ -/* Opcode: ShiftLeft P1 P2 P3 * * -** Synopsis: r[P3]=r[P2]<>r[P1] -** -** Shift the integer value in register P2 to the right by the -** number of bits specified by the integer in register P1. -** Store the result in register P3. -** If either input is NULL, the result is NULL. -*/ -case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ -case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ -case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ -case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ - i64 iA; - u64 uA; - i64 iB; - u8 op; - - pIn1 = &aMem[pOp->p1]; - pIn2 = &aMem[pOp->p2]; - pOut = &aMem[pOp->p3]; - if( (pIn1->flags | pIn2->flags) & MEM_Null ){ - sqlite3VdbeMemSetNull(pOut); - break; - } - iA = sqlite3VdbeIntValue(pIn2); - iB = sqlite3VdbeIntValue(pIn1); - op = pOp->opcode; - if( op==OP_BitAnd ){ - iA &= iB; - }else if( op==OP_BitOr ){ - iA |= iB; - }else if( iB!=0 ){ - assert( op==OP_ShiftRight || op==OP_ShiftLeft ); - - /* If shifting by a negative amount, shift in the other direction */ - if( iB<0 ){ - assert( OP_ShiftRight==OP_ShiftLeft+1 ); - op = 2*OP_ShiftLeft + 1 - op; - iB = iB>(-64) ? -iB : 64; - } - - if( iB>=64 ){ - iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1; - }else{ - memcpy(&uA, &iA, sizeof(uA)); - if( op==OP_ShiftLeft ){ - uA <<= iB; - }else{ - uA >>= iB; - /* Sign-extend on a right shift of a negative number */ - if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB); - } - memcpy(&iA, &uA, sizeof(iA)); - } - } - pOut->u.i = iA; - MemSetTypeFlag(pOut, MEM_Int); - break; -} - -/* Opcode: AddImm P1 P2 * * * -** Synopsis: r[P1]=r[P1]+P2 -** -** Add the constant P2 to the value in register P1. -** The result is always an integer. -** -** To force any register to be an integer, just add 0. -*/ -case OP_AddImm: { /* in1 */ - pIn1 = &aMem[pOp->p1]; - memAboutToChange(p, pIn1); - sqlite3VdbeMemIntegerify(pIn1); - pIn1->u.i += pOp->p2; - break; -} - -/* Opcode: MustBeInt P1 P2 * * * -** -** Force the value in register P1 to be an integer. If the value -** in P1 is not an integer and cannot be converted into an integer -** without data loss, then jump immediately to P2, or if P2==0 -** raise an SQLITE_MISMATCH exception. -*/ -case OP_MustBeInt: { /* jump, in1 */ - pIn1 = &aMem[pOp->p1]; - if( (pIn1->flags & MEM_Int)==0 ){ - applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); - if( (pIn1->flags & MEM_Int)==0 ){ - VdbeBranchTaken(1, 2); - if( pOp->p2==0 ){ - rc = SQLITE_MISMATCH; - goto abort_due_to_error; - }else{ - goto jump_to_p2; - } - } - } - VdbeBranchTaken(0, 2); - MemSetTypeFlag(pIn1, MEM_Int); - break; -} - -#ifndef SQLITE_OMIT_FLOATING_POINT -/* Opcode: RealAffinity P1 * * * * -** -** If register P1 holds an integer convert it to a real value. -** -** This opcode is used when extracting information from a column that -** has REAL affinity. Such column values may still be stored as -** integers, for space efficiency, but after extraction we want them -** to have only a real value. -*/ -case OP_RealAffinity: { /* in1 */ - pIn1 = &aMem[pOp->p1]; - if( pIn1->flags & (MEM_Int|MEM_IntReal) ){ - testcase( pIn1->flags & MEM_Int ); - testcase( pIn1->flags & MEM_IntReal ); - sqlite3VdbeMemRealify(pIn1); - REGISTER_TRACE(pOp->p1, pIn1); - } - break; -} -#endif - -#ifndef SQLITE_OMIT_CAST -/* Opcode: Cast P1 P2 * * * -** Synopsis: affinity(r[P1]) -** -** Force the value in register P1 to be the type defined by P2. -** -**
      -**
    • P2=='A' → BLOB -**
    • P2=='B' → TEXT -**
    • P2=='C' → NUMERIC -**
    • P2=='D' → INTEGER -**
    • P2=='E' → REAL -**
    -** -** A NULL value is not changed by this routine. It remains NULL. -*/ -case OP_Cast: { /* in1 */ - assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL ); - testcase( pOp->p2==SQLITE_AFF_TEXT ); - testcase( pOp->p2==SQLITE_AFF_BLOB ); - testcase( pOp->p2==SQLITE_AFF_NUMERIC ); - testcase( pOp->p2==SQLITE_AFF_INTEGER ); - testcase( pOp->p2==SQLITE_AFF_REAL ); - pIn1 = &aMem[pOp->p1]; - memAboutToChange(p, pIn1); - rc = ExpandBlob(pIn1); - if( rc ) goto abort_due_to_error; - rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding); - if( rc ) goto abort_due_to_error; - UPDATE_MAX_BLOBSIZE(pIn1); - REGISTER_TRACE(pOp->p1, pIn1); - break; -} -#endif /* SQLITE_OMIT_CAST */ - -/* Opcode: Eq P1 P2 P3 P4 P5 -** Synopsis: IF r[P3]==r[P1] -** -** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then -** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then -** store the result of comparison in register P2. -** -** The SQLITE_AFF_MASK portion of P5 must be an affinity character - -** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made -** to coerce both inputs according to this affinity before the -** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric -** affinity is used. Note that the affinity conversions are stored -** back into the input registers P1 and P3. So this opcode can cause -** persistent changes to registers P1 and P3. -** -** Once any conversions have taken place, and neither value is NULL, -** the values are compared. If both values are blobs then memcmp() is -** used to determine the results of the comparison. If both values -** are text, then the appropriate collating function specified in -** P4 is used to do the comparison. If P4 is not specified then -** memcmp() is used to compare text string. If both values are -** numeric, then a numeric comparison is used. If the two values -** are of different types, then numbers are considered less than -** strings and strings are considered less than blobs. -** -** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either -** true or false and is never NULL. If both operands are NULL then the result -** of comparison is true. If either operand is NULL then the result is false. -** If neither operand is NULL the result is the same as it would be if -** the SQLITE_NULLEQ flag were omitted from P5. -** -** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the -** content of r[P2] is only changed if the new value is NULL or 0 (false). -** In other words, a prior r[P2] value will not be overwritten by 1 (true). -*/ -/* Opcode: Ne P1 P2 P3 P4 P5 -** Synopsis: IF r[P3]!=r[P1] -** -** This works just like the Eq opcode except that the jump is taken if -** the operands in registers P1 and P3 are not equal. See the Eq opcode for -** additional information. -** -** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the -** content of r[P2] is only changed if the new value is NULL or 1 (true). -** In other words, a prior r[P2] value will not be overwritten by 0 (false). -*/ -/* Opcode: Lt P1 P2 P3 P4 P5 -** Synopsis: IF r[P3]r[P1] -** -** This works just like the Lt opcode except that the jump is taken if -** the content of register P3 is greater than the content of -** register P1. See the Lt opcode for additional information. -*/ -/* Opcode: Ge P1 P2 P3 P4 P5 -** Synopsis: IF r[P3]>=r[P1] -** -** This works just like the Lt opcode except that the jump is taken if -** the content of register P3 is greater than or equal to the content of -** register P1. See the Lt opcode for additional information. -*/ -case OP_Eq: /* same as TK_EQ, jump, in1, in3 */ -case OP_Ne: /* same as TK_NE, jump, in1, in3 */ -case OP_Lt: /* same as TK_LT, jump, in1, in3 */ -case OP_Le: /* same as TK_LE, jump, in1, in3 */ -case OP_Gt: /* same as TK_GT, jump, in1, in3 */ -case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ - int res, res2; /* Result of the comparison of pIn1 against pIn3 */ - char affinity; /* Affinity to use for comparison */ - u16 flags1; /* Copy of initial value of pIn1->flags */ - u16 flags3; /* Copy of initial value of pIn3->flags */ - - pIn1 = &aMem[pOp->p1]; - pIn3 = &aMem[pOp->p3]; - flags1 = pIn1->flags; - flags3 = pIn3->flags; - if( (flags1 | flags3)&MEM_Null ){ - /* One or both operands are NULL */ - if( pOp->p5 & SQLITE_NULLEQ ){ - /* If SQLITE_NULLEQ is set (which will only happen if the operator is - ** OP_Eq or OP_Ne) then take the jump or not depending on whether - ** or not both operands are null. - */ - assert( (flags1 & MEM_Cleared)==0 ); - assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB ); - testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 ); - if( (flags1&flags3&MEM_Null)!=0 - && (flags3&MEM_Cleared)==0 - ){ - res = 0; /* Operands are equal */ - }else{ - res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */ - } - }else{ - /* SQLITE_NULLEQ is clear and at least one operand is NULL, - ** then the result is always NULL. - ** The jump is taken if the SQLITE_JUMPIFNULL bit is set. - */ - if( pOp->p5 & SQLITE_STOREP2 ){ - pOut = &aMem[pOp->p2]; - iCompare = 1; /* Operands are not equal */ - memAboutToChange(p, pOut); - MemSetTypeFlag(pOut, MEM_Null); - REGISTER_TRACE(pOp->p2, pOut); - }else{ - VdbeBranchTaken(2,3); - if( pOp->p5 & SQLITE_JUMPIFNULL ){ - goto jump_to_p2; - } - } - break; - } - }else{ - /* Neither operand is NULL. Do a comparison. */ - affinity = pOp->p5 & SQLITE_AFF_MASK; - if( affinity>=SQLITE_AFF_NUMERIC ){ - if( (flags1 | flags3)&MEM_Str ){ - if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){ - applyNumericAffinity(pIn1,0); - testcase( flags3==pIn3->flags ); - flags3 = pIn3->flags; - } - if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){ - applyNumericAffinity(pIn3,0); - } - } - /* Handle the common case of integer comparison here, as an - ** optimization, to avoid a call to sqlite3MemCompare() */ - if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){ - if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; } - if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; } - res = 0; - goto compare_op; - } - }else if( affinity==SQLITE_AFF_TEXT ){ - if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){ - testcase( pIn1->flags & MEM_Int ); - testcase( pIn1->flags & MEM_Real ); - testcase( pIn1->flags & MEM_IntReal ); - sqlite3VdbeMemStringify(pIn1, encoding, 1); - testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) ); - flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask); - if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str; - } - if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){ - testcase( pIn3->flags & MEM_Int ); - testcase( pIn3->flags & MEM_Real ); - testcase( pIn3->flags & MEM_IntReal ); - sqlite3VdbeMemStringify(pIn3, encoding, 1); - testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) ); - flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask); - } - } - assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); - res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); - } -compare_op: - /* At this point, res is negative, zero, or positive if reg[P1] is - ** less than, equal to, or greater than reg[P3], respectively. Compute - ** the answer to this operator in res2, depending on what the comparison - ** operator actually is. The next block of code depends on the fact - ** that the 6 comparison operators are consecutive integers in this - ** order: NE, EQ, GT, LE, LT, GE */ - assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 ); - assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 ); - if( res<0 ){ /* ne, eq, gt, le, lt, ge */ - static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 }; - res2 = aLTb[pOp->opcode - OP_Ne]; - }else if( res==0 ){ - static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 }; - res2 = aEQb[pOp->opcode - OP_Ne]; - }else{ - static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 }; - res2 = aGTb[pOp->opcode - OP_Ne]; - } - - /* Undo any changes made by applyAffinity() to the input registers. */ - assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) ); - pIn3->flags = flags3; - assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); - pIn1->flags = flags1; - - if( pOp->p5 & SQLITE_STOREP2 ){ - pOut = &aMem[pOp->p2]; - iCompare = res; - if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){ - /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1 - ** and prevents OP_Ne from overwriting NULL with 0. This flag - ** is only used in contexts where either: - ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0) - ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1) - ** Therefore it is not necessary to check the content of r[P2] for - ** NULL. */ - assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq ); - assert( res2==0 || res2==1 ); - testcase( res2==0 && pOp->opcode==OP_Eq ); - testcase( res2==1 && pOp->opcode==OP_Eq ); - testcase( res2==0 && pOp->opcode==OP_Ne ); - testcase( res2==1 && pOp->opcode==OP_Ne ); - if( (pOp->opcode==OP_Eq)==res2 ) break; - } - memAboutToChange(p, pOut); - MemSetTypeFlag(pOut, MEM_Int); - pOut->u.i = res2; - REGISTER_TRACE(pOp->p2, pOut); - }else{ - VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3); - if( res2 ){ - goto jump_to_p2; - } - } - break; -} - -/* Opcode: ElseNotEq * P2 * * * -** -** This opcode must follow an OP_Lt or OP_Gt comparison operator. There -** can be zero or more OP_ReleaseReg opcodes intervening, but no other -** opcodes are allowed to occur between this instruction and the previous -** OP_Lt or OP_Gt. Furthermore, the prior OP_Lt or OP_Gt must have the -** SQLITE_STOREP2 bit set in the P5 field. -** -** If result of an OP_Eq comparison on the same two operands as the -** prior OP_Lt or OP_Gt would have been NULL or false (0), then then -** jump to P2. If the result of an OP_Eq comparison on the two previous -** operands would have been true (1), then fall through. -*/ -case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */ - -#ifdef SQLITE_DEBUG - /* Verify the preconditions of this opcode - that it follows an OP_Lt or - ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening - ** OP_ReleaseReg opcodes */ - int iAddr; - for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){ - if( aOp[iAddr].opcode==OP_ReleaseReg ) continue; - assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt ); - assert( aOp[iAddr].p5 & SQLITE_STOREP2 ); - break; - } -#endif /* SQLITE_DEBUG */ - VdbeBranchTaken(iCompare!=0, 2); - if( iCompare!=0 ) goto jump_to_p2; - break; -} - - -/* Opcode: Permutation * * * P4 * -** -** Set the permutation used by the OP_Compare operator in the next -** instruction. The permutation is stored in the P4 operand. -** -** The permutation is only valid until the next OP_Compare that has -** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should -** occur immediately prior to the OP_Compare. -** -** The first integer in the P4 integer array is the length of the array -** and does not become part of the permutation. -*/ -case OP_Permutation: { - assert( pOp->p4type==P4_INTARRAY ); - assert( pOp->p4.ai ); - assert( pOp[1].opcode==OP_Compare ); - assert( pOp[1].p5 & OPFLAG_PERMUTE ); - break; -} - -/* Opcode: Compare P1 P2 P3 P4 P5 -** Synopsis: r[P1@P3] <-> r[P2@P3] -** -** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this -** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of -** the comparison for use by the next OP_Jump instruct. -** -** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is -** determined by the most recent OP_Permutation operator. If the -** OPFLAG_PERMUTE bit is clear, then register are compared in sequential -** order. -** -** P4 is a KeyInfo structure that defines collating sequences and sort -** orders for the comparison. The permutation applies to registers -** only. The KeyInfo elements are used sequentially. -** -** The comparison is a sort comparison, so NULLs compare equal, -** NULLs are less than numbers, numbers are less than strings, -** and strings are less than blobs. -*/ -case OP_Compare: { - int n; - int i; - int p1; - int p2; - const KeyInfo *pKeyInfo; - u32 idx; - CollSeq *pColl; /* Collating sequence to use on this term */ - int bRev; /* True for DESCENDING sort order */ - u32 *aPermute; /* The permutation */ - - if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){ - aPermute = 0; - }else{ - assert( pOp>aOp ); - assert( pOp[-1].opcode==OP_Permutation ); - assert( pOp[-1].p4type==P4_INTARRAY ); - aPermute = pOp[-1].p4.ai + 1; - assert( aPermute!=0 ); - } - n = pOp->p3; - pKeyInfo = pOp->p4.pKeyInfo; - assert( n>0 ); - assert( pKeyInfo!=0 ); - p1 = pOp->p1; - p2 = pOp->p2; -#ifdef SQLITE_DEBUG - if( aPermute ){ - int k, mx = 0; - for(k=0; k(u32)mx ) mx = aPermute[k]; - assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 ); - assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 ); - }else{ - assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 ); - assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 ); - } -#endif /* SQLITE_DEBUG */ - for(i=0; inKeyField ); - pColl = pKeyInfo->aColl[i]; - bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC); - iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); - if( iCompare ){ - if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) - && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null)) - ){ - iCompare = -iCompare; - } - if( bRev ) iCompare = -iCompare; - break; - } - } - break; -} - -/* Opcode: Jump P1 P2 P3 * * -** -** Jump to the instruction at address P1, P2, or P3 depending on whether -** in the most recent OP_Compare instruction the P1 vector was less than -** equal to, or greater than the P2 vector, respectively. -*/ -case OP_Jump: { /* jump */ - if( iCompare<0 ){ - VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1]; - }else if( iCompare==0 ){ - VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1]; - }else{ - VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1]; - } - break; -} - -/* Opcode: And P1 P2 P3 * * -** Synopsis: r[P3]=(r[P1] && r[P2]) -** -** Take the logical AND of the values in registers P1 and P2 and -** write the result into register P3. -** -** If either P1 or P2 is 0 (false) then the result is 0 even if -** the other input is NULL. A NULL and true or two NULLs give -** a NULL output. -*/ -/* Opcode: Or P1 P2 P3 * * -** Synopsis: r[P3]=(r[P1] || r[P2]) -** -** Take the logical OR of the values in register P1 and P2 and -** store the answer in register P3. -** -** If either P1 or P2 is nonzero (true) then the result is 1 (true) -** even if the other input is NULL. A NULL and false or two NULLs -** give a NULL output. -*/ -case OP_And: /* same as TK_AND, in1, in2, out3 */ -case OP_Or: { /* same as TK_OR, in1, in2, out3 */ - int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ - int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ - - v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2); - v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2); - if( pOp->opcode==OP_And ){ - static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; - v1 = and_logic[v1*3+v2]; - }else{ - static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; - v1 = or_logic[v1*3+v2]; - } - pOut = &aMem[pOp->p3]; - if( v1==2 ){ - MemSetTypeFlag(pOut, MEM_Null); - }else{ - pOut->u.i = v1; - MemSetTypeFlag(pOut, MEM_Int); - } - break; -} - -/* Opcode: IsTrue P1 P2 P3 P4 * -** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 -** -** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and -** IS NOT FALSE operators. -** -** Interpret the value in register P1 as a boolean value. Store that -** boolean (a 0 or 1) in register P2. Or if the value in register P1 is -** NULL, then the P3 is stored in register P2. Invert the answer if P4 -** is 1. -** -** The logic is summarized like this: -** -**
      -**
    • If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE -**
    • If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE -**
    • If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE -**
    • If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE -**
    -*/ -case OP_IsTrue: { /* in1, out2 */ - assert( pOp->p4type==P4_INT32 ); - assert( pOp->p4.i==0 || pOp->p4.i==1 ); - assert( pOp->p3==0 || pOp->p3==1 ); - sqlite3VdbeMemSetInt64(&aMem[pOp->p2], - sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i); - break; -} - -/* Opcode: Not P1 P2 * * * -** Synopsis: r[P2]= !r[P1] -** -** Interpret the value in register P1 as a boolean value. Store the -** boolean complement in register P2. If the value in register P1 is -** NULL, then a NULL is stored in P2. -*/ -case OP_Not: { /* same as TK_NOT, in1, out2 */ - pIn1 = &aMem[pOp->p1]; - pOut = &aMem[pOp->p2]; - if( (pIn1->flags & MEM_Null)==0 ){ - sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0)); - }else{ - sqlite3VdbeMemSetNull(pOut); - } - break; -} - -/* Opcode: BitNot P1 P2 * * * -** Synopsis: r[P2]= ~r[P1] -** -** Interpret the content of register P1 as an integer. Store the -** ones-complement of the P1 value into register P2. If P1 holds -** a NULL then store a NULL in P2. -*/ -case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ - pIn1 = &aMem[pOp->p1]; - pOut = &aMem[pOp->p2]; - sqlite3VdbeMemSetNull(pOut); - if( (pIn1->flags & MEM_Null)==0 ){ - pOut->flags = MEM_Int; - pOut->u.i = ~sqlite3VdbeIntValue(pIn1); - } - break; -} - -/* Opcode: Once P1 P2 * * * -** -** Fall through to the next instruction the first time this opcode is -** encountered on each invocation of the byte-code program. Jump to P2 -** on the second and all subsequent encounters during the same invocation. -** -** Top-level programs determine first invocation by comparing the P1 -** operand against the P1 operand on the OP_Init opcode at the beginning -** of the program. If the P1 values differ, then fall through and make -** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are -** the same then take the jump. -** -** For subprograms, there is a bitmask in the VdbeFrame that determines -** whether or not the jump should be taken. The bitmask is necessary -** because the self-altering code trick does not work for recursive -** triggers. -*/ -case OP_Once: { /* jump */ - u32 iAddr; /* Address of this instruction */ - assert( p->aOp[0].opcode==OP_Init ); - if( p->pFrame ){ - iAddr = (int)(pOp - p->aOp); - if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){ - VdbeBranchTaken(1, 2); - goto jump_to_p2; - } - p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7); - }else{ - if( p->aOp[0].p1==pOp->p1 ){ - VdbeBranchTaken(1, 2); - goto jump_to_p2; - } - } - VdbeBranchTaken(0, 2); - pOp->p1 = p->aOp[0].p1; - break; -} - -/* Opcode: If P1 P2 P3 * * -** -** Jump to P2 if the value in register P1 is true. The value -** is considered true if it is numeric and non-zero. If the value -** in P1 is NULL then take the jump if and only if P3 is non-zero. -*/ -case OP_If: { /* jump, in1 */ - int c; - c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3); - VdbeBranchTaken(c!=0, 2); - if( c ) goto jump_to_p2; - break; -} - -/* Opcode: IfNot P1 P2 P3 * * -** -** Jump to P2 if the value in register P1 is False. The value -** is considered false if it has a numeric value of zero. If the value -** in P1 is NULL then take the jump if and only if P3 is non-zero. -*/ -case OP_IfNot: { /* jump, in1 */ - int c; - c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3); - VdbeBranchTaken(c!=0, 2); - if( c ) goto jump_to_p2; - break; -} - -/* Opcode: IsNull P1 P2 * * * -** Synopsis: if r[P1]==NULL goto P2 -** -** Jump to P2 if the value in register P1 is NULL. -*/ -case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ - pIn1 = &aMem[pOp->p1]; - VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2); - if( (pIn1->flags & MEM_Null)!=0 ){ - goto jump_to_p2; - } - break; -} - -/* Opcode: NotNull P1 P2 * * * -** Synopsis: if r[P1]!=NULL goto P2 -** -** Jump to P2 if the value in register P1 is not NULL. -*/ -case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ - pIn1 = &aMem[pOp->p1]; - VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2); - if( (pIn1->flags & MEM_Null)==0 ){ - goto jump_to_p2; - } - break; -} - -/* Opcode: IfNullRow P1 P2 P3 * * -** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2 -** -** Check the cursor P1 to see if it is currently pointing at a NULL row. -** If it is, then set register P3 to NULL and jump immediately to P2. -** If P1 is not on a NULL row, then fall through without making any -** changes. -*/ -case OP_IfNullRow: { /* jump */ - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( p->apCsr[pOp->p1]!=0 ); - if( p->apCsr[pOp->p1]->nullRow ){ - sqlite3VdbeMemSetNull(aMem + pOp->p3); - goto jump_to_p2; - } - break; -} - -#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC -/* Opcode: Offset P1 P2 P3 * * -** Synopsis: r[P3] = sqlite_offset(P1) -** -** Store in register r[P3] the byte offset into the database file that is the -** start of the payload for the record at which that cursor P1 is currently -** pointing. -** -** P2 is the column number for the argument to the sqlite_offset() function. -** This opcode does not use P2 itself, but the P2 value is used by the -** code generator. The P1, P2, and P3 operands to this opcode are the -** same as for OP_Column. -** -** This opcode is only available if SQLite is compiled with the -** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option. -*/ -case OP_Offset: { /* out3 */ - VdbeCursor *pC; /* The VDBE cursor */ - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - pOut = &p->aMem[pOp->p3]; - if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){ - sqlite3VdbeMemSetNull(pOut); - }else{ - sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor)); - } - break; -} -#endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */ - -/* Opcode: Column P1 P2 P3 P4 P5 -** Synopsis: r[P3]=PX -** -** Interpret the data that cursor P1 points to as a structure built using -** the MakeRecord instruction. (See the MakeRecord opcode for additional -** information about the format of the data.) Extract the P2-th column -** from this record. If there are less that (P2+1) -** values in the record, extract a NULL. -** -** The value extracted is stored in register P3. -** -** If the record contains fewer than P2 fields, then extract a NULL. Or, -** if the P4 argument is a P4_MEM use the value of the P4 argument as -** the result. -** -** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then -** the result is guaranteed to only be used as the argument of a length() -** or typeof() function, respectively. The loading of large blobs can be -** skipped for length() and all content loading can be skipped for typeof(). -*/ -case OP_Column: { - u32 p2; /* column number to retrieve */ - VdbeCursor *pC; /* The VDBE cursor */ - BtCursor *pCrsr; /* The BTree cursor */ - u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ - int len; /* The length of the serialized data for the column */ - int i; /* Loop counter */ - Mem *pDest; /* Where to write the extracted value */ - Mem sMem; /* For storing the record being decoded */ - const u8 *zData; /* Part of the record being decoded */ - const u8 *zHdr; /* Next unparsed byte of the header */ - const u8 *zEndHdr; /* Pointer to first byte after the header */ - u64 offset64; /* 64-bit offset */ - u32 t; /* A type code from the record header */ - Mem *pReg; /* PseudoTable input register */ - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - p2 = (u32)pOp->p2; - - /* If the cursor cache is stale (meaning it is not currently point at - ** the correct row) then bring it up-to-date by doing the necessary - ** B-Tree seek. */ - rc = sqlite3VdbeCursorMoveto(&pC, &p2); - if( rc ) goto abort_due_to_error; - - assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - pDest = &aMem[pOp->p3]; - memAboutToChange(p, pDest); - assert( pC!=0 ); - assert( p2<(u32)pC->nField ); - aOffset = pC->aOffset; - assert( pC->eCurType!=CURTYPE_VTAB ); - assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); - assert( pC->eCurType!=CURTYPE_SORTER ); - - if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/ - if( pC->nullRow ){ - if( pC->eCurType==CURTYPE_PSEUDO ){ - /* For the special case of as pseudo-cursor, the seekResult field - ** identifies the register that holds the record */ - assert( pC->seekResult>0 ); - pReg = &aMem[pC->seekResult]; - assert( pReg->flags & MEM_Blob ); - assert( memIsValid(pReg) ); - pC->payloadSize = pC->szRow = pReg->n; - pC->aRow = (u8*)pReg->z; - }else{ - sqlite3VdbeMemSetNull(pDest); - goto op_column_out; - } - }else{ - pCrsr = pC->uc.pCursor; - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pCrsr ); - assert( sqlite3BtreeCursorIsValid(pCrsr) ); - pC->payloadSize = sqlite3BtreePayloadSize(pCrsr); - pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow); - assert( pC->szRow<=pC->payloadSize ); - assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */ - if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - } - pC->cacheStatus = p->cacheCtr; - pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]); - pC->nHdrParsed = 0; - - - if( pC->szRowaRow does not have to hold the entire row, but it does at least - ** need to cover the header of the record. If pC->aRow does not contain - ** the complete header, then set it to zero, forcing the header to be - ** dynamically allocated. */ - pC->aRow = 0; - pC->szRow = 0; - - /* Make sure a corrupt database has not given us an oversize header. - ** Do this now to avoid an oversize memory allocation. - ** - ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte - ** types use so much data space that there can only be 4096 and 32 of - ** them, respectively. So the maximum header length results from a - ** 3-byte type for each of the maximum of 32768 columns plus three - ** extra bytes for the header length itself. 32768*3 + 3 = 98307. - */ - if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){ - goto op_column_corrupt; - } - }else{ - /* This is an optimization. By skipping over the first few tests - ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a - ** measurable performance gain. - ** - ** This branch is taken even if aOffset[0]==0. Such a record is never - ** generated by SQLite, and could be considered corruption, but we - ** accept it for historical reasons. When aOffset[0]==0, the code this - ** branch jumps to reads past the end of the record, but never more - ** than a few bytes. Even if the record occurs at the end of the page - ** content area, the "page header" comes after the page content and so - ** this overread is harmless. Similar overreads can occur for a corrupt - ** database file. - */ - zData = pC->aRow; - assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */ - testcase( aOffset[0]==0 ); - goto op_column_read_header; - } - } - - /* Make sure at least the first p2+1 entries of the header have been - ** parsed and valid information is in aOffset[] and pC->aType[]. - */ - if( pC->nHdrParsed<=p2 ){ - /* If there is more header available for parsing in the record, try - ** to extract additional fields up through the p2+1-th field - */ - if( pC->iHdrOffsetaRow==0 ){ - memset(&sMem, 0, sizeof(sMem)); - rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - zData = (u8*)sMem.z; - }else{ - zData = pC->aRow; - } - - /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */ - op_column_read_header: - i = pC->nHdrParsed; - offset64 = aOffset[i]; - zHdr = zData + pC->iHdrOffset; - zEndHdr = zData + aOffset[0]; - testcase( zHdr>=zEndHdr ); - do{ - if( (pC->aType[i] = t = zHdr[0])<0x80 ){ - zHdr++; - offset64 += sqlite3VdbeOneByteSerialTypeLen(t); - }else{ - zHdr += sqlite3GetVarint32(zHdr, &t); - pC->aType[i] = t; - offset64 += sqlite3VdbeSerialTypeLen(t); - } - aOffset[++i] = (u32)(offset64 & 0xffffffff); - }while( (u32)i<=p2 && zHdr=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize)) - || (offset64 > pC->payloadSize) - ){ - if( aOffset[0]==0 ){ - i = 0; - zHdr = zEndHdr; - }else{ - if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); - goto op_column_corrupt; - } - } - - pC->nHdrParsed = i; - pC->iHdrOffset = (u32)(zHdr - zData); - if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem); - }else{ - t = 0; - } - - /* If after trying to extract new entries from the header, nHdrParsed is - ** still not up to p2, that means that the record has fewer than p2 - ** columns. So the result will be either the default value or a NULL. - */ - if( pC->nHdrParsed<=p2 ){ - if( pOp->p4type==P4_MEM ){ - sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); - }else{ - sqlite3VdbeMemSetNull(pDest); - } - goto op_column_out; - } - }else{ - t = pC->aType[p2]; - } - - /* Extract the content for the p2+1-th column. Control can only - ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are - ** all valid. - */ - assert( p2nHdrParsed ); - assert( rc==SQLITE_OK ); - assert( sqlite3VdbeCheckMemInvariants(pDest) ); - if( VdbeMemDynamic(pDest) ){ - sqlite3VdbeMemSetNull(pDest); - } - assert( t==pC->aType[p2] ); - if( pC->szRow>=aOffset[p2+1] ){ - /* This is the common case where the desired content fits on the original - ** page - where the content is not on an overflow page */ - zData = pC->aRow + aOffset[p2]; - if( t<12 ){ - sqlite3VdbeSerialGet(zData, t, pDest); - }else{ - /* If the column value is a string, we need a persistent value, not - ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent - ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize(). - */ - static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term }; - pDest->n = len = (t-12)/2; - pDest->enc = encoding; - if( pDest->szMalloc < len+2 ){ - pDest->flags = MEM_Null; - if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; - }else{ - pDest->z = pDest->zMalloc; - } - memcpy(pDest->z, zData, len); - pDest->z[len] = 0; - pDest->z[len+1] = 0; - pDest->flags = aFlag[t&1]; - } - }else{ - pDest->enc = encoding; - /* This branch happens only when content is on overflow pages */ - if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0 - && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)) - || (len = sqlite3VdbeSerialTypeLen(t))==0 - ){ - /* Content is irrelevant for - ** 1. the typeof() function, - ** 2. the length(X) function if X is a blob, and - ** 3. if the content length is zero. - ** So we might as well use bogus content rather than reading - ** content from disk. - ** - ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the - ** buffer passed to it, debugging function VdbeMemPrettyPrint() may - ** read more. Use the global constant sqlite3CtypeMap[] as the array, - ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint()) - ** and it begins with a bunch of zeros. - */ - sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest); - }else{ - rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest); - pDest->flags &= ~MEM_Ephem; - } - } - -op_column_out: - UPDATE_MAX_BLOBSIZE(pDest); - REGISTER_TRACE(pOp->p3, pDest); - break; - -op_column_corrupt: - if( aOp[0].p3>0 ){ - pOp = &aOp[aOp[0].p3-1]; - break; - }else{ - rc = SQLITE_CORRUPT_BKPT; - goto abort_due_to_error; - } -} - -/* Opcode: Affinity P1 P2 * P4 * -** Synopsis: affinity(r[P1@P2]) -** -** Apply affinities to a range of P2 registers starting with P1. -** -** P4 is a string that is P2 characters long. The N-th character of the -** string indicates the column affinity that should be used for the N-th -** memory cell in the range. -*/ -case OP_Affinity: { - const char *zAffinity; /* The affinity to be applied */ - - zAffinity = pOp->p4.z; - assert( zAffinity!=0 ); - assert( pOp->p2>0 ); - assert( zAffinity[pOp->p2]==0 ); - pIn1 = &aMem[pOp->p1]; - while( 1 /*exit-by-break*/ ){ - assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] ); - assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) ); - applyAffinity(pIn1, zAffinity[0], encoding); - if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){ - /* When applying REAL affinity, if the result is still an MEM_Int - ** that will fit in 6 bytes, then change the type to MEM_IntReal - ** so that we keep the high-resolution integer value but know that - ** the type really wants to be REAL. */ - testcase( pIn1->u.i==140737488355328LL ); - testcase( pIn1->u.i==140737488355327LL ); - testcase( pIn1->u.i==-140737488355328LL ); - testcase( pIn1->u.i==-140737488355329LL ); - if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){ - pIn1->flags |= MEM_IntReal; - pIn1->flags &= ~MEM_Int; - }else{ - pIn1->u.r = (double)pIn1->u.i; - pIn1->flags |= MEM_Real; - pIn1->flags &= ~MEM_Int; - } - } - REGISTER_TRACE((int)(pIn1-aMem), pIn1); - zAffinity++; - if( zAffinity[0]==0 ) break; - pIn1++; - } - break; -} - -/* Opcode: MakeRecord P1 P2 P3 P4 * -** Synopsis: r[P3]=mkrec(r[P1@P2]) -** -** Convert P2 registers beginning with P1 into the [record format] -** use as a data record in a database table or as a key -** in an index. The OP_Column opcode can decode the record later. -** -** P4 may be a string that is P2 characters long. The N-th character of the -** string indicates the column affinity that should be used for the N-th -** field of the index key. -** -** The mapping from character to affinity is given by the SQLITE_AFF_ -** macros defined in sqliteInt.h. -** -** If P4 is NULL then all index fields have the affinity BLOB. -** -** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM -** compile-time option is enabled: -** -** * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index -** of the right-most table that can be null-trimmed. -** -** * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value -** OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to -** accept no-change records with serial_type 10. This value is -** only used inside an assert() and does not affect the end result. -*/ -case OP_MakeRecord: { - Mem *pRec; /* The new record */ - u64 nData; /* Number of bytes of data space */ - int nHdr; /* Number of bytes of header space */ - i64 nByte; /* Data space required for this record */ - i64 nZero; /* Number of zero bytes at the end of the record */ - int nVarint; /* Number of bytes in a varint */ - u32 serial_type; /* Type field */ - Mem *pData0; /* First field to be combined into the record */ - Mem *pLast; /* Last field of the record */ - int nField; /* Number of fields in the record */ - char *zAffinity; /* The affinity string for the record */ - int file_format; /* File format to use for encoding */ - u32 len; /* Length of a field */ - u8 *zHdr; /* Where to write next byte of the header */ - u8 *zPayload; /* Where to write next byte of the payload */ - - /* Assuming the record contains N fields, the record format looks - ** like this: - ** - ** ------------------------------------------------------------------------ - ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | - ** ------------------------------------------------------------------------ - ** - ** Data(0) is taken from register P1. Data(1) comes from register P1+1 - ** and so forth. - ** - ** Each type field is a varint representing the serial type of the - ** corresponding data element (see sqlite3VdbeSerialType()). The - ** hdr-size field is also a varint which is the offset from the beginning - ** of the record to data0. - */ - nData = 0; /* Number of bytes of data space */ - nHdr = 0; /* Number of bytes of header space */ - nZero = 0; /* Number of zero bytes at the end of the record */ - nField = pOp->p1; - zAffinity = pOp->p4.z; - assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 ); - pData0 = &aMem[nField]; - nField = pOp->p2; - pLast = &pData0[nField-1]; - file_format = p->minWriteFileFormat; - - /* Identify the output register */ - assert( pOp->p3p1 || pOp->p3>=pOp->p1+pOp->p2 ); - pOut = &aMem[pOp->p3]; - memAboutToChange(p, pOut); - - /* Apply the requested affinity to all inputs - */ - assert( pData0<=pLast ); - if( zAffinity ){ - pRec = pData0; - do{ - applyAffinity(pRec, zAffinity[0], encoding); - if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){ - pRec->flags |= MEM_IntReal; - pRec->flags &= ~(MEM_Int); - } - REGISTER_TRACE((int)(pRec-aMem), pRec); - zAffinity++; - pRec++; - assert( zAffinity[0]==0 || pRec<=pLast ); - }while( zAffinity[0] ); - } - -#ifdef SQLITE_ENABLE_NULL_TRIM - /* NULLs can be safely trimmed from the end of the record, as long as - ** as the schema format is 2 or more and none of the omitted columns - ** have a non-NULL default value. Also, the record must be left with - ** at least one field. If P5>0 then it will be one more than the - ** index of the right-most column with a non-NULL default value */ - if( pOp->p5 ){ - while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){ - pLast--; - nField--; - } - } -#endif - - /* Loop through the elements that will make up the record to figure - ** out how much space is required for the new record. After this loop, - ** the Mem.uTemp field of each term should hold the serial-type that will - ** be used for that term in the generated record: - ** - ** Mem.uTemp value type - ** --------------- --------------- - ** 0 NULL - ** 1 1-byte signed integer - ** 2 2-byte signed integer - ** 3 3-byte signed integer - ** 4 4-byte signed integer - ** 5 6-byte signed integer - ** 6 8-byte signed integer - ** 7 IEEE float - ** 8 Integer constant 0 - ** 9 Integer constant 1 - ** 10,11 reserved for expansion - ** N>=12 and even BLOB - ** N>=13 and odd text - ** - ** The following additional values are computed: - ** nHdr Number of bytes needed for the record header - ** nData Number of bytes of data space needed for the record - ** nZero Zero bytes at the end of the record - */ - pRec = pLast; - do{ - assert( memIsValid(pRec) ); - if( pRec->flags & MEM_Null ){ - if( pRec->flags & MEM_Zero ){ - /* Values with MEM_Null and MEM_Zero are created by xColumn virtual - ** table methods that never invoke sqlite3_result_xxxxx() while - ** computing an unchanging column value in an UPDATE statement. - ** Give such values a special internal-use-only serial-type of 10 - ** so that they can be passed through to xUpdate and have - ** a true sqlite3_value_nochange(). */ -#ifndef SQLITE_ENABLE_NULL_TRIM - assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB ); -#endif - pRec->uTemp = 10; - }else{ - pRec->uTemp = 0; - } - nHdr++; - }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){ - /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */ - i64 i = pRec->u.i; - u64 uu; - testcase( pRec->flags & MEM_Int ); - testcase( pRec->flags & MEM_IntReal ); - if( i<0 ){ - uu = ~i; - }else{ - uu = i; - } - nHdr++; - testcase( uu==127 ); testcase( uu==128 ); - testcase( uu==32767 ); testcase( uu==32768 ); - testcase( uu==8388607 ); testcase( uu==8388608 ); - testcase( uu==2147483647 ); testcase( uu==2147483648 ); - testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL ); - if( uu<=127 ){ - if( (i&1)==i && file_format>=4 ){ - pRec->uTemp = 8+(u32)uu; - }else{ - nData++; - pRec->uTemp = 1; - } - }else if( uu<=32767 ){ - nData += 2; - pRec->uTemp = 2; - }else if( uu<=8388607 ){ - nData += 3; - pRec->uTemp = 3; - }else if( uu<=2147483647 ){ - nData += 4; - pRec->uTemp = 4; - }else if( uu<=140737488355327LL ){ - nData += 6; - pRec->uTemp = 5; - }else{ - nData += 8; - if( pRec->flags & MEM_IntReal ){ - /* If the value is IntReal and is going to take up 8 bytes to store - ** as an integer, then we might as well make it an 8-byte floating - ** point value */ - pRec->u.r = (double)pRec->u.i; - pRec->flags &= ~MEM_IntReal; - pRec->flags |= MEM_Real; - pRec->uTemp = 7; - }else{ - pRec->uTemp = 6; - } - } - }else if( pRec->flags & MEM_Real ){ - nHdr++; - nData += 8; - pRec->uTemp = 7; - }else{ - assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) ); - assert( pRec->n>=0 ); - len = (u32)pRec->n; - serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0); - if( pRec->flags & MEM_Zero ){ - serial_type += pRec->u.nZero*2; - if( nData ){ - if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; - len += pRec->u.nZero; - }else{ - nZero += pRec->u.nZero; - } - } - nData += len; - nHdr += sqlite3VarintLen(serial_type); - pRec->uTemp = serial_type; - } - if( pRec==pData0 ) break; - pRec--; - }while(1); - - /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint - ** which determines the total number of bytes in the header. The varint - ** value is the size of the header in bytes including the size varint - ** itself. */ - testcase( nHdr==126 ); - testcase( nHdr==127 ); - if( nHdr<=126 ){ - /* The common case */ - nHdr += 1; - }else{ - /* Rare case of a really large header */ - nVarint = sqlite3VarintLen(nHdr); - nHdr += nVarint; - if( nVarintp3) is not allowed to - ** be one of the input registers (because the following call to - ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used). - */ - if( nByte+nZero<=pOut->szMalloc ){ - /* The output register is already large enough to hold the record. - ** No error checks or buffer enlargement is required */ - pOut->z = pOut->zMalloc; - }else{ - /* Need to make sure that the output is not too big and then enlarge - ** the output register to hold the full result */ - if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ - goto no_mem; - } - } - pOut->n = (int)nByte; - pOut->flags = MEM_Blob; - if( nZero ){ - pOut->u.nZero = nZero; - pOut->flags |= MEM_Zero; - } - UPDATE_MAX_BLOBSIZE(pOut); - zHdr = (u8 *)pOut->z; - zPayload = zHdr + nHdr; - - /* Write the record */ - zHdr += putVarint32(zHdr, nHdr); - assert( pData0<=pLast ); - pRec = pData0; - do{ - serial_type = pRec->uTemp; - /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more - ** additional varints, one per column. */ - zHdr += putVarint32(zHdr, serial_type); /* serial type */ - /* EVIDENCE-OF: R-64536-51728 The values for each column in the record - ** immediately follow the header. */ - zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */ - }while( (++pRec)<=pLast ); - assert( nHdr==(int)(zHdr - (u8*)pOut->z) ); - assert( nByte==(int)(zPayload - (u8*)pOut->z) ); - - assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - REGISTER_TRACE(pOp->p3, pOut); - break; -} - -/* Opcode: Count P1 P2 p3 * * -** Synopsis: r[P2]=count() -** -** Store the number of entries (an integer value) in the table or index -** opened by cursor P1 in register P2. -** -** If P3==0, then an exact count is obtained, which involves visiting -** every btree page of the table. But if P3 is non-zero, an estimate -** is returned based on the current cursor position. -*/ -case OP_Count: { /* out2 */ - i64 nEntry; - BtCursor *pCrsr; - - assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE ); - pCrsr = p->apCsr[pOp->p1]->uc.pCursor; - assert( pCrsr ); - if( pOp->p3 ){ - nEntry = sqlite3BtreeRowCountEst(pCrsr); - }else{ - nEntry = 0; /* Not needed. Only used to silence a warning. */ - rc = sqlite3BtreeCount(db, pCrsr, &nEntry); - if( rc ) goto abort_due_to_error; - } - pOut = out2Prerelease(p, pOp); - pOut->u.i = nEntry; - goto check_for_interrupt; -} - -/* Opcode: Savepoint P1 * * P4 * -** -** Open, release or rollback the savepoint named by parameter P4, depending -** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN). -** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE). -** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK). -*/ -case OP_Savepoint: { - int p1; /* Value of P1 operand */ - char *zName; /* Name of savepoint */ - int nName; - Savepoint *pNew; - Savepoint *pSavepoint; - Savepoint *pTmp; - int iSavepoint; - int ii; - - p1 = pOp->p1; - zName = pOp->p4.z; - - /* Assert that the p1 parameter is valid. Also that if there is no open - ** transaction, then there cannot be any savepoints. - */ - assert( db->pSavepoint==0 || db->autoCommit==0 ); - assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK ); - assert( db->pSavepoint || db->isTransactionSavepoint==0 ); - assert( checkSavepointCount(db) ); - assert( p->bIsReader ); - - if( p1==SAVEPOINT_BEGIN ){ - if( db->nVdbeWrite>0 ){ - /* A new savepoint cannot be created if there are active write - ** statements (i.e. open read/write incremental blob handles). - */ - sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress"); - rc = SQLITE_BUSY; - }else{ - nName = sqlite3Strlen30(zName); - -#ifndef SQLITE_OMIT_VIRTUALTABLE - /* This call is Ok even if this savepoint is actually a transaction - ** savepoint (and therefore should not prompt xSavepoint()) callbacks. - ** If this is a transaction savepoint being opened, it is guaranteed - ** that the db->aVTrans[] array is empty. */ - assert( db->autoCommit==0 || db->nVTrans==0 ); - rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, - db->nStatement+db->nSavepoint); - if( rc!=SQLITE_OK ) goto abort_due_to_error; -#endif - - /* Create a new savepoint structure. */ - pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1); - if( pNew ){ - pNew->zName = (char *)&pNew[1]; - memcpy(pNew->zName, zName, nName+1); - - /* If there is no open transaction, then mark this as a special - ** "transaction savepoint". */ - if( db->autoCommit ){ - db->autoCommit = 0; - db->isTransactionSavepoint = 1; - }else{ - db->nSavepoint++; - } - - /* Link the new savepoint into the database handle's list. */ - pNew->pNext = db->pSavepoint; - db->pSavepoint = pNew; - pNew->nDeferredCons = db->nDeferredCons; - pNew->nDeferredImmCons = db->nDeferredImmCons; - } - } - }else{ - assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK ); - iSavepoint = 0; - - /* Find the named savepoint. If there is no such savepoint, then an - ** an error is returned to the user. */ - for( - pSavepoint = db->pSavepoint; - pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName); - pSavepoint = pSavepoint->pNext - ){ - iSavepoint++; - } - if( !pSavepoint ){ - sqlite3VdbeError(p, "no such savepoint: %s", zName); - rc = SQLITE_ERROR; - }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){ - /* It is not possible to release (commit) a savepoint if there are - ** active write statements. - */ - sqlite3VdbeError(p, "cannot release savepoint - " - "SQL statements in progress"); - rc = SQLITE_BUSY; - }else{ - - /* Determine whether or not this is a transaction savepoint. If so, - ** and this is a RELEASE command, then the current transaction - ** is committed. - */ - int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; - if( isTransaction && p1==SAVEPOINT_RELEASE ){ - if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ - goto vdbe_return; - } - db->autoCommit = 1; - if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ - p->pc = (int)(pOp - aOp); - db->autoCommit = 0; - p->rc = rc = SQLITE_BUSY; - goto vdbe_return; - } - rc = p->rc; - if( rc ){ - db->autoCommit = 0; - }else{ - db->isTransactionSavepoint = 0; - } - }else{ - int isSchemaChange; - iSavepoint = db->nSavepoint - iSavepoint - 1; - if( p1==SAVEPOINT_ROLLBACK ){ - isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0; - for(ii=0; iinDb; ii++){ - rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, - SQLITE_ABORT_ROLLBACK, - isSchemaChange==0); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - } - }else{ - assert( p1==SAVEPOINT_RELEASE ); - isSchemaChange = 0; - } - for(ii=0; iinDb; ii++){ - rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - } - if( isSchemaChange ){ - sqlite3ExpirePreparedStatements(db, 0); - sqlite3ResetAllSchemasOfConnection(db); - db->mDbFlags |= DBFLAG_SchemaChange; - } - } - if( rc ) goto abort_due_to_error; - - /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all - ** savepoints nested inside of the savepoint being operated on. */ - while( db->pSavepoint!=pSavepoint ){ - pTmp = db->pSavepoint; - db->pSavepoint = pTmp->pNext; - sqlite3DbFree(db, pTmp); - db->nSavepoint--; - } - - /* If it is a RELEASE, then destroy the savepoint being operated on - ** too. If it is a ROLLBACK TO, then set the number of deferred - ** constraint violations present in the database to the value stored - ** when the savepoint was created. */ - if( p1==SAVEPOINT_RELEASE ){ - assert( pSavepoint==db->pSavepoint ); - db->pSavepoint = pSavepoint->pNext; - sqlite3DbFree(db, pSavepoint); - if( !isTransaction ){ - db->nSavepoint--; - } - }else{ - assert( p1==SAVEPOINT_ROLLBACK ); - db->nDeferredCons = pSavepoint->nDeferredCons; - db->nDeferredImmCons = pSavepoint->nDeferredImmCons; - } - - if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){ - rc = sqlite3VtabSavepoint(db, p1, iSavepoint); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - } - } - } - if( rc ) goto abort_due_to_error; - - break; -} - -/* Opcode: AutoCommit P1 P2 * * * -** -** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll -** back any currently active btree transactions. If there are any active -** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if -** there are active writing VMs or active VMs that use shared cache. -** -** This instruction causes the VM to halt. -*/ -case OP_AutoCommit: { - int desiredAutoCommit; - int iRollback; - - desiredAutoCommit = pOp->p1; - iRollback = pOp->p2; - assert( desiredAutoCommit==1 || desiredAutoCommit==0 ); - assert( desiredAutoCommit==1 || iRollback==0 ); - assert( db->nVdbeActive>0 ); /* At least this one VM is active */ - assert( p->bIsReader ); - - if( desiredAutoCommit!=db->autoCommit ){ - if( iRollback ){ - assert( desiredAutoCommit==1 ); - sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK); - db->autoCommit = 1; - }else if( desiredAutoCommit && db->nVdbeWrite>0 ){ - /* If this instruction implements a COMMIT and other VMs are writing - ** return an error indicating that the other VMs must complete first. - */ - sqlite3VdbeError(p, "cannot commit transaction - " - "SQL statements in progress"); - rc = SQLITE_BUSY; - goto abort_due_to_error; - }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ - goto vdbe_return; - }else{ - db->autoCommit = (u8)desiredAutoCommit; - } - if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ - p->pc = (int)(pOp - aOp); - db->autoCommit = (u8)(1-desiredAutoCommit); - p->rc = rc = SQLITE_BUSY; - goto vdbe_return; - } - sqlite3CloseSavepoints(db); - if( p->rc==SQLITE_OK ){ - rc = SQLITE_DONE; - }else{ - rc = SQLITE_ERROR; - } - goto vdbe_return; - }else{ - sqlite3VdbeError(p, - (!desiredAutoCommit)?"cannot start a transaction within a transaction":( - (iRollback)?"cannot rollback - no transaction is active": - "cannot commit - no transaction is active")); - - rc = SQLITE_ERROR; - goto abort_due_to_error; - } - /*NOTREACHED*/ assert(0); -} - -/* Opcode: Transaction P1 P2 P3 P4 P5 -** -** Begin a transaction on database P1 if a transaction is not already -** active. -** If P2 is non-zero, then a write-transaction is started, or if a -** read-transaction is already active, it is upgraded to a write-transaction. -** If P2 is zero, then a read-transaction is started. -** -** P1 is the index of the database file on which the transaction is -** started. Index 0 is the main database file and index 1 is the -** file used for temporary tables. Indices of 2 or more are used for -** attached databases. -** -** If a write-transaction is started and the Vdbe.usesStmtJournal flag is -** true (this flag is set if the Vdbe may modify more than one row and may -** throw an ABORT exception), a statement transaction may also be opened. -** More specifically, a statement transaction is opened iff the database -** connection is currently not in autocommit mode, or if there are other -** active statements. A statement transaction allows the changes made by this -** VDBE to be rolled back after an error without having to roll back the -** entire transaction. If no error is encountered, the statement transaction -** will automatically commit when the VDBE halts. -** -** If P5!=0 then this opcode also checks the schema cookie against P3 -** and the schema generation counter against P4. -** The cookie changes its value whenever the database schema changes. -** This operation is used to detect when that the cookie has changed -** and that the current process needs to reread the schema. If the schema -** cookie in P3 differs from the schema cookie in the database header or -** if the schema generation counter in P4 differs from the current -** generation counter, then an SQLITE_SCHEMA error is raised and execution -** halts. The sqlite3_step() wrapper function might then reprepare the -** statement and rerun it from the beginning. -*/ -case OP_Transaction: { - Btree *pBt; - int iMeta = 0; - - assert( p->bIsReader ); - assert( p->readOnly==0 || pOp->p2==0 ); - assert( pOp->p1>=0 && pOp->p1nDb ); - assert( DbMaskTest(p->btreeMask, pOp->p1) ); - if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){ - rc = SQLITE_READONLY; - goto abort_due_to_error; - } - pBt = db->aDb[pOp->p1].pBt; - - if( pBt ){ - rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta); - testcase( rc==SQLITE_BUSY_SNAPSHOT ); - testcase( rc==SQLITE_BUSY_RECOVERY ); - if( rc!=SQLITE_OK ){ - if( (rc&0xff)==SQLITE_BUSY ){ - p->pc = (int)(pOp - aOp); - p->rc = rc; - goto vdbe_return; - } - goto abort_due_to_error; - } - - if( p->usesStmtJournal - && pOp->p2 - && (db->autoCommit==0 || db->nVdbeRead>1) - ){ - assert( sqlite3BtreeIsInTrans(pBt) ); - if( p->iStatement==0 ){ - assert( db->nStatement>=0 && db->nSavepoint>=0 ); - db->nStatement++; - p->iStatement = db->nSavepoint + db->nStatement; - } - - rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1); - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeBeginStmt(pBt, p->iStatement); - } - - /* Store the current value of the database handles deferred constraint - ** counter. If the statement transaction needs to be rolled back, - ** the value of this counter needs to be restored too. */ - p->nStmtDefCons = db->nDeferredCons; - p->nStmtDefImmCons = db->nDeferredImmCons; - } - } - assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); - if( pOp->p5 - && (iMeta!=pOp->p3 - || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i) - ){ - /* - ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema - ** version is checked to ensure that the schema has not changed since the - ** SQL statement was prepared. - */ - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed"); - /* If the schema-cookie from the database file matches the cookie - ** stored with the in-memory representation of the schema, do - ** not reload the schema from the database file. - ** - ** If virtual-tables are in use, this is not just an optimization. - ** Often, v-tables store their data in other SQLite tables, which - ** are queried from within xNext() and other v-table methods using - ** prepared queries. If such a query is out-of-date, we do not want to - ** discard the database schema, as the user code implementing the - ** v-table would have to be ready for the sqlite3_vtab structure itself - ** to be invalidated whenever sqlite3_step() is called from within - ** a v-table method. - */ - if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){ - sqlite3ResetOneSchema(db, pOp->p1); - } - p->expired = 1; - rc = SQLITE_SCHEMA; - } - if( rc ) goto abort_due_to_error; - break; -} - -/* Opcode: ReadCookie P1 P2 P3 * * -** -** Read cookie number P3 from database P1 and write it into register P2. -** P3==1 is the schema version. P3==2 is the database format. -** P3==3 is the recommended pager cache size, and so forth. P1==0 is -** the main database file and P1==1 is the database file used to store -** temporary tables. -** -** There must be a read-lock on the database (either a transaction -** must be started or there must be an open cursor) before -** executing this instruction. -*/ -case OP_ReadCookie: { /* out2 */ - int iMeta; - int iDb; - int iCookie; - - assert( p->bIsReader ); - iDb = pOp->p1; - iCookie = pOp->p3; - assert( pOp->p3=0 && iDbnDb ); - assert( db->aDb[iDb].pBt!=0 ); - assert( DbMaskTest(p->btreeMask, iDb) ); - - sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta); - pOut = out2Prerelease(p, pOp); - pOut->u.i = iMeta; - break; -} - -/* Opcode: SetCookie P1 P2 P3 * P5 -** -** Write the integer value P3 into cookie number P2 of database P1. -** P2==1 is the schema version. P2==2 is the database format. -** P2==3 is the recommended pager cache -** size, and so forth. P1==0 is the main database file and P1==1 is the -** database file used to store temporary tables. -** -** A transaction must be started before executing this opcode. -** -** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal -** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement -** has P5 set to 1, so that the internal schema version will be different -** from the database schema version, resulting in a schema reset. -*/ -case OP_SetCookie: { - Db *pDb; - - sqlite3VdbeIncrWriteCounter(p, 0); - assert( pOp->p2p1>=0 && pOp->p1nDb ); - assert( DbMaskTest(p->btreeMask, pOp->p1) ); - assert( p->readOnly==0 ); - pDb = &db->aDb[pOp->p1]; - assert( pDb->pBt!=0 ); - assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) ); - /* See note about index shifting on OP_ReadCookie */ - rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3); - if( pOp->p2==BTREE_SCHEMA_VERSION ){ - /* When the schema cookie changes, record the new cookie internally */ - pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5; - db->mDbFlags |= DBFLAG_SchemaChange; - }else if( pOp->p2==BTREE_FILE_FORMAT ){ - /* Record changes in the file format */ - pDb->pSchema->file_format = pOp->p3; - } - if( pOp->p1==1 ){ - /* Invalidate all prepared statements whenever the TEMP database - ** schema is changed. Ticket #1644 */ - sqlite3ExpirePreparedStatements(db, 0); - p->expired = 0; - } - if( rc ) goto abort_due_to_error; - break; -} - -/* Opcode: OpenRead P1 P2 P3 P4 P5 -** Synopsis: root=P2 iDb=P3 -** -** Open a read-only cursor for the database table whose root page is -** P2 in a database file. The database file is determined by P3. -** P3==0 means the main database, P3==1 means the database used for -** temporary tables, and P3>1 means used the corresponding attached -** database. Give the new cursor an identifier of P1. The P1 -** values need not be contiguous but all P1 values should be small integers. -** It is an error for P1 to be negative. -** -** Allowed P5 bits: -**
      -**
    • 0x02 OPFLAG_SEEKEQ: This cursor will only be used for -** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT -** of OP_SeekLE/OP_IdxLT) -**
    -** -** The P4 value may be either an integer (P4_INT32) or a pointer to -** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo -** object, then table being opened must be an [index b-tree] where the -** KeyInfo object defines the content and collating -** sequence of that index b-tree. Otherwise, if P4 is an integer -** value, then the table being opened must be a [table b-tree] with a -** number of columns no less than the value of P4. -** -** See also: OpenWrite, ReopenIdx -*/ -/* Opcode: ReopenIdx P1 P2 P3 P4 P5 -** Synopsis: root=P2 iDb=P3 -** -** The ReopenIdx opcode works like OP_OpenRead except that it first -** checks to see if the cursor on P1 is already open on the same -** b-tree and if it is this opcode becomes a no-op. In other words, -** if the cursor is already open, do not reopen it. -** -** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ -** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must -** be the same as every other ReopenIdx or OpenRead for the same cursor -** number. -** -** Allowed P5 bits: -**
      -**
    • 0x02 OPFLAG_SEEKEQ: This cursor will only be used for -** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT -** of OP_SeekLE/OP_IdxLT) -**
    -** -** See also: OP_OpenRead, OP_OpenWrite -*/ -/* Opcode: OpenWrite P1 P2 P3 P4 P5 -** Synopsis: root=P2 iDb=P3 -** -** Open a read/write cursor named P1 on the table or index whose root -** page is P2 (or whose root page is held in register P2 if the -** OPFLAG_P2ISREG bit is set in P5 - see below). -** -** The P4 value may be either an integer (P4_INT32) or a pointer to -** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo -** object, then table being opened must be an [index b-tree] where the -** KeyInfo object defines the content and collating -** sequence of that index b-tree. Otherwise, if P4 is an integer -** value, then the table being opened must be a [table b-tree] with a -** number of columns no less than the value of P4. -** -** Allowed P5 bits: -**
      -**
    • 0x02 OPFLAG_SEEKEQ: This cursor will only be used for -** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT -** of OP_SeekLE/OP_IdxLT) -**
    • 0x08 OPFLAG_FORDELETE: This cursor is used only to seek -** and subsequently delete entries in an index btree. This is a -** hint to the storage engine that the storage engine is allowed to -** ignore. The hint is not used by the official SQLite b*tree storage -** engine, but is used by COMDB2. -**
    • 0x10 OPFLAG_P2ISREG: Use the content of register P2 -** as the root page, not the value of P2 itself. -**
    -** -** This instruction works like OpenRead except that it opens the cursor -** in read/write mode. -** -** See also: OP_OpenRead, OP_ReopenIdx -*/ -case OP_ReopenIdx: { - int nField; - KeyInfo *pKeyInfo; - u32 p2; - int iDb; - int wrFlag; - Btree *pX; - VdbeCursor *pCur; - Db *pDb; - - assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); - assert( pOp->p4type==P4_KEYINFO ); - pCur = p->apCsr[pOp->p1]; - if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){ - assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */ - goto open_cursor_set_hints; - } - /* If the cursor is not currently open or is open on a different - ** index, then fall through into OP_OpenRead to force a reopen */ -case OP_OpenRead: -case OP_OpenWrite: - - assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ ); - assert( p->bIsReader ); - assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx - || p->readOnly==0 ); - - if( p->expired==1 ){ - rc = SQLITE_ABORT_ROLLBACK; - goto abort_due_to_error; - } - - nField = 0; - pKeyInfo = 0; - p2 = (u32)pOp->p2; - iDb = pOp->p3; - assert( iDb>=0 && iDbnDb ); - assert( DbMaskTest(p->btreeMask, iDb) ); - pDb = &db->aDb[iDb]; - pX = pDb->pBt; - assert( pX!=0 ); - if( pOp->opcode==OP_OpenWrite ){ - assert( OPFLAG_FORDELETE==BTREE_FORDELETE ); - wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( pDb->pSchema->file_format < p->minWriteFileFormat ){ - p->minWriteFileFormat = pDb->pSchema->file_format; - } - }else{ - wrFlag = 0; - } - if( pOp->p5 & OPFLAG_P2ISREG ){ - assert( p2>0 ); - assert( p2<=(u32)(p->nMem+1 - p->nCursor) ); - assert( pOp->opcode==OP_OpenWrite ); - pIn2 = &aMem[p2]; - assert( memIsValid(pIn2) ); - assert( (pIn2->flags & MEM_Int)!=0 ); - sqlite3VdbeMemIntegerify(pIn2); - p2 = (int)pIn2->u.i; - /* The p2 value always comes from a prior OP_CreateBtree opcode and - ** that opcode will always set the p2 value to 2 or more or else fail. - ** If there were a failure, the prepared statement would have halted - ** before reaching this instruction. */ - assert( p2>=2 ); - } - if( pOp->p4type==P4_KEYINFO ){ - pKeyInfo = pOp->p4.pKeyInfo; - assert( pKeyInfo->enc==ENC(db) ); - assert( pKeyInfo->db==db ); - nField = pKeyInfo->nAllField; - }else if( pOp->p4type==P4_INT32 ){ - nField = pOp->p4.i; - } - assert( pOp->p1>=0 ); - assert( nField>=0 ); - testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */ - pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE); - if( pCur==0 ) goto no_mem; - pCur->nullRow = 1; - pCur->isOrdered = 1; - pCur->pgnoRoot = p2; -#ifdef SQLITE_DEBUG - pCur->wrFlag = wrFlag; -#endif - rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor); - pCur->pKeyInfo = pKeyInfo; - /* Set the VdbeCursor.isTable variable. Previous versions of - ** SQLite used to check if the root-page flags were sane at this point - ** and report database corruption if they were not, but this check has - ** since moved into the btree layer. */ - pCur->isTable = pOp->p4type!=P4_KEYINFO; - -open_cursor_set_hints: - assert( OPFLAG_BULKCSR==BTREE_BULKLOAD ); - assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ ); - testcase( pOp->p5 & OPFLAG_BULKCSR ); - testcase( pOp->p2 & OPFLAG_SEEKEQ ); - sqlite3BtreeCursorHintFlags(pCur->uc.pCursor, - (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ))); - if( rc ) goto abort_due_to_error; - break; -} - -/* Opcode: OpenDup P1 P2 * * * -** -** Open a new cursor P1 that points to the same ephemeral table as -** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral -** opcode. Only ephemeral cursors may be duplicated. -** -** Duplicate ephemeral cursors are used for self-joins of materialized views. -*/ -case OP_OpenDup: { - VdbeCursor *pOrig; /* The original cursor to be duplicated */ - VdbeCursor *pCx; /* The new cursor */ - - pOrig = p->apCsr[pOp->p2]; - assert( pOrig ); - assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */ - - pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE); - if( pCx==0 ) goto no_mem; - pCx->nullRow = 1; - pCx->isEphemeral = 1; - pCx->pKeyInfo = pOrig->pKeyInfo; - pCx->isTable = pOrig->isTable; - pCx->pgnoRoot = pOrig->pgnoRoot; - pCx->isOrdered = pOrig->isOrdered; - rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR, - pCx->pKeyInfo, pCx->uc.pCursor); - /* The sqlite3BtreeCursor() routine can only fail for the first cursor - ** opened for a database. Since there is already an open cursor when this - ** opcode is run, the sqlite3BtreeCursor() cannot fail */ - assert( rc==SQLITE_OK ); - break; -} - - -/* Opcode: OpenEphemeral P1 P2 * P4 P5 -** Synopsis: nColumn=P2 -** -** Open a new cursor P1 to a transient table. -** The cursor is always opened read/write even if -** the main database is read-only. The ephemeral -** table is deleted automatically when the cursor is closed. -** -** If the cursor P1 is already opened on an ephemeral table, the table -** is cleared (all content is erased). -** -** P2 is the number of columns in the ephemeral table. -** The cursor points to a BTree table if P4==0 and to a BTree index -** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure -** that defines the format of keys in the index. -** -** The P5 parameter can be a mask of the BTREE_* flags defined -** in btree.h. These flags control aspects of the operation of -** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are -** added automatically. -*/ -/* Opcode: OpenAutoindex P1 P2 * P4 * -** Synopsis: nColumn=P2 -** -** This opcode works the same as OP_OpenEphemeral. It has a -** different name to distinguish its use. Tables created using -** by this opcode will be used for automatically created transient -** indices in joins. -*/ -case OP_OpenAutoindex: -case OP_OpenEphemeral: { - VdbeCursor *pCx; - KeyInfo *pKeyInfo; - - static const int vfsFlags = - SQLITE_OPEN_READWRITE | - SQLITE_OPEN_CREATE | - SQLITE_OPEN_EXCLUSIVE | - SQLITE_OPEN_DELETEONCLOSE | - SQLITE_OPEN_TRANSIENT_DB; - assert( pOp->p1>=0 ); - assert( pOp->p2>=0 ); - pCx = p->apCsr[pOp->p1]; - if( pCx && pCx->pBtx ){ - /* If the ephermeral table is already open, erase all existing content - ** so that the table is empty again, rather than creating a new table. */ - assert( pCx->isEphemeral ); - pCx->seqCount = 0; - pCx->cacheStatus = CACHE_STALE; - rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0); - }else{ - pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); - if( pCx==0 ) goto no_mem; - pCx->isEphemeral = 1; - rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, - BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, - vfsFlags); - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0); - } - if( rc==SQLITE_OK ){ - /* If a transient index is required, create it by calling - ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before - ** opening it. If a transient table is required, just use the - ** automatically created table with root-page 1 (an BLOB_INTKEY table). - */ - if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){ - assert( pOp->p4type==P4_KEYINFO ); - rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot, - BTREE_BLOBKEY | pOp->p5); - if( rc==SQLITE_OK ){ - assert( pCx->pgnoRoot==SCHEMA_ROOT+1 ); - assert( pKeyInfo->db==db ); - assert( pKeyInfo->enc==ENC(db) ); - rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR, - pKeyInfo, pCx->uc.pCursor); - } - pCx->isTable = 0; - }else{ - pCx->pgnoRoot = SCHEMA_ROOT; - rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR, - 0, pCx->uc.pCursor); - pCx->isTable = 1; - } - } - pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); - } - if( rc ) goto abort_due_to_error; - pCx->nullRow = 1; - break; -} - -/* Opcode: SorterOpen P1 P2 P3 P4 * -** -** This opcode works like OP_OpenEphemeral except that it opens -** a transient index that is specifically designed to sort large -** tables using an external merge-sort algorithm. -** -** If argument P3 is non-zero, then it indicates that the sorter may -** assume that a stable sort considering the first P3 fields of each -** key is sufficient to produce the required results. -*/ -case OP_SorterOpen: { - VdbeCursor *pCx; - - assert( pOp->p1>=0 ); - assert( pOp->p2>=0 ); - pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER); - if( pCx==0 ) goto no_mem; - pCx->pKeyInfo = pOp->p4.pKeyInfo; - assert( pCx->pKeyInfo->db==db ); - assert( pCx->pKeyInfo->enc==ENC(db) ); - rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx); - if( rc ) goto abort_due_to_error; - break; -} - -/* Opcode: SequenceTest P1 P2 * * * -** Synopsis: if( cursor[P1].ctr++ ) pc = P2 -** -** P1 is a sorter cursor. If the sequence counter is currently zero, jump -** to P2. Regardless of whether or not the jump is taken, increment the -** the sequence value. -*/ -case OP_SequenceTest: { - VdbeCursor *pC; - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( isSorter(pC) ); - if( (pC->seqCount++)==0 ){ - goto jump_to_p2; - } - break; -} - -/* Opcode: OpenPseudo P1 P2 P3 * * -** Synopsis: P3 columns in r[P2] -** -** Open a new cursor that points to a fake table that contains a single -** row of data. The content of that one row is the content of memory -** register P2. In other words, cursor P1 becomes an alias for the -** MEM_Blob content contained in register P2. -** -** A pseudo-table created by this opcode is used to hold a single -** row output from the sorter so that the row can be decomposed into -** individual columns using the OP_Column opcode. The OP_Column opcode -** is the only cursor opcode that works with a pseudo-table. -** -** P3 is the number of fields in the records that will be stored by -** the pseudo-table. -*/ -case OP_OpenPseudo: { - VdbeCursor *pCx; - - assert( pOp->p1>=0 ); - assert( pOp->p3>=0 ); - pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO); - if( pCx==0 ) goto no_mem; - pCx->nullRow = 1; - pCx->seekResult = pOp->p2; - pCx->isTable = 1; - /* Give this pseudo-cursor a fake BtCursor pointer so that pCx - ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test - ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto() - ** which is a performance optimization */ - pCx->uc.pCursor = sqlite3BtreeFakeValidCursor(); - assert( pOp->p5==0 ); - break; -} - -/* Opcode: Close P1 * * * * -** -** Close a cursor previously opened as P1. If P1 is not -** currently open, this instruction is a no-op. -*/ -case OP_Close: { - assert( pOp->p1>=0 && pOp->p1nCursor ); - sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]); - p->apCsr[pOp->p1] = 0; - break; -} - -#ifdef SQLITE_ENABLE_COLUMN_USED_MASK -/* Opcode: ColumnsUsed P1 * * P4 * -** -** This opcode (which only exists if SQLite was compiled with -** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the -** table or index for cursor P1 are used. P4 is a 64-bit integer -** (P4_INT64) in which the first 63 bits are one for each of the -** first 63 columns of the table or index that are actually used -** by the cursor. The high-order bit is set if any column after -** the 64th is used. -*/ -case OP_ColumnsUsed: { - VdbeCursor *pC; - pC = p->apCsr[pOp->p1]; - assert( pC->eCurType==CURTYPE_BTREE ); - pC->maskUsed = *(u64*)pOp->p4.pI64; - break; -} -#endif - -/* Opcode: SeekGE P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), -** use the value in register P3 as the key. If cursor P1 refers -** to an SQL index, then P3 is the first in an array of P4 registers -** that are used as an unpacked index key. -** -** Reposition cursor P1 so that it points to the smallest entry that -** is greater than or equal to the key value. If there are no records -** greater than or equal to the key and P2 is not zero, then jump to P2. -** -** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this -** opcode will either land on a record that exactly matches the key, or -** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ, -** this opcode must be followed by an IdxLE opcode with the same arguments. -** The IdxGT opcode will be skipped if this opcode succeeds, but the -** IdxGT opcode will be used on subsequent loop iterations. The -** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this -** is an equality search. -** -** This opcode leaves the cursor configured to move in forward order, -** from the beginning toward the end. In other words, the cursor is -** configured to use Next, not Prev. -** -** See also: Found, NotFound, SeekLt, SeekGt, SeekLe -*/ -/* Opcode: SeekGT P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), -** use the value in register P3 as a key. If cursor P1 refers -** to an SQL index, then P3 is the first in an array of P4 registers -** that are used as an unpacked index key. -** -** Reposition cursor P1 so that it points to the smallest entry that -** is greater than the key value. If there are no records greater than -** the key and P2 is not zero, then jump to P2. -** -** This opcode leaves the cursor configured to move in forward order, -** from the beginning toward the end. In other words, the cursor is -** configured to use Next, not Prev. -** -** See also: Found, NotFound, SeekLt, SeekGe, SeekLe -*/ -/* Opcode: SeekLT P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), -** use the value in register P3 as a key. If cursor P1 refers -** to an SQL index, then P3 is the first in an array of P4 registers -** that are used as an unpacked index key. -** -** Reposition cursor P1 so that it points to the largest entry that -** is less than the key value. If there are no records less than -** the key and P2 is not zero, then jump to P2. -** -** This opcode leaves the cursor configured to move in reverse order, -** from the end toward the beginning. In other words, the cursor is -** configured to use Prev, not Next. -** -** See also: Found, NotFound, SeekGt, SeekGe, SeekLe -*/ -/* Opcode: SeekLE P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), -** use the value in register P3 as a key. If cursor P1 refers -** to an SQL index, then P3 is the first in an array of P4 registers -** that are used as an unpacked index key. -** -** Reposition cursor P1 so that it points to the largest entry that -** is less than or equal to the key value. If there are no records -** less than or equal to the key and P2 is not zero, then jump to P2. -** -** This opcode leaves the cursor configured to move in reverse order, -** from the end toward the beginning. In other words, the cursor is -** configured to use Prev, not Next. -** -** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this -** opcode will either land on a record that exactly matches the key, or -** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ, -** this opcode must be followed by an IdxLE opcode with the same arguments. -** The IdxGE opcode will be skipped if this opcode succeeds, but the -** IdxGE opcode will be used on subsequent loop iterations. The -** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this -** is an equality search. -** -** See also: Found, NotFound, SeekGt, SeekGe, SeekLt -*/ -case OP_SeekLT: /* jump, in3, group */ -case OP_SeekLE: /* jump, in3, group */ -case OP_SeekGE: /* jump, in3, group */ -case OP_SeekGT: { /* jump, in3, group */ - int res; /* Comparison result */ - int oc; /* Opcode */ - VdbeCursor *pC; /* The cursor to seek */ - UnpackedRecord r; /* The key to seek for */ - int nField; /* Number of columns or fields in the key */ - i64 iKey; /* The rowid we are to seek to */ - int eqOnly; /* Only interested in == results */ - - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( pOp->p2!=0 ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( OP_SeekLE == OP_SeekLT+1 ); - assert( OP_SeekGE == OP_SeekLT+2 ); - assert( OP_SeekGT == OP_SeekLT+3 ); - assert( pC->isOrdered ); - assert( pC->uc.pCursor!=0 ); - oc = pOp->opcode; - eqOnly = 0; - pC->nullRow = 0; -#ifdef SQLITE_DEBUG - pC->seekOp = pOp->opcode; -#endif - - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - if( pC->isTable ){ - u16 flags3, newType; - /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */ - assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 - || CORRUPT_DB ); - - /* The input value in P3 might be of any type: integer, real, string, - ** blob, or NULL. But it needs to be an integer before we can do - ** the seek, so convert it. */ - pIn3 = &aMem[pOp->p3]; - flags3 = pIn3->flags; - if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){ - applyNumericAffinity(pIn3, 0); - } - iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */ - newType = pIn3->flags; /* Record the type after applying numeric affinity */ - pIn3->flags = flags3; /* But convert the type back to its original */ - - /* If the P3 value could not be converted into an integer without - ** loss of information, then special processing is required... */ - if( (newType & (MEM_Int|MEM_IntReal))==0 ){ - if( (newType & MEM_Real)==0 ){ - if( (newType & MEM_Null) || oc>=OP_SeekGE ){ - VdbeBranchTaken(1,2); - goto jump_to_p2; - }else{ - rc = sqlite3BtreeLast(pC->uc.pCursor, &res); - if( rc!=SQLITE_OK ) goto abort_due_to_error; - goto seek_not_found; - } - }else - - /* If the approximation iKey is larger than the actual real search - ** term, substitute >= for > and < for <=. e.g. if the search term - ** is 4.9 and the integer approximation 5: - ** - ** (x > 4.9) -> (x >= 5) - ** (x <= 4.9) -> (x < 5) - */ - if( pIn3->u.r<(double)iKey ){ - assert( OP_SeekGE==(OP_SeekGT-1) ); - assert( OP_SeekLT==(OP_SeekLE-1) ); - assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) ); - if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--; - } - - /* If the approximation iKey is smaller than the actual real search - ** term, substitute <= for < and > for >=. */ - else if( pIn3->u.r>(double)iKey ){ - assert( OP_SeekLE==(OP_SeekLT+1) ); - assert( OP_SeekGT==(OP_SeekGE+1) ); - assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) ); - if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++; - } - } - rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res); - pC->movetoTarget = iKey; /* Used by OP_Delete */ - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - }else{ - /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the - ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be - ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively, - ** with the same key. - */ - if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){ - eqOnly = 1; - assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE ); - assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); - assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT ); - assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT ); - assert( pOp[1].p1==pOp[0].p1 ); - assert( pOp[1].p2==pOp[0].p2 ); - assert( pOp[1].p3==pOp[0].p3 ); - assert( pOp[1].p4.i==pOp[0].p4.i ); - } - - nField = pOp->p4.i; - assert( pOp->p4type==P4_INT32 ); - assert( nField>0 ); - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)nField; - - /* The next line of code computes as follows, only faster: - ** if( oc==OP_SeekGT || oc==OP_SeekLE ){ - ** r.default_rc = -1; - ** }else{ - ** r.default_rc = +1; - ** } - */ - r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1); - assert( oc!=OP_SeekGT || r.default_rc==-1 ); - assert( oc!=OP_SeekLE || r.default_rc==-1 ); - assert( oc!=OP_SeekGE || r.default_rc==+1 ); - assert( oc!=OP_SeekLT || r.default_rc==+1 ); - - r.aMem = &aMem[pOp->p3]; -#ifdef SQLITE_DEBUG - { int i; for(i=0; iuc.pCursor, &r, 0, 0, &res); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - if( eqOnly && r.eqSeen==0 ){ - assert( res!=0 ); - goto seek_not_found; - } - } -#ifdef SQLITE_TEST - sqlite3_search_count++; -#endif - if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT ); - if( res<0 || (res==0 && oc==OP_SeekGT) ){ - res = 0; - rc = sqlite3BtreeNext(pC->uc.pCursor, 0); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_DONE ){ - rc = SQLITE_OK; - res = 1; - }else{ - goto abort_due_to_error; - } - } - }else{ - res = 0; - } - }else{ - assert( oc==OP_SeekLT || oc==OP_SeekLE ); - if( res>0 || (res==0 && oc==OP_SeekLT) ){ - res = 0; - rc = sqlite3BtreePrevious(pC->uc.pCursor, 0); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_DONE ){ - rc = SQLITE_OK; - res = 1; - }else{ - goto abort_due_to_error; - } - } - }else{ - /* res might be negative because the table is empty. Check to - ** see if this is the case. - */ - res = sqlite3BtreeEof(pC->uc.pCursor); - } - } -seek_not_found: - assert( pOp->p2>0 ); - VdbeBranchTaken(res!=0,2); - if( res ){ - goto jump_to_p2; - }else if( eqOnly ){ - assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT ); - pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */ - } - break; -} - -/* Opcode: SeekHit P1 P2 * * * -** Synopsis: seekHit=P2 -** -** Set the seekHit flag on cursor P1 to the value in P2. -** The seekHit flag is used by the IfNoHope opcode. -** -** P1 must be a valid b-tree cursor. P2 must be a boolean value, -** either 0 or 1. -*/ -case OP_SeekHit: { - VdbeCursor *pC; - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pOp->p2==0 || pOp->p2==1 ); - pC->seekHit = pOp->p2 & 1; - break; -} - -/* Opcode: IfNotOpen P1 P2 * * * -** Synopsis: if( !csr[P1] ) goto P2 -** -** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through. -*/ -case OP_IfNotOpen: { /* jump */ - assert( pOp->p1>=0 && pOp->p1nCursor ); - VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2); - if( !p->apCsr[pOp->p1] ){ - goto jump_to_p2_and_check_for_interrupt; - } - break; -} - -/* Opcode: Found P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** If P4==0 then register P3 holds a blob constructed by MakeRecord. If -** P4>0 then register P3 is the first of P4 registers that form an unpacked -** record. -** -** Cursor P1 is on an index btree. If the record identified by P3 and P4 -** is a prefix of any entry in P1 then a jump is made to P2 and -** P1 is left pointing at the matching entry. -** -** This operation leaves the cursor in a state where it can be -** advanced in the forward direction. The Next instruction will work, -** but not the Prev instruction. -** -** See also: NotFound, NoConflict, NotExists. SeekGe -*/ -/* Opcode: NotFound P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** If P4==0 then register P3 holds a blob constructed by MakeRecord. If -** P4>0 then register P3 is the first of P4 registers that form an unpacked -** record. -** -** Cursor P1 is on an index btree. If the record identified by P3 and P4 -** is not the prefix of any entry in P1 then a jump is made to P2. If P1 -** does contain an entry whose prefix matches the P3/P4 record then control -** falls through to the next instruction and P1 is left pointing at the -** matching entry. -** -** This operation leaves the cursor in a state where it cannot be -** advanced in either direction. In other words, the Next and Prev -** opcodes do not work after this operation. -** -** See also: Found, NotExists, NoConflict, IfNoHope -*/ -/* Opcode: IfNoHope P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** Register P3 is the first of P4 registers that form an unpacked -** record. -** -** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then -** this opcode is a no-op. But if the seekHit flag of P1 is clear, then -** check to see if there is any entry in P1 that matches the -** prefix identified by P3 and P4. If no entry matches the prefix, -** jump to P2. Otherwise fall through. -** -** This opcode behaves like OP_NotFound if the seekHit -** flag is clear and it behaves like OP_Noop if the seekHit flag is set. -** -** This opcode is used in IN clause processing for a multi-column key. -** If an IN clause is attached to an element of the key other than the -** left-most element, and if there are no matches on the most recent -** seek over the whole key, then it might be that one of the key element -** to the left is prohibiting a match, and hence there is "no hope" of -** any match regardless of how many IN clause elements are checked. -** In such a case, we abandon the IN clause search early, using this -** opcode. The opcode name comes from the fact that the -** jump is taken if there is "no hope" of achieving a match. -** -** See also: NotFound, SeekHit -*/ -/* Opcode: NoConflict P1 P2 P3 P4 * -** Synopsis: key=r[P3@P4] -** -** If P4==0 then register P3 holds a blob constructed by MakeRecord. If -** P4>0 then register P3 is the first of P4 registers that form an unpacked -** record. -** -** Cursor P1 is on an index btree. If the record identified by P3 and P4 -** contains any NULL value, jump immediately to P2. If all terms of the -** record are not-NULL then a check is done to determine if any row in the -** P1 index btree has a matching key prefix. If there are no matches, jump -** immediately to P2. If there is a match, fall through and leave the P1 -** cursor pointing to the matching row. -** -** This opcode is similar to OP_NotFound with the exceptions that the -** branch is always taken if any part of the search key input is NULL. -** -** This operation leaves the cursor in a state where it cannot be -** advanced in either direction. In other words, the Next and Prev -** opcodes do not work after this operation. -** -** See also: NotFound, Found, NotExists -*/ -case OP_IfNoHope: { /* jump, in3 */ - VdbeCursor *pC; - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - if( pC->seekHit ) break; - /* Fall through into OP_NotFound */ - /* no break */ deliberate_fall_through -} -case OP_NoConflict: /* jump, in3 */ -case OP_NotFound: /* jump, in3 */ -case OP_Found: { /* jump, in3 */ - int alreadyExists; - int takeJump; - int ii; - VdbeCursor *pC; - int res; - UnpackedRecord *pFree; - UnpackedRecord *pIdxKey; - UnpackedRecord r; - -#ifdef SQLITE_TEST - if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++; -#endif - - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( pOp->p4type==P4_INT32 ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); -#ifdef SQLITE_DEBUG - pC->seekOp = pOp->opcode; -#endif - pIn3 = &aMem[pOp->p3]; - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->uc.pCursor!=0 ); - assert( pC->isTable==0 ); - if( pOp->p4.i>0 ){ - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)pOp->p4.i; - r.aMem = pIn3; -#ifdef SQLITE_DEBUG - for(ii=0; iip3+ii, &r.aMem[ii]); - } -#endif - pIdxKey = &r; - pFree = 0; - }else{ - assert( pIn3->flags & MEM_Blob ); - rc = ExpandBlob(pIn3); - assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); - if( rc ) goto no_mem; - pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo); - if( pIdxKey==0 ) goto no_mem; - sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey); - } - pIdxKey->default_rc = 0; - takeJump = 0; - if( pOp->opcode==OP_NoConflict ){ - /* For the OP_NoConflict opcode, take the jump if any of the - ** input fields are NULL, since any key with a NULL will not - ** conflict */ - for(ii=0; iinField; ii++){ - if( pIdxKey->aMem[ii].flags & MEM_Null ){ - takeJump = 1; - break; - } - } - } - rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res); - if( pFree ) sqlite3DbFreeNN(db, pFree); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - pC->seekResult = res; - alreadyExists = (res==0); - pC->nullRow = 1-alreadyExists; - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - if( pOp->opcode==OP_Found ){ - VdbeBranchTaken(alreadyExists!=0,2); - if( alreadyExists ) goto jump_to_p2; - }else{ - VdbeBranchTaken(takeJump||alreadyExists==0,2); - if( takeJump || !alreadyExists ) goto jump_to_p2; - } - break; -} - -/* Opcode: SeekRowid P1 P2 P3 * * -** Synopsis: intkey=r[P3] -** -** P1 is the index of a cursor open on an SQL table btree (with integer -** keys). If register P3 does not contain an integer or if P1 does not -** contain a record with rowid P3 then jump immediately to P2. -** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain -** a record with rowid P3 then -** leave the cursor pointing at that record and fall through to the next -** instruction. -** -** The OP_NotExists opcode performs the same operation, but with OP_NotExists -** the P3 register must be guaranteed to contain an integer value. With this -** opcode, register P3 might not contain an integer. -** -** The OP_NotFound opcode performs the same operation on index btrees -** (with arbitrary multi-value keys). -** -** This opcode leaves the cursor in a state where it cannot be advanced -** in either direction. In other words, the Next and Prev opcodes will -** not work following this opcode. -** -** See also: Found, NotFound, NoConflict, SeekRowid -*/ -/* Opcode: NotExists P1 P2 P3 * * -** Synopsis: intkey=r[P3] -** -** P1 is the index of a cursor open on an SQL table btree (with integer -** keys). P3 is an integer rowid. If P1 does not contain a record with -** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an -** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then -** leave the cursor pointing at that record and fall through to the next -** instruction. -** -** The OP_SeekRowid opcode performs the same operation but also allows the -** P3 register to contain a non-integer value, in which case the jump is -** always taken. This opcode requires that P3 always contain an integer. -** -** The OP_NotFound opcode performs the same operation on index btrees -** (with arbitrary multi-value keys). -** -** This opcode leaves the cursor in a state where it cannot be advanced -** in either direction. In other words, the Next and Prev opcodes will -** not work following this opcode. -** -** See also: Found, NotFound, NoConflict, SeekRowid -*/ -case OP_SeekRowid: { /* jump, in3 */ - VdbeCursor *pC; - BtCursor *pCrsr; - int res; - u64 iKey; - - pIn3 = &aMem[pOp->p3]; - testcase( pIn3->flags & MEM_Int ); - testcase( pIn3->flags & MEM_IntReal ); - testcase( pIn3->flags & MEM_Real ); - testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str ); - if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){ - /* If pIn3->u.i does not contain an integer, compute iKey as the - ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted - ** into an integer without loss of information. Take care to avoid - ** changing the datatype of pIn3, however, as it is used by other - ** parts of the prepared statement. */ - Mem x = pIn3[0]; - applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding); - if( (x.flags & MEM_Int)==0 ) goto jump_to_p2; - iKey = x.u.i; - goto notExistsWithKey; - } - /* Fall through into OP_NotExists */ - /* no break */ deliberate_fall_through -case OP_NotExists: /* jump, in3 */ - pIn3 = &aMem[pOp->p3]; - assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid ); - assert( pOp->p1>=0 && pOp->p1nCursor ); - iKey = pIn3->u.i; -notExistsWithKey: - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); -#ifdef SQLITE_DEBUG - if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid; -#endif - assert( pC->isTable ); - assert( pC->eCurType==CURTYPE_BTREE ); - pCrsr = pC->uc.pCursor; - assert( pCrsr!=0 ); - res = 0; - rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res); - assert( rc==SQLITE_OK || res==0 ); - pC->movetoTarget = iKey; /* Used by OP_Delete */ - pC->nullRow = 0; - pC->cacheStatus = CACHE_STALE; - pC->deferredMoveto = 0; - VdbeBranchTaken(res!=0,2); - pC->seekResult = res; - if( res!=0 ){ - assert( rc==SQLITE_OK ); - if( pOp->p2==0 ){ - rc = SQLITE_CORRUPT_BKPT; - }else{ - goto jump_to_p2; - } - } - if( rc ) goto abort_due_to_error; - break; -} - -/* Opcode: Sequence P1 P2 * * * -** Synopsis: r[P2]=cursor[P1].ctr++ -** -** Find the next available sequence number for cursor P1. -** Write the sequence number into register P2. -** The sequence number on the cursor is incremented after this -** instruction. -*/ -case OP_Sequence: { /* out2 */ - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( p->apCsr[pOp->p1]!=0 ); - assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB ); - pOut = out2Prerelease(p, pOp); - pOut->u.i = p->apCsr[pOp->p1]->seqCount++; - break; -} - - -/* Opcode: NewRowid P1 P2 P3 * * -** Synopsis: r[P2]=rowid -** -** Get a new integer record number (a.k.a "rowid") used as the key to a table. -** The record number is not previously used as a key in the database -** table that cursor P1 points to. The new record number is written -** written to register P2. -** -** If P3>0 then P3 is a register in the root frame of this VDBE that holds -** the largest previously generated record number. No new record numbers are -** allowed to be less than this value. When this value reaches its maximum, -** an SQLITE_FULL error is generated. The P3 register is updated with the ' -** generated record number. This P3 mechanism is used to help implement the -** AUTOINCREMENT feature. -*/ -case OP_NewRowid: { /* out2 */ - i64 v; /* The new rowid */ - VdbeCursor *pC; /* Cursor of table to get the new rowid */ - int res; /* Result of an sqlite3BtreeLast() */ - int cnt; /* Counter to limit the number of searches */ - Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */ - VdbeFrame *pFrame; /* Root frame of VDBE */ - - v = 0; - res = 0; - pOut = out2Prerelease(p, pOp); - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->isTable ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->uc.pCursor!=0 ); - { - /* The next rowid or record number (different terms for the same - ** thing) is obtained in a two-step algorithm. - ** - ** First we attempt to find the largest existing rowid and add one - ** to that. But if the largest existing rowid is already the maximum - ** positive integer, we have to fall through to the second - ** probabilistic algorithm - ** - ** The second algorithm is to select a rowid at random and see if - ** it already exists in the table. If it does not exist, we have - ** succeeded. If the random rowid does exist, we select a new one - ** and try again, up to 100 times. - */ - assert( pC->isTable ); - -#ifdef SQLITE_32BIT_ROWID -# define MAX_ROWID 0x7fffffff -#else - /* Some compilers complain about constants of the form 0x7fffffffffffffff. - ** Others complain about 0x7ffffffffffffffffLL. The following macro seems - ** to provide the constant while making all compilers happy. - */ -# define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff ) -#endif - - if( !pC->useRandomRowid ){ - rc = sqlite3BtreeLast(pC->uc.pCursor, &res); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - if( res ){ - v = 1; /* IMP: R-61914-48074 */ - }else{ - assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) ); - v = sqlite3BtreeIntegerKey(pC->uc.pCursor); - if( v>=MAX_ROWID ){ - pC->useRandomRowid = 1; - }else{ - v++; /* IMP: R-29538-34987 */ - } - } - } - -#ifndef SQLITE_OMIT_AUTOINCREMENT - if( pOp->p3 ){ - /* Assert that P3 is a valid memory cell. */ - assert( pOp->p3>0 ); - if( p->pFrame ){ - for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); - /* Assert that P3 is a valid memory cell. */ - assert( pOp->p3<=pFrame->nMem ); - pMem = &pFrame->aMem[pOp->p3]; - }else{ - /* Assert that P3 is a valid memory cell. */ - assert( pOp->p3<=(p->nMem+1 - p->nCursor) ); - pMem = &aMem[pOp->p3]; - memAboutToChange(p, pMem); - } - assert( memIsValid(pMem) ); - - REGISTER_TRACE(pOp->p3, pMem); - sqlite3VdbeMemIntegerify(pMem); - assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ - if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ - rc = SQLITE_FULL; /* IMP: R-17817-00630 */ - goto abort_due_to_error; - } - if( vu.i+1 ){ - v = pMem->u.i + 1; - } - pMem->u.i = v; - } -#endif - if( pC->useRandomRowid ){ - /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the - ** largest possible integer (9223372036854775807) then the database - ** engine starts picking positive candidate ROWIDs at random until - ** it finds one that is not previously used. */ - assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is - ** an AUTOINCREMENT table. */ - cnt = 0; - do{ - sqlite3_randomness(sizeof(v), &v); - v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */ - }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v, - 0, &res))==SQLITE_OK) - && (res==0) - && (++cnt<100)); - if( rc ) goto abort_due_to_error; - if( res==0 ){ - rc = SQLITE_FULL; /* IMP: R-38219-53002 */ - goto abort_due_to_error; - } - assert( v>0 ); /* EV: R-40812-03570 */ - } - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - } - pOut->u.i = v; - break; -} - -/* Opcode: Insert P1 P2 P3 P4 P5 -** Synopsis: intkey=r[P3] data=r[P2] -** -** Write an entry into the table of cursor P1. A new entry is -** created if it doesn't already exist or the data for an existing -** entry is overwritten. The data is the value MEM_Blob stored in register -** number P2. The key is stored in register P3. The key must -** be a MEM_Int. -** -** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is -** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, -** then rowid is stored for subsequent return by the -** sqlite3_last_insert_rowid() function (otherwise it is unmodified). -** -** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might -** run faster by avoiding an unnecessary seek on cursor P1. However, -** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior -** seeks on the cursor or if the most recent seek used a key equal to P3. -** -** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an -** UPDATE operation. Otherwise (if the flag is clear) then this opcode -** is part of an INSERT operation. The difference is only important to -** the update hook. -** -** Parameter P4 may point to a Table structure, or may be NULL. If it is -** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked -** following a successful insert. -** -** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically -** allocated, then ownership of P2 is transferred to the pseudo-cursor -** and register P2 becomes ephemeral. If the cursor is changed, the -** value of register P2 will then change. Make sure this does not -** cause any problems.) -** -** This instruction only works on tables. The equivalent instruction -** for indices is OP_IdxInsert. -*/ -case OP_Insert: { - Mem *pData; /* MEM cell holding data for the record to be inserted */ - Mem *pKey; /* MEM cell holding key for the record */ - VdbeCursor *pC; /* Cursor to table into which insert is written */ - int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */ - const char *zDb; /* database name - used by the update hook */ - Table *pTab; /* Table structure - used by update and pre-update hooks */ - BtreePayload x; /* Payload to be inserted */ - - pData = &aMem[pOp->p2]; - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( memIsValid(pData) ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->deferredMoveto==0 ); - assert( pC->uc.pCursor!=0 ); - assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable ); - assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); - REGISTER_TRACE(pOp->p2, pData); - sqlite3VdbeIncrWriteCounter(p, pC); - - pKey = &aMem[pOp->p3]; - assert( pKey->flags & MEM_Int ); - assert( memIsValid(pKey) ); - REGISTER_TRACE(pOp->p3, pKey); - x.nKey = pKey->u.i; - - if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ - assert( pC->iDb>=0 ); - zDb = db->aDb[pC->iDb].zDbSName; - pTab = pOp->p4.pTab; - assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) ); - }else{ - pTab = 0; - zDb = 0; /* Not needed. Silence a compiler warning. */ - } - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - /* Invoke the pre-update hook, if any */ - if( pTab ){ - if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){ - sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2); - } - if( db->xUpdateCallback==0 || pTab->aCol==0 ){ - /* Prevent post-update hook from running in cases when it should not */ - pTab = 0; - } - } - if( pOp->p5 & OPFLAG_ISNOOP ) break; -#endif - - if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; - if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey; - assert( pData->flags & (MEM_Blob|MEM_Str) ); - x.pData = pData->z; - x.nData = pData->n; - seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0); - if( pData->flags & MEM_Zero ){ - x.nZero = pData->u.nZero; - }else{ - x.nZero = 0; - } - x.pKey = 0; - rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, - (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult - ); - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - - /* Invoke the update-hook if required. */ - if( rc ) goto abort_due_to_error; - if( pTab ){ - assert( db->xUpdateCallback!=0 ); - assert( pTab->aCol!=0 ); - db->xUpdateCallback(db->pUpdateArg, - (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT, - zDb, pTab->zName, x.nKey); - } - break; -} - -/* Opcode: Delete P1 P2 P3 P4 P5 -** -** Delete the record at which the P1 cursor is currently pointing. -** -** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then -** the cursor will be left pointing at either the next or the previous -** record in the table. If it is left pointing at the next record, then -** the next Next instruction will be a no-op. As a result, in this case -** it is ok to delete a record from within a Next loop. If -** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be -** left in an undefined state. -** -** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this -** delete one of several associated with deleting a table row and all its -** associated index entries. Exactly one of those deletes is the "primary" -** delete. The others are all on OPFLAG_FORDELETE cursors or else are -** marked with the AUXDELETE flag. -** -** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row -** change count is incremented (otherwise not). -** -** P1 must not be pseudo-table. It has to be a real table with -** multiple rows. -** -** If P4 is not NULL then it points to a Table object. In this case either -** the update or pre-update hook, or both, may be invoked. The P1 cursor must -** have been positioned using OP_NotFound prior to invoking this opcode in -** this case. Specifically, if one is configured, the pre-update hook is -** invoked if P4 is not NULL. The update-hook is invoked if one is configured, -** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2. -** -** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address -** of the memory cell that contains the value that the rowid of the row will -** be set to by the update. -*/ -case OP_Delete: { - VdbeCursor *pC; - const char *zDb; - Table *pTab; - int opflags; - - opflags = pOp->p2; - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->uc.pCursor!=0 ); - assert( pC->deferredMoveto==0 ); - sqlite3VdbeIncrWriteCounter(p, pC); - -#ifdef SQLITE_DEBUG - if( pOp->p4type==P4_TABLE - && HasRowid(pOp->p4.pTab) - && pOp->p5==0 - && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) - ){ - /* If p5 is zero, the seek operation that positioned the cursor prior to - ** OP_Delete will have also set the pC->movetoTarget field to the rowid of - ** the row that is being deleted */ - i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor); - assert( CORRUPT_DB || pC->movetoTarget==iKey ); - } -#endif - - /* If the update-hook or pre-update-hook will be invoked, set zDb to - ** the name of the db to pass as to it. Also set local pTab to a copy - ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was - ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set - ** VdbeCursor.movetoTarget to the current rowid. */ - if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){ - assert( pC->iDb>=0 ); - assert( pOp->p4.pTab!=0 ); - zDb = db->aDb[pC->iDb].zDbSName; - pTab = pOp->p4.pTab; - if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){ - pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor); - } - }else{ - zDb = 0; /* Not needed. Silence a compiler warning. */ - pTab = 0; /* Not needed. Silence a compiler warning. */ - } - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - /* Invoke the pre-update-hook if required. */ - if( db->xPreUpdateCallback && pOp->p4.pTab ){ - assert( !(opflags & OPFLAG_ISUPDATE) - || HasRowid(pTab)==0 - || (aMem[pOp->p3].flags & MEM_Int) - ); - sqlite3VdbePreUpdateHook(p, pC, - (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, - zDb, pTab, pC->movetoTarget, - pOp->p3 - ); - } - if( opflags & OPFLAG_ISNOOP ) break; -#endif - - /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ - assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 ); - assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION ); - assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE ); - -#ifdef SQLITE_DEBUG - if( p->pFrame==0 ){ - if( pC->isEphemeral==0 - && (pOp->p5 & OPFLAG_AUXDELETE)==0 - && (pC->wrFlag & OPFLAG_FORDELETE)==0 - ){ - nExtraDelete++; - } - if( pOp->p2 & OPFLAG_NCHANGE ){ - nExtraDelete--; - } - } -#endif - - rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5); - pC->cacheStatus = CACHE_STALE; - pC->seekResult = 0; - if( rc ) goto abort_due_to_error; - - /* Invoke the update-hook if required. */ - if( opflags & OPFLAG_NCHANGE ){ - p->nChange++; - if( db->xUpdateCallback && HasRowid(pTab) ){ - db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName, - pC->movetoTarget); - assert( pC->iDb>=0 ); - } - } - - break; -} -/* Opcode: ResetCount * * * * * -** -** The value of the change counter is copied to the database handle -** change counter (returned by subsequent calls to sqlite3_changes()). -** Then the VMs internal change counter resets to 0. -** This is used by trigger programs. -*/ -case OP_ResetCount: { - sqlite3VdbeSetChanges(db, p->nChange); - p->nChange = 0; - break; -} - -/* Opcode: SorterCompare P1 P2 P3 P4 -** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2 -** -** P1 is a sorter cursor. This instruction compares a prefix of the -** record blob in register P3 against a prefix of the entry that -** the sorter cursor currently points to. Only the first P4 fields -** of r[P3] and the sorter record are compared. -** -** If either P3 or the sorter contains a NULL in one of their significant -** fields (not counting the P4 fields at the end which are ignored) then -** the comparison is assumed to be equal. -** -** Fall through to next instruction if the two records compare equal to -** each other. Jump to P2 if they are different. -*/ -case OP_SorterCompare: { - VdbeCursor *pC; - int res; - int nKeyCol; - - pC = p->apCsr[pOp->p1]; - assert( isSorter(pC) ); - assert( pOp->p4type==P4_INT32 ); - pIn3 = &aMem[pOp->p3]; - nKeyCol = pOp->p4.i; - res = 0; - rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res); - VdbeBranchTaken(res!=0,2); - if( rc ) goto abort_due_to_error; - if( res ) goto jump_to_p2; - break; -}; - -/* Opcode: SorterData P1 P2 P3 * * -** Synopsis: r[P2]=data -** -** Write into register P2 the current sorter data for sorter cursor P1. -** Then clear the column header cache on cursor P3. -** -** This opcode is normally use to move a record out of the sorter and into -** a register that is the source for a pseudo-table cursor created using -** OpenPseudo. That pseudo-table cursor is the one that is identified by -** parameter P3. Clearing the P3 column cache as part of this opcode saves -** us from having to issue a separate NullRow instruction to clear that cache. -*/ -case OP_SorterData: { - VdbeCursor *pC; - - pOut = &aMem[pOp->p2]; - pC = p->apCsr[pOp->p1]; - assert( isSorter(pC) ); - rc = sqlite3VdbeSorterRowkey(pC, pOut); - assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) ); - assert( pOp->p1>=0 && pOp->p1nCursor ); - if( rc ) goto abort_due_to_error; - p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE; - break; -} - -/* Opcode: RowData P1 P2 P3 * * -** Synopsis: r[P2]=data -** -** Write into register P2 the complete row content for the row at -** which cursor P1 is currently pointing. -** There is no interpretation of the data. -** It is just copied onto the P2 register exactly as -** it is found in the database file. -** -** If cursor P1 is an index, then the content is the key of the row. -** If cursor P2 is a table, then the content extracted is the data. -** -** If the P1 cursor must be pointing to a valid row (not a NULL row) -** of a real table, not a pseudo-table. -** -** If P3!=0 then this opcode is allowed to make an ephemeral pointer -** into the database page. That means that the content of the output -** register will be invalidated as soon as the cursor moves - including -** moves caused by other cursors that "save" the current cursors -** position in order that they can write to the same table. If P3==0 -** then a copy of the data is made into memory. P3!=0 is faster, but -** P3==0 is safer. -** -** If P3!=0 then the content of the P2 register is unsuitable for use -** in OP_Result and any OP_Result will invalidate the P2 register content. -** The P2 register content is invalidated by opcodes like OP_Function or -** by any use of another cursor pointing to the same table. -*/ -case OP_RowData: { - VdbeCursor *pC; - BtCursor *pCrsr; - u32 n; - - pOut = out2Prerelease(p, pOp); - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( isSorter(pC)==0 ); - assert( pC->nullRow==0 ); - assert( pC->uc.pCursor!=0 ); - pCrsr = pC->uc.pCursor; - - /* The OP_RowData opcodes always follow OP_NotExists or - ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions - ** that might invalidate the cursor. - ** If this where not the case, on of the following assert()s - ** would fail. Should this ever change (because of changes in the code - ** generator) then the fix would be to insert a call to - ** sqlite3VdbeCursorMoveto(). - */ - assert( pC->deferredMoveto==0 ); - assert( sqlite3BtreeCursorIsValid(pCrsr) ); - - n = sqlite3BtreePayloadSize(pCrsr); - if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - testcase( n==0 ); - rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut); - if( rc ) goto abort_due_to_error; - if( !pOp->p3 ) Deephemeralize(pOut); - UPDATE_MAX_BLOBSIZE(pOut); - REGISTER_TRACE(pOp->p2, pOut); - break; -} - -/* Opcode: Rowid P1 P2 * * * -** Synopsis: r[P2]=rowid -** -** Store in register P2 an integer which is the key of the table entry that -** P1 is currently point to. -** -** P1 can be either an ordinary table or a virtual table. There used to -** be a separate OP_VRowid opcode for use with virtual tables, but this -** one opcode now works for both table types. -*/ -case OP_Rowid: { /* out2 */ - VdbeCursor *pC; - i64 v; - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; - - pOut = out2Prerelease(p, pOp); - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow ); - if( pC->nullRow ){ - pOut->flags = MEM_Null; - break; - }else if( pC->deferredMoveto ){ - v = pC->movetoTarget; -#ifndef SQLITE_OMIT_VIRTUALTABLE - }else if( pC->eCurType==CURTYPE_VTAB ){ - assert( pC->uc.pVCur!=0 ); - pVtab = pC->uc.pVCur->pVtab; - pModule = pVtab->pModule; - assert( pModule->xRowid ); - rc = pModule->xRowid(pC->uc.pVCur, &v); - sqlite3VtabImportErrmsg(p, pVtab); - if( rc ) goto abort_due_to_error; -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - }else{ - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->uc.pCursor!=0 ); - rc = sqlite3VdbeCursorRestore(pC); - if( rc ) goto abort_due_to_error; - if( pC->nullRow ){ - pOut->flags = MEM_Null; - break; - } - v = sqlite3BtreeIntegerKey(pC->uc.pCursor); - } - pOut->u.i = v; - break; -} - -/* Opcode: NullRow P1 * * * * -** -** Move the cursor P1 to a null row. Any OP_Column operations -** that occur while the cursor is on the null row will always -** write a NULL. -*/ -case OP_NullRow: { - VdbeCursor *pC; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - pC->nullRow = 1; - pC->cacheStatus = CACHE_STALE; - if( pC->eCurType==CURTYPE_BTREE ){ - assert( pC->uc.pCursor!=0 ); - sqlite3BtreeClearCursor(pC->uc.pCursor); - } -#ifdef SQLITE_DEBUG - if( pC->seekOp==0 ) pC->seekOp = OP_NullRow; -#endif - break; -} - -/* Opcode: SeekEnd P1 * * * * -** -** Position cursor P1 at the end of the btree for the purpose of -** appending a new entry onto the btree. -** -** It is assumed that the cursor is used only for appending and so -** if the cursor is valid, then the cursor must already be pointing -** at the end of the btree and so no changes are made to -** the cursor. -*/ -/* Opcode: Last P1 P2 * * * -** -** The next use of the Rowid or Column or Prev instruction for P1 -** will refer to the last entry in the database table or index. -** If the table or index is empty and P2>0, then jump immediately to P2. -** If P2 is 0 or if the table or index is not empty, fall through -** to the following instruction. -** -** This opcode leaves the cursor configured to move in reverse order, -** from the end toward the beginning. In other words, the cursor is -** configured to use Prev, not Next. -*/ -case OP_SeekEnd: -case OP_Last: { /* jump */ - VdbeCursor *pC; - BtCursor *pCrsr; - int res; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - pCrsr = pC->uc.pCursor; - res = 0; - assert( pCrsr!=0 ); -#ifdef SQLITE_DEBUG - pC->seekOp = pOp->opcode; -#endif - if( pOp->opcode==OP_SeekEnd ){ - assert( pOp->p2==0 ); - pC->seekResult = -1; - if( sqlite3BtreeCursorIsValidNN(pCrsr) ){ - break; - } - } - rc = sqlite3BtreeLast(pCrsr, &res); - pC->nullRow = (u8)res; - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - if( rc ) goto abort_due_to_error; - if( pOp->p2>0 ){ - VdbeBranchTaken(res!=0,2); - if( res ) goto jump_to_p2; - } - break; -} - -/* Opcode: IfSmaller P1 P2 P3 * * -** -** Estimate the number of rows in the table P1. Jump to P2 if that -** estimate is less than approximately 2**(0.1*P3). -*/ -case OP_IfSmaller: { /* jump */ - VdbeCursor *pC; - BtCursor *pCrsr; - int res; - i64 sz; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - pCrsr = pC->uc.pCursor; - assert( pCrsr ); - rc = sqlite3BtreeFirst(pCrsr, &res); - if( rc ) goto abort_due_to_error; - if( res==0 ){ - sz = sqlite3BtreeRowCountEst(pCrsr); - if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)p3 ) res = 1; - } - VdbeBranchTaken(res!=0,2); - if( res ) goto jump_to_p2; - break; -} - - -/* Opcode: SorterSort P1 P2 * * * -** -** After all records have been inserted into the Sorter object -** identified by P1, invoke this opcode to actually do the sorting. -** Jump to P2 if there are no records to be sorted. -** -** This opcode is an alias for OP_Sort and OP_Rewind that is used -** for Sorter objects. -*/ -/* Opcode: Sort P1 P2 * * * -** -** This opcode does exactly the same thing as OP_Rewind except that -** it increments an undocumented global variable used for testing. -** -** Sorting is accomplished by writing records into a sorting index, -** then rewinding that index and playing it back from beginning to -** end. We use the OP_Sort opcode instead of OP_Rewind to do the -** rewinding so that the global variable will be incremented and -** regression tests can determine whether or not the optimizer is -** correctly optimizing out sorts. -*/ -case OP_SorterSort: /* jump */ -case OP_Sort: { /* jump */ -#ifdef SQLITE_TEST - sqlite3_sort_count++; - sqlite3_search_count--; -#endif - p->aCounter[SQLITE_STMTSTATUS_SORT]++; - /* Fall through into OP_Rewind */ - /* no break */ deliberate_fall_through -} -/* Opcode: Rewind P1 P2 * * * -** -** The next use of the Rowid or Column or Next instruction for P1 -** will refer to the first entry in the database table or index. -** If the table or index is empty, jump immediately to P2. -** If the table or index is not empty, fall through to the following -** instruction. -** -** This opcode leaves the cursor configured to move in forward order, -** from the beginning toward the end. In other words, the cursor is -** configured to use Next, not Prev. -*/ -case OP_Rewind: { /* jump */ - VdbeCursor *pC; - BtCursor *pCrsr; - int res; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( pOp->p5==0 ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) ); - res = 1; -#ifdef SQLITE_DEBUG - pC->seekOp = OP_Rewind; -#endif - if( isSorter(pC) ){ - rc = sqlite3VdbeSorterRewind(pC, &res); - }else{ - assert( pC->eCurType==CURTYPE_BTREE ); - pCrsr = pC->uc.pCursor; - assert( pCrsr ); - rc = sqlite3BtreeFirst(pCrsr, &res); - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - } - if( rc ) goto abort_due_to_error; - pC->nullRow = (u8)res; - assert( pOp->p2>0 && pOp->p2nOp ); - VdbeBranchTaken(res!=0,2); - if( res ) goto jump_to_p2; - break; -} - -/* Opcode: Next P1 P2 P3 P4 P5 -** -** Advance cursor P1 so that it points to the next key/data pair in its -** table or index. If there are no more key/value pairs then fall through -** to the following instruction. But if the cursor advance was successful, -** jump immediately to P2. -** -** The Next opcode is only valid following an SeekGT, SeekGE, or -** OP_Rewind opcode used to position the cursor. Next is not allowed -** to follow SeekLT, SeekLE, or OP_Last. -** -** The P1 cursor must be for a real table, not a pseudo-table. P1 must have -** been opened prior to this opcode or the program will segfault. -** -** The P3 value is a hint to the btree implementation. If P3==1, that -** means P1 is an SQL index and that this instruction could have been -** omitted if that index had been unique. P3 is usually 0. P3 is -** always either 0 or 1. -** -** P4 is always of type P4_ADVANCE. The function pointer points to -** sqlite3BtreeNext(). -** -** If P5 is positive and the jump is taken, then event counter -** number P5-1 in the prepared statement is incremented. -** -** See also: Prev -*/ -/* Opcode: Prev P1 P2 P3 P4 P5 -** -** Back up cursor P1 so that it points to the previous key/data pair in its -** table or index. If there is no previous key/value pairs then fall through -** to the following instruction. But if the cursor backup was successful, -** jump immediately to P2. -** -** -** The Prev opcode is only valid following an SeekLT, SeekLE, or -** OP_Last opcode used to position the cursor. Prev is not allowed -** to follow SeekGT, SeekGE, or OP_Rewind. -** -** The P1 cursor must be for a real table, not a pseudo-table. If P1 is -** not open then the behavior is undefined. -** -** The P3 value is a hint to the btree implementation. If P3==1, that -** means P1 is an SQL index and that this instruction could have been -** omitted if that index had been unique. P3 is usually 0. P3 is -** always either 0 or 1. -** -** P4 is always of type P4_ADVANCE. The function pointer points to -** sqlite3BtreePrevious(). -** -** If P5 is positive and the jump is taken, then event counter -** number P5-1 in the prepared statement is incremented. -*/ -/* Opcode: SorterNext P1 P2 * * P5 -** -** This opcode works just like OP_Next except that P1 must be a -** sorter object for which the OP_SorterSort opcode has been -** invoked. This opcode advances the cursor to the next sorted -** record, or jumps to P2 if there are no more sorted records. -*/ -case OP_SorterNext: { /* jump */ - VdbeCursor *pC; - - pC = p->apCsr[pOp->p1]; - assert( isSorter(pC) ); - rc = sqlite3VdbeSorterNext(db, pC); - goto next_tail; -case OP_Prev: /* jump */ -case OP_Next: /* jump */ - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( pOp->p5aCounter) ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->deferredMoveto==0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext ); - assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious ); - - /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found. - ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */ - assert( pOp->opcode!=OP_Next - || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE - || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found - || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid - || pC->seekOp==OP_IfNoHope); - assert( pOp->opcode!=OP_Prev - || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE - || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope - || pC->seekOp==OP_NullRow); - - rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3); -next_tail: - pC->cacheStatus = CACHE_STALE; - VdbeBranchTaken(rc==SQLITE_OK,2); - if( rc==SQLITE_OK ){ - pC->nullRow = 0; - p->aCounter[pOp->p5]++; -#ifdef SQLITE_TEST - sqlite3_search_count++; -#endif - goto jump_to_p2_and_check_for_interrupt; - } - if( rc!=SQLITE_DONE ) goto abort_due_to_error; - rc = SQLITE_OK; - pC->nullRow = 1; - goto check_for_interrupt; -} - -/* Opcode: IdxInsert P1 P2 P3 P4 P5 -** Synopsis: key=r[P2] -** -** Register P2 holds an SQL index key made using the -** MakeRecord instructions. This opcode writes that key -** into the index P1. Data for the entry is nil. -** -** If P4 is not zero, then it is the number of values in the unpacked -** key of reg(P2). In that case, P3 is the index of the first register -** for the unpacked key. The availability of the unpacked key can sometimes -** be an optimization. -** -** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer -** that this insert is likely to be an append. -** -** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is -** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear, -** then the change counter is unchanged. -** -** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might -** run faster by avoiding an unnecessary seek on cursor P1. However, -** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior -** seeks on the cursor or if the most recent seek used a key equivalent -** to P2. -** -** This instruction only works for indices. The equivalent instruction -** for tables is OP_Insert. -*/ -case OP_IdxInsert: { /* in2 */ - VdbeCursor *pC; - BtreePayload x; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - sqlite3VdbeIncrWriteCounter(p, pC); - assert( pC!=0 ); - assert( !isSorter(pC) ); - pIn2 = &aMem[pOp->p2]; - assert( pIn2->flags & MEM_Blob ); - if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->isTable==0 ); - rc = ExpandBlob(pIn2); - if( rc ) goto abort_due_to_error; - x.nKey = pIn2->n; - x.pKey = pIn2->z; - x.aMem = aMem + pOp->p3; - x.nMem = (u16)pOp->p4.i; - rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, - (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), - ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0) - ); - assert( pC->deferredMoveto==0 ); - pC->cacheStatus = CACHE_STALE; - if( rc) goto abort_due_to_error; - break; -} - -/* Opcode: SorterInsert P1 P2 * * * -** Synopsis: key=r[P2] -** -** Register P2 holds an SQL index key made using the -** MakeRecord instructions. This opcode writes that key -** into the sorter P1. Data for the entry is nil. -*/ -case OP_SorterInsert: { /* in2 */ - VdbeCursor *pC; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - sqlite3VdbeIncrWriteCounter(p, pC); - assert( pC!=0 ); - assert( isSorter(pC) ); - pIn2 = &aMem[pOp->p2]; - assert( pIn2->flags & MEM_Blob ); - assert( pC->isTable==0 ); - rc = ExpandBlob(pIn2); - if( rc ) goto abort_due_to_error; - rc = sqlite3VdbeSorterWrite(pC, pIn2); - if( rc) goto abort_due_to_error; - break; -} - -/* Opcode: IdxDelete P1 P2 P3 * P5 -** Synopsis: key=r[P2@P3] -** -** The content of P3 registers starting at register P2 form -** an unpacked index key. This opcode removes that entry from the -** index opened by cursor P1. -** -** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error -** if no matching index entry is found. This happens when running -** an UPDATE or DELETE statement and the index entry to be updated -** or deleted is not found. For some uses of IdxDelete -** (example: the EXCEPT operator) it does not matter that no matching -** entry is found. For those cases, P5 is zero. -*/ -case OP_IdxDelete: { - VdbeCursor *pC; - BtCursor *pCrsr; - int res; - UnpackedRecord r; - - assert( pOp->p3>0 ); - assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 ); - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - sqlite3VdbeIncrWriteCounter(p, pC); - pCrsr = pC->uc.pCursor; - assert( pCrsr!=0 ); - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)pOp->p3; - r.default_rc = 0; - r.aMem = &aMem[pOp->p2]; - rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res); - if( rc ) goto abort_due_to_error; - if( res==0 ){ - rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); - if( rc ) goto abort_due_to_error; - }else if( pOp->p5 ){ - rc = SQLITE_CORRUPT_INDEX; - goto abort_due_to_error; - } - assert( pC->deferredMoveto==0 ); - pC->cacheStatus = CACHE_STALE; - pC->seekResult = 0; - break; -} - -/* Opcode: DeferredSeek P1 * P3 P4 * -** Synopsis: Move P3 to P1.rowid if needed -** -** P1 is an open index cursor and P3 is a cursor on the corresponding -** table. This opcode does a deferred seek of the P3 table cursor -** to the row that corresponds to the current row of P1. -** -** This is a deferred seek. Nothing actually happens until -** the cursor is used to read a record. That way, if no reads -** occur, no unnecessary I/O happens. -** -** P4 may be an array of integers (type P4_INTARRAY) containing -** one entry for each column in the P3 table. If array entry a(i) -** is non-zero, then reading column a(i)-1 from cursor P3 is -** equivalent to performing the deferred seek and then reading column i -** from P1. This information is stored in P3 and used to redirect -** reads against P3 over to P1, thus possibly avoiding the need to -** seek and read cursor P3. -*/ -/* Opcode: IdxRowid P1 P2 * * * -** Synopsis: r[P2]=rowid -** -** Write into register P2 an integer which is the last entry in the record at -** the end of the index key pointed to by cursor P1. This integer should be -** the rowid of the table entry to which this index entry points. -** -** See also: Rowid, MakeRecord. -*/ -case OP_DeferredSeek: -case OP_IdxRowid: { /* out2 */ - VdbeCursor *pC; /* The P1 index cursor */ - VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */ - i64 rowid; /* Rowid that P1 current points to */ - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->uc.pCursor!=0 ); - assert( pC->isTable==0 ); - assert( pC->deferredMoveto==0 ); - assert( !pC->nullRow || pOp->opcode==OP_IdxRowid ); - - /* The IdxRowid and Seek opcodes are combined because of the commonality - ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */ - rc = sqlite3VdbeCursorRestore(pC); - - /* sqlite3VbeCursorRestore() can only fail if the record has been deleted - ** out from under the cursor. That will never happens for an IdxRowid - ** or Seek opcode */ - if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error; - - if( !pC->nullRow ){ - rowid = 0; /* Not needed. Only used to silence a warning. */ - rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - if( pOp->opcode==OP_DeferredSeek ){ - assert( pOp->p3>=0 && pOp->p3nCursor ); - pTabCur = p->apCsr[pOp->p3]; - assert( pTabCur!=0 ); - assert( pTabCur->eCurType==CURTYPE_BTREE ); - assert( pTabCur->uc.pCursor!=0 ); - assert( pTabCur->isTable ); - pTabCur->nullRow = 0; - pTabCur->movetoTarget = rowid; - pTabCur->deferredMoveto = 1; - assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 ); - pTabCur->aAltMap = pOp->p4.ai; - pTabCur->pAltCursor = pC; - }else{ - pOut = out2Prerelease(p, pOp); - pOut->u.i = rowid; - } - }else{ - assert( pOp->opcode==OP_IdxRowid ); - sqlite3VdbeMemSetNull(&aMem[pOp->p2]); - } - break; -} - -/* Opcode: FinishSeek P1 * * * * -** -** If cursor P1 was previously moved via OP_DeferredSeek, complete that -** seek operation now, without further delay. If the cursor seek has -** already occurred, this instruction is a no-op. -*/ -case OP_FinishSeek: { - VdbeCursor *pC; /* The P1 index cursor */ - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - if( pC->deferredMoveto ){ - rc = sqlite3VdbeFinishMoveto(pC); - if( rc ) goto abort_due_to_error; - } - break; -} - -/* Opcode: IdxGE P1 P2 P3 P4 P5 -** Synopsis: key=r[P3@P4] -** -** The P4 register values beginning with P3 form an unpacked index -** key that omits the PRIMARY KEY. Compare this key value against the index -** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID -** fields at the end. -** -** If the P1 index entry is greater than or equal to the key value -** then jump to P2. Otherwise fall through to the next instruction. -*/ -/* Opcode: IdxGT P1 P2 P3 P4 P5 -** Synopsis: key=r[P3@P4] -** -** The P4 register values beginning with P3 form an unpacked index -** key that omits the PRIMARY KEY. Compare this key value against the index -** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID -** fields at the end. -** -** If the P1 index entry is greater than the key value -** then jump to P2. Otherwise fall through to the next instruction. -*/ -/* Opcode: IdxLT P1 P2 P3 P4 P5 -** Synopsis: key=r[P3@P4] -** -** The P4 register values beginning with P3 form an unpacked index -** key that omits the PRIMARY KEY or ROWID. Compare this key value against -** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or -** ROWID on the P1 index. -** -** If the P1 index entry is less than the key value then jump to P2. -** Otherwise fall through to the next instruction. -*/ -/* Opcode: IdxLE P1 P2 P3 P4 P5 -** Synopsis: key=r[P3@P4] -** -** The P4 register values beginning with P3 form an unpacked index -** key that omits the PRIMARY KEY or ROWID. Compare this key value against -** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or -** ROWID on the P1 index. -** -** If the P1 index entry is less than or equal to the key value then jump -** to P2. Otherwise fall through to the next instruction. -*/ -case OP_IdxLE: /* jump */ -case OP_IdxGT: /* jump */ -case OP_IdxLT: /* jump */ -case OP_IdxGE: { /* jump */ - VdbeCursor *pC; - int res; - UnpackedRecord r; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->isOrdered ); - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->uc.pCursor!=0); - assert( pC->deferredMoveto==0 ); - assert( pOp->p5==0 || pOp->p5==1 ); - assert( pOp->p4type==P4_INT32 ); - r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)pOp->p4.i; - if( pOp->opcodeopcode==OP_IdxLE || pOp->opcode==OP_IdxGT ); - r.default_rc = -1; - }else{ - assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT ); - r.default_rc = 0; - } - r.aMem = &aMem[pOp->p3]; -#ifdef SQLITE_DEBUG - { - int i; - for(i=0; ip3+i, &aMem[pOp->p3+i]); - } - } -#endif - res = 0; /* Not needed. Only used to silence a warning. */ - rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res); - assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) ); - if( (pOp->opcode&1)==(OP_IdxLT&1) ){ - assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT ); - res = -res; - }else{ - assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT ); - res++; - } - VdbeBranchTaken(res>0,2); - if( rc ) goto abort_due_to_error; - if( res>0 ) goto jump_to_p2; - break; -} - -/* Opcode: Destroy P1 P2 P3 * * -** -** Delete an entire database table or index whose root page in the database -** file is given by P1. -** -** The table being destroyed is in the main database file if P3==0. If -** P3==1 then the table to be clear is in the auxiliary database file -** that is used to store tables create using CREATE TEMPORARY TABLE. -** -** If AUTOVACUUM is enabled then it is possible that another root page -** might be moved into the newly deleted root page in order to keep all -** root pages contiguous at the beginning of the database. The former -** value of the root page that moved - its value before the move occurred - -** is stored in register P2. If no page movement was required (because the -** table being dropped was already the last one in the database) then a -** zero is stored in register P2. If AUTOVACUUM is disabled then a zero -** is stored in register P2. -** -** This opcode throws an error if there are any active reader VMs when -** it is invoked. This is done to avoid the difficulty associated with -** updating existing cursors when a root page is moved in an AUTOVACUUM -** database. This error is thrown even if the database is not an AUTOVACUUM -** db in order to avoid introducing an incompatibility between autovacuum -** and non-autovacuum modes. -** -** See also: Clear -*/ -case OP_Destroy: { /* out2 */ - int iMoved; - int iDb; - - sqlite3VdbeIncrWriteCounter(p, 0); - assert( p->readOnly==0 ); - assert( pOp->p1>1 ); - pOut = out2Prerelease(p, pOp); - pOut->flags = MEM_Null; - if( db->nVdbeRead > db->nVDestroy+1 ){ - rc = SQLITE_LOCKED; - p->errorAction = OE_Abort; - goto abort_due_to_error; - }else{ - iDb = pOp->p3; - assert( DbMaskTest(p->btreeMask, iDb) ); - iMoved = 0; /* Not needed. Only to silence a warning. */ - rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); - pOut->flags = MEM_Int; - pOut->u.i = iMoved; - if( rc ) goto abort_due_to_error; -#ifndef SQLITE_OMIT_AUTOVACUUM - if( iMoved!=0 ){ - sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1); - /* All OP_Destroy operations occur on the same btree */ - assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 ); - resetSchemaOnFault = iDb+1; - } -#endif - } - break; -} - -/* Opcode: Clear P1 P2 P3 -** -** Delete all contents of the database table or index whose root page -** in the database file is given by P1. But, unlike Destroy, do not -** remove the table or index from the database file. -** -** The table being clear is in the main database file if P2==0. If -** P2==1 then the table to be clear is in the auxiliary database file -** that is used to store tables create using CREATE TEMPORARY TABLE. -** -** If the P3 value is non-zero, then the table referred to must be an -** intkey table (an SQL table, not an index). In this case the row change -** count is incremented by the number of rows in the table being cleared. -** If P3 is greater than zero, then the value stored in register P3 is -** also incremented by the number of rows in the table being cleared. -** -** See also: Destroy -*/ -case OP_Clear: { - int nChange; - - sqlite3VdbeIncrWriteCounter(p, 0); - nChange = 0; - assert( p->readOnly==0 ); - assert( DbMaskTest(p->btreeMask, pOp->p2) ); - rc = sqlite3BtreeClearTable( - db->aDb[pOp->p2].pBt, (u32)pOp->p1, (pOp->p3 ? &nChange : 0) - ); - if( pOp->p3 ){ - p->nChange += nChange; - if( pOp->p3>0 ){ - assert( memIsValid(&aMem[pOp->p3]) ); - memAboutToChange(p, &aMem[pOp->p3]); - aMem[pOp->p3].u.i += nChange; - } - } - if( rc ) goto abort_due_to_error; - break; -} - -/* Opcode: ResetSorter P1 * * * * -** -** Delete all contents from the ephemeral table or sorter -** that is open on cursor P1. -** -** This opcode only works for cursors used for sorting and -** opened with OP_OpenEphemeral or OP_SorterOpen. -*/ -case OP_ResetSorter: { - VdbeCursor *pC; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - if( isSorter(pC) ){ - sqlite3VdbeSorterReset(db, pC->uc.pSorter); - }else{ - assert( pC->eCurType==CURTYPE_BTREE ); - assert( pC->isEphemeral ); - rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor); - if( rc ) goto abort_due_to_error; - } - break; -} - -/* Opcode: CreateBtree P1 P2 P3 * * -** Synopsis: r[P2]=root iDb=P1 flags=P3 -** -** Allocate a new b-tree in the main database file if P1==0 or in the -** TEMP database file if P1==1 or in an attached database if -** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table -** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table. -** The root page number of the new b-tree is stored in register P2. -*/ -case OP_CreateBtree: { /* out2 */ - Pgno pgno; - Db *pDb; - - sqlite3VdbeIncrWriteCounter(p, 0); - pOut = out2Prerelease(p, pOp); - pgno = 0; - assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY ); - assert( pOp->p1>=0 && pOp->p1nDb ); - assert( DbMaskTest(p->btreeMask, pOp->p1) ); - assert( p->readOnly==0 ); - pDb = &db->aDb[pOp->p1]; - assert( pDb->pBt!=0 ); - rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3); - if( rc ) goto abort_due_to_error; - pOut->u.i = pgno; - break; -} - -/* Opcode: SqlExec * * * P4 * -** -** Run the SQL statement or statements specified in the P4 string. -*/ -case OP_SqlExec: { - sqlite3VdbeIncrWriteCounter(p, 0); - db->nSqlExec++; - rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0); - db->nSqlExec--; - if( rc ) goto abort_due_to_error; - break; -} - -/* Opcode: ParseSchema P1 * * P4 * -** -** Read and parse all entries from the schema table of database P1 -** that match the WHERE clause P4. If P4 is a NULL pointer, then the -** entire schema for P1 is reparsed. -** -** This opcode invokes the parser to create a new virtual machine, -** then runs the new virtual machine. It is thus a re-entrant opcode. -*/ -case OP_ParseSchema: { - int iDb; - const char *zSchema; - char *zSql; - InitData initData; - - /* Any prepared statement that invokes this opcode will hold mutexes - ** on every btree. This is a prerequisite for invoking - ** sqlite3InitCallback(). - */ -#ifdef SQLITE_DEBUG - for(iDb=0; iDbnDb; iDb++){ - assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); - } -#endif - - iDb = pOp->p1; - assert( iDb>=0 && iDbnDb ); - assert( DbHasProperty(db, iDb, DB_SchemaLoaded) ); - -#ifndef SQLITE_OMIT_ALTERTABLE - if( pOp->p4.z==0 ){ - sqlite3SchemaClear(db->aDb[iDb].pSchema); - db->mDbFlags &= ~DBFLAG_SchemaKnownOk; - rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable); - db->mDbFlags |= DBFLAG_SchemaChange; - p->expired = 0; - }else -#endif - { - zSchema = DFLT_SCHEMA_TABLE; - initData.db = db; - initData.iDb = iDb; - initData.pzErrMsg = &p->zErrMsg; - initData.mInitFlags = 0; - initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt); - zSql = sqlite3MPrintf(db, - "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid", - db->aDb[iDb].zDbSName, zSchema, pOp->p4.z); - if( zSql==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - assert( db->init.busy==0 ); - db->init.busy = 1; - initData.rc = SQLITE_OK; - initData.nInitRow = 0; - assert( !db->mallocFailed ); - rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); - if( rc==SQLITE_OK ) rc = initData.rc; - if( rc==SQLITE_OK && initData.nInitRow==0 ){ - /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse - ** at least one SQL statement. Any less than that indicates that - ** the sqlite_schema table is corrupt. */ - rc = SQLITE_CORRUPT_BKPT; - } - sqlite3DbFreeNN(db, zSql); - db->init.busy = 0; - } - } - if( rc ){ - sqlite3ResetAllSchemasOfConnection(db); - if( rc==SQLITE_NOMEM ){ - goto no_mem; - } - goto abort_due_to_error; - } - break; -} - -#if !defined(SQLITE_OMIT_ANALYZE) -/* Opcode: LoadAnalysis P1 * * * * -** -** Read the sqlite_stat1 table for database P1 and load the content -** of that table into the internal index hash table. This will cause -** the analysis to be used when preparing all subsequent queries. -*/ -case OP_LoadAnalysis: { - assert( pOp->p1>=0 && pOp->p1nDb ); - rc = sqlite3AnalysisLoad(db, pOp->p1); - if( rc ) goto abort_due_to_error; - break; -} -#endif /* !defined(SQLITE_OMIT_ANALYZE) */ - -/* Opcode: DropTable P1 * * P4 * -** -** Remove the internal (in-memory) data structures that describe -** the table named P4 in database P1. This is called after a table -** is dropped from disk (using the Destroy opcode) in order to keep -** the internal representation of the -** schema consistent with what is on disk. -*/ -case OP_DropTable: { - sqlite3VdbeIncrWriteCounter(p, 0); - sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); - break; -} - -/* Opcode: DropIndex P1 * * P4 * -** -** Remove the internal (in-memory) data structures that describe -** the index named P4 in database P1. This is called after an index -** is dropped from disk (using the Destroy opcode) -** in order to keep the internal representation of the -** schema consistent with what is on disk. -*/ -case OP_DropIndex: { - sqlite3VdbeIncrWriteCounter(p, 0); - sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); - break; -} - -/* Opcode: DropTrigger P1 * * P4 * -** -** Remove the internal (in-memory) data structures that describe -** the trigger named P4 in database P1. This is called after a trigger -** is dropped from disk (using the Destroy opcode) in order to keep -** the internal representation of the -** schema consistent with what is on disk. -*/ -case OP_DropTrigger: { - sqlite3VdbeIncrWriteCounter(p, 0); - sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); - break; -} - - -#ifndef SQLITE_OMIT_INTEGRITY_CHECK -/* Opcode: IntegrityCk P1 P2 P3 P4 P5 -** -** Do an analysis of the currently open database. Store in -** register P1 the text of an error message describing any problems. -** If no problems are found, store a NULL in register P1. -** -** The register P3 contains one less than the maximum number of allowed errors. -** At most reg(P3) errors will be reported. -** In other words, the analysis stops as soon as reg(P1) errors are -** seen. Reg(P1) is updated with the number of errors remaining. -** -** The root page numbers of all tables in the database are integers -** stored in P4_INTARRAY argument. -** -** If P5 is not zero, the check is done on the auxiliary database -** file, not the main database file. -** -** This opcode is used to implement the integrity_check pragma. -*/ -case OP_IntegrityCk: { - int nRoot; /* Number of tables to check. (Number of root pages.) */ - Pgno *aRoot; /* Array of rootpage numbers for tables to be checked */ - int nErr; /* Number of errors reported */ - char *z; /* Text of the error report */ - Mem *pnErr; /* Register keeping track of errors remaining */ - - assert( p->bIsReader ); - nRoot = pOp->p2; - aRoot = pOp->p4.ai; - assert( nRoot>0 ); - assert( aRoot[0]==(Pgno)nRoot ); - assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - pnErr = &aMem[pOp->p3]; - assert( (pnErr->flags & MEM_Int)!=0 ); - assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); - pIn1 = &aMem[pOp->p1]; - assert( pOp->p5nDb ); - assert( DbMaskTest(p->btreeMask, pOp->p5) ); - z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot, - (int)pnErr->u.i+1, &nErr); - sqlite3VdbeMemSetNull(pIn1); - if( nErr==0 ){ - assert( z==0 ); - }else if( z==0 ){ - goto no_mem; - }else{ - pnErr->u.i -= nErr-1; - sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free); - } - UPDATE_MAX_BLOBSIZE(pIn1); - sqlite3VdbeChangeEncoding(pIn1, encoding); - goto check_for_interrupt; -} -#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ - -/* Opcode: RowSetAdd P1 P2 * * * -** Synopsis: rowset(P1)=r[P2] -** -** Insert the integer value held by register P2 into a RowSet object -** held in register P1. -** -** An assertion fails if P2 is not an integer. -*/ -case OP_RowSetAdd: { /* in1, in2 */ - pIn1 = &aMem[pOp->p1]; - pIn2 = &aMem[pOp->p2]; - assert( (pIn2->flags & MEM_Int)!=0 ); - if( (pIn1->flags & MEM_Blob)==0 ){ - if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; - } - assert( sqlite3VdbeMemIsRowSet(pIn1) ); - sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i); - break; -} - -/* Opcode: RowSetRead P1 P2 P3 * * -** Synopsis: r[P3]=rowset(P1) -** -** Extract the smallest value from the RowSet object in P1 -** and put that value into register P3. -** Or, if RowSet object P1 is initially empty, leave P3 -** unchanged and jump to instruction P2. -*/ -case OP_RowSetRead: { /* jump, in1, out3 */ - i64 val; - - pIn1 = &aMem[pOp->p1]; - assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) ); - if( (pIn1->flags & MEM_Blob)==0 - || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0 - ){ - /* The boolean index is empty */ - sqlite3VdbeMemSetNull(pIn1); - VdbeBranchTaken(1,2); - goto jump_to_p2_and_check_for_interrupt; - }else{ - /* A value was pulled from the index */ - VdbeBranchTaken(0,2); - sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val); - } - goto check_for_interrupt; -} - -/* Opcode: RowSetTest P1 P2 P3 P4 -** Synopsis: if r[P3] in rowset(P1) goto P2 -** -** Register P3 is assumed to hold a 64-bit integer value. If register P1 -** contains a RowSet object and that RowSet object contains -** the value held in P3, jump to register P2. Otherwise, insert the -** integer in P3 into the RowSet and continue on to the -** next opcode. -** -** The RowSet object is optimized for the case where sets of integers -** are inserted in distinct phases, which each set contains no duplicates. -** Each set is identified by a unique P4 value. The first set -** must have P4==0, the final set must have P4==-1, and for all other sets -** must have P4>0. -** -** This allows optimizations: (a) when P4==0 there is no need to test -** the RowSet object for P3, as it is guaranteed not to contain it, -** (b) when P4==-1 there is no need to insert the value, as it will -** never be tested for, and (c) when a value that is part of set X is -** inserted, there is no need to search to see if the same value was -** previously inserted as part of set X (only if it was previously -** inserted as part of some other set). -*/ -case OP_RowSetTest: { /* jump, in1, in3 */ - int iSet; - int exists; - - pIn1 = &aMem[pOp->p1]; - pIn3 = &aMem[pOp->p3]; - iSet = pOp->p4.i; - assert( pIn3->flags&MEM_Int ); - - /* If there is anything other than a rowset object in memory cell P1, - ** delete it now and initialize P1 with an empty rowset - */ - if( (pIn1->flags & MEM_Blob)==0 ){ - if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem; - } - assert( sqlite3VdbeMemIsRowSet(pIn1) ); - assert( pOp->p4type==P4_INT32 ); - assert( iSet==-1 || iSet>=0 ); - if( iSet ){ - exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i); - VdbeBranchTaken(exists!=0,2); - if( exists ) goto jump_to_p2; - } - if( iSet>=0 ){ - sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i); - } - break; -} - - -#ifndef SQLITE_OMIT_TRIGGER - -/* Opcode: Program P1 P2 P3 P4 P5 -** -** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). -** -** P1 contains the address of the memory cell that contains the first memory -** cell in an array of values used as arguments to the sub-program. P2 -** contains the address to jump to if the sub-program throws an IGNORE -** exception using the RAISE() function. Register P3 contains the address -** of a memory cell in this (the parent) VM that is used to allocate the -** memory required by the sub-vdbe at runtime. -** -** P4 is a pointer to the VM containing the trigger program. -** -** If P5 is non-zero, then recursive program invocation is enabled. -*/ -case OP_Program: { /* jump */ - int nMem; /* Number of memory registers for sub-program */ - int nByte; /* Bytes of runtime space required for sub-program */ - Mem *pRt; /* Register to allocate runtime space */ - Mem *pMem; /* Used to iterate through memory cells */ - Mem *pEnd; /* Last memory cell in new array */ - VdbeFrame *pFrame; /* New vdbe frame to execute in */ - SubProgram *pProgram; /* Sub-program to execute */ - void *t; /* Token identifying trigger */ - - pProgram = pOp->p4.pProgram; - pRt = &aMem[pOp->p3]; - assert( pProgram->nOp>0 ); - - /* If the p5 flag is clear, then recursive invocation of triggers is - ** disabled for backwards compatibility (p5 is set if this sub-program - ** is really a trigger, not a foreign key action, and the flag set - ** and cleared by the "PRAGMA recursive_triggers" command is clear). - ** - ** It is recursive invocation of triggers, at the SQL level, that is - ** disabled. In some cases a single trigger may generate more than one - ** SubProgram (if the trigger may be executed with more than one different - ** ON CONFLICT algorithm). SubProgram structures associated with a - ** single trigger all have the same value for the SubProgram.token - ** variable. */ - if( pOp->p5 ){ - t = pProgram->token; - for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent); - if( pFrame ) break; - } - - if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ - rc = SQLITE_ERROR; - sqlite3VdbeError(p, "too many levels of trigger recursion"); - goto abort_due_to_error; - } - - /* Register pRt is used to store the memory required to save the state - ** of the current program, and the memory required at runtime to execute - ** the trigger program. If this trigger has been fired before, then pRt - ** is already allocated. Otherwise, it must be initialized. */ - if( (pRt->flags&MEM_Blob)==0 ){ - /* SubProgram.nMem is set to the number of memory cells used by the - ** program stored in SubProgram.aOp. As well as these, one memory - ** cell is required for each cursor used by the program. Set local - ** variable nMem (and later, VdbeFrame.nChildMem) to this value. - */ - nMem = pProgram->nMem + pProgram->nCsr; - assert( nMem>0 ); - if( pProgram->nCsr==0 ) nMem++; - nByte = ROUND8(sizeof(VdbeFrame)) - + nMem * sizeof(Mem) - + pProgram->nCsr * sizeof(VdbeCursor*) - + (pProgram->nOp + 7)/8; - pFrame = sqlite3DbMallocZero(db, nByte); - if( !pFrame ){ - goto no_mem; - } - sqlite3VdbeMemRelease(pRt); - pRt->flags = MEM_Blob|MEM_Dyn; - pRt->z = (char*)pFrame; - pRt->n = nByte; - pRt->xDel = sqlite3VdbeFrameMemDel; - - pFrame->v = p; - pFrame->nChildMem = nMem; - pFrame->nChildCsr = pProgram->nCsr; - pFrame->pc = (int)(pOp - aOp); - pFrame->aMem = p->aMem; - pFrame->nMem = p->nMem; - pFrame->apCsr = p->apCsr; - pFrame->nCursor = p->nCursor; - pFrame->aOp = p->aOp; - pFrame->nOp = p->nOp; - pFrame->token = pProgram->token; -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - pFrame->anExec = p->anExec; -#endif -#ifdef SQLITE_DEBUG - pFrame->iFrameMagic = SQLITE_FRAME_MAGIC; -#endif - - pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; - for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ - pMem->flags = MEM_Undefined; - pMem->db = db; - } - }else{ - pFrame = (VdbeFrame*)pRt->z; - assert( pRt->xDel==sqlite3VdbeFrameMemDel ); - assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem - || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) ); - assert( pProgram->nCsr==pFrame->nChildCsr ); - assert( (int)(pOp - aOp)==pFrame->pc ); - } - - p->nFrame++; - pFrame->pParent = p->pFrame; - pFrame->lastRowid = db->lastRowid; - pFrame->nChange = p->nChange; - pFrame->nDbChange = p->db->nChange; - assert( pFrame->pAuxData==0 ); - pFrame->pAuxData = p->pAuxData; - p->pAuxData = 0; - p->nChange = 0; - p->pFrame = pFrame; - p->aMem = aMem = VdbeFrameMem(pFrame); - p->nMem = pFrame->nChildMem; - p->nCursor = (u16)pFrame->nChildCsr; - p->apCsr = (VdbeCursor **)&aMem[p->nMem]; - pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr]; - memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8); - p->aOp = aOp = pProgram->aOp; - p->nOp = pProgram->nOp; -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - p->anExec = 0; -#endif -#ifdef SQLITE_DEBUG - /* Verify that second and subsequent executions of the same trigger do not - ** try to reuse register values from the first use. */ - { - int i; - for(i=0; inMem; i++){ - aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */ - MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */ - } - } -#endif - pOp = &aOp[-1]; - goto check_for_interrupt; -} - -/* Opcode: Param P1 P2 * * * -** -** This opcode is only ever present in sub-programs called via the -** OP_Program instruction. Copy a value currently stored in a memory -** cell of the calling (parent) frame to cell P2 in the current frames -** address space. This is used by trigger programs to access the new.* -** and old.* values. -** -** The address of the cell in the parent frame is determined by adding -** the value of the P1 argument to the value of the P1 argument to the -** calling OP_Program instruction. -*/ -case OP_Param: { /* out2 */ - VdbeFrame *pFrame; - Mem *pIn; - pOut = out2Prerelease(p, pOp); - pFrame = p->pFrame; - pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1]; - sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem); - break; -} - -#endif /* #ifndef SQLITE_OMIT_TRIGGER */ - -#ifndef SQLITE_OMIT_FOREIGN_KEY -/* Opcode: FkCounter P1 P2 * * * -** Synopsis: fkctr[P1]+=P2 -** -** Increment a "constraint counter" by P2 (P2 may be negative or positive). -** If P1 is non-zero, the database constraint counter is incremented -** (deferred foreign key constraints). Otherwise, if P1 is zero, the -** statement counter is incremented (immediate foreign key constraints). -*/ -case OP_FkCounter: { - if( db->flags & SQLITE_DeferFKs ){ - db->nDeferredImmCons += pOp->p2; - }else if( pOp->p1 ){ - db->nDeferredCons += pOp->p2; - }else{ - p->nFkConstraint += pOp->p2; - } - break; -} - -/* Opcode: FkIfZero P1 P2 * * * -** Synopsis: if fkctr[P1]==0 goto P2 -** -** This opcode tests if a foreign key constraint-counter is currently zero. -** If so, jump to instruction P2. Otherwise, fall through to the next -** instruction. -** -** If P1 is non-zero, then the jump is taken if the database constraint-counter -** is zero (the one that counts deferred constraint violations). If P1 is -** zero, the jump is taken if the statement constraint-counter is zero -** (immediate foreign key constraint violations). -*/ -case OP_FkIfZero: { /* jump */ - if( pOp->p1 ){ - VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2); - if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; - }else{ - VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2); - if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2; - } - break; -} -#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ - -#ifndef SQLITE_OMIT_AUTOINCREMENT -/* Opcode: MemMax P1 P2 * * * -** Synopsis: r[P1]=max(r[P1],r[P2]) -** -** P1 is a register in the root frame of this VM (the root frame is -** different from the current frame if this instruction is being executed -** within a sub-program). Set the value of register P1 to the maximum of -** its current value and the value in register P2. -** -** This instruction throws an error if the memory cell is not initially -** an integer. -*/ -case OP_MemMax: { /* in2 */ - VdbeFrame *pFrame; - if( p->pFrame ){ - for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent); - pIn1 = &pFrame->aMem[pOp->p1]; - }else{ - pIn1 = &aMem[pOp->p1]; - } - assert( memIsValid(pIn1) ); - sqlite3VdbeMemIntegerify(pIn1); - pIn2 = &aMem[pOp->p2]; - sqlite3VdbeMemIntegerify(pIn2); - if( pIn1->u.iu.i){ - pIn1->u.i = pIn2->u.i; - } - break; -} -#endif /* SQLITE_OMIT_AUTOINCREMENT */ - -/* Opcode: IfPos P1 P2 P3 * * -** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 -** -** Register P1 must contain an integer. -** If the value of register P1 is 1 or greater, subtract P3 from the -** value in P1 and jump to P2. -** -** If the initial value of register P1 is less than 1, then the -** value is unchanged and control passes through to the next instruction. -*/ -case OP_IfPos: { /* jump, in1 */ - pIn1 = &aMem[pOp->p1]; - assert( pIn1->flags&MEM_Int ); - VdbeBranchTaken( pIn1->u.i>0, 2); - if( pIn1->u.i>0 ){ - pIn1->u.i -= pOp->p3; - goto jump_to_p2; - } - break; -} - -/* Opcode: OffsetLimit P1 P2 P3 * * -** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) -** -** This opcode performs a commonly used computation associated with -** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3] -** holds the offset counter. The opcode computes the combined value -** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2] -** value computed is the total number of rows that will need to be -** visited in order to complete the query. -** -** If r[P3] is zero or negative, that means there is no OFFSET -** and r[P2] is set to be the value of the LIMIT, r[P1]. -** -** if r[P1] is zero or negative, that means there is no LIMIT -** and r[P2] is set to -1. -** -** Otherwise, r[P2] is set to the sum of r[P1] and r[P3]. -*/ -case OP_OffsetLimit: { /* in1, out2, in3 */ - i64 x; - pIn1 = &aMem[pOp->p1]; - pIn3 = &aMem[pOp->p3]; - pOut = out2Prerelease(p, pOp); - assert( pIn1->flags & MEM_Int ); - assert( pIn3->flags & MEM_Int ); - x = pIn1->u.i; - if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){ - /* If the LIMIT is less than or equal to zero, loop forever. This - ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then - ** also loop forever. This is undocumented. In fact, one could argue - ** that the loop should terminate. But assuming 1 billion iterations - ** per second (far exceeding the capabilities of any current hardware) - ** it would take nearly 300 years to actually reach the limit. So - ** looping forever is a reasonable approximation. */ - pOut->u.i = -1; - }else{ - pOut->u.i = x; - } - break; -} - -/* Opcode: IfNotZero P1 P2 * * * -** Synopsis: if r[P1]!=0 then r[P1]--, goto P2 -** -** Register P1 must contain an integer. If the content of register P1 is -** initially greater than zero, then decrement the value in register P1. -** If it is non-zero (negative or positive) and then also jump to P2. -** If register P1 is initially zero, leave it unchanged and fall through. -*/ -case OP_IfNotZero: { /* jump, in1 */ - pIn1 = &aMem[pOp->p1]; - assert( pIn1->flags&MEM_Int ); - VdbeBranchTaken(pIn1->u.i<0, 2); - if( pIn1->u.i ){ - if( pIn1->u.i>0 ) pIn1->u.i--; - goto jump_to_p2; - } - break; -} - -/* Opcode: DecrJumpZero P1 P2 * * * -** Synopsis: if (--r[P1])==0 goto P2 -** -** Register P1 must hold an integer. Decrement the value in P1 -** and jump to P2 if the new value is exactly zero. -*/ -case OP_DecrJumpZero: { /* jump, in1 */ - pIn1 = &aMem[pOp->p1]; - assert( pIn1->flags&MEM_Int ); - if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--; - VdbeBranchTaken(pIn1->u.i==0, 2); - if( pIn1->u.i==0 ) goto jump_to_p2; - break; -} - - -/* Opcode: AggStep * P2 P3 P4 P5 -** Synopsis: accum=r[P3] step(r[P2@P5]) -** -** Execute the xStep function for an aggregate. -** The function has P5 arguments. P4 is a pointer to the -** FuncDef structure that specifies the function. Register P3 is the -** accumulator. -** -** The P5 arguments are taken from register P2 and its -** successors. -*/ -/* Opcode: AggInverse * P2 P3 P4 P5 -** Synopsis: accum=r[P3] inverse(r[P2@P5]) -** -** Execute the xInverse function for an aggregate. -** The function has P5 arguments. P4 is a pointer to the -** FuncDef structure that specifies the function. Register P3 is the -** accumulator. -** -** The P5 arguments are taken from register P2 and its -** successors. -*/ -/* Opcode: AggStep1 P1 P2 P3 P4 P5 -** Synopsis: accum=r[P3] step(r[P2@P5]) -** -** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an -** aggregate. The function has P5 arguments. P4 is a pointer to the -** FuncDef structure that specifies the function. Register P3 is the -** accumulator. -** -** The P5 arguments are taken from register P2 and its -** successors. -** -** This opcode is initially coded as OP_AggStep0. On first evaluation, -** the FuncDef stored in P4 is converted into an sqlite3_context and -** the opcode is changed. In this way, the initialization of the -** sqlite3_context only happens once, instead of on each call to the -** step function. -*/ -case OP_AggInverse: -case OP_AggStep: { - int n; - sqlite3_context *pCtx; - - assert( pOp->p4type==P4_FUNCDEF ); - n = pOp->p5; - assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) ); - assert( pOp->p3p2 || pOp->p3>=pOp->p2+n ); - pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) + - (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*))); - if( pCtx==0 ) goto no_mem; - pCtx->pMem = 0; - pCtx->pOut = (Mem*)&(pCtx->argv[n]); - sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null); - pCtx->pFunc = pOp->p4.pFunc; - pCtx->iOp = (int)(pOp - aOp); - pCtx->pVdbe = p; - pCtx->skipFlag = 0; - pCtx->isError = 0; - pCtx->argc = n; - pOp->p4type = P4_FUNCCTX; - pOp->p4.pCtx = pCtx; - - /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */ - assert( pOp->p1==(pOp->opcode==OP_AggInverse) ); - - pOp->opcode = OP_AggStep1; - /* Fall through into OP_AggStep */ - /* no break */ deliberate_fall_through -} -case OP_AggStep1: { - int i; - sqlite3_context *pCtx; - Mem *pMem; - - assert( pOp->p4type==P4_FUNCCTX ); - pCtx = pOp->p4.pCtx; - pMem = &aMem[pOp->p3]; - -#ifdef SQLITE_DEBUG - if( pOp->p1 ){ - /* This is an OP_AggInverse call. Verify that xStep has always - ** been called at least once prior to any xInverse call. */ - assert( pMem->uTemp==0x1122e0e3 ); - }else{ - /* This is an OP_AggStep call. Mark it as such. */ - pMem->uTemp = 0x1122e0e3; - } -#endif - - /* If this function is inside of a trigger, the register array in aMem[] - ** might change from one evaluation to the next. The next block of code - ** checks to see if the register array has changed, and if so it - ** reinitializes the relavant parts of the sqlite3_context object */ - if( pCtx->pMem != pMem ){ - pCtx->pMem = pMem; - for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; - } - -#ifdef SQLITE_DEBUG - for(i=0; iargc; i++){ - assert( memIsValid(pCtx->argv[i]) ); - REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); - } -#endif - - pMem->n++; - assert( pCtx->pOut->flags==MEM_Null ); - assert( pCtx->isError==0 ); - assert( pCtx->skipFlag==0 ); -#ifndef SQLITE_OMIT_WINDOWFUNC - if( pOp->p1 ){ - (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv); - }else -#endif - (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */ - - if( pCtx->isError ){ - if( pCtx->isError>0 ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut)); - rc = pCtx->isError; - } - if( pCtx->skipFlag ){ - assert( pOp[-1].opcode==OP_CollSeq ); - i = pOp[-1].p1; - if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); - pCtx->skipFlag = 0; - } - sqlite3VdbeMemRelease(pCtx->pOut); - pCtx->pOut->flags = MEM_Null; - pCtx->isError = 0; - if( rc ) goto abort_due_to_error; - } - assert( pCtx->pOut->flags==MEM_Null ); - assert( pCtx->skipFlag==0 ); - break; -} - -/* Opcode: AggFinal P1 P2 * P4 * -** Synopsis: accum=r[P1] N=P2 -** -** P1 is the memory location that is the accumulator for an aggregate -** or window function. Execute the finalizer function -** for an aggregate and store the result in P1. -** -** P2 is the number of arguments that the step function takes and -** P4 is a pointer to the FuncDef for this function. The P2 -** argument is not used by this opcode. It is only there to disambiguate -** functions that can take varying numbers of arguments. The -** P4 argument is only needed for the case where -** the step function was not previously called. -*/ -/* Opcode: AggValue * P2 P3 P4 * -** Synopsis: r[P3]=value N=P2 -** -** Invoke the xValue() function and store the result in register P3. -** -** P2 is the number of arguments that the step function takes and -** P4 is a pointer to the FuncDef for this function. The P2 -** argument is not used by this opcode. It is only there to disambiguate -** functions that can take varying numbers of arguments. The -** P4 argument is only needed for the case where -** the step function was not previously called. -*/ -case OP_AggValue: -case OP_AggFinal: { - Mem *pMem; - assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); - assert( pOp->p3==0 || pOp->opcode==OP_AggValue ); - pMem = &aMem[pOp->p1]; - assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); -#ifndef SQLITE_OMIT_WINDOWFUNC - if( pOp->p3 ){ - memAboutToChange(p, &aMem[pOp->p3]); - rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc); - pMem = &aMem[pOp->p3]; - }else -#endif - { - rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); - } - - if( rc ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem)); - goto abort_due_to_error; - } - sqlite3VdbeChangeEncoding(pMem, encoding); - UPDATE_MAX_BLOBSIZE(pMem); - if( sqlite3VdbeMemTooBig(pMem) ){ - goto too_big; - } - break; -} - -#ifndef SQLITE_OMIT_WAL -/* Opcode: Checkpoint P1 P2 P3 * * -** -** Checkpoint database P1. This is a no-op if P1 is not currently in -** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL, -** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns -** SQLITE_BUSY or not, respectively. Write the number of pages in the -** WAL after the checkpoint into mem[P3+1] and the number of pages -** in the WAL that have been checkpointed after the checkpoint -** completes into mem[P3+2]. However on an error, mem[P3+1] and -** mem[P3+2] are initialized to -1. -*/ -case OP_Checkpoint: { - int i; /* Loop counter */ - int aRes[3]; /* Results */ - Mem *pMem; /* Write results here */ - - assert( p->readOnly==0 ); - aRes[0] = 0; - aRes[1] = aRes[2] = -1; - assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE - || pOp->p2==SQLITE_CHECKPOINT_FULL - || pOp->p2==SQLITE_CHECKPOINT_RESTART - || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE - ); - rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); - if( rc ){ - if( rc!=SQLITE_BUSY ) goto abort_due_to_error; - rc = SQLITE_OK; - aRes[0] = 1; - } - for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){ - sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]); - } - break; -}; -#endif - -#ifndef SQLITE_OMIT_PRAGMA -/* Opcode: JournalMode P1 P2 P3 * * -** -** Change the journal mode of database P1 to P3. P3 must be one of the -** PAGER_JOURNALMODE_XXX values. If changing between the various rollback -** modes (delete, truncate, persist, off and memory), this is a simple -** operation. No IO is required. -** -** If changing into or out of WAL mode the procedure is more complicated. -** -** Write a string containing the final journal-mode to register P2. -*/ -case OP_JournalMode: { /* out2 */ - Btree *pBt; /* Btree to change journal mode of */ - Pager *pPager; /* Pager associated with pBt */ - int eNew; /* New journal mode */ - int eOld; /* The old journal mode */ -#ifndef SQLITE_OMIT_WAL - const char *zFilename; /* Name of database file for pPager */ -#endif - - pOut = out2Prerelease(p, pOp); - eNew = pOp->p3; - assert( eNew==PAGER_JOURNALMODE_DELETE - || eNew==PAGER_JOURNALMODE_TRUNCATE - || eNew==PAGER_JOURNALMODE_PERSIST - || eNew==PAGER_JOURNALMODE_OFF - || eNew==PAGER_JOURNALMODE_MEMORY - || eNew==PAGER_JOURNALMODE_WAL - || eNew==PAGER_JOURNALMODE_QUERY - ); - assert( pOp->p1>=0 && pOp->p1nDb ); - assert( p->readOnly==0 ); - - pBt = db->aDb[pOp->p1].pBt; - pPager = sqlite3BtreePager(pBt); - eOld = sqlite3PagerGetJournalMode(pPager); - if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld; - if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld; - -#ifndef SQLITE_OMIT_WAL - zFilename = sqlite3PagerFilename(pPager, 1); - - /* Do not allow a transition to journal_mode=WAL for a database - ** in temporary storage or if the VFS does not support shared memory - */ - if( eNew==PAGER_JOURNALMODE_WAL - && (sqlite3Strlen30(zFilename)==0 /* Temp file */ - || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */ - ){ - eNew = eOld; - } - - if( (eNew!=eOld) - && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL) - ){ - if( !db->autoCommit || db->nVdbeRead>1 ){ - rc = SQLITE_ERROR; - sqlite3VdbeError(p, - "cannot change %s wal mode from within a transaction", - (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of") - ); - goto abort_due_to_error; - }else{ - - if( eOld==PAGER_JOURNALMODE_WAL ){ - /* If leaving WAL mode, close the log file. If successful, the call - ** to PagerCloseWal() checkpoints and deletes the write-ahead-log - ** file. An EXCLUSIVE lock may still be held on the database file - ** after a successful return. - */ - rc = sqlite3PagerCloseWal(pPager, db); - if( rc==SQLITE_OK ){ - sqlite3PagerSetJournalMode(pPager, eNew); - } - }else if( eOld==PAGER_JOURNALMODE_MEMORY ){ - /* Cannot transition directly from MEMORY to WAL. Use mode OFF - ** as an intermediate */ - sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF); - } - - /* Open a transaction on the database file. Regardless of the journal - ** mode, this transaction always uses a rollback journal. - */ - assert( sqlite3BtreeIsInTrans(pBt)==0 ); - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1)); - } - } - } -#endif /* ifndef SQLITE_OMIT_WAL */ - - if( rc ) eNew = eOld; - eNew = sqlite3PagerSetJournalMode(pPager, eNew); - - pOut->flags = MEM_Str|MEM_Static|MEM_Term; - pOut->z = (char *)sqlite3JournalModename(eNew); - pOut->n = sqlite3Strlen30(pOut->z); - pOut->enc = SQLITE_UTF8; - sqlite3VdbeChangeEncoding(pOut, encoding); - if( rc ) goto abort_due_to_error; - break; -}; -#endif /* SQLITE_OMIT_PRAGMA */ - -#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) -/* Opcode: Vacuum P1 P2 * * * -** -** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more -** for an attached database. The "temp" database may not be vacuumed. -** -** If P2 is not zero, then it is a register holding a string which is -** the file into which the result of vacuum should be written. When -** P2 is zero, the vacuum overwrites the original database. -*/ -case OP_Vacuum: { - assert( p->readOnly==0 ); - rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1, - pOp->p2 ? &aMem[pOp->p2] : 0); - if( rc ) goto abort_due_to_error; - break; -} -#endif - -#if !defined(SQLITE_OMIT_AUTOVACUUM) -/* Opcode: IncrVacuum P1 P2 * * * -** -** Perform a single step of the incremental vacuum procedure on -** the P1 database. If the vacuum has finished, jump to instruction -** P2. Otherwise, fall through to the next instruction. -*/ -case OP_IncrVacuum: { /* jump */ - Btree *pBt; - - assert( pOp->p1>=0 && pOp->p1nDb ); - assert( DbMaskTest(p->btreeMask, pOp->p1) ); - assert( p->readOnly==0 ); - pBt = db->aDb[pOp->p1].pBt; - rc = sqlite3BtreeIncrVacuum(pBt); - VdbeBranchTaken(rc==SQLITE_DONE,2); - if( rc ){ - if( rc!=SQLITE_DONE ) goto abort_due_to_error; - rc = SQLITE_OK; - goto jump_to_p2; - } - break; -} -#endif - -/* Opcode: Expire P1 P2 * * * -** -** Cause precompiled statements to expire. When an expired statement -** is executed using sqlite3_step() it will either automatically -** reprepare itself (if it was originally created using sqlite3_prepare_v2()) -** or it will fail with SQLITE_SCHEMA. -** -** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, -** then only the currently executing statement is expired. -** -** If P2 is 0, then SQL statements are expired immediately. If P2 is 1, -** then running SQL statements are allowed to continue to run to completion. -** The P2==1 case occurs when a CREATE INDEX or similar schema change happens -** that might help the statement run faster but which does not affect the -** correctness of operation. -*/ -case OP_Expire: { - assert( pOp->p2==0 || pOp->p2==1 ); - if( !pOp->p1 ){ - sqlite3ExpirePreparedStatements(db, pOp->p2); - }else{ - p->expired = pOp->p2+1; - } - break; -} - -/* Opcode: CursorLock P1 * * * * -** -** Lock the btree to which cursor P1 is pointing so that the btree cannot be -** written by an other cursor. -*/ -case OP_CursorLock: { - VdbeCursor *pC; - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - sqlite3BtreeCursorPin(pC->uc.pCursor); - break; -} - -/* Opcode: CursorUnlock P1 * * * * -** -** Unlock the btree to which cursor P1 is pointing so that it can be -** written by other cursors. -*/ -case OP_CursorUnlock: { - VdbeCursor *pC; - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( pC->eCurType==CURTYPE_BTREE ); - sqlite3BtreeCursorUnpin(pC->uc.pCursor); - break; -} - -#ifndef SQLITE_OMIT_SHARED_CACHE -/* Opcode: TableLock P1 P2 P3 P4 * -** Synopsis: iDb=P1 root=P2 write=P3 -** -** Obtain a lock on a particular table. This instruction is only used when -** the shared-cache feature is enabled. -** -** P1 is the index of the database in sqlite3.aDb[] of the database -** on which the lock is acquired. A readlock is obtained if P3==0 or -** a write lock if P3==1. -** -** P2 contains the root-page of the table to lock. -** -** P4 contains a pointer to the name of the table being locked. This is only -** used to generate an error message if the lock cannot be obtained. -*/ -case OP_TableLock: { - u8 isWriteLock = (u8)pOp->p3; - if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){ - int p1 = pOp->p1; - assert( p1>=0 && p1nDb ); - assert( DbMaskTest(p->btreeMask, p1) ); - assert( isWriteLock==0 || isWriteLock==1 ); - rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); - if( rc ){ - if( (rc&0xFF)==SQLITE_LOCKED ){ - const char *z = pOp->p4.z; - sqlite3VdbeError(p, "database table is locked: %s", z); - } - goto abort_due_to_error; - } - } - break; -} -#endif /* SQLITE_OMIT_SHARED_CACHE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VBegin * * * P4 * -** -** P4 may be a pointer to an sqlite3_vtab structure. If so, call the -** xBegin method for that table. -** -** Also, whether or not P4 is set, check that this is not being called from -** within a callback to a virtual table xSync() method. If it is, the error -** code will be set to SQLITE_LOCKED. -*/ -case OP_VBegin: { - VTable *pVTab; - pVTab = pOp->p4.pVtab; - rc = sqlite3VtabBegin(db, pVTab); - if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab); - if( rc ) goto abort_due_to_error; - break; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VCreate P1 P2 * * * -** -** P2 is a register that holds the name of a virtual table in database -** P1. Call the xCreate method for that table. -*/ -case OP_VCreate: { - Mem sMem; /* For storing the record being decoded */ - const char *zTab; /* Name of the virtual table */ - - memset(&sMem, 0, sizeof(sMem)); - sMem.db = db; - /* Because P2 is always a static string, it is impossible for the - ** sqlite3VdbeMemCopy() to fail */ - assert( (aMem[pOp->p2].flags & MEM_Str)!=0 ); - assert( (aMem[pOp->p2].flags & MEM_Static)!=0 ); - rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]); - assert( rc==SQLITE_OK ); - zTab = (const char*)sqlite3_value_text(&sMem); - assert( zTab || db->mallocFailed ); - if( zTab ){ - rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg); - } - sqlite3VdbeMemRelease(&sMem); - if( rc ) goto abort_due_to_error; - break; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VDestroy P1 * * P4 * -** -** P4 is the name of a virtual table in database P1. Call the xDestroy method -** of that table. -*/ -case OP_VDestroy: { - db->nVDestroy++; - rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); - db->nVDestroy--; - assert( p->errorAction==OE_Abort && p->usesStmtJournal ); - if( rc ) goto abort_due_to_error; - break; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VOpen P1 * * P4 * -** -** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. -** P1 is a cursor number. This opcode opens a cursor to the virtual -** table and stores that cursor in P1. -*/ -case OP_VOpen: { - VdbeCursor *pCur; - sqlite3_vtab_cursor *pVCur; - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; - - assert( p->bIsReader ); - pCur = 0; - pVCur = 0; - pVtab = pOp->p4.pVtab->pVtab; - if( pVtab==0 || NEVER(pVtab->pModule==0) ){ - rc = SQLITE_LOCKED; - goto abort_due_to_error; - } - pModule = pVtab->pModule; - rc = pModule->xOpen(pVtab, &pVCur); - sqlite3VtabImportErrmsg(p, pVtab); - if( rc ) goto abort_due_to_error; - - /* Initialize sqlite3_vtab_cursor base class */ - pVCur->pVtab = pVtab; - - /* Initialize vdbe cursor object */ - pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB); - if( pCur ){ - pCur->uc.pVCur = pVCur; - pVtab->nRef++; - }else{ - assert( db->mallocFailed ); - pModule->xClose(pVCur); - goto no_mem; - } - break; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VFilter P1 P2 P3 P4 * -** Synopsis: iplan=r[P3] zplan='P4' -** -** P1 is a cursor opened using VOpen. P2 is an address to jump to if -** the filtered result set is empty. -** -** P4 is either NULL or a string that was generated by the xBestIndex -** method of the module. The interpretation of the P4 string is left -** to the module implementation. -** -** This opcode invokes the xFilter method on the virtual table specified -** by P1. The integer query plan parameter to xFilter is stored in register -** P3. Register P3+1 stores the argc parameter to be passed to the -** xFilter method. Registers P3+2..P3+1+argc are the argc -** additional parameters which are passed to -** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. -** -** A jump is made to P2 if the result set after filtering would be empty. -*/ -case OP_VFilter: { /* jump */ - int nArg; - int iQuery; - const sqlite3_module *pModule; - Mem *pQuery; - Mem *pArgc; - sqlite3_vtab_cursor *pVCur; - sqlite3_vtab *pVtab; - VdbeCursor *pCur; - int res; - int i; - Mem **apArg; - - pQuery = &aMem[pOp->p3]; - pArgc = &pQuery[1]; - pCur = p->apCsr[pOp->p1]; - assert( memIsValid(pQuery) ); - REGISTER_TRACE(pOp->p3, pQuery); - assert( pCur->eCurType==CURTYPE_VTAB ); - pVCur = pCur->uc.pVCur; - pVtab = pVCur->pVtab; - pModule = pVtab->pModule; - - /* Grab the index number and argc parameters */ - assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); - nArg = (int)pArgc->u.i; - iQuery = (int)pQuery->u.i; - - /* Invoke the xFilter method */ - res = 0; - apArg = p->apArg; - for(i = 0; ixFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg); - sqlite3VtabImportErrmsg(p, pVtab); - if( rc ) goto abort_due_to_error; - res = pModule->xEof(pVCur); - pCur->nullRow = 0; - VdbeBranchTaken(res!=0,2); - if( res ) goto jump_to_p2; - break; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VColumn P1 P2 P3 * P5 -** Synopsis: r[P3]=vcolumn(P2) -** -** Store in register P3 the value of the P2-th column of -** the current row of the virtual-table of cursor P1. -** -** If the VColumn opcode is being used to fetch the value of -** an unchanging column during an UPDATE operation, then the P5 -** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange() -** function to return true inside the xColumn method of the virtual -** table implementation. The P5 column might also contain other -** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are -** unused by OP_VColumn. -*/ -case OP_VColumn: { - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; - Mem *pDest; - sqlite3_context sContext; - - VdbeCursor *pCur = p->apCsr[pOp->p1]; - assert( pCur->eCurType==CURTYPE_VTAB ); - assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - pDest = &aMem[pOp->p3]; - memAboutToChange(p, pDest); - if( pCur->nullRow ){ - sqlite3VdbeMemSetNull(pDest); - break; - } - pVtab = pCur->uc.pVCur->pVtab; - pModule = pVtab->pModule; - assert( pModule->xColumn ); - memset(&sContext, 0, sizeof(sContext)); - sContext.pOut = pDest; - assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 ); - if( pOp->p5 & OPFLAG_NOCHNG ){ - sqlite3VdbeMemSetNull(pDest); - pDest->flags = MEM_Null|MEM_Zero; - pDest->u.nZero = 0; - }else{ - MemSetTypeFlag(pDest, MEM_Null); - } - rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2); - sqlite3VtabImportErrmsg(p, pVtab); - if( sContext.isError>0 ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest)); - rc = sContext.isError; - } - sqlite3VdbeChangeEncoding(pDest, encoding); - REGISTER_TRACE(pOp->p3, pDest); - UPDATE_MAX_BLOBSIZE(pDest); - - if( sqlite3VdbeMemTooBig(pDest) ){ - goto too_big; - } - if( rc ) goto abort_due_to_error; - break; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VNext P1 P2 * * * -** -** Advance virtual table P1 to the next row in its result set and -** jump to instruction P2. Or, if the virtual table has reached -** the end of its result set, then fall through to the next instruction. -*/ -case OP_VNext: { /* jump */ - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; - int res; - VdbeCursor *pCur; - - res = 0; - pCur = p->apCsr[pOp->p1]; - assert( pCur->eCurType==CURTYPE_VTAB ); - if( pCur->nullRow ){ - break; - } - pVtab = pCur->uc.pVCur->pVtab; - pModule = pVtab->pModule; - assert( pModule->xNext ); - - /* Invoke the xNext() method of the module. There is no way for the - ** underlying implementation to return an error if one occurs during - ** xNext(). Instead, if an error occurs, true is returned (indicating that - ** data is available) and the error code returned when xColumn or - ** some other method is next invoked on the save virtual table cursor. - */ - rc = pModule->xNext(pCur->uc.pVCur); - sqlite3VtabImportErrmsg(p, pVtab); - if( rc ) goto abort_due_to_error; - res = pModule->xEof(pCur->uc.pVCur); - VdbeBranchTaken(!res,2); - if( !res ){ - /* If there is data, jump to P2 */ - goto jump_to_p2_and_check_for_interrupt; - } - goto check_for_interrupt; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VRename P1 * * P4 * -** -** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. -** This opcode invokes the corresponding xRename method. The value -** in register P1 is passed as the zName argument to the xRename method. -*/ -case OP_VRename: { - sqlite3_vtab *pVtab; - Mem *pName; - int isLegacy; - - isLegacy = (db->flags & SQLITE_LegacyAlter); - db->flags |= SQLITE_LegacyAlter; - pVtab = pOp->p4.pVtab->pVtab; - pName = &aMem[pOp->p1]; - assert( pVtab->pModule->xRename ); - assert( memIsValid(pName) ); - assert( p->readOnly==0 ); - REGISTER_TRACE(pOp->p1, pName); - assert( pName->flags & MEM_Str ); - testcase( pName->enc==SQLITE_UTF8 ); - testcase( pName->enc==SQLITE_UTF16BE ); - testcase( pName->enc==SQLITE_UTF16LE ); - rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8); - if( rc ) goto abort_due_to_error; - rc = pVtab->pModule->xRename(pVtab, pName->z); - if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter; - sqlite3VtabImportErrmsg(p, pVtab); - p->expired = 0; - if( rc ) goto abort_due_to_error; - break; -} -#endif - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VUpdate P1 P2 P3 P4 P5 -** Synopsis: data=r[P3@P2] -** -** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. -** This opcode invokes the corresponding xUpdate method. P2 values -** are contiguous memory cells starting at P3 to pass to the xUpdate -** invocation. The value in register (P3+P2-1) corresponds to the -** p2th element of the argv array passed to xUpdate. -** -** The xUpdate method will do a DELETE or an INSERT or both. -** The argv[0] element (which corresponds to memory cell P3) -** is the rowid of a row to delete. If argv[0] is NULL then no -** deletion occurs. The argv[1] element is the rowid of the new -** row. This can be NULL to have the virtual table select the new -** rowid for itself. The subsequent elements in the array are -** the values of columns in the new row. -** -** If P2==1 then no insert is performed. argv[0] is the rowid of -** a row to delete. -** -** P1 is a boolean flag. If it is set to true and the xUpdate call -** is successful, then the value returned by sqlite3_last_insert_rowid() -** is set to the value of the rowid for the row just inserted. -** -** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to -** apply in the case of a constraint failure on an insert or update. -*/ -case OP_VUpdate: { - sqlite3_vtab *pVtab; - const sqlite3_module *pModule; - int nArg; - int i; - sqlite_int64 rowid; - Mem **apArg; - Mem *pX; - - assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback - || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace - ); - assert( p->readOnly==0 ); - if( db->mallocFailed ) goto no_mem; - sqlite3VdbeIncrWriteCounter(p, 0); - pVtab = pOp->p4.pVtab->pVtab; - if( pVtab==0 || NEVER(pVtab->pModule==0) ){ - rc = SQLITE_LOCKED; - goto abort_due_to_error; - } - pModule = pVtab->pModule; - nArg = pOp->p2; - assert( pOp->p4type==P4_VTAB ); - if( ALWAYS(pModule->xUpdate) ){ - u8 vtabOnConflict = db->vtabOnConflict; - apArg = p->apArg; - pX = &aMem[pOp->p3]; - for(i=0; ivtabOnConflict = pOp->p5; - rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); - db->vtabOnConflict = vtabOnConflict; - sqlite3VtabImportErrmsg(p, pVtab); - if( rc==SQLITE_OK && pOp->p1 ){ - assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); - db->lastRowid = rowid; - } - if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){ - if( pOp->p5==OE_Ignore ){ - rc = SQLITE_OK; - }else{ - p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5); - } - }else{ - p->nChange++; - } - if( rc ) goto abort_due_to_error; - } - break; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_PAGER_PRAGMAS -/* Opcode: Pagecount P1 P2 * * * -** -** Write the current number of pages in database P1 to memory cell P2. -*/ -case OP_Pagecount: { /* out2 */ - pOut = out2Prerelease(p, pOp); - pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt); - break; -} -#endif - - -#ifndef SQLITE_OMIT_PAGER_PRAGMAS -/* Opcode: MaxPgcnt P1 P2 P3 * * -** -** Try to set the maximum page count for database P1 to the value in P3. -** Do not let the maximum page count fall below the current page count and -** do not change the maximum page count value if P3==0. -** -** Store the maximum page count after the change in register P2. -*/ -case OP_MaxPgcnt: { /* out2 */ - unsigned int newMax; - Btree *pBt; - - pOut = out2Prerelease(p, pOp); - pBt = db->aDb[pOp->p1].pBt; - newMax = 0; - if( pOp->p3 ){ - newMax = sqlite3BtreeLastPage(pBt); - if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3; - } - pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax); - break; -} -#endif - -/* Opcode: Function P1 P2 P3 P4 * -** Synopsis: r[P3]=func(r[P2@NP]) -** -** Invoke a user function (P4 is a pointer to an sqlite3_context object that -** contains a pointer to the function to be run) with arguments taken -** from register P2 and successors. The number of arguments is in -** the sqlite3_context object that P4 points to. -** The result of the function is stored -** in register P3. Register P3 must not be one of the function inputs. -** -** P1 is a 32-bit bitmask indicating whether or not each argument to the -** function was determined to be constant at compile time. If the first -** argument was constant then bit 0 of P1 is set. This is used to determine -** whether meta data associated with a user function argument using the -** sqlite3_set_auxdata() API may be safely retained until the next -** invocation of this opcode. -** -** See also: AggStep, AggFinal, PureFunc -*/ -/* Opcode: PureFunc P1 P2 P3 P4 * -** Synopsis: r[P3]=func(r[P2@NP]) -** -** Invoke a user function (P4 is a pointer to an sqlite3_context object that -** contains a pointer to the function to be run) with arguments taken -** from register P2 and successors. The number of arguments is in -** the sqlite3_context object that P4 points to. -** The result of the function is stored -** in register P3. Register P3 must not be one of the function inputs. -** -** P1 is a 32-bit bitmask indicating whether or not each argument to the -** function was determined to be constant at compile time. If the first -** argument was constant then bit 0 of P1 is set. This is used to determine -** whether meta data associated with a user function argument using the -** sqlite3_set_auxdata() API may be safely retained until the next -** invocation of this opcode. -** -** This opcode works exactly like OP_Function. The only difference is in -** its name. This opcode is used in places where the function must be -** purely non-deterministic. Some built-in date/time functions can be -** either determinitic of non-deterministic, depending on their arguments. -** When those function are used in a non-deterministic way, they will check -** to see if they were called using OP_PureFunc instead of OP_Function, and -** if they were, they throw an error. -** -** See also: AggStep, AggFinal, Function -*/ -case OP_PureFunc: /* group */ -case OP_Function: { /* group */ - int i; - sqlite3_context *pCtx; - - assert( pOp->p4type==P4_FUNCCTX ); - pCtx = pOp->p4.pCtx; - - /* If this function is inside of a trigger, the register array in aMem[] - ** might change from one evaluation to the next. The next block of code - ** checks to see if the register array has changed, and if so it - ** reinitializes the relavant parts of the sqlite3_context object */ - pOut = &aMem[pOp->p3]; - if( pCtx->pOut != pOut ){ - pCtx->pVdbe = p; - pCtx->pOut = pOut; - for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; - } - assert( pCtx->pVdbe==p ); - - memAboutToChange(p, pOut); -#ifdef SQLITE_DEBUG - for(i=0; iargc; i++){ - assert( memIsValid(pCtx->argv[i]) ); - REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]); - } -#endif - MemSetTypeFlag(pOut, MEM_Null); - assert( pCtx->isError==0 ); - (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ - - /* If the function returned an error, throw an exception */ - if( pCtx->isError ){ - if( pCtx->isError>0 ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut)); - rc = pCtx->isError; - } - sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); - pCtx->isError = 0; - if( rc ) goto abort_due_to_error; - } - - /* Copy the result of the function into register P3 */ - if( pOut->flags & (MEM_Str|MEM_Blob) ){ - sqlite3VdbeChangeEncoding(pOut, encoding); - if( sqlite3VdbeMemTooBig(pOut) ) goto too_big; - } - - REGISTER_TRACE(pOp->p3, pOut); - UPDATE_MAX_BLOBSIZE(pOut); - break; -} - -/* Opcode: Trace P1 P2 * P4 * -** -** Write P4 on the statement trace output if statement tracing is -** enabled. -** -** Operand P1 must be 0x7fffffff and P2 must positive. -*/ -/* Opcode: Init P1 P2 P3 P4 * -** Synopsis: Start at P2 -** -** Programs contain a single instance of this opcode as the very first -** opcode. -** -** If tracing is enabled (by the sqlite3_trace()) interface, then -** the UTF-8 string contained in P4 is emitted on the trace callback. -** Or if P4 is blank, use the string returned by sqlite3_sql(). -** -** If P2 is not zero, jump to instruction P2. -** -** Increment the value of P1 so that OP_Once opcodes will jump the -** first time they are evaluated for this run. -** -** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT -** error is encountered. -*/ -case OP_Trace: -case OP_Init: { /* jump */ - int i; -#ifndef SQLITE_OMIT_TRACE - char *zTrace; -#endif - - /* If the P4 argument is not NULL, then it must be an SQL comment string. - ** The "--" string is broken up to prevent false-positives with srcck1.c. - ** - ** This assert() provides evidence for: - ** EVIDENCE-OF: R-50676-09860 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. - */ - assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 ); - - /* OP_Init is always instruction 0 */ - assert( pOp==p->aOp || pOp->opcode==OP_Trace ); - -#ifndef SQLITE_OMIT_TRACE - if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0 - && !p->doingRerun - && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 - ){ -#ifndef SQLITE_OMIT_DEPRECATED - if( db->mTrace & SQLITE_TRACE_LEGACY ){ - char *z = sqlite3VdbeExpandSql(p, zTrace); - db->trace.xLegacy(db->pTraceArg, z); - sqlite3_free(z); - }else -#endif - if( db->nVdbeExec>1 ){ - char *z = sqlite3MPrintf(db, "-- %s", zTrace); - (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z); - sqlite3DbFree(db, z); - }else{ - (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace); - } - } -#ifdef SQLITE_USE_FCNTL_TRACE - zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql); - if( zTrace ){ - int j; - for(j=0; jnDb; j++){ - if( DbMaskTest(p->btreeMask, j)==0 ) continue; - sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace); - } - } -#endif /* SQLITE_USE_FCNTL_TRACE */ -#ifdef SQLITE_DEBUG - if( (db->flags & SQLITE_SqlTrace)!=0 - && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 - ){ - sqlite3DebugPrintf("SQL-trace: %s\n", zTrace); - } -#endif /* SQLITE_DEBUG */ -#endif /* SQLITE_OMIT_TRACE */ - assert( pOp->p2>0 ); - if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){ - if( pOp->opcode==OP_Trace ) break; - for(i=1; inOp; i++){ - if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0; - } - pOp->p1 = 0; - } - pOp->p1++; - p->aCounter[SQLITE_STMTSTATUS_RUN]++; - goto jump_to_p2; -} - -#ifdef SQLITE_ENABLE_CURSOR_HINTS -/* Opcode: CursorHint P1 * * P4 * -** -** Provide a hint to cursor P1 that it only needs to return rows that -** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer -** to values currently held in registers. TK_COLUMN terms in the P4 -** expression refer to columns in the b-tree to which cursor P1 is pointing. -*/ -case OP_CursorHint: { - VdbeCursor *pC; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - assert( pOp->p4type==P4_EXPR ); - pC = p->apCsr[pOp->p1]; - if( pC ){ - assert( pC->eCurType==CURTYPE_BTREE ); - sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, - pOp->p4.pExpr, aMem); - } - break; -} -#endif /* SQLITE_ENABLE_CURSOR_HINTS */ - -#ifdef SQLITE_DEBUG -/* Opcode: Abortable * * * * * -** -** Verify that an Abort can happen. Assert if an Abort at this point -** might cause database corruption. This opcode only appears in debugging -** builds. -** -** An Abort is safe if either there have been no writes, or if there is -** an active statement journal. -*/ -case OP_Abortable: { - sqlite3VdbeAssertAbortable(p); - break; -} -#endif - -#ifdef SQLITE_DEBUG -/* Opcode: ReleaseReg P1 P2 P3 * P5 -** Synopsis: release r[P1@P2] mask P3 -** -** Release registers from service. Any content that was in the -** the registers is unreliable after this opcode completes. -** -** The registers released will be the P2 registers starting at P1, -** except if bit ii of P3 set, then do not release register P1+ii. -** In other words, P3 is a mask of registers to preserve. -** -** Releasing a register clears the Mem.pScopyFrom pointer. That means -** that if the content of the released register was set using OP_SCopy, -** a change to the value of the source register for the OP_SCopy will no longer -** generate an assertion fault in sqlite3VdbeMemAboutToChange(). -** -** If P5 is set, then all released registers have their type set -** to MEM_Undefined so that any subsequent attempt to read the released -** register (before it is reinitialized) will generate an assertion fault. -** -** P5 ought to be set on every call to this opcode. -** However, there are places in the code generator will release registers -** before their are used, under the (valid) assumption that the registers -** will not be reallocated for some other purpose before they are used and -** hence are safe to release. -** -** This opcode is only available in testing and debugging builds. It is -** not generated for release builds. The purpose of this opcode is to help -** validate the generated bytecode. This opcode does not actually contribute -** to computing an answer. -*/ -case OP_ReleaseReg: { - Mem *pMem; - int i; - u32 constMask; - assert( pOp->p1>0 ); - assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 ); - pMem = &aMem[pOp->p1]; - constMask = pOp->p3; - for(i=0; ip2; i++, pMem++){ - if( i>=32 || (constMask & MASKBIT32(i))==0 ){ - pMem->pScopyFrom = 0; - if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined); - } - } - break; -} -#endif - -/* Opcode: Noop * * * * * -** -** Do nothing. This instruction is often useful as a jump -** destination. -*/ -/* -** The magic Explain opcode are only inserted when explain==2 (which -** is to say when the EXPLAIN QUERY PLAN syntax is used.) -** This opcode records information from the optimizer. It is the -** the same as a no-op. This opcodesnever appears in a real VM program. -*/ -default: { /* This is really OP_Noop, OP_Explain */ - assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain ); - - break; -} - -/***************************************************************************** -** The cases of the switch statement above this line should all be indented -** by 6 spaces. But the left-most 6 spaces have been removed to improve the -** readability. From this point on down, the normal indentation rules are -** restored. -*****************************************************************************/ - } - -#ifdef VDBE_PROFILE - { - u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime(); - if( endTime>start ) pOrigOp->cycles += endTime - start; - pOrigOp->cnt++; - } -#endif - - /* The following code adds nothing to the actual functionality - ** of the program. It is only here for testing and debugging. - ** On the other hand, it does burn CPU cycles every time through - ** the evaluator loop. So we can leave it out when NDEBUG is defined. - */ -#ifndef NDEBUG - assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] ); - -#ifdef SQLITE_DEBUG - if( db->flags & SQLITE_VdbeTrace ){ - u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode]; - if( rc!=0 ) printf("rc=%d\n",rc); - if( opProperty & (OPFLG_OUT2) ){ - registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]); - } - if( opProperty & OPFLG_OUT3 ){ - registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]); - } - if( opProperty==0xff ){ - /* Never happens. This code exists to avoid a harmless linkage - ** warning aboud sqlite3VdbeRegisterDump() being defined but not - ** used. */ - sqlite3VdbeRegisterDump(p); - } - } -#endif /* SQLITE_DEBUG */ -#endif /* NDEBUG */ - } /* The end of the for(;;) loop the loops through opcodes */ - - /* If we reach this point, it means that execution is finished with - ** an error of some kind. - */ -abort_due_to_error: - if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT; - assert( rc ); - if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){ - sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); - } - p->rc = rc; - sqlite3SystemError(db, rc); - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(rc, "statement aborts at %d: [%s] %s", - (int)(pOp - aOp), p->zSql, p->zErrMsg); - sqlite3VdbeHalt(p); - if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db); - rc = SQLITE_ERROR; - if( resetSchemaOnFault>0 ){ - sqlite3ResetOneSchema(db, resetSchemaOnFault-1); - } - - /* This is the only way out of this procedure. We have to - ** release the mutexes on btrees that were acquired at the - ** top. */ -vdbe_return: -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - while( nVmStep>=nProgressLimit && db->xProgress!=0 ){ - nProgressLimit += db->nProgressOps; - if( db->xProgress(db->pProgressArg) ){ - nProgressLimit = LARGEST_UINT64; - rc = SQLITE_INTERRUPT; - goto abort_due_to_error; - } - } -#endif - p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep; - sqlite3VdbeLeave(p); - assert( rc!=SQLITE_OK || nExtraDelete==0 - || sqlite3_strlike("DELETE%",p->zSql,0)!=0 - ); - return rc; - - /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH - ** is encountered. - */ -too_big: - sqlite3VdbeError(p, "string or blob too big"); - rc = SQLITE_TOOBIG; - goto abort_due_to_error; - - /* Jump to here if a malloc() fails. - */ -no_mem: - sqlite3OomFault(db); - sqlite3VdbeError(p, "out of memory"); - rc = SQLITE_NOMEM_BKPT; - goto abort_due_to_error; - - /* Jump to here if the sqlite3_interrupt() API sets the interrupt - ** flag. - */ -abort_due_to_interrupt: - assert( AtomicLoad(&db->u1.isInterrupted) ); - rc = SQLITE_INTERRUPT; - goto abort_due_to_error; -} - - -/************** End of vdbe.c ************************************************/ -/************** Begin file vdbeblob.c ****************************************/ -/* -** 2007 May 1 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains code used to implement incremental BLOB I/O. -*/ - -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -#ifndef SQLITE_OMIT_INCRBLOB - -/* -** Valid sqlite3_blob* handles point to Incrblob structures. -*/ -typedef struct Incrblob Incrblob; -struct Incrblob { - int nByte; /* Size of open blob, in bytes */ - int iOffset; /* Byte offset of blob in cursor data */ - u16 iCol; /* Table column this handle is open on */ - BtCursor *pCsr; /* Cursor pointing at blob row */ - sqlite3_stmt *pStmt; /* Statement holding cursor open */ - sqlite3 *db; /* The associated database */ - char *zDb; /* Database name */ - Table *pTab; /* Table object */ -}; - - -/* -** This function is used by both blob_open() and blob_reopen(). It seeks -** the b-tree cursor associated with blob handle p to point to row iRow. -** If successful, SQLITE_OK is returned and subsequent calls to -** sqlite3_blob_read() or sqlite3_blob_write() access the specified row. -** -** If an error occurs, or if the specified row does not exist or does not -** contain a value of type TEXT or BLOB in the column nominated when the -** blob handle was opened, then an error code is returned and *pzErr may -** be set to point to a buffer containing an error message. It is the -** responsibility of the caller to free the error message buffer using -** sqlite3DbFree(). -** -** If an error does occur, then the b-tree cursor is closed. All subsequent -** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will -** immediately return SQLITE_ABORT. -*/ -static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){ - int rc; /* Error code */ - char *zErr = 0; /* Error message */ - Vdbe *v = (Vdbe *)p->pStmt; - - /* Set the value of register r[1] in the SQL statement to integer iRow. - ** This is done directly as a performance optimization - */ - v->aMem[1].flags = MEM_Int; - v->aMem[1].u.i = iRow; - - /* If the statement has been run before (and is paused at the OP_ResultRow) - ** then back it up to the point where it does the OP_NotExists. This could - ** have been down with an extra OP_Goto, but simply setting the program - ** counter is faster. */ - if( v->pc>4 ){ - v->pc = 4; - assert( v->aOp[v->pc].opcode==OP_NotExists ); - rc = sqlite3VdbeExec(v); - }else{ - rc = sqlite3_step(p->pStmt); - } - if( rc==SQLITE_ROW ){ - VdbeCursor *pC = v->apCsr[0]; - u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0; - testcase( pC->nHdrParsed==p->iCol ); - testcase( pC->nHdrParsed==p->iCol+1 ); - if( type<12 ){ - zErr = sqlite3MPrintf(p->db, "cannot open value of type %s", - type==0?"null": type==7?"real": "integer" - ); - rc = SQLITE_ERROR; - sqlite3_finalize(p->pStmt); - p->pStmt = 0; - }else{ - p->iOffset = pC->aType[p->iCol + pC->nField]; - p->nByte = sqlite3VdbeSerialTypeLen(type); - p->pCsr = pC->uc.pCursor; - sqlite3BtreeIncrblobCursor(p->pCsr); - } - } - - if( rc==SQLITE_ROW ){ - rc = SQLITE_OK; - }else if( p->pStmt ){ - rc = sqlite3_finalize(p->pStmt); - p->pStmt = 0; - if( rc==SQLITE_OK ){ - zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow); - rc = SQLITE_ERROR; - }else{ - zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db)); - } - } - - assert( rc!=SQLITE_OK || zErr==0 ); - assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE ); - - *pzErr = zErr; - return rc; -} - -/* -** Open a blob handle. -*/ -SQLITE_API int sqlite3_blob_open( - sqlite3* db, /* The database connection */ - const char *zDb, /* The attached database containing the blob */ - const char *zTable, /* The table containing the blob */ - const char *zColumn, /* The column containing the blob */ - sqlite_int64 iRow, /* The row containing the glob */ - int wrFlag, /* True -> read/write access, false -> read-only */ - sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ -){ - int nAttempt = 0; - int iCol; /* Index of zColumn in row-record */ - int rc = SQLITE_OK; - char *zErr = 0; - Table *pTab; - Incrblob *pBlob = 0; - Parse sParse; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( ppBlob==0 ){ - return SQLITE_MISUSE_BKPT; - } -#endif - *ppBlob = 0; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zTable==0 ){ - return SQLITE_MISUSE_BKPT; - } -#endif - wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */ - - sqlite3_mutex_enter(db->mutex); - - pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob)); - do { - memset(&sParse, 0, sizeof(Parse)); - if( !pBlob ) goto blob_open_out; - sParse.db = db; - sqlite3DbFree(db, zErr); - zErr = 0; - - sqlite3BtreeEnterAll(db); - pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb); - if( pTab && IsVirtual(pTab) ){ - pTab = 0; - sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable); - } - if( pTab && !HasRowid(pTab) ){ - pTab = 0; - sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable); - } -#ifndef SQLITE_OMIT_VIEW - if( pTab && pTab->pSelect ){ - pTab = 0; - sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable); - } -#endif - if( !pTab ){ - if( sParse.zErrMsg ){ - sqlite3DbFree(db, zErr); - zErr = sParse.zErrMsg; - sParse.zErrMsg = 0; - } - rc = SQLITE_ERROR; - sqlite3BtreeLeaveAll(db); - goto blob_open_out; - } - pBlob->pTab = pTab; - pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; - - /* Now search pTab for the exact column. */ - for(iCol=0; iColnCol; iCol++) { - if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ - break; - } - } - if( iCol==pTab->nCol ){ - sqlite3DbFree(db, zErr); - zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); - rc = SQLITE_ERROR; - sqlite3BtreeLeaveAll(db); - goto blob_open_out; - } - - /* If the value is being opened for writing, check that the - ** column is not indexed, and that it is not part of a foreign key. - */ - if( wrFlag ){ - const char *zFault = 0; - Index *pIdx; -#ifndef SQLITE_OMIT_FOREIGN_KEY - if( db->flags&SQLITE_ForeignKeys ){ - /* Check that the column is not part of an FK child key definition. It - ** is not necessary to check if it is part of a parent key, as parent - ** key columns must be indexed. The check below will pick up this - ** case. */ - FKey *pFKey; - for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ - int j; - for(j=0; jnCol; j++){ - if( pFKey->aCol[j].iFrom==iCol ){ - zFault = "foreign key"; - } - } - } - } -#endif - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - int j; - for(j=0; jnKeyCol; j++){ - /* FIXME: Be smarter about indexes that use expressions */ - if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){ - zFault = "indexed"; - } - } - } - if( zFault ){ - sqlite3DbFree(db, zErr); - zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); - rc = SQLITE_ERROR; - sqlite3BtreeLeaveAll(db); - goto blob_open_out; - } - } - - pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse); - assert( pBlob->pStmt || db->mallocFailed ); - if( pBlob->pStmt ){ - - /* This VDBE program seeks a btree cursor to the identified - ** db/table/row entry. The reason for using a vdbe program instead - ** of writing code to use the b-tree layer directly is that the - ** vdbe program will take advantage of the various transaction, - ** locking and error handling infrastructure built into the vdbe. - ** - ** After seeking the cursor, the vdbe executes an OP_ResultRow. - ** Code external to the Vdbe then "borrows" the b-tree cursor and - ** uses it to implement the blob_read(), blob_write() and - ** blob_bytes() functions. - ** - ** The sqlite3_blob_close() function finalizes the vdbe program, - ** which closes the b-tree cursor and (possibly) commits the - ** transaction. - */ - static const int iLn = VDBE_OFFSET_LINENO(2); - static const VdbeOpList openBlob[] = { - {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */ - {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */ - /* blobSeekToRow() will initialize r[1] to the desired rowid */ - {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */ - {OP_Column, 0, 0, 1}, /* 3 */ - {OP_ResultRow, 1, 0, 0}, /* 4 */ - {OP_Halt, 0, 0, 0}, /* 5 */ - }; - Vdbe *v = (Vdbe *)pBlob->pStmt; - int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - VdbeOp *aOp; - - sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, - pTab->pSchema->schema_cookie, - pTab->pSchema->iGeneration); - sqlite3VdbeChangeP5(v, 1); - assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed ); - aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn); - - /* Make sure a mutex is held on the table to be accessed */ - sqlite3VdbeUsesBtree(v, iDb); - - if( db->mallocFailed==0 ){ - assert( aOp!=0 ); - /* Configure the OP_TableLock instruction */ -#ifdef SQLITE_OMIT_SHARED_CACHE - aOp[0].opcode = OP_Noop; -#else - aOp[0].p1 = iDb; - aOp[0].p2 = pTab->tnum; - aOp[0].p3 = wrFlag; - sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT); - } - if( db->mallocFailed==0 ){ -#endif - - /* Remove either the OP_OpenWrite or OpenRead. Set the P2 - ** parameter of the other to pTab->tnum. */ - if( wrFlag ) aOp[1].opcode = OP_OpenWrite; - aOp[1].p2 = pTab->tnum; - aOp[1].p3 = iDb; - - /* Configure the number of columns. Configure the cursor to - ** think that the table has one more column than it really - ** does. An OP_Column to retrieve this imaginary column will - ** always return an SQL NULL. This is useful because it means - ** we can invoke OP_Column to fill in the vdbe cursors type - ** and offset cache without causing any IO. - */ - aOp[1].p4type = P4_INT32; - aOp[1].p4.i = pTab->nCol+1; - aOp[3].p2 = pTab->nCol; - - sParse.nVar = 0; - sParse.nMem = 1; - sParse.nTab = 1; - sqlite3VdbeMakeReady(v, &sParse); - } - } - - pBlob->iCol = iCol; - pBlob->db = db; - sqlite3BtreeLeaveAll(db); - if( db->mallocFailed ){ - goto blob_open_out; - } - rc = blobSeekToRow(pBlob, iRow, &zErr); - } while( (++nAttempt)mallocFailed==0 ){ - *ppBlob = (sqlite3_blob *)pBlob; - }else{ - if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt); - sqlite3DbFree(db, pBlob); - } - sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); - sqlite3DbFree(db, zErr); - sqlite3ParserReset(&sParse); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** Close a blob handle that was previously created using -** sqlite3_blob_open(). -*/ -SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){ - Incrblob *p = (Incrblob *)pBlob; - int rc; - sqlite3 *db; - - if( p ){ - sqlite3_stmt *pStmt = p->pStmt; - db = p->db; - sqlite3_mutex_enter(db->mutex); - sqlite3DbFree(db, p); - sqlite3_mutex_leave(db->mutex); - rc = sqlite3_finalize(pStmt); - }else{ - rc = SQLITE_OK; - } - return rc; -} - -/* -** Perform a read or write operation on a blob -*/ -static int blobReadWrite( - sqlite3_blob *pBlob, - void *z, - int n, - int iOffset, - int (*xCall)(BtCursor*, u32, u32, void*) -){ - int rc; - Incrblob *p = (Incrblob *)pBlob; - Vdbe *v; - sqlite3 *db; - - if( p==0 ) return SQLITE_MISUSE_BKPT; - db = p->db; - sqlite3_mutex_enter(db->mutex); - v = (Vdbe*)p->pStmt; - - if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){ - /* Request is out of range. Return a transient error. */ - rc = SQLITE_ERROR; - }else if( v==0 ){ - /* If there is no statement handle, then the blob-handle has - ** already been invalidated. Return SQLITE_ABORT in this case. - */ - rc = SQLITE_ABORT; - }else{ - /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is - ** returned, clean-up the statement handle. - */ - assert( db == v->db ); - sqlite3BtreeEnterCursor(p->pCsr); - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){ - /* If a pre-update hook is registered and this is a write cursor, - ** invoke it here. - ** - ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this - ** operation should really be an SQLITE_UPDATE. This is probably - ** incorrect, but is convenient because at this point the new.* values - ** are not easily obtainable. And for the sessions module, an - ** SQLITE_UPDATE where the PK columns do not change is handled in the - ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually - ** slightly more efficient). Since you cannot write to a PK column - ** using the incremental-blob API, this works. For the sessions module - ** anyhow. - */ - sqlite3_int64 iKey; - iKey = sqlite3BtreeIntegerKey(p->pCsr); - sqlite3VdbePreUpdateHook( - v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1 - ); - } -#endif - - rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); - sqlite3BtreeLeaveCursor(p->pCsr); - if( rc==SQLITE_ABORT ){ - sqlite3VdbeFinalize(v); - p->pStmt = 0; - }else{ - v->rc = rc; - } - } - sqlite3Error(db, rc); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** Read data from a blob handle. -*/ -SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){ - return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked); -} - -/* -** Write data to a blob handle. -*/ -SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){ - return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData); -} - -/* -** Query a blob handle for the size of the data. -** -** The Incrblob.nByte field is fixed for the lifetime of the Incrblob -** so no mutex is required for access. -*/ -SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){ - Incrblob *p = (Incrblob *)pBlob; - return (p && p->pStmt) ? p->nByte : 0; -} - -/* -** Move an existing blob handle to point to a different row of the same -** database table. -** -** If an error occurs, or if the specified row does not exist or does not -** contain a blob or text value, then an error code is returned and the -** database handle error code and message set. If this happens, then all -** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) -** immediately return SQLITE_ABORT. -*/ -SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){ - int rc; - Incrblob *p = (Incrblob *)pBlob; - sqlite3 *db; - - if( p==0 ) return SQLITE_MISUSE_BKPT; - db = p->db; - sqlite3_mutex_enter(db->mutex); - - if( p->pStmt==0 ){ - /* If there is no statement handle, then the blob-handle has - ** already been invalidated. Return SQLITE_ABORT in this case. - */ - rc = SQLITE_ABORT; - }else{ - char *zErr; - rc = blobSeekToRow(p, iRow, &zErr); - if( rc!=SQLITE_OK ){ - sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr); - sqlite3DbFree(db, zErr); - } - assert( rc!=SQLITE_SCHEMA ); - } - - rc = sqlite3ApiExit(db, rc); - assert( rc==SQLITE_OK || p->pStmt==0 ); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -#endif /* #ifndef SQLITE_OMIT_INCRBLOB */ - -/************** End of vdbeblob.c ********************************************/ -/************** Begin file vdbesort.c ****************************************/ -/* -** 2011-07-09 -** -** 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 for the VdbeSorter object, used in concert with -** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements -** or by SELECT statements with ORDER BY clauses that cannot be satisfied -** using indexes and without LIMIT clauses. -** -** The VdbeSorter object implements a multi-threaded external merge sort -** algorithm that is efficient even if the number of elements being sorted -** exceeds the available memory. -** -** Here is the (internal, non-API) interface between this module and the -** rest of the SQLite system: -** -** sqlite3VdbeSorterInit() Create a new VdbeSorter object. -** -** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter -** object. The row is a binary blob in the -** OP_MakeRecord format that contains both -** the ORDER BY key columns and result columns -** in the case of a SELECT w/ ORDER BY, or -** the complete record for an index entry -** in the case of a CREATE INDEX. -** -** sqlite3VdbeSorterRewind() Sort all content previously added. -** Position the read cursor on the -** first sorted element. -** -** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted -** element. -** -** sqlite3VdbeSorterRowkey() Return the complete binary blob for the -** row currently under the read cursor. -** -** sqlite3VdbeSorterCompare() Compare the binary blob for the row -** currently under the read cursor against -** another binary blob X and report if -** X is strictly less than the read cursor. -** Used to enforce uniqueness in a -** CREATE UNIQUE INDEX statement. -** -** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim -** all resources. -** -** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This -** is like Close() followed by Init() only -** much faster. -** -** The interfaces above must be called in a particular order. Write() can -** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and -** Compare() can only occur in between Rewind() and Close()/Reset(). i.e. -** -** Init() -** for each record: Write() -** Rewind() -** Rowkey()/Compare() -** Next() -** Close() -** -** Algorithm: -** -** Records passed to the sorter via calls to Write() are initially held -** unsorted in main memory. Assuming the amount of memory used never exceeds -** a threshold, when Rewind() is called the set of records is sorted using -** an in-memory merge sort. In this case, no temporary files are required -** and subsequent calls to Rowkey(), Next() and Compare() read records -** directly from main memory. -** -** If the amount of space used to store records in main memory exceeds the -** threshold, then the set of records currently in memory are sorted and -** written to a temporary file in "Packed Memory Array" (PMA) format. -** A PMA created at this point is known as a "level-0 PMA". Higher levels -** of PMAs may be created by merging existing PMAs together - for example -** merging two or more level-0 PMAs together creates a level-1 PMA. -** -** The threshold for the amount of main memory to use before flushing -** records to a PMA is roughly the same as the limit configured for the -** page-cache of the main database. Specifically, the threshold is set to -** the value returned by "PRAGMA main.page_size" multipled by -** that returned by "PRAGMA main.cache_size", in bytes. -** -** If the sorter is running in single-threaded mode, then all PMAs generated -** are appended to a single temporary file. Or, if the sorter is running in -** multi-threaded mode then up to (N+1) temporary files may be opened, where -** N is the configured number of worker threads. In this case, instead of -** sorting the records and writing the PMA to a temporary file itself, the -** calling thread usually launches a worker thread to do so. Except, if -** there are already N worker threads running, the main thread does the work -** itself. -** -** The sorter is running in multi-threaded mode if (a) the library was built -** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater -** than zero, and (b) worker threads have been enabled at runtime by calling -** "PRAGMA threads=N" with some value of N greater than 0. -** -** When Rewind() is called, any data remaining in memory is flushed to a -** final PMA. So at this point the data is stored in some number of sorted -** PMAs within temporary files on disk. -** -** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the -** sorter is running in single-threaded mode, then these PMAs are merged -** incrementally as keys are retreived from the sorter by the VDBE. The -** MergeEngine object, described in further detail below, performs this -** merge. -** -** Or, if running in multi-threaded mode, then a background thread is -** launched to merge the existing PMAs. Once the background thread has -** merged T bytes of data into a single sorted PMA, the main thread -** begins reading keys from that PMA while the background thread proceeds -** with merging the next T bytes of data. And so on. -** -** Parameter T is set to half the value of the memory threshold used -** by Write() above to determine when to create a new PMA. -** -** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when -** Rewind() is called, then a hierarchy of incremental-merges is used. -** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on -** disk are merged together. Then T bytes of data from the second set, and -** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT -** PMAs at a time. This done is to improve locality. -** -** If running in multi-threaded mode and there are more than -** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more -** than one background thread may be created. Specifically, there may be -** one background thread for each temporary file on disk, and one background -** thread to merge the output of each of the others to a single PMA for -** the main thread to read from. -*/ -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -/* -** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various -** messages to stderr that may be helpful in understanding the performance -** characteristics of the sorter in multi-threaded mode. -*/ -#if 0 -# define SQLITE_DEBUG_SORTER_THREADS 1 -#endif - -/* -** Hard-coded maximum amount of data to accumulate in memory before flushing -** to a level 0 PMA. The purpose of this limit is to prevent various integer -** overflows. 512MiB. -*/ -#define SQLITE_MAX_PMASZ (1<<29) - -/* -** Private objects used by the sorter -*/ -typedef struct MergeEngine MergeEngine; /* Merge PMAs together */ -typedef struct PmaReader PmaReader; /* Incrementally read one PMA */ -typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */ -typedef struct SorterRecord SorterRecord; /* A record being sorted */ -typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */ -typedef struct SorterFile SorterFile; /* Temporary file object wrapper */ -typedef struct SorterList SorterList; /* In-memory list of records */ -typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */ - -/* -** A container for a temp file handle and the current amount of data -** stored in the file. -*/ -struct SorterFile { - sqlite3_file *pFd; /* File handle */ - i64 iEof; /* Bytes of data stored in pFd */ -}; - -/* -** An in-memory list of objects to be sorted. -** -** If aMemory==0 then each object is allocated separately and the objects -** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects -** are stored in the aMemory[] bulk memory, one right after the other, and -** are connected using SorterRecord.u.iNext. -*/ -struct SorterList { - SorterRecord *pList; /* Linked list of records */ - u8 *aMemory; /* If non-NULL, bulk memory to hold pList */ - int szPMA; /* Size of pList as PMA in bytes */ -}; - -/* -** The MergeEngine object is used to combine two or more smaller PMAs into -** one big PMA using a merge operation. Separate PMAs all need to be -** combined into one big PMA in order to be able to step through the sorted -** records in order. -** -** The aReadr[] array contains a PmaReader object for each of the PMAs being -** merged. An aReadr[] object either points to a valid key or else is at EOF. -** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.) -** For the purposes of the paragraphs below, we assume that the array is -** actually N elements in size, where N is the smallest power of 2 greater -** to or equal to the number of PMAs being merged. The extra aReadr[] elements -** are treated as if they are empty (always at EOF). -** -** The aTree[] array is also N elements in size. The value of N is stored in -** the MergeEngine.nTree variable. -** -** The final (N/2) elements of aTree[] contain the results of comparing -** pairs of PMA keys together. Element i contains the result of -** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the -** aTree element is set to the index of it. -** -** For the purposes of this comparison, EOF is considered greater than any -** other key value. If the keys are equal (only possible with two EOF -** values), it doesn't matter which index is stored. -** -** The (N/4) elements of aTree[] that precede the final (N/2) described -** above contains the index of the smallest of each block of 4 PmaReaders -** And so on. So that aTree[1] contains the index of the PmaReader that -** currently points to the smallest key value. aTree[0] is unused. -** -** Example: -** -** aReadr[0] -> Banana -** aReadr[1] -> Feijoa -** aReadr[2] -> Elderberry -** aReadr[3] -> Currant -** aReadr[4] -> Grapefruit -** aReadr[5] -> Apple -** aReadr[6] -> Durian -** aReadr[7] -> EOF -** -** aTree[] = { X, 5 0, 5 0, 3, 5, 6 } -** -** The current element is "Apple" (the value of the key indicated by -** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will -** be advanced to the next key in its segment. Say the next key is -** "Eggplant": -** -** aReadr[5] -> Eggplant -** -** The contents of aTree[] are updated first by comparing the new PmaReader -** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader -** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree. -** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader -** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Bananafile2. And instead of using a -** background thread to prepare data for the PmaReader, with a single -** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with -** keys from pMerger by the calling thread whenever the PmaReader runs out -** of data. -*/ -struct IncrMerger { - SortSubtask *pTask; /* Task that owns this merger */ - MergeEngine *pMerger; /* Merge engine thread reads data from */ - i64 iStartOff; /* Offset to start writing file at */ - int mxSz; /* Maximum bytes of data to store */ - int bEof; /* Set to true when merge is finished */ - int bUseThread; /* True to use a bg thread for this object */ - SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */ -}; - -/* -** An instance of this object is used for writing a PMA. -** -** The PMA is written one record at a time. Each record is of an arbitrary -** size. But I/O is more efficient if it occurs in page-sized blocks where -** each block is aligned on a page boundary. This object caches writes to -** the PMA so that aligned, page-size blocks are written. -*/ -struct PmaWriter { - int eFWErr; /* Non-zero if in an error state */ - u8 *aBuffer; /* Pointer to write buffer */ - int nBuffer; /* Size of write buffer in bytes */ - int iBufStart; /* First byte of buffer to write */ - int iBufEnd; /* Last byte of buffer to write */ - i64 iWriteOff; /* Offset of start of buffer in file */ - sqlite3_file *pFd; /* File handle to write to */ -}; - -/* -** This object is the header on a single record while that record is being -** held in memory and prior to being written out as part of a PMA. -** -** How the linked list is connected depends on how memory is being managed -** by this module. If using a separate allocation for each in-memory record -** (VdbeSorter.list.aMemory==0), then the list is always connected using the -** SorterRecord.u.pNext pointers. -** -** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0), -** then while records are being accumulated the list is linked using the -** SorterRecord.u.iNext offset. This is because the aMemory[] array may -** be sqlite3Realloc()ed while records are being accumulated. Once the VM -** has finished passing records to the sorter, or when the in-memory buffer -** is full, the list is sorted. As part of the sorting process, it is -** converted to use the SorterRecord.u.pNext pointers. See function -** vdbeSorterSort() for details. -*/ -struct SorterRecord { - int nVal; /* Size of the record in bytes */ - union { - SorterRecord *pNext; /* Pointer to next record in list */ - int iNext; /* Offset within aMemory of next record */ - } u; - /* The data for the record immediately follows this header */ -}; - -/* Return a pointer to the buffer containing the record data for SorterRecord -** object p. Should be used as if: -** -** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; } -*/ -#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1)) - - -/* Maximum number of PMAs that a single MergeEngine can merge */ -#define SORTER_MAX_MERGE_COUNT 16 - -static int vdbeIncrSwap(IncrMerger*); -static void vdbeIncrFree(IncrMerger *); - -/* -** Free all memory belonging to the PmaReader object passed as the -** argument. All structure fields are set to zero before returning. -*/ -static void vdbePmaReaderClear(PmaReader *pReadr){ - sqlite3_free(pReadr->aAlloc); - sqlite3_free(pReadr->aBuffer); - if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); - vdbeIncrFree(pReadr->pIncr); - memset(pReadr, 0, sizeof(PmaReader)); -} - -/* -** Read the next nByte bytes of data from the PMA p. -** If successful, set *ppOut to point to a buffer containing the data -** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite -** error code. -** -** The buffer returned in *ppOut is only valid until the -** next call to this function. -*/ -static int vdbePmaReadBlob( - PmaReader *p, /* PmaReader from which to take the blob */ - int nByte, /* Bytes of data to read */ - u8 **ppOut /* OUT: Pointer to buffer containing data */ -){ - int iBuf; /* Offset within buffer to read from */ - int nAvail; /* Bytes of data available in buffer */ - - if( p->aMap ){ - *ppOut = &p->aMap[p->iReadOff]; - p->iReadOff += nByte; - return SQLITE_OK; - } - - assert( p->aBuffer ); - - /* If there is no more data to be read from the buffer, read the next - ** p->nBuffer bytes of data from the file into it. Or, if there are less - ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */ - iBuf = p->iReadOff % p->nBuffer; - if( iBuf==0 ){ - int nRead; /* Bytes to read from disk */ - int rc; /* sqlite3OsRead() return code */ - - /* Determine how many bytes of data to read. */ - if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){ - nRead = p->nBuffer; - }else{ - nRead = (int)(p->iEof - p->iReadOff); - } - assert( nRead>0 ); - - /* Readr data from the file. Return early if an error occurs. */ - rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff); - assert( rc!=SQLITE_IOERR_SHORT_READ ); - if( rc!=SQLITE_OK ) return rc; - } - nAvail = p->nBuffer - iBuf; - - if( nByte<=nAvail ){ - /* The requested data is available in the in-memory buffer. In this - ** case there is no need to make a copy of the data, just return a - ** pointer into the buffer to the caller. */ - *ppOut = &p->aBuffer[iBuf]; - p->iReadOff += nByte; - }else{ - /* The requested data is not all available in the in-memory buffer. - ** In this case, allocate space at p->aAlloc[] to copy the requested - ** range into. Then return a copy of pointer p->aAlloc to the caller. */ - int nRem; /* Bytes remaining to copy */ - - /* Extend the p->aAlloc[] allocation if required. */ - if( p->nAllocnAlloc); - while( nByte>nNew ) nNew = nNew*2; - aNew = sqlite3Realloc(p->aAlloc, nNew); - if( !aNew ) return SQLITE_NOMEM_BKPT; - p->nAlloc = nNew; - p->aAlloc = aNew; - } - - /* Copy as much data as is available in the buffer into the start of - ** p->aAlloc[]. */ - memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail); - p->iReadOff += nAvail; - nRem = nByte - nAvail; - - /* The following loop copies up to p->nBuffer bytes per iteration into - ** the p->aAlloc[] buffer. */ - while( nRem>0 ){ - int rc; /* vdbePmaReadBlob() return code */ - int nCopy; /* Number of bytes to copy */ - u8 *aNext; /* Pointer to buffer to copy data from */ - - nCopy = nRem; - if( nRem>p->nBuffer ) nCopy = p->nBuffer; - rc = vdbePmaReadBlob(p, nCopy, &aNext); - if( rc!=SQLITE_OK ) return rc; - assert( aNext!=p->aAlloc ); - memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy); - nRem -= nCopy; - } - - *ppOut = p->aAlloc; - } - - return SQLITE_OK; -} - -/* -** Read a varint from the stream of data accessed by p. Set *pnOut to -** the value read. -*/ -static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){ - int iBuf; - - if( p->aMap ){ - p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut); - }else{ - iBuf = p->iReadOff % p->nBuffer; - if( iBuf && (p->nBuffer-iBuf)>=9 ){ - p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut); - }else{ - u8 aVarint[16], *a; - int i = 0, rc; - do{ - rc = vdbePmaReadBlob(p, 1, &a); - if( rc ) return rc; - aVarint[(i++)&0xf] = a[0]; - }while( (a[0]&0x80)!=0 ); - sqlite3GetVarint(aVarint, pnOut); - } - } - - return SQLITE_OK; -} - -/* -** Attempt to memory map file pFile. If successful, set *pp to point to the -** new mapping and return SQLITE_OK. If the mapping is not attempted -** (because the file is too large or the VFS layer is configured not to use -** mmap), return SQLITE_OK and set *pp to NULL. -** -** Or, if an error occurs, return an SQLite error code. The final value of -** *pp is undefined in this case. -*/ -static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){ - int rc = SQLITE_OK; - if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){ - sqlite3_file *pFd = pFile->pFd; - if( pFd->pMethods->iVersion>=3 ){ - rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp); - testcase( rc!=SQLITE_OK ); - } - } - return rc; -} - -/* -** Attach PmaReader pReadr to file pFile (if it is not already attached to -** that file) and seek it to offset iOff within the file. Return SQLITE_OK -** if successful, or an SQLite error code if an error occurs. -*/ -static int vdbePmaReaderSeek( - SortSubtask *pTask, /* Task context */ - PmaReader *pReadr, /* Reader whose cursor is to be moved */ - SorterFile *pFile, /* Sorter file to read from */ - i64 iOff /* Offset in pFile */ -){ - int rc = SQLITE_OK; - - assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 ); - - if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ; - if( pReadr->aMap ){ - sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); - pReadr->aMap = 0; - } - pReadr->iReadOff = iOff; - pReadr->iEof = pFile->iEof; - pReadr->pFd = pFile->pFd; - - rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap); - if( rc==SQLITE_OK && pReadr->aMap==0 ){ - int pgsz = pTask->pSorter->pgsz; - int iBuf = pReadr->iReadOff % pgsz; - if( pReadr->aBuffer==0 ){ - pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz); - if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT; - pReadr->nBuffer = pgsz; - } - if( rc==SQLITE_OK && iBuf ){ - int nRead = pgsz - iBuf; - if( (pReadr->iReadOff + nRead) > pReadr->iEof ){ - nRead = (int)(pReadr->iEof - pReadr->iReadOff); - } - rc = sqlite3OsRead( - pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff - ); - testcase( rc!=SQLITE_OK ); - } - } - - return rc; -} - -/* -** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if -** no error occurs, or an SQLite error code if one does. -*/ -static int vdbePmaReaderNext(PmaReader *pReadr){ - int rc = SQLITE_OK; /* Return Code */ - u64 nRec = 0; /* Size of record in bytes */ - - - if( pReadr->iReadOff>=pReadr->iEof ){ - IncrMerger *pIncr = pReadr->pIncr; - int bEof = 1; - if( pIncr ){ - rc = vdbeIncrSwap(pIncr); - if( rc==SQLITE_OK && pIncr->bEof==0 ){ - rc = vdbePmaReaderSeek( - pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff - ); - bEof = 0; - } - } - - if( bEof ){ - /* This is an EOF condition */ - vdbePmaReaderClear(pReadr); - testcase( rc!=SQLITE_OK ); - return rc; - } - } - - if( rc==SQLITE_OK ){ - rc = vdbePmaReadVarint(pReadr, &nRec); - } - if( rc==SQLITE_OK ){ - pReadr->nKey = (int)nRec; - rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey); - testcase( rc!=SQLITE_OK ); - } - - return rc; -} - -/* -** Initialize PmaReader pReadr to scan through the PMA stored in file pFile -** starting at offset iStart and ending at offset iEof-1. This function -** leaves the PmaReader pointing to the first key in the PMA (or EOF if the -** PMA is empty). -** -** If the pnByte parameter is NULL, then it is assumed that the file -** contains a single PMA, and that that PMA omits the initial length varint. -*/ -static int vdbePmaReaderInit( - SortSubtask *pTask, /* Task context */ - SorterFile *pFile, /* Sorter file to read from */ - i64 iStart, /* Start offset in pFile */ - PmaReader *pReadr, /* PmaReader to populate */ - i64 *pnByte /* IN/OUT: Increment this value by PMA size */ -){ - int rc; - - assert( pFile->iEof>iStart ); - assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 ); - assert( pReadr->aBuffer==0 ); - assert( pReadr->aMap==0 ); - - rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart); - if( rc==SQLITE_OK ){ - u64 nByte = 0; /* Size of PMA in bytes */ - rc = vdbePmaReadVarint(pReadr, &nByte); - pReadr->iEof = pReadr->iReadOff + nByte; - *pnByte += nByte; - } - - if( rc==SQLITE_OK ){ - rc = vdbePmaReaderNext(pReadr); - } - return rc; -} - -/* -** A version of vdbeSorterCompare() that assumes that it has already been -** determined that the first field of key1 is equal to the first field of -** key2. -*/ -static int vdbeSorterCompareTail( - SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ - int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ - const void *pKey1, int nKey1, /* Left side of comparison */ - const void *pKey2, int nKey2 /* Right side of comparison */ -){ - UnpackedRecord *r2 = pTask->pUnpacked; - if( *pbKey2Cached==0 ){ - sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); - *pbKey2Cached = 1; - } - return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1); -} - -/* -** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, -** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences -** used by the comparison. Return the result of the comparison. -** -** If IN/OUT parameter *pbKey2Cached is true when this function is called, -** it is assumed that (pTask->pUnpacked) contains the unpacked version -** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked -** version of key2 and *pbKey2Cached set to true before returning. -** -** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set -** to SQLITE_NOMEM. -*/ -static int vdbeSorterCompare( - SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ - int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ - const void *pKey1, int nKey1, /* Left side of comparison */ - const void *pKey2, int nKey2 /* Right side of comparison */ -){ - UnpackedRecord *r2 = pTask->pUnpacked; - if( !*pbKey2Cached ){ - sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); - *pbKey2Cached = 1; - } - return sqlite3VdbeRecordCompare(nKey1, pKey1, r2); -} - -/* -** A specially optimized version of vdbeSorterCompare() that assumes that -** the first field of each key is a TEXT value and that the collation -** sequence to compare them with is BINARY. -*/ -static int vdbeSorterCompareText( - SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ - int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ - const void *pKey1, int nKey1, /* Left side of comparison */ - const void *pKey2, int nKey2 /* Right side of comparison */ -){ - const u8 * const p1 = (const u8 * const)pKey1; - const u8 * const p2 = (const u8 * const)pKey2; - const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ - const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ - - int n1; - int n2; - int res; - - getVarint32NR(&p1[1], n1); - getVarint32NR(&p2[1], n2); - res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2); - if( res==0 ){ - res = n1 - n2; - } - - if( res==0 ){ - if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ - res = vdbeSorterCompareTail( - pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 - ); - } - }else{ - assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); - if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ - res = res * -1; - } - } - - return res; -} - -/* -** A specially optimized version of vdbeSorterCompare() that assumes that -** the first field of each key is an INTEGER value. -*/ -static int vdbeSorterCompareInt( - SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ - int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ - const void *pKey1, int nKey1, /* Left side of comparison */ - const void *pKey2, int nKey2 /* Right side of comparison */ -){ - const u8 * const p1 = (const u8 * const)pKey1; - const u8 * const p2 = (const u8 * const)pKey2; - const int s1 = p1[1]; /* Left hand serial type */ - const int s2 = p2[1]; /* Right hand serial type */ - const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ - const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ - int res; /* Return value */ - - assert( (s1>0 && s1<7) || s1==8 || s1==9 ); - assert( (s2>0 && s2<7) || s2==8 || s2==9 ); - - if( s1==s2 ){ - /* The two values have the same sign. Compare using memcmp(). */ - static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 }; - const u8 n = aLen[s1]; - int i; - res = 0; - for(i=0; i7 && s2>7 ){ - res = s1 - s2; - }else{ - if( s2>7 ){ - res = +1; - }else if( s1>7 ){ - res = -1; - }else{ - res = s1 - s2; - } - assert( res!=0 ); - - if( res>0 ){ - if( *v1 & 0x80 ) res = -1; - }else{ - if( *v2 & 0x80 ) res = +1; - } - } - - if( res==0 ){ - if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ - res = vdbeSorterCompareTail( - pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 - ); - } - }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ - assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); - res = res * -1; - } - - return res; -} - -/* -** Initialize the temporary index cursor just opened as a sorter cursor. -** -** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField) -** to determine the number of fields that should be compared from the -** records being sorted. However, if the value passed as argument nField -** is non-zero and the sorter is able to guarantee a stable sort, nField -** is used instead. This is used when sorting records for a CREATE INDEX -** statement. In this case, keys are always delivered to the sorter in -** order of the primary key, which happens to be make up the final part -** of the records being sorted. So if the sort is stable, there is never -** any reason to compare PK fields and they can be ignored for a small -** performance boost. -** -** The sorter can guarantee a stable sort when running in single-threaded -** mode, but not in multi-threaded mode. -** -** SQLITE_OK is returned if successful, or an SQLite error code otherwise. -*/ -SQLITE_PRIVATE int sqlite3VdbeSorterInit( - sqlite3 *db, /* Database connection (for malloc()) */ - int nField, /* Number of key fields in each record */ - VdbeCursor *pCsr /* Cursor that holds the new sorter */ -){ - int pgsz; /* Page size of main database */ - int i; /* Used to iterate through aTask[] */ - VdbeSorter *pSorter; /* The new sorter */ - KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */ - int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */ - int sz; /* Size of pSorter in bytes */ - int rc = SQLITE_OK; -#if SQLITE_MAX_WORKER_THREADS==0 -# define nWorker 0 -#else - int nWorker; -#endif - - /* Initialize the upper limit on the number of worker threads */ -#if SQLITE_MAX_WORKER_THREADS>0 - if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){ - nWorker = 0; - }else{ - nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS]; - } -#endif - - /* Do not allow the total number of threads (main thread + all workers) - ** to exceed the maximum merge count */ -#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT - if( nWorker>=SORTER_MAX_MERGE_COUNT ){ - nWorker = SORTER_MAX_MERGE_COUNT-1; - } -#endif - - assert( pCsr->pKeyInfo && pCsr->pBtx==0 ); - assert( pCsr->eCurType==CURTYPE_SORTER ); - szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*); - sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask); - - pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo); - pCsr->uc.pSorter = pSorter; - if( pSorter==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz); - memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo); - pKeyInfo->db = 0; - if( nField && nWorker==0 ){ - pKeyInfo->nKeyField = nField; - } - pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt); - pSorter->nTask = nWorker + 1; - pSorter->iPrev = (u8)(nWorker - 1); - pSorter->bUseThreads = (pSorter->nTask>1); - pSorter->db = db; - for(i=0; inTask; i++){ - SortSubtask *pTask = &pSorter->aTask[i]; - pTask->pSorter = pSorter; - } - - if( !sqlite3TempInMemory(db) ){ - i64 mxCache; /* Cache size in bytes*/ - u32 szPma = sqlite3GlobalConfig.szPma; - pSorter->mnPmaSize = szPma * pgsz; - - mxCache = db->aDb[0].pSchema->cache_size; - if( mxCache<0 ){ - /* A negative cache-size value C indicates that the cache is abs(C) - ** KiB in size. */ - mxCache = mxCache * -1024; - }else{ - mxCache = mxCache * pgsz; - } - mxCache = MIN(mxCache, SQLITE_MAX_PMASZ); - pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache); - - /* Avoid large memory allocations if the application has requested - ** SQLITE_CONFIG_SMALL_MALLOC. */ - if( sqlite3GlobalConfig.bSmallMalloc==0 ){ - assert( pSorter->iMemory==0 ); - pSorter->nMemory = pgsz; - pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz); - if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT; - } - } - - if( pKeyInfo->nAllField<13 - && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl) - && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0 - ){ - pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT; - } - } - - return rc; -} -#undef nWorker /* Defined at the top of this function */ - -/* -** Free the list of sorted records starting at pRecord. -*/ -static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ - SorterRecord *p; - SorterRecord *pNext; - for(p=pRecord; p; p=pNext){ - pNext = p->u.pNext; - sqlite3DbFree(db, p); - } -} - -/* -** Free all resources owned by the object indicated by argument pTask. All -** fields of *pTask are zeroed before returning. -*/ -static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){ - sqlite3DbFree(db, pTask->pUnpacked); -#if SQLITE_MAX_WORKER_THREADS>0 - /* pTask->list.aMemory can only be non-zero if it was handed memory - ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */ - if( pTask->list.aMemory ){ - sqlite3_free(pTask->list.aMemory); - }else -#endif - { - assert( pTask->list.aMemory==0 ); - vdbeSorterRecordFree(0, pTask->list.pList); - } - if( pTask->file.pFd ){ - sqlite3OsCloseFree(pTask->file.pFd); - } - if( pTask->file2.pFd ){ - sqlite3OsCloseFree(pTask->file2.pFd); - } - memset(pTask, 0, sizeof(SortSubtask)); -} - -#ifdef SQLITE_DEBUG_SORTER_THREADS -static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){ - i64 t; - int iTask = (pTask - pTask->pSorter->aTask); - sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); - fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent); -} -static void vdbeSorterRewindDebug(const char *zEvent){ - i64 t; - sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t); - fprintf(stderr, "%lld:X %s\n", t, zEvent); -} -static void vdbeSorterPopulateDebug( - SortSubtask *pTask, - const char *zEvent -){ - i64 t; - int iTask = (pTask - pTask->pSorter->aTask); - sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); - fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent); -} -static void vdbeSorterBlockDebug( - SortSubtask *pTask, - int bBlocked, - const char *zEvent -){ - if( bBlocked ){ - i64 t; - sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); - fprintf(stderr, "%lld:main %s\n", t, zEvent); - } -} -#else -# define vdbeSorterWorkDebug(x,y) -# define vdbeSorterRewindDebug(y) -# define vdbeSorterPopulateDebug(x,y) -# define vdbeSorterBlockDebug(x,y,z) -#endif - -#if SQLITE_MAX_WORKER_THREADS>0 -/* -** Join thread pTask->thread. -*/ -static int vdbeSorterJoinThread(SortSubtask *pTask){ - int rc = SQLITE_OK; - if( pTask->pThread ){ -#ifdef SQLITE_DEBUG_SORTER_THREADS - int bDone = pTask->bDone; -#endif - void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR); - vdbeSorterBlockDebug(pTask, !bDone, "enter"); - (void)sqlite3ThreadJoin(pTask->pThread, &pRet); - vdbeSorterBlockDebug(pTask, !bDone, "exit"); - rc = SQLITE_PTR_TO_INT(pRet); - assert( pTask->bDone==1 ); - pTask->bDone = 0; - pTask->pThread = 0; - } - return rc; -} - -/* -** Launch a background thread to run xTask(pIn). -*/ -static int vdbeSorterCreateThread( - SortSubtask *pTask, /* Thread will use this task object */ - void *(*xTask)(void*), /* Routine to run in a separate thread */ - void *pIn /* Argument passed into xTask() */ -){ - assert( pTask->pThread==0 && pTask->bDone==0 ); - return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn); -} - -/* -** Join all outstanding threads launched by SorterWrite() to create -** level-0 PMAs. -*/ -static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){ - int rc = rcin; - int i; - - /* This function is always called by the main user thread. - ** - ** If this function is being called after SorterRewind() has been called, - ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread - ** is currently attempt to join one of the other threads. To avoid a race - ** condition where this thread also attempts to join the same object, join - ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */ - for(i=pSorter->nTask-1; i>=0; i--){ - SortSubtask *pTask = &pSorter->aTask[i]; - int rc2 = vdbeSorterJoinThread(pTask); - if( rc==SQLITE_OK ) rc = rc2; - } - return rc; -} -#else -# define vdbeSorterJoinAll(x,rcin) (rcin) -# define vdbeSorterJoinThread(pTask) SQLITE_OK -#endif - -/* -** Allocate a new MergeEngine object capable of handling up to -** nReader PmaReader inputs. -** -** nReader is automatically rounded up to the next power of two. -** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up. -*/ -static MergeEngine *vdbeMergeEngineNew(int nReader){ - int N = 2; /* Smallest power of two >= nReader */ - int nByte; /* Total bytes of space to allocate */ - MergeEngine *pNew; /* Pointer to allocated object to return */ - - assert( nReader<=SORTER_MAX_MERGE_COUNT ); - - while( NnTree = N; - pNew->pTask = 0; - pNew->aReadr = (PmaReader*)&pNew[1]; - pNew->aTree = (int*)&pNew->aReadr[N]; - } - return pNew; -} - -/* -** Free the MergeEngine object passed as the only argument. -*/ -static void vdbeMergeEngineFree(MergeEngine *pMerger){ - int i; - if( pMerger ){ - for(i=0; inTree; i++){ - vdbePmaReaderClear(&pMerger->aReadr[i]); - } - } - sqlite3_free(pMerger); -} - -/* -** Free all resources associated with the IncrMerger object indicated by -** the first argument. -*/ -static void vdbeIncrFree(IncrMerger *pIncr){ - if( pIncr ){ -#if SQLITE_MAX_WORKER_THREADS>0 - if( pIncr->bUseThread ){ - vdbeSorterJoinThread(pIncr->pTask); - if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd); - if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd); - } -#endif - vdbeMergeEngineFree(pIncr->pMerger); - sqlite3_free(pIncr); - } -} - -/* -** Reset a sorting cursor back to its original empty state. -*/ -SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){ - int i; - (void)vdbeSorterJoinAll(pSorter, SQLITE_OK); - assert( pSorter->bUseThreads || pSorter->pReader==0 ); -#if SQLITE_MAX_WORKER_THREADS>0 - if( pSorter->pReader ){ - vdbePmaReaderClear(pSorter->pReader); - sqlite3DbFree(db, pSorter->pReader); - pSorter->pReader = 0; - } -#endif - vdbeMergeEngineFree(pSorter->pMerger); - pSorter->pMerger = 0; - for(i=0; inTask; i++){ - SortSubtask *pTask = &pSorter->aTask[i]; - vdbeSortSubtaskCleanup(db, pTask); - pTask->pSorter = pSorter; - } - if( pSorter->list.aMemory==0 ){ - vdbeSorterRecordFree(0, pSorter->list.pList); - } - pSorter->list.pList = 0; - pSorter->list.szPMA = 0; - pSorter->bUsePMA = 0; - pSorter->iMemory = 0; - pSorter->mxKeysize = 0; - sqlite3DbFree(db, pSorter->pUnpacked); - pSorter->pUnpacked = 0; -} - -/* -** Free any cursor components allocated by sqlite3VdbeSorterXXX routines. -*/ -SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ - VdbeSorter *pSorter; - assert( pCsr->eCurType==CURTYPE_SORTER ); - pSorter = pCsr->uc.pSorter; - if( pSorter ){ - sqlite3VdbeSorterReset(db, pSorter); - sqlite3_free(pSorter->list.aMemory); - sqlite3DbFree(db, pSorter); - pCsr->uc.pSorter = 0; - } -} - -#if SQLITE_MAX_MMAP_SIZE>0 -/* -** The first argument is a file-handle open on a temporary file. The file -** is guaranteed to be nByte bytes or smaller in size. This function -** attempts to extend the file to nByte bytes in size and to ensure that -** the VFS has memory mapped it. -** -** Whether or not the file does end up memory mapped of course depends on -** the specific VFS implementation. -*/ -static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){ - if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){ - void *p = 0; - int chunksize = 4*1024; - sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize); - sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte); - sqlite3OsFetch(pFd, 0, (int)nByte, &p); - sqlite3OsUnfetch(pFd, 0, p); - } -} -#else -# define vdbeSorterExtendFile(x,y,z) -#endif - -/* -** Allocate space for a file-handle and open a temporary file. If successful, -** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK. -** Otherwise, set *ppFd to 0 and return an SQLite error code. -*/ -static int vdbeSorterOpenTempFile( - sqlite3 *db, /* Database handle doing sort */ - i64 nExtend, /* Attempt to extend file to this size */ - sqlite3_file **ppFd -){ - int rc; - if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS; - rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd, - SQLITE_OPEN_TEMP_JOURNAL | - SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | - SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc - ); - if( rc==SQLITE_OK ){ - i64 max = SQLITE_MAX_MMAP_SIZE; - sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max); - if( nExtend>0 ){ - vdbeSorterExtendFile(db, *ppFd, nExtend); - } - } - return rc; -} - -/* -** If it has not already been allocated, allocate the UnpackedRecord -** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or -** if no allocation was required), or SQLITE_NOMEM otherwise. -*/ -static int vdbeSortAllocUnpacked(SortSubtask *pTask){ - if( pTask->pUnpacked==0 ){ - pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo); - if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT; - pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField; - pTask->pUnpacked->errCode = 0; - } - return SQLITE_OK; -} - - -/* -** Merge the two sorted lists p1 and p2 into a single list. -*/ -static SorterRecord *vdbeSorterMerge( - SortSubtask *pTask, /* Calling thread context */ - SorterRecord *p1, /* First list to merge */ - SorterRecord *p2 /* Second list to merge */ -){ - SorterRecord *pFinal = 0; - SorterRecord **pp = &pFinal; - int bCached = 0; - - assert( p1!=0 && p2!=0 ); - for(;;){ - int res; - res = pTask->xCompare( - pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal - ); - - if( res<=0 ){ - *pp = p1; - pp = &p1->u.pNext; - p1 = p1->u.pNext; - if( p1==0 ){ - *pp = p2; - break; - } - }else{ - *pp = p2; - pp = &p2->u.pNext; - p2 = p2->u.pNext; - bCached = 0; - if( p2==0 ){ - *pp = p1; - break; - } - } - } - return pFinal; -} - -/* -** Return the SorterCompare function to compare values collected by the -** sorter object passed as the only argument. -*/ -static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){ - if( p->typeMask==SORTER_TYPE_INTEGER ){ - return vdbeSorterCompareInt; - }else if( p->typeMask==SORTER_TYPE_TEXT ){ - return vdbeSorterCompareText; - } - return vdbeSorterCompare; -} - -/* -** Sort the linked list of records headed at pTask->pList. Return -** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if -** an error occurs. -*/ -static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ - int i; - SorterRecord *p; - int rc; - SorterRecord *aSlot[64]; - - rc = vdbeSortAllocUnpacked(pTask); - if( rc!=SQLITE_OK ) return rc; - - p = pList->pList; - pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter); - memset(aSlot, 0, sizeof(aSlot)); - - while( p ){ - SorterRecord *pNext; - if( pList->aMemory ){ - if( (u8*)p==pList->aMemory ){ - pNext = 0; - }else{ - assert( p->u.iNextaMemory) ); - pNext = (SorterRecord*)&pList->aMemory[p->u.iNext]; - } - }else{ - pNext = p->u.pNext; - } - - p->u.pNext = 0; - for(i=0; aSlot[i]; i++){ - p = vdbeSorterMerge(pTask, p, aSlot[i]); - aSlot[i] = 0; - } - aSlot[i] = p; - p = pNext; - } - - p = 0; - for(i=0; ipList = p; - - assert( pTask->pUnpacked->errCode==SQLITE_OK - || pTask->pUnpacked->errCode==SQLITE_NOMEM - ); - return pTask->pUnpacked->errCode; -} - -/* -** Initialize a PMA-writer object. -*/ -static void vdbePmaWriterInit( - sqlite3_file *pFd, /* File handle to write to */ - PmaWriter *p, /* Object to populate */ - int nBuf, /* Buffer size */ - i64 iStart /* Offset of pFd to begin writing at */ -){ - memset(p, 0, sizeof(PmaWriter)); - p->aBuffer = (u8*)sqlite3Malloc(nBuf); - if( !p->aBuffer ){ - p->eFWErr = SQLITE_NOMEM_BKPT; - }else{ - p->iBufEnd = p->iBufStart = (iStart % nBuf); - p->iWriteOff = iStart - p->iBufStart; - p->nBuffer = nBuf; - p->pFd = pFd; - } -} - -/* -** Write nData bytes of data to the PMA. Return SQLITE_OK -** if successful, or an SQLite error code if an error occurs. -*/ -static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ - int nRem = nData; - while( nRem>0 && p->eFWErr==0 ){ - int nCopy = nRem; - if( nCopy>(p->nBuffer - p->iBufEnd) ){ - nCopy = p->nBuffer - p->iBufEnd; - } - - memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); - p->iBufEnd += nCopy; - if( p->iBufEnd==p->nBuffer ){ - p->eFWErr = sqlite3OsWrite(p->pFd, - &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, - p->iWriteOff + p->iBufStart - ); - p->iBufStart = p->iBufEnd = 0; - p->iWriteOff += p->nBuffer; - } - assert( p->iBufEndnBuffer ); - - nRem -= nCopy; - } -} - -/* -** Flush any buffered data to disk and clean up the PMA-writer object. -** The results of using the PMA-writer after this call are undefined. -** Return SQLITE_OK if flushing the buffered data succeeds or is not -** required. Otherwise, return an SQLite error code. -** -** Before returning, set *piEof to the offset immediately following the -** last byte written to the file. -*/ -static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){ - int rc; - if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ - p->eFWErr = sqlite3OsWrite(p->pFd, - &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, - p->iWriteOff + p->iBufStart - ); - } - *piEof = (p->iWriteOff + p->iBufEnd); - sqlite3_free(p->aBuffer); - rc = p->eFWErr; - memset(p, 0, sizeof(PmaWriter)); - return rc; -} - -/* -** Write value iVal encoded as a varint to the PMA. Return -** SQLITE_OK if successful, or an SQLite error code if an error occurs. -*/ -static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){ - int nByte; - u8 aByte[10]; - nByte = sqlite3PutVarint(aByte, iVal); - vdbePmaWriteBlob(p, aByte, nByte); -} - -/* -** Write the current contents of in-memory linked-list pList to a level-0 -** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if -** successful, or an SQLite error code otherwise. -** -** The format of a PMA is: -** -** * A varint. This varint contains the total number of bytes of content -** in the PMA (not including the varint itself). -** -** * One or more records packed end-to-end in order of ascending keys. -** Each record consists of a varint followed by a blob of data (the -** key). The varint is the number of bytes in the blob of data. -*/ -static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){ - sqlite3 *db = pTask->pSorter->db; - int rc = SQLITE_OK; /* Return code */ - PmaWriter writer; /* Object used to write to the file */ - -#ifdef SQLITE_DEBUG - /* Set iSz to the expected size of file pTask->file after writing the PMA. - ** This is used by an assert() statement at the end of this function. */ - i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof; -#endif - - vdbeSorterWorkDebug(pTask, "enter"); - memset(&writer, 0, sizeof(PmaWriter)); - assert( pList->szPMA>0 ); - - /* If the first temporary PMA file has not been opened, open it now. */ - if( pTask->file.pFd==0 ){ - rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd); - assert( rc!=SQLITE_OK || pTask->file.pFd ); - assert( pTask->file.iEof==0 ); - assert( pTask->nPMA==0 ); - } - - /* Try to get the file to memory map */ - if( rc==SQLITE_OK ){ - vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9); - } - - /* Sort the list */ - if( rc==SQLITE_OK ){ - rc = vdbeSorterSort(pTask, pList); - } - - if( rc==SQLITE_OK ){ - SorterRecord *p; - SorterRecord *pNext = 0; - - vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz, - pTask->file.iEof); - pTask->nPMA++; - vdbePmaWriteVarint(&writer, pList->szPMA); - for(p=pList->pList; p; p=pNext){ - pNext = p->u.pNext; - vdbePmaWriteVarint(&writer, p->nVal); - vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal); - if( pList->aMemory==0 ) sqlite3_free(p); - } - pList->pList = p; - rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof); - } - - vdbeSorterWorkDebug(pTask, "exit"); - assert( rc!=SQLITE_OK || pList->pList==0 ); - assert( rc!=SQLITE_OK || pTask->file.iEof==iSz ); - return rc; -} - -/* -** Advance the MergeEngine to its next entry. -** Set *pbEof to true there is no next entry because -** the MergeEngine has reached the end of all its inputs. -** -** Return SQLITE_OK if successful or an error code if an error occurs. -*/ -static int vdbeMergeEngineStep( - MergeEngine *pMerger, /* The merge engine to advance to the next row */ - int *pbEof /* Set TRUE at EOF. Set false for more content */ -){ - int rc; - int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */ - SortSubtask *pTask = pMerger->pTask; - - /* Advance the current PmaReader */ - rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]); - - /* Update contents of aTree[] */ - if( rc==SQLITE_OK ){ - int i; /* Index of aTree[] to recalculate */ - PmaReader *pReadr1; /* First PmaReader to compare */ - PmaReader *pReadr2; /* Second PmaReader to compare */ - int bCached = 0; - - /* Find the first two PmaReaders to compare. The one that was just - ** advanced (iPrev) and the one next to it in the array. */ - pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)]; - pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)]; - - for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){ - /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */ - int iRes; - if( pReadr1->pFd==0 ){ - iRes = +1; - }else if( pReadr2->pFd==0 ){ - iRes = -1; - }else{ - iRes = pTask->xCompare(pTask, &bCached, - pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey - ); - } - - /* If pReadr1 contained the smaller value, set aTree[i] to its index. - ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this - ** case there is no cache of pReadr2 in pTask->pUnpacked, so set - ** pKey2 to point to the record belonging to pReadr2. - ** - ** Alternatively, if pReadr2 contains the smaller of the two values, - ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare() - ** was actually called above, then pTask->pUnpacked now contains - ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent - ** vdbeSorterCompare() from decoding pReadr2 again. - ** - ** If the two values were equal, then the value from the oldest - ** PMA should be considered smaller. The VdbeSorter.aReadr[] array - ** is sorted from oldest to newest, so pReadr1 contains older values - ** than pReadr2 iff (pReadr1aTree[i] = (int)(pReadr1 - pMerger->aReadr); - pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; - bCached = 0; - }else{ - if( pReadr1->pFd ) bCached = 0; - pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr); - pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; - } - } - *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0); - } - - return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc); -} - -#if SQLITE_MAX_WORKER_THREADS>0 -/* -** The main routine for background threads that write level-0 PMAs. -*/ -static void *vdbeSorterFlushThread(void *pCtx){ - SortSubtask *pTask = (SortSubtask*)pCtx; - int rc; /* Return code */ - assert( pTask->bDone==0 ); - rc = vdbeSorterListToPMA(pTask, &pTask->list); - pTask->bDone = 1; - return SQLITE_INT_TO_PTR(rc); -} -#endif /* SQLITE_MAX_WORKER_THREADS>0 */ - -/* -** Flush the current contents of VdbeSorter.list to a new PMA, possibly -** using a background thread. -*/ -static int vdbeSorterFlushPMA(VdbeSorter *pSorter){ -#if SQLITE_MAX_WORKER_THREADS==0 - pSorter->bUsePMA = 1; - return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list); -#else - int rc = SQLITE_OK; - int i; - SortSubtask *pTask = 0; /* Thread context used to create new PMA */ - int nWorker = (pSorter->nTask-1); - - /* Set the flag to indicate that at least one PMA has been written. - ** Or will be, anyhow. */ - pSorter->bUsePMA = 1; - - /* Select a sub-task to sort and flush the current list of in-memory - ** records to disk. If the sorter is running in multi-threaded mode, - ** round-robin between the first (pSorter->nTask-1) tasks. Except, if - ** the background thread from a sub-tasks previous turn is still running, - ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy, - ** fall back to using the final sub-task. The first (pSorter->nTask-1) - ** sub-tasks are prefered as they use background threads - the final - ** sub-task uses the main thread. */ - for(i=0; iiPrev + i + 1) % nWorker; - pTask = &pSorter->aTask[iTest]; - if( pTask->bDone ){ - rc = vdbeSorterJoinThread(pTask); - } - if( rc!=SQLITE_OK || pTask->pThread==0 ) break; - } - - if( rc==SQLITE_OK ){ - if( i==nWorker ){ - /* Use the foreground thread for this operation */ - rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list); - }else{ - /* Launch a background thread for this operation */ - u8 *aMem; - void *pCtx; - - assert( pTask!=0 ); - assert( pTask->pThread==0 && pTask->bDone==0 ); - assert( pTask->list.pList==0 ); - assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 ); - - aMem = pTask->list.aMemory; - pCtx = (void*)pTask; - pSorter->iPrev = (u8)(pTask - pSorter->aTask); - pTask->list = pSorter->list; - pSorter->list.pList = 0; - pSorter->list.szPMA = 0; - if( aMem ){ - pSorter->list.aMemory = aMem; - pSorter->nMemory = sqlite3MallocSize(aMem); - }else if( pSorter->list.aMemory ){ - pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory); - if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT; - } - - rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx); - } - } - - return rc; -#endif /* SQLITE_MAX_WORKER_THREADS!=0 */ -} - -/* -** Add a record to the sorter. -*/ -SQLITE_PRIVATE int sqlite3VdbeSorterWrite( - const VdbeCursor *pCsr, /* Sorter cursor */ - Mem *pVal /* Memory cell containing record */ -){ - VdbeSorter *pSorter; - int rc = SQLITE_OK; /* Return Code */ - SorterRecord *pNew; /* New list element */ - int bFlush; /* True to flush contents of memory to PMA */ - int nReq; /* Bytes of memory required */ - int nPMA; /* Bytes of PMA space required */ - int t; /* serial type of first record field */ - - assert( pCsr->eCurType==CURTYPE_SORTER ); - pSorter = pCsr->uc.pSorter; - getVarint32NR((const u8*)&pVal->z[1], t); - if( t>0 && t<10 && t!=7 ){ - pSorter->typeMask &= SORTER_TYPE_INTEGER; - }else if( t>10 && (t & 0x01) ){ - pSorter->typeMask &= SORTER_TYPE_TEXT; - }else{ - pSorter->typeMask = 0; - } - - assert( pSorter ); - - /* Figure out whether or not the current contents of memory should be - ** flushed to a PMA before continuing. If so, do so. - ** - ** If using the single large allocation mode (pSorter->aMemory!=0), then - ** flush the contents of memory to a new PMA if (a) at least one value is - ** already in memory and (b) the new value will not fit in memory. - ** - ** Or, if using separate allocations for each record, flush the contents - ** of memory to a PMA if either of the following are true: - ** - ** * The total memory allocated for the in-memory list is greater - ** than (page-size * cache-size), or - ** - ** * The total memory allocated for the in-memory list is greater - ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. - */ - nReq = pVal->n + sizeof(SorterRecord); - nPMA = pVal->n + sqlite3VarintLen(pVal->n); - if( pSorter->mxPmaSize ){ - if( pSorter->list.aMemory ){ - bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize; - }else{ - bFlush = ( - (pSorter->list.szPMA > pSorter->mxPmaSize) - || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull()) - ); - } - if( bFlush ){ - rc = vdbeSorterFlushPMA(pSorter); - pSorter->list.szPMA = 0; - pSorter->iMemory = 0; - assert( rc!=SQLITE_OK || pSorter->list.pList==0 ); - } - } - - pSorter->list.szPMA += nPMA; - if( nPMA>pSorter->mxKeysize ){ - pSorter->mxKeysize = nPMA; - } - - if( pSorter->list.aMemory ){ - int nMin = pSorter->iMemory + nReq; - - if( nMin>pSorter->nMemory ){ - u8 *aNew; - sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory; - int iListOff = -1; - if( pSorter->list.pList ){ - iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; - } - while( nNew < nMin ) nNew = nNew*2; - if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize; - if( nNew < nMin ) nNew = nMin; - aNew = sqlite3Realloc(pSorter->list.aMemory, nNew); - if( !aNew ) return SQLITE_NOMEM_BKPT; - if( iListOff>=0 ){ - pSorter->list.pList = (SorterRecord*)&aNew[iListOff]; - } - pSorter->list.aMemory = aNew; - pSorter->nMemory = nNew; - } - - pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory]; - pSorter->iMemory += ROUND8(nReq); - if( pSorter->list.pList ){ - pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory); - } - }else{ - pNew = (SorterRecord *)sqlite3Malloc(nReq); - if( pNew==0 ){ - return SQLITE_NOMEM_BKPT; - } - pNew->u.pNext = pSorter->list.pList; - } - - memcpy(SRVAL(pNew), pVal->z, pVal->n); - pNew->nVal = pVal->n; - pSorter->list.pList = pNew; - - return rc; -} - -/* -** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format -** of the data stored in aFile[1] is the same as that used by regular PMAs, -** except that the number-of-bytes varint is omitted from the start. -*/ -static int vdbeIncrPopulate(IncrMerger *pIncr){ - int rc = SQLITE_OK; - int rc2; - i64 iStart = pIncr->iStartOff; - SorterFile *pOut = &pIncr->aFile[1]; - SortSubtask *pTask = pIncr->pTask; - MergeEngine *pMerger = pIncr->pMerger; - PmaWriter writer; - assert( pIncr->bEof==0 ); - - vdbeSorterPopulateDebug(pTask, "enter"); - - vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart); - while( rc==SQLITE_OK ){ - int dummy; - PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ]; - int nKey = pReader->nKey; - i64 iEof = writer.iWriteOff + writer.iBufEnd; - - /* Check if the output file is full or if the input has been exhausted. - ** In either case exit the loop. */ - if( pReader->pFd==0 ) break; - if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break; - - /* Write the next key to the output. */ - vdbePmaWriteVarint(&writer, nKey); - vdbePmaWriteBlob(&writer, pReader->aKey, nKey); - assert( pIncr->pMerger->pTask==pTask ); - rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy); - } - - rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof); - if( rc==SQLITE_OK ) rc = rc2; - vdbeSorterPopulateDebug(pTask, "exit"); - return rc; -} - -#if SQLITE_MAX_WORKER_THREADS>0 -/* -** The main routine for background threads that populate aFile[1] of -** multi-threaded IncrMerger objects. -*/ -static void *vdbeIncrPopulateThread(void *pCtx){ - IncrMerger *pIncr = (IncrMerger*)pCtx; - void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) ); - pIncr->pTask->bDone = 1; - return pRet; -} - -/* -** Launch a background thread to populate aFile[1] of pIncr. -*/ -static int vdbeIncrBgPopulate(IncrMerger *pIncr){ - void *p = (void*)pIncr; - assert( pIncr->bUseThread ); - return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p); -} -#endif - -/* -** This function is called when the PmaReader corresponding to pIncr has -** finished reading the contents of aFile[0]. Its purpose is to "refill" -** aFile[0] such that the PmaReader should start rereading it from the -** beginning. -** -** For single-threaded objects, this is accomplished by literally reading -** keys from pIncr->pMerger and repopulating aFile[0]. -** -** For multi-threaded objects, all that is required is to wait until the -** background thread is finished (if it is not already) and then swap -** aFile[0] and aFile[1] in place. If the contents of pMerger have not -** been exhausted, this function also launches a new background thread -** to populate the new aFile[1]. -** -** SQLITE_OK is returned on success, or an SQLite error code otherwise. -*/ -static int vdbeIncrSwap(IncrMerger *pIncr){ - int rc = SQLITE_OK; - -#if SQLITE_MAX_WORKER_THREADS>0 - if( pIncr->bUseThread ){ - rc = vdbeSorterJoinThread(pIncr->pTask); - - if( rc==SQLITE_OK ){ - SorterFile f0 = pIncr->aFile[0]; - pIncr->aFile[0] = pIncr->aFile[1]; - pIncr->aFile[1] = f0; - } - - if( rc==SQLITE_OK ){ - if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ - pIncr->bEof = 1; - }else{ - rc = vdbeIncrBgPopulate(pIncr); - } - } - }else -#endif - { - rc = vdbeIncrPopulate(pIncr); - pIncr->aFile[0] = pIncr->aFile[1]; - if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ - pIncr->bEof = 1; - } - } - - return rc; -} - -/* -** Allocate and return a new IncrMerger object to read data from pMerger. -** -** If an OOM condition is encountered, return NULL. In this case free the -** pMerger argument before returning. -*/ -static int vdbeIncrMergerNew( - SortSubtask *pTask, /* The thread that will be using the new IncrMerger */ - MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */ - IncrMerger **ppOut /* Write the new IncrMerger here */ -){ - int rc = SQLITE_OK; - IncrMerger *pIncr = *ppOut = (IncrMerger*) - (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr))); - if( pIncr ){ - pIncr->pMerger = pMerger; - pIncr->pTask = pTask; - pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2); - pTask->file2.iEof += pIncr->mxSz; - }else{ - vdbeMergeEngineFree(pMerger); - rc = SQLITE_NOMEM_BKPT; - } - return rc; -} - -#if SQLITE_MAX_WORKER_THREADS>0 -/* -** Set the "use-threads" flag on object pIncr. -*/ -static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){ - pIncr->bUseThread = 1; - pIncr->pTask->file2.iEof -= pIncr->mxSz; -} -#endif /* SQLITE_MAX_WORKER_THREADS>0 */ - - - -/* -** Recompute pMerger->aTree[iOut] by comparing the next keys on the -** two PmaReaders that feed that entry. Neither of the PmaReaders -** are advanced. This routine merely does the comparison. -*/ -static void vdbeMergeEngineCompare( - MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */ - int iOut /* Store the result in pMerger->aTree[iOut] */ -){ - int i1; - int i2; - int iRes; - PmaReader *p1; - PmaReader *p2; - - assert( iOutnTree && iOut>0 ); - - if( iOut>=(pMerger->nTree/2) ){ - i1 = (iOut - pMerger->nTree/2) * 2; - i2 = i1 + 1; - }else{ - i1 = pMerger->aTree[iOut*2]; - i2 = pMerger->aTree[iOut*2+1]; - } - - p1 = &pMerger->aReadr[i1]; - p2 = &pMerger->aReadr[i2]; - - if( p1->pFd==0 ){ - iRes = i2; - }else if( p2->pFd==0 ){ - iRes = i1; - }else{ - SortSubtask *pTask = pMerger->pTask; - int bCached = 0; - int res; - assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */ - res = pTask->xCompare( - pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey - ); - if( res<=0 ){ - iRes = i1; - }else{ - iRes = i2; - } - } - - pMerger->aTree[iOut] = iRes; -} - -/* -** Allowed values for the eMode parameter to vdbeMergeEngineInit() -** and vdbePmaReaderIncrMergeInit(). -** -** Only INCRINIT_NORMAL is valid in single-threaded builds (when -** SQLITE_MAX_WORKER_THREADS==0). The other values are only used -** when there exists one or more separate worker threads. -*/ -#define INCRINIT_NORMAL 0 -#define INCRINIT_TASK 1 -#define INCRINIT_ROOT 2 - -/* -** Forward reference required as the vdbeIncrMergeInit() and -** vdbePmaReaderIncrInit() routines are called mutually recursively when -** building a merge tree. -*/ -static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode); - -/* -** Initialize the MergeEngine object passed as the second argument. Once this -** function returns, the first key of merged data may be read from the -** MergeEngine object in the usual fashion. -** -** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge -** objects attached to the PmaReader objects that the merger reads from have -** already been populated, but that they have not yet populated aFile[0] and -** set the PmaReader objects up to read from it. In this case all that is -** required is to call vdbePmaReaderNext() on each PmaReader to point it at -** its first key. -** -** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use -** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data -** to pMerger. -** -** SQLITE_OK is returned if successful, or an SQLite error code otherwise. -*/ -static int vdbeMergeEngineInit( - SortSubtask *pTask, /* Thread that will run pMerger */ - MergeEngine *pMerger, /* MergeEngine to initialize */ - int eMode /* One of the INCRINIT_XXX constants */ -){ - int rc = SQLITE_OK; /* Return code */ - int i; /* For looping over PmaReader objects */ - int nTree; /* Number of subtrees to merge */ - - /* Failure to allocate the merge would have been detected prior to - ** invoking this routine */ - assert( pMerger!=0 ); - - /* eMode is always INCRINIT_NORMAL in single-threaded mode */ - assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); - - /* Verify that the MergeEngine is assigned to a single thread */ - assert( pMerger->pTask==0 ); - pMerger->pTask = pTask; - - nTree = pMerger->nTree; - for(i=0; i0 && eMode==INCRINIT_ROOT ){ - /* PmaReaders should be normally initialized in order, as if they are - ** reading from the same temp file this makes for more linear file IO. - ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is - ** in use it will block the vdbePmaReaderNext() call while it uses - ** the main thread to fill its buffer. So calling PmaReaderNext() - ** on this PmaReader before any of the multi-threaded PmaReaders takes - ** better advantage of multi-processor hardware. */ - rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]); - }else{ - rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL); - } - if( rc!=SQLITE_OK ) return rc; - } - - for(i=pMerger->nTree-1; i>0; i--){ - vdbeMergeEngineCompare(pMerger, i); - } - return pTask->pUnpacked->errCode; -} - -/* -** The PmaReader passed as the first argument is guaranteed to be an -** incremental-reader (pReadr->pIncr!=0). This function serves to open -** and/or initialize the temp file related fields of the IncrMerge -** object at (pReadr->pIncr). -** -** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders -** in the sub-tree headed by pReadr are also initialized. Data is then -** loaded into the buffers belonging to pReadr and it is set to point to -** the first key in its range. -** -** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed -** to be a multi-threaded PmaReader and this function is being called in a -** background thread. In this case all PmaReaders in the sub-tree are -** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to -** pReadr is populated. However, pReadr itself is not set up to point -** to its first key. A call to vdbePmaReaderNext() is still required to do -** that. -** -** The reason this function does not call vdbePmaReaderNext() immediately -** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has -** to block on thread (pTask->thread) before accessing aFile[1]. But, since -** this entire function is being run by thread (pTask->thread), that will -** lead to the current background thread attempting to join itself. -** -** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed -** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all -** child-trees have already been initialized using IncrInit(INCRINIT_TASK). -** In this case vdbePmaReaderNext() is called on all child PmaReaders and -** the current PmaReader set to point to the first key in its range. -** -** SQLITE_OK is returned if successful, or an SQLite error code otherwise. -*/ -static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){ - int rc = SQLITE_OK; - IncrMerger *pIncr = pReadr->pIncr; - SortSubtask *pTask = pIncr->pTask; - sqlite3 *db = pTask->pSorter->db; - - /* eMode is always INCRINIT_NORMAL in single-threaded mode */ - assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); - - rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode); - - /* Set up the required files for pIncr. A multi-theaded IncrMerge object - ** requires two temp files to itself, whereas a single-threaded object - ** only requires a region of pTask->file2. */ - if( rc==SQLITE_OK ){ - int mxSz = pIncr->mxSz; -#if SQLITE_MAX_WORKER_THREADS>0 - if( pIncr->bUseThread ){ - rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd); - if( rc==SQLITE_OK ){ - rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd); - } - }else -#endif - /*if( !pIncr->bUseThread )*/{ - if( pTask->file2.pFd==0 ){ - assert( pTask->file2.iEof>0 ); - rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd); - pTask->file2.iEof = 0; - } - if( rc==SQLITE_OK ){ - pIncr->aFile[1].pFd = pTask->file2.pFd; - pIncr->iStartOff = pTask->file2.iEof; - pTask->file2.iEof += mxSz; - } - } - } - -#if SQLITE_MAX_WORKER_THREADS>0 - if( rc==SQLITE_OK && pIncr->bUseThread ){ - /* Use the current thread to populate aFile[1], even though this - ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object, - ** then this function is already running in background thread - ** pIncr->pTask->thread. - ** - ** If this is the INCRINIT_ROOT object, then it is running in the - ** main VDBE thread. But that is Ok, as that thread cannot return - ** control to the VDBE or proceed with anything useful until the - ** first results are ready from this merger object anyway. - */ - assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK ); - rc = vdbeIncrPopulate(pIncr); - } -#endif - - if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){ - rc = vdbePmaReaderNext(pReadr); - } - - return rc; -} - -#if SQLITE_MAX_WORKER_THREADS>0 -/* -** The main routine for vdbePmaReaderIncrMergeInit() operations run in -** background threads. -*/ -static void *vdbePmaReaderBgIncrInit(void *pCtx){ - PmaReader *pReader = (PmaReader*)pCtx; - void *pRet = SQLITE_INT_TO_PTR( - vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK) - ); - pReader->pIncr->pTask->bDone = 1; - return pRet; -} -#endif - -/* -** If the PmaReader passed as the first argument is not an incremental-reader -** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes -** the vdbePmaReaderIncrMergeInit() function with the parameters passed to -** this routine to initialize the incremental merge. -** -** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), -** then a background thread is launched to call vdbePmaReaderIncrMergeInit(). -** Or, if the IncrMerger is single threaded, the same function is called -** using the current thread. -*/ -static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){ - IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */ - int rc = SQLITE_OK; /* Return code */ - if( pIncr ){ -#if SQLITE_MAX_WORKER_THREADS>0 - assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK ); - if( pIncr->bUseThread ){ - void *pCtx = (void*)pReadr; - rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx); - }else -#endif - { - rc = vdbePmaReaderIncrMergeInit(pReadr, eMode); - } - } - return rc; -} - -/* -** Allocate a new MergeEngine object to merge the contents of nPMA level-0 -** PMAs from pTask->file. If no error occurs, set *ppOut to point to -** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut -** to NULL and return an SQLite error code. -** -** When this function is called, *piOffset is set to the offset of the -** first PMA to read from pTask->file. Assuming no error occurs, it is -** set to the offset immediately following the last byte of the last -** PMA before returning. If an error does occur, then the final value of -** *piOffset is undefined. -*/ -static int vdbeMergeEngineLevel0( - SortSubtask *pTask, /* Sorter task to read from */ - int nPMA, /* Number of PMAs to read */ - i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */ - MergeEngine **ppOut /* OUT: New merge-engine */ -){ - MergeEngine *pNew; /* Merge engine to return */ - i64 iOff = *piOffset; - int i; - int rc = SQLITE_OK; - - *ppOut = pNew = vdbeMergeEngineNew(nPMA); - if( pNew==0 ) rc = SQLITE_NOMEM_BKPT; - - for(i=0; iaReadr[i]; - rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy); - iOff = pReadr->iEof; - } - - if( rc!=SQLITE_OK ){ - vdbeMergeEngineFree(pNew); - *ppOut = 0; - } - *piOffset = iOff; - return rc; -} - -/* -** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of -** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes. -** -** i.e. -** -** nPMA<=16 -> TreeDepth() == 0 -** nPMA<=256 -> TreeDepth() == 1 -** nPMA<=65536 -> TreeDepth() == 2 -*/ -static int vdbeSorterTreeDepth(int nPMA){ - int nDepth = 0; - i64 nDiv = SORTER_MAX_MERGE_COUNT; - while( nDiv < (i64)nPMA ){ - nDiv = nDiv * SORTER_MAX_MERGE_COUNT; - nDepth++; - } - return nDepth; -} - -/* -** pRoot is the root of an incremental merge-tree with depth nDepth (according -** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the -** tree, counting from zero. This function adds pLeaf to the tree. -** -** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error -** code is returned and pLeaf is freed. -*/ -static int vdbeSorterAddToTree( - SortSubtask *pTask, /* Task context */ - int nDepth, /* Depth of tree according to TreeDepth() */ - int iSeq, /* Sequence number of leaf within tree */ - MergeEngine *pRoot, /* Root of tree */ - MergeEngine *pLeaf /* Leaf to add to tree */ -){ - int rc = SQLITE_OK; - int nDiv = 1; - int i; - MergeEngine *p = pRoot; - IncrMerger *pIncr; - - rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr); - - for(i=1; iaReadr[iIter]; - - if( pReadr->pIncr==0 ){ - MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); - if( pNew==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr); - } - } - if( rc==SQLITE_OK ){ - p = pReadr->pIncr->pMerger; - nDiv = nDiv / SORTER_MAX_MERGE_COUNT; - } - } - - if( rc==SQLITE_OK ){ - p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr; - }else{ - vdbeIncrFree(pIncr); - } - return rc; -} - -/* -** This function is called as part of a SorterRewind() operation on a sorter -** that has already written two or more level-0 PMAs to one or more temp -** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that -** can be used to incrementally merge all PMAs on disk. -** -** If successful, SQLITE_OK is returned and *ppOut set to point to the -** MergeEngine object at the root of the tree before returning. Or, if an -** error occurs, an SQLite error code is returned and the final value -** of *ppOut is undefined. -*/ -static int vdbeSorterMergeTreeBuild( - VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */ - MergeEngine **ppOut /* Write the MergeEngine here */ -){ - MergeEngine *pMain = 0; - int rc = SQLITE_OK; - int iTask; - -#if SQLITE_MAX_WORKER_THREADS>0 - /* If the sorter uses more than one task, then create the top-level - ** MergeEngine here. This MergeEngine will read data from exactly - ** one PmaReader per sub-task. */ - assert( pSorter->bUseThreads || pSorter->nTask==1 ); - if( pSorter->nTask>1 ){ - pMain = vdbeMergeEngineNew(pSorter->nTask); - if( pMain==0 ) rc = SQLITE_NOMEM_BKPT; - } -#endif - - for(iTask=0; rc==SQLITE_OK && iTasknTask; iTask++){ - SortSubtask *pTask = &pSorter->aTask[iTask]; - assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 ); - if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){ - MergeEngine *pRoot = 0; /* Root node of tree for this task */ - int nDepth = vdbeSorterTreeDepth(pTask->nPMA); - i64 iReadOff = 0; - - if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){ - rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot); - }else{ - int i; - int iSeq = 0; - pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); - if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT; - for(i=0; inPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){ - MergeEngine *pMerger = 0; /* New level-0 PMA merger */ - int nReader; /* Number of level-0 PMAs to merge */ - - nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT); - rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger); - if( rc==SQLITE_OK ){ - rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger); - } - } - } - - if( rc==SQLITE_OK ){ -#if SQLITE_MAX_WORKER_THREADS>0 - if( pMain!=0 ){ - rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr); - }else -#endif - { - assert( pMain==0 ); - pMain = pRoot; - } - }else{ - vdbeMergeEngineFree(pRoot); - } - } - } - - if( rc!=SQLITE_OK ){ - vdbeMergeEngineFree(pMain); - pMain = 0; - } - *ppOut = pMain; - return rc; -} - -/* -** This function is called as part of an sqlite3VdbeSorterRewind() operation -** on a sorter that has written two or more PMAs to temporary files. It sets -** up either VdbeSorter.pMerger (for single threaded sorters) or pReader -** (for multi-threaded sorters) so that it can be used to iterate through -** all records stored in the sorter. -** -** SQLITE_OK is returned if successful, or an SQLite error code otherwise. -*/ -static int vdbeSorterSetupMerge(VdbeSorter *pSorter){ - int rc; /* Return code */ - SortSubtask *pTask0 = &pSorter->aTask[0]; - MergeEngine *pMain = 0; -#if SQLITE_MAX_WORKER_THREADS - sqlite3 *db = pTask0->pSorter->db; - int i; - SorterCompare xCompare = vdbeSorterGetCompare(pSorter); - for(i=0; inTask; i++){ - pSorter->aTask[i].xCompare = xCompare; - } -#endif - - rc = vdbeSorterMergeTreeBuild(pSorter, &pMain); - if( rc==SQLITE_OK ){ -#if SQLITE_MAX_WORKER_THREADS - assert( pSorter->bUseThreads==0 || pSorter->nTask>1 ); - if( pSorter->bUseThreads ){ - int iTask; - PmaReader *pReadr = 0; - SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1]; - rc = vdbeSortAllocUnpacked(pLast); - if( rc==SQLITE_OK ){ - pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader)); - pSorter->pReader = pReadr; - if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT; - } - if( rc==SQLITE_OK ){ - rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr); - if( rc==SQLITE_OK ){ - vdbeIncrMergerSetThreads(pReadr->pIncr); - for(iTask=0; iTask<(pSorter->nTask-1); iTask++){ - IncrMerger *pIncr; - if( (pIncr = pMain->aReadr[iTask].pIncr) ){ - vdbeIncrMergerSetThreads(pIncr); - assert( pIncr->pTask!=pLast ); - } - } - for(iTask=0; rc==SQLITE_OK && iTasknTask; iTask++){ - /* Check that: - ** - ** a) The incremental merge object is configured to use the - ** right task, and - ** b) If it is using task (nTask-1), it is configured to run - ** in single-threaded mode. This is important, as the - ** root merge (INCRINIT_ROOT) will be using the same task - ** object. - */ - PmaReader *p = &pMain->aReadr[iTask]; - assert( p->pIncr==0 || ( - (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */ - && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */ - )); - rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK); - } - } - pMain = 0; - } - if( rc==SQLITE_OK ){ - rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT); - } - }else -#endif - { - rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL); - pSorter->pMerger = pMain; - pMain = 0; - } - } - - if( rc!=SQLITE_OK ){ - vdbeMergeEngineFree(pMain); - } - return rc; -} - - -/* -** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite, -** this function is called to prepare for iterating through the records -** in sorted order. -*/ -SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){ - VdbeSorter *pSorter; - int rc = SQLITE_OK; /* Return code */ - - assert( pCsr->eCurType==CURTYPE_SORTER ); - pSorter = pCsr->uc.pSorter; - assert( pSorter ); - - /* If no data has been written to disk, then do not do so now. Instead, - ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly - ** from the in-memory list. */ - if( pSorter->bUsePMA==0 ){ - if( pSorter->list.pList ){ - *pbEof = 0; - rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list); - }else{ - *pbEof = 1; - } - return rc; - } - - /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() - ** function flushes the contents of memory to disk, it immediately always - ** creates a new list consisting of a single key immediately afterwards. - ** So the list is never empty at this point. */ - assert( pSorter->list.pList ); - rc = vdbeSorterFlushPMA(pSorter); - - /* Join all threads */ - rc = vdbeSorterJoinAll(pSorter, rc); - - vdbeSorterRewindDebug("rewind"); - - /* Assuming no errors have occurred, set up a merger structure to - ** incrementally read and merge all remaining PMAs. */ - assert( pSorter->pReader==0 ); - if( rc==SQLITE_OK ){ - rc = vdbeSorterSetupMerge(pSorter); - *pbEof = 0; - } - - vdbeSorterRewindDebug("rewinddone"); - return rc; -} - -/* -** Advance to the next element in the sorter. Return value: -** -** SQLITE_OK success -** SQLITE_DONE end of data -** otherwise some kind of error. -*/ -SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){ - VdbeSorter *pSorter; - int rc; /* Return code */ - - assert( pCsr->eCurType==CURTYPE_SORTER ); - pSorter = pCsr->uc.pSorter; - assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) ); - if( pSorter->bUsePMA ){ - assert( pSorter->pReader==0 || pSorter->pMerger==0 ); - assert( pSorter->bUseThreads==0 || pSorter->pReader ); - assert( pSorter->bUseThreads==1 || pSorter->pMerger ); -#if SQLITE_MAX_WORKER_THREADS>0 - if( pSorter->bUseThreads ){ - rc = vdbePmaReaderNext(pSorter->pReader); - if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE; - }else -#endif - /*if( !pSorter->bUseThreads )*/ { - int res = 0; - assert( pSorter->pMerger!=0 ); - assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) ); - rc = vdbeMergeEngineStep(pSorter->pMerger, &res); - if( rc==SQLITE_OK && res ) rc = SQLITE_DONE; - } - }else{ - SorterRecord *pFree = pSorter->list.pList; - pSorter->list.pList = pFree->u.pNext; - pFree->u.pNext = 0; - if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree); - rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE; - } - return rc; -} - -/* -** Return a pointer to a buffer owned by the sorter that contains the -** current key. -*/ -static void *vdbeSorterRowkey( - const VdbeSorter *pSorter, /* Sorter object */ - int *pnKey /* OUT: Size of current key in bytes */ -){ - void *pKey; - if( pSorter->bUsePMA ){ - PmaReader *pReader; -#if SQLITE_MAX_WORKER_THREADS>0 - if( pSorter->bUseThreads ){ - pReader = pSorter->pReader; - }else -#endif - /*if( !pSorter->bUseThreads )*/{ - pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]]; - } - *pnKey = pReader->nKey; - pKey = pReader->aKey; - }else{ - *pnKey = pSorter->list.pList->nVal; - pKey = SRVAL(pSorter->list.pList); - } - return pKey; -} - -/* -** Copy the current sorter key into the memory cell pOut. -*/ -SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ - VdbeSorter *pSorter; - void *pKey; int nKey; /* Sorter key to copy into pOut */ - - assert( pCsr->eCurType==CURTYPE_SORTER ); - pSorter = pCsr->uc.pSorter; - pKey = vdbeSorterRowkey(pSorter, &nKey); - if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){ - return SQLITE_NOMEM_BKPT; - } - pOut->n = nKey; - MemSetTypeFlag(pOut, MEM_Blob); - memcpy(pOut->z, pKey, nKey); - - return SQLITE_OK; -} - -/* -** Compare the key in memory cell pVal with the key that the sorter cursor -** passed as the first argument currently points to. For the purposes of -** the comparison, ignore the rowid field at the end of each record. -** -** If the sorter cursor key contains any NULL values, consider it to be -** less than pVal. Even if pVal also contains NULL values. -** -** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM). -** Otherwise, set *pRes to a negative, zero or positive value if the -** key in pVal is smaller than, equal to or larger than the current sorter -** key. -** -** This routine forms the core of the OP_SorterCompare opcode, which in -** turn is used to verify uniqueness when constructing a UNIQUE INDEX. -*/ -SQLITE_PRIVATE int sqlite3VdbeSorterCompare( - const VdbeCursor *pCsr, /* Sorter cursor */ - Mem *pVal, /* Value to compare to current sorter key */ - int nKeyCol, /* Compare this many columns */ - int *pRes /* OUT: Result of comparison */ -){ - VdbeSorter *pSorter; - UnpackedRecord *r2; - KeyInfo *pKeyInfo; - int i; - void *pKey; int nKey; /* Sorter key to compare pVal with */ - - assert( pCsr->eCurType==CURTYPE_SORTER ); - pSorter = pCsr->uc.pSorter; - r2 = pSorter->pUnpacked; - pKeyInfo = pCsr->pKeyInfo; - if( r2==0 ){ - r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); - if( r2==0 ) return SQLITE_NOMEM_BKPT; - r2->nField = nKeyCol; - } - assert( r2->nField==nKeyCol ); - - pKey = vdbeSorterRowkey(pSorter, &nKey); - sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2); - for(i=0; iaMem[i].flags & MEM_Null ){ - *pRes = -1; - return SQLITE_OK; - } - } - - *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2); - return SQLITE_OK; -} - -/************** End of vdbesort.c ********************************************/ -/************** Begin file vdbevtab.c ****************************************/ -/* -** 2020-03-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 virtual-tables for examining the bytecode content -** of a prepared statement. -*/ -/* #include "sqliteInt.h" */ -#if defined(SQLITE_ENABLE_BYTECODE_VTAB) && !defined(SQLITE_OMIT_VIRTUALTABLE) -/* #include "vdbeInt.h" */ - -/* An instance of the bytecode() table-valued function. -*/ -typedef struct bytecodevtab bytecodevtab; -struct bytecodevtab { - sqlite3_vtab base; /* Base class - must be first */ - sqlite3 *db; /* Database connection */ - int bTablesUsed; /* 2 for tables_used(). 0 for bytecode(). */ -}; - -/* A cursor for scanning through the bytecode -*/ -typedef struct bytecodevtab_cursor bytecodevtab_cursor; -struct bytecodevtab_cursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - sqlite3_stmt *pStmt; /* The statement whose bytecode is displayed */ - int iRowid; /* The rowid of the output table */ - int iAddr; /* Address */ - int needFinalize; /* Cursors owns pStmt and must finalize it */ - int showSubprograms; /* Provide a listing of subprograms */ - Op *aOp; /* Operand array */ - char *zP4; /* Rendered P4 value */ - const char *zType; /* tables_used.type */ - const char *zSchema; /* tables_used.schema */ - const char *zName; /* tables_used.name */ - Mem sub; /* Subprograms */ -}; - -/* -** Create a new bytecode() table-valued function. -*/ -static int bytecodevtabConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - bytecodevtab *pNew; - int rc; - int isTabUsed = pAux!=0; - const char *azSchema[2] = { - /* bytecode() schema */ - "CREATE TABLE x(" - "addr INT," - "opcode TEXT," - "p1 INT," - "p2 INT," - "p3 INT," - "p4 TEXT," - "p5 INT," - "comment TEXT," - "subprog TEXT," - "stmt HIDDEN" - ");", - - /* Tables_used() schema */ - "CREATE TABLE x(" - "type TEXT," - "schema TEXT," - "name TEXT," - "wr INT," - "subprog TEXT," - "stmt HIDDEN" - ");" - }; - - rc = sqlite3_declare_vtab(db, azSchema[isTabUsed]); - if( rc==SQLITE_OK ){ - pNew = sqlite3_malloc( sizeof(*pNew) ); - *ppVtab = (sqlite3_vtab*)pNew; - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); - pNew->db = db; - pNew->bTablesUsed = isTabUsed*2; - } - return rc; -} - -/* -** This method is the destructor for bytecodevtab objects. -*/ -static int bytecodevtabDisconnect(sqlite3_vtab *pVtab){ - bytecodevtab *p = (bytecodevtab*)pVtab; - sqlite3_free(p); - return SQLITE_OK; -} - -/* -** Constructor for a new bytecodevtab_cursor object. -*/ -static int bytecodevtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - bytecodevtab *pVTab = (bytecodevtab*)p; - bytecodevtab_cursor *pCur; - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1); - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* -** Clear all internal content from a bytecodevtab cursor. -*/ -static void bytecodevtabCursorClear(bytecodevtab_cursor *pCur){ - sqlite3_free(pCur->zP4); - pCur->zP4 = 0; - sqlite3VdbeMemRelease(&pCur->sub); - sqlite3VdbeMemSetNull(&pCur->sub); - if( pCur->needFinalize ){ - sqlite3_finalize(pCur->pStmt); - } - pCur->pStmt = 0; - pCur->needFinalize = 0; - pCur->zType = 0; - pCur->zSchema = 0; - pCur->zName = 0; -} - -/* -** Destructor for a bytecodevtab_cursor. -*/ -static int bytecodevtabClose(sqlite3_vtab_cursor *cur){ - bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur; - bytecodevtabCursorClear(pCur); - sqlite3_free(pCur); - return SQLITE_OK; -} - - -/* -** Advance a bytecodevtab_cursor to its next row of output. -*/ -static int bytecodevtabNext(sqlite3_vtab_cursor *cur){ - bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur; - bytecodevtab *pTab = (bytecodevtab*)cur->pVtab; - int rc; - if( pCur->zP4 ){ - sqlite3_free(pCur->zP4); - pCur->zP4 = 0; - } - if( pCur->zName ){ - pCur->zName = 0; - pCur->zType = 0; - pCur->zSchema = 0; - } - rc = sqlite3VdbeNextOpcode( - (Vdbe*)pCur->pStmt, - pCur->showSubprograms ? &pCur->sub : 0, - pTab->bTablesUsed, - &pCur->iRowid, - &pCur->iAddr, - &pCur->aOp); - if( rc!=SQLITE_OK ){ - sqlite3VdbeMemSetNull(&pCur->sub); - pCur->aOp = 0; - } - return SQLITE_OK; -} - -/* -** Return TRUE if the cursor has been moved off of the last -** row of output. -*/ -static int bytecodevtabEof(sqlite3_vtab_cursor *cur){ - bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur; - return pCur->aOp==0; -} - -/* -** Return values of columns for the row at which the bytecodevtab_cursor -** is currently pointing. -*/ -static int bytecodevtabColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur; - bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab; - Op *pOp = pCur->aOp + pCur->iAddr; - if( pVTab->bTablesUsed ){ - if( i==4 ){ - i = 8; - }else{ - if( i<=2 && pCur->zType==0 ){ - Schema *pSchema; - HashElem *k; - int iDb = pOp->p3; - Pgno iRoot = (Pgno)pOp->p2; - sqlite3 *db = pVTab->db; - pSchema = db->aDb[iDb].pSchema; - pCur->zSchema = db->aDb[iDb].zDbSName; - for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ - Table *pTab = (Table*)sqliteHashData(k); - if( !IsVirtual(pTab) && pTab->tnum==iRoot ){ - pCur->zName = pTab->zName; - pCur->zType = "table"; - break; - } - } - if( pCur->zName==0 ){ - for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){ - Index *pIdx = (Index*)sqliteHashData(k); - if( pIdx->tnum==iRoot ){ - pCur->zName = pIdx->zName; - pCur->zType = "index"; - } - } - } - } - i += 10; - } - } - switch( i ){ - case 0: /* addr */ - sqlite3_result_int(ctx, pCur->iAddr); - break; - case 1: /* opcode */ - sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode), - -1, SQLITE_STATIC); - break; - case 2: /* p1 */ - sqlite3_result_int(ctx, pOp->p1); - break; - case 3: /* p2 */ - sqlite3_result_int(ctx, pOp->p2); - break; - case 4: /* p3 */ - sqlite3_result_int(ctx, pOp->p3); - break; - case 5: /* p4 */ - case 7: /* comment */ - if( pCur->zP4==0 ){ - pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp); - } - if( i==5 ){ - sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC); - }else{ -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4); - sqlite3_result_text(ctx, zCom, -1, sqlite3_free); -#endif - } - break; - case 6: /* p5 */ - sqlite3_result_int(ctx, pOp->p5); - break; - case 8: { /* subprog */ - Op *aOp = pCur->aOp; - assert( aOp[0].opcode==OP_Init ); - assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,"-" "- ",3)==0 ); - if( pCur->iRowid==pCur->iAddr+1 ){ - break; /* Result is NULL for the main program */ - }else if( aOp[0].p4.z!=0 ){ - sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC); - }else{ - sqlite3_result_text(ctx, "(FK)", 4, SQLITE_STATIC); - } - break; - } - case 10: /* tables_used.type */ - sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC); - break; - case 11: /* tables_used.schema */ - sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC); - break; - case 12: /* tables_used.name */ - sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC); - break; - case 13: /* tables_used.wr */ - sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite); - break; - } - return SQLITE_OK; -} - -/* -** Return the rowid for the current row. In this implementation, the -** rowid is the same as the output value. -*/ -static int bytecodevtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur; - *pRowid = pCur->iRowid; - return SQLITE_OK; -} - -/* -** Initialize a cursor. -** -** idxNum==0 means show all subprograms -** idxNum==1 means show only the main bytecode and omit subprograms. -*/ -static int bytecodevtabFilter( - sqlite3_vtab_cursor *pVtabCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - bytecodevtab_cursor *pCur = (bytecodevtab_cursor *)pVtabCursor; - bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab; - int rc = SQLITE_OK; - - bytecodevtabCursorClear(pCur); - pCur->iRowid = 0; - pCur->iAddr = 0; - pCur->showSubprograms = idxNum==0; - assert( argc==1 ); - if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){ - const char *zSql = (const char*)sqlite3_value_text(argv[0]); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0); - pCur->needFinalize = 1; - } - }else{ - pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],"stmt-pointer"); - } - if( pCur->pStmt==0 ){ - pVTab->base.zErrMsg = sqlite3_mprintf( - "argument to %s() is not a valid SQL statement", - pVTab->bTablesUsed ? "tables_used" : "bytecode" - ); - rc = SQLITE_ERROR; - }else{ - bytecodevtabNext(pVtabCursor); - } - return rc; -} - -/* -** We must have a single stmt=? constraint that will be passed through -** into the xFilter method. If there is no valid stmt=? constraint, -** then return an SQLITE_CONSTRAINT error. -*/ -static int bytecodevtabBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; - int rc = SQLITE_CONSTRAINT; - struct sqlite3_index_constraint *p; - bytecodevtab *pVTab = (bytecodevtab*)tab; - int iBaseCol = pVTab->bTablesUsed ? 4 : 8; - pIdxInfo->estimatedCost = (double)100; - pIdxInfo->estimatedRows = 100; - pIdxInfo->idxNum = 0; - for(i=0, p=pIdxInfo->aConstraint; inConstraint; i++, p++){ - if( p->usable==0 ) continue; - if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){ - rc = SQLITE_OK; - pIdxInfo->aConstraintUsage[i].omit = 1; - pIdxInfo->aConstraintUsage[i].argvIndex = 1; - } - if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){ - pIdxInfo->aConstraintUsage[i].omit = 1; - pIdxInfo->idxNum = 1; - } - } - return rc; -} - -/* -** This following structure defines all the methods for the -** virtual table. -*/ -static sqlite3_module bytecodevtabModule = { - /* iVersion */ 0, - /* xCreate */ 0, - /* xConnect */ bytecodevtabConnect, - /* xBestIndex */ bytecodevtabBestIndex, - /* xDisconnect */ bytecodevtabDisconnect, - /* xDestroy */ 0, - /* xOpen */ bytecodevtabOpen, - /* xClose */ bytecodevtabClose, - /* xFilter */ bytecodevtabFilter, - /* xNext */ bytecodevtabNext, - /* xEof */ bytecodevtabEof, - /* xColumn */ bytecodevtabColumn, - /* xRowid */ bytecodevtabRowid, - /* xUpdate */ 0, - /* xBegin */ 0, - /* xSync */ 0, - /* xCommit */ 0, - /* xRollback */ 0, - /* xFindMethod */ 0, - /* xRename */ 0, - /* xSavepoint */ 0, - /* xRelease */ 0, - /* xRollbackTo */ 0, - /* xShadowName */ 0 -}; - - -SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){ - int rc; - rc = sqlite3_create_module(db, "bytecode", &bytecodevtabModule, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_module(db, "tables_used", &bytecodevtabModule, &db); - } - return rc; -} -#elif defined(SQLITE_ENABLE_BYTECODE_VTAB) -SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){ return SQLITE_OK; } -#endif /* SQLITE_ENABLE_BYTECODE_VTAB */ - -/************** End of vdbevtab.c ********************************************/ -/************** Begin file memjournal.c **************************************/ -/* -** 2008 October 7 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains code use to implement an in-memory rollback journal. -** The in-memory rollback journal is used to journal transactions for -** ":memory:" databases and when the journal_mode=MEMORY pragma is used. -** -** Update: The in-memory journal is also used to temporarily cache -** smaller journals that are not critical for power-loss recovery. -** For example, statement journals that are not too big will be held -** entirely in memory, thus reducing the number of file I/O calls, and -** more importantly, reducing temporary file creation events. If these -** journals become too large for memory, they are spilled to disk. But -** in the common case, they are usually small and no file I/O needs to -** occur. -*/ -/* #include "sqliteInt.h" */ - -/* Forward references to internal structures */ -typedef struct MemJournal MemJournal; -typedef struct FilePoint FilePoint; -typedef struct FileChunk FileChunk; - -/* -** The rollback journal is composed of a linked list of these structures. -** -** The zChunk array is always at least 8 bytes in size - usually much more. -** Its actual size is stored in the MemJournal.nChunkSize variable. -*/ -struct FileChunk { - FileChunk *pNext; /* Next chunk in the journal */ - u8 zChunk[8]; /* Content of this chunk */ -}; - -/* -** By default, allocate this many bytes of memory for each FileChunk object. -*/ -#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024 - -/* -** For chunk size nChunkSize, return the number of bytes that should -** be allocated for each FileChunk structure. -*/ -#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8)) - -/* -** An instance of this object serves as a cursor into the rollback journal. -** The cursor can be either for reading or writing. -*/ -struct FilePoint { - sqlite3_int64 iOffset; /* Offset from the beginning of the file */ - FileChunk *pChunk; /* Specific chunk into which cursor points */ -}; - -/* -** This structure is a subclass of sqlite3_file. Each open memory-journal -** is an instance of this class. -*/ -struct MemJournal { - const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */ - int nChunkSize; /* In-memory chunk-size */ - - int nSpill; /* Bytes of data before flushing */ - int nSize; /* Bytes of data currently in memory */ - FileChunk *pFirst; /* Head of in-memory chunk-list */ - FilePoint endpoint; /* Pointer to the end of the file */ - FilePoint readpoint; /* Pointer to the end of the last xRead() */ - - int flags; /* xOpen flags */ - sqlite3_vfs *pVfs; /* The "real" underlying VFS */ - const char *zJournal; /* Name of the journal file */ -}; - -/* -** Read data from the in-memory journal file. This is the implementation -** of the sqlite3_vfs.xRead method. -*/ -static int memjrnlRead( - sqlite3_file *pJfd, /* The journal file from which to read */ - void *zBuf, /* Put the results here */ - int iAmt, /* Number of bytes to read */ - sqlite_int64 iOfst /* Begin reading at this offset */ -){ - MemJournal *p = (MemJournal *)pJfd; - u8 *zOut = zBuf; - int nRead = iAmt; - int iChunkOffset; - FileChunk *pChunk; - - if( (iAmt+iOfst)>p->endpoint.iOffset ){ - return SQLITE_IOERR_SHORT_READ; - } - assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 ); - if( p->readpoint.iOffset!=iOfst || iOfst==0 ){ - sqlite3_int64 iOff = 0; - for(pChunk=p->pFirst; - ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst; - pChunk=pChunk->pNext - ){ - iOff += p->nChunkSize; - } - }else{ - pChunk = p->readpoint.pChunk; - assert( pChunk!=0 ); - } - - iChunkOffset = (int)(iOfst%p->nChunkSize); - do { - int iSpace = p->nChunkSize - iChunkOffset; - int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset)); - memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy); - zOut += nCopy; - nRead -= iSpace; - iChunkOffset = 0; - } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 ); - p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0; - p->readpoint.pChunk = pChunk; - - return SQLITE_OK; -} - -/* -** Free the list of FileChunk structures headed at MemJournal.pFirst. -*/ -static void memjrnlFreeChunks(MemJournal *p){ - FileChunk *pIter; - FileChunk *pNext; - for(pIter=p->pFirst; pIter; pIter=pNext){ - pNext = pIter->pNext; - sqlite3_free(pIter); - } - p->pFirst = 0; -} - -/* -** Flush the contents of memory to a real file on disk. -*/ -static int memjrnlCreateFile(MemJournal *p){ - int rc; - sqlite3_file *pReal = (sqlite3_file*)p; - MemJournal copy = *p; - - memset(p, 0, sizeof(MemJournal)); - rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0); - if( rc==SQLITE_OK ){ - int nChunk = copy.nChunkSize; - i64 iOff = 0; - FileChunk *pIter; - for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){ - if( iOff + nChunk > copy.endpoint.iOffset ){ - nChunk = copy.endpoint.iOffset - iOff; - } - rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff); - if( rc ) break; - iOff += nChunk; - } - if( rc==SQLITE_OK ){ - /* No error has occurred. Free the in-memory buffers. */ - memjrnlFreeChunks(©); - } - } - if( rc!=SQLITE_OK ){ - /* If an error occurred while creating or writing to the file, restore - ** the original before returning. This way, SQLite uses the in-memory - ** journal data to roll back changes made to the internal page-cache - ** before this function was called. */ - sqlite3OsClose(pReal); - *p = copy; - } - return rc; -} - - -/* -** Write data to the file. -*/ -static int memjrnlWrite( - sqlite3_file *pJfd, /* The journal file into which to write */ - const void *zBuf, /* Take data to be written from here */ - int iAmt, /* Number of bytes to write */ - sqlite_int64 iOfst /* Begin writing at this offset into the file */ -){ - MemJournal *p = (MemJournal *)pJfd; - int nWrite = iAmt; - u8 *zWrite = (u8 *)zBuf; - - /* If the file should be created now, create it and write the new data - ** into the file on disk. */ - if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){ - int rc = memjrnlCreateFile(p); - if( rc==SQLITE_OK ){ - rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst); - } - return rc; - } - - /* If the contents of this write should be stored in memory */ - else{ - /* An in-memory journal file should only ever be appended to. Random - ** access writes are not required. The only exception to this is when - ** the in-memory journal is being used by a connection using the - ** atomic-write optimization. In this case the first 28 bytes of the - ** journal file may be written as part of committing the transaction. */ - assert( iOfst==p->endpoint.iOffset || iOfst==0 ); -#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ - || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) - if( iOfst==0 && p->pFirst ){ - assert( p->nChunkSize>iAmt ); - memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt); - }else -#else - assert( iOfst>0 || p->pFirst==0 ); -#endif - { - while( nWrite>0 ){ - FileChunk *pChunk = p->endpoint.pChunk; - int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize); - int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset); - - if( iChunkOffset==0 ){ - /* New chunk is required to extend the file. */ - FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize)); - if( !pNew ){ - return SQLITE_IOERR_NOMEM_BKPT; - } - pNew->pNext = 0; - if( pChunk ){ - assert( p->pFirst ); - pChunk->pNext = pNew; - }else{ - assert( !p->pFirst ); - p->pFirst = pNew; - } - p->endpoint.pChunk = pNew; - } - - memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace); - zWrite += iSpace; - nWrite -= iSpace; - p->endpoint.iOffset += iSpace; - } - p->nSize = iAmt + iOfst; - } - } - - return SQLITE_OK; -} - -/* -** Truncate the file. -** -** If the journal file is already on disk, truncate it there. Or, if it -** is still in main memory but is being truncated to zero bytes in size, -** ignore -*/ -static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){ - MemJournal *p = (MemJournal *)pJfd; - if( ALWAYS(size==0) ){ - memjrnlFreeChunks(p); - p->nSize = 0; - p->endpoint.pChunk = 0; - p->endpoint.iOffset = 0; - p->readpoint.pChunk = 0; - p->readpoint.iOffset = 0; - } - return SQLITE_OK; -} - -/* -** Close the file. -*/ -static int memjrnlClose(sqlite3_file *pJfd){ - MemJournal *p = (MemJournal *)pJfd; - memjrnlFreeChunks(p); - return SQLITE_OK; -} - -/* -** Sync the file. -** -** If the real file has been created, call its xSync method. Otherwise, -** syncing an in-memory journal is a no-op. -*/ -static int memjrnlSync(sqlite3_file *pJfd, int flags){ - UNUSED_PARAMETER2(pJfd, flags); - return SQLITE_OK; -} - -/* -** Query the size of the file in bytes. -*/ -static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){ - MemJournal *p = (MemJournal *)pJfd; - *pSize = (sqlite_int64) p->endpoint.iOffset; - return SQLITE_OK; -} - -/* -** Table of methods for MemJournal sqlite3_file object. -*/ -static const struct sqlite3_io_methods MemJournalMethods = { - 1, /* iVersion */ - memjrnlClose, /* xClose */ - memjrnlRead, /* xRead */ - memjrnlWrite, /* xWrite */ - memjrnlTruncate, /* xTruncate */ - memjrnlSync, /* xSync */ - memjrnlFileSize, /* xFileSize */ - 0, /* xLock */ - 0, /* xUnlock */ - 0, /* xCheckReservedLock */ - 0, /* xFileControl */ - 0, /* xSectorSize */ - 0, /* xDeviceCharacteristics */ - 0, /* xShmMap */ - 0, /* xShmLock */ - 0, /* xShmBarrier */ - 0, /* xShmUnmap */ - 0, /* xFetch */ - 0 /* xUnfetch */ -}; - -/* -** Open a journal file. -** -** The behaviour of the journal file depends on the value of parameter -** nSpill. If nSpill is 0, then the journal file is always create and -** accessed using the underlying VFS. If nSpill is less than zero, then -** all content is always stored in main-memory. Finally, if nSpill is a -** positive value, then the journal file is initially created in-memory -** but may be flushed to disk later on. In this case the journal file is -** flushed to disk either when it grows larger than nSpill bytes in size, -** or when sqlite3JournalCreate() is called. -*/ -SQLITE_PRIVATE int sqlite3JournalOpen( - sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */ - const char *zName, /* Name of the journal file */ - sqlite3_file *pJfd, /* Preallocated, blank file handle */ - int flags, /* Opening flags */ - int nSpill /* Bytes buffered before opening the file */ -){ - MemJournal *p = (MemJournal*)pJfd; - - /* Zero the file-handle object. If nSpill was passed zero, initialize - ** it using the sqlite3OsOpen() function of the underlying VFS. In this - ** case none of the code in this module is executed as a result of calls - ** made on the journal file-handle. */ - memset(p, 0, sizeof(MemJournal)); - if( nSpill==0 ){ - return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); - } - - if( nSpill>0 ){ - p->nChunkSize = nSpill; - }else{ - p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk); - assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) ); - } - - pJfd->pMethods = (const sqlite3_io_methods*)&MemJournalMethods; - p->nSpill = nSpill; - p->flags = flags; - p->zJournal = zName; - p->pVfs = pVfs; - return SQLITE_OK; -} - -/* -** Open an in-memory journal file. -*/ -SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){ - sqlite3JournalOpen(0, 0, pJfd, 0, -1); -} - -#if defined(SQLITE_ENABLE_ATOMIC_WRITE) \ - || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) -/* -** If the argument p points to a MemJournal structure that is not an -** in-memory-only journal file (i.e. is one that was opened with a +ve -** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying -** file has not yet been created, create it now. -*/ -SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){ - int rc = SQLITE_OK; - MemJournal *p = (MemJournal*)pJfd; - if( pJfd->pMethods==&MemJournalMethods && ( -#ifdef SQLITE_ENABLE_ATOMIC_WRITE - p->nSpill>0 -#else - /* While this appears to not be possible without ATOMIC_WRITE, the - ** paths are complex, so it seems prudent to leave the test in as - ** a NEVER(), in case our analysis is subtly flawed. */ - NEVER(p->nSpill>0) -#endif -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - || (p->flags & SQLITE_OPEN_MAIN_JOURNAL) -#endif - )){ - rc = memjrnlCreateFile(p); - } - return rc; -} -#endif - -/* -** The file-handle passed as the only argument is open on a journal file. -** Return true if this "journal file" is currently stored in heap memory, -** or false otherwise. -*/ -SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){ - return p->pMethods==&MemJournalMethods; -} - -/* -** Return the number of bytes required to store a JournalFile that uses vfs -** pVfs to create the underlying on-disk files. -*/ -SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){ - return MAX(pVfs->szOsFile, (int)sizeof(MemJournal)); -} - -/************** End of memjournal.c ******************************************/ -/************** Begin file walker.c ******************************************/ -/* -** 2008 August 16 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains routines used for walking the parser tree for -** an SQL statement. -*/ -/* #include "sqliteInt.h" */ -/* #include */ -/* #include */ - - -#if !defined(SQLITE_OMIT_WINDOWFUNC) -/* -** Walk all expressions linked into the list of Window objects passed -** as the second argument. -*/ -static int walkWindowList(Walker *pWalker, Window *pList){ - Window *pWin; - for(pWin=pList; pWin; pWin=pWin->pNextWin){ - int rc; - rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy); - if( rc ) return WRC_Abort; - rc = sqlite3WalkExprList(pWalker, pWin->pPartition); - if( rc ) return WRC_Abort; - rc = sqlite3WalkExpr(pWalker, pWin->pFilter); - if( rc ) return WRC_Abort; - - /* The next two are purely for calls to sqlite3RenameExprUnmap() - ** within sqlite3WindowOffsetExpr(). Because of constraints imposed - ** by sqlite3WindowOffsetExpr(), they can never fail. The results do - ** not matter anyhow. */ - rc = sqlite3WalkExpr(pWalker, pWin->pStart); - if( NEVER(rc) ) return WRC_Abort; - rc = sqlite3WalkExpr(pWalker, pWin->pEnd); - if( NEVER(rc) ) return WRC_Abort; - } - return WRC_Continue; -} -#endif - -/* -** Walk an expression tree. Invoke the callback once for each node -** of the expression, while descending. (In other words, the callback -** is invoked before visiting children.) -** -** The return value from the callback should be one of the WRC_* -** constants to specify how to proceed with the walk. -** -** WRC_Continue Continue descending down the tree. -** -** WRC_Prune Do not descend into child nodes, but allow -** the walk to continue with sibling nodes. -** -** WRC_Abort Do no more callbacks. Unwind the stack and -** return from the top-level walk call. -** -** The return value from this routine is WRC_Abort to abandon the tree walk -** and WRC_Continue to continue. -*/ -static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){ - int rc; - testcase( ExprHasProperty(pExpr, EP_TokenOnly) ); - testcase( ExprHasProperty(pExpr, EP_Reduced) ); - while(1){ - rc = pWalker->xExprCallback(pWalker, pExpr); - if( rc ) return rc & WRC_Abort; - if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){ - assert( pExpr->x.pList==0 || pExpr->pRight==0 ); - if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; - if( pExpr->pRight ){ - assert( !ExprHasProperty(pExpr, EP_WinFunc) ); - pExpr = pExpr->pRight; - continue; - }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - assert( !ExprHasProperty(pExpr, EP_WinFunc) ); - if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; - }else{ - if( pExpr->x.pList ){ - if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; - } -#ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort; - } -#endif - } - } - break; - } - return WRC_Continue; -} -SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){ - return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue; -} - -/* -** Call sqlite3WalkExpr() for every expression in list p or until -** an abort request is seen. -*/ -SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){ - int i; - struct ExprList_item *pItem; - if( p ){ - for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ - if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort; - } - } - return WRC_Continue; -} - -/* -** Walk all expressions associated with SELECT statement p. Do -** not invoke the SELECT callback on p, but do (of course) invoke -** any expr callbacks and SELECT callbacks that come from subqueries. -** Return WRC_Abort or WRC_Continue. -*/ -SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){ - if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort; - if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort; - if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort; - if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort; -#if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE) - { - Parse *pParse = pWalker->pParse; - if( pParse && IN_RENAME_OBJECT ){ - /* The following may return WRC_Abort if there are unresolvable - ** symbols (e.g. a table that does not exist) in a window definition. */ - int rc = walkWindowList(pWalker, p->pWinDefn); - return rc; - } - } -#endif - return WRC_Continue; -} - -/* -** Walk the parse trees associated with all subqueries in the -** FROM clause of SELECT statement p. Do not invoke the select -** callback on p, but do invoke it on each FROM clause subquery -** and on any subqueries further down in the tree. Return -** WRC_Abort or WRC_Continue; -*/ -SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){ - SrcList *pSrc; - int i; - struct SrcList_item *pItem; - - pSrc = p->pSrc; - if( pSrc ){ - for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ - if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){ - return WRC_Abort; - } - if( pItem->fg.isTabFunc - && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg) - ){ - return WRC_Abort; - } - } - } - return WRC_Continue; -} - -/* -** Call sqlite3WalkExpr() for every expression in Select statement p. -** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and -** on the compound select chain, p->pPrior. -** -** If it is not NULL, the xSelectCallback() callback is invoked before -** the walk of the expressions and FROM clause. The xSelectCallback2() -** method is invoked following the walk of the expressions and FROM clause, -** but only if both xSelectCallback and xSelectCallback2 are both non-NULL -** and if the expressions and FROM clause both return WRC_Continue; -** -** Return WRC_Continue under normal conditions. Return WRC_Abort if -** there is an abort request. -** -** If the Walker does not have an xSelectCallback() then this routine -** is a no-op returning WRC_Continue. -*/ -SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){ - int rc; - if( p==0 ) return WRC_Continue; - if( pWalker->xSelectCallback==0 ) return WRC_Continue; - do{ - rc = pWalker->xSelectCallback(pWalker, p); - if( rc ) return rc & WRC_Abort; - if( sqlite3WalkSelectExpr(pWalker, p) - || sqlite3WalkSelectFrom(pWalker, p) - ){ - return WRC_Abort; - } - if( pWalker->xSelectCallback2 ){ - pWalker->xSelectCallback2(pWalker, p); - } - p = p->pPrior; - }while( p!=0 ); - return WRC_Continue; -} - -/* Increase the walkerDepth when entering a subquery, and -** descrease when leaving the subquery. -*/ -SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect){ - UNUSED_PARAMETER(pSelect); - pWalker->walkerDepth++; - return WRC_Continue; -} -SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect){ - UNUSED_PARAMETER(pSelect); - pWalker->walkerDepth--; -} - - -/* -** No-op routine for the parse-tree walker. -** -** When this routine is the Walker.xExprCallback then expression trees -** are walked without any actions being taken at each node. Presumably, -** when this routine is used for Walker.xExprCallback then -** Walker.xSelectCallback is set to do something useful for every -** subquery in the parser tree. -*/ -SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - return WRC_Continue; -} - -/* -** No-op routine for the parse-tree walker for SELECT statements. -** subquery in the parser tree. -*/ -SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - return WRC_Continue; -} - -/************** End of walker.c **********************************************/ -/************** Begin file resolve.c *****************************************/ -/* -** 2008 August 18 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains routines used for walking the parser tree and -** resolve all identifiers by associating them with a particular -** table and column. -*/ -/* #include "sqliteInt.h" */ - -/* -** Magic table number to mean the EXCLUDED table in an UPSERT statement. -*/ -#define EXCLUDED_TABLE_NUMBER 2 - -/* -** Walk the expression tree pExpr and increase the aggregate function -** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. -** This needs to occur when copying a TK_AGG_FUNCTION node from an -** outer query into an inner subquery. -** -** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) -** is a helper function - a callback for the tree walker. -** -** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c -*/ -static int incrAggDepth(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n; - return WRC_Continue; -} -static void incrAggFunctionDepth(Expr *pExpr, int N){ - if( N>0 ){ - Walker w; - memset(&w, 0, sizeof(w)); - w.xExprCallback = incrAggDepth; - w.u.n = N; - sqlite3WalkExpr(&w, pExpr); - } -} - -/* -** Turn the pExpr expression into an alias for the iCol-th column of the -** result set in pEList. -** -** If the reference is followed by a COLLATE operator, then make sure -** the COLLATE operator is preserved. For example: -** -** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; -** -** Should be transformed into: -** -** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; -** -** The nSubquery parameter specifies how many levels of subquery the -** alias is removed from the original expression. The usual value is -** zero but it might be more if the alias is contained within a subquery -** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION -** structures must be increased by the nSubquery amount. -*/ -static void resolveAlias( - Parse *pParse, /* Parsing context */ - ExprList *pEList, /* A result set */ - int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ - Expr *pExpr, /* Transform this into an alias to the result set */ - const char *zType, /* "GROUP" or "ORDER" or "" */ - int nSubquery /* Number of subqueries that the label is moving */ -){ - Expr *pOrig; /* The iCol-th column of the result set */ - Expr *pDup; /* Copy of pOrig */ - sqlite3 *db; /* The database connection */ - - assert( iCol>=0 && iColnExpr ); - pOrig = pEList->a[iCol].pExpr; - assert( pOrig!=0 ); - db = pParse->db; - pDup = sqlite3ExprDup(db, pOrig, 0); - if( pDup!=0 ){ - if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); - if( pExpr->op==TK_COLLATE ){ - pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); - } - - /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This - ** prevents ExprDelete() from deleting the Expr structure itself, - ** allowing it to be repopulated by the memcpy() on the following line. - ** The pExpr->u.zToken might point into memory that will be freed by the - ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to - ** make a copy of the token before doing the sqlite3DbFree(). - */ - ExprSetProperty(pExpr, EP_Static); - sqlite3ExprDelete(db, pExpr); - memcpy(pExpr, pDup, sizeof(*pExpr)); - if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ - assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); - pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); - pExpr->flags |= EP_MemToken; - } - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - if( pExpr->y.pWin!=0 ){ - pExpr->y.pWin->pOwner = pExpr; - }else{ - assert( db->mallocFailed ); - } - } - sqlite3DbFree(db, pDup); - } - ExprSetProperty(pExpr, EP_Alias); -} - - -/* -** Return TRUE if the name zCol occurs anywhere in the USING clause. -** -** Return FALSE if the USING clause is NULL or if it does not contain -** zCol. -*/ -static int nameInUsingClause(IdList *pUsing, const char *zCol){ - if( pUsing ){ - int k; - for(k=0; knId; k++){ - if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; - } - } - return 0; -} - -/* -** Subqueries stores the original database, table and column names for their -** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN". -** Check to see if the zSpan given to this routine matches the zDb, zTab, -** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will -** match anything. -*/ -SQLITE_PRIVATE int sqlite3MatchEName( - const struct ExprList_item *pItem, - const char *zCol, - const char *zTab, - const char *zDb -){ - int n; - const char *zSpan; - if( pItem->eEName!=ENAME_TAB ) return 0; - zSpan = pItem->zEName; - for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} - if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ - return 0; - } - zSpan += n+1; - for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} - if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ - return 0; - } - zSpan += n+1; - if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ - return 0; - } - return 1; -} - -/* -** Return TRUE if the double-quoted string mis-feature should be supported. -*/ -static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){ - if( db->init.busy ) return 1; /* Always support for legacy schemas */ - if( pTopNC->ncFlags & NC_IsDDL ){ - /* Currently parsing a DDL statement */ - if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){ - return 1; - } - return (db->flags & SQLITE_DqsDDL)!=0; - }else{ - /* Currently parsing a DML statement */ - return (db->flags & SQLITE_DqsDML)!=0; - } -} - -/* -** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN. -** return the appropriate colUsed mask. -*/ -SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr *pExpr){ - int n; - Table *pExTab; - - n = pExpr->iColumn; - pExTab = pExpr->y.pTab; - assert( pExTab!=0 ); - if( (pExTab->tabFlags & TF_HasGenerated)!=0 - && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0 - ){ - testcase( pExTab->nCol==BMS-1 ); - testcase( pExTab->nCol==BMS ); - return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1; - }else{ - testcase( n==BMS-1 ); - testcase( n==BMS ); - if( n>=BMS ) n = BMS-1; - return ((Bitmask)1)<iDb Set the index in db->aDb[] of the database X -** (even if X is implied). -** pExpr->iTable Set to the cursor number for the table obtained -** from pSrcList. -** pExpr->y.pTab Points to the Table structure of X.Y (even if -** X and/or Y are implied.) -** pExpr->iColumn Set to the column number within the table. -** pExpr->op Set to TK_COLUMN. -** pExpr->pLeft Any expression this points to is deleted -** pExpr->pRight Any expression this points to is deleted. -** -** The zDb variable is the name of the database (the "X"). This value may be -** NULL meaning that name is of the form Y.Z or Z. Any available database -** can be used. The zTable variable is the name of the table (the "Y"). This -** value can be NULL if zDb is also NULL. If zTable is NULL it -** means that the form of the name is Z and that columns from any table -** can be used. -** -** If the name cannot be resolved unambiguously, leave an error message -** in pParse and return WRC_Abort. Return WRC_Prune on success. -*/ -static int lookupName( - Parse *pParse, /* The parsing context */ - const char *zDb, /* Name of the database containing table, or NULL */ - const char *zTab, /* Name of table containing column, or NULL */ - const char *zCol, /* Name of the column. */ - NameContext *pNC, /* The name context used to resolve the name */ - Expr *pExpr /* Make this EXPR node point to the selected column */ -){ - int i, j; /* Loop counters */ - int cnt = 0; /* Number of matching column names */ - int cntTab = 0; /* Number of matching table names */ - int nSubquery = 0; /* How many levels of subquery */ - sqlite3 *db = pParse->db; /* The database connection */ - struct SrcList_item *pItem; /* Use for looping over pSrcList items */ - struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ - NameContext *pTopNC = pNC; /* First namecontext in the list */ - Schema *pSchema = 0; /* Schema of the expression */ - int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ - Table *pTab = 0; /* Table hold the row */ - Column *pCol; /* A column of pTab */ - - assert( pNC ); /* the name context cannot be NULL. */ - assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ - assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); - - /* Initialize the node to no-match */ - pExpr->iTable = -1; - ExprSetVVAProperty(pExpr, EP_NoReduce); - - /* Translate the schema name in zDb into a pointer to the corresponding - ** schema. If not found, pSchema will remain NULL and nothing will match - ** resulting in an appropriate error message toward the end of this routine - */ - if( zDb ){ - testcase( pNC->ncFlags & NC_PartIdx ); - testcase( pNC->ncFlags & NC_IsCheck ); - if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ - /* Silently ignore database qualifiers inside CHECK constraints and - ** partial indices. Do not raise errors because that might break - ** legacy and because it does not hurt anything to just ignore the - ** database name. */ - zDb = 0; - }else{ - for(i=0; inDb; i++){ - assert( db->aDb[i].zDbSName ); - if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ - pSchema = db->aDb[i].pSchema; - break; - } - } - if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){ - /* This branch is taken when the main database has been renamed - ** using SQLITE_DBCONFIG_MAINDBNAME. */ - pSchema = db->aDb[0].pSchema; - zDb = db->aDb[0].zDbSName; - } - } - } - - /* Start at the inner-most context and move outward until a match is found */ - assert( pNC && cnt==0 ); - do{ - ExprList *pEList; - SrcList *pSrcList = pNC->pSrcList; - - if( pSrcList ){ - for(i=0, pItem=pSrcList->a; inSrc; i++, pItem++){ - u8 hCol; - pTab = pItem->pTab; - assert( pTab!=0 && pTab->zName!=0 ); - assert( pTab->nCol>0 ); - if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ - int hit = 0; - pEList = pItem->pSelect->pEList; - for(j=0; jnExpr; j++){ - if( sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){ - cnt++; - cntTab = 2; - pMatch = pItem; - pExpr->iColumn = j; - hit = 1; - } - } - if( hit || zTab==0 ) continue; - } - if( zDb && pTab->pSchema!=pSchema ){ - continue; - } - if( zTab ){ - const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; - assert( zTabName!=0 ); - if( sqlite3StrICmp(zTabName, zTab)!=0 ){ - continue; - } - if( IN_RENAME_OBJECT && pItem->zAlias ){ - sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); - } - } - if( 0==(cntTab++) ){ - pMatch = pItem; - } - hCol = sqlite3StrIHash(zCol); - for(j=0, pCol=pTab->aCol; jnCol; j++, pCol++){ - if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){ - /* If there has been exactly one prior match and this match - ** is for the right-hand table of a NATURAL JOIN or is in a - ** USING clause, then skip this match. - */ - if( cnt==1 ){ - if( pItem->fg.jointype & JT_NATURAL ) continue; - if( nameInUsingClause(pItem->pUsing, zCol) ) continue; - } - cnt++; - pMatch = pItem; - /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ - pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; - break; - } - } - } - if( pMatch ){ - pExpr->iTable = pMatch->iCursor; - pExpr->y.pTab = pMatch->pTab; - /* RIGHT JOIN not (yet) supported */ - assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); - if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ - ExprSetProperty(pExpr, EP_CanBeNull); - } - pSchema = pExpr->y.pTab->pSchema; - } - } /* if( pSrcList ) */ - -#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) - /* If we have not already resolved the name, then maybe - ** it is a new.* or old.* trigger argument reference. Or - ** maybe it is an excluded.* from an upsert. - */ - if( zDb==0 && zTab!=0 && cntTab==0 ){ - pTab = 0; -#ifndef SQLITE_OMIT_TRIGGER - if( pParse->pTriggerTab!=0 ){ - int op = pParse->eTriggerOp; - assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); - if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ - pExpr->iTable = 1; - pTab = pParse->pTriggerTab; - }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ - pExpr->iTable = 0; - pTab = pParse->pTriggerTab; - } - } -#endif /* SQLITE_OMIT_TRIGGER */ -#ifndef SQLITE_OMIT_UPSERT - if( (pNC->ncFlags & NC_UUpsert)!=0 ){ - Upsert *pUpsert = pNC->uNC.pUpsert; - if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ - pTab = pUpsert->pUpsertSrc->a[0].pTab; - pExpr->iTable = EXCLUDED_TABLE_NUMBER; - } - } -#endif /* SQLITE_OMIT_UPSERT */ - - if( pTab ){ - int iCol; - u8 hCol = sqlite3StrIHash(zCol); - pSchema = pTab->pSchema; - cntTab++; - for(iCol=0, pCol=pTab->aCol; iColnCol; iCol++, pCol++){ - if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){ - if( iCol==pTab->iPKey ){ - iCol = -1; - } - break; - } - } - if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ - /* IMP: R-51414-32910 */ - iCol = -1; - } - if( iColnCol ){ - cnt++; -#ifndef SQLITE_OMIT_UPSERT - if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){ - testcase( iCol==(-1) ); - if( IN_RENAME_OBJECT ){ - pExpr->iColumn = iCol; - pExpr->y.pTab = pTab; - eNewExprOp = TK_COLUMN; - }else{ - pExpr->iTable = pNC->uNC.pUpsert->regData + - sqlite3TableColumnToStorage(pTab, iCol); - eNewExprOp = TK_REGISTER; - ExprSetProperty(pExpr, EP_Alias); - } - }else -#endif /* SQLITE_OMIT_UPSERT */ - { -#ifndef SQLITE_OMIT_TRIGGER - if( iCol<0 ){ - pExpr->affExpr = SQLITE_AFF_INTEGER; - }else if( pExpr->iTable==0 ){ - testcase( iCol==31 ); - testcase( iCol==32 ); - pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<y.pTab = pTab; - pExpr->iColumn = (i16)iCol; - eNewExprOp = TK_TRIGGER; -#endif /* SQLITE_OMIT_TRIGGER */ - } - } - } - } -#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ - - /* - ** Perhaps the name is a reference to the ROWID - */ - if( cnt==0 - && cntTab==1 - && pMatch - && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0 - && sqlite3IsRowid(zCol) - && VisibleRowid(pMatch->pTab) - ){ - cnt = 1; - pExpr->iColumn = -1; - pExpr->affExpr = SQLITE_AFF_INTEGER; - } - - /* - ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z - ** might refer to an result-set alias. This happens, for example, when - ** we are resolving names in the WHERE clause of the following command: - ** - ** SELECT a+b AS x FROM table WHERE x<10; - ** - ** In cases like this, replace pExpr with a copy of the expression that - ** forms the result set entry ("a+b" in the example) and return immediately. - ** Note that the expression in the result set should have already been - ** resolved by the time the WHERE clause is resolved. - ** - ** The ability to use an output result-set column in the WHERE, GROUP BY, - ** or HAVING clauses, or as part of a larger expression in the ORDER BY - ** clause is not standard SQL. This is a (goofy) SQLite extension, that - ** is supported for backwards compatibility only. Hence, we issue a warning - ** on sqlite3_log() whenever the capability is used. - */ - if( (pNC->ncFlags & NC_UEList)!=0 - && cnt==0 - && zTab==0 - ){ - pEList = pNC->uNC.pEList; - assert( pEList!=0 ); - for(j=0; jnExpr; j++){ - char *zAs = pEList->a[j].zEName; - if( pEList->a[j].eEName==ENAME_NAME - && sqlite3_stricmp(zAs, zCol)==0 - ){ - Expr *pOrig; - assert( pExpr->pLeft==0 && pExpr->pRight==0 ); - assert( pExpr->x.pList==0 ); - assert( pExpr->x.pSelect==0 ); - pOrig = pEList->a[j].pExpr; - if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ - sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); - return WRC_Abort; - } - if( ExprHasProperty(pOrig, EP_Win) - && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC ) - ){ - sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs); - return WRC_Abort; - } - if( sqlite3ExprVectorSize(pOrig)!=1 ){ - sqlite3ErrorMsg(pParse, "row value misused"); - return WRC_Abort; - } - resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); - cnt = 1; - pMatch = 0; - assert( zTab==0 && zDb==0 ); - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); - } - goto lookupname_end; - } - } - } - - /* Advance to the next name context. The loop will exit when either - ** we have a match (cnt>0) or when we run out of name contexts. - */ - if( cnt ) break; - pNC = pNC->pNext; - nSubquery++; - }while( pNC ); - - - /* - ** If X and Y are NULL (in other words if only the column name Z is - ** supplied) and the value of Z is enclosed in double-quotes, then - ** Z is a string literal if it doesn't match any column names. In that - ** case, we need to return right away and not make any changes to - ** pExpr. - ** - ** Because no reference was made to outer contexts, the pNC->nRef - ** fields are not changed in any context. - */ - if( cnt==0 && zTab==0 ){ - assert( pExpr->op==TK_ID ); - if( ExprHasProperty(pExpr,EP_DblQuoted) - && areDoubleQuotedStringsEnabled(db, pTopNC) - ){ - /* If a double-quoted identifier does not match any known column name, - ** then treat it as a string. - ** - ** This hack was added in the early days of SQLite in a misguided attempt - ** to be compatible with MySQL 3.x, which used double-quotes for strings. - ** I now sorely regret putting in this hack. The effect of this hack is - ** that misspelled identifier names are silently converted into strings - ** rather than causing an error, to the frustration of countless - ** programmers. To all those frustrated programmers, my apologies. - ** - ** Someday, I hope to get rid of this hack. Unfortunately there is - ** a huge amount of legacy SQL that uses it. So for now, we just - ** issue a warning. - */ - sqlite3_log(SQLITE_WARNING, - "double-quoted string literal: \"%w\"", zCol); -#ifdef SQLITE_ENABLE_NORMALIZE - sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); -#endif - pExpr->op = TK_STRING; - pExpr->y.pTab = 0; - return WRC_Prune; - } - if( sqlite3ExprIdToTrueFalse(pExpr) ){ - return WRC_Prune; - } - } - - /* - ** cnt==0 means there was not match. cnt>1 means there were two or - ** more matches. Either way, we have an error. - */ - if( cnt!=1 ){ - const char *zErr; - zErr = cnt==0 ? "no such column" : "ambiguous column name"; - if( zDb ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); - }else if( zTab ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); - }else{ - sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); - } - pParse->checkSchema = 1; - pTopNC->nErr++; - } - - /* If a column from a table in pSrcList is referenced, then record - ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes - ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is - ** set if the 63rd or any subsequent column is used. - ** - ** The colUsed mask is an optimization used to help determine if an - ** index is a covering index. The correct answer is still obtained - ** if the mask contains extra set bits. However, it is important to - ** avoid setting bits beyond the maximum column number of the table. - ** (See ticket [b92e5e8ec2cdbaa1]). - ** - ** If a generated column is referenced, set bits for every column - ** of the table. - */ - if( pExpr->iColumn>=0 && pMatch!=0 ){ - pMatch->colUsed |= sqlite3ExprColUsed(pExpr); - } - - /* Clean up and return - */ - sqlite3ExprDelete(db, pExpr->pLeft); - pExpr->pLeft = 0; - sqlite3ExprDelete(db, pExpr->pRight); - pExpr->pRight = 0; - pExpr->op = eNewExprOp; - ExprSetProperty(pExpr, EP_Leaf); -lookupname_end: - if( cnt==1 ){ - assert( pNC!=0 ); - if( !ExprHasProperty(pExpr, EP_Alias) ){ - sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); - } - /* Increment the nRef value on all name contexts from TopNC up to - ** the point where the name matched. */ - for(;;){ - assert( pTopNC!=0 ); - pTopNC->nRef++; - if( pTopNC==pNC ) break; - pTopNC = pTopNC->pNext; - } - return WRC_Prune; - } else { - return WRC_Abort; - } -} - -/* -** Allocate and return a pointer to an expression to load the column iCol -** from datasource iSrc in SrcList pSrc. -*/ -SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ - Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); - if( p ){ - struct SrcList_item *pItem = &pSrc->a[iSrc]; - Table *pTab = p->y.pTab = pItem->pTab; - p->iTable = pItem->iCursor; - if( p->y.pTab->iPKey==iCol ){ - p->iColumn = -1; - }else{ - p->iColumn = (ynVar)iCol; - if( (pTab->tabFlags & TF_HasGenerated)!=0 - && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0 - ){ - testcase( pTab->nCol==63 ); - testcase( pTab->nCol==64 ); - pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1; - }else{ - testcase( iCol==BMS ); - testcase( iCol==BMS-1 ); - pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); - } - } - } - return p; -} - -/* -** Report an error that an expression is not valid for some set of -** pNC->ncFlags values determined by validMask. -** -** static void notValid( -** Parse *pParse, // Leave error message here -** NameContext *pNC, // The name context -** const char *zMsg, // Type of error -** int validMask, // Set of contexts for which prohibited -** Expr *pExpr // Invalidate this expression on error -** ){...} -** -** As an optimization, since the conditional is almost always false -** (because errors are rare), the conditional is moved outside of the -** function call using a macro. -*/ -static void notValidImpl( - Parse *pParse, /* Leave error message here */ - NameContext *pNC, /* The name context */ - const char *zMsg, /* Type of error */ - Expr *pExpr /* Invalidate this expression on error */ -){ - const char *zIn = "partial index WHERE clauses"; - if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; -#ifndef SQLITE_OMIT_CHECK - else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; -#endif -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns"; -#endif - sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); - if( pExpr ) pExpr->op = TK_NULL; -} -#define sqlite3ResolveNotValid(P,N,M,X,E) \ - assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \ - if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E); - -/* -** Expression p should encode a floating point value between 1.0 and 0.0. -** Return 1024 times this value. Or return -1 if p is not a floating point -** value between 1.0 and 0.0. -*/ -static int exprProbability(Expr *p){ - double r = -1.0; - if( p->op!=TK_FLOAT ) return -1; - sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); - assert( r>=0.0 ); - if( r>1.0 ) return -1; - return (int)(r*134217728.0); -} - -/* -** This routine is callback for sqlite3WalkExpr(). -** -** Resolve symbolic names into TK_COLUMN operators for the current -** node in the expression tree. Return 0 to continue the search down -** the tree or 2 to abort the tree walk. -** -** This routine also does error checking and name resolution for -** function names. The operator for aggregate functions is changed -** to TK_AGG_FUNCTION. -*/ -static int resolveExprStep(Walker *pWalker, Expr *pExpr){ - NameContext *pNC; - Parse *pParse; - - pNC = pWalker->u.pNC; - assert( pNC!=0 ); - pParse = pNC->pParse; - assert( pParse==pWalker->pParse ); - -#ifndef NDEBUG - if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ - SrcList *pSrcList = pNC->pSrcList; - int i; - for(i=0; ipSrcList->nSrc; i++){ - assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursornTab); - } - } -#endif - switch( pExpr->op ){ - - /* The special operator TK_ROW means use the rowid for the first - ** column in the FROM clause. This is used by the LIMIT and ORDER BY - ** clause processing on UPDATE and DELETE statements, and by - ** UPDATE ... FROM statement processing. - */ - case TK_ROW: { - SrcList *pSrcList = pNC->pSrcList; - struct SrcList_item *pItem; - assert( pSrcList && pSrcList->nSrc>=1 ); - pItem = pSrcList->a; - pExpr->op = TK_COLUMN; - pExpr->y.pTab = pItem->pTab; - pExpr->iTable = pItem->iCursor; - pExpr->iColumn--; - pExpr->affExpr = SQLITE_AFF_INTEGER; - break; - } - - /* A column name: ID - ** Or table name and column name: ID.ID - ** Or a database, table and column: ID.ID.ID - ** - ** The TK_ID and TK_OUT cases are combined so that there will only - ** be one call to lookupName(). Then the compiler will in-line - ** lookupName() for a size reduction and performance increase. - */ - case TK_ID: - case TK_DOT: { - const char *zColumn; - const char *zTable; - const char *zDb; - Expr *pRight; - - if( pExpr->op==TK_ID ){ - zDb = 0; - zTable = 0; - zColumn = pExpr->u.zToken; - }else{ - Expr *pLeft = pExpr->pLeft; - testcase( pNC->ncFlags & NC_IdxExpr ); - testcase( pNC->ncFlags & NC_GenCol ); - sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator", - NC_IdxExpr|NC_GenCol, 0); - pRight = pExpr->pRight; - if( pRight->op==TK_ID ){ - zDb = 0; - }else{ - assert( pRight->op==TK_DOT ); - zDb = pLeft->u.zToken; - pLeft = pRight->pLeft; - pRight = pRight->pRight; - } - zTable = pLeft->u.zToken; - zColumn = pRight->u.zToken; - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight); - sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft); - } - } - return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); - } - - /* Resolve function names - */ - case TK_FUNCTION: { - ExprList *pList = pExpr->x.pList; /* The argument list */ - int n = pList ? pList->nExpr : 0; /* Number of arguments */ - int no_such_func = 0; /* True if no such function exists */ - int wrong_num_args = 0; /* True if wrong number of arguments */ - int is_agg = 0; /* True if is an aggregate function */ - int nId; /* Number of characters in function name */ - const char *zId; /* The function name. */ - FuncDef *pDef; /* Information about the function */ - u8 enc = ENC(pParse->db); /* The database encoding */ - int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin)); -#ifndef SQLITE_OMIT_WINDOWFUNC - Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0); -#endif - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - zId = pExpr->u.zToken; - nId = sqlite3Strlen30(zId); - pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); - if( pDef==0 ){ - pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); - if( pDef==0 ){ - no_such_func = 1; - }else{ - wrong_num_args = 1; - } - }else{ - is_agg = pDef->xFinalize!=0; - if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ - ExprSetProperty(pExpr, EP_Unlikely); - if( n==2 ){ - pExpr->iTable = exprProbability(pList->a[1].pExpr); - if( pExpr->iTable<0 ){ - sqlite3ErrorMsg(pParse, - "second argument to likelihood() must be a " - "constant between 0.0 and 1.0"); - pNC->nErr++; - } - }else{ - /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is - ** equivalent to likelihood(X, 0.0625). - ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is - ** short-hand for likelihood(X,0.0625). - ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand - ** for likelihood(X,0.9375). - ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent - ** to likelihood(X,0.9375). */ - /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */ - pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120; - } - } -#ifndef SQLITE_OMIT_AUTHORIZATION - { - int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); - if( auth!=SQLITE_OK ){ - if( auth==SQLITE_DENY ){ - sqlite3ErrorMsg(pParse, "not authorized to use function: %s", - pDef->zName); - pNC->nErr++; - } - pExpr->op = TK_NULL; - return WRC_Prune; - } - } -#endif - if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ - /* For the purposes of the EP_ConstFunc flag, date and time - ** functions and other functions that change slowly are considered - ** constant because they are constant for the duration of one query. - ** This allows them to be factored out of inner loops. */ - ExprSetProperty(pExpr,EP_ConstFunc); - } - if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ - /* Clearly non-deterministic functions like random(), but also - ** date/time functions that use 'now', and other functions like - ** sqlite_version() that might change over time cannot be used - ** in an index or generated column. Curiously, they can be used - ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all - ** all this. */ - sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions", - NC_IdxExpr|NC_PartIdx|NC_GenCol, 0); - }else{ - assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */ - pExpr->op2 = pNC->ncFlags & NC_SelfRef; - if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL); - } - if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 - && pParse->nested==0 - && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0 - ){ - /* Internal-use-only functions are disallowed unless the - ** SQL is being compiled using sqlite3NestedParse() or - ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be - ** used to activate internal functionsn for testing purposes */ - no_such_func = 1; - pDef = 0; - }else - if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 - && !IN_RENAME_OBJECT - ){ - sqlite3ExprFunctionUsable(pParse, pExpr, pDef); - } - } - - if( 0==IN_RENAME_OBJECT ){ -#ifndef SQLITE_OMIT_WINDOWFUNC - assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX) - || (pDef->xValue==0 && pDef->xInverse==0) - || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize) - ); - if( pDef && pDef->xValue==0 && pWin ){ - sqlite3ErrorMsg(pParse, - "%.*s() may not be used as a window function", nId, zId - ); - pNC->nErr++; - }else if( - (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) - || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin) - || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0) - ){ - const char *zType; - if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){ - zType = "window"; - }else{ - zType = "aggregate"; - } - sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId); - pNC->nErr++; - is_agg = 0; - } -#else - if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){ - sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId); - pNC->nErr++; - is_agg = 0; - } -#endif - else if( no_such_func && pParse->db->init.busy==0 -#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION - && pParse->explain==0 -#endif - ){ - sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); - pNC->nErr++; - }else if( wrong_num_args ){ - sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", - nId, zId); - pNC->nErr++; - } -#ifndef SQLITE_OMIT_WINDOWFUNC - else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){ - sqlite3ErrorMsg(pParse, - "FILTER may not be used with non-aggregate %.*s()", - nId, zId - ); - pNC->nErr++; - } -#endif - if( is_agg ){ - /* Window functions may not be arguments of aggregate functions. - ** Or arguments of other window functions. But aggregate functions - ** may be arguments for window functions. */ -#ifndef SQLITE_OMIT_WINDOWFUNC - pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0)); -#else - pNC->ncFlags &= ~NC_AllowAgg; -#endif - } - } -#ifndef SQLITE_OMIT_WINDOWFUNC - else if( ExprHasProperty(pExpr, EP_WinFunc) ){ - is_agg = 1; - } -#endif - sqlite3WalkExprList(pWalker, pList); - if( is_agg ){ -#ifndef SQLITE_OMIT_WINDOWFUNC - if( pWin ){ - Select *pSel = pNC->pWinSelect; - assert( pWin==pExpr->y.pWin ); - if( IN_RENAME_OBJECT==0 ){ - sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef); - } - sqlite3WalkExprList(pWalker, pWin->pPartition); - sqlite3WalkExprList(pWalker, pWin->pOrderBy); - sqlite3WalkExpr(pWalker, pWin->pFilter); - sqlite3WindowLink(pSel, pWin); - pNC->ncFlags |= NC_HasWin; - }else -#endif /* SQLITE_OMIT_WINDOWFUNC */ - { - NameContext *pNC2 = pNC; - pExpr->op = TK_AGG_FUNCTION; - pExpr->op2 = 0; -#ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter); - } -#endif - while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ - pExpr->op2++; - pNC2 = pNC2->pNext; - } - assert( pDef!=0 || IN_RENAME_OBJECT ); - if( pNC2 && pDef ){ - assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); - testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); - pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); - - } - } - pNC->ncFlags |= savedAllowFlags; - } - /* FIX ME: Compute pExpr->affinity based on the expected return - ** type of the function - */ - return WRC_Prune; - } -#ifndef SQLITE_OMIT_SUBQUERY - case TK_SELECT: - case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); -#endif - case TK_IN: { - testcase( pExpr->op==TK_IN ); - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - int nRef = pNC->nRef; - testcase( pNC->ncFlags & NC_IsCheck ); - testcase( pNC->ncFlags & NC_PartIdx ); - testcase( pNC->ncFlags & NC_IdxExpr ); - testcase( pNC->ncFlags & NC_GenCol ); - sqlite3ResolveNotValid(pParse, pNC, "subqueries", - NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr); - sqlite3WalkSelect(pWalker, pExpr->x.pSelect); - assert( pNC->nRef>=nRef ); - if( nRef!=pNC->nRef ){ - ExprSetProperty(pExpr, EP_VarSelect); - pNC->ncFlags |= NC_VarSelect; - } - } - break; - } - case TK_VARIABLE: { - testcase( pNC->ncFlags & NC_IsCheck ); - testcase( pNC->ncFlags & NC_PartIdx ); - testcase( pNC->ncFlags & NC_IdxExpr ); - testcase( pNC->ncFlags & NC_GenCol ); - sqlite3ResolveNotValid(pParse, pNC, "parameters", - NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr); - break; - } - case TK_IS: - case TK_ISNOT: { - Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight); - assert( !ExprHasProperty(pExpr, EP_Reduced) ); - /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE", - ** and "x IS NOT FALSE". */ - if( pRight && pRight->op==TK_ID ){ - int rc = resolveExprStep(pWalker, pRight); - if( rc==WRC_Abort ) return WRC_Abort; - if( pRight->op==TK_TRUEFALSE ){ - pExpr->op2 = pExpr->op; - pExpr->op = TK_TRUTH; - return WRC_Continue; - } - } - /* no break */ deliberate_fall_through - } - case TK_BETWEEN: - case TK_EQ: - case TK_NE: - case TK_LT: - case TK_LE: - case TK_GT: - case TK_GE: { - int nLeft, nRight; - if( pParse->db->mallocFailed ) break; - assert( pExpr->pLeft!=0 ); - nLeft = sqlite3ExprVectorSize(pExpr->pLeft); - if( pExpr->op==TK_BETWEEN ){ - nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); - if( nRight==nLeft ){ - nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); - } - }else{ - assert( pExpr->pRight!=0 ); - nRight = sqlite3ExprVectorSize(pExpr->pRight); - } - if( nLeft!=nRight ){ - testcase( pExpr->op==TK_EQ ); - testcase( pExpr->op==TK_NE ); - testcase( pExpr->op==TK_LT ); - testcase( pExpr->op==TK_LE ); - testcase( pExpr->op==TK_GT ); - testcase( pExpr->op==TK_GE ); - testcase( pExpr->op==TK_IS ); - testcase( pExpr->op==TK_ISNOT ); - testcase( pExpr->op==TK_BETWEEN ); - sqlite3ErrorMsg(pParse, "row value misused"); - } - break; - } - } - return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; -} - -/* -** pEList is a list of expressions which are really the result set of the -** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. -** This routine checks to see if pE is a simple identifier which corresponds -** to the AS-name of one of the terms of the expression list. If it is, -** this routine return an integer between 1 and N where N is the number of -** elements in pEList, corresponding to the matching entry. If there is -** no match, or if pE is not a simple identifier, then this routine -** return 0. -** -** pEList has been resolved. pE has not. -*/ -static int resolveAsName( - Parse *pParse, /* Parsing context for error messages */ - ExprList *pEList, /* List of expressions to scan */ - Expr *pE /* Expression we are trying to match */ -){ - int i; /* Loop counter */ - - UNUSED_PARAMETER(pParse); - - if( pE->op==TK_ID ){ - char *zCol = pE->u.zToken; - for(i=0; inExpr; i++){ - if( pEList->a[i].eEName==ENAME_NAME - && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0 - ){ - return i+1; - } - } - } - return 0; -} - -/* -** pE is a pointer to an expression which is a single term in the -** ORDER BY of a compound SELECT. The expression has not been -** name resolved. -** -** At the point this routine is called, we already know that the -** ORDER BY term is not an integer index into the result set. That -** case is handled by the calling routine. -** -** Attempt to match pE against result set columns in the left-most -** SELECT statement. Return the index i of the matching column, -** as an indication to the caller that it should sort by the i-th column. -** The left-most column is 1. In other words, the value returned is the -** same integer value that would be used in the SQL statement to indicate -** the column. -** -** If there is no match, return 0. Return -1 if an error occurs. -*/ -static int resolveOrderByTermToExprList( - Parse *pParse, /* Parsing context for error messages */ - Select *pSelect, /* The SELECT statement with the ORDER BY clause */ - Expr *pE /* The specific ORDER BY term */ -){ - int i; /* Loop counter */ - ExprList *pEList; /* The columns of the result set */ - NameContext nc; /* Name context for resolving pE */ - sqlite3 *db; /* Database connection */ - int rc; /* Return code from subprocedures */ - u8 savedSuppErr; /* Saved value of db->suppressErr */ - - assert( sqlite3ExprIsInteger(pE, &i)==0 ); - pEList = pSelect->pEList; - - /* Resolve all names in the ORDER BY term expression - */ - memset(&nc, 0, sizeof(nc)); - nc.pParse = pParse; - nc.pSrcList = pSelect->pSrc; - nc.uNC.pEList = pEList; - nc.ncFlags = NC_AllowAgg|NC_UEList; - nc.nErr = 0; - db = pParse->db; - savedSuppErr = db->suppressErr; - if( IN_RENAME_OBJECT==0 ) db->suppressErr = 1; - rc = sqlite3ResolveExprNames(&nc, pE); - db->suppressErr = savedSuppErr; - if( rc ) return 0; - - /* Try to match the ORDER BY expression against an expression - ** in the result set. Return an 1-based index of the matching - ** result-set entry. - */ - for(i=0; inExpr; i++){ - if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){ - return i+1; - } - } - - /* If no match, return 0. */ - return 0; -} - -/* -** Generate an ORDER BY or GROUP BY term out-of-range error. -*/ -static void resolveOutOfRangeError( - Parse *pParse, /* The error context into which to write the error */ - const char *zType, /* "ORDER" or "GROUP" */ - int i, /* The index (1-based) of the term out of range */ - int mx /* Largest permissible value of i */ -){ - sqlite3ErrorMsg(pParse, - "%r %s BY term out of range - should be " - "between 1 and %d", i, zType, mx); -} - -/* -** Analyze the ORDER BY clause in a compound SELECT statement. Modify -** each term of the ORDER BY clause is a constant integer between 1 -** and N where N is the number of columns in the compound SELECT. -** -** ORDER BY terms that are already an integer between 1 and N are -** unmodified. ORDER BY terms that are integers outside the range of -** 1 through N generate an error. ORDER BY terms that are expressions -** are matched against result set expressions of compound SELECT -** beginning with the left-most SELECT and working toward the right. -** At the first match, the ORDER BY expression is transformed into -** the integer column number. -** -** Return the number of errors seen. -*/ -static int resolveCompoundOrderBy( - Parse *pParse, /* Parsing context. Leave error messages here */ - Select *pSelect /* The SELECT statement containing the ORDER BY */ -){ - int i; - ExprList *pOrderBy; - ExprList *pEList; - sqlite3 *db; - int moreToDo = 1; - - pOrderBy = pSelect->pOrderBy; - if( pOrderBy==0 ) return 0; - db = pParse->db; - if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); - return 1; - } - for(i=0; inExpr; i++){ - pOrderBy->a[i].done = 0; - } - pSelect->pNext = 0; - while( pSelect->pPrior ){ - pSelect->pPrior->pNext = pSelect; - pSelect = pSelect->pPrior; - } - while( pSelect && moreToDo ){ - struct ExprList_item *pItem; - moreToDo = 0; - pEList = pSelect->pEList; - assert( pEList!=0 ); - for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ - int iCol = -1; - Expr *pE, *pDup; - if( pItem->done ) continue; - pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr); - if( sqlite3ExprIsInteger(pE, &iCol) ){ - if( iCol<=0 || iCol>pEList->nExpr ){ - resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); - return 1; - } - }else{ - iCol = resolveAsName(pParse, pEList, pE); - if( iCol==0 ){ - /* Now test if expression pE matches one of the values returned - ** by pSelect. In the usual case this is done by duplicating the - ** expression, resolving any symbols in it, and then comparing - ** it against each expression returned by the SELECT statement. - ** Once the comparisons are finished, the duplicate expression - ** is deleted. - ** - ** Or, if this is running as part of an ALTER TABLE operation, - ** resolve the symbols in the actual expression, not a duplicate. - ** And, if one of the comparisons is successful, leave the expression - ** as is instead of transforming it to an integer as in the usual - ** case. This allows the code in alter.c to modify column - ** refererences within the ORDER BY expression as required. */ - if( IN_RENAME_OBJECT ){ - pDup = pE; - }else{ - pDup = sqlite3ExprDup(db, pE, 0); - } - if( !db->mallocFailed ){ - assert(pDup); - iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); - } - if( !IN_RENAME_OBJECT ){ - sqlite3ExprDelete(db, pDup); - } - } - } - if( iCol>0 ){ - /* Convert the ORDER BY term into an integer column number iCol, - ** taking care to preserve the COLLATE clause if it exists */ - if( !IN_RENAME_OBJECT ){ - Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); - if( pNew==0 ) return 1; - pNew->flags |= EP_IntValue; - pNew->u.iValue = iCol; - if( pItem->pExpr==pE ){ - pItem->pExpr = pNew; - }else{ - Expr *pParent = pItem->pExpr; - assert( pParent->op==TK_COLLATE ); - while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; - assert( pParent->pLeft==pE ); - pParent->pLeft = pNew; - } - sqlite3ExprDelete(db, pE); - pItem->u.x.iOrderByCol = (u16)iCol; - } - pItem->done = 1; - }else{ - moreToDo = 1; - } - } - pSelect = pSelect->pNext; - } - for(i=0; inExpr; i++){ - if( pOrderBy->a[i].done==0 ){ - sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " - "column in the result set", i+1); - return 1; - } - } - return 0; -} - -/* -** Check every term in the ORDER BY or GROUP BY clause pOrderBy of -** the SELECT statement pSelect. If any term is reference to a -** result set expression (as determined by the ExprList.a.u.x.iOrderByCol -** field) then convert that term into a copy of the corresponding result set -** column. -** -** If any errors are detected, add an error message to pParse and -** return non-zero. Return zero if no errors are seen. -*/ -SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy( - Parse *pParse, /* Parsing context. Leave error messages here */ - Select *pSelect, /* The SELECT statement containing the clause */ - ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ - const char *zType /* "ORDER" or "GROUP" */ -){ - int i; - sqlite3 *db = pParse->db; - ExprList *pEList; - struct ExprList_item *pItem; - - if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0; - if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); - return 1; - } - pEList = pSelect->pEList; - assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ - for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ - if( pItem->u.x.iOrderByCol ){ - if( pItem->u.x.iOrderByCol>pEList->nExpr ){ - resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); - return 1; - } - resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, - zType,0); - } - } - return 0; -} - -#ifndef SQLITE_OMIT_WINDOWFUNC -/* -** Walker callback for windowRemoveExprFromSelect(). -*/ -static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){ - UNUSED_PARAMETER(pWalker); - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - Window *pWin = pExpr->y.pWin; - sqlite3WindowUnlinkFromSelect(pWin); - } - return WRC_Continue; -} - -/* -** Remove any Window objects owned by the expression pExpr from the -** Select.pWin list of Select object pSelect. -*/ -static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){ - if( pSelect->pWin ){ - Walker sWalker; - memset(&sWalker, 0, sizeof(Walker)); - sWalker.xExprCallback = resolveRemoveWindowsCb; - sWalker.u.pSelect = pSelect; - sqlite3WalkExpr(&sWalker, pExpr); - } -} -#else -# define windowRemoveExprFromSelect(a, b) -#endif /* SQLITE_OMIT_WINDOWFUNC */ - -/* -** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. -** The Name context of the SELECT statement is pNC. zType is either -** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. -** -** This routine resolves each term of the clause into an expression. -** If the order-by term is an integer I between 1 and N (where N is the -** number of columns in the result set of the SELECT) then the expression -** in the resolution is a copy of the I-th result-set expression. If -** the order-by term is an identifier that corresponds to the AS-name of -** a result-set expression, then the term resolves to a copy of the -** result-set expression. Otherwise, the expression is resolved in -** the usual way - using sqlite3ResolveExprNames(). -** -** This routine returns the number of errors. If errors occur, then -** an appropriate error message might be left in pParse. (OOM errors -** excepted.) -*/ -static int resolveOrderGroupBy( - NameContext *pNC, /* The name context of the SELECT statement */ - Select *pSelect, /* The SELECT statement holding pOrderBy */ - ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ - const char *zType /* Either "ORDER" or "GROUP", as appropriate */ -){ - int i, j; /* Loop counters */ - int iCol; /* Column number */ - struct ExprList_item *pItem; /* A term of the ORDER BY clause */ - Parse *pParse; /* Parsing context */ - int nResult; /* Number of terms in the result set */ - - if( pOrderBy==0 ) return 0; - nResult = pSelect->pEList->nExpr; - pParse = pNC->pParse; - for(i=0, pItem=pOrderBy->a; inExpr; i++, pItem++){ - Expr *pE = pItem->pExpr; - Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE); - if( zType[0]!='G' ){ - iCol = resolveAsName(pParse, pSelect->pEList, pE2); - if( iCol>0 ){ - /* If an AS-name match is found, mark this ORDER BY column as being - ** a copy of the iCol-th result-set column. The subsequent call to - ** sqlite3ResolveOrderGroupBy() will convert the expression to a - ** copy of the iCol-th result-set expression. */ - pItem->u.x.iOrderByCol = (u16)iCol; - continue; - } - } - if( sqlite3ExprIsInteger(pE2, &iCol) ){ - /* The ORDER BY term is an integer constant. Again, set the column - ** number so that sqlite3ResolveOrderGroupBy() will convert the - ** order-by term to a copy of the result-set expression */ - if( iCol<1 || iCol>0xffff ){ - resolveOutOfRangeError(pParse, zType, i+1, nResult); - return 1; - } - pItem->u.x.iOrderByCol = (u16)iCol; - continue; - } - - /* Otherwise, treat the ORDER BY term as an ordinary expression */ - pItem->u.x.iOrderByCol = 0; - if( sqlite3ResolveExprNames(pNC, pE) ){ - return 1; - } - for(j=0; jpEList->nExpr; j++){ - if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ - /* Since this expresion is being changed into a reference - ** to an identical expression in the result set, remove all Window - ** objects belonging to the expression from the Select.pWin list. */ - windowRemoveExprFromSelect(pSelect, pE); - pItem->u.x.iOrderByCol = j+1; - } - } - } - return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); -} - -/* -** Resolve names in the SELECT statement p and all of its descendants. -*/ -static int resolveSelectStep(Walker *pWalker, Select *p){ - NameContext *pOuterNC; /* Context that contains this SELECT */ - NameContext sNC; /* Name context of this SELECT */ - int isCompound; /* True if p is a compound select */ - int nCompound; /* Number of compound terms processed so far */ - Parse *pParse; /* Parsing context */ - int i; /* Loop counter */ - ExprList *pGroupBy; /* The GROUP BY clause */ - Select *pLeftmost; /* Left-most of SELECT of a compound */ - sqlite3 *db; /* Database connection */ - - - assert( p!=0 ); - if( p->selFlags & SF_Resolved ){ - return WRC_Prune; - } - pOuterNC = pWalker->u.pNC; - pParse = pWalker->pParse; - db = pParse->db; - - /* Normally sqlite3SelectExpand() will be called first and will have - ** already expanded this SELECT. However, if this is a subquery within - ** an expression, sqlite3ResolveExprNames() will be called without a - ** prior call to sqlite3SelectExpand(). When that happens, let - ** sqlite3SelectPrep() do all of the processing for this SELECT. - ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and - ** this routine in the correct order. - */ - if( (p->selFlags & SF_Expanded)==0 ){ - sqlite3SelectPrep(pParse, p, pOuterNC); - return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; - } - - isCompound = p->pPrior!=0; - nCompound = 0; - pLeftmost = p; - while( p ){ - assert( (p->selFlags & SF_Expanded)!=0 ); - assert( (p->selFlags & SF_Resolved)==0 ); - p->selFlags |= SF_Resolved; - - /* Resolve the expressions in the LIMIT and OFFSET clauses. These - ** are not allowed to refer to any names, so pass an empty NameContext. - */ - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - sNC.pWinSelect = p; - if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){ - return WRC_Abort; - } - - /* If the SF_Converted flags is set, then this Select object was - ** was created by the convertCompoundSelectToSubquery() function. - ** In this case the ORDER BY clause (p->pOrderBy) should be resolved - ** as if it were part of the sub-query, not the parent. This block - ** moves the pOrderBy down to the sub-query. It will be moved back - ** after the names have been resolved. */ - if( p->selFlags & SF_Converted ){ - Select *pSub = p->pSrc->a[0].pSelect; - assert( p->pSrc->nSrc==1 && p->pOrderBy ); - assert( pSub->pPrior && pSub->pOrderBy==0 ); - pSub->pOrderBy = p->pOrderBy; - p->pOrderBy = 0; - } - - /* Recursively resolve names in all subqueries - */ - for(i=0; ipSrc->nSrc; i++){ - struct SrcList_item *pItem = &p->pSrc->a[i]; - if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){ - NameContext *pNC; /* Used to iterate name contexts */ - int nRef = 0; /* Refcount for pOuterNC and outer contexts */ - const char *zSavedContext = pParse->zAuthContext; - - /* Count the total number of references to pOuterNC and all of its - ** parent contexts. After resolving references to expressions in - ** pItem->pSelect, check if this value has changed. If so, then - ** SELECT statement pItem->pSelect must be correlated. Set the - ** pItem->fg.isCorrelated flag if this is the case. */ - for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; - - if( pItem->zName ) pParse->zAuthContext = pItem->zName; - sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); - pParse->zAuthContext = zSavedContext; - if( pParse->nErr || db->mallocFailed ) return WRC_Abort; - - for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef; - assert( pItem->fg.isCorrelated==0 && nRef<=0 ); - pItem->fg.isCorrelated = (nRef!=0); - } - } - - /* Set up the local name-context to pass to sqlite3ResolveExprNames() to - ** resolve the result-set expression list. - */ - sNC.ncFlags = NC_AllowAgg|NC_AllowWin; - sNC.pSrcList = p->pSrc; - sNC.pNext = pOuterNC; - - /* Resolve names in the result set. */ - if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; - sNC.ncFlags &= ~NC_AllowWin; - - /* If there are no aggregate functions in the result-set, and no GROUP BY - ** expression, do not allow aggregates in any of the other expressions. - */ - assert( (p->selFlags & SF_Aggregate)==0 ); - pGroupBy = p->pGroupBy; - if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ - assert( NC_MinMaxAgg==SF_MinMaxAgg ); - p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg); - }else{ - sNC.ncFlags &= ~NC_AllowAgg; - } - - /* If a HAVING clause is present, then there must be a GROUP BY clause. - */ - if( p->pHaving && !pGroupBy ){ - sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); - return WRC_Abort; - } - - /* Add the output column list to the name-context before parsing the - ** other expressions in the SELECT statement. This is so that - ** expressions in the WHERE clause (etc.) can refer to expressions by - ** aliases in the result set. - ** - ** Minor point: If this is the case, then the expression will be - ** re-evaluated for each reference to it. - */ - assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 ); - sNC.uNC.pEList = p->pEList; - sNC.ncFlags |= NC_UEList; - if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; - if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; - - /* Resolve names in table-valued-function arguments */ - for(i=0; ipSrc->nSrc; i++){ - struct SrcList_item *pItem = &p->pSrc->a[i]; - if( pItem->fg.isTabFunc - && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) - ){ - return WRC_Abort; - } - } - - /* The ORDER BY and GROUP BY clauses may not refer to terms in - ** outer queries - */ - sNC.pNext = 0; - sNC.ncFlags |= NC_AllowAgg|NC_AllowWin; - - /* If this is a converted compound query, move the ORDER BY clause from - ** the sub-query back to the parent query. At this point each term - ** within the ORDER BY clause has been transformed to an integer value. - ** These integers will be replaced by copies of the corresponding result - ** set expressions by the call to resolveOrderGroupBy() below. */ - if( p->selFlags & SF_Converted ){ - Select *pSub = p->pSrc->a[0].pSelect; - p->pOrderBy = pSub->pOrderBy; - pSub->pOrderBy = 0; - } - - /* Process the ORDER BY clause for singleton SELECT statements. - ** The ORDER BY clause for compounds SELECT statements is handled - ** below, after all of the result-sets for all of the elements of - ** the compound have been resolved. - ** - ** If there is an ORDER BY clause on a term of a compound-select other - ** than the right-most term, then that is a syntax error. But the error - ** is not detected until much later, and so we need to go ahead and - ** resolve those symbols on the incorrect ORDER BY for consistency. - */ - if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */ - && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") - ){ - return WRC_Abort; - } - if( db->mallocFailed ){ - return WRC_Abort; - } - sNC.ncFlags &= ~NC_AllowWin; - - /* Resolve the GROUP BY clause. At the same time, make sure - ** the GROUP BY clause does not contain aggregate functions. - */ - if( pGroupBy ){ - struct ExprList_item *pItem; - - if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ - return WRC_Abort; - } - for(i=0, pItem=pGroupBy->a; inExpr; i++, pItem++){ - if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ - sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " - "the GROUP BY clause"); - return WRC_Abort; - } - } - } - -#ifndef SQLITE_OMIT_WINDOWFUNC - if( IN_RENAME_OBJECT ){ - Window *pWin; - for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){ - if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy) - || sqlite3ResolveExprListNames(&sNC, pWin->pPartition) - ){ - return WRC_Abort; - } - } - } -#endif - - /* If this is part of a compound SELECT, check that it has the right - ** number of expressions in the select list. */ - if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){ - sqlite3SelectWrongNumTermsError(pParse, p->pNext); - return WRC_Abort; - } - - /* Advance to the next term of the compound - */ - p = p->pPrior; - nCompound++; - } - - /* Resolve the ORDER BY on a compound SELECT after all terms of - ** the compound have been resolved. - */ - if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ - return WRC_Abort; - } - - return WRC_Prune; -} - -/* -** This routine walks an expression tree and resolves references to -** table columns and result-set columns. At the same time, do error -** checking on function usage and set a flag if any aggregate functions -** are seen. -** -** To resolve table columns references we look for nodes (or subtrees) of the -** form X.Y.Z or Y.Z or just Z where -** -** X: The name of a database. Ex: "main" or "temp" or -** the symbolic name assigned to an ATTACH-ed database. -** -** Y: The name of a table in a FROM clause. Or in a trigger -** one of the special names "old" or "new". -** -** Z: The name of a column in table Y. -** -** The node at the root of the subtree is modified as follows: -** -** Expr.op Changed to TK_COLUMN -** Expr.pTab Points to the Table object for X.Y -** Expr.iColumn The column index in X.Y. -1 for the rowid. -** Expr.iTable The VDBE cursor number for X.Y -** -** -** To resolve result-set references, look for expression nodes of the -** form Z (with no X and Y prefix) where the Z matches the right-hand -** size of an AS clause in the result-set of a SELECT. The Z expression -** is replaced by a copy of the left-hand side of the result-set expression. -** Table-name and function resolution occurs on the substituted expression -** tree. For example, in: -** -** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; -** -** The "x" term of the order by is replaced by "a+b" to render: -** -** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; -** -** Function calls are checked to make sure that the function is -** defined and that the correct number of arguments are specified. -** If the function is an aggregate function, then the NC_HasAgg flag is -** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. -** If an expression contains aggregate functions then the EP_Agg -** property on the expression is set. -** -** An error message is left in pParse if anything is amiss. The number -** if errors is returned. -*/ -SQLITE_PRIVATE int sqlite3ResolveExprNames( - NameContext *pNC, /* Namespace to resolve expressions in. */ - Expr *pExpr /* The expression to be analyzed. */ -){ - int savedHasAgg; - Walker w; - - if( pExpr==0 ) return SQLITE_OK; - savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin); - pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin); - w.pParse = pNC->pParse; - w.xExprCallback = resolveExprStep; - w.xSelectCallback = resolveSelectStep; - w.xSelectCallback2 = 0; - w.u.pNC = pNC; -#if SQLITE_MAX_EXPR_DEPTH>0 - w.pParse->nHeight += pExpr->nHeight; - if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){ - return SQLITE_ERROR; - } -#endif - sqlite3WalkExpr(&w, pExpr); -#if SQLITE_MAX_EXPR_DEPTH>0 - w.pParse->nHeight -= pExpr->nHeight; -#endif - assert( EP_Agg==NC_HasAgg ); - assert( EP_Win==NC_HasWin ); - testcase( pNC->ncFlags & NC_HasAgg ); - testcase( pNC->ncFlags & NC_HasWin ); - ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) ); - pNC->ncFlags |= savedHasAgg; - return pNC->nErr>0 || w.pParse->nErr>0; -} - -/* -** Resolve all names for all expression in an expression list. This is -** just like sqlite3ResolveExprNames() except that it works for an expression -** list rather than a single expression. -*/ -SQLITE_PRIVATE int sqlite3ResolveExprListNames( - NameContext *pNC, /* Namespace to resolve expressions in. */ - ExprList *pList /* The expression list to be analyzed. */ -){ - int i; - int savedHasAgg = 0; - Walker w; - if( pList==0 ) return WRC_Continue; - w.pParse = pNC->pParse; - w.xExprCallback = resolveExprStep; - w.xSelectCallback = resolveSelectStep; - w.xSelectCallback2 = 0; - w.u.pNC = pNC; - savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin); - pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin); - for(i=0; inExpr; i++){ - Expr *pExpr = pList->a[i].pExpr; - if( pExpr==0 ) continue; -#if SQLITE_MAX_EXPR_DEPTH>0 - w.pParse->nHeight += pExpr->nHeight; - if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){ - return WRC_Abort; - } -#endif - sqlite3WalkExpr(&w, pExpr); -#if SQLITE_MAX_EXPR_DEPTH>0 - w.pParse->nHeight -= pExpr->nHeight; -#endif - assert( EP_Agg==NC_HasAgg ); - assert( EP_Win==NC_HasWin ); - testcase( pNC->ncFlags & NC_HasAgg ); - testcase( pNC->ncFlags & NC_HasWin ); - if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin) ){ - ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) ); - savedHasAgg |= pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin); - pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin); - } - if( pNC->nErr>0 || w.pParse->nErr>0 ) return WRC_Abort; - } - pNC->ncFlags |= savedHasAgg; - return WRC_Continue; -} - -/* -** Resolve all names in all expressions of a SELECT and in all -** decendents of the SELECT, including compounds off of p->pPrior, -** subqueries in expressions, and subqueries used as FROM clause -** terms. -** -** See sqlite3ResolveExprNames() for a description of the kinds of -** transformations that occur. -** -** All SELECT statements should have been expanded using -** sqlite3SelectExpand() prior to invoking this routine. -*/ -SQLITE_PRIVATE void sqlite3ResolveSelectNames( - Parse *pParse, /* The parser context */ - Select *p, /* The SELECT statement being coded. */ - NameContext *pOuterNC /* Name context for parent SELECT statement */ -){ - Walker w; - - assert( p!=0 ); - w.xExprCallback = resolveExprStep; - w.xSelectCallback = resolveSelectStep; - w.xSelectCallback2 = 0; - w.pParse = pParse; - w.u.pNC = pOuterNC; - sqlite3WalkSelect(&w, p); -} - -/* -** Resolve names in expressions that can only reference a single table -** or which cannot reference any tables at all. Examples: -** -** "type" flag -** ------------ -** (1) CHECK constraints NC_IsCheck -** (2) WHERE clauses on partial indices NC_PartIdx -** (3) Expressions in indexes on expressions NC_IdxExpr -** (4) Expression arguments to VACUUM INTO. 0 -** (5) GENERATED ALWAYS as expressions NC_GenCol -** -** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN -** nodes of the expression is set to -1 and the Expr.iColumn value is -** set to the column number. In case (4), TK_COLUMN nodes cause an error. -** -** Any errors cause an error message to be set in pParse. -*/ -SQLITE_PRIVATE int sqlite3ResolveSelfReference( - Parse *pParse, /* Parsing context */ - Table *pTab, /* The table being referenced, or NULL */ - int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */ - Expr *pExpr, /* Expression to resolve. May be NULL. */ - ExprList *pList /* Expression list to resolve. May be NULL. */ -){ - SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ - NameContext sNC; /* Name context for pParse->pNewTable */ - int rc; - - assert( type==0 || pTab!=0 ); - assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr - || type==NC_GenCol || pTab==0 ); - memset(&sNC, 0, sizeof(sNC)); - memset(&sSrc, 0, sizeof(sSrc)); - if( pTab ){ - sSrc.nSrc = 1; - sSrc.a[0].zName = pTab->zName; - sSrc.a[0].pTab = pTab; - sSrc.a[0].iCursor = -1; - if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){ - /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP - ** schema elements */ - type |= NC_FromDDL; - } - } - sNC.pParse = pParse; - sNC.pSrcList = &sSrc; - sNC.ncFlags = type | NC_IsDDL; - if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc; - if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList); - return rc; -} - -/************** End of resolve.c *********************************************/ -/************** Begin file expr.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 routines used for analyzing expressions and -** for generating VDBE code that evaluates expressions in SQLite. -*/ -/* #include "sqliteInt.h" */ - -/* Forward declarations */ -static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int); -static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree); - -/* -** Return the affinity character for a single column of a table. -*/ -SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){ - assert( iColnCol ); - return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER; -} - -/* -** Return the 'affinity' of the expression pExpr if any. -** -** If pExpr is a column, a reference to a column via an 'AS' alias, -** or a sub-select with a column as the return value, then the -** affinity of that column is returned. Otherwise, 0x00 is returned, -** indicating no affinity for the expression. -** -** i.e. the WHERE clause expressions in the following statements all -** have an affinity: -** -** CREATE TABLE t1(a); -** SELECT * FROM t1 WHERE a; -** SELECT a AS b FROM t1 WHERE b; -** SELECT * FROM t1 WHERE (select a from t1); -*/ -SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){ - int op; - while( ExprHasProperty(pExpr, EP_Skip) ){ - assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW ); - pExpr = pExpr->pLeft; - assert( pExpr!=0 ); - } - op = pExpr->op; - if( op==TK_SELECT ){ - assert( pExpr->flags&EP_xIsSelect ); - assert( pExpr->x.pSelect!=0 ); - assert( pExpr->x.pSelect->pEList!=0 ); - assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 ); - return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); - } - if( op==TK_REGISTER ) op = pExpr->op2; -#ifndef SQLITE_OMIT_CAST - if( op==TK_CAST ){ - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - return sqlite3AffinityType(pExpr->u.zToken, 0); - } -#endif - if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){ - return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); - } - if( op==TK_SELECT_COLUMN ){ - assert( pExpr->pLeft->flags&EP_xIsSelect ); - return sqlite3ExprAffinity( - pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr - ); - } - if( op==TK_VECTOR ){ - return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr); - } - return pExpr->affExpr; -} - -/* -** Set the collating sequence for expression pExpr to be the collating -** sequence named by pToken. Return a pointer to a new Expr node that -** implements the COLLATE operator. -** -** If a memory allocation error occurs, that fact is recorded in pParse->db -** and the pExpr parameter is returned unchanged. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken( - Parse *pParse, /* Parsing context */ - Expr *pExpr, /* Add the "COLLATE" clause to this expression */ - const Token *pCollName, /* Name of collating sequence */ - int dequote /* True to dequote pCollName */ -){ - if( pCollName->n>0 ){ - Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); - if( pNew ){ - pNew->pLeft = pExpr; - pNew->flags |= EP_Collate|EP_Skip; - pExpr = pNew; - } - } - return pExpr; -} -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ - Token s; - assert( zC!=0 ); - sqlite3TokenInit(&s, (char*)zC); - return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); -} - -/* -** Skip over any TK_COLLATE operators. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){ - while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ - assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW ); - pExpr = pExpr->pLeft; - } - return pExpr; -} - -/* -** Skip over any TK_COLLATE operators and/or any unlikely() -** or likelihood() or likely() functions at the root of an -** expression. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){ - while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){ - if( ExprHasProperty(pExpr, EP_Unlikely) ){ - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - assert( pExpr->x.pList->nExpr>0 ); - assert( pExpr->op==TK_FUNCTION ); - pExpr = pExpr->x.pList->a[0].pExpr; - }else{ - assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW ); - pExpr = pExpr->pLeft; - } - } - return pExpr; -} - -/* -** Return the collation sequence for the expression pExpr. If -** there is no defined collating sequence, return NULL. -** -** See also: sqlite3ExprNNCollSeq() -** -** The sqlite3ExprNNCollSeq() works the same exact that it returns the -** default collation if pExpr has no defined collation. -** -** The collating sequence might be determined by a COLLATE operator -** or by the presence of a column with a defined collating sequence. -** COLLATE operators take first precedence. Left operands take -** precedence over right operands. -*/ -SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){ - sqlite3 *db = pParse->db; - CollSeq *pColl = 0; - const Expr *p = pExpr; - while( p ){ - int op = p->op; - if( op==TK_REGISTER ) op = p->op2; - if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER) - && p->y.pTab!=0 - ){ - /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally - ** a TK_COLUMN but was previously evaluated and cached in a register */ - int j = p->iColumn; - if( j>=0 ){ - const char *zColl = p->y.pTab->aCol[j].zColl; - pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); - } - break; - } - if( op==TK_CAST || op==TK_UPLUS ){ - p = p->pLeft; - continue; - } - if( op==TK_VECTOR ){ - p = p->x.pList->a[0].pExpr; - continue; - } - if( op==TK_COLLATE ){ - pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); - break; - } - if( p->flags & EP_Collate ){ - if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ - p = p->pLeft; - }else{ - Expr *pNext = p->pRight; - /* The Expr.x union is never used at the same time as Expr.pRight */ - assert( p->x.pList==0 || p->pRight==0 ); - if( p->x.pList!=0 - && !db->mallocFailed - && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) - ){ - int i; - for(i=0; ALWAYS(ix.pList->nExpr); i++){ - if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ - pNext = p->x.pList->a[i].pExpr; - break; - } - } - } - p = pNext; - } - }else{ - break; - } - } - if( sqlite3CheckCollSeq(pParse, pColl) ){ - pColl = 0; - } - return pColl; -} - -/* -** Return the collation sequence for the expression pExpr. If -** there is no defined collating sequence, return a pointer to the -** defautl collation sequence. -** -** See also: sqlite3ExprCollSeq() -** -** The sqlite3ExprCollSeq() routine works the same except that it -** returns NULL if there is no defined collation. -*/ -SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){ - CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr); - if( p==0 ) p = pParse->db->pDfltColl; - assert( p!=0 ); - return p; -} - -/* -** Return TRUE if the two expressions have equivalent collating sequences. -*/ -SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){ - CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1); - CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2); - return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0; -} - -/* -** pExpr is an operand of a comparison operator. aff2 is the -** type affinity of the other operand. This routine returns the -** type affinity that should be used for the comparison operator. -*/ -SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2){ - char aff1 = sqlite3ExprAffinity(pExpr); - if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){ - /* Both sides of the comparison are columns. If one has numeric - ** affinity, use that. Otherwise use no affinity. - */ - if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ - return SQLITE_AFF_NUMERIC; - }else{ - return SQLITE_AFF_BLOB; - } - }else{ - /* One side is a column, the other is not. Use the columns affinity. */ - assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE ); - return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE; - } -} - -/* -** pExpr is a comparison operator. Return the type affinity that should -** be applied to both operands prior to doing the comparison. -*/ -static char comparisonAffinity(const Expr *pExpr){ - char aff; - assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || - pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || - pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); - assert( pExpr->pLeft ); - aff = sqlite3ExprAffinity(pExpr->pLeft); - if( pExpr->pRight ){ - aff = sqlite3CompareAffinity(pExpr->pRight, aff); - }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); - }else if( aff==0 ){ - aff = SQLITE_AFF_BLOB; - } - return aff; -} - -/* -** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. -** idx_affinity is the affinity of an indexed column. Return true -** if the index with affinity idx_affinity may be used to implement -** the comparison in pExpr. -*/ -SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){ - char aff = comparisonAffinity(pExpr); - if( affflags & EP_Collate ){ - pColl = sqlite3ExprCollSeq(pParse, pLeft); - }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ - pColl = sqlite3ExprCollSeq(pParse, pRight); - }else{ - pColl = sqlite3ExprCollSeq(pParse, pLeft); - if( !pColl ){ - pColl = sqlite3ExprCollSeq(pParse, pRight); - } - } - return pColl; -} - -/* Expresssion p is a comparison operator. Return a collation sequence -** appropriate for the comparison operator. -** -** This is normally just a wrapper around sqlite3BinaryCompareCollSeq(). -** However, if the OP_Commuted flag is set, then the order of the operands -** is reversed in the sqlite3BinaryCompareCollSeq() call so that the -** correct collating sequence is found. -*/ -SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){ - if( ExprHasProperty(p, EP_Commuted) ){ - return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft); - }else{ - return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight); - } -} - -/* -** Generate code for a comparison operator. -*/ -static int codeCompare( - Parse *pParse, /* The parsing (and code generating) context */ - Expr *pLeft, /* The left operand */ - Expr *pRight, /* The right operand */ - int opcode, /* The comparison opcode */ - int in1, int in2, /* Register holding operands */ - int dest, /* Jump here if true. */ - int jumpIfNull, /* If true, jump if either operand is NULL */ - int isCommuted /* The comparison has been commuted */ -){ - int p5; - int addr; - CollSeq *p4; - - if( pParse->nErr ) return 0; - if( isCommuted ){ - p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft); - }else{ - p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); - } - p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); - addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, - (void*)p4, P4_COLLSEQ); - sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); - return addr; -} - -/* -** Return true if expression pExpr is a vector, or false otherwise. -** -** A vector is defined as any expression that results in two or more -** columns of result. Every TK_VECTOR node is an vector because the -** parser will not generate a TK_VECTOR with fewer than two entries. -** But a TK_SELECT might be either a vector or a scalar. It is only -** considered a vector if it has two or more result columns. -*/ -SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){ - return sqlite3ExprVectorSize(pExpr)>1; -} - -/* -** If the expression passed as the only argument is of type TK_VECTOR -** return the number of expressions in the vector. Or, if the expression -** is a sub-select, return the number of columns in the sub-select. For -** any other type of expression, return 1. -*/ -SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){ - u8 op = pExpr->op; - if( op==TK_REGISTER ) op = pExpr->op2; - if( op==TK_VECTOR ){ - return pExpr->x.pList->nExpr; - }else if( op==TK_SELECT ){ - return pExpr->x.pSelect->pEList->nExpr; - }else{ - return 1; - } -} - -/* -** Return a pointer to a subexpression of pVector that is the i-th -** column of the vector (numbered starting with 0). The caller must -** ensure that i is within range. -** -** If pVector is really a scalar (and "scalar" here includes subqueries -** that return a single column!) then return pVector unmodified. -** -** pVector retains ownership of the returned subexpression. -** -** If the vector is a (SELECT ...) then the expression returned is -** just the expression for the i-th term of the result set, and may -** not be ready for evaluation because the table cursor has not yet -** been positioned. -*/ -SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ - assert( iop2==0 || pVector->op==TK_REGISTER ); - if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ - return pVector->x.pSelect->pEList->a[i].pExpr; - }else{ - return pVector->x.pList->a[i].pExpr; - } - } - return pVector; -} - -/* -** Compute and return a new Expr object which when passed to -** sqlite3ExprCode() will generate all necessary code to compute -** the iField-th column of the vector expression pVector. -** -** It is ok for pVector to be a scalar (as long as iField==0). -** In that case, this routine works like sqlite3ExprDup(). -** -** The caller owns the returned Expr object and is responsible for -** ensuring that the returned value eventually gets freed. -** -** The caller retains ownership of pVector. If pVector is a TK_SELECT, -** then the returned object will reference pVector and so pVector must remain -** valid for the life of the returned object. If pVector is a TK_VECTOR -** or a scalar expression, then it can be deleted as soon as this routine -** returns. -** -** A trick to cause a TK_SELECT pVector to be deleted together with -** the returned Expr object is to attach the pVector to the pRight field -** of the returned TK_SELECT_COLUMN Expr object. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprForVectorField( - Parse *pParse, /* Parsing context */ - Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ - int iField /* Which column of the vector to return */ -){ - Expr *pRet; - if( pVector->op==TK_SELECT ){ - assert( pVector->flags & EP_xIsSelect ); - /* The TK_SELECT_COLUMN Expr node: - ** - ** pLeft: pVector containing TK_SELECT. Not deleted. - ** pRight: not used. But recursively deleted. - ** iColumn: Index of a column in pVector - ** iTable: 0 or the number of columns on the LHS of an assignment - ** pLeft->iTable: First in an array of register holding result, or 0 - ** if the result is not yet computed. - ** - ** sqlite3ExprDelete() specifically skips the recursive delete of - ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector - ** can be attached to pRight to cause this node to take ownership of - ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes - ** with the same pLeft pointer to the pVector, but only one of them - ** will own the pVector. - */ - pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0); - if( pRet ){ - pRet->iColumn = iField; - pRet->pLeft = pVector; - } - assert( pRet==0 || pRet->iTable==0 ); - }else{ - if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr; - pRet = sqlite3ExprDup(pParse->db, pVector, 0); - sqlite3RenameTokenRemap(pParse, pRet, pVector); - } - return pRet; -} - -/* -** If expression pExpr is of type TK_SELECT, generate code to evaluate -** it. Return the register in which the result is stored (or, if the -** sub-select returns more than one column, the first in an array -** of registers in which the result is stored). -** -** If pExpr is not a TK_SELECT expression, return 0. -*/ -static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ - int reg = 0; -#ifndef SQLITE_OMIT_SUBQUERY - if( pExpr->op==TK_SELECT ){ - reg = sqlite3CodeSubselect(pParse, pExpr); - } -#endif - return reg; -} - -/* -** Argument pVector points to a vector expression - either a TK_VECTOR -** or TK_SELECT that returns more than one column. This function returns -** the register number of a register that contains the value of -** element iField of the vector. -** -** If pVector is a TK_SELECT expression, then code for it must have -** already been generated using the exprCodeSubselect() routine. In this -** case parameter regSelect should be the first in an array of registers -** containing the results of the sub-select. -** -** If pVector is of type TK_VECTOR, then code for the requested field -** is generated. In this case (*pRegFree) may be set to the number of -** a temporary register to be freed by the caller before returning. -** -** Before returning, output parameter (*ppExpr) is set to point to the -** Expr object corresponding to element iElem of the vector. -*/ -static int exprVectorRegister( - Parse *pParse, /* Parse context */ - Expr *pVector, /* Vector to extract element from */ - int iField, /* Field to extract from pVector */ - int regSelect, /* First in array of registers */ - Expr **ppExpr, /* OUT: Expression element */ - int *pRegFree /* OUT: Temp register to free */ -){ - u8 op = pVector->op; - assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT ); - if( op==TK_REGISTER ){ - *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); - return pVector->iTable+iField; - } - if( op==TK_SELECT ){ - *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr; - return regSelect+iField; - } - *ppExpr = pVector->x.pList->a[iField].pExpr; - return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); -} - -/* -** Expression pExpr is a comparison between two vector values. Compute -** the result of the comparison (1, 0, or NULL) and write that -** result into register dest. -** -** The caller must satisfy the following preconditions: -** -** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ -** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ -** otherwise: op==pExpr->op and p5==0 -*/ -static void codeVectorCompare( - Parse *pParse, /* Code generator context */ - Expr *pExpr, /* The comparison operation */ - int dest, /* Write results into this register */ - u8 op, /* Comparison operator */ - u8 p5 /* SQLITE_NULLEQ or zero */ -){ - Vdbe *v = pParse->pVdbe; - Expr *pLeft = pExpr->pLeft; - Expr *pRight = pExpr->pRight; - int nLeft = sqlite3ExprVectorSize(pLeft); - int i; - int regLeft = 0; - int regRight = 0; - u8 opx = op; - int addrDone = sqlite3VdbeMakeLabel(pParse); - int isCommuted = ExprHasProperty(pExpr,EP_Commuted); - - assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); - if( pParse->nErr ) return; - if( nLeft!=sqlite3ExprVectorSize(pRight) ){ - sqlite3ErrorMsg(pParse, "row value misused"); - return; - } - assert( pExpr->op==TK_EQ || pExpr->op==TK_NE - || pExpr->op==TK_IS || pExpr->op==TK_ISNOT - || pExpr->op==TK_LT || pExpr->op==TK_GT - || pExpr->op==TK_LE || pExpr->op==TK_GE - ); - assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ) - || (pExpr->op==TK_ISNOT && op==TK_NE) ); - assert( p5==0 || pExpr->op!=op ); - assert( p5==SQLITE_NULLEQ || pExpr->op==op ); - - p5 |= SQLITE_STOREP2; - if( opx==TK_LE ) opx = TK_LT; - if( opx==TK_GE ) opx = TK_GT; - - regLeft = exprCodeSubselect(pParse, pLeft); - regRight = exprCodeSubselect(pParse, pRight); - - for(i=0; 1 /*Loop exits by "break"*/; i++){ - int regFree1 = 0, regFree2 = 0; - Expr *pL, *pR; - int r1, r2; - assert( i>=0 && i0 -/* -** Check that argument nHeight is less than or equal to the maximum -** expression depth allowed. If it is not, leave an error message in -** pParse. -*/ -SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ - int rc = SQLITE_OK; - int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; - if( nHeight>mxHeight ){ - sqlite3ErrorMsg(pParse, - "Expression tree is too large (maximum depth %d)", mxHeight - ); - rc = SQLITE_ERROR; - } - return rc; -} - -/* The following three functions, heightOfExpr(), heightOfExprList() -** and heightOfSelect(), are used to determine the maximum height -** of any expression tree referenced by the structure passed as the -** first argument. -** -** If this maximum height is greater than the current value pointed -** to by pnHeight, the second parameter, then set *pnHeight to that -** value. -*/ -static void heightOfExpr(Expr *p, int *pnHeight){ - if( p ){ - if( p->nHeight>*pnHeight ){ - *pnHeight = p->nHeight; - } - } -} -static void heightOfExprList(ExprList *p, int *pnHeight){ - if( p ){ - int i; - for(i=0; inExpr; i++){ - heightOfExpr(p->a[i].pExpr, pnHeight); - } - } -} -static void heightOfSelect(Select *pSelect, int *pnHeight){ - Select *p; - for(p=pSelect; p; p=p->pPrior){ - heightOfExpr(p->pWhere, pnHeight); - heightOfExpr(p->pHaving, pnHeight); - heightOfExpr(p->pLimit, pnHeight); - heightOfExprList(p->pEList, pnHeight); - heightOfExprList(p->pGroupBy, pnHeight); - heightOfExprList(p->pOrderBy, pnHeight); - } -} - -/* -** Set the Expr.nHeight variable in the structure passed as an -** argument. An expression with no children, Expr.pList or -** Expr.pSelect member has a height of 1. Any other expression -** has a height equal to the maximum height of any other -** referenced Expr plus one. -** -** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags, -** if appropriate. -*/ -static void exprSetHeight(Expr *p){ - int nHeight = 0; - heightOfExpr(p->pLeft, &nHeight); - heightOfExpr(p->pRight, &nHeight); - if( ExprHasProperty(p, EP_xIsSelect) ){ - heightOfSelect(p->x.pSelect, &nHeight); - }else if( p->x.pList ){ - heightOfExprList(p->x.pList, &nHeight); - p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); - } - p->nHeight = nHeight + 1; -} - -/* -** Set the Expr.nHeight variable using the exprSetHeight() function. If -** the height is greater than the maximum allowed expression depth, -** leave an error in pParse. -** -** Also propagate all EP_Propagate flags from the Expr.x.pList into -** Expr.flags. -*/ -SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ - if( pParse->nErr ) return; - exprSetHeight(p); - sqlite3ExprCheckHeight(pParse, p->nHeight); -} - -/* -** Return the maximum height of any expression tree referenced -** by the select statement passed as an argument. -*/ -SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){ - int nHeight = 0; - heightOfSelect(p, &nHeight); - return nHeight; -} -#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */ -/* -** Propagate all EP_Propagate flags from the Expr.x.pList into -** Expr.flags. -*/ -SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ - if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){ - p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); - } -} -#define exprSetHeight(y) -#endif /* SQLITE_MAX_EXPR_DEPTH>0 */ - -/* -** This routine is the core allocator for Expr nodes. -** -** Construct a new expression node and return a pointer to it. Memory -** for this node and for the pToken argument is a single allocation -** obtained from sqlite3DbMalloc(). The calling function -** is responsible for making sure the node eventually gets freed. -** -** If dequote is true, then the token (if it exists) is dequoted. -** If dequote is false, no dequoting is performed. The deQuote -** parameter is ignored if pToken is NULL or if the token does not -** appear to be quoted. If the quotes were of the form "..." (double-quotes) -** then the EP_DblQuoted flag is set on the expression node. -** -** Special case: If op==TK_INTEGER and pToken points to a string that -** can be translated into a 32-bit integer, then the token is not -** stored in u.zToken. Instead, the integer values is written -** into u.iValue and the EP_IntValue flag is set. No extra storage -** is allocated to hold the integer text and the dequote flag is ignored. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprAlloc( - sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ - int op, /* Expression opcode */ - const Token *pToken, /* Token argument. Might be NULL */ - int dequote /* True to dequote */ -){ - Expr *pNew; - int nExtra = 0; - int iValue = 0; - - assert( db!=0 ); - if( pToken ){ - if( op!=TK_INTEGER || pToken->z==0 - || sqlite3GetInt32(pToken->z, &iValue)==0 ){ - nExtra = pToken->n+1; - assert( iValue>=0 ); - } - } - pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); - if( pNew ){ - memset(pNew, 0, sizeof(Expr)); - pNew->op = (u8)op; - pNew->iAgg = -1; - if( pToken ){ - if( nExtra==0 ){ - pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse); - pNew->u.iValue = iValue; - }else{ - pNew->u.zToken = (char*)&pNew[1]; - assert( pToken->z!=0 || pToken->n==0 ); - if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); - pNew->u.zToken[pToken->n] = 0; - if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ - sqlite3DequoteExpr(pNew); - } - } - } -#if SQLITE_MAX_EXPR_DEPTH>0 - pNew->nHeight = 1; -#endif - } - return pNew; -} - -/* -** Allocate a new expression node from a zero-terminated token that has -** already been dequoted. -*/ -SQLITE_PRIVATE Expr *sqlite3Expr( - sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ - int op, /* Expression opcode */ - const char *zToken /* Token argument. Might be NULL */ -){ - Token x; - x.z = zToken; - x.n = sqlite3Strlen30(zToken); - return sqlite3ExprAlloc(db, op, &x, 0); -} - -/* -** Attach subtrees pLeft and pRight to the Expr node pRoot. -** -** If pRoot==NULL that means that a memory allocation error has occurred. -** In that case, delete the subtrees pLeft and pRight. -*/ -SQLITE_PRIVATE void sqlite3ExprAttachSubtrees( - sqlite3 *db, - Expr *pRoot, - Expr *pLeft, - Expr *pRight -){ - if( pRoot==0 ){ - assert( db->mallocFailed ); - sqlite3ExprDelete(db, pLeft); - sqlite3ExprDelete(db, pRight); - }else{ - if( pRight ){ - pRoot->pRight = pRight; - pRoot->flags |= EP_Propagate & pRight->flags; - } - if( pLeft ){ - pRoot->pLeft = pLeft; - pRoot->flags |= EP_Propagate & pLeft->flags; - } - exprSetHeight(pRoot); - } -} - -/* -** Allocate an Expr node which joins as many as two subtrees. -** -** One or both of the subtrees can be NULL. Return a pointer to the new -** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, -** free the subtrees and return NULL. -*/ -SQLITE_PRIVATE Expr *sqlite3PExpr( - Parse *pParse, /* Parsing context */ - int op, /* Expression opcode */ - Expr *pLeft, /* Left operand */ - Expr *pRight /* Right operand */ -){ - Expr *p; - p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); - if( p ){ - memset(p, 0, sizeof(Expr)); - p->op = op & 0xff; - p->iAgg = -1; - sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); - sqlite3ExprCheckHeight(pParse, p->nHeight); - }else{ - sqlite3ExprDelete(pParse->db, pLeft); - sqlite3ExprDelete(pParse->db, pRight); - } - return p; -} - -/* -** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due -** do a memory allocation failure) then delete the pSelect object. -*/ -SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ - if( pExpr ){ - pExpr->x.pSelect = pSelect; - ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); - sqlite3ExprSetHeightAndFlags(pParse, pExpr); - }else{ - assert( pParse->db->mallocFailed ); - sqlite3SelectDelete(pParse->db, pSelect); - } -} - - -/* -** Join two expressions using an AND operator. If either expression is -** NULL, then just return the other expression. -** -** If one side or the other of the AND is known to be false, then instead -** of returning an AND expression, just return a constant expression with -** a value of false. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){ - sqlite3 *db = pParse->db; - if( pLeft==0 ){ - return pRight; - }else if( pRight==0 ){ - return pLeft; - }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight)) - && !IN_RENAME_OBJECT - ){ - sqlite3ExprDelete(db, pLeft); - sqlite3ExprDelete(db, pRight); - return sqlite3Expr(db, TK_INTEGER, "0"); - }else{ - return sqlite3PExpr(pParse, TK_AND, pLeft, pRight); - } -} - -/* -** Construct a new expression node for a function with multiple -** arguments. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprFunction( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* Argument list */ - Token *pToken, /* Name of the function */ - int eDistinct /* SF_Distinct or SF_ALL or 0 */ -){ - Expr *pNew; - sqlite3 *db = pParse->db; - assert( pToken ); - pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); - if( pNew==0 ){ - sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ - return 0; - } - if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ - sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken); - } - pNew->x.pList = pList; - ExprSetProperty(pNew, EP_HasFunc); - assert( !ExprHasProperty(pNew, EP_xIsSelect) ); - sqlite3ExprSetHeightAndFlags(pParse, pNew); - if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct); - return pNew; -} - -/* -** Check to see if a function is usable according to current access -** rules: -** -** SQLITE_FUNC_DIRECT - Only usable from top-level SQL -** -** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from -** top-level SQL -** -** If the function is not usable, create an error. -*/ -SQLITE_PRIVATE void sqlite3ExprFunctionUsable( - Parse *pParse, /* Parsing and code generating context */ - Expr *pExpr, /* The function invocation */ - FuncDef *pDef /* The function being invoked */ -){ - assert( !IN_RENAME_OBJECT ); - assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 ); - if( ExprHasProperty(pExpr, EP_FromDDL) ){ - if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 - || (pParse->db->flags & SQLITE_TrustedSchema)==0 - ){ - /* Functions prohibited in triggers and views if: - ** (1) tagged with SQLITE_DIRECTONLY - ** (2) not tagged with SQLITE_INNOCUOUS (which means it - ** is tagged with SQLITE_FUNC_UNSAFE) and - ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning - ** that the schema is possibly tainted). - */ - sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName); - } - } -} - -/* -** Assign a variable number to an expression that encodes a wildcard -** in the original SQL statement. -** -** Wildcards consisting of a single "?" are assigned the next sequential -** variable number. -** -** Wildcards of the form "?nnn" are assigned the number "nnn". We make -** sure "nnn" is not too big to avoid a denial of service attack when -** the SQL statement comes from an external source. -** -** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number -** as the previous instance of the same wildcard. Or if this is the first -** instance of the wildcard, the next sequential variable number is -** assigned. -*/ -SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ - sqlite3 *db = pParse->db; - const char *z; - ynVar x; - - if( pExpr==0 ) return; - assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); - z = pExpr->u.zToken; - assert( z!=0 ); - assert( z[0]!=0 ); - assert( n==(u32)sqlite3Strlen30(z) ); - if( z[1]==0 ){ - /* Wildcard of the form "?". Assign the next variable number */ - assert( z[0]=='?' ); - x = (ynVar)(++pParse->nVar); - }else{ - int doAdd = 0; - if( z[0]=='?' ){ - /* Wildcard of the form "?nnn". Convert "nnn" to an integer and - ** use it as the variable number */ - i64 i; - int bOk; - if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/ - i = z[1]-'0'; /* The common case of ?N for a single digit N */ - bOk = 1; - }else{ - bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); - } - testcase( i==0 ); - testcase( i==1 ); - testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); - testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); - if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ - sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", - db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); - return; - } - x = (ynVar)i; - if( x>pParse->nVar ){ - pParse->nVar = (int)x; - doAdd = 1; - }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){ - doAdd = 1; - } - }else{ - /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable - ** number as the prior appearance of the same name, or if the name - ** has never appeared before, reuse the same variable number - */ - x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n); - if( x==0 ){ - x = (ynVar)(++pParse->nVar); - doAdd = 1; - } - } - if( doAdd ){ - pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x); - } - } - pExpr->iColumn = x; - if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ - sqlite3ErrorMsg(pParse, "too many SQL variables"); - } -} - -/* -** Recursively delete an expression tree. -*/ -static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ - assert( p!=0 ); - /* Sanity check: Assert that the IntValue is non-negative if it exists */ - assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); - - assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed ); - assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced) - || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) ); -#ifdef SQLITE_DEBUG - if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ - assert( p->pLeft==0 ); - assert( p->pRight==0 ); - assert( p->x.pSelect==0 ); - } -#endif - if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ - /* The Expr.x union is never used at the same time as Expr.pRight */ - assert( p->x.pList==0 || p->pRight==0 ); - if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft); - if( p->pRight ){ - assert( !ExprHasProperty(p, EP_WinFunc) ); - sqlite3ExprDeleteNN(db, p->pRight); - }else if( ExprHasProperty(p, EP_xIsSelect) ){ - assert( !ExprHasProperty(p, EP_WinFunc) ); - sqlite3SelectDelete(db, p->x.pSelect); - }else{ - sqlite3ExprListDelete(db, p->x.pList); -#ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(p, EP_WinFunc) ){ - sqlite3WindowDelete(db, p->y.pWin); - } -#endif - } - } - if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); - if( !ExprHasProperty(p, EP_Static) ){ - sqlite3DbFreeNN(db, p); - } -} -SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){ - if( p ) sqlite3ExprDeleteNN(db, p); -} - -/* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the -** expression. -*/ -SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){ - if( p ){ - if( IN_RENAME_OBJECT ){ - sqlite3RenameExprUnmap(pParse, p); - } - sqlite3ExprDeleteNN(pParse->db, p); - } -} - -/* -** Return the number of bytes allocated for the expression structure -** passed as the first argument. This is always one of EXPR_FULLSIZE, -** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. -*/ -static int exprStructSize(Expr *p){ - if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; - if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; - return EXPR_FULLSIZE; -} - -/* -** The dupedExpr*Size() routines each return the number of bytes required -** to store a copy of an expression or expression tree. They differ in -** how much of the tree is measured. -** -** dupedExprStructSize() Size of only the Expr structure -** dupedExprNodeSize() Size of Expr + space for token -** dupedExprSize() Expr + token + subtree components -** -*************************************************************************** -** -** The dupedExprStructSize() function returns two values OR-ed together: -** (1) the space required for a copy of the Expr structure only and -** (2) the EP_xxx flags that indicate what the structure size should be. -** The return values is always one of: -** -** EXPR_FULLSIZE -** EXPR_REDUCEDSIZE | EP_Reduced -** EXPR_TOKENONLYSIZE | EP_TokenOnly -** -** The size of the structure can be found by masking the return value -** of this routine with 0xfff. The flags can be found by masking the -** return value with EP_Reduced|EP_TokenOnly. -** -** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size -** (unreduced) Expr objects as they or originally constructed by the parser. -** During expression analysis, extra information is computed and moved into -** later parts of the Expr object and that extra information might get chopped -** off if the expression is reduced. Note also that it does not work to -** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal -** to reduce a pristine expression tree from the parser. The implementation -** of dupedExprStructSize() contain multiple assert() statements that attempt -** to enforce this constraint. -*/ -static int dupedExprStructSize(Expr *p, int flags){ - int nSize; - assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ - assert( EXPR_FULLSIZE<=0xfff ); - assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); - if( 0==flags || p->op==TK_SELECT_COLUMN -#ifndef SQLITE_OMIT_WINDOWFUNC - || ExprHasProperty(p, EP_WinFunc) -#endif - ){ - nSize = EXPR_FULLSIZE; - }else{ - assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); - assert( !ExprHasProperty(p, EP_FromJoin) ); - assert( !ExprHasProperty(p, EP_MemToken) ); - assert( !ExprHasVVAProperty(p, EP_NoReduce) ); - if( p->pLeft || p->x.pList ){ - nSize = EXPR_REDUCEDSIZE | EP_Reduced; - }else{ - assert( p->pRight==0 ); - nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; - } - } - return nSize; -} - -/* -** This function returns the space in bytes required to store the copy -** of the Expr structure and a copy of the Expr.u.zToken string (if that -** string is defined.) -*/ -static int dupedExprNodeSize(Expr *p, int flags){ - int nByte = dupedExprStructSize(p, flags) & 0xfff; - if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ - nByte += sqlite3Strlen30NN(p->u.zToken)+1; - } - return ROUND8(nByte); -} - -/* -** Return the number of bytes required to create a duplicate of the -** expression passed as the first argument. The second argument is a -** mask containing EXPRDUP_XXX flags. -** -** The value returned includes space to create a copy of the Expr struct -** itself and the buffer referred to by Expr.u.zToken, if any. -** -** If the EXPRDUP_REDUCE flag is set, then the return value includes -** space to duplicate all Expr nodes in the tree formed by Expr.pLeft -** and Expr.pRight variables (but not for any structures pointed to or -** descended from the Expr.x.pList or Expr.x.pSelect variables). -*/ -static int dupedExprSize(Expr *p, int flags){ - int nByte = 0; - if( p ){ - nByte = dupedExprNodeSize(p, flags); - if( flags&EXPRDUP_REDUCE ){ - nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); - } - } - return nByte; -} - -/* -** This function is similar to sqlite3ExprDup(), except that if pzBuffer -** is not NULL then *pzBuffer is assumed to point to a buffer large enough -** to store the copy of expression p, the copies of p->u.zToken -** (if applicable), and the copies of the p->pLeft and p->pRight expressions, -** if any. Before returning, *pzBuffer is set to the first byte past the -** portion of the buffer copied into by this function. -*/ -static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ - Expr *pNew; /* Value to return */ - u8 *zAlloc; /* Memory space from which to build Expr object */ - u32 staticFlag; /* EP_Static if space not obtained from malloc */ - - assert( db!=0 ); - assert( p ); - assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE ); - assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE ); - - /* Figure out where to write the new Expr structure. */ - if( pzBuffer ){ - zAlloc = *pzBuffer; - staticFlag = EP_Static; - }else{ - zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags)); - staticFlag = 0; - } - pNew = (Expr *)zAlloc; - - if( pNew ){ - /* Set nNewSize to the size allocated for the structure pointed to - ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or - ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed - ** by the copy of the p->u.zToken string (if any). - */ - const unsigned nStructSize = dupedExprStructSize(p, dupFlags); - const int nNewSize = nStructSize & 0xfff; - int nToken; - if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ - nToken = sqlite3Strlen30(p->u.zToken) + 1; - }else{ - nToken = 0; - } - if( dupFlags ){ - assert( ExprHasProperty(p, EP_Reduced)==0 ); - memcpy(zAlloc, p, nNewSize); - }else{ - u32 nSize = (u32)exprStructSize(p); - memcpy(zAlloc, p, nSize); - if( nSizeflags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken); - pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); - pNew->flags |= staticFlag; - ExprClearVVAProperties(pNew); - if( dupFlags ){ - ExprSetVVAProperty(pNew, EP_Immutable); - } - - /* Copy the p->u.zToken string, if any. */ - if( nToken ){ - char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; - memcpy(zToken, p->u.zToken, nToken); - } - - if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){ - /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ - if( ExprHasProperty(p, EP_xIsSelect) ){ - pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); - }else{ - pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags); - } - } - - /* Fill in pNew->pLeft and pNew->pRight. */ - if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){ - zAlloc += dupedExprNodeSize(p, dupFlags); - if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){ - pNew->pLeft = p->pLeft ? - exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0; - pNew->pRight = p->pRight ? - exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0; - } -#ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(p, EP_WinFunc) ){ - pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin); - assert( ExprHasProperty(pNew, EP_WinFunc) ); - } -#endif /* SQLITE_OMIT_WINDOWFUNC */ - if( pzBuffer ){ - *pzBuffer = zAlloc; - } - }else{ - if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ - if( pNew->op==TK_SELECT_COLUMN ){ - pNew->pLeft = p->pLeft; - assert( p->iColumn==0 || p->pRight==0 ); - assert( p->pRight==0 || p->pRight==p->pLeft ); - }else{ - pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); - } - pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); - } - } - } - return pNew; -} - -/* -** Create and return a deep copy of the object passed as the second -** argument. If an OOM condition is encountered, NULL is returned -** and the db->mallocFailed flag set. -*/ -#ifndef SQLITE_OMIT_CTE -static With *withDup(sqlite3 *db, With *p){ - With *pRet = 0; - if( p ){ - sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); - pRet = sqlite3DbMallocZero(db, nByte); - if( pRet ){ - int i; - pRet->nCte = p->nCte; - for(i=0; inCte; i++){ - pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); - pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); - pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); - } - } - } - return pRet; -} -#else -# define withDup(x,y) 0 -#endif - -#ifndef SQLITE_OMIT_WINDOWFUNC -/* -** The gatherSelectWindows() procedure and its helper routine -** gatherSelectWindowsCallback() are used to scan all the expressions -** an a newly duplicated SELECT statement and gather all of the Window -** objects found there, assembling them onto the linked list at Select->pWin. -*/ -static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){ - Select *pSelect = pWalker->u.pSelect; - Window *pWin = pExpr->y.pWin; - assert( pWin ); - assert( IsWindowFunc(pExpr) ); - assert( pWin->ppThis==0 ); - sqlite3WindowLink(pSelect, pWin); - } - return WRC_Continue; -} -static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){ - return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune; -} -static void gatherSelectWindows(Select *p){ - Walker w; - w.xExprCallback = gatherSelectWindowsCallback; - w.xSelectCallback = gatherSelectWindowsSelectCallback; - w.xSelectCallback2 = 0; - w.pParse = 0; - w.u.pSelect = p; - sqlite3WalkSelect(&w, p); -} -#endif - - -/* -** The following group of routines make deep copies of expressions, -** expression lists, ID lists, and select statements. The copies can -** be deleted (by being passed to their respective ...Delete() routines) -** without effecting the originals. -** -** The expression list, ID, and source lists return by sqlite3ExprListDup(), -** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded -** by subsequent calls to sqlite*ListAppend() routines. -** -** Any tables that the SrcList might point to are not duplicated. -** -** The flags parameter contains a combination of the EXPRDUP_XXX flags. -** If the EXPRDUP_REDUCE flag is set, then the structure returned is a -** truncated version of the usual Expr structure that will be stored as -** part of the in-memory representation of the database schema. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ - assert( flags==0 || flags==EXPRDUP_REDUCE ); - return p ? exprDup(db, p, flags, 0) : 0; -} -SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ - ExprList *pNew; - struct ExprList_item *pItem, *pOldItem; - int i; - Expr *pPriorSelectCol = 0; - assert( db!=0 ); - if( p==0 ) return 0; - pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p)); - if( pNew==0 ) return 0; - pNew->nExpr = p->nExpr; - pItem = pNew->a; - pOldItem = p->a; - for(i=0; inExpr; i++, pItem++, pOldItem++){ - Expr *pOldExpr = pOldItem->pExpr; - Expr *pNewExpr; - pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); - if( pOldExpr - && pOldExpr->op==TK_SELECT_COLUMN - && (pNewExpr = pItem->pExpr)!=0 - ){ - assert( pNewExpr->iColumn==0 || i>0 ); - if( pNewExpr->iColumn==0 ){ - assert( pOldExpr->pLeft==pOldExpr->pRight ); - pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight; - }else{ - assert( i>0 ); - assert( pItem[-1].pExpr!=0 ); - assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 ); - assert( pPriorSelectCol==pItem[-1].pExpr->pLeft ); - pNewExpr->pLeft = pPriorSelectCol; - } - } - pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName); - pItem->sortFlags = pOldItem->sortFlags; - pItem->eEName = pOldItem->eEName; - pItem->done = 0; - pItem->bNulls = pOldItem->bNulls; - pItem->bSorterRef = pOldItem->bSorterRef; - pItem->u = pOldItem->u; - } - return pNew; -} - -/* -** If cursors, triggers, views and subqueries are all omitted from -** the build, then none of the following routines, except for -** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes -** called with a NULL argument. -*/ -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ - || !defined(SQLITE_OMIT_SUBQUERY) -SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ - SrcList *pNew; - int i; - int nByte; - assert( db!=0 ); - if( p==0 ) return 0; - nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); - pNew = sqlite3DbMallocRawNN(db, nByte ); - if( pNew==0 ) return 0; - pNew->nSrc = pNew->nAlloc = p->nSrc; - for(i=0; inSrc; i++){ - struct SrcList_item *pNewItem = &pNew->a[i]; - struct SrcList_item *pOldItem = &p->a[i]; - Table *pTab; - pNewItem->pSchema = pOldItem->pSchema; - pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); - pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); - pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); - pNewItem->fg = pOldItem->fg; - pNewItem->iCursor = pOldItem->iCursor; - pNewItem->addrFillSub = pOldItem->addrFillSub; - pNewItem->regReturn = pOldItem->regReturn; - if( pNewItem->fg.isIndexedBy ){ - pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); - } - pNewItem->pIBIndex = pOldItem->pIBIndex; - if( pNewItem->fg.isTabFunc ){ - pNewItem->u1.pFuncArg = - sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); - } - pTab = pNewItem->pTab = pOldItem->pTab; - if( pTab ){ - pTab->nTabRef++; - } - pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); - pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); - pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); - pNewItem->colUsed = pOldItem->colUsed; - } - return pNew; -} -SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ - IdList *pNew; - int i; - assert( db!=0 ); - if( p==0 ) return 0; - pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); - if( pNew==0 ) return 0; - pNew->nId = p->nId; - pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) ); - if( pNew->a==0 ){ - sqlite3DbFreeNN(db, pNew); - return 0; - } - /* Note that because the size of the allocation for p->a[] is not - ** necessarily a power of two, sqlite3IdListAppend() may not be called - ** on the duplicate created by this function. */ - for(i=0; inId; i++){ - struct IdList_item *pNewItem = &pNew->a[i]; - struct IdList_item *pOldItem = &p->a[i]; - pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); - pNewItem->idx = pOldItem->idx; - } - return pNew; -} -SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){ - Select *pRet = 0; - Select *pNext = 0; - Select **pp = &pRet; - Select *p; - - assert( db!=0 ); - for(p=pDup; p; p=p->pPrior){ - Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); - if( pNew==0 ) break; - pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); - pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); - pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); - pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); - pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); - pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); - pNew->op = p->op; - pNew->pNext = pNext; - pNew->pPrior = 0; - pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); - pNew->iLimit = 0; - pNew->iOffset = 0; - pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; - pNew->addrOpenEphm[0] = -1; - pNew->addrOpenEphm[1] = -1; - pNew->nSelectRow = p->nSelectRow; - pNew->pWith = withDup(db, p->pWith); -#ifndef SQLITE_OMIT_WINDOWFUNC - pNew->pWin = 0; - pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn); - if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew); -#endif - pNew->selId = p->selId; - *pp = pNew; - pp = &pNew->pPrior; - pNext = pNew; - } - - return pRet; -} -#else -SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ - assert( p==0 ); - return 0; -} -#endif - - -/* -** Add a new element to the end of an expression list. If pList is -** initially NULL, then create a new expression list. -** -** The pList argument must be either NULL or a pointer to an ExprList -** obtained from a prior call to sqlite3ExprListAppend(). This routine -** may not be used with an ExprList obtained from sqlite3ExprListDup(). -** Reason: This routine assumes that the number of slots in pList->a[] -** is a power of two. That is true for sqlite3ExprListAppend() returns -** but is not necessarily true from the return value of sqlite3ExprListDup(). -** -** If a memory allocation error occurs, the entire list is freed and -** NULL is returned. If non-NULL is returned, then it is guaranteed -** that the new entry was successfully appended. -*/ -SQLITE_PRIVATE ExprList *sqlite3ExprListAppend( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* List to which to append. Might be NULL */ - Expr *pExpr /* Expression to be appended. Might be NULL */ -){ - struct ExprList_item *pItem; - sqlite3 *db = pParse->db; - assert( db!=0 ); - if( pList==0 ){ - pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) ); - if( pList==0 ){ - goto no_mem; - } - pList->nExpr = 0; - }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ - ExprList *pNew; - pNew = sqlite3DbRealloc(db, pList, - sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0])); - if( pNew==0 ){ - goto no_mem; - } - pList = pNew; - } - pItem = &pList->a[pList->nExpr++]; - assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) ); - assert( offsetof(struct ExprList_item,pExpr)==0 ); - memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName)); - pItem->pExpr = pExpr; - return pList; - -no_mem: - /* Avoid leaking memory if malloc has failed. */ - sqlite3ExprDelete(db, pExpr); - sqlite3ExprListDelete(db, pList); - return 0; -} - -/* -** pColumns and pExpr form a vector assignment which is part of the SET -** clause of an UPDATE statement. Like this: -** -** (a,b,c) = (expr1,expr2,expr3) -** Or: (a,b,c) = (SELECT x,y,z FROM ....) -** -** For each term of the vector assignment, append new entries to the -** expression list pList. In the case of a subquery on the RHS, append -** TK_SELECT_COLUMN expressions. -*/ -SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* List to which to append. Might be NULL */ - IdList *pColumns, /* List of names of LHS of the assignment */ - Expr *pExpr /* Vector expression to be appended. Might be NULL */ -){ - sqlite3 *db = pParse->db; - int n; - int i; - int iFirst = pList ? pList->nExpr : 0; - /* pColumns can only be NULL due to an OOM but an OOM will cause an - ** exit prior to this routine being invoked */ - if( NEVER(pColumns==0) ) goto vector_append_error; - if( pExpr==0 ) goto vector_append_error; - - /* If the RHS is a vector, then we can immediately check to see that - ** the size of the RHS and LHS match. But if the RHS is a SELECT, - ** wildcards ("*") in the result set of the SELECT must be expanded before - ** we can do the size check, so defer the size check until code generation. - */ - if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){ - sqlite3ErrorMsg(pParse, "%d columns assigned %d values", - pColumns->nId, n); - goto vector_append_error; - } - - for(i=0; inId; i++){ - Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i); - assert( pSubExpr!=0 || db->mallocFailed ); - assert( pSubExpr==0 || pSubExpr->iTable==0 ); - if( pSubExpr==0 ) continue; - pSubExpr->iTable = pColumns->nId; - pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); - if( pList ){ - assert( pList->nExpr==iFirst+i+1 ); - pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName; - pColumns->a[i].zName = 0; - } - } - - if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){ - Expr *pFirst = pList->a[iFirst].pExpr; - assert( pFirst!=0 ); - assert( pFirst->op==TK_SELECT_COLUMN ); - - /* Store the SELECT statement in pRight so it will be deleted when - ** sqlite3ExprListDelete() is called */ - pFirst->pRight = pExpr; - pExpr = 0; - - /* Remember the size of the LHS in iTable so that we can check that - ** the RHS and LHS sizes match during code generation. */ - pFirst->iTable = pColumns->nId; - } - -vector_append_error: - sqlite3ExprUnmapAndDelete(pParse, pExpr); - sqlite3IdListDelete(db, pColumns); - return pList; -} - -/* -** Set the sort order for the last element on the given ExprList. -*/ -SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){ - struct ExprList_item *pItem; - if( p==0 ) return; - assert( p->nExpr>0 ); - - assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 ); - assert( iSortOrder==SQLITE_SO_UNDEFINED - || iSortOrder==SQLITE_SO_ASC - || iSortOrder==SQLITE_SO_DESC - ); - assert( eNulls==SQLITE_SO_UNDEFINED - || eNulls==SQLITE_SO_ASC - || eNulls==SQLITE_SO_DESC - ); - - pItem = &p->a[p->nExpr-1]; - assert( pItem->bNulls==0 ); - if( iSortOrder==SQLITE_SO_UNDEFINED ){ - iSortOrder = SQLITE_SO_ASC; - } - pItem->sortFlags = (u8)iSortOrder; - - if( eNulls!=SQLITE_SO_UNDEFINED ){ - pItem->bNulls = 1; - if( iSortOrder!=eNulls ){ - pItem->sortFlags |= KEYINFO_ORDER_BIGNULL; - } - } -} - -/* -** Set the ExprList.a[].zEName element of the most recently added item -** on the expression list. -** -** pList might be NULL following an OOM error. But pName should never be -** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag -** is set. -*/ -SQLITE_PRIVATE void sqlite3ExprListSetName( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* List to which to add the span. */ - Token *pName, /* Name to be added */ - int dequote /* True to cause the name to be dequoted */ -){ - assert( pList!=0 || pParse->db->mallocFailed!=0 ); - assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 ); - if( pList ){ - struct ExprList_item *pItem; - assert( pList->nExpr>0 ); - pItem = &pList->a[pList->nExpr-1]; - assert( pItem->zEName==0 ); - assert( pItem->eEName==ENAME_NAME ); - pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); - if( dequote ){ - /* If dequote==0, then pName->z does not point to part of a DDL - ** statement handled by the parser. And so no token need be added - ** to the token-map. */ - sqlite3Dequote(pItem->zEName); - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName); - } - } - } -} - -/* -** Set the ExprList.a[].zSpan element of the most recently added item -** on the expression list. -** -** pList might be NULL following an OOM error. But pSpan should never be -** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag -** is set. -*/ -SQLITE_PRIVATE void sqlite3ExprListSetSpan( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* List to which to add the span. */ - const char *zStart, /* Start of the span */ - const char *zEnd /* End of the span */ -){ - sqlite3 *db = pParse->db; - assert( pList!=0 || db->mallocFailed!=0 ); - if( pList ){ - struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; - assert( pList->nExpr>0 ); - if( pItem->zEName==0 ){ - pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd); - pItem->eEName = ENAME_SPAN; - } - } -} - -/* -** If the expression list pEList contains more than iLimit elements, -** leave an error message in pParse. -*/ -SQLITE_PRIVATE void sqlite3ExprListCheckLength( - Parse *pParse, - ExprList *pEList, - const char *zObject -){ - int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; - testcase( pEList && pEList->nExpr==mx ); - testcase( pEList && pEList->nExpr==mx+1 ); - if( pEList && pEList->nExpr>mx ){ - sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); - } -} - -/* -** Delete an entire expression list. -*/ -static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ - int i = pList->nExpr; - struct ExprList_item *pItem = pList->a; - assert( pList->nExpr>0 ); - do{ - sqlite3ExprDelete(db, pItem->pExpr); - sqlite3DbFree(db, pItem->zEName); - pItem++; - }while( --i>0 ); - sqlite3DbFreeNN(db, pList); -} -SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ - if( pList ) exprListDeleteNN(db, pList); -} - -/* -** Return the bitwise-OR of all Expr.flags fields in the given -** ExprList. -*/ -SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){ - int i; - u32 m = 0; - assert( pList!=0 ); - for(i=0; inExpr; i++){ - Expr *pExpr = pList->a[i].pExpr; - assert( pExpr!=0 ); - m |= pExpr->flags; - } - return m; -} - -/* -** This is a SELECT-node callback for the expression walker that -** always "fails". By "fail" in this case, we mean set -** pWalker->eCode to zero and abort. -** -** This callback is used by multiple expression walkers. -*/ -SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){ - UNUSED_PARAMETER(NotUsed); - pWalker->eCode = 0; - return WRC_Abort; -} - -/* -** Check the input string to see if it is "true" or "false" (in any case). -** -** If the string is.... Return -** "true" EP_IsTrue -** "false" EP_IsFalse -** anything else 0 -*/ -SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char *zIn){ - if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue; - if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse; - return 0; -} - - -/* -** If the input expression is an ID with the name "true" or "false" -** then convert it into an TK_TRUEFALSE term. Return non-zero if -** the conversion happened, and zero if the expression is unaltered. -*/ -SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){ - u32 v; - assert( pExpr->op==TK_ID || pExpr->op==TK_STRING ); - if( !ExprHasProperty(pExpr, EP_Quoted) - && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0 - ){ - pExpr->op = TK_TRUEFALSE; - ExprSetProperty(pExpr, v); - return 1; - } - return 0; -} - -/* -** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE -** and 0 if it is FALSE. -*/ -SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){ - pExpr = sqlite3ExprSkipCollate((Expr*)pExpr); - assert( pExpr->op==TK_TRUEFALSE ); - assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0 - || sqlite3StrICmp(pExpr->u.zToken,"false")==0 ); - return pExpr->u.zToken[4]==0; -} - -/* -** If pExpr is an AND or OR expression, try to simplify it by eliminating -** terms that are always true or false. Return the simplified expression. -** Or return the original expression if no simplification is possible. -** -** Examples: -** -** (x<10) AND true => (x<10) -** (x<10) AND false => false -** (x<10) AND (y=22 OR false) => (x<10) AND (y=22) -** (x<10) AND (y=22 OR true) => (x<10) -** (y=22) OR true => true -*/ -SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){ - assert( pExpr!=0 ); - if( pExpr->op==TK_AND || pExpr->op==TK_OR ){ - Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight); - Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft); - if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){ - pExpr = pExpr->op==TK_AND ? pRight : pLeft; - }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){ - pExpr = pExpr->op==TK_AND ? pLeft : pRight; - } - } - return pExpr; -} - - -/* -** These routines are Walker callbacks used to check expressions to -** see if they are "constant" for some definition of constant. The -** Walker.eCode value determines the type of "constant" we are looking -** for. -** -** These callback routines are used to implement the following: -** -** sqlite3ExprIsConstant() pWalker->eCode==1 -** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 -** sqlite3ExprIsTableConstant() pWalker->eCode==3 -** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 -** -** In all cases, the callbacks set Walker.eCode=0 and abort if the expression -** is found to not be a constant. -** -** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT -** expressions in a CREATE TABLE statement. The Walker.eCode value is 5 -** when parsing an existing schema out of the sqlite_schema table and 4 -** when processing a new CREATE TABLE statement. A bound parameter raises -** an error for new statements, but is silently converted -** to NULL for existing schemas. This allows sqlite_schema tables that -** contain a bound parameter because they were generated by older versions -** of SQLite to be parsed by newer versions of SQLite without raising a -** malformed schema error. -*/ -static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ - - /* If pWalker->eCode is 2 then any term of the expression that comes from - ** the ON or USING clauses of a left join disqualifies the expression - ** from being considered constant. */ - if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){ - pWalker->eCode = 0; - return WRC_Abort; - } - - switch( pExpr->op ){ - /* Consider functions to be constant if all their arguments are constant - ** and either pWalker->eCode==4 or 5 or the function has the - ** SQLITE_FUNC_CONST flag. */ - case TK_FUNCTION: - if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc)) - && !ExprHasProperty(pExpr, EP_WinFunc) - ){ - if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL); - return WRC_Continue; - }else{ - pWalker->eCode = 0; - return WRC_Abort; - } - case TK_ID: - /* Convert "true" or "false" in a DEFAULT clause into the - ** appropriate TK_TRUEFALSE operator */ - if( sqlite3ExprIdToTrueFalse(pExpr) ){ - return WRC_Prune; - } - /* no break */ deliberate_fall_through - case TK_COLUMN: - case TK_AGG_FUNCTION: - case TK_AGG_COLUMN: - testcase( pExpr->op==TK_ID ); - testcase( pExpr->op==TK_COLUMN ); - testcase( pExpr->op==TK_AGG_FUNCTION ); - testcase( pExpr->op==TK_AGG_COLUMN ); - if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){ - return WRC_Continue; - } - if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ - return WRC_Continue; - } - /* no break */ deliberate_fall_through - case TK_IF_NULL_ROW: - case TK_REGISTER: - case TK_DOT: - testcase( pExpr->op==TK_REGISTER ); - testcase( pExpr->op==TK_IF_NULL_ROW ); - testcase( pExpr->op==TK_DOT ); - pWalker->eCode = 0; - return WRC_Abort; - case TK_VARIABLE: - if( pWalker->eCode==5 ){ - /* Silently convert bound parameters that appear inside of CREATE - ** statements into a NULL when parsing the CREATE statement text out - ** of the sqlite_schema table */ - pExpr->op = TK_NULL; - }else if( pWalker->eCode==4 ){ - /* A bound parameter in a CREATE statement that originates from - ** sqlite3_prepare() causes an error */ - pWalker->eCode = 0; - return WRC_Abort; - } - /* no break */ deliberate_fall_through - default: - testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */ - testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */ - return WRC_Continue; - } -} -static int exprIsConst(Expr *p, int initFlag, int iCur){ - Walker w; - w.eCode = initFlag; - w.xExprCallback = exprNodeIsConstant; - w.xSelectCallback = sqlite3SelectWalkFail; -#ifdef SQLITE_DEBUG - w.xSelectCallback2 = sqlite3SelectWalkAssert2; -#endif - w.u.iCur = iCur; - sqlite3WalkExpr(&w, p); - return w.eCode; -} - -/* -** Walk an expression tree. Return non-zero if the expression is constant -** and 0 if it involves variables or function calls. -** -** For the purposes of this function, a double-quoted string (ex: "abc") -** is considered a variable but a single-quoted string (ex: 'abc') is -** a constant. -*/ -SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){ - return exprIsConst(p, 1, 0); -} - -/* -** Walk an expression tree. Return non-zero if -** -** (1) the expression is constant, and -** (2) the expression does originate in the ON or USING clause -** of a LEFT JOIN, and -** (3) the expression does not contain any EP_FixedCol TK_COLUMN -** operands created by the constant propagation optimization. -** -** When this routine returns true, it indicates that the expression -** can be added to the pParse->pConstExpr list and evaluated once when -** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce(). -*/ -SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){ - return exprIsConst(p, 2, 0); -} - -/* -** Walk an expression tree. Return non-zero if the expression is constant -** for any single row of the table with cursor iCur. In other words, the -** expression must not refer to any non-deterministic function nor any -** table other than iCur. -*/ -SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){ - return exprIsConst(p, 3, iCur); -} - - -/* -** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy(). -*/ -static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){ - ExprList *pGroupBy = pWalker->u.pGroupBy; - int i; - - /* Check if pExpr is identical to any GROUP BY term. If so, consider - ** it constant. */ - for(i=0; inExpr; i++){ - Expr *p = pGroupBy->a[i].pExpr; - if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){ - CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p); - if( sqlite3IsBinary(pColl) ){ - return WRC_Prune; - } - } - } - - /* Check if pExpr is a sub-select. If so, consider it variable. */ - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - pWalker->eCode = 0; - return WRC_Abort; - } - - return exprNodeIsConstant(pWalker, pExpr); -} - -/* -** Walk the expression tree passed as the first argument. Return non-zero -** if the expression consists entirely of constants or copies of terms -** in pGroupBy that sort with the BINARY collation sequence. -** -** This routine is used to determine if a term of the HAVING clause can -** be promoted into the WHERE clause. In order for such a promotion to work, -** the value of the HAVING clause term must be the same for all members of -** a "group". The requirement that the GROUP BY term must be BINARY -** assumes that no other collating sequence will have a finer-grained -** grouping than binary. In other words (A=B COLLATE binary) implies -** A=B in every other collating sequence. The requirement that the -** GROUP BY be BINARY is stricter than necessary. It would also work -** to promote HAVING clauses that use the same alternative collating -** sequence as the GROUP BY term, but that is much harder to check, -** alternative collating sequences are uncommon, and this is only an -** optimization, so we take the easy way out and simply require the -** GROUP BY to use the BINARY collating sequence. -*/ -SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){ - Walker w; - w.eCode = 1; - w.xExprCallback = exprNodeIsConstantOrGroupBy; - w.xSelectCallback = 0; - w.u.pGroupBy = pGroupBy; - w.pParse = pParse; - sqlite3WalkExpr(&w, p); - return w.eCode; -} - -/* -** Walk an expression tree for the DEFAULT field of a column definition -** in a CREATE TABLE statement. Return non-zero if the expression is -** acceptable for use as a DEFAULT. That is to say, return non-zero if -** the expression is constant or a function call with constant arguments. -** Return and 0 if there are any variables. -** -** isInit is true when parsing from sqlite_schema. isInit is false when -** processing a new CREATE TABLE statement. When isInit is true, parameters -** (such as ? or $abc) in the expression are converted into NULL. When -** isInit is false, parameters raise an error. Parameters should not be -** allowed in a CREATE TABLE statement, but some legacy versions of SQLite -** allowed it, so we need to support it when reading sqlite_schema for -** backwards compatibility. -** -** If isInit is true, set EP_FromDDL on every TK_FUNCTION node. -** -** For the purposes of this function, a double-quoted string (ex: "abc") -** is considered a variable but a single-quoted string (ex: 'abc') is -** a constant. -*/ -SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ - assert( isInit==0 || isInit==1 ); - return exprIsConst(p, 4+isInit, 0); -} - -#ifdef SQLITE_ENABLE_CURSOR_HINTS -/* -** Walk an expression tree. Return 1 if the expression contains a -** subquery of some kind. Return 0 if there are no subqueries. -*/ -SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){ - Walker w; - w.eCode = 1; - w.xExprCallback = sqlite3ExprWalkNoop; - w.xSelectCallback = sqlite3SelectWalkFail; -#ifdef SQLITE_DEBUG - w.xSelectCallback2 = sqlite3SelectWalkAssert2; -#endif - sqlite3WalkExpr(&w, p); - return w.eCode==0; -} -#endif - -/* -** If the expression p codes a constant integer that is small enough -** to fit in a 32-bit integer, return 1 and put the value of the integer -** in *pValue. If the expression is not an integer or if it is too big -** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. -*/ -SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){ - int rc = 0; - if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */ - - /* If an expression is an integer literal that fits in a signed 32-bit - ** integer, then the EP_IntValue flag will have already been set */ - assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 - || sqlite3GetInt32(p->u.zToken, &rc)==0 ); - - if( p->flags & EP_IntValue ){ - *pValue = p->u.iValue; - return 1; - } - switch( p->op ){ - case TK_UPLUS: { - rc = sqlite3ExprIsInteger(p->pLeft, pValue); - break; - } - case TK_UMINUS: { - int v; - if( sqlite3ExprIsInteger(p->pLeft, &v) ){ - assert( v!=(-2147483647-1) ); - *pValue = -v; - rc = 1; - } - break; - } - default: break; - } - return rc; -} - -/* -** Return FALSE if there is no chance that the expression can be NULL. -** -** If the expression might be NULL or if the expression is too complex -** to tell return TRUE. -** -** This routine is used as an optimization, to skip OP_IsNull opcodes -** when we know that a value cannot be NULL. Hence, a false positive -** (returning TRUE when in fact the expression can never be NULL) might -** be a small performance hit but is otherwise harmless. On the other -** hand, a false negative (returning FALSE when the result could be NULL) -** will likely result in an incorrect answer. So when in doubt, return -** TRUE. -*/ -SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){ - u8 op; - while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ - p = p->pLeft; - } - op = p->op; - if( op==TK_REGISTER ) op = p->op2; - switch( op ){ - case TK_INTEGER: - case TK_STRING: - case TK_FLOAT: - case TK_BLOB: - return 0; - case TK_COLUMN: - return ExprHasProperty(p, EP_CanBeNull) || - p->y.pTab==0 || /* Reference to column of index on expression */ - (p->iColumn>=0 - && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */ - && p->y.pTab->aCol[p->iColumn].notNull==0); - default: - return 1; - } -} - -/* -** Return TRUE if the given expression is a constant which would be -** unchanged by OP_Affinity with the affinity given in the second -** argument. -** -** This routine is used to determine if the OP_Affinity operation -** can be omitted. When in doubt return FALSE. A false negative -** is harmless. A false positive, however, can result in the wrong -** answer. -*/ -SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ - u8 op; - int unaryMinus = 0; - if( aff==SQLITE_AFF_BLOB ) return 1; - while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ - if( p->op==TK_UMINUS ) unaryMinus = 1; - p = p->pLeft; - } - op = p->op; - if( op==TK_REGISTER ) op = p->op2; - switch( op ){ - case TK_INTEGER: { - return aff>=SQLITE_AFF_NUMERIC; - } - case TK_FLOAT: { - return aff>=SQLITE_AFF_NUMERIC; - } - case TK_STRING: { - return !unaryMinus && aff==SQLITE_AFF_TEXT; - } - case TK_BLOB: { - return !unaryMinus; - } - case TK_COLUMN: { - assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ - return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0; - } - default: { - return 0; - } - } -} - -/* -** Return TRUE if the given string is a row-id column name. -*/ -SQLITE_PRIVATE int sqlite3IsRowid(const char *z){ - if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; - if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; - if( sqlite3StrICmp(z, "OID")==0 ) return 1; - return 0; -} - -/* -** pX is the RHS of an IN operator. If pX is a SELECT statement -** that can be simplified to a direct table access, then return -** a pointer to the SELECT statement. If pX is not a SELECT statement, -** or if the SELECT statement needs to be manifested into a transient -** table, then return NULL. -*/ -#ifndef SQLITE_OMIT_SUBQUERY -static Select *isCandidateForInOpt(Expr *pX){ - Select *p; - SrcList *pSrc; - ExprList *pEList; - Table *pTab; - int i; - if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */ - if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */ - p = pX->x.pSelect; - if( p->pPrior ) return 0; /* Not a compound SELECT */ - if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ - testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); - testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); - return 0; /* No DISTINCT keyword and no aggregate functions */ - } - assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ - if( p->pLimit ) return 0; /* Has no LIMIT clause */ - if( p->pWhere ) return 0; /* Has no WHERE clause */ - pSrc = p->pSrc; - assert( pSrc!=0 ); - if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ - if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ - pTab = pSrc->a[0].pTab; - assert( pTab!=0 ); - assert( pTab->pSelect==0 ); /* FROM clause is not a view */ - if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ - pEList = p->pEList; - assert( pEList!=0 ); - /* All SELECT results must be columns. */ - for(i=0; inExpr; i++){ - Expr *pRes = pEList->a[i].pExpr; - if( pRes->op!=TK_COLUMN ) return 0; - assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */ - } - return p; -} -#endif /* SQLITE_OMIT_SUBQUERY */ - -#ifndef SQLITE_OMIT_SUBQUERY -/* -** Generate code that checks the left-most column of index table iCur to see if -** it contains any NULL entries. Cause the register at regHasNull to be set -** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull -** to be set to NULL if iCur contains one or more NULL values. -*/ -static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ - int addr1; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); - addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); - sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); - VdbeComment((v, "first_entry_in(%d)", iCur)); - sqlite3VdbeJumpHere(v, addr1); -} -#endif - - -#ifndef SQLITE_OMIT_SUBQUERY -/* -** The argument is an IN operator with a list (not a subquery) on the -** right-hand side. Return TRUE if that list is constant. -*/ -static int sqlite3InRhsIsConstant(Expr *pIn){ - Expr *pLHS; - int res; - assert( !ExprHasProperty(pIn, EP_xIsSelect) ); - pLHS = pIn->pLeft; - pIn->pLeft = 0; - res = sqlite3ExprIsConstant(pIn); - pIn->pLeft = pLHS; - return res; -} -#endif - -/* -** This function is used by the implementation of the IN (...) operator. -** The pX parameter is the expression on the RHS of the IN operator, which -** might be either a list of expressions or a subquery. -** -** The job of this routine is to find or create a b-tree object that can -** be used either to test for membership in the RHS set or to iterate through -** all members of the RHS set, skipping duplicates. -** -** A cursor is opened on the b-tree object that is the RHS of the IN operator -** and pX->iTable is set to the index of that cursor. -** -** The returned value of this function indicates the b-tree type, as follows: -** -** IN_INDEX_ROWID - The cursor was opened on a database table. -** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. -** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. -** IN_INDEX_EPH - The cursor was opened on a specially created and -** populated epheremal table. -** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be -** implemented as a sequence of comparisons. -** -** An existing b-tree might be used if the RHS expression pX is a simple -** subquery such as: -** -** SELECT , ... FROM -** -** If the RHS of the IN operator is a list or a more complex subquery, then -** an ephemeral table might need to be generated from the RHS and then -** pX->iTable made to point to the ephemeral table instead of an -** existing table. -** -** The inFlags parameter must contain, at a minimum, one of the bits -** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains -** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast -** membership test. When the IN_INDEX_LOOP bit is set, the IN index will -** be used to loop over all values of the RHS of the IN operator. -** -** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate -** through the set members) then the b-tree must not contain duplicates. -** An epheremal table will be created unless the selected columns are guaranteed -** to be unique - either because it is an INTEGER PRIMARY KEY or due to -** a UNIQUE constraint or index. -** -** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used -** for fast set membership tests) then an epheremal table must -** be used unless is a single INTEGER PRIMARY KEY column or an -** index can be found with the specified as its left-most. -** -** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and -** if the RHS of the IN operator is a list (not a subquery) then this -** routine might decide that creating an ephemeral b-tree for membership -** testing is too expensive and return IN_INDEX_NOOP. In that case, the -** calling routine should implement the IN operator using a sequence -** of Eq or Ne comparison operations. -** -** When the b-tree is being used for membership tests, the calling function -** might need to know whether or not the RHS side of the IN operator -** contains a NULL. If prRhsHasNull is not a NULL pointer and -** if there is any chance that the (...) might contain a NULL value at -** runtime, then a register is allocated and the register number written -** to *prRhsHasNull. If there is no chance that the (...) contains a -** NULL value, then *prRhsHasNull is left unchanged. -** -** If a register is allocated and its location stored in *prRhsHasNull, then -** the value in that register will be NULL if the b-tree contains one or more -** NULL values, and it will be some non-NULL value if the b-tree contains no -** NULL values. -** -** If the aiMap parameter is not NULL, it must point to an array containing -** one element for each column returned by the SELECT statement on the RHS -** of the IN(...) operator. The i'th entry of the array is populated with the -** offset of the index column that matches the i'th column returned by the -** SELECT. For example, if the expression and selected index are: -** -** (?,?,?) IN (SELECT a, b, c FROM t1) -** CREATE INDEX i1 ON t1(b, c, a); -** -** then aiMap[] is populated with {2, 0, 1}. -*/ -#ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3FindInIndex( - Parse *pParse, /* Parsing context */ - Expr *pX, /* The IN expression */ - u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ - int *prRhsHasNull, /* Register holding NULL status. See notes */ - int *aiMap, /* Mapping from Index fields to RHS fields */ - int *piTab /* OUT: index to use */ -){ - Select *p; /* SELECT to the right of IN operator */ - int eType = 0; /* Type of RHS table. IN_INDEX_* */ - int iTab = pParse->nTab++; /* Cursor of the RHS table */ - int mustBeUnique; /* True if RHS must be unique */ - Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ - - assert( pX->op==TK_IN ); - mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; - - /* If the RHS of this IN(...) operator is a SELECT, and if it matters - ** whether or not the SELECT result contains NULL values, check whether - ** or not NULL is actually possible (it may not be, for example, due - ** to NOT NULL constraints in the schema). If no NULL values are possible, - ** set prRhsHasNull to 0 before continuing. */ - if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){ - int i; - ExprList *pEList = pX->x.pSelect->pEList; - for(i=0; inExpr; i++){ - if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; - } - if( i==pEList->nExpr ){ - prRhsHasNull = 0; - } - } - - /* Check to see if an existing table or index can be used to - ** satisfy the query. This is preferable to generating a new - ** ephemeral table. */ - if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ - sqlite3 *db = pParse->db; /* Database connection */ - Table *pTab; /* Table
    . */ - int iDb; /* Database idx for pTab */ - ExprList *pEList = p->pEList; - int nExpr = pEList->nExpr; - - assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ - assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ - assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ - pTab = p->pSrc->a[0].pTab; - - /* Code an OP_Transaction and OP_TableLock for
    . */ - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - assert( iDb>=0 && iDbtnum, 0, pTab->zName); - - assert(v); /* sqlite3GetVdbe() has always been previously called */ - if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ - /* The "x IN (SELECT rowid FROM table)" case */ - int iAddr = sqlite3VdbeAddOp0(v, OP_Once); - VdbeCoverage(v); - - sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); - eType = IN_INDEX_ROWID; - ExplainQueryPlan((pParse, 0, - "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName)); - sqlite3VdbeJumpHere(v, iAddr); - }else{ - Index *pIdx; /* Iterator variable */ - int affinity_ok = 1; - int i; - - /* Check that the affinity that will be used to perform each - ** comparison is the same as the affinity of each column in table - ** on the RHS of the IN operator. If it not, it is not possible to - ** use any index of the RHS table. */ - for(i=0; ipLeft, i); - int iCol = pEList->a[i].pExpr->iColumn; - char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ - char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); - testcase( cmpaff==SQLITE_AFF_BLOB ); - testcase( cmpaff==SQLITE_AFF_TEXT ); - switch( cmpaff ){ - case SQLITE_AFF_BLOB: - break; - case SQLITE_AFF_TEXT: - /* sqlite3CompareAffinity() only returns TEXT if one side or the - ** other has no affinity and the other side is TEXT. Hence, - ** the only way for cmpaff to be TEXT is for idxaff to be TEXT - ** and for the term on the LHS of the IN to have no affinity. */ - assert( idxaff==SQLITE_AFF_TEXT ); - break; - default: - affinity_ok = sqlite3IsNumericAffinity(idxaff); - } - } - - if( affinity_ok ){ - /* Search for an existing index that will work for this IN operator */ - for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){ - Bitmask colUsed; /* Columns of the index used */ - Bitmask mCol; /* Mask for the current column */ - if( pIdx->nColumnpPartIdxWhere!=0 ) continue; - /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute - ** BITMASK(nExpr) without overflowing */ - testcase( pIdx->nColumn==BMS-2 ); - testcase( pIdx->nColumn==BMS-1 ); - if( pIdx->nColumn>=BMS-1 ) continue; - if( mustBeUnique ){ - if( pIdx->nKeyCol>nExpr - ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx)) - ){ - continue; /* This index is not unique over the IN RHS columns */ - } - } - - colUsed = 0; /* Columns of index used so far */ - for(i=0; ipLeft, i); - Expr *pRhs = pEList->a[i].pExpr; - CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); - int j; - - assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr ); - for(j=0; jaiColumn[j]!=pRhs->iColumn ) continue; - assert( pIdx->azColl[j] ); - if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ - continue; - } - break; - } - if( j==nExpr ) break; - mCol = MASKBIT(j); - if( mCol & colUsed ) break; /* Each column used only once */ - colUsed |= mCol; - if( aiMap ) aiMap[i] = j; - } - - assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); - if( colUsed==(MASKBIT(nExpr)-1) ){ - /* If we reach this point, that means the index pIdx is usable */ - int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - ExplainQueryPlan((pParse, 0, - "USING INDEX %s FOR IN-OPERATOR",pIdx->zName)); - sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); - VdbeComment((v, "%s", pIdx->zName)); - assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); - eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; - - if( prRhsHasNull ){ -#ifdef SQLITE_ENABLE_COLUMN_USED_MASK - i64 mask = (1<nMem; - if( nExpr==1 ){ - sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); - } - } - sqlite3VdbeJumpHere(v, iAddr); - } - } /* End loop over indexes */ - } /* End if( affinity_ok ) */ - } /* End if not an rowid index */ - } /* End attempt to optimize using an index */ - - /* If no preexisting index is available for the IN clause - ** and IN_INDEX_NOOP is an allowed reply - ** and the RHS of the IN operator is a list, not a subquery - ** and the RHS is not constant or has two or fewer terms, - ** then it is not worth creating an ephemeral table to evaluate - ** the IN operator so return IN_INDEX_NOOP. - */ - if( eType==0 - && (inFlags & IN_INDEX_NOOP_OK) - && !ExprHasProperty(pX, EP_xIsSelect) - && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) - ){ - eType = IN_INDEX_NOOP; - } - - if( eType==0 ){ - /* Could not find an existing table or index to use as the RHS b-tree. - ** We will have to generate an ephemeral table to do the job. - */ - u32 savedNQueryLoop = pParse->nQueryLoop; - int rMayHaveNull = 0; - eType = IN_INDEX_EPH; - if( inFlags & IN_INDEX_LOOP ){ - pParse->nQueryLoop = 0; - }else if( prRhsHasNull ){ - *prRhsHasNull = rMayHaveNull = ++pParse->nMem; - } - assert( pX->op==TK_IN ); - sqlite3CodeRhsOfIN(pParse, pX, iTab); - if( rMayHaveNull ){ - sqlite3SetHasNullFlag(v, iTab, rMayHaveNull); - } - pParse->nQueryLoop = savedNQueryLoop; - } - - if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ - int i, n; - n = sqlite3ExprVectorSize(pX->pLeft); - for(i=0; ipLeft; - int nVal = sqlite3ExprVectorSize(pLeft); - Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0; - char *zRet; - - assert( pExpr->op==TK_IN ); - zRet = sqlite3DbMallocRaw(pParse->db, nVal+1); - if( zRet ){ - int i; - for(i=0; ipEList->a[i].pExpr, a); - }else{ - zRet[i] = a; - } - } - zRet[nVal] = '\0'; - } - return zRet; -} -#endif - -#ifndef SQLITE_OMIT_SUBQUERY -/* -** Load the Parse object passed as the first argument with an error -** message of the form: -** -** "sub-select returns N columns - expected M" -*/ -SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ - if( pParse->nErr==0 ){ - const char *zFmt = "sub-select returns %d columns - expected %d"; - sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); - } -} -#endif - -/* -** Expression pExpr is a vector that has been used in a context where -** it is not permitted. If pExpr is a sub-select vector, this routine -** loads the Parse object with a message of the form: -** -** "sub-select returns N columns - expected 1" -** -** Or, if it is a regular scalar vector: -** -** "row value misused" -*/ -SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){ -#ifndef SQLITE_OMIT_SUBQUERY - if( pExpr->flags & EP_xIsSelect ){ - sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1); - }else -#endif - { - sqlite3ErrorMsg(pParse, "row value misused"); - } -} - -#ifndef SQLITE_OMIT_SUBQUERY -/* -** Generate code that will construct an ephemeral table containing all terms -** in the RHS of an IN operator. The IN operator can be in either of two -** forms: -** -** x IN (4,5,11) -- IN operator with list on right-hand side -** x IN (SELECT a FROM b) -- IN operator with subquery on the right -** -** The pExpr parameter is the IN operator. The cursor number for the -** constructed ephermeral table is returned. The first time the ephemeral -** table is computed, the cursor number is also stored in pExpr->iTable, -** however the cursor number returned might not be the same, as it might -** have been duplicated using OP_OpenDup. -** -** If the LHS expression ("x" in the examples) is a column value, or -** the SELECT statement returns a column value, then the affinity of that -** column is used to build the index keys. If both 'x' and the -** SELECT... statement are columns, then numeric affinity is used -** if either column has NUMERIC or INTEGER affinity. If neither -** 'x' nor the SELECT... statement are columns, then numeric affinity -** is used. -*/ -SQLITE_PRIVATE void sqlite3CodeRhsOfIN( - Parse *pParse, /* Parsing context */ - Expr *pExpr, /* The IN operator */ - int iTab /* Use this cursor number */ -){ - int addrOnce = 0; /* Address of the OP_Once instruction at top */ - int addr; /* Address of OP_OpenEphemeral instruction */ - Expr *pLeft; /* the LHS of the IN operator */ - KeyInfo *pKeyInfo = 0; /* Key information */ - int nVal; /* Size of vector pLeft */ - Vdbe *v; /* The prepared statement under construction */ - - v = pParse->pVdbe; - assert( v!=0 ); - - /* The evaluation of the IN must be repeated every time it - ** is encountered if any of the following is true: - ** - ** * The right-hand side is a correlated subquery - ** * The right-hand side is an expression list containing variables - ** * We are inside a trigger - ** - ** If all of the above are false, then we can compute the RHS just once - ** and reuse it many names. - */ - if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){ - /* Reuse of the RHS is allowed */ - /* If this routine has already been coded, but the previous code - ** might not have been invoked yet, so invoke it now as a subroutine. - */ - if( ExprHasProperty(pExpr, EP_Subrtn) ){ - addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d", - pExpr->x.pSelect->selId)); - } - sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, - pExpr->y.sub.iAddr); - sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable); - sqlite3VdbeJumpHere(v, addrOnce); - return; - } - - /* Begin coding the subroutine */ - ExprSetProperty(pExpr, EP_Subrtn); - assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); - pExpr->y.sub.regReturn = ++pParse->nMem; - pExpr->y.sub.iAddr = - sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; - VdbeComment((v, "return address")); - - addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - } - - /* Check to see if this is a vector IN operator */ - pLeft = pExpr->pLeft; - nVal = sqlite3ExprVectorSize(pLeft); - - /* Construct the ephemeral table that will contain the content of - ** RHS of the IN operator. - */ - pExpr->iTable = iTab; - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal); -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId)); - }else{ - VdbeComment((v, "RHS of IN operator")); - } -#endif - pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1); - - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - /* Case 1: expr IN (SELECT ...) - ** - ** Generate code to write the results of the select into the temporary - ** table allocated and opened above. - */ - Select *pSelect = pExpr->x.pSelect; - ExprList *pEList = pSelect->pEList; - - ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d", - addrOnce?"":"CORRELATED ", pSelect->selId - )); - /* If the LHS and RHS of the IN operator do not match, that - ** error will have been caught long before we reach this point. */ - if( ALWAYS(pEList->nExpr==nVal) ){ - SelectDest dest; - int i; - sqlite3SelectDestInit(&dest, SRT_Set, iTab); - dest.zAffSdst = exprINAffinity(pParse, pExpr); - pSelect->iLimit = 0; - testcase( pSelect->selFlags & SF_Distinct ); - testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ - if( sqlite3Select(pParse, pSelect, &dest) ){ - sqlite3DbFree(pParse->db, dest.zAffSdst); - sqlite3KeyInfoUnref(pKeyInfo); - return; - } - sqlite3DbFree(pParse->db, dest.zAffSdst); - assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ - assert( pEList!=0 ); - assert( pEList->nExpr>0 ); - assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); - for(i=0; iaColl[i] = sqlite3BinaryCompareCollSeq( - pParse, p, pEList->a[i].pExpr - ); - } - } - }else if( ALWAYS(pExpr->x.pList!=0) ){ - /* Case 2: expr IN (exprlist) - ** - ** For each expression, build an index key from the evaluation and - ** store it in the temporary table. If is a column, then use - ** that columns affinity when building index keys. If is not - ** a column, use numeric affinity. - */ - char affinity; /* Affinity of the LHS of the IN */ - int i; - ExprList *pList = pExpr->x.pList; - struct ExprList_item *pItem; - int r1, r2; - affinity = sqlite3ExprAffinity(pLeft); - if( affinity<=SQLITE_AFF_NONE ){ - affinity = SQLITE_AFF_BLOB; - }else if( affinity==SQLITE_AFF_REAL ){ - affinity = SQLITE_AFF_NUMERIC; - } - if( pKeyInfo ){ - assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); - pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - } - - /* Loop through each expression in . */ - r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3GetTempReg(pParse); - for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ - Expr *pE2 = pItem->pExpr; - - /* If the expression is not constant then we will need to - ** disable the test that was generated above that makes sure - ** this code only executes once. Because for a non-constant - ** expression we need to rerun this code each time. - */ - if( addrOnce && !sqlite3ExprIsConstant(pE2) ){ - sqlite3VdbeChangeToNoop(v, addrOnce); - ExprClearProperty(pExpr, EP_Subrtn); - addrOnce = 0; - } - - /* Evaluate the expression and insert it into the temp table */ - sqlite3ExprCode(pParse, pE2, r1); - sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1); - } - sqlite3ReleaseTempReg(pParse, r1); - sqlite3ReleaseTempReg(pParse, r2); - } - if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); - } - if( addrOnce ){ - sqlite3VdbeJumpHere(v, addrOnce); - /* Subroutine return */ - sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); - sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1); - sqlite3ClearTempRegCache(pParse); - } -} -#endif /* SQLITE_OMIT_SUBQUERY */ - -/* -** Generate code for scalar subqueries used as a subquery expression -** or EXISTS operator: -** -** (SELECT a FROM b) -- subquery -** EXISTS (SELECT a FROM b) -- EXISTS subquery -** -** The pExpr parameter is the SELECT or EXISTS operator to be coded. -** -** Return the register that holds the result. For a multi-column SELECT, -** the result is stored in a contiguous array of registers and the -** return value is the register of the left-most result column. -** Return 0 if an error occurs. -*/ -#ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ - int addrOnce = 0; /* Address of OP_Once at top of subroutine */ - int rReg = 0; /* Register storing resulting */ - Select *pSel; /* SELECT statement to encode */ - SelectDest dest; /* How to deal with SELECT result */ - int nReg; /* Registers to allocate */ - Expr *pLimit; /* New limit expression */ - - Vdbe *v = pParse->pVdbe; - assert( v!=0 ); - testcase( pExpr->op==TK_EXISTS ); - testcase( pExpr->op==TK_SELECT ); - assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); - assert( ExprHasProperty(pExpr, EP_xIsSelect) ); - pSel = pExpr->x.pSelect; - - /* The evaluation of the EXISTS/SELECT must be repeated every time it - ** is encountered if any of the following is true: - ** - ** * The right-hand side is a correlated subquery - ** * The right-hand side is an expression list containing variables - ** * We are inside a trigger - ** - ** If all of the above are false, then we can run this code just once - ** save the results, and reuse the same result on subsequent invocations. - */ - if( !ExprHasProperty(pExpr, EP_VarSelect) ){ - /* If this routine has already been coded, then invoke it as a - ** subroutine. */ - if( ExprHasProperty(pExpr, EP_Subrtn) ){ - ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId)); - sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, - pExpr->y.sub.iAddr); - return pExpr->iTable; - } - - /* Begin coding the subroutine */ - ExprSetProperty(pExpr, EP_Subrtn); - pExpr->y.sub.regReturn = ++pParse->nMem; - pExpr->y.sub.iAddr = - sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; - VdbeComment((v, "return address")); - - addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - } - - /* For a SELECT, generate code to put the values for all columns of - ** the first row into an array of registers and return the index of - ** the first register. - ** - ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) - ** into a register and return that register number. - ** - ** In both cases, the query is augmented with "LIMIT 1". Any - ** preexisting limit is discarded in place of the new LIMIT 1. - */ - ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d", - addrOnce?"":"CORRELATED ", pSel->selId)); - nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; - sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); - pParse->nMem += nReg; - if( pExpr->op==TK_SELECT ){ - dest.eDest = SRT_Mem; - dest.iSdst = dest.iSDParm; - dest.nSdst = nReg; - sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); - VdbeComment((v, "Init subquery result")); - }else{ - dest.eDest = SRT_Exists; - sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); - VdbeComment((v, "Init EXISTS result")); - } - if( pSel->pLimit ){ - /* The subquery already has a limit. If the pre-existing limit is X - ** then make the new limit X<>0 so that the new limit is either 1 or 0 */ - sqlite3 *db = pParse->db; - pLimit = sqlite3Expr(db, TK_INTEGER, "0"); - if( pLimit ){ - pLimit->affExpr = SQLITE_AFF_NUMERIC; - pLimit = sqlite3PExpr(pParse, TK_NE, - sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit); - } - sqlite3ExprDelete(db, pSel->pLimit->pLeft); - pSel->pLimit->pLeft = pLimit; - }else{ - /* If there is no pre-existing limit add a limit of 1 */ - pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1"); - pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0); - } - pSel->iLimit = 0; - if( sqlite3Select(pParse, pSel, &dest) ){ - return 0; - } - pExpr->iTable = rReg = dest.iSDParm; - ExprSetVVAProperty(pExpr, EP_NoReduce); - if( addrOnce ){ - sqlite3VdbeJumpHere(v, addrOnce); - - /* Subroutine return */ - sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); - sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1); - sqlite3ClearTempRegCache(pParse); - } - - return rReg; -} -#endif /* SQLITE_OMIT_SUBQUERY */ - -#ifndef SQLITE_OMIT_SUBQUERY -/* -** Expr pIn is an IN(...) expression. This function checks that the -** sub-select on the RHS of the IN() operator has the same number of -** columns as the vector on the LHS. Or, if the RHS of the IN() is not -** a sub-query, that the LHS is a vector of size 1. -*/ -SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ - int nVector = sqlite3ExprVectorSize(pIn->pLeft); - if( (pIn->flags & EP_xIsSelect) ){ - if( nVector!=pIn->x.pSelect->pEList->nExpr ){ - sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); - return 1; - } - }else if( nVector!=1 ){ - sqlite3VectorErrorMsg(pParse, pIn->pLeft); - return 1; - } - return 0; -} -#endif - -#ifndef SQLITE_OMIT_SUBQUERY -/* -** Generate code for an IN expression. -** -** x IN (SELECT ...) -** x IN (value, value, ...) -** -** The left-hand side (LHS) is a scalar or vector expression. The -** right-hand side (RHS) is an array of zero or more scalar values, or a -** subquery. If the RHS is a subquery, the number of result columns must -** match the number of columns in the vector on the LHS. If the RHS is -** a list of values, the LHS must be a scalar. -** -** The IN operator is true if the LHS value is contained within the RHS. -** The result is false if the LHS is definitely not in the RHS. The -** result is NULL if the presence of the LHS in the RHS cannot be -** determined due to NULLs. -** -** This routine generates code that jumps to destIfFalse if the LHS is not -** contained within the RHS. If due to NULLs we cannot determine if the LHS -** is contained in the RHS then jump to destIfNull. If the LHS is contained -** within the RHS then fall through. -** -** See the separate in-operator.md documentation file in the canonical -** SQLite source tree for additional information. -*/ -static void sqlite3ExprCodeIN( - Parse *pParse, /* Parsing and code generating context */ - Expr *pExpr, /* The IN expression */ - int destIfFalse, /* Jump here if LHS is not contained in the RHS */ - int destIfNull /* Jump here if the results are unknown due to NULLs */ -){ - int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ - int eType; /* Type of the RHS */ - int rLhs; /* Register(s) holding the LHS values */ - int rLhsOrig; /* LHS values prior to reordering by aiMap[] */ - Vdbe *v; /* Statement under construction */ - int *aiMap = 0; /* Map from vector field to index column */ - char *zAff = 0; /* Affinity string for comparisons */ - int nVector; /* Size of vectors for this IN operator */ - int iDummy; /* Dummy parameter to exprCodeVector() */ - Expr *pLeft; /* The LHS of the IN operator */ - int i; /* loop counter */ - int destStep2; /* Where to jump when NULLs seen in step 2 */ - int destStep6 = 0; /* Start of code for Step 6 */ - int addrTruthOp; /* Address of opcode that determines the IN is true */ - int destNotNull; /* Jump here if a comparison is not true in step 6 */ - int addrTop; /* Top of the step-6 loop */ - int iTab = 0; /* Index to use */ - u8 okConstFactor = pParse->okConstFactor; - - assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); - pLeft = pExpr->pLeft; - if( sqlite3ExprCheckIN(pParse, pExpr) ) return; - zAff = exprINAffinity(pParse, pExpr); - nVector = sqlite3ExprVectorSize(pExpr->pLeft); - aiMap = (int*)sqlite3DbMallocZero( - pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1 - ); - if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; - - /* Attempt to compute the RHS. After this step, if anything other than - ** IN_INDEX_NOOP is returned, the table opened with cursor iTab - ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, - ** the RHS has not yet been coded. */ - v = pParse->pVdbe; - assert( v!=0 ); /* OOM detected prior to this routine */ - VdbeNoopComment((v, "begin IN expr")); - eType = sqlite3FindInIndex(pParse, pExpr, - IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, - destIfFalse==destIfNull ? 0 : &rRhsHasNull, - aiMap, &iTab); - - assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH - || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC - ); -#ifdef SQLITE_DEBUG - /* Confirm that aiMap[] contains nVector integer values between 0 and - ** nVector-1. */ - for(i=0; i from " IN (...)". If the LHS is a - ** vector, then it is stored in an array of nVector registers starting - ** at r1. - ** - ** sqlite3FindInIndex() might have reordered the fields of the LHS vector - ** so that the fields are in the same order as an existing index. The - ** aiMap[] array contains a mapping from the original LHS field order to - ** the field order that matches the RHS index. - ** - ** Avoid factoring the LHS of the IN(...) expression out of the loop, - ** even if it is constant, as OP_Affinity may be used on the register - ** by code generated below. */ - assert( pParse->okConstFactor==okConstFactor ); - pParse->okConstFactor = 0; - rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); - pParse->okConstFactor = okConstFactor; - for(i=0; ix.pList; - CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - int labelOk = sqlite3VdbeMakeLabel(pParse); - int r2, regToFree; - int regCkNull = 0; - int ii; - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - if( destIfNull!=destIfFalse ){ - regCkNull = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); - } - for(ii=0; iinExpr; ii++){ - r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); - if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ - sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); - } - sqlite3ReleaseTempReg(pParse, regToFree); - if( iinExpr-1 || destIfNull!=destIfFalse ){ - int op = rLhs!=r2 ? OP_Eq : OP_NotNull; - sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2, - (void*)pColl, P4_COLLSEQ); - VdbeCoverageIf(v, iinExpr-1 && op==OP_Eq); - VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq); - VdbeCoverageIf(v, iinExpr-1 && op==OP_NotNull); - VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull); - sqlite3VdbeChangeP5(v, zAff[0]); - }else{ - int op = rLhs!=r2 ? OP_Ne : OP_IsNull; - assert( destIfNull==destIfFalse ); - sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2, - (void*)pColl, P4_COLLSEQ); - VdbeCoverageIf(v, op==OP_Ne); - VdbeCoverageIf(v, op==OP_IsNull); - sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); - } - } - if( regCkNull ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); - sqlite3VdbeGoto(v, destIfFalse); - } - sqlite3VdbeResolveLabel(v, labelOk); - sqlite3ReleaseTempReg(pParse, regCkNull); - goto sqlite3ExprCodeIN_finished; - } - - /* Step 2: Check to see if the LHS contains any NULL columns. If the - ** LHS does contain NULLs then the result must be either FALSE or NULL. - ** We will then skip the binary search of the RHS. - */ - if( destIfNull==destIfFalse ){ - destStep2 = destIfFalse; - }else{ - destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse); - } - if( pParse->nErr ) goto sqlite3ExprCodeIN_finished; - for(i=0; ipLeft, i); - if( sqlite3ExprCanBeNull(p) ){ - sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); - VdbeCoverage(v); - } - } - - /* Step 3. The LHS is now known to be non-NULL. Do the binary search - ** of the RHS using the LHS as a probe. If found, the result is - ** true. - */ - if( eType==IN_INDEX_ROWID ){ - /* In this case, the RHS is the ROWID of table b-tree and so we also - ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 - ** into a single opcode. */ - sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs); - VdbeCoverage(v); - addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ - }else{ - sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); - if( destIfFalse==destIfNull ){ - /* Combine Step 3 and Step 5 into a single opcode */ - sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse, - rLhs, nVector); VdbeCoverage(v); - goto sqlite3ExprCodeIN_finished; - } - /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ - addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0, - rLhs, nVector); VdbeCoverage(v); - } - - /* Step 4. If the RHS is known to be non-NULL and we did not find - ** an match on the search above, then the result must be FALSE. - */ - if( rRhsHasNull && nVector==1 ){ - sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); - VdbeCoverage(v); - } - - /* Step 5. If we do not care about the difference between NULL and - ** FALSE, then just return false. - */ - if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); - - /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. - ** If any comparison is NULL, then the result is NULL. If all - ** comparisons are FALSE then the final result is FALSE. - ** - ** For a scalar LHS, it is sufficient to check just the first row - ** of the RHS. - */ - if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); - addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); - VdbeCoverage(v); - if( nVector>1 ){ - destNotNull = sqlite3VdbeMakeLabel(pParse); - }else{ - /* For nVector==1, combine steps 6 and 7 by immediately returning - ** FALSE if the first comparison is not NULL */ - destNotNull = destIfFalse; - } - for(i=0; i1 ){ - sqlite3VdbeResolveLabel(v, destNotNull); - sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1); - VdbeCoverage(v); - - /* Step 7: If we reach this point, we know that the result must - ** be false. */ - sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); - } - - /* Jumps here in order to return true. */ - sqlite3VdbeJumpHere(v, addrTruthOp); - -sqlite3ExprCodeIN_finished: - if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); - VdbeComment((v, "end IN expr")); -sqlite3ExprCodeIN_oom_error: - sqlite3DbFree(pParse->db, aiMap); - sqlite3DbFree(pParse->db, zAff); -} -#endif /* SQLITE_OMIT_SUBQUERY */ - -#ifndef SQLITE_OMIT_FLOATING_POINT -/* -** Generate an instruction that will put the floating point -** value described by z[0..n-1] into register iMem. -** -** The z[] string will probably not be zero-terminated. But the -** z[n] character is guaranteed to be something that does not look -** like the continuation of the number. -*/ -static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ - if( ALWAYS(z!=0) ){ - double value; - sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); - assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ - if( negateFlag ) value = -value; - sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); - } -} -#endif - - -/* -** Generate an instruction that will put the integer describe by -** text z[0..n-1] into register iMem. -** -** Expr.u.zToken is always UTF8 and zero-terminated. -*/ -static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ - Vdbe *v = pParse->pVdbe; - if( pExpr->flags & EP_IntValue ){ - int i = pExpr->u.iValue; - assert( i>=0 ); - if( negFlag ) i = -i; - sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); - }else{ - int c; - i64 value; - const char *z = pExpr->u.zToken; - assert( z!=0 ); - c = sqlite3DecOrHexToI64(z, &value); - if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){ -#ifdef SQLITE_OMIT_FLOATING_POINT - sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); -#else -#ifndef SQLITE_OMIT_HEX_INTEGER - if( sqlite3_strnicmp(z,"0x",2)==0 ){ - sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z); - }else -#endif - { - codeReal(v, z, negFlag, iMem); - } -#endif - }else{ - if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; } - sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); - } - } -} - - -/* Generate code that will load into register regOut a value that is -** appropriate for the iIdxCol-th column of index pIdx. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn( - Parse *pParse, /* The parsing context */ - Index *pIdx, /* The index whose column is to be loaded */ - int iTabCur, /* Cursor pointing to a table row */ - int iIdxCol, /* The column of the index to be loaded */ - int regOut /* Store the index column value in this register */ -){ - i16 iTabCol = pIdx->aiColumn[iIdxCol]; - if( iTabCol==XN_EXPR ){ - assert( pIdx->aColExpr ); - assert( pIdx->aColExpr->nExpr>iIdxCol ); - pParse->iSelfTab = iTabCur + 1; - sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); - pParse->iSelfTab = 0; - }else{ - sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, - iTabCol, regOut); - } -} - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS -/* -** Generate code that will compute the value of generated column pCol -** and store the result in register regOut -*/ -SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn( - Parse *pParse, - Column *pCol, - int regOut -){ - int iAddr; - Vdbe *v = pParse->pVdbe; - assert( v!=0 ); - assert( pParse->iSelfTab!=0 ); - if( pParse->iSelfTab>0 ){ - iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut); - }else{ - iAddr = 0; - } - sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut); - if( pCol->affinity>=SQLITE_AFF_TEXT ){ - sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1); - } - if( iAddr ) sqlite3VdbeJumpHere(v, iAddr); -} -#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ - -/* -** Generate code to extract the value of the iCol-th column of a table. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( - Vdbe *v, /* Parsing context */ - Table *pTab, /* The table containing the value */ - int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ - int iCol, /* Index of the column to extract */ - int regOut /* Extract the value into this register */ -){ - Column *pCol; - assert( v!=0 ); - if( pTab==0 ){ - sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut); - return; - } - if( iCol<0 || iCol==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); - }else{ - int op; - int x; - if( IsVirtual(pTab) ){ - op = OP_VColumn; - x = iCol; -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){ - Parse *pParse = sqlite3VdbeParser(v); - if( pCol->colFlags & COLFLAG_BUSY ){ - sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName); - }else{ - int savedSelfTab = pParse->iSelfTab; - pCol->colFlags |= COLFLAG_BUSY; - pParse->iSelfTab = iTabCur+1; - sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut); - pParse->iSelfTab = savedSelfTab; - pCol->colFlags &= ~COLFLAG_BUSY; - } - return; -#endif - }else if( !HasRowid(pTab) ){ - testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) ); - x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol); - op = OP_Column; - }else{ - x = sqlite3TableColumnToStorage(pTab,iCol); - testcase( x!=iCol ); - op = OP_Column; - } - sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); - sqlite3ColumnDefault(v, pTab, iCol, regOut); - } -} - -/* -** Generate code that will extract the iColumn-th column from -** table pTab and store the column value in register iReg. -** -** There must be an open cursor to pTab in iTable when this routine -** is called. If iColumn<0 then code is generated that extracts the rowid. -*/ -SQLITE_PRIVATE int sqlite3ExprCodeGetColumn( - Parse *pParse, /* Parsing and code generating context */ - Table *pTab, /* Description of the table we are reading from */ - int iColumn, /* Index of the table column */ - int iTable, /* The cursor pointing to the table */ - int iReg, /* Store results here */ - u8 p5 /* P5 value for OP_Column + FLAGS */ -){ - assert( pParse->pVdbe!=0 ); - sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg); - if( p5 ){ - VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1); - if( pOp->opcode==OP_Column ) pOp->p5 = p5; - } - return iReg; -} - -/* -** Generate code to move content from registers iFrom...iFrom+nReg-1 -** over to iTo..iTo+nReg-1. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ - sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); -} - -/* -** Convert a scalar expression node to a TK_REGISTER referencing -** register iReg. The caller must ensure that iReg already contains -** the correct value for the expression. -*/ -static void exprToRegister(Expr *pExpr, int iReg){ - Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr); - p->op2 = p->op; - p->op = TK_REGISTER; - p->iTable = iReg; - ExprClearProperty(p, EP_Skip); -} - -/* -** Evaluate an expression (either a vector or a scalar expression) and store -** the result in continguous temporary registers. Return the index of -** the first register used to store the result. -** -** If the returned result register is a temporary scalar, then also write -** that register number into *piFreeable. If the returned result register -** is not a temporary or if the expression is a vector set *piFreeable -** to 0. -*/ -static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ - int iResult; - int nResult = sqlite3ExprVectorSize(p); - if( nResult==1 ){ - iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); - }else{ - *piFreeable = 0; - if( p->op==TK_SELECT ){ -#if SQLITE_OMIT_SUBQUERY - iResult = 0; -#else - iResult = sqlite3CodeSubselect(pParse, p); -#endif - }else{ - int i; - iResult = pParse->nMem+1; - pParse->nMem += nResult; - for(i=0; ix.pList->a[i].pExpr, i+iResult); - } - } - } - return iResult; -} - -/* -** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5) -** so that a subsequent copy will not be merged into this one. -*/ -static void setDoNotMergeFlagOnCopy(Vdbe *v){ - if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){ - sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergable */ - } -} - -/* -** Generate code to implement special SQL functions that are implemented -** in-line rather than by using the usual callbacks. -*/ -static int exprCodeInlineFunction( - Parse *pParse, /* Parsing context */ - ExprList *pFarg, /* List of function arguments */ - int iFuncId, /* Function ID. One of the INTFUNC_... values */ - int target /* Store function result in this register */ -){ - int nFarg; - Vdbe *v = pParse->pVdbe; - assert( v!=0 ); - assert( pFarg!=0 ); - nFarg = pFarg->nExpr; - assert( nFarg>0 ); /* All in-line functions have at least one argument */ - switch( iFuncId ){ - case INLINEFUNC_coalesce: { - /* Attempt a direct implementation of the built-in COALESCE() and - ** IFNULL() functions. This avoids unnecessary evaluation of - ** arguments past the first non-NULL argument. - */ - int endCoalesce = sqlite3VdbeMakeLabel(pParse); - int i; - assert( nFarg>=2 ); - sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); - for(i=1; ia[i].pExpr, target); - } - setDoNotMergeFlagOnCopy(v); - sqlite3VdbeResolveLabel(v, endCoalesce); - break; - } - case INLINEFUNC_iif: { - Expr caseExpr; - memset(&caseExpr, 0, sizeof(caseExpr)); - caseExpr.op = TK_CASE; - caseExpr.x.pList = pFarg; - return sqlite3ExprCodeTarget(pParse, &caseExpr, target); - } - - default: { - /* The UNLIKELY() function is a no-op. The result is the value - ** of the first argument. - */ - assert( nFarg==1 || nFarg==2 ); - target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); - break; - } - - /*********************************************************************** - ** Test-only SQL functions that are only usable if enabled - ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS - */ - case INLINEFUNC_expr_compare: { - /* Compare two expressions using sqlite3ExprCompare() */ - assert( nFarg==2 ); - sqlite3VdbeAddOp2(v, OP_Integer, - sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), - target); - break; - } - - case INLINEFUNC_expr_implies_expr: { - /* Compare two expressions using sqlite3ExprImpliesExpr() */ - assert( nFarg==2 ); - sqlite3VdbeAddOp2(v, OP_Integer, - sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), - target); - break; - } - - case INLINEFUNC_implies_nonnull_row: { - /* REsult of sqlite3ExprImpliesNonNullRow() */ - Expr *pA1; - assert( nFarg==2 ); - pA1 = pFarg->a[1].pExpr; - if( pA1->op==TK_COLUMN ){ - sqlite3VdbeAddOp2(v, OP_Integer, - sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable), - target); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - } - break; - } - -#ifdef SQLITE_DEBUG - case INLINEFUNC_affinity: { - /* The AFFINITY() function evaluates to a string that describes - ** the type affinity of the argument. This is used for testing of - ** the SQLite type logic. - */ - const char *azAff[] = { "blob", "text", "numeric", "integer", "real" }; - char aff; - assert( nFarg==1 ); - aff = sqlite3ExprAffinity(pFarg->a[0].pExpr); - sqlite3VdbeLoadString(v, target, - (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]); - break; - } -#endif - } - return target; -} - - -/* -** Generate code into the current Vdbe to evaluate the given -** expression. Attempt to store the results in register "target". -** Return the register where results are stored. -** -** With this routine, there is no guarantee that results will -** be stored in target. The result might be stored in some other -** register if it is convenient to do so. The calling function -** must check the return code and move the results to the desired -** register. -*/ -SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ - Vdbe *v = pParse->pVdbe; /* The VM under construction */ - int op; /* The opcode being coded */ - int inReg = target; /* Results stored in register inReg */ - int regFree1 = 0; /* If non-zero free this temporary register */ - int regFree2 = 0; /* If non-zero free this temporary register */ - int r1, r2; /* Various register numbers */ - Expr tempX; /* Temporary expression node */ - int p5 = 0; - - assert( target>0 && target<=pParse->nMem ); - assert( v!=0 ); - -expr_code_doover: - if( pExpr==0 ){ - op = TK_NULL; - }else{ - assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); - op = pExpr->op; - } - switch( op ){ - case TK_AGG_COLUMN: { - AggInfo *pAggInfo = pExpr->pAggInfo; - struct AggInfo_col *pCol; - assert( pAggInfo!=0 ); - assert( pExpr->iAgg>=0 && pExpr->iAggnColumn ); - pCol = &pAggInfo->aCol[pExpr->iAgg]; - if( !pAggInfo->directMode ){ - assert( pCol->iMem>0 ); - return pCol->iMem; - }else if( pAggInfo->useSortingIdx ){ - Table *pTab = pCol->pTab; - sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, - pCol->iSorterColumn, target); - if( pCol->iColumn<0 ){ - VdbeComment((v,"%s.rowid",pTab->zName)); - }else{ - VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName)); - if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, target); - } - } - return target; - } - /* Otherwise, fall thru into the TK_COLUMN case */ - /* no break */ deliberate_fall_through - } - case TK_COLUMN: { - int iTab = pExpr->iTable; - int iReg; - if( ExprHasProperty(pExpr, EP_FixedCol) ){ - /* This COLUMN expression is really a constant due to WHERE clause - ** constraints, and that constant is coded by the pExpr->pLeft - ** expresssion. However, make sure the constant has the correct - ** datatype by applying the Affinity of the table column to the - ** constant. - */ - int aff; - iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target); - if( pExpr->y.pTab ){ - aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); - }else{ - aff = pExpr->affExpr; - } - if( aff>SQLITE_AFF_BLOB ){ - static const char zAff[] = "B\000C\000D\000E"; - assert( SQLITE_AFF_BLOB=='A' ); - assert( SQLITE_AFF_TEXT=='B' ); - sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0, - &zAff[(aff-'B')*2], P4_STATIC); - } - return iReg; - } - if( iTab<0 ){ - if( pParse->iSelfTab<0 ){ - /* Other columns in the same row for CHECK constraints or - ** generated columns or for inserting into partial index. - ** The row is unpacked into registers beginning at - ** 0-(pParse->iSelfTab). The rowid (if any) is in a register - ** immediately prior to the first column. - */ - Column *pCol; - Table *pTab = pExpr->y.pTab; - int iSrc; - int iCol = pExpr->iColumn; - assert( pTab!=0 ); - assert( iCol>=XN_ROWID ); - assert( iColnCol ); - if( iCol<0 ){ - return -1-pParse->iSelfTab; - } - pCol = pTab->aCol + iCol; - testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) ); - iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab; -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( pCol->colFlags & COLFLAG_GENERATED ){ - if( pCol->colFlags & COLFLAG_BUSY ){ - sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", - pCol->zName); - return 0; - } - pCol->colFlags |= COLFLAG_BUSY; - if( pCol->colFlags & COLFLAG_NOTAVAIL ){ - sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc); - } - pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL); - return iSrc; - }else -#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ - if( pCol->affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target); - sqlite3VdbeAddOp1(v, OP_RealAffinity, target); - return target; - }else{ - return iSrc; - } - }else{ - /* Coding an expression that is part of an index where column names - ** in the index refer to the table to which the index belongs */ - iTab = pParse->iSelfTab - 1; - } - } - iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab, - pExpr->iColumn, iTab, target, - pExpr->op2); - if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); - } - return iReg; - } - case TK_INTEGER: { - codeInteger(pParse, pExpr, 0, target); - return target; - } - case TK_TRUEFALSE: { - sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target); - return target; - } -#ifndef SQLITE_OMIT_FLOATING_POINT - case TK_FLOAT: { - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - codeReal(v, pExpr->u.zToken, 0, target); - return target; - } -#endif - case TK_STRING: { - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - sqlite3VdbeLoadString(v, target, pExpr->u.zToken); - return target; - } - default: { - /* Make NULL the default case so that if a bug causes an illegal - ** Expr node to be passed into this function, it will be handled - ** sanely and not crash. But keep the assert() to bring the problem - ** to the attention of the developers. */ - assert( op==TK_NULL ); - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - return target; - } -#ifndef SQLITE_OMIT_BLOB_LITERAL - case TK_BLOB: { - int n; - const char *z; - char *zBlob; - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); - assert( pExpr->u.zToken[1]=='\'' ); - z = &pExpr->u.zToken[2]; - n = sqlite3Strlen30(z) - 1; - assert( z[n]=='\'' ); - zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); - sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); - return target; - } -#endif - case TK_VARIABLE: { - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - assert( pExpr->u.zToken!=0 ); - assert( pExpr->u.zToken[0]!=0 ); - sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); - if( pExpr->u.zToken[1]!=0 ){ - const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn); - assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) ); - pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */ - sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC); - } - return target; - } - case TK_REGISTER: { - return pExpr->iTable; - } -#ifndef SQLITE_OMIT_CAST - case TK_CAST: { - /* Expressions of the form: CAST(pLeft AS token) */ - inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); - if( inReg!=target ){ - sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); - inReg = target; - } - sqlite3VdbeAddOp2(v, OP_Cast, target, - sqlite3AffinityType(pExpr->u.zToken, 0)); - return inReg; - } -#endif /* SQLITE_OMIT_CAST */ - case TK_IS: - case TK_ISNOT: - op = (op==TK_IS) ? TK_EQ : TK_NE; - p5 = SQLITE_NULLEQ; - /* fall-through */ - case TK_LT: - case TK_LE: - case TK_GT: - case TK_GE: - case TK_NE: - case TK_EQ: { - Expr *pLeft = pExpr->pLeft; - if( sqlite3ExprIsVector(pLeft) ){ - codeVectorCompare(pParse, pExpr, target, op, p5); - }else{ - r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); - codeCompare(pParse, pLeft, pExpr->pRight, op, - r1, r2, inReg, SQLITE_STOREP2 | p5, - ExprHasProperty(pExpr,EP_Commuted)); - assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); - assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); - assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); - assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); - assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); - assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); - testcase( regFree1==0 ); - testcase( regFree2==0 ); - } - break; - } - case TK_AND: - case TK_OR: - case TK_PLUS: - case TK_STAR: - case TK_MINUS: - case TK_REM: - case TK_BITAND: - case TK_BITOR: - case TK_SLASH: - case TK_LSHIFT: - case TK_RSHIFT: - case TK_CONCAT: { - assert( TK_AND==OP_And ); testcase( op==TK_AND ); - assert( TK_OR==OP_Or ); testcase( op==TK_OR ); - assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); - assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); - assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); - assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND ); - assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR ); - assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH ); - assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); - assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); - assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); - sqlite3VdbeAddOp3(v, op, r2, r1, target); - testcase( regFree1==0 ); - testcase( regFree2==0 ); - break; - } - case TK_UMINUS: { - Expr *pLeft = pExpr->pLeft; - assert( pLeft ); - if( pLeft->op==TK_INTEGER ){ - codeInteger(pParse, pLeft, 1, target); - return target; -#ifndef SQLITE_OMIT_FLOATING_POINT - }else if( pLeft->op==TK_FLOAT ){ - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - codeReal(v, pLeft->u.zToken, 1, target); - return target; -#endif - }else{ - tempX.op = TK_INTEGER; - tempX.flags = EP_IntValue|EP_TokenOnly; - tempX.u.iValue = 0; - ExprClearVVAProperties(&tempX); - r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); - sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); - testcase( regFree2==0 ); - } - break; - } - case TK_BITNOT: - case TK_NOT: { - assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); - assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - testcase( regFree1==0 ); - sqlite3VdbeAddOp2(v, op, r1, inReg); - break; - } - case TK_TRUTH: { - int isTrue; /* IS TRUE or IS NOT TRUE */ - int bNormal; /* IS TRUE or IS FALSE */ - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - testcase( regFree1==0 ); - isTrue = sqlite3ExprTruthValue(pExpr->pRight); - bNormal = pExpr->op2==TK_IS; - testcase( isTrue && bNormal); - testcase( !isTrue && bNormal); - sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal); - break; - } - case TK_ISNULL: - case TK_NOTNULL: { - int addr; - assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); - assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - testcase( regFree1==0 ); - addr = sqlite3VdbeAddOp1(v, op, r1); - VdbeCoverageIf(v, op==TK_ISNULL); - VdbeCoverageIf(v, op==TK_NOTNULL); - sqlite3VdbeAddOp2(v, OP_Integer, 0, target); - sqlite3VdbeJumpHere(v, addr); - break; - } - case TK_AGG_FUNCTION: { - AggInfo *pInfo = pExpr->pAggInfo; - if( pInfo==0 - || NEVER(pExpr->iAgg<0) - || NEVER(pExpr->iAgg>=pInfo->nFunc) - ){ - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); - }else{ - return pInfo->aFunc[pExpr->iAgg].iMem; - } - break; - } - case TK_FUNCTION: { - ExprList *pFarg; /* List of function arguments */ - int nFarg; /* Number of function arguments */ - FuncDef *pDef; /* The function definition object */ - const char *zId; /* The function name */ - u32 constMask = 0; /* Mask of function arguments that are constant */ - int i; /* Loop counter */ - sqlite3 *db = pParse->db; /* The database connection */ - u8 enc = ENC(db); /* The text encoding used by this database */ - CollSeq *pColl = 0; /* A collating sequence */ - -#ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - return pExpr->y.pWin->regResult; - } -#endif - - if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){ - /* SQL functions can be expensive. So try to avoid running them - ** multiple times if we know they always give the same result */ - return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); - } - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - assert( !ExprHasProperty(pExpr, EP_TokenOnly) ); - pFarg = pExpr->x.pList; - nFarg = pFarg ? pFarg->nExpr : 0; - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - zId = pExpr->u.zToken; - pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); -#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION - if( pDef==0 && pParse->explain ){ - pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); - } -#endif - if( pDef==0 || pDef->xFinalize!=0 ){ - sqlite3ErrorMsg(pParse, "unknown function: %s()", zId); - break; - } - if( pDef->funcFlags & SQLITE_FUNC_INLINE ){ - assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 ); - assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 ); - return exprCodeInlineFunction(pParse, pFarg, - SQLITE_PTR_TO_INT(pDef->pUserData), target); - }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){ - sqlite3ExprFunctionUsable(pParse, pExpr, pDef); - } - - for(i=0; ia[i].pExpr) ){ - testcase( i==31 ); - constMask |= MASKBIT32(i); - } - if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ - pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); - } - } - if( pFarg ){ - if( constMask ){ - r1 = pParse->nMem+1; - pParse->nMem += nFarg; - }else{ - r1 = sqlite3GetTempRange(pParse, nFarg); - } - - /* For length() and typeof() functions with a column argument, - ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG - ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data - ** loading. - */ - if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ - u8 exprOp; - assert( nFarg==1 ); - assert( pFarg->a[0].pExpr!=0 ); - exprOp = pFarg->a[0].pExpr->op; - if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ - assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); - assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); - testcase( pDef->funcFlags & OPFLAG_LENGTHARG ); - pFarg->a[0].pExpr->op2 = - pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG); - } - } - - sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, - SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR); - }else{ - r1 = 0; - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - /* Possibly overload the function if the first argument is - ** a virtual table column. - ** - ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the - ** second argument, not the first, as the argument to test to - ** see if it is a column in a virtual table. This is done because - ** the left operand of infix functions (the operand we want to - ** control overloading) ends up as the second argument to the - ** function. The expression "A glob B" is equivalent to - ** "glob(B,A). We want to use the A in "A glob B" to test - ** for function overloading. But we use the B term in "glob(B,A)". - */ - if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){ - pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); - }else if( nFarg>0 ){ - pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); - } -#endif - if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ - if( !pColl ) pColl = db->pDfltColl; - sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); - } -#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC - if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){ - Expr *pArg = pFarg->a[0].pExpr; - if( pArg->op==TK_COLUMN ){ - sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - } - }else -#endif - { - sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg, - pDef, pExpr->op2); - } - if( nFarg ){ - if( constMask==0 ){ - sqlite3ReleaseTempRange(pParse, r1, nFarg); - }else{ - sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1); - } - } - return target; - } -#ifndef SQLITE_OMIT_SUBQUERY - case TK_EXISTS: - case TK_SELECT: { - int nCol; - testcase( op==TK_EXISTS ); - testcase( op==TK_SELECT ); - if( pParse->db->mallocFailed ){ - return 0; - }else if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){ - sqlite3SubselectError(pParse, nCol, 1); - }else{ - return sqlite3CodeSubselect(pParse, pExpr); - } - break; - } - case TK_SELECT_COLUMN: { - int n; - if( pExpr->pLeft->iTable==0 ){ - pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft); - } - assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT ); - if( pExpr->iTable!=0 - && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft)) - ){ - sqlite3ErrorMsg(pParse, "%d columns assigned %d values", - pExpr->iTable, n); - } - return pExpr->pLeft->iTable + pExpr->iColumn; - } - case TK_IN: { - int destIfFalse = sqlite3VdbeMakeLabel(pParse); - int destIfNull = sqlite3VdbeMakeLabel(pParse); - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - sqlite3VdbeResolveLabel(v, destIfFalse); - sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); - sqlite3VdbeResolveLabel(v, destIfNull); - return target; - } -#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: { - exprCodeBetween(pParse, pExpr, target, 0, 0); - return target; - } - case TK_SPAN: - case TK_COLLATE: - case TK_UPLUS: { - pExpr = pExpr->pLeft; - goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */ - } - - case TK_TRIGGER: { - /* If the opcode is TK_TRIGGER, then the expression is a reference - ** to a column in the new.* or old.* pseudo-tables available to - ** trigger programs. In this case Expr.iTable is set to 1 for the - ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn - ** is set to the column of the pseudo-table to read, or to -1 to - ** read the rowid field. - ** - ** The expression is implemented using an OP_Param opcode. The p1 - ** parameter is set to 0 for an old.rowid reference, or to (i+1) - ** to reference another column of the old.* pseudo-table, where - ** i is the index of the column. For a new.rowid reference, p1 is - ** set to (n+1), where n is the number of columns in each pseudo-table. - ** For a reference to any other column in the new.* pseudo-table, p1 - ** is set to (n+2+i), where n and i are as defined previously. For - ** example, if the table on which triggers are being fired is - ** declared as: - ** - ** CREATE TABLE t1(a, b); - ** - ** Then p1 is interpreted as follows: - ** - ** p1==0 -> old.rowid p1==3 -> new.rowid - ** p1==1 -> old.a p1==4 -> new.a - ** p1==2 -> old.b p1==5 -> new.b - */ - Table *pTab = pExpr->y.pTab; - int iCol = pExpr->iColumn; - int p1 = pExpr->iTable * (pTab->nCol+1) + 1 - + sqlite3TableColumnToStorage(pTab, iCol); - - assert( pExpr->iTable==0 || pExpr->iTable==1 ); - assert( iCol>=-1 && iColnCol ); - assert( pTab->iPKey<0 || iCol!=pTab->iPKey ); - assert( p1>=0 && p1<(pTab->nCol*2+2) ); - - sqlite3VdbeAddOp2(v, OP_Param, p1, target); - VdbeComment((v, "r[%d]=%s.%s", target, - (pExpr->iTable ? "new" : "old"), - (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName) - )); - -#ifndef SQLITE_OMIT_FLOATING_POINT - /* If the column has REAL affinity, it may currently be stored as an - ** integer. Use OP_RealAffinity to make sure it is really real. - ** - ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to - ** floating point when extracting it from the record. */ - if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, target); - } -#endif - break; - } - - case TK_VECTOR: { - sqlite3ErrorMsg(pParse, "row value misused"); - break; - } - - /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions - ** that derive from the right-hand table of a LEFT JOIN. The - ** Expr.iTable value is the table number for the right-hand table. - ** The expression is only evaluated if that table is not currently - ** on a LEFT JOIN NULL row. - */ - case TK_IF_NULL_ROW: { - int addrINR; - u8 okConstFactor = pParse->okConstFactor; - addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable); - /* Temporarily disable factoring of constant expressions, since - ** even though expressions may appear to be constant, they are not - ** really constant because they originate from the right-hand side - ** of a LEFT JOIN. */ - pParse->okConstFactor = 0; - inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); - pParse->okConstFactor = okConstFactor; - sqlite3VdbeJumpHere(v, addrINR); - sqlite3VdbeChangeP3(v, addrINR, inReg); - break; - } - - /* - ** Form A: - ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END - ** - ** Form B: - ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END - ** - ** Form A is can be transformed into the equivalent form B as follows: - ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... - ** WHEN x=eN THEN rN ELSE y END - ** - ** X (if it exists) is in pExpr->pLeft. - ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is - ** odd. The Y is also optional. If the number of elements in x.pList - ** is even, then Y is omitted and the "otherwise" result is NULL. - ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. - ** - ** The result of the expression is the Ri for the first matching Ei, - ** or if there is no matching Ei, the ELSE term Y, or if there is - ** no ELSE term, NULL. - */ - case TK_CASE: { - int endLabel; /* GOTO label for end of CASE stmt */ - int nextCase; /* GOTO label for next WHEN clause */ - int nExpr; /* 2x number of WHEN terms */ - int i; /* Loop counter */ - ExprList *pEList; /* List of WHEN terms */ - struct ExprList_item *aListelem; /* Array of WHEN terms */ - Expr opCompare; /* The X==Ei expression */ - Expr *pX; /* The X expression */ - Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ - Expr *pDel = 0; - sqlite3 *db = pParse->db; - - assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); - assert(pExpr->x.pList->nExpr > 0); - pEList = pExpr->x.pList; - aListelem = pEList->a; - nExpr = pEList->nExpr; - endLabel = sqlite3VdbeMakeLabel(pParse); - if( (pX = pExpr->pLeft)!=0 ){ - pDel = sqlite3ExprDup(db, pX, 0); - if( db->mallocFailed ){ - sqlite3ExprDelete(db, pDel); - break; - } - testcase( pX->op==TK_COLUMN ); - exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); - testcase( regFree1==0 ); - memset(&opCompare, 0, sizeof(opCompare)); - opCompare.op = TK_EQ; - opCompare.pLeft = pDel; - pTest = &opCompare; - /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: - ** The value in regFree1 might get SCopy-ed into the file result. - ** So make sure that the regFree1 register is not reused for other - ** purposes and possibly overwritten. */ - regFree1 = 0; - } - for(i=0; iop==TK_COLUMN ); - sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); - testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); - sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); - sqlite3VdbeGoto(v, endLabel); - sqlite3VdbeResolveLabel(v, nextCase); - } - if( (nExpr&1)!=0 ){ - sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - } - sqlite3ExprDelete(db, pDel); - setDoNotMergeFlagOnCopy(v); - sqlite3VdbeResolveLabel(v, endLabel); - break; - } -#ifndef SQLITE_OMIT_TRIGGER - case TK_RAISE: { - assert( pExpr->affExpr==OE_Rollback - || pExpr->affExpr==OE_Abort - || pExpr->affExpr==OE_Fail - || pExpr->affExpr==OE_Ignore - ); - if( !pParse->pTriggerTab && !pParse->nested ){ - sqlite3ErrorMsg(pParse, - "RAISE() may only be used within a trigger-program"); - return 0; - } - if( pExpr->affExpr==OE_Abort ){ - sqlite3MayAbort(pParse); - } - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - if( pExpr->affExpr==OE_Ignore ){ - sqlite3VdbeAddOp4( - v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); - VdbeCoverage(v); - }else{ - sqlite3HaltConstraint(pParse, - pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR, - pExpr->affExpr, pExpr->u.zToken, 0, 0); - } - - break; - } -#endif - } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); - return inReg; -} - -/* -** Generate code that will evaluate expression pExpr just one time -** per prepared statement execution. -** -** If the expression uses functions (that might throw an exception) then -** guard them with an OP_Once opcode to ensure that the code is only executed -** once. If no functions are involved, then factor the code out and put it at -** the end of the prepared statement in the initialization section. -** -** If regDest>=0 then the result is always stored in that register and the -** result is not reusable. If regDest<0 then this routine is free to -** store the value whereever it wants. The register where the expression -** is stored is returned. When regDest<0, two identical expressions might -** code to the same register, if they do not contain function calls and hence -** are factored out into the initialization section at the end of the -** prepared statement. -*/ -SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce( - Parse *pParse, /* Parsing context */ - Expr *pExpr, /* The expression to code when the VDBE initializes */ - int regDest /* Store the value in this register */ -){ - ExprList *p; - assert( ConstFactorOk(pParse) ); - p = pParse->pConstExpr; - if( regDest<0 && p ){ - struct ExprList_item *pItem; - int i; - for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ - if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){ - return pItem->u.iConstExprReg; - } - } - } - pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); - if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){ - Vdbe *v = pParse->pVdbe; - int addr; - assert( v ); - addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - pParse->okConstFactor = 0; - if( !pParse->db->mallocFailed ){ - if( regDest<0 ) regDest = ++pParse->nMem; - sqlite3ExprCode(pParse, pExpr, regDest); - } - pParse->okConstFactor = 1; - sqlite3ExprDelete(pParse->db, pExpr); - sqlite3VdbeJumpHere(v, addr); - }else{ - p = sqlite3ExprListAppend(pParse, p, pExpr); - if( p ){ - struct ExprList_item *pItem = &p->a[p->nExpr-1]; - pItem->reusable = regDest<0; - if( regDest<0 ) regDest = ++pParse->nMem; - pItem->u.iConstExprReg = regDest; - } - pParse->pConstExpr = p; - } - return regDest; -} - -/* -** Generate code to evaluate an expression and store the results -** into a register. Return the register number where the results -** are stored. -** -** If the register is a temporary register that can be deallocated, -** then write its number into *pReg. If the result register is not -** a temporary, then set *pReg to zero. -** -** If pExpr is a constant, then this routine might generate this -** code to fill the register in the initialization section of the -** VDBE program, in order to factor it out of the evaluation loop. -*/ -SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ - int r2; - pExpr = sqlite3ExprSkipCollateAndLikely(pExpr); - if( ConstFactorOk(pParse) - && pExpr->op!=TK_REGISTER - && sqlite3ExprIsConstantNotJoin(pExpr) - ){ - *pReg = 0; - r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); - }else{ - int r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); - if( r2==r1 ){ - *pReg = r1; - }else{ - sqlite3ReleaseTempReg(pParse, r1); - *pReg = 0; - } - } - return r2; -} - -/* -** Generate code that will evaluate expression pExpr and store the -** results in register target. The results are guaranteed to appear -** in register target. -*/ -SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ - int inReg; - - assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) ); - assert( target>0 && target<=pParse->nMem ); - assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); - if( pParse->pVdbe==0 ) return; - inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); - if( inReg!=target ){ - u8 op; - if( ExprHasProperty(pExpr,EP_Subquery) ){ - op = OP_Copy; - }else{ - op = OP_SCopy; - } - sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target); - } -} - -/* -** Make a transient copy of expression pExpr and then code it using -** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() -** except that the input expression is guaranteed to be unchanged. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ - sqlite3 *db = pParse->db; - pExpr = sqlite3ExprDup(db, pExpr, 0); - if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); - sqlite3ExprDelete(db, pExpr); -} - -/* -** Generate code that will evaluate expression pExpr and store the -** results in register target. The results are guaranteed to appear -** in register target. If the expression is constant, then this routine -** might choose to code the expression at initialization time. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ - if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){ - sqlite3ExprCodeRunJustOnce(pParse, pExpr, target); - }else{ - sqlite3ExprCodeCopy(pParse, pExpr, target); - } -} - -/* -** Generate code that pushes the value of every element of the given -** expression list into a sequence of registers beginning at target. -** -** Return the number of elements evaluated. The number returned will -** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF -** is defined. -** -** The SQLITE_ECEL_DUP flag prevents the arguments from being -** filled using OP_SCopy. OP_Copy must be used instead. -** -** The SQLITE_ECEL_FACTOR argument allows constant arguments to be -** factored out into initialization code. -** -** The SQLITE_ECEL_REF flag means that expressions in the list with -** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored -** in registers at srcReg, and so the value can be copied from there. -** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0 -** are simply omitted rather than being copied from srcReg. -*/ -SQLITE_PRIVATE int sqlite3ExprCodeExprList( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* The expression list to be coded */ - int target, /* Where to write results */ - int srcReg, /* Source registers if SQLITE_ECEL_REF */ - u8 flags /* SQLITE_ECEL_* flags */ -){ - struct ExprList_item *pItem; - int i, j, n; - u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy; - Vdbe *v = pParse->pVdbe; - assert( pList!=0 ); - assert( target>0 ); - assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ - n = pList->nExpr; - if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; - for(pItem=pList->a, i=0; ipExpr; -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - if( pItem->bSorterRef ){ - i--; - n--; - }else -#endif - if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){ - if( flags & SQLITE_ECEL_OMITREF ){ - i--; - n--; - }else{ - sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); - } - }else if( (flags & SQLITE_ECEL_FACTOR)!=0 - && sqlite3ExprIsConstantNotJoin(pExpr) - ){ - sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i); - }else{ - int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); - if( inReg!=target+i ){ - VdbeOp *pOp; - if( copyOp==OP_Copy - && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy - && pOp->p1+pOp->p3+1==inReg - && pOp->p2+pOp->p3+1==target+i - && pOp->p5==0 /* The do-not-merge flag must be clear */ - ){ - pOp->p3++; - }else{ - sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); - } - } - } - } - return n; -} - -/* -** Generate code for a BETWEEN operator. -** -** x BETWEEN y AND z -** -** The above is equivalent to -** -** x>=y AND x<=z -** -** Code it as such, taking care to do the common subexpression -** elimination of x. -** -** The xJumpIf parameter determines details: -** -** NULL: Store the boolean result in reg[dest] -** sqlite3ExprIfTrue: Jump to dest if true -** sqlite3ExprIfFalse: Jump to dest if false -** -** The jumpIfNull parameter is ignored if xJumpIf is NULL. -*/ -static void exprCodeBetween( - Parse *pParse, /* Parsing and code generating context */ - Expr *pExpr, /* The BETWEEN expression */ - int dest, /* Jump destination or storage location */ - void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ - int jumpIfNull /* Take the jump if the BETWEEN is NULL */ -){ - Expr exprAnd; /* The AND operator in x>=y AND x<=z */ - Expr compLeft; /* The x>=y term */ - Expr compRight; /* The x<=z term */ - int regFree1 = 0; /* Temporary use register */ - Expr *pDel = 0; - sqlite3 *db = pParse->db; - - memset(&compLeft, 0, sizeof(Expr)); - memset(&compRight, 0, sizeof(Expr)); - memset(&exprAnd, 0, sizeof(Expr)); - - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - pDel = sqlite3ExprDup(db, pExpr->pLeft, 0); - if( db->mallocFailed==0 ){ - exprAnd.op = TK_AND; - exprAnd.pLeft = &compLeft; - exprAnd.pRight = &compRight; - compLeft.op = TK_GE; - compLeft.pLeft = pDel; - compLeft.pRight = pExpr->x.pList->a[0].pExpr; - compRight.op = TK_LE; - compRight.pLeft = pDel; - compRight.pRight = pExpr->x.pList->a[1].pExpr; - exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); - if( xJump ){ - xJump(pParse, &exprAnd, dest, jumpIfNull); - }else{ - /* Mark the expression is being from the ON or USING clause of a join - ** so that the sqlite3ExprCodeTarget() routine will not attempt to move - ** it into the Parse.pConstExpr list. We should use a new bit for this, - ** for clarity, but we are out of bits in the Expr.flags field so we - ** have to reuse the EP_FromJoin bit. Bummer. */ - pDel->flags |= EP_FromJoin; - sqlite3ExprCodeTarget(pParse, &exprAnd, dest); - } - sqlite3ReleaseTempReg(pParse, regFree1); - } - sqlite3ExprDelete(db, pDel); - - /* Ensure adequate test coverage */ - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); - testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); - testcase( xJump==0 ); -} - -/* -** Generate code for a boolean expression such that a jump is made -** to the label "dest" if the expression is true but execution -** continues straight thru if the expression is false. -** -** If the expression evaluates to NULL (neither true nor false), then -** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. -** -** This code depends on the fact that certain token values (ex: TK_EQ) -** are the same as opcode values (ex: OP_Eq) that implement the corresponding -** operation. Special comments in vdbe.c and the mkopcodeh.awk script in -** the make process cause these values to align. Assert()s in the code -** below verify that the numbers are aligned correctly. -*/ -SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ - Vdbe *v = pParse->pVdbe; - int op = 0; - int regFree1 = 0; - int regFree2 = 0; - int r1, r2; - - assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); - if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ - if( NEVER(pExpr==0) ) return; /* No way this can happen */ - assert( !ExprHasVVAProperty(pExpr, EP_Immutable) ); - op = pExpr->op; - switch( op ){ - case TK_AND: - case TK_OR: { - Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); - if( pAlt!=pExpr ){ - sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull); - }else if( op==TK_AND ){ - int d2 = sqlite3VdbeMakeLabel(pParse); - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, - jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); - }else{ - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - } - break; - } - case TK_NOT: { - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); - break; - } - case TK_TRUTH: { - int isNot; /* IS NOT TRUE or IS NOT FALSE */ - int isTrue; /* IS TRUE or IS NOT TRUE */ - testcase( jumpIfNull==0 ); - isNot = pExpr->op2==TK_ISNOT; - isTrue = sqlite3ExprTruthValue(pExpr->pRight); - testcase( isTrue && isNot ); - testcase( !isTrue && isNot ); - if( isTrue ^ isNot ){ - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, - isNot ? SQLITE_JUMPIFNULL : 0); - }else{ - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, - isNot ? SQLITE_JUMPIFNULL : 0); - } - break; - } - case TK_IS: - case TK_ISNOT: - testcase( op==TK_IS ); - testcase( op==TK_ISNOT ); - op = (op==TK_IS) ? TK_EQ : TK_NE; - jumpIfNull = SQLITE_NULLEQ; - /* no break */ deliberate_fall_through - case TK_LT: - case TK_LE: - case TK_GT: - case TK_GE: - case TK_NE: - case TK_EQ: { - if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; - testcase( jumpIfNull==0 ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, - r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted)); - assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); - assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); - assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); - assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); - assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); - VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); - VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); - assert(TK_NE==OP_Ne); testcase(op==OP_Ne); - VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); - VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); - testcase( regFree1==0 ); - testcase( regFree2==0 ); - break; - } - case TK_ISNULL: - case TK_NOTNULL: { - assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); - assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - sqlite3VdbeAddOp2(v, op, r1, dest); - VdbeCoverageIf(v, op==TK_ISNULL); - VdbeCoverageIf(v, op==TK_NOTNULL); - testcase( regFree1==0 ); - break; - } - case TK_BETWEEN: { - testcase( jumpIfNull==0 ); - exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); - break; - } -#ifndef SQLITE_OMIT_SUBQUERY - case TK_IN: { - int destIfFalse = sqlite3VdbeMakeLabel(pParse); - int destIfNull = jumpIfNull ? dest : destIfFalse; - sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); - sqlite3VdbeGoto(v, dest); - sqlite3VdbeResolveLabel(v, destIfFalse); - break; - } -#endif - default: { - default_expr: - if( ExprAlwaysTrue(pExpr) ){ - sqlite3VdbeGoto(v, dest); - }else if( ExprAlwaysFalse(pExpr) ){ - /* No-op */ - }else{ - r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); - sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); - VdbeCoverage(v); - testcase( regFree1==0 ); - testcase( jumpIfNull==0 ); - } - break; - } - } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); -} - -/* -** Generate code for a boolean expression such that a jump is made -** to the label "dest" if the expression is false but execution -** continues straight thru if the expression is true. -** -** If the expression evaluates to NULL (neither true nor false) then -** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull -** is 0. -*/ -SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ - Vdbe *v = pParse->pVdbe; - int op = 0; - int regFree1 = 0; - int regFree2 = 0; - int r1, r2; - - assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); - if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ - if( pExpr==0 ) return; - assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); - - /* The value of pExpr->op and op are related as follows: - ** - ** pExpr->op op - ** --------- ---------- - ** TK_ISNULL OP_NotNull - ** TK_NOTNULL OP_IsNull - ** TK_NE OP_Eq - ** TK_EQ OP_Ne - ** TK_GT OP_Le - ** TK_LE OP_Gt - ** TK_GE OP_Lt - ** TK_LT OP_Ge - ** - ** For other values of pExpr->op, op is undefined and unused. - ** The value of TK_ and OP_ constants are arranged such that we - ** can compute the mapping above using the following expression. - ** Assert()s verify that the computation is correct. - */ - op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); - - /* Verify correct alignment of TK_ and OP_ constants - */ - assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); - assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); - assert( pExpr->op!=TK_NE || op==OP_Eq ); - assert( pExpr->op!=TK_EQ || op==OP_Ne ); - assert( pExpr->op!=TK_LT || op==OP_Ge ); - assert( pExpr->op!=TK_LE || op==OP_Gt ); - assert( pExpr->op!=TK_GT || op==OP_Le ); - assert( pExpr->op!=TK_GE || op==OP_Lt ); - - switch( pExpr->op ){ - case TK_AND: - case TK_OR: { - Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); - if( pAlt!=pExpr ){ - sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull); - }else if( pExpr->op==TK_AND ){ - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - }else{ - int d2 = sqlite3VdbeMakeLabel(pParse); - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, - jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); - } - break; - } - case TK_NOT: { - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); - break; - } - case TK_TRUTH: { - int isNot; /* IS NOT TRUE or IS NOT FALSE */ - int isTrue; /* IS TRUE or IS NOT TRUE */ - testcase( jumpIfNull==0 ); - isNot = pExpr->op2==TK_ISNOT; - isTrue = sqlite3ExprTruthValue(pExpr->pRight); - testcase( isTrue && isNot ); - testcase( !isTrue && isNot ); - if( isTrue ^ isNot ){ - /* IS TRUE and IS NOT FALSE */ - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, - isNot ? 0 : SQLITE_JUMPIFNULL); - - }else{ - /* IS FALSE and IS NOT TRUE */ - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, - isNot ? 0 : SQLITE_JUMPIFNULL); - } - break; - } - case TK_IS: - case TK_ISNOT: - testcase( pExpr->op==TK_IS ); - testcase( pExpr->op==TK_ISNOT ); - op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; - jumpIfNull = SQLITE_NULLEQ; - /* no break */ deliberate_fall_through - case TK_LT: - case TK_LE: - case TK_GT: - case TK_GE: - case TK_NE: - case TK_EQ: { - if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; - testcase( jumpIfNull==0 ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, - r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted)); - assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); - assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); - assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); - assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); - assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); - VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); - VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); - assert(TK_NE==OP_Ne); testcase(op==OP_Ne); - VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); - VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); - testcase( regFree1==0 ); - testcase( regFree2==0 ); - break; - } - case TK_ISNULL: - case TK_NOTNULL: { - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - sqlite3VdbeAddOp2(v, op, r1, dest); - testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); - testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); - testcase( regFree1==0 ); - break; - } - case TK_BETWEEN: { - testcase( jumpIfNull==0 ); - exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); - break; - } -#ifndef SQLITE_OMIT_SUBQUERY - case TK_IN: { - if( jumpIfNull ){ - sqlite3ExprCodeIN(pParse, pExpr, dest, dest); - }else{ - int destIfNull = sqlite3VdbeMakeLabel(pParse); - sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); - sqlite3VdbeResolveLabel(v, destIfNull); - } - break; - } -#endif - default: { - default_expr: - if( ExprAlwaysFalse(pExpr) ){ - sqlite3VdbeGoto(v, dest); - }else if( ExprAlwaysTrue(pExpr) ){ - /* no-op */ - }else{ - r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); - sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); - VdbeCoverage(v); - testcase( regFree1==0 ); - testcase( jumpIfNull==0 ); - } - break; - } - } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); -} - -/* -** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before -** code generation, and that copy is deleted after code generation. This -** ensures that the original pExpr is unchanged. -*/ -SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ - sqlite3 *db = pParse->db; - Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); - if( db->mallocFailed==0 ){ - sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); - } - sqlite3ExprDelete(db, pCopy); -} - -/* -** Expression pVar is guaranteed to be an SQL variable. pExpr may be any -** type of expression. -** -** If pExpr is a simple SQL value - an integer, real, string, blob -** or NULL value - then the VDBE currently being prepared is configured -** to re-prepare each time a new value is bound to variable pVar. -** -** Additionally, if pExpr is a simple SQL value and the value is the -** same as that currently bound to variable pVar, non-zero is returned. -** Otherwise, if the values are not the same or if pExpr is not a simple -** SQL value, zero is returned. -*/ -static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){ - int res = 0; - int iVar; - sqlite3_value *pL, *pR = 0; - - sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR); - if( pR ){ - iVar = pVar->iColumn; - sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); - pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB); - if( pL ){ - if( sqlite3_value_type(pL)==SQLITE_TEXT ){ - sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */ - } - res = 0==sqlite3MemCompare(pL, pR, 0); - } - sqlite3ValueFree(pR); - sqlite3ValueFree(pL); - } - - return res; -} - -/* -** Do a deep comparison of two expression trees. Return 0 if the two -** expressions are completely identical. Return 1 if they differ only -** by a COLLATE operator at the top level. Return 2 if there are differences -** other than the top-level COLLATE operator. -** -** If any subelement of pB has Expr.iTable==(-1) then it is allowed -** to compare equal to an equivalent element in pA with Expr.iTable==iTab. -** -** The pA side might be using TK_REGISTER. If that is the case and pB is -** not using TK_REGISTER but is otherwise equivalent, then still return 0. -** -** Sometimes this routine will return 2 even if the two expressions -** really are equivalent. If we cannot prove that the expressions are -** identical, we return 2 just to be safe. So if this routine -** returns 2, then you do not really know for certain if the two -** expressions are the same. But if you get a 0 or 1 return, then you -** can be sure the expressions are the same. In the places where -** this routine is used, it does not hurt to get an extra 2 - that -** just might result in some slightly slower code. But returning -** an incorrect 0 or 1 could lead to a malfunction. -** -** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in -** pParse->pReprepare can be matched against literals in pB. The -** pParse->pVdbe->expmask bitmask is updated for each variable referenced. -** If pParse is NULL (the normal case) then any TK_VARIABLE term in -** Argument pParse should normally be NULL. If it is not NULL and pA or -** pB causes a return value of 2. -*/ -SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){ - u32 combinedFlags; - if( pA==0 || pB==0 ){ - return pB==pA ? 0 : 2; - } - if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){ - return 0; - } - combinedFlags = pA->flags | pB->flags; - if( combinedFlags & EP_IntValue ){ - if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ - return 0; - } - return 2; - } - if( pA->op!=pB->op || pA->op==TK_RAISE ){ - if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){ - return 1; - } - if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){ - return 1; - } - return 2; - } - if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){ - if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){ - if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; -#ifndef SQLITE_OMIT_WINDOWFUNC - assert( pA->op==pB->op ); - if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){ - return 2; - } - if( ExprHasProperty(pA,EP_WinFunc) ){ - if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){ - return 2; - } - } -#endif - }else if( pA->op==TK_NULL ){ - return 0; - }else if( pA->op==TK_COLLATE ){ - if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; - }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ - return 2; - } - } - if( (pA->flags & (EP_Distinct|EP_Commuted)) - != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2; - if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ - if( combinedFlags & EP_xIsSelect ) return 2; - if( (combinedFlags & EP_FixedCol)==0 - && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2; - if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2; - if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; - if( pA->op!=TK_STRING - && pA->op!=TK_TRUEFALSE - && ALWAYS((combinedFlags & EP_Reduced)==0) - ){ - if( pA->iColumn!=pB->iColumn ) return 2; - if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2; - if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){ - return 2; - } - } - } - return 0; -} - -/* -** Compare two ExprList objects. Return 0 if they are identical, 1 -** if they are certainly different, or 2 if it is not possible to -** determine if they are identical or not. -** -** If any subelement of pB has Expr.iTable==(-1) then it is allowed -** to compare equal to an equivalent element in pA with Expr.iTable==iTab. -** -** This routine might return non-zero for equivalent ExprLists. The -** only consequence will be disabled optimizations. But this routine -** must never return 0 if the two ExprList objects are different, or -** a malfunction will result. -** -** Two NULL pointers are considered to be the same. But a NULL pointer -** always differs from a non-NULL pointer. -*/ -SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ - int i; - if( pA==0 && pB==0 ) return 0; - if( pA==0 || pB==0 ) return 1; - if( pA->nExpr!=pB->nExpr ) return 1; - for(i=0; inExpr; i++){ - int res; - Expr *pExprA = pA->a[i].pExpr; - Expr *pExprB = pB->a[i].pExpr; - if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1; - if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res; - } - return 0; -} - -/* -** Like sqlite3ExprCompare() except COLLATE operators at the top-level -** are ignored. -*/ -SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){ - return sqlite3ExprCompare(0, - sqlite3ExprSkipCollateAndLikely(pA), - sqlite3ExprSkipCollateAndLikely(pB), - iTab); -} - -/* -** Return non-zero if Expr p can only be true if pNN is not NULL. -** -** Or if seenNot is true, return non-zero if Expr p can only be -** non-NULL if pNN is not NULL -*/ -static int exprImpliesNotNull( - Parse *pParse, /* Parsing context */ - Expr *p, /* The expression to be checked */ - Expr *pNN, /* The expression that is NOT NULL */ - int iTab, /* Table being evaluated */ - int seenNot /* Return true only if p can be any non-NULL value */ -){ - assert( p ); - assert( pNN ); - if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){ - return pNN->op!=TK_NULL; - } - switch( p->op ){ - case TK_IN: { - if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0; - assert( ExprHasProperty(p,EP_xIsSelect) - || (p->x.pList!=0 && p->x.pList->nExpr>0) ); - return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); - } - case TK_BETWEEN: { - ExprList *pList = p->x.pList; - assert( pList!=0 ); - assert( pList->nExpr==2 ); - if( seenNot ) return 0; - if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1) - || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1) - ){ - return 1; - } - return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); - } - case TK_EQ: - case TK_NE: - case TK_LT: - case TK_LE: - case TK_GT: - case TK_GE: - case TK_PLUS: - case TK_MINUS: - case TK_BITOR: - case TK_LSHIFT: - case TK_RSHIFT: - case TK_CONCAT: - seenNot = 1; - /* no break */ deliberate_fall_through - case TK_STAR: - case TK_REM: - case TK_BITAND: - case TK_SLASH: { - if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1; - /* no break */ deliberate_fall_through - } - case TK_SPAN: - case TK_COLLATE: - case TK_UPLUS: - case TK_UMINUS: { - return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); - } - case TK_TRUTH: { - if( seenNot ) return 0; - if( p->op2!=TK_IS ) return 0; - return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); - } - case TK_BITNOT: - case TK_NOT: { - return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); - } - } - return 0; -} - -/* -** Return true if we can prove the pE2 will always be true if pE1 is -** true. Return false if we cannot complete the proof or if pE2 might -** be false. Examples: -** -** pE1: x==5 pE2: x==5 Result: true -** pE1: x>0 pE2: x==5 Result: false -** pE1: x=21 pE2: x=21 OR y=43 Result: true -** pE1: x!=123 pE2: x IS NOT NULL Result: true -** pE1: x!=?1 pE2: x IS NOT NULL Result: true -** pE1: x IS NULL pE2: x IS NOT NULL Result: false -** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false -** -** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has -** Expr.iTable<0 then assume a table number given by iTab. -** -** If pParse is not NULL, then the values of bound variables in pE1 are -** compared against literal values in pE2 and pParse->pVdbe->expmask is -** modified to record which bound variables are referenced. If pParse -** is NULL, then false will be returned if pE1 contains any bound variables. -** -** When in doubt, return false. Returning true might give a performance -** improvement. Returning false might cause a performance reduction, but -** it will always give the correct answer and is hence always safe. -*/ -SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){ - if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){ - return 1; - } - if( pE2->op==TK_OR - && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab) - || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) ) - ){ - return 1; - } - if( pE2->op==TK_NOTNULL - && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0) - ){ - return 1; - } - return 0; -} - -/* -** This is the Expr node callback for sqlite3ExprImpliesNonNullRow(). -** If the expression node requires that the table at pWalker->iCur -** have one or more non-NULL column, then set pWalker->eCode to 1 and abort. -** -** This routine controls an optimization. False positives (setting -** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives -** (never setting pWalker->eCode) is a harmless missed optimization. -*/ -static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){ - testcase( pExpr->op==TK_AGG_COLUMN ); - testcase( pExpr->op==TK_AGG_FUNCTION ); - if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune; - switch( pExpr->op ){ - case TK_ISNOT: - case TK_ISNULL: - case TK_NOTNULL: - case TK_IS: - case TK_OR: - case TK_VECTOR: - case TK_CASE: - case TK_IN: - case TK_FUNCTION: - case TK_TRUTH: - testcase( pExpr->op==TK_ISNOT ); - testcase( pExpr->op==TK_ISNULL ); - testcase( pExpr->op==TK_NOTNULL ); - testcase( pExpr->op==TK_IS ); - testcase( pExpr->op==TK_OR ); - testcase( pExpr->op==TK_VECTOR ); - testcase( pExpr->op==TK_CASE ); - testcase( pExpr->op==TK_IN ); - testcase( pExpr->op==TK_FUNCTION ); - testcase( pExpr->op==TK_TRUTH ); - return WRC_Prune; - case TK_COLUMN: - if( pWalker->u.iCur==pExpr->iTable ){ - pWalker->eCode = 1; - return WRC_Abort; - } - return WRC_Prune; - - case TK_AND: - if( pWalker->eCode==0 ){ - sqlite3WalkExpr(pWalker, pExpr->pLeft); - if( pWalker->eCode ){ - pWalker->eCode = 0; - sqlite3WalkExpr(pWalker, pExpr->pRight); - } - } - return WRC_Prune; - - case TK_BETWEEN: - if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){ - assert( pWalker->eCode ); - return WRC_Abort; - } - return WRC_Prune; - - /* Virtual tables are allowed to use constraints like x=NULL. So - ** a term of the form x=y does not prove that y is not null if x - ** is the column of a virtual table */ - case TK_EQ: - case TK_NE: - case TK_LT: - case TK_LE: - case TK_GT: - case TK_GE: { - Expr *pLeft = pExpr->pLeft; - Expr *pRight = pExpr->pRight; - testcase( pExpr->op==TK_EQ ); - testcase( pExpr->op==TK_NE ); - testcase( pExpr->op==TK_LT ); - testcase( pExpr->op==TK_LE ); - testcase( pExpr->op==TK_GT ); - testcase( pExpr->op==TK_GE ); - /* The y.pTab=0 assignment in wherecode.c always happens after the - ** impliesNotNullRow() test */ - if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0) - && IsVirtual(pLeft->y.pTab)) - || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0) - && IsVirtual(pRight->y.pTab)) - ){ - return WRC_Prune; - } - /* no break */ deliberate_fall_through - } - default: - return WRC_Continue; - } -} - -/* -** Return true (non-zero) if expression p can only be true if at least -** one column of table iTab is non-null. In other words, return true -** if expression p will always be NULL or false if every column of iTab -** is NULL. -** -** False negatives are acceptable. In other words, it is ok to return -** zero even if expression p will never be true of every column of iTab -** is NULL. A false negative is merely a missed optimization opportunity. -** -** False positives are not allowed, however. A false positive may result -** in an incorrect answer. -** -** Terms of p that are marked with EP_FromJoin (and hence that come from -** the ON or USING clauses of LEFT JOINS) are excluded from the analysis. -** -** This routine is used to check if a LEFT JOIN can be converted into -** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE -** clause requires that some column of the right table of the LEFT JOIN -** be non-NULL, then the LEFT JOIN can be safely converted into an -** ordinary join. -*/ -SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){ - Walker w; - p = sqlite3ExprSkipCollateAndLikely(p); - if( p==0 ) return 0; - if( p->op==TK_NOTNULL ){ - p = p->pLeft; - }else{ - while( p->op==TK_AND ){ - if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1; - p = p->pRight; - } - } - w.xExprCallback = impliesNotNullRow; - w.xSelectCallback = 0; - w.xSelectCallback2 = 0; - w.eCode = 0; - w.u.iCur = iTab; - sqlite3WalkExpr(&w, p); - return w.eCode; -} - -/* -** An instance of the following structure is used by the tree walker -** to determine if an expression can be evaluated by reference to the -** index only, without having to do a search for the corresponding -** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur -** is the cursor for the table. -*/ -struct IdxCover { - Index *pIdx; /* The index to be tested for coverage */ - int iCur; /* Cursor number for the table corresponding to the index */ -}; - -/* -** Check to see if there are references to columns in table -** pWalker->u.pIdxCover->iCur can be satisfied using the index -** pWalker->u.pIdxCover->pIdx. -*/ -static int exprIdxCover(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_COLUMN - && pExpr->iTable==pWalker->u.pIdxCover->iCur - && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 - ){ - pWalker->eCode = 1; - return WRC_Abort; - } - return WRC_Continue; -} - -/* -** Determine if an index pIdx on table with cursor iCur contains will -** the expression pExpr. Return true if the index does cover the -** expression and false if the pExpr expression references table columns -** that are not found in the index pIdx. -** -** An index covering an expression means that the expression can be -** evaluated using only the index and without having to lookup the -** corresponding table entry. -*/ -SQLITE_PRIVATE int sqlite3ExprCoveredByIndex( - Expr *pExpr, /* The index to be tested */ - int iCur, /* The cursor number for the corresponding table */ - Index *pIdx /* The index that might be used for coverage */ -){ - Walker w; - struct IdxCover xcov; - memset(&w, 0, sizeof(w)); - xcov.iCur = iCur; - xcov.pIdx = pIdx; - w.xExprCallback = exprIdxCover; - w.u.pIdxCover = &xcov; - sqlite3WalkExpr(&w, pExpr); - return !w.eCode; -} - - -/* -** An instance of the following structure is used by the tree walker -** to count references to table columns in the arguments of an -** aggregate function, in order to implement the -** sqlite3FunctionThisSrc() routine. -*/ -struct SrcCount { - SrcList *pSrc; /* One particular FROM clause in a nested query */ - int iSrcInner; /* Smallest cursor number in this context */ - int nThis; /* Number of references to columns in pSrcList */ - int nOther; /* Number of references to columns in other FROM clauses */ -}; - -/* -** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first -** SELECT with a FROM clause encountered during this iteration, set -** SrcCount.iSrcInner to the cursor number of the leftmost object in -** the FROM cause. -*/ -static int selectSrcCount(Walker *pWalker, Select *pSel){ - struct SrcCount *p = pWalker->u.pSrcCount; - if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){ - pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor; - } - return WRC_Continue; -} - -/* -** Count the number of references to columns. -*/ -static int exprSrcCount(Walker *pWalker, Expr *pExpr){ - /* There was once a NEVER() on the second term on the grounds that - ** sqlite3FunctionUsesThisSrc() was always called before - ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet - ** been converted into TK_AGG_COLUMN. But this is no longer true due - ** to window functions - sqlite3WindowRewrite() may now indirectly call - ** FunctionUsesThisSrc() when creating a new sub-select. */ - if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){ - int i; - struct SrcCount *p = pWalker->u.pSrcCount; - SrcList *pSrc = p->pSrc; - int nSrc = pSrc ? pSrc->nSrc : 0; - for(i=0; iiTable==pSrc->a[i].iCursor ) break; - } - if( inThis++; - }else if( pExpr->iTableiSrcInner ){ - /* In a well-formed parse tree (no name resolution errors), - ** TK_COLUMN nodes with smaller Expr.iTable values are in an - ** outer context. Those are the only ones to count as "other" */ - p->nOther++; - } - } - return WRC_Continue; -} - -/* -** Determine if any of the arguments to the pExpr Function reference -** pSrcList. Return true if they do. Also return true if the function -** has no arguments or has only constant arguments. Return false if pExpr -** references columns but not columns of tables found in pSrcList. -*/ -SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ - Walker w; - struct SrcCount cnt; - assert( pExpr->op==TK_AGG_FUNCTION ); - memset(&w, 0, sizeof(w)); - w.xExprCallback = exprSrcCount; - w.xSelectCallback = selectSrcCount; - w.u.pSrcCount = &cnt; - cnt.pSrc = pSrcList; - cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF; - cnt.nThis = 0; - cnt.nOther = 0; - sqlite3WalkExprList(&w, pExpr->x.pList); -#ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter); - } -#endif - return cnt.nThis>0 || cnt.nOther==0; -} - -/* -** This is a Walker expression node callback. -** -** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo -** object that is referenced does not refer directly to the Expr. If -** it does, make a copy. This is done because the pExpr argument is -** subject to change. -** -** The copy is stored on pParse->pConstExpr with a register number of 0. -** This will cause the expression to be deleted automatically when the -** Parse object is destroyed, but the zero register number means that it -** will not generate any code in the preamble. -*/ -static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){ - if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced)) - && pExpr->pAggInfo!=0 - ){ - AggInfo *pAggInfo = pExpr->pAggInfo; - int iAgg = pExpr->iAgg; - Parse *pParse = pWalker->pParse; - sqlite3 *db = pParse->db; - assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_AGG_FUNCTION ); - if( pExpr->op==TK_AGG_COLUMN ){ - assert( iAgg>=0 && iAggnColumn ); - if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){ - pExpr = sqlite3ExprDup(db, pExpr, 0); - if( pExpr ){ - pAggInfo->aCol[iAgg].pCExpr = pExpr; - pParse->pConstExpr = - sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr); - } - } - }else{ - assert( iAgg>=0 && iAggnFunc ); - if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){ - pExpr = sqlite3ExprDup(db, pExpr, 0); - if( pExpr ){ - pAggInfo->aFunc[iAgg].pFExpr = pExpr; - pParse->pConstExpr = - sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr); - } - } - } - } - return WRC_Continue; -} - -/* -** Initialize a Walker object so that will persist AggInfo entries referenced -** by the tree that is walked. -*/ -SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){ - memset(pWalker, 0, sizeof(*pWalker)); - pWalker->pParse = pParse; - pWalker->xExprCallback = agginfoPersistExprCb; - pWalker->xSelectCallback = sqlite3SelectWalkNoop; -} - -/* -** Add a new element to the pAggInfo->aCol[] array. Return the index of -** the new element. Return a negative number if malloc fails. -*/ -static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ - int i; - pInfo->aCol = sqlite3ArrayAllocate( - db, - pInfo->aCol, - sizeof(pInfo->aCol[0]), - &pInfo->nColumn, - &i - ); - return i; -} - -/* -** Add a new element to the pAggInfo->aFunc[] array. Return the index of -** the new element. Return a negative number if malloc fails. -*/ -static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ - int i; - pInfo->aFunc = sqlite3ArrayAllocate( - db, - pInfo->aFunc, - sizeof(pInfo->aFunc[0]), - &pInfo->nFunc, - &i - ); - return i; -} - -/* -** This is the xExprCallback for a tree walker. It is used to -** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates -** for additional information. -*/ -static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ - int i; - NameContext *pNC = pWalker->u.pNC; - Parse *pParse = pNC->pParse; - SrcList *pSrcList = pNC->pSrcList; - AggInfo *pAggInfo = pNC->uNC.pAggInfo; - - assert( pNC->ncFlags & NC_UAggInfo ); - switch( pExpr->op ){ - case TK_AGG_COLUMN: - case TK_COLUMN: { - testcase( pExpr->op==TK_AGG_COLUMN ); - testcase( pExpr->op==TK_COLUMN ); - /* Check to see if the column is in one of the tables in the FROM - ** clause of the aggregate query */ - if( ALWAYS(pSrcList!=0) ){ - struct SrcList_item *pItem = pSrcList->a; - for(i=0; inSrc; i++, pItem++){ - struct AggInfo_col *pCol; - assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); - if( pExpr->iTable==pItem->iCursor ){ - /* If we reach this point, it means that pExpr refers to a table - ** that is in the FROM clause of the aggregate query. - ** - ** Make an entry for the column in pAggInfo->aCol[] if there - ** is not an entry there already. - */ - int k; - pCol = pAggInfo->aCol; - for(k=0; knColumn; k++, pCol++){ - if( pCol->iTable==pExpr->iTable && - pCol->iColumn==pExpr->iColumn ){ - break; - } - } - if( (k>=pAggInfo->nColumn) - && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 - ){ - pCol = &pAggInfo->aCol[k]; - pCol->pTab = pExpr->y.pTab; - pCol->iTable = pExpr->iTable; - pCol->iColumn = pExpr->iColumn; - pCol->iMem = ++pParse->nMem; - pCol->iSorterColumn = -1; - pCol->pCExpr = pExpr; - if( pAggInfo->pGroupBy ){ - int j, n; - ExprList *pGB = pAggInfo->pGroupBy; - struct ExprList_item *pTerm = pGB->a; - n = pGB->nExpr; - for(j=0; jpExpr; - if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && - pE->iColumn==pExpr->iColumn ){ - pCol->iSorterColumn = j; - break; - } - } - } - if( pCol->iSorterColumn<0 ){ - pCol->iSorterColumn = pAggInfo->nSortingColumn++; - } - } - /* There is now an entry for pExpr in pAggInfo->aCol[] (either - ** because it was there before or because we just created it). - ** Convert the pExpr to be a TK_AGG_COLUMN referring to that - ** pAggInfo->aCol[] entry. - */ - ExprSetVVAProperty(pExpr, EP_NoReduce); - pExpr->pAggInfo = pAggInfo; - pExpr->op = TK_AGG_COLUMN; - pExpr->iAgg = (i16)k; - break; - } /* endif pExpr->iTable==pItem->iCursor */ - } /* end loop over pSrcList */ - } - return WRC_Prune; - } - case TK_AGG_FUNCTION: { - if( (pNC->ncFlags & NC_InAggFunc)==0 - && pWalker->walkerDepth==pExpr->op2 - ){ - /* Check to see if pExpr is a duplicate of another aggregate - ** function that is already in the pAggInfo structure - */ - struct AggInfo_func *pItem = pAggInfo->aFunc; - for(i=0; inFunc; i++, pItem++){ - if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){ - break; - } - } - if( i>=pAggInfo->nFunc ){ - /* pExpr is original. Make a new entry in pAggInfo->aFunc[] - */ - u8 enc = ENC(pParse->db); - i = addAggInfoFunc(pParse->db, pAggInfo); - if( i>=0 ){ - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - pItem = &pAggInfo->aFunc[i]; - pItem->pFExpr = pExpr; - pItem->iMem = ++pParse->nMem; - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - pItem->pFunc = sqlite3FindFunction(pParse->db, - pExpr->u.zToken, - pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); - if( pExpr->flags & EP_Distinct ){ - pItem->iDistinct = pParse->nTab++; - }else{ - pItem->iDistinct = -1; - } - } - } - /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry - */ - assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); - ExprSetVVAProperty(pExpr, EP_NoReduce); - pExpr->iAgg = (i16)i; - pExpr->pAggInfo = pAggInfo; - return WRC_Prune; - }else{ - return WRC_Continue; - } - } - } - return WRC_Continue; -} - -/* -** Analyze the pExpr expression looking for aggregate functions and -** for variables that need to be added to AggInfo object that pNC->pAggInfo -** points to. Additional entries are made on the AggInfo object as -** necessary. -** -** This routine should only be called after the expression has been -** analyzed by sqlite3ResolveExprNames(). -*/ -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ - Walker w; - w.xExprCallback = analyzeAggregate; - w.xSelectCallback = sqlite3WalkerDepthIncrease; - w.xSelectCallback2 = sqlite3WalkerDepthDecrease; - w.walkerDepth = 0; - w.u.pNC = pNC; - w.pParse = 0; - assert( pNC->pSrcList!=0 ); - sqlite3WalkExpr(&w, pExpr); -} - -/* -** Call sqlite3ExprAnalyzeAggregates() for every expression in an -** expression list. Return the number of errors. -** -** If an error is found, the analysis is cut short. -*/ -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ - struct ExprList_item *pItem; - int i; - if( pList ){ - for(pItem=pList->a, i=0; inExpr; i++, pItem++){ - sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); - } - } -} - -/* -** Allocate a single new register for use to hold some intermediate result. -*/ -SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ - if( pParse->nTempReg==0 ){ - return ++pParse->nMem; - } - return pParse->aTempReg[--pParse->nTempReg]; -} - -/* -** Deallocate a register, making available for reuse for some other -** purpose. -*/ -SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ - if( iReg ){ - sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0); - if( pParse->nTempRegaTempReg) ){ - pParse->aTempReg[pParse->nTempReg++] = iReg; - } - } -} - -/* -** Allocate or deallocate a block of nReg consecutive registers. -*/ -SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ - int i, n; - if( nReg==1 ) return sqlite3GetTempReg(pParse); - i = pParse->iRangeReg; - n = pParse->nRangeReg; - if( nReg<=n ){ - pParse->iRangeReg += nReg; - pParse->nRangeReg -= nReg; - }else{ - i = pParse->nMem+1; - pParse->nMem += nReg; - } - return i; -} -SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ - if( nReg==1 ){ - sqlite3ReleaseTempReg(pParse, iReg); - return; - } - sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0); - if( nReg>pParse->nRangeReg ){ - pParse->nRangeReg = nReg; - pParse->iRangeReg = iReg; - } -} - -/* -** Mark all temporary registers as being unavailable for reuse. -** -** Always invoke this procedure after coding a subroutine or co-routine -** that might be invoked from other parts of the code, to ensure that -** the sub/co-routine does not use registers in common with the code that -** invokes the sub/co-routine. -*/ -SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){ - pParse->nTempReg = 0; - pParse->nRangeReg = 0; -} - -/* -** Validate that no temporary register falls within the range of -** iFirst..iLast, inclusive. This routine is only call from within assert() -** statements. -*/ -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ - int i; - if( pParse->nRangeReg>0 - && pParse->iRangeReg+pParse->nRangeReg > iFirst - && pParse->iRangeReg <= iLast - ){ - return 0; - } - for(i=0; inTempReg; i++){ - if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){ - return 0; - } - } - return 1; -} -#endif /* SQLITE_DEBUG */ - -/************** End of expr.c ************************************************/ -/************** Begin file alter.c *******************************************/ -/* -** 2005 February 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains C code routines that used to generate VDBE code -** that implements the ALTER TABLE command. -*/ -/* #include "sqliteInt.h" */ - -/* -** The code in this file only exists if we are not omitting the -** ALTER TABLE logic from the build. -*/ -#ifndef SQLITE_OMIT_ALTERTABLE - -/* -** Parameter zName is the name of a table that is about to be altered -** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). -** If the table is a system table, this function leaves an error message -** in pParse->zErr (system tables may not be altered) and returns non-zero. -** -** Or, if zName is not a system table, zero is returned. -*/ -static int isAlterableTable(Parse *pParse, Table *pTab){ - if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) -#ifndef SQLITE_OMIT_VIRTUALTABLE - || ( (pTab->tabFlags & TF_Shadow)!=0 - && sqlite3ReadOnlyShadowTables(pParse->db) - ) -#endif - ){ - sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName); - return 1; - } - return 0; -} - -/* -** Generate code to verify that the schemas of database zDb and, if -** bTemp is not true, database "temp", can still be parsed. This is -** called at the end of the generation of an ALTER TABLE ... RENAME ... -** statement to ensure that the operation has not rendered any schema -** objects unusable. -*/ -static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){ - sqlite3NestedParse(pParse, - "SELECT 1 " - "FROM \"%w\"." DFLT_SCHEMA_TABLE " " - "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" - " AND sql NOT LIKE 'create virtual%%'" - " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ", - zDb, - zDb, bTemp - ); - - if( bTemp==0 ){ - sqlite3NestedParse(pParse, - "SELECT 1 " - "FROM temp." DFLT_SCHEMA_TABLE " " - "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" - " AND sql NOT LIKE 'create virtual%%'" - " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ", - zDb - ); - } -} - -/* -** Generate code to reload the schema for database iDb. And, if iDb!=1, for -** the temp database as well. -*/ -static void renameReloadSchema(Parse *pParse, int iDb){ - Vdbe *v = pParse->pVdbe; - if( v ){ - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0); - if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0); - } -} - -/* -** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" -** command. -*/ -SQLITE_PRIVATE void sqlite3AlterRenameTable( - Parse *pParse, /* Parser context. */ - SrcList *pSrc, /* The table to rename. */ - Token *pName /* The new table name. */ -){ - int iDb; /* Database that contains the table */ - char *zDb; /* Name of database iDb */ - Table *pTab; /* Table being renamed */ - char *zName = 0; /* NULL-terminated version of pName */ - sqlite3 *db = pParse->db; /* Database connection */ - int nTabName; /* Number of UTF-8 characters in zTabName */ - const char *zTabName; /* Original name of the table */ - Vdbe *v; - VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ - u32 savedDbFlags; /* Saved value of db->mDbFlags */ - - savedDbFlags = db->mDbFlags; - if( NEVER(db->mallocFailed) ) goto exit_rename_table; - assert( pSrc->nSrc==1 ); - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - - pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); - if( !pTab ) goto exit_rename_table; - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - zDb = db->aDb[iDb].zDbSName; - db->mDbFlags |= DBFLAG_PreferBuiltin; - - /* Get a NULL terminated version of the new table name. */ - zName = sqlite3NameFromToken(db, pName); - if( !zName ) goto exit_rename_table; - - /* Check that a table or index named 'zName' does not already exist - ** in database iDb. If so, this is an error. - */ - if( sqlite3FindTable(db, zName, zDb) - || sqlite3FindIndex(db, zName, zDb) - || sqlite3IsShadowTableOf(db, pTab, zName) - ){ - sqlite3ErrorMsg(pParse, - "there is already another table or index with this name: %s", zName); - goto exit_rename_table; - } - - /* Make sure it is not a system table being altered, or a reserved name - ** that the table is being renamed to. - */ - if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ - goto exit_rename_table; - } - if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){ - goto exit_rename_table; - } - -#ifndef SQLITE_OMIT_VIEW - if( pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); - goto exit_rename_table; - } -#endif - -#ifndef SQLITE_OMIT_AUTHORIZATION - /* Invoke the authorization callback. */ - if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ - goto exit_rename_table; - } -#endif - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ - goto exit_rename_table; - } - if( IsVirtual(pTab) ){ - pVTab = sqlite3GetVTable(db, pTab); - if( pVTab->pVtab->pModule->xRename==0 ){ - pVTab = 0; - } - } -#endif - - /* Begin a transaction for database iDb. Then modify the schema cookie - ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(), - ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the - ** nested SQL may raise an exception. */ - v = sqlite3GetVdbe(pParse); - if( v==0 ){ - goto exit_rename_table; - } - sqlite3MayAbort(pParse); - - /* figure out how many UTF-8 characters are in zName */ - zTabName = pTab->zName; - nTabName = sqlite3Utf8CharLen(zTabName, -1); - - /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in - ** the schema to use the new table name. */ - sqlite3NestedParse(pParse, - "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET " - "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) " - "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)" - "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" - , zDb, zDb, zTabName, zName, (iDb==1), zTabName - ); - - /* Update the tbl_name and name columns of the sqlite_schema table - ** as required. */ - sqlite3NestedParse(pParse, - "UPDATE %Q." DFLT_SCHEMA_TABLE " SET " - "tbl_name = %Q, " - "name = CASE " - "WHEN type='table' THEN %Q " - "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' " - " AND type='index' THEN " - "'sqlite_autoindex_' || %Q || substr(name,%d+18) " - "ELSE name END " - "WHERE tbl_name=%Q COLLATE nocase AND " - "(type='table' OR type='index' OR type='trigger');", - zDb, - zName, zName, zName, - nTabName, zTabName - ); - -#ifndef SQLITE_OMIT_AUTOINCREMENT - /* If the sqlite_sequence table exists in this database, then update - ** it with the new table name. - */ - if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ - sqlite3NestedParse(pParse, - "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", - zDb, zName, pTab->zName); - } -#endif - - /* If the table being renamed is not itself part of the temp database, - ** edit view and trigger definitions within the temp database - ** as required. */ - if( iDb!=1 ){ - sqlite3NestedParse(pParse, - "UPDATE sqlite_temp_schema SET " - "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), " - "tbl_name = " - "CASE WHEN tbl_name=%Q COLLATE nocase AND " - " sqlite_rename_test(%Q, sql, type, name, 1) " - "THEN %Q ELSE tbl_name END " - "WHERE type IN ('view', 'trigger')" - , zDb, zTabName, zName, zTabName, zDb, zName); - } - - /* If this is a virtual table, invoke the xRename() function if - ** one is defined. The xRename() callback will modify the names - ** of any resources used by the v-table implementation (including other - ** SQLite tables) that are identified by the name of the virtual table. - */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( pVTab ){ - int i = ++pParse->nMem; - sqlite3VdbeLoadString(v, i, zName); - sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); - } -#endif - - renameReloadSchema(pParse, iDb); - renameTestSchema(pParse, zDb, iDb==1); - -exit_rename_table: - sqlite3SrcListDelete(db, pSrc); - sqlite3DbFree(db, zName); - db->mDbFlags = savedDbFlags; -} - -/* -** Write code that will raise an error if the table described by -** zDb and zTab is not empty. -*/ -static void sqlite3ErrorIfNotEmpty( - Parse *pParse, /* Parsing context */ - const char *zDb, /* Schema holding the table */ - const char *zTab, /* Table to check for empty */ - const char *zErr /* Error message text */ -){ - sqlite3NestedParse(pParse, - "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"", - zErr, zDb, zTab - ); -} - -/* -** This function is called after an "ALTER TABLE ... ADD" statement -** has been parsed. Argument pColDef contains the text of the new -** column definition. -** -** The Table structure pParse->pNewTable was extended to include -** the new column during parsing. -*/ -SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ - Table *pNew; /* Copy of pParse->pNewTable */ - Table *pTab; /* Table being altered */ - int iDb; /* Database number */ - const char *zDb; /* Database name */ - const char *zTab; /* Table name */ - char *zCol; /* Null-terminated column definition */ - Column *pCol; /* The new column */ - Expr *pDflt; /* Default value for the new column */ - sqlite3 *db; /* The database connection; */ - Vdbe *v; /* The prepared statement under construction */ - int r1; /* Temporary registers */ - - db = pParse->db; - if( pParse->nErr || db->mallocFailed ) return; - pNew = pParse->pNewTable; - assert( pNew ); - - assert( sqlite3BtreeHoldsAllMutexes(db) ); - iDb = sqlite3SchemaToIndex(db, pNew->pSchema); - zDb = db->aDb[iDb].zDbSName; - zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ - pCol = &pNew->aCol[pNew->nCol-1]; - pDflt = pCol->pDflt; - pTab = sqlite3FindTable(db, zTab, zDb); - assert( pTab ); - -#ifndef SQLITE_OMIT_AUTHORIZATION - /* Invoke the authorization callback. */ - if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ - return; - } -#endif - - - /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. - ** If there is a NOT NULL constraint, then the default value for the - ** column must not be NULL. - */ - if( pCol->colFlags & COLFLAG_PRIMKEY ){ - sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); - return; - } - if( pNew->pIndex ){ - sqlite3ErrorMsg(pParse, - "Cannot add a UNIQUE column"); - return; - } - if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){ - /* If the default value for the new column was specified with a - ** literal NULL, then set pDflt to 0. This simplifies checking - ** for an SQL NULL default below. - */ - assert( pDflt==0 || pDflt->op==TK_SPAN ); - if( pDflt && pDflt->pLeft->op==TK_NULL ){ - pDflt = 0; - } - if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ - sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, - "Cannot add a REFERENCES column with non-NULL default value"); - } - if( pCol->notNull && !pDflt ){ - sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, - "Cannot add a NOT NULL column with default value NULL"); - } - - - /* Ensure the default expression is something that sqlite3ValueFromExpr() - ** can handle (i.e. not CURRENT_TIME etc.) - */ - if( pDflt ){ - sqlite3_value *pVal = 0; - int rc; - rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal); - assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); - if( rc!=SQLITE_OK ){ - assert( db->mallocFailed == 1 ); - return; - } - if( !pVal ){ - sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, - "Cannot add a column with non-constant default"); - } - sqlite3ValueFree(pVal); - } - }else if( pCol->colFlags & COLFLAG_STORED ){ - sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column"); - } - - - /* Modify the CREATE TABLE statement. */ - zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); - if( zCol ){ - char *zEnd = &zCol[pColDef->n-1]; - u32 savedDbFlags = db->mDbFlags; - while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ - *zEnd-- = '\0'; - } - db->mDbFlags |= DBFLAG_PreferBuiltin; - sqlite3NestedParse(pParse, - "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET " - "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " - "WHERE type = 'table' AND name = %Q", - zDb, pNew->addColOffset, zCol, pNew->addColOffset+1, - zTab - ); - sqlite3DbFree(db, zCol); - db->mDbFlags = savedDbFlags; - } - - /* Make sure the schema version is at least 3. But do not upgrade - ** from less than 3 to 4, as that will corrupt any preexisting DESC - ** index. - */ - v = sqlite3GetVdbe(pParse); - if( v ){ - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); - sqlite3VdbeUsesBtree(v, iDb); - sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2); - sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3); - sqlite3ReleaseTempReg(pParse, r1); - } - - /* Reload the table definition */ - renameReloadSchema(pParse, iDb); -} - -/* -** This function is called by the parser after the table-name in -** an "ALTER TABLE ADD" statement is parsed. Argument -** pSrc is the full-name of the table being altered. -** -** This routine makes a (partial) copy of the Table structure -** for the table being altered and sets Parse.pNewTable to point -** to it. Routines called by the parser as the column definition -** is parsed (i.e. sqlite3AddColumn()) add the new Column data to -** the copy. The copy of the Table structure is deleted by tokenize.c -** after parsing is finished. -** -** Routine sqlite3AlterFinishAddColumn() will be called to complete -** coding the "ALTER TABLE ... ADD" statement. -*/ -SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ - Table *pNew; - Table *pTab; - int iDb; - int i; - int nAlloc; - sqlite3 *db = pParse->db; - - /* Look up the table being altered. */ - assert( pParse->pNewTable==0 ); - assert( sqlite3BtreeHoldsAllMutexes(db) ); - if( db->mallocFailed ) goto exit_begin_add_column; - pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); - if( !pTab ) goto exit_begin_add_column; - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pTab) ){ - sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); - goto exit_begin_add_column; - } -#endif - - /* Make sure this is not an attempt to ALTER a view. */ - if( pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); - goto exit_begin_add_column; - } - if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ - goto exit_begin_add_column; - } - - sqlite3MayAbort(pParse); - assert( pTab->addColOffset>0 ); - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - - /* Put a copy of the Table struct in Parse.pNewTable for the - ** sqlite3AddColumn() function and friends to modify. But modify - ** the name by adding an "sqlite_altertab_" prefix. By adding this - ** prefix, we insure that the name will not collide with an existing - ** table because user table are not allowed to have the "sqlite_" - ** prefix on their name. - */ - pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); - if( !pNew ) goto exit_begin_add_column; - pParse->pNewTable = pNew; - pNew->nTabRef = 1; - pNew->nCol = pTab->nCol; - assert( pNew->nCol>0 ); - nAlloc = (((pNew->nCol-1)/8)*8)+8; - assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); - pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); - pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); - if( !pNew->aCol || !pNew->zName ){ - assert( db->mallocFailed ); - goto exit_begin_add_column; - } - memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); - for(i=0; inCol; i++){ - Column *pCol = &pNew->aCol[i]; - pCol->zName = sqlite3DbStrDup(db, pCol->zName); - pCol->hName = sqlite3StrIHash(pCol->zName); - pCol->zColl = 0; - pCol->pDflt = 0; - } - pNew->pSchema = db->aDb[iDb].pSchema; - pNew->addColOffset = pTab->addColOffset; - pNew->nTabRef = 1; - -exit_begin_add_column: - sqlite3SrcListDelete(db, pSrc); - return; -} - -/* -** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN -** command. This function checks if the table is a view or virtual -** table (columns of views or virtual tables may not be renamed). If so, -** it loads an error message into pParse and returns non-zero. -** -** Or, if pTab is not a view or virtual table, zero is returned. -*/ -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) -static int isRealTable(Parse *pParse, Table *pTab){ - const char *zType = 0; -#ifndef SQLITE_OMIT_VIEW - if( pTab->pSelect ){ - zType = "view"; - } -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pTab) ){ - zType = "virtual table"; - } -#endif - if( zType ){ - sqlite3ErrorMsg( - pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName - ); - return 1; - } - return 0; -} -#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ -# define isRealTable(x,y) (0) -#endif - -/* -** Handles the following parser reduction: -** -** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew -*/ -SQLITE_PRIVATE void sqlite3AlterRenameColumn( - Parse *pParse, /* Parsing context */ - SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */ - Token *pOld, /* Name of column being changed */ - Token *pNew /* New column name */ -){ - sqlite3 *db = pParse->db; /* Database connection */ - Table *pTab; /* Table being updated */ - int iCol; /* Index of column being renamed */ - char *zOld = 0; /* Old column name */ - char *zNew = 0; /* New column name */ - const char *zDb; /* Name of schema containing the table */ - int iSchema; /* Index of the schema */ - int bQuote; /* True to quote the new name */ - - /* Locate the table to be altered */ - pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); - if( !pTab ) goto exit_rename_column; - - /* Cannot alter a system table */ - if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column; - if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column; - - /* Which schema holds the table to be altered */ - iSchema = sqlite3SchemaToIndex(db, pTab->pSchema); - assert( iSchema>=0 ); - zDb = db->aDb[iSchema].zDbSName; - -#ifndef SQLITE_OMIT_AUTHORIZATION - /* Invoke the authorization callback. */ - if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ - goto exit_rename_column; - } -#endif - - /* Make sure the old name really is a column name in the table to be - ** altered. Set iCol to be the index of the column being renamed */ - zOld = sqlite3NameFromToken(db, pOld); - if( !zOld ) goto exit_rename_column; - for(iCol=0; iColnCol; iCol++){ - if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break; - } - if( iCol==pTab->nCol ){ - sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld); - goto exit_rename_column; - } - - /* Do the rename operation using a recursive UPDATE statement that - ** uses the sqlite_rename_column() SQL function to compute the new - ** CREATE statement text for the sqlite_schema table. - */ - sqlite3MayAbort(pParse); - zNew = sqlite3NameFromToken(db, pNew); - if( !zNew ) goto exit_rename_column; - assert( pNew->n>0 ); - bQuote = sqlite3Isquote(pNew->z[0]); - sqlite3NestedParse(pParse, - "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET " - "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) " - "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' " - " AND (type != 'index' OR tbl_name = %Q)" - " AND sql NOT LIKE 'create virtual%%'", - zDb, - zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1, - pTab->zName - ); - - sqlite3NestedParse(pParse, - "UPDATE temp." DFLT_SCHEMA_TABLE " SET " - "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) " - "WHERE type IN ('trigger', 'view')", - zDb, pTab->zName, iCol, zNew, bQuote - ); - - /* Drop and reload the database schema. */ - renameReloadSchema(pParse, iSchema); - renameTestSchema(pParse, zDb, iSchema==1); - - exit_rename_column: - sqlite3SrcListDelete(db, pSrc); - sqlite3DbFree(db, zOld); - sqlite3DbFree(db, zNew); - return; -} - -/* -** Each RenameToken object maps an element of the parse tree into -** the token that generated that element. The parse tree element -** might be one of: -** -** * A pointer to an Expr that represents an ID -** * The name of a table column in Column.zName -** -** A list of RenameToken objects can be constructed during parsing. -** Each new object is created by sqlite3RenameTokenMap(). -** As the parse tree is transformed, the sqlite3RenameTokenRemap() -** routine is used to keep the mapping current. -** -** After the parse finishes, renameTokenFind() routine can be used -** to look up the actual token value that created some element in -** the parse tree. -*/ -struct RenameToken { - void *p; /* Parse tree element created by token t */ - Token t; /* The token that created parse tree element p */ - RenameToken *pNext; /* Next is a list of all RenameToken objects */ -}; - -/* -** The context of an ALTER TABLE RENAME COLUMN operation that gets passed -** down into the Walker. -*/ -typedef struct RenameCtx RenameCtx; -struct RenameCtx { - RenameToken *pList; /* List of tokens to overwrite */ - int nList; /* Number of tokens in pList */ - int iCol; /* Index of column being renamed */ - Table *pTab; /* Table being ALTERed */ - const char *zOld; /* Old column name */ -}; - -#ifdef SQLITE_DEBUG -/* -** This function is only for debugging. It performs two tasks: -** -** 1. Checks that pointer pPtr does not already appear in the -** rename-token list. -** -** 2. Dereferences each pointer in the rename-token list. -** -** The second is most effective when debugging under valgrind or -** address-sanitizer or similar. If any of these pointers no longer -** point to valid objects, an exception is raised by the memory-checking -** tool. -** -** The point of this is to prevent comparisons of invalid pointer values. -** Even though this always seems to work, it is undefined according to the -** C standard. Example of undefined comparison: -** -** sqlite3_free(x); -** if( x==y ) ... -** -** Technically, as x no longer points into a valid object or to the byte -** following a valid object, it may not be used in comparison operations. -*/ -static void renameTokenCheckAll(Parse *pParse, void *pPtr){ - if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){ - RenameToken *p; - u8 i = 0; - for(p=pParse->pRename; p; p=p->pNext){ - if( p->p ){ - assert( p->p!=pPtr ); - i += *(u8*)(p->p); - } - } - } -} -#else -# define renameTokenCheckAll(x,y) -#endif - -/* -** Remember that the parser tree element pPtr was created using -** the token pToken. -** -** In other words, construct a new RenameToken object and add it -** to the list of RenameToken objects currently being built up -** in pParse->pRename. -** -** The pPtr argument is returned so that this routine can be used -** with tail recursion in tokenExpr() routine, for a small performance -** improvement. -*/ -SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){ - RenameToken *pNew; - assert( pPtr || pParse->db->mallocFailed ); - renameTokenCheckAll(pParse, pPtr); - if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){ - pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken)); - if( pNew ){ - pNew->p = pPtr; - pNew->t = *pToken; - pNew->pNext = pParse->pRename; - pParse->pRename = pNew; - } - } - - return pPtr; -} - -/* -** It is assumed that there is already a RenameToken object associated -** with parse tree element pFrom. This function remaps the associated token -** to parse tree element pTo. -*/ -SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){ - RenameToken *p; - renameTokenCheckAll(pParse, pTo); - for(p=pParse->pRename; p; p=p->pNext){ - if( p->p==pFrom ){ - p->p = pTo; - break; - } - } -} - -/* -** Walker callback used by sqlite3RenameExprUnmap(). -*/ -static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){ - Parse *pParse = pWalker->pParse; - sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); - return WRC_Continue; -} - -/* -** Iterate through the Select objects that are part of WITH clauses attached -** to select statement pSelect. -*/ -static void renameWalkWith(Walker *pWalker, Select *pSelect){ - With *pWith = pSelect->pWith; - if( pWith ){ - int i; - for(i=0; inCte; i++){ - Select *p = pWith->a[i].pSelect; - NameContext sNC; - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pWalker->pParse; - sqlite3SelectPrep(sNC.pParse, p, &sNC); - sqlite3WalkSelect(pWalker, p); - sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols); - } - } -} - -/* -** Unmap all tokens in the IdList object passed as the second argument. -*/ -static void unmapColumnIdlistNames( - Parse *pParse, - IdList *pIdList -){ - if( pIdList ){ - int ii; - for(ii=0; iinId; ii++){ - sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName); - } - } -} - -/* -** Walker callback used by sqlite3RenameExprUnmap(). -*/ -static int renameUnmapSelectCb(Walker *pWalker, Select *p){ - Parse *pParse = pWalker->pParse; - int i; - if( pParse->nErr ) return WRC_Abort; - if( NEVER(p->selFlags & SF_View) ) return WRC_Prune; - if( ALWAYS(p->pEList) ){ - ExprList *pList = p->pEList; - for(i=0; inExpr; i++){ - if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){ - sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName); - } - } - } - if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */ - SrcList *pSrc = p->pSrc; - for(i=0; inSrc; i++){ - sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName); - if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort; - unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing); - } - } - - renameWalkWith(pWalker, p); - return WRC_Continue; -} - -/* -** Remove all nodes that are part of expression pExpr from the rename list. -*/ -SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){ - u8 eMode = pParse->eParseMode; - Walker sWalker; - memset(&sWalker, 0, sizeof(Walker)); - sWalker.pParse = pParse; - sWalker.xExprCallback = renameUnmapExprCb; - sWalker.xSelectCallback = renameUnmapSelectCb; - pParse->eParseMode = PARSE_MODE_UNMAP; - sqlite3WalkExpr(&sWalker, pExpr); - pParse->eParseMode = eMode; -} - -/* -** Remove all nodes that are part of expression-list pEList from the -** rename list. -*/ -SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){ - if( pEList ){ - int i; - Walker sWalker; - memset(&sWalker, 0, sizeof(Walker)); - sWalker.pParse = pParse; - sWalker.xExprCallback = renameUnmapExprCb; - sqlite3WalkExprList(&sWalker, pEList); - for(i=0; inExpr; i++){ - if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){ - sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName); - } - } - } -} - -/* -** Free the list of RenameToken objects given in the second argument -*/ -static void renameTokenFree(sqlite3 *db, RenameToken *pToken){ - RenameToken *pNext; - RenameToken *p; - for(p=pToken; p; p=pNext){ - pNext = p->pNext; - sqlite3DbFree(db, p); - } -} - -/* -** Search the Parse object passed as the first argument for a RenameToken -** object associated with parse tree element pPtr. If found, remove it -** from the Parse object and add it to the list maintained by the -** RenameCtx object passed as the second argument. -*/ -static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){ - RenameToken **pp; - assert( pPtr!=0 ); - for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){ - if( (*pp)->p==pPtr ){ - RenameToken *pToken = *pp; - *pp = pToken->pNext; - pToken->pNext = pCtx->pList; - pCtx->pList = pToken; - pCtx->nList++; - break; - } - } -} - -/* -** This is a Walker select callback. It does nothing. It is only required -** because without a dummy callback, sqlite3WalkExpr() and similar do not -** descend into sub-select statements. -*/ -static int renameColumnSelectCb(Walker *pWalker, Select *p){ - if( p->selFlags & SF_View ) return WRC_Prune; - renameWalkWith(pWalker, p); - return WRC_Continue; -} - -/* -** This is a Walker expression callback. -** -** For every TK_COLUMN node in the expression tree, search to see -** if the column being references is the column being renamed by an -** ALTER TABLE statement. If it is, then attach its associated -** RenameToken object to the list of RenameToken objects being -** constructed in RenameCtx object at pWalker->u.pRename. -*/ -static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){ - RenameCtx *p = pWalker->u.pRename; - if( pExpr->op==TK_TRIGGER - && pExpr->iColumn==p->iCol - && pWalker->pParse->pTriggerTab==p->pTab - ){ - renameTokenFind(pWalker->pParse, p, (void*)pExpr); - }else if( pExpr->op==TK_COLUMN - && pExpr->iColumn==p->iCol - && p->pTab==pExpr->y.pTab - ){ - renameTokenFind(pWalker->pParse, p, (void*)pExpr); - } - return WRC_Continue; -} - -/* -** The RenameCtx contains a list of tokens that reference a column that -** is being renamed by an ALTER TABLE statement. Return the "last" -** RenameToken in the RenameCtx and remove that RenameToken from the -** RenameContext. "Last" means the last RenameToken encountered when -** the input SQL is parsed from left to right. Repeated calls to this routine -** return all column name tokens in the order that they are encountered -** in the SQL statement. -*/ -static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){ - RenameToken *pBest = pCtx->pList; - RenameToken *pToken; - RenameToken **pp; - - for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){ - if( pToken->t.z>pBest->t.z ) pBest = pToken; - } - for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext); - *pp = pBest->pNext; - - return pBest; -} - -/* -** An error occured while parsing or otherwise processing a database -** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an -** ALTER TABLE RENAME COLUMN program. The error message emitted by the -** sub-routine is currently stored in pParse->zErrMsg. This function -** adds context to the error message and then stores it in pCtx. -*/ -static void renameColumnParseError( - sqlite3_context *pCtx, - int bPost, - sqlite3_value *pType, - sqlite3_value *pObject, - Parse *pParse -){ - const char *zT = (const char*)sqlite3_value_text(pType); - const char *zN = (const char*)sqlite3_value_text(pObject); - char *zErr; - - zErr = sqlite3_mprintf("error in %s %s%s: %s", - zT, zN, (bPost ? " after rename" : ""), - pParse->zErrMsg - ); - sqlite3_result_error(pCtx, zErr, -1); - sqlite3_free(zErr); -} - -/* -** For each name in the the expression-list pEList (i.e. each -** pEList->a[i].zName) that matches the string in zOld, extract the -** corresponding rename-token from Parse object pParse and add it -** to the RenameCtx pCtx. -*/ -static void renameColumnElistNames( - Parse *pParse, - RenameCtx *pCtx, - ExprList *pEList, - const char *zOld -){ - if( pEList ){ - int i; - for(i=0; inExpr; i++){ - char *zName = pEList->a[i].zEName; - if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) - && ALWAYS(zName!=0) - && 0==sqlite3_stricmp(zName, zOld) - ){ - renameTokenFind(pParse, pCtx, (void*)zName); - } - } - } -} - -/* -** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName) -** that matches the string in zOld, extract the corresponding rename-token -** from Parse object pParse and add it to the RenameCtx pCtx. -*/ -static void renameColumnIdlistNames( - Parse *pParse, - RenameCtx *pCtx, - IdList *pIdList, - const char *zOld -){ - if( pIdList ){ - int i; - for(i=0; inId; i++){ - char *zName = pIdList->a[i].zName; - if( 0==sqlite3_stricmp(zName, zOld) ){ - renameTokenFind(pParse, pCtx, (void*)zName); - } - } - } -} - - -/* -** Parse the SQL statement zSql using Parse object (*p). The Parse object -** is initialized by this function before it is used. -*/ -static int renameParseSql( - Parse *p, /* Memory to use for Parse object */ - const char *zDb, /* Name of schema SQL belongs to */ - sqlite3 *db, /* Database handle */ - const char *zSql, /* SQL to parse */ - int bTemp /* True if SQL is from temp schema */ -){ - int rc; - char *zErr = 0; - - db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb); - - /* Parse the SQL statement passed as the first argument. If no error - ** occurs and the parse does not result in a new table, index or - ** trigger object, the database must be corrupt. */ - memset(p, 0, sizeof(Parse)); - p->eParseMode = PARSE_MODE_RENAME; - p->db = db; - p->nQueryLoop = 1; - rc = sqlite3RunParser(p, zSql, &zErr); - assert( p->zErrMsg==0 ); - assert( rc!=SQLITE_OK || zErr==0 ); - p->zErrMsg = zErr; - if( db->mallocFailed ) rc = SQLITE_NOMEM; - if( rc==SQLITE_OK - && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0 - ){ - rc = SQLITE_CORRUPT_BKPT; - } - -#ifdef SQLITE_DEBUG - /* Ensure that all mappings in the Parse.pRename list really do map to - ** a part of the input string. */ - if( rc==SQLITE_OK ){ - int nSql = sqlite3Strlen30(zSql); - RenameToken *pToken; - for(pToken=p->pRename; pToken; pToken=pToken->pNext){ - assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] ); - } - } -#endif - - db->init.iDb = 0; - return rc; -} - -/* -** This function edits SQL statement zSql, replacing each token identified -** by the linked list pRename with the text of zNew. If argument bQuote is -** true, then zNew is always quoted first. If no error occurs, the result -** is loaded into context object pCtx as the result. -** -** Or, if an error occurs (i.e. an OOM condition), an error is left in -** pCtx and an SQLite error code returned. -*/ -static int renameEditSql( - sqlite3_context *pCtx, /* Return result here */ - RenameCtx *pRename, /* Rename context */ - const char *zSql, /* SQL statement to edit */ - const char *zNew, /* New token text */ - int bQuote /* True to always quote token */ -){ - int nNew = sqlite3Strlen30(zNew); - int nSql = sqlite3Strlen30(zSql); - sqlite3 *db = sqlite3_context_db_handle(pCtx); - int rc = SQLITE_OK; - char *zQuot; - char *zOut; - int nQuot; - - /* Set zQuot to point to a buffer containing a quoted copy of the - ** identifier zNew. If the corresponding identifier in the original - ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to - ** point to zQuot so that all substitutions are made using the - ** quoted version of the new column name. */ - zQuot = sqlite3MPrintf(db, "\"%w\"", zNew); - if( zQuot==0 ){ - return SQLITE_NOMEM; - }else{ - nQuot = sqlite3Strlen30(zQuot); - } - if( bQuote ){ - zNew = zQuot; - nNew = nQuot; - } - - /* At this point pRename->pList contains a list of RenameToken objects - ** corresponding to all tokens in the input SQL that must be replaced - ** with the new column name. All that remains is to construct and - ** return the edited SQL string. */ - assert( nQuot>=nNew ); - zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1); - if( zOut ){ - int nOut = nSql; - memcpy(zOut, zSql, nSql); - while( pRename->pList ){ - int iOff; /* Offset of token to replace in zOut */ - RenameToken *pBest = renameColumnTokenNext(pRename); - - u32 nReplace; - const char *zReplace; - if( sqlite3IsIdChar(*pBest->t.z) ){ - nReplace = nNew; - zReplace = zNew; - }else{ - nReplace = nQuot; - zReplace = zQuot; - } - - iOff = pBest->t.z - zSql; - if( pBest->t.n!=nReplace ){ - memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], - nOut - (iOff + pBest->t.n) - ); - nOut += nReplace - pBest->t.n; - zOut[nOut] = '\0'; - } - memcpy(&zOut[iOff], zReplace, nReplace); - sqlite3DbFree(db, pBest); - } - - sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT); - sqlite3DbFree(db, zOut); - }else{ - rc = SQLITE_NOMEM; - } - - sqlite3_free(zQuot); - return rc; -} - -/* -** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming -** it was read from the schema of database zDb. Return SQLITE_OK if -** successful. Otherwise, return an SQLite error code and leave an error -** message in the Parse object. -*/ -static int renameResolveTrigger(Parse *pParse){ - sqlite3 *db = pParse->db; - Trigger *pNew = pParse->pNewTrigger; - TriggerStep *pStep; - NameContext sNC; - int rc = SQLITE_OK; - - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - assert( pNew->pTabSchema ); - pParse->pTriggerTab = sqlite3FindTable(db, pNew->table, - db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName - ); - pParse->eTriggerOp = pNew->op; - /* ALWAYS() because if the table of the trigger does not exist, the - ** error would have been hit before this point */ - if( ALWAYS(pParse->pTriggerTab) ){ - rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab); - } - - /* Resolve symbols in WHEN clause */ - if( rc==SQLITE_OK && pNew->pWhen ){ - rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen); - } - - for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){ - if( pStep->pSelect ){ - sqlite3SelectPrep(pParse, pStep->pSelect, &sNC); - if( pParse->nErr ) rc = pParse->rc; - } - if( rc==SQLITE_OK && pStep->zTarget ){ - SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep); - if( pSrc ){ - int i; - for(i=0; inSrc && rc==SQLITE_OK; i++){ - struct SrcList_item *p = &pSrc->a[i]; - p->pTab = sqlite3LocateTableItem(pParse, 0, p); - p->iCursor = pParse->nTab++; - if( p->pTab==0 ){ - rc = SQLITE_ERROR; - }else{ - p->pTab->nTabRef++; - rc = sqlite3ViewGetColumnNames(pParse, p->pTab); - } - } - sNC.pSrcList = pSrc; - if( rc==SQLITE_OK && pStep->pWhere ){ - rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere); - } - if( rc==SQLITE_OK ){ - rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList); - } - assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) ); - if( pStep->pUpsert ){ - Upsert *pUpsert = pStep->pUpsert; - assert( rc==SQLITE_OK ); - pUpsert->pUpsertSrc = pSrc; - sNC.uNC.pUpsert = pUpsert; - sNC.ncFlags = NC_UUpsert; - rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget); - if( rc==SQLITE_OK ){ - ExprList *pUpsertSet = pUpsert->pUpsertSet; - rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet); - } - if( rc==SQLITE_OK ){ - rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere); - } - if( rc==SQLITE_OK ){ - rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere); - } - sNC.ncFlags = 0; - } - sNC.pSrcList = 0; - sqlite3SrcListDelete(db, pSrc); - }else{ - rc = SQLITE_NOMEM; - } - } - } - return rc; -} - -/* -** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr -** objects that are part of the trigger passed as the second argument. -*/ -static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){ - TriggerStep *pStep; - - /* Find tokens to edit in WHEN clause */ - sqlite3WalkExpr(pWalker, pTrigger->pWhen); - - /* Find tokens to edit in trigger steps */ - for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ - sqlite3WalkSelect(pWalker, pStep->pSelect); - sqlite3WalkExpr(pWalker, pStep->pWhere); - sqlite3WalkExprList(pWalker, pStep->pExprList); - if( pStep->pUpsert ){ - Upsert *pUpsert = pStep->pUpsert; - sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget); - sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet); - sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere); - sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere); - } - } -} - -/* -** Free the contents of Parse object (*pParse). Do not free the memory -** occupied by the Parse object itself. -*/ -static void renameParseCleanup(Parse *pParse){ - sqlite3 *db = pParse->db; - Index *pIdx; - if( pParse->pVdbe ){ - sqlite3VdbeFinalize(pParse->pVdbe); - } - sqlite3DeleteTable(db, pParse->pNewTable); - while( (pIdx = pParse->pNewIndex)!=0 ){ - pParse->pNewIndex = pIdx->pNext; - sqlite3FreeIndex(db, pIdx); - } - sqlite3DeleteTrigger(db, pParse->pNewTrigger); - sqlite3DbFree(db, pParse->zErrMsg); - renameTokenFree(db, pParse->pRename); - sqlite3ParserReset(pParse); -} - -/* -** SQL function: -** -** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld) -** -** 0. zSql: SQL statement to rewrite -** 1. type: Type of object ("table", "view" etc.) -** 2. object: Name of object -** 3. Database: Database name (e.g. "main") -** 4. Table: Table name -** 5. iCol: Index of column to rename -** 6. zNew: New column name -** 7. bQuote: Non-zero if the new column name should be quoted. -** 8. bTemp: True if zSql comes from temp schema -** -** Do a column rename operation on the CREATE statement given in zSql. -** The iCol-th column (left-most is 0) of table zTable is renamed from zCol -** into zNew. The name should be quoted if bQuote is true. -** -** This function is used internally by the ALTER TABLE RENAME COLUMN command. -** It is only accessible to SQL created using sqlite3NestedParse(). It is -** not reachable from ordinary SQL passed into sqlite3_prepare(). -*/ -static void renameColumnFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - RenameCtx sCtx; - const char *zSql = (const char*)sqlite3_value_text(argv[0]); - const char *zDb = (const char*)sqlite3_value_text(argv[3]); - const char *zTable = (const char*)sqlite3_value_text(argv[4]); - int iCol = sqlite3_value_int(argv[5]); - const char *zNew = (const char*)sqlite3_value_text(argv[6]); - int bQuote = sqlite3_value_int(argv[7]); - int bTemp = sqlite3_value_int(argv[8]); - const char *zOld; - int rc; - Parse sParse; - Walker sWalker; - Index *pIdx; - int i; - Table *pTab; -#ifndef SQLITE_OMIT_AUTHORIZATION - sqlite3_xauth xAuth = db->xAuth; -#endif - - UNUSED_PARAMETER(NotUsed); - if( zSql==0 ) return; - if( zTable==0 ) return; - if( zNew==0 ) return; - if( iCol<0 ) return; - sqlite3BtreeEnterAll(db); - pTab = sqlite3FindTable(db, zTable, zDb); - if( pTab==0 || iCol>=pTab->nCol ){ - sqlite3BtreeLeaveAll(db); - return; - } - zOld = pTab->aCol[iCol].zName; - memset(&sCtx, 0, sizeof(sCtx)); - sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol); - -#ifndef SQLITE_OMIT_AUTHORIZATION - db->xAuth = 0; -#endif - rc = renameParseSql(&sParse, zDb, db, zSql, bTemp); - - /* Find tokens that need to be replaced. */ - memset(&sWalker, 0, sizeof(Walker)); - sWalker.pParse = &sParse; - sWalker.xExprCallback = renameColumnExprCb; - sWalker.xSelectCallback = renameColumnSelectCb; - sWalker.u.pRename = &sCtx; - - sCtx.pTab = pTab; - if( rc!=SQLITE_OK ) goto renameColumnFunc_done; - if( sParse.pNewTable ){ - Select *pSelect = sParse.pNewTable->pSelect; - if( pSelect ){ - pSelect->selFlags &= ~SF_View; - sParse.rc = SQLITE_OK; - sqlite3SelectPrep(&sParse, pSelect, 0); - rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); - if( rc==SQLITE_OK ){ - sqlite3WalkSelect(&sWalker, pSelect); - } - if( rc!=SQLITE_OK ) goto renameColumnFunc_done; - }else{ - /* A regular table */ - int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName); - FKey *pFKey; - assert( sParse.pNewTable->pSelect==0 ); - sCtx.pTab = sParse.pNewTable; - if( bFKOnly==0 ){ - renameTokenFind( - &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName - ); - if( sCtx.iCol<0 ){ - renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey); - } - sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck); - for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){ - sqlite3WalkExprList(&sWalker, pIdx->aColExpr); - } - for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){ - sqlite3WalkExprList(&sWalker, pIdx->aColExpr); - } - } -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - for(i=0; inCol; i++){ - sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt); - } -#endif - - for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){ - for(i=0; inCol; i++){ - if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){ - renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]); - } - if( 0==sqlite3_stricmp(pFKey->zTo, zTable) - && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld) - ){ - renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol); - } - } - } - } - }else if( sParse.pNewIndex ){ - sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr); - sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); - }else{ - /* A trigger */ - TriggerStep *pStep; - rc = renameResolveTrigger(&sParse); - if( rc!=SQLITE_OK ) goto renameColumnFunc_done; - - for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){ - if( pStep->zTarget ){ - Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb); - if( pTarget==pTab ){ - if( pStep->pUpsert ){ - ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet; - renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld); - } - renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld); - renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld); - } - } - } - - - /* Find tokens to edit in UPDATE OF clause */ - if( sParse.pTriggerTab==pTab ){ - renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld); - } - - /* Find tokens to edit in various expressions and selects */ - renameWalkTrigger(&sWalker, sParse.pNewTrigger); - } - - assert( rc==SQLITE_OK ); - rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote); - -renameColumnFunc_done: - if( rc!=SQLITE_OK ){ - if( sParse.zErrMsg ){ - renameColumnParseError(context, 0, argv[1], argv[2], &sParse); - }else{ - sqlite3_result_error_code(context, rc); - } - } - - renameParseCleanup(&sParse); - renameTokenFree(db, sCtx.pList); -#ifndef SQLITE_OMIT_AUTHORIZATION - db->xAuth = xAuth; -#endif - sqlite3BtreeLeaveAll(db); -} - -/* -** Walker expression callback used by "RENAME TABLE". -*/ -static int renameTableExprCb(Walker *pWalker, Expr *pExpr){ - RenameCtx *p = pWalker->u.pRename; - if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){ - renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab); - } - return WRC_Continue; -} - -/* -** Walker select callback used by "RENAME TABLE". -*/ -static int renameTableSelectCb(Walker *pWalker, Select *pSelect){ - int i; - RenameCtx *p = pWalker->u.pRename; - SrcList *pSrc = pSelect->pSrc; - if( pSelect->selFlags & SF_View ) return WRC_Prune; - if( pSrc==0 ){ - assert( pWalker->pParse->db->mallocFailed ); - return WRC_Abort; - } - for(i=0; inSrc; i++){ - struct SrcList_item *pItem = &pSrc->a[i]; - if( pItem->pTab==p->pTab ){ - renameTokenFind(pWalker->pParse, p, pItem->zName); - } - } - renameWalkWith(pWalker, pSelect); - - return WRC_Continue; -} - - -/* -** This C function implements an SQL user function that is used by SQL code -** generated by the ALTER TABLE ... RENAME command to modify the definition -** of any foreign key constraints that use the table being renamed as the -** parent table. It is passed three arguments: -** -** 0: The database containing the table being renamed. -** 1. type: Type of object ("table", "view" etc.) -** 2. object: Name of object -** 3: The complete text of the schema statement being modified, -** 4: The old name of the table being renamed, and -** 5: The new name of the table being renamed. -** 6: True if the schema statement comes from the temp db. -** -** It returns the new schema statement. For example: -** -** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0) -** -> 'CREATE TABLE t1(a REFERENCES t3)' -*/ -static void renameTableFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - const char *zDb = (const char*)sqlite3_value_text(argv[0]); - const char *zInput = (const char*)sqlite3_value_text(argv[3]); - const char *zOld = (const char*)sqlite3_value_text(argv[4]); - const char *zNew = (const char*)sqlite3_value_text(argv[5]); - int bTemp = sqlite3_value_int(argv[6]); - UNUSED_PARAMETER(NotUsed); - - if( zInput && zOld && zNew ){ - Parse sParse; - int rc; - int bQuote = 1; - RenameCtx sCtx; - Walker sWalker; - -#ifndef SQLITE_OMIT_AUTHORIZATION - sqlite3_xauth xAuth = db->xAuth; - db->xAuth = 0; -#endif - - sqlite3BtreeEnterAll(db); - - memset(&sCtx, 0, sizeof(RenameCtx)); - sCtx.pTab = sqlite3FindTable(db, zOld, zDb); - memset(&sWalker, 0, sizeof(Walker)); - sWalker.pParse = &sParse; - sWalker.xExprCallback = renameTableExprCb; - sWalker.xSelectCallback = renameTableSelectCb; - sWalker.u.pRename = &sCtx; - - rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); - - if( rc==SQLITE_OK ){ - int isLegacy = (db->flags & SQLITE_LegacyAlter); - if( sParse.pNewTable ){ - Table *pTab = sParse.pNewTable; - - if( pTab->pSelect ){ - if( isLegacy==0 ){ - Select *pSelect = pTab->pSelect; - NameContext sNC; - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = &sParse; - - assert( pSelect->selFlags & SF_View ); - pSelect->selFlags &= ~SF_View; - sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC); - if( sParse.nErr ){ - rc = sParse.rc; - }else{ - sqlite3WalkSelect(&sWalker, pTab->pSelect); - } - } - }else{ - /* Modify any FK definitions to point to the new table. */ -#ifndef SQLITE_OMIT_FOREIGN_KEY - if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){ - FKey *pFKey; - for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ - if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){ - renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo); - } - } - } -#endif - - /* If this is the table being altered, fix any table refs in CHECK - ** expressions. Also update the name that appears right after the - ** "CREATE [VIRTUAL] TABLE" bit. */ - if( sqlite3_stricmp(zOld, pTab->zName)==0 ){ - sCtx.pTab = pTab; - if( isLegacy==0 ){ - sqlite3WalkExprList(&sWalker, pTab->pCheck); - } - renameTokenFind(&sParse, &sCtx, pTab->zName); - } - } - } - - else if( sParse.pNewIndex ){ - renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName); - if( isLegacy==0 ){ - sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); - } - } - -#ifndef SQLITE_OMIT_TRIGGER - else{ - Trigger *pTrigger = sParse.pNewTrigger; - TriggerStep *pStep; - if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) - && sCtx.pTab->pSchema==pTrigger->pTabSchema - ){ - renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table); - } - - if( isLegacy==0 ){ - rc = renameResolveTrigger(&sParse); - if( rc==SQLITE_OK ){ - renameWalkTrigger(&sWalker, pTrigger); - for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ - if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){ - renameTokenFind(&sParse, &sCtx, pStep->zTarget); - } - } - } - } - } -#endif - } - - if( rc==SQLITE_OK ){ - rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote); - } - if( rc!=SQLITE_OK ){ - if( sParse.zErrMsg ){ - renameColumnParseError(context, 0, argv[1], argv[2], &sParse); - }else{ - sqlite3_result_error_code(context, rc); - } - } - - renameParseCleanup(&sParse); - renameTokenFree(db, sCtx.pList); - sqlite3BtreeLeaveAll(db); -#ifndef SQLITE_OMIT_AUTHORIZATION - db->xAuth = xAuth; -#endif - } - - return; -} - -/* -** An SQL user function that checks that there are no parse or symbol -** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement. -** After an ALTER TABLE .. RENAME operation is performed and the schema -** reloaded, this function is called on each SQL statement in the schema -** to ensure that it is still usable. -** -** 0: Database name ("main", "temp" etc.). -** 1: SQL statement. -** 2: Object type ("view", "table", "trigger" or "index"). -** 3: Object name. -** 4: True if object is from temp schema. -** -** Unless it finds an error, this function normally returns NULL. However, it -** returns integer value 1 if: -** -** * the SQL argument creates a trigger, and -** * the table that the trigger is attached to is in database zDb. -*/ -static void renameTableTest( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - char const *zDb = (const char*)sqlite3_value_text(argv[0]); - char const *zInput = (const char*)sqlite3_value_text(argv[1]); - int bTemp = sqlite3_value_int(argv[4]); - int isLegacy = (db->flags & SQLITE_LegacyAlter); - -#ifndef SQLITE_OMIT_AUTHORIZATION - sqlite3_xauth xAuth = db->xAuth; - db->xAuth = 0; -#endif - - UNUSED_PARAMETER(NotUsed); - if( zDb && zInput ){ - int rc; - Parse sParse; - rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); - if( rc==SQLITE_OK ){ - if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){ - NameContext sNC; - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = &sParse; - sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC); - if( sParse.nErr ) rc = sParse.rc; - } - - else if( sParse.pNewTrigger ){ - if( isLegacy==0 ){ - rc = renameResolveTrigger(&sParse); - } - if( rc==SQLITE_OK ){ - int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema); - int i2 = sqlite3FindDbName(db, zDb); - if( i1==i2 ) sqlite3_result_int(context, 1); - } - } - } - - if( rc!=SQLITE_OK ){ - renameColumnParseError(context, 1, argv[2], argv[3], &sParse); - } - renameParseCleanup(&sParse); - } - -#ifndef SQLITE_OMIT_AUTHORIZATION - db->xAuth = xAuth; -#endif -} - -/* -** Register built-in functions used to help implement ALTER TABLE -*/ -SQLITE_PRIVATE void sqlite3AlterFunctions(void){ - static FuncDef aAlterTableFuncs[] = { - INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc), - INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc), - INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest), - }; - sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); -} -#endif /* SQLITE_ALTER_TABLE */ - -/************** End of alter.c ***********************************************/ -/************** Begin file analyze.c *****************************************/ -/* -** 2005-07-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 code associated with the ANALYZE command. -** -** The ANALYZE command gather statistics about the content of tables -** and indices. These statistics are made available to the query planner -** to help it make better decisions about how to perform queries. -** -** The following system tables are or have been supported: -** -** CREATE TABLE sqlite_stat1(tbl, idx, stat); -** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample); -** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample); -** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample); -** -** Additional tables might be added in future releases of SQLite. -** The sqlite_stat2 table is not created or used unless the SQLite version -** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled -** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated. -** The sqlite_stat2 table is superseded by sqlite_stat3, which is only -** created and used by SQLite versions 3.7.9 through 3.29.0 when -** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 -** is a superset of sqlite_stat2 and is also now deprecated. The -** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only -** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite -** versions 3.8.1 and later. STAT4 is the only variant that is still -** supported. -** -** For most applications, sqlite_stat1 provides all the statistics required -** for the query planner to make good choices. -** -** Format of sqlite_stat1: -** -** There is normally one row per index, with the index identified by the -** name in the idx column. The tbl column is the name of the table to -** which the index belongs. In each such row, the stat column will be -** a string consisting of a list of integers. The first integer in this -** list is the number of rows in the index. (This is the same as the -** number of rows in the table, except for partial indices.) The second -** integer is the average number of rows in the index that have the same -** value in the first column of the index. The third integer is the average -** number of rows in the index that have the same value for the first two -** columns. The N-th integer (for N>1) is the average number of rows in -** the index which have the same value for the first N-1 columns. For -** a K-column index, there will be K+1 integers in the stat column. If -** the index is unique, then the last integer will be 1. -** -** The list of integers in the stat column can optionally be followed -** by the keyword "unordered". The "unordered" keyword, if it is present, -** must be separated from the last integer by a single space. If the -** "unordered" keyword is present, then the query planner assumes that -** the index is unordered and will not use the index for a range query. -** -** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat -** column contains a single integer which is the (estimated) number of -** rows in the table identified by sqlite_stat1.tbl. -** -** Format of sqlite_stat2: -** -** The sqlite_stat2 is only created and is only used if SQLite is compiled -** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between -** 3.6.18 and 3.7.8. The "stat2" table contains additional information -** about the distribution of keys within an index. The index is identified by -** the "idx" column and the "tbl" column is the name of the table to which -** the index belongs. There are usually 10 rows in the sqlite_stat2 -** table for each index. -** -** The sqlite_stat2 entries for an index that have sampleno between 0 and 9 -** inclusive are samples of the left-most key value in the index taken at -** evenly spaced points along the index. Let the number of samples be S -** (10 in the standard build) and let C be the number of rows in the index. -** Then the sampled rows are given by: -** -** rownumber = (i*C*2 + C)/(S*2) -** -** For i between 0 and S-1. Conceptually, the index space is divided into -** S uniform buckets and the samples are the middle row from each bucket. -** -** The format for sqlite_stat2 is recorded here for legacy reference. This -** version of SQLite does not support sqlite_stat2. It neither reads nor -** writes the sqlite_stat2 table. This version of SQLite only supports -** sqlite_stat3. -** -** Format for sqlite_stat3: -** -** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the -** sqlite_stat4 format will be described first. Further information -** about sqlite_stat3 follows the sqlite_stat4 description. -** -** Format for sqlite_stat4: -** -** As with sqlite_stat2, the sqlite_stat4 table contains histogram data -** to aid the query planner in choosing good indices based on the values -** that indexed columns are compared against in the WHERE clauses of -** queries. -** -** The sqlite_stat4 table contains multiple entries for each index. -** The idx column names the index and the tbl column is the table of the -** index. If the idx and tbl columns are the same, then the sample is -** of the INTEGER PRIMARY KEY. The sample column is a blob which is the -** binary encoding of a key from the index. The nEq column is a -** list of integers. The first integer is the approximate number -** of entries in the index whose left-most column exactly matches -** the left-most column of the sample. The second integer in nEq -** is the approximate number of entries in the index where the -** first two columns match the first two columns of the sample. -** And so forth. nLt is another list of integers that show the approximate -** number of entries that are strictly less than the sample. The first -** integer in nLt contains the number of entries in the index where the -** left-most column is less than the left-most column of the sample. -** The K-th integer in the nLt entry is the number of index entries -** where the first K columns are less than the first K columns of the -** sample. The nDLt column is like nLt except that it contains the -** number of distinct entries in the index that are less than the -** sample. -** -** There can be an arbitrary number of sqlite_stat4 entries per index. -** The ANALYZE command will typically generate sqlite_stat4 tables -** that contain between 10 and 40 samples which are distributed across -** the key space, though not uniformly, and which include samples with -** large nEq values. -** -** Format for sqlite_stat3 redux: -** -** The sqlite_stat3 table is like sqlite_stat4 except that it only -** looks at the left-most column of the index. The sqlite_stat3.sample -** column contains the actual value of the left-most column instead -** of a blob encoding of the complete index key as is found in -** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3 -** all contain just a single integer which is the same as the first -** integer in the equivalent columns in sqlite_stat4. -*/ -#ifndef SQLITE_OMIT_ANALYZE -/* #include "sqliteInt.h" */ - -#if defined(SQLITE_ENABLE_STAT4) -# define IsStat4 1 -#else -# define IsStat4 0 -# undef SQLITE_STAT4_SAMPLES -# define SQLITE_STAT4_SAMPLES 1 -#endif - -/* -** This routine generates code that opens the sqlite_statN tables. -** The sqlite_stat1 table is always relevant. sqlite_stat2 is now -** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when -** appropriate compile-time options are provided. -** -** If the sqlite_statN tables do not previously exist, it is created. -** -** Argument zWhere may be a pointer to a buffer containing a table name, -** or it may be a NULL pointer. If it is not NULL, then all entries in -** the sqlite_statN tables associated with the named table are deleted. -** If zWhere==0, then code is generated to delete all stat table entries. -*/ -static void openStatTable( - Parse *pParse, /* Parsing context */ - int iDb, /* The database we are looking in */ - int iStatCur, /* Open the sqlite_stat1 table on this cursor */ - const char *zWhere, /* Delete entries for this table or index */ - const char *zWhereType /* Either "tbl" or "idx" */ -){ - static const struct { - const char *zName; - const char *zCols; - } aTable[] = { - { "sqlite_stat1", "tbl,idx,stat" }, -#if defined(SQLITE_ENABLE_STAT4) - { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" }, -#else - { "sqlite_stat4", 0 }, -#endif - { "sqlite_stat3", 0 }, - }; - int i; - sqlite3 *db = pParse->db; - Db *pDb; - Vdbe *v = sqlite3GetVdbe(pParse); - u32 aRoot[ArraySize(aTable)]; - u8 aCreateTbl[ArraySize(aTable)]; -#ifdef SQLITE_ENABLE_STAT4 - const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1; -#else - const int nToOpen = 1; -#endif - - if( v==0 ) return; - assert( sqlite3BtreeHoldsAllMutexes(db) ); - assert( sqlite3VdbeDb(v)==db ); - pDb = &db->aDb[iDb]; - - /* Create new statistic tables if they do not exist, or clear them - ** if they do already exist. - */ - for(i=0; izDbSName))==0 ){ - if( iregRoot. This is important - ** because the OpenWrite opcode below will be needing it. */ - sqlite3NestedParse(pParse, - "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols - ); - aRoot[i] = (u32)pParse->regRoot; - aCreateTbl[i] = OPFLAG_P2ISREG; - } - }else{ - /* The table already exists. If zWhere is not NULL, delete all entries - ** associated with the table zWhere. If zWhere is NULL, delete the - ** entire contents of the table. */ - aRoot[i] = pStat->tnum; - sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); - if( zWhere ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.%s WHERE %s=%Q", - pDb->zDbSName, zTab, zWhereType, zWhere - ); -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - }else if( db->xPreUpdateCallback ){ - sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab); -#endif - }else{ - /* The sqlite_stat[134] table already exists. Delete all rows. */ - sqlite3VdbeAddOp2(v, OP_Clear, (int)aRoot[i], iDb); - } - } - } - - /* Open the sqlite_stat[134] tables for writing. */ - for(i=0; inRowid ){ - sqlite3DbFree(db, p->u.aRowid); - p->nRowid = 0; - } -} -#endif - -/* Initialize the BLOB value of a ROWID -*/ -#ifdef SQLITE_ENABLE_STAT4 -static void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){ - assert( db!=0 ); - if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); - p->u.aRowid = sqlite3DbMallocRawNN(db, n); - if( p->u.aRowid ){ - p->nRowid = n; - memcpy(p->u.aRowid, pData, n); - }else{ - p->nRowid = 0; - } -} -#endif - -/* Initialize the INTEGER value of a ROWID. -*/ -#ifdef SQLITE_ENABLE_STAT4 -static void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){ - assert( db!=0 ); - if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid); - p->nRowid = 0; - p->u.iRowid = iRowid; -} -#endif - - -/* -** Copy the contents of object (*pFrom) into (*pTo). -*/ -#ifdef SQLITE_ENABLE_STAT4 -static void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){ - pTo->isPSample = pFrom->isPSample; - pTo->iCol = pFrom->iCol; - pTo->iHash = pFrom->iHash; - memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol); - memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol); - memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol); - if( pFrom->nRowid ){ - sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid); - }else{ - sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid); - } -} -#endif - -/* -** Reclaim all memory of a StatAccum structure. -*/ -static void statAccumDestructor(void *pOld){ - StatAccum *p = (StatAccum*)pOld; -#ifdef SQLITE_ENABLE_STAT4 - if( p->mxSample ){ - int i; - for(i=0; inCol; i++) sampleClear(p->db, p->aBest+i); - for(i=0; imxSample; i++) sampleClear(p->db, p->a+i); - sampleClear(p->db, &p->current); - } -#endif - sqlite3DbFree(p->db, p); -} - -/* -** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters -** are: -** N: The number of columns in the index including the rowid/pk (note 1) -** K: The number of columns in the index excluding the rowid/pk. -** C: Estimated number of rows in the index -** L: A limit on the number of rows to scan, or 0 for no-limit -** -** Note 1: In the special case of the covering index that implements a -** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the -** total number of columns in the table. -** -** For indexes on ordinary rowid tables, N==K+1. But for indexes on -** WITHOUT ROWID tables, N=K+P where P is the number of columns in the -** PRIMARY KEY of the table. The covering index that implements the -** original WITHOUT ROWID table as N==K as a special case. -** -** This routine allocates the StatAccum object in heap memory. The return -** value is a pointer to the StatAccum object. The datatype of the -** return value is BLOB, but it is really just a pointer to the StatAccum -** object. -*/ -static void statInit( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - StatAccum *p; - int nCol; /* Number of columns in index being sampled */ - int nKeyCol; /* Number of key columns */ - int nColUp; /* nCol rounded up for alignment */ - int n; /* Bytes of space to allocate */ - sqlite3 *db = sqlite3_context_db_handle(context); /* Database connection */ -#ifdef SQLITE_ENABLE_STAT4 - /* Maximum number of samples. 0 if STAT4 data is not collected */ - int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0; -#endif - - /* Decode the three function arguments */ - UNUSED_PARAMETER(argc); - nCol = sqlite3_value_int(argv[0]); - assert( nCol>0 ); - nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol; - nKeyCol = sqlite3_value_int(argv[1]); - assert( nKeyCol<=nCol ); - assert( nKeyCol>0 ); - - /* Allocate the space required for the StatAccum object */ - n = sizeof(*p) - + sizeof(tRowcnt)*nColUp /* StatAccum.anEq */ - + sizeof(tRowcnt)*nColUp; /* StatAccum.anDLt */ -#ifdef SQLITE_ENABLE_STAT4 - if( mxSample ){ - n += sizeof(tRowcnt)*nColUp /* StatAccum.anLt */ - + sizeof(StatSample)*(nCol+mxSample) /* StatAccum.aBest[], a[] */ - + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample); - } -#endif - db = sqlite3_context_db_handle(context); - p = sqlite3DbMallocZero(db, n); - if( p==0 ){ - sqlite3_result_error_nomem(context); - return; - } - - p->db = db; - p->nEst = sqlite3_value_int64(argv[2]); - p->nRow = 0; - p->nLimit = sqlite3_value_int64(argv[3]); - p->nCol = nCol; - p->nKeyCol = nKeyCol; - p->nSkipAhead = 0; - p->current.anDLt = (tRowcnt*)&p[1]; - p->current.anEq = &p->current.anDLt[nColUp]; - -#ifdef SQLITE_ENABLE_STAT4 - p->mxSample = p->nLimit==0 ? mxSample : 0; - if( mxSample ){ - u8 *pSpace; /* Allocated space not yet assigned */ - int i; /* Used to iterate through p->aSample[] */ - - p->iGet = -1; - p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1); - p->current.anLt = &p->current.anEq[nColUp]; - p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]); - - /* Set up the StatAccum.a[] and aBest[] arrays */ - p->a = (struct StatSample*)&p->current.anLt[nColUp]; - p->aBest = &p->a[mxSample]; - pSpace = (u8*)(&p->a[mxSample+nCol]); - for(i=0; i<(mxSample+nCol); i++){ - p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); - p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); - p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp); - } - assert( (pSpace - (u8*)p)==n ); - - for(i=0; iaBest[i].iCol = i; - } - } -#endif - - /* Return a pointer to the allocated object to the caller. Note that - ** only the pointer (the 2nd parameter) matters. The size of the object - ** (given by the 3rd parameter) is never used and can be any positive - ** value. */ - sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor); -} -static const FuncDef statInitFuncdef = { - 4, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - statInit, /* xSFunc */ - 0, /* xFinalize */ - 0, 0, /* xValue, xInverse */ - "stat_init", /* zName */ - {0} -}; - -#ifdef SQLITE_ENABLE_STAT4 -/* -** pNew and pOld are both candidate non-periodic samples selected for -** the same column (pNew->iCol==pOld->iCol). Ignoring this column and -** considering only any trailing columns and the sample hash value, this -** function returns true if sample pNew is to be preferred over pOld. -** In other words, if we assume that the cardinalities of the selected -** column for pNew and pOld are equal, is pNew to be preferred over pOld. -** -** This function assumes that for each argument sample, the contents of -** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. -*/ -static int sampleIsBetterPost( - StatAccum *pAccum, - StatSample *pNew, - StatSample *pOld -){ - int nCol = pAccum->nCol; - int i; - assert( pNew->iCol==pOld->iCol ); - for(i=pNew->iCol+1; ianEq[i]>pOld->anEq[i] ) return 1; - if( pNew->anEq[i]anEq[i] ) return 0; - } - if( pNew->iHash>pOld->iHash ) return 1; - return 0; -} -#endif - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Return true if pNew is to be preferred over pOld. -** -** This function assumes that for each argument sample, the contents of -** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. -*/ -static int sampleIsBetter( - StatAccum *pAccum, - StatSample *pNew, - StatSample *pOld -){ - tRowcnt nEqNew = pNew->anEq[pNew->iCol]; - tRowcnt nEqOld = pOld->anEq[pOld->iCol]; - - assert( pOld->isPSample==0 && pNew->isPSample==0 ); - assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) ); - - if( (nEqNew>nEqOld) ) return 1; - if( nEqNew==nEqOld ){ - if( pNew->iColiCol ) return 1; - return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld)); - } - return 0; -} - -/* -** Copy the contents of sample *pNew into the p->a[] array. If necessary, -** remove the least desirable sample from p->a[] to make room. -*/ -static void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){ - StatSample *pSample = 0; - int i; - - assert( IsStat4 || nEqZero==0 ); - - /* StatAccum.nMaxEqZero is set to the maximum number of leading 0 - ** values in the anEq[] array of any sample in StatAccum.a[]. In - ** other words, if nMaxEqZero is n, then it is guaranteed that there - ** are no samples with StatSample.anEq[m]==0 for (m>=n). */ - if( nEqZero>p->nMaxEqZero ){ - p->nMaxEqZero = nEqZero; - } - if( pNew->isPSample==0 ){ - StatSample *pUpgrade = 0; - assert( pNew->anEq[pNew->iCol]>0 ); - - /* This sample is being added because the prefix that ends in column - ** iCol occurs many times in the table. However, if we have already - ** added a sample that shares this prefix, there is no need to add - ** this one. Instead, upgrade the priority of the highest priority - ** existing sample that shares this prefix. */ - for(i=p->nSample-1; i>=0; i--){ - StatSample *pOld = &p->a[i]; - if( pOld->anEq[pNew->iCol]==0 ){ - if( pOld->isPSample ) return; - assert( pOld->iCol>pNew->iCol ); - assert( sampleIsBetter(p, pNew, pOld) ); - if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){ - pUpgrade = pOld; - } - } - } - if( pUpgrade ){ - pUpgrade->iCol = pNew->iCol; - pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol]; - goto find_new_min; - } - } - - /* If necessary, remove sample iMin to make room for the new sample. */ - if( p->nSample>=p->mxSample ){ - StatSample *pMin = &p->a[p->iMin]; - tRowcnt *anEq = pMin->anEq; - tRowcnt *anLt = pMin->anLt; - tRowcnt *anDLt = pMin->anDLt; - sampleClear(p->db, pMin); - memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1)); - pSample = &p->a[p->nSample-1]; - pSample->nRowid = 0; - pSample->anEq = anEq; - pSample->anDLt = anDLt; - pSample->anLt = anLt; - p->nSample = p->mxSample-1; - } - - /* The "rows less-than" for the rowid column must be greater than that - ** for the last sample in the p->a[] array. Otherwise, the samples would - ** be out of order. */ - assert( p->nSample==0 - || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] ); - - /* Insert the new sample */ - pSample = &p->a[p->nSample]; - sampleCopy(p, pSample, pNew); - p->nSample++; - - /* Zero the first nEqZero entries in the anEq[] array. */ - memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero); - -find_new_min: - if( p->nSample>=p->mxSample ){ - int iMin = -1; - for(i=0; imxSample; i++){ - if( p->a[i].isPSample ) continue; - if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){ - iMin = i; - } - } - assert( iMin>=0 ); - p->iMin = iMin; - } -} -#endif /* SQLITE_ENABLE_STAT4 */ - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Field iChng of the index being scanned has changed. So at this point -** p->current contains a sample that reflects the previous row of the -** index. The value of anEq[iChng] and subsequent anEq[] elements are -** correct at this point. -*/ -static void samplePushPrevious(StatAccum *p, int iChng){ - int i; - - /* Check if any samples from the aBest[] array should be pushed - ** into IndexSample.a[] at this point. */ - for(i=(p->nCol-2); i>=iChng; i--){ - StatSample *pBest = &p->aBest[i]; - pBest->anEq[i] = p->current.anEq[i]; - if( p->nSamplemxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){ - sampleInsert(p, pBest, i); - } - } - - /* Check that no sample contains an anEq[] entry with an index of - ** p->nMaxEqZero or greater set to zero. */ - for(i=p->nSample-1; i>=0; i--){ - int j; - for(j=p->nMaxEqZero; jnCol; j++) assert( p->a[i].anEq[j]>0 ); - } - - /* Update the anEq[] fields of any samples already collected. */ - if( iChngnMaxEqZero ){ - for(i=p->nSample-1; i>=0; i--){ - int j; - for(j=iChng; jnCol; j++){ - if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j]; - } - } - p->nMaxEqZero = iChng; - } -} -#endif /* SQLITE_ENABLE_STAT4 */ - -/* -** Implementation of the stat_push SQL function: stat_push(P,C,R) -** Arguments: -** -** P Pointer to the StatAccum object created by stat_init() -** C Index of left-most column to differ from previous row -** R Rowid for the current row. Might be a key record for -** WITHOUT ROWID tables. -** -** The purpose of this routine is to collect statistical data and/or -** samples from the index being analyzed into the StatAccum object. -** The stat_get() SQL function will be used afterwards to -** retrieve the information gathered. -** -** This SQL function usually returns NULL, but might return an integer -** if it wants the byte-code to do special processing. -** -** The R parameter is only used for STAT4 -*/ -static void statPush( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int i; - - /* The three function arguments */ - StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]); - int iChng = sqlite3_value_int(argv[1]); - - UNUSED_PARAMETER( argc ); - UNUSED_PARAMETER( context ); - assert( p->nCol>0 ); - assert( iChngnCol ); - - if( p->nRow==0 ){ - /* This is the first call to this function. Do initialization. */ - for(i=0; inCol; i++) p->current.anEq[i] = 1; - }else{ - /* Second and subsequent calls get processed here */ -#ifdef SQLITE_ENABLE_STAT4 - if( p->mxSample ) samplePushPrevious(p, iChng); -#endif - - /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply - ** to the current row of the index. */ - for(i=0; icurrent.anEq[i]++; - } - for(i=iChng; inCol; i++){ - p->current.anDLt[i]++; -#ifdef SQLITE_ENABLE_STAT4 - if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i]; -#endif - p->current.anEq[i] = 1; - } - } - - p->nRow++; -#ifdef SQLITE_ENABLE_STAT4 - if( p->mxSample ){ - tRowcnt nLt; - if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){ - sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2])); - }else{ - sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]), - sqlite3_value_blob(argv[2])); - } - p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345; - - nLt = p->current.anLt[p->nCol-1]; - /* Check if this is to be a periodic sample. If so, add it. */ - if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){ - p->current.isPSample = 1; - p->current.iCol = 0; - sampleInsert(p, &p->current, p->nCol-1); - p->current.isPSample = 0; - } - - /* Update the aBest[] array. */ - for(i=0; i<(p->nCol-1); i++){ - p->current.iCol = i; - if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){ - sampleCopy(p, &p->aBest[i], &p->current); - } - } - }else -#endif - if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){ - p->nSkipAhead++; - sqlite3_result_int(context, p->current.anDLt[0]>0); - } -} - -static const FuncDef statPushFuncdef = { - 2+IsStat4, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - statPush, /* xSFunc */ - 0, /* xFinalize */ - 0, 0, /* xValue, xInverse */ - "stat_push", /* zName */ - {0} -}; - -#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */ -#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */ -#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */ -#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */ -#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */ - -/* -** Implementation of the stat_get(P,J) SQL function. This routine is -** used to query statistical information that has been gathered into -** the StatAccum object by prior calls to stat_push(). The P parameter -** has type BLOB but it is really just a pointer to the StatAccum object. -** The content to returned is determined by the parameter J -** which is one of the STAT_GET_xxxx values defined above. -** -** The stat_get(P,J) function is not available to generic SQL. It is -** inserted as part of a manually constructed bytecode program. (See -** the callStatGet() routine below.) It is guaranteed that the P -** parameter will always be a pointer to a StatAccum object, never a -** NULL. -** -** If STAT4 is not enabled, then J is always -** STAT_GET_STAT1 and is hence omitted and this routine becomes -** a one-parameter function, stat_get(P), that always returns the -** stat1 table entry information. -*/ -static void statGet( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]); -#ifdef SQLITE_ENABLE_STAT4 - /* STAT4 has a parameter on this routine. */ - int eCall = sqlite3_value_int(argv[1]); - assert( argc==2 ); - assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ - || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT - || eCall==STAT_GET_NDLT - ); - assert( eCall==STAT_GET_STAT1 || p->mxSample ); - if( eCall==STAT_GET_STAT1 ) -#else - assert( argc==1 ); -#endif - { - /* Return the value to store in the "stat" column of the sqlite_stat1 - ** table for this index. - ** - ** The value is a string composed of a list of integers describing - ** the index. The first integer in the list is the total number of - ** entries in the index. There is one additional integer in the list - ** for each indexed column. This additional integer is an estimate of - ** the number of rows matched by a equality query on the index using - ** a key with the corresponding number of fields. In other words, - ** if the index is on columns (a,b) and the sqlite_stat1 value is - ** "100 10 2", then SQLite estimates that: - ** - ** * the index contains 100 rows, - ** * "WHERE a=?" matches 10 rows, and - ** * "WHERE a=? AND b=?" matches 2 rows. - ** - ** If D is the count of distinct values and K is the total number of - ** rows, then each estimate is computed as: - ** - ** I = (K+D-1)/D - */ - char *z; - int i; - - char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 ); - if( zRet==0 ){ - sqlite3_result_error_nomem(context); - return; - } - - sqlite3_snprintf(24, zRet, "%llu", - p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow); - z = zRet + sqlite3Strlen30(zRet); - for(i=0; inKeyCol; i++){ - u64 nDistinct = p->current.anDLt[i] + 1; - u64 iVal = (p->nRow + nDistinct - 1) / nDistinct; - sqlite3_snprintf(24, z, " %llu", iVal); - z += sqlite3Strlen30(z); - assert( p->current.anEq[i] ); - } - assert( z[0]=='\0' && z>zRet ); - - sqlite3_result_text(context, zRet, -1, sqlite3_free); - } -#ifdef SQLITE_ENABLE_STAT4 - else if( eCall==STAT_GET_ROWID ){ - if( p->iGet<0 ){ - samplePushPrevious(p, 0); - p->iGet = 0; - } - if( p->iGetnSample ){ - StatSample *pS = p->a + p->iGet; - if( pS->nRowid==0 ){ - sqlite3_result_int64(context, pS->u.iRowid); - }else{ - sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid, - SQLITE_TRANSIENT); - } - } - }else{ - tRowcnt *aCnt = 0; - - assert( p->iGetnSample ); - switch( eCall ){ - case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break; - case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break; - default: { - aCnt = p->a[p->iGet].anDLt; - p->iGet++; - break; - } - } - - { - char *zRet = sqlite3MallocZero(p->nCol * 25); - if( zRet==0 ){ - sqlite3_result_error_nomem(context); - }else{ - int i; - char *z = zRet; - for(i=0; inCol; i++){ - sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]); - z += sqlite3Strlen30(z); - } - assert( z[0]=='\0' && z>zRet ); - z[-1] = '\0'; - sqlite3_result_text(context, zRet, -1, sqlite3_free); - } - } - } -#endif /* SQLITE_ENABLE_STAT4 */ -#ifndef SQLITE_DEBUG - UNUSED_PARAMETER( argc ); -#endif -} -static const FuncDef statGetFuncdef = { - 1+IsStat4, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - statGet, /* xSFunc */ - 0, /* xFinalize */ - 0, 0, /* xValue, xInverse */ - "stat_get", /* zName */ - {0} -}; - -static void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){ -#ifdef SQLITE_ENABLE_STAT4 - sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1); -#elif SQLITE_DEBUG - assert( iParam==STAT_GET_STAT1 ); -#else - UNUSED_PARAMETER( iParam ); -#endif - assert( regOut!=regStat && regOut!=regStat+1 ); - sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4, - &statGetFuncdef, 0); -} - -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS -/* Add a comment to the most recent VDBE opcode that is the name -** of the k-th column of the pIdx index. -*/ -static void analyzeVdbeCommentIndexWithColumnName( - Vdbe *v, /* Prepared statement under construction */ - Index *pIdx, /* Index whose column is being loaded */ - int k /* Which column index */ -){ - int i; /* Index of column in the table */ - assert( k>=0 && knColumn ); - i = pIdx->aiColumn[k]; - if( NEVER(i==XN_ROWID) ){ - VdbeComment((v,"%s.rowid",pIdx->zName)); - }else if( i==XN_EXPR ){ - VdbeComment((v,"%s.expr(%d)",pIdx->zName, k)); - }else{ - VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zName)); - } -} -#else -# define analyzeVdbeCommentIndexWithColumnName(a,b,c) -#endif /* SQLITE_DEBUG */ - -/* -** Generate code to do an analysis of all indices associated with -** a single table. -*/ -static void analyzeOneTable( - Parse *pParse, /* Parser context */ - Table *pTab, /* Table whose indices are to be analyzed */ - Index *pOnlyIdx, /* If not NULL, only analyze this one index */ - int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ - int iMem, /* Available memory locations begin here */ - int iTab /* Next available cursor */ -){ - sqlite3 *db = pParse->db; /* Database handle */ - Index *pIdx; /* An index to being analyzed */ - int iIdxCur; /* Cursor open on index being analyzed */ - int iTabCur; /* Table cursor */ - Vdbe *v; /* The virtual machine being built up */ - int i; /* Loop counter */ - int jZeroRows = -1; /* Jump from here if number of rows is zero */ - int iDb; /* Index of database containing pTab */ - u8 needTableCnt = 1; /* True to count the table */ - int regNewRowid = iMem++; /* Rowid for the inserted record */ - int regStat = iMem++; /* Register to hold StatAccum object */ - int regChng = iMem++; /* Index of changed index field */ - int regRowid = iMem++; /* Rowid argument passed to stat_push() */ - int regTemp = iMem++; /* Temporary use register */ - int regTemp2 = iMem++; /* Second temporary use register */ - int regTabname = iMem++; /* Register containing table name */ - int regIdxname = iMem++; /* Register containing index name */ - int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */ - int regPrev = iMem; /* MUST BE LAST (see below) */ -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - Table *pStat1 = 0; -#endif - - pParse->nMem = MAX(pParse->nMem, iMem); - v = sqlite3GetVdbe(pParse); - if( v==0 || NEVER(pTab==0) ){ - return; - } - if( pTab->tnum==0 ){ - /* Do not gather statistics on views or virtual tables */ - return; - } - if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){ - /* Do not gather statistics on system tables */ - return; - } - assert( sqlite3BtreeHoldsAllMutexes(db) ); - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - assert( iDb>=0 ); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); -#ifndef SQLITE_OMIT_AUTHORIZATION - if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0, - db->aDb[iDb].zDbSName ) ){ - return; - } -#endif - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - if( db->xPreUpdateCallback ){ - pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13); - if( pStat1==0 ) return; - pStat1->zName = (char*)&pStat1[1]; - memcpy(pStat1->zName, "sqlite_stat1", 13); - pStat1->nCol = 3; - pStat1->iPKey = -1; - sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB); - } -#endif - - /* Establish a read-lock on the table at the shared-cache level. - ** Open a read-only cursor on the table. Also allocate a cursor number - ** to use for scanning indexes (iIdxCur). No index cursor is opened at - ** this time though. */ - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); - iTabCur = iTab++; - iIdxCur = iTab++; - pParse->nTab = MAX(pParse->nTab, iTab); - sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); - sqlite3VdbeLoadString(v, regTabname, pTab->zName); - - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - int nCol; /* Number of columns in pIdx. "N" */ - int addrRewind; /* Address of "OP_Rewind iIdxCur" */ - int addrNextRow; /* Address of "next_row:" */ - const char *zIdxName; /* Name of the index */ - int nColTest; /* Number of columns to test for changes */ - - if( pOnlyIdx && pOnlyIdx!=pIdx ) continue; - if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0; - if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){ - nCol = pIdx->nKeyCol; - zIdxName = pTab->zName; - nColTest = nCol - 1; - }else{ - nCol = pIdx->nColumn; - zIdxName = pIdx->zName; - nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1; - } - - /* Populate the register containing the index name. */ - sqlite3VdbeLoadString(v, regIdxname, zIdxName); - VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName)); - - /* - ** Pseudo-code for loop that calls stat_push(): - ** - ** Rewind csr - ** if eof(csr) goto end_of_scan; - ** regChng = 0 - ** goto chng_addr_0; - ** - ** next_row: - ** regChng = 0 - ** if( idx(0) != regPrev(0) ) goto chng_addr_0 - ** regChng = 1 - ** if( idx(1) != regPrev(1) ) goto chng_addr_1 - ** ... - ** regChng = N - ** goto chng_addr_N - ** - ** chng_addr_0: - ** regPrev(0) = idx(0) - ** chng_addr_1: - ** regPrev(1) = idx(1) - ** ... - ** - ** endDistinctTest: - ** regRowid = idx(rowid) - ** stat_push(P, regChng, regRowid) - ** Next csr - ** if !eof(csr) goto next_row; - ** - ** end_of_scan: - */ - - /* Make sure there are enough memory cells allocated to accommodate - ** the regPrev array and a trailing rowid (the rowid slot is required - ** when building a record to insert into the sample column of - ** the sqlite_stat4 table. */ - pParse->nMem = MAX(pParse->nMem, regPrev+nColTest); - - /* Open a read-only cursor on the index being analyzed. */ - assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) ); - sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); - VdbeComment((v, "%s", pIdx->zName)); - - /* Invoke the stat_init() function. The arguments are: - ** - ** (1) the number of columns in the index including the rowid - ** (or for a WITHOUT ROWID table, the number of PK columns), - ** (2) the number of columns in the key without the rowid/pk - ** (3) estimated number of rows in the index, - */ - sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1); - assert( regRowid==regStat+2 ); - sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid); -#ifdef SQLITE_ENABLE_STAT4 - if( OptimizationEnabled(db, SQLITE_Stat4) ){ - sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regTemp); - addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); - VdbeCoverage(v); - }else -#endif - { - addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp, 1); - } - assert( regTemp2==regStat+4 ); - sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2); - sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4, - &statInitFuncdef, 0); - - /* Implementation of the following: - ** - ** Rewind csr - ** if eof(csr) goto end_of_scan; - ** regChng = 0 - ** goto next_push_0; - ** - */ - sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); - addrNextRow = sqlite3VdbeCurrentAddr(v); - - if( nColTest>0 ){ - int endDistinctTest = sqlite3VdbeMakeLabel(pParse); - int *aGotoChng; /* Array of jump instruction addresses */ - aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest); - if( aGotoChng==0 ) continue; - - /* - ** next_row: - ** regChng = 0 - ** if( idx(0) != regPrev(0) ) goto chng_addr_0 - ** regChng = 1 - ** if( idx(1) != regPrev(1) ) goto chng_addr_1 - ** ... - ** regChng = N - ** goto endDistinctTest - */ - sqlite3VdbeAddOp0(v, OP_Goto); - addrNextRow = sqlite3VdbeCurrentAddr(v); - if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){ - /* For a single-column UNIQUE index, once we have found a non-NULL - ** row, we know that all the rest will be distinct, so skip - ** subsequent distinctness tests. */ - sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest); - VdbeCoverage(v); - } - for(i=0; iazColl[i]); - sqlite3VdbeAddOp2(v, OP_Integer, i, regChng); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp); - analyzeVdbeCommentIndexWithColumnName(v,pIdx,i); - aGotoChng[i] = - sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ); - sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); - VdbeCoverage(v); - } - sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng); - sqlite3VdbeGoto(v, endDistinctTest); - - - /* - ** chng_addr_0: - ** regPrev(0) = idx(0) - ** chng_addr_1: - ** regPrev(1) = idx(1) - ** ... - */ - sqlite3VdbeJumpHere(v, addrNextRow-1); - for(i=0; ipTable); - int j, k, regKey; - regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol); - for(j=0; jnKeyCol; j++){ - k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]); - assert( k>=0 && knColumn ); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j); - analyzeVdbeCommentIndexWithColumnName(v,pIdx,k); - } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid); - sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol); - } - } -#endif - assert( regChng==(regStat+1) ); - { - sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4, - &statPushFuncdef, 0); - if( db->nAnalysisLimit ){ - int j1, j2, j3; - j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v); - j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v); - j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1); - VdbeCoverage(v); - sqlite3VdbeJumpHere(v, j1); - sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, j2); - sqlite3VdbeJumpHere(v, j3); - }else{ - sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v); - } - } - - /* Add the entry to the stat1 table. */ - callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1); - assert( "BBB"[0]==SQLITE_AFF_TEXT ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); - sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE); -#endif - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - - /* Add the entries to the stat4 table. */ -#ifdef SQLITE_ENABLE_STAT4 - if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){ - int regEq = regStat1; - int regLt = regStat1+1; - int regDLt = regStat1+2; - int regSample = regStat1+3; - int regCol = regStat1+4; - int regSampleRowid = regCol + nCol; - int addrNext; - int addrIsNull; - u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound; - - pParse->nMem = MAX(pParse->nMem, regCol+nCol); - - addrNext = sqlite3VdbeCurrentAddr(v); - callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid); - addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); - VdbeCoverage(v); - callStatGet(pParse, regStat, STAT_GET_NEQ, regEq); - callStatGet(pParse, regStat, STAT_GET_NLT, regLt); - callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt); - sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0); - VdbeCoverage(v); - for(i=0; izName)); - sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1); - jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname); - assert( "BBB"[0]==SQLITE_AFF_TEXT ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0); - sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE); -#endif - sqlite3VdbeJumpHere(v, jZeroRows); - } -} - - -/* -** Generate code that will cause the most recent index analysis to -** be loaded into internal hash tables where is can be used. -*/ -static void loadAnalysis(Parse *pParse, int iDb){ - Vdbe *v = sqlite3GetVdbe(pParse); - if( v ){ - sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); - } -} - -/* -** Generate code that will do an analysis of an entire database -*/ -static void analyzeDatabase(Parse *pParse, int iDb){ - sqlite3 *db = pParse->db; - Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */ - HashElem *k; - int iStatCur; - int iMem; - int iTab; - - sqlite3BeginWriteOperation(pParse, 0, iDb); - iStatCur = pParse->nTab; - pParse->nTab += 3; - openStatTable(pParse, iDb, iStatCur, 0, 0); - iMem = pParse->nMem+1; - iTab = pParse->nTab; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ - Table *pTab = (Table*)sqliteHashData(k); - analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab); - } - loadAnalysis(pParse, iDb); -} - -/* -** Generate code that will do an analysis of a single table in -** a database. If pOnlyIdx is not NULL then it is a single index -** in pTab that should be analyzed. -*/ -static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){ - int iDb; - int iStatCur; - - assert( pTab!=0 ); - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - sqlite3BeginWriteOperation(pParse, 0, iDb); - iStatCur = pParse->nTab; - pParse->nTab += 3; - if( pOnlyIdx ){ - openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx"); - }else{ - openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl"); - } - analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab); - loadAnalysis(pParse, iDb); -} - -/* -** Generate code for the ANALYZE command. The parser calls this routine -** when it recognizes an ANALYZE command. -** -** ANALYZE -- 1 -** ANALYZE -- 2 -** ANALYZE ?.? -- 3 -** -** Form 1 causes all indices in all attached databases to be analyzed. -** Form 2 analyzes all indices the single database named. -** Form 3 analyzes all indices associated with the named table. -*/ -SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ - sqlite3 *db = pParse->db; - int iDb; - int i; - char *z, *zDb; - Table *pTab; - Index *pIdx; - Token *pTableName; - Vdbe *v; - - /* Read the database schema. If an error occurs, leave an error message - ** and code in pParse and return NULL. */ - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ - return; - } - - assert( pName2!=0 || pName1==0 ); - if( pName1==0 ){ - /* Form 1: Analyze everything */ - for(i=0; inDb; i++){ - if( i==1 ) continue; /* Do not analyze the TEMP database */ - analyzeDatabase(pParse, i); - } - }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){ - /* Analyze the schema named as the argument */ - analyzeDatabase(pParse, iDb); - }else{ - /* Form 3: Analyze the table or index named as an argument */ - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName); - if( iDb>=0 ){ - zDb = pName2->n ? db->aDb[iDb].zDbSName : 0; - z = sqlite3NameFromToken(db, pTableName); - if( z ){ - if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){ - analyzeTable(pParse, pIdx->pTable, pIdx); - }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){ - analyzeTable(pParse, pTab, 0); - } - sqlite3DbFree(db, z); - } - } - } - if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){ - sqlite3VdbeAddOp0(v, OP_Expire); - } -} - -/* -** Used to pass information from the analyzer reader through to the -** callback routine. -*/ -typedef struct analysisInfo analysisInfo; -struct analysisInfo { - sqlite3 *db; - const char *zDatabase; -}; - -/* -** The first argument points to a nul-terminated string containing a -** list of space separated integers. Read the first nOut of these into -** the array aOut[]. -*/ -static void decodeIntArray( - char *zIntArray, /* String containing int array to decode */ - int nOut, /* Number of slots in aOut[] */ - tRowcnt *aOut, /* Store integers here */ - LogEst *aLog, /* Or, if aOut==0, here */ - Index *pIndex /* Handle extra flags for this index, if not NULL */ -){ - char *z = zIntArray; - int c; - int i; - tRowcnt v; - -#ifdef SQLITE_ENABLE_STAT4 - if( z==0 ) z = ""; -#else - assert( z!=0 ); -#endif - for(i=0; *z && i='0' && c<='9' ){ - v = v*10 + c - '0'; - z++; - } -#ifdef SQLITE_ENABLE_STAT4 - if( aOut ) aOut[i] = v; - if( aLog ) aLog[i] = sqlite3LogEst(v); -#else - assert( aOut==0 ); - UNUSED_PARAMETER(aOut); - assert( aLog!=0 ); - aLog[i] = sqlite3LogEst(v); -#endif - if( *z==' ' ) z++; - } -#ifndef SQLITE_ENABLE_STAT4 - assert( pIndex!=0 ); { -#else - if( pIndex ){ -#endif - pIndex->bUnordered = 0; - pIndex->noSkipScan = 0; - while( z[0] ){ - if( sqlite3_strglob("unordered*", z)==0 ){ - pIndex->bUnordered = 1; - }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){ - int sz = sqlite3Atoi(z+3); - if( sz<2 ) sz = 2; - pIndex->szIdxRow = sqlite3LogEst(sz); - }else if( sqlite3_strglob("noskipscan*", z)==0 ){ - pIndex->noSkipScan = 1; - } -#ifdef SQLITE_ENABLE_COSTMULT - else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){ - pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9)); - } -#endif - while( z[0]!=0 && z[0]!=' ' ) z++; - while( z[0]==' ' ) z++; - } - } -} - -/* -** This callback is invoked once for each index when reading the -** sqlite_stat1 table. -** -** argv[0] = name of the table -** argv[1] = name of the index (might be NULL) -** argv[2] = results of analysis - on integer for each column -** -** Entries for which argv[1]==NULL simply record the number of rows in -** the table. -*/ -static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){ - analysisInfo *pInfo = (analysisInfo*)pData; - Index *pIndex; - Table *pTable; - const char *z; - - assert( argc==3 ); - UNUSED_PARAMETER2(NotUsed, argc); - - if( argv==0 || argv[0]==0 || argv[2]==0 ){ - return 0; - } - pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase); - if( pTable==0 ){ - return 0; - } - if( argv[1]==0 ){ - pIndex = 0; - }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){ - pIndex = sqlite3PrimaryKeyIndex(pTable); - }else{ - pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase); - } - z = argv[2]; - - if( pIndex ){ - tRowcnt *aiRowEst = 0; - int nCol = pIndex->nKeyCol+1; -#ifdef SQLITE_ENABLE_STAT4 - /* Index.aiRowEst may already be set here if there are duplicate - ** sqlite_stat1 entries for this index. In that case just clobber - ** the old data with the new instead of allocating a new array. */ - if( pIndex->aiRowEst==0 ){ - pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol); - if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db); - } - aiRowEst = pIndex->aiRowEst; -#endif - pIndex->bUnordered = 0; - decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex); - pIndex->hasStat1 = 1; - if( pIndex->pPartIdxWhere==0 ){ - pTable->nRowLogEst = pIndex->aiRowLogEst[0]; - pTable->tabFlags |= TF_HasStat1; - } - }else{ - Index fakeIdx; - fakeIdx.szIdxRow = pTable->szTabRow; -#ifdef SQLITE_ENABLE_COSTMULT - fakeIdx.pTable = pTable; -#endif - decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx); - pTable->szTabRow = fakeIdx.szIdxRow; - pTable->tabFlags |= TF_HasStat1; - } - - return 0; -} - -/* -** If the Index.aSample variable is not NULL, delete the aSample[] array -** and its contents. -*/ -SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){ -#ifdef SQLITE_ENABLE_STAT4 - if( pIdx->aSample ){ - int j; - for(j=0; jnSample; j++){ - IndexSample *p = &pIdx->aSample[j]; - sqlite3DbFree(db, p->p); - } - sqlite3DbFree(db, pIdx->aSample); - } - if( db && db->pnBytesFreed==0 ){ - pIdx->nSample = 0; - pIdx->aSample = 0; - } -#else - UNUSED_PARAMETER(db); - UNUSED_PARAMETER(pIdx); -#endif /* SQLITE_ENABLE_STAT4 */ -} - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Populate the pIdx->aAvgEq[] array based on the samples currently -** stored in pIdx->aSample[]. -*/ -static void initAvgEq(Index *pIdx){ - if( pIdx ){ - IndexSample *aSample = pIdx->aSample; - IndexSample *pFinal = &aSample[pIdx->nSample-1]; - int iCol; - int nCol = 1; - if( pIdx->nSampleCol>1 ){ - /* If this is stat4 data, then calculate aAvgEq[] values for all - ** sample columns except the last. The last is always set to 1, as - ** once the trailing PK fields are considered all index keys are - ** unique. */ - nCol = pIdx->nSampleCol-1; - pIdx->aAvgEq[nCol] = 1; - } - for(iCol=0; iColnSample; - int i; /* Used to iterate through samples */ - tRowcnt sumEq = 0; /* Sum of the nEq values */ - tRowcnt avgEq = 0; - tRowcnt nRow; /* Number of rows in index */ - i64 nSum100 = 0; /* Number of terms contributing to sumEq */ - i64 nDist100; /* Number of distinct values in index */ - - if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){ - nRow = pFinal->anLt[iCol]; - nDist100 = (i64)100 * pFinal->anDLt[iCol]; - nSample--; - }else{ - nRow = pIdx->aiRowEst[0]; - nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1]; - } - pIdx->nRowEst0 = nRow; - - /* Set nSum to the number of distinct (iCol+1) field prefixes that - ** occur in the stat4 table for this index. Set sumEq to the sum of - ** the nEq values for column iCol for the same set (adding the value - ** only once where there exist duplicate prefixes). */ - for(i=0; inSample-1) - || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] - ){ - sumEq += aSample[i].anEq[iCol]; - nSum100 += 100; - } - } - - if( nDist100>nSum100 && sumEqaAvgEq[iCol] = avgEq; - } - } -} - -/* -** Look up an index by name. Or, if the name of a WITHOUT ROWID table -** is supplied instead, find the PRIMARY KEY index for that table. -*/ -static Index *findIndexOrPrimaryKey( - sqlite3 *db, - const char *zName, - const char *zDb -){ - Index *pIdx = sqlite3FindIndex(db, zName, zDb); - if( pIdx==0 ){ - Table *pTab = sqlite3FindTable(db, zName, zDb); - if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab); - } - return pIdx; -} - -/* -** Load the content from either the sqlite_stat4 -** into the relevant Index.aSample[] arrays. -** -** Arguments zSql1 and zSql2 must point to SQL statements that return -** data equivalent to the following: -** -** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx -** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4 -** -** where %Q is replaced with the database name before the SQL is executed. -*/ -static int loadStatTbl( - sqlite3 *db, /* Database handle */ - const char *zSql1, /* SQL statement 1 (see above) */ - const char *zSql2, /* SQL statement 2 (see above) */ - const char *zDb /* Database name (e.g. "main") */ -){ - int rc; /* Result codes from subroutines */ - sqlite3_stmt *pStmt = 0; /* An SQL statement being run */ - char *zSql; /* Text of the SQL statement */ - Index *pPrevIdx = 0; /* Previous index in the loop */ - IndexSample *pSample; /* A slot in pIdx->aSample[] */ - - assert( db->lookaside.bDisable ); - zSql = sqlite3MPrintf(db, zSql1, zDb); - if( !zSql ){ - return SQLITE_NOMEM_BKPT; - } - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); - sqlite3DbFree(db, zSql); - if( rc ) return rc; - - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - int nIdxCol = 1; /* Number of columns in stat4 records */ - - char *zIndex; /* Index name */ - Index *pIdx; /* Pointer to the index object */ - int nSample; /* Number of samples */ - int nByte; /* Bytes of space required */ - int i; /* Bytes of space required */ - tRowcnt *pSpace; - - zIndex = (char *)sqlite3_column_text(pStmt, 0); - if( zIndex==0 ) continue; - nSample = sqlite3_column_int(pStmt, 1); - pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); - assert( pIdx==0 || pIdx->nSample==0 ); - if( pIdx==0 ) continue; - assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 ); - if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){ - nIdxCol = pIdx->nKeyCol; - }else{ - nIdxCol = pIdx->nColumn; - } - pIdx->nSampleCol = nIdxCol; - nByte = sizeof(IndexSample) * nSample; - nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample; - nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */ - - pIdx->aSample = sqlite3DbMallocZero(db, nByte); - if( pIdx->aSample==0 ){ - sqlite3_finalize(pStmt); - return SQLITE_NOMEM_BKPT; - } - pSpace = (tRowcnt*)&pIdx->aSample[nSample]; - pIdx->aAvgEq = pSpace; pSpace += nIdxCol; - for(i=0; iaSample[i].anEq = pSpace; pSpace += nIdxCol; - pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol; - pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol; - } - assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) ); - } - rc = sqlite3_finalize(pStmt); - if( rc ) return rc; - - zSql = sqlite3MPrintf(db, zSql2, zDb); - if( !zSql ){ - return SQLITE_NOMEM_BKPT; - } - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); - sqlite3DbFree(db, zSql); - if( rc ) return rc; - - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - char *zIndex; /* Index name */ - Index *pIdx; /* Pointer to the index object */ - int nCol = 1; /* Number of columns in index */ - - zIndex = (char *)sqlite3_column_text(pStmt, 0); - if( zIndex==0 ) continue; - pIdx = findIndexOrPrimaryKey(db, zIndex, zDb); - if( pIdx==0 ) continue; - /* This next condition is true if data has already been loaded from - ** the sqlite_stat4 table. */ - nCol = pIdx->nSampleCol; - if( pIdx!=pPrevIdx ){ - initAvgEq(pPrevIdx); - pPrevIdx = pIdx; - } - pSample = &pIdx->aSample[pIdx->nSample]; - decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0); - decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0); - decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0); - - /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer. - ** This is in case the sample record is corrupted. In that case, the - ** sqlite3VdbeRecordCompare() may read up to two varints past the - ** end of the allocated buffer before it realizes it is dealing with - ** a corrupt record. Adding the two 0x00 bytes prevents this from causing - ** a buffer overread. */ - pSample->n = sqlite3_column_bytes(pStmt, 4); - pSample->p = sqlite3DbMallocZero(db, pSample->n + 2); - if( pSample->p==0 ){ - sqlite3_finalize(pStmt); - return SQLITE_NOMEM_BKPT; - } - if( pSample->n ){ - memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n); - } - pIdx->nSample++; - } - rc = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ) initAvgEq(pPrevIdx); - return rc; -} - -/* -** Load content from the sqlite_stat4 table into -** the Index.aSample[] arrays of all indices. -*/ -static int loadStat4(sqlite3 *db, const char *zDb){ - int rc = SQLITE_OK; /* Result codes from subroutines */ - - assert( db->lookaside.bDisable ); - if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){ - rc = loadStatTbl(db, - "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", - "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4", - zDb - ); - } - return rc; -} -#endif /* SQLITE_ENABLE_STAT4 */ - -/* -** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The -** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] -** arrays. The contents of sqlite_stat4 are used to populate the -** Index.aSample[] arrays. -** -** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR -** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined -** during compilation and the sqlite_stat4 table is present, no data is -** read from it. -** -** If SQLITE_ENABLE_STAT4 was defined during compilation and the -** sqlite_stat4 table is not present in the database, SQLITE_ERROR is -** returned. However, in this case, data is read from the sqlite_stat1 -** table (if it is present) before returning. -** -** If an OOM error occurs, this function always sets db->mallocFailed. -** This means if the caller does not care about other errors, the return -** code may be ignored. -*/ -SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ - analysisInfo sInfo; - HashElem *i; - char *zSql; - int rc = SQLITE_OK; - Schema *pSchema = db->aDb[iDb].pSchema; - - assert( iDb>=0 && iDbnDb ); - assert( db->aDb[iDb].pBt!=0 ); - - /* Clear any prior statistics */ - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){ - Table *pTab = sqliteHashData(i); - pTab->tabFlags &= ~TF_HasStat1; - } - for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){ - Index *pIdx = sqliteHashData(i); - pIdx->hasStat1 = 0; -#ifdef SQLITE_ENABLE_STAT4 - sqlite3DeleteIndexSamples(db, pIdx); - pIdx->aSample = 0; -#endif - } - - /* Load new statistics out of the sqlite_stat1 table */ - sInfo.db = db; - sInfo.zDatabase = db->aDb[iDb].zDbSName; - if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){ - zSql = sqlite3MPrintf(db, - "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase); - if( zSql==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); - sqlite3DbFree(db, zSql); - } - } - - /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */ - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){ - Index *pIdx = sqliteHashData(i); - if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx); - } - - /* Load the statistics from the sqlite_stat4 table. */ -#ifdef SQLITE_ENABLE_STAT4 - if( rc==SQLITE_OK ){ - DisableLookaside; - rc = loadStat4(db, sInfo.zDatabase); - EnableLookaside; - } - for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){ - Index *pIdx = sqliteHashData(i); - sqlite3_free(pIdx->aiRowEst); - pIdx->aiRowEst = 0; - } -#endif - - if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); - } - return rc; -} - - -#endif /* SQLITE_OMIT_ANALYZE */ - -/************** End of analyze.c *********************************************/ -/************** Begin file attach.c ******************************************/ -/* -** 2003 April 6 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code used to implement the ATTACH and DETACH commands. -*/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_OMIT_ATTACH -/* -** Resolve an expression that was part of an ATTACH or DETACH statement. This -** is slightly different from resolving a normal SQL expression, because simple -** identifiers are treated as strings, not possible column names or aliases. -** -** i.e. if the parser sees: -** -** ATTACH DATABASE abc AS def -** -** it treats the two expressions as literal strings 'abc' and 'def' instead of -** looking for columns of the same name. -** -** This only applies to the root node of pExpr, so the statement: -** -** ATTACH DATABASE abc||def AS 'db2' -** -** will fail because neither abc or def can be resolved. -*/ -static int resolveAttachExpr(NameContext *pName, Expr *pExpr) -{ - int rc = SQLITE_OK; - if( pExpr ){ - if( pExpr->op!=TK_ID ){ - rc = sqlite3ResolveExprNames(pName, pExpr); - }else{ - pExpr->op = TK_STRING; - } - } - return rc; -} - -/* -** Return true if zName points to a name that may be used to refer to -** database iDb attached to handle db. -*/ -SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName){ - return ( - sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0 - || (iDb==0 && sqlite3StrICmp("main", zName)==0) - ); -} - -/* -** An SQL user-function registered to do the work of an ATTACH statement. The -** three arguments to the function come directly from an attach statement: -** -** ATTACH DATABASE x AS y KEY z -** -** SELECT sqlite_attach(x, y, z) -** -** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the -** third argument. -** -** If the db->init.reopenMemdb flags is set, then instead of attaching a -** new database, close the database on db->init.iDb and reopen it as an -** empty MemDB. -*/ -static void attachFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - int i; - int rc = 0; - sqlite3 *db = sqlite3_context_db_handle(context); - const char *zName; - const char *zFile; - char *zPath = 0; - char *zErr = 0; - unsigned int flags; - Db *aNew; /* New array of Db pointers */ - Db *pNew; /* Db object for the newly attached database */ - char *zErrDyn = 0; - sqlite3_vfs *pVfs; - - UNUSED_PARAMETER(NotUsed); - zFile = (const char *)sqlite3_value_text(argv[0]); - zName = (const char *)sqlite3_value_text(argv[1]); - if( zFile==0 ) zFile = ""; - if( zName==0 ) zName = ""; - -#ifdef SQLITE_ENABLE_DESERIALIZE -# define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb) -#else -# define REOPEN_AS_MEMDB(db) (0) -#endif - - if( REOPEN_AS_MEMDB(db) ){ - /* This is not a real ATTACH. Instead, this routine is being called - ** from sqlite3_deserialize() to close database db->init.iDb and - ** reopen it as a MemDB */ - pVfs = sqlite3_vfs_find("memdb"); - if( pVfs==0 ) return; - pNew = &db->aDb[db->init.iDb]; - if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt); - pNew->pBt = 0; - pNew->pSchema = 0; - rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB); - }else{ - /* This is a real ATTACH - ** - ** Check for the following errors: - ** - ** * Too many attached databases, - ** * Transaction currently open - ** * Specified database name already being used. - */ - if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ - zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", - db->aLimit[SQLITE_LIMIT_ATTACHED] - ); - goto attach_error; - } - for(i=0; inDb; i++){ - assert( zName ); - if( sqlite3DbIsNamed(db, i, zName) ){ - zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); - goto attach_error; - } - } - - /* Allocate the new entry in the db->aDb[] array and initialize the schema - ** hash tables. - */ - if( db->aDb==db->aDbStatic ){ - aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 ); - if( aNew==0 ) return; - memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); - }else{ - aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); - if( aNew==0 ) return; - } - db->aDb = aNew; - pNew = &db->aDb[db->nDb]; - memset(pNew, 0, sizeof(*pNew)); - - /* Open the database file. If the btree is successfully opened, use - ** it to obtain the database schema. At this point the schema may - ** or may not be initialized. - */ - flags = db->openFlags; - rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); - sqlite3_result_error(context, zErr, -1); - sqlite3_free(zErr); - return; - } - assert( pVfs ); - flags |= SQLITE_OPEN_MAIN_DB; - rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags); - db->nDb++; - pNew->zDbSName = sqlite3DbStrDup(db, zName); - } - db->noSharedCache = 0; - if( rc==SQLITE_CONSTRAINT ){ - rc = SQLITE_ERROR; - zErrDyn = sqlite3MPrintf(db, "database is already attached"); - }else if( rc==SQLITE_OK ){ - Pager *pPager; - pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt); - if( !pNew->pSchema ){ - rc = SQLITE_NOMEM_BKPT; - }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){ - zErrDyn = sqlite3MPrintf(db, - "attached databases must use the same text encoding as main database"); - rc = SQLITE_ERROR; - } - sqlite3BtreeEnter(pNew->pBt); - pPager = sqlite3BtreePager(pNew->pBt); - sqlite3PagerLockingMode(pPager, db->dfltLockMode); - sqlite3BtreeSecureDelete(pNew->pBt, - sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) ); -#ifndef SQLITE_OMIT_PAGER_PRAGMAS - sqlite3BtreeSetPagerFlags(pNew->pBt, - PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK)); -#endif - sqlite3BtreeLeave(pNew->pBt); - } - pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; - if( rc==SQLITE_OK && pNew->zDbSName==0 ){ - rc = SQLITE_NOMEM_BKPT; - } - sqlite3_free_filename( zPath ); - - /* If the file was opened successfully, read the schema for the new database. - ** If this fails, or if opening the file failed, then close the file and - ** remove the entry from the db->aDb[] array. i.e. put everything back the - ** way we found it. - */ - if( rc==SQLITE_OK ){ - sqlite3BtreeEnterAll(db); - db->init.iDb = 0; - db->mDbFlags &= ~(DBFLAG_SchemaKnownOk); - if( !REOPEN_AS_MEMDB(db) ){ - rc = sqlite3Init(db, &zErrDyn); - } - sqlite3BtreeLeaveAll(db); - assert( zErrDyn==0 || rc!=SQLITE_OK ); - } -#ifdef SQLITE_USER_AUTHENTICATION - if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){ - u8 newAuth = 0; - rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth); - if( newAuthauth.authLevel ){ - rc = SQLITE_AUTH_USER; - } - } -#endif - if( rc ){ - if( !REOPEN_AS_MEMDB(db) ){ - int iDb = db->nDb - 1; - assert( iDb>=2 ); - if( db->aDb[iDb].pBt ){ - sqlite3BtreeClose(db->aDb[iDb].pBt); - db->aDb[iDb].pBt = 0; - db->aDb[iDb].pSchema = 0; - } - sqlite3ResetAllSchemasOfConnection(db); - db->nDb = iDb; - if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ - sqlite3OomFault(db); - sqlite3DbFree(db, zErrDyn); - zErrDyn = sqlite3MPrintf(db, "out of memory"); - }else if( zErrDyn==0 ){ - zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile); - } - } - goto attach_error; - } - - return; - -attach_error: - /* Return an error if we get here */ - if( zErrDyn ){ - sqlite3_result_error(context, zErrDyn, -1); - sqlite3DbFree(db, zErrDyn); - } - if( rc ) sqlite3_result_error_code(context, rc); -} - -/* -** An SQL user-function registered to do the work of an DETACH statement. The -** three arguments to the function come directly from a detach statement: -** -** DETACH DATABASE x -** -** SELECT sqlite_detach(x) -*/ -static void detachFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - const char *zName = (const char *)sqlite3_value_text(argv[0]); - sqlite3 *db = sqlite3_context_db_handle(context); - int i; - Db *pDb = 0; - HashElem *pEntry; - char zErr[128]; - - UNUSED_PARAMETER(NotUsed); - - if( zName==0 ) zName = ""; - for(i=0; inDb; i++){ - pDb = &db->aDb[i]; - if( pDb->pBt==0 ) continue; - if( sqlite3DbIsNamed(db, i, zName) ) break; - } - - if( i>=db->nDb ){ - sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName); - goto detach_error; - } - if( i<2 ){ - sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName); - goto detach_error; - } - if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){ - sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName); - goto detach_error; - } - - /* If any TEMP triggers reference the schema being detached, move those - ** triggers to reference the TEMP schema itself. */ - assert( db->aDb[1].pSchema ); - pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash); - while( pEntry ){ - Trigger *pTrig = (Trigger*)sqliteHashData(pEntry); - if( pTrig->pTabSchema==pDb->pSchema ){ - pTrig->pTabSchema = pTrig->pSchema; - } - pEntry = sqliteHashNext(pEntry); - } - - sqlite3BtreeClose(pDb->pBt); - pDb->pBt = 0; - pDb->pSchema = 0; - sqlite3CollapseDatabaseArray(db); - return; - -detach_error: - sqlite3_result_error(context, zErr, -1); -} - -/* -** This procedure generates VDBE code for a single invocation of either the -** sqlite_detach() or sqlite_attach() SQL user functions. -*/ -static void codeAttach( - Parse *pParse, /* The parser context */ - int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ - FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */ - Expr *pAuthArg, /* Expression to pass to authorization callback */ - Expr *pFilename, /* Name of database file */ - Expr *pDbname, /* Name of the database to use internally */ - Expr *pKey /* Database key for encryption extension */ -){ - int rc; - NameContext sName; - Vdbe *v; - sqlite3* db = pParse->db; - int regArgs; - - if( pParse->nErr ) goto attach_end; - memset(&sName, 0, sizeof(NameContext)); - sName.pParse = pParse; - - if( - SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) || - SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) || - SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey)) - ){ - goto attach_end; - } - -#ifndef SQLITE_OMIT_AUTHORIZATION - if( pAuthArg ){ - char *zAuthArg; - if( pAuthArg->op==TK_STRING ){ - zAuthArg = pAuthArg->u.zToken; - }else{ - zAuthArg = 0; - } - rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); - if(rc!=SQLITE_OK ){ - goto attach_end; - } - } -#endif /* SQLITE_OMIT_AUTHORIZATION */ - - - v = sqlite3GetVdbe(pParse); - regArgs = sqlite3GetTempRange(pParse, 4); - sqlite3ExprCode(pParse, pFilename, regArgs); - sqlite3ExprCode(pParse, pDbname, regArgs+1); - sqlite3ExprCode(pParse, pKey, regArgs+2); - - assert( v || db->mallocFailed ); - if( v ){ - sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3, - pFunc->nArg, pFunc, 0); - /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this - ** statement only). For DETACH, set it to false (expire all existing - ** statements). - */ - sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); - } - -attach_end: - sqlite3ExprDelete(db, pFilename); - sqlite3ExprDelete(db, pDbname); - sqlite3ExprDelete(db, pKey); -} - -/* -** Called by the parser to compile a DETACH statement. -** -** DETACH pDbname -*/ -SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){ - static const FuncDef detach_func = { - 1, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - detachFunc, /* xSFunc */ - 0, /* xFinalize */ - 0, 0, /* xValue, xInverse */ - "sqlite_detach", /* zName */ - {0} - }; - codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname); -} - -/* -** Called by the parser to compile an ATTACH statement. -** -** ATTACH p AS pDbname KEY pKey -*/ -SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){ - static const FuncDef attach_func = { - 3, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - attachFunc, /* xSFunc */ - 0, /* xFinalize */ - 0, 0, /* xValue, xInverse */ - "sqlite_attach", /* zName */ - {0} - }; - codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey); -} -#endif /* SQLITE_OMIT_ATTACH */ - -/* -** Initialize a DbFixer structure. This routine must be called prior -** to passing the structure to one of the sqliteFixAAAA() routines below. -*/ -SQLITE_PRIVATE void sqlite3FixInit( - DbFixer *pFix, /* The fixer to be initialized */ - Parse *pParse, /* Error messages will be written here */ - int iDb, /* This is the database that must be used */ - const char *zType, /* "view", "trigger", or "index" */ - const Token *pName /* Name of the view, trigger, or index */ -){ - sqlite3 *db; - - db = pParse->db; - assert( db->nDb>iDb ); - pFix->pParse = pParse; - pFix->zDb = db->aDb[iDb].zDbSName; - pFix->pSchema = db->aDb[iDb].pSchema; - pFix->zType = zType; - pFix->pName = pName; - pFix->bTemp = (iDb==1); -} - -/* -** The following set of routines walk through the parse tree and assign -** a specific database to all table references where the database name -** was left unspecified in the original SQL statement. The pFix structure -** must have been initialized by a prior call to sqlite3FixInit(). -** -** These routines are used to make sure that an index, trigger, or -** view in one database does not refer to objects in a different database. -** (Exception: indices, triggers, and views in the TEMP database are -** allowed to refer to anything.) If a reference is explicitly made -** to an object in a different database, an error message is added to -** pParse->zErrMsg and these routines return non-zero. If everything -** checks out, these routines return 0. -*/ -SQLITE_PRIVATE int sqlite3FixSrcList( - DbFixer *pFix, /* Context of the fixation */ - SrcList *pList /* The Source list to check and modify */ -){ - int i; - struct SrcList_item *pItem; - sqlite3 *db = pFix->pParse->db; - int iDb = sqlite3FindDbName(db, pFix->zDb); - - if( NEVER(pList==0) ) return 0; - - for(i=0, pItem=pList->a; inSrc; i++, pItem++){ - if( pFix->bTemp==0 ){ - if( pItem->zDatabase && iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){ - sqlite3ErrorMsg(pFix->pParse, - "%s %T cannot reference objects in database %s", - pFix->zType, pFix->pName, pItem->zDatabase); - return 1; - } - sqlite3DbFree(db, pItem->zDatabase); - pItem->zDatabase = 0; - pItem->pSchema = pFix->pSchema; - pItem->fg.fromDDL = 1; - } -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) - if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1; - if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1; -#endif - if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){ - return 1; - } - } - return 0; -} -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) -SQLITE_PRIVATE int sqlite3FixSelect( - DbFixer *pFix, /* Context of the fixation */ - Select *pSelect /* The SELECT statement to be fixed to one database */ -){ - while( pSelect ){ - if( sqlite3FixExprList(pFix, pSelect->pEList) ){ - return 1; - } - if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){ - return 1; - } - if( sqlite3FixExpr(pFix, pSelect->pWhere) ){ - return 1; - } - if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){ - return 1; - } - if( sqlite3FixExpr(pFix, pSelect->pHaving) ){ - return 1; - } - if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){ - return 1; - } - if( sqlite3FixExpr(pFix, pSelect->pLimit) ){ - return 1; - } - if( pSelect->pWith ){ - int i; - for(i=0; ipWith->nCte; i++){ - if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){ - return 1; - } - } - } - pSelect = pSelect->pPrior; - } - return 0; -} -SQLITE_PRIVATE int sqlite3FixExpr( - DbFixer *pFix, /* Context of the fixation */ - Expr *pExpr /* The expression to be fixed to one database */ -){ - while( pExpr ){ - if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL); - if( pExpr->op==TK_VARIABLE ){ - if( pFix->pParse->db->init.busy ){ - pExpr->op = TK_NULL; - }else{ - sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType); - return 1; - } - } - if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break; - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1; - }else{ - if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1; - } - if( sqlite3FixExpr(pFix, pExpr->pRight) ){ - return 1; - } - pExpr = pExpr->pLeft; - } - return 0; -} -SQLITE_PRIVATE int sqlite3FixExprList( - DbFixer *pFix, /* Context of the fixation */ - ExprList *pList /* The expression to be fixed to one database */ -){ - int i; - struct ExprList_item *pItem; - if( pList==0 ) return 0; - for(i=0, pItem=pList->a; inExpr; i++, pItem++){ - if( sqlite3FixExpr(pFix, pItem->pExpr) ){ - return 1; - } - } - return 0; -} -#endif - -#ifndef SQLITE_OMIT_TRIGGER -SQLITE_PRIVATE int sqlite3FixTriggerStep( - DbFixer *pFix, /* Context of the fixation */ - TriggerStep *pStep /* The trigger step be fixed to one database */ -){ - while( pStep ){ - if( sqlite3FixSelect(pFix, pStep->pSelect) ){ - return 1; - } - if( sqlite3FixExpr(pFix, pStep->pWhere) ){ - return 1; - } - if( sqlite3FixExprList(pFix, pStep->pExprList) ){ - return 1; - } - if( pStep->pFrom && sqlite3FixSrcList(pFix, pStep->pFrom) ){ - return 1; - } -#ifndef SQLITE_OMIT_UPSERT - if( pStep->pUpsert ){ - Upsert *pUp = pStep->pUpsert; - if( sqlite3FixExprList(pFix, pUp->pUpsertTarget) - || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere) - || sqlite3FixExprList(pFix, pUp->pUpsertSet) - || sqlite3FixExpr(pFix, pUp->pUpsertWhere) - ){ - return 1; - } - } -#endif - pStep = pStep->pNext; - } - return 0; -} -#endif - -/************** End of attach.c **********************************************/ -/************** Begin file auth.c ********************************************/ -/* -** 2003 January 11 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code used to implement the sqlite3_set_authorizer() -** API. This facility is an optional feature of the library. Embedded -** systems that do not need this facility may omit it by recompiling -** the library with -DSQLITE_OMIT_AUTHORIZATION=1 -*/ -/* #include "sqliteInt.h" */ - -/* -** All of the code in this file may be omitted by defining a single -** macro. -*/ -#ifndef SQLITE_OMIT_AUTHORIZATION - -/* -** Set or clear the access authorization function. -** -** The access authorization function is be called during the compilation -** phase to verify that the user has read and/or write access permission on -** various fields of the database. The first argument to the auth function -** is a copy of the 3rd argument to this routine. The second argument -** to the auth function is one of these constants: -** -** SQLITE_CREATE_INDEX -** SQLITE_CREATE_TABLE -** SQLITE_CREATE_TEMP_INDEX -** SQLITE_CREATE_TEMP_TABLE -** SQLITE_CREATE_TEMP_TRIGGER -** SQLITE_CREATE_TEMP_VIEW -** SQLITE_CREATE_TRIGGER -** SQLITE_CREATE_VIEW -** SQLITE_DELETE -** SQLITE_DROP_INDEX -** SQLITE_DROP_TABLE -** SQLITE_DROP_TEMP_INDEX -** SQLITE_DROP_TEMP_TABLE -** SQLITE_DROP_TEMP_TRIGGER -** SQLITE_DROP_TEMP_VIEW -** SQLITE_DROP_TRIGGER -** SQLITE_DROP_VIEW -** SQLITE_INSERT -** SQLITE_PRAGMA -** SQLITE_READ -** SQLITE_SELECT -** SQLITE_TRANSACTION -** SQLITE_UPDATE -** -** The third and fourth arguments to the auth function are the name of -** the table and the column that are being accessed. The auth function -** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If -** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY -** means that the SQL statement will never-run - the sqlite3_exec() call -** will return with an error. SQLITE_IGNORE means that the SQL statement -** should run but attempts to read the specified column will return NULL -** and attempts to write the column will be ignored. -** -** Setting the auth function to NULL disables this hook. The default -** setting of the auth function is NULL. -*/ -SQLITE_API int sqlite3_set_authorizer( - sqlite3 *db, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pArg -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - db->xAuth = (sqlite3_xauth)xAuth; - db->pAuthArg = pArg; - if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1); - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -/* -** Write an error message into pParse->zErrMsg that explains that the -** user-supplied authorization function returned an illegal value. -*/ -static void sqliteAuthBadReturnCode(Parse *pParse){ - sqlite3ErrorMsg(pParse, "authorizer malfunction"); - pParse->rc = SQLITE_ERROR; -} - -/* -** Invoke the authorization callback for permission to read column zCol from -** table zTab in database zDb. This function assumes that an authorization -** callback has been registered (i.e. that sqlite3.xAuth is not NULL). -** -** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed -** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE -** is treated as SQLITE_DENY. In this case an error is left in pParse. -*/ -SQLITE_PRIVATE int sqlite3AuthReadCol( - Parse *pParse, /* The parser context */ - const char *zTab, /* Table name */ - const char *zCol, /* Column name */ - int iDb /* Index of containing database. */ -){ - sqlite3 *db = pParse->db; /* Database handle */ - char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */ - int rc; /* Auth callback return code */ - - if( db->init.busy ) return SQLITE_OK; - rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext -#ifdef SQLITE_USER_AUTHENTICATION - ,db->auth.zAuthUser -#endif - ); - if( rc==SQLITE_DENY ){ - char *z = sqlite3_mprintf("%s.%s", zTab, zCol); - if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z); - sqlite3ErrorMsg(pParse, "access to %z is prohibited", z); - pParse->rc = SQLITE_AUTH; - }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){ - sqliteAuthBadReturnCode(pParse); - } - return rc; -} - -/* -** The pExpr should be a TK_COLUMN expression. The table referred to -** is in pTabList or else it is the NEW or OLD table of a trigger. -** Check to see if it is OK to read this particular column. -** -** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN -** instruction into a TK_NULL. If the auth function returns SQLITE_DENY, -** then generate an error. -*/ -SQLITE_PRIVATE void sqlite3AuthRead( - Parse *pParse, /* The parser context */ - Expr *pExpr, /* The expression to check authorization on */ - Schema *pSchema, /* The schema of the expression */ - SrcList *pTabList /* All table that pExpr might refer to */ -){ - sqlite3 *db = pParse->db; - Table *pTab = 0; /* The table being read */ - const char *zCol; /* Name of the column of the table */ - int iSrc; /* Index in pTabList->a[] of table being read */ - int iDb; /* The index of the database the expression refers to */ - int iCol; /* Index of column in table */ - - assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); - assert( !IN_RENAME_OBJECT || db->xAuth==0 ); - if( db->xAuth==0 ) return; - iDb = sqlite3SchemaToIndex(pParse->db, pSchema); - if( iDb<0 ){ - /* An attempt to read a column out of a subquery or other - ** temporary table. */ - return; - } - - if( pExpr->op==TK_TRIGGER ){ - pTab = pParse->pTriggerTab; - }else{ - assert( pTabList ); - for(iSrc=0; ALWAYS(iSrcnSrc); iSrc++){ - if( pExpr->iTable==pTabList->a[iSrc].iCursor ){ - pTab = pTabList->a[iSrc].pTab; - break; - } - } - } - iCol = pExpr->iColumn; - if( NEVER(pTab==0) ) return; - - if( iCol>=0 ){ - assert( iColnCol ); - zCol = pTab->aCol[iCol].zName; - }else if( pTab->iPKey>=0 ){ - assert( pTab->iPKeynCol ); - zCol = pTab->aCol[pTab->iPKey].zName; - }else{ - zCol = "ROWID"; - } - assert( iDb>=0 && iDbnDb ); - if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){ - pExpr->op = TK_NULL; - } -} - -/* -** Do an authorization check using the code and arguments given. Return -** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY -** is returned, then the error count and error message in pParse are -** modified appropriately. -*/ -SQLITE_PRIVATE int sqlite3AuthCheck( - Parse *pParse, - int code, - const char *zArg1, - const char *zArg2, - const char *zArg3 -){ - sqlite3 *db = pParse->db; - int rc; - - /* Don't do any authorization checks if the database is initialising - ** or if the parser is being invoked from within sqlite3_declare_vtab. - */ - assert( !IN_RENAME_OBJECT || db->xAuth==0 ); - if( db->init.busy || IN_SPECIAL_PARSE ){ - return SQLITE_OK; - } - - if( db->xAuth==0 ){ - return SQLITE_OK; - } - - /* EVIDENCE-OF: R-43249-19882 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. - ** - ** The following testcase() macros show that any of the 3rd through 6th - ** parameters can be either NULL or a string. */ - testcase( zArg1==0 ); - testcase( zArg2==0 ); - testcase( zArg3==0 ); - testcase( pParse->zAuthContext==0 ); - - rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext -#ifdef SQLITE_USER_AUTHENTICATION - ,db->auth.zAuthUser -#endif - ); - if( rc==SQLITE_DENY ){ - sqlite3ErrorMsg(pParse, "not authorized"); - pParse->rc = SQLITE_AUTH; - }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){ - rc = SQLITE_DENY; - sqliteAuthBadReturnCode(pParse); - } - return rc; -} - -/* -** Push an authorization context. After this routine is called, the -** zArg3 argument to authorization callbacks will be zContext until -** popped. Or if pParse==0, this routine is a no-op. -*/ -SQLITE_PRIVATE void sqlite3AuthContextPush( - Parse *pParse, - AuthContext *pContext, - const char *zContext -){ - assert( pParse ); - pContext->pParse = pParse; - pContext->zAuthContext = pParse->zAuthContext; - pParse->zAuthContext = zContext; -} - -/* -** Pop an authorization context that was previously pushed -** by sqlite3AuthContextPush -*/ -SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){ - if( pContext->pParse ){ - pContext->pParse->zAuthContext = pContext->zAuthContext; - pContext->pParse = 0; - } -} - -#endif /* SQLITE_OMIT_AUTHORIZATION */ - -/************** End of auth.c ************************************************/ -/************** Begin file build.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 C code routines that are called by the SQLite parser -** when syntax rules are reduced. The routines in this file handle the -** following kinds of SQL syntax: -** -** CREATE TABLE -** DROP TABLE -** CREATE INDEX -** DROP INDEX -** creating ID lists -** BEGIN TRANSACTION -** COMMIT -** ROLLBACK -*/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_OMIT_SHARED_CACHE -/* -** The TableLock structure is only used by the sqlite3TableLock() and -** codeTableLocks() functions. -*/ -struct TableLock { - int iDb; /* The database containing the table to be locked */ - Pgno iTab; /* The root page of the table to be locked */ - u8 isWriteLock; /* True for write lock. False for a read lock */ - const char *zLockName; /* Name of the table */ -}; - -/* -** Record the fact that we want to lock a table at run-time. -** -** The table to be locked has root page iTab and is found in database iDb. -** A read or a write lock can be taken depending on isWritelock. -** -** This routine just records the fact that the lock is desired. The -** code to make the lock occur is generated by a later call to -** codeTableLocks() which occurs during sqlite3FinishCoding(). -*/ -SQLITE_PRIVATE void sqlite3TableLock( - Parse *pParse, /* Parsing context */ - int iDb, /* Index of the database containing the table to lock */ - Pgno iTab, /* Root page number of the table to be locked */ - u8 isWriteLock, /* True for a write lock */ - const char *zName /* Name of the table to be locked */ -){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - int i; - int nBytes; - TableLock *p; - assert( iDb>=0 ); - - if( iDb==1 ) return; - if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return; - for(i=0; inTableLock; i++){ - p = &pToplevel->aTableLock[i]; - if( p->iDb==iDb && p->iTab==iTab ){ - p->isWriteLock = (p->isWriteLock || isWriteLock); - return; - } - } - - nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); - pToplevel->aTableLock = - sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); - if( pToplevel->aTableLock ){ - p = &pToplevel->aTableLock[pToplevel->nTableLock++]; - p->iDb = iDb; - p->iTab = iTab; - p->isWriteLock = isWriteLock; - p->zLockName = zName; - }else{ - pToplevel->nTableLock = 0; - sqlite3OomFault(pToplevel->db); - } -} - -/* -** Code an OP_TableLock instruction for each table locked by the -** statement (configured by calls to sqlite3TableLock()). -*/ -static void codeTableLocks(Parse *pParse){ - int i; - Vdbe *pVdbe; - - pVdbe = sqlite3GetVdbe(pParse); - assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */ - - for(i=0; inTableLock; i++){ - TableLock *p = &pParse->aTableLock[i]; - int p1 = p->iDb; - sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, - p->zLockName, P4_STATIC); - } -} -#else - #define codeTableLocks(x) -#endif - -/* -** Return TRUE if the given yDbMask object is empty - if it contains no -** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero() -** macros when SQLITE_MAX_ATTACHED is greater than 30. -*/ -#if SQLITE_MAX_ATTACHED>30 -SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){ - int i; - for(i=0; ipToplevel==0 ); - db = pParse->db; - if( pParse->nested ) return; - if( db->mallocFailed || pParse->nErr ){ - if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR; - return; - } - - /* Begin by generating some termination code at the end of the - ** vdbe program - */ - v = sqlite3GetVdbe(pParse); - assert( !pParse->isMultiWrite - || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); - if( v ){ - sqlite3VdbeAddOp0(v, OP_Halt); - -#if SQLITE_USER_AUTHENTICATION - if( pParse->nTableLock>0 && db->init.busy==0 ){ - sqlite3UserAuthInit(db); - if( db->auth.authLevelrc = SQLITE_AUTH_USER; - return; - } - } -#endif - - /* The cookie mask contains one bit for each database file open. - ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are - ** set for each database that is used. Generate code to start a - ** transaction on each used database and to verify the schema cookie - ** on each used database. - */ - if( db->mallocFailed==0 - && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr) - ){ - int iDb, i; - assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init ); - sqlite3VdbeJumpHere(v, 0); - for(iDb=0; iDbnDb; iDb++){ - Schema *pSchema; - if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue; - sqlite3VdbeUsesBtree(v, iDb); - pSchema = db->aDb[iDb].pSchema; - sqlite3VdbeAddOp4Int(v, - OP_Transaction, /* Opcode */ - iDb, /* P1 */ - DbMaskTest(pParse->writeMask,iDb), /* P2 */ - pSchema->schema_cookie, /* P3 */ - pSchema->iGeneration /* P4 */ - ); - if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1); - VdbeComment((v, - "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite)); - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - for(i=0; inVtabLock; i++){ - char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]); - sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); - } - pParse->nVtabLock = 0; -#endif - - /* Once all the cookies have been verified and transactions opened, - ** obtain the required table-locks. This is a no-op unless the - ** shared-cache feature is enabled. - */ - codeTableLocks(pParse); - - /* Initialize any AUTOINCREMENT data structures required. - */ - sqlite3AutoincrementBegin(pParse); - - /* Code constant expressions that where factored out of inner loops. - ** - ** The pConstExpr list might also contain expressions that we simply - ** want to keep around until the Parse object is deleted. Such - ** expressions have iConstExprReg==0. Do not generate code for - ** those expressions, of course. - */ - if( pParse->pConstExpr ){ - ExprList *pEL = pParse->pConstExpr; - pParse->okConstFactor = 0; - for(i=0; inExpr; i++){ - int iReg = pEL->a[i].u.iConstExprReg; - if( iReg>0 ){ - sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg); - } - } - } - - /* Finally, jump back to the beginning of the executable code. */ - sqlite3VdbeGoto(v, 1); - } - } - - - /* Get the VDBE program ready for execution - */ - if( v && pParse->nErr==0 && !db->mallocFailed ){ - /* A minimum of one cursor is required if autoincrement is used - * See ticket [a696379c1f08866] */ - assert( pParse->pAinc==0 || pParse->nTab>0 ); - sqlite3VdbeMakeReady(v, pParse); - pParse->rc = SQLITE_DONE; - }else{ - pParse->rc = SQLITE_ERROR; - } -} - -/* -** Run the parser and code generator recursively in order to generate -** code for the SQL statement given onto the end of the pParse context -** currently under construction. When the parser is run recursively -** this way, the final OP_Halt is not appended and other initialization -** and finalization steps are omitted because those are handling by the -** outermost parser. -** -** Not everything is nestable. This facility is designed to permit -** INSERT, UPDATE, and DELETE operations against the schema table. Use -** care if you decide to try to use this routine for some other purposes. -*/ -SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ - va_list ap; - char *zSql; - char *zErrMsg = 0; - sqlite3 *db = pParse->db; - char saveBuf[PARSE_TAIL_SZ]; - - if( pParse->nErr ) return; - assert( pParse->nested<10 ); /* Nesting should only be of limited depth */ - va_start(ap, zFormat); - zSql = sqlite3VMPrintf(db, zFormat, ap); - va_end(ap); - if( zSql==0 ){ - /* This can result either from an OOM or because the formatted string - ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set - ** an error */ - if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG; - pParse->nErr++; - return; - } - pParse->nested++; - memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ); - memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); - sqlite3RunParser(pParse, zSql, &zErrMsg); - sqlite3DbFree(db, zErrMsg); - sqlite3DbFree(db, zSql); - memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ); - pParse->nested--; -} - -#if SQLITE_USER_AUTHENTICATION -/* -** Return TRUE if zTable is the name of the system table that stores the -** list of users and their access credentials. -*/ -SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){ - return sqlite3_stricmp(zTable, "sqlite_user")==0; -} -#endif - -/* -** Locate the in-memory structure that describes a particular database -** table given the name of that table and (optionally) the name of the -** database containing the table. Return NULL if not found. -** -** If zDatabase is 0, all databases are searched for the table and the -** first matching table is returned. (No checking for duplicate table -** names is done.) The search order is TEMP first, then MAIN, then any -** auxiliary databases added using the ATTACH command. -** -** See also sqlite3LocateTable(). -*/ -SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ - Table *p = 0; - int i; - - /* All mutexes are required for schema access. Make sure we hold them. */ - assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); -#if SQLITE_USER_AUTHENTICATION - /* Only the admin user is allowed to know that the sqlite_user table - ** exists */ - if( db->auth.authLevelnDb; i++){ - if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break; - } - if( i>=db->nDb ){ - /* No match against the official names. But always match "main" - ** to schema 0 as a legacy fallback. */ - if( sqlite3StrICmp(zDatabase,"main")==0 ){ - i = 0; - }else{ - return 0; - } - } - p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName); - if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){ - if( i==1 ){ - if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 - || sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 - || sqlite3StrICmp(zName+7, &DFLT_SCHEMA_TABLE[7])==0 - ){ - p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, - DFLT_TEMP_SCHEMA_TABLE); - } - }else{ - if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){ - p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, - DFLT_SCHEMA_TABLE); - } - } - } - }else{ - /* Match against TEMP first */ - p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName); - if( p ) return p; - /* The main database is second */ - p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName); - if( p ) return p; - /* Attached databases are in order of attachment */ - for(i=2; inDb; i++){ - assert( sqlite3SchemaMutexHeld(db, i, 0) ); - p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName); - if( p ) break; - } - if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){ - if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){ - p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, DFLT_SCHEMA_TABLE); - }else if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 ){ - p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, - DFLT_TEMP_SCHEMA_TABLE); - } - } - } - return p; -} - -/* -** Locate the in-memory structure that describes a particular database -** table given the name of that table and (optionally) the name of the -** database containing the table. Return NULL if not found. Also leave an -** error message in pParse->zErrMsg. -** -** The difference between this routine and sqlite3FindTable() is that this -** routine leaves an error message in pParse->zErrMsg where -** sqlite3FindTable() does not. -*/ -SQLITE_PRIVATE Table *sqlite3LocateTable( - Parse *pParse, /* context in which to report errors */ - u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */ - const char *zName, /* Name of the table we are looking for */ - const char *zDbase /* Name of the database. Might be NULL */ -){ - Table *p; - sqlite3 *db = pParse->db; - - /* Read the database schema. If an error occurs, leave an error message - ** and code in pParse and return NULL. */ - if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 - && SQLITE_OK!=sqlite3ReadSchema(pParse) - ){ - return 0; - } - - p = sqlite3FindTable(db, zName, zDbase); - if( p==0 ){ -#ifndef SQLITE_OMIT_VIRTUALTABLE - /* If zName is the not the name of a table in the schema created using - ** CREATE, then check to see if it is the name of an virtual table that - ** can be an eponymous virtual table. */ - if( pParse->disableVtab==0 ){ - Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName); - if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){ - pMod = sqlite3PragmaVtabRegister(db, zName); - } - if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ - return pMod->pEpoTab; - } - } -#endif - if( flags & LOCATE_NOERR ) return 0; - pParse->checkSchema = 1; - }else if( IsVirtual(p) && pParse->disableVtab ){ - p = 0; - } - - if( p==0 ){ - const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; - if( zDbase ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); - }else{ - sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); - } - } - - return p; -} - -/* -** Locate the table identified by *p. -** -** This is a wrapper around sqlite3LocateTable(). The difference between -** sqlite3LocateTable() and this function is that this function restricts -** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be -** non-NULL if it is part of a view or trigger program definition. See -** sqlite3FixSrcList() for details. -*/ -SQLITE_PRIVATE Table *sqlite3LocateTableItem( - Parse *pParse, - u32 flags, - struct SrcList_item *p -){ - const char *zDb; - assert( p->pSchema==0 || p->zDatabase==0 ); - if( p->pSchema ){ - int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); - zDb = pParse->db->aDb[iDb].zDbSName; - }else{ - zDb = p->zDatabase; - } - return sqlite3LocateTable(pParse, flags, p->zName, zDb); -} - -/* -** Locate the in-memory structure that describes -** a particular index given the name of that index -** and the name of the database that contains the index. -** Return NULL if not found. -** -** If zDatabase is 0, all databases are searched for the -** table and the first matching index is returned. (No checking -** for duplicate index names is done.) The search order is -** TEMP first, then MAIN, then any auxiliary databases added -** using the ATTACH command. -*/ -SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ - Index *p = 0; - int i; - /* All mutexes are required for schema access. Make sure we hold them. */ - assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); - for(i=OMIT_TEMPDB; inDb; i++){ - int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ - Schema *pSchema = db->aDb[j].pSchema; - assert( pSchema ); - if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue; - assert( sqlite3SchemaMutexHeld(db, j, 0) ); - p = sqlite3HashFind(&pSchema->idxHash, zName); - if( p ) break; - } - return p; -} - -/* -** Reclaim the memory used by an index -*/ -SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){ -#ifndef SQLITE_OMIT_ANALYZE - sqlite3DeleteIndexSamples(db, p); -#endif - sqlite3ExprDelete(db, p->pPartIdxWhere); - sqlite3ExprListDelete(db, p->aColExpr); - sqlite3DbFree(db, p->zColAff); - if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl); -#ifdef SQLITE_ENABLE_STAT4 - sqlite3_free(p->aiRowEst); -#endif - sqlite3DbFree(db, p); -} - -/* -** For the index called zIdxName which is found in the database iDb, -** unlike that index from its Table then remove the index from -** the index hash table and free all memory structures associated -** with the index. -*/ -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){ - Index *pIndex; - Hash *pHash; - - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pHash = &db->aDb[iDb].pSchema->idxHash; - pIndex = sqlite3HashInsert(pHash, zIdxName, 0); - if( ALWAYS(pIndex) ){ - if( pIndex->pTable->pIndex==pIndex ){ - pIndex->pTable->pIndex = pIndex->pNext; - }else{ - Index *p; - /* Justification of ALWAYS(); The index must be on the list of - ** indices. */ - p = pIndex->pTable->pIndex; - while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; } - if( ALWAYS(p && p->pNext==pIndex) ){ - p->pNext = pIndex->pNext; - } - } - sqlite3FreeIndex(db, pIndex); - } - db->mDbFlags |= DBFLAG_SchemaChange; -} - -/* -** Look through the list of open database files in db->aDb[] and if -** any have been closed, remove them from the list. Reallocate the -** db->aDb[] structure to a smaller size, if possible. -** -** Entry 0 (the "main" database) and entry 1 (the "temp" database) -** are never candidates for being collapsed. -*/ -SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){ - int i, j; - for(i=j=2; inDb; i++){ - struct Db *pDb = &db->aDb[i]; - if( pDb->pBt==0 ){ - sqlite3DbFree(db, pDb->zDbSName); - pDb->zDbSName = 0; - continue; - } - if( jaDb[j] = db->aDb[i]; - } - j++; - } - db->nDb = j; - if( db->nDb<=2 && db->aDb!=db->aDbStatic ){ - memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0])); - sqlite3DbFree(db, db->aDb); - db->aDb = db->aDbStatic; - } -} - -/* -** Reset the schema for the database at index iDb. Also reset the -** TEMP schema. The reset is deferred if db->nSchemaLock is not zero. -** Deferred resets may be run by calling with iDb<0. -*/ -SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ - int i; - assert( iDbnDb ); - - if( iDb>=0 ){ - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - DbSetProperty(db, iDb, DB_ResetWanted); - DbSetProperty(db, 1, DB_ResetWanted); - db->mDbFlags &= ~DBFLAG_SchemaKnownOk; - } - - if( db->nSchemaLock==0 ){ - for(i=0; inDb; i++){ - if( DbHasProperty(db, i, DB_ResetWanted) ){ - sqlite3SchemaClear(db->aDb[i].pSchema); - } - } - } -} - -/* -** Erase all schema information from all attached databases (including -** "main" and "temp") for a single database connection. -*/ -SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){ - int i; - sqlite3BtreeEnterAll(db); - for(i=0; inDb; i++){ - Db *pDb = &db->aDb[i]; - if( pDb->pSchema ){ - if( db->nSchemaLock==0 ){ - sqlite3SchemaClear(pDb->pSchema); - }else{ - DbSetProperty(db, i, DB_ResetWanted); - } - } - } - db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk); - sqlite3VtabUnlockList(db); - sqlite3BtreeLeaveAll(db); - if( db->nSchemaLock==0 ){ - sqlite3CollapseDatabaseArray(db); - } -} - -/* -** This routine is called when a commit occurs. -*/ -SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){ - db->mDbFlags &= ~DBFLAG_SchemaChange; -} - -/* -** Delete memory allocated for the column names of a table or view (the -** Table.aCol[] array). -*/ -SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){ - int i; - Column *pCol; - assert( pTable!=0 ); - if( (pCol = pTable->aCol)!=0 ){ - for(i=0; inCol; i++, pCol++){ - assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) ); - sqlite3DbFree(db, pCol->zName); - sqlite3ExprDelete(db, pCol->pDflt); - sqlite3DbFree(db, pCol->zColl); - } - sqlite3DbFree(db, pTable->aCol); - } -} - -/* -** Remove the memory data structures associated with the given -** Table. No changes are made to disk by this routine. -** -** This routine just deletes the data structure. It does not unlink -** the table data structure from the hash table. But it does destroy -** memory structures of the indices and foreign keys associated with -** the table. -** -** The db parameter is optional. It is needed if the Table object -** contains lookaside memory. (Table objects in the schema do not use -** lookaside memory, but some ephemeral Table objects do.) Or the -** db parameter can be used with db->pnBytesFreed to measure the memory -** used by the Table object. -*/ -static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){ - Index *pIndex, *pNext; - -#ifdef SQLITE_DEBUG - /* Record the number of outstanding lookaside allocations in schema Tables - ** prior to doing any free() operations. Since schema Tables do not use - ** lookaside, this number should not change. - ** - ** If malloc has already failed, it may be that it failed while allocating - ** a Table object that was going to be marked ephemeral. So do not check - ** that no lookaside memory is used in this case either. */ - int nLookaside = 0; - if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){ - nLookaside = sqlite3LookasideUsed(db, 0); - } -#endif - - /* Delete all indices associated with this table. */ - for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ - pNext = pIndex->pNext; - assert( pIndex->pSchema==pTable->pSchema - || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) ); - if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){ - char *zName = pIndex->zName; - TESTONLY ( Index *pOld = ) sqlite3HashInsert( - &pIndex->pSchema->idxHash, zName, 0 - ); - assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); - assert( pOld==pIndex || pOld==0 ); - } - sqlite3FreeIndex(db, pIndex); - } - - /* Delete any foreign keys attached to this table. */ - sqlite3FkDelete(db, pTable); - - /* Delete the Table structure itself. - */ - sqlite3DeleteColumnNames(db, pTable); - sqlite3DbFree(db, pTable->zName); - sqlite3DbFree(db, pTable->zColAff); - sqlite3SelectDelete(db, pTable->pSelect); - sqlite3ExprListDelete(db, pTable->pCheck); -#ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3VtabClear(db, pTable); -#endif - sqlite3DbFree(db, pTable); - - /* Verify that no lookaside memory was used by schema tables */ - assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) ); -} -SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ - /* Do not delete the table until the reference count reaches zero. */ - if( !pTable ) return; - if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return; - deleteTable(db, pTable); -} - - -/* -** Unlink the given table from the hash tables and the delete the -** table structure with all its indices and foreign keys. -*/ -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){ - Table *p; - Db *pDb; - - assert( db!=0 ); - assert( iDb>=0 && iDbnDb ); - assert( zTabName ); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */ - pDb = &db->aDb[iDb]; - p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0); - sqlite3DeleteTable(db, p); - db->mDbFlags |= DBFLAG_SchemaChange; -} - -/* -** Given a token, return a string that consists of the text of that -** token. Space to hold the returned string -** is obtained from sqliteMalloc() and must be freed by the calling -** function. -** -** Any quotation marks (ex: "name", 'name', [name], or `name`) that -** surround the body of the token are removed. -** -** Tokens are often just pointers into the original SQL text and so -** are not \000 terminated and are not persistent. The returned string -** is \000 terminated and is persistent. -*/ -SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ - char *zName; - if( pName ){ - zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n); - sqlite3Dequote(zName); - }else{ - zName = 0; - } - return zName; -} - -/* -** Open the sqlite_schema table stored in database number iDb for -** writing. The table is opened using cursor 0. -*/ -SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *p, int iDb){ - Vdbe *v = sqlite3GetVdbe(p); - sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, DFLT_SCHEMA_TABLE); - sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5); - if( p->nTab==0 ){ - p->nTab = 1; - } -} - -/* -** Parameter zName points to a nul-terminated buffer containing the name -** of a database ("main", "temp" or the name of an attached db). This -** function returns the index of the named database in db->aDb[], or -** -1 if the named db cannot be found. -*/ -SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){ - int i = -1; /* Database number */ - if( zName ){ - Db *pDb; - for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){ - if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break; - /* "main" is always an acceptable alias for the primary database - ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */ - if( i==0 && 0==sqlite3_stricmp("main", zName) ) break; - } - } - return i; -} - -/* -** The token *pName contains the name of a database (either "main" or -** "temp" or the name of an attached db). This routine returns the -** index of the named database in db->aDb[], or -1 if the named db -** does not exist. -*/ -SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){ - int i; /* Database number */ - char *zName; /* Name we are searching for */ - zName = sqlite3NameFromToken(db, pName); - i = sqlite3FindDbName(db, zName); - sqlite3DbFree(db, zName); - return i; -} - -/* The table or view or trigger name is passed to this routine via tokens -** pName1 and pName2. If the table name was fully qualified, for example: -** -** CREATE TABLE xxx.yyy (...); -** -** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if -** the table name is not fully qualified, i.e.: -** -** CREATE TABLE yyy(...); -** -** Then pName1 is set to "yyy" and pName2 is "". -** -** This routine sets the *ppUnqual pointer to point at the token (pName1 or -** pName2) that stores the unqualified table name. The index of the -** database "xxx" is returned. -*/ -SQLITE_PRIVATE int sqlite3TwoPartName( - Parse *pParse, /* Parsing and code generating context */ - Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */ - Token *pName2, /* The "yyy" in the name "xxx.yyy" */ - Token **pUnqual /* Write the unqualified object name here */ -){ - int iDb; /* Database holding the object */ - sqlite3 *db = pParse->db; - - assert( pName2!=0 ); - if( pName2->n>0 ){ - if( db->init.busy ) { - sqlite3ErrorMsg(pParse, "corrupt database"); - return -1; - } - *pUnqual = pName2; - iDb = sqlite3FindDb(db, pName1); - if( iDb<0 ){ - sqlite3ErrorMsg(pParse, "unknown database %T", pName1); - return -1; - } - }else{ - assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT - || (db->mDbFlags & DBFLAG_Vacuum)!=0); - iDb = db->init.iDb; - *pUnqual = pName1; - } - return iDb; -} - -/* -** True if PRAGMA writable_schema is ON -*/ -SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){ - testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 ); - testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== - SQLITE_WriteSchema ); - testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== - SQLITE_Defensive ); - testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))== - (SQLITE_WriteSchema|SQLITE_Defensive) ); - return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema; -} - -/* -** This routine is used to check if the UTF-8 string zName is a legal -** unqualified name for a new schema object (table, index, view or -** trigger). All names are legal except those that begin with the string -** "sqlite_" (in upper, lower or mixed case). This portion of the namespace -** is reserved for internal use. -** -** When parsing the sqlite_schema table, this routine also checks to -** make sure the "type", "name", and "tbl_name" columns are consistent -** with the SQL. -*/ -SQLITE_PRIVATE int sqlite3CheckObjectName( - Parse *pParse, /* Parsing context */ - const char *zName, /* Name of the object to check */ - const char *zType, /* Type of this object */ - const char *zTblName /* Parent table name for triggers and indexes */ -){ - sqlite3 *db = pParse->db; - if( sqlite3WritableSchema(db) - || db->init.imposterTable - || !sqlite3Config.bExtraSchemaChecks - ){ - /* Skip these error checks for writable_schema=ON */ - return SQLITE_OK; - } - if( db->init.busy ){ - if( sqlite3_stricmp(zType, db->init.azInit[0]) - || sqlite3_stricmp(zName, db->init.azInit[1]) - || sqlite3_stricmp(zTblName, db->init.azInit[2]) - ){ - sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */ - return SQLITE_ERROR; - } - }else{ - if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7)) - || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName)) - ){ - sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", - zName); - return SQLITE_ERROR; - } - - } - return SQLITE_OK; -} - -/* -** Return the PRIMARY KEY index of a table -*/ -SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){ - Index *p; - for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){} - return p; -} - -/* -** Convert an table column number into a index column number. That is, -** for the column iCol in the table (as defined by the CREATE TABLE statement) -** find the (first) offset of that column in index pIdx. Or return -1 -** if column iCol is not used in index pIdx. -*/ -SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){ - int i; - for(i=0; inColumn; i++){ - if( iCol==pIdx->aiColumn[i] ) return i; - } - return -1; -} - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS -/* Convert a storage column number into a table column number. -** -** The storage column number (0,1,2,....) is the index of the value -** as it appears in the record on disk. The true column number -** is the index (0,1,2,...) of the column in the CREATE TABLE statement. -** -** The storage column number is less than the table column number if -** and only there are VIRTUAL columns to the left. -** -** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro. -*/ -SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){ - if( pTab->tabFlags & TF_HasVirtual ){ - int i; - for(i=0; i<=iCol; i++){ - if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++; - } - } - return iCol; -} -#endif - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS -/* Convert a table column number into a storage column number. -** -** The storage column number (0,1,2,....) is the index of the value -** as it appears in the record on disk. Or, if the input column is -** the N-th virtual column (zero-based) then the storage number is -** the number of non-virtual columns in the table plus N. -** -** The true column number is the index (0,1,2,...) of the column in -** the CREATE TABLE statement. -** -** If the input column is a VIRTUAL column, then it should not appear -** in storage. But the value sometimes is cached in registers that -** follow the range of registers used to construct storage. This -** avoids computing the same VIRTUAL column multiple times, and provides -** values for use by OP_Param opcodes in triggers. Hence, if the -** input column is a VIRTUAL table, put it after all the other columns. -** -** In the following, N means "normal column", S means STORED, and -** V means VIRTUAL. Suppose the CREATE TABLE has columns like this: -** -** CREATE TABLE ex(N,S,V,N,S,V,N,S,V); -** -- 0 1 2 3 4 5 6 7 8 -** -** Then the mapping from this function is as follows: -** -** INPUTS: 0 1 2 3 4 5 6 7 8 -** OUTPUTS: 0 1 6 2 3 7 4 5 8 -** -** So, in other words, this routine shifts all the virtual columns to -** the end. -** -** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and -** this routine is a no-op macro. If the pTab does not have any virtual -** columns, then this routine is no-op that always return iCol. If iCol -** is negative (indicating the ROWID column) then this routine return iCol. -*/ -SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){ - int i; - i16 n; - assert( iColnCol ); - if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol; - for(i=0, n=0; iaCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++; - } - if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){ - /* iCol is a virtual column itself */ - return pTab->nNVCol + i - n; - }else{ - /* iCol is a normal or stored column */ - return n; - } -} -#endif - -/* -** Begin constructing a new table representation in memory. This is -** the first of several action routines that get called in response -** to a CREATE TABLE statement. In particular, this routine is called -** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp -** flag is true if the table should be stored in the auxiliary database -** file instead of in the main database file. This is normally the case -** when the "TEMP" or "TEMPORARY" keyword occurs in between -** CREATE and TABLE. -** -** The new table record is initialized and put in pParse->pNewTable. -** As more of the CREATE TABLE statement is parsed, additional action -** routines will be called to add more information to this record. -** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine -** is called to complete the construction of the new table record. -*/ -SQLITE_PRIVATE void sqlite3StartTable( - Parse *pParse, /* Parser context */ - Token *pName1, /* First part of the name of the table or view */ - Token *pName2, /* Second part of the name of the table or view */ - int isTemp, /* True if this is a TEMP table */ - int isView, /* True if this is a VIEW */ - int isVirtual, /* True if this is a VIRTUAL table */ - int noErr /* Do nothing if table already exists */ -){ - Table *pTable; - char *zName = 0; /* The name of the new table */ - sqlite3 *db = pParse->db; - Vdbe *v; - int iDb; /* Database number to create the table in */ - Token *pName; /* Unqualified name of the table to create */ - - if( db->init.busy && db->init.newTnum==1 ){ - /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */ - iDb = db->init.iDb; - zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb)); - pName = pName1; - }else{ - /* The common case */ - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); - if( iDb<0 ) return; - if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){ - /* If creating a temp table, the name may not be qualified. Unless - ** the database name is "temp" anyway. */ - sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); - return; - } - if( !OMIT_TEMPDB && isTemp ) iDb = 1; - zName = sqlite3NameFromToken(db, pName); - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenMap(pParse, (void*)zName, pName); - } - } - pParse->sNameToken = *pName; - if( zName==0 ) return; - if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){ - goto begin_table_error; - } - if( db->init.iDb==1 ) isTemp = 1; -#ifndef SQLITE_OMIT_AUTHORIZATION - assert( isTemp==0 || isTemp==1 ); - assert( isView==0 || isView==1 ); - { - static const u8 aCode[] = { - SQLITE_CREATE_TABLE, - SQLITE_CREATE_TEMP_TABLE, - SQLITE_CREATE_VIEW, - SQLITE_CREATE_TEMP_VIEW - }; - char *zDb = db->aDb[iDb].zDbSName; - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ - goto begin_table_error; - } - if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView], - zName, 0, zDb) ){ - goto begin_table_error; - } - } -#endif - - /* Make sure the new table name does not collide with an existing - ** index or table name in the same database. Issue an error message if - ** it does. The exception is if the statement being parsed was passed - ** to an sqlite3_declare_vtab() call. In that case only the column names - ** and types will be used, so there is no need to test for namespace - ** collisions. - */ - if( !IN_SPECIAL_PARSE ){ - char *zDb = db->aDb[iDb].zDbSName; - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ - goto begin_table_error; - } - pTable = sqlite3FindTable(db, zName, zDb); - if( pTable ){ - if( !noErr ){ - sqlite3ErrorMsg(pParse, "table %T already exists", pName); - }else{ - assert( !db->init.busy || CORRUPT_DB ); - sqlite3CodeVerifySchema(pParse, iDb); - } - goto begin_table_error; - } - if( sqlite3FindIndex(db, zName, zDb)!=0 ){ - sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); - goto begin_table_error; - } - } - - pTable = sqlite3DbMallocZero(db, sizeof(Table)); - if( pTable==0 ){ - assert( db->mallocFailed ); - pParse->rc = SQLITE_NOMEM_BKPT; - pParse->nErr++; - goto begin_table_error; - } - pTable->zName = zName; - pTable->iPKey = -1; - pTable->pSchema = db->aDb[iDb].pSchema; - pTable->nTabRef = 1; -#ifdef SQLITE_DEFAULT_ROWEST - pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST); -#else - pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); -#endif - assert( pParse->pNewTable==0 ); - pParse->pNewTable = pTable; - - /* If this is the magic sqlite_sequence table used by autoincrement, - ** then record a pointer to this table in the main database structure - ** so that INSERT can find the table easily. - */ -#ifndef SQLITE_OMIT_AUTOINCREMENT - if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pTable->pSchema->pSeqTab = pTable; - } -#endif - - /* Begin generating the code that will insert the table record into - ** the schema table. Note in particular that we must go ahead - ** and allocate the record number for the table entry now. Before any - ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause - ** indices to be created and the table record must come before the - ** indices. Hence, the record number for the table must be allocated - ** now. - */ - if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ - int addr1; - int fileFormat; - int reg1, reg2, reg3; - /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */ - static const char nullRow[] = { 6, 0, 0, 0, 0, 0 }; - sqlite3BeginWriteOperation(pParse, 1, iDb); - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( isVirtual ){ - sqlite3VdbeAddOp0(v, OP_VBegin); - } -#endif - - /* If the file format and encoding in the database have not been set, - ** set them now. - */ - reg1 = pParse->regRowid = ++pParse->nMem; - reg2 = pParse->regRoot = ++pParse->nMem; - reg3 = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); - sqlite3VdbeUsesBtree(v, iDb); - addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v); - fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? - 1 : SQLITE_MAX_FILE_FORMAT; - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db)); - sqlite3VdbeJumpHere(v, addr1); - - /* This just creates a place-holder record in the sqlite_schema table. - ** The record created does not contain anything yet. It will be replaced - ** by the real entry in code generated at sqlite3EndTable(). - ** - ** The rowid for the new entry is left in register pParse->regRowid. - ** The root page number of the new table is left in reg pParse->regRoot. - ** The rowid and root page number values are needed by the code that - ** sqlite3EndTable will generate. - */ -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) - if( isView || isVirtual ){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); - }else -#endif - { - pParse->addrCrTab = - sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY); - } - sqlite3OpenSchemaTable(pParse, iDb); - sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); - sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC); - sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3VdbeAddOp0(v, OP_Close); - } - - /* Normal (non-error) return. */ - return; - - /* If an error occurs, we jump here */ -begin_table_error: - sqlite3DbFree(db, zName); - return; -} - -/* Set properties of a table column based on the (magical) -** name of the column. -*/ -#if SQLITE_ENABLE_HIDDEN_COLUMNS -SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){ - if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){ - pCol->colFlags |= COLFLAG_HIDDEN; - }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){ - pTab->tabFlags |= TF_OOOHidden; - } -} -#endif - - -/* -** Add a new column to the table currently being constructed. -** -** The parser calls this routine once for each column declaration -** in a CREATE TABLE statement. sqlite3StartTable() gets called -** first to get things going. Then this routine is called for each -** column. -*/ -SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){ - Table *p; - int i; - char *z; - char *zType; - Column *pCol; - sqlite3 *db = pParse->db; - if( (p = pParse->pNewTable)==0 ) return; - if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); - return; - } - z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2); - if( z==0 ) return; - if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName); - memcpy(z, pName->z, pName->n); - z[pName->n] = 0; - sqlite3Dequote(z); - for(i=0; inCol; i++){ - if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){ - sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); - sqlite3DbFree(db, z); - return; - } - } - if( (p->nCol & 0x7)==0 ){ - Column *aNew; - aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0])); - if( aNew==0 ){ - sqlite3DbFree(db, z); - return; - } - p->aCol = aNew; - } - pCol = &p->aCol[p->nCol]; - memset(pCol, 0, sizeof(p->aCol[0])); - pCol->zName = z; - pCol->hName = sqlite3StrIHash(z); - sqlite3ColumnPropertiesFromName(p, pCol); - - if( pType->n==0 ){ - /* If there is no type specified, columns have the default affinity - ** 'BLOB' with a default size of 4 bytes. */ - pCol->affinity = SQLITE_AFF_BLOB; - pCol->szEst = 1; -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - if( 4>=sqlite3GlobalConfig.szSorterRef ){ - pCol->colFlags |= COLFLAG_SORTERREF; - } -#endif - }else{ - zType = z + sqlite3Strlen30(z) + 1; - memcpy(zType, pType->z, pType->n); - zType[pType->n] = 0; - sqlite3Dequote(zType); - pCol->affinity = sqlite3AffinityType(zType, pCol); - pCol->colFlags |= COLFLAG_HASTYPE; - } - p->nCol++; - p->nNVCol++; - pParse->constraintName.n = 0; -} - -/* -** This routine is called by the parser while in the middle of -** parsing a CREATE TABLE statement. A "NOT NULL" constraint has -** been seen on a column. This routine sets the notNull flag on -** the column currently under construction. -*/ -SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){ - Table *p; - Column *pCol; - p = pParse->pNewTable; - if( p==0 || NEVER(p->nCol<1) ) return; - pCol = &p->aCol[p->nCol-1]; - pCol->notNull = (u8)onError; - p->tabFlags |= TF_HasNotNull; - - /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created - ** on this column. */ - if( pCol->colFlags & COLFLAG_UNIQUE ){ - Index *pIdx; - for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ - assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None ); - if( pIdx->aiColumn[0]==p->nCol-1 ){ - pIdx->uniqNotNull = 1; - } - } - } -} - -/* -** Scan the column type name zType (length nType) and return the -** associated affinity type. -** -** This routine does a case-independent search of zType for the -** substrings in the following table. If one of the substrings is -** found, the corresponding affinity is returned. If zType contains -** more than one of the substrings, entries toward the top of -** the table take priority. For example, if zType is 'BLOBINT', -** SQLITE_AFF_INTEGER is returned. -** -** Substring | Affinity -** -------------------------------- -** 'INT' | SQLITE_AFF_INTEGER -** 'CHAR' | SQLITE_AFF_TEXT -** 'CLOB' | SQLITE_AFF_TEXT -** 'TEXT' | SQLITE_AFF_TEXT -** 'BLOB' | SQLITE_AFF_BLOB -** 'REAL' | SQLITE_AFF_REAL -** 'FLOA' | SQLITE_AFF_REAL -** 'DOUB' | SQLITE_AFF_REAL -** -** If none of the substrings in the above table are found, -** SQLITE_AFF_NUMERIC is returned. -*/ -SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){ - u32 h = 0; - char aff = SQLITE_AFF_NUMERIC; - const char *zChar = 0; - - assert( zIn!=0 ); - while( zIn[0] ){ - h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff]; - zIn++; - if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */ - aff = SQLITE_AFF_TEXT; - zChar = zIn; - }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */ - aff = SQLITE_AFF_TEXT; - }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */ - aff = SQLITE_AFF_TEXT; - }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */ - && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){ - aff = SQLITE_AFF_BLOB; - if( zIn[0]=='(' ) zChar = zIn; -#ifndef SQLITE_OMIT_FLOATING_POINT - }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */ - && aff==SQLITE_AFF_NUMERIC ){ - aff = SQLITE_AFF_REAL; - }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */ - && aff==SQLITE_AFF_NUMERIC ){ - aff = SQLITE_AFF_REAL; - }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */ - && aff==SQLITE_AFF_NUMERIC ){ - aff = SQLITE_AFF_REAL; -#endif - }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */ - aff = SQLITE_AFF_INTEGER; - break; - } - } - - /* If pCol is not NULL, store an estimate of the field size. The - ** estimate is scaled so that the size of an integer is 1. */ - if( pCol ){ - int v = 0; /* default size is approx 4 bytes */ - if( aff r=(k/4+1) */ - sqlite3GetInt32(zChar, &v); - break; - } - zChar++; - } - }else{ - v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ - } - } -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - if( v>=sqlite3GlobalConfig.szSorterRef ){ - pCol->colFlags |= COLFLAG_SORTERREF; - } -#endif - v = v/4 + 1; - if( v>255 ) v = 255; - pCol->szEst = v; - } - return aff; -} - -/* -** The expression is the default value for the most recently added column -** of the table currently under construction. -** -** Default value expressions must be constant. Raise an exception if this -** is not the case. -** -** This routine is called by the parser while in the middle of -** parsing a CREATE TABLE statement. -*/ -SQLITE_PRIVATE void sqlite3AddDefaultValue( - Parse *pParse, /* Parsing context */ - Expr *pExpr, /* The parsed expression of the default value */ - const char *zStart, /* Start of the default value text */ - const char *zEnd /* First character past end of defaut value text */ -){ - Table *p; - Column *pCol; - sqlite3 *db = pParse->db; - p = pParse->pNewTable; - if( p!=0 ){ - int isInit = db->init.busy && db->init.iDb!=1; - pCol = &(p->aCol[p->nCol-1]); - if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){ - sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", - pCol->zName); -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - }else if( pCol->colFlags & COLFLAG_GENERATED ){ - testcase( pCol->colFlags & COLFLAG_VIRTUAL ); - testcase( pCol->colFlags & COLFLAG_STORED ); - sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column"); -#endif - }else{ - /* A copy of pExpr is used instead of the original, as pExpr contains - ** tokens that point to volatile memory. - */ - Expr x; - sqlite3ExprDelete(db, pCol->pDflt); - memset(&x, 0, sizeof(x)); - x.op = TK_SPAN; - x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd); - x.pLeft = pExpr; - x.flags = EP_Skip; - pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); - sqlite3DbFree(db, x.u.zToken); - } - } - if( IN_RENAME_OBJECT ){ - sqlite3RenameExprUnmap(pParse, pExpr); - } - sqlite3ExprDelete(db, pExpr); -} - -/* -** Backwards Compatibility Hack: -** -** Historical versions of SQLite accepted strings as column names in -** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example: -** -** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim) -** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC); -** -** This is goofy. But to preserve backwards compatibility we continue to -** accept it. This routine does the necessary conversion. It converts -** the expression given in its argument from a TK_STRING into a TK_ID -** if the expression is just a TK_STRING with an optional COLLATE clause. -** If the expression is anything other than TK_STRING, the expression is -** unchanged. -*/ -static void sqlite3StringToId(Expr *p){ - if( p->op==TK_STRING ){ - p->op = TK_ID; - }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){ - p->pLeft->op = TK_ID; - } -} - -/* -** Tag the given column as being part of the PRIMARY KEY -*/ -static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){ - pCol->colFlags |= COLFLAG_PRIMKEY; -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( pCol->colFlags & COLFLAG_GENERATED ){ - testcase( pCol->colFlags & COLFLAG_VIRTUAL ); - testcase( pCol->colFlags & COLFLAG_STORED ); - sqlite3ErrorMsg(pParse, - "generated columns cannot be part of the PRIMARY KEY"); - } -#endif -} - -/* -** Designate the PRIMARY KEY for the table. pList is a list of names -** of columns that form the primary key. If pList is NULL, then the -** most recently added column of the table is the primary key. -** -** A table can have at most one primary key. If the table already has -** a primary key (and this is the second primary key) then create an -** error. -** -** If the PRIMARY KEY is on a single column whose datatype is INTEGER, -** then we will try to use that column as the rowid. Set the Table.iPKey -** field of the table under construction to be the index of the -** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is -** no INTEGER PRIMARY KEY. -** -** If the key is not an INTEGER PRIMARY KEY, then create a unique -** index for the key. No index is created for INTEGER PRIMARY KEYs. -*/ -SQLITE_PRIVATE void sqlite3AddPrimaryKey( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* List of field names to be indexed */ - int onError, /* What to do with a uniqueness conflict */ - int autoInc, /* True if the AUTOINCREMENT keyword is present */ - int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ -){ - Table *pTab = pParse->pNewTable; - Column *pCol = 0; - int iCol = -1, i; - int nTerm; - if( pTab==0 ) goto primary_key_exit; - if( pTab->tabFlags & TF_HasPrimaryKey ){ - sqlite3ErrorMsg(pParse, - "table \"%s\" has more than one primary key", pTab->zName); - goto primary_key_exit; - } - pTab->tabFlags |= TF_HasPrimaryKey; - if( pList==0 ){ - iCol = pTab->nCol - 1; - pCol = &pTab->aCol[iCol]; - makeColumnPartOfPrimaryKey(pParse, pCol); - nTerm = 1; - }else{ - nTerm = pList->nExpr; - for(i=0; ia[i].pExpr); - assert( pCExpr!=0 ); - sqlite3StringToId(pCExpr); - if( pCExpr->op==TK_ID ){ - const char *zCName = pCExpr->u.zToken; - for(iCol=0; iColnCol; iCol++){ - if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){ - pCol = &pTab->aCol[iCol]; - makeColumnPartOfPrimaryKey(pParse, pCol); - break; - } - } - } - } - } - if( nTerm==1 - && pCol - && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0 - && sortOrder!=SQLITE_SO_DESC - ){ - if( IN_RENAME_OBJECT && pList ){ - Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr); - sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr); - } - pTab->iPKey = iCol; - pTab->keyConf = (u8)onError; - assert( autoInc==0 || autoInc==1 ); - pTab->tabFlags |= autoInc*TF_Autoincrement; - if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags; - (void)sqlite3HasExplicitNulls(pParse, pList); - }else if( autoInc ){ -#ifndef SQLITE_OMIT_AUTOINCREMENT - sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " - "INTEGER PRIMARY KEY"); -#endif - }else{ - sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, - 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY); - pList = 0; - } - -primary_key_exit: - sqlite3ExprListDelete(pParse->db, pList); - return; -} - -/* -** Add a new CHECK constraint to the table currently under construction. -*/ -SQLITE_PRIVATE void sqlite3AddCheckConstraint( - Parse *pParse, /* Parsing context */ - Expr *pCheckExpr /* The check expression */ -){ -#ifndef SQLITE_OMIT_CHECK - Table *pTab = pParse->pNewTable; - sqlite3 *db = pParse->db; - if( pTab && !IN_DECLARE_VTAB - && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) - ){ - pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); - if( pParse->constraintName.n ){ - sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); - } - }else -#endif - { - sqlite3ExprDelete(pParse->db, pCheckExpr); - } -} - -/* -** Set the collation function of the most recently parsed table column -** to the CollSeq given. -*/ -SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){ - Table *p; - int i; - char *zColl; /* Dequoted name of collation sequence */ - sqlite3 *db; - - if( (p = pParse->pNewTable)==0 ) return; - i = p->nCol-1; - db = pParse->db; - zColl = sqlite3NameFromToken(db, pToken); - if( !zColl ) return; - - if( sqlite3LocateCollSeq(pParse, zColl) ){ - Index *pIdx; - sqlite3DbFree(db, p->aCol[i].zColl); - p->aCol[i].zColl = zColl; - - /* If the column is declared as " PRIMARY KEY COLLATE ", - ** then an index may have been created on this column before the - ** collation type was added. Correct this if it is the case. - */ - for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ - assert( pIdx->nKeyCol==1 ); - if( pIdx->aiColumn[0]==i ){ - pIdx->azColl[0] = p->aCol[i].zColl; - } - } - }else{ - sqlite3DbFree(db, zColl); - } -} - -/* Change the most recently parsed column to be a GENERATED ALWAYS AS -** column. -*/ -SQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){ -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - u8 eType = COLFLAG_VIRTUAL; - Table *pTab = pParse->pNewTable; - Column *pCol; - if( pTab==0 ){ - /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */ - goto generated_done; - } - pCol = &(pTab->aCol[pTab->nCol-1]); - if( IN_DECLARE_VTAB ){ - sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns"); - goto generated_done; - } - if( pCol->pDflt ) goto generated_error; - if( pType ){ - if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){ - /* no-op */ - }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){ - eType = COLFLAG_STORED; - }else{ - goto generated_error; - } - } - if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--; - pCol->colFlags |= eType; - assert( TF_HasVirtual==COLFLAG_VIRTUAL ); - assert( TF_HasStored==COLFLAG_STORED ); - pTab->tabFlags |= eType; - if( pCol->colFlags & COLFLAG_PRIMKEY ){ - makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */ - } - pCol->pDflt = pExpr; - pExpr = 0; - goto generated_done; - -generated_error: - sqlite3ErrorMsg(pParse, "error in generated column \"%s\"", - pCol->zName); -generated_done: - sqlite3ExprDelete(pParse->db, pExpr); -#else - /* Throw and error for the GENERATED ALWAYS AS clause if the - ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */ - sqlite3ErrorMsg(pParse, "generated columns not supported"); - sqlite3ExprDelete(pParse->db, pExpr); -#endif -} - -/* -** Generate code that will increment the schema cookie. -** -** The schema cookie is used to determine when the schema for the -** database changes. After each schema change, the cookie value -** changes. When a process first reads the schema it records the -** cookie. Thereafter, whenever it goes to access the database, -** it checks the cookie to make sure the schema has not changed -** since it was last read. -** -** This plan is not completely bullet-proof. It is possible for -** the schema to change multiple times and for the cookie to be -** set back to prior value. But schema changes are infrequent -** and the probability of hitting the same cookie value is only -** 1 chance in 2^32. So we're safe enough. -** -** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments -** the schema-version whenever the schema changes. -*/ -SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){ - sqlite3 *db = pParse->db; - Vdbe *v = pParse->pVdbe; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, - (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie)); -} - -/* -** Measure the number of characters needed to output the given -** identifier. The number returned includes any quotes used -** but does not include the null terminator. -** -** The estimate is conservative. It might be larger that what is -** really needed. -*/ -static int identLength(const char *z){ - int n; - for(n=0; *z; n++, z++){ - if( *z=='"' ){ n++; } - } - return n + 2; -} - -/* -** The first parameter is a pointer to an output buffer. The second -** parameter is a pointer to an integer that contains the offset at -** which to write into the output buffer. This function copies the -** nul-terminated string pointed to by the third parameter, zSignedIdent, -** to the specified offset in the buffer and updates *pIdx to refer -** to the first byte after the last byte written before returning. -** -** If the string zSignedIdent consists entirely of alpha-numeric -** characters, does not begin with a digit and is not an SQL keyword, -** then it is copied to the output buffer exactly as it is. Otherwise, -** it is quoted using double-quotes. -*/ -static void identPut(char *z, int *pIdx, char *zSignedIdent){ - unsigned char *zIdent = (unsigned char*)zSignedIdent; - int i, j, needQuote; - i = *pIdx; - - for(j=0; zIdent[j]; j++){ - if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break; - } - needQuote = sqlite3Isdigit(zIdent[0]) - || sqlite3KeywordCode(zIdent, j)!=TK_ID - || zIdent[j]!=0 - || j==0; - - if( needQuote ) z[i++] = '"'; - for(j=0; zIdent[j]; j++){ - z[i++] = zIdent[j]; - if( zIdent[j]=='"' ) z[i++] = '"'; - } - if( needQuote ) z[i++] = '"'; - z[i] = 0; - *pIdx = i; -} - -/* -** Generate a CREATE TABLE statement appropriate for the given -** table. Memory to hold the text of the statement is obtained -** from sqliteMalloc() and must be freed by the calling function. -*/ -static char *createTableStmt(sqlite3 *db, Table *p){ - int i, k, n; - char *zStmt; - char *zSep, *zSep2, *zEnd; - Column *pCol; - n = 0; - for(pCol = p->aCol, i=0; inCol; i++, pCol++){ - n += identLength(pCol->zName) + 5; - } - n += identLength(p->zName); - if( n<50 ){ - zSep = ""; - zSep2 = ","; - zEnd = ")"; - }else{ - zSep = "\n "; - zSep2 = ",\n "; - zEnd = "\n)"; - } - n += 35 + 6*p->nCol; - zStmt = sqlite3DbMallocRaw(0, n); - if( zStmt==0 ){ - sqlite3OomFault(db); - return 0; - } - sqlite3_snprintf(n, zStmt, "CREATE TABLE "); - k = sqlite3Strlen30(zStmt); - identPut(zStmt, &k, p->zName); - zStmt[k++] = '('; - for(pCol=p->aCol, i=0; inCol; i++, pCol++){ - static const char * const azType[] = { - /* SQLITE_AFF_BLOB */ "", - /* SQLITE_AFF_TEXT */ " TEXT", - /* SQLITE_AFF_NUMERIC */ " NUM", - /* SQLITE_AFF_INTEGER */ " INT", - /* SQLITE_AFF_REAL */ " REAL" - }; - int len; - const char *zType; - - sqlite3_snprintf(n-k, &zStmt[k], zSep); - k += sqlite3Strlen30(&zStmt[k]); - zSep = zSep2; - identPut(zStmt, &k, pCol->zName); - assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); - assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); - testcase( pCol->affinity==SQLITE_AFF_BLOB ); - testcase( pCol->affinity==SQLITE_AFF_TEXT ); - testcase( pCol->affinity==SQLITE_AFF_NUMERIC ); - testcase( pCol->affinity==SQLITE_AFF_INTEGER ); - testcase( pCol->affinity==SQLITE_AFF_REAL ); - - zType = azType[pCol->affinity - SQLITE_AFF_BLOB]; - len = sqlite3Strlen30(zType); - assert( pCol->affinity==SQLITE_AFF_BLOB - || pCol->affinity==sqlite3AffinityType(zType, 0) ); - memcpy(&zStmt[k], zType, len); - k += len; - assert( k<=n ); - } - sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); - return zStmt; -} - -/* -** Resize an Index object to hold N columns total. Return SQLITE_OK -** on success and SQLITE_NOMEM on an OOM error. -*/ -static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ - char *zExtra; - int nByte; - if( pIdx->nColumn>=N ) return SQLITE_OK; - assert( pIdx->isResized==0 ); - nByte = (sizeof(char*) + sizeof(i16) + 1)*N; - zExtra = sqlite3DbMallocZero(db, nByte); - if( zExtra==0 ) return SQLITE_NOMEM_BKPT; - memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); - pIdx->azColl = (const char**)zExtra; - zExtra += sizeof(char*)*N; - memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn); - pIdx->aiColumn = (i16*)zExtra; - zExtra += sizeof(i16)*N; - memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); - pIdx->aSortOrder = (u8*)zExtra; - pIdx->nColumn = N; - pIdx->isResized = 1; - return SQLITE_OK; -} - -/* -** Estimate the total row width for a table. -*/ -static void estimateTableWidth(Table *pTab){ - unsigned wTable = 0; - const Column *pTabCol; - int i; - for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){ - wTable += pTabCol->szEst; - } - if( pTab->iPKey<0 ) wTable++; - pTab->szTabRow = sqlite3LogEst(wTable*4); -} - -/* -** Estimate the average size of a row for an index. -*/ -static void estimateIndexWidth(Index *pIdx){ - unsigned wIndex = 0; - int i; - const Column *aCol = pIdx->pTable->aCol; - for(i=0; inColumn; i++){ - i16 x = pIdx->aiColumn[i]; - assert( xpTable->nCol ); - wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst; - } - pIdx->szIdxRow = sqlite3LogEst(wIndex*4); -} - -/* Return true if column number x is any of the first nCol entries of aiCol[]. -** This is used to determine if the column number x appears in any of the -** first nCol entries of an index. -*/ -static int hasColumn(const i16 *aiCol, int nCol, int x){ - while( nCol-- > 0 ){ - assert( aiCol[0]>=0 ); - if( x==*(aiCol++) ){ - return 1; - } - } - return 0; -} - -/* -** Return true if any of the first nKey entries of index pIdx exactly -** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID -** PRIMARY KEY index. pIdx is an index on the same table. pIdx may -** or may not be the same index as pPk. -** -** The first nKey entries of pIdx are guaranteed to be ordinary columns, -** not a rowid or expression. -** -** This routine differs from hasColumn() in that both the column and the -** collating sequence must match for this routine, but for hasColumn() only -** the column name must match. -*/ -static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){ - int i, j; - assert( nKey<=pIdx->nColumn ); - assert( iColnColumn,pPk->nKeyCol) ); - assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY ); - assert( pPk->pTable->tabFlags & TF_WithoutRowid ); - assert( pPk->pTable==pIdx->pTable ); - testcase( pPk==pIdx ); - j = pPk->aiColumn[iCol]; - assert( j!=XN_ROWID && j!=XN_EXPR ); - for(i=0; iaiColumn[i]>=0 || j>=0 ); - if( pIdx->aiColumn[i]==j - && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0 - ){ - return 1; - } - } - return 0; -} - -/* Recompute the colNotIdxed field of the Index. -** -** colNotIdxed is a bitmask that has a 0 bit representing each indexed -** columns that are within the first 63 columns of the table. The -** high-order bit of colNotIdxed is always 1. All unindexed columns -** of the table have a 1. -** -** 2019-10-24: For the purpose of this computation, virtual columns are -** not considered to be covered by the index, even if they are in the -** index, because we do not trust the logic in whereIndexExprTrans() to be -** able to find all instances of a reference to the indexed table column -** and convert them into references to the index. Hence we always want -** the actual table at hand in order to recompute the virtual column, if -** necessary. -** -** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask -** to determine if the index is covering index. -*/ -static void recomputeColumnsNotIndexed(Index *pIdx){ - Bitmask m = 0; - int j; - Table *pTab = pIdx->pTable; - for(j=pIdx->nColumn-1; j>=0; j--){ - int x = pIdx->aiColumn[j]; - if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){ - testcase( x==BMS-1 ); - testcase( x==BMS-2 ); - if( xcolNotIdxed = ~m; - assert( (pIdx->colNotIdxed>>63)==1 ); -} - -/* -** This routine runs at the end of parsing a CREATE TABLE statement that -** has a WITHOUT ROWID clause. The job of this routine is to convert both -** internal schema data structures and the generated VDBE code so that they -** are appropriate for a WITHOUT ROWID table instead of a rowid table. -** Changes include: -** -** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL. -** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY -** into BTREE_BLOBKEY. -** (3) Bypass the creation of the sqlite_schema table entry -** for the PRIMARY KEY as the primary key index is now -** identified by the sqlite_schema table entry of the table itself. -** (4) Set the Index.tnum of the PRIMARY KEY Index object in the -** schema to the rootpage from the main table. -** (5) Add all table columns to the PRIMARY KEY Index object -** so that the PRIMARY KEY is a covering index. The surplus -** columns are part of KeyInfo.nAllField and are not used for -** sorting or lookup or uniqueness checks. -** (6) Replace the rowid tail on all automatically generated UNIQUE -** indices with the PRIMARY KEY columns. -** -** For virtual tables, only (1) is performed. -*/ -static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ - Index *pIdx; - Index *pPk; - int nPk; - int nExtra; - int i, j; - sqlite3 *db = pParse->db; - Vdbe *v = pParse->pVdbe; - - /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables) - */ - if( !db->init.imposterTable ){ - for(i=0; inCol; i++){ - if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){ - pTab->aCol[i].notNull = OE_Abort; - } - } - pTab->tabFlags |= TF_HasNotNull; - } - - /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY - ** into BTREE_BLOBKEY. - */ - if( pParse->addrCrTab ){ - assert( v ); - sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY); - } - - /* Locate the PRIMARY KEY index. Or, if this table was originally - ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. - */ - if( pTab->iPKey>=0 ){ - ExprList *pList; - Token ipkToken; - sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName); - pList = sqlite3ExprListAppend(pParse, 0, - sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0)); - if( pList==0 ) return; - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey); - } - pList->a[0].sortFlags = pParse->iPkSortOrder; - assert( pParse->pNewTable==pTab ); - pTab->iPKey = -1; - sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, - SQLITE_IDXTYPE_PRIMARYKEY); - if( db->mallocFailed || pParse->nErr ) return; - pPk = sqlite3PrimaryKeyIndex(pTab); - assert( pPk->nKeyCol==1 ); - }else{ - pPk = sqlite3PrimaryKeyIndex(pTab); - assert( pPk!=0 ); - - /* - ** Remove all redundant columns from the PRIMARY KEY. For example, change - ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later - ** code assumes the PRIMARY KEY contains no repeated columns. - */ - for(i=j=1; inKeyCol; i++){ - if( isDupColumn(pPk, j, pPk, i) ){ - pPk->nColumn--; - }else{ - testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ); - pPk->azColl[j] = pPk->azColl[i]; - pPk->aSortOrder[j] = pPk->aSortOrder[i]; - pPk->aiColumn[j++] = pPk->aiColumn[i]; - } - } - pPk->nKeyCol = j; - } - assert( pPk!=0 ); - pPk->isCovering = 1; - if( !db->init.imposterTable ) pPk->uniqNotNull = 1; - nPk = pPk->nColumn = pPk->nKeyCol; - - /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema - ** table entry. This is only required if currently generating VDBE - ** code for a CREATE TABLE (not when parsing one as part of reading - ** a database schema). */ - if( v && pPk->tnum>0 ){ - assert( db->init.busy==0 ); - sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto); - } - - /* The root page of the PRIMARY KEY is the table root page */ - pPk->tnum = pTab->tnum; - - /* Update the in-memory representation of all UNIQUE indices by converting - ** the final rowid column into one or more columns of the PRIMARY KEY. - */ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - int n; - if( IsPrimaryKeyIndex(pIdx) ) continue; - for(i=n=0; inKeyCol, pPk, i) ){ - testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); - n++; - } - } - if( n==0 ){ - /* This index is a superset of the primary key */ - pIdx->nColumn = pIdx->nKeyCol; - continue; - } - if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; - for(i=0, j=pIdx->nKeyCol; inKeyCol, pPk, i) ){ - testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); - pIdx->aiColumn[j] = pPk->aiColumn[i]; - pIdx->azColl[j] = pPk->azColl[i]; - if( pPk->aSortOrder[i] ){ - /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */ - pIdx->bAscKeyBug = 1; - } - j++; - } - } - assert( pIdx->nColumn>=pIdx->nKeyCol+n ); - assert( pIdx->nColumn>=j ); - } - - /* Add all table columns to the PRIMARY KEY index - */ - nExtra = 0; - for(i=0; inCol; i++){ - if( !hasColumn(pPk->aiColumn, nPk, i) - && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++; - } - if( resizeIndexObject(db, pPk, nPk+nExtra) ) return; - for(i=0, j=nPk; inCol; i++){ - if( !hasColumn(pPk->aiColumn, j, i) - && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 - ){ - assert( jnColumn ); - pPk->aiColumn[j] = i; - pPk->azColl[j] = sqlite3StrBINARY; - j++; - } - } - assert( pPk->nColumn==j ); - assert( pTab->nNVCol<=j ); - recomputeColumnsNotIndexed(pPk); -} - - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Return true if pTab is a virtual table and zName is a shadow table name -** for that virtual table. -*/ -SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){ - int nName; /* Length of zName */ - Module *pMod; /* Module for the virtual table */ - - if( !IsVirtual(pTab) ) return 0; - nName = sqlite3Strlen30(pTab->zName); - if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0; - if( zName[nName]!='_' ) return 0; - pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]); - if( pMod==0 ) return 0; - if( pMod->pModule->iVersion<3 ) return 0; - if( pMod->pModule->xShadowName==0 ) return 0; - return pMod->pModule->xShadowName(zName+nName+1); -} -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Return true if zName is a shadow table name in the current database -** connection. -** -** zName is temporarily modified while this routine is running, but is -** restored to its original value prior to this routine returning. -*/ -SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){ - char *zTail; /* Pointer to the last "_" in zName */ - Table *pTab; /* Table that zName is a shadow of */ - zTail = strrchr(zName, '_'); - if( zTail==0 ) return 0; - *zTail = 0; - pTab = sqlite3FindTable(db, zName, 0); - *zTail = '_'; - if( pTab==0 ) return 0; - if( !IsVirtual(pTab) ) return 0; - return sqlite3IsShadowTableOf(db, pTab, zName); -} -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ - - -#ifdef SQLITE_DEBUG -/* -** Mark all nodes of an expression as EP_Immutable, indicating that -** they should not be changed. Expressions attached to a table or -** index definition are tagged this way to help ensure that we do -** not pass them into code generator routines by mistake. -*/ -static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){ - ExprSetVVAProperty(pExpr, EP_Immutable); - return WRC_Continue; -} -static void markExprListImmutable(ExprList *pList){ - if( pList ){ - Walker w; - memset(&w, 0, sizeof(w)); - w.xExprCallback = markImmutableExprStep; - w.xSelectCallback = sqlite3SelectWalkNoop; - w.xSelectCallback2 = 0; - sqlite3WalkExprList(&w, pList); - } -} -#else -#define markExprListImmutable(X) /* no-op */ -#endif /* SQLITE_DEBUG */ - - -/* -** This routine is called to report the final ")" that terminates -** a CREATE TABLE statement. -** -** The table structure that other action routines have been building -** is added to the internal hash tables, assuming no errors have -** occurred. -** -** An entry for the table is made in the schema table on disk, unless -** this is a temporary table or db->init.busy==1. When db->init.busy==1 -** it means we are reading the sqlite_schema table because we just -** connected to the database or because the sqlite_schema table has -** recently changed, so the entry for this table already exists in -** the sqlite_schema table. We do not want to create it again. -** -** If the pSelect argument is not NULL, it means that this routine -** was called to create a table generated from a -** "CREATE TABLE ... AS SELECT ..." statement. The column names of -** the new table will match the result set of the SELECT. -*/ -SQLITE_PRIVATE void sqlite3EndTable( - Parse *pParse, /* Parse context */ - Token *pCons, /* The ',' token after the last column defn. */ - Token *pEnd, /* The ')' before options in the CREATE TABLE */ - u8 tabOpts, /* Extra table options. Usually 0. */ - Select *pSelect /* Select from a "CREATE ... AS SELECT" */ -){ - Table *p; /* The new table */ - sqlite3 *db = pParse->db; /* The database connection */ - int iDb; /* Database in which the table lives */ - Index *pIdx; /* An implied index of the table */ - - if( pEnd==0 && pSelect==0 ){ - return; - } - assert( !db->mallocFailed ); - p = pParse->pNewTable; - if( p==0 ) return; - - if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){ - p->tabFlags |= TF_Shadow; - } - - /* If the db->init.busy is 1 it means we are reading the SQL off the - ** "sqlite_schema" or "sqlite_temp_schema" table on the disk. - ** So do not write to the disk again. Extract the root page number - ** for the table from the db->init.newTnum field. (The page number - ** should have been put there by the sqliteOpenCb routine.) - ** - ** If the root page number is 1, that means this is the sqlite_schema - ** table itself. So mark it read-only. - */ - if( db->init.busy ){ - if( pSelect ){ - sqlite3ErrorMsg(pParse, ""); - return; - } - p->tnum = db->init.newTnum; - if( p->tnum==1 ) p->tabFlags |= TF_Readonly; - } - - assert( (p->tabFlags & TF_HasPrimaryKey)==0 - || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 ); - assert( (p->tabFlags & TF_HasPrimaryKey)!=0 - || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) ); - - /* Special processing for WITHOUT ROWID Tables */ - if( tabOpts & TF_WithoutRowid ){ - if( (p->tabFlags & TF_Autoincrement) ){ - sqlite3ErrorMsg(pParse, - "AUTOINCREMENT not allowed on WITHOUT ROWID tables"); - return; - } - if( (p->tabFlags & TF_HasPrimaryKey)==0 ){ - sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName); - return; - } - p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid; - convertToWithoutRowidTable(pParse, p); - } - iDb = sqlite3SchemaToIndex(db, p->pSchema); - -#ifndef SQLITE_OMIT_CHECK - /* Resolve names in all CHECK constraint expressions. - */ - if( p->pCheck ){ - sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck); - if( pParse->nErr ){ - /* If errors are seen, delete the CHECK constraints now, else they might - ** actually be used if PRAGMA writable_schema=ON is set. */ - sqlite3ExprListDelete(db, p->pCheck); - p->pCheck = 0; - }else{ - markExprListImmutable(p->pCheck); - } - } -#endif /* !defined(SQLITE_OMIT_CHECK) */ -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( p->tabFlags & TF_HasGenerated ){ - int ii, nNG = 0; - testcase( p->tabFlags & TF_HasVirtual ); - testcase( p->tabFlags & TF_HasStored ); - for(ii=0; iinCol; ii++){ - u32 colFlags = p->aCol[ii].colFlags; - if( (colFlags & COLFLAG_GENERATED)!=0 ){ - Expr *pX = p->aCol[ii].pDflt; - testcase( colFlags & COLFLAG_VIRTUAL ); - testcase( colFlags & COLFLAG_STORED ); - if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){ - /* If there are errors in resolving the expression, change the - ** expression to a NULL. This prevents code generators that operate - ** on the expression from inserting extra parts into the expression - ** tree that have been allocated from lookaside memory, which is - ** illegal in a schema and will lead to errors or heap corruption - ** when the database connection closes. */ - sqlite3ExprDelete(db, pX); - p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0); - } - }else{ - nNG++; - } - } - if( nNG==0 ){ - sqlite3ErrorMsg(pParse, "must have at least one non-generated column"); - return; - } - } -#endif - - /* Estimate the average row size for the table and for all implied indices */ - estimateTableWidth(p); - for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ - estimateIndexWidth(pIdx); - } - - /* If not initializing, then create a record for the new table - ** in the schema table of the database. - ** - ** If this is a TEMPORARY table, write the entry into the auxiliary - ** file instead of into the main database file. - */ - if( !db->init.busy ){ - int n; - Vdbe *v; - char *zType; /* "view" or "table" */ - char *zType2; /* "VIEW" or "TABLE" */ - char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ - - v = sqlite3GetVdbe(pParse); - if( NEVER(v==0) ) return; - - sqlite3VdbeAddOp1(v, OP_Close, 0); - - /* - ** Initialize zType for the new view or table. - */ - if( p->pSelect==0 ){ - /* A regular table */ - zType = "table"; - zType2 = "TABLE"; -#ifndef SQLITE_OMIT_VIEW - }else{ - /* A view */ - zType = "view"; - zType2 = "VIEW"; -#endif - } - - /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT - ** statement to populate the new table. The root-page number for the - ** new table is in register pParse->regRoot. - ** - ** Once the SELECT has been coded by sqlite3Select(), it is in a - ** suitable state to query for the column names and types to be used - ** by the new table. - ** - ** A shared-cache write-lock is not required to write to the new table, - ** as a schema-lock must have already been obtained to create it. Since - ** a schema-lock excludes all other database users, the write-lock would - ** be redundant. - */ - if( pSelect ){ - SelectDest dest; /* Where the SELECT should store results */ - int regYield; /* Register holding co-routine entry-point */ - int addrTop; /* Top of the co-routine */ - int regRec; /* A record to be insert into the new table */ - int regRowid; /* Rowid of the next row to insert */ - int addrInsLoop; /* Top of the loop for inserting rows */ - Table *pSelTab; /* A table that describes the SELECT results */ - - regYield = ++pParse->nMem; - regRec = ++pParse->nMem; - regRowid = ++pParse->nMem; - assert(pParse->nTab==1); - sqlite3MayAbort(pParse); - sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); - sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); - pParse->nTab = 2; - addrTop = sqlite3VdbeCurrentAddr(v) + 1; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); - if( pParse->nErr ) return; - pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB); - if( pSelTab==0 ) return; - assert( p->aCol==0 ); - p->nCol = p->nNVCol = pSelTab->nCol; - p->aCol = pSelTab->aCol; - pSelTab->nCol = 0; - pSelTab->aCol = 0; - sqlite3DeleteTable(db, pSelTab); - sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); - sqlite3Select(pParse, pSelect, &dest); - if( pParse->nErr ) return; - sqlite3VdbeEndCoroutine(v, regYield); - sqlite3VdbeJumpHere(v, addrTop - 1); - addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec); - sqlite3TableAffinity(v, p, 0); - sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid); - sqlite3VdbeGoto(v, addrInsLoop); - sqlite3VdbeJumpHere(v, addrInsLoop); - sqlite3VdbeAddOp1(v, OP_Close, 1); - } - - /* Compute the complete text of the CREATE statement */ - if( pSelect ){ - zStmt = createTableStmt(db, p); - }else{ - Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd; - n = (int)(pEnd2->z - pParse->sNameToken.z); - if( pEnd2->z[0]!=';' ) n += pEnd2->n; - zStmt = sqlite3MPrintf(db, - "CREATE %s %.*s", zType2, n, pParse->sNameToken.z - ); - } - - /* A slot for the record has already been allocated in the - ** schema table. We just need to update that slot with all - ** the information we've collected. - */ - sqlite3NestedParse(pParse, - "UPDATE %Q." DFLT_SCHEMA_TABLE - " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q" - " WHERE rowid=#%d", - db->aDb[iDb].zDbSName, - zType, - p->zName, - p->zName, - pParse->regRoot, - zStmt, - pParse->regRowid - ); - sqlite3DbFree(db, zStmt); - sqlite3ChangeCookie(pParse, iDb); - -#ifndef SQLITE_OMIT_AUTOINCREMENT - /* Check to see if we need to create an sqlite_sequence table for - ** keeping track of autoincrement keys. - */ - if( (p->tabFlags & TF_Autoincrement)!=0 ){ - Db *pDb = &db->aDb[iDb]; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( pDb->pSchema->pSeqTab==0 ){ - sqlite3NestedParse(pParse, - "CREATE TABLE %Q.sqlite_sequence(name,seq)", - pDb->zDbSName - ); - } - } -#endif - - /* Reparse everything to update our internal data structures */ - sqlite3VdbeAddParseSchemaOp(v, iDb, - sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName)); - } - - /* Add the table to the in-memory representation of the database. - */ - if( db->init.busy ){ - Table *pOld; - Schema *pSchema = p->pSchema; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p); - if( pOld ){ - assert( p==pOld ); /* Malloc must have failed inside HashInsert() */ - sqlite3OomFault(db); - return; - } - pParse->pNewTable = 0; - db->mDbFlags |= DBFLAG_SchemaChange; - -#ifndef SQLITE_OMIT_ALTERTABLE - if( !p->pSelect ){ - const char *zName = (const char *)pParse->sNameToken.z; - int nName; - assert( !pSelect && pCons && pEnd ); - if( pCons->z==0 ){ - pCons = pEnd; - } - nName = (int)((const char *)pCons->z - zName); - p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName); - } -#endif - } -} - -#ifndef SQLITE_OMIT_VIEW -/* -** The parser calls this routine in order to create a new VIEW -*/ -SQLITE_PRIVATE void sqlite3CreateView( - Parse *pParse, /* The parsing context */ - Token *pBegin, /* The CREATE token that begins the statement */ - Token *pName1, /* The token that holds the name of the view */ - Token *pName2, /* The token that holds the name of the view */ - ExprList *pCNames, /* Optional list of view column names */ - Select *pSelect, /* A SELECT statement that will become the new view */ - int isTemp, /* TRUE for a TEMPORARY view */ - int noErr /* Suppress error messages if VIEW already exists */ -){ - Table *p; - int n; - const char *z; - Token sEnd; - DbFixer sFix; - Token *pName = 0; - int iDb; - sqlite3 *db = pParse->db; - - if( pParse->nVar>0 ){ - sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); - goto create_view_fail; - } - sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr); - p = pParse->pNewTable; - if( p==0 || pParse->nErr ) goto create_view_fail; - sqlite3TwoPartName(pParse, pName1, pName2, &pName); - iDb = sqlite3SchemaToIndex(db, p->pSchema); - sqlite3FixInit(&sFix, pParse, iDb, "view", pName); - if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; - - /* Make a copy of the entire SELECT statement that defines the view. - ** This will force all the Expr.token.z values to be dynamically - ** allocated rather than point to the input string - which means that - ** they will persist after the current sqlite3_exec() call returns. - */ - pSelect->selFlags |= SF_View; - if( IN_RENAME_OBJECT ){ - p->pSelect = pSelect; - pSelect = 0; - }else{ - p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); - } - p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE); - if( db->mallocFailed ) goto create_view_fail; - - /* Locate the end of the CREATE VIEW statement. Make sEnd point to - ** the end. - */ - sEnd = pParse->sLastToken; - assert( sEnd.z[0]!=0 || sEnd.n==0 ); - if( sEnd.z[0]!=';' ){ - sEnd.z += sEnd.n; - } - sEnd.n = 0; - n = (int)(sEnd.z - pBegin->z); - assert( n>0 ); - z = pBegin->z; - while( sqlite3Isspace(z[n-1]) ){ n--; } - sEnd.z = &z[n-1]; - sEnd.n = 1; - - /* Use sqlite3EndTable() to add the view to the schema table */ - sqlite3EndTable(pParse, 0, &sEnd, 0, 0); - -create_view_fail: - sqlite3SelectDelete(db, pSelect); - if( IN_RENAME_OBJECT ){ - sqlite3RenameExprlistUnmap(pParse, pCNames); - } - sqlite3ExprListDelete(db, pCNames); - return; -} -#endif /* SQLITE_OMIT_VIEW */ - -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) -/* -** The Table structure pTable is really a VIEW. Fill in the names of -** the columns of the view in the pTable structure. Return the number -** of errors. If an error is seen leave an error message in pParse->zErrMsg. -*/ -SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){ - Table *pSelTab; /* A fake table from which we get the result set */ - Select *pSel; /* Copy of the SELECT that implements the view */ - int nErr = 0; /* Number of errors encountered */ - int n; /* Temporarily holds the number of cursors assigned */ - sqlite3 *db = pParse->db; /* Database connection for malloc errors */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - int rc; -#endif -#ifndef SQLITE_OMIT_AUTHORIZATION - sqlite3_xauth xAuth; /* Saved xAuth pointer */ -#endif - - assert( pTable ); - -#ifndef SQLITE_OMIT_VIRTUALTABLE - db->nSchemaLock++; - rc = sqlite3VtabCallConnect(pParse, pTable); - db->nSchemaLock--; - if( rc ){ - return 1; - } - if( IsVirtual(pTable) ) return 0; -#endif - -#ifndef SQLITE_OMIT_VIEW - /* A positive nCol means the columns names for this view are - ** already known. - */ - if( pTable->nCol>0 ) return 0; - - /* A negative nCol is a special marker meaning that we are currently - ** trying to compute the column names. If we enter this routine with - ** a negative nCol, it means two or more views form a loop, like this: - ** - ** CREATE VIEW one AS SELECT * FROM two; - ** CREATE VIEW two AS SELECT * FROM one; - ** - ** Actually, the error above is now caught prior to reaching this point. - ** But the following test is still important as it does come up - ** in the following: - ** - ** CREATE TABLE main.ex1(a); - ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1; - ** SELECT * FROM temp.ex1; - */ - if( pTable->nCol<0 ){ - sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName); - return 1; - } - assert( pTable->nCol>=0 ); - - /* If we get this far, it means we need to compute the table names. - ** Note that the call to sqlite3ResultSetOfSelect() will expand any - ** "*" elements in the results set of the view and will assign cursors - ** to the elements of the FROM clause. But we do not want these changes - ** to be permanent. So the computation is done on a copy of the SELECT - ** statement that defines the view. - */ - assert( pTable->pSelect ); - pSel = sqlite3SelectDup(db, pTable->pSelect, 0); - if( pSel ){ - u8 eParseMode = pParse->eParseMode; - pParse->eParseMode = PARSE_MODE_NORMAL; - n = pParse->nTab; - sqlite3SrcListAssignCursors(pParse, pSel->pSrc); - pTable->nCol = -1; - DisableLookaside; -#ifndef SQLITE_OMIT_AUTHORIZATION - xAuth = db->xAuth; - db->xAuth = 0; - pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); - db->xAuth = xAuth; -#else - pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE); -#endif - pParse->nTab = n; - if( pSelTab==0 ){ - pTable->nCol = 0; - nErr++; - }else if( pTable->pCheck ){ - /* CREATE VIEW name(arglist) AS ... - ** The names of the columns in the table are taken from - ** arglist which is stored in pTable->pCheck. The pCheck field - ** normally holds CHECK constraints on an ordinary table, but for - ** a VIEW it holds the list of column names. - */ - sqlite3ColumnsFromExprList(pParse, pTable->pCheck, - &pTable->nCol, &pTable->aCol); - if( db->mallocFailed==0 - && pParse->nErr==0 - && pTable->nCol==pSel->pEList->nExpr - ){ - sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel, - SQLITE_AFF_NONE); - } - }else{ - /* CREATE VIEW name AS... without an argument list. Construct - ** the column names from the SELECT statement that defines the view. - */ - assert( pTable->aCol==0 ); - pTable->nCol = pSelTab->nCol; - pTable->aCol = pSelTab->aCol; - pSelTab->nCol = 0; - pSelTab->aCol = 0; - assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) ); - } - pTable->nNVCol = pTable->nCol; - sqlite3DeleteTable(db, pSelTab); - sqlite3SelectDelete(db, pSel); - EnableLookaside; - pParse->eParseMode = eParseMode; - } else { - nErr++; - } - pTable->pSchema->schemaFlags |= DB_UnresetViews; - if( db->mallocFailed ){ - sqlite3DeleteColumnNames(db, pTable); - pTable->aCol = 0; - pTable->nCol = 0; - } -#endif /* SQLITE_OMIT_VIEW */ - return nErr; -} -#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ - -#ifndef SQLITE_OMIT_VIEW -/* -** Clear the column names from every VIEW in database idx. -*/ -static void sqliteViewResetAll(sqlite3 *db, int idx){ - HashElem *i; - assert( sqlite3SchemaMutexHeld(db, idx, 0) ); - if( !DbHasProperty(db, idx, DB_UnresetViews) ) return; - for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){ - Table *pTab = sqliteHashData(i); - if( pTab->pSelect ){ - sqlite3DeleteColumnNames(db, pTab); - pTab->aCol = 0; - pTab->nCol = 0; - } - } - DbClearProperty(db, idx, DB_UnresetViews); -} -#else -# define sqliteViewResetAll(A,B) -#endif /* SQLITE_OMIT_VIEW */ - -/* -** This function is called by the VDBE to adjust the internal schema -** used by SQLite when the btree layer moves a table root page. The -** root-page of a table or index in database iDb has changed from iFrom -** to iTo. -** -** Ticket #1728: The symbol table might still contain information -** on tables and/or indices that are the process of being deleted. -** If you are unlucky, one of those deleted indices or tables might -** have the same rootpage number as the real table or index that is -** being moved. So we cannot stop searching after the first match -** because the first match might be for one of the deleted indices -** or tables and not the table/index that is actually being moved. -** We must continue looping until all tables and indices with -** rootpage==iFrom have been converted to have a rootpage of iTo -** in order to be certain that we got the right one. -*/ -#ifndef SQLITE_OMIT_AUTOVACUUM -SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){ - HashElem *pElem; - Hash *pHash; - Db *pDb; - - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pDb = &db->aDb[iDb]; - pHash = &pDb->pSchema->tblHash; - for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ - Table *pTab = sqliteHashData(pElem); - if( pTab->tnum==iFrom ){ - pTab->tnum = iTo; - } - } - pHash = &pDb->pSchema->idxHash; - for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){ - Index *pIdx = sqliteHashData(pElem); - if( pIdx->tnum==iFrom ){ - pIdx->tnum = iTo; - } - } -} -#endif - -/* -** Write code to erase the table with root-page iTable from database iDb. -** Also write code to modify the sqlite_schema table and internal schema -** if a root-page of another table is moved by the btree-layer whilst -** erasing iTable (this can happen with an auto-vacuum database). -*/ -static void destroyRootPage(Parse *pParse, int iTable, int iDb){ - Vdbe *v = sqlite3GetVdbe(pParse); - int r1 = sqlite3GetTempReg(pParse); - if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema"); - sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); - sqlite3MayAbort(pParse); -#ifndef SQLITE_OMIT_AUTOVACUUM - /* OP_Destroy stores an in integer r1. If this integer - ** is non-zero, then it is the root page number of a table moved to - ** location iTable. The following code modifies the sqlite_schema table to - ** reflect this. - ** - ** The "#NNN" in the SQL is a special constant that means whatever value - ** is in register NNN. See grammar rules associated with the TK_REGISTER - ** token for additional information. - */ - sqlite3NestedParse(pParse, - "UPDATE %Q." DFLT_SCHEMA_TABLE - " SET rootpage=%d WHERE #%d AND rootpage=#%d", - pParse->db->aDb[iDb].zDbSName, iTable, r1, r1); -#endif - sqlite3ReleaseTempReg(pParse, r1); -} - -/* -** Write VDBE code to erase table pTab and all associated indices on disk. -** Code to update the sqlite_schema tables and internal schema definitions -** in case a root-page belonging to another table is moved by the btree layer -** is also added (this can happen with an auto-vacuum database). -*/ -static void destroyTable(Parse *pParse, Table *pTab){ - /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM - ** is not defined), then it is important to call OP_Destroy on the - ** table and index root-pages in order, starting with the numerically - ** largest root-page number. This guarantees that none of the root-pages - ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the - ** following were coded: - ** - ** OP_Destroy 4 0 - ** ... - ** OP_Destroy 5 0 - ** - ** and root page 5 happened to be the largest root-page number in the - ** database, then root page 5 would be moved to page 4 by the - ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit - ** a free-list page. - */ - Pgno iTab = pTab->tnum; - Pgno iDestroyed = 0; - - while( 1 ){ - Index *pIdx; - Pgno iLargest = 0; - - if( iDestroyed==0 || iTabpIndex; pIdx; pIdx=pIdx->pNext){ - Pgno iIdx = pIdx->tnum; - assert( pIdx->pSchema==pTab->pSchema ); - if( (iDestroyed==0 || (iIdxiLargest ){ - iLargest = iIdx; - } - } - if( iLargest==0 ){ - return; - }else{ - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - assert( iDb>=0 && iDbdb->nDb ); - destroyRootPage(pParse, iLargest, iDb); - iDestroyed = iLargest; - } - } -} - -/* -** Remove entries from the sqlite_statN tables (for N in (1,2,3)) -** after a DROP INDEX or DROP TABLE command. -*/ -static void sqlite3ClearStatTables( - Parse *pParse, /* The parsing context */ - int iDb, /* The database number */ - const char *zType, /* "idx" or "tbl" */ - const char *zName /* Name of index or table */ -){ - int i; - const char *zDbName = pParse->db->aDb[iDb].zDbSName; - for(i=1; i<=4; i++){ - char zTab[24]; - sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i); - if( sqlite3FindTable(pParse->db, zTab, zDbName) ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.%s WHERE %s=%Q", - zDbName, zTab, zType, zName - ); - } - } -} - -/* -** Generate code to drop a table. -*/ -SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){ - Vdbe *v; - sqlite3 *db = pParse->db; - Trigger *pTrigger; - Db *pDb = &db->aDb[iDb]; - - v = sqlite3GetVdbe(pParse); - assert( v!=0 ); - sqlite3BeginWriteOperation(pParse, 1, iDb); - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp0(v, OP_VBegin); - } -#endif - - /* Drop all triggers associated with the table being dropped. Code - ** is generated to remove entries from sqlite_schema and/or - ** sqlite_temp_schema if required. - */ - pTrigger = sqlite3TriggerList(pParse, pTab); - while( pTrigger ){ - assert( pTrigger->pSchema==pTab->pSchema || - pTrigger->pSchema==db->aDb[1].pSchema ); - sqlite3DropTriggerPtr(pParse, pTrigger); - pTrigger = pTrigger->pNext; - } - -#ifndef SQLITE_OMIT_AUTOINCREMENT - /* Remove any entries of the sqlite_sequence table associated with - ** the table being dropped. This is done before the table is dropped - ** at the btree level, in case the sqlite_sequence table needs to - ** move as a result of the drop (can happen in auto-vacuum mode). - */ - if( pTab->tabFlags & TF_Autoincrement ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.sqlite_sequence WHERE name=%Q", - pDb->zDbSName, pTab->zName - ); - } -#endif - - /* Drop all entries in the schema table that refer to the - ** table. The program name loops through the schema table and deletes - ** every row that refers to a table of the same name as the one being - ** dropped. Triggers are handled separately because a trigger can be - ** created in the temp database that refers to a table in another - ** database. - */ - sqlite3NestedParse(pParse, - "DELETE FROM %Q." DFLT_SCHEMA_TABLE - " WHERE tbl_name=%Q and type!='trigger'", - pDb->zDbSName, pTab->zName); - if( !isView && !IsVirtual(pTab) ){ - destroyTable(pParse, pTab); - } - - /* Remove the table entry from SQLite's internal schema and modify - ** the schema cookie. - */ - if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); - sqlite3MayAbort(pParse); - } - sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); - sqlite3ChangeCookie(pParse, iDb); - sqliteViewResetAll(db, iDb); -} - -/* -** Return TRUE if shadow tables should be read-only in the current -** context. -*/ -SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db){ -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( (db->flags & SQLITE_Defensive)!=0 - && db->pVtabCtx==0 - && db->nVdbeExec==0 - ){ - return 1; - } -#endif - return 0; -} - -/* -** Return true if it is not allowed to drop the given table -*/ -static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){ - if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ - if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0; - if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0; - return 1; - } - if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){ - return 1; - } - return 0; -} - -/* -** This routine is called to do the work of a DROP TABLE statement. -** pName is the name of the table to be dropped. -*/ -SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ - Table *pTab; - Vdbe *v; - sqlite3 *db = pParse->db; - int iDb; - - if( db->mallocFailed ){ - goto exit_drop_table; - } - assert( pParse->nErr==0 ); - assert( pName->nSrc==1 ); - if( sqlite3ReadSchema(pParse) ) goto exit_drop_table; - if( noErr ) db->suppressErr++; - assert( isView==0 || isView==LOCATE_VIEW ); - pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]); - if( noErr ) db->suppressErr--; - - if( pTab==0 ){ - if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); - goto exit_drop_table; - } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - assert( iDb>=0 && iDbnDb ); - - /* If pTab is a virtual table, call ViewGetColumnNames() to ensure - ** it is initialized. - */ - if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){ - goto exit_drop_table; - } -#ifndef SQLITE_OMIT_AUTHORIZATION - { - int code; - const char *zTab = SCHEMA_TABLE(iDb); - const char *zDb = db->aDb[iDb].zDbSName; - const char *zArg2 = 0; - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){ - goto exit_drop_table; - } - if( isView ){ - if( !OMIT_TEMPDB && iDb==1 ){ - code = SQLITE_DROP_TEMP_VIEW; - }else{ - code = SQLITE_DROP_VIEW; - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - }else if( IsVirtual(pTab) ){ - code = SQLITE_DROP_VTABLE; - zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName; -#endif - }else{ - if( !OMIT_TEMPDB && iDb==1 ){ - code = SQLITE_DROP_TEMP_TABLE; - }else{ - code = SQLITE_DROP_TABLE; - } - } - if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){ - goto exit_drop_table; - } - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){ - goto exit_drop_table; - } - } -#endif - if( tableMayNotBeDropped(db, pTab) ){ - sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName); - goto exit_drop_table; - } - -#ifndef SQLITE_OMIT_VIEW - /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used - ** on a table. - */ - if( isView && pTab->pSelect==0 ){ - sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName); - goto exit_drop_table; - } - if( !isView && pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName); - goto exit_drop_table; - } -#endif - - /* Generate code to remove the table from the schema table - ** on disk. - */ - v = sqlite3GetVdbe(pParse); - if( v ){ - sqlite3BeginWriteOperation(pParse, 1, iDb); - if( !isView ){ - sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName); - sqlite3FkDropTable(pParse, pName, pTab); - } - sqlite3CodeDropTable(pParse, pTab, iDb, isView); - } - -exit_drop_table: - sqlite3SrcListDelete(db, pName); -} - -/* -** This routine is called to create a new foreign key on the table -** currently under construction. pFromCol determines which columns -** in the current table point to the foreign key. If pFromCol==0 then -** connect the key to the last column inserted. pTo is the name of -** the table referred to (a.k.a the "parent" table). pToCol is a list -** of tables in the parent pTo table. flags contains all -** information about the conflict resolution algorithms specified -** in the ON DELETE, ON UPDATE and ON INSERT clauses. -** -** An FKey structure is created and added to the table currently -** under construction in the pParse->pNewTable field. -** -** The foreign key is set for IMMEDIATE processing. A subsequent call -** to sqlite3DeferForeignKey() might change this to DEFERRED. -*/ -SQLITE_PRIVATE void sqlite3CreateForeignKey( - Parse *pParse, /* Parsing context */ - ExprList *pFromCol, /* Columns in this table that point to other table */ - Token *pTo, /* Name of the other table */ - ExprList *pToCol, /* Columns in the other table */ - int flags /* Conflict resolution algorithms. */ -){ - sqlite3 *db = pParse->db; -#ifndef SQLITE_OMIT_FOREIGN_KEY - FKey *pFKey = 0; - FKey *pNextTo; - Table *p = pParse->pNewTable; - int nByte; - int i; - int nCol; - char *z; - - assert( pTo!=0 ); - if( p==0 || IN_DECLARE_VTAB ) goto fk_end; - if( pFromCol==0 ){ - int iCol = p->nCol-1; - if( NEVER(iCol<0) ) goto fk_end; - if( pToCol && pToCol->nExpr!=1 ){ - sqlite3ErrorMsg(pParse, "foreign key on %s" - " should reference only one column of table %T", - p->aCol[iCol].zName, pTo); - goto fk_end; - } - nCol = 1; - }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ - sqlite3ErrorMsg(pParse, - "number of columns in foreign key does not match the number of " - "columns in the referenced table"); - goto fk_end; - }else{ - nCol = pFromCol->nExpr; - } - nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; - if( pToCol ){ - for(i=0; inExpr; i++){ - nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1; - } - } - pFKey = sqlite3DbMallocZero(db, nByte ); - if( pFKey==0 ){ - goto fk_end; - } - pFKey->pFrom = p; - pFKey->pNextFrom = p->pFKey; - z = (char*)&pFKey->aCol[nCol]; - pFKey->zTo = z; - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenMap(pParse, (void*)z, pTo); - } - memcpy(z, pTo->z, pTo->n); - z[pTo->n] = 0; - sqlite3Dequote(z); - z += pTo->n+1; - pFKey->nCol = nCol; - if( pFromCol==0 ){ - pFKey->aCol[0].iFrom = p->nCol-1; - }else{ - for(i=0; inCol; j++){ - if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){ - pFKey->aCol[i].iFrom = j; - break; - } - } - if( j>=p->nCol ){ - sqlite3ErrorMsg(pParse, - "unknown column \"%s\" in foreign key definition", - pFromCol->a[i].zEName); - goto fk_end; - } - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName); - } - } - } - if( pToCol ){ - for(i=0; ia[i].zEName); - pFKey->aCol[i].zCol = z; - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName); - } - memcpy(z, pToCol->a[i].zEName, n); - z[n] = 0; - z += n+1; - } - } - pFKey->isDeferred = 0; - pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ - pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ - - assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); - pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, - pFKey->zTo, (void *)pFKey - ); - if( pNextTo==pFKey ){ - sqlite3OomFault(db); - goto fk_end; - } - if( pNextTo ){ - assert( pNextTo->pPrevTo==0 ); - pFKey->pNextTo = pNextTo; - pNextTo->pPrevTo = pFKey; - } - - /* Link the foreign key to the table as the last step. - */ - p->pFKey = pFKey; - pFKey = 0; - -fk_end: - sqlite3DbFree(db, pFKey); -#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ - sqlite3ExprListDelete(db, pFromCol); - sqlite3ExprListDelete(db, pToCol); -} - -/* -** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED -** clause is seen as part of a foreign key definition. The isDeferred -** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE. -** The behavior of the most recently created foreign key is adjusted -** accordingly. -*/ -SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ -#ifndef SQLITE_OMIT_FOREIGN_KEY - Table *pTab; - FKey *pFKey; - if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return; - assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */ - pFKey->isDeferred = (u8)isDeferred; -#endif -} - -/* -** Generate code that will erase and refill index *pIdx. This is -** used to initialize a newly created index or to recompute the -** content of an index in response to a REINDEX command. -** -** if memRootPage is not negative, it means that the index is newly -** created. The register specified by memRootPage contains the -** root page number of the index. If memRootPage is negative, then -** the index already exists and must be cleared before being refilled and -** the root page number of the index is taken from pIndex->tnum. -*/ -static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ - Table *pTab = pIndex->pTable; /* The table that is indexed */ - int iTab = pParse->nTab++; /* Btree cursor used for pTab */ - int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */ - int iSorter; /* Cursor opened by OpenSorter (if in use) */ - int addr1; /* Address of top of loop */ - int addr2; /* Address to jump to for next iteration */ - Pgno tnum; /* Root page of index */ - int iPartIdxLabel; /* Jump to this label to skip a row */ - Vdbe *v; /* Generate code into this virtual machine */ - KeyInfo *pKey; /* KeyInfo for index */ - int regRecord; /* Register holding assembled index record */ - sqlite3 *db = pParse->db; /* The database connection */ - int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); - -#ifndef SQLITE_OMIT_AUTHORIZATION - if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, - db->aDb[iDb].zDbSName ) ){ - return; - } -#endif - - /* Require a write-lock on the table to perform this operation */ - sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); - - v = sqlite3GetVdbe(pParse); - if( v==0 ) return; - if( memRootPage>=0 ){ - tnum = (Pgno)memRootPage; - }else{ - tnum = pIndex->tnum; - } - pKey = sqlite3KeyInfoOfIndex(pParse, pIndex); - assert( pKey!=0 || db->mallocFailed || pParse->nErr ); - - /* Open the sorter cursor if we are to use one. */ - iSorter = pParse->nTab++; - sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*) - sqlite3KeyInfoRef(pKey), P4_KEYINFO); - - /* Open the table. Loop through all rows of the table, inserting index - ** records into the sorter. */ - sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v); - regRecord = sqlite3GetTempReg(pParse); - sqlite3MultiWrite(pParse); - - sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0); - sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord); - sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); - sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); - if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb, - (char *)pKey, P4_KEYINFO); - sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0)); - - addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v); - if( IsUniqueIndex(pIndex) ){ - int j2 = sqlite3VdbeGoto(v, 1); - addr2 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeVerifyAbortable(v, OE_Abort); - sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, - pIndex->nKeyCol); VdbeCoverage(v); - sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); - sqlite3VdbeJumpHere(v, j2); - }else{ - /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not - ** abort. The exception is if one of the indexed expressions contains a - ** user function that throws an exception when it is evaluated. But the - ** overhead of adding a statement journal to a CREATE INDEX statement is - ** very small (since most of the pages written do not contain content that - ** needs to be restored if the statement aborts), so we call - ** sqlite3MayAbort() for all CREATE INDEX statements. */ - sqlite3MayAbort(pParse); - addr2 = sqlite3VdbeCurrentAddr(v); - } - sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); - if( !pIndex->bAscKeyBug ){ - /* This OP_SeekEnd opcode makes index insert for a REINDEX go much - ** faster by avoiding unnecessary seeks. But the optimization does - ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables - ** with DESC primary keys, since those indexes have there keys in - ** a different order from the main table. - ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf - */ - sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx); - } - sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); - - sqlite3VdbeAddOp1(v, OP_Close, iTab); - sqlite3VdbeAddOp1(v, OP_Close, iIdx); - sqlite3VdbeAddOp1(v, OP_Close, iSorter); -} - -/* -** Allocate heap space to hold an Index object with nCol columns. -** -** Increase the allocation size to provide an extra nExtra bytes -** of 8-byte aligned space after the Index object and return a -** pointer to this extra space in *ppExtra. -*/ -SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( - sqlite3 *db, /* Database connection */ - i16 nCol, /* Total number of columns in the index */ - int nExtra, /* Number of bytes of extra space to alloc */ - char **ppExtra /* Pointer to the "extra" space */ -){ - Index *p; /* Allocated index object */ - int nByte; /* Bytes of space for Index object + arrays */ - - nByte = ROUND8(sizeof(Index)) + /* Index structure */ - ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ - ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ - sizeof(i16)*nCol + /* Index.aiColumn */ - sizeof(u8)*nCol); /* Index.aSortOrder */ - p = sqlite3DbMallocZero(db, nByte + nExtra); - if( p ){ - char *pExtra = ((char*)p)+ROUND8(sizeof(Index)); - p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol); - p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); - p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; - p->aSortOrder = (u8*)pExtra; - p->nColumn = nCol; - p->nKeyCol = nCol - 1; - *ppExtra = ((char*)p) + nByte; - } - return p; -} - -/* -** If expression list pList contains an expression that was parsed with -** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in -** pParse and return non-zero. Otherwise, return zero. -*/ -SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){ - if( pList ){ - int i; - for(i=0; inExpr; i++){ - if( pList->a[i].bNulls ){ - u8 sf = pList->a[i].sortFlags; - sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s", - (sf==0 || sf==3) ? "FIRST" : "LAST" - ); - return 1; - } - } - } - return 0; -} - -/* -** Create a new index for an SQL table. pName1.pName2 is the name of the index -** and pTblList is the name of the table that is to be indexed. Both will -** be NULL for a primary key or an index that is created to satisfy a -** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable -** as the table to be indexed. pParse->pNewTable is a table that is -** currently being constructed by a CREATE TABLE statement. -** -** pList is a list of columns to be indexed. pList will be NULL if this -** is a primary key or unique-constraint on the most recent column added -** to the table currently under construction. -*/ -SQLITE_PRIVATE void sqlite3CreateIndex( - Parse *pParse, /* All information about this parse */ - Token *pName1, /* First part of index name. May be NULL */ - Token *pName2, /* Second part of index name. May be NULL */ - SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ - ExprList *pList, /* A list of columns to be indexed */ - int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ - Token *pStart, /* The CREATE token that begins this statement */ - Expr *pPIWhere, /* WHERE clause for partial indices */ - int sortOrder, /* Sort order of primary key when pList==NULL */ - int ifNotExist, /* Omit error if index already exists */ - u8 idxType /* The index type */ -){ - Table *pTab = 0; /* Table to be indexed */ - Index *pIndex = 0; /* The index to be created */ - char *zName = 0; /* Name of the index */ - int nName; /* Number of characters in zName */ - int i, j; - DbFixer sFix; /* For assigning database names to pTable */ - int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */ - sqlite3 *db = pParse->db; - Db *pDb; /* The specific table containing the indexed database */ - int iDb; /* Index of the database that is being written */ - Token *pName = 0; /* Unqualified name of the index to create */ - struct ExprList_item *pListItem; /* For looping over pList */ - int nExtra = 0; /* Space allocated for zExtra[] */ - int nExtraCol; /* Number of extra columns needed */ - char *zExtra = 0; /* Extra space after the Index object */ - Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */ - - if( db->mallocFailed || pParse->nErr>0 ){ - goto exit_create_index; - } - if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){ - goto exit_create_index; - } - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ - goto exit_create_index; - } - if( sqlite3HasExplicitNulls(pParse, pList) ){ - goto exit_create_index; - } - - /* - ** Find the table that is to be indexed. Return early if not found. - */ - if( pTblName!=0 ){ - - /* Use the two-part index name to determine the database - ** to search for the table. 'Fix' the table name to this db - ** before looking up the table. - */ - assert( pName1 && pName2 ); - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); - if( iDb<0 ) goto exit_create_index; - assert( pName && pName->z ); - -#ifndef SQLITE_OMIT_TEMPDB - /* If the index name was unqualified, check if the table - ** is a temp table. If so, set the database to 1. Do not do this - ** if initialising a database schema. - */ - if( !db->init.busy ){ - pTab = sqlite3SrcListLookup(pParse, pTblName); - if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ - iDb = 1; - } - } -#endif - - sqlite3FixInit(&sFix, pParse, iDb, "index", pName); - if( sqlite3FixSrcList(&sFix, pTblName) ){ - /* Because the parser constructs pTblName from a single identifier, - ** sqlite3FixSrcList can never fail. */ - assert(0); - } - pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]); - assert( db->mallocFailed==0 || pTab==0 ); - if( pTab==0 ) goto exit_create_index; - if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){ - sqlite3ErrorMsg(pParse, - "cannot create a TEMP index on non-TEMP table \"%s\"", - pTab->zName); - goto exit_create_index; - } - if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab); - }else{ - assert( pName==0 ); - assert( pStart==0 ); - pTab = pParse->pNewTable; - if( !pTab ) goto exit_create_index; - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - } - pDb = &db->aDb[iDb]; - - assert( pTab!=0 ); - assert( pParse->nErr==0 ); - if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 - && db->init.busy==0 - && pTblName!=0 -#if SQLITE_USER_AUTHENTICATION - && sqlite3UserAuthTable(pTab->zName)==0 -#endif - ){ - sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); - goto exit_create_index; - } -#ifndef SQLITE_OMIT_VIEW - if( pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "views may not be indexed"); - goto exit_create_index; - } -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pTab) ){ - sqlite3ErrorMsg(pParse, "virtual tables may not be indexed"); - goto exit_create_index; - } -#endif - - /* - ** Find the name of the index. Make sure there is not already another - ** index or table with the same name. - ** - ** Exception: If we are reading the names of permanent indices from the - ** sqlite_schema table (because some other process changed the schema) and - ** one of the index names collides with the name of a temporary table or - ** index, then we will continue to process this index. - ** - ** If pName==0 it means that we are - ** dealing with a primary key or UNIQUE constraint. We have to invent our - ** own name. - */ - if( pName ){ - zName = sqlite3NameFromToken(db, pName); - if( zName==0 ) goto exit_create_index; - assert( pName->z!=0 ); - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){ - goto exit_create_index; - } - if( !IN_RENAME_OBJECT ){ - if( !db->init.busy ){ - if( sqlite3FindTable(db, zName, 0)!=0 ){ - sqlite3ErrorMsg(pParse, "there is already a table named %s", zName); - goto exit_create_index; - } - } - if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ - if( !ifNotExist ){ - sqlite3ErrorMsg(pParse, "index %s already exists", zName); - }else{ - assert( !db->init.busy ); - sqlite3CodeVerifySchema(pParse, iDb); - } - goto exit_create_index; - } - } - }else{ - int n; - Index *pLoop; - for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} - zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); - if( zName==0 ){ - goto exit_create_index; - } - - /* Automatic index names generated from within sqlite3_declare_vtab() - ** must have names that are distinct from normal automatic index names. - ** The following statement converts "sqlite3_autoindex..." into - ** "sqlite3_butoindex..." in order to make the names distinct. - ** The "vtab_err.test" test demonstrates the need of this statement. */ - if( IN_SPECIAL_PARSE ) zName[7]++; - } - - /* Check for authorization to create an index. - */ -#ifndef SQLITE_OMIT_AUTHORIZATION - if( !IN_RENAME_OBJECT ){ - const char *zDb = pDb->zDbSName; - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){ - goto exit_create_index; - } - i = SQLITE_CREATE_INDEX; - if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX; - if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){ - goto exit_create_index; - } - } -#endif - - /* If pList==0, it means this routine was called to make a primary - ** key out of the last column added to the table under construction. - ** So create a fake list to simulate this. - */ - if( pList==0 ){ - Token prevCol; - Column *pCol = &pTab->aCol[pTab->nCol-1]; - pCol->colFlags |= COLFLAG_UNIQUE; - sqlite3TokenInit(&prevCol, pCol->zName); - pList = sqlite3ExprListAppend(pParse, 0, - sqlite3ExprAlloc(db, TK_ID, &prevCol, 0)); - if( pList==0 ) goto exit_create_index; - assert( pList->nExpr==1 ); - sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED); - }else{ - sqlite3ExprListCheckLength(pParse, pList, "index"); - if( pParse->nErr ) goto exit_create_index; - } - - /* Figure out how many bytes of space are required to store explicitly - ** specified collation sequence names. - */ - for(i=0; inExpr; i++){ - Expr *pExpr = pList->a[i].pExpr; - assert( pExpr!=0 ); - if( pExpr->op==TK_COLLATE ){ - nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken)); - } - } - - /* - ** Allocate the index structure. - */ - nName = sqlite3Strlen30(zName); - nExtraCol = pPk ? pPk->nKeyCol : 1; - assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ ); - pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol, - nName + nExtra + 1, &zExtra); - if( db->mallocFailed ){ - goto exit_create_index; - } - assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) ); - assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) ); - pIndex->zName = zExtra; - zExtra += nName + 1; - memcpy(pIndex->zName, zName, nName+1); - pIndex->pTable = pTab; - pIndex->onError = (u8)onError; - pIndex->uniqNotNull = onError!=OE_None; - pIndex->idxType = idxType; - pIndex->pSchema = db->aDb[iDb].pSchema; - pIndex->nKeyCol = pList->nExpr; - if( pPIWhere ){ - sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0); - pIndex->pPartIdxWhere = pPIWhere; - pPIWhere = 0; - } - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - - /* Check to see if we should honor DESC requests on index columns - */ - if( pDb->pSchema->file_format>=4 ){ - sortOrderMask = -1; /* Honor DESC */ - }else{ - sortOrderMask = 0; /* Ignore DESC */ - } - - /* Analyze the list of expressions that form the terms of the index and - ** report any errors. In the common case where the expression is exactly - ** a table column, store that column in aiColumn[]. For general expressions, - ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[]. - ** - ** TODO: Issue a warning if two or more columns of the index are identical. - ** TODO: Issue a warning if the table primary key is used as part of the - ** index key. - */ - pListItem = pList->a; - if( IN_RENAME_OBJECT ){ - pIndex->aColExpr = pList; - pList = 0; - } - for(i=0; inKeyCol; i++, pListItem++){ - Expr *pCExpr; /* The i-th index expression */ - int requestedSortOrder; /* ASC or DESC on the i-th expression */ - const char *zColl; /* Collation sequence name */ - - sqlite3StringToId(pListItem->pExpr); - sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0); - if( pParse->nErr ) goto exit_create_index; - pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr); - if( pCExpr->op!=TK_COLUMN ){ - if( pTab==pParse->pNewTable ){ - sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and " - "UNIQUE constraints"); - goto exit_create_index; - } - if( pIndex->aColExpr==0 ){ - pIndex->aColExpr = pList; - pList = 0; - } - j = XN_EXPR; - pIndex->aiColumn[i] = XN_EXPR; - pIndex->uniqNotNull = 0; - }else{ - j = pCExpr->iColumn; - assert( j<=0x7fff ); - if( j<0 ){ - j = pTab->iPKey; - }else{ - if( pTab->aCol[j].notNull==0 ){ - pIndex->uniqNotNull = 0; - } - if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){ - pIndex->bHasVCol = 1; - } - } - pIndex->aiColumn[i] = (i16)j; - } - zColl = 0; - if( pListItem->pExpr->op==TK_COLLATE ){ - int nColl; - zColl = pListItem->pExpr->u.zToken; - nColl = sqlite3Strlen30(zColl) + 1; - assert( nExtra>=nColl ); - memcpy(zExtra, zColl, nColl); - zColl = zExtra; - zExtra += nColl; - nExtra -= nColl; - }else if( j>=0 ){ - zColl = pTab->aCol[j].zColl; - } - if( !zColl ) zColl = sqlite3StrBINARY; - if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){ - goto exit_create_index; - } - pIndex->azColl[i] = zColl; - requestedSortOrder = pListItem->sortFlags & sortOrderMask; - pIndex->aSortOrder[i] = (u8)requestedSortOrder; - } - - /* Append the table key to the end of the index. For WITHOUT ROWID - ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For - ** normal tables (when pPk==0) this will be the rowid. - */ - if( pPk ){ - for(j=0; jnKeyCol; j++){ - int x = pPk->aiColumn[j]; - assert( x>=0 ); - if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){ - pIndex->nColumn--; - }else{ - testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) ); - pIndex->aiColumn[i] = x; - pIndex->azColl[i] = pPk->azColl[j]; - pIndex->aSortOrder[i] = pPk->aSortOrder[j]; - i++; - } - } - assert( i==pIndex->nColumn ); - }else{ - pIndex->aiColumn[i] = XN_ROWID; - pIndex->azColl[i] = sqlite3StrBINARY; - } - sqlite3DefaultRowEst(pIndex); - if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex); - - /* If this index contains every column of its table, then mark - ** it as a covering index */ - assert( HasRowid(pTab) - || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 ); - recomputeColumnsNotIndexed(pIndex); - if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ - pIndex->isCovering = 1; - for(j=0; jnCol; j++){ - if( j==pTab->iPKey ) continue; - if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue; - pIndex->isCovering = 0; - break; - } - } - - if( pTab==pParse->pNewTable ){ - /* This routine has been called to create an automatic index as a - ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or - ** a PRIMARY KEY or UNIQUE clause following the column definitions. - ** i.e. one of: - ** - ** CREATE TABLE t(x PRIMARY KEY, y); - ** CREATE TABLE t(x, y, UNIQUE(x, y)); - ** - ** Either way, check to see if the table already has such an index. If - ** so, don't bother creating this one. This only applies to - ** automatically created indices. Users can do as they wish with - ** explicit indices. - ** - ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent - ** (and thus suppressing the second one) even if they have different - ** sort orders. - ** - ** If there are different collating sequences or if the columns of - ** the constraint occur in different orders, then the constraints are - ** considered distinct and both result in separate indices. - */ - Index *pIdx; - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - int k; - assert( IsUniqueIndex(pIdx) ); - assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF ); - assert( IsUniqueIndex(pIndex) ); - - if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue; - for(k=0; knKeyCol; k++){ - const char *z1; - const char *z2; - assert( pIdx->aiColumn[k]>=0 ); - if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break; - z1 = pIdx->azColl[k]; - z2 = pIndex->azColl[k]; - if( sqlite3StrICmp(z1, z2) ) break; - } - if( k==pIdx->nKeyCol ){ - if( pIdx->onError!=pIndex->onError ){ - /* This constraint creates the same index as a previous - ** constraint specified somewhere in the CREATE TABLE statement. - ** However the ON CONFLICT clauses are different. If both this - ** constraint and the previous equivalent constraint have explicit - ** ON CONFLICT clauses this is an error. Otherwise, use the - ** explicitly specified behavior for the index. - */ - if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){ - sqlite3ErrorMsg(pParse, - "conflicting ON CONFLICT clauses specified", 0); - } - if( pIdx->onError==OE_Default ){ - pIdx->onError = pIndex->onError; - } - } - if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType; - if( IN_RENAME_OBJECT ){ - pIndex->pNext = pParse->pNewIndex; - pParse->pNewIndex = pIndex; - pIndex = 0; - } - goto exit_create_index; - } - } - } - - if( !IN_RENAME_OBJECT ){ - - /* Link the new Index structure to its table and to the other - ** in-memory database structures. - */ - assert( pParse->nErr==0 ); - if( db->init.busy ){ - Index *p; - assert( !IN_SPECIAL_PARSE ); - assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); - if( pTblName!=0 ){ - pIndex->tnum = db->init.newTnum; - if( sqlite3IndexHasDuplicateRootPage(pIndex) ){ - sqlite3ErrorMsg(pParse, "invalid rootpage"); - pParse->rc = SQLITE_CORRUPT_BKPT; - goto exit_create_index; - } - } - p = sqlite3HashInsert(&pIndex->pSchema->idxHash, - pIndex->zName, pIndex); - if( p ){ - assert( p==pIndex ); /* Malloc must have failed */ - sqlite3OomFault(db); - goto exit_create_index; - } - db->mDbFlags |= DBFLAG_SchemaChange; - } - - /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the - ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then - ** emit code to allocate the index rootpage on disk and make an entry for - ** the index in the sqlite_schema table and populate the index with - ** content. But, do not do this if we are simply reading the sqlite_schema - ** table to parse the schema, or if this index is the PRIMARY KEY index - ** of a WITHOUT ROWID table. - ** - ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY - ** or UNIQUE index in a CREATE TABLE statement. Since the table - ** has just been created, it contains no data and the index initialization - ** step can be skipped. - */ - else if( HasRowid(pTab) || pTblName!=0 ){ - Vdbe *v; - char *zStmt; - int iMem = ++pParse->nMem; - - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto exit_create_index; - - sqlite3BeginWriteOperation(pParse, 1, iDb); - - /* Create the rootpage for the index using CreateIndex. But before - ** doing so, code a Noop instruction and store its address in - ** Index.tnum. This is required in case this index is actually a - ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In - ** that case the convertToWithoutRowidTable() routine will replace - ** the Noop with a Goto to jump over the VDBE code generated below. */ - pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop); - sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY); - - /* Gather the complete text of the CREATE INDEX statement into - ** the zStmt variable - */ - assert( pName!=0 || pStart==0 ); - if( pStart ){ - int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n; - if( pName->z[n-1]==';' ) n--; - /* A named index with an explicit CREATE INDEX statement */ - zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s", - onError==OE_None ? "" : " UNIQUE", n, pName->z); - }else{ - /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */ - /* zStmt = sqlite3MPrintf(""); */ - zStmt = 0; - } - - /* Add an entry in sqlite_schema for this index - */ - sqlite3NestedParse(pParse, - "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);", - db->aDb[iDb].zDbSName, - pIndex->zName, - pTab->zName, - iMem, - zStmt - ); - sqlite3DbFree(db, zStmt); - - /* Fill the index with data and reparse the schema. Code an OP_Expire - ** to invalidate all pre-compiled statements. - */ - if( pTblName ){ - sqlite3RefillIndex(pParse, pIndex, iMem); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddParseSchemaOp(v, iDb, - sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName)); - sqlite3VdbeAddOp2(v, OP_Expire, 0, 1); - } - - sqlite3VdbeJumpHere(v, (int)pIndex->tnum); - } - } - if( db->init.busy || pTblName==0 ){ - pIndex->pNext = pTab->pIndex; - pTab->pIndex = pIndex; - pIndex = 0; - } - else if( IN_RENAME_OBJECT ){ - assert( pParse->pNewIndex==0 ); - pParse->pNewIndex = pIndex; - pIndex = 0; - } - - /* Clean up before exiting */ -exit_create_index: - if( pIndex ) sqlite3FreeIndex(db, pIndex); - if( pTab ){ /* Ensure all REPLACE indexes are at the end of the list */ - Index **ppFrom = &pTab->pIndex; - Index *pThis; - for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){ - Index *pNext; - if( pThis->onError!=OE_Replace ) continue; - while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){ - *ppFrom = pNext; - pThis->pNext = pNext->pNext; - pNext->pNext = pThis; - ppFrom = &pNext->pNext; - } - break; - } - } - sqlite3ExprDelete(db, pPIWhere); - sqlite3ExprListDelete(db, pList); - sqlite3SrcListDelete(db, pTblName); - sqlite3DbFree(db, zName); -} - -/* -** Fill the Index.aiRowEst[] array with default information - information -** to be used when we have not run the ANALYZE command. -** -** aiRowEst[0] is supposed to contain the number of elements in the index. -** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the -** number of rows in the table that match any particular value of the -** first column of the index. aiRowEst[2] is an estimate of the number -** of rows that match any particular combination of the first 2 columns -** of the index. And so forth. It must always be the case that -* -** aiRowEst[N]<=aiRowEst[N-1] -** aiRowEst[N]>=1 -** -** Apart from that, we have little to go on besides intuition as to -** how aiRowEst[] should be initialized. The numbers generated here -** are based on typical values found in actual indices. -*/ -SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ - /* 10, 9, 8, 7, 6 */ - static const LogEst aVal[] = { 33, 32, 30, 28, 26 }; - LogEst *a = pIdx->aiRowLogEst; - LogEst x; - int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol); - int i; - - /* Indexes with default row estimates should not have stat1 data */ - assert( !pIdx->hasStat1 ); - - /* Set the first entry (number of rows in the index) to the estimated - ** number of rows in the table, or half the number of rows in the table - ** for a partial index. - ** - ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1 - ** table but other parts we are having to guess at, then do not let the - ** estimated number of rows in the table be less than 1000 (LogEst 99). - ** Failure to do this can cause the indexes for which we do not have - ** stat1 data to be ignored by the query planner. - */ - x = pIdx->pTable->nRowLogEst; - assert( 99==sqlite3LogEst(1000) ); - if( x<99 ){ - pIdx->pTable->nRowLogEst = x = 99; - } - if( pIdx->pPartIdxWhere!=0 ) x -= 10; assert( 10==sqlite3LogEst(2) ); - a[0] = x; - - /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is - ** 6 and each subsequent value (if any) is 5. */ - memcpy(&a[1], aVal, nCopy*sizeof(LogEst)); - for(i=nCopy+1; i<=pIdx->nKeyCol; i++){ - a[i] = 23; assert( 23==sqlite3LogEst(5) ); - } - - assert( 0==sqlite3LogEst(1) ); - if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0; -} - -/* -** This routine will drop an existing named index. This routine -** implements the DROP INDEX statement. -*/ -SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ - Index *pIndex; - Vdbe *v; - sqlite3 *db = pParse->db; - int iDb; - - assert( pParse->nErr==0 ); /* Never called with prior errors */ - if( db->mallocFailed ){ - goto exit_drop_index; - } - assert( pName->nSrc==1 ); - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ - goto exit_drop_index; - } - pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); - if( pIndex==0 ){ - if( !ifExists ){ - sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); - }else{ - sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase); - } - pParse->checkSchema = 1; - goto exit_drop_index; - } - if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){ - sqlite3ErrorMsg(pParse, "index associated with UNIQUE " - "or PRIMARY KEY constraint cannot be dropped", 0); - goto exit_drop_index; - } - iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); -#ifndef SQLITE_OMIT_AUTHORIZATION - { - int code = SQLITE_DROP_INDEX; - Table *pTab = pIndex->pTable; - const char *zDb = db->aDb[iDb].zDbSName; - const char *zTab = SCHEMA_TABLE(iDb); - if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ - goto exit_drop_index; - } - if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; - if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ - goto exit_drop_index; - } - } -#endif - - /* Generate code to remove the index and from the schema table */ - v = sqlite3GetVdbe(pParse); - if( v ){ - sqlite3BeginWriteOperation(pParse, 1, iDb); - sqlite3NestedParse(pParse, - "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'", - db->aDb[iDb].zDbSName, pIndex->zName - ); - sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName); - sqlite3ChangeCookie(pParse, iDb); - destroyRootPage(pParse, pIndex->tnum, iDb); - sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); - } - -exit_drop_index: - sqlite3SrcListDelete(db, pName); -} - -/* -** pArray is a pointer to an array of objects. Each object in the -** array is szEntry bytes in size. This routine uses sqlite3DbRealloc() -** to extend the array so that there is space for a new object at the end. -** -** When this function is called, *pnEntry contains the current size of -** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes -** in total). -** -** If the realloc() is successful (i.e. if no OOM condition occurs), the -** space allocated for the new object is zeroed, *pnEntry updated to -** reflect the new size of the array and a pointer to the new allocation -** returned. *pIdx is set to the index of the new array entry in this case. -** -** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains -** unchanged and a copy of pArray returned. -*/ -SQLITE_PRIVATE void *sqlite3ArrayAllocate( - sqlite3 *db, /* Connection to notify of malloc failures */ - void *pArray, /* Array of objects. Might be reallocated */ - int szEntry, /* Size of each object in the array */ - int *pnEntry, /* Number of objects currently in use */ - int *pIdx /* Write the index of a new slot here */ -){ - char *z; - sqlite3_int64 n = *pIdx = *pnEntry; - if( (n & (n-1))==0 ){ - sqlite3_int64 sz = (n==0) ? 1 : 2*n; - void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); - if( pNew==0 ){ - *pIdx = -1; - return pArray; - } - pArray = pNew; - } - z = (char*)pArray; - memset(&z[n * szEntry], 0, szEntry); - ++*pnEntry; - return pArray; -} - -/* -** Append a new element to the given IdList. Create a new IdList if -** need be. -** -** A new IdList is returned, or NULL if malloc() fails. -*/ -SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){ - sqlite3 *db = pParse->db; - int i; - if( pList==0 ){ - pList = sqlite3DbMallocZero(db, sizeof(IdList) ); - if( pList==0 ) return 0; - } - pList->a = sqlite3ArrayAllocate( - db, - pList->a, - sizeof(pList->a[0]), - &pList->nId, - &i - ); - if( i<0 ){ - sqlite3IdListDelete(db, pList); - return 0; - } - pList->a[i].zName = sqlite3NameFromToken(db, pToken); - if( IN_RENAME_OBJECT && pList->a[i].zName ){ - sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken); - } - return pList; -} - -/* -** Delete an IdList. -*/ -SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ - int i; - if( pList==0 ) return; - for(i=0; inId; i++){ - sqlite3DbFree(db, pList->a[i].zName); - } - sqlite3DbFree(db, pList->a); - sqlite3DbFreeNN(db, pList); -} - -/* -** Return the index in pList of the identifier named zId. Return -1 -** if not found. -*/ -SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){ - int i; - if( pList==0 ) return -1; - for(i=0; inId; i++){ - if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; - } - return -1; -} - -/* -** Maximum size of a SrcList object. -** The SrcList object is used to represent the FROM clause of a -** SELECT statement, and the query planner cannot deal with more -** than 64 tables in a join. So any value larger than 64 here -** is sufficient for most uses. Smaller values, like say 10, are -** appropriate for small and memory-limited applications. -*/ -#ifndef SQLITE_MAX_SRCLIST -# define SQLITE_MAX_SRCLIST 200 -#endif - -/* -** Expand the space allocated for the given SrcList object by -** creating nExtra new slots beginning at iStart. iStart is zero based. -** New slots are zeroed. -** -** For example, suppose a SrcList initially contains two entries: A,B. -** To append 3 new entries onto the end, do this: -** -** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); -** -** After the call above it would contain: A, B, nil, nil, nil. -** If the iStart argument had been 1 instead of 2, then the result -** would have been: A, nil, nil, nil, B. To prepend the new slots, -** the iStart value would be 0. The result then would -** be: nil, nil, nil, A, B. -** -** If a memory allocation fails or the SrcList becomes too large, leave -** the original SrcList unchanged, return NULL, and leave an error message -** in pParse. -*/ -SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( - Parse *pParse, /* Parsing context into which errors are reported */ - SrcList *pSrc, /* The SrcList to be enlarged */ - int nExtra, /* Number of new slots to add to pSrc->a[] */ - int iStart /* Index in pSrc->a[] of first new slot */ -){ - int i; - - /* Sanity checking on calling parameters */ - assert( iStart>=0 ); - assert( nExtra>=1 ); - assert( pSrc!=0 ); - assert( iStart<=pSrc->nSrc ); - - /* Allocate additional space if needed */ - if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ - SrcList *pNew; - sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra; - sqlite3 *db = pParse->db; - - if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){ - sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d", - SQLITE_MAX_SRCLIST); - return 0; - } - if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST; - pNew = sqlite3DbRealloc(db, pSrc, - sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); - if( pNew==0 ){ - assert( db->mallocFailed ); - return 0; - } - pSrc = pNew; - pSrc->nAlloc = nAlloc; - } - - /* Move existing slots that come after the newly inserted slots - ** out of the way */ - for(i=pSrc->nSrc-1; i>=iStart; i--){ - pSrc->a[i+nExtra] = pSrc->a[i]; - } - pSrc->nSrc += nExtra; - - /* Zero the newly allocated slots */ - memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra); - for(i=iStart; ia[i].iCursor = -1; - } - - /* Return a pointer to the enlarged SrcList */ - return pSrc; -} - - -/* -** Append a new table name to the given SrcList. Create a new SrcList if -** need be. A new entry is created in the SrcList even if pTable is NULL. -** -** A SrcList is returned, or NULL if there is an OOM error or if the -** SrcList grows to large. The returned -** SrcList might be the same as the SrcList that was input or it might be -** a new one. If an OOM error does occurs, then the prior value of pList -** that is input to this routine is automatically freed. -** -** If pDatabase is not null, it means that the table has an optional -** database name prefix. Like this: "database.table". The pDatabase -** points to the table name and the pTable points to the database name. -** The SrcList.a[].zName field is filled with the table name which might -** come from pTable (if pDatabase is NULL) or from pDatabase. -** SrcList.a[].zDatabase is filled with the database name from pTable, -** or with NULL if no database is specified. -** -** In other words, if call like this: -** -** sqlite3SrcListAppend(D,A,B,0); -** -** Then B is a table name and the database name is unspecified. If called -** like this: -** -** sqlite3SrcListAppend(D,A,B,C); -** -** Then C is the table name and B is the database name. If C is defined -** then so is B. In other words, we never have a case where: -** -** sqlite3SrcListAppend(D,A,0,C); -** -** Both pTable and pDatabase are assumed to be quoted. They are dequoted -** before being added to the SrcList. -*/ -SQLITE_PRIVATE SrcList *sqlite3SrcListAppend( - Parse *pParse, /* Parsing context, in which errors are reported */ - SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ - Token *pTable, /* Table to append */ - Token *pDatabase /* Database of the table */ -){ - struct SrcList_item *pItem; - sqlite3 *db; - assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ - assert( pParse!=0 ); - assert( pParse->db!=0 ); - db = pParse->db; - if( pList==0 ){ - pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) ); - if( pList==0 ) return 0; - pList->nAlloc = 1; - pList->nSrc = 1; - memset(&pList->a[0], 0, sizeof(pList->a[0])); - pList->a[0].iCursor = -1; - }else{ - SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc); - if( pNew==0 ){ - sqlite3SrcListDelete(db, pList); - return 0; - }else{ - pList = pNew; - } - } - pItem = &pList->a[pList->nSrc-1]; - if( pDatabase && pDatabase->z==0 ){ - pDatabase = 0; - } - if( pDatabase ){ - pItem->zName = sqlite3NameFromToken(db, pDatabase); - pItem->zDatabase = sqlite3NameFromToken(db, pTable); - }else{ - pItem->zName = sqlite3NameFromToken(db, pTable); - pItem->zDatabase = 0; - } - return pList; -} - -/* -** Assign VdbeCursor index numbers to all tables in a SrcList -*/ -SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ - int i; - struct SrcList_item *pItem; - assert(pList || pParse->db->mallocFailed ); - if( pList ){ - for(i=0, pItem=pList->a; inSrc; i++, pItem++){ - if( pItem->iCursor>=0 ) break; - pItem->iCursor = pParse->nTab++; - if( pItem->pSelect ){ - sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); - } - } - } -} - -/* -** Delete an entire SrcList including all its substructure. -*/ -SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){ - int i; - struct SrcList_item *pItem; - if( pList==0 ) return; - for(pItem=pList->a, i=0; inSrc; i++, pItem++){ - sqlite3DbFree(db, pItem->zDatabase); - sqlite3DbFree(db, pItem->zName); - sqlite3DbFree(db, pItem->zAlias); - if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy); - if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg); - sqlite3DeleteTable(db, pItem->pTab); - sqlite3SelectDelete(db, pItem->pSelect); - sqlite3ExprDelete(db, pItem->pOn); - sqlite3IdListDelete(db, pItem->pUsing); - } - sqlite3DbFreeNN(db, pList); -} - -/* -** This routine is called by the parser to add a new term to the -** end of a growing FROM clause. The "p" parameter is the part of -** the FROM clause that has already been constructed. "p" is NULL -** if this is the first term of the FROM clause. pTable and pDatabase -** are the name of the table and database named in the FROM clause term. -** pDatabase is NULL if the database name qualifier is missing - the -** usual case. If the term has an alias, then pAlias points to the -** alias token. If the term is a subquery, then pSubquery is the -** SELECT statement that the subquery encodes. The pTable and -** pDatabase parameters are NULL for subqueries. The pOn and pUsing -** parameters are the content of the ON and USING clauses. -** -** Return a new SrcList which encodes is the FROM with the new -** term added. -*/ -SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm( - Parse *pParse, /* Parsing context */ - SrcList *p, /* The left part of the FROM clause already seen */ - Token *pTable, /* Name of the table to add to the FROM clause */ - Token *pDatabase, /* Name of the database containing pTable */ - Token *pAlias, /* The right-hand side of the AS subexpression */ - Select *pSubquery, /* A subquery used in place of a table name */ - Expr *pOn, /* The ON clause of a join */ - IdList *pUsing /* The USING clause of a join */ -){ - struct SrcList_item *pItem; - sqlite3 *db = pParse->db; - if( !p && (pOn || pUsing) ){ - sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", - (pOn ? "ON" : "USING") - ); - goto append_from_error; - } - p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase); - if( p==0 ){ - goto append_from_error; - } - assert( p->nSrc>0 ); - pItem = &p->a[p->nSrc-1]; - assert( (pTable==0)==(pDatabase==0) ); - assert( pItem->zName==0 || pDatabase!=0 ); - if( IN_RENAME_OBJECT && pItem->zName ){ - Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable; - sqlite3RenameTokenMap(pParse, pItem->zName, pToken); - } - assert( pAlias!=0 ); - if( pAlias->n ){ - pItem->zAlias = sqlite3NameFromToken(db, pAlias); - } - pItem->pSelect = pSubquery; - pItem->pOn = pOn; - pItem->pUsing = pUsing; - return p; - - append_from_error: - assert( p==0 ); - sqlite3ExprDelete(db, pOn); - sqlite3IdListDelete(db, pUsing); - sqlite3SelectDelete(db, pSubquery); - return 0; -} - -/* -** Add an INDEXED BY or NOT INDEXED clause to the most recently added -** element of the source-list passed as the second argument. -*/ -SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){ - assert( pIndexedBy!=0 ); - if( p && pIndexedBy->n>0 ){ - struct SrcList_item *pItem; - assert( p->nSrc>0 ); - pItem = &p->a[p->nSrc-1]; - assert( pItem->fg.notIndexed==0 ); - assert( pItem->fg.isIndexedBy==0 ); - assert( pItem->fg.isTabFunc==0 ); - if( pIndexedBy->n==1 && !pIndexedBy->z ){ - /* A "NOT INDEXED" clause was supplied. See parse.y - ** construct "indexed_opt" for details. */ - pItem->fg.notIndexed = 1; - }else{ - pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy); - pItem->fg.isIndexedBy = 1; - } - } -} - -/* -** Append the contents of SrcList p2 to SrcList p1 and return the resulting -** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2 -** are deleted by this function. -*/ -SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){ - assert( p1 && p1->nSrc==1 ); - if( p2 ){ - SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1); - if( pNew==0 ){ - sqlite3SrcListDelete(pParse->db, p2); - }else{ - p1 = pNew; - memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(struct SrcList_item)); - sqlite3DbFree(pParse->db, p2); - } - } - return p1; -} - -/* -** Add the list of function arguments to the SrcList entry for a -** table-valued-function. -*/ -SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){ - if( p ){ - struct SrcList_item *pItem = &p->a[p->nSrc-1]; - assert( pItem->fg.notIndexed==0 ); - assert( pItem->fg.isIndexedBy==0 ); - assert( pItem->fg.isTabFunc==0 ); - pItem->u1.pFuncArg = pList; - pItem->fg.isTabFunc = 1; - }else{ - sqlite3ExprListDelete(pParse->db, pList); - } -} - -/* -** When building up a FROM clause in the parser, the join operator -** is initially attached to the left operand. But the code generator -** expects the join operator to be on the right operand. This routine -** Shifts all join operators from left to right for an entire FROM -** clause. -** -** Example: Suppose the join is like this: -** -** A natural cross join B -** -** The operator is "natural cross join". The A and B operands are stored -** in p->a[0] and p->a[1], respectively. The parser initially stores the -** operator with A. This routine shifts that operator over to B. -*/ -SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){ - if( p ){ - int i; - for(i=p->nSrc-1; i>0; i--){ - p->a[i].fg.jointype = p->a[i-1].fg.jointype; - } - p->a[0].fg.jointype = 0; - } -} - -/* -** Generate VDBE code for a BEGIN statement. -*/ -SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){ - sqlite3 *db; - Vdbe *v; - int i; - - assert( pParse!=0 ); - db = pParse->db; - assert( db!=0 ); - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){ - return; - } - v = sqlite3GetVdbe(pParse); - if( !v ) return; - if( type!=TK_DEFERRED ){ - for(i=0; inDb; i++){ - sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); - sqlite3VdbeUsesBtree(v, i); - } - } - sqlite3VdbeAddOp0(v, OP_AutoCommit); -} - -/* -** Generate VDBE code for a COMMIT or ROLLBACK statement. -** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise -** code is generated for a COMMIT. -*/ -SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){ - Vdbe *v; - int isRollback; - - assert( pParse!=0 ); - assert( pParse->db!=0 ); - assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK ); - isRollback = eType==TK_ROLLBACK; - if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, - isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){ - return; - } - v = sqlite3GetVdbe(pParse); - if( v ){ - sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback); - } -} - -/* -** This function is called by the parser when it parses a command to create, -** release or rollback an SQL savepoint. -*/ -SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){ - char *zName = sqlite3NameFromToken(pParse->db, pName); - if( zName ){ - Vdbe *v = sqlite3GetVdbe(pParse); -#ifndef SQLITE_OMIT_AUTHORIZATION - static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" }; - assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 ); -#endif - if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){ - sqlite3DbFree(pParse->db, zName); - return; - } - sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC); - } -} - -/* -** Make sure the TEMP database is open and available for use. Return -** the number of errors. Leave any error messages in the pParse structure. -*/ -SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ - sqlite3 *db = pParse->db; - if( db->aDb[1].pBt==0 && !pParse->explain ){ - int rc; - Btree *pBt; - static const int flags = - SQLITE_OPEN_READWRITE | - SQLITE_OPEN_CREATE | - SQLITE_OPEN_EXCLUSIVE | - SQLITE_OPEN_DELETEONCLOSE | - SQLITE_OPEN_TEMP_DB; - - rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags); - if( rc!=SQLITE_OK ){ - sqlite3ErrorMsg(pParse, "unable to open a temporary database " - "file for storing temporary tables"); - pParse->rc = rc; - return 1; - } - db->aDb[1].pBt = pBt; - assert( db->aDb[1].pSchema ); - if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){ - sqlite3OomFault(db); - return 1; - } - } - return 0; -} - -/* -** Record the fact that the schema cookie will need to be verified -** for database iDb. The code to actually verify the schema cookie -** will occur at the end of the top-level VDBE and will be generated -** later, by sqlite3FinishCoding(). -*/ -SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - - assert( iDb>=0 && iDbdb->nDb ); - assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 ); - assert( iDbdb, iDb, 0) ); - if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){ - DbMaskSet(pToplevel->cookieMask, iDb); - if( !OMIT_TEMPDB && iDb==1 ){ - sqlite3OpenTempDatabase(pToplevel); - } - } -} - -/* -** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each -** attached database. Otherwise, invoke it for the database named zDb only. -*/ -SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){ - sqlite3 *db = pParse->db; - int i; - for(i=0; inDb; i++){ - Db *pDb = &db->aDb[i]; - if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){ - sqlite3CodeVerifySchema(pParse, i); - } - } -} - -/* -** Generate VDBE code that prepares for doing an operation that -** might change the database. -** -** This routine starts a new transaction if we are not already within -** a transaction. If we are already within a transaction, then a checkpoint -** is set if the setStatement parameter is true. A checkpoint should -** be set for operations that might fail (due to a constraint) part of -** the way through and which will need to undo some writes without having to -** rollback the whole transaction. For operations where all constraints -** can be checked before any changes are made to the database, it is never -** necessary to undo a write and the checkpoint should not be set. -*/ -SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - sqlite3CodeVerifySchema(pParse, iDb); - DbMaskSet(pToplevel->writeMask, iDb); - pToplevel->isMultiWrite |= setStatement; -} - -/* -** Indicate that the statement currently under construction might write -** more than one entry (example: deleting one row then inserting another, -** inserting multiple rows in a table, or inserting a row and index entries.) -** If an abort occurs after some of these writes have completed, then it will -** be necessary to undo the completed writes. -*/ -SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - pToplevel->isMultiWrite = 1; -} - -/* -** The code generator calls this routine if is discovers that it is -** possible to abort a statement prior to completion. In order to -** perform this abort without corrupting the database, we need to make -** sure that the statement is protected by a statement transaction. -** -** Technically, we only need to set the mayAbort flag if the -** isMultiWrite flag was previously set. There is a time dependency -** such that the abort must occur after the multiwrite. This makes -** some statements involving the REPLACE conflict resolution algorithm -** go a little faster. But taking advantage of this time dependency -** makes it more difficult to prove that the code is correct (in -** particular, it prevents us from writing an effective -** implementation of sqlite3AssertMayAbort()) and so we have chosen -** to take the safe route and skip the optimization. -*/ -SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - pToplevel->mayAbort = 1; -} - -/* -** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT -** error. The onError parameter determines which (if any) of the statement -** and/or current transaction is rolled back. -*/ -SQLITE_PRIVATE void sqlite3HaltConstraint( - Parse *pParse, /* Parsing context */ - int errCode, /* extended error code */ - int onError, /* Constraint type */ - char *p4, /* Error message */ - i8 p4type, /* P4_STATIC or P4_TRANSIENT */ - u8 p5Errmsg /* P5_ErrMsg type */ -){ - Vdbe *v = sqlite3GetVdbe(pParse); - assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested ); - if( onError==OE_Abort ){ - sqlite3MayAbort(pParse); - } - sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type); - sqlite3VdbeChangeP5(v, p5Errmsg); -} - -/* -** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation. -*/ -SQLITE_PRIVATE void sqlite3UniqueConstraint( - Parse *pParse, /* Parsing context */ - int onError, /* Constraint type */ - Index *pIdx /* The index that triggers the constraint */ -){ - char *zErr; - int j; - StrAccum errMsg; - Table *pTab = pIdx->pTable; - - sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, - pParse->db->aLimit[SQLITE_LIMIT_LENGTH]); - if( pIdx->aColExpr ){ - sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName); - }else{ - for(j=0; jnKeyCol; j++){ - char *zCol; - assert( pIdx->aiColumn[j]>=0 ); - zCol = pTab->aCol[pIdx->aiColumn[j]].zName; - if( j ) sqlite3_str_append(&errMsg, ", ", 2); - sqlite3_str_appendall(&errMsg, pTab->zName); - sqlite3_str_append(&errMsg, ".", 1); - sqlite3_str_appendall(&errMsg, zCol); - } - } - zErr = sqlite3StrAccumFinish(&errMsg); - sqlite3HaltConstraint(pParse, - IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY - : SQLITE_CONSTRAINT_UNIQUE, - onError, zErr, P4_DYNAMIC, P5_ConstraintUnique); -} - - -/* -** Code an OP_Halt due to non-unique rowid. -*/ -SQLITE_PRIVATE void sqlite3RowidConstraint( - Parse *pParse, /* Parsing context */ - int onError, /* Conflict resolution algorithm */ - Table *pTab /* The table with the non-unique rowid */ -){ - char *zMsg; - int rc; - if( pTab->iPKey>=0 ){ - zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName, - pTab->aCol[pTab->iPKey].zName); - rc = SQLITE_CONSTRAINT_PRIMARYKEY; - }else{ - zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName); - rc = SQLITE_CONSTRAINT_ROWID; - } - sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC, - P5_ConstraintUnique); -} - -/* -** Check to see if pIndex uses the collating sequence pColl. Return -** true if it does and false if it does not. -*/ -#ifndef SQLITE_OMIT_REINDEX -static int collationMatch(const char *zColl, Index *pIndex){ - int i; - assert( zColl!=0 ); - for(i=0; inColumn; i++){ - const char *z = pIndex->azColl[i]; - assert( z!=0 || pIndex->aiColumn[i]<0 ); - if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ - return 1; - } - } - return 0; -} -#endif - -/* -** Recompute all indices of pTab that use the collating sequence pColl. -** If pColl==0 then recompute all indices of pTab. -*/ -#ifndef SQLITE_OMIT_REINDEX -static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ - if( !IsVirtual(pTab) ){ - Index *pIndex; /* An index associated with pTab */ - - for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ - if( zColl==0 || collationMatch(zColl, pIndex) ){ - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3RefillIndex(pParse, pIndex, -1); - } - } - } -} -#endif - -/* -** Recompute all indices of all tables in all databases where the -** indices use the collating sequence pColl. If pColl==0 then recompute -** all indices everywhere. -*/ -#ifndef SQLITE_OMIT_REINDEX -static void reindexDatabases(Parse *pParse, char const *zColl){ - Db *pDb; /* A single database */ - int iDb; /* The database index number */ - sqlite3 *db = pParse->db; /* The database connection */ - HashElem *k; /* For looping over tables in pDb */ - Table *pTab; /* A table in the database */ - - assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ - for(iDb=0, pDb=db->aDb; iDbnDb; iDb++, pDb++){ - assert( pDb!=0 ); - for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ - pTab = (Table*)sqliteHashData(k); - reindexTable(pParse, pTab, zColl); - } - } -} -#endif - -/* -** Generate code for the REINDEX command. -** -** REINDEX -- 1 -** REINDEX -- 2 -** REINDEX ?.? -- 3 -** REINDEX ?.? -- 4 -** -** Form 1 causes all indices in all attached databases to be rebuilt. -** Form 2 rebuilds all indices in all databases that use the named -** collating function. Forms 3 and 4 rebuild the named index or all -** indices associated with the named table. -*/ -#ifndef SQLITE_OMIT_REINDEX -SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ - CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ - char *z; /* Name of a table or index */ - const char *zDb; /* Name of the database */ - Table *pTab; /* A table in the database */ - Index *pIndex; /* An index associated with pTab */ - int iDb; /* The database index number */ - sqlite3 *db = pParse->db; /* The database connection */ - Token *pObjName; /* Name of the table or index to be reindexed */ - - /* Read the database schema. If an error occurs, leave an error message - ** and code in pParse and return NULL. */ - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ - return; - } - - if( pName1==0 ){ - reindexDatabases(pParse, 0); - return; - }else if( NEVER(pName2==0) || pName2->z==0 ){ - char *zColl; - assert( pName1->z ); - zColl = sqlite3NameFromToken(pParse->db, pName1); - if( !zColl ) return; - pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); - if( pColl ){ - reindexDatabases(pParse, zColl); - sqlite3DbFree(db, zColl); - return; - } - sqlite3DbFree(db, zColl); - } - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); - if( iDb<0 ) return; - z = sqlite3NameFromToken(db, pObjName); - if( z==0 ) return; - zDb = db->aDb[iDb].zDbSName; - pTab = sqlite3FindTable(db, z, zDb); - if( pTab ){ - reindexTable(pParse, pTab, 0); - sqlite3DbFree(db, z); - return; - } - pIndex = sqlite3FindIndex(db, z, zDb); - sqlite3DbFree(db, z); - if( pIndex ){ - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3RefillIndex(pParse, pIndex, -1); - return; - } - sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); -} -#endif - -/* -** Return a KeyInfo structure that is appropriate for the given Index. -** -** The caller should invoke sqlite3KeyInfoUnref() on the returned object -** when it has finished using it. -*/ -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ - int i; - int nCol = pIdx->nColumn; - int nKey = pIdx->nKeyCol; - KeyInfo *pKey; - if( pParse->nErr ) return 0; - if( pIdx->uniqNotNull ){ - pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey); - }else{ - pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0); - } - if( pKey ){ - assert( sqlite3KeyInfoIsWriteable(pKey) ); - for(i=0; iazColl[i]; - pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 : - sqlite3LocateCollSeq(pParse, zColl); - pKey->aSortFlags[i] = pIdx->aSortOrder[i]; - assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) ); - } - if( pParse->nErr ){ - assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ ); - if( pIdx->bNoQuery==0 ){ - /* Deactivate the index because it contains an unknown collating - ** sequence. The only way to reactive the index is to reload the - ** schema. Adding the missing collating sequence later does not - ** reactive the index. The application had the chance to register - ** the missing index using the collation-needed callback. For - ** simplicity, SQLite will not give the application a second chance. - */ - pIdx->bNoQuery = 1; - pParse->rc = SQLITE_ERROR_RETRY; - } - sqlite3KeyInfoUnref(pKey); - pKey = 0; - } - } - return pKey; -} - -#ifndef SQLITE_OMIT_CTE -/* -** This routine is invoked once per CTE by the parser while parsing a -** WITH clause. -*/ -SQLITE_PRIVATE With *sqlite3WithAdd( - Parse *pParse, /* Parsing context */ - With *pWith, /* Existing WITH clause, or NULL */ - Token *pName, /* Name of the common-table */ - ExprList *pArglist, /* Optional column name list for the table */ - Select *pQuery /* Query used to initialize the table */ -){ - sqlite3 *db = pParse->db; - With *pNew; - char *zName; - - /* Check that the CTE name is unique within this WITH clause. If - ** not, store an error in the Parse structure. */ - zName = sqlite3NameFromToken(pParse->db, pName); - if( zName && pWith ){ - int i; - for(i=0; inCte; i++){ - if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){ - sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName); - } - } - } - - if( pWith ){ - sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); - pNew = sqlite3DbRealloc(db, pWith, nByte); - }else{ - pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); - } - assert( (pNew!=0 && zName!=0) || db->mallocFailed ); - - if( db->mallocFailed ){ - sqlite3ExprListDelete(db, pArglist); - sqlite3SelectDelete(db, pQuery); - sqlite3DbFree(db, zName); - pNew = pWith; - }else{ - pNew->a[pNew->nCte].pSelect = pQuery; - pNew->a[pNew->nCte].pCols = pArglist; - pNew->a[pNew->nCte].zName = zName; - pNew->a[pNew->nCte].zCteErr = 0; - pNew->nCte++; - } - - return pNew; -} - -/* -** Free the contents of the With object passed as the second argument. -*/ -SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){ - if( pWith ){ - int i; - for(i=0; inCte; i++){ - struct Cte *pCte = &pWith->a[i]; - sqlite3ExprListDelete(db, pCte->pCols); - sqlite3SelectDelete(db, pCte->pSelect); - sqlite3DbFree(db, pCte->zName); - } - sqlite3DbFree(db, pWith); - } -} -#endif /* !defined(SQLITE_OMIT_CTE) */ - -/************** End of build.c ***********************************************/ -/************** Begin file callback.c ****************************************/ -/* -** 2005 May 23 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains functions used to access the internal hash tables -** of user defined functions and collation sequences. -*/ - -/* #include "sqliteInt.h" */ - -/* -** Invoke the 'collation needed' callback to request a collation sequence -** in the encoding enc of name zName, length nName. -*/ -static void callCollNeeded(sqlite3 *db, int enc, const char *zName){ - assert( !db->xCollNeeded || !db->xCollNeeded16 ); - if( db->xCollNeeded ){ - char *zExternal = sqlite3DbStrDup(db, zName); - if( !zExternal ) return; - db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal); - sqlite3DbFree(db, zExternal); - } -#ifndef SQLITE_OMIT_UTF16 - if( db->xCollNeeded16 ){ - char const *zExternal; - sqlite3_value *pTmp = sqlite3ValueNew(db); - sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC); - zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE); - if( zExternal ){ - db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal); - } - sqlite3ValueFree(pTmp); - } -#endif -} - -/* -** This routine is called if the collation factory fails to deliver a -** collation function in the best encoding but there may be other versions -** of this collation function (for other text encodings) available. Use one -** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if -** possible. -*/ -static int synthCollSeq(sqlite3 *db, CollSeq *pColl){ - CollSeq *pColl2; - char *z = pColl->zName; - int i; - static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 }; - for(i=0; i<3; i++){ - pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0); - if( pColl2->xCmp!=0 ){ - memcpy(pColl, pColl2, sizeof(CollSeq)); - pColl->xDel = 0; /* Do not copy the destructor */ - return SQLITE_OK; - } - } - return SQLITE_ERROR; -} - -/* -** This routine is called on a collation sequence before it is used to -** check that it is defined. An undefined collation sequence exists when -** a database is loaded that contains references to collation sequences -** that have not been defined by sqlite3_create_collation() etc. -** -** If required, this routine calls the 'collation needed' callback to -** request a definition of the collating sequence. If this doesn't work, -** an equivalent collating sequence that uses a text encoding different -** from the main database is substituted, if one is available. -*/ -SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){ - if( pColl && pColl->xCmp==0 ){ - const char *zName = pColl->zName; - sqlite3 *db = pParse->db; - CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName); - if( !p ){ - return SQLITE_ERROR; - } - assert( p==pColl ); - } - return SQLITE_OK; -} - - - -/* -** Locate and return an entry from the db.aCollSeq hash table. If the entry -** specified by zName and nName is not found and parameter 'create' is -** true, then create a new entry. Otherwise return NULL. -** -** Each pointer stored in the sqlite3.aCollSeq hash table contains an -** array of three CollSeq structures. The first is the collation sequence -** preferred for UTF-8, the second UTF-16le, and the third UTF-16be. -** -** Stored immediately after the three collation sequences is a copy of -** the collation sequence name. A pointer to this string is stored in -** each collation sequence structure. -*/ -static CollSeq *findCollSeqEntry( - sqlite3 *db, /* Database connection */ - const char *zName, /* Name of the collating sequence */ - int create /* Create a new entry if true */ -){ - CollSeq *pColl; - pColl = sqlite3HashFind(&db->aCollSeq, zName); - - if( 0==pColl && create ){ - int nName = sqlite3Strlen30(zName) + 1; - pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName); - if( pColl ){ - CollSeq *pDel = 0; - pColl[0].zName = (char*)&pColl[3]; - pColl[0].enc = SQLITE_UTF8; - pColl[1].zName = (char*)&pColl[3]; - pColl[1].enc = SQLITE_UTF16LE; - pColl[2].zName = (char*)&pColl[3]; - pColl[2].enc = SQLITE_UTF16BE; - memcpy(pColl[0].zName, zName, nName); - pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl); - - /* If a malloc() failure occurred in sqlite3HashInsert(), it will - ** return the pColl pointer to be deleted (because it wasn't added - ** to the hash table). - */ - assert( pDel==0 || pDel==pColl ); - if( pDel!=0 ){ - sqlite3OomFault(db); - sqlite3DbFree(db, pDel); - pColl = 0; - } - } - } - return pColl; -} - -/* -** Parameter zName points to a UTF-8 encoded string nName bytes long. -** Return the CollSeq* pointer for the collation sequence named zName -** for the encoding 'enc' from the database 'db'. -** -** If the entry specified is not found and 'create' is true, then create a -** new entry. Otherwise return NULL. -** -** A separate function sqlite3LocateCollSeq() is a wrapper around -** this routine. sqlite3LocateCollSeq() invokes the collation factory -** if necessary and generates an error message if the collating sequence -** cannot be found. -** -** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq() -*/ -SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq( - sqlite3 *db, /* Database connection to search */ - u8 enc, /* Desired text encoding */ - const char *zName, /* Name of the collating sequence. Might be NULL */ - int create /* True to create CollSeq if doesn't already exist */ -){ - CollSeq *pColl; - assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); - assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE ); - if( zName ){ - pColl = findCollSeqEntry(db, zName, create); - if( pColl ) pColl += enc-1; - }else{ - pColl = db->pDfltColl; - } - return pColl; -} - -/* -** Change the text encoding for a database connection. This means that -** the pDfltColl must change as well. -*/ -SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){ - assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); - db->enc = enc; - /* EVIDENCE-OF: R-08308-17224 The default collating function for all - ** strings is BINARY. - */ - db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0); -} - -/* -** This function is responsible for invoking the collation factory callback -** or substituting a collation sequence of a different encoding when the -** requested collation sequence is not available in the desired encoding. -** -** If it is not NULL, then pColl must point to the database native encoding -** collation sequence with name zName, length nName. -** -** The return value is either the collation sequence to be used in database -** db for collation type name zName, length nName, or NULL, if no collation -** sequence can be found. If no collation is found, leave an error message. -** -** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq() -*/ -SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq( - Parse *pParse, /* Parsing context */ - u8 enc, /* The desired encoding for the collating sequence */ - CollSeq *pColl, /* Collating sequence with native encoding, or NULL */ - const char *zName /* Collating sequence name */ -){ - CollSeq *p; - sqlite3 *db = pParse->db; - - p = pColl; - if( !p ){ - p = sqlite3FindCollSeq(db, enc, zName, 0); - } - if( !p || !p->xCmp ){ - /* No collation sequence of this type for this encoding is registered. - ** Call the collation factory to see if it can supply us with one. - */ - callCollNeeded(db, enc, zName); - p = sqlite3FindCollSeq(db, enc, zName, 0); - } - if( p && !p->xCmp && synthCollSeq(db, p) ){ - p = 0; - } - assert( !p || p->xCmp ); - if( p==0 ){ - sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName); - pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ; - } - return p; -} - -/* -** This function returns the collation sequence for database native text -** encoding identified by the string zName. -** -** If the requested collation sequence is not available, or not available -** in the database native encoding, the collation factory is invoked to -** request it. If the collation factory does not supply such a sequence, -** and the sequence is available in another text encoding, then that is -** returned instead. -** -** If no versions of the requested collations sequence are available, or -** another error occurs, NULL is returned and an error message written into -** pParse. -** -** This routine is a wrapper around sqlite3FindCollSeq(). This routine -** invokes the collation factory if the named collation cannot be found -** and generates an error message. -** -** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() -*/ -SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){ - sqlite3 *db = pParse->db; - u8 enc = ENC(db); - u8 initbusy = db->init.busy; - CollSeq *pColl; - - pColl = sqlite3FindCollSeq(db, enc, zName, initbusy); - if( !initbusy && (!pColl || !pColl->xCmp) ){ - pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName); - } - - return pColl; -} - -/* During the search for the best function definition, this procedure -** is called to test how well the function passed as the first argument -** matches the request for a function with nArg arguments in a system -** that uses encoding enc. The value returned indicates how well the -** request is matched. A higher value indicates a better match. -** -** If nArg is -1 that means to only return a match (non-zero) if p->nArg -** is also -1. In other words, we are searching for a function that -** takes a variable number of arguments. -** -** If nArg is -2 that means that we are searching for any function -** regardless of the number of arguments it uses, so return a positive -** match score for any -** -** The returned value is always between 0 and 6, as follows: -** -** 0: Not a match. -** 1: UTF8/16 conversion required and function takes any number of arguments. -** 2: UTF16 byte order change required and function takes any number of args. -** 3: encoding matches and function takes any number of arguments -** 4: UTF8/16 conversion required - argument count matches exactly -** 5: UTF16 byte order conversion required - argument count matches exactly -** 6: Perfect match: encoding and argument count match exactly. -** -** If nArg==(-2) then any function with a non-null xSFunc is -** a perfect match and any function with xSFunc NULL is -** a non-match. -*/ -#define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */ -static int matchQuality( - FuncDef *p, /* The function we are evaluating for match quality */ - int nArg, /* Desired number of arguments. (-1)==any */ - u8 enc /* Desired text encoding */ -){ - int match; - assert( p->nArg>=-1 ); - - /* Wrong number of arguments means "no match" */ - if( p->nArg!=nArg ){ - if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH; - if( p->nArg>=0 ) return 0; - } - - /* Give a better score to a function with a specific number of arguments - ** than to function that accepts any number of arguments. */ - if( p->nArg==nArg ){ - match = 4; - }else{ - match = 1; - } - - /* Bonus points if the text encoding matches */ - if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){ - match += 2; /* Exact encoding match */ - }else if( (enc & p->funcFlags & 2)!=0 ){ - match += 1; /* Both are UTF16, but with different byte orders */ - } - - return match; -} - -/* -** Search a FuncDefHash for a function with the given name. Return -** a pointer to the matching FuncDef if found, or 0 if there is no match. -*/ -SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch( - int h, /* Hash of the name */ - const char *zFunc /* Name of function */ -){ - FuncDef *p; - for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){ - if( sqlite3StrICmp(p->zName, zFunc)==0 ){ - return p; - } - } - return 0; -} - -/* -** Insert a new FuncDef into a FuncDefHash hash table. -*/ -SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs( - FuncDef *aDef, /* List of global functions to be inserted */ - int nDef /* Length of the apDef[] list */ -){ - int i; - for(i=0; i='a' && zName[0]<='z' ); - pOther = sqlite3FunctionSearch(h, zName); - if( pOther ){ - assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] ); - aDef[i].pNext = pOther->pNext; - pOther->pNext = &aDef[i]; - }else{ - aDef[i].pNext = 0; - aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h]; - sqlite3BuiltinFunctions.a[h] = &aDef[i]; - } - } -} - - - -/* -** Locate a user function given a name, a number of arguments and a flag -** indicating whether the function prefers UTF-16 over UTF-8. Return a -** pointer to the FuncDef structure that defines that function, or return -** NULL if the function does not exist. -** -** If the createFlag argument is true, then a new (blank) FuncDef -** structure is created and liked into the "db" structure if a -** no matching function previously existed. -** -** If nArg is -2, then the first valid function found is returned. A -** function is valid if xSFunc is non-zero. The nArg==(-2) -** case is used to see if zName is a valid function name for some number -** of arguments. If nArg is -2, then createFlag must be 0. -** -** If createFlag is false, then a function with the required name and -** number of arguments may be returned even if the eTextRep flag does not -** match that requested. -*/ -SQLITE_PRIVATE FuncDef *sqlite3FindFunction( - sqlite3 *db, /* An open database */ - const char *zName, /* Name of the function. zero-terminated */ - int nArg, /* Number of arguments. -1 means any number */ - u8 enc, /* Preferred text encoding */ - u8 createFlag /* Create new entry if true and does not otherwise exist */ -){ - FuncDef *p; /* Iterator variable */ - FuncDef *pBest = 0; /* Best match found so far */ - int bestScore = 0; /* Score of best match */ - int h; /* Hash value */ - int nName; /* Length of the name */ - - assert( nArg>=(-2) ); - assert( nArg>=(-1) || createFlag==0 ); - nName = sqlite3Strlen30(zName); - - /* First search for a match amongst the application-defined functions. - */ - p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName); - while( p ){ - int score = matchQuality(p, nArg, enc); - if( score>bestScore ){ - pBest = p; - bestScore = score; - } - p = p->pNext; - } - - /* If no match is found, search the built-in functions. - ** - ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in - ** functions even if a prior app-defined function was found. And give - ** priority to built-in functions. - ** - ** Except, if createFlag is true, that means that we are trying to - ** install a new function. Whatever FuncDef structure is returned it will - ** have fields overwritten with new information appropriate for the - ** new function. But the FuncDefs for built-in functions are read-only. - ** So we must not search for built-ins when creating a new function. - */ - if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){ - bestScore = 0; - h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName); - p = sqlite3FunctionSearch(h, zName); - while( p ){ - int score = matchQuality(p, nArg, enc); - if( score>bestScore ){ - pBest = p; - bestScore = score; - } - p = p->pNext; - } - } - - /* If the createFlag parameter is true and the search did not reveal an - ** exact match for the name, number of arguments and encoding, then add a - ** new entry to the hash table and return it. - */ - if( createFlag && bestScorezName = (const char*)&pBest[1]; - pBest->nArg = (u16)nArg; - pBest->funcFlags = enc; - memcpy((char*)&pBest[1], zName, nName+1); - for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z]; - pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest); - if( pOther==pBest ){ - sqlite3DbFree(db, pBest); - sqlite3OomFault(db); - return 0; - }else{ - pBest->pNext = pOther; - } - } - - if( pBest && (pBest->xSFunc || createFlag) ){ - return pBest; - } - return 0; -} - -/* -** Free all resources held by the schema structure. The void* argument points -** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the -** pointer itself, it just cleans up subsidiary resources (i.e. the contents -** of the schema hash tables). -** -** The Schema.cache_size variable is not cleared. -*/ -SQLITE_PRIVATE void sqlite3SchemaClear(void *p){ - Hash temp1; - Hash temp2; - HashElem *pElem; - Schema *pSchema = (Schema *)p; - - temp1 = pSchema->tblHash; - temp2 = pSchema->trigHash; - sqlite3HashInit(&pSchema->trigHash); - sqlite3HashClear(&pSchema->idxHash); - for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ - sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem)); - } - sqlite3HashClear(&temp2); - sqlite3HashInit(&pSchema->tblHash); - for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ - Table *pTab = sqliteHashData(pElem); - sqlite3DeleteTable(0, pTab); - } - sqlite3HashClear(&temp1); - sqlite3HashClear(&pSchema->fkeyHash); - pSchema->pSeqTab = 0; - if( pSchema->schemaFlags & DB_SchemaLoaded ){ - pSchema->iGeneration++; - } - pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted); -} - -/* -** Find and return the schema associated with a BTree. Create -** a new one if necessary. -*/ -SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ - Schema * p; - if( pBt ){ - p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear); - }else{ - p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema)); - } - if( !p ){ - sqlite3OomFault(db); - }else if ( 0==p->file_format ){ - sqlite3HashInit(&p->tblHash); - sqlite3HashInit(&p->idxHash); - sqlite3HashInit(&p->trigHash); - sqlite3HashInit(&p->fkeyHash); - p->enc = SQLITE_UTF8; - } - return p; -} - -/************** End of callback.c ********************************************/ -/************** Begin file delete.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 C code routines that are called by the parser -** in order to generate code for DELETE FROM statements. -*/ -/* #include "sqliteInt.h" */ - -/* -** While a SrcList can in general represent multiple tables and subqueries -** (as in the FROM clause of a SELECT statement) in this case it contains -** the name of a single table, as one might find in an INSERT, DELETE, -** or UPDATE statement. Look up that table in the symbol table and -** return a pointer. Set an error message and return NULL if the table -** name is not found or if any other error occurs. -** -** The following fields are initialized appropriate in pSrc: -** -** pSrc->a[0].pTab Pointer to the Table object -** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one -** -*/ -SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ - struct SrcList_item *pItem = pSrc->a; - Table *pTab; - assert( pItem && pSrc->nSrc>=1 ); - pTab = sqlite3LocateTableItem(pParse, 0, pItem); - sqlite3DeleteTable(pParse->db, pItem->pTab); - pItem->pTab = pTab; - if( pTab ){ - pTab->nTabRef++; - } - if( sqlite3IndexedByLookup(pParse, pItem) ){ - pTab = 0; - } - return pTab; -} - -/* Return true if table pTab is read-only. -** -** A table is read-only if any of the following are true: -** -** 1) It is a virtual table and no implementation of the xUpdate method -** has been provided -** -** 2) It is a system table (i.e. sqlite_schema), this call is not -** part of a nested parse and writable_schema pragma has not -** been specified -** -** 3) The table is a shadow table, the database connection is in -** defensive mode, and the current sqlite3_prepare() -** is for a top-level SQL statement. -*/ -static int tabIsReadOnly(Parse *pParse, Table *pTab){ - sqlite3 *db; - if( IsVirtual(pTab) ){ - return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0; - } - if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0; - db = pParse->db; - if( (pTab->tabFlags & TF_Readonly)!=0 ){ - return sqlite3WritableSchema(db)==0 && pParse->nested==0; - } - assert( pTab->tabFlags & TF_Shadow ); - return sqlite3ReadOnlyShadowTables(db); -} - -/* -** Check to make sure the given table is writable. If it is not -** writable, generate an error message and return 1. If it is -** writable return 0; -*/ -SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){ - if( tabIsReadOnly(pParse, pTab) ){ - sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); - return 1; - } -#ifndef SQLITE_OMIT_VIEW - if( !viewOk && pTab->pSelect ){ - sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName); - return 1; - } -#endif - return 0; -} - - -#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) -/* -** Evaluate a view and store its result in an ephemeral table. The -** pWhere argument is an optional WHERE clause that restricts the -** set of rows in the view that are to be added to the ephemeral table. -*/ -SQLITE_PRIVATE void sqlite3MaterializeView( - Parse *pParse, /* Parsing context */ - Table *pView, /* View definition */ - Expr *pWhere, /* Optional WHERE clause to be added */ - ExprList *pOrderBy, /* Optional ORDER BY clause */ - Expr *pLimit, /* Optional LIMIT clause */ - int iCur /* Cursor number for ephemeral table */ -){ - SelectDest dest; - Select *pSel; - SrcList *pFrom; - sqlite3 *db = pParse->db; - int iDb = sqlite3SchemaToIndex(db, pView->pSchema); - pWhere = sqlite3ExprDup(db, pWhere, 0); - pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0); - if( pFrom ){ - assert( pFrom->nSrc==1 ); - pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName); - pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName); - assert( pFrom->a[0].pOn==0 ); - assert( pFrom->a[0].pUsing==0 ); - } - pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy, - SF_IncludeHidden, pLimit); - sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); - sqlite3Select(pParse, pSel, &dest); - sqlite3SelectDelete(db, pSel); -} -#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ - -#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) -/* -** Generate an expression tree to implement the WHERE, ORDER BY, -** and LIMIT/OFFSET portion of DELETE and UPDATE statements. -** -** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1; -** \__________________________/ -** pLimitWhere (pInClause) -*/ -SQLITE_PRIVATE Expr *sqlite3LimitWhere( - Parse *pParse, /* The parser context */ - SrcList *pSrc, /* the FROM clause -- which tables to scan */ - Expr *pWhere, /* The WHERE clause. May be null */ - ExprList *pOrderBy, /* The ORDER BY clause. May be null */ - Expr *pLimit, /* The LIMIT clause. May be null */ - char *zStmtType /* Either DELETE or UPDATE. For err msgs. */ -){ - sqlite3 *db = pParse->db; - Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */ - Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ - ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ - SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ - Select *pSelect = NULL; /* Complete SELECT tree */ - Table *pTab; - - /* Check that there isn't an ORDER BY without a LIMIT clause. - */ - if( pOrderBy && pLimit==0 ) { - sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); - sqlite3ExprDelete(pParse->db, pWhere); - sqlite3ExprListDelete(pParse->db, pOrderBy); - return 0; - } - - /* We only need to generate a select expression if there - ** is a limit/offset term to enforce. - */ - if( pLimit == 0 ) { - return pWhere; - } - - /* Generate a select expression tree to enforce the limit/offset - ** term for the DELETE or UPDATE statement. For example: - ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 - ** becomes: - ** DELETE FROM table_a WHERE rowid IN ( - ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1 - ** ); - */ - - pTab = pSrc->a[0].pTab; - if( HasRowid(pTab) ){ - pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0); - pEList = sqlite3ExprListAppend( - pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0) - ); - }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - if( pPk->nKeyCol==1 ){ - const char *zName = pTab->aCol[pPk->aiColumn[0]].zName; - pLhs = sqlite3Expr(db, TK_ID, zName); - pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName)); - }else{ - int i; - for(i=0; inKeyCol; i++){ - Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName); - pEList = sqlite3ExprListAppend(pParse, pEList, p); - } - pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); - if( pLhs ){ - pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0); - } - } - } - - /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree - ** and the SELECT subtree. */ - pSrc->a[0].pTab = 0; - pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); - pSrc->a[0].pTab = pTab; - pSrc->a[0].pIBIndex = 0; - - /* generate the SELECT expression tree. */ - pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0, - pOrderBy,0,pLimit - ); - - /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ - pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0); - sqlite3PExprAddSelect(pParse, pInClause, pSelect); - return pInClause; -} -#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */ - /* && !defined(SQLITE_OMIT_SUBQUERY) */ - -/* -** Generate code for a DELETE FROM statement. -** -** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL; -** \________/ \________________/ -** pTabList pWhere -*/ -SQLITE_PRIVATE void sqlite3DeleteFrom( - Parse *pParse, /* The parser context */ - SrcList *pTabList, /* The table from which we should delete things */ - Expr *pWhere, /* The WHERE clause. May be null */ - ExprList *pOrderBy, /* ORDER BY clause. May be null */ - Expr *pLimit /* LIMIT clause. May be null */ -){ - Vdbe *v; /* The virtual database engine */ - Table *pTab; /* The table from which records will be deleted */ - int i; /* Loop counter */ - WhereInfo *pWInfo; /* Information about the WHERE clause */ - Index *pIdx; /* For looping over indices of the table */ - int iTabCur; /* Cursor number for the table */ - int iDataCur = 0; /* VDBE cursor for the canonical data source */ - int iIdxCur = 0; /* Cursor number of the first index */ - int nIdx; /* Number of indices */ - sqlite3 *db; /* Main database structure */ - AuthContext sContext; /* Authorization context */ - NameContext sNC; /* Name context to resolve expressions in */ - int iDb; /* Database number */ - int memCnt = 0; /* Memory cell used for change counting */ - int rcauth; /* Value returned by authorization callback */ - int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */ - int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ - u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */ - Index *pPk; /* The PRIMARY KEY index on the table */ - int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */ - i16 nPk = 1; /* Number of columns in the PRIMARY KEY */ - int iKey; /* Memory cell holding key of row to be deleted */ - i16 nKey; /* Number of memory cells in the row key */ - int iEphCur = 0; /* Ephemeral table holding all primary key values */ - int iRowSet = 0; /* Register for rowset of rows to delete */ - int addrBypass = 0; /* Address of jump over the delete logic */ - int addrLoop = 0; /* Top of the delete loop */ - int addrEphOpen = 0; /* Instruction to open the Ephemeral table */ - int bComplex; /* True if there are triggers or FKs or - ** subqueries in the WHERE clause */ - -#ifndef SQLITE_OMIT_TRIGGER - int isView; /* True if attempting to delete from a view */ - Trigger *pTrigger; /* List of table triggers, if required */ -#endif - - memset(&sContext, 0, sizeof(sContext)); - db = pParse->db; - if( pParse->nErr || db->mallocFailed ){ - goto delete_from_cleanup; - } - assert( pTabList->nSrc==1 ); - - - /* Locate the table which we want to delete. This table has to be - ** put in an SrcList structure because some of the subroutines we - ** will be calling are designed to work with multiple tables and expect - ** an SrcList* parameter instead of just a Table* parameter. - */ - pTab = sqlite3SrcListLookup(pParse, pTabList); - if( pTab==0 ) goto delete_from_cleanup; - - /* Figure out if we have any triggers and if the table being - ** deleted from is a view - */ -#ifndef SQLITE_OMIT_TRIGGER - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); - isView = pTab->pSelect!=0; -#else -# define pTrigger 0 -# define isView 0 -#endif - bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0); -#ifdef SQLITE_OMIT_VIEW -# undef isView -# define isView 0 -#endif - -#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT - if( !isView ){ - pWhere = sqlite3LimitWhere( - pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE" - ); - pOrderBy = 0; - pLimit = 0; - } -#endif - - /* If pTab is really a view, make sure it has been initialized. - */ - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ - goto delete_from_cleanup; - } - - if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){ - goto delete_from_cleanup; - } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - assert( iDbnDb ); - rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, - db->aDb[iDb].zDbSName); - assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE ); - if( rcauth==SQLITE_DENY ){ - goto delete_from_cleanup; - } - assert(!isView || pTrigger); - - /* Assign cursor numbers to the table and all its indices. - */ - assert( pTabList->nSrc==1 ); - iTabCur = pTabList->a[0].iCursor = pParse->nTab++; - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ - pParse->nTab++; - } - - /* Start the view context - */ - if( isView ){ - sqlite3AuthContextPush(pParse, &sContext, pTab->zName); - } - - /* Begin generating code. - */ - v = sqlite3GetVdbe(pParse); - if( v==0 ){ - goto delete_from_cleanup; - } - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); - sqlite3BeginWriteOperation(pParse, bComplex, iDb); - - /* If we are trying to delete from a view, realize that view into - ** an ephemeral table. - */ -#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) - if( isView ){ - sqlite3MaterializeView(pParse, pTab, - pWhere, pOrderBy, pLimit, iTabCur - ); - iDataCur = iIdxCur = iTabCur; - pOrderBy = 0; - pLimit = 0; - } -#endif - - /* Resolve the column names in the WHERE clause. - */ - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - sNC.pSrcList = pTabList; - if( sqlite3ResolveExprNames(&sNC, pWhere) ){ - goto delete_from_cleanup; - } - - /* Initialize the counter of the number of rows deleted, if - ** we are counting rows. - */ - if( (db->flags & SQLITE_CountRows)!=0 - && !pParse->nested - && !pParse->pTriggerTab - ){ - memCnt = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); - } - -#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION - /* Special case: A DELETE without a WHERE clause deletes everything. - ** It is easier just to erase the whole table. Prior to version 3.6.5, - ** this optimization caused the row change count (the value returned by - ** API function sqlite3_count_changes) to be set incorrectly. - ** - ** The "rcauth==SQLITE_OK" terms is the - ** IMPLEMENTATION-OF: R-17228-37124 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. - */ - if( rcauth==SQLITE_OK - && pWhere==0 - && !bComplex - && !IsVirtual(pTab) -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - && db->xPreUpdateCallback==0 -#endif - ){ - assert( !isView ); - sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); - if( HasRowid(pTab) ){ - sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1, - pTab->zName, P4_STATIC); - } - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - assert( pIdx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); - } - }else -#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */ - { - u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE; - if( sNC.ncFlags & NC_VarSelect ) bComplex = 1; - wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW); - if( HasRowid(pTab) ){ - /* For a rowid table, initialize the RowSet to an empty set */ - pPk = 0; - nPk = 1; - iRowSet = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet); - }else{ - /* For a WITHOUT ROWID table, create an ephemeral table used to - ** hold all primary keys for rows to be deleted. */ - pPk = sqlite3PrimaryKeyIndex(pTab); - assert( pPk!=0 ); - nPk = pPk->nKeyCol; - iPk = pParse->nMem+1; - pParse->nMem += nPk; - iEphCur = pParse->nTab++; - addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); - } - - /* Construct a query to find the rowid or primary key for every row - ** to be deleted, based on the WHERE clause. Set variable eOnePass - ** to indicate the strategy used to implement this delete: - ** - ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values. - ** ONEPASS_SINGLE: One-pass approach - at most one row deleted. - ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted. - */ - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1); - if( pWInfo==0 ) goto delete_from_cleanup; - eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); - assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI ); - assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF ); - if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse); - - /* Keep track of the number of rows to be deleted */ - if( memCnt ){ - sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); - } - - /* Extract the rowid or primary key for the current row */ - if( pPk ){ - for(i=0; iaiColumn[i]>=0 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, - pPk->aiColumn[i], iPk+i); - } - iKey = iPk; - }else{ - iKey = ++pParse->nMem; - sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey); - } - - if( eOnePass!=ONEPASS_OFF ){ - /* For ONEPASS, no need to store the rowid/primary-key. There is only - ** one, so just keep it in its register(s) and fall through to the - ** delete code. */ - nKey = nPk; /* OP_Found will use an unpacked key */ - aToOpen = sqlite3DbMallocRawNN(db, nIdx+2); - if( aToOpen==0 ){ - sqlite3WhereEnd(pWInfo); - goto delete_from_cleanup; - } - memset(aToOpen, 1, nIdx+1); - aToOpen[nIdx+1] = 0; - if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0; - if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0; - if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen); - }else{ - if( pPk ){ - /* Add the PK key for this row to the temporary table */ - iKey = ++pParse->nMem; - nKey = 0; /* Zero tells OP_Found to use a composite key */ - sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey, - sqlite3IndexAffinityStr(pParse->db, pPk), nPk); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk); - }else{ - /* Add the rowid of the row to be deleted to the RowSet */ - nKey = 1; /* OP_DeferredSeek always uses a single rowid */ - sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey); - } - } - - /* If this DELETE cannot use the ONEPASS strategy, this is the - ** end of the WHERE loop */ - if( eOnePass!=ONEPASS_OFF ){ - addrBypass = sqlite3VdbeMakeLabel(pParse); - }else{ - sqlite3WhereEnd(pWInfo); - } - - /* Unless this is a view, open cursors for the table we are - ** deleting from and all its indices. If this is a view, then the - ** only effect this statement has is to fire the INSTEAD OF - ** triggers. - */ - if( !isView ){ - int iAddrOnce = 0; - if( eOnePass==ONEPASS_MULTI ){ - iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - } - testcase( IsVirtual(pTab) ); - sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE, - iTabCur, aToOpen, &iDataCur, &iIdxCur); - assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur ); - assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 ); - if( eOnePass==ONEPASS_MULTI ){ - sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce); - } - } - - /* Set up a loop over the rowids/primary-keys that were found in the - ** where-clause loop above. - */ - if( eOnePass!=ONEPASS_OFF ){ - assert( nKey==nPk ); /* OP_Found will use an unpacked key */ - if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){ - assert( pPk!=0 || pTab->pSelect!=0 ); - sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey); - VdbeCoverage(v); - } - }else if( pPk ){ - addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v); - if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey); - }else{ - sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey); - } - assert( nKey==0 ); /* OP_Found will use a composite key */ - }else{ - addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey); - VdbeCoverage(v); - assert( nKey==1 ); - } - - /* Delete the row */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pTab) ){ - const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); - sqlite3VtabMakeWritable(pParse, pTab); - assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); - sqlite3MayAbort(pParse); - if( eOnePass==ONEPASS_SINGLE ){ - sqlite3VdbeAddOp1(v, OP_Close, iTabCur); - if( sqlite3IsToplevel(pParse) ){ - pParse->isMultiWrite = 0; - } - } - sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); - sqlite3VdbeChangeP5(v, OE_Abort); - }else -#endif - { - int count = (pParse->nested==0); /* True to count changes */ - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, - iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]); - } - - /* End of the loop over all rowids/primary-keys. */ - if( eOnePass!=ONEPASS_OFF ){ - sqlite3VdbeResolveLabel(v, addrBypass); - sqlite3WhereEnd(pWInfo); - }else if( pPk ){ - sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addrLoop); - }else{ - sqlite3VdbeGoto(v, addrLoop); - sqlite3VdbeJumpHere(v, addrLoop); - } - } /* End non-truncate path */ - - /* Update the sqlite_sequence table by storing the content of the - ** maximum rowid counter values recorded while inserting into - ** autoincrement tables. - */ - if( pParse->nested==0 && pParse->pTriggerTab==0 ){ - sqlite3AutoincrementEnd(pParse); - } - - /* Return the number of rows that were deleted. If this routine is - ** generating code because of a call to sqlite3NestedParse(), do not - ** invoke the callback function. - */ - if( memCnt ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC); - } - -delete_from_cleanup: - sqlite3AuthContextPop(&sContext); - sqlite3SrcListDelete(db, pTabList); - sqlite3ExprDelete(db, pWhere); -#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) - sqlite3ExprListDelete(db, pOrderBy); - sqlite3ExprDelete(db, pLimit); -#endif - sqlite3DbFree(db, aToOpen); - return; -} -/* Make sure "isView" and other macros defined above are undefined. Otherwise -** they may interfere with compilation of other functions in this file -** (or in another file, if this file becomes part of the amalgamation). */ -#ifdef isView - #undef isView -#endif -#ifdef pTrigger - #undef pTrigger -#endif - -/* -** This routine generates VDBE code that causes a single row of a -** single table to be deleted. Both the original table entry and -** all indices are removed. -** -** Preconditions: -** -** 1. iDataCur is an open cursor on the btree that is the canonical data -** store for the table. (This will be either the table itself, -** in the case of a rowid table, or the PRIMARY KEY index in the case -** of a WITHOUT ROWID table.) -** -** 2. Read/write cursors for all indices of pTab must be open as -** cursor number iIdxCur+i for the i-th index. -** -** 3. The primary key for the row to be deleted must be stored in a -** sequence of nPk memory cells starting at iPk. If nPk==0 that means -** that a search record formed from OP_MakeRecord is contained in the -** single memory location iPk. -** -** eMode: -** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or -** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor -** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF -** then this function must seek iDataCur to the entry identified by iPk -** and nPk before reading from it. -** -** If eMode is ONEPASS_MULTI, then this call is being made as part -** of a ONEPASS delete that affects multiple rows. In this case, if -** iIdxNoSeek is a valid cursor number (>=0) and is not the same as -** iDataCur, then its position should be preserved following the delete -** operation. Or, if iIdxNoSeek is not a valid cursor number, the -** position of iDataCur should be preserved instead. -** -** iIdxNoSeek: -** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur, -** then it identifies an index cursor (from within array of cursors -** starting at iIdxCur) that already points to the index entry to be deleted. -** Except, this optimization is disabled if there are BEFORE triggers since -** the trigger body might have moved the cursor. -*/ -SQLITE_PRIVATE void sqlite3GenerateRowDelete( - Parse *pParse, /* Parsing context */ - Table *pTab, /* Table containing the row to be deleted */ - Trigger *pTrigger, /* List of triggers to (potentially) fire */ - int iDataCur, /* Cursor from which column data is extracted */ - int iIdxCur, /* First index cursor */ - int iPk, /* First memory cell containing the PRIMARY KEY */ - i16 nPk, /* Number of PRIMARY KEY memory cells */ - u8 count, /* If non-zero, increment the row change counter */ - u8 onconf, /* Default ON CONFLICT policy for triggers */ - u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */ - int iIdxNoSeek /* Cursor number of cursor that does not need seeking */ -){ - Vdbe *v = pParse->pVdbe; /* Vdbe */ - int iOld = 0; /* First register in OLD.* array */ - int iLabel; /* Label resolved to end of generated code */ - u8 opSeek; /* Seek opcode */ - - /* Vdbe is guaranteed to have been allocated by this stage. */ - assert( v ); - VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)", - iDataCur, iIdxCur, iPk, (int)nPk)); - - /* Seek cursor iCur to the row to delete. If this row no longer exists - ** (this can happen if a trigger program has already deleted it), do - ** not attempt to delete it or fire any DELETE triggers. */ - iLabel = sqlite3VdbeMakeLabel(pParse); - opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound; - if( eMode==ONEPASS_OFF ){ - sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk); - VdbeCoverageIf(v, opSeek==OP_NotExists); - VdbeCoverageIf(v, opSeek==OP_NotFound); - } - - /* If there are any triggers to fire, allocate a range of registers to - ** use for the old.* references in the triggers. */ - if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){ - u32 mask; /* Mask of OLD.* columns in use */ - int iCol; /* Iterator used while populating OLD.* */ - int addrStart; /* Start of BEFORE trigger programs */ - - /* TODO: Could use temporary registers here. Also could attempt to - ** avoid copying the contents of the rowid register. */ - mask = sqlite3TriggerColmask( - pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf - ); - mask |= sqlite3FkOldmask(pParse, pTab); - iOld = pParse->nMem+1; - pParse->nMem += (1 + pTab->nCol); - - /* Populate the OLD.* pseudo-table register array. These values will be - ** used by any BEFORE and AFTER triggers that exist. */ - sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld); - for(iCol=0; iColnCol; iCol++){ - testcase( mask!=0xffffffff && iCol==31 ); - testcase( mask!=0xffffffff && iCol==32 ); - if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){ - int kk = sqlite3TableColumnToStorage(pTab, iCol); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1); - } - } - - /* Invoke BEFORE DELETE trigger programs. */ - addrStart = sqlite3VdbeCurrentAddr(v); - sqlite3CodeRowTrigger(pParse, pTrigger, - TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel - ); - - /* If any BEFORE triggers were coded, then seek the cursor to the - ** row to be deleted again. It may be that the BEFORE triggers moved - ** the cursor or already deleted the row that the cursor was - ** pointing to. - ** - ** Also disable the iIdxNoSeek optimization since the BEFORE trigger - ** may have moved that cursor. - */ - if( addrStart=0 ); - iIdxNoSeek = -1; - } - - /* Do FK processing. This call checks that any FK constraints that - ** refer to this table (i.e. constraints attached to other tables) - ** are not violated by deleting this row. */ - sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0); - } - - /* Delete the index and table entries. Skip this step if pTab is really - ** a view (in which case the only effect of the DELETE statement is to - ** fire the INSTEAD OF triggers). - ** - ** If variable 'count' is non-zero, then this OP_Delete instruction should - ** invoke the update-hook. The pre-update-hook, on the other hand should - ** be invoked unless table pTab is a system table. The difference is that - ** the update-hook is not invoked for rows removed by REPLACE, but the - ** pre-update-hook is. - */ - if( pTab->pSelect==0 ){ - u8 p5 = 0; - sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek); - sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0)); - if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){ - sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE); - } - if( eMode!=ONEPASS_OFF ){ - sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE); - } - if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){ - sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek); - } - if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION; - sqlite3VdbeChangeP5(v, p5); - } - - /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to - ** handle rows (possibly in other tables) that refer via a foreign key - ** to the row just deleted. */ - sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0); - - /* Invoke AFTER DELETE trigger programs. */ - sqlite3CodeRowTrigger(pParse, pTrigger, - TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel - ); - - /* Jump here if the row had already been deleted before any BEFORE - ** trigger programs were invoked. Or if a trigger program throws a - ** RAISE(IGNORE) exception. */ - sqlite3VdbeResolveLabel(v, iLabel); - VdbeModuleComment((v, "END: GenRowDel()")); -} - -/* -** This routine generates VDBE code that causes the deletion of all -** index entries associated with a single row of a single table, pTab -** -** Preconditions: -** -** 1. A read/write cursor "iDataCur" must be open on the canonical storage -** btree for the table pTab. (This will be either the table itself -** for rowid tables or to the primary key index for WITHOUT ROWID -** tables.) -** -** 2. Read/write cursors for all indices of pTab must be open as -** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex -** index is the 0-th index.) -** -** 3. The "iDataCur" cursor must be already be positioned on the row -** that is to be deleted. -*/ -SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( - Parse *pParse, /* Parsing and code generating context */ - Table *pTab, /* Table containing the row to be deleted */ - int iDataCur, /* Cursor of table holding data. */ - int iIdxCur, /* First index cursor */ - int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ - int iIdxNoSeek /* Do not delete from this cursor */ -){ - int i; /* Index loop counter */ - int r1 = -1; /* Register holding an index key */ - int iPartIdxLabel; /* Jump destination for skipping partial index entries */ - Index *pIdx; /* Current index */ - Index *pPrior = 0; /* Prior index */ - Vdbe *v; /* The prepared statement under construction */ - Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */ - - v = pParse->pVdbe; - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); - for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ - assert( iIdxCur+i!=iDataCur || pPk==pIdx ); - if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; - if( pIdx==pPk ) continue; - if( iIdxCur+i==iIdxNoSeek ) continue; - VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); - r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, - &iPartIdxLabel, pPrior, r1); - sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, - pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); - sqlite3VdbeChangeP5(v, 1); /* Cause IdxDelete to error if no entry found */ - sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); - pPrior = pIdx; - } -} - -/* -** Generate code that will assemble an index key and stores it in register -** regOut. The key with be for index pIdx which is an index on pTab. -** iCur is the index of a cursor open on the pTab table and pointing to -** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then -** iCur must be the cursor of the PRIMARY KEY index. -** -** Return a register number which is the first in a block of -** registers that holds the elements of the index key. The -** block of registers has already been deallocated by the time -** this routine returns. -** -** If *piPartIdxLabel is not NULL, fill it in with a label and jump -** to that label if pIdx is a partial index that should be skipped. -** The label should be resolved using sqlite3ResolvePartIdxLabel(). -** A partial index should be skipped if its WHERE clause evaluates -** to false or null. If pIdx is not a partial index, *piPartIdxLabel -** will be set to zero which is an empty label that is ignored by -** sqlite3ResolvePartIdxLabel(). -** -** The pPrior and regPrior parameters are used to implement a cache to -** avoid unnecessary register loads. If pPrior is not NULL, then it is -** a pointer to a different index for which an index key has just been -** computed into register regPrior. If the current pIdx index is generating -** its key into the same sequence of registers and if pPrior and pIdx share -** a column in common, then the register corresponding to that column already -** holds the correct value and the loading of that register is skipped. -** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK -** on a table with multiple indices, and especially with the ROWID or -** PRIMARY KEY columns of the index. -*/ -SQLITE_PRIVATE int sqlite3GenerateIndexKey( - Parse *pParse, /* Parsing context */ - Index *pIdx, /* The index for which to generate a key */ - int iDataCur, /* Cursor number from which to take column data */ - int regOut, /* Put the new key into this register if not 0 */ - int prefixOnly, /* Compute only a unique prefix of the key */ - int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */ - Index *pPrior, /* Previously generated index key */ - int regPrior /* Register holding previous generated key */ -){ - Vdbe *v = pParse->pVdbe; - int j; - int regBase; - int nCol; - - if( piPartIdxLabel ){ - if( pIdx->pPartIdxWhere ){ - *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse); - pParse->iSelfTab = iDataCur + 1; - sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, - SQLITE_JUMPIFNULL); - pParse->iSelfTab = 0; - pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02; - ** pPartIdxWhere may have corrupted regPrior registers */ - }else{ - *piPartIdxLabel = 0; - } - } - nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn; - regBase = sqlite3GetTempRange(pParse, nCol); - if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0; - for(j=0; jaiColumn[j]==pIdx->aiColumn[j] - && pPrior->aiColumn[j]!=XN_EXPR - ){ - /* This column was already computed by the previous index */ - continue; - } - sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j); - /* If the column affinity is REAL but the number is an integer, then it - ** might be stored in the table as an integer (using a compact - ** representation) then converted to REAL by an OP_RealAffinity opcode. - ** But we are getting ready to store this value back into an index, where - ** it should be converted by to INTEGER again. So omit the OP_RealAffinity - ** opcode if it is present */ - sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); - } - if( regOut ){ - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut); - if( pIdx->pTable->pSelect ){ - const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx); - sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT); - } - } - sqlite3ReleaseTempRange(pParse, regBase, nCol); - return regBase; -} - -/* -** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label -** because it was a partial index, then this routine should be called to -** resolve that label. -*/ -SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){ - if( iLabel ){ - sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel); - } -} - -/************** End of delete.c **********************************************/ -/************** Begin file func.c ********************************************/ -/* -** 2002 February 23 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the C-language implementations for many of the SQL -** functions of SQLite. (Some function, and in particular the date and -** time functions, are implemented separately.) -*/ -/* #include "sqliteInt.h" */ -/* #include */ -/* #include */ -#ifndef SQLITE_OMIT_FLOATING_POINT -/* #include */ -#endif -/* #include "vdbeInt.h" */ - -/* -** Return the collating function associated with a function. -*/ -static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){ - VdbeOp *pOp; - assert( context->pVdbe!=0 ); - pOp = &context->pVdbe->aOp[context->iOp-1]; - assert( pOp->opcode==OP_CollSeq ); - assert( pOp->p4type==P4_COLLSEQ ); - return pOp->p4.pColl; -} - -/* -** Indicate that the accumulator load should be skipped on this -** iteration of the aggregate loop. -*/ -static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){ - assert( context->isError<=0 ); - context->isError = -1; - context->skipFlag = 1; -} - -/* -** Implementation of the non-aggregate min() and max() functions -*/ -static void minmaxFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int i; - int mask; /* 0 for min() or 0xffffffff for max() */ - int iBest; - CollSeq *pColl; - - assert( argc>1 ); - mask = sqlite3_user_data(context)==0 ? 0 : -1; - pColl = sqlite3GetFuncCollSeq(context); - assert( pColl ); - assert( mask==-1 || mask==0 ); - iBest = 0; - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - for(i=1; i=0 ){ - testcase( mask==0 ); - iBest = i; - } - } - sqlite3_result_value(context, argv[iBest]); -} - -/* -** Return the type of the argument. -*/ -static void typeofFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - static const char *azType[] = { "integer", "real", "text", "blob", "null" }; - int i = sqlite3_value_type(argv[0]) - 1; - UNUSED_PARAMETER(NotUsed); - assert( i>=0 && i=0xc0 ){ - while( (*z & 0xc0)==0x80 ){ z++; z0++; } - } - } - sqlite3_result_int(context, (int)(z-z0)); - break; - } - default: { - sqlite3_result_null(context); - break; - } - } -} - -/* -** Implementation of the abs() function. -** -** IMP: R-23979-26855 The abs(X) function returns the absolute value of -** the numeric argument X. -*/ -static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ - assert( argc==1 ); - UNUSED_PARAMETER(argc); - switch( sqlite3_value_type(argv[0]) ){ - case SQLITE_INTEGER: { - i64 iVal = sqlite3_value_int64(argv[0]); - if( iVal<0 ){ - if( iVal==SMALLEST_INT64 ){ - /* IMP: R-31676-45509 If X is the integer -9223372036854775808 - ** then abs(X) throws an integer overflow error since there is no - ** equivalent positive 64-bit two complement value. */ - sqlite3_result_error(context, "integer overflow", -1); - return; - } - iVal = -iVal; - } - sqlite3_result_int64(context, iVal); - break; - } - case SQLITE_NULL: { - /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */ - sqlite3_result_null(context); - break; - } - default: { - /* Because sqlite3_value_double() returns 0.0 if the argument is not - ** something that can be converted into a number, we have: - ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob - ** that cannot be converted to a numeric value. - */ - double rVal = sqlite3_value_double(argv[0]); - if( rVal<0 ) rVal = -rVal; - sqlite3_result_double(context, rVal); - break; - } - } -} - -/* -** Implementation of the instr() function. -** -** instr(haystack,needle) finds the first occurrence of needle -** in haystack and returns the number of previous characters plus 1, -** or 0 if needle does not occur within haystack. -** -** If both haystack and needle are BLOBs, then the result is one more than -** the number of bytes in haystack prior to the first occurrence of needle, -** or 0 if needle never occurs in haystack. -*/ -static void instrFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *zHaystack; - const unsigned char *zNeedle; - int nHaystack; - int nNeedle; - int typeHaystack, typeNeedle; - int N = 1; - int isText; - unsigned char firstChar; - sqlite3_value *pC1 = 0; - sqlite3_value *pC2 = 0; - - UNUSED_PARAMETER(argc); - typeHaystack = sqlite3_value_type(argv[0]); - typeNeedle = sqlite3_value_type(argv[1]); - if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return; - nHaystack = sqlite3_value_bytes(argv[0]); - nNeedle = sqlite3_value_bytes(argv[1]); - if( nNeedle>0 ){ - if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ - zHaystack = sqlite3_value_blob(argv[0]); - zNeedle = sqlite3_value_blob(argv[1]); - isText = 0; - }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){ - zHaystack = sqlite3_value_text(argv[0]); - zNeedle = sqlite3_value_text(argv[1]); - isText = 1; - }else{ - pC1 = sqlite3_value_dup(argv[0]); - zHaystack = sqlite3_value_text(pC1); - if( zHaystack==0 ) goto endInstrOOM; - nHaystack = sqlite3_value_bytes(pC1); - pC2 = sqlite3_value_dup(argv[1]); - zNeedle = sqlite3_value_text(pC2); - if( zNeedle==0 ) goto endInstrOOM; - nNeedle = sqlite3_value_bytes(pC2); - isText = 1; - } - if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM; - firstChar = zNeedle[0]; - while( nNeedle<=nHaystack - && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0) - ){ - N++; - do{ - nHaystack--; - zHaystack++; - }while( isText && (zHaystack[0]&0xc0)==0x80 ); - } - if( nNeedle>nHaystack ) N = 0; - } - sqlite3_result_int(context, N); -endInstr: - sqlite3_value_free(pC1); - sqlite3_value_free(pC2); - return; -endInstrOOM: - sqlite3_result_error_nomem(context); - goto endInstr; -} - -/* -** Implementation of the printf() function. -*/ -static void printfFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - PrintfArguments x; - StrAccum str; - const char *zFormat; - int n; - sqlite3 *db = sqlite3_context_db_handle(context); - - if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ - x.nArg = argc-1; - x.nUsed = 0; - x.apArg = argv+1; - sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); - str.printfFlags = SQLITE_PRINTF_SQLFUNC; - sqlite3_str_appendf(&str, zFormat, &x); - n = str.nChar; - sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, - SQLITE_DYNAMIC); - } -} - -/* -** Implementation of the substr() function. -** -** substr(x,p1,p2) returns p2 characters of x[] beginning with p1. -** p1 is 1-indexed. So substr(x,1,1) returns the first character -** of x. If x is text, then we actually count UTF-8 characters. -** If x is a blob, then we count bytes. -** -** If p1 is negative, then we begin abs(p1) from the end of x[]. -** -** If p2 is negative, return the p2 characters preceding p1. -*/ -static void substrFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *z; - const unsigned char *z2; - int len; - int p0type; - i64 p1, p2; - int negP2 = 0; - - assert( argc==3 || argc==2 ); - if( sqlite3_value_type(argv[1])==SQLITE_NULL - || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) - ){ - return; - } - p0type = sqlite3_value_type(argv[0]); - p1 = sqlite3_value_int(argv[1]); - if( p0type==SQLITE_BLOB ){ - len = sqlite3_value_bytes(argv[0]); - z = sqlite3_value_blob(argv[0]); - if( z==0 ) return; - assert( len==sqlite3_value_bytes(argv[0]) ); - }else{ - z = sqlite3_value_text(argv[0]); - if( z==0 ) return; - len = 0; - if( p1<0 ){ - for(z2=z; *z2; len++){ - SQLITE_SKIP_UTF8(z2); - } - } - } -#ifdef SQLITE_SUBSTR_COMPATIBILITY - /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as - ** as substr(X,1,N) - it returns the first N characters of X. This - ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] - ** from 2009-02-02 for compatibility of applications that exploited the - ** old buggy behavior. */ - if( p1==0 ) p1 = 1; /* */ -#endif - if( argc==3 ){ - p2 = sqlite3_value_int(argv[2]); - if( p2<0 ){ - p2 = -p2; - negP2 = 1; - } - }else{ - p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; - } - if( p1<0 ){ - p1 += len; - if( p1<0 ){ - p2 += p1; - if( p2<0 ) p2 = 0; - p1 = 0; - } - }else if( p1>0 ){ - p1--; - }else if( p2>0 ){ - p2--; - } - if( negP2 ){ - p1 -= p2; - if( p1<0 ){ - p2 += p1; - p1 = 0; - } - } - assert( p1>=0 && p2>=0 ); - if( p0type!=SQLITE_BLOB ){ - while( *z && p1 ){ - SQLITE_SKIP_UTF8(z); - p1--; - } - for(z2=z; *z2 && p2; p2--){ - SQLITE_SKIP_UTF8(z2); - } - sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, - SQLITE_UTF8); - }else{ - if( p1+p2>len ){ - p2 = len-p1; - if( p2<0 ) p2 = 0; - } - sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); - } -} - -/* -** Implementation of the round() function -*/ -#ifndef SQLITE_OMIT_FLOATING_POINT -static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ - int n = 0; - double r; - char *zBuf; - assert( argc==1 || argc==2 ); - if( argc==2 ){ - if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; - n = sqlite3_value_int(argv[1]); - if( n>30 ) n = 30; - if( n<0 ) n = 0; - } - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - r = sqlite3_value_double(argv[0]); - /* If Y==0 and X will fit in a 64-bit int, - ** handle the rounding directly, - ** otherwise use printf. - */ - if( r<-4503599627370496.0 || r>+4503599627370496.0 ){ - /* The value has no fractional part so there is nothing to round */ - }else if( n==0 ){ - r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5))); - }else{ - zBuf = sqlite3_mprintf("%.*f",n,r); - if( zBuf==0 ){ - sqlite3_result_error_nomem(context); - return; - } - sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8); - sqlite3_free(zBuf); - } - sqlite3_result_double(context, r); -} -#endif - -/* -** Allocate nByte bytes of space using sqlite3Malloc(). If the -** allocation fails, call sqlite3_result_error_nomem() to notify -** the database handle that malloc() has failed and return NULL. -** If nByte is larger than the maximum string or blob length, then -** raise an SQLITE_TOOBIG exception and return NULL. -*/ -static void *contextMalloc(sqlite3_context *context, i64 nByte){ - char *z; - sqlite3 *db = sqlite3_context_db_handle(context); - assert( nByte>0 ); - testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); - testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); - if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); - z = 0; - }else{ - z = sqlite3Malloc(nByte); - if( !z ){ - sqlite3_result_error_nomem(context); - } - } - return z; -} - -/* -** Implementation of the upper() and lower() SQL functions. -*/ -static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ - char *z1; - const char *z2; - int i, n; - UNUSED_PARAMETER(argc); - z2 = (char*)sqlite3_value_text(argv[0]); - n = sqlite3_value_bytes(argv[0]); - /* Verify that the call to _bytes() does not invalidate the _text() pointer */ - assert( z2==(char*)sqlite3_value_text(argv[0]) ); - if( z2 ){ - z1 = contextMalloc(context, ((i64)n)+1); - if( z1 ){ - for(i=0; imatchOne; /* "?" or "_" */ - u32 matchAll = pInfo->matchAll; /* "*" or "%" */ - u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */ - const u8 *zEscaped = 0; /* One past the last escaped input char */ - - while( (c = Utf8Read(zPattern))!=0 ){ - if( c==matchAll ){ /* Match "*" */ - /* Skip over multiple "*" characters in the pattern. If there - ** are also "?" characters, skip those as well, but consume a - ** single character of the input string for each "?" skipped */ - while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){ - if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){ - return SQLITE_NOWILDCARDMATCH; - } - } - if( c==0 ){ - return SQLITE_MATCH; /* "*" at the end of the pattern matches */ - }else if( c==matchOther ){ - if( pInfo->matchSet==0 ){ - c = sqlite3Utf8Read(&zPattern); - if( c==0 ) return SQLITE_NOWILDCARDMATCH; - }else{ - /* "[...]" immediately follows the "*". We have to do a slow - ** recursive search in this case, but it is an unusual case. */ - assert( matchOther<0x80 ); /* '[' is a single-byte character */ - while( *zString ){ - int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther); - if( bMatch!=SQLITE_NOMATCH ) return bMatch; - SQLITE_SKIP_UTF8(zString); - } - return SQLITE_NOWILDCARDMATCH; - } - } - - /* At this point variable c contains the first character of the - ** pattern string past the "*". Search in the input string for the - ** first matching character and recursively continue the match from - ** that point. - ** - ** For a case-insensitive search, set variable cx to be the same as - ** c but in the other case and search the input string for either - ** c or cx. - */ - if( c<=0x80 ){ - char zStop[3]; - int bMatch; - if( noCase ){ - zStop[0] = sqlite3Toupper(c); - zStop[1] = sqlite3Tolower(c); - zStop[2] = 0; - }else{ - zStop[0] = c; - zStop[1] = 0; - } - while(1){ - zString += strcspn((const char*)zString, zStop); - if( zString[0]==0 ) break; - zString++; - bMatch = patternCompare(zPattern,zString,pInfo,matchOther); - if( bMatch!=SQLITE_NOMATCH ) return bMatch; - } - }else{ - int bMatch; - while( (c2 = Utf8Read(zString))!=0 ){ - if( c2!=c ) continue; - bMatch = patternCompare(zPattern,zString,pInfo,matchOther); - if( bMatch!=SQLITE_NOMATCH ) return bMatch; - } - } - return SQLITE_NOWILDCARDMATCH; - } - if( c==matchOther ){ - if( pInfo->matchSet==0 ){ - c = sqlite3Utf8Read(&zPattern); - if( c==0 ) return SQLITE_NOMATCH; - zEscaped = zPattern; - }else{ - u32 prior_c = 0; - int seen = 0; - int invert = 0; - c = sqlite3Utf8Read(&zString); - if( c==0 ) return SQLITE_NOMATCH; - c2 = sqlite3Utf8Read(&zPattern); - if( c2=='^' ){ - invert = 1; - c2 = sqlite3Utf8Read(&zPattern); - } - if( c2==']' ){ - if( c==']' ) seen = 1; - c2 = sqlite3Utf8Read(&zPattern); - } - while( c2 && c2!=']' ){ - if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){ - c2 = sqlite3Utf8Read(&zPattern); - if( c>=prior_c && c<=c2 ) seen = 1; - prior_c = 0; - }else{ - if( c==c2 ){ - seen = 1; - } - prior_c = c2; - } - c2 = sqlite3Utf8Read(&zPattern); - } - if( c2==0 || (seen ^ invert)==0 ){ - return SQLITE_NOMATCH; - } - continue; - } - } - c2 = Utf8Read(zString); - if( c==c2 ) continue; - if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){ - continue; - } - if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue; - return SQLITE_NOMATCH; - } - return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH; -} - -/* -** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and -** non-zero if there is no match. -*/ -SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){ - return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '['); -} - -/* -** The sqlite3_strlike() interface. Return 0 on a match and non-zero for -** a miss - like strcmp(). -*/ -SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){ - return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc); -} - -/* -** Count the number of times that the LIKE operator (or GLOB which is -** just a variation of LIKE) gets called. This is used for testing -** only. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_like_count = 0; -#endif - - -/* -** Implementation of the like() SQL function. This function implements -** the build-in LIKE operator. The first argument to the function is the -** pattern and the second argument is the string. So, the SQL statements: -** -** A LIKE B -** -** is implemented as like(B,A). -** -** This same function (with a different compareInfo structure) computes -** the GLOB operator. -*/ -static void likeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *zA, *zB; - u32 escape; - int nPat; - sqlite3 *db = sqlite3_context_db_handle(context); - struct compareInfo *pInfo = sqlite3_user_data(context); - struct compareInfo backupInfo; - -#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS - if( sqlite3_value_type(argv[0])==SQLITE_BLOB - || sqlite3_value_type(argv[1])==SQLITE_BLOB - ){ -#ifdef SQLITE_TEST - sqlite3_like_count++; -#endif - sqlite3_result_int(context, 0); - return; - } -#endif - - /* Limit the length of the LIKE or GLOB pattern to avoid problems - ** of deep recursion and N*N behavior in patternCompare(). - */ - nPat = sqlite3_value_bytes(argv[0]); - testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); - testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); - if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ - sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); - return; - } - if( argc==3 ){ - /* The escape character string must consist of a single UTF-8 character. - ** Otherwise, return an error. - */ - const unsigned char *zEsc = sqlite3_value_text(argv[2]); - if( zEsc==0 ) return; - if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){ - sqlite3_result_error(context, - "ESCAPE expression must be a single character", -1); - return; - } - escape = sqlite3Utf8Read(&zEsc); - if( escape==pInfo->matchAll || escape==pInfo->matchOne ){ - memcpy(&backupInfo, pInfo, sizeof(backupInfo)); - pInfo = &backupInfo; - if( escape==pInfo->matchAll ) pInfo->matchAll = 0; - if( escape==pInfo->matchOne ) pInfo->matchOne = 0; - } - }else{ - escape = pInfo->matchSet; - } - zB = sqlite3_value_text(argv[0]); - zA = sqlite3_value_text(argv[1]); - if( zA && zB ){ -#ifdef SQLITE_TEST - sqlite3_like_count++; -#endif - sqlite3_result_int(context, - patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH); - } -} - -/* -** Implementation of the NULLIF(x,y) function. The result is the first -** argument if the arguments are different. The result is NULL if the -** arguments are equal to each other. -*/ -static void nullifFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - CollSeq *pColl = sqlite3GetFuncCollSeq(context); - UNUSED_PARAMETER(NotUsed); - if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){ - sqlite3_result_value(context, argv[0]); - } -} - -/* -** Implementation of the sqlite_version() function. The result is the version -** of the SQLite library that is running. -*/ -static void versionFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **NotUsed2 -){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - /* IMP: R-48699-48617 This function is an SQL wrapper around the - ** sqlite3_libversion() C-interface. */ - sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC); -} - -/* -** Implementation of the sqlite_source_id() function. The result is a string -** that identifies the particular version of the source code used to build -** SQLite. -*/ -static void sourceidFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **NotUsed2 -){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - /* IMP: R-24470-31136 This function is an SQL wrapper around the - ** sqlite3_sourceid() C interface. */ - sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC); -} - -/* -** Implementation of the sqlite_log() function. This is a wrapper around -** sqlite3_log(). The return value is NULL. The function exists purely for -** its side-effects. -*/ -static void errlogFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - UNUSED_PARAMETER(argc); - UNUSED_PARAMETER(context); - sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1])); -} - -/* -** Implementation of the sqlite_compileoption_used() function. -** The result is an integer that identifies if the compiler option -** was used to build SQLite. -*/ -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -static void compileoptionusedFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zOptName; - assert( argc==1 ); - UNUSED_PARAMETER(argc); - /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL - ** function is a wrapper around the sqlite3_compileoption_used() C/C++ - ** function. - */ - if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){ - sqlite3_result_int(context, sqlite3_compileoption_used(zOptName)); - } -} -#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ - -/* -** Implementation of the sqlite_compileoption_get() function. -** The result is a string that identifies the compiler options -** used to build SQLite. -*/ -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -static void compileoptiongetFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int n; - assert( argc==1 ); - UNUSED_PARAMETER(argc); - /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function - ** is a wrapper around the sqlite3_compileoption_get() C/C++ function. - */ - n = sqlite3_value_int(argv[0]); - sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC); -} -#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ - -/* Array for converting from half-bytes (nybbles) into ASCII hex -** digits. */ -static const char hexdigits[] = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' -}; - -/* -** Implementation of the QUOTE() function. This function takes a single -** argument. If the argument is numeric, the return value is the same as -** the argument. If the argument is NULL, the return value is the string -** "NULL". Otherwise, the argument is enclosed in single quotes with -** single-quote escapes. -*/ -static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ - assert( argc==1 ); - UNUSED_PARAMETER(argc); - switch( sqlite3_value_type(argv[0]) ){ - case SQLITE_FLOAT: { - double r1, r2; - char zBuf[50]; - r1 = sqlite3_value_double(argv[0]); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1); - sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8); - if( r1!=r2 ){ - sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1); - } - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); - break; - } - case SQLITE_INTEGER: { - sqlite3_result_value(context, argv[0]); - break; - } - case SQLITE_BLOB: { - char *zText = 0; - char const *zBlob = sqlite3_value_blob(argv[0]); - int nBlob = sqlite3_value_bytes(argv[0]); - assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ - zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); - if( zText ){ - int i; - for(i=0; i>4)&0x0F]; - zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F]; - } - zText[(nBlob*2)+2] = '\''; - zText[(nBlob*2)+3] = '\0'; - zText[0] = 'X'; - zText[1] = '\''; - sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); - sqlite3_free(zText); - } - break; - } - case SQLITE_TEXT: { - int i,j; - u64 n; - const unsigned char *zArg = sqlite3_value_text(argv[0]); - char *z; - - if( zArg==0 ) return; - for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; } - z = contextMalloc(context, ((i64)i)+((i64)n)+3); - if( z ){ - z[0] = '\''; - for(i=0, j=1; zArg[i]; i++){ - z[j++] = zArg[i]; - if( zArg[i]=='\'' ){ - z[j++] = '\''; - } - } - z[j++] = '\''; - z[j] = 0; - sqlite3_result_text(context, z, j, sqlite3_free); - } - break; - } - default: { - assert( sqlite3_value_type(argv[0])==SQLITE_NULL ); - sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC); - break; - } - } -} - -/* -** The unicode() function. Return the integer unicode code-point value -** for the first character of the input string. -*/ -static void unicodeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *z = sqlite3_value_text(argv[0]); - (void)argc; - if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z)); -} - -/* -** The char() function takes zero or more arguments, each of which is -** an integer. It constructs a string where each character of the string -** is the unicode character for the corresponding integer argument. -*/ -static void charFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - unsigned char *z, *zOut; - int i; - zOut = z = sqlite3_malloc64( argc*4+1 ); - if( z==0 ){ - sqlite3_result_error_nomem(context); - return; - } - for(i=0; i0x10ffff ) x = 0xfffd; - c = (unsigned)(x & 0x1fffff); - 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); - } \ - } - sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); -} - -/* -** The hex() function. Interpret the argument as a blob. Return -** a hexadecimal rendering as text. -*/ -static void hexFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int i, n; - const unsigned char *pBlob; - char *zHex, *z; - assert( argc==1 ); - UNUSED_PARAMETER(argc); - pBlob = sqlite3_value_blob(argv[0]); - n = sqlite3_value_bytes(argv[0]); - assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ - z = zHex = contextMalloc(context, ((i64)n)*2 + 1); - if( zHex ){ - for(i=0; i>4)&0xf]; - *(z++) = hexdigits[c&0xf]; - } - *z = 0; - sqlite3_result_text(context, zHex, n*2, sqlite3_free); - } -} - -/* -** The zeroblob(N) function returns a zero-filled blob of size N bytes. -*/ -static void zeroblobFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - i64 n; - int rc; - assert( argc==1 ); - UNUSED_PARAMETER(argc); - n = sqlite3_value_int64(argv[0]); - if( n<0 ) n = 0; - rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */ - if( rc ){ - sqlite3_result_error_code(context, rc); - } -} - -/* -** The replace() function. Three arguments are all strings: call -** them A, B, and C. The result is also a string which is derived -** from A by replacing every occurrence of B with C. The match -** must be exact. Collating sequences are not used. -*/ -static void replaceFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *zStr; /* The input string A */ - const unsigned char *zPattern; /* The pattern string B */ - const unsigned char *zRep; /* The replacement string C */ - unsigned char *zOut; /* The output */ - int nStr; /* Size of zStr */ - int nPattern; /* Size of zPattern */ - int nRep; /* Size of zRep */ - i64 nOut; /* Maximum size of zOut */ - int loopLimit; /* Last zStr[] that might match zPattern[] */ - int i, j; /* Loop counters */ - unsigned cntExpand; /* Number zOut expansions */ - sqlite3 *db = sqlite3_context_db_handle(context); - - assert( argc==3 ); - UNUSED_PARAMETER(argc); - zStr = sqlite3_value_text(argv[0]); - if( zStr==0 ) return; - nStr = sqlite3_value_bytes(argv[0]); - assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */ - zPattern = sqlite3_value_text(argv[1]); - if( zPattern==0 ){ - assert( sqlite3_value_type(argv[1])==SQLITE_NULL - || sqlite3_context_db_handle(context)->mallocFailed ); - return; - } - if( zPattern[0]==0 ){ - assert( sqlite3_value_type(argv[1])!=SQLITE_NULL ); - sqlite3_result_value(context, argv[0]); - return; - } - nPattern = sqlite3_value_bytes(argv[1]); - assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */ - zRep = sqlite3_value_text(argv[2]); - if( zRep==0 ) return; - nRep = sqlite3_value_bytes(argv[2]); - assert( zRep==sqlite3_value_text(argv[2]) ); - nOut = nStr + 1; - assert( nOutnPattern ){ - nOut += nRep - nPattern; - testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] ); - testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); - if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); - sqlite3_free(zOut); - return; - } - cntExpand++; - if( (cntExpand&(cntExpand-1))==0 ){ - /* Grow the size of the output buffer only on substitutions - ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */ - u8 *zOld; - zOld = zOut; - zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1)); - if( zOut==0 ){ - sqlite3_result_error_nomem(context); - sqlite3_free(zOld); - return; - } - } - } - memcpy(&zOut[j], zRep, nRep); - j += nRep; - i += nPattern-1; - } - } - assert( j+nStr-i+1<=nOut ); - memcpy(&zOut[j], &zStr[i], nStr-i); - j += nStr - i; - assert( j<=nOut ); - zOut[j] = 0; - sqlite3_result_text(context, (char*)zOut, j, sqlite3_free); -} - -/* -** Implementation of the TRIM(), LTRIM(), and RTRIM() functions. -** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both. -*/ -static void trimFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *zIn; /* Input string */ - const unsigned char *zCharSet; /* Set of characters to trim */ - int nIn; /* Number of bytes in input */ - int flags; /* 1: trimleft 2: trimright 3: trim */ - int i; /* Loop counter */ - unsigned char *aLen = 0; /* Length of each character in zCharSet */ - unsigned char **azChar = 0; /* Individual characters in zCharSet */ - int nChar; /* Number of characters in zCharSet */ - - if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ - return; - } - zIn = sqlite3_value_text(argv[0]); - if( zIn==0 ) return; - nIn = sqlite3_value_bytes(argv[0]); - assert( zIn==sqlite3_value_text(argv[0]) ); - if( argc==1 ){ - static const unsigned char lenOne[] = { 1 }; - static unsigned char * const azOne[] = { (u8*)" " }; - nChar = 1; - aLen = (u8*)lenOne; - azChar = (unsigned char **)azOne; - zCharSet = 0; - }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ - return; - }else{ - const unsigned char *z; - for(z=zCharSet, nChar=0; *z; nChar++){ - SQLITE_SKIP_UTF8(z); - } - if( nChar>0 ){ - azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); - if( azChar==0 ){ - return; - } - aLen = (unsigned char*)&azChar[nChar]; - for(z=zCharSet, nChar=0; *z; nChar++){ - azChar[nChar] = (unsigned char *)z; - SQLITE_SKIP_UTF8(z); - aLen[nChar] = (u8)(z - azChar[nChar]); - } - } - } - if( nChar>0 ){ - flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); - if( flags & 1 ){ - while( nIn>0 ){ - int len = 0; - for(i=0; i=nChar ) break; - zIn += len; - nIn -= len; - } - } - if( flags & 2 ){ - while( nIn>0 ){ - int len = 0; - for(i=0; i=nChar ) break; - nIn -= len; - } - } - if( zCharSet ){ - sqlite3_free(azChar); - } - } - sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT); -} - - -#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION -/* -** The "unknown" function is automatically substituted in place of -** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN -** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used. -** When the "sqlite3" command-line shell is built using this functionality, -** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries -** involving application-defined functions to be examined in a generic -** sqlite3 shell. -*/ -static void unknownFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - /* no-op */ -} -#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/ - - -/* IMP: R-25361-16150 This function is omitted from SQLite by default. It -** is only available if the SQLITE_SOUNDEX compile-time option is used -** when SQLite is built. -*/ -#ifdef SQLITE_SOUNDEX -/* -** Compute the soundex encoding of a word. -** -** IMP: R-59782-00072 The soundex(X) function returns a string that is the -** soundex encoding of the string X. -*/ -static void soundexFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - char zResult[8]; - const u8 *zIn; - int i, j; - static const unsigned char iCode[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, - 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, - 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, - 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0, - }; - assert( argc==1 ); - zIn = (u8*)sqlite3_value_text(argv[0]); - if( zIn==0 ) zIn = (u8*)""; - for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){} - if( zIn[i] ){ - u8 prevcode = iCode[zIn[i]&0x7f]; - zResult[0] = sqlite3Toupper(zIn[i]); - for(j=1; j<4 && zIn[i]; i++){ - int code = iCode[zIn[i]&0x7f]; - if( code>0 ){ - if( code!=prevcode ){ - prevcode = code; - zResult[j++] = code + '0'; - } - }else{ - prevcode = 0; - } - } - while( j<4 ){ - zResult[j++] = '0'; - } - zResult[j] = 0; - sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT); - }else{ - /* IMP: R-64894-50321 The string "?000" is returned if the argument - ** is NULL or contains no ASCII alphabetic characters. */ - sqlite3_result_text(context, "?000", 4, SQLITE_STATIC); - } -} -#endif /* SQLITE_SOUNDEX */ - -#ifndef SQLITE_OMIT_LOAD_EXTENSION -/* -** A function that loads a shared-library extension then returns NULL. -*/ -static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ - const char *zFile = (const char *)sqlite3_value_text(argv[0]); - const char *zProc; - sqlite3 *db = sqlite3_context_db_handle(context); - char *zErrMsg = 0; - - /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc - ** flag is set. See the sqlite3_enable_load_extension() API. - */ - if( (db->flags & SQLITE_LoadExtFunc)==0 ){ - sqlite3_result_error(context, "not authorized", -1); - return; - } - - if( argc==2 ){ - zProc = (const char *)sqlite3_value_text(argv[1]); - }else{ - zProc = 0; - } - if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){ - sqlite3_result_error(context, zErrMsg, -1); - sqlite3_free(zErrMsg); - } -} -#endif - - -/* -** An instance of the following structure holds the context of a -** sum() or avg() aggregate computation. -*/ -typedef struct SumCtx SumCtx; -struct SumCtx { - double rSum; /* Floating point sum */ - i64 iSum; /* Integer sum */ - i64 cnt; /* Number of elements summed */ - u8 overflow; /* True if integer overflow seen */ - u8 approx; /* True if non-integer value was input to the sum */ -}; - -/* -** Routines used to compute the sum, average, and total. -** -** The SUM() function follows the (broken) SQL standard which means -** that it returns NULL if it sums over no inputs. TOTAL returns -** 0.0 in that case. In addition, TOTAL always returns a float where -** SUM might return an integer if it never encounters a floating point -** value. TOTAL never fails, but SUM might through an exception if -** it overflows an integer. -*/ -static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ - SumCtx *p; - int type; - assert( argc==1 ); - UNUSED_PARAMETER(argc); - p = sqlite3_aggregate_context(context, sizeof(*p)); - type = sqlite3_value_numeric_type(argv[0]); - if( p && type!=SQLITE_NULL ){ - p->cnt++; - if( type==SQLITE_INTEGER ){ - i64 v = sqlite3_value_int64(argv[0]); - p->rSum += v; - if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){ - p->approx = p->overflow = 1; - } - }else{ - p->rSum += sqlite3_value_double(argv[0]); - p->approx = 1; - } - } -} -#ifndef SQLITE_OMIT_WINDOWFUNC -static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){ - SumCtx *p; - int type; - assert( argc==1 ); - UNUSED_PARAMETER(argc); - p = sqlite3_aggregate_context(context, sizeof(*p)); - type = sqlite3_value_numeric_type(argv[0]); - /* p is always non-NULL because sumStep() will have been called first - ** to initialize it */ - if( ALWAYS(p) && type!=SQLITE_NULL ){ - assert( p->cnt>0 ); - p->cnt--; - assert( type==SQLITE_INTEGER || p->approx ); - if( type==SQLITE_INTEGER && p->approx==0 ){ - i64 v = sqlite3_value_int64(argv[0]); - p->rSum -= v; - p->iSum -= v; - }else{ - p->rSum -= sqlite3_value_double(argv[0]); - } - } -} -#else -# define sumInverse 0 -#endif /* SQLITE_OMIT_WINDOWFUNC */ -static void sumFinalize(sqlite3_context *context){ - SumCtx *p; - p = sqlite3_aggregate_context(context, 0); - if( p && p->cnt>0 ){ - if( p->overflow ){ - sqlite3_result_error(context,"integer overflow",-1); - }else if( p->approx ){ - sqlite3_result_double(context, p->rSum); - }else{ - sqlite3_result_int64(context, p->iSum); - } - } -} -static void avgFinalize(sqlite3_context *context){ - SumCtx *p; - p = sqlite3_aggregate_context(context, 0); - if( p && p->cnt>0 ){ - sqlite3_result_double(context, p->rSum/(double)p->cnt); - } -} -static void totalFinalize(sqlite3_context *context){ - SumCtx *p; - p = sqlite3_aggregate_context(context, 0); - /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ - sqlite3_result_double(context, p ? p->rSum : (double)0); -} - -/* -** The following structure keeps track of state information for the -** count() aggregate function. -*/ -typedef struct CountCtx CountCtx; -struct CountCtx { - i64 n; -#ifdef SQLITE_DEBUG - int bInverse; /* True if xInverse() ever called */ -#endif -}; - -/* -** Routines to implement the count() aggregate function. -*/ -static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){ - CountCtx *p; - p = sqlite3_aggregate_context(context, sizeof(*p)); - if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){ - p->n++; - } - -#ifndef SQLITE_OMIT_DEPRECATED - /* The sqlite3_aggregate_count() function is deprecated. But just to make - ** sure it still operates correctly, verify that its count agrees with our - ** internal count when using count(*) and when the total count can be - ** expressed as a 32-bit integer. */ - assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse - || p->n==sqlite3_aggregate_count(context) ); -#endif -} -static void countFinalize(sqlite3_context *context){ - CountCtx *p; - p = sqlite3_aggregate_context(context, 0); - sqlite3_result_int64(context, p ? p->n : 0); -} -#ifndef SQLITE_OMIT_WINDOWFUNC -static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){ - CountCtx *p; - p = sqlite3_aggregate_context(ctx, sizeof(*p)); - /* p is always non-NULL since countStep() will have been called first */ - if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){ - p->n--; -#ifdef SQLITE_DEBUG - p->bInverse = 1; -#endif - } -} -#else -# define countInverse 0 -#endif /* SQLITE_OMIT_WINDOWFUNC */ - -/* -** Routines to implement min() and max() aggregate functions. -*/ -static void minmaxStep( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - Mem *pArg = (Mem *)argv[0]; - Mem *pBest; - UNUSED_PARAMETER(NotUsed); - - pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest)); - if( !pBest ) return; - - if( sqlite3_value_type(pArg)==SQLITE_NULL ){ - if( pBest->flags ) sqlite3SkipAccumulatorLoad(context); - }else if( pBest->flags ){ - int max; - int cmp; - CollSeq *pColl = sqlite3GetFuncCollSeq(context); - /* This step function is used for both the min() and max() aggregates, - ** the only difference between the two being that the sense of the - ** comparison is inverted. For the max() aggregate, the - ** sqlite3_user_data() function returns (void *)-1. For min() it - ** returns (void *)db, where db is the sqlite3* database pointer. - ** Therefore the next statement sets variable 'max' to 1 for the max() - ** aggregate, or 0 for min(). - */ - max = sqlite3_user_data(context)!=0; - cmp = sqlite3MemCompare(pBest, pArg, pColl); - if( (max && cmp<0) || (!max && cmp>0) ){ - sqlite3VdbeMemCopy(pBest, pArg); - }else{ - sqlite3SkipAccumulatorLoad(context); - } - }else{ - pBest->db = sqlite3_context_db_handle(context); - sqlite3VdbeMemCopy(pBest, pArg); - } -} -static void minMaxValueFinalize(sqlite3_context *context, int bValue){ - sqlite3_value *pRes; - pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); - if( pRes ){ - if( pRes->flags ){ - sqlite3_result_value(context, pRes); - } - if( bValue==0 ) sqlite3VdbeMemRelease(pRes); - } -} -#ifndef SQLITE_OMIT_WINDOWFUNC -static void minMaxValue(sqlite3_context *context){ - minMaxValueFinalize(context, 1); -} -#else -# define minMaxValue 0 -#endif /* SQLITE_OMIT_WINDOWFUNC */ -static void minMaxFinalize(sqlite3_context *context){ - minMaxValueFinalize(context, 0); -} - -/* -** group_concat(EXPR, ?SEPARATOR?) -*/ -static void groupConcatStep( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zVal; - StrAccum *pAccum; - const char *zSep; - int nVal, nSep; - assert( argc==1 || argc==2 ); - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); - - if( pAccum ){ - sqlite3 *db = sqlite3_context_db_handle(context); - int firstTerm = pAccum->mxAlloc==0; - pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; - if( !firstTerm ){ - if( argc==2 ){ - zSep = (char*)sqlite3_value_text(argv[1]); - nSep = sqlite3_value_bytes(argv[1]); - }else{ - zSep = ","; - nSep = 1; - } - if( zSep ) sqlite3_str_append(pAccum, zSep, nSep); - } - zVal = (char*)sqlite3_value_text(argv[0]); - nVal = sqlite3_value_bytes(argv[0]); - if( zVal ) sqlite3_str_append(pAccum, zVal, nVal); - } -} -#ifndef SQLITE_OMIT_WINDOWFUNC -static void groupConcatInverse( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int n; - StrAccum *pAccum; - assert( argc==1 || argc==2 ); - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); - /* pAccum is always non-NULL since groupConcatStep() will have always - ** run frist to initialize it */ - if( ALWAYS(pAccum) ){ - n = sqlite3_value_bytes(argv[0]); - if( argc==2 ){ - n += sqlite3_value_bytes(argv[1]); - }else{ - n++; - } - if( n>=(int)pAccum->nChar ){ - pAccum->nChar = 0; - }else{ - pAccum->nChar -= n; - memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar); - } - if( pAccum->nChar==0 ) pAccum->mxAlloc = 0; - } -} -#else -# define groupConcatInverse 0 -#endif /* SQLITE_OMIT_WINDOWFUNC */ -static void groupConcatFinalize(sqlite3_context *context){ - StrAccum *pAccum; - pAccum = sqlite3_aggregate_context(context, 0); - if( pAccum ){ - if( pAccum->accError==SQLITE_TOOBIG ){ - sqlite3_result_error_toobig(context); - }else if( pAccum->accError==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, - sqlite3_free); - } - } -} -#ifndef SQLITE_OMIT_WINDOWFUNC -static void groupConcatValue(sqlite3_context *context){ - sqlite3_str *pAccum; - pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0); - if( pAccum ){ - if( pAccum->accError==SQLITE_TOOBIG ){ - sqlite3_result_error_toobig(context); - }else if( pAccum->accError==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - }else{ - const char *zText = sqlite3_str_value(pAccum); - sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT); - } - } -} -#else -# define groupConcatValue 0 -#endif /* SQLITE_OMIT_WINDOWFUNC */ - -/* -** This routine does per-connection function registration. Most -** of the built-in functions above are part of the global function set. -** This routine only deals with those that are not global. -*/ -SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){ - int rc = sqlite3_overload_function(db, "MATCH", 2); - assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); - if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); - } -} - -/* -** Re-register the built-in LIKE functions. The caseSensitive -** parameter determines whether or not the LIKE operator is case -** sensitive. -*/ -SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ - struct compareInfo *pInfo; - int flags; - if( caseSensitive ){ - pInfo = (struct compareInfo*)&likeInfoAlt; - flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE; - }else{ - pInfo = (struct compareInfo*)&likeInfoNorm; - flags = SQLITE_FUNC_LIKE; - } - sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); - sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); - sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags; - sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags; -} - -/* -** pExpr points to an expression which implements a function. If -** it is appropriate to apply the LIKE optimization to that function -** then set aWc[0] through aWc[2] to the wildcard characters and the -** escape character and then return TRUE. If the function is not a -** LIKE-style function then return FALSE. -** -** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE -** operator if c is a string literal that is exactly one byte in length. -** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is -** no ESCAPE clause. -** -** *pIsNocase is set to true if uppercase and lowercase are equivalent for -** the function (default for LIKE). If the function makes the distinction -** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to -** false. -*/ -SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){ - FuncDef *pDef; - int nExpr; - if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){ - return 0; - } - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - nExpr = pExpr->x.pList->nExpr; - pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0); -#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION - if( pDef==0 ) return 0; -#endif - if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ - return 0; - } - - /* The memcpy() statement assumes that the wildcard characters are - ** the first three statements in the compareInfo structure. The - ** asserts() that follow verify that assumption - */ - memcpy(aWc, pDef->pUserData, 3); - assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll ); - assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne ); - assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet ); - - if( nExpr<3 ){ - aWc[3] = 0; - }else{ - Expr *pEscape = pExpr->x.pList->a[2].pExpr; - char *zEscape; - if( pEscape->op!=TK_STRING ) return 0; - zEscape = pEscape->u.zToken; - if( zEscape[0]==0 || zEscape[1]!=0 ) return 0; - if( zEscape[0]==aWc[0] ) return 0; - if( zEscape[0]==aWc[1] ) return 0; - aWc[3] = zEscape[0]; - } - - *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0; - return 1; -} - -/* -** All of the FuncDef structures in the aBuiltinFunc[] array above -** to the global function hash table. This occurs at start-time (as -** a consequence of calling sqlite3_initialize()). -** -** After this routine runs -*/ -SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ - /* - ** The following array holds FuncDef structures for all of the functions - ** defined in this file. - ** - ** The array cannot be constant since changes are made to the - ** FuncDef.pHash elements at start-time. The elements of this array - ** are read-only after initialization is complete. - ** - ** For peak efficiency, put the most frequently used function last. - */ - static FuncDef aBuiltinFunc[] = { -/***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/ - TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0), - TEST_FUNC(expr_compare, 2, INLINEFUNC_expr_compare, 0), - TEST_FUNC(expr_implies_expr, 2, INLINEFUNC_expr_implies_expr, 0), -#ifdef SQLITE_DEBUG - TEST_FUNC(affinity, 1, INLINEFUNC_affinity, 0), -#endif -/***** Regular functions *****/ -#ifdef SQLITE_SOUNDEX - FUNCTION(soundex, 1, 0, 0, soundexFunc ), -#endif -#ifndef SQLITE_OMIT_LOAD_EXTENSION - SFUNCTION(load_extension, 1, 0, 0, loadExt ), - SFUNCTION(load_extension, 2, 0, 0, loadExt ), -#endif -#if SQLITE_USER_AUTHENTICATION - FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), -#endif -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS - DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), - DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), -#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ - INLINE_FUNC(unlikely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), - INLINE_FUNC(likelihood, 2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), - INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), -#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC - FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET| - SQLITE_FUNC_TYPEOF), -#endif - FUNCTION(ltrim, 1, 1, 0, trimFunc ), - FUNCTION(ltrim, 2, 1, 0, trimFunc ), - FUNCTION(rtrim, 1, 2, 0, trimFunc ), - FUNCTION(rtrim, 2, 2, 0, trimFunc ), - FUNCTION(trim, 1, 3, 0, trimFunc ), - FUNCTION(trim, 2, 3, 0, trimFunc ), - FUNCTION(min, -1, 0, 1, minmaxFunc ), - FUNCTION(min, 0, 0, 1, 0 ), - WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, - SQLITE_FUNC_MINMAX ), - FUNCTION(max, -1, 1, 1, minmaxFunc ), - FUNCTION(max, 0, 1, 1, 0 ), - WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, - SQLITE_FUNC_MINMAX ), - FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), - FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH), - FUNCTION(instr, 2, 0, 0, instrFunc ), - FUNCTION(printf, -1, 0, 0, printfFunc ), - FUNCTION(unicode, 1, 0, 0, unicodeFunc ), - FUNCTION(char, -1, 0, 0, charFunc ), - FUNCTION(abs, 1, 0, 0, absFunc ), -#ifndef SQLITE_OMIT_FLOATING_POINT - FUNCTION(round, 1, 0, 0, roundFunc ), - FUNCTION(round, 2, 0, 0, roundFunc ), -#endif - FUNCTION(upper, 1, 0, 0, upperFunc ), - FUNCTION(lower, 1, 0, 0, lowerFunc ), - FUNCTION(hex, 1, 0, 0, hexFunc ), - INLINE_FUNC(ifnull, 2, INLINEFUNC_coalesce, 0 ), - VFUNCTION(random, 0, 0, 0, randomFunc ), - VFUNCTION(randomblob, 1, 0, 0, randomBlob ), - FUNCTION(nullif, 2, 0, 1, nullifFunc ), - DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ), - DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), - FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), - FUNCTION(quote, 1, 0, 0, quoteFunc ), - VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), - VFUNCTION(changes, 0, 0, 0, changes ), - VFUNCTION(total_changes, 0, 0, 0, total_changes ), - FUNCTION(replace, 3, 0, 0, replaceFunc ), - FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ), - FUNCTION(substr, 2, 0, 0, substrFunc ), - FUNCTION(substr, 3, 0, 0, substrFunc ), - WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0), - WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0), - WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0), - WAGGREGATE(count, 0,0,0, countStep, - countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ), - WAGGREGATE(count, 1,0,0, countStep, - countFinalize, countFinalize, countInverse, 0 ), - WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, - groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), - WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, - groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), - - LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), -#ifdef SQLITE_CASE_SENSITIVE_LIKE - LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), - LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), -#else - LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE), - LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE), -#endif -#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION - FUNCTION(unknown, -1, 0, 0, unknownFunc ), -#endif - FUNCTION(coalesce, 1, 0, 0, 0 ), - FUNCTION(coalesce, 0, 0, 0, 0 ), - INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, 0 ), - INLINE_FUNC(iif, 3, INLINEFUNC_iif, 0 ), - }; -#ifndef SQLITE_OMIT_ALTERTABLE - sqlite3AlterFunctions(); -#endif - sqlite3WindowFunctions(); - sqlite3RegisterDateTimeFunctions(); - sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc)); - -#if 0 /* Enable to print out how the built-in functions are hashed */ - { - int i; - FuncDef *p; - for(i=0; iu.pHash){ - int n = sqlite3Strlen30(p->zName); - int h = p->zName[0] + n; - printf(" %s(%d)", p->zName, h); - } - printf("\n"); - } - } -#endif -} - -/************** End of func.c ************************************************/ -/************** Begin file fkey.c ********************************************/ -/* -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code used by the compiler to add foreign key -** support to compiled SQL statements. -*/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_OMIT_FOREIGN_KEY -#ifndef SQLITE_OMIT_TRIGGER - -/* -** Deferred and Immediate FKs -** -------------------------- -** -** Foreign keys in SQLite come in two flavours: deferred and immediate. -** If an immediate foreign key constraint is violated, -** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current -** statement transaction rolled back. If a -** deferred foreign key constraint is violated, no action is taken -** immediately. However if the application attempts to commit the -** transaction before fixing the constraint violation, the attempt fails. -** -** Deferred constraints are implemented using a simple counter associated -** with the database handle. The counter is set to zero each time a -** database transaction is opened. Each time a statement is executed -** that causes a foreign key violation, the counter is incremented. Each -** time a statement is executed that removes an existing violation from -** the database, the counter is decremented. When the transaction is -** committed, the commit fails if the current value of the counter is -** greater than zero. This scheme has two big drawbacks: -** -** * When a commit fails due to a deferred foreign key constraint, -** there is no way to tell which foreign constraint is not satisfied, -** or which row it is not satisfied for. -** -** * If the database contains foreign key violations when the -** transaction is opened, this may cause the mechanism to malfunction. -** -** Despite these problems, this approach is adopted as it seems simpler -** than the alternatives. -** -** INSERT operations: -** -** I.1) For each FK for which the table is the child table, search -** the parent table for a match. If none is found increment the -** constraint counter. -** -** I.2) For each FK for which the table is the parent table, -** search the child table for rows that correspond to the new -** row in the parent table. Decrement the counter for each row -** found (as the constraint is now satisfied). -** -** DELETE operations: -** -** D.1) For each FK for which the table is the child table, -** search the parent table for a row that corresponds to the -** deleted row in the child table. If such a row is not found, -** decrement the counter. -** -** D.2) For each FK for which the table is the parent table, search -** the child table for rows that correspond to the deleted row -** in the parent table. For each found increment the counter. -** -** UPDATE operations: -** -** An UPDATE command requires that all 4 steps above are taken, but only -** for FK constraints for which the affected columns are actually -** modified (values must be compared at runtime). -** -** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2. -** This simplifies the implementation a bit. -** -** For the purposes of immediate FK constraints, the OR REPLACE conflict -** resolution is considered to delete rows before the new row is inserted. -** If a delete caused by OR REPLACE violates an FK constraint, an exception -** is thrown, even if the FK constraint would be satisfied after the new -** row is inserted. -** -** Immediate constraints are usually handled similarly. The only difference -** is that the counter used is stored as part of each individual statement -** object (struct Vdbe). If, after the statement has run, its immediate -** constraint counter is greater than zero, -** it returns SQLITE_CONSTRAINT_FOREIGNKEY -** and the statement transaction is rolled back. An exception is an INSERT -** statement that inserts a single row only (no triggers). In this case, -** instead of using a counter, an exception is thrown immediately if the -** INSERT violates a foreign key constraint. This is necessary as such -** an INSERT does not open a statement transaction. -** -** TODO: How should dropping a table be handled? How should renaming a -** table be handled? -** -** -** Query API Notes -** --------------- -** -** Before coding an UPDATE or DELETE row operation, the code-generator -** for those two operations needs to know whether or not the operation -** requires any FK processing and, if so, which columns of the original -** row are required by the FK processing VDBE code (i.e. if FKs were -** implemented using triggers, which of the old.* columns would be -** accessed). No information is required by the code-generator before -** coding an INSERT operation. The functions used by the UPDATE/DELETE -** generation code to query for this information are: -** -** sqlite3FkRequired() - Test to see if FK processing is required. -** sqlite3FkOldmask() - Query for the set of required old.* columns. -** -** -** Externally accessible module functions -** -------------------------------------- -** -** sqlite3FkCheck() - Check for foreign key violations. -** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions. -** sqlite3FkDelete() - Delete an FKey structure. -*/ - -/* -** VDBE Calling Convention -** ----------------------- -** -** Example: -** -** For the following INSERT statement: -** -** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c); -** INSERT INTO t1 VALUES(1, 2, 3.1); -** -** Register (x): 2 (type integer) -** Register (x+1): 1 (type integer) -** Register (x+2): NULL (type NULL) -** Register (x+3): 3.1 (type real) -*/ - -/* -** A foreign key constraint requires that the key columns in the parent -** table are collectively subject to a UNIQUE or PRIMARY KEY constraint. -** Given that pParent is the parent table for foreign key constraint pFKey, -** search the schema for a unique index on the parent key columns. -** -** If successful, zero is returned. If the parent key is an INTEGER PRIMARY -** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx -** is set to point to the unique index. -** -** If the parent key consists of a single column (the foreign key constraint -** is not a composite foreign key), output variable *paiCol is set to NULL. -** Otherwise, it is set to point to an allocated array of size N, where -** N is the number of columns in the parent key. The first element of the -** array is the index of the child table column that is mapped by the FK -** constraint to the parent table column stored in the left-most column -** of index *ppIdx. The second element of the array is the index of the -** child table column that corresponds to the second left-most column of -** *ppIdx, and so on. -** -** If the required index cannot be found, either because: -** -** 1) The named parent key columns do not exist, or -** -** 2) The named parent key columns do exist, but are not subject to a -** UNIQUE or PRIMARY KEY constraint, or -** -** 3) No parent key columns were provided explicitly as part of the -** foreign key definition, and the parent table does not have a -** PRIMARY KEY, or -** -** 4) No parent key columns were provided explicitly as part of the -** foreign key definition, and the PRIMARY KEY of the parent table -** consists of a different number of columns to the child key in -** the child table. -** -** then non-zero is returned, and a "foreign key mismatch" error loaded -** into pParse. If an OOM error occurs, non-zero is returned and the -** pParse->db->mallocFailed flag is set. -*/ -SQLITE_PRIVATE int sqlite3FkLocateIndex( - Parse *pParse, /* Parse context to store any error in */ - Table *pParent, /* Parent table of FK constraint pFKey */ - FKey *pFKey, /* Foreign key to find index for */ - Index **ppIdx, /* OUT: Unique index on parent table */ - int **paiCol /* OUT: Map of index columns in pFKey */ -){ - Index *pIdx = 0; /* Value to return via *ppIdx */ - int *aiCol = 0; /* Value to return via *paiCol */ - int nCol = pFKey->nCol; /* Number of columns in parent key */ - char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */ - - /* The caller is responsible for zeroing output parameters. */ - assert( ppIdx && *ppIdx==0 ); - assert( !paiCol || *paiCol==0 ); - assert( pParse ); - - /* If this is a non-composite (single column) foreign key, check if it - ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx - ** and *paiCol set to zero and return early. - ** - ** Otherwise, for a composite foreign key (more than one column), allocate - ** space for the aiCol array (returned via output parameter *paiCol). - ** Non-composite foreign keys do not require the aiCol array. - */ - if( nCol==1 ){ - /* The FK maps to the IPK if any of the following are true: - ** - ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly - ** mapped to the primary key of table pParent, or - ** 2) The FK is explicitly mapped to a column declared as INTEGER - ** PRIMARY KEY. - */ - if( pParent->iPKey>=0 ){ - if( !zKey ) return 0; - if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0; - } - }else if( paiCol ){ - assert( nCol>1 ); - aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int)); - if( !aiCol ) return 1; - *paiCol = aiCol; - } - - for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){ - /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number - ** of columns. If each indexed column corresponds to a foreign key - ** column of pFKey, then this index is a winner. */ - - if( zKey==0 ){ - /* If zKey is NULL, then this foreign key is implicitly mapped to - ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be - ** identified by the test. */ - if( IsPrimaryKeyIndex(pIdx) ){ - if( aiCol ){ - int i; - for(i=0; iaCol[i].iFrom; - } - break; - } - }else{ - /* If zKey is non-NULL, then this foreign key was declared to - ** map to an explicit list of columns in table pParent. Check if this - ** index matches those columns. Also, check that the index uses - ** the default collation sequences for each column. */ - int i, j; - for(i=0; iaiColumn[i]; /* Index of column in parent tbl */ - const char *zDfltColl; /* Def. collation for column */ - char *zIdxCol; /* Name of indexed column */ - - if( iCol<0 ) break; /* No foreign keys against expression indexes */ - - /* If the index uses a collation sequence that is different from - ** the default collation sequence for the column, this index is - ** unusable. Bail out early in this case. */ - zDfltColl = pParent->aCol[iCol].zColl; - if( !zDfltColl ) zDfltColl = sqlite3StrBINARY; - if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break; - - zIdxCol = pParent->aCol[iCol].zName; - for(j=0; jaCol[j].zCol, zIdxCol)==0 ){ - if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom; - break; - } - } - if( j==nCol ) break; - } - if( i==nCol ) break; /* pIdx is usable */ - } - } - } - - if( !pIdx ){ - if( !pParse->disableTriggers ){ - sqlite3ErrorMsg(pParse, - "foreign key mismatch - \"%w\" referencing \"%w\"", - pFKey->pFrom->zName, pFKey->zTo); - } - sqlite3DbFree(pParse->db, aiCol); - return 1; - } - - *ppIdx = pIdx; - return 0; -} - -/* -** This function is called when a row is inserted into or deleted from the -** child table of foreign key constraint pFKey. If an SQL UPDATE is executed -** on the child table of pFKey, this function is invoked twice for each row -** affected - once to "delete" the old row, and then again to "insert" the -** new row. -** -** Each time it is called, this function generates VDBE code to locate the -** row in the parent table that corresponds to the row being inserted into -** or deleted from the child table. If the parent row can be found, no -** special action is taken. Otherwise, if the parent row can *not* be -** found in the parent table: -** -** Operation | FK type | Action taken -** -------------------------------------------------------------------------- -** INSERT immediate Increment the "immediate constraint counter". -** -** DELETE immediate Decrement the "immediate constraint counter". -** -** INSERT deferred Increment the "deferred constraint counter". -** -** DELETE deferred Decrement the "deferred constraint counter". -** -** These operations are identified in the comment at the top of this file -** (fkey.c) as "I.1" and "D.1". -*/ -static void fkLookupParent( - Parse *pParse, /* Parse context */ - int iDb, /* Index of database housing pTab */ - Table *pTab, /* Parent table of FK pFKey */ - Index *pIdx, /* Unique index on parent key columns in pTab */ - FKey *pFKey, /* Foreign key constraint */ - int *aiCol, /* Map from parent key columns to child table columns */ - int regData, /* Address of array containing child table row */ - int nIncr, /* Increment constraint counter by this */ - int isIgnore /* If true, pretend pTab contains all NULL values */ -){ - int i; /* Iterator variable */ - Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */ - int iCur = pParse->nTab - 1; /* Cursor number to use */ - int iOk = sqlite3VdbeMakeLabel(pParse); /* jump here if parent key found */ - - sqlite3VdbeVerifyAbortable(v, - (!pFKey->isDeferred - && !(pParse->db->flags & SQLITE_DeferFKs) - && !pParse->pToplevel - && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore); - - /* If nIncr is less than zero, then check at runtime if there are any - ** outstanding constraints to resolve. If there are not, there is no need - ** to check if deleting this row resolves any outstanding violations. - ** - ** Check if any of the key columns in the child table row are NULL. If - ** any are, then the constraint is considered satisfied. No need to - ** search for a matching row in the parent table. */ - if( nIncr<0 ){ - sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); - VdbeCoverage(v); - } - for(i=0; inCol; i++){ - int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1; - sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v); - } - - if( isIgnore==0 ){ - if( pIdx==0 ){ - /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY - ** column of the parent table (table pTab). */ - int iMustBeInt; /* Address of MustBeInt instruction */ - int regTemp = sqlite3GetTempReg(pParse); - - /* Invoke MustBeInt to coerce the child key value to an integer (i.e. - ** apply the affinity of the parent key). If this fails, then there - ** is no matching parent key. Before using MustBeInt, make a copy of - ** the value. Otherwise, the value inserted into the child key column - ** will have INTEGER affinity applied to it, which may not be correct. */ - sqlite3VdbeAddOp2(v, OP_SCopy, - sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp); - iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0); - VdbeCoverage(v); - - /* If the parent table is the same as the child table, and we are about - ** to increment the constraint-counter (i.e. this is an INSERT operation), - ** then check if the row being inserted matches itself. If so, do not - ** increment the constraint-counter. */ - if( pTab==pFKey->pFrom && nIncr==1 ){ - sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - } - - sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v); - sqlite3VdbeGoto(v, iOk); - sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); - sqlite3VdbeJumpHere(v, iMustBeInt); - sqlite3ReleaseTempReg(pParse, regTemp); - }else{ - int nCol = pFKey->nCol; - int regTemp = sqlite3GetTempRange(pParse, nCol); - int regRec = sqlite3GetTempReg(pParse); - - sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); - for(i=0; ipFrom, aiCol[i])+1+regData, - regTemp+i); - } - - /* If the parent table is the same as the child table, and we are about - ** to increment the constraint-counter (i.e. this is an INSERT operation), - ** then check if the row being inserted matches itself. If so, do not - ** increment the constraint-counter. - ** - ** If any of the parent-key values are NULL, then the row cannot match - ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any - ** of the parent-key values are NULL (at this point it is known that - ** none of the child key values are). - */ - if( pTab==pFKey->pFrom && nIncr==1 ){ - int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; - for(i=0; ipFrom,aiCol[i]) - +1+regData; - int iParent = 1+regData; - iParent += sqlite3TableColumnToStorage(pIdx->pTable, - pIdx->aiColumn[i]); - assert( pIdx->aiColumn[i]>=0 ); - assert( aiCol[i]!=pTab->iPKey ); - if( pIdx->aiColumn[i]==pTab->iPKey ){ - /* The parent key is a composite key that includes the IPK column */ - iParent = regData; - } - sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); - } - sqlite3VdbeGoto(v, iOk); - } - - sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec, - sqlite3IndexAffinityStr(pParse->db,pIdx), nCol); - sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v); - - sqlite3ReleaseTempReg(pParse, regRec); - sqlite3ReleaseTempRange(pParse, regTemp, nCol); - } - } - - if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs) - && !pParse->pToplevel - && !pParse->isMultiWrite - ){ - /* Special case: If this is an INSERT statement that will insert exactly - ** one row into the table, raise a constraint immediately instead of - ** incrementing a counter. This is necessary as the VM code is being - ** generated for will not open a statement transaction. */ - assert( nIncr==1 ); - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, - OE_Abort, 0, P4_STATIC, P5_ConstraintFK); - }else{ - if( nIncr>0 && pFKey->isDeferred==0 ){ - sqlite3MayAbort(pParse); - } - sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); - } - - sqlite3VdbeResolveLabel(v, iOk); - sqlite3VdbeAddOp1(v, OP_Close, iCur); -} - - -/* -** Return an Expr object that refers to a memory register corresponding -** to column iCol of table pTab. -** -** regBase is the first of an array of register that contains the data -** for pTab. regBase itself holds the rowid. regBase+1 holds the first -** column. regBase+2 holds the second column, and so forth. -*/ -static Expr *exprTableRegister( - Parse *pParse, /* Parsing and code generating context */ - Table *pTab, /* The table whose content is at r[regBase]... */ - int regBase, /* Contents of table pTab */ - i16 iCol /* Which column of pTab is desired */ -){ - Expr *pExpr; - Column *pCol; - const char *zColl; - sqlite3 *db = pParse->db; - - pExpr = sqlite3Expr(db, TK_REGISTER, 0); - if( pExpr ){ - if( iCol>=0 && iCol!=pTab->iPKey ){ - pCol = &pTab->aCol[iCol]; - pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1; - pExpr->affExpr = pCol->affinity; - zColl = pCol->zColl; - if( zColl==0 ) zColl = db->pDfltColl->zName; - pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl); - }else{ - pExpr->iTable = regBase; - pExpr->affExpr = SQLITE_AFF_INTEGER; - } - } - return pExpr; -} - -/* -** Return an Expr object that refers to column iCol of table pTab which -** has cursor iCur. -*/ -static Expr *exprTableColumn( - sqlite3 *db, /* The database connection */ - Table *pTab, /* The table whose column is desired */ - int iCursor, /* The open cursor on the table */ - i16 iCol /* The column that is wanted */ -){ - Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0); - if( pExpr ){ - pExpr->y.pTab = pTab; - pExpr->iTable = iCursor; - pExpr->iColumn = iCol; - } - return pExpr; -} - -/* -** This function is called to generate code executed when a row is deleted -** from the parent table of foreign key constraint pFKey and, if pFKey is -** deferred, when a row is inserted into the same table. When generating -** code for an SQL UPDATE operation, this function may be called twice - -** once to "delete" the old row and once to "insert" the new row. -** -** Parameter nIncr is passed -1 when inserting a row (as this may decrease -** the number of FK violations in the db) or +1 when deleting one (as this -** may increase the number of FK constraint problems). -** -** The code generated by this function scans through the rows in the child -** table that correspond to the parent table row being deleted or inserted. -** For each child row found, one of the following actions is taken: -** -** Operation | FK type | Action taken -** -------------------------------------------------------------------------- -** DELETE immediate Increment the "immediate constraint counter". -** Or, if the ON (UPDATE|DELETE) action is RESTRICT, -** throw a "FOREIGN KEY constraint failed" exception. -** -** INSERT immediate Decrement the "immediate constraint counter". -** -** DELETE deferred Increment the "deferred constraint counter". -** Or, if the ON (UPDATE|DELETE) action is RESTRICT, -** throw a "FOREIGN KEY constraint failed" exception. -** -** INSERT deferred Decrement the "deferred constraint counter". -** -** These operations are identified in the comment at the top of this file -** (fkey.c) as "I.2" and "D.2". -*/ -static void fkScanChildren( - Parse *pParse, /* Parse context */ - SrcList *pSrc, /* The child table to be scanned */ - Table *pTab, /* The parent table */ - Index *pIdx, /* Index on parent covering the foreign key */ - FKey *pFKey, /* The foreign key linking pSrc to pTab */ - int *aiCol, /* Map from pIdx cols to child table cols */ - int regData, /* Parent row data starts here */ - int nIncr /* Amount to increment deferred counter by */ -){ - sqlite3 *db = pParse->db; /* Database handle */ - int i; /* Iterator variable */ - Expr *pWhere = 0; /* WHERE clause to scan with */ - NameContext sNameContext; /* Context used to resolve WHERE clause */ - WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */ - int iFkIfZero = 0; /* Address of OP_FkIfZero */ - Vdbe *v = sqlite3GetVdbe(pParse); - - assert( pIdx==0 || pIdx->pTable==pTab ); - assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol ); - assert( pIdx!=0 || pFKey->nCol==1 ); - assert( pIdx!=0 || HasRowid(pTab) ); - - if( nIncr<0 ){ - iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0); - VdbeCoverage(v); - } - - /* Create an Expr object representing an SQL expression like: - ** - ** = AND = ... - ** - ** The collation sequence used for the comparison should be that of - ** the parent key columns. The affinity of the parent key column should - ** be applied to each child key value before the comparison takes place. - */ - for(i=0; inCol; i++){ - Expr *pLeft; /* Value from parent table row */ - Expr *pRight; /* Column ref to child table */ - Expr *pEq; /* Expression (pLeft = pRight) */ - i16 iCol; /* Index of column in child table */ - const char *zCol; /* Name of column in child table */ - - iCol = pIdx ? pIdx->aiColumn[i] : -1; - pLeft = exprTableRegister(pParse, pTab, regData, iCol); - iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; - assert( iCol>=0 ); - zCol = pFKey->pFrom->aCol[iCol].zName; - pRight = sqlite3Expr(db, TK_ID, zCol); - pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight); - pWhere = sqlite3ExprAnd(pParse, pWhere, pEq); - } - - /* If the child table is the same as the parent table, then add terms - ** to the WHERE clause that prevent this entry from being scanned. - ** The added WHERE clause terms are like this: - ** - ** $current_rowid!=rowid - ** NOT( $current_a==a AND $current_b==b AND ... ) - ** - ** The first form is used for rowid tables. The second form is used - ** for WITHOUT ROWID tables. In the second form, the *parent* key is - ** (a,b,...). Either the parent or primary key could be used to - ** uniquely identify the current row, but the parent key is more convenient - ** as the required values have already been loaded into registers - ** by the caller. - */ - if( pTab==pFKey->pFrom && nIncr>0 ){ - Expr *pNe; /* Expression (pLeft != pRight) */ - Expr *pLeft; /* Value from parent table row */ - Expr *pRight; /* Column ref to child table */ - if( HasRowid(pTab) ){ - pLeft = exprTableRegister(pParse, pTab, regData, -1); - pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1); - pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight); - }else{ - Expr *pEq, *pAll = 0; - assert( pIdx!=0 ); - for(i=0; inKeyCol; i++){ - i16 iCol = pIdx->aiColumn[i]; - assert( iCol>=0 ); - pLeft = exprTableRegister(pParse, pTab, regData, iCol); - pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName); - pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight); - pAll = sqlite3ExprAnd(pParse, pAll, pEq); - } - pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0); - } - pWhere = sqlite3ExprAnd(pParse, pWhere, pNe); - } - - /* Resolve the references in the WHERE clause. */ - memset(&sNameContext, 0, sizeof(NameContext)); - sNameContext.pSrcList = pSrc; - sNameContext.pParse = pParse; - sqlite3ResolveExprNames(&sNameContext, pWhere); - - /* Create VDBE to loop through the entries in pSrc that match the WHERE - ** clause. For each row found, increment either the deferred or immediate - ** foreign key constraint counter. */ - if( pParse->nErr==0 ){ - pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0); - sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr); - if( pWInfo ){ - sqlite3WhereEnd(pWInfo); - } - } - - /* Clean up the WHERE clause constructed above. */ - sqlite3ExprDelete(db, pWhere); - if( iFkIfZero ){ - sqlite3VdbeJumpHereOrPopInst(v, iFkIfZero); - } -} - -/* -** This function returns a linked list of FKey objects (connected by -** FKey.pNextTo) holding all children of table pTab. For example, -** given the following schema: -** -** CREATE TABLE t1(a PRIMARY KEY); -** CREATE TABLE t2(b REFERENCES t1(a); -** -** Calling this function with table "t1" as an argument returns a pointer -** to the FKey structure representing the foreign key constraint on table -** "t2". Calling this function with "t2" as the argument would return a -** NULL pointer (as there are no FK constraints for which t2 is the parent -** table). -*/ -SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){ - return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName); -} - -/* -** The second argument is a Trigger structure allocated by the -** fkActionTrigger() routine. This function deletes the Trigger structure -** and all of its sub-components. -** -** The Trigger structure or any of its sub-components may be allocated from -** the lookaside buffer belonging to database handle dbMem. -*/ -static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ - if( p ){ - TriggerStep *pStep = p->step_list; - sqlite3ExprDelete(dbMem, pStep->pWhere); - sqlite3ExprListDelete(dbMem, pStep->pExprList); - sqlite3SelectDelete(dbMem, pStep->pSelect); - sqlite3ExprDelete(dbMem, p->pWhen); - sqlite3DbFree(dbMem, p); - } -} - -/* -** This function is called to generate code that runs when table pTab is -** being dropped from the database. The SrcList passed as the second argument -** to this function contains a single entry guaranteed to resolve to -** table pTab. -** -** Normally, no code is required. However, if either -** -** (a) The table is the parent table of a FK constraint, or -** (b) The table is the child table of a deferred FK constraint and it is -** determined at runtime that there are outstanding deferred FK -** constraint violations in the database, -** -** then the equivalent of "DELETE FROM " is executed before dropping -** the table from the database. Triggers are disabled while running this -** DELETE, but foreign key actions are not. -*/ -SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){ - sqlite3 *db = pParse->db; - if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){ - int iSkip = 0; - Vdbe *v = sqlite3GetVdbe(pParse); - - assert( v ); /* VDBE has already been allocated */ - assert( pTab->pSelect==0 ); /* Not a view */ - if( sqlite3FkReferences(pTab)==0 ){ - /* Search for a deferred foreign key constraint for which this table - ** is the child table. If one cannot be found, return without - ** generating any VDBE code. If one can be found, then jump over - ** the entire DELETE if there are no outstanding deferred constraints - ** when this statement is run. */ - FKey *p; - for(p=pTab->pFKey; p; p=p->pNextFrom){ - if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break; - } - if( !p ) return; - iSkip = sqlite3VdbeMakeLabel(pParse); - sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v); - } - - pParse->disableTriggers = 1; - sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0); - pParse->disableTriggers = 0; - - /* If the DELETE has generated immediate foreign key constraint - ** violations, halt the VDBE and return an error at this point, before - ** any modifications to the schema are made. This is because statement - ** transactions are not able to rollback schema changes. - ** - ** If the SQLITE_DeferFKs flag is set, then this is not required, as - ** the statement transaction will not be rolled back even if FK - ** constraints are violated. - */ - if( (db->flags & SQLITE_DeferFKs)==0 ){ - sqlite3VdbeVerifyAbortable(v, OE_Abort); - sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY, - OE_Abort, 0, P4_STATIC, P5_ConstraintFK); - } - - if( iSkip ){ - sqlite3VdbeResolveLabel(v, iSkip); - } - } -} - - -/* -** The second argument points to an FKey object representing a foreign key -** for which pTab is the child table. An UPDATE statement against pTab -** is currently being processed. For each column of the table that is -** actually updated, the corresponding element in the aChange[] array -** is zero or greater (if a column is unmodified the corresponding element -** is set to -1). If the rowid column is modified by the UPDATE statement -** the bChngRowid argument is non-zero. -** -** This function returns true if any of the columns that are part of the -** child key for FK constraint *p are modified. -*/ -static int fkChildIsModified( - Table *pTab, /* Table being updated */ - FKey *p, /* Foreign key for which pTab is the child */ - int *aChange, /* Array indicating modified columns */ - int bChngRowid /* True if rowid is modified by this update */ -){ - int i; - for(i=0; inCol; i++){ - int iChildKey = p->aCol[i].iFrom; - if( aChange[iChildKey]>=0 ) return 1; - if( iChildKey==pTab->iPKey && bChngRowid ) return 1; - } - return 0; -} - -/* -** The second argument points to an FKey object representing a foreign key -** for which pTab is the parent table. An UPDATE statement against pTab -** is currently being processed. For each column of the table that is -** actually updated, the corresponding element in the aChange[] array -** is zero or greater (if a column is unmodified the corresponding element -** is set to -1). If the rowid column is modified by the UPDATE statement -** the bChngRowid argument is non-zero. -** -** This function returns true if any of the columns that are part of the -** parent key for FK constraint *p are modified. -*/ -static int fkParentIsModified( - Table *pTab, - FKey *p, - int *aChange, - int bChngRowid -){ - int i; - for(i=0; inCol; i++){ - char *zKey = p->aCol[i].zCol; - int iKey; - for(iKey=0; iKeynCol; iKey++){ - if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){ - Column *pCol = &pTab->aCol[iKey]; - if( zKey ){ - if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1; - }else if( pCol->colFlags & COLFLAG_PRIMKEY ){ - return 1; - } - } - } - } - return 0; -} - -/* -** Return true if the parser passed as the first argument is being -** used to code a trigger that is really a "SET NULL" action belonging -** to trigger pFKey. -*/ -static int isSetNullAction(Parse *pParse, FKey *pFKey){ - Parse *pTop = sqlite3ParseToplevel(pParse); - if( pTop->pTriggerPrg ){ - Trigger *p = pTop->pTriggerPrg->pTrigger; - if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull) - || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull) - ){ - return 1; - } - } - return 0; -} - -/* -** This function is called when inserting, deleting or updating a row of -** table pTab to generate VDBE code to perform foreign key constraint -** processing for the operation. -** -** For a DELETE operation, parameter regOld is passed the index of the -** first register in an array of (pTab->nCol+1) registers containing the -** rowid of the row being deleted, followed by each of the column values -** of the row being deleted, from left to right. Parameter regNew is passed -** zero in this case. -** -** For an INSERT operation, regOld is passed zero and regNew is passed the -** first register of an array of (pTab->nCol+1) registers containing the new -** row data. -** -** For an UPDATE operation, this function is called twice. Once before -** the original record is deleted from the table using the calling convention -** described for DELETE. Then again after the original record is deleted -** but before the new record is inserted using the INSERT convention. -*/ -SQLITE_PRIVATE void sqlite3FkCheck( - Parse *pParse, /* Parse context */ - Table *pTab, /* Row is being deleted from this table */ - int regOld, /* Previous row data is stored here */ - int regNew, /* New row data is stored here */ - int *aChange, /* Array indicating UPDATEd columns (or 0) */ - int bChngRowid /* True if rowid is UPDATEd */ -){ - sqlite3 *db = pParse->db; /* Database handle */ - FKey *pFKey; /* Used to iterate through FKs */ - int iDb; /* Index of database containing pTab */ - const char *zDb; /* Name of database containing pTab */ - int isIgnoreErrors = pParse->disableTriggers; - - /* Exactly one of regOld and regNew should be non-zero. */ - assert( (regOld==0)!=(regNew==0) ); - - /* If foreign-keys are disabled, this function is a no-op. */ - if( (db->flags&SQLITE_ForeignKeys)==0 ) return; - - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - zDb = db->aDb[iDb].zDbSName; - - /* Loop through all the foreign key constraints for which pTab is the - ** child table (the table that the foreign key definition is part of). */ - for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ - Table *pTo; /* Parent table of foreign key pFKey */ - Index *pIdx = 0; /* Index on key columns in pTo */ - int *aiFree = 0; - int *aiCol; - int iCol; - int i; - int bIgnore = 0; - - if( aChange - && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0 - && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 - ){ - continue; - } - - /* Find the parent table of this foreign key. Also find a unique index - ** on the parent key columns in the parent table. If either of these - ** schema items cannot be located, set an error in pParse and return - ** early. */ - if( pParse->disableTriggers ){ - pTo = sqlite3FindTable(db, pFKey->zTo, zDb); - }else{ - pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb); - } - if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){ - assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) ); - if( !isIgnoreErrors || db->mallocFailed ) return; - if( pTo==0 ){ - /* If isIgnoreErrors is true, then a table is being dropped. In this - ** case SQLite runs a "DELETE FROM xxx" on the table being dropped - ** before actually dropping it in order to check FK constraints. - ** If the parent table of an FK constraint on the current table is - ** missing, behave as if it is empty. i.e. decrement the relevant - ** FK counter for each row of the current table with non-NULL keys. - */ - Vdbe *v = sqlite3GetVdbe(pParse); - int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1; - for(i=0; inCol; i++){ - int iFromCol, iReg; - iFromCol = pFKey->aCol[i].iFrom; - iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1; - sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v); - } - sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1); - } - continue; - } - assert( pFKey->nCol==1 || (aiFree && pIdx) ); - - if( aiFree ){ - aiCol = aiFree; - }else{ - iCol = pFKey->aCol[0].iFrom; - aiCol = &iCol; - } - for(i=0; inCol; i++){ - if( aiCol[i]==pTab->iPKey ){ - aiCol[i] = -1; - } - assert( pIdx==0 || pIdx->aiColumn[i]>=0 ); -#ifndef SQLITE_OMIT_AUTHORIZATION - /* Request permission to read the parent key columns. If the - ** authorization callback returns SQLITE_IGNORE, behave as if any - ** values read from the parent table are NULL. */ - if( db->xAuth ){ - int rcauth; - char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName; - rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb); - bIgnore = (rcauth==SQLITE_IGNORE); - } -#endif - } - - /* Take a shared-cache advisory read-lock on the parent table. Allocate - ** a cursor to use to search the unique index on the parent key columns - ** in the parent table. */ - sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName); - pParse->nTab++; - - if( regOld!=0 ){ - /* A row is being removed from the child table. Search for the parent. - ** If the parent does not exist, removing the child row resolves an - ** outstanding foreign key constraint violation. */ - fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore); - } - if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){ - /* A row is being added to the child table. If a parent row cannot - ** be found, adding the child row has violated the FK constraint. - ** - ** If this operation is being performed as part of a trigger program - ** that is actually a "SET NULL" action belonging to this very - ** foreign key, then omit this scan altogether. As all child key - ** values are guaranteed to be NULL, it is not possible for adding - ** this row to cause an FK violation. */ - fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore); - } - - sqlite3DbFree(db, aiFree); - } - - /* Loop through all the foreign key constraints that refer to this table. - ** (the "child" constraints) */ - for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ - Index *pIdx = 0; /* Foreign key index for pFKey */ - SrcList *pSrc; - int *aiCol = 0; - - if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){ - continue; - } - - if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) - && !pParse->pToplevel && !pParse->isMultiWrite - ){ - assert( regOld==0 && regNew!=0 ); - /* Inserting a single row into a parent table cannot cause (or fix) - ** an immediate foreign key violation. So do nothing in this case. */ - continue; - } - - if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){ - if( !isIgnoreErrors || db->mallocFailed ) return; - continue; - } - assert( aiCol || pFKey->nCol==1 ); - - /* Create a SrcList structure containing the child table. We need the - ** child table as a SrcList for sqlite3WhereBegin() */ - pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); - if( pSrc ){ - struct SrcList_item *pItem = pSrc->a; - pItem->pTab = pFKey->pFrom; - pItem->zName = pFKey->pFrom->zName; - pItem->pTab->nTabRef++; - pItem->iCursor = pParse->nTab++; - - if( regNew!=0 ){ - fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1); - } - if( regOld!=0 ){ - int eAction = pFKey->aAction[aChange!=0]; - fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1); - /* If this is a deferred FK constraint, or a CASCADE or SET NULL - ** action applies, then any foreign key violations caused by - ** removing the parent key will be rectified by the action trigger. - ** So do not set the "may-abort" flag in this case. - ** - ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the - ** may-abort flag will eventually be set on this statement anyway - ** (when this function is called as part of processing the UPDATE - ** within the action trigger). - ** - ** Note 2: At first glance it may seem like SQLite could simply omit - ** all OP_FkCounter related scans when either CASCADE or SET NULL - ** applies. The trouble starts if the CASCADE or SET NULL action - ** trigger causes other triggers or action rules attached to the - ** child table to fire. In these cases the fk constraint counters - ** might be set incorrectly if any OP_FkCounter related scans are - ** omitted. */ - if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){ - sqlite3MayAbort(pParse); - } - } - pItem->zName = 0; - sqlite3SrcListDelete(db, pSrc); - } - sqlite3DbFree(db, aiCol); - } -} - -#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x))) - -/* -** This function is called before generating code to update or delete a -** row contained in table pTab. -*/ -SQLITE_PRIVATE u32 sqlite3FkOldmask( - Parse *pParse, /* Parse context */ - Table *pTab /* Table being modified */ -){ - u32 mask = 0; - if( pParse->db->flags&SQLITE_ForeignKeys ){ - FKey *p; - int i; - for(p=pTab->pFKey; p; p=p->pNextFrom){ - for(i=0; inCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom); - } - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ - Index *pIdx = 0; - sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0); - if( pIdx ){ - for(i=0; inKeyCol; i++){ - assert( pIdx->aiColumn[i]>=0 ); - mask |= COLUMN_MASK(pIdx->aiColumn[i]); - } - } - } - } - return mask; -} - - -/* -** This function is called before generating code to update or delete a -** row contained in table pTab. If the operation is a DELETE, then -** parameter aChange is passed a NULL value. For an UPDATE, aChange points -** to an array of size N, where N is the number of columns in table pTab. -** If the i'th column is not modified by the UPDATE, then the corresponding -** entry in the aChange[] array is set to -1. If the column is modified, -** the value is 0 or greater. Parameter chngRowid is set to true if the -** UPDATE statement modifies the rowid fields of the table. -** -** If any foreign key processing will be required, this function returns -** non-zero. If there is no foreign key related processing, this function -** returns zero. -** -** For an UPDATE, this function returns 2 if: -** -** * There are any FKs for which pTab is the child and the parent table, or -** * the UPDATE modifies one or more parent keys for which the action is -** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL). -** -** Or, assuming some other foreign key processing is required, 1. -*/ -SQLITE_PRIVATE int sqlite3FkRequired( - Parse *pParse, /* Parse context */ - Table *pTab, /* Table being modified */ - int *aChange, /* Non-NULL for UPDATE operations */ - int chngRowid /* True for UPDATE that affects rowid */ -){ - int eRet = 0; - if( pParse->db->flags&SQLITE_ForeignKeys ){ - if( !aChange ){ - /* A DELETE operation. Foreign key processing is required if the - ** table in question is either the child or parent table for any - ** foreign key constraint. */ - eRet = (sqlite3FkReferences(pTab) || pTab->pFKey); - }else{ - /* This is an UPDATE. Foreign key processing is only required if the - ** operation modifies one or more child or parent key columns. */ - FKey *p; - - /* Check if any child key columns are being modified. */ - for(p=pTab->pFKey; p; p=p->pNextFrom){ - if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2; - if( fkChildIsModified(pTab, p, aChange, chngRowid) ){ - eRet = 1; - } - } - - /* Check if any parent key columns are being modified. */ - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ - if( fkParentIsModified(pTab, p, aChange, chngRowid) ){ - if( p->aAction[1]!=OE_None ) return 2; - eRet = 1; - } - } - } - } - return eRet; -} - -/* -** This function is called when an UPDATE or DELETE operation is being -** compiled on table pTab, which is the parent table of foreign-key pFKey. -** If the current operation is an UPDATE, then the pChanges parameter is -** passed a pointer to the list of columns being modified. If it is a -** DELETE, pChanges is passed a NULL pointer. -** -** It returns a pointer to a Trigger structure containing a trigger -** equivalent to the ON UPDATE or ON DELETE action specified by pFKey. -** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is -** returned (these actions require no special handling by the triggers -** sub-system, code for them is created by fkScanChildren()). -** -** For example, if pFKey is the foreign key and pTab is table "p" in -** the following schema: -** -** CREATE TABLE p(pk PRIMARY KEY); -** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE); -** -** then the returned trigger structure is equivalent to: -** -** CREATE TRIGGER ... DELETE ON p BEGIN -** DELETE FROM c WHERE ck = old.pk; -** END; -** -** The returned pointer is cached as part of the foreign key object. It -** is eventually freed along with the rest of the foreign key object by -** sqlite3FkDelete(). -*/ -static Trigger *fkActionTrigger( - Parse *pParse, /* Parse context */ - Table *pTab, /* Table being updated or deleted from */ - FKey *pFKey, /* Foreign key to get action for */ - ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */ -){ - sqlite3 *db = pParse->db; /* Database handle */ - int action; /* One of OE_None, OE_Cascade etc. */ - Trigger *pTrigger; /* Trigger definition to return */ - int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */ - - action = pFKey->aAction[iAction]; - if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){ - return 0; - } - pTrigger = pFKey->apTrigger[iAction]; - - if( action!=OE_None && !pTrigger ){ - char const *zFrom; /* Name of child table */ - int nFrom; /* Length in bytes of zFrom */ - Index *pIdx = 0; /* Parent key index for this FK */ - int *aiCol = 0; /* child table cols -> parent key cols */ - TriggerStep *pStep = 0; /* First (only) step of trigger program */ - Expr *pWhere = 0; /* WHERE clause of trigger step */ - ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */ - Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */ - int i; /* Iterator variable */ - Expr *pWhen = 0; /* WHEN clause for the trigger */ - - if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0; - assert( aiCol || pFKey->nCol==1 ); - - for(i=0; inCol; i++){ - Token tOld = { "old", 3 }; /* Literal "old" token */ - Token tNew = { "new", 3 }; /* Literal "new" token */ - Token tFromCol; /* Name of column in child table */ - Token tToCol; /* Name of column in parent table */ - int iFromCol; /* Idx of column in child table */ - Expr *pEq; /* tFromCol = OLD.tToCol */ - - iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom; - assert( iFromCol>=0 ); - assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKeynCol) ); - assert( pIdx==0 || pIdx->aiColumn[i]>=0 ); - sqlite3TokenInit(&tToCol, - pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName); - sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName); - - /* Create the expression "OLD.zToCol = zFromCol". It is important - ** that the "OLD.zToCol" term is on the LHS of the = operator, so - ** that the affinity and collation sequence associated with the - ** parent table are used for the comparison. */ - pEq = sqlite3PExpr(pParse, TK_EQ, - sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tOld, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)), - sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0) - ); - pWhere = sqlite3ExprAnd(pParse, pWhere, pEq); - - /* For ON UPDATE, construct the next term of the WHEN clause. - ** The final WHEN clause will be like this: - ** - ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) - */ - if( pChanges ){ - pEq = sqlite3PExpr(pParse, TK_IS, - sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tOld, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)), - sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tNew, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)) - ); - pWhen = sqlite3ExprAnd(pParse, pWhen, pEq); - } - - if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){ - Expr *pNew; - if( action==OE_Cascade ){ - pNew = sqlite3PExpr(pParse, TK_DOT, - sqlite3ExprAlloc(db, TK_ID, &tNew, 0), - sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)); - }else if( action==OE_SetDflt ){ - Column *pCol = pFKey->pFrom->aCol + iFromCol; - Expr *pDflt; - if( pCol->colFlags & COLFLAG_GENERATED ){ - testcase( pCol->colFlags & COLFLAG_VIRTUAL ); - testcase( pCol->colFlags & COLFLAG_STORED ); - pDflt = 0; - }else{ - pDflt = pCol->pDflt; - } - if( pDflt ){ - pNew = sqlite3ExprDup(db, pDflt, 0); - }else{ - pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); - } - }else{ - pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0); - } - pList = sqlite3ExprListAppend(pParse, pList, pNew); - sqlite3ExprListSetName(pParse, pList, &tFromCol, 0); - } - } - sqlite3DbFree(db, aiCol); - - zFrom = pFKey->pFrom->zName; - nFrom = sqlite3Strlen30(zFrom); - - if( action==OE_Restrict ){ - Token tFrom; - Expr *pRaise; - - tFrom.z = zFrom; - tFrom.n = nFrom; - pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed"); - if( pRaise ){ - pRaise->affExpr = OE_Abort; - } - pSelect = sqlite3SelectNew(pParse, - sqlite3ExprListAppend(pParse, 0, pRaise), - sqlite3SrcListAppend(pParse, 0, &tFrom, 0), - pWhere, - 0, 0, 0, 0, 0 - ); - pWhere = 0; - } - - /* Disable lookaside memory allocation */ - DisableLookaside; - - pTrigger = (Trigger *)sqlite3DbMallocZero(db, - sizeof(Trigger) + /* struct Trigger */ - sizeof(TriggerStep) + /* Single step in trigger program */ - nFrom + 1 /* Space for pStep->zTarget */ - ); - if( pTrigger ){ - pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; - pStep->zTarget = (char *)&pStep[1]; - memcpy((char *)pStep->zTarget, zFrom, nFrom); - - pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); - pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); - pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); - if( pWhen ){ - pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0); - pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); - } - } - - /* Re-enable the lookaside buffer, if it was disabled earlier. */ - EnableLookaside; - - sqlite3ExprDelete(db, pWhere); - sqlite3ExprDelete(db, pWhen); - sqlite3ExprListDelete(db, pList); - sqlite3SelectDelete(db, pSelect); - if( db->mallocFailed==1 ){ - fkTriggerDelete(db, pTrigger); - return 0; - } - assert( pStep!=0 ); - assert( pTrigger!=0 ); - - switch( action ){ - case OE_Restrict: - pStep->op = TK_SELECT; - break; - case OE_Cascade: - if( !pChanges ){ - pStep->op = TK_DELETE; - break; - } - /* no break */ deliberate_fall_through - default: - pStep->op = TK_UPDATE; - } - pStep->pTrig = pTrigger; - pTrigger->pSchema = pTab->pSchema; - pTrigger->pTabSchema = pTab->pSchema; - pFKey->apTrigger[iAction] = pTrigger; - pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE); - } - - return pTrigger; -} - -/* -** This function is called when deleting or updating a row to implement -** any required CASCADE, SET NULL or SET DEFAULT actions. -*/ -SQLITE_PRIVATE void sqlite3FkActions( - Parse *pParse, /* Parse context */ - Table *pTab, /* Table being updated or deleted from */ - ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */ - int regOld, /* Address of array containing old row */ - int *aChange, /* Array indicating UPDATEd columns (or 0) */ - int bChngRowid /* True if rowid is UPDATEd */ -){ - /* If foreign-key support is enabled, iterate through all FKs that - ** refer to table pTab. If there is an action associated with the FK - ** for this operation (either update or delete), invoke the associated - ** trigger sub-program. */ - if( pParse->db->flags&SQLITE_ForeignKeys ){ - FKey *pFKey; /* Iterator variable */ - for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){ - if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){ - Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges); - if( pAct ){ - sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0); - } - } - } - } -} - -#endif /* ifndef SQLITE_OMIT_TRIGGER */ - -/* -** Free all memory associated with foreign key definitions attached to -** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash -** hash table. -*/ -SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){ - FKey *pFKey; /* Iterator variable */ - FKey *pNext; /* Copy of pFKey->pNextFrom */ - - assert( db==0 || IsVirtual(pTab) - || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) ); - for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){ - - /* Remove the FK from the fkeyHash hash table. */ - if( !db || db->pnBytesFreed==0 ){ - if( pFKey->pPrevTo ){ - pFKey->pPrevTo->pNextTo = pFKey->pNextTo; - }else{ - void *p = (void *)pFKey->pNextTo; - const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo); - sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p); - } - if( pFKey->pNextTo ){ - pFKey->pNextTo->pPrevTo = pFKey->pPrevTo; - } - } - - /* EV: R-30323-21917 Each foreign key constraint in SQLite is - ** classified as either immediate or deferred. - */ - assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 ); - - /* Delete any triggers created to implement actions for this FK. */ -#ifndef SQLITE_OMIT_TRIGGER - fkTriggerDelete(db, pFKey->apTrigger[0]); - fkTriggerDelete(db, pFKey->apTrigger[1]); -#endif - - pNext = pFKey->pNextFrom; - sqlite3DbFree(db, pFKey); - } -} -#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */ - -/************** End of fkey.c ************************************************/ -/************** Begin file insert.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 C code routines that are called by the parser -** to handle INSERT statements in SQLite. -*/ -/* #include "sqliteInt.h" */ - -/* -** Generate code that will -** -** (1) acquire a lock for table pTab then -** (2) open pTab as cursor iCur. -** -** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index -** for that table that is actually opened. -*/ -SQLITE_PRIVATE void sqlite3OpenTable( - Parse *pParse, /* Generate code into this VDBE */ - int iCur, /* The cursor number of the table */ - int iDb, /* The database index in sqlite3.aDb[] */ - Table *pTab, /* The table to be opened */ - int opcode /* OP_OpenRead or OP_OpenWrite */ -){ - Vdbe *v; - assert( !IsVirtual(pTab) ); - v = sqlite3GetVdbe(pParse); - assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); - sqlite3TableLock(pParse, iDb, pTab->tnum, - (opcode==OP_OpenWrite)?1:0, pTab->zName); - if( HasRowid(pTab) ){ - sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol); - VdbeComment((v, "%s", pTab->zName)); - }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - assert( pPk!=0 ); - assert( pPk->tnum==pTab->tnum ); - sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); - VdbeComment((v, "%s", pTab->zName)); - } -} - -/* -** Return a pointer to the column affinity string associated with index -** pIdx. A column affinity string has one character for each column in -** the table, according to the affinity of the column: -** -** Character Column affinity -** ------------------------------ -** 'A' BLOB -** 'B' TEXT -** 'C' NUMERIC -** 'D' INTEGER -** 'F' REAL -** -** An extra 'D' is appended to the end of the string to cover the -** rowid that appears as the last column in every index. -** -** Memory for the buffer containing the column index affinity string -** is managed along with the rest of the Index structure. It will be -** released when sqlite3DeleteIndex() is called. -*/ -SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){ - if( !pIdx->zColAff ){ - /* The first time a column affinity string for a particular index is - ** required, it is allocated and populated here. It is then stored as - ** a member of the Index structure for subsequent use. - ** - ** The column affinity string will eventually be deleted by - ** sqliteDeleteIndex() when the Index structure itself is cleaned - ** up. - */ - int n; - Table *pTab = pIdx->pTable; - pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1); - if( !pIdx->zColAff ){ - sqlite3OomFault(db); - return 0; - } - for(n=0; nnColumn; n++){ - i16 x = pIdx->aiColumn[n]; - char aff; - if( x>=0 ){ - aff = pTab->aCol[x].affinity; - }else if( x==XN_ROWID ){ - aff = SQLITE_AFF_INTEGER; - }else{ - assert( x==XN_EXPR ); - assert( pIdx->aColExpr!=0 ); - aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); - } - if( affSQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC; - pIdx->zColAff[n] = aff; - } - pIdx->zColAff[n] = 0; - } - - return pIdx->zColAff; -} - -/* -** Compute the affinity string for table pTab, if it has not already been -** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities. -** -** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and -** if iReg>0 then code an OP_Affinity opcode that will set the affinities -** for register iReg and following. Or if affinities exists and iReg==0, -** then just set the P4 operand of the previous opcode (which should be -** an OP_MakeRecord) to the affinity string. -** -** A column affinity string has one character per column: -** -** Character Column affinity -** ------------------------------ -** 'A' BLOB -** 'B' TEXT -** 'C' NUMERIC -** 'D' INTEGER -** 'E' REAL -*/ -SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ - int i, j; - char *zColAff = pTab->zColAff; - if( zColAff==0 ){ - sqlite3 *db = sqlite3VdbeDb(v); - zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1); - if( !zColAff ){ - sqlite3OomFault(db); - return; - } - - for(i=j=0; inCol; i++){ - assert( pTab->aCol[i].affinity!=0 ); - if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ - zColAff[j++] = pTab->aCol[i].affinity; - } - } - do{ - zColAff[j--] = 0; - }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB ); - pTab->zColAff = zColAff; - } - assert( zColAff!=0 ); - i = sqlite3Strlen30NN(zColAff); - if( i ){ - if( iReg ){ - sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i); - }else{ - sqlite3VdbeChangeP4(v, -1, zColAff, i); - } - } -} - -/* -** Return non-zero if the table pTab in database iDb or any of its indices -** have been opened at any point in the VDBE program. This is used to see if -** a statement of the form "INSERT INTO SELECT ..." can -** run without using a temporary table for the results of the SELECT. -*/ -static int readsTable(Parse *p, int iDb, Table *pTab){ - Vdbe *v = sqlite3GetVdbe(p); - int i; - int iEnd = sqlite3VdbeCurrentAddr(v); -#ifndef SQLITE_OMIT_VIRTUALTABLE - VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0; -#endif - - for(i=1; iopcode==OP_OpenRead && pOp->p3==iDb ){ - Index *pIndex; - Pgno tnum = pOp->p2; - if( tnum==pTab->tnum ){ - return 1; - } - for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ - if( tnum==pIndex->tnum ){ - return 1; - } - } - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){ - assert( pOp->p4.pVtab!=0 ); - assert( pOp->p4type==P4_VTAB ); - return 1; - } -#endif - } - return 0; -} - -/* This walker callback will compute the union of colFlags flags for all -** referenced columns in a CHECK constraint or generated column expression. -*/ -static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){ - assert( pExpr->iColumn < pWalker->u.pTab->nCol ); - pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags; - } - return WRC_Continue; -} - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS -/* -** All regular columns for table pTab have been puts into registers -** starting with iRegStore. The registers that correspond to STORED -** or VIRTUAL columns have not yet been initialized. This routine goes -** back and computes the values for those columns based on the previously -** computed normal columns. -*/ -SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns( - Parse *pParse, /* Parsing context */ - int iRegStore, /* Register holding the first column */ - Table *pTab /* The table */ -){ - int i; - Walker w; - Column *pRedo; - int eProgress; - VdbeOp *pOp; - - assert( pTab->tabFlags & TF_HasGenerated ); - testcase( pTab->tabFlags & TF_HasVirtual ); - testcase( pTab->tabFlags & TF_HasStored ); - - /* Before computing generated columns, first go through and make sure - ** that appropriate affinity has been applied to the regular columns - */ - sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore); - if( (pTab->tabFlags & TF_HasStored)!=0 - && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity - ){ - /* Change the OP_Affinity argument to '@' (NONE) for all stored - ** columns. '@' is the no-op affinity and those columns have not - ** yet been computed. */ - int ii, jj; - char *zP4 = pOp->p4.z; - assert( zP4!=0 ); - assert( pOp->p4type==P4_DYNAMIC ); - for(ii=jj=0; zP4[jj]; ii++){ - if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){ - continue; - } - if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){ - zP4[jj] = SQLITE_AFF_NONE; - } - jj++; - } - } - - /* Because there can be multiple generated columns that refer to one another, - ** this is a two-pass algorithm. On the first pass, mark all generated - ** columns as "not available". - */ - for(i=0; inCol; i++){ - if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ - testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); - testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); - pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL; - } - } - - w.u.pTab = pTab; - w.xExprCallback = exprColumnFlagUnion; - w.xSelectCallback = 0; - w.xSelectCallback2 = 0; - - /* On the second pass, compute the value of each NOT-AVAILABLE column. - ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will - ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as - ** they are needed. - */ - pParse->iSelfTab = -iRegStore; - do{ - eProgress = 0; - pRedo = 0; - for(i=0; inCol; i++){ - Column *pCol = pTab->aCol + i; - if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){ - int x; - pCol->colFlags |= COLFLAG_BUSY; - w.eCode = 0; - sqlite3WalkExpr(&w, pCol->pDflt); - pCol->colFlags &= ~COLFLAG_BUSY; - if( w.eCode & COLFLAG_NOTAVAIL ){ - pRedo = pCol; - continue; - } - eProgress = 1; - assert( pCol->colFlags & COLFLAG_GENERATED ); - x = sqlite3TableColumnToStorage(pTab, i) + iRegStore; - sqlite3ExprCodeGeneratedColumn(pParse, pCol, x); - pCol->colFlags &= ~COLFLAG_NOTAVAIL; - } - } - }while( pRedo && eProgress ); - if( pRedo ){ - sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName); - } - pParse->iSelfTab = 0; -} -#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ - - -#ifndef SQLITE_OMIT_AUTOINCREMENT -/* -** Locate or create an AutoincInfo structure associated with table pTab -** which is in database iDb. Return the register number for the register -** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT -** table. (Also return zero when doing a VACUUM since we do not want to -** update the AUTOINCREMENT counters during a VACUUM.) -** -** There is at most one AutoincInfo structure per table even if the -** same table is autoincremented multiple times due to inserts within -** triggers. A new AutoincInfo structure is created if this is the -** first use of table pTab. On 2nd and subsequent uses, the original -** AutoincInfo structure is used. -** -** Four consecutive registers are allocated: -** -** (1) The name of the pTab table. -** (2) The maximum ROWID of pTab. -** (3) The rowid in sqlite_sequence of pTab -** (4) The original value of the max ROWID in pTab, or NULL if none -** -** The 2nd register is the one that is returned. That is all the -** insert routine needs to know about. -*/ -static int autoIncBegin( - Parse *pParse, /* Parsing context */ - int iDb, /* Index of the database holding pTab */ - Table *pTab /* The table we are writing to */ -){ - int memId = 0; /* Register holding maximum rowid */ - assert( pParse->db->aDb[iDb].pSchema!=0 ); - if( (pTab->tabFlags & TF_Autoincrement)!=0 - && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 - ){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - AutoincInfo *pInfo; - Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab; - - /* Verify that the sqlite_sequence table exists and is an ordinary - ** rowid table with exactly two columns. - ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */ - if( pSeqTab==0 - || !HasRowid(pSeqTab) - || IsVirtual(pSeqTab) - || pSeqTab->nCol!=2 - ){ - pParse->nErr++; - pParse->rc = SQLITE_CORRUPT_SEQUENCE; - return 0; - } - - pInfo = pToplevel->pAinc; - while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } - if( pInfo==0 ){ - pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo)); - if( pInfo==0 ) return 0; - pInfo->pNext = pToplevel->pAinc; - pToplevel->pAinc = pInfo; - pInfo->pTab = pTab; - pInfo->iDb = iDb; - pToplevel->nMem++; /* Register to hold name of table */ - pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */ - pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */ - } - memId = pInfo->regCtr; - } - return memId; -} - -/* -** This routine generates code that will initialize all of the -** register used by the autoincrement tracker. -*/ -SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ - AutoincInfo *p; /* Information about an AUTOINCREMENT */ - sqlite3 *db = pParse->db; /* The database connection */ - Db *pDb; /* Database only autoinc table */ - int memId; /* Register holding max rowid */ - Vdbe *v = pParse->pVdbe; /* VDBE under construction */ - - /* This routine is never called during trigger-generation. It is - ** only called from the top-level */ - assert( pParse->pTriggerTab==0 ); - assert( sqlite3IsToplevel(pParse) ); - - assert( v ); /* We failed long ago if this is not so */ - for(p = pParse->pAinc; p; p = p->pNext){ - static const int iLn = VDBE_OFFSET_LINENO(2); - static const VdbeOpList autoInc[] = { - /* 0 */ {OP_Null, 0, 0, 0}, - /* 1 */ {OP_Rewind, 0, 10, 0}, - /* 2 */ {OP_Column, 0, 0, 0}, - /* 3 */ {OP_Ne, 0, 9, 0}, - /* 4 */ {OP_Rowid, 0, 0, 0}, - /* 5 */ {OP_Column, 0, 1, 0}, - /* 6 */ {OP_AddImm, 0, 0, 0}, - /* 7 */ {OP_Copy, 0, 0, 0}, - /* 8 */ {OP_Goto, 0, 11, 0}, - /* 9 */ {OP_Next, 0, 2, 0}, - /* 10 */ {OP_Integer, 0, 0, 0}, - /* 11 */ {OP_Close, 0, 0, 0} - }; - VdbeOp *aOp; - pDb = &db->aDb[p->iDb]; - memId = p->regCtr; - assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); - sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead); - sqlite3VdbeLoadString(v, memId-1, p->pTab->zName); - aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn); - if( aOp==0 ) break; - aOp[0].p2 = memId; - aOp[0].p3 = memId+2; - aOp[2].p3 = memId; - aOp[3].p1 = memId-1; - aOp[3].p3 = memId; - aOp[3].p5 = SQLITE_JUMPIFNULL; - aOp[4].p2 = memId+1; - aOp[5].p3 = memId; - aOp[6].p1 = memId; - aOp[7].p2 = memId+2; - aOp[7].p1 = memId; - aOp[10].p2 = memId; - if( pParse->nTab==0 ) pParse->nTab = 1; - } -} - -/* -** Update the maximum rowid for an autoincrement calculation. -** -** This routine should be called when the regRowid register holds a -** new rowid that is about to be inserted. If that new rowid is -** larger than the maximum rowid in the memId memory cell, then the -** memory cell is updated. -*/ -static void autoIncStep(Parse *pParse, int memId, int regRowid){ - if( memId>0 ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); - } -} - -/* -** This routine generates the code needed to write autoincrement -** maximum rowid values back into the sqlite_sequence register. -** Every statement that might do an INSERT into an autoincrement -** table (either directly or through triggers) needs to call this -** routine just before the "exit" code. -*/ -static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ - AutoincInfo *p; - Vdbe *v = pParse->pVdbe; - sqlite3 *db = pParse->db; - - assert( v ); - for(p = pParse->pAinc; p; p = p->pNext){ - static const int iLn = VDBE_OFFSET_LINENO(2); - static const VdbeOpList autoIncEnd[] = { - /* 0 */ {OP_NotNull, 0, 2, 0}, - /* 1 */ {OP_NewRowid, 0, 0, 0}, - /* 2 */ {OP_MakeRecord, 0, 2, 0}, - /* 3 */ {OP_Insert, 0, 0, 0}, - /* 4 */ {OP_Close, 0, 0, 0} - }; - VdbeOp *aOp; - Db *pDb = &db->aDb[p->iDb]; - int iRec; - int memId = p->regCtr; - - iRec = sqlite3GetTempReg(pParse); - assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) ); - sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId); - VdbeCoverage(v); - sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); - aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn); - if( aOp==0 ) break; - aOp[0].p1 = memId+1; - aOp[1].p2 = memId+1; - aOp[2].p1 = memId-1; - aOp[2].p3 = iRec; - aOp[3].p2 = iRec; - aOp[3].p3 = memId+1; - aOp[3].p5 = OPFLAG_APPEND; - sqlite3ReleaseTempReg(pParse, iRec); - } -} -SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){ - if( pParse->pAinc ) autoIncrementEnd(pParse); -} -#else -/* -** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines -** above are all no-ops -*/ -# define autoIncBegin(A,B,C) (0) -# define autoIncStep(A,B,C) -#endif /* SQLITE_OMIT_AUTOINCREMENT */ - - -/* Forward declaration */ -static int xferOptimization( - Parse *pParse, /* Parser context */ - Table *pDest, /* The table we are inserting into */ - Select *pSelect, /* A SELECT statement to use as the data source */ - int onError, /* How to handle constraint errors */ - int iDbDest /* The database of pDest */ -); - -/* -** This routine is called to handle SQL of the following forms: -** -** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),... -** insert into TABLE (IDLIST) select -** insert into TABLE (IDLIST) default values -** -** The IDLIST following the table name is always optional. If omitted, -** then a list of all (non-hidden) columns for the table is substituted. -** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST -** is omitted. -** -** For the pSelect parameter holds the values to be inserted for the -** first two forms shown above. A VALUES clause is really just short-hand -** for a SELECT statement that omits the FROM clause and everything else -** that follows. If the pSelect parameter is NULL, that means that the -** DEFAULT VALUES form of the INSERT statement is intended. -** -** The code generated follows one of four templates. For a simple -** insert with data coming from a single-row VALUES clause, the code executes -** once straight down through. Pseudo-code follows (we call this -** the "1st template"): -** -** open write cursor to
    and its indices -** put VALUES clause expressions into registers -** write the resulting record into
    -** cleanup -** -** The three remaining templates assume the statement is of the form -** -** INSERT INTO
    SELECT ... -** -** If the SELECT clause is of the restricted form "SELECT * FROM " - -** in other words if the SELECT pulls all columns from a single table -** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and -** if and are distinct tables but have identical -** schemas, including all the same indices, then a special optimization -** is invoked that copies raw records from over to . -** See the xferOptimization() function for the implementation of this -** template. This is the 2nd template. -** -** open a write cursor to
    -** open read cursor on -** transfer all records in over to
    -** close cursors -** foreach index on
    -** open a write cursor on the
    index -** open a read cursor on the corresponding index -** transfer all records from the read to the write cursors -** close cursors -** end foreach -** -** The 3rd template is for when the second template does not apply -** and the SELECT clause does not read from
    at any time. -** The generated code follows this template: -** -** X <- A -** goto B -** A: setup for the SELECT -** loop over the rows in the SELECT -** load values into registers R..R+n -** yield X -** end loop -** cleanup after the SELECT -** end-coroutine X -** B: open write cursor to
    and its indices -** C: yield X, at EOF goto D -** insert the select result into
    from R..R+n -** goto C -** D: cleanup -** -** The 4th template is used if the insert statement takes its -** values from a SELECT but the data is being inserted into a table -** that is also read as part of the SELECT. In the third form, -** we have to use an intermediate table to store the results of -** the select. The template is like this: -** -** X <- A -** goto B -** A: setup for the SELECT -** loop over the tables in the SELECT -** load value into register R..R+n -** yield X -** end loop -** cleanup after the SELECT -** end co-routine R -** B: open temp table -** L: yield X, at EOF goto M -** insert row from R..R+n into temp table -** goto L -** M: open write cursor to
    and its indices -** rewind temp table -** C: loop over rows of intermediate table -** transfer values form intermediate table into
    -** end loop -** D: cleanup -*/ -SQLITE_PRIVATE void sqlite3Insert( - Parse *pParse, /* Parser context */ - SrcList *pTabList, /* Name of table into which we are inserting */ - Select *pSelect, /* A SELECT statement to use as the data source */ - IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */ - int onError, /* How to handle constraint errors */ - Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */ -){ - sqlite3 *db; /* The main database structure */ - Table *pTab; /* The table to insert into. aka TABLE */ - int i, j; /* Loop counters */ - Vdbe *v; /* Generate code into this virtual machine */ - Index *pIdx; /* For looping over indices of the table */ - int nColumn; /* Number of columns in the data */ - int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ - int iDataCur = 0; /* VDBE cursor that is the main data repository */ - int iIdxCur = 0; /* First index cursor */ - int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ - int endOfLoop; /* Label for the end of the insertion loop */ - int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ - int addrInsTop = 0; /* Jump to label "D" */ - int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ - SelectDest dest; /* Destination for SELECT on rhs of INSERT */ - int iDb; /* Index of database holding TABLE */ - u8 useTempTable = 0; /* Store SELECT results in intermediate table */ - u8 appendFlag = 0; /* True if the insert is likely to be an append */ - u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */ - u8 bIdListInOrder; /* True if IDLIST is in table order */ - ExprList *pList = 0; /* List of VALUES() to be inserted */ - int iRegStore; /* Register in which to store next column */ - - /* Register allocations */ - int regFromSelect = 0;/* Base register for data coming from SELECT */ - int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ - int regRowCount = 0; /* Memory cell used for the row counter */ - int regIns; /* Block of regs holding rowid+data being inserted */ - int regRowid; /* registers holding insert rowid */ - int regData; /* register holding first column to insert */ - int *aRegIdx = 0; /* One register allocated to each index */ - -#ifndef SQLITE_OMIT_TRIGGER - int isView; /* True if attempting to insert into a view */ - Trigger *pTrigger; /* List of triggers on pTab, if required */ - int tmask; /* Mask of trigger times */ -#endif - - db = pParse->db; - if( pParse->nErr || db->mallocFailed ){ - goto insert_cleanup; - } - dest.iSDParm = 0; /* Suppress a harmless compiler warning */ - - /* If the Select object is really just a simple VALUES() list with a - ** single row (the common case) then keep that one row of values - ** and discard the other (unused) parts of the pSelect object - */ - if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){ - pList = pSelect->pEList; - pSelect->pEList = 0; - sqlite3SelectDelete(db, pSelect); - pSelect = 0; - } - - /* Locate the table into which we will be inserting new information. - */ - assert( pTabList->nSrc==1 ); - pTab = sqlite3SrcListLookup(pParse, pTabList); - if( pTab==0 ){ - goto insert_cleanup; - } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - assert( iDbnDb ); - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, - db->aDb[iDb].zDbSName) ){ - goto insert_cleanup; - } - withoutRowid = !HasRowid(pTab); - - /* Figure out if we have any triggers and if the table being - ** inserted into is a view - */ -#ifndef SQLITE_OMIT_TRIGGER - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask); - isView = pTab->pSelect!=0; -#else -# define pTrigger 0 -# define tmask 0 -# define isView 0 -#endif -#ifdef SQLITE_OMIT_VIEW -# undef isView -# define isView 0 -#endif - assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) ); - - /* If pTab is really a view, make sure it has been initialized. - ** ViewGetColumnNames() is a no-op if pTab is not a view. - */ - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ - goto insert_cleanup; - } - - /* Cannot insert into a read-only table. - */ - if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ - goto insert_cleanup; - } - - /* Allocate a VDBE - */ - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto insert_cleanup; - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); - sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb); - -#ifndef SQLITE_OMIT_XFER_OPT - /* If the statement is of the form - ** - ** INSERT INTO SELECT * FROM ; - ** - ** Then special optimizations can be applied that make the transfer - ** very fast and which reduce fragmentation of indices. - ** - ** This is the 2nd template. - */ - if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ - assert( !pTrigger ); - assert( pList==0 ); - goto insert_end; - } -#endif /* SQLITE_OMIT_XFER_OPT */ - - /* If this is an AUTOINCREMENT table, look up the sequence number in the - ** sqlite_sequence table and store it in memory cell regAutoinc. - */ - regAutoinc = autoIncBegin(pParse, iDb, pTab); - - /* Allocate a block registers to hold the rowid and the values - ** for all columns of the new row. - */ - regRowid = regIns = pParse->nMem+1; - pParse->nMem += pTab->nCol + 1; - if( IsVirtual(pTab) ){ - regRowid++; - pParse->nMem++; - } - regData = regRowid+1; - - /* If the INSERT statement included an IDLIST term, then make sure - ** all elements of the IDLIST really are columns of the table and - ** remember the column indices. - ** - ** If the table has an INTEGER PRIMARY KEY column and that column - ** is named in the IDLIST, then record in the ipkColumn variable - ** the index into IDLIST of the primary key column. ipkColumn is - ** the index of the primary key as it appears in IDLIST, not as - ** is appears in the original table. (The index of the INTEGER - ** PRIMARY KEY in the original table is pTab->iPKey.) After this - ** loop, if ipkColumn==(-1), that means that integer primary key - ** is unspecified, and hence the table is either WITHOUT ROWID or - ** it will automatically generated an integer primary key. - ** - ** bIdListInOrder is true if the columns in IDLIST are in storage - ** order. This enables an optimization that avoids shuffling the - ** columns into storage order. False negatives are harmless, - ** but false positives will cause database corruption. - */ - bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0; - if( pColumn ){ - for(i=0; inId; i++){ - pColumn->a[i].idx = -1; - } - for(i=0; inId; i++){ - for(j=0; jnCol; j++){ - if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){ - pColumn->a[i].idx = j; - if( i!=j ) bIdListInOrder = 0; - if( j==pTab->iPKey ){ - ipkColumn = i; assert( !withoutRowid ); - } -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ - sqlite3ErrorMsg(pParse, - "cannot INSERT into generated column \"%s\"", - pTab->aCol[j].zName); - goto insert_cleanup; - } -#endif - break; - } - } - if( j>=pTab->nCol ){ - if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ - ipkColumn = i; - bIdListInOrder = 0; - }else{ - sqlite3ErrorMsg(pParse, "table %S has no column named %s", - pTabList, 0, pColumn->a[i].zName); - pParse->checkSchema = 1; - goto insert_cleanup; - } - } - } - } - - /* Figure out how many columns of data are supplied. If the data - ** is coming from a SELECT statement, then generate a co-routine that - ** produces a single row of the SELECT on each invocation. The - ** co-routine is the common header to the 3rd and 4th templates. - */ - if( pSelect ){ - /* Data is coming from a SELECT or from a multi-row VALUES clause. - ** Generate a co-routine to run the SELECT. */ - int regYield; /* Register holding co-routine entry-point */ - int addrTop; /* Top of the co-routine */ - int rc; /* Result code */ - - regYield = ++pParse->nMem; - addrTop = sqlite3VdbeCurrentAddr(v) + 1; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); - sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); - dest.iSdst = bIdListInOrder ? regData : 0; - dest.nSdst = pTab->nCol; - rc = sqlite3Select(pParse, pSelect, &dest); - regFromSelect = dest.iSdst; - if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup; - sqlite3VdbeEndCoroutine(v, regYield); - sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */ - assert( pSelect->pEList ); - nColumn = pSelect->pEList->nExpr; - - /* Set useTempTable to TRUE if the result of the SELECT statement - ** should be written into a temporary table (template 4). Set to - ** FALSE if each output row of the SELECT can be written directly into - ** the destination table (template 3). - ** - ** A temp table must be used if the table being updated is also one - ** of the tables being read by the SELECT statement. Also use a - ** temp table in the case of row triggers. - */ - if( pTrigger || readsTable(pParse, iDb, pTab) ){ - useTempTable = 1; - } - - if( useTempTable ){ - /* Invoke the coroutine to extract information from the SELECT - ** and add it to a transient table srcTab. The code generated - ** here is from the 4th template: - ** - ** B: open temp table - ** L: yield X, goto M at EOF - ** insert row from R..R+n into temp table - ** goto L - ** M: ... - */ - int regRec; /* Register to hold packed record */ - int regTempRowid; /* Register to hold temp table ROWID */ - int addrL; /* Label "L" */ - - srcTab = pParse->nTab++; - regRec = sqlite3GetTempReg(pParse); - regTempRowid = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); - addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); - sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid); - sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid); - sqlite3VdbeGoto(v, addrL); - sqlite3VdbeJumpHere(v, addrL); - sqlite3ReleaseTempReg(pParse, regRec); - sqlite3ReleaseTempReg(pParse, regTempRowid); - } - }else{ - /* This is the case if the data for the INSERT is coming from a - ** single-row VALUES clause - */ - NameContext sNC; - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - srcTab = -1; - assert( useTempTable==0 ); - if( pList ){ - nColumn = pList->nExpr; - if( sqlite3ResolveExprListNames(&sNC, pList) ){ - goto insert_cleanup; - } - }else{ - nColumn = 0; - } - } - - /* If there is no IDLIST term but the table has an integer primary - ** key, the set the ipkColumn variable to the integer primary key - ** column index in the original table definition. - */ - if( pColumn==0 && nColumn>0 ){ - ipkColumn = pTab->iPKey; -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){ - testcase( pTab->tabFlags & TF_HasVirtual ); - testcase( pTab->tabFlags & TF_HasStored ); - for(i=ipkColumn-1; i>=0; i--){ - if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ - testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ); - testcase( pTab->aCol[i].colFlags & COLFLAG_STORED ); - ipkColumn--; - } - } - } -#endif - } - - /* Make sure the number of columns in the source data matches the number - ** of columns to be inserted into the table. - */ - for(i=0; inCol; i++){ - if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++; - } - if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){ - sqlite3ErrorMsg(pParse, - "table %S has %d columns but %d values were supplied", - pTabList, 0, pTab->nCol-nHidden, nColumn); - goto insert_cleanup; - } - if( pColumn!=0 && nColumn!=pColumn->nId ){ - sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId); - goto insert_cleanup; - } - - /* Initialize the count of rows to be inserted - */ - if( (db->flags & SQLITE_CountRows)!=0 - && !pParse->nested - && !pParse->pTriggerTab - ){ - regRowCount = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); - } - - /* If this is not a view, open the table and and all indices */ - if( !isView ){ - int nIdx; - nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0, - &iDataCur, &iIdxCur); - aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2)); - if( aRegIdx==0 ){ - goto insert_cleanup; - } - for(i=0, pIdx=pTab->pIndex; ipNext, i++){ - assert( pIdx ); - aRegIdx[i] = ++pParse->nMem; - pParse->nMem += pIdx->nColumn; - } - aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */ - } -#ifndef SQLITE_OMIT_UPSERT - if( pUpsert ){ - if( IsVirtual(pTab) ){ - sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"", - pTab->zName); - goto insert_cleanup; - } - if( pTab->pSelect ){ - sqlite3ErrorMsg(pParse, "cannot UPSERT a view"); - goto insert_cleanup; - } - if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){ - goto insert_cleanup; - } - pTabList->a[0].iCursor = iDataCur; - pUpsert->pUpsertSrc = pTabList; - pUpsert->regData = regData; - pUpsert->iDataCur = iDataCur; - pUpsert->iIdxCur = iIdxCur; - if( pUpsert->pUpsertTarget ){ - sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert); - } - } -#endif - - - /* This is the top of the main insertion loop */ - if( useTempTable ){ - /* This block codes the top of loop only. The complete loop is the - ** following pseudocode (template 4): - ** - ** rewind temp table, if empty goto D - ** C: loop over rows of intermediate table - ** transfer values form intermediate table into
    - ** end loop - ** D: ... - */ - addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v); - addrCont = sqlite3VdbeCurrentAddr(v); - }else if( pSelect ){ - /* This block codes the top of loop only. The complete loop is the - ** following pseudocode (template 3): - ** - ** C: yield X, at EOF goto D - ** insert the select result into
    from R..R+n - ** goto C - ** D: ... - */ - sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0); - addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); - VdbeCoverage(v); - if( ipkColumn>=0 ){ - /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the - ** SELECT, go ahead and copy the value into the rowid slot now, so that - ** the value does not get overwritten by a NULL at tag-20191021-002. */ - sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); - } - } - - /* Compute data for ordinary columns of the new entry. Values - ** are written in storage order into registers starting with regData. - ** Only ordinary columns are computed in this loop. The rowid - ** (if there is one) is computed later and generated columns are - ** computed after the rowid since they might depend on the value - ** of the rowid. - */ - nHidden = 0; - iRegStore = regData; assert( regData==regRowid+1 ); - for(i=0; inCol; i++, iRegStore++){ - int k; - u32 colFlags; - assert( i>=nHidden ); - if( i==pTab->iPKey ){ - /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled - ** using the rowid. So put a NULL in the IPK slot of the record to avoid - ** using excess space. The file format definition requires this extra - ** NULL - we cannot optimize further by skipping the column completely */ - sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); - continue; - } - if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){ - nHidden++; - if( (colFlags & COLFLAG_VIRTUAL)!=0 ){ - /* Virtual columns do not participate in OP_MakeRecord. So back up - ** iRegStore by one slot to compensate for the iRegStore++ in the - ** outer for() loop */ - iRegStore--; - continue; - }else if( (colFlags & COLFLAG_STORED)!=0 ){ - /* Stored columns are computed later. But if there are BEFORE - ** triggers, the slots used for stored columns will be OP_Copy-ed - ** to a second block of registers, so the register needs to be - ** initialized to NULL to avoid an uninitialized register read */ - if( tmask & TRIGGER_BEFORE ){ - sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); - } - continue; - }else if( pColumn==0 ){ - /* Hidden columns that are not explicitly named in the INSERT - ** get there default value */ - sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); - continue; - } - } - if( pColumn ){ - for(j=0; jnId && pColumn->a[j].idx!=i; j++){} - if( j>=pColumn->nId ){ - /* A column not named in the insert column list gets its - ** default value */ - sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); - continue; - } - k = j; - }else if( nColumn==0 ){ - /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */ - sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); - continue; - }else{ - k = i - nHidden; - } - - if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore); - }else if( pSelect ){ - if( regFromSelect!=regData ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore); - } - }else{ - sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore); - } - } - - - /* Run the BEFORE and INSTEAD OF triggers, if there are any - */ - endOfLoop = sqlite3VdbeMakeLabel(pParse); - if( tmask & TRIGGER_BEFORE ){ - int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1); - - /* build the NEW.* reference row. Note that if there is an INTEGER - ** PRIMARY KEY into which a NULL is being inserted, that NULL will be - ** translated into a unique ID for the row. But on a BEFORE trigger, - ** we do not know what the unique ID will be (because the insert has - ** not happened yet) so we substitute a rowid of -1 - */ - if( ipkColumn<0 ){ - sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); - }else{ - int addr1; - assert( !withoutRowid ); - if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols); - }else{ - assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols); - } - addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); - } - - /* Cannot have triggers on a virtual table. If it were possible, - ** this block would have to account for hidden column. - */ - assert( !IsVirtual(pTab) ); - - /* Copy the new data already generated. */ - assert( pTab->nNVCol>0 ); - sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1); - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - /* Compute the new value for generated columns after all other - ** columns have already been computed. This must be done after - ** computing the ROWID in case one of the generated columns - ** refers to the ROWID. */ - if( pTab->tabFlags & TF_HasGenerated ){ - testcase( pTab->tabFlags & TF_HasVirtual ); - testcase( pTab->tabFlags & TF_HasStored ); - sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab); - } -#endif - - /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, - ** do not attempt any conversions before assembling the record. - ** If this is a real table, attempt conversions as required by the - ** table column affinities. - */ - if( !isView ){ - sqlite3TableAffinity(v, pTab, regCols+1); - } - - /* Fire BEFORE or INSTEAD OF triggers */ - sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, - pTab, regCols-pTab->nCol-1, onError, endOfLoop); - - sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1); - } - - if( !isView ){ - if( IsVirtual(pTab) ){ - /* The row that the VUpdate opcode will delete: none */ - sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); - } - if( ipkColumn>=0 ){ - /* Compute the new rowid */ - if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); - }else if( pSelect ){ - /* Rowid already initialized at tag-20191021-001 */ - }else{ - Expr *pIpk = pList->a[ipkColumn].pExpr; - if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){ - sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); - appendFlag = 1; - }else{ - sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); - } - } - /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid - ** to generate a unique primary key value. - */ - if( !appendFlag ){ - int addr1; - if( !IsVirtual(pTab) ){ - addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); - sqlite3VdbeJumpHere(v, addr1); - }else{ - addr1 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); - } - sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); - } - }else if( IsVirtual(pTab) || withoutRowid ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); - }else{ - sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc); - appendFlag = 1; - } - autoIncStep(pParse, regAutoinc, regRowid); - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - /* Compute the new value for generated columns after all other - ** columns have already been computed. This must be done after - ** computing the ROWID in case one of the generated columns - ** is derived from the INTEGER PRIMARY KEY. */ - if( pTab->tabFlags & TF_HasGenerated ){ - sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab); - } -#endif - - /* Generate code to check constraints and generate index keys and - ** do the insertion. - */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pTab) ){ - const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); - sqlite3VtabMakeWritable(pParse, pTab); - sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB); - sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError); - sqlite3MayAbort(pParse); - }else -#endif - { - int isReplace; /* Set to true if constraints may cause a replace */ - int bUseSeek; /* True to use OPFLAG_SEEKRESULT */ - sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, - regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert - ); - sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0); - - /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE - ** constraints or (b) there are no triggers and this table is not a - ** parent table in a foreign key constraint. It is safe to set the - ** flag in the second case as if any REPLACE constraint is hit, an - ** OP_Delete or OP_IdxDelete instruction will be executed on each - ** cursor that is disturbed. And these instructions both clear the - ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT - ** functionality. */ - bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v)); - sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, - regIns, aRegIdx, 0, appendFlag, bUseSeek - ); - } - } - - /* Update the count of rows that are inserted - */ - if( regRowCount ){ - sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); - } - - if( pTrigger ){ - /* Code AFTER triggers */ - sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, - pTab, regData-2-pTab->nCol, onError, endOfLoop); - } - - /* The bottom of the main insertion loop, if the data source - ** is a SELECT statement. - */ - sqlite3VdbeResolveLabel(v, endOfLoop); - if( useTempTable ){ - sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addrInsTop); - sqlite3VdbeAddOp1(v, OP_Close, srcTab); - }else if( pSelect ){ - sqlite3VdbeGoto(v, addrCont); -#ifdef SQLITE_DEBUG - /* If we are jumping back to an OP_Yield that is preceded by an - ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the - ** OP_ReleaseReg will be included in the loop. */ - if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){ - assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield ); - sqlite3VdbeChangeP5(v, 1); - } -#endif - sqlite3VdbeJumpHere(v, addrInsTop); - } - -insert_end: - /* Update the sqlite_sequence table by storing the content of the - ** maximum rowid counter values recorded while inserting into - ** autoincrement tables. - */ - if( pParse->nested==0 && pParse->pTriggerTab==0 ){ - sqlite3AutoincrementEnd(pParse); - } - - /* - ** Return the number of rows inserted. If this routine is - ** generating code because of a call to sqlite3NestedParse(), do not - ** invoke the callback function. - */ - if( regRowCount ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC); - } - -insert_cleanup: - sqlite3SrcListDelete(db, pTabList); - sqlite3ExprListDelete(db, pList); - sqlite3UpsertDelete(db, pUpsert); - sqlite3SelectDelete(db, pSelect); - sqlite3IdListDelete(db, pColumn); - sqlite3DbFree(db, aRegIdx); -} - -/* Make sure "isView" and other macros defined above are undefined. Otherwise -** they may interfere with compilation of other functions in this file -** (or in another file, if this file becomes part of the amalgamation). */ -#ifdef isView - #undef isView -#endif -#ifdef pTrigger - #undef pTrigger -#endif -#ifdef tmask - #undef tmask -#endif - -/* -** Meanings of bits in of pWalker->eCode for -** sqlite3ExprReferencesUpdatedColumn() -*/ -#define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */ -#define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */ - -/* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn(). -* Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this -** expression node references any of the -** columns that are being modifed by an UPDATE statement. -*/ -static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_COLUMN ){ - assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 ); - if( pExpr->iColumn>=0 ){ - if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){ - pWalker->eCode |= CKCNSTRNT_COLUMN; - } - }else{ - pWalker->eCode |= CKCNSTRNT_ROWID; - } - } - return WRC_Continue; -} - -/* -** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The -** only columns that are modified by the UPDATE are those for which -** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true. -** -** Return true if CHECK constraint pExpr uses any of the -** changing columns (or the rowid if it is changing). In other words, -** return true if this CHECK constraint must be validated for -** the new row in the UPDATE statement. -** -** 2018-09-15: pExpr might also be an expression for an index-on-expressions. -** The operation of this routine is the same - return true if an only if -** the expression uses one or more of columns identified by the second and -** third arguments. -*/ -SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn( - Expr *pExpr, /* The expression to be checked */ - int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */ - int chngRowid /* True if UPDATE changes the rowid */ -){ - Walker w; - memset(&w, 0, sizeof(w)); - w.eCode = 0; - w.xExprCallback = checkConstraintExprNode; - w.u.aiCol = aiChng; - sqlite3WalkExpr(&w, pExpr); - if( !chngRowid ){ - testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 ); - w.eCode &= ~CKCNSTRNT_ROWID; - } - testcase( w.eCode==0 ); - testcase( w.eCode==CKCNSTRNT_COLUMN ); - testcase( w.eCode==CKCNSTRNT_ROWID ); - testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) ); - return w.eCode!=0; -} - -/* -** Generate code to do constraint checks prior to an INSERT or an UPDATE -** on table pTab. -** -** The regNewData parameter is the first register in a range that contains -** the data to be inserted or the data after the update. There will be -** pTab->nCol+1 registers in this range. The first register (the one -** that regNewData points to) will contain the new rowid, or NULL in the -** case of a WITHOUT ROWID table. The second register in the range will -** contain the content of the first table column. The third register will -** contain the content of the second table column. And so forth. -** -** The regOldData parameter is similar to regNewData except that it contains -** the data prior to an UPDATE rather than afterwards. regOldData is zero -** for an INSERT. This routine can distinguish between UPDATE and INSERT by -** checking regOldData for zero. -** -** For an UPDATE, the pkChng boolean is true if the true primary key (the -** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table) -** might be modified by the UPDATE. If pkChng is false, then the key of -** the iDataCur content table is guaranteed to be unchanged by the UPDATE. -** -** For an INSERT, the pkChng boolean indicates whether or not the rowid -** was explicitly specified as part of the INSERT statement. If pkChng -** is zero, it means that the either rowid is computed automatically or -** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT, -** pkChng will only be true if the INSERT statement provides an integer -** value for either the rowid column or its INTEGER PRIMARY KEY alias. -** -** The code generated by this routine will store new index entries into -** registers identified by aRegIdx[]. No index entry is created for -** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is -** the same as the order of indices on the linked list of indices -** at pTab->pIndex. -** -** (2019-05-07) The generated code also creates a new record for the -** main table, if pTab is a rowid table, and stores that record in the -** register identified by aRegIdx[nIdx] - in other words in the first -** entry of aRegIdx[] past the last index. It is important that the -** record be generated during constraint checks to avoid affinity changes -** to the register content that occur after constraint checks but before -** the new record is inserted. -** -** The caller must have already opened writeable cursors on the main -** table and all applicable indices (that is to say, all indices for which -** aRegIdx[] is not zero). iDataCur is the cursor for the main table when -** inserting or updating a rowid table, or the cursor for the PRIMARY KEY -** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor -** for the first index in the pTab->pIndex list. Cursors for other indices -** are at iIdxCur+N for the N-th element of the pTab->pIndex list. -** -** This routine also generates code to check constraints. NOT NULL, -** CHECK, and UNIQUE constraints are all checked. If a constraint fails, -** then the appropriate action is performed. There are five possible -** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. -** -** Constraint type Action What Happens -** --------------- ---------- ---------------------------------------- -** any ROLLBACK The current transaction is rolled back and -** sqlite3_step() returns immediately with a -** return code of SQLITE_CONSTRAINT. -** -** any ABORT Back out changes from the current command -** only (do not do a complete rollback) then -** cause sqlite3_step() to return immediately -** with SQLITE_CONSTRAINT. -** -** any FAIL Sqlite3_step() returns immediately with a -** return code of SQLITE_CONSTRAINT. The -** transaction is not rolled back and any -** changes to prior rows are retained. -** -** any IGNORE The attempt in insert or update the current -** row is skipped, without throwing an error. -** Processing continues with the next row. -** (There is an immediate jump to ignoreDest.) -** -** NOT NULL REPLACE The NULL value is replace by the default -** value for that column. If the default value -** is NULL, the action is the same as ABORT. -** -** UNIQUE REPLACE The other row that conflicts with the row -** being inserted is removed. -** -** CHECK REPLACE Illegal. The results in an exception. -** -** Which action to take is determined by the overrideError parameter. -** Or if overrideError==OE_Default, then the pParse->onError parameter -** is used. Or if pParse->onError==OE_Default then the onError value -** for the constraint is used. -*/ -SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( - Parse *pParse, /* The parser context */ - Table *pTab, /* The table being inserted or updated */ - int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */ - int iDataCur, /* Canonical data cursor (main table or PK index) */ - int iIdxCur, /* First index cursor */ - int regNewData, /* First register in a range holding values to insert */ - int regOldData, /* Previous content. 0 for INSERTs */ - u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */ - u8 overrideError, /* Override onError to this if not OE_Default */ - int ignoreDest, /* Jump to this label on an OE_Ignore resolution */ - int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */ - int *aiChng, /* column i is unchanged if aiChng[i]<0 */ - Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */ -){ - Vdbe *v; /* VDBE under constrution */ - Index *pIdx; /* Pointer to one of the indices */ - Index *pPk = 0; /* The PRIMARY KEY index */ - sqlite3 *db; /* Database connection */ - int i; /* loop counter */ - int ix; /* Index loop counter */ - int nCol; /* Number of columns */ - int onError; /* Conflict resolution strategy */ - int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */ - int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */ - Index *pUpIdx = 0; /* Index to which to apply the upsert */ - u8 isUpdate; /* True if this is an UPDATE operation */ - u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ - int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */ - int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */ - int ipkTop = 0; /* Top of the IPK uniqueness check */ - int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */ - /* Variables associated with retesting uniqueness constraints after - ** replace triggers fire have run */ - int regTrigCnt; /* Register used to count replace trigger invocations */ - int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */ - int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */ - Trigger *pTrigger; /* List of DELETE triggers on the table pTab */ - int nReplaceTrig = 0; /* Number of replace triggers coded */ - - isUpdate = regOldData!=0; - db = pParse->db; - v = sqlite3GetVdbe(pParse); - assert( v!=0 ); - assert( pTab->pSelect==0 ); /* This table is not a VIEW */ - nCol = pTab->nCol; - - /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for - ** normal rowid tables. nPkField is the number of key fields in the - ** pPk index or 1 for a rowid table. In other words, nPkField is the - ** number of fields in the true primary key of the table. */ - if( HasRowid(pTab) ){ - pPk = 0; - nPkField = 1; - }else{ - pPk = sqlite3PrimaryKeyIndex(pTab); - nPkField = pPk->nKeyCol; - } - - /* Record that this module has started */ - VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)", - iDataCur, iIdxCur, regNewData, regOldData, pkChng)); - - /* Test all NOT NULL constraints. - */ - if( pTab->tabFlags & TF_HasNotNull ){ - int b2ndPass = 0; /* True if currently running 2nd pass */ - int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */ - int nGenerated = 0; /* Number of generated columns with NOT NULL */ - while(1){ /* Make 2 passes over columns. Exit loop via "break" */ - for(i=0; iaCol[i]; /* The column to check for NOT NULL */ - int isGenerated; /* non-zero if column is generated */ - onError = pCol->notNull; - if( onError==OE_None ) continue; /* No NOT NULL on this column */ - if( i==pTab->iPKey ){ - continue; /* ROWID is never NULL */ - } - isGenerated = pCol->colFlags & COLFLAG_GENERATED; - if( isGenerated && !b2ndPass ){ - nGenerated++; - continue; /* Generated columns processed on 2nd pass */ - } - if( aiChng && aiChng[i]<0 && !isGenerated ){ - /* Do not check NOT NULL on columns that do not change */ - continue; - } - if( overrideError!=OE_Default ){ - onError = overrideError; - }else if( onError==OE_Default ){ - onError = OE_Abort; - } - if( onError==OE_Replace ){ - if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */ - || pCol->pDflt==0 /* REPLACE is ABORT if no DEFAULT value */ - ){ - testcase( pCol->colFlags & COLFLAG_VIRTUAL ); - testcase( pCol->colFlags & COLFLAG_STORED ); - testcase( pCol->colFlags & COLFLAG_GENERATED ); - onError = OE_Abort; - }else{ - assert( !isGenerated ); - } - }else if( b2ndPass && !isGenerated ){ - continue; - } - assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail - || onError==OE_Ignore || onError==OE_Replace ); - testcase( i!=sqlite3TableColumnToStorage(pTab, i) ); - iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1; - switch( onError ){ - case OE_Replace: { - int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg); - VdbeCoverage(v); - assert( (pCol->colFlags & COLFLAG_GENERATED)==0 ); - nSeenReplace++; - sqlite3ExprCodeCopy(pParse, pCol->pDflt, iReg); - sqlite3VdbeJumpHere(v, addr1); - break; - } - case OE_Abort: - sqlite3MayAbort(pParse); - /* no break */ deliberate_fall_through - case OE_Rollback: - case OE_Fail: { - char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, - pCol->zName); - sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, - onError, iReg); - sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); - sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); - VdbeCoverage(v); - break; - } - default: { - assert( onError==OE_Ignore ); - sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest); - VdbeCoverage(v); - break; - } - } /* end switch(onError) */ - } /* end loop i over columns */ - if( nGenerated==0 && nSeenReplace==0 ){ - /* If there are no generated columns with NOT NULL constraints - ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single - ** pass is sufficient */ - break; - } - if( b2ndPass ) break; /* Never need more than 2 passes */ - b2ndPass = 1; -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){ - /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the - ** first pass, recomputed values for all generated columns, as - ** those values might depend on columns affected by the REPLACE. - */ - sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab); - } -#endif - } /* end of 2-pass loop */ - } /* end if( has-not-null-constraints ) */ - - /* Test all CHECK constraints - */ -#ifndef SQLITE_OMIT_CHECK - if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ - ExprList *pCheck = pTab->pCheck; - pParse->iSelfTab = -(regNewData+1); - onError = overrideError!=OE_Default ? overrideError : OE_Abort; - for(i=0; inExpr; i++){ - int allOk; - Expr *pCopy; - Expr *pExpr = pCheck->a[i].pExpr; - if( aiChng - && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng) - ){ - /* The check constraints do not reference any of the columns being - ** updated so there is no point it verifying the check constraint */ - continue; - } - if( bAffinityDone==0 ){ - sqlite3TableAffinity(v, pTab, regNewData+1); - bAffinityDone = 1; - } - allOk = sqlite3VdbeMakeLabel(pParse); - sqlite3VdbeVerifyAbortable(v, onError); - pCopy = sqlite3ExprDup(db, pExpr, 0); - if( !db->mallocFailed ){ - sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL); - } - sqlite3ExprDelete(db, pCopy); - if( onError==OE_Ignore ){ - sqlite3VdbeGoto(v, ignoreDest); - }else{ - char *zName = pCheck->a[i].zEName; - if( zName==0 ) zName = pTab->zName; - if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */ - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, - onError, zName, P4_TRANSIENT, - P5_ConstraintCheck); - } - sqlite3VdbeResolveLabel(v, allOk); - } - pParse->iSelfTab = 0; - } -#endif /* !defined(SQLITE_OMIT_CHECK) */ - - /* UNIQUE and PRIMARY KEY constraints should be handled in the following - ** order: - ** - ** (1) OE_Update - ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore - ** (3) OE_Replace - ** - ** OE_Fail and OE_Ignore must happen before any changes are made. - ** OE_Update guarantees that only a single row will change, so it - ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback - ** could happen in any order, but they are grouped up front for - ** convenience. - ** - ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43 - ** The order of constraints used to have OE_Update as (2) and OE_Abort - ** and so forth as (1). But apparently PostgreSQL checks the OE_Update - ** constraint before any others, so it had to be moved. - ** - ** Constraint checking code is generated in this order: - ** (A) The rowid constraint - ** (B) Unique index constraints that do not have OE_Replace as their - ** default conflict resolution strategy - ** (C) Unique index that do use OE_Replace by default. - ** - ** The ordering of (2) and (3) is accomplished by making sure the linked - ** list of indexes attached to a table puts all OE_Replace indexes last - ** in the list. See sqlite3CreateIndex() for where that happens. - */ - - if( pUpsert ){ - if( pUpsert->pUpsertTarget==0 ){ - /* An ON CONFLICT DO NOTHING clause, without a constraint-target. - ** Make all unique constraint resolution be OE_Ignore */ - assert( pUpsert->pUpsertSet==0 ); - overrideError = OE_Ignore; - pUpsert = 0; - }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){ - /* If the constraint-target uniqueness check must be run first. - ** Jump to that uniqueness check now */ - upsertJump = sqlite3VdbeAddOp0(v, OP_Goto); - VdbeComment((v, "UPSERT constraint goes first")); - } - } - - /* Determine if it is possible that triggers (either explicitly coded - ** triggers or FK resolution actions) might run as a result of deletes - ** that happen when OE_Replace conflict resolution occurs. (Call these - ** "replace triggers".) If any replace triggers run, we will need to - ** recheck all of the uniqueness constraints after they have all run. - ** But on the recheck, the resolution is OE_Abort instead of OE_Replace. - ** - ** If replace triggers are a possibility, then - ** - ** (1) Allocate register regTrigCnt and initialize it to zero. - ** That register will count the number of replace triggers that - ** fire. Constraint recheck only occurs if the number is positive. - ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab. - ** (3) Initialize addrRecheck and lblRecheckOk - ** - ** The uniqueness rechecking code will create a series of tests to run - ** in a second pass. The addrRecheck and lblRecheckOk variables are - ** used to link together these tests which are separated from each other - ** in the generate bytecode. - */ - if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){ - /* There are not DELETE triggers nor FK constraints. No constraint - ** rechecks are needed. */ - pTrigger = 0; - regTrigCnt = 0; - }else{ - if( db->flags&SQLITE_RecTriggers ){ - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); - regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0); - }else{ - pTrigger = 0; - regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0); - } - if( regTrigCnt ){ - /* Replace triggers might exist. Allocate the counter and - ** initialize it to zero. */ - regTrigCnt = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt); - VdbeComment((v, "trigger count")); - lblRecheckOk = sqlite3VdbeMakeLabel(pParse); - addrRecheck = lblRecheckOk; - } - } - - /* If rowid is changing, make sure the new rowid does not previously - ** exist in the table. - */ - if( pkChng && pPk==0 ){ - int addrRowidOk = sqlite3VdbeMakeLabel(pParse); - - /* Figure out what action to take in case of a rowid collision */ - onError = pTab->keyConf; - if( overrideError!=OE_Default ){ - onError = overrideError; - }else if( onError==OE_Default ){ - onError = OE_Abort; - } - - /* figure out whether or not upsert applies in this case */ - if( pUpsert && pUpsert->pUpsertIdx==0 ){ - if( pUpsert->pUpsertSet==0 ){ - onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ - }else{ - onError = OE_Update; /* DO UPDATE */ - } - } - - /* If the response to a rowid conflict is REPLACE but the response - ** to some other UNIQUE constraint is FAIL or IGNORE, then we need - ** to defer the running of the rowid conflict checking until after - ** the UNIQUE constraints have run. - */ - if( onError==OE_Replace /* IPK rule is REPLACE */ - && onError!=overrideError /* Rules for other contraints are different */ - && pTab->pIndex /* There exist other constraints */ - ){ - ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1; - VdbeComment((v, "defer IPK REPLACE until last")); - } - - if( isUpdate ){ - /* pkChng!=0 does not mean that the rowid has changed, only that - ** it might have changed. Skip the conflict logic below if the rowid - ** is unchanged. */ - sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - VdbeCoverage(v); - } - - /* Check to see if the new rowid already exists in the table. Skip - ** the following conflict logic if it does not. */ - VdbeNoopComment((v, "uniqueness check for ROWID")); - sqlite3VdbeVerifyAbortable(v, onError); - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); - VdbeCoverage(v); - - switch( onError ){ - default: { - onError = OE_Abort; - /* no break */ deliberate_fall_through - } - case OE_Rollback: - case OE_Abort: - case OE_Fail: { - testcase( onError==OE_Rollback ); - testcase( onError==OE_Abort ); - testcase( onError==OE_Fail ); - sqlite3RowidConstraint(pParse, onError, pTab); - break; - } - case OE_Replace: { - /* If there are DELETE triggers on this table and the - ** recursive-triggers flag is set, call GenerateRowDelete() to - ** remove the conflicting row from the table. This will fire - ** the triggers and remove both the table and index b-tree entries. - ** - ** Otherwise, if there are no triggers or the recursive-triggers - ** flag is not set, but the table has one or more indexes, call - ** GenerateRowIndexDelete(). This removes the index b-tree entries - ** only. The table b-tree entry will be replaced by the new entry - ** when it is inserted. - ** - ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called, - ** also invoke MultiWrite() to indicate that this VDBE may require - ** statement rollback (if the statement is aborted after the delete - ** takes place). Earlier versions called sqlite3MultiWrite() regardless, - ** but being more selective here allows statements like: - ** - ** REPLACE INTO t(rowid) VALUES($newrowid) - ** - ** to run without a statement journal if there are no indexes on the - ** table. - */ - if( regTrigCnt ){ - sqlite3MultiWrite(pParse); - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, - regNewData, 1, 0, OE_Replace, 1, -1); - sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ - nReplaceTrig++; - }else{ -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - assert( HasRowid(pTab) ); - /* This OP_Delete opcode fires the pre-update-hook only. It does - ** not modify the b-tree. It is more efficient to let the coming - ** OP_Insert replace the existing entry than it is to delete the - ** existing entry and then insert a new one. */ - sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP); - sqlite3VdbeAppendP4(v, pTab, P4_TABLE); -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - if( pTab->pIndex ){ - sqlite3MultiWrite(pParse); - sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1); - } - } - seenReplace = 1; - break; - } -#ifndef SQLITE_OMIT_UPSERT - case OE_Update: { - sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur); - /* no break */ deliberate_fall_through - } -#endif - case OE_Ignore: { - testcase( onError==OE_Ignore ); - sqlite3VdbeGoto(v, ignoreDest); - break; - } - } - sqlite3VdbeResolveLabel(v, addrRowidOk); - if( ipkTop ){ - ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, ipkTop-1); - } - } - - /* Test all UNIQUE constraints by creating entries for each UNIQUE - ** index and making sure that duplicate entries do not already exist. - ** Compute the revised record entries for indices as we go. - ** - ** This loop also handles the case of the PRIMARY KEY index for a - ** WITHOUT ROWID table. - */ - for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){ - int regIdx; /* Range of registers hold conent for pIdx */ - int regR; /* Range of registers holding conflicting PK */ - int iThisCur; /* Cursor for this UNIQUE index */ - int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ - int addrConflictCk; /* First opcode in the conflict check logic */ - - if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ - if( pUpIdx==pIdx ){ - addrUniqueOk = upsertJump+1; - upsertBypass = sqlite3VdbeGoto(v, 0); - VdbeComment((v, "Skip upsert subroutine")); - sqlite3VdbeJumpHere(v, upsertJump); - }else{ - addrUniqueOk = sqlite3VdbeMakeLabel(pParse); - } - if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){ - sqlite3TableAffinity(v, pTab, regNewData+1); - bAffinityDone = 1; - } - VdbeNoopComment((v, "prep index %s", pIdx->zName)); - iThisCur = iIdxCur+ix; - - - /* Skip partial indices for which the WHERE clause is not true */ - if( pIdx->pPartIdxWhere ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]); - pParse->iSelfTab = -(regNewData+1); - sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk, - SQLITE_JUMPIFNULL); - pParse->iSelfTab = 0; - } - - /* Create a record for this index entry as it should appear after - ** the insert or update. Store that record in the aRegIdx[ix] register - */ - regIdx = aRegIdx[ix]+1; - for(i=0; inColumn; i++){ - int iField = pIdx->aiColumn[i]; - int x; - if( iField==XN_EXPR ){ - pParse->iSelfTab = -(regNewData+1); - sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i); - pParse->iSelfTab = 0; - VdbeComment((v, "%s column %d", pIdx->zName, i)); - }else if( iField==XN_ROWID || iField==pTab->iPKey ){ - x = regNewData; - sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i); - VdbeComment((v, "rowid")); - }else{ - testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField ); - x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1; - sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i); - VdbeComment((v, "%s", pTab->aCol[iField].zName)); - } - } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]); - VdbeComment((v, "for %s", pIdx->zName)); -#ifdef SQLITE_ENABLE_NULL_TRIM - if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ - sqlite3SetMakeRecordP5(v, pIdx->pTable); - } -#endif - sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0); - - /* In an UPDATE operation, if this index is the PRIMARY KEY index - ** of a WITHOUT ROWID table and there has been no change the - ** primary key, then no collision is possible. The collision detection - ** logic below can all be skipped. */ - if( isUpdate && pPk==pIdx && pkChng==0 ){ - sqlite3VdbeResolveLabel(v, addrUniqueOk); - continue; - } - - /* Find out what action to take in case there is a uniqueness conflict */ - onError = pIdx->onError; - if( onError==OE_None ){ - sqlite3VdbeResolveLabel(v, addrUniqueOk); - continue; /* pIdx is not a UNIQUE index */ - } - if( overrideError!=OE_Default ){ - onError = overrideError; - }else if( onError==OE_Default ){ - onError = OE_Abort; - } - - /* Figure out if the upsert clause applies to this index */ - if( pUpIdx==pIdx ){ - if( pUpsert->pUpsertSet==0 ){ - onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */ - }else{ - onError = OE_Update; /* DO UPDATE */ - } - } - - /* Collision detection may be omitted if all of the following are true: - ** (1) The conflict resolution algorithm is REPLACE - ** (2) The table is a WITHOUT ROWID table - ** (3) There are no secondary indexes on the table - ** (4) No delete triggers need to be fired if there is a conflict - ** (5) No FK constraint counters need to be updated if a conflict occurs. - ** - ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row - ** must be explicitly deleted in order to ensure any pre-update hook - ** is invoked. */ -#ifndef SQLITE_ENABLE_PREUPDATE_HOOK - if( (ix==0 && pIdx->pNext==0) /* Condition 3 */ - && pPk==pIdx /* Condition 2 */ - && onError==OE_Replace /* Condition 1 */ - && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */ - 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0)) - && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */ - (0==pTab->pFKey && 0==sqlite3FkReferences(pTab))) - ){ - sqlite3VdbeResolveLabel(v, addrUniqueOk); - continue; - } -#endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */ - - /* Check to see if the new index entry will be unique */ - sqlite3VdbeVerifyAbortable(v, onError); - addrConflictCk = - sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk, - regIdx, pIdx->nKeyCol); VdbeCoverage(v); - - /* Generate code to handle collisions */ - regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField); - if( isUpdate || onError==OE_Replace ){ - if( HasRowid(pTab) ){ - sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR); - /* Conflict only if the rowid of the existing index entry - ** is different from old-rowid */ - if( isUpdate ){ - sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - VdbeCoverage(v); - } - }else{ - int x; - /* Extract the PRIMARY KEY from the end of the index entry and - ** store it in registers regR..regR+nPk-1 */ - if( pIdx!=pPk ){ - for(i=0; inKeyCol; i++){ - assert( pPk->aiColumn[i]>=0 ); - x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]); - sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i); - VdbeComment((v, "%s.%s", pTab->zName, - pTab->aCol[pPk->aiColumn[i]].zName)); - } - } - if( isUpdate ){ - /* If currently processing the PRIMARY KEY of a WITHOUT ROWID - ** table, only conflict if the new PRIMARY KEY values are actually - ** different from the old. - ** - ** For a UNIQUE index, only conflict if the PRIMARY KEY values - ** of the matched index row are different from the original PRIMARY - ** KEY values of this row before the update. */ - int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol; - int op = OP_Ne; - int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR); - - for(i=0; inKeyCol; i++){ - char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]); - x = pPk->aiColumn[i]; - assert( x>=0 ); - if( i==(pPk->nKeyCol-1) ){ - addrJump = addrUniqueOk; - op = OP_Eq; - } - x = sqlite3TableColumnToStorage(pTab, x); - sqlite3VdbeAddOp4(v, op, - regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ - ); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - VdbeCoverageIf(v, op==OP_Eq); - VdbeCoverageIf(v, op==OP_Ne); - } - } - } - } - - /* Generate code that executes if the new index entry is not unique */ - assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail - || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update ); - switch( onError ){ - case OE_Rollback: - case OE_Abort: - case OE_Fail: { - testcase( onError==OE_Rollback ); - testcase( onError==OE_Abort ); - testcase( onError==OE_Fail ); - sqlite3UniqueConstraint(pParse, onError, pIdx); - break; - } -#ifndef SQLITE_OMIT_UPSERT - case OE_Update: { - sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix); - /* no break */ deliberate_fall_through - } -#endif - case OE_Ignore: { - testcase( onError==OE_Ignore ); - sqlite3VdbeGoto(v, ignoreDest); - break; - } - default: { - int nConflictCk; /* Number of opcodes in conflict check logic */ - - assert( onError==OE_Replace ); - nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk; - assert( nConflictCk>0 ); - testcase( nConflictCk>1 ); - if( regTrigCnt ){ - sqlite3MultiWrite(pParse); - nReplaceTrig++; - } - if( pTrigger && isUpdate ){ - sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur); - } - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, - regR, nPkField, 0, OE_Replace, - (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); - if( pTrigger && isUpdate ){ - sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur); - } - if( regTrigCnt ){ - int addrBypass; /* Jump destination to bypass recheck logic */ - - sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ - addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */ - VdbeComment((v, "bypass recheck")); - - /* Here we insert code that will be invoked after all constraint - ** checks have run, if and only if one or more replace triggers - ** fired. */ - sqlite3VdbeResolveLabel(v, lblRecheckOk); - lblRecheckOk = sqlite3VdbeMakeLabel(pParse); - if( pIdx->pPartIdxWhere ){ - /* Bypass the recheck if this partial index is not defined - ** for the current row */ - sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk); - VdbeCoverage(v); - } - /* Copy the constraint check code from above, except change - ** the constraint-ok jump destination to be the address of - ** the next retest block */ - while( nConflictCk>0 ){ - VdbeOp x; /* Conflict check opcode to copy */ - /* The sqlite3VdbeAddOp4() call might reallocate the opcode array. - ** Hence, make a complete copy of the opcode, rather than using - ** a pointer to the opcode. */ - x = *sqlite3VdbeGetOp(v, addrConflictCk); - if( x.opcode!=OP_IdxRowid ){ - int p2; /* New P2 value for copied conflict check opcode */ - const char *zP4; - if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){ - p2 = lblRecheckOk; - }else{ - p2 = x.p2; - } - zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z; - sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type); - sqlite3VdbeChangeP5(v, x.p5); - VdbeCoverageIf(v, p2!=x.p2); - } - nConflictCk--; - addrConflictCk++; - } - /* If the retest fails, issue an abort */ - sqlite3UniqueConstraint(pParse, OE_Abort, pIdx); - - sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */ - } - seenReplace = 1; - break; - } - } - if( pUpIdx==pIdx ){ - sqlite3VdbeGoto(v, upsertJump+1); - sqlite3VdbeJumpHere(v, upsertBypass); - }else{ - sqlite3VdbeResolveLabel(v, addrUniqueOk); - } - if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); - } - - /* If the IPK constraint is a REPLACE, run it last */ - if( ipkTop ){ - sqlite3VdbeGoto(v, ipkTop); - VdbeComment((v, "Do IPK REPLACE")); - sqlite3VdbeJumpHere(v, ipkBottom); - } - - /* Recheck all uniqueness constraints after replace triggers have run */ - testcase( regTrigCnt!=0 && nReplaceTrig==0 ); - assert( regTrigCnt!=0 || nReplaceTrig==0 ); - if( nReplaceTrig ){ - sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v); - if( !pPk ){ - if( isUpdate ){ - sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - VdbeCoverage(v); - } - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData); - VdbeCoverage(v); - sqlite3RowidConstraint(pParse, OE_Abort, pTab); - }else{ - sqlite3VdbeGoto(v, addrRecheck); - } - sqlite3VdbeResolveLabel(v, lblRecheckOk); - } - - /* Generate the table record */ - if( HasRowid(pTab) ){ - int regRec = aRegIdx[ix]; - sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec); - sqlite3SetMakeRecordP5(v, pTab); - if( !bAffinityDone ){ - sqlite3TableAffinity(v, pTab, 0); - } - } - - *pbMayReplace = seenReplace; - VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace)); -} - -#ifdef SQLITE_ENABLE_NULL_TRIM -/* -** Change the P5 operand on the last opcode (which should be an OP_MakeRecord) -** to be the number of columns in table pTab that must not be NULL-trimmed. -** -** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero. -*/ -SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){ - u16 i; - - /* Records with omitted columns are only allowed for schema format - ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */ - if( pTab->pSchema->file_format<2 ) return; - - for(i=pTab->nCol-1; i>0; i--){ - if( pTab->aCol[i].pDflt!=0 ) break; - if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break; - } - sqlite3VdbeChangeP5(v, i+1); -} -#endif - -/* -** This routine generates code to finish the INSERT or UPDATE operation -** that was started by a prior call to sqlite3GenerateConstraintChecks. -** A consecutive range of registers starting at regNewData contains the -** rowid and the content to be inserted. -** -** The arguments to this routine should be the same as the first six -** arguments to sqlite3GenerateConstraintChecks. -*/ -SQLITE_PRIVATE void sqlite3CompleteInsertion( - Parse *pParse, /* The parser context */ - Table *pTab, /* the table into which we are inserting */ - int iDataCur, /* Cursor of the canonical data source */ - int iIdxCur, /* First index cursor */ - int regNewData, /* Range of content */ - int *aRegIdx, /* Register used by each index. 0 for unused indices */ - int update_flags, /* True for UPDATE, False for INSERT */ - int appendBias, /* True if this is likely to be an append */ - int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */ -){ - Vdbe *v; /* Prepared statements under construction */ - Index *pIdx; /* An index being inserted or updated */ - u8 pik_flags; /* flag values passed to the btree insert */ - int i; /* Loop counter */ - - assert( update_flags==0 - || update_flags==OPFLAG_ISUPDATE - || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION) - ); - - v = sqlite3GetVdbe(pParse); - assert( v!=0 ); - assert( pTab->pSelect==0 ); /* This table is not a VIEW */ - for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ - /* All REPLACE indexes are at the end of the list */ - assert( pIdx->onError!=OE_Replace - || pIdx->pNext==0 - || pIdx->pNext->onError==OE_Replace ); - if( aRegIdx[i]==0 ) continue; - if( pIdx->pPartIdxWhere ){ - sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - } - pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0); - if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ - assert( pParse->nested==0 ); - pik_flags |= OPFLAG_NCHANGE; - pik_flags |= (update_flags & OPFLAG_SAVEPOSITION); -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - if( update_flags==0 ){ - int r = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_Integer, 0, r); - sqlite3VdbeAddOp4(v, OP_Insert, - iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE - ); - sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); - sqlite3ReleaseTempReg(pParse, r); - } -#endif - } - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i], - aRegIdx[i]+1, - pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn); - sqlite3VdbeChangeP5(v, pik_flags); - } - if( !HasRowid(pTab) ) return; - if( pParse->nested ){ - pik_flags = 0; - }else{ - pik_flags = OPFLAG_NCHANGE; - pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID); - } - if( appendBias ){ - pik_flags |= OPFLAG_APPEND; - } - if( useSeekResult ){ - pik_flags |= OPFLAG_USESEEKRESULT; - } - sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData); - if( !pParse->nested ){ - sqlite3VdbeAppendP4(v, pTab, P4_TABLE); - } - sqlite3VdbeChangeP5(v, pik_flags); -} - -/* -** Allocate cursors for the pTab table and all its indices and generate -** code to open and initialized those cursors. -** -** The cursor for the object that contains the complete data (normally -** the table itself, but the PRIMARY KEY index in the case of a WITHOUT -** ROWID table) is returned in *piDataCur. The first index cursor is -** returned in *piIdxCur. The number of indices is returned. -** -** Use iBase as the first cursor (either the *piDataCur for rowid tables -** or the first index for WITHOUT ROWID tables) if it is non-negative. -** If iBase is negative, then allocate the next available cursor. -** -** For a rowid table, *piDataCur will be exactly one less than *piIdxCur. -** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range -** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the -** pTab->pIndex list. -** -** If pTab is a virtual table, then this routine is a no-op and the -** *piDataCur and *piIdxCur values are left uninitialized. -*/ -SQLITE_PRIVATE int sqlite3OpenTableAndIndices( - Parse *pParse, /* Parsing context */ - Table *pTab, /* Table to be opened */ - int op, /* OP_OpenRead or OP_OpenWrite */ - u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */ - int iBase, /* Use this for the table cursor, if there is one */ - u8 *aToOpen, /* If not NULL: boolean for each table and index */ - int *piDataCur, /* Write the database source cursor number here */ - int *piIdxCur /* Write the first index cursor number here */ -){ - int i; - int iDb; - int iDataCur; - Index *pIdx; - Vdbe *v; - - assert( op==OP_OpenRead || op==OP_OpenWrite ); - assert( op==OP_OpenWrite || p5==0 ); - if( IsVirtual(pTab) ){ - /* This routine is a no-op for virtual tables. Leave the output - ** variables *piDataCur and *piIdxCur uninitialized so that valgrind - ** can detect if they are used by mistake in the caller. */ - return 0; - } - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - v = sqlite3GetVdbe(pParse); - assert( v!=0 ); - if( iBase<0 ) iBase = pParse->nTab; - iDataCur = iBase++; - if( piDataCur ) *piDataCur = iDataCur; - if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){ - sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op); - }else{ - sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName); - } - if( piIdxCur ) *piIdxCur = iBase; - for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ - int iIdxCur = iBase++; - assert( pIdx->pSchema==pTab->pSchema ); - if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){ - if( piDataCur ) *piDataCur = iIdxCur; - p5 = 0; - } - if( aToOpen==0 || aToOpen[i+1] ){ - sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); - sqlite3VdbeChangeP5(v, p5); - VdbeComment((v, "%s", pIdx->zName)); - } - } - if( iBase>pParse->nTab ) pParse->nTab = iBase; - return i; -} - - -#ifdef SQLITE_TEST -/* -** The following global variable is incremented whenever the -** transfer optimization is used. This is used for testing -** purposes only - to make sure the transfer optimization really -** is happening when it is supposed to. -*/ -SQLITE_API int sqlite3_xferopt_count; -#endif /* SQLITE_TEST */ - - -#ifndef SQLITE_OMIT_XFER_OPT -/* -** Check to see if index pSrc is compatible as a source of data -** for index pDest in an insert transfer optimization. The rules -** for a compatible index: -** -** * The index is over the same set of columns -** * The same DESC and ASC markings occurs on all columns -** * The same onError processing (OE_Abort, OE_Ignore, etc) -** * The same collating sequence on each column -** * The index has the exact same WHERE clause -*/ -static int xferCompatibleIndex(Index *pDest, Index *pSrc){ - int i; - assert( pDest && pSrc ); - assert( pDest->pTable!=pSrc->pTable ); - if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){ - return 0; /* Different number of columns */ - } - if( pDest->onError!=pSrc->onError ){ - return 0; /* Different conflict resolution strategies */ - } - for(i=0; inKeyCol; i++){ - if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){ - return 0; /* Different columns indexed */ - } - if( pSrc->aiColumn[i]==XN_EXPR ){ - assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 ); - if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr, - pDest->aColExpr->a[i].pExpr, -1)!=0 ){ - return 0; /* Different expressions in the index */ - } - } - if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ - return 0; /* Different sort orders */ - } - if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){ - return 0; /* Different collating sequences */ - } - } - if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){ - return 0; /* Different WHERE clauses */ - } - - /* If no test above fails then the indices must be compatible */ - return 1; -} - -/* -** Attempt the transfer optimization on INSERTs of the form -** -** INSERT INTO tab1 SELECT * FROM tab2; -** -** The xfer optimization transfers raw records from tab2 over to tab1. -** Columns are not decoded and reassembled, which greatly improves -** performance. Raw index records are transferred in the same way. -** -** The xfer optimization is only attempted if tab1 and tab2 are compatible. -** There are lots of rules for determining compatibility - see comments -** embedded in the code for details. -** -** This routine returns TRUE if the optimization is guaranteed to be used. -** Sometimes the xfer optimization will only work if the destination table -** is empty - a factor that can only be determined at run-time. In that -** case, this routine generates code for the xfer optimization but also -** does a test to see if the destination table is empty and jumps over the -** xfer optimization code if the test fails. In that case, this routine -** returns FALSE so that the caller will know to go ahead and generate -** an unoptimized transfer. This routine also returns FALSE if there -** is no chance that the xfer optimization can be applied. -** -** This optimization is particularly useful at making VACUUM run faster. -*/ -static int xferOptimization( - Parse *pParse, /* Parser context */ - Table *pDest, /* The table we are inserting into */ - Select *pSelect, /* A SELECT statement to use as the data source */ - int onError, /* How to handle constraint errors */ - int iDbDest /* The database of pDest */ -){ - sqlite3 *db = pParse->db; - ExprList *pEList; /* The result set of the SELECT */ - Table *pSrc; /* The table in the FROM clause of SELECT */ - Index *pSrcIdx, *pDestIdx; /* Source and destination indices */ - struct SrcList_item *pItem; /* An element of pSelect->pSrc */ - int i; /* Loop counter */ - int iDbSrc; /* The database of pSrc */ - int iSrc, iDest; /* Cursors from source and destination */ - int addr1, addr2; /* Loop addresses */ - int emptyDestTest = 0; /* Address of test for empty pDest */ - int emptySrcTest = 0; /* Address of test for empty pSrc */ - Vdbe *v; /* The VDBE we are building */ - int regAutoinc; /* Memory register used by AUTOINC */ - int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ - int regData, regRowid; /* Registers holding data and rowid */ - - if( pSelect==0 ){ - return 0; /* Must be of the form INSERT INTO ... SELECT ... */ - } - if( pParse->pWith || pSelect->pWith ){ - /* Do not attempt to process this query if there are an WITH clauses - ** attached to it. Proceeding may generate a false "no such table: xxx" - ** error if pSelect reads from a CTE named "xxx". */ - return 0; - } - if( sqlite3TriggerList(pParse, pDest) ){ - return 0; /* tab1 must not have triggers */ - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pDest) ){ - return 0; /* tab1 must not be a virtual table */ - } -#endif - if( onError==OE_Default ){ - if( pDest->iPKey>=0 ) onError = pDest->keyConf; - if( onError==OE_Default ) onError = OE_Abort; - } - assert(pSelect->pSrc); /* allocated even if there is no FROM clause */ - if( pSelect->pSrc->nSrc!=1 ){ - return 0; /* FROM clause must have exactly one term */ - } - if( pSelect->pSrc->a[0].pSelect ){ - return 0; /* FROM clause cannot contain a subquery */ - } - if( pSelect->pWhere ){ - return 0; /* SELECT may not have a WHERE clause */ - } - if( pSelect->pOrderBy ){ - return 0; /* SELECT may not have an ORDER BY clause */ - } - /* Do not need to test for a HAVING clause. If HAVING is present but - ** there is no ORDER BY, we will get an error. */ - if( pSelect->pGroupBy ){ - return 0; /* SELECT may not have a GROUP BY clause */ - } - if( pSelect->pLimit ){ - return 0; /* SELECT may not have a LIMIT clause */ - } - if( pSelect->pPrior ){ - return 0; /* SELECT may not be a compound query */ - } - if( pSelect->selFlags & SF_Distinct ){ - return 0; /* SELECT may not be DISTINCT */ - } - pEList = pSelect->pEList; - assert( pEList!=0 ); - if( pEList->nExpr!=1 ){ - return 0; /* The result set must have exactly one column */ - } - assert( pEList->a[0].pExpr ); - if( pEList->a[0].pExpr->op!=TK_ASTERISK ){ - return 0; /* The result set must be the special operator "*" */ - } - - /* At this point we have established that the statement is of the - ** correct syntactic form to participate in this optimization. Now - ** we have to check the semantics. - */ - pItem = pSelect->pSrc->a; - pSrc = sqlite3LocateTableItem(pParse, 0, pItem); - if( pSrc==0 ){ - return 0; /* FROM clause does not contain a real table */ - } - if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){ - testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */ - return 0; /* tab1 and tab2 may not be the same table */ - } - if( HasRowid(pDest)!=HasRowid(pSrc) ){ - return 0; /* source and destination must both be WITHOUT ROWID or not */ - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pSrc) ){ - return 0; /* tab2 must not be a virtual table */ - } -#endif - if( pSrc->pSelect ){ - return 0; /* tab2 may not be a view */ - } - if( pDest->nCol!=pSrc->nCol ){ - return 0; /* Number of columns must be the same in tab1 and tab2 */ - } - if( pDest->iPKey!=pSrc->iPKey ){ - return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ - } - for(i=0; inCol; i++){ - Column *pDestCol = &pDest->aCol[i]; - Column *pSrcCol = &pSrc->aCol[i]; -#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS - if( (db->mDbFlags & DBFLAG_Vacuum)==0 - && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN - ){ - return 0; /* Neither table may have __hidden__ columns */ - } -#endif -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - /* Even if tables t1 and t2 have identical schemas, if they contain - ** generated columns, then this statement is semantically incorrect: - ** - ** INSERT INTO t2 SELECT * FROM t1; - ** - ** The reason is that generated column values are returned by the - ** the SELECT statement on the right but the INSERT statement on the - ** left wants them to be omitted. - ** - ** Nevertheless, this is a useful notational shorthand to tell SQLite - ** to do a bulk transfer all of the content from t1 over to t2. - ** - ** We could, in theory, disable this (except for internal use by the - ** VACUUM command where it is actually needed). But why do that? It - ** seems harmless enough, and provides a useful service. - */ - if( (pDestCol->colFlags & COLFLAG_GENERATED) != - (pSrcCol->colFlags & COLFLAG_GENERATED) ){ - return 0; /* Both columns have the same generated-column type */ - } - /* But the transfer is only allowed if both the source and destination - ** tables have the exact same expressions for generated columns. - ** This requirement could be relaxed for VIRTUAL columns, I suppose. - */ - if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){ - if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){ - testcase( pDestCol->colFlags & COLFLAG_VIRTUAL ); - testcase( pDestCol->colFlags & COLFLAG_STORED ); - return 0; /* Different generator expressions */ - } - } -#endif - if( pDestCol->affinity!=pSrcCol->affinity ){ - return 0; /* Affinity must be the same on all columns */ - } - if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){ - return 0; /* Collating sequence must be the same on all columns */ - } - if( pDestCol->notNull && !pSrcCol->notNull ){ - return 0; /* tab2 must be NOT NULL if tab1 is */ - } - /* Default values for second and subsequent columns need to match. */ - if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){ - assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN ); - assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN ); - if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) - || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken, - pSrcCol->pDflt->u.zToken)!=0) - ){ - return 0; /* Default values must be the same for all columns */ - } - } - } - for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ - if( IsUniqueIndex(pDestIdx) ){ - destHasUniqueIdx = 1; - } - for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ - if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; - } - if( pSrcIdx==0 ){ - return 0; /* pDestIdx has no corresponding index in pSrc */ - } - if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema - && sqlite3FaultSim(411)==SQLITE_OK ){ - /* The sqlite3FaultSim() call allows this corruption test to be - ** bypassed during testing, in order to exercise other corruption tests - ** further downstream. */ - return 0; /* Corrupt schema - two indexes on the same btree */ - } - } -#ifndef SQLITE_OMIT_CHECK - if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ - return 0; /* Tables have different CHECK constraints. Ticket #2252 */ - } -#endif -#ifndef SQLITE_OMIT_FOREIGN_KEY - /* Disallow the transfer optimization if the destination table constains - ** any foreign key constraints. This is more restrictive than necessary. - ** But the main beneficiary of the transfer optimization is the VACUUM - ** command, and the VACUUM command disables foreign key constraints. So - ** the extra complication to make this rule less restrictive is probably - ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e] - */ - if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){ - return 0; - } -#endif - if( (db->flags & SQLITE_CountRows)!=0 ){ - return 0; /* xfer opt does not play well with PRAGMA count_changes */ - } - - /* If we get this far, it means that the xfer optimization is at - ** least a possibility, though it might only work if the destination - ** table (tab1) is initially empty. - */ -#ifdef SQLITE_TEST - sqlite3_xferopt_count++; -#endif - iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema); - v = sqlite3GetVdbe(pParse); - sqlite3CodeVerifySchema(pParse, iDbSrc); - iSrc = pParse->nTab++; - iDest = pParse->nTab++; - regAutoinc = autoIncBegin(pParse, iDbDest, pDest); - regData = sqlite3GetTempReg(pParse); - regRowid = sqlite3GetTempReg(pParse); - sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); - assert( HasRowid(pDest) || destHasUniqueIdx ); - if( (db->mDbFlags & DBFLAG_Vacuum)==0 && ( - (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */ - || destHasUniqueIdx /* (2) */ - || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */ - )){ - /* In some circumstances, we are able to run the xfer optimization - ** only if the destination table is initially empty. Unless the - ** DBFLAG_Vacuum flag is set, this block generates code to make - ** that determination. If DBFLAG_Vacuum is set, then the destination - ** table is always empty. - ** - ** Conditions under which the destination must be empty: - ** - ** (1) There is no INTEGER PRIMARY KEY but there are indices. - ** (If the destination is not initially empty, the rowid fields - ** of index entries might need to change.) - ** - ** (2) The destination has a unique index. (The xfer optimization - ** is unable to test uniqueness.) - ** - ** (3) onError is something other than OE_Abort and OE_Rollback. - */ - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v); - emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, addr1); - } - if( HasRowid(pSrc) ){ - u8 insFlags; - sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); - emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); - if( pDest->iPKey>=0 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); - sqlite3VdbeVerifyAbortable(v, onError); - addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); - VdbeCoverage(v); - sqlite3RowidConstraint(pParse, onError, pDest); - sqlite3VdbeJumpHere(v, addr2); - autoIncStep(pParse, regAutoinc, regRowid); - }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){ - addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); - }else{ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); - assert( (pDest->tabFlags & TF_Autoincrement)==0 ); - } - if( db->mDbFlags & DBFLAG_Vacuum ){ - sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); - insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT; - }else{ - insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; - } - sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); - sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid, - (char*)pDest, P4_TABLE); - sqlite3VdbeChangeP5(v, insFlags); - sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); - }else{ - sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName); - sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName); - } - for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ - u8 idxInsFlags = 0; - for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){ - if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; - } - assert( pSrcIdx ); - sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc); - sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx); - VdbeComment((v, "%s", pSrcIdx->zName)); - sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest); - sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx); - sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR); - VdbeComment((v, "%s", pDestIdx->zName)); - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v); - if( db->mDbFlags & DBFLAG_Vacuum ){ - /* This INSERT command is part of a VACUUM operation, which guarantees - ** that the destination table is empty. If all indexed columns use - ** collation sequence BINARY, then it can also be assumed that the - ** index will be populated by inserting keys in strictly sorted - ** order. In this case, instead of seeking within the b-tree as part - ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the - ** OP_IdxInsert to seek to the point within the b-tree where each key - ** should be inserted. This is faster. - ** - ** If any of the indexed columns use a collation sequence other than - ** BINARY, this optimization is disabled. This is because the user - ** might change the definition of a collation sequence and then run - ** a VACUUM command. In that case keys may not be written in strictly - ** sorted order. */ - for(i=0; inColumn; i++){ - const char *zColl = pSrcIdx->azColl[i]; - if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break; - } - if( i==pSrcIdx->nColumn ){ - idxInsFlags = OPFLAG_USESEEKRESULT; - sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); - } - }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){ - idxInsFlags |= OPFLAG_NCHANGE; - } - sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData); - sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND); - sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); - } - if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest); - sqlite3ReleaseTempReg(pParse, regRowid); - sqlite3ReleaseTempReg(pParse, regData); - if( emptyDestTest ){ - sqlite3AutoincrementEnd(pParse); - sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); - sqlite3VdbeJumpHere(v, emptyDestTest); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); - return 0; - }else{ - return 1; - } -} -#endif /* SQLITE_OMIT_XFER_OPT */ - -/************** End of insert.c **********************************************/ -/************** Begin file legacy.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. -** -************************************************************************* -** Main file for the SQLite library. The routines in this file -** implement the programmer interface to the library. Routines in -** other files are for internal use by SQLite and should not be -** accessed by users of the library. -*/ - -/* #include "sqliteInt.h" */ - -/* -** Execute SQL code. Return one of the SQLITE_ success/failure -** codes. Also write an error message into memory obtained from -** malloc() and make *pzErrMsg point to that message. -** -** If the SQL is a query, then for each row in the query result -** the xCallback() function is called. pArg becomes the first -** argument to xCallback(). If xCallback=NULL then no callback -** is invoked, even for queries. -*/ -SQLITE_API int sqlite3_exec( - sqlite3 *db, /* The database on which the SQL executes */ - const char *zSql, /* The SQL to be executed */ - sqlite3_callback xCallback, /* Invoke this callback routine */ - void *pArg, /* First argument to xCallback() */ - char **pzErrMsg /* Write error messages here */ -){ - int rc = SQLITE_OK; /* Return code */ - const char *zLeftover; /* Tail of unprocessed SQL */ - sqlite3_stmt *pStmt = 0; /* The current SQL statement */ - char **azCols = 0; /* Names of result columns */ - int callbackIsInit; /* True if callback data is initialized */ - - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; - if( zSql==0 ) zSql = ""; - - sqlite3_mutex_enter(db->mutex); - sqlite3Error(db, SQLITE_OK); - while( rc==SQLITE_OK && zSql[0] ){ - int nCol = 0; - char **azVals = 0; - - pStmt = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); - assert( rc==SQLITE_OK || pStmt==0 ); - if( rc!=SQLITE_OK ){ - continue; - } - if( !pStmt ){ - /* this happens for a comment or white-space */ - zSql = zLeftover; - continue; - } - callbackIsInit = 0; - - while( 1 ){ - int i; - rc = sqlite3_step(pStmt); - - /* Invoke the callback function if required */ - if( xCallback && (SQLITE_ROW==rc || - (SQLITE_DONE==rc && !callbackIsInit - && db->flags&SQLITE_NullCallback)) ){ - if( !callbackIsInit ){ - nCol = sqlite3_column_count(pStmt); - azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*)); - if( azCols==0 ){ - goto exec_out; - } - for(i=0; ierrMask)==rc ); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/************** End of legacy.c **********************************************/ -/************** Begin file loadext.c *****************************************/ -/* -** 2006 June 7 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code used to dynamically load extensions into -** the SQLite library. -*/ - -#ifndef SQLITE_CORE - #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ -#endif -/************** Include sqlite3ext.h in the middle of loadext.c **************/ -/************** Begin file sqlite3ext.h **************************************/ -/* -** 2006 June 7 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the SQLite interface for use by -** shared libraries that want to be imported as extensions into -** an SQLite instance. Shared libraries that intend to be loaded -** as extensions by SQLite should #include this file instead of -** sqlite3.h. -*/ -#ifndef SQLITE3EXT_H -#define SQLITE3EXT_H -/* #include "sqlite3.h" */ - -/* -** The following structure holds pointers to all of the SQLite API -** routines. -** -** WARNING: In order to maintain backwards compatibility, add new -** interfaces to the end of this structure only. If you insert new -** interfaces in the middle of this structure, then older different -** versions of SQLite will not be able to load each other's shared -** libraries! -*/ -struct sqlite3_api_routines { - void * (*aggregate_context)(sqlite3_context*,int nBytes); - int (*aggregate_count)(sqlite3_context*); - int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); - int (*bind_double)(sqlite3_stmt*,int,double); - int (*bind_int)(sqlite3_stmt*,int,int); - int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); - int (*bind_null)(sqlite3_stmt*,int); - int (*bind_parameter_count)(sqlite3_stmt*); - int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); - const char * (*bind_parameter_name)(sqlite3_stmt*,int); - int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); - int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); - int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); - int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); - int (*busy_timeout)(sqlite3*,int ms); - int (*changes)(sqlite3*); - int (*close)(sqlite3*); - int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*, - int eTextRep,const char*)); - int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*, - int eTextRep,const void*)); - const void * (*column_blob)(sqlite3_stmt*,int iCol); - int (*column_bytes)(sqlite3_stmt*,int iCol); - int (*column_bytes16)(sqlite3_stmt*,int iCol); - int (*column_count)(sqlite3_stmt*pStmt); - const char * (*column_database_name)(sqlite3_stmt*,int); - const void * (*column_database_name16)(sqlite3_stmt*,int); - const char * (*column_decltype)(sqlite3_stmt*,int i); - const void * (*column_decltype16)(sqlite3_stmt*,int); - double (*column_double)(sqlite3_stmt*,int iCol); - int (*column_int)(sqlite3_stmt*,int iCol); - sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); - const char * (*column_name)(sqlite3_stmt*,int); - const void * (*column_name16)(sqlite3_stmt*,int); - const char * (*column_origin_name)(sqlite3_stmt*,int); - const void * (*column_origin_name16)(sqlite3_stmt*,int); - const char * (*column_table_name)(sqlite3_stmt*,int); - const void * (*column_table_name16)(sqlite3_stmt*,int); - const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); - const void * (*column_text16)(sqlite3_stmt*,int iCol); - int (*column_type)(sqlite3_stmt*,int iCol); - sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); - void * (*commit_hook)(sqlite3*,int(*)(void*),void*); - int (*complete)(const char*sql); - int (*complete16)(const void*sql); - int (*create_collation)(sqlite3*,const char*,int,void*, - int(*)(void*,int,const void*,int,const void*)); - int (*create_collation16)(sqlite3*,const void*,int,void*, - int(*)(void*,int,const void*,int,const void*)); - int (*create_function)(sqlite3*,const char*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*)); - int (*create_function16)(sqlite3*,const void*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*)); - int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); - int (*data_count)(sqlite3_stmt*pStmt); - sqlite3 * (*db_handle)(sqlite3_stmt*); - int (*declare_vtab)(sqlite3*,const char*); - int (*enable_shared_cache)(int); - int (*errcode)(sqlite3*db); - const char * (*errmsg)(sqlite3*); - const void * (*errmsg16)(sqlite3*); - int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); - int (*expired)(sqlite3_stmt*); - int (*finalize)(sqlite3_stmt*pStmt); - void (*free)(void*); - void (*free_table)(char**result); - int (*get_autocommit)(sqlite3*); - void * (*get_auxdata)(sqlite3_context*,int); - int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); - int (*global_recover)(void); - void (*interruptx)(sqlite3*); - sqlite_int64 (*last_insert_rowid)(sqlite3*); - const char * (*libversion)(void); - int (*libversion_number)(void); - void *(*malloc)(int); - char * (*mprintf)(const char*,...); - int (*open)(const char*,sqlite3**); - int (*open16)(const void*,sqlite3**); - int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); - int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); - void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); - void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); - void *(*realloc)(void*,int); - int (*reset)(sqlite3_stmt*pStmt); - void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_double)(sqlite3_context*,double); - void (*result_error)(sqlite3_context*,const char*,int); - void (*result_error16)(sqlite3_context*,const void*,int); - void (*result_int)(sqlite3_context*,int); - void (*result_int64)(sqlite3_context*,sqlite_int64); - void (*result_null)(sqlite3_context*); - void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); - void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); - void (*result_value)(sqlite3_context*,sqlite3_value*); - void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); - int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, - const char*,const char*),void*); - void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); - char * (*xsnprintf)(int,char*,const char*,...); - int (*step)(sqlite3_stmt*); - int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, - char const**,char const**,int*,int*,int*); - void (*thread_cleanup)(void); - int (*total_changes)(sqlite3*); - void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); - int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); - void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*, - sqlite_int64),void*); - void * (*user_data)(sqlite3_context*); - const void * (*value_blob)(sqlite3_value*); - int (*value_bytes)(sqlite3_value*); - int (*value_bytes16)(sqlite3_value*); - double (*value_double)(sqlite3_value*); - int (*value_int)(sqlite3_value*); - sqlite_int64 (*value_int64)(sqlite3_value*); - int (*value_numeric_type)(sqlite3_value*); - const unsigned char * (*value_text)(sqlite3_value*); - const void * (*value_text16)(sqlite3_value*); - const void * (*value_text16be)(sqlite3_value*); - const void * (*value_text16le)(sqlite3_value*); - int (*value_type)(sqlite3_value*); - char *(*vmprintf)(const char*,va_list); - /* Added ??? */ - int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); - /* Added by 3.3.13 */ - int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); - int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); - int (*clear_bindings)(sqlite3_stmt*); - /* Added by 3.4.1 */ - int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*, - void (*xDestroy)(void *)); - /* Added by 3.5.0 */ - int (*bind_zeroblob)(sqlite3_stmt*,int,int); - int (*blob_bytes)(sqlite3_blob*); - int (*blob_close)(sqlite3_blob*); - int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64, - int,sqlite3_blob**); - int (*blob_read)(sqlite3_blob*,void*,int,int); - int (*blob_write)(sqlite3_blob*,const void*,int,int); - int (*create_collation_v2)(sqlite3*,const char*,int,void*, - int(*)(void*,int,const void*,int,const void*), - void(*)(void*)); - int (*file_control)(sqlite3*,const char*,int,void*); - sqlite3_int64 (*memory_highwater)(int); - sqlite3_int64 (*memory_used)(void); - sqlite3_mutex *(*mutex_alloc)(int); - void (*mutex_enter)(sqlite3_mutex*); - void (*mutex_free)(sqlite3_mutex*); - void (*mutex_leave)(sqlite3_mutex*); - int (*mutex_try)(sqlite3_mutex*); - int (*open_v2)(const char*,sqlite3**,int,const char*); - int (*release_memory)(int); - void (*result_error_nomem)(sqlite3_context*); - void (*result_error_toobig)(sqlite3_context*); - int (*sleep)(int); - void (*soft_heap_limit)(int); - sqlite3_vfs *(*vfs_find)(const char*); - int (*vfs_register)(sqlite3_vfs*,int); - int (*vfs_unregister)(sqlite3_vfs*); - int (*xthreadsafe)(void); - void (*result_zeroblob)(sqlite3_context*,int); - void (*result_error_code)(sqlite3_context*,int); - int (*test_control)(int, ...); - void (*randomness)(int,void*); - sqlite3 *(*context_db_handle)(sqlite3_context*); - int (*extended_result_codes)(sqlite3*,int); - int (*limit)(sqlite3*,int,int); - sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); - const char *(*sql)(sqlite3_stmt*); - int (*status)(int,int*,int*,int); - int (*backup_finish)(sqlite3_backup*); - sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*); - int (*backup_pagecount)(sqlite3_backup*); - int (*backup_remaining)(sqlite3_backup*); - int (*backup_step)(sqlite3_backup*,int); - const char *(*compileoption_get)(int); - int (*compileoption_used)(const char*); - int (*create_function_v2)(sqlite3*,const char*,int,int,void*, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*), - void(*xDestroy)(void*)); - int (*db_config)(sqlite3*,int,...); - sqlite3_mutex *(*db_mutex)(sqlite3*); - int (*db_status)(sqlite3*,int,int*,int*,int); - int (*extended_errcode)(sqlite3*); - void (*log)(int,const char*,...); - sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); - const char *(*sourceid)(void); - int (*stmt_status)(sqlite3_stmt*,int,int); - int (*strnicmp)(const char*,const char*,int); - int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*); - int (*wal_autocheckpoint)(sqlite3*,int); - int (*wal_checkpoint)(sqlite3*,const char*); - void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); - int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); - int (*vtab_config)(sqlite3*,int op,...); - int (*vtab_on_conflict)(sqlite3*); - /* Version 3.7.16 and later */ - int (*close_v2)(sqlite3*); - const char *(*db_filename)(sqlite3*,const char*); - int (*db_readonly)(sqlite3*,const char*); - int (*db_release_memory)(sqlite3*); - const char *(*errstr)(int); - int (*stmt_busy)(sqlite3_stmt*); - int (*stmt_readonly)(sqlite3_stmt*); - int (*stricmp)(const char*,const char*); - int (*uri_boolean)(const char*,const char*,int); - sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64); - const char *(*uri_parameter)(const char*,const char*); - char *(*xvsnprintf)(int,char*,const char*,va_list); - int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*); - /* Version 3.8.7 and later */ - int (*auto_extension)(void(*)(void)); - int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64, - void(*)(void*)); - int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64, - void(*)(void*),unsigned char); - int (*cancel_auto_extension)(void(*)(void)); - int (*load_extension)(sqlite3*,const char*,const char*,char**); - void *(*malloc64)(sqlite3_uint64); - sqlite3_uint64 (*msize)(void*); - void *(*realloc64)(void*,sqlite3_uint64); - void (*reset_auto_extension)(void); - void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64, - void(*)(void*)); - void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64, - void(*)(void*), unsigned char); - int (*strglob)(const char*,const char*); - /* Version 3.8.11 and later */ - sqlite3_value *(*value_dup)(const sqlite3_value*); - void (*value_free)(sqlite3_value*); - int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64); - int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64); - /* Version 3.9.0 and later */ - unsigned int (*value_subtype)(sqlite3_value*); - void (*result_subtype)(sqlite3_context*,unsigned int); - /* Version 3.10.0 and later */ - int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int); - int (*strlike)(const char*,const char*,unsigned int); - int (*db_cacheflush)(sqlite3*); - /* Version 3.12.0 and later */ - int (*system_errno)(sqlite3*); - /* Version 3.14.0 and later */ - int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*); - char *(*expanded_sql)(sqlite3_stmt*); - /* Version 3.18.0 and later */ - void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64); - /* Version 3.20.0 and later */ - int (*prepare_v3)(sqlite3*,const char*,int,unsigned int, - sqlite3_stmt**,const char**); - int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int, - sqlite3_stmt**,const void**); - int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*)); - void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*)); - void *(*value_pointer)(sqlite3_value*,const char*); - int (*vtab_nochange)(sqlite3_context*); - int (*value_nochange)(sqlite3_value*); - const char *(*vtab_collation)(sqlite3_index_info*,int); - /* Version 3.24.0 and later */ - int (*keyword_count)(void); - int (*keyword_name)(int,const char**,int*); - int (*keyword_check)(const char*,int); - sqlite3_str *(*str_new)(sqlite3*); - char *(*str_finish)(sqlite3_str*); - void (*str_appendf)(sqlite3_str*, const char *zFormat, ...); - void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list); - void (*str_append)(sqlite3_str*, const char *zIn, int N); - void (*str_appendall)(sqlite3_str*, const char *zIn); - void (*str_appendchar)(sqlite3_str*, int N, char C); - void (*str_reset)(sqlite3_str*); - int (*str_errcode)(sqlite3_str*); - int (*str_length)(sqlite3_str*); - char *(*str_value)(sqlite3_str*); - /* Version 3.25.0 and later */ - int (*create_window_function)(sqlite3*,const char*,int,int,void*, - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*), - void (*xValue)(sqlite3_context*), - void (*xInv)(sqlite3_context*,int,sqlite3_value**), - void(*xDestroy)(void*)); - /* Version 3.26.0 and later */ - const char *(*normalized_sql)(sqlite3_stmt*); - /* Version 3.28.0 and later */ - int (*stmt_isexplain)(sqlite3_stmt*); - int (*value_frombind)(sqlite3_value*); - /* Version 3.30.0 and later */ - int (*drop_modules)(sqlite3*,const char**); - /* Version 3.31.0 and later */ - sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64); - const char *(*uri_key)(const char*,int); - const char *(*filename_database)(const char*); - const char *(*filename_journal)(const char*); - const char *(*filename_wal)(const char*); - /* Version 3.32.0 and later */ - char *(*create_filename)(const char*,const char*,const char*, - int,const char**); - void (*free_filename)(char*); - sqlite3_file *(*database_file_object)(const char*); -}; - -/* -** This is the function signature used for all extension entry points. It -** is also defined in the file "loadext.c". -*/ -typedef int (*sqlite3_loadext_entry)( - sqlite3 *db, /* Handle to the database. */ - char **pzErrMsg, /* Used to set error string on failure. */ - const sqlite3_api_routines *pThunk /* Extension API function pointers. */ -); - -/* -** The following macros redefine the API routines so that they are -** redirected through the global sqlite3_api structure. -** -** This header file is also used by the loadext.c source file -** (part of the main SQLite library - not an extension) so that -** it can get access to the sqlite3_api_routines structure -** definition. But the main library does not want to redefine -** the API. So the redefinition macros are only valid if the -** SQLITE_CORE macros is undefined. -*/ -#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) -#define sqlite3_aggregate_context sqlite3_api->aggregate_context -#ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_aggregate_count sqlite3_api->aggregate_count -#endif -#define sqlite3_bind_blob sqlite3_api->bind_blob -#define sqlite3_bind_double sqlite3_api->bind_double -#define sqlite3_bind_int sqlite3_api->bind_int -#define sqlite3_bind_int64 sqlite3_api->bind_int64 -#define sqlite3_bind_null sqlite3_api->bind_null -#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count -#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index -#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name -#define sqlite3_bind_text sqlite3_api->bind_text -#define sqlite3_bind_text16 sqlite3_api->bind_text16 -#define sqlite3_bind_value sqlite3_api->bind_value -#define sqlite3_busy_handler sqlite3_api->busy_handler -#define sqlite3_busy_timeout sqlite3_api->busy_timeout -#define sqlite3_changes sqlite3_api->changes -#define sqlite3_close sqlite3_api->close -#define sqlite3_collation_needed sqlite3_api->collation_needed -#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 -#define sqlite3_column_blob sqlite3_api->column_blob -#define sqlite3_column_bytes sqlite3_api->column_bytes -#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 -#define sqlite3_column_count sqlite3_api->column_count -#define sqlite3_column_database_name sqlite3_api->column_database_name -#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 -#define sqlite3_column_decltype sqlite3_api->column_decltype -#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 -#define sqlite3_column_double sqlite3_api->column_double -#define sqlite3_column_int sqlite3_api->column_int -#define sqlite3_column_int64 sqlite3_api->column_int64 -#define sqlite3_column_name sqlite3_api->column_name -#define sqlite3_column_name16 sqlite3_api->column_name16 -#define sqlite3_column_origin_name sqlite3_api->column_origin_name -#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 -#define sqlite3_column_table_name sqlite3_api->column_table_name -#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 -#define sqlite3_column_text sqlite3_api->column_text -#define sqlite3_column_text16 sqlite3_api->column_text16 -#define sqlite3_column_type sqlite3_api->column_type -#define sqlite3_column_value sqlite3_api->column_value -#define sqlite3_commit_hook sqlite3_api->commit_hook -#define sqlite3_complete sqlite3_api->complete -#define sqlite3_complete16 sqlite3_api->complete16 -#define sqlite3_create_collation sqlite3_api->create_collation -#define sqlite3_create_collation16 sqlite3_api->create_collation16 -#define sqlite3_create_function sqlite3_api->create_function -#define sqlite3_create_function16 sqlite3_api->create_function16 -#define sqlite3_create_module sqlite3_api->create_module -#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 -#define sqlite3_data_count sqlite3_api->data_count -#define sqlite3_db_handle sqlite3_api->db_handle -#define sqlite3_declare_vtab sqlite3_api->declare_vtab -#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache -#define sqlite3_errcode sqlite3_api->errcode -#define sqlite3_errmsg sqlite3_api->errmsg -#define sqlite3_errmsg16 sqlite3_api->errmsg16 -#define sqlite3_exec sqlite3_api->exec -#ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_expired sqlite3_api->expired -#endif -#define sqlite3_finalize sqlite3_api->finalize -#define sqlite3_free sqlite3_api->free -#define sqlite3_free_table sqlite3_api->free_table -#define sqlite3_get_autocommit sqlite3_api->get_autocommit -#define sqlite3_get_auxdata sqlite3_api->get_auxdata -#define sqlite3_get_table sqlite3_api->get_table -#ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_global_recover sqlite3_api->global_recover -#endif -#define sqlite3_interrupt sqlite3_api->interruptx -#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid -#define sqlite3_libversion sqlite3_api->libversion -#define sqlite3_libversion_number sqlite3_api->libversion_number -#define sqlite3_malloc sqlite3_api->malloc -#define sqlite3_mprintf sqlite3_api->mprintf -#define sqlite3_open sqlite3_api->open -#define sqlite3_open16 sqlite3_api->open16 -#define sqlite3_prepare sqlite3_api->prepare -#define sqlite3_prepare16 sqlite3_api->prepare16 -#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 -#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 -#define sqlite3_profile sqlite3_api->profile -#define sqlite3_progress_handler sqlite3_api->progress_handler -#define sqlite3_realloc sqlite3_api->realloc -#define sqlite3_reset sqlite3_api->reset -#define sqlite3_result_blob sqlite3_api->result_blob -#define sqlite3_result_double sqlite3_api->result_double -#define sqlite3_result_error sqlite3_api->result_error -#define sqlite3_result_error16 sqlite3_api->result_error16 -#define sqlite3_result_int sqlite3_api->result_int -#define sqlite3_result_int64 sqlite3_api->result_int64 -#define sqlite3_result_null sqlite3_api->result_null -#define sqlite3_result_text sqlite3_api->result_text -#define sqlite3_result_text16 sqlite3_api->result_text16 -#define sqlite3_result_text16be sqlite3_api->result_text16be -#define sqlite3_result_text16le sqlite3_api->result_text16le -#define sqlite3_result_value sqlite3_api->result_value -#define sqlite3_rollback_hook sqlite3_api->rollback_hook -#define sqlite3_set_authorizer sqlite3_api->set_authorizer -#define sqlite3_set_auxdata sqlite3_api->set_auxdata -#define sqlite3_snprintf sqlite3_api->xsnprintf -#define sqlite3_step sqlite3_api->step -#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata -#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup -#define sqlite3_total_changes sqlite3_api->total_changes -#define sqlite3_trace sqlite3_api->trace -#ifndef SQLITE_OMIT_DEPRECATED -#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings -#endif -#define sqlite3_update_hook sqlite3_api->update_hook -#define sqlite3_user_data sqlite3_api->user_data -#define sqlite3_value_blob sqlite3_api->value_blob -#define sqlite3_value_bytes sqlite3_api->value_bytes -#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 -#define sqlite3_value_double sqlite3_api->value_double -#define sqlite3_value_int sqlite3_api->value_int -#define sqlite3_value_int64 sqlite3_api->value_int64 -#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type -#define sqlite3_value_text sqlite3_api->value_text -#define sqlite3_value_text16 sqlite3_api->value_text16 -#define sqlite3_value_text16be sqlite3_api->value_text16be -#define sqlite3_value_text16le sqlite3_api->value_text16le -#define sqlite3_value_type sqlite3_api->value_type -#define sqlite3_vmprintf sqlite3_api->vmprintf -#define sqlite3_vsnprintf sqlite3_api->xvsnprintf -#define sqlite3_overload_function sqlite3_api->overload_function -#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 -#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 -#define sqlite3_clear_bindings sqlite3_api->clear_bindings -#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob -#define sqlite3_blob_bytes sqlite3_api->blob_bytes -#define sqlite3_blob_close sqlite3_api->blob_close -#define sqlite3_blob_open sqlite3_api->blob_open -#define sqlite3_blob_read sqlite3_api->blob_read -#define sqlite3_blob_write sqlite3_api->blob_write -#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 -#define sqlite3_file_control sqlite3_api->file_control -#define sqlite3_memory_highwater sqlite3_api->memory_highwater -#define sqlite3_memory_used sqlite3_api->memory_used -#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc -#define sqlite3_mutex_enter sqlite3_api->mutex_enter -#define sqlite3_mutex_free sqlite3_api->mutex_free -#define sqlite3_mutex_leave sqlite3_api->mutex_leave -#define sqlite3_mutex_try sqlite3_api->mutex_try -#define sqlite3_open_v2 sqlite3_api->open_v2 -#define sqlite3_release_memory sqlite3_api->release_memory -#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem -#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig -#define sqlite3_sleep sqlite3_api->sleep -#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit -#define sqlite3_vfs_find sqlite3_api->vfs_find -#define sqlite3_vfs_register sqlite3_api->vfs_register -#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister -#define sqlite3_threadsafe sqlite3_api->xthreadsafe -#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob -#define sqlite3_result_error_code sqlite3_api->result_error_code -#define sqlite3_test_control sqlite3_api->test_control -#define sqlite3_randomness sqlite3_api->randomness -#define sqlite3_context_db_handle sqlite3_api->context_db_handle -#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes -#define sqlite3_limit sqlite3_api->limit -#define sqlite3_next_stmt sqlite3_api->next_stmt -#define sqlite3_sql sqlite3_api->sql -#define sqlite3_status sqlite3_api->status -#define sqlite3_backup_finish sqlite3_api->backup_finish -#define sqlite3_backup_init sqlite3_api->backup_init -#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount -#define sqlite3_backup_remaining sqlite3_api->backup_remaining -#define sqlite3_backup_step sqlite3_api->backup_step -#define sqlite3_compileoption_get sqlite3_api->compileoption_get -#define sqlite3_compileoption_used sqlite3_api->compileoption_used -#define sqlite3_create_function_v2 sqlite3_api->create_function_v2 -#define sqlite3_db_config sqlite3_api->db_config -#define sqlite3_db_mutex sqlite3_api->db_mutex -#define sqlite3_db_status sqlite3_api->db_status -#define sqlite3_extended_errcode sqlite3_api->extended_errcode -#define sqlite3_log sqlite3_api->log -#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64 -#define sqlite3_sourceid sqlite3_api->sourceid -#define sqlite3_stmt_status sqlite3_api->stmt_status -#define sqlite3_strnicmp sqlite3_api->strnicmp -#define sqlite3_unlock_notify sqlite3_api->unlock_notify -#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint -#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint -#define sqlite3_wal_hook sqlite3_api->wal_hook -#define sqlite3_blob_reopen sqlite3_api->blob_reopen -#define sqlite3_vtab_config sqlite3_api->vtab_config -#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict -/* Version 3.7.16 and later */ -#define sqlite3_close_v2 sqlite3_api->close_v2 -#define sqlite3_db_filename sqlite3_api->db_filename -#define sqlite3_db_readonly sqlite3_api->db_readonly -#define sqlite3_db_release_memory sqlite3_api->db_release_memory -#define sqlite3_errstr sqlite3_api->errstr -#define sqlite3_stmt_busy sqlite3_api->stmt_busy -#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly -#define sqlite3_stricmp sqlite3_api->stricmp -#define sqlite3_uri_boolean sqlite3_api->uri_boolean -#define sqlite3_uri_int64 sqlite3_api->uri_int64 -#define sqlite3_uri_parameter sqlite3_api->uri_parameter -#define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf -#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2 -/* Version 3.8.7 and later */ -#define sqlite3_auto_extension sqlite3_api->auto_extension -#define sqlite3_bind_blob64 sqlite3_api->bind_blob64 -#define sqlite3_bind_text64 sqlite3_api->bind_text64 -#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension -#define sqlite3_load_extension sqlite3_api->load_extension -#define sqlite3_malloc64 sqlite3_api->malloc64 -#define sqlite3_msize sqlite3_api->msize -#define sqlite3_realloc64 sqlite3_api->realloc64 -#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension -#define sqlite3_result_blob64 sqlite3_api->result_blob64 -#define sqlite3_result_text64 sqlite3_api->result_text64 -#define sqlite3_strglob sqlite3_api->strglob -/* Version 3.8.11 and later */ -#define sqlite3_value_dup sqlite3_api->value_dup -#define sqlite3_value_free sqlite3_api->value_free -#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64 -#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64 -/* Version 3.9.0 and later */ -#define sqlite3_value_subtype sqlite3_api->value_subtype -#define sqlite3_result_subtype sqlite3_api->result_subtype -/* Version 3.10.0 and later */ -#define sqlite3_status64 sqlite3_api->status64 -#define sqlite3_strlike sqlite3_api->strlike -#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush -/* Version 3.12.0 and later */ -#define sqlite3_system_errno sqlite3_api->system_errno -/* Version 3.14.0 and later */ -#define sqlite3_trace_v2 sqlite3_api->trace_v2 -#define sqlite3_expanded_sql sqlite3_api->expanded_sql -/* Version 3.18.0 and later */ -#define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid -/* Version 3.20.0 and later */ -#define sqlite3_prepare_v3 sqlite3_api->prepare_v3 -#define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3 -#define sqlite3_bind_pointer sqlite3_api->bind_pointer -#define sqlite3_result_pointer sqlite3_api->result_pointer -#define sqlite3_value_pointer sqlite3_api->value_pointer -/* Version 3.22.0 and later */ -#define sqlite3_vtab_nochange sqlite3_api->vtab_nochange -#define sqlite3_value_nochange sqlite3_api->value_nochange -#define sqlite3_vtab_collation sqlite3_api->vtab_collation -/* Version 3.24.0 and later */ -#define sqlite3_keyword_count sqlite3_api->keyword_count -#define sqlite3_keyword_name sqlite3_api->keyword_name -#define sqlite3_keyword_check sqlite3_api->keyword_check -#define sqlite3_str_new sqlite3_api->str_new -#define sqlite3_str_finish sqlite3_api->str_finish -#define sqlite3_str_appendf sqlite3_api->str_appendf -#define sqlite3_str_vappendf sqlite3_api->str_vappendf -#define sqlite3_str_append sqlite3_api->str_append -#define sqlite3_str_appendall sqlite3_api->str_appendall -#define sqlite3_str_appendchar sqlite3_api->str_appendchar -#define sqlite3_str_reset sqlite3_api->str_reset -#define sqlite3_str_errcode sqlite3_api->str_errcode -#define sqlite3_str_length sqlite3_api->str_length -#define sqlite3_str_value sqlite3_api->str_value -/* Version 3.25.0 and later */ -#define sqlite3_create_window_function sqlite3_api->create_window_function -/* Version 3.26.0 and later */ -#define sqlite3_normalized_sql sqlite3_api->normalized_sql -/* Version 3.28.0 and later */ -#define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain -#define sqlite3_value_frombind sqlite3_api->value_frombind -/* Version 3.30.0 and later */ -#define sqlite3_drop_modules sqlite3_api->drop_modules -/* Version 3.31.0 and later */ -#define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64 -#define sqlite3_uri_key sqlite3_api->uri_key -#define sqlite3_filename_database sqlite3_api->filename_database -#define sqlite3_filename_journal sqlite3_api->filename_journal -#define sqlite3_filename_wal sqlite3_api->filename_wal -/* Version 3.32.0 and later */ -#define sqlite3_create_filename sqlite3_api->create_filename -#define sqlite3_free_filename sqlite3_api->free_filename -#define sqlite3_database_file_object sqlite3_api->database_file_object -#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ - -#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) - /* This case when the file really is being compiled as a loadable - ** extension */ -# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0; -# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v; -# define SQLITE_EXTENSION_INIT3 \ - extern const sqlite3_api_routines *sqlite3_api; -#else - /* This case when the file is being statically linked into the - ** application */ -# define SQLITE_EXTENSION_INIT1 /*no-op*/ -# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */ -# define SQLITE_EXTENSION_INIT3 /*no-op*/ -#endif - -#endif /* SQLITE3EXT_H */ - -/************** End of sqlite3ext.h ******************************************/ -/************** Continuing where we left off in loadext.c ********************/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_OMIT_LOAD_EXTENSION -/* -** Some API routines are omitted when various features are -** excluded from a build of SQLite. Substitute a NULL pointer -** for any missing APIs. -*/ -#ifndef SQLITE_ENABLE_COLUMN_METADATA -# define sqlite3_column_database_name 0 -# define sqlite3_column_database_name16 0 -# define sqlite3_column_table_name 0 -# define sqlite3_column_table_name16 0 -# define sqlite3_column_origin_name 0 -# define sqlite3_column_origin_name16 0 -#endif - -#ifdef SQLITE_OMIT_AUTHORIZATION -# define sqlite3_set_authorizer 0 -#endif - -#ifdef SQLITE_OMIT_UTF16 -# define sqlite3_bind_text16 0 -# define sqlite3_collation_needed16 0 -# define sqlite3_column_decltype16 0 -# define sqlite3_column_name16 0 -# define sqlite3_column_text16 0 -# define sqlite3_complete16 0 -# define sqlite3_create_collation16 0 -# define sqlite3_create_function16 0 -# define sqlite3_errmsg16 0 -# define sqlite3_open16 0 -# define sqlite3_prepare16 0 -# define sqlite3_prepare16_v2 0 -# define sqlite3_prepare16_v3 0 -# define sqlite3_result_error16 0 -# define sqlite3_result_text16 0 -# define sqlite3_result_text16be 0 -# define sqlite3_result_text16le 0 -# define sqlite3_value_text16 0 -# define sqlite3_value_text16be 0 -# define sqlite3_value_text16le 0 -# define sqlite3_column_database_name16 0 -# define sqlite3_column_table_name16 0 -# define sqlite3_column_origin_name16 0 -#endif - -#ifdef SQLITE_OMIT_COMPLETE -# define sqlite3_complete 0 -# define sqlite3_complete16 0 -#endif - -#ifdef SQLITE_OMIT_DECLTYPE -# define sqlite3_column_decltype16 0 -# define sqlite3_column_decltype 0 -#endif - -#ifdef SQLITE_OMIT_PROGRESS_CALLBACK -# define sqlite3_progress_handler 0 -#endif - -#ifdef SQLITE_OMIT_VIRTUALTABLE -# define sqlite3_create_module 0 -# define sqlite3_create_module_v2 0 -# define sqlite3_declare_vtab 0 -# define sqlite3_vtab_config 0 -# define sqlite3_vtab_on_conflict 0 -# define sqlite3_vtab_collation 0 -#endif - -#ifdef SQLITE_OMIT_SHARED_CACHE -# define sqlite3_enable_shared_cache 0 -#endif - -#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED) -# define sqlite3_profile 0 -# define sqlite3_trace 0 -#endif - -#ifdef SQLITE_OMIT_GET_TABLE -# define sqlite3_free_table 0 -# define sqlite3_get_table 0 -#endif - -#ifdef SQLITE_OMIT_INCRBLOB -#define sqlite3_bind_zeroblob 0 -#define sqlite3_blob_bytes 0 -#define sqlite3_blob_close 0 -#define sqlite3_blob_open 0 -#define sqlite3_blob_read 0 -#define sqlite3_blob_write 0 -#define sqlite3_blob_reopen 0 -#endif - -#if defined(SQLITE_OMIT_TRACE) -# define sqlite3_trace_v2 0 -#endif - -/* -** The following structure contains pointers to all SQLite API routines. -** A pointer to this structure is passed into extensions when they are -** loaded so that the extension can make calls back into the SQLite -** library. -** -** When adding new APIs, add them to the bottom of this structure -** in order to preserve backwards compatibility. -** -** Extensions that use newer APIs should first call the -** sqlite3_libversion_number() to make sure that the API they -** intend to use is supported by the library. Extensions should -** also check to make sure that the pointer to the function is -** not NULL before calling it. -*/ -static const sqlite3_api_routines sqlite3Apis = { - sqlite3_aggregate_context, -#ifndef SQLITE_OMIT_DEPRECATED - sqlite3_aggregate_count, -#else - 0, -#endif - sqlite3_bind_blob, - sqlite3_bind_double, - sqlite3_bind_int, - sqlite3_bind_int64, - sqlite3_bind_null, - sqlite3_bind_parameter_count, - sqlite3_bind_parameter_index, - sqlite3_bind_parameter_name, - sqlite3_bind_text, - sqlite3_bind_text16, - sqlite3_bind_value, - sqlite3_busy_handler, - sqlite3_busy_timeout, - sqlite3_changes, - sqlite3_close, - sqlite3_collation_needed, - sqlite3_collation_needed16, - sqlite3_column_blob, - sqlite3_column_bytes, - sqlite3_column_bytes16, - sqlite3_column_count, - sqlite3_column_database_name, - sqlite3_column_database_name16, - sqlite3_column_decltype, - sqlite3_column_decltype16, - sqlite3_column_double, - sqlite3_column_int, - sqlite3_column_int64, - sqlite3_column_name, - sqlite3_column_name16, - sqlite3_column_origin_name, - sqlite3_column_origin_name16, - sqlite3_column_table_name, - sqlite3_column_table_name16, - sqlite3_column_text, - sqlite3_column_text16, - sqlite3_column_type, - sqlite3_column_value, - sqlite3_commit_hook, - sqlite3_complete, - sqlite3_complete16, - sqlite3_create_collation, - sqlite3_create_collation16, - sqlite3_create_function, - sqlite3_create_function16, - sqlite3_create_module, - sqlite3_data_count, - sqlite3_db_handle, - sqlite3_declare_vtab, - sqlite3_enable_shared_cache, - sqlite3_errcode, - sqlite3_errmsg, - sqlite3_errmsg16, - sqlite3_exec, -#ifndef SQLITE_OMIT_DEPRECATED - sqlite3_expired, -#else - 0, -#endif - sqlite3_finalize, - sqlite3_free, - sqlite3_free_table, - sqlite3_get_autocommit, - sqlite3_get_auxdata, - sqlite3_get_table, - 0, /* Was sqlite3_global_recover(), but that function is deprecated */ - sqlite3_interrupt, - sqlite3_last_insert_rowid, - sqlite3_libversion, - sqlite3_libversion_number, - sqlite3_malloc, - sqlite3_mprintf, - sqlite3_open, - sqlite3_open16, - sqlite3_prepare, - sqlite3_prepare16, - sqlite3_profile, - sqlite3_progress_handler, - sqlite3_realloc, - sqlite3_reset, - sqlite3_result_blob, - sqlite3_result_double, - sqlite3_result_error, - sqlite3_result_error16, - sqlite3_result_int, - sqlite3_result_int64, - sqlite3_result_null, - sqlite3_result_text, - sqlite3_result_text16, - sqlite3_result_text16be, - sqlite3_result_text16le, - sqlite3_result_value, - sqlite3_rollback_hook, - sqlite3_set_authorizer, - sqlite3_set_auxdata, - sqlite3_snprintf, - sqlite3_step, - sqlite3_table_column_metadata, -#ifndef SQLITE_OMIT_DEPRECATED - sqlite3_thread_cleanup, -#else - 0, -#endif - sqlite3_total_changes, - sqlite3_trace, -#ifndef SQLITE_OMIT_DEPRECATED - sqlite3_transfer_bindings, -#else - 0, -#endif - sqlite3_update_hook, - sqlite3_user_data, - sqlite3_value_blob, - sqlite3_value_bytes, - sqlite3_value_bytes16, - sqlite3_value_double, - sqlite3_value_int, - sqlite3_value_int64, - sqlite3_value_numeric_type, - sqlite3_value_text, - sqlite3_value_text16, - sqlite3_value_text16be, - sqlite3_value_text16le, - sqlite3_value_type, - sqlite3_vmprintf, - /* - ** The original API set ends here. All extensions can call any - ** of the APIs above provided that the pointer is not NULL. But - ** before calling APIs that follow, extension should check the - ** sqlite3_libversion_number() to make sure they are dealing with - ** a library that is new enough to support that API. - ************************************************************************* - */ - sqlite3_overload_function, - - /* - ** Added after 3.3.13 - */ - sqlite3_prepare_v2, - sqlite3_prepare16_v2, - sqlite3_clear_bindings, - - /* - ** Added for 3.4.1 - */ - sqlite3_create_module_v2, - - /* - ** Added for 3.5.0 - */ - sqlite3_bind_zeroblob, - sqlite3_blob_bytes, - sqlite3_blob_close, - sqlite3_blob_open, - sqlite3_blob_read, - sqlite3_blob_write, - sqlite3_create_collation_v2, - sqlite3_file_control, - sqlite3_memory_highwater, - sqlite3_memory_used, -#ifdef SQLITE_MUTEX_OMIT - 0, - 0, - 0, - 0, - 0, -#else - sqlite3_mutex_alloc, - sqlite3_mutex_enter, - sqlite3_mutex_free, - sqlite3_mutex_leave, - sqlite3_mutex_try, -#endif - sqlite3_open_v2, - sqlite3_release_memory, - sqlite3_result_error_nomem, - sqlite3_result_error_toobig, - sqlite3_sleep, - sqlite3_soft_heap_limit, - sqlite3_vfs_find, - sqlite3_vfs_register, - sqlite3_vfs_unregister, - - /* - ** Added for 3.5.8 - */ - sqlite3_threadsafe, - sqlite3_result_zeroblob, - sqlite3_result_error_code, - sqlite3_test_control, - sqlite3_randomness, - sqlite3_context_db_handle, - - /* - ** Added for 3.6.0 - */ - sqlite3_extended_result_codes, - sqlite3_limit, - sqlite3_next_stmt, - sqlite3_sql, - sqlite3_status, - - /* - ** Added for 3.7.4 - */ - sqlite3_backup_finish, - sqlite3_backup_init, - sqlite3_backup_pagecount, - sqlite3_backup_remaining, - sqlite3_backup_step, -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS - sqlite3_compileoption_get, - sqlite3_compileoption_used, -#else - 0, - 0, -#endif - sqlite3_create_function_v2, - sqlite3_db_config, - sqlite3_db_mutex, - sqlite3_db_status, - sqlite3_extended_errcode, - sqlite3_log, - sqlite3_soft_heap_limit64, - sqlite3_sourceid, - sqlite3_stmt_status, - sqlite3_strnicmp, -#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY - sqlite3_unlock_notify, -#else - 0, -#endif -#ifndef SQLITE_OMIT_WAL - sqlite3_wal_autocheckpoint, - sqlite3_wal_checkpoint, - sqlite3_wal_hook, -#else - 0, - 0, - 0, -#endif - sqlite3_blob_reopen, - sqlite3_vtab_config, - sqlite3_vtab_on_conflict, - sqlite3_close_v2, - sqlite3_db_filename, - sqlite3_db_readonly, - sqlite3_db_release_memory, - sqlite3_errstr, - sqlite3_stmt_busy, - sqlite3_stmt_readonly, - sqlite3_stricmp, - sqlite3_uri_boolean, - sqlite3_uri_int64, - sqlite3_uri_parameter, - sqlite3_vsnprintf, - sqlite3_wal_checkpoint_v2, - /* Version 3.8.7 and later */ - sqlite3_auto_extension, - sqlite3_bind_blob64, - sqlite3_bind_text64, - sqlite3_cancel_auto_extension, - sqlite3_load_extension, - sqlite3_malloc64, - sqlite3_msize, - sqlite3_realloc64, - sqlite3_reset_auto_extension, - sqlite3_result_blob64, - sqlite3_result_text64, - sqlite3_strglob, - /* Version 3.8.11 and later */ - (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup, - sqlite3_value_free, - sqlite3_result_zeroblob64, - sqlite3_bind_zeroblob64, - /* Version 3.9.0 and later */ - sqlite3_value_subtype, - sqlite3_result_subtype, - /* Version 3.10.0 and later */ - sqlite3_status64, - sqlite3_strlike, - sqlite3_db_cacheflush, - /* Version 3.12.0 and later */ - sqlite3_system_errno, - /* Version 3.14.0 and later */ - sqlite3_trace_v2, - sqlite3_expanded_sql, - /* Version 3.18.0 and later */ - sqlite3_set_last_insert_rowid, - /* Version 3.20.0 and later */ - sqlite3_prepare_v3, - sqlite3_prepare16_v3, - sqlite3_bind_pointer, - sqlite3_result_pointer, - sqlite3_value_pointer, - /* Version 3.22.0 and later */ - sqlite3_vtab_nochange, - sqlite3_value_nochange, - sqlite3_vtab_collation, - /* Version 3.24.0 and later */ - sqlite3_keyword_count, - sqlite3_keyword_name, - sqlite3_keyword_check, - sqlite3_str_new, - sqlite3_str_finish, - sqlite3_str_appendf, - sqlite3_str_vappendf, - sqlite3_str_append, - sqlite3_str_appendall, - sqlite3_str_appendchar, - sqlite3_str_reset, - sqlite3_str_errcode, - sqlite3_str_length, - sqlite3_str_value, - /* Version 3.25.0 and later */ - sqlite3_create_window_function, - /* Version 3.26.0 and later */ -#ifdef SQLITE_ENABLE_NORMALIZE - sqlite3_normalized_sql, -#else - 0, -#endif - /* Version 3.28.0 and later */ - sqlite3_stmt_isexplain, - sqlite3_value_frombind, - /* Version 3.30.0 and later */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3_drop_modules, -#else - 0, -#endif - /* Version 3.31.0 and later */ - sqlite3_hard_heap_limit64, - sqlite3_uri_key, - sqlite3_filename_database, - sqlite3_filename_journal, - sqlite3_filename_wal, - /* Version 3.32.0 and later */ - sqlite3_create_filename, - sqlite3_free_filename, - sqlite3_database_file_object, -}; - -/* True if x is the directory separator character -*/ -#if SQLITE_OS_WIN -# define DirSep(X) ((X)=='/'||(X)=='\\') -#else -# define DirSep(X) ((X)=='/') -#endif - -/* -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case a -** default entry point name (sqlite3_extension_init) is used. Use -** of the default name is recommended. -** -** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling sqlite3DbFree(db, ). -*/ -static int sqlite3LoadExtension( - sqlite3 *db, /* Load the extension into this database connection */ - const char *zFile, /* Name of the shared library containing extension */ - const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ - char **pzErrMsg /* Put error message here if not 0 */ -){ - sqlite3_vfs *pVfs = db->pVfs; - void *handle; - sqlite3_loadext_entry xInit; - char *zErrmsg = 0; - const char *zEntry; - char *zAltEntry = 0; - void **aHandle; - u64 nMsg = 300 + sqlite3Strlen30(zFile); - int ii; - int rc; - - /* Shared library endings to try if zFile cannot be loaded as written */ - static const char *azEndings[] = { -#if SQLITE_OS_WIN - "dll" -#elif defined(__APPLE__) - "dylib" -#else - "so" -#endif - }; - - - if( pzErrMsg ) *pzErrMsg = 0; - - /* Ticket #1863. To avoid a creating security problems for older - ** applications that relink against newer versions of SQLite, the - ** ability to run load_extension is turned off by default. One - ** must call either sqlite3_enable_load_extension(db) or - ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0) - ** to turn on extension loading. - */ - if( (db->flags & SQLITE_LoadExtension)==0 ){ - if( pzErrMsg ){ - *pzErrMsg = sqlite3_mprintf("not authorized"); - } - return SQLITE_ERROR; - } - - zEntry = zProc ? zProc : "sqlite3_extension_init"; - - handle = sqlite3OsDlOpen(pVfs, zFile); -#if SQLITE_OS_UNIX || SQLITE_OS_WIN - for(ii=0; ii sqlite3_example_init - ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init - */ - if( xInit==0 && zProc==0 ){ - int iFile, iEntry, c; - int ncFile = sqlite3Strlen30(zFile); - zAltEntry = sqlite3_malloc64(ncFile+30); - if( zAltEntry==0 ){ - sqlite3OsDlClose(pVfs, handle); - return SQLITE_NOMEM_BKPT; - } - memcpy(zAltEntry, "sqlite3_", 8); - for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){} - iFile++; - if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; - for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ - if( sqlite3Isalpha(c) ){ - zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; - } - } - memcpy(zAltEntry+iEntry, "_init", 6); - zEntry = zAltEntry; - xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); - } - if( xInit==0 ){ - if( pzErrMsg ){ - nMsg += sqlite3Strlen30(zEntry); - *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg); - if( zErrmsg ){ - sqlite3_snprintf(nMsg, zErrmsg, - "no entry point [%s] in shared library [%s]", zEntry, zFile); - sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); - } - } - sqlite3OsDlClose(pVfs, handle); - sqlite3_free(zAltEntry); - return SQLITE_ERROR; - } - sqlite3_free(zAltEntry); - rc = xInit(db, &zErrmsg, &sqlite3Apis); - if( rc ){ - if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK; - if( pzErrMsg ){ - *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); - } - sqlite3_free(zErrmsg); - sqlite3OsDlClose(pVfs, handle); - return SQLITE_ERROR; - } - - /* Append the new shared library handle to the db->aExtension array. */ - aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1)); - if( aHandle==0 ){ - return SQLITE_NOMEM_BKPT; - } - if( db->nExtension>0 ){ - memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension); - } - sqlite3DbFree(db, db->aExtension); - db->aExtension = aHandle; - - db->aExtension[db->nExtension++] = handle; - return SQLITE_OK; -} -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. Use "sqlite3_extension_init" if 0 */ - char **pzErrMsg /* Put error message here if not 0 */ -){ - int rc; - sqlite3_mutex_enter(db->mutex); - rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** Call this routine when the database connection is closing in order -** to clean up loaded extensions -*/ -SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){ - int i; - assert( sqlite3_mutex_held(db->mutex) ); - for(i=0; inExtension; i++){ - sqlite3OsDlClose(db->pVfs, db->aExtension[i]); - } - sqlite3DbFree(db, db->aExtension); -} - -/* -** Enable or disable extension loading. Extension loading is disabled by -** default so as not to open security holes in older applications. -*/ -SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ - sqlite3_mutex_enter(db->mutex); - if( onoff ){ - db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc; - }else{ - db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc); - } - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -#endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */ - -/* -** The following object holds the list of automatically loaded -** extensions. -** -** This list is shared across threads. The SQLITE_MUTEX_STATIC_MAIN -** mutex must be held while accessing this list. -*/ -typedef struct sqlite3AutoExtList sqlite3AutoExtList; -static SQLITE_WSD struct sqlite3AutoExtList { - u32 nExt; /* Number of entries in aExt[] */ - void (**aExt)(void); /* Pointers to the extension init functions */ -} sqlite3Autoext = { 0, 0 }; - -/* The "wsdAutoext" macro will resolve to the autoextension -** state vector. If writable static data is unsupported on the target, -** we have to locate the state vector at run-time. In the more common -** case where writable static data is supported, wsdStat can refer directly -** to the "sqlite3Autoext" state vector declared above. -*/ -#ifdef SQLITE_OMIT_WSD -# define wsdAutoextInit \ - sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) -# define wsdAutoext x[0] -#else -# define wsdAutoextInit -# define wsdAutoext sqlite3Autoext -#endif - - -/* -** Register a statically linked extension that is automatically -** loaded by every new database connection. -*/ -SQLITE_API int sqlite3_auto_extension( - void (*xInit)(void) -){ - int rc = SQLITE_OK; -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ){ - return rc; - }else -#endif - { - u32 i; -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); -#endif - wsdAutoextInit; - sqlite3_mutex_enter(mutex); - for(i=0; i=0; i--){ - if( wsdAutoext.aExt[i]==xInit ){ - wsdAutoext.nExt--; - wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt]; - n++; - break; - } - } - sqlite3_mutex_leave(mutex); - return n; -} - -/* -** Reset the automatic extension loading mechanism. -*/ -SQLITE_API void sqlite3_reset_auto_extension(void){ -#ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize()==SQLITE_OK ) -#endif - { -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); -#endif - wsdAutoextInit; - sqlite3_mutex_enter(mutex); - sqlite3_free(wsdAutoext.aExt); - wsdAutoext.aExt = 0; - wsdAutoext.nExt = 0; - sqlite3_mutex_leave(mutex); - } -} - -/* -** Load all automatic extensions. -** -** If anything goes wrong, set an error in the database connection. -*/ -SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){ - u32 i; - int go = 1; - int rc; - sqlite3_loadext_entry xInit; - - wsdAutoextInit; - if( wsdAutoext.nExt==0 ){ - /* Common case: early out without every having to acquire a mutex */ - return; - } - for(i=0; go; i++){ - char *zErrmsg; -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); -#endif -#ifdef SQLITE_OMIT_LOAD_EXTENSION - const sqlite3_api_routines *pThunk = 0; -#else - const sqlite3_api_routines *pThunk = &sqlite3Apis; -#endif - sqlite3_mutex_enter(mutex); - if( i>=wsdAutoext.nExt ){ - xInit = 0; - go = 0; - }else{ - xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i]; - } - sqlite3_mutex_leave(mutex); - zErrmsg = 0; - if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){ - sqlite3ErrorWithMsg(db, rc, - "automatic extension loading failed: %s", zErrmsg); - go = 0; - } - sqlite3_free(zErrmsg); - } -} - -/************** End of loadext.c *********************************************/ -/************** Begin file pragma.c ******************************************/ -/* -** 2003 April 6 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code used to implement the PRAGMA command. -*/ -/* #include "sqliteInt.h" */ - -#if !defined(SQLITE_ENABLE_LOCKING_STYLE) -# if defined(__APPLE__) -# define SQLITE_ENABLE_LOCKING_STYLE 1 -# else -# define SQLITE_ENABLE_LOCKING_STYLE 0 -# endif -#endif - -/*************************************************************************** -** The "pragma.h" include file is an automatically generated file that -** that includes the PragType_XXXX macro definitions and the aPragmaName[] -** object. This ensures that the aPragmaName[] table is arranged in -** lexicographical order to facility a binary search of the pragma name. -** Do not edit pragma.h directly. Edit and rerun the script in at -** ../tool/mkpragmatab.tcl. */ -/************** Include pragma.h in the middle of pragma.c *******************/ -/************** Begin file pragma.h ******************************************/ -/* DO NOT EDIT! -** This file is automatically generated by the script at -** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit -** that script and rerun it. -*/ - -/* The various pragma types */ -#define PragTyp_ACTIVATE_EXTENSIONS 0 -#define PragTyp_ANALYSIS_LIMIT 1 -#define PragTyp_HEADER_VALUE 2 -#define PragTyp_AUTO_VACUUM 3 -#define PragTyp_FLAG 4 -#define PragTyp_BUSY_TIMEOUT 5 -#define PragTyp_CACHE_SIZE 6 -#define PragTyp_CACHE_SPILL 7 -#define PragTyp_CASE_SENSITIVE_LIKE 8 -#define PragTyp_COLLATION_LIST 9 -#define PragTyp_COMPILE_OPTIONS 10 -#define PragTyp_DATA_STORE_DIRECTORY 11 -#define PragTyp_DATABASE_LIST 12 -#define PragTyp_DEFAULT_CACHE_SIZE 13 -#define PragTyp_ENCODING 14 -#define PragTyp_FOREIGN_KEY_CHECK 15 -#define PragTyp_FOREIGN_KEY_LIST 16 -#define PragTyp_FUNCTION_LIST 17 -#define PragTyp_HARD_HEAP_LIMIT 18 -#define PragTyp_INCREMENTAL_VACUUM 19 -#define PragTyp_INDEX_INFO 20 -#define PragTyp_INDEX_LIST 21 -#define PragTyp_INTEGRITY_CHECK 22 -#define PragTyp_JOURNAL_MODE 23 -#define PragTyp_JOURNAL_SIZE_LIMIT 24 -#define PragTyp_LOCK_PROXY_FILE 25 -#define PragTyp_LOCKING_MODE 26 -#define PragTyp_PAGE_COUNT 27 -#define PragTyp_MMAP_SIZE 28 -#define PragTyp_MODULE_LIST 29 -#define PragTyp_OPTIMIZE 30 -#define PragTyp_PAGE_SIZE 31 -#define PragTyp_PRAGMA_LIST 32 -#define PragTyp_SECURE_DELETE 33 -#define PragTyp_SHRINK_MEMORY 34 -#define PragTyp_SOFT_HEAP_LIMIT 35 -#define PragTyp_SYNCHRONOUS 36 -#define PragTyp_TABLE_INFO 37 -#define PragTyp_TEMP_STORE 38 -#define PragTyp_TEMP_STORE_DIRECTORY 39 -#define PragTyp_THREADS 40 -#define PragTyp_WAL_AUTOCHECKPOINT 41 -#define PragTyp_WAL_CHECKPOINT 42 -#define PragTyp_LOCK_STATUS 43 -#define PragTyp_STATS 44 - -/* Property flags associated with various pragma. */ -#define PragFlg_NeedSchema 0x01 /* Force schema load before running */ -#define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */ -#define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */ -#define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */ -#define PragFlg_Result0 0x10 /* Acts as query when no argument */ -#define PragFlg_Result1 0x20 /* Acts as query when has one argument */ -#define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */ -#define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */ - -/* Names of columns for pragmas that return multi-column result -** or that return single-column results where the name of the -** result column is different from the name of the pragma -*/ -static const char *const pragCName[] = { - /* 0 */ "id", /* Used by: foreign_key_list */ - /* 1 */ "seq", - /* 2 */ "table", - /* 3 */ "from", - /* 4 */ "to", - /* 5 */ "on_update", - /* 6 */ "on_delete", - /* 7 */ "match", - /* 8 */ "cid", /* Used by: table_xinfo */ - /* 9 */ "name", - /* 10 */ "type", - /* 11 */ "notnull", - /* 12 */ "dflt_value", - /* 13 */ "pk", - /* 14 */ "hidden", - /* table_info reuses 8 */ - /* 15 */ "seqno", /* Used by: index_xinfo */ - /* 16 */ "cid", - /* 17 */ "name", - /* 18 */ "desc", - /* 19 */ "coll", - /* 20 */ "key", - /* 21 */ "name", /* Used by: function_list */ - /* 22 */ "builtin", - /* 23 */ "type", - /* 24 */ "enc", - /* 25 */ "narg", - /* 26 */ "flags", - /* 27 */ "tbl", /* Used by: stats */ - /* 28 */ "idx", - /* 29 */ "wdth", - /* 30 */ "hght", - /* 31 */ "flgs", - /* 32 */ "seq", /* Used by: index_list */ - /* 33 */ "name", - /* 34 */ "unique", - /* 35 */ "origin", - /* 36 */ "partial", - /* 37 */ "table", /* Used by: foreign_key_check */ - /* 38 */ "rowid", - /* 39 */ "parent", - /* 40 */ "fkid", - /* index_info reuses 15 */ - /* 41 */ "seq", /* Used by: database_list */ - /* 42 */ "name", - /* 43 */ "file", - /* 44 */ "busy", /* Used by: wal_checkpoint */ - /* 45 */ "log", - /* 46 */ "checkpointed", - /* collation_list reuses 32 */ - /* 47 */ "database", /* Used by: lock_status */ - /* 48 */ "status", - /* 49 */ "cache_size", /* Used by: default_cache_size */ - /* module_list pragma_list reuses 9 */ - /* 50 */ "timeout", /* Used by: busy_timeout */ -}; - -/* Definitions of all built-in pragmas */ -typedef struct PragmaName { - const char *const zName; /* Name of pragma */ - u8 ePragTyp; /* PragTyp_XXX value */ - u8 mPragFlg; /* Zero or more PragFlg_XXX values */ - u8 iPragCName; /* Start of column names in pragCName[] */ - u8 nPragCName; /* Num of col names. 0 means use pragma name */ - u64 iArg; /* Extra argument */ -} PragmaName; -static const PragmaName aPragmaName[] = { -#if defined(SQLITE_ENABLE_CEROD) - {/* zName: */ "activate_extensions", - /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif - {/* zName: */ "analysis_limit", - /* ePragTyp: */ PragTyp_ANALYSIS_LIMIT, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - {/* zName: */ "application_id", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ BTREE_APPLICATION_ID }, -#endif -#if !defined(SQLITE_OMIT_AUTOVACUUM) - {/* zName: */ "auto_vacuum", - /* ePragTyp: */ PragTyp_AUTO_VACUUM, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) -#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX) - {/* zName: */ "automatic_index", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_AutoIndex }, -#endif -#endif - {/* zName: */ "busy_timeout", - /* ePragTyp: */ PragTyp_BUSY_TIMEOUT, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 50, 1, - /* iArg: */ 0 }, -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - {/* zName: */ "cache_size", - /* ePragTyp: */ PragTyp_CACHE_SIZE, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "cache_spill", - /* ePragTyp: */ PragTyp_CACHE_SPILL, - /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA) - {/* zName: */ "case_sensitive_like", - /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, - /* ePragFlg: */ PragFlg_NoColumns, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif - {/* zName: */ "cell_size_check", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_CellSizeCk }, -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "checkpoint_fullfsync", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_CkptFullFSync }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - {/* zName: */ "collation_list", - /* ePragTyp: */ PragTyp_COLLATION_LIST, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 32, 2, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) - {/* zName: */ "compile_options", - /* ePragTyp: */ PragTyp_COMPILE_OPTIONS, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "count_changes", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_CountRows }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN - {/* zName: */ "data_store_directory", - /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, - /* ePragFlg: */ PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - {/* zName: */ "data_version", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ BTREE_DATA_VERSION }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - {/* zName: */ "database_list", - /* ePragTyp: */ PragTyp_DATABASE_LIST, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0, - /* ColNames: */ 41, 3, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) - {/* zName: */ "default_cache_size", - /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, - /* ColNames: */ 49, 1, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - {/* zName: */ "defer_foreign_keys", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_DeferFKs }, -#endif -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "empty_result_callbacks", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_NullCallback }, -#endif -#if !defined(SQLITE_OMIT_UTF16) - {/* zName: */ "encoding", - /* ePragTyp: */ PragTyp_ENCODING, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - {/* zName: */ "foreign_key_check", - /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 37, 4, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FOREIGN_KEY) - {/* zName: */ "foreign_key_list", - /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 0, 8, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - {/* zName: */ "foreign_keys", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_ForeignKeys }, -#endif -#endif -#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - {/* zName: */ "freelist_count", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ BTREE_FREE_PAGE_COUNT }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "full_column_names", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_FullColNames }, - {/* zName: */ "fullfsync", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_FullFSync }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) -#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) - {/* zName: */ "function_list", - /* ePragTyp: */ PragTyp_FUNCTION_LIST, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 21, 6, - /* iArg: */ 0 }, -#endif -#endif - {/* zName: */ "hard_heap_limit", - /* ePragTyp: */ PragTyp_HARD_HEAP_LIMIT, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) -#if !defined(SQLITE_OMIT_CHECK) - {/* zName: */ "ignore_check_constraints", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_IgnoreChecks }, -#endif -#endif -#if !defined(SQLITE_OMIT_AUTOVACUUM) - {/* zName: */ "incremental_vacuum", - /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - {/* zName: */ "index_info", - /* ePragTyp: */ PragTyp_INDEX_INFO, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 15, 3, - /* iArg: */ 0 }, - {/* zName: */ "index_list", - /* ePragTyp: */ PragTyp_INDEX_LIST, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 32, 5, - /* iArg: */ 0 }, - {/* zName: */ "index_xinfo", - /* ePragTyp: */ PragTyp_INDEX_INFO, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 15, 6, - /* iArg: */ 1 }, -#endif -#if !defined(SQLITE_OMIT_INTEGRITY_CHECK) - {/* zName: */ "integrity_check", - /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - {/* zName: */ "journal_mode", - /* ePragTyp: */ PragTyp_JOURNAL_MODE, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "journal_size_limit", - /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT, - /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "legacy_alter_table", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_LegacyAlter }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE - {/* zName: */ "lock_proxy_file", - /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE, - /* ePragFlg: */ PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - {/* zName: */ "lock_status", - /* ePragTyp: */ PragTyp_LOCK_STATUS, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 47, 2, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - {/* zName: */ "locking_mode", - /* ePragTyp: */ PragTyp_LOCKING_MODE, - /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "max_page_count", - /* ePragTyp: */ PragTyp_PAGE_COUNT, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "mmap_size", - /* ePragTyp: */ PragTyp_MMAP_SIZE, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) -#if !defined(SQLITE_OMIT_VIRTUALTABLE) -#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) - {/* zName: */ "module_list", - /* ePragTyp: */ PragTyp_MODULE_LIST, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 9, 1, - /* iArg: */ 0 }, -#endif -#endif -#endif - {/* zName: */ "optimize", - /* ePragTyp: */ PragTyp_OPTIMIZE, - /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - {/* zName: */ "page_count", - /* ePragTyp: */ PragTyp_PAGE_COUNT, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "page_size", - /* ePragTyp: */ PragTyp_PAGE_SIZE, - /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) -#if defined(SQLITE_DEBUG) - {/* zName: */ "parser_trace", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_ParserTrace }, -#endif -#endif -#if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) - {/* zName: */ "pragma_list", - /* ePragTyp: */ PragTyp_PRAGMA_LIST, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 9, 1, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "query_only", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_QueryOnly }, -#endif -#if !defined(SQLITE_OMIT_INTEGRITY_CHECK) - {/* zName: */ "quick_check", - /* ePragTyp: */ PragTyp_INTEGRITY_CHECK, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "read_uncommitted", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_ReadUncommit }, - {/* zName: */ "recursive_triggers", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_RecTriggers }, - {/* zName: */ "reverse_unordered_selects", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_ReverseOrder }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - {/* zName: */ "schema_version", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ BTREE_SCHEMA_VERSION }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - {/* zName: */ "secure_delete", - /* ePragTyp: */ PragTyp_SECURE_DELETE, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "short_column_names", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_ShortColNames }, -#endif - {/* zName: */ "shrink_memory", - /* ePragTyp: */ PragTyp_SHRINK_MEMORY, - /* ePragFlg: */ PragFlg_NoColumns, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "soft_heap_limit", - /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) -#if defined(SQLITE_DEBUG) - {/* zName: */ "sql_trace", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_SqlTrace }, -#endif -#endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG) - {/* zName: */ "stats", - /* ePragTyp: */ PragTyp_STATS, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, - /* ColNames: */ 27, 5, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - {/* zName: */ "synchronous", - /* ePragTyp: */ PragTyp_SYNCHRONOUS, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - {/* zName: */ "table_info", - /* ePragTyp: */ PragTyp_TABLE_INFO, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 8, 6, - /* iArg: */ 0 }, - {/* zName: */ "table_xinfo", - /* ePragTyp: */ PragTyp_TABLE_INFO, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 8, 7, - /* iArg: */ 1 }, -#endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - {/* zName: */ "temp_store", - /* ePragTyp: */ PragTyp_TEMP_STORE, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "temp_store_directory", - /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY, - /* ePragFlg: */ PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif - {/* zName: */ "threads", - /* ePragTyp: */ PragTyp_THREADS, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "trusted_schema", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_TrustedSchema }, -#endif -#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - {/* zName: */ "user_version", - /* ePragTyp: */ PragTyp_HEADER_VALUE, - /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0, - /* ColNames: */ 0, 0, - /* iArg: */ BTREE_USER_VERSION }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) -#if defined(SQLITE_DEBUG) - {/* zName: */ "vdbe_addoptrace", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_VdbeAddopTrace }, - {/* zName: */ "vdbe_debug", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace }, - {/* zName: */ "vdbe_eqp", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_VdbeEQP }, - {/* zName: */ "vdbe_listing", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_VdbeListing }, - {/* zName: */ "vdbe_trace", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_VdbeTrace }, -#endif -#endif -#if !defined(SQLITE_OMIT_WAL) - {/* zName: */ "wal_autocheckpoint", - /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "wal_checkpoint", - /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, - /* ePragFlg: */ PragFlg_NeedSchema, - /* ColNames: */ 44, 3, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "writable_schema", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError }, -#endif -}; -/* Number of pragmas: 67 on by default, 77 total. */ - -/************** End of pragma.h **********************************************/ -/************** Continuing where we left off in pragma.c *********************/ - -/* -** Interpret the given string as a safety level. Return 0 for OFF, -** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or -** unrecognized string argument. The FULL and EXTRA option is disallowed -** if the omitFull parameter it 1. -** -** Note that the values returned are one less that the values that -** should be passed into sqlite3BtreeSetSafetyLevel(). The is done -** to support legacy SQL code. The safety level used to be boolean -** and older scripts may have used numbers 0 for OFF and 1 for ON. -*/ -static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){ - /* 123456789 123456789 123 */ - static const char zText[] = "onoffalseyestruextrafull"; - static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20}; - static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4}; - static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2}; - /* on no off false yes true extra full */ - int i, n; - if( sqlite3Isdigit(*z) ){ - return (u8)sqlite3Atoi(z); - } - n = sqlite3Strlen30(z); - for(i=0; i=0&&i<=2)?i:0); -} -#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */ - -#ifndef SQLITE_OMIT_PAGER_PRAGMAS -/* -** Interpret the given string as a temp db location. Return 1 for file -** backed temporary databases, 2 for the Red-Black tree in memory database -** and 0 to use the compile-time default. -*/ -static int getTempStore(const char *z){ - if( z[0]>='0' && z[0]<='2' ){ - return z[0] - '0'; - }else if( sqlite3StrICmp(z, "file")==0 ){ - return 1; - }else if( sqlite3StrICmp(z, "memory")==0 ){ - return 2; - }else{ - return 0; - } -} -#endif /* SQLITE_PAGER_PRAGMAS */ - -#ifndef SQLITE_OMIT_PAGER_PRAGMAS -/* -** Invalidate temp storage, either when the temp storage is changed -** from default, or when 'file' and the temp_store_directory has changed -*/ -static int invalidateTempStorage(Parse *pParse){ - sqlite3 *db = pParse->db; - if( db->aDb[1].pBt!=0 ){ - if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ - sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " - "from within a transaction"); - return SQLITE_ERROR; - } - sqlite3BtreeClose(db->aDb[1].pBt); - db->aDb[1].pBt = 0; - sqlite3ResetAllSchemasOfConnection(db); - } - return SQLITE_OK; -} -#endif /* SQLITE_PAGER_PRAGMAS */ - -#ifndef SQLITE_OMIT_PAGER_PRAGMAS -/* -** If the TEMP database is open, close it and mark the database schema -** as needing reloading. This must be done when using the SQLITE_TEMP_STORE -** or DEFAULT_TEMP_STORE pragmas. -*/ -static int changeTempStorage(Parse *pParse, const char *zStorageType){ - int ts = getTempStore(zStorageType); - sqlite3 *db = pParse->db; - if( db->temp_store==ts ) return SQLITE_OK; - if( invalidateTempStorage( pParse ) != SQLITE_OK ){ - return SQLITE_ERROR; - } - db->temp_store = (u8)ts; - return SQLITE_OK; -} -#endif /* SQLITE_PAGER_PRAGMAS */ - -/* -** Set result column names for a pragma. -*/ -static void setPragmaResultColumnNames( - Vdbe *v, /* The query under construction */ - const PragmaName *pPragma /* The pragma */ -){ - u8 n = pPragma->nPragCName; - sqlite3VdbeSetNumCols(v, n==0 ? 1 : n); - if( n==0 ){ - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC); - }else{ - int i, j; - for(i=0, j=pPragma->iPragCName; iautoCommit ){ - Db *pDb = db->aDb; - int n = db->nDb; - assert( SQLITE_FullFSync==PAGER_FULLFSYNC ); - assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC ); - assert( SQLITE_CacheSpill==PAGER_CACHESPILL ); - assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL) - == PAGER_FLAGS_MASK ); - assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level ); - while( (n--) > 0 ){ - if( pDb->pBt ){ - sqlite3BtreeSetPagerFlags(pDb->pBt, - pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) ); - } - pDb++; - } - } -} -#else -# define setAllPagerFlags(X) /* no-op */ -#endif - - -/* -** Return a human-readable name for a constraint resolution action. -*/ -#ifndef SQLITE_OMIT_FOREIGN_KEY -static const char *actionName(u8 action){ - const char *zName; - switch( action ){ - case OE_SetNull: zName = "SET NULL"; break; - case OE_SetDflt: zName = "SET DEFAULT"; break; - case OE_Cascade: zName = "CASCADE"; break; - case OE_Restrict: zName = "RESTRICT"; break; - default: zName = "NO ACTION"; - assert( action==OE_None ); break; - } - return zName; -} -#endif - - -/* -** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants -** defined in pager.h. This function returns the associated lowercase -** journal-mode name. -*/ -SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){ - static char * const azModeName[] = { - "delete", "persist", "off", "truncate", "memory" -#ifndef SQLITE_OMIT_WAL - , "wal" -#endif - }; - assert( PAGER_JOURNALMODE_DELETE==0 ); - assert( PAGER_JOURNALMODE_PERSIST==1 ); - assert( PAGER_JOURNALMODE_OFF==2 ); - assert( PAGER_JOURNALMODE_TRUNCATE==3 ); - assert( PAGER_JOURNALMODE_MEMORY==4 ); - assert( PAGER_JOURNALMODE_WAL==5 ); - assert( eMode>=0 && eMode<=ArraySize(azModeName) ); - - if( eMode==ArraySize(azModeName) ) return 0; - return azModeName[eMode]; -} - -/* -** Locate a pragma in the aPragmaName[] array. -*/ -static const PragmaName *pragmaLocate(const char *zName){ - int upr, lwr, mid = 0, rc; - lwr = 0; - upr = ArraySize(aPragmaName)-1; - while( lwr<=upr ){ - mid = (lwr+upr)/2; - rc = sqlite3_stricmp(zName, aPragmaName[mid].zName); - if( rc==0 ) break; - if( rc<0 ){ - upr = mid - 1; - }else{ - lwr = mid + 1; - } - } - return lwr>upr ? 0 : &aPragmaName[mid]; -} - -/* -** Create zero or more entries in the output for the SQL functions -** defined by FuncDef p. -*/ -static void pragmaFunclistLine( - Vdbe *v, /* The prepared statement being created */ - FuncDef *p, /* A particular function definition */ - int isBuiltin, /* True if this is a built-in function */ - int showInternFuncs /* True if showing internal functions */ -){ - for(; p; p=p->pNext){ - const char *zType; - static const u32 mask = - SQLITE_DETERMINISTIC | - SQLITE_DIRECTONLY | - SQLITE_SUBTYPE | - SQLITE_INNOCUOUS | - SQLITE_FUNC_INTERNAL - ; - static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" }; - - assert( SQLITE_FUNC_ENCMASK==0x3 ); - assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 ); - assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 ); - assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 ); - - if( p->xSFunc==0 ) continue; - if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0 - && showInternFuncs==0 - ){ - continue; - } - if( p->xValue!=0 ){ - zType = "w"; - }else if( p->xFinalize!=0 ){ - zType = "a"; - }else{ - zType = "s"; - } - sqlite3VdbeMultiLoad(v, 1, "sissii", - p->zName, isBuiltin, - zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK], - p->nArg, - (p->funcFlags & mask) ^ SQLITE_INNOCUOUS - ); - } -} - - -/* -** Helper subroutine for PRAGMA integrity_check: -** -** Generate code to output a single-column result row with a value of the -** string held in register 3. Decrement the result count in register 1 -** and halt if the maximum number of result rows have been issued. -*/ -static int integrityCheckResultRow(Vdbe *v){ - int addr; - sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1); - addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1); - VdbeCoverage(v); - sqlite3VdbeAddOp0(v, OP_Halt); - return addr; -} - -/* -** Process a pragma statement. -** -** Pragmas are of this form: -** -** PRAGMA [schema.]id [= value] -** -** The identifier might also be a string. The value is a string, and -** identifier, or a number. If minusFlag is true, then the value is -** a number that was preceded by a minus sign. -** -** If the left side is "database.id" then pId1 is the database name -** and pId2 is the id. If the left side is just "id" then pId1 is the -** id and pId2 is any empty string. -*/ -SQLITE_PRIVATE void sqlite3Pragma( - Parse *pParse, - Token *pId1, /* First part of [schema.]id field */ - Token *pId2, /* Second part of [schema.]id field, or NULL */ - Token *pValue, /* Token for , or NULL */ - int minusFlag /* True if a '-' sign preceded */ -){ - char *zLeft = 0; /* Nul-terminated UTF-8 string */ - char *zRight = 0; /* Nul-terminated UTF-8 string , or NULL */ - const char *zDb = 0; /* The database name */ - Token *pId; /* Pointer to token */ - char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ - int iDb; /* Database index for */ - int rc; /* return value form SQLITE_FCNTL_PRAGMA */ - sqlite3 *db = pParse->db; /* The database connection */ - Db *pDb; /* The specific database being pragmaed */ - Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ - const PragmaName *pPragma; /* The pragma */ - - if( v==0 ) return; - sqlite3VdbeRunOnlyOnce(v); - pParse->nMem = 2; - - /* Interpret the [schema.] part of the pragma statement. iDb is the - ** index of the database this pragma is being applied to in db.aDb[]. */ - iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); - if( iDb<0 ) return; - pDb = &db->aDb[iDb]; - - /* If the temp database has been explicitly named as part of the - ** pragma, make sure it is open. - */ - if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ - return; - } - - zLeft = sqlite3NameFromToken(db, pId); - if( !zLeft ) return; - if( minusFlag ){ - zRight = sqlite3MPrintf(db, "-%T", pValue); - }else{ - zRight = sqlite3NameFromToken(db, pValue); - } - - assert( pId2 ); - zDb = pId2->n>0 ? pDb->zDbSName : 0; - if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ - goto pragma_out; - } - - /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS - ** connection. If it returns SQLITE_OK, then assume that the VFS - ** handled the pragma and generate a no-op prepared statement. - ** - ** IMPLEMENTATION-OF: R-12238-55120 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. - ** - ** IMPLEMENTATION-OF: R-29875-31678 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. - */ - aFcntl[0] = 0; - aFcntl[1] = zLeft; - aFcntl[2] = zRight; - aFcntl[3] = 0; - db->busyHandler.nBusy = 0; - rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); - if( rc==SQLITE_OK ){ - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); - returnSingleText(v, aFcntl[0]); - sqlite3_free(aFcntl[0]); - goto pragma_out; - } - if( rc!=SQLITE_NOTFOUND ){ - if( aFcntl[0] ){ - sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); - sqlite3_free(aFcntl[0]); - } - pParse->nErr++; - pParse->rc = rc; - goto pragma_out; - } - - /* Locate the pragma in the lookup table */ - pPragma = pragmaLocate(zLeft); - if( pPragma==0 ) goto pragma_out; - - /* Make sure the database schema is loaded if the pragma requires that */ - if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){ - if( sqlite3ReadSchema(pParse) ) goto pragma_out; - } - - /* Register the result column names for pragmas that return results */ - if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 - && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0) - ){ - setPragmaResultColumnNames(v, pPragma); - } - - /* Jump to the appropriate pragma handler */ - switch( pPragma->ePragTyp ){ - -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) - /* - ** PRAGMA [schema.]default_cache_size - ** PRAGMA [schema.]default_cache_size=N - ** - ** The first form reports the current persistent setting for the - ** page cache size. The value returned is the maximum number of - ** pages in the page cache. The second form sets both the current - ** page cache size value and the persistent page cache size value - ** stored in the database file. - ** - ** Older versions of SQLite would set the default cache size to a - ** negative number to indicate synchronous=OFF. These days, synchronous - ** is always on by default regardless of the sign of the default cache - ** size. But continue to take the absolute value of the default cache - ** size of historical compatibility. - */ - case PragTyp_DEFAULT_CACHE_SIZE: { - static const int iLn = VDBE_OFFSET_LINENO(2); - static const VdbeOpList getCacheSize[] = { - { OP_Transaction, 0, 0, 0}, /* 0 */ - { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */ - { OP_IfPos, 1, 8, 0}, - { OP_Integer, 0, 2, 0}, - { OP_Subtract, 1, 2, 1}, - { OP_IfPos, 1, 8, 0}, - { OP_Integer, 0, 1, 0}, /* 6 */ - { OP_Noop, 0, 0, 0}, - { OP_ResultRow, 1, 1, 0}, - }; - VdbeOp *aOp; - sqlite3VdbeUsesBtree(v, iDb); - if( !zRight ){ - pParse->nMem += 2; - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); - if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; - aOp[0].p1 = iDb; - aOp[1].p1 = iDb; - aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; - }else{ - int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pDb->pSchema->cache_size = size; - sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); - } - break; - } -#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */ - -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) - /* - ** PRAGMA [schema.]page_size - ** PRAGMA [schema.]page_size=N - ** - ** The first form reports the current setting for the - ** database page size in bytes. The second form sets the - ** database page size value. The value can only be set if - ** the database has not yet been created. - */ - case PragTyp_PAGE_SIZE: { - Btree *pBt = pDb->pBt; - assert( pBt!=0 ); - if( !zRight ){ - int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; - returnSingleInt(v, size); - }else{ - /* Malloc may fail when setting the page-size, as there is an internal - ** buffer that the pager module resizes using sqlite3_realloc(). - */ - db->nextPagesize = sqlite3Atoi(zRight); - if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){ - sqlite3OomFault(db); - } - } - break; - } - - /* - ** PRAGMA [schema.]secure_delete - ** PRAGMA [schema.]secure_delete=ON/OFF/FAST - ** - ** The first form reports the current setting for the - ** secure_delete flag. The second form changes the secure_delete - ** flag setting and reports the new value. - */ - case PragTyp_SECURE_DELETE: { - Btree *pBt = pDb->pBt; - int b = -1; - assert( pBt!=0 ); - if( zRight ){ - if( sqlite3_stricmp(zRight, "fast")==0 ){ - b = 2; - }else{ - b = sqlite3GetBoolean(zRight, 0); - } - } - if( pId2->n==0 && b>=0 ){ - int ii; - for(ii=0; iinDb; ii++){ - sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); - } - } - b = sqlite3BtreeSecureDelete(pBt, b); - returnSingleInt(v, b); - break; - } - - /* - ** PRAGMA [schema.]max_page_count - ** PRAGMA [schema.]max_page_count=N - ** - ** The first form reports the current setting for the - ** maximum number of pages in the database file. The - ** second form attempts to change this setting. Both - ** forms return the current setting. - ** - ** The absolute value of N is used. This is undocumented and might - ** change. The only purpose is to provide an easy way to test - ** the sqlite3AbsInt32() function. - ** - ** PRAGMA [schema.]page_count - ** - ** Return the number of pages in the specified database. - */ - case PragTyp_PAGE_COUNT: { - int iReg; - i64 x = 0; - sqlite3CodeVerifySchema(pParse, iDb); - iReg = ++pParse->nMem; - if( sqlite3Tolower(zLeft[0])=='p' ){ - sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); - }else{ - if( zRight && sqlite3DecOrHexToI64(zRight,&x)==0 ){ - if( x<0 ) x = 0; - else if( x>0xfffffffe ) x = 0xfffffffe; - }else{ - x = 0; - } - sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, (int)x); - } - sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); - break; - } - - /* - ** PRAGMA [schema.]locking_mode - ** PRAGMA [schema.]locking_mode = (normal|exclusive) - */ - case PragTyp_LOCKING_MODE: { - const char *zRet = "normal"; - int eMode = getLockingMode(zRight); - - if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ - /* Simple "PRAGMA locking_mode;" statement. This is a query for - ** the current default locking mode (which may be different to - ** the locking-mode of the main database). - */ - eMode = db->dfltLockMode; - }else{ - Pager *pPager; - if( pId2->n==0 ){ - /* This indicates that no database name was specified as part - ** of the PRAGMA command. In this case the locking-mode must be - ** set on all attached databases, as well as the main db file. - ** - ** Also, the sqlite3.dfltLockMode variable is set so that - ** any subsequently attached databases also use the specified - ** locking mode. - */ - int ii; - assert(pDb==&db->aDb[0]); - for(ii=2; iinDb; ii++){ - pPager = sqlite3BtreePager(db->aDb[ii].pBt); - sqlite3PagerLockingMode(pPager, eMode); - } - db->dfltLockMode = (u8)eMode; - } - pPager = sqlite3BtreePager(pDb->pBt); - eMode = sqlite3PagerLockingMode(pPager, eMode); - } - - assert( eMode==PAGER_LOCKINGMODE_NORMAL - || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); - if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ - zRet = "exclusive"; - } - returnSingleText(v, zRet); - break; - } - - /* - ** PRAGMA [schema.]journal_mode - ** PRAGMA [schema.]journal_mode = - ** (delete|persist|off|truncate|memory|wal|off) - */ - case PragTyp_JOURNAL_MODE: { - int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ - int ii; /* Loop counter */ - - if( zRight==0 ){ - /* If there is no "=MODE" part of the pragma, do a query for the - ** current mode */ - eMode = PAGER_JOURNALMODE_QUERY; - }else{ - const char *zMode; - int n = sqlite3Strlen30(zRight); - for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ - if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; - } - if( !zMode ){ - /* If the "=MODE" part does not match any known journal mode, - ** then do a query */ - eMode = PAGER_JOURNALMODE_QUERY; - } - if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){ - /* Do not allow journal-mode "OFF" in defensive since the database - ** can become corrupted using ordinary SQL when the journal is off */ - eMode = PAGER_JOURNALMODE_QUERY; - } - } - if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ - /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ - iDb = 0; - pId2->n = 1; - } - for(ii=db->nDb-1; ii>=0; ii--){ - if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ - sqlite3VdbeUsesBtree(v, ii); - sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); - } - } - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); - break; - } - - /* - ** PRAGMA [schema.]journal_size_limit - ** PRAGMA [schema.]journal_size_limit=N - ** - ** Get or set the size limit on rollback journal files. - */ - case PragTyp_JOURNAL_SIZE_LIMIT: { - Pager *pPager = sqlite3BtreePager(pDb->pBt); - i64 iLimit = -2; - if( zRight ){ - sqlite3DecOrHexToI64(zRight, &iLimit); - if( iLimit<-1 ) iLimit = -1; - } - iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); - returnSingleInt(v, iLimit); - break; - } - -#endif /* SQLITE_OMIT_PAGER_PRAGMAS */ - - /* - ** PRAGMA [schema.]auto_vacuum - ** PRAGMA [schema.]auto_vacuum=N - ** - ** Get or set the value of the database 'auto-vacuum' parameter. - ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL - */ -#ifndef SQLITE_OMIT_AUTOVACUUM - case PragTyp_AUTO_VACUUM: { - Btree *pBt = pDb->pBt; - assert( pBt!=0 ); - if( !zRight ){ - returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt)); - }else{ - int eAuto = getAutoVacuum(zRight); - assert( eAuto>=0 && eAuto<=2 ); - db->nextAutovac = (u8)eAuto; - /* Call SetAutoVacuum() to set initialize the internal auto and - ** incr-vacuum flags. This is required in case this connection - ** creates the database file. It is important that it is created - ** as an auto-vacuum capable db. - */ - rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); - if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ - /* When setting the auto_vacuum mode to either "full" or - ** "incremental", write the value of meta[6] in the database - ** file. Before writing to meta[6], check that meta[3] indicates - ** that this really is an auto-vacuum capable database. - */ - static const int iLn = VDBE_OFFSET_LINENO(2); - static const VdbeOpList setMeta6[] = { - { OP_Transaction, 0, 1, 0}, /* 0 */ - { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, - { OP_If, 1, 0, 0}, /* 2 */ - { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ - { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */ - }; - VdbeOp *aOp; - int iAddr = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); - if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; - aOp[0].p1 = iDb; - aOp[1].p1 = iDb; - aOp[2].p2 = iAddr+4; - aOp[4].p1 = iDb; - aOp[4].p3 = eAuto - 1; - sqlite3VdbeUsesBtree(v, iDb); - } - } - break; - } -#endif - - /* - ** PRAGMA [schema.]incremental_vacuum(N) - ** - ** Do N steps of incremental vacuuming on a database. - */ -#ifndef SQLITE_OMIT_AUTOVACUUM - case PragTyp_INCREMENTAL_VACUUM: { - int iLimit, addr; - if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ - iLimit = 0x7fffffff; - } - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); - addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); - sqlite3VdbeAddOp1(v, OP_ResultRow, 1); - sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); - sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr); - break; - } -#endif - -#ifndef SQLITE_OMIT_PAGER_PRAGMAS - /* - ** PRAGMA [schema.]cache_size - ** PRAGMA [schema.]cache_size=N - ** - ** The first form reports the current local setting for the - ** page cache size. The second form sets the local - ** page cache size value. If N is positive then that is the - ** number of pages in the cache. If N is negative, then the - ** number of pages is adjusted so that the cache uses -N kibibytes - ** of memory. - */ - case PragTyp_CACHE_SIZE: { - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( !zRight ){ - returnSingleInt(v, pDb->pSchema->cache_size); - }else{ - int size = sqlite3Atoi(zRight); - pDb->pSchema->cache_size = size; - sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); - } - break; - } - - /* - ** PRAGMA [schema.]cache_spill - ** PRAGMA cache_spill=BOOLEAN - ** PRAGMA [schema.]cache_spill=N - ** - ** The first form reports the current local setting for the - ** page cache spill size. The second form turns cache spill on - ** or off. When turnning cache spill on, the size is set to the - ** current cache_size. The third form sets a spill size that - ** may be different form the cache size. - ** If N is positive then that is the - ** number of pages in the cache. If N is negative, then the - ** number of pages is adjusted so that the cache uses -N kibibytes - ** of memory. - ** - ** If the number of cache_spill pages is less then the number of - ** cache_size pages, no spilling occurs until the page count exceeds - ** the number of cache_size pages. - ** - ** The cache_spill=BOOLEAN setting applies to all attached schemas, - ** not just the schema specified. - */ - case PragTyp_CACHE_SPILL: { - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( !zRight ){ - returnSingleInt(v, - (db->flags & SQLITE_CacheSpill)==0 ? 0 : - sqlite3BtreeSetSpillSize(pDb->pBt,0)); - }else{ - int size = 1; - if( sqlite3GetInt32(zRight, &size) ){ - sqlite3BtreeSetSpillSize(pDb->pBt, size); - } - if( sqlite3GetBoolean(zRight, size!=0) ){ - db->flags |= SQLITE_CacheSpill; - }else{ - db->flags &= ~(u64)SQLITE_CacheSpill; - } - setAllPagerFlags(db); - } - break; - } - - /* - ** PRAGMA [schema.]mmap_size(N) - ** - ** Used to set mapping size limit. The mapping size limit is - ** used to limit the aggregate size of all memory mapped regions of the - ** database file. If this parameter is set to zero, then memory mapping - ** is not used at all. If N is negative, then the default memory map - ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. - ** The parameter N is measured in bytes. - ** - ** This value is advisory. The underlying VFS is free to memory map - ** as little or as much as it wants. Except, if N is set to 0 then the - ** upper layers will never invoke the xFetch interfaces to the VFS. - */ - case PragTyp_MMAP_SIZE: { - sqlite3_int64 sz; -#if SQLITE_MAX_MMAP_SIZE>0 - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( zRight ){ - int ii; - sqlite3DecOrHexToI64(zRight, &sz); - if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; - if( pId2->n==0 ) db->szMmap = sz; - for(ii=db->nDb-1; ii>=0; ii--){ - if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ - sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); - } - } - } - sz = -1; - rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); -#else - sz = 0; - rc = SQLITE_OK; -#endif - if( rc==SQLITE_OK ){ - returnSingleInt(v, sz); - }else if( rc!=SQLITE_NOTFOUND ){ - pParse->nErr++; - pParse->rc = rc; - } - break; - } - - /* - ** PRAGMA temp_store - ** PRAGMA temp_store = "default"|"memory"|"file" - ** - ** Return or set the local value of the temp_store flag. Changing - ** the local value does not make changes to the disk file and the default - ** value will be restored the next time the database is opened. - ** - ** Note that it is possible for the library compile-time options to - ** override this setting - */ - case PragTyp_TEMP_STORE: { - if( !zRight ){ - returnSingleInt(v, db->temp_store); - }else{ - changeTempStorage(pParse, zRight); - } - break; - } - - /* - ** PRAGMA temp_store_directory - ** PRAGMA temp_store_directory = ""|"directory_name" - ** - ** Return or set the local value of the temp_store_directory flag. Changing - ** the value sets a specific directory to be used for temporary files. - ** Setting to a null string reverts to the default temporary directory search. - ** If temporary directory is changed, then invalidateTempStorage. - ** - */ - case PragTyp_TEMP_STORE_DIRECTORY: { - if( !zRight ){ - returnSingleText(v, sqlite3_temp_directory); - }else{ -#ifndef SQLITE_OMIT_WSD - if( zRight[0] ){ - int res; - rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); - if( rc!=SQLITE_OK || res==0 ){ - sqlite3ErrorMsg(pParse, "not a writable directory"); - goto pragma_out; - } - } - if( SQLITE_TEMP_STORE==0 - || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) - || (SQLITE_TEMP_STORE==2 && db->temp_store==1) - ){ - invalidateTempStorage(pParse); - } - sqlite3_free(sqlite3_temp_directory); - if( zRight[0] ){ - sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); - }else{ - sqlite3_temp_directory = 0; - } -#endif /* SQLITE_OMIT_WSD */ - } - break; - } - -#if SQLITE_OS_WIN - /* - ** PRAGMA data_store_directory - ** PRAGMA data_store_directory = ""|"directory_name" - ** - ** Return or set the local value of the data_store_directory flag. Changing - ** the value sets a specific directory to be used for database files that - ** were specified with a relative pathname. Setting to a null string reverts - ** to the default database directory, which for database files specified with - ** a relative path will probably be based on the current directory for the - ** process. Database file specified with an absolute path are not impacted - ** by this setting, regardless of its value. - ** - */ - case PragTyp_DATA_STORE_DIRECTORY: { - if( !zRight ){ - returnSingleText(v, sqlite3_data_directory); - }else{ -#ifndef SQLITE_OMIT_WSD - if( zRight[0] ){ - int res; - rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); - if( rc!=SQLITE_OK || res==0 ){ - sqlite3ErrorMsg(pParse, "not a writable directory"); - goto pragma_out; - } - } - sqlite3_free(sqlite3_data_directory); - if( zRight[0] ){ - sqlite3_data_directory = sqlite3_mprintf("%s", zRight); - }else{ - sqlite3_data_directory = 0; - } -#endif /* SQLITE_OMIT_WSD */ - } - break; - } -#endif - -#if SQLITE_ENABLE_LOCKING_STYLE - /* - ** PRAGMA [schema.]lock_proxy_file - ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path" - ** - ** Return or set the value of the lock_proxy_file flag. Changing - ** the value sets a specific file to be used for database access locks. - ** - */ - case PragTyp_LOCK_PROXY_FILE: { - if( !zRight ){ - Pager *pPager = sqlite3BtreePager(pDb->pBt); - char *proxy_file_path = NULL; - sqlite3_file *pFile = sqlite3PagerFile(pPager); - sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, - &proxy_file_path); - returnSingleText(v, proxy_file_path); - }else{ - Pager *pPager = sqlite3BtreePager(pDb->pBt); - sqlite3_file *pFile = sqlite3PagerFile(pPager); - int res; - if( zRight[0] ){ - res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, - zRight); - } else { - res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, - NULL); - } - if( res!=SQLITE_OK ){ - sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); - goto pragma_out; - } - } - break; - } -#endif /* SQLITE_ENABLE_LOCKING_STYLE */ - - /* - ** PRAGMA [schema.]synchronous - ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA - ** - ** Return or set the local value of the synchronous flag. Changing - ** the local value does not make changes to the disk file and the - ** default value will be restored the next time the database is - ** opened. - */ - case PragTyp_SYNCHRONOUS: { - if( !zRight ){ - returnSingleInt(v, pDb->safety_level-1); - }else{ - if( !db->autoCommit ){ - sqlite3ErrorMsg(pParse, - "Safety level may not be changed inside a transaction"); - }else if( iDb!=1 ){ - int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; - if( iLevel==0 ) iLevel = 1; - pDb->safety_level = iLevel; - pDb->bSyncSet = 1; - setAllPagerFlags(db); - } - } - break; - } -#endif /* SQLITE_OMIT_PAGER_PRAGMAS */ - -#ifndef SQLITE_OMIT_FLAG_PRAGMAS - case PragTyp_FLAG: { - if( zRight==0 ){ - setPragmaResultColumnNames(v, pPragma); - returnSingleInt(v, (db->flags & pPragma->iArg)!=0 ); - }else{ - u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */ - if( db->autoCommit==0 ){ - /* Foreign key support may not be enabled or disabled while not - ** in auto-commit mode. */ - mask &= ~(SQLITE_ForeignKeys); - } -#if SQLITE_USER_AUTHENTICATION - if( db->auth.authLevel==UAUTH_User ){ - /* Do not allow non-admin users to modify the schema arbitrarily */ - mask &= ~(SQLITE_WriteSchema); - } -#endif - - if( sqlite3GetBoolean(zRight, 0) ){ - db->flags |= mask; - }else{ - db->flags &= ~mask; - if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; - } - - /* Many of the flag-pragmas modify the code generated by the SQL - ** compiler (eg. count_changes). So add an opcode to expire all - ** compiled SQL statements after modifying a pragma value. - */ - sqlite3VdbeAddOp0(v, OP_Expire); - setAllPagerFlags(db); - } - break; - } -#endif /* SQLITE_OMIT_FLAG_PRAGMAS */ - -#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS - /* - ** PRAGMA table_info(
    ) - ** - ** Return a single row for each column of the named table. The columns of - ** the returned data set are: - ** - ** cid: Column id (numbered from left to right, starting at 0) - ** name: Column name - ** type: Column declaration type. - ** notnull: True if 'NOT NULL' is part of column declaration - ** dflt_value: The default value for the column, if any. - ** pk: Non-zero for PK fields. - */ - case PragTyp_TABLE_INFO: if( zRight ){ - Table *pTab; - sqlite3CodeVerifyNamedSchema(pParse, zDb); - pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); - if( pTab ){ - int i, k; - int nHidden = 0; - Column *pCol; - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - pParse->nMem = 7; - sqlite3ViewGetColumnNames(pParse, pTab); - for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ - int isHidden = 0; - if( pCol->colFlags & COLFLAG_NOINSERT ){ - if( pPragma->iArg==0 ){ - nHidden++; - continue; - } - if( pCol->colFlags & COLFLAG_VIRTUAL ){ - isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */ - }else if( pCol->colFlags & COLFLAG_STORED ){ - isHidden = 3; /* GENERATED ALWAYS AS ... STORED */ - }else{ assert( pCol->colFlags & COLFLAG_HIDDEN ); - isHidden = 1; /* HIDDEN */ - } - } - if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ - k = 0; - }else if( pPk==0 ){ - k = 1; - }else{ - for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} - } - assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 ); - sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi", - i-nHidden, - pCol->zName, - sqlite3ColumnType(pCol,""), - pCol->notNull ? 1 : 0, - pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0, - k, - isHidden); - } - } - } - break; - -#ifdef SQLITE_DEBUG - case PragTyp_STATS: { - Index *pIdx; - HashElem *i; - pParse->nMem = 5; - sqlite3CodeVerifySchema(pParse, iDb); - for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ - Table *pTab = sqliteHashData(i); - sqlite3VdbeMultiLoad(v, 1, "ssiii", - pTab->zName, - 0, - pTab->szTabRow, - pTab->nRowLogEst, - pTab->tabFlags); - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - sqlite3VdbeMultiLoad(v, 2, "siiiX", - pIdx->zName, - pIdx->szIdxRow, - pIdx->aiRowLogEst[0], - pIdx->hasStat1); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); - } - } - } - break; -#endif - - case PragTyp_INDEX_INFO: if( zRight ){ - Index *pIdx; - Table *pTab; - pIdx = sqlite3FindIndex(db, zRight, zDb); - if( pIdx==0 ){ - /* If there is no index named zRight, check to see if there is a - ** WITHOUT ROWID table named zRight, and if there is, show the - ** structure of the PRIMARY KEY index for that table. */ - pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); - if( pTab && !HasRowid(pTab) ){ - pIdx = sqlite3PrimaryKeyIndex(pTab); - } - } - if( pIdx ){ - int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema); - int i; - int mx; - if( pPragma->iArg ){ - /* PRAGMA index_xinfo (newer version with more rows and columns) */ - mx = pIdx->nColumn; - pParse->nMem = 6; - }else{ - /* PRAGMA index_info (legacy version) */ - mx = pIdx->nKeyCol; - pParse->nMem = 3; - } - pTab = pIdx->pTable; - sqlite3CodeVerifySchema(pParse, iIdxDb); - assert( pParse->nMem<=pPragma->nPragCName ); - for(i=0; iaiColumn[i]; - sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum, - cnum<0 ? 0 : pTab->aCol[cnum].zName); - if( pPragma->iArg ){ - sqlite3VdbeMultiLoad(v, 4, "isiX", - pIdx->aSortOrder[i], - pIdx->azColl[i], - inKeyCol); - } - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); - } - } - } - break; - - case PragTyp_INDEX_LIST: if( zRight ){ - Index *pIdx; - Table *pTab; - int i; - pTab = sqlite3FindTable(db, zRight, zDb); - if( pTab ){ - int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); - pParse->nMem = 5; - sqlite3CodeVerifySchema(pParse, iTabDb); - for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ - const char *azOrigin[] = { "c", "u", "pk" }; - sqlite3VdbeMultiLoad(v, 1, "isisi", - i, - pIdx->zName, - IsUniqueIndex(pIdx), - azOrigin[pIdx->idxType], - pIdx->pPartIdxWhere!=0); - } - } - } - break; - - case PragTyp_DATABASE_LIST: { - int i; - pParse->nMem = 3; - for(i=0; inDb; i++){ - if( db->aDb[i].pBt==0 ) continue; - assert( db->aDb[i].zDbSName!=0 ); - sqlite3VdbeMultiLoad(v, 1, "iss", - i, - db->aDb[i].zDbSName, - sqlite3BtreeGetFilename(db->aDb[i].pBt)); - } - } - break; - - case PragTyp_COLLATION_LIST: { - int i = 0; - HashElem *p; - pParse->nMem = 2; - for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ - CollSeq *pColl = (CollSeq *)sqliteHashData(p); - sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName); - } - } - break; - -#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS - case PragTyp_FUNCTION_LIST: { - int i; - HashElem *j; - FuncDef *p; - int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0; - pParse->nMem = 6; - for(i=0; iu.pHash ){ - pragmaFunclistLine(v, p, 1, showInternFunc); - } - } - for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){ - p = (FuncDef*)sqliteHashData(j); - pragmaFunclistLine(v, p, 0, showInternFunc); - } - } - break; - -#ifndef SQLITE_OMIT_VIRTUALTABLE - case PragTyp_MODULE_LIST: { - HashElem *j; - pParse->nMem = 1; - for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){ - Module *pMod = (Module*)sqliteHashData(j); - sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName); - } - } - break; -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - - case PragTyp_PRAGMA_LIST: { - int i; - for(i=0; ipFKey; - if( pFK ){ - int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); - int i = 0; - pParse->nMem = 8; - sqlite3CodeVerifySchema(pParse, iTabDb); - while(pFK){ - int j; - for(j=0; jnCol; j++){ - sqlite3VdbeMultiLoad(v, 1, "iissssss", - i, - j, - pFK->zTo, - pTab->aCol[pFK->aCol[j].iFrom].zName, - pFK->aCol[j].zCol, - actionName(pFK->aAction[1]), /* ON UPDATE */ - actionName(pFK->aAction[0]), /* ON DELETE */ - "NONE"); - } - ++i; - pFK = pFK->pNextFrom; - } - } - } - } - break; -#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ - -#ifndef SQLITE_OMIT_FOREIGN_KEY -#ifndef SQLITE_OMIT_TRIGGER - case PragTyp_FOREIGN_KEY_CHECK: { - FKey *pFK; /* A foreign key constraint */ - Table *pTab; /* Child table contain "REFERENCES" keyword */ - Table *pParent; /* Parent table that child points to */ - Index *pIdx; /* Index in the parent table */ - int i; /* Loop counter: Foreign key number for pTab */ - int j; /* Loop counter: Field of the foreign key */ - HashElem *k; /* Loop counter: Next table in schema */ - int x; /* result variable */ - int regResult; /* 3 registers to hold a result row */ - int regKey; /* Register to hold key for checking the FK */ - int regRow; /* Registers to hold a row from pTab */ - int addrTop; /* Top of a loop checking foreign keys */ - int addrOk; /* Jump here if the key is OK */ - int *aiCols; /* child to parent column mapping */ - - regResult = pParse->nMem+1; - pParse->nMem += 4; - regKey = ++pParse->nMem; - regRow = ++pParse->nMem; - k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); - while( k ){ - if( zRight ){ - pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); - k = 0; - }else{ - pTab = (Table*)sqliteHashData(k); - k = sqliteHashNext(k); - } - if( pTab==0 || pTab->pFKey==0 ) continue; - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - zDb = db->aDb[iDb].zDbSName; - sqlite3CodeVerifySchema(pParse, iDb); - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); - if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; - sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead); - sqlite3VdbeLoadString(v, regResult, pTab->zName); - for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ - pParent = sqlite3FindTable(db, pFK->zTo, zDb); - if( pParent==0 ) continue; - pIdx = 0; - sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName); - x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); - if( x==0 ){ - if( pIdx==0 ){ - sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead); - }else{ - sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); - } - }else{ - k = 0; - break; - } - } - assert( pParse->nErr>0 || pFK==0 ); - if( pFK ) break; - if( pParse->nTabnTab = i; - addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); - for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ - pParent = sqlite3FindTable(db, pFK->zTo, zDb); - pIdx = 0; - aiCols = 0; - if( pParent ){ - x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); - assert( x==0 ); - } - addrOk = sqlite3VdbeMakeLabel(pParse); - - /* Generate code to read the child key values into registers - ** regRow..regRow+n. If any of the child key values are NULL, this - ** row cannot cause an FK violation. Jump directly to addrOk in - ** this case. */ - for(j=0; jnCol; j++){ - int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom; - sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j); - sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); - } - - /* Generate code to query the parent index for a matching parent - ** key. If a match is found, jump to addrOk. */ - if( pIdx ){ - sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, - sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); - sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); - VdbeCoverage(v); - }else if( pParent ){ - int jmp = sqlite3VdbeCurrentAddr(v)+2; - sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v); - sqlite3VdbeGoto(v, addrOk); - assert( pFK->nCol==1 ); - } - - /* Generate code to report an FK violation to the caller. */ - if( HasRowid(pTab) ){ - sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1); - } - sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1); - sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); - sqlite3VdbeResolveLabel(v, addrOk); - sqlite3DbFree(db, aiCols); - } - sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addrTop); - } - } - break; -#endif /* !defined(SQLITE_OMIT_TRIGGER) */ -#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ - -#ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA - /* Reinstall the LIKE and GLOB functions. The variant of LIKE - ** used will be case sensitive or not depending on the RHS. - */ - case PragTyp_CASE_SENSITIVE_LIKE: { - if( zRight ){ - sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); - } - } - break; -#endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */ - -#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX -# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 -#endif - -#ifndef SQLITE_OMIT_INTEGRITY_CHECK - /* PRAGMA integrity_check - ** PRAGMA integrity_check(N) - ** PRAGMA quick_check - ** PRAGMA quick_check(N) - ** - ** Verify the integrity of the database. - ** - ** The "quick_check" is reduced version of - ** integrity_check designed to detect most database corruption - ** without the overhead of cross-checking indexes. Quick_check - ** is linear time wherease integrity_check is O(NlogN). - ** - ** The maximum nubmer of errors is 100 by default. A different default - ** can be specified using a numeric parameter N. - ** - ** Or, the parameter N can be the name of a table. In that case, only - ** the one table named is verified. The freelist is only verified if - ** the named table is "sqlite_schema" (or one of its aliases). - ** - ** All schemas are checked by default. To check just a single - ** schema, use the form: - ** - ** PRAGMA schema.integrity_check; - */ - case PragTyp_INTEGRITY_CHECK: { - int i, j, addr, mxErr; - Table *pObjTab = 0; /* Check only this one table, if not NULL */ - - int isQuick = (sqlite3Tolower(zLeft[0])=='q'); - - /* If the PRAGMA command was of the form "PRAGMA .integrity_check", - ** then iDb is set to the index of the database identified by . - ** In this case, the integrity of database iDb only is verified by - ** the VDBE created below. - ** - ** Otherwise, if the command was simply "PRAGMA integrity_check" (or - ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb - ** to -1 here, to indicate that the VDBE should verify the integrity - ** of all attached databases. */ - assert( iDb>=0 ); - assert( iDb==0 || pId2->z ); - if( pId2->z==0 ) iDb = -1; - - /* Initialize the VDBE program */ - pParse->nMem = 6; - - /* Set the maximum error count */ - mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; - if( zRight ){ - if( sqlite3GetInt32(zRight, &mxErr) ){ - if( mxErr<=0 ){ - mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; - } - }else{ - pObjTab = sqlite3LocateTable(pParse, 0, zRight, - iDb>=0 ? db->aDb[iDb].zDbSName : 0); - } - } - sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */ - - /* Do an integrity check on each database file */ - for(i=0; inDb; i++){ - HashElem *x; /* For looping over tables in the schema */ - Hash *pTbls; /* Set of all tables in the schema */ - int *aRoot; /* Array of root page numbers of all btrees */ - int cnt = 0; /* Number of entries in aRoot[] */ - int mxIdx = 0; /* Maximum number of indexes for any table */ - - if( OMIT_TEMPDB && i==1 ) continue; - if( iDb>=0 && i!=iDb ) continue; - - sqlite3CodeVerifySchema(pParse, i); - - /* Do an integrity check of the B-Tree - ** - ** Begin by finding the root pages numbers - ** for all tables and indices in the database. - */ - assert( sqlite3SchemaMutexHeld(db, i, 0) ); - pTbls = &db->aDb[i].pSchema->tblHash; - for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ - Table *pTab = sqliteHashData(x); /* Current table */ - Index *pIdx; /* An index on pTab */ - int nIdx; /* Number of indexes on pTab */ - if( pObjTab && pObjTab!=pTab ) continue; - if( HasRowid(pTab) ) cnt++; - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } - if( nIdx>mxIdx ) mxIdx = nIdx; - } - if( cnt==0 ) continue; - if( pObjTab ) cnt++; - aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); - if( aRoot==0 ) break; - cnt = 0; - if( pObjTab ) aRoot[++cnt] = 0; - for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ - Table *pTab = sqliteHashData(x); - Index *pIdx; - if( pObjTab && pObjTab!=pTab ) continue; - if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum; - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - aRoot[++cnt] = pIdx->tnum; - } - } - aRoot[0] = cnt; - - /* Make sure sufficient number of registers have been allocated */ - pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); - sqlite3ClearTempRegCache(pParse); - - /* Do the b-tree integrity checks */ - sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); - sqlite3VdbeChangeP5(v, (u8)i); - addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, - sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), - P4_DYNAMIC); - sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3); - integrityCheckResultRow(v); - sqlite3VdbeJumpHere(v, addr); - - /* Make sure all the indices are constructed correctly. - */ - for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ - Table *pTab = sqliteHashData(x); - Index *pIdx, *pPk; - Index *pPrior = 0; - int loopTop; - int iDataCur, iIdxCur; - int r1 = -1; - - if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */ - if( pObjTab && pObjTab!=pTab ) continue; - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); - sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, - 1, 0, &iDataCur, &iIdxCur); - /* reg[7] counts the number of entries in the table. - ** reg[8+i] counts the number of entries in the i-th index - */ - sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ - } - assert( pParse->nMem>=8+j ); - assert( sqlite3NoTempsInRange(pParse,1,7+j) ); - sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); - loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); - if( !isQuick ){ - /* Sanity check on record header decoding */ - sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3); - sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); - } - /* Verify that all NOT NULL columns really are NOT NULL */ - for(j=0; jnCol; j++){ - char *zErr; - int jmp2; - if( j==pTab->iPKey ) continue; - if( pTab->aCol[j].notNull==0 ) continue; - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); - if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){ - sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); - } - jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); - zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName, - pTab->aCol[j].zName); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); - integrityCheckResultRow(v); - sqlite3VdbeJumpHere(v, jmp2); - } - /* Verify CHECK constraints */ - if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ - ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0); - if( db->mallocFailed==0 ){ - int addrCkFault = sqlite3VdbeMakeLabel(pParse); - int addrCkOk = sqlite3VdbeMakeLabel(pParse); - char *zErr; - int k; - pParse->iSelfTab = iDataCur + 1; - for(k=pCheck->nExpr-1; k>0; k--){ - sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0); - } - sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, - SQLITE_JUMPIFNULL); - sqlite3VdbeResolveLabel(v, addrCkFault); - pParse->iSelfTab = 0; - zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s", - pTab->zName); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); - integrityCheckResultRow(v); - sqlite3VdbeResolveLabel(v, addrCkOk); - } - sqlite3ExprListDelete(db, pCheck); - } - if( !isQuick ){ /* Omit the remaining tests for quick_check */ - /* Validate index entries for the current row */ - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - int jmp2, jmp3, jmp4, jmp5; - int ckUniq = sqlite3VdbeMakeLabel(pParse); - if( pPk==pIdx ) continue; - r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, - pPrior, r1); - pPrior = pIdx; - sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */ - /* Verify that an index entry exists for the current table row */ - jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, - pIdx->nColumn); VdbeCoverage(v); - sqlite3VdbeLoadString(v, 3, "row "); - sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); - sqlite3VdbeLoadString(v, 4, " missing from index "); - sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); - jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); - sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); - jmp4 = integrityCheckResultRow(v); - sqlite3VdbeJumpHere(v, jmp2); - /* For UNIQUE indexes, verify that only one entry exists with the - ** current key. The entry is unique if (1) any column is NULL - ** or (2) the next entry has a different key */ - if( IsUniqueIndex(pIdx) ){ - int uniqOk = sqlite3VdbeMakeLabel(pParse); - int jmp6; - int kk; - for(kk=0; kknKeyCol; kk++){ - int iCol = pIdx->aiColumn[kk]; - assert( iCol!=XN_ROWID && iColnCol ); - if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; - sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); - VdbeCoverage(v); - } - jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); - sqlite3VdbeGoto(v, uniqOk); - sqlite3VdbeJumpHere(v, jmp6); - sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, - pIdx->nKeyCol); VdbeCoverage(v); - sqlite3VdbeLoadString(v, 3, "non-unique entry in index "); - sqlite3VdbeGoto(v, jmp5); - sqlite3VdbeResolveLabel(v, uniqOk); - } - sqlite3VdbeJumpHere(v, jmp4); - sqlite3ResolvePartIdxLabel(pParse, jmp3); - } - } - sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, loopTop-1); - if( !isQuick ){ - sqlite3VdbeLoadString(v, 2, "wrong # of entries in index "); - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - if( pPk==pIdx ) continue; - sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); - addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); - sqlite3VdbeLoadString(v, 4, pIdx->zName); - sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3); - integrityCheckResultRow(v); - sqlite3VdbeJumpHere(v, addr); - } - } - } - } - { - static const int iLn = VDBE_OFFSET_LINENO(2); - static const VdbeOpList endCode[] = { - { OP_AddImm, 1, 0, 0}, /* 0 */ - { OP_IfNotZero, 1, 4, 0}, /* 1 */ - { OP_String8, 0, 3, 0}, /* 2 */ - { OP_ResultRow, 3, 1, 0}, /* 3 */ - { OP_Halt, 0, 0, 0}, /* 4 */ - { OP_String8, 0, 3, 0}, /* 5 */ - { OP_Goto, 0, 3, 0}, /* 6 */ - }; - VdbeOp *aOp; - - aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); - if( aOp ){ - aOp[0].p2 = 1-mxErr; - aOp[2].p4type = P4_STATIC; - aOp[2].p4.z = "ok"; - aOp[5].p4type = P4_STATIC; - aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT); - } - sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2); - } - } - break; -#endif /* SQLITE_OMIT_INTEGRITY_CHECK */ - -#ifndef SQLITE_OMIT_UTF16 - /* - ** PRAGMA encoding - ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" - ** - ** In its first form, this pragma returns the encoding of the main - ** database. If the database is not initialized, it is initialized now. - ** - ** The second form of this pragma is a no-op if the main database file - ** has not already been initialized. In this case it sets the default - ** encoding that will be used for the main database file if a new file - ** is created. If an existing main database file is opened, then the - ** default text encoding for the existing database is used. - ** - ** In all cases new databases created using the ATTACH command are - ** created to use the same default text encoding as the main database. If - ** the main database has not been initialized and/or created when ATTACH - ** is executed, this is done before the ATTACH operation. - ** - ** In the second form this pragma sets the text encoding to be used in - ** new database files created using this database handle. It is only - ** useful if invoked immediately after the main database i - */ - case PragTyp_ENCODING: { - static const struct EncName { - char *zName; - u8 enc; - } encnames[] = { - { "UTF8", SQLITE_UTF8 }, - { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */ - { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */ - { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */ - { "UTF16le", SQLITE_UTF16LE }, - { "UTF16be", SQLITE_UTF16BE }, - { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */ - { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */ - { 0, 0 } - }; - const struct EncName *pEnc; - if( !zRight ){ /* "PRAGMA encoding" */ - if( sqlite3ReadSchema(pParse) ) goto pragma_out; - assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); - assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); - assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); - returnSingleText(v, encnames[ENC(pParse->db)].zName); - }else{ /* "PRAGMA encoding = XXX" */ - /* Only change the value of sqlite.enc if the database handle is not - ** initialized. If the main database exists, the new sqlite.enc value - ** will be overwritten when the schema is next loaded. If it does not - ** already exists, it will be created to use the new encoding value. - */ - if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){ - for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ - if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ - u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; - SCHEMA_ENC(db) = enc; - sqlite3SetTextEncoding(db, enc); - break; - } - } - if( !pEnc->zName ){ - sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); - } - } - } - } - break; -#endif /* SQLITE_OMIT_UTF16 */ - -#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS - /* - ** PRAGMA [schema.]schema_version - ** PRAGMA [schema.]schema_version = - ** - ** PRAGMA [schema.]user_version - ** PRAGMA [schema.]user_version = - ** - ** PRAGMA [schema.]freelist_count - ** - ** PRAGMA [schema.]data_version - ** - ** PRAGMA [schema.]application_id - ** PRAGMA [schema.]application_id = - ** - ** The pragma's schema_version and user_version are used to set or get - ** the value of the schema-version and user-version, respectively. Both - ** the schema-version and the user-version are 32-bit signed integers - ** stored in the database header. - ** - ** The schema-cookie is usually only manipulated internally by SQLite. It - ** is incremented by SQLite whenever the database schema is modified (by - ** creating or dropping a table or index). The schema version is used by - ** SQLite each time a query is executed to ensure that the internal cache - ** of the schema used when compiling the SQL query matches the schema of - ** the database against which the compiled query is actually executed. - ** Subverting this mechanism by using "PRAGMA schema_version" to modify - ** the schema-version is potentially dangerous and may lead to program - ** crashes or database corruption. Use with caution! - ** - ** The user-version is not used internally by SQLite. It may be used by - ** applications for any purpose. - */ - case PragTyp_HEADER_VALUE: { - int iCookie = pPragma->iArg; /* Which cookie to read or write */ - sqlite3VdbeUsesBtree(v, iDb); - if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){ - /* Write the specified cookie value */ - static const VdbeOpList setCookie[] = { - { OP_Transaction, 0, 1, 0}, /* 0 */ - { OP_SetCookie, 0, 0, 0}, /* 1 */ - }; - VdbeOp *aOp; - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); - if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; - aOp[0].p1 = iDb; - aOp[1].p1 = iDb; - aOp[1].p2 = iCookie; - aOp[1].p3 = sqlite3Atoi(zRight); - aOp[1].p5 = 1; - }else{ - /* Read the specified cookie value */ - static const VdbeOpList readCookie[] = { - { OP_Transaction, 0, 0, 0}, /* 0 */ - { OP_ReadCookie, 0, 1, 0}, /* 1 */ - { OP_ResultRow, 1, 1, 0} - }; - VdbeOp *aOp; - sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); - aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); - if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; - aOp[0].p1 = iDb; - aOp[1].p1 = iDb; - aOp[1].p3 = iCookie; - sqlite3VdbeReusable(v); - } - } - break; -#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ - -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS - /* - ** PRAGMA compile_options - ** - ** Return the names of all compile-time options used in this build, - ** one option per row. - */ - case PragTyp_COMPILE_OPTIONS: { - int i = 0; - const char *zOpt; - pParse->nMem = 1; - while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ - sqlite3VdbeLoadString(v, 1, zOpt); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); - } - sqlite3VdbeReusable(v); - } - break; -#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ - -#ifndef SQLITE_OMIT_WAL - /* - ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate - ** - ** Checkpoint the database. - */ - case PragTyp_WAL_CHECKPOINT: { - int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); - int eMode = SQLITE_CHECKPOINT_PASSIVE; - if( zRight ){ - if( sqlite3StrICmp(zRight, "full")==0 ){ - eMode = SQLITE_CHECKPOINT_FULL; - }else if( sqlite3StrICmp(zRight, "restart")==0 ){ - eMode = SQLITE_CHECKPOINT_RESTART; - }else if( sqlite3StrICmp(zRight, "truncate")==0 ){ - eMode = SQLITE_CHECKPOINT_TRUNCATE; - } - } - pParse->nMem = 3; - sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); - } - break; - - /* - ** PRAGMA wal_autocheckpoint - ** PRAGMA wal_autocheckpoint = N - ** - ** Configure a database connection to automatically checkpoint a database - ** after accumulating N frames in the log. Or query for the current value - ** of N. - */ - case PragTyp_WAL_AUTOCHECKPOINT: { - if( zRight ){ - sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); - } - returnSingleInt(v, - db->xWalCallback==sqlite3WalDefaultHook ? - SQLITE_PTR_TO_INT(db->pWalArg) : 0); - } - break; -#endif - - /* - ** PRAGMA shrink_memory - ** - ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database - ** connection on which it is invoked to free up as much memory as it - ** can, by calling sqlite3_db_release_memory(). - */ - case PragTyp_SHRINK_MEMORY: { - sqlite3_db_release_memory(db); - break; - } - - /* - ** PRAGMA optimize - ** PRAGMA optimize(MASK) - ** PRAGMA schema.optimize - ** PRAGMA schema.optimize(MASK) - ** - ** Attempt to optimize the database. All schemas are optimized in the first - ** two forms, and only the specified schema is optimized in the latter two. - ** - ** The details of optimizations performed by this pragma are expected - ** to change and improve over time. Applications should anticipate that - ** this pragma will perform new optimizations in future releases. - ** - ** The optional argument is a bitmask of optimizations to perform: - ** - ** 0x0001 Debugging mode. Do not actually perform any optimizations - ** but instead return one line of text for each optimization - ** that would have been done. Off by default. - ** - ** 0x0002 Run ANALYZE on tables that might benefit. On by default. - ** See below for additional information. - ** - ** 0x0004 (Not yet implemented) Record usage and performance - ** information from the current session in the - ** database file so that it will be available to "optimize" - ** pragmas run by future database connections. - ** - ** 0x0008 (Not yet implemented) Create indexes that might have - ** been helpful to recent queries - ** - ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all - ** of the optimizations listed above except Debug Mode, including new - ** optimizations that have not yet been invented. If new optimizations are - ** ever added that should be off by default, those off-by-default - ** optimizations will have bitmasks of 0x10000 or larger. - ** - ** DETERMINATION OF WHEN TO RUN ANALYZE - ** - ** In the current implementation, a table is analyzed if only if all of - ** the following are true: - ** - ** (1) MASK bit 0x02 is set. - ** - ** (2) The query planner used sqlite_stat1-style statistics for one or - ** more indexes of the table at some point during the lifetime of - ** the current connection. - ** - ** (3) One or more indexes of the table are currently unanalyzed OR - ** the number of rows in the table has increased by 25 times or more - ** since the last time ANALYZE was run. - ** - ** The rules for when tables are analyzed are likely to change in - ** future releases. - */ - case PragTyp_OPTIMIZE: { - int iDbLast; /* Loop termination point for the schema loop */ - int iTabCur; /* Cursor for a table whose size needs checking */ - HashElem *k; /* Loop over tables of a schema */ - Schema *pSchema; /* The current schema */ - Table *pTab; /* A table in the schema */ - Index *pIdx; /* An index of the table */ - LogEst szThreshold; /* Size threshold above which reanalysis is needd */ - char *zSubSql; /* SQL statement for the OP_SqlExec opcode */ - u32 opMask; /* Mask of operations to perform */ - - if( zRight ){ - opMask = (u32)sqlite3Atoi(zRight); - if( (opMask & 0x02)==0 ) break; - }else{ - opMask = 0xfffe; - } - iTabCur = pParse->nTab++; - for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){ - if( iDb==1 ) continue; - sqlite3CodeVerifySchema(pParse, iDb); - pSchema = db->aDb[iDb].pSchema; - for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ - pTab = (Table*)sqliteHashData(k); - - /* If table pTab has not been used in a way that would benefit from - ** having analysis statistics during the current session, then skip it. - ** This also has the effect of skipping virtual tables and views */ - if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue; - - /* Reanalyze if the table is 25 times larger than the last analysis */ - szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 ); - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( !pIdx->hasStat1 ){ - szThreshold = 0; /* Always analyze if any index lacks statistics */ - break; - } - } - if( szThreshold ){ - sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); - sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, - sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold); - VdbeCoverage(v); - } - zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"", - db->aDb[iDb].zDbSName, pTab->zName); - if( opMask & 0x01 ){ - int r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC); - sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1); - }else{ - sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC); - } - } - } - sqlite3VdbeAddOp0(v, OP_Expire); - break; - } - - /* - ** PRAGMA busy_timeout - ** PRAGMA busy_timeout = N - ** - ** Call sqlite3_busy_timeout(db, N). Return the current timeout value - ** if one is set. If no busy handler or a different busy handler is set - ** then 0 is returned. Setting the busy_timeout to 0 or negative - ** disables the timeout. - */ - /*case PragTyp_BUSY_TIMEOUT*/ default: { - assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); - if( zRight ){ - sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); - } - returnSingleInt(v, db->busyTimeout); - break; - } - - /* - ** PRAGMA soft_heap_limit - ** PRAGMA soft_heap_limit = N - ** - ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the - ** sqlite3_soft_heap_limit64() interface with the argument N, if N is - ** specified and is a non-negative integer. - ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always - ** returns the same integer that would be returned by the - ** sqlite3_soft_heap_limit64(-1) C-language function. - */ - case PragTyp_SOFT_HEAP_LIMIT: { - sqlite3_int64 N; - if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ - sqlite3_soft_heap_limit64(N); - } - returnSingleInt(v, sqlite3_soft_heap_limit64(-1)); - break; - } - - /* - ** PRAGMA hard_heap_limit - ** PRAGMA hard_heap_limit = N - ** - ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap - ** limit. The hard heap limit can be activated or lowered by this - ** pragma, but not raised or deactivated. Only the - ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate - ** the hard heap limit. This allows an application to set a heap limit - ** constraint that cannot be relaxed by an untrusted SQL script. - */ - case PragTyp_HARD_HEAP_LIMIT: { - sqlite3_int64 N; - if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ - sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1); - if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N); - } - returnSingleInt(v, sqlite3_hard_heap_limit64(-1)); - break; - } - - /* - ** PRAGMA threads - ** PRAGMA threads = N - ** - ** Configure the maximum number of worker threads. Return the new - ** maximum, which might be less than requested. - */ - case PragTyp_THREADS: { - sqlite3_int64 N; - if( zRight - && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK - && N>=0 - ){ - sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); - } - returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); - break; - } - - /* - ** PRAGMA analysis_limit - ** PRAGMA analysis_limit = N - ** - ** Configure the maximum number of rows that ANALYZE will examine - ** in each index that it looks at. Return the new limit. - */ - case PragTyp_ANALYSIS_LIMIT: { - sqlite3_int64 N; - if( zRight - && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK - && N>=0 - ){ - db->nAnalysisLimit = (int)(N&0x7fffffff); - } - returnSingleInt(v, db->nAnalysisLimit); - break; - } - -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - /* - ** Report the current state of file logs for all databases - */ - case PragTyp_LOCK_STATUS: { - static const char *const azLockName[] = { - "unlocked", "shared", "reserved", "pending", "exclusive" - }; - int i; - pParse->nMem = 2; - for(i=0; inDb; i++){ - Btree *pBt; - const char *zState = "unknown"; - int j; - if( db->aDb[i].zDbSName==0 ) continue; - pBt = db->aDb[i].pBt; - if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ - zState = "closed"; - }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, - SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ - zState = azLockName[j]; - } - sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState); - } - break; - } -#endif - -#if defined(SQLITE_ENABLE_CEROD) - case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){ - if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ - sqlite3_activate_cerod(&zRight[6]); - } - } - break; -#endif - - } /* End of the PRAGMA switch */ - - /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only - ** purpose is to execute assert() statements to verify that if the - ** PragFlg_NoColumns1 flag is set and the caller specified an argument - ** to the PRAGMA, the implementation has not added any OP_ResultRow - ** instructions to the VM. */ - if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){ - sqlite3VdbeVerifyNoResultRow(v); - } - -pragma_out: - sqlite3DbFree(db, zLeft); - sqlite3DbFree(db, zRight); -} -#ifndef SQLITE_OMIT_VIRTUALTABLE -/***************************************************************************** -** Implementation of an eponymous virtual table that runs a pragma. -** -*/ -typedef struct PragmaVtab PragmaVtab; -typedef struct PragmaVtabCursor PragmaVtabCursor; -struct PragmaVtab { - sqlite3_vtab base; /* Base class. Must be first */ - sqlite3 *db; /* The database connection to which it belongs */ - const PragmaName *pName; /* Name of the pragma */ - u8 nHidden; /* Number of hidden columns */ - u8 iHidden; /* Index of the first hidden column */ -}; -struct PragmaVtabCursor { - sqlite3_vtab_cursor base; /* Base class. Must be first */ - sqlite3_stmt *pPragma; /* The pragma statement to run */ - sqlite_int64 iRowid; /* Current rowid */ - char *azArg[2]; /* Value of the argument and schema */ -}; - -/* -** Pragma virtual table module xConnect method. -*/ -static int pragmaVtabConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - const PragmaName *pPragma = (const PragmaName*)pAux; - PragmaVtab *pTab = 0; - int rc; - int i, j; - char cSep = '('; - StrAccum acc; - char zBuf[200]; - - UNUSED_PARAMETER(argc); - UNUSED_PARAMETER(argv); - sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); - sqlite3_str_appendall(&acc, "CREATE TABLE x"); - for(i=0, j=pPragma->iPragCName; inPragCName; i++, j++){ - sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]); - cSep = ','; - } - if( i==0 ){ - sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName); - i++; - } - j = 0; - if( pPragma->mPragFlg & PragFlg_Result1 ){ - sqlite3_str_appendall(&acc, ",arg HIDDEN"); - j++; - } - if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){ - sqlite3_str_appendall(&acc, ",schema HIDDEN"); - j++; - } - sqlite3_str_append(&acc, ")", 1); - sqlite3StrAccumFinish(&acc); - assert( strlen(zBuf) < sizeof(zBuf)-1 ); - rc = sqlite3_declare_vtab(db, zBuf); - if( rc==SQLITE_OK ){ - pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab)); - if( pTab==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pTab, 0, sizeof(PragmaVtab)); - pTab->pName = pPragma; - pTab->db = db; - pTab->iHidden = i; - pTab->nHidden = j; - } - }else{ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - } - - *ppVtab = (sqlite3_vtab*)pTab; - return rc; -} - -/* -** Pragma virtual table module xDisconnect method. -*/ -static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){ - PragmaVtab *pTab = (PragmaVtab*)pVtab; - sqlite3_free(pTab); - return SQLITE_OK; -} - -/* Figure out the best index to use to search a pragma virtual table. -** -** There are not really any index choices. But we want to encourage the -** query planner to give == constraints on as many hidden parameters as -** possible, and especially on the first hidden parameter. So return a -** high cost if hidden parameters are unconstrained. -*/ -static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ - PragmaVtab *pTab = (PragmaVtab*)tab; - const struct sqlite3_index_constraint *pConstraint; - int i, j; - int seen[2]; - - pIdxInfo->estimatedCost = (double)1; - if( pTab->nHidden==0 ){ return SQLITE_OK; } - pConstraint = pIdxInfo->aConstraint; - seen[0] = 0; - seen[1] = 0; - for(i=0; inConstraint; i++, pConstraint++){ - if( pConstraint->usable==0 ) continue; - if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; - if( pConstraint->iColumn < pTab->iHidden ) continue; - j = pConstraint->iColumn - pTab->iHidden; - assert( j < 2 ); - seen[j] = i+1; - } - if( seen[0]==0 ){ - pIdxInfo->estimatedCost = (double)2147483647; - pIdxInfo->estimatedRows = 2147483647; - return SQLITE_OK; - } - j = seen[0]-1; - pIdxInfo->aConstraintUsage[j].argvIndex = 1; - pIdxInfo->aConstraintUsage[j].omit = 1; - if( seen[1]==0 ) return SQLITE_OK; - pIdxInfo->estimatedCost = (double)20; - pIdxInfo->estimatedRows = 20; - j = seen[1]-1; - pIdxInfo->aConstraintUsage[j].argvIndex = 2; - pIdxInfo->aConstraintUsage[j].omit = 1; - return SQLITE_OK; -} - -/* Create a new cursor for the pragma virtual table */ -static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){ - PragmaVtabCursor *pCsr; - pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr)); - if( pCsr==0 ) return SQLITE_NOMEM; - memset(pCsr, 0, sizeof(PragmaVtabCursor)); - pCsr->base.pVtab = pVtab; - *ppCursor = &pCsr->base; - return SQLITE_OK; -} - -/* Clear all content from pragma virtual table cursor. */ -static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){ - int i; - sqlite3_finalize(pCsr->pPragma); - pCsr->pPragma = 0; - for(i=0; iazArg); i++){ - sqlite3_free(pCsr->azArg[i]); - pCsr->azArg[i] = 0; - } -} - -/* Close a pragma virtual table cursor */ -static int pragmaVtabClose(sqlite3_vtab_cursor *cur){ - PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur; - pragmaVtabCursorClear(pCsr); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* Advance the pragma virtual table cursor to the next row */ -static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){ - PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; - int rc = SQLITE_OK; - - /* Increment the xRowid value */ - pCsr->iRowid++; - assert( pCsr->pPragma ); - if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){ - rc = sqlite3_finalize(pCsr->pPragma); - pCsr->pPragma = 0; - pragmaVtabCursorClear(pCsr); - } - return rc; -} - -/* -** Pragma virtual table module xFilter method. -*/ -static int pragmaVtabFilter( - sqlite3_vtab_cursor *pVtabCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; - PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); - int rc; - int i, j; - StrAccum acc; - char *zSql; - - UNUSED_PARAMETER(idxNum); - UNUSED_PARAMETER(idxStr); - pragmaVtabCursorClear(pCsr); - j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1; - for(i=0; iazArg) ); - assert( pCsr->azArg[j]==0 ); - if( zText ){ - pCsr->azArg[j] = sqlite3_mprintf("%s", zText); - if( pCsr->azArg[j]==0 ){ - return SQLITE_NOMEM; - } - } - } - sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]); - sqlite3_str_appendall(&acc, "PRAGMA "); - if( pCsr->azArg[1] ){ - sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]); - } - sqlite3_str_appendall(&acc, pTab->pName->zName); - if( pCsr->azArg[0] ){ - sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]); - } - zSql = sqlite3StrAccumFinish(&acc); - if( zSql==0 ) return SQLITE_NOMEM; - rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0); - sqlite3_free(zSql); - if( rc!=SQLITE_OK ){ - pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); - return rc; - } - return pragmaVtabNext(pVtabCursor); -} - -/* -** Pragma virtual table module xEof method. -*/ -static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){ - PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; - return (pCsr->pPragma==0); -} - -/* The xColumn method simply returns the corresponding column from -** the PRAGMA. -*/ -static int pragmaVtabColumn( - sqlite3_vtab_cursor *pVtabCursor, - sqlite3_context *ctx, - int i -){ - PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; - PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab); - if( iiHidden ){ - sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i)); - }else{ - sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT); - } - return SQLITE_OK; -} - -/* -** Pragma virtual table module xRowid method. -*/ -static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){ - PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor; - *p = pCsr->iRowid; - return SQLITE_OK; -} - -/* The pragma virtual table object */ -static const sqlite3_module pragmaVtabModule = { - 0, /* iVersion */ - 0, /* xCreate - create a table */ - pragmaVtabConnect, /* xConnect - connect to an existing table */ - pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */ - pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */ - 0, /* xDestroy - Drop a table */ - pragmaVtabOpen, /* xOpen - open a cursor */ - pragmaVtabClose, /* xClose - close a cursor */ - pragmaVtabFilter, /* xFilter - configure scan constraints */ - pragmaVtabNext, /* xNext - advance a cursor */ - pragmaVtabEof, /* xEof */ - pragmaVtabColumn, /* xColumn - read data */ - pragmaVtabRowid, /* xRowid - read data */ - 0, /* xUpdate - write data */ - 0, /* xBegin - begin transaction */ - 0, /* xSync - sync transaction */ - 0, /* xCommit - commit transaction */ - 0, /* xRollback - rollback transaction */ - 0, /* xFindFunction - function overloading */ - 0, /* xRename - rename the table */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0 /* xShadowName */ -}; - -/* -** Check to see if zTabName is really the name of a pragma. If it is, -** then register an eponymous virtual table for that pragma and return -** a pointer to the Module object for the new virtual table. -*/ -SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){ - const PragmaName *pName; - assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 ); - pName = pragmaLocate(zName+7); - if( pName==0 ) return 0; - if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0; - assert( sqlite3HashFind(&db->aModule, zName)==0 ); - return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0); -} - -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#endif /* SQLITE_OMIT_PRAGMA */ - -/************** End of pragma.c **********************************************/ -/************** Begin file prepare.c *****************************************/ -/* -** 2005 May 25 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the implementation of the sqlite3_prepare() -** interface, and routines that contribute to loading the database schema -** from disk. -*/ -/* #include "sqliteInt.h" */ - -/* -** Fill the InitData structure with an error message that indicates -** that the database is corrupt. -*/ -static void corruptSchema( - InitData *pData, /* Initialization context */ - const char *zObj, /* Object being parsed at the point of error */ - const char *zExtra /* Error information */ -){ - sqlite3 *db = pData->db; - if( db->mallocFailed ){ - pData->rc = SQLITE_NOMEM_BKPT; - }else if( pData->pzErrMsg[0]!=0 ){ - /* A error message has already been generated. Do not overwrite it */ - }else if( pData->mInitFlags & INITFLAG_AlterTable ){ - *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra); - pData->rc = SQLITE_ERROR; - }else if( db->flags & SQLITE_WriteSchema ){ - pData->rc = SQLITE_CORRUPT_BKPT; - }else{ - char *z; - if( zObj==0 ) zObj = "?"; - z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj); - if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra); - *pData->pzErrMsg = z; - pData->rc = SQLITE_CORRUPT_BKPT; - } -} - -/* -** Check to see if any sibling index (another index on the same table) -** of pIndex has the same root page number, and if it does, return true. -** This would indicate a corrupt schema. -*/ -SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){ - Index *p; - for(p=pIndex->pTable->pIndex; p; p=p->pNext){ - if( p->tnum==pIndex->tnum && p!=pIndex ) return 1; - } - return 0; -} - -/* forward declaration */ -static int sqlite3Prepare( - sqlite3 *db, /* Database handle. */ - const char *zSql, /* UTF-8 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ - Vdbe *pReprepare, /* VM being reprepared */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const char **pzTail /* OUT: End of parsed string */ -); - - -/* -** This is the callback routine for the code that initializes the -** database. See sqlite3Init() below for additional information. -** This routine is also called from the OP_ParseSchema opcode of the VDBE. -** -** Each callback contains the following information: -** -** argv[0] = type of object: "table", "index", "trigger", or "view". -** argv[1] = name of thing being created -** argv[2] = associated table if an index or trigger -** argv[3] = root page number for table or index. 0 for trigger or view. -** argv[4] = SQL text for the CREATE statement. -** -*/ -SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){ - InitData *pData = (InitData*)pInit; - sqlite3 *db = pData->db; - int iDb = pData->iDb; - - assert( argc==5 ); - UNUSED_PARAMETER2(NotUsed, argc); - assert( sqlite3_mutex_held(db->mutex) ); - db->mDbFlags |= DBFLAG_EncodingFixed; - pData->nInitRow++; - if( db->mallocFailed ){ - corruptSchema(pData, argv[1], 0); - return 1; - } - - assert( iDb>=0 && iDbnDb ); - if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ - if( argv[3]==0 ){ - corruptSchema(pData, argv[1], 0); - }else if( sqlite3_strnicmp(argv[4],"create ",7)==0 ){ - /* Call the parser to process a CREATE TABLE, INDEX or VIEW. - ** But because db->init.busy is set to 1, no VDBE code is generated - ** or executed. All the parser does is build the internal data - ** structures that describe the table, index, or view. - */ - int rc; - u8 saved_iDb = db->init.iDb; - sqlite3_stmt *pStmt; - TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ - - assert( db->init.busy ); - db->init.iDb = iDb; - if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0 - || (db->init.newTnum>pData->mxPage && pData->mxPage>0) - ){ - if( sqlite3Config.bExtraSchemaChecks ){ - corruptSchema(pData, argv[1], "invalid rootpage"); - } - } - db->init.orphanTrigger = 0; - db->init.azInit = argv; - pStmt = 0; - TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0); - rc = db->errCode; - assert( (rc&0xFF)==(rcp&0xFF) ); - db->init.iDb = saved_iDb; - /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */ - if( SQLITE_OK!=rc ){ - if( db->init.orphanTrigger ){ - assert( iDb==1 ); - }else{ - if( rc > pData->rc ) pData->rc = rc; - if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); - }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ - corruptSchema(pData, argv[1], sqlite3_errmsg(db)); - } - } - } - sqlite3_finalize(pStmt); - }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){ - corruptSchema(pData, argv[1], 0); - }else{ - /* If the SQL column is blank it means this is an index that - ** was created to be the PRIMARY KEY or to fulfill a UNIQUE - ** constraint for a CREATE TABLE. The index should have already - ** been created when we processed the CREATE TABLE. All we have - ** to do here is record the root page number for that index. - */ - Index *pIndex; - pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName); - if( pIndex==0 ){ - corruptSchema(pData, argv[1], "orphan index"); - }else - if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0 - || pIndex->tnum<2 - || pIndex->tnum>pData->mxPage - || sqlite3IndexHasDuplicateRootPage(pIndex) - ){ - if( sqlite3Config.bExtraSchemaChecks ){ - corruptSchema(pData, argv[1], "invalid rootpage"); - } - } - } - return 0; -} - -/* -** Attempt to read the database schema and initialize internal -** data structures for a single database file. The index of the -** database file is given by iDb. iDb==0 is used for the main -** database. iDb==1 should never be used. iDb>=2 is used for -** auxiliary databases. Return one of the SQLITE_ error codes to -** indicate success or failure. -*/ -SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){ - int rc; - int i; -#ifndef SQLITE_OMIT_DEPRECATED - int size; -#endif - Db *pDb; - char const *azArg[6]; - int meta[5]; - InitData initData; - const char *zSchemaTabName; - int openedTransaction = 0; - int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed); - - assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ); - assert( iDb>=0 && iDbnDb ); - assert( db->aDb[iDb].pSchema ); - assert( sqlite3_mutex_held(db->mutex) ); - assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); - - db->init.busy = 1; - - /* Construct the in-memory representation schema tables (sqlite_schema or - ** sqlite_temp_schema) by invoking the parser directly. The appropriate - ** table name will be inserted automatically by the parser so we can just - ** use the abbreviation "x" here. The parser will also automatically tag - ** the schema table as read-only. */ - azArg[0] = "table"; - azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb); - azArg[2] = azArg[1]; - azArg[3] = "1"; - azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text," - "rootpage int,sql text)"; - azArg[5] = 0; - initData.db = db; - initData.iDb = iDb; - initData.rc = SQLITE_OK; - initData.pzErrMsg = pzErrMsg; - initData.mInitFlags = mFlags; - initData.nInitRow = 0; - initData.mxPage = 0; - sqlite3InitCallback(&initData, 5, (char **)azArg, 0); - db->mDbFlags &= mask; - if( initData.rc ){ - rc = initData.rc; - goto error_out; - } - - /* Create a cursor to hold the database open - */ - pDb = &db->aDb[iDb]; - if( pDb->pBt==0 ){ - assert( iDb==1 ); - DbSetProperty(db, 1, DB_SchemaLoaded); - rc = SQLITE_OK; - goto error_out; - } - - /* If there is not already a read-only (or read-write) transaction opened - ** on the b-tree database, open one now. If a transaction is opened, it - ** will be closed before this function returns. */ - sqlite3BtreeEnter(pDb->pBt); - if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){ - rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0); - if( rc!=SQLITE_OK ){ - sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc)); - goto initone_error_out; - } - openedTransaction = 1; - } - - /* Get the database meta information. - ** - ** Meta values are as follows: - ** meta[0] Schema cookie. Changes with each schema change. - ** meta[1] File format of schema layer. - ** meta[2] Size of the page cache. - ** meta[3] Largest rootpage (auto/incr_vacuum mode) - ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE - ** meta[5] User version - ** meta[6] Incremental vacuum mode - ** meta[7] unused - ** meta[8] unused - ** meta[9] unused - ** - ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to - ** the possible values of meta[4]. - */ - for(i=0; ipBt, i+1, (u32 *)&meta[i]); - } - if( (db->flags & SQLITE_ResetDatabase)!=0 ){ - memset(meta, 0, sizeof(meta)); - } - pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1]; - - /* If opening a non-empty database, check the text encoding. For the - ** main database, set sqlite3.enc to the encoding of the main database. - ** For an attached db, it is an error if the encoding is not the same - ** as sqlite3.enc. - */ - if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */ - if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){ - u8 encoding; -#ifndef SQLITE_OMIT_UTF16 - /* If opening the main database, set ENC(db). */ - encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3; - if( encoding==0 ) encoding = SQLITE_UTF8; -#else - encoding = SQLITE_UTF8; -#endif - sqlite3SetTextEncoding(db, encoding); - }else{ - /* If opening an attached database, the encoding much match ENC(db) */ - if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){ - sqlite3SetString(pzErrMsg, db, "attached databases must use the same" - " text encoding as main database"); - rc = SQLITE_ERROR; - goto initone_error_out; - } - } - } - pDb->pSchema->enc = ENC(db); - - if( pDb->pSchema->cache_size==0 ){ -#ifndef SQLITE_OMIT_DEPRECATED - size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]); - if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } - pDb->pSchema->cache_size = size; -#else - pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE; -#endif - sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); - } - - /* - ** file_format==1 Version 3.0.0. - ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN - ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults - ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants - */ - pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1]; - if( pDb->pSchema->file_format==0 ){ - pDb->pSchema->file_format = 1; - } - if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ - sqlite3SetString(pzErrMsg, db, "unsupported file format"); - rc = SQLITE_ERROR; - goto initone_error_out; - } - - /* Ticket #2804: When we open a database in the newer file format, - ** clear the legacy_file_format pragma flag so that a VACUUM will - ** not downgrade the database and thus invalidate any descending - ** indices that the user might have created. - */ - if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){ - db->flags &= ~(u64)SQLITE_LegacyFileFmt; - } - - /* Read the schema information out of the schema tables - */ - assert( db->init.busy ); - initData.mxPage = sqlite3BtreeLastPage(pDb->pBt); - { - char *zSql; - zSql = sqlite3MPrintf(db, - "SELECT*FROM\"%w\".%s ORDER BY rowid", - db->aDb[iDb].zDbSName, zSchemaTabName); -#ifndef SQLITE_OMIT_AUTHORIZATION - { - sqlite3_xauth xAuth; - xAuth = db->xAuth; - db->xAuth = 0; -#endif - rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); -#ifndef SQLITE_OMIT_AUTHORIZATION - db->xAuth = xAuth; - } -#endif - if( rc==SQLITE_OK ) rc = initData.rc; - sqlite3DbFree(db, zSql); -#ifndef SQLITE_OMIT_ANALYZE - if( rc==SQLITE_OK ){ - sqlite3AnalysisLoad(db, iDb); - } -#endif - } - if( db->mallocFailed ){ - rc = SQLITE_NOMEM_BKPT; - sqlite3ResetAllSchemasOfConnection(db); - } - if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){ - /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider - ** the schema loaded, even if errors occurred. In this situation the - ** current sqlite3_prepare() operation will fail, but the following one - ** will attempt to compile the supplied statement against whatever subset - ** of the schema was loaded before the error occurred. The primary - ** purpose of this is to allow access to the sqlite_schema table - ** even when its contents have been corrupted. - */ - DbSetProperty(db, iDb, DB_SchemaLoaded); - rc = SQLITE_OK; - } - - /* Jump here for an error that occurs after successfully allocating - ** curMain and calling sqlite3BtreeEnter(). For an error that occurs - ** before that point, jump to error_out. - */ -initone_error_out: - if( openedTransaction ){ - sqlite3BtreeCommit(pDb->pBt); - } - sqlite3BtreeLeave(pDb->pBt); - -error_out: - if( rc ){ - if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ - sqlite3OomFault(db); - } - sqlite3ResetOneSchema(db, iDb); - } - db->init.busy = 0; - return rc; -} - -/* -** Initialize all database files - the main database file, the file -** used to store temporary tables, and any additional database files -** created using ATTACH statements. Return a success code. If an -** error occurs, write an error message into *pzErrMsg. -** -** After a database is initialized, the DB_SchemaLoaded bit is set -** bit is set in the flags field of the Db structure. -*/ -SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){ - int i, rc; - int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange); - - assert( sqlite3_mutex_held(db->mutex) ); - assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) ); - assert( db->init.busy==0 ); - ENC(db) = SCHEMA_ENC(db); - assert( db->nDb>0 ); - /* Do the main schema first */ - if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){ - rc = sqlite3InitOne(db, 0, pzErrMsg, 0); - if( rc ) return rc; - } - /* All other schemas after the main schema. The "temp" schema must be last */ - for(i=db->nDb-1; i>0; i--){ - assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) ); - if( !DbHasProperty(db, i, DB_SchemaLoaded) ){ - rc = sqlite3InitOne(db, i, pzErrMsg, 0); - if( rc ) return rc; - } - } - if( commit_internal ){ - sqlite3CommitInternalChanges(db); - } - return SQLITE_OK; -} - -/* -** This routine is a no-op if the database schema is already initialized. -** Otherwise, the schema is loaded. An error code is returned. -*/ -SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){ - int rc = SQLITE_OK; - sqlite3 *db = pParse->db; - assert( sqlite3_mutex_held(db->mutex) ); - if( !db->init.busy ){ - rc = sqlite3Init(db, &pParse->zErrMsg); - if( rc!=SQLITE_OK ){ - pParse->rc = rc; - pParse->nErr++; - }else if( db->noSharedCache ){ - db->mDbFlags |= DBFLAG_SchemaKnownOk; - } - } - return rc; -} - - -/* -** Check schema cookies in all databases. If any cookie is out -** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies -** make no changes to pParse->rc. -*/ -static void schemaIsValid(Parse *pParse){ - sqlite3 *db = pParse->db; - int iDb; - int rc; - int cookie; - - assert( pParse->checkSchema ); - assert( sqlite3_mutex_held(db->mutex) ); - for(iDb=0; iDbnDb; iDb++){ - int openedTransaction = 0; /* True if a transaction is opened */ - Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */ - if( pBt==0 ) continue; - - /* If there is not already a read-only (or read-write) transaction opened - ** on the b-tree database, open one now. If a transaction is opened, it - ** will be closed immediately after reading the meta-value. */ - if( !sqlite3BtreeIsInReadTrans(pBt) ){ - rc = sqlite3BtreeBeginTrans(pBt, 0, 0); - if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ - sqlite3OomFault(db); - } - if( rc!=SQLITE_OK ) return; - openedTransaction = 1; - } - - /* Read the schema cookie from the database. If it does not match the - ** value stored as part of the in-memory schema representation, - ** set Parse.rc to SQLITE_SCHEMA. */ - sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie); - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){ - sqlite3ResetOneSchema(db, iDb); - pParse->rc = SQLITE_SCHEMA; - } - - /* Close the transaction, if one was opened. */ - if( openedTransaction ){ - sqlite3BtreeCommit(pBt); - } - } -} - -/* -** Convert a schema pointer into the iDb index that indicates -** which database file in db->aDb[] the schema refers to. -** -** If the same database is attached more than once, the first -** attached database is returned. -*/ -SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ - int i = -32768; - - /* If pSchema is NULL, then return -32768. This happens when code in - ** expr.c is trying to resolve a reference to a transient table (i.e. one - ** created by a sub-select). In this case the return value of this - ** function should never be used. - ** - ** We return -32768 instead of the more usual -1 simply because using - ** -32768 as the incorrect index into db->aDb[] is much - ** more likely to cause a segfault than -1 (of course there are assert() - ** statements too, but it never hurts to play the odds) and - ** -32768 will still fit into a 16-bit signed integer. - */ - assert( sqlite3_mutex_held(db->mutex) ); - if( pSchema ){ - for(i=0; 1; i++){ - assert( inDb ); - if( db->aDb[i].pSchema==pSchema ){ - break; - } - } - assert( i>=0 && inDb ); - } - return i; -} - -/* -** Deallocate a single AggInfo object -*/ -static void agginfoFree(sqlite3 *db, AggInfo *p){ - sqlite3DbFree(db, p->aCol); - sqlite3DbFree(db, p->aFunc); - sqlite3DbFree(db, p); -} - -/* -** Free all memory allocations in the pParse object -*/ -SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){ - sqlite3 *db = pParse->db; - AggInfo *pThis = pParse->pAggList; - while( pThis ){ - AggInfo *pNext = pThis->pNext; - agginfoFree(db, pThis); - pThis = pNext; - } - sqlite3DbFree(db, pParse->aLabel); - sqlite3ExprListDelete(db, pParse->pConstExpr); - if( db ){ - assert( db->lookaside.bDisable >= pParse->disableLookaside ); - db->lookaside.bDisable -= pParse->disableLookaside; - db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue; - } - pParse->disableLookaside = 0; -} - -/* -** Compile the UTF-8 encoded SQL statement zSql into a statement handle. -*/ -static int sqlite3Prepare( - sqlite3 *db, /* Database handle. */ - const char *zSql, /* UTF-8 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ - Vdbe *pReprepare, /* VM being reprepared */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const char **pzTail /* OUT: End of parsed string */ -){ - char *zErrMsg = 0; /* Error message */ - int rc = SQLITE_OK; /* Result code */ - int i; /* Loop counter */ - Parse sParse; /* Parsing context */ - - memset(&sParse, 0, PARSE_HDR_SZ); - memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ); - sParse.pReprepare = pReprepare; - assert( ppStmt && *ppStmt==0 ); - /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */ - assert( sqlite3_mutex_held(db->mutex) ); - - /* For a long-term use prepared statement avoid the use of - ** lookaside memory. - */ - if( prepFlags & SQLITE_PREPARE_PERSISTENT ){ - sParse.disableLookaside++; - DisableLookaside; - } - sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0; - - /* Check to verify that it is possible to get a read lock on all - ** database schemas. The inability to get a read lock indicates that - ** some other database connection is holding a write-lock, which in - ** turn means that the other connection has made uncommitted changes - ** to the schema. - ** - ** Were we to proceed and prepare the statement against the uncommitted - ** schema changes and if those schema changes are subsequently rolled - ** back and different changes are made in their place, then when this - ** prepared statement goes to run the schema cookie would fail to detect - ** the schema change. Disaster would follow. - ** - ** This thread is currently holding mutexes on all Btrees (because - ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it - ** is not possible for another thread to start a new schema change - ** while this routine is running. Hence, we do not need to hold - ** locks on the schema, we just need to make sure nobody else is - ** holding them. - ** - ** Note that setting READ_UNCOMMITTED overrides most lock detection, - ** but it does *not* override schema lock detection, so this all still - ** works even if READ_UNCOMMITTED is set. - */ - if( !db->noSharedCache ){ - for(i=0; inDb; i++) { - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - assert( sqlite3BtreeHoldsMutex(pBt) ); - rc = sqlite3BtreeSchemaLocked(pBt); - if( rc ){ - const char *zDb = db->aDb[i].zDbSName; - sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb); - testcase( db->flags & SQLITE_ReadUncommit ); - goto end_prepare; - } - } - } - } - - sqlite3VtabUnlockList(db); - - sParse.db = db; - if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ - char *zSqlCopy; - int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; - testcase( nBytes==mxLen ); - testcase( nBytes==mxLen+1 ); - if( nBytes>mxLen ){ - sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long"); - rc = sqlite3ApiExit(db, SQLITE_TOOBIG); - goto end_prepare; - } - zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); - if( zSqlCopy ){ - sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); - sParse.zTail = &zSql[sParse.zTail-zSqlCopy]; - sqlite3DbFree(db, zSqlCopy); - }else{ - sParse.zTail = &zSql[nBytes]; - } - }else{ - sqlite3RunParser(&sParse, zSql, &zErrMsg); - } - assert( 0==sParse.nQueryLoop ); - - if( sParse.rc==SQLITE_DONE ){ - sParse.rc = SQLITE_OK; - } - if( sParse.checkSchema ){ - schemaIsValid(&sParse); - } - if( pzTail ){ - *pzTail = sParse.zTail; - } - - if( db->init.busy==0 ){ - sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags); - } - if( db->mallocFailed ){ - sParse.rc = SQLITE_NOMEM_BKPT; - } - rc = sParse.rc; - if( rc!=SQLITE_OK ){ - if( sParse.pVdbe ) sqlite3VdbeFinalize(sParse.pVdbe); - assert(!(*ppStmt)); - }else{ - *ppStmt = (sqlite3_stmt*)sParse.pVdbe; - } - - if( zErrMsg ){ - sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg); - sqlite3DbFree(db, zErrMsg); - }else{ - sqlite3Error(db, rc); - } - - /* Delete any TriggerPrg structures allocated while parsing this statement. */ - while( sParse.pTriggerPrg ){ - TriggerPrg *pT = sParse.pTriggerPrg; - sParse.pTriggerPrg = pT->pNext; - sqlite3DbFree(db, pT); - } - -end_prepare: - - sqlite3ParserReset(&sParse); - return rc; -} -static int sqlite3LockAndPrepare( - sqlite3 *db, /* Database handle. */ - const char *zSql, /* UTF-8 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ - Vdbe *pOld, /* VM being reprepared */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const char **pzTail /* OUT: End of parsed string */ -){ - int rc; - int cnt = 0; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; -#endif - *ppStmt = 0; - if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ - return SQLITE_MISUSE_BKPT; - } - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); - do{ - /* Make multiple attempts to compile the SQL, until it either succeeds - ** or encounters a permanent error. A schema problem after one schema - ** reset is considered a permanent error. */ - rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail); - assert( rc==SQLITE_OK || *ppStmt==0 ); - }while( rc==SQLITE_ERROR_RETRY - || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) ); - sqlite3BtreeLeaveAll(db); - rc = sqlite3ApiExit(db, rc); - assert( (rc&db->errMask)==rc ); - sqlite3_mutex_leave(db->mutex); - return rc; -} - - -/* -** Rerun the compilation of a statement after a schema change. -** -** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, -** if the statement cannot be recompiled because another connection has -** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error -** occurs, return SQLITE_SCHEMA. -*/ -SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){ - int rc; - sqlite3_stmt *pNew; - const char *zSql; - sqlite3 *db; - u8 prepFlags; - - assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); - zSql = sqlite3_sql((sqlite3_stmt *)p); - assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ - db = sqlite3VdbeDb(p); - assert( sqlite3_mutex_held(db->mutex) ); - prepFlags = sqlite3VdbePrepareFlags(p); - rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0); - if( rc ){ - if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); - } - assert( pNew==0 ); - return rc; - }else{ - assert( pNew!=0 ); - } - sqlite3VdbeSwap((Vdbe*)pNew, p); - sqlite3TransferBindings(pNew, (sqlite3_stmt*)p); - sqlite3VdbeResetStepResult((Vdbe*)pNew); - sqlite3VdbeFinalize((Vdbe*)pNew); - return SQLITE_OK; -} - - -/* -** Two versions of the official API. Legacy and new use. In the legacy -** version, the original SQL text is not saved in the prepared statement -** and so if a schema change occurs, SQLITE_SCHEMA is returned by -** sqlite3_step(). In the new version, the original SQL text is retained -** and the statement is automatically recompiled if an schema change -** occurs. -*/ -SQLITE_API int sqlite3_prepare( - sqlite3 *db, /* Database handle. */ - const char *zSql, /* UTF-8 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const char **pzTail /* OUT: End of parsed string */ -){ - int rc; - rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; -} -SQLITE_API int sqlite3_prepare_v2( - sqlite3 *db, /* Database handle. */ - const char *zSql, /* UTF-8 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const char **pzTail /* OUT: End of parsed string */ -){ - int rc; - /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works - ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags - ** parameter. - ** - ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */ - rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0, - ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); - return rc; -} -SQLITE_API int sqlite3_prepare_v3( - sqlite3 *db, /* Database handle. */ - const char *zSql, /* UTF-8 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const char **pzTail /* OUT: End of parsed string */ -){ - int rc; - /* EVIDENCE-OF: R-56861-42673 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_* flags. - ** - ** Proof by comparison to the implementation of sqlite3_prepare_v2() - ** directly above. */ - rc = sqlite3LockAndPrepare(db,zSql,nBytes, - SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK), - 0,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); - return rc; -} - - -#ifndef SQLITE_OMIT_UTF16 -/* -** Compile the UTF-16 encoded SQL statement zSql into a statement handle. -*/ -static int sqlite3Prepare16( - sqlite3 *db, /* Database handle. */ - const void *zSql, /* UTF-16 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const void **pzTail /* OUT: End of parsed string */ -){ - /* This function currently works by first transforming the UTF-16 - ** encoded string to UTF-8, then invoking sqlite3_prepare(). The - ** tricky bit is figuring out the pointer to return in *pzTail. - */ - char *zSql8; - const char *zTail8 = 0; - int rc = SQLITE_OK; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( ppStmt==0 ) return SQLITE_MISUSE_BKPT; -#endif - *ppStmt = 0; - if( !sqlite3SafetyCheckOk(db)||zSql==0 ){ - return SQLITE_MISUSE_BKPT; - } - if( nBytes>=0 ){ - int sz; - const char *z = (const char*)zSql; - for(sz=0; szmutex); - zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE); - if( zSql8 ){ - rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8); - } - - if( zTail8 && pzTail ){ - /* If sqlite3_prepare returns a tail pointer, we calculate the - ** equivalent pointer into the UTF-16 string by counting the unicode - ** characters between zSql8 and zTail8, and then returning a pointer - ** the same number of characters into the UTF-16 string. - */ - int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8)); - *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed); - } - sqlite3DbFree(db, zSql8); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** Two versions of the official API. Legacy and new use. In the legacy -** version, the original SQL text is not saved in the prepared statement -** and so if a schema change occurs, SQLITE_SCHEMA is returned by -** sqlite3_step(). In the new version, the original SQL text is retained -** and the statement is automatically recompiled if an schema change -** occurs. -*/ -SQLITE_API int sqlite3_prepare16( - sqlite3 *db, /* Database handle. */ - const void *zSql, /* UTF-16 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const void **pzTail /* OUT: End of parsed string */ -){ - int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; -} -SQLITE_API int sqlite3_prepare16_v2( - sqlite3 *db, /* Database handle. */ - const void *zSql, /* UTF-16 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const void **pzTail /* OUT: End of parsed string */ -){ - int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; -} -SQLITE_API int sqlite3_prepare16_v3( - sqlite3 *db, /* Database handle. */ - const void *zSql, /* UTF-16 encoded SQL statement. */ - int nBytes, /* Length of zSql in bytes. */ - unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */ - sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ - const void **pzTail /* OUT: End of parsed string */ -){ - int rc; - rc = sqlite3Prepare16(db,zSql,nBytes, - SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK), - ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; -} - -#endif /* SQLITE_OMIT_UTF16 */ - -/************** End of prepare.c *********************************************/ -/************** Begin file select.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 C code routines that are called by the parser -** to handle SELECT statements in SQLite. -*/ -/* #include "sqliteInt.h" */ - -/* -** An instance of the following object is used to record information about -** how to process the DISTINCT keyword, to simplify passing that information -** into the selectInnerLoop() routine. -*/ -typedef struct DistinctCtx DistinctCtx; -struct DistinctCtx { - u8 isTnct; /* True if the DISTINCT keyword is present */ - u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ - int tabTnct; /* Ephemeral table used for DISTINCT processing */ - int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ -}; - -/* -** An instance of the following object is used to record information about -** the ORDER BY (or GROUP BY) clause of query is being coded. -** -** The aDefer[] array is used by the sorter-references optimization. For -** example, assuming there is no index that can be used for the ORDER BY, -** for the query: -** -** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10; -** -** it may be more efficient to add just the "a" values to the sorter, and -** retrieve the associated "bigblob" values directly from table t1 as the -** 10 smallest "a" values are extracted from the sorter. -** -** When the sorter-reference optimization is used, there is one entry in the -** aDefer[] array for each database table that may be read as values are -** extracted from the sorter. -*/ -typedef struct SortCtx SortCtx; -struct SortCtx { - ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ - int nOBSat; /* Number of ORDER BY terms satisfied by indices */ - int iECursor; /* Cursor number for the sorter */ - int regReturn; /* Register holding block-output return address */ - int labelBkOut; /* Start label for the block-output subroutine */ - int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ - int labelDone; /* Jump here when done, ex: LIMIT reached */ - int labelOBLopt; /* Jump here when sorter is full */ - u8 sortFlags; /* Zero or more SORTFLAG_* bits */ -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - u8 nDefer; /* Number of valid entries in aDefer[] */ - struct DeferredCsr { - Table *pTab; /* Table definition */ - int iCsr; /* Cursor number for table */ - int nKey; /* Number of PK columns for table pTab (>=1) */ - } aDefer[4]; -#endif - struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */ -}; -#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ - -/* -** Delete all the content of a Select structure. Deallocate the structure -** itself depending on the value of bFree -** -** If bFree==1, call sqlite3DbFree() on the p object. -** If bFree==0, Leave the first Select object unfreed -*/ -static void clearSelect(sqlite3 *db, Select *p, int bFree){ - while( p ){ - Select *pPrior = p->pPrior; - sqlite3ExprListDelete(db, p->pEList); - sqlite3SrcListDelete(db, p->pSrc); - sqlite3ExprDelete(db, p->pWhere); - sqlite3ExprListDelete(db, p->pGroupBy); - sqlite3ExprDelete(db, p->pHaving); - sqlite3ExprListDelete(db, p->pOrderBy); - sqlite3ExprDelete(db, p->pLimit); -#ifndef SQLITE_OMIT_WINDOWFUNC - if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){ - sqlite3WindowListDelete(db, p->pWinDefn); - } -#endif - if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith); - if( bFree ) sqlite3DbFreeNN(db, p); - p = pPrior; - bFree = 1; - } -} - -/* -** Initialize a SelectDest structure. -*/ -SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ - pDest->eDest = (u8)eDest; - pDest->iSDParm = iParm; - pDest->iSDParm2 = 0; - pDest->zAffSdst = 0; - pDest->iSdst = 0; - pDest->nSdst = 0; -} - - -/* -** Allocate a new Select structure and return a pointer to that -** structure. -*/ -SQLITE_PRIVATE Select *sqlite3SelectNew( - Parse *pParse, /* Parsing context */ - ExprList *pEList, /* which columns to include in the result */ - SrcList *pSrc, /* the FROM clause -- which tables to scan */ - Expr *pWhere, /* the WHERE clause */ - ExprList *pGroupBy, /* the GROUP BY clause */ - Expr *pHaving, /* the HAVING clause */ - ExprList *pOrderBy, /* the ORDER BY clause */ - u32 selFlags, /* Flag parameters, such as SF_Distinct */ - Expr *pLimit /* LIMIT value. NULL means not used */ -){ - Select *pNew, *pAllocated; - Select standin; - pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); - if( pNew==0 ){ - assert( pParse->db->mallocFailed ); - pNew = &standin; - } - if( pEList==0 ){ - pEList = sqlite3ExprListAppend(pParse, 0, - sqlite3Expr(pParse->db,TK_ASTERISK,0)); - } - pNew->pEList = pEList; - pNew->op = TK_SELECT; - pNew->selFlags = selFlags; - pNew->iLimit = 0; - pNew->iOffset = 0; - pNew->selId = ++pParse->nSelect; - pNew->addrOpenEphm[0] = -1; - pNew->addrOpenEphm[1] = -1; - pNew->nSelectRow = 0; - if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); - pNew->pSrc = pSrc; - pNew->pWhere = pWhere; - pNew->pGroupBy = pGroupBy; - pNew->pHaving = pHaving; - pNew->pOrderBy = pOrderBy; - pNew->pPrior = 0; - pNew->pNext = 0; - pNew->pLimit = pLimit; - pNew->pWith = 0; -#ifndef SQLITE_OMIT_WINDOWFUNC - pNew->pWin = 0; - pNew->pWinDefn = 0; -#endif - if( pParse->db->mallocFailed ) { - clearSelect(pParse->db, pNew, pNew!=&standin); - pAllocated = 0; - }else{ - assert( pNew->pSrc!=0 || pParse->nErr>0 ); - } - return pAllocated; -} - - -/* -** Delete the given Select structure and all of its substructures. -*/ -SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){ - if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); -} - -/* -** Return a pointer to the right-most SELECT statement in a compound. -*/ -static Select *findRightmost(Select *p){ - while( p->pNext ) p = p->pNext; - return p; -} - -/* -** Given 1 to 3 identifiers preceding the JOIN keyword, determine the -** type of join. Return an integer constant that expresses that type -** in terms of the following bit values: -** -** JT_INNER -** JT_CROSS -** JT_OUTER -** JT_NATURAL -** JT_LEFT -** JT_RIGHT -** -** A full outer join is the combination of JT_LEFT and JT_RIGHT. -** -** If an illegal or unsupported join type is seen, then still return -** a join type, but put an error in the pParse structure. -*/ -SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ - int jointype = 0; - Token *apAll[3]; - Token *p; - /* 0123456789 123456789 123456789 123 */ - static const char zKeyText[] = "naturaleftouterightfullinnercross"; - static const struct { - u8 i; /* Beginning of keyword text in zKeyText[] */ - u8 nChar; /* Length of the keyword in characters */ - u8 code; /* Join type mask */ - } aKeyword[] = { - /* natural */ { 0, 7, JT_NATURAL }, - /* left */ { 6, 4, JT_LEFT|JT_OUTER }, - /* outer */ { 10, 5, JT_OUTER }, - /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, - /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, - /* inner */ { 23, 5, JT_INNER }, - /* cross */ { 28, 5, JT_INNER|JT_CROSS }, - }; - int i, j; - apAll[0] = pA; - apAll[1] = pB; - apAll[2] = pC; - for(i=0; i<3 && apAll[i]; i++){ - p = apAll[i]; - for(j=0; jn==aKeyword[j].nChar - && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ - jointype |= aKeyword[j].code; - break; - } - } - testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); - if( j>=ArraySize(aKeyword) ){ - jointype |= JT_ERROR; - break; - } - } - if( - (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || - (jointype & JT_ERROR)!=0 - ){ - const char *zSp = " "; - assert( pB!=0 ); - if( pC==0 ){ zSp++; } - sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " - "%T %T%s%T", pA, pB, zSp, pC); - jointype = JT_INNER; - }else if( (jointype & JT_OUTER)!=0 - && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ - sqlite3ErrorMsg(pParse, - "RIGHT and FULL OUTER JOINs are not currently supported"); - jointype = JT_INNER; - } - return jointype; -} - -/* -** Return the index of a column in a table. Return -1 if the column -** is not contained in the table. -*/ -static int columnIndex(Table *pTab, const char *zCol){ - int i; - u8 h = sqlite3StrIHash(zCol); - Column *pCol; - for(pCol=pTab->aCol, i=0; inCol; pCol++, i++){ - if( pCol->hName==h && sqlite3StrICmp(pCol->zName, zCol)==0 ) return i; - } - return -1; -} - -/* -** Search the first N tables in pSrc, from left to right, looking for a -** table that has a column named zCol. -** -** When found, set *piTab and *piCol to the table index and column index -** of the matching column and return TRUE. -** -** If not found, return FALSE. -*/ -static int tableAndColumnIndex( - SrcList *pSrc, /* Array of tables to search */ - int N, /* Number of tables in pSrc->a[] to search */ - const char *zCol, /* Name of the column we are looking for */ - int *piTab, /* Write index of pSrc->a[] here */ - int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ - int bIgnoreHidden /* True to ignore hidden columns */ -){ - int i; /* For looping over tables in pSrc */ - int iCol; /* Index of column matching zCol */ - - assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ - for(i=0; ia[i].pTab, zCol); - if( iCol>=0 - && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0) - ){ - if( piTab ){ - *piTab = i; - *piCol = iCol; - } - return 1; - } - } - return 0; -} - -/* -** This function is used to add terms implied by JOIN syntax to the -** WHERE clause expression of a SELECT statement. The new term, which -** is ANDed with the existing WHERE clause, is of the form: -** -** (tab1.col1 = tab2.col2) -** -** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the -** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is -** column iColRight of tab2. -*/ -static void addWhereTerm( - Parse *pParse, /* Parsing context */ - SrcList *pSrc, /* List of tables in FROM clause */ - int iLeft, /* Index of first table to join in pSrc */ - int iColLeft, /* Index of column in first table */ - int iRight, /* Index of second table in pSrc */ - int iColRight, /* Index of column in second table */ - int isOuterJoin, /* True if this is an OUTER join */ - Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ -){ - sqlite3 *db = pParse->db; - Expr *pE1; - Expr *pE2; - Expr *pEq; - - assert( iLeftnSrc>iRight ); - assert( pSrc->a[iLeft].pTab ); - assert( pSrc->a[iRight].pTab ); - - pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); - pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); - - pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); - if( pEq && isOuterJoin ){ - ExprSetProperty(pEq, EP_FromJoin); - assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); - ExprSetVVAProperty(pEq, EP_NoReduce); - pEq->iRightJoinTable = (i16)pE2->iTable; - } - *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq); -} - -/* -** Set the EP_FromJoin property on all terms of the given expression. -** And set the Expr.iRightJoinTable to iTable for every term in the -** expression. -** -** The EP_FromJoin property is used on terms of an expression to tell -** the LEFT OUTER JOIN processing logic that this term is part of the -** join restriction specified in the ON or USING clause and not a part -** of the more general WHERE clause. These terms are moved over to the -** WHERE clause during join processing but we need to remember that they -** originated in the ON or USING clause. -** -** The Expr.iRightJoinTable tells the WHERE clause processing that the -** expression depends on table iRightJoinTable even if that table is not -** explicitly mentioned in the expression. That information is needed -** for cases like this: -** -** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 -** -** The where clause needs to defer the handling of the t1.x=5 -** term until after the t2 loop of the join. In that way, a -** NULL t2 row will be inserted whenever t1.x!=5. If we do not -** defer the handling of t1.x=5, it will be processed immediately -** after the t1 loop and rows with t1.x!=5 will never appear in -** the output, which is incorrect. -*/ -SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){ - while( p ){ - ExprSetProperty(p, EP_FromJoin); - assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); - ExprSetVVAProperty(p, EP_NoReduce); - p->iRightJoinTable = (i16)iTable; - if( p->op==TK_FUNCTION && p->x.pList ){ - int i; - for(i=0; ix.pList->nExpr; i++){ - sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable); - } - } - sqlite3SetJoinExpr(p->pLeft, iTable); - p = p->pRight; - } -} - -/* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every -** term that is marked with EP_FromJoin and iRightJoinTable==iTable into -** an ordinary term that omits the EP_FromJoin mark. -** -** This happens when a LEFT JOIN is simplified into an ordinary JOIN. -*/ -static void unsetJoinExpr(Expr *p, int iTable){ - while( p ){ - if( ExprHasProperty(p, EP_FromJoin) - && (iTable<0 || p->iRightJoinTable==iTable) ){ - ExprClearProperty(p, EP_FromJoin); - } - if( p->op==TK_FUNCTION && p->x.pList ){ - int i; - for(i=0; ix.pList->nExpr; i++){ - unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); - } - } - unsetJoinExpr(p->pLeft, iTable); - p = p->pRight; - } -} - -/* -** This routine processes the join information for a SELECT statement. -** ON and USING clauses are converted into extra terms of the WHERE clause. -** NATURAL joins also create extra WHERE clause terms. -** -** The terms of a FROM clause are contained in the Select.pSrc structure. -** The left most table is the first entry in Select.pSrc. The right-most -** table is the last entry. The join operator is held in the entry to -** the left. Thus entry 0 contains the join operator for the join between -** entries 0 and 1. Any ON or USING clauses associated with the join are -** also attached to the left entry. -** -** This routine returns the number of errors encountered. -*/ -static int sqliteProcessJoin(Parse *pParse, Select *p){ - SrcList *pSrc; /* All tables in the FROM clause */ - int i, j; /* Loop counters */ - struct SrcList_item *pLeft; /* Left table being joined */ - struct SrcList_item *pRight; /* Right table being joined */ - - pSrc = p->pSrc; - pLeft = &pSrc->a[0]; - pRight = &pLeft[1]; - for(i=0; inSrc-1; i++, pRight++, pLeft++){ - Table *pRightTab = pRight->pTab; - int isOuter; - - if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; - isOuter = (pRight->fg.jointype & JT_OUTER)!=0; - - /* When the NATURAL keyword is present, add WHERE clause terms for - ** every column that the two tables have in common. - */ - if( pRight->fg.jointype & JT_NATURAL ){ - if( pRight->pOn || pRight->pUsing ){ - sqlite3ErrorMsg(pParse, "a NATURAL join may not have " - "an ON or USING clause", 0); - return 1; - } - for(j=0; jnCol; j++){ - char *zName; /* Name of column in the right table */ - int iLeft; /* Matching left table */ - int iLeftCol; /* Matching column in the left table */ - - if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue; - zName = pRightTab->aCol[j].zName; - if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){ - addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, - isOuter, &p->pWhere); - } - } - } - - /* Disallow both ON and USING clauses in the same join - */ - if( pRight->pOn && pRight->pUsing ){ - sqlite3ErrorMsg(pParse, "cannot have both ON and USING " - "clauses in the same join"); - return 1; - } - - /* Add the ON clause to the end of the WHERE clause, connected by - ** an AND operator. - */ - if( pRight->pOn ){ - if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor); - p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn); - pRight->pOn = 0; - } - - /* Create extra terms on the WHERE clause for each column named - ** in the USING clause. Example: If the two tables to be joined are - ** A and B and the USING clause names X, Y, and Z, then add this - ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z - ** Report an error if any column mentioned in the USING clause is - ** not contained in both tables to be joined. - */ - if( pRight->pUsing ){ - IdList *pList = pRight->pUsing; - for(j=0; jnId; j++){ - char *zName; /* Name of the term in the USING clause */ - int iLeft; /* Table on the left with matching column name */ - int iLeftCol; /* Column number of matching column on the left */ - int iRightCol; /* Column number of matching column on the right */ - - zName = pList->a[j].zName; - iRightCol = columnIndex(pRightTab, zName); - if( iRightCol<0 - || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0) - ){ - sqlite3ErrorMsg(pParse, "cannot join using column %s - column " - "not present in both tables", zName); - return 1; - } - addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, - isOuter, &p->pWhere); - } - } - } - return 0; -} - -/* -** An instance of this object holds information (beyond pParse and pSelect) -** needed to load the next result row that is to be added to the sorter. -*/ -typedef struct RowLoadInfo RowLoadInfo; -struct RowLoadInfo { - int regResult; /* Store results in array of registers here */ - u8 ecelFlags; /* Flag argument to ExprCodeExprList() */ -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - ExprList *pExtra; /* Extra columns needed by sorter refs */ - int regExtraResult; /* Where to load the extra columns */ -#endif -}; - -/* -** This routine does the work of loading query data into an array of -** registers so that it can be added to the sorter. -*/ -static void innerLoopLoadRow( - Parse *pParse, /* Statement under construction */ - Select *pSelect, /* The query being coded */ - RowLoadInfo *pInfo /* Info needed to complete the row load */ -){ - sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult, - 0, pInfo->ecelFlags); -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - if( pInfo->pExtra ){ - sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0); - sqlite3ExprListDelete(pParse->db, pInfo->pExtra); - } -#endif -} - -/* -** Code the OP_MakeRecord instruction that generates the entry to be -** added into the sorter. -** -** Return the register in which the result is stored. -*/ -static int makeSorterRecord( - Parse *pParse, - SortCtx *pSort, - Select *pSelect, - int regBase, - int nBase -){ - int nOBSat = pSort->nOBSat; - Vdbe *v = pParse->pVdbe; - int regOut = ++pParse->nMem; - if( pSort->pDeferredRowLoad ){ - innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad); - } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut); - return regOut; -} - -/* -** Generate code that will push the record in registers regData -** through regData+nData-1 onto the sorter. -*/ -static void pushOntoSorter( - Parse *pParse, /* Parser context */ - SortCtx *pSort, /* Information about the ORDER BY clause */ - Select *pSelect, /* The whole SELECT statement */ - int regData, /* First register holding data to be sorted */ - int regOrigData, /* First register holding data before packing */ - int nData, /* Number of elements in the regData data array */ - int nPrefixReg /* No. of reg prior to regData available for use */ -){ - Vdbe *v = pParse->pVdbe; /* Stmt under construction */ - int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); - int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ - int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ - int regBase; /* Regs for sorter record */ - int regRecord = 0; /* Assembled sorter record */ - int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ - int op; /* Opcode to add sorter record to sorter */ - int iLimit; /* LIMIT counter */ - int iSkip = 0; /* End of the sorter insert loop */ - - assert( bSeq==0 || bSeq==1 ); - - /* Three cases: - ** (1) The data to be sorted has already been packed into a Record - ** by a prior OP_MakeRecord. In this case nData==1 and regData - ** will be completely unrelated to regOrigData. - ** (2) All output columns are included in the sort record. In that - ** case regData==regOrigData. - ** (3) Some output columns are omitted from the sort record due to - ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the - ** SQLITE_ECEL_OMITREF optimization, or due to the - ** SortCtx.pDeferredRowLoad optimiation. In any of these cases - ** regOrigData is 0 to prevent this routine from trying to copy - ** values that might not yet exist. - */ - assert( nData==1 || regData==regOrigData || regOrigData==0 ); - - if( nPrefixReg ){ - assert( nPrefixReg==nExpr+bSeq ); - regBase = regData - nPrefixReg; - }else{ - regBase = pParse->nMem + 1; - pParse->nMem += nBase; - } - assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); - iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; - pSort->labelDone = sqlite3VdbeMakeLabel(pParse); - sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, - SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); - if( bSeq ){ - sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); - } - if( nPrefixReg==0 && nData>0 ){ - sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); - } - if( nOBSat>0 ){ - int regPrevKey; /* The first nOBSat columns of the previous row */ - int addrFirst; /* Address of the OP_IfNot opcode */ - int addrJmp; /* Address of the OP_Jump opcode */ - VdbeOp *pOp; /* Opcode that opens the sorter */ - int nKey; /* Number of sorting key columns, including OP_Sequence */ - KeyInfo *pKI; /* Original KeyInfo on the sorter table */ - - regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); - regPrevKey = pParse->nMem+1; - pParse->nMem += pSort->nOBSat; - nKey = nExpr - pSort->nOBSat + bSeq; - if( bSeq ){ - addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); - }else{ - addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); - } - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); - pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); - if( pParse->db->mallocFailed ) return; - pOp->p2 = nKey + nData; - pKI = pOp->p4.pKeyInfo; - memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */ - sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); - testcase( pKI->nAllField > pKI->nKeyField+2 ); - pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat, - pKI->nAllField-pKI->nKeyField-1); - pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */ - addrJmp = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); - pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse); - pSort->regReturn = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); - sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); - if( iLimit ){ - sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); - VdbeCoverage(v); - } - sqlite3VdbeJumpHere(v, addrFirst); - sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); - sqlite3VdbeJumpHere(v, addrJmp); - } - if( iLimit ){ - /* At this point the values for the new sorter entry are stored - ** in an array of registers. They need to be composed into a record - ** and inserted into the sorter if either (a) there are currently - ** less than LIMIT+OFFSET items or (b) the new record is smaller than - ** the largest record currently in the sorter. If (b) is true and there - ** are already LIMIT+OFFSET items in the sorter, delete the largest - ** entry before inserting the new one. This way there are never more - ** than LIMIT+OFFSET items in the sorter. - ** - ** If the new record does not need to be inserted into the sorter, - ** jump to the next iteration of the loop. If the pSort->labelOBLopt - ** value is not zero, then it is a label of where to jump. Otherwise, - ** just bypass the row insert logic. See the header comment on the - ** sqlite3WhereOrderByLimitOptLabel() function for additional info. - */ - int iCsr = pSort->iECursor; - sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4); - VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0); - iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE, - iCsr, 0, regBase+nOBSat, nExpr-nOBSat); - VdbeCoverage(v); - sqlite3VdbeAddOp1(v, OP_Delete, iCsr); - } - if( regRecord==0 ){ - regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); - } - if( pSort->sortFlags & SORTFLAG_UseSorter ){ - op = OP_SorterInsert; - }else{ - op = OP_IdxInsert; - } - sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, - regBase+nOBSat, nBase-nOBSat); - if( iSkip ){ - sqlite3VdbeChangeP2(v, iSkip, - pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v)); - } -} - -/* -** Add code to implement the OFFSET -*/ -static void codeOffset( - Vdbe *v, /* Generate code into this VM */ - int iOffset, /* Register holding the offset counter */ - int iContinue /* Jump here to skip the current record */ -){ - if( iOffset>0 ){ - sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); - VdbeComment((v, "OFFSET")); - } -} - -/* -** Add code that will check to make sure the N registers starting at iMem -** form a distinct entry. iTab is a sorting index that holds previously -** seen combinations of the N values. A new entry is made in iTab -** if the current N values are new. -** -** A jump to addrRepeat is made and the N+1 values are popped from the -** stack if the top N elements are not distinct. -*/ -static void codeDistinct( - Parse *pParse, /* Parsing and code generating context */ - int iTab, /* A sorting index used to test for distinctness */ - int addrRepeat, /* Jump to here if not distinct */ - int N, /* Number of elements */ - int iMem /* First element */ -){ - Vdbe *v; - int r1; - - v = pParse->pVdbe; - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); - sqlite3ReleaseTempReg(pParse, r1); -} - -#ifdef SQLITE_ENABLE_SORTER_REFERENCES -/* -** This function is called as part of inner-loop generation for a SELECT -** statement with an ORDER BY that is not optimized by an index. It -** determines the expressions, if any, that the sorter-reference -** optimization should be used for. The sorter-reference optimization -** is used for SELECT queries like: -** -** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 -** -** If the optimization is used for expression "bigblob", then instead of -** storing values read from that column in the sorter records, the PK of -** the row from table t1 is stored instead. Then, as records are extracted from -** the sorter to return to the user, the required value of bigblob is -** retrieved directly from table t1. If the values are very large, this -** can be more efficient than storing them directly in the sorter records. -** -** The ExprList_item.bSorterRef flag is set for each expression in pEList -** for which the sorter-reference optimization should be enabled. -** Additionally, the pSort->aDefer[] array is populated with entries -** for all cursors required to evaluate all selected expressions. Finally. -** output variable (*ppExtra) is set to an expression list containing -** expressions for all extra PK values that should be stored in the -** sorter records. -*/ -static void selectExprDefer( - Parse *pParse, /* Leave any error here */ - SortCtx *pSort, /* Sorter context */ - ExprList *pEList, /* Expressions destined for sorter */ - ExprList **ppExtra /* Expressions to append to sorter record */ -){ - int i; - int nDefer = 0; - ExprList *pExtra = 0; - for(i=0; inExpr; i++){ - struct ExprList_item *pItem = &pEList->a[i]; - if( pItem->u.x.iOrderByCol==0 ){ - Expr *pExpr = pItem->pExpr; - Table *pTab = pExpr->y.pTab; - if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab) - && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF) - ){ - int j; - for(j=0; jaDefer[j].iCsr==pExpr->iTable ) break; - } - if( j==nDefer ){ - if( nDefer==ArraySize(pSort->aDefer) ){ - continue; - }else{ - int nKey = 1; - int k; - Index *pPk = 0; - if( !HasRowid(pTab) ){ - pPk = sqlite3PrimaryKeyIndex(pTab); - nKey = pPk->nKeyCol; - } - for(k=0; kiTable = pExpr->iTable; - pNew->y.pTab = pExpr->y.pTab; - pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; - pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew); - } - } - pSort->aDefer[nDefer].pTab = pExpr->y.pTab; - pSort->aDefer[nDefer].iCsr = pExpr->iTable; - pSort->aDefer[nDefer].nKey = nKey; - nDefer++; - } - } - pItem->bSorterRef = 1; - } - } - } - pSort->nDefer = (u8)nDefer; - *ppExtra = pExtra; -} -#endif - -/* -** This routine generates the code for the inside of the inner loop -** of a SELECT. -** -** If srcTab is negative, then the p->pEList expressions -** are evaluated in order to get the data for this row. If srcTab is -** zero or more, then data is pulled from srcTab and p->pEList is used only -** to get the number of columns and the collation sequence for each column. -*/ -static void selectInnerLoop( - Parse *pParse, /* The parser context */ - Select *p, /* The complete select statement being coded */ - int srcTab, /* Pull data from this table if non-negative */ - SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ - DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ - SelectDest *pDest, /* How to dispose of the results */ - int iContinue, /* Jump here to continue with next row */ - int iBreak /* Jump here to break out of the inner loop */ -){ - Vdbe *v = pParse->pVdbe; - int i; - int hasDistinct; /* True if the DISTINCT keyword is present */ - int eDest = pDest->eDest; /* How to dispose of results */ - int iParm = pDest->iSDParm; /* First argument to disposal method */ - int nResultCol; /* Number of result columns */ - int nPrefixReg = 0; /* Number of extra registers before regResult */ - RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */ - - /* Usually, regResult is the first cell in an array of memory cells - ** containing the current result row. In this case regOrig is set to the - ** same value. However, if the results are being sent to the sorter, the - ** values for any expressions that are also part of the sort-key are omitted - ** from this array. In this case regOrig is set to zero. */ - int regResult; /* Start of memory holding current results */ - int regOrig; /* Start of memory holding full result (or 0) */ - - assert( v ); - assert( p->pEList!=0 ); - hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; - if( pSort && pSort->pOrderBy==0 ) pSort = 0; - if( pSort==0 && !hasDistinct ){ - assert( iContinue!=0 ); - codeOffset(v, p->iOffset, iContinue); - } - - /* Pull the requested columns. - */ - nResultCol = p->pEList->nExpr; - - if( pDest->iSdst==0 ){ - if( pSort ){ - nPrefixReg = pSort->pOrderBy->nExpr; - if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; - pParse->nMem += nPrefixReg; - } - pDest->iSdst = pParse->nMem+1; - pParse->nMem += nResultCol; - }else if( pDest->iSdst+nResultCol > pParse->nMem ){ - /* This is an error condition that can result, for example, when a SELECT - ** on the right-hand side of an INSERT contains more result columns than - ** there are columns in the table on the left. The error will be caught - ** and reported later. But we need to make sure enough memory is allocated - ** to avoid other spurious errors in the meantime. */ - pParse->nMem += nResultCol; - } - pDest->nSdst = nResultCol; - regOrig = regResult = pDest->iSdst; - if( srcTab>=0 ){ - for(i=0; ipEList->a[i].zEName)); - } - }else if( eDest!=SRT_Exists ){ -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - ExprList *pExtra = 0; -#endif - /* If the destination is an EXISTS(...) expression, the actual - ** values returned by the SELECT are not required. - */ - u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */ - ExprList *pEList; - if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ - ecelFlags = SQLITE_ECEL_DUP; - }else{ - ecelFlags = 0; - } - if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ - /* For each expression in p->pEList that is a copy of an expression in - ** the ORDER BY clause (pSort->pOrderBy), set the associated - ** iOrderByCol value to one more than the index of the ORDER BY - ** expression within the sort-key that pushOntoSorter() will generate. - ** This allows the p->pEList field to be omitted from the sorted record, - ** saving space and CPU cycles. */ - ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); - - for(i=pSort->nOBSat; ipOrderBy->nExpr; i++){ - int j; - if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ - p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; - } - } -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - selectExprDefer(pParse, pSort, p->pEList, &pExtra); - if( pExtra && pParse->db->mallocFailed==0 ){ - /* If there are any extra PK columns to add to the sorter records, - ** allocate extra memory cells and adjust the OpenEphemeral - ** instruction to account for the larger records. This is only - ** required if there are one or more WITHOUT ROWID tables with - ** composite primary keys in the SortCtx.aDefer[] array. */ - VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); - pOp->p2 += (pExtra->nExpr - pSort->nDefer); - pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); - pParse->nMem += pExtra->nExpr; - } -#endif - - /* Adjust nResultCol to account for columns that are omitted - ** from the sorter by the optimizations in this branch */ - pEList = p->pEList; - for(i=0; inExpr; i++){ - if( pEList->a[i].u.x.iOrderByCol>0 -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - || pEList->a[i].bSorterRef -#endif - ){ - nResultCol--; - regOrig = 0; - } - } - - testcase( regOrig ); - testcase( eDest==SRT_Set ); - testcase( eDest==SRT_Mem ); - testcase( eDest==SRT_Coroutine ); - testcase( eDest==SRT_Output ); - assert( eDest==SRT_Set || eDest==SRT_Mem - || eDest==SRT_Coroutine || eDest==SRT_Output - || eDest==SRT_Upfrom ); - } - sRowLoadInfo.regResult = regResult; - sRowLoadInfo.ecelFlags = ecelFlags; -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - sRowLoadInfo.pExtra = pExtra; - sRowLoadInfo.regExtraResult = regResult + nResultCol; - if( pExtra ) nResultCol += pExtra->nExpr; -#endif - if( p->iLimit - && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 - && nPrefixReg>0 - ){ - assert( pSort!=0 ); - assert( hasDistinct==0 ); - pSort->pDeferredRowLoad = &sRowLoadInfo; - regOrig = 0; - }else{ - innerLoopLoadRow(pParse, p, &sRowLoadInfo); - } - } - - /* If the DISTINCT keyword was present on the SELECT statement - ** and this row has been seen before, then do not make this row - ** part of the result. - */ - if( hasDistinct ){ - switch( pDistinct->eTnctType ){ - case WHERE_DISTINCT_ORDERED: { - VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ - int iJump; /* Jump destination */ - int regPrev; /* Previous row content */ - - /* Allocate space for the previous row */ - regPrev = pParse->nMem+1; - pParse->nMem += nResultCol; - - /* Change the OP_OpenEphemeral coded earlier to an OP_Null - ** sets the MEM_Cleared bit on the first register of the - ** previous value. This will cause the OP_Ne below to always - ** fail on the first iteration of the loop even if the first - ** row is all NULLs. - */ - sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); - pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); - pOp->opcode = OP_Null; - pOp->p1 = 1; - pOp->p2 = regPrev; - pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */ - - iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; - for(i=0; ipEList->a[i].pExpr); - if( idb->mallocFailed ); - sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); - break; - } - - case WHERE_DISTINCT_UNIQUE: { - sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); - break; - } - - default: { - assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); - codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, - regResult); - break; - } - } - if( pSort==0 ){ - codeOffset(v, p->iOffset, iContinue); - } - } - - switch( eDest ){ - /* In this mode, write each query result to the key of the temporary - ** table iParm. - */ -#ifndef SQLITE_OMIT_COMPOUND_SELECT - case SRT_Union: { - int r1; - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); - sqlite3ReleaseTempReg(pParse, r1); - break; - } - - /* Construct a record from the query result, but instead of - ** saving that record, use it as a key to delete elements from - ** the temporary table iParm. - */ - case SRT_Except: { - sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); - break; - } -#endif /* SQLITE_OMIT_COMPOUND_SELECT */ - - /* Store the result as data using a unique key. - */ - case SRT_Fifo: - case SRT_DistFifo: - case SRT_Table: - case SRT_EphemTab: { - int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); - testcase( eDest==SRT_Table ); - testcase( eDest==SRT_EphemTab ); - testcase( eDest==SRT_Fifo ); - testcase( eDest==SRT_DistFifo ); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); -#ifndef SQLITE_OMIT_CTE - if( eDest==SRT_DistFifo ){ - /* If the destination is DistFifo, then cursor (iParm+1) is open - ** on an ephemeral index. If the current row is already present - ** in the index, do not write it to the output. If not, add the - ** current row to the index and proceed with writing it to the - ** output table as well. */ - int addr = sqlite3VdbeCurrentAddr(v) + 4; - sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); - VdbeCoverage(v); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); - assert( pSort==0 ); - } -#endif - if( pSort ){ - assert( regResult==regOrig ); - pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg); - }else{ - int r2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); - sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3ReleaseTempReg(pParse, r2); - } - sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); - break; - } - - case SRT_Upfrom: { - if( pSort ){ - pushOntoSorter( - pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); - }else{ - int i2 = pDest->iSDParm2; - int r1 = sqlite3GetTempReg(pParse); - - /* If the UPDATE FROM join is an aggregate that matches no rows, it - ** might still be trying to return one row, because that is what - ** aggregates do. Don't record that empty row in the output table. */ - sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v); - - sqlite3VdbeAddOp3(v, OP_MakeRecord, - regResult+(i2<0), nResultCol-(i2<0), r1); - if( i2<0 ){ - sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult); - }else{ - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2); - } - } - break; - } - -#ifndef SQLITE_OMIT_SUBQUERY - /* If we are creating a set for an "expr IN (SELECT ...)" construct, - ** then there should be a single item on the stack. Write this - ** item into the set table with bogus data. - */ - case SRT_Set: { - if( pSort ){ - /* At first glance you would think we could optimize out the - ** ORDER BY in this case since the order of entries in the set - ** does not matter. But there might be a LIMIT clause, in which - ** case the order does matter */ - pushOntoSorter( - pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); - }else{ - int r1 = sqlite3GetTempReg(pParse); - assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, - r1, pDest->zAffSdst, nResultCol); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); - sqlite3ReleaseTempReg(pParse, r1); - } - break; - } - - - /* If any row exist in the result set, record that fact and abort. - */ - case SRT_Exists: { - sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); - /* The LIMIT clause will terminate the loop for us */ - break; - } - - /* If this is a scalar select that is part of an expression, then - ** store the results in the appropriate memory cell or array of - ** memory cells and break out of the scan loop. - */ - case SRT_Mem: { - if( pSort ){ - assert( nResultCol<=pDest->nSdst ); - pushOntoSorter( - pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); - }else{ - assert( nResultCol==pDest->nSdst ); - assert( regResult==iParm ); - /* The LIMIT clause will jump out of the loop for us */ - } - break; - } -#endif /* #ifndef SQLITE_OMIT_SUBQUERY */ - - case SRT_Coroutine: /* Send data to a co-routine */ - case SRT_Output: { /* Return the results */ - testcase( eDest==SRT_Coroutine ); - testcase( eDest==SRT_Output ); - if( pSort ){ - pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, - nPrefixReg); - }else if( eDest==SRT_Coroutine ){ - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); - }else{ - sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); - } - break; - } - -#ifndef SQLITE_OMIT_CTE - /* Write the results into a priority queue that is order according to - ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an - ** index with pSO->nExpr+2 columns. Build a key using pSO for the first - ** pSO->nExpr columns, then make sure all keys are unique by adding a - ** final OP_Sequence column. The last column is the record as a blob. - */ - case SRT_DistQueue: - case SRT_Queue: { - int nKey; - int r1, r2, r3; - int addrTest = 0; - ExprList *pSO; - pSO = pDest->pOrderBy; - assert( pSO ); - nKey = pSO->nExpr; - r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3GetTempRange(pParse, nKey+2); - r3 = r2+nKey+1; - if( eDest==SRT_DistQueue ){ - /* If the destination is DistQueue, then cursor (iParm+1) is open - ** on a second ephemeral index that holds all values every previously - ** added to the queue. */ - addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, - regResult, nResultCol); - VdbeCoverage(v); - } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); - if( eDest==SRT_DistQueue ){ - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); - } - for(i=0; ia[i].u.x.iOrderByCol - 1, - r2+i); - } - sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); - sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); - if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); - sqlite3ReleaseTempReg(pParse, r1); - sqlite3ReleaseTempRange(pParse, r2, nKey+2); - break; - } -#endif /* SQLITE_OMIT_CTE */ - - - -#if !defined(SQLITE_OMIT_TRIGGER) - /* Discard the results. This is used for SELECT statements inside - ** the body of a TRIGGER. The purpose of such selects is to call - ** user-defined functions that have side effects. We do not care - ** about the actual results of the select. - */ - default: { - assert( eDest==SRT_Discard ); - break; - } -#endif - } - - /* Jump to the end of the loop if the LIMIT is reached. Except, if - ** there is a sorter, in which case the sorter has already limited - ** the output for us. - */ - if( pSort==0 && p->iLimit ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); - } -} - -/* -** Allocate a KeyInfo object sufficient for an index of N key columns and -** X extra columns. -*/ -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ - int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); - KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); - if( p ){ - p->aSortFlags = (u8*)&p->aColl[N+X]; - p->nKeyField = (u16)N; - p->nAllField = (u16)(N+X); - p->enc = ENC(db); - p->db = db; - p->nRef = 1; - memset(&p[1], 0, nExtra); - }else{ - sqlite3OomFault(db); - } - return p; -} - -/* -** Deallocate a KeyInfo object -*/ -SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){ - if( p ){ - assert( p->nRef>0 ); - p->nRef--; - if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); - } -} - -/* -** Make a new pointer to a KeyInfo object -*/ -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ - if( p ){ - assert( p->nRef>0 ); - p->nRef++; - } - return p; -} - -#ifdef SQLITE_DEBUG -/* -** Return TRUE if a KeyInfo object can be change. The KeyInfo object -** can only be changed if this is just a single reference to the object. -** -** This routine is used only inside of assert() statements. -*/ -SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } -#endif /* SQLITE_DEBUG */ - -/* -** Given an expression list, generate a KeyInfo structure that records -** the collating sequence for each expression in that expression list. -** -** If the ExprList is an ORDER BY or GROUP BY clause then the resulting -** KeyInfo structure is appropriate for initializing a virtual index to -** implement that clause. If the ExprList is the result set of a SELECT -** then the KeyInfo structure is appropriate for initializing a virtual -** index to implement a DISTINCT test. -** -** Space to hold the KeyInfo structure is obtained from malloc. The calling -** function is responsible for seeing that this structure is eventually -** freed. -*/ -SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* Form the KeyInfo object from this ExprList */ - int iStart, /* Begin with this column of pList */ - int nExtra /* Add this many extra columns to the end */ -){ - int nExpr; - KeyInfo *pInfo; - struct ExprList_item *pItem; - sqlite3 *db = pParse->db; - int i; - - nExpr = pList->nExpr; - pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); - if( pInfo ){ - assert( sqlite3KeyInfoIsWriteable(pInfo) ); - for(i=iStart, pItem=pList->a+iStart; iaColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr); - pInfo->aSortFlags[i-iStart] = pItem->sortFlags; - } - } - return pInfo; -} - -/* -** Name of the connection operator, used for error messages. -*/ -static const char *selectOpName(int id){ - char *z; - switch( id ){ - case TK_ALL: z = "UNION ALL"; break; - case TK_INTERSECT: z = "INTERSECT"; break; - case TK_EXCEPT: z = "EXCEPT"; break; - default: z = "UNION"; break; - } - return z; -} - -#ifndef SQLITE_OMIT_EXPLAIN -/* -** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function -** is a no-op. Otherwise, it adds a single row of output to the EQP result, -** where the caption is of the form: -** -** "USE TEMP B-TREE FOR xxx" -** -** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which -** is determined by the zUsage argument. -*/ -static void explainTempTable(Parse *pParse, const char *zUsage){ - ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage)); -} - -/* -** Assign expression b to lvalue a. A second, no-op, version of this macro -** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code -** in sqlite3Select() to assign values to structure member variables that -** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the -** code with #ifndef directives. -*/ -# define explainSetInteger(a, b) a = b - -#else -/* No-op versions of the explainXXX() functions and macros. */ -# define explainTempTable(y,z) -# define explainSetInteger(y,z) -#endif - - -/* -** If the inner loop was generated using a non-null pOrderBy argument, -** then the results were placed in a sorter. After the loop is terminated -** we need to run the sorter and output the results. The following -** routine generates the code needed to do that. -*/ -static void generateSortTail( - Parse *pParse, /* Parsing context */ - Select *p, /* The SELECT statement */ - SortCtx *pSort, /* Information on the ORDER BY clause */ - int nColumn, /* Number of columns of data */ - SelectDest *pDest /* Write the sorted results here */ -){ - Vdbe *v = pParse->pVdbe; /* The prepared statement */ - int addrBreak = pSort->labelDone; /* Jump here to exit loop */ - int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */ - int addr; /* Top of output loop. Jump for Next. */ - int addrOnce = 0; - int iTab; - ExprList *pOrderBy = pSort->pOrderBy; - int eDest = pDest->eDest; - int iParm = pDest->iSDParm; - int regRow; - int regRowid; - int iCol; - int nKey; /* Number of key columns in sorter record */ - int iSortTab; /* Sorter cursor to read from */ - int i; - int bSeq; /* True if sorter record includes seq. no. */ - int nRefKey = 0; - struct ExprList_item *aOutEx = p->pEList->a; - - assert( addrBreak<0 ); - if( pSort->labelBkOut ){ - sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); - sqlite3VdbeGoto(v, addrBreak); - sqlite3VdbeResolveLabel(v, pSort->labelBkOut); - } - -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - /* Open any cursors needed for sorter-reference expressions */ - for(i=0; inDefer; i++){ - Table *pTab = pSort->aDefer[i].pTab; - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); - nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); - } -#endif - - iTab = pSort->iECursor; - if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ - regRowid = 0; - regRow = pDest->iSdst; - }else{ - regRowid = sqlite3GetTempReg(pParse); - if( eDest==SRT_EphemTab || eDest==SRT_Table ){ - regRow = sqlite3GetTempReg(pParse); - nColumn = 0; - }else{ - regRow = sqlite3GetTempRange(pParse, nColumn); - } - } - nKey = pOrderBy->nExpr - pSort->nOBSat; - if( pSort->sortFlags & SORTFLAG_UseSorter ){ - int regSortOut = ++pParse->nMem; - iSortTab = pParse->nTab++; - if( pSort->labelBkOut ){ - addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - } - sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, - nKey+1+nColumn+nRefKey); - if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); - addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); - VdbeCoverage(v); - codeOffset(v, p->iOffset, addrContinue); - sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); - bSeq = 0; - }else{ - addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); - codeOffset(v, p->iOffset, addrContinue); - iSortTab = iTab; - bSeq = 1; - } - for(i=0, iCol=nKey+bSeq-1; inDefer ){ - int iKey = iCol+1; - int regKey = sqlite3GetTempRange(pParse, nRefKey); - - for(i=0; inDefer; i++){ - int iCsr = pSort->aDefer[i].iCsr; - Table *pTab = pSort->aDefer[i].pTab; - int nKey = pSort->aDefer[i].nKey; - - sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); - if( HasRowid(pTab) ){ - sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); - sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, - sqlite3VdbeCurrentAddr(v)+1, regKey); - }else{ - int k; - int iJmp; - assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); - for(k=0; k=0; i--){ -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - if( aOutEx[i].bSorterRef ){ - sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); - }else -#endif - { - int iRead; - if( aOutEx[i].u.x.iOrderByCol ){ - iRead = aOutEx[i].u.x.iOrderByCol-1; - }else{ - iRead = iCol--; - } - sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); - VdbeComment((v, "%s", aOutEx[i].zEName)); - } - } - switch( eDest ){ - case SRT_Table: - case SRT_EphemTab: { - sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow); - sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - break; - } -#ifndef SQLITE_OMIT_SUBQUERY - case SRT_Set: { - assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, - pDest->zAffSdst, nColumn); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); - break; - } - case SRT_Mem: { - /* The LIMIT clause will terminate the loop for us */ - break; - } -#endif - case SRT_Upfrom: { - int i2 = pDest->iSDParm2; - int r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1); - if( i2<0 ){ - sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow); - }else{ - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2); - } - break; - } - default: { - assert( eDest==SRT_Output || eDest==SRT_Coroutine ); - testcase( eDest==SRT_Output ); - testcase( eDest==SRT_Coroutine ); - if( eDest==SRT_Output ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); - }else{ - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); - } - break; - } - } - if( regRowid ){ - if( eDest==SRT_Set ){ - sqlite3ReleaseTempRange(pParse, regRow, nColumn); - }else{ - sqlite3ReleaseTempReg(pParse, regRow); - } - sqlite3ReleaseTempReg(pParse, regRowid); - } - /* The bottom of the loop - */ - sqlite3VdbeResolveLabel(v, addrContinue); - if( pSort->sortFlags & SORTFLAG_UseSorter ){ - sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); - }else{ - sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); - } - if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); - sqlite3VdbeResolveLabel(v, addrBreak); -} - -/* -** Return a pointer to a string containing the 'declaration type' of the -** expression pExpr. The string may be treated as static by the caller. -** -** Also try to estimate the size of the returned value and return that -** result in *pEstWidth. -** -** The declaration type is the exact datatype definition extracted from the -** original CREATE TABLE statement if the expression is a column. The -** declaration type for a ROWID field is INTEGER. Exactly when an expression -** is considered a column can be complex in the presence of subqueries. The -** result-set expression in all of the following SELECT statements is -** considered a column by this function. -** -** SELECT col FROM tbl; -** SELECT (SELECT col FROM tbl; -** SELECT (SELECT col FROM tbl); -** SELECT abc FROM (SELECT col AS abc FROM tbl); -** -** The declaration type for any expression other than a column is NULL. -** -** This routine has either 3 or 6 parameters depending on whether or not -** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. -*/ -#ifdef SQLITE_ENABLE_COLUMN_METADATA -# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) -#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ -# define columnType(A,B,C,D,E) columnTypeImpl(A,B) -#endif -static const char *columnTypeImpl( - NameContext *pNC, -#ifndef SQLITE_ENABLE_COLUMN_METADATA - Expr *pExpr -#else - Expr *pExpr, - const char **pzOrigDb, - const char **pzOrigTab, - const char **pzOrigCol -#endif -){ - char const *zType = 0; - int j; -#ifdef SQLITE_ENABLE_COLUMN_METADATA - char const *zOrigDb = 0; - char const *zOrigTab = 0; - char const *zOrigCol = 0; -#endif - - assert( pExpr!=0 ); - assert( pNC->pSrcList!=0 ); - switch( pExpr->op ){ - case TK_COLUMN: { - /* The expression is a column. Locate the table the column is being - ** extracted from in NameContext.pSrcList. This table may be real - ** database table or a subquery. - */ - Table *pTab = 0; /* Table structure column is extracted from */ - Select *pS = 0; /* Select the column is extracted from */ - int iCol = pExpr->iColumn; /* Index of column in pTab */ - while( pNC && !pTab ){ - SrcList *pTabList = pNC->pSrcList; - for(j=0;jnSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); - if( jnSrc ){ - pTab = pTabList->a[j].pTab; - pS = pTabList->a[j].pSelect; - }else{ - pNC = pNC->pNext; - } - } - - if( pTab==0 ){ - /* At one time, code such as "SELECT new.x" within a trigger would - ** cause this condition to run. Since then, we have restructured how - ** trigger code is generated and so this condition is no longer - ** possible. However, it can still be true for statements like - ** the following: - ** - ** CREATE TABLE t1(col INTEGER); - ** SELECT (SELECT t1.col) FROM FROM t1; - ** - ** when columnType() is called on the expression "t1.col" in the - ** sub-select. In this case, set the column type to NULL, even - ** though it should really be "INTEGER". - ** - ** This is not a problem, as the column type of "t1.col" is never - ** used. When columnType() is called on the expression - ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT - ** branch below. */ - break; - } - - assert( pTab && pExpr->y.pTab==pTab ); - if( pS ){ - /* The "table" is actually a sub-select or a view in the FROM clause - ** of the SELECT statement. Return the declaration type and origin - ** data for the result-set column of the sub-select. - */ - if( iCol>=0 && iColpEList->nExpr ){ - /* If iCol is less than zero, then the expression requests the - ** rowid of the sub-select or view. This expression is legal (see - ** test case misc2.2.2) - it always evaluates to NULL. - */ - NameContext sNC; - Expr *p = pS->pEList->a[iCol].pExpr; - sNC.pSrcList = pS->pSrc; - sNC.pNext = pNC; - sNC.pParse = pNC->pParse; - zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); - } - }else{ - /* A real table or a CTE table */ - assert( !pS ); -#ifdef SQLITE_ENABLE_COLUMN_METADATA - if( iCol<0 ) iCol = pTab->iPKey; - assert( iCol==XN_ROWID || (iCol>=0 && iColnCol) ); - if( iCol<0 ){ - zType = "INTEGER"; - zOrigCol = "rowid"; - }else{ - zOrigCol = pTab->aCol[iCol].zName; - zType = sqlite3ColumnType(&pTab->aCol[iCol],0); - } - zOrigTab = pTab->zName; - if( pNC->pParse && pTab->pSchema ){ - int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); - zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; - } -#else - assert( iCol==XN_ROWID || (iCol>=0 && iColnCol) ); - if( iCol<0 ){ - zType = "INTEGER"; - }else{ - zType = sqlite3ColumnType(&pTab->aCol[iCol],0); - } -#endif - } - break; - } -#ifndef SQLITE_OMIT_SUBQUERY - case TK_SELECT: { - /* The expression is a sub-select. Return the declaration type and - ** origin info for the single column in the result set of the SELECT - ** statement. - */ - NameContext sNC; - Select *pS = pExpr->x.pSelect; - Expr *p = pS->pEList->a[0].pExpr; - assert( ExprHasProperty(pExpr, EP_xIsSelect) ); - sNC.pSrcList = pS->pSrc; - sNC.pNext = pNC; - sNC.pParse = pNC->pParse; - zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); - break; - } -#endif - } - -#ifdef SQLITE_ENABLE_COLUMN_METADATA - if( pzOrigDb ){ - assert( pzOrigTab && pzOrigCol ); - *pzOrigDb = zOrigDb; - *pzOrigTab = zOrigTab; - *pzOrigCol = zOrigCol; - } -#endif - return zType; -} - -/* -** Generate code that will tell the VDBE the declaration types of columns -** in the result set. -*/ -static void generateColumnTypes( - Parse *pParse, /* Parser context */ - SrcList *pTabList, /* List of tables */ - ExprList *pEList /* Expressions defining the result set */ -){ -#ifndef SQLITE_OMIT_DECLTYPE - Vdbe *v = pParse->pVdbe; - int i; - NameContext sNC; - sNC.pSrcList = pTabList; - sNC.pParse = pParse; - sNC.pNext = 0; - for(i=0; inExpr; i++){ - Expr *p = pEList->a[i].pExpr; - const char *zType; -#ifdef SQLITE_ENABLE_COLUMN_METADATA - const char *zOrigDb = 0; - const char *zOrigTab = 0; - const char *zOrigCol = 0; - zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); - - /* The vdbe must make its own copy of the column-type and other - ** column specific strings, in case the schema is reset before this - ** virtual machine is deleted. - */ - sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); - sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); - sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); -#else - zType = columnType(&sNC, p, 0, 0, 0); -#endif - sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); - } -#endif /* !defined(SQLITE_OMIT_DECLTYPE) */ -} - - -/* -** Compute the column names for a SELECT statement. -** -** The only guarantee that SQLite makes about column names is that if the -** column has an AS clause assigning it a name, that will be the name used. -** That is the only documented guarantee. However, countless applications -** developed over the years have made baseless assumptions about column names -** and will break if those assumptions changes. Hence, use extreme caution -** when modifying this routine to avoid breaking legacy. -** -** See Also: sqlite3ColumnsFromExprList() -** -** The PRAGMA short_column_names and PRAGMA full_column_names settings are -** deprecated. The default setting is short=ON, full=OFF. 99.9% of all -** applications should operate this way. Nevertheless, we need to support the -** other modes for legacy: -** -** short=OFF, full=OFF: Column name is the text of the expression has it -** originally appears in the SELECT statement. In -** other words, the zSpan of the result expression. -** -** short=ON, full=OFF: (This is the default setting). If the result -** refers directly to a table column, then the -** result column name is just the table column -** name: COLUMN. Otherwise use zSpan. -** -** full=ON, short=ANY: If the result refers directly to a table column, -** then the result column name with the table name -** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. -*/ -static void generateColumnNames( - Parse *pParse, /* Parser context */ - Select *pSelect /* Generate column names for this SELECT statement */ -){ - Vdbe *v = pParse->pVdbe; - int i; - Table *pTab; - SrcList *pTabList; - ExprList *pEList; - sqlite3 *db = pParse->db; - int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ - int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ - -#ifndef SQLITE_OMIT_EXPLAIN - /* If this is an EXPLAIN, skip this step */ - if( pParse->explain ){ - return; - } -#endif - - if( pParse->colNamesSet ) return; - /* Column names are determined by the left-most term of a compound select */ - while( pSelect->pPrior ) pSelect = pSelect->pPrior; - SELECTTRACE(1,pParse,pSelect,("generating column names\n")); - pTabList = pSelect->pSrc; - pEList = pSelect->pEList; - assert( v!=0 ); - assert( pTabList!=0 ); - pParse->colNamesSet = 1; - fullName = (db->flags & SQLITE_FullColNames)!=0; - srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; - sqlite3VdbeSetNumCols(v, pEList->nExpr); - for(i=0; inExpr; i++){ - Expr *p = pEList->a[i].pExpr; - - assert( p!=0 ); - assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ - assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */ - if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){ - /* An AS clause always takes first priority */ - char *zName = pEList->a[i].zEName; - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); - }else if( srcName && p->op==TK_COLUMN ){ - char *zCol; - int iCol = p->iColumn; - pTab = p->y.pTab; - assert( pTab!=0 ); - if( iCol<0 ) iCol = pTab->iPKey; - assert( iCol==-1 || (iCol>=0 && iColnCol) ); - if( iCol<0 ){ - zCol = "rowid"; - }else{ - zCol = pTab->aCol[iCol].zName; - } - if( fullName ){ - char *zName = 0; - zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); - }else{ - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); - } - }else{ - const char *z = pEList->a[i].zEName; - z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); - sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); - } - } - generateColumnTypes(pParse, pTabList, pEList); -} - -/* -** Given an expression list (which is really the list of expressions -** that form the result set of a SELECT statement) compute appropriate -** column names for a table that would hold the expression list. -** -** All column names will be unique. -** -** Only the column names are computed. Column.zType, Column.zColl, -** and other fields of Column are zeroed. -** -** Return SQLITE_OK on success. If a memory allocation error occurs, -** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. -** -** The only guarantee that SQLite makes about column names is that if the -** column has an AS clause assigning it a name, that will be the name used. -** That is the only documented guarantee. However, countless applications -** developed over the years have made baseless assumptions about column names -** and will break if those assumptions changes. Hence, use extreme caution -** when modifying this routine to avoid breaking legacy. -** -** See Also: generateColumnNames() -*/ -SQLITE_PRIVATE int sqlite3ColumnsFromExprList( - Parse *pParse, /* Parsing context */ - ExprList *pEList, /* Expr list from which to derive column names */ - i16 *pnCol, /* Write the number of columns here */ - Column **paCol /* Write the new column list here */ -){ - sqlite3 *db = pParse->db; /* Database connection */ - int i, j; /* Loop counters */ - u32 cnt; /* Index added to make the name unique */ - Column *aCol, *pCol; /* For looping over result columns */ - int nCol; /* Number of columns in the result set */ - char *zName; /* Column name */ - int nName; /* Size of name in zName[] */ - Hash ht; /* Hash table of column names */ - - sqlite3HashInit(&ht); - if( pEList ){ - nCol = pEList->nExpr; - aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); - testcase( aCol==0 ); - if( nCol>32767 ) nCol = 32767; - }else{ - nCol = 0; - aCol = 0; - } - assert( nCol==(i16)nCol ); - *pnCol = nCol; - *paCol = aCol; - - for(i=0, pCol=aCol; imallocFailed; i++, pCol++){ - /* Get an appropriate name for the column - */ - if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){ - /* If the column contains an "AS " phrase, use as the name */ - }else{ - Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr); - while( pColExpr->op==TK_DOT ){ - pColExpr = pColExpr->pRight; - assert( pColExpr!=0 ); - } - if( pColExpr->op==TK_COLUMN ){ - /* For columns use the column name name */ - int iCol = pColExpr->iColumn; - Table *pTab = pColExpr->y.pTab; - assert( pTab!=0 ); - if( iCol<0 ) iCol = pTab->iPKey; - zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; - }else if( pColExpr->op==TK_ID ){ - assert( !ExprHasProperty(pColExpr, EP_IntValue) ); - zName = pColExpr->u.zToken; - }else{ - /* Use the original text of the column expression as its name */ - zName = pEList->a[i].zEName; - } - } - if( zName && !sqlite3IsTrueOrFalse(zName) ){ - zName = sqlite3DbStrDup(db, zName); - }else{ - zName = sqlite3MPrintf(db,"column%d",i+1); - } - - /* Make sure the column name is unique. If the name is not unique, - ** append an integer to the name so that it becomes unique. - */ - cnt = 0; - while( zName && sqlite3HashFind(&ht, zName)!=0 ){ - nName = sqlite3Strlen30(zName); - if( nName>0 ){ - for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} - if( zName[j]==':' ) nName = j; - } - zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); - if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); - } - pCol->zName = zName; - pCol->hName = sqlite3StrIHash(zName); - sqlite3ColumnPropertiesFromName(0, pCol); - if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ - sqlite3OomFault(db); - } - } - sqlite3HashClear(&ht); - if( db->mallocFailed ){ - for(j=0; jdb; - NameContext sNC; - Column *pCol; - CollSeq *pColl; - int i; - Expr *p; - struct ExprList_item *a; - - assert( pSelect!=0 ); - assert( (pSelect->selFlags & SF_Resolved)!=0 ); - assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); - if( db->mallocFailed ) return; - memset(&sNC, 0, sizeof(sNC)); - sNC.pSrcList = pSelect->pSrc; - a = pSelect->pEList->a; - for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ - const char *zType; - int n, m; - p = a[i].pExpr; - zType = columnType(&sNC, p, 0, 0, 0); - /* pCol->szEst = ... // Column size est for SELECT tables never used */ - pCol->affinity = sqlite3ExprAffinity(p); - if( zType ){ - m = sqlite3Strlen30(zType); - n = sqlite3Strlen30(pCol->zName); - pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); - if( pCol->zName ){ - memcpy(&pCol->zName[n+1], zType, m+1); - pCol->colFlags |= COLFLAG_HASTYPE; - } - } - if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff; - pColl = sqlite3ExprCollSeq(pParse, p); - if( pColl && pCol->zColl==0 ){ - pCol->zColl = sqlite3DbStrDup(db, pColl->zName); - } - } - pTab->szTabRow = 1; /* Any non-zero value works */ -} - -/* -** Given a SELECT statement, generate a Table structure that describes -** the result set of that SELECT. -*/ -SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){ - Table *pTab; - sqlite3 *db = pParse->db; - u64 savedFlags; - - savedFlags = db->flags; - db->flags &= ~(u64)SQLITE_FullColNames; - db->flags |= SQLITE_ShortColNames; - sqlite3SelectPrep(pParse, pSelect, 0); - db->flags = savedFlags; - if( pParse->nErr ) return 0; - while( pSelect->pPrior ) pSelect = pSelect->pPrior; - pTab = sqlite3DbMallocZero(db, sizeof(Table) ); - if( pTab==0 ){ - return 0; - } - pTab->nTabRef = 1; - pTab->zName = 0; - pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); - sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); - sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff); - pTab->iPKey = -1; - if( db->mallocFailed ){ - sqlite3DeleteTable(db, pTab); - return 0; - } - return pTab; -} - -/* -** Get a VDBE for the given parser context. Create a new one if necessary. -** If an error occurs, return NULL and leave a message in pParse. -*/ -SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ - if( pParse->pVdbe ){ - return pParse->pVdbe; - } - if( pParse->pToplevel==0 - && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) - ){ - pParse->okConstFactor = 1; - } - return sqlite3VdbeCreate(pParse); -} - - -/* -** Compute the iLimit and iOffset fields of the SELECT based on the -** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions -** that appear in the original SQL statement after the LIMIT and OFFSET -** keywords. Or NULL if those keywords are omitted. iLimit and iOffset -** are the integer memory register numbers for counters used to compute -** the limit and offset. If there is no limit and/or offset, then -** iLimit and iOffset are negative. -** -** This routine changes the values of iLimit and iOffset only if -** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit -** and iOffset should have been preset to appropriate default values (zero) -** prior to calling this routine. -** -** The iOffset register (if it exists) is initialized to the value -** of the OFFSET. The iLimit register is initialized to LIMIT. Register -** iOffset+1 is initialized to LIMIT+OFFSET. -** -** Only if pLimit->pLeft!=0 do the limit registers get -** redefined. The UNION ALL operator uses this property to force -** the reuse of the same limit and offset registers across multiple -** SELECT statements. -*/ -static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ - Vdbe *v = 0; - int iLimit = 0; - int iOffset; - int n; - Expr *pLimit = p->pLimit; - - if( p->iLimit ) return; - - /* - ** "LIMIT -1" always shows all rows. There is some - ** controversy about what the correct behavior should be. - ** The current implementation interprets "LIMIT 0" to mean - ** no rows. - */ - if( pLimit ){ - assert( pLimit->op==TK_LIMIT ); - assert( pLimit->pLeft!=0 ); - p->iLimit = iLimit = ++pParse->nMem; - v = sqlite3GetVdbe(pParse); - assert( v!=0 ); - if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){ - sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); - VdbeComment((v, "LIMIT counter")); - if( n==0 ){ - sqlite3VdbeGoto(v, iBreak); - }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ - p->nSelectRow = sqlite3LogEst((u64)n); - p->selFlags |= SF_FixedLimit; - } - }else{ - sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); - sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); - VdbeComment((v, "LIMIT counter")); - sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); - } - if( pLimit->pRight ){ - p->iOffset = iOffset = ++pParse->nMem; - pParse->nMem++; /* Allocate an extra register for limit+offset */ - sqlite3ExprCode(pParse, pLimit->pRight, iOffset); - sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); - VdbeComment((v, "OFFSET counter")); - sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); - VdbeComment((v, "LIMIT+OFFSET")); - } - } -} - -#ifndef SQLITE_OMIT_COMPOUND_SELECT -/* -** Return the appropriate collating sequence for the iCol-th column of -** the result set for the compound-select statement "p". Return NULL if -** the column has no default collating sequence. -** -** The collating sequence for the compound select is taken from the -** left-most term of the select that has a collating sequence. -*/ -static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ - CollSeq *pRet; - if( p->pPrior ){ - pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); - }else{ - pRet = 0; - } - assert( iCol>=0 ); - /* iCol must be less than p->pEList->nExpr. Otherwise an error would - ** have been thrown during name resolution and we would not have gotten - ** this far */ - if( pRet==0 && ALWAYS(iColpEList->nExpr) ){ - pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); - } - return pRet; -} - -/* -** The select statement passed as the second parameter is a compound SELECT -** with an ORDER BY clause. This function allocates and returns a KeyInfo -** structure suitable for implementing the ORDER BY. -** -** Space to hold the KeyInfo structure is obtained from malloc. The calling -** function is responsible for ensuring that this structure is eventually -** freed. -*/ -static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ - ExprList *pOrderBy = p->pOrderBy; - int nOrderBy = p->pOrderBy->nExpr; - sqlite3 *db = pParse->db; - KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); - if( pRet ){ - int i; - for(i=0; ia[i]; - Expr *pTerm = pItem->pExpr; - CollSeq *pColl; - - if( pTerm->flags & EP_Collate ){ - pColl = sqlite3ExprCollSeq(pParse, pTerm); - }else{ - pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); - if( pColl==0 ) pColl = db->pDfltColl; - pOrderBy->a[i].pExpr = - sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); - } - assert( sqlite3KeyInfoIsWriteable(pRet) ); - pRet->aColl[i] = pColl; - pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags; - } - } - - return pRet; -} - -#ifndef SQLITE_OMIT_CTE -/* -** This routine generates VDBE code to compute the content of a WITH RECURSIVE -** query of the form: -** -** AS ( UNION [ALL] ) -** \___________/ \_______________/ -** p->pPrior p -** -** -** There is exactly one reference to the recursive-table in the FROM clause -** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. -** -** The setup-query runs once to generate an initial set of rows that go -** into a Queue table. Rows are extracted from the Queue table one by -** one. Each row extracted from Queue is output to pDest. Then the single -** extracted row (now in the iCurrent table) becomes the content of the -** recursive-table for a recursive-query run. The output of the recursive-query -** is added back into the Queue table. Then another row is extracted from Queue -** and the iteration continues until the Queue table is empty. -** -** If the compound query operator is UNION then no duplicate rows are ever -** inserted into the Queue table. The iDistinct table keeps a copy of all rows -** that have ever been inserted into Queue and causes duplicates to be -** discarded. If the operator is UNION ALL, then duplicates are allowed. -** -** If the query has an ORDER BY, then entries in the Queue table are kept in -** ORDER BY order and the first entry is extracted for each cycle. Without -** an ORDER BY, the Queue table is just a FIFO. -** -** If a LIMIT clause is provided, then the iteration stops after LIMIT rows -** have been output to pDest. A LIMIT of zero means to output no rows and a -** negative LIMIT means to output all rows. If there is also an OFFSET clause -** with a positive value, then the first OFFSET outputs are discarded rather -** than being sent to pDest. The LIMIT count does not begin until after OFFSET -** rows have been skipped. -*/ -static void generateWithRecursiveQuery( - Parse *pParse, /* Parsing context */ - Select *p, /* The recursive SELECT to be coded */ - SelectDest *pDest /* What to do with query results */ -){ - SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ - int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ - Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ - Select *pSetup = p->pPrior; /* The setup query */ - int addrTop; /* Top of the loop */ - int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ - int iCurrent = 0; /* The Current table */ - int regCurrent; /* Register holding Current table */ - int iQueue; /* The Queue table */ - int iDistinct = 0; /* To ensure unique results if UNION */ - int eDest = SRT_Fifo; /* How to write to Queue */ - SelectDest destQueue; /* SelectDest targetting the Queue table */ - int i; /* Loop counter */ - int rc; /* Result code */ - ExprList *pOrderBy; /* The ORDER BY clause */ - Expr *pLimit; /* Saved LIMIT and OFFSET */ - int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ - -#ifndef SQLITE_OMIT_WINDOWFUNC - if( p->pWin ){ - sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries"); - return; - } -#endif - - /* Obtain authorization to do a recursive query */ - if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; - - /* Process the LIMIT and OFFSET clauses, if they exist */ - addrBreak = sqlite3VdbeMakeLabel(pParse); - p->nSelectRow = 320; /* 4 billion rows */ - computeLimitRegisters(pParse, p, addrBreak); - pLimit = p->pLimit; - regLimit = p->iLimit; - regOffset = p->iOffset; - p->pLimit = 0; - p->iLimit = p->iOffset = 0; - pOrderBy = p->pOrderBy; - - /* Locate the cursor number of the Current table */ - for(i=0; ALWAYS(inSrc); i++){ - if( pSrc->a[i].fg.isRecursive ){ - iCurrent = pSrc->a[i].iCursor; - break; - } - } - - /* Allocate cursors numbers for Queue and Distinct. The cursor number for - ** the Distinct table must be exactly one greater than Queue in order - ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ - iQueue = pParse->nTab++; - if( p->op==TK_UNION ){ - eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; - iDistinct = pParse->nTab++; - }else{ - eDest = pOrderBy ? SRT_Queue : SRT_Fifo; - } - sqlite3SelectDestInit(&destQueue, eDest, iQueue); - - /* Allocate cursors for Current, Queue, and Distinct. */ - regCurrent = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); - if( pOrderBy ){ - KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, - (char*)pKeyInfo, P4_KEYINFO); - destQueue.pOrderBy = pOrderBy; - }else{ - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); - } - VdbeComment((v, "Queue table")); - if( iDistinct ){ - p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); - p->selFlags |= SF_UsesEphemeral; - } - - /* Detach the ORDER BY clause from the compound SELECT */ - p->pOrderBy = 0; - - /* Store the results of the setup-query in Queue. */ - pSetup->pNext = 0; - ExplainQueryPlan((pParse, 1, "SETUP")); - rc = sqlite3Select(pParse, pSetup, &destQueue); - pSetup->pNext = p; - if( rc ) goto end_of_recursive_query; - - /* Find the next row in the Queue and output that row */ - addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); - - /* Transfer the next row in Queue over to Current */ - sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ - if( pOrderBy ){ - sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); - }else{ - sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); - } - sqlite3VdbeAddOp1(v, OP_Delete, iQueue); - - /* Output the single row in Current */ - addrCont = sqlite3VdbeMakeLabel(pParse); - codeOffset(v, regOffset, addrCont); - selectInnerLoop(pParse, p, iCurrent, - 0, 0, pDest, addrCont, addrBreak); - if( regLimit ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); - VdbeCoverage(v); - } - sqlite3VdbeResolveLabel(v, addrCont); - - /* Execute the recursive SELECT taking the single row in Current as - ** the value for the recursive-table. Store the results in the Queue. - */ - if( p->selFlags & SF_Aggregate ){ - sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); - }else{ - p->pPrior = 0; - ExplainQueryPlan((pParse, 1, "RECURSIVE STEP")); - sqlite3Select(pParse, p, &destQueue); - assert( p->pPrior==0 ); - p->pPrior = pSetup; - } - - /* Keep running the loop until the Queue is empty */ - sqlite3VdbeGoto(v, addrTop); - sqlite3VdbeResolveLabel(v, addrBreak); - -end_of_recursive_query: - sqlite3ExprListDelete(pParse->db, p->pOrderBy); - p->pOrderBy = pOrderBy; - p->pLimit = pLimit; - return; -} -#endif /* SQLITE_OMIT_CTE */ - -/* Forward references */ -static int multiSelectOrderBy( - Parse *pParse, /* Parsing context */ - Select *p, /* The right-most of SELECTs to be coded */ - SelectDest *pDest /* What to do with query results */ -); - -/* -** Handle the special case of a compound-select that originates from a -** VALUES clause. By handling this as a special case, we avoid deep -** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT -** on a VALUES clause. -** -** Because the Select object originates from a VALUES clause: -** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 -** (2) All terms are UNION ALL -** (3) There is no ORDER BY clause -** -** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES -** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). -** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. -** Since the limit is exactly 1, we only need to evalutes the left-most VALUES. -*/ -static int multiSelectValues( - Parse *pParse, /* Parsing context */ - Select *p, /* The right-most of SELECTs to be coded */ - SelectDest *pDest /* What to do with query results */ -){ - int nRow = 1; - int rc = 0; - int bShowAll = p->pLimit==0; - assert( p->selFlags & SF_MultiValue ); - do{ - assert( p->selFlags & SF_Values ); - assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); - assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); -#ifndef SQLITE_OMIT_WINDOWFUNC - if( p->pWin ) return -1; -#endif - if( p->pPrior==0 ) break; - assert( p->pPrior->pNext==p ); - p = p->pPrior; - nRow += bShowAll; - }while(1); - ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow, - nRow==1 ? "" : "S")); - while( p ){ - selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1); - if( !bShowAll ) break; - p->nSelectRow = nRow; - p = p->pNext; - } - return rc; -} - -/* -** This routine is called to process a compound query form from -** two or more separate queries using UNION, UNION ALL, EXCEPT, or -** INTERSECT -** -** "p" points to the right-most of the two queries. the query on the -** left is p->pPrior. The left query could also be a compound query -** in which case this routine will be called recursively. -** -** The results of the total query are to be written into a destination -** of type eDest with parameter iParm. -** -** Example 1: Consider a three-way compound SQL statement. -** -** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 -** -** This statement is parsed up as follows: -** -** SELECT c FROM t3 -** | -** `-----> SELECT b FROM t2 -** | -** `------> SELECT a FROM t1 -** -** The arrows in the diagram above represent the Select.pPrior pointer. -** So if this routine is called with p equal to the t3 query, then -** pPrior will be the t2 query. p->op will be TK_UNION in this case. -** -** Notice that because of the way SQLite parses compound SELECTs, the -** individual selects always group from left to right. -*/ -static int multiSelect( - Parse *pParse, /* Parsing context */ - Select *p, /* The right-most of SELECTs to be coded */ - SelectDest *pDest /* What to do with query results */ -){ - int rc = SQLITE_OK; /* Success code from a subroutine */ - Select *pPrior; /* Another SELECT immediately to our left */ - Vdbe *v; /* Generate code to this VDBE */ - SelectDest dest; /* Alternative data destination */ - Select *pDelete = 0; /* Chain of simple selects to delete */ - sqlite3 *db; /* Database connection */ - - /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only - ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. - */ - assert( p && p->pPrior ); /* Calling function guarantees this much */ - assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); - assert( p->selFlags & SF_Compound ); - db = pParse->db; - pPrior = p->pPrior; - dest = *pDest; - if( pPrior->pOrderBy || pPrior->pLimit ){ - sqlite3ErrorMsg(pParse,"%s clause should come after %s not before", - pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op)); - rc = 1; - goto multi_select_end; - } - - v = sqlite3GetVdbe(pParse); - assert( v!=0 ); /* The VDBE already created by calling function */ - - /* Create the destination temporary table if necessary - */ - if( dest.eDest==SRT_EphemTab ){ - assert( p->pEList ); - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); - dest.eDest = SRT_Table; - } - - /* Special handling for a compound-select that originates as a VALUES clause. - */ - if( p->selFlags & SF_MultiValue ){ - rc = multiSelectValues(pParse, p, &dest); - if( rc>=0 ) goto multi_select_end; - rc = SQLITE_OK; - } - - /* Make sure all SELECTs in the statement have the same number of elements - ** in their result sets. - */ - assert( p->pEList && pPrior->pEList ); - assert( p->pEList->nExpr==pPrior->pEList->nExpr ); - -#ifndef SQLITE_OMIT_CTE - if( p->selFlags & SF_Recursive ){ - generateWithRecursiveQuery(pParse, p, &dest); - }else -#endif - - /* Compound SELECTs that have an ORDER BY clause are handled separately. - */ - if( p->pOrderBy ){ - return multiSelectOrderBy(pParse, p, pDest); - }else{ - -#ifndef SQLITE_OMIT_EXPLAIN - if( pPrior->pPrior==0 ){ - ExplainQueryPlan((pParse, 1, "COMPOUND QUERY")); - ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); - } -#endif - - /* Generate code for the left and right SELECT statements. - */ - switch( p->op ){ - case TK_ALL: { - int addr = 0; - int nLimit; - assert( !pPrior->pLimit ); - pPrior->iLimit = p->iLimit; - pPrior->iOffset = p->iOffset; - pPrior->pLimit = p->pLimit; - rc = sqlite3Select(pParse, pPrior, &dest); - p->pLimit = 0; - if( rc ){ - goto multi_select_end; - } - p->pPrior = 0; - p->iLimit = pPrior->iLimit; - p->iOffset = pPrior->iOffset; - if( p->iLimit ){ - addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); - VdbeComment((v, "Jump ahead if LIMIT reached")); - if( p->iOffset ){ - sqlite3VdbeAddOp3(v, OP_OffsetLimit, - p->iLimit, p->iOffset+1, p->iOffset); - } - } - ExplainQueryPlan((pParse, 1, "UNION ALL")); - rc = sqlite3Select(pParse, p, &dest); - testcase( rc!=SQLITE_OK ); - pDelete = p->pPrior; - p->pPrior = pPrior; - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); - if( pPrior->pLimit - && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) - && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) - ){ - p->nSelectRow = sqlite3LogEst((u64)nLimit); - } - if( addr ){ - sqlite3VdbeJumpHere(v, addr); - } - break; - } - case TK_EXCEPT: - case TK_UNION: { - int unionTab; /* Cursor number of the temp table holding result */ - u8 op = 0; /* One of the SRT_ operations to apply to self */ - int priorOp; /* The SRT_ operation to apply to prior selects */ - Expr *pLimit; /* Saved values of p->nLimit */ - int addr; - SelectDest uniondest; - - testcase( p->op==TK_EXCEPT ); - testcase( p->op==TK_UNION ); - priorOp = SRT_Union; - if( dest.eDest==priorOp ){ - /* We can reuse a temporary table generated by a SELECT to our - ** right. - */ - assert( p->pLimit==0 ); /* Not allowed on leftward elements */ - unionTab = dest.iSDParm; - }else{ - /* We will need to create our own temporary table to hold the - ** intermediate results. - */ - unionTab = pParse->nTab++; - assert( p->pOrderBy==0 ); - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); - assert( p->addrOpenEphm[0] == -1 ); - p->addrOpenEphm[0] = addr; - findRightmost(p)->selFlags |= SF_UsesEphemeral; - assert( p->pEList ); - } - - /* Code the SELECT statements to our left - */ - assert( !pPrior->pOrderBy ); - sqlite3SelectDestInit(&uniondest, priorOp, unionTab); - rc = sqlite3Select(pParse, pPrior, &uniondest); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT statement - */ - if( p->op==TK_EXCEPT ){ - op = SRT_Except; - }else{ - assert( p->op==TK_UNION ); - op = SRT_Union; - } - p->pPrior = 0; - pLimit = p->pLimit; - p->pLimit = 0; - uniondest.eDest = op; - ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", - selectOpName(p->op))); - rc = sqlite3Select(pParse, p, &uniondest); - testcase( rc!=SQLITE_OK ); - assert( p->pOrderBy==0 ); - pDelete = p->pPrior; - p->pPrior = pPrior; - p->pOrderBy = 0; - if( p->op==TK_UNION ){ - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); - } - sqlite3ExprDelete(db, p->pLimit); - p->pLimit = pLimit; - p->iLimit = 0; - p->iOffset = 0; - - /* Convert the data in the temporary table into whatever form - ** it is that we currently need. - */ - assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); - assert( p->pEList || db->mallocFailed ); - if( dest.eDest!=priorOp && db->mallocFailed==0 ){ - int iCont, iBreak, iStart; - iBreak = sqlite3VdbeMakeLabel(pParse); - iCont = sqlite3VdbeMakeLabel(pParse); - computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); - iStart = sqlite3VdbeCurrentAddr(v); - selectInnerLoop(pParse, p, unionTab, - 0, 0, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); - } - break; - } - default: assert( p->op==TK_INTERSECT ); { - int tab1, tab2; - int iCont, iBreak, iStart; - Expr *pLimit; - int addr; - SelectDest intersectdest; - int r1; - - /* INTERSECT is different from the others since it requires - ** two temporary tables. Hence it has its own case. Begin - ** by allocating the tables we will need. - */ - tab1 = pParse->nTab++; - tab2 = pParse->nTab++; - assert( p->pOrderBy==0 ); - - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); - assert( p->addrOpenEphm[0] == -1 ); - p->addrOpenEphm[0] = addr; - findRightmost(p)->selFlags |= SF_UsesEphemeral; - assert( p->pEList ); - - /* Code the SELECTs to our left into temporary table "tab1". - */ - sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); - rc = sqlite3Select(pParse, pPrior, &intersectdest); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT into temporary table "tab2" - */ - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); - assert( p->addrOpenEphm[1] == -1 ); - p->addrOpenEphm[1] = addr; - p->pPrior = 0; - pLimit = p->pLimit; - p->pLimit = 0; - intersectdest.iSDParm = tab2; - ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", - selectOpName(p->op))); - rc = sqlite3Select(pParse, p, &intersectdest); - testcase( rc!=SQLITE_OK ); - pDelete = p->pPrior; - p->pPrior = pPrior; - if( p->nSelectRow>pPrior->nSelectRow ){ - p->nSelectRow = pPrior->nSelectRow; - } - sqlite3ExprDelete(db, p->pLimit); - p->pLimit = pLimit; - - /* Generate code to take the intersection of the two temporary - ** tables. - */ - if( rc ) break; - assert( p->pEList ); - iBreak = sqlite3VdbeMakeLabel(pParse); - iCont = sqlite3VdbeMakeLabel(pParse); - computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); - r1 = sqlite3GetTempReg(pParse); - iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); - sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); - VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, r1); - selectInnerLoop(pParse, p, tab1, - 0, 0, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); - sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); - break; - } - } - - #ifndef SQLITE_OMIT_EXPLAIN - if( p->pNext==0 ){ - ExplainQueryPlanPop(pParse); - } - #endif - } - if( pParse->nErr ) goto multi_select_end; - - /* Compute collating sequences used by - ** temporary tables needed to implement the compound select. - ** Attach the KeyInfo structure to all temporary tables. - ** - ** This section is run by the right-most SELECT statement only. - ** SELECT statements to the left always skip this part. The right-most - ** SELECT might also skip this part if it has no ORDER BY clause and - ** no temp tables are required. - */ - if( p->selFlags & SF_UsesEphemeral ){ - int i; /* Loop counter */ - KeyInfo *pKeyInfo; /* Collating sequence for the result set */ - Select *pLoop; /* For looping through SELECT statements */ - CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ - int nCol; /* Number of columns in result set */ - - assert( p->pNext==0 ); - nCol = p->pEList->nExpr; - pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); - if( !pKeyInfo ){ - rc = SQLITE_NOMEM_BKPT; - goto multi_select_end; - } - for(i=0, apColl=pKeyInfo->aColl; ipDfltColl; - } - } - - for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ - for(i=0; i<2; i++){ - int addr = pLoop->addrOpenEphm[i]; - if( addr<0 ){ - /* If [0] is unused then [1] is also unused. So we can - ** always safely abort as soon as the first unused slot is found */ - assert( pLoop->addrOpenEphm[1]<0 ); - break; - } - sqlite3VdbeChangeP2(v, addr, nCol); - sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), - P4_KEYINFO); - pLoop->addrOpenEphm[i] = -1; - } - } - sqlite3KeyInfoUnref(pKeyInfo); - } - -multi_select_end: - pDest->iSdst = dest.iSdst; - pDest->nSdst = dest.nSdst; - sqlite3SelectDelete(db, pDelete); - return rc; -} -#endif /* SQLITE_OMIT_COMPOUND_SELECT */ - -/* -** Error message for when two or more terms of a compound select have different -** size result sets. -*/ -SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ - if( p->selFlags & SF_Values ){ - sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); - }else{ - sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" - " do not have the same number of result columns", selectOpName(p->op)); - } -} - -/* -** Code an output subroutine for a coroutine implementation of a -** SELECT statment. -** -** The data to be output is contained in pIn->iSdst. There are -** pIn->nSdst columns to be output. pDest is where the output should -** be sent. -** -** regReturn is the number of the register holding the subroutine -** return address. -** -** If regPrev>0 then it is the first register in a vector that -** records the previous output. mem[regPrev] is a flag that is false -** if there has been no previous output. If regPrev>0 then code is -** generated to suppress duplicates. pKeyInfo is used for comparing -** keys. -** -** If the LIMIT found in p->iLimit is reached, jump immediately to -** iBreak. -*/ -static int generateOutputSubroutine( - Parse *pParse, /* Parsing context */ - Select *p, /* The SELECT statement */ - SelectDest *pIn, /* Coroutine supplying data */ - SelectDest *pDest, /* Where to send the data */ - int regReturn, /* The return address register */ - int regPrev, /* Previous result register. No uniqueness if 0 */ - KeyInfo *pKeyInfo, /* For comparing with previous entry */ - int iBreak /* Jump here if we hit the LIMIT */ -){ - Vdbe *v = pParse->pVdbe; - int iContinue; - int addr; - - addr = sqlite3VdbeCurrentAddr(v); - iContinue = sqlite3VdbeMakeLabel(pParse); - - /* Suppress duplicates for UNION, EXCEPT, and INTERSECT - */ - if( regPrev ){ - int addr1, addr2; - addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); - addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, - (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); - sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); - sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); - } - if( pParse->db->mallocFailed ) return 0; - - /* Suppress the first OFFSET entries if there is an OFFSET clause - */ - codeOffset(v, p->iOffset, iContinue); - - assert( pDest->eDest!=SRT_Exists ); - assert( pDest->eDest!=SRT_Table ); - switch( pDest->eDest ){ - /* Store the result as data using a unique key. - */ - case SRT_EphemTab: { - int r1 = sqlite3GetTempReg(pParse); - int r2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); - sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); - sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3ReleaseTempReg(pParse, r2); - sqlite3ReleaseTempReg(pParse, r1); - break; - } - -#ifndef SQLITE_OMIT_SUBQUERY - /* If we are creating a set for an "expr IN (SELECT ...)". - */ - case SRT_Set: { - int r1; - testcase( pIn->nSdst>1 ); - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, - r1, pDest->zAffSdst, pIn->nSdst); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, - pIn->iSdst, pIn->nSdst); - sqlite3ReleaseTempReg(pParse, r1); - break; - } - - /* If this is a scalar select that is part of an expression, then - ** store the results in the appropriate memory cell and break out - ** of the scan loop. Note that the select might return multiple columns - ** if it is the RHS of a row-value IN operator. - */ - case SRT_Mem: { - if( pParse->nErr==0 ){ - testcase( pIn->nSdst>1 ); - sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst); - } - /* The LIMIT clause will jump out of the loop for us */ - break; - } -#endif /* #ifndef SQLITE_OMIT_SUBQUERY */ - - /* The results are stored in a sequence of registers - ** starting at pDest->iSdst. Then the co-routine yields. - */ - case SRT_Coroutine: { - if( pDest->iSdst==0 ){ - pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); - pDest->nSdst = pIn->nSdst; - } - sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); - break; - } - - /* If none of the above, then the result destination must be - ** SRT_Output. This routine is never called with any other - ** destination other than the ones handled above or SRT_Output. - ** - ** For SRT_Output, results are stored in a sequence of registers. - ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to - ** return the next row of result. - */ - default: { - assert( pDest->eDest==SRT_Output ); - sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); - break; - } - } - - /* Jump to the end of the loop if the LIMIT is reached. - */ - if( p->iLimit ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); - } - - /* Generate the subroutine return - */ - sqlite3VdbeResolveLabel(v, iContinue); - sqlite3VdbeAddOp1(v, OP_Return, regReturn); - - return addr; -} - -/* -** Alternative compound select code generator for cases when there -** is an ORDER BY clause. -** -** We assume a query of the following form: -** -** ORDER BY -** -** is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea -** is to code both and with the ORDER BY clause as -** co-routines. Then run the co-routines in parallel and merge the results -** into the output. In addition to the two coroutines (called selectA and -** selectB) there are 7 subroutines: -** -** outA: Move the output of the selectA coroutine into the output -** of the compound query. -** -** outB: Move the output of the selectB coroutine into the output -** of the compound query. (Only generated for UNION and -** UNION ALL. EXCEPT and INSERTSECT never output a row that -** appears only in B.) -** -** AltB: Called when there is data from both coroutines and AB. -** -** EofA: Called when data is exhausted from selectA. -** -** EofB: Called when data is exhausted from selectB. -** -** The implementation of the latter five subroutines depend on which -** is used: -** -** -** UNION ALL UNION EXCEPT INTERSECT -** ------------- ----------------- -------------- ----------------- -** AltB: outA, nextA outA, nextA outA, nextA nextA -** -** AeqB: outA, nextA nextA nextA outA, nextA -** -** AgtB: outB, nextB outB, nextB nextB nextB -** -** EofA: outB, nextB outB, nextB halt halt -** -** EofB: outA, nextA outA, nextA outA, nextA halt -** -** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA -** causes an immediate jump to EofA and an EOF on B following nextB causes -** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or -** following nextX causes a jump to the end of the select processing. -** -** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled -** within the output subroutine. The regPrev register set holds the previously -** output value. A comparison is made against this value and the output -** is skipped if the next results would be the same as the previous. -** -** The implementation plan is to implement the two coroutines and seven -** subroutines first, then put the control logic at the bottom. Like this: -** -** goto Init -** coA: coroutine for left query (A) -** coB: coroutine for right query (B) -** outA: output one row of A -** outB: output one row of B (UNION and UNION ALL only) -** EofA: ... -** EofB: ... -** AltB: ... -** AeqB: ... -** AgtB: ... -** Init: initialize coroutine registers -** yield coA -** if eof(A) goto EofA -** yield coB -** if eof(B) goto EofB -** Cmpr: Compare A, B -** Jump AltB, AeqB, AgtB -** End: ... -** -** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not -** actually called using Gosub and they do not Return. EofA and EofB loop -** until all data is exhausted then jump to the "end" labe. AltB, AeqB, -** and AgtB jump to either L2 or to one of EofA or EofB. -*/ -#ifndef SQLITE_OMIT_COMPOUND_SELECT -static int multiSelectOrderBy( - Parse *pParse, /* Parsing context */ - Select *p, /* The right-most of SELECTs to be coded */ - SelectDest *pDest /* What to do with query results */ -){ - int i, j; /* Loop counters */ - Select *pPrior; /* Another SELECT immediately to our left */ - Vdbe *v; /* Generate code to this VDBE */ - SelectDest destA; /* Destination for coroutine A */ - SelectDest destB; /* Destination for coroutine B */ - int regAddrA; /* Address register for select-A coroutine */ - int regAddrB; /* Address register for select-B coroutine */ - int addrSelectA; /* Address of the select-A coroutine */ - int addrSelectB; /* Address of the select-B coroutine */ - int regOutA; /* Address register for the output-A subroutine */ - int regOutB; /* Address register for the output-B subroutine */ - int addrOutA; /* Address of the output-A subroutine */ - int addrOutB = 0; /* Address of the output-B subroutine */ - int addrEofA; /* Address of the select-A-exhausted subroutine */ - int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ - int addrEofB; /* Address of the select-B-exhausted subroutine */ - int addrAltB; /* Address of the AB subroutine */ - int regLimitA; /* Limit register for select-A */ - int regLimitB; /* Limit register for select-A */ - int regPrev; /* A range of registers to hold previous output */ - int savedLimit; /* Saved value of p->iLimit */ - int savedOffset; /* Saved value of p->iOffset */ - int labelCmpr; /* Label for the start of the merge algorithm */ - int labelEnd; /* Label for the end of the overall SELECT stmt */ - int addr1; /* Jump instructions that get retargetted */ - int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ - KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ - KeyInfo *pKeyMerge; /* Comparison information for merging rows */ - sqlite3 *db; /* Database connection */ - ExprList *pOrderBy; /* The ORDER BY clause */ - int nOrderBy; /* Number of terms in the ORDER BY clause */ - u32 *aPermute; /* Mapping from ORDER BY terms to result set columns */ - - assert( p->pOrderBy!=0 ); - assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ - db = pParse->db; - v = pParse->pVdbe; - assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ - labelEnd = sqlite3VdbeMakeLabel(pParse); - labelCmpr = sqlite3VdbeMakeLabel(pParse); - - - /* Patch up the ORDER BY clause - */ - op = p->op; - pPrior = p->pPrior; - assert( pPrior->pOrderBy==0 ); - pOrderBy = p->pOrderBy; - assert( pOrderBy ); - nOrderBy = pOrderBy->nExpr; - - /* For operators other than UNION ALL we have to make sure that - ** the ORDER BY clause covers every term of the result set. Add - ** terms to the ORDER BY clause as necessary. - */ - if( op!=TK_ALL ){ - for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ - struct ExprList_item *pItem; - for(j=0, pItem=pOrderBy->a; ju.x.iOrderByCol>0 ); - if( pItem->u.x.iOrderByCol==i ) break; - } - if( j==nOrderBy ){ - Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); - if( pNew==0 ) return SQLITE_NOMEM_BKPT; - pNew->flags |= EP_IntValue; - pNew->u.iValue = i; - p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); - if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; - } - } - } - - /* Compute the comparison permutation and keyinfo that is used with - ** the permutation used to determine if the next - ** row of results comes from selectA or selectB. Also add explicit - ** collations to the ORDER BY clause terms so that when the subqueries - ** to the right and the left are evaluated, they use the correct - ** collation. - */ - aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1)); - if( aPermute ){ - struct ExprList_item *pItem; - aPermute[0] = nOrderBy; - for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ - assert( pItem->u.x.iOrderByCol>0 ); - assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); - aPermute[i] = pItem->u.x.iOrderByCol - 1; - } - pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); - }else{ - pKeyMerge = 0; - } - - /* Reattach the ORDER BY clause to the query. - */ - p->pOrderBy = pOrderBy; - pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); - - /* Allocate a range of temporary registers and the KeyInfo needed - ** for the logic that removes duplicate result rows when the - ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). - */ - if( op==TK_ALL ){ - regPrev = 0; - }else{ - int nExpr = p->pEList->nExpr; - assert( nOrderBy>=nExpr || db->mallocFailed ); - regPrev = pParse->nMem+1; - pParse->nMem += nExpr+1; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); - pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); - if( pKeyDup ){ - assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); - for(i=0; iaColl[i] = multiSelectCollSeq(pParse, p, i); - pKeyDup->aSortFlags[i] = 0; - } - } - } - - /* Separate the left and the right query from one another - */ - p->pPrior = 0; - pPrior->pNext = 0; - sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); - if( pPrior->pPrior==0 ){ - sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); - } - - /* Compute the limit registers */ - computeLimitRegisters(pParse, p, labelEnd); - if( p->iLimit && op==TK_ALL ){ - regLimitA = ++pParse->nMem; - regLimitB = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, - regLimitA); - sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); - }else{ - regLimitA = regLimitB = 0; - } - sqlite3ExprDelete(db, p->pLimit); - p->pLimit = 0; - - regAddrA = ++pParse->nMem; - regAddrB = ++pParse->nMem; - regOutA = ++pParse->nMem; - regOutB = ++pParse->nMem; - sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); - sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); - - ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op))); - - /* Generate a coroutine to evaluate the SELECT statement to the - ** left of the compound operator - the "A" select. - */ - addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; - addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); - VdbeComment((v, "left SELECT")); - pPrior->iLimit = regLimitA; - ExplainQueryPlan((pParse, 1, "LEFT")); - sqlite3Select(pParse, pPrior, &destA); - sqlite3VdbeEndCoroutine(v, regAddrA); - sqlite3VdbeJumpHere(v, addr1); - - /* Generate a coroutine to evaluate the SELECT statement on - ** the right - the "B" select - */ - addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; - addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); - VdbeComment((v, "right SELECT")); - savedLimit = p->iLimit; - savedOffset = p->iOffset; - p->iLimit = regLimitB; - p->iOffset = 0; - ExplainQueryPlan((pParse, 1, "RIGHT")); - sqlite3Select(pParse, p, &destB); - p->iLimit = savedLimit; - p->iOffset = savedOffset; - sqlite3VdbeEndCoroutine(v, regAddrB); - - /* Generate a subroutine that outputs the current row of the A - ** select as the next output row of the compound select. - */ - VdbeNoopComment((v, "Output routine for A")); - addrOutA = generateOutputSubroutine(pParse, - p, &destA, pDest, regOutA, - regPrev, pKeyDup, labelEnd); - - /* Generate a subroutine that outputs the current row of the B - ** select as the next output row of the compound select. - */ - if( op==TK_ALL || op==TK_UNION ){ - VdbeNoopComment((v, "Output routine for B")); - addrOutB = generateOutputSubroutine(pParse, - p, &destB, pDest, regOutB, - regPrev, pKeyDup, labelEnd); - } - sqlite3KeyInfoUnref(pKeyDup); - - /* Generate a subroutine to run when the results from select A - ** are exhausted and only data in select B remains. - */ - if( op==TK_EXCEPT || op==TK_INTERSECT ){ - addrEofA_noB = addrEofA = labelEnd; - }else{ - VdbeNoopComment((v, "eof-A subroutine")); - addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); - addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); - VdbeCoverage(v); - sqlite3VdbeGoto(v, addrEofA); - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); - } - - /* Generate a subroutine to run when the results from select B - ** are exhausted and only data in select A remains. - */ - if( op==TK_INTERSECT ){ - addrEofB = addrEofA; - if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; - }else{ - VdbeNoopComment((v, "eof-B subroutine")); - addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); - sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); - sqlite3VdbeGoto(v, addrEofB); - } - - /* Generate code to handle the case of AB - */ - VdbeNoopComment((v, "A-gt-B subroutine")); - addrAgtB = sqlite3VdbeCurrentAddr(v); - if( op==TK_ALL || op==TK_UNION ){ - sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); - } - sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); - sqlite3VdbeGoto(v, labelCmpr); - - /* This code runs once to initialize everything. - */ - sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); - - /* Implement the main merge loop - */ - sqlite3VdbeResolveLabel(v, labelCmpr); - sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); - sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, - (char*)pKeyMerge, P4_KEYINFO); - sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); - sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); - - /* Jump to the this point in order to terminate the query. - */ - sqlite3VdbeResolveLabel(v, labelEnd); - - /* Reassembly the compound query so that it will be freed correctly - ** by the calling function */ - if( p->pPrior ){ - sqlite3SelectDelete(db, p->pPrior); - } - p->pPrior = pPrior; - pPrior->pNext = p; - - /*** TBD: Insert subroutine calls to close cursors on incomplete - **** subqueries ****/ - ExplainQueryPlanPop(pParse); - return pParse->nErr!=0; -} -#endif - -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) - -/* An instance of the SubstContext object describes an substitution edit -** to be performed on a parse tree. -** -** All references to columns in table iTable are to be replaced by corresponding -** expressions in pEList. -*/ -typedef struct SubstContext { - Parse *pParse; /* The parsing context */ - int iTable; /* Replace references to this table */ - int iNewTable; /* New table number */ - int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ - ExprList *pEList; /* Replacement expressions */ -} SubstContext; - -/* Forward Declarations */ -static void substExprList(SubstContext*, ExprList*); -static void substSelect(SubstContext*, Select*, int); - -/* -** Scan through the expression pExpr. Replace every reference to -** a column in table number iTable with a copy of the iColumn-th -** entry in pEList. (But leave references to the ROWID column -** unchanged.) -** -** This routine is part of the flattening procedure. A subquery -** whose result set is defined by pEList appears as entry in the -** FROM clause of a SELECT such that the VDBE cursor assigned to that -** FORM clause entry is iTable. This routine makes the necessary -** changes to pExpr so that it refers directly to the source table -** of the subquery rather the result set of the subquery. -*/ -static Expr *substExpr( - SubstContext *pSubst, /* Description of the substitution */ - Expr *pExpr /* Expr in which substitution occurs */ -){ - if( pExpr==0 ) return 0; - if( ExprHasProperty(pExpr, EP_FromJoin) - && pExpr->iRightJoinTable==pSubst->iTable - ){ - pExpr->iRightJoinTable = pSubst->iNewTable; - } - if( pExpr->op==TK_COLUMN - && pExpr->iTable==pSubst->iTable - && !ExprHasProperty(pExpr, EP_FixedCol) - ){ - if( pExpr->iColumn<0 ){ - pExpr->op = TK_NULL; - }else{ - Expr *pNew; - Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; - Expr ifNullRow; - assert( pSubst->pEList!=0 && pExpr->iColumnpEList->nExpr ); - assert( pExpr->pRight==0 ); - if( sqlite3ExprIsVector(pCopy) ){ - sqlite3VectorErrorMsg(pSubst->pParse, pCopy); - }else{ - sqlite3 *db = pSubst->pParse->db; - if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){ - memset(&ifNullRow, 0, sizeof(ifNullRow)); - ifNullRow.op = TK_IF_NULL_ROW; - ifNullRow.pLeft = pCopy; - ifNullRow.iTable = pSubst->iNewTable; - ifNullRow.flags = EP_Skip; - pCopy = &ifNullRow; - } - testcase( ExprHasProperty(pCopy, EP_Subquery) ); - pNew = sqlite3ExprDup(db, pCopy, 0); - if( pNew && pSubst->isLeftJoin ){ - ExprSetProperty(pNew, EP_CanBeNull); - } - if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){ - pNew->iRightJoinTable = pExpr->iRightJoinTable; - ExprSetProperty(pNew, EP_FromJoin); - } - sqlite3ExprDelete(db, pExpr); - pExpr = pNew; - - /* Ensure that the expression now has an implicit collation sequence, - ** just as it did when it was a column of a view or sub-query. */ - if( pExpr ){ - if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){ - CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr); - pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr, - (pColl ? pColl->zName : "BINARY") - ); - } - ExprClearProperty(pExpr, EP_Collate); - } - } - } - }else{ - if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ - pExpr->iTable = pSubst->iNewTable; - } - pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); - pExpr->pRight = substExpr(pSubst, pExpr->pRight); - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - substSelect(pSubst, pExpr->x.pSelect, 1); - }else{ - substExprList(pSubst, pExpr->x.pList); - } -#ifndef SQLITE_OMIT_WINDOWFUNC - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - Window *pWin = pExpr->y.pWin; - pWin->pFilter = substExpr(pSubst, pWin->pFilter); - substExprList(pSubst, pWin->pPartition); - substExprList(pSubst, pWin->pOrderBy); - } -#endif - } - return pExpr; -} -static void substExprList( - SubstContext *pSubst, /* Description of the substitution */ - ExprList *pList /* List to scan and in which to make substitutes */ -){ - int i; - if( pList==0 ) return; - for(i=0; inExpr; i++){ - pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); - } -} -static void substSelect( - SubstContext *pSubst, /* Description of the substitution */ - Select *p, /* SELECT statement in which to make substitutions */ - int doPrior /* Do substitutes on p->pPrior too */ -){ - SrcList *pSrc; - struct SrcList_item *pItem; - int i; - if( !p ) return; - do{ - substExprList(pSubst, p->pEList); - substExprList(pSubst, p->pGroupBy); - substExprList(pSubst, p->pOrderBy); - p->pHaving = substExpr(pSubst, p->pHaving); - p->pWhere = substExpr(pSubst, p->pWhere); - pSrc = p->pSrc; - assert( pSrc!=0 ); - for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ - substSelect(pSubst, pItem->pSelect, 1); - if( pItem->fg.isTabFunc ){ - substExprList(pSubst, pItem->u1.pFuncArg); - } - } - }while( doPrior && (p = p->pPrior)!=0 ); -} -#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ - -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) -/* -** pSelect is a SELECT statement and pSrcItem is one item in the FROM -** clause of that SELECT. -** -** This routine scans the entire SELECT statement and recomputes the -** pSrcItem->colUsed mask. -*/ -static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){ - struct SrcList_item *pItem; - if( pExpr->op!=TK_COLUMN ) return WRC_Continue; - pItem = pWalker->u.pSrcItem; - if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue; - if( pExpr->iColumn<0 ) return WRC_Continue; - pItem->colUsed |= sqlite3ExprColUsed(pExpr); - return WRC_Continue; -} -static void recomputeColumnsUsed( - Select *pSelect, /* The complete SELECT statement */ - struct SrcList_item *pSrcItem /* Which FROM clause item to recompute */ -){ - Walker w; - if( NEVER(pSrcItem->pTab==0) ) return; - memset(&w, 0, sizeof(w)); - w.xExprCallback = recomputeColumnsUsedExpr; - w.xSelectCallback = sqlite3SelectWalkNoop; - w.u.pSrcItem = pSrcItem; - pSrcItem->colUsed = 0; - sqlite3WalkSelect(&w, pSelect); -} -#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ - -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) -/* -** This routine attempts to flatten subqueries as a performance optimization. -** This routine returns 1 if it makes changes and 0 if no flattening occurs. -** -** To understand the concept of flattening, consider the following -** query: -** -** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 -** -** The default way of implementing this query is to execute the -** subquery first and store the results in a temporary table, then -** run the outer query on that temporary table. This requires two -** passes over the data. Furthermore, because the temporary table -** has no indices, the WHERE clause on the outer query cannot be -** optimized. -** -** This routine attempts to rewrite queries such as the above into -** a single flat select, like this: -** -** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 -** -** The code generated for this simplification gives the same result -** but only has to scan the data once. And because indices might -** exist on the table t1, a complete scan of the data might be -** avoided. -** -** Flattening is subject to the following constraints: -** -** (**) We no longer attempt to flatten aggregate subqueries. Was: -** The subquery and the outer query cannot both be aggregates. -** -** (**) We no longer attempt to flatten aggregate subqueries. Was: -** (2) If the subquery is an aggregate then -** (2a) the outer query must not be a join and -** (2b) the outer query must not use subqueries -** other than the one FROM-clause subquery that is a candidate -** for flattening. (This is due to ticket [2f7170d73bf9abf80] -** from 2015-02-09.) -** -** (3) If the subquery is the right operand of a LEFT JOIN then -** (3a) the subquery may not be a join and -** (3b) the FROM clause of the subquery may not contain a virtual -** table and -** (3c) the outer query may not be an aggregate. -** (3d) the outer query may not be DISTINCT. -** -** (4) The subquery can not be DISTINCT. -** -** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT -** sub-queries that were excluded from this optimization. Restriction -** (4) has since been expanded to exclude all DISTINCT subqueries. -** -** (**) We no longer attempt to flatten aggregate subqueries. Was: -** If the subquery is aggregate, the outer query may not be DISTINCT. -** -** (7) The subquery must have a FROM clause. TODO: For subqueries without -** A FROM clause, consider adding a FROM clause with the special -** table sqlite_once that consists of a single row containing a -** single NULL. -** -** (8) If the subquery uses LIMIT then the outer query may not be a join. -** -** (9) If the subquery uses LIMIT then the outer query may not be aggregate. -** -** (**) Restriction (10) was removed from the code on 2005-02-05 but we -** accidently carried the comment forward until 2014-09-15. Original -** constraint: "If the subquery is aggregate then the outer query -** may not use LIMIT." -** -** (11) The subquery and the outer query may not both have ORDER BY clauses. -** -** (**) Not implemented. Subsumed into restriction (3). Was previously -** a separate restriction deriving from ticket #350. -** -** (13) The subquery and outer query may not both use LIMIT. -** -** (14) The subquery may not use OFFSET. -** -** (15) If the outer query is part of a compound select, then the -** subquery may not use LIMIT. -** (See ticket #2339 and ticket [02a8e81d44]). -** -** (16) If the outer query is aggregate, then the subquery may not -** use ORDER BY. (Ticket #2942) This used to not matter -** until we introduced the group_concat() function. -** -** (17) If the subquery is a compound select, then -** (17a) all compound operators must be a UNION ALL, and -** (17b) no terms within the subquery compound may be aggregate -** or DISTINCT, and -** (17c) every term within the subquery compound must have a FROM clause -** (17d) the outer query may not be -** (17d1) aggregate, or -** (17d2) DISTINCT, or -** (17d3) a join. -** (17e) the subquery may not contain window functions -** -** The parent and sub-query may contain WHERE clauses. Subject to -** rules (11), (13) and (14), they may also contain ORDER BY, -** LIMIT and OFFSET clauses. The subquery cannot use any compound -** operator other than UNION ALL because all the other compound -** operators have an implied DISTINCT which is disallowed by -** restriction (4). -** -** Also, each component of the sub-query must return the same number -** of result columns. This is actually a requirement for any compound -** SELECT statement, but all the code here does is make sure that no -** such (illegal) sub-query is flattened. The caller will detect the -** syntax error and return a detailed message. -** -** (18) If the sub-query is a compound select, then all terms of the -** ORDER BY clause of the parent must be simple references to -** columns of the sub-query. -** -** (19) If the subquery uses LIMIT then the outer query may not -** have a WHERE clause. -** -** (20) If the sub-query is a compound select, then it must not use -** an ORDER BY clause. Ticket #3773. We could relax this constraint -** somewhat by saying that the terms of the ORDER BY clause must -** appear as unmodified result columns in the outer query. But we -** have other optimizations in mind to deal with that case. -** -** (21) If the subquery uses LIMIT then the outer query may not be -** DISTINCT. (See ticket [752e1646fc]). -** -** (22) The subquery may not be a recursive CTE. -** -** (**) Subsumed into restriction (17d3). Was: If the outer query is -** a recursive CTE, then the sub-query may not be a compound query. -** This restriction is because transforming the -** parent to a compound query confuses the code that handles -** recursive queries in multiSelect(). -** -** (**) We no longer attempt to flatten aggregate subqueries. Was: -** The subquery may not be an aggregate that uses the built-in min() or -** or max() functions. (Without this restriction, a query like: -** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily -** return the value X for which Y was maximal.) -** -** (25) If either the subquery or the parent query contains a window -** function in the select list or ORDER BY clause, flattening -** is not attempted. -** -** -** In this routine, the "p" parameter is a pointer to the outer query. -** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query -** uses aggregates. -** -** If flattening is not attempted, this routine is a no-op and returns 0. -** If flattening is attempted this routine returns 1. -** -** All of the expression analysis must occur on both the outer query and -** the subquery before this routine runs. -*/ -static int flattenSubquery( - Parse *pParse, /* Parsing context */ - Select *p, /* The parent or outer SELECT statement */ - int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ - int isAgg /* True if outer SELECT uses aggregate functions */ -){ - const char *zSavedAuthContext = pParse->zAuthContext; - Select *pParent; /* Current UNION ALL term of the other query */ - Select *pSub; /* The inner query or "subquery" */ - Select *pSub1; /* Pointer to the rightmost select in sub-query */ - SrcList *pSrc; /* The FROM clause of the outer query */ - SrcList *pSubSrc; /* The FROM clause of the subquery */ - int iParent; /* VDBE cursor number of the pSub result set temp table */ - int iNewParent = -1;/* Replacement table for iParent */ - int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ - int i; /* Loop counter */ - Expr *pWhere; /* The WHERE clause */ - struct SrcList_item *pSubitem; /* The subquery */ - sqlite3 *db = pParse->db; - Walker w; /* Walker to persist agginfo data */ - - /* Check to see if flattening is permitted. Return 0 if not. - */ - assert( p!=0 ); - assert( p->pPrior==0 ); - if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; - pSrc = p->pSrc; - assert( pSrc && iFrom>=0 && iFromnSrc ); - pSubitem = &pSrc->a[iFrom]; - iParent = pSubitem->iCursor; - pSub = pSubitem->pSelect; - assert( pSub!=0 ); - -#ifndef SQLITE_OMIT_WINDOWFUNC - if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ -#endif - - pSubSrc = pSub->pSrc; - assert( pSubSrc ); - /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, - ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET - ** because they could be computed at compile-time. But when LIMIT and OFFSET - ** became arbitrary expressions, we were forced to add restrictions (13) - ** and (14). */ - if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ - if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ - if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ - return 0; /* Restriction (15) */ - } - if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ - if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ - if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ - return 0; /* Restrictions (8)(9) */ - } - if( p->pOrderBy && pSub->pOrderBy ){ - return 0; /* Restriction (11) */ - } - if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ - if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ - if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ - return 0; /* Restriction (21) */ - } - if( pSub->selFlags & (SF_Recursive) ){ - return 0; /* Restrictions (22) */ - } - - /* - ** If the subquery is the right operand of a LEFT JOIN, then the - ** subquery may not be a join itself (3a). Example of why this is not - ** allowed: - ** - ** t1 LEFT OUTER JOIN (t2 JOIN t3) - ** - ** If we flatten the above, we would get - ** - ** (t1 LEFT OUTER JOIN t2) JOIN t3 - ** - ** which is not at all the same thing. - ** - ** If the subquery is the right operand of a LEFT JOIN, then the outer - ** query cannot be an aggregate. (3c) This is an artifact of the way - ** aggregates are processed - there is no mechanism to determine if - ** the LEFT JOIN table should be all-NULL. - ** - ** See also tickets #306, #350, and #3300. - */ - if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ - isLeftJoin = 1; - if( pSubSrc->nSrc>1 /* (3a) */ - || isAgg /* (3b) */ - || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */ - || (p->selFlags & SF_Distinct)!=0 /* (3d) */ - ){ - return 0; - } - } -#ifdef SQLITE_EXTRA_IFNULLROW - else if( iFrom>0 && !isAgg ){ - /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for - ** every reference to any result column from subquery in a join, even - ** though they are not necessary. This will stress-test the OP_IfNullRow - ** opcode. */ - isLeftJoin = -1; - } -#endif - - /* Restriction (17): If the sub-query is a compound SELECT, then it must - ** use only the UNION ALL operator. And none of the simple select queries - ** that make up the compound SELECT are allowed to be aggregate or distinct - ** queries. - */ - if( pSub->pPrior ){ - if( pSub->pOrderBy ){ - return 0; /* Restriction (20) */ - } - if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ - return 0; /* (17d1), (17d2), or (17d3) */ - } - for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ - testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); - testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); - assert( pSub->pSrc!=0 ); - assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); - if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ - || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ - || pSub1->pSrc->nSrc<1 /* (17c) */ -#ifndef SQLITE_OMIT_WINDOWFUNC - || pSub1->pWin /* (17e) */ -#endif - ){ - return 0; - } - testcase( pSub1->pSrc->nSrc>1 ); - } - - /* Restriction (18). */ - if( p->pOrderBy ){ - int ii; - for(ii=0; iipOrderBy->nExpr; ii++){ - if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; - } - } - } - - /* Ex-restriction (23): - ** The only way that the recursive part of a CTE can contain a compound - ** subquery is for the subquery to be one term of a join. But if the - ** subquery is a join, then the flattening has already been stopped by - ** restriction (17d3) - */ - assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); - - /***** If we reach this point, flattening is permitted. *****/ - SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n", - pSub->selId, pSub, iFrom)); - - /* Authorize the subquery */ - pParse->zAuthContext = pSubitem->zName; - TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); - testcase( i==SQLITE_DENY ); - pParse->zAuthContext = zSavedAuthContext; - - /* If the sub-query is a compound SELECT statement, then (by restrictions - ** 17 and 18 above) it must be a UNION ALL and the parent query must - ** be of the form: - ** - ** SELECT FROM () - ** - ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block - ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or - ** OFFSET clauses and joins them to the left-hand-side of the original - ** using UNION ALL operators. In this case N is the number of simple - ** select statements in the compound sub-query. - ** - ** Example: - ** - ** SELECT a+1 FROM ( - ** SELECT x FROM tab - ** UNION ALL - ** SELECT y FROM tab - ** UNION ALL - ** SELECT abs(z*2) FROM tab2 - ** ) WHERE a!=5 ORDER BY 1 - ** - ** Transformed into: - ** - ** SELECT x+1 FROM tab WHERE x+1!=5 - ** UNION ALL - ** SELECT y+1 FROM tab WHERE y+1!=5 - ** UNION ALL - ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 - ** ORDER BY 1 - ** - ** We call this the "compound-subquery flattening". - */ - for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ - Select *pNew; - ExprList *pOrderBy = p->pOrderBy; - Expr *pLimit = p->pLimit; - Select *pPrior = p->pPrior; - p->pOrderBy = 0; - p->pSrc = 0; - p->pPrior = 0; - p->pLimit = 0; - pNew = sqlite3SelectDup(db, p, 0); - p->pLimit = pLimit; - p->pOrderBy = pOrderBy; - p->pSrc = pSrc; - p->op = TK_ALL; - if( pNew==0 ){ - p->pPrior = pPrior; - }else{ - pNew->pPrior = pPrior; - if( pPrior ) pPrior->pNext = pNew; - pNew->pNext = p; - p->pPrior = pNew; - SELECTTRACE(2,pParse,p,("compound-subquery flattener" - " creates %u as peer\n",pNew->selId)); - } - if( db->mallocFailed ) return 1; - } - - /* Begin flattening the iFrom-th entry of the FROM clause - ** in the outer query. - */ - pSub = pSub1 = pSubitem->pSelect; - - /* Delete the transient table structure associated with the - ** subquery - */ - sqlite3DbFree(db, pSubitem->zDatabase); - sqlite3DbFree(db, pSubitem->zName); - sqlite3DbFree(db, pSubitem->zAlias); - pSubitem->zDatabase = 0; - pSubitem->zName = 0; - pSubitem->zAlias = 0; - pSubitem->pSelect = 0; - - /* Defer deleting the Table object associated with the - ** subquery until code generation is - ** complete, since there may still exist Expr.pTab entries that - ** refer to the subquery even after flattening. Ticket #3346. - ** - ** pSubitem->pTab is always non-NULL by test restrictions and tests above. - */ - if( ALWAYS(pSubitem->pTab!=0) ){ - Table *pTabToDel = pSubitem->pTab; - if( pTabToDel->nTabRef==1 ){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - pTabToDel->pNextZombie = pToplevel->pZombieTab; - pToplevel->pZombieTab = pTabToDel; - }else{ - pTabToDel->nTabRef--; - } - pSubitem->pTab = 0; - } - - /* The following loop runs once for each term in a compound-subquery - ** flattening (as described above). If we are doing a different kind - ** of flattening - a flattening other than a compound-subquery flattening - - ** then this loop only runs once. - ** - ** This loop moves all of the FROM elements of the subquery into the - ** the FROM clause of the outer query. Before doing this, remember - ** the cursor number for the original outer query FROM element in - ** iParent. The iParent cursor will never be used. Subsequent code - ** will scan expressions looking for iParent references and replace - ** those references with expressions that resolve to the subquery FROM - ** elements we are now copying in. - */ - for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ - int nSubSrc; - u8 jointype = 0; - assert( pSub!=0 ); - pSubSrc = pSub->pSrc; /* FROM clause of subquery */ - nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ - pSrc = pParent->pSrc; /* FROM clause of the outer query */ - - if( pSrc ){ - assert( pParent==p ); /* First time through the loop */ - jointype = pSubitem->fg.jointype; - }else{ - assert( pParent!=p ); /* 2nd and subsequent times through the loop */ - pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); - if( pSrc==0 ) break; - pParent->pSrc = pSrc; - } - - /* The subquery uses a single slot of the FROM clause of the outer - ** query. If the subquery has more than one element in its FROM clause, - ** then expand the outer query to make space for it to hold all elements - ** of the subquery. - ** - ** Example: - ** - ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; - ** - ** The outer query has 3 slots in its FROM clause. One slot of the - ** outer query (the middle slot) is used by the subquery. The next - ** block of code will expand the outer query FROM clause to 4 slots. - ** The middle slot is expanded to two slots in order to make space - ** for the two elements in the FROM clause of the subquery. - */ - if( nSubSrc>1 ){ - pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); - if( pSrc==0 ) break; - pParent->pSrc = pSrc; - } - - /* Transfer the FROM clause terms from the subquery into the - ** outer query. - */ - for(i=0; ia[i+iFrom].pUsing); - assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); - pSrc->a[i+iFrom] = pSubSrc->a[i]; - iNewParent = pSubSrc->a[i].iCursor; - memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); - } - pSrc->a[iFrom].fg.jointype = jointype; - - /* Now begin substituting subquery result set expressions for - ** references to the iParent in the outer query. - ** - ** Example: - ** - ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; - ** \ \_____________ subquery __________/ / - ** \_____________________ outer query ______________________________/ - ** - ** We look at every expression in the outer query and every place we see - ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". - */ - if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){ - /* At this point, any non-zero iOrderByCol values indicate that the - ** ORDER BY column expression is identical to the iOrderByCol'th - ** expression returned by SELECT statement pSub. Since these values - ** do not necessarily correspond to columns in SELECT statement pParent, - ** zero them before transfering the ORDER BY clause. - ** - ** Not doing this may cause an error if a subsequent call to this - ** function attempts to flatten a compound sub-query into pParent - ** (the only way this can happen is if the compound sub-query is - ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ - ExprList *pOrderBy = pSub->pOrderBy; - for(i=0; inExpr; i++){ - pOrderBy->a[i].u.x.iOrderByCol = 0; - } - assert( pParent->pOrderBy==0 ); - pParent->pOrderBy = pOrderBy; - pSub->pOrderBy = 0; - } - pWhere = pSub->pWhere; - pSub->pWhere = 0; - if( isLeftJoin>0 ){ - sqlite3SetJoinExpr(pWhere, iNewParent); - } - if( pWhere ){ - if( pParent->pWhere ){ - pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere); - }else{ - pParent->pWhere = pWhere; - } - } - if( db->mallocFailed==0 ){ - SubstContext x; - x.pParse = pParse; - x.iTable = iParent; - x.iNewTable = iNewParent; - x.isLeftJoin = isLeftJoin; - x.pEList = pSub->pEList; - substSelect(&x, pParent, 0); - } - - /* The flattened query is a compound if either the inner or the - ** outer query is a compound. */ - pParent->selFlags |= pSub->selFlags & SF_Compound; - assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ - - /* - ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; - ** - ** One is tempted to try to add a and b to combine the limits. But this - ** does not work if either limit is negative. - */ - if( pSub->pLimit ){ - pParent->pLimit = pSub->pLimit; - pSub->pLimit = 0; - } - - /* Recompute the SrcList_item.colUsed masks for the flattened - ** tables. */ - for(i=0; ia[i+iFrom]); - } - } - - /* Finially, delete what is left of the subquery and return - ** success. - */ - sqlite3AggInfoPersistWalkerInit(&w, pParse); - sqlite3WalkSelect(&w,pSub1); - sqlite3SelectDelete(db, pSub1); - -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p,("After flattening:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - - return 1; -} -#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ - -/* -** A structure to keep track of all of the column values that are fixed to -** a known value due to WHERE clause constraints of the form COLUMN=VALUE. -*/ -typedef struct WhereConst WhereConst; -struct WhereConst { - Parse *pParse; /* Parsing context */ - int nConst; /* Number for COLUMN=CONSTANT terms */ - int nChng; /* Number of times a constant is propagated */ - Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */ -}; - -/* -** Add a new entry to the pConst object. Except, do not add duplicate -** pColumn entires. Also, do not add if doing so would not be appropriate. -** -** The caller guarantees the pColumn is a column and pValue is a constant. -** This routine has to do some additional checks before completing the -** insert. -*/ -static void constInsert( - WhereConst *pConst, /* The WhereConst into which we are inserting */ - Expr *pColumn, /* The COLUMN part of the constraint */ - Expr *pValue, /* The VALUE part of the constraint */ - Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */ -){ - int i; - assert( pColumn->op==TK_COLUMN ); - assert( sqlite3ExprIsConstant(pValue) ); - - if( ExprHasProperty(pColumn, EP_FixedCol) ) return; - if( sqlite3ExprAffinity(pValue)!=0 ) return; - if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ - return; - } - - /* 2018-10-25 ticket [cf5ed20f] - ** Make sure the same pColumn is not inserted more than once */ - for(i=0; inConst; i++){ - const Expr *pE2 = pConst->apExpr[i*2]; - assert( pE2->op==TK_COLUMN ); - if( pE2->iTable==pColumn->iTable - && pE2->iColumn==pColumn->iColumn - ){ - return; /* Already present. Return without doing anything. */ - } - } - - pConst->nConst++; - pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr, - pConst->nConst*2*sizeof(Expr*)); - if( pConst->apExpr==0 ){ - pConst->nConst = 0; - }else{ - pConst->apExpr[pConst->nConst*2-2] = pColumn; - pConst->apExpr[pConst->nConst*2-1] = pValue; - } -} - -/* -** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE -** is a constant expression and where the term must be true because it -** is part of the AND-connected terms of the expression. For each term -** found, add it to the pConst structure. -*/ -static void findConstInWhere(WhereConst *pConst, Expr *pExpr){ - Expr *pRight, *pLeft; - if( pExpr==0 ) return; - if( ExprHasProperty(pExpr, EP_FromJoin) ) return; - if( pExpr->op==TK_AND ){ - findConstInWhere(pConst, pExpr->pRight); - findConstInWhere(pConst, pExpr->pLeft); - return; - } - if( pExpr->op!=TK_EQ ) return; - pRight = pExpr->pRight; - pLeft = pExpr->pLeft; - assert( pRight!=0 ); - assert( pLeft!=0 ); - if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){ - constInsert(pConst,pRight,pLeft,pExpr); - } - if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){ - constInsert(pConst,pLeft,pRight,pExpr); - } -} - -/* -** This is a Walker expression callback. pExpr is a candidate expression -** to be replaced by a value. If pExpr is equivalent to one of the -** columns named in pWalker->u.pConst, then overwrite it with its -** corresponding value. -*/ -static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ - int i; - WhereConst *pConst; - if( pExpr->op!=TK_COLUMN ) return WRC_Continue; - if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){ - testcase( ExprHasProperty(pExpr, EP_FixedCol) ); - testcase( ExprHasProperty(pExpr, EP_FromJoin) ); - return WRC_Continue; - } - pConst = pWalker->u.pConst; - for(i=0; inConst; i++){ - Expr *pColumn = pConst->apExpr[i*2]; - if( pColumn==pExpr ) continue; - if( pColumn->iTable!=pExpr->iTable ) continue; - if( pColumn->iColumn!=pExpr->iColumn ) continue; - /* A match is found. Add the EP_FixedCol property */ - pConst->nChng++; - ExprClearProperty(pExpr, EP_Leaf); - ExprSetProperty(pExpr, EP_FixedCol); - assert( pExpr->pLeft==0 ); - pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); - break; - } - return WRC_Prune; -} - -/* -** The WHERE-clause constant propagation optimization. -** -** If the WHERE clause contains terms of the form COLUMN=CONSTANT or -** CONSTANT=COLUMN that are top-level AND-connected terms that are not -** part of a ON clause from a LEFT JOIN, then throughout the query -** replace all other occurrences of COLUMN with CONSTANT. -** -** For example, the query: -** -** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b -** -** Is transformed into -** -** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39 -** -** Return true if any transformations where made and false if not. -** -** Implementation note: Constant propagation is tricky due to affinity -** and collating sequence interactions. Consider this example: -** -** CREATE TABLE t1(a INT,b TEXT); -** INSERT INTO t1 VALUES(123,'0123'); -** SELECT * FROM t1 WHERE a=123 AND b=a; -** SELECT * FROM t1 WHERE a=123 AND b=123; -** -** The two SELECT statements above should return different answers. b=a -** is alway true because the comparison uses numeric affinity, but b=123 -** is false because it uses text affinity and '0123' is not the same as '123'. -** To work around this, the expression tree is not actually changed from -** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol -** and the "123" value is hung off of the pLeft pointer. Code generator -** routines know to generate the constant "123" instead of looking up the -** column value. Also, to avoid collation problems, this optimization is -** only attempted if the "a=123" term uses the default BINARY collation. -*/ -static int propagateConstants( - Parse *pParse, /* The parsing context */ - Select *p /* The query in which to propagate constants */ -){ - WhereConst x; - Walker w; - int nChng = 0; - x.pParse = pParse; - do{ - x.nConst = 0; - x.nChng = 0; - x.apExpr = 0; - findConstInWhere(&x, p->pWhere); - if( x.nConst ){ - memset(&w, 0, sizeof(w)); - w.pParse = pParse; - w.xExprCallback = propagateConstantExprRewrite; - w.xSelectCallback = sqlite3SelectWalkNoop; - w.xSelectCallback2 = 0; - w.walkerDepth = 0; - w.u.pConst = &x; - sqlite3WalkExpr(&w, p->pWhere); - sqlite3DbFree(x.pParse->db, x.apExpr); - nChng += x.nChng; - } - }while( x.nChng ); - return nChng; -} - -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) -/* -** Make copies of relevant WHERE clause terms of the outer query into -** the WHERE clause of subquery. Example: -** -** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; -** -** Transformed into: -** -** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) -** WHERE x=5 AND y=10; -** -** The hope is that the terms added to the inner query will make it more -** efficient. -** -** Do not attempt this optimization if: -** -** (1) (** This restriction was removed on 2017-09-29. We used to -** disallow this optimization for aggregate subqueries, but now -** it is allowed by putting the extra terms on the HAVING clause. -** The added HAVING clause is pointless if the subquery lacks -** a GROUP BY clause. But such a HAVING clause is also harmless -** so there does not appear to be any reason to add extra logic -** to suppress it. **) -** -** (2) The inner query is the recursive part of a common table expression. -** -** (3) The inner query has a LIMIT clause (since the changes to the WHERE -** clause would change the meaning of the LIMIT). -** -** (4) The inner query is the right operand of a LEFT JOIN and the -** expression to be pushed down does not come from the ON clause -** on that LEFT JOIN. -** -** (5) The WHERE clause expression originates in the ON or USING clause -** of a LEFT JOIN where iCursor is not the right-hand table of that -** left join. An example: -** -** SELECT * -** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa -** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) -** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); -** -** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). -** But if the (b2=2) term were to be pushed down into the bb subquery, -** then the (1,1,NULL) row would be suppressed. -** -** (6) The inner query features one or more window-functions (since -** changes to the WHERE clause of the inner query could change the -** window over which window functions are calculated). -** -** Return 0 if no changes are made and non-zero if one or more WHERE clause -** terms are duplicated into the subquery. -*/ -static int pushDownWhereTerms( - Parse *pParse, /* Parse context (for malloc() and error reporting) */ - Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ - Expr *pWhere, /* The WHERE clause of the outer query */ - int iCursor, /* Cursor number of the subquery */ - int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ -){ - Expr *pNew; - int nChng = 0; - Select *pSel; - if( pWhere==0 ) return 0; - if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ - -#ifndef SQLITE_OMIT_WINDOWFUNC - for(pSel=pSubq; pSel; pSel=pSel->pPrior){ - if( pSel->pWin ) return 0; /* restriction (6) */ - } -#endif - -#ifdef SQLITE_DEBUG - /* Only the first term of a compound can have a WITH clause. But make - ** sure no other terms are marked SF_Recursive in case something changes - ** in the future. - */ - { - Select *pX; - for(pX=pSubq; pX; pX=pX->pPrior){ - assert( (pX->selFlags & (SF_Recursive))==0 ); - } - } -#endif - - if( pSubq->pLimit!=0 ){ - return 0; /* restriction (3) */ - } - while( pWhere->op==TK_AND ){ - nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, - iCursor, isLeftJoin); - pWhere = pWhere->pLeft; - } - if( isLeftJoin - && (ExprHasProperty(pWhere,EP_FromJoin)==0 - || pWhere->iRightJoinTable!=iCursor) - ){ - return 0; /* restriction (4) */ - } - if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){ - return 0; /* restriction (5) */ - } - if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ - nChng++; - while( pSubq ){ - SubstContext x; - pNew = sqlite3ExprDup(pParse->db, pWhere, 0); - unsetJoinExpr(pNew, -1); - x.pParse = pParse; - x.iTable = iCursor; - x.iNewTable = iCursor; - x.isLeftJoin = 0; - x.pEList = pSubq->pEList; - pNew = substExpr(&x, pNew); - if( pSubq->selFlags & SF_Aggregate ){ - pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew); - }else{ - pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew); - } - pSubq = pSubq->pPrior; - } - } - return nChng; -} -#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ - -/* -** The pFunc is the only aggregate function in the query. Check to see -** if the query is a candidate for the min/max optimization. -** -** If the query is a candidate for the min/max optimization, then set -** *ppMinMax to be an ORDER BY clause to be used for the optimization -** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on -** whether pFunc is a min() or max() function. -** -** If the query is not a candidate for the min/max optimization, return -** WHERE_ORDERBY_NORMAL (which must be zero). -** -** This routine must be called after aggregate functions have been -** located but before their arguments have been subjected to aggregate -** analysis. -*/ -static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ - int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ - ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */ - const char *zFunc; /* Name of aggregate function pFunc */ - ExprList *pOrderBy; - u8 sortFlags = 0; - - assert( *ppMinMax==0 ); - assert( pFunc->op==TK_AGG_FUNCTION ); - assert( !IsWindowFunc(pFunc) ); - if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){ - return eRet; - } - zFunc = pFunc->u.zToken; - if( sqlite3StrICmp(zFunc, "min")==0 ){ - eRet = WHERE_ORDERBY_MIN; - if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){ - sortFlags = KEYINFO_ORDER_BIGNULL; - } - }else if( sqlite3StrICmp(zFunc, "max")==0 ){ - eRet = WHERE_ORDERBY_MAX; - sortFlags = KEYINFO_ORDER_DESC; - }else{ - return eRet; - } - *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0); - assert( pOrderBy!=0 || db->mallocFailed ); - if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags; - return eRet; -} - -/* -** The select statement passed as the first argument is an aggregate query. -** The second argument is the associated aggregate-info object. This -** function tests if the SELECT is of the form: -** -** SELECT count(*) FROM -** -** where table is a database table, not a sub-select or view. If the query -** does match this pattern, then a pointer to the Table object representing -** is returned. Otherwise, 0 is returned. -*/ -static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ - Table *pTab; - Expr *pExpr; - - assert( !p->pGroupBy ); - - if( p->pWhere || p->pEList->nExpr!=1 - || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect - ){ - return 0; - } - pTab = p->pSrc->a[0].pTab; - pExpr = p->pEList->a[0].pExpr; - assert( pTab && !pTab->pSelect && pExpr ); - - if( IsVirtual(pTab) ) return 0; - if( pExpr->op!=TK_AGG_FUNCTION ) return 0; - if( NEVER(pAggInfo->nFunc==0) ) return 0; - if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; - if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0; - - return pTab; -} - -/* -** If the source-list item passed as an argument was augmented with an -** INDEXED BY clause, then try to locate the specified index. If there -** was such a clause and the named index cannot be found, return -** SQLITE_ERROR and leave an error in pParse. Otherwise, populate -** pFrom->pIndex and return SQLITE_OK. -*/ -SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ - if( pFrom->pTab && pFrom->fg.isIndexedBy ){ - Table *pTab = pFrom->pTab; - char *zIndexedBy = pFrom->u1.zIndexedBy; - Index *pIdx; - for(pIdx=pTab->pIndex; - pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); - pIdx=pIdx->pNext - ); - if( !pIdx ){ - sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); - pParse->checkSchema = 1; - return SQLITE_ERROR; - } - pFrom->pIBIndex = pIdx; - } - return SQLITE_OK; -} -/* -** Detect compound SELECT statements that use an ORDER BY clause with -** an alternative collating sequence. -** -** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... -** -** These are rewritten as a subquery: -** -** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) -** ORDER BY ... COLLATE ... -** -** This transformation is necessary because the multiSelectOrderBy() routine -** above that generates the code for a compound SELECT with an ORDER BY clause -** uses a merge algorithm that requires the same collating sequence on the -** result columns as on the ORDER BY clause. See ticket -** http://www.sqlite.org/src/info/6709574d2a -** -** This transformation is only needed for EXCEPT, INTERSECT, and UNION. -** The UNION ALL operator works fine with multiSelectOrderBy() even when -** there are COLLATE terms in the ORDER BY. -*/ -static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ - int i; - Select *pNew; - Select *pX; - sqlite3 *db; - struct ExprList_item *a; - SrcList *pNewSrc; - Parse *pParse; - Token dummy; - - if( p->pPrior==0 ) return WRC_Continue; - if( p->pOrderBy==0 ) return WRC_Continue; - for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} - if( pX==0 ) return WRC_Continue; - a = p->pOrderBy->a; -#ifndef SQLITE_OMIT_WINDOWFUNC - /* If iOrderByCol is already non-zero, then it has already been matched - ** to a result column of the SELECT statement. This occurs when the - ** SELECT is rewritten for window-functions processing and then passed - ** to sqlite3SelectPrep() and similar a second time. The rewriting done - ** by this function is not required in this case. */ - if( a[0].u.x.iOrderByCol ) return WRC_Continue; -#endif - for(i=p->pOrderBy->nExpr-1; i>=0; i--){ - if( a[i].pExpr->flags & EP_Collate ) break; - } - if( i<0 ) return WRC_Continue; - - /* If we reach this point, that means the transformation is required. */ - - pParse = pWalker->pParse; - db = pParse->db; - pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); - if( pNew==0 ) return WRC_Abort; - memset(&dummy, 0, sizeof(dummy)); - pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); - if( pNewSrc==0 ) return WRC_Abort; - *pNew = *p; - p->pSrc = pNewSrc; - p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); - p->op = TK_SELECT; - p->pWhere = 0; - pNew->pGroupBy = 0; - pNew->pHaving = 0; - pNew->pOrderBy = 0; - p->pPrior = 0; - p->pNext = 0; - p->pWith = 0; -#ifndef SQLITE_OMIT_WINDOWFUNC - p->pWinDefn = 0; -#endif - p->selFlags &= ~SF_Compound; - assert( (p->selFlags & SF_Converted)==0 ); - p->selFlags |= SF_Converted; - assert( pNew->pPrior!=0 ); - pNew->pPrior->pNext = pNew; - pNew->pLimit = 0; - return WRC_Continue; -} - -/* -** Check to see if the FROM clause term pFrom has table-valued function -** arguments. If it does, leave an error message in pParse and return -** non-zero, since pFrom is not allowed to be a table-valued function. -*/ -static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ - if( pFrom->fg.isTabFunc ){ - sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); - return 1; - } - return 0; -} - -#ifndef SQLITE_OMIT_CTE -/* -** Argument pWith (which may be NULL) points to a linked list of nested -** WITH contexts, from inner to outermost. If the table identified by -** FROM clause element pItem is really a common-table-expression (CTE) -** then return a pointer to the CTE definition for that table. Otherwise -** return NULL. -** -** If a non-NULL value is returned, set *ppContext to point to the With -** object that the returned CTE belongs to. -*/ -static struct Cte *searchWith( - With *pWith, /* Current innermost WITH clause */ - struct SrcList_item *pItem, /* FROM clause element to resolve */ - With **ppContext /* OUT: WITH clause return value belongs to */ -){ - const char *zName; - if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ - With *p; - for(p=pWith; p; p=p->pOuter){ - int i; - for(i=0; inCte; i++){ - if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ - *ppContext = p; - return &p->a[i]; - } - } - } - } - return 0; -} - -/* The code generator maintains a stack of active WITH clauses -** with the inner-most WITH clause being at the top of the stack. -** -** This routine pushes the WITH clause passed as the second argument -** onto the top of the stack. If argument bFree is true, then this -** WITH clause will never be popped from the stack. In this case it -** should be freed along with the Parse object. In other cases, when -** bFree==0, the With object will be freed along with the SELECT -** statement with which it is associated. -*/ -SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ - assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); - if( pWith ){ - assert( pParse->pWith!=pWith ); - pWith->pOuter = pParse->pWith; - pParse->pWith = pWith; - if( bFree ) pParse->pWithToFree = pWith; - } -} - -/* -** This function checks if argument pFrom refers to a CTE declared by -** a WITH clause on the stack currently maintained by the parser. And, -** if currently processing a CTE expression, if it is a recursive -** reference to the current CTE. -** -** If pFrom falls into either of the two categories above, pFrom->pTab -** and other fields are populated accordingly. The caller should check -** (pFrom->pTab!=0) to determine whether or not a successful match -** was found. -** -** Whether or not a match is found, SQLITE_OK is returned if no error -** occurs. If an error does occur, an error message is stored in the -** parser and some error code other than SQLITE_OK returned. -*/ -static int withExpand( - Walker *pWalker, - struct SrcList_item *pFrom -){ - Parse *pParse = pWalker->pParse; - sqlite3 *db = pParse->db; - struct Cte *pCte; /* Matched CTE (or NULL if no match) */ - With *pWith; /* WITH clause that pCte belongs to */ - - assert( pFrom->pTab==0 ); - if( pParse->nErr ){ - return SQLITE_ERROR; - } - - pCte = searchWith(pParse->pWith, pFrom, &pWith); - if( pCte ){ - Table *pTab; - ExprList *pEList; - Select *pSel; - Select *pLeft; /* Left-most SELECT statement */ - int bMayRecursive; /* True if compound joined by UNION [ALL] */ - With *pSavedWith; /* Initial value of pParse->pWith */ - - /* If pCte->zCteErr is non-NULL at this point, then this is an illegal - ** recursive reference to CTE pCte. Leave an error in pParse and return - ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. - ** In this case, proceed. */ - if( pCte->zCteErr ){ - sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); - return SQLITE_ERROR; - } - if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; - - assert( pFrom->pTab==0 ); - pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); - if( pTab==0 ) return WRC_Abort; - pTab->nTabRef = 1; - pTab->zName = sqlite3DbStrDup(db, pCte->zName); - pTab->iPKey = -1; - pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); - pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; - pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); - if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; - assert( pFrom->pSelect ); - - /* Check if this is a recursive CTE. */ - pSel = pFrom->pSelect; - bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); - if( bMayRecursive ){ - int i; - SrcList *pSrc = pFrom->pSelect->pSrc; - for(i=0; inSrc; i++){ - struct SrcList_item *pItem = &pSrc->a[i]; - if( pItem->zDatabase==0 - && pItem->zName!=0 - && 0==sqlite3StrICmp(pItem->zName, pCte->zName) - ){ - pItem->pTab = pTab; - pItem->fg.isRecursive = 1; - pTab->nTabRef++; - pSel->selFlags |= SF_Recursive; - } - } - } - - /* Only one recursive reference is permitted. */ - if( pTab->nTabRef>2 ){ - sqlite3ErrorMsg( - pParse, "multiple references to recursive table: %s", pCte->zName - ); - return SQLITE_ERROR; - } - assert( pTab->nTabRef==1 || - ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); - - pCte->zCteErr = "circular reference: %s"; - pSavedWith = pParse->pWith; - pParse->pWith = pWith; - if( bMayRecursive ){ - Select *pPrior = pSel->pPrior; - assert( pPrior->pWith==0 ); - pPrior->pWith = pSel->pWith; - sqlite3WalkSelect(pWalker, pPrior); - pPrior->pWith = 0; - }else{ - sqlite3WalkSelect(pWalker, pSel); - } - pParse->pWith = pWith; - - for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); - pEList = pLeft->pEList; - if( pCte->pCols ){ - if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ - sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", - pCte->zName, pEList->nExpr, pCte->pCols->nExpr - ); - pParse->pWith = pSavedWith; - return SQLITE_ERROR; - } - pEList = pCte->pCols; - } - - sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); - if( bMayRecursive ){ - if( pSel->selFlags & SF_Recursive ){ - pCte->zCteErr = "multiple recursive references: %s"; - }else{ - pCte->zCteErr = "recursive reference in a subquery: %s"; - } - sqlite3WalkSelect(pWalker, pSel); - } - pCte->zCteErr = 0; - pParse->pWith = pSavedWith; - } - - return SQLITE_OK; -} -#endif - -#ifndef SQLITE_OMIT_CTE -/* -** If the SELECT passed as the second argument has an associated WITH -** clause, pop it from the stack stored as part of the Parse object. -** -** This function is used as the xSelectCallback2() callback by -** sqlite3SelectExpand() when walking a SELECT tree to resolve table -** names and other FROM clause elements. -*/ -static void selectPopWith(Walker *pWalker, Select *p){ - Parse *pParse = pWalker->pParse; - if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ - With *pWith = findRightmost(p)->pWith; - if( pWith!=0 ){ - assert( pParse->pWith==pWith || pParse->nErr ); - pParse->pWith = pWith->pOuter; - } - } -} -#else -#define selectPopWith 0 -#endif - -/* -** The SrcList_item structure passed as the second argument represents a -** sub-query in the FROM clause of a SELECT statement. This function -** allocates and populates the SrcList_item.pTab object. If successful, -** SQLITE_OK is returned. Otherwise, if an OOM error is encountered, -** SQLITE_NOMEM. -*/ -SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){ - Select *pSel = pFrom->pSelect; - Table *pTab; - - assert( pSel ); - pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table)); - if( pTab==0 ) return SQLITE_NOMEM; - pTab->nTabRef = 1; - if( pFrom->zAlias ){ - pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias); - }else{ - pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId); - } - while( pSel->pPrior ){ pSel = pSel->pPrior; } - sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); - pTab->iPKey = -1; - pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); - pTab->tabFlags |= TF_Ephemeral; - - return pParse->nErr ? SQLITE_ERROR : SQLITE_OK; -} - -/* -** This routine is a Walker callback for "expanding" a SELECT statement. -** "Expanding" means to do the following: -** -** (1) Make sure VDBE cursor numbers have been assigned to every -** element of the FROM clause. -** -** (2) Fill in the pTabList->a[].pTab fields in the SrcList that -** defines FROM clause. When views appear in the FROM clause, -** fill pTabList->a[].pSelect with a copy of the SELECT statement -** that implements the view. A copy is made of the view's SELECT -** statement so that we can freely modify or delete that statement -** without worrying about messing up the persistent representation -** of the view. -** -** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword -** on joins and the ON and USING clause of joins. -** -** (4) Scan the list of columns in the result set (pEList) looking -** for instances of the "*" operator or the TABLE.* operator. -** If found, expand each "*" to be every column in every table -** and TABLE.* to be every column in TABLE. -** -*/ -static int selectExpander(Walker *pWalker, Select *p){ - Parse *pParse = pWalker->pParse; - int i, j, k; - SrcList *pTabList; - ExprList *pEList; - struct SrcList_item *pFrom; - sqlite3 *db = pParse->db; - Expr *pE, *pRight, *pExpr; - u16 selFlags = p->selFlags; - u32 elistFlags = 0; - - p->selFlags |= SF_Expanded; - if( db->mallocFailed ){ - return WRC_Abort; - } - assert( p->pSrc!=0 ); - if( (selFlags & SF_Expanded)!=0 ){ - return WRC_Prune; - } - if( pWalker->eCode ){ - /* Renumber selId because it has been copied from a view */ - p->selId = ++pParse->nSelect; - } - pTabList = p->pSrc; - pEList = p->pEList; - sqlite3WithPush(pParse, p->pWith, 0); - - /* Make sure cursor numbers have been assigned to all entries in - ** the FROM clause of the SELECT statement. - */ - sqlite3SrcListAssignCursors(pParse, pTabList); - - /* Look up every table named in the FROM clause of the select. If - ** an entry of the FROM clause is a subquery instead of a table or view, - ** then create a transient table structure to describe the subquery. - */ - for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ - Table *pTab; - assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); - if( pFrom->pTab ) continue; - assert( pFrom->fg.isRecursive==0 ); -#ifndef SQLITE_OMIT_CTE - if( withExpand(pWalker, pFrom) ) return WRC_Abort; - if( pFrom->pTab ) {} else -#endif - if( pFrom->zName==0 ){ -#ifndef SQLITE_OMIT_SUBQUERY - Select *pSel = pFrom->pSelect; - /* A sub-query in the FROM clause of a SELECT */ - assert( pSel!=0 ); - assert( pFrom->pTab==0 ); - if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; - if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort; -#endif - }else{ - /* An ordinary table or view name in the FROM clause */ - assert( pFrom->pTab==0 ); - pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); - if( pTab==0 ) return WRC_Abort; - if( pTab->nTabRef>=0xffff ){ - sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", - pTab->zName); - pFrom->pTab = 0; - return WRC_Abort; - } - pTab->nTabRef++; - if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ - return WRC_Abort; - } -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) - if( IsVirtual(pTab) || pTab->pSelect ){ - i16 nCol; - u8 eCodeOrig = pWalker->eCode; - if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; - assert( pFrom->pSelect==0 ); - if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){ - sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited", - pTab->zName); - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pTab) - && pFrom->fg.fromDDL - && ALWAYS(pTab->pVTable!=0) - && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0) - ){ - sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"", - pTab->zName); - } -#endif - pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); - nCol = pTab->nCol; - pTab->nCol = -1; - pWalker->eCode = 1; /* Turn on Select.selId renumbering */ - sqlite3WalkSelect(pWalker, pFrom->pSelect); - pWalker->eCode = eCodeOrig; - pTab->nCol = nCol; - } -#endif - } - - /* Locate the index named by the INDEXED BY clause, if any. */ - if( sqlite3IndexedByLookup(pParse, pFrom) ){ - return WRC_Abort; - } - } - - /* Process NATURAL keywords, and ON and USING clauses of joins. - */ - if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){ - return WRC_Abort; - } - - /* For every "*" that occurs in the column list, insert the names of - ** all columns in all tables. And for every TABLE.* insert the names - ** of all columns in TABLE. The parser inserted a special expression - ** with the TK_ASTERISK operator for each "*" that it found in the column - ** list. The following code just has to locate the TK_ASTERISK - ** expressions and expand each one to the list of all columns in - ** all tables. - ** - ** The first loop just checks to see if there are any "*" operators - ** that need expanding. - */ - for(k=0; knExpr; k++){ - pE = pEList->a[k].pExpr; - if( pE->op==TK_ASTERISK ) break; - assert( pE->op!=TK_DOT || pE->pRight!=0 ); - assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); - if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; - elistFlags |= pE->flags; - } - if( knExpr ){ - /* - ** If we get here it means the result set contains one or more "*" - ** operators that need to be expanded. Loop through each expression - ** in the result set and expand them one by one. - */ - struct ExprList_item *a = pEList->a; - ExprList *pNew = 0; - int flags = pParse->db->flags; - int longNames = (flags & SQLITE_FullColNames)!=0 - && (flags & SQLITE_ShortColNames)==0; - - for(k=0; knExpr; k++){ - pE = a[k].pExpr; - elistFlags |= pE->flags; - pRight = pE->pRight; - assert( pE->op!=TK_DOT || pRight!=0 ); - if( pE->op!=TK_ASTERISK - && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) - ){ - /* This particular expression does not need to be expanded. - */ - pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); - if( pNew ){ - pNew->a[pNew->nExpr-1].zEName = a[k].zEName; - pNew->a[pNew->nExpr-1].eEName = a[k].eEName; - a[k].zEName = 0; - } - a[k].pExpr = 0; - }else{ - /* This expression is a "*" or a "TABLE.*" and needs to be - ** expanded. */ - int tableSeen = 0; /* Set to 1 when TABLE matches */ - char *zTName = 0; /* text of name of TABLE */ - if( pE->op==TK_DOT ){ - assert( pE->pLeft!=0 ); - assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); - zTName = pE->pLeft->u.zToken; - } - for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ - Table *pTab = pFrom->pTab; - Select *pSub = pFrom->pSelect; - char *zTabName = pFrom->zAlias; - const char *zSchemaName = 0; - int iDb; - if( zTabName==0 ){ - zTabName = pTab->zName; - } - if( db->mallocFailed ) break; - if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ - pSub = 0; - if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ - continue; - } - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; - } - for(j=0; jnCol; j++){ - char *zName = pTab->aCol[j].zName; - char *zColname; /* The computed column name */ - char *zToFree; /* Malloced string that needs to be freed */ - Token sColname; /* Computed column name as a token */ - - assert( zName ); - if( zTName && pSub - && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0 - ){ - continue; - } - - /* If a column is marked as 'hidden', omit it from the expanded - ** result-set list unless the SELECT has the SF_IncludeHidden - ** bit set. - */ - if( (p->selFlags & SF_IncludeHidden)==0 - && IsHiddenColumn(&pTab->aCol[j]) - ){ - continue; - } - tableSeen = 1; - - if( i>0 && zTName==0 ){ - if( (pFrom->fg.jointype & JT_NATURAL)!=0 - && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1) - ){ - /* In a NATURAL join, omit the join columns from the - ** table to the right of the join */ - continue; - } - if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ - /* In a join with a USING clause, omit columns in the - ** using clause from the table on the right. */ - continue; - } - } - pRight = sqlite3Expr(db, TK_ID, zName); - zColname = zName; - zToFree = 0; - if( longNames || pTabList->nSrc>1 ){ - Expr *pLeft; - pLeft = sqlite3Expr(db, TK_ID, zTabName); - pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); - if( zSchemaName ){ - pLeft = sqlite3Expr(db, TK_ID, zSchemaName); - pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); - } - if( longNames ){ - zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); - zToFree = zColname; - } - }else{ - pExpr = pRight; - } - pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); - sqlite3TokenInit(&sColname, zColname); - sqlite3ExprListSetName(pParse, pNew, &sColname, 0); - if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){ - struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; - sqlite3DbFree(db, pX->zEName); - if( pSub ){ - pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName); - testcase( pX->zEName==0 ); - }else{ - pX->zEName = sqlite3MPrintf(db, "%s.%s.%s", - zSchemaName, zTabName, zColname); - testcase( pX->zEName==0 ); - } - pX->eEName = ENAME_TAB; - } - sqlite3DbFree(db, zToFree); - } - } - if( !tableSeen ){ - if( zTName ){ - sqlite3ErrorMsg(pParse, "no such table: %s", zTName); - }else{ - sqlite3ErrorMsg(pParse, "no tables specified"); - } - } - } - } - sqlite3ExprListDelete(db, pEList); - p->pEList = pNew; - } - if( p->pEList ){ - if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many columns in result set"); - return WRC_Abort; - } - if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ - p->selFlags |= SF_ComplexResult; - } - } - return WRC_Continue; -} - -#if SQLITE_DEBUG -/* -** Always assert. This xSelectCallback2 implementation proves that the -** xSelectCallback2 is never invoked. -*/ -SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - assert( 0 ); -} -#endif -/* -** This routine "expands" a SELECT statement and all of its subqueries. -** For additional information on what it means to "expand" a SELECT -** statement, see the comment on the selectExpand worker callback above. -** -** Expanding a SELECT statement is the first step in processing a -** SELECT statement. The SELECT statement must be expanded before -** name resolution is performed. -** -** If anything goes wrong, an error message is written into pParse. -** The calling function can detect the problem by looking at pParse->nErr -** and/or pParse->db->mallocFailed. -*/ -static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ - Walker w; - w.xExprCallback = sqlite3ExprWalkNoop; - w.pParse = pParse; - if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ - w.xSelectCallback = convertCompoundSelectToSubquery; - w.xSelectCallback2 = 0; - sqlite3WalkSelect(&w, pSelect); - } - w.xSelectCallback = selectExpander; - w.xSelectCallback2 = selectPopWith; - w.eCode = 0; - sqlite3WalkSelect(&w, pSelect); -} - - -#ifndef SQLITE_OMIT_SUBQUERY -/* -** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() -** interface. -** -** For each FROM-clause subquery, add Column.zType and Column.zColl -** information to the Table structure that represents the result set -** of that subquery. -** -** The Table structure that represents the result set was constructed -** by selectExpander() but the type and collation information was omitted -** at that point because identifiers had not yet been resolved. This -** routine is called after identifier resolution. -*/ -static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ - Parse *pParse; - int i; - SrcList *pTabList; - struct SrcList_item *pFrom; - - assert( p->selFlags & SF_Resolved ); - if( p->selFlags & SF_HasTypeInfo ) return; - p->selFlags |= SF_HasTypeInfo; - pParse = pWalker->pParse; - pTabList = p->pSrc; - for(i=0, pFrom=pTabList->a; inSrc; i++, pFrom++){ - Table *pTab = pFrom->pTab; - assert( pTab!=0 ); - if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ - /* A sub-query in the FROM clause of a SELECT */ - Select *pSel = pFrom->pSelect; - if( pSel ){ - while( pSel->pPrior ) pSel = pSel->pPrior; - sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel, - SQLITE_AFF_NONE); - } - } - } -} -#endif - - -/* -** This routine adds datatype and collating sequence information to -** the Table structures of all FROM-clause subqueries in a -** SELECT statement. -** -** Use this routine after name resolution. -*/ -static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ -#ifndef SQLITE_OMIT_SUBQUERY - Walker w; - w.xSelectCallback = sqlite3SelectWalkNoop; - w.xSelectCallback2 = selectAddSubqueryTypeInfo; - w.xExprCallback = sqlite3ExprWalkNoop; - w.pParse = pParse; - sqlite3WalkSelect(&w, pSelect); -#endif -} - - -/* -** This routine sets up a SELECT statement for processing. The -** following is accomplished: -** -** * VDBE Cursor numbers are assigned to all FROM-clause terms. -** * Ephemeral Table objects are created for all FROM-clause subqueries. -** * ON and USING clauses are shifted into WHERE statements -** * Wildcards "*" and "TABLE.*" in result sets are expanded. -** * Identifiers in expression are matched to tables. -** -** This routine acts recursively on all subqueries within the SELECT. -*/ -SQLITE_PRIVATE void sqlite3SelectPrep( - Parse *pParse, /* The parser context */ - Select *p, /* The SELECT statement being coded. */ - NameContext *pOuterNC /* Name context for container */ -){ - assert( p!=0 || pParse->db->mallocFailed ); - if( pParse->db->mallocFailed ) return; - if( p->selFlags & SF_HasTypeInfo ) return; - sqlite3SelectExpand(pParse, p); - if( pParse->nErr || pParse->db->mallocFailed ) return; - sqlite3ResolveSelectNames(pParse, p, pOuterNC); - if( pParse->nErr || pParse->db->mallocFailed ) return; - sqlite3SelectAddTypeInfo(pParse, p); -} - -/* -** Reset the aggregate accumulator. -** -** The aggregate accumulator is a set of memory cells that hold -** intermediate results while calculating an aggregate. This -** routine generates code that stores NULLs in all of those memory -** cells. -*/ -static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ - Vdbe *v = pParse->pVdbe; - int i; - struct AggInfo_func *pFunc; - int nReg = pAggInfo->nFunc + pAggInfo->nColumn; - if( nReg==0 ) return; - if( pParse->nErr || pParse->db->mallocFailed ) return; -#ifdef SQLITE_DEBUG - /* Verify that all AggInfo registers are within the range specified by - ** AggInfo.mnReg..AggInfo.mxReg */ - assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); - for(i=0; inColumn; i++){ - assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg - && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); - } - for(i=0; inFunc; i++){ - assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg - && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); - } -#endif - sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); - for(pFunc=pAggInfo->aFunc, i=0; inFunc; i++, pFunc++){ - if( pFunc->iDistinct>=0 ){ - Expr *pE = pFunc->pFExpr; - assert( !ExprHasProperty(pE, EP_xIsSelect) ); - if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ - sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " - "argument"); - pFunc->iDistinct = -1; - }else{ - KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0); - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, - (char*)pKeyInfo, P4_KEYINFO); - } - } - } -} - -/* -** Invoke the OP_AggFinalize opcode for every aggregate function -** in the AggInfo structure. -*/ -static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ - Vdbe *v = pParse->pVdbe; - int i; - struct AggInfo_func *pF; - for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ - ExprList *pList = pF->pFExpr->x.pList; - assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) ); - sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); - sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); - } -} - - -/* -** Update the accumulator memory cells for an aggregate based on -** the current cursor position. -** -** If regAcc is non-zero and there are no min() or max() aggregates -** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator -** registers if register regAcc contains 0. The caller will take care -** of setting and clearing regAcc. -*/ -static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){ - Vdbe *v = pParse->pVdbe; - int i; - int regHit = 0; - int addrHitTest = 0; - struct AggInfo_func *pF; - struct AggInfo_col *pC; - - pAggInfo->directMode = 1; - for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ - int nArg; - int addrNext = 0; - int regAgg; - ExprList *pList = pF->pFExpr->x.pList; - assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) ); - assert( !IsWindowFunc(pF->pFExpr) ); - if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){ - Expr *pFilter = pF->pFExpr->y.pWin->pFilter; - if( pAggInfo->nAccumulator - && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) - && regAcc - ){ - /* If regAcc==0, there there exists some min() or max() function - ** without a FILTER clause that will ensure the magnet registers - ** are populated. */ - if( regHit==0 ) regHit = ++pParse->nMem; - /* If this is the first row of the group (regAcc contains 0), clear the - ** "magnet" register regHit so that the accumulator registers - ** are populated if the FILTER clause jumps over the the - ** invocation of min() or max() altogether. Or, if this is not - ** the first row (regAcc contains 1), set the magnet register so that - ** the accumulators are not populated unless the min()/max() is invoked - ** and indicates that they should be. */ - sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit); - } - addrNext = sqlite3VdbeMakeLabel(pParse); - sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL); - } - if( pList ){ - nArg = pList->nExpr; - regAgg = sqlite3GetTempRange(pParse, nArg); - sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); - }else{ - nArg = 0; - regAgg = 0; - } - if( pF->iDistinct>=0 ){ - if( addrNext==0 ){ - addrNext = sqlite3VdbeMakeLabel(pParse); - } - testcase( nArg==0 ); /* Error condition */ - testcase( nArg>1 ); /* Also an error */ - codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); - } - if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ - CollSeq *pColl = 0; - struct ExprList_item *pItem; - int j; - assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ - for(j=0, pItem=pList->a; !pColl && jpExpr); - } - if( !pColl ){ - pColl = pParse->db->pDfltColl; - } - if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; - sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); - } - sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem); - sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nArg); - sqlite3ReleaseTempRange(pParse, regAgg, nArg); - if( addrNext ){ - sqlite3VdbeResolveLabel(v, addrNext); - } - } - if( regHit==0 && pAggInfo->nAccumulator ){ - regHit = regAcc; - } - if( regHit ){ - addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); - } - for(i=0, pC=pAggInfo->aCol; inAccumulator; i++, pC++){ - sqlite3ExprCode(pParse, pC->pCExpr, pC->iMem); - } - - pAggInfo->directMode = 0; - if( addrHitTest ){ - sqlite3VdbeJumpHereOrPopInst(v, addrHitTest); - } -} - -/* -** Add a single OP_Explain instruction to the VDBE to explain a simple -** count(*) query ("SELECT count(*) FROM pTab"). -*/ -#ifndef SQLITE_OMIT_EXPLAIN -static void explainSimpleCount( - Parse *pParse, /* Parse context */ - Table *pTab, /* Table being queried */ - Index *pIdx /* Index used to optimize scan, or NULL */ -){ - if( pParse->explain==2 ){ - int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); - sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s", - pTab->zName, - bCover ? " USING COVERING INDEX " : "", - bCover ? pIdx->zName : "" - ); - } -} -#else -# define explainSimpleCount(a,b,c) -#endif - -/* -** sqlite3WalkExpr() callback used by havingToWhere(). -** -** If the node passed to the callback is a TK_AND node, return -** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes. -** -** Otherwise, return WRC_Prune. In this case, also check if the -** sub-expression matches the criteria for being moved to the WHERE -** clause. If so, add it to the WHERE clause and replace the sub-expression -** within the HAVING expression with a constant "1". -*/ -static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ - if( pExpr->op!=TK_AND ){ - Select *pS = pWalker->u.pSelect; - if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){ - sqlite3 *db = pWalker->pParse->db; - Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1"); - if( pNew ){ - Expr *pWhere = pS->pWhere; - SWAP(Expr, *pNew, *pExpr); - pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew); - pS->pWhere = pNew; - pWalker->eCode = 1; - } - } - return WRC_Prune; - } - return WRC_Continue; -} - -/* -** Transfer eligible terms from the HAVING clause of a query, which is -** processed after grouping, to the WHERE clause, which is processed before -** grouping. For example, the query: -** -** SELECT * FROM WHERE a=? GROUP BY b HAVING b=? AND c=? -** -** can be rewritten as: -** -** SELECT * FROM WHERE a=? AND b=? GROUP BY b HAVING c=? -** -** A term of the HAVING expression is eligible for transfer if it consists -** entirely of constants and expressions that are also GROUP BY terms that -** use the "BINARY" collation sequence. -*/ -static void havingToWhere(Parse *pParse, Select *p){ - Walker sWalker; - memset(&sWalker, 0, sizeof(sWalker)); - sWalker.pParse = pParse; - sWalker.xExprCallback = havingToWhereExprCb; - sWalker.u.pSelect = p; - sqlite3WalkExpr(&sWalker, p->pHaving); -#if SELECTTRACE_ENABLED - if( sWalker.eCode && (sqlite3_unsupported_selecttrace & 0x100)!=0 ){ - SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif -} - -/* -** Check to see if the pThis entry of pTabList is a self-join of a prior view. -** If it is, then return the SrcList_item for the prior view. If it is not, -** then return 0. -*/ -static struct SrcList_item *isSelfJoinView( - SrcList *pTabList, /* Search for self-joins in this FROM clause */ - struct SrcList_item *pThis /* Search for prior reference to this subquery */ -){ - struct SrcList_item *pItem; - for(pItem = pTabList->a; pItempSelect==0 ) continue; - if( pItem->fg.viaCoroutine ) continue; - if( pItem->zName==0 ) continue; - assert( pItem->pTab!=0 ); - assert( pThis->pTab!=0 ); - if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue; - if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; - pS1 = pItem->pSelect; - if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){ - /* The query flattener left two different CTE tables with identical - ** names in the same FROM clause. */ - continue; - } - if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1) - || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1) - ){ - /* The view was modified by some other optimization such as - ** pushDownWhereTerms() */ - continue; - } - return pItem; - } - return 0; -} - -#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION -/* -** Attempt to transform a query of the form -** -** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) -** -** Into this: -** -** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) -** -** The transformation only works if all of the following are true: -** -** * The subquery is a UNION ALL of two or more terms -** * The subquery does not have a LIMIT clause -** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries -** * The outer query is a simple count(*) with no WHERE clause or other -** extraneous syntax. -** -** Return TRUE if the optimization is undertaken. -*/ -static int countOfViewOptimization(Parse *pParse, Select *p){ - Select *pSub, *pPrior; - Expr *pExpr; - Expr *pCount; - sqlite3 *db; - if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ - if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ - if( p->pWhere ) return 0; - if( p->pGroupBy ) return 0; - pExpr = p->pEList->a[0].pExpr; - if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ - if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ - if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ - if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ - pSub = p->pSrc->a[0].pSelect; - if( pSub==0 ) return 0; /* The FROM is a subquery */ - if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ - do{ - if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ - if( pSub->pWhere ) return 0; /* No WHERE clause */ - if( pSub->pLimit ) return 0; /* No LIMIT clause */ - if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ - pSub = pSub->pPrior; /* Repeat over compound */ - }while( pSub ); - - /* If we reach this point then it is OK to perform the transformation */ - - db = pParse->db; - pCount = pExpr; - pExpr = 0; - pSub = p->pSrc->a[0].pSelect; - p->pSrc->a[0].pSelect = 0; - sqlite3SrcListDelete(db, p->pSrc); - p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); - while( pSub ){ - Expr *pTerm; - pPrior = pSub->pPrior; - pSub->pPrior = 0; - pSub->pNext = 0; - pSub->selFlags |= SF_Aggregate; - pSub->selFlags &= ~SF_Compound; - pSub->nSelectRow = 0; - sqlite3ExprListDelete(db, pSub->pEList); - pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; - pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm); - pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0); - sqlite3PExprAddSelect(pParse, pTerm, pSub); - if( pExpr==0 ){ - pExpr = pTerm; - }else{ - pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); - } - pSub = pPrior; - } - p->pEList->a[0].pExpr = pExpr; - p->selFlags &= ~SF_Aggregate; - -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x400 ){ - SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - return 1; -} -#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ - -/* -** Generate code for the SELECT statement given in the p argument. -** -** The results are returned according to the SelectDest structure. -** See comments in sqliteInt.h for further information. -** -** This routine returns the number of errors. If any errors are -** encountered, then an appropriate error message is left in -** pParse->zErrMsg. -** -** This routine does NOT free the Select structure passed in. The -** calling function needs to do that. -*/ -SQLITE_PRIVATE int sqlite3Select( - Parse *pParse, /* The parser context */ - Select *p, /* The SELECT statement being coded. */ - SelectDest *pDest /* What to do with the query results */ -){ - int i, j; /* Loop counters */ - WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ - Vdbe *v; /* The virtual machine under construction */ - int isAgg; /* True for select lists like "count(*)" */ - ExprList *pEList = 0; /* List of columns to extract. */ - SrcList *pTabList; /* List of tables to select from */ - Expr *pWhere; /* The WHERE clause. May be NULL */ - ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ - Expr *pHaving; /* The HAVING clause. May be NULL */ - AggInfo *pAggInfo = 0; /* Aggregate information */ - int rc = 1; /* Value to return from this function */ - DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ - SortCtx sSort; /* Info on how to code the ORDER BY clause */ - int iEnd; /* Address of the end of the query */ - sqlite3 *db; /* The database connection */ - ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ - u8 minMaxFlag; /* Flag for min/max queries */ - - db = pParse->db; - v = sqlite3GetVdbe(pParse); - if( p==0 || db->mallocFailed || pParse->nErr ){ - return 1; - } - if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; -#if SELECTTRACE_ENABLED - SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain)); - if( sqlite3_unsupported_selecttrace & 0x100 ){ - sqlite3TreeViewSelect(0, p, 0); - } -#endif - - assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); - assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); - assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); - assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); - if( IgnorableOrderby(pDest) ){ - assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || - pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || - pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || - pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); - /* If ORDER BY makes no difference in the output then neither does - ** DISTINCT so it can be removed too. */ - sqlite3ExprListDelete(db, p->pOrderBy); - p->pOrderBy = 0; - p->selFlags &= ~SF_Distinct; - p->selFlags |= SF_NoopOrderBy; - } - sqlite3SelectPrep(pParse, p, 0); - if( pParse->nErr || db->mallocFailed ){ - goto select_end; - } - assert( p->pEList!=0 ); -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x104 ){ - SELECTTRACE(0x104,pParse,p, ("after name resolution:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - - /* If the SF_UpdateFrom flag is set, then this function is being called - ** as part of populating the temp table for an UPDATE...FROM statement. - ** In this case, it is an error if the target object (pSrc->a[0]) name - ** or alias is duplicated within FROM clause (pSrc->a[1..n]). */ - if( p->selFlags & SF_UpdateFrom ){ - struct SrcList_item *p0 = &p->pSrc->a[0]; - for(i=1; ipSrc->nSrc; i++){ - struct SrcList_item *p1 = &p->pSrc->a[i]; - if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){ - sqlite3ErrorMsg(pParse, - "target object/alias may not appear in FROM clause: %s", - p0->zAlias ? p0->zAlias : p0->pTab->zName - ); - goto select_end; - } - } - } - - if( pDest->eDest==SRT_Output ){ - generateColumnNames(pParse, p); - } - -#ifndef SQLITE_OMIT_WINDOWFUNC - rc = sqlite3WindowRewrite(pParse, p); - if( rc ){ - assert( db->mallocFailed || pParse->nErr>0 ); - goto select_end; - } -#if SELECTTRACE_ENABLED - if( p->pWin && (sqlite3_unsupported_selecttrace & 0x108)!=0 ){ - SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif -#endif /* SQLITE_OMIT_WINDOWFUNC */ - pTabList = p->pSrc; - isAgg = (p->selFlags & SF_Aggregate)!=0; - memset(&sSort, 0, sizeof(sSort)); - sSort.pOrderBy = p->pOrderBy; - - /* Try to do various optimizations (flattening subqueries, and strength - ** reduction of join operators) in the FROM clause up into the main query - */ -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) - for(i=0; !p->pPrior && inSrc; i++){ - struct SrcList_item *pItem = &pTabList->a[i]; - Select *pSub = pItem->pSelect; - Table *pTab = pItem->pTab; - - /* The expander should have already created transient Table objects - ** even for FROM clause elements such as subqueries that do not correspond - ** to a real table */ - assert( pTab!=0 ); - - /* Convert LEFT JOIN into JOIN if there are terms of the right table - ** of the LEFT JOIN used in the WHERE clause. - */ - if( (pItem->fg.jointype & JT_LEFT)!=0 - && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) - && OptimizationEnabled(db, SQLITE_SimplifyJoin) - ){ - SELECTTRACE(0x100,pParse,p, - ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); - pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); - unsetJoinExpr(p->pWhere, pItem->iCursor); - } - - /* No futher action if this term of the FROM clause is no a subquery */ - if( pSub==0 ) continue; - - /* Catch mismatch in the declared columns of a view and the number of - ** columns in the SELECT on the RHS */ - if( pTab->nCol!=pSub->pEList->nExpr ){ - sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", - pTab->nCol, pTab->zName, pSub->pEList->nExpr); - goto select_end; - } - - /* Do not try to flatten an aggregate subquery. - ** - ** Flattening an aggregate subquery is only possible if the outer query - ** is not a join. But if the outer query is not a join, then the subquery - ** will be implemented as a co-routine and there is no advantage to - ** flattening in that case. - */ - if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; - assert( pSub->pGroupBy==0 ); - - /* If the outer query contains a "complex" result set (that is, - ** if the result set of the outer query uses functions or subqueries) - ** and if the subquery contains an ORDER BY clause and if - ** it will be implemented as a co-routine, then do not flatten. This - ** restriction allows SQL constructs like this: - ** - ** SELECT expensive_function(x) - ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); - ** - ** The expensive_function() is only computed on the 10 rows that - ** are output, rather than every row of the table. - ** - ** The requirement that the outer query have a complex result set - ** means that flattening does occur on simpler SQL constraints without - ** the expensive_function() like: - ** - ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); - */ - if( pSub->pOrderBy!=0 - && i==0 - && (p->selFlags & SF_ComplexResult)!=0 - && (pTabList->nSrc==1 - || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) - ){ - continue; - } - - if( flattenSubquery(pParse, p, i, isAgg) ){ - if( pParse->nErr ) goto select_end; - /* This subquery can be absorbed into its parent. */ - i = -1; - } - pTabList = p->pSrc; - if( db->mallocFailed ) goto select_end; - if( !IgnorableOrderby(pDest) ){ - sSort.pOrderBy = p->pOrderBy; - } - } -#endif - -#ifndef SQLITE_OMIT_COMPOUND_SELECT - /* Handle compound SELECT statements using the separate multiSelect() - ** procedure. - */ - if( p->pPrior ){ - rc = multiSelect(pParse, p, pDest); -#if SELECTTRACE_ENABLED - SELECTTRACE(0x1,pParse,p,("end compound-select processing\n")); - if( (sqlite3_unsupported_selecttrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ - sqlite3TreeViewSelect(0, p, 0); - } -#endif - if( p->pNext==0 ) ExplainQueryPlanPop(pParse); - return rc; - } -#endif - - /* Do the WHERE-clause constant propagation optimization if this is - ** a join. No need to speed time on this operation for non-join queries - ** as the equivalent optimization will be handled by query planner in - ** sqlite3WhereBegin(). - */ - if( pTabList->nSrc>1 - && OptimizationEnabled(db, SQLITE_PropagateConst) - && propagateConstants(pParse, p) - ){ -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p,("After constant propagation:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - }else{ - SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n")); - } - -#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION - if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) - && countOfViewOptimization(pParse, p) - ){ - if( db->mallocFailed ) goto select_end; - pEList = p->pEList; - pTabList = p->pSrc; - } -#endif - - /* For each term in the FROM clause, do two things: - ** (1) Authorized unreferenced tables - ** (2) Generate code for all sub-queries - */ - for(i=0; inSrc; i++){ - struct SrcList_item *pItem = &pTabList->a[i]; - SelectDest dest; - Select *pSub; -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) - const char *zSavedAuthContext; -#endif - - /* Issue SQLITE_READ authorizations with a fake column name for any - ** tables that are referenced but from which no values are extracted. - ** Examples of where these kinds of null SQLITE_READ authorizations - ** would occur: - ** - ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" - ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" - ** - ** The fake column name is an empty string. It is possible for a table to - ** have a column named by the empty string, in which case there is no way to - ** distinguish between an unreferenced table and an actual reference to the - ** "" column. The original design was for the fake column name to be a NULL, - ** which would be unambiguous. But legacy authorization callbacks might - ** assume the column name is non-NULL and segfault. The use of an empty - ** string for the fake column name seems safer. - */ - if( pItem->colUsed==0 && pItem->zName!=0 ){ - sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); - } - -#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) - /* Generate code for all sub-queries in the FROM clause - */ - pSub = pItem->pSelect; - if( pSub==0 ) continue; - - /* The code for a subquery should only be generated once, though it is - ** technically harmless for it to be generated multiple times. The - ** following assert() will detect if something changes to cause - ** the same subquery to be coded multiple times, as a signal to the - ** developers to try to optimize the situation. - ** - ** Update 2019-07-24: - ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40. - ** The dbsqlfuzz fuzzer found a case where the same subquery gets - ** coded twice. So this assert() now becomes a testcase(). It should - ** be very rare, though. - */ - testcase( pItem->addrFillSub!=0 ); - - /* Increment Parse.nHeight by the height of the largest expression - ** tree referred to by this, the parent select. The child select - ** may contain expression trees of at most - ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit - ** more conservative than necessary, but much easier than enforcing - ** an exact limit. - */ - pParse->nHeight += sqlite3SelectExprHeight(p); - - /* Make copies of constant WHERE-clause terms in the outer query down - ** inside the subquery. This can help the subquery to run more efficiently. - */ - if( OptimizationEnabled(db, SQLITE_PushDown) - && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, - (pItem->fg.jointype & JT_OUTER)!=0) - ){ -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p, - ("After WHERE-clause push-down into subquery %d:\n", pSub->selId)); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - }else{ - SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); - } - - zSavedAuthContext = pParse->zAuthContext; - pParse->zAuthContext = pItem->zName; - - /* Generate code to implement the subquery - ** - ** The subquery is implemented as a co-routine if the subquery is - ** guaranteed to be the outer loop (so that it does not need to be - ** computed more than once) - ** - ** TODO: Are there other reasons beside (1) to use a co-routine - ** implementation? - */ - if( i==0 - && (pTabList->nSrc==1 - || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ - ){ - /* Implement a co-routine that will return a single row of the result - ** set on each invocation. - */ - int addrTop = sqlite3VdbeCurrentAddr(v)+1; - - pItem->regReturn = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); - VdbeComment((v, "%s", pItem->pTab->zName)); - pItem->addrFillSub = addrTop; - sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); - ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId)); - sqlite3Select(pParse, pSub, &dest); - pItem->pTab->nRowLogEst = pSub->nSelectRow; - pItem->fg.viaCoroutine = 1; - pItem->regResult = dest.iSdst; - sqlite3VdbeEndCoroutine(v, pItem->regReturn); - sqlite3VdbeJumpHere(v, addrTop-1); - sqlite3ClearTempRegCache(pParse); - }else{ - /* Generate a subroutine that will fill an ephemeral table with - ** the content of this subquery. pItem->addrFillSub will point - ** to the address of the generated subroutine. pItem->regReturn - ** is a register allocated to hold the subroutine return address - */ - int topAddr; - int onceAddr = 0; - int retAddr; - struct SrcList_item *pPrior; - - testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */ - pItem->regReturn = ++pParse->nMem; - topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); - pItem->addrFillSub = topAddr+1; - if( pItem->fg.isCorrelated==0 ){ - /* If the subquery is not correlated and if we are not inside of - ** a trigger, then we only need to compute the value of the subquery - ** once. */ - onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); - }else{ - VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); - } - pPrior = isSelfJoinView(pTabList, pItem); - if( pPrior ){ - sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); - assert( pPrior->pSelect!=0 ); - pSub->nSelectRow = pPrior->pSelect->nSelectRow; - }else{ - sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); - ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId)); - sqlite3Select(pParse, pSub, &dest); - } - pItem->pTab->nRowLogEst = pSub->nSelectRow; - if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); - retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); - VdbeComment((v, "end %s", pItem->pTab->zName)); - sqlite3VdbeChangeP1(v, topAddr, retAddr); - sqlite3ClearTempRegCache(pParse); - } - if( db->mallocFailed ) goto select_end; - pParse->nHeight -= sqlite3SelectExprHeight(p); - pParse->zAuthContext = zSavedAuthContext; -#endif - } - - /* Various elements of the SELECT copied into local variables for - ** convenience */ - pEList = p->pEList; - pWhere = p->pWhere; - pGroupBy = p->pGroupBy; - pHaving = p->pHaving; - sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; - -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x400 ){ - SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - - /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and - ** if the select-list is the same as the ORDER BY list, then this query - ** can be rewritten as a GROUP BY. In other words, this: - ** - ** SELECT DISTINCT xyz FROM ... ORDER BY xyz - ** - ** is transformed to: - ** - ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz - ** - ** The second form is preferred as a single index (or temp-table) may be - ** used for both the ORDER BY and DISTINCT processing. As originally - ** written the query must use a temp-table for at least one of the ORDER - ** BY and DISTINCT, and an index or separate temp-table for the other. - */ - if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct - && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 -#ifndef SQLITE_OMIT_WINDOWFUNC - && p->pWin==0 -#endif - ){ - p->selFlags &= ~SF_Distinct; - pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); - p->selFlags |= SF_Aggregate; - /* Notice that even thought SF_Distinct has been cleared from p->selFlags, - ** the sDistinct.isTnct is still set. Hence, isTnct represents the - ** original setting of the SF_Distinct flag, not the current setting */ - assert( sDistinct.isTnct ); - -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x400 ){ - SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - } - - /* If there is an ORDER BY clause, then create an ephemeral index to - ** do the sorting. But this sorting ephemeral index might end up - ** being unused if the data can be extracted in pre-sorted order. - ** If that is the case, then the OP_OpenEphemeral instruction will be - ** changed to an OP_Noop once we figure out that the sorting index is - ** not needed. The sSort.addrSortIndex variable is used to facilitate - ** that change. - */ - if( sSort.pOrderBy ){ - KeyInfo *pKeyInfo; - pKeyInfo = sqlite3KeyInfoFromExprList( - pParse, sSort.pOrderBy, 0, pEList->nExpr); - sSort.iECursor = pParse->nTab++; - sSort.addrSortIndex = - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, - sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, - (char*)pKeyInfo, P4_KEYINFO - ); - }else{ - sSort.addrSortIndex = -1; - } - - /* If the output is destined for a temporary table, open that table. - */ - if( pDest->eDest==SRT_EphemTab ){ - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); - } - - /* Set the limiter. - */ - iEnd = sqlite3VdbeMakeLabel(pParse); - if( (p->selFlags & SF_FixedLimit)==0 ){ - p->nSelectRow = 320; /* 4 billion rows */ - } - computeLimitRegisters(pParse, p, iEnd); - if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ - sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); - sSort.sortFlags |= SORTFLAG_UseSorter; - } - - /* Open an ephemeral index to use for the distinct set. - */ - if( p->selFlags & SF_Distinct ){ - sDistinct.tabTnct = pParse->nTab++; - sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, - sDistinct.tabTnct, 0, 0, - (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0), - P4_KEYINFO); - sqlite3VdbeChangeP5(v, BTREE_UNORDERED); - sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; - }else{ - sDistinct.eTnctType = WHERE_DISTINCT_NOOP; - } - - if( !isAgg && pGroupBy==0 ){ - /* No aggregate functions and no GROUP BY clause */ - u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0) - | (p->selFlags & SF_FixedLimit); -#ifndef SQLITE_OMIT_WINDOWFUNC - Window *pWin = p->pWin; /* Main window object (or NULL) */ - if( pWin ){ - sqlite3WindowCodeInit(pParse, p); - } -#endif - assert( WHERE_USE_LIMIT==SF_FixedLimit ); - - - /* Begin the database scan. */ - SELECTTRACE(1,pParse,p,("WhereBegin\n")); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, - p->pEList, wctrlFlags, p->nSelectRow); - if( pWInfo==0 ) goto select_end; - if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ - p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); - } - if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ - sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); - } - if( sSort.pOrderBy ){ - sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); - sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo); - if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ - sSort.pOrderBy = 0; - } - } - - /* If sorting index that was created by a prior OP_OpenEphemeral - ** instruction ended up not being needed, then change the OP_OpenEphemeral - ** into an OP_Noop. - */ - if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ - sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); - } - - assert( p->pEList==pEList ); -#ifndef SQLITE_OMIT_WINDOWFUNC - if( pWin ){ - int addrGosub = sqlite3VdbeMakeLabel(pParse); - int iCont = sqlite3VdbeMakeLabel(pParse); - int iBreak = sqlite3VdbeMakeLabel(pParse); - int regGosub = ++pParse->nMem; - - sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub); - - sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); - sqlite3VdbeResolveLabel(v, addrGosub); - VdbeNoopComment((v, "inner-loop subroutine")); - sSort.labelOBLopt = 0; - selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp1(v, OP_Return, regGosub); - VdbeComment((v, "end inner-loop subroutine")); - sqlite3VdbeResolveLabel(v, iBreak); - }else -#endif /* SQLITE_OMIT_WINDOWFUNC */ - { - /* Use the standard inner loop. */ - selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, - sqlite3WhereContinueLabel(pWInfo), - sqlite3WhereBreakLabel(pWInfo)); - - /* End the database scan loop. - */ - sqlite3WhereEnd(pWInfo); - } - }else{ - /* This case when there exist aggregate functions or a GROUP BY clause - ** or both */ - NameContext sNC; /* Name context for processing aggregate information */ - int iAMem; /* First Mem address for storing current GROUP BY */ - int iBMem; /* First Mem address for previous GROUP BY */ - int iUseFlag; /* Mem address holding flag indicating that at least - ** one row of the input to the aggregator has been - ** processed */ - int iAbortFlag; /* Mem address which causes query abort if positive */ - int groupBySort; /* Rows come from source in GROUP BY order */ - int addrEnd; /* End of processing for this SELECT */ - int sortPTab = 0; /* Pseudotable used to decode sorting results */ - int sortOut = 0; /* Output register from the sorter */ - int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ - - /* Remove any and all aliases between the result set and the - ** GROUP BY clause. - */ - if( pGroupBy ){ - int k; /* Loop counter */ - struct ExprList_item *pItem; /* For looping over expression in a list */ - - for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ - pItem->u.x.iAlias = 0; - } - for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ - pItem->u.x.iAlias = 0; - } - assert( 66==sqlite3LogEst(100) ); - if( p->nSelectRow>66 ) p->nSelectRow = 66; - - /* If there is both a GROUP BY and an ORDER BY clause and they are - ** identical, then it may be possible to disable the ORDER BY clause - ** on the grounds that the GROUP BY will cause elements to come out - ** in the correct order. It also may not - the GROUP BY might use a - ** database index that causes rows to be grouped together as required - ** but not actually sorted. Either way, record the fact that the - ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp - ** variable. */ - if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){ - int ii; - /* The GROUP BY processing doesn't care whether rows are delivered in - ** ASC or DESC order - only that each group is returned contiguously. - ** So set the ASC/DESC flags in the GROUP BY to match those in the - ** ORDER BY to maximize the chances of rows being delivered in an - ** order that makes the ORDER BY redundant. */ - for(ii=0; iinExpr; ii++){ - u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC; - pGroupBy->a[ii].sortFlags = sortFlags; - } - if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ - orderByGrp = 1; - } - } - }else{ - assert( 0==sqlite3LogEst(1) ); - p->nSelectRow = 0; - } - - /* Create a label to jump to when we want to abort the query */ - addrEnd = sqlite3VdbeMakeLabel(pParse); - - /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in - ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the - ** SELECT statement. - */ - pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) ); - if( pAggInfo==0 ){ - goto select_end; - } - pAggInfo->pNext = pParse->pAggList; - pParse->pAggList = pAggInfo; - pAggInfo->selId = p->selId; - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - sNC.pSrcList = pTabList; - sNC.uNC.pAggInfo = pAggInfo; - VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) - pAggInfo->mnReg = pParse->nMem+1; - pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; - pAggInfo->pGroupBy = pGroupBy; - sqlite3ExprAnalyzeAggList(&sNC, pEList); - sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); - if( pHaving ){ - if( pGroupBy ){ - assert( pWhere==p->pWhere ); - assert( pHaving==p->pHaving ); - assert( pGroupBy==p->pGroupBy ); - havingToWhere(pParse, p); - pWhere = p->pWhere; - } - sqlite3ExprAnalyzeAggregates(&sNC, pHaving); - } - pAggInfo->nAccumulator = pAggInfo->nColumn; - if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){ - minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy); - }else{ - minMaxFlag = WHERE_ORDERBY_NORMAL; - } - for(i=0; inFunc; i++){ - Expr *pExpr = pAggInfo->aFunc[i].pFExpr; - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - sNC.ncFlags |= NC_InAggFunc; - sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList); -#ifndef SQLITE_OMIT_WINDOWFUNC - assert( !IsWindowFunc(pExpr) ); - if( ExprHasProperty(pExpr, EP_WinFunc) ){ - sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter); - } -#endif - sNC.ncFlags &= ~NC_InAggFunc; - } - pAggInfo->mxReg = pParse->nMem; - if( db->mallocFailed ) goto select_end; -#if SELECTTRACE_ENABLED - if( sqlite3_unsupported_selecttrace & 0x400 ){ - int ii; - SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", pAggInfo)); - sqlite3TreeViewSelect(0, p, 0); - for(ii=0; iinColumn; ii++){ - sqlite3DebugPrintf("agg-column[%d] iMem=%d\n", - ii, pAggInfo->aCol[ii].iMem); - sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0); - } - for(ii=0; iinFunc; ii++){ - sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", - ii, pAggInfo->aFunc[ii].iMem); - sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0); - } - } -#endif - - - /* Processing for aggregates with GROUP BY is very different and - ** much more complex than aggregates without a GROUP BY. - */ - if( pGroupBy ){ - KeyInfo *pKeyInfo; /* Keying information for the group by clause */ - int addr1; /* A-vs-B comparision jump */ - int addrOutputRow; /* Start of subroutine that outputs a result row */ - int regOutputRow; /* Return address register for output subroutine */ - int addrSetAbort; /* Set the abort flag and return */ - int addrTopOfLoop; /* Top of the input loop */ - int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ - int addrReset; /* Subroutine for resetting the accumulator */ - int regReset; /* Return address register for reset subroutine */ - - /* If there is a GROUP BY clause we might need a sorting index to - ** implement it. Allocate that sorting index now. If it turns out - ** that we do not need it after all, the OP_SorterOpen instruction - ** will be converted into a Noop. - */ - pAggInfo->sortingIdx = pParse->nTab++; - pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy, - 0, pAggInfo->nColumn); - addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, - pAggInfo->sortingIdx, pAggInfo->nSortingColumn, - 0, (char*)pKeyInfo, P4_KEYINFO); - - /* Initialize memory locations used by GROUP BY aggregate processing - */ - iUseFlag = ++pParse->nMem; - iAbortFlag = ++pParse->nMem; - regOutputRow = ++pParse->nMem; - addrOutputRow = sqlite3VdbeMakeLabel(pParse); - regReset = ++pParse->nMem; - addrReset = sqlite3VdbeMakeLabel(pParse); - iAMem = pParse->nMem + 1; - pParse->nMem += pGroupBy->nExpr; - iBMem = pParse->nMem + 1; - pParse->nMem += pGroupBy->nExpr; - sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); - VdbeComment((v, "clear abort flag")); - sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); - - /* Begin a loop that will extract all source rows in GROUP BY order. - ** This might involve two separate loops with an OP_Sort in between, or - ** it might be a single loop that uses an index to extract information - ** in the right order to begin with. - */ - sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); - SELECTTRACE(1,pParse,p,("WhereBegin\n")); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, - WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 - ); - if( pWInfo==0 ) goto select_end; - if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ - /* The optimizer is able to deliver rows in group by order so - ** we do not have to sort. The OP_OpenEphemeral table will be - ** cancelled later because we still need to use the pKeyInfo - */ - groupBySort = 0; - }else{ - /* Rows are coming out in undetermined order. We have to push - ** each row into a sorting index, terminate the first loop, - ** then loop over the sorting index in order to get the output - ** in sorted order - */ - int regBase; - int regRecord; - int nCol; - int nGroupBy; - - explainTempTable(pParse, - (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? - "DISTINCT" : "GROUP BY"); - - groupBySort = 1; - nGroupBy = pGroupBy->nExpr; - nCol = nGroupBy; - j = nGroupBy; - for(i=0; inColumn; i++){ - if( pAggInfo->aCol[i].iSorterColumn>=j ){ - nCol++; - j++; - } - } - regBase = sqlite3GetTempRange(pParse, nCol); - sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); - j = nGroupBy; - for(i=0; inColumn; i++){ - struct AggInfo_col *pCol = &pAggInfo->aCol[i]; - if( pCol->iSorterColumn>=j ){ - int r1 = j + regBase; - sqlite3ExprCodeGetColumnOfTable(v, - pCol->pTab, pCol->iTable, pCol->iColumn, r1); - j++; - } - } - regRecord = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); - sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3ReleaseTempRange(pParse, regBase, nCol); - sqlite3WhereEnd(pWInfo); - pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++; - sortOut = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); - sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd); - VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); - pAggInfo->useSortingIdx = 1; - } - - /* If the index or temporary table used by the GROUP BY sort - ** will naturally deliver rows in the order required by the ORDER BY - ** clause, cancel the ephemeral table open coded earlier. - ** - ** This is an optimization - the correct answer should result regardless. - ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to - ** disable this optimization for testing purposes. */ - if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) - && (groupBySort || sqlite3WhereIsSorted(pWInfo)) - ){ - sSort.pOrderBy = 0; - sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); - } - - /* Evaluate the current GROUP BY terms and store in b0, b1, b2... - ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) - ** Then compare the current GROUP BY terms against the GROUP BY terms - ** from the previous row currently stored in a0, a1, a2... - */ - addrTopOfLoop = sqlite3VdbeCurrentAddr(v); - if( groupBySort ){ - sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx, - sortOut, sortPTab); - } - for(j=0; jnExpr; j++){ - if( groupBySort ){ - sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); - }else{ - pAggInfo->directMode = 1; - sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); - } - } - sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, - (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); - addr1 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); - - /* Generate code that runs whenever the GROUP BY changes. - ** Changes in the GROUP BY are detected by the previous code - ** block. If there were no changes, this block is skipped. - ** - ** This code copies current group by terms in b0,b1,b2,... - ** over to a0,a1,a2. It then calls the output subroutine - ** and resets the aggregate accumulator registers in preparation - ** for the next GROUP BY batch. - */ - sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); - sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); - VdbeComment((v, "output one row")); - sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); - VdbeComment((v, "check abort flag")); - sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); - VdbeComment((v, "reset accumulator")); - - /* Update the aggregate accumulators based on the content of - ** the current row - */ - sqlite3VdbeJumpHere(v, addr1); - updateAccumulator(pParse, iUseFlag, pAggInfo); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); - VdbeComment((v, "indicate data in accumulator")); - - /* End of the loop - */ - if( groupBySort ){ - sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx, addrTopOfLoop); - VdbeCoverage(v); - }else{ - sqlite3WhereEnd(pWInfo); - sqlite3VdbeChangeToNoop(v, addrSortingIdx); - } - - /* Output the final row of result - */ - sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); - VdbeComment((v, "output final row")); - - /* Jump over the subroutines - */ - sqlite3VdbeGoto(v, addrEnd); - - /* Generate a subroutine that outputs a single row of the result - ** set. This subroutine first looks at the iUseFlag. If iUseFlag - ** is less than or equal to zero, the subroutine is a no-op. If - ** the processing calls for the query to abort, this subroutine - ** increments the iAbortFlag memory location before returning in - ** order to signal the caller to abort. - */ - addrSetAbort = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); - VdbeComment((v, "set abort flag")); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); - sqlite3VdbeResolveLabel(v, addrOutputRow); - addrOutputRow = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); - VdbeCoverage(v); - VdbeComment((v, "Groupby result generator entry point")); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); - finalizeAggFunctions(pParse, pAggInfo); - sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); - selectInnerLoop(pParse, p, -1, &sSort, - &sDistinct, pDest, - addrOutputRow+1, addrSetAbort); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); - VdbeComment((v, "end groupby result generator")); - - /* Generate a subroutine that will reset the group-by accumulator - */ - sqlite3VdbeResolveLabel(v, addrReset); - resetAccumulator(pParse, pAggInfo); - sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); - VdbeComment((v, "indicate accumulator empty")); - sqlite3VdbeAddOp1(v, OP_Return, regReset); - - } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ - else { - Table *pTab; - if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){ - /* If isSimpleCount() returns a pointer to a Table structure, then - ** the SQL statement is of the form: - ** - ** SELECT count(*) FROM - ** - ** where the Table structure returned represents table . - ** - ** This statement is so common that it is optimized specially. The - ** OP_Count instruction is executed either on the intkey table that - ** contains the data for table or on one of its indexes. It - ** is better to execute the op on an index, as indexes are almost - ** always spread across less pages than their corresponding tables. - */ - const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ - Index *pIdx; /* Iterator variable */ - KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ - Index *pBest = 0; /* Best index found so far */ - Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */ - - sqlite3CodeVerifySchema(pParse, iDb); - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); - - /* Search for the index that has the lowest scan cost. - ** - ** (2011-04-15) Do not do a full scan of an unordered index. - ** - ** (2013-10-03) Do not count the entries in a partial index. - ** - ** In practice the KeyInfo structure will not be used. It is only - ** passed to keep OP_OpenRead happy. - */ - if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); - if( !p->pSrc->a[0].fg.notIndexed ){ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->bUnordered==0 - && pIdx->szIdxRowszTabRow - && pIdx->pPartIdxWhere==0 - && (!pBest || pIdx->szIdxRowszIdxRow) - ){ - pBest = pIdx; - } - } - } - if( pBest ){ - iRoot = pBest->tnum; - pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); - } - - /* Open a read-only cursor, execute the OP_Count, close the cursor. */ - sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1); - if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); - } - sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem); - sqlite3VdbeAddOp1(v, OP_Close, iCsr); - explainSimpleCount(pParse, pTab, pBest); - }else{ - int regAcc = 0; /* "populate accumulators" flag */ - int addrSkip; - - /* If there are accumulator registers but no min() or max() functions - ** without FILTER clauses, allocate register regAcc. Register regAcc - ** will contain 0 the first time the inner loop runs, and 1 thereafter. - ** The code generated by updateAccumulator() uses this to ensure - ** that the accumulator registers are (a) updated only once if - ** there are no min() or max functions or (b) always updated for the - ** first row visited by the aggregate, so that they are updated at - ** least once even if the FILTER clause means the min() or max() - ** function visits zero rows. */ - if( pAggInfo->nAccumulator ){ - for(i=0; inFunc; i++){ - if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){ - continue; - } - if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){ - break; - } - } - if( i==pAggInfo->nFunc ){ - regAcc = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc); - } - } - - /* This case runs if the aggregate has no GROUP BY clause. The - ** processing is much simpler since there is only a single row - ** of output. - */ - assert( p->pGroupBy==0 ); - resetAccumulator(pParse, pAggInfo); - - /* If this query is a candidate for the min/max optimization, then - ** minMaxFlag will have been previously set to either - ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will - ** be an appropriate ORDER BY expression for the optimization. - */ - assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); - assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); - - SELECTTRACE(1,pParse,p,("WhereBegin\n")); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, - 0, minMaxFlag, 0); - if( pWInfo==0 ){ - goto select_end; - } - updateAccumulator(pParse, regAcc, pAggInfo); - if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc); - addrSkip = sqlite3WhereOrderByLimitOptLabel(pWInfo); - if( addrSkip!=sqlite3WhereContinueLabel(pWInfo) ){ - sqlite3VdbeGoto(v, addrSkip); - } - sqlite3WhereEnd(pWInfo); - finalizeAggFunctions(pParse, pAggInfo); - } - - sSort.pOrderBy = 0; - sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); - selectInnerLoop(pParse, p, -1, 0, 0, - pDest, addrEnd, addrEnd); - } - sqlite3VdbeResolveLabel(v, addrEnd); - - } /* endif aggregate query */ - - if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ - explainTempTable(pParse, "DISTINCT"); - } - - /* If there is an ORDER BY clause, then we need to sort the results - ** and send them to the callback one by one. - */ - if( sSort.pOrderBy ){ - explainTempTable(pParse, - sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); - assert( p->pEList==pEList ); - generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); - } - - /* Jump here to skip this query - */ - sqlite3VdbeResolveLabel(v, iEnd); - - /* The SELECT has been coded. If there is an error in the Parse structure, - ** set the return code to 1. Otherwise 0. */ - rc = (pParse->nErr>0); - - /* Control jumps to here if an error is encountered above, or upon - ** successful coding of the SELECT. - */ -select_end: - sqlite3ExprListDelete(db, pMinMaxOrderBy); -#ifdef SQLITE_DEBUG - if( pAggInfo && !db->mallocFailed ){ - for(i=0; inColumn; i++){ - Expr *pExpr = pAggInfo->aCol[i].pCExpr; - assert( pExpr!=0 || db->mallocFailed ); - if( pExpr==0 ) continue; - assert( pExpr->pAggInfo==pAggInfo ); - assert( pExpr->iAgg==i ); - } - for(i=0; inFunc; i++){ - Expr *pExpr = pAggInfo->aFunc[i].pFExpr; - assert( pExpr!=0 || db->mallocFailed ); - if( pExpr==0 ) continue; - assert( pExpr->pAggInfo==pAggInfo ); - assert( pExpr->iAgg==i ); - } - } -#endif - -#if SELECTTRACE_ENABLED - SELECTTRACE(0x1,pParse,p,("end processing\n")); - if( (sqlite3_unsupported_selecttrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ - sqlite3TreeViewSelect(0, p, 0); - } -#endif - ExplainQueryPlanPop(pParse); - return rc; -} - -/************** End of select.c **********************************************/ -/************** Begin file table.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 the sqlite3_get_table() and sqlite3_free_table() -** interface routines. These are just wrappers around the main -** interface routine of sqlite3_exec(). -** -** These routines are in a separate files so that they will not be linked -** if they are not used. -*/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_OMIT_GET_TABLE - -/* -** This structure is used to pass data from sqlite3_get_table() through -** to the callback function is uses to build the result. -*/ -typedef struct TabResult { - char **azResult; /* Accumulated output */ - char *zErrMsg; /* Error message text, if an error occurs */ - u32 nAlloc; /* Slots allocated for azResult[] */ - u32 nRow; /* Number of rows in the result */ - u32 nColumn; /* Number of columns in the result */ - u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */ - int rc; /* Return code from sqlite3_exec() */ -} TabResult; - -/* -** This routine is called once for each row in the result table. Its job -** is to fill in the TabResult structure appropriately, allocating new -** memory as necessary. -*/ -static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ - TabResult *p = (TabResult*)pArg; /* Result accumulator */ - int need; /* Slots needed in p->azResult[] */ - int i; /* Loop counter */ - char *z; /* A single column of result */ - - /* Make sure there is enough space in p->azResult to hold everything - ** we need to remember from this invocation of the callback. - */ - if( p->nRow==0 && argv!=0 ){ - need = nCol*2; - }else{ - need = nCol; - } - if( p->nData + need > p->nAlloc ){ - char **azNew; - p->nAlloc = p->nAlloc*2 + need; - azNew = sqlite3Realloc( p->azResult, sizeof(char*)*p->nAlloc ); - if( azNew==0 ) goto malloc_failed; - p->azResult = azNew; - } - - /* If this is the first row, then generate an extra row containing - ** the names of all columns. - */ - if( p->nRow==0 ){ - p->nColumn = nCol; - for(i=0; iazResult[p->nData++] = z; - } - }else if( (int)p->nColumn!=nCol ){ - sqlite3_free(p->zErrMsg); - p->zErrMsg = sqlite3_mprintf( - "sqlite3_get_table() called with two or more incompatible queries" - ); - p->rc = SQLITE_ERROR; - return 1; - } - - /* Copy over the row data - */ - if( argv!=0 ){ - for(i=0; iazResult[p->nData++] = z; - } - p->nRow++; - } - return 0; - -malloc_failed: - p->rc = SQLITE_NOMEM_BKPT; - return 1; -} - -/* -** Query the database. But instead of invoking a callback for each row, -** malloc() for space to hold the result and return the entire results -** at the conclusion of the call. -** -** The result that is written to ***pazResult is held in memory obtained -** from malloc(). But the caller cannot free this memory directly. -** Instead, the entire table should be passed to sqlite3_free_table() when -** the calling procedure is finished using it. -*/ -SQLITE_API int sqlite3_get_table( - sqlite3 *db, /* The database on which the SQL executes */ - const char *zSql, /* The SQL to be executed */ - char ***pazResult, /* Write the result table here */ - int *pnRow, /* Write the number of rows in the result here */ - int *pnColumn, /* Write the number of columns of result here */ - char **pzErrMsg /* Write error messages here */ -){ - int rc; - TabResult res; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT; -#endif - *pazResult = 0; - if( pnColumn ) *pnColumn = 0; - if( pnRow ) *pnRow = 0; - if( pzErrMsg ) *pzErrMsg = 0; - res.zErrMsg = 0; - res.nRow = 0; - res.nColumn = 0; - res.nData = 1; - res.nAlloc = 20; - res.rc = SQLITE_OK; - res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc ); - if( res.azResult==0 ){ - db->errCode = SQLITE_NOMEM; - return SQLITE_NOMEM_BKPT; - } - res.azResult[0] = 0; - rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); - assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); - res.azResult[0] = SQLITE_INT_TO_PTR(res.nData); - if( (rc&0xff)==SQLITE_ABORT ){ - sqlite3_free_table(&res.azResult[1]); - if( res.zErrMsg ){ - if( pzErrMsg ){ - sqlite3_free(*pzErrMsg); - *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); - } - sqlite3_free(res.zErrMsg); - } - db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ - return res.rc; - } - sqlite3_free(res.zErrMsg); - if( rc!=SQLITE_OK ){ - sqlite3_free_table(&res.azResult[1]); - return rc; - } - if( res.nAlloc>res.nData ){ - char **azNew; - azNew = sqlite3Realloc( res.azResult, sizeof(char*)*res.nData ); - if( azNew==0 ){ - sqlite3_free_table(&res.azResult[1]); - db->errCode = SQLITE_NOMEM; - return SQLITE_NOMEM_BKPT; - } - res.azResult = azNew; - } - *pazResult = &res.azResult[1]; - if( pnColumn ) *pnColumn = res.nColumn; - if( pnRow ) *pnRow = res.nRow; - return rc; -} - -/* -** This routine frees the space the sqlite3_get_table() malloced. -*/ -SQLITE_API void sqlite3_free_table( - char **azResult /* Result returned from sqlite3_get_table() */ -){ - if( azResult ){ - int i, n; - azResult--; - assert( azResult!=0 ); - n = SQLITE_PTR_TO_INT(azResult[0]); - for(i=1; ipNext; - - sqlite3ExprDelete(db, pTmp->pWhere); - sqlite3ExprListDelete(db, pTmp->pExprList); - sqlite3SelectDelete(db, pTmp->pSelect); - sqlite3IdListDelete(db, pTmp->pIdList); - sqlite3UpsertDelete(db, pTmp->pUpsert); - sqlite3SrcListDelete(db, pTmp->pFrom); - sqlite3DbFree(db, pTmp->zSpan); - - sqlite3DbFree(db, pTmp); - } -} - -/* -** Given table pTab, return a list of all the triggers attached to -** the table. The list is connected by Trigger.pNext pointers. -** -** All of the triggers on pTab that are in the same database as pTab -** are already attached to pTab->pTrigger. But there might be additional -** triggers on pTab in the TEMP schema. This routine prepends all -** TEMP triggers on pTab to the beginning of the pTab->pTrigger list -** and returns the combined list. -** -** To state it another way: This routine returns a list of all triggers -** that fire off of pTab. The list will include any TEMP triggers on -** pTab as well as the triggers lised in pTab->pTrigger. -*/ -SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ - Schema * const pTmpSchema = pParse->db->aDb[1].pSchema; - Trigger *pList = 0; /* List of triggers to return */ - - if( pParse->disableTriggers ){ - return 0; - } - - if( pTmpSchema!=pTab->pSchema ){ - HashElem *p; - assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) ); - for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){ - Trigger *pTrig = (Trigger *)sqliteHashData(p); - if( pTrig->pTabSchema==pTab->pSchema - && 0==sqlite3StrICmp(pTrig->table, pTab->zName) - ){ - pTrig->pNext = (pList ? pList : pTab->pTrigger); - pList = pTrig; - } - } - } - - return (pList ? pList : pTab->pTrigger); -} - -/* -** This is called by the parser when it sees a CREATE TRIGGER statement -** up to the point of the BEGIN before the trigger actions. A Trigger -** structure is generated based on the information available and stored -** in pParse->pNewTrigger. After the trigger actions have been parsed, the -** sqlite3FinishTrigger() function is called to complete the trigger -** construction process. -*/ -SQLITE_PRIVATE void sqlite3BeginTrigger( - Parse *pParse, /* The parse context of the CREATE TRIGGER statement */ - Token *pName1, /* The name of the trigger */ - Token *pName2, /* The name of the trigger */ - int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */ - int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */ - IdList *pColumns, /* column list if this is an UPDATE OF trigger */ - SrcList *pTableName,/* The name of the table/view the trigger applies to */ - Expr *pWhen, /* WHEN clause */ - int isTemp, /* True if the TEMPORARY keyword is present */ - int noErr /* Suppress errors if the trigger already exists */ -){ - Trigger *pTrigger = 0; /* The new trigger */ - Table *pTab; /* Table that the trigger fires off of */ - char *zName = 0; /* Name of the trigger */ - sqlite3 *db = pParse->db; /* The database connection */ - int iDb; /* The database to store the trigger in */ - Token *pName; /* The unqualified db name */ - DbFixer sFix; /* State vector for the DB fixer */ - - assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */ - assert( pName2!=0 ); - assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE ); - assert( op>0 && op<0xff ); - if( isTemp ){ - /* If TEMP was specified, then the trigger name may not be qualified. */ - if( pName2->n>0 ){ - sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name"); - goto trigger_cleanup; - } - iDb = 1; - pName = pName1; - }else{ - /* Figure out the db that the trigger will be created in */ - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); - if( iDb<0 ){ - goto trigger_cleanup; - } - } - if( !pTableName || db->mallocFailed ){ - goto trigger_cleanup; - } - - /* A long-standing parser bug is that this syntax was allowed: - ** - ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab .... - ** ^^^^^^^^ - ** - ** To maintain backwards compatibility, ignore the database - ** name on pTableName if we are reparsing out of the schema table - */ - if( db->init.busy && iDb!=1 ){ - sqlite3DbFree(db, pTableName->a[0].zDatabase); - pTableName->a[0].zDatabase = 0; - } - - /* If the trigger name was unqualified, and the table is a temp table, - ** then set iDb to 1 to create the trigger in the temporary database. - ** If sqlite3SrcListLookup() returns 0, indicating the table does not - ** exist, the error is caught by the block below. - */ - pTab = sqlite3SrcListLookup(pParse, pTableName); - if( db->init.busy==0 && pName2->n==0 && pTab - && pTab->pSchema==db->aDb[1].pSchema ){ - iDb = 1; - } - - /* Ensure the table name matches database name and that the table exists */ - if( db->mallocFailed ) goto trigger_cleanup; - assert( pTableName->nSrc==1 ); - sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName); - if( sqlite3FixSrcList(&sFix, pTableName) ){ - goto trigger_cleanup; - } - pTab = sqlite3SrcListLookup(pParse, pTableName); - if( !pTab ){ - /* The table does not exist. */ - if( db->init.iDb==1 ){ - /* Ticket #3810. - ** Normally, whenever a table is dropped, all associated triggers are - ** dropped too. But if a TEMP trigger is created on a non-TEMP table - ** and the table is dropped by a different database connection, the - ** trigger is not visible to the database connection that does the - ** drop so the trigger cannot be dropped. This results in an - ** "orphaned trigger" - a trigger whose associated table is missing. - */ - db->init.orphanTrigger = 1; - } - goto trigger_cleanup; - } - if( IsVirtual(pTab) ){ - sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables"); - goto trigger_cleanup; - } - - /* Check that the trigger name is not reserved and that no trigger of the - ** specified name exists */ - zName = sqlite3NameFromToken(db, pName); - if( zName==0 ){ - assert( db->mallocFailed ); - goto trigger_cleanup; - } - if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){ - goto trigger_cleanup; - } - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - if( !IN_RENAME_OBJECT ){ - if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){ - if( !noErr ){ - sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); - }else{ - assert( !db->init.busy ); - sqlite3CodeVerifySchema(pParse, iDb); - } - goto trigger_cleanup; - } - } - - /* Do not create a trigger on a system table */ - if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ - sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); - goto trigger_cleanup; - } - - /* INSTEAD of triggers are only for views and views only support INSTEAD - ** of triggers. - */ - if( pTab->pSelect && tr_tm!=TK_INSTEAD ){ - sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", - (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0); - goto trigger_cleanup; - } - if( !pTab->pSelect && tr_tm==TK_INSTEAD ){ - sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF" - " trigger on table: %S", pTableName, 0); - goto trigger_cleanup; - } - -#ifndef SQLITE_OMIT_AUTHORIZATION - if( !IN_RENAME_OBJECT ){ - int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); - int code = SQLITE_CREATE_TRIGGER; - const char *zDb = db->aDb[iTabDb].zDbSName; - const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb; - if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER; - if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){ - goto trigger_cleanup; - } - if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){ - goto trigger_cleanup; - } - } -#endif - - /* INSTEAD OF triggers can only appear on views and BEFORE triggers - ** cannot appear on views. So we might as well translate every - ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code - ** elsewhere. - */ - if (tr_tm == TK_INSTEAD){ - tr_tm = TK_BEFORE; - } - - /* Build the Trigger object */ - pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger)); - if( pTrigger==0 ) goto trigger_cleanup; - pTrigger->zName = zName; - zName = 0; - pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName); - pTrigger->pSchema = db->aDb[iDb].pSchema; - pTrigger->pTabSchema = pTab->pSchema; - pTrigger->op = (u8)op; - pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER; - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName); - pTrigger->pWhen = pWhen; - pWhen = 0; - }else{ - pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); - } - pTrigger->pColumns = pColumns; - pColumns = 0; - assert( pParse->pNewTrigger==0 ); - pParse->pNewTrigger = pTrigger; - -trigger_cleanup: - sqlite3DbFree(db, zName); - sqlite3SrcListDelete(db, pTableName); - sqlite3IdListDelete(db, pColumns); - sqlite3ExprDelete(db, pWhen); - if( !pParse->pNewTrigger ){ - sqlite3DeleteTrigger(db, pTrigger); - }else{ - assert( pParse->pNewTrigger==pTrigger ); - } -} - -/* -** This routine is called after all of the trigger actions have been parsed -** in order to complete the process of building the trigger. -*/ -SQLITE_PRIVATE void sqlite3FinishTrigger( - Parse *pParse, /* Parser context */ - TriggerStep *pStepList, /* The triggered program */ - Token *pAll /* Token that describes the complete CREATE TRIGGER */ -){ - Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */ - char *zName; /* Name of trigger */ - sqlite3 *db = pParse->db; /* The database */ - DbFixer sFix; /* Fixer object */ - int iDb; /* Database containing the trigger */ - Token nameToken; /* Trigger name for error reporting */ - - pParse->pNewTrigger = 0; - if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; - zName = pTrig->zName; - iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); - pTrig->step_list = pStepList; - while( pStepList ){ - pStepList->pTrig = pTrig; - pStepList = pStepList->pNext; - } - sqlite3TokenInit(&nameToken, pTrig->zName); - sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); - if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) - || sqlite3FixExpr(&sFix, pTrig->pWhen) - ){ - goto triggerfinish_cleanup; - } - -#ifndef SQLITE_OMIT_ALTERTABLE - if( IN_RENAME_OBJECT ){ - assert( !db->init.busy ); - pParse->pNewTrigger = pTrig; - pTrig = 0; - }else -#endif - - /* if we are not initializing, - ** build the sqlite_schema entry - */ - if( !db->init.busy ){ - Vdbe *v; - char *z; - - /* Make an entry in the sqlite_schema table */ - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto triggerfinish_cleanup; - sqlite3BeginWriteOperation(pParse, 0, iDb); - z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); - testcase( z==0 ); - sqlite3NestedParse(pParse, - "INSERT INTO %Q." DFLT_SCHEMA_TABLE - " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", - db->aDb[iDb].zDbSName, zName, - pTrig->table, z); - sqlite3DbFree(db, z); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddParseSchemaOp(v, iDb, - sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName)); - } - - if( db->init.busy ){ - Trigger *pLink = pTrig; - Hash *pHash = &db->aDb[iDb].pSchema->trigHash; - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - assert( pLink!=0 ); - pTrig = sqlite3HashInsert(pHash, zName, pTrig); - if( pTrig ){ - sqlite3OomFault(db); - }else if( pLink->pSchema==pLink->pTabSchema ){ - Table *pTab; - pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table); - assert( pTab!=0 ); - pLink->pNext = pTab->pTrigger; - pTab->pTrigger = pLink; - } - } - -triggerfinish_cleanup: - sqlite3DeleteTrigger(db, pTrig); - assert( IN_RENAME_OBJECT || !pParse->pNewTrigger ); - sqlite3DeleteTriggerStep(db, pStepList); -} - -/* -** Duplicate a range of text from an SQL statement, then convert all -** whitespace characters into ordinary space characters. -*/ -static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){ - char *z = sqlite3DbSpanDup(db, zStart, zEnd); - int i; - if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' '; - return z; -} - -/* -** Turn a SELECT statement (that the pSelect parameter points to) into -** a trigger step. Return a pointer to a TriggerStep structure. -** -** The parser calls this routine when it finds a SELECT statement in -** body of a TRIGGER. -*/ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep( - sqlite3 *db, /* Database connection */ - Select *pSelect, /* The SELECT statement */ - const char *zStart, /* Start of SQL text */ - const char *zEnd /* End of SQL text */ -){ - TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); - if( pTriggerStep==0 ) { - sqlite3SelectDelete(db, pSelect); - return 0; - } - pTriggerStep->op = TK_SELECT; - pTriggerStep->pSelect = pSelect; - pTriggerStep->orconf = OE_Default; - pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd); - return pTriggerStep; -} - -/* -** Allocate space to hold a new trigger step. The allocated space -** holds both the TriggerStep object and the TriggerStep.target.z string. -** -** If an OOM error occurs, NULL is returned and db->mallocFailed is set. -*/ -static TriggerStep *triggerStepAllocate( - Parse *pParse, /* Parser context */ - u8 op, /* Trigger opcode */ - Token *pName, /* The target name */ - const char *zStart, /* Start of SQL text */ - const char *zEnd /* End of SQL text */ -){ - sqlite3 *db = pParse->db; - TriggerStep *pTriggerStep; - - pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1); - if( pTriggerStep ){ - char *z = (char*)&pTriggerStep[1]; - memcpy(z, pName->z, pName->n); - sqlite3Dequote(z); - pTriggerStep->zTarget = z; - pTriggerStep->op = op; - pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd); - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName); - } - } - return pTriggerStep; -} - -/* -** Build a trigger step out of an INSERT statement. Return a pointer -** to the new trigger step. -** -** The parser calls this routine when it sees an INSERT inside the -** body of a trigger. -*/ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( - Parse *pParse, /* Parser */ - Token *pTableName, /* Name of the table into which we insert */ - IdList *pColumn, /* List of columns in pTableName to insert into */ - Select *pSelect, /* A SELECT statement that supplies values */ - u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ - Upsert *pUpsert, /* ON CONFLICT clauses for upsert */ - const char *zStart, /* Start of SQL text */ - const char *zEnd /* End of SQL text */ -){ - sqlite3 *db = pParse->db; - TriggerStep *pTriggerStep; - - assert(pSelect != 0 || db->mallocFailed); - - pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd); - if( pTriggerStep ){ - if( IN_RENAME_OBJECT ){ - pTriggerStep->pSelect = pSelect; - pSelect = 0; - }else{ - pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); - } - pTriggerStep->pIdList = pColumn; - pTriggerStep->pUpsert = pUpsert; - pTriggerStep->orconf = orconf; - if( pUpsert ){ - sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget); - } - }else{ - testcase( pColumn ); - sqlite3IdListDelete(db, pColumn); - testcase( pUpsert ); - sqlite3UpsertDelete(db, pUpsert); - } - sqlite3SelectDelete(db, pSelect); - - return pTriggerStep; -} - -/* -** Construct a trigger step that implements an UPDATE statement and return -** a pointer to that trigger step. The parser calls this routine when it -** sees an UPDATE statement inside the body of a CREATE TRIGGER. -*/ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( - Parse *pParse, /* Parser */ - Token *pTableName, /* Name of the table to be updated */ - SrcList *pFrom, - ExprList *pEList, /* The SET clause: list of column and new values */ - Expr *pWhere, /* The WHERE clause */ - u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */ - const char *zStart, /* Start of SQL text */ - const char *zEnd /* End of SQL text */ -){ - sqlite3 *db = pParse->db; - TriggerStep *pTriggerStep; - - pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd); - if( pTriggerStep ){ - if( IN_RENAME_OBJECT ){ - pTriggerStep->pExprList = pEList; - pTriggerStep->pWhere = pWhere; - pTriggerStep->pFrom = pFrom; - pEList = 0; - pWhere = 0; - pFrom = 0; - }else{ - pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); - pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); - pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE); - } - pTriggerStep->orconf = orconf; - } - sqlite3ExprListDelete(db, pEList); - sqlite3ExprDelete(db, pWhere); - sqlite3SrcListDelete(db, pFrom); - return pTriggerStep; -} - -/* -** Construct a trigger step that implements a DELETE statement and return -** a pointer to that trigger step. The parser calls this routine when it -** sees a DELETE statement inside the body of a CREATE TRIGGER. -*/ -SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep( - Parse *pParse, /* Parser */ - Token *pTableName, /* The table from which rows are deleted */ - Expr *pWhere, /* The WHERE clause */ - const char *zStart, /* Start of SQL text */ - const char *zEnd /* End of SQL text */ -){ - sqlite3 *db = pParse->db; - TriggerStep *pTriggerStep; - - pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd); - if( pTriggerStep ){ - if( IN_RENAME_OBJECT ){ - pTriggerStep->pWhere = pWhere; - pWhere = 0; - }else{ - pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); - } - pTriggerStep->orconf = OE_Default; - } - sqlite3ExprDelete(db, pWhere); - return pTriggerStep; -} - -/* -** Recursively delete a Trigger structure -*/ -SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){ - if( pTrigger==0 ) return; - sqlite3DeleteTriggerStep(db, pTrigger->step_list); - sqlite3DbFree(db, pTrigger->zName); - sqlite3DbFree(db, pTrigger->table); - sqlite3ExprDelete(db, pTrigger->pWhen); - sqlite3IdListDelete(db, pTrigger->pColumns); - sqlite3DbFree(db, pTrigger); -} - -/* -** This function is called to drop a trigger from the database schema. -** -** This may be called directly from the parser and therefore identifies -** the trigger by name. The sqlite3DropTriggerPtr() routine does the -** same job as this routine except it takes a pointer to the trigger -** instead of the trigger name. -**/ -SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){ - Trigger *pTrigger = 0; - int i; - const char *zDb; - const char *zName; - sqlite3 *db = pParse->db; - - if( db->mallocFailed ) goto drop_trigger_cleanup; - if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ - goto drop_trigger_cleanup; - } - - assert( pName->nSrc==1 ); - zDb = pName->a[0].zDatabase; - zName = pName->a[0].zName; - assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) ); - for(i=OMIT_TEMPDB; inDb; i++){ - int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ - if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue; - assert( sqlite3SchemaMutexHeld(db, j, 0) ); - pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName); - if( pTrigger ) break; - } - if( !pTrigger ){ - if( !noErr ){ - sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0); - }else{ - sqlite3CodeVerifyNamedSchema(pParse, zDb); - } - pParse->checkSchema = 1; - goto drop_trigger_cleanup; - } - sqlite3DropTriggerPtr(pParse, pTrigger); - -drop_trigger_cleanup: - sqlite3SrcListDelete(db, pName); -} - -/* -** Return a pointer to the Table structure for the table that a trigger -** is set on. -*/ -static Table *tableOfTrigger(Trigger *pTrigger){ - return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table); -} - - -/* -** Drop a trigger given a pointer to that trigger. -*/ -SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ - Table *pTable; - Vdbe *v; - sqlite3 *db = pParse->db; - int iDb; - - iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema); - assert( iDb>=0 && iDbnDb ); - pTable = tableOfTrigger(pTrigger); - assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 ); -#ifndef SQLITE_OMIT_AUTHORIZATION - if( pTable ){ - int code = SQLITE_DROP_TRIGGER; - const char *zDb = db->aDb[iDb].zDbSName; - const char *zTab = SCHEMA_TABLE(iDb); - if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER; - if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) || - sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ - return; - } - } -#endif - - /* Generate code to destroy the database record of the trigger. - */ - if( (v = sqlite3GetVdbe(pParse))!=0 ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'", - db->aDb[iDb].zDbSName, pTrigger->zName - ); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0); - } -} - -/* -** Remove a trigger from the hash tables of the sqlite* pointer. -*/ -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){ - Trigger *pTrigger; - Hash *pHash; - - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - pHash = &(db->aDb[iDb].pSchema->trigHash); - pTrigger = sqlite3HashInsert(pHash, zName, 0); - if( ALWAYS(pTrigger) ){ - if( pTrigger->pSchema==pTrigger->pTabSchema ){ - Table *pTab = tableOfTrigger(pTrigger); - if( pTab ){ - Trigger **pp; - for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){ - if( *pp==pTrigger ){ - *pp = (*pp)->pNext; - break; - } - } - } - } - sqlite3DeleteTrigger(db, pTrigger); - db->mDbFlags |= DBFLAG_SchemaChange; - } -} - -/* -** pEList is the SET clause of an UPDATE statement. Each entry -** in pEList is of the format =. If any of the entries -** in pEList have an which matches an identifier in pIdList, -** then return TRUE. If pIdList==NULL, then it is considered a -** wildcard that matches anything. Likewise if pEList==NULL then -** it matches anything so always return true. Return false only -** if there is no match. -*/ -static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){ - int e; - if( pIdList==0 || NEVER(pEList==0) ) return 1; - for(e=0; enExpr; e++){ - if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1; - } - return 0; -} - -/* -** Return a list of all triggers on table pTab if there exists at least -** one trigger that must be fired when an operation of type 'op' is -** performed on the table, and, if that operation is an UPDATE, if at -** least one of the columns in pChanges is being modified. -*/ -SQLITE_PRIVATE Trigger *sqlite3TriggersExist( - Parse *pParse, /* Parse context */ - Table *pTab, /* The table the contains the triggers */ - int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */ - ExprList *pChanges, /* Columns that change in an UPDATE statement */ - int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ -){ - int mask = 0; - Trigger *pList = 0; - Trigger *p; - - if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){ - pList = sqlite3TriggerList(pParse, pTab); - } - assert( pList==0 || IsVirtual(pTab)==0 ); - for(p=pList; p; p=p->pNext){ - if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){ - mask |= p->tr_tm; - } - } - if( pMask ){ - *pMask = mask; - } - return (mask ? pList : 0); -} - -/* -** Convert the pStep->zTarget string into a SrcList and return a pointer -** to that SrcList. -** -** This routine adds a specific database name, if needed, to the target when -** forming the SrcList. This prevents a trigger in one database from -** referring to a target in another database. An exception is when the -** trigger is in TEMP in which case it can refer to any other database it -** wants. -*/ -SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc( - Parse *pParse, /* The parsing context */ - TriggerStep *pStep /* The trigger containing the target token */ -){ - sqlite3 *db = pParse->db; - SrcList *pSrc; /* SrcList to be returned */ - char *zName = sqlite3DbStrDup(db, pStep->zTarget); - pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); - assert( pSrc==0 || pSrc->nSrc==1 ); - assert( zName || pSrc==0 ); - if( pSrc ){ - Schema *pSchema = pStep->pTrig->pSchema; - pSrc->a[0].zName = zName; - if( pSchema!=db->aDb[1].pSchema ){ - pSrc->a[0].pSchema = pSchema; - } - if( pStep->pFrom ){ - SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0); - pSrc = sqlite3SrcListAppendList(pParse, pSrc, pDup); - } - }else{ - sqlite3DbFree(db, zName); - } - return pSrc; -} - -/* -** Generate VDBE code for the statements inside the body of a single -** trigger. -*/ -static int codeTriggerProgram( - Parse *pParse, /* The parser context */ - TriggerStep *pStepList, /* List of statements inside the trigger body */ - int orconf /* Conflict algorithm. (OE_Abort, etc) */ -){ - TriggerStep *pStep; - Vdbe *v = pParse->pVdbe; - sqlite3 *db = pParse->db; - - assert( pParse->pTriggerTab && pParse->pToplevel ); - assert( pStepList ); - assert( v!=0 ); - for(pStep=pStepList; pStep; pStep=pStep->pNext){ - /* Figure out the ON CONFLICT policy that will be used for this step - ** of the trigger program. If the statement that caused this trigger - ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use - ** the ON CONFLICT policy that was specified as part of the trigger - ** step statement. Example: - ** - ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN; - ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b); - ** END; - ** - ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy - ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy - */ - pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf; - assert( pParse->okConstFactor==0 ); - -#ifndef SQLITE_OMIT_TRACE - if( pStep->zSpan ){ - sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0, - sqlite3MPrintf(db, "-- %s", pStep->zSpan), - P4_DYNAMIC); - } -#endif - - switch( pStep->op ){ - case TK_UPDATE: { - sqlite3Update(pParse, - sqlite3TriggerStepSrc(pParse, pStep), - sqlite3ExprListDup(db, pStep->pExprList, 0), - sqlite3ExprDup(db, pStep->pWhere, 0), - pParse->eOrconf, 0, 0, 0 - ); - break; - } - case TK_INSERT: { - sqlite3Insert(pParse, - sqlite3TriggerStepSrc(pParse, pStep), - sqlite3SelectDup(db, pStep->pSelect, 0), - sqlite3IdListDup(db, pStep->pIdList), - pParse->eOrconf, - sqlite3UpsertDup(db, pStep->pUpsert) - ); - break; - } - case TK_DELETE: { - sqlite3DeleteFrom(pParse, - sqlite3TriggerStepSrc(pParse, pStep), - sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0 - ); - break; - } - default: assert( pStep->op==TK_SELECT ); { - SelectDest sDest; - Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0); - sqlite3SelectDestInit(&sDest, SRT_Discard, 0); - sqlite3Select(pParse, pSelect, &sDest); - sqlite3SelectDelete(db, pSelect); - break; - } - } - if( pStep->op!=TK_SELECT ){ - sqlite3VdbeAddOp0(v, OP_ResetCount); - } - } - - return 0; -} - -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS -/* -** This function is used to add VdbeComment() annotations to a VDBE -** program. It is not used in production code, only for debugging. -*/ -static const char *onErrorText(int onError){ - switch( onError ){ - case OE_Abort: return "abort"; - case OE_Rollback: return "rollback"; - case OE_Fail: return "fail"; - case OE_Replace: return "replace"; - case OE_Ignore: return "ignore"; - case OE_Default: return "default"; - } - return "n/a"; -} -#endif - -/* -** Parse context structure pFrom has just been used to create a sub-vdbe -** (trigger program). If an error has occurred, transfer error information -** from pFrom to pTo. -*/ -static void transferParseError(Parse *pTo, Parse *pFrom){ - assert( pFrom->zErrMsg==0 || pFrom->nErr ); - assert( pTo->zErrMsg==0 || pTo->nErr ); - if( pTo->nErr==0 ){ - pTo->zErrMsg = pFrom->zErrMsg; - pTo->nErr = pFrom->nErr; - pTo->rc = pFrom->rc; - }else{ - sqlite3DbFree(pFrom->db, pFrom->zErrMsg); - } -} - -/* -** Create and populate a new TriggerPrg object with a sub-program -** implementing trigger pTrigger with ON CONFLICT policy orconf. -*/ -static TriggerPrg *codeRowTrigger( - Parse *pParse, /* Current parse context */ - Trigger *pTrigger, /* Trigger to code */ - Table *pTab, /* The table pTrigger is attached to */ - int orconf /* ON CONFLICT policy to code trigger program with */ -){ - Parse *pTop = sqlite3ParseToplevel(pParse); - sqlite3 *db = pParse->db; /* Database handle */ - TriggerPrg *pPrg; /* Value to return */ - Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */ - Vdbe *v; /* Temporary VM */ - NameContext sNC; /* Name context for sub-vdbe */ - SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */ - Parse *pSubParse; /* Parse context for sub-vdbe */ - int iEndTrigger = 0; /* Label to jump to if WHEN is false */ - - assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); - assert( pTop->pVdbe ); - - /* Allocate the TriggerPrg and SubProgram objects. To ensure that they - ** are freed if an error occurs, link them into the Parse.pTriggerPrg - ** list of the top-level Parse object sooner rather than later. */ - pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg)); - if( !pPrg ) return 0; - pPrg->pNext = pTop->pTriggerPrg; - pTop->pTriggerPrg = pPrg; - pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram)); - if( !pProgram ) return 0; - sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram); - pPrg->pTrigger = pTrigger; - pPrg->orconf = orconf; - pPrg->aColmask[0] = 0xffffffff; - pPrg->aColmask[1] = 0xffffffff; - - /* Allocate and populate a new Parse context to use for coding the - ** trigger sub-program. */ - pSubParse = sqlite3StackAllocZero(db, sizeof(Parse)); - if( !pSubParse ) return 0; - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pSubParse; - pSubParse->db = db; - pSubParse->pTriggerTab = pTab; - pSubParse->pToplevel = pTop; - pSubParse->zAuthContext = pTrigger->zName; - pSubParse->eTriggerOp = pTrigger->op; - pSubParse->nQueryLoop = pParse->nQueryLoop; - pSubParse->disableVtab = pParse->disableVtab; - - v = sqlite3GetVdbe(pSubParse); - if( v ){ - VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", - pTrigger->zName, onErrorText(orconf), - (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"), - (pTrigger->op==TK_UPDATE ? "UPDATE" : ""), - (pTrigger->op==TK_INSERT ? "INSERT" : ""), - (pTrigger->op==TK_DELETE ? "DELETE" : ""), - pTab->zName - )); -#ifndef SQLITE_OMIT_TRACE - if( pTrigger->zName ){ - sqlite3VdbeChangeP4(v, -1, - sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC - ); - } -#endif - - /* If one was specified, code the WHEN clause. If it evaluates to false - ** (or NULL) the sub-vdbe is immediately halted by jumping to the - ** OP_Halt inserted at the end of the program. */ - if( pTrigger->pWhen ){ - pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0); - if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) - && db->mallocFailed==0 - ){ - iEndTrigger = sqlite3VdbeMakeLabel(pSubParse); - sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL); - } - sqlite3ExprDelete(db, pWhen); - } - - /* Code the trigger program into the sub-vdbe. */ - codeTriggerProgram(pSubParse, pTrigger->step_list, orconf); - - /* Insert an OP_Halt at the end of the sub-program. */ - if( iEndTrigger ){ - sqlite3VdbeResolveLabel(v, iEndTrigger); - } - sqlite3VdbeAddOp0(v, OP_Halt); - VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf))); - - transferParseError(pParse, pSubParse); - if( db->mallocFailed==0 && pParse->nErr==0 ){ - pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg); - } - pProgram->nMem = pSubParse->nMem; - pProgram->nCsr = pSubParse->nTab; - pProgram->token = (void *)pTrigger; - pPrg->aColmask[0] = pSubParse->oldmask; - pPrg->aColmask[1] = pSubParse->newmask; - sqlite3VdbeDelete(v); - } - - assert( !pSubParse->pAinc && !pSubParse->pZombieTab ); - assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg ); - sqlite3ParserReset(pSubParse); - sqlite3StackFree(db, pSubParse); - - return pPrg; -} - -/* -** Return a pointer to a TriggerPrg object containing the sub-program for -** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such -** TriggerPrg object exists, a new object is allocated and populated before -** being returned. -*/ -static TriggerPrg *getRowTrigger( - Parse *pParse, /* Current parse context */ - Trigger *pTrigger, /* Trigger to code */ - Table *pTab, /* The table trigger pTrigger is attached to */ - int orconf /* ON CONFLICT algorithm. */ -){ - Parse *pRoot = sqlite3ParseToplevel(pParse); - TriggerPrg *pPrg; - - assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); - - /* It may be that this trigger has already been coded (or is in the - ** process of being coded). If this is the case, then an entry with - ** a matching TriggerPrg.pTrigger field will be present somewhere - ** in the Parse.pTriggerPrg list. Search for such an entry. */ - for(pPrg=pRoot->pTriggerPrg; - pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); - pPrg=pPrg->pNext - ); - - /* If an existing TriggerPrg could not be located, create a new one. */ - if( !pPrg ){ - pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf); - } - - return pPrg; -} - -/* -** Generate code for the trigger program associated with trigger p on -** table pTab. The reg, orconf and ignoreJump parameters passed to this -** function are the same as those described in the header function for -** sqlite3CodeRowTrigger() -*/ -SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( - Parse *pParse, /* Parse context */ - Trigger *p, /* Trigger to code */ - Table *pTab, /* The table to code triggers from */ - int reg, /* Reg array containing OLD.* and NEW.* values */ - int orconf, /* ON CONFLICT policy */ - int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ -){ - Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */ - TriggerPrg *pPrg; - pPrg = getRowTrigger(pParse, p, pTab, orconf); - assert( pPrg || pParse->nErr || pParse->db->mallocFailed ); - - /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program - ** is a pointer to the sub-vdbe containing the trigger program. */ - if( pPrg ){ - int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers)); - - sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem, - (const char *)pPrg->pProgram, P4_SUBPROGRAM); - VdbeComment( - (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf))); - - /* Set the P5 operand of the OP_Program instruction to non-zero if - ** recursive invocation of this trigger program is disallowed. Recursive - ** invocation is disallowed if (a) the sub-program is really a trigger, - ** not a foreign key action, and (b) the flag to enable recursive triggers - ** is clear. */ - sqlite3VdbeChangeP5(v, (u8)bRecursive); - } -} - -/* -** This is called to code the required FOR EACH ROW triggers for an operation -** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE) -** is given by the op parameter. The tr_tm parameter determines whether the -** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then -** parameter pChanges is passed the list of columns being modified. -** -** If there are no triggers that fire at the specified time for the specified -** operation on pTab, this function is a no-op. -** -** The reg argument is the address of the first in an array of registers -** that contain the values substituted for the new.* and old.* references -** in the trigger program. If N is the number of columns in table pTab -** (a copy of pTab->nCol), then registers are populated as follows: -** -** Register Contains -** ------------------------------------------------------ -** reg+0 OLD.rowid -** reg+1 OLD.* value of left-most column of pTab -** ... ... -** reg+N OLD.* value of right-most column of pTab -** reg+N+1 NEW.rowid -** reg+N+2 OLD.* value of left-most column of pTab -** ... ... -** reg+N+N+1 NEW.* value of right-most column of pTab -** -** For ON DELETE triggers, the registers containing the NEW.* values will -** never be accessed by the trigger program, so they are not allocated or -** populated by the caller (there is no data to populate them with anyway). -** Similarly, for ON INSERT triggers the values stored in the OLD.* registers -** are never accessed, and so are not allocated by the caller. So, for an -** ON INSERT trigger, the value passed to this function as parameter reg -** is not a readable register, although registers (reg+N) through -** (reg+N+N+1) are. -** -** Parameter orconf is the default conflict resolution algorithm for the -** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump -** is the instruction that control should jump to if a trigger program -** raises an IGNORE exception. -*/ -SQLITE_PRIVATE void sqlite3CodeRowTrigger( - Parse *pParse, /* Parse context */ - Trigger *pTrigger, /* List of triggers on table pTab */ - int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ - ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ - int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ - Table *pTab, /* The table to code triggers from */ - int reg, /* The first in an array of registers (see above) */ - int orconf, /* ON CONFLICT policy */ - int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ -){ - Trigger *p; /* Used to iterate through pTrigger list */ - - assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE ); - assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER ); - assert( (op==TK_UPDATE)==(pChanges!=0) ); - - for(p=pTrigger; p; p=p->pNext){ - - /* Sanity checking: The schema for the trigger and for the table are - ** always defined. The trigger must be in the same schema as the table - ** or else it must be a TEMP trigger. */ - assert( p->pSchema!=0 ); - assert( p->pTabSchema!=0 ); - assert( p->pSchema==p->pTabSchema - || p->pSchema==pParse->db->aDb[1].pSchema ); - - /* Determine whether we should code this trigger */ - if( p->op==op - && p->tr_tm==tr_tm - && checkColumnOverlap(p->pColumns, pChanges) - ){ - sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump); - } - } -} - -/* -** Triggers may access values stored in the old.* or new.* pseudo-table. -** This function returns a 32-bit bitmask indicating which columns of the -** old.* or new.* tables actually are used by triggers. This information -** may be used by the caller, for example, to avoid having to load the entire -** old.* record into memory when executing an UPDATE or DELETE command. -** -** Bit 0 of the returned mask is set if the left-most column of the -** table may be accessed using an [old|new].reference. Bit 1 is set if -** the second leftmost column value is required, and so on. If there -** are more than 32 columns in the table, and at least one of the columns -** with an index greater than 32 may be accessed, 0xffffffff is returned. -** -** It is not possible to determine if the old.rowid or new.rowid column is -** accessed by triggers. The caller must always assume that it is. -** -** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned -** applies to the old.* table. If 1, the new.* table. -** -** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE -** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only -** included in the returned mask if the TRIGGER_BEFORE bit is set in the -** tr_tm parameter. Similarly, values accessed by AFTER triggers are only -** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm. -*/ -SQLITE_PRIVATE u32 sqlite3TriggerColmask( - Parse *pParse, /* Parse context */ - Trigger *pTrigger, /* List of triggers on table pTab */ - ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ - int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */ - int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ - Table *pTab, /* The table to code triggers from */ - int orconf /* Default ON CONFLICT policy for trigger steps */ -){ - const int op = pChanges ? TK_UPDATE : TK_DELETE; - u32 mask = 0; - Trigger *p; - - assert( isNew==1 || isNew==0 ); - for(p=pTrigger; p; p=p->pNext){ - if( p->op==op && (tr_tm&p->tr_tm) - && checkColumnOverlap(p->pColumns,pChanges) - ){ - TriggerPrg *pPrg; - pPrg = getRowTrigger(pParse, p, pTab, orconf); - if( pPrg ){ - mask |= pPrg->aColmask[isNew]; - } - } - } - - return mask; -} - -#endif /* !defined(SQLITE_OMIT_TRIGGER) */ - -/************** End of trigger.c *********************************************/ -/************** Begin file update.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 C code routines that are called by the parser -** to handle UPDATE statements. -*/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* Forward declaration */ -static void updateVirtualTable( - Parse *pParse, /* The parsing context */ - SrcList *pSrc, /* The virtual table to be modified */ - Table *pTab, /* The virtual table */ - ExprList *pChanges, /* The columns to change in the UPDATE statement */ - Expr *pRowidExpr, /* Expression used to recompute the rowid */ - int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ - Expr *pWhere, /* WHERE clause of the UPDATE statement */ - int onError /* ON CONFLICT strategy */ -); -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -/* -** The most recently coded instruction was an OP_Column to retrieve the -** i-th column of table pTab. This routine sets the P4 parameter of the -** OP_Column to the default value, if any. -** -** The default value of a column is specified by a DEFAULT clause in the -** column definition. This was either supplied by the user when the table -** was created, or added later to the table definition by an ALTER TABLE -** command. If the latter, then the row-records in the table btree on disk -** may not contain a value for the column and the default value, taken -** from the P4 parameter of the OP_Column instruction, is returned instead. -** If the former, then all row-records are guaranteed to include a value -** for the column and the P4 value is not required. -** -** Column definitions created by an ALTER TABLE command may only have -** literal default values specified: a number, null or a string. (If a more -** complicated default expression value was provided, it is evaluated -** when the ALTER TABLE is executed and one of the literal values written -** into the sqlite_schema table.) -** -** Therefore, the P4 parameter is only required if the default value for -** the column is a literal number, string or null. The sqlite3ValueFromExpr() -** function is capable of transforming these types of expressions into -** sqlite3_value objects. -** -** If column as REAL affinity and the table is an ordinary b-tree table -** (not a virtual table) then the value might have been stored as an -** integer. In that case, add an OP_RealAffinity opcode to make sure -** it has been converted into REAL. -*/ -SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ - assert( pTab!=0 ); - if( !pTab->pSelect ){ - sqlite3_value *pValue = 0; - u8 enc = ENC(sqlite3VdbeDb(v)); - Column *pCol = &pTab->aCol[i]; - VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); - assert( inCol ); - sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, - pCol->affinity, &pValue); - if( pValue ){ - sqlite3VdbeAppendP4(v, pValue, P4_MEM); - } - } -#ifndef SQLITE_OMIT_FLOATING_POINT - if( pTab->aCol[i].affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); - } -#endif -} - -/* -** Check to see if column iCol of index pIdx references any of the -** columns defined by aXRef and chngRowid. Return true if it does -** and false if not. This is an optimization. False-positives are a -** performance degradation, but false-negatives can result in a corrupt -** index and incorrect answers. -** -** aXRef[j] will be non-negative if column j of the original table is -** being updated. chngRowid will be true if the rowid of the table is -** being updated. -*/ -static int indexColumnIsBeingUpdated( - Index *pIdx, /* The index to check */ - int iCol, /* Which column of the index to check */ - int *aXRef, /* aXRef[j]>=0 if column j is being updated */ - int chngRowid /* true if the rowid is being updated */ -){ - i16 iIdxCol = pIdx->aiColumn[iCol]; - assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */ - if( iIdxCol>=0 ){ - return aXRef[iIdxCol]>=0; - } - assert( iIdxCol==XN_EXPR ); - assert( pIdx->aColExpr!=0 ); - assert( pIdx->aColExpr->a[iCol].pExpr!=0 ); - return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr, - aXRef,chngRowid); -} - -/* -** Check to see if index pIdx is a partial index whose conditional -** expression might change values due to an UPDATE. Return true if -** the index is subject to change and false if the index is guaranteed -** to be unchanged. This is an optimization. False-positives are a -** performance degradation, but false-negatives can result in a corrupt -** index and incorrect answers. -** -** aXRef[j] will be non-negative if column j of the original table is -** being updated. chngRowid will be true if the rowid of the table is -** being updated. -*/ -static int indexWhereClauseMightChange( - Index *pIdx, /* The index to check */ - int *aXRef, /* aXRef[j]>=0 if column j is being updated */ - int chngRowid /* true if the rowid is being updated */ -){ - if( pIdx->pPartIdxWhere==0 ) return 0; - return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere, - aXRef, chngRowid); -} - -/* -** Allocate and return a pointer to an expression of type TK_ROW with -** Expr.iColumn set to value (iCol+1). The resolver will modify the -** expression to be a TK_COLUMN reading column iCol of the first -** table in the source-list (pSrc->a[0]). -*/ -static Expr *exprRowColumn(Parse *pParse, int iCol){ - Expr *pRet = sqlite3PExpr(pParse, TK_ROW, 0, 0); - if( pRet ) pRet->iColumn = iCol+1; - return pRet; -} - -/* -** Assuming both the pLimit and pOrderBy parameters are NULL, this function -** generates VM code to run the query: -** -** SELECT , pChanges FROM pTabList WHERE pWhere -** -** and write the results to the ephemeral table already opened as cursor -** iEph. None of pChanges, pTabList or pWhere are modified or consumed by -** this function, they must be deleted by the caller. -** -** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view: -** -** SELECT , pChanges FROM pTabList -** WHERE pWhere -** GROUP BY -** ORDER BY pOrderBy LIMIT pLimit -** -** If pTab is a view, the GROUP BY clause is omitted. -** -** Exactly how results are written to table iEph, and exactly what -** the in the query above are is determined by the type -** of table pTabList->a[0].pTab. -** -** If the table is a WITHOUT ROWID table, then argument pPk must be its -** PRIMARY KEY. In this case are the primary key columns -** of the table, in order. The results of the query are written to ephemeral -** table iEph as index keys, using OP_IdxInsert. -** -** If the table is actually a view, then are all columns of -** the view. The results are written to the ephemeral table iEph as records -** with automatically assigned integer keys. -** -** If the table is a virtual or ordinary intkey table, then -** is its rowid. For a virtual table, the results are written to iEph as -** records with automatically assigned integer keys For intkey tables, the -** rowid value in is used as the integer key, and the -** remaining fields make up the table record. -*/ -static void updateFromSelect( - Parse *pParse, /* Parse context */ - int iEph, /* Cursor for open eph. table */ - Index *pPk, /* PK if table 0 is WITHOUT ROWID */ - ExprList *pChanges, /* List of expressions to return */ - SrcList *pTabList, /* List of tables to select from */ - Expr *pWhere, /* WHERE clause for query */ - ExprList *pOrderBy, /* ORDER BY clause */ - Expr *pLimit /* LIMIT clause */ -){ - int i; - SelectDest dest; - Select *pSelect = 0; - ExprList *pList = 0; - ExprList *pGrp = 0; - Expr *pLimit2 = 0; - ExprList *pOrderBy2 = 0; - sqlite3 *db = pParse->db; - Table *pTab = pTabList->a[0].pTab; - SrcList *pSrc; - Expr *pWhere2; - int eDest; - -#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT - if( pOrderBy && pLimit==0 ) { - sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on UPDATE"); - return; - } - pOrderBy2 = sqlite3ExprListDup(db, pOrderBy, 0); - pLimit2 = sqlite3ExprDup(db, pLimit, 0); -#else - UNUSED_PARAMETER(pOrderBy); - UNUSED_PARAMETER(pLimit); -#endif - - pSrc = sqlite3SrcListDup(db, pTabList, 0); - pWhere2 = sqlite3ExprDup(db, pWhere, 0); - - assert( pTabList->nSrc>1 ); - if( pSrc ){ - pSrc->a[0].iCursor = -1; - pSrc->a[0].pTab->nTabRef--; - pSrc->a[0].pTab = 0; - } - if( pPk ){ - for(i=0; inKeyCol; i++){ - Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]); -#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT - if( pLimit ){ - pGrp = sqlite3ExprListAppend(pParse, pGrp, sqlite3ExprDup(db, pNew, 0)); - } -#endif - pList = sqlite3ExprListAppend(pParse, pList, pNew); - } - eDest = SRT_Upfrom; - }else if( pTab->pSelect ){ - for(i=0; inCol; i++){ - pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i)); - } - eDest = SRT_Table; - }else{ - eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom; - pList = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0)); -#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT - if( pLimit ){ - pGrp = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0)); - } -#endif - } - if( ALWAYS(pChanges) ){ - for(i=0; inExpr; i++){ - pList = sqlite3ExprListAppend(pParse, pList, - sqlite3ExprDup(db, pChanges->a[i].pExpr, 0) - ); - } - } - pSelect = sqlite3SelectNew(pParse, pList, - pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UpdateFrom|SF_IncludeHidden, pLimit2 - ); - sqlite3SelectDestInit(&dest, eDest, iEph); - dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1); - sqlite3Select(pParse, pSelect, &dest); - sqlite3SelectDelete(db, pSelect); -} - -/* -** Process an UPDATE statement. -** -** UPDATE OR IGNORE tbl SET a=b, c=d FROM tbl2... WHERE e<5 AND f NOT NULL; -** \_______/ \_/ \______/ \_____/ \________________/ -** onError | pChanges | pWhere -** \_______________________/ -** pTabList -*/ -SQLITE_PRIVATE void sqlite3Update( - Parse *pParse, /* The parser context */ - SrcList *pTabList, /* The table in which we should change things */ - ExprList *pChanges, /* Things to be changed */ - Expr *pWhere, /* The WHERE clause. May be null */ - int onError, /* How to handle constraint errors */ - ExprList *pOrderBy, /* ORDER BY clause. May be null */ - Expr *pLimit, /* LIMIT clause. May be null */ - Upsert *pUpsert /* ON CONFLICT clause, or null */ -){ - int i, j, k; /* Loop counters */ - Table *pTab; /* The table to be updated */ - int addrTop = 0; /* VDBE instruction address of the start of the loop */ - WhereInfo *pWInfo = 0; /* Information about the WHERE clause */ - Vdbe *v; /* The virtual database engine */ - Index *pIdx; /* For looping over indices */ - Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */ - int nIdx; /* Number of indices that need updating */ - int nAllIdx; /* Total number of indexes */ - int iBaseCur; /* Base cursor number */ - int iDataCur; /* Cursor for the canonical data btree */ - int iIdxCur; /* Cursor for the first index */ - sqlite3 *db; /* The database structure */ - int *aRegIdx = 0; /* Registers for to each index and the main table */ - int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the - ** an expression for the i-th column of the table. - ** aXRef[i]==-1 if the i-th column is not changed. */ - u8 *aToOpen; /* 1 for tables and indices to be opened */ - u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */ - u8 chngRowid; /* Rowid changed in a normal table */ - u8 chngKey; /* Either chngPk or chngRowid */ - Expr *pRowidExpr = 0; /* Expression defining the new record number */ - int iRowidExpr = -1; /* Index of "rowid=" (or IPK) assignment in pChanges */ - AuthContext sContext; /* The authorization context */ - NameContext sNC; /* The name-context to resolve expressions in */ - int iDb; /* Database containing the table being updated */ - int eOnePass; /* ONEPASS_XXX value from where.c */ - int hasFK; /* True if foreign key processing is required */ - int labelBreak; /* Jump here to break out of UPDATE loop */ - int labelContinue; /* Jump here to continue next step of UPDATE loop */ - int flags; /* Flags for sqlite3WhereBegin() */ - -#ifndef SQLITE_OMIT_TRIGGER - int isView; /* True when updating a view (INSTEAD OF trigger) */ - Trigger *pTrigger; /* List of triggers on pTab, if required */ - int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ -#endif - int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ - int iEph = 0; /* Ephemeral table holding all primary key values */ - int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */ - int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */ - int addrOpen = 0; /* Address of OP_OpenEphemeral */ - int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */ - i16 nPk = 0; /* Number of components of the PRIMARY KEY */ - int bReplace = 0; /* True if REPLACE conflict resolution might happen */ - int bFinishSeek = 1; /* The OP_FinishSeek opcode is needed */ - int nChangeFrom = 0; /* If there is a FROM, pChanges->nExpr, else 0 */ - - /* Register Allocations */ - int regRowCount = 0; /* A count of rows changed */ - int regOldRowid = 0; /* The old rowid */ - int regNewRowid = 0; /* The new rowid */ - int regNew = 0; /* Content of the NEW.* table in triggers */ - int regOld = 0; /* Content of OLD.* table in triggers */ - int regRowSet = 0; /* Rowset of rows to be updated */ - int regKey = 0; /* composite PRIMARY KEY value */ - - memset(&sContext, 0, sizeof(sContext)); - db = pParse->db; - if( pParse->nErr || db->mallocFailed ){ - goto update_cleanup; - } - - /* Locate the table which we want to update. - */ - pTab = sqlite3SrcListLookup(pParse, pTabList); - if( pTab==0 ) goto update_cleanup; - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - - /* Figure out if we have any triggers and if the table being - ** updated is a view. - */ -#ifndef SQLITE_OMIT_TRIGGER - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask); - isView = pTab->pSelect!=0; - assert( pTrigger || tmask==0 ); -#else -# define pTrigger 0 -# define isView 0 -# define tmask 0 -#endif -#ifdef SQLITE_OMIT_VIEW -# undef isView -# define isView 0 -#endif - - /* If there was a FROM clause, set nChangeFrom to the number of expressions - ** in the change-list. Otherwise, set it to 0. There cannot be a FROM - ** clause if this function is being called to generate code for part of - ** an UPSERT statement. */ - nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0; - assert( nChangeFrom==0 || pUpsert==0 ); - -#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT - if( !isView && nChangeFrom==0 ){ - pWhere = sqlite3LimitWhere( - pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE" - ); - pOrderBy = 0; - pLimit = 0; - } -#endif - - if( sqlite3ViewGetColumnNames(pParse, pTab) ){ - goto update_cleanup; - } - if( sqlite3IsReadOnly(pParse, pTab, tmask) ){ - goto update_cleanup; - } - - /* Allocate a cursors for the main database table and for all indices. - ** The index cursors might not be used, but if they are used they - ** need to occur right after the database cursor. So go ahead and - ** allocate enough space, just in case. - */ - iBaseCur = iDataCur = pParse->nTab++; - iIdxCur = iDataCur+1; - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); - testcase( pPk!=0 && pPk!=pTab->pIndex ); - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ - if( pPk==pIdx ){ - iDataCur = pParse->nTab; - } - pParse->nTab++; - } - if( pUpsert ){ - /* On an UPSERT, reuse the same cursors already opened by INSERT */ - iDataCur = pUpsert->iDataCur; - iIdxCur = pUpsert->iIdxCur; - pParse->nTab = iBaseCur; - } - pTabList->a[0].iCursor = iDataCur; - - /* Allocate space for aXRef[], aRegIdx[], and aToOpen[]. - ** Initialize aXRef[] and aToOpen[] to their default values. - */ - aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 ); - if( aXRef==0 ) goto update_cleanup; - aRegIdx = aXRef+pTab->nCol; - aToOpen = (u8*)(aRegIdx+nIdx+1); - memset(aToOpen, 1, nIdx+1); - aToOpen[nIdx+1] = 0; - for(i=0; inCol; i++) aXRef[i] = -1; - - /* Initialize the name-context */ - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - sNC.pSrcList = pTabList; - sNC.uNC.pUpsert = pUpsert; - sNC.ncFlags = NC_UUpsert; - - /* Begin generating code. */ - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto update_cleanup; - - /* Resolve the column names in all the expressions of the - ** of the UPDATE statement. Also find the column index - ** for each column to be updated in the pChanges array. For each - ** column to be updated, make sure we have authorization to change - ** that column. - */ - chngRowid = chngPk = 0; - for(i=0; inExpr; i++){ - /* If this is an UPDATE with a FROM clause, do not resolve expressions - ** here. The call to sqlite3Select() below will do that. */ - if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ - goto update_cleanup; - } - for(j=0; jnCol; j++){ - if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){ - if( j==pTab->iPKey ){ - chngRowid = 1; - pRowidExpr = pChanges->a[i].pExpr; - iRowidExpr = i; - }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ - chngPk = 1; - } -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){ - testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ); - testcase( pTab->aCol[j].colFlags & COLFLAG_STORED ); - sqlite3ErrorMsg(pParse, - "cannot UPDATE generated column \"%s\"", - pTab->aCol[j].zName); - goto update_cleanup; - } -#endif - aXRef[j] = i; - break; - } - } - if( j>=pTab->nCol ){ - if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){ - j = -1; - chngRowid = 1; - pRowidExpr = pChanges->a[i].pExpr; - iRowidExpr = i; - }else{ - sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName); - pParse->checkSchema = 1; - goto update_cleanup; - } - } -#ifndef SQLITE_OMIT_AUTHORIZATION - { - int rc; - rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName, - j<0 ? "ROWID" : pTab->aCol[j].zName, - db->aDb[iDb].zDbSName); - if( rc==SQLITE_DENY ){ - goto update_cleanup; - }else if( rc==SQLITE_IGNORE ){ - aXRef[j] = -1; - } - } -#endif - } - assert( (chngRowid & chngPk)==0 ); - assert( chngRowid==0 || chngRowid==1 ); - assert( chngPk==0 || chngPk==1 ); - chngKey = chngRowid + chngPk; - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - /* Mark generated columns as changing if their generator expressions - ** reference any changing column. The actual aXRef[] value for - ** generated expressions is not used, other than to check to see that it - ** is non-negative, so the value of aXRef[] for generated columns can be - ** set to any non-negative number. We use 99999 so that the value is - ** obvious when looking at aXRef[] in a symbolic debugger. - */ - if( pTab->tabFlags & TF_HasGenerated ){ - int bProgress; - testcase( pTab->tabFlags & TF_HasVirtual ); - testcase( pTab->tabFlags & TF_HasStored ); - do{ - bProgress = 0; - for(i=0; inCol; i++){ - if( aXRef[i]>=0 ) continue; - if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue; - if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt, - aXRef, chngRowid) ){ - aXRef[i] = 99999; - bProgress = 1; - } - } - }while( bProgress ); - } -#endif - - /* The SET expressions are not actually used inside the WHERE loop. - ** So reset the colUsed mask. Unless this is a virtual table. In that - ** case, set all bits of the colUsed mask (to ensure that the virtual - ** table implementation makes all columns available). - */ - pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0; - - hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey); - - /* There is one entry in the aRegIdx[] array for each index on the table - ** being updated. Fill in aRegIdx[] with a register number that will hold - ** the key for accessing each index. - */ - if( onError==OE_Replace ) bReplace = 1; - for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){ - int reg; - if( chngKey || hasFK>1 || pIdx==pPk - || indexWhereClauseMightChange(pIdx,aXRef,chngRowid) - ){ - reg = ++pParse->nMem; - pParse->nMem += pIdx->nColumn; - }else{ - reg = 0; - for(i=0; inKeyCol; i++){ - if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){ - reg = ++pParse->nMem; - pParse->nMem += pIdx->nColumn; - if( onError==OE_Default && pIdx->onError==OE_Replace ){ - bReplace = 1; - } - break; - } - } - } - if( reg==0 ) aToOpen[nAllIdx+1] = 0; - aRegIdx[nAllIdx] = reg; - } - aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */ - if( bReplace ){ - /* If REPLACE conflict resolution might be invoked, open cursors on all - ** indexes in case they are needed to delete records. */ - memset(aToOpen, 1, nIdx+1); - } - - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); - sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb); - - /* Allocate required registers. */ - if( !IsVirtual(pTab) ){ - /* For now, regRowSet and aRegIdx[nAllIdx] share the same register. - ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be - ** reallocated. aRegIdx[nAllIdx] is the register in which the main - ** table record is written. regRowSet holds the RowSet for the - ** two-pass update algorithm. */ - assert( aRegIdx[nAllIdx]==pParse->nMem ); - regRowSet = aRegIdx[nAllIdx]; - regOldRowid = regNewRowid = ++pParse->nMem; - if( chngPk || pTrigger || hasFK ){ - regOld = pParse->nMem + 1; - pParse->nMem += pTab->nCol; - } - if( chngKey || pTrigger || hasFK ){ - regNewRowid = ++pParse->nMem; - } - regNew = pParse->nMem + 1; - pParse->nMem += pTab->nCol; - } - - /* Start the view context. */ - if( isView ){ - sqlite3AuthContextPush(pParse, &sContext, pTab->zName); - } - - /* If we are trying to update a view, realize that view into - ** an ephemeral table. - */ -#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) - if( nChangeFrom==0 && isView ){ - sqlite3MaterializeView(pParse, pTab, - pWhere, pOrderBy, pLimit, iDataCur - ); - pOrderBy = 0; - pLimit = 0; - } -#endif - - /* Resolve the column names in all the expressions in the - ** WHERE clause. - */ - if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pWhere) ){ - goto update_cleanup; - } - -#ifndef SQLITE_OMIT_VIRTUALTABLE - /* Virtual tables must be handled separately */ - if( IsVirtual(pTab) ){ - updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, - pWhere, onError); - goto update_cleanup; - } -#endif - - /* Jump to labelBreak to abandon further processing of this UPDATE */ - labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse); - - /* Not an UPSERT. Normal processing. Begin by - ** initialize the count of updated rows */ - if( (db->flags&SQLITE_CountRows)!=0 - && !pParse->pTriggerTab - && !pParse->nested - && pUpsert==0 - ){ - regRowCount = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); - } - - if( nChangeFrom==0 && HasRowid(pTab) ){ - sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); - }else{ - assert( pPk!=0 || HasRowid(pTab) ); - nPk = pPk ? pPk->nKeyCol : 0; - iPk = pParse->nMem+1; - pParse->nMem += nPk; - pParse->nMem += nChangeFrom; - regKey = ++pParse->nMem; - if( pUpsert==0 ){ - int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0); - iEph = pParse->nTab++; - if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1); - addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nEphCol); - if( pPk ){ - KeyInfo *pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pPk); - if( pKeyInfo ){ - pKeyInfo->nAllField = nEphCol; - sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); - } - } - if( nChangeFrom ){ - updateFromSelect( - pParse, iEph, pPk, pChanges, pTabList, pWhere, pOrderBy, pLimit - ); -#ifndef SQLITE_OMIT_SUBQUERY - if( isView ) iDataCur = iEph; -#endif - } - } - } - - if( nChangeFrom ){ - sqlite3MultiWrite(pParse); - eOnePass = ONEPASS_OFF; - nKey = nPk; - regKey = iPk; - }else{ - if( pUpsert ){ - /* If this is an UPSERT, then all cursors have already been opened by - ** the outer INSERT and the data cursor should be pointing at the row - ** that is to be updated. So bypass the code that searches for the - ** row(s) to be updated. - */ - pWInfo = 0; - eOnePass = ONEPASS_SINGLE; - sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL); - bFinishSeek = 0; - }else{ - /* Begin the database scan. - ** - ** Do not consider a single-pass strategy for a multi-row update if - ** there are any triggers or foreign keys to process, or rows may - ** be deleted as a result of REPLACE conflict handling. Any of these - ** things might disturb a cursor being used to scan through the table - ** or index, causing a single-pass approach to malfunction. */ - flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE; - if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){ - flags |= WHERE_ONEPASS_MULTIROW; - } - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags,iIdxCur); - if( pWInfo==0 ) goto update_cleanup; - - /* A one-pass strategy that might update more than one row may not - ** be used if any column of the index used for the scan is being - ** updated. Otherwise, if there is an index on "b", statements like - ** the following could create an infinite loop: - ** - ** UPDATE t1 SET b=b+1 WHERE b>? - ** - ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI - ** strategy that uses an index for which one or more columns are being - ** updated. */ - eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass); - bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo); - if( eOnePass!=ONEPASS_SINGLE ){ - sqlite3MultiWrite(pParse); - if( eOnePass==ONEPASS_MULTI ){ - int iCur = aiCurOnePass[1]; - if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){ - eOnePass = ONEPASS_OFF; - } - assert( iCur!=iDataCur || !HasRowid(pTab) ); - } - } - } - - if( HasRowid(pTab) ){ - /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF - ** mode, write the rowid into the FIFO. In either of the one-pass modes, - ** leave it in register regOldRowid. */ - sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid); - if( eOnePass==ONEPASS_OFF ){ - /* We need to use regRowSet, so reallocate aRegIdx[nAllIdx] */ - aRegIdx[nAllIdx] = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); - } - }else{ - /* Read the PK of the current row into an array of registers. In - ** ONEPASS_OFF mode, serialize the array into a record and store it in - ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change - ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table - ** is not required) and leave the PK fields in the array of registers. */ - for(i=0; iaiColumn[i]>=0 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, - pPk->aiColumn[i], iPk+i); - } - if( eOnePass ){ - if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen); - nKey = nPk; - regKey = iPk; - }else{ - sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey, - sqlite3IndexAffinityStr(db, pPk), nPk); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk); - } - } - } - - if( pUpsert==0 ){ - if( nChangeFrom==0 && eOnePass!=ONEPASS_MULTI ){ - sqlite3WhereEnd(pWInfo); - } - - if( !isView ){ - int addrOnce = 0; - - /* Open every index that needs updating. */ - if( eOnePass!=ONEPASS_OFF ){ - if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0; - if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0; - } - - if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){ - addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - } - sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, - aToOpen, 0, 0); - if( addrOnce ){ - sqlite3VdbeJumpHereOrPopInst(v, addrOnce); - } - } - - /* Top of the update loop */ - if( eOnePass!=ONEPASS_OFF ){ - if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){ - assert( pPk ); - sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey); - VdbeCoverage(v); - } - if( eOnePass!=ONEPASS_SINGLE ){ - labelContinue = sqlite3VdbeMakeLabel(pParse); - } - sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); - VdbeCoverageIf(v, pPk==0); - VdbeCoverageIf(v, pPk!=0); - }else if( pPk || nChangeFrom ){ - labelContinue = sqlite3VdbeMakeLabel(pParse); - sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); - addrTop = sqlite3VdbeCurrentAddr(v); - if( nChangeFrom ){ - if( !isView ){ - if( pPk ){ - for(i=0; i=0 ); - if( nChangeFrom==0 ){ - sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); - }else{ - sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid); - } - sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v); - } - - /* Compute the old pre-UPDATE content of the row being changed, if that - ** information is needed */ - if( chngPk || hasFK || pTrigger ){ - u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); - oldmask |= sqlite3TriggerColmask(pParse, - pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError - ); - for(i=0; inCol; i++){ - u32 colFlags = pTab->aCol[i].colFlags; - k = sqlite3TableColumnToStorage(pTab, i) + regOld; - if( oldmask==0xffffffff - || (i<32 && (oldmask & MASKBIT32(i))!=0) - || (colFlags & COLFLAG_PRIMKEY)!=0 - ){ - testcase( oldmask!=0xffffffff && i==31 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, k); - } - } - if( chngRowid==0 && pPk==0 ){ - sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); - } - } - - /* Populate the array of registers beginning at regNew with the new - ** row data. This array is used to check constants, create the new - ** table and index records, and as the values for any new.* references - ** made by triggers. - ** - ** If there are one or more BEFORE triggers, then do not populate the - ** registers associated with columns that are (a) not modified by - ** this UPDATE statement and (b) not accessed by new.* references. The - ** values for registers not modified by the UPDATE must be reloaded from - ** the database after the BEFORE triggers are fired anyway (as the trigger - ** may have modified them). So not loading those that are not going to - ** be used eliminates some redundant opcodes. - */ - newmask = sqlite3TriggerColmask( - pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError - ); - for(i=0, k=regNew; inCol; i++, k++){ - if( i==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, k); - }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){ - if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--; - }else{ - j = aXRef[i]; - if( j>=0 ){ - if( nChangeFrom ){ - int nOff = (isView ? pTab->nCol : nPk); - assert( eOnePass==ONEPASS_OFF ); - sqlite3VdbeAddOp3(v, OP_Column, iEph, nOff+j, k); - }else{ - sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k); - } - }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){ - /* This branch loads the value of a column that will not be changed - ** into a register. This is done if there are no BEFORE triggers, or - ** if there are one or more BEFORE triggers that use this value via - ** a new.* reference in a trigger program. - */ - testcase( i==31 ); - testcase( i==32 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); - bFinishSeek = 0; - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, k); - } - } - } -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( pTab->tabFlags & TF_HasGenerated ){ - testcase( pTab->tabFlags & TF_HasVirtual ); - testcase( pTab->tabFlags & TF_HasStored ); - sqlite3ComputeGeneratedColumns(pParse, regNew, pTab); - } -#endif - - /* Fire any BEFORE UPDATE triggers. This happens before constraints are - ** verified. One could argue that this is wrong. - */ - if( tmask&TRIGGER_BEFORE ){ - sqlite3TableAffinity(v, pTab, regNew); - sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, - TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue); - - if( !isView ){ - /* The row-trigger may have deleted the row being updated. In this - ** case, jump to the next row. No updates or AFTER triggers are - ** required. This behavior - what happens when the row being updated - ** is deleted or renamed by a BEFORE trigger - is left undefined in the - ** documentation. - */ - if( pPk ){ - sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey); - VdbeCoverage(v); - }else{ - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid); - VdbeCoverage(v); - } - - /* After-BEFORE-trigger-reload-loop: - ** If it did not delete it, the BEFORE trigger may still have modified - ** some of the columns of the row being updated. Load the values for - ** all columns not modified by the update statement into their registers - ** in case this has happened. Only unmodified columns are reloaded. - ** The values computed for modified columns use the values before the - ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26) - ** for an example. - */ - for(i=0, k=regNew; inCol; i++, k++){ - if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){ - if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--; - }else if( aXRef[i]<0 && i!=pTab->iPKey ){ - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k); - } - } -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( pTab->tabFlags & TF_HasGenerated ){ - testcase( pTab->tabFlags & TF_HasVirtual ); - testcase( pTab->tabFlags & TF_HasStored ); - sqlite3ComputeGeneratedColumns(pParse, regNew, pTab); - } -#endif - } - } - - if( !isView ){ - /* Do constraint checks. */ - assert( regOldRowid>0 ); - sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, - regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace, - aXRef, 0); - - /* If REPLACE conflict handling may have been used, or if the PK of the - ** row is changing, then the GenerateConstraintChecks() above may have - ** moved cursor iDataCur. Reseek it. */ - if( bReplace || chngKey ){ - if( pPk ){ - sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey); - }else{ - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid); - } - VdbeCoverageNeverTaken(v); - } - - /* Do FK constraint checks. */ - if( hasFK ){ - sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); - } - - /* Delete the index entries associated with the current record. */ - sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1); - - /* We must run the OP_FinishSeek opcode to resolve a prior - ** OP_DeferredSeek if there is any possibility that there have been - ** no OP_Column opcodes since the OP_DeferredSeek was issued. But - ** we want to avoid the OP_FinishSeek if possible, as running it - ** costs CPU cycles. */ - if( bFinishSeek ){ - sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur); - } - - /* If changing the rowid value, or if there are foreign key constraints - ** to process, delete the old record. Otherwise, add a noop OP_Delete - ** to invoke the pre-update hook. - ** - ** That (regNew==regnewRowid+1) is true is also important for the - ** pre-update hook. If the caller invokes preupdate_new(), the returned - ** value is copied from memory cell (regNewRowid+1+iCol), where iCol - ** is the column index supplied by the user. - */ - assert( regNew==regNewRowid+1 ); -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3VdbeAddOp3(v, OP_Delete, iDataCur, - OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP), - regNewRowid - ); - if( eOnePass==ONEPASS_MULTI ){ - assert( hasFK==0 && chngKey==0 ); - sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); - } - if( !pParse->nested ){ - sqlite3VdbeAppendP4(v, pTab, P4_TABLE); - } -#else - if( hasFK>1 || chngKey ){ - sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0); - } -#endif - - if( hasFK ){ - sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey); - } - - /* Insert the new index entries and the new record. */ - sqlite3CompleteInsertion( - pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, - OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), - 0, 0 - ); - - /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to - ** handle rows (possibly in other tables) that refer via a foreign key - ** to the row just updated. */ - if( hasFK ){ - sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey); - } - } - - /* Increment the row counter - */ - if( regRowCount ){ - sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); - } - - sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, - TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue); - - /* Repeat the above with the next record to be updated, until - ** all record selected by the WHERE clause have been updated. - */ - if( eOnePass==ONEPASS_SINGLE ){ - /* Nothing to do at end-of-loop for a single-pass */ - }else if( eOnePass==ONEPASS_MULTI ){ - sqlite3VdbeResolveLabel(v, labelContinue); - sqlite3WhereEnd(pWInfo); - }else if( pPk || nChangeFrom ){ - sqlite3VdbeResolveLabel(v, labelContinue); - sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v); - }else{ - sqlite3VdbeGoto(v, labelContinue); - } - sqlite3VdbeResolveLabel(v, labelBreak); - - /* Update the sqlite_sequence table by storing the content of the - ** maximum rowid counter values recorded while inserting into - ** autoincrement tables. - */ - if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){ - sqlite3AutoincrementEnd(pParse); - } - - /* - ** Return the number of rows that were changed, if we are tracking - ** that information. - */ - if( regRowCount ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); - } - -update_cleanup: - sqlite3AuthContextPop(&sContext); - sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */ - sqlite3SrcListDelete(db, pTabList); - sqlite3ExprListDelete(db, pChanges); - sqlite3ExprDelete(db, pWhere); -#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) - sqlite3ExprListDelete(db, pOrderBy); - sqlite3ExprDelete(db, pLimit); -#endif - return; -} -/* Make sure "isView" and other macros defined above are undefined. Otherwise -** they may interfere with compilation of other functions in this file -** (or in another file, if this file becomes part of the amalgamation). */ -#ifdef isView - #undef isView -#endif -#ifdef pTrigger - #undef pTrigger -#endif - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Generate code for an UPDATE of a virtual table. -** -** There are two possible strategies - the default and the special -** "onepass" strategy. Onepass is only used if the virtual table -** implementation indicates that pWhere may match at most one row. -** -** The default strategy is to create an ephemeral table that contains -** for each row to be changed: -** -** (A) The original rowid of that row. -** (B) The revised rowid for the row. -** (C) The content of every column in the row. -** -** Then loop through the contents of this ephemeral table executing a -** VUpdate for each row. When finished, drop the ephemeral table. -** -** The "onepass" strategy does not use an ephemeral table. Instead, it -** stores the same values (A, B and C above) in a register array and -** makes a single invocation of VUpdate. -*/ -static void updateVirtualTable( - Parse *pParse, /* The parsing context */ - SrcList *pSrc, /* The virtual table to be modified */ - Table *pTab, /* The virtual table */ - ExprList *pChanges, /* The columns to change in the UPDATE statement */ - Expr *pRowid, /* Expression used to recompute the rowid */ - int *aXRef, /* Mapping from columns of pTab to entries in pChanges */ - Expr *pWhere, /* WHERE clause of the UPDATE statement */ - int onError /* ON CONFLICT strategy */ -){ - Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */ - int ephemTab; /* Table holding the result of the SELECT */ - int i; /* Loop counter */ - sqlite3 *db = pParse->db; /* Database connection */ - const char *pVTab = (const char*)sqlite3GetVTable(db, pTab); - WhereInfo *pWInfo = 0; - int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */ - int regArg; /* First register in VUpdate arg array */ - int regRec; /* Register in which to assemble record */ - int regRowid; /* Register for ephem table rowid */ - int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */ - int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */ - int eOnePass; /* True to use onepass strategy */ - int addr; /* Address of OP_OpenEphemeral */ - - /* Allocate nArg registers in which to gather the arguments for VUpdate. Then - ** create and open the ephemeral table in which the records created from - ** these arguments will be temporarily stored. */ - assert( v ); - ephemTab = pParse->nTab++; - addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg); - regArg = pParse->nMem + 1; - pParse->nMem += nArg; - if( pSrc->nSrc>1 ){ - Expr *pRow; - ExprList *pList; - if( pRowid ){ - pRow = sqlite3ExprDup(db, pRowid, 0); - }else{ - pRow = sqlite3PExpr(pParse, TK_ROW, 0, 0); - } - pList = sqlite3ExprListAppend(pParse, 0, pRow); - - for(i=0; inCol; i++){ - if( aXRef[i]>=0 ){ - pList = sqlite3ExprListAppend(pParse, pList, - sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0) - ); - }else{ - pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i)); - } - } - - updateFromSelect(pParse, ephemTab, 0, pList, pSrc, pWhere, 0, 0); - sqlite3ExprListDelete(db, pList); - eOnePass = ONEPASS_OFF; - }else{ - regRec = ++pParse->nMem; - regRowid = ++pParse->nMem; - - /* Start scanning the virtual table */ - pWInfo = sqlite3WhereBegin(pParse, pSrc,pWhere,0,0,WHERE_ONEPASS_DESIRED,0); - if( pWInfo==0 ) return; - - /* Populate the argument registers. */ - for(i=0; inCol; i++){ - assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ); - if( aXRef[i]>=0 ){ - sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i); - }else{ - sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i); - sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* For sqlite3_vtab_nochange() */ - } - } - if( HasRowid(pTab) ){ - sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg); - if( pRowid ){ - sqlite3ExprCode(pParse, pRowid, regArg+1); - }else{ - sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1); - } - }else{ - Index *pPk; /* PRIMARY KEY index */ - i16 iPk; /* PRIMARY KEY column */ - pPk = sqlite3PrimaryKeyIndex(pTab); - assert( pPk!=0 ); - assert( pPk->nKeyCol==1 ); - iPk = pPk->aiColumn[0]; - sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg); - sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1); - } - - eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy); - - /* There is no ONEPASS_MULTI on virtual tables */ - assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); - - if( eOnePass ){ - /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded - ** above. */ - sqlite3VdbeChangeToNoop(v, addr); - sqlite3VdbeAddOp1(v, OP_Close, iCsr); - }else{ - /* Create a record from the argument register contents and insert it into - ** the ephemeral table. */ - sqlite3MultiWrite(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec); -#if defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_NULL_TRIM) - /* Signal an assert() within OP_MakeRecord that it is allowed to - ** accept no-change records with serial_type 10 */ - sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC); -#endif - sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid); - } - } - - - if( eOnePass==ONEPASS_OFF ){ - /* End the virtual table scan */ - if( pSrc->nSrc==1 ){ - sqlite3WhereEnd(pWInfo); - } - - /* Begin scannning through the ephemeral table. */ - addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v); - - /* Extract arguments from the current row of the ephemeral table and - ** invoke the VUpdate method. */ - for(i=0; ipUpsertTarget); - sqlite3ExprDelete(db, p->pUpsertTargetWhere); - sqlite3ExprListDelete(db, p->pUpsertSet); - sqlite3ExprDelete(db, p->pUpsertWhere); - sqlite3DbFree(db, p); - } -} - -/* -** Duplicate an Upsert object. -*/ -SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){ - if( p==0 ) return 0; - return sqlite3UpsertNew(db, - sqlite3ExprListDup(db, p->pUpsertTarget, 0), - sqlite3ExprDup(db, p->pUpsertTargetWhere, 0), - sqlite3ExprListDup(db, p->pUpsertSet, 0), - sqlite3ExprDup(db, p->pUpsertWhere, 0) - ); -} - -/* -** Create a new Upsert object. -*/ -SQLITE_PRIVATE Upsert *sqlite3UpsertNew( - sqlite3 *db, /* Determines which memory allocator to use */ - ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */ - Expr *pTargetWhere, /* Optional WHERE clause on the target */ - ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */ - Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */ -){ - Upsert *pNew; - pNew = sqlite3DbMallocRaw(db, sizeof(Upsert)); - if( pNew==0 ){ - sqlite3ExprListDelete(db, pTarget); - sqlite3ExprDelete(db, pTargetWhere); - sqlite3ExprListDelete(db, pSet); - sqlite3ExprDelete(db, pWhere); - return 0; - }else{ - pNew->pUpsertTarget = pTarget; - pNew->pUpsertTargetWhere = pTargetWhere; - pNew->pUpsertSet = pSet; - pNew->pUpsertWhere = pWhere; - pNew->pUpsertIdx = 0; - } - return pNew; -} - -/* -** Analyze the ON CONFLICT clause described by pUpsert. Resolve all -** symbols in the conflict-target. -** -** Return SQLITE_OK if everything works, or an error code is something -** is wrong. -*/ -SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget( - Parse *pParse, /* The parsing context */ - SrcList *pTabList, /* Table into which we are inserting */ - Upsert *pUpsert /* The ON CONFLICT clauses */ -){ - Table *pTab; /* That table into which we are inserting */ - int rc; /* Result code */ - int iCursor; /* Cursor used by pTab */ - Index *pIdx; /* One of the indexes of pTab */ - ExprList *pTarget; /* The conflict-target clause */ - Expr *pTerm; /* One term of the conflict-target clause */ - NameContext sNC; /* Context for resolving symbolic names */ - Expr sCol[2]; /* Index column converted into an Expr */ - - assert( pTabList->nSrc==1 ); - assert( pTabList->a[0].pTab!=0 ); - assert( pUpsert!=0 ); - assert( pUpsert->pUpsertTarget!=0 ); - - /* Resolve all symbolic names in the conflict-target clause, which - ** includes both the list of columns and the optional partial-index - ** WHERE clause. - */ - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - sNC.pSrcList = pTabList; - rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget); - if( rc ) return rc; - rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere); - if( rc ) return rc; - - /* Check to see if the conflict target matches the rowid. */ - pTab = pTabList->a[0].pTab; - pTarget = pUpsert->pUpsertTarget; - iCursor = pTabList->a[0].iCursor; - if( HasRowid(pTab) - && pTarget->nExpr==1 - && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN - && pTerm->iColumn==XN_ROWID - ){ - /* The conflict-target is the rowid of the primary table */ - assert( pUpsert->pUpsertIdx==0 ); - return SQLITE_OK; - } - - /* Initialize sCol[0..1] to be an expression parse tree for a - ** single column of an index. The sCol[0] node will be the TK_COLLATE - ** operator and sCol[1] will be the TK_COLUMN operator. Code below - ** will populate the specific collation and column number values - ** prior to comparing against the conflict-target expression. - */ - memset(sCol, 0, sizeof(sCol)); - sCol[0].op = TK_COLLATE; - sCol[0].pLeft = &sCol[1]; - sCol[1].op = TK_COLUMN; - sCol[1].iTable = pTabList->a[0].iCursor; - - /* Check for matches against other indexes */ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - int ii, jj, nn; - if( !IsUniqueIndex(pIdx) ) continue; - if( pTarget->nExpr!=pIdx->nKeyCol ) continue; - if( pIdx->pPartIdxWhere ){ - if( pUpsert->pUpsertTargetWhere==0 ) continue; - if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere, - pIdx->pPartIdxWhere, iCursor)!=0 ){ - continue; - } - } - nn = pIdx->nKeyCol; - for(ii=0; iiazColl[ii]; - if( pIdx->aiColumn[ii]==XN_EXPR ){ - assert( pIdx->aColExpr!=0 ); - assert( pIdx->aColExpr->nExpr>ii ); - pExpr = pIdx->aColExpr->a[ii].pExpr; - if( pExpr->op!=TK_COLLATE ){ - sCol[0].pLeft = pExpr; - pExpr = &sCol[0]; - } - }else{ - sCol[0].pLeft = &sCol[1]; - sCol[1].iColumn = pIdx->aiColumn[ii]; - pExpr = &sCol[0]; - } - for(jj=0; jja[jj].pExpr, pExpr,iCursor)<2 ){ - break; /* Column ii of the index matches column jj of target */ - } - } - if( jj>=nn ){ - /* The target contains no match for column jj of the index */ - break; - } - } - if( iipUpsertIdx = pIdx; - return SQLITE_OK; - } - sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any " - "PRIMARY KEY or UNIQUE constraint"); - return SQLITE_ERROR; -} - -/* -** Generate bytecode that does an UPDATE as part of an upsert. -** -** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK. -** In this case parameter iCur is a cursor open on the table b-tree that -** currently points to the conflicting table row. Otherwise, if pIdx -** is not NULL, then pIdx is the constraint that failed and iCur is a -** cursor points to the conflicting row. -*/ -SQLITE_PRIVATE void sqlite3UpsertDoUpdate( - Parse *pParse, /* The parsing and code-generating context */ - Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */ - Table *pTab, /* The table being updated */ - Index *pIdx, /* The UNIQUE constraint that failed */ - int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */ -){ - Vdbe *v = pParse->pVdbe; - sqlite3 *db = pParse->db; - SrcList *pSrc; /* FROM clause for the UPDATE */ - int iDataCur; - int i; - - assert( v!=0 ); - assert( pUpsert!=0 ); - VdbeNoopComment((v, "Begin DO UPDATE of UPSERT")); - iDataCur = pUpsert->iDataCur; - if( pIdx && iCur!=iDataCur ){ - if( HasRowid(pTab) ){ - int regRowid = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid); - sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid); - VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, regRowid); - }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - int nPk = pPk->nKeyCol; - int iPk = pParse->nMem+1; - pParse->nMem += nPk; - for(i=0; iaiColumn[i]>=0 ); - k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]); - sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i); - VdbeComment((v, "%s.%s", pIdx->zName, - pTab->aCol[pPk->aiColumn[i]].zName)); - } - sqlite3VdbeVerifyAbortable(v, OE_Abort); - i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk); - VdbeCoverage(v); - sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0, - "corrupt database", P4_STATIC); - sqlite3MayAbort(pParse); - sqlite3VdbeJumpHere(v, i); - } - } - /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So - ** we have to make a copy before passing it down into sqlite3Update() */ - pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0); - /* excluded.* columns of type REAL need to be converted to a hard real */ - for(i=0; inCol; i++){ - if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, pUpsert->regData+i); - } - } - sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet, - pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert); - pUpsert->pUpsertSet = 0; /* Will have been deleted by sqlite3Update() */ - pUpsert->pUpsertWhere = 0; /* Will have been deleted by sqlite3Update() */ - VdbeNoopComment((v, "End DO UPDATE of UPSERT")); -} - -#endif /* SQLITE_OMIT_UPSERT */ - -/************** End of upsert.c **********************************************/ -/************** Begin file vacuum.c ******************************************/ -/* -** 2003 April 6 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code used to implement the VACUUM command. -** -** Most of the code in this file may be omitted by defining the -** SQLITE_OMIT_VACUUM macro. -*/ -/* #include "sqliteInt.h" */ -/* #include "vdbeInt.h" */ - -#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) - -/* -** Execute zSql on database db. -** -** If zSql returns rows, then each row will have exactly one -** column. (This will only happen if zSql begins with "SELECT".) -** Take each row of result and call execSql() again recursively. -** -** The execSqlF() routine does the same thing, except it accepts -** a format string as its third argument -*/ -static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){ - sqlite3_stmt *pStmt; - int rc; - - /* printf("SQL: [%s]\n", zSql); fflush(stdout); */ - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc!=SQLITE_OK ) return rc; - while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ - const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0); - assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 ); - /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX, - ** or INSERT. Historically there have been attacks that first - ** corrupt the sqlite_schema.sql field with other kinds of statements - ** then run VACUUM to get those statements to execute at inappropriate - ** times. */ - if( zSubSql - && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0) - ){ - rc = execSql(db, pzErrMsg, zSubSql); - if( rc!=SQLITE_OK ) break; - } - } - assert( rc!=SQLITE_ROW ); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - if( rc ){ - sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db)); - } - (void)sqlite3_finalize(pStmt); - return rc; -} -static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){ - char *z; - va_list ap; - int rc; - va_start(ap, zSql); - z = sqlite3VMPrintf(db, zSql, ap); - va_end(ap); - if( z==0 ) return SQLITE_NOMEM; - rc = execSql(db, pzErrMsg, z); - sqlite3DbFree(db, z); - return rc; -} - -/* -** The VACUUM command is used to clean up the database, -** collapse free space, etc. It is modelled after the VACUUM command -** in PostgreSQL. The VACUUM command works as follows: -** -** (1) Create a new transient database file -** (2) Copy all content from the database being vacuumed into -** the new transient database file -** (3) Copy content from the transient database back into the -** original database. -** -** The transient database requires temporary disk space approximately -** equal to the size of the original database. The copy operation of -** step (3) requires additional temporary disk space approximately equal -** to the size of the original database for the rollback journal. -** Hence, temporary disk space that is approximately 2x the size of the -** original database is required. Every page of the database is written -** approximately 3 times: Once for step (2) and twice for step (3). -** Two writes per page are required in step (3) because the original -** database content must be written into the rollback journal prior to -** overwriting the database with the vacuumed content. -** -** Only 1x temporary space and only 1x writes would be required if -** the copy of step (3) were replaced by deleting the original database -** and renaming the transient database as the original. But that will -** not work if other processes are attached to the original database. -** And a power loss in between deleting the original and renaming the -** transient would cause the database file to appear to be deleted -** following reboot. -*/ -SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){ - Vdbe *v = sqlite3GetVdbe(pParse); - int iDb = 0; - if( v==0 ) goto build_vacuum_end; - if( pParse->nErr ) goto build_vacuum_end; - if( pNm ){ -#ifndef SQLITE_BUG_COMPATIBLE_20160819 - /* Default behavior: Report an error if the argument to VACUUM is - ** not recognized */ - iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm); - if( iDb<0 ) goto build_vacuum_end; -#else - /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments - ** to VACUUM are silently ignored. This is a back-out of a bug fix that - ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270). - ** The buggy behavior is required for binary compatibility with some - ** legacy applications. */ - iDb = sqlite3FindDb(pParse->db, pNm); - if( iDb<0 ) iDb = 0; -#endif - } - if( iDb!=1 ){ - int iIntoReg = 0; - if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){ - iIntoReg = ++pParse->nMem; - sqlite3ExprCode(pParse, pInto, iIntoReg); - } - sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg); - sqlite3VdbeUsesBtree(v, iDb); - } -build_vacuum_end: - sqlite3ExprDelete(pParse->db, pInto); - return; -} - -/* -** This routine implements the OP_Vacuum opcode of the VDBE. -*/ -SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum( - char **pzErrMsg, /* Write error message here */ - sqlite3 *db, /* Database connection */ - int iDb, /* Which attached DB to vacuum */ - sqlite3_value *pOut /* Write results here, if not NULL. VACUUM INTO */ -){ - int rc = SQLITE_OK; /* Return code from service routines */ - Btree *pMain; /* The database being vacuumed */ - Btree *pTemp; /* The temporary database we vacuum into */ - u32 saved_mDbFlags; /* Saved value of db->mDbFlags */ - u64 saved_flags; /* Saved value of db->flags */ - int saved_nChange; /* Saved value of db->nChange */ - int saved_nTotalChange; /* Saved value of db->nTotalChange */ - u32 saved_openFlags; /* Saved value of db->openFlags */ - u8 saved_mTrace; /* Saved trace settings */ - Db *pDb = 0; /* Database to detach at end of vacuum */ - int isMemDb; /* True if vacuuming a :memory: database */ - int nRes; /* Bytes of reserved space at the end of each page */ - int nDb; /* Number of attached databases */ - const char *zDbMain; /* Schema name of database to vacuum */ - const char *zOut; /* Name of output file */ - - if( !db->autoCommit ){ - sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); - return SQLITE_ERROR; /* IMP: R-12218-18073 */ - } - if( db->nVdbeActive>1 ){ - sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); - return SQLITE_ERROR; /* IMP: R-15610-35227 */ - } - saved_openFlags = db->openFlags; - if( pOut ){ - if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){ - sqlite3SetString(pzErrMsg, db, "non-text filename"); - return SQLITE_ERROR; - } - zOut = (const char*)sqlite3_value_text(pOut); - db->openFlags &= ~SQLITE_OPEN_READONLY; - db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; - }else{ - zOut = ""; - } - - /* Save the current value of the database flags so that it can be - ** restored before returning. Then set the writable-schema flag, and - ** disable CHECK and foreign key constraints. */ - saved_flags = db->flags; - saved_mDbFlags = db->mDbFlags; - saved_nChange = db->nChange; - saved_nTotalChange = db->nTotalChange; - saved_mTrace = db->mTrace; - db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; - db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum; - db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder - | SQLITE_Defensive | SQLITE_CountRows); - db->mTrace = 0; - - zDbMain = db->aDb[iDb].zDbSName; - pMain = db->aDb[iDb].pBt; - isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain)); - - /* Attach the temporary database as 'vacuum_db'. The synchronous pragma - ** can be set to 'off' for this file, as it is not recovered if a crash - ** occurs anyway. The integrity of the database is maintained by a - ** (possibly synchronous) transaction opened on the main database before - ** sqlite3BtreeCopyFile() is called. - ** - ** An optimisation would be to use a non-journaled pager. - ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but - ** that actually made the VACUUM run slower. Very little journalling - ** actually occurs when doing a vacuum since the vacuum_db is initially - ** empty. Only the journal header is written. Apparently it takes more - ** time to parse and run the PRAGMA to turn journalling off than it does - ** to write the journal header file. - */ - nDb = db->nDb; - rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut); - db->openFlags = saved_openFlags; - if( rc!=SQLITE_OK ) goto end_of_vacuum; - assert( (db->nDb-1)==nDb ); - pDb = &db->aDb[nDb]; - assert( strcmp(pDb->zDbSName,"vacuum_db")==0 ); - pTemp = pDb->pBt; - if( pOut ){ - sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp)); - i64 sz = 0; - if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){ - rc = SQLITE_ERROR; - sqlite3SetString(pzErrMsg, db, "output file already exists"); - goto end_of_vacuum; - } - db->mDbFlags |= DBFLAG_VacuumInto; - } - nRes = sqlite3BtreeGetRequestedReserve(pMain); - - sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); - sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0)); - sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL); - - /* Begin a transaction and take an exclusive lock on the main database - ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below, - ** to ensure that we do not try to change the page-size on a WAL database. - */ - rc = execSql(db, pzErrMsg, "BEGIN"); - if( rc!=SQLITE_OK ) goto end_of_vacuum; - rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0); - if( rc!=SQLITE_OK ) goto end_of_vacuum; - - /* Do not attempt to change the page size for a WAL database */ - if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain)) - ==PAGER_JOURNALMODE_WAL ){ - db->nextPagesize = 0; - } - - if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0) - || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0)) - || NEVER(db->mallocFailed) - ){ - rc = SQLITE_NOMEM_BKPT; - goto end_of_vacuum; - } - -#ifndef SQLITE_OMIT_AUTOVACUUM - sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : - sqlite3BtreeGetAutoVacuum(pMain)); -#endif - - /* Query the schema of the main database. Create a mirror schema - ** in the temporary database. - */ - db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */ - rc = execSqlF(db, pzErrMsg, - "SELECT sql FROM \"%w\".sqlite_schema" - " WHERE type='table'AND name<>'sqlite_sequence'" - " AND coalesce(rootpage,1)>0", - zDbMain - ); - if( rc!=SQLITE_OK ) goto end_of_vacuum; - rc = execSqlF(db, pzErrMsg, - "SELECT sql FROM \"%w\".sqlite_schema" - " WHERE type='index'", - zDbMain - ); - if( rc!=SQLITE_OK ) goto end_of_vacuum; - db->init.iDb = 0; - - /* Loop through the tables in the main database. For each, do - ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy - ** the contents to the temporary database. - */ - rc = execSqlF(db, pzErrMsg, - "SELECT'INSERT INTO vacuum_db.'||quote(name)" - "||' SELECT*FROM\"%w\".'||quote(name)" - "FROM vacuum_db.sqlite_schema " - "WHERE type='table'AND coalesce(rootpage,1)>0", - zDbMain - ); - assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 ); - db->mDbFlags &= ~DBFLAG_Vacuum; - if( rc!=SQLITE_OK ) goto end_of_vacuum; - - /* Copy the triggers, views, and virtual tables from the main database - ** over to the temporary database. None of these objects has any - ** associated storage, so all we have to do is copy their entries - ** from the schema table. - */ - rc = execSqlF(db, pzErrMsg, - "INSERT INTO vacuum_db.sqlite_schema" - " SELECT*FROM \"%w\".sqlite_schema" - " WHERE type IN('view','trigger')" - " OR(type='table'AND rootpage=0)", - zDbMain - ); - if( rc ) goto end_of_vacuum; - - /* At this point, there is a write transaction open on both the - ** vacuum database and the main database. Assuming no error occurs, - ** both transactions are closed by this block - the main database - ** transaction by sqlite3BtreeCopyFile() and the other by an explicit - ** call to sqlite3BtreeCommit(). - */ - { - u32 meta; - int i; - - /* This array determines which meta meta values are preserved in the - ** vacuum. Even entries are the meta value number and odd entries - ** are an increment to apply to the meta value after the vacuum. - ** The increment is used to increase the schema cookie so that other - ** connections to the same database will know to reread the schema. - */ - static const unsigned char aCopy[] = { - BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */ - BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */ - BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */ - BTREE_USER_VERSION, 0, /* Preserve the user version */ - BTREE_APPLICATION_ID, 0, /* Preserve the application id */ - }; - - assert( 1==sqlite3BtreeIsInTrans(pTemp) ); - assert( pOut!=0 || 1==sqlite3BtreeIsInTrans(pMain) ); - - /* Copy Btree meta values */ - for(i=0; iflags */ - db->init.iDb = 0; - db->mDbFlags = saved_mDbFlags; - db->flags = saved_flags; - db->nChange = saved_nChange; - db->nTotalChange = saved_nTotalChange; - db->mTrace = saved_mTrace; - sqlite3BtreeSetPageSize(pMain, -1, 0, 1); - - /* Currently there is an SQL level transaction open on the vacuum - ** database. No locks are held on any other files (since the main file - ** was committed at the btree level). So it safe to end the transaction - ** by manually setting the autoCommit flag to true and detaching the - ** vacuum database. The vacuum_db journal file is deleted when the pager - ** is closed by the DETACH. - */ - db->autoCommit = 1; - - if( pDb ){ - sqlite3BtreeClose(pDb->pBt); - pDb->pBt = 0; - pDb->pSchema = 0; - } - - /* This both clears the schemas and reduces the size of the db->aDb[] - ** array. */ - sqlite3ResetAllSchemasOfConnection(db); - - return rc; -} - -#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */ - -/************** End of vacuum.c **********************************************/ -/************** Begin file vtab.c ********************************************/ -/* -** 2006 June 10 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code used to help implement virtual tables. -*/ -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* #include "sqliteInt.h" */ - -/* -** Before a virtual table xCreate() or xConnect() method is invoked, the -** sqlite3.pVtabCtx member variable is set to point to an instance of -** this struct allocated on the stack. It is used by the implementation of -** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which -** are invoked only from within xCreate and xConnect methods. -*/ -struct VtabCtx { - VTable *pVTable; /* The virtual table being constructed */ - Table *pTab; /* The Table object to which the virtual table belongs */ - VtabCtx *pPrior; /* Parent context (if any) */ - int bDeclared; /* True after sqlite3_declare_vtab() is called */ -}; - -/* -** Construct and install a Module object for a virtual table. When this -** routine is called, it is guaranteed that all appropriate locks are held -** and the module is not already part of the connection. -** -** If there already exists a module with zName, replace it with the new one. -** If pModule==0, then delete the module zName if it exists. -*/ -SQLITE_PRIVATE Module *sqlite3VtabCreateModule( - sqlite3 *db, /* Database in which module is registered */ - const char *zName, /* Name assigned to this module */ - const sqlite3_module *pModule, /* The definition of the module */ - void *pAux, /* Context pointer for xCreate/xConnect */ - void (*xDestroy)(void *) /* Module destructor function */ -){ - Module *pMod; - Module *pDel; - char *zCopy; - if( pModule==0 ){ - zCopy = (char*)zName; - pMod = 0; - }else{ - int nName = sqlite3Strlen30(zName); - pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1); - if( pMod==0 ){ - sqlite3OomFault(db); - return 0; - } - zCopy = (char *)(&pMod[1]); - memcpy(zCopy, zName, nName+1); - pMod->zName = zCopy; - pMod->pModule = pModule; - pMod->pAux = pAux; - pMod->xDestroy = xDestroy; - pMod->pEpoTab = 0; - pMod->nRefModule = 1; - } - pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod); - if( pDel ){ - if( pDel==pMod ){ - sqlite3OomFault(db); - sqlite3DbFree(db, pDel); - pMod = 0; - }else{ - sqlite3VtabEponymousTableClear(db, pDel); - sqlite3VtabModuleUnref(db, pDel); - } - } - return pMod; -} - -/* -** The actual function that does the work of creating a new module. -** This function implements the sqlite3_create_module() and -** sqlite3_create_module_v2() interfaces. -*/ -static int createModule( - sqlite3 *db, /* Database in which module is registered */ - const char *zName, /* Name assigned to this module */ - const sqlite3_module *pModule, /* The definition of the module */ - void *pAux, /* Context pointer for xCreate/xConnect */ - void (*xDestroy)(void *) /* Module destructor function */ -){ - int rc = SQLITE_OK; - - sqlite3_mutex_enter(db->mutex); - (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy); - rc = sqlite3ApiExit(db, rc); - if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux); - sqlite3_mutex_leave(db->mutex); - return rc; -} - - -/* -** External API function used to create a new virtual-table module. -*/ -SQLITE_API int sqlite3_create_module( - sqlite3 *db, /* Database in which module is registered */ - const char *zName, /* Name assigned to this module */ - const sqlite3_module *pModule, /* The definition of the module */ - void *pAux /* Context pointer for xCreate/xConnect */ -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; -#endif - return createModule(db, zName, pModule, pAux, 0); -} - -/* -** External API function used to create a new virtual-table module. -*/ -SQLITE_API int sqlite3_create_module_v2( - sqlite3 *db, /* Database in which module is registered */ - const char *zName, /* Name assigned to this module */ - const sqlite3_module *pModule, /* The definition of the module */ - void *pAux, /* Context pointer for xCreate/xConnect */ - void (*xDestroy)(void *) /* Module destructor function */ -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; -#endif - return createModule(db, zName, pModule, pAux, xDestroy); -} - -/* -** External API to drop all virtual-table modules, except those named -** on the azNames list. -*/ -SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){ - HashElem *pThis, *pNext; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){ - Module *pMod = (Module*)sqliteHashData(pThis); - pNext = sqliteHashNext(pThis); - if( azNames ){ - int ii; - for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){} - if( azNames[ii]!=0 ) continue; - } - createModule(db, pMod->zName, 0, 0, 0); - } - return SQLITE_OK; -} - -/* -** Decrement the reference count on a Module object. Destroy the -** module when the reference count reaches zero. -*/ -SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3 *db, Module *pMod){ - assert( pMod->nRefModule>0 ); - pMod->nRefModule--; - if( pMod->nRefModule==0 ){ - if( pMod->xDestroy ){ - pMod->xDestroy(pMod->pAux); - } - assert( pMod->pEpoTab==0 ); - sqlite3DbFree(db, pMod); - } -} - -/* -** Lock the virtual table so that it cannot be disconnected. -** Locks nest. Every lock should have a corresponding unlock. -** If an unlock is omitted, resources leaks will occur. -** -** If a disconnect is attempted while a virtual table is locked, -** the disconnect is deferred until all locks have been removed. -*/ -SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){ - pVTab->nRef++; -} - - -/* -** pTab is a pointer to a Table structure representing a virtual-table. -** Return a pointer to the VTable object used by connection db to access -** this virtual-table, if one has been created, or NULL otherwise. -*/ -SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){ - VTable *pVtab; - assert( IsVirtual(pTab) ); - for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext); - return pVtab; -} - -/* -** Decrement the ref-count on a virtual table object. When the ref-count -** reaches zero, call the xDisconnect() method to delete the object. -*/ -SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){ - sqlite3 *db = pVTab->db; - - assert( db ); - assert( pVTab->nRef>0 ); - assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE ); - - pVTab->nRef--; - if( pVTab->nRef==0 ){ - sqlite3_vtab *p = pVTab->pVtab; - sqlite3VtabModuleUnref(pVTab->db, pVTab->pMod); - if( p ){ - p->pModule->xDisconnect(p); - } - sqlite3DbFree(db, pVTab); - } -} - -/* -** Table p is a virtual table. This function moves all elements in the -** p->pVTable list to the sqlite3.pDisconnect lists of their associated -** database connections to be disconnected at the next opportunity. -** Except, if argument db is not NULL, then the entry associated with -** connection db is left in the p->pVTable list. -*/ -static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){ - VTable *pRet = 0; - VTable *pVTable = p->pVTable; - p->pVTable = 0; - - /* Assert that the mutex (if any) associated with the BtShared database - ** that contains table p is held by the caller. See header comments - ** above function sqlite3VtabUnlockList() for an explanation of why - ** this makes it safe to access the sqlite3.pDisconnect list of any - ** database connection that may have an entry in the p->pVTable list. - */ - assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) ); - - while( pVTable ){ - sqlite3 *db2 = pVTable->db; - VTable *pNext = pVTable->pNext; - assert( db2 ); - if( db2==db ){ - pRet = pVTable; - p->pVTable = pRet; - pRet->pNext = 0; - }else{ - pVTable->pNext = db2->pDisconnect; - db2->pDisconnect = pVTable; - } - pVTable = pNext; - } - - assert( !db || pRet ); - return pRet; -} - -/* -** Table *p is a virtual table. This function removes the VTable object -** for table *p associated with database connection db from the linked -** list in p->pVTab. It also decrements the VTable ref count. This is -** used when closing database connection db to free all of its VTable -** objects without disturbing the rest of the Schema object (which may -** be being used by other shared-cache connections). -*/ -SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){ - VTable **ppVTab; - - assert( IsVirtual(p) ); - assert( sqlite3BtreeHoldsAllMutexes(db) ); - assert( sqlite3_mutex_held(db->mutex) ); - - for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){ - if( (*ppVTab)->db==db ){ - VTable *pVTab = *ppVTab; - *ppVTab = pVTab->pNext; - sqlite3VtabUnlock(pVTab); - break; - } - } -} - - -/* -** Disconnect all the virtual table objects in the sqlite3.pDisconnect list. -** -** This function may only be called when the mutexes associated with all -** shared b-tree databases opened using connection db are held by the -** caller. This is done to protect the sqlite3.pDisconnect list. The -** sqlite3.pDisconnect list is accessed only as follows: -** -** 1) By this function. In this case, all BtShared mutexes and the mutex -** associated with the database handle itself must be held. -** -** 2) By function vtabDisconnectAll(), when it adds a VTable entry to -** the sqlite3.pDisconnect list. In this case either the BtShared mutex -** associated with the database the virtual table is stored in is held -** or, if the virtual table is stored in a non-sharable database, then -** the database handle mutex is held. -** -** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously -** by multiple threads. It is thread-safe. -*/ -SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){ - VTable *p = db->pDisconnect; - - assert( sqlite3BtreeHoldsAllMutexes(db) ); - assert( sqlite3_mutex_held(db->mutex) ); - - if( p ){ - db->pDisconnect = 0; - sqlite3ExpirePreparedStatements(db, 0); - do { - VTable *pNext = p->pNext; - sqlite3VtabUnlock(p); - p = pNext; - }while( p ); - } -} - -/* -** Clear any and all virtual-table information from the Table record. -** This routine is called, for example, just before deleting the Table -** record. -** -** Since it is a virtual-table, the Table structure contains a pointer -** to the head of a linked list of VTable structures. Each VTable -** structure is associated with a single sqlite3* user of the schema. -** The reference count of the VTable structure associated with database -** connection db is decremented immediately (which may lead to the -** structure being xDisconnected and free). Any other VTable structures -** in the list are moved to the sqlite3.pDisconnect list of the associated -** database connection. -*/ -SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){ - if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p); - if( p->azModuleArg ){ - int i; - for(i=0; inModuleArg; i++){ - if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]); - } - sqlite3DbFree(db, p->azModuleArg); - } -} - -/* -** Add a new module argument to pTable->azModuleArg[]. -** The string is not copied - the pointer is stored. The -** string will be freed automatically when the table is -** deleted. -*/ -static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){ - sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg); - char **azModuleArg; - sqlite3 *db = pParse->db; - if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName); - } - azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); - if( azModuleArg==0 ){ - sqlite3DbFree(db, zArg); - }else{ - int i = pTable->nModuleArg++; - azModuleArg[i] = zArg; - azModuleArg[i+1] = 0; - pTable->azModuleArg = azModuleArg; - } -} - -/* -** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE -** statement. The module name has been parsed, but the optional list -** of parameters that follow the module name are still pending. -*/ -SQLITE_PRIVATE void sqlite3VtabBeginParse( - Parse *pParse, /* Parsing context */ - Token *pName1, /* Name of new table, or database name */ - Token *pName2, /* Name of new table or NULL */ - Token *pModuleName, /* Name of the module for the virtual table */ - int ifNotExists /* No error if the table already exists */ -){ - Table *pTable; /* The new virtual table */ - sqlite3 *db; /* Database connection */ - - sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists); - pTable = pParse->pNewTable; - if( pTable==0 ) return; - assert( 0==pTable->pIndex ); - - db = pParse->db; - - assert( pTable->nModuleArg==0 ); - addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName)); - addModuleArgument(pParse, pTable, 0); - addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName)); - assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0) - || (pParse->sNameToken.z==pName1->z && pName2->z==0) - ); - pParse->sNameToken.n = (int)( - &pModuleName->z[pModuleName->n] - pParse->sNameToken.z - ); - -#ifndef SQLITE_OMIT_AUTHORIZATION - /* Creating a virtual table invokes the authorization callback twice. - ** The first invocation, to obtain permission to INSERT a row into the - ** sqlite_schema table, has already been made by sqlite3StartTable(). - ** The second call, to obtain permission to create the table, is made now. - */ - if( pTable->azModuleArg ){ - int iDb = sqlite3SchemaToIndex(db, pTable->pSchema); - assert( iDb>=0 ); /* The database the table is being created in */ - sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, - pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName); - } -#endif -} - -/* -** This routine takes the module argument that has been accumulating -** in pParse->zArg[] and appends it to the list of arguments on the -** virtual table currently under construction in pParse->pTable. -*/ -static void addArgumentToVtab(Parse *pParse){ - if( pParse->sArg.z && pParse->pNewTable ){ - const char *z = (const char*)pParse->sArg.z; - int n = pParse->sArg.n; - sqlite3 *db = pParse->db; - addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); - } -} - -/* -** The parser calls this routine after the CREATE VIRTUAL TABLE statement -** has been completely parsed. -*/ -SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ - Table *pTab = pParse->pNewTable; /* The table being constructed */ - sqlite3 *db = pParse->db; /* The database connection */ - - if( pTab==0 ) return; - addArgumentToVtab(pParse); - pParse->sArg.z = 0; - if( pTab->nModuleArg<1 ) return; - - /* If the CREATE VIRTUAL TABLE statement is being entered for the - ** first time (in other words if the virtual table is actually being - ** created now instead of just being read out of sqlite_schema) then - ** do additional initialization work and store the statement text - ** in the sqlite_schema table. - */ - if( !db->init.busy ){ - char *zStmt; - char *zWhere; - int iDb; - int iReg; - Vdbe *v; - - sqlite3MayAbort(pParse); - - /* Compute the complete text of the CREATE VIRTUAL TABLE statement */ - if( pEnd ){ - pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n; - } - zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken); - - /* A slot for the record has already been allocated in the - ** schema table. We just need to update that slot with all - ** the information we've collected. - ** - ** The VM register number pParse->regRowid holds the rowid of an - ** entry in the sqlite_schema table tht was created for this vtab - ** by sqlite3StartTable(). - */ - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - sqlite3NestedParse(pParse, - "UPDATE %Q." DFLT_SCHEMA_TABLE " " - "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " - "WHERE rowid=#%d", - db->aDb[iDb].zDbSName, - pTab->zName, - pTab->zName, - zStmt, - pParse->regRowid - ); - v = sqlite3GetVdbe(pParse); - sqlite3ChangeCookie(pParse, iDb); - - sqlite3VdbeAddOp0(v, OP_Expire); - zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt); - sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); - sqlite3DbFree(db, zStmt); - - iReg = ++pParse->nMem; - sqlite3VdbeLoadString(v, iReg, pTab->zName); - sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg); - } - - /* If we are rereading the sqlite_schema table create the in-memory - ** record of the table. The xConnect() method is not called until - ** the first time the virtual table is used in an SQL statement. This - ** allows a schema that contains virtual tables to be loaded before - ** the required virtual table implementations are registered. */ - else { - Table *pOld; - Schema *pSchema = pTab->pSchema; - const char *zName = pTab->zName; - assert( sqlite3SchemaMutexHeld(db, 0, pSchema) ); - pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab); - if( pOld ){ - sqlite3OomFault(db); - assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */ - return; - } - pParse->pNewTable = 0; - } -} - -/* -** The parser calls this routine when it sees the first token -** of an argument to the module name in a CREATE VIRTUAL TABLE statement. -*/ -SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){ - addArgumentToVtab(pParse); - pParse->sArg.z = 0; - pParse->sArg.n = 0; -} - -/* -** The parser calls this routine for each token after the first token -** in an argument to the module name in a CREATE VIRTUAL TABLE statement. -*/ -SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){ - Token *pArg = &pParse->sArg; - if( pArg->z==0 ){ - pArg->z = p->z; - pArg->n = p->n; - }else{ - assert(pArg->z <= p->z); - pArg->n = (int)(&p->z[p->n] - pArg->z); - } -} - -/* -** Invoke a virtual table constructor (either xCreate or xConnect). The -** pointer to the function to invoke is passed as the fourth parameter -** to this procedure. -*/ -static int vtabCallConstructor( - sqlite3 *db, - Table *pTab, - Module *pMod, - int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**), - char **pzErr -){ - VtabCtx sCtx; - VTable *pVTable; - int rc; - const char *const*azArg = (const char *const*)pTab->azModuleArg; - int nArg = pTab->nModuleArg; - char *zErr = 0; - char *zModuleName; - int iDb; - VtabCtx *pCtx; - - /* Check that the virtual-table is not already being initialized */ - for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){ - if( pCtx->pTab==pTab ){ - *pzErr = sqlite3MPrintf(db, - "vtable constructor called recursively: %s", pTab->zName - ); - return SQLITE_LOCKED; - } - } - - zModuleName = sqlite3DbStrDup(db, pTab->zName); - if( !zModuleName ){ - return SQLITE_NOMEM_BKPT; - } - - pVTable = sqlite3MallocZero(sizeof(VTable)); - if( !pVTable ){ - sqlite3OomFault(db); - sqlite3DbFree(db, zModuleName); - return SQLITE_NOMEM_BKPT; - } - pVTable->db = db; - pVTable->pMod = pMod; - pVTable->eVtabRisk = SQLITE_VTABRISK_Normal; - - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - pTab->azModuleArg[1] = db->aDb[iDb].zDbSName; - - /* Invoke the virtual table constructor */ - assert( &db->pVtabCtx ); - assert( xConstruct ); - sCtx.pTab = pTab; - sCtx.pVTable = pVTable; - sCtx.pPrior = db->pVtabCtx; - sCtx.bDeclared = 0; - db->pVtabCtx = &sCtx; - rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr); - db->pVtabCtx = sCtx.pPrior; - if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); - assert( sCtx.pTab==pTab ); - - if( SQLITE_OK!=rc ){ - if( zErr==0 ){ - *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName); - }else { - *pzErr = sqlite3MPrintf(db, "%s", zErr); - sqlite3_free(zErr); - } - sqlite3DbFree(db, pVTable); - }else if( ALWAYS(pVTable->pVtab) ){ - /* Justification of ALWAYS(): A correct vtab constructor must allocate - ** the sqlite3_vtab object if successful. */ - memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0])); - pVTable->pVtab->pModule = pMod->pModule; - pMod->nRefModule++; - pVTable->nRef = 1; - if( sCtx.bDeclared==0 ){ - const char *zFormat = "vtable constructor did not declare schema: %s"; - *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName); - sqlite3VtabUnlock(pVTable); - rc = SQLITE_ERROR; - }else{ - int iCol; - u16 oooHidden = 0; - /* If everything went according to plan, link the new VTable structure - ** into the linked list headed by pTab->pVTable. Then loop through the - ** columns of the table to see if any of them contain the token "hidden". - ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from - ** the type string. */ - pVTable->pNext = pTab->pVTable; - pTab->pVTable = pVTable; - - for(iCol=0; iColnCol; iCol++){ - char *zType = sqlite3ColumnType(&pTab->aCol[iCol], ""); - int nType; - int i = 0; - nType = sqlite3Strlen30(zType); - for(i=0; i0 ){ - assert(zType[i-1]==' '); - zType[i-1] = '\0'; - } - pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN; - oooHidden = TF_OOOHidden; - }else{ - pTab->tabFlags |= oooHidden; - } - } - } - } - - sqlite3DbFree(db, zModuleName); - return rc; -} - -/* -** This function is invoked by the parser to call the xConnect() method -** of the virtual table pTab. If an error occurs, an error code is returned -** and an error left in pParse. -** -** This call is a no-op if table pTab is not a virtual table. -*/ -SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ - sqlite3 *db = pParse->db; - const char *zMod; - Module *pMod; - int rc; - - assert( pTab ); - if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){ - return SQLITE_OK; - } - - /* Locate the required virtual table module */ - zMod = pTab->azModuleArg[0]; - pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); - - if( !pMod ){ - const char *zModule = pTab->azModuleArg[0]; - sqlite3ErrorMsg(pParse, "no such module: %s", zModule); - rc = SQLITE_ERROR; - }else{ - char *zErr = 0; - rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr); - if( rc!=SQLITE_OK ){ - sqlite3ErrorMsg(pParse, "%s", zErr); - pParse->rc = rc; - } - sqlite3DbFree(db, zErr); - } - - return rc; -} -/* -** Grow the db->aVTrans[] array so that there is room for at least one -** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise. -*/ -static int growVTrans(sqlite3 *db){ - const int ARRAY_INCR = 5; - - /* Grow the sqlite3.aVTrans array if required */ - if( (db->nVTrans%ARRAY_INCR)==0 ){ - VTable **aVTrans; - sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)* - ((sqlite3_int64)db->nVTrans + ARRAY_INCR); - aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); - if( !aVTrans ){ - return SQLITE_NOMEM_BKPT; - } - memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR); - db->aVTrans = aVTrans; - } - - return SQLITE_OK; -} - -/* -** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should -** have already been reserved using growVTrans(). -*/ -static void addToVTrans(sqlite3 *db, VTable *pVTab){ - /* Add pVtab to the end of sqlite3.aVTrans */ - db->aVTrans[db->nVTrans++] = pVTab; - sqlite3VtabLock(pVTab); -} - -/* -** This function is invoked by the vdbe to call the xCreate method -** of the virtual table named zTab in database iDb. -** -** If an error occurs, *pzErr is set to point to an English language -** description of the error and an SQLITE_XXX error code is returned. -** In this case the caller must call sqlite3DbFree(db, ) on *pzErr. -*/ -SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){ - int rc = SQLITE_OK; - Table *pTab; - Module *pMod; - const char *zMod; - - pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); - assert( pTab && IsVirtual(pTab) && !pTab->pVTable ); - - /* Locate the required virtual table module */ - zMod = pTab->azModuleArg[0]; - pMod = (Module*)sqlite3HashFind(&db->aModule, zMod); - - /* If the module has been registered and includes a Create method, - ** invoke it now. If the module has not been registered, return an - ** error. Otherwise, do nothing. - */ - if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){ - *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod); - rc = SQLITE_ERROR; - }else{ - rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr); - } - - /* Justification of ALWAYS(): The xConstructor method is required to - ** create a valid sqlite3_vtab if it returns SQLITE_OK. */ - if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){ - rc = growVTrans(db); - if( rc==SQLITE_OK ){ - addToVTrans(db, sqlite3GetVTable(db, pTab)); - } - } - - return rc; -} - -/* -** This function is used to set the schema of a virtual table. It is only -** valid to call this function from within the xCreate() or xConnect() of a -** virtual table module. -*/ -SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ - VtabCtx *pCtx; - int rc = SQLITE_OK; - Table *pTab; - char *zErr = 0; - Parse sParse; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - pCtx = db->pVtabCtx; - if( !pCtx || pCtx->bDeclared ){ - sqlite3Error(db, SQLITE_MISUSE); - sqlite3_mutex_leave(db->mutex); - return SQLITE_MISUSE_BKPT; - } - pTab = pCtx->pTab; - assert( IsVirtual(pTab) ); - - memset(&sParse, 0, sizeof(sParse)); - sParse.eParseMode = PARSE_MODE_DECLARE_VTAB; - sParse.db = db; - sParse.nQueryLoop = 1; - if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr) - && sParse.pNewTable - && !db->mallocFailed - && !sParse.pNewTable->pSelect - && !IsVirtual(sParse.pNewTable) - ){ - if( !pTab->aCol ){ - Table *pNew = sParse.pNewTable; - Index *pIdx; - pTab->aCol = pNew->aCol; - pTab->nCol = pNew->nCol; - pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid); - pNew->nCol = 0; - pNew->aCol = 0; - assert( pTab->pIndex==0 ); - assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 ); - if( !HasRowid(pNew) - && pCtx->pVTable->pMod->pModule->xUpdate!=0 - && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1 - ){ - /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0) - ** or else must have a single-column PRIMARY KEY */ - rc = SQLITE_ERROR; - } - pIdx = pNew->pIndex; - if( pIdx ){ - assert( pIdx->pNext==0 ); - pTab->pIndex = pIdx; - pNew->pIndex = 0; - pIdx->pTable = pTab; - } - } - pCtx->bDeclared = 1; - }else{ - sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr); - sqlite3DbFree(db, zErr); - rc = SQLITE_ERROR; - } - sParse.eParseMode = PARSE_MODE_NORMAL; - - if( sParse.pVdbe ){ - sqlite3VdbeFinalize(sParse.pVdbe); - } - sqlite3DeleteTable(db, sParse.pNewTable); - sqlite3ParserReset(&sParse); - - assert( (rc&0xff)==rc ); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** This function is invoked by the vdbe to call the xDestroy method -** of the virtual table named zTab in database iDb. This occurs -** when a DROP TABLE is mentioned. -** -** This call is a no-op if zTab is not a virtual table. -*/ -SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){ - int rc = SQLITE_OK; - Table *pTab; - - pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName); - if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){ - VTable *p; - int (*xDestroy)(sqlite3_vtab *); - for(p=pTab->pVTable; p; p=p->pNext){ - assert( p->pVtab ); - if( p->pVtab->nRef>0 ){ - return SQLITE_LOCKED; - } - } - p = vtabDisconnectAll(db, pTab); - xDestroy = p->pMod->pModule->xDestroy; - if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect; - assert( xDestroy!=0 ); - pTab->nTabRef++; - rc = xDestroy(p->pVtab); - /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */ - if( rc==SQLITE_OK ){ - assert( pTab->pVTable==p && p->pNext==0 ); - p->pVtab = 0; - pTab->pVTable = 0; - sqlite3VtabUnlock(p); - } - sqlite3DeleteTable(db, pTab); - } - - return rc; -} - -/* -** This function invokes either the xRollback or xCommit method -** of each of the virtual tables in the sqlite3.aVTrans array. The method -** called is identified by the second argument, "offset", which is -** the offset of the method to call in the sqlite3_module structure. -** -** The array is cleared after invoking the callbacks. -*/ -static void callFinaliser(sqlite3 *db, int offset){ - int i; - if( db->aVTrans ){ - VTable **aVTrans = db->aVTrans; - db->aVTrans = 0; - for(i=0; inVTrans; i++){ - VTable *pVTab = aVTrans[i]; - sqlite3_vtab *p = pVTab->pVtab; - if( p ){ - int (*x)(sqlite3_vtab *); - x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset); - if( x ) x(p); - } - pVTab->iSavepoint = 0; - sqlite3VtabUnlock(pVTab); - } - sqlite3DbFree(db, aVTrans); - db->nVTrans = 0; - } -} - -/* -** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans -** array. Return the error code for the first error that occurs, or -** SQLITE_OK if all xSync operations are successful. -** -** If an error message is available, leave it in p->zErrMsg. -*/ -SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){ - int i; - int rc = SQLITE_OK; - VTable **aVTrans = db->aVTrans; - - db->aVTrans = 0; - for(i=0; rc==SQLITE_OK && inVTrans; i++){ - int (*x)(sqlite3_vtab *); - sqlite3_vtab *pVtab = aVTrans[i]->pVtab; - if( pVtab && (x = pVtab->pModule->xSync)!=0 ){ - rc = x(pVtab); - sqlite3VtabImportErrmsg(p, pVtab); - } - } - db->aVTrans = aVTrans; - return rc; -} - -/* -** Invoke the xRollback method of all virtual tables in the -** sqlite3.aVTrans array. Then clear the array itself. -*/ -SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ - callFinaliser(db, offsetof(sqlite3_module,xRollback)); - return SQLITE_OK; -} - -/* -** Invoke the xCommit method of all virtual tables in the -** sqlite3.aVTrans array. Then clear the array itself. -*/ -SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){ - callFinaliser(db, offsetof(sqlite3_module,xCommit)); - return SQLITE_OK; -} - -/* -** If the virtual table pVtab supports the transaction interface -** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is -** not currently open, invoke the xBegin method now. -** -** If the xBegin call is successful, place the sqlite3_vtab pointer -** in the sqlite3.aVTrans array. -*/ -SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){ - int rc = SQLITE_OK; - const sqlite3_module *pModule; - - /* Special case: If db->aVTrans is NULL and db->nVTrans is greater - ** than zero, then this function is being called from within a - ** virtual module xSync() callback. It is illegal to write to - ** virtual module tables in this case, so return SQLITE_LOCKED. - */ - if( sqlite3VtabInSync(db) ){ - return SQLITE_LOCKED; - } - if( !pVTab ){ - return SQLITE_OK; - } - pModule = pVTab->pVtab->pModule; - - if( pModule->xBegin ){ - int i; - - /* If pVtab is already in the aVTrans array, return early */ - for(i=0; inVTrans; i++){ - if( db->aVTrans[i]==pVTab ){ - return SQLITE_OK; - } - } - - /* Invoke the xBegin method. If successful, add the vtab to the - ** sqlite3.aVTrans[] array. */ - rc = growVTrans(db); - if( rc==SQLITE_OK ){ - rc = pModule->xBegin(pVTab->pVtab); - if( rc==SQLITE_OK ){ - int iSvpt = db->nStatement + db->nSavepoint; - addToVTrans(db, pVTab); - if( iSvpt && pModule->xSavepoint ){ - pVTab->iSavepoint = iSvpt; - rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1); - } - } - } - } - return rc; -} - -/* -** Invoke either the xSavepoint, xRollbackTo or xRelease method of all -** virtual tables that currently have an open transaction. Pass iSavepoint -** as the second argument to the virtual table method invoked. -** -** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is -** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is -** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with -** an open transaction is invoked. -** -** If any virtual table method returns an error code other than SQLITE_OK, -** processing is abandoned and the error returned to the caller of this -** function immediately. If all calls to virtual table methods are successful, -** SQLITE_OK is returned. -*/ -SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){ - int rc = SQLITE_OK; - - assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN ); - assert( iSavepoint>=-1 ); - if( db->aVTrans ){ - int i; - for(i=0; rc==SQLITE_OK && inVTrans; i++){ - VTable *pVTab = db->aVTrans[i]; - const sqlite3_module *pMod = pVTab->pMod->pModule; - if( pVTab->pVtab && pMod->iVersion>=2 ){ - int (*xMethod)(sqlite3_vtab *, int); - sqlite3VtabLock(pVTab); - switch( op ){ - case SAVEPOINT_BEGIN: - xMethod = pMod->xSavepoint; - pVTab->iSavepoint = iSavepoint+1; - break; - case SAVEPOINT_ROLLBACK: - xMethod = pMod->xRollbackTo; - break; - default: - xMethod = pMod->xRelease; - break; - } - if( xMethod && pVTab->iSavepoint>iSavepoint ){ - rc = xMethod(pVTab->pVtab, iSavepoint); - } - sqlite3VtabUnlock(pVTab); - } - } - } - return rc; -} - -/* -** The first parameter (pDef) is a function implementation. The -** second parameter (pExpr) is the first argument to this function. -** If pExpr is a column in a virtual table, then let the virtual -** table implementation have an opportunity to overload the function. -** -** This routine is used to allow virtual table implementations to -** overload MATCH, LIKE, GLOB, and REGEXP operators. -** -** Return either the pDef argument (indicating no change) or a -** new FuncDef structure that is marked as ephemeral using the -** SQLITE_FUNC_EPHEM flag. -*/ -SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( - sqlite3 *db, /* Database connection for reporting malloc problems */ - FuncDef *pDef, /* Function to possibly overload */ - int nArg, /* Number of arguments to the function */ - Expr *pExpr /* First argument to the function */ -){ - Table *pTab; - sqlite3_vtab *pVtab; - sqlite3_module *pMod; - void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0; - void *pArg = 0; - FuncDef *pNew; - int rc = 0; - - /* Check to see the left operand is a column in a virtual table */ - if( NEVER(pExpr==0) ) return pDef; - if( pExpr->op!=TK_COLUMN ) return pDef; - pTab = pExpr->y.pTab; - if( pTab==0 ) return pDef; - if( !IsVirtual(pTab) ) return pDef; - pVtab = sqlite3GetVTable(db, pTab)->pVtab; - assert( pVtab!=0 ); - assert( pVtab->pModule!=0 ); - pMod = (sqlite3_module *)pVtab->pModule; - if( pMod->xFindFunction==0 ) return pDef; - - /* Call the xFindFunction method on the virtual table implementation - ** to see if the implementation wants to overload this function. - ** - ** Though undocumented, we have historically always invoked xFindFunction - ** with an all lower-case function name. Continue in this tradition to - ** avoid any chance of an incompatibility. - */ -#ifdef SQLITE_DEBUG - { - int i; - for(i=0; pDef->zName[i]; i++){ - unsigned char x = (unsigned char)pDef->zName[i]; - assert( x==sqlite3UpperToLower[x] ); - } - } -#endif - rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg); - if( rc==0 ){ - return pDef; - } - - /* Create a new ephemeral function definition for the overloaded - ** function */ - pNew = sqlite3DbMallocZero(db, sizeof(*pNew) - + sqlite3Strlen30(pDef->zName) + 1); - if( pNew==0 ){ - return pDef; - } - *pNew = *pDef; - pNew->zName = (const char*)&pNew[1]; - memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1); - pNew->xSFunc = xSFunc; - pNew->pUserData = pArg; - pNew->funcFlags |= SQLITE_FUNC_EPHEM; - return pNew; -} - -/* -** Make sure virtual table pTab is contained in the pParse->apVirtualLock[] -** array so that an OP_VBegin will get generated for it. Add pTab to the -** array if it is missing. If pTab is already in the array, this routine -** is a no-op. -*/ -SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - int i, n; - Table **apVtabLock; - - assert( IsVirtual(pTab) ); - for(i=0; inVtabLock; i++){ - if( pTab==pToplevel->apVtabLock[i] ) return; - } - n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]); - apVtabLock = sqlite3Realloc(pToplevel->apVtabLock, n); - if( apVtabLock ){ - pToplevel->apVtabLock = apVtabLock; - pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab; - }else{ - sqlite3OomFault(pToplevel->db); - } -} - -/* -** Check to see if virtual table module pMod can be have an eponymous -** virtual table instance. If it can, create one if one does not already -** exist. Return non-zero if the eponymous virtual table instance exists -** when this routine returns, and return zero if it does not exist. -** -** An eponymous virtual table instance is one that is named after its -** module, and more importantly, does not require a CREATE VIRTUAL TABLE -** statement in order to come into existance. Eponymous virtual table -** instances always exist. They cannot be DROP-ed. -** -** Any virtual table module for which xConnect and xCreate are the same -** method can have an eponymous virtual table instance. -*/ -SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ - const sqlite3_module *pModule = pMod->pModule; - Table *pTab; - char *zErr = 0; - int rc; - sqlite3 *db = pParse->db; - if( pMod->pEpoTab ) return 1; - if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0; - pTab = sqlite3DbMallocZero(db, sizeof(Table)); - if( pTab==0 ) return 0; - pTab->zName = sqlite3DbStrDup(db, pMod->zName); - if( pTab->zName==0 ){ - sqlite3DbFree(db, pTab); - return 0; - } - pMod->pEpoTab = pTab; - pTab->nTabRef = 1; - pTab->pSchema = db->aDb[0].pSchema; - assert( pTab->nModuleArg==0 ); - pTab->iPKey = -1; - addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName)); - addModuleArgument(pParse, pTab, 0); - addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName)); - rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr); - if( rc ){ - sqlite3ErrorMsg(pParse, "%s", zErr); - sqlite3DbFree(db, zErr); - sqlite3VtabEponymousTableClear(db, pMod); - return 0; - } - return 1; -} - -/* -** Erase the eponymous virtual table instance associated with -** virtual table module pMod, if it exists. -*/ -SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){ - Table *pTab = pMod->pEpoTab; - if( pTab!=0 ){ - /* Mark the table as Ephemeral prior to deleting it, so that the - ** sqlite3DeleteTable() routine will know that it is not stored in - ** the schema. */ - pTab->tabFlags |= TF_Ephemeral; - sqlite3DeleteTable(db, pTab); - pMod->pEpoTab = 0; - } -} - -/* -** Return the ON CONFLICT resolution mode in effect for the virtual -** table update operation currently in progress. -** -** The results of this routine are undefined unless it is called from -** within an xUpdate method. -*/ -SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){ - static const unsigned char aMap[] = { - SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE - }; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 ); - assert( OE_Ignore==4 && OE_Replace==5 ); - assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 ); - return (int)aMap[db->vtabOnConflict-1]; -} - -/* -** Call from within the xCreate() or xConnect() methods to provide -** the SQLite core with additional information about the behavior -** of the virtual table being implemented. -*/ -SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){ - va_list ap; - int rc = SQLITE_OK; - VtabCtx *p; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - p = db->pVtabCtx; - if( !p ){ - rc = SQLITE_MISUSE_BKPT; - }else{ - assert( p->pTab==0 || IsVirtual(p->pTab) ); - va_start(ap, op); - switch( op ){ - case SQLITE_VTAB_CONSTRAINT_SUPPORT: { - p->pVTable->bConstraint = (u8)va_arg(ap, int); - break; - } - case SQLITE_VTAB_INNOCUOUS: { - p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low; - break; - } - case SQLITE_VTAB_DIRECTONLY: { - p->pVTable->eVtabRisk = SQLITE_VTABRISK_High; - break; - } - default: { - rc = SQLITE_MISUSE_BKPT; - break; - } - } - va_end(ap); - } - - if( rc!=SQLITE_OK ) sqlite3Error(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -/************** End of vtab.c ************************************************/ -/************** Begin file wherecode.c ***************************************/ -/* -** 2015-06-06 -** -** 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 contains C code that generates VDBE code used to process -** the WHERE clause of SQL statements. -** -** This file was split off from where.c on 2015-06-06 in order to reduce the -** size of where.c and make it easier to edit. This file contains the routines -** that actually generate the bulk of the WHERE loop code. The original where.c -** file retains the code that does query planning and analysis. -*/ -/* #include "sqliteInt.h" */ -/************** Include whereInt.h in the middle of wherecode.c **************/ -/************** Begin file whereInt.h ****************************************/ -/* -** 2013-11-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 structure and macro definitions for the query -** planner logic in "where.c". These definitions are broken out into -** a separate source file for easier editing. -*/ -#ifndef SQLITE_WHEREINT_H -#define SQLITE_WHEREINT_H - -/* -** Trace output macros -*/ -#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) -/***/ extern int sqlite3WhereTrace; -#endif -#if defined(SQLITE_DEBUG) \ - && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE)) -# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X -# define WHERETRACE_ENABLED 1 -#else -# define WHERETRACE(K,X) -#endif - -/* Forward references -*/ -typedef struct WhereClause WhereClause; -typedef struct WhereMaskSet WhereMaskSet; -typedef struct WhereOrInfo WhereOrInfo; -typedef struct WhereAndInfo WhereAndInfo; -typedef struct WhereLevel WhereLevel; -typedef struct WhereLoop WhereLoop; -typedef struct WherePath WherePath; -typedef struct WhereTerm WhereTerm; -typedef struct WhereLoopBuilder WhereLoopBuilder; -typedef struct WhereScan WhereScan; -typedef struct WhereOrCost WhereOrCost; -typedef struct WhereOrSet WhereOrSet; - -/* -** This object contains information needed to implement a single nested -** loop in WHERE clause. -** -** Contrast this object with WhereLoop. This object describes the -** implementation of the loop. WhereLoop describes the algorithm. -** This object contains a pointer to the WhereLoop algorithm as one of -** its elements. -** -** The WhereInfo object contains a single instance of this object for -** each term in the FROM clause (which is to say, for each of the -** nested loops as implemented). The order of WhereLevel objects determines -** the loop nested order, with WhereInfo.a[0] being the outer loop and -** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop. -*/ -struct WhereLevel { - int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */ - int iTabCur; /* The VDBE cursor used to access the table */ - int iIdxCur; /* The VDBE cursor used to access pIdx */ - int addrBrk; /* Jump here to break out of the loop */ - int addrNxt; /* Jump here to start the next IN combination */ - int addrSkip; /* Jump here for next iteration of skip-scan */ - int addrCont; /* Jump here to continue with the next loop cycle */ - int addrFirst; /* First instruction of interior of the loop */ - int addrBody; /* Beginning of the body of this loop */ - int regBignull; /* big-null flag reg. True if a NULL-scan is needed */ - int addrBignull; /* Jump here for next part of big-null scan */ -#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS - u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */ - int addrLikeRep; /* LIKE range processing address */ -#endif - u8 iFrom; /* Which entry in the FROM clause */ - u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */ - int p1, p2; /* Operands of the opcode used to end the loop */ - union { /* Information that depends on pWLoop->wsFlags */ - struct { - int nIn; /* Number of entries in aInLoop[] */ - struct InLoop { - int iCur; /* The VDBE cursor used by this IN operator */ - int addrInTop; /* Top of the IN loop */ - int iBase; /* Base register of multi-key index record */ - int nPrefix; /* Number of prior entires in the key */ - u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */ - } *aInLoop; /* Information about each nested IN operator */ - } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */ - Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */ - } u; - struct WhereLoop *pWLoop; /* The selected WhereLoop object */ - Bitmask notReady; /* FROM entries not usable at this level */ -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - int addrVisit; /* Address at which row is visited */ -#endif -}; - -/* -** Each instance of this object represents an algorithm for evaluating one -** term of a join. Every term of the FROM clause will have at least -** one corresponding WhereLoop object (unless INDEXED BY constraints -** prevent a query solution - which is an error) and many terms of the -** FROM clause will have multiple WhereLoop objects, each describing a -** potential way of implementing that FROM-clause term, together with -** dependencies and cost estimates for using the chosen algorithm. -** -** Query planning consists of building up a collection of these WhereLoop -** objects, then computing a particular sequence of WhereLoop objects, with -** one WhereLoop object per FROM clause term, that satisfy all dependencies -** and that minimize the overall cost. -*/ -struct WhereLoop { - Bitmask prereq; /* Bitmask of other loops that must run first */ - Bitmask maskSelf; /* Bitmask identifying table iTab */ -#ifdef SQLITE_DEBUG - char cId; /* Symbolic ID of this loop for debugging use */ -#endif - u8 iTab; /* Position in FROM clause of table for this loop */ - u8 iSortIdx; /* Sorting index number. 0==None */ - LogEst rSetup; /* One-time setup cost (ex: create transient index) */ - LogEst rRun; /* Cost of running each loop */ - LogEst nOut; /* Estimated number of output rows */ - union { - struct { /* Information for internal btree tables */ - u16 nEq; /* Number of equality constraints */ - u16 nBtm; /* Size of BTM vector */ - u16 nTop; /* Size of TOP vector */ - u16 nDistinctCol; /* Index columns used to sort for DISTINCT */ - Index *pIndex; /* Index used, or NULL */ - } btree; - struct { /* Information for virtual tables */ - int idxNum; /* Index number */ - u8 needFree; /* True if sqlite3_free(idxStr) is needed */ - i8 isOrdered; /* True if satisfies ORDER BY */ - u16 omitMask; /* Terms that may be omitted */ - char *idxStr; /* Index identifier string */ - } vtab; - } u; - u32 wsFlags; /* WHERE_* flags describing the plan */ - u16 nLTerm; /* Number of entries in aLTerm[] */ - u16 nSkip; /* Number of NULL aLTerm[] entries */ - /**** whereLoopXfer() copies fields above ***********************/ -# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot) - u16 nLSlot; /* Number of slots allocated for aLTerm[] */ - WhereTerm **aLTerm; /* WhereTerms used */ - WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */ - WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */ -}; - -/* This object holds the prerequisites and the cost of running a -** subquery on one operand of an OR operator in the WHERE clause. -** See WhereOrSet for additional information -*/ -struct WhereOrCost { - Bitmask prereq; /* Prerequisites */ - LogEst rRun; /* Cost of running this subquery */ - LogEst nOut; /* Number of outputs for this subquery */ -}; - -/* The WhereOrSet object holds a set of possible WhereOrCosts that -** correspond to the subquery(s) of OR-clause processing. Only the -** best N_OR_COST elements are retained. -*/ -#define N_OR_COST 3 -struct WhereOrSet { - u16 n; /* Number of valid a[] entries */ - WhereOrCost a[N_OR_COST]; /* Set of best costs */ -}; - -/* -** Each instance of this object holds a sequence of WhereLoop objects -** that implement some or all of a query plan. -** -** Think of each WhereLoop object as a node in a graph with arcs -** showing dependencies and costs for travelling between nodes. (That is -** not a completely accurate description because WhereLoop costs are a -** vector, not a scalar, and because dependencies are many-to-one, not -** one-to-one as are graph nodes. But it is a useful visualization aid.) -** Then a WherePath object is a path through the graph that visits some -** or all of the WhereLoop objects once. -** -** The "solver" works by creating the N best WherePath objects of length -** 1. Then using those as a basis to compute the N best WherePath objects -** of length 2. And so forth until the length of WherePaths equals the -** number of nodes in the FROM clause. The best (lowest cost) WherePath -** at the end is the chosen query plan. -*/ -struct WherePath { - Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */ - Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */ - LogEst nRow; /* Estimated number of rows generated by this path */ - LogEst rCost; /* Total cost of this path */ - LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */ - i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */ - WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */ -}; - -/* -** The query generator uses an array of instances of this structure to -** help it analyze the subexpressions of the WHERE clause. Each WHERE -** clause subexpression is separated from the others by AND operators, -** usually, or sometimes subexpressions separated by OR. -** -** All WhereTerms are collected into a single WhereClause structure. -** The following identity holds: -** -** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm -** -** When a term is of the form: -** -** X -** -** where X is a column name and is one of certain operators, -** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the -** cursor number and column number for X. WhereTerm.eOperator records -** the using a bitmask encoding defined by WO_xxx below. The -** use of a bitmask encoding for the operator allows us to search -** quickly for terms that match any of several different operators. -** -** A WhereTerm might also be two or more subterms connected by OR: -** -** (t1.X ) OR (t1.Y ) OR .... -** -** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR -** and the WhereTerm.u.pOrInfo field points to auxiliary information that -** is collected about the OR clause. -** -** If a term in the WHERE clause does not match either of the two previous -** categories, then eOperator==0. The WhereTerm.pExpr field is still set -** to the original subexpression content and wtFlags is set up appropriately -** but no other fields in the WhereTerm object are meaningful. -** -** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers, -** but they do so indirectly. A single WhereMaskSet structure translates -** cursor number into bits and the translated bit is stored in the prereq -** fields. The translation is used in order to maximize the number of -** bits that will fit in a Bitmask. The VDBE cursor numbers might be -** spread out over the non-negative integers. For example, the cursor -** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet -** translates these sparse cursor numbers into consecutive integers -** beginning with 0 in order to make the best possible use of the available -** bits in the Bitmask. So, in the example above, the cursor numbers -** would be mapped into integers 0 through 7. -** -** The number of terms in a join is limited by the number of bits -** in prereqRight and prereqAll. The default is 64 bits, hence SQLite -** is only able to process joins with 64 or fewer tables. -*/ -struct WhereTerm { - Expr *pExpr; /* Pointer to the subexpression that is this term */ - WhereClause *pWC; /* The clause this term is part of */ - LogEst truthProb; /* Probability of truth for this expression */ - u16 wtFlags; /* TERM_xxx bit flags. See below */ - u16 eOperator; /* A WO_xx value describing */ - u8 nChild; /* Number of children that must disable us */ - u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */ - int iParent; /* Disable pWC->a[iParent] when this term disabled */ - int leftCursor; /* Cursor number of X in "X " */ - int iField; /* Field in (?,?,?) IN (SELECT...) vector */ - union { - int leftColumn; /* Column number of X in "X " */ - WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */ - WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */ - } u; - Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */ - Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */ -}; - -/* -** Allowed values of WhereTerm.wtFlags -*/ -#define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(db, pExpr) */ -#define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */ -#define TERM_CODED 0x0004 /* This term is already coded */ -#define TERM_COPIED 0x0008 /* Has a child */ -#define TERM_ORINFO 0x0010 /* Need to free the WhereTerm.u.pOrInfo object */ -#define TERM_ANDINFO 0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */ -#define TERM_OR_OK 0x0040 /* Used during OR-clause processing */ -#ifdef SQLITE_ENABLE_STAT4 -# define TERM_VNULL 0x0080 /* Manufactured x>NULL or x<=NULL term */ -#else -# define TERM_VNULL 0x0000 /* Disabled if not using stat4 */ -#endif -#define TERM_LIKEOPT 0x0100 /* Virtual terms from the LIKE optimization */ -#define TERM_LIKECOND 0x0200 /* Conditionally this LIKE operator term */ -#define TERM_LIKE 0x0400 /* The original LIKE operator */ -#define TERM_IS 0x0800 /* Term.pExpr is an IS operator */ -#define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */ -#define TERM_HEURTRUTH 0x2000 /* Heuristic truthProb used */ -#ifdef SQLITE_ENABLE_STAT4 -# define TERM_HIGHTRUTH 0x4000 /* Term excludes few rows */ -#else -# define TERM_HIGHTRUTH 0 /* Only used with STAT4 */ -#endif - -/* -** An instance of the WhereScan object is used as an iterator for locating -** terms in the WHERE clause that are useful to the query planner. -*/ -struct WhereScan { - WhereClause *pOrigWC; /* Original, innermost WhereClause */ - WhereClause *pWC; /* WhereClause currently being scanned */ - const char *zCollName; /* Required collating sequence, if not NULL */ - Expr *pIdxExpr; /* Search for this index expression */ - char idxaff; /* Must match this affinity, if zCollName!=NULL */ - unsigned char nEquiv; /* Number of entries in aEquiv[] */ - unsigned char iEquiv; /* Next unused slot in aEquiv[] */ - u32 opMask; /* Acceptable operators */ - int k; /* Resume scanning at this->pWC->a[this->k] */ - int aiCur[11]; /* Cursors in the equivalence class */ - i16 aiColumn[11]; /* Corresponding column number in the eq-class */ -}; - -/* -** An instance of the following structure holds all information about a -** WHERE clause. Mostly this is a container for one or more WhereTerms. -** -** Explanation of pOuter: For a WHERE clause of the form -** -** a AND ((b AND c) OR (d AND e)) AND f -** -** There are separate WhereClause objects for the whole clause and for -** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the -** subclauses points to the WhereClause object for the whole clause. -*/ -struct WhereClause { - WhereInfo *pWInfo; /* WHERE clause processing context */ - WhereClause *pOuter; /* Outer conjunction */ - u8 op; /* Split operator. TK_AND or TK_OR */ - u8 hasOr; /* True if any a[].eOperator is WO_OR */ - int nTerm; /* Number of terms */ - int nSlot; /* Number of entries in a[] */ - WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ -#if defined(SQLITE_SMALL_STACK) - WhereTerm aStatic[1]; /* Initial static space for a[] */ -#else - WhereTerm aStatic[8]; /* Initial static space for a[] */ -#endif -}; - -/* -** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to -** a dynamically allocated instance of the following structure. -*/ -struct WhereOrInfo { - WhereClause wc; /* Decomposition into subterms */ - Bitmask indexable; /* Bitmask of all indexable tables in the clause */ -}; - -/* -** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to -** a dynamically allocated instance of the following structure. -*/ -struct WhereAndInfo { - WhereClause wc; /* The subexpression broken out */ -}; - -/* -** An instance of the following structure keeps track of a mapping -** between VDBE cursor numbers and bits of the bitmasks in WhereTerm. -** -** The VDBE cursor numbers are small integers contained in -** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE -** clause, the cursor numbers might not begin with 0 and they might -** contain gaps in the numbering sequence. But we want to make maximum -** use of the bits in our bitmasks. This structure provides a mapping -** from the sparse cursor numbers into consecutive integers beginning -** with 0. -** -** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask -** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<3, 5->1, 8->2, 29->0, -** 57->5, 73->4. Or one of 719 other combinations might be used. It -** does not really matter. What is important is that sparse cursor -** numbers all get mapped into bit numbers that begin with 0 and contain -** no gaps. -*/ -struct WhereMaskSet { - int bVarSelect; /* Used by sqlite3WhereExprUsage() */ - int n; /* Number of assigned cursor values */ - int ix[BMS]; /* Cursor assigned to each bit */ -}; - -/* -** Initialize a WhereMaskSet object -*/ -#define initMaskSet(P) (P)->n=0 - -/* -** This object is a convenience wrapper holding all information needed -** to construct WhereLoop objects for a particular query. -*/ -struct WhereLoopBuilder { - WhereInfo *pWInfo; /* Information about this WHERE */ - WhereClause *pWC; /* WHERE clause terms */ - ExprList *pOrderBy; /* ORDER BY clause */ - WhereLoop *pNew; /* Template WhereLoop */ - WhereOrSet *pOrSet; /* Record best loops here, if not NULL */ -#ifdef SQLITE_ENABLE_STAT4 - UnpackedRecord *pRec; /* Probe for stat4 (if required) */ - int nRecValid; /* Number of valid fields currently in pRec */ -#endif - unsigned char bldFlags1; /* First set of SQLITE_BLDF_* flags */ - unsigned char bldFlags2; /* Second set of SQLITE_BLDF_* flags */ - unsigned int iPlanLimit; /* Search limiter */ -}; - -/* Allowed values for WhereLoopBuider.bldFlags */ -#define SQLITE_BLDF1_INDEXED 0x0001 /* An index is used */ -#define SQLITE_BLDF1_UNIQUE 0x0002 /* All keys of a UNIQUE index used */ - -#define SQLITE_BLDF2_2NDPASS 0x0004 /* Second builder pass needed */ - -/* The WhereLoopBuilder.iPlanLimit is used to limit the number of -** index+constraint combinations the query planner will consider for a -** particular query. If this parameter is unlimited, then certain -** pathological queries can spend excess time in the sqlite3WhereBegin() -** routine. The limit is high enough that is should not impact real-world -** queries. -** -** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit. The limit is -** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM -** clause is processed, so that every table in a join is guaranteed to be -** able to propose a some index+constraint combinations even if the initial -** baseline limit was exhausted by prior tables of the join. -*/ -#ifndef SQLITE_QUERY_PLANNER_LIMIT -# define SQLITE_QUERY_PLANNER_LIMIT 20000 -#endif -#ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR -# define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000 -#endif - -/* -** Each instance of this object records a change to a single node -** in an expression tree to cause that node to point to a column -** of an index rather than an expression or a virtual column. All -** such transformations need to be undone at the end of WHERE clause -** processing. -*/ -typedef struct WhereExprMod WhereExprMod; -struct WhereExprMod { - WhereExprMod *pNext; /* Next translation on a list of them all */ - Expr *pExpr; /* The Expr node that was transformed */ - Expr orig; /* Original value of the Expr node */ -}; - -/* -** The WHERE clause processing routine has two halves. The -** first part does the start of the WHERE loop and the second -** half does the tail of the WHERE loop. An instance of -** this structure is returned by the first half and passed -** into the second half to give some continuity. -** -** An instance of this object holds the complete state of the query -** planner. -*/ -struct WhereInfo { - Parse *pParse; /* Parsing and code generating context */ - SrcList *pTabList; /* List of tables in the join */ - ExprList *pOrderBy; /* The ORDER BY clause or NULL */ - ExprList *pResultSet; /* Result set of the query */ - Expr *pWhere; /* The complete WHERE clause */ - int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */ - int iContinue; /* Jump here to continue with next record */ - int iBreak; /* Jump here to break out of the loop */ - int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */ - u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */ - LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */ - u8 nLevel; /* Number of nested loop */ - i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */ - u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */ - u8 eDistinct; /* One of the WHERE_DISTINCT_* values */ - unsigned bDeferredSeek :1; /* Uses OP_DeferredSeek */ - unsigned untestedTerms :1; /* Not all WHERE terms resolved by outer loop */ - unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */ - unsigned sorted :1; /* True if really sorted (not just grouped) */ - LogEst nRowOut; /* Estimated number of output rows */ - int iTop; /* The very beginning of the WHERE loop */ - WhereLoop *pLoops; /* List of all WhereLoop objects */ - WhereExprMod *pExprMods; /* Expression modifications */ - Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ - WhereClause sWC; /* Decomposition of the WHERE clause */ - WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ - WhereLevel a[1]; /* Information about each nest loop in WHERE */ -}; - -/* -** Private interfaces - callable only by other where.c routines. -** -** where.c: -*/ -SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int); -#ifdef WHERETRACE_ENABLED -SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC); -SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm); -SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC); -#endif -SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( - WhereClause *pWC, /* The WHERE clause to be searched */ - int iCur, /* Cursor number of LHS */ - int iColumn, /* Column number of LHS */ - Bitmask notReady, /* RHS must not overlap with this mask */ - u32 op, /* Mask of WO_xx values describing operator */ - Index *pIdx /* Must be compatible with this index, if not NULL */ -); - -/* wherecode.c: */ -#ifndef SQLITE_OMIT_EXPLAIN -SQLITE_PRIVATE int sqlite3WhereExplainOneScan( - Parse *pParse, /* Parse context */ - SrcList *pTabList, /* Table list this loop refers to */ - WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ - u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ -); -#else -# define sqlite3WhereExplainOneScan(u,v,w,x) 0 -#endif /* SQLITE_OMIT_EXPLAIN */ -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS -SQLITE_PRIVATE void sqlite3WhereAddScanStatus( - Vdbe *v, /* Vdbe to add scanstatus entry to */ - SrcList *pSrclist, /* FROM clause pLvl reads data from */ - WhereLevel *pLvl, /* Level to add scanstatus() entry for */ - int addrExplain /* Address of OP_Explain (or 0) */ -); -#else -# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d) -#endif -SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( - Parse *pParse, /* Parsing context */ - Vdbe *v, /* Prepared statement under construction */ - WhereInfo *pWInfo, /* Complete information about the WHERE clause */ - int iLevel, /* Which level of pWInfo->a[] should be coded */ - WhereLevel *pLevel, /* The current level pointer */ - Bitmask notReady /* Which tables are currently available */ -); - -/* whereexpr.c: */ -SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*); -SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*); -SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8); -SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*); -SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*); -SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*); -SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*); -SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*); - - - - - -/* -** Bitmasks for the operators on WhereTerm objects. These are all -** operators that are of interest to the query planner. An -** OR-ed combination of these values can be used when searching for -** particular WhereTerms within a WhereClause. -** -** Value constraints: -** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ -** WO_LT == SQLITE_INDEX_CONSTRAINT_LT -** WO_LE == SQLITE_INDEX_CONSTRAINT_LE -** WO_GT == SQLITE_INDEX_CONSTRAINT_GT -** WO_GE == SQLITE_INDEX_CONSTRAINT_GE -*/ -#define WO_IN 0x0001 -#define WO_EQ 0x0002 -#define WO_LT (WO_EQ<<(TK_LT-TK_EQ)) -#define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) -#define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) -#define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) -#define WO_AUX 0x0040 /* Op useful to virtual tables only */ -#define WO_IS 0x0080 -#define WO_ISNULL 0x0100 -#define WO_OR 0x0200 /* Two or more OR-connected terms */ -#define WO_AND 0x0400 /* Two or more AND-connected terms */ -#define WO_EQUIV 0x0800 /* Of the form A==B, both columns */ -#define WO_NOOP 0x1000 /* This term does not restrict search space */ - -#define WO_ALL 0x1fff /* Mask of all possible WO_* values */ -#define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */ - -/* -** These are definitions of bits in the WhereLoop.wsFlags field. -** The particular combination of bits in each WhereLoop help to -** determine the algorithm that WhereLoop represents. -*/ -#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */ -#define WHERE_COLUMN_RANGE 0x00000002 /* xEXPR */ -#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */ -#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */ -#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */ -#define WHERE_TOP_LIMIT 0x00000010 /* xEXPR or x>=EXPR constraint */ -#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and xaiColumn[i]; - if( i==XN_EXPR ) return ""; - if( i==XN_ROWID ) return "rowid"; - return pIdx->pTable->aCol[i].zName; -} - -/* -** This routine is a helper for explainIndexRange() below -** -** pStr holds the text of an expression that we are building up one term -** at a time. This routine adds a new term to the end of the expression. -** Terms are separated by AND so add the "AND" text for second and subsequent -** terms only. -*/ -static void explainAppendTerm( - StrAccum *pStr, /* The text expression being built */ - Index *pIdx, /* Index to read column names from */ - int nTerm, /* Number of terms */ - int iTerm, /* Zero-based index of first term. */ - int bAnd, /* Non-zero to append " AND " */ - const char *zOp /* Name of the operator */ -){ - int i; - - assert( nTerm>=1 ); - if( bAnd ) sqlite3_str_append(pStr, " AND ", 5); - - if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); - for(i=0; i1 ) sqlite3_str_append(pStr, ")", 1); - - sqlite3_str_append(pStr, zOp, 1); - - if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); - for(i=0; i1 ) sqlite3_str_append(pStr, ")", 1); -} - -/* -** Argument pLevel describes a strategy for scanning table pTab. This -** function appends text to pStr that describes the subset of table -** rows scanned by the strategy in the form of an SQL expression. -** -** For example, if the query: -** -** SELECT * FROM t1 WHERE a=1 AND b>2; -** -** is run and there is an index on (a, b), then this function returns a -** string similar to: -** -** "a=? AND b>?" -*/ -static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ - Index *pIndex = pLoop->u.btree.pIndex; - u16 nEq = pLoop->u.btree.nEq; - u16 nSkip = pLoop->nSkip; - int i, j; - - if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; - sqlite3_str_append(pStr, " (", 2); - for(i=0; i=nSkip ? "%s=?" : "ANY(%s)", z); - } - - j = i; - if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ - explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); - i = 1; - } - if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ - explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); - } - sqlite3_str_append(pStr, ")", 1); -} - -/* -** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN -** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was -** defined at compile-time. If it is not a no-op, a single OP_Explain opcode -** is added to the output to describe the table scan strategy in pLevel. -** -** If an OP_Explain opcode is added to the VM, its address is returned. -** Otherwise, if no OP_Explain is coded, zero is returned. -*/ -SQLITE_PRIVATE int sqlite3WhereExplainOneScan( - Parse *pParse, /* Parse context */ - SrcList *pTabList, /* Table list this loop refers to */ - WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ - u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ -){ - int ret = 0; -#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) - if( sqlite3ParseToplevel(pParse)->explain==2 ) -#endif - { - struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; - Vdbe *v = pParse->pVdbe; /* VM being constructed */ - sqlite3 *db = pParse->db; /* Database handle */ - int isSearch; /* True for a SEARCH. False for SCAN. */ - WhereLoop *pLoop; /* The controlling WhereLoop object */ - u32 flags; /* Flags that describe this loop */ - char *zMsg; /* Text to add to EQP output */ - StrAccum str; /* EQP output string */ - char zBuf[100]; /* Initial space for EQP output string */ - - pLoop = pLevel->pWLoop; - flags = pLoop->wsFlags; - if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; - - isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 - || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) - || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); - - sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); - sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN"); - if( pItem->pSelect ){ - sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId); - }else{ - sqlite3_str_appendf(&str, " TABLE %s", pItem->zName); - } - - if( pItem->zAlias ){ - sqlite3_str_appendf(&str, " AS %s", pItem->zAlias); - } - if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ - const char *zFmt = 0; - Index *pIdx; - - assert( pLoop->u.btree.pIndex!=0 ); - pIdx = pLoop->u.btree.pIndex; - assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); - if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ - if( isSearch ){ - zFmt = "PRIMARY KEY"; - } - }else if( flags & WHERE_PARTIALIDX ){ - zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; - }else if( flags & WHERE_AUTO_INDEX ){ - zFmt = "AUTOMATIC COVERING INDEX"; - }else if( flags & WHERE_IDX_ONLY ){ - zFmt = "COVERING INDEX %s"; - }else{ - zFmt = "INDEX %s"; - } - if( zFmt ){ - sqlite3_str_append(&str, " USING ", 7); - sqlite3_str_appendf(&str, zFmt, pIdx->zName); - explainIndexRange(&str, pLoop); - } - }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ - const char *zRangeOp; - if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ - zRangeOp = "="; - }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ - zRangeOp = ">? AND rowid<"; - }else if( flags&WHERE_BTM_LIMIT ){ - zRangeOp = ">"; - }else{ - assert( flags&WHERE_TOP_LIMIT); - zRangeOp = "<"; - } - sqlite3_str_appendf(&str, - " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ - sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s", - pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); - } -#endif -#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS - if( pLoop->nOut>=10 ){ - sqlite3_str_appendf(&str, " (~%llu rows)", - sqlite3LogEstToInt(pLoop->nOut)); - }else{ - sqlite3_str_append(&str, " (~1 row)", 9); - } -#endif - zMsg = sqlite3StrAccumFinish(&str); - sqlite3ExplainBreakpoint("",zMsg); - ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v), - pParse->addrExplain, 0, zMsg,P4_DYNAMIC); - } - return ret; -} -#endif /* SQLITE_OMIT_EXPLAIN */ - -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS -/* -** Configure the VM passed as the first argument with an -** sqlite3_stmt_scanstatus() entry corresponding to the scan used to -** implement level pLvl. Argument pSrclist is a pointer to the FROM -** clause that the scan reads data from. -** -** If argument addrExplain is not 0, it must be the address of an -** OP_Explain instruction that describes the same loop. -*/ -SQLITE_PRIVATE void sqlite3WhereAddScanStatus( - Vdbe *v, /* Vdbe to add scanstatus entry to */ - SrcList *pSrclist, /* FROM clause pLvl reads data from */ - WhereLevel *pLvl, /* Level to add scanstatus() entry for */ - int addrExplain /* Address of OP_Explain (or 0) */ -){ - const char *zObj = 0; - WhereLoop *pLoop = pLvl->pWLoop; - if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ - zObj = pLoop->u.btree.pIndex->zName; - }else{ - zObj = pSrclist->a[pLvl->iFrom].zName; - } - sqlite3VdbeScanStatus( - v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj - ); -} -#endif - - -/* -** Disable a term in the WHERE clause. Except, do not disable the term -** if it controls a LEFT OUTER JOIN and it did not originate in the ON -** or USING clause of that join. -** -** Consider the term t2.z='ok' in the following queries: -** -** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' -** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' -** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' -** -** The t2.z='ok' is disabled in the in (2) because it originates -** in the ON clause. The term is disabled in (3) because it is not part -** of a LEFT OUTER JOIN. In (1), the term is not disabled. -** -** Disabling a term causes that term to not be tested in the inner loop -** of the join. Disabling is an optimization. When terms are satisfied -** by indices, we disable them to prevent redundant tests in the inner -** loop. We would get the correct results if nothing were ever disabled, -** but joins might run a little slower. The trick is to disable as much -** as we can without disabling too much. If we disabled in (1), we'd get -** the wrong answer. See ticket #813. -** -** If all the children of a term are disabled, then that term is also -** automatically disabled. In this way, terms get disabled if derived -** virtual terms are tested first. For example: -** -** x GLOB 'abc*' AND x>='abc' AND x<'acd' -** \___________/ \______/ \_____/ -** parent child1 child2 -** -** Only the parent term was in the original WHERE clause. The child1 -** and child2 terms were added by the LIKE optimization. If both of -** the virtual child terms are valid, then testing of the parent can be -** skipped. -** -** Usually the parent term is marked as TERM_CODED. But if the parent -** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. -** The TERM_LIKECOND marking indicates that the term should be coded inside -** a conditional such that is only evaluated on the second pass of a -** LIKE-optimization loop, when scanning BLOBs instead of strings. -*/ -static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ - int nLoop = 0; - assert( pTerm!=0 ); - while( (pTerm->wtFlags & TERM_CODED)==0 - && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) - && (pLevel->notReady & pTerm->prereqAll)==0 - ){ - if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ - pTerm->wtFlags |= TERM_LIKECOND; - }else{ - pTerm->wtFlags |= TERM_CODED; - } - if( pTerm->iParent<0 ) break; - pTerm = &pTerm->pWC->a[pTerm->iParent]; - assert( pTerm!=0 ); - pTerm->nChild--; - if( pTerm->nChild!=0 ) break; - nLoop++; - } -} - -/* -** Code an OP_Affinity opcode to apply the column affinity string zAff -** to the n registers starting at base. -** -** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which -** are no-ops) at the beginning and end of zAff are ignored. If all entries -** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated. -** -** This routine makes its own copy of zAff so that the caller is free -** to modify zAff after this routine returns. -*/ -static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ - Vdbe *v = pParse->pVdbe; - if( zAff==0 ){ - assert( pParse->db->mallocFailed ); - return; - } - assert( v!=0 ); - - /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE - ** entries at the beginning and end of the affinity string. - */ - assert( SQLITE_AFF_NONE0 && zAff[0]<=SQLITE_AFF_BLOB ){ - n--; - base++; - zAff++; - } - while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){ - n--; - } - - /* Code the OP_Affinity opcode if there is anything left to do. */ - if( n>0 ){ - sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); - } -} - -/* -** Expression pRight, which is the RHS of a comparison operation, is -** either a vector of n elements or, if n==1, a scalar expression. -** Before the comparison operation, affinity zAff is to be applied -** to the pRight values. This function modifies characters within the -** affinity string to SQLITE_AFF_BLOB if either: -** -** * the comparison will be performed with no affinity, or -** * the affinity change in zAff is guaranteed not to change the value. -*/ -static void updateRangeAffinityStr( - Expr *pRight, /* RHS of comparison */ - int n, /* Number of vector elements in comparison */ - char *zAff /* Affinity string to modify */ -){ - int i; - for(i=0; idb; - Expr *pNew; - pNew = sqlite3ExprDup(db, pX, 0); - if( db->mallocFailed==0 ){ - ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */ - ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */ - ExprList *pRhs = 0; /* New RHS after modifications */ - ExprList *pLhs = 0; /* New LHS after mods */ - int i; /* Loop counter */ - Select *pSelect; /* Pointer to the SELECT on the RHS */ - - for(i=iEq; inLTerm; i++){ - if( pLoop->aLTerm[i]->pExpr==pX ){ - int iField = pLoop->aLTerm[i]->iField - 1; - if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */ - pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr); - pOrigRhs->a[iField].pExpr = 0; - assert( pOrigLhs->a[iField].pExpr!=0 ); - pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr); - pOrigLhs->a[iField].pExpr = 0; - } - } - sqlite3ExprListDelete(db, pOrigRhs); - sqlite3ExprListDelete(db, pOrigLhs); - pNew->pLeft->x.pList = pLhs; - pNew->x.pSelect->pEList = pRhs; - if( pLhs && pLhs->nExpr==1 ){ - /* Take care here not to generate a TK_VECTOR containing only a - ** single value. Since the parser never creates such a vector, some - ** of the subroutines do not handle this case. */ - Expr *p = pLhs->a[0].pExpr; - pLhs->a[0].pExpr = 0; - sqlite3ExprDelete(db, pNew->pLeft); - pNew->pLeft = p; - } - pSelect = pNew->x.pSelect; - if( pSelect->pOrderBy ){ - /* If the SELECT statement has an ORDER BY clause, zero the - ** iOrderByCol variables. These are set to non-zero when an - ** ORDER BY term exactly matches one of the terms of the - ** result-set. Since the result-set of the SELECT statement may - ** have been modified or reordered, these variables are no longer - ** set correctly. Since setting them is just an optimization, - ** it's easiest just to zero them here. */ - ExprList *pOrderBy = pSelect->pOrderBy; - for(i=0; inExpr; i++){ - pOrderBy->a[i].u.x.iOrderByCol = 0; - } - } - -#if 0 - printf("For indexing, change the IN expr:\n"); - sqlite3TreeViewExpr(0, pX, 0); - printf("Into:\n"); - sqlite3TreeViewExpr(0, pNew, 0); -#endif - } - return pNew; -} - - -/* -** Generate code for a single equality term of the WHERE clause. An equality -** term can be either X=expr or X IN (...). pTerm is the term to be -** coded. -** -** The current value for the constraint is left in a register, the index -** of which is returned. An attempt is made store the result in iTarget but -** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the -** constraint is a TK_EQ or TK_IS, then the current value might be left in -** some other register and it is the caller's responsibility to compensate. -** -** For a constraint of the form X=expr, the expression is evaluated in -** straight-line code. For constraints of the form X IN (...) -** this routine sets up a loop that will iterate over all values of X. -*/ -static int codeEqualityTerm( - Parse *pParse, /* The parsing context */ - WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ - WhereLevel *pLevel, /* The level of the FROM clause we are working on */ - int iEq, /* Index of the equality term within this level */ - int bRev, /* True for reverse-order IN operations */ - int iTarget /* Attempt to leave results in this register */ -){ - Expr *pX = pTerm->pExpr; - Vdbe *v = pParse->pVdbe; - int iReg; /* Register holding results */ - - assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); - assert( iTarget>0 ); - if( pX->op==TK_EQ || pX->op==TK_IS ){ - iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); - }else if( pX->op==TK_ISNULL ){ - iReg = iTarget; - sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); -#ifndef SQLITE_OMIT_SUBQUERY - }else{ - int eType = IN_INDEX_NOOP; - int iTab; - struct InLoop *pIn; - WhereLoop *pLoop = pLevel->pWLoop; - int i; - int nEq = 0; - int *aiMap = 0; - - if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 - && pLoop->u.btree.pIndex!=0 - && pLoop->u.btree.pIndex->aSortOrder[iEq] - ){ - testcase( iEq==0 ); - testcase( bRev ); - bRev = !bRev; - } - assert( pX->op==TK_IN ); - iReg = iTarget; - - for(i=0; iaLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ - disableTerm(pLevel, pTerm); - return iTarget; - } - } - for(i=iEq;inLTerm; i++){ - assert( pLoop->aLTerm[i]!=0 ); - if( pLoop->aLTerm[i]->pExpr==pX ) nEq++; - } - - iTab = 0; - if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab); - }else{ - sqlite3 *db = pParse->db; - pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX); - - if( !db->mallocFailed ){ - aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq); - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab); - pTerm->pExpr->iTable = iTab; - } - sqlite3ExprDelete(db, pX); - pX = pTerm->pExpr; - } - - if( eType==IN_INDEX_INDEX_DESC ){ - testcase( bRev ); - bRev = !bRev; - } - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); - VdbeCoverageIf(v, bRev); - VdbeCoverageIf(v, !bRev); - assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); - - pLoop->wsFlags |= WHERE_IN_ABLE; - if( pLevel->u.in.nIn==0 ){ - pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); - } - - i = pLevel->u.in.nIn; - pLevel->u.in.nIn += nEq; - pLevel->u.in.aInLoop = - sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, - sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); - pIn = pLevel->u.in.aInLoop; - if( pIn ){ - int iMap = 0; /* Index in aiMap[] */ - pIn += i; - for(i=iEq;inLTerm; i++){ - if( pLoop->aLTerm[i]->pExpr==pX ){ - int iOut = iReg + i - iEq; - if( eType==IN_INDEX_ROWID ){ - pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); - }else{ - int iCol = aiMap ? aiMap[iMap++] : 0; - pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); - } - sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); - if( i==iEq ){ - pIn->iCur = iTab; - pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next; - if( iEq>0 ){ - pIn->iBase = iReg - i; - pIn->nPrefix = i; - pLoop->wsFlags |= WHERE_IN_EARLYOUT; - }else{ - pIn->nPrefix = 0; - } - }else{ - pIn->eEndLoopOp = OP_Noop; - } - pIn++; - } - } - }else{ - pLevel->u.in.nIn = 0; - } - sqlite3DbFree(pParse->db, aiMap); -#endif - } - disableTerm(pLevel, pTerm); - return iReg; -} - -/* -** Generate code that will evaluate all == and IN constraints for an -** index scan. -** -** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). -** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 -** The index has as many as three equality constraints, but in this -** example, the third "c" value is an inequality. So only two -** constraints are coded. This routine will generate code to evaluate -** a==5 and b IN (1,2,3). The current values for a and b will be stored -** in consecutive registers and the index of the first register is returned. -** -** In the example above nEq==2. But this subroutine works for any value -** of nEq including 0. If nEq==0, this routine is nearly a no-op. -** The only thing it does is allocate the pLevel->iMem memory cell and -** compute the affinity string. -** -** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints -** are == or IN and are covered by the nEq. nExtraReg is 1 if there is -** an inequality constraint (such as the "c>=5 AND c<10" in the example) that -** occurs after the nEq quality constraints. -** -** This routine allocates a range of nEq+nExtraReg memory cells and returns -** the index of the first memory cell in that range. The code that -** calls this routine will use that memory range to store keys for -** start and termination conditions of the loop. -** key value of the loop. If one or more IN operators appear, then -** this routine allocates an additional nEq memory cells for internal -** use. -** -** Before returning, *pzAff is set to point to a buffer containing a -** copy of the column affinity string of the index allocated using -** sqlite3DbMalloc(). Except, entries in the copy of the string associated -** with equality constraints that use BLOB or NONE affinity are set to -** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: -** -** CREATE TABLE t1(a TEXT PRIMARY KEY, b); -** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; -** -** In the example above, the index on t1(a) has TEXT affinity. But since -** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, -** no conversion should be attempted before using a t2.b value as part of -** a key to search the index. Hence the first byte in the returned affinity -** string in this example would be set to SQLITE_AFF_BLOB. -*/ -static int codeAllEqualityTerms( - Parse *pParse, /* Parsing context */ - WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ - int bRev, /* Reverse the order of IN operators */ - int nExtraReg, /* Number of extra registers to allocate */ - char **pzAff /* OUT: Set to point to affinity string */ -){ - u16 nEq; /* The number of == or IN constraints to code */ - u16 nSkip; /* Number of left-most columns to skip */ - Vdbe *v = pParse->pVdbe; /* The vm under construction */ - Index *pIdx; /* The index being used for this loop */ - WhereTerm *pTerm; /* A single constraint term */ - WhereLoop *pLoop; /* The WhereLoop object */ - int j; /* Loop counter */ - int regBase; /* Base register */ - int nReg; /* Number of registers to allocate */ - char *zAff; /* Affinity string to return */ - - /* This module is only called on query plans that use an index. */ - pLoop = pLevel->pWLoop; - assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); - nEq = pLoop->u.btree.nEq; - nSkip = pLoop->nSkip; - pIdx = pLoop->u.btree.pIndex; - assert( pIdx!=0 ); - - /* Figure out how many memory cells we will need then allocate them. - */ - regBase = pParse->nMem + 1; - nReg = pLoop->u.btree.nEq + nExtraReg; - pParse->nMem += nReg; - - zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); - assert( zAff!=0 || pParse->db->mallocFailed ); - - if( nSkip ){ - int iIdxCur = pLevel->iIdxCur; - sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); - VdbeCoverageIf(v, bRev==0); - VdbeCoverageIf(v, bRev!=0); - VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); - j = sqlite3VdbeAddOp0(v, OP_Goto); - pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), - iIdxCur, 0, regBase, nSkip); - VdbeCoverageIf(v, bRev==0); - VdbeCoverageIf(v, bRev!=0); - sqlite3VdbeJumpHere(v, j); - for(j=0; jaiColumn[j]==XN_EXPR ); - VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); - } - } - - /* Evaluate the equality constraints - */ - assert( zAff==0 || (int)strlen(zAff)>=nEq ); - for(j=nSkip; jaLTerm[j]; - assert( pTerm!=0 ); - /* The following testcase is true for indices with redundant columns. - ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ - testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); - testcase( pTerm->wtFlags & TERM_VIRTUAL ); - r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); - if( r1!=regBase+j ){ - if( nReg==1 ){ - sqlite3ReleaseTempReg(pParse, regBase); - regBase = r1; - }else{ - sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); - } - } - if( pTerm->eOperator & WO_IN ){ - if( pTerm->pExpr->flags & EP_xIsSelect ){ - /* No affinity ever needs to be (or should be) applied to a value - ** from the RHS of an "? IN (SELECT ...)" expression. The - ** sqlite3FindInIndex() routine has already ensured that the - ** affinity of the comparison has been applied to the value. */ - if( zAff ) zAff[j] = SQLITE_AFF_BLOB; - } - }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ - Expr *pRight = pTerm->pExpr->pRight; - if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); - VdbeCoverage(v); - } - if( zAff ){ - if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ - zAff[j] = SQLITE_AFF_BLOB; - } - if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ - zAff[j] = SQLITE_AFF_BLOB; - } - } - } - } - *pzAff = zAff; - return regBase; -} - -#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS -/* -** If the most recently coded instruction is a constant range constraint -** (a string literal) that originated from the LIKE optimization, then -** set P3 and P5 on the OP_String opcode so that the string will be cast -** to a BLOB at appropriate times. -** -** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range -** expression: "x>='ABC' AND x<'abd'". But this requires that the range -** scan loop run twice, once for strings and a second time for BLOBs. -** The OP_String opcodes on the second pass convert the upper and lower -** bound string constants to blobs. This routine makes the necessary changes -** to the OP_String opcodes for that to happen. -** -** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then -** only the one pass through the string space is required, so this routine -** becomes a no-op. -*/ -static void whereLikeOptimizationStringFixup( - Vdbe *v, /* prepared statement under construction */ - WhereLevel *pLevel, /* The loop that contains the LIKE operator */ - WhereTerm *pTerm /* The upper or lower bound just coded */ -){ - if( pTerm->wtFlags & TERM_LIKEOPT ){ - VdbeOp *pOp; - assert( pLevel->iLikeRepCntr>0 ); - pOp = sqlite3VdbeGetOp(v, -1); - assert( pOp!=0 ); - assert( pOp->opcode==OP_String8 - || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); - pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ - pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ - } -} -#else -# define whereLikeOptimizationStringFixup(A,B,C) -#endif - -#ifdef SQLITE_ENABLE_CURSOR_HINTS -/* -** Information is passed from codeCursorHint() down to individual nodes of -** the expression tree (by sqlite3WalkExpr()) using an instance of this -** structure. -*/ -struct CCurHint { - int iTabCur; /* Cursor for the main table */ - int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ - Index *pIdx; /* The index used to access the table */ -}; - -/* -** This function is called for every node of an expression that is a candidate -** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference -** the table CCurHint.iTabCur, verify that the same column can be -** accessed through the index. If it cannot, then set pWalker->eCode to 1. -*/ -static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ - struct CCurHint *pHint = pWalker->u.pCCurHint; - assert( pHint->pIdx!=0 ); - if( pExpr->op==TK_COLUMN - && pExpr->iTable==pHint->iTabCur - && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0 - ){ - pWalker->eCode = 1; - } - return WRC_Continue; -} - -/* -** Test whether or not expression pExpr, which was part of a WHERE clause, -** should be included in the cursor-hint for a table that is on the rhs -** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the -** expression is not suitable. -** -** An expression is unsuitable if it might evaluate to non NULL even if -** a TK_COLUMN node that does affect the value of the expression is set -** to NULL. For example: -** -** col IS NULL -** col IS NOT NULL -** coalesce(col, 1) -** CASE WHEN col THEN 0 ELSE 1 END -*/ -static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_IS - || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT - || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE - ){ - pWalker->eCode = 1; - }else if( pExpr->op==TK_FUNCTION ){ - int d1; - char d2[4]; - if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ - pWalker->eCode = 1; - } - } - - return WRC_Continue; -} - - -/* -** This function is called on every node of an expression tree used as an -** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN -** that accesses any table other than the one identified by -** CCurHint.iTabCur, then do the following: -** -** 1) allocate a register and code an OP_Column instruction to read -** the specified column into the new register, and -** -** 2) transform the expression node to a TK_REGISTER node that reads -** from the newly populated register. -** -** Also, if the node is a TK_COLUMN that does access the table idenified -** by pCCurHint.iTabCur, and an index is being used (which we will -** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into -** an access of the index rather than the original table. -*/ -static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ - int rc = WRC_Continue; - struct CCurHint *pHint = pWalker->u.pCCurHint; - if( pExpr->op==TK_COLUMN ){ - if( pExpr->iTable!=pHint->iTabCur ){ - int reg = ++pWalker->pParse->nMem; /* Register for column value */ - sqlite3ExprCode(pWalker->pParse, pExpr, reg); - pExpr->op = TK_REGISTER; - pExpr->iTable = reg; - }else if( pHint->pIdx!=0 ){ - pExpr->iTable = pHint->iIdxCur; - pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn); - assert( pExpr->iColumn>=0 ); - } - }else if( pExpr->op==TK_AGG_FUNCTION ){ - /* An aggregate function in the WHERE clause of a query means this must - ** be a correlated sub-query, and expression pExpr is an aggregate from - ** the parent context. Do not walk the function arguments in this case. - ** - ** todo: It should be possible to replace this node with a TK_REGISTER - ** expression, as the result of the expression must be stored in a - ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ - rc = WRC_Prune; - } - return rc; -} - -/* -** Insert an OP_CursorHint instruction if it is appropriate to do so. -*/ -static void codeCursorHint( - struct SrcList_item *pTabItem, /* FROM clause item */ - WhereInfo *pWInfo, /* The where clause */ - WhereLevel *pLevel, /* Which loop to provide hints for */ - WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ -){ - Parse *pParse = pWInfo->pParse; - sqlite3 *db = pParse->db; - Vdbe *v = pParse->pVdbe; - Expr *pExpr = 0; - WhereLoop *pLoop = pLevel->pWLoop; - int iCur; - WhereClause *pWC; - WhereTerm *pTerm; - int i, j; - struct CCurHint sHint; - Walker sWalker; - - if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; - iCur = pLevel->iTabCur; - assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); - sHint.iTabCur = iCur; - sHint.iIdxCur = pLevel->iIdxCur; - sHint.pIdx = pLoop->u.btree.pIndex; - memset(&sWalker, 0, sizeof(sWalker)); - sWalker.pParse = pParse; - sWalker.u.pCCurHint = &sHint; - pWC = &pWInfo->sWC; - for(i=0; inTerm; i++){ - pTerm = &pWC->a[i]; - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; - if( pTerm->prereqAll & pLevel->notReady ) continue; - - /* Any terms specified as part of the ON(...) clause for any LEFT - ** JOIN for which the current table is not the rhs are omitted - ** from the cursor-hint. - ** - ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms - ** that were specified as part of the WHERE clause must be excluded. - ** This is to address the following: - ** - ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; - ** - ** Say there is a single row in t2 that matches (t1.a=t2.b), but its - ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is - ** pushed down to the cursor, this row is filtered out, causing - ** SQLite to synthesize a row of NULL values. Which does match the - ** WHERE clause, and so the query returns a row. Which is incorrect. - ** - ** For the same reason, WHERE terms such as: - ** - ** WHERE 1 = (t2.c IS NULL) - ** - ** are also excluded. See codeCursorHintIsOrFunction() for details. - */ - if( pTabItem->fg.jointype & JT_LEFT ){ - Expr *pExpr = pTerm->pExpr; - if( !ExprHasProperty(pExpr, EP_FromJoin) - || pExpr->iRightJoinTable!=pTabItem->iCursor - ){ - sWalker.eCode = 0; - sWalker.xExprCallback = codeCursorHintIsOrFunction; - sqlite3WalkExpr(&sWalker, pTerm->pExpr); - if( sWalker.eCode ) continue; - } - }else{ - if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; - } - - /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize - ** the cursor. These terms are not needed as hints for a pure range - ** scan (that has no == terms) so omit them. */ - if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ - for(j=0; jnLTerm && pLoop->aLTerm[j]!=pTerm; j++){} - if( jnLTerm ) continue; - } - - /* No subqueries or non-deterministic functions allowed */ - if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; - - /* For an index scan, make sure referenced columns are actually in - ** the index. */ - if( sHint.pIdx!=0 ){ - sWalker.eCode = 0; - sWalker.xExprCallback = codeCursorHintCheckExpr; - sqlite3WalkExpr(&sWalker, pTerm->pExpr); - if( sWalker.eCode ) continue; - } - - /* If we survive all prior tests, that means this term is worth hinting */ - pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); - } - if( pExpr!=0 ){ - sWalker.xExprCallback = codeCursorHintFixExpr; - sqlite3WalkExpr(&sWalker, pExpr); - sqlite3VdbeAddOp4(v, OP_CursorHint, - (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, - (const char*)pExpr, P4_EXPR); - } -} -#else -# define codeCursorHint(A,B,C,D) /* No-op */ -#endif /* SQLITE_ENABLE_CURSOR_HINTS */ - -/* -** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains -** a rowid value just read from cursor iIdxCur, open on index pIdx. This -** function generates code to do a deferred seek of cursor iCur to the -** rowid stored in register iRowid. -** -** Normally, this is just: -** -** OP_DeferredSeek $iCur $iRowid -** -** However, if the scan currently being coded is a branch of an OR-loop and -** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek -** is set to iIdxCur and P4 is set to point to an array of integers -** containing one entry for each column of the table cursor iCur is open -** on. For each table column, if the column is the i'th column of the -** index, then the corresponding array entry is set to (i+1). If the column -** does not appear in the index at all, the array entry is set to 0. -*/ -static void codeDeferredSeek( - WhereInfo *pWInfo, /* Where clause context */ - Index *pIdx, /* Index scan is using */ - int iCur, /* Cursor for IPK b-tree */ - int iIdxCur /* Index cursor */ -){ - Parse *pParse = pWInfo->pParse; /* Parse context */ - Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ - - assert( iIdxCur>0 ); - assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); - - pWInfo->bDeferredSeek = 1; - sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur); - if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) - && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) - ){ - int i; - Table *pTab = pIdx->pTable; - u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1)); - if( ai ){ - ai[0] = pTab->nCol; - for(i=0; inColumn-1; i++){ - int x1, x2; - assert( pIdx->aiColumn[i]nCol ); - x1 = pIdx->aiColumn[i]; - x2 = sqlite3TableColumnToStorage(pTab, x1); - testcase( x1!=x2 ); - if( x1>=0 ) ai[x2+1] = i+1; - } - sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); - } - } -} - -/* -** If the expression passed as the second argument is a vector, generate -** code to write the first nReg elements of the vector into an array -** of registers starting with iReg. -** -** If the expression is not a vector, then nReg must be passed 1. In -** this case, generate code to evaluate the expression and leave the -** result in register iReg. -*/ -static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ - assert( nReg>0 ); - if( p && sqlite3ExprIsVector(p) ){ -#ifndef SQLITE_OMIT_SUBQUERY - if( (p->flags & EP_xIsSelect) ){ - Vdbe *v = pParse->pVdbe; - int iSelect; - assert( p->op==TK_SELECT ); - iSelect = sqlite3CodeSubselect(pParse, p); - sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); - }else -#endif - { - int i; - ExprList *pList = p->x.pList; - assert( nReg<=pList->nExpr ); - for(i=0; ia[i].pExpr, iReg+i); - } - } - }else{ - assert( nReg==1 ); - sqlite3ExprCode(pParse, p, iReg); - } -} - -/* An instance of the IdxExprTrans object carries information about a -** mapping from an expression on table columns into a column in an index -** down through the Walker. -*/ -typedef struct IdxExprTrans { - Expr *pIdxExpr; /* The index expression */ - int iTabCur; /* The cursor of the corresponding table */ - int iIdxCur; /* The cursor for the index */ - int iIdxCol; /* The column for the index */ - int iTabCol; /* The column for the table */ - WhereInfo *pWInfo; /* Complete WHERE clause information */ - sqlite3 *db; /* Database connection (for malloc()) */ -} IdxExprTrans; - -/* -** Preserve pExpr on the WhereETrans list of the WhereInfo. -*/ -static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){ - WhereExprMod *pNew; - pNew = sqlite3DbMallocRaw(pTrans->db, sizeof(*pNew)); - if( pNew==0 ) return; - pNew->pNext = pTrans->pWInfo->pExprMods; - pTrans->pWInfo->pExprMods = pNew; - pNew->pExpr = pExpr; - memcpy(&pNew->orig, pExpr, sizeof(*pExpr)); -} - -/* The walker node callback used to transform matching expressions into -** a reference to an index column for an index on an expression. -** -** If pExpr matches, then transform it into a reference to the index column -** that contains the value of pExpr. -*/ -static int whereIndexExprTransNode(Walker *p, Expr *pExpr){ - IdxExprTrans *pX = p->u.pIdxTrans; - if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){ - preserveExpr(pX, pExpr); - pExpr->affExpr = sqlite3ExprAffinity(pExpr); - pExpr->op = TK_COLUMN; - pExpr->iTable = pX->iIdxCur; - pExpr->iColumn = pX->iIdxCol; - pExpr->y.pTab = 0; - testcase( ExprHasProperty(pExpr, EP_Skip) ); - testcase( ExprHasProperty(pExpr, EP_Unlikely) ); - ExprClearProperty(pExpr, EP_Skip|EP_Unlikely); - return WRC_Prune; - }else{ - return WRC_Continue; - } -} - -#ifndef SQLITE_OMIT_GENERATED_COLUMNS -/* A walker node callback that translates a column reference to a table -** into a corresponding column reference of an index. -*/ -static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){ - if( pExpr->op==TK_COLUMN ){ - IdxExprTrans *pX = p->u.pIdxTrans; - if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){ - assert( pExpr->y.pTab!=0 ); - preserveExpr(pX, pExpr); - pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn); - pExpr->iTable = pX->iIdxCur; - pExpr->iColumn = pX->iIdxCol; - pExpr->y.pTab = 0; - } - } - return WRC_Continue; -} -#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ - -/* -** For an indexes on expression X, locate every instance of expression X -** in pExpr and change that subexpression into a reference to the appropriate -** column of the index. -** -** 2019-10-24: Updated to also translate references to a VIRTUAL column in -** the table into references to the corresponding (stored) column of the -** index. -*/ -static void whereIndexExprTrans( - Index *pIdx, /* The Index */ - int iTabCur, /* Cursor of the table that is being indexed */ - int iIdxCur, /* Cursor of the index itself */ - WhereInfo *pWInfo /* Transform expressions in this WHERE clause */ -){ - int iIdxCol; /* Column number of the index */ - ExprList *aColExpr; /* Expressions that are indexed */ - Table *pTab; - Walker w; - IdxExprTrans x; - aColExpr = pIdx->aColExpr; - if( aColExpr==0 && !pIdx->bHasVCol ){ - /* The index does not reference any expressions or virtual columns - ** so no translations are needed. */ - return; - } - pTab = pIdx->pTable; - memset(&w, 0, sizeof(w)); - w.u.pIdxTrans = &x; - x.iTabCur = iTabCur; - x.iIdxCur = iIdxCur; - x.pWInfo = pWInfo; - x.db = pWInfo->pParse->db; - for(iIdxCol=0; iIdxColnColumn; iIdxCol++){ - i16 iRef = pIdx->aiColumn[iIdxCol]; - if( iRef==XN_EXPR ){ - assert( aColExpr->a[iIdxCol].pExpr!=0 ); - x.pIdxExpr = aColExpr->a[iIdxCol].pExpr; - if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue; - w.xExprCallback = whereIndexExprTransNode; -#ifndef SQLITE_OMIT_GENERATED_COLUMNS - }else if( iRef>=0 - && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0 - && (pTab->aCol[iRef].zColl==0 - || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0) - ){ - /* Check to see if there are direct references to generated columns - ** that are contained in the index. Pulling the generated column - ** out of the index is an optimization only - the main table is always - ** available if the index cannot be used. To avoid unnecessary - ** complication, omit this optimization if the collating sequence for - ** the column is non-standard */ - x.iTabCol = iRef; - w.xExprCallback = whereIndexExprTransColumn; -#endif /* SQLITE_OMIT_GENERATED_COLUMNS */ - }else{ - continue; - } - x.iIdxCol = iIdxCol; - sqlite3WalkExpr(&w, pWInfo->pWhere); - sqlite3WalkExprList(&w, pWInfo->pOrderBy); - sqlite3WalkExprList(&w, pWInfo->pResultSet); - } -} - -/* -** The pTruth expression is always true because it is the WHERE clause -** a partial index that is driving a query loop. Look through all of the -** WHERE clause terms on the query, and if any of those terms must be -** true because pTruth is true, then mark those WHERE clause terms as -** coded. -*/ -static void whereApplyPartialIndexConstraints( - Expr *pTruth, - int iTabCur, - WhereClause *pWC -){ - int i; - WhereTerm *pTerm; - while( pTruth->op==TK_AND ){ - whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC); - pTruth = pTruth->pRight; - } - for(i=0, pTerm=pWC->a; inTerm; i++, pTerm++){ - Expr *pExpr; - if( pTerm->wtFlags & TERM_CODED ) continue; - pExpr = pTerm->pExpr; - if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){ - pTerm->wtFlags |= TERM_CODED; - } - } -} - -/* -** Generate code for the start of the iLevel-th loop in the WHERE clause -** implementation described by pWInfo. -*/ -SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( - Parse *pParse, /* Parsing context */ - Vdbe *v, /* Prepared statement under construction */ - WhereInfo *pWInfo, /* Complete information about the WHERE clause */ - int iLevel, /* Which level of pWInfo->a[] should be coded */ - WhereLevel *pLevel, /* The current level pointer */ - Bitmask notReady /* Which tables are currently available */ -){ - int j, k; /* Loop counters */ - int iCur; /* The VDBE cursor for the table */ - int addrNxt; /* Where to jump to continue with the next IN case */ - int bRev; /* True if we need to scan in reverse order */ - WhereLoop *pLoop; /* The WhereLoop object being coded */ - WhereClause *pWC; /* Decomposition of the entire WHERE clause */ - WhereTerm *pTerm; /* A WHERE clause term */ - sqlite3 *db; /* Database connection */ - struct SrcList_item *pTabItem; /* FROM clause term being coded */ - int addrBrk; /* Jump here to break out of the loop */ - int addrHalt; /* addrBrk for the outermost loop */ - int addrCont; /* Jump here to continue with next cycle */ - int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ - int iReleaseReg = 0; /* Temp register to free before returning */ - Index *pIdx = 0; /* Index used by loop (if any) */ - int iLoop; /* Iteration of constraint generator loop */ - - pWC = &pWInfo->sWC; - db = pParse->db; - pLoop = pLevel->pWLoop; - pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; - iCur = pTabItem->iCursor; - pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); - bRev = (pWInfo->revMask>>iLevel)&1; - VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); -#if WHERETRACE_ENABLED /* 0x20800 */ - if( sqlite3WhereTrace & 0x800 ){ - sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n", - iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom); - sqlite3WhereLoopPrint(pLoop, pWC); - } - if( sqlite3WhereTrace & 0x20000 ){ - if( iLevel==0 ){ - sqlite3DebugPrintf("WHERE clause being coded:\n"); - sqlite3TreeViewExpr(0, pWInfo->pWhere, 0); - } - sqlite3DebugPrintf("All WHERE-clause terms before coding:\n"); - sqlite3WhereClausePrint(pWC); - } -#endif - - /* Create labels for the "break" and "continue" instructions - ** for the current loop. Jump to addrBrk to break out of a loop. - ** Jump to cont to go immediately to the next iteration of the - ** loop. - ** - ** When there is an IN operator, we also have a "addrNxt" label that - ** means to continue with the next IN value combination. When - ** there are no IN operators in the constraints, the "addrNxt" label - ** is the same as "addrBrk". - */ - addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); - addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse); - - /* If this is the right table of a LEFT OUTER JOIN, allocate and - ** initialize a memory cell that records if this table matches any - ** row of the left table of the join. - */ - assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) - || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0 - ); - if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ - pLevel->iLeftJoin = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); - VdbeComment((v, "init LEFT JOIN no-match flag")); - } - - /* Compute a safe address to jump to if we discover that the table for - ** this loop is empty and can never contribute content. */ - for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){} - addrHalt = pWInfo->a[j].addrBrk; - - /* Special case of a FROM clause subquery implemented as a co-routine */ - if( pTabItem->fg.viaCoroutine ){ - int regYield = pTabItem->regReturn; - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); - pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); - VdbeCoverage(v); - VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); - pLevel->op = OP_Goto; - }else - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ - /* Case 1: The table is a virtual-table. Use the VFilter and VNext - ** to access the data. - */ - int iReg; /* P3 Value for OP_VFilter */ - int addrNotFound; - int nConstraint = pLoop->nLTerm; - int iIn; /* Counter for IN constraints */ - - iReg = sqlite3GetTempRange(pParse, nConstraint+2); - addrNotFound = pLevel->addrBrk; - for(j=0; jaLTerm[j]; - if( NEVER(pTerm==0) ) continue; - if( pTerm->eOperator & WO_IN ){ - codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); - addrNotFound = pLevel->addrNxt; - }else{ - Expr *pRight = pTerm->pExpr->pRight; - codeExprOrVector(pParse, pRight, iTarget, 1); - } - } - sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); - sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); - sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, - pLoop->u.vtab.idxStr, - pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); - VdbeCoverage(v); - pLoop->u.vtab.needFree = 0; - pLevel->p1 = iCur; - pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; - pLevel->p2 = sqlite3VdbeCurrentAddr(v); - iIn = pLevel->u.in.nIn; - for(j=nConstraint-1; j>=0; j--){ - pTerm = pLoop->aLTerm[j]; - if( (pTerm->eOperator & WO_IN)!=0 ) iIn--; - if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ - disableTerm(pLevel, pTerm); - }else if( (pTerm->eOperator & WO_IN)!=0 - && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1 - ){ - Expr *pCompare; /* The comparison operator */ - Expr *pRight; /* RHS of the comparison */ - VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ - - /* Reload the constraint value into reg[iReg+j+2]. The same value - ** was loaded into the same register prior to the OP_VFilter, but - ** the xFilter implementation might have changed the datatype or - ** encoding of the value in the register, so it *must* be reloaded. */ - assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); - if( !db->mallocFailed ){ - assert( iIn>=0 && iInu.in.nIn ); - pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop); - assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); - assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); - assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); - testcase( pOp->opcode==OP_Rowid ); - sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); - } - - /* Generate code that will continue to the next row if - ** the IN constraint is not satisfied */ - pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0); - assert( pCompare!=0 || db->mallocFailed ); - if( pCompare ){ - pCompare->pLeft = pTerm->pExpr->pLeft; - pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); - if( pRight ){ - pRight->iTable = iReg+j+2; - sqlite3ExprIfFalse( - pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL - ); - } - pCompare->pLeft = 0; - sqlite3ExprDelete(db, pCompare); - } - } - } - assert( iIn==0 || db->mallocFailed ); - /* These registers need to be preserved in case there is an IN operator - ** loop. So we could deallocate the registers here (and potentially - ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems - ** simpler and safer to simply not reuse the registers. - ** - ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); - */ - }else -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - - if( (pLoop->wsFlags & WHERE_IPK)!=0 - && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 - ){ - /* Case 2: We can directly reference a single row using an - ** equality comparison against the ROWID field. Or - ** we reference multiple rows using a "rowid IN (...)" - ** construct. - */ - assert( pLoop->u.btree.nEq==1 ); - pTerm = pLoop->aLTerm[0]; - assert( pTerm!=0 ); - assert( pTerm->pExpr!=0 ); - testcase( pTerm->wtFlags & TERM_VIRTUAL ); - iReleaseReg = ++pParse->nMem; - iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); - if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); - addrNxt = pLevel->addrNxt; - sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); - VdbeCoverage(v); - pLevel->op = OP_Noop; - if( (pTerm->prereqAll & pLevel->notReady)==0 ){ - pTerm->wtFlags |= TERM_CODED; - } - }else if( (pLoop->wsFlags & WHERE_IPK)!=0 - && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 - ){ - /* Case 3: We have an inequality comparison against the ROWID field. - */ - int testOp = OP_Noop; - int start; - int memEndValue = 0; - WhereTerm *pStart, *pEnd; - - j = 0; - pStart = pEnd = 0; - if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; - if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; - assert( pStart!=0 || pEnd!=0 ); - if( bRev ){ - pTerm = pStart; - pStart = pEnd; - pEnd = pTerm; - } - codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); - if( pStart ){ - Expr *pX; /* The expression that defines the start bound */ - int r1, rTemp; /* Registers for holding the start boundary */ - int op; /* Cursor seek operation */ - - /* The following constant maps TK_xx codes into corresponding - ** seek opcodes. It depends on a particular ordering of TK_xx - */ - const u8 aMoveOp[] = { - /* TK_GT */ OP_SeekGT, - /* TK_LE */ OP_SeekLE, - /* TK_LT */ OP_SeekLT, - /* TK_GE */ OP_SeekGE - }; - assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ - assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ - assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ - - assert( (pStart->wtFlags & TERM_VNULL)==0 ); - testcase( pStart->wtFlags & TERM_VIRTUAL ); - pX = pStart->pExpr; - assert( pX!=0 ); - testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ - if( sqlite3ExprIsVector(pX->pRight) ){ - r1 = rTemp = sqlite3GetTempReg(pParse); - codeExprOrVector(pParse, pX->pRight, r1, 1); - testcase( pX->op==TK_GT ); - testcase( pX->op==TK_GE ); - testcase( pX->op==TK_LT ); - testcase( pX->op==TK_LE ); - op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1]; - assert( pX->op!=TK_GT || op==OP_SeekGE ); - assert( pX->op!=TK_GE || op==OP_SeekGE ); - assert( pX->op!=TK_LT || op==OP_SeekLE ); - assert( pX->op!=TK_LE || op==OP_SeekLE ); - }else{ - r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); - disableTerm(pLevel, pStart); - op = aMoveOp[(pX->op - TK_GT)]; - } - sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); - VdbeComment((v, "pk")); - VdbeCoverageIf(v, pX->op==TK_GT); - VdbeCoverageIf(v, pX->op==TK_LE); - VdbeCoverageIf(v, pX->op==TK_LT); - VdbeCoverageIf(v, pX->op==TK_GE); - sqlite3ReleaseTempReg(pParse, rTemp); - }else{ - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt); - VdbeCoverageIf(v, bRev==0); - VdbeCoverageIf(v, bRev!=0); - } - if( pEnd ){ - Expr *pX; - pX = pEnd->pExpr; - assert( pX!=0 ); - assert( (pEnd->wtFlags & TERM_VNULL)==0 ); - testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ - testcase( pEnd->wtFlags & TERM_VIRTUAL ); - memEndValue = ++pParse->nMem; - codeExprOrVector(pParse, pX->pRight, memEndValue, 1); - if( 0==sqlite3ExprIsVector(pX->pRight) - && (pX->op==TK_LT || pX->op==TK_GT) - ){ - testOp = bRev ? OP_Le : OP_Ge; - }else{ - testOp = bRev ? OP_Lt : OP_Gt; - } - if( 0==sqlite3ExprIsVector(pX->pRight) ){ - disableTerm(pLevel, pEnd); - } - } - start = sqlite3VdbeCurrentAddr(v); - pLevel->op = bRev ? OP_Prev : OP_Next; - pLevel->p1 = iCur; - pLevel->p2 = start; - assert( pLevel->p5==0 ); - if( testOp!=OP_Noop ){ - iRowidReg = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); - sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); - VdbeCoverageIf(v, testOp==OP_Le); - VdbeCoverageIf(v, testOp==OP_Lt); - VdbeCoverageIf(v, testOp==OP_Ge); - VdbeCoverageIf(v, testOp==OP_Gt); - sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); - } - }else if( pLoop->wsFlags & WHERE_INDEXED ){ - /* Case 4: A scan using an index. - ** - ** The WHERE clause may contain zero or more equality - ** terms ("==" or "IN" operators) that refer to the N - ** left-most columns of the index. It may also contain - ** inequality constraints (>, <, >= or <=) on the indexed - ** column that immediately follows the N equalities. Only - ** the right-most column can be an inequality - the rest must - ** use the "==" and "IN" operators. For example, if the - ** index is on (x,y,z), then the following clauses are all - ** optimized: - ** - ** x=5 - ** x=5 AND y=10 - ** x=5 AND y<10 - ** x=5 AND y>5 AND y<10 - ** x=5 AND y=5 AND z<=10 - ** - ** The z<10 term of the following cannot be used, only - ** the x=5 term: - ** - ** x=5 AND z<10 - ** - ** N may be zero if there are inequality constraints. - ** If there are no inequality constraints, then N is at - ** least one. - ** - ** This case is also used when there are no WHERE clause - ** constraints but an index is selected anyway, in order - ** to force the output order to conform to an ORDER BY. - */ - static const u8 aStartOp[] = { - 0, - 0, - OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ - OP_Last, /* 3: (!start_constraints && startEq && bRev) */ - OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ - OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ - OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ - OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ - }; - static const u8 aEndOp[] = { - OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ - OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ - OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ - OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ - }; - u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ - u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ - u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ - int regBase; /* Base register holding constraint values */ - WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ - WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ - int startEq; /* True if range start uses ==, >= or <= */ - int endEq; /* True if range end uses ==, >= or <= */ - int start_constraints; /* Start of range is constrained */ - int nConstraint; /* Number of constraint terms */ - int iIdxCur; /* The VDBE cursor for the index */ - int nExtraReg = 0; /* Number of extra registers needed */ - int op; /* Instruction opcode */ - char *zStartAff; /* Affinity for start of range constraint */ - char *zEndAff = 0; /* Affinity for end of range constraint */ - u8 bSeekPastNull = 0; /* True to seek past initial nulls */ - u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ - int omitTable; /* True if we use the index only */ - int regBignull = 0; /* big-null flag register */ - - pIdx = pLoop->u.btree.pIndex; - iIdxCur = pLevel->iIdxCur; - assert( nEq>=pLoop->nSkip ); - - /* Find any inequality constraint terms for the start and end - ** of the range. - */ - j = nEq; - if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ - pRangeStart = pLoop->aLTerm[j++]; - nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); - /* Like optimization range constraints always occur in pairs */ - assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || - (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); - } - if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ - pRangeEnd = pLoop->aLTerm[j++]; - nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); -#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS - if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ - assert( pRangeStart!=0 ); /* LIKE opt constraints */ - assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ - pLevel->iLikeRepCntr = (u32)++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); - VdbeComment((v, "LIKE loop counter")); - pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); - /* iLikeRepCntr actually stores 2x the counter register number. The - ** bottom bit indicates whether the search order is ASC or DESC. */ - testcase( bRev ); - testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); - assert( (bRev & ~1)==0 ); - pLevel->iLikeRepCntr <<=1; - pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); - } -#endif - if( pRangeStart==0 ){ - j = pIdx->aiColumn[nEq]; - if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ - bSeekPastNull = 1; - } - } - } - assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); - - /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses - ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS - ** FIRST). In both cases separate ordered scans are made of those - ** index entries for which the column is null and for those for which - ** it is not. For an ASC sort, the non-NULL entries are scanned first. - ** For DESC, NULL entries are scanned first. - */ - if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0 - && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0 - ){ - assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 ); - assert( pRangeEnd==0 && pRangeStart==0 ); - testcase( pLoop->nSkip>0 ); - nExtraReg = 1; - bSeekPastNull = 1; - pLevel->regBignull = regBignull = ++pParse->nMem; - if( pLevel->iLeftJoin ){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull); - } - pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse); - } - - /* If we are doing a reverse order scan on an ascending index, or - ** a forward order scan on a descending index, interchange the - ** start and end terms (pRangeStart and pRangeEnd). - */ - if( (nEqnKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) - || (bRev && pIdx->nKeyCol==nEq) - ){ - SWAP(WhereTerm *, pRangeEnd, pRangeStart); - SWAP(u8, bSeekPastNull, bStopAtNull); - SWAP(u8, nBtm, nTop); - } - - /* Generate code to evaluate all constraint terms using == or IN - ** and store the values of those terms in an array of registers - ** starting at regBase. - */ - codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); - regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); - assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); - if( zStartAff && nTop ){ - zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); - } - addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt); - - testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); - testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); - testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); - testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); - startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); - endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); - start_constraints = pRangeStart || nEq>0; - - /* Seek the index cursor to the start of the range. */ - nConstraint = nEq; - if( pRangeStart ){ - Expr *pRight = pRangeStart->pExpr->pRight; - codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); - whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); - if( (pRangeStart->wtFlags & TERM_VNULL)==0 - && sqlite3ExprCanBeNull(pRight) - ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); - VdbeCoverage(v); - } - if( zStartAff ){ - updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); - } - nConstraint += nBtm; - testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); - if( sqlite3ExprIsVector(pRight)==0 ){ - disableTerm(pLevel, pRangeStart); - }else{ - startEq = 1; - } - bSeekPastNull = 0; - }else if( bSeekPastNull ){ - startEq = 0; - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); - start_constraints = 1; - nConstraint++; - }else if( regBignull ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); - start_constraints = 1; - nConstraint++; - } - codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); - if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ - /* The skip-scan logic inside the call to codeAllEqualityConstraints() - ** above has already left the cursor sitting on the correct row, - ** so no further seeking is needed */ - }else{ - if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){ - sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur); - } - if( regBignull ){ - sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull); - VdbeComment((v, "NULL-scan pass ctr")); - } - - op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; - assert( op!=0 ); - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); - VdbeCoverage(v); - VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); - VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); - VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); - VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); - VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); - VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); - - assert( bSeekPastNull==0 || bStopAtNull==0 ); - if( regBignull ){ - assert( bSeekPastNull==1 || bStopAtNull==1 ); - assert( bSeekPastNull==!bStopAtNull ); - assert( bStopAtNull==startEq ); - sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); - op = aStartOp[(nConstraint>1)*4 + 2 + bRev]; - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, - nConstraint-startEq); - VdbeCoverage(v); - VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); - VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); - VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); - VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); - assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE); - } - } - - /* Load the value for the inequality constraint at the end of the - ** range (if any). - */ - nConstraint = nEq; - if( pRangeEnd ){ - Expr *pRight = pRangeEnd->pExpr->pRight; - codeExprOrVector(pParse, pRight, regBase+nEq, nTop); - whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); - if( (pRangeEnd->wtFlags & TERM_VNULL)==0 - && sqlite3ExprCanBeNull(pRight) - ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); - VdbeCoverage(v); - } - if( zEndAff ){ - updateRangeAffinityStr(pRight, nTop, zEndAff); - codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); - }else{ - assert( pParse->db->mallocFailed ); - } - nConstraint += nTop; - testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); - - if( sqlite3ExprIsVector(pRight)==0 ){ - disableTerm(pLevel, pRangeEnd); - }else{ - endEq = 1; - } - }else if( bStopAtNull ){ - if( regBignull==0 ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); - endEq = 0; - } - nConstraint++; - } - sqlite3DbFree(db, zStartAff); - sqlite3DbFree(db, zEndAff); - - /* Top of the loop body */ - pLevel->p2 = sqlite3VdbeCurrentAddr(v); - - /* Check if the index cursor is past the end of the range. */ - if( nConstraint ){ - if( regBignull ){ - /* Except, skip the end-of-range check while doing the NULL-scan */ - sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3); - VdbeComment((v, "If NULL-scan 2nd pass")); - VdbeCoverage(v); - } - op = aEndOp[bRev*2 + endEq]; - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); - testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); - testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); - testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); - testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); - } - if( regBignull ){ - /* During a NULL-scan, check to see if we have reached the end of - ** the NULLs */ - assert( bSeekPastNull==!bStopAtNull ); - assert( bSeekPastNull+bStopAtNull==1 ); - assert( nConstraint+bSeekPastNull>0 ); - sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2); - VdbeComment((v, "If NULL-scan 1st pass")); - VdbeCoverage(v); - op = aEndOp[bRev*2 + bSeekPastNull]; - sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, - nConstraint+bSeekPastNull); - testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); - testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); - testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); - testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); - } - - if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){ - sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1); - } - - /* Seek the table cursor, if required */ - omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 - && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; - if( omitTable ){ - /* pIdx is a covering index. No need to access the main table. */ - }else if( HasRowid(pIdx->pTable) ){ - if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) - || ( (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)!=0 - && (pWInfo->eOnePass==ONEPASS_SINGLE || pLoop->nLTerm==0) ) - ){ - iRowidReg = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); - VdbeCoverage(v); - }else{ - codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); - } - }else if( iCur!=iIdxCur ){ - Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); - iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); - for(j=0; jnKeyCol; j++){ - k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); - } - sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, - iRowidReg, pPk->nKeyCol); VdbeCoverage(v); - } - - if( pLevel->iLeftJoin==0 ){ - /* If pIdx is an index on one or more expressions, then look through - ** all the expressions in pWInfo and try to transform matching expressions - ** into reference to index columns. Also attempt to translate references - ** to virtual columns in the table into references to (stored) columns - ** of the index. - ** - ** Do not do this for the RHS of a LEFT JOIN. This is because the - ** expression may be evaluated after OP_NullRow has been executed on - ** the cursor. In this case it is important to do the full evaluation, - ** as the result of the expression may not be NULL, even if all table - ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a - ** - ** Also, do not do this when processing one index an a multi-index - ** OR clause, since the transformation will become invalid once we - ** move forward to the next index. - ** https://sqlite.org/src/info/4e8e4857d32d401f - */ - if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ - whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo); - } - - /* If a partial index is driving the loop, try to eliminate WHERE clause - ** terms from the query that must be true due to the WHERE clause of - ** the partial index. - ** - ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work - ** for a LEFT JOIN. - */ - if( pIdx->pPartIdxWhere ){ - whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC); - } - }else{ - testcase( pIdx->pPartIdxWhere ); - /* The following assert() is not a requirement, merely an observation: - ** The OR-optimization doesn't work for the right hand table of - ** a LEFT JOIN: */ - assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ); - } - - /* Record the instruction used to terminate the loop. */ - if( pLoop->wsFlags & WHERE_ONEROW ){ - pLevel->op = OP_Noop; - }else if( bRev ){ - pLevel->op = OP_Prev; - }else{ - pLevel->op = OP_Next; - } - pLevel->p1 = iIdxCur; - pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; - if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ - pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; - }else{ - assert( pLevel->p5==0 ); - } - if( omitTable ) pIdx = 0; - }else - -#ifndef SQLITE_OMIT_OR_OPTIMIZATION - if( pLoop->wsFlags & WHERE_MULTI_OR ){ - /* Case 5: Two or more separately indexed terms connected by OR - ** - ** Example: - ** - ** CREATE TABLE t1(a,b,c,d); - ** CREATE INDEX i1 ON t1(a); - ** CREATE INDEX i2 ON t1(b); - ** CREATE INDEX i3 ON t1(c); - ** - ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) - ** - ** In the example, there are three indexed terms connected by OR. - ** The top of the loop looks like this: - ** - ** Null 1 # Zero the rowset in reg 1 - ** - ** Then, for each indexed term, the following. The arguments to - ** RowSetTest are such that the rowid of the current row is inserted - ** into the RowSet. If it is already present, control skips the - ** Gosub opcode and jumps straight to the code generated by WhereEnd(). - ** - ** sqlite3WhereBegin() - ** RowSetTest # Insert rowid into rowset - ** Gosub 2 A - ** sqlite3WhereEnd() - ** - ** Following the above, code to terminate the loop. Label A, the target - ** of the Gosub above, jumps to the instruction right after the Goto. - ** - ** Null 1 # Zero the rowset in reg 1 - ** Goto B # The loop is finished. - ** - ** A: # Return data, whatever. - ** - ** Return 2 # Jump back to the Gosub - ** - ** B: - ** - ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then - ** use an ephemeral index instead of a RowSet to record the primary - ** keys of the rows we have already seen. - ** - */ - WhereClause *pOrWc; /* The OR-clause broken out into subterms */ - SrcList *pOrTab; /* Shortened table list or OR-clause generation */ - Index *pCov = 0; /* Potential covering index (or NULL) */ - int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ - - int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ - int regRowset = 0; /* Register for RowSet object */ - int regRowid = 0; /* Register holding rowid */ - int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */ - int iRetInit; /* Address of regReturn init */ - int untestedTerms = 0; /* Some terms not completely tested */ - int ii; /* Loop counter */ - u16 wctrlFlags; /* Flags for sub-WHERE clause */ - Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ - Table *pTab = pTabItem->pTab; - - pTerm = pLoop->aLTerm[0]; - assert( pTerm!=0 ); - assert( pTerm->eOperator & WO_OR ); - assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); - pOrWc = &pTerm->u.pOrInfo->wc; - pLevel->op = OP_Return; - pLevel->p1 = regReturn; - - /* Set up a new SrcList in pOrTab containing the table being scanned - ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. - ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). - */ - if( pWInfo->nLevel>1 ){ - int nNotReady; /* The number of notReady tables */ - struct SrcList_item *origSrc; /* Original list of tables */ - nNotReady = pWInfo->nLevel - iLevel - 1; - pOrTab = sqlite3StackAllocRaw(db, - sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); - if( pOrTab==0 ) return notReady; - pOrTab->nAlloc = (u8)(nNotReady + 1); - pOrTab->nSrc = pOrTab->nAlloc; - memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); - origSrc = pWInfo->pTabList->a; - for(k=1; k<=nNotReady; k++){ - memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); - } - }else{ - pOrTab = pWInfo->pTabList; - } - - /* Initialize the rowset register to contain NULL. An SQL NULL is - ** equivalent to an empty rowset. Or, create an ephemeral index - ** capable of holding primary keys in the case of a WITHOUT ROWID. - ** - ** Also initialize regReturn to contain the address of the instruction - ** immediately following the OP_Return at the bottom of the loop. This - ** is required in a few obscure LEFT JOIN cases where control jumps - ** over the top of the loop into the body of it. In this case the - ** correct response for the end-of-loop code (the OP_Return) is to - ** fall through to the next instruction, just as an OP_Next does if - ** called on an uninitialized cursor. - */ - if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ - if( HasRowid(pTab) ){ - regRowset = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); - }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - regRowset = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); - } - regRowid = ++pParse->nMem; - } - iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); - - /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y - ** Then for every term xN, evaluate as the subexpression: xN AND z - ** That way, terms in y that are factored into the disjunction will - ** be picked up by the recursive calls to sqlite3WhereBegin() below. - ** - ** Actually, each subexpression is converted to "xN AND w" where w is - ** the "interesting" terms of z - terms that did not originate in the - ** ON or USING clause of a LEFT JOIN, and terms that are usable as - ** indices. - ** - ** This optimization also only applies if the (x1 OR x2 OR ...) term - ** is not contained in the ON clause of a LEFT JOIN. - ** See ticket http://www.sqlite.org/src/info/f2369304e4 - */ - if( pWC->nTerm>1 ){ - int iTerm; - for(iTerm=0; iTermnTerm; iTerm++){ - Expr *pExpr = pWC->a[iTerm].pExpr; - if( &pWC->a[iTerm] == pTerm ) continue; - testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); - testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); - if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; - if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; - testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); - pExpr = sqlite3ExprDup(db, pExpr, 0); - pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr); - } - if( pAndExpr ){ - /* The extra 0x10000 bit on the opcode is masked off and does not - ** become part of the new Expr.op. However, it does make the - ** op==TK_AND comparison inside of sqlite3PExpr() false, and this - ** prevents sqlite3PExpr() from implementing AND short-circuit - ** optimization, which we do not want here. */ - pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr); - } - } - - /* Run a separate WHERE clause for each term of the OR clause. After - ** eliminating duplicates from other WHERE clauses, the action for each - ** sub-WHERE clause is to to invoke the main loop body as a subroutine. - */ - wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); - ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR")); - for(ii=0; iinTerm; ii++){ - WhereTerm *pOrTerm = &pOrWc->a[ii]; - if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ - WhereInfo *pSubWInfo; /* Info for single OR-term scan */ - Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ - int jmp1 = 0; /* Address of jump operation */ - testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0 - && !ExprHasProperty(pOrExpr, EP_FromJoin) - ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */ - if( pAndExpr ){ - pAndExpr->pLeft = pOrExpr; - pOrExpr = pAndExpr; - } - /* Loop through table entries that match term pOrTerm. */ - ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1)); - WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); - pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, - wctrlFlags, iCovCur); - assert( pSubWInfo || pParse->nErr || db->mallocFailed ); - if( pSubWInfo ){ - WhereLoop *pSubLoop; - int addrExplain = sqlite3WhereExplainOneScan( - pParse, pOrTab, &pSubWInfo->a[0], 0 - ); - sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); - - /* This is the sub-WHERE clause body. First skip over - ** duplicate rows from prior sub-WHERE clauses, and record the - ** rowid (or PRIMARY KEY) for the current row so that the same - ** row will be skipped in subsequent sub-WHERE clauses. - */ - if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ - int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); - if( HasRowid(pTab) ){ - sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid); - jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, - regRowid, iSet); - VdbeCoverage(v); - }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - int nPk = pPk->nKeyCol; - int iPk; - int r; - - /* Read the PK into an array of temp registers. */ - r = sqlite3GetTempRange(pParse, nPk); - for(iPk=0; iPkaiColumn[iPk]; - sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk); - } - - /* Check if the temp table already contains this key. If so, - ** the row has already been included in the result set and - ** can be ignored (by jumping past the Gosub below). Otherwise, - ** insert the key into the temp table and proceed with processing - ** the row. - ** - ** Use some of the same optimizations as OP_RowSetTest: If iSet - ** is zero, assume that the key cannot already be present in - ** the temp table. And if iSet is -1, assume that there is no - ** need to insert the key into the temp table, as it will never - ** be tested for. */ - if( iSet ){ - jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); - VdbeCoverage(v); - } - if( iSet>=0 ){ - sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, - r, nPk); - if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); - } - - /* Release the array of temp registers */ - sqlite3ReleaseTempRange(pParse, r, nPk); - } - } - - /* Invoke the main loop body as a subroutine */ - sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); - - /* Jump here (skipping the main loop body subroutine) if the - ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ - if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); - - /* The pSubWInfo->untestedTerms flag means that this OR term - ** contained one or more AND term from a notReady table. The - ** terms from the notReady table could not be tested and will - ** need to be tested later. - */ - if( pSubWInfo->untestedTerms ) untestedTerms = 1; - - /* If all of the OR-connected terms are optimized using the same - ** index, and the index is opened using the same cursor number - ** by each call to sqlite3WhereBegin() made by this loop, it may - ** be possible to use that index as a covering index. - ** - ** If the call to sqlite3WhereBegin() above resulted in a scan that - ** uses an index, and this is either the first OR-connected term - ** processed or the index is the same as that used by all previous - ** terms, set pCov to the candidate covering index. Otherwise, set - ** pCov to NULL to indicate that no candidate covering index will - ** be available. - */ - pSubLoop = pSubWInfo->a[0].pWLoop; - assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); - if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 - && (ii==0 || pSubLoop->u.btree.pIndex==pCov) - && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) - ){ - assert( pSubWInfo->a[0].iIdxCur==iCovCur ); - pCov = pSubLoop->u.btree.pIndex; - }else{ - pCov = 0; - } - - /* Finish the loop through table entries that match term pOrTerm. */ - sqlite3WhereEnd(pSubWInfo); - ExplainQueryPlanPop(pParse); - } - } - } - ExplainQueryPlanPop(pParse); - pLevel->u.pCovidx = pCov; - if( pCov ) pLevel->iIdxCur = iCovCur; - if( pAndExpr ){ - pAndExpr->pLeft = 0; - sqlite3ExprDelete(db, pAndExpr); - } - sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); - sqlite3VdbeGoto(v, pLevel->addrBrk); - sqlite3VdbeResolveLabel(v, iLoopBody); - - if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); } - if( !untestedTerms ) disableTerm(pLevel, pTerm); - }else -#endif /* SQLITE_OMIT_OR_OPTIMIZATION */ - - { - /* Case 6: There is no usable index. We must do a complete - ** scan of the entire table. - */ - static const u8 aStep[] = { OP_Next, OP_Prev }; - static const u8 aStart[] = { OP_Rewind, OP_Last }; - assert( bRev==0 || bRev==1 ); - if( pTabItem->fg.isRecursive ){ - /* Tables marked isRecursive have only a single row that is stored in - ** a pseudo-cursor. No need to Rewind or Next such cursors. */ - pLevel->op = OP_Noop; - }else{ - codeCursorHint(pTabItem, pWInfo, pLevel, 0); - pLevel->op = aStep[bRev]; - pLevel->p1 = iCur; - pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt); - VdbeCoverageIf(v, bRev==0); - VdbeCoverageIf(v, bRev!=0); - pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; - } - } - -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); -#endif - - /* Insert code to test every subexpression that can be completely - ** computed using the current set of tables. - ** - ** This loop may run between one and three times, depending on the - ** constraints to be generated. The value of stack variable iLoop - ** determines the constraints coded by each iteration, as follows: - ** - ** iLoop==1: Code only expressions that are entirely covered by pIdx. - ** iLoop==2: Code remaining expressions that do not contain correlated - ** sub-queries. - ** iLoop==3: Code all remaining expressions. - ** - ** An effort is made to skip unnecessary iterations of the loop. - */ - iLoop = (pIdx ? 1 : 2); - do{ - int iNext = 0; /* Next value for iLoop */ - for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ - Expr *pE; - int skipLikeAddr = 0; - testcase( pTerm->wtFlags & TERM_VIRTUAL ); - testcase( pTerm->wtFlags & TERM_CODED ); - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; - if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ - testcase( pWInfo->untestedTerms==0 - && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); - pWInfo->untestedTerms = 1; - continue; - } - pE = pTerm->pExpr; - assert( pE!=0 ); - if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){ - continue; - } - - if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){ - iNext = 2; - continue; - } - if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){ - if( iNext==0 ) iNext = 3; - continue; - } - - if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){ - /* If the TERM_LIKECOND flag is set, that means that the range search - ** is sufficient to guarantee that the LIKE operator is true, so we - ** can skip the call to the like(A,B) function. But this only works - ** for strings. So do not skip the call to the function on the pass - ** that compares BLOBs. */ -#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS - continue; -#else - u32 x = pLevel->iLikeRepCntr; - if( x>0 ){ - skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1)); - VdbeCoverageIf(v, (x&1)==1); - VdbeCoverageIf(v, (x&1)==0); - } -#endif - } -#ifdef WHERETRACE_ENABLED /* 0xffff */ - if( sqlite3WhereTrace ){ - VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d", - pWC->nTerm-j, pTerm, iLoop)); - } - if( sqlite3WhereTrace & 0x800 ){ - sqlite3DebugPrintf("Coding auxiliary constraint:\n"); - sqlite3WhereTermPrint(pTerm, pWC->nTerm-j); - } -#endif - sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); - if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); - pTerm->wtFlags |= TERM_CODED; - } - iLoop = iNext; - }while( iLoop>0 ); - - /* Insert code to test for implied constraints based on transitivity - ** of the "==" operator. - ** - ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" - ** and we are coding the t1 loop and the t2 loop has not yet coded, - ** then we cannot use the "t1.a=t2.b" constraint, but we can code - ** the implied "t1.a=123" constraint. - */ - for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ - Expr *pE, sEAlt; - WhereTerm *pAlt; - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; - if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; - if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; - if( pTerm->leftCursor!=iCur ) continue; - if( pTabItem->fg.jointype & JT_LEFT ) continue; - pE = pTerm->pExpr; -#ifdef WHERETRACE_ENABLED /* 0x800 */ - if( sqlite3WhereTrace & 0x800 ){ - sqlite3DebugPrintf("Coding transitive constraint:\n"); - sqlite3WhereTermPrint(pTerm, pWC->nTerm-j); - } -#endif - assert( !ExprHasProperty(pE, EP_FromJoin) ); - assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); - pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, - WO_EQ|WO_IN|WO_IS, 0); - if( pAlt==0 ) continue; - if( pAlt->wtFlags & (TERM_CODED) ) continue; - if( (pAlt->eOperator & WO_IN) - && (pAlt->pExpr->flags & EP_xIsSelect) - && (pAlt->pExpr->x.pSelect->pEList->nExpr>1) - ){ - continue; - } - testcase( pAlt->eOperator & WO_EQ ); - testcase( pAlt->eOperator & WO_IS ); - testcase( pAlt->eOperator & WO_IN ); - VdbeModuleComment((v, "begin transitive constraint")); - sEAlt = *pAlt->pExpr; - sEAlt.pLeft = pE->pLeft; - sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); - } - - /* For a LEFT OUTER JOIN, generate code that will record the fact that - ** at least one row of the right table has matched the left table. - */ - if( pLevel->iLeftJoin ){ - pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); - VdbeComment((v, "record LEFT JOIN hit")); - for(pTerm=pWC->a, j=0; jnTerm; j++, pTerm++){ - testcase( pTerm->wtFlags & TERM_VIRTUAL ); - testcase( pTerm->wtFlags & TERM_CODED ); - if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; - if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ - assert( pWInfo->untestedTerms ); - continue; - } - assert( pTerm->pExpr ); - sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); - pTerm->wtFlags |= TERM_CODED; - } - } - -#if WHERETRACE_ENABLED /* 0x20800 */ - if( sqlite3WhereTrace & 0x20000 ){ - sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n", - iLevel); - sqlite3WhereClausePrint(pWC); - } - if( sqlite3WhereTrace & 0x800 ){ - sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n", - iLevel, (u64)pLevel->notReady); - } -#endif - return pLevel->notReady; -} - -/************** End of wherecode.c *******************************************/ -/************** Begin file whereexpr.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 module contains C code that generates VDBE code used to process -** the WHERE clause of SQL statements. -** -** This file was originally part of where.c but was split out to improve -** readability and editabiliity. This file contains utility routines for -** analyzing Expr objects in the WHERE clause. -*/ -/* #include "sqliteInt.h" */ -/* #include "whereInt.h" */ - -/* Forward declarations */ -static void exprAnalyze(SrcList*, WhereClause*, int); - -/* -** Deallocate all memory associated with a WhereOrInfo object. -*/ -static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ - sqlite3WhereClauseClear(&p->wc); - sqlite3DbFree(db, p); -} - -/* -** Deallocate all memory associated with a WhereAndInfo object. -*/ -static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ - sqlite3WhereClauseClear(&p->wc); - sqlite3DbFree(db, p); -} - -/* -** Add a single new WhereTerm entry to the WhereClause object pWC. -** The new WhereTerm object is constructed from Expr p and with wtFlags. -** The index in pWC->a[] of the new WhereTerm is returned on success. -** 0 is returned if the new WhereTerm could not be added due to a memory -** allocation error. The memory allocation failure will be recorded in -** the db->mallocFailed flag so that higher-level functions can detect it. -** -** This routine will increase the size of the pWC->a[] array as necessary. -** -** If the wtFlags argument includes TERM_DYNAMIC, then responsibility -** for freeing the expression p is assumed by the WhereClause object pWC. -** This is true even if this routine fails to allocate a new WhereTerm. -** -** WARNING: This routine might reallocate the space used to store -** WhereTerms. All pointers to WhereTerms should be invalidated after -** calling this routine. Such pointers may be reinitialized by referencing -** the pWC->a[] array. -*/ -static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){ - WhereTerm *pTerm; - int idx; - testcase( wtFlags & TERM_VIRTUAL ); - if( pWC->nTerm>=pWC->nSlot ){ - WhereTerm *pOld = pWC->a; - sqlite3 *db = pWC->pWInfo->pParse->db; - pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); - if( pWC->a==0 ){ - if( wtFlags & TERM_DYNAMIC ){ - sqlite3ExprDelete(db, p); - } - pWC->a = pOld; - return 0; - } - memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); - if( pOld!=pWC->aStatic ){ - sqlite3DbFree(db, pOld); - } - pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); - } - pTerm = &pWC->a[idx = pWC->nTerm++]; - if( p && ExprHasProperty(p, EP_Unlikely) ){ - pTerm->truthProb = sqlite3LogEst(p->iTable) - 270; - }else{ - pTerm->truthProb = 1; - } - pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p); - pTerm->wtFlags = wtFlags; - pTerm->pWC = pWC; - pTerm->iParent = -1; - memset(&pTerm->eOperator, 0, - sizeof(WhereTerm) - offsetof(WhereTerm,eOperator)); - return idx; -} - -/* -** Return TRUE if the given operator is one of the operators that is -** allowed for an indexable WHERE clause term. The allowed operators are -** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL" -*/ -static int allowedOp(int op){ - assert( TK_GT>TK_EQ && TK_GTTK_EQ && TK_LTTK_EQ && TK_LE=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS; -} - -/* -** Commute a comparison operator. Expressions of the form "X op Y" -** are converted into "Y op X". -*/ -static u16 exprCommute(Parse *pParse, Expr *pExpr){ - if( pExpr->pLeft->op==TK_VECTOR - || pExpr->pRight->op==TK_VECTOR - || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) != - sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft) - ){ - pExpr->flags ^= EP_Commuted; - } - SWAP(Expr*,pExpr->pRight,pExpr->pLeft); - if( pExpr->op>=TK_GT ){ - assert( TK_LT==TK_GT+2 ); - assert( TK_GE==TK_LE+2 ); - assert( TK_GT>TK_EQ ); - assert( TK_GTop>=TK_GT && pExpr->op<=TK_GE ); - pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; - } - return 0; -} - -/* -** Translate from TK_xx operator to WO_xx bitmask. -*/ -static u16 operatorMask(int op){ - u16 c; - assert( allowedOp(op) ); - if( op==TK_IN ){ - c = WO_IN; - }else if( op==TK_ISNULL ){ - c = WO_ISNULL; - }else if( op==TK_IS ){ - c = WO_IS; - }else{ - assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); - c = (u16)(WO_EQ<<(op-TK_EQ)); - } - assert( op!=TK_ISNULL || c==WO_ISNULL ); - assert( op!=TK_IN || c==WO_IN ); - assert( op!=TK_EQ || c==WO_EQ ); - assert( op!=TK_LT || c==WO_LT ); - assert( op!=TK_LE || c==WO_LE ); - assert( op!=TK_GT || c==WO_GT ); - assert( op!=TK_GE || c==WO_GE ); - assert( op!=TK_IS || c==WO_IS ); - return c; -} - - -#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION -/* -** Check to see if the given expression is a LIKE or GLOB operator that -** can be optimized using inequality constraints. Return TRUE if it is -** so and false if not. -** -** In order for the operator to be optimizible, the RHS must be a string -** literal that does not begin with a wildcard. The LHS must be a column -** that may only be NULL, a string, or a BLOB, never a number. (This means -** that virtual tables cannot participate in the LIKE optimization.) The -** collating sequence for the column on the LHS must be appropriate for -** the operator. -*/ -static int isLikeOrGlob( - Parse *pParse, /* Parsing and code generating context */ - Expr *pExpr, /* Test this expression */ - Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ - int *pisComplete, /* True if the only wildcard is % in the last character */ - int *pnoCase /* True if uppercase is equivalent to lowercase */ -){ - const u8 *z = 0; /* String on RHS of LIKE operator */ - Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ - ExprList *pList; /* List of operands to the LIKE operator */ - u8 c; /* One character in z[] */ - int cnt; /* Number of non-wildcard prefix characters */ - u8 wc[4]; /* Wildcard characters */ - sqlite3 *db = pParse->db; /* Database connection */ - sqlite3_value *pVal = 0; - int op; /* Opcode of pRight */ - int rc; /* Result code to return */ - - if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){ - return 0; - } -#ifdef SQLITE_EBCDIC - if( *pnoCase ) return 0; -#endif - pList = pExpr->x.pList; - pLeft = pList->a[1].pExpr; - - pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr); - op = pRight->op; - if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){ - Vdbe *pReprepare = pParse->pReprepare; - int iCol = pRight->iColumn; - pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB); - if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ - z = sqlite3_value_text(pVal); - } - sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); - assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); - }else if( op==TK_STRING ){ - z = (u8*)pRight->u.zToken; - } - if( z ){ - - /* Count the number of prefix characters prior to the first wildcard */ - cnt = 0; - while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ - cnt++; - if( c==wc[3] && z[cnt]!=0 ) cnt++; - } - - /* The optimization is possible only if (1) the pattern does not begin - ** with a wildcard and if (2) the non-wildcard prefix does not end with - ** an (illegal 0xff) character, or (3) the pattern does not consist of - ** a single escape character. The second condition is necessary so - ** that we can increment the prefix key to find an upper bound for the - ** range search. The third is because the caller assumes that the pattern - ** consists of at least one character after all escapes have been - ** removed. */ - if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){ - Expr *pPrefix; - - /* A "complete" match if the pattern ends with "*" or "%" */ - *pisComplete = c==wc[0] && z[cnt+1]==0; - - /* Get the pattern prefix. Remove all escapes from the prefix. */ - pPrefix = sqlite3Expr(db, TK_STRING, (char*)z); - if( pPrefix ){ - int iFrom, iTo; - char *zNew = pPrefix->u.zToken; - zNew[cnt] = 0; - for(iFrom=iTo=0; iFrom0 ); - - /* If the LHS is not an ordinary column with TEXT affinity, then the - ** pattern prefix boundaries (both the start and end boundaries) must - ** not look like a number. Otherwise the pattern might be treated as - ** a number, which will invalidate the LIKE optimization. - ** - ** Getting this right has been a persistent source of bugs in the - ** LIKE optimization. See, for example: - ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1 - ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28 - ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07 - ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975 - ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a - */ - if( pLeft->op!=TK_COLUMN - || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT - || IsVirtual(pLeft->y.pTab) /* Value might be numeric */ - ){ - int isNum; - double rDummy; - isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); - if( isNum<=0 ){ - if( iTo==1 && zNew[0]=='-' ){ - isNum = +1; - }else{ - zNew[iTo-1]++; - isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); - zNew[iTo-1]--; - } - } - if( isNum>0 ){ - sqlite3ExprDelete(db, pPrefix); - sqlite3ValueFree(pVal); - return 0; - } - } - } - *ppPrefix = pPrefix; - - /* If the RHS pattern is a bound parameter, make arrangements to - ** reprepare the statement when that parameter is rebound */ - if( op==TK_VARIABLE ){ - Vdbe *v = pParse->pVdbe; - sqlite3VdbeSetVarmask(v, pRight->iColumn); - if( *pisComplete && pRight->u.zToken[1] ){ - /* If the rhs of the LIKE expression is a variable, and the current - ** value of the variable means there is no need to invoke the LIKE - ** function, then no OP_Variable will be added to the program. - ** This causes problems for the sqlite3_bind_parameter_name() - ** API. To work around them, add a dummy OP_Variable here. - */ - int r1 = sqlite3GetTempReg(pParse); - sqlite3ExprCodeTarget(pParse, pRight, r1); - sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); - sqlite3ReleaseTempReg(pParse, r1); - } - } - }else{ - z = 0; - } - } - - rc = (z!=0); - sqlite3ValueFree(pVal); - return rc; -} -#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ - - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Check to see if the pExpr expression is a form that needs to be passed -** to the xBestIndex method of virtual tables. Forms of interest include: -** -** Expression Virtual Table Operator -** ----------------------- --------------------------------- -** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH -** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB -** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE -** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP -** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE -** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE -** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT -** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT -** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL -** -** In every case, "column" must be a column of a virtual table. If there -** is a match, set *ppLeft to the "column" expression, set *ppRight to the -** "expr" expression (even though in forms (6) and (8) the column is on the -** right and the expression is on the left). Also set *peOp2 to the -** appropriate virtual table operator. The return value is 1 or 2 if there -** is a match. The usual return is 1, but if the RHS is also a column -** of virtual table in forms (5) or (7) then return 2. -** -** If the expression matches none of the patterns above, return 0. -*/ -static int isAuxiliaryVtabOperator( - sqlite3 *db, /* Parsing context */ - Expr *pExpr, /* Test this expression */ - unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */ - Expr **ppLeft, /* Column expression to left of MATCH/op2 */ - Expr **ppRight /* Expression to left of MATCH/op2 */ -){ - if( pExpr->op==TK_FUNCTION ){ - static const struct Op2 { - const char *zOp; - unsigned char eOp2; - } aOp[] = { - { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, - { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, - { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, - { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } - }; - ExprList *pList; - Expr *pCol; /* Column reference */ - int i; - - pList = pExpr->x.pList; - if( pList==0 || pList->nExpr!=2 ){ - return 0; - } - - /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a - ** virtual table on their second argument, which is the same as - ** the left-hand side operand in their in-fix form. - ** - ** vtab_column MATCH expression - ** MATCH(expression,vtab_column) - */ - pCol = pList->a[1].pExpr; - testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 ); - if( ExprIsVtab(pCol) ){ - for(i=0; iu.zToken, aOp[i].zOp)==0 ){ - *peOp2 = aOp[i].eOp2; - *ppRight = pList->a[0].pExpr; - *ppLeft = pCol; - return 1; - } - } - } - - /* We can also match against the first column of overloaded - ** functions where xFindFunction returns a value of at least - ** SQLITE_INDEX_CONSTRAINT_FUNCTION. - ** - ** OVERLOADED(vtab_column,expression) - ** - ** Historically, xFindFunction expected to see lower-case function - ** names. But for this use case, xFindFunction is expected to deal - ** with function names in an arbitrary case. - */ - pCol = pList->a[0].pExpr; - testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 ); - if( ExprIsVtab(pCol) ){ - sqlite3_vtab *pVtab; - sqlite3_module *pMod; - void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**); - void *pNotUsed; - pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab; - assert( pVtab!=0 ); - assert( pVtab->pModule!=0 ); - pMod = (sqlite3_module *)pVtab->pModule; - if( pMod->xFindFunction!=0 ){ - i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed); - if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){ - *peOp2 = i; - *ppRight = pList->a[1].pExpr; - *ppLeft = pCol; - return 1; - } - } - } - }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){ - int res = 0; - Expr *pLeft = pExpr->pLeft; - Expr *pRight = pExpr->pRight; - testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 ); - if( ExprIsVtab(pLeft) ){ - res++; - } - testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 ); - if( pRight && ExprIsVtab(pRight) ){ - res++; - SWAP(Expr*, pLeft, pRight); - } - *ppLeft = pLeft; - *ppRight = pRight; - if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE; - if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT; - if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL; - return res; - } - return 0; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -/* -** If the pBase expression originated in the ON or USING clause of -** a join, then transfer the appropriate markings over to derived. -*/ -static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ - if( pDerived ){ - pDerived->flags |= pBase->flags & EP_FromJoin; - pDerived->iRightJoinTable = pBase->iRightJoinTable; - } -} - -/* -** Mark term iChild as being a child of term iParent -*/ -static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){ - pWC->a[iChild].iParent = iParent; - pWC->a[iChild].truthProb = pWC->a[iParent].truthProb; - pWC->a[iParent].nChild++; -} - -/* -** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not -** a conjunction, then return just pTerm when N==0. If N is exceeds -** the number of available subterms, return NULL. -*/ -static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){ - if( pTerm->eOperator!=WO_AND ){ - return N==0 ? pTerm : 0; - } - if( Nu.pAndInfo->wc.nTerm ){ - return &pTerm->u.pAndInfo->wc.a[N]; - } - return 0; -} - -/* -** Subterms pOne and pTwo are contained within WHERE clause pWC. The -** two subterms are in disjunction - they are OR-ed together. -** -** If these two terms are both of the form: "A op B" with the same -** A and B values but different operators and if the operators are -** compatible (if one is = and the other is <, for example) then -** add a new virtual AND term to pWC that is the combination of the -** two. -** -** Some examples: -** -** x x<=y -** x=y OR x=y --> x=y -** x<=y OR x x<=y -** -** The following is NOT generated: -** -** xy --> x!=y -*/ -static void whereCombineDisjuncts( - SrcList *pSrc, /* the FROM clause */ - WhereClause *pWC, /* The complete WHERE clause */ - WhereTerm *pOne, /* First disjunct */ - WhereTerm *pTwo /* Second disjunct */ -){ - u16 eOp = pOne->eOperator | pTwo->eOperator; - sqlite3 *db; /* Database connection (for malloc) */ - Expr *pNew; /* New virtual expression */ - int op; /* Operator for the combined expression */ - int idxNew; /* Index in pWC of the next virtual term */ - - if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; - if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; - if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp - && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; - assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); - assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); - if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; - if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return; - /* If we reach this point, it means the two subterms can be combined */ - if( (eOp & (eOp-1))!=0 ){ - if( eOp & (WO_LT|WO_LE) ){ - eOp = WO_LE; - }else{ - assert( eOp & (WO_GT|WO_GE) ); - eOp = WO_GE; - } - } - db = pWC->pWInfo->pParse->db; - pNew = sqlite3ExprDup(db, pOne->pExpr, 0); - if( pNew==0 ) return; - for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( opop = op; - idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); - exprAnalyze(pSrc, pWC, idxNew); -} - -#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) -/* -** Analyze a term that consists of two or more OR-connected -** subterms. So in: -** -** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) -** ^^^^^^^^^^^^^^^^^^^^ -** -** This routine analyzes terms such as the middle term in the above example. -** A WhereOrTerm object is computed and attached to the term under -** analysis, regardless of the outcome of the analysis. Hence: -** -** WhereTerm.wtFlags |= TERM_ORINFO -** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object -** -** The term being analyzed must have two or more of OR-connected subterms. -** A single subterm might be a set of AND-connected sub-subterms. -** Examples of terms under analysis: -** -** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 -** (B) x=expr1 OR expr2=x OR x=expr3 -** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) -** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') -** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) -** (F) x>A OR (x=A AND y>=B) -** -** CASE 1: -** -** If all subterms are of the form T.C=expr for some single column of C and -** a single table T (as shown in example B above) then create a new virtual -** term that is an equivalent IN expression. In other words, if the term -** being analyzed is: -** -** x = expr1 OR expr2 = x OR x = expr3 -** -** then create a new virtual term like this: -** -** x IN (expr1,expr2,expr3) -** -** CASE 2: -** -** If there are exactly two disjuncts and one side has x>A and the other side -** has x=A (for the same x and A) then add a new virtual conjunct term to the -** WHERE clause of the form "x>=A". Example: -** -** x>A OR (x=A AND y>B) adds: x>=A -** -** The added conjunct can sometimes be helpful in query planning. -** -** CASE 3: -** -** If all subterms are indexable by a single table T, then set -** -** WhereTerm.eOperator = WO_OR -** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T -** -** A subterm is "indexable" if it is of the form -** "T.C " where C is any column of table T and -** is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". -** A subterm is also indexable if it is an AND of two or more -** subsubterms at least one of which is indexable. Indexable AND -** subterms have their eOperator set to WO_AND and they have -** u.pAndInfo set to a dynamically allocated WhereAndTerm object. -** -** From another point of view, "indexable" means that the subterm could -** potentially be used with an index if an appropriate index exists. -** This analysis does not consider whether or not the index exists; that -** is decided elsewhere. This analysis only looks at whether subterms -** appropriate for indexing exist. -** -** All examples A through E above satisfy case 3. But if a term -** also satisfies case 1 (such as B) we know that the optimizer will -** always prefer case 1, so in that case we pretend that case 3 is not -** satisfied. -** -** It might be the case that multiple tables are indexable. For example, -** (E) above is indexable on tables P, Q, and R. -** -** Terms that satisfy case 3 are candidates for lookup by using -** separate indices to find rowids for each subterm and composing -** the union of all rowids using a RowSet object. This is similar -** to "bitmap indices" in other database engines. -** -** OTHERWISE: -** -** If none of cases 1, 2, or 3 apply, then leave the eOperator set to -** zero. This term is not useful for search. -*/ -static void exprAnalyzeOrTerm( - SrcList *pSrc, /* the FROM clause */ - WhereClause *pWC, /* the complete WHERE clause */ - int idxTerm /* Index of the OR-term to be analyzed */ -){ - WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ - Parse *pParse = pWInfo->pParse; /* Parser context */ - sqlite3 *db = pParse->db; /* Database connection */ - WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ - Expr *pExpr = pTerm->pExpr; /* The expression of the term */ - int i; /* Loop counters */ - WhereClause *pOrWc; /* Breakup of pTerm into subterms */ - WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ - WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ - Bitmask chngToIN; /* Tables that might satisfy case 1 */ - Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ - - /* - ** Break the OR clause into its separate subterms. The subterms are - ** stored in a WhereClause structure containing within the WhereOrInfo - ** object that is attached to the original OR clause term. - */ - assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); - assert( pExpr->op==TK_OR ); - pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); - if( pOrInfo==0 ) return; - pTerm->wtFlags |= TERM_ORINFO; - pOrWc = &pOrInfo->wc; - memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic)); - sqlite3WhereClauseInit(pOrWc, pWInfo); - sqlite3WhereSplit(pOrWc, pExpr, TK_OR); - sqlite3WhereExprAnalyze(pSrc, pOrWc); - if( db->mallocFailed ) return; - assert( pOrWc->nTerm>=2 ); - - /* - ** Compute the set of tables that might satisfy cases 1 or 3. - */ - indexable = ~(Bitmask)0; - chngToIN = ~(Bitmask)0; - for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ - if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ - WhereAndInfo *pAndInfo; - assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); - chngToIN = 0; - pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo)); - if( pAndInfo ){ - WhereClause *pAndWC; - WhereTerm *pAndTerm; - int j; - Bitmask b = 0; - pOrTerm->u.pAndInfo = pAndInfo; - pOrTerm->wtFlags |= TERM_ANDINFO; - pOrTerm->eOperator = WO_AND; - pAndWC = &pAndInfo->wc; - memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic)); - sqlite3WhereClauseInit(pAndWC, pWC->pWInfo); - sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); - sqlite3WhereExprAnalyze(pSrc, pAndWC); - pAndWC->pOuter = pWC; - if( !db->mallocFailed ){ - for(j=0, pAndTerm=pAndWC->a; jnTerm; j++, pAndTerm++){ - assert( pAndTerm->pExpr ); - if( allowedOp(pAndTerm->pExpr->op) - || pAndTerm->eOperator==WO_AUX - ){ - b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); - } - } - } - indexable &= b; - } - }else if( pOrTerm->wtFlags & TERM_COPIED ){ - /* Skip this term for now. We revisit it when we process the - ** corresponding TERM_VIRTUAL term */ - }else{ - Bitmask b; - b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); - if( pOrTerm->wtFlags & TERM_VIRTUAL ){ - WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; - b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); - } - indexable &= b; - if( (pOrTerm->eOperator & WO_EQ)==0 ){ - chngToIN = 0; - }else{ - chngToIN &= b; - } - } - } - - /* - ** Record the set of tables that satisfy case 3. The set might be - ** empty. - */ - pOrInfo->indexable = indexable; - if( indexable ){ - pTerm->eOperator = WO_OR; - pWC->hasOr = 1; - }else{ - pTerm->eOperator = WO_OR; - } - - /* For a two-way OR, attempt to implementation case 2. - */ - if( indexable && pOrWc->nTerm==2 ){ - int iOne = 0; - WhereTerm *pOne; - while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){ - int iTwo = 0; - WhereTerm *pTwo; - while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){ - whereCombineDisjuncts(pSrc, pWC, pOne, pTwo); - } - } - } - - /* - ** chngToIN holds a set of tables that *might* satisfy case 1. But - ** we have to do some additional checking to see if case 1 really - ** is satisfied. - ** - ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means - ** that there is no possibility of transforming the OR clause into an - ** IN operator because one or more terms in the OR clause contain - ** something other than == on a column in the single table. The 1-bit - ** case means that every term of the OR clause is of the form - ** "table.column=expr" for some single table. The one bit that is set - ** will correspond to the common table. We still need to check to make - ** sure the same column is used on all terms. The 2-bit case is when - ** the all terms are of the form "table1.column=table2.column". It - ** might be possible to form an IN operator with either table1.column - ** or table2.column as the LHS if either is common to every term of - ** the OR clause. - ** - ** Note that terms of the form "table.column1=table.column2" (the - ** same table on both sizes of the ==) cannot be optimized. - */ - if( chngToIN ){ - int okToChngToIN = 0; /* True if the conversion to IN is valid */ - int iColumn = -1; /* Column index on lhs of IN operator */ - int iCursor = -1; /* Table cursor common to all terms */ - int j = 0; /* Loop counter */ - - /* Search for a table and column that appears on one side or the - ** other of the == operator in every subterm. That table and column - ** will be recorded in iCursor and iColumn. There might not be any - ** such table and column. Set okToChngToIN if an appropriate table - ** and column is found but leave okToChngToIN false if not found. - */ - for(j=0; j<2 && !okToChngToIN; j++){ - Expr *pLeft = 0; - pOrTerm = pOrWc->a; - for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ - assert( pOrTerm->eOperator & WO_EQ ); - pOrTerm->wtFlags &= ~TERM_OR_OK; - if( pOrTerm->leftCursor==iCursor ){ - /* This is the 2-bit case and we are on the second iteration and - ** current term is from the first iteration. So skip this term. */ - assert( j==1 ); - continue; - } - if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet, - pOrTerm->leftCursor))==0 ){ - /* This term must be of the form t1.a==t2.b where t2 is in the - ** chngToIN set but t1 is not. This term will be either preceded - ** or follwed by an inverted copy (t2.b==t1.a). Skip this term - ** and use its inversion. */ - testcase( pOrTerm->wtFlags & TERM_COPIED ); - testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); - assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); - continue; - } - iColumn = pOrTerm->u.leftColumn; - iCursor = pOrTerm->leftCursor; - pLeft = pOrTerm->pExpr->pLeft; - break; - } - if( i<0 ){ - /* No candidate table+column was found. This can only occur - ** on the second iteration */ - assert( j==1 ); - assert( IsPowerOfTwo(chngToIN) ); - assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) ); - break; - } - testcase( j==1 ); - - /* We have found a candidate table and column. Check to see if that - ** table and column is common to every term in the OR clause */ - okToChngToIN = 1; - for(; i>=0 && okToChngToIN; i--, pOrTerm++){ - assert( pOrTerm->eOperator & WO_EQ ); - if( pOrTerm->leftCursor!=iCursor ){ - pOrTerm->wtFlags &= ~TERM_OR_OK; - }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR - && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1) - )){ - okToChngToIN = 0; - }else{ - int affLeft, affRight; - /* If the right-hand side is also a column, then the affinities - ** of both right and left sides must be such that no type - ** conversions are required on the right. (Ticket #2249) - */ - affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); - affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); - if( affRight!=0 && affRight!=affLeft ){ - okToChngToIN = 0; - }else{ - pOrTerm->wtFlags |= TERM_OR_OK; - } - } - } - } - - /* At this point, okToChngToIN is true if original pTerm satisfies - ** case 1. In that case, construct a new virtual term that is - ** pTerm converted into an IN operator. - */ - if( okToChngToIN ){ - Expr *pDup; /* A transient duplicate expression */ - ExprList *pList = 0; /* The RHS of the IN operator */ - Expr *pLeft = 0; /* The LHS of the IN operator */ - Expr *pNew; /* The complete IN operator */ - - for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ - if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; - assert( pOrTerm->eOperator & WO_EQ ); - assert( pOrTerm->leftCursor==iCursor ); - assert( pOrTerm->u.leftColumn==iColumn ); - pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); - pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); - pLeft = pOrTerm->pExpr->pLeft; - } - assert( pLeft!=0 ); - pDup = sqlite3ExprDup(db, pLeft, 0); - pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0); - if( pNew ){ - int idxNew; - transferJoinMarkings(pNew, pExpr); - assert( !ExprHasProperty(pNew, EP_xIsSelect) ); - pNew->x.pList = pList; - idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); - testcase( idxNew==0 ); - exprAnalyze(pSrc, pWC, idxNew); - /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */ - markTermAsChild(pWC, idxNew, idxTerm); - }else{ - sqlite3ExprListDelete(db, pList); - } - } - } -} -#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ - -/* -** We already know that pExpr is a binary operator where both operands are -** column references. This routine checks to see if pExpr is an equivalence -** relation: -** 1. The SQLITE_Transitive optimization must be enabled -** 2. Must be either an == or an IS operator -** 3. Not originating in the ON clause of an OUTER JOIN -** 4. The affinities of A and B must be compatible -** 5a. Both operands use the same collating sequence OR -** 5b. The overall collating sequence is BINARY -** If this routine returns TRUE, that means that the RHS can be substituted -** for the LHS anyplace else in the WHERE clause where the LHS column occurs. -** This is an optimization. No harm comes from returning 0. But if 1 is -** returned when it should not be, then incorrect answers might result. -*/ -static int termIsEquivalence(Parse *pParse, Expr *pExpr){ - char aff1, aff2; - CollSeq *pColl; - if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; - if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; - if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0; - aff1 = sqlite3ExprAffinity(pExpr->pLeft); - aff2 = sqlite3ExprAffinity(pExpr->pRight); - if( aff1!=aff2 - && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) - ){ - return 0; - } - pColl = sqlite3ExprCompareCollSeq(pParse, pExpr); - if( sqlite3IsBinary(pColl) ) return 1; - return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight); -} - -/* -** Recursively walk the expressions of a SELECT statement and generate -** a bitmask indicating which tables are used in that expression -** tree. -*/ -static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ - Bitmask mask = 0; - while( pS ){ - SrcList *pSrc = pS->pSrc; - mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList); - mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); - mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); - mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere); - mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving); - if( ALWAYS(pSrc!=0) ){ - int i; - for(i=0; inSrc; i++){ - mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect); - mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); - if( pSrc->a[i].fg.isTabFunc ){ - mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg); - } - } - } - pS = pS->pPrior; - } - return mask; -} - -/* -** Expression pExpr is one operand of a comparison operator that might -** be useful for indexing. This routine checks to see if pExpr appears -** in any index. Return TRUE (1) if pExpr is an indexed term and return -** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor -** number of the table that is indexed and aiCurCol[1] to the column number -** of the column that is indexed, or XN_EXPR (-2) if an expression is being -** indexed. -** -** If pExpr is a TK_COLUMN column reference, then this routine always returns -** true even if that particular column is not indexed, because the column -** might be added to an automatic index later. -*/ -static SQLITE_NOINLINE int exprMightBeIndexed2( - SrcList *pFrom, /* The FROM clause */ - Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ - int *aiCurCol, /* Write the referenced table cursor and column here */ - Expr *pExpr /* An operand of a comparison operator */ -){ - Index *pIdx; - int i; - int iCur; - for(i=0; mPrereq>1; i++, mPrereq>>=1){} - iCur = pFrom->a[i].iCursor; - for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->aColExpr==0 ) continue; - for(i=0; inKeyCol; i++){ - if( pIdx->aiColumn[i]!=XN_EXPR ) continue; - if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ - aiCurCol[0] = iCur; - aiCurCol[1] = XN_EXPR; - return 1; - } - } - } - return 0; -} -static int exprMightBeIndexed( - SrcList *pFrom, /* The FROM clause */ - Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ - int *aiCurCol, /* Write the referenced table cursor & column here */ - Expr *pExpr, /* An operand of a comparison operator */ - int op /* The specific comparison operator */ -){ - /* If this expression is a vector to the left or right of a - ** inequality constraint (>, <, >= or <=), perform the processing - ** on the first element of the vector. */ - assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE ); - assert( TK_ISop==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){ - pExpr = pExpr->x.pList->a[0].pExpr; - } - - if( pExpr->op==TK_COLUMN ){ - aiCurCol[0] = pExpr->iTable; - aiCurCol[1] = pExpr->iColumn; - return 1; - } - if( mPrereq==0 ) return 0; /* No table references */ - if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */ - return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr); -} - -/* -** The input to this routine is an WhereTerm structure with only the -** "pExpr" field filled in. The job of this routine is to analyze the -** subexpression and populate all the other fields of the WhereTerm -** structure. -** -** If the expression is of the form " X" it gets commuted -** to the standard form of "X ". -** -** If the expression is of the form "X Y" where both X and Y are -** columns, then the original expression is unchanged and a new virtual -** term of the form "Y X" is added to the WHERE clause and -** analyzed separately. The original term is marked with TERM_COPIED -** and the new term is marked with TERM_DYNAMIC (because it's pExpr -** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it -** is a commuted copy of a prior term.) The original term has nChild=1 -** and the copy has idxParent set to the index of the original term. -*/ -static void exprAnalyze( - SrcList *pSrc, /* the FROM clause */ - WhereClause *pWC, /* the WHERE clause */ - int idxTerm /* Index of the term to be analyzed */ -){ - WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ - WhereTerm *pTerm; /* The term to be analyzed */ - WhereMaskSet *pMaskSet; /* Set of table index masks */ - Expr *pExpr; /* The expression to be analyzed */ - Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ - Bitmask prereqAll; /* Prerequesites of pExpr */ - Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ - Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ - int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ - int noCase = 0; /* uppercase equivalent to lowercase */ - int op; /* Top-level operator. pExpr->op */ - Parse *pParse = pWInfo->pParse; /* Parsing context */ - sqlite3 *db = pParse->db; /* Database connection */ - unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */ - int nLeft; /* Number of elements on left side vector */ - - if( db->mallocFailed ){ - return; - } - pTerm = &pWC->a[idxTerm]; - pMaskSet = &pWInfo->sMaskSet; - pExpr = pTerm->pExpr; - assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); - prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); - op = pExpr->op; - if( op==TK_IN ){ - assert( pExpr->pRight==0 ); - if( sqlite3ExprCheckIN(pParse, pExpr) ) return; - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect); - }else{ - pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); - } - }else if( op==TK_ISNULL ){ - pTerm->prereqRight = 0; - }else{ - pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight); - } - pMaskSet->bVarSelect = 0; - prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr); - if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT; - if( ExprHasProperty(pExpr, EP_FromJoin) ){ - Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable); - prereqAll |= x; - extraRight = x-1; /* ON clause terms may not be used with an index - ** on left table of a LEFT JOIN. Ticket #3015 */ - if( (prereqAll>>1)>=x ){ - sqlite3ErrorMsg(pParse, "ON clause references tables to its right"); - return; - } - } - pTerm->prereqAll = prereqAll; - pTerm->leftCursor = -1; - pTerm->iParent = -1; - pTerm->eOperator = 0; - if( allowedOp(op) ){ - int aiCurCol[2]; - Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); - Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); - u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; - - if( pTerm->iField>0 ){ - assert( op==TK_IN ); - assert( pLeft->op==TK_VECTOR ); - pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr; - } - - if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){ - pTerm->leftCursor = aiCurCol[0]; - pTerm->u.leftColumn = aiCurCol[1]; - pTerm->eOperator = operatorMask(op) & opMask; - } - if( op==TK_IS ) pTerm->wtFlags |= TERM_IS; - if( pRight - && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op) - ){ - WhereTerm *pNew; - Expr *pDup; - u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ - assert( pTerm->iField==0 ); - if( pTerm->leftCursor>=0 ){ - int idxNew; - pDup = sqlite3ExprDup(db, pExpr, 0); - if( db->mallocFailed ){ - sqlite3ExprDelete(db, pDup); - return; - } - idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); - if( idxNew==0 ) return; - pNew = &pWC->a[idxNew]; - markTermAsChild(pWC, idxNew, idxTerm); - if( op==TK_IS ) pNew->wtFlags |= TERM_IS; - pTerm = &pWC->a[idxTerm]; - pTerm->wtFlags |= TERM_COPIED; - - if( termIsEquivalence(pParse, pDup) ){ - pTerm->eOperator |= WO_EQUIV; - eExtraOp = WO_EQUIV; - } - }else{ - pDup = pExpr; - pNew = pTerm; - } - pNew->wtFlags |= exprCommute(pParse, pDup); - pNew->leftCursor = aiCurCol[0]; - pNew->u.leftColumn = aiCurCol[1]; - testcase( (prereqLeft | extraRight) != prereqLeft ); - pNew->prereqRight = prereqLeft | extraRight; - pNew->prereqAll = prereqAll; - pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; - } - } - -#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION - /* If a term is the BETWEEN operator, create two new virtual terms - ** that define the range that the BETWEEN implements. For example: - ** - ** a BETWEEN b AND c - ** - ** is converted into: - ** - ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) - ** - ** The two new terms are added onto the end of the WhereClause object. - ** The new terms are "dynamic" and are children of the original BETWEEN - ** term. That means that if the BETWEEN term is coded, the children are - ** skipped. Or, if the children are satisfied by an index, the original - ** BETWEEN term is skipped. - */ - else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ - ExprList *pList = pExpr->x.pList; - int i; - static const u8 ops[] = {TK_GE, TK_LE}; - assert( pList!=0 ); - assert( pList->nExpr==2 ); - for(i=0; i<2; i++){ - Expr *pNewExpr; - int idxNew; - pNewExpr = sqlite3PExpr(pParse, ops[i], - sqlite3ExprDup(db, pExpr->pLeft, 0), - sqlite3ExprDup(db, pList->a[i].pExpr, 0)); - transferJoinMarkings(pNewExpr, pExpr); - idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); - testcase( idxNew==0 ); - exprAnalyze(pSrc, pWC, idxNew); - pTerm = &pWC->a[idxTerm]; - markTermAsChild(pWC, idxNew, idxTerm); - } - } -#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ - -#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) - /* Analyze a term that is composed of two or more subterms connected by - ** an OR operator. - */ - else if( pExpr->op==TK_OR ){ - assert( pWC->op==TK_AND ); - exprAnalyzeOrTerm(pSrc, pWC, idxTerm); - pTerm = &pWC->a[idxTerm]; - } -#endif /* SQLITE_OMIT_OR_OPTIMIZATION */ - -#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION - /* Add constraints to reduce the search space on a LIKE or GLOB - ** operator. - ** - ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints - ** - ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%' - ** - ** The last character of the prefix "abc" is incremented to form the - ** termination condition "abd". If case is not significant (the default - ** for LIKE) then the lower-bound is made all uppercase and the upper- - ** bound is made all lowercase so that the bounds also work when comparing - ** BLOBs. - */ - if( pWC->op==TK_AND - && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) - ){ - Expr *pLeft; /* LHS of LIKE/GLOB operator */ - Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ - Expr *pNewExpr1; - Expr *pNewExpr2; - int idxNew1; - int idxNew2; - const char *zCollSeqName; /* Name of collating sequence */ - const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC; - - pLeft = pExpr->x.pList->a[1].pExpr; - pStr2 = sqlite3ExprDup(db, pStr1, 0); - - /* Convert the lower bound to upper-case and the upper bound to - ** lower-case (upper-case is less than lower-case in ASCII) so that - ** the range constraints also work for BLOBs - */ - if( noCase && !pParse->db->mallocFailed ){ - int i; - char c; - pTerm->wtFlags |= TERM_LIKE; - for(i=0; (c = pStr1->u.zToken[i])!=0; i++){ - pStr1->u.zToken[i] = sqlite3Toupper(c); - pStr2->u.zToken[i] = sqlite3Tolower(c); - } - } - - if( !db->mallocFailed ){ - u8 c, *pC; /* Last character before the first wildcard */ - pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; - c = *pC; - if( noCase ){ - /* The point is to increment the last character before the first - ** wildcard. But if we increment '@', that will push it into the - ** alphabetic range where case conversions will mess up the - ** inequality. To avoid this, make sure to also run the full - ** LIKE on all candidate expressions by clearing the isComplete flag - */ - if( c=='A'-1 ) isComplete = 0; - c = sqlite3UpperToLower[c]; - } - *pC = c + 1; - } - zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY; - pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); - pNewExpr1 = sqlite3PExpr(pParse, TK_GE, - sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), - pStr1); - transferJoinMarkings(pNewExpr1, pExpr); - idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags); - testcase( idxNew1==0 ); - exprAnalyze(pSrc, pWC, idxNew1); - pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); - pNewExpr2 = sqlite3PExpr(pParse, TK_LT, - sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), - pStr2); - transferJoinMarkings(pNewExpr2, pExpr); - idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags); - testcase( idxNew2==0 ); - exprAnalyze(pSrc, pWC, idxNew2); - pTerm = &pWC->a[idxTerm]; - if( isComplete ){ - markTermAsChild(pWC, idxNew1, idxTerm); - markTermAsChild(pWC, idxNew2, idxTerm); - } - } -#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE - /* Add a WO_AUX auxiliary term to the constraint set if the - ** current expression is of the form "column OP expr" where OP - ** is an operator that gets passed into virtual tables but which is - ** not normally optimized for ordinary tables. In other words, OP - ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL. - ** This information is used by the xBestIndex methods of - ** virtual tables. The native query optimizer does not attempt - ** to do anything with MATCH functions. - */ - if( pWC->op==TK_AND ){ - Expr *pRight = 0, *pLeft = 0; - int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight); - while( res-- > 0 ){ - int idxNew; - WhereTerm *pNewTerm; - Bitmask prereqColumn, prereqExpr; - - prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight); - prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft); - if( (prereqExpr & prereqColumn)==0 ){ - Expr *pNewExpr; - pNewExpr = sqlite3PExpr(pParse, TK_MATCH, - 0, sqlite3ExprDup(db, pRight, 0)); - if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){ - ExprSetProperty(pNewExpr, EP_FromJoin); - pNewExpr->iRightJoinTable = pExpr->iRightJoinTable; - } - idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); - testcase( idxNew==0 ); - pNewTerm = &pWC->a[idxNew]; - pNewTerm->prereqRight = prereqExpr; - pNewTerm->leftCursor = pLeft->iTable; - pNewTerm->u.leftColumn = pLeft->iColumn; - pNewTerm->eOperator = WO_AUX; - pNewTerm->eMatchOp = eOp2; - markTermAsChild(pWC, idxNew, idxTerm); - pTerm = &pWC->a[idxTerm]; - pTerm->wtFlags |= TERM_COPIED; - pNewTerm->prereqAll = pTerm->prereqAll; - } - SWAP(Expr*, pLeft, pRight); - } - } -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - - /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create - ** new terms for each component comparison - "a = ?" and "b = ?". The - ** new terms completely replace the original vector comparison, which is - ** no longer used. - ** - ** This is only required if at least one side of the comparison operation - ** is not a sub-select. */ - if( pWC->op==TK_AND - && (pExpr->op==TK_EQ || pExpr->op==TK_IS) - && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1 - && sqlite3ExprVectorSize(pExpr->pRight)==nLeft - && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 - || (pExpr->pRight->flags & EP_xIsSelect)==0) - ){ - int i; - for(i=0; ipLeft, i); - Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i); - - pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight); - transferJoinMarkings(pNew, pExpr); - idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC); - exprAnalyze(pSrc, pWC, idxNew); - } - pTerm = &pWC->a[idxTerm]; - pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */ - pTerm->eOperator = 0; - } - - /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create - ** a virtual term for each vector component. The expression object - ** used by each such virtual term is pExpr (the full vector IN(...) - ** expression). The WhereTerm.iField variable identifies the index within - ** the vector on the LHS that the virtual term represents. - ** - ** This only works if the RHS is a simple SELECT (not a compound) that does - ** not use window functions. - */ - if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0 - && pExpr->pLeft->op==TK_VECTOR - && pExpr->x.pSelect->pPrior==0 -#ifndef SQLITE_OMIT_WINDOWFUNC - && pExpr->x.pSelect->pWin==0 -#endif - ){ - int i; - for(i=0; ipLeft); i++){ - int idxNew; - idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL); - pWC->a[idxNew].iField = i+1; - exprAnalyze(pSrc, pWC, idxNew); - markTermAsChild(pWC, idxNew, idxTerm); - } - } - -#ifdef SQLITE_ENABLE_STAT4 - /* When sqlite_stat4 histogram data is available an operator of the - ** form "x IS NOT NULL" can sometimes be evaluated more efficiently - ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a - ** virtual term of that form. - ** - ** Note that the virtual term must be tagged with TERM_VNULL. - */ - if( pExpr->op==TK_NOTNULL - && pExpr->pLeft->op==TK_COLUMN - && pExpr->pLeft->iColumn>=0 - && !ExprHasProperty(pExpr, EP_FromJoin) - && OptimizationEnabled(db, SQLITE_Stat4) - ){ - Expr *pNewExpr; - Expr *pLeft = pExpr->pLeft; - int idxNew; - WhereTerm *pNewTerm; - - pNewExpr = sqlite3PExpr(pParse, TK_GT, - sqlite3ExprDup(db, pLeft, 0), - sqlite3ExprAlloc(db, TK_NULL, 0, 0)); - - idxNew = whereClauseInsert(pWC, pNewExpr, - TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); - if( idxNew ){ - pNewTerm = &pWC->a[idxNew]; - pNewTerm->prereqRight = 0; - pNewTerm->leftCursor = pLeft->iTable; - pNewTerm->u.leftColumn = pLeft->iColumn; - pNewTerm->eOperator = WO_GT; - markTermAsChild(pWC, idxNew, idxTerm); - pTerm = &pWC->a[idxTerm]; - pTerm->wtFlags |= TERM_COPIED; - pNewTerm->prereqAll = pTerm->prereqAll; - } - } -#endif /* SQLITE_ENABLE_STAT4 */ - - /* Prevent ON clause terms of a LEFT JOIN from being used to drive - ** an index for tables to the left of the join. - */ - testcase( pTerm!=&pWC->a[idxTerm] ); - pTerm = &pWC->a[idxTerm]; - pTerm->prereqRight |= extraRight; -} - -/*************************************************************************** -** Routines with file scope above. Interface to the rest of the where.c -** subsystem follows. -***************************************************************************/ - -/* -** This routine identifies subexpressions in the WHERE clause where -** each subexpression is separated by the AND operator or some other -** operator specified in the op parameter. The WhereClause structure -** is filled with pointers to subexpressions. For example: -** -** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) -** \________/ \_______________/ \________________/ -** slot[0] slot[1] slot[2] -** -** The original WHERE clause in pExpr is unaltered. All this routine -** does is make slot[] entries point to substructure within pExpr. -** -** In the previous sentence and in the diagram, "slot[]" refers to -** the WhereClause.a[] array. The slot[] array grows as needed to contain -** all terms of the WHERE clause. -*/ -SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ - Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr); - pWC->op = op; - if( pE2==0 ) return; - if( pE2->op!=op ){ - whereClauseInsert(pWC, pExpr, 0); - }else{ - sqlite3WhereSplit(pWC, pE2->pLeft, op); - sqlite3WhereSplit(pWC, pE2->pRight, op); - } -} - -/* -** Initialize a preallocated WhereClause structure. -*/ -SQLITE_PRIVATE void sqlite3WhereClauseInit( - WhereClause *pWC, /* The WhereClause to be initialized */ - WhereInfo *pWInfo /* The WHERE processing context */ -){ - pWC->pWInfo = pWInfo; - pWC->hasOr = 0; - pWC->pOuter = 0; - pWC->nTerm = 0; - pWC->nSlot = ArraySize(pWC->aStatic); - pWC->a = pWC->aStatic; -} - -/* -** Deallocate a WhereClause structure. The WhereClause structure -** itself is not freed. This routine is the inverse of -** sqlite3WhereClauseInit(). -*/ -SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){ - int i; - WhereTerm *a; - sqlite3 *db = pWC->pWInfo->pParse->db; - for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ - if( a->wtFlags & TERM_DYNAMIC ){ - sqlite3ExprDelete(db, a->pExpr); - } - if( a->wtFlags & TERM_ORINFO ){ - whereOrInfoDelete(db, a->u.pOrInfo); - }else if( a->wtFlags & TERM_ANDINFO ){ - whereAndInfoDelete(db, a->u.pAndInfo); - } - } - if( pWC->a!=pWC->aStatic ){ - sqlite3DbFree(db, pWC->a); - } -} - - -/* -** These routines walk (recursively) an expression tree and generate -** a bitmask indicating which tables are used in that expression -** tree. -*/ -SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){ - Bitmask mask; - if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){ - return sqlite3WhereGetMask(pMaskSet, p->iTable); - }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ - assert( p->op!=TK_IF_NULL_ROW ); - return 0; - } - mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0; - if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft); - if( p->pRight ){ - mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight); - assert( p->x.pList==0 ); - }else if( ExprHasProperty(p, EP_xIsSelect) ){ - if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1; - mask |= exprSelectUsage(pMaskSet, p->x.pSelect); - }else if( p->x.pList ){ - mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList); - } -#ifndef SQLITE_OMIT_WINDOWFUNC - if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){ - mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition); - mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy); - mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter); - } -#endif - return mask; -} -SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ - return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0; -} -SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ - int i; - Bitmask mask = 0; - if( pList ){ - for(i=0; inExpr; i++){ - mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); - } - } - return mask; -} - - -/* -** Call exprAnalyze on all terms in a WHERE clause. -** -** Note that exprAnalyze() might add new virtual terms onto the -** end of the WHERE clause. We do not want to analyze these new -** virtual terms, so start analyzing at the end and work forward -** so that the added virtual terms are never processed. -*/ -SQLITE_PRIVATE void sqlite3WhereExprAnalyze( - SrcList *pTabList, /* the FROM clause */ - WhereClause *pWC /* the WHERE clause to be analyzed */ -){ - int i; - for(i=pWC->nTerm-1; i>=0; i--){ - exprAnalyze(pTabList, pWC, i); - } -} - -/* -** For table-valued-functions, transform the function arguments into -** new WHERE clause terms. -** -** Each function argument translates into an equality constraint against -** a HIDDEN column in the table. -*/ -SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( - Parse *pParse, /* Parsing context */ - struct SrcList_item *pItem, /* The FROM clause term to process */ - WhereClause *pWC /* Xfer function arguments to here */ -){ - Table *pTab; - int j, k; - ExprList *pArgs; - Expr *pColRef; - Expr *pTerm; - if( pItem->fg.isTabFunc==0 ) return; - pTab = pItem->pTab; - assert( pTab!=0 ); - pArgs = pItem->u1.pFuncArg; - if( pArgs==0 ) return; - for(j=k=0; jnExpr; j++){ - Expr *pRhs; - while( knCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;} - if( k>=pTab->nCol ){ - sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", - pTab->zName, j); - return; - } - pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); - if( pColRef==0 ) return; - pColRef->iTable = pItem->iCursor; - pColRef->iColumn = k++; - pColRef->y.pTab = pTab; - pRhs = sqlite3PExpr(pParse, TK_UPLUS, - sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0); - pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs); - if( pItem->fg.jointype & JT_LEFT ){ - sqlite3SetJoinExpr(pTerm, pItem->iCursor); - } - whereClauseInsert(pWC, pTerm, TERM_DYNAMIC); - } -} - -/************** End of whereexpr.c *******************************************/ -/************** Begin file where.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 module contains C code that generates VDBE code used to process -** the WHERE clause of SQL statements. This module is responsible for -** generating the code that loops through a table looking for applicable -** rows. Indices are selected and used to speed the search when doing -** so is applicable. Because this module is responsible for selecting -** indices, you might also think of this module as the "query optimizer". -*/ -/* #include "sqliteInt.h" */ -/* #include "whereInt.h" */ - -/* -** Extra information appended to the end of sqlite3_index_info but not -** visible to the xBestIndex function, at least not directly. The -** sqlite3_vtab_collation() interface knows how to reach it, however. -** -** This object is not an API and can be changed from one release to the -** next. As long as allocateIndexInfo() and sqlite3_vtab_collation() -** agree on the structure, all will be well. -*/ -typedef struct HiddenIndexInfo HiddenIndexInfo; -struct HiddenIndexInfo { - WhereClause *pWC; /* The Where clause being analyzed */ - Parse *pParse; /* The parsing context */ -}; - -/* Forward declaration of methods */ -static int whereLoopResize(sqlite3*, WhereLoop*, int); - -/* Test variable that can be set to enable WHERE tracing */ -#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) -/***/ int sqlite3WhereTrace = 0; -#endif - - -/* -** Return the estimated number of output rows from a WHERE clause -*/ -SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ - return pWInfo->nRowOut; -} - -/* -** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this -** WHERE clause returns outputs for DISTINCT processing. -*/ -SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ - return pWInfo->eDistinct; -} - -/* -** Return the number of ORDER BY terms that are satisfied by the -** WHERE clause. A return of 0 means that the output must be -** completely sorted. A return equal to the number of ORDER BY -** terms means that no sorting is needed at all. A return that -** is positive but less than the number of ORDER BY terms means that -** block sorting is required. -*/ -SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ - return pWInfo->nOBSat; -} - -/* -** In the ORDER BY LIMIT optimization, if the inner-most loop is known -** to emit rows in increasing order, and if the last row emitted by the -** inner-most loop did not fit within the sorter, then we can skip all -** subsequent rows for the current iteration of the inner loop (because they -** will not fit in the sorter either) and continue with the second inner -** loop - the loop immediately outside the inner-most. -** -** When a row does not fit in the sorter (because the sorter already -** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the -** label returned by this function. -** -** If the ORDER BY LIMIT optimization applies, the jump destination should -** be the continuation for the second-inner-most loop. If the ORDER BY -** LIMIT optimization does not apply, then the jump destination should -** be the continuation for the inner-most loop. -** -** It is always safe for this routine to return the continuation of the -** inner-most loop, in the sense that a correct answer will result. -** Returning the continuation the second inner loop is an optimization -** that might make the code run a little faster, but should not change -** the final answer. -*/ -SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){ - WhereLevel *pInner; - if( !pWInfo->bOrderedInnerLoop ){ - /* The ORDER BY LIMIT optimization does not apply. Jump to the - ** continuation of the inner-most loop. */ - return pWInfo->iContinue; - } - pInner = &pWInfo->a[pWInfo->nLevel-1]; - assert( pInner->addrNxt!=0 ); - return pInner->addrNxt; -} - -/* -** Return the VDBE address or label to jump to in order to continue -** immediately with the next row of a WHERE clause. -*/ -SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ - assert( pWInfo->iContinue!=0 ); - return pWInfo->iContinue; -} - -/* -** Return the VDBE address or label to jump to in order to break -** out of a WHERE loop. -*/ -SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ - return pWInfo->iBreak; -} - -/* -** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to -** operate directly on the rowids returned by a WHERE clause. Return -** ONEPASS_SINGLE (1) if the statement can operation directly because only -** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass -** optimization can be used on multiple -** -** If the ONEPASS optimization is used (if this routine returns true) -** then also write the indices of open cursors used by ONEPASS -** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data -** table and iaCur[1] gets the cursor used by an auxiliary index. -** Either value may be -1, indicating that cursor is not used. -** Any cursors returned will have been opened for writing. -** -** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is -** unable to use the ONEPASS optimization. -*/ -SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ - memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); -#ifdef WHERETRACE_ENABLED - if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ - sqlite3DebugPrintf("%s cursors: %d %d\n", - pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI", - aiCur[0], aiCur[1]); - } -#endif - return pWInfo->eOnePass; -} - -/* -** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move -** the data cursor to the row selected by the index cursor. -*/ -SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){ - return pWInfo->bDeferredSeek; -} - -/* -** Move the content of pSrc into pDest -*/ -static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ - pDest->n = pSrc->n; - memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); -} - -/* -** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. -** -** The new entry might overwrite an existing entry, or it might be -** appended, or it might be discarded. Do whatever is the right thing -** so that pSet keeps the N_OR_COST best entries seen so far. -*/ -static int whereOrInsert( - WhereOrSet *pSet, /* The WhereOrSet to be updated */ - Bitmask prereq, /* Prerequisites of the new entry */ - LogEst rRun, /* Run-cost of the new entry */ - LogEst nOut /* Number of outputs for the new entry */ -){ - u16 i; - WhereOrCost *p; - for(i=pSet->n, p=pSet->a; i>0; i--, p++){ - if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ - goto whereOrInsert_done; - } - if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ - return 0; - } - } - if( pSet->na[pSet->n++]; - p->nOut = nOut; - }else{ - p = pSet->a; - for(i=1; in; i++){ - if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i; - } - if( p->rRun<=rRun ) return 0; - } -whereOrInsert_done: - p->prereq = prereq; - p->rRun = rRun; - if( p->nOut>nOut ) p->nOut = nOut; - return 1; -} - -/* -** Return the bitmask for the given cursor number. Return 0 if -** iCursor is not in the set. -*/ -SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ - int i; - assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); - for(i=0; in; i++){ - if( pMaskSet->ix[i]==iCursor ){ - return MASKBIT(i); - } - } - return 0; -} - -/* -** Create a new mask for cursor iCursor. -** -** There is one cursor per table in the FROM clause. The number of -** tables in the FROM clause is limited by a test early in the -** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] -** array will never overflow. -*/ -static void createMask(WhereMaskSet *pMaskSet, int iCursor){ - assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); - pMaskSet->ix[pMaskSet->n++] = iCursor; -} - -/* -** Advance to the next WhereTerm that matches according to the criteria -** established when the pScan object was initialized by whereScanInit(). -** Return NULL if there are no more matching WhereTerms. -*/ -static WhereTerm *whereScanNext(WhereScan *pScan){ - int iCur; /* The cursor on the LHS of the term */ - i16 iColumn; /* The column on the LHS of the term. -1 for IPK */ - Expr *pX; /* An expression being tested */ - WhereClause *pWC; /* Shorthand for pScan->pWC */ - WhereTerm *pTerm; /* The term being tested */ - int k = pScan->k; /* Where to start scanning */ - - assert( pScan->iEquiv<=pScan->nEquiv ); - pWC = pScan->pWC; - while(1){ - iColumn = pScan->aiColumn[pScan->iEquiv-1]; - iCur = pScan->aiCur[pScan->iEquiv-1]; - assert( pWC!=0 ); - do{ - for(pTerm=pWC->a+k; knTerm; k++, pTerm++){ - if( pTerm->leftCursor==iCur - && pTerm->u.leftColumn==iColumn - && (iColumn!=XN_EXPR - || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft, - pScan->pIdxExpr,iCur)==0) - && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin)) - ){ - if( (pTerm->eOperator & WO_EQUIV)!=0 - && pScan->nEquivaiCur) - && (pX = sqlite3ExprSkipCollateAndLikely(pTerm->pExpr->pRight))->op - ==TK_COLUMN - ){ - int j; - for(j=0; jnEquiv; j++){ - if( pScan->aiCur[j]==pX->iTable - && pScan->aiColumn[j]==pX->iColumn ){ - break; - } - } - if( j==pScan->nEquiv ){ - pScan->aiCur[j] = pX->iTable; - pScan->aiColumn[j] = pX->iColumn; - pScan->nEquiv++; - } - } - if( (pTerm->eOperator & pScan->opMask)!=0 ){ - /* Verify the affinity and collating sequence match */ - if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ - CollSeq *pColl; - Parse *pParse = pWC->pWInfo->pParse; - pX = pTerm->pExpr; - if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ - continue; - } - assert(pX->pLeft); - pColl = sqlite3ExprCompareCollSeq(pParse, pX); - if( pColl==0 ) pColl = pParse->db->pDfltColl; - if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ - continue; - } - } - if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0 - && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN - && pX->iTable==pScan->aiCur[0] - && pX->iColumn==pScan->aiColumn[0] - ){ - testcase( pTerm->eOperator & WO_IS ); - continue; - } - pScan->pWC = pWC; - pScan->k = k+1; - return pTerm; - } - } - } - pWC = pWC->pOuter; - k = 0; - }while( pWC!=0 ); - if( pScan->iEquiv>=pScan->nEquiv ) break; - pWC = pScan->pOrigWC; - k = 0; - pScan->iEquiv++; - } - return 0; -} - -/* -** This is whereScanInit() for the case of an index on an expression. -** It is factored out into a separate tail-recursion subroutine so that -** the normal whereScanInit() routine, which is a high-runner, does not -** need to push registers onto the stack as part of its prologue. -*/ -static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){ - pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr); - return whereScanNext(pScan); -} - -/* -** Initialize a WHERE clause scanner object. Return a pointer to the -** first match. Return NULL if there are no matches. -** -** The scanner will be searching the WHERE clause pWC. It will look -** for terms of the form "X " where X is column iColumn of table -** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx -** must be one of the indexes of table iCur. -** -** The must be one of the operators described by opMask. -** -** If the search is for X and the WHERE clause contains terms of the -** form X=Y then this routine might also return terms of the form -** "Y ". The number of levels of transitivity is limited, -** but is enough to handle most commonly occurring SQL statements. -** -** If X is not the INTEGER PRIMARY KEY then X must be compatible with -** index pIdx. -*/ -static WhereTerm *whereScanInit( - WhereScan *pScan, /* The WhereScan object being initialized */ - WhereClause *pWC, /* The WHERE clause to be scanned */ - int iCur, /* Cursor to scan for */ - int iColumn, /* Column to scan for */ - u32 opMask, /* Operator(s) to scan for */ - Index *pIdx /* Must be compatible with this index */ -){ - pScan->pOrigWC = pWC; - pScan->pWC = pWC; - pScan->pIdxExpr = 0; - pScan->idxaff = 0; - pScan->zCollName = 0; - pScan->opMask = opMask; - pScan->k = 0; - pScan->aiCur[0] = iCur; - pScan->nEquiv = 1; - pScan->iEquiv = 1; - if( pIdx ){ - int j = iColumn; - iColumn = pIdx->aiColumn[j]; - if( iColumn==XN_EXPR ){ - pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; - pScan->zCollName = pIdx->azColl[j]; - pScan->aiColumn[0] = XN_EXPR; - return whereScanInitIndexExpr(pScan); - }else if( iColumn==pIdx->pTable->iPKey ){ - iColumn = XN_ROWID; - }else if( iColumn>=0 ){ - pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; - pScan->zCollName = pIdx->azColl[j]; - } - }else if( iColumn==XN_EXPR ){ - return 0; - } - pScan->aiColumn[0] = iColumn; - return whereScanNext(pScan); -} - -/* -** Search for a term in the WHERE clause that is of the form "X " -** where X is a reference to the iColumn of table iCur or of index pIdx -** if pIdx!=0 and is one of the WO_xx operator codes specified by -** the op parameter. Return a pointer to the term. Return 0 if not found. -** -** If pIdx!=0 then it must be one of the indexes of table iCur. -** Search for terms matching the iColumn-th column of pIdx -** rather than the iColumn-th column of table iCur. -** -** The term returned might by Y= if there is another constraint in -** the WHERE clause that specifies that X=Y. Any such constraints will be -** identified by the WO_EQUIV bit in the pTerm->eOperator field. The -** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11 -** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10 -** other equivalent values. Hence a search for X will return if X=A1 -** and A1=A2 and A2=A3 and ... and A9=A10 and A10=. -** -** If there are multiple terms in the WHERE clause of the form "X " -** then try for the one with no dependencies on - in other words where -** is a constant expression of some kind. Only return entries of -** the form "X Y" where Y is a column in another table if no terms of -** the form "X " exist. If no terms with a constant RHS -** exist, try to return a term that does not use WO_EQUIV. -*/ -SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm( - WhereClause *pWC, /* The WHERE clause to be searched */ - int iCur, /* Cursor number of LHS */ - int iColumn, /* Column number of LHS */ - Bitmask notReady, /* RHS must not overlap with this mask */ - u32 op, /* Mask of WO_xx values describing operator */ - Index *pIdx /* Must be compatible with this index, if not NULL */ -){ - WhereTerm *pResult = 0; - WhereTerm *p; - WhereScan scan; - - p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); - op &= WO_EQ|WO_IS; - while( p ){ - if( (p->prereqRight & notReady)==0 ){ - if( p->prereqRight==0 && (p->eOperator&op)!=0 ){ - testcase( p->eOperator & WO_IS ); - return p; - } - if( pResult==0 ) pResult = p; - } - p = whereScanNext(&scan); - } - return pResult; -} - -/* -** This function searches pList for an entry that matches the iCol-th column -** of index pIdx. -** -** If such an expression is found, its index in pList->a[] is returned. If -** no expression is found, -1 is returned. -*/ -static int findIndexCol( - Parse *pParse, /* Parse context */ - ExprList *pList, /* Expression list to search */ - int iBase, /* Cursor for table associated with pIdx */ - Index *pIdx, /* Index to match column of */ - int iCol /* Column of index to match */ -){ - int i; - const char *zColl = pIdx->azColl[iCol]; - - for(i=0; inExpr; i++){ - Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr); - if( p->op==TK_COLUMN - && p->iColumn==pIdx->aiColumn[iCol] - && p->iTable==iBase - ){ - CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr); - if( 0==sqlite3StrICmp(pColl->zName, zColl) ){ - return i; - } - } - } - - return -1; -} - -/* -** Return TRUE if the iCol-th column of index pIdx is NOT NULL -*/ -static int indexColumnNotNull(Index *pIdx, int iCol){ - int j; - assert( pIdx!=0 ); - assert( iCol>=0 && iColnColumn ); - j = pIdx->aiColumn[iCol]; - if( j>=0 ){ - return pIdx->pTable->aCol[j].notNull; - }else if( j==(-1) ){ - return 1; - }else{ - assert( j==(-2) ); - return 0; /* Assume an indexed expression can always yield a NULL */ - - } -} - -/* -** Return true if the DISTINCT expression-list passed as the third argument -** is redundant. -** -** A DISTINCT list is redundant if any subset of the columns in the -** DISTINCT list are collectively unique and individually non-null. -*/ -static int isDistinctRedundant( - Parse *pParse, /* Parsing context */ - SrcList *pTabList, /* The FROM clause */ - WhereClause *pWC, /* The WHERE clause */ - ExprList *pDistinct /* The result set that needs to be DISTINCT */ -){ - Table *pTab; - Index *pIdx; - int i; - int iBase; - - /* If there is more than one table or sub-select in the FROM clause of - ** this query, then it will not be possible to show that the DISTINCT - ** clause is redundant. */ - if( pTabList->nSrc!=1 ) return 0; - iBase = pTabList->a[0].iCursor; - pTab = pTabList->a[0].pTab; - - /* If any of the expressions is an IPK column on table iBase, then return - ** true. Note: The (p->iTable==iBase) part of this test may be false if the - ** current SELECT is a correlated sub-query. - */ - for(i=0; inExpr; i++){ - Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr); - if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1; - } - - /* Loop through all indices on the table, checking each to see if it makes - ** the DISTINCT qualifier redundant. It does so if: - ** - ** 1. The index is itself UNIQUE, and - ** - ** 2. All of the columns in the index are either part of the pDistinct - ** list, or else the WHERE clause contains a term of the form "col=X", - ** where X is a constant value. The collation sequences of the - ** comparison and select-list expressions must match those of the index. - ** - ** 3. All of those index columns for which the WHERE clause does not - ** contain a "col=X" term are subject to a NOT NULL constraint. - */ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( !IsUniqueIndex(pIdx) ) continue; - for(i=0; inKeyCol; i++){ - if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ - if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break; - if( indexColumnNotNull(pIdx, i)==0 ) break; - } - } - if( i==pIdx->nKeyCol ){ - /* This index implies that the DISTINCT qualifier is redundant. */ - return 1; - } - } - - return 0; -} - - -/* -** Estimate the logarithm of the input value to base 2. -*/ -static LogEst estLog(LogEst N){ - return N<=10 ? 0 : sqlite3LogEst(N) - 33; -} - -/* -** Convert OP_Column opcodes to OP_Copy in previously generated code. -** -** This routine runs over generated VDBE code and translates OP_Column -** opcodes into OP_Copy when the table is being accessed via co-routine -** instead of via table lookup. -** -** If the iAutoidxCur is not zero, then any OP_Rowid instructions on -** cursor iTabCur are transformed into OP_Sequence opcode for the -** iAutoidxCur cursor, in order to generate unique rowids for the -** automatic index being generated. -*/ -static void translateColumnToCopy( - Parse *pParse, /* Parsing context */ - int iStart, /* Translate from this opcode to the end */ - int iTabCur, /* OP_Column/OP_Rowid references to this table */ - int iRegister, /* The first column is in this register */ - int iAutoidxCur /* If non-zero, cursor of autoindex being generated */ -){ - Vdbe *v = pParse->pVdbe; - VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart); - int iEnd = sqlite3VdbeCurrentAddr(v); - if( pParse->db->mallocFailed ) return; - for(; iStartp1!=iTabCur ) continue; - if( pOp->opcode==OP_Column ){ - pOp->opcode = OP_Copy; - pOp->p1 = pOp->p2 + iRegister; - pOp->p2 = pOp->p3; - pOp->p3 = 0; - }else if( pOp->opcode==OP_Rowid ){ - if( iAutoidxCur ){ - pOp->opcode = OP_Sequence; - pOp->p1 = iAutoidxCur; - }else{ - pOp->opcode = OP_Null; - pOp->p1 = 0; - pOp->p3 = 0; - } - } - } -} - -/* -** Two routines for printing the content of an sqlite3_index_info -** structure. Used for testing and debugging only. If neither -** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines -** are no-ops. -*/ -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) -static void whereTraceIndexInfoInputs(sqlite3_index_info *p){ - int i; - if( !sqlite3WhereTrace ) return; - for(i=0; inConstraint; i++){ - sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", - i, - p->aConstraint[i].iColumn, - p->aConstraint[i].iTermOffset, - p->aConstraint[i].op, - p->aConstraint[i].usable); - } - for(i=0; inOrderBy; i++){ - sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", - i, - p->aOrderBy[i].iColumn, - p->aOrderBy[i].desc); - } -} -static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){ - int i; - if( !sqlite3WhereTrace ) return; - for(i=0; inConstraint; i++){ - sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", - i, - p->aConstraintUsage[i].argvIndex, - p->aConstraintUsage[i].omit); - } - sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); - sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); - sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); - sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); - sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); -} -#else -#define whereTraceIndexInfoInputs(A) -#define whereTraceIndexInfoOutputs(A) -#endif - -#ifndef SQLITE_OMIT_AUTOMATIC_INDEX -/* -** Return TRUE if the WHERE clause term pTerm is of a form where it -** could be used with an index to access pSrc, assuming an appropriate -** index existed. -*/ -static int termCanDriveIndex( - WhereTerm *pTerm, /* WHERE clause term to check */ - struct SrcList_item *pSrc, /* Table we are trying to access */ - Bitmask notReady /* Tables in outer loops of the join */ -){ - char aff; - if( pTerm->leftCursor!=pSrc->iCursor ) return 0; - if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0; - if( (pSrc->fg.jointype & JT_LEFT) - && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - && (pTerm->eOperator & WO_IS) - ){ - /* Cannot use an IS term from the WHERE clause as an index driver for - ** the RHS of a LEFT JOIN. Such a term can only be used if it is from - ** the ON clause. */ - return 0; - } - if( (pTerm->prereqRight & notReady)!=0 ) return 0; - if( pTerm->u.leftColumn<0 ) return 0; - aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; - if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; - testcase( pTerm->pExpr->op==TK_IS ); - return 1; -} -#endif - - -#ifndef SQLITE_OMIT_AUTOMATIC_INDEX -/* -** Generate code to construct the Index object for an automatic index -** and to set up the WhereLevel object pLevel so that the code generator -** makes use of the automatic index. -*/ -static void constructAutomaticIndex( - Parse *pParse, /* The parsing context */ - WhereClause *pWC, /* The WHERE clause */ - struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ - Bitmask notReady, /* Mask of cursors that are not available */ - WhereLevel *pLevel /* Write new index here */ -){ - int nKeyCol; /* Number of columns in the constructed index */ - WhereTerm *pTerm; /* A single term of the WHERE clause */ - WhereTerm *pWCEnd; /* End of pWC->a[] */ - Index *pIdx; /* Object describing the transient index */ - Vdbe *v; /* Prepared statement under construction */ - int addrInit; /* Address of the initialization bypass jump */ - Table *pTable; /* The table being indexed */ - int addrTop; /* Top of the index fill loop */ - int regRecord; /* Register holding an index record */ - int n; /* Column counter */ - int i; /* Loop counter */ - int mxBitCol; /* Maximum column in pSrc->colUsed */ - CollSeq *pColl; /* Collating sequence to on a column */ - WhereLoop *pLoop; /* The Loop object */ - char *zNotUsed; /* Extra space on the end of pIdx */ - Bitmask idxCols; /* Bitmap of columns used for indexing */ - Bitmask extraCols; /* Bitmap of additional columns */ - u8 sentWarning = 0; /* True if a warnning has been issued */ - Expr *pPartial = 0; /* Partial Index Expression */ - int iContinue = 0; /* Jump here to skip excluded rows */ - struct SrcList_item *pTabItem; /* FROM clause term being indexed */ - int addrCounter = 0; /* Address where integer counter is initialized */ - int regBase; /* Array of registers where record is assembled */ - - /* Generate code to skip over the creation and initialization of the - ** transient index on 2nd and subsequent iterations of the loop. */ - v = pParse->pVdbe; - assert( v!=0 ); - addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - - /* Count the number of columns that will be added to the index - ** and used to match WHERE clause constraints */ - nKeyCol = 0; - pTable = pSrc->pTab; - pWCEnd = &pWC->a[pWC->nTerm]; - pLoop = pLevel->pWLoop; - idxCols = 0; - for(pTerm=pWC->a; pTermpExpr; - assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */ - || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */ - || pLoop->prereq!=0 ); /* table of a LEFT JOIN */ - if( pLoop->prereq==0 - && (pTerm->wtFlags & TERM_VIRTUAL)==0 - && !ExprHasProperty(pExpr, EP_FromJoin) - && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){ - pPartial = sqlite3ExprAnd(pParse, pPartial, - sqlite3ExprDup(pParse->db, pExpr, 0)); - } - if( termCanDriveIndex(pTerm, pSrc, notReady) ){ - int iCol = pTerm->u.leftColumn; - Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); - testcase( iCol==BMS ); - testcase( iCol==BMS-1 ); - if( !sentWarning ){ - sqlite3_log(SQLITE_WARNING_AUTOINDEX, - "automatic index on %s(%s)", pTable->zName, - pTable->aCol[iCol].zName); - sentWarning = 1; - } - if( (idxCols & cMask)==0 ){ - if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){ - goto end_auto_index_create; - } - pLoop->aLTerm[nKeyCol++] = pTerm; - idxCols |= cMask; - } - } - } - assert( nKeyCol>0 ); - pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; - pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED - | WHERE_AUTO_INDEX; - - /* Count the number of additional columns needed to create a - ** covering index. A "covering index" is an index that contains all - ** columns that are needed by the query. With a covering index, the - ** original table never needs to be accessed. Automatic indices must - ** be a covering index because the index will not be updated if the - ** original table changes and the index and table cannot both be used - ** if they go out of sync. - */ - extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); - mxBitCol = MIN(BMS-1,pTable->nCol); - testcase( pTable->nCol==BMS-1 ); - testcase( pTable->nCol==BMS-2 ); - for(i=0; icolUsed & MASKBIT(BMS-1) ){ - nKeyCol += pTable->nCol - BMS + 1; - } - - /* Construct the Index object to describe this index */ - pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); - if( pIdx==0 ) goto end_auto_index_create; - pLoop->u.btree.pIndex = pIdx; - pIdx->zName = "auto-index"; - pIdx->pTable = pTable; - n = 0; - idxCols = 0; - for(pTerm=pWC->a; pTermu.leftColumn; - Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); - testcase( iCol==BMS-1 ); - testcase( iCol==BMS ); - if( (idxCols & cMask)==0 ){ - Expr *pX = pTerm->pExpr; - idxCols |= cMask; - pIdx->aiColumn[n] = pTerm->u.leftColumn; - pColl = sqlite3ExprCompareCollSeq(pParse, pX); - assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */ - pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; - n++; - } - } - } - assert( (u32)n==pLoop->u.btree.nEq ); - - /* Add additional columns needed to make the automatic index into - ** a covering index */ - for(i=0; iaiColumn[n] = i; - pIdx->azColl[n] = sqlite3StrBINARY; - n++; - } - } - if( pSrc->colUsed & MASKBIT(BMS-1) ){ - for(i=BMS-1; inCol; i++){ - pIdx->aiColumn[n] = i; - pIdx->azColl[n] = sqlite3StrBINARY; - n++; - } - } - assert( n==nKeyCol ); - pIdx->aiColumn[n] = XN_ROWID; - pIdx->azColl[n] = sqlite3StrBINARY; - - /* Create the automatic index */ - assert( pLevel->iIdxCur>=0 ); - pLevel->iIdxCur = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); - sqlite3VdbeSetP4KeyInfo(pParse, pIdx); - VdbeComment((v, "for %s", pTable->zName)); - - /* Fill the automatic index with content */ - pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom]; - if( pTabItem->fg.viaCoroutine ){ - int regYield = pTabItem->regReturn; - addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0); - sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); - addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield); - VdbeCoverage(v); - VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); - }else{ - addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); - } - if( pPartial ){ - iContinue = sqlite3VdbeMakeLabel(pParse); - sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); - pLoop->wsFlags |= WHERE_PARTIALIDX; - } - regRecord = sqlite3GetTempReg(pParse); - regBase = sqlite3GenerateIndexKey( - pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 - ); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); - if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue); - if( pTabItem->fg.viaCoroutine ){ - sqlite3VdbeChangeP2(v, addrCounter, regBase+n); - testcase( pParse->db->mallocFailed ); - assert( pLevel->iIdxCur>0 ); - translateColumnToCopy(pParse, addrTop, pLevel->iTabCur, - pTabItem->regResult, pLevel->iIdxCur); - sqlite3VdbeGoto(v, addrTop); - pTabItem->fg.viaCoroutine = 0; - }else{ - sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); - } - sqlite3VdbeJumpHere(v, addrTop); - sqlite3ReleaseTempReg(pParse, regRecord); - - /* Jump here when skipping the initialization */ - sqlite3VdbeJumpHere(v, addrInit); - -end_auto_index_create: - sqlite3ExprDelete(pParse->db, pPartial); -} -#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Allocate and populate an sqlite3_index_info structure. It is the -** responsibility of the caller to eventually release the structure -** by passing the pointer returned by this function to sqlite3_free(). -*/ -static sqlite3_index_info *allocateIndexInfo( - Parse *pParse, /* The parsing context */ - WhereClause *pWC, /* The WHERE clause being analyzed */ - Bitmask mUnusable, /* Ignore terms with these prereqs */ - struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */ - ExprList *pOrderBy, /* The ORDER BY clause */ - u16 *pmNoOmit /* Mask of terms not to omit */ -){ - int i, j; - int nTerm; - struct sqlite3_index_constraint *pIdxCons; - struct sqlite3_index_orderby *pIdxOrderBy; - struct sqlite3_index_constraint_usage *pUsage; - struct HiddenIndexInfo *pHidden; - WhereTerm *pTerm; - int nOrderBy; - sqlite3_index_info *pIdxInfo; - u16 mNoOmit = 0; - - /* Count the number of possible WHERE clause constraints referring - ** to this virtual table */ - for(i=nTerm=0, pTerm=pWC->a; inTerm; i++, pTerm++){ - if( pTerm->leftCursor != pSrc->iCursor ) continue; - if( pTerm->prereqRight & mUnusable ) continue; - assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); - testcase( pTerm->eOperator & WO_IN ); - testcase( pTerm->eOperator & WO_ISNULL ); - testcase( pTerm->eOperator & WO_IS ); - testcase( pTerm->eOperator & WO_ALL ); - if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue; - if( pTerm->wtFlags & TERM_VNULL ) continue; - assert( pTerm->u.leftColumn>=(-1) ); - nTerm++; - } - - /* If the ORDER BY clause contains only columns in the current - ** virtual table then allocate space for the aOrderBy part of - ** the sqlite3_index_info structure. - */ - nOrderBy = 0; - if( pOrderBy ){ - int n = pOrderBy->nExpr; - for(i=0; ia[i].pExpr; - if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; - if( pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL ) break; - } - if( i==n){ - nOrderBy = n; - } - } - - /* Allocate the sqlite3_index_info structure - */ - pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) - + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm - + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) ); - if( pIdxInfo==0 ){ - sqlite3ErrorMsg(pParse, "out of memory"); - return 0; - } - pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1]; - pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1]; - pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; - pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; - pIdxInfo->nOrderBy = nOrderBy; - pIdxInfo->aConstraint = pIdxCons; - pIdxInfo->aOrderBy = pIdxOrderBy; - pIdxInfo->aConstraintUsage = pUsage; - pHidden->pWC = pWC; - pHidden->pParse = pParse; - for(i=j=0, pTerm=pWC->a; inTerm; i++, pTerm++){ - u16 op; - if( pTerm->leftCursor != pSrc->iCursor ) continue; - if( pTerm->prereqRight & mUnusable ) continue; - assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); - testcase( pTerm->eOperator & WO_IN ); - testcase( pTerm->eOperator & WO_IS ); - testcase( pTerm->eOperator & WO_ISNULL ); - testcase( pTerm->eOperator & WO_ALL ); - if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue; - if( pTerm->wtFlags & TERM_VNULL ) continue; - - /* tag-20191211-002: WHERE-clause constraints are not useful to the - ** right-hand table of a LEFT JOIN. See tag-20191211-001 for the - ** equivalent restriction for ordinary tables. */ - if( (pSrc->fg.jointype & JT_LEFT)!=0 - && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - ){ - continue; - } - assert( pTerm->u.leftColumn>=(-1) ); - pIdxCons[j].iColumn = pTerm->u.leftColumn; - pIdxCons[j].iTermOffset = i; - op = pTerm->eOperator & WO_ALL; - if( op==WO_IN ) op = WO_EQ; - if( op==WO_AUX ){ - pIdxCons[j].op = pTerm->eMatchOp; - }else if( op & (WO_ISNULL|WO_IS) ){ - if( op==WO_ISNULL ){ - pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL; - }else{ - pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS; - } - }else{ - pIdxCons[j].op = (u8)op; - /* The direct assignment in the previous line is possible only because - ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The - ** following asserts verify this fact. */ - assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); - assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); - assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); - assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); - assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); - assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) ); - - if( op & (WO_LT|WO_LE|WO_GT|WO_GE) - && sqlite3ExprIsVector(pTerm->pExpr->pRight) - ){ - testcase( j!=i ); - if( j<16 ) mNoOmit |= (1 << j); - if( op==WO_LT ) pIdxCons[j].op = WO_LE; - if( op==WO_GT ) pIdxCons[j].op = WO_GE; - } - } - - j++; - } - pIdxInfo->nConstraint = j; - for(i=0; ia[i].pExpr; - pIdxOrderBy[i].iColumn = pExpr->iColumn; - pIdxOrderBy[i].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC; - } - - *pmNoOmit = mNoOmit; - return pIdxInfo; -} - -/* -** The table object reference passed as the second argument to this function -** must represent a virtual table. This function invokes the xBestIndex() -** method of the virtual table with the sqlite3_index_info object that -** comes in as the 3rd argument to this function. -** -** If an error occurs, pParse is populated with an error message and an -** appropriate error code is returned. A return of SQLITE_CONSTRAINT from -** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that -** the current configuration of "unusable" flags in sqlite3_index_info can -** not result in a valid plan. -** -** Whether or not an error is returned, it is the responsibility of the -** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates -** that this is required. -*/ -static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ - sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; - int rc; - - whereTraceIndexInfoInputs(p); - rc = pVtab->pModule->xBestIndex(pVtab, p); - whereTraceIndexInfoOutputs(p); - - if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){ - if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(pParse->db); - }else if( !pVtab->zErrMsg ){ - sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); - }else{ - sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); - } - } - sqlite3_free(pVtab->zErrMsg); - pVtab->zErrMsg = 0; - return rc; -} -#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Estimate the location of a particular key among all keys in an -** index. Store the results in aStat as follows: -** -** aStat[0] Est. number of rows less than pRec -** aStat[1] Est. number of rows equal to pRec -** -** Return the index of the sample that is the smallest sample that -** is greater than or equal to pRec. Note that this index is not an index -** into the aSample[] array - it is an index into a virtual set of samples -** based on the contents of aSample[] and the number of fields in record -** pRec. -*/ -static int whereKeyStats( - Parse *pParse, /* Database connection */ - Index *pIdx, /* Index to consider domain of */ - UnpackedRecord *pRec, /* Vector of values to consider */ - int roundUp, /* Round up if true. Round down if false */ - tRowcnt *aStat /* OUT: stats written here */ -){ - IndexSample *aSample = pIdx->aSample; - int iCol; /* Index of required stats in anEq[] etc. */ - int i; /* Index of first sample >= pRec */ - int iSample; /* Smallest sample larger than or equal to pRec */ - int iMin = 0; /* Smallest sample not yet tested */ - int iTest; /* Next sample to test */ - int res; /* Result of comparison operation */ - int nField; /* Number of fields in pRec */ - tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */ - -#ifndef SQLITE_DEBUG - UNUSED_PARAMETER( pParse ); -#endif - assert( pRec!=0 ); - assert( pIdx->nSample>0 ); - assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol ); - - /* Do a binary search to find the first sample greater than or equal - ** to pRec. If pRec contains a single field, the set of samples to search - ** is simply the aSample[] array. If the samples in aSample[] contain more - ** than one fields, all fields following the first are ignored. - ** - ** If pRec contains N fields, where N is more than one, then as well as the - ** samples in aSample[] (truncated to N fields), the search also has to - ** consider prefixes of those samples. For example, if the set of samples - ** in aSample is: - ** - ** aSample[0] = (a, 5) - ** aSample[1] = (a, 10) - ** aSample[2] = (b, 5) - ** aSample[3] = (c, 100) - ** aSample[4] = (c, 105) - ** - ** Then the search space should ideally be the samples above and the - ** unique prefixes [a], [b] and [c]. But since that is hard to organize, - ** the code actually searches this set: - ** - ** 0: (a) - ** 1: (a, 5) - ** 2: (a, 10) - ** 3: (a, 10) - ** 4: (b) - ** 5: (b, 5) - ** 6: (c) - ** 7: (c, 100) - ** 8: (c, 105) - ** 9: (c, 105) - ** - ** For each sample in the aSample[] array, N samples are present in the - ** effective sample array. In the above, samples 0 and 1 are based on - ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc. - ** - ** Often, sample i of each block of N effective samples has (i+1) fields. - ** Except, each sample may be extended to ensure that it is greater than or - ** equal to the previous sample in the array. For example, in the above, - ** sample 2 is the first sample of a block of N samples, so at first it - ** appears that it should be 1 field in size. However, that would make it - ** smaller than sample 1, so the binary search would not work. As a result, - ** it is extended to two fields. The duplicates that this creates do not - ** cause any problems. - */ - nField = pRec->nField; - iCol = 0; - iSample = pIdx->nSample * nField; - do{ - int iSamp; /* Index in aSample[] of test sample */ - int n; /* Number of fields in test sample */ - - iTest = (iMin+iSample)/2; - iSamp = iTest / nField; - if( iSamp>0 ){ - /* The proposed effective sample is a prefix of sample aSample[iSamp]. - ** Specifically, the shortest prefix of at least (1 + iTest%nField) - ** fields that is greater than the previous effective sample. */ - for(n=(iTest % nField) + 1; nnField = n; - res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); - if( res<0 ){ - iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1]; - iMin = iTest+1; - }else if( res==0 && ndb->mallocFailed==0 ){ - if( res==0 ){ - /* If (res==0) is true, then pRec must be equal to sample i. */ - assert( inSample ); - assert( iCol==nField-1 ); - pRec->nField = nField; - assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) - || pParse->db->mallocFailed - ); - }else{ - /* Unless i==pIdx->nSample, indicating that pRec is larger than - ** all samples in the aSample[] array, pRec must be smaller than the - ** (iCol+1) field prefix of sample i. */ - assert( i<=pIdx->nSample && i>=0 ); - pRec->nField = iCol+1; - assert( i==pIdx->nSample - || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 - || pParse->db->mallocFailed ); - - /* if i==0 and iCol==0, then record pRec is smaller than all samples - ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must - ** be greater than or equal to the (iCol) field prefix of sample i. - ** If (i>0), then pRec must also be greater than sample (i-1). */ - if( iCol>0 ){ - pRec->nField = iCol; - assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 - || pParse->db->mallocFailed ); - } - if( i>0 ){ - pRec->nField = nField; - assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 - || pParse->db->mallocFailed ); - } - } - } -#endif /* ifdef SQLITE_DEBUG */ - - if( res==0 ){ - /* Record pRec is equal to sample i */ - assert( iCol==nField-1 ); - aStat[0] = aSample[i].anLt[iCol]; - aStat[1] = aSample[i].anEq[iCol]; - }else{ - /* At this point, the (iCol+1) field prefix of aSample[i] is the first - ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec - ** is larger than all samples in the array. */ - tRowcnt iUpper, iGap; - if( i>=pIdx->nSample ){ - iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]); - }else{ - iUpper = aSample[i].anLt[iCol]; - } - - if( iLower>=iUpper ){ - iGap = 0; - }else{ - iGap = iUpper - iLower; - } - if( roundUp ){ - iGap = (iGap*2)/3; - }else{ - iGap = iGap/3; - } - aStat[0] = iLower + iGap; - aStat[1] = pIdx->aAvgEq[nField-1]; - } - - /* Restore the pRec->nField value before returning. */ - pRec->nField = nField; - return i; -} -#endif /* SQLITE_ENABLE_STAT4 */ - -/* -** If it is not NULL, pTerm is a term that provides an upper or lower -** bound on a range scan. Without considering pTerm, it is estimated -** that the scan will visit nNew rows. This function returns the number -** estimated to be visited after taking pTerm into account. -** -** If the user explicitly specified a likelihood() value for this term, -** then the return value is the likelihood multiplied by the number of -** input rows. Otherwise, this function assumes that an "IS NOT NULL" term -** has a likelihood of 0.50, and any other term a likelihood of 0.25. -*/ -static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ - LogEst nRet = nNew; - if( pTerm ){ - if( pTerm->truthProb<=0 ){ - nRet += pTerm->truthProb; - }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ - nRet -= 20; assert( 20==sqlite3LogEst(4) ); - } - } - return nRet; -} - - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Return the affinity for a single column of an index. -*/ -SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){ - assert( iCol>=0 && iColnColumn ); - if( !pIdx->zColAff ){ - if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; - } - assert( pIdx->zColAff[iCol]!=0 ); - return pIdx->zColAff[iCol]; -} -#endif - - -#ifdef SQLITE_ENABLE_STAT4 -/* -** This function is called to estimate the number of rows visited by a -** range-scan on a skip-scan index. For example: -** -** CREATE INDEX i1 ON t1(a, b, c); -** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; -** -** Value pLoop->nOut is currently set to the estimated number of rows -** visited for scanning (a=? AND b=?). This function reduces that estimate -** by some factor to account for the (c BETWEEN ? AND ?) expression based -** on the stat4 data for the index. this scan will be peformed multiple -** times (once for each (a,b) combination that matches a=?) is dealt with -** by the caller. -** -** It does this by scanning through all stat4 samples, comparing values -** extracted from pLower and pUpper with the corresponding column in each -** sample. If L and U are the number of samples found to be less than or -** equal to the values extracted from pLower and pUpper respectively, and -** N is the total number of samples, the pLoop->nOut value is adjusted -** as follows: -** -** nOut = nOut * ( min(U - L, 1) / N ) -** -** If pLower is NULL, or a value cannot be extracted from the term, L is -** set to zero. If pUpper is NULL, or a value cannot be extracted from it, -** U is set to N. -** -** Normally, this function sets *pbDone to 1 before returning. However, -** if no value can be extracted from either pLower or pUpper (and so the -** estimate of the number of rows delivered remains unchanged), *pbDone -** is left as is. -** -** If an error occurs, an SQLite error code is returned. Otherwise, -** SQLITE_OK. -*/ -static int whereRangeSkipScanEst( - Parse *pParse, /* Parsing & code generating context */ - WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ - WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ - WhereLoop *pLoop, /* Update the .nOut value of this loop */ - int *pbDone /* Set to true if at least one expr. value extracted */ -){ - Index *p = pLoop->u.btree.pIndex; - int nEq = pLoop->u.btree.nEq; - sqlite3 *db = pParse->db; - int nLower = -1; - int nUpper = p->nSample+1; - int rc = SQLITE_OK; - u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); - CollSeq *pColl; - - sqlite3_value *p1 = 0; /* Value extracted from pLower */ - sqlite3_value *p2 = 0; /* Value extracted from pUpper */ - sqlite3_value *pVal = 0; /* Value extracted from record */ - - pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); - if( pLower ){ - rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); - nLower = 0; - } - if( pUpper && rc==SQLITE_OK ){ - rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); - nUpper = p2 ? 0 : p->nSample; - } - - if( p1 || p2 ){ - int i; - int nDiff; - for(i=0; rc==SQLITE_OK && inSample; i++){ - rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); - if( rc==SQLITE_OK && p1 ){ - int res = sqlite3MemCompare(p1, pVal, pColl); - if( res>=0 ) nLower++; - } - if( rc==SQLITE_OK && p2 ){ - int res = sqlite3MemCompare(p2, pVal, pColl); - if( res>=0 ) nUpper++; - } - } - nDiff = (nUpper - nLower); - if( nDiff<=0 ) nDiff = 1; - - /* If there is both an upper and lower bound specified, and the - ** comparisons indicate that they are close together, use the fallback - ** method (assume that the scan visits 1/64 of the rows) for estimating - ** the number of rows visited. Otherwise, estimate the number of rows - ** using the method described in the header comment for this function. */ - if( nDiff!=1 || pUpper==0 || pLower==0 ){ - int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); - pLoop->nOut -= nAdjust; - *pbDone = 1; - WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", - nLower, nUpper, nAdjust*-1, pLoop->nOut)); - } - - }else{ - assert( *pbDone==0 ); - } - - sqlite3ValueFree(p1); - sqlite3ValueFree(p2); - sqlite3ValueFree(pVal); - - return rc; -} -#endif /* SQLITE_ENABLE_STAT4 */ - -/* -** This function is used to estimate the number of rows that will be visited -** by scanning an index for a range of values. The range may have an upper -** bound, a lower bound, or both. The WHERE clause terms that set the upper -** and lower bounds are represented by pLower and pUpper respectively. For -** example, assuming that index p is on t1(a): -** -** ... FROM t1 WHERE a > ? AND a < ? ... -** |_____| |_____| -** | | -** pLower pUpper -** -** If either of the upper or lower bound is not present, then NULL is passed in -** place of the corresponding WhereTerm. -** -** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index -** column subject to the range constraint. Or, equivalently, the number of -** equality constraints optimized by the proposed index scan. For example, -** assuming index p is on t1(a, b), and the SQL query is: -** -** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... -** -** then nEq is set to 1 (as the range restricted column, b, is the second -** left-most column of the index). Or, if the query is: -** -** ... FROM t1 WHERE a > ? AND a < ? ... -** -** then nEq is set to 0. -** -** When this function is called, *pnOut is set to the sqlite3LogEst() of the -** number of rows that the index scan is expected to visit without -** considering the range constraints. If nEq is 0, then *pnOut is the number of -** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) -** to account for the range constraints pLower and pUpper. -** -** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be -** used, a single range inequality reduces the search space by a factor of 4. -** and a pair of constraints (x>? AND x123" Might be NULL */ - WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ - WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ -){ - int rc = SQLITE_OK; - int nOut = pLoop->nOut; - LogEst nNew; - -#ifdef SQLITE_ENABLE_STAT4 - Index *p = pLoop->u.btree.pIndex; - int nEq = pLoop->u.btree.nEq; - - if( p->nSample>0 && ALWAYS(nEqnSampleCol) - && OptimizationEnabled(pParse->db, SQLITE_Stat4) - ){ - if( nEq==pBuilder->nRecValid ){ - UnpackedRecord *pRec = pBuilder->pRec; - tRowcnt a[2]; - int nBtm = pLoop->u.btree.nBtm; - int nTop = pLoop->u.btree.nTop; - - /* Variable iLower will be set to the estimate of the number of rows in - ** the index that are less than the lower bound of the range query. The - ** lower bound being the concatenation of $P and $L, where $P is the - ** key-prefix formed by the nEq values matched against the nEq left-most - ** columns of the index, and $L is the value in pLower. - ** - ** Or, if pLower is NULL or $L cannot be extracted from it (because it - ** is not a simple variable or literal value), the lower bound of the - ** range is $P. Due to a quirk in the way whereKeyStats() works, even - ** if $L is available, whereKeyStats() is called for both ($P) and - ** ($P:$L) and the larger of the two returned values is used. - ** - ** Similarly, iUpper is to be set to the estimate of the number of rows - ** less than the upper bound of the range query. Where the upper bound - ** is either ($P) or ($P:$U). Again, even if $U is available, both values - ** of iUpper are requested of whereKeyStats() and the smaller used. - ** - ** The number of rows between the two bounds is then just iUpper-iLower. - */ - tRowcnt iLower; /* Rows less than the lower bound */ - tRowcnt iUpper; /* Rows less than the upper bound */ - int iLwrIdx = -2; /* aSample[] for the lower bound */ - int iUprIdx = -1; /* aSample[] for the upper bound */ - - if( pRec ){ - testcase( pRec->nField!=pBuilder->nRecValid ); - pRec->nField = pBuilder->nRecValid; - } - /* Determine iLower and iUpper using ($P) only. */ - if( nEq==0 ){ - iLower = 0; - iUpper = p->nRowEst0; - }else{ - /* Note: this call could be optimized away - since the same values must - ** have been requested when testing key $P in whereEqualScanEst(). */ - whereKeyStats(pParse, p, pRec, 0, a); - iLower = a[0]; - iUpper = a[0] + a[1]; - } - - assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); - assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); - assert( p->aSortOrder!=0 ); - if( p->aSortOrder[nEq] ){ - /* The roles of pLower and pUpper are swapped for a DESC index */ - SWAP(WhereTerm*, pLower, pUpper); - SWAP(int, nBtm, nTop); - } - - /* If possible, improve on the iLower estimate using ($P:$L). */ - if( pLower ){ - int n; /* Values extracted from pExpr */ - Expr *pExpr = pLower->pExpr->pRight; - rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); - if( rc==SQLITE_OK && n ){ - tRowcnt iNew; - u16 mask = WO_GT|WO_LE; - if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); - iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); - iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0); - if( iNew>iLower ) iLower = iNew; - nOut--; - pLower = 0; - } - } - - /* If possible, improve on the iUpper estimate using ($P:$U). */ - if( pUpper ){ - int n; /* Values extracted from pExpr */ - Expr *pExpr = pUpper->pExpr->pRight; - rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); - if( rc==SQLITE_OK && n ){ - tRowcnt iNew; - u16 mask = WO_GT|WO_LE; - if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); - iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); - iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0); - if( iNewpRec = pRec; - if( rc==SQLITE_OK ){ - if( iUpper>iLower ){ - nNew = sqlite3LogEst(iUpper - iLower); - /* TUNING: If both iUpper and iLower are derived from the same - ** sample, then assume they are 4x more selective. This brings - ** the estimated selectivity more in line with what it would be - ** if estimated without the use of STAT4 tables. */ - if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) ); - }else{ - nNew = 10; assert( 10==sqlite3LogEst(2) ); - } - if( nNewwtFlags & TERM_VNULL)==0 ); - nNew = whereRangeAdjust(pLower, nOut); - nNew = whereRangeAdjust(pUpper, nNew); - - /* TUNING: If there is both an upper and lower limit and neither limit - ** has an application-defined likelihood(), assume the range is - ** reduced by an additional 75%. This means that, by default, an open-ended - ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the - ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to - ** match 1/64 of the index. */ - if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){ - nNew -= 20; - } - - nOut -= (pLower!=0) + (pUpper!=0); - if( nNew<10 ) nNew = 10; - if( nNewnOut>nOut ){ - WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n", - pLoop->nOut, nOut)); - } -#endif - pLoop->nOut = (LogEst)nOut; - return rc; -} - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Estimate the number of rows that will be returned based on -** an equality constraint x=VALUE and where that VALUE occurs in -** the histogram data. This only works when x is the left-most -** column of an index and sqlite_stat4 histogram data is available -** for that index. When pExpr==NULL that means the constraint is -** "x IS NULL" instead of "x=VALUE". -** -** Write the estimated row count into *pnRow and return SQLITE_OK. -** If unable to make an estimate, leave *pnRow unchanged and return -** non-zero. -** -** This routine can fail if it is unable to load a collating sequence -** required for string comparison, or if unable to allocate memory -** for a UTF conversion required for comparison. The error is stored -** in the pParse structure. -*/ -static int whereEqualScanEst( - Parse *pParse, /* Parsing & code generating context */ - WhereLoopBuilder *pBuilder, - Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ - tRowcnt *pnRow /* Write the revised row estimate here */ -){ - Index *p = pBuilder->pNew->u.btree.pIndex; - int nEq = pBuilder->pNew->u.btree.nEq; - UnpackedRecord *pRec = pBuilder->pRec; - int rc; /* Subfunction return code */ - tRowcnt a[2]; /* Statistics */ - int bOk; - - assert( nEq>=1 ); - assert( nEq<=p->nColumn ); - assert( p->aSample!=0 ); - assert( p->nSample>0 ); - assert( pBuilder->nRecValidnRecValid<(nEq-1) ){ - return SQLITE_NOTFOUND; - } - - /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() - ** below would return the same value. */ - if( nEq>=p->nColumn ){ - *pnRow = 1; - return SQLITE_OK; - } - - rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk); - pBuilder->pRec = pRec; - if( rc!=SQLITE_OK ) return rc; - if( bOk==0 ) return SQLITE_NOTFOUND; - pBuilder->nRecValid = nEq; - - whereKeyStats(pParse, p, pRec, 0, a); - WHERETRACE(0x10,("equality scan regions %s(%d): %d\n", - p->zName, nEq-1, (int)a[1])); - *pnRow = a[1]; - - return rc; -} -#endif /* SQLITE_ENABLE_STAT4 */ - -#ifdef SQLITE_ENABLE_STAT4 -/* -** Estimate the number of rows that will be returned based on -** an IN constraint where the right-hand side of the IN operator -** is a list of values. Example: -** -** WHERE x IN (1,2,3,4) -** -** Write the estimated row count into *pnRow and return SQLITE_OK. -** If unable to make an estimate, leave *pnRow unchanged and return -** non-zero. -** -** This routine can fail if it is unable to load a collating sequence -** required for string comparison, or if unable to allocate memory -** for a UTF conversion required for comparison. The error is stored -** in the pParse structure. -*/ -static int whereInScanEst( - Parse *pParse, /* Parsing & code generating context */ - WhereLoopBuilder *pBuilder, - ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ - tRowcnt *pnRow /* Write the revised row estimate here */ -){ - Index *p = pBuilder->pNew->u.btree.pIndex; - i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]); - int nRecValid = pBuilder->nRecValid; - int rc = SQLITE_OK; /* Subfunction return code */ - tRowcnt nEst; /* Number of rows for a single term */ - tRowcnt nRowEst = 0; /* New estimate of the number of rows */ - int i; /* Loop counter */ - - assert( p->aSample!=0 ); - for(i=0; rc==SQLITE_OK && inExpr; i++){ - nEst = nRow0; - rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); - nRowEst += nEst; - pBuilder->nRecValid = nRecValid; - } - - if( rc==SQLITE_OK ){ - if( nRowEst > nRow0 ) nRowEst = nRow0; - *pnRow = nRowEst; - WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst)); - } - assert( pBuilder->nRecValid==nRecValid ); - return rc; -} -#endif /* SQLITE_ENABLE_STAT4 */ - - -#ifdef WHERETRACE_ENABLED -/* -** Print the content of a WhereTerm object -*/ -SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){ - if( pTerm==0 ){ - sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); - }else{ - char zType[8]; - char zLeft[50]; - memcpy(zType, "....", 5); - if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; - if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; - if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; - if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C'; - if( pTerm->eOperator & WO_SINGLE ){ - sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", - pTerm->leftCursor, pTerm->u.leftColumn); - }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){ - sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", - pTerm->u.pOrInfo->indexable); - }else{ - sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); - } - sqlite3DebugPrintf( - "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x", - iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags); - /* The 0x10000 .wheretrace flag causes extra information to be - ** shown about each Term */ - if( sqlite3WhereTrace & 0x10000 ){ - sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx", - pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight); - } - if( pTerm->iField ){ - sqlite3DebugPrintf(" iField=%d", pTerm->iField); - } - if( pTerm->iParent>=0 ){ - sqlite3DebugPrintf(" iParent=%d", pTerm->iParent); - } - sqlite3DebugPrintf("\n"); - sqlite3TreeViewExpr(0, pTerm->pExpr, 0); - } -} -#endif - -#ifdef WHERETRACE_ENABLED -/* -** Show the complete content of a WhereClause -*/ -SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){ - int i; - for(i=0; inTerm; i++){ - sqlite3WhereTermPrint(&pWC->a[i], i); - } -} -#endif - -#ifdef WHERETRACE_ENABLED -/* -** Print a WhereLoop object for debugging purposes -*/ -SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){ - WhereInfo *pWInfo = pWC->pWInfo; - int nb = 1+(pWInfo->pTabList->nSrc+3)/4; - struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab; - Table *pTab = pItem->pTab; - Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1; - sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, - p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); - sqlite3DebugPrintf(" %12s", - pItem->zAlias ? pItem->zAlias : pTab->zName); - if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ - const char *zName; - if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ - if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ - int i = sqlite3Strlen30(zName) - 1; - while( zName[i]!='_' ) i--; - zName += i; - } - sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); - }else{ - sqlite3DebugPrintf("%20s",""); - } - }else{ - char *z; - if( p->u.vtab.idxStr ){ - z = sqlite3_mprintf("(%d,\"%s\",%#x)", - p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); - }else{ - z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); - } - sqlite3DebugPrintf(" %-19s", z); - sqlite3_free(z); - } - if( p->wsFlags & WHERE_SKIPSCAN ){ - sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); - }else{ - sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); - } - sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); - if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ - int i; - for(i=0; inLTerm; i++){ - sqlite3WhereTermPrint(p->aLTerm[i], i); - } - } -} -#endif - -/* -** Convert bulk memory into a valid WhereLoop that can be passed -** to whereLoopClear harmlessly. -*/ -static void whereLoopInit(WhereLoop *p){ - p->aLTerm = p->aLTermSpace; - p->nLTerm = 0; - p->nLSlot = ArraySize(p->aLTermSpace); - p->wsFlags = 0; -} - -/* -** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. -*/ -static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ - if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ - if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ - sqlite3_free(p->u.vtab.idxStr); - p->u.vtab.needFree = 0; - p->u.vtab.idxStr = 0; - }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ - sqlite3DbFree(db, p->u.btree.pIndex->zColAff); - sqlite3DbFreeNN(db, p->u.btree.pIndex); - p->u.btree.pIndex = 0; - } - } -} - -/* -** Deallocate internal memory used by a WhereLoop object -*/ -static void whereLoopClear(sqlite3 *db, WhereLoop *p){ - if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm); - whereLoopClearUnion(db, p); - whereLoopInit(p); -} - -/* -** Increase the memory allocation for pLoop->aLTerm[] to be at least n. -*/ -static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ - WhereTerm **paNew; - if( p->nLSlot>=n ) return SQLITE_OK; - n = (n+7)&~7; - paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); - if( paNew==0 ) return SQLITE_NOMEM_BKPT; - memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); - if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm); - p->aLTerm = paNew; - p->nLSlot = n; - return SQLITE_OK; -} - -/* -** Transfer content from the second pLoop into the first. -*/ -static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ - whereLoopClearUnion(db, pTo); - if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ - memset(&pTo->u, 0, sizeof(pTo->u)); - return SQLITE_NOMEM_BKPT; - } - memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); - memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); - if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ - pFrom->u.vtab.needFree = 0; - }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ - pFrom->u.btree.pIndex = 0; - } - return SQLITE_OK; -} - -/* -** Delete a WhereLoop object -*/ -static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ - whereLoopClear(db, p); - sqlite3DbFreeNN(db, p); -} - -/* -** Free a WhereInfo structure -*/ -static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ - int i; - assert( pWInfo!=0 ); - for(i=0; inLevel; i++){ - WhereLevel *pLevel = &pWInfo->a[i]; - if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){ - sqlite3DbFree(db, pLevel->u.in.aInLoop); - } - } - sqlite3WhereClauseClear(&pWInfo->sWC); - while( pWInfo->pLoops ){ - WhereLoop *p = pWInfo->pLoops; - pWInfo->pLoops = p->pNextLoop; - whereLoopDelete(db, p); - } - assert( pWInfo->pExprMods==0 ); - sqlite3DbFreeNN(db, pWInfo); -} - -/* -** Return TRUE if all of the following are true: -** -** (1) X has the same or lower cost that Y -** (2) X uses fewer WHERE clause terms than Y -** (3) Every WHERE clause term used by X is also used by Y -** (4) X skips at least as many columns as Y -** (5) If X is a covering index, than Y is too -** -** Conditions (2) and (3) mean that X is a "proper subset" of Y. -** If X is a proper subset of Y then Y is a better choice and ought -** to have a lower cost. This routine returns TRUE when that cost -** relationship is inverted and needs to be adjusted. Constraint (4) -** was added because if X uses skip-scan less than Y it still might -** deserve a lower cost even if it is a proper subset of Y. Constraint (5) -** was added because a covering index probably deserves to have a lower cost -** than a non-covering index even if it is a proper subset. -*/ -static int whereLoopCheaperProperSubset( - const WhereLoop *pX, /* First WhereLoop to compare */ - const WhereLoop *pY /* Compare against this WhereLoop */ -){ - int i, j; - if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){ - return 0; /* X is not a subset of Y */ - } - if( pY->nSkip > pX->nSkip ) return 0; - if( pX->rRun >= pY->rRun ){ - if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */ - if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */ - } - for(i=pX->nLTerm-1; i>=0; i--){ - if( pX->aLTerm[i]==0 ) continue; - for(j=pY->nLTerm-1; j>=0; j--){ - if( pY->aLTerm[j]==pX->aLTerm[i] ) break; - } - if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ - } - if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 - && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){ - return 0; /* Constraint (5) */ - } - return 1; /* All conditions meet */ -} - -/* -** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so -** that: -** -** (1) pTemplate costs less than any other WhereLoops that are a proper -** subset of pTemplate -** -** (2) pTemplate costs more than any other WhereLoops for which pTemplate -** is a proper subset. -** -** To say "WhereLoop X is a proper subset of Y" means that X uses fewer -** WHERE clause terms than Y and that every WHERE clause term used by X is -** also used by Y. -*/ -static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ - if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; - for(; p; p=p->pNextLoop){ - if( p->iTab!=pTemplate->iTab ) continue; - if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; - if( whereLoopCheaperProperSubset(p, pTemplate) ){ - /* Adjust pTemplate cost downward so that it is cheaper than its - ** subset p. */ - WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", - pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1)); - pTemplate->rRun = p->rRun; - pTemplate->nOut = p->nOut - 1; - }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ - /* Adjust pTemplate cost upward so that it is costlier than p since - ** pTemplate is a proper subset of p */ - WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", - pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1)); - pTemplate->rRun = p->rRun; - pTemplate->nOut = p->nOut + 1; - } - } -} - -/* -** Search the list of WhereLoops in *ppPrev looking for one that can be -** replaced by pTemplate. -** -** Return NULL if pTemplate does not belong on the WhereLoop list. -** In other words if pTemplate ought to be dropped from further consideration. -** -** If pX is a WhereLoop that pTemplate can replace, then return the -** link that points to pX. -** -** If pTemplate cannot replace any existing element of the list but needs -** to be added to the list as a new entry, then return a pointer to the -** tail of the list. -*/ -static WhereLoop **whereLoopFindLesser( - WhereLoop **ppPrev, - const WhereLoop *pTemplate -){ - WhereLoop *p; - for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){ - if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ - /* If either the iTab or iSortIdx values for two WhereLoop are different - ** then those WhereLoops need to be considered separately. Neither is - ** a candidate to replace the other. */ - continue; - } - /* In the current implementation, the rSetup value is either zero - ** or the cost of building an automatic index (NlogN) and the NlogN - ** is the same for compatible WhereLoops. */ - assert( p->rSetup==0 || pTemplate->rSetup==0 - || p->rSetup==pTemplate->rSetup ); - - /* whereLoopAddBtree() always generates and inserts the automatic index - ** case first. Hence compatible candidate WhereLoops never have a larger - ** rSetup. Call this SETUP-INVARIANT */ - assert( p->rSetup>=pTemplate->rSetup ); - - /* Any loop using an appliation-defined index (or PRIMARY KEY or - ** UNIQUE constraint) with one or more == constraints is better - ** than an automatic index. Unless it is a skip-scan. */ - if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 - && (pTemplate->nSkip)==0 - && (pTemplate->wsFlags & WHERE_INDEXED)!=0 - && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 - && (p->prereq & pTemplate->prereq)==pTemplate->prereq - ){ - break; - } - - /* If existing WhereLoop p is better than pTemplate, pTemplate can be - ** discarded. WhereLoop p is better if: - ** (1) p has no more dependencies than pTemplate, and - ** (2) p has an equal or lower cost than pTemplate - */ - if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */ - && p->rSetup<=pTemplate->rSetup /* (2a) */ - && p->rRun<=pTemplate->rRun /* (2b) */ - && p->nOut<=pTemplate->nOut /* (2c) */ - ){ - return 0; /* Discard pTemplate */ - } - - /* If pTemplate is always better than p, then cause p to be overwritten - ** with pTemplate. pTemplate is better than p if: - ** (1) pTemplate has no more dependences than p, and - ** (2) pTemplate has an equal or lower cost than p. - */ - if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */ - && p->rRun>=pTemplate->rRun /* (2a) */ - && p->nOut>=pTemplate->nOut /* (2b) */ - ){ - assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ - break; /* Cause p to be overwritten by pTemplate */ - } - } - return ppPrev; -} - -/* -** Insert or replace a WhereLoop entry using the template supplied. -** -** An existing WhereLoop entry might be overwritten if the new template -** is better and has fewer dependencies. Or the template will be ignored -** and no insert will occur if an existing WhereLoop is faster and has -** fewer dependencies than the template. Otherwise a new WhereLoop is -** added based on the template. -** -** If pBuilder->pOrSet is not NULL then we care about only the -** prerequisites and rRun and nOut costs of the N best loops. That -** information is gathered in the pBuilder->pOrSet object. This special -** processing mode is used only for OR clause processing. -** -** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we -** still might overwrite similar loops with the new template if the -** new template is better. Loops may be overwritten if the following -** conditions are met: -** -** (1) They have the same iTab. -** (2) They have the same iSortIdx. -** (3) The template has same or fewer dependencies than the current loop -** (4) The template has the same or lower cost than the current loop -*/ -static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ - WhereLoop **ppPrev, *p; - WhereInfo *pWInfo = pBuilder->pWInfo; - sqlite3 *db = pWInfo->pParse->db; - int rc; - - /* Stop the search once we hit the query planner search limit */ - if( pBuilder->iPlanLimit==0 ){ - WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n")); - if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0; - return SQLITE_DONE; - } - pBuilder->iPlanLimit--; - - whereLoopAdjustCost(pWInfo->pLoops, pTemplate); - - /* If pBuilder->pOrSet is defined, then only keep track of the costs - ** and prereqs. - */ - if( pBuilder->pOrSet!=0 ){ - if( pTemplate->nLTerm ){ -#if WHERETRACE_ENABLED - u16 n = pBuilder->pOrSet->n; - int x = -#endif - whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, - pTemplate->nOut); -#if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ - sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); - sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); - } -#endif - } - return SQLITE_OK; - } - - /* Look for an existing WhereLoop to replace with pTemplate - */ - ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); - - if( ppPrev==0 ){ - /* There already exists a WhereLoop on the list that is better - ** than pTemplate, so just ignore pTemplate */ -#if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ - sqlite3DebugPrintf(" skip: "); - sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); - } -#endif - return SQLITE_OK; - }else{ - p = *ppPrev; - } - - /* If we reach this point it means that either p[] should be overwritten - ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new - ** WhereLoop and insert it. - */ -#if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ - if( p!=0 ){ - sqlite3DebugPrintf("replace: "); - sqlite3WhereLoopPrint(p, pBuilder->pWC); - sqlite3DebugPrintf(" with: "); - }else{ - sqlite3DebugPrintf(" add: "); - } - sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); - } -#endif - if( p==0 ){ - /* Allocate a new WhereLoop to add to the end of the list */ - *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop)); - if( p==0 ) return SQLITE_NOMEM_BKPT; - whereLoopInit(p); - p->pNextLoop = 0; - }else{ - /* We will be overwriting WhereLoop p[]. But before we do, first - ** go through the rest of the list and delete any other entries besides - ** p[] that are also supplated by pTemplate */ - WhereLoop **ppTail = &p->pNextLoop; - WhereLoop *pToDel; - while( *ppTail ){ - ppTail = whereLoopFindLesser(ppTail, pTemplate); - if( ppTail==0 ) break; - pToDel = *ppTail; - if( pToDel==0 ) break; - *ppTail = pToDel->pNextLoop; -#if WHERETRACE_ENABLED /* 0x8 */ - if( sqlite3WhereTrace & 0x8 ){ - sqlite3DebugPrintf(" delete: "); - sqlite3WhereLoopPrint(pToDel, pBuilder->pWC); - } -#endif - whereLoopDelete(db, pToDel); - } - } - rc = whereLoopXfer(db, p, pTemplate); - if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ - Index *pIndex = p->u.btree.pIndex; - if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){ - p->u.btree.pIndex = 0; - } - } - return rc; -} - -/* -** Adjust the WhereLoop.nOut value downward to account for terms of the -** WHERE clause that reference the loop but which are not used by an -** index. -* -** For every WHERE clause term that is not used by the index -** and which has a truth probability assigned by one of the likelihood(), -** likely(), or unlikely() SQL functions, reduce the estimated number -** of output rows by the probability specified. -** -** TUNING: For every WHERE clause term that is not used by the index -** and which does not have an assigned truth probability, heuristics -** described below are used to try to estimate the truth probability. -** TODO --> Perhaps this is something that could be improved by better -** table statistics. -** -** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75% -** value corresponds to -1 in LogEst notation, so this means decrement -** the WhereLoop.nOut field for every such WHERE clause term. -** -** Heuristic 2: If there exists one or more WHERE clause terms of the -** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the -** final output row estimate is no greater than 1/4 of the total number -** of rows in the table. In other words, assume that x==EXPR will filter -** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the -** "x" column is boolean or else -1 or 0 or 1 is a common default value -** on the "x" column and so in that case only cap the output row estimate -** at 1/2 instead of 1/4. -*/ -static void whereLoopOutputAdjust( - WhereClause *pWC, /* The WHERE clause */ - WhereLoop *pLoop, /* The loop to adjust downward */ - LogEst nRow /* Number of rows in the entire table */ -){ - WhereTerm *pTerm, *pX; - Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); - int i, j; - LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ - - assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); - for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ - assert( pTerm!=0 ); - if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; - if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; - if( (pTerm->prereqAll & notAllowed)!=0 ) continue; - for(j=pLoop->nLTerm-1; j>=0; j--){ - pX = pLoop->aLTerm[j]; - if( pX==0 ) continue; - if( pX==pTerm ) break; - if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; - } - if( j<0 ){ - if( pTerm->truthProb<=0 ){ - /* If a truth probability is specified using the likelihood() hints, - ** then use the probability provided by the application. */ - pLoop->nOut += pTerm->truthProb; - }else{ - /* In the absence of explicit truth probabilities, use heuristics to - ** guess a reasonable truth probability. */ - pLoop->nOut--; - if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 - && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */ - ){ - Expr *pRight = pTerm->pExpr->pRight; - int k = 0; - testcase( pTerm->pExpr->op==TK_IS ); - if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ - k = 10; - }else{ - k = 20; - } - if( iReducewtFlags |= TERM_HEURTRUTH; - iReduce = k; - } - } - } - } - } - if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce; -} - -/* -** Term pTerm is a vector range comparison operation. The first comparison -** in the vector can be optimized using column nEq of the index. This -** function returns the total number of vector elements that can be used -** as part of the range comparison. -** -** For example, if the query is: -** -** WHERE a = ? AND (b, c, d) > (?, ?, ?) -** -** and the index: -** -** CREATE INDEX ... ON (a, b, c, d, e) -** -** then this function would be invoked with nEq=1. The value returned in -** this case is 3. -*/ -static int whereRangeVectorLen( - Parse *pParse, /* Parsing context */ - int iCur, /* Cursor open on pIdx */ - Index *pIdx, /* The index to be used for a inequality constraint */ - int nEq, /* Number of prior equality constraints on same index */ - WhereTerm *pTerm /* The vector inequality constraint */ -){ - int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft); - int i; - - nCmp = MIN(nCmp, (pIdx->nColumn - nEq)); - for(i=1; ipExpr->pLeft->x.pList->a[i].pExpr; - Expr *pRhs = pTerm->pExpr->pRight; - if( pRhs->flags & EP_xIsSelect ){ - pRhs = pRhs->x.pSelect->pEList->a[i].pExpr; - }else{ - pRhs = pRhs->x.pList->a[i].pExpr; - } - - /* Check that the LHS of the comparison is a column reference to - ** the right column of the right source table. And that the sort - ** order of the index column is the same as the sort order of the - ** leftmost index column. */ - if( pLhs->op!=TK_COLUMN - || pLhs->iTable!=iCur - || pLhs->iColumn!=pIdx->aiColumn[i+nEq] - || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq] - ){ - break; - } - - testcase( pLhs->iColumn==XN_ROWID ); - aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs)); - idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); - if( aff!=idxaff ) break; - - pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); - if( pColl==0 ) break; - if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; - } - return i; -} - -/* -** Adjust the cost C by the costMult facter T. This only occurs if -** compiled with -DSQLITE_ENABLE_COSTMULT -*/ -#ifdef SQLITE_ENABLE_COSTMULT -# define ApplyCostMultiplier(C,T) C += T -#else -# define ApplyCostMultiplier(C,T) -#endif - -/* -** We have so far matched pBuilder->pNew->u.btree.nEq terms of the -** index pIndex. Try to match one more. -** -** When this function is called, pBuilder->pNew->nOut contains the -** number of rows expected to be visited by filtering using the nEq -** terms only. If it is modified, this value is restored before this -** function returns. -** -** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is -** a fake index used for the INTEGER PRIMARY KEY. -*/ -static int whereLoopAddBtreeIndex( - WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ - struct SrcList_item *pSrc, /* FROM clause term being analyzed */ - Index *pProbe, /* An index on pSrc */ - LogEst nInMul /* log(Number of iterations due to IN) */ -){ - WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ - Parse *pParse = pWInfo->pParse; /* Parsing context */ - sqlite3 *db = pParse->db; /* Database connection malloc context */ - WhereLoop *pNew; /* Template WhereLoop under construction */ - WhereTerm *pTerm; /* A WhereTerm under consideration */ - int opMask; /* Valid operators for constraints */ - WhereScan scan; /* Iterator for WHERE terms */ - Bitmask saved_prereq; /* Original value of pNew->prereq */ - u16 saved_nLTerm; /* Original value of pNew->nLTerm */ - u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ - u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */ - u16 saved_nTop; /* Original value of pNew->u.btree.nTop */ - u16 saved_nSkip; /* Original value of pNew->nSkip */ - u32 saved_wsFlags; /* Original value of pNew->wsFlags */ - LogEst saved_nOut; /* Original value of pNew->nOut */ - int rc = SQLITE_OK; /* Return code */ - LogEst rSize; /* Number of rows in the table */ - LogEst rLogSize; /* Logarithm of table size */ - WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ - - pNew = pBuilder->pNew; - if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; - WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d\n", - pProbe->pTable->zName,pProbe->zName, - pNew->u.btree.nEq, pNew->nSkip)); - - assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); - assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); - if( pNew->wsFlags & WHERE_BTM_LIMIT ){ - opMask = WO_LT|WO_LE; - }else{ - assert( pNew->u.btree.nBtm==0 ); - opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS; - } - if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); - - assert( pNew->u.btree.nEqnColumn ); - - saved_nEq = pNew->u.btree.nEq; - saved_nBtm = pNew->u.btree.nBtm; - saved_nTop = pNew->u.btree.nTop; - saved_nSkip = pNew->nSkip; - saved_nLTerm = pNew->nLTerm; - saved_wsFlags = pNew->wsFlags; - saved_prereq = pNew->prereq; - saved_nOut = pNew->nOut; - pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq, - opMask, pProbe); - pNew->rSetup = 0; - rSize = pProbe->aiRowLogEst[0]; - rLogSize = estLog(rSize); - for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ - u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ - LogEst rCostIdx; - LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ - int nIn = 0; -#ifdef SQLITE_ENABLE_STAT4 - int nRecValid = pBuilder->nRecValid; -#endif - if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) - && indexColumnNotNull(pProbe, saved_nEq) - ){ - continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ - } - if( pTerm->prereqRight & pNew->maskSelf ) continue; - - /* Do not allow the upper bound of a LIKE optimization range constraint - ** to mix with a lower range bound from some other source */ - if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue; - - /* tag-20191211-001: Do not allow constraints from the WHERE clause to - ** be used by the right table of a LEFT JOIN. Only constraints in the - ** ON clause are allowed. See tag-20191211-002 for the vtab equivalent. */ - if( (pSrc->fg.jointype & JT_LEFT)!=0 - && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - ){ - continue; - } - - if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){ - pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE; - }else{ - pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED; - } - pNew->wsFlags = saved_wsFlags; - pNew->u.btree.nEq = saved_nEq; - pNew->u.btree.nBtm = saved_nBtm; - pNew->u.btree.nTop = saved_nTop; - pNew->nLTerm = saved_nLTerm; - if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ - pNew->aLTerm[pNew->nLTerm++] = pTerm; - pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; - - assert( nInMul==0 - || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 - || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 - || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 - ); - - if( eOp & WO_IN ){ - Expr *pExpr = pTerm->pExpr; - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ - int i; - nIn = 46; assert( 46==sqlite3LogEst(25) ); - - /* The expression may actually be of the form (x, y) IN (SELECT...). - ** In this case there is a separate term for each of (x) and (y). - ** However, the nIn multiplier should only be applied once, not once - ** for each such term. The following loop checks that pTerm is the - ** first such term in use, and sets nIn back to 0 if it is not. */ - for(i=0; inLTerm-1; i++){ - if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0; - } - }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ - /* "x IN (value, value, ...)" */ - nIn = sqlite3LogEst(pExpr->x.pList->nExpr); - } - if( pProbe->hasStat1 ){ - LogEst M, logK, safetyMargin; - /* Let: - ** N = the total number of rows in the table - ** K = the number of entries on the RHS of the IN operator - ** M = the number of rows in the table that match terms to the - ** to the left in the same index. If the IN operator is on - ** the left-most index column, M==N. - ** - ** Given the definitions above, it is better to omit the IN operator - ** from the index lookup and instead do a scan of the M elements, - ** testing each scanned row against the IN operator separately, if: - ** - ** M*log(K) < K*log(N) - ** - ** Our estimates for M, K, and N might be inaccurate, so we build in - ** a safety margin of 2 (LogEst: 10) that favors using the IN operator - ** with the index, as using an index has better worst-case behavior. - ** If we do not have real sqlite_stat1 data, always prefer to use - ** the index. - */ - M = pProbe->aiRowLogEst[saved_nEq]; - logK = estLog(nIn); - safetyMargin = 10; /* TUNING: extra weight for indexed IN */ - if( M + logK + safetyMargin < nIn + rLogSize ){ - WHERETRACE(0x40, - ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n", - saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize)); - continue; - }else{ - WHERETRACE(0x40, - ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n", - saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize)); - } - } - pNew->wsFlags |= WHERE_COLUMN_IN; - }else if( eOp & (WO_EQ|WO_IS) ){ - int iCol = pProbe->aiColumn[saved_nEq]; - pNew->wsFlags |= WHERE_COLUMN_EQ; - assert( saved_nEq==pNew->u.btree.nEq ); - if( iCol==XN_ROWID - || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) - ){ - if( iCol==XN_ROWID || pProbe->uniqNotNull - || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ) - ){ - pNew->wsFlags |= WHERE_ONEROW; - }else{ - pNew->wsFlags |= WHERE_UNQ_WANTED; - } - } - }else if( eOp & WO_ISNULL ){ - pNew->wsFlags |= WHERE_COLUMN_NULL; - }else if( eOp & (WO_GT|WO_GE) ){ - testcase( eOp & WO_GT ); - testcase( eOp & WO_GE ); - pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; - pNew->u.btree.nBtm = whereRangeVectorLen( - pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm - ); - pBtm = pTerm; - pTop = 0; - if( pTerm->wtFlags & TERM_LIKEOPT ){ - /* Range contraints that come from the LIKE optimization are - ** always used in pairs. */ - pTop = &pTerm[1]; - assert( (pTop-(pTerm->pWC->a))pWC->nTerm ); - assert( pTop->wtFlags & TERM_LIKEOPT ); - assert( pTop->eOperator==WO_LT ); - if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ - pNew->aLTerm[pNew->nLTerm++] = pTop; - pNew->wsFlags |= WHERE_TOP_LIMIT; - pNew->u.btree.nTop = 1; - } - }else{ - assert( eOp & (WO_LT|WO_LE) ); - testcase( eOp & WO_LT ); - testcase( eOp & WO_LE ); - pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; - pNew->u.btree.nTop = whereRangeVectorLen( - pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm - ); - pTop = pTerm; - pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? - pNew->aLTerm[pNew->nLTerm-2] : 0; - } - - /* At this point pNew->nOut is set to the number of rows expected to - ** be visited by the index scan before considering term pTerm, or the - ** values of nIn and nInMul. In other words, assuming that all - ** "x IN(...)" terms are replaced with "x = ?". This block updates - ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ - assert( pNew->nOut==saved_nOut ); - if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ - /* Adjust nOut using stat4 data. Or, if there is no stat4 - ** data, using some other estimate. */ - whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); - }else{ - int nEq = ++pNew->u.btree.nEq; - assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) ); - - assert( pNew->nOut==saved_nOut ); - if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){ - assert( (eOp & WO_IN) || nIn==0 ); - testcase( eOp & WO_IN ); - pNew->nOut += pTerm->truthProb; - pNew->nOut -= nIn; - }else{ -#ifdef SQLITE_ENABLE_STAT4 - tRowcnt nOut = 0; - if( nInMul==0 - && pProbe->nSample - && pNew->u.btree.nEq<=pProbe->nSampleCol - && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) - && OptimizationEnabled(db, SQLITE_Stat4) - ){ - Expr *pExpr = pTerm->pExpr; - if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){ - testcase( eOp & WO_EQ ); - testcase( eOp & WO_IS ); - testcase( eOp & WO_ISNULL ); - rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); - }else{ - rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); - } - if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; - if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ - if( nOut ){ - pNew->nOut = sqlite3LogEst(nOut); - if( nEq==1 - /* TUNING: Mark terms as "low selectivity" if they seem likely - ** to be true for half or more of the rows in the table. - ** See tag-202002240-1 */ - && pNew->nOut+10 > pProbe->aiRowLogEst[0] - ){ -#if WHERETRACE_ENABLED /* 0x01 */ - if( sqlite3WhereTrace & 0x01 ){ - sqlite3DebugPrintf( - "STAT4 determines term has low selectivity:\n"); - sqlite3WhereTermPrint(pTerm, 999); - } -#endif - pTerm->wtFlags |= TERM_HIGHTRUTH; - if( pTerm->wtFlags & TERM_HEURTRUTH ){ - /* If the term has previously been used with an assumption of - ** higher selectivity, then set the flag to rerun the - ** loop computations. */ - pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS; - } - } - if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; - pNew->nOut -= nIn; - } - } - if( nOut==0 ) -#endif - { - pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]); - if( eOp & WO_ISNULL ){ - /* TUNING: If there is no likelihood() value, assume that a - ** "col IS NULL" expression matches twice as many rows - ** as (col=?). */ - pNew->nOut += 10; - } - } - } - } - - /* Set rCostIdx to the cost of visiting selected rows in index. Add - ** it to pNew->rRun, which is currently set to the cost of the index - ** seek only. Then, if this is a non-covering index, add the cost of - ** visiting the rows in the main table. */ - assert( pSrc->pTab->szTabRow>0 ); - rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow; - pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx); - if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ - pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); - } - ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); - - nOutUnadjusted = pNew->nOut; - pNew->rRun += nInMul + nIn; - pNew->nOut += nInMul + nIn; - whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize); - rc = whereLoopInsert(pBuilder, pNew); - - if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ - pNew->nOut = saved_nOut; - }else{ - pNew->nOut = nOutUnadjusted; - } - - if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 - && pNew->u.btree.nEqnColumn - ){ - whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); - } - pNew->nOut = saved_nOut; -#ifdef SQLITE_ENABLE_STAT4 - pBuilder->nRecValid = nRecValid; -#endif - } - pNew->prereq = saved_prereq; - pNew->u.btree.nEq = saved_nEq; - pNew->u.btree.nBtm = saved_nBtm; - pNew->u.btree.nTop = saved_nTop; - pNew->nSkip = saved_nSkip; - pNew->wsFlags = saved_wsFlags; - pNew->nOut = saved_nOut; - pNew->nLTerm = saved_nLTerm; - - /* Consider using a skip-scan if there are no WHERE clause constraints - ** available for the left-most terms of the index, and if the average - ** number of repeats in the left-most terms is at least 18. - ** - ** The magic number 18 is selected on the basis that scanning 17 rows - ** is almost always quicker than an index seek (even though if the index - ** contains fewer than 2^17 rows we assume otherwise in other parts of - ** the code). And, even if it is not, it should not be too much slower. - ** On the other hand, the extra seeks could end up being significantly - ** more expensive. */ - assert( 42==sqlite3LogEst(18) ); - if( saved_nEq==saved_nSkip - && saved_nEq+1nKeyCol - && saved_nEq==pNew->nLTerm - && pProbe->noSkipScan==0 - && pProbe->hasStat1!=0 - && OptimizationEnabled(db, SQLITE_SkipScan) - && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ - && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK - ){ - LogEst nIter; - pNew->u.btree.nEq++; - pNew->nSkip++; - pNew->aLTerm[pNew->nLTerm++] = 0; - pNew->wsFlags |= WHERE_SKIPSCAN; - nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; - pNew->nOut -= nIter; - /* TUNING: Because uncertainties in the estimates for skip-scan queries, - ** add a 1.375 fudge factor to make skip-scan slightly less likely. */ - nIter += 5; - whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); - pNew->nOut = saved_nOut; - pNew->u.btree.nEq = saved_nEq; - pNew->nSkip = saved_nSkip; - pNew->wsFlags = saved_wsFlags; - } - - WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n", - pProbe->pTable->zName, pProbe->zName, saved_nEq, rc)); - return rc; -} - -/* -** Return True if it is possible that pIndex might be useful in -** implementing the ORDER BY clause in pBuilder. -** -** Return False if pBuilder does not contain an ORDER BY clause or -** if there is no way for pIndex to be useful in implementing that -** ORDER BY clause. -*/ -static int indexMightHelpWithOrderBy( - WhereLoopBuilder *pBuilder, - Index *pIndex, - int iCursor -){ - ExprList *pOB; - ExprList *aColExpr; - int ii, jj; - - if( pIndex->bUnordered ) return 0; - if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; - for(ii=0; iinExpr; ii++){ - Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr); - if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){ - if( pExpr->iColumn<0 ) return 1; - for(jj=0; jjnKeyCol; jj++){ - if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; - } - }else if( (aColExpr = pIndex->aColExpr)!=0 ){ - for(jj=0; jjnKeyCol; jj++){ - if( pIndex->aiColumn[jj]!=XN_EXPR ) continue; - if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ - return 1; - } - } - } - } - return 0; -} - -/* Check to see if a partial index with pPartIndexWhere can be used -** in the current query. Return true if it can be and false if not. -*/ -static int whereUsablePartialIndex( - int iTab, /* The table for which we want an index */ - int isLeft, /* True if iTab is the right table of a LEFT JOIN */ - WhereClause *pWC, /* The WHERE clause of the query */ - Expr *pWhere /* The WHERE clause from the partial index */ -){ - int i; - WhereTerm *pTerm; - Parse *pParse = pWC->pWInfo->pParse; - while( pWhere->op==TK_AND ){ - if( !whereUsablePartialIndex(iTab,isLeft,pWC,pWhere->pLeft) ) return 0; - pWhere = pWhere->pRight; - } - if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0; - for(i=0, pTerm=pWC->a; inTerm; i++, pTerm++){ - Expr *pExpr; - pExpr = pTerm->pExpr; - if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) - && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin)) - && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) - ){ - return 1; - } - } - return 0; -} - -/* -** Add all WhereLoop objects for a single table of the join where the table -** is identified by pBuilder->pNew->iTab. That table is guaranteed to be -** a b-tree table, not a virtual table. -** -** The costs (WhereLoop.rRun) of the b-tree loops added by this function -** are calculated as follows: -** -** For a full scan, assuming the table (or index) contains nRow rows: -** -** cost = nRow * 3.0 // full-table scan -** cost = nRow * K // scan of covering index -** cost = nRow * (K+3.0) // scan of non-covering index -** -** where K is a value between 1.1 and 3.0 set based on the relative -** estimated average size of the index and table records. -** -** For an index scan, where nVisit is the number of index rows visited -** by the scan, and nSeek is the number of seek operations required on -** the index b-tree: -** -** cost = nSeek * (log(nRow) + K * nVisit) // covering index -** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index -** -** Normally, nSeek is 1. nSeek values greater than 1 come about if the -** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when -** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans. -** -** The estimated values (nRow, nVisit, nSeek) often contain a large amount -** of uncertainty. For this reason, scoring is designed to pick plans that -** "do the least harm" if the estimates are inaccurate. For example, a -** log(nRow) factor is omitted from a non-covering index scan in order to -** bias the scoring in favor of using an index, since the worst-case -** performance of using an index is far better than the worst-case performance -** of a full table scan. -*/ -static int whereLoopAddBtree( - WhereLoopBuilder *pBuilder, /* WHERE clause information */ - Bitmask mPrereq /* Extra prerequesites for using this table */ -){ - WhereInfo *pWInfo; /* WHERE analysis context */ - Index *pProbe; /* An index we are evaluating */ - Index sPk; /* A fake index object for the primary key */ - LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */ - i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */ - SrcList *pTabList; /* The FROM clause */ - struct SrcList_item *pSrc; /* The FROM clause btree term to add */ - WhereLoop *pNew; /* Template WhereLoop object */ - int rc = SQLITE_OK; /* Return code */ - int iSortIdx = 1; /* Index number */ - int b; /* A boolean value */ - LogEst rSize; /* number of rows in the table */ - LogEst rLogSize; /* Logarithm of the number of rows in the table */ - WhereClause *pWC; /* The parsed WHERE clause */ - Table *pTab; /* Table being queried */ - - pNew = pBuilder->pNew; - pWInfo = pBuilder->pWInfo; - pTabList = pWInfo->pTabList; - pSrc = pTabList->a + pNew->iTab; - pTab = pSrc->pTab; - pWC = pBuilder->pWC; - assert( !IsVirtual(pSrc->pTab) ); - - if( pSrc->pIBIndex ){ - /* An INDEXED BY clause specifies a particular index to use */ - pProbe = pSrc->pIBIndex; - }else if( !HasRowid(pTab) ){ - pProbe = pTab->pIndex; - }else{ - /* There is no INDEXED BY clause. Create a fake Index object in local - ** variable sPk to represent the rowid primary key index. Make this - ** fake index the first in a chain of Index objects with all of the real - ** indices to follow */ - Index *pFirst; /* First of real indices on the table */ - memset(&sPk, 0, sizeof(Index)); - sPk.nKeyCol = 1; - sPk.nColumn = 1; - sPk.aiColumn = &aiColumnPk; - sPk.aiRowLogEst = aiRowEstPk; - sPk.onError = OE_Replace; - sPk.pTable = pTab; - sPk.szIdxRow = pTab->szTabRow; - sPk.idxType = SQLITE_IDXTYPE_IPK; - aiRowEstPk[0] = pTab->nRowLogEst; - aiRowEstPk[1] = 0; - pFirst = pSrc->pTab->pIndex; - if( pSrc->fg.notIndexed==0 ){ - /* The real indices of the table are only considered if the - ** NOT INDEXED qualifier is omitted from the FROM clause */ - sPk.pNext = pFirst; - } - pProbe = &sPk; - } - rSize = pTab->nRowLogEst; - rLogSize = estLog(rSize); - -#ifndef SQLITE_OMIT_AUTOMATIC_INDEX - /* Automatic indexes */ - if( !pBuilder->pOrSet /* Not part of an OR optimization */ - && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 - && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 - && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */ - && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */ - && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */ - && !pSrc->fg.isCorrelated /* Not a correlated subquery */ - && !pSrc->fg.isRecursive /* Not a recursive common table expression. */ - ){ - /* Generate auto-index WhereLoops */ - WhereTerm *pTerm; - WhereTerm *pWCEnd = pWC->a + pWC->nTerm; - for(pTerm=pWC->a; rc==SQLITE_OK && pTermprereqRight & pNew->maskSelf ) continue; - if( termCanDriveIndex(pTerm, pSrc, 0) ){ - pNew->u.btree.nEq = 1; - pNew->nSkip = 0; - pNew->u.btree.pIndex = 0; - pNew->nLTerm = 1; - pNew->aLTerm[0] = pTerm; - /* TUNING: One-time cost for computing the automatic index is - ** estimated to be X*N*log2(N) where N is the number of rows in - ** the table being indexed and where X is 7 (LogEst=28) for normal - ** tables or 0.5 (LogEst=-10) for views and subqueries. The value - ** of X is smaller for views and subqueries so that the query planner - ** will be more aggressive about generating automatic indexes for - ** those objects, since there is no opportunity to add schema - ** indexes on subqueries and views. */ - pNew->rSetup = rLogSize + rSize; - if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){ - pNew->rSetup += 28; - }else{ - pNew->rSetup -= 10; - } - ApplyCostMultiplier(pNew->rSetup, pTab->costMult); - if( pNew->rSetup<0 ) pNew->rSetup = 0; - /* TUNING: Each index lookup yields 20 rows in the table. This - ** is more than the usual guess of 10 rows, since we have no way - ** of knowing how selective the index will ultimately be. It would - ** not be unreasonable to make this value much larger. */ - pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); - pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); - pNew->wsFlags = WHERE_AUTO_INDEX; - pNew->prereq = mPrereq | pTerm->prereqRight; - rc = whereLoopInsert(pBuilder, pNew); - } - } - } -#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ - - /* Loop over all indices. If there was an INDEXED BY clause, then only - ** consider index pProbe. */ - for(; rc==SQLITE_OK && pProbe; - pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++ - ){ - int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0; - if( pProbe->pPartIdxWhere!=0 - && !whereUsablePartialIndex(pSrc->iCursor, isLeft, pWC, - pProbe->pPartIdxWhere) - ){ - testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ - continue; /* Partial index inappropriate for this query */ - } - if( pProbe->bNoQuery ) continue; - rSize = pProbe->aiRowLogEst[0]; - pNew->u.btree.nEq = 0; - pNew->u.btree.nBtm = 0; - pNew->u.btree.nTop = 0; - pNew->nSkip = 0; - pNew->nLTerm = 0; - pNew->iSortIdx = 0; - pNew->rSetup = 0; - pNew->prereq = mPrereq; - pNew->nOut = rSize; - pNew->u.btree.pIndex = pProbe; - b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); - - /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ - assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); - if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){ - /* Integer primary key index */ - pNew->wsFlags = WHERE_IPK; - - /* Full table scan */ - pNew->iSortIdx = b ? iSortIdx : 0; - /* TUNING: Cost of full table scan is (N*3.0). */ - pNew->rRun = rSize + 16; - ApplyCostMultiplier(pNew->rRun, pTab->costMult); - whereLoopOutputAdjust(pWC, pNew, rSize); - rc = whereLoopInsert(pBuilder, pNew); - pNew->nOut = rSize; - if( rc ) break; - }else{ - Bitmask m; - if( pProbe->isCovering ){ - pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; - m = 0; - }else{ - m = pSrc->colUsed & pProbe->colNotIdxed; - pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; - } - - /* Full scan via index */ - if( b - || !HasRowid(pTab) - || pProbe->pPartIdxWhere!=0 - || pSrc->fg.isIndexedBy - || ( m==0 - && pProbe->bUnordered==0 - && (pProbe->szIdxRowszTabRow) - && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 - && sqlite3GlobalConfig.bUseCis - && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) - ) - ){ - pNew->iSortIdx = b ? iSortIdx : 0; - - /* The cost of visiting the index rows is N*K, where K is - ** between 1.1 and 3.0, depending on the relative sizes of the - ** index and table rows. */ - pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; - if( m!=0 ){ - /* If this is a non-covering index scan, add in the cost of - ** doing table lookups. The cost will be 3x the number of - ** lookups. Take into account WHERE clause terms that can be - ** satisfied using just the index, and that do not require a - ** table lookup. */ - LogEst nLookup = rSize + 16; /* Base cost: N*3 */ - int ii; - int iCur = pSrc->iCursor; - WhereClause *pWC2 = &pWInfo->sWC; - for(ii=0; iinTerm; ii++){ - WhereTerm *pTerm = &pWC2->a[ii]; - if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ - break; - } - /* pTerm can be evaluated using just the index. So reduce - ** the expected number of table lookups accordingly */ - if( pTerm->truthProb<=0 ){ - nLookup += pTerm->truthProb; - }else{ - nLookup--; - if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19; - } - } - - pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup); - } - ApplyCostMultiplier(pNew->rRun, pTab->costMult); - whereLoopOutputAdjust(pWC, pNew, rSize); - rc = whereLoopInsert(pBuilder, pNew); - pNew->nOut = rSize; - if( rc ) break; - } - } - - pBuilder->bldFlags1 = 0; - rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); - if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){ - /* If a non-unique index is used, or if a prefix of the key for - ** unique index is used (making the index functionally non-unique) - ** then the sqlite_stat1 data becomes important for scoring the - ** plan */ - pTab->tabFlags |= TF_StatsUsed; - } -#ifdef SQLITE_ENABLE_STAT4 - sqlite3Stat4ProbeFree(pBuilder->pRec); - pBuilder->nRecValid = 0; - pBuilder->pRec = 0; -#endif - } - return rc; -} - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* -** Argument pIdxInfo is already populated with all constraints that may -** be used by the virtual table identified by pBuilder->pNew->iTab. This -** function marks a subset of those constraints usable, invokes the -** xBestIndex method and adds the returned plan to pBuilder. -** -** A constraint is marked usable if: -** -** * Argument mUsable indicates that its prerequisites are available, and -** -** * It is not one of the operators specified in the mExclude mask passed -** as the fourth argument (which in practice is either WO_IN or 0). -** -** Argument mPrereq is a mask of tables that must be scanned before the -** virtual table in question. These are added to the plans prerequisites -** before it is added to pBuilder. -** -** Output parameter *pbIn is set to true if the plan added to pBuilder -** uses one or more WO_IN terms, or false otherwise. -*/ -static int whereLoopAddVirtualOne( - WhereLoopBuilder *pBuilder, - Bitmask mPrereq, /* Mask of tables that must be used. */ - Bitmask mUsable, /* Mask of usable tables */ - u16 mExclude, /* Exclude terms using these operators */ - sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ - u16 mNoOmit, /* Do not omit these constraints */ - int *pbIn /* OUT: True if plan uses an IN(...) op */ -){ - WhereClause *pWC = pBuilder->pWC; - struct sqlite3_index_constraint *pIdxCons; - struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; - int i; - int mxTerm; - int rc = SQLITE_OK; - WhereLoop *pNew = pBuilder->pNew; - Parse *pParse = pBuilder->pWInfo->pParse; - struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab]; - int nConstraint = pIdxInfo->nConstraint; - - assert( (mUsable & mPrereq)==mPrereq ); - *pbIn = 0; - pNew->prereq = mPrereq; - - /* Set the usable flag on the subset of constraints identified by - ** arguments mUsable and mExclude. */ - pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; - for(i=0; ia[pIdxCons->iTermOffset]; - pIdxCons->usable = 0; - if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight - && (pTerm->eOperator & mExclude)==0 - ){ - pIdxCons->usable = 1; - } - } - - /* Initialize the output fields of the sqlite3_index_info structure */ - memset(pUsage, 0, sizeof(pUsage[0])*nConstraint); - assert( pIdxInfo->needToFreeIdxStr==0 ); - pIdxInfo->idxStr = 0; - pIdxInfo->idxNum = 0; - pIdxInfo->orderByConsumed = 0; - pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; - pIdxInfo->estimatedRows = 25; - pIdxInfo->idxFlags = 0; - pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; - - /* Invoke the virtual table xBestIndex() method */ - rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo); - if( rc ){ - if( rc==SQLITE_CONSTRAINT ){ - /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means - ** that the particular combination of parameters provided is unusable. - ** Make no entries in the loop table. - */ - WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n")); - return SQLITE_OK; - } - return rc; - } - - mxTerm = -1; - assert( pNew->nLSlot>=nConstraint ); - for(i=0; iaLTerm[i] = 0; - pNew->u.vtab.omitMask = 0; - pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; - for(i=0; i=0 ){ - WhereTerm *pTerm; - int j = pIdxCons->iTermOffset; - if( iTerm>=nConstraint - || j<0 - || j>=pWC->nTerm - || pNew->aLTerm[iTerm]!=0 - || pIdxCons->usable==0 - ){ - sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); - testcase( pIdxInfo->needToFreeIdxStr ); - return SQLITE_ERROR; - } - testcase( iTerm==nConstraint-1 ); - testcase( j==0 ); - testcase( j==pWC->nTerm-1 ); - pTerm = &pWC->a[j]; - pNew->prereq |= pTerm->prereqRight; - assert( iTermnLSlot ); - pNew->aLTerm[iTerm] = pTerm; - if( iTerm>mxTerm ) mxTerm = iTerm; - testcase( iTerm==15 ); - testcase( iTerm==16 ); - if( pUsage[i].omit ){ - if( i<16 && ((1<u.vtab.omitMask |= 1<eOperator & WO_IN)!=0 ){ - /* A virtual table that is constrained by an IN clause may not - ** consume the ORDER BY clause because (1) the order of IN terms - ** is not necessarily related to the order of output terms and - ** (2) Multiple outputs from a single IN value will not merge - ** together. */ - pIdxInfo->orderByConsumed = 0; - pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE; - *pbIn = 1; assert( (mExclude & WO_IN)==0 ); - } - } - } - - pNew->nLTerm = mxTerm+1; - for(i=0; i<=mxTerm; i++){ - if( pNew->aLTerm[i]==0 ){ - /* The non-zero argvIdx values must be contiguous. Raise an - ** error if they are not */ - sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); - testcase( pIdxInfo->needToFreeIdxStr ); - return SQLITE_ERROR; - } - } - assert( pNew->nLTerm<=pNew->nLSlot ); - pNew->u.vtab.idxNum = pIdxInfo->idxNum; - pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; - pIdxInfo->needToFreeIdxStr = 0; - pNew->u.vtab.idxStr = pIdxInfo->idxStr; - pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? - pIdxInfo->nOrderBy : 0); - pNew->rSetup = 0; - pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); - pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); - - /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated - ** that the scan will visit at most one row. Clear it otherwise. */ - if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){ - pNew->wsFlags |= WHERE_ONEROW; - }else{ - pNew->wsFlags &= ~WHERE_ONEROW; - } - rc = whereLoopInsert(pBuilder, pNew); - if( pNew->u.vtab.needFree ){ - sqlite3_free(pNew->u.vtab.idxStr); - pNew->u.vtab.needFree = 0; - } - WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n", - *pbIn, (sqlite3_uint64)mPrereq, - (sqlite3_uint64)(pNew->prereq & ~mPrereq))); - - return rc; -} - -/* -** If this function is invoked from within an xBestIndex() callback, it -** returns a pointer to a buffer containing the name of the collation -** sequence associated with element iCons of the sqlite3_index_info.aConstraint -** array. Or, if iCons is out of range or there is no active xBestIndex -** call, return NULL. -*/ -SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){ - HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; - const char *zRet = 0; - if( iCons>=0 && iConsnConstraint ){ - CollSeq *pC = 0; - int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset; - Expr *pX = pHidden->pWC->a[iTerm].pExpr; - if( pX->pLeft ){ - pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX); - } - zRet = (pC ? pC->zName : sqlite3StrBINARY); - } - return zRet; -} - -/* -** Add all WhereLoop objects for a table of the join identified by -** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. -** -** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and -** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause -** entries that occur before the virtual table in the FROM clause and are -** separated from it by at least one LEFT or CROSS JOIN. Similarly, the -** mUnusable mask contains all FROM clause entries that occur after the -** virtual table and are separated from it by at least one LEFT or -** CROSS JOIN. -** -** For example, if the query were: -** -** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6; -** -** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6). -** -** All the tables in mPrereq must be scanned before the current virtual -** table. So any terms for which all prerequisites are satisfied by -** mPrereq may be specified as "usable" in all calls to xBestIndex. -** Conversely, all tables in mUnusable must be scanned after the current -** virtual table, so any terms for which the prerequisites overlap with -** mUnusable should always be configured as "not-usable" for xBestIndex. -*/ -static int whereLoopAddVirtual( - WhereLoopBuilder *pBuilder, /* WHERE clause information */ - Bitmask mPrereq, /* Tables that must be scanned before this one */ - Bitmask mUnusable /* Tables that must be scanned after this one */ -){ - int rc = SQLITE_OK; /* Return code */ - WhereInfo *pWInfo; /* WHERE analysis context */ - Parse *pParse; /* The parsing context */ - WhereClause *pWC; /* The WHERE clause */ - struct SrcList_item *pSrc; /* The FROM clause term to search */ - sqlite3_index_info *p; /* Object to pass to xBestIndex() */ - int nConstraint; /* Number of constraints in p */ - int bIn; /* True if plan uses IN(...) operator */ - WhereLoop *pNew; - Bitmask mBest; /* Tables used by best possible plan */ - u16 mNoOmit; - - assert( (mPrereq & mUnusable)==0 ); - pWInfo = pBuilder->pWInfo; - pParse = pWInfo->pParse; - pWC = pBuilder->pWC; - pNew = pBuilder->pNew; - pSrc = &pWInfo->pTabList->a[pNew->iTab]; - assert( IsVirtual(pSrc->pTab) ); - p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, - &mNoOmit); - if( p==0 ) return SQLITE_NOMEM_BKPT; - pNew->rSetup = 0; - pNew->wsFlags = WHERE_VIRTUALTABLE; - pNew->nLTerm = 0; - pNew->u.vtab.needFree = 0; - nConstraint = p->nConstraint; - if( whereLoopResize(pParse->db, pNew, nConstraint) ){ - sqlite3DbFree(pParse->db, p); - return SQLITE_NOMEM_BKPT; - } - - /* First call xBestIndex() with all constraints usable. */ - WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName)); - WHERETRACE(0x40, (" VirtualOne: all usable\n")); - rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn); - - /* If the call to xBestIndex() with all terms enabled produced a plan - ** that does not require any source tables (IOW: a plan with mBest==0) - ** and does not use an IN(...) operator, then there is no point in making - ** any further calls to xBestIndex() since they will all return the same - ** result (if the xBestIndex() implementation is sane). */ - if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){ - int seenZero = 0; /* True if a plan with no prereqs seen */ - int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */ - Bitmask mPrev = 0; - Bitmask mBestNoIn = 0; - - /* If the plan produced by the earlier call uses an IN(...) term, call - ** xBestIndex again, this time with IN(...) terms disabled. */ - if( bIn ){ - WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n")); - rc = whereLoopAddVirtualOne( - pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn); - assert( bIn==0 ); - mBestNoIn = pNew->prereq & ~mPrereq; - if( mBestNoIn==0 ){ - seenZero = 1; - seenZeroNoIN = 1; - } - } - - /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) - ** in the set of terms that apply to the current virtual table. */ - while( rc==SQLITE_OK ){ - int i; - Bitmask mNext = ALLBITS; - assert( mNext>0 ); - for(i=0; ia[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq - ); - if( mThis>mPrev && mThisprereq==mPrereq ){ - seenZero = 1; - if( bIn==0 ) seenZeroNoIN = 1; - } - } - - /* If the calls to xBestIndex() in the above loop did not find a plan - ** that requires no source tables at all (i.e. one guaranteed to be - ** usable), make a call here with all source tables disabled */ - if( rc==SQLITE_OK && seenZero==0 ){ - WHERETRACE(0x40, (" VirtualOne: all disabled\n")); - rc = whereLoopAddVirtualOne( - pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn); - if( bIn==0 ) seenZeroNoIN = 1; - } - - /* If the calls to xBestIndex() have so far failed to find a plan - ** that requires no source tables at all and does not use an IN(...) - ** operator, make a final call to obtain one here. */ - if( rc==SQLITE_OK && seenZeroNoIN==0 ){ - WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n")); - rc = whereLoopAddVirtualOne( - pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn); - } - } - - if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr); - sqlite3DbFreeNN(pParse->db, p); - WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc)); - return rc; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -/* -** Add WhereLoop entries to handle OR terms. This works for either -** btrees or virtual tables. -*/ -static int whereLoopAddOr( - WhereLoopBuilder *pBuilder, - Bitmask mPrereq, - Bitmask mUnusable -){ - WhereInfo *pWInfo = pBuilder->pWInfo; - WhereClause *pWC; - WhereLoop *pNew; - WhereTerm *pTerm, *pWCEnd; - int rc = SQLITE_OK; - int iCur; - WhereClause tempWC; - WhereLoopBuilder sSubBuild; - WhereOrSet sSum, sCur; - struct SrcList_item *pItem; - - pWC = pBuilder->pWC; - pWCEnd = pWC->a + pWC->nTerm; - pNew = pBuilder->pNew; - memset(&sSum, 0, sizeof(sSum)); - pItem = pWInfo->pTabList->a + pNew->iTab; - iCur = pItem->iCursor; - - for(pTerm=pWC->a; pTermeOperator & WO_OR)!=0 - && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 - ){ - WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; - WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; - WhereTerm *pOrTerm; - int once = 1; - int i, j; - - sSubBuild = *pBuilder; - sSubBuild.pOrderBy = 0; - sSubBuild.pOrSet = &sCur; - - WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm)); - for(pOrTerm=pOrWC->a; pOrTermeOperator & WO_AND)!=0 ){ - sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; - }else if( pOrTerm->leftCursor==iCur ){ - tempWC.pWInfo = pWC->pWInfo; - tempWC.pOuter = pWC; - tempWC.op = TK_AND; - tempWC.nTerm = 1; - tempWC.a = pOrTerm; - sSubBuild.pWC = &tempWC; - }else{ - continue; - } - sCur.n = 0; -#ifdef WHERETRACE_ENABLED - WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", - (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); - if( sqlite3WhereTrace & 0x400 ){ - sqlite3WhereClausePrint(sSubBuild.pWC); - } -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pItem->pTab) ){ - rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable); - }else -#endif - { - rc = whereLoopAddBtree(&sSubBuild, mPrereq); - } - if( rc==SQLITE_OK ){ - rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable); - } - assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 ); - testcase( rc==SQLITE_DONE ); - if( sCur.n==0 ){ - sSum.n = 0; - break; - }else if( once ){ - whereOrMove(&sSum, &sCur); - once = 0; - }else{ - WhereOrSet sPrev; - whereOrMove(&sPrev, &sSum); - sSum.n = 0; - for(i=0; inLTerm = 1; - pNew->aLTerm[0] = pTerm; - pNew->wsFlags = WHERE_MULTI_OR; - pNew->rSetup = 0; - pNew->iSortIdx = 0; - memset(&pNew->u, 0, sizeof(pNew->u)); - for(i=0; rc==SQLITE_OK && irRun = sSum.a[i].rRun + 1; - pNew->nOut = sSum.a[i].nOut; - pNew->prereq = sSum.a[i].prereq; - rc = whereLoopInsert(pBuilder, pNew); - } - WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm)); - } - } - return rc; -} - -/* -** Add all WhereLoop objects for all tables -*/ -static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ - WhereInfo *pWInfo = pBuilder->pWInfo; - Bitmask mPrereq = 0; - Bitmask mPrior = 0; - int iTab; - SrcList *pTabList = pWInfo->pTabList; - struct SrcList_item *pItem; - struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel]; - sqlite3 *db = pWInfo->pParse->db; - int rc = SQLITE_OK; - WhereLoop *pNew; - - /* Loop over the tables in the join, from left to right */ - pNew = pBuilder->pNew; - whereLoopInit(pNew); - pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT; - for(iTab=0, pItem=pTabList->a; pItemiTab = iTab; - pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR; - pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); - if( (pItem->fg.jointype & (JT_LEFT|JT_CROSS))!=0 ){ - /* This condition is true when pItem is the FROM clause term on the - ** right-hand-side of a LEFT or CROSS JOIN. */ - mPrereq = mPrior; - }else{ - mPrereq = 0; - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( IsVirtual(pItem->pTab) ){ - struct SrcList_item *p; - for(p=&pItem[1]; pfg.jointype & (JT_LEFT|JT_CROSS)) ){ - mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); - } - } - rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable); - }else -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - { - rc = whereLoopAddBtree(pBuilder, mPrereq); - } - if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){ - rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); - } - mPrior |= pNew->maskSelf; - if( rc || db->mallocFailed ){ - if( rc==SQLITE_DONE ){ - /* We hit the query planner search limit set by iPlanLimit */ - sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search"); - rc = SQLITE_OK; - }else{ - break; - } - } - } - - whereLoopClear(db, pNew); - return rc; -} - -/* -** Examine a WherePath (with the addition of the extra WhereLoop of the 6th -** parameters) to see if it outputs rows in the requested ORDER BY -** (or GROUP BY) without requiring a separate sort operation. Return N: -** -** N>0: N terms of the ORDER BY clause are satisfied -** N==0: No terms of the ORDER BY clause are satisfied -** N<0: Unknown yet how many terms of ORDER BY might be satisfied. -** -** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as -** strict. With GROUP BY and DISTINCT the only requirement is that -** equivalent rows appear immediately adjacent to one another. GROUP BY -** and DISTINCT do not require rows to appear in any particular order as long -** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT -** the pOrderBy terms can be matched in any order. With ORDER BY, the -** pOrderBy terms must be matched in strict left-to-right order. -*/ -static i8 wherePathSatisfiesOrderBy( - WhereInfo *pWInfo, /* The WHERE clause */ - ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ - WherePath *pPath, /* The WherePath to check */ - u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ - u16 nLoop, /* Number of entries in pPath->aLoop[] */ - WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ - Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ -){ - u8 revSet; /* True if rev is known */ - u8 rev; /* Composite sort order */ - u8 revIdx; /* Index sort order */ - u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ - u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ - u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ - u16 eqOpMask; /* Allowed equality operators */ - u16 nKeyCol; /* Number of key columns in pIndex */ - u16 nColumn; /* Total number of ordered columns in the index */ - u16 nOrderBy; /* Number terms in the ORDER BY clause */ - int iLoop; /* Index of WhereLoop in pPath being processed */ - int i, j; /* Loop counters */ - int iCur; /* Cursor number for current WhereLoop */ - int iColumn; /* A column number within table iCur */ - WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ - WhereTerm *pTerm; /* A single term of the WHERE clause */ - Expr *pOBExpr; /* An expression from the ORDER BY clause */ - CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ - Index *pIndex; /* The index associated with pLoop */ - sqlite3 *db = pWInfo->pParse->db; /* Database connection */ - Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ - Bitmask obDone; /* Mask of all ORDER BY terms */ - Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ - Bitmask ready; /* Mask of inner loops */ - - /* - ** We say the WhereLoop is "one-row" if it generates no more than one - ** row of output. A WhereLoop is one-row if all of the following are true: - ** (a) All index columns match with WHERE_COLUMN_EQ. - ** (b) The index is unique - ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. - ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. - ** - ** We say the WhereLoop is "order-distinct" if the set of columns from - ** that WhereLoop that are in the ORDER BY clause are different for every - ** row of the WhereLoop. Every one-row WhereLoop is automatically - ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause - ** is not order-distinct. To be order-distinct is not quite the same as being - ** UNIQUE since a UNIQUE column or index can have multiple rows that - ** are NULL and NULL values are equivalent for the purpose of order-distinct. - ** To be order-distinct, the columns must be UNIQUE and NOT NULL. - ** - ** The rowid for a table is always UNIQUE and NOT NULL so whenever the - ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is - ** automatically order-distinct. - */ - - assert( pOrderBy!=0 ); - if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; - - nOrderBy = pOrderBy->nExpr; - testcase( nOrderBy==BMS-1 ); - if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ - isOrderDistinct = 1; - obDone = MASKBIT(nOrderBy)-1; - orderDistinctMask = 0; - ready = 0; - eqOpMask = WO_EQ | WO_IS | WO_ISNULL; - if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){ - eqOpMask |= WO_IN; - } - for(iLoop=0; isOrderDistinct && obSat0 ) ready |= pLoop->maskSelf; - if( iLoopaLoop[iLoop]; - if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue; - }else{ - pLoop = pLast; - } - if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ - if( pLoop->u.vtab.isOrdered && (wctrlFlags & WHERE_DISTINCTBY)==0 ){ - obSat = obDone; - } - break; - }else if( wctrlFlags & WHERE_DISTINCTBY ){ - pLoop->u.btree.nDistinctCol = 0; - } - iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; - - /* Mark off any ORDER BY term X that is a column in the table of - ** the current loop for which there is term in the WHERE - ** clause of the form X IS NULL or X=? that reference only outer - ** loops. - */ - for(i=0; ia[i].pExpr); - if( pOBExpr->op!=TK_COLUMN ) continue; - if( pOBExpr->iTable!=iCur ) continue; - pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, - ~ready, eqOpMask, 0); - if( pTerm==0 ) continue; - if( pTerm->eOperator==WO_IN ){ - /* IN terms are only valid for sorting in the ORDER BY LIMIT - ** optimization, and then only if they are actually used - ** by the query plan */ - assert( wctrlFlags & - (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ); - for(j=0; jnLTerm && pTerm!=pLoop->aLTerm[j]; j++){} - if( j>=pLoop->nLTerm ) continue; - } - if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ - Parse *pParse = pWInfo->pParse; - CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr); - CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr); - assert( pColl1 ); - if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){ - continue; - } - testcase( pTerm->pExpr->op==TK_IS ); - } - obSat |= MASKBIT(i); - } - - if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ - if( pLoop->wsFlags & WHERE_IPK ){ - pIndex = 0; - nKeyCol = 0; - nColumn = 1; - }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ - return 0; - }else{ - nKeyCol = pIndex->nKeyCol; - nColumn = pIndex->nColumn; - assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); - assert( pIndex->aiColumn[nColumn-1]==XN_ROWID - || !HasRowid(pIndex->pTable)); - isOrderDistinct = IsUniqueIndex(pIndex) - && (pLoop->wsFlags & WHERE_SKIPSCAN)==0; - } - - /* Loop through all columns of the index and deal with the ones - ** that are not constrained by == or IN. - */ - rev = revSet = 0; - distinctColumns = 0; - for(j=0; j=pLoop->u.btree.nEq - || (pLoop->aLTerm[j]==0)==(jnSkip) - ); - if( ju.btree.nEq && j>=pLoop->nSkip ){ - u16 eOp = pLoop->aLTerm[j]->eOperator; - - /* Skip over == and IS and ISNULL terms. (Also skip IN terms when - ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL - ** terms imply that the index is not UNIQUE NOT NULL in which case - ** the loop need to be marked as not order-distinct because it can - ** have repeated NULL rows. - ** - ** If the current term is a column of an ((?,?) IN (SELECT...)) - ** expression for which the SELECT returns more than one column, - ** check that it is the only column used by this loop. Otherwise, - ** if it is one of two or more, none of the columns can be - ** considered to match an ORDER BY term. - */ - if( (eOp & eqOpMask)!=0 ){ - if( eOp & (WO_ISNULL|WO_IS) ){ - testcase( eOp & WO_ISNULL ); - testcase( eOp & WO_IS ); - testcase( isOrderDistinct ); - isOrderDistinct = 0; - } - continue; - }else if( ALWAYS(eOp & WO_IN) ){ - /* ALWAYS() justification: eOp is an equality operator due to the - ** ju.btree.nEq constraint above. Any equality other - ** than WO_IN is captured by the previous "if". So this one - ** always has to be WO_IN. */ - Expr *pX = pLoop->aLTerm[j]->pExpr; - for(i=j+1; iu.btree.nEq; i++){ - if( pLoop->aLTerm[i]->pExpr==pX ){ - assert( (pLoop->aLTerm[i]->eOperator & WO_IN) ); - bOnce = 0; - break; - } - } - } - } - - /* Get the column number in the table (iColumn) and sort order - ** (revIdx) for the j-th column of the index. - */ - if( pIndex ){ - iColumn = pIndex->aiColumn[j]; - revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC; - if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID; - }else{ - iColumn = XN_ROWID; - revIdx = 0; - } - - /* An unconstrained column that might be NULL means that this - ** WhereLoop is not well-ordered - */ - if( isOrderDistinct - && iColumn>=0 - && j>=pLoop->u.btree.nEq - && pIndex->pTable->aCol[iColumn].notNull==0 - ){ - isOrderDistinct = 0; - } - - /* Find the ORDER BY term that corresponds to the j-th column - ** of the index and mark that ORDER BY term off - */ - isMatch = 0; - for(i=0; bOnce && ia[i].pExpr); - testcase( wctrlFlags & WHERE_GROUPBY ); - testcase( wctrlFlags & WHERE_DISTINCTBY ); - if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; - if( iColumn>=XN_ROWID ){ - if( pOBExpr->op!=TK_COLUMN ) continue; - if( pOBExpr->iTable!=iCur ) continue; - if( pOBExpr->iColumn!=iColumn ) continue; - }else{ - Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr; - if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){ - continue; - } - } - if( iColumn!=XN_ROWID ){ - pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); - if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; - } - if( wctrlFlags & WHERE_DISTINCTBY ){ - pLoop->u.btree.nDistinctCol = j+1; - } - isMatch = 1; - break; - } - if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ - /* Make sure the sort order is compatible in an ORDER BY clause. - ** Sort order is irrelevant for a GROUP BY clause. */ - if( revSet ){ - if( (rev ^ revIdx)!=(pOrderBy->a[i].sortFlags&KEYINFO_ORDER_DESC) ){ - isMatch = 0; - } - }else{ - rev = revIdx ^ (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC); - if( rev ) *pRevMask |= MASKBIT(iLoop); - revSet = 1; - } - } - if( isMatch && (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL) ){ - if( j==pLoop->u.btree.nEq ){ - pLoop->wsFlags |= WHERE_BIGNULL_SORT; - }else{ - isMatch = 0; - } - } - if( isMatch ){ - if( iColumn==XN_ROWID ){ - testcase( distinctColumns==0 ); - distinctColumns = 1; - } - obSat |= MASKBIT(i); - }else{ - /* No match found */ - if( j==0 || jmaskSelf; - for(i=0; ia[i].pExpr; - mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); - if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; - if( (mTerm&~orderDistinctMask)==0 ){ - obSat |= MASKBIT(i); - } - } - } - } /* End the loop over all WhereLoops from outer-most down to inner-most */ - if( obSat==obDone ) return (i8)nOrderBy; - if( !isOrderDistinct ){ - for(i=nOrderBy-1; i>0; i--){ - Bitmask m = MASKBIT(i) - 1; - if( (obSat&m)==m ) return i; - } - return 0; - } - return -1; -} - - -/* -** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(), -** the planner assumes that the specified pOrderBy list is actually a GROUP -** BY clause - and so any order that groups rows as required satisfies the -** request. -** -** Normally, in this case it is not possible for the caller to determine -** whether or not the rows are really being delivered in sorted order, or -** just in some other order that provides the required grouping. However, -** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then -** this function may be called on the returned WhereInfo object. It returns -** true if the rows really will be sorted in the specified order, or false -** otherwise. -** -** For example, assuming: -** -** CREATE INDEX i1 ON t1(x, Y); -** -** then -** -** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1 -** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0 -*/ -SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){ - assert( pWInfo->wctrlFlags & WHERE_GROUPBY ); - assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); - return pWInfo->sorted; -} - -#ifdef WHERETRACE_ENABLED -/* For debugging use only: */ -static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ - static char zName[65]; - int i; - for(i=0; iaLoop[i]->cId; } - if( pLast ) zName[i++] = pLast->cId; - zName[i] = 0; - return zName; -} -#endif - -/* -** Return the cost of sorting nRow rows, assuming that the keys have -** nOrderby columns and that the first nSorted columns are already in -** order. -*/ -static LogEst whereSortingCost( - WhereInfo *pWInfo, - LogEst nRow, - int nOrderBy, - int nSorted -){ - /* TUNING: Estimated cost of a full external sort, where N is - ** the number of rows to sort is: - ** - ** cost = (3.0 * N * log(N)). - ** - ** Or, if the order-by clause has X terms but only the last Y - ** terms are out of order, then block-sorting will reduce the - ** sorting cost to: - ** - ** cost = (3.0 * N * log(N)) * (Y/X) - ** - ** The (Y/X) term is implemented using stack variable rScale - ** below. */ - LogEst rScale, rSortCost; - assert( nOrderBy>0 && 66==sqlite3LogEst(100) ); - rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; - rSortCost = nRow + rScale + 16; - - /* Multiple by log(M) where M is the number of output rows. - ** Use the LIMIT for M if it is smaller */ - if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimitiLimit; - } - rSortCost += estLog(nRow); - return rSortCost; -} - -/* -** Given the list of WhereLoop objects at pWInfo->pLoops, this routine -** attempts to find the lowest cost path that visits each WhereLoop -** once. This path is then loaded into the pWInfo->a[].pWLoop fields. -** -** Assume that the total number of output rows that will need to be sorted -** will be nRowEst (in the 10*log2 representation). Or, ignore sorting -** costs if nRowEst==0. -** -** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation -** error occurs. -*/ -static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ - int mxChoice; /* Maximum number of simultaneous paths tracked */ - int nLoop; /* Number of terms in the join */ - Parse *pParse; /* Parsing context */ - sqlite3 *db; /* The database connection */ - int iLoop; /* Loop counter over the terms of the join */ - int ii, jj; /* Loop counters */ - int mxI = 0; /* Index of next entry to replace */ - int nOrderBy; /* Number of ORDER BY clause terms */ - LogEst mxCost = 0; /* Maximum cost of a set of paths */ - LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */ - int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ - WherePath *aFrom; /* All nFrom paths at the previous level */ - WherePath *aTo; /* The nTo best paths at the current level */ - WherePath *pFrom; /* An element of aFrom[] that we are working on */ - WherePath *pTo; /* An element of aTo[] that we are working on */ - WhereLoop *pWLoop; /* One of the WhereLoop objects */ - WhereLoop **pX; /* Used to divy up the pSpace memory */ - LogEst *aSortCost = 0; /* Sorting and partial sorting costs */ - char *pSpace; /* Temporary memory used by this routine */ - int nSpace; /* Bytes of space allocated at pSpace */ - - pParse = pWInfo->pParse; - db = pParse->db; - nLoop = pWInfo->nLevel; - /* TUNING: For simple queries, only the best path is tracked. - ** For 2-way joins, the 5 best paths are followed. - ** For joins of 3 or more tables, track the 10 best paths */ - mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10); - assert( nLoop<=pWInfo->pTabList->nSrc ); - WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst)); - - /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this - ** case the purpose of this call is to estimate the number of rows returned - ** by the overall query. Once this estimate has been obtained, the caller - ** will invoke this function a second time, passing the estimate as the - ** nRowEst parameter. */ - if( pWInfo->pOrderBy==0 || nRowEst==0 ){ - nOrderBy = 0; - }else{ - nOrderBy = pWInfo->pOrderBy->nExpr; - } - - /* Allocate and initialize space for aTo, aFrom and aSortCost[] */ - nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; - nSpace += sizeof(LogEst) * nOrderBy; - pSpace = sqlite3DbMallocRawNN(db, nSpace); - if( pSpace==0 ) return SQLITE_NOMEM_BKPT; - aTo = (WherePath*)pSpace; - aFrom = aTo+mxChoice; - memset(aFrom, 0, sizeof(aFrom[0])); - pX = (WhereLoop**)(aFrom+mxChoice); - for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ - pFrom->aLoop = pX; - } - if( nOrderBy ){ - /* If there is an ORDER BY clause and it is not being ignored, set up - ** space for the aSortCost[] array. Each element of the aSortCost array - ** is either zero - meaning it has not yet been initialized - or the - ** cost of sorting nRowEst rows of data where the first X terms of - ** the ORDER BY clause are already in order, where X is the array - ** index. */ - aSortCost = (LogEst*)pX; - memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); - } - assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); - assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); - - /* Seed the search with a single WherePath containing zero WhereLoops. - ** - ** TUNING: Do not let the number of iterations go above 28. If the cost - ** of computing an automatic index is not paid back within the first 28 - ** rows, then do not use the automatic index. */ - aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) ); - nFrom = 1; - assert( aFrom[0].isOrdered==0 ); - if( nOrderBy ){ - /* If nLoop is zero, then there are no FROM terms in the query. Since - ** in this case the query may return a maximum of one row, the results - ** are already in the requested order. Set isOrdered to nOrderBy to - ** indicate this. Or, if nLoop is greater than zero, set isOrdered to - ** -1, indicating that the result set may or may not be ordered, - ** depending on the loops added to the current plan. */ - aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; - } - - /* Compute successively longer WherePaths using the previous generation - ** of WherePaths as the basis for the next. Keep track of the mxChoice - ** best paths at each generation */ - for(iLoop=0; iLooppLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ - LogEst nOut; /* Rows visited by (pFrom+pWLoop) */ - LogEst rCost; /* Cost of path (pFrom+pWLoop) */ - LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */ - i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */ - Bitmask maskNew; /* Mask of src visited by (..) */ - Bitmask revMask = 0; /* Mask of rev-order loops for (..) */ - - if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; - if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; - if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){ - /* Do not use an automatic index if the this loop is expected - ** to run less than 1.25 times. It is tempting to also exclude - ** automatic index usage on an outer loop, but sometimes an automatic - ** index is useful in the outer loop of a correlated subquery. */ - assert( 10==sqlite3LogEst(2) ); - continue; - } - - /* At this point, pWLoop is a candidate to be the next loop. - ** Compute its cost */ - rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); - rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); - nOut = pFrom->nRow + pWLoop->nOut; - maskNew = pFrom->maskLoop | pWLoop->maskSelf; - if( isOrdered<0 ){ - isOrdered = wherePathSatisfiesOrderBy(pWInfo, - pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, - iLoop, pWLoop, &revMask); - }else{ - revMask = pFrom->revLoop; - } - if( isOrdered>=0 && isOrderedisOrdered^isOrdered)&0x80)==0" is equivalent - ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range - ** of legal values for isOrdered, -1..64. - */ - for(jj=0, pTo=aTo; jjmaskLoop==maskNew - && ((pTo->isOrdered^isOrdered)&0x80)==0 - ){ - testcase( jj==nTo-1 ); - break; - } - } - if( jj>=nTo ){ - /* None of the existing best-so-far paths match the candidate. */ - if( nTo>=mxChoice - && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted)) - ){ - /* The current candidate is no better than any of the mxChoice - ** paths currently in the best-so-far buffer. So discard - ** this candidate as not viable. */ -#ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, - isOrdered>=0 ? isOrdered+'0' : '?'); - } -#endif - continue; - } - /* If we reach this points it means that the new candidate path - ** needs to be added to the set of best-so-far paths. */ - if( nTo=0 ? isOrdered+'0' : '?'); - } -#endif - }else{ - /* Control reaches here if best-so-far path pTo=aTo[jj] covers the - ** same set of loops and has the same isOrdered setting as the - ** candidate path. Check to see if the candidate should replace - ** pTo or if the candidate should be skipped. - ** - ** The conditional is an expanded vector comparison equivalent to: - ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted) - */ - if( pTo->rCostrCost==rCost - && (pTo->nRownRow==nOut && pTo->rUnsorted<=rUnsorted) - ) - ) - ){ -#ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - sqlite3DebugPrintf( - "Skip %s cost=%-3d,%3d,%3d order=%c", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, - isOrdered>=0 ? isOrdered+'0' : '?'); - sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n", - wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, - pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); - } -#endif - /* Discard the candidate path from further consideration */ - testcase( pTo->rCost==rCost ); - continue; - } - testcase( pTo->rCost==rCost+1 ); - /* Control reaches here if the candidate path is better than the - ** pTo path. Replace pTo with the candidate. */ -#ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - sqlite3DebugPrintf( - "Update %s cost=%-3d,%3d,%3d order=%c", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, - isOrdered>=0 ? isOrdered+'0' : '?'); - sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n", - wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, - pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); - } -#endif - } - /* pWLoop is a winner. Add it to the set of best so far */ - pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; - pTo->revLoop = revMask; - pTo->nRow = nOut; - pTo->rCost = rCost; - pTo->rUnsorted = rUnsorted; - pTo->isOrdered = isOrdered; - memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); - pTo->aLoop[iLoop] = pWLoop; - if( nTo>=mxChoice ){ - mxI = 0; - mxCost = aTo[0].rCost; - mxUnsorted = aTo[0].nRow; - for(jj=1, pTo=&aTo[1]; jjrCost>mxCost - || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) - ){ - mxCost = pTo->rCost; - mxUnsorted = pTo->rUnsorted; - mxI = jj; - } - } - } - } - } - -#ifdef WHERETRACE_ENABLED /* >=2 */ - if( sqlite3WhereTrace & 0x02 ){ - sqlite3DebugPrintf("---- after round %d ----\n", iLoop); - for(ii=0, pTo=aTo; iirCost, pTo->nRow, - pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); - if( pTo->isOrdered>0 ){ - sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); - }else{ - sqlite3DebugPrintf("\n"); - } - } - } -#endif - - /* Swap the roles of aFrom and aTo for the next generation */ - pFrom = aTo; - aTo = aFrom; - aFrom = pFrom; - nFrom = nTo; - } - - if( nFrom==0 ){ - sqlite3ErrorMsg(pParse, "no query solution"); - sqlite3DbFreeNN(db, pSpace); - return SQLITE_ERROR; - } - - /* Find the lowest cost path. pFrom will be left pointing to that path */ - pFrom = aFrom; - for(ii=1; iirCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; - } - assert( pWInfo->nLevel==nLoop ); - /* Load the lowest cost path into pWInfo */ - for(iLoop=0; iLoopa + iLoop; - pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; - pLevel->iFrom = pWLoop->iTab; - pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; - } - if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 - && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 - && pWInfo->eDistinct==WHERE_DISTINCT_NOOP - && nRowEst - ){ - Bitmask notUsed; - int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom, - WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); - if( rc==pWInfo->pResultSet->nExpr ){ - pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; - } - } - pWInfo->bOrderedInnerLoop = 0; - if( pWInfo->pOrderBy ){ - if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ - if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ - pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; - } - }else{ - pWInfo->nOBSat = pFrom->isOrdered; - pWInfo->revMask = pFrom->revLoop; - if( pWInfo->nOBSat<=0 ){ - pWInfo->nOBSat = 0; - if( nLoop>0 ){ - u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags; - if( (wsFlags & WHERE_ONEROW)==0 - && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN) - ){ - Bitmask m = 0; - int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, - WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m); - testcase( wsFlags & WHERE_IPK ); - testcase( wsFlags & WHERE_COLUMN_IN ); - if( rc==pWInfo->pOrderBy->nExpr ){ - pWInfo->bOrderedInnerLoop = 1; - pWInfo->revMask = m; - } - } - } - }else if( nLoop - && pWInfo->nOBSat==1 - && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0 - ){ - pWInfo->bOrderedInnerLoop = 1; - } - } - if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) - && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0 - ){ - Bitmask revMask = 0; - int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, - pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask - ); - assert( pWInfo->sorted==0 ); - if( nOrder==pWInfo->pOrderBy->nExpr ){ - pWInfo->sorted = 1; - pWInfo->revMask = revMask; - } - } - } - - - pWInfo->nRowOut = pFrom->nRow; - - /* Free temporary memory and return success */ - sqlite3DbFreeNN(db, pSpace); - return SQLITE_OK; -} - -/* -** Most queries use only a single table (they are not joins) and have -** simple == constraints against indexed fields. This routine attempts -** to plan those simple cases using much less ceremony than the -** general-purpose query planner, and thereby yield faster sqlite3_prepare() -** times for the common case. -** -** Return non-zero on success, if this query can be handled by this -** no-frills query planner. Return zero if this query needs the -** general-purpose query planner. -*/ -static int whereShortCut(WhereLoopBuilder *pBuilder){ - WhereInfo *pWInfo; - struct SrcList_item *pItem; - WhereClause *pWC; - WhereTerm *pTerm; - WhereLoop *pLoop; - int iCur; - int j; - Table *pTab; - Index *pIdx; - - pWInfo = pBuilder->pWInfo; - if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0; - assert( pWInfo->pTabList->nSrc>=1 ); - pItem = pWInfo->pTabList->a; - pTab = pItem->pTab; - if( IsVirtual(pTab) ) return 0; - if( pItem->fg.isIndexedBy ) return 0; - iCur = pItem->iCursor; - pWC = &pWInfo->sWC; - pLoop = pBuilder->pNew; - pLoop->wsFlags = 0; - pLoop->nSkip = 0; - pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0); - if( pTerm ){ - testcase( pTerm->eOperator & WO_IS ); - pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; - pLoop->aLTerm[0] = pTerm; - pLoop->nLTerm = 1; - pLoop->u.btree.nEq = 1; - /* TUNING: Cost of a rowid lookup is 10 */ - pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ - }else{ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - int opMask; - assert( pLoop->aLTermSpace==pLoop->aLTerm ); - if( !IsUniqueIndex(pIdx) - || pIdx->pPartIdxWhere!=0 - || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) - ) continue; - opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ; - for(j=0; jnKeyCol; j++){ - pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx); - if( pTerm==0 ) break; - testcase( pTerm->eOperator & WO_IS ); - pLoop->aLTerm[j] = pTerm; - } - if( j!=pIdx->nKeyCol ) continue; - pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; - if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){ - pLoop->wsFlags |= WHERE_IDX_ONLY; - } - pLoop->nLTerm = j; - pLoop->u.btree.nEq = j; - pLoop->u.btree.pIndex = pIdx; - /* TUNING: Cost of a unique index lookup is 15 */ - pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ - break; - } - } - if( pLoop->wsFlags ){ - pLoop->nOut = (LogEst)1; - pWInfo->a[0].pWLoop = pLoop; - assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] ); - pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */ - pWInfo->a[0].iTabCur = iCur; - pWInfo->nRowOut = 1; - if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; - if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ - pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; - } -#ifdef SQLITE_DEBUG - pLoop->cId = '0'; -#endif - return 1; - } - return 0; -} - -/* -** Helper function for exprIsDeterministic(). -*/ -static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){ - pWalker->eCode = 0; - return WRC_Abort; - } - return WRC_Continue; -} - -/* -** Return true if the expression contains no non-deterministic SQL -** functions. Do not consider non-deterministic SQL functions that are -** part of sub-select statements. -*/ -static int exprIsDeterministic(Expr *p){ - Walker w; - memset(&w, 0, sizeof(w)); - w.eCode = 1; - w.xExprCallback = exprNodeIsDeterministic; - w.xSelectCallback = sqlite3SelectWalkFail; - sqlite3WalkExpr(&w, p); - return w.eCode; -} - - -#ifdef WHERETRACE_ENABLED -/* -** Display all WhereLoops in pWInfo -*/ -static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){ - if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ - WhereLoop *p; - int i; - static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" - "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; - for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ - p->cId = zLabel[i%(sizeof(zLabel)-1)]; - sqlite3WhereLoopPrint(p, pWC); - } - } -} -# define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C) -#else -# define WHERETRACE_ALL_LOOPS(W,C) -#endif - -/* -** Generate the beginning of the loop used for WHERE clause processing. -** The return value is a pointer to an opaque structure that contains -** information needed to terminate the loop. Later, the calling routine -** should invoke sqlite3WhereEnd() with the return value of this function -** in order to complete the WHERE clause processing. -** -** If an error occurs, this routine returns NULL. -** -** The basic idea is to do a nested loop, one loop for each table in -** the FROM clause of a select. (INSERT and UPDATE statements are the -** same as a SELECT with only a single table in the FROM clause.) For -** example, if the SQL is this: -** -** SELECT * FROM t1, t2, t3 WHERE ...; -** -** Then the code generated is conceptually like the following: -** -** foreach row1 in t1 do \ Code generated -** foreach row2 in t2 do |-- by sqlite3WhereBegin() -** foreach row3 in t3 do / -** ... -** end \ Code generated -** end |-- by sqlite3WhereEnd() -** end / -** -** Note that the loops might not be nested in the order in which they -** appear in the FROM clause if a different order is better able to make -** use of indices. Note also that when the IN operator appears in -** the WHERE clause, it might result in additional nested loops for -** scanning through all values on the right-hand side of the IN. -** -** There are Btree cursors associated with each table. t1 uses cursor -** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. -** And so forth. This routine generates code to open those VDBE cursors -** and sqlite3WhereEnd() generates the code to close them. -** -** The code that sqlite3WhereBegin() generates leaves the cursors named -** in pTabList pointing at their appropriate entries. The [...] code -** can use OP_Column and OP_Rowid opcodes on these cursors to extract -** data from the various tables of the loop. -** -** If the WHERE clause is empty, the foreach loops must each scan their -** entire tables. Thus a three-way join is an O(N^3) operation. But if -** the tables have indices and there are terms in the WHERE clause that -** refer to those indices, a complete table scan can be avoided and the -** code will run much faster. Most of the work of this routine is checking -** to see if there are indices that can be used to speed up the loop. -** -** Terms of the WHERE clause are also used to limit which rows actually -** make it to the "..." in the middle of the loop. After each "foreach", -** terms of the WHERE clause that use only terms in that loop and outer -** loops are evaluated and if false a jump is made around all subsequent -** inner loops (or around the "..." if the test occurs within the inner- -** most loop) -** -** OUTER JOINS -** -** An outer join of tables t1 and t2 is conceptally coded as follows: -** -** foreach row1 in t1 do -** flag = 0 -** foreach row2 in t2 do -** start: -** ... -** flag = 1 -** end -** if flag==0 then -** move the row2 cursor to a null row -** goto start -** fi -** end -** -** ORDER BY CLAUSE PROCESSING -** -** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause -** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement -** if there is one. If there is no ORDER BY clause or if this routine -** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. -** -** The iIdxCur parameter is the cursor number of an index. If -** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index -** to use for OR clause processing. The WHERE clause should use this -** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is -** the first cursor in an array of cursors for all indices. iIdxCur should -** be used to compute the appropriate cursor depending on which index is -** used. -*/ -SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( - Parse *pParse, /* The parser context */ - SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ - Expr *pWhere, /* The WHERE clause */ - ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ - ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */ - u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */ - int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number - ** If WHERE_USE_LIMIT, then the limit amount */ -){ - int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ - int nTabList; /* Number of elements in pTabList */ - WhereInfo *pWInfo; /* Will become the return value of this function */ - Vdbe *v = pParse->pVdbe; /* The virtual database engine */ - Bitmask notReady; /* Cursors that are not yet positioned */ - WhereLoopBuilder sWLB; /* The WhereLoop builder */ - WhereMaskSet *pMaskSet; /* The expression mask set */ - WhereLevel *pLevel; /* A single level in pWInfo->a[] */ - WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ - int ii; /* Loop counter */ - sqlite3 *db; /* Database connection */ - int rc; /* Return code */ - u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */ - - assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || ( - (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 - && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 - )); - - /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */ - assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 - || (wctrlFlags & WHERE_USE_LIMIT)==0 ); - - /* Variable initialization */ - db = pParse->db; - memset(&sWLB, 0, sizeof(sWLB)); - - /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ - testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); - if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; - sWLB.pOrderBy = pOrderBy; - - /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via - ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ - if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ - wctrlFlags &= ~WHERE_WANT_DISTINCT; - } - - /* The number of tables in the FROM clause is limited by the number of - ** bits in a Bitmask - */ - testcase( pTabList->nSrc==BMS ); - if( pTabList->nSrc>BMS ){ - sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); - return 0; - } - - /* This function normally generates a nested loop for all tables in - ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should - ** only generate code for the first table in pTabList and assume that - ** any cursors associated with subsequent tables are uninitialized. - */ - nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc; - - /* Allocate and initialize the WhereInfo structure that will become the - ** return value. A single allocation is used to store the WhereInfo - ** struct, the contents of WhereInfo.a[], the WhereClause structure - ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte - ** field (type Bitmask) it must be aligned on an 8-byte boundary on - ** some architectures. Hence the ROUND8() below. - */ - nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); - pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); - if( db->mallocFailed ){ - sqlite3DbFree(db, pWInfo); - pWInfo = 0; - goto whereBeginError; - } - pWInfo->pParse = pParse; - pWInfo->pTabList = pTabList; - pWInfo->pOrderBy = pOrderBy; - pWInfo->pWhere = pWhere; - pWInfo->pResultSet = pResultSet; - pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; - pWInfo->nLevel = nTabList; - pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse); - pWInfo->wctrlFlags = wctrlFlags; - pWInfo->iLimit = iAuxArg; - pWInfo->savedNQueryLoop = pParse->nQueryLoop; - memset(&pWInfo->nOBSat, 0, - offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat)); - memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel)); - assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */ - pMaskSet = &pWInfo->sMaskSet; - sWLB.pWInfo = pWInfo; - sWLB.pWC = &pWInfo->sWC; - sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); - assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); - whereLoopInit(sWLB.pNew); -#ifdef SQLITE_DEBUG - sWLB.pNew->cId = '*'; -#endif - - /* Split the WHERE clause into separate subexpressions where each - ** subexpression is separated by an AND operator. - */ - initMaskSet(pMaskSet); - sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); - sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); - - /* Special case: No FROM clause - */ - if( nTabList==0 ){ - if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; - if( wctrlFlags & WHERE_WANT_DISTINCT ){ - pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; - } - ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW")); - }else{ - /* Assign a bit from the bitmask to every term in the FROM clause. - ** - ** The N-th term of the FROM clause is assigned a bitmask of 1<nSrc tables in - ** pTabList, not just the first nTabList tables. nTabList is normally - ** equal to pTabList->nSrc but might be shortened to 1 if the - ** WHERE_OR_SUBCLAUSE flag is set. - */ - ii = 0; - do{ - createMask(pMaskSet, pTabList->a[ii].iCursor); - sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); - }while( (++ii)nSrc ); - #ifdef SQLITE_DEBUG - { - Bitmask mx = 0; - for(ii=0; iinSrc; ii++){ - Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); - assert( m>=mx ); - mx = m; - } - } - #endif - } - - /* Analyze all of the subexpressions. */ - sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); - if( db->mallocFailed ) goto whereBeginError; - - /* Special case: WHERE terms that do not refer to any tables in the join - ** (constant expressions). Evaluate each such term, and jump over all the - ** generated code if the result is not true. - ** - ** Do not do this if the expression contains non-deterministic functions - ** that are not within a sub-select. This is not strictly required, but - ** preserves SQLite's legacy behaviour in the following two cases: - ** - ** FROM ... WHERE random()>0; -- eval random() once per row - ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall - */ - for(ii=0; iinTerm; ii++){ - WhereTerm *pT = &sWLB.pWC->a[ii]; - if( pT->wtFlags & TERM_VIRTUAL ) continue; - if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){ - sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL); - pT->wtFlags |= TERM_CODED; - } - } - - if( wctrlFlags & WHERE_WANT_DISTINCT ){ - if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ - /* The DISTINCT marking is pointless. Ignore it. */ - pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; - }else if( pOrderBy==0 ){ - /* Try to ORDER BY the result set to make distinct processing easier */ - pWInfo->wctrlFlags |= WHERE_DISTINCTBY; - pWInfo->pOrderBy = pResultSet; - } - } - - /* Construct the WhereLoop objects */ -#if defined(WHERETRACE_ENABLED) - if( sqlite3WhereTrace & 0xffff ){ - sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); - if( wctrlFlags & WHERE_USE_LIMIT ){ - sqlite3DebugPrintf(", limit: %d", iAuxArg); - } - sqlite3DebugPrintf(")\n"); - if( sqlite3WhereTrace & 0x100 ){ - Select sSelect; - memset(&sSelect, 0, sizeof(sSelect)); - sSelect.selFlags = SF_WhereBegin; - sSelect.pSrc = pTabList; - sSelect.pWhere = pWhere; - sSelect.pOrderBy = pOrderBy; - sSelect.pEList = pResultSet; - sqlite3TreeViewSelect(0, &sSelect, 0); - } - } - if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ - sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n"); - sqlite3WhereClausePrint(sWLB.pWC); - } -#endif - - if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ - rc = whereLoopAddAll(&sWLB); - if( rc ) goto whereBeginError; - -#ifdef SQLITE_ENABLE_STAT4 - /* If one or more WhereTerm.truthProb values were used in estimating - ** loop parameters, but then those truthProb values were subsequently - ** changed based on STAT4 information while computing subsequent loops, - ** then we need to rerun the whole loop building process so that all - ** loops will be built using the revised truthProb values. */ - if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){ - WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC); - WHERETRACE(0xffff, - ("**** Redo all loop computations due to" - " TERM_HIGHTRUTH changes ****\n")); - while( pWInfo->pLoops ){ - WhereLoop *p = pWInfo->pLoops; - pWInfo->pLoops = p->pNextLoop; - whereLoopDelete(db, p); - } - rc = whereLoopAddAll(&sWLB); - if( rc ) goto whereBeginError; - } -#endif - WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC); - - wherePathSolver(pWInfo, 0); - if( db->mallocFailed ) goto whereBeginError; - if( pWInfo->pOrderBy ){ - wherePathSolver(pWInfo, pWInfo->nRowOut+1); - if( db->mallocFailed ) goto whereBeginError; - } - } - if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ - pWInfo->revMask = ALLBITS; - } - if( pParse->nErr || NEVER(db->mallocFailed) ){ - goto whereBeginError; - } -#ifdef WHERETRACE_ENABLED - if( sqlite3WhereTrace ){ - sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); - if( pWInfo->nOBSat>0 ){ - sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); - } - switch( pWInfo->eDistinct ){ - case WHERE_DISTINCT_UNIQUE: { - sqlite3DebugPrintf(" DISTINCT=unique"); - break; - } - case WHERE_DISTINCT_ORDERED: { - sqlite3DebugPrintf(" DISTINCT=ordered"); - break; - } - case WHERE_DISTINCT_UNORDERED: { - sqlite3DebugPrintf(" DISTINCT=unordered"); - break; - } - } - sqlite3DebugPrintf("\n"); - for(ii=0; iinLevel; ii++){ - sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); - } - } -#endif - - /* Attempt to omit tables from the join that do not affect the result. - ** For a table to not affect the result, the following must be true: - ** - ** 1) The query must not be an aggregate. - ** 2) The table must be the RHS of a LEFT JOIN. - ** 3) Either the query must be DISTINCT, or else the ON or USING clause - ** must contain a constraint that limits the scan of the table to - ** at most a single row. - ** 4) The table must not be referenced by any part of the query apart - ** from its own USING or ON clause. - ** - ** For example, given: - ** - ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1); - ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2); - ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3); - ** - ** then table t2 can be omitted from the following: - ** - ** SELECT v1, v3 FROM t1 - ** LEFT JOIN t2 ON (t1.ipk=t2.ipk) - ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) - ** - ** or from: - ** - ** SELECT DISTINCT v1, v3 FROM t1 - ** LEFT JOIN t2 - ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) - */ - notReady = ~(Bitmask)0; - if( pWInfo->nLevel>=2 - && pResultSet!=0 /* guarantees condition (1) above */ - && OptimizationEnabled(db, SQLITE_OmitNoopJoin) - ){ - int i; - Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet); - if( sWLB.pOrderBy ){ - tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); - } - for(i=pWInfo->nLevel-1; i>=1; i--){ - WhereTerm *pTerm, *pEnd; - struct SrcList_item *pItem; - pLoop = pWInfo->a[i].pWLoop; - pItem = &pWInfo->pTabList->a[pLoop->iTab]; - if( (pItem->fg.jointype & JT_LEFT)==0 ) continue; - if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 - && (pLoop->wsFlags & WHERE_ONEROW)==0 - ){ - continue; - } - if( (tabUsed & pLoop->maskSelf)!=0 ) continue; - pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; - for(pTerm=sWLB.pWC->a; pTermprereqAll & pLoop->maskSelf)!=0 ){ - if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - || pTerm->pExpr->iRightJoinTable!=pItem->iCursor - ){ - break; - } - } - } - if( pTerm drop loop %c not used\n", pLoop->cId)); - notReady &= ~pLoop->maskSelf; - for(pTerm=sWLB.pWC->a; pTermprereqAll & pLoop->maskSelf)!=0 ){ - pTerm->wtFlags |= TERM_CODED; - } - } - if( i!=pWInfo->nLevel-1 ){ - int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel); - memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte); - } - pWInfo->nLevel--; - nTabList--; - } - } -#if defined(WHERETRACE_ENABLED) - if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ - sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n"); - sqlite3WhereClausePrint(sWLB.pWC); - } - WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); -#endif - pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; - - /* If the caller is an UPDATE or DELETE statement that is requesting - ** to use a one-pass algorithm, determine if this is appropriate. - ** - ** A one-pass approach can be used if the caller has requested one - ** and either (a) the scan visits at most one row or (b) each - ** of the following are true: - ** - ** * the caller has indicated that a one-pass approach can be used - ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and - ** * the table is not a virtual table, and - ** * either the scan does not use the OR optimization or the caller - ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified - ** for DELETE). - ** - ** The last qualification is because an UPDATE statement uses - ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can - ** use a one-pass approach, and this is not set accurately for scans - ** that use the OR optimization. - */ - assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); - if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){ - int wsFlags = pWInfo->a[0].pWLoop->wsFlags; - int bOnerow = (wsFlags & WHERE_ONEROW)!=0; - assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) ); - if( bOnerow || ( - 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW) - && !IsVirtual(pTabList->a[0].pTab) - && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK)) - )){ - pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI; - if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){ - if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){ - bFordelete = OPFLAG_FORDELETE; - } - pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY); - } - } - } - - /* Open all tables in the pTabList and any indices selected for - ** searching those tables. - */ - for(ii=0, pLevel=pWInfo->a; iia[pLevel->iFrom]; - pTab = pTabItem->pTab; - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - pLoop = pLevel->pWLoop; - if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ - /* Do nothing */ - }else -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ - const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); - int iCur = pTabItem->iCursor; - sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); - }else if( IsVirtual(pTab) ){ - /* noop */ - }else -#endif - if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 - && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ - int op = OP_OpenRead; - if( pWInfo->eOnePass!=ONEPASS_OFF ){ - op = OP_OpenWrite; - pWInfo->aiCurOnePass[0] = pTabItem->iCursor; - }; - sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); - assert( pTabItem->iCursor==pLevel->iTabCur ); - testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 ); - testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS ); - if( pWInfo->eOnePass==ONEPASS_OFF - && pTab->nColtabFlags & (TF_HasGenerated|TF_WithoutRowid))==0 - ){ - /* If we know that only a prefix of the record will be used, - ** it is advantageous to reduce the "column count" field in - ** the P4 operand of the OP_OpenRead/Write opcode. */ - Bitmask b = pTabItem->colUsed; - int n = 0; - for(; b; b=b>>1, n++){} - sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32); - assert( n<=pTab->nCol ); - } -#ifdef SQLITE_ENABLE_CURSOR_HINTS - if( pLoop->u.btree.pIndex!=0 ){ - sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); - }else -#endif - { - sqlite3VdbeChangeP5(v, bFordelete); - } -#ifdef SQLITE_ENABLE_COLUMN_USED_MASK - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, - (const u8*)&pTabItem->colUsed, P4_INT64); -#endif - }else{ - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); - } - if( pLoop->wsFlags & WHERE_INDEXED ){ - Index *pIx = pLoop->u.btree.pIndex; - int iIndexCur; - int op = OP_OpenRead; - /* iAuxArg is always set to a positive value if ONEPASS is possible */ - assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); - if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) - && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 - ){ - /* This is one term of an OR-optimization using the PRIMARY KEY of a - ** WITHOUT ROWID table. No need for a separate index */ - iIndexCur = pLevel->iTabCur; - op = 0; - }else if( pWInfo->eOnePass!=ONEPASS_OFF ){ - Index *pJ = pTabItem->pTab->pIndex; - iIndexCur = iAuxArg; - assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); - while( ALWAYS(pJ) && pJ!=pIx ){ - iIndexCur++; - pJ = pJ->pNext; - } - op = OP_OpenWrite; - pWInfo->aiCurOnePass[1] = iIndexCur; - }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ - iIndexCur = iAuxArg; - op = OP_ReopenIdx; - }else{ - iIndexCur = pParse->nTab++; - } - pLevel->iIdxCur = iIndexCur; - assert( pIx->pSchema==pTab->pSchema ); - assert( iIndexCur>=0 ); - if( op ){ - sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); - sqlite3VdbeSetP4KeyInfo(pParse, pIx); - if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0 - && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0 - && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0 - && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 - && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED - ){ - sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); - } - VdbeComment((v, "%s", pIx->zName)); -#ifdef SQLITE_ENABLE_COLUMN_USED_MASK - { - u64 colUsed = 0; - int ii, jj; - for(ii=0; iinColumn; ii++){ - jj = pIx->aiColumn[ii]; - if( jj<0 ) continue; - if( jj>63 ) jj = 63; - if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; - colUsed |= ((u64)1)<<(ii<63 ? ii : 63); - } - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, - (u8*)&colUsed, P4_INT64); - } -#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ - } - } - if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); - } - pWInfo->iTop = sqlite3VdbeCurrentAddr(v); - if( db->mallocFailed ) goto whereBeginError; - - /* Generate the code to do the search. Each iteration of the for - ** loop below generates code for a single nested loop of the VM - ** program. - */ - for(ii=0; iia[ii]; - wsFlags = pLevel->pWLoop->wsFlags; -#ifndef SQLITE_OMIT_AUTOMATIC_INDEX - if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ - constructAutomaticIndex(pParse, &pWInfo->sWC, - &pTabList->a[pLevel->iFrom], notReady, pLevel); - if( db->mallocFailed ) goto whereBeginError; - } -#endif - addrExplain = sqlite3WhereExplainOneScan( - pParse, pTabList, pLevel, wctrlFlags - ); - pLevel->addrBody = sqlite3VdbeCurrentAddr(v); - notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady); - pWInfo->iContinue = pLevel->addrCont; - if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){ - sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); - } - } - - /* Done. */ - VdbeModuleComment((v, "Begin WHERE-core")); - return pWInfo; - - /* Jump here if malloc fails */ -whereBeginError: - if( pWInfo ){ - pParse->nQueryLoop = pWInfo->savedNQueryLoop; - whereInfoFree(db, pWInfo); - } - return 0; -} - -/* -** Part of sqlite3WhereEnd() will rewrite opcodes to reference the -** index rather than the main table. In SQLITE_DEBUG mode, we want -** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine -** does that. -*/ -#ifndef SQLITE_DEBUG -# define OpcodeRewriteTrace(D,K,P) /* no-op */ -#else -# define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P) - static void sqlite3WhereOpcodeRewriteTrace( - sqlite3 *db, - int pc, - VdbeOp *pOp - ){ - if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return; - sqlite3VdbePrintOp(0, pc, pOp); - } -#endif - -/* -** Generate the end of the WHERE loop. See comments on -** sqlite3WhereBegin() for additional information. -*/ -SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ - Parse *pParse = pWInfo->pParse; - Vdbe *v = pParse->pVdbe; - int i; - WhereLevel *pLevel; - WhereLoop *pLoop; - SrcList *pTabList = pWInfo->pTabList; - sqlite3 *db = pParse->db; - - /* Generate loop termination code. - */ - VdbeModuleComment((v, "End WHERE-core")); - for(i=pWInfo->nLevel-1; i>=0; i--){ - int addr; - pLevel = &pWInfo->a[i]; - pLoop = pLevel->pWLoop; - if( pLevel->op!=OP_Noop ){ -#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT - int addrSeek = 0; - Index *pIdx; - int n; - if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED - && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */ - && (pLoop->wsFlags & WHERE_INDEXED)!=0 - && (pIdx = pLoop->u.btree.pIndex)->hasStat1 - && (n = pLoop->u.btree.nDistinctCol)>0 - && pIdx->aiRowLogEst[n]>=36 - ){ - int r1 = pParse->nMem+1; - int j, op; - for(j=0; jiIdxCur, j, r1+j); - } - pParse->nMem += n+1; - op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT; - addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n); - VdbeCoverageIf(v, op==OP_SeekLT); - VdbeCoverageIf(v, op==OP_SeekGT); - sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2); - } -#endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */ - /* The common case: Advance to the next row */ - sqlite3VdbeResolveLabel(v, pLevel->addrCont); - sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); - sqlite3VdbeChangeP5(v, pLevel->p5); - VdbeCoverage(v); - VdbeCoverageIf(v, pLevel->op==OP_Next); - VdbeCoverageIf(v, pLevel->op==OP_Prev); - VdbeCoverageIf(v, pLevel->op==OP_VNext); - if( pLevel->regBignull ){ - sqlite3VdbeResolveLabel(v, pLevel->addrBignull); - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1); - VdbeCoverage(v); - } -#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT - if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek); -#endif - }else{ - sqlite3VdbeResolveLabel(v, pLevel->addrCont); - } - if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ - struct InLoop *pIn; - int j; - sqlite3VdbeResolveLabel(v, pLevel->addrNxt); - for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ - sqlite3VdbeJumpHere(v, pIn->addrInTop+1); - if( pIn->eEndLoopOp!=OP_Noop ){ - if( pIn->nPrefix ){ - assert( pLoop->wsFlags & WHERE_IN_EARLYOUT ); - if( pLevel->iLeftJoin ){ - /* For LEFT JOIN queries, cursor pIn->iCur may not have been - ** opened yet. This occurs for WHERE clauses such as - ** "a = ? AND b IN (...)", where the index is on (a, b). If - ** the RHS of the (a=?) is NULL, then the "b IN (...)" may - ** never have been coded, but the body of the loop run to - ** return the null-row. So, if the cursor is not open yet, - ** jump over the OP_Next or OP_Prev instruction about to - ** be coded. */ - sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur, - sqlite3VdbeCurrentAddr(v) + 2 + - ((pLoop->wsFlags & WHERE_VIRTUALTABLE)==0) - ); - VdbeCoverage(v); - } - if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){ - sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur, - sqlite3VdbeCurrentAddr(v)+2, - pIn->iBase, pIn->nPrefix); - VdbeCoverage(v); - } - } - sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); - VdbeCoverage(v); - VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev); - VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next); - } - sqlite3VdbeJumpHere(v, pIn->addrInTop-1); - } - } - sqlite3VdbeResolveLabel(v, pLevel->addrBrk); - if( pLevel->addrSkip ){ - sqlite3VdbeGoto(v, pLevel->addrSkip); - VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); - sqlite3VdbeJumpHere(v, pLevel->addrSkip); - sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); - } -#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS - if( pLevel->addrLikeRep ){ - sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), - pLevel->addrLikeRep); - VdbeCoverage(v); - } -#endif - if( pLevel->iLeftJoin ){ - int ws = pLoop->wsFlags; - addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); - assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 ); - if( (ws & WHERE_IDX_ONLY)==0 ){ - assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor ); - sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur); - } - if( (ws & WHERE_INDEXED) - || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) - ){ - sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); - } - if( pLevel->op==OP_Return ){ - sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); - }else{ - sqlite3VdbeGoto(v, pLevel->addrFirst); - } - sqlite3VdbeJumpHere(v, addr); - } - VdbeModuleComment((v, "End WHERE-loop%d: %s", i, - pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); - } - - /* The "break" point is here, just past the end of the outer loop. - ** Set it. - */ - sqlite3VdbeResolveLabel(v, pWInfo->iBreak); - - assert( pWInfo->nLevel<=pTabList->nSrc ); - for(i=0, pLevel=pWInfo->a; inLevel; i++, pLevel++){ - int k, last; - VdbeOp *pOp; - Index *pIdx = 0; - struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; - Table *pTab = pTabItem->pTab; - assert( pTab!=0 ); - pLoop = pLevel->pWLoop; - - /* For a co-routine, change all OP_Column references to the table of - ** the co-routine into OP_Copy of result contained in a register. - ** OP_Rowid becomes OP_Null. - */ - if( pTabItem->fg.viaCoroutine ){ - testcase( pParse->db->mallocFailed ); - translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur, - pTabItem->regResult, 0); - continue; - } - -#ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE - /* Close all of the cursors that were opened by sqlite3WhereBegin. - ** Except, do not close cursors that will be reused by the OR optimization - ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors - ** created for the ONEPASS optimization. - */ - if( (pTab->tabFlags & TF_Ephemeral)==0 - && pTab->pSelect==0 - && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 - ){ - int ws = pLoop->wsFlags; - if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){ - sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); - } - if( (ws & WHERE_INDEXED)!=0 - && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 - && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] - ){ - sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); - } - } -#endif - - /* If this scan uses an index, make VDBE code substitutions to read data - ** from the index instead of from the table where possible. In some cases - ** this optimization prevents the table from ever being read, which can - ** yield a significant performance boost. - ** - ** Calls to the code generator in between sqlite3WhereBegin and - ** sqlite3WhereEnd will have created code that references the table - ** directly. This loop scans all that code looking for opcodes - ** that reference the table and converts them into opcodes that - ** reference the index. - */ - if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ - pIdx = pLoop->u.btree.pIndex; - }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ - pIdx = pLevel->u.pCovidx; - } - if( pIdx - && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable)) - && !db->mallocFailed - ){ - last = sqlite3VdbeCurrentAddr(v); - k = pLevel->addrBody; -#ifdef SQLITE_DEBUG - if( db->flags & SQLITE_VdbeAddopTrace ){ - printf("TRANSLATE opcodes in range %d..%d\n", k, last-1); - } -#endif - pOp = sqlite3VdbeGetOp(v, k); - for(; kp1!=pLevel->iTabCur ) continue; - if( pOp->opcode==OP_Column -#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC - || pOp->opcode==OP_Offset -#endif - ){ - int x = pOp->p2; - assert( pIdx->pTable==pTab ); - if( !HasRowid(pTab) ){ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - x = pPk->aiColumn[x]; - assert( x>=0 ); - }else{ - testcase( x!=sqlite3StorageColumnToTable(pTab,x) ); - x = sqlite3StorageColumnToTable(pTab,x); - } - x = sqlite3TableColumnToIndex(pIdx, x); - if( x>=0 ){ - pOp->p2 = x; - pOp->p1 = pLevel->iIdxCur; - OpcodeRewriteTrace(db, k, pOp); - } - assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 - || pWInfo->eOnePass ); - }else if( pOp->opcode==OP_Rowid ){ - pOp->p1 = pLevel->iIdxCur; - pOp->opcode = OP_IdxRowid; - OpcodeRewriteTrace(db, k, pOp); - }else if( pOp->opcode==OP_IfNullRow ){ - pOp->p1 = pLevel->iIdxCur; - OpcodeRewriteTrace(db, k, pOp); - } - } -#ifdef SQLITE_DEBUG - if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n"); -#endif - } - } - - /* Undo all Expr node modifications */ - while( pWInfo->pExprMods ){ - WhereExprMod *p = pWInfo->pExprMods; - pWInfo->pExprMods = p->pNext; - memcpy(p->pExpr, &p->orig, sizeof(p->orig)); - sqlite3DbFree(db, p); - } - - /* Final cleanup - */ - pParse->nQueryLoop = pWInfo->savedNQueryLoop; - whereInfoFree(db, pWInfo); - return; -} - -/************** End of where.c ***********************************************/ -/************** Begin file window.c ******************************************/ -/* -** 2018 May 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. -** -************************************************************************* -*/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_OMIT_WINDOWFUNC - -/* -** SELECT REWRITING -** -** Any SELECT statement that contains one or more window functions in -** either the select list or ORDER BY clause (the only two places window -** functions may be used) is transformed by function sqlite3WindowRewrite() -** in order to support window function processing. For example, with the -** schema: -** -** CREATE TABLE t1(a, b, c, d, e, f, g); -** -** the statement: -** -** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e; -** -** is transformed to: -** -** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM ( -** SELECT a, e, c, d, b FROM t1 ORDER BY c, d -** ) ORDER BY e; -** -** The flattening optimization is disabled when processing this transformed -** SELECT statement. This allows the implementation of the window function -** (in this case max()) to process rows sorted in order of (c, d), which -** makes things easier for obvious reasons. More generally: -** -** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to -** the sub-query. -** -** * ORDER BY, LIMIT and OFFSET remain part of the parent query. -** -** * Terminals from each of the expression trees that make up the -** select-list and ORDER BY expressions in the parent query are -** selected by the sub-query. For the purposes of the transformation, -** terminals are column references and aggregate functions. -** -** If there is more than one window function in the SELECT that uses -** the same window declaration (the OVER bit), then a single scan may -** be used to process more than one window function. For example: -** -** SELECT max(b) OVER (PARTITION BY c ORDER BY d), -** min(e) OVER (PARTITION BY c ORDER BY d) -** FROM t1; -** -** is transformed in the same way as the example above. However: -** -** SELECT max(b) OVER (PARTITION BY c ORDER BY d), -** min(e) OVER (PARTITION BY a ORDER BY b) -** FROM t1; -** -** Must be transformed to: -** -** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM ( -** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM -** SELECT a, e, c, d, b FROM t1 ORDER BY a, b -** ) ORDER BY c, d -** ) ORDER BY e; -** -** so that both min() and max() may process rows in the order defined by -** their respective window declarations. -** -** INTERFACE WITH SELECT.C -** -** When processing the rewritten SELECT statement, code in select.c calls -** sqlite3WhereBegin() to begin iterating through the results of the -** sub-query, which is always implemented as a co-routine. It then calls -** sqlite3WindowCodeStep() to process rows and finish the scan by calling -** sqlite3WhereEnd(). -** -** sqlite3WindowCodeStep() generates VM code so that, for each row returned -** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked. -** When the sub-routine is invoked: -** -** * The results of all window-functions for the row are stored -** in the associated Window.regResult registers. -** -** * The required terminal values are stored in the current row of -** temp table Window.iEphCsr. -** -** In some cases, depending on the window frame and the specific window -** functions invoked, sqlite3WindowCodeStep() caches each entire partition -** in a temp table before returning any rows. In other cases it does not. -** This detail is encapsulated within this file, the code generated by -** select.c is the same in either case. -** -** BUILT-IN WINDOW FUNCTIONS -** -** This implementation features the following built-in window functions: -** -** row_number() -** rank() -** dense_rank() -** percent_rank() -** cume_dist() -** ntile(N) -** lead(expr [, offset [, default]]) -** lag(expr [, offset [, default]]) -** first_value(expr) -** last_value(expr) -** nth_value(expr, N) -** -** These are the same built-in window functions supported by Postgres. -** Although the behaviour of aggregate window functions (functions that -** can be used as either aggregates or window funtions) allows them to -** be implemented using an API, built-in window functions are much more -** esoteric. Additionally, some window functions (e.g. nth_value()) -** may only be implemented by caching the entire partition in memory. -** As such, some built-in window functions use the same API as aggregate -** window functions and some are implemented directly using VDBE -** instructions. Additionally, for those functions that use the API, the -** window frame is sometimes modified before the SELECT statement is -** rewritten. For example, regardless of the specified window frame, the -** row_number() function always uses: -** -** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW -** -** See sqlite3WindowUpdate() for details. -** -** As well as some of the built-in window functions, aggregate window -** functions min() and max() are implemented using VDBE instructions if -** the start of the window frame is declared as anything other than -** UNBOUNDED PRECEDING. -*/ - -/* -** Implementation of built-in window function row_number(). Assumes that the -** window frame has been coerced to: -** -** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW -*/ -static void row_numberStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ) (*p)++; - UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(apArg); -} -static void row_numberValueFunc(sqlite3_context *pCtx){ - i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - sqlite3_result_int64(pCtx, (p ? *p : 0)); -} - -/* -** Context object type used by rank(), dense_rank(), percent_rank() and -** cume_dist(). -*/ -struct CallCount { - i64 nValue; - i64 nStep; - i64 nTotal; -}; - -/* -** Implementation of built-in window function dense_rank(). Assumes that -** the window frame has been set to: -** -** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW -*/ -static void dense_rankStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct CallCount *p; - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ) p->nStep = 1; - UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(apArg); -} -static void dense_rankValueFunc(sqlite3_context *pCtx){ - struct CallCount *p; - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - if( p->nStep ){ - p->nValue++; - p->nStep = 0; - } - sqlite3_result_int64(pCtx, p->nValue); - } -} - -/* -** Implementation of built-in window function nth_value(). This -** implementation is used in "slow mode" only - when the EXCLUDE clause -** is not set to the default value "NO OTHERS". -*/ -struct NthValueCtx { - i64 nStep; - sqlite3_value *pValue; -}; -static void nth_valueStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct NthValueCtx *p; - p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - i64 iVal; - switch( sqlite3_value_numeric_type(apArg[1]) ){ - case SQLITE_INTEGER: - iVal = sqlite3_value_int64(apArg[1]); - break; - case SQLITE_FLOAT: { - double fVal = sqlite3_value_double(apArg[1]); - if( ((i64)fVal)!=fVal ) goto error_out; - iVal = (i64)fVal; - break; - } - default: - goto error_out; - } - if( iVal<=0 ) goto error_out; - - p->nStep++; - if( iVal==p->nStep ){ - p->pValue = sqlite3_value_dup(apArg[0]); - if( !p->pValue ){ - sqlite3_result_error_nomem(pCtx); - } - } - } - UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(apArg); - return; - - error_out: - sqlite3_result_error( - pCtx, "second argument to nth_value must be a positive integer", -1 - ); -} -static void nth_valueFinalizeFunc(sqlite3_context *pCtx){ - struct NthValueCtx *p; - p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0); - if( p && p->pValue ){ - sqlite3_result_value(pCtx, p->pValue); - sqlite3_value_free(p->pValue); - p->pValue = 0; - } -} -#define nth_valueInvFunc noopStepFunc -#define nth_valueValueFunc noopValueFunc - -static void first_valueStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct NthValueCtx *p; - p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p && p->pValue==0 ){ - p->pValue = sqlite3_value_dup(apArg[0]); - if( !p->pValue ){ - sqlite3_result_error_nomem(pCtx); - } - } - UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(apArg); -} -static void first_valueFinalizeFunc(sqlite3_context *pCtx){ - struct NthValueCtx *p; - p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p && p->pValue ){ - sqlite3_result_value(pCtx, p->pValue); - sqlite3_value_free(p->pValue); - p->pValue = 0; - } -} -#define first_valueInvFunc noopStepFunc -#define first_valueValueFunc noopValueFunc - -/* -** Implementation of built-in window function rank(). Assumes that -** the window frame has been set to: -** -** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW -*/ -static void rankStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct CallCount *p; - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - p->nStep++; - if( p->nValue==0 ){ - p->nValue = p->nStep; - } - } - UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(apArg); -} -static void rankValueFunc(sqlite3_context *pCtx){ - struct CallCount *p; - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - sqlite3_result_int64(pCtx, p->nValue); - p->nValue = 0; - } -} - -/* -** Implementation of built-in window function percent_rank(). Assumes that -** the window frame has been set to: -** -** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING -*/ -static void percent_rankStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct CallCount *p; - UNUSED_PARAMETER(nArg); assert( nArg==0 ); - UNUSED_PARAMETER(apArg); - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - p->nTotal++; - } -} -static void percent_rankInvFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct CallCount *p; - UNUSED_PARAMETER(nArg); assert( nArg==0 ); - UNUSED_PARAMETER(apArg); - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - p->nStep++; -} -static void percent_rankValueFunc(sqlite3_context *pCtx){ - struct CallCount *p; - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - p->nValue = p->nStep; - if( p->nTotal>1 ){ - double r = (double)p->nValue / (double)(p->nTotal-1); - sqlite3_result_double(pCtx, r); - }else{ - sqlite3_result_double(pCtx, 0.0); - } - } -} -#define percent_rankFinalizeFunc percent_rankValueFunc - -/* -** Implementation of built-in window function cume_dist(). Assumes that -** the window frame has been set to: -** -** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING -*/ -static void cume_distStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct CallCount *p; - UNUSED_PARAMETER(nArg); assert( nArg==0 ); - UNUSED_PARAMETER(apArg); - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - p->nTotal++; - } -} -static void cume_distInvFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct CallCount *p; - UNUSED_PARAMETER(nArg); assert( nArg==0 ); - UNUSED_PARAMETER(apArg); - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - p->nStep++; -} -static void cume_distValueFunc(sqlite3_context *pCtx){ - struct CallCount *p; - p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0); - if( p ){ - double r = (double)(p->nStep) / (double)(p->nTotal); - sqlite3_result_double(pCtx, r); - } -} -#define cume_distFinalizeFunc cume_distValueFunc - -/* -** Context object for ntile() window function. -*/ -struct NtileCtx { - i64 nTotal; /* Total rows in partition */ - i64 nParam; /* Parameter passed to ntile(N) */ - i64 iRow; /* Current row */ -}; - -/* -** Implementation of ntile(). This assumes that the window frame has -** been coerced to: -** -** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING -*/ -static void ntileStepFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct NtileCtx *p; - assert( nArg==1 ); UNUSED_PARAMETER(nArg); - p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p ){ - if( p->nTotal==0 ){ - p->nParam = sqlite3_value_int64(apArg[0]); - if( p->nParam<=0 ){ - sqlite3_result_error( - pCtx, "argument of ntile must be a positive integer", -1 - ); - } - } - p->nTotal++; - } -} -static void ntileInvFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct NtileCtx *p; - assert( nArg==1 ); UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(apArg); - p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - p->iRow++; -} -static void ntileValueFunc(sqlite3_context *pCtx){ - struct NtileCtx *p; - p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p && p->nParam>0 ){ - int nSize = (p->nTotal / p->nParam); - if( nSize==0 ){ - sqlite3_result_int64(pCtx, p->iRow+1); - }else{ - i64 nLarge = p->nTotal - p->nParam*nSize; - i64 iSmall = nLarge*(nSize+1); - i64 iRow = p->iRow; - - assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal ); - - if( iRowpVal); - p->pVal = sqlite3_value_dup(apArg[0]); - if( p->pVal==0 ){ - sqlite3_result_error_nomem(pCtx); - }else{ - p->nVal++; - } - } -} -static void last_valueInvFunc( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - struct LastValueCtx *p; - UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(apArg); - p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( ALWAYS(p) ){ - p->nVal--; - if( p->nVal==0 ){ - sqlite3_value_free(p->pVal); - p->pVal = 0; - } - } -} -static void last_valueValueFunc(sqlite3_context *pCtx){ - struct LastValueCtx *p; - p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0); - if( p && p->pVal ){ - sqlite3_result_value(pCtx, p->pVal); - } -} -static void last_valueFinalizeFunc(sqlite3_context *pCtx){ - struct LastValueCtx *p; - p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p && p->pVal ){ - sqlite3_result_value(pCtx, p->pVal); - sqlite3_value_free(p->pVal); - p->pVal = 0; - } -} - -/* -** Static names for the built-in window function names. These static -** names are used, rather than string literals, so that FuncDef objects -** can be associated with a particular window function by direct -** comparison of the zName pointer. Example: -** -** if( pFuncDef->zName==row_valueName ){ ... } -*/ -static const char row_numberName[] = "row_number"; -static const char dense_rankName[] = "dense_rank"; -static const char rankName[] = "rank"; -static const char percent_rankName[] = "percent_rank"; -static const char cume_distName[] = "cume_dist"; -static const char ntileName[] = "ntile"; -static const char last_valueName[] = "last_value"; -static const char nth_valueName[] = "nth_value"; -static const char first_valueName[] = "first_value"; -static const char leadName[] = "lead"; -static const char lagName[] = "lag"; - -/* -** No-op implementations of xStep() and xFinalize(). Used as place-holders -** for built-in window functions that never call those interfaces. -** -** The noopValueFunc() is called but is expected to do nothing. The -** noopStepFunc() is never called, and so it is marked with NO_TEST to -** let the test coverage routine know not to expect this function to be -** invoked. -*/ -static void noopStepFunc( /*NO_TEST*/ - sqlite3_context *p, /*NO_TEST*/ - int n, /*NO_TEST*/ - sqlite3_value **a /*NO_TEST*/ -){ /*NO_TEST*/ - UNUSED_PARAMETER(p); /*NO_TEST*/ - UNUSED_PARAMETER(n); /*NO_TEST*/ - UNUSED_PARAMETER(a); /*NO_TEST*/ - assert(0); /*NO_TEST*/ -} /*NO_TEST*/ -static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ } - -/* Window functions that use all window interfaces: xStep, xFinal, -** xValue, and xInverse */ -#define WINDOWFUNCALL(name,nArg,extra) { \ - nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ - name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \ - name ## InvFunc, name ## Name, {0} \ -} - -/* Window functions that are implemented using bytecode and thus have -** no-op routines for their methods */ -#define WINDOWFUNCNOOP(name,nArg,extra) { \ - nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ - noopStepFunc, noopValueFunc, noopValueFunc, \ - noopStepFunc, name ## Name, {0} \ -} - -/* Window functions that use all window interfaces: xStep, the -** same routine for xFinalize and xValue and which never call -** xInverse. */ -#define WINDOWFUNCX(name,nArg,extra) { \ - nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ - name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \ - noopStepFunc, name ## Name, {0} \ -} - - -/* -** Register those built-in window functions that are not also aggregates. -*/ -SQLITE_PRIVATE void sqlite3WindowFunctions(void){ - static FuncDef aWindowFuncs[] = { - WINDOWFUNCX(row_number, 0, 0), - WINDOWFUNCX(dense_rank, 0, 0), - WINDOWFUNCX(rank, 0, 0), - WINDOWFUNCALL(percent_rank, 0, 0), - WINDOWFUNCALL(cume_dist, 0, 0), - WINDOWFUNCALL(ntile, 1, 0), - WINDOWFUNCALL(last_value, 1, 0), - WINDOWFUNCALL(nth_value, 2, 0), - WINDOWFUNCALL(first_value, 1, 0), - WINDOWFUNCNOOP(lead, 1, 0), - WINDOWFUNCNOOP(lead, 2, 0), - WINDOWFUNCNOOP(lead, 3, 0), - WINDOWFUNCNOOP(lag, 1, 0), - WINDOWFUNCNOOP(lag, 2, 0), - WINDOWFUNCNOOP(lag, 3, 0), - }; - sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs)); -} - -static Window *windowFind(Parse *pParse, Window *pList, const char *zName){ - Window *p; - for(p=pList; p; p=p->pNextWin){ - if( sqlite3StrICmp(p->zName, zName)==0 ) break; - } - if( p==0 ){ - sqlite3ErrorMsg(pParse, "no such window: %s", zName); - } - return p; -} - -/* -** This function is called immediately after resolving the function name -** for a window function within a SELECT statement. Argument pList is a -** linked list of WINDOW definitions for the current SELECT statement. -** Argument pFunc is the function definition just resolved and pWin -** is the Window object representing the associated OVER clause. This -** function updates the contents of pWin as follows: -** -** * If the OVER clause refered to a named window (as in "max(x) OVER win"), -** search list pList for a matching WINDOW definition, and update pWin -** accordingly. If no such WINDOW clause can be found, leave an error -** in pParse. -** -** * If the function is a built-in window function that requires the -** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top -** of this file), pWin is updated here. -*/ -SQLITE_PRIVATE void sqlite3WindowUpdate( - Parse *pParse, - Window *pList, /* List of named windows for this SELECT */ - Window *pWin, /* Window frame to update */ - FuncDef *pFunc /* Window function definition */ -){ - if( pWin->zName && pWin->eFrmType==0 ){ - Window *p = windowFind(pParse, pList, pWin->zName); - if( p==0 ) return; - pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0); - pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0); - pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0); - pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0); - pWin->eStart = p->eStart; - pWin->eEnd = p->eEnd; - pWin->eFrmType = p->eFrmType; - pWin->eExclude = p->eExclude; - }else{ - sqlite3WindowChain(pParse, pWin, pList); - } - if( (pWin->eFrmType==TK_RANGE) - && (pWin->pStart || pWin->pEnd) - && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1) - ){ - sqlite3ErrorMsg(pParse, - "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression" - ); - }else - if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){ - sqlite3 *db = pParse->db; - if( pWin->pFilter ){ - sqlite3ErrorMsg(pParse, - "FILTER clause may only be used with aggregate window functions" - ); - }else{ - struct WindowUpdate { - const char *zFunc; - int eFrmType; - int eStart; - int eEnd; - } aUp[] = { - { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, - { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, - { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, - { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED }, - { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED }, - { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED }, - { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED }, - { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, - }; - int i; - for(i=0; izName==aUp[i].zFunc ){ - sqlite3ExprDelete(db, pWin->pStart); - sqlite3ExprDelete(db, pWin->pEnd); - pWin->pEnd = pWin->pStart = 0; - pWin->eFrmType = aUp[i].eFrmType; - pWin->eStart = aUp[i].eStart; - pWin->eEnd = aUp[i].eEnd; - pWin->eExclude = 0; - if( pWin->eStart==TK_FOLLOWING ){ - pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1"); - } - break; - } - } - } - } - pWin->pFunc = pFunc; -} - -/* -** Context object passed through sqlite3WalkExprList() to -** selectWindowRewriteExprCb() by selectWindowRewriteEList(). -*/ -typedef struct WindowRewrite WindowRewrite; -struct WindowRewrite { - Window *pWin; - SrcList *pSrc; - ExprList *pSub; - Table *pTab; - Select *pSubSelect; /* Current sub-select, if any */ -}; - -/* -** Callback function used by selectWindowRewriteEList(). If necessary, -** this function appends to the output expression-list and updates -** expression (*ppExpr) in place. -*/ -static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){ - struct WindowRewrite *p = pWalker->u.pRewrite; - Parse *pParse = pWalker->pParse; - assert( p!=0 ); - assert( p->pWin!=0 ); - - /* If this function is being called from within a scalar sub-select - ** that used by the SELECT statement being processed, only process - ** TK_COLUMN expressions that refer to it (the outer SELECT). Do - ** not process aggregates or window functions at all, as they belong - ** to the scalar sub-select. */ - if( p->pSubSelect ){ - if( pExpr->op!=TK_COLUMN ){ - return WRC_Continue; - }else{ - int nSrc = p->pSrc->nSrc; - int i; - for(i=0; iiTable==p->pSrc->a[i].iCursor ) break; - } - if( i==nSrc ) return WRC_Continue; - } - } - - switch( pExpr->op ){ - - case TK_FUNCTION: - if( !ExprHasProperty(pExpr, EP_WinFunc) ){ - break; - }else{ - Window *pWin; - for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){ - if( pExpr->y.pWin==pWin ){ - assert( pWin->pOwner==pExpr ); - return WRC_Prune; - } - } - } - /* no break */ deliberate_fall_through - - case TK_AGG_FUNCTION: - case TK_COLUMN: { - int iCol = -1; - if( p->pSub ){ - int i; - for(i=0; ipSub->nExpr; i++){ - if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){ - iCol = i; - break; - } - } - } - if( iCol<0 ){ - Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0); - if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION; - p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup); - } - if( p->pSub ){ - int f = pExpr->flags & EP_Collate; - assert( ExprHasProperty(pExpr, EP_Static)==0 ); - ExprSetProperty(pExpr, EP_Static); - sqlite3ExprDelete(pParse->db, pExpr); - ExprClearProperty(pExpr, EP_Static); - memset(pExpr, 0, sizeof(Expr)); - - pExpr->op = TK_COLUMN; - pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol); - pExpr->iTable = p->pWin->iEphCsr; - pExpr->y.pTab = p->pTab; - pExpr->flags = f; - } - if( pParse->db->mallocFailed ) return WRC_Abort; - break; - } - - default: /* no-op */ - break; - } - - return WRC_Continue; -} -static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){ - struct WindowRewrite *p = pWalker->u.pRewrite; - Select *pSave = p->pSubSelect; - if( pSave==pSelect ){ - return WRC_Continue; - }else{ - p->pSubSelect = pSelect; - sqlite3WalkSelect(pWalker, pSelect); - p->pSubSelect = pSave; - } - return WRC_Prune; -} - - -/* -** Iterate through each expression in expression-list pEList. For each: -** -** * TK_COLUMN, -** * aggregate function, or -** * window function with a Window object that is not a member of the -** Window list passed as the second argument (pWin). -** -** Append the node to output expression-list (*ppSub). And replace it -** with a TK_COLUMN that reads the (N-1)th element of table -** pWin->iEphCsr, where N is the number of elements in (*ppSub) after -** appending the new one. -*/ -static void selectWindowRewriteEList( - Parse *pParse, - Window *pWin, - SrcList *pSrc, - ExprList *pEList, /* Rewrite expressions in this list */ - Table *pTab, - ExprList **ppSub /* IN/OUT: Sub-select expression-list */ -){ - Walker sWalker; - WindowRewrite sRewrite; - - assert( pWin!=0 ); - memset(&sWalker, 0, sizeof(Walker)); - memset(&sRewrite, 0, sizeof(WindowRewrite)); - - sRewrite.pSub = *ppSub; - sRewrite.pWin = pWin; - sRewrite.pSrc = pSrc; - sRewrite.pTab = pTab; - - sWalker.pParse = pParse; - sWalker.xExprCallback = selectWindowRewriteExprCb; - sWalker.xSelectCallback = selectWindowRewriteSelectCb; - sWalker.u.pRewrite = &sRewrite; - - (void)sqlite3WalkExprList(&sWalker, pEList); - - *ppSub = sRewrite.pSub; -} - -/* -** Append a copy of each expression in expression-list pAppend to -** expression list pList. Return a pointer to the result list. -*/ -static ExprList *exprListAppendList( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* List to which to append. Might be NULL */ - ExprList *pAppend, /* List of values to append. Might be NULL */ - int bIntToNull -){ - if( pAppend ){ - int i; - int nInit = pList ? pList->nExpr : 0; - for(i=0; inExpr; i++){ - Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0); - assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) ); - if( bIntToNull && pDup ){ - int iDummy; - Expr *pSub; - for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){ - assert( pSub ); - } - if( sqlite3ExprIsInteger(pSub, &iDummy) ){ - pSub->op = TK_NULL; - pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); - pSub->u.zToken = 0; - } - } - pList = sqlite3ExprListAppend(pParse, pList, pDup); - if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags; - } - } - return pList; -} - -/* -** When rewriting a query, if the new subquery in the FROM clause -** contains TK_AGG_FUNCTION nodes that refer to an outer query, -** then we have to increase the Expr->op2 values of those nodes -** due to the extra subquery layer that was added. -** -** See also the incrAggDepth() routine in resolve.c -*/ -static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){ - if( pExpr->op==TK_AGG_FUNCTION - && pExpr->op2>=pWalker->walkerDepth - ){ - pExpr->op2++; - } - return WRC_Continue; -} - -/* -** If the SELECT statement passed as the second argument does not invoke -** any SQL window functions, this function is a no-op. Otherwise, it -** rewrites the SELECT statement so that window function xStep functions -** are invoked in the correct order as described under "SELECT REWRITING" -** at the top of this file. -*/ -SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){ - int rc = SQLITE_OK; - if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){ - Vdbe *v = sqlite3GetVdbe(pParse); - sqlite3 *db = pParse->db; - Select *pSub = 0; /* The subquery */ - SrcList *pSrc = p->pSrc; - Expr *pWhere = p->pWhere; - ExprList *pGroupBy = p->pGroupBy; - Expr *pHaving = p->pHaving; - ExprList *pSort = 0; - - ExprList *pSublist = 0; /* Expression list for sub-query */ - Window *pMWin = p->pWin; /* Main window object */ - Window *pWin; /* Window object iterator */ - Table *pTab; - Walker w; - - u32 selFlags = p->selFlags; - - pTab = sqlite3DbMallocZero(db, sizeof(Table)); - if( pTab==0 ){ - return sqlite3ErrorToParser(db, SQLITE_NOMEM); - } - sqlite3AggInfoPersistWalkerInit(&w, pParse); - sqlite3WalkSelect(&w, p); - - p->pSrc = 0; - p->pWhere = 0; - p->pGroupBy = 0; - p->pHaving = 0; - p->selFlags &= ~SF_Aggregate; - p->selFlags |= SF_WinRewrite; - - /* Create the ORDER BY clause for the sub-select. This is the concatenation - ** of the window PARTITION and ORDER BY clauses. Then, if this makes it - ** redundant, remove the ORDER BY from the parent SELECT. */ - pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1); - pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1); - if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){ - int nSave = pSort->nExpr; - pSort->nExpr = p->pOrderBy->nExpr; - if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){ - sqlite3ExprListDelete(db, p->pOrderBy); - p->pOrderBy = 0; - } - pSort->nExpr = nSave; - } - - /* Assign a cursor number for the ephemeral table used to buffer rows. - ** The OpenEphemeral instruction is coded later, after it is known how - ** many columns the table will have. */ - pMWin->iEphCsr = pParse->nTab++; - pParse->nTab += 3; - - selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist); - selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist); - pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0); - - /* Append the PARTITION BY and ORDER BY expressions to the to the - ** sub-select expression list. They are required to figure out where - ** boundaries for partitions and sets of peer rows lie. */ - pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0); - pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0); - - /* Append the arguments passed to each window function to the - ** sub-select expression list. Also allocate two registers for each - ** window function - one for the accumulator, another for interim - ** results. */ - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - ExprList *pArgs = pWin->pOwner->x.pList; - if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){ - selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist); - pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); - pWin->bExprArgs = 1; - }else{ - pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); - pSublist = exprListAppendList(pParse, pSublist, pArgs, 0); - } - if( pWin->pFilter ){ - Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0); - pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter); - } - pWin->regAccum = ++pParse->nMem; - pWin->regResult = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); - } - - /* If there is no ORDER BY or PARTITION BY clause, and the window - ** function accepts zero arguments, and there are no other columns - ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible - ** that pSublist is still NULL here. Add a constant expression here to - ** keep everything legal in this case. - */ - if( pSublist==0 ){ - pSublist = sqlite3ExprListAppend(pParse, 0, - sqlite3Expr(db, TK_INTEGER, "0") - ); - } - - pSub = sqlite3SelectNew( - pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0 - ); - SELECTTRACE(1,pParse,pSub, - ("New window-function subquery in FROM clause of (%u/%p)\n", - p->selId, p)); - p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); - if( p->pSrc ){ - Table *pTab2; - p->pSrc->a[0].pSelect = pSub; - sqlite3SrcListAssignCursors(pParse, p->pSrc); - pSub->selFlags |= SF_Expanded; - pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE); - pSub->selFlags |= (selFlags & SF_Aggregate); - if( pTab2==0 ){ - /* Might actually be some other kind of error, but in that case - ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get - ** the correct error message regardless. */ - rc = SQLITE_NOMEM; - }else{ - memcpy(pTab, pTab2, sizeof(Table)); - pTab->tabFlags |= TF_Ephemeral; - p->pSrc->a[0].pTab = pTab; - pTab = pTab2; - memset(&w, 0, sizeof(w)); - w.xExprCallback = sqlite3WindowExtraAggFuncDepth; - w.xSelectCallback = sqlite3WalkerDepthIncrease; - w.xSelectCallback2 = sqlite3WalkerDepthDecrease; - sqlite3WalkSelect(&w, pSub); - } - }else{ - sqlite3SelectDelete(db, pSub); - } - if( db->mallocFailed ) rc = SQLITE_NOMEM; - sqlite3DbFree(db, pTab); - } - - if( rc ){ - if( pParse->nErr==0 ){ - assert( pParse->db->mallocFailed ); - sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM); - } - } - return rc; -} - -/* -** Unlink the Window object from the Select to which it is attached, -** if it is attached. -*/ -SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window *p){ - if( p->ppThis ){ - *p->ppThis = p->pNextWin; - if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis; - p->ppThis = 0; - } -} - -/* -** Free the Window object passed as the second argument. -*/ -SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){ - if( p ){ - sqlite3WindowUnlinkFromSelect(p); - sqlite3ExprDelete(db, p->pFilter); - sqlite3ExprListDelete(db, p->pPartition); - sqlite3ExprListDelete(db, p->pOrderBy); - sqlite3ExprDelete(db, p->pEnd); - sqlite3ExprDelete(db, p->pStart); - sqlite3DbFree(db, p->zName); - sqlite3DbFree(db, p->zBase); - sqlite3DbFree(db, p); - } -} - -/* -** Free the linked list of Window objects starting at the second argument. -*/ -SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){ - while( p ){ - Window *pNext = p->pNextWin; - sqlite3WindowDelete(db, p); - p = pNext; - } -} - -/* -** The argument expression is an PRECEDING or FOLLOWING offset. The -** value should be a non-negative integer. If the value is not a -** constant, change it to NULL. The fact that it is then a non-negative -** integer will be caught later. But it is important not to leave -** variable values in the expression tree. -*/ -static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){ - if( 0==sqlite3ExprIsConstant(pExpr) ){ - if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr); - sqlite3ExprDelete(pParse->db, pExpr); - pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0); - } - return pExpr; -} - -/* -** Allocate and return a new Window object describing a Window Definition. -*/ -SQLITE_PRIVATE Window *sqlite3WindowAlloc( - Parse *pParse, /* Parsing context */ - int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */ - int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */ - Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */ - int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */ - Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */ - u8 eExclude /* EXCLUDE clause */ -){ - Window *pWin = 0; - int bImplicitFrame = 0; - - /* Parser assures the following: */ - assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS ); - assert( eStart==TK_CURRENT || eStart==TK_PRECEDING - || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING ); - assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING - || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING ); - assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) ); - assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) ); - - if( eType==0 ){ - bImplicitFrame = 1; - eType = TK_RANGE; - } - - /* Additionally, the - ** starting boundary type may not occur earlier in the following list than - ** the ending boundary type: - ** - ** UNBOUNDED PRECEDING - ** PRECEDING - ** CURRENT ROW - ** FOLLOWING - ** UNBOUNDED FOLLOWING - ** - ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending - ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting - ** frame boundary. - */ - if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING) - || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT)) - ){ - sqlite3ErrorMsg(pParse, "unsupported frame specification"); - goto windowAllocErr; - } - - pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); - if( pWin==0 ) goto windowAllocErr; - pWin->eFrmType = eType; - pWin->eStart = eStart; - pWin->eEnd = eEnd; - if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){ - eExclude = TK_NO; - } - pWin->eExclude = eExclude; - pWin->bImplicitFrame = bImplicitFrame; - pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd); - pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart); - return pWin; - -windowAllocErr: - sqlite3ExprDelete(pParse->db, pEnd); - sqlite3ExprDelete(pParse->db, pStart); - return 0; -} - -/* -** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window -** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the -** equivalent nul-terminated string. -*/ -SQLITE_PRIVATE Window *sqlite3WindowAssemble( - Parse *pParse, - Window *pWin, - ExprList *pPartition, - ExprList *pOrderBy, - Token *pBase -){ - if( pWin ){ - pWin->pPartition = pPartition; - pWin->pOrderBy = pOrderBy; - if( pBase ){ - pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n); - } - }else{ - sqlite3ExprListDelete(pParse->db, pPartition); - sqlite3ExprListDelete(pParse->db, pOrderBy); - } - return pWin; -} - -/* -** Window *pWin has just been created from a WINDOW clause. Tokne pBase -** is the base window. Earlier windows from the same WINDOW clause are -** stored in the linked list starting at pWin->pNextWin. This function -** either updates *pWin according to the base specification, or else -** leaves an error in pParse. -*/ -SQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){ - if( pWin->zBase ){ - sqlite3 *db = pParse->db; - Window *pExist = windowFind(pParse, pList, pWin->zBase); - if( pExist ){ - const char *zErr = 0; - /* Check for errors */ - if( pWin->pPartition ){ - zErr = "PARTITION clause"; - }else if( pExist->pOrderBy && pWin->pOrderBy ){ - zErr = "ORDER BY clause"; - }else if( pExist->bImplicitFrame==0 ){ - zErr = "frame specification"; - } - if( zErr ){ - sqlite3ErrorMsg(pParse, - "cannot override %s of window: %s", zErr, pWin->zBase - ); - }else{ - pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0); - if( pExist->pOrderBy ){ - assert( pWin->pOrderBy==0 ); - pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0); - } - sqlite3DbFree(db, pWin->zBase); - pWin->zBase = 0; - } - } - } -} - -/* -** Attach window object pWin to expression p. -*/ -SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){ - if( p ){ - assert( p->op==TK_FUNCTION ); - assert( pWin ); - p->y.pWin = pWin; - ExprSetProperty(p, EP_WinFunc); - pWin->pOwner = p; - if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){ - sqlite3ErrorMsg(pParse, - "DISTINCT is not supported for window functions" - ); - } - }else{ - sqlite3WindowDelete(pParse->db, pWin); - } -} - -/* -** Possibly link window pWin into the list at pSel->pWin (window functions -** to be processed as part of SELECT statement pSel). The window is linked -** in if either (a) there are no other windows already linked to this -** SELECT, or (b) the windows already linked use a compatible window frame. -*/ -SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){ - if( pSel!=0 - && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0)) - ){ - pWin->pNextWin = pSel->pWin; - if( pSel->pWin ){ - pSel->pWin->ppThis = &pWin->pNextWin; - } - pSel->pWin = pWin; - pWin->ppThis = &pSel->pWin; - } -} - -/* -** Return 0 if the two window objects are identical, 1 if they are -** different, or 2 if it cannot be determined if the objects are identical -** or not. Identical window objects can be processed in a single scan. -*/ -SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){ - int res; - if( NEVER(p1==0) || NEVER(p2==0) ) return 1; - if( p1->eFrmType!=p2->eFrmType ) return 1; - if( p1->eStart!=p2->eStart ) return 1; - if( p1->eEnd!=p2->eEnd ) return 1; - if( p1->eExclude!=p2->eExclude ) return 1; - if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1; - if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1; - if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){ - return res; - } - if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){ - return res; - } - if( bFilter ){ - if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){ - return res; - } - } - return 0; -} - - -/* -** This is called by code in select.c before it calls sqlite3WhereBegin() -** to begin iterating through the sub-query results. It is used to allocate -** and initialize registers and cursors used by sqlite3WindowCodeStep(). -*/ -SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){ - int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr; - Window *pMWin = pSelect->pWin; - Window *pWin; - Vdbe *v = sqlite3GetVdbe(pParse); - - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr); - sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr); - sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr); - sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr); - - /* Allocate registers to use for PARTITION BY values, if any. Initialize - ** said registers to NULL. */ - if( pMWin->pPartition ){ - int nExpr = pMWin->pPartition->nExpr; - pMWin->regPart = pParse->nMem+1; - pParse->nMem += nExpr; - sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1); - } - - pMWin->regOne = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne); - - if( pMWin->eExclude ){ - pMWin->regStartRowid = ++pParse->nMem; - pMWin->regEndRowid = ++pParse->nMem; - pMWin->csrApp = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); - sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); - sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr); - return; - } - - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - FuncDef *p = pWin->pFunc; - if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){ - /* The inline versions of min() and max() require a single ephemeral - ** table and 3 registers. The registers are used as follows: - ** - ** regApp+0: slot to copy min()/max() argument to for MakeRecord - ** regApp+1: integer value used to ensure keys are unique - ** regApp+2: output of MakeRecord - */ - ExprList *pList = pWin->pOwner->x.pList; - KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0); - pWin->csrApp = pParse->nTab++; - pWin->regApp = pParse->nMem+1; - pParse->nMem += 3; - if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){ - assert( pKeyInfo->aSortFlags[0]==0 ); - pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC; - } - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2); - sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); - sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); - } - else if( p->zName==nth_valueName || p->zName==first_valueName ){ - /* Allocate two registers at pWin->regApp. These will be used to - ** store the start and end index of the current frame. */ - pWin->regApp = pParse->nMem+1; - pWin->csrApp = pParse->nTab++; - pParse->nMem += 2; - sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); - } - else if( p->zName==leadName || p->zName==lagName ){ - pWin->csrApp = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); - } - } -} - -#define WINDOW_STARTING_INT 0 -#define WINDOW_ENDING_INT 1 -#define WINDOW_NTH_VALUE_INT 2 -#define WINDOW_STARTING_NUM 3 -#define WINDOW_ENDING_NUM 4 - -/* -** A "PRECEDING " (eCond==0) or "FOLLOWING " (eCond==1) or the -** value of the second argument to nth_value() (eCond==2) has just been -** evaluated and the result left in register reg. This function generates VM -** code to check that the value is a non-negative integer and throws an -** exception if it is not. -*/ -static void windowCheckValue(Parse *pParse, int reg, int eCond){ - static const char *azErr[] = { - "frame starting offset must be a non-negative integer", - "frame ending offset must be a non-negative integer", - "second argument to nth_value must be a positive integer", - "frame starting offset must be a non-negative number", - "frame ending offset must be a non-negative number", - }; - static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge }; - Vdbe *v = sqlite3GetVdbe(pParse); - int regZero = sqlite3GetTempReg(pParse); - assert( eCond>=0 && eCond=WINDOW_STARTING_NUM ){ - int regString = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); - sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg); - sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL); - VdbeCoverage(v); - assert( eCond==3 || eCond==4 ); - VdbeCoverageIf(v, eCond==3); - VdbeCoverageIf(v, eCond==4); - }else{ - sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - assert( eCond==0 || eCond==1 || eCond==2 ); - VdbeCoverageIf(v, eCond==0); - VdbeCoverageIf(v, eCond==1); - VdbeCoverageIf(v, eCond==2); - } - sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg); - VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */ - VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */ - VdbeCoverageNeverNullIf(v, eCond==2); - VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */ - VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */ - sqlite3MayAbort(pParse); - sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort); - sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC); - sqlite3ReleaseTempReg(pParse, regZero); -} - -/* -** Return the number of arguments passed to the window-function associated -** with the object passed as the only argument to this function. -*/ -static int windowArgCount(Window *pWin){ - ExprList *pList = pWin->pOwner->x.pList; - return (pList ? pList->nExpr : 0); -} - -typedef struct WindowCodeArg WindowCodeArg; -typedef struct WindowCsrAndReg WindowCsrAndReg; - -/* -** See comments above struct WindowCodeArg. -*/ -struct WindowCsrAndReg { - int csr; /* Cursor number */ - int reg; /* First in array of peer values */ -}; - -/* -** A single instance of this structure is allocated on the stack by -** sqlite3WindowCodeStep() and a pointer to it passed to the various helper -** routines. This is to reduce the number of arguments required by each -** helper function. -** -** regArg: -** Each window function requires an accumulator register (just as an -** ordinary aggregate function does). This variable is set to the first -** in an array of accumulator registers - one for each window function -** in the WindowCodeArg.pMWin list. -** -** eDelete: -** The window functions implementation sometimes caches the input rows -** that it processes in a temporary table. If it is not zero, this -** variable indicates when rows may be removed from the temp table (in -** order to reduce memory requirements - it would always be safe just -** to leave them there). Possible values for eDelete are: -** -** WINDOW_RETURN_ROW: -** An input row can be discarded after it is returned to the caller. -** -** WINDOW_AGGINVERSE: -** An input row can be discarded after the window functions xInverse() -** callbacks have been invoked in it. -** -** WINDOW_AGGSTEP: -** An input row can be discarded after the window functions xStep() -** callbacks have been invoked in it. -** -** start,current,end -** Consider a window-frame similar to the following: -** -** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING) -** -** The windows functions implmentation caches the input rows in a temp -** table, sorted by "a, b" (it actually populates the cache lazily, and -** aggressively removes rows once they are no longer required, but that's -** a mere detail). It keeps three cursors open on the temp table. One -** (current) that points to the next row to return to the query engine -** once its window function values have been calculated. Another (end) -** points to the next row to call the xStep() method of each window function -** on (so that it is 2 groups ahead of current). And a third (start) that -** points to the next row to call the xInverse() method of each window -** function on. -** -** Each cursor (start, current and end) consists of a VDBE cursor -** (WindowCsrAndReg.csr) and an array of registers (starting at -** WindowCodeArg.reg) that always contains a copy of the peer values -** read from the corresponding cursor. -** -** Depending on the window-frame in question, all three cursors may not -** be required. In this case both WindowCodeArg.csr and reg are set to -** 0. -*/ -struct WindowCodeArg { - Parse *pParse; /* Parse context */ - Window *pMWin; /* First in list of functions being processed */ - Vdbe *pVdbe; /* VDBE object */ - int addrGosub; /* OP_Gosub to this address to return one row */ - int regGosub; /* Register used with OP_Gosub(addrGosub) */ - int regArg; /* First in array of accumulator registers */ - int eDelete; /* See above */ - - WindowCsrAndReg start; - WindowCsrAndReg current; - WindowCsrAndReg end; -}; - -/* -** Generate VM code to read the window frames peer values from cursor csr into -** an array of registers starting at reg. -*/ -static void windowReadPeerValues( - WindowCodeArg *p, - int csr, - int reg -){ - Window *pMWin = p->pMWin; - ExprList *pOrderBy = pMWin->pOrderBy; - if( pOrderBy ){ - Vdbe *v = sqlite3GetVdbe(p->pParse); - ExprList *pPart = pMWin->pPartition; - int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0); - int i; - for(i=0; inExpr; i++){ - sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i); - } - } -} - -/* -** Generate VM code to invoke either xStep() (if bInverse is 0) or -** xInverse (if bInverse is non-zero) for each window function in the -** linked list starting at pMWin. Or, for built-in window functions -** that do not use the standard function API, generate the required -** inline VM code. -** -** If argument csr is greater than or equal to 0, then argument reg is -** the first register in an array of registers guaranteed to be large -** enough to hold the array of arguments for each function. In this case -** the arguments are extracted from the current row of csr into the -** array of registers before invoking OP_AggStep or OP_AggInverse -** -** Or, if csr is less than zero, then the array of registers at reg is -** already populated with all columns from the current row of the sub-query. -** -** If argument regPartSize is non-zero, then it is a register containing the -** number of rows in the current partition. -*/ -static void windowAggStep( - WindowCodeArg *p, - Window *pMWin, /* Linked list of window functions */ - int csr, /* Read arguments from this cursor */ - int bInverse, /* True to invoke xInverse instead of xStep */ - int reg /* Array of registers */ -){ - Parse *pParse = p->pParse; - Vdbe *v = sqlite3GetVdbe(pParse); - Window *pWin; - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - FuncDef *pFunc = pWin->pFunc; - int regArg; - int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin); - int i; - - assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED ); - - /* All OVER clauses in the same window function aggregate step must - ** be the same. */ - assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 ); - - for(i=0; izName!=nth_valueName ){ - sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i); - }else{ - sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i); - } - } - regArg = reg; - - if( pMWin->regStartRowid==0 - && (pFunc->funcFlags & SQLITE_FUNC_MINMAX) - && (pWin->eStart!=TK_UNBOUNDED) - ){ - int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg); - VdbeCoverage(v); - if( bInverse==0 ){ - sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1); - sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp); - sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2); - }else{ - sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1); - VdbeCoverageNeverTaken(v); - sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp); - sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); - } - sqlite3VdbeJumpHere(v, addrIsNull); - }else if( pWin->regApp ){ - assert( pFunc->zName==nth_valueName - || pFunc->zName==first_valueName - ); - assert( bInverse==0 || bInverse==1 ); - sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1); - }else if( pFunc->xSFunc!=noopStepFunc ){ - int addrIf = 0; - if( pWin->pFilter ){ - int regTmp; - assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr ); - assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 ); - regTmp = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp); - addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1); - VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, regTmp); - } - - if( pWin->bExprArgs ){ - int iStart = sqlite3VdbeCurrentAddr(v); - VdbeOp *pOp, *pEnd; - - nArg = pWin->pOwner->x.pList->nExpr; - regArg = sqlite3GetTempRange(pParse, nArg); - sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0); - - pEnd = sqlite3VdbeGetOp(v, -1); - for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){ - if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){ - pOp->p1 = csr; - } - } - } - if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ - CollSeq *pColl; - assert( nArg>0 ); - pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr); - sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ); - } - sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, - bInverse, regArg, pWin->regAccum); - sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nArg); - if( pWin->bExprArgs ){ - sqlite3ReleaseTempRange(pParse, regArg, nArg); - } - if( addrIf ) sqlite3VdbeJumpHere(v, addrIf); - } - } -} - -/* -** Values that may be passed as the second argument to windowCodeOp(). -*/ -#define WINDOW_RETURN_ROW 1 -#define WINDOW_AGGINVERSE 2 -#define WINDOW_AGGSTEP 3 - -/* -** Generate VM code to invoke either xValue() (bFin==0) or xFinalize() -** (bFin==1) for each window function in the linked list starting at -** pMWin. Or, for built-in window-functions that do not use the standard -** API, generate the equivalent VM code. -*/ -static void windowAggFinal(WindowCodeArg *p, int bFin){ - Parse *pParse = p->pParse; - Window *pMWin = p->pMWin; - Vdbe *v = sqlite3GetVdbe(pParse); - Window *pWin; - - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - if( pMWin->regStartRowid==0 - && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) - && (pWin->eStart!=TK_UNBOUNDED) - ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); - sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult); - sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); - }else if( pWin->regApp ){ - assert( pMWin->regStartRowid==0 ); - }else{ - int nArg = windowArgCount(pWin); - if( bFin ){ - sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg); - sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); - sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult); - sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); - }else{ - sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult); - sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); - } - } - } -} - -/* -** Generate code to calculate the current values of all window functions in the -** p->pMWin list by doing a full scan of the current window frame. Store the -** results in the Window.regResult registers, ready to return the upper -** layer. -*/ -static void windowFullScan(WindowCodeArg *p){ - Window *pWin; - Parse *pParse = p->pParse; - Window *pMWin = p->pMWin; - Vdbe *v = p->pVdbe; - - int regCRowid = 0; /* Current rowid value */ - int regCPeer = 0; /* Current peer values */ - int regRowid = 0; /* AggStep rowid value */ - int regPeer = 0; /* AggStep peer values */ - - int nPeer; - int lblNext; - int lblBrk; - int addrNext; - int csr; - - VdbeModuleComment((v, "windowFullScan begin")); - - assert( pMWin!=0 ); - csr = pMWin->csrApp; - nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); - - lblNext = sqlite3VdbeMakeLabel(pParse); - lblBrk = sqlite3VdbeMakeLabel(pParse); - - regCRowid = sqlite3GetTempReg(pParse); - regRowid = sqlite3GetTempReg(pParse); - if( nPeer ){ - regCPeer = sqlite3GetTempRange(pParse, nPeer); - regPeer = sqlite3GetTempRange(pParse, nPeer); - } - - sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid); - windowReadPeerValues(p, pMWin->iEphCsr, regCPeer); - - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); - } - - sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid); - VdbeCoverage(v); - addrNext = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid); - sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid); - VdbeCoverageNeverNull(v); - - if( pMWin->eExclude==TK_CURRENT ){ - sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid); - VdbeCoverageNeverNull(v); - }else if( pMWin->eExclude!=TK_NO ){ - int addr; - int addrEq = 0; - KeyInfo *pKeyInfo = 0; - - if( pMWin->pOrderBy ){ - pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0); - } - if( pMWin->eExclude==TK_TIES ){ - addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid); - VdbeCoverageNeverNull(v); - } - if( pKeyInfo ){ - windowReadPeerValues(p, csr, regPeer); - sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer); - sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); - addr = sqlite3VdbeCurrentAddr(v)+1; - sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr); - VdbeCoverageEqNe(v); - }else{ - sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext); - } - if( addrEq ) sqlite3VdbeJumpHere(v, addrEq); - } - - windowAggStep(p, pMWin, csr, 0, p->regArg); - - sqlite3VdbeResolveLabel(v, lblNext); - sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext); - VdbeCoverage(v); - sqlite3VdbeJumpHere(v, addrNext-1); - sqlite3VdbeJumpHere(v, addrNext+1); - sqlite3ReleaseTempReg(pParse, regRowid); - sqlite3ReleaseTempReg(pParse, regCRowid); - if( nPeer ){ - sqlite3ReleaseTempRange(pParse, regPeer, nPeer); - sqlite3ReleaseTempRange(pParse, regCPeer, nPeer); - } - - windowAggFinal(p, 1); - VdbeModuleComment((v, "windowFullScan end")); -} - -/* -** Invoke the sub-routine at regGosub (generated by code in select.c) to -** return the current row of Window.iEphCsr. If all window functions are -** aggregate window functions that use the standard API, a single -** OP_Gosub instruction is all that this routine generates. Extra VM code -** for per-row processing is only generated for the following built-in window -** functions: -** -** nth_value() -** first_value() -** lag() -** lead() -*/ -static void windowReturnOneRow(WindowCodeArg *p){ - Window *pMWin = p->pMWin; - Vdbe *v = p->pVdbe; - - if( pMWin->regStartRowid ){ - windowFullScan(p); - }else{ - Parse *pParse = p->pParse; - Window *pWin; - - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - FuncDef *pFunc = pWin->pFunc; - if( pFunc->zName==nth_valueName - || pFunc->zName==first_valueName - ){ - int csr = pWin->csrApp; - int lbl = sqlite3VdbeMakeLabel(pParse); - int tmpReg = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); - - if( pFunc->zName==nth_valueName ){ - sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg); - windowCheckValue(pParse, tmpReg, 2); - }else{ - sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg); - } - sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg); - sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg); - VdbeCoverageNeverNull(v); - sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg); - VdbeCoverageNeverTaken(v); - sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); - sqlite3VdbeResolveLabel(v, lbl); - sqlite3ReleaseTempReg(pParse, tmpReg); - } - else if( pFunc->zName==leadName || pFunc->zName==lagName ){ - int nArg = pWin->pOwner->x.pList->nExpr; - int csr = pWin->csrApp; - int lbl = sqlite3VdbeMakeLabel(pParse); - int tmpReg = sqlite3GetTempReg(pParse); - int iEph = pMWin->iEphCsr; - - if( nArg<3 ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); - }else{ - sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult); - } - sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg); - if( nArg<2 ){ - int val = (pFunc->zName==leadName ? 1 : -1); - sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val); - }else{ - int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract); - int tmpReg2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2); - sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg); - sqlite3ReleaseTempReg(pParse, tmpReg2); - } - - sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); - sqlite3VdbeResolveLabel(v, lbl); - sqlite3ReleaseTempReg(pParse, tmpReg); - } - } - } - sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub); -} - -/* -** Generate code to set the accumulator register for each window function -** in the linked list passed as the second argument to NULL. And perform -** any equivalent initialization required by any built-in window functions -** in the list. -*/ -static int windowInitAccum(Parse *pParse, Window *pMWin){ - Vdbe *v = sqlite3GetVdbe(pParse); - int regArg; - int nArg = 0; - Window *pWin; - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - FuncDef *pFunc = pWin->pFunc; - assert( pWin->regAccum ); - sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); - nArg = MAX(nArg, windowArgCount(pWin)); - if( pMWin->regStartRowid==0 ){ - if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp); - sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); - } - - if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){ - assert( pWin->eStart!=TK_UNBOUNDED ); - sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp); - sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); - } - } - } - regArg = pParse->nMem+1; - pParse->nMem += nArg; - return regArg; -} - -/* -** Return true if the current frame should be cached in the ephemeral table, -** even if there are no xInverse() calls required. -*/ -static int windowCacheFrame(Window *pMWin){ - Window *pWin; - if( pMWin->regStartRowid ) return 1; - for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ - FuncDef *pFunc = pWin->pFunc; - if( (pFunc->zName==nth_valueName) - || (pFunc->zName==first_valueName) - || (pFunc->zName==leadName) - || (pFunc->zName==lagName) - ){ - return 1; - } - } - return 0; -} - -/* -** regOld and regNew are each the first register in an array of size -** pOrderBy->nExpr. This function generates code to compare the two -** arrays of registers using the collation sequences and other comparison -** parameters specified by pOrderBy. -** -** If the two arrays are not equal, the contents of regNew is copied to -** regOld and control falls through. Otherwise, if the contents of the arrays -** are equal, an OP_Goto is executed. The address of the OP_Goto is returned. -*/ -static void windowIfNewPeer( - Parse *pParse, - ExprList *pOrderBy, - int regNew, /* First in array of new values */ - int regOld, /* First in array of old values */ - int addr /* Jump here */ -){ - Vdbe *v = sqlite3GetVdbe(pParse); - if( pOrderBy ){ - int nVal = pOrderBy->nExpr; - KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0); - sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal); - sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); - sqlite3VdbeAddOp3(v, OP_Jump, - sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1 - ); - VdbeCoverageEqNe(v); - sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1); - }else{ - sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); - } -} - -/* -** This function is called as part of generating VM programs for RANGE -** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for -** the ORDER BY term in the window, and that argument op is OP_Ge, it generates -** code equivalent to: -** -** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl; -** -** The value of parameter op may also be OP_Gt or OP_Le. In these cases the -** operator in the above pseudo-code is replaced with ">" or "<=", respectively. -** -** If the sort-order for the ORDER BY term in the window is DESC, then the -** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is -** subtracted. And the comparison operator is inverted to - ">=" becomes "<=", -** ">" becomes "<", and so on. So, with DESC sort order, if the argument op -** is OP_Ge, the generated code is equivalent to: -** -** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl; -** -** A special type of arithmetic is used such that if csr1.peerVal is not -** a numeric type (real or integer), then the result of the addition addition -** or subtraction is a a copy of csr1.peerVal. -*/ -static void windowCodeRangeTest( - WindowCodeArg *p, - int op, /* OP_Ge, OP_Gt, or OP_Le */ - int csr1, /* Cursor number for cursor 1 */ - int regVal, /* Register containing non-negative number */ - int csr2, /* Cursor number for cursor 2 */ - int lbl /* Jump destination if condition is true */ -){ - Parse *pParse = p->pParse; - Vdbe *v = sqlite3GetVdbe(pParse); - ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */ - int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */ - int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */ - int regString = ++pParse->nMem; /* Reg. for constant value '' */ - int arith = OP_Add; /* OP_Add or OP_Subtract */ - int addrGe; /* Jump destination */ - - assert( op==OP_Ge || op==OP_Gt || op==OP_Le ); - assert( pOrderBy && pOrderBy->nExpr==1 ); - if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){ - switch( op ){ - case OP_Ge: op = OP_Le; break; - case OP_Gt: op = OP_Lt; break; - default: assert( op==OP_Le ); op = OP_Ge; break; - } - arith = OP_Subtract; - } - - /* Read the peer-value from each cursor into a register */ - windowReadPeerValues(p, csr1, reg1); - windowReadPeerValues(p, csr2, reg2); - - VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl", - reg1, (arith==OP_Add ? "+" : "-"), regVal, - ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2 - )); - - /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1). - ** This block adds (or subtracts for DESC) the numeric value in regVal - ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob), - ** then leave reg1 as it is. In pseudo-code, this is implemented as: - ** - ** if( reg1>='' ) goto addrGe; - ** reg1 = reg1 +/- regVal - ** addrGe: - ** - ** Since all strings and blobs are greater-than-or-equal-to an empty string, - ** the add/subtract is skipped for these, as required. If reg1 is a NULL, - ** then the arithmetic is performed, but since adding or subtracting from - ** NULL is always NULL anyway, this case is handled as required too. */ - sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); - addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1); - sqlite3VdbeJumpHere(v, addrGe); - - /* If the BIGNULL flag is set for the ORDER BY, then it is required to - ** consider NULL values to be larger than all other values, instead of - ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this - ** (and adding that capability causes a performance regression), so - ** instead if the BIGNULL flag is set then cases where either reg1 or - ** reg2 are NULL are handled separately in the following block. The code - ** generated is equivalent to: - ** - ** if( reg1 IS NULL ){ - ** if( op==OP_Ge ) goto lbl; - ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl; - ** if( op==OP_Le && reg2 IS NULL ) goto lbl; - ** }else if( reg2 IS NULL ){ - ** if( op==OP_Le ) goto lbl; - ** } - ** - ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is - ** not taken, control jumps over the comparison operator coded below this - ** block. */ - if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){ - /* This block runs if reg1 contains a NULL. */ - int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v); - switch( op ){ - case OP_Ge: - sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl); - break; - case OP_Gt: - sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl); - VdbeCoverage(v); - break; - case OP_Le: - sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); - VdbeCoverage(v); - break; - default: assert( op==OP_Lt ); /* no-op */ break; - } - sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); - - /* This block runs if reg1 is not NULL, but reg2 is. */ - sqlite3VdbeJumpHere(v, addr); - sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v); - if( op==OP_Gt || op==OP_Ge ){ - sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1); - } - } - - /* Compare registers reg2 and reg1, taking the jump if required. Note that - ** control skips over this test if the BIGNULL flag is set and either - ** reg1 or reg2 contain a NULL value. */ - sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); - - assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le ); - testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge); - testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt); - testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le); - testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt); - sqlite3ReleaseTempReg(pParse, reg1); - sqlite3ReleaseTempReg(pParse, reg2); - - VdbeModuleComment((v, "CodeRangeTest: end")); -} - -/* -** Helper function for sqlite3WindowCodeStep(). Each call to this function -** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE -** operation. Refer to the header comment for sqlite3WindowCodeStep() for -** details. -*/ -static int windowCodeOp( - WindowCodeArg *p, /* Context object */ - int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */ - int regCountdown, /* Register for OP_IfPos countdown */ - int jumpOnEof /* Jump here if stepped cursor reaches EOF */ -){ - int csr, reg; - Parse *pParse = p->pParse; - Window *pMWin = p->pMWin; - int ret = 0; - Vdbe *v = p->pVdbe; - int addrContinue = 0; - int bPeer = (pMWin->eFrmType!=TK_ROWS); - - int lblDone = sqlite3VdbeMakeLabel(pParse); - int addrNextRange = 0; - - /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame - ** starts with UNBOUNDED PRECEDING. */ - if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){ - assert( regCountdown==0 && jumpOnEof==0 ); - return 0; - } - - if( regCountdown>0 ){ - if( pMWin->eFrmType==TK_RANGE ){ - addrNextRange = sqlite3VdbeCurrentAddr(v); - assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP ); - if( op==WINDOW_AGGINVERSE ){ - if( pMWin->eStart==TK_FOLLOWING ){ - windowCodeRangeTest( - p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone - ); - }else{ - windowCodeRangeTest( - p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone - ); - } - }else{ - windowCodeRangeTest( - p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone - ); - } - }else{ - sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1); - VdbeCoverage(v); - } - } - - if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){ - windowAggFinal(p, 0); - } - addrContinue = sqlite3VdbeCurrentAddr(v); - - /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or - ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the - ** start cursor does not advance past the end cursor within the - ** temporary table. It otherwise might, if (a>b). */ - if( pMWin->eStart==pMWin->eEnd && regCountdown - && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE - ){ - int regRowid1 = sqlite3GetTempReg(pParse); - int regRowid2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1); - sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2); - sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1); - VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, regRowid1); - sqlite3ReleaseTempReg(pParse, regRowid2); - assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ); - } - - switch( op ){ - case WINDOW_RETURN_ROW: - csr = p->current.csr; - reg = p->current.reg; - windowReturnOneRow(p); - break; - - case WINDOW_AGGINVERSE: - csr = p->start.csr; - reg = p->start.reg; - if( pMWin->regStartRowid ){ - assert( pMWin->regEndRowid ); - sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1); - }else{ - windowAggStep(p, pMWin, csr, 1, p->regArg); - } - break; - - default: - assert( op==WINDOW_AGGSTEP ); - csr = p->end.csr; - reg = p->end.reg; - if( pMWin->regStartRowid ){ - assert( pMWin->regEndRowid ); - sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1); - }else{ - windowAggStep(p, pMWin, csr, 0, p->regArg); - } - break; - } - - if( op==p->eDelete ){ - sqlite3VdbeAddOp1(v, OP_Delete, csr); - sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); - } - - if( jumpOnEof ){ - sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - ret = sqlite3VdbeAddOp0(v, OP_Goto); - }else{ - sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer); - VdbeCoverage(v); - if( bPeer ){ - sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone); - } - } - - if( bPeer ){ - int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); - int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0); - windowReadPeerValues(p, csr, regTmp); - windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue); - sqlite3ReleaseTempRange(pParse, regTmp, nReg); - } - - if( addrNextRange ){ - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange); - } - sqlite3VdbeResolveLabel(v, lblDone); - return ret; -} - - -/* -** Allocate and return a duplicate of the Window object indicated by the -** third argument. Set the Window.pOwner field of the new object to -** pOwner. -*/ -SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){ - Window *pNew = 0; - if( ALWAYS(p) ){ - pNew = sqlite3DbMallocZero(db, sizeof(Window)); - if( pNew ){ - pNew->zName = sqlite3DbStrDup(db, p->zName); - pNew->zBase = sqlite3DbStrDup(db, p->zBase); - pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0); - pNew->pFunc = p->pFunc; - pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0); - pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0); - pNew->eFrmType = p->eFrmType; - pNew->eEnd = p->eEnd; - pNew->eStart = p->eStart; - pNew->eExclude = p->eExclude; - pNew->regResult = p->regResult; - pNew->regAccum = p->regAccum; - pNew->iArgCol = p->iArgCol; - pNew->iEphCsr = p->iEphCsr; - pNew->bExprArgs = p->bExprArgs; - pNew->pStart = sqlite3ExprDup(db, p->pStart, 0); - pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0); - pNew->pOwner = pOwner; - pNew->bImplicitFrame = p->bImplicitFrame; - } - } - return pNew; -} - -/* -** Return a copy of the linked list of Window objects passed as the -** second argument. -*/ -SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){ - Window *pWin; - Window *pRet = 0; - Window **pp = &pRet; - - for(pWin=p; pWin; pWin=pWin->pNextWin){ - *pp = sqlite3WindowDup(db, 0, pWin); - if( *pp==0 ) break; - pp = &((*pp)->pNextWin); - } - - return pRet; -} - -/* -** Return true if it can be determined at compile time that expression -** pExpr evaluates to a value that, when cast to an integer, is greater -** than zero. False otherwise. -** -** If an OOM error occurs, this function sets the Parse.db.mallocFailed -** flag and returns zero. -*/ -static int windowExprGtZero(Parse *pParse, Expr *pExpr){ - int ret = 0; - sqlite3 *db = pParse->db; - sqlite3_value *pVal = 0; - sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal); - if( pVal && sqlite3_value_int(pVal)>0 ){ - ret = 1; - } - sqlite3ValueFree(pVal); - return ret; -} - -/* -** sqlite3WhereBegin() has already been called for the SELECT statement -** passed as the second argument when this function is invoked. It generates -** code to populate the Window.regResult register for each window function -** and invoke the sub-routine at instruction addrGosub once for each row. -** sqlite3WhereEnd() is always called before returning. -** -** This function handles several different types of window frames, which -** require slightly different processing. The following pseudo code is -** used to implement window frames of the form: -** -** ROWS BETWEEN PRECEDING AND FOLLOWING -** -** Other window frame types use variants of the following: -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** -** if( first row of partition ){ -** // Rewind three cursors, all open on the eph table. -** Rewind(csrEnd); -** Rewind(csrStart); -** Rewind(csrCurrent); -** -** regEnd = // FOLLOWING expression -** regStart = // PRECEDING expression -** }else{ -** // First time this branch is taken, the eph table contains two -** // rows. The first row in the partition, which all three cursors -** // currently point to, and the following row. -** AGGSTEP -** if( (regEnd--)<=0 ){ -** RETURN_ROW -** if( (regStart--)<=0 ){ -** AGGINVERSE -** } -** } -** } -** } -** flush: -** AGGSTEP -** while( 1 ){ -** RETURN ROW -** if( csrCurrent is EOF ) break; -** if( (regStart--)<=0 ){ -** AggInverse(csrStart) -** Next(csrStart) -** } -** } -** -** The pseudo-code above uses the following shorthand: -** -** AGGSTEP: invoke the aggregate xStep() function for each window function -** with arguments read from the current row of cursor csrEnd, then -** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()). -** -** RETURN_ROW: return a row to the caller based on the contents of the -** current row of csrCurrent and the current state of all -** aggregates. Then step cursor csrCurrent forward one row. -** -** AGGINVERSE: invoke the aggregate xInverse() function for each window -** functions with arguments read from the current row of cursor -** csrStart. Then step csrStart forward one row. -** -** There are two other ROWS window frames that are handled significantly -** differently from the above - "BETWEEN PRECEDING AND PRECEDING" -** and "BETWEEN FOLLOWING AND FOLLOWING". These are special -** cases because they change the order in which the three cursors (csrStart, -** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that -** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these -** three. -** -** ROWS BETWEEN PRECEDING AND PRECEDING -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regEnd = -** regStart = -** }else{ -** if( (regEnd--)<=0 ){ -** AGGSTEP -** } -** RETURN_ROW -** if( (regStart--)<=0 ){ -** AGGINVERSE -** } -** } -** } -** flush: -** if( (regEnd--)<=0 ){ -** AGGSTEP -** } -** RETURN_ROW -** -** -** ROWS BETWEEN FOLLOWING AND FOLLOWING -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regEnd = -** regStart = regEnd - -** }else{ -** AGGSTEP -** if( (regEnd--)<=0 ){ -** RETURN_ROW -** } -** if( (regStart--)<=0 ){ -** AGGINVERSE -** } -** } -** } -** flush: -** AGGSTEP -** while( 1 ){ -** if( (regEnd--)<=0 ){ -** RETURN_ROW -** if( eof ) break; -** } -** if( (regStart--)<=0 ){ -** AGGINVERSE -** if( eof ) break -** } -** } -** while( !eof csrCurrent ){ -** RETURN_ROW -** } -** -** For the most part, the patterns above are adapted to support UNBOUNDED by -** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and -** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING". -** This is optimized of course - branches that will never be taken and -** conditions that are always true are omitted from the VM code. The only -** exceptional case is: -** -** ROWS BETWEEN FOLLOWING AND UNBOUNDED FOLLOWING -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regStart = -** }else{ -** AGGSTEP -** } -** } -** flush: -** AGGSTEP -** while( 1 ){ -** if( (regStart--)<=0 ){ -** AGGINVERSE -** if( eof ) break -** } -** RETURN_ROW -** } -** while( !eof csrCurrent ){ -** RETURN_ROW -** } -** -** Also requiring special handling are the cases: -** -** ROWS BETWEEN PRECEDING AND PRECEDING -** ROWS BETWEEN FOLLOWING AND FOLLOWING -** -** when (expr1 < expr2). This is detected at runtime, not by this function. -** To handle this case, the pseudo-code programs depicted above are modified -** slightly to be: -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regEnd = -** regStart = -** if( regEnd < regStart ){ -** RETURN_ROW -** delete eph table contents -** continue -** } -** ... -** -** The new "continue" statement in the above jumps to the next iteration -** of the outer loop - the one started by sqlite3WhereBegin(). -** -** The various GROUPS cases are implemented using the same patterns as -** ROWS. The VM code is modified slightly so that: -** -** 1. The else branch in the main loop is only taken if the row just -** added to the ephemeral table is the start of a new group. In -** other words, it becomes: -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regEnd = -** regStart = -** }else if( new group ){ -** ... -** } -** } -** -** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or -** AGGINVERSE step processes the current row of the relevant cursor and -** all subsequent rows belonging to the same group. -** -** RANGE window frames are a little different again. As for GROUPS, the -** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE -** deal in groups instead of rows. As for ROWS and GROUPS, there are three -** basic cases: -** -** RANGE BETWEEN PRECEDING AND FOLLOWING -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regEnd = -** regStart = -** }else{ -** AGGSTEP -** while( (csrCurrent.key + regEnd) < csrEnd.key ){ -** RETURN_ROW -** while( csrStart.key + regStart) < csrCurrent.key ){ -** AGGINVERSE -** } -** } -** } -** } -** flush: -** AGGSTEP -** while( 1 ){ -** RETURN ROW -** if( csrCurrent is EOF ) break; -** while( csrStart.key + regStart) < csrCurrent.key ){ -** AGGINVERSE -** } -** } -** } -** -** In the above notation, "csr.key" means the current value of the ORDER BY -** expression (there is only ever 1 for a RANGE that uses an FOLLOWING -** or PRECEDING AND PRECEDING -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regEnd = -** regStart = -** }else{ -** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ -** AGGSTEP -** } -** while( (csrStart.key + regStart) < csrCurrent.key ){ -** AGGINVERSE -** } -** RETURN_ROW -** } -** } -** flush: -** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ -** AGGSTEP -** } -** while( (csrStart.key + regStart) < csrCurrent.key ){ -** AGGINVERSE -** } -** RETURN_ROW -** -** RANGE BETWEEN FOLLOWING AND FOLLOWING -** -** ... loop started by sqlite3WhereBegin() ... -** if( new partition ){ -** Gosub flush -** } -** Insert new row into eph table. -** if( first row of partition ){ -** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) -** regEnd = -** regStart = -** }else{ -** AGGSTEP -** while( (csrCurrent.key + regEnd) < csrEnd.key ){ -** while( (csrCurrent.key + regStart) > csrStart.key ){ -** AGGINVERSE -** } -** RETURN_ROW -** } -** } -** } -** flush: -** AGGSTEP -** while( 1 ){ -** while( (csrCurrent.key + regStart) > csrStart.key ){ -** AGGINVERSE -** if( eof ) break "while( 1 )" loop. -** } -** RETURN_ROW -** } -** while( !eof csrCurrent ){ -** RETURN_ROW -** } -** -** The text above leaves out many details. Refer to the code and comments -** below for a more complete picture. -*/ -SQLITE_PRIVATE void sqlite3WindowCodeStep( - Parse *pParse, /* Parse context */ - Select *p, /* Rewritten SELECT statement */ - WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */ - int regGosub, /* Register for OP_Gosub */ - int addrGosub /* OP_Gosub here to return each row */ -){ - Window *pMWin = p->pWin; - ExprList *pOrderBy = pMWin->pOrderBy; - Vdbe *v = sqlite3GetVdbe(pParse); - int csrWrite; /* Cursor used to write to eph. table */ - int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */ - int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */ - int iInput; /* To iterate through sub cols */ - int addrNe; /* Address of OP_Ne */ - int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */ - int addrInteger = 0; /* Address of OP_Integer */ - int addrEmpty; /* Address of OP_Rewind in flush: */ - int regNew; /* Array of registers holding new input row */ - int regRecord; /* regNew array in record form */ - int regRowid; /* Rowid for regRecord in eph table */ - int regNewPeer = 0; /* Peer values for new row (part of regNew) */ - int regPeer = 0; /* Peer values for current row */ - int regFlushPart = 0; /* Register for "Gosub flush_partition" */ - WindowCodeArg s; /* Context object for sub-routines */ - int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */ - int regStart = 0; /* Value of PRECEDING */ - int regEnd = 0; /* Value of FOLLOWING */ - - assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT - || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED - ); - assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT - || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING - ); - assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT - || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES - || pMWin->eExclude==TK_NO - ); - - lblWhereEnd = sqlite3VdbeMakeLabel(pParse); - - /* Fill in the context object */ - memset(&s, 0, sizeof(WindowCodeArg)); - s.pParse = pParse; - s.pMWin = pMWin; - s.pVdbe = v; - s.regGosub = regGosub; - s.addrGosub = addrGosub; - s.current.csr = pMWin->iEphCsr; - csrWrite = s.current.csr+1; - s.start.csr = s.current.csr+2; - s.end.csr = s.current.csr+3; - - /* Figure out when rows may be deleted from the ephemeral table. There - ** are four options - they may never be deleted (eDelete==0), they may - ** be deleted as soon as they are no longer part of the window frame - ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row - ** has been returned to the caller (WINDOW_RETURN_ROW), or they may - ** be deleted after they enter the frame (WINDOW_AGGSTEP). */ - switch( pMWin->eStart ){ - case TK_FOLLOWING: - if( pMWin->eFrmType!=TK_RANGE - && windowExprGtZero(pParse, pMWin->pStart) - ){ - s.eDelete = WINDOW_RETURN_ROW; - } - break; - case TK_UNBOUNDED: - if( windowCacheFrame(pMWin)==0 ){ - if( pMWin->eEnd==TK_PRECEDING ){ - if( pMWin->eFrmType!=TK_RANGE - && windowExprGtZero(pParse, pMWin->pEnd) - ){ - s.eDelete = WINDOW_AGGSTEP; - } - }else{ - s.eDelete = WINDOW_RETURN_ROW; - } - } - break; - default: - s.eDelete = WINDOW_AGGINVERSE; - break; - } - - /* Allocate registers for the array of values from the sub-query, the - ** samve values in record form, and the rowid used to insert said record - ** into the ephemeral table. */ - regNew = pParse->nMem+1; - pParse->nMem += nInput; - regRecord = ++pParse->nMem; - regRowid = ++pParse->nMem; - - /* If the window frame contains an " PRECEDING" or " FOLLOWING" - ** clause, allocate registers to store the results of evaluating each - ** . */ - if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){ - regStart = ++pParse->nMem; - } - if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){ - regEnd = ++pParse->nMem; - } - - /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of - ** registers to store copies of the ORDER BY expressions (peer values) - ** for the main loop, and for each cursor (start, current and end). */ - if( pMWin->eFrmType!=TK_ROWS ){ - int nPeer = (pOrderBy ? pOrderBy->nExpr : 0); - regNewPeer = regNew + pMWin->nBufferCol; - if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr; - regPeer = pParse->nMem+1; pParse->nMem += nPeer; - s.start.reg = pParse->nMem+1; pParse->nMem += nPeer; - s.current.reg = pParse->nMem+1; pParse->nMem += nPeer; - s.end.reg = pParse->nMem+1; pParse->nMem += nPeer; - } - - /* Load the column values for the row returned by the sub-select - ** into an array of registers starting at regNew. Assemble them into - ** a record in register regRecord. */ - for(iInput=0; iInputpPartition ){ - int addr; - ExprList *pPart = pMWin->pPartition; - int nPart = pPart->nExpr; - int regNewPart = regNew + pMWin->nBufferCol; - KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0); - - regFlushPart = ++pParse->nMem; - addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart); - sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); - sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2); - VdbeCoverageEqNe(v); - addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart); - VdbeComment((v, "call flush_partition")); - sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1); - } - - /* Insert the new row into the ephemeral table */ - sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid); - addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid); - VdbeCoverageNeverNull(v); - - /* This block is run for the first row of each partition */ - s.regArg = windowInitAccum(pParse, pMWin); - - if( regStart ){ - sqlite3ExprCode(pParse, pMWin->pStart, regStart); - windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0)); - } - if( regEnd ){ - sqlite3ExprCode(pParse, pMWin->pEnd, regEnd); - windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0)); - } - - if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){ - int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le); - int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd); - VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound */ - VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */ - windowAggFinal(&s, 0); - sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1); - VdbeCoverageNeverTaken(v); - windowReturnOneRow(&s); - sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); - sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); - sqlite3VdbeJumpHere(v, addrGe); - } - if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){ - assert( pMWin->eEnd==TK_FOLLOWING ); - sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart); - } - - if( pMWin->eStart!=TK_UNBOUNDED ){ - sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1); - VdbeCoverageNeverTaken(v); - } - sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1); - VdbeCoverageNeverTaken(v); - sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1); - VdbeCoverageNeverTaken(v); - if( regPeer && pOrderBy ){ - sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1); - sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1); - sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1); - sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1); - } - - sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); - - sqlite3VdbeJumpHere(v, addrNe); - - /* Beginning of the block executed for the second and subsequent rows. */ - if( regPeer ){ - windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd); - } - if( pMWin->eStart==TK_FOLLOWING ){ - windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); - if( pMWin->eEnd!=TK_UNBOUNDED ){ - if( pMWin->eFrmType==TK_RANGE ){ - int lbl = sqlite3VdbeMakeLabel(pParse); - int addrNext = sqlite3VdbeCurrentAddr(v); - windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); - windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext); - sqlite3VdbeResolveLabel(v, lbl); - }else{ - windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0); - windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - } - } - }else - if( pMWin->eEnd==TK_PRECEDING ){ - int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); - windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); - if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); - if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - }else{ - int addr = 0; - windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); - if( pMWin->eEnd!=TK_UNBOUNDED ){ - if( pMWin->eFrmType==TK_RANGE ){ - int lbl = 0; - addr = sqlite3VdbeCurrentAddr(v); - if( regEnd ){ - lbl = sqlite3VdbeMakeLabel(pParse); - windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); - } - windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); - windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - if( regEnd ){ - sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); - sqlite3VdbeResolveLabel(v, lbl); - } - }else{ - if( regEnd ){ - addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1); - VdbeCoverage(v); - } - windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); - windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - if( regEnd ) sqlite3VdbeJumpHere(v, addr); - } - } - } - - /* End of the main input loop */ - sqlite3VdbeResolveLabel(v, lblWhereEnd); - sqlite3WhereEnd(pWInfo); - - /* Fall through */ - if( pMWin->pPartition ){ - addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart); - sqlite3VdbeJumpHere(v, addrGosubFlush); - } - - addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite); - VdbeCoverage(v); - if( pMWin->eEnd==TK_PRECEDING ){ - int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); - windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); - if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); - }else if( pMWin->eStart==TK_FOLLOWING ){ - int addrStart; - int addrBreak1; - int addrBreak2; - int addrBreak3; - windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); - if( pMWin->eFrmType==TK_RANGE ){ - addrStart = sqlite3VdbeCurrentAddr(v); - addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); - addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); - }else - if( pMWin->eEnd==TK_UNBOUNDED ){ - addrStart = sqlite3VdbeCurrentAddr(v); - addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1); - addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1); - }else{ - assert( pMWin->eEnd==TK_FOLLOWING ); - addrStart = sqlite3VdbeCurrentAddr(v); - addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1); - addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); - } - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); - sqlite3VdbeJumpHere(v, addrBreak2); - addrStart = sqlite3VdbeCurrentAddr(v); - addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); - sqlite3VdbeJumpHere(v, addrBreak1); - sqlite3VdbeJumpHere(v, addrBreak3); - }else{ - int addrBreak; - int addrStart; - windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); - addrStart = sqlite3VdbeCurrentAddr(v); - addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); - windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); - sqlite3VdbeJumpHere(v, addrBreak); - } - sqlite3VdbeJumpHere(v, addrEmpty); - - sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); - if( pMWin->pPartition ){ - if( pMWin->regStartRowid ){ - sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); - sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); - } - sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v)); - sqlite3VdbeAddOp1(v, OP_Return, regFlushPart); - } -} - -#endif /* SQLITE_OMIT_WINDOWFUNC */ - -/************** End of window.c **********************************************/ -/************** Begin file parse.c *******************************************/ -/* -** 2000-05-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. -** -************************************************************************* -** Driver template for the LEMON parser generator. -** -** The "lemon" program processes an LALR(1) input grammar file, then uses -** this template to construct a parser. The "lemon" program inserts text -** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the -** interstitial "-" characters) contained in this template is changed into -** the value of the %name directive from the grammar. Otherwise, the content -** of this template is copied straight through into the generate parser -** source file. -** -** The following is the concatenation of all %include directives from the -** input grammar file: -*/ -/* #include */ -/* #include */ -/************ Begin %include sections from the grammar ************************/ - -/* #include "sqliteInt.h" */ - -/* -** Disable all error recovery processing in the parser push-down -** automaton. -*/ -#define YYNOERRORRECOVERY 1 - -/* -** Make yytestcase() the same as testcase() -*/ -#define yytestcase(X) testcase(X) - -/* -** Indicate that sqlite3ParserFree() will never be called with a null -** pointer. -*/ -#define YYPARSEFREENEVERNULL 1 - -/* -** In the amalgamation, the parse.c file generated by lemon and the -** tokenize.c file are concatenated. In that case, sqlite3RunParser() -** has access to the the size of the yyParser object and so the parser -** engine can be allocated from stack. In that case, only the -** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked -** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be -** omitted. -*/ -#ifdef SQLITE_AMALGAMATION -# define sqlite3Parser_ENGINEALWAYSONSTACK 1 -#endif - -/* -** Alternative datatype for the argument to the malloc() routine passed -** into sqlite3ParserAlloc(). The default is size_t. -*/ -#define YYMALLOCARGTYPE u64 - -/* -** An instance of the following structure describes the event of a -** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT, -** TK_DELETE, or TK_INSTEAD. If the event is of the form -** -** UPDATE ON (a,b,c) -** -** Then the "b" IdList records the list "a,b,c". -*/ -struct TrigEvent { int a; IdList * b; }; - -struct FrameBound { int eType; Expr *pExpr; }; - -/* -** Disable lookaside memory allocation for objects that might be -** shared across database connections. -*/ -static void disableLookaside(Parse *pParse){ - sqlite3 *db = pParse->db; - pParse->disableLookaside++; - DisableLookaside; -} - -#if !defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) \ - && defined(SQLITE_UDL_CAPABLE_PARSER) -/* -** Issue an error message if an ORDER BY or LIMIT clause occurs on an -** UPDATE or DELETE statement. -*/ -static void updateDeleteLimitError( - Parse *pParse, - ExprList *pOrderBy, - Expr *pLimit -){ - if( pOrderBy ){ - sqlite3ErrorMsg(pParse, "syntax error near \"ORDER BY\""); - }else{ - sqlite3ErrorMsg(pParse, "syntax error near \"LIMIT\""); - } - sqlite3ExprListDelete(pParse->db, pOrderBy); - sqlite3ExprDelete(pParse->db, pLimit); -} -#endif /* SQLITE_ENABLE_UPDATE_DELETE_LIMIT */ - - - /* - ** For a compound SELECT statement, make sure p->pPrior->pNext==p for - ** all elements in the list. And make sure list length does not exceed - ** SQLITE_LIMIT_COMPOUND_SELECT. - */ - static void parserDoubleLinkSelect(Parse *pParse, Select *p){ - assert( p!=0 ); - if( p->pPrior ){ - Select *pNext = 0, *pLoop; - int mxSelect, cnt = 0; - for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){ - pLoop->pNext = pNext; - pLoop->selFlags |= SF_Compound; - } - if( (p->selFlags & SF_MultiValue)==0 && - (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 && - cnt>mxSelect - ){ - sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); - } - } - } - - - /* Construct a new Expr object from a single identifier. Use the - ** new Expr to populate pOut. Set the span of pOut to be the identifier - ** that created the expression. - */ - static Expr *tokenExpr(Parse *pParse, int op, Token t){ - Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1); - if( p ){ - /* memset(p, 0, sizeof(Expr)); */ - p->op = (u8)op; - p->affExpr = 0; - p->flags = EP_Leaf; - ExprClearVVAProperties(p); - p->iAgg = -1; - p->pLeft = p->pRight = 0; - p->x.pList = 0; - p->pAggInfo = 0; - p->y.pTab = 0; - p->op2 = 0; - p->iTable = 0; - p->iColumn = 0; - p->u.zToken = (char*)&p[1]; - memcpy(p->u.zToken, t.z, t.n); - p->u.zToken[t.n] = 0; - if( sqlite3Isquote(p->u.zToken[0]) ){ - sqlite3DequoteExpr(p); - } -#if SQLITE_MAX_EXPR_DEPTH>0 - p->nHeight = 1; -#endif - if( IN_RENAME_OBJECT ){ - return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t); - } - } - return p; - } - - - /* A routine to convert a binary TK_IS or TK_ISNOT expression into a - ** unary TK_ISNULL or TK_NOTNULL expression. */ - static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ - sqlite3 *db = pParse->db; - if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){ - pA->op = (u8)op; - sqlite3ExprDelete(db, pA->pRight); - pA->pRight = 0; - } - } - - /* Add a single new term to an ExprList that is used to store a - ** list of identifiers. Report an error if the ID list contains - ** a COLLATE clause or an ASC or DESC keyword, except ignore the - ** error while parsing a legacy schema. - */ - static ExprList *parserAddExprIdListTerm( - Parse *pParse, - ExprList *pPrior, - Token *pIdToken, - int hasCollate, - int sortOrder - ){ - ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0); - if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED) - && pParse->db->init.busy==0 - ){ - sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"", - pIdToken->n, pIdToken->z); - } - sqlite3ExprListSetName(pParse, p, pIdToken, 1); - return p; - } - -#if TK_SPAN>255 -# error too many tokens in the grammar -#endif -/**************** End of %include directives **********************************/ -/* These constants specify the various numeric values for terminal symbols -** in a format understandable to "makeheaders". This section is blank unless -** "lemon" is run with the "-m" command-line option. -***************** Begin makeheaders token definitions *************************/ -/**************** End makeheaders token definitions ***************************/ - -/* The next sections is a series of control #defines. -** various aspects of the generated parser. -** YYCODETYPE is the data type used to store the integer codes -** that represent terminal and non-terminal symbols. -** "unsigned char" is used if there are fewer than -** 256 symbols. Larger types otherwise. -** YYNOCODE is a number of type YYCODETYPE that is not used for -** any terminal or nonterminal symbol. -** YYFALLBACK If defined, this indicates that one or more tokens -** (also known as: "terminal symbols") have fall-back -** values which should be used if the original symbol -** would not parse. This permits keywords to sometimes -** be used as identifiers, for example. -** YYACTIONTYPE is the data type used for "action codes" - numbers -** that indicate what to do in response to the next -** token. -** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal -** symbols. Background: A "minor type" is a semantic -** value associated with a terminal or non-terminal -** symbols. For example, for an "ID" terminal symbol, -** the minor type might be the name of the identifier. -** Each non-terminal can have a different minor type. -** Terminal symbols all have the same minor type, though. -** This macros defines the minor type for terminal -** symbols. -** YYMINORTYPE is the data type used for all minor types. -** This is typically a union of many types, one of -** which is sqlite3ParserTOKENTYPE. The entry in the union -** for terminal symbols is called "yy0". -** YYSTACKDEPTH is the maximum depth of the parser's stack. If -** zero the stack is dynamically sized using realloc() -** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument -** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument -** sqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter -** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser -** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser -** sqlite3ParserCTX_* As sqlite3ParserARG_ except for %extra_context -** YYERRORSYMBOL is the code number of the error symbol. If not -** defined, then do no error processing. -** YYNSTATE the combined number of states. -** YYNRULE the number of rules in the grammar -** YYNTOKEN Number of terminal symbols -** YY_MAX_SHIFT Maximum value for shift actions -** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions -** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions -** YY_ERROR_ACTION The yy_action[] code for syntax error -** YY_ACCEPT_ACTION The yy_action[] code for accept -** YY_NO_ACTION The yy_action[] code for no-op -** YY_MIN_REDUCE Minimum value for reduce actions -** YY_MAX_REDUCE Maximum value for reduce actions -*/ -#ifndef INTERFACE -# define INTERFACE 1 -#endif -/************* Begin control #defines *****************************************/ -#define YYCODETYPE unsigned short int -#define YYNOCODE 310 -#define YYACTIONTYPE unsigned short int -#define YYWILDCARD 100 -#define sqlite3ParserTOKENTYPE Token -typedef union { - int yyinit; - sqlite3ParserTOKENTYPE yy0; - SrcList* yy47; - u8 yy58; - struct FrameBound yy77; - With* yy131; - int yy192; - Expr* yy202; - struct {int value; int mask;} yy207; - struct TrigEvent yy230; - ExprList* yy242; - Window* yy303; - Upsert* yy318; - const char* yy436; - TriggerStep* yy447; - Select* yy539; - IdList* yy600; -} YYMINORTYPE; -#ifndef YYSTACKDEPTH -#define YYSTACKDEPTH 100 -#endif -#define sqlite3ParserARG_SDECL -#define sqlite3ParserARG_PDECL -#define sqlite3ParserARG_PARAM -#define sqlite3ParserARG_FETCH -#define sqlite3ParserARG_STORE -#define sqlite3ParserCTX_SDECL Parse *pParse; -#define sqlite3ParserCTX_PDECL ,Parse *pParse -#define sqlite3ParserCTX_PARAM ,pParse -#define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse; -#define sqlite3ParserCTX_STORE yypParser->pParse=pParse; -#define YYFALLBACK 1 -#define YYNSTATE 553 -#define YYNRULE 385 -#define YYNRULE_WITH_ACTION 325 -#define YYNTOKEN 181 -#define YY_MAX_SHIFT 552 -#define YY_MIN_SHIFTREDUCE 803 -#define YY_MAX_SHIFTREDUCE 1187 -#define YY_ERROR_ACTION 1188 -#define YY_ACCEPT_ACTION 1189 -#define YY_NO_ACTION 1190 -#define YY_MIN_REDUCE 1191 -#define YY_MAX_REDUCE 1575 -/************* End control #defines *******************************************/ -#define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0]))) - -/* Define the yytestcase() macro to be a no-op if is not already defined -** otherwise. -** -** Applications can choose to define yytestcase() in the %include section -** to a macro that can assist in verifying code coverage. For production -** code the yytestcase() macro should be turned off. But it is useful -** for testing. -*/ -#ifndef yytestcase -# define yytestcase(X) -#endif - - -/* Next are the tables used to determine what action to take based on the -** current state and lookahead token. These tables are used to implement -** functions that take a state number and lookahead value and return an -** action integer. -** -** Suppose the action integer is N. Then the action is determined as -** follows -** -** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead -** token onto the stack and goto state N. -** -** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then -** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE. -** -** N == YY_ERROR_ACTION A syntax error has occurred. -** -** N == YY_ACCEPT_ACTION The parser accepts its input. -** -** N == YY_NO_ACTION No such action. Denotes unused -** slots in the yy_action[] table. -** -** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE -** and YY_MAX_REDUCE -** -** The action table is constructed as a single large table named yy_action[]. -** Given state S and lookahead X, the action is computed as either: -** -** (A) N = yy_action[ yy_shift_ofst[S] + X ] -** (B) N = yy_default[S] -** -** The (A) formula is preferred. The B formula is used instead if -** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X. -** -** The formulas above are for computing the action when the lookahead is -** a terminal symbol. If the lookahead is a non-terminal (as occurs after -** a reduce action) then the yy_reduce_ofst[] array is used in place of -** the yy_shift_ofst[] array. -** -** The following are the tables generated in this section: -** -** yy_action[] A single table containing all actions. -** yy_lookahead[] A table containing the lookahead for each entry in -** yy_action. Used to detect hash collisions. -** yy_shift_ofst[] For each state, the offset into yy_action for -** shifting terminals. -** yy_reduce_ofst[] For each state, the offset into yy_action for -** shifting non-terminals after a reduce. -** yy_default[] Default action for each state. -** -*********** Begin parsing tables **********************************************/ -#define YY_ACTTAB_COUNT (1962) -static const YYACTIONTYPE yy_action[] = { - /* 0 */ 546, 1222, 546, 451, 1260, 546, 1239, 546, 114, 111, - /* 10 */ 211, 546, 1537, 546, 1260, 523, 114, 111, 211, 392, - /* 20 */ 1232, 344, 42, 42, 42, 42, 1225, 42, 42, 71, - /* 30 */ 71, 937, 1224, 71, 71, 71, 71, 1462, 1493, 938, - /* 40 */ 820, 453, 6, 121, 122, 112, 1165, 1165, 1006, 1009, - /* 50 */ 999, 999, 119, 119, 120, 120, 120, 120, 1543, 392, - /* 60 */ 1358, 1517, 552, 2, 1193, 194, 528, 436, 143, 291, - /* 70 */ 528, 136, 528, 371, 261, 504, 272, 385, 1273, 527, - /* 80 */ 503, 493, 164, 121, 122, 112, 1165, 1165, 1006, 1009, - /* 90 */ 999, 999, 119, 119, 120, 120, 120, 120, 1358, 442, - /* 100 */ 1514, 118, 118, 118, 118, 117, 117, 116, 116, 116, - /* 110 */ 115, 424, 266, 266, 266, 266, 1498, 358, 1500, 435, - /* 120 */ 357, 1498, 517, 524, 1485, 543, 1114, 543, 1114, 392, - /* 130 */ 405, 241, 208, 114, 111, 211, 98, 290, 537, 221, - /* 140 */ 1029, 118, 118, 118, 118, 117, 117, 116, 116, 116, - /* 150 */ 115, 424, 1142, 121, 122, 112, 1165, 1165, 1006, 1009, - /* 160 */ 999, 999, 119, 119, 120, 120, 120, 120, 406, 428, - /* 170 */ 117, 117, 116, 116, 116, 115, 424, 1418, 468, 123, - /* 180 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115, - /* 190 */ 424, 116, 116, 116, 115, 424, 540, 540, 540, 392, - /* 200 */ 505, 120, 120, 120, 120, 113, 1051, 1142, 1143, 1144, - /* 210 */ 1051, 118, 118, 118, 118, 117, 117, 116, 116, 116, - /* 220 */ 115, 424, 1461, 121, 122, 112, 1165, 1165, 1006, 1009, - /* 230 */ 999, 999, 119, 119, 120, 120, 120, 120, 392, 444, - /* 240 */ 316, 83, 463, 81, 359, 382, 1142, 80, 118, 118, - /* 250 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 179, - /* 260 */ 434, 424, 121, 122, 112, 1165, 1165, 1006, 1009, 999, - /* 270 */ 999, 119, 119, 120, 120, 120, 120, 434, 433, 266, - /* 280 */ 266, 118, 118, 118, 118, 117, 117, 116, 116, 116, - /* 290 */ 115, 424, 543, 1109, 903, 506, 1142, 114, 111, 211, - /* 300 */ 1431, 1142, 1143, 1144, 206, 491, 1109, 392, 449, 1109, - /* 310 */ 545, 330, 120, 120, 120, 120, 298, 1431, 1433, 17, - /* 320 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115, - /* 330 */ 424, 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999, - /* 340 */ 119, 119, 120, 120, 120, 120, 392, 1358, 434, 1142, - /* 350 */ 482, 1142, 1143, 1144, 996, 996, 1007, 1010, 445, 118, - /* 360 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 424, - /* 370 */ 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119, - /* 380 */ 119, 120, 120, 120, 120, 1054, 1054, 465, 1431, 118, - /* 390 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 424, - /* 400 */ 1142, 451, 546, 1426, 1142, 1143, 1144, 233, 966, 1142, - /* 410 */ 481, 478, 477, 171, 360, 392, 164, 407, 414, 842, - /* 420 */ 476, 164, 185, 334, 71, 71, 1243, 1000, 118, 118, - /* 430 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 121, - /* 440 */ 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119, 119, - /* 450 */ 120, 120, 120, 120, 392, 1142, 1143, 1144, 835, 12, - /* 460 */ 314, 509, 163, 356, 1142, 1143, 1144, 114, 111, 211, - /* 470 */ 508, 290, 537, 546, 276, 180, 290, 537, 121, 122, - /* 480 */ 112, 1165, 1165, 1006, 1009, 999, 999, 119, 119, 120, - /* 490 */ 120, 120, 120, 345, 484, 71, 71, 118, 118, 118, - /* 500 */ 118, 117, 117, 116, 116, 116, 115, 424, 1142, 209, - /* 510 */ 411, 523, 1142, 1109, 1571, 378, 252, 269, 342, 487, - /* 520 */ 337, 486, 238, 392, 513, 364, 1109, 1127, 333, 1109, - /* 530 */ 191, 409, 286, 32, 457, 443, 118, 118, 118, 118, - /* 540 */ 117, 117, 116, 116, 116, 115, 424, 121, 122, 112, - /* 550 */ 1165, 1165, 1006, 1009, 999, 999, 119, 119, 120, 120, - /* 560 */ 120, 120, 392, 1142, 1143, 1144, 987, 1142, 1143, 1144, - /* 570 */ 1142, 233, 492, 1492, 481, 478, 477, 6, 163, 546, - /* 580 */ 512, 546, 115, 424, 476, 5, 121, 122, 112, 1165, - /* 590 */ 1165, 1006, 1009, 999, 999, 119, 119, 120, 120, 120, - /* 600 */ 120, 13, 13, 13, 13, 118, 118, 118, 118, 117, - /* 610 */ 117, 116, 116, 116, 115, 424, 403, 502, 408, 546, - /* 620 */ 1486, 544, 1142, 892, 892, 1142, 1143, 1144, 1473, 1142, - /* 630 */ 275, 392, 808, 809, 810, 971, 422, 422, 422, 16, - /* 640 */ 16, 55, 55, 1242, 118, 118, 118, 118, 117, 117, - /* 650 */ 116, 116, 116, 115, 424, 121, 122, 112, 1165, 1165, - /* 660 */ 1006, 1009, 999, 999, 119, 119, 120, 120, 120, 120, - /* 670 */ 392, 1189, 1, 1, 552, 2, 1193, 1142, 1143, 1144, - /* 680 */ 194, 291, 898, 136, 1142, 1143, 1144, 897, 521, 1492, - /* 690 */ 1273, 3, 380, 6, 121, 122, 112, 1165, 1165, 1006, - /* 700 */ 1009, 999, 999, 119, 119, 120, 120, 120, 120, 858, - /* 710 */ 546, 924, 546, 118, 118, 118, 118, 117, 117, 116, - /* 720 */ 116, 116, 115, 424, 266, 266, 1092, 1569, 1142, 551, - /* 730 */ 1569, 1193, 13, 13, 13, 13, 291, 543, 136, 392, - /* 740 */ 485, 421, 420, 966, 344, 1273, 468, 410, 859, 279, - /* 750 */ 140, 221, 118, 118, 118, 118, 117, 117, 116, 116, - /* 760 */ 116, 115, 424, 121, 122, 112, 1165, 1165, 1006, 1009, - /* 770 */ 999, 999, 119, 119, 120, 120, 120, 120, 546, 266, - /* 780 */ 266, 428, 392, 1142, 1143, 1144, 1172, 830, 1172, 468, - /* 790 */ 431, 145, 543, 1146, 401, 314, 439, 302, 838, 1490, - /* 800 */ 71, 71, 412, 6, 1090, 473, 221, 100, 112, 1165, - /* 810 */ 1165, 1006, 1009, 999, 999, 119, 119, 120, 120, 120, - /* 820 */ 120, 118, 118, 118, 118, 117, 117, 116, 116, 116, - /* 830 */ 115, 424, 237, 1425, 546, 451, 428, 287, 986, 546, - /* 840 */ 236, 235, 234, 830, 97, 529, 429, 1265, 1265, 1146, - /* 850 */ 494, 307, 430, 838, 977, 546, 71, 71, 976, 1241, - /* 860 */ 546, 51, 51, 300, 118, 118, 118, 118, 117, 117, - /* 870 */ 116, 116, 116, 115, 424, 194, 103, 70, 70, 266, - /* 880 */ 266, 546, 71, 71, 266, 266, 30, 391, 344, 976, - /* 890 */ 976, 978, 543, 528, 1109, 328, 392, 543, 495, 397, - /* 900 */ 1470, 195, 530, 13, 13, 1358, 240, 1109, 277, 280, - /* 910 */ 1109, 280, 304, 457, 306, 333, 392, 31, 188, 419, - /* 920 */ 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119, - /* 930 */ 119, 120, 120, 120, 120, 142, 392, 365, 457, 986, - /* 940 */ 121, 122, 112, 1165, 1165, 1006, 1009, 999, 999, 119, - /* 950 */ 119, 120, 120, 120, 120, 977, 323, 1142, 326, 976, - /* 960 */ 121, 110, 112, 1165, 1165, 1006, 1009, 999, 999, 119, - /* 970 */ 119, 120, 120, 120, 120, 464, 377, 1185, 118, 118, - /* 980 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 1142, - /* 990 */ 976, 976, 978, 305, 9, 366, 244, 362, 118, 118, - /* 1000 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 313, - /* 1010 */ 546, 344, 1142, 1143, 1144, 299, 290, 537, 118, 118, - /* 1020 */ 118, 118, 117, 117, 116, 116, 116, 115, 424, 1263, - /* 1030 */ 1263, 1163, 13, 13, 278, 421, 420, 468, 392, 923, - /* 1040 */ 260, 260, 289, 1169, 1142, 1143, 1144, 189, 1171, 266, - /* 1050 */ 266, 468, 390, 543, 1186, 546, 1170, 263, 144, 489, - /* 1060 */ 922, 546, 543, 122, 112, 1165, 1165, 1006, 1009, 999, - /* 1070 */ 999, 119, 119, 120, 120, 120, 120, 71, 71, 1142, - /* 1080 */ 1172, 1272, 1172, 13, 13, 898, 1070, 1163, 546, 468, - /* 1090 */ 897, 107, 538, 1491, 4, 1268, 1109, 6, 525, 1049, - /* 1100 */ 12, 1071, 1092, 1570, 312, 455, 1570, 520, 541, 1109, - /* 1110 */ 56, 56, 1109, 1489, 423, 1358, 1072, 6, 345, 285, - /* 1120 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115, - /* 1130 */ 424, 425, 1271, 321, 1142, 1143, 1144, 878, 266, 266, - /* 1140 */ 1277, 107, 538, 535, 4, 1488, 293, 879, 1211, 6, - /* 1150 */ 210, 543, 543, 164, 294, 496, 416, 204, 541, 267, - /* 1160 */ 267, 1214, 398, 511, 499, 204, 266, 266, 396, 531, - /* 1170 */ 8, 986, 543, 519, 546, 922, 458, 105, 105, 543, - /* 1180 */ 1090, 425, 266, 266, 106, 417, 425, 548, 547, 266, - /* 1190 */ 266, 976, 518, 535, 1373, 543, 15, 15, 266, 266, - /* 1200 */ 456, 1120, 543, 266, 266, 1070, 1372, 515, 290, 537, - /* 1210 */ 546, 543, 514, 97, 444, 316, 543, 546, 922, 125, - /* 1220 */ 1071, 986, 976, 976, 978, 979, 27, 105, 105, 401, - /* 1230 */ 343, 1511, 44, 44, 106, 1072, 425, 548, 547, 57, - /* 1240 */ 57, 976, 343, 1511, 107, 538, 546, 4, 462, 401, - /* 1250 */ 214, 1120, 459, 297, 377, 1091, 534, 1309, 546, 539, - /* 1260 */ 398, 541, 290, 537, 104, 244, 102, 526, 58, 58, - /* 1270 */ 546, 199, 976, 976, 978, 979, 27, 1516, 1131, 427, - /* 1280 */ 59, 59, 270, 237, 425, 138, 95, 375, 375, 374, - /* 1290 */ 255, 372, 60, 60, 817, 1180, 535, 546, 273, 546, - /* 1300 */ 1163, 1308, 389, 388, 546, 438, 546, 215, 210, 296, - /* 1310 */ 515, 849, 546, 265, 208, 516, 1476, 295, 274, 61, - /* 1320 */ 61, 62, 62, 308, 986, 109, 45, 45, 46, 46, - /* 1330 */ 105, 105, 1186, 922, 47, 47, 341, 106, 546, 425, - /* 1340 */ 548, 547, 1542, 546, 976, 867, 340, 217, 546, 937, - /* 1350 */ 397, 107, 538, 218, 4, 156, 1163, 938, 158, 546, - /* 1360 */ 49, 49, 1162, 546, 268, 50, 50, 546, 541, 1450, - /* 1370 */ 63, 63, 546, 1449, 216, 976, 976, 978, 979, 27, - /* 1380 */ 446, 64, 64, 546, 460, 65, 65, 546, 318, 14, - /* 1390 */ 14, 425, 1305, 546, 66, 66, 1087, 546, 141, 379, - /* 1400 */ 38, 546, 963, 535, 322, 127, 127, 546, 393, 67, - /* 1410 */ 67, 546, 325, 290, 537, 52, 52, 515, 546, 68, - /* 1420 */ 68, 845, 514, 69, 69, 399, 165, 857, 856, 53, - /* 1430 */ 53, 986, 311, 151, 151, 97, 432, 105, 105, 327, - /* 1440 */ 152, 152, 526, 1048, 106, 1048, 425, 548, 547, 1131, - /* 1450 */ 427, 976, 1032, 270, 968, 239, 329, 243, 375, 375, - /* 1460 */ 374, 255, 372, 940, 941, 817, 1296, 546, 220, 546, - /* 1470 */ 107, 538, 546, 4, 546, 1256, 199, 845, 215, 1036, - /* 1480 */ 296, 1530, 976, 976, 978, 979, 27, 541, 295, 76, - /* 1490 */ 76, 54, 54, 980, 72, 72, 128, 128, 864, 865, - /* 1500 */ 107, 538, 546, 4, 1047, 546, 1047, 533, 469, 546, - /* 1510 */ 425, 546, 450, 1240, 546, 243, 546, 541, 217, 546, - /* 1520 */ 452, 197, 535, 243, 73, 73, 156, 129, 129, 158, - /* 1530 */ 336, 130, 130, 126, 126, 1036, 150, 150, 149, 149, - /* 1540 */ 425, 134, 134, 317, 474, 216, 97, 239, 331, 980, - /* 1550 */ 986, 97, 535, 346, 347, 546, 105, 105, 902, 931, - /* 1560 */ 546, 895, 243, 106, 109, 425, 548, 547, 546, 1505, - /* 1570 */ 976, 828, 99, 538, 139, 4, 546, 133, 133, 393, - /* 1580 */ 986, 1317, 131, 131, 290, 537, 105, 105, 1357, 541, - /* 1590 */ 132, 132, 1292, 106, 1303, 425, 548, 547, 75, 75, - /* 1600 */ 976, 976, 976, 978, 979, 27, 546, 432, 896, 1289, - /* 1610 */ 532, 109, 425, 1363, 546, 1221, 1213, 1202, 258, 546, - /* 1620 */ 349, 546, 1201, 11, 535, 1203, 1524, 351, 77, 77, - /* 1630 */ 376, 976, 976, 978, 979, 27, 74, 74, 353, 213, - /* 1640 */ 301, 43, 43, 48, 48, 437, 310, 201, 303, 1350, - /* 1650 */ 315, 355, 986, 454, 479, 1239, 339, 192, 105, 105, - /* 1660 */ 1422, 1421, 193, 536, 205, 106, 1527, 425, 548, 547, - /* 1670 */ 1180, 167, 976, 270, 247, 1469, 1467, 1177, 375, 375, - /* 1680 */ 374, 255, 372, 200, 369, 817, 400, 83, 79, 82, - /* 1690 */ 1427, 448, 177, 95, 1342, 161, 169, 1339, 215, 440, - /* 1700 */ 296, 172, 173, 976, 976, 978, 979, 27, 295, 174, - /* 1710 */ 175, 441, 472, 223, 1347, 383, 35, 381, 36, 461, - /* 1720 */ 88, 1353, 181, 447, 384, 1416, 227, 467, 259, 229, - /* 1730 */ 186, 488, 470, 324, 1250, 230, 231, 320, 217, 1204, - /* 1740 */ 1438, 1259, 386, 1258, 413, 90, 156, 849, 1541, 158, - /* 1750 */ 206, 415, 1540, 507, 1300, 1257, 94, 348, 1229, 1301, - /* 1760 */ 387, 1510, 1228, 338, 1227, 216, 350, 1539, 498, 283, - /* 1770 */ 284, 1249, 501, 1299, 352, 245, 246, 418, 1298, 354, - /* 1780 */ 1496, 1495, 124, 10, 526, 363, 101, 1324, 253, 96, - /* 1790 */ 510, 1210, 34, 549, 1137, 254, 256, 257, 166, 393, - /* 1800 */ 550, 1199, 1282, 361, 290, 537, 1281, 196, 367, 368, - /* 1810 */ 1194, 153, 1454, 137, 281, 1323, 1455, 804, 154, 426, - /* 1820 */ 198, 155, 1453, 1452, 292, 212, 202, 432, 1402, 203, - /* 1830 */ 271, 135, 288, 78, 1046, 1044, 960, 168, 157, 881, - /* 1840 */ 170, 219, 309, 222, 1060, 176, 964, 159, 402, 84, - /* 1850 */ 178, 404, 85, 86, 87, 160, 1063, 224, 394, 395, - /* 1860 */ 225, 1059, 146, 18, 226, 319, 243, 1174, 466, 228, - /* 1870 */ 1052, 182, 183, 37, 819, 471, 340, 232, 332, 483, - /* 1880 */ 184, 89, 162, 19, 20, 475, 91, 480, 847, 335, - /* 1890 */ 147, 860, 282, 92, 490, 93, 1125, 148, 1012, 1095, - /* 1900 */ 39, 497, 1096, 40, 500, 262, 207, 264, 930, 187, - /* 1910 */ 925, 109, 1111, 1115, 1113, 7, 1099, 242, 33, 1119, - /* 1920 */ 21, 522, 22, 23, 24, 1118, 25, 190, 97, 26, - /* 1930 */ 1027, 1013, 1011, 1015, 1069, 1016, 1068, 249, 248, 28, - /* 1940 */ 41, 891, 981, 829, 108, 29, 250, 542, 251, 370, - /* 1950 */ 373, 1133, 1132, 1190, 1190, 1190, 1190, 1190, 1190, 1190, - /* 1960 */ 1532, 1531, -}; -static const YYCODETYPE yy_lookahead[] = { - /* 0 */ 189, 211, 189, 189, 218, 189, 220, 189, 267, 268, - /* 10 */ 269, 189, 210, 189, 228, 189, 267, 268, 269, 19, - /* 20 */ 218, 189, 211, 212, 211, 212, 211, 211, 212, 211, - /* 30 */ 212, 31, 211, 211, 212, 211, 212, 288, 300, 39, - /* 40 */ 21, 189, 304, 43, 44, 45, 46, 47, 48, 49, - /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 225, 19, - /* 60 */ 189, 183, 184, 185, 186, 189, 248, 263, 236, 191, - /* 70 */ 248, 193, 248, 197, 208, 257, 262, 201, 200, 257, - /* 80 */ 200, 257, 81, 43, 44, 45, 46, 47, 48, 49, - /* 90 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 80, - /* 100 */ 189, 101, 102, 103, 104, 105, 106, 107, 108, 109, - /* 110 */ 110, 111, 234, 235, 234, 235, 305, 306, 305, 118, - /* 120 */ 307, 305, 306, 297, 298, 247, 86, 247, 88, 19, - /* 130 */ 259, 251, 252, 267, 268, 269, 26, 136, 137, 261, - /* 140 */ 121, 101, 102, 103, 104, 105, 106, 107, 108, 109, - /* 150 */ 110, 111, 59, 43, 44, 45, 46, 47, 48, 49, - /* 160 */ 50, 51, 52, 53, 54, 55, 56, 57, 259, 291, - /* 170 */ 105, 106, 107, 108, 109, 110, 111, 158, 189, 69, - /* 180 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, - /* 190 */ 111, 107, 108, 109, 110, 111, 205, 206, 207, 19, - /* 200 */ 19, 54, 55, 56, 57, 58, 29, 114, 115, 116, - /* 210 */ 33, 101, 102, 103, 104, 105, 106, 107, 108, 109, - /* 220 */ 110, 111, 233, 43, 44, 45, 46, 47, 48, 49, - /* 230 */ 50, 51, 52, 53, 54, 55, 56, 57, 19, 126, - /* 240 */ 127, 148, 65, 24, 214, 200, 59, 67, 101, 102, - /* 250 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 22, - /* 260 */ 189, 111, 43, 44, 45, 46, 47, 48, 49, 50, - /* 270 */ 51, 52, 53, 54, 55, 56, 57, 206, 207, 234, - /* 280 */ 235, 101, 102, 103, 104, 105, 106, 107, 108, 109, - /* 290 */ 110, 111, 247, 76, 107, 114, 59, 267, 268, 269, - /* 300 */ 189, 114, 115, 116, 162, 163, 89, 19, 263, 92, - /* 310 */ 189, 23, 54, 55, 56, 57, 189, 206, 207, 22, - /* 320 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, - /* 330 */ 111, 43, 44, 45, 46, 47, 48, 49, 50, 51, - /* 340 */ 52, 53, 54, 55, 56, 57, 19, 189, 277, 59, - /* 350 */ 23, 114, 115, 116, 46, 47, 48, 49, 61, 101, - /* 360 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - /* 370 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 380 */ 53, 54, 55, 56, 57, 125, 126, 127, 277, 101, - /* 390 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - /* 400 */ 59, 189, 189, 276, 114, 115, 116, 117, 73, 59, - /* 410 */ 120, 121, 122, 72, 214, 19, 81, 259, 19, 23, - /* 420 */ 130, 81, 72, 24, 211, 212, 221, 119, 101, 102, - /* 430 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 43, - /* 440 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - /* 450 */ 54, 55, 56, 57, 19, 114, 115, 116, 23, 208, - /* 460 */ 125, 248, 189, 189, 114, 115, 116, 267, 268, 269, - /* 470 */ 189, 136, 137, 189, 262, 22, 136, 137, 43, 44, - /* 480 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, - /* 490 */ 55, 56, 57, 189, 95, 211, 212, 101, 102, 103, - /* 500 */ 104, 105, 106, 107, 108, 109, 110, 111, 59, 189, - /* 510 */ 111, 189, 59, 76, 294, 295, 117, 118, 119, 120, - /* 520 */ 121, 122, 123, 19, 87, 189, 89, 23, 129, 92, - /* 530 */ 279, 227, 248, 22, 189, 284, 101, 102, 103, 104, - /* 540 */ 105, 106, 107, 108, 109, 110, 111, 43, 44, 45, - /* 550 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - /* 560 */ 56, 57, 19, 114, 115, 116, 23, 114, 115, 116, - /* 570 */ 59, 117, 299, 300, 120, 121, 122, 304, 189, 189, - /* 580 */ 143, 189, 110, 111, 130, 22, 43, 44, 45, 46, - /* 590 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - /* 600 */ 57, 211, 212, 211, 212, 101, 102, 103, 104, 105, - /* 610 */ 106, 107, 108, 109, 110, 111, 226, 189, 226, 189, - /* 620 */ 298, 132, 59, 134, 135, 114, 115, 116, 189, 59, - /* 630 */ 285, 19, 7, 8, 9, 23, 205, 206, 207, 211, - /* 640 */ 212, 211, 212, 221, 101, 102, 103, 104, 105, 106, - /* 650 */ 107, 108, 109, 110, 111, 43, 44, 45, 46, 47, - /* 660 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, - /* 670 */ 19, 181, 182, 183, 184, 185, 186, 114, 115, 116, - /* 680 */ 189, 191, 133, 193, 114, 115, 116, 138, 299, 300, - /* 690 */ 200, 22, 201, 304, 43, 44, 45, 46, 47, 48, - /* 700 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, - /* 710 */ 189, 141, 189, 101, 102, 103, 104, 105, 106, 107, - /* 720 */ 108, 109, 110, 111, 234, 235, 22, 23, 59, 184, - /* 730 */ 26, 186, 211, 212, 211, 212, 191, 247, 193, 19, - /* 740 */ 66, 105, 106, 73, 189, 200, 189, 226, 74, 226, - /* 750 */ 22, 261, 101, 102, 103, 104, 105, 106, 107, 108, - /* 760 */ 109, 110, 111, 43, 44, 45, 46, 47, 48, 49, - /* 770 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 234, - /* 780 */ 235, 291, 19, 114, 115, 116, 150, 59, 152, 189, - /* 790 */ 233, 236, 247, 59, 189, 125, 126, 127, 59, 300, - /* 800 */ 211, 212, 128, 304, 100, 19, 261, 156, 45, 46, - /* 810 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - /* 820 */ 57, 101, 102, 103, 104, 105, 106, 107, 108, 109, - /* 830 */ 110, 111, 46, 233, 189, 189, 291, 248, 99, 189, - /* 840 */ 125, 126, 127, 115, 26, 200, 289, 230, 231, 115, - /* 850 */ 200, 16, 189, 114, 115, 189, 211, 212, 119, 221, - /* 860 */ 189, 211, 212, 258, 101, 102, 103, 104, 105, 106, - /* 870 */ 107, 108, 109, 110, 111, 189, 156, 211, 212, 234, - /* 880 */ 235, 189, 211, 212, 234, 235, 22, 201, 189, 150, - /* 890 */ 151, 152, 247, 248, 76, 16, 19, 247, 248, 113, - /* 900 */ 189, 24, 257, 211, 212, 189, 26, 89, 262, 223, - /* 910 */ 92, 225, 77, 189, 79, 129, 19, 53, 226, 248, - /* 920 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 930 */ 53, 54, 55, 56, 57, 236, 19, 271, 189, 99, - /* 940 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 950 */ 53, 54, 55, 56, 57, 115, 77, 59, 79, 119, - /* 960 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - /* 970 */ 53, 54, 55, 56, 57, 259, 22, 23, 101, 102, - /* 980 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 59, - /* 990 */ 150, 151, 152, 158, 22, 244, 24, 246, 101, 102, - /* 1000 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 285, - /* 1010 */ 189, 189, 114, 115, 116, 200, 136, 137, 101, 102, - /* 1020 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 230, - /* 1030 */ 231, 59, 211, 212, 285, 105, 106, 189, 19, 141, - /* 1040 */ 234, 235, 239, 113, 114, 115, 116, 226, 118, 234, - /* 1050 */ 235, 189, 249, 247, 100, 189, 126, 23, 236, 107, - /* 1060 */ 26, 189, 247, 44, 45, 46, 47, 48, 49, 50, - /* 1070 */ 51, 52, 53, 54, 55, 56, 57, 211, 212, 59, - /* 1080 */ 150, 233, 152, 211, 212, 133, 12, 115, 189, 189, - /* 1090 */ 138, 19, 20, 300, 22, 233, 76, 304, 226, 11, - /* 1100 */ 208, 27, 22, 23, 200, 19, 26, 87, 36, 89, - /* 1110 */ 211, 212, 92, 300, 248, 189, 42, 304, 189, 250, - /* 1120 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, - /* 1130 */ 111, 59, 200, 233, 114, 115, 116, 63, 234, 235, - /* 1140 */ 235, 19, 20, 71, 22, 300, 189, 73, 200, 304, - /* 1150 */ 116, 247, 247, 81, 189, 200, 227, 26, 36, 234, - /* 1160 */ 235, 203, 204, 143, 200, 26, 234, 235, 194, 200, - /* 1170 */ 48, 99, 247, 66, 189, 141, 284, 105, 106, 247, - /* 1180 */ 100, 59, 234, 235, 112, 259, 114, 115, 116, 234, - /* 1190 */ 235, 119, 85, 71, 266, 247, 211, 212, 234, 235, - /* 1200 */ 114, 94, 247, 234, 235, 12, 266, 85, 136, 137, - /* 1210 */ 189, 247, 90, 26, 126, 127, 247, 189, 26, 22, - /* 1220 */ 27, 99, 150, 151, 152, 153, 154, 105, 106, 189, - /* 1230 */ 302, 303, 211, 212, 112, 42, 114, 115, 116, 211, - /* 1240 */ 212, 119, 302, 303, 19, 20, 189, 22, 274, 189, - /* 1250 */ 15, 144, 278, 189, 22, 23, 63, 189, 189, 203, - /* 1260 */ 204, 36, 136, 137, 155, 24, 157, 143, 211, 212, - /* 1270 */ 189, 140, 150, 151, 152, 153, 154, 0, 1, 2, - /* 1280 */ 211, 212, 5, 46, 59, 161, 147, 10, 11, 12, - /* 1290 */ 13, 14, 211, 212, 17, 60, 71, 189, 258, 189, - /* 1300 */ 59, 189, 105, 106, 189, 189, 189, 30, 116, 32, - /* 1310 */ 85, 124, 189, 251, 252, 90, 189, 40, 258, 211, - /* 1320 */ 212, 211, 212, 189, 99, 26, 211, 212, 211, 212, - /* 1330 */ 105, 106, 100, 141, 211, 212, 119, 112, 189, 114, - /* 1340 */ 115, 116, 23, 189, 119, 26, 129, 70, 189, 31, - /* 1350 */ 113, 19, 20, 24, 22, 78, 115, 39, 81, 189, - /* 1360 */ 211, 212, 26, 189, 22, 211, 212, 189, 36, 189, - /* 1370 */ 211, 212, 189, 189, 97, 150, 151, 152, 153, 154, - /* 1380 */ 127, 211, 212, 189, 189, 211, 212, 189, 189, 211, - /* 1390 */ 212, 59, 189, 189, 211, 212, 23, 189, 22, 26, - /* 1400 */ 24, 189, 149, 71, 189, 211, 212, 189, 131, 211, - /* 1410 */ 212, 189, 189, 136, 137, 211, 212, 85, 189, 211, - /* 1420 */ 212, 59, 90, 211, 212, 292, 293, 118, 119, 211, - /* 1430 */ 212, 99, 23, 211, 212, 26, 159, 105, 106, 189, - /* 1440 */ 211, 212, 143, 150, 112, 152, 114, 115, 116, 1, - /* 1450 */ 2, 119, 23, 5, 23, 26, 189, 26, 10, 11, - /* 1460 */ 12, 13, 14, 83, 84, 17, 253, 189, 139, 189, - /* 1470 */ 19, 20, 189, 22, 189, 189, 140, 115, 30, 59, - /* 1480 */ 32, 139, 150, 151, 152, 153, 154, 36, 40, 211, - /* 1490 */ 212, 211, 212, 59, 211, 212, 211, 212, 7, 8, - /* 1500 */ 19, 20, 189, 22, 150, 189, 152, 231, 281, 189, - /* 1510 */ 59, 189, 23, 189, 189, 26, 189, 36, 70, 189, - /* 1520 */ 23, 237, 71, 26, 211, 212, 78, 211, 212, 81, - /* 1530 */ 189, 211, 212, 211, 212, 115, 211, 212, 211, 212, - /* 1540 */ 59, 211, 212, 23, 23, 97, 26, 26, 23, 115, - /* 1550 */ 99, 26, 71, 189, 189, 189, 105, 106, 107, 23, - /* 1560 */ 189, 23, 26, 112, 26, 114, 115, 116, 189, 309, - /* 1570 */ 119, 23, 19, 20, 26, 22, 189, 211, 212, 131, - /* 1580 */ 99, 189, 211, 212, 136, 137, 105, 106, 189, 36, - /* 1590 */ 211, 212, 189, 112, 189, 114, 115, 116, 211, 212, - /* 1600 */ 119, 150, 151, 152, 153, 154, 189, 159, 23, 250, - /* 1610 */ 189, 26, 59, 189, 189, 189, 189, 189, 280, 189, - /* 1620 */ 250, 189, 189, 238, 71, 189, 189, 250, 211, 212, - /* 1630 */ 187, 150, 151, 152, 153, 154, 211, 212, 250, 290, - /* 1640 */ 240, 211, 212, 211, 212, 254, 286, 209, 254, 241, - /* 1650 */ 240, 254, 99, 286, 215, 220, 214, 244, 105, 106, - /* 1660 */ 214, 214, 244, 273, 224, 112, 192, 114, 115, 116, - /* 1670 */ 60, 290, 119, 5, 139, 196, 196, 38, 10, 11, - /* 1680 */ 12, 13, 14, 238, 240, 17, 196, 148, 287, 287, - /* 1690 */ 276, 113, 22, 147, 241, 43, 229, 241, 30, 18, - /* 1700 */ 32, 232, 232, 150, 151, 152, 153, 154, 40, 232, - /* 1710 */ 232, 196, 18, 195, 265, 265, 264, 241, 264, 196, - /* 1720 */ 155, 229, 229, 241, 241, 241, 195, 62, 196, 195, - /* 1730 */ 22, 113, 216, 196, 222, 195, 195, 282, 70, 196, - /* 1740 */ 283, 213, 216, 213, 64, 22, 78, 124, 219, 81, - /* 1750 */ 162, 111, 219, 142, 256, 213, 113, 255, 213, 256, - /* 1760 */ 216, 303, 215, 213, 213, 97, 255, 213, 216, 275, - /* 1770 */ 275, 222, 216, 256, 255, 196, 91, 82, 256, 255, - /* 1780 */ 308, 308, 146, 22, 143, 196, 155, 260, 25, 145, - /* 1790 */ 144, 199, 26, 198, 13, 190, 190, 6, 293, 131, - /* 1800 */ 188, 188, 245, 244, 136, 137, 245, 243, 242, 241, - /* 1810 */ 188, 202, 208, 217, 217, 260, 208, 4, 202, 3, - /* 1820 */ 22, 202, 208, 208, 160, 15, 209, 159, 270, 209, - /* 1830 */ 98, 16, 272, 208, 23, 23, 137, 148, 128, 20, - /* 1840 */ 140, 24, 16, 142, 1, 140, 149, 128, 61, 53, - /* 1850 */ 148, 37, 53, 53, 53, 128, 114, 34, 296, 296, - /* 1860 */ 139, 1, 5, 22, 113, 158, 26, 75, 41, 139, - /* 1870 */ 68, 68, 113, 24, 20, 19, 129, 123, 23, 96, - /* 1880 */ 22, 22, 37, 22, 22, 67, 22, 67, 59, 24, - /* 1890 */ 23, 28, 67, 147, 22, 26, 23, 23, 23, 23, - /* 1900 */ 22, 24, 23, 22, 24, 23, 139, 23, 114, 22, - /* 1910 */ 141, 26, 88, 75, 86, 44, 23, 34, 22, 75, - /* 1920 */ 34, 24, 34, 34, 34, 93, 34, 26, 26, 34, - /* 1930 */ 23, 23, 23, 23, 23, 11, 23, 22, 26, 22, - /* 1940 */ 22, 133, 23, 23, 22, 22, 139, 26, 139, 23, - /* 1950 */ 15, 1, 1, 310, 310, 310, 310, 310, 310, 310, - /* 1960 */ 139, 139, 310, 310, 310, 310, 310, 310, 310, 310, - /* 1970 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 1980 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 1990 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2000 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2010 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2020 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2030 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2040 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2050 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2060 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2070 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2080 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2090 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2100 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2110 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2120 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2130 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310, - /* 2140 */ 310, 310, 310, -}; -#define YY_SHIFT_COUNT (552) -#define YY_SHIFT_MIN (0) -#define YY_SHIFT_MAX (1951) -static const unsigned short int yy_shift_ofst[] = { - /* 0 */ 1448, 1277, 1668, 1072, 1072, 340, 1122, 1225, 1332, 1481, - /* 10 */ 1481, 1481, 335, 0, 0, 180, 897, 1481, 1481, 1481, - /* 20 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, - /* 30 */ 930, 930, 1020, 1020, 290, 1, 340, 340, 340, 340, - /* 40 */ 340, 340, 40, 110, 219, 288, 327, 396, 435, 504, - /* 50 */ 543, 612, 651, 720, 877, 897, 897, 897, 897, 897, - /* 60 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897, - /* 70 */ 897, 897, 897, 917, 897, 1019, 763, 763, 1451, 1481, - /* 80 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, - /* 90 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, - /* 100 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, - /* 110 */ 1481, 1481, 1553, 1481, 1481, 1481, 1481, 1481, 1481, 1481, - /* 120 */ 1481, 1481, 1481, 1481, 1481, 1481, 147, 258, 258, 258, - /* 130 */ 258, 258, 79, 65, 84, 449, 19, 786, 449, 636, - /* 140 */ 636, 449, 880, 880, 880, 880, 113, 142, 142, 472, - /* 150 */ 150, 1962, 1962, 399, 399, 399, 93, 237, 341, 237, - /* 160 */ 237, 1074, 1074, 437, 350, 704, 1080, 449, 449, 449, - /* 170 */ 449, 449, 449, 449, 449, 449, 449, 449, 449, 449, - /* 180 */ 449, 449, 449, 449, 449, 449, 449, 449, 818, 818, - /* 190 */ 449, 1088, 217, 217, 734, 734, 1124, 1126, 1962, 1962, - /* 200 */ 1962, 739, 840, 840, 453, 454, 511, 187, 563, 570, - /* 210 */ 898, 669, 449, 449, 449, 449, 449, 449, 449, 449, - /* 220 */ 449, 670, 449, 449, 449, 449, 449, 449, 449, 449, - /* 230 */ 449, 449, 449, 449, 674, 674, 674, 449, 449, 449, - /* 240 */ 449, 1034, 449, 449, 449, 972, 1107, 449, 449, 1193, - /* 250 */ 449, 449, 449, 449, 449, 449, 449, 449, 260, 177, - /* 260 */ 489, 1241, 1241, 1241, 1241, 1192, 489, 489, 952, 1197, - /* 270 */ 625, 1235, 1131, 181, 181, 1086, 1139, 1131, 1086, 1187, - /* 280 */ 1319, 1237, 1318, 1318, 1318, 181, 1299, 1299, 1109, 1336, - /* 290 */ 549, 1376, 1610, 1535, 1535, 1639, 1639, 1535, 1539, 1578, - /* 300 */ 1670, 1546, 1652, 1546, 1681, 1681, 1681, 1681, 1535, 1694, - /* 310 */ 1546, 1546, 1578, 1670, 1652, 1546, 1652, 1546, 1535, 1694, - /* 320 */ 1565, 1665, 1535, 1694, 1708, 1535, 1694, 1535, 1694, 1708, - /* 330 */ 1618, 1618, 1618, 1680, 1723, 1723, 1708, 1618, 1623, 1618, - /* 340 */ 1680, 1618, 1618, 1588, 1708, 1640, 1640, 1708, 1611, 1643, - /* 350 */ 1611, 1643, 1611, 1643, 1611, 1643, 1535, 1685, 1685, 1695, - /* 360 */ 1695, 1636, 1641, 1761, 1535, 1631, 1636, 1644, 1646, 1546, - /* 370 */ 1763, 1766, 1781, 1781, 1791, 1791, 1791, 1962, 1962, 1962, - /* 380 */ 1962, 1962, 1962, 1962, 1962, 1962, 1962, 1962, 1962, 1962, - /* 390 */ 1962, 1962, 308, 835, 954, 1232, 879, 715, 728, 1373, - /* 400 */ 864, 1329, 1253, 1409, 297, 1431, 1489, 1497, 1520, 1521, - /* 410 */ 1525, 1362, 1309, 1491, 1217, 1420, 1429, 1536, 1380, 1538, - /* 420 */ 1293, 1354, 1548, 1585, 1434, 1342, 1813, 1816, 1798, 1664, - /* 430 */ 1810, 1732, 1815, 1811, 1812, 1699, 1689, 1710, 1817, 1700, - /* 440 */ 1819, 1701, 1826, 1843, 1705, 1697, 1719, 1787, 1814, 1702, - /* 450 */ 1796, 1799, 1800, 1801, 1727, 1742, 1823, 1721, 1860, 1857, - /* 460 */ 1841, 1751, 1707, 1802, 1840, 1803, 1792, 1827, 1730, 1759, - /* 470 */ 1849, 1854, 1856, 1747, 1754, 1858, 1818, 1859, 1861, 1855, - /* 480 */ 1862, 1820, 1829, 1865, 1783, 1863, 1864, 1825, 1845, 1867, - /* 490 */ 1746, 1872, 1873, 1874, 1875, 1869, 1876, 1878, 1877, 1879, - /* 500 */ 1881, 1880, 1767, 1882, 1884, 1794, 1883, 1887, 1769, 1885, - /* 510 */ 1886, 1888, 1889, 1890, 1824, 1838, 1828, 1871, 1844, 1832, - /* 520 */ 1892, 1893, 1896, 1897, 1901, 1902, 1895, 1907, 1885, 1908, - /* 530 */ 1909, 1910, 1911, 1912, 1913, 1915, 1924, 1917, 1918, 1919, - /* 540 */ 1920, 1922, 1923, 1921, 1808, 1807, 1809, 1821, 1822, 1926, - /* 550 */ 1935, 1950, 1951, -}; -#define YY_REDUCE_COUNT (391) -#define YY_REDUCE_MIN (-262) -#define YY_REDUCE_MAX (1625) -static const short yy_reduce_ofst[] = { - /* 0 */ 490, -122, 545, 645, 650, -120, -189, -187, -184, -182, - /* 10 */ -178, -176, 45, 30, 200, -251, -134, 390, 392, 521, - /* 20 */ 523, 213, 692, 821, 284, 589, 872, 666, 671, 866, - /* 30 */ 71, 111, 273, 389, 686, 815, 904, 932, 948, 955, - /* 40 */ 964, 969, -259, -259, -259, -259, -259, -259, -259, -259, - /* 50 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259, - /* 60 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259, - /* 70 */ -259, -259, -259, -259, -259, -259, -259, -259, 428, 430, - /* 80 */ 899, 985, 1021, 1028, 1057, 1069, 1081, 1108, 1110, 1115, - /* 90 */ 1117, 1123, 1149, 1154, 1159, 1170, 1174, 1178, 1183, 1194, - /* 100 */ 1198, 1204, 1208, 1212, 1218, 1222, 1229, 1278, 1280, 1283, - /* 110 */ 1285, 1313, 1316, 1320, 1322, 1325, 1327, 1330, 1366, 1371, - /* 120 */ 1379, 1387, 1417, 1425, 1430, 1432, -259, -259, -259, -259, - /* 130 */ -259, -259, -259, -259, -259, 557, 974, -214, -174, -9, - /* 140 */ 431, -124, 806, 925, 806, 925, 251, 928, 940, -259, - /* 150 */ -259, -259, -259, -198, -198, -198, 127, -186, -168, 212, - /* 160 */ 646, 617, 799, -262, 555, 220, 220, 491, 605, 1040, - /* 170 */ 1060, 699, -11, 600, 848, 862, 345, -129, 724, -91, - /* 180 */ 158, 749, 716, 900, 304, 822, 929, 926, 499, 793, - /* 190 */ 322, 892, 813, 845, 958, 1056, 751, 905, 1133, 1062, - /* 200 */ 803, -210, -185, -179, -148, -167, -89, 121, 274, 281, - /* 210 */ 320, 336, 439, 663, 711, 957, 965, 1064, 1068, 1112, - /* 220 */ 1116, -196, 1127, 1134, 1180, 1184, 1195, 1199, 1203, 1215, - /* 230 */ 1223, 1250, 1267, 1286, 205, 422, 638, 1324, 1341, 1364, - /* 240 */ 1365, 1213, 1392, 1399, 1403, 869, 1260, 1405, 1421, 1276, - /* 250 */ 1424, 121, 1426, 1427, 1428, 1433, 1436, 1437, 1227, 1338, - /* 260 */ 1284, 1359, 1370, 1377, 1388, 1213, 1284, 1284, 1385, 1438, - /* 270 */ 1443, 1349, 1400, 1391, 1394, 1360, 1408, 1410, 1367, 1439, - /* 280 */ 1440, 1435, 1442, 1446, 1447, 1397, 1413, 1418, 1390, 1444, - /* 290 */ 1445, 1474, 1381, 1479, 1480, 1401, 1402, 1490, 1414, 1449, - /* 300 */ 1452, 1453, 1467, 1456, 1469, 1470, 1477, 1478, 1515, 1518, - /* 310 */ 1476, 1482, 1450, 1454, 1492, 1483, 1493, 1484, 1523, 1531, - /* 320 */ 1457, 1455, 1532, 1534, 1516, 1537, 1540, 1543, 1541, 1526, - /* 330 */ 1528, 1530, 1542, 1512, 1529, 1533, 1544, 1545, 1547, 1550, - /* 340 */ 1549, 1551, 1554, 1458, 1552, 1494, 1495, 1556, 1498, 1502, - /* 350 */ 1503, 1511, 1517, 1519, 1522, 1524, 1579, 1472, 1473, 1527, - /* 360 */ 1555, 1557, 1559, 1558, 1589, 1560, 1561, 1564, 1566, 1568, - /* 370 */ 1592, 1595, 1605, 1606, 1612, 1613, 1622, 1562, 1563, 1505, - /* 380 */ 1609, 1604, 1608, 1614, 1615, 1616, 1596, 1597, 1617, 1620, - /* 390 */ 1625, 1619, -}; -static const YYACTIONTYPE yy_default[] = { - /* 0 */ 1575, 1575, 1575, 1411, 1188, 1297, 1188, 1188, 1188, 1411, - /* 10 */ 1411, 1411, 1188, 1327, 1327, 1464, 1219, 1188, 1188, 1188, - /* 20 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1410, 1188, 1188, - /* 30 */ 1188, 1188, 1494, 1494, 1188, 1188, 1188, 1188, 1188, 1188, - /* 40 */ 1188, 1188, 1188, 1336, 1188, 1188, 1188, 1188, 1188, 1188, - /* 50 */ 1412, 1413, 1188, 1188, 1188, 1463, 1465, 1428, 1346, 1345, - /* 60 */ 1344, 1343, 1446, 1314, 1341, 1334, 1338, 1406, 1407, 1405, - /* 70 */ 1409, 1413, 1412, 1188, 1337, 1377, 1391, 1376, 1188, 1188, - /* 80 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 90 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 100 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 110 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 120 */ 1188, 1188, 1188, 1188, 1188, 1188, 1385, 1390, 1396, 1389, - /* 130 */ 1386, 1379, 1378, 1380, 1381, 1188, 1209, 1261, 1188, 1188, - /* 140 */ 1188, 1188, 1482, 1481, 1188, 1188, 1219, 1371, 1370, 1382, - /* 150 */ 1383, 1393, 1392, 1471, 1529, 1528, 1429, 1188, 1188, 1188, - /* 160 */ 1188, 1188, 1188, 1494, 1188, 1188, 1188, 1188, 1188, 1188, - /* 170 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 180 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1494, 1494, - /* 190 */ 1188, 1219, 1494, 1494, 1215, 1215, 1321, 1188, 1477, 1297, - /* 200 */ 1288, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 210 */ 1188, 1188, 1188, 1188, 1188, 1468, 1466, 1188, 1188, 1188, - /* 220 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 230 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 240 */ 1188, 1188, 1188, 1188, 1188, 1293, 1188, 1188, 1188, 1188, - /* 250 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1523, 1188, 1441, - /* 260 */ 1275, 1293, 1293, 1293, 1293, 1295, 1276, 1274, 1287, 1220, - /* 270 */ 1195, 1567, 1294, 1316, 1316, 1564, 1340, 1294, 1564, 1236, - /* 280 */ 1545, 1231, 1327, 1327, 1327, 1316, 1321, 1321, 1408, 1294, - /* 290 */ 1287, 1188, 1567, 1302, 1302, 1566, 1566, 1302, 1429, 1349, - /* 300 */ 1355, 1340, 1264, 1340, 1270, 1270, 1270, 1270, 1302, 1206, - /* 310 */ 1340, 1340, 1349, 1355, 1264, 1340, 1264, 1340, 1302, 1206, - /* 320 */ 1445, 1561, 1302, 1206, 1419, 1302, 1206, 1302, 1206, 1419, - /* 330 */ 1262, 1262, 1262, 1251, 1188, 1188, 1419, 1262, 1236, 1262, - /* 340 */ 1251, 1262, 1262, 1512, 1419, 1423, 1423, 1419, 1320, 1315, - /* 350 */ 1320, 1315, 1320, 1315, 1320, 1315, 1302, 1504, 1504, 1330, - /* 360 */ 1330, 1335, 1321, 1414, 1302, 1188, 1335, 1333, 1331, 1340, - /* 370 */ 1212, 1254, 1526, 1526, 1522, 1522, 1522, 1572, 1572, 1477, - /* 380 */ 1538, 1219, 1219, 1219, 1219, 1538, 1238, 1238, 1220, 1220, - /* 390 */ 1219, 1538, 1188, 1188, 1188, 1188, 1188, 1188, 1533, 1188, - /* 400 */ 1430, 1306, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 410 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 420 */ 1188, 1188, 1188, 1188, 1188, 1360, 1188, 1191, 1474, 1188, - /* 430 */ 1188, 1472, 1188, 1188, 1188, 1188, 1188, 1188, 1307, 1188, - /* 440 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 450 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1563, 1188, 1188, - /* 460 */ 1188, 1188, 1188, 1188, 1444, 1443, 1188, 1188, 1304, 1188, - /* 470 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 480 */ 1188, 1188, 1234, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 490 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 500 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1332, - /* 510 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 520 */ 1188, 1188, 1188, 1188, 1509, 1322, 1188, 1188, 1554, 1188, - /* 530 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1188, - /* 540 */ 1188, 1188, 1188, 1549, 1278, 1362, 1188, 1361, 1365, 1188, - /* 550 */ 1200, 1188, 1188, -}; -/********** End of lemon-generated parsing tables *****************************/ - -/* The next table maps tokens (terminal symbols) into fallback tokens. -** If a construct like the following: -** -** %fallback ID X Y Z. -** -** appears in the grammar, then ID becomes a fallback token for X, Y, -** and Z. Whenever one of the tokens X, Y, or Z is input to the parser -** but it does not parse, the type of the token is changed to ID and -** the parse is retried before an error is thrown. -** -** This feature can be used, for example, to cause some keywords in a language -** to revert to identifiers if they keyword does not apply in the context where -** it appears. -*/ -#ifdef YYFALLBACK -static const YYCODETYPE yyFallback[] = { - 0, /* $ => nothing */ - 0, /* SEMI => nothing */ - 59, /* EXPLAIN => ID */ - 59, /* QUERY => ID */ - 59, /* PLAN => ID */ - 59, /* BEGIN => ID */ - 0, /* TRANSACTION => nothing */ - 59, /* DEFERRED => ID */ - 59, /* IMMEDIATE => ID */ - 59, /* EXCLUSIVE => ID */ - 0, /* COMMIT => nothing */ - 59, /* END => ID */ - 59, /* ROLLBACK => ID */ - 59, /* SAVEPOINT => ID */ - 59, /* RELEASE => ID */ - 0, /* TO => nothing */ - 0, /* TABLE => nothing */ - 0, /* CREATE => nothing */ - 59, /* IF => ID */ - 0, /* NOT => nothing */ - 0, /* EXISTS => nothing */ - 59, /* TEMP => ID */ - 0, /* LP => nothing */ - 0, /* RP => nothing */ - 0, /* AS => nothing */ - 59, /* WITHOUT => ID */ - 0, /* COMMA => nothing */ - 59, /* ABORT => ID */ - 59, /* ACTION => ID */ - 59, /* AFTER => ID */ - 59, /* ANALYZE => ID */ - 59, /* ASC => ID */ - 59, /* ATTACH => ID */ - 59, /* BEFORE => ID */ - 59, /* BY => ID */ - 59, /* CASCADE => ID */ - 59, /* CAST => ID */ - 59, /* CONFLICT => ID */ - 59, /* DATABASE => ID */ - 59, /* DESC => ID */ - 59, /* DETACH => ID */ - 59, /* EACH => ID */ - 59, /* FAIL => ID */ - 0, /* OR => nothing */ - 0, /* AND => nothing */ - 0, /* IS => nothing */ - 59, /* MATCH => ID */ - 59, /* LIKE_KW => ID */ - 0, /* BETWEEN => nothing */ - 0, /* IN => nothing */ - 0, /* ISNULL => nothing */ - 0, /* NOTNULL => nothing */ - 0, /* NE => nothing */ - 0, /* EQ => nothing */ - 0, /* GT => nothing */ - 0, /* LE => nothing */ - 0, /* LT => nothing */ - 0, /* GE => nothing */ - 0, /* ESCAPE => nothing */ - 0, /* ID => nothing */ - 59, /* COLUMNKW => ID */ - 59, /* DO => ID */ - 59, /* FOR => ID */ - 59, /* IGNORE => ID */ - 59, /* INITIALLY => ID */ - 59, /* INSTEAD => ID */ - 59, /* NO => ID */ - 59, /* KEY => ID */ - 59, /* OF => ID */ - 59, /* OFFSET => ID */ - 59, /* PRAGMA => ID */ - 59, /* RAISE => ID */ - 59, /* RECURSIVE => ID */ - 59, /* REPLACE => ID */ - 59, /* RESTRICT => ID */ - 59, /* ROW => ID */ - 59, /* ROWS => ID */ - 59, /* TRIGGER => ID */ - 59, /* VACUUM => ID */ - 59, /* VIEW => ID */ - 59, /* VIRTUAL => ID */ - 59, /* WITH => ID */ - 59, /* NULLS => ID */ - 59, /* FIRST => ID */ - 59, /* LAST => ID */ - 59, /* CURRENT => ID */ - 59, /* FOLLOWING => ID */ - 59, /* PARTITION => ID */ - 59, /* PRECEDING => ID */ - 59, /* RANGE => ID */ - 59, /* UNBOUNDED => ID */ - 59, /* EXCLUDE => ID */ - 59, /* GROUPS => ID */ - 59, /* OTHERS => ID */ - 59, /* TIES => ID */ - 59, /* GENERATED => ID */ - 59, /* ALWAYS => ID */ - 59, /* REINDEX => ID */ - 59, /* RENAME => ID */ - 59, /* CTIME_KW => ID */ - 0, /* ANY => nothing */ - 0, /* BITAND => nothing */ - 0, /* BITOR => nothing */ - 0, /* LSHIFT => nothing */ - 0, /* RSHIFT => nothing */ - 0, /* PLUS => nothing */ - 0, /* MINUS => nothing */ - 0, /* STAR => nothing */ - 0, /* SLASH => nothing */ - 0, /* REM => nothing */ - 0, /* CONCAT => nothing */ - 0, /* COLLATE => nothing */ - 0, /* BITNOT => nothing */ - 0, /* ON => nothing */ - 0, /* INDEXED => nothing */ - 0, /* STRING => nothing */ - 0, /* JOIN_KW => nothing */ - 0, /* CONSTRAINT => nothing */ - 0, /* DEFAULT => nothing */ - 0, /* NULL => nothing */ - 0, /* PRIMARY => nothing */ - 0, /* UNIQUE => nothing */ - 0, /* CHECK => nothing */ - 0, /* REFERENCES => nothing */ - 0, /* AUTOINCR => nothing */ - 0, /* INSERT => nothing */ - 0, /* DELETE => nothing */ - 0, /* UPDATE => nothing */ - 0, /* SET => nothing */ - 0, /* DEFERRABLE => nothing */ - 0, /* FOREIGN => nothing */ - 0, /* DROP => nothing */ - 0, /* UNION => nothing */ - 0, /* ALL => nothing */ - 0, /* EXCEPT => nothing */ - 0, /* INTERSECT => nothing */ - 0, /* SELECT => nothing */ - 0, /* VALUES => nothing */ - 0, /* DISTINCT => nothing */ - 0, /* DOT => nothing */ - 0, /* FROM => nothing */ - 0, /* JOIN => nothing */ - 0, /* USING => nothing */ - 0, /* ORDER => nothing */ - 0, /* GROUP => nothing */ - 0, /* HAVING => nothing */ - 0, /* LIMIT => nothing */ - 0, /* WHERE => nothing */ - 0, /* INTO => nothing */ - 0, /* NOTHING => nothing */ - 0, /* FLOAT => nothing */ - 0, /* BLOB => nothing */ - 0, /* INTEGER => nothing */ - 0, /* VARIABLE => nothing */ - 0, /* CASE => nothing */ - 0, /* WHEN => nothing */ - 0, /* THEN => nothing */ - 0, /* ELSE => nothing */ - 0, /* INDEX => nothing */ - 0, /* ALTER => nothing */ - 0, /* ADD => nothing */ - 0, /* WINDOW => nothing */ - 0, /* OVER => nothing */ - 0, /* FILTER => nothing */ - 0, /* COLUMN => nothing */ - 0, /* AGG_FUNCTION => nothing */ - 0, /* AGG_COLUMN => nothing */ - 0, /* TRUEFALSE => nothing */ - 0, /* ISNOT => nothing */ - 0, /* FUNCTION => nothing */ - 0, /* UMINUS => nothing */ - 0, /* UPLUS => nothing */ - 0, /* TRUTH => nothing */ - 0, /* REGISTER => nothing */ - 0, /* VECTOR => nothing */ - 0, /* SELECT_COLUMN => nothing */ - 0, /* IF_NULL_ROW => nothing */ - 0, /* ASTERISK => nothing */ - 0, /* SPAN => nothing */ - 0, /* SPACE => nothing */ - 0, /* ILLEGAL => nothing */ -}; -#endif /* YYFALLBACK */ - -/* The following structure represents a single element of the -** parser's stack. Information stored includes: -** -** + The state number for the parser at this level of the stack. -** -** + The value of the token stored at this level of the stack. -** (In other words, the "major" token.) -** -** + The semantic value stored at this level of the stack. This is -** the information used by the action routines in the grammar. -** It is sometimes called the "minor" token. -** -** After the "shift" half of a SHIFTREDUCE action, the stateno field -** actually contains the reduce action for the second half of the -** SHIFTREDUCE. -*/ -struct yyStackEntry { - YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */ - YYCODETYPE major; /* The major token value. This is the code - ** number for the token at this stack level */ - YYMINORTYPE minor; /* The user-supplied minor token value. This - ** is the value of the token */ -}; -typedef struct yyStackEntry yyStackEntry; - -/* The state of the parser is completely contained in an instance of -** the following structure */ -struct yyParser { - yyStackEntry *yytos; /* Pointer to top element of the stack */ -#ifdef YYTRACKMAXSTACKDEPTH - int yyhwm; /* High-water mark of the stack */ -#endif -#ifndef YYNOERRORRECOVERY - int yyerrcnt; /* Shifts left before out of the error */ -#endif - sqlite3ParserARG_SDECL /* A place to hold %extra_argument */ - sqlite3ParserCTX_SDECL /* A place to hold %extra_context */ -#if YYSTACKDEPTH<=0 - int yystksz; /* Current side of the stack */ - yyStackEntry *yystack; /* The parser's stack */ - yyStackEntry yystk0; /* First stack entry */ -#else - yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ - yyStackEntry *yystackEnd; /* Last entry in the stack */ -#endif -}; -typedef struct yyParser yyParser; - -#ifndef NDEBUG -/* #include */ -static FILE *yyTraceFILE = 0; -static char *yyTracePrompt = 0; -#endif /* NDEBUG */ - -#ifndef NDEBUG -/* -** Turn parser tracing on by giving a stream to which to write the trace -** and a prompt to preface each trace message. Tracing is turned off -** by making either argument NULL -** -** Inputs: -**
      -**
    • A FILE* to which trace output should be written. -** If NULL, then tracing is turned off. -**
    • A prefix string written at the beginning of every -** line of trace output. If NULL, then tracing is -** turned off. -**
    -** -** Outputs: -** None. -*/ -SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){ - yyTraceFILE = TraceFILE; - yyTracePrompt = zTracePrompt; - if( yyTraceFILE==0 ) yyTracePrompt = 0; - else if( yyTracePrompt==0 ) yyTraceFILE = 0; -} -#endif /* NDEBUG */ - -#if defined(YYCOVERAGE) || !defined(NDEBUG) -/* For tracing shifts, the names of all terminals and nonterminals -** are required. The following table supplies these names */ -static const char *const yyTokenName[] = { - /* 0 */ "$", - /* 1 */ "SEMI", - /* 2 */ "EXPLAIN", - /* 3 */ "QUERY", - /* 4 */ "PLAN", - /* 5 */ "BEGIN", - /* 6 */ "TRANSACTION", - /* 7 */ "DEFERRED", - /* 8 */ "IMMEDIATE", - /* 9 */ "EXCLUSIVE", - /* 10 */ "COMMIT", - /* 11 */ "END", - /* 12 */ "ROLLBACK", - /* 13 */ "SAVEPOINT", - /* 14 */ "RELEASE", - /* 15 */ "TO", - /* 16 */ "TABLE", - /* 17 */ "CREATE", - /* 18 */ "IF", - /* 19 */ "NOT", - /* 20 */ "EXISTS", - /* 21 */ "TEMP", - /* 22 */ "LP", - /* 23 */ "RP", - /* 24 */ "AS", - /* 25 */ "WITHOUT", - /* 26 */ "COMMA", - /* 27 */ "ABORT", - /* 28 */ "ACTION", - /* 29 */ "AFTER", - /* 30 */ "ANALYZE", - /* 31 */ "ASC", - /* 32 */ "ATTACH", - /* 33 */ "BEFORE", - /* 34 */ "BY", - /* 35 */ "CASCADE", - /* 36 */ "CAST", - /* 37 */ "CONFLICT", - /* 38 */ "DATABASE", - /* 39 */ "DESC", - /* 40 */ "DETACH", - /* 41 */ "EACH", - /* 42 */ "FAIL", - /* 43 */ "OR", - /* 44 */ "AND", - /* 45 */ "IS", - /* 46 */ "MATCH", - /* 47 */ "LIKE_KW", - /* 48 */ "BETWEEN", - /* 49 */ "IN", - /* 50 */ "ISNULL", - /* 51 */ "NOTNULL", - /* 52 */ "NE", - /* 53 */ "EQ", - /* 54 */ "GT", - /* 55 */ "LE", - /* 56 */ "LT", - /* 57 */ "GE", - /* 58 */ "ESCAPE", - /* 59 */ "ID", - /* 60 */ "COLUMNKW", - /* 61 */ "DO", - /* 62 */ "FOR", - /* 63 */ "IGNORE", - /* 64 */ "INITIALLY", - /* 65 */ "INSTEAD", - /* 66 */ "NO", - /* 67 */ "KEY", - /* 68 */ "OF", - /* 69 */ "OFFSET", - /* 70 */ "PRAGMA", - /* 71 */ "RAISE", - /* 72 */ "RECURSIVE", - /* 73 */ "REPLACE", - /* 74 */ "RESTRICT", - /* 75 */ "ROW", - /* 76 */ "ROWS", - /* 77 */ "TRIGGER", - /* 78 */ "VACUUM", - /* 79 */ "VIEW", - /* 80 */ "VIRTUAL", - /* 81 */ "WITH", - /* 82 */ "NULLS", - /* 83 */ "FIRST", - /* 84 */ "LAST", - /* 85 */ "CURRENT", - /* 86 */ "FOLLOWING", - /* 87 */ "PARTITION", - /* 88 */ "PRECEDING", - /* 89 */ "RANGE", - /* 90 */ "UNBOUNDED", - /* 91 */ "EXCLUDE", - /* 92 */ "GROUPS", - /* 93 */ "OTHERS", - /* 94 */ "TIES", - /* 95 */ "GENERATED", - /* 96 */ "ALWAYS", - /* 97 */ "REINDEX", - /* 98 */ "RENAME", - /* 99 */ "CTIME_KW", - /* 100 */ "ANY", - /* 101 */ "BITAND", - /* 102 */ "BITOR", - /* 103 */ "LSHIFT", - /* 104 */ "RSHIFT", - /* 105 */ "PLUS", - /* 106 */ "MINUS", - /* 107 */ "STAR", - /* 108 */ "SLASH", - /* 109 */ "REM", - /* 110 */ "CONCAT", - /* 111 */ "COLLATE", - /* 112 */ "BITNOT", - /* 113 */ "ON", - /* 114 */ "INDEXED", - /* 115 */ "STRING", - /* 116 */ "JOIN_KW", - /* 117 */ "CONSTRAINT", - /* 118 */ "DEFAULT", - /* 119 */ "NULL", - /* 120 */ "PRIMARY", - /* 121 */ "UNIQUE", - /* 122 */ "CHECK", - /* 123 */ "REFERENCES", - /* 124 */ "AUTOINCR", - /* 125 */ "INSERT", - /* 126 */ "DELETE", - /* 127 */ "UPDATE", - /* 128 */ "SET", - /* 129 */ "DEFERRABLE", - /* 130 */ "FOREIGN", - /* 131 */ "DROP", - /* 132 */ "UNION", - /* 133 */ "ALL", - /* 134 */ "EXCEPT", - /* 135 */ "INTERSECT", - /* 136 */ "SELECT", - /* 137 */ "VALUES", - /* 138 */ "DISTINCT", - /* 139 */ "DOT", - /* 140 */ "FROM", - /* 141 */ "JOIN", - /* 142 */ "USING", - /* 143 */ "ORDER", - /* 144 */ "GROUP", - /* 145 */ "HAVING", - /* 146 */ "LIMIT", - /* 147 */ "WHERE", - /* 148 */ "INTO", - /* 149 */ "NOTHING", - /* 150 */ "FLOAT", - /* 151 */ "BLOB", - /* 152 */ "INTEGER", - /* 153 */ "VARIABLE", - /* 154 */ "CASE", - /* 155 */ "WHEN", - /* 156 */ "THEN", - /* 157 */ "ELSE", - /* 158 */ "INDEX", - /* 159 */ "ALTER", - /* 160 */ "ADD", - /* 161 */ "WINDOW", - /* 162 */ "OVER", - /* 163 */ "FILTER", - /* 164 */ "COLUMN", - /* 165 */ "AGG_FUNCTION", - /* 166 */ "AGG_COLUMN", - /* 167 */ "TRUEFALSE", - /* 168 */ "ISNOT", - /* 169 */ "FUNCTION", - /* 170 */ "UMINUS", - /* 171 */ "UPLUS", - /* 172 */ "TRUTH", - /* 173 */ "REGISTER", - /* 174 */ "VECTOR", - /* 175 */ "SELECT_COLUMN", - /* 176 */ "IF_NULL_ROW", - /* 177 */ "ASTERISK", - /* 178 */ "SPAN", - /* 179 */ "SPACE", - /* 180 */ "ILLEGAL", - /* 181 */ "input", - /* 182 */ "cmdlist", - /* 183 */ "ecmd", - /* 184 */ "cmdx", - /* 185 */ "explain", - /* 186 */ "cmd", - /* 187 */ "transtype", - /* 188 */ "trans_opt", - /* 189 */ "nm", - /* 190 */ "savepoint_opt", - /* 191 */ "create_table", - /* 192 */ "create_table_args", - /* 193 */ "createkw", - /* 194 */ "temp", - /* 195 */ "ifnotexists", - /* 196 */ "dbnm", - /* 197 */ "columnlist", - /* 198 */ "conslist_opt", - /* 199 */ "table_options", - /* 200 */ "select", - /* 201 */ "columnname", - /* 202 */ "carglist", - /* 203 */ "typetoken", - /* 204 */ "typename", - /* 205 */ "signed", - /* 206 */ "plus_num", - /* 207 */ "minus_num", - /* 208 */ "scanpt", - /* 209 */ "scantok", - /* 210 */ "ccons", - /* 211 */ "term", - /* 212 */ "expr", - /* 213 */ "onconf", - /* 214 */ "sortorder", - /* 215 */ "autoinc", - /* 216 */ "eidlist_opt", - /* 217 */ "refargs", - /* 218 */ "defer_subclause", - /* 219 */ "generated", - /* 220 */ "refarg", - /* 221 */ "refact", - /* 222 */ "init_deferred_pred_opt", - /* 223 */ "conslist", - /* 224 */ "tconscomma", - /* 225 */ "tcons", - /* 226 */ "sortlist", - /* 227 */ "eidlist", - /* 228 */ "defer_subclause_opt", - /* 229 */ "orconf", - /* 230 */ "resolvetype", - /* 231 */ "raisetype", - /* 232 */ "ifexists", - /* 233 */ "fullname", - /* 234 */ "selectnowith", - /* 235 */ "oneselect", - /* 236 */ "wqlist", - /* 237 */ "multiselect_op", - /* 238 */ "distinct", - /* 239 */ "selcollist", - /* 240 */ "from", - /* 241 */ "where_opt", - /* 242 */ "groupby_opt", - /* 243 */ "having_opt", - /* 244 */ "orderby_opt", - /* 245 */ "limit_opt", - /* 246 */ "window_clause", - /* 247 */ "values", - /* 248 */ "nexprlist", - /* 249 */ "sclp", - /* 250 */ "as", - /* 251 */ "seltablist", - /* 252 */ "stl_prefix", - /* 253 */ "joinop", - /* 254 */ "indexed_opt", - /* 255 */ "on_opt", - /* 256 */ "using_opt", - /* 257 */ "exprlist", - /* 258 */ "xfullname", - /* 259 */ "idlist", - /* 260 */ "nulls", - /* 261 */ "with", - /* 262 */ "setlist", - /* 263 */ "insert_cmd", - /* 264 */ "idlist_opt", - /* 265 */ "upsert", - /* 266 */ "filter_over", - /* 267 */ "likeop", - /* 268 */ "between_op", - /* 269 */ "in_op", - /* 270 */ "paren_exprlist", - /* 271 */ "case_operand", - /* 272 */ "case_exprlist", - /* 273 */ "case_else", - /* 274 */ "uniqueflag", - /* 275 */ "collate", - /* 276 */ "vinto", - /* 277 */ "nmnum", - /* 278 */ "trigger_decl", - /* 279 */ "trigger_cmd_list", - /* 280 */ "trigger_time", - /* 281 */ "trigger_event", - /* 282 */ "foreach_clause", - /* 283 */ "when_clause", - /* 284 */ "trigger_cmd", - /* 285 */ "trnm", - /* 286 */ "tridxby", - /* 287 */ "database_kw_opt", - /* 288 */ "key_opt", - /* 289 */ "add_column_fullname", - /* 290 */ "kwcolumn_opt", - /* 291 */ "create_vtab", - /* 292 */ "vtabarglist", - /* 293 */ "vtabarg", - /* 294 */ "vtabargtoken", - /* 295 */ "lp", - /* 296 */ "anylist", - /* 297 */ "windowdefn_list", - /* 298 */ "windowdefn", - /* 299 */ "window", - /* 300 */ "frame_opt", - /* 301 */ "part_opt", - /* 302 */ "filter_clause", - /* 303 */ "over_clause", - /* 304 */ "range_or_rows", - /* 305 */ "frame_bound", - /* 306 */ "frame_bound_s", - /* 307 */ "frame_bound_e", - /* 308 */ "frame_exclude_opt", - /* 309 */ "frame_exclude", -}; -#endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */ - -#ifndef NDEBUG -/* For tracing reduce actions, the names of all rules are required. -*/ -static const char *const yyRuleName[] = { - /* 0 */ "explain ::= EXPLAIN", - /* 1 */ "explain ::= EXPLAIN QUERY PLAN", - /* 2 */ "cmdx ::= cmd", - /* 3 */ "cmd ::= BEGIN transtype trans_opt", - /* 4 */ "transtype ::=", - /* 5 */ "transtype ::= DEFERRED", - /* 6 */ "transtype ::= IMMEDIATE", - /* 7 */ "transtype ::= EXCLUSIVE", - /* 8 */ "cmd ::= COMMIT|END trans_opt", - /* 9 */ "cmd ::= ROLLBACK trans_opt", - /* 10 */ "cmd ::= SAVEPOINT nm", - /* 11 */ "cmd ::= RELEASE savepoint_opt nm", - /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm", - /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm", - /* 14 */ "createkw ::= CREATE", - /* 15 */ "ifnotexists ::=", - /* 16 */ "ifnotexists ::= IF NOT EXISTS", - /* 17 */ "temp ::= TEMP", - /* 18 */ "temp ::=", - /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options", - /* 20 */ "create_table_args ::= AS select", - /* 21 */ "table_options ::=", - /* 22 */ "table_options ::= WITHOUT nm", - /* 23 */ "columnname ::= nm typetoken", - /* 24 */ "typetoken ::=", - /* 25 */ "typetoken ::= typename LP signed RP", - /* 26 */ "typetoken ::= typename LP signed COMMA signed RP", - /* 27 */ "typename ::= typename ID|STRING", - /* 28 */ "scanpt ::=", - /* 29 */ "scantok ::=", - /* 30 */ "ccons ::= CONSTRAINT nm", - /* 31 */ "ccons ::= DEFAULT scantok term", - /* 32 */ "ccons ::= DEFAULT LP expr RP", - /* 33 */ "ccons ::= DEFAULT PLUS scantok term", - /* 34 */ "ccons ::= DEFAULT MINUS scantok term", - /* 35 */ "ccons ::= DEFAULT scantok ID|INDEXED", - /* 36 */ "ccons ::= NOT NULL onconf", - /* 37 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", - /* 38 */ "ccons ::= UNIQUE onconf", - /* 39 */ "ccons ::= CHECK LP expr RP", - /* 40 */ "ccons ::= REFERENCES nm eidlist_opt refargs", - /* 41 */ "ccons ::= defer_subclause", - /* 42 */ "ccons ::= COLLATE ID|STRING", - /* 43 */ "generated ::= LP expr RP", - /* 44 */ "generated ::= LP expr RP ID", - /* 45 */ "autoinc ::=", - /* 46 */ "autoinc ::= AUTOINCR", - /* 47 */ "refargs ::=", - /* 48 */ "refargs ::= refargs refarg", - /* 49 */ "refarg ::= MATCH nm", - /* 50 */ "refarg ::= ON INSERT refact", - /* 51 */ "refarg ::= ON DELETE refact", - /* 52 */ "refarg ::= ON UPDATE refact", - /* 53 */ "refact ::= SET NULL", - /* 54 */ "refact ::= SET DEFAULT", - /* 55 */ "refact ::= CASCADE", - /* 56 */ "refact ::= RESTRICT", - /* 57 */ "refact ::= NO ACTION", - /* 58 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", - /* 59 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", - /* 60 */ "init_deferred_pred_opt ::=", - /* 61 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", - /* 62 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", - /* 63 */ "conslist_opt ::=", - /* 64 */ "tconscomma ::= COMMA", - /* 65 */ "tcons ::= CONSTRAINT nm", - /* 66 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf", - /* 67 */ "tcons ::= UNIQUE LP sortlist RP onconf", - /* 68 */ "tcons ::= CHECK LP expr RP onconf", - /* 69 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt", - /* 70 */ "defer_subclause_opt ::=", - /* 71 */ "onconf ::=", - /* 72 */ "onconf ::= ON CONFLICT resolvetype", - /* 73 */ "orconf ::=", - /* 74 */ "orconf ::= OR resolvetype", - /* 75 */ "resolvetype ::= IGNORE", - /* 76 */ "resolvetype ::= REPLACE", - /* 77 */ "cmd ::= DROP TABLE ifexists fullname", - /* 78 */ "ifexists ::= IF EXISTS", - /* 79 */ "ifexists ::=", - /* 80 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select", - /* 81 */ "cmd ::= DROP VIEW ifexists fullname", - /* 82 */ "cmd ::= select", - /* 83 */ "select ::= WITH wqlist selectnowith", - /* 84 */ "select ::= WITH RECURSIVE wqlist selectnowith", - /* 85 */ "select ::= selectnowith", - /* 86 */ "selectnowith ::= selectnowith multiselect_op oneselect", - /* 87 */ "multiselect_op ::= UNION", - /* 88 */ "multiselect_op ::= UNION ALL", - /* 89 */ "multiselect_op ::= EXCEPT|INTERSECT", - /* 90 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", - /* 91 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt", - /* 92 */ "values ::= VALUES LP nexprlist RP", - /* 93 */ "values ::= values COMMA LP nexprlist RP", - /* 94 */ "distinct ::= DISTINCT", - /* 95 */ "distinct ::= ALL", - /* 96 */ "distinct ::=", - /* 97 */ "sclp ::=", - /* 98 */ "selcollist ::= sclp scanpt expr scanpt as", - /* 99 */ "selcollist ::= sclp scanpt STAR", - /* 100 */ "selcollist ::= sclp scanpt nm DOT STAR", - /* 101 */ "as ::= AS nm", - /* 102 */ "as ::=", - /* 103 */ "from ::=", - /* 104 */ "from ::= FROM seltablist", - /* 105 */ "stl_prefix ::= seltablist joinop", - /* 106 */ "stl_prefix ::=", - /* 107 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", - /* 108 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt", - /* 109 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", - /* 110 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", - /* 111 */ "dbnm ::=", - /* 112 */ "dbnm ::= DOT nm", - /* 113 */ "fullname ::= nm", - /* 114 */ "fullname ::= nm DOT nm", - /* 115 */ "xfullname ::= nm", - /* 116 */ "xfullname ::= nm DOT nm", - /* 117 */ "xfullname ::= nm DOT nm AS nm", - /* 118 */ "xfullname ::= nm AS nm", - /* 119 */ "joinop ::= COMMA|JOIN", - /* 120 */ "joinop ::= JOIN_KW JOIN", - /* 121 */ "joinop ::= JOIN_KW nm JOIN", - /* 122 */ "joinop ::= JOIN_KW nm nm JOIN", - /* 123 */ "on_opt ::= ON expr", - /* 124 */ "on_opt ::=", - /* 125 */ "indexed_opt ::=", - /* 126 */ "indexed_opt ::= INDEXED BY nm", - /* 127 */ "indexed_opt ::= NOT INDEXED", - /* 128 */ "using_opt ::= USING LP idlist RP", - /* 129 */ "using_opt ::=", - /* 130 */ "orderby_opt ::=", - /* 131 */ "orderby_opt ::= ORDER BY sortlist", - /* 132 */ "sortlist ::= sortlist COMMA expr sortorder nulls", - /* 133 */ "sortlist ::= expr sortorder nulls", - /* 134 */ "sortorder ::= ASC", - /* 135 */ "sortorder ::= DESC", - /* 136 */ "sortorder ::=", - /* 137 */ "nulls ::= NULLS FIRST", - /* 138 */ "nulls ::= NULLS LAST", - /* 139 */ "nulls ::=", - /* 140 */ "groupby_opt ::=", - /* 141 */ "groupby_opt ::= GROUP BY nexprlist", - /* 142 */ "having_opt ::=", - /* 143 */ "having_opt ::= HAVING expr", - /* 144 */ "limit_opt ::=", - /* 145 */ "limit_opt ::= LIMIT expr", - /* 146 */ "limit_opt ::= LIMIT expr OFFSET expr", - /* 147 */ "limit_opt ::= LIMIT expr COMMA expr", - /* 148 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt", - /* 149 */ "where_opt ::=", - /* 150 */ "where_opt ::= WHERE expr", - /* 151 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt", - /* 152 */ "setlist ::= setlist COMMA nm EQ expr", - /* 153 */ "setlist ::= setlist COMMA LP idlist RP EQ expr", - /* 154 */ "setlist ::= nm EQ expr", - /* 155 */ "setlist ::= LP idlist RP EQ expr", - /* 156 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert", - /* 157 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES", - /* 158 */ "upsert ::=", - /* 159 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt", - /* 160 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING", - /* 161 */ "upsert ::= ON CONFLICT DO NOTHING", - /* 162 */ "insert_cmd ::= INSERT orconf", - /* 163 */ "insert_cmd ::= REPLACE", - /* 164 */ "idlist_opt ::=", - /* 165 */ "idlist_opt ::= LP idlist RP", - /* 166 */ "idlist ::= idlist COMMA nm", - /* 167 */ "idlist ::= nm", - /* 168 */ "expr ::= LP expr RP", - /* 169 */ "expr ::= ID|INDEXED", - /* 170 */ "expr ::= JOIN_KW", - /* 171 */ "expr ::= nm DOT nm", - /* 172 */ "expr ::= nm DOT nm DOT nm", - /* 173 */ "term ::= NULL|FLOAT|BLOB", - /* 174 */ "term ::= STRING", - /* 175 */ "term ::= INTEGER", - /* 176 */ "expr ::= VARIABLE", - /* 177 */ "expr ::= expr COLLATE ID|STRING", - /* 178 */ "expr ::= CAST LP expr AS typetoken RP", - /* 179 */ "expr ::= ID|INDEXED LP distinct exprlist RP", - /* 180 */ "expr ::= ID|INDEXED LP STAR RP", - /* 181 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over", - /* 182 */ "expr ::= ID|INDEXED LP STAR RP filter_over", - /* 183 */ "term ::= CTIME_KW", - /* 184 */ "expr ::= LP nexprlist COMMA expr RP", - /* 185 */ "expr ::= expr AND expr", - /* 186 */ "expr ::= expr OR expr", - /* 187 */ "expr ::= expr LT|GT|GE|LE expr", - /* 188 */ "expr ::= expr EQ|NE expr", - /* 189 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", - /* 190 */ "expr ::= expr PLUS|MINUS expr", - /* 191 */ "expr ::= expr STAR|SLASH|REM expr", - /* 192 */ "expr ::= expr CONCAT expr", - /* 193 */ "likeop ::= NOT LIKE_KW|MATCH", - /* 194 */ "expr ::= expr likeop expr", - /* 195 */ "expr ::= expr likeop expr ESCAPE expr", - /* 196 */ "expr ::= expr ISNULL|NOTNULL", - /* 197 */ "expr ::= expr NOT NULL", - /* 198 */ "expr ::= expr IS expr", - /* 199 */ "expr ::= expr IS NOT expr", - /* 200 */ "expr ::= NOT expr", - /* 201 */ "expr ::= BITNOT expr", - /* 202 */ "expr ::= PLUS|MINUS expr", - /* 203 */ "between_op ::= BETWEEN", - /* 204 */ "between_op ::= NOT BETWEEN", - /* 205 */ "expr ::= expr between_op expr AND expr", - /* 206 */ "in_op ::= IN", - /* 207 */ "in_op ::= NOT IN", - /* 208 */ "expr ::= expr in_op LP exprlist RP", - /* 209 */ "expr ::= LP select RP", - /* 210 */ "expr ::= expr in_op LP select RP", - /* 211 */ "expr ::= expr in_op nm dbnm paren_exprlist", - /* 212 */ "expr ::= EXISTS LP select RP", - /* 213 */ "expr ::= CASE case_operand case_exprlist case_else END", - /* 214 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", - /* 215 */ "case_exprlist ::= WHEN expr THEN expr", - /* 216 */ "case_else ::= ELSE expr", - /* 217 */ "case_else ::=", - /* 218 */ "case_operand ::= expr", - /* 219 */ "case_operand ::=", - /* 220 */ "exprlist ::=", - /* 221 */ "nexprlist ::= nexprlist COMMA expr", - /* 222 */ "nexprlist ::= expr", - /* 223 */ "paren_exprlist ::=", - /* 224 */ "paren_exprlist ::= LP exprlist RP", - /* 225 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt", - /* 226 */ "uniqueflag ::= UNIQUE", - /* 227 */ "uniqueflag ::=", - /* 228 */ "eidlist_opt ::=", - /* 229 */ "eidlist_opt ::= LP eidlist RP", - /* 230 */ "eidlist ::= eidlist COMMA nm collate sortorder", - /* 231 */ "eidlist ::= nm collate sortorder", - /* 232 */ "collate ::=", - /* 233 */ "collate ::= COLLATE ID|STRING", - /* 234 */ "cmd ::= DROP INDEX ifexists fullname", - /* 235 */ "cmd ::= VACUUM vinto", - /* 236 */ "cmd ::= VACUUM nm vinto", - /* 237 */ "vinto ::= INTO expr", - /* 238 */ "vinto ::=", - /* 239 */ "cmd ::= PRAGMA nm dbnm", - /* 240 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", - /* 241 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", - /* 242 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", - /* 243 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", - /* 244 */ "plus_num ::= PLUS INTEGER|FLOAT", - /* 245 */ "minus_num ::= MINUS INTEGER|FLOAT", - /* 246 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", - /* 247 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", - /* 248 */ "trigger_time ::= BEFORE|AFTER", - /* 249 */ "trigger_time ::= INSTEAD OF", - /* 250 */ "trigger_time ::=", - /* 251 */ "trigger_event ::= DELETE|INSERT", - /* 252 */ "trigger_event ::= UPDATE", - /* 253 */ "trigger_event ::= UPDATE OF idlist", - /* 254 */ "when_clause ::=", - /* 255 */ "when_clause ::= WHEN expr", - /* 256 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", - /* 257 */ "trigger_cmd_list ::= trigger_cmd SEMI", - /* 258 */ "trnm ::= nm DOT nm", - /* 259 */ "tridxby ::= INDEXED BY nm", - /* 260 */ "tridxby ::= NOT INDEXED", - /* 261 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt", - /* 262 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt", - /* 263 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt", - /* 264 */ "trigger_cmd ::= scanpt select scanpt", - /* 265 */ "expr ::= RAISE LP IGNORE RP", - /* 266 */ "expr ::= RAISE LP raisetype COMMA nm RP", - /* 267 */ "raisetype ::= ROLLBACK", - /* 268 */ "raisetype ::= ABORT", - /* 269 */ "raisetype ::= FAIL", - /* 270 */ "cmd ::= DROP TRIGGER ifexists fullname", - /* 271 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", - /* 272 */ "cmd ::= DETACH database_kw_opt expr", - /* 273 */ "key_opt ::=", - /* 274 */ "key_opt ::= KEY expr", - /* 275 */ "cmd ::= REINDEX", - /* 276 */ "cmd ::= REINDEX nm dbnm", - /* 277 */ "cmd ::= ANALYZE", - /* 278 */ "cmd ::= ANALYZE nm dbnm", - /* 279 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", - /* 280 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", - /* 281 */ "add_column_fullname ::= fullname", - /* 282 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm", - /* 283 */ "cmd ::= create_vtab", - /* 284 */ "cmd ::= create_vtab LP vtabarglist RP", - /* 285 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", - /* 286 */ "vtabarg ::=", - /* 287 */ "vtabargtoken ::= ANY", - /* 288 */ "vtabargtoken ::= lp anylist RP", - /* 289 */ "lp ::= LP", - /* 290 */ "with ::= WITH wqlist", - /* 291 */ "with ::= WITH RECURSIVE wqlist", - /* 292 */ "wqlist ::= nm eidlist_opt AS LP select RP", - /* 293 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP", - /* 294 */ "windowdefn_list ::= windowdefn", - /* 295 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn", - /* 296 */ "windowdefn ::= nm AS LP window RP", - /* 297 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt", - /* 298 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt", - /* 299 */ "window ::= ORDER BY sortlist frame_opt", - /* 300 */ "window ::= nm ORDER BY sortlist frame_opt", - /* 301 */ "window ::= frame_opt", - /* 302 */ "window ::= nm frame_opt", - /* 303 */ "frame_opt ::=", - /* 304 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt", - /* 305 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt", - /* 306 */ "range_or_rows ::= RANGE|ROWS|GROUPS", - /* 307 */ "frame_bound_s ::= frame_bound", - /* 308 */ "frame_bound_s ::= UNBOUNDED PRECEDING", - /* 309 */ "frame_bound_e ::= frame_bound", - /* 310 */ "frame_bound_e ::= UNBOUNDED FOLLOWING", - /* 311 */ "frame_bound ::= expr PRECEDING|FOLLOWING", - /* 312 */ "frame_bound ::= CURRENT ROW", - /* 313 */ "frame_exclude_opt ::=", - /* 314 */ "frame_exclude_opt ::= EXCLUDE frame_exclude", - /* 315 */ "frame_exclude ::= NO OTHERS", - /* 316 */ "frame_exclude ::= CURRENT ROW", - /* 317 */ "frame_exclude ::= GROUP|TIES", - /* 318 */ "window_clause ::= WINDOW windowdefn_list", - /* 319 */ "filter_over ::= filter_clause over_clause", - /* 320 */ "filter_over ::= over_clause", - /* 321 */ "filter_over ::= filter_clause", - /* 322 */ "over_clause ::= OVER LP window RP", - /* 323 */ "over_clause ::= OVER nm", - /* 324 */ "filter_clause ::= FILTER LP WHERE expr RP", - /* 325 */ "input ::= cmdlist", - /* 326 */ "cmdlist ::= cmdlist ecmd", - /* 327 */ "cmdlist ::= ecmd", - /* 328 */ "ecmd ::= SEMI", - /* 329 */ "ecmd ::= cmdx SEMI", - /* 330 */ "ecmd ::= explain cmdx SEMI", - /* 331 */ "trans_opt ::=", - /* 332 */ "trans_opt ::= TRANSACTION", - /* 333 */ "trans_opt ::= TRANSACTION nm", - /* 334 */ "savepoint_opt ::= SAVEPOINT", - /* 335 */ "savepoint_opt ::=", - /* 336 */ "cmd ::= create_table create_table_args", - /* 337 */ "columnlist ::= columnlist COMMA columnname carglist", - /* 338 */ "columnlist ::= columnname carglist", - /* 339 */ "nm ::= ID|INDEXED", - /* 340 */ "nm ::= STRING", - /* 341 */ "nm ::= JOIN_KW", - /* 342 */ "typetoken ::= typename", - /* 343 */ "typename ::= ID|STRING", - /* 344 */ "signed ::= plus_num", - /* 345 */ "signed ::= minus_num", - /* 346 */ "carglist ::= carglist ccons", - /* 347 */ "carglist ::=", - /* 348 */ "ccons ::= NULL onconf", - /* 349 */ "ccons ::= GENERATED ALWAYS AS generated", - /* 350 */ "ccons ::= AS generated", - /* 351 */ "conslist_opt ::= COMMA conslist", - /* 352 */ "conslist ::= conslist tconscomma tcons", - /* 353 */ "conslist ::= tcons", - /* 354 */ "tconscomma ::=", - /* 355 */ "defer_subclause_opt ::= defer_subclause", - /* 356 */ "resolvetype ::= raisetype", - /* 357 */ "selectnowith ::= oneselect", - /* 358 */ "oneselect ::= values", - /* 359 */ "sclp ::= selcollist COMMA", - /* 360 */ "as ::= ID|STRING", - /* 361 */ "expr ::= term", - /* 362 */ "likeop ::= LIKE_KW|MATCH", - /* 363 */ "exprlist ::= nexprlist", - /* 364 */ "nmnum ::= plus_num", - /* 365 */ "nmnum ::= nm", - /* 366 */ "nmnum ::= ON", - /* 367 */ "nmnum ::= DELETE", - /* 368 */ "nmnum ::= DEFAULT", - /* 369 */ "plus_num ::= INTEGER|FLOAT", - /* 370 */ "foreach_clause ::=", - /* 371 */ "foreach_clause ::= FOR EACH ROW", - /* 372 */ "trnm ::= nm", - /* 373 */ "tridxby ::=", - /* 374 */ "database_kw_opt ::= DATABASE", - /* 375 */ "database_kw_opt ::=", - /* 376 */ "kwcolumn_opt ::=", - /* 377 */ "kwcolumn_opt ::= COLUMNKW", - /* 378 */ "vtabarglist ::= vtabarg", - /* 379 */ "vtabarglist ::= vtabarglist COMMA vtabarg", - /* 380 */ "vtabarg ::= vtabarg vtabargtoken", - /* 381 */ "anylist ::=", - /* 382 */ "anylist ::= anylist LP anylist RP", - /* 383 */ "anylist ::= anylist ANY", - /* 384 */ "with ::=", -}; -#endif /* NDEBUG */ - - -#if YYSTACKDEPTH<=0 -/* -** Try to increase the size of the parser stack. Return the number -** of errors. Return 0 on success. -*/ -static int yyGrowStack(yyParser *p){ - int newSize; - int idx; - yyStackEntry *pNew; - - newSize = p->yystksz*2 + 100; - idx = p->yytos ? (int)(p->yytos - p->yystack) : 0; - if( p->yystack==&p->yystk0 ){ - pNew = malloc(newSize*sizeof(pNew[0])); - if( pNew ) pNew[0] = p->yystk0; - }else{ - pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); - } - if( pNew ){ - p->yystack = pNew; - p->yytos = &p->yystack[idx]; -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n", - yyTracePrompt, p->yystksz, newSize); - } -#endif - p->yystksz = newSize; - } - return pNew==0; -} -#endif - -/* Datatype of the argument to the memory allocated passed as the -** second argument to sqlite3ParserAlloc() below. This can be changed by -** putting an appropriate #define in the %include section of the input -** grammar. -*/ -#ifndef YYMALLOCARGTYPE -# define YYMALLOCARGTYPE size_t -#endif - -/* Initialize a new parser that has already been allocated. -*/ -SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){ - yyParser *yypParser = (yyParser*)yypRawParser; - sqlite3ParserCTX_STORE -#ifdef YYTRACKMAXSTACKDEPTH - yypParser->yyhwm = 0; -#endif -#if YYSTACKDEPTH<=0 - yypParser->yytos = NULL; - yypParser->yystack = NULL; - yypParser->yystksz = 0; - if( yyGrowStack(yypParser) ){ - yypParser->yystack = &yypParser->yystk0; - yypParser->yystksz = 1; - } -#endif -#ifndef YYNOERRORRECOVERY - yypParser->yyerrcnt = -1; -#endif - yypParser->yytos = yypParser->yystack; - yypParser->yystack[0].stateno = 0; - yypParser->yystack[0].major = 0; -#if YYSTACKDEPTH>0 - yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1]; -#endif -} - -#ifndef sqlite3Parser_ENGINEALWAYSONSTACK -/* -** This function allocates a new parser. -** The only argument is a pointer to a function which works like -** malloc. -** -** Inputs: -** A pointer to the function used to allocate memory. -** -** Outputs: -** A pointer to a parser. This pointer is used in subsequent calls -** to sqlite3Parser and sqlite3ParserFree. -*/ -SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){ - yyParser *yypParser; - yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) ); - if( yypParser ){ - sqlite3ParserCTX_STORE - sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM); - } - return (void*)yypParser; -} -#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */ - - -/* The following function deletes the "minor type" or semantic value -** associated with a symbol. The symbol can be either a terminal -** or nonterminal. "yymajor" is the symbol code, and "yypminor" is -** a pointer to the value to be deleted. The code used to do the -** deletions is derived from the %destructor and/or %token_destructor -** directives of the input grammar. -*/ -static void yy_destructor( - yyParser *yypParser, /* The parser */ - YYCODETYPE yymajor, /* Type code for object to destroy */ - YYMINORTYPE *yypminor /* The object to be destroyed */ -){ - sqlite3ParserARG_FETCH - sqlite3ParserCTX_FETCH - switch( yymajor ){ - /* Here is inserted the actions which take place when a - ** terminal or non-terminal is destroyed. This can happen - ** when the symbol is popped from the stack during a - ** reduce or during error processing or when a parser is - ** being destroyed before it is finished parsing. - ** - ** Note: during a reduce, the only symbols destroyed are those - ** which appear on the RHS of the rule, but which are *not* used - ** inside the C code. - */ -/********* Begin destructor definitions ***************************************/ - case 200: /* select */ - case 234: /* selectnowith */ - case 235: /* oneselect */ - case 247: /* values */ -{ -sqlite3SelectDelete(pParse->db, (yypminor->yy539)); -} - break; - case 211: /* term */ - case 212: /* expr */ - case 241: /* where_opt */ - case 243: /* having_opt */ - case 255: /* on_opt */ - case 271: /* case_operand */ - case 273: /* case_else */ - case 276: /* vinto */ - case 283: /* when_clause */ - case 288: /* key_opt */ - case 302: /* filter_clause */ -{ -sqlite3ExprDelete(pParse->db, (yypminor->yy202)); -} - break; - case 216: /* eidlist_opt */ - case 226: /* sortlist */ - case 227: /* eidlist */ - case 239: /* selcollist */ - case 242: /* groupby_opt */ - case 244: /* orderby_opt */ - case 248: /* nexprlist */ - case 249: /* sclp */ - case 257: /* exprlist */ - case 262: /* setlist */ - case 270: /* paren_exprlist */ - case 272: /* case_exprlist */ - case 301: /* part_opt */ -{ -sqlite3ExprListDelete(pParse->db, (yypminor->yy242)); -} - break; - case 233: /* fullname */ - case 240: /* from */ - case 251: /* seltablist */ - case 252: /* stl_prefix */ - case 258: /* xfullname */ -{ -sqlite3SrcListDelete(pParse->db, (yypminor->yy47)); -} - break; - case 236: /* wqlist */ -{ -sqlite3WithDelete(pParse->db, (yypminor->yy131)); -} - break; - case 246: /* window_clause */ - case 297: /* windowdefn_list */ -{ -sqlite3WindowListDelete(pParse->db, (yypminor->yy303)); -} - break; - case 256: /* using_opt */ - case 259: /* idlist */ - case 264: /* idlist_opt */ -{ -sqlite3IdListDelete(pParse->db, (yypminor->yy600)); -} - break; - case 266: /* filter_over */ - case 298: /* windowdefn */ - case 299: /* window */ - case 300: /* frame_opt */ - case 303: /* over_clause */ -{ -sqlite3WindowDelete(pParse->db, (yypminor->yy303)); -} - break; - case 279: /* trigger_cmd_list */ - case 284: /* trigger_cmd */ -{ -sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy447)); -} - break; - case 281: /* trigger_event */ -{ -sqlite3IdListDelete(pParse->db, (yypminor->yy230).b); -} - break; - case 305: /* frame_bound */ - case 306: /* frame_bound_s */ - case 307: /* frame_bound_e */ -{ -sqlite3ExprDelete(pParse->db, (yypminor->yy77).pExpr); -} - break; -/********* End destructor definitions *****************************************/ - default: break; /* If no destructor action specified: do nothing */ - } -} - -/* -** Pop the parser's stack once. -** -** If there is a destructor routine associated with the token which -** is popped from the stack, then call it. -*/ -static void yy_pop_parser_stack(yyParser *pParser){ - yyStackEntry *yytos; - assert( pParser->yytos!=0 ); - assert( pParser->yytos > pParser->yystack ); - yytos = pParser->yytos--; -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sPopping %s\n", - yyTracePrompt, - yyTokenName[yytos->major]); - } -#endif - yy_destructor(pParser, yytos->major, &yytos->minor); -} - -/* -** Clear all secondary memory allocations from the parser -*/ -SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){ - yyParser *pParser = (yyParser*)p; - while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser); -#if YYSTACKDEPTH<=0 - if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack); -#endif -} - -#ifndef sqlite3Parser_ENGINEALWAYSONSTACK -/* -** Deallocate and destroy a parser. Destructors are called for -** all stack elements before shutting the parser down. -** -** If the YYPARSEFREENEVERNULL macro exists (for example because it -** is defined in a %include section of the input grammar) then it is -** assumed that the input pointer is never NULL. -*/ -SQLITE_PRIVATE void sqlite3ParserFree( - void *p, /* The parser to be deleted */ - void (*freeProc)(void*) /* Function used to reclaim memory */ -){ -#ifndef YYPARSEFREENEVERNULL - if( p==0 ) return; -#endif - sqlite3ParserFinalize(p); - (*freeProc)(p); -} -#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */ - -/* -** Return the peak depth of the stack for a parser. -*/ -#ifdef YYTRACKMAXSTACKDEPTH -SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){ - yyParser *pParser = (yyParser*)p; - return pParser->yyhwm; -} -#endif - -/* This array of booleans keeps track of the parser statement -** coverage. The element yycoverage[X][Y] is set when the parser -** is in state X and has a lookahead token Y. In a well-tested -** systems, every element of this matrix should end up being set. -*/ -#if defined(YYCOVERAGE) -static unsigned char yycoverage[YYNSTATE][YYNTOKEN]; -#endif - -/* -** Write into out a description of every state/lookahead combination that -** -** (1) has not been used by the parser, and -** (2) is not a syntax error. -** -** Return the number of missed state/lookahead combinations. -*/ -#if defined(YYCOVERAGE) -SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){ - int stateno, iLookAhead, i; - int nMissed = 0; - for(stateno=0; statenoYY_MAX_SHIFT ) return stateno; - assert( stateno <= YY_SHIFT_COUNT ); -#if defined(YYCOVERAGE) - yycoverage[stateno][iLookAhead] = 1; -#endif - do{ - i = yy_shift_ofst[stateno]; - assert( i>=0 ); - assert( i<=YY_ACTTAB_COUNT ); - assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD ); - assert( iLookAhead!=YYNOCODE ); - assert( iLookAhead < YYNTOKEN ); - i += iLookAhead; - assert( i<(int)YY_NLOOKAHEAD ); - if( yy_lookahead[i]!=iLookAhead ){ -#ifdef YYFALLBACK - YYCODETYPE iFallback; /* Fallback token */ - assert( iLookAhead %s\n", - yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); - } -#endif - assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */ - iLookAhead = iFallback; - continue; - } -#endif -#ifdef YYWILDCARD - { - int j = i - iLookAhead + YYWILDCARD; - assert( j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) ); - if( yy_lookahead[j]==YYWILDCARD && iLookAhead>0 ){ -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n", - yyTracePrompt, yyTokenName[iLookAhead], - yyTokenName[YYWILDCARD]); - } -#endif /* NDEBUG */ - return yy_action[j]; - } - } -#endif /* YYWILDCARD */ - return yy_default[stateno]; - }else{ - assert( i>=0 && iYY_REDUCE_COUNT ){ - return yy_default[stateno]; - } -#else - assert( stateno<=YY_REDUCE_COUNT ); -#endif - i = yy_reduce_ofst[stateno]; - assert( iLookAhead!=YYNOCODE ); - i += iLookAhead; -#ifdef YYERRORSYMBOL - if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ - return yy_default[stateno]; - } -#else - assert( i>=0 && iyytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); - /* Here code is inserted which will execute if the parser - ** stack every overflows */ -/******** Begin %stack_overflow code ******************************************/ - - sqlite3ErrorMsg(pParse, "parser stack overflow"); -/******** End %stack_overflow code ********************************************/ - sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */ - sqlite3ParserCTX_STORE -} - -/* -** Print tracing information for a SHIFT action -*/ -#ifndef NDEBUG -static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){ - if( yyTraceFILE ){ - if( yyNewStateyytos->major], - yyNewState); - }else{ - fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n", - yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major], - yyNewState - YY_MIN_REDUCE); - } - } -} -#else -# define yyTraceShift(X,Y,Z) -#endif - -/* -** Perform a shift action. -*/ -static void yy_shift( - yyParser *yypParser, /* The parser to be shifted */ - YYACTIONTYPE yyNewState, /* The new state to shift in */ - YYCODETYPE yyMajor, /* The major token to shift in */ - sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */ -){ - yyStackEntry *yytos; - yypParser->yytos++; -#ifdef YYTRACKMAXSTACKDEPTH - if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){ - yypParser->yyhwm++; - assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) ); - } -#endif -#if YYSTACKDEPTH>0 - if( yypParser->yytos>yypParser->yystackEnd ){ - yypParser->yytos--; - yyStackOverflow(yypParser); - return; - } -#else - if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){ - if( yyGrowStack(yypParser) ){ - yypParser->yytos--; - yyStackOverflow(yypParser); - return; - } - } -#endif - if( yyNewState > YY_MAX_SHIFT ){ - yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE; - } - yytos = yypParser->yytos; - yytos->stateno = yyNewState; - yytos->major = yyMajor; - yytos->minor.yy0 = yyMinor; - yyTraceShift(yypParser, yyNewState, "Shift"); -} - -/* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side -** of that rule */ -static const YYCODETYPE yyRuleInfoLhs[] = { - 185, /* (0) explain ::= EXPLAIN */ - 185, /* (1) explain ::= EXPLAIN QUERY PLAN */ - 184, /* (2) cmdx ::= cmd */ - 186, /* (3) cmd ::= BEGIN transtype trans_opt */ - 187, /* (4) transtype ::= */ - 187, /* (5) transtype ::= DEFERRED */ - 187, /* (6) transtype ::= IMMEDIATE */ - 187, /* (7) transtype ::= EXCLUSIVE */ - 186, /* (8) cmd ::= COMMIT|END trans_opt */ - 186, /* (9) cmd ::= ROLLBACK trans_opt */ - 186, /* (10) cmd ::= SAVEPOINT nm */ - 186, /* (11) cmd ::= RELEASE savepoint_opt nm */ - 186, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ - 191, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */ - 193, /* (14) createkw ::= CREATE */ - 195, /* (15) ifnotexists ::= */ - 195, /* (16) ifnotexists ::= IF NOT EXISTS */ - 194, /* (17) temp ::= TEMP */ - 194, /* (18) temp ::= */ - 192, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */ - 192, /* (20) create_table_args ::= AS select */ - 199, /* (21) table_options ::= */ - 199, /* (22) table_options ::= WITHOUT nm */ - 201, /* (23) columnname ::= nm typetoken */ - 203, /* (24) typetoken ::= */ - 203, /* (25) typetoken ::= typename LP signed RP */ - 203, /* (26) typetoken ::= typename LP signed COMMA signed RP */ - 204, /* (27) typename ::= typename ID|STRING */ - 208, /* (28) scanpt ::= */ - 209, /* (29) scantok ::= */ - 210, /* (30) ccons ::= CONSTRAINT nm */ - 210, /* (31) ccons ::= DEFAULT scantok term */ - 210, /* (32) ccons ::= DEFAULT LP expr RP */ - 210, /* (33) ccons ::= DEFAULT PLUS scantok term */ - 210, /* (34) ccons ::= DEFAULT MINUS scantok term */ - 210, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */ - 210, /* (36) ccons ::= NOT NULL onconf */ - 210, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */ - 210, /* (38) ccons ::= UNIQUE onconf */ - 210, /* (39) ccons ::= CHECK LP expr RP */ - 210, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */ - 210, /* (41) ccons ::= defer_subclause */ - 210, /* (42) ccons ::= COLLATE ID|STRING */ - 219, /* (43) generated ::= LP expr RP */ - 219, /* (44) generated ::= LP expr RP ID */ - 215, /* (45) autoinc ::= */ - 215, /* (46) autoinc ::= AUTOINCR */ - 217, /* (47) refargs ::= */ - 217, /* (48) refargs ::= refargs refarg */ - 220, /* (49) refarg ::= MATCH nm */ - 220, /* (50) refarg ::= ON INSERT refact */ - 220, /* (51) refarg ::= ON DELETE refact */ - 220, /* (52) refarg ::= ON UPDATE refact */ - 221, /* (53) refact ::= SET NULL */ - 221, /* (54) refact ::= SET DEFAULT */ - 221, /* (55) refact ::= CASCADE */ - 221, /* (56) refact ::= RESTRICT */ - 221, /* (57) refact ::= NO ACTION */ - 218, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ - 218, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ - 222, /* (60) init_deferred_pred_opt ::= */ - 222, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */ - 222, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ - 198, /* (63) conslist_opt ::= */ - 224, /* (64) tconscomma ::= COMMA */ - 225, /* (65) tcons ::= CONSTRAINT nm */ - 225, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ - 225, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */ - 225, /* (68) tcons ::= CHECK LP expr RP onconf */ - 225, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ - 228, /* (70) defer_subclause_opt ::= */ - 213, /* (71) onconf ::= */ - 213, /* (72) onconf ::= ON CONFLICT resolvetype */ - 229, /* (73) orconf ::= */ - 229, /* (74) orconf ::= OR resolvetype */ - 230, /* (75) resolvetype ::= IGNORE */ - 230, /* (76) resolvetype ::= REPLACE */ - 186, /* (77) cmd ::= DROP TABLE ifexists fullname */ - 232, /* (78) ifexists ::= IF EXISTS */ - 232, /* (79) ifexists ::= */ - 186, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ - 186, /* (81) cmd ::= DROP VIEW ifexists fullname */ - 186, /* (82) cmd ::= select */ - 200, /* (83) select ::= WITH wqlist selectnowith */ - 200, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */ - 200, /* (85) select ::= selectnowith */ - 234, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */ - 237, /* (87) multiselect_op ::= UNION */ - 237, /* (88) multiselect_op ::= UNION ALL */ - 237, /* (89) multiselect_op ::= EXCEPT|INTERSECT */ - 235, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ - 235, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ - 247, /* (92) values ::= VALUES LP nexprlist RP */ - 247, /* (93) values ::= values COMMA LP nexprlist RP */ - 238, /* (94) distinct ::= DISTINCT */ - 238, /* (95) distinct ::= ALL */ - 238, /* (96) distinct ::= */ - 249, /* (97) sclp ::= */ - 239, /* (98) selcollist ::= sclp scanpt expr scanpt as */ - 239, /* (99) selcollist ::= sclp scanpt STAR */ - 239, /* (100) selcollist ::= sclp scanpt nm DOT STAR */ - 250, /* (101) as ::= AS nm */ - 250, /* (102) as ::= */ - 240, /* (103) from ::= */ - 240, /* (104) from ::= FROM seltablist */ - 252, /* (105) stl_prefix ::= seltablist joinop */ - 252, /* (106) stl_prefix ::= */ - 251, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ - 251, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ - 251, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */ - 251, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ - 196, /* (111) dbnm ::= */ - 196, /* (112) dbnm ::= DOT nm */ - 233, /* (113) fullname ::= nm */ - 233, /* (114) fullname ::= nm DOT nm */ - 258, /* (115) xfullname ::= nm */ - 258, /* (116) xfullname ::= nm DOT nm */ - 258, /* (117) xfullname ::= nm DOT nm AS nm */ - 258, /* (118) xfullname ::= nm AS nm */ - 253, /* (119) joinop ::= COMMA|JOIN */ - 253, /* (120) joinop ::= JOIN_KW JOIN */ - 253, /* (121) joinop ::= JOIN_KW nm JOIN */ - 253, /* (122) joinop ::= JOIN_KW nm nm JOIN */ - 255, /* (123) on_opt ::= ON expr */ - 255, /* (124) on_opt ::= */ - 254, /* (125) indexed_opt ::= */ - 254, /* (126) indexed_opt ::= INDEXED BY nm */ - 254, /* (127) indexed_opt ::= NOT INDEXED */ - 256, /* (128) using_opt ::= USING LP idlist RP */ - 256, /* (129) using_opt ::= */ - 244, /* (130) orderby_opt ::= */ - 244, /* (131) orderby_opt ::= ORDER BY sortlist */ - 226, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */ - 226, /* (133) sortlist ::= expr sortorder nulls */ - 214, /* (134) sortorder ::= ASC */ - 214, /* (135) sortorder ::= DESC */ - 214, /* (136) sortorder ::= */ - 260, /* (137) nulls ::= NULLS FIRST */ - 260, /* (138) nulls ::= NULLS LAST */ - 260, /* (139) nulls ::= */ - 242, /* (140) groupby_opt ::= */ - 242, /* (141) groupby_opt ::= GROUP BY nexprlist */ - 243, /* (142) having_opt ::= */ - 243, /* (143) having_opt ::= HAVING expr */ - 245, /* (144) limit_opt ::= */ - 245, /* (145) limit_opt ::= LIMIT expr */ - 245, /* (146) limit_opt ::= LIMIT expr OFFSET expr */ - 245, /* (147) limit_opt ::= LIMIT expr COMMA expr */ - 186, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */ - 241, /* (149) where_opt ::= */ - 241, /* (150) where_opt ::= WHERE expr */ - 186, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt */ - 262, /* (152) setlist ::= setlist COMMA nm EQ expr */ - 262, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */ - 262, /* (154) setlist ::= nm EQ expr */ - 262, /* (155) setlist ::= LP idlist RP EQ expr */ - 186, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ - 186, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */ - 265, /* (158) upsert ::= */ - 265, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */ - 265, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */ - 265, /* (161) upsert ::= ON CONFLICT DO NOTHING */ - 263, /* (162) insert_cmd ::= INSERT orconf */ - 263, /* (163) insert_cmd ::= REPLACE */ - 264, /* (164) idlist_opt ::= */ - 264, /* (165) idlist_opt ::= LP idlist RP */ - 259, /* (166) idlist ::= idlist COMMA nm */ - 259, /* (167) idlist ::= nm */ - 212, /* (168) expr ::= LP expr RP */ - 212, /* (169) expr ::= ID|INDEXED */ - 212, /* (170) expr ::= JOIN_KW */ - 212, /* (171) expr ::= nm DOT nm */ - 212, /* (172) expr ::= nm DOT nm DOT nm */ - 211, /* (173) term ::= NULL|FLOAT|BLOB */ - 211, /* (174) term ::= STRING */ - 211, /* (175) term ::= INTEGER */ - 212, /* (176) expr ::= VARIABLE */ - 212, /* (177) expr ::= expr COLLATE ID|STRING */ - 212, /* (178) expr ::= CAST LP expr AS typetoken RP */ - 212, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */ - 212, /* (180) expr ::= ID|INDEXED LP STAR RP */ - 212, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */ - 212, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */ - 211, /* (183) term ::= CTIME_KW */ - 212, /* (184) expr ::= LP nexprlist COMMA expr RP */ - 212, /* (185) expr ::= expr AND expr */ - 212, /* (186) expr ::= expr OR expr */ - 212, /* (187) expr ::= expr LT|GT|GE|LE expr */ - 212, /* (188) expr ::= expr EQ|NE expr */ - 212, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ - 212, /* (190) expr ::= expr PLUS|MINUS expr */ - 212, /* (191) expr ::= expr STAR|SLASH|REM expr */ - 212, /* (192) expr ::= expr CONCAT expr */ - 267, /* (193) likeop ::= NOT LIKE_KW|MATCH */ - 212, /* (194) expr ::= expr likeop expr */ - 212, /* (195) expr ::= expr likeop expr ESCAPE expr */ - 212, /* (196) expr ::= expr ISNULL|NOTNULL */ - 212, /* (197) expr ::= expr NOT NULL */ - 212, /* (198) expr ::= expr IS expr */ - 212, /* (199) expr ::= expr IS NOT expr */ - 212, /* (200) expr ::= NOT expr */ - 212, /* (201) expr ::= BITNOT expr */ - 212, /* (202) expr ::= PLUS|MINUS expr */ - 268, /* (203) between_op ::= BETWEEN */ - 268, /* (204) between_op ::= NOT BETWEEN */ - 212, /* (205) expr ::= expr between_op expr AND expr */ - 269, /* (206) in_op ::= IN */ - 269, /* (207) in_op ::= NOT IN */ - 212, /* (208) expr ::= expr in_op LP exprlist RP */ - 212, /* (209) expr ::= LP select RP */ - 212, /* (210) expr ::= expr in_op LP select RP */ - 212, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */ - 212, /* (212) expr ::= EXISTS LP select RP */ - 212, /* (213) expr ::= CASE case_operand case_exprlist case_else END */ - 272, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */ - 272, /* (215) case_exprlist ::= WHEN expr THEN expr */ - 273, /* (216) case_else ::= ELSE expr */ - 273, /* (217) case_else ::= */ - 271, /* (218) case_operand ::= expr */ - 271, /* (219) case_operand ::= */ - 257, /* (220) exprlist ::= */ - 248, /* (221) nexprlist ::= nexprlist COMMA expr */ - 248, /* (222) nexprlist ::= expr */ - 270, /* (223) paren_exprlist ::= */ - 270, /* (224) paren_exprlist ::= LP exprlist RP */ - 186, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ - 274, /* (226) uniqueflag ::= UNIQUE */ - 274, /* (227) uniqueflag ::= */ - 216, /* (228) eidlist_opt ::= */ - 216, /* (229) eidlist_opt ::= LP eidlist RP */ - 227, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */ - 227, /* (231) eidlist ::= nm collate sortorder */ - 275, /* (232) collate ::= */ - 275, /* (233) collate ::= COLLATE ID|STRING */ - 186, /* (234) cmd ::= DROP INDEX ifexists fullname */ - 186, /* (235) cmd ::= VACUUM vinto */ - 186, /* (236) cmd ::= VACUUM nm vinto */ - 276, /* (237) vinto ::= INTO expr */ - 276, /* (238) vinto ::= */ - 186, /* (239) cmd ::= PRAGMA nm dbnm */ - 186, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */ - 186, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */ - 186, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */ - 186, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */ - 206, /* (244) plus_num ::= PLUS INTEGER|FLOAT */ - 207, /* (245) minus_num ::= MINUS INTEGER|FLOAT */ - 186, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ - 278, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ - 280, /* (248) trigger_time ::= BEFORE|AFTER */ - 280, /* (249) trigger_time ::= INSTEAD OF */ - 280, /* (250) trigger_time ::= */ - 281, /* (251) trigger_event ::= DELETE|INSERT */ - 281, /* (252) trigger_event ::= UPDATE */ - 281, /* (253) trigger_event ::= UPDATE OF idlist */ - 283, /* (254) when_clause ::= */ - 283, /* (255) when_clause ::= WHEN expr */ - 279, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ - 279, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */ - 285, /* (258) trnm ::= nm DOT nm */ - 286, /* (259) tridxby ::= INDEXED BY nm */ - 286, /* (260) tridxby ::= NOT INDEXED */ - 284, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */ - 284, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ - 284, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ - 284, /* (264) trigger_cmd ::= scanpt select scanpt */ - 212, /* (265) expr ::= RAISE LP IGNORE RP */ - 212, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */ - 231, /* (267) raisetype ::= ROLLBACK */ - 231, /* (268) raisetype ::= ABORT */ - 231, /* (269) raisetype ::= FAIL */ - 186, /* (270) cmd ::= DROP TRIGGER ifexists fullname */ - 186, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ - 186, /* (272) cmd ::= DETACH database_kw_opt expr */ - 288, /* (273) key_opt ::= */ - 288, /* (274) key_opt ::= KEY expr */ - 186, /* (275) cmd ::= REINDEX */ - 186, /* (276) cmd ::= REINDEX nm dbnm */ - 186, /* (277) cmd ::= ANALYZE */ - 186, /* (278) cmd ::= ANALYZE nm dbnm */ - 186, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */ - 186, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ - 289, /* (281) add_column_fullname ::= fullname */ - 186, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ - 186, /* (283) cmd ::= create_vtab */ - 186, /* (284) cmd ::= create_vtab LP vtabarglist RP */ - 291, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ - 293, /* (286) vtabarg ::= */ - 294, /* (287) vtabargtoken ::= ANY */ - 294, /* (288) vtabargtoken ::= lp anylist RP */ - 295, /* (289) lp ::= LP */ - 261, /* (290) with ::= WITH wqlist */ - 261, /* (291) with ::= WITH RECURSIVE wqlist */ - 236, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */ - 236, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ - 297, /* (294) windowdefn_list ::= windowdefn */ - 297, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */ - 298, /* (296) windowdefn ::= nm AS LP window RP */ - 299, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ - 299, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ - 299, /* (299) window ::= ORDER BY sortlist frame_opt */ - 299, /* (300) window ::= nm ORDER BY sortlist frame_opt */ - 299, /* (301) window ::= frame_opt */ - 299, /* (302) window ::= nm frame_opt */ - 300, /* (303) frame_opt ::= */ - 300, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ - 300, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ - 304, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */ - 306, /* (307) frame_bound_s ::= frame_bound */ - 306, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */ - 307, /* (309) frame_bound_e ::= frame_bound */ - 307, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */ - 305, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */ - 305, /* (312) frame_bound ::= CURRENT ROW */ - 308, /* (313) frame_exclude_opt ::= */ - 308, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */ - 309, /* (315) frame_exclude ::= NO OTHERS */ - 309, /* (316) frame_exclude ::= CURRENT ROW */ - 309, /* (317) frame_exclude ::= GROUP|TIES */ - 246, /* (318) window_clause ::= WINDOW windowdefn_list */ - 266, /* (319) filter_over ::= filter_clause over_clause */ - 266, /* (320) filter_over ::= over_clause */ - 266, /* (321) filter_over ::= filter_clause */ - 303, /* (322) over_clause ::= OVER LP window RP */ - 303, /* (323) over_clause ::= OVER nm */ - 302, /* (324) filter_clause ::= FILTER LP WHERE expr RP */ - 181, /* (325) input ::= cmdlist */ - 182, /* (326) cmdlist ::= cmdlist ecmd */ - 182, /* (327) cmdlist ::= ecmd */ - 183, /* (328) ecmd ::= SEMI */ - 183, /* (329) ecmd ::= cmdx SEMI */ - 183, /* (330) ecmd ::= explain cmdx SEMI */ - 188, /* (331) trans_opt ::= */ - 188, /* (332) trans_opt ::= TRANSACTION */ - 188, /* (333) trans_opt ::= TRANSACTION nm */ - 190, /* (334) savepoint_opt ::= SAVEPOINT */ - 190, /* (335) savepoint_opt ::= */ - 186, /* (336) cmd ::= create_table create_table_args */ - 197, /* (337) columnlist ::= columnlist COMMA columnname carglist */ - 197, /* (338) columnlist ::= columnname carglist */ - 189, /* (339) nm ::= ID|INDEXED */ - 189, /* (340) nm ::= STRING */ - 189, /* (341) nm ::= JOIN_KW */ - 203, /* (342) typetoken ::= typename */ - 204, /* (343) typename ::= ID|STRING */ - 205, /* (344) signed ::= plus_num */ - 205, /* (345) signed ::= minus_num */ - 202, /* (346) carglist ::= carglist ccons */ - 202, /* (347) carglist ::= */ - 210, /* (348) ccons ::= NULL onconf */ - 210, /* (349) ccons ::= GENERATED ALWAYS AS generated */ - 210, /* (350) ccons ::= AS generated */ - 198, /* (351) conslist_opt ::= COMMA conslist */ - 223, /* (352) conslist ::= conslist tconscomma tcons */ - 223, /* (353) conslist ::= tcons */ - 224, /* (354) tconscomma ::= */ - 228, /* (355) defer_subclause_opt ::= defer_subclause */ - 230, /* (356) resolvetype ::= raisetype */ - 234, /* (357) selectnowith ::= oneselect */ - 235, /* (358) oneselect ::= values */ - 249, /* (359) sclp ::= selcollist COMMA */ - 250, /* (360) as ::= ID|STRING */ - 212, /* (361) expr ::= term */ - 267, /* (362) likeop ::= LIKE_KW|MATCH */ - 257, /* (363) exprlist ::= nexprlist */ - 277, /* (364) nmnum ::= plus_num */ - 277, /* (365) nmnum ::= nm */ - 277, /* (366) nmnum ::= ON */ - 277, /* (367) nmnum ::= DELETE */ - 277, /* (368) nmnum ::= DEFAULT */ - 206, /* (369) plus_num ::= INTEGER|FLOAT */ - 282, /* (370) foreach_clause ::= */ - 282, /* (371) foreach_clause ::= FOR EACH ROW */ - 285, /* (372) trnm ::= nm */ - 286, /* (373) tridxby ::= */ - 287, /* (374) database_kw_opt ::= DATABASE */ - 287, /* (375) database_kw_opt ::= */ - 290, /* (376) kwcolumn_opt ::= */ - 290, /* (377) kwcolumn_opt ::= COLUMNKW */ - 292, /* (378) vtabarglist ::= vtabarg */ - 292, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ - 293, /* (380) vtabarg ::= vtabarg vtabargtoken */ - 296, /* (381) anylist ::= */ - 296, /* (382) anylist ::= anylist LP anylist RP */ - 296, /* (383) anylist ::= anylist ANY */ - 261, /* (384) with ::= */ -}; - -/* For rule J, yyRuleInfoNRhs[J] contains the negative of the number -** of symbols on the right-hand side of that rule. */ -static const signed char yyRuleInfoNRhs[] = { - -1, /* (0) explain ::= EXPLAIN */ - -3, /* (1) explain ::= EXPLAIN QUERY PLAN */ - -1, /* (2) cmdx ::= cmd */ - -3, /* (3) cmd ::= BEGIN transtype trans_opt */ - 0, /* (4) transtype ::= */ - -1, /* (5) transtype ::= DEFERRED */ - -1, /* (6) transtype ::= IMMEDIATE */ - -1, /* (7) transtype ::= EXCLUSIVE */ - -2, /* (8) cmd ::= COMMIT|END trans_opt */ - -2, /* (9) cmd ::= ROLLBACK trans_opt */ - -2, /* (10) cmd ::= SAVEPOINT nm */ - -3, /* (11) cmd ::= RELEASE savepoint_opt nm */ - -5, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ - -6, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */ - -1, /* (14) createkw ::= CREATE */ - 0, /* (15) ifnotexists ::= */ - -3, /* (16) ifnotexists ::= IF NOT EXISTS */ - -1, /* (17) temp ::= TEMP */ - 0, /* (18) temp ::= */ - -5, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */ - -2, /* (20) create_table_args ::= AS select */ - 0, /* (21) table_options ::= */ - -2, /* (22) table_options ::= WITHOUT nm */ - -2, /* (23) columnname ::= nm typetoken */ - 0, /* (24) typetoken ::= */ - -4, /* (25) typetoken ::= typename LP signed RP */ - -6, /* (26) typetoken ::= typename LP signed COMMA signed RP */ - -2, /* (27) typename ::= typename ID|STRING */ - 0, /* (28) scanpt ::= */ - 0, /* (29) scantok ::= */ - -2, /* (30) ccons ::= CONSTRAINT nm */ - -3, /* (31) ccons ::= DEFAULT scantok term */ - -4, /* (32) ccons ::= DEFAULT LP expr RP */ - -4, /* (33) ccons ::= DEFAULT PLUS scantok term */ - -4, /* (34) ccons ::= DEFAULT MINUS scantok term */ - -3, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */ - -3, /* (36) ccons ::= NOT NULL onconf */ - -5, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */ - -2, /* (38) ccons ::= UNIQUE onconf */ - -4, /* (39) ccons ::= CHECK LP expr RP */ - -4, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */ - -1, /* (41) ccons ::= defer_subclause */ - -2, /* (42) ccons ::= COLLATE ID|STRING */ - -3, /* (43) generated ::= LP expr RP */ - -4, /* (44) generated ::= LP expr RP ID */ - 0, /* (45) autoinc ::= */ - -1, /* (46) autoinc ::= AUTOINCR */ - 0, /* (47) refargs ::= */ - -2, /* (48) refargs ::= refargs refarg */ - -2, /* (49) refarg ::= MATCH nm */ - -3, /* (50) refarg ::= ON INSERT refact */ - -3, /* (51) refarg ::= ON DELETE refact */ - -3, /* (52) refarg ::= ON UPDATE refact */ - -2, /* (53) refact ::= SET NULL */ - -2, /* (54) refact ::= SET DEFAULT */ - -1, /* (55) refact ::= CASCADE */ - -1, /* (56) refact ::= RESTRICT */ - -2, /* (57) refact ::= NO ACTION */ - -3, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ - -2, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ - 0, /* (60) init_deferred_pred_opt ::= */ - -2, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */ - -2, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ - 0, /* (63) conslist_opt ::= */ - -1, /* (64) tconscomma ::= COMMA */ - -2, /* (65) tcons ::= CONSTRAINT nm */ - -7, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ - -5, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */ - -5, /* (68) tcons ::= CHECK LP expr RP onconf */ - -10, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ - 0, /* (70) defer_subclause_opt ::= */ - 0, /* (71) onconf ::= */ - -3, /* (72) onconf ::= ON CONFLICT resolvetype */ - 0, /* (73) orconf ::= */ - -2, /* (74) orconf ::= OR resolvetype */ - -1, /* (75) resolvetype ::= IGNORE */ - -1, /* (76) resolvetype ::= REPLACE */ - -4, /* (77) cmd ::= DROP TABLE ifexists fullname */ - -2, /* (78) ifexists ::= IF EXISTS */ - 0, /* (79) ifexists ::= */ - -9, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ - -4, /* (81) cmd ::= DROP VIEW ifexists fullname */ - -1, /* (82) cmd ::= select */ - -3, /* (83) select ::= WITH wqlist selectnowith */ - -4, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */ - -1, /* (85) select ::= selectnowith */ - -3, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */ - -1, /* (87) multiselect_op ::= UNION */ - -2, /* (88) multiselect_op ::= UNION ALL */ - -1, /* (89) multiselect_op ::= EXCEPT|INTERSECT */ - -9, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ - -10, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ - -4, /* (92) values ::= VALUES LP nexprlist RP */ - -5, /* (93) values ::= values COMMA LP nexprlist RP */ - -1, /* (94) distinct ::= DISTINCT */ - -1, /* (95) distinct ::= ALL */ - 0, /* (96) distinct ::= */ - 0, /* (97) sclp ::= */ - -5, /* (98) selcollist ::= sclp scanpt expr scanpt as */ - -3, /* (99) selcollist ::= sclp scanpt STAR */ - -5, /* (100) selcollist ::= sclp scanpt nm DOT STAR */ - -2, /* (101) as ::= AS nm */ - 0, /* (102) as ::= */ - 0, /* (103) from ::= */ - -2, /* (104) from ::= FROM seltablist */ - -2, /* (105) stl_prefix ::= seltablist joinop */ - 0, /* (106) stl_prefix ::= */ - -7, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ - -9, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ - -7, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */ - -7, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ - 0, /* (111) dbnm ::= */ - -2, /* (112) dbnm ::= DOT nm */ - -1, /* (113) fullname ::= nm */ - -3, /* (114) fullname ::= nm DOT nm */ - -1, /* (115) xfullname ::= nm */ - -3, /* (116) xfullname ::= nm DOT nm */ - -5, /* (117) xfullname ::= nm DOT nm AS nm */ - -3, /* (118) xfullname ::= nm AS nm */ - -1, /* (119) joinop ::= COMMA|JOIN */ - -2, /* (120) joinop ::= JOIN_KW JOIN */ - -3, /* (121) joinop ::= JOIN_KW nm JOIN */ - -4, /* (122) joinop ::= JOIN_KW nm nm JOIN */ - -2, /* (123) on_opt ::= ON expr */ - 0, /* (124) on_opt ::= */ - 0, /* (125) indexed_opt ::= */ - -3, /* (126) indexed_opt ::= INDEXED BY nm */ - -2, /* (127) indexed_opt ::= NOT INDEXED */ - -4, /* (128) using_opt ::= USING LP idlist RP */ - 0, /* (129) using_opt ::= */ - 0, /* (130) orderby_opt ::= */ - -3, /* (131) orderby_opt ::= ORDER BY sortlist */ - -5, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */ - -3, /* (133) sortlist ::= expr sortorder nulls */ - -1, /* (134) sortorder ::= ASC */ - -1, /* (135) sortorder ::= DESC */ - 0, /* (136) sortorder ::= */ - -2, /* (137) nulls ::= NULLS FIRST */ - -2, /* (138) nulls ::= NULLS LAST */ - 0, /* (139) nulls ::= */ - 0, /* (140) groupby_opt ::= */ - -3, /* (141) groupby_opt ::= GROUP BY nexprlist */ - 0, /* (142) having_opt ::= */ - -2, /* (143) having_opt ::= HAVING expr */ - 0, /* (144) limit_opt ::= */ - -2, /* (145) limit_opt ::= LIMIT expr */ - -4, /* (146) limit_opt ::= LIMIT expr OFFSET expr */ - -4, /* (147) limit_opt ::= LIMIT expr COMMA expr */ - -6, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */ - 0, /* (149) where_opt ::= */ - -2, /* (150) where_opt ::= WHERE expr */ - -9, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt */ - -5, /* (152) setlist ::= setlist COMMA nm EQ expr */ - -7, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */ - -3, /* (154) setlist ::= nm EQ expr */ - -5, /* (155) setlist ::= LP idlist RP EQ expr */ - -7, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ - -7, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */ - 0, /* (158) upsert ::= */ - -11, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */ - -8, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */ - -4, /* (161) upsert ::= ON CONFLICT DO NOTHING */ - -2, /* (162) insert_cmd ::= INSERT orconf */ - -1, /* (163) insert_cmd ::= REPLACE */ - 0, /* (164) idlist_opt ::= */ - -3, /* (165) idlist_opt ::= LP idlist RP */ - -3, /* (166) idlist ::= idlist COMMA nm */ - -1, /* (167) idlist ::= nm */ - -3, /* (168) expr ::= LP expr RP */ - -1, /* (169) expr ::= ID|INDEXED */ - -1, /* (170) expr ::= JOIN_KW */ - -3, /* (171) expr ::= nm DOT nm */ - -5, /* (172) expr ::= nm DOT nm DOT nm */ - -1, /* (173) term ::= NULL|FLOAT|BLOB */ - -1, /* (174) term ::= STRING */ - -1, /* (175) term ::= INTEGER */ - -1, /* (176) expr ::= VARIABLE */ - -3, /* (177) expr ::= expr COLLATE ID|STRING */ - -6, /* (178) expr ::= CAST LP expr AS typetoken RP */ - -5, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */ - -4, /* (180) expr ::= ID|INDEXED LP STAR RP */ - -6, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */ - -5, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */ - -1, /* (183) term ::= CTIME_KW */ - -5, /* (184) expr ::= LP nexprlist COMMA expr RP */ - -3, /* (185) expr ::= expr AND expr */ - -3, /* (186) expr ::= expr OR expr */ - -3, /* (187) expr ::= expr LT|GT|GE|LE expr */ - -3, /* (188) expr ::= expr EQ|NE expr */ - -3, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ - -3, /* (190) expr ::= expr PLUS|MINUS expr */ - -3, /* (191) expr ::= expr STAR|SLASH|REM expr */ - -3, /* (192) expr ::= expr CONCAT expr */ - -2, /* (193) likeop ::= NOT LIKE_KW|MATCH */ - -3, /* (194) expr ::= expr likeop expr */ - -5, /* (195) expr ::= expr likeop expr ESCAPE expr */ - -2, /* (196) expr ::= expr ISNULL|NOTNULL */ - -3, /* (197) expr ::= expr NOT NULL */ - -3, /* (198) expr ::= expr IS expr */ - -4, /* (199) expr ::= expr IS NOT expr */ - -2, /* (200) expr ::= NOT expr */ - -2, /* (201) expr ::= BITNOT expr */ - -2, /* (202) expr ::= PLUS|MINUS expr */ - -1, /* (203) between_op ::= BETWEEN */ - -2, /* (204) between_op ::= NOT BETWEEN */ - -5, /* (205) expr ::= expr between_op expr AND expr */ - -1, /* (206) in_op ::= IN */ - -2, /* (207) in_op ::= NOT IN */ - -5, /* (208) expr ::= expr in_op LP exprlist RP */ - -3, /* (209) expr ::= LP select RP */ - -5, /* (210) expr ::= expr in_op LP select RP */ - -5, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */ - -4, /* (212) expr ::= EXISTS LP select RP */ - -5, /* (213) expr ::= CASE case_operand case_exprlist case_else END */ - -5, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */ - -4, /* (215) case_exprlist ::= WHEN expr THEN expr */ - -2, /* (216) case_else ::= ELSE expr */ - 0, /* (217) case_else ::= */ - -1, /* (218) case_operand ::= expr */ - 0, /* (219) case_operand ::= */ - 0, /* (220) exprlist ::= */ - -3, /* (221) nexprlist ::= nexprlist COMMA expr */ - -1, /* (222) nexprlist ::= expr */ - 0, /* (223) paren_exprlist ::= */ - -3, /* (224) paren_exprlist ::= LP exprlist RP */ - -12, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ - -1, /* (226) uniqueflag ::= UNIQUE */ - 0, /* (227) uniqueflag ::= */ - 0, /* (228) eidlist_opt ::= */ - -3, /* (229) eidlist_opt ::= LP eidlist RP */ - -5, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */ - -3, /* (231) eidlist ::= nm collate sortorder */ - 0, /* (232) collate ::= */ - -2, /* (233) collate ::= COLLATE ID|STRING */ - -4, /* (234) cmd ::= DROP INDEX ifexists fullname */ - -2, /* (235) cmd ::= VACUUM vinto */ - -3, /* (236) cmd ::= VACUUM nm vinto */ - -2, /* (237) vinto ::= INTO expr */ - 0, /* (238) vinto ::= */ - -3, /* (239) cmd ::= PRAGMA nm dbnm */ - -5, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */ - -6, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */ - -5, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */ - -6, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */ - -2, /* (244) plus_num ::= PLUS INTEGER|FLOAT */ - -2, /* (245) minus_num ::= MINUS INTEGER|FLOAT */ - -5, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ - -11, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ - -1, /* (248) trigger_time ::= BEFORE|AFTER */ - -2, /* (249) trigger_time ::= INSTEAD OF */ - 0, /* (250) trigger_time ::= */ - -1, /* (251) trigger_event ::= DELETE|INSERT */ - -1, /* (252) trigger_event ::= UPDATE */ - -3, /* (253) trigger_event ::= UPDATE OF idlist */ - 0, /* (254) when_clause ::= */ - -2, /* (255) when_clause ::= WHEN expr */ - -3, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ - -2, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */ - -3, /* (258) trnm ::= nm DOT nm */ - -3, /* (259) tridxby ::= INDEXED BY nm */ - -2, /* (260) tridxby ::= NOT INDEXED */ - -9, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */ - -8, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ - -6, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ - -3, /* (264) trigger_cmd ::= scanpt select scanpt */ - -4, /* (265) expr ::= RAISE LP IGNORE RP */ - -6, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */ - -1, /* (267) raisetype ::= ROLLBACK */ - -1, /* (268) raisetype ::= ABORT */ - -1, /* (269) raisetype ::= FAIL */ - -4, /* (270) cmd ::= DROP TRIGGER ifexists fullname */ - -6, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ - -3, /* (272) cmd ::= DETACH database_kw_opt expr */ - 0, /* (273) key_opt ::= */ - -2, /* (274) key_opt ::= KEY expr */ - -1, /* (275) cmd ::= REINDEX */ - -3, /* (276) cmd ::= REINDEX nm dbnm */ - -1, /* (277) cmd ::= ANALYZE */ - -3, /* (278) cmd ::= ANALYZE nm dbnm */ - -6, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */ - -7, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ - -1, /* (281) add_column_fullname ::= fullname */ - -8, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ - -1, /* (283) cmd ::= create_vtab */ - -4, /* (284) cmd ::= create_vtab LP vtabarglist RP */ - -8, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ - 0, /* (286) vtabarg ::= */ - -1, /* (287) vtabargtoken ::= ANY */ - -3, /* (288) vtabargtoken ::= lp anylist RP */ - -1, /* (289) lp ::= LP */ - -2, /* (290) with ::= WITH wqlist */ - -3, /* (291) with ::= WITH RECURSIVE wqlist */ - -6, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */ - -8, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ - -1, /* (294) windowdefn_list ::= windowdefn */ - -3, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */ - -5, /* (296) windowdefn ::= nm AS LP window RP */ - -5, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ - -6, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ - -4, /* (299) window ::= ORDER BY sortlist frame_opt */ - -5, /* (300) window ::= nm ORDER BY sortlist frame_opt */ - -1, /* (301) window ::= frame_opt */ - -2, /* (302) window ::= nm frame_opt */ - 0, /* (303) frame_opt ::= */ - -3, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ - -6, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ - -1, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */ - -1, /* (307) frame_bound_s ::= frame_bound */ - -2, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */ - -1, /* (309) frame_bound_e ::= frame_bound */ - -2, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */ - -2, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */ - -2, /* (312) frame_bound ::= CURRENT ROW */ - 0, /* (313) frame_exclude_opt ::= */ - -2, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */ - -2, /* (315) frame_exclude ::= NO OTHERS */ - -2, /* (316) frame_exclude ::= CURRENT ROW */ - -1, /* (317) frame_exclude ::= GROUP|TIES */ - -2, /* (318) window_clause ::= WINDOW windowdefn_list */ - -2, /* (319) filter_over ::= filter_clause over_clause */ - -1, /* (320) filter_over ::= over_clause */ - -1, /* (321) filter_over ::= filter_clause */ - -4, /* (322) over_clause ::= OVER LP window RP */ - -2, /* (323) over_clause ::= OVER nm */ - -5, /* (324) filter_clause ::= FILTER LP WHERE expr RP */ - -1, /* (325) input ::= cmdlist */ - -2, /* (326) cmdlist ::= cmdlist ecmd */ - -1, /* (327) cmdlist ::= ecmd */ - -1, /* (328) ecmd ::= SEMI */ - -2, /* (329) ecmd ::= cmdx SEMI */ - -3, /* (330) ecmd ::= explain cmdx SEMI */ - 0, /* (331) trans_opt ::= */ - -1, /* (332) trans_opt ::= TRANSACTION */ - -2, /* (333) trans_opt ::= TRANSACTION nm */ - -1, /* (334) savepoint_opt ::= SAVEPOINT */ - 0, /* (335) savepoint_opt ::= */ - -2, /* (336) cmd ::= create_table create_table_args */ - -4, /* (337) columnlist ::= columnlist COMMA columnname carglist */ - -2, /* (338) columnlist ::= columnname carglist */ - -1, /* (339) nm ::= ID|INDEXED */ - -1, /* (340) nm ::= STRING */ - -1, /* (341) nm ::= JOIN_KW */ - -1, /* (342) typetoken ::= typename */ - -1, /* (343) typename ::= ID|STRING */ - -1, /* (344) signed ::= plus_num */ - -1, /* (345) signed ::= minus_num */ - -2, /* (346) carglist ::= carglist ccons */ - 0, /* (347) carglist ::= */ - -2, /* (348) ccons ::= NULL onconf */ - -4, /* (349) ccons ::= GENERATED ALWAYS AS generated */ - -2, /* (350) ccons ::= AS generated */ - -2, /* (351) conslist_opt ::= COMMA conslist */ - -3, /* (352) conslist ::= conslist tconscomma tcons */ - -1, /* (353) conslist ::= tcons */ - 0, /* (354) tconscomma ::= */ - -1, /* (355) defer_subclause_opt ::= defer_subclause */ - -1, /* (356) resolvetype ::= raisetype */ - -1, /* (357) selectnowith ::= oneselect */ - -1, /* (358) oneselect ::= values */ - -2, /* (359) sclp ::= selcollist COMMA */ - -1, /* (360) as ::= ID|STRING */ - -1, /* (361) expr ::= term */ - -1, /* (362) likeop ::= LIKE_KW|MATCH */ - -1, /* (363) exprlist ::= nexprlist */ - -1, /* (364) nmnum ::= plus_num */ - -1, /* (365) nmnum ::= nm */ - -1, /* (366) nmnum ::= ON */ - -1, /* (367) nmnum ::= DELETE */ - -1, /* (368) nmnum ::= DEFAULT */ - -1, /* (369) plus_num ::= INTEGER|FLOAT */ - 0, /* (370) foreach_clause ::= */ - -3, /* (371) foreach_clause ::= FOR EACH ROW */ - -1, /* (372) trnm ::= nm */ - 0, /* (373) tridxby ::= */ - -1, /* (374) database_kw_opt ::= DATABASE */ - 0, /* (375) database_kw_opt ::= */ - 0, /* (376) kwcolumn_opt ::= */ - -1, /* (377) kwcolumn_opt ::= COLUMNKW */ - -1, /* (378) vtabarglist ::= vtabarg */ - -3, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ - -2, /* (380) vtabarg ::= vtabarg vtabargtoken */ - 0, /* (381) anylist ::= */ - -4, /* (382) anylist ::= anylist LP anylist RP */ - -2, /* (383) anylist ::= anylist ANY */ - 0, /* (384) with ::= */ -}; - -static void yy_accept(yyParser*); /* Forward Declaration */ - -/* -** Perform a reduce action and the shift that must immediately -** follow the reduce. -** -** The yyLookahead and yyLookaheadToken parameters provide reduce actions -** access to the lookahead token (if any). The yyLookahead will be YYNOCODE -** if the lookahead token has already been consumed. As this procedure is -** only called from one place, optimizing compilers will in-line it, which -** means that the extra parameters have no performance impact. -*/ -static YYACTIONTYPE yy_reduce( - yyParser *yypParser, /* The parser */ - unsigned int yyruleno, /* Number of the rule by which to reduce */ - int yyLookahead, /* Lookahead token, or YYNOCODE if none */ - sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */ - sqlite3ParserCTX_PDECL /* %extra_context */ -){ - int yygoto; /* The next state */ - YYACTIONTYPE yyact; /* The next action */ - yyStackEntry *yymsp; /* The top of the parser's stack */ - int yysize; /* Amount to pop the stack */ - sqlite3ParserARG_FETCH - (void)yyLookahead; - (void)yyLookaheadToken; - yymsp = yypParser->yytos; -#ifndef NDEBUG - if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ - yysize = yyRuleInfoNRhs[yyruleno]; - if( yysize ){ - fprintf(yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n", - yyTracePrompt, - yyruleno, yyRuleName[yyruleno], - yyrulenoyytos - yypParser->yystack)>yypParser->yyhwm ){ - yypParser->yyhwm++; - assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack)); - } -#endif -#if YYSTACKDEPTH>0 - if( yypParser->yytos>=yypParser->yystackEnd ){ - yyStackOverflow(yypParser); - /* The call to yyStackOverflow() above pops the stack until it is - ** empty, causing the main parser loop to exit. So the return value - ** is never used and does not matter. */ - return 0; - } -#else - if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){ - if( yyGrowStack(yypParser) ){ - yyStackOverflow(yypParser); - /* The call to yyStackOverflow() above pops the stack until it is - ** empty, causing the main parser loop to exit. So the return value - ** is never used and does not matter. */ - return 0; - } - yymsp = yypParser->yytos; - } -#endif - } - - switch( yyruleno ){ - /* Beginning here are the reduction cases. A typical example - ** follows: - ** case 0: - ** #line - ** { ... } // User supplied code - ** #line - ** break; - */ -/********** Begin reduce actions **********************************************/ - YYMINORTYPE yylhsminor; - case 0: /* explain ::= EXPLAIN */ -{ pParse->explain = 1; } - break; - case 1: /* explain ::= EXPLAIN QUERY PLAN */ -{ pParse->explain = 2; } - break; - case 2: /* cmdx ::= cmd */ -{ sqlite3FinishCoding(pParse); } - break; - case 3: /* cmd ::= BEGIN transtype trans_opt */ -{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy192);} - break; - case 4: /* transtype ::= */ -{yymsp[1].minor.yy192 = TK_DEFERRED;} - break; - case 5: /* transtype ::= DEFERRED */ - case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6); - case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7); - case 306: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==306); -{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/} - break; - case 8: /* cmd ::= COMMIT|END trans_opt */ - case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9); -{sqlite3EndTransaction(pParse,yymsp[-1].major);} - break; - case 10: /* cmd ::= SAVEPOINT nm */ -{ - sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0); -} - break; - case 11: /* cmd ::= RELEASE savepoint_opt nm */ -{ - sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0); -} - break; - case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ -{ - sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0); -} - break; - case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */ -{ - sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy192,0,0,yymsp[-2].minor.yy192); -} - break; - case 14: /* createkw ::= CREATE */ -{disableLookaside(pParse);} - break; - case 15: /* ifnotexists ::= */ - case 18: /* temp ::= */ yytestcase(yyruleno==18); - case 21: /* table_options ::= */ yytestcase(yyruleno==21); - case 45: /* autoinc ::= */ yytestcase(yyruleno==45); - case 60: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==60); - case 70: /* defer_subclause_opt ::= */ yytestcase(yyruleno==70); - case 79: /* ifexists ::= */ yytestcase(yyruleno==79); - case 96: /* distinct ::= */ yytestcase(yyruleno==96); - case 232: /* collate ::= */ yytestcase(yyruleno==232); -{yymsp[1].minor.yy192 = 0;} - break; - case 16: /* ifnotexists ::= IF NOT EXISTS */ -{yymsp[-2].minor.yy192 = 1;} - break; - case 17: /* temp ::= TEMP */ - case 46: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==46); -{yymsp[0].minor.yy192 = 1;} - break; - case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */ -{ - sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy192,0); -} - break; - case 20: /* create_table_args ::= AS select */ -{ - sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy539); - sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539); -} - break; - case 22: /* table_options ::= WITHOUT nm */ -{ - if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){ - yymsp[-1].minor.yy192 = TF_WithoutRowid | TF_NoVisibleRowid; - }else{ - yymsp[-1].minor.yy192 = 0; - sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z); - } -} - break; - case 23: /* columnname ::= nm typetoken */ -{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} - break; - case 24: /* typetoken ::= */ - case 63: /* conslist_opt ::= */ yytestcase(yyruleno==63); - case 102: /* as ::= */ yytestcase(yyruleno==102); -{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;} - break; - case 25: /* typetoken ::= typename LP signed RP */ -{ - yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z); -} - break; - case 26: /* typetoken ::= typename LP signed COMMA signed RP */ -{ - yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z); -} - break; - case 27: /* typename ::= typename ID|STRING */ -{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);} - break; - case 28: /* scanpt ::= */ -{ - assert( yyLookahead!=YYNOCODE ); - yymsp[1].minor.yy436 = yyLookaheadToken.z; -} - break; - case 29: /* scantok ::= */ -{ - assert( yyLookahead!=YYNOCODE ); - yymsp[1].minor.yy0 = yyLookaheadToken; -} - break; - case 30: /* ccons ::= CONSTRAINT nm */ - case 65: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==65); -{pParse->constraintName = yymsp[0].minor.yy0;} - break; - case 31: /* ccons ::= DEFAULT scantok term */ -{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);} - break; - case 32: /* ccons ::= DEFAULT LP expr RP */ -{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);} - break; - case 33: /* ccons ::= DEFAULT PLUS scantok term */ -{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);} - break; - case 34: /* ccons ::= DEFAULT MINUS scantok term */ -{ - Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy202, 0); - sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]); -} - break; - case 35: /* ccons ::= DEFAULT scantok ID|INDEXED */ -{ - Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0); - if( p ){ - sqlite3ExprIdToTrueFalse(p); - testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) ); - } - sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n); -} - break; - case 36: /* ccons ::= NOT NULL onconf */ -{sqlite3AddNotNull(pParse, yymsp[0].minor.yy192);} - break; - case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ -{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy192,yymsp[0].minor.yy192,yymsp[-2].minor.yy192);} - break; - case 38: /* ccons ::= UNIQUE onconf */ -{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy192,0,0,0,0, - SQLITE_IDXTYPE_UNIQUE);} - break; - case 39: /* ccons ::= CHECK LP expr RP */ -{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy202);} - break; - case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */ -{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy192);} - break; - case 41: /* ccons ::= defer_subclause */ -{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy192);} - break; - case 42: /* ccons ::= COLLATE ID|STRING */ -{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} - break; - case 43: /* generated ::= LP expr RP */ -{sqlite3AddGenerated(pParse,yymsp[-1].minor.yy202,0);} - break; - case 44: /* generated ::= LP expr RP ID */ -{sqlite3AddGenerated(pParse,yymsp[-2].minor.yy202,&yymsp[0].minor.yy0);} - break; - case 47: /* refargs ::= */ -{ yymsp[1].minor.yy192 = OE_None*0x0101; /* EV: R-19803-45884 */} - break; - case 48: /* refargs ::= refargs refarg */ -{ yymsp[-1].minor.yy192 = (yymsp[-1].minor.yy192 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; } - break; - case 49: /* refarg ::= MATCH nm */ -{ yymsp[-1].minor.yy207.value = 0; yymsp[-1].minor.yy207.mask = 0x000000; } - break; - case 50: /* refarg ::= ON INSERT refact */ -{ yymsp[-2].minor.yy207.value = 0; yymsp[-2].minor.yy207.mask = 0x000000; } - break; - case 51: /* refarg ::= ON DELETE refact */ -{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192; yymsp[-2].minor.yy207.mask = 0x0000ff; } - break; - case 52: /* refarg ::= ON UPDATE refact */ -{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192<<8; yymsp[-2].minor.yy207.mask = 0x00ff00; } - break; - case 53: /* refact ::= SET NULL */ -{ yymsp[-1].minor.yy192 = OE_SetNull; /* EV: R-33326-45252 */} - break; - case 54: /* refact ::= SET DEFAULT */ -{ yymsp[-1].minor.yy192 = OE_SetDflt; /* EV: R-33326-45252 */} - break; - case 55: /* refact ::= CASCADE */ -{ yymsp[0].minor.yy192 = OE_Cascade; /* EV: R-33326-45252 */} - break; - case 56: /* refact ::= RESTRICT */ -{ yymsp[0].minor.yy192 = OE_Restrict; /* EV: R-33326-45252 */} - break; - case 57: /* refact ::= NO ACTION */ -{ yymsp[-1].minor.yy192 = OE_None; /* EV: R-33326-45252 */} - break; - case 58: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ -{yymsp[-2].minor.yy192 = 0;} - break; - case 59: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ - case 74: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==74); - case 162: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==162); -{yymsp[-1].minor.yy192 = yymsp[0].minor.yy192;} - break; - case 61: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ - case 78: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==78); - case 204: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==204); - case 207: /* in_op ::= NOT IN */ yytestcase(yyruleno==207); - case 233: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==233); -{yymsp[-1].minor.yy192 = 1;} - break; - case 62: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ -{yymsp[-1].minor.yy192 = 0;} - break; - case 64: /* tconscomma ::= COMMA */ -{pParse->constraintName.n = 0;} - break; - case 66: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ -{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy192,yymsp[-2].minor.yy192,0);} - break; - case 67: /* tcons ::= UNIQUE LP sortlist RP onconf */ -{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy192,0,0,0,0, - SQLITE_IDXTYPE_UNIQUE);} - break; - case 68: /* tcons ::= CHECK LP expr RP onconf */ -{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy202);} - break; - case 69: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ -{ - sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy192); - sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy192); -} - break; - case 71: /* onconf ::= */ - case 73: /* orconf ::= */ yytestcase(yyruleno==73); -{yymsp[1].minor.yy192 = OE_Default;} - break; - case 72: /* onconf ::= ON CONFLICT resolvetype */ -{yymsp[-2].minor.yy192 = yymsp[0].minor.yy192;} - break; - case 75: /* resolvetype ::= IGNORE */ -{yymsp[0].minor.yy192 = OE_Ignore;} - break; - case 76: /* resolvetype ::= REPLACE */ - case 163: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==163); -{yymsp[0].minor.yy192 = OE_Replace;} - break; - case 77: /* cmd ::= DROP TABLE ifexists fullname */ -{ - sqlite3DropTable(pParse, yymsp[0].minor.yy47, 0, yymsp[-1].minor.yy192); -} - break; - case 80: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ -{ - sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[0].minor.yy539, yymsp[-7].minor.yy192, yymsp[-5].minor.yy192); -} - break; - case 81: /* cmd ::= DROP VIEW ifexists fullname */ -{ - sqlite3DropTable(pParse, yymsp[0].minor.yy47, 1, yymsp[-1].minor.yy192); -} - break; - case 82: /* cmd ::= select */ -{ - SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0, 0}; - sqlite3Select(pParse, yymsp[0].minor.yy539, &dest); - sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539); -} - break; - case 83: /* select ::= WITH wqlist selectnowith */ -{ - Select *p = yymsp[0].minor.yy539; - if( p ){ - p->pWith = yymsp[-1].minor.yy131; - parserDoubleLinkSelect(pParse, p); - }else{ - sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131); - } - yymsp[-2].minor.yy539 = p; -} - break; - case 84: /* select ::= WITH RECURSIVE wqlist selectnowith */ -{ - Select *p = yymsp[0].minor.yy539; - if( p ){ - p->pWith = yymsp[-1].minor.yy131; - parserDoubleLinkSelect(pParse, p); - }else{ - sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131); - } - yymsp[-3].minor.yy539 = p; -} - break; - case 85: /* select ::= selectnowith */ -{ - Select *p = yymsp[0].minor.yy539; - if( p ){ - parserDoubleLinkSelect(pParse, p); - } - yymsp[0].minor.yy539 = p; /*A-overwrites-X*/ -} - break; - case 86: /* selectnowith ::= selectnowith multiselect_op oneselect */ -{ - Select *pRhs = yymsp[0].minor.yy539; - Select *pLhs = yymsp[-2].minor.yy539; - if( pRhs && pRhs->pPrior ){ - SrcList *pFrom; - Token x; - x.n = 0; - parserDoubleLinkSelect(pParse, pRhs); - pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0); - pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0); - } - if( pRhs ){ - pRhs->op = (u8)yymsp[-1].minor.yy192; - pRhs->pPrior = pLhs; - if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue; - pRhs->selFlags &= ~SF_MultiValue; - if( yymsp[-1].minor.yy192!=TK_ALL ) pParse->hasCompound = 1; - }else{ - sqlite3SelectDelete(pParse->db, pLhs); - } - yymsp[-2].minor.yy539 = pRhs; -} - break; - case 87: /* multiselect_op ::= UNION */ - case 89: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==89); -{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-OP*/} - break; - case 88: /* multiselect_op ::= UNION ALL */ -{yymsp[-1].minor.yy192 = TK_ALL;} - break; - case 90: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ -{ - yymsp[-8].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy242,yymsp[-5].minor.yy47,yymsp[-4].minor.yy202,yymsp[-3].minor.yy242,yymsp[-2].minor.yy202,yymsp[-1].minor.yy242,yymsp[-7].minor.yy192,yymsp[0].minor.yy202); -} - break; - case 91: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ -{ - yymsp[-9].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy242,yymsp[-6].minor.yy47,yymsp[-5].minor.yy202,yymsp[-4].minor.yy242,yymsp[-3].minor.yy202,yymsp[-1].minor.yy242,yymsp[-8].minor.yy192,yymsp[0].minor.yy202); - if( yymsp[-9].minor.yy539 ){ - yymsp[-9].minor.yy539->pWinDefn = yymsp[-2].minor.yy303; - }else{ - sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy303); - } -} - break; - case 92: /* values ::= VALUES LP nexprlist RP */ -{ - yymsp[-3].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values,0); -} - break; - case 93: /* values ::= values COMMA LP nexprlist RP */ -{ - Select *pRight, *pLeft = yymsp[-4].minor.yy539; - pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values|SF_MultiValue,0); - if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue; - if( pRight ){ - pRight->op = TK_ALL; - pRight->pPrior = pLeft; - yymsp[-4].minor.yy539 = pRight; - }else{ - yymsp[-4].minor.yy539 = pLeft; - } -} - break; - case 94: /* distinct ::= DISTINCT */ -{yymsp[0].minor.yy192 = SF_Distinct;} - break; - case 95: /* distinct ::= ALL */ -{yymsp[0].minor.yy192 = SF_All;} - break; - case 97: /* sclp ::= */ - case 130: /* orderby_opt ::= */ yytestcase(yyruleno==130); - case 140: /* groupby_opt ::= */ yytestcase(yyruleno==140); - case 220: /* exprlist ::= */ yytestcase(yyruleno==220); - case 223: /* paren_exprlist ::= */ yytestcase(yyruleno==223); - case 228: /* eidlist_opt ::= */ yytestcase(yyruleno==228); -{yymsp[1].minor.yy242 = 0;} - break; - case 98: /* selcollist ::= sclp scanpt expr scanpt as */ -{ - yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[-2].minor.yy202); - if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[0].minor.yy0, 1); - sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy242,yymsp[-3].minor.yy436,yymsp[-1].minor.yy436); -} - break; - case 99: /* selcollist ::= sclp scanpt STAR */ -{ - Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0); - yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy242, p); -} - break; - case 100: /* selcollist ::= sclp scanpt nm DOT STAR */ -{ - Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0); - Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); - Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); - yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, pDot); -} - break; - case 101: /* as ::= AS nm */ - case 112: /* dbnm ::= DOT nm */ yytestcase(yyruleno==112); - case 244: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==244); - case 245: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==245); -{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;} - break; - case 103: /* from ::= */ - case 106: /* stl_prefix ::= */ yytestcase(yyruleno==106); -{yymsp[1].minor.yy47 = 0;} - break; - case 104: /* from ::= FROM seltablist */ -{ - yymsp[-1].minor.yy47 = yymsp[0].minor.yy47; - sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy47); -} - break; - case 105: /* stl_prefix ::= seltablist joinop */ -{ - if( ALWAYS(yymsp[-1].minor.yy47 && yymsp[-1].minor.yy47->nSrc>0) ) yymsp[-1].minor.yy47->a[yymsp[-1].minor.yy47->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy192; -} - break; - case 107: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ -{ - yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); - sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy47, &yymsp[-2].minor.yy0); -} - break; - case 108: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ -{ - yymsp[-8].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy47,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); - sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy47, yymsp[-4].minor.yy242); -} - break; - case 109: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ -{ - yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy539,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); - } - break; - case 110: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ -{ - if( yymsp[-6].minor.yy47==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy202==0 && yymsp[0].minor.yy600==0 ){ - yymsp[-6].minor.yy47 = yymsp[-4].minor.yy47; - }else if( yymsp[-4].minor.yy47->nSrc==1 ){ - yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); - if( yymsp[-6].minor.yy47 ){ - struct SrcList_item *pNew = &yymsp[-6].minor.yy47->a[yymsp[-6].minor.yy47->nSrc-1]; - struct SrcList_item *pOld = yymsp[-4].minor.yy47->a; - pNew->zName = pOld->zName; - pNew->zDatabase = pOld->zDatabase; - pNew->pSelect = pOld->pSelect; - if( pOld->fg.isTabFunc ){ - pNew->u1.pFuncArg = pOld->u1.pFuncArg; - pOld->u1.pFuncArg = 0; - pOld->fg.isTabFunc = 0; - pNew->fg.isTabFunc = 1; - } - pOld->zName = pOld->zDatabase = 0; - pOld->pSelect = 0; - } - sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy47); - }else{ - Select *pSubquery; - sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy47); - pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy47,0,0,0,0,SF_NestedFrom,0); - yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy202,yymsp[0].minor.yy600); - } - } - break; - case 111: /* dbnm ::= */ - case 125: /* indexed_opt ::= */ yytestcase(yyruleno==125); -{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;} - break; - case 113: /* fullname ::= nm */ -{ - yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); - if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0); -} - yymsp[0].minor.yy47 = yylhsminor.yy47; - break; - case 114: /* fullname ::= nm DOT nm */ -{ - yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); - if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0); -} - yymsp[-2].minor.yy47 = yylhsminor.yy47; - break; - case 115: /* xfullname ::= nm */ -{yymsp[0].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/} - break; - case 116: /* xfullname ::= nm DOT nm */ -{yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} - break; - case 117: /* xfullname ::= nm DOT nm AS nm */ -{ - yymsp[-4].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/ - if( yymsp[-4].minor.yy47 ) yymsp[-4].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); -} - break; - case 118: /* xfullname ::= nm AS nm */ -{ - yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/ - if( yymsp[-2].minor.yy47 ) yymsp[-2].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); -} - break; - case 119: /* joinop ::= COMMA|JOIN */ -{ yymsp[0].minor.yy192 = JT_INNER; } - break; - case 120: /* joinop ::= JOIN_KW JOIN */ -{yymsp[-1].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/} - break; - case 121: /* joinop ::= JOIN_KW nm JOIN */ -{yymsp[-2].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/} - break; - case 122: /* joinop ::= JOIN_KW nm nm JOIN */ -{yymsp[-3].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/} - break; - case 123: /* on_opt ::= ON expr */ - case 143: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==143); - case 150: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==150); - case 216: /* case_else ::= ELSE expr */ yytestcase(yyruleno==216); - case 237: /* vinto ::= INTO expr */ yytestcase(yyruleno==237); -{yymsp[-1].minor.yy202 = yymsp[0].minor.yy202;} - break; - case 124: /* on_opt ::= */ - case 142: /* having_opt ::= */ yytestcase(yyruleno==142); - case 144: /* limit_opt ::= */ yytestcase(yyruleno==144); - case 149: /* where_opt ::= */ yytestcase(yyruleno==149); - case 217: /* case_else ::= */ yytestcase(yyruleno==217); - case 219: /* case_operand ::= */ yytestcase(yyruleno==219); - case 238: /* vinto ::= */ yytestcase(yyruleno==238); -{yymsp[1].minor.yy202 = 0;} - break; - case 126: /* indexed_opt ::= INDEXED BY nm */ -{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;} - break; - case 127: /* indexed_opt ::= NOT INDEXED */ -{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;} - break; - case 128: /* using_opt ::= USING LP idlist RP */ -{yymsp[-3].minor.yy600 = yymsp[-1].minor.yy600;} - break; - case 129: /* using_opt ::= */ - case 164: /* idlist_opt ::= */ yytestcase(yyruleno==164); -{yymsp[1].minor.yy600 = 0;} - break; - case 131: /* orderby_opt ::= ORDER BY sortlist */ - case 141: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==141); -{yymsp[-2].minor.yy242 = yymsp[0].minor.yy242;} - break; - case 132: /* sortlist ::= sortlist COMMA expr sortorder nulls */ -{ - yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202); - sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192); -} - break; - case 133: /* sortlist ::= expr sortorder nulls */ -{ - yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy202); /*A-overwrites-Y*/ - sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192); -} - break; - case 134: /* sortorder ::= ASC */ -{yymsp[0].minor.yy192 = SQLITE_SO_ASC;} - break; - case 135: /* sortorder ::= DESC */ -{yymsp[0].minor.yy192 = SQLITE_SO_DESC;} - break; - case 136: /* sortorder ::= */ - case 139: /* nulls ::= */ yytestcase(yyruleno==139); -{yymsp[1].minor.yy192 = SQLITE_SO_UNDEFINED;} - break; - case 137: /* nulls ::= NULLS FIRST */ -{yymsp[-1].minor.yy192 = SQLITE_SO_ASC;} - break; - case 138: /* nulls ::= NULLS LAST */ -{yymsp[-1].minor.yy192 = SQLITE_SO_DESC;} - break; - case 145: /* limit_opt ::= LIMIT expr */ -{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,0);} - break; - case 146: /* limit_opt ::= LIMIT expr OFFSET expr */ -{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);} - break; - case 147: /* limit_opt ::= LIMIT expr COMMA expr */ -{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,yymsp[-2].minor.yy202);} - break; - case 148: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */ -{ - sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy47, &yymsp[-1].minor.yy0); - sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy47,yymsp[0].minor.yy202,0,0); -} - break; - case 151: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt */ -{ - sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy47, &yymsp[-4].minor.yy0); - sqlite3ExprListCheckLength(pParse,yymsp[-2].minor.yy242,"set list"); - yymsp[-5].minor.yy47 = sqlite3SrcListAppendList(pParse, yymsp[-5].minor.yy47, yymsp[-1].minor.yy47); - sqlite3Update(pParse,yymsp[-5].minor.yy47,yymsp[-2].minor.yy242,yymsp[0].minor.yy202,yymsp[-6].minor.yy192,0,0,0); -} - break; - case 152: /* setlist ::= setlist COMMA nm EQ expr */ -{ - yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[0].minor.yy202); - sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, 1); -} - break; - case 153: /* setlist ::= setlist COMMA LP idlist RP EQ expr */ -{ - yymsp[-6].minor.yy242 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy242, yymsp[-3].minor.yy600, yymsp[0].minor.yy202); -} - break; - case 154: /* setlist ::= nm EQ expr */ -{ - yylhsminor.yy242 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy202); - sqlite3ExprListSetName(pParse, yylhsminor.yy242, &yymsp[-2].minor.yy0, 1); -} - yymsp[-2].minor.yy242 = yylhsminor.yy242; - break; - case 155: /* setlist ::= LP idlist RP EQ expr */ -{ - yymsp[-4].minor.yy242 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy600, yymsp[0].minor.yy202); -} - break; - case 156: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ -{ - sqlite3Insert(pParse, yymsp[-3].minor.yy47, yymsp[-1].minor.yy539, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, yymsp[0].minor.yy318); -} - break; - case 157: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */ -{ - sqlite3Insert(pParse, yymsp[-3].minor.yy47, 0, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, 0); -} - break; - case 158: /* upsert ::= */ -{ yymsp[1].minor.yy318 = 0; } - break; - case 159: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */ -{ yymsp[-10].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy242,yymsp[-5].minor.yy202,yymsp[-1].minor.yy242,yymsp[0].minor.yy202);} - break; - case 160: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */ -{ yymsp[-7].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202,0,0); } - break; - case 161: /* upsert ::= ON CONFLICT DO NOTHING */ -{ yymsp[-3].minor.yy318 = sqlite3UpsertNew(pParse->db,0,0,0,0); } - break; - case 165: /* idlist_opt ::= LP idlist RP */ -{yymsp[-2].minor.yy600 = yymsp[-1].minor.yy600;} - break; - case 166: /* idlist ::= idlist COMMA nm */ -{yymsp[-2].minor.yy600 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy600,&yymsp[0].minor.yy0);} - break; - case 167: /* idlist ::= nm */ -{yymsp[0].minor.yy600 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/} - break; - case 168: /* expr ::= LP expr RP */ -{yymsp[-2].minor.yy202 = yymsp[-1].minor.yy202;} - break; - case 169: /* expr ::= ID|INDEXED */ - case 170: /* expr ::= JOIN_KW */ yytestcase(yyruleno==170); -{yymsp[0].minor.yy202=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/} - break; - case 171: /* expr ::= nm DOT nm */ -{ - Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); - Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0); - sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0); - } - yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2); -} - yymsp[-2].minor.yy202 = yylhsminor.yy202; - break; - case 172: /* expr ::= nm DOT nm DOT nm */ -{ - Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1); - Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1); - Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1); - Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3); - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0); - sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0); - } - yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4); -} - yymsp[-4].minor.yy202 = yylhsminor.yy202; - break; - case 173: /* term ::= NULL|FLOAT|BLOB */ - case 174: /* term ::= STRING */ yytestcase(yyruleno==174); -{yymsp[0].minor.yy202=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/} - break; - case 175: /* term ::= INTEGER */ -{ - yylhsminor.yy202 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); -} - yymsp[0].minor.yy202 = yylhsminor.yy202; - break; - case 176: /* expr ::= VARIABLE */ -{ - if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){ - u32 n = yymsp[0].minor.yy0.n; - yymsp[0].minor.yy202 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0); - sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy202, n); - }else{ - /* When doing a nested parse, one can include terms in an expression - ** that look like this: #1 #2 ... These terms refer to registers - ** in the virtual machine. #N is the N-th register. */ - Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/ - assert( t.n>=2 ); - if( pParse->nested==0 ){ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); - yymsp[0].minor.yy202 = 0; - }else{ - yymsp[0].minor.yy202 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0); - if( yymsp[0].minor.yy202 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy202->iTable); - } - } -} - break; - case 177: /* expr ::= expr COLLATE ID|STRING */ -{ - yymsp[-2].minor.yy202 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy202, &yymsp[0].minor.yy0, 1); -} - break; - case 178: /* expr ::= CAST LP expr AS typetoken RP */ -{ - yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1); - sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy202, yymsp[-3].minor.yy202, 0); -} - break; - case 179: /* expr ::= ID|INDEXED LP distinct exprlist RP */ -{ - yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy192); -} - yymsp[-4].minor.yy202 = yylhsminor.yy202; - break; - case 180: /* expr ::= ID|INDEXED LP STAR RP */ -{ - yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0); -} - yymsp[-3].minor.yy202 = yylhsminor.yy202; - break; - case 181: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */ -{ - yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy242, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy192); - sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303); -} - yymsp[-5].minor.yy202 = yylhsminor.yy202; - break; - case 182: /* expr ::= ID|INDEXED LP STAR RP filter_over */ -{ - yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0); - sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303); -} - yymsp[-4].minor.yy202 = yylhsminor.yy202; - break; - case 183: /* term ::= CTIME_KW */ -{ - yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0); -} - yymsp[0].minor.yy202 = yylhsminor.yy202; - break; - case 184: /* expr ::= LP nexprlist COMMA expr RP */ -{ - ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202); - yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); - if( yymsp[-4].minor.yy202 ){ - yymsp[-4].minor.yy202->x.pList = pList; - if( ALWAYS(pList->nExpr) ){ - yymsp[-4].minor.yy202->flags |= pList->a[0].pExpr->flags & EP_Propagate; - } - }else{ - sqlite3ExprListDelete(pParse->db, pList); - } -} - break; - case 185: /* expr ::= expr AND expr */ -{yymsp[-2].minor.yy202=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);} - break; - case 186: /* expr ::= expr OR expr */ - case 187: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==187); - case 188: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==188); - case 189: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==189); - case 190: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==190); - case 191: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==191); - case 192: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==192); -{yymsp[-2].minor.yy202=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);} - break; - case 193: /* likeop ::= NOT LIKE_KW|MATCH */ -{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/} - break; - case 194: /* expr ::= expr likeop expr */ -{ - ExprList *pList; - int bNot = yymsp[-1].minor.yy0.n & 0x80000000; - yymsp[-1].minor.yy0.n &= 0x7fffffff; - pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy202); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy202); - yymsp[-2].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0); - if( bNot ) yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy202, 0); - if( yymsp[-2].minor.yy202 ) yymsp[-2].minor.yy202->flags |= EP_InfixFunc; -} - break; - case 195: /* expr ::= expr likeop expr ESCAPE expr */ -{ - ExprList *pList; - int bNot = yymsp[-3].minor.yy0.n & 0x80000000; - yymsp[-3].minor.yy0.n &= 0x7fffffff; - pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy202); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202); - yymsp[-4].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0); - if( bNot ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); - if( yymsp[-4].minor.yy202 ) yymsp[-4].minor.yy202->flags |= EP_InfixFunc; -} - break; - case 196: /* expr ::= expr ISNULL|NOTNULL */ -{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy202,0);} - break; - case 197: /* expr ::= expr NOT NULL */ -{yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy202,0);} - break; - case 198: /* expr ::= expr IS expr */ -{ - yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy202,yymsp[0].minor.yy202); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-2].minor.yy202, TK_ISNULL); -} - break; - case 199: /* expr ::= expr IS NOT expr */ -{ - yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy202,yymsp[0].minor.yy202); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-3].minor.yy202, TK_NOTNULL); -} - break; - case 200: /* expr ::= NOT expr */ - case 201: /* expr ::= BITNOT expr */ yytestcase(yyruleno==201); -{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy202, 0);/*A-overwrites-B*/} - break; - case 202: /* expr ::= PLUS|MINUS expr */ -{ - yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy202, 0); - /*A-overwrites-B*/ -} - break; - case 203: /* between_op ::= BETWEEN */ - case 206: /* in_op ::= IN */ yytestcase(yyruleno==206); -{yymsp[0].minor.yy192 = 0;} - break; - case 205: /* expr ::= expr between_op expr AND expr */ -{ - ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202); - yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy202, 0); - if( yymsp[-4].minor.yy202 ){ - yymsp[-4].minor.yy202->x.pList = pList; - }else{ - sqlite3ExprListDelete(pParse->db, pList); - } - if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); -} - break; - case 208: /* expr ::= expr in_op LP exprlist RP */ -{ - if( yymsp[-1].minor.yy242==0 ){ - /* Expressions of the form - ** - ** expr1 IN () - ** expr1 NOT IN () - ** - ** simplify to constants 0 (false) and 1 (true), respectively, - ** regardless of the value of expr1. - */ - sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy202); - yymsp[-4].minor.yy202 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy192 ? "1" : "0"); - }else if( yymsp[-1].minor.yy242->nExpr==1 && sqlite3ExprIsConstant(yymsp[-1].minor.yy242->a[0].pExpr) ){ - Expr *pRHS = yymsp[-1].minor.yy242->a[0].pExpr; - yymsp[-1].minor.yy242->a[0].pExpr = 0; - sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242); - pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0); - yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy202, pRHS); - if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); - }else{ - yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0); - if( yymsp[-4].minor.yy202 ){ - yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy242; - sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202); - }else{ - sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242); - } - if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); - } - } - break; - case 209: /* expr ::= LP select RP */ -{ - yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_SELECT, 0, 0); - sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy202, yymsp[-1].minor.yy539); - } - break; - case 210: /* expr ::= expr in_op LP select RP */ -{ - yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0); - sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, yymsp[-1].minor.yy539); - if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); - } - break; - case 211: /* expr ::= expr in_op nm dbnm paren_exprlist */ -{ - SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); - Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0); - if( yymsp[0].minor.yy242 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy242); - yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0); - sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, pSelect); - if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0); - } - break; - case 212: /* expr ::= EXISTS LP select RP */ -{ - Expr *p; - p = yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0); - sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy539); - } - break; - case 213: /* expr ::= CASE case_operand case_exprlist case_else END */ -{ - yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy202, 0); - if( yymsp[-4].minor.yy202 ){ - yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy202 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy202) : yymsp[-2].minor.yy242; - sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202); - }else{ - sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242); - sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy202); - } -} - break; - case 214: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ -{ - yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy202); - yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[0].minor.yy202); -} - break; - case 215: /* case_exprlist ::= WHEN expr THEN expr */ -{ - yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202); - yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, yymsp[0].minor.yy202); -} - break; - case 218: /* case_operand ::= expr */ -{yymsp[0].minor.yy202 = yymsp[0].minor.yy202; /*A-overwrites-X*/} - break; - case 221: /* nexprlist ::= nexprlist COMMA expr */ -{yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy202);} - break; - case 222: /* nexprlist ::= expr */ -{yymsp[0].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy202); /*A-overwrites-Y*/} - break; - case 224: /* paren_exprlist ::= LP exprlist RP */ - case 229: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==229); -{yymsp[-2].minor.yy242 = yymsp[-1].minor.yy242;} - break; - case 225: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ -{ - sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, - sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy242, yymsp[-10].minor.yy192, - &yymsp[-11].minor.yy0, yymsp[0].minor.yy202, SQLITE_SO_ASC, yymsp[-8].minor.yy192, SQLITE_IDXTYPE_APPDEF); - if( IN_RENAME_OBJECT && pParse->pNewIndex ){ - sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0); - } -} - break; - case 226: /* uniqueflag ::= UNIQUE */ - case 268: /* raisetype ::= ABORT */ yytestcase(yyruleno==268); -{yymsp[0].minor.yy192 = OE_Abort;} - break; - case 227: /* uniqueflag ::= */ -{yymsp[1].minor.yy192 = OE_None;} - break; - case 230: /* eidlist ::= eidlist COMMA nm collate sortorder */ -{ - yymsp[-4].minor.yy242 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); -} - break; - case 231: /* eidlist ::= nm collate sortorder */ -{ - yymsp[-2].minor.yy242 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); /*A-overwrites-Y*/ -} - break; - case 234: /* cmd ::= DROP INDEX ifexists fullname */ -{sqlite3DropIndex(pParse, yymsp[0].minor.yy47, yymsp[-1].minor.yy192);} - break; - case 235: /* cmd ::= VACUUM vinto */ -{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy202);} - break; - case 236: /* cmd ::= VACUUM nm vinto */ -{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy202);} - break; - case 239: /* cmd ::= PRAGMA nm dbnm */ -{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} - break; - case 240: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ -{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} - break; - case 241: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ -{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} - break; - case 242: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ -{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} - break; - case 243: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */ -{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);} - break; - case 246: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ -{ - Token all; - all.z = yymsp[-3].minor.yy0.z; - all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; - sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy447, &all); -} - break; - case 247: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ -{ - sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy192, yymsp[-4].minor.yy230.a, yymsp[-4].minor.yy230.b, yymsp[-2].minor.yy47, yymsp[0].minor.yy202, yymsp[-10].minor.yy192, yymsp[-8].minor.yy192); - yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/ -} - break; - case 248: /* trigger_time ::= BEFORE|AFTER */ -{ yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/ } - break; - case 249: /* trigger_time ::= INSTEAD OF */ -{ yymsp[-1].minor.yy192 = TK_INSTEAD;} - break; - case 250: /* trigger_time ::= */ -{ yymsp[1].minor.yy192 = TK_BEFORE; } - break; - case 251: /* trigger_event ::= DELETE|INSERT */ - case 252: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==252); -{yymsp[0].minor.yy230.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy230.b = 0;} - break; - case 253: /* trigger_event ::= UPDATE OF idlist */ -{yymsp[-2].minor.yy230.a = TK_UPDATE; yymsp[-2].minor.yy230.b = yymsp[0].minor.yy600;} - break; - case 254: /* when_clause ::= */ - case 273: /* key_opt ::= */ yytestcase(yyruleno==273); -{ yymsp[1].minor.yy202 = 0; } - break; - case 255: /* when_clause ::= WHEN expr */ - case 274: /* key_opt ::= KEY expr */ yytestcase(yyruleno==274); -{ yymsp[-1].minor.yy202 = yymsp[0].minor.yy202; } - break; - case 256: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ -{ - assert( yymsp[-2].minor.yy447!=0 ); - yymsp[-2].minor.yy447->pLast->pNext = yymsp[-1].minor.yy447; - yymsp[-2].minor.yy447->pLast = yymsp[-1].minor.yy447; -} - break; - case 257: /* trigger_cmd_list ::= trigger_cmd SEMI */ -{ - assert( yymsp[-1].minor.yy447!=0 ); - yymsp[-1].minor.yy447->pLast = yymsp[-1].minor.yy447; -} - break; - case 258: /* trnm ::= nm DOT nm */ -{ - yymsp[-2].minor.yy0 = yymsp[0].minor.yy0; - sqlite3ErrorMsg(pParse, - "qualified table names are not allowed on INSERT, UPDATE, and DELETE " - "statements within triggers"); -} - break; - case 259: /* tridxby ::= INDEXED BY nm */ -{ - sqlite3ErrorMsg(pParse, - "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " - "within triggers"); -} - break; - case 260: /* tridxby ::= NOT INDEXED */ -{ - sqlite3ErrorMsg(pParse, - "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " - "within triggers"); -} - break; - case 261: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */ -{yylhsminor.yy447 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy47, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202, yymsp[-7].minor.yy192, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy436);} - yymsp[-8].minor.yy447 = yylhsminor.yy447; - break; - case 262: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ -{ - yylhsminor.yy447 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy600,yymsp[-2].minor.yy539,yymsp[-6].minor.yy192,yymsp[-1].minor.yy318,yymsp[-7].minor.yy436,yymsp[0].minor.yy436);/*yylhsminor.yy447-overwrites-yymsp[-6].minor.yy192*/ -} - yymsp[-7].minor.yy447 = yylhsminor.yy447; - break; - case 263: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ -{yylhsminor.yy447 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy202, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy436);} - yymsp[-5].minor.yy447 = yylhsminor.yy447; - break; - case 264: /* trigger_cmd ::= scanpt select scanpt */ -{yylhsminor.yy447 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy539, yymsp[-2].minor.yy436, yymsp[0].minor.yy436); /*yylhsminor.yy447-overwrites-yymsp[-1].minor.yy539*/} - yymsp[-2].minor.yy447 = yylhsminor.yy447; - break; - case 265: /* expr ::= RAISE LP IGNORE RP */ -{ - yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_RAISE, 0, 0); - if( yymsp[-3].minor.yy202 ){ - yymsp[-3].minor.yy202->affExpr = OE_Ignore; - } -} - break; - case 266: /* expr ::= RAISE LP raisetype COMMA nm RP */ -{ - yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); - if( yymsp[-5].minor.yy202 ) { - yymsp[-5].minor.yy202->affExpr = (char)yymsp[-3].minor.yy192; - } -} - break; - case 267: /* raisetype ::= ROLLBACK */ -{yymsp[0].minor.yy192 = OE_Rollback;} - break; - case 269: /* raisetype ::= FAIL */ -{yymsp[0].minor.yy192 = OE_Fail;} - break; - case 270: /* cmd ::= DROP TRIGGER ifexists fullname */ -{ - sqlite3DropTrigger(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy192); -} - break; - case 271: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ -{ - sqlite3Attach(pParse, yymsp[-3].minor.yy202, yymsp[-1].minor.yy202, yymsp[0].minor.yy202); -} - break; - case 272: /* cmd ::= DETACH database_kw_opt expr */ -{ - sqlite3Detach(pParse, yymsp[0].minor.yy202); -} - break; - case 275: /* cmd ::= REINDEX */ -{sqlite3Reindex(pParse, 0, 0);} - break; - case 276: /* cmd ::= REINDEX nm dbnm */ -{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} - break; - case 277: /* cmd ::= ANALYZE */ -{sqlite3Analyze(pParse, 0, 0);} - break; - case 278: /* cmd ::= ANALYZE nm dbnm */ -{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} - break; - case 279: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ -{ - sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy47,&yymsp[0].minor.yy0); -} - break; - case 280: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ -{ - yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n; - sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0); -} - break; - case 281: /* add_column_fullname ::= fullname */ -{ - disableLookaside(pParse); - sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy47); -} - break; - case 282: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ -{ - sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy47, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0); -} - break; - case 283: /* cmd ::= create_vtab */ -{sqlite3VtabFinishParse(pParse,0);} - break; - case 284: /* cmd ::= create_vtab LP vtabarglist RP */ -{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} - break; - case 285: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ -{ - sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy192); -} - break; - case 286: /* vtabarg ::= */ -{sqlite3VtabArgInit(pParse);} - break; - case 287: /* vtabargtoken ::= ANY */ - case 288: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==288); - case 289: /* lp ::= LP */ yytestcase(yyruleno==289); -{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} - break; - case 290: /* with ::= WITH wqlist */ - case 291: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==291); -{ sqlite3WithPush(pParse, yymsp[0].minor.yy131, 1); } - break; - case 292: /* wqlist ::= nm eidlist_opt AS LP select RP */ -{ - yymsp[-5].minor.yy131 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); /*A-overwrites-X*/ -} - break; - case 293: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ -{ - yymsp[-7].minor.yy131 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy131, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); -} - break; - case 294: /* windowdefn_list ::= windowdefn */ -{ yylhsminor.yy303 = yymsp[0].minor.yy303; } - yymsp[0].minor.yy303 = yylhsminor.yy303; - break; - case 295: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */ -{ - assert( yymsp[0].minor.yy303!=0 ); - sqlite3WindowChain(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy303); - yymsp[0].minor.yy303->pNextWin = yymsp[-2].minor.yy303; - yylhsminor.yy303 = yymsp[0].minor.yy303; -} - yymsp[-2].minor.yy303 = yylhsminor.yy303; - break; - case 296: /* windowdefn ::= nm AS LP window RP */ -{ - if( ALWAYS(yymsp[-1].minor.yy303) ){ - yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n); - } - yylhsminor.yy303 = yymsp[-1].minor.yy303; -} - yymsp[-4].minor.yy303 = yylhsminor.yy303; - break; - case 297: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */ -{ - yymsp[-4].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, 0); -} - break; - case 298: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ -{ - yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, &yymsp[-5].minor.yy0); -} - yymsp[-5].minor.yy303 = yylhsminor.yy303; - break; - case 299: /* window ::= ORDER BY sortlist frame_opt */ -{ - yymsp[-3].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, 0); -} - break; - case 300: /* window ::= nm ORDER BY sortlist frame_opt */ -{ - yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0); -} - yymsp[-4].minor.yy303 = yylhsminor.yy303; - break; - case 301: /* window ::= frame_opt */ - case 320: /* filter_over ::= over_clause */ yytestcase(yyruleno==320); -{ - yylhsminor.yy303 = yymsp[0].minor.yy303; -} - yymsp[0].minor.yy303 = yylhsminor.yy303; - break; - case 302: /* window ::= nm frame_opt */ -{ - yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, 0, &yymsp[-1].minor.yy0); -} - yymsp[-1].minor.yy303 = yylhsminor.yy303; - break; - case 303: /* frame_opt ::= */ -{ - yymsp[1].minor.yy303 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0); -} - break; - case 304: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ -{ - yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy192, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy58); -} - yymsp[-2].minor.yy303 = yylhsminor.yy303; - break; - case 305: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ -{ - yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy192, yymsp[-3].minor.yy77.eType, yymsp[-3].minor.yy77.pExpr, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, yymsp[0].minor.yy58); -} - yymsp[-5].minor.yy303 = yylhsminor.yy303; - break; - case 307: /* frame_bound_s ::= frame_bound */ - case 309: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==309); -{yylhsminor.yy77 = yymsp[0].minor.yy77;} - yymsp[0].minor.yy77 = yylhsminor.yy77; - break; - case 308: /* frame_bound_s ::= UNBOUNDED PRECEDING */ - case 310: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==310); - case 312: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==312); -{yylhsminor.yy77.eType = yymsp[-1].major; yylhsminor.yy77.pExpr = 0;} - yymsp[-1].minor.yy77 = yylhsminor.yy77; - break; - case 311: /* frame_bound ::= expr PRECEDING|FOLLOWING */ -{yylhsminor.yy77.eType = yymsp[0].major; yylhsminor.yy77.pExpr = yymsp[-1].minor.yy202;} - yymsp[-1].minor.yy77 = yylhsminor.yy77; - break; - case 313: /* frame_exclude_opt ::= */ -{yymsp[1].minor.yy58 = 0;} - break; - case 314: /* frame_exclude_opt ::= EXCLUDE frame_exclude */ -{yymsp[-1].minor.yy58 = yymsp[0].minor.yy58;} - break; - case 315: /* frame_exclude ::= NO OTHERS */ - case 316: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==316); -{yymsp[-1].minor.yy58 = yymsp[-1].major; /*A-overwrites-X*/} - break; - case 317: /* frame_exclude ::= GROUP|TIES */ -{yymsp[0].minor.yy58 = yymsp[0].major; /*A-overwrites-X*/} - break; - case 318: /* window_clause ::= WINDOW windowdefn_list */ -{ yymsp[-1].minor.yy303 = yymsp[0].minor.yy303; } - break; - case 319: /* filter_over ::= filter_clause over_clause */ -{ - yymsp[0].minor.yy303->pFilter = yymsp[-1].minor.yy202; - yylhsminor.yy303 = yymsp[0].minor.yy303; -} - yymsp[-1].minor.yy303 = yylhsminor.yy303; - break; - case 321: /* filter_over ::= filter_clause */ -{ - yylhsminor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); - if( yylhsminor.yy303 ){ - yylhsminor.yy303->eFrmType = TK_FILTER; - yylhsminor.yy303->pFilter = yymsp[0].minor.yy202; - }else{ - sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy202); - } -} - yymsp[0].minor.yy303 = yylhsminor.yy303; - break; - case 322: /* over_clause ::= OVER LP window RP */ -{ - yymsp[-3].minor.yy303 = yymsp[-1].minor.yy303; - assert( yymsp[-3].minor.yy303!=0 ); -} - break; - case 323: /* over_clause ::= OVER nm */ -{ - yymsp[-1].minor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); - if( yymsp[-1].minor.yy303 ){ - yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n); - } -} - break; - case 324: /* filter_clause ::= FILTER LP WHERE expr RP */ -{ yymsp[-4].minor.yy202 = yymsp[-1].minor.yy202; } - break; - default: - /* (325) input ::= cmdlist */ yytestcase(yyruleno==325); - /* (326) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==326); - /* (327) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=327); - /* (328) ecmd ::= SEMI */ yytestcase(yyruleno==328); - /* (329) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==329); - /* (330) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=330); - /* (331) trans_opt ::= */ yytestcase(yyruleno==331); - /* (332) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==332); - /* (333) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==333); - /* (334) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==334); - /* (335) savepoint_opt ::= */ yytestcase(yyruleno==335); - /* (336) cmd ::= create_table create_table_args */ yytestcase(yyruleno==336); - /* (337) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==337); - /* (338) columnlist ::= columnname carglist */ yytestcase(yyruleno==338); - /* (339) nm ::= ID|INDEXED */ yytestcase(yyruleno==339); - /* (340) nm ::= STRING */ yytestcase(yyruleno==340); - /* (341) nm ::= JOIN_KW */ yytestcase(yyruleno==341); - /* (342) typetoken ::= typename */ yytestcase(yyruleno==342); - /* (343) typename ::= ID|STRING */ yytestcase(yyruleno==343); - /* (344) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=344); - /* (345) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=345); - /* (346) carglist ::= carglist ccons */ yytestcase(yyruleno==346); - /* (347) carglist ::= */ yytestcase(yyruleno==347); - /* (348) ccons ::= NULL onconf */ yytestcase(yyruleno==348); - /* (349) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==349); - /* (350) ccons ::= AS generated */ yytestcase(yyruleno==350); - /* (351) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==351); - /* (352) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==352); - /* (353) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=353); - /* (354) tconscomma ::= */ yytestcase(yyruleno==354); - /* (355) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=355); - /* (356) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=356); - /* (357) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=357); - /* (358) oneselect ::= values */ yytestcase(yyruleno==358); - /* (359) sclp ::= selcollist COMMA */ yytestcase(yyruleno==359); - /* (360) as ::= ID|STRING */ yytestcase(yyruleno==360); - /* (361) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=361); - /* (362) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==362); - /* (363) exprlist ::= nexprlist */ yytestcase(yyruleno==363); - /* (364) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=364); - /* (365) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=365); - /* (366) nmnum ::= ON */ yytestcase(yyruleno==366); - /* (367) nmnum ::= DELETE */ yytestcase(yyruleno==367); - /* (368) nmnum ::= DEFAULT */ yytestcase(yyruleno==368); - /* (369) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==369); - /* (370) foreach_clause ::= */ yytestcase(yyruleno==370); - /* (371) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==371); - /* (372) trnm ::= nm */ yytestcase(yyruleno==372); - /* (373) tridxby ::= */ yytestcase(yyruleno==373); - /* (374) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==374); - /* (375) database_kw_opt ::= */ yytestcase(yyruleno==375); - /* (376) kwcolumn_opt ::= */ yytestcase(yyruleno==376); - /* (377) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==377); - /* (378) vtabarglist ::= vtabarg */ yytestcase(yyruleno==378); - /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==379); - /* (380) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==380); - /* (381) anylist ::= */ yytestcase(yyruleno==381); - /* (382) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==382); - /* (383) anylist ::= anylist ANY */ yytestcase(yyruleno==383); - /* (384) with ::= */ yytestcase(yyruleno==384); - break; -/********** End reduce actions ************************************************/ - }; - assert( yyrulenoYY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) ); - - /* It is not possible for a REDUCE to be followed by an error */ - assert( yyact!=YY_ERROR_ACTION ); - - yymsp += yysize+1; - yypParser->yytos = yymsp; - yymsp->stateno = (YYACTIONTYPE)yyact; - yymsp->major = (YYCODETYPE)yygoto; - yyTraceShift(yypParser, yyact, "... then shift"); - return yyact; -} - -/* -** The following code executes when the parse fails -*/ -#ifndef YYNOERRORRECOVERY -static void yy_parse_failed( - yyParser *yypParser /* The parser */ -){ - sqlite3ParserARG_FETCH - sqlite3ParserCTX_FETCH -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); - } -#endif - while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser); - /* Here code is inserted which will be executed whenever the - ** parser fails */ -/************ Begin %parse_failure code ***************************************/ -/************ End %parse_failure code *****************************************/ - sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ - sqlite3ParserCTX_STORE -} -#endif /* YYNOERRORRECOVERY */ - -/* -** The following code executes when a syntax error first occurs. -*/ -static void yy_syntax_error( - yyParser *yypParser, /* The parser */ - int yymajor, /* The major type of the error token */ - sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */ -){ - sqlite3ParserARG_FETCH - sqlite3ParserCTX_FETCH -#define TOKEN yyminor -/************ Begin %syntax_error code ****************************************/ - - UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ - if( TOKEN.z[0] ){ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); - }else{ - sqlite3ErrorMsg(pParse, "incomplete input"); - } -/************ End %syntax_error code ******************************************/ - sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ - sqlite3ParserCTX_STORE -} - -/* -** The following is executed when the parser accepts -*/ -static void yy_accept( - yyParser *yypParser /* The parser */ -){ - sqlite3ParserARG_FETCH - sqlite3ParserCTX_FETCH -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); - } -#endif -#ifndef YYNOERRORRECOVERY - yypParser->yyerrcnt = -1; -#endif - assert( yypParser->yytos==yypParser->yystack ); - /* Here code is inserted which will be executed whenever the - ** parser accepts */ -/*********** Begin %parse_accept code *****************************************/ -/*********** End %parse_accept code *******************************************/ - sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */ - sqlite3ParserCTX_STORE -} - -/* The main parser program. -** The first argument is a pointer to a structure obtained from -** "sqlite3ParserAlloc" which describes the current state of the parser. -** The second argument is the major token number. The third is -** the minor token. The fourth optional argument is whatever the -** user wants (and specified in the grammar) and is available for -** use by the action routines. -** -** Inputs: -**
      -**
    • A pointer to the parser (an opaque structure.) -**
    • The major token number. -**
    • The minor token number. -**
    • An option argument of a grammar-specified type. -**
    -** -** Outputs: -** None. -*/ -SQLITE_PRIVATE void sqlite3Parser( - void *yyp, /* The parser */ - int yymajor, /* The major token code number */ - sqlite3ParserTOKENTYPE yyminor /* The value for the token */ - sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ -){ - YYMINORTYPE yyminorunion; - YYACTIONTYPE yyact; /* The parser action. */ -#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) - int yyendofinput; /* True if we are at the end of input */ -#endif -#ifdef YYERRORSYMBOL - int yyerrorhit = 0; /* True if yymajor has invoked an error */ -#endif - yyParser *yypParser = (yyParser*)yyp; /* The parser */ - sqlite3ParserCTX_FETCH - sqlite3ParserARG_STORE - - assert( yypParser->yytos!=0 ); -#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) - yyendofinput = (yymajor==0); -#endif - - yyact = yypParser->yytos->stateno; -#ifndef NDEBUG - if( yyTraceFILE ){ - if( yyact < YY_MIN_REDUCE ){ - fprintf(yyTraceFILE,"%sInput '%s' in state %d\n", - yyTracePrompt,yyTokenName[yymajor],yyact); - }else{ - fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n", - yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE); - } - } -#endif - - do{ - assert( yyact==yypParser->yytos->stateno ); - yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact); - if( yyact >= YY_MIN_REDUCE ){ - yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor, - yyminor sqlite3ParserCTX_PARAM); - }else if( yyact <= YY_MAX_SHIFTREDUCE ){ - yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor); -#ifndef YYNOERRORRECOVERY - yypParser->yyerrcnt--; -#endif - break; - }else if( yyact==YY_ACCEPT_ACTION ){ - yypParser->yytos--; - yy_accept(yypParser); - return; - }else{ - assert( yyact == YY_ERROR_ACTION ); - yyminorunion.yy0 = yyminor; -#ifdef YYERRORSYMBOL - int yymx; -#endif -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); - } -#endif -#ifdef YYERRORSYMBOL - /* A syntax error has occurred. - ** The response to an error depends upon whether or not the - ** grammar defines an error token "ERROR". - ** - ** This is what we do if the grammar does define ERROR: - ** - ** * Call the %syntax_error function. - ** - ** * Begin popping the stack until we enter a state where - ** it is legal to shift the error symbol, then shift - ** the error symbol. - ** - ** * Set the error count to three. - ** - ** * Begin accepting and shifting new tokens. No new error - ** processing will occur until three tokens have been - ** shifted successfully. - ** - */ - if( yypParser->yyerrcnt<0 ){ - yy_syntax_error(yypParser,yymajor,yyminor); - } - yymx = yypParser->yytos->major; - if( yymx==YYERRORSYMBOL || yyerrorhit ){ -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sDiscard input token %s\n", - yyTracePrompt,yyTokenName[yymajor]); - } -#endif - yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion); - yymajor = YYNOCODE; - }else{ - while( yypParser->yytos >= yypParser->yystack - && (yyact = yy_find_reduce_action( - yypParser->yytos->stateno, - YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE - ){ - yy_pop_parser_stack(yypParser); - } - if( yypParser->yytos < yypParser->yystack || yymajor==0 ){ - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - yy_parse_failed(yypParser); -#ifndef YYNOERRORRECOVERY - yypParser->yyerrcnt = -1; -#endif - yymajor = YYNOCODE; - }else if( yymx!=YYERRORSYMBOL ){ - yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor); - } - } - yypParser->yyerrcnt = 3; - yyerrorhit = 1; - if( yymajor==YYNOCODE ) break; - yyact = yypParser->yytos->stateno; -#elif defined(YYNOERRORRECOVERY) - /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to - ** do any kind of error recovery. Instead, simply invoke the syntax - ** error routine and continue going as if nothing had happened. - ** - ** Applications can set this macro (for example inside %include) if - ** they intend to abandon the parse upon the first syntax error seen. - */ - yy_syntax_error(yypParser,yymajor, yyminor); - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - break; -#else /* YYERRORSYMBOL is not defined */ - /* This is what we do if the grammar does not define ERROR: - ** - ** * Report an error message, and throw away the input token. - ** - ** * If the input token is $, then fail the parse. - ** - ** As before, subsequent error messages are suppressed until - ** three input tokens have been successfully shifted. - */ - if( yypParser->yyerrcnt<=0 ){ - yy_syntax_error(yypParser,yymajor, yyminor); - } - yypParser->yyerrcnt = 3; - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - if( yyendofinput ){ - yy_parse_failed(yypParser); -#ifndef YYNOERRORRECOVERY - yypParser->yyerrcnt = -1; -#endif - } - break; -#endif - } - }while( yypParser->yytos>yypParser->yystack ); -#ifndef NDEBUG - if( yyTraceFILE ){ - yyStackEntry *i; - char cDiv = '['; - fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt); - for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){ - fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]); - cDiv = ' '; - } - fprintf(yyTraceFILE,"]\n"); - } -#endif - return; -} - -/* -** Return the fallback token corresponding to canonical token iToken, or -** 0 if iToken has no fallback. -*/ -SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){ -#ifdef YYFALLBACK - assert( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) ); - return yyFallback[iToken]; -#else - (void)iToken; - return 0; -#endif -} - -/************** End of parse.c ***********************************************/ -/************** Begin file tokenize.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. -** -************************************************************************* -** An tokenizer for SQL -** -** This file contains C code that splits an SQL input string up into -** individual tokens and sends those tokens one-by-one over to the -** parser for analysis. -*/ -/* #include "sqliteInt.h" */ -/* #include */ - -/* Character classes for tokenizing -** -** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented -** using a lookup table, whereas a switch() directly on c uses a binary search. -** The lookup table is much faster. To maximize speed, and to ensure that -** a lookup table is used, all of the classes need to be small integers and -** all of them need to be used within the switch. -*/ -#define CC_X 0 /* The letter 'x', or start of BLOB literal */ -#define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */ -#define CC_ID 2 /* unicode characters usable in IDs */ -#define CC_DIGIT 3 /* Digits */ -#define CC_DOLLAR 4 /* '$' */ -#define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */ -#define CC_VARNUM 6 /* '?'. Numeric SQL variables */ -#define CC_SPACE 7 /* Space characters */ -#define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */ -#define CC_QUOTE2 9 /* '['. [...] style quoted ids */ -#define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */ -#define CC_MINUS 11 /* '-'. Minus or SQL-style comment */ -#define CC_LT 12 /* '<'. Part of < or <= or <> */ -#define CC_GT 13 /* '>'. Part of > or >= */ -#define CC_EQ 14 /* '='. Part of = or == */ -#define CC_BANG 15 /* '!'. Part of != */ -#define CC_SLASH 16 /* '/'. / or c-style comment */ -#define CC_LP 17 /* '(' */ -#define CC_RP 18 /* ')' */ -#define CC_SEMI 19 /* ';' */ -#define CC_PLUS 20 /* '+' */ -#define CC_STAR 21 /* '*' */ -#define CC_PERCENT 22 /* '%' */ -#define CC_COMMA 23 /* ',' */ -#define CC_AND 24 /* '&' */ -#define CC_TILDA 25 /* '~' */ -#define CC_DOT 26 /* '.' */ -#define CC_ILLEGAL 27 /* Illegal character */ -#define CC_NUL 28 /* 0x00 */ - -static const unsigned char aiClass[] = { -#ifdef SQLITE_ASCII -/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ -/* 0x */ 28, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27, -/* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -/* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16, -/* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6, -/* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -/* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1, -/* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -/* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27, -/* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -/* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -/* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -/* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -/* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -/* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -/* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -/* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 -#endif -#ifdef SQLITE_EBCDIC -/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ -/* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27, -/* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -/* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -/* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -/* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10, -/* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27, -/* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6, -/* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8, -/* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, -/* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, -/* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, -/* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27, -/* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, -/* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27, -/* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27, -/* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27, -#endif -}; - -/* -** The charMap() macro maps alphabetic characters (only) into their -** lower-case ASCII equivalent. On ASCII machines, this is just -** an upper-to-lower case map. On EBCDIC machines we also need -** to adjust the encoding. The mapping is only valid for alphabetics -** which are the only characters for which this feature is used. -** -** Used by keywordhash.h -*/ -#ifdef SQLITE_ASCII -# define charMap(X) sqlite3UpperToLower[(unsigned char)X] -#endif -#ifdef SQLITE_EBCDIC -# define charMap(X) ebcdicToAscii[(unsigned char)X] -const unsigned char ebcdicToAscii[] = { -/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ - 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ - 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ - 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ - 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ - 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ - 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ -}; -#endif - -/* -** The sqlite3KeywordCode function looks up an identifier to determine if -** it is a keyword. If it is a keyword, the token code of that keyword is -** returned. If the input is not a keyword, TK_ID is returned. -** -** The implementation of this routine was generated by a program, -** mkkeywordhash.c, located in the tool subdirectory of the distribution. -** The output of the mkkeywordhash.c program is written into a file -** named keywordhash.h and then included into this source file by -** the #include below. -*/ -/************** Include keywordhash.h in the middle of tokenize.c ************/ -/************** Begin file keywordhash.h *************************************/ -/***** This file contains automatically generated code ****** -** -** The code in this file has been automatically generated by -** -** sqlite/tool/mkkeywordhash.c -** -** The code in this file implements a function that determines whether -** or not a given identifier is really an SQL keyword. The same thing -** might be implemented more directly using a hand-written hash table. -** But by using this automatically generated code, the size of the code -** is substantially reduced. This is important for embedded applications -** on platforms with limited memory. -*/ -/* Hash score: 227 */ -/* zKWText[] encodes 984 bytes of keyword text in 648 bytes */ -/* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ -/* ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYISNULLSAVEPOINTERSECT */ -/* IESNOTNULLIKEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTS */ -/* CONSTRAINTOFFSETRIGGERANGENERATEDETACHAVINGLOBEGINNEREFERENCES */ -/* UNIQUERYWITHOUTERELEASEATTACHBETWEENOTHINGROUPSCASCADEFAULT */ -/* CASECOLLATECREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZE */ -/* PRAGMABORTUPDATEVALUESVIRTUALWAYSWHENWHERECURSIVEAFTERENAMEAND */ -/* EFERREDISTINCTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */ -/* CURRENT_TIMESTAMPARTITIONDROPRECEDINGFAILASTFILTEREPLACEFIRST */ -/* FOLLOWINGFROMFULLIMITIFORDERESTRICTOTHERSOVERIGHTROLLBACKROWS */ -/* UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY */ -static const char zKWText[647] = { - 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', - 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', - 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', - 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', - 'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E', - 'T','E','M','P','O','R','A','R','Y','I','S','N','U','L','L','S','A','V', - 'E','P','O','I','N','T','E','R','S','E','C','T','I','E','S','N','O','T', - 'N','U','L','L','I','K','E','X','C','E','P','T','R','A','N','S','A','C', - 'T','I','O','N','A','T','U','R','A','L','T','E','R','A','I','S','E','X', - 'C','L','U','S','I','V','E','X','I','S','T','S','C','O','N','S','T','R', - 'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','A','N', - 'G','E','N','E','R','A','T','E','D','E','T','A','C','H','A','V','I','N', - 'G','L','O','B','E','G','I','N','N','E','R','E','F','E','R','E','N','C', - 'E','S','U','N','I','Q','U','E','R','Y','W','I','T','H','O','U','T','E', - 'R','E','L','E','A','S','E','A','T','T','A','C','H','B','E','T','W','E', - 'E','N','O','T','H','I','N','G','R','O','U','P','S','C','A','S','C','A', - 'D','E','F','A','U','L','T','C','A','S','E','C','O','L','L','A','T','E', - 'C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E', - 'I','M','M','E','D','I','A','T','E','J','O','I','N','S','E','R','T','M', - 'A','T','C','H','P','L','A','N','A','L','Y','Z','E','P','R','A','G','M', - 'A','B','O','R','T','U','P','D','A','T','E','V','A','L','U','E','S','V', - 'I','R','T','U','A','L','W','A','Y','S','W','H','E','N','W','H','E','R', - 'E','C','U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E', - 'A','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','A', - 'U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C','O', - 'L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C','T', - 'C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E','S', - 'T','A','M','P','A','R','T','I','T','I','O','N','D','R','O','P','R','E', - 'C','E','D','I','N','G','F','A','I','L','A','S','T','F','I','L','T','E', - 'R','E','P','L','A','C','E','F','I','R','S','T','F','O','L','L','O','W', - 'I','N','G','F','R','O','M','F','U','L','L','I','M','I','T','I','F','O', - 'R','D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O', - 'V','E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W', - 'S','U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I', - 'N','G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B', - 'Y','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y', -}; -/* aKWHash[i] is the hash value for the i-th keyword */ -static const unsigned char aKWHash[127] = { - 84, 102, 132, 82, 114, 29, 0, 0, 91, 0, 85, 72, 0, - 53, 35, 86, 15, 0, 42, 94, 54, 126, 133, 19, 0, 0, - 138, 0, 40, 128, 0, 22, 104, 0, 9, 0, 0, 122, 80, - 0, 78, 6, 0, 65, 99, 145, 0, 134, 112, 0, 0, 48, - 0, 100, 24, 0, 17, 0, 27, 70, 23, 26, 5, 60, 140, - 107, 121, 0, 73, 101, 71, 143, 61, 119, 74, 0, 49, 0, - 11, 41, 0, 110, 0, 0, 0, 106, 10, 108, 113, 124, 14, - 50, 123, 0, 89, 0, 18, 120, 142, 56, 129, 137, 88, 83, - 37, 30, 125, 0, 0, 105, 51, 130, 127, 0, 34, 0, 0, - 44, 0, 95, 38, 39, 0, 20, 45, 116, 90, -}; -/* aKWNext[] forms the hash collision chain. If aKWHash[i]==0 -** then the i-th keyword has no more hash collisions. Otherwise, -** the next keyword with the same hash is aKWHash[i]-1. */ -static const unsigned char aKWNext[145] = { - 0, 0, 0, 0, 4, 0, 43, 0, 0, 103, 111, 0, 0, - 0, 2, 0, 0, 141, 0, 0, 0, 13, 0, 0, 0, 0, - 139, 0, 0, 118, 52, 0, 0, 135, 12, 0, 0, 62, 0, - 136, 0, 131, 0, 0, 36, 0, 0, 28, 77, 0, 0, 0, - 0, 59, 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 69, 0, 0, 0, 0, 0, 144, 3, 0, 58, 0, 1, - 75, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 64, 66, - 63, 0, 0, 0, 0, 46, 0, 16, 0, 115, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 81, 97, 0, 8, 0, 109, - 21, 7, 67, 0, 79, 93, 117, 0, 0, 68, 0, 0, 96, - 0, 55, 0, 76, 0, 92, 32, 33, 57, 25, 0, 98, 0, - 0, 87, -}; -/* aKWLen[i] is the length (in bytes) of the i-th keyword */ -static const unsigned char aKWLen[145] = { - 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, - 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 7, - 6, 9, 4, 2, 6, 5, 9, 9, 4, 7, 3, 2, 4, - 4, 6, 11, 6, 2, 7, 5, 5, 9, 6, 10, 4, 6, - 2, 3, 7, 5, 9, 6, 6, 4, 5, 5, 10, 6, 5, - 7, 4, 5, 7, 6, 7, 7, 6, 5, 7, 3, 7, 4, - 7, 6, 12, 9, 4, 6, 5, 4, 7, 6, 5, 6, 6, - 7, 6, 4, 5, 9, 5, 6, 3, 8, 8, 2, 13, 2, - 2, 4, 6, 6, 8, 5, 17, 12, 7, 9, 4, 9, 4, - 4, 6, 7, 5, 9, 4, 4, 5, 2, 5, 8, 6, 4, - 5, 8, 4, 3, 9, 5, 5, 6, 4, 6, 2, 2, 9, - 3, 7, -}; -/* aKWOffset[i] is the index into zKWText[] of the start of -** the text for the i-th keyword. */ -static const unsigned short int aKWOffset[145] = { - 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, - 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, - 86, 90, 90, 94, 99, 101, 105, 111, 119, 123, 123, 123, 126, - 129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184, - 184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239, - 244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295, - 299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 360, 365, 371, - 377, 382, 388, 392, 395, 404, 408, 414, 416, 423, 424, 431, 433, - 435, 444, 448, 454, 460, 468, 473, 473, 473, 489, 498, 501, 510, - 513, 517, 522, 529, 534, 543, 547, 550, 555, 557, 561, 569, 575, - 578, 583, 591, 591, 595, 604, 609, 614, 620, 623, 626, 629, 631, - 636, 640, -}; -/* aKWCode[i] is the parser symbol code for the i-th keyword */ -static const unsigned char aKWCode[145] = { - TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, - TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, - TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, - TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, - TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, - TK_EXCLUDE, TK_DELETE, TK_TEMP, TK_TEMP, TK_OR, - TK_ISNULL, TK_NULLS, TK_SAVEPOINT, TK_INTERSECT, TK_TIES, - TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, - TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, - TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_CONSTRAINT, - TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TRIGGER, - TK_RANGE, TK_GENERATED, TK_DETACH, TK_HAVING, TK_LIKE_KW, - TK_BEGIN, TK_JOIN_KW, TK_REFERENCES, TK_UNIQUE, TK_QUERY, - TK_WITHOUT, TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_ATTACH, - TK_BETWEEN, TK_NOTHING, TK_GROUPS, TK_GROUP, TK_CASCADE, - TK_ASC, TK_DEFAULT, TK_CASE, TK_COLLATE, TK_CREATE, - TK_CTIME_KW, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH, - TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_UPDATE, - TK_VALUES, TK_VIRTUAL, TK_ALWAYS, TK_WHEN, TK_WHERE, - TK_RECURSIVE, TK_AFTER, TK_RENAME, TK_AND, TK_DEFERRED, - TK_DISTINCT, TK_IS, TK_AUTOINCR, TK_TO, TK_IN, - TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, - TK_CTIME_KW, TK_CTIME_KW, TK_CURRENT, TK_PARTITION, TK_DROP, - TK_PRECEDING, TK_FAIL, TK_LAST, TK_FILTER, TK_REPLACE, - TK_FIRST, TK_FOLLOWING, TK_FROM, TK_JOIN_KW, TK_LIMIT, - TK_IF, TK_ORDER, TK_RESTRICT, TK_OTHERS, TK_OVER, - TK_JOIN_KW, TK_ROLLBACK, TK_ROWS, TK_ROW, TK_UNBOUNDED, - TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_WINDOW, - TK_DO, TK_BY, TK_INITIALLY, TK_ALL, TK_PRIMARY, -}; -/* Hash table decoded: -** 0: INSERT -** 1: IS -** 2: ROLLBACK TRIGGER -** 3: IMMEDIATE -** 4: PARTITION -** 5: TEMP -** 6: -** 7: -** 8: VALUES WITHOUT -** 9: -** 10: MATCH -** 11: NOTHING -** 12: -** 13: OF -** 14: TIES IGNORE -** 15: PLAN -** 16: INSTEAD INDEXED -** 17: -** 18: TRANSACTION RIGHT -** 19: WHEN -** 20: SET HAVING -** 21: IF -** 22: ROWS -** 23: SELECT -** 24: -** 25: -** 26: VACUUM SAVEPOINT -** 27: -** 28: LIKE UNION VIRTUAL REFERENCES -** 29: RESTRICT -** 30: -** 31: THEN REGEXP -** 32: TO -** 33: -** 34: BEFORE -** 35: -** 36: -** 37: FOLLOWING COLLATE CASCADE -** 38: CREATE -** 39: -** 40: CASE REINDEX -** 41: EACH -** 42: -** 43: QUERY -** 44: AND ADD -** 45: PRIMARY ANALYZE -** 46: -** 47: ROW ASC DETACH -** 48: CURRENT_TIME CURRENT_DATE -** 49: -** 50: -** 51: EXCLUSIVE TEMPORARY -** 52: -** 53: DEFERRED -** 54: DEFERRABLE -** 55: -** 56: DATABASE -** 57: -** 58: DELETE VIEW GENERATED -** 59: ATTACH -** 60: END -** 61: EXCLUDE -** 62: ESCAPE DESC -** 63: GLOB -** 64: WINDOW ELSE -** 65: COLUMN -** 66: FIRST -** 67: -** 68: GROUPS ALL -** 69: DISTINCT DROP KEY -** 70: BETWEEN -** 71: INITIALLY -** 72: BEGIN -** 73: FILTER CHECK ACTION -** 74: GROUP INDEX -** 75: -** 76: EXISTS DEFAULT -** 77: -** 78: FOR CURRENT_TIMESTAMP -** 79: EXCEPT -** 80: -** 81: CROSS -** 82: -** 83: -** 84: -** 85: CAST -** 86: FOREIGN AUTOINCREMENT -** 87: COMMIT -** 88: CURRENT AFTER ALTER -** 89: FULL FAIL CONFLICT -** 90: EXPLAIN -** 91: CONSTRAINT -** 92: FROM ALWAYS -** 93: -** 94: ABORT -** 95: -** 96: AS DO -** 97: REPLACE WITH RELEASE -** 98: BY RENAME -** 99: RANGE RAISE -** 100: OTHERS -** 101: USING NULLS -** 102: PRAGMA -** 103: JOIN ISNULL OFFSET -** 104: NOT -** 105: OR LAST LEFT -** 106: LIMIT -** 107: -** 108: -** 109: IN -** 110: INTO -** 111: OVER RECURSIVE -** 112: ORDER OUTER -** 113: -** 114: INTERSECT UNBOUNDED -** 115: -** 116: -** 117: ON -** 118: -** 119: WHERE -** 120: NO INNER -** 121: NULL -** 122: -** 123: TABLE -** 124: NATURAL NOTNULL -** 125: PRECEDING -** 126: UPDATE UNIQUE -*/ -/* Check to see if z[0..n-1] is a keyword. If it is, write the -** parser symbol code for that keyword into *pType. Always -** return the integer n (the length of the token). */ -static int keywordCode(const char *z, int n, int *pType){ - int i, j; - const char *zKW; - if( n>=2 ){ - i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127; - for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){ - if( aKWLen[i]!=n ) continue; - zKW = &zKWText[aKWOffset[i]]; -#ifdef SQLITE_ASCII - if( (z[0]&~0x20)!=zKW[0] ) continue; - if( (z[1]&~0x20)!=zKW[1] ) continue; - j = 2; - while( j=SQLITE_N_KEYWORD ) return SQLITE_ERROR; - *pzName = zKWText + aKWOffset[i]; - *pnName = aKWLen[i]; - return SQLITE_OK; -} -SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; } -SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){ - return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName); -} - -/************** End of keywordhash.h *****************************************/ -/************** Continuing where we left off in tokenize.c *******************/ - - -/* -** If X is a character that can be used in an identifier then -** IdChar(X) will be true. Otherwise it is false. -** -** For ASCII, any character with the high-order bit set is -** allowed in an identifier. For 7-bit characters, -** sqlite3IsIdChar[X] must be 1. -** -** For EBCDIC, the rules are more complex but have the same -** end result. -** -** Ticket #1066. the SQL standard does not allow '$' in the -** middle of identifiers. But many SQL implementations do. -** SQLite will allow '$' in identifiers for compatibility. -** But the feature is undocumented. -*/ -#ifdef SQLITE_ASCII -#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) -#endif -#ifdef SQLITE_EBCDIC -SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = { -/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ - 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ - 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ - 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ - 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ -}; -#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) -#endif - -/* Make the IdChar function accessible from ctime.c and alter.c */ -SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); } - -#ifndef SQLITE_OMIT_WINDOWFUNC -/* -** Return the id of the next token in string (*pz). Before returning, set -** (*pz) to point to the byte following the parsed token. -*/ -static int getToken(const unsigned char **pz){ - const unsigned char *z = *pz; - int t; /* Token type to return */ - do { - z += sqlite3GetToken(z, &t); - }while( t==TK_SPACE ); - if( t==TK_ID - || t==TK_STRING - || t==TK_JOIN_KW - || t==TK_WINDOW - || t==TK_OVER - || sqlite3ParserFallback(t)==TK_ID - ){ - t = TK_ID; - } - *pz = z; - return t; -} - -/* -** The following three functions are called immediately after the tokenizer -** reads the keywords WINDOW, OVER and FILTER, respectively, to determine -** whether the token should be treated as a keyword or an SQL identifier. -** This cannot be handled by the usual lemon %fallback method, due to -** the ambiguity in some constructions. e.g. -** -** SELECT sum(x) OVER ... -** -** In the above, "OVER" might be a keyword, or it might be an alias for the -** sum(x) expression. If a "%fallback ID OVER" directive were added to -** grammar, then SQLite would always treat "OVER" as an alias, making it -** impossible to call a window-function without a FILTER clause. -** -** WINDOW is treated as a keyword if: -** -** * the following token is an identifier, or a keyword that can fallback -** to being an identifier, and -** * the token after than one is TK_AS. -** -** OVER is a keyword if: -** -** * the previous token was TK_RP, and -** * the next token is either TK_LP or an identifier. -** -** FILTER is a keyword if: -** -** * the previous token was TK_RP, and -** * the next token is TK_LP. -*/ -static int analyzeWindowKeyword(const unsigned char *z){ - int t; - t = getToken(&z); - if( t!=TK_ID ) return TK_ID; - t = getToken(&z); - if( t!=TK_AS ) return TK_ID; - return TK_WINDOW; -} -static int analyzeOverKeyword(const unsigned char *z, int lastToken){ - if( lastToken==TK_RP ){ - int t = getToken(&z); - if( t==TK_LP || t==TK_ID ) return TK_OVER; - } - return TK_ID; -} -static int analyzeFilterKeyword(const unsigned char *z, int lastToken){ - if( lastToken==TK_RP && getToken(&z)==TK_LP ){ - return TK_FILTER; - } - return TK_ID; -} -#endif /* SQLITE_OMIT_WINDOWFUNC */ - -/* -** Return the length (in bytes) of the token that begins at z[0]. -** Store the token type in *tokenType before returning. -*/ -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ - int i, c; - switch( aiClass[*z] ){ /* Switch on the character-class of the first byte - ** of the token. See the comment on the CC_ defines - ** above. */ - case CC_SPACE: { - testcase( z[0]==' ' ); - testcase( z[0]=='\t' ); - testcase( z[0]=='\n' ); - testcase( z[0]=='\f' ); - testcase( z[0]=='\r' ); - for(i=1; sqlite3Isspace(z[i]); i++){} - *tokenType = TK_SPACE; - return i; - } - case CC_MINUS: { - if( z[1]=='-' ){ - for(i=2; (c=z[i])!=0 && c!='\n'; i++){} - *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ - return i; - } - *tokenType = TK_MINUS; - return 1; - } - case CC_LP: { - *tokenType = TK_LP; - return 1; - } - case CC_RP: { - *tokenType = TK_RP; - return 1; - } - case CC_SEMI: { - *tokenType = TK_SEMI; - return 1; - } - case CC_PLUS: { - *tokenType = TK_PLUS; - return 1; - } - case CC_STAR: { - *tokenType = TK_STAR; - return 1; - } - case CC_SLASH: { - if( z[1]!='*' || z[2]==0 ){ - *tokenType = TK_SLASH; - return 1; - } - for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){} - if( c ) i++; - *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ - return i; - } - case CC_PERCENT: { - *tokenType = TK_REM; - return 1; - } - case CC_EQ: { - *tokenType = TK_EQ; - return 1 + (z[1]=='='); - } - case CC_LT: { - if( (c=z[1])=='=' ){ - *tokenType = TK_LE; - return 2; - }else if( c=='>' ){ - *tokenType = TK_NE; - return 2; - }else if( c=='<' ){ - *tokenType = TK_LSHIFT; - return 2; - }else{ - *tokenType = TK_LT; - return 1; - } - } - case CC_GT: { - if( (c=z[1])=='=' ){ - *tokenType = TK_GE; - return 2; - }else if( c=='>' ){ - *tokenType = TK_RSHIFT; - return 2; - }else{ - *tokenType = TK_GT; - return 1; - } - } - case CC_BANG: { - if( z[1]!='=' ){ - *tokenType = TK_ILLEGAL; - return 1; - }else{ - *tokenType = TK_NE; - return 2; - } - } - case CC_PIPE: { - if( z[1]!='|' ){ - *tokenType = TK_BITOR; - return 1; - }else{ - *tokenType = TK_CONCAT; - return 2; - } - } - case CC_COMMA: { - *tokenType = TK_COMMA; - return 1; - } - case CC_AND: { - *tokenType = TK_BITAND; - return 1; - } - case CC_TILDA: { - *tokenType = TK_BITNOT; - return 1; - } - case CC_QUOTE: { - int delim = z[0]; - testcase( delim=='`' ); - testcase( delim=='\'' ); - testcase( delim=='"' ); - for(i=1; (c=z[i])!=0; i++){ - if( c==delim ){ - if( z[i+1]==delim ){ - i++; - }else{ - break; - } - } - } - if( c=='\'' ){ - *tokenType = TK_STRING; - return i+1; - }else if( c!=0 ){ - *tokenType = TK_ID; - return i+1; - }else{ - *tokenType = TK_ILLEGAL; - return i; - } - } - case CC_DOT: { -#ifndef SQLITE_OMIT_FLOATING_POINT - if( !sqlite3Isdigit(z[1]) ) -#endif - { - *tokenType = TK_DOT; - return 1; - } - /* If the next character is a digit, this is a floating point - ** number that begins with ".". Fall thru into the next case */ - /* no break */ deliberate_fall_through - } - case CC_DIGIT: { - testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' ); - testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' ); - testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' ); - testcase( z[0]=='9' ); - *tokenType = TK_INTEGER; -#ifndef SQLITE_OMIT_HEX_INTEGER - if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){ - for(i=3; sqlite3Isxdigit(z[i]); i++){} - return i; - } -#endif - for(i=0; sqlite3Isdigit(z[i]); i++){} -#ifndef SQLITE_OMIT_FLOATING_POINT - if( z[i]=='.' ){ - i++; - while( sqlite3Isdigit(z[i]) ){ i++; } - *tokenType = TK_FLOAT; - } - if( (z[i]=='e' || z[i]=='E') && - ( sqlite3Isdigit(z[i+1]) - || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2])) - ) - ){ - i += 2; - while( sqlite3Isdigit(z[i]) ){ i++; } - *tokenType = TK_FLOAT; - } -#endif - while( IdChar(z[i]) ){ - *tokenType = TK_ILLEGAL; - i++; - } - return i; - } - case CC_QUOTE2: { - for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} - *tokenType = c==']' ? TK_ID : TK_ILLEGAL; - return i; - } - case CC_VARNUM: { - *tokenType = TK_VARIABLE; - for(i=1; sqlite3Isdigit(z[i]); i++){} - return i; - } - case CC_DOLLAR: - case CC_VARALPHA: { - int n = 0; - testcase( z[0]=='$' ); testcase( z[0]=='@' ); - testcase( z[0]==':' ); testcase( z[0]=='#' ); - *tokenType = TK_VARIABLE; - for(i=1; (c=z[i])!=0; i++){ - if( IdChar(c) ){ - n++; -#ifndef SQLITE_OMIT_TCL_VARIABLE - }else if( c=='(' && n>0 ){ - do{ - i++; - }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' ); - if( c==')' ){ - i++; - }else{ - *tokenType = TK_ILLEGAL; - } - break; - }else if( c==':' && z[i+1]==':' ){ - i++; -#endif - }else{ - break; - } - } - if( n==0 ) *tokenType = TK_ILLEGAL; - return i; - } - case CC_KYWD: { - for(i=1; aiClass[z[i]]<=CC_KYWD; i++){} - if( IdChar(z[i]) ){ - /* This token started out using characters that can appear in keywords, - ** but z[i] is a character not allowed within keywords, so this must - ** be an identifier instead */ - i++; - break; - } - *tokenType = TK_ID; - return keywordCode((char*)z, i, tokenType); - } - case CC_X: { -#ifndef SQLITE_OMIT_BLOB_LITERAL - testcase( z[0]=='x' ); testcase( z[0]=='X' ); - if( z[1]=='\'' ){ - *tokenType = TK_BLOB; - for(i=2; sqlite3Isxdigit(z[i]); i++){} - if( z[i]!='\'' || i%2 ){ - *tokenType = TK_ILLEGAL; - while( z[i] && z[i]!='\'' ){ i++; } - } - if( z[i] ) i++; - return i; - } -#endif - /* If it is not a BLOB literal, then it must be an ID, since no - ** SQL keywords start with the letter 'x'. Fall through */ - /* no break */ deliberate_fall_through - } - case CC_ID: { - i = 1; - break; - } - case CC_NUL: { - *tokenType = TK_ILLEGAL; - return 0; - } - default: { - *tokenType = TK_ILLEGAL; - return 1; - } - } - while( IdChar(z[i]) ){ i++; } - *tokenType = TK_ID; - return i; -} - -/* -** Run the parser on the given SQL string. The parser structure is -** passed in. An SQLITE_ status code is returned. If an error occurs -** then an and attempt is made to write an error message into -** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that -** error message. -*/ -SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ - int nErr = 0; /* Number of errors encountered */ - void *pEngine; /* The LEMON-generated LALR(1) parser */ - int n = 0; /* Length of the next token token */ - int tokenType; /* type of the next token */ - int lastTokenParsed = -1; /* type of the previous token */ - sqlite3 *db = pParse->db; /* The database connection */ - int mxSqlLen; /* Max length of an SQL string */ -#ifdef sqlite3Parser_ENGINEALWAYSONSTACK - yyParser sEngine; /* Space to hold the Lemon-generated Parser object */ -#endif - VVA_ONLY( u8 startedWithOom = db->mallocFailed ); - - assert( zSql!=0 ); - mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; - if( db->nVdbeActive==0 ){ - AtomicStore(&db->u1.isInterrupted, 0); - } - pParse->rc = SQLITE_OK; - pParse->zTail = zSql; - assert( pzErrMsg!=0 ); -#ifdef SQLITE_DEBUG - if( db->flags & SQLITE_ParserTrace ){ - printf("parser: [[[%s]]]\n", zSql); - sqlite3ParserTrace(stdout, "parser: "); - }else{ - sqlite3ParserTrace(0, 0); - } -#endif -#ifdef sqlite3Parser_ENGINEALWAYSONSTACK - pEngine = &sEngine; - sqlite3ParserInit(pEngine, pParse); -#else - pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse); - if( pEngine==0 ){ - sqlite3OomFault(db); - return SQLITE_NOMEM_BKPT; - } -#endif - assert( pParse->pNewTable==0 ); - assert( pParse->pNewTrigger==0 ); - assert( pParse->nVar==0 ); - assert( pParse->pVList==0 ); - pParse->pParentParse = db->pParse; - db->pParse = pParse; - while( 1 ){ - n = sqlite3GetToken((u8*)zSql, &tokenType); - mxSqlLen -= n; - if( mxSqlLen<0 ){ - pParse->rc = SQLITE_TOOBIG; - break; - } -#ifndef SQLITE_OMIT_WINDOWFUNC - if( tokenType>=TK_WINDOW ){ - assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER - || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW - ); -#else - if( tokenType>=TK_SPACE ){ - assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL ); -#endif /* SQLITE_OMIT_WINDOWFUNC */ - if( AtomicLoad(&db->u1.isInterrupted) ){ - pParse->rc = SQLITE_INTERRUPT; - break; - } - if( tokenType==TK_SPACE ){ - zSql += n; - continue; - } - if( zSql[0]==0 ){ - /* Upon reaching the end of input, call the parser two more times - ** with tokens TK_SEMI and 0, in that order. */ - if( lastTokenParsed==TK_SEMI ){ - tokenType = 0; - }else if( lastTokenParsed==0 ){ - break; - }else{ - tokenType = TK_SEMI; - } - n = 0; -#ifndef SQLITE_OMIT_WINDOWFUNC - }else if( tokenType==TK_WINDOW ){ - assert( n==6 ); - tokenType = analyzeWindowKeyword((const u8*)&zSql[6]); - }else if( tokenType==TK_OVER ){ - assert( n==4 ); - tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed); - }else if( tokenType==TK_FILTER ){ - assert( n==6 ); - tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed); -#endif /* SQLITE_OMIT_WINDOWFUNC */ - }else{ - sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql); - break; - } - } - pParse->sLastToken.z = zSql; - pParse->sLastToken.n = n; - sqlite3Parser(pEngine, tokenType, pParse->sLastToken); - lastTokenParsed = tokenType; - zSql += n; - assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom ); - if( pParse->rc!=SQLITE_OK ) break; - } - assert( nErr==0 ); -#ifdef YYTRACKMAXSTACKDEPTH - sqlite3_mutex_enter(sqlite3MallocMutex()); - sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK, - sqlite3ParserStackPeak(pEngine) - ); - sqlite3_mutex_leave(sqlite3MallocMutex()); -#endif /* YYDEBUG */ -#ifdef sqlite3Parser_ENGINEALWAYSONSTACK - sqlite3ParserFinalize(pEngine); -#else - sqlite3ParserFree(pEngine, sqlite3_free); -#endif - if( db->mallocFailed ){ - pParse->rc = SQLITE_NOMEM_BKPT; - } - if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ - pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc)); - } - assert( pzErrMsg!=0 ); - if( pParse->zErrMsg ){ - *pzErrMsg = pParse->zErrMsg; - sqlite3_log(pParse->rc, "%s in \"%s\"", - *pzErrMsg, pParse->zTail); - pParse->zErrMsg = 0; - nErr++; - } - pParse->zTail = zSql; - if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ - sqlite3VdbeDelete(pParse->pVdbe); - pParse->pVdbe = 0; - } -#ifndef SQLITE_OMIT_SHARED_CACHE - if( pParse->nested==0 ){ - sqlite3DbFree(db, pParse->aTableLock); - pParse->aTableLock = 0; - pParse->nTableLock = 0; - } -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3_free(pParse->apVtabLock); -#endif - - if( !IN_SPECIAL_PARSE ){ - /* If the pParse->declareVtab flag is set, do not delete any table - ** structure built up in pParse->pNewTable. The calling code (see vtab.c) - ** will take responsibility for freeing the Table structure. - */ - sqlite3DeleteTable(db, pParse->pNewTable); - } - if( !IN_RENAME_OBJECT ){ - sqlite3DeleteTrigger(db, pParse->pNewTrigger); - } - - if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree); - sqlite3DbFree(db, pParse->pVList); - while( pParse->pAinc ){ - AutoincInfo *p = pParse->pAinc; - pParse->pAinc = p->pNext; - sqlite3DbFreeNN(db, p); - } - while( pParse->pZombieTab ){ - Table *p = pParse->pZombieTab; - pParse->pZombieTab = p->pNextZombie; - sqlite3DeleteTable(db, p); - } - db->pParse = pParse->pParentParse; - pParse->pParentParse = 0; - assert( nErr==0 || pParse->rc!=SQLITE_OK ); - return nErr; -} - - -#ifdef SQLITE_ENABLE_NORMALIZE -/* -** Insert a single space character into pStr if the current string -** ends with an identifier -*/ -static void addSpaceSeparator(sqlite3_str *pStr){ - if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){ - sqlite3_str_append(pStr, " ", 1); - } -} - -/* -** Compute a normalization of the SQL given by zSql[0..nSql-1]. Return -** the normalization in space obtained from sqlite3DbMalloc(). Or return -** NULL if anything goes wrong or if zSql is NULL. -*/ -SQLITE_PRIVATE char *sqlite3Normalize( - Vdbe *pVdbe, /* VM being reprepared */ - const char *zSql /* The original SQL string */ -){ - sqlite3 *db; /* The database connection */ - int i; /* Next unread byte of zSql[] */ - int n; /* length of current token */ - int tokenType; /* type of current token */ - int prevType = 0; /* Previous non-whitespace token */ - int nParen; /* Number of nested levels of parentheses */ - int iStartIN; /* Start of RHS of IN operator in z[] */ - int nParenAtIN; /* Value of nParent at start of RHS of IN operator */ - u32 j; /* Bytes of normalized SQL generated so far */ - sqlite3_str *pStr; /* The normalized SQL string under construction */ - - db = sqlite3VdbeDb(pVdbe); - tokenType = -1; - nParen = iStartIN = nParenAtIN = 0; - pStr = sqlite3_str_new(db); - assert( pStr!=0 ); /* sqlite3_str_new() never returns NULL */ - for(i=0; zSql[i] && pStr->accError==0; i+=n){ - if( tokenType!=TK_SPACE ){ - prevType = tokenType; - } - n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType); - if( NEVER(n<=0) ) break; - switch( tokenType ){ - case TK_SPACE: { - break; - } - case TK_NULL: { - if( prevType==TK_IS || prevType==TK_NOT ){ - sqlite3_str_append(pStr, " NULL", 5); - break; - } - /* Fall through */ - } - case TK_STRING: - case TK_INTEGER: - case TK_FLOAT: - case TK_VARIABLE: - case TK_BLOB: { - sqlite3_str_append(pStr, "?", 1); - break; - } - case TK_LP: { - nParen++; - if( prevType==TK_IN ){ - iStartIN = pStr->nChar; - nParenAtIN = nParen; - } - sqlite3_str_append(pStr, "(", 1); - break; - } - case TK_RP: { - if( iStartIN>0 && nParen==nParenAtIN ){ - assert( pStr->nChar>=(u32)iStartIN ); - pStr->nChar = iStartIN+1; - sqlite3_str_append(pStr, "?,?,?", 5); - iStartIN = 0; - } - nParen--; - sqlite3_str_append(pStr, ")", 1); - break; - } - case TK_ID: { - iStartIN = 0; - j = pStr->nChar; - if( sqlite3Isquote(zSql[i]) ){ - char *zId = sqlite3DbStrNDup(db, zSql+i, n); - int nId; - int eType = 0; - if( zId==0 ) break; - sqlite3Dequote(zId); - if( zSql[i]=='"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){ - sqlite3_str_append(pStr, "?", 1); - sqlite3DbFree(db, zId); - break; - } - nId = sqlite3Strlen30(zId); - if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){ - addSpaceSeparator(pStr); - sqlite3_str_append(pStr, zId, nId); - }else{ - sqlite3_str_appendf(pStr, "\"%w\"", zId); - } - sqlite3DbFree(db, zId); - }else{ - addSpaceSeparator(pStr); - sqlite3_str_append(pStr, zSql+i, n); - } - while( jnChar ){ - pStr->zText[j] = sqlite3Tolower(pStr->zText[j]); - j++; - } - break; - } - case TK_SELECT: { - iStartIN = 0; - /* fall through */ - } - default: { - if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr); - j = pStr->nChar; - sqlite3_str_append(pStr, zSql+i, n); - while( jnChar ){ - pStr->zText[j] = sqlite3Toupper(pStr->zText[j]); - j++; - } - break; - } - } - } - if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, ";", 1); - return sqlite3_str_finish(pStr); -} -#endif /* SQLITE_ENABLE_NORMALIZE */ - -/************** End of tokenize.c ********************************************/ -/************** Begin file complete.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. -** -************************************************************************* -** An tokenizer for SQL -** -** This file contains C code that implements the sqlite3_complete() API. -** This code used to be part of the tokenizer.c source file. But by -** separating it out, the code will be automatically omitted from -** static links that do not use it. -*/ -/* #include "sqliteInt.h" */ -#ifndef SQLITE_OMIT_COMPLETE - -/* -** This is defined in tokenize.c. We just have to import the definition. -*/ -#ifndef SQLITE_AMALGAMATION -#ifdef SQLITE_ASCII -#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) -#endif -#ifdef SQLITE_EBCDIC -SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; -#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) -#endif -#endif /* SQLITE_AMALGAMATION */ - - -/* -** Token types used by the sqlite3_complete() routine. See the header -** comments on that procedure for additional information. -*/ -#define tkSEMI 0 -#define tkWS 1 -#define tkOTHER 2 -#ifndef SQLITE_OMIT_TRIGGER -#define tkEXPLAIN 3 -#define tkCREATE 4 -#define tkTEMP 5 -#define tkTRIGGER 6 -#define tkEND 7 -#endif - -/* -** Return TRUE if the given SQL string ends in a semicolon. -** -** Special handling is require for CREATE TRIGGER statements. -** Whenever the CREATE TRIGGER keywords are seen, the statement -** must end with ";END;". -** -** This implementation uses a state machine with 8 states: -** -** (0) INVALID We have not yet seen a non-whitespace character. -** -** (1) START At the beginning or end of an SQL statement. This routine -** returns 1 if it ends in the START state and 0 if it ends -** in any other state. -** -** (2) NORMAL We are in the middle of statement which ends with a single -** semicolon. -** -** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of -** a statement. -** -** (4) CREATE The keyword CREATE has been seen at the beginning of a -** statement, possibly preceded by EXPLAIN and/or followed by -** TEMP or TEMPORARY -** -** (5) TRIGGER We are in the middle of a trigger definition that must be -** ended by a semicolon, the keyword END, and another semicolon. -** -** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at -** the end of a trigger definition. -** -** (7) END We've seen the ";END" of the ";END;" that occurs at the end -** of a trigger definition. -** -** Transitions between states above are determined by tokens extracted -** from the input. The following tokens are significant: -** -** (0) tkSEMI A semicolon. -** (1) tkWS Whitespace. -** (2) tkOTHER Any other SQL token. -** (3) tkEXPLAIN The "explain" keyword. -** (4) tkCREATE The "create" keyword. -** (5) tkTEMP The "temp" or "temporary" keyword. -** (6) tkTRIGGER The "trigger" keyword. -** (7) tkEND The "end" keyword. -** -** Whitespace never causes a state transition and is always ignored. -** This means that a SQL string of all whitespace is invalid. -** -** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed -** to recognize the end of a trigger can be omitted. All we have to do -** is look for a semicolon that is not part of an string or comment. -*/ -SQLITE_API int sqlite3_complete(const char *zSql){ - u8 state = 0; /* Current state, using numbers defined in header comment */ - u8 token; /* Value of the next token */ - -#ifndef SQLITE_OMIT_TRIGGER - /* A complex statement machine used to detect the end of a CREATE TRIGGER - ** statement. This is the normal case. - */ - static const u8 trans[8][8] = { - /* Token: */ - /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ - /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, - /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, }, - /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, }, - /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, }, - /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, }, - /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, }, - /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, }, - /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, }, - }; -#else - /* If triggers are not supported by this compile then the statement machine - ** used to detect the end of a statement is much simpler - */ - static const u8 trans[3][3] = { - /* Token: */ - /* State: ** SEMI WS OTHER */ - /* 0 INVALID: */ { 1, 0, 2, }, - /* 1 START: */ { 1, 1, 2, }, - /* 2 NORMAL: */ { 1, 2, 2, }, - }; -#endif /* SQLITE_OMIT_TRIGGER */ - -#ifdef SQLITE_ENABLE_API_ARMOR - if( zSql==0 ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - - while( *zSql ){ - switch( *zSql ){ - case ';': { /* A semicolon */ - token = tkSEMI; - break; - } - case ' ': - case '\r': - case '\t': - case '\n': - case '\f': { /* White space is ignored */ - token = tkWS; - break; - } - case '/': { /* C-style comments */ - if( zSql[1]!='*' ){ - token = tkOTHER; - break; - } - zSql += 2; - while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; } - if( zSql[0]==0 ) return 0; - zSql++; - token = tkWS; - break; - } - case '-': { /* SQL-style comments from "--" to end of line */ - if( zSql[1]!='-' ){ - token = tkOTHER; - break; - } - while( *zSql && *zSql!='\n' ){ zSql++; } - if( *zSql==0 ) return state==1; - token = tkWS; - break; - } - case '[': { /* Microsoft-style identifiers in [...] */ - zSql++; - while( *zSql && *zSql!=']' ){ zSql++; } - if( *zSql==0 ) return 0; - token = tkOTHER; - break; - } - case '`': /* Grave-accent quoted symbols used by MySQL */ - case '"': /* single- and double-quoted strings */ - case '\'': { - int c = *zSql; - zSql++; - while( *zSql && *zSql!=c ){ zSql++; } - if( *zSql==0 ) return 0; - token = tkOTHER; - break; - } - default: { -#ifdef SQLITE_EBCDIC - unsigned char c; -#endif - if( IdChar((u8)*zSql) ){ - /* Keywords and unquoted identifiers */ - int nId; - for(nId=1; IdChar(zSql[nId]); nId++){} -#ifdef SQLITE_OMIT_TRIGGER - token = tkOTHER; -#else - switch( *zSql ){ - case 'c': case 'C': { - if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){ - token = tkCREATE; - }else{ - token = tkOTHER; - } - break; - } - case 't': case 'T': { - if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){ - token = tkTRIGGER; - }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){ - token = tkTEMP; - }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){ - token = tkTEMP; - }else{ - token = tkOTHER; - } - break; - } - case 'e': case 'E': { - if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){ - token = tkEND; - }else -#ifndef SQLITE_OMIT_EXPLAIN - if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){ - token = tkEXPLAIN; - }else -#endif - { - token = tkOTHER; - } - break; - } - default: { - token = tkOTHER; - break; - } - } -#endif /* SQLITE_OMIT_TRIGGER */ - zSql += nId-1; - }else{ - /* Operators and special symbols */ - token = tkOTHER; - } - break; - } - } - state = trans[state][token]; - zSql++; - } - return state==1; -} - -#ifndef SQLITE_OMIT_UTF16 -/* -** This routine is the same as the sqlite3_complete() routine described -** above, except that the parameter is required to be UTF-16 encoded, not -** UTF-8. -*/ -SQLITE_API int sqlite3_complete16(const void *zSql){ - sqlite3_value *pVal; - char const *zSql8; - int rc; - -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ) return rc; -#endif - pVal = sqlite3ValueNew(0); - sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); - zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); - if( zSql8 ){ - rc = sqlite3_complete(zSql8); - }else{ - rc = SQLITE_NOMEM_BKPT; - } - sqlite3ValueFree(pVal); - return rc & 0xff; -} -#endif /* SQLITE_OMIT_UTF16 */ -#endif /* SQLITE_OMIT_COMPLETE */ - -/************** End of complete.c ********************************************/ -/************** Begin file main.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. -** -************************************************************************* -** Main file for the SQLite library. The routines in this file -** implement the programmer interface to the library. Routines in -** other files are for internal use by SQLite and should not be -** accessed by users of the library. -*/ -/* #include "sqliteInt.h" */ - -#ifdef SQLITE_ENABLE_FTS3 -/************** Include fts3.h in the middle of main.c ***********************/ -/************** Begin file fts3.h ********************************************/ -/* -** 2006 Oct 10 -** -** 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 is used by programs that want to link against the -** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. -*/ -/* #include "sqlite3.h" */ - -#if 0 -extern "C" { -#endif /* __cplusplus */ - -SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); - -#if 0 -} /* extern "C" */ -#endif /* __cplusplus */ - -/************** End of fts3.h ************************************************/ -/************** Continuing where we left off in main.c ***********************/ -#endif -#ifdef SQLITE_ENABLE_RTREE -/************** Include rtree.h in the middle of main.c **********************/ -/************** Begin file rtree.h *******************************************/ -/* -** 2008 May 26 -** -** 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 is used by programs that want to link against the -** RTREE library. All it does is declare the sqlite3RtreeInit() interface. -*/ -/* #include "sqlite3.h" */ - -#ifdef SQLITE_OMIT_VIRTUALTABLE -# undef SQLITE_ENABLE_RTREE -#endif - -#if 0 -extern "C" { -#endif /* __cplusplus */ - -SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); - -#if 0 -} /* extern "C" */ -#endif /* __cplusplus */ - -/************** End of rtree.h ***********************************************/ -/************** Continuing where we left off in main.c ***********************/ -#endif -#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS) -/************** Include sqliteicu.h in the middle of main.c ******************/ -/************** Begin file sqliteicu.h ***************************************/ -/* -** 2008 May 26 -** -** 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 is used by programs that want to link against the -** ICU extension. All it does is declare the sqlite3IcuInit() interface. -*/ -/* #include "sqlite3.h" */ - -#if 0 -extern "C" { -#endif /* __cplusplus */ - -SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db); - -#if 0 -} /* extern "C" */ -#endif /* __cplusplus */ - -/************** End of sqliteicu.h *******************************************/ -/************** Continuing where we left off in main.c ***********************/ -#endif - -/* -** This is an extension initializer that is a no-op and always -** succeeds, except that it fails if the fault-simulation is set -** to 500. -*/ -static int sqlite3TestExtInit(sqlite3 *db){ - (void)db; - return sqlite3FaultSim(500); -} - - -/* -** Forward declarations of external module initializer functions -** for modules that need them. -*/ -#ifdef SQLITE_ENABLE_FTS1 -SQLITE_PRIVATE int sqlite3Fts1Init(sqlite3*); -#endif -#ifdef SQLITE_ENABLE_FTS2 -SQLITE_PRIVATE int sqlite3Fts2Init(sqlite3*); -#endif -#ifdef SQLITE_ENABLE_FTS5 -SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*); -#endif -#ifdef SQLITE_ENABLE_JSON1 -SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*); -#endif -#ifdef SQLITE_ENABLE_STMTVTAB -SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*); -#endif - -/* -** An array of pointers to extension initializer functions for -** built-in extensions. -*/ -static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = { -#ifdef SQLITE_ENABLE_FTS1 - sqlite3Fts1Init, -#endif -#ifdef SQLITE_ENABLE_FTS2 - sqlite3Fts2Init, -#endif -#ifdef SQLITE_ENABLE_FTS3 - sqlite3Fts3Init, -#endif -#ifdef SQLITE_ENABLE_FTS5 - sqlite3Fts5Init, -#endif -#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS) - sqlite3IcuInit, -#endif -#ifdef SQLITE_ENABLE_RTREE - sqlite3RtreeInit, -#endif -#ifdef SQLITE_ENABLE_DBPAGE_VTAB - sqlite3DbpageRegister, -#endif -#ifdef SQLITE_ENABLE_DBSTAT_VTAB - sqlite3DbstatRegister, -#endif - sqlite3TestExtInit, -#ifdef SQLITE_ENABLE_JSON1 - sqlite3Json1Init, -#endif -#ifdef SQLITE_ENABLE_STMTVTAB - sqlite3StmtVtabInit, -#endif -#ifdef SQLITE_ENABLE_BYTECODE_VTAB - sqlite3VdbeBytecodeVtabInit, -#endif -}; - -#ifndef SQLITE_AMALGAMATION -/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant -** contains the text of SQLITE_VERSION macro. -*/ -SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; -#endif - -/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns -** a pointer to the to the sqlite3_version[] string constant. -*/ -SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; } - -/* IMPLEMENTATION-OF: R-25063-23286 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. -*/ -/* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */ - -/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function -** returns an integer equal to SQLITE_VERSION_NUMBER. -*/ -SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } - -/* IMPLEMENTATION-OF: R-20790-14025 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_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } - -/* -** When compiling the test fixture or with debugging enabled (on Win32), -** this variable being set to non-zero will cause OSTRACE macros to emit -** extra diagnostic information. -*/ -#ifdef SQLITE_HAVE_OS_TRACE -# ifndef SQLITE_DEBUG_OS_TRACE -# define SQLITE_DEBUG_OS_TRACE 0 -# endif - int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE; -#endif - -#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) -/* -** If the following function pointer is not NULL and if -** SQLITE_ENABLE_IOTRACE is enabled, then messages describing -** I/O active are written using this function. These messages -** are intended for debugging activity only. -*/ -SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0; -#endif - -/* -** If the following global variable points to a string which is the -** name of a directory, then that directory will be used to store -** temporary files. -** -** See also the "PRAGMA temp_store_directory" SQL command. -*/ -SQLITE_API char *sqlite3_temp_directory = 0; - -/* -** If the following global variable points to a string which is the -** name of a directory, then that directory will be used to store -** all database files specified with a relative pathname. -** -** See also the "PRAGMA data_store_directory" SQL command. -*/ -SQLITE_API char *sqlite3_data_directory = 0; - -/* -** Initialize SQLite. -** -** This routine must be called to initialize the memory allocation, -** VFS, and mutex subsystems prior to doing any serious work with -** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT -** this routine will be called automatically by key routines such as -** sqlite3_open(). -** -** This routine is a no-op except on its very first call for the process, -** or for the first call after a call to sqlite3_shutdown. -** -** The first thread to call this routine runs the initialization to -** completion. If subsequent threads call this routine before the first -** thread has finished the initialization process, then the subsequent -** threads must block until the first thread finishes with the initialization. -** -** The first thread might call this routine recursively. Recursive -** calls to this routine should not block, of course. Otherwise the -** initialization process would never complete. -** -** Let X be the first thread to enter this routine. Let Y be some other -** thread. Then while the initial invocation of this routine by X is -** incomplete, it is required that: -** -** * Calls to this routine from Y must block until the outer-most -** call by X completes. -** -** * Recursive calls to this routine from thread X return immediately -** without blocking. -*/ -SQLITE_API int sqlite3_initialize(void){ - MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */ - int rc; /* Result code */ -#ifdef SQLITE_EXTRA_INIT - int bRunExtraInit = 0; /* Extra initialization needed */ -#endif - -#ifdef SQLITE_OMIT_WSD - rc = sqlite3_wsd_init(4096, 24); - if( rc!=SQLITE_OK ){ - return rc; - } -#endif - - /* If the following assert() fails on some obscure processor/compiler - ** combination, the work-around is to set the correct pointer - ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */ - assert( SQLITE_PTRSIZE==sizeof(char*) ); - - /* If SQLite is already completely initialized, then this call - ** to sqlite3_initialize() should be a no-op. But the initialization - ** must be complete. So isInit must not be set until the very end - ** of this routine. - */ - if( sqlite3GlobalConfig.isInit ){ - sqlite3MemoryBarrier(); - return SQLITE_OK; - } - - /* Make sure the mutex subsystem is initialized. If unable to - ** initialize the mutex subsystem, return early with the error. - ** If the system is so sick that we are unable to allocate a mutex, - ** there is not much SQLite is going to be able to do. - ** - ** The mutex subsystem must take care of serializing its own - ** initialization. - */ - rc = sqlite3MutexInit(); - if( rc ) return rc; - - /* Initialize the malloc() system and the recursive pInitMutex mutex. - ** This operation is protected by the STATIC_MAIN mutex. Note that - ** MutexAlloc() is called for a static mutex prior to initializing the - ** malloc subsystem - this implies that the allocation of a static - ** mutex must not require support from the malloc subsystem. - */ - MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); ) - sqlite3_mutex_enter(pMainMtx); - sqlite3GlobalConfig.isMutexInit = 1; - if( !sqlite3GlobalConfig.isMallocInit ){ - rc = sqlite3MallocInit(); - } - if( rc==SQLITE_OK ){ - sqlite3GlobalConfig.isMallocInit = 1; - if( !sqlite3GlobalConfig.pInitMutex ){ - sqlite3GlobalConfig.pInitMutex = - sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); - if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){ - rc = SQLITE_NOMEM_BKPT; - } - } - } - if( rc==SQLITE_OK ){ - sqlite3GlobalConfig.nRefInitMutex++; - } - sqlite3_mutex_leave(pMainMtx); - - /* If rc is not SQLITE_OK at this point, then either the malloc - ** subsystem could not be initialized or the system failed to allocate - ** the pInitMutex mutex. Return an error in either case. */ - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Do the rest of the initialization under the recursive mutex so - ** that we will be able to handle recursive calls into - ** sqlite3_initialize(). The recursive calls normally come through - ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other - ** recursive calls might also be possible. - ** - ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls - ** to the xInit method, so the xInit method need not be threadsafe. - ** - ** The following mutex is what serializes access to the appdef pcache xInit - ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the - ** call to sqlite3PcacheInitialize(). - */ - sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); - if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){ - sqlite3GlobalConfig.inProgress = 1; -#ifdef SQLITE_ENABLE_SQLLOG - { - extern void sqlite3_init_sqllog(void); - sqlite3_init_sqllog(); - } -#endif - memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions)); - sqlite3RegisterBuiltinFunctions(); - if( sqlite3GlobalConfig.isPCacheInit==0 ){ - rc = sqlite3PcacheInitialize(); - } - if( rc==SQLITE_OK ){ - sqlite3GlobalConfig.isPCacheInit = 1; - rc = sqlite3OsInit(); - } -#ifdef SQLITE_ENABLE_DESERIALIZE - if( rc==SQLITE_OK ){ - rc = sqlite3MemdbInit(); - } -#endif - if( rc==SQLITE_OK ){ - sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, - sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); - sqlite3MemoryBarrier(); - sqlite3GlobalConfig.isInit = 1; -#ifdef SQLITE_EXTRA_INIT - bRunExtraInit = 1; -#endif - } - sqlite3GlobalConfig.inProgress = 0; - } - sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex); - - /* Go back under the static mutex and clean up the recursive - ** mutex to prevent a resource leak. - */ - sqlite3_mutex_enter(pMainMtx); - sqlite3GlobalConfig.nRefInitMutex--; - if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ - assert( sqlite3GlobalConfig.nRefInitMutex==0 ); - sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); - sqlite3GlobalConfig.pInitMutex = 0; - } - sqlite3_mutex_leave(pMainMtx); - - /* The following is just a sanity check to make sure SQLite has - ** been compiled correctly. It is important to run this code, but - ** we don't want to run it too often and soak up CPU cycles for no - ** reason. So we run it once during initialization. - */ -#ifndef NDEBUG -#ifndef SQLITE_OMIT_FLOATING_POINT - /* This section of code's only "output" is via assert() statements. */ - if( rc==SQLITE_OK ){ - u64 x = (((u64)1)<<63)-1; - double y; - assert(sizeof(x)==8); - assert(sizeof(x)==sizeof(y)); - memcpy(&y, &x, 8); - assert( sqlite3IsNaN(y) ); - } -#endif -#endif - - /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT - ** compile-time option. - */ -#ifdef SQLITE_EXTRA_INIT - if( bRunExtraInit ){ - int SQLITE_EXTRA_INIT(const char*); - rc = SQLITE_EXTRA_INIT(0); - } -#endif - - return rc; -} - -/* -** Undo the effects of sqlite3_initialize(). Must not be called while -** there are outstanding database connections or memory allocations or -** while any part of SQLite is otherwise in use in any thread. This -** routine is not threadsafe. But it is safe to invoke this routine -** on when SQLite is already shut down. If SQLite is already shut down -** when this routine is invoked, then this routine is a harmless no-op. -*/ -SQLITE_API int sqlite3_shutdown(void){ -#ifdef SQLITE_OMIT_WSD - int rc = sqlite3_wsd_init(4096, 24); - if( rc!=SQLITE_OK ){ - return rc; - } -#endif - - if( sqlite3GlobalConfig.isInit ){ -#ifdef SQLITE_EXTRA_SHUTDOWN - void SQLITE_EXTRA_SHUTDOWN(void); - SQLITE_EXTRA_SHUTDOWN(); -#endif - sqlite3_os_end(); - sqlite3_reset_auto_extension(); - sqlite3GlobalConfig.isInit = 0; - } - if( sqlite3GlobalConfig.isPCacheInit ){ - sqlite3PcacheShutdown(); - sqlite3GlobalConfig.isPCacheInit = 0; - } - if( sqlite3GlobalConfig.isMallocInit ){ - sqlite3MallocEnd(); - sqlite3GlobalConfig.isMallocInit = 0; - -#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES - /* The heap subsystem has now been shutdown and these values are supposed - ** to be NULL or point to memory that was obtained from sqlite3_malloc(), - ** which would rely on that heap subsystem; therefore, make sure these - ** values cannot refer to heap memory that was just invalidated when the - ** heap subsystem was shutdown. This is only done if the current call to - ** this function resulted in the heap subsystem actually being shutdown. - */ - sqlite3_data_directory = 0; - sqlite3_temp_directory = 0; -#endif - } - if( sqlite3GlobalConfig.isMutexInit ){ - sqlite3MutexEnd(); - sqlite3GlobalConfig.isMutexInit = 0; - } - - return SQLITE_OK; -} - -/* -** This API allows applications to modify the global configuration of -** the SQLite library at run-time. -** -** This routine should only be called when there are no outstanding -** database connections or memory allocations. This routine is not -** threadsafe. Failure to heed these warnings can lead to unpredictable -** behavior. -*/ -SQLITE_API int sqlite3_config(int op, ...){ - va_list ap; - int rc = SQLITE_OK; - - /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while - ** the SQLite library is in use. */ - if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT; - - va_start(ap, op); - switch( op ){ - - /* Mutex configuration options are only available in a threadsafe - ** compile. - */ -#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */ - case SQLITE_CONFIG_SINGLETHREAD: { - /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to - ** Single-thread. */ - sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */ - sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ - break; - } -#endif -#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */ - case SQLITE_CONFIG_MULTITHREAD: { - /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to - ** Multi-thread. */ - sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ - sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */ - break; - } -#endif -#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */ - case SQLITE_CONFIG_SERIALIZED: { - /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to - ** Serialized. */ - sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */ - sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */ - break; - } -#endif -#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */ - case SQLITE_CONFIG_MUTEX: { - /* Specify an alternative mutex implementation */ - sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*); - break; - } -#endif -#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */ - case SQLITE_CONFIG_GETMUTEX: { - /* Retrieve the current mutex implementation */ - *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex; - break; - } -#endif - - case SQLITE_CONFIG_MALLOC: { - /* EVIDENCE-OF: R-55594-21030 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. */ - sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*); - break; - } - case SQLITE_CONFIG_GETMALLOC: { - /* EVIDENCE-OF: R-51213-46414 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. */ - if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault(); - *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m; - break; - } - case SQLITE_CONFIG_MEMSTATUS: { - /* EVIDENCE-OF: R-61275-35157 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. */ - sqlite3GlobalConfig.bMemstat = va_arg(ap, int); - break; - } - case SQLITE_CONFIG_SMALL_MALLOC: { - sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int); - break; - } - case SQLITE_CONFIG_PAGECACHE: { - /* EVIDENCE-OF: R-18761-36601 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). */ - sqlite3GlobalConfig.pPage = va_arg(ap, void*); - sqlite3GlobalConfig.szPage = va_arg(ap, int); - sqlite3GlobalConfig.nPage = va_arg(ap, int); - break; - } - case SQLITE_CONFIG_PCACHE_HDRSZ: { - /* EVIDENCE-OF: R-39100-27317 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. */ - *va_arg(ap, int*) = - sqlite3HeaderSizeBtree() + - sqlite3HeaderSizePcache() + - sqlite3HeaderSizePcache1(); - break; - } - - case SQLITE_CONFIG_PCACHE: { - /* no-op */ - break; - } - case SQLITE_CONFIG_GETPCACHE: { - /* now an error */ - rc = SQLITE_ERROR; - break; - } - - case SQLITE_CONFIG_PCACHE2: { - /* EVIDENCE-OF: R-63325-48378 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. */ - sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*); - break; - } - case SQLITE_CONFIG_GETPCACHE2: { - /* EVIDENCE-OF: R-22035-46182 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. */ - if( sqlite3GlobalConfig.pcache2.xInit==0 ){ - sqlite3PCacheSetDefault(); - } - *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2; - break; - } - -/* EVIDENCE-OF: R-06626-12911 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. */ -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) - case SQLITE_CONFIG_HEAP: { - /* EVIDENCE-OF: R-19854-42126 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. - */ - sqlite3GlobalConfig.pHeap = va_arg(ap, void*); - sqlite3GlobalConfig.nHeap = va_arg(ap, int); - sqlite3GlobalConfig.mnReq = va_arg(ap, int); - - if( sqlite3GlobalConfig.mnReq<1 ){ - sqlite3GlobalConfig.mnReq = 1; - }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){ - /* cap min request size at 2^12 */ - sqlite3GlobalConfig.mnReq = (1<<12); - } - - if( sqlite3GlobalConfig.pHeap==0 ){ - /* EVIDENCE-OF: R-49920-60189 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. - ** - ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to - ** revert to its default implementation when sqlite3_initialize() is run - */ - memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m)); - }else{ - /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the - ** alternative memory allocator is engaged to handle all of SQLites - ** memory allocation needs. */ -#ifdef SQLITE_ENABLE_MEMSYS3 - sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3(); -#endif -#ifdef SQLITE_ENABLE_MEMSYS5 - sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5(); -#endif - } - break; - } -#endif - - case SQLITE_CONFIG_LOOKASIDE: { - sqlite3GlobalConfig.szLookaside = va_arg(ap, int); - sqlite3GlobalConfig.nLookaside = va_arg(ap, int); - break; - } - - /* Record a pointer to the logger function and its first argument. - ** The default is NULL. Logging is disabled if the function pointer is - ** NULL. - */ - case SQLITE_CONFIG_LOG: { - /* MSVC is picky about pulling func ptrs from va lists. - ** http://support.microsoft.com/kb/47961 - ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*)); - */ - typedef void(*LOGFUNC_t)(void*,int,const char*); - sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t); - sqlite3GlobalConfig.pLogArg = va_arg(ap, void*); - break; - } - - /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames - ** can be changed at start-time using the - ** sqlite3_config(SQLITE_CONFIG_URI,1) or - ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls. - */ - case SQLITE_CONFIG_URI: { - /* EVIDENCE-OF: R-25451-61125 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. */ - sqlite3GlobalConfig.bOpenUri = va_arg(ap, int); - break; - } - - case SQLITE_CONFIG_COVERING_INDEX_SCAN: { - /* EVIDENCE-OF: R-36592-02772 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. */ - sqlite3GlobalConfig.bUseCis = va_arg(ap, int); - break; - } - -#ifdef SQLITE_ENABLE_SQLLOG - case SQLITE_CONFIG_SQLLOG: { - typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int); - sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t); - sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *); - break; - } -#endif - - case SQLITE_CONFIG_MMAP_SIZE: { - /* EVIDENCE-OF: R-58063-38258 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. */ - sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64); - sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64); - /* EVIDENCE-OF: R-53367-43190 If either argument to this option is - ** negative, then that argument is changed to its compile-time default. - ** - ** EVIDENCE-OF: R-34993-45031 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( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){ - mxMmap = SQLITE_MAX_MMAP_SIZE; - } - if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE; - if( szMmap>mxMmap) szMmap = mxMmap; - sqlite3GlobalConfig.mxMmap = mxMmap; - sqlite3GlobalConfig.szMmap = szMmap; - break; - } - -#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */ - case SQLITE_CONFIG_WIN32_HEAPSIZE: { - /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit - ** unsigned integer value that specifies the maximum size of the created - ** heap. */ - sqlite3GlobalConfig.nHeap = va_arg(ap, int); - break; - } -#endif - - case SQLITE_CONFIG_PMASZ: { - sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int); - break; - } - - case SQLITE_CONFIG_STMTJRNL_SPILL: { - sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int); - break; - } - -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - case SQLITE_CONFIG_SORTERREF_SIZE: { - int iVal = va_arg(ap, int); - if( iVal<0 ){ - iVal = SQLITE_DEFAULT_SORTERREF_SIZE; - } - sqlite3GlobalConfig.szSorterRef = (u32)iVal; - break; - } -#endif /* SQLITE_ENABLE_SORTER_REFERENCES */ - -#ifdef SQLITE_ENABLE_DESERIALIZE - case SQLITE_CONFIG_MEMDB_MAXSIZE: { - sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64); - break; - } -#endif /* SQLITE_ENABLE_DESERIALIZE */ - - default: { - rc = SQLITE_ERROR; - break; - } - } - va_end(ap); - return rc; -} - -/* -** Set up the lookaside buffers for a database connection. -** Return SQLITE_OK on success. -** If lookaside is already active, return SQLITE_BUSY. -** -** The sz parameter is the number of bytes in each lookaside slot. -** The cnt parameter is the number of slots. If pStart is NULL the -** space for the lookaside memory is obtained from sqlite3_malloc(). -** If pStart is not NULL then it is sz*cnt bytes of memory to use for -** the lookaside memory. -*/ -static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ -#ifndef SQLITE_OMIT_LOOKASIDE - void *pStart; - sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt; - int nBig; /* Number of full-size slots */ - int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */ - - if( sqlite3LookasideUsed(db,0)>0 ){ - return SQLITE_BUSY; - } - /* Free any existing lookaside buffer for this handle before - ** allocating a new one so we don't have to have space for - ** both at the same time. - */ - if( db->lookaside.bMalloced ){ - sqlite3_free(db->lookaside.pStart); - } - /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger - ** than a pointer to be useful. - */ - sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ - if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; - if( cnt<0 ) cnt = 0; - if( sz==0 || cnt==0 ){ - sz = 0; - pStart = 0; - }else if( pBuf==0 ){ - sqlite3BeginBenignMalloc(); - pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */ - sqlite3EndBenignMalloc(); - if( pStart ) szAlloc = sqlite3MallocSize(pStart); - }else{ - pStart = pBuf; - } -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - if( sz>=LOOKASIDE_SMALL*3 ){ - nBig = szAlloc/(3*LOOKASIDE_SMALL+sz); - nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL; - }else if( sz>=LOOKASIDE_SMALL*2 ){ - nBig = szAlloc/(LOOKASIDE_SMALL+sz); - nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL; - }else -#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ - if( sz>0 ){ - nBig = szAlloc/sz; - nSm = 0; - }else{ - nBig = nSm = 0; - } - db->lookaside.pStart = pStart; - db->lookaside.pInit = 0; - db->lookaside.pFree = 0; - db->lookaside.sz = (u16)sz; - db->lookaside.szTrue = (u16)sz; - if( pStart ){ - int i; - LookasideSlot *p; - assert( sz > (int)sizeof(LookasideSlot*) ); - p = (LookasideSlot*)pStart; - for(i=0; ipNext = db->lookaside.pInit; - db->lookaside.pInit = p; - p = (LookasideSlot*)&((u8*)p)[sz]; - } -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - db->lookaside.pSmallInit = 0; - db->lookaside.pSmallFree = 0; - db->lookaside.pMiddle = p; - for(i=0; ipNext = db->lookaside.pSmallInit; - db->lookaside.pSmallInit = p; - p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL]; - } -#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ - assert( ((uptr)p)<=szAlloc + (uptr)pStart ); - db->lookaside.pEnd = p; - db->lookaside.bDisable = 0; - db->lookaside.bMalloced = pBuf==0 ?1:0; - db->lookaside.nSlot = nBig+nSm; - }else{ - db->lookaside.pStart = db; -#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE - db->lookaside.pSmallInit = 0; - db->lookaside.pSmallFree = 0; - db->lookaside.pMiddle = db; -#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ - db->lookaside.pEnd = db; - db->lookaside.bDisable = 1; - db->lookaside.sz = 0; - db->lookaside.bMalloced = 0; - db->lookaside.nSlot = 0; - } - assert( sqlite3LookasideUsed(db,0)==0 ); -#endif /* SQLITE_OMIT_LOOKASIDE */ - return SQLITE_OK; -} - -/* -** Return the mutex associated with a database connection. -*/ -SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - return db->mutex; -} - -/* -** Free up as much memory as we can from the given database -** connection. -*/ -SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){ - int i; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); - for(i=0; inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - Pager *pPager = sqlite3BtreePager(pBt); - sqlite3PagerShrink(pPager); - } - } - sqlite3BtreeLeaveAll(db); - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -/* -** Flush any dirty pages in the pager-cache for any attached database -** to disk. -*/ -SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){ - int i; - int rc = SQLITE_OK; - int bSeenBusy = 0; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); - for(i=0; rc==SQLITE_OK && inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt && sqlite3BtreeIsInTrans(pBt) ){ - Pager *pPager = sqlite3BtreePager(pBt); - rc = sqlite3PagerFlush(pPager); - if( rc==SQLITE_BUSY ){ - bSeenBusy = 1; - rc = SQLITE_OK; - } - } - } - sqlite3BtreeLeaveAll(db); - sqlite3_mutex_leave(db->mutex); - return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc); -} - -/* -** Configuration settings for an individual database connection -*/ -SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ - va_list ap; - int rc; - va_start(ap, op); - switch( op ){ - case SQLITE_DBCONFIG_MAINDBNAME: { - /* IMP: R-06824-28531 */ - /* IMP: R-36257-52125 */ - db->aDb[0].zDbSName = va_arg(ap,char*); - rc = SQLITE_OK; - break; - } - case SQLITE_DBCONFIG_LOOKASIDE: { - void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */ - int sz = va_arg(ap, int); /* IMP: R-47871-25994 */ - int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */ - rc = setupLookaside(db, pBuf, sz, cnt); - break; - } - default: { - static const struct { - int op; /* The opcode */ - u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ - } aFlagOp[] = { - { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, - { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, - { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView }, - { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer }, - { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension }, - { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose }, - { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG }, - { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP }, - { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase }, - { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive }, - { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema| - SQLITE_NoSchemaError }, - { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter }, - { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL }, - { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML }, - { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt }, - { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema }, - }; - unsigned int i; - rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ - for(i=0; iflags; - if( onoff>0 ){ - db->flags |= aFlagOp[i].mask; - }else if( onoff==0 ){ - db->flags &= ~(u64)aFlagOp[i].mask; - } - if( oldFlags!=db->flags ){ - sqlite3ExpirePreparedStatements(db, 0); - } - if( pRes ){ - *pRes = (db->flags & aFlagOp[i].mask)!=0; - } - rc = SQLITE_OK; - break; - } - } - break; - } - } - va_end(ap); - return rc; -} - -/* -** This is the default collating function named "BINARY" which is always -** available. -*/ -static int binCollFunc( - void *NotUsed, - int nKey1, const void *pKey1, - int nKey2, const void *pKey2 -){ - int rc, n; - UNUSED_PARAMETER(NotUsed); - n = nKey1xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 ); - return p==0 || p->xCmp==binCollFunc; -} - -/* -** Another built-in collating sequence: NOCASE. -** -** This collating sequence is intended to be used for "case independent -** comparison". SQLite's knowledge of upper and lower case equivalents -** extends only to the 26 characters used in the English language. -** -** At the moment there is only a UTF-8 implementation. -*/ -static int nocaseCollatingFunc( - void *NotUsed, - int nKey1, const void *pKey1, - int nKey2, const void *pKey2 -){ - int r = sqlite3StrNICmp( - (const char *)pKey1, (const char *)pKey2, (nKey1lastRowid; -} - -/* -** Set the value returned by the sqlite3_last_insert_rowid() API function. -*/ -SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return; - } -#endif - sqlite3_mutex_enter(db->mutex); - db->lastRowid = iRowid; - sqlite3_mutex_leave(db->mutex); -} - -/* -** Return the number of changes in the most recent call to sqlite3_exec(). -*/ -SQLITE_API int sqlite3_changes(sqlite3 *db){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - return db->nChange; -} - -/* -** Return the number of changes since the database handle was opened. -*/ -SQLITE_API int sqlite3_total_changes(sqlite3 *db){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - return db->nTotalChange; -} - -/* -** Close all open savepoints. This function only manipulates fields of the -** database handle object, it does not close any savepoints that may be open -** at the b-tree/pager level. -*/ -SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){ - while( db->pSavepoint ){ - Savepoint *pTmp = db->pSavepoint; - db->pSavepoint = pTmp->pNext; - sqlite3DbFree(db, pTmp); - } - db->nSavepoint = 0; - db->nStatement = 0; - db->isTransactionSavepoint = 0; -} - -/* -** Invoke the destructor function associated with FuncDef p, if any. Except, -** if this is not the last copy of the function, do not invoke it. Multiple -** copies of a single function are created when create_function() is called -** with SQLITE_ANY as the encoding. -*/ -static void functionDestroy(sqlite3 *db, FuncDef *p){ - FuncDestructor *pDestructor = p->u.pDestructor; - if( pDestructor ){ - pDestructor->nRef--; - if( pDestructor->nRef==0 ){ - pDestructor->xDestroy(pDestructor->pUserData); - sqlite3DbFree(db, pDestructor); - } - } -} - -/* -** Disconnect all sqlite3_vtab objects that belong to database connection -** db. This is called when db is being closed. -*/ -static void disconnectAllVtab(sqlite3 *db){ -#ifndef SQLITE_OMIT_VIRTUALTABLE - int i; - HashElem *p; - sqlite3BtreeEnterAll(db); - for(i=0; inDb; i++){ - Schema *pSchema = db->aDb[i].pSchema; - if( pSchema ){ - for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ - Table *pTab = (Table *)sqliteHashData(p); - if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab); - } - } - } - for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){ - Module *pMod = (Module *)sqliteHashData(p); - if( pMod->pEpoTab ){ - sqlite3VtabDisconnect(db, pMod->pEpoTab); - } - } - sqlite3VtabUnlockList(db); - sqlite3BtreeLeaveAll(db); -#else - UNUSED_PARAMETER(db); -#endif -} - -/* -** Return TRUE if database connection db has unfinalized prepared -** statements or unfinished sqlite3_backup objects. -*/ -static int connectionIsBusy(sqlite3 *db){ - int j; - assert( sqlite3_mutex_held(db->mutex) ); - if( db->pVdbe ) return 1; - for(j=0; jnDb; j++){ - Btree *pBt = db->aDb[j].pBt; - if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1; - } - return 0; -} - -/* -** Close an existing SQLite database -*/ -static int sqlite3Close(sqlite3 *db, int forceZombie){ - if( !db ){ - /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or - ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */ - return SQLITE_OK; - } - if( !sqlite3SafetyCheckSickOrOk(db) ){ - return SQLITE_MISUSE_BKPT; - } - sqlite3_mutex_enter(db->mutex); - if( db->mTrace & SQLITE_TRACE_CLOSE ){ - db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0); - } - - /* Force xDisconnect calls on all virtual tables */ - disconnectAllVtab(db); - - /* If a transaction is open, the disconnectAllVtab() call above - ** will not have called the xDisconnect() method on any virtual - ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback() - ** call will do so. We need to do this before the check for active - ** SQL statements below, as the v-table implementation may be storing - ** some prepared statements internally. - */ - sqlite3VtabRollback(db); - - /* Legacy behavior (sqlite3_close() behavior) is to return - ** SQLITE_BUSY if the connection can not be closed immediately. - */ - if( !forceZombie && connectionIsBusy(db) ){ - sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized " - "statements or unfinished backups"); - sqlite3_mutex_leave(db->mutex); - return SQLITE_BUSY; - } - -#ifdef SQLITE_ENABLE_SQLLOG - if( sqlite3GlobalConfig.xSqllog ){ - /* Closing the handle. Fourth parameter is passed the value 2. */ - sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2); - } -#endif - - /* Convert the connection into a zombie and then close it. - */ - db->magic = SQLITE_MAGIC_ZOMBIE; - sqlite3LeaveMutexAndCloseZombie(db); - return SQLITE_OK; -} - -/* -** Two variations on the public interface for closing a database -** connection. The sqlite3_close() version returns SQLITE_BUSY and -** leaves the connection option if there are unfinalized prepared -** statements or unfinished sqlite3_backups. The sqlite3_close_v2() -** version forces the connection to become a zombie if there are -** unclosed resources, and arranges for deallocation when the last -** prepare statement or sqlite3_backup closes. -*/ -SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); } -SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); } - - -/* -** Close the mutex on database connection db. -** -** Furthermore, if database connection db is a zombie (meaning that there -** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and -** every sqlite3_stmt has now been finalized and every sqlite3_backup has -** finished, then free all resources. -*/ -SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ - HashElem *i; /* Hash table iterator */ - int j; - - /* If there are outstanding sqlite3_stmt or sqlite3_backup objects - ** or if the connection has not yet been closed by sqlite3_close_v2(), - ** then just leave the mutex and return. - */ - if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){ - sqlite3_mutex_leave(db->mutex); - return; - } - - /* If we reach this point, it means that the database connection has - ** closed all sqlite3_stmt and sqlite3_backup objects and has been - ** passed to sqlite3_close (meaning that it is a zombie). Therefore, - ** go ahead and free all resources. - */ - - /* If a transaction is open, roll it back. This also ensures that if - ** any database schemas have been modified by an uncommitted transaction - ** they are reset. And that the required b-tree mutex is held to make - ** the pager rollback and schema reset an atomic operation. */ - sqlite3RollbackAll(db, SQLITE_OK); - - /* Free any outstanding Savepoint structures. */ - sqlite3CloseSavepoints(db); - - /* Close all database connections */ - for(j=0; jnDb; j++){ - struct Db *pDb = &db->aDb[j]; - if( pDb->pBt ){ - sqlite3BtreeClose(pDb->pBt); - pDb->pBt = 0; - if( j!=1 ){ - pDb->pSchema = 0; - } - } - } - /* Clear the TEMP schema separately and last */ - if( db->aDb[1].pSchema ){ - sqlite3SchemaClear(db->aDb[1].pSchema); - } - sqlite3VtabUnlockList(db); - - /* Free up the array of auxiliary databases */ - sqlite3CollapseDatabaseArray(db); - assert( db->nDb<=2 ); - assert( db->aDb==db->aDbStatic ); - - /* Tell the code in notify.c that the connection no longer holds any - ** locks and does not require any further unlock-notify callbacks. - */ - sqlite3ConnectionClosed(db); - - for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){ - FuncDef *pNext, *p; - p = sqliteHashData(i); - do{ - functionDestroy(db, p); - pNext = p->pNext; - sqlite3DbFree(db, p); - p = pNext; - }while( p ); - } - sqlite3HashClear(&db->aFunc); - for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){ - CollSeq *pColl = (CollSeq *)sqliteHashData(i); - /* Invoke any destructors registered for collation sequence user data. */ - for(j=0; j<3; j++){ - if( pColl[j].xDel ){ - pColl[j].xDel(pColl[j].pUser); - } - } - sqlite3DbFree(db, pColl); - } - sqlite3HashClear(&db->aCollSeq); -#ifndef SQLITE_OMIT_VIRTUALTABLE - for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){ - Module *pMod = (Module *)sqliteHashData(i); - sqlite3VtabEponymousTableClear(db, pMod); - sqlite3VtabModuleUnref(db, pMod); - } - sqlite3HashClear(&db->aModule); -#endif - - sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ - sqlite3ValueFree(db->pErr); - sqlite3CloseExtensions(db); -#if SQLITE_USER_AUTHENTICATION - sqlite3_free(db->auth.zAuthUser); - sqlite3_free(db->auth.zAuthPW); -#endif - - db->magic = SQLITE_MAGIC_ERROR; - - /* The temp-database schema is allocated differently from the other schema - ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()). - ** So it needs to be freed here. Todo: Why not roll the temp schema into - ** the same sqliteMalloc() as the one that allocates the database - ** structure? - */ - sqlite3DbFree(db, db->aDb[1].pSchema); - sqlite3_mutex_leave(db->mutex); - db->magic = SQLITE_MAGIC_CLOSED; - sqlite3_mutex_free(db->mutex); - assert( sqlite3LookasideUsed(db,0)==0 ); - if( db->lookaside.bMalloced ){ - sqlite3_free(db->lookaside.pStart); - } - sqlite3_free(db); -} - -/* -** Rollback all database files. If tripCode is not SQLITE_OK, then -** any write cursors are invalidated ("tripped" - as in "tripping a circuit -** breaker") and made to return tripCode if there are any further -** attempts to use that cursor. Read cursors remain open and valid -** but are "saved" in case the table pages are moved around. -*/ -SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){ - int i; - int inTrans = 0; - int schemaChange; - assert( sqlite3_mutex_held(db->mutex) ); - sqlite3BeginBenignMalloc(); - - /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). - ** This is important in case the transaction being rolled back has - ** modified the database schema. If the b-tree mutexes are not taken - ** here, then another shared-cache connection might sneak in between - ** the database rollback and schema reset, which can cause false - ** corruption reports in some cases. */ - sqlite3BtreeEnterAll(db); - schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0; - - for(i=0; inDb; i++){ - Btree *p = db->aDb[i].pBt; - if( p ){ - if( sqlite3BtreeIsInTrans(p) ){ - inTrans = 1; - } - sqlite3BtreeRollback(p, tripCode, !schemaChange); - } - } - sqlite3VtabRollback(db); - sqlite3EndBenignMalloc(); - - if( schemaChange ){ - sqlite3ExpirePreparedStatements(db, 0); - sqlite3ResetAllSchemasOfConnection(db); - } - sqlite3BtreeLeaveAll(db); - - /* Any deferred constraint violations have now been resolved. */ - db->nDeferredCons = 0; - db->nDeferredImmCons = 0; - db->flags &= ~(u64)SQLITE_DeferFKs; - - /* If one has been configured, invoke the rollback-hook callback */ - if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){ - db->xRollbackCallback(db->pRollbackArg); - } -} - -/* -** Return a static string containing the name corresponding to the error code -** specified in the argument. -*/ -#if defined(SQLITE_NEED_ERR_NAME) -SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ - const char *zName = 0; - int i, origRc = rc; - for(i=0; i<2 && zName==0; i++, rc &= 0xff){ - switch( rc ){ - case SQLITE_OK: zName = "SQLITE_OK"; break; - case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; - case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break; - case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; - case SQLITE_PERM: zName = "SQLITE_PERM"; break; - case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; - case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break; - case SQLITE_BUSY: zName = "SQLITE_BUSY"; break; - case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break; - case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break; - case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break; - case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break; - case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break; - case SQLITE_READONLY: zName = "SQLITE_READONLY"; break; - case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break; - case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break; - case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; - case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break; - case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break; - case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break; - case SQLITE_IOERR: zName = "SQLITE_IOERR"; break; - case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break; - case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break; - case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break; - case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break; - case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break; - case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break; - case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break; - case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break; - case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break; - case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break; - case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break; - case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break; - case SQLITE_IOERR_CHECKRESERVEDLOCK: - zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; - case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break; - case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break; - case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break; - case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break; - case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break; - case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break; - case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break; - case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break; - case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break; - case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break; - case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break; - case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break; - case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break; - case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break; - case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break; - case SQLITE_FULL: zName = "SQLITE_FULL"; break; - case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break; - case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break; - case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break; - case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break; - case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break; - case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break; - case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break; - case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break; - case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break; - case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break; - case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break; - case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break; - case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break; - case SQLITE_CONSTRAINT_FOREIGNKEY: - zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break; - case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break; - case SQLITE_CONSTRAINT_PRIMARYKEY: - zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break; - case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break; - case SQLITE_CONSTRAINT_COMMITHOOK: - zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break; - case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break; - case SQLITE_CONSTRAINT_FUNCTION: - zName = "SQLITE_CONSTRAINT_FUNCTION"; break; - case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break; - case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break; - case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break; - case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break; - case SQLITE_AUTH: zName = "SQLITE_AUTH"; break; - case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break; - case SQLITE_RANGE: zName = "SQLITE_RANGE"; break; - case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break; - case SQLITE_ROW: zName = "SQLITE_ROW"; break; - case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break; - case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break; - case SQLITE_NOTICE_RECOVER_ROLLBACK: - zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break; - case SQLITE_WARNING: zName = "SQLITE_WARNING"; break; - case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break; - case SQLITE_DONE: zName = "SQLITE_DONE"; break; - } - } - if( zName==0 ){ - static char zBuf[50]; - sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc); - zName = zBuf; - } - return zName; -} -#endif - -/* -** Return a static string that describes the kind of error specified in the -** argument. -*/ -SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ - static const char* const aMsg[] = { - /* SQLITE_OK */ "not an error", - /* SQLITE_ERROR */ "SQL logic error", - /* SQLITE_INTERNAL */ 0, - /* SQLITE_PERM */ "access permission denied", - /* SQLITE_ABORT */ "query aborted", - /* SQLITE_BUSY */ "database is locked", - /* SQLITE_LOCKED */ "database table is locked", - /* SQLITE_NOMEM */ "out of memory", - /* SQLITE_READONLY */ "attempt to write a readonly database", - /* SQLITE_INTERRUPT */ "interrupted", - /* SQLITE_IOERR */ "disk I/O error", - /* SQLITE_CORRUPT */ "database disk image is malformed", - /* SQLITE_NOTFOUND */ "unknown operation", - /* SQLITE_FULL */ "database or disk is full", - /* SQLITE_CANTOPEN */ "unable to open database file", - /* SQLITE_PROTOCOL */ "locking protocol", - /* SQLITE_EMPTY */ 0, - /* SQLITE_SCHEMA */ "database schema has changed", - /* SQLITE_TOOBIG */ "string or blob too big", - /* SQLITE_CONSTRAINT */ "constraint failed", - /* SQLITE_MISMATCH */ "datatype mismatch", - /* SQLITE_MISUSE */ "bad parameter or other API misuse", -#ifdef SQLITE_DISABLE_LFS - /* SQLITE_NOLFS */ "large file support is disabled", -#else - /* SQLITE_NOLFS */ 0, -#endif - /* SQLITE_AUTH */ "authorization denied", - /* SQLITE_FORMAT */ 0, - /* SQLITE_RANGE */ "column index out of range", - /* SQLITE_NOTADB */ "file is not a database", - /* SQLITE_NOTICE */ "notification message", - /* SQLITE_WARNING */ "warning message", - }; - const char *zErr = "unknown error"; - switch( rc ){ - case SQLITE_ABORT_ROLLBACK: { - zErr = "abort due to ROLLBACK"; - break; - } - case SQLITE_ROW: { - zErr = "another row available"; - break; - } - case SQLITE_DONE: { - zErr = "no more rows available"; - break; - } - default: { - rc &= 0xff; - if( ALWAYS(rc>=0) && rcbusyTimeout; - int delay, prior; - - assert( count>=0 ); - if( count < NDELAY ){ - delay = delays[count]; - prior = totals[count]; - }else{ - delay = delays[NDELAY-1]; - prior = totals[NDELAY-1] + delay*(count-(NDELAY-1)); - } - if( prior + delay > tmout ){ - delay = tmout - prior; - if( delay<=0 ) return 0; - } - sqlite3OsSleep(db->pVfs, delay*1000); - return 1; -#else - /* This case for unix systems that lack usleep() support. Sleeping - ** must be done in increments of whole seconds */ - sqlite3 *db = (sqlite3 *)ptr; - int tmout = ((sqlite3 *)ptr)->busyTimeout; - if( (count+1)*1000 > tmout ){ - return 0; - } - sqlite3OsSleep(db->pVfs, 1000000); - return 1; -#endif -} - -/* -** Invoke the given busy handler. -** -** This routine is called when an operation failed to acquire a -** lock on VFS file pFile. -** -** If this routine returns non-zero, the lock is retried. If it -** returns 0, the operation aborts with an SQLITE_BUSY error. -*/ -SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ - int rc; - if( p->xBusyHandler==0 || p->nBusy<0 ) return 0; - rc = p->xBusyHandler(p->pBusyArg, p->nBusy); - if( rc==0 ){ - p->nBusy = -1; - }else{ - p->nBusy++; - } - return rc; -} - -/* -** This routine sets the busy callback for an Sqlite database to the -** given callback function with the given argument. -*/ -SQLITE_API int sqlite3_busy_handler( - sqlite3 *db, - int (*xBusy)(void*,int), - void *pArg -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - db->busyHandler.xBusyHandler = xBusy; - db->busyHandler.pBusyArg = pArg; - db->busyHandler.nBusy = 0; - db->busyTimeout = 0; - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK -/* -** This routine sets the progress callback for an Sqlite database to the -** given callback function with the given argument. The progress callback will -** be invoked every nOps opcodes. -*/ -SQLITE_API void sqlite3_progress_handler( - sqlite3 *db, - int nOps, - int (*xProgress)(void*), - void *pArg -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return; - } -#endif - sqlite3_mutex_enter(db->mutex); - if( nOps>0 ){ - db->xProgress = xProgress; - db->nProgressOps = (unsigned)nOps; - db->pProgressArg = pArg; - }else{ - db->xProgress = 0; - db->nProgressOps = 0; - db->pProgressArg = 0; - } - sqlite3_mutex_leave(db->mutex); -} -#endif - - -/* -** This routine installs a default busy handler that waits for the -** specified number of milliseconds before returning 0. -*/ -SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - if( ms>0 ){ - sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback, - (void*)db); - db->busyTimeout = ms; - }else{ - sqlite3_busy_handler(db, 0, 0); - } - return SQLITE_OK; -} - -/* -** Cause any pending operation to stop at its earliest opportunity. -*/ -SQLITE_API void sqlite3_interrupt(sqlite3 *db){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){ - (void)SQLITE_MISUSE_BKPT; - return; - } -#endif - AtomicStore(&db->u1.isInterrupted, 1); -} - - -/* -** This function is exactly the same as sqlite3_create_function(), except -** that it is designed to be called by internal code. The difference is -** that if a malloc() fails in sqlite3_create_function(), an error code -** is returned and the mallocFailed flag cleared. -*/ -SQLITE_PRIVATE int sqlite3CreateFunc( - sqlite3 *db, - const char *zFunctionName, - int nArg, - int enc, - void *pUserData, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), - void (*xStep)(sqlite3_context*,int,sqlite3_value **), - void (*xFinal)(sqlite3_context*), - void (*xValue)(sqlite3_context*), - void (*xInverse)(sqlite3_context*,int,sqlite3_value **), - FuncDestructor *pDestructor -){ - FuncDef *p; - int nName; - int extraFlags; - - assert( sqlite3_mutex_held(db->mutex) ); - assert( xValue==0 || xSFunc==0 ); - if( zFunctionName==0 /* Must have a valid name */ - || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */ - || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */ - || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */ - || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) - || (255<(nName = sqlite3Strlen30( zFunctionName))) - ){ - return SQLITE_MISUSE_BKPT; - } - - assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); - assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY ); - extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY| - SQLITE_SUBTYPE|SQLITE_INNOCUOUS); - enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); - - /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But - ** the meaning is inverted. So flip the bit. */ - assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS ); - extraFlags ^= SQLITE_FUNC_UNSAFE; - - -#ifndef SQLITE_OMIT_UTF16 - /* If SQLITE_UTF16 is specified as the encoding type, transform this - ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the - ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. - ** - ** If SQLITE_ANY is specified, add three versions of the function - ** to the hash table. - */ - if( enc==SQLITE_UTF16 ){ - enc = SQLITE_UTF16NATIVE; - }else if( enc==SQLITE_ANY ){ - int rc; - rc = sqlite3CreateFunc(db, zFunctionName, nArg, - (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE, - pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor); - if( rc==SQLITE_OK ){ - rc = sqlite3CreateFunc(db, zFunctionName, nArg, - (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE, - pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor); - } - if( rc!=SQLITE_OK ){ - return rc; - } - enc = SQLITE_UTF16BE; - } -#else - enc = SQLITE_UTF8; -#endif - - /* Check if an existing function is being overridden or deleted. If so, - ** and there are active VMs, then return SQLITE_BUSY. If a function - ** is being overridden/deleted but there are no active VMs, allow the - ** operation to continue but invalidate all precompiled statements. - */ - p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); - if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){ - if( db->nVdbeActive ){ - sqlite3ErrorWithMsg(db, SQLITE_BUSY, - "unable to delete/modify user-function due to active statements"); - assert( !db->mallocFailed ); - return SQLITE_BUSY; - }else{ - sqlite3ExpirePreparedStatements(db, 0); - } - } - - p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1); - assert(p || db->mallocFailed); - if( !p ){ - return SQLITE_NOMEM_BKPT; - } - - /* If an older version of the function with a configured destructor is - ** being replaced invoke the destructor function here. */ - functionDestroy(db, p); - - if( pDestructor ){ - pDestructor->nRef++; - } - p->u.pDestructor = pDestructor; - p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags; - testcase( p->funcFlags & SQLITE_DETERMINISTIC ); - testcase( p->funcFlags & SQLITE_DIRECTONLY ); - p->xSFunc = xSFunc ? xSFunc : xStep; - p->xFinalize = xFinal; - p->xValue = xValue; - p->xInverse = xInverse; - p->pUserData = pUserData; - p->nArg = (u16)nArg; - return SQLITE_OK; -} - -/* -** Worker function used by utf-8 APIs that create new functions: -** -** sqlite3_create_function() -** sqlite3_create_function_v2() -** sqlite3_create_window_function() -*/ -static int createFunctionApi( - sqlite3 *db, - const char *zFunc, - int nArg, - int enc, - void *p, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), - 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*) -){ - int rc = SQLITE_ERROR; - FuncDestructor *pArg = 0; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - if( xDestroy ){ - pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor)); - if( !pArg ){ - sqlite3OomFault(db); - xDestroy(p); - goto out; - } - pArg->nRef = 0; - pArg->xDestroy = xDestroy; - pArg->pUserData = p; - } - rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, - xSFunc, xStep, xFinal, xValue, xInverse, pArg - ); - if( pArg && pArg->nRef==0 ){ - assert( rc!=SQLITE_OK ); - xDestroy(p); - sqlite3_free(pArg); - } - - out: - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** Create new user functions. -*/ -SQLITE_API int sqlite3_create_function( - sqlite3 *db, - const char *zFunc, - int nArg, - int enc, - void *p, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), - void (*xStep)(sqlite3_context*,int,sqlite3_value **), - void (*xFinal)(sqlite3_context*) -){ - return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep, - xFinal, 0, 0, 0); -} -SQLITE_API int sqlite3_create_function_v2( - sqlite3 *db, - const char *zFunc, - int nArg, - int enc, - void *p, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value **), - void (*xStep)(sqlite3_context*,int,sqlite3_value **), - void (*xFinal)(sqlite3_context*), - void (*xDestroy)(void *) -){ - return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep, - xFinal, 0, 0, xDestroy); -} -SQLITE_API int sqlite3_create_window_function( - sqlite3 *db, - const char *zFunc, - int nArg, - int enc, - void *p, - 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 *) -){ - return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep, - xFinal, xValue, xInverse, xDestroy); -} - -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API int sqlite3_create_function16( - sqlite3 *db, - const void *zFunctionName, - int nArg, - int eTextRep, - void *p, - void (*xSFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) -){ - int rc; - char *zFunc8; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - assert( !db->mallocFailed ); - zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE); - rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0); - sqlite3DbFree(db, zFunc8); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} -#endif - - -/* -** The following is the implementation of an SQL function that always -** fails with an error message stating that the function is used in the -** wrong context. The sqlite3_overload_function() API might construct -** SQL function that use this routine so that the functions will exist -** for name resolution but are actually overloaded by the xFindFunction -** method of virtual tables. -*/ -static void sqlite3InvalidFunction( - sqlite3_context *context, /* The function calling context */ - int NotUsed, /* Number of arguments to the function */ - sqlite3_value **NotUsed2 /* Value of each argument */ -){ - const char *zName = (const char*)sqlite3_user_data(context); - char *zErr; - UNUSED_PARAMETER2(NotUsed, NotUsed2); - zErr = sqlite3_mprintf( - "unable to use function %s in the requested context", zName); - sqlite3_result_error(context, zErr, -1); - sqlite3_free(zErr); -} - -/* -** Declare that a function has been overloaded by a virtual table. -** -** If the function already exists as a regular global function, then -** this routine is a no-op. If the function does not exist, then create -** a new one that always throws a run-time error. -** -** When virtual tables intend to provide an overloaded function, they -** should call this routine to make sure the global function exists. -** A global function must exist in order for name resolution to work -** properly. -*/ -SQLITE_API int sqlite3_overload_function( - sqlite3 *db, - const char *zName, - int nArg -){ - int rc; - char *zCopy; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0; - sqlite3_mutex_leave(db->mutex); - if( rc ) return SQLITE_OK; - zCopy = sqlite3_mprintf(zName); - if( zCopy==0 ) return SQLITE_NOMEM; - return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8, - zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free); -} - -#ifndef SQLITE_OMIT_TRACE -/* -** Register a trace function. The pArg from the previously registered trace -** is returned. -** -** A NULL trace function means that no tracing is executes. A non-NULL -** trace is a pointer to a function that is invoked at the start of each -** SQL statement. -*/ -#ifndef SQLITE_OMIT_DEPRECATED -SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){ - void *pOld; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - sqlite3_mutex_enter(db->mutex); - pOld = db->pTraceArg; - db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0; - db->trace.xLegacy = xTrace; - db->pTraceArg = pArg; - sqlite3_mutex_leave(db->mutex); - return pOld; -} -#endif /* SQLITE_OMIT_DEPRECATED */ - -/* Register a trace callback using the version-2 interface. -*/ -SQLITE_API int sqlite3_trace_v2( - sqlite3 *db, /* Trace this connection */ - unsigned mTrace, /* Mask of events to be traced */ - int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */ - void *pArg /* Context */ -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - if( mTrace==0 ) xTrace = 0; - if( xTrace==0 ) mTrace = 0; - db->mTrace = mTrace; - db->trace.xV2 = xTrace; - db->pTraceArg = pArg; - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** Register a profile function. The pArg from the previously registered -** profile function is returned. -** -** A NULL profile function means that no profiling is executes. A non-NULL -** profile is a pointer to a function that is invoked at the conclusion of -** each SQL statement that is run. -*/ -SQLITE_API void *sqlite3_profile( - sqlite3 *db, - void (*xProfile)(void*,const char*,sqlite_uint64), - void *pArg -){ - void *pOld; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - sqlite3_mutex_enter(db->mutex); - pOld = db->pProfileArg; - db->xProfile = xProfile; - db->pProfileArg = pArg; - db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK; - if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE; - sqlite3_mutex_leave(db->mutex); - return pOld; -} -#endif /* SQLITE_OMIT_DEPRECATED */ -#endif /* SQLITE_OMIT_TRACE */ - -/* -** Register a function to be invoked when a transaction commits. -** If the invoked function returns non-zero, then the commit becomes a -** rollback. -*/ -SQLITE_API void *sqlite3_commit_hook( - sqlite3 *db, /* Attach the hook to this database */ - int (*xCallback)(void*), /* Function to invoke on each commit */ - void *pArg /* Argument to the function */ -){ - void *pOld; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - sqlite3_mutex_enter(db->mutex); - pOld = db->pCommitArg; - db->xCommitCallback = xCallback; - db->pCommitArg = pArg; - sqlite3_mutex_leave(db->mutex); - return pOld; -} - -/* -** Register a callback to be invoked each time a row is updated, -** inserted or deleted using this database connection. -*/ -SQLITE_API void *sqlite3_update_hook( - sqlite3 *db, /* Attach the hook to this database */ - void (*xCallback)(void*,int,char const *,char const *,sqlite_int64), - void *pArg /* Argument to the function */ -){ - void *pRet; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - sqlite3_mutex_enter(db->mutex); - pRet = db->pUpdateArg; - db->xUpdateCallback = xCallback; - db->pUpdateArg = pArg; - sqlite3_mutex_leave(db->mutex); - return pRet; -} - -/* -** Register a callback to be invoked each time a transaction is rolled -** back by this database connection. -*/ -SQLITE_API void *sqlite3_rollback_hook( - sqlite3 *db, /* Attach the hook to this database */ - void (*xCallback)(void*), /* Callback function */ - void *pArg /* Argument to the function */ -){ - void *pRet; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - sqlite3_mutex_enter(db->mutex); - pRet = db->pRollbackArg; - db->xRollbackCallback = xCallback; - db->pRollbackArg = pArg; - sqlite3_mutex_leave(db->mutex); - return pRet; -} - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK -/* -** Register a callback to be invoked each time a row is updated, -** inserted or deleted using this database connection. -*/ -SQLITE_API void *sqlite3_preupdate_hook( - sqlite3 *db, /* Attach the hook to this database */ - void(*xCallback)( /* Callback function */ - void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64), - void *pArg /* First callback argument */ -){ - void *pRet; - sqlite3_mutex_enter(db->mutex); - pRet = db->pPreUpdateArg; - db->xPreUpdateCallback = xCallback; - db->pPreUpdateArg = pArg; - sqlite3_mutex_leave(db->mutex); - return pRet; -} -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ - -#ifndef SQLITE_OMIT_WAL -/* -** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint(). -** Invoke sqlite3_wal_checkpoint if the number of frames in the log file -** is greater than sqlite3.pWalArg cast to an integer (the value configured by -** wal_autocheckpoint()). -*/ -SQLITE_PRIVATE int sqlite3WalDefaultHook( - void *pClientData, /* Argument */ - sqlite3 *db, /* Connection */ - const char *zDb, /* Database */ - int nFrame /* Size of WAL */ -){ - if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){ - sqlite3BeginBenignMalloc(); - sqlite3_wal_checkpoint(db, zDb); - sqlite3EndBenignMalloc(); - } - return SQLITE_OK; -} -#endif /* SQLITE_OMIT_WAL */ - -/* -** Configure an sqlite3_wal_hook() callback to automatically checkpoint -** a database after committing a transaction if there are nFrame or -** more frames in the log file. Passing zero or a negative value as the -** nFrame parameter disables automatic checkpoints entirely. -** -** The callback registered by this function replaces any existing callback -** registered using sqlite3_wal_hook(). Likewise, registering a callback -** using sqlite3_wal_hook() disables the automatic checkpoint mechanism -** configured by this function. -*/ -SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){ -#ifdef SQLITE_OMIT_WAL - UNUSED_PARAMETER(db); - UNUSED_PARAMETER(nFrame); -#else -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - if( nFrame>0 ){ - sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame)); - }else{ - sqlite3_wal_hook(db, 0, 0); - } -#endif - return SQLITE_OK; -} - -/* -** Register a callback to be invoked each time a transaction is written -** into the write-ahead-log by this database connection. -*/ -SQLITE_API void *sqlite3_wal_hook( - sqlite3 *db, /* Attach the hook to this db handle */ - int(*xCallback)(void *, sqlite3*, const char*, int), - void *pArg /* First argument passed to xCallback() */ -){ -#ifndef SQLITE_OMIT_WAL - void *pRet; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - sqlite3_mutex_enter(db->mutex); - pRet = db->pWalArg; - db->xWalCallback = xCallback; - db->pWalArg = pArg; - sqlite3_mutex_leave(db->mutex); - return pRet; -#else - return 0; -#endif -} - -/* -** Checkpoint database zDb. -*/ -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 */ -){ -#ifdef SQLITE_OMIT_WAL - return SQLITE_OK; -#else - int rc; /* Return code */ - int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */ - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - - /* Initialize the output variables to -1 in case an error occurs. */ - if( pnLog ) *pnLog = -1; - if( pnCkpt ) *pnCkpt = -1; - - assert( SQLITE_CHECKPOINT_PASSIVE==0 ); - assert( SQLITE_CHECKPOINT_FULL==1 ); - assert( SQLITE_CHECKPOINT_RESTART==2 ); - assert( SQLITE_CHECKPOINT_TRUNCATE==3 ); - if( eModeSQLITE_CHECKPOINT_TRUNCATE ){ - /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint - ** mode: */ - return SQLITE_MISUSE; - } - - sqlite3_mutex_enter(db->mutex); - if( zDb && zDb[0] ){ - iDb = sqlite3FindDbName(db, zDb); - } - if( iDb<0 ){ - rc = SQLITE_ERROR; - sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb); - }else{ - db->busyHandler.nBusy = 0; - rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt); - sqlite3Error(db, rc); - } - rc = sqlite3ApiExit(db, rc); - - /* If there are no active statements, clear the interrupt flag at this - ** point. */ - if( db->nVdbeActive==0 ){ - AtomicStore(&db->u1.isInterrupted, 0); - } - - sqlite3_mutex_leave(db->mutex); - return rc; -#endif -} - - -/* -** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points -** to contains a zero-length string, all attached databases are -** checkpointed. -*/ -SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){ - /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to - ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */ - return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0); -} - -#ifndef SQLITE_OMIT_WAL -/* -** Run a checkpoint on database iDb. This is a no-op if database iDb is -** not currently open in WAL mode. -** -** If a transaction is open on the database being checkpointed, this -** function returns SQLITE_LOCKED and a checkpoint is not attempted. If -** an error occurs while running the checkpoint, an SQLite error code is -** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK. -** -** The mutex on database handle db should be held by the caller. The mutex -** associated with the specific b-tree being checkpointed is taken by -** this function while the checkpoint is running. -** -** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are -** checkpointed. If an error is encountered it is returned immediately - -** no attempt is made to checkpoint any remaining databases. -** -** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART -** or TRUNCATE. -*/ -SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){ - int rc = SQLITE_OK; /* Return code */ - int i; /* Used to iterate through attached dbs */ - int bBusy = 0; /* True if SQLITE_BUSY has been encountered */ - - assert( sqlite3_mutex_held(db->mutex) ); - assert( !pnLog || *pnLog==-1 ); - assert( !pnCkpt || *pnCkpt==-1 ); - - for(i=0; inDb && rc==SQLITE_OK; i++){ - if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){ - rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt); - pnLog = 0; - pnCkpt = 0; - if( rc==SQLITE_BUSY ){ - bBusy = 1; - rc = SQLITE_OK; - } - } - } - - return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc; -} -#endif /* SQLITE_OMIT_WAL */ - -/* -** This function returns true if main-memory should be used instead of -** a temporary file for transient pager files and statement journals. -** The value returned depends on the value of db->temp_store (runtime -** parameter) and the compile time value of SQLITE_TEMP_STORE. The -** following table describes the relationship between these two values -** and this functions return value. -** -** SQLITE_TEMP_STORE db->temp_store Location of temporary database -** ----------------- -------------- ------------------------------ -** 0 any file (return 0) -** 1 1 file (return 0) -** 1 2 memory (return 1) -** 1 0 file (return 0) -** 2 1 file (return 0) -** 2 2 memory (return 1) -** 2 0 memory (return 1) -** 3 any memory (return 1) -*/ -SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){ -#if SQLITE_TEMP_STORE==1 - return ( db->temp_store==2 ); -#endif -#if SQLITE_TEMP_STORE==2 - return ( db->temp_store!=1 ); -#endif -#if SQLITE_TEMP_STORE==3 - UNUSED_PARAMETER(db); - return 1; -#endif -#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3 - UNUSED_PARAMETER(db); - return 0; -#endif -} - -/* -** Return UTF-8 encoded English language explanation of the most recent -** error. -*/ -SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ - const char *z; - if( !db ){ - return sqlite3ErrStr(SQLITE_NOMEM_BKPT); - } - if( !sqlite3SafetyCheckSickOrOk(db) ){ - return sqlite3ErrStr(SQLITE_MISUSE_BKPT); - } - sqlite3_mutex_enter(db->mutex); - if( db->mallocFailed ){ - z = sqlite3ErrStr(SQLITE_NOMEM_BKPT); - }else{ - testcase( db->pErr==0 ); - z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0; - assert( !db->mallocFailed ); - if( z==0 ){ - z = sqlite3ErrStr(db->errCode); - } - } - sqlite3_mutex_leave(db->mutex); - return z; -} - -#ifndef SQLITE_OMIT_UTF16 -/* -** Return UTF-16 encoded English language explanation of the most recent -** error. -*/ -SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ - static const u16 outOfMem[] = { - 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0 - }; - static const u16 misuse[] = { - 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ', - 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ', - 'm', 'i', 's', 'u', 's', 'e', 0 - }; - - const void *z; - if( !db ){ - return (void *)outOfMem; - } - if( !sqlite3SafetyCheckSickOrOk(db) ){ - return (void *)misuse; - } - sqlite3_mutex_enter(db->mutex); - if( db->mallocFailed ){ - z = (void *)outOfMem; - }else{ - z = sqlite3_value_text16(db->pErr); - if( z==0 ){ - sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode)); - z = sqlite3_value_text16(db->pErr); - } - /* A malloc() may have failed within the call to sqlite3_value_text16() - ** above. If this is the case, then the db->mallocFailed flag needs to - ** be cleared before returning. Do this directly, instead of via - ** sqlite3ApiExit(), to avoid setting the database handle error message. - */ - sqlite3OomClear(db); - } - sqlite3_mutex_leave(db->mutex); - return z; -} -#endif /* SQLITE_OMIT_UTF16 */ - -/* -** Return the most recent error code generated by an SQLite routine. If NULL is -** passed to this function, we assume a malloc() failed during sqlite3_open(). -*/ -SQLITE_API int sqlite3_errcode(sqlite3 *db){ - if( db && !sqlite3SafetyCheckSickOrOk(db) ){ - return SQLITE_MISUSE_BKPT; - } - if( !db || db->mallocFailed ){ - return SQLITE_NOMEM_BKPT; - } - return db->errCode & db->errMask; -} -SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ - if( db && !sqlite3SafetyCheckSickOrOk(db) ){ - return SQLITE_MISUSE_BKPT; - } - if( !db || db->mallocFailed ){ - return SQLITE_NOMEM_BKPT; - } - return db->errCode; -} -SQLITE_API int sqlite3_system_errno(sqlite3 *db){ - return db ? db->iSysErrno : 0; -} - -/* -** Return a string that describes the kind of error specified in the -** argument. For now, this simply calls the internal sqlite3ErrStr() -** function. -*/ -SQLITE_API const char *sqlite3_errstr(int rc){ - return sqlite3ErrStr(rc); -} - -/* -** Create a new collating function for database "db". The name is zName -** and the encoding is enc. -*/ -static int createCollation( - sqlite3* db, - const char *zName, - u8 enc, - void* pCtx, - int(*xCompare)(void*,int,const void*,int,const void*), - void(*xDel)(void*) -){ - CollSeq *pColl; - int enc2; - - assert( sqlite3_mutex_held(db->mutex) ); - - /* If SQLITE_UTF16 is specified as the encoding type, transform this - ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the - ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. - */ - enc2 = enc; - testcase( enc2==SQLITE_UTF16 ); - testcase( enc2==SQLITE_UTF16_ALIGNED ); - if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){ - enc2 = SQLITE_UTF16NATIVE; - } - if( enc2SQLITE_UTF16BE ){ - return SQLITE_MISUSE_BKPT; - } - - /* Check if this call is removing or replacing an existing collation - ** sequence. If so, and there are active VMs, return busy. If there - ** are no active VMs, invalidate any pre-compiled statements. - */ - pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0); - if( pColl && pColl->xCmp ){ - if( db->nVdbeActive ){ - sqlite3ErrorWithMsg(db, SQLITE_BUSY, - "unable to delete/modify collation sequence due to active statements"); - return SQLITE_BUSY; - } - sqlite3ExpirePreparedStatements(db, 0); - - /* If collation sequence pColl was created directly by a call to - ** sqlite3_create_collation, and not generated by synthCollSeq(), - ** then any copies made by synthCollSeq() need to be invalidated. - ** Also, collation destructor - CollSeq.xDel() - function may need - ** to be called. - */ - if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ - CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName); - int j; - for(j=0; j<3; j++){ - CollSeq *p = &aColl[j]; - if( p->enc==pColl->enc ){ - if( p->xDel ){ - p->xDel(p->pUser); - } - p->xCmp = 0; - } - } - } - } - - pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1); - if( pColl==0 ) return SQLITE_NOMEM_BKPT; - pColl->xCmp = xCompare; - pColl->pUser = pCtx; - pColl->xDel = xDel; - pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED)); - sqlite3Error(db, SQLITE_OK); - return SQLITE_OK; -} - - -/* -** This array defines hard upper bounds on limit values. The -** initializer must be kept in sync with the SQLITE_LIMIT_* -** #defines in sqlite3.h. -*/ -static const int aHardLimit[] = { - SQLITE_MAX_LENGTH, - SQLITE_MAX_SQL_LENGTH, - SQLITE_MAX_COLUMN, - SQLITE_MAX_EXPR_DEPTH, - SQLITE_MAX_COMPOUND_SELECT, - SQLITE_MAX_VDBE_OP, - SQLITE_MAX_FUNCTION_ARG, - SQLITE_MAX_ATTACHED, - SQLITE_MAX_LIKE_PATTERN_LENGTH, - SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ - SQLITE_MAX_TRIGGER_DEPTH, - SQLITE_MAX_WORKER_THREADS, -}; - -/* -** Make sure the hard limits are set to reasonable values -*/ -#if SQLITE_MAX_LENGTH<100 -# error SQLITE_MAX_LENGTH must be at least 100 -#endif -#if SQLITE_MAX_SQL_LENGTH<100 -# error SQLITE_MAX_SQL_LENGTH must be at least 100 -#endif -#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH -# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH -#endif -#if SQLITE_MAX_COMPOUND_SELECT<2 -# error SQLITE_MAX_COMPOUND_SELECT must be at least 2 -#endif -#if SQLITE_MAX_VDBE_OP<40 -# error SQLITE_MAX_VDBE_OP must be at least 40 -#endif -#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127 -# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127 -#endif -#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 -# error SQLITE_MAX_ATTACHED must be between 0 and 125 -#endif -#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 -# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 -#endif -#if SQLITE_MAX_COLUMN>32767 -# error SQLITE_MAX_COLUMN must not exceed 32767 -#endif -#if SQLITE_MAX_TRIGGER_DEPTH<1 -# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1 -#endif -#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 -# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 -#endif - - -/* -** Change the value of a limit. Report the old value. -** If an invalid limit index is supplied, report -1. -** Make no changes but still report the old value if the -** new limit is negative. -** -** A new lower limit does not shrink existing constructs. -** It merely prevents new constructs that exceed the limit -** from forming. -*/ -SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ - int oldLimit; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return -1; - } -#endif - - /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME - ** there is a hard upper bound set at compile-time by a C preprocessor - ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to - ** "_MAX_".) - */ - assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH ); - assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); - assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); - assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); - assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); - assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); - assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); - assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED ); - assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]== - SQLITE_MAX_LIKE_PATTERN_LENGTH ); - assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); - assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); - assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); - assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); - - - if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ - return -1; - } - oldLimit = db->aLimit[limitId]; - if( newLimit>=0 ){ /* IMP: R-52476-28732 */ - if( newLimit>aHardLimit[limitId] ){ - newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ - } - db->aLimit[limitId] = newLimit; - } - return oldLimit; /* IMP: R-53341-35419 */ -} - -/* -** This function is used to parse both URIs and non-URI filenames passed by the -** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database -** URIs specified as part of ATTACH statements. -** -** The first argument to this function is the name of the VFS to use (or -** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx" -** query parameter. The second argument contains the URI (or non-URI filename) -** itself. When this function is called the *pFlags variable should contain -** the default flags to open the database handle with. The value stored in -** *pFlags may be updated before returning if the URI filename contains -** "cache=xxx" or "mode=xxx" query parameters. -** -** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to -** the VFS that should be used to open the database file. *pzFile is set to -** point to a buffer containing the name of the file to open. The value -** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter() -** and is in the same format as names created using sqlite3_create_filename(). -** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on -** the value returned in *pzFile to avoid a memory leak. -** -** If an error occurs, then an SQLite error code is returned and *pzErrMsg -** may be set to point to a buffer containing an English language error -** message. It is the responsibility of the caller to eventually release -** this buffer by calling sqlite3_free(). -*/ -SQLITE_PRIVATE int sqlite3ParseUri( - const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */ - const char *zUri, /* Nul-terminated URI to parse */ - unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */ - sqlite3_vfs **ppVfs, /* OUT: VFS to use */ - char **pzFile, /* OUT: Filename component of URI */ - char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */ -){ - int rc = SQLITE_OK; - unsigned int flags = *pFlags; - const char *zVfs = zDefaultVfs; - char *zFile; - char c; - int nUri = sqlite3Strlen30(zUri); - - assert( *pzErrMsg==0 ); - - if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */ - || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */ - && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */ - ){ - char *zOpt; - int eState; /* Parser state when parsing URI */ - int iIn; /* Input character index */ - int iOut = 0; /* Output character index */ - u64 nByte = nUri+8; /* Bytes of space to allocate */ - - /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen - ** method that there may be extra parameters following the file-name. */ - flags |= SQLITE_OPEN_URI; - - for(iIn=0; iIn=0 && octet<256 ); - if( octet==0 ){ -#ifndef SQLITE_ENABLE_URI_00_ERROR - /* This branch is taken when "%00" appears within the URI. In this - ** case we ignore all text in the remainder of the path, name or - ** value currently being parsed. So ignore the current character - ** and skip to the next "?", "=" or "&", as appropriate. */ - while( (c = zUri[iIn])!=0 && c!='#' - && (eState!=0 || c!='?') - && (eState!=1 || (c!='=' && c!='&')) - && (eState!=2 || c!='&') - ){ - iIn++; - } - continue; -#else - /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */ - *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri"); - rc = SQLITE_ERROR; - goto parse_uri_out; -#endif - } - c = octet; - }else if( eState==1 && (c=='&' || c=='=') ){ - if( zFile[iOut-1]==0 ){ - /* An empty option name. Ignore this option altogether. */ - while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++; - continue; - } - if( c=='&' ){ - zFile[iOut++] = '\0'; - }else{ - eState = 2; - } - c = 0; - }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){ - c = 0; - eState = 1; - } - zFile[iOut++] = c; - } - if( eState==1 ) zFile[iOut++] = '\0'; - memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */ - - /* Check if there were any options specified that should be interpreted - ** here. Options that are interpreted here include "vfs" and those that - ** correspond to flags that may be passed to the sqlite3_open_v2() - ** method. */ - zOpt = &zFile[sqlite3Strlen30(zFile)+1]; - while( zOpt[0] ){ - int nOpt = sqlite3Strlen30(zOpt); - char *zVal = &zOpt[nOpt+1]; - int nVal = sqlite3Strlen30(zVal); - - if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ - zVfs = zVal; - }else{ - struct OpenMode { - const char *z; - int mode; - } *aMode = 0; - char *zModeType = 0; - int mask = 0; - int limit = 0; - - if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){ - static struct OpenMode aCacheMode[] = { - { "shared", SQLITE_OPEN_SHAREDCACHE }, - { "private", SQLITE_OPEN_PRIVATECACHE }, - { 0, 0 } - }; - - mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE; - aMode = aCacheMode; - limit = mask; - zModeType = "cache"; - } - if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){ - static struct OpenMode aOpenMode[] = { - { "ro", SQLITE_OPEN_READONLY }, - { "rw", SQLITE_OPEN_READWRITE }, - { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE }, - { "memory", SQLITE_OPEN_MEMORY }, - { 0, 0 } - }; - - mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE - | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY; - aMode = aOpenMode; - limit = mask & flags; - zModeType = "access"; - } - - if( aMode ){ - int i; - int mode = 0; - for(i=0; aMode[i].z; i++){ - const char *z = aMode[i].z; - if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ - mode = aMode[i].mode; - break; - } - } - if( mode==0 ){ - *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal); - rc = SQLITE_ERROR; - goto parse_uri_out; - } - if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){ - *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s", - zModeType, zVal); - rc = SQLITE_PERM; - goto parse_uri_out; - } - flags = (flags & ~mask) | mode; - } - } - - zOpt = &zVal[nVal+1]; - } - - }else{ - zFile = sqlite3_malloc64(nUri+8); - if( !zFile ) return SQLITE_NOMEM_BKPT; - memset(zFile, 0, 4); - zFile += 4; - if( nUri ){ - memcpy(zFile, zUri, nUri); - } - memset(zFile+nUri, 0, 4); - flags &= ~SQLITE_OPEN_URI; - } - - *ppVfs = sqlite3_vfs_find(zVfs); - if( *ppVfs==0 ){ - *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs); - rc = SQLITE_ERROR; - } - parse_uri_out: - if( rc!=SQLITE_OK ){ - sqlite3_free_filename(zFile); - zFile = 0; - } - *pFlags = flags; - *pzFile = zFile; - return rc; -} - -/* -** This routine does the core work of extracting URI parameters from a -** database filename for the sqlite3_uri_parameter() interface. -*/ -static const char *uriParameter(const char *zFilename, const char *zParam){ - zFilename += sqlite3Strlen30(zFilename) + 1; - while( zFilename[0] ){ - int x = strcmp(zFilename, zParam); - zFilename += sqlite3Strlen30(zFilename) + 1; - if( x==0 ) return zFilename; - zFilename += sqlite3Strlen30(zFilename) + 1; - } - return 0; -} - - - -/* -** This routine does the work of opening a database on behalf of -** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" -** is UTF-8 encoded. -*/ -static int openDatabase( - const char *zFilename, /* Database filename UTF-8 encoded */ - sqlite3 **ppDb, /* OUT: Returned database handle */ - unsigned int flags, /* Operational flags */ - const char *zVfs /* Name of the VFS to use */ -){ - sqlite3 *db; /* Store allocated handle here */ - int rc; /* Return code */ - int isThreadsafe; /* True for threadsafe connections */ - char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */ - char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */ - int i; /* Loop counter */ - -#ifdef SQLITE_ENABLE_API_ARMOR - if( ppDb==0 ) return SQLITE_MISUSE_BKPT; -#endif - *ppDb = 0; -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ) return rc; -#endif - - if( sqlite3GlobalConfig.bCoreMutex==0 ){ - isThreadsafe = 0; - }else if( flags & SQLITE_OPEN_NOMUTEX ){ - isThreadsafe = 0; - }else if( flags & SQLITE_OPEN_FULLMUTEX ){ - isThreadsafe = 1; - }else{ - isThreadsafe = sqlite3GlobalConfig.bFullMutex; - } - - if( flags & SQLITE_OPEN_PRIVATECACHE ){ - flags &= ~SQLITE_OPEN_SHAREDCACHE; - }else if( sqlite3GlobalConfig.sharedCacheEnabled ){ - flags |= SQLITE_OPEN_SHAREDCACHE; - } - - /* Remove harmful bits from the flags parameter - ** - ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were - ** dealt with in the previous code block. Besides these, the only - ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY, - ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE, - ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask - ** off all other flags. - */ - flags &= ~( SQLITE_OPEN_DELETEONCLOSE | - SQLITE_OPEN_EXCLUSIVE | - SQLITE_OPEN_MAIN_DB | - SQLITE_OPEN_TEMP_DB | - SQLITE_OPEN_TRANSIENT_DB | - SQLITE_OPEN_MAIN_JOURNAL | - SQLITE_OPEN_TEMP_JOURNAL | - SQLITE_OPEN_SUBJOURNAL | - SQLITE_OPEN_SUPER_JOURNAL | - SQLITE_OPEN_NOMUTEX | - SQLITE_OPEN_FULLMUTEX | - SQLITE_OPEN_WAL - ); - - /* Allocate the sqlite data structure */ - db = sqlite3MallocZero( sizeof(sqlite3) ); - if( db==0 ) goto opendb_out; - if( isThreadsafe -#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS - || sqlite3GlobalConfig.bCoreMutex -#endif - ){ - db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); - if( db->mutex==0 ){ - sqlite3_free(db); - db = 0; - goto opendb_out; - } - if( isThreadsafe==0 ){ - sqlite3MutexWarnOnContention(db->mutex); - } - } - sqlite3_mutex_enter(db->mutex); - db->errMask = 0xff; - db->nDb = 2; - db->magic = SQLITE_MAGIC_BUSY; - db->aDb = db->aDbStatic; - db->lookaside.bDisable = 1; - db->lookaside.sz = 0; - - assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); - memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); - db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS; - db->autoCommit = 1; - db->nextAutovac = -1; - db->szMmap = sqlite3GlobalConfig.szMmap; - db->nextPagesize = 0; - db->nMaxSorterMmap = 0x7FFFFFFF; - db->flags |= SQLITE_ShortColNames - | SQLITE_EnableTrigger - | SQLITE_EnableView - | SQLITE_CacheSpill -#if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0 - | SQLITE_TrustedSchema -#endif -/* The SQLITE_DQS compile-time option determines the default settings -** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML. -** -** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML -** ---------- ----------------------- ----------------------- -** undefined on on -** 3 on on -** 2 on off -** 1 off on -** 0 off off -** -** Legacy behavior is 3 (double-quoted string literals are allowed anywhere) -** and so that is the default. But developers are encouranged to use -** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible. -*/ -#if !defined(SQLITE_DQS) -# define SQLITE_DQS 3 -#endif -#if (SQLITE_DQS&1)==1 - | SQLITE_DqsDML -#endif -#if (SQLITE_DQS&2)==2 - | SQLITE_DqsDDL -#endif - -#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX - | SQLITE_AutoIndex -#endif -#if SQLITE_DEFAULT_CKPTFULLFSYNC - | SQLITE_CkptFullFSync -#endif -#if SQLITE_DEFAULT_FILE_FORMAT<4 - | SQLITE_LegacyFileFmt -#endif -#ifdef SQLITE_ENABLE_LOAD_EXTENSION - | SQLITE_LoadExtension -#endif -#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS - | SQLITE_RecTriggers -#endif -#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS - | SQLITE_ForeignKeys -#endif -#if defined(SQLITE_REVERSE_UNORDERED_SELECTS) - | SQLITE_ReverseOrder -#endif -#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK) - | SQLITE_CellSizeCk -#endif -#if defined(SQLITE_ENABLE_FTS3_TOKENIZER) - | SQLITE_Fts3Tokenizer -#endif -#if defined(SQLITE_ENABLE_QPSG) - | SQLITE_EnableQPSG -#endif -#if defined(SQLITE_DEFAULT_DEFENSIVE) - | SQLITE_Defensive -#endif -#if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE) - | SQLITE_LegacyAlter -#endif - ; - sqlite3HashInit(&db->aCollSeq); -#ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3HashInit(&db->aModule); -#endif - - /* Add the default collation sequence BINARY. BINARY works for both UTF-8 - ** and UTF-16, so add a version for each to avoid any unnecessary - ** conversions. The only error that can occur here is a malloc() failure. - ** - ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating - ** functions: - */ - createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); - createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); - createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); - createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); - createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0); - if( db->mallocFailed ){ - goto opendb_out; - } - - /* Parse the filename/URI argument - ** - ** Only allow sensible combinations of bits in the flags argument. - ** Throw an error if any non-sense combination is used. If we - ** do not block illegal combinations here, it could trigger - ** assert() statements in deeper layers. Sensible combinations - ** are: - ** - ** 1: SQLITE_OPEN_READONLY - ** 2: SQLITE_OPEN_READWRITE - ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE - */ - db->openFlags = flags; - assert( SQLITE_OPEN_READONLY == 0x01 ); - assert( SQLITE_OPEN_READWRITE == 0x02 ); - assert( SQLITE_OPEN_CREATE == 0x04 ); - testcase( (1<<(flags&7))==0x02 ); /* READONLY */ - testcase( (1<<(flags&7))==0x04 ); /* READWRITE */ - testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */ - if( ((1<<(flags&7)) & 0x46)==0 ){ - rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */ - }else{ - rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg); - } - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_NOMEM ) sqlite3OomFault(db); - sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg); - sqlite3_free(zErrMsg); - goto opendb_out; - } - - /* Open the backend database driver */ - rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0, - flags | SQLITE_OPEN_MAIN_DB); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_IOERR_NOMEM ){ - rc = SQLITE_NOMEM_BKPT; - } - sqlite3Error(db, rc); - goto opendb_out; - } - sqlite3BtreeEnter(db->aDb[0].pBt); - db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); - if( !db->mallocFailed ){ - sqlite3SetTextEncoding(db, SCHEMA_ENC(db)); - } - sqlite3BtreeLeave(db->aDb[0].pBt); - db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); - - /* The default safety_level for the main database is FULL; for the temp - ** database it is OFF. This matches the pager layer defaults. - */ - db->aDb[0].zDbSName = "main"; - db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1; - db->aDb[1].zDbSName = "temp"; - db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF; - - db->magic = SQLITE_MAGIC_OPEN; - if( db->mallocFailed ){ - goto opendb_out; - } - - /* Register all built-in functions, but do not attempt to read the - ** database schema yet. This is delayed until the first time the database - ** is accessed. - */ - sqlite3Error(db, SQLITE_OK); - sqlite3RegisterPerConnectionBuiltinFunctions(db); - rc = sqlite3_errcode(db); - - - /* Load compiled-in extensions */ - for(i=0; rc==SQLITE_OK && imDbFlags |= DBFLAG_InternalFunc; -#endif - - /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking - ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking - ** mode. Doing nothing at all also makes NORMAL the default. - */ -#ifdef SQLITE_DEFAULT_LOCKING_MODE - db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE; - sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt), - SQLITE_DEFAULT_LOCKING_MODE); -#endif - - if( rc ) sqlite3Error(db, rc); - - /* Enable the lookaside-malloc subsystem */ - setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside, - sqlite3GlobalConfig.nLookaside); - - sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT); - -opendb_out: - if( db ){ - assert( db->mutex!=0 || isThreadsafe==0 - || sqlite3GlobalConfig.bFullMutex==0 ); - sqlite3_mutex_leave(db->mutex); - } - rc = sqlite3_errcode(db); - assert( db!=0 || rc==SQLITE_NOMEM ); - if( rc==SQLITE_NOMEM ){ - sqlite3_close(db); - db = 0; - }else if( rc!=SQLITE_OK ){ - db->magic = SQLITE_MAGIC_SICK; - } - *ppDb = db; -#ifdef SQLITE_ENABLE_SQLLOG - if( sqlite3GlobalConfig.xSqllog ){ - /* Opening a db handle. Fourth parameter is passed 0. */ - void *pArg = sqlite3GlobalConfig.pSqllogArg; - sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0); - } -#endif - sqlite3_free_filename(zOpen); - return rc & 0xff; -} - - -/* -** Open a new database handle. -*/ -SQLITE_API int sqlite3_open( - const char *zFilename, - sqlite3 **ppDb -){ - return openDatabase(zFilename, ppDb, - SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); -} -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 */ -){ - return openDatabase(filename, ppDb, (unsigned int)flags, zVfs); -} - -#ifndef SQLITE_OMIT_UTF16 -/* -** Open a new database handle. -*/ -SQLITE_API int sqlite3_open16( - const void *zFilename, - sqlite3 **ppDb -){ - char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ - sqlite3_value *pVal; - int rc; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( ppDb==0 ) return SQLITE_MISUSE_BKPT; -#endif - *ppDb = 0; -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ) return rc; -#endif - if( zFilename==0 ) zFilename = "\000\000"; - pVal = sqlite3ValueNew(0); - sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); - zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); - if( zFilename8 ){ - rc = openDatabase(zFilename8, ppDb, - SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); - assert( *ppDb || rc==SQLITE_NOMEM ); - if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ - SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE; - } - }else{ - rc = SQLITE_NOMEM_BKPT; - } - sqlite3ValueFree(pVal); - - return rc & 0xff; -} -#endif /* SQLITE_OMIT_UTF16 */ - -/* -** Register a new collation sequence with the database handle db. -*/ -SQLITE_API int sqlite3_create_collation( - sqlite3* db, - const char *zName, - int enc, - void* pCtx, - int(*xCompare)(void*,int,const void*,int,const void*) -){ - return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0); -} - -/* -** Register a new collation sequence with the database handle db. -*/ -SQLITE_API int sqlite3_create_collation_v2( - sqlite3* db, - const char *zName, - int enc, - void* pCtx, - int(*xCompare)(void*,int,const void*,int,const void*), - void(*xDel)(void*) -){ - int rc; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - assert( !db->mallocFailed ); - rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -#ifndef SQLITE_OMIT_UTF16 -/* -** Register a new collation sequence with the database handle db. -*/ -SQLITE_API int sqlite3_create_collation16( - sqlite3* db, - const void *zName, - int enc, - void* pCtx, - int(*xCompare)(void*,int,const void*,int,const void*) -){ - int rc = SQLITE_OK; - char *zName8; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - assert( !db->mallocFailed ); - zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE); - if( zName8 ){ - rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0); - sqlite3DbFree(db, zName8); - } - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} -#endif /* SQLITE_OMIT_UTF16 */ - -/* -** Register a collation sequence factory callback with the database handle -** db. Replace any previously installed collation sequence factory. -*/ -SQLITE_API int sqlite3_collation_needed( - sqlite3 *db, - void *pCollNeededArg, - void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - db->xCollNeeded = xCollNeeded; - db->xCollNeeded16 = 0; - db->pCollNeededArg = pCollNeededArg; - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -#ifndef SQLITE_OMIT_UTF16 -/* -** Register a collation sequence factory callback with the database handle -** db. Replace any previously installed collation sequence factory. -*/ -SQLITE_API int sqlite3_collation_needed16( - sqlite3 *db, - void *pCollNeededArg, - void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) -){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - db->xCollNeeded = 0; - db->xCollNeeded16 = xCollNeeded16; - db->pCollNeededArg = pCollNeededArg; - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} -#endif /* SQLITE_OMIT_UTF16 */ - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** This function is now an anachronism. It used to be used to recover from a -** malloc() failure, but SQLite now does this automatically. -*/ -SQLITE_API int sqlite3_global_recover(void){ - return SQLITE_OK; -} -#endif - -/* -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -*/ -SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - return db->autoCommit; -} - -/* -** The following routines are substitutes for constants SQLITE_CORRUPT, -** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error -** constants. They serve two purposes: -** -** 1. Serve as a convenient place to set a breakpoint in a debugger -** to detect when version error conditions occurs. -** -** 2. Invoke sqlite3_log() to provide the source code location where -** a low-level error is first detected. -*/ -SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){ - sqlite3_log(iErr, "%s at line %d of [%.10s]", - zType, lineno, 20+sqlite3_sourceid()); - return iErr; -} -SQLITE_PRIVATE int sqlite3CorruptError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption"); -} -SQLITE_PRIVATE int sqlite3MisuseError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse"); -} -SQLITE_PRIVATE int sqlite3CantopenError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file"); -} -#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO) -SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){ - char zMsg[100]; - sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno); - testcase( sqlite3GlobalConfig.xLog!=0 ); - return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg); -} -#endif -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3NomemError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM"); -} -SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error"); -} -#endif - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** This is a convenience routine that makes sure that all thread-specific -** data for this thread has been deallocated. -** -** SQLite no longer uses thread-specific data so this routine is now a -** no-op. It is retained for historical compatibility. -*/ -SQLITE_API void sqlite3_thread_cleanup(void){ -} -#endif - -/* -** Return meta information about a specific column of a database table. -** See comment in sqlite3.h (sqlite.h.in) for details. -*/ -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 */ -){ - int rc; - char *zErrMsg = 0; - Table *pTab = 0; - Column *pCol = 0; - int iCol = 0; - char const *zDataType = 0; - char const *zCollSeq = 0; - int notnull = 0; - int primarykey = 0; - int autoinc = 0; - - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){ - return SQLITE_MISUSE_BKPT; - } -#endif - - /* Ensure the database schema has been loaded */ - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeEnterAll(db); - rc = sqlite3Init(db, &zErrMsg); - if( SQLITE_OK!=rc ){ - goto error_out; - } - - /* Locate the table in question */ - pTab = sqlite3FindTable(db, zTableName, zDbName); - if( !pTab || pTab->pSelect ){ - pTab = 0; - goto error_out; - } - - /* Find the column for which info is requested */ - if( zColumnName==0 ){ - /* Query for existance of table only */ - }else{ - for(iCol=0; iColnCol; iCol++){ - pCol = &pTab->aCol[iCol]; - if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){ - break; - } - } - if( iCol==pTab->nCol ){ - if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ - iCol = pTab->iPKey; - pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; - }else{ - pTab = 0; - goto error_out; - } - } - } - - /* The following block stores the meta information that will be returned - ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey - ** and autoinc. At this point there are two possibilities: - ** - ** 1. The specified column name was rowid", "oid" or "_rowid_" - ** and there is no explicitly declared IPK column. - ** - ** 2. The table is not a view and the column name identified an - ** explicitly declared column. Copy meta information from *pCol. - */ - if( pCol ){ - zDataType = sqlite3ColumnType(pCol,0); - zCollSeq = pCol->zColl; - notnull = pCol->notNull!=0; - primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0; - autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0; - }else{ - zDataType = "INTEGER"; - primarykey = 1; - } - if( !zCollSeq ){ - zCollSeq = sqlite3StrBINARY; - } - -error_out: - sqlite3BtreeLeaveAll(db); - - /* Whether the function call succeeded or failed, set the output parameters - ** to whatever their local counterparts contain. If an error did occur, - ** this has the effect of zeroing all output parameters. - */ - if( pzDataType ) *pzDataType = zDataType; - if( pzCollSeq ) *pzCollSeq = zCollSeq; - if( pNotNull ) *pNotNull = notnull; - if( pPrimaryKey ) *pPrimaryKey = primarykey; - if( pAutoinc ) *pAutoinc = autoinc; - - if( SQLITE_OK==rc && !pTab ){ - sqlite3DbFree(db, zErrMsg); - zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, - zColumnName); - rc = SQLITE_ERROR; - } - sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg); - sqlite3DbFree(db, zErrMsg); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** Sleep for a little while. Return the amount of time slept. -*/ -SQLITE_API int sqlite3_sleep(int ms){ - sqlite3_vfs *pVfs; - int rc; - pVfs = sqlite3_vfs_find(0); - if( pVfs==0 ) return 0; - - /* This function works in milliseconds, but the underlying OsSleep() - ** API uses microseconds. Hence the 1000's. - */ - rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000); - return rc; -} - -/* -** Enable or disable the extended result codes. -*/ -SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - db->errMask = onoff ? 0xffffffff : 0xff; - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -/* -** Invoke the xFileControl method on a particular database. -*/ -SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){ - int rc = SQLITE_ERROR; - Btree *pBtree; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - pBtree = sqlite3DbNameToBtree(db, zDbName); - if( pBtree ){ - Pager *pPager; - sqlite3_file *fd; - sqlite3BtreeEnter(pBtree); - pPager = sqlite3BtreePager(pBtree); - assert( pPager!=0 ); - fd = sqlite3PagerFile(pPager); - assert( fd!=0 ); - if( op==SQLITE_FCNTL_FILE_POINTER ){ - *(sqlite3_file**)pArg = fd; - rc = SQLITE_OK; - }else if( op==SQLITE_FCNTL_VFS_POINTER ){ - *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager); - rc = SQLITE_OK; - }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){ - *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager); - rc = SQLITE_OK; - }else if( op==SQLITE_FCNTL_DATA_VERSION ){ - *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager); - rc = SQLITE_OK; - }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){ - int iNew = *(int*)pArg; - *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree); - if( iNew>=0 && iNew<=255 ){ - sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0); - } - rc = SQLITE_OK; - }else{ - rc = sqlite3OsFileControl(fd, op, pArg); - } - sqlite3BtreeLeave(pBtree); - } - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** Interface to the testing logic. -*/ -SQLITE_API int sqlite3_test_control(int op, ...){ - int rc = 0; -#ifdef SQLITE_UNTESTABLE - UNUSED_PARAMETER(op); -#else - va_list ap; - va_start(ap, op); - switch( op ){ - - /* - ** Save the current state of the PRNG. - */ - case SQLITE_TESTCTRL_PRNG_SAVE: { - sqlite3PrngSaveState(); - break; - } - - /* - ** Restore the state of the PRNG to the last state saved using - ** PRNG_SAVE. If PRNG_SAVE has never before been called, then - ** this verb acts like PRNG_RESET. - */ - case SQLITE_TESTCTRL_PRNG_RESTORE: { - sqlite3PrngRestoreState(); - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db); - ** - ** Control the seed for the pseudo-random number generator (PRNG) that - ** is built into SQLite. Cases: - ** - ** x!=0 && db!=0 Seed the PRNG to the current value of the - ** schema cookie in the main database for db, or - ** x if the schema cookie is zero. This case - ** is convenient to use with database fuzzers - ** as it allows the fuzzer some control over the - ** the PRNG seed. - ** - ** x!=0 && db==0 Seed the PRNG to the value of x. - ** - ** x==0 && db==0 Revert to default behavior of using the - ** xRandomness method on the primary VFS. - ** - ** This test-control also resets the PRNG so that the new seed will - ** be used for the next call to sqlite3_randomness(). - */ -#ifndef SQLITE_OMIT_WSD - case SQLITE_TESTCTRL_PRNG_SEED: { - int x = va_arg(ap, int); - int y; - sqlite3 *db = va_arg(ap, sqlite3*); - assert( db==0 || db->aDb[0].pSchema!=0 ); - if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; } - sqlite3Config.iPrngSeed = x; - sqlite3_randomness(0,0); - break; - } -#endif - - /* - ** sqlite3_test_control(BITVEC_TEST, size, program) - ** - ** Run a test against a Bitvec object of size. The program argument - ** is an array of integers that defines the test. Return -1 on a - ** memory allocation error, 0 on success, or non-zero for an error. - ** See the sqlite3BitvecBuiltinTest() for additional information. - */ - case SQLITE_TESTCTRL_BITVEC_TEST: { - int sz = va_arg(ap, int); - int *aProg = va_arg(ap, int*); - rc = sqlite3BitvecBuiltinTest(sz, aProg); - break; - } - - /* - ** sqlite3_test_control(FAULT_INSTALL, xCallback) - ** - ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called, - ** if xCallback is not NULL. - ** - ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0) - ** is called immediately after installing the new callback and the return - ** value from sqlite3FaultSim(0) becomes the return from - ** sqlite3_test_control(). - */ - case SQLITE_TESTCTRL_FAULT_INSTALL: { - /* MSVC is picky about pulling func ptrs from va lists. - ** http://support.microsoft.com/kb/47961 - ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int)); - */ - typedef int(*TESTCALLBACKFUNC_t)(int); - sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t); - rc = sqlite3FaultSim(0); - break; - } - - /* - ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) - ** - ** Register hooks to call to indicate which malloc() failures - ** are benign. - */ - case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { - typedef void (*void_function)(void); - void_function xBenignBegin; - void_function xBenignEnd; - xBenignBegin = va_arg(ap, void_function); - xBenignEnd = va_arg(ap, void_function); - sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); - break; - } - - /* - ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X) - ** - ** Set the PENDING byte to the value in the argument, if X>0. - ** Make no changes if X==0. Return the value of the pending byte - ** as it existing before this routine was called. - ** - ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in - ** an incompatible database file format. Changing the PENDING byte - ** while any database connection is open results in undefined and - ** deleterious behavior. - */ - case SQLITE_TESTCTRL_PENDING_BYTE: { - rc = PENDING_BYTE; -#ifndef SQLITE_OMIT_WSD - { - unsigned int newVal = va_arg(ap, unsigned int); - if( newVal ) sqlite3PendingByte = newVal; - } -#endif - break; - } - - /* - ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X) - ** - ** This action provides a run-time test to see whether or not - ** assert() was enabled at compile-time. If X is true and assert() - ** is enabled, then the return value is true. If X is true and - ** assert() is disabled, then the return value is zero. If X is - ** false and assert() is enabled, then the assertion fires and the - ** process aborts. If X is false and assert() is disabled, then the - ** return value is zero. - */ - case SQLITE_TESTCTRL_ASSERT: { - volatile int x = 0; - assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 ); - rc = x; - break; - } - - - /* - ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X) - ** - ** This action provides a run-time test to see how the ALWAYS and - ** NEVER macros were defined at compile-time. - ** - ** The return value is ALWAYS(X) if X is true, or 0 if X is false. - ** - ** The recommended test is X==2. If the return value is 2, that means - ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the - ** default setting. If the return value is 1, then ALWAYS() is either - ** hard-coded to true or else it asserts if its argument is false. - ** The first behavior (hard-coded to true) is the case if - ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second - ** behavior (assert if the argument to ALWAYS() is false) is the case if - ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled. - ** - ** The run-time test procedure might look something like this: - ** - ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){ - ** // ALWAYS() and NEVER() are no-op pass-through macros - ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){ - ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false. - ** }else{ - ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0. - ** } - */ - case SQLITE_TESTCTRL_ALWAYS: { - int x = va_arg(ap,int); - rc = x ? ALWAYS(x) : 0; - break; - } - - /* - ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER); - ** - ** The integer returned reveals the byte-order of the computer on which - ** SQLite is running: - ** - ** 1 big-endian, determined at run-time - ** 10 little-endian, determined at run-time - ** 432101 big-endian, determined at compile-time - ** 123410 little-endian, determined at compile-time - */ - case SQLITE_TESTCTRL_BYTEORDER: { - rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN; - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) - ** - ** Enable or disable various optimizations for testing purposes. The - ** argument N is a bitmask of optimizations to be disabled. For normal - ** operation N should be 0. The idea is that a test program (like the - ** SQL Logic Test or SLT test module) can run the same SQL multiple times - ** with various optimizations disabled to verify that the same answer - ** is obtained in every case. - */ - case SQLITE_TESTCTRL_OPTIMIZATIONS: { - sqlite3 *db = va_arg(ap, sqlite3*); - db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); - ** - ** If parameter onoff is non-zero, subsequent calls to localtime() - ** and its variants fail. If onoff is zero, undo this setting. - */ - case SQLITE_TESTCTRL_LOCALTIME_FAULT: { - sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*); - ** - ** Toggle the ability to use internal functions on or off for - ** the database connection given in the argument. - */ - case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: { - sqlite3 *db = va_arg(ap, sqlite3*); - db->mDbFlags ^= DBFLAG_InternalFunc; - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int); - ** - ** Set or clear a flag that indicates that the database file is always well- - ** formed and never corrupt. This flag is clear by default, indicating that - ** database files might have arbitrary corruption. Setting the flag during - ** testing causes certain assert() statements in the code to be activated - ** that demonstrat invariants on well-formed database files. - */ - case SQLITE_TESTCTRL_NEVER_CORRUPT: { - sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int); - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int); - ** - ** Set or clear a flag that causes SQLite to verify that type, name, - ** and tbl_name fields of the sqlite_schema table. This is normally - ** on, but it is sometimes useful to turn it off for testing. - ** - ** 2020-07-22: Disabling EXTRA_SCHEMA_CHECKS also disables the - ** verification of rootpage numbers when parsing the schema. This - ** is useful to make it easier to reach strange internal error states - ** during testing. The EXTRA_SCHEMA_CHECKS setting is always enabled - ** in production. - */ - case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: { - sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int); - break; - } - - /* Set the threshold at which OP_Once counters reset back to zero. - ** By default this is 0x7ffffffe (over 2 billion), but that value is - ** too big to test in a reasonable amount of time, so this control is - ** provided to set a small and easily reachable reset value. - */ - case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: { - sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int); - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr); - ** - ** Set the VDBE coverage callback function to xCallback with context - ** pointer ptr. - */ - case SQLITE_TESTCTRL_VDBE_COVERAGE: { -#ifdef SQLITE_VDBE_COVERAGE - typedef void (*branch_callback)(void*,unsigned int, - unsigned char,unsigned char); - sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback); - sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*); -#endif - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */ - case SQLITE_TESTCTRL_SORTER_MMAP: { - sqlite3 *db = va_arg(ap, sqlite3*); - db->nMaxSorterMmap = va_arg(ap, int); - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT); - ** - ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if - ** not. - */ - case SQLITE_TESTCTRL_ISINIT: { - if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR; - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); - ** - ** This test control is used to create imposter tables. "db" is a pointer - ** to the database connection. dbName is the database name (ex: "main" or - ** "temp") which will receive the imposter. "onOff" turns imposter mode on - ** or off. "tnum" is the root page of the b-tree to which the imposter - ** table should connect. - ** - ** Enable imposter mode only when the schema has already been parsed. Then - ** run a single CREATE TABLE statement to construct the imposter table in - ** the parsed schema. Then turn imposter mode back off again. - ** - ** If onOff==0 and tnum>0 then reset the schema for all databases, causing - ** the schema to be reparsed the next time it is needed. This has the - ** effect of erasing all imposter tables. - */ - case SQLITE_TESTCTRL_IMPOSTER: { - sqlite3 *db = va_arg(ap, sqlite3*); - sqlite3_mutex_enter(db->mutex); - db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*)); - db->init.busy = db->init.imposterTable = va_arg(ap,int); - db->init.newTnum = va_arg(ap,int); - if( db->init.busy==0 && db->init.newTnum>0 ){ - sqlite3ResetAllSchemasOfConnection(db); - } - sqlite3_mutex_leave(db->mutex); - break; - } - -#if defined(YYCOVERAGE) - /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out) - ** - ** This test control (only available when SQLite is compiled with - ** -DYYCOVERAGE) writes a report onto "out" that shows all - ** state/lookahead combinations in the parser state machine - ** which are never exercised. If any state is missed, make the - ** return code SQLITE_ERROR. - */ - case SQLITE_TESTCTRL_PARSER_COVERAGE: { - FILE *out = va_arg(ap, FILE*); - if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR; - break; - } -#endif /* defined(YYCOVERAGE) */ - - /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*); - ** - ** This test-control causes the most recent sqlite3_result_int64() value - ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally, - ** MEM_IntReal values only arise during an INSERT operation of integer - ** values into a REAL column, so they can be challenging to test. This - ** test-control enables us to write an intreal() SQL function that can - ** inject an intreal() value at arbitrary places in an SQL statement, - ** for testing purposes. - */ - case SQLITE_TESTCTRL_RESULT_INTREAL: { - sqlite3_context *pCtx = va_arg(ap, sqlite3_context*); - sqlite3ResultIntReal(pCtx); - break; - } - } - va_end(ap); -#endif /* SQLITE_UNTESTABLE */ - return rc; -} - -/* -** The Pager stores the Database filename, Journal filename, and WAL filename -** consecutively in memory, in that order. The database filename is prefixed -** by four zero bytes. Locate the start of the database filename by searching -** backwards for the first byte following four consecutive zero bytes. -** -** This only works if the filename passed in was obtained from the Pager. -*/ -static const char *databaseName(const char *zName){ - while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){ - zName--; - } - return zName; -} - -/* -** Append text z[] to the end of p[]. Return a pointer to the first -** character after then zero terminator on the new text in p[]. -*/ -static char *appendText(char *p, const char *z){ - size_t n = strlen(z); - memcpy(p, z, n+1); - return p+n+1; -} - -/* -** Allocate memory to hold names for a database, journal file, WAL file, -** and query parameters. The pointer returned is valid for use by -** sqlite3_filename_database() and sqlite3_uri_parameter() and related -** functions. -** -** Memory layout must be compatible with that generated by the pager -** and expected by sqlite3_uri_parameter() and databaseName(). -*/ -SQLITE_API char *sqlite3_create_filename( - const char *zDatabase, - const char *zJournal, - const char *zWal, - int nParam, - const char **azParam -){ - sqlite3_int64 nByte; - int i; - char *pResult, *p; - nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10; - for(i=0; i0 ){ - zFilename += sqlite3Strlen30(zFilename) + 1; - zFilename += sqlite3Strlen30(zFilename) + 1; - } - return zFilename[0] ? zFilename : 0; -} - -/* -** Return a boolean value for a query parameter. -*/ -SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){ - const char *z = sqlite3_uri_parameter(zFilename, zParam); - bDflt = bDflt!=0; - return z ? sqlite3GetBoolean(z, bDflt) : bDflt; -} - -/* -** Return a 64-bit integer value for a query parameter. -*/ -SQLITE_API sqlite3_int64 sqlite3_uri_int64( - const char *zFilename, /* Filename as passed to xOpen */ - const char *zParam, /* URI parameter sought */ - sqlite3_int64 bDflt /* return if parameter is missing */ -){ - const char *z = sqlite3_uri_parameter(zFilename, zParam); - sqlite3_int64 v; - if( z && sqlite3DecOrHexToI64(z, &v)==0 ){ - bDflt = v; - } - return bDflt; -} - -/* -** Translate a filename that was handed to a VFS routine into the corresponding -** database, journal, or WAL file. -** -** It is an error to pass this routine a filename string that was not -** passed into the VFS from the SQLite core. Doing so is similar to -** passing free() a pointer that was not obtained from malloc() - it is -** an error that we cannot easily detect but that will likely cause memory -** corruption. -*/ -SQLITE_API const char *sqlite3_filename_database(const char *zFilename){ - return databaseName(zFilename); -} -SQLITE_API const char *sqlite3_filename_journal(const char *zFilename){ - zFilename = databaseName(zFilename); - zFilename += sqlite3Strlen30(zFilename) + 1; - while( zFilename[0] ){ - zFilename += sqlite3Strlen30(zFilename) + 1; - zFilename += sqlite3Strlen30(zFilename) + 1; - } - return zFilename + 1; -} -SQLITE_API const char *sqlite3_filename_wal(const char *zFilename){ -#ifdef SQLITE_OMIT_WAL - return 0; -#else - zFilename = sqlite3_filename_journal(zFilename); - zFilename += sqlite3Strlen30(zFilename) + 1; - return zFilename; -#endif -} - -/* -** Return the Btree pointer identified by zDbName. Return NULL if not found. -*/ -SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ - int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0; - return iDb<0 ? 0 : db->aDb[iDb].pBt; -} - -/* -** Return the filename of the database associated with a database -** connection. -*/ -SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){ - Btree *pBt; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - pBt = sqlite3DbNameToBtree(db, zDbName); - return pBt ? sqlite3BtreeGetFilename(pBt) : 0; -} - -/* -** Return 1 if database is read-only or 0 if read/write. Return -1 if -** no such database exists. -*/ -SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){ - Btree *pBt; -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - (void)SQLITE_MISUSE_BKPT; - return -1; - } -#endif - pBt = sqlite3DbNameToBtree(db, zDbName); - return pBt ? sqlite3BtreeIsReadonly(pBt) : -1; -} - -#ifdef SQLITE_ENABLE_SNAPSHOT -/* -** Obtain a snapshot handle for the snapshot of database zDb currently -** being read by handle db. -*/ -SQLITE_API int sqlite3_snapshot_get( - sqlite3 *db, - const char *zDb, - sqlite3_snapshot **ppSnapshot -){ - int rc = SQLITE_ERROR; -#ifndef SQLITE_OMIT_WAL - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - - if( db->autoCommit==0 ){ - int iDb = sqlite3FindDbName(db, zDb); - if( iDb==0 || iDb>1 ){ - Btree *pBt = db->aDb[iDb].pBt; - if( 0==sqlite3BtreeIsInTrans(pBt) ){ - rc = sqlite3BtreeBeginTrans(pBt, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot); - } - } - } - } - - sqlite3_mutex_leave(db->mutex); -#endif /* SQLITE_OMIT_WAL */ - return rc; -} - -/* -** Open a read-transaction on the snapshot idendified by pSnapshot. -*/ -SQLITE_API int sqlite3_snapshot_open( - sqlite3 *db, - const char *zDb, - sqlite3_snapshot *pSnapshot -){ - int rc = SQLITE_ERROR; -#ifndef SQLITE_OMIT_WAL - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - if( db->autoCommit==0 ){ - int iDb; - iDb = sqlite3FindDbName(db, zDb); - if( iDb==0 || iDb>1 ){ - Btree *pBt = db->aDb[iDb].pBt; - if( sqlite3BtreeIsInTrans(pBt)==0 ){ - Pager *pPager = sqlite3BtreePager(pBt); - int bUnlock = 0; - if( sqlite3BtreeIsInReadTrans(pBt) ){ - if( db->nVdbeActive==0 ){ - rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot); - if( rc==SQLITE_OK ){ - bUnlock = 1; - rc = sqlite3BtreeCommit(pBt); - } - } - }else{ - rc = SQLITE_OK; - } - if( rc==SQLITE_OK ){ - rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot); - } - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeBeginTrans(pBt, 0, 0); - sqlite3PagerSnapshotOpen(pPager, 0); - } - if( bUnlock ){ - sqlite3PagerSnapshotUnlock(pPager); - } - } - } - } - - sqlite3_mutex_leave(db->mutex); -#endif /* SQLITE_OMIT_WAL */ - return rc; -} - -/* -** Recover as many snapshots as possible from the wal file associated with -** schema zDb of database db. -*/ -SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){ - int rc = SQLITE_ERROR; - int iDb; -#ifndef SQLITE_OMIT_WAL - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ){ - return SQLITE_MISUSE_BKPT; - } -#endif - - sqlite3_mutex_enter(db->mutex); - iDb = sqlite3FindDbName(db, zDb); - if( iDb==0 || iDb>1 ){ - Btree *pBt = db->aDb[iDb].pBt; - if( 0==sqlite3BtreeIsInReadTrans(pBt) ){ - rc = sqlite3BtreeBeginTrans(pBt, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt)); - sqlite3BtreeCommit(pBt); - } - } - } - sqlite3_mutex_leave(db->mutex); -#endif /* SQLITE_OMIT_WAL */ - return rc; -} - -/* -** Free a snapshot handle obtained from sqlite3_snapshot_get(). -*/ -SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){ - sqlite3_free(pSnapshot); -} -#endif /* SQLITE_ENABLE_SNAPSHOT */ - -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -/* -** Given the name of a compile-time option, return true if that option -** was used and false if not. -** -** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix -** is not required for a match. -*/ -SQLITE_API int sqlite3_compileoption_used(const char *zOptName){ - int i, n; - int nOpt; - const char **azCompileOpt; - -#if SQLITE_ENABLE_API_ARMOR - if( zOptName==0 ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - - azCompileOpt = sqlite3CompileOptions(&nOpt); - - if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7; - n = sqlite3Strlen30(zOptName); - - /* Since nOpt is normally in single digits, a linear search is - ** adequate. No need for a binary search. */ - for(i=0; i=0 && NpNextBlocked){ - int seen = 0; - sqlite3 *p2; - - /* Verify property (1) */ - assert( p->pUnlockConnection || p->pBlockingConnection ); - - /* Verify property (2) */ - for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){ - if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1; - assert( p2->xUnlockNotify==p->xUnlockNotify || !seen ); - assert( db==0 || p->pUnlockConnection!=db ); - assert( db==0 || p->pBlockingConnection!=db ); - } - } -} -#else -# define checkListProperties(x) -#endif - -/* -** Remove connection db from the blocked connections list. If connection -** db is not currently a part of the list, this function is a no-op. -*/ -static void removeFromBlockedList(sqlite3 *db){ - sqlite3 **pp; - assertMutexHeld(); - for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){ - if( *pp==db ){ - *pp = (*pp)->pNextBlocked; - break; - } - } -} - -/* -** Add connection db to the blocked connections list. It is assumed -** that it is not already a part of the list. -*/ -static void addToBlockedList(sqlite3 *db){ - sqlite3 **pp; - assertMutexHeld(); - for( - pp=&sqlite3BlockedList; - *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; - pp=&(*pp)->pNextBlocked - ); - db->pNextBlocked = *pp; - *pp = db; -} - -/* -** Obtain the STATIC_MAIN mutex. -*/ -static void enterMutex(void){ - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)); - checkListProperties(0); -} - -/* -** Release the STATIC_MAIN mutex. -*/ -static void leaveMutex(void){ - assertMutexHeld(); - checkListProperties(0); - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)); -} - -/* -** Register an unlock-notify callback. -** -** This is called after connection "db" has attempted some operation -** but has received an SQLITE_LOCKED error because another connection -** (call it pOther) in the same process was busy using the same shared -** cache. pOther is found by looking at db->pBlockingConnection. -** -** If there is no blocking connection, the callback is invoked immediately, -** before this routine returns. -** -** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate -** a deadlock. -** -** Otherwise, make arrangements to invoke xNotify when pOther drops -** its locks. -** -** Each call to this routine overrides any prior callbacks registered -** on the same "db". If xNotify==0 then any prior callbacks are immediately -** cancelled. -*/ -SQLITE_API int sqlite3_unlock_notify( - sqlite3 *db, - void (*xNotify)(void **, int), - void *pArg -){ - int rc = SQLITE_OK; - - sqlite3_mutex_enter(db->mutex); - enterMutex(); - - if( xNotify==0 ){ - removeFromBlockedList(db); - db->pBlockingConnection = 0; - db->pUnlockConnection = 0; - db->xUnlockNotify = 0; - db->pUnlockArg = 0; - }else if( 0==db->pBlockingConnection ){ - /* The blocking transaction has been concluded. Or there never was a - ** blocking transaction. In either case, invoke the notify callback - ** immediately. - */ - xNotify(&pArg, 1); - }else{ - sqlite3 *p; - - for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){} - if( p ){ - rc = SQLITE_LOCKED; /* Deadlock detected. */ - }else{ - db->pUnlockConnection = db->pBlockingConnection; - db->xUnlockNotify = xNotify; - db->pUnlockArg = pArg; - removeFromBlockedList(db); - addToBlockedList(db); - } - } - - leaveMutex(); - assert( !db->mallocFailed ); - sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0)); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -/* -** This function is called while stepping or preparing a statement -** associated with connection db. The operation will return SQLITE_LOCKED -** to the user because it requires a lock that will not be available -** until connection pBlocker concludes its current transaction. -*/ -SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){ - enterMutex(); - if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){ - addToBlockedList(db); - } - db->pBlockingConnection = pBlocker; - leaveMutex(); -} - -/* -** This function is called when -** the transaction opened by database db has just finished. Locks held -** by database connection db have been released. -** -** This function loops through each entry in the blocked connections -** list and does the following: -** -** 1) If the sqlite3.pBlockingConnection member of a list entry is -** set to db, then set pBlockingConnection=0. -** -** 2) If the sqlite3.pUnlockConnection member of a list entry is -** set to db, then invoke the configured unlock-notify callback and -** set pUnlockConnection=0. -** -** 3) If the two steps above mean that pBlockingConnection==0 and -** pUnlockConnection==0, remove the entry from the blocked connections -** list. -*/ -SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){ - void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */ - int nArg = 0; /* Number of entries in aArg[] */ - sqlite3 **pp; /* Iterator variable */ - void **aArg; /* Arguments to the unlock callback */ - void **aDyn = 0; /* Dynamically allocated space for aArg[] */ - void *aStatic[16]; /* Starter space for aArg[]. No malloc required */ - - aArg = aStatic; - enterMutex(); /* Enter STATIC_MAIN mutex */ - - /* This loop runs once for each entry in the blocked-connections list. */ - for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ - sqlite3 *p = *pp; - - /* Step 1. */ - if( p->pBlockingConnection==db ){ - p->pBlockingConnection = 0; - } - - /* Step 2. */ - if( p->pUnlockConnection==db ){ - assert( p->xUnlockNotify ); - if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ - xUnlockNotify(aArg, nArg); - nArg = 0; - } - - sqlite3BeginBenignMalloc(); - assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); - assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); - if( (!aDyn && nArg==(int)ArraySize(aStatic)) - || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*))) - ){ - /* The aArg[] array needs to grow. */ - void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2); - if( pNew ){ - memcpy(pNew, aArg, nArg*sizeof(void *)); - sqlite3_free(aDyn); - aDyn = aArg = pNew; - }else{ - /* This occurs when the array of context pointers that need to - ** be passed to the unlock-notify callback is larger than the - ** aStatic[] array allocated on the stack and the attempt to - ** allocate a larger array from the heap has failed. - ** - ** This is a difficult situation to handle. Returning an error - ** code to the caller is insufficient, as even if an error code - ** is returned the transaction on connection db will still be - ** closed and the unlock-notify callbacks on blocked connections - ** will go unissued. This might cause the application to wait - ** indefinitely for an unlock-notify callback that will never - ** arrive. - ** - ** Instead, invoke the unlock-notify callback with the context - ** array already accumulated. We can then clear the array and - ** begin accumulating any further context pointers without - ** requiring any dynamic allocation. This is sub-optimal because - ** it means that instead of one callback with a large array of - ** context pointers the application will receive two or more - ** callbacks with smaller arrays of context pointers, which will - ** reduce the applications ability to prioritize multiple - ** connections. But it is the best that can be done under the - ** circumstances. - */ - xUnlockNotify(aArg, nArg); - nArg = 0; - } - } - sqlite3EndBenignMalloc(); - - aArg[nArg++] = p->pUnlockArg; - xUnlockNotify = p->xUnlockNotify; - p->pUnlockConnection = 0; - p->xUnlockNotify = 0; - p->pUnlockArg = 0; - } - - /* Step 3. */ - if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){ - /* Remove connection p from the blocked connections list. */ - *pp = p->pNextBlocked; - p->pNextBlocked = 0; - }else{ - pp = &p->pNextBlocked; - } - } - - if( nArg!=0 ){ - xUnlockNotify(aArg, nArg); - } - sqlite3_free(aDyn); - leaveMutex(); /* Leave STATIC_MAIN mutex */ -} - -/* -** This is called when the database connection passed as an argument is -** being closed. The connection is removed from the blocked list. -*/ -SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ - sqlite3ConnectionUnlocked(db); - enterMutex(); - removeFromBlockedList(db); - checkListProperties(db); - leaveMutex(); -} -#endif - -/************** End of notify.c **********************************************/ -/************** Begin file fts3.c ********************************************/ -/* -** 2006 Oct 10 -** -** 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 an SQLite module implementing full-text search. -*/ - -/* -** The code in this file is only compiled if: -** -** * The FTS3 module is being built as an extension -** (in which case SQLITE_CORE is not defined), or -** -** * The FTS3 module is being built into the core of -** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). -*/ - -/* The full-text index is stored in a series of b+tree (-like) -** structures called segments which map terms to doclists. The -** structures are like b+trees in layout, but are constructed from the -** bottom up in optimal fashion and are not updatable. Since trees -** are built from the bottom up, things will be described from the -** bottom up. -** -** -**** Varints **** -** The basic unit of encoding is a variable-length integer called a -** varint. We encode variable-length integers in little-endian order -** using seven bits * per byte as follows: -** -** KEY: -** A = 0xxxxxxx 7 bits of data and one flag bit -** B = 1xxxxxxx 7 bits of data and one flag bit -** -** 7 bits - A -** 14 bits - BA -** 21 bits - BBA -** and so on. -** -** This is similar in concept to how sqlite encodes "varints" but -** the encoding is not the same. SQLite varints are big-endian -** are are limited to 9 bytes in length whereas FTS3 varints are -** little-endian and can be up to 10 bytes in length (in theory). -** -** Example encodings: -** -** 1: 0x01 -** 127: 0x7f -** 128: 0x81 0x00 -** -** -**** Document lists **** -** A doclist (document list) holds a docid-sorted list of hits for a -** given term. Doclists hold docids and associated token positions. -** A docid is the unique integer identifier for a single document. -** A position is the index of a word within the document. The first -** word of the document has a position of 0. -** -** FTS3 used to optionally store character offsets using a compile-time -** option. But that functionality is no longer supported. -** -** A doclist is stored like this: -** -** array { -** varint docid; (delta from previous doclist) -** array { (position list for column 0) -** varint position; (2 more than the delta from previous position) -** } -** array { -** varint POS_COLUMN; (marks start of position list for new column) -** varint column; (index of new column) -** array { -** varint position; (2 more than the delta from previous position) -** } -** } -** varint POS_END; (marks end of positions for this document. -** } -** -** Here, array { X } means zero or more occurrences of X, adjacent in -** memory. A "position" is an index of a token in the token stream -** generated by the tokenizer. Note that POS_END and POS_COLUMN occur -** in the same logical place as the position element, and act as sentinals -** ending a position list array. POS_END is 0. POS_COLUMN is 1. -** The positions numbers are not stored literally but rather as two more -** than the difference from the prior position, or the just the position plus -** 2 for the first position. Example: -** -** label: A B C D E F G H I J K -** value: 123 5 9 1 1 14 35 0 234 72 0 -** -** The 123 value is the first docid. For column zero in this document -** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1 -** at D signals the start of a new column; the 1 at E indicates that the -** new column is column number 1. There are two positions at 12 and 45 -** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The -** 234 at I is the delta to next docid (357). It has one position 70 -** (72-2) and then terminates with the 0 at K. -** -** A "position-list" is the list of positions for multiple columns for -** a single docid. A "column-list" is the set of positions for a single -** column. Hence, a position-list consists of one or more column-lists, -** a document record consists of a docid followed by a position-list and -** a doclist consists of one or more document records. -** -** A bare doclist omits the position information, becoming an -** array of varint-encoded docids. -** -**** Segment leaf nodes **** -** Segment leaf nodes store terms and doclists, ordered by term. Leaf -** nodes are written using LeafWriter, and read using LeafReader (to -** iterate through a single leaf node's data) and LeavesReader (to -** iterate through a segment's entire leaf layer). Leaf nodes have -** the format: -** -** varint iHeight; (height from leaf level, always 0) -** varint nTerm; (length of first term) -** char pTerm[nTerm]; (content of first term) -** varint nDoclist; (length of term's associated doclist) -** char pDoclist[nDoclist]; (content of doclist) -** array { -** (further terms are delta-encoded) -** varint nPrefix; (length of prefix shared with previous term) -** varint nSuffix; (length of unshared suffix) -** char pTermSuffix[nSuffix];(unshared suffix of next term) -** varint nDoclist; (length of term's associated doclist) -** char pDoclist[nDoclist]; (content of doclist) -** } -** -** Here, array { X } means zero or more occurrences of X, adjacent in -** memory. -** -** Leaf nodes are broken into blocks which are stored contiguously in -** the %_segments table in sorted order. This means that when the end -** of a node is reached, the next term is in the node with the next -** greater node id. -** -** New data is spilled to a new leaf node when the current node -** exceeds LEAF_MAX bytes (default 2048). New data which itself is -** larger than STANDALONE_MIN (default 1024) is placed in a standalone -** node (a leaf node with a single term and doclist). The goal of -** these settings is to pack together groups of small doclists while -** making it efficient to directly access large doclists. The -** assumption is that large doclists represent terms which are more -** likely to be query targets. -** -** TODO(shess) It may be useful for blocking decisions to be more -** dynamic. For instance, it may make more sense to have a 2.5k leaf -** node rather than splitting into 2k and .5k nodes. My intuition is -** that this might extend through 2x or 4x the pagesize. -** -** -**** Segment interior nodes **** -** Segment interior nodes store blockids for subtree nodes and terms -** to describe what data is stored by the each subtree. Interior -** nodes are written using InteriorWriter, and read using -** InteriorReader. InteriorWriters are created as needed when -** SegmentWriter creates new leaf nodes, or when an interior node -** itself grows too big and must be split. The format of interior -** nodes: -** -** varint iHeight; (height from leaf level, always >0) -** varint iBlockid; (block id of node's leftmost subtree) -** optional { -** varint nTerm; (length of first term) -** char pTerm[nTerm]; (content of first term) -** array { -** (further terms are delta-encoded) -** varint nPrefix; (length of shared prefix with previous term) -** varint nSuffix; (length of unshared suffix) -** char pTermSuffix[nSuffix]; (unshared suffix of next term) -** } -** } -** -** Here, optional { X } means an optional element, while array { X } -** means zero or more occurrences of X, adjacent in memory. -** -** An interior node encodes n terms separating n+1 subtrees. The -** subtree blocks are contiguous, so only the first subtree's blockid -** is encoded. The subtree at iBlockid will contain all terms less -** than the first term encoded (or all terms if no term is encoded). -** Otherwise, for terms greater than or equal to pTerm[i] but less -** than pTerm[i+1], the subtree for that term will be rooted at -** iBlockid+i. Interior nodes only store enough term data to -** distinguish adjacent children (if the rightmost term of the left -** child is "something", and the leftmost term of the right child is -** "wicked", only "w" is stored). -** -** New data is spilled to a new interior node at the same height when -** the current node exceeds INTERIOR_MAX bytes (default 2048). -** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing -** interior nodes and making the tree too skinny. The interior nodes -** at a given height are naturally tracked by interior nodes at -** height+1, and so on. -** -** -**** Segment directory **** -** The segment directory in table %_segdir stores meta-information for -** merging and deleting segments, and also the root node of the -** segment's tree. -** -** The root node is the top node of the segment's tree after encoding -** the entire segment, restricted to ROOT_MAX bytes (default 1024). -** This could be either a leaf node or an interior node. If the top -** node requires more than ROOT_MAX bytes, it is flushed to %_segments -** and a new root interior node is generated (which should always fit -** within ROOT_MAX because it only needs space for 2 varints, the -** height and the blockid of the previous root). -** -** The meta-information in the segment directory is: -** level - segment level (see below) -** idx - index within level -** - (level,idx uniquely identify a segment) -** start_block - first leaf node -** leaves_end_block - last leaf node -** end_block - last block (including interior nodes) -** root - contents of root node -** -** If the root node is a leaf node, then start_block, -** leaves_end_block, and end_block are all 0. -** -** -**** Segment merging **** -** To amortize update costs, segments are grouped into levels and -** merged in batches. Each increase in level represents exponentially -** more documents. -** -** New documents (actually, document updates) are tokenized and -** written individually (using LeafWriter) to a level 0 segment, with -** incrementing idx. When idx reaches MERGE_COUNT (default 16), all -** level 0 segments are merged into a single level 1 segment. Level 1 -** is populated like level 0, and eventually MERGE_COUNT level 1 -** segments are merged to a single level 2 segment (representing -** MERGE_COUNT^2 updates), and so on. -** -** A segment merge traverses all segments at a given level in -** parallel, performing a straightforward sorted merge. Since segment -** leaf nodes are written in to the %_segments table in order, this -** merge traverses the underlying sqlite disk structures efficiently. -** After the merge, all segment blocks from the merged level are -** deleted. -** -** MERGE_COUNT controls how often we merge segments. 16 seems to be -** somewhat of a sweet spot for insertion performance. 32 and 64 show -** very similar performance numbers to 16 on insertion, though they're -** a tiny bit slower (perhaps due to more overhead in merge-time -** sorting). 8 is about 20% slower than 16, 4 about 50% slower than -** 16, 2 about 66% slower than 16. -** -** At query time, high MERGE_COUNT increases the number of segments -** which need to be scanned and merged. For instance, with 100k docs -** inserted: -** -** MERGE_COUNT segments -** 16 25 -** 8 12 -** 4 10 -** 2 6 -** -** This appears to have only a moderate impact on queries for very -** frequent terms (which are somewhat dominated by segment merge -** costs), and infrequent and non-existent terms still seem to be fast -** even with many segments. -** -** TODO(shess) That said, it would be nice to have a better query-side -** argument for MERGE_COUNT of 16. Also, it is possible/likely that -** optimizations to things like doclist merging will swing the sweet -** spot around. -** -** -** -**** Handling of deletions and updates **** -** Since we're using a segmented structure, with no docid-oriented -** index into the term index, we clearly cannot simply update the term -** index when a document is deleted or updated. For deletions, we -** write an empty doclist (varint(docid) varint(POS_END)), for updates -** we simply write the new doclist. Segment merges overwrite older -** data for a particular docid with newer data, so deletes or updates -** will eventually overtake the earlier data and knock it out. The -** query logic likewise merges doclists so that newer data knocks out -** older data. -*/ - -/************** Include fts3Int.h in the middle of fts3.c ********************/ -/************** Begin file fts3Int.h *****************************************/ -/* -** 2009 Nov 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. -** -****************************************************************************** -** -*/ -#ifndef _FTSINT_H -#define _FTSINT_H - -#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) -# define NDEBUG 1 -#endif - -/* FTS3/FTS4 require virtual tables */ -#ifdef 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 all -** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. -*/ -#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) -# define SQLITE_ENABLE_FTS3 -#endif - -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* If not building as part of the core, include sqlite3ext.h. */ -#ifndef SQLITE_CORE -/* # include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT3 -#endif - -/* #include "sqlite3.h" */ -/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/ -/************** Begin file fts3_tokenizer.h **********************************/ -/* -** 2006 July 10 -** -** The author disclaims copyright to this source code. -** -************************************************************************* -** Defines the interface to tokenizers used by fulltext-search. There -** are three basic components: -** -** sqlite3_tokenizer_module is a singleton defining the tokenizer -** interface functions. This is essentially the class structure for -** tokenizers. -** -** sqlite3_tokenizer is used to define a particular tokenizer, perhaps -** including customization information defined at creation time. -** -** sqlite3_tokenizer_cursor is generated by a tokenizer to generate -** tokens from a particular input. -*/ -#ifndef _FTS3_TOKENIZER_H_ -#define _FTS3_TOKENIZER_H_ - -/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. -** If tokenizers are to be allowed to call sqlite3_*() functions, then -** we will need a way to register the API consistently. -*/ -/* #include "sqlite3.h" */ - -/* -** Structures used by the tokenizer interface. When a new tokenizer -** implementation is registered, the caller provides a pointer to -** an sqlite3_tokenizer_module containing pointers to the callback -** functions that make up an implementation. -** -** When an fts3 table is created, it passes any arguments passed to -** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the -** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer -** implementation. The xCreate() function in turn returns an -** sqlite3_tokenizer structure representing the specific tokenizer to -** be used for the fts3 table (customized by the tokenizer clause arguments). -** -** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() -** method is called. It returns an sqlite3_tokenizer_cursor object -** that may be used to tokenize a specific input buffer based on -** the tokenization rules supplied by a specific sqlite3_tokenizer -** object. -*/ -typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; -typedef struct sqlite3_tokenizer sqlite3_tokenizer; -typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; - -struct sqlite3_tokenizer_module { - - /* - ** Structure version. Should always be set to 0 or 1. - */ - int iVersion; - - /* - ** Create a new tokenizer. The values in the argv[] array are the - ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL - ** TABLE statement that created the fts3 table. For example, if - ** the following SQL is executed: - ** - ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) - ** - ** then argc is set to 2, and the argv[] array contains pointers - ** to the strings "arg1" and "arg2". - ** - ** This method should return either SQLITE_OK (0), or an SQLite error - ** code. If SQLITE_OK is returned, then *ppTokenizer should be set - ** to point at the newly created tokenizer structure. The generic - ** sqlite3_tokenizer.pModule variable should not be initialized by - ** this callback. The caller will do so. - */ - int (*xCreate)( - int argc, /* Size of argv array */ - const char *const*argv, /* Tokenizer argument strings */ - sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ - ); - - /* - ** Destroy an existing tokenizer. The fts3 module calls this method - ** exactly once for each successful call to xCreate(). - */ - int (*xDestroy)(sqlite3_tokenizer *pTokenizer); - - /* - ** Create a tokenizer cursor to tokenize an input buffer. The caller - ** is responsible for ensuring that the input buffer remains valid - ** until the cursor is closed (using the xClose() method). - */ - int (*xOpen)( - sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ - const char *pInput, int nBytes, /* Input buffer */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ - ); - - /* - ** Destroy an existing tokenizer cursor. The fts3 module calls this - ** method exactly once for each successful call to xOpen(). - */ - int (*xClose)(sqlite3_tokenizer_cursor *pCursor); - - /* - ** Retrieve the next token from the tokenizer cursor pCursor. This - ** method should either return SQLITE_OK and set the values of the - ** "OUT" variables identified below, or SQLITE_DONE to indicate that - ** the end of the buffer has been reached, or an SQLite error code. - ** - ** *ppToken should be set to point at a buffer containing the - ** normalized version of the token (i.e. after any case-folding and/or - ** stemming has been performed). *pnBytes should be set to the length - ** of this buffer in bytes. The input text that generated the token is - ** identified by the byte offsets returned in *piStartOffset and - ** *piEndOffset. *piStartOffset should be set to the index of the first - ** byte of the token in the input buffer. *piEndOffset should be set - ** to the index of the first byte just past the end of the token in - ** the input buffer. - ** - ** The buffer *ppToken is set to point at is managed by the tokenizer - ** implementation. It is only required to be valid until the next call - ** to xNext() or xClose(). - */ - /* TODO(shess) current implementation requires pInput to be - ** nul-terminated. This should either be fixed, or pInput/nBytes - ** should be converted to zInput. - */ - int (*xNext)( - sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ - const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ - int *piStartOffset, /* OUT: Byte offset of token in input buffer */ - int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ - int *piPosition /* OUT: Number of tokens returned before this one */ - ); - - /*********************************************************************** - ** Methods below this point are only available if iVersion>=1. - */ - - /* - ** Configure the language id of a tokenizer cursor. - */ - int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid); -}; - -struct sqlite3_tokenizer { - const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ - /* Tokenizer implementations will typically add additional fields */ -}; - -struct sqlite3_tokenizer_cursor { - sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ - /* Tokenizer implementations will typically add additional fields */ -}; - -int fts3_global_term_cnt(int iTerm, int iCol); -int fts3_term_cnt(int iTerm, int iCol); - - -#endif /* _FTS3_TOKENIZER_H_ */ - -/************** End of fts3_tokenizer.h **************************************/ -/************** Continuing where we left off in fts3Int.h ********************/ -/************** Include fts3_hash.h in the middle of fts3Int.h ***************/ -/************** Begin file fts3_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. We've modified it slightly to serve as a standalone -** hash table implementation for the full-text indexing module. -** -*/ -#ifndef _FTS3_HASH_H_ -#define _FTS3_HASH_H_ - -/* Forward declarations of structures. */ -typedef struct Fts3Hash Fts3Hash; -typedef struct Fts3HashElem Fts3HashElem; - -/* 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, many of the "procedures" and "functions" for modifying and -** accessing this structure are really macros, so we can't really make -** this structure opaque. -*/ -struct Fts3Hash { - char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ - char copyKey; /* True if copy of key made on insert */ - int count; /* Number of entries in this table */ - Fts3HashElem *first; /* The first element of the array */ - int htsize; /* Number of buckets in the hash table */ - struct _fts3ht { /* the hash table */ - int count; /* Number of entries with this hash */ - Fts3HashElem *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 Fts3HashElem { - Fts3HashElem *next, *prev; /* Next and previous elements in the table */ - void *data; /* Data associated with this element */ - void *pKey; int nKey; /* Key associated with this element */ -}; - -/* -** There are 2 different modes of operation for a hash table: -** -** FTS3_HASH_STRING pKey points to a string that is nKey bytes long -** (including the null-terminator, if any). Case -** is respected in comparisons. -** -** FTS3_HASH_BINARY pKey points to binary data nKey bytes long. -** memcmp() is used to compare keys. -** -** A copy of the key is made if the copyKey parameter to fts3HashInit is 1. -*/ -#define FTS3_HASH_STRING 1 -#define FTS3_HASH_BINARY 2 - -/* -** Access routines. To delete, insert a NULL pointer. -*/ -SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey); -SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData); -SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey); -SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*); -SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int); - -/* -** Shorthand for the functions above -*/ -#define fts3HashInit sqlite3Fts3HashInit -#define fts3HashInsert sqlite3Fts3HashInsert -#define fts3HashFind sqlite3Fts3HashFind -#define fts3HashClear sqlite3Fts3HashClear -#define fts3HashFindElem sqlite3Fts3HashFindElem - -/* -** Macros for looping over all elements of a hash table. The idiom is -** like this: -** -** Fts3Hash h; -** Fts3HashElem *p; -** ... -** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){ -** SomeStructure *pData = fts3HashData(p); -** // do something with pData -** } -*/ -#define fts3HashFirst(H) ((H)->first) -#define fts3HashNext(E) ((E)->next) -#define fts3HashData(E) ((E)->data) -#define fts3HashKey(E) ((E)->pKey) -#define fts3HashKeysize(E) ((E)->nKey) - -/* -** Number of entries in a hash table -*/ -#define fts3HashCount(H) ((H)->count) - -#endif /* _FTS3_HASH_H_ */ - -/************** End of fts3_hash.h *******************************************/ -/************** Continuing where we left off in fts3Int.h ********************/ - -/* -** This constant determines the maximum depth of an FTS expression tree -** that the library will create and use. FTS uses recursion to perform -** various operations on the query tree, so the disadvantage of a large -** limit is that it may allow very large queries to use large amounts -** of stack space (perhaps causing a stack overflow). -*/ -#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH -# define SQLITE_FTS3_MAX_EXPR_DEPTH 12 -#endif - - -/* -** This constant controls how often segments are merged. Once there are -** FTS3_MERGE_COUNT segments of level N, they are merged into a single -** segment of level N+1. -*/ -#define FTS3_MERGE_COUNT 16 - -/* -** This is the maximum amount of data (in bytes) to store in the -** Fts3Table.pendingTerms hash table. Normally, the hash table is -** populated as documents are inserted/updated/deleted in a transaction -** and used to create a new segment when the transaction is committed. -** However if this limit is reached midway through a transaction, a new -** segment is created and the hash table cleared immediately. -*/ -#define FTS3_MAX_PENDING_DATA (1*1024*1024) - -/* -** Macro to return the number of elements in an array. SQLite has a -** similar macro called ArraySize(). Use a different name to avoid -** a collision when building an amalgamation with built-in FTS3. -*/ -#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0]))) - - -#ifndef MIN -# define MIN(x,y) ((x)<(y)?(x):(y)) -#endif -#ifndef MAX -# define MAX(x,y) ((x)>(y)?(x):(y)) -#endif - -/* -** Maximum length of a varint encoded integer. The varint format is different -** from that used by SQLite, so the maximum length is 10, not 9. -*/ -#define FTS3_VARINT_MAX 10 - -#define FTS3_BUFFER_PADDING 8 - -/* -** FTS4 virtual tables may maintain multiple indexes - one index of all terms -** in the document set and zero or more prefix indexes. All indexes are stored -** as one or more b+-trees in the %_segments and %_segdir tables. -** -** It is possible to determine which index a b+-tree belongs to based on the -** value stored in the "%_segdir.level" column. Given this value L, the index -** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with -** level values between 0 and 1023 (inclusive) belong to index 0, all levels -** between 1024 and 2047 to index 1, and so on. -** -** It is considered impossible for an index to use more than 1024 levels. In -** theory though this may happen, but only after at least -** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables. -*/ -#define FTS3_SEGDIR_MAXLEVEL 1024 -#define FTS3_SEGDIR_MAXLEVEL_STR "1024" - -/* -** The testcase() macro is only used by the amalgamation. If undefined, -** make it a no-op. -*/ -#ifndef testcase -# define testcase(X) -#endif - -/* -** Terminator values for position-lists and column-lists. -*/ -#define POS_COLUMN (1) /* Column-list terminator */ -#define POS_END (0) /* Position-list terminator */ - -/* -** The assert_fts3_nc() macro is similar to the assert() macro, except that it -** is used for assert() conditions that are true only if it can be -** guranteed that the database is not corrupt. -*/ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_fts3_may_be_corrupt; -# define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x)) -#else -# define assert_fts3_nc(x) assert(x) -#endif - -/* -** This section provides definitions to allow the -** FTS3 extension to be compiled outside of the -** amalgamation. -*/ -#ifndef SQLITE_AMALGAMATION -/* -** Macros indicating that conditional expressions are always true or -** false. -*/ -#ifdef SQLITE_COVERAGE_TEST -# define ALWAYS(x) (1) -# define NEVER(X) (0) -#elif defined(SQLITE_DEBUG) -# define ALWAYS(x) sqlite3Fts3Always((x)!=0) -# define NEVER(x) sqlite3Fts3Never((x)!=0) -SQLITE_PRIVATE int sqlite3Fts3Always(int b); -SQLITE_PRIVATE int sqlite3Fts3Never(int b); -#else -# define ALWAYS(x) (x) -# define NEVER(x) (x) -#endif - -/* -** Internal types used by SQLite. -*/ -typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */ -typedef short int i16; /* 2-byte (or larger) signed integer */ -typedef unsigned int u32; /* 4-byte unsigned integer */ -typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */ -typedef sqlite3_int64 i64; /* 8-byte signed integer */ - -/* -** Macro used to suppress compiler warnings for unused parameters. -*/ -#define UNUSED_PARAMETER(x) (void)(x) - -/* -** Activate assert() only if SQLITE_TEST is enabled. -*/ -#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) -# define NDEBUG 1 -#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(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) -# define TESTONLY(X) X -#else -# define TESTONLY(X) -#endif - -#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) -#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) - -#define deliberate_fall_through - -#endif /* SQLITE_AMALGAMATION */ - -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3Fts3Corrupt(void); -# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt() -#else -# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB -#endif - -typedef struct Fts3Table Fts3Table; -typedef struct Fts3Cursor Fts3Cursor; -typedef struct Fts3Expr Fts3Expr; -typedef struct Fts3Phrase Fts3Phrase; -typedef struct Fts3PhraseToken Fts3PhraseToken; - -typedef struct Fts3Doclist Fts3Doclist; -typedef struct Fts3SegFilter Fts3SegFilter; -typedef struct Fts3DeferredToken Fts3DeferredToken; -typedef struct Fts3SegReader Fts3SegReader; -typedef struct Fts3MultiSegReader Fts3MultiSegReader; - -typedef struct MatchinfoBuffer MatchinfoBuffer; - -/* -** A connection to a fulltext index is an instance of the following -** structure. The xCreate and xConnect methods create an instance -** of this structure and xDestroy and xDisconnect free that instance. -** All other methods receive a pointer to the structure as one of their -** arguments. -*/ -struct Fts3Table { - sqlite3_vtab base; /* Base class used by SQLite core */ - sqlite3 *db; /* The database connection */ - const char *zDb; /* logical database name */ - const char *zName; /* virtual table name */ - int nColumn; /* number of named columns in virtual table */ - char **azColumn; /* column names. malloced */ - u8 *abNotindexed; /* True for 'notindexed' columns */ - sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ - char *zContentTbl; /* content=xxx option, or NULL */ - char *zLanguageid; /* languageid=xxx option, or NULL */ - int nAutoincrmerge; /* Value configured by 'automerge' */ - u32 nLeafAdd; /* Number of leaf blocks added this trans */ - int bLock; /* Used to prevent recursive content= tbls */ - - /* Precompiled statements used by the implementation. Each of these - ** statements is run and reset within a single virtual table API call. - */ - sqlite3_stmt *aStmt[40]; - sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */ - - char *zReadExprlist; - char *zWriteExprlist; - - int nNodeSize; /* Soft limit for node size */ - u8 bFts4; /* True for FTS4, false for FTS3 */ - u8 bHasStat; /* True if %_stat table exists (2==unknown) */ - u8 bHasDocsize; /* True if %_docsize table exists */ - u8 bDescIdx; /* True if doclists are in reverse order */ - u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */ - int nPgsz; /* Page size for host database */ - char *zSegmentsTbl; /* Name of %_segments table */ - sqlite3_blob *pSegments; /* Blob handle open on %_segments table */ - - /* - ** The following array of hash tables is used to buffer pending index - ** updates during transactions. All pending updates buffered at any one - ** time must share a common language-id (see the FTS4 langid= feature). - ** The current language id is stored in variable iPrevLangid. - ** - ** A single FTS4 table may have multiple full-text indexes. For each index - ** there is an entry in the aIndex[] array. Index 0 is an index of all the - ** terms that appear in the document set. Each subsequent index in aIndex[] - ** is an index of prefixes of a specific length. - ** - ** Variable nPendingData contains an estimate the memory consumed by the - ** pending data structures, including hash table overhead, but not including - ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash - ** tables are flushed to disk. Variable iPrevDocid is the docid of the most - ** recently inserted record. - */ - int nIndex; /* Size of aIndex[] */ - struct Fts3Index { - int nPrefix; /* Prefix length (0 for main terms index) */ - Fts3Hash hPending; /* Pending terms table for this index */ - } *aIndex; - int nMaxPendingData; /* Max pending data before flush to disk */ - int nPendingData; /* Current bytes of pending data */ - sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */ - int iPrevLangid; /* Langid of recently inserted document */ - int bPrevDelete; /* True if last operation was a delete */ - -#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) - /* State variables used for validating that the transaction control - ** methods of the virtual table are called at appropriate times. These - ** values do not contribute to FTS functionality; they are used for - ** verifying the operation of the SQLite core. - */ - int inTransaction; /* True after xBegin but before xCommit/xRollback */ - int mxSavepoint; /* Largest valid xSavepoint integer */ -#endif - -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - /* True to disable the incremental doclist optimization. This is controled - ** by special insert command 'test-no-incr-doclist'. */ - int bNoIncrDoclist; - - /* Number of segments in a level */ - int nMergeCount; -#endif -}; - -/* Macro to find the number of segments to merge */ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) -# define MergeCount(P) ((P)->nMergeCount) -#else -# define MergeCount(P) FTS3_MERGE_COUNT -#endif - -/* -** When the core wants to read from the virtual table, it creates a -** virtual table cursor (an instance of the following structure) using -** the xOpen method. Cursors are destroyed using the xClose method. -*/ -struct Fts3Cursor { - sqlite3_vtab_cursor base; /* Base class used by SQLite core */ - i16 eSearch; /* Search strategy (see below) */ - u8 isEof; /* True if at End Of Results */ - u8 isRequireSeek; /* True if must seek pStmt to %_content row */ - u8 bSeekStmt; /* True if pStmt is a seek */ - sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ - Fts3Expr *pExpr; /* Parsed MATCH query string */ - int iLangid; /* Language being queried for */ - int nPhrase; /* Number of matchable phrases in query */ - Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */ - sqlite3_int64 iPrevId; /* Previous id read from aDoclist */ - char *pNextId; /* Pointer into the body of aDoclist */ - char *aDoclist; /* List of docids for full-text queries */ - int nDoclist; /* Size of buffer at aDoclist */ - u8 bDesc; /* True to sort in descending order */ - int eEvalmode; /* An FTS3_EVAL_XX constant */ - int nRowAvg; /* Average size of database rows, in pages */ - sqlite3_int64 nDoc; /* Documents in table */ - i64 iMinDocid; /* Minimum docid to return */ - i64 iMaxDocid; /* Maximum docid to return */ - int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */ - MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */ -}; - -#define FTS3_EVAL_FILTER 0 -#define FTS3_EVAL_NEXT 1 -#define FTS3_EVAL_MATCHINFO 2 - -/* -** The Fts3Cursor.eSearch member is always set to one of the following. -** Actualy, Fts3Cursor.eSearch can be greater than or equal to -** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index -** of the column to be searched. For example, in -** -** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d); -** SELECT docid FROM ex1 WHERE b MATCH 'one two three'; -** -** Because the LHS of the MATCH operator is 2nd column "b", -** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a, -** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1" -** indicating that all columns should be searched, -** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4. -*/ -#define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */ -#define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */ -#define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */ - -/* -** The lower 16-bits of the sqlite3_index_info.idxNum value set by -** the xBestIndex() method contains the Fts3Cursor.eSearch value described -** above. The upper 16-bits contain a combination of the following -** bits, used to describe extra constraints on full-text searches. -*/ -#define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */ -#define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */ -#define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */ - -struct Fts3Doclist { - char *aAll; /* Array containing doclist (or NULL) */ - int nAll; /* Size of a[] in bytes */ - char *pNextDocid; /* Pointer to next docid */ - - sqlite3_int64 iDocid; /* Current docid (if pList!=0) */ - int bFreeList; /* True if pList should be sqlite3_free()d */ - char *pList; /* Pointer to position list following iDocid */ - int nList; /* Length of position list */ -}; - -/* -** A "phrase" is a sequence of one or more tokens that must match in -** sequence. A single token is the base case and the most common case. -** For a sequence of tokens contained in double-quotes (i.e. "one two three") -** nToken will be the number of tokens in the string. -*/ -struct Fts3PhraseToken { - char *z; /* Text of the token */ - int n; /* Number of bytes in buffer z */ - int isPrefix; /* True if token ends with a "*" character */ - int bFirst; /* True if token must appear at position 0 */ - - /* Variables above this point are populated when the expression is - ** parsed (by code in fts3_expr.c). Below this point the variables are - ** used when evaluating the expression. */ - Fts3DeferredToken *pDeferred; /* Deferred token object for this token */ - Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */ -}; - -struct Fts3Phrase { - /* Cache of doclist for this phrase. */ - Fts3Doclist doclist; - int bIncr; /* True if doclist is loaded incrementally */ - int iDoclistToken; - - /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an - ** OR condition. */ - char *pOrPoslist; - i64 iOrDocid; - - /* Variables below this point are populated by fts3_expr.c when parsing - ** a MATCH expression. Everything above is part of the evaluation phase. - */ - int nToken; /* Number of tokens in the phrase */ - int iColumn; /* Index of column this phrase must match */ - Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */ -}; - -/* -** A tree of these objects forms the RHS of a MATCH operator. -** -** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist -** points to a malloced buffer, size nDoclist bytes, containing the results -** of this phrase query in FTS3 doclist format. As usual, the initial -** "Length" field found in doclists stored on disk is omitted from this -** buffer. -** -** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global -** matchinfo data. If it is not NULL, it points to an array of size nCol*3, -** where nCol is the number of columns in the queried FTS table. The array -** is populated as follows: -** -** aMI[iCol*3 + 0] = Undefined -** aMI[iCol*3 + 1] = Number of occurrences -** aMI[iCol*3 + 2] = Number of rows containing at least one instance -** -** The aMI array is allocated using sqlite3_malloc(). It should be freed -** when the expression node is. -*/ -struct Fts3Expr { - int eType; /* One of the FTSQUERY_XXX values defined below */ - int nNear; /* Valid if eType==FTSQUERY_NEAR */ - Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */ - Fts3Expr *pLeft; /* Left operand */ - Fts3Expr *pRight; /* Right operand */ - Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */ - - /* The following are used by the fts3_eval.c module. */ - sqlite3_int64 iDocid; /* Current docid */ - u8 bEof; /* True this expression is at EOF already */ - u8 bStart; /* True if iDocid is valid */ - u8 bDeferred; /* True if this expression is entirely deferred */ - - /* The following are used by the fts3_snippet.c module. */ - int iPhrase; /* Index of this phrase in matchinfo() results */ - u32 *aMI; /* See above */ -}; - -/* -** Candidate values for Fts3Query.eType. Note that the order of the first -** four values is in order of precedence when parsing expressions. For -** example, the following: -** -** "a OR b AND c NOT d NEAR e" -** -** is equivalent to: -** -** "a OR (b AND (c NOT (d NEAR e)))" -*/ -#define FTSQUERY_NEAR 1 -#define FTSQUERY_NOT 2 -#define FTSQUERY_AND 3 -#define FTSQUERY_OR 4 -#define FTSQUERY_PHRASE 5 - - -/* fts3_write.c */ -SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*); -SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *); -SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *); -SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *); -SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64, - sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**); -SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( - Fts3Table*,int,const char*,int,int,Fts3SegReader**); -SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *); -SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **); -SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*); - -SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **); -SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **); - -#ifndef SQLITE_DISABLE_FTS4_DEFERRED -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *); -SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int); -SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *); -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *); -SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *); -#else -# define sqlite3Fts3FreeDeferredTokens(x) -# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK -# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK -# define sqlite3Fts3FreeDeferredDoclists(x) -# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK -#endif - -SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *); -SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *); - -/* Special values interpreted by sqlite3SegReaderCursor() */ -#define FTS3_SEGCURSOR_PENDING -1 -#define FTS3_SEGCURSOR_ALL -2 - -SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*); -SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *); -SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *); - -SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, - int, int, int, const char *, int, int, int, Fts3MultiSegReader *); - -/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */ -#define FTS3_SEGMENT_REQUIRE_POS 0x00000001 -#define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002 -#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004 -#define FTS3_SEGMENT_PREFIX 0x00000008 -#define FTS3_SEGMENT_SCAN 0x00000010 -#define FTS3_SEGMENT_FIRST 0x00000020 - -/* Type passed as 4th argument to SegmentReaderIterate() */ -struct Fts3SegFilter { - const char *zTerm; - int nTerm; - int iCol; - int flags; -}; - -struct Fts3MultiSegReader { - /* Used internally by sqlite3Fts3SegReaderXXX() calls */ - Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */ - int nSegment; /* Size of apSegment array */ - int nAdvance; /* How many seg-readers to advance */ - Fts3SegFilter *pFilter; /* Pointer to filter object */ - char *aBuffer; /* Buffer to merge doclists in */ - int nBuffer; /* Allocated size of aBuffer[] in bytes */ - - int iColFilter; /* If >=0, filter for this column */ - int bRestart; - - /* Used by fts3.c only. */ - int nCost; /* Cost of running iterator */ - int bLookup; /* True if a lookup of a single entry. */ - - /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */ - char *zTerm; /* Pointer to term buffer */ - int nTerm; /* Size of zTerm in bytes */ - char *aDoclist; /* Pointer to doclist buffer */ - int nDoclist; /* Size of aDoclist[] in bytes */ -}; - -SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int); - -#define fts3GetVarint32(p, piVal) ( \ - (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \ -) - -/* fts3.c */ -SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...); -SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64); -SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *); -SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *, sqlite_uint64 *); -SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(const char*,const char*,sqlite3_int64*); -SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *); -SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64); -SQLITE_PRIVATE void sqlite3Fts3Dequote(char *); -SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*); -SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *); -SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *); -SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*); -SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc); -SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut); - -/* fts3_tokenizer.c */ -SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *); -SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *); -SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, - sqlite3_tokenizer **, char ** -); -SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char); - -/* fts3_snippet.c */ -SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*); -SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *, - const char *, const char *, int, int -); -SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *); -SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p); - -/* fts3_expr.c */ -SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int, - char **, int, int, int, const char *, int, Fts3Expr **, char ** -); -SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *); -#ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*); -SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db); -#endif - -SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int, - sqlite3_tokenizer_cursor ** -); - -/* fts3_aux.c */ -SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db); - -SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *); - -SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( - Fts3Table*, Fts3MultiSegReader*, int, const char*, int); -SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( - Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *); -SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); -SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); -SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); - -/* fts3_tokenize_vtab.c */ -SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *); - -/* fts3_unicode2.c (functions generated by parsing unicode text files) */ -#ifndef SQLITE_DISABLE_FTS3_UNICODE -SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int); -SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int); -SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int); -#endif - -#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */ -#endif /* _FTSINT_H */ - -/************** End of fts3Int.h *********************************************/ -/************** Continuing where we left off in fts3.c ***********************/ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) -# define SQLITE_CORE 1 -#endif - -/* #include */ -/* #include */ -/* #include */ -/* #include */ -/* #include */ -/* #include */ - -/* #include "fts3.h" */ -#ifndef SQLITE_CORE -/* # include "sqlite3ext.h" */ - SQLITE_EXTENSION_INIT1 -#endif - -static int fts3EvalNext(Fts3Cursor *pCsr); -static int fts3EvalStart(Fts3Cursor *pCsr); -static int fts3TermSegReaderCursor( - Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **); - -#ifndef SQLITE_AMALGAMATION -# if defined(SQLITE_DEBUG) -SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; } -SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; } -# endif -#endif - -/* -** This variable is set to false when running tests for which the on disk -** structures should not be corrupt. Otherwise, true. If it is false, extra -** assert() conditions in the fts3 code are activated - conditions that are -** only true if it is guaranteed that the fts3 database is not corrupt. -*/ -SQLITE_API int sqlite3_fts3_may_be_corrupt = 1; - -/* -** Write a 64-bit variable-length integer to memory starting at p[0]. -** The length of data written will be between 1 and FTS3_VARINT_MAX bytes. -** The number of bytes written is returned. -*/ -SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){ - unsigned char *q = (unsigned char *) p; - sqlite_uint64 vu = v; - do{ - *q++ = (unsigned char) ((vu & 0x7f) | 0x80); - vu >>= 7; - }while( vu!=0 ); - q[-1] &= 0x7f; /* turn off high bit in final byte */ - assert( q - (unsigned char *)p <= FTS3_VARINT_MAX ); - return (int) (q - (unsigned char *)p); -} - -#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \ - v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \ - if( (v & mask2)==0 ){ var = v; return ret; } -#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \ - v = (*ptr++); \ - if( (v & mask2)==0 ){ var = v; return ret; } - -SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){ - const unsigned char *p = (const unsigned char*)pBuf; - const unsigned char *pStart = p; - u32 a; - u64 b; - int shift; - - GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1); - GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2); - GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3); - GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4); - b = (a & 0x0FFFFFFF ); - - for(shift=28; shift<=63; shift+=7){ - u64 c = *p++; - b += (c&0x7F) << shift; - if( (c & 0x80)==0 ) break; - } - *v = b; - return (int)(p - pStart); -} - -/* -** Read a 64-bit variable-length integer from memory starting at p[0]. -** Return the number of bytes read, or 0 on error. -** The value is stored in *v. -*/ -SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){ - return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v); -} - -/* -** Read a 64-bit variable-length integer from memory starting at p[0] and -** not extending past pEnd[-1]. -** Return the number of bytes read, or 0 on error. -** The value is stored in *v. -*/ -SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded( - const char *pBuf, - const char *pEnd, - sqlite_int64 *v -){ - const unsigned char *p = (const unsigned char*)pBuf; - const unsigned char *pStart = p; - const unsigned char *pX = (const unsigned char*)pEnd; - u64 b = 0; - int shift; - for(shift=0; shift<=63; shift+=7){ - u64 c = p=0 ); - return 5; -} - -/* -** Return the number of bytes required to encode v as a varint -*/ -SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){ - int i = 0; - do{ - i++; - v >>= 7; - }while( v!=0 ); - return i; -} - -/* -** 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. -** -** Examples: -** -** "abc" becomes abc -** 'xyz' becomes xyz -** [pqr] becomes pqr -** `mno` becomes mno -** -*/ -SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){ - char quote; /* Quote character (if any ) */ - - quote = z[0]; - if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){ - int iIn = 1; /* Index of next byte to read from input */ - int iOut = 0; /* Index of next byte to write to output */ - - /* If the first byte was a '[', then the close-quote character is a ']' */ - if( quote=='[' ) quote = ']'; - - while( z[iIn] ){ - if( z[iIn]==quote ){ - if( z[iIn+1]!=quote ) break; - z[iOut++] = quote; - iIn += 2; - }else{ - z[iOut++] = z[iIn++]; - } - } - z[iOut] = '\0'; - } -} - -/* -** Read a single varint from the doclist at *pp and advance *pp to point -** to the first byte past the end of the varint. Add the value of the varint -** to *pVal. -*/ -static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){ - sqlite3_int64 iVal; - *pp += sqlite3Fts3GetVarint(*pp, &iVal); - *pVal += iVal; -} - -/* -** When this function is called, *pp points to the first byte following a -** varint that is part of a doclist (or position-list, or any other list -** of varints). This function moves *pp to point to the start of that varint, -** and sets *pVal by the varint value. -** -** Argument pStart points to the first byte of the doclist that the -** varint is part of. -*/ -static void fts3GetReverseVarint( - char **pp, - char *pStart, - sqlite3_int64 *pVal -){ - sqlite3_int64 iVal; - char *p; - - /* Pointer p now points at the first byte past the varint we are - ** interested in. So, unless the doclist is corrupt, the 0x80 bit is - ** clear on character p[-1]. */ - for(p = (*pp)-2; p>=pStart && *p&0x80; p--); - p++; - *pp = p; - - sqlite3Fts3GetVarint(p, &iVal); - *pVal = iVal; -} - -/* -** The xDisconnect() virtual table method. -*/ -static int fts3DisconnectMethod(sqlite3_vtab *pVtab){ - Fts3Table *p = (Fts3Table *)pVtab; - int i; - - assert( p->nPendingData==0 ); - assert( p->pSegments==0 ); - - /* Free any prepared statements held */ - sqlite3_finalize(p->pSeekStmt); - for(i=0; iaStmt); i++){ - sqlite3_finalize(p->aStmt[i]); - } - sqlite3_free(p->zSegmentsTbl); - sqlite3_free(p->zReadExprlist); - sqlite3_free(p->zWriteExprlist); - sqlite3_free(p->zContentTbl); - sqlite3_free(p->zLanguageid); - - /* Invoke the tokenizer destructor to free the tokenizer. */ - p->pTokenizer->pModule->xDestroy(p->pTokenizer); - - sqlite3_free(p); - return SQLITE_OK; -} - -/* -** Write an error message into *pzErr -*/ -SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){ - va_list ap; - sqlite3_free(*pzErr); - va_start(ap, zFormat); - *pzErr = sqlite3_vmprintf(zFormat, ap); - va_end(ap); -} - -/* -** Construct one or more SQL statements from the format string given -** and then evaluate those statements. The success code is written -** into *pRc. -** -** If *pRc is initially non-zero then this routine is a no-op. -*/ -static void fts3DbExec( - int *pRc, /* Success code */ - sqlite3 *db, /* Database in which to run SQL */ - const char *zFormat, /* Format string for SQL */ - ... /* Arguments to the format string */ -){ - va_list ap; - char *zSql; - if( *pRc ) return; - va_start(ap, zFormat); - zSql = sqlite3_vmprintf(zFormat, ap); - va_end(ap); - if( zSql==0 ){ - *pRc = SQLITE_NOMEM; - }else{ - *pRc = sqlite3_exec(db, zSql, 0, 0, 0); - sqlite3_free(zSql); - } -} - -/* -** The xDestroy() virtual table method. -*/ -static int fts3DestroyMethod(sqlite3_vtab *pVtab){ - Fts3Table *p = (Fts3Table *)pVtab; - int rc = SQLITE_OK; /* Return code */ - const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */ - sqlite3 *db = p->db; /* Database handle */ - - /* Drop the shadow tables */ - fts3DbExec(&rc, db, - "DROP TABLE IF EXISTS %Q.'%q_segments';" - "DROP TABLE IF EXISTS %Q.'%q_segdir';" - "DROP TABLE IF EXISTS %Q.'%q_docsize';" - "DROP TABLE IF EXISTS %Q.'%q_stat';" - "%s DROP TABLE IF EXISTS %Q.'%q_content';", - zDb, p->zName, - zDb, p->zName, - zDb, p->zName, - zDb, p->zName, - (p->zContentTbl ? "--" : ""), zDb,p->zName - ); - - /* If everything has worked, invoke fts3DisconnectMethod() to free the - ** memory associated with the Fts3Table structure and return SQLITE_OK. - ** Otherwise, return an SQLite error code. - */ - return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc); -} - - -/* -** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table -** passed as the first argument. This is done as part of the xConnect() -** and xCreate() methods. -** -** If *pRc is non-zero when this function is called, it is a no-op. -** Otherwise, if an error occurs, an SQLite error code is stored in *pRc -** before returning. -*/ -static void fts3DeclareVtab(int *pRc, Fts3Table *p){ - if( *pRc==SQLITE_OK ){ - int i; /* Iterator variable */ - int rc; /* Return code */ - char *zSql; /* SQL statement passed to declare_vtab() */ - char *zCols; /* List of user defined columns */ - const char *zLanguageid; - - zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid"); - sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); - - /* Create a list of user columns for the virtual table */ - zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]); - for(i=1; zCols && inColumn; i++){ - zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]); - } - - /* Create the whole "CREATE TABLE" statement to pass to SQLite */ - zSql = sqlite3_mprintf( - "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", - zCols, p->zName, zLanguageid - ); - if( !zCols || !zSql ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_declare_vtab(p->db, zSql); - } - - sqlite3_free(zSql); - sqlite3_free(zCols); - *pRc = rc; - } -} - -/* -** Create the %_stat table if it does not already exist. -*/ -SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){ - fts3DbExec(pRc, p->db, - "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'" - "(id INTEGER PRIMARY KEY, value BLOB);", - p->zDb, p->zName - ); - if( (*pRc)==SQLITE_OK ) p->bHasStat = 1; -} - -/* -** Create the backing store tables (%_content, %_segments and %_segdir) -** required by the FTS3 table passed as the only argument. This is done -** as part of the vtab xCreate() method. -** -** If the p->bHasDocsize boolean is true (indicating that this is an -** FTS4 table, not an FTS3 table) then also create the %_docsize and -** %_stat tables required by FTS4. -*/ -static int fts3CreateTables(Fts3Table *p){ - int rc = SQLITE_OK; /* Return code */ - int i; /* Iterator variable */ - sqlite3 *db = p->db; /* The database connection */ - - if( p->zContentTbl==0 ){ - const char *zLanguageid = p->zLanguageid; - char *zContentCols; /* Columns of %_content table */ - - /* Create a list of user columns for the content table */ - zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY"); - for(i=0; zContentCols && inColumn; i++){ - char *z = p->azColumn[i]; - zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z); - } - if( zLanguageid && zContentCols ){ - zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid); - } - if( zContentCols==0 ) rc = SQLITE_NOMEM; - - /* Create the content table */ - fts3DbExec(&rc, db, - "CREATE TABLE %Q.'%q_content'(%s)", - p->zDb, p->zName, zContentCols - ); - sqlite3_free(zContentCols); - } - - /* Create other tables */ - fts3DbExec(&rc, db, - "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);", - p->zDb, p->zName - ); - fts3DbExec(&rc, db, - "CREATE TABLE %Q.'%q_segdir'(" - "level INTEGER," - "idx INTEGER," - "start_block INTEGER," - "leaves_end_block INTEGER," - "end_block INTEGER," - "root BLOB," - "PRIMARY KEY(level, idx)" - ");", - p->zDb, p->zName - ); - if( p->bHasDocsize ){ - fts3DbExec(&rc, db, - "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);", - p->zDb, p->zName - ); - } - assert( p->bHasStat==p->bFts4 ); - if( p->bHasStat ){ - sqlite3Fts3CreateStatTable(&rc, p); - } - return rc; -} - -/* -** Store the current database page-size in bytes in p->nPgsz. -** -** If *pRc is non-zero when this function is called, it is a no-op. -** Otherwise, if an error occurs, an SQLite error code is stored in *pRc -** before returning. -*/ -static void fts3DatabasePageSize(int *pRc, Fts3Table *p){ - if( *pRc==SQLITE_OK ){ - int rc; /* Return code */ - char *zSql; /* SQL text "PRAGMA %Q.page_size" */ - sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */ - - zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb); - if( !zSql ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_step(pStmt); - p->nPgsz = sqlite3_column_int(pStmt, 0); - rc = sqlite3_finalize(pStmt); - }else if( rc==SQLITE_AUTH ){ - p->nPgsz = 1024; - rc = SQLITE_OK; - } - } - assert( p->nPgsz>0 || rc!=SQLITE_OK ); - sqlite3_free(zSql); - *pRc = rc; - } -} - -/* -** "Special" FTS4 arguments are column specifications of the following form: -** -** = -** -** There may not be whitespace surrounding the "=" character. The -** term may be quoted, but the may not. -*/ -static int fts3IsSpecialColumn( - const char *z, - int *pnKey, - char **pzValue -){ - char *zValue; - const char *zCsr = z; - - while( *zCsr!='=' ){ - if( *zCsr=='\0' ) return 0; - zCsr++; - } - - *pnKey = (int)(zCsr-z); - zValue = sqlite3_mprintf("%s", &zCsr[1]); - if( zValue ){ - sqlite3Fts3Dequote(zValue); - } - *pzValue = zValue; - return 1; -} - -/* -** Append the output of a printf() style formatting to an existing string. -*/ -static void fts3Appendf( - int *pRc, /* IN/OUT: Error code */ - char **pz, /* IN/OUT: Pointer to string buffer */ - const char *zFormat, /* Printf format string to append */ - ... /* Arguments for printf format string */ -){ - if( *pRc==SQLITE_OK ){ - va_list ap; - char *z; - va_start(ap, zFormat); - z = sqlite3_vmprintf(zFormat, ap); - va_end(ap); - if( z && *pz ){ - char *z2 = sqlite3_mprintf("%s%s", *pz, z); - sqlite3_free(z); - z = z2; - } - if( z==0 ) *pRc = SQLITE_NOMEM; - sqlite3_free(*pz); - *pz = z; - } -} - -/* -** Return a copy of input string zInput enclosed in double-quotes (") and -** with all double quote characters escaped. For example: -** -** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\"" -** -** The pointer returned points to memory obtained from sqlite3_malloc(). It -** is the callers responsibility to call sqlite3_free() to release this -** memory. -*/ -static char *fts3QuoteId(char const *zInput){ - sqlite3_int64 nRet; - char *zRet; - nRet = 2 + (int)strlen(zInput)*2 + 1; - zRet = sqlite3_malloc64(nRet); - if( zRet ){ - int i; - char *z = zRet; - *(z++) = '"'; - for(i=0; zInput[i]; i++){ - if( zInput[i]=='"' ) *(z++) = '"'; - *(z++) = zInput[i]; - } - *(z++) = '"'; - *(z++) = '\0'; - } - return zRet; -} - -/* -** Return a list of comma separated SQL expressions and a FROM clause that -** could be used in a SELECT statement such as the following: -** -** SELECT FROM %_content AS x ... -** -** to return the docid, followed by each column of text data in order -** from left to write. If parameter zFunc is not NULL, then instead of -** being returned directly each column of text data is passed to an SQL -** function named zFunc first. For example, if zFunc is "unzip" and the -** table has the three user-defined columns "a", "b", and "c", the following -** string is returned: -** -** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x" -** -** The pointer returned points to a buffer allocated by sqlite3_malloc(). It -** is the responsibility of the caller to eventually free it. -** -** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and -** a NULL pointer is returned). Otherwise, if an OOM error is encountered -** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If -** no error occurs, *pRc is left unmodified. -*/ -static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){ - char *zRet = 0; - char *zFree = 0; - char *zFunction; - int i; - - if( p->zContentTbl==0 ){ - if( !zFunc ){ - zFunction = ""; - }else{ - zFree = zFunction = fts3QuoteId(zFunc); - } - fts3Appendf(pRc, &zRet, "docid"); - for(i=0; inColumn; i++){ - fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]); - } - if( p->zLanguageid ){ - fts3Appendf(pRc, &zRet, ", x.%Q", "langid"); - } - sqlite3_free(zFree); - }else{ - fts3Appendf(pRc, &zRet, "rowid"); - for(i=0; inColumn; i++){ - fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]); - } - if( p->zLanguageid ){ - fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid); - } - } - fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", - p->zDb, - (p->zContentTbl ? p->zContentTbl : p->zName), - (p->zContentTbl ? "" : "_content") - ); - return zRet; -} - -/* -** Return a list of N comma separated question marks, where N is the number -** of columns in the %_content table (one for the docid plus one for each -** user-defined text column). -** -** If argument zFunc is not NULL, then all but the first question mark -** is preceded by zFunc and an open bracket, and followed by a closed -** bracket. For example, if zFunc is "zip" and the FTS3 table has three -** user-defined text columns, the following string is returned: -** -** "?, zip(?), zip(?), zip(?)" -** -** The pointer returned points to a buffer allocated by sqlite3_malloc(). It -** is the responsibility of the caller to eventually free it. -** -** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and -** a NULL pointer is returned). Otherwise, if an OOM error is encountered -** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If -** no error occurs, *pRc is left unmodified. -*/ -static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){ - char *zRet = 0; - char *zFree = 0; - char *zFunction; - int i; - - if( !zFunc ){ - zFunction = ""; - }else{ - zFree = zFunction = fts3QuoteId(zFunc); - } - fts3Appendf(pRc, &zRet, "?"); - for(i=0; inColumn; i++){ - fts3Appendf(pRc, &zRet, ",%s(?)", zFunction); - } - if( p->zLanguageid ){ - fts3Appendf(pRc, &zRet, ", ?"); - } - sqlite3_free(zFree); - return zRet; -} - -/* -** Buffer z contains a positive integer value encoded as utf-8 text. -** Decode this value and store it in *pnOut, returning the number of bytes -** consumed. If an overflow error occurs return a negative value. -*/ -SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut){ - u64 iVal = 0; - int i; - for(i=0; z[i]>='0' && z[i]<='9'; i++){ - iVal = iVal*10 + (z[i] - '0'); - if( iVal>0x7FFFFFFF ) return -1; - } - *pnOut = (int)iVal; - return i; -} - -/* -** This function interprets the string at (*pp) as a non-negative integer -** value. It reads the integer and sets *pnOut to the value read, then -** sets *pp to point to the byte immediately following the last byte of -** the integer value. -** -** Only decimal digits ('0'..'9') may be part of an integer value. -** -** If *pp does not being with a decimal digit SQLITE_ERROR is returned and -** the output value undefined. Otherwise SQLITE_OK is returned. -** -** This function is used when parsing the "prefix=" FTS4 parameter. -*/ -static int fts3GobbleInt(const char **pp, int *pnOut){ - const int MAX_NPREFIX = 10000000; - int nInt = 0; /* Output value */ - int nByte; - nByte = sqlite3Fts3ReadInt(*pp, &nInt); - if( nInt>MAX_NPREFIX ){ - nInt = 0; - } - if( nByte==0 ){ - return SQLITE_ERROR; - } - *pnOut = nInt; - *pp += nByte; - return SQLITE_OK; -} - -/* -** This function is called to allocate an array of Fts3Index structures -** representing the indexes maintained by the current FTS table. FTS tables -** always maintain the main "terms" index, but may also maintain one or -** more "prefix" indexes, depending on the value of the "prefix=" parameter -** (if any) specified as part of the CREATE VIRTUAL TABLE statement. -** -** Argument zParam is passed the value of the "prefix=" option if one was -** specified, or NULL otherwise. -** -** If no error occurs, SQLITE_OK is returned and *apIndex set to point to -** the allocated array. *pnIndex is set to the number of elements in the -** array. If an error does occur, an SQLite error code is returned. -** -** Regardless of whether or not an error is returned, it is the responsibility -** of the caller to call sqlite3_free() on the output array to free it. -*/ -static int fts3PrefixParameter( - const char *zParam, /* ABC in prefix=ABC parameter to parse */ - int *pnIndex, /* OUT: size of *apIndex[] array */ - struct Fts3Index **apIndex /* OUT: Array of indexes for this table */ -){ - struct Fts3Index *aIndex; /* Allocated array */ - int nIndex = 1; /* Number of entries in array */ - - if( zParam && zParam[0] ){ - const char *p; - nIndex++; - for(p=zParam; *p; p++){ - if( *p==',' ) nIndex++; - } - } - - aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex); - *apIndex = aIndex; - if( !aIndex ){ - return SQLITE_NOMEM; - } - - memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex); - if( zParam ){ - const char *p = zParam; - int i; - for(i=1; i=0 ); - if( nPrefix==0 ){ - nIndex--; - i--; - }else{ - aIndex[i].nPrefix = nPrefix; - } - p++; - } - } - - *pnIndex = nIndex; - return SQLITE_OK; -} - -/* -** This function is called when initializing an FTS4 table that uses the -** content=xxx option. It determines the number of and names of the columns -** of the new FTS4 table. -** -** The third argument passed to this function is the value passed to the -** config=xxx option (i.e. "xxx"). This function queries the database for -** a table of that name. If found, the output variables are populated -** as follows: -** -** *pnCol: Set to the number of columns table xxx has, -** -** *pnStr: Set to the total amount of space required to store a copy -** of each columns name, including the nul-terminator. -** -** *pazCol: Set to point to an array of *pnCol strings. Each string is -** the name of the corresponding column in table xxx. The array -** and its contents are allocated using a single allocation. It -** is the responsibility of the caller to free this allocation -** by eventually passing the *pazCol value to sqlite3_free(). -** -** If the table cannot be found, an error code is returned and the output -** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is -** returned (and the output variables are undefined). -*/ -static int fts3ContentColumns( - sqlite3 *db, /* Database handle */ - const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */ - const char *zTbl, /* Name of content table */ - const char ***pazCol, /* OUT: Malloc'd array of column names */ - int *pnCol, /* OUT: Size of array *pazCol */ - int *pnStr, /* OUT: Bytes of string content */ - char **pzErr /* OUT: error message */ -){ - int rc = SQLITE_OK; /* Return code */ - char *zSql; /* "SELECT *" statement on zTbl */ - sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */ - - zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl); - if( !zSql ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); - if( rc!=SQLITE_OK ){ - sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db)); - } - } - sqlite3_free(zSql); - - if( rc==SQLITE_OK ){ - const char **azCol; /* Output array */ - sqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */ - int nCol; /* Number of table columns */ - int i; /* Used to iterate through columns */ - - /* Loop through the returned columns. Set nStr to the number of bytes of - ** space required to store a copy of each column name, including the - ** nul-terminator byte. */ - nCol = sqlite3_column_count(pStmt); - for(i=0; i module name ("fts3" or "fts4") -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> "column name" and other module argument fields. -*/ -static int fts3InitVtab( - int isCreate, /* True for xCreate, false for xConnect */ - sqlite3 *db, /* The SQLite database connection */ - void *pAux, /* Hash table containing tokenizers */ - int argc, /* Number of elements in argv array */ - const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ - char **pzErr /* Write any error message here */ -){ - Fts3Hash *pHash = (Fts3Hash *)pAux; - Fts3Table *p = 0; /* Pointer to allocated vtab */ - int rc = SQLITE_OK; /* Return code */ - int i; /* Iterator variable */ - sqlite3_int64 nByte; /* Size of allocation used for *p */ - int iCol; /* Column index */ - int nString = 0; /* Bytes required to hold all column names */ - int nCol = 0; /* Number of columns in the FTS table */ - char *zCsr; /* Space for holding column names */ - int nDb; /* Bytes required to hold database name */ - int nName; /* Bytes required to hold table name */ - int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */ - const char **aCol; /* Array of column names */ - sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */ - - int nIndex = 0; /* Size of aIndex[] array */ - struct Fts3Index *aIndex = 0; /* Array of indexes for this table */ - - /* The results of parsing supported FTS4 key=value options: */ - int bNoDocsize = 0; /* True to omit %_docsize table */ - int bDescIdx = 0; /* True to store descending indexes */ - char *zPrefix = 0; /* Prefix parameter value (or NULL) */ - char *zCompress = 0; /* compress=? parameter (or NULL) */ - char *zUncompress = 0; /* uncompress=? parameter (or NULL) */ - char *zContent = 0; /* content=? parameter (or NULL) */ - char *zLanguageid = 0; /* languageid=? parameter (or NULL) */ - char **azNotindexed = 0; /* The set of notindexed= columns */ - int nNotindexed = 0; /* Size of azNotindexed[] array */ - - assert( strlen(argv[0])==4 ); - assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4) - || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4) - ); - - nDb = (int)strlen(argv[1]) + 1; - nName = (int)strlen(argv[2]) + 1; - - nByte = sizeof(const char *) * (argc-2); - aCol = (const char **)sqlite3_malloc64(nByte); - if( aCol ){ - memset((void*)aCol, 0, nByte); - azNotindexed = (char **)sqlite3_malloc64(nByte); - } - if( azNotindexed ){ - memset(azNotindexed, 0, nByte); - } - if( !aCol || !azNotindexed ){ - rc = SQLITE_NOMEM; - goto fts3_init_out; - } - - /* Loop through all of the arguments passed by the user to the FTS3/4 - ** module (i.e. all the column names and special arguments). This loop - ** does the following: - ** - ** + Figures out the number of columns the FTSX table will have, and - ** the number of bytes of space that must be allocated to store copies - ** of the column names. - ** - ** + If there is a tokenizer specification included in the arguments, - ** initializes the tokenizer pTokenizer. - */ - for(i=3; rc==SQLITE_OK && i8 - && 0==sqlite3_strnicmp(z, "tokenize", 8) - && 0==sqlite3Fts3IsIdChar(z[8]) - ){ - rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr); - } - - /* Check if it is an FTS4 special argument. */ - else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){ - struct Fts4Option { - const char *zOpt; - int nOpt; - } aFts4Opt[] = { - { "matchinfo", 9 }, /* 0 -> MATCHINFO */ - { "prefix", 6 }, /* 1 -> PREFIX */ - { "compress", 8 }, /* 2 -> COMPRESS */ - { "uncompress", 10 }, /* 3 -> UNCOMPRESS */ - { "order", 5 }, /* 4 -> ORDER */ - { "content", 7 }, /* 5 -> CONTENT */ - { "languageid", 10 }, /* 6 -> LANGUAGEID */ - { "notindexed", 10 } /* 7 -> NOTINDEXED */ - }; - - int iOpt; - if( !zVal ){ - rc = SQLITE_NOMEM; - }else{ - for(iOpt=0; iOptnOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){ - break; - } - } - switch( iOpt ){ - case 0: /* MATCHINFO */ - if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){ - sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal); - rc = SQLITE_ERROR; - } - bNoDocsize = 1; - break; - - case 1: /* PREFIX */ - sqlite3_free(zPrefix); - zPrefix = zVal; - zVal = 0; - break; - - case 2: /* COMPRESS */ - sqlite3_free(zCompress); - zCompress = zVal; - zVal = 0; - break; - - case 3: /* UNCOMPRESS */ - sqlite3_free(zUncompress); - zUncompress = zVal; - zVal = 0; - break; - - case 4: /* ORDER */ - if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) - && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) - ){ - sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal); - rc = SQLITE_ERROR; - } - bDescIdx = (zVal[0]=='d' || zVal[0]=='D'); - break; - - case 5: /* CONTENT */ - sqlite3_free(zContent); - zContent = zVal; - zVal = 0; - break; - - case 6: /* LANGUAGEID */ - assert( iOpt==6 ); - sqlite3_free(zLanguageid); - zLanguageid = zVal; - zVal = 0; - break; - - case 7: /* NOTINDEXED */ - azNotindexed[nNotindexed++] = zVal; - zVal = 0; - break; - - default: - assert( iOpt==SizeofArray(aFts4Opt) ); - sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z); - rc = SQLITE_ERROR; - break; - } - sqlite3_free(zVal); - } - } - - /* Otherwise, the argument is a column name. */ - else { - nString += (int)(strlen(z) + 1); - aCol[nCol++] = z; - } - } - - /* If a content=xxx option was specified, the following: - ** - ** 1. Ignore any compress= and uncompress= options. - ** - ** 2. If no column names were specified as part of the CREATE VIRTUAL - ** TABLE statement, use all columns from the content table. - */ - if( rc==SQLITE_OK && zContent ){ - sqlite3_free(zCompress); - sqlite3_free(zUncompress); - zCompress = 0; - zUncompress = 0; - if( nCol==0 ){ - sqlite3_free((void*)aCol); - aCol = 0; - rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr); - - /* If a languageid= option was specified, remove the language id - ** column from the aCol[] array. */ - if( rc==SQLITE_OK && zLanguageid ){ - int j; - for(j=0; jdb = db; - p->nColumn = nCol; - p->nPendingData = 0; - p->azColumn = (char **)&p[1]; - p->pTokenizer = pTokenizer; - p->nMaxPendingData = FTS3_MAX_PENDING_DATA; - p->bHasDocsize = (isFts4 && bNoDocsize==0); - p->bHasStat = (u8)isFts4; - p->bFts4 = (u8)isFts4; - p->bDescIdx = (u8)bDescIdx; - p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */ - p->zContentTbl = zContent; - p->zLanguageid = zLanguageid; - zContent = 0; - zLanguageid = 0; - TESTONLY( p->inTransaction = -1 ); - TESTONLY( p->mxSavepoint = -1 ); - - p->aIndex = (struct Fts3Index *)&p->azColumn[nCol]; - memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex); - p->nIndex = nIndex; - for(i=0; iaIndex[i].hPending, FTS3_HASH_STRING, 1); - } - p->abNotindexed = (u8 *)&p->aIndex[nIndex]; - - /* Fill in the zName and zDb fields of the vtab structure. */ - zCsr = (char *)&p->abNotindexed[nCol]; - p->zName = zCsr; - memcpy(zCsr, argv[2], nName); - zCsr += nName; - p->zDb = zCsr; - memcpy(zCsr, argv[1], nDb); - zCsr += nDb; - - /* Fill in the azColumn array */ - for(iCol=0; iCol0 ){ - memcpy(zCsr, z, n); - } - zCsr[n] = '\0'; - sqlite3Fts3Dequote(zCsr); - p->azColumn[iCol] = zCsr; - zCsr += n+1; - assert( zCsr <= &((char *)p)[nByte] ); - } - - /* Fill in the abNotindexed array */ - for(iCol=0; iColazColumn[iCol]); - for(i=0; iazColumn[iCol], zNot, n) - ){ - p->abNotindexed[iCol] = 1; - sqlite3_free(zNot); - azNotindexed[i] = 0; - } - } - } - for(i=0; izReadExprlist = fts3ReadExprList(p, zUncompress, &rc); - p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc); - if( rc!=SQLITE_OK ) goto fts3_init_out; - - /* If this is an xCreate call, create the underlying tables in the - ** database. TODO: For xConnect(), it could verify that said tables exist. - */ - if( isCreate ){ - rc = fts3CreateTables(p); - } - - /* Check to see if a legacy fts3 table has been "upgraded" by the - ** addition of a %_stat table so that it can use incremental merge. - */ - if( !isFts4 && !isCreate ){ - p->bHasStat = 2; - } - - /* Figure out the page-size for the database. This is required in order to - ** estimate the cost of loading large doclists from the database. */ - fts3DatabasePageSize(&rc, p); - p->nNodeSize = p->nPgsz-35; - -#if defined(SQLITE_DEBUG)||defined(SQLITE_TEST) - p->nMergeCount = FTS3_MERGE_COUNT; -#endif - - /* Declare the table schema to SQLite. */ - fts3DeclareVtab(&rc, p); - -fts3_init_out: - sqlite3_free(zPrefix); - sqlite3_free(aIndex); - sqlite3_free(zCompress); - sqlite3_free(zUncompress); - sqlite3_free(zContent); - sqlite3_free(zLanguageid); - for(i=0; ipModule->xDestroy(pTokenizer); - } - }else{ - assert( p->pSegments==0 ); - *ppVTab = &p->base; - } - return rc; -} - -/* -** The xConnect() and xCreate() methods for the virtual table. All the -** work is done in function fts3InitVtab(). -*/ -static int fts3ConnectMethod( - sqlite3 *db, /* Database connection */ - void *pAux, /* Pointer to tokenizer hash table */ - int argc, /* Number of elements in argv array */ - const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ -){ - return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr); -} -static int fts3CreateMethod( - sqlite3 *db, /* Database connection */ - void *pAux, /* Pointer to tokenizer hash table */ - int argc, /* Number of elements in argv array */ - const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ -){ - return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr); -} - -/* -** Set the pIdxInfo->estimatedRows variable to nRow. Unless this -** extension is currently being used by a version of SQLite too old to -** support estimatedRows. In that case this function is a no-op. -*/ -static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ -#if SQLITE_VERSION_NUMBER>=3008002 - if( sqlite3_libversion_number()>=3008002 ){ - pIdxInfo->estimatedRows = nRow; - } -#endif -} - -/* -** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this -** extension is currently being used by a version of SQLite too old to -** support index-info flags. In that case this function is a no-op. -*/ -static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){ -#if SQLITE_VERSION_NUMBER>=3008012 - if( sqlite3_libversion_number()>=3008012 ){ - pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE; - } -#endif -} - -/* -** Implementation of the xBestIndex method for FTS3 tables. There -** are three possible strategies, in order of preference: -** -** 1. Direct lookup by rowid or docid. -** 2. Full-text search using a MATCH operator on a non-docid column. -** 3. Linear scan of %_content table. -*/ -static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ - Fts3Table *p = (Fts3Table *)pVTab; - int i; /* Iterator variable */ - int iCons = -1; /* Index of constraint to use */ - - int iLangidCons = -1; /* Index of langid=x constraint, if present */ - int iDocidGe = -1; /* Index of docid>=x constraint, if present */ - int iDocidLe = -1; /* Index of docid<=x constraint, if present */ - int iIdx; - - if( p->bLock ){ - return SQLITE_ERROR; - } - - /* By default use a full table scan. This is an expensive option, - ** so search through the constraints to see if a more efficient - ** strategy is possible. - */ - pInfo->idxNum = FTS3_FULLSCAN_SEARCH; - pInfo->estimatedCost = 5000000; - for(i=0; inConstraint; i++){ - int bDocid; /* True if this constraint is on docid */ - struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i]; - if( pCons->usable==0 ){ - if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ - /* There exists an unusable MATCH constraint. This means that if - ** the planner does elect to use the results of this call as part - ** of the overall query plan the user will see an "unable to use - ** function MATCH in the requested context" error. To discourage - ** this, return a very high cost here. */ - pInfo->idxNum = FTS3_FULLSCAN_SEARCH; - pInfo->estimatedCost = 1e50; - fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50); - return SQLITE_OK; - } - continue; - } - - bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1); - - /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */ - if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){ - pInfo->idxNum = FTS3_DOCID_SEARCH; - pInfo->estimatedCost = 1.0; - iCons = i; - } - - /* A MATCH constraint. Use a full-text search. - ** - ** If there is more than one MATCH constraint available, use the first - ** one encountered. If there is both a MATCH constraint and a direct - ** rowid/docid lookup, prefer the MATCH strategy. This is done even - ** though the rowid/docid lookup is faster than a MATCH query, selecting - ** it would lead to an "unable to use function MATCH in the requested - ** context" error. - */ - if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH - && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn - ){ - pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn; - pInfo->estimatedCost = 2.0; - iCons = i; - } - - /* Equality constraint on the langid column */ - if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ - && pCons->iColumn==p->nColumn + 2 - ){ - iLangidCons = i; - } - - if( bDocid ){ - switch( pCons->op ){ - case SQLITE_INDEX_CONSTRAINT_GE: - case SQLITE_INDEX_CONSTRAINT_GT: - iDocidGe = i; - break; - - case SQLITE_INDEX_CONSTRAINT_LE: - case SQLITE_INDEX_CONSTRAINT_LT: - iDocidLe = i; - break; - } - } - } - - /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */ - if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo); - - iIdx = 1; - if( iCons>=0 ){ - pInfo->aConstraintUsage[iCons].argvIndex = iIdx++; - pInfo->aConstraintUsage[iCons].omit = 1; - } - if( iLangidCons>=0 ){ - pInfo->idxNum |= FTS3_HAVE_LANGID; - pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++; - } - if( iDocidGe>=0 ){ - pInfo->idxNum |= FTS3_HAVE_DOCID_GE; - pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++; - } - if( iDocidLe>=0 ){ - pInfo->idxNum |= FTS3_HAVE_DOCID_LE; - pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++; - } - - /* Regardless of the strategy selected, FTS can deliver rows in rowid (or - ** docid) order. Both ascending and descending are possible. - */ - if( pInfo->nOrderBy==1 ){ - struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0]; - if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){ - if( pOrder->desc ){ - pInfo->idxStr = "DESC"; - }else{ - pInfo->idxStr = "ASC"; - } - pInfo->orderByConsumed = 1; - } - } - - assert( p->pSegments==0 ); - return SQLITE_OK; -} - -/* -** Implementation of xOpen method. -*/ -static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ - sqlite3_vtab_cursor *pCsr; /* Allocated cursor */ - - UNUSED_PARAMETER(pVTab); - - /* Allocate a buffer large enough for an Fts3Cursor structure. If the - ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, - ** if the allocation fails, return SQLITE_NOMEM. - */ - *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor)); - if( !pCsr ){ - return SQLITE_NOMEM; - } - memset(pCsr, 0, sizeof(Fts3Cursor)); - return SQLITE_OK; -} - -/* -** Finalize the statement handle at pCsr->pStmt. -** -** Or, if that statement handle is one created by fts3CursorSeekStmt(), -** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement -** pointer there instead of finalizing it. -*/ -static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){ - if( pCsr->bSeekStmt ){ - Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; - if( p->pSeekStmt==0 ){ - p->pSeekStmt = pCsr->pStmt; - sqlite3_reset(pCsr->pStmt); - pCsr->pStmt = 0; - } - pCsr->bSeekStmt = 0; - } - sqlite3_finalize(pCsr->pStmt); -} - -/* -** Free all resources currently held by the cursor passed as the only -** argument. -*/ -static void fts3ClearCursor(Fts3Cursor *pCsr){ - fts3CursorFinalizeStmt(pCsr); - sqlite3Fts3FreeDeferredTokens(pCsr); - sqlite3_free(pCsr->aDoclist); - sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); - sqlite3Fts3ExprFree(pCsr->pExpr); - memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor)); -} - -/* -** Close the cursor. For additional information see the documentation -** on the xClose method of the virtual table interface. -*/ -static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){ - Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; - assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); - fts3ClearCursor(pCsr); - assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then -** compose and prepare an SQL statement of the form: -** -** "SELECT FROM %_content WHERE rowid = ?" -** -** (or the equivalent for a content=xxx table) and set pCsr->pStmt to -** it. If an error occurs, return an SQLite error code. -*/ -static int fts3CursorSeekStmt(Fts3Cursor *pCsr){ - int rc = SQLITE_OK; - if( pCsr->pStmt==0 ){ - Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; - char *zSql; - if( p->pSeekStmt ){ - pCsr->pStmt = p->pSeekStmt; - p->pSeekStmt = 0; - }else{ - zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); - if( !zSql ) return SQLITE_NOMEM; - p->bLock++; - rc = sqlite3_prepare_v3( - p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0 - ); - p->bLock--; - sqlite3_free(zSql); - } - if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1; - } - return rc; -} - -/* -** Position the pCsr->pStmt statement so that it is on the row -** of the %_content table that contains the last match. Return -** SQLITE_OK on success. -*/ -static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){ - int rc = SQLITE_OK; - if( pCsr->isRequireSeek ){ - rc = fts3CursorSeekStmt(pCsr); - if( rc==SQLITE_OK ){ - Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab; - pTab->bLock++; - sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); - pCsr->isRequireSeek = 0; - if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ - pTab->bLock--; - return SQLITE_OK; - }else{ - pTab->bLock--; - rc = sqlite3_reset(pCsr->pStmt); - if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){ - /* If no row was found and no error has occurred, then the %_content - ** table is missing a row that is present in the full-text index. - ** The data structures are corrupt. */ - rc = FTS_CORRUPT_VTAB; - pCsr->isEof = 1; - } - } - } - } - - if( rc!=SQLITE_OK && pContext ){ - sqlite3_result_error_code(pContext, rc); - } - return rc; -} - -/* -** This function is used to process a single interior node when searching -** a b-tree for a term or term prefix. The node data is passed to this -** function via the zNode/nNode parameters. The term to search for is -** passed in zTerm/nTerm. -** -** If piFirst is not NULL, then this function sets *piFirst to the blockid -** of the child node that heads the sub-tree that may contain the term. -** -** If piLast is not NULL, then *piLast is set to the right-most child node -** that heads a sub-tree that may contain a term for which zTerm/nTerm is -** a prefix. -** -** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. -*/ -static int fts3ScanInteriorNode( - const char *zTerm, /* Term to select leaves for */ - int nTerm, /* Size of term zTerm in bytes */ - const char *zNode, /* Buffer containing segment interior node */ - int nNode, /* Size of buffer at zNode */ - sqlite3_int64 *piFirst, /* OUT: Selected child node */ - sqlite3_int64 *piLast /* OUT: Selected child node */ -){ - int rc = SQLITE_OK; /* Return code */ - const char *zCsr = zNode; /* Cursor to iterate through node */ - const char *zEnd = &zCsr[nNode];/* End of interior node buffer */ - char *zBuffer = 0; /* Buffer to load terms into */ - i64 nAlloc = 0; /* Size of allocated buffer */ - int isFirstTerm = 1; /* True when processing first term on page */ - sqlite3_int64 iChild; /* Block id of child node to descend to */ - int nBuffer = 0; /* Total term size */ - - /* Skip over the 'height' varint that occurs at the start of every - ** interior node. Then load the blockid of the left-child of the b-tree - ** node into variable iChild. - ** - ** Even if the data structure on disk is corrupted, this (reading two - ** varints from the buffer) does not risk an overread. If zNode is a - ** root node, then the buffer comes from a SELECT statement. SQLite does - ** not make this guarantee explicitly, but in practice there are always - ** either more than 20 bytes of allocated space following the nNode bytes of - ** contents, or two zero bytes. Or, if the node is read from the %_segments - ** table, then there are always 20 bytes of zeroed padding following the - ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details). - */ - zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); - zCsr += sqlite3Fts3GetVarint(zCsr, &iChild); - if( zCsr>zEnd ){ - return FTS_CORRUPT_VTAB; - } - - while( zCsrnBuffer ){ - rc = FTS_CORRUPT_VTAB; - goto finish_scan; - } - } - isFirstTerm = 0; - zCsr += fts3GetVarint32(zCsr, &nSuffix); - - assert( nPrefix>=0 && nSuffix>=0 ); - if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){ - rc = FTS_CORRUPT_VTAB; - goto finish_scan; - } - if( (i64)nPrefix+nSuffix>nAlloc ){ - char *zNew; - nAlloc = ((i64)nPrefix+nSuffix) * 2; - zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc); - if( !zNew ){ - rc = SQLITE_NOMEM; - goto finish_scan; - } - zBuffer = zNew; - } - assert( zBuffer ); - memcpy(&zBuffer[nPrefix], zCsr, nSuffix); - nBuffer = nPrefix + nSuffix; - zCsr += nSuffix; - - /* Compare the term we are searching for with the term just loaded from - ** the interior node. If the specified term is greater than or equal - ** to the term from the interior node, then all terms on the sub-tree - ** headed by node iChild are smaller than zTerm. No need to search - ** iChild. - ** - ** If the interior node term is larger than the specified term, then - ** the tree headed by iChild may contain the specified term. - */ - cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer)); - if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){ - *piFirst = iChild; - piFirst = 0; - } - - if( piLast && cmp<0 ){ - *piLast = iChild; - piLast = 0; - } - - iChild++; - }; - - if( piFirst ) *piFirst = iChild; - if( piLast ) *piLast = iChild; - - finish_scan: - sqlite3_free(zBuffer); - return rc; -} - - -/* -** The buffer pointed to by argument zNode (size nNode bytes) contains an -** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes) -** contains a term. This function searches the sub-tree headed by the zNode -** node for the range of leaf nodes that may contain the specified term -** or terms for which the specified term is a prefix. -** -** If piLeaf is not NULL, then *piLeaf is set to the blockid of the -** left-most leaf node in the tree that may contain the specified term. -** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the -** right-most leaf node that may contain a term for which the specified -** term is a prefix. -** -** It is possible that the range of returned leaf nodes does not contain -** the specified term or any terms for which it is a prefix. However, if the -** segment does contain any such terms, they are stored within the identified -** range. Because this function only inspects interior segment nodes (and -** never loads leaf nodes into memory), it is not possible to be sure. -** -** If an error occurs, an error code other than SQLITE_OK is returned. -*/ -static int fts3SelectLeaf( - Fts3Table *p, /* Virtual table handle */ - const char *zTerm, /* Term to select leaves for */ - int nTerm, /* Size of term zTerm in bytes */ - const char *zNode, /* Buffer containing segment interior node */ - int nNode, /* Size of buffer at zNode */ - sqlite3_int64 *piLeaf, /* Selected leaf node */ - sqlite3_int64 *piLeaf2 /* Selected leaf node */ -){ - int rc = SQLITE_OK; /* Return code */ - int iHeight; /* Height of this node in tree */ - - assert( piLeaf || piLeaf2 ); - - fts3GetVarint32(zNode, &iHeight); - rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); - assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); - - if( rc==SQLITE_OK && iHeight>1 ){ - char *zBlob = 0; /* Blob read from %_segments table */ - int nBlob = 0; /* Size of zBlob in bytes */ - - if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ - rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); - if( rc==SQLITE_OK ){ - rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); - } - sqlite3_free(zBlob); - piLeaf = 0; - zBlob = 0; - } - - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); - } - if( rc==SQLITE_OK ){ - int iNewHeight = 0; - fts3GetVarint32(zBlob, &iNewHeight); - if( iNewHeight>=iHeight ){ - rc = FTS_CORRUPT_VTAB; - }else{ - rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); - } - } - sqlite3_free(zBlob); - } - - return rc; -} - -/* -** This function is used to create delta-encoded serialized lists of FTS3 -** varints. Each call to this function appends a single varint to a list. -*/ -static void fts3PutDeltaVarint( - char **pp, /* IN/OUT: Output pointer */ - sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ - sqlite3_int64 iVal /* Write this value to the list */ -){ - assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); - *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); - *piPrev = iVal; -} - -/* -** When this function is called, *ppPoslist is assumed to point to the -** start of a position-list. After it returns, *ppPoslist points to the -** first byte after the position-list. -** -** A position list is list of positions (delta encoded) and columns for -** a single document record of a doclist. So, in other words, this -** routine advances *ppPoslist so that it points to the next docid in -** the doclist, or to the first byte past the end of the doclist. -** -** If pp is not NULL, then the contents of the position list are copied -** to *pp. *pp is set to point to the first byte past the last byte copied -** before this function returns. -*/ -static void fts3PoslistCopy(char **pp, char **ppPoslist){ - char *pEnd = *ppPoslist; - char c = 0; - - /* The end of a position list is marked by a zero encoded as an FTS3 - ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by - ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail - ** of some other, multi-byte, value. - ** - ** The following while-loop moves pEnd to point to the first byte that is not - ** immediately preceded by a byte with the 0x80 bit set. Then increments - ** pEnd once more so that it points to the byte immediately following the - ** last byte in the position-list. - */ - while( *pEnd | c ){ - c = *pEnd++ & 0x80; - testcase( c!=0 && (*pEnd)==0 ); - } - pEnd++; /* Advance past the POS_END terminator byte */ - - if( pp ){ - int n = (int)(pEnd - *ppPoslist); - char *p = *pp; - memcpy(p, *ppPoslist, n); - p += n; - *pp = p; - } - *ppPoslist = pEnd; -} - -/* -** When this function is called, *ppPoslist is assumed to point to the -** start of a column-list. After it returns, *ppPoslist points to the -** to the terminator (POS_COLUMN or POS_END) byte of the column-list. -** -** A column-list is list of delta-encoded positions for a single column -** within a single document within a doclist. -** -** The column-list is terminated either by a POS_COLUMN varint (1) or -** a POS_END varint (0). This routine leaves *ppPoslist pointing to -** the POS_COLUMN or POS_END that terminates the column-list. -** -** If pp is not NULL, then the contents of the column-list are copied -** to *pp. *pp is set to point to the first byte past the last byte copied -** before this function returns. The POS_COLUMN or POS_END terminator -** is not copied into *pp. -*/ -static void fts3ColumnlistCopy(char **pp, char **ppPoslist){ - char *pEnd = *ppPoslist; - char c = 0; - - /* A column-list is terminated by either a 0x01 or 0x00 byte that is - ** not part of a multi-byte varint. - */ - while( 0xFE & (*pEnd | c) ){ - c = *pEnd++ & 0x80; - testcase( c!=0 && ((*pEnd)&0xfe)==0 ); - } - if( pp ){ - int n = (int)(pEnd - *ppPoslist); - char *p = *pp; - memcpy(p, *ppPoslist, n); - p += n; - *pp = p; - } - *ppPoslist = pEnd; -} - -/* -** Value used to signify the end of an position-list. This must be -** as large or larger than any value that might appear on the -** position-list, even a position list that has been corrupted. -*/ -#define POSITION_LIST_END LARGEST_INT64 - -/* -** This function is used to help parse position-lists. When this function is -** called, *pp may point to the start of the next varint in the position-list -** being parsed, or it may point to 1 byte past the end of the position-list -** (in which case **pp will be a terminator bytes POS_END (0) or -** (1)). -** -** If *pp points past the end of the current position-list, set *pi to -** POSITION_LIST_END and return. Otherwise, read the next varint from *pp, -** increment the current value of *pi by the value read, and set *pp to -** point to the next value before returning. -** -** Before calling this routine *pi must be initialized to the value of -** the previous position, or zero if we are reading the first position -** in the position-list. Because positions are delta-encoded, the value -** of the previous position is needed in order to compute the value of -** the next position. -*/ -static void fts3ReadNextPos( - char **pp, /* IN/OUT: Pointer into position-list buffer */ - sqlite3_int64 *pi /* IN/OUT: Value read from position-list */ -){ - if( (**pp)&0xFE ){ - int iVal; - *pp += fts3GetVarint32((*pp), &iVal); - *pi += iVal; - *pi -= 2; - }else{ - *pi = POSITION_LIST_END; - } -} - -/* -** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by -** the value of iCol encoded as a varint to *pp. This will start a new -** column list. -** -** Set *pp to point to the byte just after the last byte written before -** returning (do not modify it if iCol==0). Return the total number of bytes -** written (0 if iCol==0). -*/ -static int fts3PutColNumber(char **pp, int iCol){ - int n = 0; /* Number of bytes written */ - if( iCol ){ - char *p = *pp; /* Output pointer */ - n = 1 + sqlite3Fts3PutVarint(&p[1], iCol); - *p = 0x01; - *pp = &p[n]; - } - return n; -} - -/* -** Compute the union of two position lists. The output written -** into *pp contains all positions of both *pp1 and *pp2 in sorted -** order and with any duplicates removed. All pointers are -** updated appropriately. The caller is responsible for insuring -** that there is enough space in *pp to hold the complete output. -*/ -static int fts3PoslistMerge( - char **pp, /* Output buffer */ - char **pp1, /* Left input list */ - char **pp2 /* Right input list */ -){ - char *p = *pp; - char *p1 = *pp1; - char *p2 = *pp2; - - while( *p1 || *p2 ){ - int iCol1; /* The current column index in pp1 */ - int iCol2; /* The current column index in pp2 */ - - if( *p1==POS_COLUMN ){ - fts3GetVarint32(&p1[1], &iCol1); - if( iCol1==0 ) return FTS_CORRUPT_VTAB; - } - else if( *p1==POS_END ) iCol1 = 0x7fffffff; - else iCol1 = 0; - - if( *p2==POS_COLUMN ){ - fts3GetVarint32(&p2[1], &iCol2); - if( iCol2==0 ) return FTS_CORRUPT_VTAB; - } - else if( *p2==POS_END ) iCol2 = 0x7fffffff; - else iCol2 = 0; - - if( iCol1==iCol2 ){ - sqlite3_int64 i1 = 0; /* Last position from pp1 */ - sqlite3_int64 i2 = 0; /* Last position from pp2 */ - sqlite3_int64 iPrev = 0; - int n = fts3PutColNumber(&p, iCol1); - p1 += n; - p2 += n; - - /* At this point, both p1 and p2 point to the start of column-lists - ** for the same column (the column with index iCol1 and iCol2). - ** A column-list is a list of non-negative delta-encoded varints, each - ** incremented by 2 before being stored. Each list is terminated by a - ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists - ** and writes the results to buffer p. p is left pointing to the byte - ** after the list written. No terminator (POS_END or POS_COLUMN) is - ** written to the output. - */ - fts3GetDeltaVarint(&p1, &i1); - fts3GetDeltaVarint(&p2, &i2); - if( i1<2 || i2<2 ){ - break; - } - do { - fts3PutDeltaVarint(&p, &iPrev, (i1pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e. -** when the *pp1 token appears before the *pp2 token, but not more than nToken -** slots before it. -** -** e.g. nToken==1 searches for adjacent positions. -*/ -static int fts3PoslistPhraseMerge( - char **pp, /* IN/OUT: Preallocated output buffer */ - int nToken, /* Maximum difference in token positions */ - int isSaveLeft, /* Save the left position */ - int isExact, /* If *pp1 is exactly nTokens before *pp2 */ - char **pp1, /* IN/OUT: Left input list */ - char **pp2 /* IN/OUT: Right input list */ -){ - char *p = *pp; - char *p1 = *pp1; - char *p2 = *pp2; - int iCol1 = 0; - int iCol2 = 0; - - /* Never set both isSaveLeft and isExact for the same invocation. */ - assert( isSaveLeft==0 || isExact==0 ); - - assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 ); - if( *p1==POS_COLUMN ){ - p1++; - p1 += fts3GetVarint32(p1, &iCol1); - } - if( *p2==POS_COLUMN ){ - p2++; - p2 += fts3GetVarint32(p2, &iCol2); - } - - while( 1 ){ - if( iCol1==iCol2 ){ - char *pSave = p; - sqlite3_int64 iPrev = 0; - sqlite3_int64 iPos1 = 0; - sqlite3_int64 iPos2 = 0; - - if( iCol1 ){ - *p++ = POS_COLUMN; - p += sqlite3Fts3PutVarint(p, iCol1); - } - - fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; - fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; - if( iPos1<0 || iPos2<0 ) break; - - while( 1 ){ - if( iPos2==iPos1+nToken - || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) - ){ - sqlite3_int64 iSave; - iSave = isSaveLeft ? iPos1 : iPos2; - fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2; - pSave = 0; - assert( p ); - } - if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){ - if( (*p2&0xFE)==0 ) break; - fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; - }else{ - if( (*p1&0xFE)==0 ) break; - fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; - } - } - - if( pSave ){ - assert( pp && p ); - p = pSave; - } - - fts3ColumnlistCopy(0, &p1); - fts3ColumnlistCopy(0, &p2); - assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 ); - if( 0==*p1 || 0==*p2 ) break; - - p1++; - p1 += fts3GetVarint32(p1, &iCol1); - p2++; - p2 += fts3GetVarint32(p2, &iCol2); - } - - /* Advance pointer p1 or p2 (whichever corresponds to the smaller of - ** iCol1 and iCol2) so that it points to either the 0x00 that marks the - ** end of the position list, or the 0x01 that precedes the next - ** column-number in the position list. - */ - else if( iCol1=pEnd ){ - *pp = 0; - }else{ - u64 iVal; - *pp += sqlite3Fts3GetVarintU(*pp, &iVal); - if( bDescIdx ){ - *pVal = (i64)((u64)*pVal - iVal); - }else{ - *pVal = (i64)((u64)*pVal + iVal); - } - } -} - -/* -** This function is used to write a single varint to a buffer. The varint -** is written to *pp. Before returning, *pp is set to point 1 byte past the -** end of the value written. -** -** If *pbFirst is zero when this function is called, the value written to -** the buffer is that of parameter iVal. -** -** If *pbFirst is non-zero when this function is called, then the value -** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal) -** (if bDescIdx is non-zero). -** -** Before returning, this function always sets *pbFirst to 1 and *piPrev -** to the value of parameter iVal. -*/ -static void fts3PutDeltaVarint3( - char **pp, /* IN/OUT: Output pointer */ - int bDescIdx, /* True for descending docids */ - sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */ - int *pbFirst, /* IN/OUT: True after first int written */ - sqlite3_int64 iVal /* Write this value to the list */ -){ - sqlite3_uint64 iWrite; - if( bDescIdx==0 || *pbFirst==0 ){ - assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev ); - iWrite = (u64)iVal - (u64)*piPrev; - }else{ - assert_fts3_nc( *piPrev>=iVal ); - iWrite = (u64)*piPrev - (u64)iVal; - } - assert( *pbFirst || *piPrev==0 ); - assert_fts3_nc( *pbFirst==0 || iWrite>0 ); - *pp += sqlite3Fts3PutVarint(*pp, iWrite); - *piPrev = iVal; - *pbFirst = 1; -} - - -/* -** This macro is used by various functions that merge doclists. The two -** arguments are 64-bit docid values. If the value of the stack variable -** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). -** Otherwise, (i2-i1). -** -** Using this makes it easier to write code that can merge doclists that are -** sorted in either ascending or descending order. -*/ -/* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */ -#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1))) - -/* -** This function does an "OR" merge of two doclists (output contains all -** positions contained in either argument doclist). If the docids in the -** input doclists are sorted in ascending order, parameter bDescDoclist -** should be false. If they are sorted in ascending order, it should be -** passed a non-zero value. -** -** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer -** containing the output doclist and SQLITE_OK is returned. In this case -** *pnOut is set to the number of bytes in the output doclist. -** -** If an error occurs, an SQLite error code is returned. The output values -** are undefined in this case. -*/ -static int fts3DoclistOrMerge( - int bDescDoclist, /* True if arguments are desc */ - char *a1, int n1, /* First doclist */ - char *a2, int n2, /* Second doclist */ - char **paOut, int *pnOut /* OUT: Malloc'd doclist */ -){ - int rc = SQLITE_OK; - sqlite3_int64 i1 = 0; - sqlite3_int64 i2 = 0; - sqlite3_int64 iPrev = 0; - char *pEnd1 = &a1[n1]; - char *pEnd2 = &a2[n2]; - char *p1 = a1; - char *p2 = a2; - char *p; - char *aOut; - int bFirstOut = 0; - - *paOut = 0; - *pnOut = 0; - - /* Allocate space for the output. Both the input and output doclists - ** are delta encoded. If they are in ascending order (bDescDoclist==0), - ** then the first docid in each list is simply encoded as a varint. For - ** each subsequent docid, the varint stored is the difference between the - ** current and previous docid (a positive number - since the list is in - ** ascending order). - ** - ** The first docid written to the output is therefore encoded using the - ** same number of bytes as it is in whichever of the input lists it is - ** read from. And each subsequent docid read from the same input list - ** consumes either the same or less bytes as it did in the input (since - ** the difference between it and the previous value in the output must - ** be a positive value less than or equal to the delta value read from - ** the input list). The same argument applies to all but the first docid - ** read from the 'other' list. And to the contents of all position lists - ** that will be copied and merged from the input to the output. - ** - ** However, if the first docid copied to the output is a negative number, - ** then the encoding of the first docid from the 'other' input list may - ** be larger in the output than it was in the input (since the delta value - ** may be a larger positive integer than the actual docid). - ** - ** The space required to store the output is therefore the sum of the - ** sizes of the two inputs, plus enough space for exactly one of the input - ** docids to grow. - ** - ** A symetric argument may be made if the doclists are in descending - ** order. - */ - aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING); - if( !aOut ) return SQLITE_NOMEM; - - p = aOut; - fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); - fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); - while( p1 || p2 ){ - sqlite3_int64 iDiff = DOCID_CMP(i1, i2); - - if( p2 && p1 && iDiff==0 ){ - fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); - rc = fts3PoslistMerge(&p, &p1, &p2); - if( rc ) break; - fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); - fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); - }else if( !p2 || (p1 && iDiff<0) ){ - fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); - fts3PoslistCopy(&p, &p1); - fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); - }else{ - fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2); - fts3PoslistCopy(&p, &p2); - fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); - } - - assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) ); - } - - if( rc!=SQLITE_OK ){ - sqlite3_free(aOut); - p = aOut = 0; - }else{ - assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 ); - memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING); - } - *paOut = aOut; - *pnOut = (int)(p-aOut); - return rc; -} - -/* -** This function does a "phrase" merge of two doclists. In a phrase merge, -** the output contains a copy of each position from the right-hand input -** doclist for which there is a position in the left-hand input doclist -** exactly nDist tokens before it. -** -** If the docids in the input doclists are sorted in ascending order, -** parameter bDescDoclist should be false. If they are sorted in ascending -** order, it should be passed a non-zero value. -** -** The right-hand input doclist is overwritten by this function. -*/ -static int fts3DoclistPhraseMerge( - int bDescDoclist, /* True if arguments are desc */ - int nDist, /* Distance from left to right (1=adjacent) */ - char *aLeft, int nLeft, /* Left doclist */ - char **paRight, int *pnRight /* IN/OUT: Right/output doclist */ -){ - sqlite3_int64 i1 = 0; - sqlite3_int64 i2 = 0; - sqlite3_int64 iPrev = 0; - char *aRight = *paRight; - char *pEnd1 = &aLeft[nLeft]; - char *pEnd2 = &aRight[*pnRight]; - char *p1 = aLeft; - char *p2 = aRight; - char *p; - int bFirstOut = 0; - char *aOut; - - assert( nDist>0 ); - if( bDescDoclist ){ - aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX); - if( aOut==0 ) return SQLITE_NOMEM; - }else{ - aOut = aRight; - } - p = aOut; - - fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1); - fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2); - - while( p1 && p2 ){ - sqlite3_int64 iDiff = DOCID_CMP(i1, i2); - if( iDiff==0 ){ - char *pSave = p; - sqlite3_int64 iPrevSave = iPrev; - int bFirstOutSave = bFirstOut; - - fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1); - if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){ - p = pSave; - iPrev = iPrevSave; - bFirstOut = bFirstOutSave; - } - fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); - fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); - }else if( iDiff<0 ){ - fts3PoslistCopy(0, &p1); - fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1); - }else{ - fts3PoslistCopy(0, &p2); - fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2); - } - } - - *pnRight = (int)(p - aOut); - if( bDescDoclist ){ - sqlite3_free(aRight); - *paRight = aOut; - } - - return SQLITE_OK; -} - -/* -** Argument pList points to a position list nList bytes in size. This -** function checks to see if the position list contains any entries for -** a token in position 0 (of any column). If so, it writes argument iDelta -** to the output buffer pOut, followed by a position list consisting only -** of the entries from pList at position 0, and terminated by an 0x00 byte. -** The value returned is the number of bytes written to pOut (if any). -*/ -SQLITE_PRIVATE int sqlite3Fts3FirstFilter( - sqlite3_int64 iDelta, /* Varint that may be written to pOut */ - char *pList, /* Position list (no 0x00 term) */ - int nList, /* Size of pList in bytes */ - char *pOut /* Write output here */ -){ - int nOut = 0; - int bWritten = 0; /* True once iDelta has been written */ - char *p = pList; - char *pEnd = &pList[nList]; - - if( *p!=0x01 ){ - if( *p==0x02 ){ - nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta); - pOut[nOut++] = 0x02; - bWritten = 1; - } - fts3ColumnlistCopy(0, &p); - } - - while( paaOutput); i++){ - if( pTS->aaOutput[i] ){ - if( !aOut ){ - aOut = pTS->aaOutput[i]; - nOut = pTS->anOutput[i]; - pTS->aaOutput[i] = 0; - }else{ - int nNew; - char *aNew; - - int rc = fts3DoclistOrMerge(p->bDescIdx, - pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew - ); - if( rc!=SQLITE_OK ){ - sqlite3_free(aOut); - return rc; - } - - sqlite3_free(pTS->aaOutput[i]); - sqlite3_free(aOut); - pTS->aaOutput[i] = 0; - aOut = aNew; - nOut = nNew; - } - } - } - - pTS->aaOutput[0] = aOut; - pTS->anOutput[0] = nOut; - return SQLITE_OK; -} - -/* -** Merge the doclist aDoclist/nDoclist into the TermSelect object passed -** as the first argument. The merge is an "OR" merge (see function -** fts3DoclistOrMerge() for details). -** -** This function is called with the doclist for each term that matches -** a queried prefix. It merges all these doclists into one, the doclist -** for the specified prefix. Since there can be a very large number of -** doclists to merge, the merging is done pair-wise using the TermSelect -** object. -** -** This function returns SQLITE_OK if the merge is successful, or an -** SQLite error code (SQLITE_NOMEM) if an error occurs. -*/ -static int fts3TermSelectMerge( - Fts3Table *p, /* FTS table handle */ - TermSelect *pTS, /* TermSelect object to merge into */ - char *aDoclist, /* Pointer to doclist */ - int nDoclist /* Size of aDoclist in bytes */ -){ - if( pTS->aaOutput[0]==0 ){ - /* If this is the first term selected, copy the doclist to the output - ** buffer using memcpy(). - ** - ** Add FTS3_VARINT_MAX bytes of unused space to the end of the - ** allocation. This is so as to ensure that the buffer is big enough - ** to hold the current doclist AND'd with any other doclist. If the - ** doclists are stored in order=ASC order, this padding would not be - ** required (since the size of [doclistA AND doclistB] is always less - ** than or equal to the size of [doclistA] in that case). But this is - ** not true for order=DESC. For example, a doclist containing (1, -1) - ** may be smaller than (-1), as in the first example the -1 may be stored - ** as a single-byte delta, whereas in the second it must be stored as a - ** FTS3_VARINT_MAX byte varint. - ** - ** Similar padding is added in the fts3DoclistOrMerge() function. - */ - pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1); - pTS->anOutput[0] = nDoclist; - if( pTS->aaOutput[0] ){ - memcpy(pTS->aaOutput[0], aDoclist, nDoclist); - memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX); - }else{ - return SQLITE_NOMEM; - } - }else{ - char *aMerge = aDoclist; - int nMerge = nDoclist; - int iOut; - - for(iOut=0; iOutaaOutput); iOut++){ - if( pTS->aaOutput[iOut]==0 ){ - assert( iOut>0 ); - pTS->aaOutput[iOut] = aMerge; - pTS->anOutput[iOut] = nMerge; - break; - }else{ - char *aNew; - int nNew; - - int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, - pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew - ); - if( rc!=SQLITE_OK ){ - if( aMerge!=aDoclist ) sqlite3_free(aMerge); - return rc; - } - - if( aMerge!=aDoclist ) sqlite3_free(aMerge); - sqlite3_free(pTS->aaOutput[iOut]); - pTS->aaOutput[iOut] = 0; - - aMerge = aNew; - nMerge = nNew; - if( (iOut+1)==SizeofArray(pTS->aaOutput) ){ - pTS->aaOutput[iOut] = aMerge; - pTS->anOutput[iOut] = nMerge; - } - } - } - } - return SQLITE_OK; -} - -/* -** Append SegReader object pNew to the end of the pCsr->apSegment[] array. -*/ -static int fts3SegReaderCursorAppend( - Fts3MultiSegReader *pCsr, - Fts3SegReader *pNew -){ - if( (pCsr->nSegment%16)==0 ){ - Fts3SegReader **apNew; - sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); - apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte); - if( !apNew ){ - sqlite3Fts3SegReaderFree(pNew); - return SQLITE_NOMEM; - } - pCsr->apSegment = apNew; - } - pCsr->apSegment[pCsr->nSegment++] = pNew; - return SQLITE_OK; -} - -/* -** Add seg-reader objects to the Fts3MultiSegReader object passed as the -** 8th argument. -** -** This function returns SQLITE_OK if successful, or an SQLite error code -** otherwise. -*/ -static int fts3SegReaderCursor( - Fts3Table *p, /* FTS3 table handle */ - int iLangid, /* Language id */ - int iIndex, /* Index to search (from 0 to p->nIndex-1) */ - int iLevel, /* Level of segments to scan */ - const char *zTerm, /* Term to query for */ - int nTerm, /* Size of zTerm in bytes */ - int isPrefix, /* True for a prefix search */ - int isScan, /* True to scan from zTerm to EOF */ - Fts3MultiSegReader *pCsr /* Cursor object to populate */ -){ - int rc = SQLITE_OK; /* Error code */ - sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */ - int rc2; /* Result of sqlite3_reset() */ - - /* If iLevel is less than 0 and this is not a scan, include a seg-reader - ** for the pending-terms. If this is a scan, then this call must be being - ** made by an fts4aux module, not an FTS table. In this case calling - ** Fts3SegReaderPending might segfault, as the data structures used by - ** fts4aux are not completely populated. So it's easiest to filter these - ** calls out here. */ - if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){ - Fts3SegReader *pSeg = 0; - rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg); - if( rc==SQLITE_OK && pSeg ){ - rc = fts3SegReaderCursorAppend(pCsr, pSeg); - } - } - - if( iLevel!=FTS3_SEGCURSOR_PENDING ){ - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt); - } - - while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ - Fts3SegReader *pSeg = 0; - - /* Read the values returned by the SELECT into local variables. */ - sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1); - sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2); - sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3); - int nRoot = sqlite3_column_bytes(pStmt, 4); - char const *zRoot = sqlite3_column_blob(pStmt, 4); - - /* If zTerm is not NULL, and this segment is not stored entirely on its - ** root node, the range of leaves scanned can be reduced. Do this. */ - if( iStartBlock && zTerm && zRoot ){ - sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0); - rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi); - if( rc!=SQLITE_OK ) goto finished; - if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock; - } - - rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, - (isPrefix==0 && isScan==0), - iStartBlock, iLeavesEndBlock, - iEndBlock, zRoot, nRoot, &pSeg - ); - if( rc!=SQLITE_OK ) goto finished; - rc = fts3SegReaderCursorAppend(pCsr, pSeg); - } - } - - finished: - rc2 = sqlite3_reset(pStmt); - if( rc==SQLITE_DONE ) rc = rc2; - - return rc; -} - -/* -** Set up a cursor object for iterating through a full-text index or a -** single level therein. -*/ -SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor( - Fts3Table *p, /* FTS3 table handle */ - int iLangid, /* Language-id to search */ - int iIndex, /* Index to search (from 0 to p->nIndex-1) */ - int iLevel, /* Level of segments to scan */ - const char *zTerm, /* Term to query for */ - int nTerm, /* Size of zTerm in bytes */ - int isPrefix, /* True for a prefix search */ - int isScan, /* True to scan from zTerm to EOF */ - Fts3MultiSegReader *pCsr /* Cursor object to populate */ -){ - assert( iIndex>=0 && iIndexnIndex ); - assert( iLevel==FTS3_SEGCURSOR_ALL - || iLevel==FTS3_SEGCURSOR_PENDING - || iLevel>=0 - ); - assert( iLevelbase.pVtab; - - if( isPrefix ){ - for(i=1; bFound==0 && inIndex; i++){ - if( p->aIndex[i].nPrefix==nTerm ){ - bFound = 1; - rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, - i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr - ); - pSegcsr->bLookup = 1; - } - } - - for(i=1; bFound==0 && inIndex; i++){ - if( p->aIndex[i].nPrefix==nTerm+1 ){ - bFound = 1; - rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, - i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr - ); - if( rc==SQLITE_OK ){ - rc = fts3SegReaderCursorAddZero( - p, pCsr->iLangid, zTerm, nTerm, pSegcsr - ); - } - } - } - } - - if( bFound==0 ){ - rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, - 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr - ); - pSegcsr->bLookup = !isPrefix; - } - } - - *ppSegcsr = pSegcsr; - return rc; -} - -/* -** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor(). -*/ -static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){ - sqlite3Fts3SegReaderFinish(pSegcsr); - sqlite3_free(pSegcsr); -} - -/* -** This function retrieves the doclist for the specified term (or term -** prefix) from the database. -*/ -static int fts3TermSelect( - Fts3Table *p, /* Virtual table handle */ - Fts3PhraseToken *pTok, /* Token to query for */ - int iColumn, /* Column to query (or -ve for all columns) */ - int *pnOut, /* OUT: Size of buffer at *ppOut */ - char **ppOut /* OUT: Malloced result buffer */ -){ - int rc; /* Return code */ - Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */ - TermSelect tsc; /* Object for pair-wise doclist merging */ - Fts3SegFilter filter; /* Segment term filter configuration */ - - pSegcsr = pTok->pSegcsr; - memset(&tsc, 0, sizeof(TermSelect)); - - filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS - | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0) - | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0) - | (iColumnnColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0); - filter.iCol = iColumn; - filter.zTerm = pTok->z; - filter.nTerm = pTok->n; - - rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter); - while( SQLITE_OK==rc - && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) - ){ - rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist); - } - - if( rc==SQLITE_OK ){ - rc = fts3TermSelectFinishMerge(p, &tsc); - } - if( rc==SQLITE_OK ){ - *ppOut = tsc.aaOutput[0]; - *pnOut = tsc.anOutput[0]; - }else{ - int i; - for(i=0; ipSegcsr = 0; - return rc; -} - -/* -** This function counts the total number of docids in the doclist stored -** in buffer aList[], size nList bytes. -** -** If the isPoslist argument is true, then it is assumed that the doclist -** contains a position-list following each docid. Otherwise, it is assumed -** that the doclist is simply a list of docids stored as delta encoded -** varints. -*/ -static int fts3DoclistCountDocids(char *aList, int nList){ - int nDoc = 0; /* Return value */ - if( aList ){ - char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */ - char *p = aList; /* Cursor */ - while( peSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){ - Fts3Table *pTab = (Fts3Table*)pCursor->pVtab; - pTab->bLock++; - if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){ - pCsr->isEof = 1; - rc = sqlite3_reset(pCsr->pStmt); - }else{ - pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0); - rc = SQLITE_OK; - } - pTab->bLock--; - }else{ - rc = fts3EvalNext((Fts3Cursor *)pCursor); - } - assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); - return rc; -} - -/* -** If the numeric type of argument pVal is "integer", then return it -** converted to a 64-bit signed integer. Otherwise, return a copy of -** the second parameter, iDefault. -*/ -static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){ - if( pVal ){ - int eType = sqlite3_value_numeric_type(pVal); - if( eType==SQLITE_INTEGER ){ - return sqlite3_value_int64(pVal); - } - } - return iDefault; -} - -/* -** This is the xFilter interface for the virtual table. See -** the virtual table xFilter method documentation for additional -** information. -** -** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against -** the %_content table. -** -** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry -** in the %_content table. -** -** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The -** column on the left-hand side of the MATCH operator is column -** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand -** side of the MATCH operator. -*/ -static int fts3FilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ - int idxNum, /* Strategy index */ - const char *idxStr, /* Unused */ - int nVal, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ -){ - int rc = SQLITE_OK; - char *zSql; /* SQL statement used to access %_content */ - int eSearch; - Fts3Table *p = (Fts3Table *)pCursor->pVtab; - Fts3Cursor *pCsr = (Fts3Cursor *)pCursor; - - sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */ - sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */ - sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */ - sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */ - int iIdx; - - UNUSED_PARAMETER(idxStr); - UNUSED_PARAMETER(nVal); - - if( p->bLock ){ - return SQLITE_ERROR; - } - - eSearch = (idxNum & 0x0000FFFF); - assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) ); - assert( p->pSegments==0 ); - - /* Collect arguments into local variables */ - iIdx = 0; - if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++]; - if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++]; - if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++]; - if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++]; - assert( iIdx==nVal ); - - /* In case the cursor has been used before, clear it now. */ - fts3ClearCursor(pCsr); - - /* Set the lower and upper bounds on docids to return */ - pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64); - pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64); - - if( idxStr ){ - pCsr->bDesc = (idxStr[0]=='D'); - }else{ - pCsr->bDesc = p->bDescIdx; - } - pCsr->eSearch = (i16)eSearch; - - if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){ - int iCol = eSearch-FTS3_FULLTEXT_SEARCH; - const char *zQuery = (const char *)sqlite3_value_text(pCons); - - if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){ - return SQLITE_NOMEM; - } - - pCsr->iLangid = 0; - if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid); - - assert( p->base.zErrMsg==0 ); - rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid, - p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, - &p->base.zErrMsg - ); - if( rc!=SQLITE_OK ){ - return rc; - } - - rc = fts3EvalStart(pCsr); - sqlite3Fts3SegmentsClose(p); - if( rc!=SQLITE_OK ) return rc; - pCsr->pNextId = pCsr->aDoclist; - pCsr->iPrevId = 0; - } - - /* Compile a SELECT statement for this cursor. For a full-table-scan, the - ** statement loops through all rows of the %_content table. For a - ** full-text query or docid lookup, the statement retrieves a single - ** row by docid. - */ - if( eSearch==FTS3_FULLSCAN_SEARCH ){ - if( pDocidGe || pDocidLe ){ - zSql = sqlite3_mprintf( - "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s", - p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid, - (pCsr->bDesc ? "DESC" : "ASC") - ); - }else{ - zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", - p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC") - ); - } - if( zSql ){ - p->bLock++; - rc = sqlite3_prepare_v3( - p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0 - ); - p->bLock--; - sqlite3_free(zSql); - }else{ - rc = SQLITE_NOMEM; - } - }else if( eSearch==FTS3_DOCID_SEARCH ){ - rc = fts3CursorSeekStmt(pCsr); - if( rc==SQLITE_OK ){ - rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons); - } - } - if( rc!=SQLITE_OK ) return rc; - - return fts3NextMethod(pCursor); -} - -/* -** This is the xEof method of the virtual table. SQLite calls this -** routine to find out if it has reached the end of a result set. -*/ -static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){ - Fts3Cursor *pCsr = (Fts3Cursor*)pCursor; - if( pCsr->isEof ){ - fts3ClearCursor(pCsr); - pCsr->isEof = 1; - } - return pCsr->isEof; -} - -/* -** This is the xRowid method. The SQLite core calls this routine to -** retrieve the rowid for the current row of the result set. fts3 -** exposes %_content.docid as the rowid for the virtual table. The -** rowid should be written to *pRowid. -*/ -static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ - Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; - *pRowid = pCsr->iPrevId; - return SQLITE_OK; -} - -/* -** This is the xColumn method, called by SQLite to request a value from -** the row that the supplied cursor currently points to. -** -** If: -** -** (iCol < p->nColumn) -> The value of the iCol'th user column. -** (iCol == p->nColumn) -> Magic column with the same name as the table. -** (iCol == p->nColumn+1) -> Docid column -** (iCol == p->nColumn+2) -> Langid column -*/ -static int fts3ColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ - int iCol /* Index of column to read value from */ -){ - int rc = SQLITE_OK; /* Return Code */ - Fts3Cursor *pCsr = (Fts3Cursor *) pCursor; - Fts3Table *p = (Fts3Table *)pCursor->pVtab; - - /* The column value supplied by SQLite must be in range. */ - assert( iCol>=0 && iCol<=p->nColumn+2 ); - - switch( iCol-p->nColumn ){ - case 0: - /* The special 'table-name' column */ - sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0); - break; - - case 1: - /* The docid column */ - sqlite3_result_int64(pCtx, pCsr->iPrevId); - break; - - case 2: - if( pCsr->pExpr ){ - sqlite3_result_int64(pCtx, pCsr->iLangid); - break; - }else if( p->zLanguageid==0 ){ - sqlite3_result_int(pCtx, 0); - break; - }else{ - iCol = p->nColumn; - /* no break */ deliberate_fall_through - } - - default: - /* A user column. Or, if this is a full-table scan, possibly the - ** language-id column. Seek the cursor. */ - rc = fts3CursorSeek(0, pCsr); - if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){ - sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1)); - } - break; - } - - assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); - return rc; -} - -/* -** This function is the implementation of the xUpdate callback used by -** FTS3 virtual tables. It is invoked by SQLite each time a row is to be -** inserted, updated or deleted. -*/ -static int fts3UpdateMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ - int nArg, /* Size of argument array */ - sqlite3_value **apVal, /* Array of arguments */ - sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ -){ - return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid); -} - -/* -** Implementation of xSync() method. Flush the contents of the pending-terms -** hash-table to the database. -*/ -static int fts3SyncMethod(sqlite3_vtab *pVtab){ - - /* Following an incremental-merge operation, assuming that the input - ** segments are not completely consumed (the usual case), they are updated - ** in place to remove the entries that have already been merged. This - ** involves updating the leaf block that contains the smallest unmerged - ** entry and each block (if any) between the leaf and the root node. So - ** if the height of the input segment b-trees is N, and input segments - ** are merged eight at a time, updating the input segments at the end - ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually - ** small - often between 0 and 2. So the overhead of the incremental - ** merge is somewhere between 8 and 24 blocks. To avoid this overhead - ** dwarfing the actual productive work accomplished, the incremental merge - ** is only attempted if it will write at least 64 leaf blocks. Hence - ** nMinMerge. - ** - ** Of course, updating the input segments also involves deleting a bunch - ** of blocks from the segments table. But this is not considered overhead - ** as it would also be required by a crisis-merge that used the same input - ** segments. - */ - const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */ - - Fts3Table *p = (Fts3Table*)pVtab; - int rc; - i64 iLastRowid = sqlite3_last_insert_rowid(p->db); - - rc = sqlite3Fts3PendingTermsFlush(p); - if( rc==SQLITE_OK - && p->nLeafAdd>(nMinMerge/16) - && p->nAutoincrmerge && p->nAutoincrmerge!=0xff - ){ - int mxLevel = 0; /* Maximum relative level value in db */ - int A; /* Incr-merge parameter A */ - - rc = sqlite3Fts3MaxLevel(p, &mxLevel); - assert( rc==SQLITE_OK || mxLevel==0 ); - A = p->nLeafAdd * mxLevel; - A += (A/2); - if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge); - } - sqlite3Fts3SegmentsClose(p); - sqlite3_set_last_insert_rowid(p->db, iLastRowid); - return rc; -} - -/* -** If it is currently unknown whether or not the FTS table has an %_stat -** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat -** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code -** if an error occurs. -*/ -static int fts3SetHasStat(Fts3Table *p){ - int rc = SQLITE_OK; - if( p->bHasStat==2 ){ - char *zTbl = sqlite3_mprintf("%s_stat", p->zName); - if( zTbl ){ - int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0); - sqlite3_free(zTbl); - p->bHasStat = (res==SQLITE_OK); - }else{ - rc = SQLITE_NOMEM; - } - } - return rc; -} - -/* -** Implementation of xBegin() method. -*/ -static int fts3BeginMethod(sqlite3_vtab *pVtab){ - Fts3Table *p = (Fts3Table*)pVtab; - UNUSED_PARAMETER(pVtab); - assert( p->pSegments==0 ); - assert( p->nPendingData==0 ); - assert( p->inTransaction!=1 ); - TESTONLY( p->inTransaction = 1 ); - TESTONLY( p->mxSavepoint = -1; ); - p->nLeafAdd = 0; - return fts3SetHasStat(p); -} - -/* -** Implementation of xCommit() method. This is a no-op. The contents of -** the pending-terms hash-table have already been flushed into the database -** by fts3SyncMethod(). -*/ -static int fts3CommitMethod(sqlite3_vtab *pVtab){ - TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); - UNUSED_PARAMETER(pVtab); - assert( p->nPendingData==0 ); - assert( p->inTransaction!=0 ); - assert( p->pSegments==0 ); - TESTONLY( p->inTransaction = 0 ); - TESTONLY( p->mxSavepoint = -1; ); - return SQLITE_OK; -} - -/* -** Implementation of xRollback(). Discard the contents of the pending-terms -** hash-table. Any changes made to the database are reverted by SQLite. -*/ -static int fts3RollbackMethod(sqlite3_vtab *pVtab){ - Fts3Table *p = (Fts3Table*)pVtab; - sqlite3Fts3PendingTermsClear(p); - assert( p->inTransaction!=0 ); - TESTONLY( p->inTransaction = 0 ); - TESTONLY( p->mxSavepoint = -1; ); - return SQLITE_OK; -} - -/* -** When called, *ppPoslist must point to the byte immediately following the -** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function -** moves *ppPoslist so that it instead points to the first byte of the -** same position list. -*/ -static void fts3ReversePoslist(char *pStart, char **ppPoslist){ - char *p = &(*ppPoslist)[-2]; - char c = 0; - - /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */ - while( p>pStart && (c=*p--)==0 ); - - /* Search backwards for a varint with value zero (the end of the previous - ** poslist). This is an 0x00 byte preceded by some byte that does not - ** have the 0x80 bit set. */ - while( p>pStart && (*p & 0x80) | c ){ - c = *p--; - } - assert( p==pStart || c==0 ); - - /* At this point p points to that preceding byte without the 0x80 bit - ** set. So to find the start of the poslist, skip forward 2 bytes then - ** over a varint. - ** - ** Normally. The other case is that p==pStart and the poslist to return - ** is the first in the doclist. In this case do not skip forward 2 bytes. - ** The second part of the if condition (c==0 && *ppPoslist>&p[2]) - ** is required for cases where the first byte of a doclist and the - ** doclist is empty. For example, if the first docid is 10, a doclist - ** that begins with: - ** - ** 0x0A 0x00 - */ - if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; } - while( *p++&0x80 ); - *ppPoslist = p; -} - -/* -** Helper function used by the implementation of the overloaded snippet(), -** offsets() and optimize() SQL functions. -** -** If the value passed as the third argument is a blob of size -** sizeof(Fts3Cursor*), then the blob contents are copied to the -** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error -** message is written to context pContext and SQLITE_ERROR returned. The -** string passed via zFunc is used as part of the error message. -*/ -static int fts3FunctionArg( - sqlite3_context *pContext, /* SQL function call context */ - const char *zFunc, /* Function name */ - sqlite3_value *pVal, /* argv[0] passed to function */ - Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ -){ - int rc; - *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor"); - if( (*ppCsr)!=0 ){ - rc = SQLITE_OK; - }else{ - char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc); - sqlite3_result_error(pContext, zErr, -1); - sqlite3_free(zErr); - rc = SQLITE_ERROR; - } - return rc; -} - -/* -** Implementation of the snippet() function for FTS3 -*/ -static void fts3SnippetFunc( - sqlite3_context *pContext, /* SQLite function call context */ - int nVal, /* Size of apVal[] array */ - sqlite3_value **apVal /* Array of arguments */ -){ - Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ - const char *zStart = ""; - const char *zEnd = ""; - const char *zEllipsis = "..."; - int iCol = -1; - int nToken = 15; /* Default number of tokens in snippet */ - - /* There must be at least one argument passed to this function (otherwise - ** the non-overloaded version would have been called instead of this one). - */ - assert( nVal>=1 ); - - if( nVal>6 ){ - sqlite3_result_error(pContext, - "wrong number of arguments to function snippet()", -1); - return; - } - if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; - - switch( nVal ){ - case 6: nToken = sqlite3_value_int(apVal[5]); - /* no break */ deliberate_fall_through - case 5: iCol = sqlite3_value_int(apVal[4]); - /* no break */ deliberate_fall_through - case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); - /* no break */ deliberate_fall_through - case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); - /* no break */ deliberate_fall_through - case 2: zStart = (const char*)sqlite3_value_text(apVal[1]); - } - if( !zEllipsis || !zEnd || !zStart ){ - sqlite3_result_error_nomem(pContext); - }else if( nToken==0 ){ - sqlite3_result_text(pContext, "", -1, SQLITE_STATIC); - }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ - sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); - } -} - -/* -** Implementation of the offsets() function for FTS3 -*/ -static void fts3OffsetsFunc( - sqlite3_context *pContext, /* SQLite function call context */ - int nVal, /* Size of argument array */ - sqlite3_value **apVal /* Array of arguments */ -){ - Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ - - UNUSED_PARAMETER(nVal); - - assert( nVal==1 ); - if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return; - assert( pCsr ); - if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ - sqlite3Fts3Offsets(pContext, pCsr); - } -} - -/* -** Implementation of the special optimize() function for FTS3. This -** function merges all segments in the database to a single segment. -** Example usage is: -** -** SELECT optimize(t) FROM t LIMIT 1; -** -** where 't' is the name of an FTS3 table. -*/ -static void fts3OptimizeFunc( - sqlite3_context *pContext, /* SQLite function call context */ - int nVal, /* Size of argument array */ - sqlite3_value **apVal /* Array of arguments */ -){ - int rc; /* Return code */ - Fts3Table *p; /* Virtual table handle */ - Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */ - - UNUSED_PARAMETER(nVal); - - assert( nVal==1 ); - if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return; - p = (Fts3Table *)pCursor->base.pVtab; - assert( p ); - - rc = sqlite3Fts3Optimize(p); - - switch( rc ){ - case SQLITE_OK: - sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); - break; - case SQLITE_DONE: - sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC); - break; - default: - sqlite3_result_error_code(pContext, rc); - break; - } -} - -/* -** Implementation of the matchinfo() function for FTS3 -*/ -static void fts3MatchinfoFunc( - sqlite3_context *pContext, /* SQLite function call context */ - int nVal, /* Size of argument array */ - sqlite3_value **apVal /* Array of arguments */ -){ - Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ - assert( nVal==1 || nVal==2 ); - if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){ - const char *zArg = 0; - if( nVal>1 ){ - zArg = (const char *)sqlite3_value_text(apVal[1]); - } - sqlite3Fts3Matchinfo(pContext, pCsr, zArg); - } -} - -/* -** This routine implements the xFindFunction method for the FTS3 -** virtual table. -*/ -static int fts3FindFunctionMethod( - sqlite3_vtab *pVtab, /* Virtual table handle */ - int nArg, /* Number of SQL function arguments */ - const char *zName, /* Name of SQL function */ - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ - void **ppArg /* Unused */ -){ - struct Overloaded { - const char *zName; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } aOverload[] = { - { "snippet", fts3SnippetFunc }, - { "offsets", fts3OffsetsFunc }, - { "optimize", fts3OptimizeFunc }, - { "matchinfo", fts3MatchinfoFunc }, - }; - int i; /* Iterator variable */ - - UNUSED_PARAMETER(pVtab); - UNUSED_PARAMETER(nArg); - UNUSED_PARAMETER(ppArg); - - for(i=0; idb; /* Database connection */ - int rc; /* Return Code */ - - /* At this point it must be known if the %_stat table exists or not. - ** So bHasStat may not be 2. */ - rc = fts3SetHasStat(p); - - /* As it happens, the pending terms table is always empty here. This is - ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction - ** always opens a savepoint transaction. And the xSavepoint() method - ** flushes the pending terms table. But leave the (no-op) call to - ** PendingTermsFlush() in in case that changes. - */ - assert( p->nPendingData==0 ); - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3PendingTermsFlush(p); - } - - if( p->zContentTbl==0 ){ - fts3DbExec(&rc, db, - "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';", - p->zDb, p->zName, zName - ); - } - - if( p->bHasDocsize ){ - fts3DbExec(&rc, db, - "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';", - p->zDb, p->zName, zName - ); - } - if( p->bHasStat ){ - fts3DbExec(&rc, db, - "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';", - p->zDb, p->zName, zName - ); - } - fts3DbExec(&rc, db, - "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';", - p->zDb, p->zName, zName - ); - fts3DbExec(&rc, db, - "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';", - p->zDb, p->zName, zName - ); - return rc; -} - -/* -** The xSavepoint() method. -** -** Flush the contents of the pending-terms table to disk. -*/ -static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){ - int rc = SQLITE_OK; - UNUSED_PARAMETER(iSavepoint); - assert( ((Fts3Table *)pVtab)->inTransaction ); - assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint ); - TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint ); - if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){ - rc = fts3SyncMethod(pVtab); - } - return rc; -} - -/* -** The xRelease() method. -** -** This is a no-op. -*/ -static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){ - TESTONLY( Fts3Table *p = (Fts3Table*)pVtab ); - UNUSED_PARAMETER(iSavepoint); - UNUSED_PARAMETER(pVtab); - assert( p->inTransaction ); - assert( p->mxSavepoint >= iSavepoint ); - TESTONLY( p->mxSavepoint = iSavepoint-1 ); - return SQLITE_OK; -} - -/* -** The xRollbackTo() method. -** -** Discard the contents of the pending terms table. -*/ -static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){ - Fts3Table *p = (Fts3Table*)pVtab; - UNUSED_PARAMETER(iSavepoint); - assert( p->inTransaction ); - TESTONLY( p->mxSavepoint = iSavepoint ); - sqlite3Fts3PendingTermsClear(p); - return SQLITE_OK; -} - -/* -** Return true if zName is the extension on one of the shadow tables used -** by this module. -*/ -static int fts3ShadowName(const char *zName){ - static const char *azName[] = { - "content", "docsize", "segdir", "segments", "stat", - }; - unsigned int i; - for(i=0; ieType==FTSQUERY_PHRASE ){ - int i; - int nToken = pExpr->pPhrase->nToken; - *pnToken += nToken; - for(i=0; ipPhrase->aToken[i]; - int rc = fts3TermSegReaderCursor(pCsr, - pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr - ); - if( rc!=SQLITE_OK ){ - *pRc = rc; - return; - } - } - assert( pExpr->pPhrase->iDoclistToken==0 ); - pExpr->pPhrase->iDoclistToken = -1; - }else{ - *pnOr += (pExpr->eType==FTSQUERY_OR); - fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc); - fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc); - } - } -} - -/* -** Arguments pList/nList contain the doclist for token iToken of phrase p. -** It is merged into the main doclist stored in p->doclist.aAll/nAll. -** -** This function assumes that pList points to a buffer allocated using -** sqlite3_malloc(). This function takes responsibility for eventually -** freeing the buffer. -** -** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs. -*/ -static int fts3EvalPhraseMergeToken( - Fts3Table *pTab, /* FTS Table pointer */ - Fts3Phrase *p, /* Phrase to merge pList/nList into */ - int iToken, /* Token pList/nList corresponds to */ - char *pList, /* Pointer to doclist */ - int nList /* Number of bytes in pList */ -){ - int rc = SQLITE_OK; - assert( iToken!=p->iDoclistToken ); - - if( pList==0 ){ - sqlite3_free(p->doclist.aAll); - p->doclist.aAll = 0; - p->doclist.nAll = 0; - } - - else if( p->iDoclistToken<0 ){ - p->doclist.aAll = pList; - p->doclist.nAll = nList; - } - - else if( p->doclist.aAll==0 ){ - sqlite3_free(pList); - } - - else { - char *pLeft; - char *pRight; - int nLeft; - int nRight; - int nDiff; - - if( p->iDoclistTokendoclist.aAll; - nLeft = p->doclist.nAll; - pRight = pList; - nRight = nList; - nDiff = iToken - p->iDoclistToken; - }else{ - pRight = p->doclist.aAll; - nRight = p->doclist.nAll; - pLeft = pList; - nLeft = nList; - nDiff = p->iDoclistToken - iToken; - } - - rc = fts3DoclistPhraseMerge( - pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight - ); - sqlite3_free(pLeft); - p->doclist.aAll = pRight; - p->doclist.nAll = nRight; - } - - if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken; - return rc; -} - -/* -** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist -** does not take deferred tokens into account. -** -** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. -*/ -static int fts3EvalPhraseLoad( - Fts3Cursor *pCsr, /* FTS Cursor handle */ - Fts3Phrase *p /* Phrase object */ -){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int iToken; - int rc = SQLITE_OK; - - for(iToken=0; rc==SQLITE_OK && iTokennToken; iToken++){ - Fts3PhraseToken *pToken = &p->aToken[iToken]; - assert( pToken->pDeferred==0 || pToken->pSegcsr==0 ); - - if( pToken->pSegcsr ){ - int nThis = 0; - char *pThis = 0; - rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis); - if( rc==SQLITE_OK ){ - rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis); - } - } - assert( pToken->pSegcsr==0 ); - } - - return rc; -} - -#ifndef SQLITE_DISABLE_FTS4_DEFERRED -/* -** This function is called on each phrase after the position lists for -** any deferred tokens have been loaded into memory. It updates the phrases -** current position list to include only those positions that are really -** instances of the phrase (after considering deferred tokens). If this -** means that the phrase does not appear in the current row, doclist.pList -** and doclist.nList are both zeroed. -** -** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. -*/ -static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ - int iToken; /* Used to iterate through phrase tokens */ - char *aPoslist = 0; /* Position list for deferred tokens */ - int nPoslist = 0; /* Number of bytes in aPoslist */ - int iPrev = -1; /* Token number of previous deferred token */ - - assert( pPhrase->doclist.bFreeList==0 ); - - for(iToken=0; iTokennToken; iToken++){ - Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; - Fts3DeferredToken *pDeferred = pToken->pDeferred; - - if( pDeferred ){ - char *pList; - int nList; - int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList); - if( rc!=SQLITE_OK ) return rc; - - if( pList==0 ){ - sqlite3_free(aPoslist); - pPhrase->doclist.pList = 0; - pPhrase->doclist.nList = 0; - return SQLITE_OK; - - }else if( aPoslist==0 ){ - aPoslist = pList; - nPoslist = nList; - - }else{ - char *aOut = pList; - char *p1 = aPoslist; - char *p2 = aOut; - - assert( iPrev>=0 ); - fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2); - sqlite3_free(aPoslist); - aPoslist = pList; - nPoslist = (int)(aOut - aPoslist); - if( nPoslist==0 ){ - sqlite3_free(aPoslist); - pPhrase->doclist.pList = 0; - pPhrase->doclist.nList = 0; - return SQLITE_OK; - } - } - iPrev = iToken; - } - } - - if( iPrev>=0 ){ - int nMaxUndeferred = pPhrase->iDoclistToken; - if( nMaxUndeferred<0 ){ - pPhrase->doclist.pList = aPoslist; - pPhrase->doclist.nList = nPoslist; - pPhrase->doclist.iDocid = pCsr->iPrevId; - pPhrase->doclist.bFreeList = 1; - }else{ - int nDistance; - char *p1; - char *p2; - char *aOut; - - if( nMaxUndeferred>iPrev ){ - p1 = aPoslist; - p2 = pPhrase->doclist.pList; - nDistance = nMaxUndeferred - iPrev; - }else{ - p1 = pPhrase->doclist.pList; - p2 = aPoslist; - nDistance = iPrev - nMaxUndeferred; - } - - aOut = (char *)sqlite3_malloc(nPoslist+8); - if( !aOut ){ - sqlite3_free(aPoslist); - return SQLITE_NOMEM; - } - - pPhrase->doclist.pList = aOut; - if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){ - pPhrase->doclist.bFreeList = 1; - pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList); - }else{ - sqlite3_free(aOut); - pPhrase->doclist.pList = 0; - pPhrase->doclist.nList = 0; - } - sqlite3_free(aPoslist); - } - } - - return SQLITE_OK; -} -#endif /* SQLITE_DISABLE_FTS4_DEFERRED */ - -/* -** Maximum number of tokens a phrase may have to be considered for the -** incremental doclists strategy. -*/ -#define MAX_INCR_PHRASE_TOKENS 4 - -/* -** This function is called for each Fts3Phrase in a full-text query -** expression to initialize the mechanism for returning rows. Once this -** function has been called successfully on an Fts3Phrase, it may be -** used with fts3EvalPhraseNext() to iterate through the matching docids. -** -** If parameter bOptOk is true, then the phrase may (or may not) use the -** incremental loading strategy. Otherwise, the entire doclist is loaded into -** memory within this call. -** -** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code. -*/ -static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int rc = SQLITE_OK; /* Error code */ - int i; - - /* Determine if doclists may be loaded from disk incrementally. This is - ** possible if the bOptOk argument is true, the FTS doclists will be - ** scanned in forward order, and the phrase consists of - ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first" - ** tokens or prefix tokens that cannot use a prefix-index. */ - int bHaveIncr = 0; - int bIncrOk = (bOptOk - && pCsr->bDesc==pTab->bDescIdx - && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - && pTab->bNoIncrDoclist==0 -#endif - ); - for(i=0; bIncrOk==1 && inToken; i++){ - Fts3PhraseToken *pToken = &p->aToken[i]; - if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){ - bIncrOk = 0; - } - if( pToken->pSegcsr ) bHaveIncr = 1; - } - - if( bIncrOk && bHaveIncr ){ - /* Use the incremental approach. */ - int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn); - for(i=0; rc==SQLITE_OK && inToken; i++){ - Fts3PhraseToken *pToken = &p->aToken[i]; - Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; - if( pSegcsr ){ - rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); - } - } - p->bIncr = 1; - }else{ - /* Load the full doclist for the phrase into memory. */ - rc = fts3EvalPhraseLoad(pCsr, p); - p->bIncr = 0; - } - - assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr ); - return rc; -} - -/* -** This function is used to iterate backwards (from the end to start) -** through doclists. It is used by this module to iterate through phrase -** doclists in reverse and by the fts3_write.c module to iterate through -** pending-terms lists when writing to databases with "order=desc". -** -** The doclist may be sorted in ascending (parameter bDescIdx==0) or -** descending (parameter bDescIdx==1) order of docid. Regardless, this -** function iterates from the end of the doclist to the beginning. -*/ -SQLITE_PRIVATE void sqlite3Fts3DoclistPrev( - int bDescIdx, /* True if the doclist is desc */ - char *aDoclist, /* Pointer to entire doclist */ - int nDoclist, /* Length of aDoclist in bytes */ - char **ppIter, /* IN/OUT: Iterator pointer */ - sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */ - int *pnList, /* OUT: List length pointer */ - u8 *pbEof /* OUT: End-of-file flag */ -){ - char *p = *ppIter; - - assert( nDoclist>0 ); - assert( *pbEof==0 ); - assert( p || *piDocid==0 ); - assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) ); - - if( p==0 ){ - sqlite3_int64 iDocid = 0; - char *pNext = 0; - char *pDocid = aDoclist; - char *pEnd = &aDoclist[nDoclist]; - int iMul = 1; - - while( pDocid0 ); - assert( *pbEof==0 ); - assert_fts3_nc( p || *piDocid==0 ); - assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) ); - - if( p==0 ){ - p = aDoclist; - p += sqlite3Fts3GetVarint(p, piDocid); - }else{ - fts3PoslistCopy(0, &p); - while( p<&aDoclist[nDoclist] && *p==0 ) p++; - if( p>=&aDoclist[nDoclist] ){ - *pbEof = 1; - }else{ - sqlite3_int64 iVar; - p += sqlite3Fts3GetVarint(p, &iVar); - *piDocid += ((bDescIdx ? -1 : 1) * iVar); - } - } - - *ppIter = p; -} - -/* -** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof -** to true if EOF is reached. -*/ -static void fts3EvalDlPhraseNext( - Fts3Table *pTab, - Fts3Doclist *pDL, - u8 *pbEof -){ - char *pIter; /* Used to iterate through aAll */ - char *pEnd; /* 1 byte past end of aAll */ - - if( pDL->pNextDocid ){ - pIter = pDL->pNextDocid; - assert( pDL->aAll!=0 || pIter==0 ); - }else{ - pIter = pDL->aAll; - } - - if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){ - /* We have already reached the end of this doclist. EOF. */ - *pbEof = 1; - }else{ - sqlite3_int64 iDelta; - pIter += sqlite3Fts3GetVarint(pIter, &iDelta); - if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){ - pDL->iDocid += iDelta; - }else{ - pDL->iDocid -= iDelta; - } - pDL->pList = pIter; - fts3PoslistCopy(0, &pIter); - pDL->nList = (int)(pIter - pDL->pList); - - /* pIter now points just past the 0x00 that terminates the position- - ** list for document pDL->iDocid. However, if this position-list was - ** edited in place by fts3EvalNearTrim(), then pIter may not actually - ** point to the start of the next docid value. The following line deals - ** with this case by advancing pIter past the zero-padding added by - ** fts3EvalNearTrim(). */ - while( pIterpNextDocid = pIter; - assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter ); - *pbEof = 0; - } -} - -/* -** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext(). -*/ -typedef struct TokenDoclist TokenDoclist; -struct TokenDoclist { - int bIgnore; - sqlite3_int64 iDocid; - char *pList; - int nList; -}; - -/* -** Token pToken is an incrementally loaded token that is part of a -** multi-token phrase. Advance it to the next matching document in the -** database and populate output variable *p with the details of the new -** entry. Or, if the iterator has reached EOF, set *pbEof to true. -** -** If an error occurs, return an SQLite error code. Otherwise, return -** SQLITE_OK. -*/ -static int incrPhraseTokenNext( - Fts3Table *pTab, /* Virtual table handle */ - Fts3Phrase *pPhrase, /* Phrase to advance token of */ - int iToken, /* Specific token to advance */ - TokenDoclist *p, /* OUT: Docid and doclist for new entry */ - u8 *pbEof /* OUT: True if iterator is at EOF */ -){ - int rc = SQLITE_OK; - - if( pPhrase->iDoclistToken==iToken ){ - assert( p->bIgnore==0 ); - assert( pPhrase->aToken[iToken].pSegcsr==0 ); - fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof); - p->pList = pPhrase->doclist.pList; - p->nList = pPhrase->doclist.nList; - p->iDocid = pPhrase->doclist.iDocid; - }else{ - Fts3PhraseToken *pToken = &pPhrase->aToken[iToken]; - assert( pToken->pDeferred==0 ); - assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 ); - if( pToken->pSegcsr ){ - assert( p->bIgnore==0 ); - rc = sqlite3Fts3MsrIncrNext( - pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList - ); - if( p->pList==0 ) *pbEof = 1; - }else{ - p->bIgnore = 1; - } - } - - return rc; -} - - -/* -** The phrase iterator passed as the second argument: -** -** * features at least one token that uses an incremental doclist, and -** -** * does not contain any deferred tokens. -** -** Advance it to the next matching documnent in the database and populate -** the Fts3Doclist.pList and nList fields. -** -** If there is no "next" entry and no error occurs, then *pbEof is set to -** 1 before returning. Otherwise, if no error occurs and the iterator is -** successfully advanced, *pbEof is set to 0. -** -** If an error occurs, return an SQLite error code. Otherwise, return -** SQLITE_OK. -*/ -static int fts3EvalIncrPhraseNext( - Fts3Cursor *pCsr, /* FTS Cursor handle */ - Fts3Phrase *p, /* Phrase object to advance to next docid */ - u8 *pbEof /* OUT: Set to 1 if EOF */ -){ - int rc = SQLITE_OK; - Fts3Doclist *pDL = &p->doclist; - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - u8 bEof = 0; - - /* This is only called if it is guaranteed that the phrase has at least - ** one incremental token. In which case the bIncr flag is set. */ - assert( p->bIncr==1 ); - - if( p->nToken==1 ){ - rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, - &pDL->iDocid, &pDL->pList, &pDL->nList - ); - if( pDL->pList==0 ) bEof = 1; - }else{ - int bDescDoclist = pCsr->bDesc; - struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS]; - - memset(a, 0, sizeof(a)); - assert( p->nToken<=MAX_INCR_PHRASE_TOKENS ); - assert( p->iDoclistTokennToken && bEof==0; i++){ - rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); - if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){ - iMax = a[i].iDocid; - bMaxSet = 1; - } - } - assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) ); - assert( rc!=SQLITE_OK || bMaxSet ); - - /* Keep advancing iterators until they all point to the same document */ - for(i=0; inToken; i++){ - while( rc==SQLITE_OK && bEof==0 - && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 - ){ - rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof); - if( DOCID_CMP(a[i].iDocid, iMax)>0 ){ - iMax = a[i].iDocid; - i = 0; - } - } - } - - /* Check if the current entries really are a phrase match */ - if( bEof==0 ){ - int nList = 0; - int nByte = a[p->nToken-1].nList; - char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING); - if( !aDoclist ) return SQLITE_NOMEM; - memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); - memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING); - - for(i=0; i<(p->nToken-1); i++){ - if( a[i].bIgnore==0 ){ - char *pL = a[i].pList; - char *pR = aDoclist; - char *pOut = aDoclist; - int nDist = p->nToken-1-i; - int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR); - if( res==0 ) break; - nList = (int)(pOut - aDoclist); - } - } - if( i==(p->nToken-1) ){ - pDL->iDocid = iMax; - pDL->pList = aDoclist; - pDL->nList = nList; - pDL->bFreeList = 1; - break; - } - sqlite3_free(aDoclist); - } - } - } - - *pbEof = bEof; - return rc; -} - -/* -** Attempt to move the phrase iterator to point to the next matching docid. -** If an error occurs, return an SQLite error code. Otherwise, return -** SQLITE_OK. -** -** If there is no "next" entry and no error occurs, then *pbEof is set to -** 1 before returning. Otherwise, if no error occurs and the iterator is -** successfully advanced, *pbEof is set to 0. -*/ -static int fts3EvalPhraseNext( - Fts3Cursor *pCsr, /* FTS Cursor handle */ - Fts3Phrase *p, /* Phrase object to advance to next docid */ - u8 *pbEof /* OUT: Set to 1 if EOF */ -){ - int rc = SQLITE_OK; - Fts3Doclist *pDL = &p->doclist; - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - - if( p->bIncr ){ - rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof); - }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){ - sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, - &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof - ); - pDL->pList = pDL->pNextDocid; - }else{ - fts3EvalDlPhraseNext(pTab, pDL, pbEof); - } - - return rc; -} - -/* -** -** If *pRc is not SQLITE_OK when this function is called, it is a no-op. -** Otherwise, fts3EvalPhraseStart() is called on all phrases within the -** expression. Also the Fts3Expr.bDeferred variable is set to true for any -** expressions for which all descendent tokens are deferred. -** -** If parameter bOptOk is zero, then it is guaranteed that the -** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for -** each phrase in the expression (subject to deferred token processing). -** Or, if bOptOk is non-zero, then one or more tokens within the expression -** may be loaded incrementally, meaning doclist.aAll/nAll is not available. -** -** If an error occurs within this function, *pRc is set to an SQLite error -** code before returning. -*/ -static void fts3EvalStartReaders( - Fts3Cursor *pCsr, /* FTS Cursor handle */ - Fts3Expr *pExpr, /* Expression to initialize phrases in */ - int *pRc /* IN/OUT: Error code */ -){ - if( pExpr && SQLITE_OK==*pRc ){ - if( pExpr->eType==FTSQUERY_PHRASE ){ - int nToken = pExpr->pPhrase->nToken; - if( nToken ){ - int i; - for(i=0; ipPhrase->aToken[i].pDeferred==0 ) break; - } - pExpr->bDeferred = (i==nToken); - } - *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase); - }else{ - fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc); - fts3EvalStartReaders(pCsr, pExpr->pRight, pRc); - pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred); - } - } -} - -/* -** An array of the following structures is assembled as part of the process -** of selecting tokens to defer before the query starts executing (as part -** of the xFilter() method). There is one element in the array for each -** token in the FTS expression. -** -** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong -** to phrases that are connected only by AND and NEAR operators (not OR or -** NOT). When determining tokens to defer, each AND/NEAR cluster is considered -** separately. The root of a tokens AND/NEAR cluster is stored in -** Fts3TokenAndCost.pRoot. -*/ -typedef struct Fts3TokenAndCost Fts3TokenAndCost; -struct Fts3TokenAndCost { - Fts3Phrase *pPhrase; /* The phrase the token belongs to */ - int iToken; /* Position of token in phrase */ - Fts3PhraseToken *pToken; /* The token itself */ - Fts3Expr *pRoot; /* Root of NEAR/AND cluster */ - int nOvfl; /* Number of overflow pages to load doclist */ - int iCol; /* The column the token must match */ -}; - -/* -** This function is used to populate an allocated Fts3TokenAndCost array. -** -** If *pRc is not SQLITE_OK when this function is called, it is a no-op. -** Otherwise, if an error occurs during execution, *pRc is set to an -** SQLite error code. -*/ -static void fts3EvalTokenCosts( - Fts3Cursor *pCsr, /* FTS Cursor handle */ - Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */ - Fts3Expr *pExpr, /* Expression to consider */ - Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */ - Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */ - int *pRc /* IN/OUT: Error code */ -){ - if( *pRc==SQLITE_OK ){ - if( pExpr->eType==FTSQUERY_PHRASE ){ - Fts3Phrase *pPhrase = pExpr->pPhrase; - int i; - for(i=0; *pRc==SQLITE_OK && inToken; i++){ - Fts3TokenAndCost *pTC = (*ppTC)++; - pTC->pPhrase = pPhrase; - pTC->iToken = i; - pTC->pRoot = pRoot; - pTC->pToken = &pPhrase->aToken[i]; - pTC->iCol = pPhrase->iColumn; - *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl); - } - }else if( pExpr->eType!=FTSQUERY_NOT ){ - assert( pExpr->eType==FTSQUERY_OR - || pExpr->eType==FTSQUERY_AND - || pExpr->eType==FTSQUERY_NEAR - ); - assert( pExpr->pLeft && pExpr->pRight ); - if( pExpr->eType==FTSQUERY_OR ){ - pRoot = pExpr->pLeft; - **ppOr = pRoot; - (*ppOr)++; - } - fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc); - if( pExpr->eType==FTSQUERY_OR ){ - pRoot = pExpr->pRight; - **ppOr = pRoot; - (*ppOr)++; - } - fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc); - } - } -} - -/* -** Determine the average document (row) size in pages. If successful, -** write this value to *pnPage and return SQLITE_OK. Otherwise, return -** an SQLite error code. -** -** The average document size in pages is calculated by first calculating -** determining the average size in bytes, B. If B is less than the amount -** of data that will fit on a single leaf page of an intkey table in -** this database, then the average docsize is 1. Otherwise, it is 1 plus -** the number of overflow pages consumed by a record B bytes in size. -*/ -static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){ - int rc = SQLITE_OK; - if( pCsr->nRowAvg==0 ){ - /* The average document size, which is required to calculate the cost - ** of each doclist, has not yet been determined. Read the required - ** data from the %_stat table to calculate it. - ** - ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 - ** varints, where nCol is the number of columns in the FTS3 table. - ** The first varint is the number of documents currently stored in - ** the table. The following nCol varints contain the total amount of - ** data stored in all rows of each column of the table, from left - ** to right. - */ - Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; - sqlite3_stmt *pStmt; - sqlite3_int64 nDoc = 0; - sqlite3_int64 nByte = 0; - const char *pEnd; - const char *a; - - rc = sqlite3Fts3SelectDoctotal(p, &pStmt); - if( rc!=SQLITE_OK ) return rc; - a = sqlite3_column_blob(pStmt, 0); - testcase( a==0 ); /* If %_stat.value set to X'' */ - if( a ){ - pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; - a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc); - while( anDoc = nDoc; - pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz); - assert( pCsr->nRowAvg>0 ); - rc = sqlite3_reset(pStmt); - } - - *pnPage = pCsr->nRowAvg; - return rc; -} - -/* -** This function is called to select the tokens (if any) that will be -** deferred. The array aTC[] has already been populated when this is -** called. -** -** This function is called once for each AND/NEAR cluster in the -** expression. Each invocation determines which tokens to defer within -** the cluster with root node pRoot. See comments above the definition -** of struct Fts3TokenAndCost for more details. -** -** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken() -** called on each token to defer. Otherwise, an SQLite error code is -** returned. -*/ -static int fts3EvalSelectDeferred( - Fts3Cursor *pCsr, /* FTS Cursor handle */ - Fts3Expr *pRoot, /* Consider tokens with this root node */ - Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */ - int nTC /* Number of entries in aTC[] */ -){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int nDocSize = 0; /* Number of pages per doc loaded */ - int rc = SQLITE_OK; /* Return code */ - int ii; /* Iterator variable for various purposes */ - int nOvfl = 0; /* Total overflow pages used by doclists */ - int nToken = 0; /* Total number of tokens in cluster */ - - int nMinEst = 0; /* The minimum count for any phrase so far. */ - int nLoad4 = 1; /* (Phrases that will be loaded)^4. */ - - /* Tokens are never deferred for FTS tables created using the content=xxx - ** option. The reason being that it is not guaranteed that the content - ** table actually contains the same data as the index. To prevent this from - ** causing any problems, the deferred token optimization is completely - ** disabled for content=xxx tables. */ - if( pTab->zContentTbl ){ - return SQLITE_OK; - } - - /* Count the tokens in this AND/NEAR cluster. If none of the doclists - ** associated with the tokens spill onto overflow pages, or if there is - ** only 1 token, exit early. No tokens to defer in this case. */ - for(ii=0; ii0 ); - - - /* Iterate through all tokens in this AND/NEAR cluster, in ascending order - ** of the number of overflow pages that will be loaded by the pager layer - ** to retrieve the entire doclist for the token from the full-text index. - ** Load the doclists for tokens that are either: - ** - ** a. The cheapest token in the entire query (i.e. the one visited by the - ** first iteration of this loop), or - ** - ** b. Part of a multi-token phrase. - ** - ** After each token doclist is loaded, merge it with the others from the - ** same phrase and count the number of documents that the merged doclist - ** contains. Set variable "nMinEst" to the smallest number of documents in - ** any phrase doclist for which 1 or more token doclists have been loaded. - ** Let nOther be the number of other phrases for which it is certain that - ** one or more tokens will not be deferred. - ** - ** Then, for each token, defer it if loading the doclist would result in - ** loading N or more overflow pages into memory, where N is computed as: - ** - ** (nMinEst + 4^nOther - 1) / (4^nOther) - */ - for(ii=0; iinOvfl) - ){ - pTC = &aTC[iTC]; - } - } - assert( pTC ); - - if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){ - /* The number of overflow pages to load for this (and therefore all - ** subsequent) tokens is greater than the estimated number of pages - ** that will be loaded if all subsequent tokens are deferred. - */ - Fts3PhraseToken *pToken = pTC->pToken; - rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol); - fts3SegReaderCursorFree(pToken->pSegcsr); - pToken->pSegcsr = 0; - }else{ - /* Set nLoad4 to the value of (4^nOther) for the next iteration of the - ** for-loop. Except, limit the value to 2^24 to prevent it from - ** overflowing the 32-bit integer it is stored in. */ - if( ii<12 ) nLoad4 = nLoad4*4; - - if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){ - /* Either this is the cheapest token in the entire query, or it is - ** part of a multi-token phrase. Either way, the entire doclist will - ** (eventually) be loaded into memory. It may as well be now. */ - Fts3PhraseToken *pToken = pTC->pToken; - int nList = 0; - char *pList = 0; - rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList); - assert( rc==SQLITE_OK || pList==0 ); - if( rc==SQLITE_OK ){ - rc = fts3EvalPhraseMergeToken( - pTab, pTC->pPhrase, pTC->iToken,pList,nList - ); - } - if( rc==SQLITE_OK ){ - int nCount; - nCount = fts3DoclistCountDocids( - pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll - ); - if( ii==0 || nCountpToken = 0; - } - - return rc; -} - -/* -** This function is called from within the xFilter method. It initializes -** the full-text query currently stored in pCsr->pExpr. To iterate through -** the results of a query, the caller does: -** -** fts3EvalStart(pCsr); -** while( 1 ){ -** fts3EvalNext(pCsr); -** if( pCsr->bEof ) break; -** ... return row pCsr->iPrevId to the caller ... -** } -*/ -static int fts3EvalStart(Fts3Cursor *pCsr){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int rc = SQLITE_OK; - int nToken = 0; - int nOr = 0; - - /* Allocate a MultiSegReader for each token in the expression. */ - fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc); - - /* Determine which, if any, tokens in the expression should be deferred. */ -#ifndef SQLITE_DISABLE_FTS4_DEFERRED - if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){ - Fts3TokenAndCost *aTC; - Fts3Expr **apOr; - aTC = (Fts3TokenAndCost *)sqlite3_malloc64( - sizeof(Fts3TokenAndCost) * nToken - + sizeof(Fts3Expr *) * nOr * 2 - ); - apOr = (Fts3Expr **)&aTC[nToken]; - - if( !aTC ){ - rc = SQLITE_NOMEM; - }else{ - int ii; - Fts3TokenAndCost *pTC = aTC; - Fts3Expr **ppOr = apOr; - - fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc); - nToken = (int)(pTC-aTC); - nOr = (int)(ppOr-apOr); - - if( rc==SQLITE_OK ){ - rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken); - for(ii=0; rc==SQLITE_OK && iipExpr, &rc); - return rc; -} - -/* -** Invalidate the current position list for phrase pPhrase. -*/ -static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){ - if( pPhrase->doclist.bFreeList ){ - sqlite3_free(pPhrase->doclist.pList); - } - pPhrase->doclist.pList = 0; - pPhrase->doclist.nList = 0; - pPhrase->doclist.bFreeList = 0; -} - -/* -** This function is called to edit the position list associated with -** the phrase object passed as the fifth argument according to a NEAR -** condition. For example: -** -** abc NEAR/5 "def ghi" -** -** Parameter nNear is passed the NEAR distance of the expression (5 in -** the example above). When this function is called, *paPoslist points to -** the position list, and *pnToken is the number of phrase tokens in the -** phrase on the other side of the NEAR operator to pPhrase. For example, -** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to -** the position list associated with phrase "abc". -** -** All positions in the pPhrase position list that are not sufficiently -** close to a position in the *paPoslist position list are removed. If this -** leaves 0 positions, zero is returned. Otherwise, non-zero. -** -** Before returning, *paPoslist is set to point to the position lsit -** associated with pPhrase. And *pnToken is set to the number of tokens in -** pPhrase. -*/ -static int fts3EvalNearTrim( - int nNear, /* NEAR distance. As in "NEAR/nNear". */ - char *aTmp, /* Temporary space to use */ - char **paPoslist, /* IN/OUT: Position list */ - int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */ - Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */ -){ - int nParam1 = nNear + pPhrase->nToken; - int nParam2 = nNear + *pnToken; - int nNew; - char *p2; - char *pOut; - int res; - - assert( pPhrase->doclist.pList ); - - p2 = pOut = pPhrase->doclist.pList; - res = fts3PoslistNearMerge( - &pOut, aTmp, nParam1, nParam2, paPoslist, &p2 - ); - if( res ){ - nNew = (int)(pOut - pPhrase->doclist.pList) - 1; - if( nNew>=0 ){ - assert( pPhrase->doclist.pList[nNew]=='\0' ); - assert( nNew<=pPhrase->doclist.nList && nNew>0 ); - memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew); - pPhrase->doclist.nList = nNew; - } - *paPoslist = pPhrase->doclist.pList; - *pnToken = pPhrase->nToken; - } - - return res; -} - -/* -** This function is a no-op if *pRc is other than SQLITE_OK when it is called. -** Otherwise, it advances the expression passed as the second argument to -** point to the next matching row in the database. Expressions iterate through -** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero, -** or descending if it is non-zero. -** -** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if -** successful, the following variables in pExpr are set: -** -** Fts3Expr.bEof (non-zero if EOF - there is no next row) -** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row) -** -** If the expression is of type FTSQUERY_PHRASE, and the expression is not -** at EOF, then the following variables are populated with the position list -** for the phrase for the visited row: -** -** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes) -** FTs3Expr.pPhrase->doclist.pList (pointer to position list) -** -** It says above that this function advances the expression to the next -** matching row. This is usually true, but there are the following exceptions: -** -** 1. Deferred tokens are not taken into account. If a phrase consists -** entirely of deferred tokens, it is assumed to match every row in -** the db. In this case the position-list is not populated at all. -** -** Or, if a phrase contains one or more deferred tokens and one or -** more non-deferred tokens, then the expression is advanced to the -** next possible match, considering only non-deferred tokens. In other -** words, if the phrase is "A B C", and "B" is deferred, the expression -** is advanced to the next row that contains an instance of "A * C", -** where "*" may match any single token. The position list in this case -** is populated as for "A * C" before returning. -** -** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is -** advanced to point to the next row that matches "x AND y". -** -** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is -** really a match, taking into account deferred tokens and NEAR operators. -*/ -static void fts3EvalNextRow( - Fts3Cursor *pCsr, /* FTS Cursor handle */ - Fts3Expr *pExpr, /* Expr. to advance to next matching row */ - int *pRc /* IN/OUT: Error code */ -){ - if( *pRc==SQLITE_OK ){ - int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */ - assert( pExpr->bEof==0 ); - pExpr->bStart = 1; - - switch( pExpr->eType ){ - case FTSQUERY_NEAR: - case FTSQUERY_AND: { - Fts3Expr *pLeft = pExpr->pLeft; - Fts3Expr *pRight = pExpr->pRight; - assert( !pLeft->bDeferred || !pRight->bDeferred ); - - if( pLeft->bDeferred ){ - /* LHS is entirely deferred. So we assume it matches every row. - ** Advance the RHS iterator to find the next row visited. */ - fts3EvalNextRow(pCsr, pRight, pRc); - pExpr->iDocid = pRight->iDocid; - pExpr->bEof = pRight->bEof; - }else if( pRight->bDeferred ){ - /* RHS is entirely deferred. So we assume it matches every row. - ** Advance the LHS iterator to find the next row visited. */ - fts3EvalNextRow(pCsr, pLeft, pRc); - pExpr->iDocid = pLeft->iDocid; - pExpr->bEof = pLeft->bEof; - }else{ - /* Neither the RHS or LHS are deferred. */ - fts3EvalNextRow(pCsr, pLeft, pRc); - fts3EvalNextRow(pCsr, pRight, pRc); - while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){ - sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid); - if( iDiff==0 ) break; - if( iDiff<0 ){ - fts3EvalNextRow(pCsr, pLeft, pRc); - }else{ - fts3EvalNextRow(pCsr, pRight, pRc); - } - } - pExpr->iDocid = pLeft->iDocid; - pExpr->bEof = (pLeft->bEof || pRight->bEof); - if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){ - assert( pRight->eType==FTSQUERY_PHRASE ); - if( pRight->pPhrase->doclist.aAll ){ - Fts3Doclist *pDl = &pRight->pPhrase->doclist; - while( *pRc==SQLITE_OK && pRight->bEof==0 ){ - memset(pDl->pList, 0, pDl->nList); - fts3EvalNextRow(pCsr, pRight, pRc); - } - } - if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){ - Fts3Doclist *pDl = &pLeft->pPhrase->doclist; - while( *pRc==SQLITE_OK && pLeft->bEof==0 ){ - memset(pDl->pList, 0, pDl->nList); - fts3EvalNextRow(pCsr, pLeft, pRc); - } - } - pRight->bEof = pLeft->bEof = 1; - } - } - break; - } - - case FTSQUERY_OR: { - Fts3Expr *pLeft = pExpr->pLeft; - Fts3Expr *pRight = pExpr->pRight; - sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); - - assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid ); - assert( pRight->bStart || pLeft->iDocid==pRight->iDocid ); - - if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ - fts3EvalNextRow(pCsr, pLeft, pRc); - }else if( pLeft->bEof || iCmp>0 ){ - fts3EvalNextRow(pCsr, pRight, pRc); - }else{ - fts3EvalNextRow(pCsr, pLeft, pRc); - fts3EvalNextRow(pCsr, pRight, pRc); - } - - pExpr->bEof = (pLeft->bEof && pRight->bEof); - iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid); - if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){ - pExpr->iDocid = pLeft->iDocid; - }else{ - pExpr->iDocid = pRight->iDocid; - } - - break; - } - - case FTSQUERY_NOT: { - Fts3Expr *pLeft = pExpr->pLeft; - Fts3Expr *pRight = pExpr->pRight; - - if( pRight->bStart==0 ){ - fts3EvalNextRow(pCsr, pRight, pRc); - assert( *pRc!=SQLITE_OK || pRight->bStart ); - } - - fts3EvalNextRow(pCsr, pLeft, pRc); - if( pLeft->bEof==0 ){ - while( !*pRc - && !pRight->bEof - && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 - ){ - fts3EvalNextRow(pCsr, pRight, pRc); - } - } - pExpr->iDocid = pLeft->iDocid; - pExpr->bEof = pLeft->bEof; - break; - } - - default: { - Fts3Phrase *pPhrase = pExpr->pPhrase; - fts3EvalInvalidatePoslist(pPhrase); - *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof); - pExpr->iDocid = pPhrase->doclist.iDocid; - break; - } - } - } -} - -/* -** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR -** cluster, then this function returns 1 immediately. -** -** Otherwise, it checks if the current row really does match the NEAR -** expression, using the data currently stored in the position lists -** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. -** -** If the current row is a match, the position list associated with each -** phrase in the NEAR expression is edited in place to contain only those -** phrase instances sufficiently close to their peers to satisfy all NEAR -** constraints. In this case it returns 1. If the NEAR expression does not -** match the current row, 0 is returned. The position lists may or may not -** be edited if 0 is returned. -*/ -static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ - int res = 1; - - /* The following block runs if pExpr is the root of a NEAR query. - ** For example, the query: - ** - ** "w" NEAR "x" NEAR "y" NEAR "z" - ** - ** which is represented in tree form as: - ** - ** | - ** +--NEAR--+ <-- root of NEAR query - ** | | - ** +--NEAR--+ "z" - ** | | - ** +--NEAR--+ "y" - ** | | - ** "w" "x" - ** - ** The right-hand child of a NEAR node is always a phrase. The - ** left-hand child may be either a phrase or a NEAR node. There are - ** no exceptions to this - it's the way the parser in fts3_expr.c works. - */ - if( *pRc==SQLITE_OK - && pExpr->eType==FTSQUERY_NEAR - && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) - ){ - Fts3Expr *p; - sqlite3_int64 nTmp = 0; /* Bytes of temp space */ - char *aTmp; /* Temp space for PoslistNearMerge() */ - - /* Allocate temporary working space. */ - for(p=pExpr; p->pLeft; p=p->pLeft){ - assert( p->pRight->pPhrase->doclist.nList>0 ); - nTmp += p->pRight->pPhrase->doclist.nList; - } - nTmp += p->pPhrase->doclist.nList; - aTmp = sqlite3_malloc64(nTmp*2); - if( !aTmp ){ - *pRc = SQLITE_NOMEM; - res = 0; - }else{ - char *aPoslist = p->pPhrase->doclist.pList; - int nToken = p->pPhrase->nToken; - - for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){ - Fts3Phrase *pPhrase = p->pRight->pPhrase; - int nNear = p->nNear; - res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); - } - - aPoslist = pExpr->pRight->pPhrase->doclist.pList; - nToken = pExpr->pRight->pPhrase->nToken; - for(p=pExpr->pLeft; p && res; p=p->pLeft){ - int nNear; - Fts3Phrase *pPhrase; - assert( p->pParent && p->pParent->pLeft==p ); - nNear = p->pParent->nNear; - pPhrase = ( - p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase - ); - res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase); - } - } - - sqlite3_free(aTmp); - } - - return res; -} - -/* -** This function is a helper function for sqlite3Fts3EvalTestDeferred(). -** Assuming no error occurs or has occurred, It returns non-zero if the -** expression passed as the second argument matches the row that pCsr -** currently points to, or zero if it does not. -** -** If *pRc is not SQLITE_OK when this function is called, it is a no-op. -** If an error occurs during execution of this function, *pRc is set to -** the appropriate SQLite error code. In this case the returned value is -** undefined. -*/ -static int fts3EvalTestExpr( - Fts3Cursor *pCsr, /* FTS cursor handle */ - Fts3Expr *pExpr, /* Expr to test. May or may not be root. */ - int *pRc /* IN/OUT: Error code */ -){ - int bHit = 1; /* Return value */ - if( *pRc==SQLITE_OK ){ - switch( pExpr->eType ){ - case FTSQUERY_NEAR: - case FTSQUERY_AND: - bHit = ( - fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) - && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) - && fts3EvalNearTest(pExpr, pRc) - ); - - /* If the NEAR expression does not match any rows, zero the doclist for - ** all phrases involved in the NEAR. This is because the snippet(), - ** offsets() and matchinfo() functions are not supposed to recognize - ** any instances of phrases that are part of unmatched NEAR queries. - ** For example if this expression: - ** - ** ... MATCH 'a OR (b NEAR c)' - ** - ** is matched against a row containing: - ** - ** 'a b d e' - ** - ** then any snippet() should ony highlight the "a" term, not the "b" - ** (as "b" is part of a non-matching NEAR clause). - */ - if( bHit==0 - && pExpr->eType==FTSQUERY_NEAR - && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR) - ){ - Fts3Expr *p; - for(p=pExpr; p->pPhrase==0; p=p->pLeft){ - if( p->pRight->iDocid==pCsr->iPrevId ){ - fts3EvalInvalidatePoslist(p->pRight->pPhrase); - } - } - if( p->iDocid==pCsr->iPrevId ){ - fts3EvalInvalidatePoslist(p->pPhrase); - } - } - - break; - - case FTSQUERY_OR: { - int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc); - int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc); - bHit = bHit1 || bHit2; - break; - } - - case FTSQUERY_NOT: - bHit = ( - fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc) - && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc) - ); - break; - - default: { -#ifndef SQLITE_DISABLE_FTS4_DEFERRED - if( pCsr->pDeferred - && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred) - ){ - Fts3Phrase *pPhrase = pExpr->pPhrase; - assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 ); - if( pExpr->bDeferred ){ - fts3EvalInvalidatePoslist(pPhrase); - } - *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase); - bHit = (pPhrase->doclist.pList!=0); - pExpr->iDocid = pCsr->iPrevId; - }else -#endif - { - bHit = ( - pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId - && pExpr->pPhrase->doclist.nList>0 - ); - } - break; - } - } - } - return bHit; -} - -/* -** This function is called as the second part of each xNext operation when -** iterating through the results of a full-text query. At this point the -** cursor points to a row that matches the query expression, with the -** following caveats: -** -** * Up until this point, "NEAR" operators in the expression have been -** treated as "AND". -** -** * Deferred tokens have not yet been considered. -** -** If *pRc is not SQLITE_OK when this function is called, it immediately -** returns 0. Otherwise, it tests whether or not after considering NEAR -** operators and deferred tokens the current row is still a match for the -** expression. It returns 1 if both of the following are true: -** -** 1. *pRc is SQLITE_OK when this function returns, and -** -** 2. After scanning the current FTS table row for the deferred tokens, -** it is determined that the row does *not* match the query. -** -** Or, if no error occurs and it seems the current row does match the FTS -** query, return 0. -*/ -SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){ - int rc = *pRc; - int bMiss = 0; - if( rc==SQLITE_OK ){ - - /* If there are one or more deferred tokens, load the current row into - ** memory and scan it to determine the position list for each deferred - ** token. Then, see if this row is really a match, considering deferred - ** tokens and NEAR operators (neither of which were taken into account - ** earlier, by fts3EvalNextRow()). - */ - if( pCsr->pDeferred ){ - rc = fts3CursorSeek(0, pCsr); - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3CacheDeferredDoclists(pCsr); - } - } - bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc)); - - /* Free the position-lists accumulated for each deferred token above. */ - sqlite3Fts3FreeDeferredDoclists(pCsr); - *pRc = rc; - } - return (rc==SQLITE_OK && bMiss); -} - -/* -** Advance to the next document that matches the FTS expression in -** Fts3Cursor.pExpr. -*/ -static int fts3EvalNext(Fts3Cursor *pCsr){ - int rc = SQLITE_OK; /* Return Code */ - Fts3Expr *pExpr = pCsr->pExpr; - assert( pCsr->isEof==0 ); - if( pExpr==0 ){ - pCsr->isEof = 1; - }else{ - do { - if( pCsr->isRequireSeek==0 ){ - sqlite3_reset(pCsr->pStmt); - } - assert( sqlite3_data_count(pCsr->pStmt)==0 ); - fts3EvalNextRow(pCsr, pExpr, &rc); - pCsr->isEof = pExpr->bEof; - pCsr->isRequireSeek = 1; - pCsr->isMatchinfoNeeded = 1; - pCsr->iPrevId = pExpr->iDocid; - }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) ); - } - - /* Check if the cursor is past the end of the docid range specified - ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */ - if( rc==SQLITE_OK && ( - (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid) - || (pCsr->bDesc!=0 && pCsr->iPrevIdiMinDocid) - )){ - pCsr->isEof = 1; - } - - return rc; -} - -/* -** Restart interation for expression pExpr so that the next call to -** fts3EvalNext() visits the first row. Do not allow incremental -** loading or merging of phrase doclists for this iteration. -** -** If *pRc is other than SQLITE_OK when this function is called, it is -** a no-op. If an error occurs within this function, *pRc is set to an -** SQLite error code before returning. -*/ -static void fts3EvalRestart( - Fts3Cursor *pCsr, - Fts3Expr *pExpr, - int *pRc -){ - if( pExpr && *pRc==SQLITE_OK ){ - Fts3Phrase *pPhrase = pExpr->pPhrase; - - if( pPhrase ){ - fts3EvalInvalidatePoslist(pPhrase); - if( pPhrase->bIncr ){ - int i; - for(i=0; inToken; i++){ - Fts3PhraseToken *pToken = &pPhrase->aToken[i]; - assert( pToken->pDeferred==0 ); - if( pToken->pSegcsr ){ - sqlite3Fts3MsrIncrRestart(pToken->pSegcsr); - } - } - *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase); - } - pPhrase->doclist.pNextDocid = 0; - pPhrase->doclist.iDocid = 0; - pPhrase->pOrPoslist = 0; - } - - pExpr->iDocid = 0; - pExpr->bEof = 0; - pExpr->bStart = 0; - - fts3EvalRestart(pCsr, pExpr->pLeft, pRc); - fts3EvalRestart(pCsr, pExpr->pRight, pRc); - } -} - -/* -** After allocating the Fts3Expr.aMI[] array for each phrase in the -** expression rooted at pExpr, the cursor iterates through all rows matched -** by pExpr, calling this function for each row. This function increments -** the values in Fts3Expr.aMI[] according to the position-list currently -** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase -** expression nodes. -*/ -static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){ - if( pExpr ){ - Fts3Phrase *pPhrase = pExpr->pPhrase; - if( pPhrase && pPhrase->doclist.pList ){ - int iCol = 0; - char *p = pPhrase->doclist.pList; - - do{ - u8 c = 0; - int iCnt = 0; - while( 0xFE & (*p | c) ){ - if( (c&0x80)==0 ) iCnt++; - c = *p++ & 0x80; - } - - /* aMI[iCol*3 + 1] = Number of occurrences - ** aMI[iCol*3 + 2] = Number of rows containing at least one instance - */ - pExpr->aMI[iCol*3 + 1] += iCnt; - pExpr->aMI[iCol*3 + 2] += (iCnt>0); - if( *p==0x00 ) break; - p++; - p += fts3GetVarint32(p, &iCol); - }while( iColpLeft, nCol); - fts3EvalUpdateCounts(pExpr->pRight, nCol); - } -} - -/* -** Expression pExpr must be of type FTSQUERY_PHRASE. -** -** If it is not already allocated and populated, this function allocates and -** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part -** of a NEAR expression, then it also allocates and populates the same array -** for all other phrases that are part of the NEAR expression. -** -** SQLITE_OK is returned if the aMI[] array is successfully allocated and -** populated. Otherwise, if an error occurs, an SQLite error code is returned. -*/ -static int fts3EvalGatherStats( - Fts3Cursor *pCsr, /* Cursor object */ - Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */ -){ - int rc = SQLITE_OK; /* Return code */ - - assert( pExpr->eType==FTSQUERY_PHRASE ); - if( pExpr->aMI==0 ){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - Fts3Expr *pRoot; /* Root of NEAR expression */ - Fts3Expr *p; /* Iterator used for several purposes */ - - sqlite3_int64 iPrevId = pCsr->iPrevId; - sqlite3_int64 iDocid; - u8 bEof; - - /* Find the root of the NEAR expression */ - pRoot = pExpr; - while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){ - pRoot = pRoot->pParent; - } - iDocid = pRoot->iDocid; - bEof = pRoot->bEof; - assert( pRoot->bStart ); - - /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */ - for(p=pRoot; p; p=p->pLeft){ - Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight); - assert( pE->aMI==0 ); - pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32)); - if( !pE->aMI ) return SQLITE_NOMEM; - memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32)); - } - - fts3EvalRestart(pCsr, pRoot, &rc); - - while( pCsr->isEof==0 && rc==SQLITE_OK ){ - - do { - /* Ensure the %_content statement is reset. */ - if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt); - assert( sqlite3_data_count(pCsr->pStmt)==0 ); - - /* Advance to the next document */ - fts3EvalNextRow(pCsr, pRoot, &rc); - pCsr->isEof = pRoot->bEof; - pCsr->isRequireSeek = 1; - pCsr->isMatchinfoNeeded = 1; - pCsr->iPrevId = pRoot->iDocid; - }while( pCsr->isEof==0 - && pRoot->eType==FTSQUERY_NEAR - && sqlite3Fts3EvalTestDeferred(pCsr, &rc) - ); - - if( rc==SQLITE_OK && pCsr->isEof==0 ){ - fts3EvalUpdateCounts(pRoot, pTab->nColumn); - } - } - - pCsr->isEof = 0; - pCsr->iPrevId = iPrevId; - - if( bEof ){ - pRoot->bEof = bEof; - }else{ - /* Caution: pRoot may iterate through docids in ascending or descending - ** order. For this reason, even though it seems more defensive, the - ** do loop can not be written: - ** - ** do {...} while( pRoot->iDocidbEof==0 ); - if( pRoot->bEof ) rc = FTS_CORRUPT_VTAB; - }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK ); - } - } - return rc; -} - -/* -** This function is used by the matchinfo() module to query a phrase -** expression node for the following information: -** -** 1. The total number of occurrences of the phrase in each column of -** the FTS table (considering all rows), and -** -** 2. For each column, the number of rows in the table for which the -** column contains at least one instance of the phrase. -** -** If no error occurs, SQLITE_OK is returned and the values for each column -** written into the array aiOut as follows: -** -** aiOut[iCol*3 + 1] = Number of occurrences -** aiOut[iCol*3 + 2] = Number of rows containing at least one instance -** -** Caveats: -** -** * If a phrase consists entirely of deferred tokens, then all output -** values are set to the number of documents in the table. In other -** words we assume that very common tokens occur exactly once in each -** column of each row of the table. -** -** * If a phrase contains some deferred tokens (and some non-deferred -** tokens), count the potential occurrence identified by considering -** the non-deferred tokens instead of actual phrase occurrences. -** -** * If the phrase is part of a NEAR expression, then only phrase instances -** that meet the NEAR constraint are included in the counts. -*/ -SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats( - Fts3Cursor *pCsr, /* FTS cursor handle */ - Fts3Expr *pExpr, /* Phrase expression */ - u32 *aiOut /* Array to write results into (see above) */ -){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int rc = SQLITE_OK; - int iCol; - - if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){ - assert( pCsr->nDoc>0 ); - for(iCol=0; iColnColumn; iCol++){ - aiOut[iCol*3 + 1] = (u32)pCsr->nDoc; - aiOut[iCol*3 + 2] = (u32)pCsr->nDoc; - } - }else{ - rc = fts3EvalGatherStats(pCsr, pExpr); - if( rc==SQLITE_OK ){ - assert( pExpr->aMI ); - for(iCol=0; iColnColumn; iCol++){ - aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1]; - aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2]; - } - } - } - - return rc; -} - -/* -** The expression pExpr passed as the second argument to this function -** must be of type FTSQUERY_PHRASE. -** -** The returned value is either NULL or a pointer to a buffer containing -** a position-list indicating the occurrences of the phrase in column iCol -** of the current row. -** -** More specifically, the returned buffer contains 1 varint for each -** occurrence of the phrase in the column, stored using the normal (delta+2) -** compression and is terminated by either an 0x01 or 0x00 byte. For example, -** if the requested column contains "a b X c d X X" and the position-list -** for 'X' is requested, the buffer returned may contain: -** -** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00 -** -** This function works regardless of whether or not the phrase is deferred, -** incremental, or neither. -*/ -SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist( - Fts3Cursor *pCsr, /* FTS3 cursor object */ - Fts3Expr *pExpr, /* Phrase to return doclist for */ - int iCol, /* Column to return position list for */ - char **ppOut /* OUT: Pointer to position list */ -){ - Fts3Phrase *pPhrase = pExpr->pPhrase; - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - char *pIter; - int iThis; - sqlite3_int64 iDocid; - - /* If this phrase is applies specifically to some column other than - ** column iCol, return a NULL pointer. */ - *ppOut = 0; - assert( iCol>=0 && iColnColumn ); - if( (pPhrase->iColumnnColumn && pPhrase->iColumn!=iCol) ){ - return SQLITE_OK; - } - - iDocid = pExpr->iDocid; - pIter = pPhrase->doclist.pList; - if( iDocid!=pCsr->iPrevId || pExpr->bEof ){ - int rc = SQLITE_OK; - int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */ - int bOr = 0; - u8 bTreeEof = 0; - Fts3Expr *p; /* Used to iterate from pExpr to root */ - Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */ - int bMatch; - - /* Check if this phrase descends from an OR expression node. If not, - ** return NULL. Otherwise, the entry that corresponds to docid - ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the - ** tree that the node is part of has been marked as EOF, but the node - ** itself is not EOF, then it may point to an earlier entry. */ - pNear = pExpr; - for(p=pExpr->pParent; p; p=p->pParent){ - if( p->eType==FTSQUERY_OR ) bOr = 1; - if( p->eType==FTSQUERY_NEAR ) pNear = p; - if( p->bEof ) bTreeEof = 1; - } - if( bOr==0 ) return SQLITE_OK; - - /* This is the descendent of an OR node. In this case we cannot use - ** an incremental phrase. Load the entire doclist for the phrase - ** into memory in this case. */ - if( pPhrase->bIncr ){ - int bEofSave = pNear->bEof; - fts3EvalRestart(pCsr, pNear, &rc); - while( rc==SQLITE_OK && !pNear->bEof ){ - fts3EvalNextRow(pCsr, pNear, &rc); - if( bEofSave==0 && pNear->iDocid==iDocid ) break; - } - assert( rc!=SQLITE_OK || pPhrase->bIncr==0 ); - } - if( bTreeEof ){ - while( rc==SQLITE_OK && !pNear->bEof ){ - fts3EvalNextRow(pCsr, pNear, &rc); - } - } - if( rc!=SQLITE_OK ) return rc; - - bMatch = 1; - for(p=pNear; p; p=p->pLeft){ - u8 bEof = 0; - Fts3Expr *pTest = p; - Fts3Phrase *pPh; - assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE ); - if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight; - assert( pTest->eType==FTSQUERY_PHRASE ); - pPh = pTest->pPhrase; - - pIter = pPh->pOrPoslist; - iDocid = pPh->iOrDocid; - if( pCsr->bDesc==bDescDoclist ){ - bEof = !pPh->doclist.nAll || - (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll)); - while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){ - sqlite3Fts3DoclistNext( - bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, - &pIter, &iDocid, &bEof - ); - } - }else{ - bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll); - while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){ - int dummy; - sqlite3Fts3DoclistPrev( - bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, - &pIter, &iDocid, &dummy, &bEof - ); - } - } - pPh->pOrPoslist = pIter; - pPh->iOrDocid = iDocid; - if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0; - } - - if( bMatch ){ - pIter = pPhrase->pOrPoslist; - }else{ - pIter = 0; - } - } - if( pIter==0 ) return SQLITE_OK; - - if( *pIter==0x01 ){ - pIter++; - pIter += fts3GetVarint32(pIter, &iThis); - }else{ - iThis = 0; - } - while( iThisdoclist, and -** * any Fts3MultiSegReader objects held by phrase tokens. -*/ -SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){ - if( pPhrase ){ - int i; - sqlite3_free(pPhrase->doclist.aAll); - fts3EvalInvalidatePoslist(pPhrase); - memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist)); - for(i=0; inToken; i++){ - fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr); - pPhrase->aToken[i].pSegcsr = 0; - } - } -} - - -/* -** Return SQLITE_CORRUPT_VTAB. -*/ -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3Fts3Corrupt(){ - return SQLITE_CORRUPT_VTAB; -} -#endif - -#if !SQLITE_CORE -/* -** Initialize API pointer table, if required. -*/ -#ifdef _WIN32 -__declspec(dllexport) -#endif -SQLITE_API int sqlite3_fts3_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - SQLITE_EXTENSION_INIT2(pApi) - return sqlite3Fts3Init(db); -} -#endif - -#endif - -/************** End of fts3.c ************************************************/ -/************** Begin file fts3_aux.c ****************************************/ -/* -** 2011 Jan 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. -** -****************************************************************************** -** -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ - -typedef struct Fts3auxTable Fts3auxTable; -typedef struct Fts3auxCursor Fts3auxCursor; - -struct Fts3auxTable { - sqlite3_vtab base; /* Base class used by SQLite core */ - Fts3Table *pFts3Tab; -}; - -struct Fts3auxCursor { - sqlite3_vtab_cursor base; /* Base class used by SQLite core */ - Fts3MultiSegReader csr; /* Must be right after "base" */ - Fts3SegFilter filter; - char *zStop; - int nStop; /* Byte-length of string zStop */ - int iLangid; /* Language id to query */ - int isEof; /* True if cursor is at EOF */ - sqlite3_int64 iRowid; /* Current rowid */ - - int iCol; /* Current value of 'col' column */ - int nStat; /* Size of aStat[] array */ - struct Fts3auxColstats { - sqlite3_int64 nDoc; /* 'documents' values for current csr row */ - sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */ - } *aStat; -}; - -/* -** Schema of the terms table. -*/ -#define FTS3_AUX_SCHEMA \ - "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)" - -/* -** This function does all the work for both the xConnect and xCreate methods. -** These tables have no persistent representation of their own, so xConnect -** and xCreate are identical operations. -*/ -static int fts3auxConnectMethod( - sqlite3 *db, /* Database connection */ - void *pUnused, /* Unused */ - int argc, /* Number of elements in argv array */ - const char * const *argv, /* xCreate/xConnect argument array */ - sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */ - char **pzErr /* OUT: sqlite3_malloc'd error message */ -){ - char const *zDb; /* Name of database (e.g. "main") */ - char const *zFts3; /* Name of fts3 table */ - int nDb; /* Result of strlen(zDb) */ - int nFts3; /* Result of strlen(zFts3) */ - sqlite3_int64 nByte; /* Bytes of space to allocate here */ - int rc; /* value returned by declare_vtab() */ - Fts3auxTable *p; /* Virtual table object to return */ - - UNUSED_PARAMETER(pUnused); - - /* The user should invoke this in one of two forms: - ** - ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table); - ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table); - */ - if( argc!=4 && argc!=5 ) goto bad_args; - - zDb = argv[1]; - nDb = (int)strlen(zDb); - if( argc==5 ){ - if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){ - zDb = argv[3]; - nDb = (int)strlen(zDb); - zFts3 = argv[4]; - }else{ - goto bad_args; - } - }else{ - zFts3 = argv[3]; - } - nFts3 = (int)strlen(zFts3); - - rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA); - if( rc!=SQLITE_OK ) return rc; - - nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2; - p = (Fts3auxTable *)sqlite3_malloc64(nByte); - if( !p ) return SQLITE_NOMEM; - memset(p, 0, nByte); - - p->pFts3Tab = (Fts3Table *)&p[1]; - p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1]; - p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1]; - p->pFts3Tab->db = db; - p->pFts3Tab->nIndex = 1; - - memcpy((char *)p->pFts3Tab->zDb, zDb, nDb); - memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3); - sqlite3Fts3Dequote((char *)p->pFts3Tab->zName); - - *ppVtab = (sqlite3_vtab *)p; - return SQLITE_OK; - - bad_args: - sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor"); - return SQLITE_ERROR; -} - -/* -** This function does the work for both the xDisconnect and xDestroy methods. -** These tables have no persistent representation of their own, so xDisconnect -** and xDestroy are identical operations. -*/ -static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ - Fts3auxTable *p = (Fts3auxTable *)pVtab; - Fts3Table *pFts3 = p->pFts3Tab; - int i; - - /* Free any prepared statements held */ - for(i=0; iaStmt); i++){ - sqlite3_finalize(pFts3->aStmt[i]); - } - sqlite3_free(pFts3->zSegmentsTbl); - sqlite3_free(p); - return SQLITE_OK; -} - -#define FTS4AUX_EQ_CONSTRAINT 1 -#define FTS4AUX_GE_CONSTRAINT 2 -#define FTS4AUX_LE_CONSTRAINT 4 - -/* -** xBestIndex - Analyze a WHERE and ORDER BY clause. -*/ -static int fts3auxBestIndexMethod( - sqlite3_vtab *pVTab, - sqlite3_index_info *pInfo -){ - int i; - int iEq = -1; - int iGe = -1; - int iLe = -1; - int iLangid = -1; - int iNext = 1; /* Next free argvIndex value */ - - UNUSED_PARAMETER(pVTab); - - /* This vtab delivers always results in "ORDER BY term ASC" order. */ - if( pInfo->nOrderBy==1 - && pInfo->aOrderBy[0].iColumn==0 - && pInfo->aOrderBy[0].desc==0 - ){ - pInfo->orderByConsumed = 1; - } - - /* Search for equality and range constraints on the "term" column. - ** And equality constraints on the hidden "languageid" column. */ - for(i=0; inConstraint; i++){ - if( pInfo->aConstraint[i].usable ){ - int op = pInfo->aConstraint[i].op; - int iCol = pInfo->aConstraint[i].iColumn; - - if( iCol==0 ){ - if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i; - if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i; - if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i; - if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i; - if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i; - } - if( iCol==4 ){ - if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i; - } - } - } - - if( iEq>=0 ){ - pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT; - pInfo->aConstraintUsage[iEq].argvIndex = iNext++; - pInfo->estimatedCost = 5; - }else{ - pInfo->idxNum = 0; - pInfo->estimatedCost = 20000; - if( iGe>=0 ){ - pInfo->idxNum += FTS4AUX_GE_CONSTRAINT; - pInfo->aConstraintUsage[iGe].argvIndex = iNext++; - pInfo->estimatedCost /= 2; - } - if( iLe>=0 ){ - pInfo->idxNum += FTS4AUX_LE_CONSTRAINT; - pInfo->aConstraintUsage[iLe].argvIndex = iNext++; - pInfo->estimatedCost /= 2; - } - } - if( iLangid>=0 ){ - pInfo->aConstraintUsage[iLangid].argvIndex = iNext++; - pInfo->estimatedCost--; - } - - return SQLITE_OK; -} - -/* -** xOpen - Open a cursor. -*/ -static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ - Fts3auxCursor *pCsr; /* Pointer to cursor object to return */ - - UNUSED_PARAMETER(pVTab); - - pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor)); - if( !pCsr ) return SQLITE_NOMEM; - memset(pCsr, 0, sizeof(Fts3auxCursor)); - - *ppCsr = (sqlite3_vtab_cursor *)pCsr; - return SQLITE_OK; -} - -/* -** xClose - Close a cursor. -*/ -static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){ - Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; - Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; - - sqlite3Fts3SegmentsClose(pFts3); - sqlite3Fts3SegReaderFinish(&pCsr->csr); - sqlite3_free((void *)pCsr->filter.zTerm); - sqlite3_free(pCsr->zStop); - sqlite3_free(pCsr->aStat); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){ - if( nSize>pCsr->nStat ){ - struct Fts3auxColstats *aNew; - aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat, - sizeof(struct Fts3auxColstats) * nSize - ); - if( aNew==0 ) return SQLITE_NOMEM; - memset(&aNew[pCsr->nStat], 0, - sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat) - ); - pCsr->aStat = aNew; - pCsr->nStat = nSize; - } - return SQLITE_OK; -} - -/* -** xNext - Advance the cursor to the next row, if any. -*/ -static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ - Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; - Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; - int rc; - - /* Increment our pretend rowid value. */ - pCsr->iRowid++; - - for(pCsr->iCol++; pCsr->iColnStat; pCsr->iCol++){ - if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK; - } - - rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr); - if( rc==SQLITE_ROW ){ - int i = 0; - int nDoclist = pCsr->csr.nDoclist; - char *aDoclist = pCsr->csr.aDoclist; - int iCol; - - int eState = 0; - - if( pCsr->zStop ){ - int n = (pCsr->nStopcsr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm; - int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n); - if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){ - pCsr->isEof = 1; - return SQLITE_OK; - } - } - - if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM; - memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat); - iCol = 0; - - while( iaStat[0].nDoc++; - eState = 1; - iCol = 0; - break; - - /* State 1. In this state we are expecting either a 1, indicating - ** that the following integer will be a column number, or the - ** start of a position list for column 0. - ** - ** The only difference between state 1 and state 2 is that if the - ** integer encountered in state 1 is not 0 or 1, then we need to - ** increment the column 0 "nDoc" count for this term. - */ - case 1: - assert( iCol==0 ); - if( v>1 ){ - pCsr->aStat[1].nDoc++; - } - eState = 2; - /* fall through */ - - case 2: - if( v==0 ){ /* 0x00. Next integer will be a docid. */ - eState = 0; - }else if( v==1 ){ /* 0x01. Next integer will be a column number. */ - eState = 3; - }else{ /* 2 or greater. A position. */ - pCsr->aStat[iCol+1].nOcc++; - pCsr->aStat[0].nOcc++; - } - break; - - /* State 3. The integer just read is a column number. */ - default: assert( eState==3 ); - iCol = (int)v; - if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM; - pCsr->aStat[iCol+1].nDoc++; - eState = 2; - break; - } - } - - pCsr->iCol = 0; - rc = SQLITE_OK; - }else{ - pCsr->isEof = 1; - } - return rc; -} - -/* -** xFilter - Initialize a cursor to point at the start of its data. -*/ -static int fts3auxFilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ - int idxNum, /* Strategy index */ - const char *idxStr, /* Unused */ - int nVal, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ -){ - Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; - Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab; - int rc; - int isScan = 0; - int iLangVal = 0; /* Language id to query */ - - int iEq = -1; /* Index of term=? value in apVal */ - int iGe = -1; /* Index of term>=? value in apVal */ - int iLe = -1; /* Index of term<=? value in apVal */ - int iLangid = -1; /* Index of languageid=? value in apVal */ - int iNext = 0; - - UNUSED_PARAMETER(nVal); - UNUSED_PARAMETER(idxStr); - - assert( idxStr==0 ); - assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0 - || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT - || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) - ); - - if( idxNum==FTS4AUX_EQ_CONSTRAINT ){ - iEq = iNext++; - }else{ - isScan = 1; - if( idxNum & FTS4AUX_GE_CONSTRAINT ){ - iGe = iNext++; - } - if( idxNum & FTS4AUX_LE_CONSTRAINT ){ - iLe = iNext++; - } - } - if( iNextfilter.zTerm); - sqlite3Fts3SegReaderFinish(&pCsr->csr); - sqlite3_free((void *)pCsr->filter.zTerm); - sqlite3_free(pCsr->aStat); - memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr); - - pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; - if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN; - - if( iEq>=0 || iGe>=0 ){ - const unsigned char *zStr = sqlite3_value_text(apVal[0]); - assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) ); - if( zStr ){ - pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr); - if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM; - pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm); - } - } - - if( iLe>=0 ){ - pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); - if( pCsr->zStop==0 ) return SQLITE_NOMEM; - pCsr->nStop = (int)strlen(pCsr->zStop); - } - - if( iLangid>=0 ){ - iLangVal = sqlite3_value_int(apVal[iLangid]); - - /* If the user specified a negative value for the languageid, use zero - ** instead. This works, as the "languageid=?" constraint will also - ** be tested by the VDBE layer. The test will always be false (since - ** this module will not return a row with a negative languageid), and - ** so the overall query will return zero rows. */ - if( iLangVal<0 ) iLangVal = 0; - } - pCsr->iLangid = iLangVal; - - rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL, - pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr - ); - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter); - } - - if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor); - return rc; -} - -/* -** xEof - Return true if the cursor is at EOF, or false otherwise. -*/ -static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){ - Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; - return pCsr->isEof; -} - -/* -** xColumn - Return a column value. -*/ -static int fts3auxColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ - int iCol /* Index of column to read value from */ -){ - Fts3auxCursor *p = (Fts3auxCursor *)pCursor; - - assert( p->isEof==0 ); - switch( iCol ){ - case 0: /* term */ - sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT); - break; - - case 1: /* col */ - if( p->iCol ){ - sqlite3_result_int(pCtx, p->iCol-1); - }else{ - sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC); - } - break; - - case 2: /* documents */ - sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc); - break; - - case 3: /* occurrences */ - sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc); - break; - - default: /* languageid */ - assert( iCol==4 ); - sqlite3_result_int(pCtx, p->iLangid); - break; - } - - return SQLITE_OK; -} - -/* -** xRowid - Return the current rowid for the cursor. -*/ -static int fts3auxRowidMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite_int64 *pRowid /* OUT: Rowid value */ -){ - Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor; - *pRowid = pCsr->iRowid; - return SQLITE_OK; -} - -/* -** Register the fts3aux module with database connection db. Return SQLITE_OK -** if successful or an error code if sqlite3_create_module() fails. -*/ -SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){ - static const sqlite3_module fts3aux_module = { - 0, /* iVersion */ - fts3auxConnectMethod, /* xCreate */ - fts3auxConnectMethod, /* xConnect */ - fts3auxBestIndexMethod, /* xBestIndex */ - fts3auxDisconnectMethod, /* xDisconnect */ - fts3auxDisconnectMethod, /* xDestroy */ - fts3auxOpenMethod, /* xOpen */ - fts3auxCloseMethod, /* xClose */ - fts3auxFilterMethod, /* xFilter */ - fts3auxNextMethod, /* xNext */ - fts3auxEofMethod, /* xEof */ - fts3auxColumnMethod, /* xColumn */ - fts3auxRowidMethod, /* xRowid */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindFunction */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0 /* xShadowName */ - }; - int rc; /* Return code */ - - rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0); - return rc; -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_aux.c ********************************************/ -/************** Begin file fts3_expr.c ***************************************/ -/* -** 2008 Nov 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 module contains code that implements a parser for fts3 query strings -** (the right-hand argument to the MATCH operator). Because the supported -** syntax is relatively simple, the whole tokenizer/parser system is -** hand-coded. -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* -** By default, this module parses the legacy syntax that has been -** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS -** is defined, then it uses the new syntax. The differences between -** the new and the old syntaxes are: -** -** a) The new syntax supports parenthesis. The old does not. -** -** b) The new syntax supports the AND and NOT operators. The old does not. -** -** c) The old syntax supports the "-" token qualifier. This is not -** supported by the new syntax (it is replaced by the NOT operator). -** -** d) When using the old syntax, the OR operator has a greater precedence -** than an implicit AND. When using the new, both implicity and explicit -** AND operators have a higher precedence than OR. -** -** If compiled with SQLITE_TEST defined, then this module exports the -** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable -** to zero causes the module to use the old syntax. If it is set to -** non-zero the new syntax is activated. This is so both syntaxes can -** be tested using a single build of testfixture. -** -** The following describes the syntax supported by the fts3 MATCH -** operator in a similar format to that used by the lemon parser -** generator. This module does not use actually lemon, it uses a -** custom parser. -** -** query ::= andexpr (OR andexpr)*. -** -** andexpr ::= notexpr (AND? notexpr)*. -** -** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*. -** notexpr ::= LP query RP. -** -** nearexpr ::= phrase (NEAR distance_opt nearexpr)*. -** -** distance_opt ::= . -** distance_opt ::= / INTEGER. -** -** phrase ::= TOKEN. -** phrase ::= COLUMN:TOKEN. -** phrase ::= "TOKEN TOKEN TOKEN...". -*/ - -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_fts3_enable_parentheses = 0; -#else -# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS -# define sqlite3_fts3_enable_parentheses 1 -# else -# define sqlite3_fts3_enable_parentheses 0 -# endif -#endif - -/* -** Default span for NEAR operators. -*/ -#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 - -/* #include */ -/* #include */ - -/* -** isNot: -** This variable is used by function getNextNode(). When getNextNode() is -** called, it sets ParseContext.isNot to true if the 'next node' is a -** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the -** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to -** zero. -*/ -typedef struct ParseContext ParseContext; -struct ParseContext { - sqlite3_tokenizer *pTokenizer; /* Tokenizer module */ - int iLangid; /* Language id used with tokenizer */ - const char **azCol; /* Array of column names for fts3 table */ - int bFts4; /* True to allow FTS4-only syntax */ - int nCol; /* Number of entries in azCol[] */ - int iDefaultCol; /* Default column to query */ - int isNot; /* True if getNextNode() sees a unary - */ - sqlite3_context *pCtx; /* Write error message here */ - int nNest; /* Number of nested brackets */ -}; - -/* -** This function is equivalent to the standard isspace() function. -** -** The standard isspace() can be awkward to use safely, because although it -** is defined to accept an argument of type int, its behavior when passed -** an integer that falls outside of the range of the unsigned char type -** is undefined (and sometimes, "undefined" means segfault). This wrapper -** is defined to accept an argument of type char, and always returns 0 for -** any values that fall outside of the range of the unsigned char type (i.e. -** negative values). -*/ -static int fts3isspace(char c){ - return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; -} - -/* -** Allocate nByte bytes of memory using sqlite3_malloc(). If successful, -** zero the memory before returning a pointer to it. If unsuccessful, -** return NULL. -*/ -static void *fts3MallocZero(sqlite3_int64 nByte){ - void *pRet = sqlite3_malloc64(nByte); - if( pRet ) memset(pRet, 0, nByte); - return pRet; -} - -SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer( - sqlite3_tokenizer *pTokenizer, - int iLangid, - const char *z, - int n, - sqlite3_tokenizer_cursor **ppCsr -){ - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; - sqlite3_tokenizer_cursor *pCsr = 0; - int rc; - - rc = pModule->xOpen(pTokenizer, z, n, &pCsr); - assert( rc==SQLITE_OK || pCsr==0 ); - if( rc==SQLITE_OK ){ - pCsr->pTokenizer = pTokenizer; - if( pModule->iVersion>=1 ){ - rc = pModule->xLanguageid(pCsr, iLangid); - if( rc!=SQLITE_OK ){ - pModule->xClose(pCsr); - pCsr = 0; - } - } - } - *ppCsr = pCsr; - return rc; -} - -/* -** Function getNextNode(), which is called by fts3ExprParse(), may itself -** call fts3ExprParse(). So this forward declaration is required. -*/ -static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); - -/* -** Extract the next token from buffer z (length n) using the tokenizer -** and other information (column names etc.) in pParse. Create an Fts3Expr -** structure of type FTSQUERY_PHRASE containing a phrase consisting of this -** single token and set *ppExpr to point to it. If the end of the buffer is -** reached before a token is found, set *ppExpr to zero. It is the -** responsibility of the caller to eventually deallocate the allocated -** Fts3Expr structure (if any) by passing it to sqlite3_free(). -** -** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation -** fails. -*/ -static int getNextToken( - ParseContext *pParse, /* fts3 query parse context */ - int iCol, /* Value for Fts3Phrase.iColumn */ - const char *z, int n, /* Input string */ - Fts3Expr **ppExpr, /* OUT: expression */ - int *pnConsumed /* OUT: Number of bytes consumed */ -){ - sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; - int rc; - sqlite3_tokenizer_cursor *pCursor; - Fts3Expr *pRet = 0; - int i = 0; - - /* Set variable i to the maximum number of bytes of input to tokenize. */ - for(i=0; iiLangid, z, i, &pCursor); - if( rc==SQLITE_OK ){ - const char *zToken; - int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0; - sqlite3_int64 nByte; /* total space to allocate */ - - rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); - if( rc==SQLITE_OK ){ - nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken; - pRet = (Fts3Expr *)fts3MallocZero(nByte); - if( !pRet ){ - rc = SQLITE_NOMEM; - }else{ - pRet->eType = FTSQUERY_PHRASE; - pRet->pPhrase = (Fts3Phrase *)&pRet[1]; - pRet->pPhrase->nToken = 1; - pRet->pPhrase->iColumn = iCol; - pRet->pPhrase->aToken[0].n = nToken; - pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1]; - memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken); - - if( iEndpPhrase->aToken[0].isPrefix = 1; - iEnd++; - } - - while( 1 ){ - if( !sqlite3_fts3_enable_parentheses - && iStart>0 && z[iStart-1]=='-' - ){ - pParse->isNot = 1; - iStart--; - }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){ - pRet->pPhrase->aToken[0].bFirst = 1; - iStart--; - }else{ - break; - } - } - - } - *pnConsumed = iEnd; - }else if( i && rc==SQLITE_DONE ){ - rc = SQLITE_OK; - } - - pModule->xClose(pCursor); - } - - *ppExpr = pRet; - return rc; -} - - -/* -** Enlarge a memory allocation. If an out-of-memory allocation occurs, -** then free the old allocation. -*/ -static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){ - void *pRet = sqlite3_realloc64(pOrig, nNew); - if( !pRet ){ - sqlite3_free(pOrig); - } - return pRet; -} - -/* -** Buffer zInput, length nInput, contains the contents of a quoted string -** that appeared as part of an fts3 query expression. Neither quote character -** is included in the buffer. This function attempts to tokenize the entire -** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE -** containing the results. -** -** If successful, SQLITE_OK is returned and *ppExpr set to point at the -** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory -** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set -** to 0. -*/ -static int getNextString( - ParseContext *pParse, /* fts3 query parse context */ - const char *zInput, int nInput, /* Input string */ - Fts3Expr **ppExpr /* OUT: expression */ -){ - sqlite3_tokenizer *pTokenizer = pParse->pTokenizer; - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; - int rc; - Fts3Expr *p = 0; - sqlite3_tokenizer_cursor *pCursor = 0; - char *zTemp = 0; - int nTemp = 0; - - const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase); - int nToken = 0; - - /* The final Fts3Expr data structure, including the Fts3Phrase, - ** Fts3PhraseToken structures token buffers are all stored as a single - ** allocation so that the expression can be freed with a single call to - ** sqlite3_free(). Setting this up requires a two pass approach. - ** - ** The first pass, in the block below, uses a tokenizer cursor to iterate - ** through the tokens in the expression. This pass uses fts3ReallocOrFree() - ** to assemble data in two dynamic buffers: - ** - ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase - ** structure, followed by the array of Fts3PhraseToken - ** structures. This pass only populates the Fts3PhraseToken array. - ** - ** Buffer zTemp: Contains copies of all tokens. - ** - ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below, - ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase - ** structures. - */ - rc = sqlite3Fts3OpenTokenizer( - pTokenizer, pParse->iLangid, zInput, nInput, &pCursor); - if( rc==SQLITE_OK ){ - int ii; - for(ii=0; rc==SQLITE_OK; ii++){ - const char *zByte; - int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0; - rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos); - if( rc==SQLITE_OK ){ - Fts3PhraseToken *pToken; - - p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken)); - if( !p ) goto no_mem; - - zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte); - if( !zTemp ) goto no_mem; - - assert( nToken==ii ); - pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii]; - memset(pToken, 0, sizeof(Fts3PhraseToken)); - - memcpy(&zTemp[nTemp], zByte, nByte); - nTemp += nByte; - - pToken->n = nByte; - pToken->isPrefix = (iEndbFirst = (iBegin>0 && zInput[iBegin-1]=='^'); - nToken = ii+1; - } - } - - pModule->xClose(pCursor); - pCursor = 0; - } - - if( rc==SQLITE_DONE ){ - int jj; - char *zBuf = 0; - - p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp); - if( !p ) goto no_mem; - memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p); - p->eType = FTSQUERY_PHRASE; - p->pPhrase = (Fts3Phrase *)&p[1]; - p->pPhrase->iColumn = pParse->iDefaultCol; - p->pPhrase->nToken = nToken; - - zBuf = (char *)&p->pPhrase->aToken[nToken]; - if( zTemp ){ - memcpy(zBuf, zTemp, nTemp); - sqlite3_free(zTemp); - }else{ - assert( nTemp==0 ); - } - - for(jj=0; jjpPhrase->nToken; jj++){ - p->pPhrase->aToken[jj].z = zBuf; - zBuf += p->pPhrase->aToken[jj].n; - } - rc = SQLITE_OK; - } - - *ppExpr = p; - return rc; -no_mem: - - if( pCursor ){ - pModule->xClose(pCursor); - } - sqlite3_free(zTemp); - sqlite3_free(p); - *ppExpr = 0; - return SQLITE_NOMEM; -} - -/* -** The output variable *ppExpr is populated with an allocated Fts3Expr -** structure, or set to 0 if the end of the input buffer is reached. -** -** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM -** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered. -** If SQLITE_ERROR is returned, pContext is populated with an error message. -*/ -static int getNextNode( - ParseContext *pParse, /* fts3 query parse context */ - const char *z, int n, /* Input string */ - Fts3Expr **ppExpr, /* OUT: expression */ - int *pnConsumed /* OUT: Number of bytes consumed */ -){ - static const struct Fts3Keyword { - char *z; /* Keyword text */ - unsigned char n; /* Length of the keyword */ - unsigned char parenOnly; /* Only valid in paren mode */ - unsigned char eType; /* Keyword code */ - } aKeyword[] = { - { "OR" , 2, 0, FTSQUERY_OR }, - { "AND", 3, 1, FTSQUERY_AND }, - { "NOT", 3, 1, FTSQUERY_NOT }, - { "NEAR", 4, 0, FTSQUERY_NEAR } - }; - int ii; - int iCol; - int iColLen; - int rc; - Fts3Expr *pRet = 0; - - const char *zInput = z; - int nInput = n; - - pParse->isNot = 0; - - /* Skip over any whitespace before checking for a keyword, an open or - ** close bracket, or a quoted string. - */ - while( nInput>0 && fts3isspace(*zInput) ){ - nInput--; - zInput++; - } - if( nInput==0 ){ - return SQLITE_DONE; - } - - /* See if we are dealing with a keyword. */ - for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){ - const struct Fts3Keyword *pKey = &aKeyword[ii]; - - if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){ - continue; - } - - if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){ - int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM; - int nKey = pKey->n; - char cNext; - - /* If this is a "NEAR" keyword, check for an explicit nearness. */ - if( pKey->eType==FTSQUERY_NEAR ){ - assert( nKey==4 ); - if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){ - nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear); - } - } - - /* At this point this is probably a keyword. But for that to be true, - ** the next byte must contain either whitespace, an open or close - ** parenthesis, a quote character, or EOF. - */ - cNext = zInput[nKey]; - if( fts3isspace(cNext) - || cNext=='"' || cNext=='(' || cNext==')' || cNext==0 - ){ - pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr)); - if( !pRet ){ - return SQLITE_NOMEM; - } - pRet->eType = pKey->eType; - pRet->nNear = nNear; - *ppExpr = pRet; - *pnConsumed = (int)((zInput - z) + nKey); - return SQLITE_OK; - } - - /* Turns out that wasn't a keyword after all. This happens if the - ** user has supplied a token such as "ORacle". Continue. - */ - } - } - - /* See if we are dealing with a quoted phrase. If this is the case, then - ** search for the closing quote and pass the whole string to getNextString() - ** for processing. This is easy to do, as fts3 has no syntax for escaping - ** a quote character embedded in a string. - */ - if( *zInput=='"' ){ - for(ii=1; iinNest++; - rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed); - *pnConsumed = (int)(zInput - z) + 1 + nConsumed; - return rc; - }else if( *zInput==')' ){ - pParse->nNest--; - *pnConsumed = (int)((zInput - z) + 1); - *ppExpr = 0; - return SQLITE_DONE; - } - } - - /* If control flows to this point, this must be a regular token, or - ** the end of the input. Read a regular token using the sqlite3_tokenizer - ** interface. Before doing so, figure out if there is an explicit - ** column specifier for the token. - ** - ** TODO: Strangely, it is not possible to associate a column specifier - ** with a quoted phrase, only with a single token. Not sure if this was - ** an implementation artifact or an intentional decision when fts3 was - ** first implemented. Whichever it was, this module duplicates the - ** limitation. - */ - iCol = pParse->iDefaultCol; - iColLen = 0; - for(ii=0; iinCol; ii++){ - const char *zStr = pParse->azCol[ii]; - int nStr = (int)strlen(zStr); - if( nInput>nStr && zInput[nStr]==':' - && sqlite3_strnicmp(zStr, zInput, nStr)==0 - ){ - iCol = ii; - iColLen = (int)((zInput - z) + nStr + 1); - break; - } - } - rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed); - *pnConsumed += iColLen; - return rc; -} - -/* -** The argument is an Fts3Expr structure for a binary operator (any type -** except an FTSQUERY_PHRASE). Return an integer value representing the -** precedence of the operator. Lower values have a higher precedence (i.e. -** group more tightly). For example, in the C language, the == operator -** groups more tightly than ||, and would therefore have a higher precedence. -** -** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS -** is defined), the order of the operators in precedence from highest to -** lowest is: -** -** NEAR -** NOT -** AND (including implicit ANDs) -** OR -** -** Note that when using the old query syntax, the OR operator has a higher -** precedence than the AND operator. -*/ -static int opPrecedence(Fts3Expr *p){ - assert( p->eType!=FTSQUERY_PHRASE ); - if( sqlite3_fts3_enable_parentheses ){ - return p->eType; - }else if( p->eType==FTSQUERY_NEAR ){ - return 1; - }else if( p->eType==FTSQUERY_OR ){ - return 2; - } - assert( p->eType==FTSQUERY_AND ); - return 3; -} - -/* -** Argument ppHead contains a pointer to the current head of a query -** expression tree being parsed. pPrev is the expression node most recently -** inserted into the tree. This function adds pNew, which is always a binary -** operator node, into the expression tree based on the relative precedence -** of pNew and the existing nodes of the tree. This may result in the head -** of the tree changing, in which case *ppHead is set to the new root node. -*/ -static void insertBinaryOperator( - Fts3Expr **ppHead, /* Pointer to the root node of a tree */ - Fts3Expr *pPrev, /* Node most recently inserted into the tree */ - Fts3Expr *pNew /* New binary node to insert into expression tree */ -){ - Fts3Expr *pSplit = pPrev; - while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){ - pSplit = pSplit->pParent; - } - - if( pSplit->pParent ){ - assert( pSplit->pParent->pRight==pSplit ); - pSplit->pParent->pRight = pNew; - pNew->pParent = pSplit->pParent; - }else{ - *ppHead = pNew; - } - pNew->pLeft = pSplit; - pSplit->pParent = pNew; -} - -/* -** Parse the fts3 query expression found in buffer z, length n. This function -** returns either when the end of the buffer is reached or an unmatched -** closing bracket - ')' - is encountered. -** -** If successful, SQLITE_OK is returned, *ppExpr is set to point to the -** parsed form of the expression and *pnConsumed is set to the number of -** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM -** (out of memory error) or SQLITE_ERROR (parse error) is returned. -*/ -static int fts3ExprParse( - ParseContext *pParse, /* fts3 query parse context */ - const char *z, int n, /* Text of MATCH query */ - Fts3Expr **ppExpr, /* OUT: Parsed query structure */ - int *pnConsumed /* OUT: Number of bytes consumed */ -){ - Fts3Expr *pRet = 0; - Fts3Expr *pPrev = 0; - Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */ - int nIn = n; - const char *zIn = z; - int rc = SQLITE_OK; - int isRequirePhrase = 1; - - while( rc==SQLITE_OK ){ - Fts3Expr *p = 0; - int nByte = 0; - - rc = getNextNode(pParse, zIn, nIn, &p, &nByte); - assert( nByte>0 || (rc!=SQLITE_OK && p==0) ); - if( rc==SQLITE_OK ){ - if( p ){ - int isPhrase; - - if( !sqlite3_fts3_enable_parentheses - && p->eType==FTSQUERY_PHRASE && pParse->isNot - ){ - /* Create an implicit NOT operator. */ - Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr)); - if( !pNot ){ - sqlite3Fts3ExprFree(p); - rc = SQLITE_NOMEM; - goto exprparse_out; - } - pNot->eType = FTSQUERY_NOT; - pNot->pRight = p; - p->pParent = pNot; - if( pNotBranch ){ - pNot->pLeft = pNotBranch; - pNotBranch->pParent = pNot; - } - pNotBranch = pNot; - p = pPrev; - }else{ - int eType = p->eType; - isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft); - - /* The isRequirePhrase variable is set to true if a phrase or - ** an expression contained in parenthesis is required. If a - ** binary operator (AND, OR, NOT or NEAR) is encounted when - ** isRequirePhrase is set, this is a syntax error. - */ - if( !isPhrase && isRequirePhrase ){ - sqlite3Fts3ExprFree(p); - rc = SQLITE_ERROR; - goto exprparse_out; - } - - if( isPhrase && !isRequirePhrase ){ - /* Insert an implicit AND operator. */ - Fts3Expr *pAnd; - assert( pRet && pPrev ); - pAnd = fts3MallocZero(sizeof(Fts3Expr)); - if( !pAnd ){ - sqlite3Fts3ExprFree(p); - rc = SQLITE_NOMEM; - goto exprparse_out; - } - pAnd->eType = FTSQUERY_AND; - insertBinaryOperator(&pRet, pPrev, pAnd); - pPrev = pAnd; - } - - /* This test catches attempts to make either operand of a NEAR - ** operator something other than a phrase. For example, either of - ** the following: - ** - ** (bracketed expression) NEAR phrase - ** phrase NEAR (bracketed expression) - ** - ** Return an error in either case. - */ - if( pPrev && ( - (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE) - || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR) - )){ - sqlite3Fts3ExprFree(p); - rc = SQLITE_ERROR; - goto exprparse_out; - } - - if( isPhrase ){ - if( pRet ){ - assert( pPrev && pPrev->pLeft && pPrev->pRight==0 ); - pPrev->pRight = p; - p->pParent = pPrev; - }else{ - pRet = p; - } - }else{ - insertBinaryOperator(&pRet, pPrev, p); - } - isRequirePhrase = !isPhrase; - } - pPrev = p; - } - assert( nByte>0 ); - } - assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) ); - nIn -= nByte; - zIn += nByte; - } - - if( rc==SQLITE_DONE && pRet && isRequirePhrase ){ - rc = SQLITE_ERROR; - } - - if( rc==SQLITE_DONE ){ - rc = SQLITE_OK; - if( !sqlite3_fts3_enable_parentheses && pNotBranch ){ - if( !pRet ){ - rc = SQLITE_ERROR; - }else{ - Fts3Expr *pIter = pNotBranch; - while( pIter->pLeft ){ - pIter = pIter->pLeft; - } - pIter->pLeft = pRet; - pRet->pParent = pIter; - pRet = pNotBranch; - } - } - } - *pnConsumed = n - nIn; - -exprparse_out: - if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(pRet); - sqlite3Fts3ExprFree(pNotBranch); - pRet = 0; - } - *ppExpr = pRet; - return rc; -} - -/* -** Return SQLITE_ERROR if the maximum depth of the expression tree passed -** as the only argument is more than nMaxDepth. -*/ -static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){ - int rc = SQLITE_OK; - if( p ){ - if( nMaxDepth<0 ){ - rc = SQLITE_TOOBIG; - }else{ - rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1); - if( rc==SQLITE_OK ){ - rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1); - } - } - } - return rc; -} - -/* -** This function attempts to transform the expression tree at (*pp) to -** an equivalent but more balanced form. The tree is modified in place. -** If successful, SQLITE_OK is returned and (*pp) set to point to the -** new root expression node. -** -** nMaxDepth is the maximum allowable depth of the balanced sub-tree. -** -** Otherwise, if an error occurs, an SQLite error code is returned and -** expression (*pp) freed. -*/ -static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){ - int rc = SQLITE_OK; /* Return code */ - Fts3Expr *pRoot = *pp; /* Initial root node */ - Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */ - int eType = pRoot->eType; /* Type of node in this tree */ - - if( nMaxDepth==0 ){ - rc = SQLITE_ERROR; - } - - if( rc==SQLITE_OK ){ - if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){ - Fts3Expr **apLeaf; - apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth); - if( 0==apLeaf ){ - rc = SQLITE_NOMEM; - }else{ - memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth); - } - - if( rc==SQLITE_OK ){ - int i; - Fts3Expr *p; - - /* Set $p to point to the left-most leaf in the tree of eType nodes. */ - for(p=pRoot; p->eType==eType; p=p->pLeft){ - assert( p->pParent==0 || p->pParent->pLeft==p ); - assert( p->pLeft && p->pRight ); - } - - /* This loop runs once for each leaf in the tree of eType nodes. */ - while( 1 ){ - int iLvl; - Fts3Expr *pParent = p->pParent; /* Current parent of p */ - - assert( pParent==0 || pParent->pLeft==p ); - p->pParent = 0; - if( pParent ){ - pParent->pLeft = 0; - }else{ - pRoot = 0; - } - rc = fts3ExprBalance(&p, nMaxDepth-1); - if( rc!=SQLITE_OK ) break; - - for(iLvl=0; p && iLvlpLeft = apLeaf[iLvl]; - pFree->pRight = p; - pFree->pLeft->pParent = pFree; - pFree->pRight->pParent = pFree; - - p = pFree; - pFree = pFree->pParent; - p->pParent = 0; - apLeaf[iLvl] = 0; - } - } - if( p ){ - sqlite3Fts3ExprFree(p); - rc = SQLITE_TOOBIG; - break; - } - - /* If that was the last leaf node, break out of the loop */ - if( pParent==0 ) break; - - /* Set $p to point to the next leaf in the tree of eType nodes */ - for(p=pParent->pRight; p->eType==eType; p=p->pLeft); - - /* Remove pParent from the original tree. */ - assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent ); - pParent->pRight->pParent = pParent->pParent; - if( pParent->pParent ){ - pParent->pParent->pLeft = pParent->pRight; - }else{ - assert( pParent==pRoot ); - pRoot = pParent->pRight; - } - - /* Link pParent into the free node list. It will be used as an - ** internal node of the new tree. */ - pParent->pParent = pFree; - pFree = pParent; - } - - if( rc==SQLITE_OK ){ - p = 0; - for(i=0; ipParent = 0; - }else{ - assert( pFree!=0 ); - pFree->pRight = p; - pFree->pLeft = apLeaf[i]; - pFree->pLeft->pParent = pFree; - pFree->pRight->pParent = pFree; - - p = pFree; - pFree = pFree->pParent; - p->pParent = 0; - } - } - } - pRoot = p; - }else{ - /* An error occurred. Delete the contents of the apLeaf[] array - ** and pFree list. Everything else is cleaned up by the call to - ** sqlite3Fts3ExprFree(pRoot) below. */ - Fts3Expr *pDel; - for(i=0; ipParent; - sqlite3_free(pDel); - } - } - - assert( pFree==0 ); - sqlite3_free( apLeaf ); - } - }else if( eType==FTSQUERY_NOT ){ - Fts3Expr *pLeft = pRoot->pLeft; - Fts3Expr *pRight = pRoot->pRight; - - pRoot->pLeft = 0; - pRoot->pRight = 0; - pLeft->pParent = 0; - pRight->pParent = 0; - - rc = fts3ExprBalance(&pLeft, nMaxDepth-1); - if( rc==SQLITE_OK ){ - rc = fts3ExprBalance(&pRight, nMaxDepth-1); - } - - if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(pRight); - sqlite3Fts3ExprFree(pLeft); - }else{ - assert( pLeft && pRight ); - pRoot->pLeft = pLeft; - pLeft->pParent = pRoot; - pRoot->pRight = pRight; - pRight->pParent = pRoot; - } - } - } - - if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(pRoot); - pRoot = 0; - } - *pp = pRoot; - return rc; -} - -/* -** This function is similar to sqlite3Fts3ExprParse(), with the following -** differences: -** -** 1. It does not do expression rebalancing. -** 2. It does not check that the expression does not exceed the -** maximum allowable depth. -** 3. Even if it fails, *ppExpr may still be set to point to an -** expression tree. It should be deleted using sqlite3Fts3ExprFree() -** in this case. -*/ -static int fts3ExprParseUnbalanced( - sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ - int iLangid, /* Language id for tokenizer */ - char **azCol, /* Array of column names for fts3 table */ - int bFts4, /* True to allow FTS4-only syntax */ - int nCol, /* Number of entries in azCol[] */ - int iDefaultCol, /* Default column to query */ - const char *z, int n, /* Text of MATCH query */ - Fts3Expr **ppExpr /* OUT: Parsed query structure */ -){ - int nParsed; - int rc; - ParseContext sParse; - - memset(&sParse, 0, sizeof(ParseContext)); - sParse.pTokenizer = pTokenizer; - sParse.iLangid = iLangid; - sParse.azCol = (const char **)azCol; - sParse.nCol = nCol; - sParse.iDefaultCol = iDefaultCol; - sParse.bFts4 = bFts4; - if( z==0 ){ - *ppExpr = 0; - return SQLITE_OK; - } - if( n<0 ){ - n = (int)strlen(z); - } - rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed); - assert( rc==SQLITE_OK || *ppExpr==0 ); - - /* Check for mismatched parenthesis */ - if( rc==SQLITE_OK && sParse.nNest ){ - rc = SQLITE_ERROR; - } - - return rc; -} - -/* -** Parameters z and n contain a pointer to and length of a buffer containing -** an fts3 query expression, respectively. This function attempts to parse the -** query expression and create a tree of Fts3Expr structures representing the -** parsed expression. If successful, *ppExpr is set to point to the head -** of the parsed expression tree and SQLITE_OK is returned. If an error -** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse -** error) is returned and *ppExpr is set to 0. -** -** If parameter n is a negative number, then z is assumed to point to a -** nul-terminated string and the length is determined using strlen(). -** -** The first parameter, pTokenizer, is passed the fts3 tokenizer module to -** use to normalize query tokens while parsing the expression. The azCol[] -** array, which is assumed to contain nCol entries, should contain the names -** of each column in the target fts3 table, in order from left to right. -** Column names must be nul-terminated strings. -** -** The iDefaultCol parameter should be passed the index of the table column -** that appears on the left-hand-side of the MATCH operator (the default -** column to match against for tokens for which a column name is not explicitly -** specified as part of the query string), or -1 if tokens may by default -** match any table column. -*/ -SQLITE_PRIVATE int sqlite3Fts3ExprParse( - sqlite3_tokenizer *pTokenizer, /* Tokenizer module */ - int iLangid, /* Language id for tokenizer */ - char **azCol, /* Array of column names for fts3 table */ - int bFts4, /* True to allow FTS4-only syntax */ - int nCol, /* Number of entries in azCol[] */ - int iDefaultCol, /* Default column to query */ - const char *z, int n, /* Text of MATCH query */ - Fts3Expr **ppExpr, /* OUT: Parsed query structure */ - char **pzErr /* OUT: Error message (sqlite3_malloc) */ -){ - int rc = fts3ExprParseUnbalanced( - pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr - ); - - /* Rebalance the expression. And check that its depth does not exceed - ** SQLITE_FTS3_MAX_EXPR_DEPTH. */ - if( rc==SQLITE_OK && *ppExpr ){ - rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); - if( rc==SQLITE_OK ){ - rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH); - } - } - - if( rc!=SQLITE_OK ){ - sqlite3Fts3ExprFree(*ppExpr); - *ppExpr = 0; - if( rc==SQLITE_TOOBIG ){ - sqlite3Fts3ErrMsg(pzErr, - "FTS expression tree is too large (maximum depth %d)", - SQLITE_FTS3_MAX_EXPR_DEPTH - ); - rc = SQLITE_ERROR; - }else if( rc==SQLITE_ERROR ){ - sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z); - } - } - - return rc; -} - -/* -** Free a single node of an expression tree. -*/ -static void fts3FreeExprNode(Fts3Expr *p){ - assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 ); - sqlite3Fts3EvalPhraseCleanup(p->pPhrase); - sqlite3_free(p->aMI); - sqlite3_free(p); -} - -/* -** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse(). -** -** This function would be simpler if it recursively called itself. But -** that would mean passing a sufficiently large expression to ExprParse() -** could cause a stack overflow. -*/ -SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){ - Fts3Expr *p; - assert( pDel==0 || pDel->pParent==0 ); - for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){ - assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft ); - } - while( p ){ - Fts3Expr *pParent = p->pParent; - fts3FreeExprNode(p); - if( pParent && p==pParent->pLeft && pParent->pRight ){ - p = pParent->pRight; - while( p && (p->pLeft || p->pRight) ){ - assert( p==p->pParent->pRight || p==p->pParent->pLeft ); - p = (p->pLeft ? p->pLeft : p->pRight); - } - }else{ - p = pParent; - } - } -} - -/**************************************************************************** -***************************************************************************** -** Everything after this point is just test code. -*/ - -#ifdef SQLITE_TEST - -/* #include */ - -/* -** Return a pointer to a buffer containing a text representation of the -** expression passed as the first argument. The buffer is obtained from -** sqlite3_malloc(). It is the responsibility of the caller to use -** sqlite3_free() to release the memory. If an OOM condition is encountered, -** NULL is returned. -** -** If the second argument is not NULL, then its contents are prepended to -** the returned expression text and then freed using sqlite3_free(). -*/ -static char *exprToString(Fts3Expr *pExpr, char *zBuf){ - if( pExpr==0 ){ - return sqlite3_mprintf(""); - } - switch( pExpr->eType ){ - case FTSQUERY_PHRASE: { - Fts3Phrase *pPhrase = pExpr->pPhrase; - int i; - zBuf = sqlite3_mprintf( - "%zPHRASE %d 0", zBuf, pPhrase->iColumn); - for(i=0; zBuf && inToken; i++){ - zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, - pPhrase->aToken[i].n, pPhrase->aToken[i].z, - (pPhrase->aToken[i].isPrefix?"+":"") - ); - } - return zBuf; - } - - case FTSQUERY_NEAR: - zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear); - break; - case FTSQUERY_NOT: - zBuf = sqlite3_mprintf("%zNOT ", zBuf); - break; - case FTSQUERY_AND: - zBuf = sqlite3_mprintf("%zAND ", zBuf); - break; - case FTSQUERY_OR: - zBuf = sqlite3_mprintf("%zOR ", zBuf); - break; - } - - if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf); - if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf); - if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf); - - if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf); - if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf); - - return zBuf; -} - -/* -** This is the implementation of a scalar SQL function used to test the -** expression parser. It should be called as follows: -** -** fts3_exprtest(, , , ...); -** -** The first argument, , is the name of the fts3 tokenizer used -** to parse the query expression (see README.tokenizers). The second argument -** is the query expression to parse. Each subsequent argument is the name -** of a column of the fts3 table that the query expression may refer to. -** For example: -** -** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2'); -*/ -static void fts3ExprTestCommon( - int bRebalance, - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - sqlite3_tokenizer *pTokenizer = 0; - int rc; - char **azCol = 0; - const char *zExpr; - int nExpr; - int nCol; - int ii; - Fts3Expr *pExpr; - char *zBuf = 0; - Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context); - const char *zTokenizer = 0; - char *zErr = 0; - - if( argc<3 ){ - sqlite3_result_error(context, - "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1 - ); - return; - } - - zTokenizer = (const char*)sqlite3_value_text(argv[0]); - rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_error(context, zErr, -1); - } - sqlite3_free(zErr); - return; - } - - zExpr = (const char *)sqlite3_value_text(argv[1]); - nExpr = sqlite3_value_bytes(argv[1]); - nCol = argc-2; - azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *)); - if( !azCol ){ - sqlite3_result_error_nomem(context); - goto exprtest_out; - } - for(ii=0; iipModule->xDestroy(pTokenizer); - } - sqlite3_free(azCol); -} - -static void fts3ExprTest( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fts3ExprTestCommon(0, context, argc, argv); -} -static void fts3ExprTestRebalance( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - fts3ExprTestCommon(1, context, argc, argv); -} - -/* -** Register the query expression parser test function fts3_exprtest() -** with database connection db. -*/ -SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){ - int rc = sqlite3_create_function( - db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0 - ); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", - -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0 - ); - } - return rc; -} - -#endif -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_expr.c *******************************************/ -/************** Begin file fts3_hash.c ***************************************/ -/* -** 2001 September 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This is the implementation of generic hash-tables used in SQLite. -** We've modified it slightly to serve as a standalone hash table -** implementation for the full-text indexing module. -*/ - -/* -** The code in this file is only compiled if: -** -** * The FTS3 module is being built as an extension -** (in which case SQLITE_CORE is not defined), or -** -** * The FTS3 module is being built into the core of -** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ -/* #include */ - -/* #include "fts3_hash.h" */ - -/* -** Malloc and Free functions -*/ -static void *fts3HashMalloc(sqlite3_int64 n){ - void *p = sqlite3_malloc64(n); - if( p ){ - memset(p, 0, n); - } - return p; -} -static void fts3HashFree(void *p){ - sqlite3_free(p); -} - -/* 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. -** keyClass is one of the constants -** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass -** determines what kind of key the hash table will use. "copyKey" is -** true if the hash table should make its own private copy of keys and -** false if it should just use the supplied pointer. -*/ -SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){ - assert( pNew!=0 ); - assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); - pNew->keyClass = keyClass; - pNew->copyKey = copyKey; - 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 sqlite3Fts3HashClear(Fts3Hash *pH){ - Fts3HashElem *elem; /* For looping over all elements of the table */ - - assert( pH!=0 ); - elem = pH->first; - pH->first = 0; - fts3HashFree(pH->ht); - pH->ht = 0; - pH->htsize = 0; - while( elem ){ - Fts3HashElem *next_elem = elem->next; - if( pH->copyKey && elem->pKey ){ - fts3HashFree(elem->pKey); - } - fts3HashFree(elem); - elem = next_elem; - } - pH->count = 0; -} - -/* -** Hash and comparison functions when the mode is FTS3_HASH_STRING -*/ -static int fts3StrHash(const void *pKey, int nKey){ - const char *z = (const char *)pKey; - unsigned h = 0; - if( nKey<=0 ) nKey = (int) strlen(z); - while( nKey > 0 ){ - h = (h<<3) ^ h ^ *z++; - nKey--; - } - return (int)(h & 0x7fffffff); -} -static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){ - if( n1!=n2 ) return 1; - return strncmp((const char*)pKey1,(const char*)pKey2,n1); -} - -/* -** Hash and comparison functions when the mode is FTS3_HASH_BINARY -*/ -static int fts3BinHash(const void *pKey, int nKey){ - int h = 0; - const char *z = (const char *)pKey; - while( nKey-- > 0 ){ - h = (h<<3) ^ h ^ *(z++); - } - return h & 0x7fffffff; -} -static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){ - if( n1!=n2 ) return 1; - return memcmp(pKey1,pKey2,n1); -} - -/* -** Return a pointer to the appropriate hash function given the key class. -** -** The C syntax in this function definition may be unfamilar to some -** programmers, so we provide the following additional explanation: -** -** The name of the function is "ftsHashFunction". The function takes a -** single parameter "keyClass". The return value of ftsHashFunction() -** is a pointer to another function. Specifically, the return value -** of ftsHashFunction() is a pointer to a function that takes two parameters -** with types "const void*" and "int" and returns an "int". -*/ -static int (*ftsHashFunction(int keyClass))(const void*,int){ - if( keyClass==FTS3_HASH_STRING ){ - return &fts3StrHash; - }else{ - assert( keyClass==FTS3_HASH_BINARY ); - return &fts3BinHash; - } -} - -/* -** Return a pointer to the appropriate hash function given the key class. -** -** For help in interpreted the obscure C code in the function definition, -** see the header comment on the previous function. -*/ -static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){ - if( keyClass==FTS3_HASH_STRING ){ - return &fts3StrCompare; - }else{ - assert( keyClass==FTS3_HASH_BINARY ); - return &fts3BinCompare; - } -} - -/* Link an element into the hash table -*/ -static void fts3HashInsertElement( - Fts3Hash *pH, /* The complete hash table */ - struct _fts3ht *pEntry, /* The entry into which pNew is inserted */ - Fts3HashElem *pNew /* The element to be inserted */ -){ - Fts3HashElem *pHead; /* First element already in pEntry */ - pHead = pEntry->chain; - 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; - } - pEntry->count++; - pEntry->chain = pNew; -} - - -/* Resize the hash table so that it cantains "new_size" buckets. -** "new_size" must be a power of 2. The hash table might fail -** to resize if sqliteMalloc() fails. -** -** Return non-zero if a memory allocation error occurs. -*/ -static int fts3Rehash(Fts3Hash *pH, int new_size){ - struct _fts3ht *new_ht; /* The new hash table */ - Fts3HashElem *elem, *next_elem; /* For looping over existing elements */ - int (*xHash)(const void*,int); /* The hash function */ - - assert( (new_size & (new_size-1))==0 ); - new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) ); - if( new_ht==0 ) return 1; - fts3HashFree(pH->ht); - pH->ht = new_ht; - pH->htsize = new_size; - xHash = ftsHashFunction(pH->keyClass); - for(elem=pH->first, pH->first=0; elem; elem = next_elem){ - int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1); - next_elem = elem->next; - fts3HashInsertElement(pH, &new_ht[h], elem); - } - return 0; -} - -/* This function (for internal use only) locates an element in an -** hash table that matches the given key. The hash for this key has -** already been computed and is passed as the 4th parameter. -*/ -static Fts3HashElem *fts3FindElementByHash( - const Fts3Hash *pH, /* The pH to be searched */ - const void *pKey, /* The key we are searching for */ - int nKey, - int h /* The hash for this key. */ -){ - Fts3HashElem *elem; /* Used to loop thru the element list */ - int count; /* Number of elements left to test */ - int (*xCompare)(const void*,int,const void*,int); /* comparison function */ - - if( pH->ht ){ - struct _fts3ht *pEntry = &pH->ht[h]; - elem = pEntry->chain; - count = pEntry->count; - xCompare = ftsCompareFunction(pH->keyClass); - while( count-- && elem ){ - if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ - return elem; - } - elem = elem->next; - } - } - return 0; -} - -/* Remove a single entry from the hash table given a pointer to that -** element and a hash on the element's key. -*/ -static void fts3RemoveElementByHash( - Fts3Hash *pH, /* The pH containing "elem" */ - Fts3HashElem* elem, /* The element to be removed from the pH */ - int h /* Hash value for the element */ -){ - struct _fts3ht *pEntry; - if( elem->prev ){ - elem->prev->next = elem->next; - }else{ - pH->first = elem->next; - } - if( elem->next ){ - elem->next->prev = elem->prev; - } - pEntry = &pH->ht[h]; - if( pEntry->chain==elem ){ - pEntry->chain = elem->next; - } - pEntry->count--; - if( pEntry->count<=0 ){ - pEntry->chain = 0; - } - if( pH->copyKey && elem->pKey ){ - fts3HashFree(elem->pKey); - } - fts3HashFree( elem ); - pH->count--; - if( pH->count<=0 ){ - assert( pH->first==0 ); - assert( pH->count==0 ); - fts3HashClear(pH); - } -} - -SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem( - const Fts3Hash *pH, - const void *pKey, - int nKey -){ - int h; /* A hash on key */ - int (*xHash)(const void*,int); /* The hash function */ - - if( pH==0 || pH->ht==0 ) return 0; - xHash = ftsHashFunction(pH->keyClass); - assert( xHash!=0 ); - h = (*xHash)(pKey,nKey); - assert( (pH->htsize & (pH->htsize-1))==0 ); - return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1)); -} - -/* -** Attempt to locate an element of the hash table pH with a key -** that matches pKey,nKey. Return the data for this element if it is -** found, or NULL if there is no match. -*/ -SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){ - Fts3HashElem *pElem; /* The element that matches key (if any) */ - - pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey); - return pElem ? pElem->data : 0; -} - -/* Insert an element into the hash table pH. The key is pKey,nKey -** and the data is "data". -** -** If no element exists with a matching key, then a new -** element is created. A copy of the key is made if the copyKey -** flag is set. 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 *sqlite3Fts3HashInsert( - Fts3Hash *pH, /* The hash table to insert into */ - const void *pKey, /* The key */ - int nKey, /* Number of bytes in the key */ - void *data /* The data */ -){ - int hraw; /* Raw hash value of the key */ - int h; /* the hash of the key modulo hash table size */ - Fts3HashElem *elem; /* Used to loop thru the element list */ - Fts3HashElem *new_elem; /* New element added to the pH */ - int (*xHash)(const void*,int); /* The hash function */ - - assert( pH!=0 ); - xHash = ftsHashFunction(pH->keyClass); - assert( xHash!=0 ); - hraw = (*xHash)(pKey, nKey); - assert( (pH->htsize & (pH->htsize-1))==0 ); - h = hraw & (pH->htsize-1); - elem = fts3FindElementByHash(pH,pKey,nKey,h); - if( elem ){ - void *old_data = elem->data; - if( data==0 ){ - fts3RemoveElementByHash(pH,elem,h); - }else{ - elem->data = data; - } - return old_data; - } - if( data==0 ) return 0; - if( (pH->htsize==0 && fts3Rehash(pH,8)) - || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2)) - ){ - pH->count = 0; - return data; - } - assert( pH->htsize>0 ); - new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) ); - if( new_elem==0 ) return data; - if( pH->copyKey && pKey!=0 ){ - new_elem->pKey = fts3HashMalloc( nKey ); - if( new_elem->pKey==0 ){ - fts3HashFree(new_elem); - return data; - } - memcpy((void*)new_elem->pKey, pKey, nKey); - }else{ - new_elem->pKey = (void*)pKey; - } - new_elem->nKey = nKey; - pH->count++; - assert( pH->htsize>0 ); - assert( (pH->htsize & (pH->htsize-1))==0 ); - h = hraw & (pH->htsize-1); - fts3HashInsertElement(pH, &pH->ht[h], new_elem); - new_elem->data = data; - return 0; -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_hash.c *******************************************/ -/************** Begin file fts3_porter.c *************************************/ -/* -** 2006 September 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. -** -************************************************************************* -** Implementation of the full-text-search tokenizer that implements -** a Porter stemmer. -*/ - -/* -** The code in this file is only compiled if: -** -** * The FTS3 module is being built as an extension -** (in which case SQLITE_CORE is not defined), or -** -** * The FTS3 module is being built into the core of -** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ -/* #include */ -/* #include */ - -/* #include "fts3_tokenizer.h" */ - -/* -** Class derived from sqlite3_tokenizer -*/ -typedef struct porter_tokenizer { - sqlite3_tokenizer base; /* Base class */ -} porter_tokenizer; - -/* -** Class derived from sqlite3_tokenizer_cursor -*/ -typedef struct porter_tokenizer_cursor { - sqlite3_tokenizer_cursor base; - const char *zInput; /* input we are tokenizing */ - int nInput; /* size of the input */ - int iOffset; /* current position in zInput */ - int iToken; /* index of next token to be returned */ - char *zToken; /* storage for current token */ - int nAllocated; /* space allocated to zToken buffer */ -} porter_tokenizer_cursor; - - -/* -** Create a new tokenizer instance. -*/ -static int porterCreate( - int argc, const char * const *argv, - sqlite3_tokenizer **ppTokenizer -){ - porter_tokenizer *t; - - UNUSED_PARAMETER(argc); - UNUSED_PARAMETER(argv); - - t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t)); - if( t==NULL ) return SQLITE_NOMEM; - memset(t, 0, sizeof(*t)); - *ppTokenizer = &t->base; - return SQLITE_OK; -} - -/* -** Destroy a tokenizer -*/ -static int porterDestroy(sqlite3_tokenizer *pTokenizer){ - sqlite3_free(pTokenizer); - return SQLITE_OK; -} - -/* -** Prepare to begin tokenizing a particular string. The input -** string to be tokenized is zInput[0..nInput-1]. A cursor -** used to incrementally tokenize this string is returned in -** *ppCursor. -*/ -static int porterOpen( - sqlite3_tokenizer *pTokenizer, /* The tokenizer */ - const char *zInput, int nInput, /* String to be tokenized */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ -){ - porter_tokenizer_cursor *c; - - UNUSED_PARAMETER(pTokenizer); - - c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); - if( c==NULL ) return SQLITE_NOMEM; - - c->zInput = zInput; - if( zInput==0 ){ - c->nInput = 0; - }else if( nInput<0 ){ - c->nInput = (int)strlen(zInput); - }else{ - c->nInput = nInput; - } - c->iOffset = 0; /* start tokenizing at the beginning */ - c->iToken = 0; - c->zToken = NULL; /* no space allocated, yet. */ - c->nAllocated = 0; - - *ppCursor = &c->base; - return SQLITE_OK; -} - -/* -** Close a tokenization cursor previously opened by a call to -** porterOpen() above. -*/ -static int porterClose(sqlite3_tokenizer_cursor *pCursor){ - porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; - sqlite3_free(c->zToken); - sqlite3_free(c); - return SQLITE_OK; -} -/* -** Vowel or consonant -*/ -static const char cType[] = { - 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, - 1, 1, 1, 2, 1 -}; - -/* -** isConsonant() and isVowel() determine if their first character in -** the string they point to is a consonant or a vowel, according -** to Porter ruls. -** -** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'. -** 'Y' is a consonant unless it follows another consonant, -** in which case it is a vowel. -** -** In these routine, the letters are in reverse order. So the 'y' rule -** is that 'y' is a consonant unless it is followed by another -** consonent. -*/ -static int isVowel(const char*); -static int isConsonant(const char *z){ - int j; - char x = *z; - if( x==0 ) return 0; - assert( x>='a' && x<='z' ); - j = cType[x-'a']; - if( j<2 ) return j; - return z[1]==0 || isVowel(z + 1); -} -static int isVowel(const char *z){ - int j; - char x = *z; - if( x==0 ) return 0; - assert( x>='a' && x<='z' ); - j = cType[x-'a']; - if( j<2 ) return 1-j; - return isConsonant(z + 1); -} - -/* -** Let any sequence of one or more vowels be represented by V and let -** C be sequence of one or more consonants. Then every word can be -** represented as: -** -** [C] (VC){m} [V] -** -** In prose: A word is an optional consonant followed by zero or -** vowel-consonant pairs followed by an optional vowel. "m" is the -** number of vowel consonant pairs. This routine computes the value -** of m for the first i bytes of a word. -** -** Return true if the m-value for z is 1 or more. In other words, -** return true if z contains at least one vowel that is followed -** by a consonant. -** -** In this routine z[] is in reverse order. So we are really looking -** for an instance of a consonant followed by a vowel. -*/ -static int m_gt_0(const char *z){ - while( isVowel(z) ){ z++; } - if( *z==0 ) return 0; - while( isConsonant(z) ){ z++; } - return *z!=0; -} - -/* Like mgt0 above except we are looking for a value of m which is -** exactly 1 -*/ -static int m_eq_1(const char *z){ - while( isVowel(z) ){ z++; } - if( *z==0 ) return 0; - while( isConsonant(z) ){ z++; } - if( *z==0 ) return 0; - while( isVowel(z) ){ z++; } - if( *z==0 ) return 1; - while( isConsonant(z) ){ z++; } - return *z==0; -} - -/* Like mgt0 above except we are looking for a value of m>1 instead -** or m>0 -*/ -static int m_gt_1(const char *z){ - while( isVowel(z) ){ z++; } - if( *z==0 ) return 0; - while( isConsonant(z) ){ z++; } - if( *z==0 ) return 0; - while( isVowel(z) ){ z++; } - if( *z==0 ) return 0; - while( isConsonant(z) ){ z++; } - return *z!=0; -} - -/* -** Return TRUE if there is a vowel anywhere within z[0..n-1] -*/ -static int hasVowel(const char *z){ - while( isConsonant(z) ){ z++; } - return *z!=0; -} - -/* -** Return TRUE if the word ends in a double consonant. -** -** The text is reversed here. So we are really looking at -** the first two characters of z[]. -*/ -static int doubleConsonant(const char *z){ - return isConsonant(z) && z[0]==z[1]; -} - -/* -** Return TRUE if the word ends with three letters which -** are consonant-vowel-consonent and where the final consonant -** is not 'w', 'x', or 'y'. -** -** The word is reversed here. So we are really checking the -** first three letters and the first one cannot be in [wxy]. -*/ -static int star_oh(const char *z){ - return - isConsonant(z) && - z[0]!='w' && z[0]!='x' && z[0]!='y' && - isVowel(z+1) && - isConsonant(z+2); -} - -/* -** If the word ends with zFrom and xCond() is true for the stem -** of the word that preceeds the zFrom ending, then change the -** ending to zTo. -** -** The input word *pz and zFrom are both in reverse order. zTo -** is in normal order. -** -** Return TRUE if zFrom matches. Return FALSE if zFrom does not -** match. Not that TRUE is returned even if xCond() fails and -** no substitution occurs. -*/ -static int stem( - char **pz, /* The word being stemmed (Reversed) */ - const char *zFrom, /* If the ending matches this... (Reversed) */ - const char *zTo, /* ... change the ending to this (not reversed) */ - int (*xCond)(const char*) /* Condition that must be true */ -){ - char *z = *pz; - while( *zFrom && *zFrom==*z ){ z++; zFrom++; } - if( *zFrom!=0 ) return 0; - if( xCond && !xCond(z) ) return 1; - while( *zTo ){ - *(--z) = *(zTo++); - } - *pz = z; - return 1; -} - -/* -** This is the fallback stemmer used when the porter stemmer is -** inappropriate. The input word is copied into the output with -** US-ASCII case folding. If the input word is too long (more -** than 20 bytes if it contains no digits or more than 6 bytes if -** it contains digits) then word is truncated to 20 or 6 bytes -** by taking 10 or 3 bytes from the beginning and end. -*/ -static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){ - int i, mx, j; - int hasDigit = 0; - for(i=0; i='A' && c<='Z' ){ - zOut[i] = c - 'A' + 'a'; - }else{ - if( c>='0' && c<='9' ) hasDigit = 1; - zOut[i] = c; - } - } - mx = hasDigit ? 3 : 10; - if( nIn>mx*2 ){ - for(j=mx, i=nIn-mx; i=(int)sizeof(zReverse)-7 ){ - /* The word is too big or too small for the porter stemmer. - ** Fallback to the copy stemmer */ - copy_stemmer(zIn, nIn, zOut, pnOut); - return; - } - for(i=0, j=sizeof(zReverse)-6; i='A' && c<='Z' ){ - zReverse[j] = c + 'a' - 'A'; - }else if( c>='a' && c<='z' ){ - zReverse[j] = c; - }else{ - /* The use of a character not in [a-zA-Z] means that we fallback - ** to the copy stemmer */ - copy_stemmer(zIn, nIn, zOut, pnOut); - return; - } - } - memset(&zReverse[sizeof(zReverse)-5], 0, 5); - z = &zReverse[j+1]; - - - /* Step 1a */ - if( z[0]=='s' ){ - if( - !stem(&z, "sess", "ss", 0) && - !stem(&z, "sei", "i", 0) && - !stem(&z, "ss", "ss", 0) - ){ - z++; - } - } - - /* Step 1b */ - z2 = z; - if( stem(&z, "dee", "ee", m_gt_0) ){ - /* Do nothing. The work was all in the test */ - }else if( - (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel)) - && z!=z2 - ){ - if( stem(&z, "ta", "ate", 0) || - stem(&z, "lb", "ble", 0) || - stem(&z, "zi", "ize", 0) ){ - /* Do nothing. The work was all in the test */ - }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){ - z++; - }else if( m_eq_1(z) && star_oh(z) ){ - *(--z) = 'e'; - } - } - - /* Step 1c */ - if( z[0]=='y' && hasVowel(z+1) ){ - z[0] = 'i'; - } - - /* Step 2 */ - switch( z[1] ){ - case 'a': - if( !stem(&z, "lanoita", "ate", m_gt_0) ){ - stem(&z, "lanoit", "tion", m_gt_0); - } - break; - case 'c': - if( !stem(&z, "icne", "ence", m_gt_0) ){ - stem(&z, "icna", "ance", m_gt_0); - } - break; - case 'e': - stem(&z, "rezi", "ize", m_gt_0); - break; - case 'g': - stem(&z, "igol", "log", m_gt_0); - break; - case 'l': - if( !stem(&z, "ilb", "ble", m_gt_0) - && !stem(&z, "illa", "al", m_gt_0) - && !stem(&z, "iltne", "ent", m_gt_0) - && !stem(&z, "ile", "e", m_gt_0) - ){ - stem(&z, "ilsuo", "ous", m_gt_0); - } - break; - case 'o': - if( !stem(&z, "noitazi", "ize", m_gt_0) - && !stem(&z, "noita", "ate", m_gt_0) - ){ - stem(&z, "rota", "ate", m_gt_0); - } - break; - case 's': - if( !stem(&z, "msila", "al", m_gt_0) - && !stem(&z, "ssenevi", "ive", m_gt_0) - && !stem(&z, "ssenluf", "ful", m_gt_0) - ){ - stem(&z, "ssensuo", "ous", m_gt_0); - } - break; - case 't': - if( !stem(&z, "itila", "al", m_gt_0) - && !stem(&z, "itivi", "ive", m_gt_0) - ){ - stem(&z, "itilib", "ble", m_gt_0); - } - break; - } - - /* Step 3 */ - switch( z[0] ){ - case 'e': - if( !stem(&z, "etaci", "ic", m_gt_0) - && !stem(&z, "evita", "", m_gt_0) - ){ - stem(&z, "ezila", "al", m_gt_0); - } - break; - case 'i': - stem(&z, "itici", "ic", m_gt_0); - break; - case 'l': - if( !stem(&z, "laci", "ic", m_gt_0) ){ - stem(&z, "luf", "", m_gt_0); - } - break; - case 's': - stem(&z, "ssen", "", m_gt_0); - break; - } - - /* Step 4 */ - switch( z[1] ){ - case 'a': - if( z[0]=='l' && m_gt_1(z+2) ){ - z += 2; - } - break; - case 'c': - if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){ - z += 4; - } - break; - case 'e': - if( z[0]=='r' && m_gt_1(z+2) ){ - z += 2; - } - break; - case 'i': - if( z[0]=='c' && m_gt_1(z+2) ){ - z += 2; - } - break; - case 'l': - if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){ - z += 4; - } - break; - case 'n': - if( z[0]=='t' ){ - if( z[2]=='a' ){ - if( m_gt_1(z+3) ){ - z += 3; - } - }else if( z[2]=='e' ){ - if( !stem(&z, "tneme", "", m_gt_1) - && !stem(&z, "tnem", "", m_gt_1) - ){ - stem(&z, "tne", "", m_gt_1); - } - } - } - break; - case 'o': - if( z[0]=='u' ){ - if( m_gt_1(z+2) ){ - z += 2; - } - }else if( z[3]=='s' || z[3]=='t' ){ - stem(&z, "noi", "", m_gt_1); - } - break; - case 's': - if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){ - z += 3; - } - break; - case 't': - if( !stem(&z, "eta", "", m_gt_1) ){ - stem(&z, "iti", "", m_gt_1); - } - break; - case 'u': - if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){ - z += 3; - } - break; - case 'v': - case 'z': - if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){ - z += 3; - } - break; - } - - /* Step 5a */ - if( z[0]=='e' ){ - if( m_gt_1(z+1) ){ - z++; - }else if( m_eq_1(z+1) && !star_oh(z+1) ){ - z++; - } - } - - /* Step 5b */ - if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){ - z++; - } - - /* z[] is now the stemmed word in reverse order. Flip it back - ** around into forward order and return. - */ - *pnOut = i = (int)strlen(z); - zOut[i] = 0; - while( *z ){ - zOut[--i] = *(z++); - } -} - -/* -** Characters that can be part of a token. We assume any character -** whose value is greater than 0x80 (any UTF character) can be -** part of a token. In other words, delimiters all must have -** values of 0x7f or lower. -*/ -static const char porterIdChar[] = { -/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ -}; -#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30])) - -/* -** Extract the next token from a tokenization cursor. The cursor must -** have been opened by a prior call to porterOpen(). -*/ -static int porterNext( - sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */ - const char **pzToken, /* OUT: *pzToken is the token text */ - int *pnBytes, /* OUT: Number of bytes in token */ - int *piStartOffset, /* OUT: Starting offset of token */ - int *piEndOffset, /* OUT: Ending offset of token */ - int *piPosition /* OUT: Position integer of token */ -){ - porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor; - const char *z = c->zInput; - - while( c->iOffsetnInput ){ - int iStartOffset, ch; - - /* Scan past delimiter characters */ - while( c->iOffsetnInput && isDelim(z[c->iOffset]) ){ - c->iOffset++; - } - - /* Count non-delimiter characters. */ - iStartOffset = c->iOffset; - while( c->iOffsetnInput && !isDelim(z[c->iOffset]) ){ - c->iOffset++; - } - - if( c->iOffset>iStartOffset ){ - int n = c->iOffset-iStartOffset; - if( n>c->nAllocated ){ - char *pNew; - c->nAllocated = n+20; - pNew = sqlite3_realloc(c->zToken, c->nAllocated); - if( !pNew ) return SQLITE_NOMEM; - c->zToken = pNew; - } - porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); - *pzToken = c->zToken; - *piStartOffset = iStartOffset; - *piEndOffset = c->iOffset; - *piPosition = c->iToken++; - return SQLITE_OK; - } - } - return SQLITE_DONE; -} - -/* -** The set of routines that implement the porter-stemmer tokenizer -*/ -static const sqlite3_tokenizer_module porterTokenizerModule = { - 0, - porterCreate, - porterDestroy, - porterOpen, - porterClose, - porterNext, - 0 -}; - -/* -** Allocate a new porter tokenizer. Return a pointer to the new -** tokenizer in *ppModule -*/ -SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( - sqlite3_tokenizer_module const**ppModule -){ - *ppModule = &porterTokenizerModule; -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_porter.c *****************************************/ -/************** Begin file fts3_tokenizer.c **********************************/ -/* -** 2007 June 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 part of an SQLite module implementing full-text search. -** This particular file implements the generic tokenizer interface. -*/ - -/* -** The code in this file is only compiled if: -** -** * The FTS3 module is being built as an extension -** (in which case SQLITE_CORE is not defined), or -** -** * The FTS3 module is being built into the core of -** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ - -/* -** Return true if the two-argument version of fts3_tokenizer() -** has been activated via a prior call to sqlite3_db_config(db, -** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0); -*/ -static int fts3TokenizerEnabled(sqlite3_context *context){ - sqlite3 *db = sqlite3_context_db_handle(context); - int isEnabled = 0; - sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled); - return isEnabled; -} - -/* -** Implementation of the SQL scalar function for accessing the underlying -** hash table. This function may be called as follows: -** -** SELECT (); -** SELECT (, ); -** -** where is the name passed as the second argument -** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer'). -** -** If the argument is specified, it must be a blob value -** containing a pointer to be stored as the hash data corresponding -** to the string . If is not specified, then -** the string must already exist in the has table. Otherwise, -** an error is returned. -** -** Whether or not the argument is specified, the value returned -** is a blob containing the pointer stored as the hash data corresponding -** to string (after the hash-table is updated, if applicable). -*/ -static void fts3TokenizerFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Fts3Hash *pHash; - void *pPtr = 0; - const unsigned char *zName; - int nName; - - assert( argc==1 || argc==2 ); - - pHash = (Fts3Hash *)sqlite3_user_data(context); - - zName = sqlite3_value_text(argv[0]); - nName = sqlite3_value_bytes(argv[0])+1; - - if( argc==2 ){ - if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[1]) ){ - void *pOld; - int n = sqlite3_value_bytes(argv[1]); - if( zName==0 || n!=sizeof(pPtr) ){ - sqlite3_result_error(context, "argument type mismatch", -1); - return; - } - pPtr = *(void **)sqlite3_value_blob(argv[1]); - pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr); - if( pOld==pPtr ){ - sqlite3_result_error(context, "out of memory", -1); - } - }else{ - sqlite3_result_error(context, "fts3tokenize disabled", -1); - return; - } - }else{ - if( zName ){ - pPtr = sqlite3Fts3HashFind(pHash, zName, nName); - } - if( !pPtr ){ - char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName); - sqlite3_result_error(context, zErr, -1); - sqlite3_free(zErr); - return; - } - } - if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[0]) ){ - sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); - } -} - -SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){ - static const char isFtsIdChar[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ - 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ - }; - return (c&0x80 || isFtsIdChar[(int)(c)]); -} - -SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){ - const char *z1; - const char *z2 = 0; - - /* Find the start of the next token. */ - z1 = zStr; - while( z2==0 ){ - char c = *z1; - switch( c ){ - case '\0': return 0; /* No more tokens here */ - case '\'': - case '"': - case '`': { - z2 = z1; - while( *++z2 && (*z2!=c || *++z2==c) ); - break; - } - case '[': - z2 = &z1[1]; - while( *z2 && z2[0]!=']' ) z2++; - if( *z2 ) z2++; - break; - - default: - if( sqlite3Fts3IsIdChar(*z1) ){ - z2 = &z1[1]; - while( sqlite3Fts3IsIdChar(*z2) ) z2++; - }else{ - z1++; - } - } - } - - *pn = (int)(z2-z1); - return z1; -} - -SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( - Fts3Hash *pHash, /* Tokenizer hash table */ - const char *zArg, /* Tokenizer name */ - sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */ - char **pzErr /* OUT: Set to malloced error message */ -){ - int rc; - char *z = (char *)zArg; - int n = 0; - char *zCopy; - char *zEnd; /* Pointer to nul-term of zCopy */ - sqlite3_tokenizer_module *m; - - zCopy = sqlite3_mprintf("%s", zArg); - if( !zCopy ) return SQLITE_NOMEM; - zEnd = &zCopy[strlen(zCopy)]; - - z = (char *)sqlite3Fts3NextToken(zCopy, &n); - if( z==0 ){ - assert( n==0 ); - z = zCopy; - } - z[n] = '\0'; - sqlite3Fts3Dequote(z); - - m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1); - if( !m ){ - sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z); - rc = SQLITE_ERROR; - }else{ - char const **aArg = 0; - int iArg = 0; - z = &z[n+1]; - while( zxCreate(iArg, aArg, ppTok); - assert( rc!=SQLITE_OK || *ppTok ); - if( rc!=SQLITE_OK ){ - sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer"); - }else{ - (*ppTok)->pModule = m; - } - sqlite3_free((void *)aArg); - } - - sqlite3_free(zCopy); - return rc; -} - - -#ifdef SQLITE_TEST - -#if defined(INCLUDE_SQLITE_TCL_H) -# include "sqlite_tcl.h" -#else -# include "tcl.h" -#endif -/* #include */ - -/* -** Implementation of a special SQL scalar function for testing tokenizers -** designed to be used in concert with the Tcl testing framework. This -** function must be called with two or more arguments: -** -** SELECT (, ..., ); -** -** where is the name passed as the second argument -** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer') -** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test'). -** -** The return value is a string that may be interpreted as a Tcl -** list. For each token in the , three elements are -** added to the returned list. The first is the token position, the -** second is the token text (folded, stemmed, etc.) and the third is the -** substring of associated with the token. For example, -** using the built-in "simple" tokenizer: -** -** SELECT fts_tokenizer_test('simple', 'I don't see how'); -** -** will return the string: -** -** "{0 i I 1 dont don't 2 see see 3 how how}" -** -*/ -static void testFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Fts3Hash *pHash; - sqlite3_tokenizer_module *p; - sqlite3_tokenizer *pTokenizer = 0; - sqlite3_tokenizer_cursor *pCsr = 0; - - const char *zErr = 0; - - const char *zName; - int nName; - const char *zInput; - int nInput; - - const char *azArg[64]; - - const char *zToken; - int nToken = 0; - int iStart = 0; - int iEnd = 0; - int iPos = 0; - int i; - - Tcl_Obj *pRet; - - if( argc<2 ){ - sqlite3_result_error(context, "insufficient arguments", -1); - return; - } - - nName = sqlite3_value_bytes(argv[0]); - zName = (const char *)sqlite3_value_text(argv[0]); - nInput = sqlite3_value_bytes(argv[argc-1]); - zInput = (const char *)sqlite3_value_text(argv[argc-1]); - - pHash = (Fts3Hash *)sqlite3_user_data(context); - p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); - - if( !p ){ - char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName); - sqlite3_result_error(context, zErr2, -1); - sqlite3_free(zErr2); - return; - } - - pRet = Tcl_NewObj(); - Tcl_IncrRefCount(pRet); - - for(i=1; ixCreate(argc-2, azArg, &pTokenizer) ){ - zErr = "error in xCreate()"; - goto finish; - } - pTokenizer->pModule = p; - if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){ - zErr = "error in xOpen()"; - goto finish; - } - - while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){ - Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos)); - Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); - zToken = &zInput[iStart]; - nToken = iEnd-iStart; - Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken)); - } - - if( SQLITE_OK!=p->xClose(pCsr) ){ - zErr = "error in xClose()"; - goto finish; - } - if( SQLITE_OK!=p->xDestroy(pTokenizer) ){ - zErr = "error in xDestroy()"; - goto finish; - } - -finish: - if( zErr ){ - sqlite3_result_error(context, zErr, -1); - }else{ - sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT); - } - Tcl_DecrRefCount(pRet); -} - -static -int registerTokenizer( - sqlite3 *db, - char *zName, - const sqlite3_tokenizer_module *p -){ - int rc; - sqlite3_stmt *pStmt; - const char zSql[] = "SELECT fts3_tokenizer(?, ?)"; - - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - - sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); - sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC); - sqlite3_step(pStmt); - - return sqlite3_finalize(pStmt); -} - - -static -int queryTokenizer( - sqlite3 *db, - char *zName, - const sqlite3_tokenizer_module **pp -){ - int rc; - sqlite3_stmt *pStmt; - const char zSql[] = "SELECT fts3_tokenizer(?)"; - - *pp = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - - sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB - && sqlite3_column_bytes(pStmt, 0)==sizeof(*pp) - ){ - memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); - } - } - - return sqlite3_finalize(pStmt); -} - -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); - -/* -** Implementation of the scalar function fts3_tokenizer_internal_test(). -** This function is used for testing only, it is not included in the -** build unless SQLITE_TEST is defined. -** -** The purpose of this is to test that the fts3_tokenizer() function -** can be used as designed by the C-code in the queryTokenizer and -** registerTokenizer() functions above. These two functions are repeated -** in the README.tokenizer file as an example, so it is important to -** test them. -** -** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar -** function with no arguments. An assert() will fail if a problem is -** detected. i.e.: -** -** SELECT fts3_tokenizer_internal_test(); -** -*/ -static void intTestFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int rc; - const sqlite3_tokenizer_module *p1; - const sqlite3_tokenizer_module *p2; - sqlite3 *db = (sqlite3 *)sqlite3_user_data(context); - - UNUSED_PARAMETER(argc); - UNUSED_PARAMETER(argv); - - /* Test the query function */ - sqlite3Fts3SimpleTokenizerModule(&p1); - rc = queryTokenizer(db, "simple", &p2); - assert( rc==SQLITE_OK ); - assert( p1==p2 ); - rc = queryTokenizer(db, "nosuchtokenizer", &p2); - assert( rc==SQLITE_ERROR ); - assert( p2==0 ); - assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") ); - - /* Test the storage function */ - if( fts3TokenizerEnabled(context) ){ - rc = registerTokenizer(db, "nosuchtokenizer", p1); - assert( rc==SQLITE_OK ); - rc = queryTokenizer(db, "nosuchtokenizer", &p2); - assert( rc==SQLITE_OK ); - assert( p2==p1 ); - } - - sqlite3_result_text(context, "ok", -1, SQLITE_STATIC); -} - -#endif - -/* -** Set up SQL objects in database db used to access the contents of -** the hash table pointed to by argument pHash. The hash table must -** been initialized to use string keys, and to take a private copy -** of the key when a value is inserted. i.e. by a call similar to: -** -** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); -** -** This function adds a scalar function (see header comment above -** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is -** defined at compilation time, a temporary virtual table (see header -** comment above struct HashTableVtab) to the database schema. Both -** provide read/write access to the contents of *pHash. -** -** The third argument to this function, zName, is used as the name -** of both the scalar and, if created, the virtual table. -*/ -SQLITE_PRIVATE int sqlite3Fts3InitHashTable( - sqlite3 *db, - Fts3Hash *pHash, - const char *zName -){ - int rc = SQLITE_OK; - void *p = (void *)pHash; - const int any = SQLITE_UTF8|SQLITE_DIRECTONLY; - -#ifdef SQLITE_TEST - char *zTest = 0; - char *zTest2 = 0; - void *pdb = (void *)db; - zTest = sqlite3_mprintf("%s_test", zName); - zTest2 = sqlite3_mprintf("%s_internal_test", zName); - if( !zTest || !zTest2 ){ - rc = SQLITE_NOMEM; - } -#endif - - if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0); - } - if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0); - } -#ifdef SQLITE_TEST - if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0); - } - if( SQLITE_OK==rc ){ - rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0); - } -#endif - -#ifdef SQLITE_TEST - sqlite3_free(zTest); - sqlite3_free(zTest2); -#endif - - return rc; -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_tokenizer.c **************************************/ -/************** Begin file fts3_tokenizer1.c *********************************/ -/* -** 2006 Oct 10 -** -** 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. -** -****************************************************************************** -** -** Implementation of the "simple" full-text-search tokenizer. -*/ - -/* -** The code in this file is only compiled if: -** -** * The FTS3 module is being built as an extension -** (in which case SQLITE_CORE is not defined), or -** -** * The FTS3 module is being built into the core of -** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ -/* #include */ -/* #include */ - -/* #include "fts3_tokenizer.h" */ - -typedef struct simple_tokenizer { - sqlite3_tokenizer base; - char delim[128]; /* flag ASCII delimiters */ -} simple_tokenizer; - -typedef struct simple_tokenizer_cursor { - sqlite3_tokenizer_cursor base; - const char *pInput; /* input we are tokenizing */ - int nBytes; /* size of the input */ - int iOffset; /* current position in pInput */ - int iToken; /* index of next token to be returned */ - char *pToken; /* storage for current token */ - int nTokenAllocated; /* space allocated to zToken buffer */ -} simple_tokenizer_cursor; - - -static int simpleDelim(simple_tokenizer *t, unsigned char c){ - return c<0x80 && t->delim[c]; -} -static int fts3_isalnum(int x){ - return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z'); -} - -/* -** Create a new tokenizer instance. -*/ -static int simpleCreate( - int argc, const char * const *argv, - sqlite3_tokenizer **ppTokenizer -){ - simple_tokenizer *t; - - t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t)); - if( t==NULL ) return SQLITE_NOMEM; - memset(t, 0, sizeof(*t)); - - /* TODO(shess) Delimiters need to remain the same from run to run, - ** else we need to reindex. One solution would be a meta-table to - ** track such information in the database, then we'd only want this - ** information on the initial create. - */ - if( argc>1 ){ - int i, n = (int)strlen(argv[1]); - for(i=0; i=0x80 ){ - sqlite3_free(t); - return SQLITE_ERROR; - } - t->delim[ch] = 1; - } - } else { - /* Mark non-alphanumeric ASCII characters as delimiters */ - int i; - for(i=1; i<0x80; i++){ - t->delim[i] = !fts3_isalnum(i) ? -1 : 0; - } - } - - *ppTokenizer = &t->base; - return SQLITE_OK; -} - -/* -** Destroy a tokenizer -*/ -static int simpleDestroy(sqlite3_tokenizer *pTokenizer){ - sqlite3_free(pTokenizer); - return SQLITE_OK; -} - -/* -** Prepare to begin tokenizing a particular string. The input -** string to be tokenized is pInput[0..nBytes-1]. A cursor -** used to incrementally tokenize this string is returned in -** *ppCursor. -*/ -static int simpleOpen( - sqlite3_tokenizer *pTokenizer, /* The tokenizer */ - const char *pInput, int nBytes, /* String to be tokenized */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ -){ - simple_tokenizer_cursor *c; - - UNUSED_PARAMETER(pTokenizer); - - c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); - if( c==NULL ) return SQLITE_NOMEM; - - c->pInput = pInput; - if( pInput==0 ){ - c->nBytes = 0; - }else if( nBytes<0 ){ - c->nBytes = (int)strlen(pInput); - }else{ - c->nBytes = nBytes; - } - c->iOffset = 0; /* start tokenizing at the beginning */ - c->iToken = 0; - c->pToken = NULL; /* no space allocated, yet. */ - c->nTokenAllocated = 0; - - *ppCursor = &c->base; - return SQLITE_OK; -} - -/* -** Close a tokenization cursor previously opened by a call to -** simpleOpen() above. -*/ -static int simpleClose(sqlite3_tokenizer_cursor *pCursor){ - simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; - sqlite3_free(c->pToken); - sqlite3_free(c); - return SQLITE_OK; -} - -/* -** Extract the next token from a tokenization cursor. The cursor must -** have been opened by a prior call to simpleOpen(). -*/ -static int simpleNext( - sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ - const char **ppToken, /* OUT: *ppToken is the token text */ - int *pnBytes, /* OUT: Number of bytes in token */ - int *piStartOffset, /* OUT: Starting offset of token */ - int *piEndOffset, /* OUT: Ending offset of token */ - int *piPosition /* OUT: Position integer of token */ -){ - simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor; - simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer; - unsigned char *p = (unsigned char *)c->pInput; - - while( c->iOffsetnBytes ){ - int iStartOffset; - - /* Scan past delimiter characters */ - while( c->iOffsetnBytes && simpleDelim(t, p[c->iOffset]) ){ - c->iOffset++; - } - - /* Count non-delimiter characters. */ - iStartOffset = c->iOffset; - while( c->iOffsetnBytes && !simpleDelim(t, p[c->iOffset]) ){ - c->iOffset++; - } - - if( c->iOffset>iStartOffset ){ - int i, n = c->iOffset-iStartOffset; - if( n>c->nTokenAllocated ){ - char *pNew; - c->nTokenAllocated = n+20; - pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated); - if( !pNew ) return SQLITE_NOMEM; - c->pToken = pNew; - } - for(i=0; ipToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch); - } - *ppToken = c->pToken; - *pnBytes = n; - *piStartOffset = iStartOffset; - *piEndOffset = c->iOffset; - *piPosition = c->iToken++; - - return SQLITE_OK; - } - } - return SQLITE_DONE; -} - -/* -** The set of routines that implement the simple tokenizer -*/ -static const sqlite3_tokenizer_module simpleTokenizerModule = { - 0, - simpleCreate, - simpleDestroy, - simpleOpen, - simpleClose, - simpleNext, - 0, -}; - -/* -** Allocate a new simple tokenizer. Return a pointer to the new -** tokenizer in *ppModule -*/ -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( - sqlite3_tokenizer_module const**ppModule -){ - *ppModule = &simpleTokenizerModule; -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_tokenizer1.c *************************************/ -/************** Begin file fts3_tokenize_vtab.c ******************************/ -/* -** 2013 Apr 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 for the "fts3tokenize" virtual table module. -** An fts3tokenize virtual table is created as follows: -** -** CREATE VIRTUAL TABLE USING fts3tokenize( -** , , ... -** ); -** -** The table created has the following schema: -** -** CREATE TABLE (input, token, start, end, position) -** -** When queried, the query must include a WHERE clause of type: -** -** input = -** -** The virtual table module tokenizes this , using the FTS3 -** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE -** statement and returns one row for each token in the result. With -** fields set as follows: -** -** input: Always set to a copy of -** token: A token from the input. -** start: Byte offset of the token within the input . -** end: Byte offset of the byte immediately following the end of the -** token within the input string. -** pos: Token offset of token within input. -** -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ - -typedef struct Fts3tokTable Fts3tokTable; -typedef struct Fts3tokCursor Fts3tokCursor; - -/* -** Virtual table structure. -*/ -struct Fts3tokTable { - sqlite3_vtab base; /* Base class used by SQLite core */ - const sqlite3_tokenizer_module *pMod; - sqlite3_tokenizer *pTok; -}; - -/* -** Virtual table cursor structure. -*/ -struct Fts3tokCursor { - sqlite3_vtab_cursor base; /* Base class used by SQLite core */ - char *zInput; /* Input string */ - sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */ - int iRowid; /* Current 'rowid' value */ - const char *zToken; /* Current 'token' value */ - int nToken; /* Size of zToken in bytes */ - int iStart; /* Current 'start' value */ - int iEnd; /* Current 'end' value */ - int iPos; /* Current 'pos' value */ -}; - -/* -** Query FTS for the tokenizer implementation named zName. -*/ -static int fts3tokQueryTokenizer( - Fts3Hash *pHash, - const char *zName, - const sqlite3_tokenizer_module **pp, - char **pzErr -){ - sqlite3_tokenizer_module *p; - int nName = (int)strlen(zName); - - p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1); - if( !p ){ - sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName); - return SQLITE_ERROR; - } - - *pp = p; - return SQLITE_OK; -} - -/* -** The second argument, argv[], is an array of pointers to nul-terminated -** strings. This function makes a copy of the array and strings into a -** single block of memory. It then dequotes any of the strings that appear -** to be quoted. -** -** If successful, output parameter *pazDequote is set to point at the -** array of dequoted strings and SQLITE_OK is returned. The caller is -** responsible for eventually calling sqlite3_free() to free the array -** in this case. Or, if an error occurs, an SQLite error code is returned. -** The final value of *pazDequote is undefined in this case. -*/ -static int fts3tokDequoteArray( - int argc, /* Number of elements in argv[] */ - const char * const *argv, /* Input array */ - char ***pazDequote /* Output array */ -){ - int rc = SQLITE_OK; /* Return code */ - if( argc==0 ){ - *pazDequote = 0; - }else{ - int i; - int nByte = 0; - char **azDequote; - - for(i=0; i1 ) azArg = (const char * const *)&azDequote[1]; - rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok); - } - - if( rc==SQLITE_OK ){ - pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable)); - if( pTab==0 ){ - rc = SQLITE_NOMEM; - } - } - - if( rc==SQLITE_OK ){ - memset(pTab, 0, sizeof(Fts3tokTable)); - pTab->pMod = pMod; - pTab->pTok = pTok; - *ppVtab = &pTab->base; - }else{ - if( pTok ){ - pMod->xDestroy(pTok); - } - } - - sqlite3_free(azDequote); - return rc; -} - -/* -** This function does the work for both the xDisconnect and xDestroy methods. -** These tables have no persistent representation of their own, so xDisconnect -** and xDestroy are identical operations. -*/ -static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){ - Fts3tokTable *pTab = (Fts3tokTable *)pVtab; - - pTab->pMod->xDestroy(pTab->pTok); - sqlite3_free(pTab); - return SQLITE_OK; -} - -/* -** xBestIndex - Analyze a WHERE and ORDER BY clause. -*/ -static int fts3tokBestIndexMethod( - sqlite3_vtab *pVTab, - sqlite3_index_info *pInfo -){ - int i; - UNUSED_PARAMETER(pVTab); - - for(i=0; inConstraint; i++){ - if( pInfo->aConstraint[i].usable - && pInfo->aConstraint[i].iColumn==0 - && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ - ){ - pInfo->idxNum = 1; - pInfo->aConstraintUsage[i].argvIndex = 1; - pInfo->aConstraintUsage[i].omit = 1; - pInfo->estimatedCost = 1; - return SQLITE_OK; - } - } - - pInfo->idxNum = 0; - assert( pInfo->estimatedCost>1000000.0 ); - - return SQLITE_OK; -} - -/* -** xOpen - Open a cursor. -*/ -static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){ - Fts3tokCursor *pCsr; - UNUSED_PARAMETER(pVTab); - - pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor)); - if( pCsr==0 ){ - return SQLITE_NOMEM; - } - memset(pCsr, 0, sizeof(Fts3tokCursor)); - - *ppCsr = (sqlite3_vtab_cursor *)pCsr; - return SQLITE_OK; -} - -/* -** Reset the tokenizer cursor passed as the only argument. As if it had -** just been returned by fts3tokOpenMethod(). -*/ -static void fts3tokResetCursor(Fts3tokCursor *pCsr){ - if( pCsr->pCsr ){ - Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab); - pTab->pMod->xClose(pCsr->pCsr); - pCsr->pCsr = 0; - } - sqlite3_free(pCsr->zInput); - pCsr->zInput = 0; - pCsr->zToken = 0; - pCsr->nToken = 0; - pCsr->iStart = 0; - pCsr->iEnd = 0; - pCsr->iPos = 0; - pCsr->iRowid = 0; -} - -/* -** xClose - Close a cursor. -*/ -static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){ - Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; - - fts3tokResetCursor(pCsr); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** xNext - Advance the cursor to the next row, if any. -*/ -static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){ - Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; - Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); - int rc; /* Return code */ - - pCsr->iRowid++; - rc = pTab->pMod->xNext(pCsr->pCsr, - &pCsr->zToken, &pCsr->nToken, - &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos - ); - - if( rc!=SQLITE_OK ){ - fts3tokResetCursor(pCsr); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - } - - return rc; -} - -/* -** xFilter - Initialize a cursor to point at the start of its data. -*/ -static int fts3tokFilterMethod( - sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ - int idxNum, /* Strategy index */ - const char *idxStr, /* Unused */ - int nVal, /* Number of elements in apVal */ - sqlite3_value **apVal /* Arguments for the indexing scheme */ -){ - int rc = SQLITE_ERROR; - Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; - Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab); - UNUSED_PARAMETER(idxStr); - UNUSED_PARAMETER(nVal); - - fts3tokResetCursor(pCsr); - if( idxNum==1 ){ - const char *zByte = (const char *)sqlite3_value_text(apVal[0]); - int nByte = sqlite3_value_bytes(apVal[0]); - pCsr->zInput = sqlite3_malloc64(nByte+1); - if( pCsr->zInput==0 ){ - rc = SQLITE_NOMEM; - }else{ - if( nByte>0 ) memcpy(pCsr->zInput, zByte, nByte); - pCsr->zInput[nByte] = 0; - rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr); - if( rc==SQLITE_OK ){ - pCsr->pCsr->pTokenizer = pTab->pTok; - } - } - } - - if( rc!=SQLITE_OK ) return rc; - return fts3tokNextMethod(pCursor); -} - -/* -** xEof - Return true if the cursor is at EOF, or false otherwise. -*/ -static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){ - Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; - return (pCsr->zToken==0); -} - -/* -** xColumn - Return a column value. -*/ -static int fts3tokColumnMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */ - int iCol /* Index of column to read value from */ -){ - Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; - - /* CREATE TABLE x(input, token, start, end, position) */ - switch( iCol ){ - case 0: - sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT); - break; - case 1: - sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT); - break; - case 2: - sqlite3_result_int(pCtx, pCsr->iStart); - break; - case 3: - sqlite3_result_int(pCtx, pCsr->iEnd); - break; - default: - assert( iCol==4 ); - sqlite3_result_int(pCtx, pCsr->iPos); - break; - } - return SQLITE_OK; -} - -/* -** xRowid - Return the current rowid for the cursor. -*/ -static int fts3tokRowidMethod( - sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */ - sqlite_int64 *pRowid /* OUT: Rowid value */ -){ - Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor; - *pRowid = (sqlite3_int64)pCsr->iRowid; - return SQLITE_OK; -} - -/* -** Register the fts3tok module with database connection db. Return SQLITE_OK -** if successful or an error code if sqlite3_create_module() fails. -*/ -SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){ - static const sqlite3_module fts3tok_module = { - 0, /* iVersion */ - fts3tokConnectMethod, /* xCreate */ - fts3tokConnectMethod, /* xConnect */ - fts3tokBestIndexMethod, /* xBestIndex */ - fts3tokDisconnectMethod, /* xDisconnect */ - fts3tokDisconnectMethod, /* xDestroy */ - fts3tokOpenMethod, /* xOpen */ - fts3tokCloseMethod, /* xClose */ - fts3tokFilterMethod, /* xFilter */ - fts3tokNextMethod, /* xNext */ - fts3tokEofMethod, /* xEof */ - fts3tokColumnMethod, /* xColumn */ - fts3tokRowidMethod, /* xRowid */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindFunction */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0 /* xShadowName */ - }; - int rc; /* Return code */ - - rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash); - return rc; -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_tokenize_vtab.c **********************************/ -/************** Begin file fts3_write.c **************************************/ -/* -** 2009 Oct 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 is part of the SQLite FTS3 extension module. Specifically, -** this file contains code to insert, update and delete rows from FTS3 -** tables. It also contains code to merge FTS3 b-tree segments. Some -** of the sub-routines used to merge segments are also used by the query -** code in fts3.c. -*/ - -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ -/* #include */ -/* #include */ - -#define FTS_MAX_APPENDABLE_HEIGHT 16 - -/* -** When full-text index nodes are loaded from disk, the buffer that they -** are loaded into has the following number of bytes of padding at the end -** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer -** of 920 bytes is allocated for it. -** -** This means that if we have a pointer into a buffer containing node data, -** it is always safe to read up to two varints from it without risking an -** overread, even if the node data is corrupted. -*/ -#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2) - -/* -** Under certain circumstances, b-tree nodes (doclists) can be loaded into -** memory incrementally instead of all at once. This can be a big performance -** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext() -** method before retrieving all query results (as may happen, for example, -** if a query has a LIMIT clause). -** -** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD -** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes. -** The code is written so that the hard lower-limit for each of these values -** is 1. Clearly such small values would be inefficient, but can be useful -** for testing purposes. -** -** If this module is built with SQLITE_TEST defined, these constants may -** be overridden at runtime for testing purposes. File fts3_test.c contains -** a Tcl interface to read and write the values. -*/ -#ifdef SQLITE_TEST -int test_fts3_node_chunksize = (4*1024); -int test_fts3_node_chunk_threshold = (4*1024)*4; -# define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize -# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold -#else -# define FTS3_NODE_CHUNKSIZE (4*1024) -# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4) -#endif - -/* -** The values that may be meaningfully bound to the :1 parameter in -** statements SQL_REPLACE_STAT and SQL_SELECT_STAT. -*/ -#define FTS_STAT_DOCTOTAL 0 -#define FTS_STAT_INCRMERGEHINT 1 -#define FTS_STAT_AUTOINCRMERGE 2 - -/* -** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic -** and incremental merge operation that takes place. This is used for -** debugging FTS only, it should not usually be turned on in production -** systems. -*/ -#ifdef FTS3_LOG_MERGES -static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){ - sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel); -} -#else -#define fts3LogMerge(x, y) -#endif - - -typedef struct PendingList PendingList; -typedef struct SegmentNode SegmentNode; -typedef struct SegmentWriter SegmentWriter; - -/* -** An instance of the following data structure is used to build doclists -** incrementally. See function fts3PendingListAppend() for details. -*/ -struct PendingList { - int nData; - char *aData; - int nSpace; - sqlite3_int64 iLastDocid; - sqlite3_int64 iLastCol; - sqlite3_int64 iLastPos; -}; - - -/* -** Each cursor has a (possibly empty) linked list of the following objects. -*/ -struct Fts3DeferredToken { - Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */ - int iCol; /* Column token must occur in */ - Fts3DeferredToken *pNext; /* Next in list of deferred tokens */ - PendingList *pList; /* Doclist is assembled here */ -}; - -/* -** An instance of this structure is used to iterate through the terms on -** a contiguous set of segment b-tree leaf nodes. Although the details of -** this structure are only manipulated by code in this file, opaque handles -** of type Fts3SegReader* are also used by code in fts3.c to iterate through -** terms when querying the full-text index. See functions: -** -** sqlite3Fts3SegReaderNew() -** sqlite3Fts3SegReaderFree() -** sqlite3Fts3SegReaderIterate() -** -** Methods used to manipulate Fts3SegReader structures: -** -** fts3SegReaderNext() -** fts3SegReaderFirstDocid() -** fts3SegReaderNextDocid() -*/ -struct Fts3SegReader { - int iIdx; /* Index within level, or 0x7FFFFFFF for PT */ - u8 bLookup; /* True for a lookup only */ - u8 rootOnly; /* True for a root-only reader */ - - sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */ - sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */ - sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */ - sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */ - - char *aNode; /* Pointer to node data (or NULL) */ - int nNode; /* Size of buffer at aNode (or 0) */ - int nPopulate; /* If >0, bytes of buffer aNode[] loaded */ - sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */ - - Fts3HashElem **ppNextElem; - - /* Variables set by fts3SegReaderNext(). These may be read directly - ** by the caller. They are valid from the time SegmentReaderNew() returns - ** until SegmentReaderNext() returns something other than SQLITE_OK - ** (i.e. SQLITE_DONE). - */ - int nTerm; /* Number of bytes in current term */ - char *zTerm; /* Pointer to current term */ - int nTermAlloc; /* Allocated size of zTerm buffer */ - char *aDoclist; /* Pointer to doclist of current entry */ - int nDoclist; /* Size of doclist in current entry */ - - /* The following variables are used by fts3SegReaderNextDocid() to iterate - ** through the current doclist (aDoclist/nDoclist). - */ - char *pOffsetList; - int nOffsetList; /* For descending pending seg-readers only */ - sqlite3_int64 iDocid; -}; - -#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0) -#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0) - -/* -** An instance of this structure is used to create a segment b-tree in the -** database. The internal details of this type are only accessed by the -** following functions: -** -** fts3SegWriterAdd() -** fts3SegWriterFlush() -** fts3SegWriterFree() -*/ -struct SegmentWriter { - SegmentNode *pTree; /* Pointer to interior tree structure */ - sqlite3_int64 iFirst; /* First slot in %_segments written */ - sqlite3_int64 iFree; /* Next free slot in %_segments */ - char *zTerm; /* Pointer to previous term buffer */ - int nTerm; /* Number of bytes in zTerm */ - int nMalloc; /* Size of malloc'd buffer at zMalloc */ - char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ - int nSize; /* Size of allocation at aData */ - int nData; /* Bytes of data in aData */ - char *aData; /* Pointer to block from malloc() */ - i64 nLeafData; /* Number of bytes of leaf data written */ -}; - -/* -** Type SegmentNode is used by the following three functions to create -** the interior part of the segment b+-tree structures (everything except -** the leaf nodes). These functions and type are only ever used by code -** within the fts3SegWriterXXX() family of functions described above. -** -** fts3NodeAddTerm() -** fts3NodeWrite() -** fts3NodeFree() -** -** When a b+tree is written to the database (either as a result of a merge -** or the pending-terms table being flushed), leaves are written into the -** database file as soon as they are completely populated. The interior of -** the tree is assembled in memory and written out only once all leaves have -** been populated and stored. This is Ok, as the b+-tree fanout is usually -** very large, meaning that the interior of the tree consumes relatively -** little memory. -*/ -struct SegmentNode { - SegmentNode *pParent; /* Parent node (or NULL for root node) */ - SegmentNode *pRight; /* Pointer to right-sibling */ - SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */ - int nEntry; /* Number of terms written to node so far */ - char *zTerm; /* Pointer to previous term buffer */ - int nTerm; /* Number of bytes in zTerm */ - int nMalloc; /* Size of malloc'd buffer at zMalloc */ - char *zMalloc; /* Malloc'd space (possibly) used for zTerm */ - int nData; /* Bytes of valid data so far */ - char *aData; /* Node data */ -}; - -/* -** Valid values for the second argument to fts3SqlStmt(). -*/ -#define SQL_DELETE_CONTENT 0 -#define SQL_IS_EMPTY 1 -#define SQL_DELETE_ALL_CONTENT 2 -#define SQL_DELETE_ALL_SEGMENTS 3 -#define SQL_DELETE_ALL_SEGDIR 4 -#define SQL_DELETE_ALL_DOCSIZE 5 -#define SQL_DELETE_ALL_STAT 6 -#define SQL_SELECT_CONTENT_BY_ROWID 7 -#define SQL_NEXT_SEGMENT_INDEX 8 -#define SQL_INSERT_SEGMENTS 9 -#define SQL_NEXT_SEGMENTS_ID 10 -#define SQL_INSERT_SEGDIR 11 -#define SQL_SELECT_LEVEL 12 -#define SQL_SELECT_LEVEL_RANGE 13 -#define SQL_SELECT_LEVEL_COUNT 14 -#define SQL_SELECT_SEGDIR_MAX_LEVEL 15 -#define SQL_DELETE_SEGDIR_LEVEL 16 -#define SQL_DELETE_SEGMENTS_RANGE 17 -#define SQL_CONTENT_INSERT 18 -#define SQL_DELETE_DOCSIZE 19 -#define SQL_REPLACE_DOCSIZE 20 -#define SQL_SELECT_DOCSIZE 21 -#define SQL_SELECT_STAT 22 -#define SQL_REPLACE_STAT 23 - -#define SQL_SELECT_ALL_PREFIX_LEVEL 24 -#define SQL_DELETE_ALL_TERMS_SEGDIR 25 -#define SQL_DELETE_SEGDIR_RANGE 26 -#define SQL_SELECT_ALL_LANGID 27 -#define SQL_FIND_MERGE_LEVEL 28 -#define SQL_MAX_LEAF_NODE_ESTIMATE 29 -#define SQL_DELETE_SEGDIR_ENTRY 30 -#define SQL_SHIFT_SEGDIR_ENTRY 31 -#define SQL_SELECT_SEGDIR 32 -#define SQL_CHOMP_SEGDIR 33 -#define SQL_SEGMENT_IS_APPENDABLE 34 -#define SQL_SELECT_INDEXES 35 -#define SQL_SELECT_MXLEVEL 36 - -#define SQL_SELECT_LEVEL_RANGE2 37 -#define SQL_UPDATE_LEVEL_IDX 38 -#define SQL_UPDATE_LEVEL 39 - -/* -** This function is used to obtain an SQLite prepared statement handle -** for the statement identified by the second argument. If successful, -** *pp is set to the requested statement handle and SQLITE_OK returned. -** Otherwise, an SQLite error code is returned and *pp is set to 0. -** -** If argument apVal is not NULL, then it must point to an array with -** at least as many entries as the requested statement has bound -** parameters. The values are bound to the statements parameters before -** returning. -*/ -static int fts3SqlStmt( - Fts3Table *p, /* Virtual table handle */ - int eStmt, /* One of the SQL_XXX constants above */ - sqlite3_stmt **pp, /* OUT: Statement handle */ - sqlite3_value **apVal /* Values to bind to statement */ -){ - const char *azSql[] = { -/* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?", -/* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)", -/* 2 */ "DELETE FROM %Q.'%q_content'", -/* 3 */ "DELETE FROM %Q.'%q_segments'", -/* 4 */ "DELETE FROM %Q.'%q_segdir'", -/* 5 */ "DELETE FROM %Q.'%q_docsize'", -/* 6 */ "DELETE FROM %Q.'%q_stat'", -/* 7 */ "SELECT %s WHERE rowid=?", -/* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1", -/* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)", -/* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)", -/* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)", - - /* Return segments in order from oldest to newest.*/ -/* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root " - "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC", -/* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root " - "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?" - "ORDER BY level DESC, idx ASC", - -/* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?", -/* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", - -/* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?", -/* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?", -/* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)", -/* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?", -/* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", -/* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?", -/* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?", -/* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)", -/* 24 */ "", -/* 25 */ "", - -/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?", -/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'", - -/* This statement is used to determine which level to read the input from -** when performing an incremental merge. It returns the absolute level number -** of the oldest level in the db that contains at least ? segments. Or, -** if no level in the FTS index contains more than ? segments, the statement -** returns zero rows. */ -/* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' " - " GROUP BY level HAVING cnt>=?" - " ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1", - -/* Estimate the upper limit on the number of leaf nodes in a new segment -** created by merging the oldest :2 segments from absolute level :1. See -** function sqlite3Fts3Incrmerge() for details. */ -/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) " - " FROM (SELECT * FROM %Q.'%q_segdir' " - " WHERE level = ? ORDER BY idx ASC LIMIT ?" - " )", - -/* SQL_DELETE_SEGDIR_ENTRY -** Delete the %_segdir entry on absolute level :1 with index :2. */ -/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", - -/* SQL_SHIFT_SEGDIR_ENTRY -** Modify the idx value for the segment with idx=:3 on absolute level :2 -** to :1. */ -/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?", - -/* SQL_SELECT_SEGDIR -** Read a single entry from the %_segdir table. The entry from absolute -** level :1 with index value :2. */ -/* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root " - "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?", - -/* SQL_CHOMP_SEGDIR -** Update the start_block (:1) and root (:2) fields of the %_segdir -** entry located on absolute level :3 with index :4. */ -/* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?" - "WHERE level = ? AND idx = ?", - -/* SQL_SEGMENT_IS_APPENDABLE -** Return a single row if the segment with end_block=? is appendable. Or -** no rows otherwise. */ -/* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL", - -/* SQL_SELECT_INDEXES -** Return the list of valid segment indexes for absolute level ? */ -/* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC", - -/* SQL_SELECT_MXLEVEL -** Return the largest relative level in the FTS index or indexes. */ -/* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'", - - /* Return segments in order from oldest to newest.*/ -/* 37 */ "SELECT level, idx, end_block " - "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? " - "ORDER BY level DESC, idx ASC", - - /* Update statements used while promoting segments */ -/* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? " - "WHERE level=? AND idx=?", -/* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1" - - }; - int rc = SQLITE_OK; - sqlite3_stmt *pStmt; - - assert( SizeofArray(azSql)==SizeofArray(p->aStmt) ); - assert( eStmt=0 ); - - pStmt = p->aStmt[eStmt]; - if( !pStmt ){ - int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB; - char *zSql; - if( eStmt==SQL_CONTENT_INSERT ){ - zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); - }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){ - f &= ~SQLITE_PREPARE_NO_VTAB; - zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist); - }else{ - zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); - } - if( !zSql ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL); - sqlite3_free(zSql); - assert( rc==SQLITE_OK || pStmt==0 ); - p->aStmt[eStmt] = pStmt; - } - } - if( apVal ){ - int i; - int nParam = sqlite3_bind_parameter_count(pStmt); - for(i=0; rc==SQLITE_OK && inPendingData==0 ){ - sqlite3_stmt *pStmt; - rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_null(pStmt, 1); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); - } - } - - return rc; -} - -/* -** FTS maintains a separate indexes for each language-id (a 32-bit integer). -** Within each language id, a separate index is maintained to store the -** document terms, and each configured prefix size (configured the FTS -** "prefix=" option). And each index consists of multiple levels ("relative -** levels"). -** -** All three of these values (the language id, the specific index and the -** level within the index) are encoded in 64-bit integer values stored -** in the %_segdir table on disk. This function is used to convert three -** separate component values into the single 64-bit integer value that -** can be used to query the %_segdir table. -** -** Specifically, each language-id/index combination is allocated 1024 -** 64-bit integer level values ("absolute levels"). The main terms index -** for language-id 0 is allocate values 0-1023. The first prefix index -** (if any) for language-id 0 is allocated values 1024-2047. And so on. -** Language 1 indexes are allocated immediately following language 0. -** -** So, for a system with nPrefix prefix indexes configured, the block of -** absolute levels that corresponds to language-id iLangid and index -** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024). -*/ -static sqlite3_int64 getAbsoluteLevel( - Fts3Table *p, /* FTS3 table handle */ - int iLangid, /* Language id */ - int iIndex, /* Index in p->aIndex[] */ - int iLevel /* Level of segments */ -){ - sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */ - assert_fts3_nc( iLangid>=0 ); - assert( p->nIndex>0 ); - assert( iIndex>=0 && iIndexnIndex ); - - iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL; - return iBase + iLevel; -} - -/* -** Set *ppStmt to a statement handle that may be used to iterate through -** all rows in the %_segdir table, from oldest to newest. If successful, -** return SQLITE_OK. If an error occurs while preparing the statement, -** return an SQLite error code. -** -** There is only ever one instance of this SQL statement compiled for -** each FTS3 table. -** -** The statement returns the following columns from the %_segdir table: -** -** 0: idx -** 1: start_block -** 2: leaves_end_block -** 3: end_block -** 4: root -*/ -SQLITE_PRIVATE int sqlite3Fts3AllSegdirs( - Fts3Table *p, /* FTS3 table */ - int iLangid, /* Language being queried */ - int iIndex, /* Index for p->aIndex[] */ - int iLevel, /* Level to select (relative level) */ - sqlite3_stmt **ppStmt /* OUT: Compiled statement */ -){ - int rc; - sqlite3_stmt *pStmt = 0; - - assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 ); - assert( iLevel=0 && iIndexnIndex ); - - if( iLevel<0 ){ - /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */ - rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); - sqlite3_bind_int64(pStmt, 2, - getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) - ); - } - }else{ - /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */ - rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel)); - } - } - *ppStmt = pStmt; - return rc; -} - - -/* -** Append a single varint to a PendingList buffer. SQLITE_OK is returned -** if successful, or an SQLite error code otherwise. -** -** This function also serves to allocate the PendingList structure itself. -** For example, to create a new PendingList structure containing two -** varints: -** -** PendingList *p = 0; -** fts3PendingListAppendVarint(&p, 1); -** fts3PendingListAppendVarint(&p, 2); -*/ -static int fts3PendingListAppendVarint( - PendingList **pp, /* IN/OUT: Pointer to PendingList struct */ - sqlite3_int64 i /* Value to append to data */ -){ - PendingList *p = *pp; - - /* Allocate or grow the PendingList as required. */ - if( !p ){ - p = sqlite3_malloc(sizeof(*p) + 100); - if( !p ){ - return SQLITE_NOMEM; - } - p->nSpace = 100; - p->aData = (char *)&p[1]; - p->nData = 0; - } - else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){ - int nNew = p->nSpace * 2; - p = sqlite3_realloc(p, sizeof(*p) + nNew); - if( !p ){ - sqlite3_free(*pp); - *pp = 0; - return SQLITE_NOMEM; - } - p->nSpace = nNew; - p->aData = (char *)&p[1]; - } - - /* Append the new serialized varint to the end of the list. */ - p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i); - p->aData[p->nData] = '\0'; - *pp = p; - return SQLITE_OK; -} - -/* -** Add a docid/column/position entry to a PendingList structure. Non-zero -** is returned if the structure is sqlite3_realloced as part of adding -** the entry. Otherwise, zero. -** -** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning. -** Zero is always returned in this case. Otherwise, if no OOM error occurs, -** it is set to SQLITE_OK. -*/ -static int fts3PendingListAppend( - PendingList **pp, /* IN/OUT: PendingList structure */ - sqlite3_int64 iDocid, /* Docid for entry to add */ - sqlite3_int64 iCol, /* Column for entry to add */ - sqlite3_int64 iPos, /* Position of term for entry to add */ - int *pRc /* OUT: Return code */ -){ - PendingList *p = *pp; - int rc = SQLITE_OK; - - assert( !p || p->iLastDocid<=iDocid ); - - if( !p || p->iLastDocid!=iDocid ){ - u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0); - if( p ){ - assert( p->nDatanSpace ); - assert( p->aData[p->nData]==0 ); - p->nData++; - } - if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){ - goto pendinglistappend_out; - } - p->iLastCol = -1; - p->iLastPos = 0; - p->iLastDocid = iDocid; - } - if( iCol>0 && p->iLastCol!=iCol ){ - if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1)) - || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol)) - ){ - goto pendinglistappend_out; - } - p->iLastCol = iCol; - p->iLastPos = 0; - } - if( iCol>=0 ){ - assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) ); - rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos); - if( rc==SQLITE_OK ){ - p->iLastPos = iPos; - } - } - - pendinglistappend_out: - *pRc = rc; - if( p!=*pp ){ - *pp = p; - return 1; - } - return 0; -} - -/* -** Free a PendingList object allocated by fts3PendingListAppend(). -*/ -static void fts3PendingListDelete(PendingList *pList){ - sqlite3_free(pList); -} - -/* -** Add an entry to one of the pending-terms hash tables. -*/ -static int fts3PendingTermsAddOne( - Fts3Table *p, - int iCol, - int iPos, - Fts3Hash *pHash, /* Pending terms hash table to add entry to */ - const char *zToken, - int nToken -){ - PendingList *pList; - int rc = SQLITE_OK; - - pList = (PendingList *)fts3HashFind(pHash, zToken, nToken); - if( pList ){ - p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem)); - } - if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){ - if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){ - /* Malloc failed while inserting the new entry. This can only - ** happen if there was no previous entry for this token. - */ - assert( 0==fts3HashFind(pHash, zToken, nToken) ); - sqlite3_free(pList); - rc = SQLITE_NOMEM; - } - } - if( rc==SQLITE_OK ){ - p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem)); - } - return rc; -} - -/* -** Tokenize the nul-terminated string zText and add all tokens to the -** pending-terms hash-table. The docid used is that currently stored in -** p->iPrevDocid, and the column is specified by argument iCol. -** -** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. -*/ -static int fts3PendingTermsAdd( - Fts3Table *p, /* Table into which text will be inserted */ - int iLangid, /* Language id to use */ - const char *zText, /* Text of document to be inserted */ - int iCol, /* Column into which text is being inserted */ - u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */ -){ - int rc; - int iStart = 0; - int iEnd = 0; - int iPos = 0; - int nWord = 0; - - char const *zToken; - int nToken = 0; - - sqlite3_tokenizer *pTokenizer = p->pTokenizer; - sqlite3_tokenizer_module const *pModule = pTokenizer->pModule; - sqlite3_tokenizer_cursor *pCsr; - int (*xNext)(sqlite3_tokenizer_cursor *pCursor, - const char**,int*,int*,int*,int*); - - assert( pTokenizer && pModule ); - - /* If the user has inserted a NULL value, this function may be called with - ** zText==0. In this case, add zero token entries to the hash table and - ** return early. */ - if( zText==0 ){ - *pnWord = 0; - return SQLITE_OK; - } - - rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr); - if( rc!=SQLITE_OK ){ - return rc; - } - - xNext = pModule->xNext; - while( SQLITE_OK==rc - && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos)) - ){ - int i; - if( iPos>=nWord ) nWord = iPos+1; - - /* Positions cannot be negative; we use -1 as a terminator internally. - ** Tokens must have a non-zero length. - */ - if( iPos<0 || !zToken || nToken<=0 ){ - rc = SQLITE_ERROR; - break; - } - - /* Add the term to the terms index */ - rc = fts3PendingTermsAddOne( - p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken - ); - - /* Add the term to each of the prefix indexes that it is not too - ** short for. */ - for(i=1; rc==SQLITE_OK && inIndex; i++){ - struct Fts3Index *pIndex = &p->aIndex[i]; - if( nTokennPrefix ) continue; - rc = fts3PendingTermsAddOne( - p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix - ); - } - } - - pModule->xClose(pCsr); - *pnWord += nWord; - return (rc==SQLITE_DONE ? SQLITE_OK : rc); -} - -/* -** Calling this function indicates that subsequent calls to -** fts3PendingTermsAdd() are to add term/position-list pairs for the -** contents of the document with docid iDocid. -*/ -static int fts3PendingTermsDocid( - Fts3Table *p, /* Full-text table handle */ - int bDelete, /* True if this op is a delete */ - int iLangid, /* Language id of row being written */ - sqlite_int64 iDocid /* Docid of row being written */ -){ - assert( iLangid>=0 ); - assert( bDelete==1 || bDelete==0 ); - - /* TODO(shess) Explore whether partially flushing the buffer on - ** forced-flush would provide better performance. I suspect that if - ** we ordered the doclists by size and flushed the largest until the - ** buffer was half empty, that would let the less frequent terms - ** generate longer doclists. - */ - if( iDocidiPrevDocid - || (iDocid==p->iPrevDocid && p->bPrevDelete==0) - || p->iPrevLangid!=iLangid - || p->nPendingData>p->nMaxPendingData - ){ - int rc = sqlite3Fts3PendingTermsFlush(p); - if( rc!=SQLITE_OK ) return rc; - } - p->iPrevDocid = iDocid; - p->iPrevLangid = iLangid; - p->bPrevDelete = bDelete; - return SQLITE_OK; -} - -/* -** Discard the contents of the pending-terms hash tables. -*/ -SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){ - int i; - for(i=0; inIndex; i++){ - Fts3HashElem *pElem; - Fts3Hash *pHash = &p->aIndex[i].hPending; - for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){ - PendingList *pList = (PendingList *)fts3HashData(pElem); - fts3PendingListDelete(pList); - } - fts3HashClear(pHash); - } - p->nPendingData = 0; -} - -/* -** This function is called by the xUpdate() method as part of an INSERT -** operation. It adds entries for each term in the new record to the -** pendingTerms hash table. -** -** Argument apVal is the same as the similarly named argument passed to -** fts3InsertData(). Parameter iDocid is the docid of the new row. -*/ -static int fts3InsertTerms( - Fts3Table *p, - int iLangid, - sqlite3_value **apVal, - u32 *aSz -){ - int i; /* Iterator variable */ - for(i=2; inColumn+2; i++){ - int iCol = i-2; - if( p->abNotindexed[iCol]==0 ){ - const char *zText = (const char *)sqlite3_value_text(apVal[i]); - int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]); - if( rc!=SQLITE_OK ){ - return rc; - } - aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]); - } - } - return SQLITE_OK; -} - -/* -** This function is called by the xUpdate() method for an INSERT operation. -** The apVal parameter is passed a copy of the apVal argument passed by -** SQLite to the xUpdate() method. i.e: -** -** apVal[0] Not used for INSERT. -** apVal[1] rowid -** apVal[2] Left-most user-defined column -** ... -** apVal[p->nColumn+1] Right-most user-defined column -** apVal[p->nColumn+2] Hidden column with same name as table -** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid) -** apVal[p->nColumn+4] Hidden languageid column -*/ -static int fts3InsertData( - Fts3Table *p, /* Full-text table */ - sqlite3_value **apVal, /* Array of values to insert */ - sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */ -){ - int rc; /* Return code */ - sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */ - - if( p->zContentTbl ){ - sqlite3_value *pRowid = apVal[p->nColumn+3]; - if( sqlite3_value_type(pRowid)==SQLITE_NULL ){ - pRowid = apVal[1]; - } - if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){ - return SQLITE_CONSTRAINT; - } - *piDocid = sqlite3_value_int64(pRowid); - return SQLITE_OK; - } - - /* Locate the statement handle used to insert data into the %_content - ** table. The SQL for this statement is: - ** - ** INSERT INTO %_content VALUES(?, ?, ?, ...) - ** - ** The statement features N '?' variables, where N is the number of user - ** defined columns in the FTS3 table, plus one for the docid field. - */ - rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]); - if( rc==SQLITE_OK && p->zLanguageid ){ - rc = sqlite3_bind_int( - pContentInsert, p->nColumn+2, - sqlite3_value_int(apVal[p->nColumn+4]) - ); - } - if( rc!=SQLITE_OK ) return rc; - - /* There is a quirk here. The users INSERT statement may have specified - ** a value for the "rowid" field, for the "docid" field, or for both. - ** Which is a problem, since "rowid" and "docid" are aliases for the - ** same value. For example: - ** - ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2); - ** - ** In FTS3, this is an error. It is an error to specify non-NULL values - ** for both docid and some other rowid alias. - */ - if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){ - if( SQLITE_NULL==sqlite3_value_type(apVal[0]) - && SQLITE_NULL!=sqlite3_value_type(apVal[1]) - ){ - /* A rowid/docid conflict. */ - return SQLITE_ERROR; - } - rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]); - if( rc!=SQLITE_OK ) return rc; - } - - /* Execute the statement to insert the record. Set *piDocid to the - ** new docid value. - */ - sqlite3_step(pContentInsert); - rc = sqlite3_reset(pContentInsert); - - *piDocid = sqlite3_last_insert_rowid(p->db); - return rc; -} - - - -/* -** Remove all data from the FTS3 table. Clear the hash table containing -** pending terms. -*/ -static int fts3DeleteAll(Fts3Table *p, int bContent){ - int rc = SQLITE_OK; /* Return code */ - - /* Discard the contents of the pending-terms hash table. */ - sqlite3Fts3PendingTermsClear(p); - - /* Delete everything from the shadow tables. Except, leave %_content as - ** is if bContent is false. */ - assert( p->zContentTbl==0 || bContent==0 ); - if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0); - fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0); - fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0); - if( p->bHasDocsize ){ - fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0); - } - if( p->bHasStat ){ - fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0); - } - return rc; -} - -/* -** -*/ -static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){ - int iLangid = 0; - if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1); - return iLangid; -} - -/* -** The first element in the apVal[] array is assumed to contain the docid -** (an integer) of a row about to be deleted. Remove all terms from the -** full-text index. -*/ -static void fts3DeleteTerms( - int *pRC, /* Result code */ - Fts3Table *p, /* The FTS table to delete from */ - sqlite3_value *pRowid, /* The docid to be deleted */ - u32 *aSz, /* Sizes of deleted document written here */ - int *pbFound /* OUT: Set to true if row really does exist */ -){ - int rc; - sqlite3_stmt *pSelect; - - assert( *pbFound==0 ); - if( *pRC ) return; - rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid); - if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pSelect) ){ - int i; - int iLangid = langidFromSelect(p, pSelect); - i64 iDocid = sqlite3_column_int64(pSelect, 0); - rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid); - for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){ - int iCol = i-1; - if( p->abNotindexed[iCol]==0 ){ - const char *zText = (const char *)sqlite3_column_text(pSelect, i); - rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]); - aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i); - } - } - if( rc!=SQLITE_OK ){ - sqlite3_reset(pSelect); - *pRC = rc; - return; - } - *pbFound = 1; - } - rc = sqlite3_reset(pSelect); - }else{ - sqlite3_reset(pSelect); - } - *pRC = rc; -} - -/* -** Forward declaration to account for the circular dependency between -** functions fts3SegmentMerge() and fts3AllocateSegdirIdx(). -*/ -static int fts3SegmentMerge(Fts3Table *, int, int, int); - -/* -** This function allocates a new level iLevel index in the segdir table. -** Usually, indexes are allocated within a level sequentially starting -** with 0, so the allocated index is one greater than the value returned -** by: -** -** SELECT max(idx) FROM %_segdir WHERE level = :iLevel -** -** However, if there are already FTS3_MERGE_COUNT indexes at the requested -** level, they are merged into a single level (iLevel+1) segment and the -** allocated index is 0. -** -** If successful, *piIdx is set to the allocated index slot and SQLITE_OK -** returned. Otherwise, an SQLite error code is returned. -*/ -static int fts3AllocateSegdirIdx( - Fts3Table *p, - int iLangid, /* Language id */ - int iIndex, /* Index for p->aIndex */ - int iLevel, - int *piIdx -){ - int rc; /* Return Code */ - sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ - int iNext = 0; /* Result of query pNextIdx */ - - assert( iLangid>=0 ); - assert( p->nIndex>=1 ); - - /* Set variable iNext to the next available segdir index at level iLevel. */ - rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64( - pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) - ); - if( SQLITE_ROW==sqlite3_step(pNextIdx) ){ - iNext = sqlite3_column_int(pNextIdx, 0); - } - rc = sqlite3_reset(pNextIdx); - } - - if( rc==SQLITE_OK ){ - /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already - ** full, merge all segments in level iLevel into a single iLevel+1 - ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise, - ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext. - */ - if( iNext>=MergeCount(p) ){ - fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel)); - rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel); - *piIdx = 0; - }else{ - *piIdx = iNext; - } - } - - return rc; -} - -/* -** The %_segments table is declared as follows: -** -** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB) -** -** This function reads data from a single row of the %_segments table. The -** specific row is identified by the iBlockid parameter. If paBlob is not -** NULL, then a buffer is allocated using sqlite3_malloc() and populated -** with the contents of the blob stored in the "block" column of the -** identified table row is. Whether or not paBlob is NULL, *pnBlob is set -** to the size of the blob in bytes before returning. -** -** If an error occurs, or the table does not contain the specified row, -** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If -** paBlob is non-NULL, then it is the responsibility of the caller to -** eventually free the returned buffer. -** -** This function may leave an open sqlite3_blob* handle in the -** Fts3Table.pSegments variable. This handle is reused by subsequent calls -** to this function. The handle may be closed by calling the -** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy -** performance improvement, but the blob handle should always be closed -** before control is returned to the user (to prevent a lock being held -** on the database file for longer than necessary). Thus, any virtual table -** method (xFilter etc.) that may directly or indirectly call this function -** must call sqlite3Fts3SegmentsClose() before returning. -*/ -SQLITE_PRIVATE int sqlite3Fts3ReadBlock( - Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */ - char **paBlob, /* OUT: Blob data in malloc'd buffer */ - int *pnBlob, /* OUT: Size of blob data */ - int *pnLoad /* OUT: Bytes actually loaded */ -){ - int rc; /* Return code */ - - /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */ - assert( pnBlob ); - - if( p->pSegments ){ - rc = sqlite3_blob_reopen(p->pSegments, iBlockid); - }else{ - if( 0==p->zSegmentsTbl ){ - p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName); - if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM; - } - rc = sqlite3_blob_open( - p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments - ); - } - - if( rc==SQLITE_OK ){ - int nByte = sqlite3_blob_bytes(p->pSegments); - *pnBlob = nByte; - if( paBlob ){ - char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING); - if( !aByte ){ - rc = SQLITE_NOMEM; - }else{ - if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){ - nByte = FTS3_NODE_CHUNKSIZE; - *pnLoad = nByte; - } - rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0); - memset(&aByte[nByte], 0, FTS3_NODE_PADDING); - if( rc!=SQLITE_OK ){ - sqlite3_free(aByte); - aByte = 0; - } - } - *paBlob = aByte; - } - }else if( rc==SQLITE_ERROR ){ - rc = FTS_CORRUPT_VTAB; - } - - return rc; -} - -/* -** Close the blob handle at p->pSegments, if it is open. See comments above -** the sqlite3Fts3ReadBlock() function for details. -*/ -SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){ - sqlite3_blob_close(p->pSegments); - p->pSegments = 0; -} - -static int fts3SegReaderIncrRead(Fts3SegReader *pReader){ - int nRead; /* Number of bytes to read */ - int rc; /* Return code */ - - nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE); - rc = sqlite3_blob_read( - pReader->pBlob, - &pReader->aNode[pReader->nPopulate], - nRead, - pReader->nPopulate - ); - - if( rc==SQLITE_OK ){ - pReader->nPopulate += nRead; - memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING); - if( pReader->nPopulate==pReader->nNode ){ - sqlite3_blob_close(pReader->pBlob); - pReader->pBlob = 0; - pReader->nPopulate = 0; - } - } - return rc; -} - -static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){ - int rc = SQLITE_OK; - assert( !pReader->pBlob - || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode]) - ); - while( pReader->pBlob && rc==SQLITE_OK - && (pFrom - pReader->aNode + nByte)>pReader->nPopulate - ){ - rc = fts3SegReaderIncrRead(pReader); - } - return rc; -} - -/* -** Set an Fts3SegReader cursor to point at EOF. -*/ -static void fts3SegReaderSetEof(Fts3SegReader *pSeg){ - if( !fts3SegReaderIsRootOnly(pSeg) ){ - sqlite3_free(pSeg->aNode); - sqlite3_blob_close(pSeg->pBlob); - pSeg->pBlob = 0; - } - pSeg->aNode = 0; -} - -/* -** Move the iterator passed as the first argument to the next term in the -** segment. If successful, SQLITE_OK is returned. If there is no next term, -** SQLITE_DONE. Otherwise, an SQLite error code. -*/ -static int fts3SegReaderNext( - Fts3Table *p, - Fts3SegReader *pReader, - int bIncr -){ - int rc; /* Return code of various sub-routines */ - char *pNext; /* Cursor variable */ - int nPrefix; /* Number of bytes in term prefix */ - int nSuffix; /* Number of bytes in term suffix */ - - if( !pReader->aDoclist ){ - pNext = pReader->aNode; - }else{ - pNext = &pReader->aDoclist[pReader->nDoclist]; - } - - if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){ - - if( fts3SegReaderIsPending(pReader) ){ - Fts3HashElem *pElem = *(pReader->ppNextElem); - sqlite3_free(pReader->aNode); - pReader->aNode = 0; - if( pElem ){ - char *aCopy; - PendingList *pList = (PendingList *)fts3HashData(pElem); - int nCopy = pList->nData+1; - pReader->zTerm = (char *)fts3HashKey(pElem); - pReader->nTerm = fts3HashKeysize(pElem); - aCopy = (char*)sqlite3_malloc(nCopy); - if( !aCopy ) return SQLITE_NOMEM; - memcpy(aCopy, pList->aData, nCopy); - pReader->nNode = pReader->nDoclist = nCopy; - pReader->aNode = pReader->aDoclist = aCopy; - pReader->ppNextElem++; - assert( pReader->aNode ); - } - return SQLITE_OK; - } - - fts3SegReaderSetEof(pReader); - - /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf - ** blocks have already been traversed. */ -#ifdef CORRUPT_DB - assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB ); -#endif - if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){ - return SQLITE_OK; - } - - rc = sqlite3Fts3ReadBlock( - p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, - (bIncr ? &pReader->nPopulate : 0) - ); - if( rc!=SQLITE_OK ) return rc; - assert( pReader->pBlob==0 ); - if( bIncr && pReader->nPopulatenNode ){ - pReader->pBlob = p->pSegments; - p->pSegments = 0; - } - pNext = pReader->aNode; - } - - assert( !fts3SegReaderIsPending(pReader) ); - - rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2); - if( rc!=SQLITE_OK ) return rc; - - /* Because of the FTS3_NODE_PADDING bytes of padding, the following is - ** safe (no risk of overread) even if the node data is corrupted. */ - pNext += fts3GetVarint32(pNext, &nPrefix); - pNext += fts3GetVarint32(pNext, &nSuffix); - if( nSuffix<=0 - || (&pReader->aNode[pReader->nNode] - pNext)pReader->nTerm - ){ - return FTS_CORRUPT_VTAB; - } - - /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are - ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer - ** overflow - hence the (i64) casts. */ - if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){ - i64 nNew = ((i64)nPrefix+nSuffix)*2; - char *zNew = sqlite3_realloc64(pReader->zTerm, nNew); - if( !zNew ){ - return SQLITE_NOMEM; - } - pReader->zTerm = zNew; - pReader->nTermAlloc = nNew; - } - - rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX); - if( rc!=SQLITE_OK ) return rc; - - memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix); - pReader->nTerm = nPrefix+nSuffix; - pNext += nSuffix; - pNext += fts3GetVarint32(pNext, &pReader->nDoclist); - pReader->aDoclist = pNext; - pReader->pOffsetList = 0; - - /* Check that the doclist does not appear to extend past the end of the - ** b-tree node. And that the final byte of the doclist is 0x00. If either - ** of these statements is untrue, then the data structure is corrupt. - */ - if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode) - || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1]) - || pReader->nDoclist==0 - ){ - return FTS_CORRUPT_VTAB; - } - return SQLITE_OK; -} - -/* -** Set the SegReader to point to the first docid in the doclist associated -** with the current term. -*/ -static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){ - int rc = SQLITE_OK; - assert( pReader->aDoclist ); - assert( !pReader->pOffsetList ); - if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ - u8 bEof = 0; - pReader->iDocid = 0; - pReader->nOffsetList = 0; - sqlite3Fts3DoclistPrev(0, - pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, - &pReader->iDocid, &pReader->nOffsetList, &bEof - ); - }else{ - rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX); - if( rc==SQLITE_OK ){ - int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid); - pReader->pOffsetList = &pReader->aDoclist[n]; - } - } - return rc; -} - -/* -** Advance the SegReader to point to the next docid in the doclist -** associated with the current term. -** -** If arguments ppOffsetList and pnOffsetList are not NULL, then -** *ppOffsetList is set to point to the first column-offset list -** in the doclist entry (i.e. immediately past the docid varint). -** *pnOffsetList is set to the length of the set of column-offset -** lists, not including the nul-terminator byte. For example: -*/ -static int fts3SegReaderNextDocid( - Fts3Table *pTab, - Fts3SegReader *pReader, /* Reader to advance to next docid */ - char **ppOffsetList, /* OUT: Pointer to current position-list */ - int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */ -){ - int rc = SQLITE_OK; - char *p = pReader->pOffsetList; - char c = 0; - - assert( p ); - - if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){ - /* A pending-terms seg-reader for an FTS4 table that uses order=desc. - ** Pending-terms doclists are always built up in ascending order, so - ** we have to iterate through them backwards here. */ - u8 bEof = 0; - if( ppOffsetList ){ - *ppOffsetList = pReader->pOffsetList; - *pnOffsetList = pReader->nOffsetList - 1; - } - sqlite3Fts3DoclistPrev(0, - pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid, - &pReader->nOffsetList, &bEof - ); - if( bEof ){ - pReader->pOffsetList = 0; - }else{ - pReader->pOffsetList = p; - } - }else{ - char *pEnd = &pReader->aDoclist[pReader->nDoclist]; - - /* Pointer p currently points at the first byte of an offset list. The - ** following block advances it to point one byte past the end of - ** the same offset list. */ - while( 1 ){ - - /* The following line of code (and the "p++" below the while() loop) is - ** normally all that is required to move pointer p to the desired - ** position. The exception is if this node is being loaded from disk - ** incrementally and pointer "p" now points to the first byte past - ** the populated part of pReader->aNode[]. - */ - while( *p | c ) c = *p++ & 0x80; - assert( *p==0 ); - - if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break; - rc = fts3SegReaderIncrRead(pReader); - if( rc!=SQLITE_OK ) return rc; - } - p++; - - /* If required, populate the output variables with a pointer to and the - ** size of the previous offset-list. - */ - if( ppOffsetList ){ - *ppOffsetList = pReader->pOffsetList; - *pnOffsetList = (int)(p - pReader->pOffsetList - 1); - } - - /* List may have been edited in place by fts3EvalNearTrim() */ - while( p=pEnd ){ - pReader->pOffsetList = 0; - }else{ - rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX); - if( rc==SQLITE_OK ){ - u64 iDelta; - pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta); - if( pTab->bDescIdx ){ - pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta); - }else{ - pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta); - } - } - } - } - - return rc; -} - - -SQLITE_PRIVATE int sqlite3Fts3MsrOvfl( - Fts3Cursor *pCsr, - Fts3MultiSegReader *pMsr, - int *pnOvfl -){ - Fts3Table *p = (Fts3Table*)pCsr->base.pVtab; - int nOvfl = 0; - int ii; - int rc = SQLITE_OK; - int pgsz = p->nPgsz; - - assert( p->bFts4 ); - assert( pgsz>0 ); - - for(ii=0; rc==SQLITE_OK && iinSegment; ii++){ - Fts3SegReader *pReader = pMsr->apSegment[ii]; - if( !fts3SegReaderIsPending(pReader) - && !fts3SegReaderIsRootOnly(pReader) - ){ - sqlite3_int64 jj; - for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){ - int nBlob; - rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0); - if( rc!=SQLITE_OK ) break; - if( (nBlob+35)>pgsz ){ - nOvfl += (nBlob + 34)/pgsz; - } - } - } - } - *pnOvfl = nOvfl; - return rc; -} - -/* -** Free all allocations associated with the iterator passed as the -** second argument. -*/ -SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){ - if( pReader ){ - if( !fts3SegReaderIsPending(pReader) ){ - sqlite3_free(pReader->zTerm); - } - if( !fts3SegReaderIsRootOnly(pReader) ){ - sqlite3_free(pReader->aNode); - } - sqlite3_blob_close(pReader->pBlob); - } - sqlite3_free(pReader); -} - -/* -** Allocate a new SegReader object. -*/ -SQLITE_PRIVATE int sqlite3Fts3SegReaderNew( - int iAge, /* Segment "age". */ - int bLookup, /* True for a lookup only */ - sqlite3_int64 iStartLeaf, /* First leaf to traverse */ - sqlite3_int64 iEndLeaf, /* Final leaf to traverse */ - sqlite3_int64 iEndBlock, /* Final block of segment */ - const char *zRoot, /* Buffer containing root node */ - int nRoot, /* Size of buffer containing root node */ - Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */ -){ - Fts3SegReader *pReader; /* Newly allocated SegReader object */ - int nExtra = 0; /* Bytes to allocate segment root node */ - - assert( zRoot!=0 || nRoot==0 ); -#ifdef CORRUPT_DB - assert( zRoot!=0 || CORRUPT_DB ); -#endif - - if( iStartLeaf==0 ){ - if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB; - nExtra = nRoot + FTS3_NODE_PADDING; - } - - pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra); - if( !pReader ){ - return SQLITE_NOMEM; - } - memset(pReader, 0, sizeof(Fts3SegReader)); - pReader->iIdx = iAge; - pReader->bLookup = bLookup!=0; - pReader->iStartBlock = iStartLeaf; - pReader->iLeafEndBlock = iEndLeaf; - pReader->iEndBlock = iEndBlock; - - if( nExtra ){ - /* The entire segment is stored in the root node. */ - pReader->aNode = (char *)&pReader[1]; - pReader->rootOnly = 1; - pReader->nNode = nRoot; - if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot); - memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING); - }else{ - pReader->iCurrentBlock = iStartLeaf-1; - } - *ppReader = pReader; - return SQLITE_OK; -} - -/* -** This is a comparison function used as a qsort() callback when sorting -** an array of pending terms by term. This occurs as part of flushing -** the contents of the pending-terms hash table to the database. -*/ -static int SQLITE_CDECL fts3CompareElemByTerm( - const void *lhs, - const void *rhs -){ - char *z1 = fts3HashKey(*(Fts3HashElem **)lhs); - char *z2 = fts3HashKey(*(Fts3HashElem **)rhs); - int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs); - int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs); - - int n = (n1aIndex */ - const char *zTerm, /* Term to search for */ - int nTerm, /* Size of buffer zTerm */ - int bPrefix, /* True for a prefix iterator */ - Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */ -){ - Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */ - Fts3HashElem *pE; /* Iterator variable */ - Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */ - int nElem = 0; /* Size of array at aElem */ - int rc = SQLITE_OK; /* Return Code */ - Fts3Hash *pHash; - - pHash = &p->aIndex[iIndex].hPending; - if( bPrefix ){ - int nAlloc = 0; /* Size of allocated array at aElem */ - - for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){ - char *zKey = (char *)fts3HashKey(pE); - int nKey = fts3HashKeysize(pE); - if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){ - if( nElem==nAlloc ){ - Fts3HashElem **aElem2; - nAlloc += 16; - aElem2 = (Fts3HashElem **)sqlite3_realloc( - aElem, nAlloc*sizeof(Fts3HashElem *) - ); - if( !aElem2 ){ - rc = SQLITE_NOMEM; - nElem = 0; - break; - } - aElem = aElem2; - } - - aElem[nElem++] = pE; - } - } - - /* If more than one term matches the prefix, sort the Fts3HashElem - ** objects in term order using qsort(). This uses the same comparison - ** callback as is used when flushing terms to disk. - */ - if( nElem>1 ){ - qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm); - } - - }else{ - /* The query is a simple term lookup that matches at most one term in - ** the index. All that is required is a straight hash-lookup. - ** - ** Because the stack address of pE may be accessed via the aElem pointer - ** below, the "Fts3HashElem *pE" must be declared so that it is valid - ** within this entire function, not just this "else{...}" block. - */ - pE = fts3HashFindElem(pHash, zTerm, nTerm); - if( pE ){ - aElem = &pE; - nElem = 1; - } - } - - if( nElem>0 ){ - sqlite3_int64 nByte; - nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); - pReader = (Fts3SegReader *)sqlite3_malloc64(nByte); - if( !pReader ){ - rc = SQLITE_NOMEM; - }else{ - memset(pReader, 0, nByte); - pReader->iIdx = 0x7FFFFFFF; - pReader->ppNextElem = (Fts3HashElem **)&pReader[1]; - memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *)); - } - } - - if( bPrefix ){ - sqlite3_free(aElem); - } - *ppReader = pReader; - return rc; -} - -/* -** Compare the entries pointed to by two Fts3SegReader structures. -** Comparison is as follows: -** -** 1) EOF is greater than not EOF. -** -** 2) The current terms (if any) are compared using memcmp(). If one -** term is a prefix of another, the longer term is considered the -** larger. -** -** 3) By segment age. An older segment is considered larger. -*/ -static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ - int rc; - if( pLhs->aNode && pRhs->aNode ){ - int rc2 = pLhs->nTerm - pRhs->nTerm; - if( rc2<0 ){ - rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm); - }else{ - rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm); - } - if( rc==0 ){ - rc = rc2; - } - }else{ - rc = (pLhs->aNode==0) - (pRhs->aNode==0); - } - if( rc==0 ){ - rc = pRhs->iIdx - pLhs->iIdx; - } - assert( rc!=0 ); - return rc; -} - -/* -** A different comparison function for SegReader structures. In this -** version, it is assumed that each SegReader points to an entry in -** a doclist for identical terms. Comparison is made as follows: -** -** 1) EOF (end of doclist in this case) is greater than not EOF. -** -** 2) By current docid. -** -** 3) By segment age. An older segment is considered larger. -*/ -static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ - int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); - if( rc==0 ){ - if( pLhs->iDocid==pRhs->iDocid ){ - rc = pRhs->iIdx - pLhs->iIdx; - }else{ - rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1; - } - } - assert( pLhs->aNode && pRhs->aNode ); - return rc; -} -static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){ - int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0); - if( rc==0 ){ - if( pLhs->iDocid==pRhs->iDocid ){ - rc = pRhs->iIdx - pLhs->iIdx; - }else{ - rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1; - } - } - assert( pLhs->aNode && pRhs->aNode ); - return rc; -} - -/* -** Compare the term that the Fts3SegReader object passed as the first argument -** points to with the term specified by arguments zTerm and nTerm. -** -** If the pSeg iterator is already at EOF, return 0. Otherwise, return -** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are -** equal, or +ve if the pSeg term is greater than zTerm/nTerm. -*/ -static int fts3SegReaderTermCmp( - Fts3SegReader *pSeg, /* Segment reader object */ - const char *zTerm, /* Term to compare to */ - int nTerm /* Size of term zTerm in bytes */ -){ - int res = 0; - if( pSeg->aNode ){ - if( pSeg->nTerm>nTerm ){ - res = memcmp(pSeg->zTerm, zTerm, nTerm); - }else{ - res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm); - } - if( res==0 ){ - res = pSeg->nTerm-nTerm; - } - } - return res; -} - -/* -** Argument apSegment is an array of nSegment elements. It is known that -** the final (nSegment-nSuspect) members are already in sorted order -** (according to the comparison function provided). This function shuffles -** the array around until all entries are in sorted order. -*/ -static void fts3SegReaderSort( - Fts3SegReader **apSegment, /* Array to sort entries of */ - int nSegment, /* Size of apSegment array */ - int nSuspect, /* Unsorted entry count */ - int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */ -){ - int i; /* Iterator variable */ - - assert( nSuspect<=nSegment ); - - if( nSuspect==nSegment ) nSuspect--; - for(i=nSuspect-1; i>=0; i--){ - int j; - for(j=i; j<(nSegment-1); j++){ - Fts3SegReader *pTmp; - if( xCmp(apSegment[j], apSegment[j+1])<0 ) break; - pTmp = apSegment[j+1]; - apSegment[j+1] = apSegment[j]; - apSegment[j] = pTmp; - } - } - -#ifndef NDEBUG - /* Check that the list really is sorted now. */ - for(i=0; i<(nSuspect-1); i++){ - assert( xCmp(apSegment[i], apSegment[i+1])<0 ); - } -#endif -} - -/* -** Insert a record into the %_segments table. -*/ -static int fts3WriteSegment( - Fts3Table *p, /* Virtual table handle */ - sqlite3_int64 iBlock, /* Block id for new block */ - char *z, /* Pointer to buffer containing block data */ - int n /* Size of buffer z in bytes */ -){ - sqlite3_stmt *pStmt; - int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, iBlock); - sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); - sqlite3_bind_null(pStmt, 2); - } - return rc; -} - -/* -** Find the largest relative level number in the table. If successful, set -** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs, -** set *pnMax to zero and return an SQLite error code. -*/ -SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){ - int rc; - int mxLevel = 0; - sqlite3_stmt *pStmt = 0; - - rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0); - if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - mxLevel = sqlite3_column_int(pStmt, 0); - } - rc = sqlite3_reset(pStmt); - } - *pnMax = mxLevel; - return rc; -} - -/* -** Insert a record into the %_segdir table. -*/ -static int fts3WriteSegdir( - Fts3Table *p, /* Virtual table handle */ - sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */ - int iIdx, /* Value for "idx" field */ - sqlite3_int64 iStartBlock, /* Value for "start_block" field */ - sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */ - sqlite3_int64 iEndBlock, /* Value for "end_block" field */ - sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */ - char *zRoot, /* Blob value for "root" field */ - int nRoot /* Number of bytes in buffer zRoot */ -){ - sqlite3_stmt *pStmt; - int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pStmt, 1, iLevel); - sqlite3_bind_int(pStmt, 2, iIdx); - sqlite3_bind_int64(pStmt, 3, iStartBlock); - sqlite3_bind_int64(pStmt, 4, iLeafEndBlock); - if( nLeafData==0 ){ - sqlite3_bind_int64(pStmt, 5, iEndBlock); - }else{ - char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData); - if( !zEnd ) return SQLITE_NOMEM; - sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free); - } - sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); - sqlite3_bind_null(pStmt, 6); - } - return rc; -} - -/* -** Return the size of the common prefix (if any) shared by zPrev and -** zNext, in bytes. For example, -** -** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3 -** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2 -** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0 -*/ -static int fts3PrefixCompress( - const char *zPrev, /* Buffer containing previous term */ - int nPrev, /* Size of buffer zPrev in bytes */ - const char *zNext, /* Buffer containing next term */ - int nNext /* Size of buffer zNext in bytes */ -){ - int n; - UNUSED_PARAMETER(nNext); - for(n=0; nnData; /* Current size of node in bytes */ - int nReq = nData; /* Required space after adding zTerm */ - int nPrefix; /* Number of bytes of prefix compression */ - int nSuffix; /* Suffix length */ - - nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm); - nSuffix = nTerm-nPrefix; - - /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of - ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when - ** compared with BINARY collation. This indicates corruption. */ - if( nSuffix<=0 ) return FTS_CORRUPT_VTAB; - - nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix; - if( nReq<=p->nNodeSize || !pTree->zTerm ){ - - if( nReq>p->nNodeSize ){ - /* An unusual case: this is the first term to be added to the node - ** and the static node buffer (p->nNodeSize bytes) is not large - ** enough. Use a separately malloced buffer instead This wastes - ** p->nNodeSize bytes, but since this scenario only comes about when - ** the database contain two terms that share a prefix of almost 2KB, - ** this is not expected to be a serious problem. - */ - assert( pTree->aData==(char *)&pTree[1] ); - pTree->aData = (char *)sqlite3_malloc(nReq); - if( !pTree->aData ){ - return SQLITE_NOMEM; - } - } - - if( pTree->zTerm ){ - /* There is no prefix-length field for first term in a node */ - nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix); - } - - nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix); - memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix); - pTree->nData = nData + nSuffix; - pTree->nEntry++; - - if( isCopyTerm ){ - if( pTree->nMalloczMalloc, nTerm*2); - if( !zNew ){ - return SQLITE_NOMEM; - } - pTree->nMalloc = nTerm*2; - pTree->zMalloc = zNew; - } - pTree->zTerm = pTree->zMalloc; - memcpy(pTree->zTerm, zTerm, nTerm); - pTree->nTerm = nTerm; - }else{ - pTree->zTerm = (char *)zTerm; - pTree->nTerm = nTerm; - } - return SQLITE_OK; - } - } - - /* If control flows to here, it was not possible to append zTerm to the - ** current node. Create a new node (a right-sibling of the current node). - ** If this is the first node in the tree, the term is added to it. - ** - ** Otherwise, the term is not added to the new node, it is left empty for - ** now. Instead, the term is inserted into the parent of pTree. If pTree - ** has no parent, one is created here. - */ - pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize); - if( !pNew ){ - return SQLITE_NOMEM; - } - memset(pNew, 0, sizeof(SegmentNode)); - pNew->nData = 1 + FTS3_VARINT_MAX; - pNew->aData = (char *)&pNew[1]; - - if( pTree ){ - SegmentNode *pParent = pTree->pParent; - rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm); - if( pTree->pParent==0 ){ - pTree->pParent = pParent; - } - pTree->pRight = pNew; - pNew->pLeftmost = pTree->pLeftmost; - pNew->pParent = pParent; - pNew->zMalloc = pTree->zMalloc; - pNew->nMalloc = pTree->nMalloc; - pTree->zMalloc = 0; - }else{ - pNew->pLeftmost = pNew; - rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); - } - - *ppTree = pNew; - return rc; -} - -/* -** Helper function for fts3NodeWrite(). -*/ -static int fts3TreeFinishNode( - SegmentNode *pTree, - int iHeight, - sqlite3_int64 iLeftChild -){ - int nStart; - assert( iHeight>=1 && iHeight<128 ); - nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild); - pTree->aData[nStart] = (char)iHeight; - sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild); - return nStart; -} - -/* -** Write the buffer for the segment node pTree and all of its peers to the -** database. Then call this function recursively to write the parent of -** pTree and its peers to the database. -** -** Except, if pTree is a root node, do not write it to the database. Instead, -** set output variables *paRoot and *pnRoot to contain the root node. -** -** If successful, SQLITE_OK is returned and output variable *piLast is -** set to the largest blockid written to the database (or zero if no -** blocks were written to the db). Otherwise, an SQLite error code is -** returned. -*/ -static int fts3NodeWrite( - Fts3Table *p, /* Virtual table handle */ - SegmentNode *pTree, /* SegmentNode handle */ - int iHeight, /* Height of this node in tree */ - sqlite3_int64 iLeaf, /* Block id of first leaf node */ - sqlite3_int64 iFree, /* Block id of next free slot in %_segments */ - sqlite3_int64 *piLast, /* OUT: Block id of last entry written */ - char **paRoot, /* OUT: Data for root node */ - int *pnRoot /* OUT: Size of root node in bytes */ -){ - int rc = SQLITE_OK; - - if( !pTree->pParent ){ - /* Root node of the tree. */ - int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf); - *piLast = iFree-1; - *pnRoot = pTree->nData - nStart; - *paRoot = &pTree->aData[nStart]; - }else{ - SegmentNode *pIter; - sqlite3_int64 iNextFree = iFree; - sqlite3_int64 iNextLeaf = iLeaf; - for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){ - int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf); - int nWrite = pIter->nData - nStart; - - rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite); - iNextFree++; - iNextLeaf += (pIter->nEntry+1); - } - if( rc==SQLITE_OK ){ - assert( iNextLeaf==iFree ); - rc = fts3NodeWrite( - p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot - ); - } - } - - return rc; -} - -/* -** Free all memory allocations associated with the tree pTree. -*/ -static void fts3NodeFree(SegmentNode *pTree){ - if( pTree ){ - SegmentNode *p = pTree->pLeftmost; - fts3NodeFree(p->pParent); - while( p ){ - SegmentNode *pRight = p->pRight; - if( p->aData!=(char *)&p[1] ){ - sqlite3_free(p->aData); - } - assert( pRight==0 || p->zMalloc==0 ); - sqlite3_free(p->zMalloc); - sqlite3_free(p); - p = pRight; - } - } -} - -/* -** Add a term to the segment being constructed by the SegmentWriter object -** *ppWriter. When adding the first term to a segment, *ppWriter should -** be passed NULL. This function will allocate a new SegmentWriter object -** and return it via the input/output variable *ppWriter in this case. -** -** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code. -*/ -static int fts3SegWriterAdd( - Fts3Table *p, /* Virtual table handle */ - SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */ - int isCopyTerm, /* True if buffer zTerm must be copied */ - const char *zTerm, /* Pointer to buffer containing term */ - int nTerm, /* Size of term in bytes */ - const char *aDoclist, /* Pointer to buffer containing doclist */ - int nDoclist /* Size of doclist in bytes */ -){ - int nPrefix; /* Size of term prefix in bytes */ - int nSuffix; /* Size of term suffix in bytes */ - int nReq; /* Number of bytes required on leaf page */ - int nData; - SegmentWriter *pWriter = *ppWriter; - - if( !pWriter ){ - int rc; - sqlite3_stmt *pStmt; - - /* Allocate the SegmentWriter structure */ - pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter)); - if( !pWriter ) return SQLITE_NOMEM; - memset(pWriter, 0, sizeof(SegmentWriter)); - *ppWriter = pWriter; - - /* Allocate a buffer in which to accumulate data */ - pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize); - if( !pWriter->aData ) return SQLITE_NOMEM; - pWriter->nSize = p->nNodeSize; - - /* Find the next free blockid in the %_segments table */ - rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0); - if( rc!=SQLITE_OK ) return rc; - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - pWriter->iFree = sqlite3_column_int64(pStmt, 0); - pWriter->iFirst = pWriter->iFree; - } - rc = sqlite3_reset(pStmt); - if( rc!=SQLITE_OK ) return rc; - } - nData = pWriter->nData; - - nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm); - nSuffix = nTerm-nPrefix; - - /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of - ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when - ** compared with BINARY collation. This indicates corruption. */ - if( nSuffix<=0 ) return FTS_CORRUPT_VTAB; - - /* Figure out how many bytes are required by this new entry */ - nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */ - sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */ - nSuffix + /* Term suffix */ - sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ - nDoclist; /* Doclist data */ - - if( nData>0 && nData+nReq>p->nNodeSize ){ - int rc; - - /* The current leaf node is full. Write it out to the database. */ - if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB; - rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData); - if( rc!=SQLITE_OK ) return rc; - p->nLeafAdd++; - - /* Add the current term to the interior node tree. The term added to - ** the interior tree must: - ** - ** a) be greater than the largest term on the leaf node just written - ** to the database (still available in pWriter->zTerm), and - ** - ** b) be less than or equal to the term about to be added to the new - ** leaf node (zTerm/nTerm). - ** - ** In other words, it must be the prefix of zTerm 1 byte longer than - ** the common prefix (if any) of zTerm and pWriter->zTerm. - */ - assert( nPrefixpTree, isCopyTerm, zTerm, nPrefix+1); - if( rc!=SQLITE_OK ) return rc; - - nData = 0; - pWriter->nTerm = 0; - - nPrefix = 0; - nSuffix = nTerm; - nReq = 1 + /* varint containing prefix size */ - sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */ - nTerm + /* Term suffix */ - sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */ - nDoclist; /* Doclist data */ - } - - /* Increase the total number of bytes written to account for the new entry. */ - pWriter->nLeafData += nReq; - - /* If the buffer currently allocated is too small for this entry, realloc - ** the buffer to make it large enough. - */ - if( nReq>pWriter->nSize ){ - char *aNew = sqlite3_realloc(pWriter->aData, nReq); - if( !aNew ) return SQLITE_NOMEM; - pWriter->aData = aNew; - pWriter->nSize = nReq; - } - assert( nData+nReq<=pWriter->nSize ); - - /* Append the prefix-compressed term and doclist to the buffer. */ - nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix); - nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix); - assert( nSuffix>0 ); - memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); - nData += nSuffix; - nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); - assert( nDoclist>0 ); - memcpy(&pWriter->aData[nData], aDoclist, nDoclist); - pWriter->nData = nData + nDoclist; - - /* Save the current term so that it can be used to prefix-compress the next. - ** If the isCopyTerm parameter is true, then the buffer pointed to by - ** zTerm is transient, so take a copy of the term data. Otherwise, just - ** store a copy of the pointer. - */ - if( isCopyTerm ){ - if( nTerm>pWriter->nMalloc ){ - char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2); - if( !zNew ){ - return SQLITE_NOMEM; - } - pWriter->nMalloc = nTerm*2; - pWriter->zMalloc = zNew; - pWriter->zTerm = zNew; - } - assert( pWriter->zTerm==pWriter->zMalloc ); - assert( nTerm>0 ); - memcpy(pWriter->zTerm, zTerm, nTerm); - }else{ - pWriter->zTerm = (char *)zTerm; - } - pWriter->nTerm = nTerm; - - return SQLITE_OK; -} - -/* -** Flush all data associated with the SegmentWriter object pWriter to the -** database. This function must be called after all terms have been added -** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is -** returned. Otherwise, an SQLite error code. -*/ -static int fts3SegWriterFlush( - Fts3Table *p, /* Virtual table handle */ - SegmentWriter *pWriter, /* SegmentWriter to flush to the db */ - sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */ - int iIdx /* Value for 'idx' column of %_segdir */ -){ - int rc; /* Return code */ - if( pWriter->pTree ){ - sqlite3_int64 iLast = 0; /* Largest block id written to database */ - sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */ - char *zRoot = NULL; /* Pointer to buffer containing root node */ - int nRoot = 0; /* Size of buffer zRoot */ - - iLastLeaf = pWriter->iFree; - rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData); - if( rc==SQLITE_OK ){ - rc = fts3NodeWrite(p, pWriter->pTree, 1, - pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot); - } - if( rc==SQLITE_OK ){ - rc = fts3WriteSegdir(p, iLevel, iIdx, - pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot); - } - }else{ - /* The entire tree fits on the root node. Write it to the segdir table. */ - rc = fts3WriteSegdir(p, iLevel, iIdx, - 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData); - } - p->nLeafAdd++; - return rc; -} - -/* -** Release all memory held by the SegmentWriter object passed as the -** first argument. -*/ -static void fts3SegWriterFree(SegmentWriter *pWriter){ - if( pWriter ){ - sqlite3_free(pWriter->aData); - sqlite3_free(pWriter->zMalloc); - fts3NodeFree(pWriter->pTree); - sqlite3_free(pWriter); - } -} - -/* -** The first value in the apVal[] array is assumed to contain an integer. -** This function tests if there exist any documents with docid values that -** are different from that integer. i.e. if deleting the document with docid -** pRowid would mean the FTS3 table were empty. -** -** If successful, *pisEmpty is set to true if the table is empty except for -** document pRowid, or false otherwise, and SQLITE_OK is returned. If an -** error occurs, an SQLite error code is returned. -*/ -static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){ - sqlite3_stmt *pStmt; - int rc; - if( p->zContentTbl ){ - /* If using the content=xxx option, assume the table is never empty */ - *pisEmpty = 0; - rc = SQLITE_OK; - }else{ - rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid); - if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *pisEmpty = sqlite3_column_int(pStmt, 0); - } - rc = sqlite3_reset(pStmt); - } - } - return rc; -} - -/* -** Set *pnMax to the largest segment level in the database for the index -** iIndex. -** -** Segment levels are stored in the 'level' column of the %_segdir table. -** -** Return SQLITE_OK if successful, or an SQLite error code if not. -*/ -static int fts3SegmentMaxLevel( - Fts3Table *p, - int iLangid, - int iIndex, - sqlite3_int64 *pnMax -){ - sqlite3_stmt *pStmt; - int rc; - assert( iIndex>=0 && iIndexnIndex ); - - /* Set pStmt to the compiled version of: - ** - ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? - ** - ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). - */ - rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); - if( rc!=SQLITE_OK ) return rc; - sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); - sqlite3_bind_int64(pStmt, 2, - getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) - ); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *pnMax = sqlite3_column_int64(pStmt, 0); - } - return sqlite3_reset(pStmt); -} - -/* -** iAbsLevel is an absolute level that may be assumed to exist within -** the database. This function checks if it is the largest level number -** within its index. Assuming no error occurs, *pbMax is set to 1 if -** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK -** is returned. If an error occurs, an error code is returned and the -** final value of *pbMax is undefined. -*/ -static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){ - - /* Set pStmt to the compiled version of: - ** - ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? - ** - ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR). - */ - sqlite3_stmt *pStmt; - int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0); - if( rc!=SQLITE_OK ) return rc; - sqlite3_bind_int64(pStmt, 1, iAbsLevel+1); - sqlite3_bind_int64(pStmt, 2, - (((u64)iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL - ); - - *pbMax = 0; - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL; - } - return sqlite3_reset(pStmt); -} - -/* -** Delete all entries in the %_segments table associated with the segment -** opened with seg-reader pSeg. This function does not affect the contents -** of the %_segdir table. -*/ -static int fts3DeleteSegment( - Fts3Table *p, /* FTS table handle */ - Fts3SegReader *pSeg /* Segment to delete */ -){ - int rc = SQLITE_OK; /* Return code */ - if( pSeg->iStartBlock ){ - sqlite3_stmt *pDelete; /* SQL statement to delete rows */ - rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock); - sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock); - sqlite3_step(pDelete); - rc = sqlite3_reset(pDelete); - } - } - return rc; -} - -/* -** This function is used after merging multiple segments into a single large -** segment to delete the old, now redundant, segment b-trees. Specifically, -** it: -** -** 1) Deletes all %_segments entries for the segments associated with -** each of the SegReader objects in the array passed as the third -** argument, and -** -** 2) deletes all %_segdir entries with level iLevel, or all %_segdir -** entries regardless of level if (iLevel<0). -** -** SQLITE_OK is returned if successful, otherwise an SQLite error code. -*/ -static int fts3DeleteSegdir( - Fts3Table *p, /* Virtual table handle */ - int iLangid, /* Language id */ - int iIndex, /* Index for p->aIndex */ - int iLevel, /* Level of %_segdir entries to delete */ - Fts3SegReader **apSegment, /* Array of SegReader objects */ - int nReader /* Size of array apSegment */ -){ - int rc = SQLITE_OK; /* Return Code */ - int i; /* Iterator variable */ - sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */ - - for(i=0; rc==SQLITE_OK && i=0 || iLevel==FTS3_SEGCURSOR_ALL ); - if( iLevel==FTS3_SEGCURSOR_ALL ){ - rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0)); - sqlite3_bind_int64(pDelete, 2, - getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1) - ); - } - }else{ - rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64( - pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) - ); - } - } - - if( rc==SQLITE_OK ){ - sqlite3_step(pDelete); - rc = sqlite3_reset(pDelete); - } - - return rc; -} - -/* -** When this function is called, buffer *ppList (size *pnList bytes) contains -** a position list that may (or may not) feature multiple columns. This -** function adjusts the pointer *ppList and the length *pnList so that they -** identify the subset of the position list that corresponds to column iCol. -** -** If there are no entries in the input position list for column iCol, then -** *pnList is set to zero before returning. -** -** If parameter bZero is non-zero, then any part of the input list following -** the end of the output list is zeroed before returning. -*/ -static void fts3ColumnFilter( - int iCol, /* Column to filter on */ - int bZero, /* Zero out anything following *ppList */ - char **ppList, /* IN/OUT: Pointer to position list */ - int *pnList /* IN/OUT: Size of buffer *ppList in bytes */ -){ - char *pList = *ppList; - int nList = *pnList; - char *pEnd = &pList[nList]; - int iCurrent = 0; - char *p = pList; - - assert( iCol>=0 ); - while( 1 ){ - char c = 0; - while( p0){ - memset(&pList[nList], 0, pEnd - &pList[nList]); - } - *ppList = pList; - *pnList = nList; -} - -/* -** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any -** existing data). Grow the buffer if required. -** -** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered -** trying to resize the buffer, return SQLITE_NOMEM. -*/ -static int fts3MsrBufferData( - Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ - char *pList, - int nList -){ - if( nList>pMsr->nBuffer ){ - char *pNew; - pMsr->nBuffer = nList*2; - pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); - if( !pNew ) return SQLITE_NOMEM; - pMsr->aBuffer = pNew; - } - - assert( nList>0 ); - memcpy(pMsr->aBuffer, pList, nList); - return SQLITE_OK; -} - -SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( - Fts3Table *p, /* Virtual table handle */ - Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ - sqlite3_int64 *piDocid, /* OUT: Docid value */ - char **paPoslist, /* OUT: Pointer to position list */ - int *pnPoslist /* OUT: Size of position list in bytes */ -){ - int nMerge = pMsr->nAdvance; - Fts3SegReader **apSegment = pMsr->apSegment; - int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( - p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp - ); - - if( nMerge==0 ){ - *paPoslist = 0; - return SQLITE_OK; - } - - while( 1 ){ - Fts3SegReader *pSeg; - pSeg = pMsr->apSegment[0]; - - if( pSeg->pOffsetList==0 ){ - *paPoslist = 0; - break; - }else{ - int rc; - char *pList; - int nList; - int j; - sqlite3_int64 iDocid = apSegment[0]->iDocid; - - rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); - j = 1; - while( rc==SQLITE_OK - && jpOffsetList - && apSegment[j]->iDocid==iDocid - ){ - rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0); - j++; - } - if( rc!=SQLITE_OK ) return rc; - fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp); - - if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){ - rc = fts3MsrBufferData(pMsr, pList, nList+1); - if( rc!=SQLITE_OK ) return rc; - assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 ); - pList = pMsr->aBuffer; - } - - if( pMsr->iColFilter>=0 ){ - fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList); - } - - if( nList>0 ){ - *paPoslist = pList; - *piDocid = iDocid; - *pnPoslist = nList; - break; - } - } - } - - return SQLITE_OK; -} - -static int fts3SegReaderStart( - Fts3Table *p, /* Virtual table handle */ - Fts3MultiSegReader *pCsr, /* Cursor object */ - const char *zTerm, /* Term searched for (or NULL) */ - int nTerm /* Length of zTerm in bytes */ -){ - int i; - int nSeg = pCsr->nSegment; - - /* If the Fts3SegFilter defines a specific term (or term prefix) to search - ** for, then advance each segment iterator until it points to a term of - ** equal or greater value than the specified term. This prevents many - ** unnecessary merge/sort operations for the case where single segment - ** b-tree leaf nodes contain more than one term. - */ - for(i=0; pCsr->bRestart==0 && inSegment; i++){ - int res = 0; - Fts3SegReader *pSeg = pCsr->apSegment[i]; - do { - int rc = fts3SegReaderNext(p, pSeg, 0); - if( rc!=SQLITE_OK ) return rc; - }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 ); - - if( pSeg->bLookup && res!=0 ){ - fts3SegReaderSetEof(pSeg); - } - } - fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp); - - return SQLITE_OK; -} - -SQLITE_PRIVATE int sqlite3Fts3SegReaderStart( - Fts3Table *p, /* Virtual table handle */ - Fts3MultiSegReader *pCsr, /* Cursor object */ - Fts3SegFilter *pFilter /* Restrictions on range of iteration */ -){ - pCsr->pFilter = pFilter; - return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm); -} - -SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart( - Fts3Table *p, /* Virtual table handle */ - Fts3MultiSegReader *pCsr, /* Cursor object */ - int iCol, /* Column to match on. */ - const char *zTerm, /* Term to iterate through a doclist for */ - int nTerm /* Number of bytes in zTerm */ -){ - int i; - int rc; - int nSegment = pCsr->nSegment; - int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( - p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp - ); - - assert( pCsr->pFilter==0 ); - assert( zTerm && nTerm>0 ); - - /* Advance each segment iterator until it points to the term zTerm/nTerm. */ - rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm); - if( rc!=SQLITE_OK ) return rc; - - /* Determine how many of the segments actually point to zTerm/nTerm. */ - for(i=0; iapSegment[i]; - if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){ - break; - } - } - pCsr->nAdvance = i; - - /* Advance each of the segments to point to the first docid. */ - for(i=0; inAdvance; i++){ - rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]); - if( rc!=SQLITE_OK ) return rc; - } - fts3SegReaderSort(pCsr->apSegment, i, i, xCmp); - - assert( iCol<0 || iColnColumn ); - pCsr->iColFilter = iCol; - - return SQLITE_OK; -} - -/* -** This function is called on a MultiSegReader that has been started using -** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also -** have been made. Calling this function puts the MultiSegReader in such -** a state that if the next two calls are: -** -** sqlite3Fts3SegReaderStart() -** sqlite3Fts3SegReaderStep() -** -** then the entire doclist for the term is available in -** MultiSegReader.aDoclist/nDoclist. -*/ -SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){ - int i; /* Used to iterate through segment-readers */ - - assert( pCsr->zTerm==0 ); - assert( pCsr->nTerm==0 ); - assert( pCsr->aDoclist==0 ); - assert( pCsr->nDoclist==0 ); - - pCsr->nAdvance = 0; - pCsr->bRestart = 1; - for(i=0; inSegment; i++){ - pCsr->apSegment[i]->pOffsetList = 0; - pCsr->apSegment[i]->nOffsetList = 0; - pCsr->apSegment[i]->iDocid = 0; - } - - return SQLITE_OK; -} - -static int fts3GrowSegReaderBuffer(Fts3MultiSegReader *pCsr, int nReq){ - if( nReq>pCsr->nBuffer ){ - char *aNew; - pCsr->nBuffer = nReq*2; - aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); - if( !aNew ){ - return SQLITE_NOMEM; - } - pCsr->aBuffer = aNew; - } - return SQLITE_OK; -} - - -SQLITE_PRIVATE int sqlite3Fts3SegReaderStep( - Fts3Table *p, /* Virtual table handle */ - Fts3MultiSegReader *pCsr /* Cursor object */ -){ - int rc = SQLITE_OK; - - int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY); - int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS); - int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER); - int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX); - int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN); - int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST); - - Fts3SegReader **apSegment = pCsr->apSegment; - int nSegment = pCsr->nSegment; - Fts3SegFilter *pFilter = pCsr->pFilter; - int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = ( - p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp - ); - - if( pCsr->nSegment==0 ) return SQLITE_OK; - - do { - int nMerge; - int i; - - /* Advance the first pCsr->nAdvance entries in the apSegment[] array - ** forward. Then sort the list in order of current term again. - */ - for(i=0; inAdvance; i++){ - Fts3SegReader *pSeg = apSegment[i]; - if( pSeg->bLookup ){ - fts3SegReaderSetEof(pSeg); - }else{ - rc = fts3SegReaderNext(p, pSeg, 0); - } - if( rc!=SQLITE_OK ) return rc; - } - fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp); - pCsr->nAdvance = 0; - - /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */ - assert( rc==SQLITE_OK ); - if( apSegment[0]->aNode==0 ) break; - - pCsr->nTerm = apSegment[0]->nTerm; - pCsr->zTerm = apSegment[0]->zTerm; - - /* If this is a prefix-search, and if the term that apSegment[0] points - ** to does not share a suffix with pFilter->zTerm/nTerm, then all - ** required callbacks have been made. In this case exit early. - ** - ** Similarly, if this is a search for an exact match, and the first term - ** of segment apSegment[0] is not a match, exit early. - */ - if( pFilter->zTerm && !isScan ){ - if( pCsr->nTermnTerm - || (!isPrefix && pCsr->nTerm>pFilter->nTerm) - || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) - ){ - break; - } - } - - nMerge = 1; - while( nMergeaNode - && apSegment[nMerge]->nTerm==pCsr->nTerm - && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm) - ){ - nMerge++; - } - - assert( isIgnoreEmpty || (isRequirePos && !isColFilter) ); - if( nMerge==1 - && !isIgnoreEmpty - && !isFirst - && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0) - ){ - pCsr->nDoclist = apSegment[0]->nDoclist; - if( fts3SegReaderIsPending(apSegment[0]) ){ - rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist); - pCsr->aDoclist = pCsr->aBuffer; - }else{ - pCsr->aDoclist = apSegment[0]->aDoclist; - } - if( rc==SQLITE_OK ) rc = SQLITE_ROW; - }else{ - int nDoclist = 0; /* Size of doclist */ - sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */ - - /* The current term of the first nMerge entries in the array - ** of Fts3SegReader objects is the same. The doclists must be merged - ** and a single term returned with the merged doclist. - */ - for(i=0; ipOffsetList ){ - int j; /* Number of segments that share a docid */ - char *pList = 0; - int nList = 0; - int nByte; - sqlite3_int64 iDocid = apSegment[0]->iDocid; - fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList); - j = 1; - while( jpOffsetList - && apSegment[j]->iDocid==iDocid - ){ - fts3SegReaderNextDocid(p, apSegment[j], 0, 0); - j++; - } - - if( isColFilter ){ - fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList); - } - - if( !isIgnoreEmpty || nList>0 ){ - - /* Calculate the 'docid' delta value to write into the merged - ** doclist. */ - sqlite3_int64 iDelta; - if( p->bDescIdx && nDoclist>0 ){ - if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB; - iDelta = (i64)((u64)iPrev - (u64)iDocid); - }else{ - if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB; - iDelta = (i64)((u64)iDocid - (u64)iPrev); - } - - nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); - - rc = fts3GrowSegReaderBuffer(pCsr, nByte+nDoclist); - if( rc ) return rc; - - if( isFirst ){ - char *a = &pCsr->aBuffer[nDoclist]; - int nWrite; - - nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a); - if( nWrite ){ - iPrev = iDocid; - nDoclist += nWrite; - } - }else{ - nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta); - iPrev = iDocid; - if( isRequirePos ){ - memcpy(&pCsr->aBuffer[nDoclist], pList, nList); - nDoclist += nList; - pCsr->aBuffer[nDoclist++] = '\0'; - } - } - } - - fts3SegReaderSort(apSegment, nMerge, j, xCmp); - } - if( nDoclist>0 ){ - rc = fts3GrowSegReaderBuffer(pCsr, nDoclist+FTS3_NODE_PADDING); - if( rc ) return rc; - memset(&pCsr->aBuffer[nDoclist], 0, FTS3_NODE_PADDING); - pCsr->aDoclist = pCsr->aBuffer; - pCsr->nDoclist = nDoclist; - rc = SQLITE_ROW; - } - } - pCsr->nAdvance = nMerge; - }while( rc==SQLITE_OK ); - - return rc; -} - - -SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish( - Fts3MultiSegReader *pCsr /* Cursor object */ -){ - if( pCsr ){ - int i; - for(i=0; inSegment; i++){ - sqlite3Fts3SegReaderFree(pCsr->apSegment[i]); - } - sqlite3_free(pCsr->apSegment); - sqlite3_free(pCsr->aBuffer); - - pCsr->nSegment = 0; - pCsr->apSegment = 0; - pCsr->aBuffer = 0; - } -} - -/* -** Decode the "end_block" field, selected by column iCol of the SELECT -** statement passed as the first argument. -** -** The "end_block" field may contain either an integer, or a text field -** containing the text representation of two non-negative integers separated -** by one or more space (0x20) characters. In the first case, set *piEndBlock -** to the integer value and *pnByte to zero before returning. In the second, -** set *piEndBlock to the first value and *pnByte to the second. -*/ -static void fts3ReadEndBlockField( - sqlite3_stmt *pStmt, - int iCol, - i64 *piEndBlock, - i64 *pnByte -){ - const unsigned char *zText = sqlite3_column_text(pStmt, iCol); - if( zText ){ - int i; - int iMul = 1; - u64 iVal = 0; - for(i=0; zText[i]>='0' && zText[i]<='9'; i++){ - iVal = iVal*10 + (zText[i] - '0'); - } - *piEndBlock = (i64)iVal; - while( zText[i]==' ' ) i++; - iVal = 0; - if( zText[i]=='-' ){ - i++; - iMul = -1; - } - for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){ - iVal = iVal*10 + (zText[i] - '0'); - } - *pnByte = ((i64)iVal * (i64)iMul); - } -} - - -/* -** A segment of size nByte bytes has just been written to absolute level -** iAbsLevel. Promote any segments that should be promoted as a result. -*/ -static int fts3PromoteSegments( - Fts3Table *p, /* FTS table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level just updated */ - sqlite3_int64 nByte /* Size of new segment at iAbsLevel */ -){ - int rc = SQLITE_OK; - sqlite3_stmt *pRange; - - rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0); - - if( rc==SQLITE_OK ){ - int bOk = 0; - i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1; - i64 nLimit = (nByte*3)/2; - - /* Loop through all entries in the %_segdir table corresponding to - ** segments in this index on levels greater than iAbsLevel. If there is - ** at least one such segment, and it is possible to determine that all - ** such segments are smaller than nLimit bytes in size, they will be - ** promoted to level iAbsLevel. */ - sqlite3_bind_int64(pRange, 1, iAbsLevel+1); - sqlite3_bind_int64(pRange, 2, iLast); - while( SQLITE_ROW==sqlite3_step(pRange) ){ - i64 nSize = 0, dummy; - fts3ReadEndBlockField(pRange, 2, &dummy, &nSize); - if( nSize<=0 || nSize>nLimit ){ - /* If nSize==0, then the %_segdir.end_block field does not not - ** contain a size value. This happens if it was written by an - ** old version of FTS. In this case it is not possible to determine - ** the size of the segment, and so segment promotion does not - ** take place. */ - bOk = 0; - break; - } - bOk = 1; - } - rc = sqlite3_reset(pRange); - - if( bOk ){ - int iIdx = 0; - sqlite3_stmt *pUpdate1 = 0; - sqlite3_stmt *pUpdate2 = 0; - - if( rc==SQLITE_OK ){ - rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0); - } - if( rc==SQLITE_OK ){ - rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0); - } - - if( rc==SQLITE_OK ){ - - /* Loop through all %_segdir entries for segments in this index with - ** levels equal to or greater than iAbsLevel. As each entry is visited, - ** updated it to set (level = -1) and (idx = N), where N is 0 for the - ** oldest segment in the range, 1 for the next oldest, and so on. - ** - ** In other words, move all segments being promoted to level -1, - ** setting the "idx" fields as appropriate to keep them in the same - ** order. The contents of level -1 (which is never used, except - ** transiently here), will be moved back to level iAbsLevel below. */ - sqlite3_bind_int64(pRange, 1, iAbsLevel); - while( SQLITE_ROW==sqlite3_step(pRange) ){ - sqlite3_bind_int(pUpdate1, 1, iIdx++); - sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0)); - sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1)); - sqlite3_step(pUpdate1); - rc = sqlite3_reset(pUpdate1); - if( rc!=SQLITE_OK ){ - sqlite3_reset(pRange); - break; - } - } - } - if( rc==SQLITE_OK ){ - rc = sqlite3_reset(pRange); - } - - /* Move level -1 to level iAbsLevel */ - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pUpdate2, 1, iAbsLevel); - sqlite3_step(pUpdate2); - rc = sqlite3_reset(pUpdate2); - } - } - } - - - return rc; -} - -/* -** Merge all level iLevel segments in the database into a single -** iLevel+1 segment. Or, if iLevel<0, merge all segments into a -** single segment with a level equal to the numerically largest level -** currently present in the database. -** -** If this function is called with iLevel<0, but there is only one -** segment in the database, SQLITE_DONE is returned immediately. -** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, -** an SQLite error code is returned. -*/ -static int fts3SegmentMerge( - Fts3Table *p, - int iLangid, /* Language id to merge */ - int iIndex, /* Index in p->aIndex[] to merge */ - int iLevel /* Level to merge */ -){ - int rc; /* Return code */ - int iIdx = 0; /* Index of new segment */ - sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */ - SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */ - Fts3SegFilter filter; /* Segment term filter condition */ - Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */ - int bIgnoreEmpty = 0; /* True to ignore empty segments */ - i64 iMaxLevel = 0; /* Max level number for this index/langid */ - - assert( iLevel==FTS3_SEGCURSOR_ALL - || iLevel==FTS3_SEGCURSOR_PENDING - || iLevel>=0 - ); - assert( iLevel=0 && iIndexnIndex ); - - rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr); - if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished; - - if( iLevel!=FTS3_SEGCURSOR_PENDING ){ - rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel); - if( rc!=SQLITE_OK ) goto finished; - } - - if( iLevel==FTS3_SEGCURSOR_ALL ){ - /* This call is to merge all segments in the database to a single - ** segment. The level of the new segment is equal to the numerically - ** greatest segment level currently present in the database for this - ** index. The idx of the new segment is always 0. */ - if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){ - rc = SQLITE_DONE; - goto finished; - } - iNewLevel = iMaxLevel; - bIgnoreEmpty = 1; - - }else{ - /* This call is to merge all segments at level iLevel. find the next - ** available segment index at level iLevel+1. The call to - ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to - ** a single iLevel+2 segment if necessary. */ - assert( FTS3_SEGCURSOR_PENDING==-1 ); - iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1); - rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx); - bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel); - } - if( rc!=SQLITE_OK ) goto finished; - - assert( csr.nSegment>0 ); - assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); - assert_fts3_nc( - iNewLevelnLeafData); - } - } - } - - finished: - fts3SegWriterFree(pWriter); - sqlite3Fts3SegReaderFinish(&csr); - return rc; -} - - -/* -** Flush the contents of pendingTerms to level 0 segments. -*/ -SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){ - int rc = SQLITE_OK; - int i; - - for(i=0; rc==SQLITE_OK && inIndex; i++){ - rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - } - sqlite3Fts3PendingTermsClear(p); - - /* Determine the auto-incr-merge setting if unknown. If enabled, - ** estimate the number of leaf blocks of content to be written - */ - if( rc==SQLITE_OK && p->bHasStat - && p->nAutoincrmerge==0xff && p->nLeafAdd>0 - ){ - sqlite3_stmt *pStmt = 0; - rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); - rc = sqlite3_step(pStmt); - if( rc==SQLITE_ROW ){ - p->nAutoincrmerge = sqlite3_column_int(pStmt, 0); - if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8; - }else if( rc==SQLITE_DONE ){ - p->nAutoincrmerge = 0; - } - rc = sqlite3_reset(pStmt); - } - } - return rc; -} - -/* -** Encode N integers as varints into a blob. -*/ -static void fts3EncodeIntArray( - int N, /* The number of integers to encode */ - u32 *a, /* The integer values */ - char *zBuf, /* Write the BLOB here */ - int *pNBuf /* Write number of bytes if zBuf[] used here */ -){ - int i, j; - for(i=j=0; iiPrevDocid. The sizes are encoded as -** a blob of varints. -*/ -static void fts3InsertDocsize( - int *pRC, /* Result code */ - Fts3Table *p, /* Table into which to insert */ - u32 *aSz /* Sizes of each column, in tokens */ -){ - char *pBlob; /* The BLOB encoding of the document size */ - int nBlob; /* Number of bytes in the BLOB */ - sqlite3_stmt *pStmt; /* Statement used to insert the encoding */ - int rc; /* Result code from subfunctions */ - - if( *pRC ) return; - pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn ); - if( pBlob==0 ){ - *pRC = SQLITE_NOMEM; - return; - } - fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob); - rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0); - if( rc ){ - sqlite3_free(pBlob); - *pRC = rc; - return; - } - sqlite3_bind_int64(pStmt, 1, p->iPrevDocid); - sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free); - sqlite3_step(pStmt); - *pRC = sqlite3_reset(pStmt); -} - -/* -** Record 0 of the %_stat table contains a blob consisting of N varints, -** where N is the number of user defined columns in the fts3 table plus -** two. If nCol is the number of user defined columns, then values of the -** varints are set as follows: -** -** Varint 0: Total number of rows in the table. -** -** Varint 1..nCol: For each column, the total number of tokens stored in -** the column for all rows of the table. -** -** Varint 1+nCol: The total size, in bytes, of all text values in all -** columns of all rows of the table. -** -*/ -static void fts3UpdateDocTotals( - int *pRC, /* The result code */ - Fts3Table *p, /* Table being updated */ - u32 *aSzIns, /* Size increases */ - u32 *aSzDel, /* Size decreases */ - int nChng /* Change in the number of documents */ -){ - char *pBlob; /* Storage for BLOB written into %_stat */ - int nBlob; /* Size of BLOB written into %_stat */ - u32 *a; /* Array of integers that becomes the BLOB */ - sqlite3_stmt *pStmt; /* Statement for reading and writing */ - int i; /* Loop counter */ - int rc; /* Result code from subfunctions */ - - const int nStat = p->nColumn+2; - - if( *pRC ) return; - a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat ); - if( a==0 ){ - *pRC = SQLITE_NOMEM; - return; - } - pBlob = (char*)&a[nStat]; - rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0); - if( rc ){ - sqlite3_free(a); - *pRC = rc; - return; - } - sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); - if( sqlite3_step(pStmt)==SQLITE_ROW ){ - fts3DecodeIntArray(nStat, a, - sqlite3_column_blob(pStmt, 0), - sqlite3_column_bytes(pStmt, 0)); - }else{ - memset(a, 0, sizeof(u32)*(nStat) ); - } - rc = sqlite3_reset(pStmt); - if( rc!=SQLITE_OK ){ - sqlite3_free(a); - *pRC = rc; - return; - } - if( nChng<0 && a[0]<(u32)(-nChng) ){ - a[0] = 0; - }else{ - a[0] += nChng; - } - for(i=0; inColumn+1; i++){ - u32 x = a[i+1]; - if( x+aSzIns[i] < aSzDel[i] ){ - x = 0; - }else{ - x = x + aSzIns[i] - aSzDel[i]; - } - a[i+1] = x; - } - fts3EncodeIntArray(nStat, a, pBlob, &nBlob); - rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); - if( rc ){ - sqlite3_free(a); - *pRC = rc; - return; - } - sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL); - sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC); - sqlite3_step(pStmt); - *pRC = sqlite3_reset(pStmt); - sqlite3_bind_null(pStmt, 2); - sqlite3_free(a); -} - -/* -** Merge the entire database so that there is one segment for each -** iIndex/iLangid combination. -*/ -static int fts3DoOptimize(Fts3Table *p, int bReturnDone){ - int bSeenDone = 0; - int rc; - sqlite3_stmt *pAllLangid = 0; - - rc = sqlite3Fts3PendingTermsFlush(p); - if( rc==SQLITE_OK ){ - rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); - } - if( rc==SQLITE_OK ){ - int rc2; - sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); - sqlite3_bind_int(pAllLangid, 2, p->nIndex); - while( sqlite3_step(pAllLangid)==SQLITE_ROW ){ - int i; - int iLangid = sqlite3_column_int(pAllLangid, 0); - for(i=0; rc==SQLITE_OK && inIndex; i++){ - rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL); - if( rc==SQLITE_DONE ){ - bSeenDone = 1; - rc = SQLITE_OK; - } - } - } - rc2 = sqlite3_reset(pAllLangid); - if( rc==SQLITE_OK ) rc = rc2; - } - - sqlite3Fts3SegmentsClose(p); - - return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc; -} - -/* -** This function is called when the user executes the following statement: -** -** INSERT INTO () VALUES('rebuild'); -** -** The entire FTS index is discarded and rebuilt. If the table is one -** created using the content=xxx option, then the new index is based on -** the current contents of the xxx table. Otherwise, it is rebuilt based -** on the contents of the %_content table. -*/ -static int fts3DoRebuild(Fts3Table *p){ - int rc; /* Return Code */ - - rc = fts3DeleteAll(p, 0); - if( rc==SQLITE_OK ){ - u32 *aSz = 0; - u32 *aSzIns = 0; - u32 *aSzDel = 0; - sqlite3_stmt *pStmt = 0; - int nEntry = 0; - - /* Compose and prepare an SQL statement to loop through the content table */ - char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); - if( !zSql ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - } - - if( rc==SQLITE_OK ){ - sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3; - aSz = (u32 *)sqlite3_malloc64(nByte); - if( aSz==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(aSz, 0, nByte); - aSzIns = &aSz[p->nColumn+1]; - aSzDel = &aSzIns[p->nColumn+1]; - } - } - - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - int iCol; - int iLangid = langidFromSelect(p, pStmt); - rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0)); - memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1)); - for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ - if( p->abNotindexed[iCol]==0 ){ - const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1); - rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]); - aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1); - } - } - if( p->bHasDocsize ){ - fts3InsertDocsize(&rc, p, aSz); - } - if( rc!=SQLITE_OK ){ - sqlite3_finalize(pStmt); - pStmt = 0; - }else{ - nEntry++; - for(iCol=0; iCol<=p->nColumn; iCol++){ - aSzIns[iCol] += aSz[iCol]; - } - } - } - if( p->bFts4 ){ - fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry); - } - sqlite3_free(aSz); - - if( pStmt ){ - int rc2 = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - - return rc; -} - - -/* -** This function opens a cursor used to read the input data for an -** incremental merge operation. Specifically, it opens a cursor to scan -** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute -** level iAbsLevel. -*/ -static int fts3IncrmergeCsr( - Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level to open */ - int nSeg, /* Number of segments to merge */ - Fts3MultiSegReader *pCsr /* Cursor object to populate */ -){ - int rc; /* Return Code */ - sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ - sqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */ - - /* Allocate space for the Fts3MultiSegReader.aCsr[] array */ - memset(pCsr, 0, sizeof(*pCsr)); - nByte = sizeof(Fts3SegReader *) * nSeg; - pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte); - - if( pCsr->apSegment==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pCsr->apSegment, 0, nByte); - rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0); - } - if( rc==SQLITE_OK ){ - int i; - int rc2; - sqlite3_bind_int64(pStmt, 1, iAbsLevel); - assert( pCsr->nSegment==0 ); - for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && iapSegment[i] - ); - pCsr->nSegment++; - } - rc2 = sqlite3_reset(pStmt); - if( rc==SQLITE_OK ) rc = rc2; - } - - return rc; -} - -typedef struct IncrmergeWriter IncrmergeWriter; -typedef struct NodeWriter NodeWriter; -typedef struct Blob Blob; -typedef struct NodeReader NodeReader; - -/* -** An instance of the following structure is used as a dynamic buffer -** to build up nodes or other blobs of data in. -** -** The function blobGrowBuffer() is used to extend the allocation. -*/ -struct Blob { - char *a; /* Pointer to allocation */ - int n; /* Number of valid bytes of data in a[] */ - int nAlloc; /* Allocated size of a[] (nAlloc>=n) */ -}; - -/* -** This structure is used to build up buffers containing segment b-tree -** nodes (blocks). -*/ -struct NodeWriter { - sqlite3_int64 iBlock; /* Current block id */ - Blob key; /* Last key written to the current block */ - Blob block; /* Current block image */ -}; - -/* -** An object of this type contains the state required to create or append -** to an appendable b-tree segment. -*/ -struct IncrmergeWriter { - int nLeafEst; /* Space allocated for leaf blocks */ - int nWork; /* Number of leaf pages flushed */ - sqlite3_int64 iAbsLevel; /* Absolute level of input segments */ - int iIdx; /* Index of *output* segment in iAbsLevel+1 */ - sqlite3_int64 iStart; /* Block number of first allocated block */ - sqlite3_int64 iEnd; /* Block number of last allocated block */ - sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */ - u8 bNoLeafData; /* If true, store 0 for segment size */ - NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT]; -}; - -/* -** An object of the following type is used to read data from a single -** FTS segment node. See the following functions: -** -** nodeReaderInit() -** nodeReaderNext() -** nodeReaderRelease() -*/ -struct NodeReader { - const char *aNode; - int nNode; - int iOff; /* Current offset within aNode[] */ - - /* Output variables. Containing the current node entry. */ - sqlite3_int64 iChild; /* Pointer to child node */ - Blob term; /* Current term */ - const char *aDoclist; /* Pointer to doclist */ - int nDoclist; /* Size of doclist in bytes */ -}; - -/* -** If *pRc is not SQLITE_OK when this function is called, it is a no-op. -** Otherwise, if the allocation at pBlob->a is not already at least nMin -** bytes in size, extend (realloc) it to be so. -** -** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a -** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc -** to reflect the new size of the pBlob->a[] buffer. -*/ -static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){ - if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){ - int nAlloc = nMin; - char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc); - if( a ){ - pBlob->nAlloc = nAlloc; - pBlob->a = a; - }else{ - *pRc = SQLITE_NOMEM; - } - } -} - -/* -** Attempt to advance the node-reader object passed as the first argument to -** the next entry on the node. -** -** Return an error code if an error occurs (SQLITE_NOMEM is possible). -** Otherwise return SQLITE_OK. If there is no next entry on the node -** (e.g. because the current entry is the last) set NodeReader->aNode to -** NULL to indicate EOF. Otherwise, populate the NodeReader structure output -** variables for the new entry. -*/ -static int nodeReaderNext(NodeReader *p){ - int bFirst = (p->term.n==0); /* True for first term on the node */ - int nPrefix = 0; /* Bytes to copy from previous term */ - int nSuffix = 0; /* Bytes to append to the prefix */ - int rc = SQLITE_OK; /* Return code */ - - assert( p->aNode ); - if( p->iChild && bFirst==0 ) p->iChild++; - if( p->iOff>=p->nNode ){ - /* EOF */ - p->aNode = 0; - }else{ - if( bFirst==0 ){ - p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix); - } - p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix); - - if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){ - return FTS_CORRUPT_VTAB; - } - blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc); - if( rc==SQLITE_OK ){ - memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix); - p->term.n = nPrefix+nSuffix; - p->iOff += nSuffix; - if( p->iChild==0 ){ - p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist); - if( (p->nNode-p->iOff)nDoclist ){ - return FTS_CORRUPT_VTAB; - } - p->aDoclist = &p->aNode[p->iOff]; - p->iOff += p->nDoclist; - } - } - } - - assert_fts3_nc( p->iOff<=p->nNode ); - return rc; -} - -/* -** Release all dynamic resources held by node-reader object *p. -*/ -static void nodeReaderRelease(NodeReader *p){ - sqlite3_free(p->term.a); -} - -/* -** Initialize a node-reader object to read the node in buffer aNode/nNode. -** -** If successful, SQLITE_OK is returned and the NodeReader object set to -** point to the first entry on the node (if any). Otherwise, an SQLite -** error code is returned. -*/ -static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){ - memset(p, 0, sizeof(NodeReader)); - p->aNode = aNode; - p->nNode = nNode; - - /* Figure out if this is a leaf or an internal node. */ - if( aNode && aNode[0] ){ - /* An internal node. */ - p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); - }else{ - p->iOff = 1; - } - - return aNode ? nodeReaderNext(p) : SQLITE_OK; -} - -/* -** This function is called while writing an FTS segment each time a leaf o -** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed -** to be greater than the largest key on the node just written, but smaller -** than or equal to the first key that will be written to the next leaf -** node. -** -** The block id of the leaf node just written to disk may be found in -** (pWriter->aNodeWriter[0].iBlock) when this function is called. -*/ -static int fts3IncrmergePush( - Fts3Table *p, /* Fts3 table handle */ - IncrmergeWriter *pWriter, /* Writer object */ - const char *zTerm, /* Term to write to internal node */ - int nTerm /* Bytes at zTerm */ -){ - sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock; - int iLayer; - - assert( nTerm>0 ); - for(iLayer=1; ALWAYS(iLayeraNodeWriter[iLayer]; - int rc = SQLITE_OK; - int nPrefix; - int nSuffix; - int nSpace; - - /* Figure out how much space the key will consume if it is written to - ** the current node of layer iLayer. Due to the prefix compression, - ** the space required changes depending on which node the key is to - ** be added to. */ - nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm); - nSuffix = nTerm - nPrefix; - if(nSuffix<=0 ) return FTS_CORRUPT_VTAB; - nSpace = sqlite3Fts3VarintLen(nPrefix); - nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; - - if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ - /* If the current node of layer iLayer contains zero keys, or if adding - ** the key to it will not cause it to grow to larger than nNodeSize - ** bytes in size, write the key here. */ - - Blob *pBlk = &pNode->block; - if( pBlk->n==0 ){ - blobGrowBuffer(pBlk, p->nNodeSize, &rc); - if( rc==SQLITE_OK ){ - pBlk->a[0] = (char)iLayer; - pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr); - } - } - blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc); - blobGrowBuffer(&pNode->key, nTerm, &rc); - - if( rc==SQLITE_OK ){ - if( pNode->key.n ){ - pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix); - } - pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix); - memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix); - pBlk->n += nSuffix; - - memcpy(pNode->key.a, zTerm, nTerm); - pNode->key.n = nTerm; - } - }else{ - /* Otherwise, flush the current node of layer iLayer to disk. - ** Then allocate a new, empty sibling node. The key will be written - ** into the parent of this node. */ - rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); - - assert( pNode->block.nAlloc>=p->nNodeSize ); - pNode->block.a[0] = (char)iLayer; - pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1); - - iNextPtr = pNode->iBlock; - pNode->iBlock++; - pNode->key.n = 0; - } - - if( rc!=SQLITE_OK || iNextPtr==0 ) return rc; - iPtr = iNextPtr; - } - - assert( 0 ); - return 0; -} - -/* -** Append a term and (optionally) doclist to the FTS segment node currently -** stored in blob *pNode. The node need not contain any terms, but the -** header must be written before this function is called. -** -** A node header is a single 0x00 byte for a leaf node, or a height varint -** followed by the left-hand-child varint for an internal node. -** -** The term to be appended is passed via arguments zTerm/nTerm. For a -** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal -** node, both aDoclist and nDoclist must be passed 0. -** -** If the size of the value in blob pPrev is zero, then this is the first -** term written to the node. Otherwise, pPrev contains a copy of the -** previous term. Before this function returns, it is updated to contain a -** copy of zTerm/nTerm. -** -** It is assumed that the buffer associated with pNode is already large -** enough to accommodate the new entry. The buffer associated with pPrev -** is extended by this function if requrired. -** -** If an error (i.e. OOM condition) occurs, an SQLite error code is -** returned. Otherwise, SQLITE_OK. -*/ -static int fts3AppendToNode( - Blob *pNode, /* Current node image to append to */ - Blob *pPrev, /* Buffer containing previous term written */ - const char *zTerm, /* New term to write */ - int nTerm, /* Size of zTerm in bytes */ - const char *aDoclist, /* Doclist (or NULL) to write */ - int nDoclist /* Size of aDoclist in bytes */ -){ - int rc = SQLITE_OK; /* Return code */ - int bFirst = (pPrev->n==0); /* True if this is the first term written */ - int nPrefix; /* Size of term prefix in bytes */ - int nSuffix; /* Size of term suffix in bytes */ - - /* Node must have already been started. There must be a doclist for a - ** leaf node, and there must not be a doclist for an internal node. */ - assert( pNode->n>0 ); - assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) ); - - blobGrowBuffer(pPrev, nTerm, &rc); - if( rc!=SQLITE_OK ) return rc; - - nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm); - nSuffix = nTerm - nPrefix; - if( nSuffix<=0 ) return FTS_CORRUPT_VTAB; - memcpy(pPrev->a, zTerm, nTerm); - pPrev->n = nTerm; - - if( bFirst==0 ){ - pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix); - } - pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix); - memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix); - pNode->n += nSuffix; - - if( aDoclist ){ - pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist); - memcpy(&pNode->a[pNode->n], aDoclist, nDoclist); - pNode->n += nDoclist; - } - - assert( pNode->n<=pNode->nAlloc ); - - return SQLITE_OK; -} - -/* -** Append the current term and doclist pointed to by cursor pCsr to the -** appendable b-tree segment opened for writing by pWriter. -** -** Return SQLITE_OK if successful, or an SQLite error code otherwise. -*/ -static int fts3IncrmergeAppend( - Fts3Table *p, /* Fts3 table handle */ - IncrmergeWriter *pWriter, /* Writer object */ - Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */ -){ - const char *zTerm = pCsr->zTerm; - int nTerm = pCsr->nTerm; - const char *aDoclist = pCsr->aDoclist; - int nDoclist = pCsr->nDoclist; - int rc = SQLITE_OK; /* Return code */ - int nSpace; /* Total space in bytes required on leaf */ - int nPrefix; /* Size of prefix shared with previous term */ - int nSuffix; /* Size of suffix (nTerm - nPrefix) */ - NodeWriter *pLeaf; /* Object used to write leaf nodes */ - - pLeaf = &pWriter->aNodeWriter[0]; - nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm); - nSuffix = nTerm - nPrefix; - - nSpace = sqlite3Fts3VarintLen(nPrefix); - nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; - nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; - - /* If the current block is not empty, and if adding this term/doclist - ** to the current block would make it larger than Fts3Table.nNodeSize - ** bytes, write this block out to the database. */ - if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){ - rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n); - pWriter->nWork++; - - /* Add the current term to the parent node. The term added to the - ** parent must: - ** - ** a) be greater than the largest term on the leaf node just written - ** to the database (still available in pLeaf->key), and - ** - ** b) be less than or equal to the term about to be added to the new - ** leaf node (zTerm/nTerm). - ** - ** In other words, it must be the prefix of zTerm 1 byte longer than - ** the common prefix (if any) of zTerm and pWriter->zTerm. - */ - if( rc==SQLITE_OK ){ - rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1); - } - - /* Advance to the next output block */ - pLeaf->iBlock++; - pLeaf->key.n = 0; - pLeaf->block.n = 0; - - nSuffix = nTerm; - nSpace = 1; - nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix; - nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist; - } - - pWriter->nLeafData += nSpace; - blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc); - if( rc==SQLITE_OK ){ - if( pLeaf->block.n==0 ){ - pLeaf->block.n = 1; - pLeaf->block.a[0] = '\0'; - } - rc = fts3AppendToNode( - &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist - ); - } - - return rc; -} - -/* -** This function is called to release all dynamic resources held by the -** merge-writer object pWriter, and if no error has occurred, to flush -** all outstanding node buffers held by pWriter to disk. -** -** If *pRc is not SQLITE_OK when this function is called, then no attempt -** is made to write any data to disk. Instead, this function serves only -** to release outstanding resources. -** -** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while -** flushing buffers to disk, *pRc is set to an SQLite error code before -** returning. -*/ -static void fts3IncrmergeRelease( - Fts3Table *p, /* FTS3 table handle */ - IncrmergeWriter *pWriter, /* Merge-writer object */ - int *pRc /* IN/OUT: Error code */ -){ - int i; /* Used to iterate through non-root layers */ - int iRoot; /* Index of root in pWriter->aNodeWriter */ - NodeWriter *pRoot; /* NodeWriter for root node */ - int rc = *pRc; /* Error code */ - - /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment - ** root node. If the segment fits entirely on a single leaf node, iRoot - ** will be set to 0. If the root node is the parent of the leaves, iRoot - ** will be 1. And so on. */ - for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){ - NodeWriter *pNode = &pWriter->aNodeWriter[iRoot]; - if( pNode->block.n>0 ) break; - assert( *pRc || pNode->block.nAlloc==0 ); - assert( *pRc || pNode->key.nAlloc==0 ); - sqlite3_free(pNode->block.a); - sqlite3_free(pNode->key.a); - } - - /* Empty output segment. This is a no-op. */ - if( iRoot<0 ) return; - - /* The entire output segment fits on a single node. Normally, this means - ** the node would be stored as a blob in the "root" column of the %_segdir - ** table. However, this is not permitted in this case. The problem is that - ** space has already been reserved in the %_segments table, and so the - ** start_block and end_block fields of the %_segdir table must be populated. - ** And, by design or by accident, released versions of FTS cannot handle - ** segments that fit entirely on the root node with start_block!=0. - ** - ** Instead, create a synthetic root node that contains nothing but a - ** pointer to the single content node. So that the segment consists of a - ** single leaf and a single interior (root) node. - ** - ** Todo: Better might be to defer allocating space in the %_segments - ** table until we are sure it is needed. - */ - if( iRoot==0 ){ - Blob *pBlock = &pWriter->aNodeWriter[1].block; - blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc); - if( rc==SQLITE_OK ){ - pBlock->a[0] = 0x01; - pBlock->n = 1 + sqlite3Fts3PutVarint( - &pBlock->a[1], pWriter->aNodeWriter[0].iBlock - ); - } - iRoot = 1; - } - pRoot = &pWriter->aNodeWriter[iRoot]; - - /* Flush all currently outstanding nodes to disk. */ - for(i=0; iaNodeWriter[i]; - if( pNode->block.n>0 && rc==SQLITE_OK ){ - rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n); - } - sqlite3_free(pNode->block.a); - sqlite3_free(pNode->key.a); - } - - /* Write the %_segdir record. */ - if( rc==SQLITE_OK ){ - rc = fts3WriteSegdir(p, - pWriter->iAbsLevel+1, /* level */ - pWriter->iIdx, /* idx */ - pWriter->iStart, /* start_block */ - pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */ - pWriter->iEnd, /* end_block */ - (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */ - pRoot->block.a, pRoot->block.n /* root */ - ); - } - sqlite3_free(pRoot->block.a); - sqlite3_free(pRoot->key.a); - - *pRc = rc; -} - -/* -** Compare the term in buffer zLhs (size in bytes nLhs) with that in -** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of -** the other, it is considered to be smaller than the other. -** -** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve -** if it is greater. -*/ -static int fts3TermCmp( - const char *zLhs, int nLhs, /* LHS of comparison */ - const char *zRhs, int nRhs /* RHS of comparison */ -){ - int nCmp = MIN(nLhs, nRhs); - int res; - - res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0); - if( res==0 ) res = nLhs - nRhs; - - return res; -} - - -/* -** Query to see if the entry in the %_segments table with blockid iEnd is -** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before -** returning. Otherwise, set *pbRes to 0. -** -** Or, if an error occurs while querying the database, return an SQLite -** error code. The final value of *pbRes is undefined in this case. -** -** This is used to test if a segment is an "appendable" segment. If it -** is, then a NULL entry has been inserted into the %_segments table -** with blockid %_segdir.end_block. -*/ -static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){ - int bRes = 0; /* Result to set *pbRes to */ - sqlite3_stmt *pCheck = 0; /* Statement to query database with */ - int rc; /* Return code */ - - rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pCheck, 1, iEnd); - if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1; - rc = sqlite3_reset(pCheck); - } - - *pbRes = bRes; - return rc; -} - -/* -** This function is called when initializing an incremental-merge operation. -** It checks if the existing segment with index value iIdx at absolute level -** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the -** merge-writer object *pWriter is initialized to write to it. -** -** An existing segment can be appended to by an incremental merge if: -** -** * It was initially created as an appendable segment (with all required -** space pre-allocated), and -** -** * The first key read from the input (arguments zKey and nKey) is -** greater than the largest key currently stored in the potential -** output segment. -*/ -static int fts3IncrmergeLoad( - Fts3Table *p, /* Fts3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ - int iIdx, /* Index of candidate output segment */ - const char *zKey, /* First key to write */ - int nKey, /* Number of bytes in nKey */ - IncrmergeWriter *pWriter /* Populate this object */ -){ - int rc; /* Return code */ - sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */ - - rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0); - if( rc==SQLITE_OK ){ - sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */ - sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */ - sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */ - const char *aRoot = 0; /* Pointer to %_segdir.root buffer */ - int nRoot = 0; /* Size of aRoot[] in bytes */ - int rc2; /* Return code from sqlite3_reset() */ - int bAppendable = 0; /* Set to true if segment is appendable */ - - /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */ - sqlite3_bind_int64(pSelect, 1, iAbsLevel+1); - sqlite3_bind_int(pSelect, 2, iIdx); - if( sqlite3_step(pSelect)==SQLITE_ROW ){ - iStart = sqlite3_column_int64(pSelect, 1); - iLeafEnd = sqlite3_column_int64(pSelect, 2); - fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData); - if( pWriter->nLeafData<0 ){ - pWriter->nLeafData = pWriter->nLeafData * -1; - } - pWriter->bNoLeafData = (pWriter->nLeafData==0); - nRoot = sqlite3_column_bytes(pSelect, 4); - aRoot = sqlite3_column_blob(pSelect, 4); - if( aRoot==0 ){ - sqlite3_reset(pSelect); - return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB; - } - }else{ - return sqlite3_reset(pSelect); - } - - /* Check for the zero-length marker in the %_segments table */ - rc = fts3IsAppendable(p, iEnd, &bAppendable); - - /* Check that zKey/nKey is larger than the largest key the candidate */ - if( rc==SQLITE_OK && bAppendable ){ - char *aLeaf = 0; - int nLeaf = 0; - - rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0); - if( rc==SQLITE_OK ){ - NodeReader reader; - for(rc = nodeReaderInit(&reader, aLeaf, nLeaf); - rc==SQLITE_OK && reader.aNode; - rc = nodeReaderNext(&reader) - ){ - assert( reader.aNode ); - } - if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){ - bAppendable = 0; - } - nodeReaderRelease(&reader); - } - sqlite3_free(aLeaf); - } - - if( rc==SQLITE_OK && bAppendable ){ - /* It is possible to append to this segment. Set up the IncrmergeWriter - ** object to do so. */ - int i; - int nHeight = (int)aRoot[0]; - NodeWriter *pNode; - if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){ - sqlite3_reset(pSelect); - return FTS_CORRUPT_VTAB; - } - - pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT; - pWriter->iStart = iStart; - pWriter->iEnd = iEnd; - pWriter->iAbsLevel = iAbsLevel; - pWriter->iIdx = iIdx; - - for(i=nHeight+1; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; - } - - pNode = &pWriter->aNodeWriter[nHeight]; - pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight; - blobGrowBuffer(&pNode->block, - MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc - ); - if( rc==SQLITE_OK ){ - memcpy(pNode->block.a, aRoot, nRoot); - pNode->block.n = nRoot; - memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING); - } - - for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){ - NodeReader reader; - pNode = &pWriter->aNodeWriter[i]; - - if( pNode->block.a){ - rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n); - while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader); - blobGrowBuffer(&pNode->key, reader.term.n, &rc); - if( rc==SQLITE_OK ){ - memcpy(pNode->key.a, reader.term.a, reader.term.n); - pNode->key.n = reader.term.n; - if( i>0 ){ - char *aBlock = 0; - int nBlock = 0; - pNode = &pWriter->aNodeWriter[i-1]; - pNode->iBlock = reader.iChild; - rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0); - blobGrowBuffer(&pNode->block, - MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc - ); - if( rc==SQLITE_OK ){ - memcpy(pNode->block.a, aBlock, nBlock); - pNode->block.n = nBlock; - memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING); - } - sqlite3_free(aBlock); - } - } - } - nodeReaderRelease(&reader); - } - } - - rc2 = sqlite3_reset(pSelect); - if( rc==SQLITE_OK ) rc = rc2; - } - - return rc; -} - -/* -** Determine the largest segment index value that exists within absolute -** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus -** one before returning SQLITE_OK. Or, if there are no segments at all -** within level iAbsLevel, set *piIdx to zero. -** -** If an error occurs, return an SQLite error code. The final value of -** *piIdx is undefined in this case. -*/ -static int fts3IncrmergeOutputIdx( - Fts3Table *p, /* FTS Table handle */ - sqlite3_int64 iAbsLevel, /* Absolute index of input segments */ - int *piIdx /* OUT: Next free index at iAbsLevel+1 */ -){ - int rc; - sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */ - - rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1); - sqlite3_step(pOutputIdx); - *piIdx = sqlite3_column_int(pOutputIdx, 0); - rc = sqlite3_reset(pOutputIdx); - } - - return rc; -} - -/* -** Allocate an appendable output segment on absolute level iAbsLevel+1 -** with idx value iIdx. -** -** In the %_segdir table, a segment is defined by the values in three -** columns: -** -** start_block -** leaves_end_block -** end_block -** -** When an appendable segment is allocated, it is estimated that the -** maximum number of leaf blocks that may be required is the sum of the -** number of leaf blocks consumed by the input segments, plus the number -** of input segments, multiplied by two. This value is stored in stack -** variable nLeafEst. -** -** A total of 16*nLeafEst blocks are allocated when an appendable segment -** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous -** array of leaf nodes starts at the first block allocated. The array -** of interior nodes that are parents of the leaf nodes start at block -** (start_block + (1 + end_block - start_block) / 16). And so on. -** -** In the actual code below, the value "16" is replaced with the -** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT. -*/ -static int fts3IncrmergeWriter( - Fts3Table *p, /* Fts3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level of input segments */ - int iIdx, /* Index of new output segment */ - Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */ - IncrmergeWriter *pWriter /* Populate this object */ -){ - int rc; /* Return Code */ - int i; /* Iterator variable */ - int nLeafEst = 0; /* Blocks allocated for leaf nodes */ - sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ - sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ - - /* Calculate nLeafEst. */ - rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pLeafEst, 1, iAbsLevel); - sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); - if( SQLITE_ROW==sqlite3_step(pLeafEst) ){ - nLeafEst = sqlite3_column_int(pLeafEst, 0); - } - rc = sqlite3_reset(pLeafEst); - } - if( rc!=SQLITE_OK ) return rc; - - /* Calculate the first block to use in the output segment */ - rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0); - if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){ - pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0); - pWriter->iEnd = pWriter->iStart - 1; - pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT; - } - rc = sqlite3_reset(pFirstBlock); - } - if( rc!=SQLITE_OK ) return rc; - - /* Insert the marker in the %_segments table to make sure nobody tries - ** to steal the space just allocated. This is also used to identify - ** appendable segments. */ - rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0); - if( rc!=SQLITE_OK ) return rc; - - pWriter->iAbsLevel = iAbsLevel; - pWriter->nLeafEst = nLeafEst; - pWriter->iIdx = iIdx; - - /* Set up the array of NodeWriter objects */ - for(i=0; iaNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst; - } - return SQLITE_OK; -} - -/* -** Remove an entry from the %_segdir table. This involves running the -** following two statements: -** -** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx -** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx -** -** The DELETE statement removes the specific %_segdir level. The UPDATE -** statement ensures that the remaining segments have contiguously allocated -** idx values. -*/ -static int fts3RemoveSegdirEntry( - Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level to delete from */ - int iIdx /* Index of %_segdir entry to delete */ -){ - int rc; /* Return code */ - sqlite3_stmt *pDelete = 0; /* DELETE statement */ - - rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDelete, 1, iAbsLevel); - sqlite3_bind_int(pDelete, 2, iIdx); - sqlite3_step(pDelete); - rc = sqlite3_reset(pDelete); - } - - return rc; -} - -/* -** One or more segments have just been removed from absolute level iAbsLevel. -** Update the 'idx' values of the remaining segments in the level so that -** the idx values are a contiguous sequence starting from 0. -*/ -static int fts3RepackSegdirLevel( - Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel /* Absolute level to repack */ -){ - int rc; /* Return code */ - int *aIdx = 0; /* Array of remaining idx values */ - int nIdx = 0; /* Valid entries in aIdx[] */ - int nAlloc = 0; /* Allocated size of aIdx[] */ - int i; /* Iterator variable */ - sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */ - sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */ - - rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0); - if( rc==SQLITE_OK ){ - int rc2; - sqlite3_bind_int64(pSelect, 1, iAbsLevel); - while( SQLITE_ROW==sqlite3_step(pSelect) ){ - if( nIdx>=nAlloc ){ - int *aNew; - nAlloc += 16; - aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int)); - if( !aNew ){ - rc = SQLITE_NOMEM; - break; - } - aIdx = aNew; - } - aIdx[nIdx++] = sqlite3_column_int(pSelect, 0); - } - rc2 = sqlite3_reset(pSelect); - if( rc==SQLITE_OK ) rc = rc2; - } - - if( rc==SQLITE_OK ){ - rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0); - } - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pUpdate, 2, iAbsLevel); - } - - assert( p->bIgnoreSavepoint==0 ); - p->bIgnoreSavepoint = 1; - for(i=0; rc==SQLITE_OK && ibIgnoreSavepoint = 0; - - sqlite3_free(aIdx); - return rc; -} - -static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){ - pNode->a[0] = (char)iHeight; - if( iChild ){ - assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) ); - pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild); - }else{ - assert( pNode->nAlloc>=1 ); - pNode->n = 1; - } -} - -/* -** The first two arguments are a pointer to and the size of a segment b-tree -** node. The node may be a leaf or an internal node. -** -** This function creates a new node image in blob object *pNew by copying -** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes) -** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode. -*/ -static int fts3TruncateNode( - const char *aNode, /* Current node image */ - int nNode, /* Size of aNode in bytes */ - Blob *pNew, /* OUT: Write new node image here */ - const char *zTerm, /* Omit all terms smaller than this */ - int nTerm, /* Size of zTerm in bytes */ - sqlite3_int64 *piBlock /* OUT: Block number in next layer down */ -){ - NodeReader reader; /* Reader object */ - Blob prev = {0, 0, 0}; /* Previous term written to new node */ - int rc = SQLITE_OK; /* Return code */ - int bLeaf; /* True for a leaf node */ - - if( nNode<1 ) return FTS_CORRUPT_VTAB; - bLeaf = aNode[0]=='\0'; - - /* Allocate required output space */ - blobGrowBuffer(pNew, nNode, &rc); - if( rc!=SQLITE_OK ) return rc; - pNew->n = 0; - - /* Populate new node buffer */ - for(rc = nodeReaderInit(&reader, aNode, nNode); - rc==SQLITE_OK && reader.aNode; - rc = nodeReaderNext(&reader) - ){ - if( pNew->n==0 ){ - int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm); - if( res<0 || (bLeaf==0 && res==0) ) continue; - fts3StartNode(pNew, (int)aNode[0], reader.iChild); - *piBlock = reader.iChild; - } - rc = fts3AppendToNode( - pNew, &prev, reader.term.a, reader.term.n, - reader.aDoclist, reader.nDoclist - ); - if( rc!=SQLITE_OK ) break; - } - if( pNew->n==0 ){ - fts3StartNode(pNew, (int)aNode[0], reader.iChild); - *piBlock = reader.iChild; - } - assert( pNew->n<=pNew->nAlloc ); - - nodeReaderRelease(&reader); - sqlite3_free(prev.a); - return rc; -} - -/* -** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute -** level iAbsLevel. This may involve deleting entries from the %_segments -** table, and modifying existing entries in both the %_segments and %_segdir -** tables. -** -** SQLITE_OK is returned if the segment is updated successfully. Or an -** SQLite error code otherwise. -*/ -static int fts3TruncateSegment( - Fts3Table *p, /* FTS3 table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */ - int iIdx, /* Index within level of segment to modify */ - const char *zTerm, /* Remove terms smaller than this */ - int nTerm /* Number of bytes in buffer zTerm */ -){ - int rc = SQLITE_OK; /* Return code */ - Blob root = {0,0,0}; /* New root page image */ - Blob block = {0,0,0}; /* Buffer used for any other block */ - sqlite3_int64 iBlock = 0; /* Block id */ - sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */ - sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */ - sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */ - - rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0); - if( rc==SQLITE_OK ){ - int rc2; /* sqlite3_reset() return code */ - sqlite3_bind_int64(pFetch, 1, iAbsLevel); - sqlite3_bind_int(pFetch, 2, iIdx); - if( SQLITE_ROW==sqlite3_step(pFetch) ){ - const char *aRoot = sqlite3_column_blob(pFetch, 4); - int nRoot = sqlite3_column_bytes(pFetch, 4); - iOldStart = sqlite3_column_int64(pFetch, 1); - rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock); - } - rc2 = sqlite3_reset(pFetch); - if( rc==SQLITE_OK ) rc = rc2; - } - - while( rc==SQLITE_OK && iBlock ){ - char *aBlock = 0; - int nBlock = 0; - iNewStart = iBlock; - - rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0); - if( rc==SQLITE_OK ){ - rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock); - } - if( rc==SQLITE_OK ){ - rc = fts3WriteSegment(p, iNewStart, block.a, block.n); - } - sqlite3_free(aBlock); - } - - /* Variable iNewStart now contains the first valid leaf node. */ - if( rc==SQLITE_OK && iNewStart ){ - sqlite3_stmt *pDel = 0; - rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pDel, 1, iOldStart); - sqlite3_bind_int64(pDel, 2, iNewStart-1); - sqlite3_step(pDel); - rc = sqlite3_reset(pDel); - } - } - - if( rc==SQLITE_OK ){ - sqlite3_stmt *pChomp = 0; - rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pChomp, 1, iNewStart); - sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC); - sqlite3_bind_int64(pChomp, 3, iAbsLevel); - sqlite3_bind_int(pChomp, 4, iIdx); - sqlite3_step(pChomp); - rc = sqlite3_reset(pChomp); - sqlite3_bind_null(pChomp, 2); - } - } - - sqlite3_free(root.a); - sqlite3_free(block.a); - return rc; -} - -/* -** This function is called after an incrmental-merge operation has run to -** merge (or partially merge) two or more segments from absolute level -** iAbsLevel. -** -** Each input segment is either removed from the db completely (if all of -** its data was copied to the output segment by the incrmerge operation) -** or modified in place so that it no longer contains those entries that -** have been duplicated in the output segment. -*/ -static int fts3IncrmergeChomp( - Fts3Table *p, /* FTS table handle */ - sqlite3_int64 iAbsLevel, /* Absolute level containing segments */ - Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */ - int *pnRem /* Number of segments not deleted */ -){ - int i; - int nRem = 0; - int rc = SQLITE_OK; - - for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){ - Fts3SegReader *pSeg = 0; - int j; - - /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding - ** somewhere in the pCsr->apSegment[] array. */ - for(j=0; ALWAYS(jnSegment); j++){ - pSeg = pCsr->apSegment[j]; - if( pSeg->iIdx==i ) break; - } - assert( jnSegment && pSeg->iIdx==i ); - - if( pSeg->aNode==0 ){ - /* Seg-reader is at EOF. Remove the entire input segment. */ - rc = fts3DeleteSegment(p, pSeg); - if( rc==SQLITE_OK ){ - rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx); - } - *pnRem = 0; - }else{ - /* The incremental merge did not copy all the data from this - ** segment to the upper level. The segment is modified in place - ** so that it contains no keys smaller than zTerm/nTerm. */ - const char *zTerm = pSeg->zTerm; - int nTerm = pSeg->nTerm; - rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm); - nRem++; - } - } - - if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){ - rc = fts3RepackSegdirLevel(p, iAbsLevel); - } - - *pnRem = nRem; - return rc; -} - -/* -** Store an incr-merge hint in the database. -*/ -static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){ - sqlite3_stmt *pReplace = 0; - int rc; /* Return code */ - - rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT); - sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC); - sqlite3_step(pReplace); - rc = sqlite3_reset(pReplace); - sqlite3_bind_null(pReplace, 2); - } - - return rc; -} - -/* -** Load an incr-merge hint from the database. The incr-merge hint, if one -** exists, is stored in the rowid==1 row of the %_stat table. -** -** If successful, populate blob *pHint with the value read from the %_stat -** table and return SQLITE_OK. Otherwise, if an error occurs, return an -** SQLite error code. -*/ -static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){ - sqlite3_stmt *pSelect = 0; - int rc; - - pHint->n = 0; - rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0); - if( rc==SQLITE_OK ){ - int rc2; - sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT); - if( SQLITE_ROW==sqlite3_step(pSelect) ){ - const char *aHint = sqlite3_column_blob(pSelect, 0); - int nHint = sqlite3_column_bytes(pSelect, 0); - if( aHint ){ - blobGrowBuffer(pHint, nHint, &rc); - if( rc==SQLITE_OK ){ - memcpy(pHint->a, aHint, nHint); - pHint->n = nHint; - } - } - } - rc2 = sqlite3_reset(pSelect); - if( rc==SQLITE_OK ) rc = rc2; - } - - return rc; -} - -/* -** If *pRc is not SQLITE_OK when this function is called, it is a no-op. -** Otherwise, append an entry to the hint stored in blob *pHint. Each entry -** consists of two varints, the absolute level number of the input segments -** and the number of input segments. -** -** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs, -** set *pRc to an SQLite error code before returning. -*/ -static void fts3IncrmergeHintPush( - Blob *pHint, /* Hint blob to append to */ - i64 iAbsLevel, /* First varint to store in hint */ - int nInput, /* Second varint to store in hint */ - int *pRc /* IN/OUT: Error code */ -){ - blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc); - if( *pRc==SQLITE_OK ){ - pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel); - pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput); - } -} - -/* -** Read the last entry (most recently pushed) from the hint blob *pHint -** and then remove the entry. Write the two values read to *piAbsLevel and -** *pnInput before returning. -** -** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does -** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB. -*/ -static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){ - const int nHint = pHint->n; - int i; - - i = pHint->n-1; - if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB; - while( i>0 && (pHint->a[i-1] & 0x80) ) i--; - if( i==0 ) return FTS_CORRUPT_VTAB; - i--; - while( i>0 && (pHint->a[i-1] & 0x80) ) i--; - - pHint->n = i; - i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel); - i += fts3GetVarint32(&pHint->a[i], pnInput); - assert( i<=nHint ); - if( i!=nHint ) return FTS_CORRUPT_VTAB; - - return SQLITE_OK; -} - - -/* -** Attempt an incremental merge that writes nMerge leaf blocks. -** -** Incremental merges happen nMin segments at a time. The segments -** to be merged are the nMin oldest segments (the ones with the smallest -** values for the _segdir.idx field) in the highest level that contains -** at least nMin segments. Multiple merges might occur in an attempt to -** write the quota of nMerge leaf blocks. -*/ -SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){ - int rc; /* Return code */ - int nRem = nMerge; /* Number of leaf pages yet to be written */ - Fts3MultiSegReader *pCsr; /* Cursor used to read input data */ - Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */ - IncrmergeWriter *pWriter; /* Writer object */ - int nSeg = 0; /* Number of input segments */ - sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */ - Blob hint = {0, 0, 0}; /* Hint read from %_stat table */ - int bDirtyHint = 0; /* True if blob 'hint' has been modified */ - - /* Allocate space for the cursor, filter and writer objects */ - const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter); - pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc); - if( !pWriter ) return SQLITE_NOMEM; - pFilter = (Fts3SegFilter *)&pWriter[1]; - pCsr = (Fts3MultiSegReader *)&pFilter[1]; - - rc = fts3IncrmergeHintLoad(p, &hint); - while( rc==SQLITE_OK && nRem>0 ){ - const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex; - sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */ - int bUseHint = 0; /* True if attempting to append */ - int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */ - - /* Search the %_segdir table for the absolute level with the smallest - ** relative level number that contains at least nMin segments, if any. - ** If one is found, set iAbsLevel to the absolute level number and - ** nSeg to nMin. If no level with at least nMin segments can be found, - ** set nSeg to -1. - */ - rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0); - sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin)); - if( sqlite3_step(pFindLevel)==SQLITE_ROW ){ - iAbsLevel = sqlite3_column_int64(pFindLevel, 0); - nSeg = sqlite3_column_int(pFindLevel, 1); - assert( nSeg>=2 ); - }else{ - nSeg = -1; - } - rc = sqlite3_reset(pFindLevel); - - /* If the hint read from the %_stat table is not empty, check if the - ** last entry in it specifies a relative level smaller than or equal - ** to the level identified by the block above (if any). If so, this - ** iteration of the loop will work on merging at the hinted level. - */ - if( rc==SQLITE_OK && hint.n ){ - int nHint = hint.n; - sqlite3_int64 iHintAbsLevel = 0; /* Hint level */ - int nHintSeg = 0; /* Hint number of segments */ - - rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg); - if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){ - /* Based on the scan in the block above, it is known that there - ** are no levels with a relative level smaller than that of - ** iAbsLevel with more than nSeg segments, or if nSeg is -1, - ** no levels with more than nMin segments. Use this to limit the - ** value of nHintSeg to avoid a large memory allocation in case the - ** merge-hint is corrupt*/ - iAbsLevel = iHintAbsLevel; - nSeg = MIN(MAX(nMin,nSeg), nHintSeg); - bUseHint = 1; - bDirtyHint = 1; - }else{ - /* This undoes the effect of the HintPop() above - so that no entry - ** is removed from the hint blob. */ - hint.n = nHint; - } - } - - /* If nSeg is less that zero, then there is no level with at least - ** nMin segments and no hint in the %_stat table. No work to do. - ** Exit early in this case. */ - if( nSeg<=0 ) break; - - assert( nMod<=0x7FFFFFFF ); - if( iAbsLevel<0 || iAbsLevel>(nMod<<32) ){ - rc = FTS_CORRUPT_VTAB; - break; - } - - /* Open a cursor to iterate through the contents of the oldest nSeg - ** indexes of absolute level iAbsLevel. If this cursor is opened using - ** the 'hint' parameters, it is possible that there are less than nSeg - ** segments available in level iAbsLevel. In this case, no work is - ** done on iAbsLevel - fall through to the next iteration of the loop - ** to start work on some other level. */ - memset(pWriter, 0, nAlloc); - pFilter->flags = FTS3_SEGMENT_REQUIRE_POS; - - if( rc==SQLITE_OK ){ - rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx); - assert( bUseHint==1 || bUseHint==0 ); - if( iIdx==0 || (bUseHint && iIdx==1) ){ - int bIgnore = 0; - rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore); - if( bIgnore ){ - pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY; - } - } - } - - if( rc==SQLITE_OK ){ - rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr); - } - if( SQLITE_OK==rc && pCsr->nSegment==nSeg - && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter)) - ){ - int bEmpty = 0; - rc = sqlite3Fts3SegReaderStep(p, pCsr); - if( rc==SQLITE_OK ){ - bEmpty = 1; - }else if( rc!=SQLITE_ROW ){ - sqlite3Fts3SegReaderFinish(pCsr); - break; - } - if( bUseHint && iIdx>0 ){ - const char *zKey = pCsr->zTerm; - int nKey = pCsr->nTerm; - rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter); - }else{ - rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter); - } - - if( rc==SQLITE_OK && pWriter->nLeafEst ){ - fts3LogMerge(nSeg, iAbsLevel); - if( bEmpty==0 ){ - do { - rc = fts3IncrmergeAppend(p, pWriter, pCsr); - if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr); - if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK; - }while( rc==SQLITE_ROW ); - } - - /* Update or delete the input segments */ - if( rc==SQLITE_OK ){ - nRem -= (1 + pWriter->nWork); - rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg); - if( nSeg!=0 ){ - bDirtyHint = 1; - fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc); - } - } - } - - if( nSeg!=0 ){ - pWriter->nLeafData = pWriter->nLeafData * -1; - } - fts3IncrmergeRelease(p, pWriter, &rc); - if( nSeg==0 && pWriter->bNoLeafData==0 ){ - fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData); - } - } - - sqlite3Fts3SegReaderFinish(pCsr); - } - - /* Write the hint values into the %_stat table for the next incr-merger */ - if( bDirtyHint && rc==SQLITE_OK ){ - rc = fts3IncrmergeHintStore(p, &hint); - } - - sqlite3_free(pWriter); - sqlite3_free(hint.a); - return rc; -} - -/* -** Convert the text beginning at *pz into an integer and return -** its value. Advance *pz to point to the first character past -** the integer. -** -** This function used for parameters to merge= and incrmerge= -** commands. -*/ -static int fts3Getint(const char **pz){ - const char *z = *pz; - int i = 0; - while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0'; - *pz = z; - return i; -} - -/* -** Process statements of the form: -** -** INSERT INTO table(table) VALUES('merge=A,B'); -** -** A and B are integers that decode to be the number of leaf pages -** written for the merge, and the minimum number of segments on a level -** before it will be selected for a merge, respectively. -*/ -static int fts3DoIncrmerge( - Fts3Table *p, /* FTS3 table handle */ - const char *zParam /* Nul-terminated string containing "A,B" */ -){ - int rc; - int nMin = (MergeCount(p) / 2); - int nMerge = 0; - const char *z = zParam; - - /* Read the first integer value */ - nMerge = fts3Getint(&z); - - /* If the first integer value is followed by a ',', read the second - ** integer value. */ - if( z[0]==',' && z[1]!='\0' ){ - z++; - nMin = fts3Getint(&z); - } - - if( z[0]!='\0' || nMin<2 ){ - rc = SQLITE_ERROR; - }else{ - rc = SQLITE_OK; - if( !p->bHasStat ){ - assert( p->bFts4==0 ); - sqlite3Fts3CreateStatTable(&rc, p); - } - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3Incrmerge(p, nMerge, nMin); - } - sqlite3Fts3SegmentsClose(p); - } - return rc; -} - -/* -** Process statements of the form: -** -** INSERT INTO table(table) VALUES('automerge=X'); -** -** where X is an integer. X==0 means to turn automerge off. X!=0 means -** turn it on. The setting is persistent. -*/ -static int fts3DoAutoincrmerge( - Fts3Table *p, /* FTS3 table handle */ - const char *zParam /* Nul-terminated string containing boolean */ -){ - int rc = SQLITE_OK; - sqlite3_stmt *pStmt = 0; - p->nAutoincrmerge = fts3Getint(&zParam); - if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){ - p->nAutoincrmerge = 8; - } - if( !p->bHasStat ){ - assert( p->bFts4==0 ); - sqlite3Fts3CreateStatTable(&rc, p); - if( rc ) return rc; - } - rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0); - if( rc ) return rc; - sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE); - sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge); - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); - return rc; -} - -/* -** Return a 64-bit checksum for the FTS index entry specified by the -** arguments to this function. -*/ -static u64 fts3ChecksumEntry( - const char *zTerm, /* Pointer to buffer containing term */ - int nTerm, /* Size of zTerm in bytes */ - int iLangid, /* Language id for current row */ - int iIndex, /* Index (0..Fts3Table.nIndex-1) */ - i64 iDocid, /* Docid for current row. */ - int iCol, /* Column number */ - int iPos /* Position */ -){ - int i; - u64 ret = (u64)iDocid; - - ret += (ret<<3) + iLangid; - ret += (ret<<3) + iIndex; - ret += (ret<<3) + iCol; - ret += (ret<<3) + iPos; - for(i=0; inIndex-1) */ - int *pRc /* OUT: Return code */ -){ - Fts3SegFilter filter; - Fts3MultiSegReader csr; - int rc; - u64 cksum = 0; - - assert( *pRc==SQLITE_OK ); - - memset(&filter, 0, sizeof(filter)); - memset(&csr, 0, sizeof(csr)); - filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; - filter.flags |= FTS3_SEGMENT_SCAN; - - rc = sqlite3Fts3SegReaderCursor( - p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr - ); - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); - } - - if( rc==SQLITE_OK ){ - while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){ - char *pCsr = csr.aDoclist; - char *pEnd = &pCsr[csr.nDoclist]; - - i64 iDocid = 0; - i64 iCol = 0; - u64 iPos = 0; - - pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); - while( pCsrbDescIdx ){ - iDocid = (i64)((u64)iDocid - iVal); - }else{ - iDocid = (i64)((u64)iDocid + iVal); - } - } - }else{ - iPos += (iVal - 2); - cksum = cksum ^ fts3ChecksumEntry( - csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid, - (int)iCol, (int)iPos - ); - } - } - } - } - } - sqlite3Fts3SegReaderFinish(&csr); - - *pRc = rc; - return cksum; -} - -/* -** Check if the contents of the FTS index match the current contents of the -** content table. If no error occurs and the contents do match, set *pbOk -** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk -** to false before returning. -** -** If an error occurs (e.g. an OOM or IO error), return an SQLite error -** code. The final value of *pbOk is undefined in this case. -*/ -static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){ - int rc = SQLITE_OK; /* Return code */ - u64 cksum1 = 0; /* Checksum based on FTS index contents */ - u64 cksum2 = 0; /* Checksum based on %_content contents */ - sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */ - - /* This block calculates the checksum according to the FTS index. */ - rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); - if( rc==SQLITE_OK ){ - int rc2; - sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid); - sqlite3_bind_int(pAllLangid, 2, p->nIndex); - while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){ - int iLangid = sqlite3_column_int(pAllLangid, 0); - int i; - for(i=0; inIndex; i++){ - cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc); - } - } - rc2 = sqlite3_reset(pAllLangid); - if( rc==SQLITE_OK ) rc = rc2; - } - - /* This block calculates the checksum according to the %_content table */ - if( rc==SQLITE_OK ){ - sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; - sqlite3_stmt *pStmt = 0; - char *zSql; - - zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist); - if( !zSql ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - } - - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - i64 iDocid = sqlite3_column_int64(pStmt, 0); - int iLang = langidFromSelect(p, pStmt); - int iCol; - - for(iCol=0; rc==SQLITE_OK && iColnColumn; iCol++){ - if( p->abNotindexed[iCol]==0 ){ - const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1); - sqlite3_tokenizer_cursor *pT = 0; - - rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT); - while( rc==SQLITE_OK ){ - char const *zToken; /* Buffer containing token */ - int nToken = 0; /* Number of bytes in token */ - int iDum1 = 0, iDum2 = 0; /* Dummy variables */ - int iPos = 0; /* Position of token in zText */ - - rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos); - if( rc==SQLITE_OK ){ - int i; - cksum2 = cksum2 ^ fts3ChecksumEntry( - zToken, nToken, iLang, 0, iDocid, iCol, iPos - ); - for(i=1; inIndex; i++){ - if( p->aIndex[i].nPrefix<=nToken ){ - cksum2 = cksum2 ^ fts3ChecksumEntry( - zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos - ); - } - } - } - } - if( pT ) pModule->xClose(pT); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - } - } - } - - sqlite3_finalize(pStmt); - } - - *pbOk = (cksum1==cksum2); - return rc; -} - -/* -** Run the integrity-check. If no error occurs and the current contents of -** the FTS index are correct, return SQLITE_OK. Or, if the contents of the -** FTS index are incorrect, return SQLITE_CORRUPT_VTAB. -** -** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite -** error code. -** -** The integrity-check works as follows. For each token and indexed token -** prefix in the document set, a 64-bit checksum is calculated (by code -** in fts3ChecksumEntry()) based on the following: -** -** + The index number (0 for the main index, 1 for the first prefix -** index etc.), -** + The token (or token prefix) text itself, -** + The language-id of the row it appears in, -** + The docid of the row it appears in, -** + The column it appears in, and -** + The tokens position within that column. -** -** The checksums for all entries in the index are XORed together to create -** a single checksum for the entire index. -** -** The integrity-check code calculates the same checksum in two ways: -** -** 1. By scanning the contents of the FTS index, and -** 2. By scanning and tokenizing the content table. -** -** If the two checksums are identical, the integrity-check is deemed to have -** passed. -*/ -static int fts3DoIntegrityCheck( - Fts3Table *p /* FTS3 table handle */ -){ - int rc; - int bOk = 0; - rc = fts3IntegrityCheck(p, &bOk); - if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB; - return rc; -} - -/* -** Handle a 'special' INSERT of the form: -** -** "INSERT INTO tbl(tbl) VALUES()" -** -** Argument pVal contains the result of . Currently the only -** meaningful value to insert is the text 'optimize'. -*/ -static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ - int rc = SQLITE_ERROR; /* Return Code */ - const char *zVal = (const char *)sqlite3_value_text(pVal); - int nVal = sqlite3_value_bytes(pVal); - - if( !zVal ){ - return SQLITE_NOMEM; - }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ - rc = fts3DoOptimize(p, 0); - }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ - rc = fts3DoRebuild(p); - }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ - rc = fts3DoIntegrityCheck(p); - }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ - rc = fts3DoIncrmerge(p, &zVal[6]); - }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ - rc = fts3DoAutoincrmerge(p, &zVal[10]); -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - }else{ - int v; - if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ - v = atoi(&zVal[9]); - if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v; - rc = SQLITE_OK; - }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ - v = atoi(&zVal[11]); - if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v; - rc = SQLITE_OK; - }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){ - p->bNoIncrDoclist = atoi(&zVal[21]); - rc = SQLITE_OK; - }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,"mergecount=",11) ){ - v = atoi(&zVal[11]); - if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v; - rc = SQLITE_OK; - } -#endif - } - return rc; -} - -#ifndef SQLITE_DISABLE_FTS4_DEFERRED -/* -** Delete all cached deferred doclists. Deferred doclists are cached -** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function. -*/ -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){ - Fts3DeferredToken *pDef; - for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){ - fts3PendingListDelete(pDef->pList); - pDef->pList = 0; - } -} - -/* -** Free all entries in the pCsr->pDeffered list. Entries are added to -** this list using sqlite3Fts3DeferToken(). -*/ -SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){ - Fts3DeferredToken *pDef; - Fts3DeferredToken *pNext; - for(pDef=pCsr->pDeferred; pDef; pDef=pNext){ - pNext = pDef->pNext; - fts3PendingListDelete(pDef->pList); - sqlite3_free(pDef); - } - pCsr->pDeferred = 0; -} - -/* -** Generate deferred-doclists for all tokens in the pCsr->pDeferred list -** based on the row that pCsr currently points to. -** -** A deferred-doclist is like any other doclist with position information -** included, except that it only contains entries for a single row of the -** table, not for all rows. -*/ -SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){ - int rc = SQLITE_OK; /* Return code */ - if( pCsr->pDeferred ){ - int i; /* Used to iterate through table columns */ - sqlite3_int64 iDocid; /* Docid of the row pCsr points to */ - Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */ - - Fts3Table *p = (Fts3Table *)pCsr->base.pVtab; - sqlite3_tokenizer *pT = p->pTokenizer; - sqlite3_tokenizer_module const *pModule = pT->pModule; - - assert( pCsr->isRequireSeek==0 ); - iDocid = sqlite3_column_int64(pCsr->pStmt, 0); - - for(i=0; inColumn && rc==SQLITE_OK; i++){ - if( p->abNotindexed[i]==0 ){ - const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1); - sqlite3_tokenizer_cursor *pTC = 0; - - rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC); - while( rc==SQLITE_OK ){ - char const *zToken; /* Buffer containing token */ - int nToken = 0; /* Number of bytes in token */ - int iDum1 = 0, iDum2 = 0; /* Dummy variables */ - int iPos = 0; /* Position of token in zText */ - - rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos); - for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ - Fts3PhraseToken *pPT = pDef->pToken; - if( (pDef->iCol>=p->nColumn || pDef->iCol==i) - && (pPT->bFirst==0 || iPos==0) - && (pPT->n==nToken || (pPT->isPrefix && pPT->nz, pPT->n)) - ){ - fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc); - } - } - } - if( pTC ) pModule->xClose(pTC); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - } - } - - for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){ - if( pDef->pList ){ - rc = fts3PendingListAppendVarint(&pDef->pList, 0); - } - } - } - - return rc; -} - -SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList( - Fts3DeferredToken *p, - char **ppData, - int *pnData -){ - char *pRet; - int nSkip; - sqlite3_int64 dummy; - - *ppData = 0; - *pnData = 0; - - if( p->pList==0 ){ - return SQLITE_OK; - } - - pRet = (char *)sqlite3_malloc(p->pList->nData); - if( !pRet ) return SQLITE_NOMEM; - - nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy); - *pnData = p->pList->nData - nSkip; - *ppData = pRet; - - memcpy(pRet, &p->pList->aData[nSkip], *pnData); - return SQLITE_OK; -} - -/* -** Add an entry for token pToken to the pCsr->pDeferred list. -*/ -SQLITE_PRIVATE int sqlite3Fts3DeferToken( - Fts3Cursor *pCsr, /* Fts3 table cursor */ - Fts3PhraseToken *pToken, /* Token to defer */ - int iCol /* Column that token must appear in (or -1) */ -){ - Fts3DeferredToken *pDeferred; - pDeferred = sqlite3_malloc(sizeof(*pDeferred)); - if( !pDeferred ){ - return SQLITE_NOMEM; - } - memset(pDeferred, 0, sizeof(*pDeferred)); - pDeferred->pToken = pToken; - pDeferred->pNext = pCsr->pDeferred; - pDeferred->iCol = iCol; - pCsr->pDeferred = pDeferred; - - assert( pToken->pDeferred==0 ); - pToken->pDeferred = pDeferred; - - return SQLITE_OK; -} -#endif - -/* -** SQLite value pRowid contains the rowid of a row that may or may not be -** present in the FTS3 table. If it is, delete it and adjust the contents -** of subsiduary data structures accordingly. -*/ -static int fts3DeleteByRowid( - Fts3Table *p, - sqlite3_value *pRowid, - int *pnChng, /* IN/OUT: Decrement if row is deleted */ - u32 *aSzDel -){ - int rc = SQLITE_OK; /* Return code */ - int bFound = 0; /* True if *pRowid really is in the table */ - - fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound); - if( bFound && rc==SQLITE_OK ){ - int isEmpty = 0; /* Deleting *pRowid leaves the table empty */ - rc = fts3IsEmpty(p, pRowid, &isEmpty); - if( rc==SQLITE_OK ){ - if( isEmpty ){ - /* Deleting this row means the whole table is empty. In this case - ** delete the contents of all three tables and throw away any - ** data in the pendingTerms hash table. */ - rc = fts3DeleteAll(p, 1); - *pnChng = 0; - memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2); - }else{ - *pnChng = *pnChng - 1; - if( p->zContentTbl==0 ){ - fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid); - } - if( p->bHasDocsize ){ - fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid); - } - } - } - } - - return rc; -} - -/* -** This function does the work for the xUpdate method of FTS3 virtual -** tables. The schema of the virtual table being: -** -** CREATE TABLE
    ( -** , -**
    HIDDEN, -** docid HIDDEN, -** HIDDEN -** ); -** -** -*/ -SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( - sqlite3_vtab *pVtab, /* FTS3 vtab object */ - int nArg, /* Size of argument array */ - sqlite3_value **apVal, /* Array of arguments */ - sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */ -){ - Fts3Table *p = (Fts3Table *)pVtab; - int rc = SQLITE_OK; /* Return Code */ - u32 *aSzIns = 0; /* Sizes of inserted documents */ - u32 *aSzDel = 0; /* Sizes of deleted documents */ - int nChng = 0; /* Net change in number of documents */ - int bInsertDone = 0; - - /* At this point it must be known if the %_stat table exists or not. - ** So bHasStat may not be 2. */ - assert( p->bHasStat==0 || p->bHasStat==1 ); - - assert( p->pSegments==0 ); - assert( - nArg==1 /* DELETE operations */ - || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */ - ); - - /* Check for a "special" INSERT operation. One of the form: - ** - ** INSERT INTO xyz(xyz) VALUES('command'); - */ - if( nArg>1 - && sqlite3_value_type(apVal[0])==SQLITE_NULL - && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL - ){ - rc = fts3SpecialInsert(p, apVal[p->nColumn+2]); - goto update_out; - } - - if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){ - rc = SQLITE_CONSTRAINT; - goto update_out; - } - - /* Allocate space to hold the change in document sizes */ - aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2); - if( aSzDel==0 ){ - rc = SQLITE_NOMEM; - goto update_out; - } - aSzIns = &aSzDel[p->nColumn+1]; - memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2); - - rc = fts3Writelock(p); - if( rc!=SQLITE_OK ) goto update_out; - - /* If this is an INSERT operation, or an UPDATE that modifies the rowid - ** value, then this operation requires constraint handling. - ** - ** If the on-conflict mode is REPLACE, this means that the existing row - ** should be deleted from the database before inserting the new row. Or, - ** if the on-conflict mode is other than REPLACE, then this method must - ** detect the conflict and return SQLITE_CONSTRAINT before beginning to - ** modify the database file. - */ - if( nArg>1 && p->zContentTbl==0 ){ - /* Find the value object that holds the new rowid value. */ - sqlite3_value *pNewRowid = apVal[3+p->nColumn]; - if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){ - pNewRowid = apVal[1]; - } - - if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( - sqlite3_value_type(apVal[0])==SQLITE_NULL - || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid) - )){ - /* The new rowid is not NULL (in this case the rowid will be - ** automatically assigned and there is no chance of a conflict), and - ** the statement is either an INSERT or an UPDATE that modifies the - ** rowid column. So if the conflict mode is REPLACE, then delete any - ** existing row with rowid=pNewRowid. - ** - ** Or, if the conflict mode is not REPLACE, insert the new record into - ** the %_content table. If we hit the duplicate rowid constraint (or any - ** other error) while doing so, return immediately. - ** - ** This branch may also run if pNewRowid contains a value that cannot - ** be losslessly converted to an integer. In this case, the eventual - ** call to fts3InsertData() (either just below or further on in this - ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is - ** invoked, it will delete zero rows (since no row will have - ** docid=$pNewRowid if $pNewRowid is not an integer value). - */ - if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){ - rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel); - }else{ - rc = fts3InsertData(p, apVal, pRowid); - bInsertDone = 1; - } - } - } - if( rc!=SQLITE_OK ){ - goto update_out; - } - - /* If this is a DELETE or UPDATE operation, remove the old record. */ - if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ - assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER ); - rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel); - } - - /* If this is an INSERT or UPDATE operation, insert the new record. */ - if( nArg>1 && rc==SQLITE_OK ){ - int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]); - if( bInsertDone==0 ){ - rc = fts3InsertData(p, apVal, pRowid); - if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){ - rc = FTS_CORRUPT_VTAB; - } - } - if( rc==SQLITE_OK ){ - rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid); - } - if( rc==SQLITE_OK ){ - assert( p->iPrevDocid==*pRowid ); - rc = fts3InsertTerms(p, iLangid, apVal, aSzIns); - } - if( p->bHasDocsize ){ - fts3InsertDocsize(&rc, p, aSzIns); - } - nChng++; - } - - if( p->bFts4 ){ - fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng); - } - - update_out: - sqlite3_free(aSzDel); - sqlite3Fts3SegmentsClose(p); - return rc; -} - -/* -** Flush any data in the pending-terms hash table to disk. If successful, -** merge all segments in the database (including the new segment, if -** there was any data to flush) into a single segment. -*/ -SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){ - int rc; - rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0); - if( rc==SQLITE_OK ){ - rc = fts3DoOptimize(p, 1); - if( rc==SQLITE_OK || rc==SQLITE_DONE ){ - int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); - if( rc2!=SQLITE_OK ) rc = rc2; - }else{ - sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0); - sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0); - } - } - sqlite3Fts3SegmentsClose(p); - return rc; -} - -#endif - -/************** End of fts3_write.c ******************************************/ -/************** Begin file fts3_snippet.c ************************************/ -/* -** 2009 Oct 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. -** -****************************************************************************** -*/ - -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ - -/* -** Characters that may appear in the second argument to matchinfo(). -*/ -#define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */ -#define FTS3_MATCHINFO_NCOL 'c' /* 1 value */ -#define FTS3_MATCHINFO_NDOC 'n' /* 1 value */ -#define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */ -#define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */ -#define FTS3_MATCHINFO_LCS 's' /* nCol values */ -#define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */ -#define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */ -#define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */ - -/* -** The default value for the second argument to matchinfo(). -*/ -#define FTS3_MATCHINFO_DEFAULT "pcx" - - -/* -** Used as an fts3ExprIterate() context when loading phrase doclists to -** Fts3Expr.aDoclist[]/nDoclist. -*/ -typedef struct LoadDoclistCtx LoadDoclistCtx; -struct LoadDoclistCtx { - Fts3Cursor *pCsr; /* FTS3 Cursor */ - int nPhrase; /* Number of phrases seen so far */ - int nToken; /* Number of tokens seen so far */ -}; - -/* -** The following types are used as part of the implementation of the -** fts3BestSnippet() routine. -*/ -typedef struct SnippetIter SnippetIter; -typedef struct SnippetPhrase SnippetPhrase; -typedef struct SnippetFragment SnippetFragment; - -struct SnippetIter { - Fts3Cursor *pCsr; /* Cursor snippet is being generated from */ - int iCol; /* Extract snippet from this column */ - int nSnippet; /* Requested snippet length (in tokens) */ - int nPhrase; /* Number of phrases in query */ - SnippetPhrase *aPhrase; /* Array of size nPhrase */ - int iCurrent; /* First token of current snippet */ -}; - -struct SnippetPhrase { - int nToken; /* Number of tokens in phrase */ - char *pList; /* Pointer to start of phrase position list */ - int iHead; /* Next value in position list */ - char *pHead; /* Position list data following iHead */ - int iTail; /* Next value in trailing position list */ - char *pTail; /* Position list data following iTail */ -}; - -struct SnippetFragment { - int iCol; /* Column snippet is extracted from */ - int iPos; /* Index of first token in snippet */ - u64 covered; /* Mask of query phrases covered */ - u64 hlmask; /* Mask of snippet terms to highlight */ -}; - -/* -** This type is used as an fts3ExprIterate() context object while -** accumulating the data returned by the matchinfo() function. -*/ -typedef struct MatchInfo MatchInfo; -struct MatchInfo { - Fts3Cursor *pCursor; /* FTS3 Cursor */ - int nCol; /* Number of columns in table */ - int nPhrase; /* Number of matchable phrases in query */ - sqlite3_int64 nDoc; /* Number of docs in database */ - char flag; - u32 *aMatchinfo; /* Pre-allocated buffer */ -}; - -/* -** An instance of this structure is used to manage a pair of buffers, each -** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below -** for details. -*/ -struct MatchinfoBuffer { - u8 aRef[3]; - int nElem; - int bGlobal; /* Set if global data is loaded */ - char *zMatchinfo; - u32 aMatchinfo[1]; -}; - - -/* -** The snippet() and offsets() functions both return text values. An instance -** of the following structure is used to accumulate those values while the -** functions are running. See fts3StringAppend() for details. -*/ -typedef struct StrBuffer StrBuffer; -struct StrBuffer { - char *z; /* Pointer to buffer containing string */ - int n; /* Length of z in bytes (excl. nul-term) */ - int nAlloc; /* Allocated size of buffer z in bytes */ -}; - - -/************************************************************************* -** Start of MatchinfoBuffer code. -*/ - -/* -** Allocate a two-slot MatchinfoBuffer object. -*/ -static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){ - MatchinfoBuffer *pRet; - sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1) - + sizeof(MatchinfoBuffer); - sqlite3_int64 nStr = strlen(zMatchinfo); - - pRet = sqlite3_malloc64(nByte + nStr+1); - if( pRet ){ - memset(pRet, 0, nByte); - pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet; - pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] - + sizeof(u32)*((int)nElem+1); - pRet->nElem = (int)nElem; - pRet->zMatchinfo = ((char*)pRet) + nByte; - memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1); - pRet->aRef[0] = 1; - } - - return pRet; -} - -static void fts3MIBufferFree(void *p){ - MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]); - - assert( (u32*)p==&pBuf->aMatchinfo[1] - || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] - ); - if( (u32*)p==&pBuf->aMatchinfo[1] ){ - pBuf->aRef[1] = 0; - }else{ - pBuf->aRef[2] = 0; - } - - if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){ - sqlite3_free(pBuf); - } -} - -static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ - void (*xRet)(void*) = 0; - u32 *aOut = 0; - - if( p->aRef[1]==0 ){ - p->aRef[1] = 1; - aOut = &p->aMatchinfo[1]; - xRet = fts3MIBufferFree; - } - else if( p->aRef[2]==0 ){ - p->aRef[2] = 1; - aOut = &p->aMatchinfo[p->nElem+2]; - xRet = fts3MIBufferFree; - }else{ - aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32)); - if( aOut ){ - xRet = sqlite3_free; - if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32)); - } - } - - *paOut = aOut; - return xRet; -} - -static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){ - p->bGlobal = 1; - memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32)); -} - -/* -** Free a MatchinfoBuffer object allocated using fts3MIBufferNew() -*/ -SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){ - if( p ){ - assert( p->aRef[0]==1 ); - p->aRef[0] = 0; - if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){ - sqlite3_free(p); - } - } -} - -/* -** End of MatchinfoBuffer code. -*************************************************************************/ - - -/* -** This function is used to help iterate through a position-list. A position -** list is a list of unique integers, sorted from smallest to largest. Each -** element of the list is represented by an FTS3 varint that takes the value -** of the difference between the current element and the previous one plus -** two. For example, to store the position-list: -** -** 4 9 113 -** -** the three varints: -** -** 6 7 106 -** -** are encoded. -** -** When this function is called, *pp points to the start of an element of -** the list. *piPos contains the value of the previous entry in the list. -** After it returns, *piPos contains the value of the next element of the -** list and *pp is advanced to the following varint. -*/ -static void fts3GetDeltaPosition(char **pp, int *piPos){ - int iVal; - *pp += fts3GetVarint32(*pp, &iVal); - *piPos += (iVal-2); -} - -/* -** Helper function for fts3ExprIterate() (see below). -*/ -static int fts3ExprIterate2( - Fts3Expr *pExpr, /* Expression to iterate phrases of */ - int *piPhrase, /* Pointer to phrase counter */ - int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ - void *pCtx /* Second argument to pass to callback */ -){ - int rc; /* Return code */ - int eType = pExpr->eType; /* Type of expression node pExpr */ - - if( eType!=FTSQUERY_PHRASE ){ - assert( pExpr->pLeft && pExpr->pRight ); - rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx); - if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){ - rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx); - } - }else{ - rc = x(pExpr, *piPhrase, pCtx); - (*piPhrase)++; - } - return rc; -} - -/* -** Iterate through all phrase nodes in an FTS3 query, except those that -** are part of a sub-tree that is the right-hand-side of a NOT operator. -** For each phrase node found, the supplied callback function is invoked. -** -** If the callback function returns anything other than SQLITE_OK, -** the iteration is abandoned and the error code returned immediately. -** Otherwise, SQLITE_OK is returned after a callback has been made for -** all eligible phrase nodes. -*/ -static int fts3ExprIterate( - Fts3Expr *pExpr, /* Expression to iterate phrases of */ - int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */ - void *pCtx /* Second argument to pass to callback */ -){ - int iPhrase = 0; /* Variable used as the phrase counter */ - return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx); -} - - -/* -** This is an fts3ExprIterate() callback used while loading the doclists -** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also -** fts3ExprLoadDoclists(). -*/ -static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ - int rc = SQLITE_OK; - Fts3Phrase *pPhrase = pExpr->pPhrase; - LoadDoclistCtx *p = (LoadDoclistCtx *)ctx; - - UNUSED_PARAMETER(iPhrase); - - p->nPhrase++; - p->nToken += pPhrase->nToken; - - return rc; -} - -/* -** Load the doclists for each phrase in the query associated with FTS3 cursor -** pCsr. -** -** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable -** phrases in the expression (all phrases except those directly or -** indirectly descended from the right-hand-side of a NOT operator). If -** pnToken is not NULL, then it is set to the number of tokens in all -** matchable phrases of the expression. -*/ -static int fts3ExprLoadDoclists( - Fts3Cursor *pCsr, /* Fts3 cursor for current query */ - int *pnPhrase, /* OUT: Number of phrases in query */ - int *pnToken /* OUT: Number of tokens in query */ -){ - int rc; /* Return Code */ - LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */ - sCtx.pCsr = pCsr; - rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx); - if( pnPhrase ) *pnPhrase = sCtx.nPhrase; - if( pnToken ) *pnToken = sCtx.nToken; - return rc; -} - -static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ - (*(int *)ctx)++; - pExpr->iPhrase = iPhrase; - return SQLITE_OK; -} -static int fts3ExprPhraseCount(Fts3Expr *pExpr){ - int nPhrase = 0; - (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase); - return nPhrase; -} - -/* -** Advance the position list iterator specified by the first two -** arguments so that it points to the first element with a value greater -** than or equal to parameter iNext. -*/ -static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){ - char *pIter = *ppIter; - if( pIter ){ - int iIter = *piIter; - - while( iIteriCurrent<0 ){ - /* The SnippetIter object has just been initialized. The first snippet - ** candidate always starts at offset 0 (even if this candidate has a - ** score of 0.0). - */ - pIter->iCurrent = 0; - - /* Advance the 'head' iterator of each phrase to the first offset that - ** is greater than or equal to (iNext+nSnippet). - */ - for(i=0; inPhrase; i++){ - SnippetPhrase *pPhrase = &pIter->aPhrase[i]; - fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet); - } - }else{ - int iStart; - int iEnd = 0x7FFFFFFF; - - for(i=0; inPhrase; i++){ - SnippetPhrase *pPhrase = &pIter->aPhrase[i]; - if( pPhrase->pHead && pPhrase->iHeadiHead; - } - } - if( iEnd==0x7FFFFFFF ){ - return 1; - } - - pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1; - for(i=0; inPhrase; i++){ - SnippetPhrase *pPhrase = &pIter->aPhrase[i]; - fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1); - fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart); - } - } - - return 0; -} - -/* -** Retrieve information about the current candidate snippet of snippet -** iterator pIter. -*/ -static void fts3SnippetDetails( - SnippetIter *pIter, /* Snippet iterator */ - u64 mCovered, /* Bitmask of phrases already covered */ - int *piToken, /* OUT: First token of proposed snippet */ - int *piScore, /* OUT: "Score" for this snippet */ - u64 *pmCover, /* OUT: Bitmask of phrases covered */ - u64 *pmHighlight /* OUT: Bitmask of terms to highlight */ -){ - int iStart = pIter->iCurrent; /* First token of snippet */ - int iScore = 0; /* Score of this snippet */ - int i; /* Loop counter */ - u64 mCover = 0; /* Mask of phrases covered by this snippet */ - u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */ - - for(i=0; inPhrase; i++){ - SnippetPhrase *pPhrase = &pIter->aPhrase[i]; - if( pPhrase->pTail ){ - char *pCsr = pPhrase->pTail; - int iCsr = pPhrase->iTail; - - while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){ - int j; - u64 mPhrase = (u64)1 << (i%64); - u64 mPos = (u64)1 << (iCsr - iStart); - assert( iCsr>=iStart && (iCsr - iStart)<=64 ); - assert( i>=0 ); - if( (mCover|mCovered)&mPhrase ){ - iScore++; - }else{ - iScore += 1000; - } - mCover |= mPhrase; - - for(j=0; jnToken; j++){ - mHighlight |= (mPos>>j); - } - - if( 0==(*pCsr & 0x0FE) ) break; - fts3GetDeltaPosition(&pCsr, &iCsr); - } - } - } - - /* Set the output variables before returning. */ - *piToken = iStart; - *piScore = iScore; - *pmCover = mCover; - *pmHighlight = mHighlight; -} - -/* -** This function is an fts3ExprIterate() callback used by fts3BestSnippet(). -** Each invocation populates an element of the SnippetIter.aPhrase[] array. -*/ -static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){ - SnippetIter *p = (SnippetIter *)ctx; - SnippetPhrase *pPhrase = &p->aPhrase[iPhrase]; - char *pCsr; - int rc; - - pPhrase->nToken = pExpr->pPhrase->nToken; - rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr); - assert( rc==SQLITE_OK || pCsr==0 ); - if( pCsr ){ - int iFirst = 0; - pPhrase->pList = pCsr; - fts3GetDeltaPosition(&pCsr, &iFirst); - if( iFirst<0 ){ - rc = FTS_CORRUPT_VTAB; - }else{ - pPhrase->pHead = pCsr; - pPhrase->pTail = pCsr; - pPhrase->iHead = iFirst; - pPhrase->iTail = iFirst; - } - }else{ - assert( rc!=SQLITE_OK || ( - pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 - )); - } - - return rc; -} - -/* -** Select the fragment of text consisting of nFragment contiguous tokens -** from column iCol that represent the "best" snippet. The best snippet -** is the snippet with the highest score, where scores are calculated -** by adding: -** -** (a) +1 point for each occurrence of a matchable phrase in the snippet. -** -** (b) +1000 points for the first occurrence of each matchable phrase in -** the snippet for which the corresponding mCovered bit is not set. -** -** The selected snippet parameters are stored in structure *pFragment before -** returning. The score of the selected snippet is stored in *piScore -** before returning. -*/ -static int fts3BestSnippet( - int nSnippet, /* Desired snippet length */ - Fts3Cursor *pCsr, /* Cursor to create snippet for */ - int iCol, /* Index of column to create snippet from */ - u64 mCovered, /* Mask of phrases already covered */ - u64 *pmSeen, /* IN/OUT: Mask of phrases seen */ - SnippetFragment *pFragment, /* OUT: Best snippet found */ - int *piScore /* OUT: Score of snippet pFragment */ -){ - int rc; /* Return Code */ - int nList; /* Number of phrases in expression */ - SnippetIter sIter; /* Iterates through snippet candidates */ - sqlite3_int64 nByte; /* Number of bytes of space to allocate */ - int iBestScore = -1; /* Best snippet score found so far */ - int i; /* Loop counter */ - - memset(&sIter, 0, sizeof(sIter)); - - /* Iterate through the phrases in the expression to count them. The same - ** callback makes sure the doclists are loaded for each phrase. - */ - rc = fts3ExprLoadDoclists(pCsr, &nList, 0); - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Now that it is known how many phrases there are, allocate and zero - ** the required space using malloc(). - */ - nByte = sizeof(SnippetPhrase) * nList; - sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte); - if( !sIter.aPhrase ){ - return SQLITE_NOMEM; - } - memset(sIter.aPhrase, 0, nByte); - - /* Initialize the contents of the SnippetIter object. Then iterate through - ** the set of phrases in the expression to populate the aPhrase[] array. - */ - sIter.pCsr = pCsr; - sIter.iCol = iCol; - sIter.nSnippet = nSnippet; - sIter.nPhrase = nList; - sIter.iCurrent = -1; - rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter); - if( rc==SQLITE_OK ){ - - /* Set the *pmSeen output variable. */ - for(i=0; iiCol = iCol; - while( !fts3SnippetNextCandidate(&sIter) ){ - int iPos; - int iScore; - u64 mCover; - u64 mHighlite; - fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite); - assert( iScore>=0 ); - if( iScore>iBestScore ){ - pFragment->iPos = iPos; - pFragment->hlmask = mHighlite; - pFragment->covered = mCover; - iBestScore = iScore; - } - } - - *piScore = iBestScore; - } - sqlite3_free(sIter.aPhrase); - return rc; -} - - -/* -** Append a string to the string-buffer passed as the first argument. -** -** If nAppend is negative, then the length of the string zAppend is -** determined using strlen(). -*/ -static int fts3StringAppend( - StrBuffer *pStr, /* Buffer to append to */ - const char *zAppend, /* Pointer to data to append to buffer */ - int nAppend /* Size of zAppend in bytes (or -1) */ -){ - if( nAppend<0 ){ - nAppend = (int)strlen(zAppend); - } - - /* If there is insufficient space allocated at StrBuffer.z, use realloc() - ** to grow the buffer until so that it is big enough to accomadate the - ** appended data. - */ - if( pStr->n+nAppend+1>=pStr->nAlloc ){ - sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100; - char *zNew = sqlite3_realloc64(pStr->z, nAlloc); - if( !zNew ){ - return SQLITE_NOMEM; - } - pStr->z = zNew; - pStr->nAlloc = nAlloc; - } - assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) ); - - /* Append the data to the string buffer. */ - memcpy(&pStr->z[pStr->n], zAppend, nAppend); - pStr->n += nAppend; - pStr->z[pStr->n] = '\0'; - - return SQLITE_OK; -} - -/* -** The fts3BestSnippet() function often selects snippets that end with a -** query term. That is, the final term of the snippet is always a term -** that requires highlighting. For example, if 'X' is a highlighted term -** and '.' is a non-highlighted term, BestSnippet() may select: -** -** ........X.....X -** -** This function "shifts" the beginning of the snippet forward in the -** document so that there are approximately the same number of -** non-highlighted terms to the right of the final highlighted term as there -** are to the left of the first highlighted term. For example, to this: -** -** ....X.....X.... -** -** This is done as part of extracting the snippet text, not when selecting -** the snippet. Snippet selection is done based on doclists only, so there -** is no way for fts3BestSnippet() to know whether or not the document -** actually contains terms that follow the final highlighted term. -*/ -static int fts3SnippetShift( - Fts3Table *pTab, /* FTS3 table snippet comes from */ - int iLangid, /* Language id to use in tokenizing */ - int nSnippet, /* Number of tokens desired for snippet */ - const char *zDoc, /* Document text to extract snippet from */ - int nDoc, /* Size of buffer zDoc in bytes */ - int *piPos, /* IN/OUT: First token of snippet */ - u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */ -){ - u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */ - - if( hlmask ){ - int nLeft; /* Tokens to the left of first highlight */ - int nRight; /* Tokens to the right of last highlight */ - int nDesired; /* Ideal number of tokens to shift forward */ - - for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++); - for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++); - assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 ); - nDesired = (nLeft-nRight)/2; - - /* Ideally, the start of the snippet should be pushed forward in the - ** document nDesired tokens. This block checks if there are actually - ** nDesired tokens to the right of the snippet. If so, *piPos and - ** *pHlMask are updated to shift the snippet nDesired tokens to the - ** right. Otherwise, the snippet is shifted by the number of tokens - ** available. - */ - if( nDesired>0 ){ - int nShift; /* Number of tokens to shift snippet by */ - int iCurrent = 0; /* Token counter */ - int rc; /* Return Code */ - sqlite3_tokenizer_module *pMod; - sqlite3_tokenizer_cursor *pC; - pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; - - /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired) - ** or more tokens in zDoc/nDoc. - */ - rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC); - if( rc!=SQLITE_OK ){ - return rc; - } - while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){ - const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0; - rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent); - } - pMod->xClose(pC); - if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; } - - nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet; - assert( nShift<=nDesired ); - if( nShift>0 ){ - *piPos += nShift; - *pHlmask = hlmask >> nShift; - } - } - } - return SQLITE_OK; -} - -/* -** Extract the snippet text for fragment pFragment from cursor pCsr and -** append it to string buffer pOut. -*/ -static int fts3SnippetText( - Fts3Cursor *pCsr, /* FTS3 Cursor */ - SnippetFragment *pFragment, /* Snippet to extract */ - int iFragment, /* Fragment number */ - int isLast, /* True for final fragment in snippet */ - int nSnippet, /* Number of tokens in extracted snippet */ - const char *zOpen, /* String inserted before highlighted term */ - const char *zClose, /* String inserted after highlighted term */ - const char *zEllipsis, /* String inserted between snippets */ - StrBuffer *pOut /* Write output here */ -){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int rc; /* Return code */ - const char *zDoc; /* Document text to extract snippet from */ - int nDoc; /* Size of zDoc in bytes */ - int iCurrent = 0; /* Current token number of document */ - int iEnd = 0; /* Byte offset of end of current token */ - int isShiftDone = 0; /* True after snippet is shifted */ - int iPos = pFragment->iPos; /* First token of snippet */ - u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */ - int iCol = pFragment->iCol+1; /* Query column to extract text from */ - sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */ - sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */ - - zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol); - if( zDoc==0 ){ - if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){ - return SQLITE_NOMEM; - } - return SQLITE_OK; - } - nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol); - - /* Open a token cursor on the document. */ - pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule; - rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC); - if( rc!=SQLITE_OK ){ - return rc; - } - - while( rc==SQLITE_OK ){ - const char *ZDUMMY; /* Dummy argument used with tokenizer */ - int DUMMY1 = -1; /* Dummy argument used with tokenizer */ - int iBegin = 0; /* Offset in zDoc of start of token */ - int iFin = 0; /* Offset in zDoc of end of token */ - int isHighlight = 0; /* True for highlighted terms */ - - /* Variable DUMMY1 is initialized to a negative value above. Elsewhere - ** in the FTS code the variable that the third argument to xNext points to - ** is initialized to zero before the first (*but not necessarily - ** subsequent*) call to xNext(). This is done for a particular application - ** that needs to know whether or not the tokenizer is being used for - ** snippet generation or for some other purpose. - ** - ** Extreme care is required when writing code to depend on this - ** initialization. It is not a documented part of the tokenizer interface. - ** If a tokenizer is used directly by any code outside of FTS, this - ** convention might not be respected. */ - rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent); - if( rc!=SQLITE_OK ){ - if( rc==SQLITE_DONE ){ - /* Special case - the last token of the snippet is also the last token - ** of the column. Append any punctuation that occurred between the end - ** of the previous token and the end of the document to the output. - ** Then break out of the loop. */ - rc = fts3StringAppend(pOut, &zDoc[iEnd], -1); - } - break; - } - if( iCurrentiLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask - ); - isShiftDone = 1; - - /* Now that the shift has been done, check if the initial "..." are - ** required. They are required if (a) this is not the first fragment, - ** or (b) this fragment does not begin at position 0 of its column. - */ - if( rc==SQLITE_OK ){ - if( iPos>0 || iFragment>0 ){ - rc = fts3StringAppend(pOut, zEllipsis, -1); - }else if( iBegin ){ - rc = fts3StringAppend(pOut, zDoc, iBegin); - } - } - if( rc!=SQLITE_OK || iCurrent=(iPos+nSnippet) ){ - if( isLast ){ - rc = fts3StringAppend(pOut, zEllipsis, -1); - } - break; - } - - /* Set isHighlight to true if this term should be highlighted. */ - isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0; - - if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd); - if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1); - if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin); - if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1); - - iEnd = iFin; - } - - pMod->xClose(pC); - return rc; -} - - -/* -** This function is used to count the entries in a column-list (a -** delta-encoded list of term offsets within a single column of a single -** row). When this function is called, *ppCollist should point to the -** beginning of the first varint in the column-list (the varint that -** contains the position of the first matching term in the column data). -** Before returning, *ppCollist is set to point to the first byte after -** the last varint in the column-list (either the 0x00 signifying the end -** of the position-list, or the 0x01 that precedes the column number of -** the next column in the position-list). -** -** The number of elements in the column-list is returned. -*/ -static int fts3ColumnlistCount(char **ppCollist){ - char *pEnd = *ppCollist; - char c = 0; - int nEntry = 0; - - /* A column-list is terminated by either a 0x01 or 0x00. */ - while( 0xFE & (*pEnd | c) ){ - c = *pEnd++ & 0x80; - if( !c ) nEntry++; - } - - *ppCollist = pEnd; - return nEntry; -} - -/* -** This function gathers 'y' or 'b' data for a single phrase. -*/ -static int fts3ExprLHits( - Fts3Expr *pExpr, /* Phrase expression node */ - MatchInfo *p /* Matchinfo context */ -){ - Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab; - int iStart; - Fts3Phrase *pPhrase = pExpr->pPhrase; - char *pIter = pPhrase->doclist.pList; - int iCol = 0; - - assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS ); - if( p->flag==FTS3_MATCHINFO_LHITS ){ - iStart = pExpr->iPhrase * p->nCol; - }else{ - iStart = pExpr->iPhrase * ((p->nCol + 31) / 32); - } - - if( pIter ) while( 1 ){ - int nHit = fts3ColumnlistCount(&pIter); - if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){ - if( p->flag==FTS3_MATCHINFO_LHITS ){ - p->aMatchinfo[iStart + iCol] = (u32)nHit; - }else if( nHit ){ - p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F)); - } - } - assert( *pIter==0x00 || *pIter==0x01 ); - if( *pIter!=0x01 ) break; - pIter++; - pIter += fts3GetVarint32(pIter, &iCol); - if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB; - } - return SQLITE_OK; -} - -/* -** Gather the results for matchinfo directives 'y' and 'b'. -*/ -static int fts3ExprLHitGather( - Fts3Expr *pExpr, - MatchInfo *p -){ - int rc = SQLITE_OK; - assert( (pExpr->pLeft==0)==(pExpr->pRight==0) ); - if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){ - if( pExpr->pLeft ){ - rc = fts3ExprLHitGather(pExpr->pLeft, p); - if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p); - }else{ - rc = fts3ExprLHits(pExpr, p); - } - } - return rc; -} - -/* -** fts3ExprIterate() callback used to collect the "global" matchinfo stats -** for a single query. -** -** fts3ExprIterate() callback to load the 'global' elements of a -** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements -** of the matchinfo array that are constant for all rows returned by the -** current query. -** -** Argument pCtx is actually a pointer to a struct of type MatchInfo. This -** function populates Matchinfo.aMatchinfo[] as follows: -** -** for(iCol=0; iColpCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol] - ); -} - -/* -** fts3ExprIterate() callback used to collect the "local" part of the -** FTS3_MATCHINFO_HITS array. The local stats are those elements of the -** array that are different for each row returned by the query. -*/ -static int fts3ExprLocalHitsCb( - Fts3Expr *pExpr, /* Phrase expression node */ - int iPhrase, /* Phrase number */ - void *pCtx /* Pointer to MatchInfo structure */ -){ - int rc = SQLITE_OK; - MatchInfo *p = (MatchInfo *)pCtx; - int iStart = iPhrase * p->nCol * 3; - int i; - - for(i=0; inCol && rc==SQLITE_OK; i++){ - char *pCsr; - rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr); - if( pCsr ){ - p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr); - }else{ - p->aMatchinfo[iStart+i*3] = 0; - } - } - - return rc; -} - -static int fts3MatchinfoCheck( - Fts3Table *pTab, - char cArg, - char **pzErr -){ - if( (cArg==FTS3_MATCHINFO_NPHRASE) - || (cArg==FTS3_MATCHINFO_NCOL) - || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4) - || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4) - || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize) - || (cArg==FTS3_MATCHINFO_LCS) - || (cArg==FTS3_MATCHINFO_HITS) - || (cArg==FTS3_MATCHINFO_LHITS) - || (cArg==FTS3_MATCHINFO_LHITS_BM) - ){ - return SQLITE_OK; - } - sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg); - return SQLITE_ERROR; -} - -static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ - size_t nVal; /* Number of integers output by cArg */ - - switch( cArg ){ - case FTS3_MATCHINFO_NDOC: - case FTS3_MATCHINFO_NPHRASE: - case FTS3_MATCHINFO_NCOL: - nVal = 1; - break; - - case FTS3_MATCHINFO_AVGLENGTH: - case FTS3_MATCHINFO_LENGTH: - case FTS3_MATCHINFO_LCS: - nVal = pInfo->nCol; - break; - - case FTS3_MATCHINFO_LHITS: - nVal = pInfo->nCol * pInfo->nPhrase; - break; - - case FTS3_MATCHINFO_LHITS_BM: - nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32); - break; - - default: - assert( cArg==FTS3_MATCHINFO_HITS ); - nVal = pInfo->nCol * pInfo->nPhrase * 3; - break; - } - - return nVal; -} - -static int fts3MatchinfoSelectDoctotal( - Fts3Table *pTab, - sqlite3_stmt **ppStmt, - sqlite3_int64 *pnDoc, - const char **paLen, - const char **ppEnd -){ - sqlite3_stmt *pStmt; - const char *a; - const char *pEnd; - sqlite3_int64 nDoc; - int n; - - - if( !*ppStmt ){ - int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); - if( rc!=SQLITE_OK ) return rc; - } - pStmt = *ppStmt; - assert( sqlite3_data_count(pStmt)==1 ); - - n = sqlite3_column_bytes(pStmt, 0); - a = sqlite3_column_blob(pStmt, 0); - if( a==0 ){ - return FTS_CORRUPT_VTAB; - } - pEnd = a + n; - a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc); - if( nDoc<=0 || a>pEnd ){ - return FTS_CORRUPT_VTAB; - } - *pnDoc = nDoc; - - if( paLen ) *paLen = a; - if( ppEnd ) *ppEnd = pEnd; - return SQLITE_OK; -} - -/* -** An instance of the following structure is used to store state while -** iterating through a multi-column position-list corresponding to the -** hits for a single phrase on a single row in order to calculate the -** values for a matchinfo() FTS3_MATCHINFO_LCS request. -*/ -typedef struct LcsIterator LcsIterator; -struct LcsIterator { - Fts3Expr *pExpr; /* Pointer to phrase expression */ - int iPosOffset; /* Tokens count up to end of this phrase */ - char *pRead; /* Cursor used to iterate through aDoclist */ - int iPos; /* Current position */ -}; - -/* -** If LcsIterator.iCol is set to the following value, the iterator has -** finished iterating through all offsets for all columns. -*/ -#define LCS_ITERATOR_FINISHED 0x7FFFFFFF; - -static int fts3MatchinfoLcsCb( - Fts3Expr *pExpr, /* Phrase expression node */ - int iPhrase, /* Phrase number (numbered from zero) */ - void *pCtx /* Pointer to MatchInfo structure */ -){ - LcsIterator *aIter = (LcsIterator *)pCtx; - aIter[iPhrase].pExpr = pExpr; - return SQLITE_OK; -} - -/* -** Advance the iterator passed as an argument to the next position. Return -** 1 if the iterator is at EOF or if it now points to the start of the -** position list for the next column. -*/ -static int fts3LcsIteratorAdvance(LcsIterator *pIter){ - char *pRead = pIter->pRead; - sqlite3_int64 iRead; - int rc = 0; - - pRead += sqlite3Fts3GetVarint(pRead, &iRead); - if( iRead==0 || iRead==1 ){ - pRead = 0; - rc = 1; - }else{ - pIter->iPos += (int)(iRead-2); - } - - pIter->pRead = pRead; - return rc; -} - -/* -** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. -** -** If the call is successful, the longest-common-substring lengths for each -** column are written into the first nCol elements of the pInfo->aMatchinfo[] -** array before returning. SQLITE_OK is returned in this case. -** -** Otherwise, if an error occurs, an SQLite error code is returned and the -** data written to the first nCol elements of pInfo->aMatchinfo[] is -** undefined. -*/ -static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){ - LcsIterator *aIter; - int i; - int iCol; - int nToken = 0; - int rc = SQLITE_OK; - - /* Allocate and populate the array of LcsIterator objects. The array - ** contains one element for each matchable phrase in the query. - **/ - aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase); - if( !aIter ) return SQLITE_NOMEM; - memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase); - (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter); - - for(i=0; inPhrase; i++){ - LcsIterator *pIter = &aIter[i]; - nToken -= pIter->pExpr->pPhrase->nToken; - pIter->iPosOffset = nToken; - } - - for(iCol=0; iColnCol; iCol++){ - int nLcs = 0; /* LCS value for this column */ - int nLive = 0; /* Number of iterators in aIter not at EOF */ - - for(i=0; inPhrase; i++){ - LcsIterator *pIt = &aIter[i]; - rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); - if( rc!=SQLITE_OK ) goto matchinfo_lcs_out; - if( pIt->pRead ){ - pIt->iPos = pIt->iPosOffset; - fts3LcsIteratorAdvance(pIt); - if( pIt->pRead==0 ){ - rc = FTS_CORRUPT_VTAB; - goto matchinfo_lcs_out; - } - nLive++; - } - } - - while( nLive>0 ){ - LcsIterator *pAdv = 0; /* The iterator to advance by one position */ - int nThisLcs = 0; /* LCS for the current iterator positions */ - - for(i=0; inPhrase; i++){ - LcsIterator *pIter = &aIter[i]; - if( pIter->pRead==0 ){ - /* This iterator is already at EOF for this column. */ - nThisLcs = 0; - }else{ - if( pAdv==0 || pIter->iPosiPos ){ - pAdv = pIter; - } - if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){ - nThisLcs++; - }else{ - nThisLcs = 1; - } - if( nThisLcs>nLcs ) nLcs = nThisLcs; - } - } - if( fts3LcsIteratorAdvance(pAdv) ) nLive--; - } - - pInfo->aMatchinfo[iCol] = nLcs; - } - - matchinfo_lcs_out: - sqlite3_free(aIter); - return rc; -} - -/* -** Populate the buffer pInfo->aMatchinfo[] with an array of integers to -** be returned by the matchinfo() function. Argument zArg contains the -** format string passed as the second argument to matchinfo (or the -** default value "pcx" if no second argument was specified). The format -** string has already been validated and the pInfo->aMatchinfo[] array -** is guaranteed to be large enough for the output. -** -** If bGlobal is true, then populate all fields of the matchinfo() output. -** If it is false, then assume that those fields that do not change between -** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS) -** have already been populated. -** -** Return SQLITE_OK if successful, or an SQLite error code if an error -** occurs. If a value other than SQLITE_OK is returned, the state the -** pInfo->aMatchinfo[] buffer is left in is undefined. -*/ -static int fts3MatchinfoValues( - Fts3Cursor *pCsr, /* FTS3 cursor object */ - int bGlobal, /* True to grab the global stats */ - MatchInfo *pInfo, /* Matchinfo context object */ - const char *zArg /* Matchinfo format string */ -){ - int rc = SQLITE_OK; - int i; - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - sqlite3_stmt *pSelect = 0; - - for(i=0; rc==SQLITE_OK && zArg[i]; i++){ - pInfo->flag = zArg[i]; - switch( zArg[i] ){ - case FTS3_MATCHINFO_NPHRASE: - if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase; - break; - - case FTS3_MATCHINFO_NCOL: - if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol; - break; - - case FTS3_MATCHINFO_NDOC: - if( bGlobal ){ - sqlite3_int64 nDoc = 0; - rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0); - pInfo->aMatchinfo[0] = (u32)nDoc; - } - break; - - case FTS3_MATCHINFO_AVGLENGTH: - if( bGlobal ){ - sqlite3_int64 nDoc; /* Number of rows in table */ - const char *a; /* Aggregate column length array */ - const char *pEnd; /* First byte past end of length array */ - - rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd); - if( rc==SQLITE_OK ){ - int iCol; - for(iCol=0; iColnCol; iCol++){ - u32 iVal; - sqlite3_int64 nToken; - a += sqlite3Fts3GetVarint(a, &nToken); - if( a>pEnd ){ - rc = SQLITE_CORRUPT_VTAB; - break; - } - iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc); - pInfo->aMatchinfo[iCol] = iVal; - } - } - } - break; - - case FTS3_MATCHINFO_LENGTH: { - sqlite3_stmt *pSelectDocsize = 0; - rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize); - if( rc==SQLITE_OK ){ - int iCol; - const char *a = sqlite3_column_blob(pSelectDocsize, 0); - const char *pEnd = a + sqlite3_column_bytes(pSelectDocsize, 0); - for(iCol=0; iColnCol; iCol++){ - sqlite3_int64 nToken; - a += sqlite3Fts3GetVarintBounded(a, pEnd, &nToken); - if( a>pEnd ){ - rc = SQLITE_CORRUPT_VTAB; - break; - } - pInfo->aMatchinfo[iCol] = (u32)nToken; - } - } - sqlite3_reset(pSelectDocsize); - break; - } - - case FTS3_MATCHINFO_LCS: - rc = fts3ExprLoadDoclists(pCsr, 0, 0); - if( rc==SQLITE_OK ){ - rc = fts3MatchinfoLcs(pCsr, pInfo); - } - break; - - case FTS3_MATCHINFO_LHITS_BM: - case FTS3_MATCHINFO_LHITS: { - size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); - memset(pInfo->aMatchinfo, 0, nZero); - rc = fts3ExprLHitGather(pCsr->pExpr, pInfo); - break; - } - - default: { - Fts3Expr *pExpr; - assert( zArg[i]==FTS3_MATCHINFO_HITS ); - pExpr = pCsr->pExpr; - rc = fts3ExprLoadDoclists(pCsr, 0, 0); - if( rc!=SQLITE_OK ) break; - if( bGlobal ){ - if( pCsr->pDeferred ){ - rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0); - if( rc!=SQLITE_OK ) break; - } - rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo); - sqlite3Fts3EvalTestDeferred(pCsr, &rc); - if( rc!=SQLITE_OK ) break; - } - (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo); - break; - } - } - - pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]); - } - - sqlite3_reset(pSelect); - return rc; -} - - -/* -** Populate pCsr->aMatchinfo[] with data for the current row. The -** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32). -*/ -static void fts3GetMatchinfo( - sqlite3_context *pCtx, /* Return results here */ - Fts3Cursor *pCsr, /* FTS3 Cursor object */ - const char *zArg /* Second argument to matchinfo() function */ -){ - MatchInfo sInfo; - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int rc = SQLITE_OK; - int bGlobal = 0; /* Collect 'global' stats as well as local */ - - u32 *aOut = 0; - void (*xDestroyOut)(void*) = 0; - - memset(&sInfo, 0, sizeof(MatchInfo)); - sInfo.pCursor = pCsr; - sInfo.nCol = pTab->nColumn; - - /* If there is cached matchinfo() data, but the format string for the - ** cache does not match the format string for this request, discard - ** the cached data. */ - if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){ - sqlite3Fts3MIBufferFree(pCsr->pMIBuffer); - pCsr->pMIBuffer = 0; - } - - /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the - ** matchinfo function has been called for this query. In this case - ** allocate the array used to accumulate the matchinfo data and - ** initialize those elements that are constant for every row. - */ - if( pCsr->pMIBuffer==0 ){ - size_t nMatchinfo = 0; /* Number of u32 elements in match-info */ - int i; /* Used to iterate through zArg */ - - /* Determine the number of phrases in the query */ - pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr); - sInfo.nPhrase = pCsr->nPhrase; - - /* Determine the number of integers in the buffer returned by this call. */ - for(i=0; zArg[i]; i++){ - char *zErr = 0; - if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){ - sqlite3_result_error(pCtx, zErr, -1); - sqlite3_free(zErr); - return; - } - nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]); - } - - /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */ - pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg); - if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM; - - pCsr->isMatchinfoNeeded = 1; - bGlobal = 1; - } - - if( rc==SQLITE_OK ){ - xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut); - if( xDestroyOut==0 ){ - rc = SQLITE_NOMEM; - } - } - - if( rc==SQLITE_OK ){ - sInfo.aMatchinfo = aOut; - sInfo.nPhrase = pCsr->nPhrase; - rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg); - if( bGlobal ){ - fts3MIBufferSetGlobal(pCsr->pMIBuffer); - } - } - - if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); - if( xDestroyOut ) xDestroyOut(aOut); - }else{ - int n = pCsr->pMIBuffer->nElem * sizeof(u32); - sqlite3_result_blob(pCtx, aOut, n, xDestroyOut); - } -} - -/* -** Implementation of snippet() function. -*/ -SQLITE_PRIVATE void sqlite3Fts3Snippet( - sqlite3_context *pCtx, /* SQLite function call context */ - Fts3Cursor *pCsr, /* Cursor object */ - const char *zStart, /* Snippet start text - "" */ - const char *zEnd, /* Snippet end text - "" */ - const char *zEllipsis, /* Snippet ellipsis text - "..." */ - int iCol, /* Extract snippet from this column */ - int nToken /* Approximate number of tokens in snippet */ -){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - int rc = SQLITE_OK; - int i; - StrBuffer res = {0, 0, 0}; - - /* The returned text includes up to four fragments of text extracted from - ** the data in the current row. The first iteration of the for(...) loop - ** below attempts to locate a single fragment of text nToken tokens in - ** size that contains at least one instance of all phrases in the query - ** expression that appear in the current row. If such a fragment of text - ** cannot be found, the second iteration of the loop attempts to locate - ** a pair of fragments, and so on. - */ - int nSnippet = 0; /* Number of fragments in this snippet */ - SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */ - int nFToken = -1; /* Number of tokens in each fragment */ - - if( !pCsr->pExpr ){ - sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); - return; - } - - /* Limit the snippet length to 64 tokens. */ - if( nToken<-64 ) nToken = -64; - if( nToken>+64 ) nToken = +64; - - for(nSnippet=1; 1; nSnippet++){ - - int iSnip; /* Loop counter 0..nSnippet-1 */ - u64 mCovered = 0; /* Bitmask of phrases covered by snippet */ - u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */ - - if( nToken>=0 ){ - nFToken = (nToken+nSnippet-1) / nSnippet; - }else{ - nFToken = -1 * nToken; - } - - for(iSnip=0; iSnipnColumn; iRead++){ - SnippetFragment sF = {0, 0, 0, 0}; - int iS = 0; - if( iCol>=0 && iRead!=iCol ) continue; - - /* Find the best snippet of nFToken tokens in column iRead. */ - rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS); - if( rc!=SQLITE_OK ){ - goto snippet_out; - } - if( iS>iBestScore ){ - *pFragment = sF; - iBestScore = iS; - } - } - - mCovered |= pFragment->covered; - } - - /* If all query phrases seen by fts3BestSnippet() are present in at least - ** one of the nSnippet snippet fragments, break out of the loop. - */ - assert( (mCovered&mSeen)==mCovered ); - if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break; - } - - assert( nFToken>0 ); - - for(i=0; ipCsr, pExpr, p->iCol, &pList); - nTerm = pExpr->pPhrase->nToken; - if( pList ){ - fts3GetDeltaPosition(&pList, &iPos); - assert_fts3_nc( iPos>=0 ); - } - - for(iTerm=0; iTermaTerm[p->iTerm++]; - pT->iOff = nTerm-iTerm-1; - pT->pList = pList; - pT->iPos = iPos; - } - - return rc; -} - -/* -** Implementation of offsets() function. -*/ -SQLITE_PRIVATE void sqlite3Fts3Offsets( - sqlite3_context *pCtx, /* SQLite function call context */ - Fts3Cursor *pCsr /* Cursor object */ -){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule; - int rc; /* Return Code */ - int nToken; /* Number of tokens in query */ - int iCol; /* Column currently being processed */ - StrBuffer res = {0, 0, 0}; /* Result string */ - TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */ - - if( !pCsr->pExpr ){ - sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); - return; - } - - memset(&sCtx, 0, sizeof(sCtx)); - assert( pCsr->isRequireSeek==0 ); - - /* Count the number of terms in the query */ - rc = fts3ExprLoadDoclists(pCsr, 0, &nToken); - if( rc!=SQLITE_OK ) goto offsets_out; - - /* Allocate the array of TermOffset iterators. */ - sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken); - if( 0==sCtx.aTerm ){ - rc = SQLITE_NOMEM; - goto offsets_out; - } - sCtx.iDocid = pCsr->iPrevId; - sCtx.pCsr = pCsr; - - /* Loop through the table columns, appending offset information to - ** string-buffer res for each column. - */ - for(iCol=0; iColnColumn; iCol++){ - sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */ - const char *ZDUMMY; /* Dummy argument used with xNext() */ - int NDUMMY = 0; /* Dummy argument used with xNext() */ - int iStart = 0; - int iEnd = 0; - int iCurrent = 0; - const char *zDoc; - int nDoc; - - /* Initialize the contents of sCtx.aTerm[] for column iCol. There is - ** no way that this operation can fail, so the return code from - ** fts3ExprIterate() can be discarded. - */ - sCtx.iCol = iCol; - sCtx.iTerm = 0; - (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx); - - /* Retreive the text stored in column iCol. If an SQL NULL is stored - ** in column iCol, jump immediately to the next iteration of the loop. - ** If an OOM occurs while retrieving the data (this can happen if SQLite - ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM - ** to the caller. - */ - zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1); - nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1); - if( zDoc==0 ){ - if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){ - continue; - } - rc = SQLITE_NOMEM; - goto offsets_out; - } - - /* Initialize a tokenizer iterator to iterate through column iCol. */ - rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, - zDoc, nDoc, &pC - ); - if( rc!=SQLITE_OK ) goto offsets_out; - - rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); - while( rc==SQLITE_OK ){ - int i; /* Used to loop through terms */ - int iMinPos = 0x7FFFFFFF; /* Position of next token */ - TermOffset *pTerm = 0; /* TermOffset associated with next token */ - - for(i=0; ipList && (pT->iPos-pT->iOff)iPos-pT->iOff; - pTerm = pT; - } - } - - if( !pTerm ){ - /* All offsets for this column have been gathered. */ - rc = SQLITE_DONE; - }else{ - assert_fts3_nc( iCurrent<=iMinPos ); - if( 0==(0xFE&*pTerm->pList) ){ - pTerm->pList = 0; - }else{ - fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos); - } - while( rc==SQLITE_OK && iCurrentxNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent); - } - if( rc==SQLITE_OK ){ - char aBuffer[64]; - sqlite3_snprintf(sizeof(aBuffer), aBuffer, - "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart - ); - rc = fts3StringAppend(&res, aBuffer, -1); - }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){ - rc = FTS_CORRUPT_VTAB; - } - } - } - if( rc==SQLITE_DONE ){ - rc = SQLITE_OK; - } - - pMod->xClose(pC); - if( rc!=SQLITE_OK ) goto offsets_out; - } - - offsets_out: - sqlite3_free(sCtx.aTerm); - assert( rc!=SQLITE_DONE ); - sqlite3Fts3SegmentsClose(pTab); - if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); - sqlite3_free(res.z); - }else{ - sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free); - } - return; -} - -/* -** Implementation of matchinfo() function. -*/ -SQLITE_PRIVATE void sqlite3Fts3Matchinfo( - sqlite3_context *pContext, /* Function call context */ - Fts3Cursor *pCsr, /* FTS3 table cursor */ - const char *zArg /* Second arg to matchinfo() function */ -){ - Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; - const char *zFormat; - - if( zArg ){ - zFormat = zArg; - }else{ - zFormat = FTS3_MATCHINFO_DEFAULT; - } - - if( !pCsr->pExpr ){ - sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC); - return; - }else{ - /* Retrieve matchinfo() data. */ - fts3GetMatchinfo(pContext, pCsr, zFormat); - sqlite3Fts3SegmentsClose(pTab); - } -} - -#endif - -/************** End of fts3_snippet.c ****************************************/ -/************** Begin file fts3_unicode.c ************************************/ -/* -** 2012 May 24 -** -** 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. -** -****************************************************************************** -** -** Implementation of the "unicode" full-text-search tokenizer. -*/ - -#ifndef SQLITE_DISABLE_FTS3_UNICODE - -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) - -/* #include */ -/* #include */ -/* #include */ -/* #include */ - -/* #include "fts3_tokenizer.h" */ - -/* -** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied -** from the sqlite3 source file utf.c. If this file is compiled as part -** of the amalgamation, they are not required. -*/ -#ifndef SQLITE_AMALGAMATION - -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 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; } \ - } - -#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); \ - } \ -} - -#endif /* ifndef SQLITE_AMALGAMATION */ - -typedef struct unicode_tokenizer unicode_tokenizer; -typedef struct unicode_cursor unicode_cursor; - -struct unicode_tokenizer { - sqlite3_tokenizer base; - int eRemoveDiacritic; - int nException; - int *aiException; -}; - -struct unicode_cursor { - sqlite3_tokenizer_cursor base; - const unsigned char *aInput; /* Input text being tokenized */ - int nInput; /* Size of aInput[] in bytes */ - int iOff; /* Current offset within aInput[] */ - int iToken; /* Index of next token to be returned */ - char *zToken; /* storage for current token */ - int nAlloc; /* space allocated at zToken */ -}; - - -/* -** Destroy a tokenizer allocated by unicodeCreate(). -*/ -static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ - if( pTokenizer ){ - unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer; - sqlite3_free(p->aiException); - sqlite3_free(p); - } - return SQLITE_OK; -} - -/* -** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE -** statement has specified that the tokenizer for this table shall consider -** all characters in string zIn/nIn to be separators (if bAlnum==0) or -** token characters (if bAlnum==1). -** -** For each codepoint in the zIn/nIn string, this function checks if the -** sqlite3FtsUnicodeIsalnum() function already returns the desired result. -** If so, no action is taken. Otherwise, the codepoint is added to the -** unicode_tokenizer.aiException[] array. For the purposes of tokenization, -** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all -** codepoints in the aiException[] array. -** -** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic() -** identifies as a diacritic) occurs in the zIn/nIn string it is ignored. -** It is not possible to change the behavior of the tokenizer with respect -** to these codepoints. -*/ -static int unicodeAddExceptions( - unicode_tokenizer *p, /* Tokenizer to add exceptions to */ - int bAlnum, /* Replace Isalnum() return value with this */ - const char *zIn, /* Array of characters to make exceptions */ - int nIn /* Length of z in bytes */ -){ - const unsigned char *z = (const unsigned char *)zIn; - const unsigned char *zTerm = &z[nIn]; - unsigned int iCode; - int nEntry = 0; - - assert( bAlnum==0 || bAlnum==1 ); - - while( zaiException,(p->nException+nEntry)*sizeof(int)); - if( aNew==0 ) return SQLITE_NOMEM; - nNew = p->nException; - - z = (const unsigned char *)zIn; - while( zi; j--) aNew[j] = aNew[j-1]; - aNew[i] = (int)iCode; - nNew++; - } - } - p->aiException = aNew; - p->nException = nNew; - } - - return SQLITE_OK; -} - -/* -** Return true if the p->aiException[] array contains the value iCode. -*/ -static int unicodeIsException(unicode_tokenizer *p, int iCode){ - if( p->nException>0 ){ - int *a = p->aiException; - int iLo = 0; - int iHi = p->nException-1; - - while( iHi>=iLo ){ - int iTest = (iHi + iLo) / 2; - if( iCode==a[iTest] ){ - return 1; - }else if( iCode>a[iTest] ){ - iLo = iTest+1; - }else{ - iHi = iTest-1; - } - } - } - - return 0; -} - -/* -** Return true if, for the purposes of tokenization, codepoint iCode is -** considered a token character (not a separator). -*/ -static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ - assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); - return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); -} - -/* -** Create a new tokenizer instance. -*/ -static int unicodeCreate( - int nArg, /* Size of array argv[] */ - const char * const *azArg, /* Tokenizer creation arguments */ - sqlite3_tokenizer **pp /* OUT: New tokenizer handle */ -){ - unicode_tokenizer *pNew; /* New tokenizer object */ - int i; - int rc = SQLITE_OK; - - pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer)); - if( pNew==NULL ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(unicode_tokenizer)); - pNew->eRemoveDiacritic = 1; - - for(i=0; rc==SQLITE_OK && ieRemoveDiacritic = 1; - } - else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ - pNew->eRemoveDiacritic = 0; - } - else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){ - pNew->eRemoveDiacritic = 2; - } - else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){ - rc = unicodeAddExceptions(pNew, 1, &z[11], n-11); - } - else if( n>=11 && memcmp("separators=", z, 11)==0 ){ - rc = unicodeAddExceptions(pNew, 0, &z[11], n-11); - } - else{ - /* Unrecognized argument */ - rc = SQLITE_ERROR; - } - } - - if( rc!=SQLITE_OK ){ - unicodeDestroy((sqlite3_tokenizer *)pNew); - pNew = 0; - } - *pp = (sqlite3_tokenizer *)pNew; - return rc; -} - -/* -** Prepare to begin tokenizing a particular string. The input -** string to be tokenized is pInput[0..nBytes-1]. A cursor -** used to incrementally tokenize this string is returned in -** *ppCursor. -*/ -static int unicodeOpen( - sqlite3_tokenizer *p, /* The tokenizer */ - const char *aInput, /* Input string */ - int nInput, /* Size of string aInput in bytes */ - sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ -){ - unicode_cursor *pCsr; - - pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor)); - if( pCsr==0 ){ - return SQLITE_NOMEM; - } - memset(pCsr, 0, sizeof(unicode_cursor)); - - pCsr->aInput = (const unsigned char *)aInput; - if( aInput==0 ){ - pCsr->nInput = 0; - }else if( nInput<0 ){ - pCsr->nInput = (int)strlen(aInput); - }else{ - pCsr->nInput = nInput; - } - - *pp = &pCsr->base; - UNUSED_PARAMETER(p); - return SQLITE_OK; -} - -/* -** Close a tokenization cursor previously opened by a call to -** simpleOpen() above. -*/ -static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ - unicode_cursor *pCsr = (unicode_cursor *) pCursor; - sqlite3_free(pCsr->zToken); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Extract the next token from a tokenization cursor. The cursor must -** have been opened by a prior call to simpleOpen(). -*/ -static int unicodeNext( - sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ - const char **paToken, /* OUT: Token text */ - int *pnToken, /* OUT: Number of bytes at *paToken */ - int *piStart, /* OUT: Starting offset of token */ - int *piEnd, /* OUT: Ending offset of token */ - int *piPos /* OUT: Position integer of token */ -){ - unicode_cursor *pCsr = (unicode_cursor *)pC; - unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer); - unsigned int iCode = 0; - char *zOut; - const unsigned char *z = &pCsr->aInput[pCsr->iOff]; - const unsigned char *zStart = z; - const unsigned char *zEnd; - const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput]; - - /* Scan past any delimiter characters before the start of the next token. - ** Return SQLITE_DONE early if this takes us all the way to the end of - ** the input. */ - while( z=zTerm ) return SQLITE_DONE; - - zOut = pCsr->zToken; - do { - int iOut; - - /* Grow the output buffer if required. */ - if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){ - char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64); - if( !zNew ) return SQLITE_NOMEM; - zOut = &zNew[zOut - pCsr->zToken]; - pCsr->zToken = zNew; - pCsr->nAlloc += 64; - } - - /* Write the folded case of the last character read to the output */ - zEnd = z; - iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic); - if( iOut ){ - WRITE_UTF8(zOut, iOut); - } - - /* If the cursor is not at EOF, read the next character */ - if( z>=zTerm ) break; - READ_UTF8(z, zTerm, iCode); - }while( unicodeIsAlnum(p, (int)iCode) - || sqlite3FtsUnicodeIsdiacritic((int)iCode) - ); - - /* Set the output variables and return. */ - pCsr->iOff = (int)(z - pCsr->aInput); - *paToken = pCsr->zToken; - *pnToken = (int)(zOut - pCsr->zToken); - *piStart = (int)(zStart - pCsr->aInput); - *piEnd = (int)(zEnd - pCsr->aInput); - *piPos = pCsr->iToken++; - return SQLITE_OK; -} - -/* -** Set *ppModule to a pointer to the sqlite3_tokenizer_module -** structure for the unicode tokenizer. -*/ -SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){ - static const sqlite3_tokenizer_module module = { - 0, - unicodeCreate, - unicodeDestroy, - unicodeOpen, - unicodeClose, - unicodeNext, - 0, - }; - *ppModule = &module; -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ -#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */ - -/************** End of fts3_unicode.c ****************************************/ -/************** Begin file fts3_unicode2.c ***********************************/ -/* -** 2012-05-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. -** -****************************************************************************** -*/ - -/* -** DO NOT EDIT THIS MACHINE GENERATED FILE. -*/ - -#ifndef SQLITE_DISABLE_FTS3_UNICODE -#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) - -/* #include */ - -/* -** Return true if the argument corresponds to a unicode codepoint -** classified as either a letter or a number. Otherwise false. -** -** The results are undefined if the value passed to this function -** is less than zero. -*/ -SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){ - /* Each unsigned integer in the following array corresponds to a contiguous - ** range of unicode codepoints that are not either letters or numbers (i.e. - ** codepoints for which this function should return 0). - ** - ** The most significant 22 bits in each 32-bit value contain the first - ** codepoint in the range. The least significant 10 bits are used to store - ** the size of the range (always at least 1). In other words, the value - ** ((C<<22) + N) represents a range of N codepoints starting with codepoint - ** C. It is not possible to represent a range larger than 1023 codepoints - ** using this format. - */ - static const unsigned int aEntry[] = { - 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07, - 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01, - 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401, - 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01, - 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01, - 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802, - 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F, - 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401, - 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804, - 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403, - 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812, - 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001, - 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802, - 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805, - 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401, - 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03, - 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807, - 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001, - 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01, - 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804, - 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001, - 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802, - 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01, - 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06, - 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, - 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006, - 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417, - 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14, - 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07, - 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01, - 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001, - 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802, - 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F, - 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, - 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802, - 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006, - 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D, - 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802, - 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027, - 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403, - 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805, - 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04, - 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401, - 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, - 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B, - 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A, - 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, - 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59, - 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, - 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, - 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, - 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100, - 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10, - 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402, - 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804, - 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012, - 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004, - 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002, - 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803, - 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07, - 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02, - 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802, - 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013, - 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06, - 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003, - 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01, - 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403, - 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009, - 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003, - 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003, - 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E, - 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046, - 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401, - 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401, - 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, - 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C, - 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002, - 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025, - 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6, - 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46, - 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060, - 0x380400F0, - }; - static const unsigned int aAscii[4] = { - 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001, - }; - - if( (unsigned int)c<128 ){ - return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 ); - }else if( (unsigned int)c<(1<<22) ){ - unsigned int key = (((unsigned int)c)<<10) | 0x000003FF; - int iRes = 0; - int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; - int iLo = 0; - while( iHi>=iLo ){ - int iTest = (iHi + iLo) / 2; - if( key >= aEntry[iTest] ){ - iRes = iTest; - iLo = iTest+1; - }else{ - iHi = iTest-1; - } - } - assert( aEntry[0]=aEntry[iRes] ); - return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF))); - } - return 1; -} - - -/* -** If the argument is a codepoint corresponding to a lowercase letter -** in the ASCII range with a diacritic added, return the codepoint -** of the ASCII letter only. For example, if passed 235 - "LATIN -** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER -** E"). The resuls of passing a codepoint that corresponds to an -** uppercase letter are undefined. -*/ -static int remove_diacritic(int c, int bComplex){ - unsigned short aDia[] = { - 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995, - 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286, - 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732, - 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336, - 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896, - 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106, - 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344, - 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198, - 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468, - 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, - 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, - 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, - 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, - 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, - 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, - 63182, 63242, 63274, 63310, 63368, 63390, - }; -#define HIBIT ((unsigned char)0x80) - unsigned char aChar[] = { - '\0', 'a', 'c', 'e', 'i', 'n', - 'o', 'u', 'y', 'y', 'a', 'c', - 'd', 'e', 'e', 'g', 'h', 'i', - 'j', 'k', 'l', 'n', 'o', 'r', - 's', 't', 'u', 'u', 'w', 'y', - 'z', 'o', 'u', 'a', 'i', 'o', - 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o', - 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a', - 'e', 'i', 'o', 'r', 'u', 's', - 't', 'h', 'a', 'e', 'o'|HIBIT, 'o', - 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0', - '\0', '\0', '\0', '\0', 'a', 'b', - 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT, - 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT, - 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n', - 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's', - 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w', - 'w', 'x', 'y', 'z', 'h', 't', - 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, - 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT, - 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y', - }; - - unsigned int key = (((unsigned int)c)<<3) | 0x00000007; - int iRes = 0; - int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1; - int iLo = 0; - while( iHi>=iLo ){ - int iTest = (iHi + iLo) / 2; - if( key >= aDia[iTest] ){ - iRes = iTest; - iLo = iTest+1; - }else{ - iHi = iTest-1; - } - } - assert( key>=aDia[iRes] ); - if( bComplex==0 && (aChar[iRes] & 0x80) ) return c; - return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F); -} - - -/* -** Return true if the argument interpreted as a unicode codepoint -** is a diacritical modifier character. -*/ -SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){ - unsigned int mask0 = 0x08029FDF; - unsigned int mask1 = 0x000361F8; - if( c<768 || c>817 ) return 0; - return (c < 768+32) ? - (mask0 & ((unsigned int)1 << (c-768))) : - (mask1 & ((unsigned int)1 << (c-768-32))); -} - - -/* -** Interpret the argument as a unicode codepoint. If the codepoint -** is an upper case character that has a lower case equivalent, -** return the codepoint corresponding to the lower case version. -** Otherwise, return a copy of the argument. -** -** The results are undefined if the value passed to this function -** is less than zero. -*/ -SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){ - /* Each entry in the following array defines a rule for folding a range - ** of codepoints to lower case. The rule applies to a range of nRange - ** codepoints starting at codepoint iCode. - ** - ** If the least significant bit in flags is clear, then the rule applies - ** to all nRange codepoints (i.e. all nRange codepoints are upper case and - ** need to be folded). Or, if it is set, then the rule only applies to - ** every second codepoint in the range, starting with codepoint C. - ** - ** The 7 most significant bits in flags are an index into the aiOff[] - ** array. If a specific codepoint C does require folding, then its lower - ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF). - ** - ** The contents of this array are generated by parsing the CaseFolding.txt - ** file distributed as part of the "Unicode Character Database". See - ** http://www.unicode.org for details. - */ - static const struct TableEntry { - unsigned short iCode; - unsigned char flags; - unsigned char nRange; - } aEntry[] = { - {65, 14, 26}, {181, 64, 1}, {192, 14, 23}, - {216, 14, 7}, {256, 1, 48}, {306, 1, 6}, - {313, 1, 16}, {330, 1, 46}, {376, 116, 1}, - {377, 1, 6}, {383, 104, 1}, {385, 50, 1}, - {386, 1, 4}, {390, 44, 1}, {391, 0, 1}, - {393, 42, 2}, {395, 0, 1}, {398, 32, 1}, - {399, 38, 1}, {400, 40, 1}, {401, 0, 1}, - {403, 42, 1}, {404, 46, 1}, {406, 52, 1}, - {407, 48, 1}, {408, 0, 1}, {412, 52, 1}, - {413, 54, 1}, {415, 56, 1}, {416, 1, 6}, - {422, 60, 1}, {423, 0, 1}, {425, 60, 1}, - {428, 0, 1}, {430, 60, 1}, {431, 0, 1}, - {433, 58, 2}, {435, 1, 4}, {439, 62, 1}, - {440, 0, 1}, {444, 0, 1}, {452, 2, 1}, - {453, 0, 1}, {455, 2, 1}, {456, 0, 1}, - {458, 2, 1}, {459, 1, 18}, {478, 1, 18}, - {497, 2, 1}, {498, 1, 4}, {502, 122, 1}, - {503, 134, 1}, {504, 1, 40}, {544, 110, 1}, - {546, 1, 18}, {570, 70, 1}, {571, 0, 1}, - {573, 108, 1}, {574, 68, 1}, {577, 0, 1}, - {579, 106, 1}, {580, 28, 1}, {581, 30, 1}, - {582, 1, 10}, {837, 36, 1}, {880, 1, 4}, - {886, 0, 1}, {902, 18, 1}, {904, 16, 3}, - {908, 26, 1}, {910, 24, 2}, {913, 14, 17}, - {931, 14, 9}, {962, 0, 1}, {975, 4, 1}, - {976, 140, 1}, {977, 142, 1}, {981, 146, 1}, - {982, 144, 1}, {984, 1, 24}, {1008, 136, 1}, - {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1}, - {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1}, - {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32}, - {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1}, - {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38}, - {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1}, - {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1}, - {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6}, - {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6}, - {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8}, - {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2}, - {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1}, - {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2}, - {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2}, - {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2}, - {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1}, - {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16}, - {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47}, - {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1}, - {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1}, - {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1}, - {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2}, - {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1}, - {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14}, - {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1}, - {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1}, - {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1}, - {65313, 14, 26}, - }; - static const unsigned short aiOff[] = { - 1, 2, 8, 15, 16, 26, 28, 32, - 37, 38, 40, 48, 63, 64, 69, 71, - 79, 80, 116, 202, 203, 205, 206, 207, - 209, 210, 211, 213, 214, 217, 218, 219, - 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721, - 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, - 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, - 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, - 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, - 65514, 65521, 65527, 65528, 65529, - }; - - int ret = c; - - assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 ); - - if( c<128 ){ - if( c>='A' && c<='Z' ) ret = c + ('a' - 'A'); - }else if( c<65536 ){ - const struct TableEntry *p; - int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1; - int iLo = 0; - int iRes = -1; - - assert( c>aEntry[0].iCode ); - while( iHi>=iLo ){ - int iTest = (iHi + iLo) / 2; - int cmp = (c - aEntry[iTest].iCode); - if( cmp>=0 ){ - iRes = iTest; - iLo = iTest+1; - }else{ - iHi = iTest-1; - } - } - - assert( iRes>=0 && c>=aEntry[iRes].iCode ); - p = &aEntry[iRes]; - if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){ - ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF; - assert( ret>0 ); - } - - if( eRemoveDiacritic ){ - ret = remove_diacritic(ret, eRemoveDiacritic==2); - } - } - - else if( c>=66560 && c<66600 ){ - ret = c + 40; - } - - return ret; -} -#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */ -#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */ - -/************** End of fts3_unicode2.c ***************************************/ -/************** Begin file json1.c *******************************************/ -/* -** 2015-08-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 SQLite extension implements JSON functions. The interface is -** modeled after MySQL JSON functions: -** -** https://dev.mysql.com/doc/refman/5.7/en/json.html -** -** For the time being, all JSON is stored as pure text. (We might add -** a JSONB type in the future which stores a binary encoding of JSON in -** a BLOB, but there is no support for JSONB in the current implementation. -** This implementation parses JSON text at 250 MB/s, so it is hard to see -** how JSONB might improve on that.) -*/ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) -#if !defined(SQLITEINT_H) -/* #include "sqlite3ext.h" */ -#endif -SQLITE_EXTENSION_INIT1 -/* #include */ -/* #include */ -/* #include */ -/* #include */ - -/* Mark a function parameter as unused, to suppress nuisance compiler -** warnings. */ -#ifndef UNUSED_PARAM -# define UNUSED_PARAM(X) (void)(X) -#endif - -#ifndef LARGEST_INT64 -# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) -# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) -#endif - -#ifndef deliberate_fall_through -# define deliberate_fall_through -#endif - -/* -** Versions of isspace(), isalnum() and isdigit() to which it is safe -** to pass signed char values. -*/ -#ifdef sqlite3Isdigit - /* Use the SQLite core versions if this routine is part of the - ** SQLite amalgamation */ -# define safe_isdigit(x) sqlite3Isdigit(x) -# define safe_isalnum(x) sqlite3Isalnum(x) -# define safe_isxdigit(x) sqlite3Isxdigit(x) -#else - /* Use the standard library for separate compilation */ -#include /* amalgamator: keep */ -# define safe_isdigit(x) isdigit((unsigned char)(x)) -# define safe_isalnum(x) isalnum((unsigned char)(x)) -# define safe_isxdigit(x) isxdigit((unsigned char)(x)) -#endif - -/* -** Growing our own isspace() routine this way is twice as fast as -** the library isspace() function, resulting in a 7% overall performance -** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os). -*/ -static const char jsonIsSpace[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -}; -#define safe_isspace(x) (jsonIsSpace[(unsigned char)x]) - -#ifndef SQLITE_AMALGAMATION - /* Unsigned integer types. These are already defined in the sqliteInt.h, - ** but the definitions need to be repeated for separate compilation. */ - typedef sqlite3_uint64 u64; - typedef unsigned int u32; - typedef unsigned short int u16; - typedef unsigned char u8; -#endif - -/* Objects */ -typedef struct JsonString JsonString; -typedef struct JsonNode JsonNode; -typedef struct JsonParse JsonParse; - -/* An instance of this object represents a JSON string -** under construction. Really, this is a generic string accumulator -** that can be and is used to create strings other than JSON. -*/ -struct JsonString { - sqlite3_context *pCtx; /* Function context - put error messages here */ - char *zBuf; /* Append JSON content here */ - u64 nAlloc; /* Bytes of storage available in zBuf[] */ - u64 nUsed; /* Bytes of zBuf[] currently used */ - u8 bStatic; /* True if zBuf is static space */ - u8 bErr; /* True if an error has been encountered */ - char zSpace[100]; /* Initial static space */ -}; - -/* JSON type values -*/ -#define JSON_NULL 0 -#define JSON_TRUE 1 -#define JSON_FALSE 2 -#define JSON_INT 3 -#define JSON_REAL 4 -#define JSON_STRING 5 -#define JSON_ARRAY 6 -#define JSON_OBJECT 7 - -/* The "subtype" set for JSON values */ -#define JSON_SUBTYPE 74 /* Ascii for "J" */ - -/* -** Names of the various JSON types: -*/ -static const char * const jsonType[] = { - "null", "true", "false", "integer", "real", "text", "array", "object" -}; - -/* Bit values for the JsonNode.jnFlag field -*/ -#define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */ -#define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */ -#define JNODE_REMOVE 0x04 /* Do not output */ -#define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */ -#define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */ -#define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */ -#define JNODE_LABEL 0x40 /* Is a label of an object */ - - -/* A single node of parsed JSON -*/ -struct JsonNode { - u8 eType; /* One of the JSON_ type values */ - u8 jnFlags; /* JNODE flags */ - u32 n; /* Bytes of content, or number of sub-nodes */ - union { - const char *zJContent; /* Content for INT, REAL, and STRING */ - u32 iAppend; /* More terms for ARRAY and OBJECT */ - u32 iKey; /* Key for ARRAY objects in json_tree() */ - u32 iReplace; /* Replacement content for JNODE_REPLACE */ - JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */ - } u; -}; - -/* A completely parsed JSON string -*/ -struct JsonParse { - u32 nNode; /* Number of slots of aNode[] used */ - u32 nAlloc; /* Number of slots of aNode[] allocated */ - JsonNode *aNode; /* Array of nodes containing the parse */ - const char *zJson; /* Original JSON string */ - u32 *aUp; /* Index of parent of each node */ - u8 oom; /* Set to true if out of memory */ - u8 nErr; /* Number of errors seen */ - u16 iDepth; /* Nesting depth */ - int nJson; /* Length of the zJson string in bytes */ - u32 iHold; /* Replace cache line with the lowest iHold value */ -}; - -/* -** Maximum nesting depth of JSON for this implementation. -** -** This limit is needed to avoid a stack overflow in the recursive -** descent parser. A depth of 2000 is far deeper than any sane JSON -** should go. -*/ -#define JSON_MAX_DEPTH 2000 - -/************************************************************************** -** Utility routines for dealing with JsonString objects -**************************************************************************/ - -/* Set the JsonString object to an empty string -*/ -static void jsonZero(JsonString *p){ - p->zBuf = p->zSpace; - p->nAlloc = sizeof(p->zSpace); - p->nUsed = 0; - p->bStatic = 1; -} - -/* Initialize the JsonString object -*/ -static void jsonInit(JsonString *p, sqlite3_context *pCtx){ - p->pCtx = pCtx; - p->bErr = 0; - jsonZero(p); -} - - -/* Free all allocated memory and reset the JsonString object back to its -** initial state. -*/ -static void jsonReset(JsonString *p){ - if( !p->bStatic ) sqlite3_free(p->zBuf); - jsonZero(p); -} - - -/* Report an out-of-memory (OOM) condition -*/ -static void jsonOom(JsonString *p){ - p->bErr = 1; - sqlite3_result_error_nomem(p->pCtx); - jsonReset(p); -} - -/* Enlarge pJson->zBuf so that it can hold at least N more bytes. -** Return zero on success. Return non-zero on an OOM error -*/ -static int jsonGrow(JsonString *p, u32 N){ - u64 nTotal = NnAlloc ? p->nAlloc*2 : p->nAlloc+N+10; - char *zNew; - if( p->bStatic ){ - if( p->bErr ) return 1; - zNew = sqlite3_malloc64(nTotal); - if( zNew==0 ){ - jsonOom(p); - return SQLITE_NOMEM; - } - memcpy(zNew, p->zBuf, (size_t)p->nUsed); - p->zBuf = zNew; - p->bStatic = 0; - }else{ - zNew = sqlite3_realloc64(p->zBuf, nTotal); - if( zNew==0 ){ - jsonOom(p); - return SQLITE_NOMEM; - } - p->zBuf = zNew; - } - p->nAlloc = nTotal; - return SQLITE_OK; -} - -/* Append N bytes from zIn onto the end of the JsonString string. -*/ -static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){ - if( N==0 ) return; - if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return; - memcpy(p->zBuf+p->nUsed, zIn, N); - p->nUsed += N; -} - -/* Append formatted text (not to exceed N bytes) to the JsonString. -*/ -static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){ - va_list ap; - if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return; - va_start(ap, zFormat); - sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap); - va_end(ap); - p->nUsed += (int)strlen(p->zBuf+p->nUsed); -} - -/* Append a single character -*/ -static void jsonAppendChar(JsonString *p, char c){ - if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return; - p->zBuf[p->nUsed++] = c; -} - -/* Append a comma separator to the output buffer, if the previous -** character is not '[' or '{'. -*/ -static void jsonAppendSeparator(JsonString *p){ - char c; - if( p->nUsed==0 ) return; - c = p->zBuf[p->nUsed-1]; - if( c!='[' && c!='{' ) jsonAppendChar(p, ','); -} - -/* Append the N-byte string in zIn to the end of the JsonString string -** under construction. Enclose the string in "..." and escape -** any double-quotes or backslash characters contained within the -** string. -*/ -static void jsonAppendString(JsonString *p, const char *zIn, u32 N){ - u32 i; - if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return; - p->zBuf[p->nUsed++] = '"'; - for(i=0; inUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return; - p->zBuf[p->nUsed++] = '\\'; - }else if( c<=0x1f ){ - static const char aSpecial[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - assert( sizeof(aSpecial)==32 ); - assert( aSpecial['\b']=='b' ); - assert( aSpecial['\f']=='f' ); - assert( aSpecial['\n']=='n' ); - assert( aSpecial['\r']=='r' ); - assert( aSpecial['\t']=='t' ); - if( aSpecial[c] ){ - c = aSpecial[c]; - goto json_simple_escape; - } - if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return; - p->zBuf[p->nUsed++] = '\\'; - p->zBuf[p->nUsed++] = 'u'; - p->zBuf[p->nUsed++] = '0'; - p->zBuf[p->nUsed++] = '0'; - p->zBuf[p->nUsed++] = '0' + (c>>4); - c = "0123456789abcdef"[c&0xf]; - } - p->zBuf[p->nUsed++] = c; - } - p->zBuf[p->nUsed++] = '"'; - assert( p->nUsednAlloc ); -} - -/* -** Append a function parameter value to the JSON string under -** construction. -*/ -static void jsonAppendValue( - JsonString *p, /* Append to this JSON string */ - sqlite3_value *pValue /* Value to append */ -){ - switch( sqlite3_value_type(pValue) ){ - case SQLITE_NULL: { - jsonAppendRaw(p, "null", 4); - break; - } - case SQLITE_INTEGER: - case SQLITE_FLOAT: { - const char *z = (const char*)sqlite3_value_text(pValue); - u32 n = (u32)sqlite3_value_bytes(pValue); - jsonAppendRaw(p, z, n); - break; - } - case SQLITE_TEXT: { - const char *z = (const char*)sqlite3_value_text(pValue); - u32 n = (u32)sqlite3_value_bytes(pValue); - if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){ - jsonAppendRaw(p, z, n); - }else{ - jsonAppendString(p, z, n); - } - break; - } - default: { - if( p->bErr==0 ){ - sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1); - p->bErr = 2; - jsonReset(p); - } - break; - } - } -} - - -/* Make the JSON in p the result of the SQL function. -*/ -static void jsonResult(JsonString *p){ - if( p->bErr==0 ){ - sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, - p->bStatic ? SQLITE_TRANSIENT : sqlite3_free, - SQLITE_UTF8); - jsonZero(p); - } - assert( p->bStatic ); -} - -/************************************************************************** -** Utility routines for dealing with JsonNode and JsonParse objects -**************************************************************************/ - -/* -** Return the number of consecutive JsonNode slots need to represent -** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and -** OBJECT types, the number might be larger. -** -** Appended elements are not counted. The value returned is the number -** by which the JsonNode counter should increment in order to go to the -** next peer value. -*/ -static u32 jsonNodeSize(JsonNode *pNode){ - return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1; -} - -/* -** Reclaim all memory allocated by a JsonParse object. But do not -** delete the JsonParse object itself. -*/ -static void jsonParseReset(JsonParse *pParse){ - sqlite3_free(pParse->aNode); - pParse->aNode = 0; - pParse->nNode = 0; - pParse->nAlloc = 0; - sqlite3_free(pParse->aUp); - pParse->aUp = 0; -} - -/* -** Free a JsonParse object that was obtained from sqlite3_malloc(). -*/ -static void jsonParseFree(JsonParse *pParse){ - jsonParseReset(pParse); - sqlite3_free(pParse); -} - -/* -** Convert the JsonNode pNode into a pure JSON string and -** append to pOut. Subsubstructure is also included. Return -** the number of JsonNode objects that are encoded. -*/ -static void jsonRenderNode( - JsonNode *pNode, /* The node to render */ - JsonString *pOut, /* Write JSON here */ - sqlite3_value **aReplace /* Replacement values */ -){ - if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){ - if( pNode->jnFlags & JNODE_REPLACE ){ - jsonAppendValue(pOut, aReplace[pNode->u.iReplace]); - return; - } - pNode = pNode->u.pPatch; - } - switch( pNode->eType ){ - default: { - assert( pNode->eType==JSON_NULL ); - jsonAppendRaw(pOut, "null", 4); - break; - } - case JSON_TRUE: { - jsonAppendRaw(pOut, "true", 4); - break; - } - case JSON_FALSE: { - jsonAppendRaw(pOut, "false", 5); - break; - } - case JSON_STRING: { - if( pNode->jnFlags & JNODE_RAW ){ - jsonAppendString(pOut, pNode->u.zJContent, pNode->n); - break; - } - /* no break */ deliberate_fall_through - } - case JSON_REAL: - case JSON_INT: { - jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n); - break; - } - case JSON_ARRAY: { - u32 j = 1; - jsonAppendChar(pOut, '['); - for(;;){ - while( j<=pNode->n ){ - if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){ - jsonAppendSeparator(pOut); - jsonRenderNode(&pNode[j], pOut, aReplace); - } - j += jsonNodeSize(&pNode[j]); - } - if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; - pNode = &pNode[pNode->u.iAppend]; - j = 1; - } - jsonAppendChar(pOut, ']'); - break; - } - case JSON_OBJECT: { - u32 j = 1; - jsonAppendChar(pOut, '{'); - for(;;){ - while( j<=pNode->n ){ - if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){ - jsonAppendSeparator(pOut); - jsonRenderNode(&pNode[j], pOut, aReplace); - jsonAppendChar(pOut, ':'); - jsonRenderNode(&pNode[j+1], pOut, aReplace); - } - j += 1 + jsonNodeSize(&pNode[j+1]); - } - if( (pNode->jnFlags & JNODE_APPEND)==0 ) break; - pNode = &pNode[pNode->u.iAppend]; - j = 1; - } - jsonAppendChar(pOut, '}'); - break; - } - } -} - -/* -** Return a JsonNode and all its descendents as a JSON string. -*/ -static void jsonReturnJson( - JsonNode *pNode, /* Node to return */ - sqlite3_context *pCtx, /* Return value for this function */ - sqlite3_value **aReplace /* Array of replacement values */ -){ - JsonString s; - jsonInit(&s, pCtx); - jsonRenderNode(pNode, &s, aReplace); - jsonResult(&s); - sqlite3_result_subtype(pCtx, JSON_SUBTYPE); -} - -/* -** 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 -*/ -static u8 jsonHexToInt(int h){ - assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); -#ifdef SQLITE_EBCDIC - h += 9*(1&~(h>>4)); -#else - h += 9*(1&(h>>6)); -#endif - return (u8)(h & 0xf); -} - -/* -** Convert a 4-byte hex string into an integer -*/ -static u32 jsonHexToInt4(const char *z){ - u32 v; - assert( safe_isxdigit(z[0]) ); - assert( safe_isxdigit(z[1]) ); - assert( safe_isxdigit(z[2]) ); - assert( safe_isxdigit(z[3]) ); - v = (jsonHexToInt(z[0])<<12) - + (jsonHexToInt(z[1])<<8) - + (jsonHexToInt(z[2])<<4) - + jsonHexToInt(z[3]); - return v; -} - -/* -** Make the JsonNode the return value of the function. -*/ -static void jsonReturn( - JsonNode *pNode, /* Node to return */ - sqlite3_context *pCtx, /* Return value for this function */ - sqlite3_value **aReplace /* Array of replacement values */ -){ - switch( pNode->eType ){ - default: { - assert( pNode->eType==JSON_NULL ); - sqlite3_result_null(pCtx); - break; - } - case JSON_TRUE: { - sqlite3_result_int(pCtx, 1); - break; - } - case JSON_FALSE: { - sqlite3_result_int(pCtx, 0); - break; - } - case JSON_INT: { - sqlite3_int64 i = 0; - const char *z = pNode->u.zJContent; - if( z[0]=='-' ){ z++; } - while( z[0]>='0' && z[0]<='9' ){ - unsigned v = *(z++) - '0'; - if( i>=LARGEST_INT64/10 ){ - if( i>LARGEST_INT64/10 ) goto int_as_real; - if( z[0]>='0' && z[0]<='9' ) goto int_as_real; - if( v==9 ) goto int_as_real; - if( v==8 ){ - if( pNode->u.zJContent[0]=='-' ){ - sqlite3_result_int64(pCtx, SMALLEST_INT64); - goto int_done; - }else{ - goto int_as_real; - } - } - } - i = i*10 + v; - } - if( pNode->u.zJContent[0]=='-' ){ i = -i; } - sqlite3_result_int64(pCtx, i); - int_done: - break; - int_as_real: i=0; /* no break */ deliberate_fall_through - } - case JSON_REAL: { - double r; -#ifdef SQLITE_AMALGAMATION - const char *z = pNode->u.zJContent; - sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8); -#else - r = strtod(pNode->u.zJContent, 0); -#endif - sqlite3_result_double(pCtx, r); - break; - } - case JSON_STRING: { -#if 0 /* Never happens because JNODE_RAW is only set by json_set(), - ** json_insert() and json_replace() and those routines do not - ** call jsonReturn() */ - if( pNode->jnFlags & JNODE_RAW ){ - sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n, - SQLITE_TRANSIENT); - }else -#endif - assert( (pNode->jnFlags & JNODE_RAW)==0 ); - if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){ - /* JSON formatted without any backslash-escapes */ - sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2, - SQLITE_TRANSIENT); - }else{ - /* Translate JSON formatted string into raw text */ - u32 i; - u32 n = pNode->n; - const char *z = pNode->u.zJContent; - char *zOut; - u32 j; - zOut = sqlite3_malloc( n+1 ); - if( zOut==0 ){ - sqlite3_result_error_nomem(pCtx); - break; - } - for(i=1, j=0; i>6)); - zOut[j++] = 0x80 | (v&0x3f); - }else{ - u32 vlo; - if( (v&0xfc00)==0xd800 - && i>18); - zOut[j++] = 0x80 | ((v>>12)&0x3f); - zOut[j++] = 0x80 | ((v>>6)&0x3f); - zOut[j++] = 0x80 | (v&0x3f); - }else{ - zOut[j++] = 0xe0 | (v>>12); - zOut[j++] = 0x80 | ((v>>6)&0x3f); - zOut[j++] = 0x80 | (v&0x3f); - } - } - }else{ - if( c=='b' ){ - c = '\b'; - }else if( c=='f' ){ - c = '\f'; - }else if( c=='n' ){ - c = '\n'; - }else if( c=='r' ){ - c = '\r'; - }else if( c=='t' ){ - c = '\t'; - } - zOut[j++] = c; - } - } - } - zOut[j] = 0; - sqlite3_result_text(pCtx, zOut, j, sqlite3_free); - } - break; - } - case JSON_ARRAY: - case JSON_OBJECT: { - jsonReturnJson(pNode, pCtx, aReplace); - break; - } - } -} - -/* Forward reference */ -static int jsonParseAddNode(JsonParse*,u32,u32,const char*); - -/* -** A macro to hint to the compiler that a function should not be -** inlined. -*/ -#if defined(__GNUC__) -# define JSON_NOINLINE __attribute__((noinline)) -#elif defined(_MSC_VER) && _MSC_VER>=1310 -# define JSON_NOINLINE __declspec(noinline) -#else -# define JSON_NOINLINE -#endif - - -static JSON_NOINLINE int jsonParseAddNodeExpand( - JsonParse *pParse, /* Append the node to this object */ - u32 eType, /* Node type */ - u32 n, /* Content size or sub-node count */ - const char *zContent /* Content */ -){ - u32 nNew; - JsonNode *pNew; - assert( pParse->nNode>=pParse->nAlloc ); - if( pParse->oom ) return -1; - nNew = pParse->nAlloc*2 + 10; - pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew); - if( pNew==0 ){ - pParse->oom = 1; - return -1; - } - pParse->nAlloc = nNew; - pParse->aNode = pNew; - assert( pParse->nNodenAlloc ); - return jsonParseAddNode(pParse, eType, n, zContent); -} - -/* -** Create a new JsonNode instance based on the arguments and append that -** instance to the JsonParse. Return the index in pParse->aNode[] of the -** new node, or -1 if a memory allocation fails. -*/ -static int jsonParseAddNode( - JsonParse *pParse, /* Append the node to this object */ - u32 eType, /* Node type */ - u32 n, /* Content size or sub-node count */ - const char *zContent /* Content */ -){ - JsonNode *p; - if( pParse->nNode>=pParse->nAlloc ){ - return jsonParseAddNodeExpand(pParse, eType, n, zContent); - } - p = &pParse->aNode[pParse->nNode]; - p->eType = (u8)eType; - p->jnFlags = 0; - p->n = n; - p->u.zJContent = zContent; - return pParse->nNode++; -} - -/* -** Return true if z[] begins with 4 (or more) hexadecimal digits -*/ -static int jsonIs4Hex(const char *z){ - int i; - for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0; - return 1; -} - -/* -** Parse a single JSON value which begins at pParse->zJson[i]. Return the -** index of the first character past the end of the value parsed. -** -** Return negative for a syntax error. Special cases: return -2 if the -** first non-whitespace character is '}' and return -3 if the first -** non-whitespace character is ']'. -*/ -static int jsonParseValue(JsonParse *pParse, u32 i){ - char c; - u32 j; - int iThis; - int x; - JsonNode *pNode; - const char *z = pParse->zJson; - while( safe_isspace(z[i]) ){ i++; } - if( (c = z[i])=='{' ){ - /* Parse object */ - iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); - if( iThis<0 ) return -1; - for(j=i+1;;j++){ - while( safe_isspace(z[j]) ){ j++; } - if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1; - x = jsonParseValue(pParse, j); - if( x<0 ){ - pParse->iDepth--; - if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1; - return -1; - } - if( pParse->oom ) return -1; - pNode = &pParse->aNode[pParse->nNode-1]; - if( pNode->eType!=JSON_STRING ) return -1; - pNode->jnFlags |= JNODE_LABEL; - j = x; - while( safe_isspace(z[j]) ){ j++; } - if( z[j]!=':' ) return -1; - j++; - x = jsonParseValue(pParse, j); - pParse->iDepth--; - if( x<0 ) return -1; - j = x; - while( safe_isspace(z[j]) ){ j++; } - c = z[j]; - if( c==',' ) continue; - if( c!='}' ) return -1; - break; - } - pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; - return j+1; - }else if( c=='[' ){ - /* Parse array */ - iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); - if( iThis<0 ) return -1; - for(j=i+1;;j++){ - while( safe_isspace(z[j]) ){ j++; } - if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1; - x = jsonParseValue(pParse, j); - pParse->iDepth--; - if( x<0 ){ - if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1; - return -1; - } - j = x; - while( safe_isspace(z[j]) ){ j++; } - c = z[j]; - if( c==',' ) continue; - if( c!=']' ) return -1; - break; - } - pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1; - return j+1; - }else if( c=='"' ){ - /* Parse string */ - u8 jnFlags = 0; - j = i+1; - for(;;){ - c = z[j]; - if( (c & ~0x1f)==0 ){ - /* Control characters are not allowed in strings */ - return -1; - } - if( c=='\\' ){ - c = z[++j]; - if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f' - || c=='n' || c=='r' || c=='t' - || (c=='u' && jsonIs4Hex(z+j+1)) ){ - jnFlags = JNODE_ESCAPE; - }else{ - return -1; - } - }else if( c=='"' ){ - break; - } - j++; - } - jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]); - if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags; - return j+1; - }else if( c=='n' - && strncmp(z+i,"null",4)==0 - && !safe_isalnum(z[i+4]) ){ - jsonParseAddNode(pParse, JSON_NULL, 0, 0); - return i+4; - }else if( c=='t' - && strncmp(z+i,"true",4)==0 - && !safe_isalnum(z[i+4]) ){ - jsonParseAddNode(pParse, JSON_TRUE, 0, 0); - return i+4; - }else if( c=='f' - && strncmp(z+i,"false",5)==0 - && !safe_isalnum(z[i+5]) ){ - jsonParseAddNode(pParse, JSON_FALSE, 0, 0); - return i+5; - }else if( c=='-' || (c>='0' && c<='9') ){ - /* Parse number */ - u8 seenDP = 0; - u8 seenE = 0; - assert( '-' < '0' ); - if( c<='0' ){ - j = c=='-' ? i+1 : i; - if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1; - } - j = i+1; - for(;; j++){ - c = z[j]; - if( c>='0' && c<='9' ) continue; - if( c=='.' ){ - if( z[j-1]=='-' ) return -1; - if( seenDP ) return -1; - seenDP = 1; - continue; - } - if( c=='e' || c=='E' ){ - if( z[j-1]<'0' ) return -1; - if( seenE ) return -1; - seenDP = seenE = 1; - c = z[j+1]; - if( c=='+' || c=='-' ){ - j++; - c = z[j+1]; - } - if( c<'0' || c>'9' ) return -1; - continue; - } - break; - } - if( z[j-1]<'0' ) return -1; - jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT, - j - i, &z[i]); - return j; - }else if( c=='}' ){ - return -2; /* End of {...} */ - }else if( c==']' ){ - return -3; /* End of [...] */ - }else if( c==0 ){ - return 0; /* End of file */ - }else{ - return -1; /* Syntax error */ - } -} - -/* -** Parse a complete JSON string. Return 0 on success or non-zero if there -** are any errors. If an error occurs, free all memory associated with -** pParse. -** -** pParse is uninitialized when this routine is called. -*/ -static int jsonParse( - JsonParse *pParse, /* Initialize and fill this JsonParse object */ - sqlite3_context *pCtx, /* Report errors here */ - const char *zJson /* Input JSON text to be parsed */ -){ - int i; - memset(pParse, 0, sizeof(*pParse)); - if( zJson==0 ) return 1; - pParse->zJson = zJson; - i = jsonParseValue(pParse, 0); - if( pParse->oom ) i = -1; - if( i>0 ){ - assert( pParse->iDepth==0 ); - while( safe_isspace(zJson[i]) ) i++; - if( zJson[i] ) i = -1; - } - if( i<=0 ){ - if( pCtx!=0 ){ - if( pParse->oom ){ - sqlite3_result_error_nomem(pCtx); - }else{ - sqlite3_result_error(pCtx, "malformed JSON", -1); - } - } - jsonParseReset(pParse); - return 1; - } - return 0; -} - -/* Mark node i of pParse as being a child of iParent. Call recursively -** to fill in all the descendants of node i. -*/ -static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){ - JsonNode *pNode = &pParse->aNode[i]; - u32 j; - pParse->aUp[i] = iParent; - switch( pNode->eType ){ - case JSON_ARRAY: { - for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){ - jsonParseFillInParentage(pParse, i+j, i); - } - break; - } - case JSON_OBJECT: { - for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){ - pParse->aUp[i+j] = i; - jsonParseFillInParentage(pParse, i+j+1, i); - } - break; - } - default: { - break; - } - } -} - -/* -** Compute the parentage of all nodes in a completed parse. -*/ -static int jsonParseFindParents(JsonParse *pParse){ - u32 *aUp; - assert( pParse->aUp==0 ); - aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode ); - if( aUp==0 ){ - pParse->oom = 1; - return SQLITE_NOMEM; - } - jsonParseFillInParentage(pParse, 0, 0); - return SQLITE_OK; -} - -/* -** Magic number used for the JSON parse cache in sqlite3_get_auxdata() -*/ -#define JSON_CACHE_ID (-429938) /* First cache entry */ -#define JSON_CACHE_SZ 4 /* Max number of cache entries */ - -/* -** Obtain a complete parse of the JSON found in the first argument -** of the argv array. Use the sqlite3_get_auxdata() cache for this -** parse if it is available. If the cache is not available or if it -** is no longer valid, parse the JSON again and return the new parse, -** and also register the new parse so that it will be available for -** future sqlite3_get_auxdata() calls. -*/ -static JsonParse *jsonParseCached( - sqlite3_context *pCtx, - sqlite3_value **argv, - sqlite3_context *pErrCtx -){ - const char *zJson = (const char*)sqlite3_value_text(argv[0]); - int nJson = sqlite3_value_bytes(argv[0]); - JsonParse *p; - JsonParse *pMatch = 0; - int iKey; - int iMinKey = 0; - u32 iMinHold = 0xffffffff; - u32 iMaxHold = 0; - if( zJson==0 ) return 0; - for(iKey=0; iKeynJson==nJson - && memcmp(p->zJson,zJson,nJson)==0 - ){ - p->nErr = 0; - pMatch = p; - }else if( p->iHoldiHold; - iMinKey = iKey; - } - if( p->iHold>iMaxHold ){ - iMaxHold = p->iHold; - } - } - if( pMatch ){ - pMatch->nErr = 0; - pMatch->iHold = iMaxHold+1; - return pMatch; - } - p = sqlite3_malloc64( sizeof(*p) + nJson + 1 ); - if( p==0 ){ - sqlite3_result_error_nomem(pCtx); - return 0; - } - memset(p, 0, sizeof(*p)); - p->zJson = (char*)&p[1]; - memcpy((char*)p->zJson, zJson, nJson+1); - if( jsonParse(p, pErrCtx, p->zJson) ){ - sqlite3_free(p); - return 0; - } - p->nJson = nJson; - p->iHold = iMaxHold+1; - sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p, - (void(*)(void*))jsonParseFree); - return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey); -} - -/* -** Compare the OBJECT label at pNode against zKey,nKey. Return true on -** a match. -*/ -static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){ - if( pNode->jnFlags & JNODE_RAW ){ - if( pNode->n!=nKey ) return 0; - return strncmp(pNode->u.zJContent, zKey, nKey)==0; - }else{ - if( pNode->n!=nKey+2 ) return 0; - return strncmp(pNode->u.zJContent+1, zKey, nKey)==0; - } -} - -/* forward declaration */ -static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**); - -/* -** Search along zPath to find the node specified. Return a pointer -** to that node, or NULL if zPath is malformed or if there is no such -** node. -** -** If pApnd!=0, then try to append new nodes to complete zPath if it is -** possible to do so and if no existing node corresponds to zPath. If -** new nodes are appended *pApnd is set to 1. -*/ -static JsonNode *jsonLookupStep( - JsonParse *pParse, /* The JSON to search */ - u32 iRoot, /* Begin the search at this node */ - const char *zPath, /* The path to search */ - int *pApnd, /* Append nodes to complete path if not NULL */ - const char **pzErr /* Make *pzErr point to any syntax error in zPath */ -){ - u32 i, j, nKey; - const char *zKey; - JsonNode *pRoot = &pParse->aNode[iRoot]; - if( zPath[0]==0 ) return pRoot; - if( pRoot->jnFlags & JNODE_REPLACE ) return 0; - if( zPath[0]=='.' ){ - if( pRoot->eType!=JSON_OBJECT ) return 0; - zPath++; - if( zPath[0]=='"' ){ - zKey = zPath + 1; - for(i=1; zPath[i] && zPath[i]!='"'; i++){} - nKey = i-1; - if( zPath[i] ){ - i++; - }else{ - *pzErr = zPath; - return 0; - } - }else{ - zKey = zPath; - for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){} - nKey = i; - } - if( nKey==0 ){ - *pzErr = zPath; - return 0; - } - j = 1; - for(;;){ - while( j<=pRoot->n ){ - if( jsonLabelCompare(pRoot+j, zKey, nKey) ){ - return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr); - } - j++; - j += jsonNodeSize(&pRoot[j]); - } - if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; - iRoot += pRoot->u.iAppend; - pRoot = &pParse->aNode[iRoot]; - j = 1; - } - if( pApnd ){ - u32 iStart, iLabel; - JsonNode *pNode; - iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0); - iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey); - zPath += i; - pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); - if( pParse->oom ) return 0; - if( pNode ){ - pRoot = &pParse->aNode[iRoot]; - pRoot->u.iAppend = iStart - iRoot; - pRoot->jnFlags |= JNODE_APPEND; - pParse->aNode[iLabel].jnFlags |= JNODE_RAW; - } - return pNode; - } - }else if( zPath[0]=='[' ){ - i = 0; - j = 1; - while( safe_isdigit(zPath[j]) ){ - i = i*10 + zPath[j] - '0'; - j++; - } - if( j<2 || zPath[j]!=']' ){ - if( zPath[1]=='#' ){ - JsonNode *pBase = pRoot; - int iBase = iRoot; - if( pRoot->eType!=JSON_ARRAY ) return 0; - for(;;){ - while( j<=pBase->n ){ - if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++; - j += jsonNodeSize(&pBase[j]); - } - if( (pBase->jnFlags & JNODE_APPEND)==0 ) break; - iBase += pBase->u.iAppend; - pBase = &pParse->aNode[iBase]; - j = 1; - } - j = 2; - if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){ - unsigned int x = 0; - j = 3; - do{ - x = x*10 + zPath[j] - '0'; - j++; - }while( safe_isdigit(zPath[j]) ); - if( x>i ) return 0; - i -= x; - } - if( zPath[j]!=']' ){ - *pzErr = zPath; - return 0; - } - }else{ - *pzErr = zPath; - return 0; - } - } - if( pRoot->eType!=JSON_ARRAY ) return 0; - zPath += j + 1; - j = 1; - for(;;){ - while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){ - if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--; - j += jsonNodeSize(&pRoot[j]); - } - if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break; - iRoot += pRoot->u.iAppend; - pRoot = &pParse->aNode[iRoot]; - j = 1; - } - if( j<=pRoot->n ){ - return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr); - } - if( i==0 && pApnd ){ - u32 iStart; - JsonNode *pNode; - iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0); - pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr); - if( pParse->oom ) return 0; - if( pNode ){ - pRoot = &pParse->aNode[iRoot]; - pRoot->u.iAppend = iStart - iRoot; - pRoot->jnFlags |= JNODE_APPEND; - } - return pNode; - } - }else{ - *pzErr = zPath; - } - return 0; -} - -/* -** Append content to pParse that will complete zPath. Return a pointer -** to the inserted node, or return NULL if the append fails. -*/ -static JsonNode *jsonLookupAppend( - JsonParse *pParse, /* Append content to the JSON parse */ - const char *zPath, /* Description of content to append */ - int *pApnd, /* Set this flag to 1 */ - const char **pzErr /* Make this point to any syntax error */ -){ - *pApnd = 1; - if( zPath[0]==0 ){ - jsonParseAddNode(pParse, JSON_NULL, 0, 0); - return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1]; - } - if( zPath[0]=='.' ){ - jsonParseAddNode(pParse, JSON_OBJECT, 0, 0); - }else if( strncmp(zPath,"[0]",3)==0 ){ - jsonParseAddNode(pParse, JSON_ARRAY, 0, 0); - }else{ - return 0; - } - if( pParse->oom ) return 0; - return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr); -} - -/* -** Return the text of a syntax error message on a JSON path. Space is -** obtained from sqlite3_malloc(). -*/ -static char *jsonPathSyntaxError(const char *zErr){ - return sqlite3_mprintf("JSON path error near '%q'", zErr); -} - -/* -** Do a node lookup using zPath. Return a pointer to the node on success. -** Return NULL if not found or if there is an error. -** -** On an error, write an error message into pCtx and increment the -** pParse->nErr counter. -** -** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if -** nodes are appended. -*/ -static JsonNode *jsonLookup( - JsonParse *pParse, /* The JSON to search */ - const char *zPath, /* The path to search */ - int *pApnd, /* Append nodes to complete path if not NULL */ - sqlite3_context *pCtx /* Report errors here, if not NULL */ -){ - const char *zErr = 0; - JsonNode *pNode = 0; - char *zMsg; - - if( zPath==0 ) return 0; - if( zPath[0]!='$' ){ - zErr = zPath; - goto lookup_err; - } - zPath++; - pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr); - if( zErr==0 ) return pNode; - -lookup_err: - pParse->nErr++; - assert( zErr!=0 && pCtx!=0 ); - zMsg = jsonPathSyntaxError(zErr); - if( zMsg ){ - sqlite3_result_error(pCtx, zMsg, -1); - sqlite3_free(zMsg); - }else{ - sqlite3_result_error_nomem(pCtx); - } - return 0; -} - - -/* -** Report the wrong number of arguments for json_insert(), json_replace() -** or json_set(). -*/ -static void jsonWrongNumArgs( - sqlite3_context *pCtx, - const char *zFuncName -){ - char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments", - zFuncName); - sqlite3_result_error(pCtx, zMsg, -1); - sqlite3_free(zMsg); -} - -/* -** Mark all NULL entries in the Object passed in as JNODE_REMOVE. -*/ -static void jsonRemoveAllNulls(JsonNode *pNode){ - int i, n; - assert( pNode->eType==JSON_OBJECT ); - n = pNode->n; - for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){ - switch( pNode[i].eType ){ - case JSON_NULL: - pNode[i].jnFlags |= JNODE_REMOVE; - break; - case JSON_OBJECT: - jsonRemoveAllNulls(&pNode[i]); - break; - } - } -} - - -/**************************************************************************** -** SQL functions used for testing and debugging -****************************************************************************/ - -#ifdef SQLITE_DEBUG -/* -** The json_parse(JSON) function returns a string which describes -** a parse of the JSON provided. Or it returns NULL if JSON is not -** well-formed. -*/ -static void jsonParseFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonString s; /* Output string - not real JSON */ - JsonParse x; /* The parse */ - u32 i; - - assert( argc==1 ); - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - jsonParseFindParents(&x); - jsonInit(&s, ctx); - for(i=0; inNode ); - if( argc==2 ){ - const char *zPath = (const char*)sqlite3_value_text(argv[1]); - pNode = jsonLookup(p, zPath, 0, ctx); - }else{ - pNode = p->aNode; - } - if( pNode==0 ){ - return; - } - if( pNode->eType==JSON_ARRAY ){ - assert( (pNode->jnFlags & JNODE_APPEND)==0 ); - for(i=1; i<=pNode->n; n++){ - i += jsonNodeSize(&pNode[i]); - } - } - sqlite3_result_int64(ctx, n); -} - -/* -** json_extract(JSON, PATH, ...) -** -** Return the element described by PATH. Return NULL if there is no -** PATH element. If there are multiple PATHs, then return a JSON array -** with the result from each path. Throw an error if the JSON or any PATH -** is malformed. -*/ -static void jsonExtractFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse *p; /* The parse */ - JsonNode *pNode; - const char *zPath; - JsonString jx; - int i; - - if( argc<2 ) return; - p = jsonParseCached(ctx, argv, ctx); - if( p==0 ) return; - jsonInit(&jx, ctx); - jsonAppendChar(&jx, '['); - for(i=1; inErr ) break; - if( argc>2 ){ - jsonAppendSeparator(&jx); - if( pNode ){ - jsonRenderNode(pNode, &jx, 0); - }else{ - jsonAppendRaw(&jx, "null", 4); - } - }else if( pNode ){ - jsonReturn(pNode, ctx, 0); - } - } - if( argc>2 && i==argc ){ - jsonAppendChar(&jx, ']'); - jsonResult(&jx); - sqlite3_result_subtype(ctx, JSON_SUBTYPE); - } - jsonReset(&jx); -} - -/* This is the RFC 7396 MergePatch algorithm. -*/ -static JsonNode *jsonMergePatch( - JsonParse *pParse, /* The JSON parser that contains the TARGET */ - u32 iTarget, /* Node of the TARGET in pParse */ - JsonNode *pPatch /* The PATCH */ -){ - u32 i, j; - u32 iRoot; - JsonNode *pTarget; - if( pPatch->eType!=JSON_OBJECT ){ - return pPatch; - } - assert( iTarget>=0 && iTargetnNode ); - pTarget = &pParse->aNode[iTarget]; - assert( (pPatch->jnFlags & JNODE_APPEND)==0 ); - if( pTarget->eType!=JSON_OBJECT ){ - jsonRemoveAllNulls(pPatch); - return pPatch; - } - iRoot = iTarget; - for(i=1; in; i += jsonNodeSize(&pPatch[i+1])+1){ - u32 nKey; - const char *zKey; - assert( pPatch[i].eType==JSON_STRING ); - assert( pPatch[i].jnFlags & JNODE_LABEL ); - nKey = pPatch[i].n; - zKey = pPatch[i].u.zJContent; - assert( (pPatch[i].jnFlags & JNODE_RAW)==0 ); - for(j=1; jn; j += jsonNodeSize(&pTarget[j+1])+1 ){ - assert( pTarget[j].eType==JSON_STRING ); - assert( pTarget[j].jnFlags & JNODE_LABEL ); - assert( (pPatch[i].jnFlags & JNODE_RAW)==0 ); - if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){ - if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break; - if( pPatch[i+1].eType==JSON_NULL ){ - pTarget[j+1].jnFlags |= JNODE_REMOVE; - }else{ - JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]); - if( pNew==0 ) return 0; - pTarget = &pParse->aNode[iTarget]; - if( pNew!=&pTarget[j+1] ){ - pTarget[j+1].u.pPatch = pNew; - pTarget[j+1].jnFlags |= JNODE_PATCH; - } - } - break; - } - } - if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){ - int iStart, iPatch; - iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0); - jsonParseAddNode(pParse, JSON_STRING, nKey, zKey); - iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0); - if( pParse->oom ) return 0; - jsonRemoveAllNulls(pPatch); - pTarget = &pParse->aNode[iTarget]; - pParse->aNode[iRoot].jnFlags |= JNODE_APPEND; - pParse->aNode[iRoot].u.iAppend = iStart - iRoot; - iRoot = iStart; - pParse->aNode[iPatch].jnFlags |= JNODE_PATCH; - pParse->aNode[iPatch].u.pPatch = &pPatch[i+1]; - } - } - return pTarget; -} - -/* -** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON -** object that is the result of running the RFC 7396 MergePatch() algorithm -** on the two arguments. -*/ -static void jsonPatchFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The JSON that is being patched */ - JsonParse y; /* The patch */ - JsonNode *pResult; /* The result of the merge */ - - UNUSED_PARAM(argc); - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){ - jsonParseReset(&x); - return; - } - pResult = jsonMergePatch(&x, 0, y.aNode); - assert( pResult!=0 || x.oom ); - if( pResult ){ - jsonReturnJson(pResult, ctx, 0); - }else{ - sqlite3_result_error_nomem(ctx); - } - jsonParseReset(&x); - jsonParseReset(&y); -} - - -/* -** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON -** object that contains all name/value given in arguments. Or if any name -** is not a string or if any value is a BLOB, throw an error. -*/ -static void jsonObjectFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - int i; - JsonString jx; - const char *z; - u32 n; - - if( argc&1 ){ - sqlite3_result_error(ctx, "json_object() requires an even number " - "of arguments", -1); - return; - } - jsonInit(&jx, ctx); - jsonAppendChar(&jx, '{'); - for(i=0; ijnFlags |= JNODE_REMOVE; - } - if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){ - jsonReturnJson(x.aNode, ctx, 0); - } -remove_done: - jsonParseReset(&x); -} - -/* -** json_replace(JSON, PATH, VALUE, ...) -** -** Replace the value at PATH with VALUE. If PATH does not already exist, -** this routine is a no-op. If JSON or PATH is malformed, throw an error. -*/ -static void jsonReplaceFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The parse */ - JsonNode *pNode; - const char *zPath; - u32 i; - - if( argc<1 ) return; - if( (argc&1)==0 ) { - jsonWrongNumArgs(ctx, "replace"); - return; - } - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - assert( x.nNode ); - for(i=1; i<(u32)argc; i+=2){ - zPath = (const char*)sqlite3_value_text(argv[i]); - pNode = jsonLookup(&x, zPath, 0, ctx); - if( x.nErr ) goto replace_err; - if( pNode ){ - pNode->jnFlags |= (u8)JNODE_REPLACE; - pNode->u.iReplace = i + 1; - } - } - if( x.aNode[0].jnFlags & JNODE_REPLACE ){ - sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]); - }else{ - jsonReturnJson(x.aNode, ctx, argv); - } -replace_err: - jsonParseReset(&x); -} - -/* -** json_set(JSON, PATH, VALUE, ...) -** -** Set the value at PATH to VALUE. Create the PATH if it does not already -** exist. Overwrite existing values that do exist. -** If JSON or PATH is malformed, throw an error. -** -** json_insert(JSON, PATH, VALUE, ...) -** -** Create PATH and initialize it to VALUE. If PATH already exists, this -** routine is a no-op. If JSON or PATH is malformed, throw an error. -*/ -static void jsonSetFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse x; /* The parse */ - JsonNode *pNode; - const char *zPath; - u32 i; - int bApnd; - int bIsSet = *(int*)sqlite3_user_data(ctx); - - if( argc<1 ) return; - if( (argc&1)==0 ) { - jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert"); - return; - } - if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return; - assert( x.nNode ); - for(i=1; i<(u32)argc; i+=2){ - zPath = (const char*)sqlite3_value_text(argv[i]); - bApnd = 0; - pNode = jsonLookup(&x, zPath, &bApnd, ctx); - if( x.oom ){ - sqlite3_result_error_nomem(ctx); - goto jsonSetDone; - }else if( x.nErr ){ - goto jsonSetDone; - }else if( pNode && (bApnd || bIsSet) ){ - pNode->jnFlags |= (u8)JNODE_REPLACE; - pNode->u.iReplace = i + 1; - } - } - if( x.aNode[0].jnFlags & JNODE_REPLACE ){ - sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]); - }else{ - jsonReturnJson(x.aNode, ctx, argv); - } -jsonSetDone: - jsonParseReset(&x); -} - -/* -** json_type(JSON) -** json_type(JSON, PATH) -** -** Return the top-level "type" of a JSON string. Throw an error if -** either the JSON or PATH inputs are not well-formed. -*/ -static void jsonTypeFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse *p; /* The parse */ - const char *zPath; - JsonNode *pNode; - - p = jsonParseCached(ctx, argv, ctx); - if( p==0 ) return; - if( argc==2 ){ - zPath = (const char*)sqlite3_value_text(argv[1]); - pNode = jsonLookup(p, zPath, 0, ctx); - }else{ - pNode = p->aNode; - } - if( pNode ){ - sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC); - } -} - -/* -** json_valid(JSON) -** -** Return 1 if JSON is a well-formed JSON string according to RFC-7159. -** Return 0 otherwise. -*/ -static void jsonValidFunc( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonParse *p; /* The parse */ - UNUSED_PARAM(argc); - p = jsonParseCached(ctx, argv, 0); - sqlite3_result_int(ctx, p!=0); -} - - -/**************************************************************************** -** Aggregate SQL function implementations -****************************************************************************/ -/* -** json_group_array(VALUE) -** -** Return a JSON array composed of all values in the aggregate. -*/ -static void jsonArrayStep( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonString *pStr; - UNUSED_PARAM(argc); - pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); - if( pStr ){ - if( pStr->zBuf==0 ){ - jsonInit(pStr, ctx); - jsonAppendChar(pStr, '['); - }else if( pStr->nUsed>1 ){ - jsonAppendChar(pStr, ','); - pStr->pCtx = ctx; - } - jsonAppendValue(pStr, argv[0]); - } -} -static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){ - JsonString *pStr; - pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); - if( pStr ){ - pStr->pCtx = ctx; - jsonAppendChar(pStr, ']'); - if( pStr->bErr ){ - if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx); - assert( pStr->bStatic ); - }else if( isFinal ){ - sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, - pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free); - pStr->bStatic = 1; - }else{ - sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); - pStr->nUsed--; - } - }else{ - sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC); - } - sqlite3_result_subtype(ctx, JSON_SUBTYPE); -} -static void jsonArrayValue(sqlite3_context *ctx){ - jsonArrayCompute(ctx, 0); -} -static void jsonArrayFinal(sqlite3_context *ctx){ - jsonArrayCompute(ctx, 1); -} - -#ifndef SQLITE_OMIT_WINDOWFUNC -/* -** This method works for both json_group_array() and json_group_object(). -** It works by removing the first element of the group by searching forward -** to the first comma (",") that is not within a string and deleting all -** text through that comma. -*/ -static void jsonGroupInverse( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - unsigned int i; - int inStr = 0; - int nNest = 0; - char *z; - char c; - JsonString *pStr; - UNUSED_PARAM(argc); - UNUSED_PARAM(argv); - pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); -#ifdef NEVER - /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will - ** always have been called to initalize it */ - if( NEVER(!pStr) ) return; -#endif - z = pStr->zBuf; - for(i=1; (c = z[i])!=',' || inStr || nNest; i++){ - if( i>=pStr->nUsed ){ - pStr->nUsed = 1; - return; - } - if( c=='"' ){ - inStr = !inStr; - }else if( c=='\\' ){ - i++; - }else if( !inStr ){ - if( c=='{' || c=='[' ) nNest++; - if( c=='}' || c==']' ) nNest--; - } - } - pStr->nUsed -= i; - memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1); -} -#else -# define jsonGroupInverse 0 -#endif - - -/* -** json_group_obj(NAME,VALUE) -** -** Return a JSON object composed of all names and values in the aggregate. -*/ -static void jsonObjectStep( - sqlite3_context *ctx, - int argc, - sqlite3_value **argv -){ - JsonString *pStr; - const char *z; - u32 n; - UNUSED_PARAM(argc); - pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); - if( pStr ){ - if( pStr->zBuf==0 ){ - jsonInit(pStr, ctx); - jsonAppendChar(pStr, '{'); - }else if( pStr->nUsed>1 ){ - jsonAppendChar(pStr, ','); - pStr->pCtx = ctx; - } - z = (const char*)sqlite3_value_text(argv[0]); - n = (u32)sqlite3_value_bytes(argv[0]); - jsonAppendString(pStr, z, n); - jsonAppendChar(pStr, ':'); - jsonAppendValue(pStr, argv[1]); - } -} -static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){ - JsonString *pStr; - pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); - if( pStr ){ - jsonAppendChar(pStr, '}'); - if( pStr->bErr ){ - if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx); - assert( pStr->bStatic ); - }else if( isFinal ){ - sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, - pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free); - pStr->bStatic = 1; - }else{ - sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); - pStr->nUsed--; - } - }else{ - sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC); - } - sqlite3_result_subtype(ctx, JSON_SUBTYPE); -} -static void jsonObjectValue(sqlite3_context *ctx){ - jsonObjectCompute(ctx, 0); -} -static void jsonObjectFinal(sqlite3_context *ctx){ - jsonObjectCompute(ctx, 1); -} - - - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/**************************************************************************** -** The json_each virtual table -****************************************************************************/ -typedef struct JsonEachCursor JsonEachCursor; -struct JsonEachCursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - u32 iRowid; /* The rowid */ - u32 iBegin; /* The first node of the scan */ - u32 i; /* Index in sParse.aNode[] of current row */ - u32 iEnd; /* EOF when i equals or exceeds this value */ - u8 eType; /* Type of top-level element */ - u8 bRecursive; /* True for json_tree(). False for json_each() */ - char *zJson; /* Input JSON */ - char *zRoot; /* Path by which to filter zJson */ - JsonParse sParse; /* Parse of the input JSON */ -}; - -/* Constructor for the json_each virtual table */ -static int jsonEachConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - sqlite3_vtab *pNew; - int rc; - -/* Column numbers */ -#define JEACH_KEY 0 -#define JEACH_VALUE 1 -#define JEACH_TYPE 2 -#define JEACH_ATOM 3 -#define JEACH_ID 4 -#define JEACH_PARENT 5 -#define JEACH_FULLKEY 6 -#define JEACH_PATH 7 -/* The xBestIndex method assumes that the JSON and ROOT columns are -** the last two columns in the table. Should this ever changes, be -** sure to update the xBestIndex method. */ -#define JEACH_JSON 8 -#define JEACH_ROOT 9 - - UNUSED_PARAM(pzErr); - UNUSED_PARAM(argv); - UNUSED_PARAM(argc); - UNUSED_PARAM(pAux); - rc = sqlite3_declare_vtab(db, - "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path," - "json HIDDEN,root HIDDEN)"); - if( rc==SQLITE_OK ){ - pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); - sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); - } - return rc; -} - -/* destructor for json_each virtual table */ -static int jsonEachDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* constructor for a JsonEachCursor object for json_each(). */ -static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - JsonEachCursor *pCur; - - UNUSED_PARAM(p); - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* constructor for a JsonEachCursor object for json_tree(). */ -static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - int rc = jsonEachOpenEach(p, ppCursor); - if( rc==SQLITE_OK ){ - JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor; - pCur->bRecursive = 1; - } - return rc; -} - -/* Reset a JsonEachCursor back to its original state. Free any memory -** held. */ -static void jsonEachCursorReset(JsonEachCursor *p){ - sqlite3_free(p->zJson); - sqlite3_free(p->zRoot); - jsonParseReset(&p->sParse); - p->iRowid = 0; - p->i = 0; - p->iEnd = 0; - p->eType = 0; - p->zJson = 0; - p->zRoot = 0; -} - -/* Destructor for a jsonEachCursor object */ -static int jsonEachClose(sqlite3_vtab_cursor *cur){ - JsonEachCursor *p = (JsonEachCursor*)cur; - jsonEachCursorReset(p); - sqlite3_free(cur); - return SQLITE_OK; -} - -/* Return TRUE if the jsonEachCursor object has been advanced off the end -** of the JSON object */ -static int jsonEachEof(sqlite3_vtab_cursor *cur){ - JsonEachCursor *p = (JsonEachCursor*)cur; - return p->i >= p->iEnd; -} - -/* Advance the cursor to the next element for json_tree() */ -static int jsonEachNext(sqlite3_vtab_cursor *cur){ - JsonEachCursor *p = (JsonEachCursor*)cur; - if( p->bRecursive ){ - if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++; - p->i++; - p->iRowid++; - if( p->iiEnd ){ - u32 iUp = p->sParse.aUp[p->i]; - JsonNode *pUp = &p->sParse.aNode[iUp]; - p->eType = pUp->eType; - if( pUp->eType==JSON_ARRAY ){ - if( iUp==p->i-1 ){ - pUp->u.iKey = 0; - }else{ - pUp->u.iKey++; - } - } - } - }else{ - switch( p->eType ){ - case JSON_ARRAY: { - p->i += jsonNodeSize(&p->sParse.aNode[p->i]); - p->iRowid++; - break; - } - case JSON_OBJECT: { - p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]); - p->iRowid++; - break; - } - default: { - p->i = p->iEnd; - break; - } - } - } - return SQLITE_OK; -} - -/* Append the name of the path for element i to pStr -*/ -static void jsonEachComputePath( - JsonEachCursor *p, /* The cursor */ - JsonString *pStr, /* Write the path here */ - u32 i /* Path to this element */ -){ - JsonNode *pNode, *pUp; - u32 iUp; - if( i==0 ){ - jsonAppendChar(pStr, '$'); - return; - } - iUp = p->sParse.aUp[i]; - jsonEachComputePath(p, pStr, iUp); - pNode = &p->sParse.aNode[i]; - pUp = &p->sParse.aNode[iUp]; - if( pUp->eType==JSON_ARRAY ){ - jsonPrintf(30, pStr, "[%d]", pUp->u.iKey); - }else{ - assert( pUp->eType==JSON_OBJECT ); - if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--; - assert( pNode->eType==JSON_STRING ); - assert( pNode->jnFlags & JNODE_LABEL ); - jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1); - } -} - -/* Return the value of a column */ -static int jsonEachColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - JsonEachCursor *p = (JsonEachCursor*)cur; - JsonNode *pThis = &p->sParse.aNode[p->i]; - switch( i ){ - case JEACH_KEY: { - if( p->i==0 ) break; - if( p->eType==JSON_OBJECT ){ - jsonReturn(pThis, ctx, 0); - }else if( p->eType==JSON_ARRAY ){ - u32 iKey; - if( p->bRecursive ){ - if( p->iRowid==0 ) break; - iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey; - }else{ - iKey = p->iRowid; - } - sqlite3_result_int64(ctx, (sqlite3_int64)iKey); - } - break; - } - case JEACH_VALUE: { - if( pThis->jnFlags & JNODE_LABEL ) pThis++; - jsonReturn(pThis, ctx, 0); - break; - } - case JEACH_TYPE: { - if( pThis->jnFlags & JNODE_LABEL ) pThis++; - sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC); - break; - } - case JEACH_ATOM: { - if( pThis->jnFlags & JNODE_LABEL ) pThis++; - if( pThis->eType>=JSON_ARRAY ) break; - jsonReturn(pThis, ctx, 0); - break; - } - case JEACH_ID: { - sqlite3_result_int64(ctx, - (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0)); - break; - } - case JEACH_PARENT: { - if( p->i>p->iBegin && p->bRecursive ){ - sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]); - } - break; - } - case JEACH_FULLKEY: { - JsonString x; - jsonInit(&x, ctx); - if( p->bRecursive ){ - jsonEachComputePath(p, &x, p->i); - }else{ - if( p->zRoot ){ - jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot)); - }else{ - jsonAppendChar(&x, '$'); - } - if( p->eType==JSON_ARRAY ){ - jsonPrintf(30, &x, "[%d]", p->iRowid); - }else if( p->eType==JSON_OBJECT ){ - jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1); - } - } - jsonResult(&x); - break; - } - case JEACH_PATH: { - if( p->bRecursive ){ - JsonString x; - jsonInit(&x, ctx); - jsonEachComputePath(p, &x, p->sParse.aUp[p->i]); - jsonResult(&x); - break; - } - /* For json_each() path and root are the same so fall through - ** into the root case */ - /* no break */ deliberate_fall_through - } - default: { - const char *zRoot = p->zRoot; - if( zRoot==0 ) zRoot = "$"; - sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC); - break; - } - case JEACH_JSON: { - assert( i==JEACH_JSON ); - sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC); - break; - } - } - return SQLITE_OK; -} - -/* Return the current rowid value */ -static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - JsonEachCursor *p = (JsonEachCursor*)cur; - *pRowid = p->iRowid; - return SQLITE_OK; -} - -/* The query strategy is to look for an equality constraint on the json -** column. Without such a constraint, the table cannot operate. idxNum is -** 1 if the constraint is found, 3 if the constraint and zRoot are found, -** and 0 otherwise. -*/ -static int jsonEachBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; /* Loop counter or computed array index */ - int aIdx[2]; /* Index of constraints for JSON and ROOT */ - int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */ - int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */ - const struct sqlite3_index_constraint *pConstraint; - - /* This implementation assumes that JSON and ROOT are the last two - ** columns in the table */ - assert( JEACH_ROOT == JEACH_JSON+1 ); - UNUSED_PARAM(tab); - aIdx[0] = aIdx[1] = -1; - pConstraint = pIdxInfo->aConstraint; - for(i=0; inConstraint; i++, pConstraint++){ - int iCol; - int iMask; - if( pConstraint->iColumn < JEACH_JSON ) continue; - iCol = pConstraint->iColumn - JEACH_JSON; - assert( iCol==0 || iCol==1 ); - iMask = 1 << iCol; - if( pConstraint->usable==0 ){ - unusableMask |= iMask; - }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - aIdx[iCol] = i; - idxMask |= iMask; - } - } - if( (unusableMask & ~idxMask)!=0 ){ - /* If there are any unusable constraints on JSON or ROOT, then reject - ** this entire plan */ - return SQLITE_CONSTRAINT; - } - if( aIdx[0]<0 ){ - /* No JSON input. Leave estimatedCost at the huge value that it was - ** initialized to to discourage the query planner from selecting this - ** plan. */ - pIdxInfo->idxNum = 0; - }else{ - pIdxInfo->estimatedCost = 1.0; - i = aIdx[0]; - pIdxInfo->aConstraintUsage[i].argvIndex = 1; - pIdxInfo->aConstraintUsage[i].omit = 1; - if( aIdx[1]<0 ){ - pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */ - }else{ - i = aIdx[1]; - pIdxInfo->aConstraintUsage[i].argvIndex = 2; - pIdxInfo->aConstraintUsage[i].omit = 1; - pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */ - } - } - return SQLITE_OK; -} - -/* Start a search on a new JSON string */ -static int jsonEachFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - JsonEachCursor *p = (JsonEachCursor*)cur; - const char *z; - const char *zRoot = 0; - sqlite3_int64 n; - - UNUSED_PARAM(idxStr); - UNUSED_PARAM(argc); - jsonEachCursorReset(p); - if( idxNum==0 ) return SQLITE_OK; - z = (const char*)sqlite3_value_text(argv[0]); - if( z==0 ) return SQLITE_OK; - n = sqlite3_value_bytes(argv[0]); - p->zJson = sqlite3_malloc64( n+1 ); - if( p->zJson==0 ) return SQLITE_NOMEM; - memcpy(p->zJson, z, (size_t)n+1); - if( jsonParse(&p->sParse, 0, p->zJson) ){ - int rc = SQLITE_NOMEM; - if( p->sParse.oom==0 ){ - sqlite3_free(cur->pVtab->zErrMsg); - cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON"); - if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR; - } - jsonEachCursorReset(p); - return rc; - }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){ - jsonEachCursorReset(p); - return SQLITE_NOMEM; - }else{ - JsonNode *pNode = 0; - if( idxNum==3 ){ - const char *zErr = 0; - zRoot = (const char*)sqlite3_value_text(argv[1]); - if( zRoot==0 ) return SQLITE_OK; - n = sqlite3_value_bytes(argv[1]); - p->zRoot = sqlite3_malloc64( n+1 ); - if( p->zRoot==0 ) return SQLITE_NOMEM; - memcpy(p->zRoot, zRoot, (size_t)n+1); - if( zRoot[0]!='$' ){ - zErr = zRoot; - }else{ - pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr); - } - if( zErr ){ - sqlite3_free(cur->pVtab->zErrMsg); - cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr); - jsonEachCursorReset(p); - return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; - }else if( pNode==0 ){ - return SQLITE_OK; - } - }else{ - pNode = p->sParse.aNode; - } - p->iBegin = p->i = (int)(pNode - p->sParse.aNode); - p->eType = pNode->eType; - if( p->eType>=JSON_ARRAY ){ - pNode->u.iKey = 0; - p->iEnd = p->i + pNode->n + 1; - if( p->bRecursive ){ - p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType; - if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){ - p->i--; - } - }else{ - p->i++; - } - }else{ - p->iEnd = p->i+1; - } - } - return SQLITE_OK; -} - -/* The methods of the json_each virtual table */ -static sqlite3_module jsonEachModule = { - 0, /* iVersion */ - 0, /* xCreate */ - jsonEachConnect, /* xConnect */ - jsonEachBestIndex, /* xBestIndex */ - jsonEachDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - jsonEachOpenEach, /* xOpen - open a cursor */ - jsonEachClose, /* xClose - close a cursor */ - jsonEachFilter, /* xFilter - configure scan constraints */ - jsonEachNext, /* xNext - advance a cursor */ - jsonEachEof, /* xEof - check for end of scan */ - jsonEachColumn, /* xColumn - read data */ - jsonEachRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0 /* xShadowName */ -}; - -/* The methods of the json_tree virtual table. */ -static sqlite3_module jsonTreeModule = { - 0, /* iVersion */ - 0, /* xCreate */ - jsonEachConnect, /* xConnect */ - jsonEachBestIndex, /* xBestIndex */ - jsonEachDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - jsonEachOpenTree, /* xOpen - open a cursor */ - jsonEachClose, /* xClose - close a cursor */ - jsonEachFilter, /* xFilter - configure scan constraints */ - jsonEachNext, /* xNext - advance a cursor */ - jsonEachEof, /* xEof - check for end of scan */ - jsonEachColumn, /* xColumn - read data */ - jsonEachRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0 /* xShadowName */ -}; -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -/**************************************************************************** -** The following routines are the only publically visible identifiers in this -** file. Call the following routines in order to register the various SQL -** functions and the virtual table implemented by this file. -****************************************************************************/ - -SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){ - int rc = SQLITE_OK; - unsigned int i; - static const struct { - const char *zName; - int nArg; - int flag; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } aFunc[] = { - { "json", 1, 0, jsonRemoveFunc }, - { "json_array", -1, 0, jsonArrayFunc }, - { "json_array_length", 1, 0, jsonArrayLengthFunc }, - { "json_array_length", 2, 0, jsonArrayLengthFunc }, - { "json_extract", -1, 0, jsonExtractFunc }, - { "json_insert", -1, 0, jsonSetFunc }, - { "json_object", -1, 0, jsonObjectFunc }, - { "json_patch", 2, 0, jsonPatchFunc }, - { "json_quote", 1, 0, jsonQuoteFunc }, - { "json_remove", -1, 0, jsonRemoveFunc }, - { "json_replace", -1, 0, jsonReplaceFunc }, - { "json_set", -1, 1, jsonSetFunc }, - { "json_type", 1, 0, jsonTypeFunc }, - { "json_type", 2, 0, jsonTypeFunc }, - { "json_valid", 1, 0, jsonValidFunc }, - -#if SQLITE_DEBUG - /* DEBUG and TESTING functions */ - { "json_parse", 1, 0, jsonParseFunc }, - { "json_test1", 1, 0, jsonTest1Func }, -#endif - }; - static const struct { - const char *zName; - int nArg; - void (*xStep)(sqlite3_context*,int,sqlite3_value**); - void (*xFinal)(sqlite3_context*); - void (*xValue)(sqlite3_context*); - } aAgg[] = { - { "json_group_array", 1, - jsonArrayStep, jsonArrayFinal, jsonArrayValue }, - { "json_group_object", 2, - jsonObjectStep, jsonObjectFinal, jsonObjectValue }, - }; -#ifndef SQLITE_OMIT_VIRTUALTABLE - static const struct { - const char *zName; - sqlite3_module *pModule; - } aMod[] = { - { "json_each", &jsonEachModule }, - { "json_tree", &jsonTreeModule }, - }; -#endif - static const int enc = - SQLITE_UTF8 | - SQLITE_DETERMINISTIC | - SQLITE_INNOCUOUS; - for(i=0; i */ -/* #include */ -/* #include */ -/* #include */ - -/* The following macro is used to suppress compiler warnings. -*/ -#ifndef UNUSED_PARAMETER -# define UNUSED_PARAMETER(x) (void)(x) -#endif - -typedef struct Rtree Rtree; -typedef struct RtreeCursor RtreeCursor; -typedef struct RtreeNode RtreeNode; -typedef struct RtreeCell RtreeCell; -typedef struct RtreeConstraint RtreeConstraint; -typedef struct RtreeMatchArg RtreeMatchArg; -typedef struct RtreeGeomCallback RtreeGeomCallback; -typedef union RtreeCoord RtreeCoord; -typedef struct RtreeSearchPoint RtreeSearchPoint; - -/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ -#define RTREE_MAX_DIMENSIONS 5 - -/* Maximum number of auxiliary columns */ -#define RTREE_MAX_AUX_COLUMN 100 - -/* Size of hash table Rtree.aHash. This hash table is not expected to -** ever contain very many entries, so a fixed number of buckets is -** used. -*/ -#define HASHSIZE 97 - -/* The xBestIndex method of this virtual table requires an estimate of -** the number of rows in the virtual table to calculate the costs of -** various strategies. If possible, this estimate is loaded from the -** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum). -** Otherwise, if no sqlite_stat1 entry is available, use -** RTREE_DEFAULT_ROWEST. -*/ -#define RTREE_DEFAULT_ROWEST 1048576 -#define RTREE_MIN_ROWEST 100 - -/* -** An rtree virtual-table object. -*/ -struct Rtree { - sqlite3_vtab base; /* Base class. Must be first */ - sqlite3 *db; /* Host database connection */ - int iNodeSize; /* Size in bytes of each node in the node table */ - u8 nDim; /* Number of dimensions */ - u8 nDim2; /* Twice the number of dimensions */ - u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */ - u8 nBytesPerCell; /* Bytes consumed per cell */ - u8 inWrTrans; /* True if inside write transaction */ - u8 nAux; /* # of auxiliary columns in %_rowid */ - u8 nAuxNotNull; /* Number of initial not-null aux columns */ -#ifdef SQLITE_DEBUG - u8 bCorrupt; /* Shadow table corruption detected */ -#endif - int iDepth; /* Current depth of the r-tree structure */ - char *zDb; /* Name of database containing r-tree table */ - char *zName; /* Name of r-tree table */ - u32 nBusy; /* Current number of users of this structure */ - i64 nRowEst; /* Estimated number of rows in this table */ - u32 nCursor; /* Number of open cursors */ - u32 nNodeRef; /* Number RtreeNodes with positive nRef */ - char *zReadAuxSql; /* SQL for statement to read aux data */ - - /* List of nodes removed during a CondenseTree operation. List is - ** linked together via the pointer normally used for hash chains - - ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree - ** headed by the node (leaf nodes have RtreeNode.iNode==0). - */ - RtreeNode *pDeleted; - int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ - - /* Blob I/O on xxx_node */ - sqlite3_blob *pNodeBlob; - - /* Statements to read/write/delete a record from xxx_node */ - sqlite3_stmt *pWriteNode; - sqlite3_stmt *pDeleteNode; - - /* Statements to read/write/delete a record from xxx_rowid */ - sqlite3_stmt *pReadRowid; - sqlite3_stmt *pWriteRowid; - sqlite3_stmt *pDeleteRowid; - - /* Statements to read/write/delete a record from xxx_parent */ - sqlite3_stmt *pReadParent; - sqlite3_stmt *pWriteParent; - sqlite3_stmt *pDeleteParent; - - /* Statement for writing to the "aux:" fields, if there are any */ - sqlite3_stmt *pWriteAux; - - RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ -}; - -/* Possible values for Rtree.eCoordType: */ -#define RTREE_COORD_REAL32 0 -#define RTREE_COORD_INT32 1 - -/* -** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will -** only deal with integer coordinates. No floating point operations -** will be done. -*/ -#ifdef SQLITE_RTREE_INT_ONLY - typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */ - typedef int RtreeValue; /* Low accuracy coordinate */ -# define RTREE_ZERO 0 -#else - typedef double RtreeDValue; /* High accuracy coordinate */ - typedef float RtreeValue; /* Low accuracy coordinate */ -# define RTREE_ZERO 0.0 -#endif - -/* -** Set the Rtree.bCorrupt flag -*/ -#ifdef SQLITE_DEBUG -# define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1) -#else -# define RTREE_IS_CORRUPT(X) -#endif - -/* -** When doing a search of an r-tree, instances of the following structure -** record intermediate results from the tree walk. -** -** The id is always a node-id. For iLevel>=1 the id is the node-id of -** the node that the RtreeSearchPoint represents. When iLevel==0, however, -** the id is of the parent node and the cell that RtreeSearchPoint -** represents is the iCell-th entry in the parent node. -*/ -struct RtreeSearchPoint { - RtreeDValue rScore; /* The score for this node. Smallest goes first. */ - sqlite3_int64 id; /* Node ID */ - u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */ - u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */ - u8 iCell; /* Cell index within the node */ -}; - -/* -** The minimum number of cells allowed for a node is a third of the -** maximum. In Gutman's notation: -** -** m = M/3 -** -** If an R*-tree "Reinsert" operation is required, the same number of -** cells are removed from the overfull node and reinserted into the tree. -*/ -#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) -#define RTREE_REINSERT(p) RTREE_MINCELLS(p) -#define RTREE_MAXCELLS 51 - -/* -** The smallest possible node-size is (512-64)==448 bytes. And the largest -** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates). -** Therefore all non-root nodes must contain at least 3 entries. Since -** 3^40 is greater than 2^64, an r-tree structure always has a depth of -** 40 or less. -*/ -#define RTREE_MAX_DEPTH 40 - - -/* -** Number of entries in the cursor RtreeNode cache. The first entry is -** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining -** entries cache the RtreeNode for the first elements of the priority queue. -*/ -#define RTREE_CACHE_SZ 5 - -/* -** An rtree cursor object. -*/ -struct RtreeCursor { - sqlite3_vtab_cursor base; /* Base class. Must be first */ - u8 atEOF; /* True if at end of search */ - u8 bPoint; /* True if sPoint is valid */ - u8 bAuxValid; /* True if pReadAux is valid */ - int iStrategy; /* Copy of idxNum search parameter */ - int nConstraint; /* Number of entries in aConstraint */ - RtreeConstraint *aConstraint; /* Search constraints. */ - int nPointAlloc; /* Number of slots allocated for aPoint[] */ - int nPoint; /* Number of slots used in aPoint[] */ - int mxLevel; /* iLevel value for root of the tree */ - RtreeSearchPoint *aPoint; /* Priority queue for search points */ - sqlite3_stmt *pReadAux; /* Statement to read aux-data */ - RtreeSearchPoint sPoint; /* Cached next search point */ - RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */ - u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */ -}; - -/* Return the Rtree of a RtreeCursor */ -#define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab)) - -/* -** A coordinate can be either a floating point number or a integer. All -** coordinates within a single R-Tree are always of the same time. -*/ -union RtreeCoord { - RtreeValue f; /* Floating point value */ - int i; /* Integer value */ - u32 u; /* Unsigned for byte-order conversions */ -}; - -/* -** The argument is an RtreeCoord. Return the value stored within the RtreeCoord -** formatted as a RtreeDValue (double or int64). This macro assumes that local -** variable pRtree points to the Rtree structure associated with the -** RtreeCoord. -*/ -#ifdef SQLITE_RTREE_INT_ONLY -# define DCOORD(coord) ((RtreeDValue)coord.i) -#else -# define DCOORD(coord) ( \ - (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ - ((double)coord.f) : \ - ((double)coord.i) \ - ) -#endif - -/* -** A search constraint. -*/ -struct RtreeConstraint { - int iCoord; /* Index of constrained coordinate */ - int op; /* Constraining operation */ - union { - RtreeDValue rValue; /* Constraint value. */ - int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*); - int (*xQueryFunc)(sqlite3_rtree_query_info*); - } u; - sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */ -}; - -/* Possible values for RtreeConstraint.op */ -#define RTREE_EQ 0x41 /* A */ -#define RTREE_LE 0x42 /* B */ -#define RTREE_LT 0x43 /* C */ -#define RTREE_GE 0x44 /* D */ -#define RTREE_GT 0x45 /* E */ -#define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */ -#define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */ - -/* Special operators available only on cursors. Needs to be consecutive -** with the normal values above, but must be less than RTREE_MATCH. These -** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or -** x<'xyz' (RTREE_TRUE) */ -#define RTREE_TRUE 0x3f /* ? */ -#define RTREE_FALSE 0x40 /* @ */ - -/* -** An rtree structure node. -*/ -struct RtreeNode { - RtreeNode *pParent; /* Parent node */ - i64 iNode; /* The node number */ - int nRef; /* Number of references to this node */ - int isDirty; /* True if the node needs to be written to disk */ - u8 *zData; /* Content of the node, as should be on disk */ - RtreeNode *pNext; /* Next node in this hash collision chain */ -}; - -/* Return the number of cells in a node */ -#define NCELL(pNode) readInt16(&(pNode)->zData[2]) - -/* -** A single cell from a node, deserialized -*/ -struct RtreeCell { - i64 iRowid; /* Node or entry ID */ - RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */ -}; - - -/* -** This object becomes the sqlite3_user_data() for the SQL functions -** that are created by sqlite3_rtree_geometry_callback() and -** sqlite3_rtree_query_callback() and which appear on the right of MATCH -** operators in order to constrain a search. -** -** xGeom and xQueryFunc are the callback functions. Exactly one of -** xGeom and xQueryFunc fields is non-NULL, depending on whether the -** SQL function was created using sqlite3_rtree_geometry_callback() or -** sqlite3_rtree_query_callback(). -** -** This object is deleted automatically by the destructor mechanism in -** sqlite3_create_function_v2(). -*/ -struct RtreeGeomCallback { - int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); - int (*xQueryFunc)(sqlite3_rtree_query_info*); - void (*xDestructor)(void*); - void *pContext; -}; - -/* -** An instance of this structure (in the form of a BLOB) is returned by -** the SQL functions that sqlite3_rtree_geometry_callback() and -** sqlite3_rtree_query_callback() create, and is read as the right-hand -** operand to the MATCH operator of an R-Tree. -*/ -struct RtreeMatchArg { - u32 iSize; /* Size of this object */ - RtreeGeomCallback cb; /* Info about the callback functions */ - int nParam; /* Number of parameters to the SQL function */ - sqlite3_value **apSqlParam; /* Original SQL parameter values */ - RtreeDValue aParam[1]; /* Values for parameters to the SQL function */ -}; - -#ifndef MAX -# define MAX(x,y) ((x) < (y) ? (y) : (x)) -#endif -#ifndef MIN -# define MIN(x,y) ((x) > (y) ? (y) : (x)) -#endif - -/* What version of GCC is being used. 0 means GCC is not being used . -** Note that the GCC_VERSION macro will also be set correctly when using -** clang, since clang works hard to be gcc compatible. So the gcc -** optimizations will also work when compiling with clang. -*/ -#ifndef GCC_VERSION -#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) -# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) -#else -# define GCC_VERSION 0 -#endif -#endif - -/* The testcase() macro should already be defined in the amalgamation. If -** it is not, make it a no-op. -*/ -#ifndef SQLITE_AMALGAMATION -# define testcase(X) -#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_ulong) -# pragma intrinsic(_byteswap_uint64) -# else -/* # include */ -# endif -# endif -#endif - -/* -** 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_RUNTIME_BYTEORDER=1 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(__arm__) -# define SQLITE_BYTEORDER 1234 -#elif defined(sparc) || defined(__ppc__) -# define SQLITE_BYTEORDER 4321 -#else -# define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */ -#endif -#endif - - -/* What version of MSVC is being used. 0 means MSVC is not being used */ -#ifndef MSVC_VERSION -#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) -# define MSVC_VERSION _MSC_VER -#else -# define MSVC_VERSION 0 -#endif -#endif - -/* -** Functions to deserialize a 16 bit integer, 32 bit real number and -** 64 bit integer. The deserialized value is returned. -*/ -static int readInt16(u8 *p){ - return (p[0]<<8) + p[1]; -} -static void readCoord(u8 *p, RtreeCoord *pCoord){ - assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ -#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 - pCoord->u = _byteswap_ulong(*(u32*)p); -#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 - pCoord->u = __builtin_bswap32(*(u32*)p); -#elif SQLITE_BYTEORDER==4321 - pCoord->u = *(u32*)p; -#else - pCoord->u = ( - (((u32)p[0]) << 24) + - (((u32)p[1]) << 16) + - (((u32)p[2]) << 8) + - (((u32)p[3]) << 0) - ); -#endif -} -static i64 readInt64(u8 *p){ -#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 - u64 x; - memcpy(&x, p, 8); - return (i64)_byteswap_uint64(x); -#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 - u64 x; - memcpy(&x, p, 8); - return (i64)__builtin_bswap64(x); -#elif SQLITE_BYTEORDER==4321 - i64 x; - memcpy(&x, p, 8); - return x; -#else - return (i64)( - (((u64)p[0]) << 56) + - (((u64)p[1]) << 48) + - (((u64)p[2]) << 40) + - (((u64)p[3]) << 32) + - (((u64)p[4]) << 24) + - (((u64)p[5]) << 16) + - (((u64)p[6]) << 8) + - (((u64)p[7]) << 0) - ); -#endif -} - -/* -** Functions to serialize a 16 bit integer, 32 bit real number and -** 64 bit integer. The value returned is the number of bytes written -** to the argument buffer (always 2, 4 and 8 respectively). -*/ -static void writeInt16(u8 *p, int i){ - p[0] = (i>> 8)&0xFF; - p[1] = (i>> 0)&0xFF; -} -static int writeCoord(u8 *p, RtreeCoord *pCoord){ - u32 i; - assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ - assert( sizeof(RtreeCoord)==4 ); - assert( sizeof(u32)==4 ); -#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 - i = __builtin_bswap32(pCoord->u); - memcpy(p, &i, 4); -#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 - i = _byteswap_ulong(pCoord->u); - memcpy(p, &i, 4); -#elif SQLITE_BYTEORDER==4321 - i = pCoord->u; - memcpy(p, &i, 4); -#else - i = pCoord->u; - p[0] = (i>>24)&0xFF; - p[1] = (i>>16)&0xFF; - p[2] = (i>> 8)&0xFF; - p[3] = (i>> 0)&0xFF; -#endif - return 4; -} -static int writeInt64(u8 *p, i64 i){ -#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 - i = (i64)__builtin_bswap64((u64)i); - memcpy(p, &i, 8); -#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 - i = (i64)_byteswap_uint64((u64)i); - memcpy(p, &i, 8); -#elif SQLITE_BYTEORDER==4321 - memcpy(p, &i, 8); -#else - p[0] = (i>>56)&0xFF; - p[1] = (i>>48)&0xFF; - p[2] = (i>>40)&0xFF; - p[3] = (i>>32)&0xFF; - p[4] = (i>>24)&0xFF; - p[5] = (i>>16)&0xFF; - p[6] = (i>> 8)&0xFF; - p[7] = (i>> 0)&0xFF; -#endif - return 8; -} - -/* -** Increment the reference count of node p. -*/ -static void nodeReference(RtreeNode *p){ - if( p ){ - assert( p->nRef>0 ); - p->nRef++; - } -} - -/* -** Clear the content of node p (set all bytes to 0x00). -*/ -static void nodeZero(Rtree *pRtree, RtreeNode *p){ - memset(&p->zData[2], 0, pRtree->iNodeSize-2); - p->isDirty = 1; -} - -/* -** Given a node number iNode, return the corresponding key to use -** in the Rtree.aHash table. -*/ -static unsigned int nodeHash(i64 iNode){ - return ((unsigned)iNode) % HASHSIZE; -} - -/* -** Search the node hash table for node iNode. If found, return a pointer -** to it. Otherwise, return 0. -*/ -static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ - RtreeNode *p; - for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); - return p; -} - -/* -** Add node pNode to the node hash table. -*/ -static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ - int iHash; - assert( pNode->pNext==0 ); - iHash = nodeHash(pNode->iNode); - pNode->pNext = pRtree->aHash[iHash]; - pRtree->aHash[iHash] = pNode; -} - -/* -** Remove node pNode from the node hash table. -*/ -static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ - RtreeNode **pp; - if( pNode->iNode!=0 ){ - pp = &pRtree->aHash[nodeHash(pNode->iNode)]; - for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } - *pp = pNode->pNext; - pNode->pNext = 0; - } -} - -/* -** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), -** indicating that node has not yet been assigned a node number. It is -** assigned a node number when nodeWrite() is called to write the -** node contents out to the database. -*/ -static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ - RtreeNode *pNode; - pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize); - if( pNode ){ - memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); - pNode->zData = (u8 *)&pNode[1]; - pNode->nRef = 1; - pRtree->nNodeRef++; - pNode->pParent = pParent; - pNode->isDirty = 1; - nodeReference(pParent); - } - return pNode; -} - -/* -** Clear the Rtree.pNodeBlob object -*/ -static void nodeBlobReset(Rtree *pRtree){ - if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){ - sqlite3_blob *pBlob = pRtree->pNodeBlob; - pRtree->pNodeBlob = 0; - sqlite3_blob_close(pBlob); - } -} - -/* -** Check to see if pNode is the same as pParent or any of the parents -** of pParent. -*/ -static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){ - do{ - if( pNode==pParent ) return 1; - pParent = pParent->pParent; - }while( pParent ); - return 0; -} - -/* -** Obtain a reference to an r-tree node. -*/ -static int nodeAcquire( - Rtree *pRtree, /* R-tree structure */ - i64 iNode, /* Node number to load */ - RtreeNode *pParent, /* Either the parent node or NULL */ - RtreeNode **ppNode /* OUT: Acquired node */ -){ - int rc = SQLITE_OK; - RtreeNode *pNode = 0; - - /* Check if the requested node is already in the hash table. If so, - ** increase its reference count and return it. - */ - if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){ - if( pParent && !pNode->pParent ){ - if( nodeInParentChain(pNode, pParent) ){ - RTREE_IS_CORRUPT(pRtree); - return SQLITE_CORRUPT_VTAB; - } - pParent->nRef++; - pNode->pParent = pParent; - }else if( pParent && pNode->pParent && pParent!=pNode->pParent ){ - RTREE_IS_CORRUPT(pRtree); - return SQLITE_CORRUPT_VTAB; - } - pNode->nRef++; - *ppNode = pNode; - return SQLITE_OK; - } - - if( pRtree->pNodeBlob ){ - sqlite3_blob *pBlob = pRtree->pNodeBlob; - pRtree->pNodeBlob = 0; - rc = sqlite3_blob_reopen(pBlob, iNode); - pRtree->pNodeBlob = pBlob; - if( rc ){ - nodeBlobReset(pRtree); - if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM; - } - } - if( pRtree->pNodeBlob==0 ){ - char *zTab = sqlite3_mprintf("%s_node", pRtree->zName); - if( zTab==0 ) return SQLITE_NOMEM; - rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0, - &pRtree->pNodeBlob); - sqlite3_free(zTab); - } - if( rc ){ - nodeBlobReset(pRtree); - *ppNode = 0; - /* If unable to open an sqlite3_blob on the desired row, that can only - ** be because the shadow tables hold erroneous data. */ - if( rc==SQLITE_ERROR ){ - rc = SQLITE_CORRUPT_VTAB; - RTREE_IS_CORRUPT(pRtree); - } - }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){ - pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize); - if( !pNode ){ - rc = SQLITE_NOMEM; - }else{ - pNode->pParent = pParent; - pNode->zData = (u8 *)&pNode[1]; - pNode->nRef = 1; - pRtree->nNodeRef++; - pNode->iNode = iNode; - pNode->isDirty = 0; - pNode->pNext = 0; - rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData, - pRtree->iNodeSize, 0); - } - } - - /* If the root node was just loaded, set pRtree->iDepth to the height - ** of the r-tree structure. A height of zero means all data is stored on - ** the root node. A height of one means the children of the root node - ** are the leaves, and so on. If the depth as specified on the root node - ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt. - */ - if( pNode && iNode==1 ){ - pRtree->iDepth = readInt16(pNode->zData); - if( pRtree->iDepth>RTREE_MAX_DEPTH ){ - rc = SQLITE_CORRUPT_VTAB; - RTREE_IS_CORRUPT(pRtree); - } - } - - /* If no error has occurred so far, check if the "number of entries" - ** field on the node is too large. If so, set the return code to - ** SQLITE_CORRUPT_VTAB. - */ - if( pNode && rc==SQLITE_OK ){ - if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){ - rc = SQLITE_CORRUPT_VTAB; - RTREE_IS_CORRUPT(pRtree); - } - } - - if( rc==SQLITE_OK ){ - if( pNode!=0 ){ - nodeReference(pParent); - nodeHashInsert(pRtree, pNode); - }else{ - rc = SQLITE_CORRUPT_VTAB; - RTREE_IS_CORRUPT(pRtree); - } - *ppNode = pNode; - }else{ - if( pNode ){ - pRtree->nNodeRef--; - sqlite3_free(pNode); - } - *ppNode = 0; - } - - return rc; -} - -/* -** Overwrite cell iCell of node pNode with the contents of pCell. -*/ -static void nodeOverwriteCell( - Rtree *pRtree, /* The overall R-Tree */ - RtreeNode *pNode, /* The node into which the cell is to be written */ - RtreeCell *pCell, /* The cell to write */ - int iCell /* Index into pNode into which pCell is written */ -){ - int ii; - u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; - p += writeInt64(p, pCell->iRowid); - for(ii=0; iinDim2; ii++){ - p += writeCoord(p, &pCell->aCoord[ii]); - } - pNode->isDirty = 1; -} - -/* -** Remove the cell with index iCell from node pNode. -*/ -static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ - u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; - u8 *pSrc = &pDst[pRtree->nBytesPerCell]; - int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; - memmove(pDst, pSrc, nByte); - writeInt16(&pNode->zData[2], NCELL(pNode)-1); - pNode->isDirty = 1; -} - -/* -** Insert the contents of cell pCell into node pNode. If the insert -** is successful, return SQLITE_OK. -** -** If there is not enough free space in pNode, return SQLITE_FULL. -*/ -static int nodeInsertCell( - Rtree *pRtree, /* The overall R-Tree */ - RtreeNode *pNode, /* Write new cell into this node */ - RtreeCell *pCell /* The cell to be inserted */ -){ - int nCell; /* Current number of cells in pNode */ - int nMaxCell; /* Maximum number of cells for pNode */ - - nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; - nCell = NCELL(pNode); - - assert( nCell<=nMaxCell ); - if( nCellzData[2], nCell+1); - pNode->isDirty = 1; - } - - return (nCell==nMaxCell); -} - -/* -** If the node is dirty, write it out to the database. -*/ -static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){ - int rc = SQLITE_OK; - if( pNode->isDirty ){ - sqlite3_stmt *p = pRtree->pWriteNode; - if( pNode->iNode ){ - sqlite3_bind_int64(p, 1, pNode->iNode); - }else{ - sqlite3_bind_null(p, 1); - } - sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); - sqlite3_step(p); - pNode->isDirty = 0; - rc = sqlite3_reset(p); - sqlite3_bind_null(p, 2); - if( pNode->iNode==0 && rc==SQLITE_OK ){ - pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); - nodeHashInsert(pRtree, pNode); - } - } - return rc; -} - -/* -** Release a reference to a node. If the node is dirty and the reference -** count drops to zero, the node data is written to the database. -*/ -static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){ - int rc = SQLITE_OK; - if( pNode ){ - assert( pNode->nRef>0 ); - assert( pRtree->nNodeRef>0 ); - pNode->nRef--; - if( pNode->nRef==0 ){ - pRtree->nNodeRef--; - if( pNode->iNode==1 ){ - pRtree->iDepth = -1; - } - if( pNode->pParent ){ - rc = nodeRelease(pRtree, pNode->pParent); - } - if( rc==SQLITE_OK ){ - rc = nodeWrite(pRtree, pNode); - } - nodeHashDelete(pRtree, pNode); - sqlite3_free(pNode); - } - } - return rc; -} - -/* -** Return the 64-bit integer value associated with cell iCell of -** node pNode. If pNode is a leaf node, this is a rowid. If it is -** an internal node, then the 64-bit integer is a child page number. -*/ -static i64 nodeGetRowid( - Rtree *pRtree, /* The overall R-Tree */ - RtreeNode *pNode, /* The node from which to extract the ID */ - int iCell /* The cell index from which to extract the ID */ -){ - assert( iCellzData[4 + pRtree->nBytesPerCell*iCell]); -} - -/* -** Return coordinate iCoord from cell iCell in node pNode. -*/ -static void nodeGetCoord( - Rtree *pRtree, /* The overall R-Tree */ - RtreeNode *pNode, /* The node from which to extract a coordinate */ - int iCell, /* The index of the cell within the node */ - int iCoord, /* Which coordinate to extract */ - RtreeCoord *pCoord /* OUT: Space to write result to */ -){ - readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); -} - -/* -** Deserialize cell iCell of node pNode. Populate the structure pointed -** to by pCell with the results. -*/ -static void nodeGetCell( - Rtree *pRtree, /* The overall R-Tree */ - RtreeNode *pNode, /* The node containing the cell to be read */ - int iCell, /* Index of the cell within the node */ - RtreeCell *pCell /* OUT: Write the cell contents here */ -){ - u8 *pData; - RtreeCoord *pCoord; - int ii = 0; - pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); - pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell); - pCoord = pCell->aCoord; - do{ - readCoord(pData, &pCoord[ii]); - readCoord(pData+4, &pCoord[ii+1]); - pData += 8; - ii += 2; - }while( iinDim2 ); -} - - -/* Forward declaration for the function that does the work of -** the virtual table module xCreate() and xConnect() methods. -*/ -static int rtreeInit( - sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int -); - -/* -** Rtree virtual table module xCreate method. -*/ -static int rtreeCreate( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); -} - -/* -** Rtree virtual table module xConnect method. -*/ -static int rtreeConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); -} - -/* -** Increment the r-tree reference count. -*/ -static void rtreeReference(Rtree *pRtree){ - pRtree->nBusy++; -} - -/* -** Decrement the r-tree reference count. When the reference count reaches -** zero the structure is deleted. -*/ -static void rtreeRelease(Rtree *pRtree){ - pRtree->nBusy--; - if( pRtree->nBusy==0 ){ - pRtree->inWrTrans = 0; - assert( pRtree->nCursor==0 ); - nodeBlobReset(pRtree); - assert( pRtree->nNodeRef==0 || pRtree->bCorrupt ); - sqlite3_finalize(pRtree->pWriteNode); - sqlite3_finalize(pRtree->pDeleteNode); - sqlite3_finalize(pRtree->pReadRowid); - sqlite3_finalize(pRtree->pWriteRowid); - sqlite3_finalize(pRtree->pDeleteRowid); - sqlite3_finalize(pRtree->pReadParent); - sqlite3_finalize(pRtree->pWriteParent); - sqlite3_finalize(pRtree->pDeleteParent); - sqlite3_finalize(pRtree->pWriteAux); - sqlite3_free(pRtree->zReadAuxSql); - sqlite3_free(pRtree); - } -} - -/* -** Rtree virtual table module xDisconnect method. -*/ -static int rtreeDisconnect(sqlite3_vtab *pVtab){ - rtreeRelease((Rtree *)pVtab); - return SQLITE_OK; -} - -/* -** Rtree virtual table module xDestroy method. -*/ -static int rtreeDestroy(sqlite3_vtab *pVtab){ - Rtree *pRtree = (Rtree *)pVtab; - int rc; - char *zCreate = sqlite3_mprintf( - "DROP TABLE '%q'.'%q_node';" - "DROP TABLE '%q'.'%q_rowid';" - "DROP TABLE '%q'.'%q_parent';", - pRtree->zDb, pRtree->zName, - pRtree->zDb, pRtree->zName, - pRtree->zDb, pRtree->zName - ); - if( !zCreate ){ - rc = SQLITE_NOMEM; - }else{ - nodeBlobReset(pRtree); - rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); - sqlite3_free(zCreate); - } - if( rc==SQLITE_OK ){ - rtreeRelease(pRtree); - } - - return rc; -} - -/* -** Rtree virtual table module xOpen method. -*/ -static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ - int rc = SQLITE_NOMEM; - Rtree *pRtree = (Rtree *)pVTab; - RtreeCursor *pCsr; - - pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor)); - if( pCsr ){ - memset(pCsr, 0, sizeof(RtreeCursor)); - pCsr->base.pVtab = pVTab; - rc = SQLITE_OK; - pRtree->nCursor++; - } - *ppCursor = (sqlite3_vtab_cursor *)pCsr; - - return rc; -} - - -/* -** Reset a cursor back to its initial state. -*/ -static void resetCursor(RtreeCursor *pCsr){ - Rtree *pRtree = (Rtree *)(pCsr->base.pVtab); - int ii; - sqlite3_stmt *pStmt; - if( pCsr->aConstraint ){ - int i; /* Used to iterate through constraint array */ - for(i=0; inConstraint; i++){ - sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo; - if( pInfo ){ - if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser); - sqlite3_free(pInfo); - } - } - sqlite3_free(pCsr->aConstraint); - pCsr->aConstraint = 0; - } - for(ii=0; iiaNode[ii]); - sqlite3_free(pCsr->aPoint); - pStmt = pCsr->pReadAux; - memset(pCsr, 0, sizeof(RtreeCursor)); - pCsr->base.pVtab = (sqlite3_vtab*)pRtree; - pCsr->pReadAux = pStmt; - -} - -/* -** Rtree virtual table module xClose method. -*/ -static int rtreeClose(sqlite3_vtab_cursor *cur){ - Rtree *pRtree = (Rtree *)(cur->pVtab); - RtreeCursor *pCsr = (RtreeCursor *)cur; - assert( pRtree->nCursor>0 ); - resetCursor(pCsr); - sqlite3_finalize(pCsr->pReadAux); - sqlite3_free(pCsr); - pRtree->nCursor--; - nodeBlobReset(pRtree); - return SQLITE_OK; -} - -/* -** Rtree virtual table module xEof method. -** -** Return non-zero if the cursor does not currently point to a valid -** record (i.e if the scan has finished), or zero otherwise. -*/ -static int rtreeEof(sqlite3_vtab_cursor *cur){ - RtreeCursor *pCsr = (RtreeCursor *)cur; - return pCsr->atEOF; -} - -/* -** Convert raw bits from the on-disk RTree record into a coordinate value. -** The on-disk format is big-endian and needs to be converted for little- -** endian platforms. The on-disk record stores integer coordinates if -** eInt is true and it stores 32-bit floating point records if eInt is -** false. a[] is the four bytes of the on-disk record to be decoded. -** Store the results in "r". -** -** There are five versions of this macro. The last one is generic. The -** other four are various architectures-specific optimizations. -*/ -#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 -#define RTREE_DECODE_COORD(eInt, a, r) { \ - RtreeCoord c; /* Coordinate decoded */ \ - c.u = _byteswap_ulong(*(u32*)a); \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ -} -#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 -#define RTREE_DECODE_COORD(eInt, a, r) { \ - RtreeCoord c; /* Coordinate decoded */ \ - c.u = __builtin_bswap32(*(u32*)a); \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ -} -#elif SQLITE_BYTEORDER==1234 -#define RTREE_DECODE_COORD(eInt, a, r) { \ - RtreeCoord c; /* Coordinate decoded */ \ - memcpy(&c.u,a,4); \ - c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \ - ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ -} -#elif SQLITE_BYTEORDER==4321 -#define RTREE_DECODE_COORD(eInt, a, r) { \ - RtreeCoord c; /* Coordinate decoded */ \ - memcpy(&c.u,a,4); \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ -} -#else -#define RTREE_DECODE_COORD(eInt, a, r) { \ - RtreeCoord c; /* Coordinate decoded */ \ - c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \ - +((u32)a[2]<<8) + a[3]; \ - r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ -} -#endif - -/* -** Check the RTree node or entry given by pCellData and p against the MATCH -** constraint pConstraint. -*/ -static int rtreeCallbackConstraint( - RtreeConstraint *pConstraint, /* The constraint to test */ - int eInt, /* True if RTree holding integer coordinates */ - u8 *pCellData, /* Raw cell content */ - RtreeSearchPoint *pSearch, /* Container of this cell */ - sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */ - int *peWithin /* OUT: visibility of the cell */ -){ - sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */ - int nCoord = pInfo->nCoord; /* No. of coordinates */ - int rc; /* Callback return code */ - RtreeCoord c; /* Translator union */ - sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */ - - assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY ); - assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 ); - - if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){ - pInfo->iRowid = readInt64(pCellData); - } - pCellData += 8; -#ifndef SQLITE_RTREE_INT_ONLY - if( eInt==0 ){ - switch( nCoord ){ - case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f; - readCoord(pCellData+32, &c); aCoord[8] = c.f; - case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f; - readCoord(pCellData+24, &c); aCoord[6] = c.f; - case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f; - readCoord(pCellData+16, &c); aCoord[4] = c.f; - case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f; - readCoord(pCellData+8, &c); aCoord[2] = c.f; - default: readCoord(pCellData+4, &c); aCoord[1] = c.f; - readCoord(pCellData, &c); aCoord[0] = c.f; - } - }else -#endif - { - switch( nCoord ){ - case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i; - readCoord(pCellData+32, &c); aCoord[8] = c.i; - case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i; - readCoord(pCellData+24, &c); aCoord[6] = c.i; - case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i; - readCoord(pCellData+16, &c); aCoord[4] = c.i; - case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i; - readCoord(pCellData+8, &c); aCoord[2] = c.i; - default: readCoord(pCellData+4, &c); aCoord[1] = c.i; - readCoord(pCellData, &c); aCoord[0] = c.i; - } - } - if( pConstraint->op==RTREE_MATCH ){ - int eWithin = 0; - rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo, - nCoord, aCoord, &eWithin); - if( eWithin==0 ) *peWithin = NOT_WITHIN; - *prScore = RTREE_ZERO; - }else{ - pInfo->aCoord = aCoord; - pInfo->iLevel = pSearch->iLevel - 1; - pInfo->rScore = pInfo->rParentScore = pSearch->rScore; - pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin; - rc = pConstraint->u.xQueryFunc(pInfo); - if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin; - if( pInfo->rScore<*prScore || *prScorerScore; - } - } - return rc; -} - -/* -** Check the internal RTree node given by pCellData against constraint p. -** If this constraint cannot be satisfied by any child within the node, -** set *peWithin to NOT_WITHIN. -*/ -static void rtreeNonleafConstraint( - RtreeConstraint *p, /* The constraint to test */ - int eInt, /* True if RTree holds integer coordinates */ - u8 *pCellData, /* Raw cell content as appears on disk */ - int *peWithin /* Adjust downward, as appropriate */ -){ - sqlite3_rtree_dbl val; /* Coordinate value convert to a double */ - - /* p->iCoord might point to either a lower or upper bound coordinate - ** in a coordinate pair. But make pCellData point to the lower bound. - */ - pCellData += 8 + 4*(p->iCoord&0xfe); - - assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE - || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE - || p->op==RTREE_FALSE ); - assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ - switch( p->op ){ - case RTREE_TRUE: return; /* Always satisfied */ - case RTREE_FALSE: break; /* Never satisfied */ - case RTREE_LE: - case RTREE_LT: - case RTREE_EQ: - RTREE_DECODE_COORD(eInt, pCellData, val); - /* val now holds the lower bound of the coordinate pair */ - if( p->u.rValue>=val ) return; - if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */ - /* Fall through for the RTREE_EQ case */ - - default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */ - pCellData += 4; - RTREE_DECODE_COORD(eInt, pCellData, val); - /* val now holds the upper bound of the coordinate pair */ - if( p->u.rValue<=val ) return; - } - *peWithin = NOT_WITHIN; -} - -/* -** Check the leaf RTree cell given by pCellData against constraint p. -** If this constraint is not satisfied, set *peWithin to NOT_WITHIN. -** If the constraint is satisfied, leave *peWithin unchanged. -** -** The constraint is of the form: xN op $val -** -** The op is given by p->op. The xN is p->iCoord-th coordinate in -** pCellData. $val is given by p->u.rValue. -*/ -static void rtreeLeafConstraint( - RtreeConstraint *p, /* The constraint to test */ - int eInt, /* True if RTree holds integer coordinates */ - u8 *pCellData, /* Raw cell content as appears on disk */ - int *peWithin /* Adjust downward, as appropriate */ -){ - RtreeDValue xN; /* Coordinate value converted to a double */ - - assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE - || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE - || p->op==RTREE_FALSE ); - pCellData += 8 + p->iCoord*4; - assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ - RTREE_DECODE_COORD(eInt, pCellData, xN); - switch( p->op ){ - case RTREE_TRUE: return; /* Always satisfied */ - case RTREE_FALSE: break; /* Never satisfied */ - case RTREE_LE: if( xN <= p->u.rValue ) return; break; - case RTREE_LT: if( xN < p->u.rValue ) return; break; - case RTREE_GE: if( xN >= p->u.rValue ) return; break; - case RTREE_GT: if( xN > p->u.rValue ) return; break; - default: if( xN == p->u.rValue ) return; break; - } - *peWithin = NOT_WITHIN; -} - -/* -** One of the cells in node pNode is guaranteed to have a 64-bit -** integer value equal to iRowid. Return the index of this cell. -*/ -static int nodeRowidIndex( - Rtree *pRtree, - RtreeNode *pNode, - i64 iRowid, - int *piIndex -){ - int ii; - int nCell = NCELL(pNode); - assert( nCell<200 ); - for(ii=0; iipParent; - if( pParent ){ - return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex); - } - *piIndex = -1; - return SQLITE_OK; -} - -/* -** Compare two search points. Return negative, zero, or positive if the first -** is less than, equal to, or greater than the second. -** -** The rScore is the primary key. Smaller rScore values come first. -** If the rScore is a tie, then use iLevel as the tie breaker with smaller -** iLevel values coming first. In this way, if rScore is the same for all -** SearchPoints, then iLevel becomes the deciding factor and the result -** is a depth-first search, which is the desired default behavior. -*/ -static int rtreeSearchPointCompare( - const RtreeSearchPoint *pA, - const RtreeSearchPoint *pB -){ - if( pA->rScorerScore ) return -1; - if( pA->rScore>pB->rScore ) return +1; - if( pA->iLeveliLevel ) return -1; - if( pA->iLevel>pB->iLevel ) return +1; - return 0; -} - -/* -** Interchange two search points in a cursor. -*/ -static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){ - RtreeSearchPoint t = p->aPoint[i]; - assert( iaPoint[i] = p->aPoint[j]; - p->aPoint[j] = t; - i++; j++; - if( i=RTREE_CACHE_SZ ){ - nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); - p->aNode[i] = 0; - }else{ - RtreeNode *pTemp = p->aNode[i]; - p->aNode[i] = p->aNode[j]; - p->aNode[j] = pTemp; - } - } -} - -/* -** Return the search point with the lowest current score. -*/ -static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){ - return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0; -} - -/* -** Get the RtreeNode for the search point with the lowest score. -*/ -static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){ - sqlite3_int64 id; - int ii = 1 - pCur->bPoint; - assert( ii==0 || ii==1 ); - assert( pCur->bPoint || pCur->nPoint ); - if( pCur->aNode[ii]==0 ){ - assert( pRC!=0 ); - id = ii ? pCur->aPoint[0].id : pCur->sPoint.id; - *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]); - } - return pCur->aNode[ii]; -} - -/* -** Push a new element onto the priority queue -*/ -static RtreeSearchPoint *rtreeEnqueue( - RtreeCursor *pCur, /* The cursor */ - RtreeDValue rScore, /* Score for the new search point */ - u8 iLevel /* Level for the new search point */ -){ - int i, j; - RtreeSearchPoint *pNew; - if( pCur->nPoint>=pCur->nPointAlloc ){ - int nNew = pCur->nPointAlloc*2 + 8; - pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0])); - if( pNew==0 ) return 0; - pCur->aPoint = pNew; - pCur->nPointAlloc = nNew; - } - i = pCur->nPoint++; - pNew = pCur->aPoint + i; - pNew->rScore = rScore; - pNew->iLevel = iLevel; - assert( iLevel<=RTREE_MAX_DEPTH ); - while( i>0 ){ - RtreeSearchPoint *pParent; - j = (i-1)/2; - pParent = pCur->aPoint + j; - if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break; - rtreeSearchPointSwap(pCur, j, i); - i = j; - pNew = pParent; - } - return pNew; -} - -/* -** Allocate a new RtreeSearchPoint and return a pointer to it. Return -** NULL if malloc fails. -*/ -static RtreeSearchPoint *rtreeSearchPointNew( - RtreeCursor *pCur, /* The cursor */ - RtreeDValue rScore, /* Score for the new search point */ - u8 iLevel /* Level for the new search point */ -){ - RtreeSearchPoint *pNew, *pFirst; - pFirst = rtreeSearchPointFirst(pCur); - pCur->anQueue[iLevel]++; - if( pFirst==0 - || pFirst->rScore>rScore - || (pFirst->rScore==rScore && pFirst->iLevel>iLevel) - ){ - if( pCur->bPoint ){ - int ii; - pNew = rtreeEnqueue(pCur, rScore, iLevel); - if( pNew==0 ) return 0; - ii = (int)(pNew - pCur->aPoint) + 1; - if( iiaNode[ii]==0 ); - pCur->aNode[ii] = pCur->aNode[0]; - }else{ - nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]); - } - pCur->aNode[0] = 0; - *pNew = pCur->sPoint; - } - pCur->sPoint.rScore = rScore; - pCur->sPoint.iLevel = iLevel; - pCur->bPoint = 1; - return &pCur->sPoint; - }else{ - return rtreeEnqueue(pCur, rScore, iLevel); - } -} - -#if 0 -/* Tracing routines for the RtreeSearchPoint queue */ -static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){ - if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); } - printf(" %d.%05lld.%02d %g %d", - p->iLevel, p->id, p->iCell, p->rScore, p->eWithin - ); - idx++; - if( idxaNode[idx]); - }else{ - printf("\n"); - } -} -static void traceQueue(RtreeCursor *pCur, const char *zPrefix){ - int ii; - printf("=== %9s ", zPrefix); - if( pCur->bPoint ){ - tracePoint(&pCur->sPoint, -1, pCur); - } - for(ii=0; iinPoint; ii++){ - if( ii>0 || pCur->bPoint ) printf(" "); - tracePoint(&pCur->aPoint[ii], ii, pCur); - } -} -# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B) -#else -# define RTREE_QUEUE_TRACE(A,B) /* no-op */ -#endif - -/* Remove the search point with the lowest current score. -*/ -static void rtreeSearchPointPop(RtreeCursor *p){ - int i, j, k, n; - i = 1 - p->bPoint; - assert( i==0 || i==1 ); - if( p->aNode[i] ){ - nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); - p->aNode[i] = 0; - } - if( p->bPoint ){ - p->anQueue[p->sPoint.iLevel]--; - p->bPoint = 0; - }else if( p->nPoint ){ - p->anQueue[p->aPoint[0].iLevel]--; - n = --p->nPoint; - p->aPoint[0] = p->aPoint[n]; - if( naNode[1] = p->aNode[n+1]; - p->aNode[n+1] = 0; - } - i = 0; - while( (j = i*2+1)aPoint[k], &p->aPoint[j])<0 ){ - if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){ - rtreeSearchPointSwap(p, i, k); - i = k; - }else{ - break; - } - }else{ - if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){ - rtreeSearchPointSwap(p, i, j); - i = j; - }else{ - break; - } - } - } - } -} - - -/* -** Continue the search on cursor pCur until the front of the queue -** contains an entry suitable for returning as a result-set row, -** or until the RtreeSearchPoint queue is empty, indicating that the -** query has completed. -*/ -static int rtreeStepToLeaf(RtreeCursor *pCur){ - RtreeSearchPoint *p; - Rtree *pRtree = RTREE_OF_CURSOR(pCur); - RtreeNode *pNode; - int eWithin; - int rc = SQLITE_OK; - int nCell; - int nConstraint = pCur->nConstraint; - int ii; - int eInt; - RtreeSearchPoint x; - - eInt = pRtree->eCoordType==RTREE_COORD_INT32; - while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){ - u8 *pCellData; - pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc); - if( rc ) return rc; - nCell = NCELL(pNode); - assert( nCell<200 ); - pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell); - while( p->iCellaConstraint + ii; - if( pConstraint->op>=RTREE_MATCH ){ - rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p, - &rScore, &eWithin); - if( rc ) return rc; - }else if( p->iLevel==1 ){ - rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin); - }else{ - rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin); - } - if( eWithin==NOT_WITHIN ){ - p->iCell++; - pCellData += pRtree->nBytesPerCell; - break; - } - } - if( eWithin==NOT_WITHIN ) continue; - p->iCell++; - x.iLevel = p->iLevel - 1; - if( x.iLevel ){ - x.id = readInt64(pCellData); - for(ii=0; iinPoint; ii++){ - if( pCur->aPoint[ii].id==x.id ){ - RTREE_IS_CORRUPT(pRtree); - return SQLITE_CORRUPT_VTAB; - } - } - x.iCell = 0; - }else{ - x.id = p->id; - x.iCell = p->iCell - 1; - } - if( p->iCell>=nCell ){ - RTREE_QUEUE_TRACE(pCur, "POP-S:"); - rtreeSearchPointPop(pCur); - } - if( rScoreeWithin = (u8)eWithin; - p->id = x.id; - p->iCell = x.iCell; - RTREE_QUEUE_TRACE(pCur, "PUSH-S:"); - break; - } - if( p->iCell>=nCell ){ - RTREE_QUEUE_TRACE(pCur, "POP-Se:"); - rtreeSearchPointPop(pCur); - } - } - pCur->atEOF = p==0; - return SQLITE_OK; -} - -/* -** Rtree virtual table module xNext method. -*/ -static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ - RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; - int rc = SQLITE_OK; - - /* Move to the next entry that matches the configured constraints. */ - RTREE_QUEUE_TRACE(pCsr, "POP-Nx:"); - if( pCsr->bAuxValid ){ - pCsr->bAuxValid = 0; - sqlite3_reset(pCsr->pReadAux); - } - rtreeSearchPointPop(pCsr); - rc = rtreeStepToLeaf(pCsr); - return rc; -} - -/* -** Rtree virtual table module xRowid method. -*/ -static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ - RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; - RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); - int rc = SQLITE_OK; - RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); - if( rc==SQLITE_OK && p ){ - *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell); - } - return rc; -} - -/* -** Rtree virtual table module xColumn method. -*/ -static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ - Rtree *pRtree = (Rtree *)cur->pVtab; - RtreeCursor *pCsr = (RtreeCursor *)cur; - RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); - RtreeCoord c; - int rc = SQLITE_OK; - RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); - - if( rc ) return rc; - if( p==0 ) return SQLITE_OK; - if( i==0 ){ - sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell)); - }else if( i<=pRtree->nDim2 ){ - nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c); -#ifndef SQLITE_RTREE_INT_ONLY - if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - sqlite3_result_double(ctx, c.f); - }else -#endif - { - assert( pRtree->eCoordType==RTREE_COORD_INT32 ); - sqlite3_result_int(ctx, c.i); - } - }else{ - if( !pCsr->bAuxValid ){ - if( pCsr->pReadAux==0 ){ - rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0, - &pCsr->pReadAux, 0); - if( rc ) return rc; - } - sqlite3_bind_int64(pCsr->pReadAux, 1, - nodeGetRowid(pRtree, pNode, p->iCell)); - rc = sqlite3_step(pCsr->pReadAux); - if( rc==SQLITE_ROW ){ - pCsr->bAuxValid = 1; - }else{ - sqlite3_reset(pCsr->pReadAux); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - return rc; - } - } - sqlite3_result_value(ctx, - sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1)); - } - return SQLITE_OK; -} - -/* -** Use nodeAcquire() to obtain the leaf node containing the record with -** rowid iRowid. If successful, set *ppLeaf to point to the node and -** return SQLITE_OK. If there is no such record in the table, set -** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf -** to zero and return an SQLite error code. -*/ -static int findLeafNode( - Rtree *pRtree, /* RTree to search */ - i64 iRowid, /* The rowid searching for */ - RtreeNode **ppLeaf, /* Write the node here */ - sqlite3_int64 *piNode /* Write the node-id here */ -){ - int rc; - *ppLeaf = 0; - sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); - if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ - i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); - if( piNode ) *piNode = iNode; - rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); - sqlite3_reset(pRtree->pReadRowid); - }else{ - rc = sqlite3_reset(pRtree->pReadRowid); - } - return rc; -} - -/* -** This function is called to configure the RtreeConstraint object passed -** as the second argument for a MATCH constraint. The value passed as the -** first argument to this function is the right-hand operand to the MATCH -** operator. -*/ -static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ - RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */ - sqlite3_rtree_query_info *pInfo; /* Callback information */ - - pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg"); - if( pSrc==0 ) return SQLITE_ERROR; - pInfo = (sqlite3_rtree_query_info*) - sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize ); - if( !pInfo ) return SQLITE_NOMEM; - memset(pInfo, 0, sizeof(*pInfo)); - pBlob = (RtreeMatchArg*)&pInfo[1]; - memcpy(pBlob, pSrc, pSrc->iSize); - pInfo->pContext = pBlob->cb.pContext; - pInfo->nParam = pBlob->nParam; - pInfo->aParam = pBlob->aParam; - pInfo->apSqlParam = pBlob->apSqlParam; - - if( pBlob->cb.xGeom ){ - pCons->u.xGeom = pBlob->cb.xGeom; - }else{ - pCons->op = RTREE_QUERY; - pCons->u.xQueryFunc = pBlob->cb.xQueryFunc; - } - pCons->pInfo = pInfo; - return SQLITE_OK; -} - -/* -** Rtree virtual table module xFilter method. -*/ -static int rtreeFilter( - sqlite3_vtab_cursor *pVtabCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; - RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; - RtreeNode *pRoot = 0; - int ii; - int rc = SQLITE_OK; - int iCell = 0; - - rtreeReference(pRtree); - - /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ - resetCursor(pCsr); - - pCsr->iStrategy = idxNum; - if( idxNum==1 ){ - /* Special case - lookup by rowid. */ - RtreeNode *pLeaf; /* Leaf on which the required cell resides */ - RtreeSearchPoint *p; /* Search point for the leaf */ - i64 iRowid = sqlite3_value_int64(argv[0]); - i64 iNode = 0; - int eType = sqlite3_value_numeric_type(argv[0]); - if( eType==SQLITE_INTEGER - || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid) - ){ - rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); - }else{ - rc = SQLITE_OK; - pLeaf = 0; - } - if( rc==SQLITE_OK && pLeaf!=0 ){ - p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); - assert( p!=0 ); /* Always returns pCsr->sPoint */ - pCsr->aNode[0] = pLeaf; - p->id = iNode; - p->eWithin = PARTLY_WITHIN; - rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); - p->iCell = (u8)iCell; - RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); - }else{ - pCsr->atEOF = 1; - } - }else{ - /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array - ** with the configured constraints. - */ - rc = nodeAcquire(pRtree, 1, 0, &pRoot); - if( rc==SQLITE_OK && argc>0 ){ - pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc); - pCsr->nConstraint = argc; - if( !pCsr->aConstraint ){ - rc = SQLITE_NOMEM; - }else{ - memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc); - memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1)); - assert( (idxStr==0 && argc==0) - || (idxStr && (int)strlen(idxStr)==argc*2) ); - for(ii=0; iiaConstraint[ii]; - int eType = sqlite3_value_numeric_type(argv[ii]); - p->op = idxStr[ii*2]; - p->iCoord = idxStr[ii*2+1]-'0'; - if( p->op>=RTREE_MATCH ){ - /* A MATCH operator. The right-hand-side must be a blob that - ** can be cast into an RtreeMatchArg object. One created using - ** an sqlite3_rtree_geometry_callback() SQL user function. - */ - rc = deserializeGeometry(argv[ii], p); - if( rc!=SQLITE_OK ){ - break; - } - p->pInfo->nCoord = pRtree->nDim2; - p->pInfo->anQueue = pCsr->anQueue; - p->pInfo->mxLevel = pRtree->iDepth + 1; - }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ -#ifdef SQLITE_RTREE_INT_ONLY - p->u.rValue = sqlite3_value_int64(argv[ii]); -#else - p->u.rValue = sqlite3_value_double(argv[ii]); -#endif - }else{ - p->u.rValue = RTREE_ZERO; - if( eType==SQLITE_NULL ){ - p->op = RTREE_FALSE; - }else if( p->op==RTREE_LT || p->op==RTREE_LE ){ - p->op = RTREE_TRUE; - }else{ - p->op = RTREE_FALSE; - } - } - } - } - } - if( rc==SQLITE_OK ){ - RtreeSearchPoint *pNew; - pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1)); - if( pNew==0 ) return SQLITE_NOMEM; - pNew->id = 1; - pNew->iCell = 0; - pNew->eWithin = PARTLY_WITHIN; - assert( pCsr->bPoint==1 ); - pCsr->aNode[0] = pRoot; - pRoot = 0; - RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:"); - rc = rtreeStepToLeaf(pCsr); - } - } - - nodeRelease(pRtree, pRoot); - rtreeRelease(pRtree); - return rc; -} - -/* -** Rtree virtual table module xBestIndex method. There are three -** table scan strategies to choose from (in order from most to -** least desirable): -** -** idxNum idxStr Strategy -** ------------------------------------------------ -** 1 Unused Direct lookup by rowid. -** 2 See below R-tree query or full-table scan. -** ------------------------------------------------ -** -** If strategy 1 is used, then idxStr is not meaningful. If strategy -** 2 is used, idxStr is formatted to contain 2 bytes for each -** constraint used. The first two bytes of idxStr correspond to -** the constraint in sqlite3_index_info.aConstraintUsage[] with -** (argvIndex==1) etc. -** -** The first of each pair of bytes in idxStr identifies the constraint -** operator as follows: -** -** Operator Byte Value -** ---------------------- -** = 0x41 ('A') -** <= 0x42 ('B') -** < 0x43 ('C') -** >= 0x44 ('D') -** > 0x45 ('E') -** MATCH 0x46 ('F') -** ---------------------- -** -** The second of each pair of bytes identifies the coordinate column -** to which the constraint applies. The leftmost coordinate column -** is 'a', the second from the left 'b' etc. -*/ -static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ - Rtree *pRtree = (Rtree*)tab; - int rc = SQLITE_OK; - int ii; - int bMatch = 0; /* True if there exists a MATCH constraint */ - i64 nRow; /* Estimated rows returned by this scan */ - - int iIdx = 0; - char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; - memset(zIdxStr, 0, sizeof(zIdxStr)); - - /* Check if there exists a MATCH constraint - even an unusable one. If there - ** is, do not consider the lookup-by-rowid plan as using such a plan would - ** require the VDBE to evaluate the MATCH constraint, which is not currently - ** possible. */ - for(ii=0; iinConstraint; ii++){ - if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){ - bMatch = 1; - } - } - - assert( pIdxInfo->idxStr==0 ); - for(ii=0; iinConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ - struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; - - if( bMatch==0 && p->usable - && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ - ){ - /* We have an equality constraint on the rowid. Use strategy 1. */ - int jj; - for(jj=0; jjaConstraintUsage[jj].argvIndex = 0; - pIdxInfo->aConstraintUsage[jj].omit = 0; - } - pIdxInfo->idxNum = 1; - pIdxInfo->aConstraintUsage[ii].argvIndex = 1; - pIdxInfo->aConstraintUsage[jj].omit = 1; - - /* This strategy involves a two rowid lookups on an B-Tree structures - ** and then a linear search of an R-Tree node. This should be - ** considered almost as quick as a direct rowid lookup (for which - ** sqlite uses an internal cost of 0.0). It is expected to return - ** a single row. - */ - pIdxInfo->estimatedCost = 30.0; - pIdxInfo->estimatedRows = 1; - pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE; - return SQLITE_OK; - } - - if( p->usable - && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2) - || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) - ){ - u8 op; - switch( p->op ){ - case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; - case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; - case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; - case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; - case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; - case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break; - default: op = 0; break; - } - if( op ){ - zIdxStr[iIdx++] = op; - zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0'); - pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); - pIdxInfo->aConstraintUsage[ii].omit = 1; - } - } - } - - pIdxInfo->idxNum = 2; - pIdxInfo->needToFreeIdxStr = 1; - if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ - return SQLITE_NOMEM; - } - - nRow = pRtree->nRowEst >> (iIdx/2); - pIdxInfo->estimatedCost = (double)6.0 * (double)nRow; - pIdxInfo->estimatedRows = nRow; - - return rc; -} - -/* -** Return the N-dimensional volumn of the cell stored in *p. -*/ -static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ - RtreeDValue area = (RtreeDValue)1; - assert( pRtree->nDim>=1 && pRtree->nDim<=5 ); -#ifndef SQLITE_RTREE_INT_ONLY - if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - switch( pRtree->nDim ){ - case 5: area = p->aCoord[9].f - p->aCoord[8].f; - case 4: area *= p->aCoord[7].f - p->aCoord[6].f; - case 3: area *= p->aCoord[5].f - p->aCoord[4].f; - case 2: area *= p->aCoord[3].f - p->aCoord[2].f; - default: area *= p->aCoord[1].f - p->aCoord[0].f; - } - }else -#endif - { - switch( pRtree->nDim ){ - case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i; - case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i; - case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i; - case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i; - default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i; - } - } - return area; -} - -/* -** Return the margin length of cell p. The margin length is the sum -** of the objects size in each dimension. -*/ -static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ - RtreeDValue margin = 0; - int ii = pRtree->nDim2 - 2; - do{ - margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); - ii -= 2; - }while( ii>=0 ); - return margin; -} - -/* -** Store the union of cells p1 and p2 in p1. -*/ -static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ - int ii = 0; - if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - do{ - p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); - p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); - ii += 2; - }while( iinDim2 ); - }else{ - do{ - p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); - p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); - ii += 2; - }while( iinDim2 ); - } -} - -/* -** Return true if the area covered by p2 is a subset of the area covered -** by p1. False otherwise. -*/ -static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ - int ii; - int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); - for(ii=0; iinDim2; ii+=2){ - RtreeCoord *a1 = &p1->aCoord[ii]; - RtreeCoord *a2 = &p2->aCoord[ii]; - if( (!isInt && (a2[0].fa1[1].f)) - || ( isInt && (a2[0].ia1[1].i)) - ){ - return 0; - } - } - return 1; -} - -/* -** Return the amount cell p would grow by if it were unioned with pCell. -*/ -static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ - RtreeDValue area; - RtreeCell cell; - memcpy(&cell, p, sizeof(RtreeCell)); - area = cellArea(pRtree, &cell); - cellUnion(pRtree, &cell, pCell); - return (cellArea(pRtree, &cell)-area); -} - -static RtreeDValue cellOverlap( - Rtree *pRtree, - RtreeCell *p, - RtreeCell *aCell, - int nCell -){ - int ii; - RtreeDValue overlap = RTREE_ZERO; - for(ii=0; iinDim2; jj+=2){ - RtreeDValue x1, x2; - x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); - x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); - if( x2iDepth-iHeight); ii++){ - int iCell; - sqlite3_int64 iBest = 0; - - RtreeDValue fMinGrowth = RTREE_ZERO; - RtreeDValue fMinArea = RTREE_ZERO; - - int nCell = NCELL(pNode); - RtreeCell cell; - RtreeNode *pChild; - - RtreeCell *aCell = 0; - - /* Select the child node which will be enlarged the least if pCell - ** is inserted into it. Resolve ties by choosing the entry with - ** the smallest area. - */ - for(iCell=0; iCellpParent ){ - RtreeNode *pParent = p->pParent; - RtreeCell cell; - int iCell; - - if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell) ){ - RTREE_IS_CORRUPT(pRtree); - return SQLITE_CORRUPT_VTAB; - } - - nodeGetCell(pRtree, pParent, iCell, &cell); - if( !cellContains(pRtree, &cell, pCell) ){ - cellUnion(pRtree, &cell, pCell); - nodeOverwriteCell(pRtree, pParent, &cell, iCell); - } - - p = pParent; - } - return SQLITE_OK; -} - -/* -** Write mapping (iRowid->iNode) to the _rowid table. -*/ -static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ - sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); - sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); - sqlite3_step(pRtree->pWriteRowid); - return sqlite3_reset(pRtree->pWriteRowid); -} - -/* -** Write mapping (iNode->iPar) to the _parent table. -*/ -static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ - sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); - sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); - sqlite3_step(pRtree->pWriteParent); - return sqlite3_reset(pRtree->pWriteParent); -} - -static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); - - -/* -** Arguments aIdx, aDistance and aSpare all point to arrays of size -** nIdx. The aIdx array contains the set of integers from 0 to -** (nIdx-1) in no particular order. This function sorts the values -** in aIdx according to the indexed values in aDistance. For -** example, assuming the inputs: -** -** aIdx = { 0, 1, 2, 3 } -** aDistance = { 5.0, 2.0, 7.0, 6.0 } -** -** this function sets the aIdx array to contain: -** -** aIdx = { 0, 1, 2, 3 } -** -** The aSpare array is used as temporary working space by the -** sorting algorithm. -*/ -static void SortByDistance( - int *aIdx, - int nIdx, - RtreeDValue *aDistance, - int *aSpare -){ - if( nIdx>1 ){ - int iLeft = 0; - int iRight = 0; - - int nLeft = nIdx/2; - int nRight = nIdx-nLeft; - int *aLeft = aIdx; - int *aRight = &aIdx[nLeft]; - - SortByDistance(aLeft, nLeft, aDistance, aSpare); - SortByDistance(aRight, nRight, aDistance, aSpare); - - memcpy(aSpare, aLeft, sizeof(int)*nLeft); - aLeft = aSpare; - - while( iLeft1 ){ - - int iLeft = 0; - int iRight = 0; - - int nLeft = nIdx/2; - int nRight = nIdx-nLeft; - int *aLeft = aIdx; - int *aRight = &aIdx[nLeft]; - - SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); - SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); - - memcpy(aSpare, aLeft, sizeof(int)*nLeft); - aLeft = aSpare; - while( iLeftnDim+1)*(sizeof(int*)+nCell*sizeof(int)); - - aaSorted = (int **)sqlite3_malloc64(nByte); - if( !aaSorted ){ - return SQLITE_NOMEM; - } - - aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; - memset(aaSorted, 0, nByte); - for(ii=0; iinDim; ii++){ - int jj; - aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; - for(jj=0; jjnDim; ii++){ - RtreeDValue margin = RTREE_ZERO; - RtreeDValue fBestOverlap = RTREE_ZERO; - RtreeDValue fBestArea = RTREE_ZERO; - int iBestLeft = 0; - int nLeft; - - for( - nLeft=RTREE_MINCELLS(pRtree); - nLeft<=(nCell-RTREE_MINCELLS(pRtree)); - nLeft++ - ){ - RtreeCell left; - RtreeCell right; - int kk; - RtreeDValue overlap; - RtreeDValue area; - - memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); - memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); - for(kk=1; kk<(nCell-1); kk++){ - if( kk0 ){ - RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); - if( pChild ){ - nodeRelease(pRtree, pChild->pParent); - nodeReference(pNode); - pChild->pParent = pNode; - } - } - return xSetMapping(pRtree, iRowid, pNode->iNode); -} - -static int SplitNode( - Rtree *pRtree, - RtreeNode *pNode, - RtreeCell *pCell, - int iHeight -){ - int i; - int newCellIsRight = 0; - - int rc = SQLITE_OK; - int nCell = NCELL(pNode); - RtreeCell *aCell; - int *aiUsed; - - RtreeNode *pLeft = 0; - RtreeNode *pRight = 0; - - RtreeCell leftbbox; - RtreeCell rightbbox; - - /* Allocate an array and populate it with a copy of pCell and - ** all cells from node pLeft. Then zero the original node. - */ - aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); - if( !aCell ){ - rc = SQLITE_NOMEM; - goto splitnode_out; - } - aiUsed = (int *)&aCell[nCell+1]; - memset(aiUsed, 0, sizeof(int)*(nCell+1)); - for(i=0; iiNode==1 ){ - pRight = nodeNew(pRtree, pNode); - pLeft = nodeNew(pRtree, pNode); - pRtree->iDepth++; - pNode->isDirty = 1; - writeInt16(pNode->zData, pRtree->iDepth); - }else{ - pLeft = pNode; - pRight = nodeNew(pRtree, pLeft->pParent); - pLeft->nRef++; - } - - if( !pLeft || !pRight ){ - rc = SQLITE_NOMEM; - goto splitnode_out; - } - - memset(pLeft->zData, 0, pRtree->iNodeSize); - memset(pRight->zData, 0, pRtree->iNodeSize); - - rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight, - &leftbbox, &rightbbox); - if( rc!=SQLITE_OK ){ - goto splitnode_out; - } - - /* Ensure both child nodes have node numbers assigned to them by calling - ** nodeWrite(). Node pRight always needs a node number, as it was created - ** by nodeNew() above. But node pLeft sometimes already has a node number. - ** In this case avoid the all to nodeWrite(). - */ - if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) - || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) - ){ - goto splitnode_out; - } - - rightbbox.iRowid = pRight->iNode; - leftbbox.iRowid = pLeft->iNode; - - if( pNode->iNode==1 ){ - rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); - if( rc!=SQLITE_OK ){ - goto splitnode_out; - } - }else{ - RtreeNode *pParent = pLeft->pParent; - int iCell; - rc = nodeParentIndex(pRtree, pLeft, &iCell); - if( rc==SQLITE_OK ){ - nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); - rc = AdjustTree(pRtree, pParent, &leftbbox); - } - if( rc!=SQLITE_OK ){ - goto splitnode_out; - } - } - if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ - goto splitnode_out; - } - - for(i=0; iiRowid ){ - newCellIsRight = 1; - } - if( rc!=SQLITE_OK ){ - goto splitnode_out; - } - } - if( pNode->iNode==1 ){ - for(i=0; iiRowid, pLeft, iHeight); - } - - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pRight); - pRight = 0; - } - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pLeft); - pLeft = 0; - } - -splitnode_out: - nodeRelease(pRtree, pRight); - nodeRelease(pRtree, pLeft); - sqlite3_free(aCell); - return rc; -} - -/* -** If node pLeaf is not the root of the r-tree and its pParent pointer is -** still NULL, load all ancestor nodes of pLeaf into memory and populate -** the pLeaf->pParent chain all the way up to the root node. -** -** This operation is required when a row is deleted (or updated - an update -** is implemented as a delete followed by an insert). SQLite provides the -** rowid of the row to delete, which can be used to find the leaf on which -** the entry resides (argument pLeaf). Once the leaf is located, this -** function is called to determine its ancestry. -*/ -static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ - int rc = SQLITE_OK; - RtreeNode *pChild = pLeaf; - while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){ - int rc2 = SQLITE_OK; /* sqlite3_reset() return code */ - sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); - rc = sqlite3_step(pRtree->pReadParent); - if( rc==SQLITE_ROW ){ - RtreeNode *pTest; /* Used to test for reference loops */ - i64 iNode; /* Node number of parent node */ - - /* Before setting pChild->pParent, test that we are not creating a - ** loop of references (as we would if, say, pChild==pParent). We don't - ** want to do this as it leads to a memory leak when trying to delete - ** the referenced counted node structures. - */ - iNode = sqlite3_column_int64(pRtree->pReadParent, 0); - for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent); - if( !pTest ){ - rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent); - } - } - rc = sqlite3_reset(pRtree->pReadParent); - if( rc==SQLITE_OK ) rc = rc2; - if( rc==SQLITE_OK && !pChild->pParent ){ - RTREE_IS_CORRUPT(pRtree); - rc = SQLITE_CORRUPT_VTAB; - } - pChild = pChild->pParent; - } - return rc; -} - -static int deleteCell(Rtree *, RtreeNode *, int, int); - -static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ - int rc; - int rc2; - RtreeNode *pParent = 0; - int iCell; - - assert( pNode->nRef==1 ); - - /* Remove the entry in the parent cell. */ - rc = nodeParentIndex(pRtree, pNode, &iCell); - if( rc==SQLITE_OK ){ - pParent = pNode->pParent; - pNode->pParent = 0; - rc = deleteCell(pRtree, pParent, iCell, iHeight+1); - } - rc2 = nodeRelease(pRtree, pParent); - if( rc==SQLITE_OK ){ - rc = rc2; - } - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Remove the xxx_node entry. */ - sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); - sqlite3_step(pRtree->pDeleteNode); - if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ - return rc; - } - - /* Remove the xxx_parent entry. */ - sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); - sqlite3_step(pRtree->pDeleteParent); - if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ - return rc; - } - - /* Remove the node from the in-memory hash table and link it into - ** the Rtree.pDeleted list. Its contents will be re-inserted later on. - */ - nodeHashDelete(pRtree, pNode); - pNode->iNode = iHeight; - pNode->pNext = pRtree->pDeleted; - pNode->nRef++; - pRtree->pDeleted = pNode; - - return SQLITE_OK; -} - -static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ - RtreeNode *pParent = pNode->pParent; - int rc = SQLITE_OK; - if( pParent ){ - int ii; - int nCell = NCELL(pNode); - RtreeCell box; /* Bounding box for pNode */ - nodeGetCell(pRtree, pNode, 0, &box); - for(ii=1; iiiNode; - rc = nodeParentIndex(pRtree, pNode, &ii); - if( rc==SQLITE_OK ){ - nodeOverwriteCell(pRtree, pParent, &box, ii); - rc = fixBoundingBox(pRtree, pParent); - } - } - return rc; -} - -/* -** Delete the cell at index iCell of node pNode. After removing the -** cell, adjust the r-tree data structure if required. -*/ -static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ - RtreeNode *pParent; - int rc; - - if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ - return rc; - } - - /* Remove the cell from the node. This call just moves bytes around - ** the in-memory node image, so it cannot fail. - */ - nodeDeleteCell(pRtree, pNode, iCell); - - /* If the node is not the tree root and now has less than the minimum - ** number of cells, remove it from the tree. Otherwise, update the - ** cell in the parent node so that it tightly contains the updated - ** node. - */ - pParent = pNode->pParent; - assert( pParent || pNode->iNode==1 ); - if( pParent ){ - if( NCELL(pNode)nDim; iDim++){ - aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); - aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); - } - } - for(iDim=0; iDimnDim; iDim++){ - aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2)); - } - - for(ii=0; iinDim; iDim++){ - RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - - DCOORD(aCell[ii].aCoord[iDim*2])); - aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); - } - } - - SortByDistance(aOrder, nCell, aDistance, aSpare); - nodeZero(pRtree, pNode); - - for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ - RtreeCell *p = &aCell[aOrder[ii]]; - nodeInsertCell(pRtree, pNode, p); - if( p->iRowid==pCell->iRowid ){ - if( iHeight==0 ){ - rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); - }else{ - rc = parentWrite(pRtree, p->iRowid, pNode->iNode); - } - } - } - if( rc==SQLITE_OK ){ - rc = fixBoundingBox(pRtree, pNode); - } - for(; rc==SQLITE_OK && iiiNode currently contains - ** the height of the sub-tree headed by the cell. - */ - RtreeNode *pInsert; - RtreeCell *p = &aCell[aOrder[ii]]; - rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); - if( rc==SQLITE_OK ){ - int rc2; - rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); - rc2 = nodeRelease(pRtree, pInsert); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - - sqlite3_free(aCell); - return rc; -} - -/* -** Insert cell pCell into node pNode. Node pNode is the head of a -** subtree iHeight high (leaf nodes have iHeight==0). -*/ -static int rtreeInsertCell( - Rtree *pRtree, - RtreeNode *pNode, - RtreeCell *pCell, - int iHeight -){ - int rc = SQLITE_OK; - if( iHeight>0 ){ - RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); - if( pChild ){ - nodeRelease(pRtree, pChild->pParent); - nodeReference(pNode); - pChild->pParent = pNode; - } - } - if( nodeInsertCell(pRtree, pNode, pCell) ){ - if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ - rc = SplitNode(pRtree, pNode, pCell, iHeight); - }else{ - pRtree->iReinsertHeight = iHeight; - rc = Reinsert(pRtree, pNode, pCell, iHeight); - } - }else{ - rc = AdjustTree(pRtree, pNode, pCell); - if( rc==SQLITE_OK ){ - if( iHeight==0 ){ - rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); - }else{ - rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); - } - } - } - return rc; -} - -static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ - int ii; - int rc = SQLITE_OK; - int nCell = NCELL(pNode); - - for(ii=0; rc==SQLITE_OK && iiiNode currently contains - ** the height of the sub-tree headed by the cell. - */ - rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert); - if( rc==SQLITE_OK ){ - int rc2; - rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode); - rc2 = nodeRelease(pRtree, pInsert); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - return rc; -} - -/* -** Select a currently unused rowid for a new r-tree record. -*/ -static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){ - int rc; - sqlite3_bind_null(pRtree->pWriteRowid, 1); - sqlite3_bind_null(pRtree->pWriteRowid, 2); - sqlite3_step(pRtree->pWriteRowid); - rc = sqlite3_reset(pRtree->pWriteRowid); - *piRowid = sqlite3_last_insert_rowid(pRtree->db); - return rc; -} - -/* -** Remove the entry with rowid=iDelete from the r-tree structure. -*/ -static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ - int rc; /* Return code */ - RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */ - int iCell; /* Index of iDelete cell in pLeaf */ - RtreeNode *pRoot = 0; /* Root node of rtree structure */ - - - /* Obtain a reference to the root node to initialize Rtree.iDepth */ - rc = nodeAcquire(pRtree, 1, 0, &pRoot); - - /* Obtain a reference to the leaf node that contains the entry - ** about to be deleted. - */ - if( rc==SQLITE_OK ){ - rc = findLeafNode(pRtree, iDelete, &pLeaf, 0); - } - -#ifdef CORRUPT_DB - assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB ); -#endif - - /* Delete the cell in question from the leaf node. */ - if( rc==SQLITE_OK && pLeaf ){ - int rc2; - rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell); - if( rc==SQLITE_OK ){ - rc = deleteCell(pRtree, pLeaf, iCell, 0); - } - rc2 = nodeRelease(pRtree, pLeaf); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - - /* Delete the corresponding entry in the _rowid table. */ - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); - sqlite3_step(pRtree->pDeleteRowid); - rc = sqlite3_reset(pRtree->pDeleteRowid); - } - - /* Check if the root node now has exactly one child. If so, remove - ** it, schedule the contents of the child for reinsertion and - ** reduce the tree height by one. - ** - ** This is equivalent to copying the contents of the child into - ** the root node (the operation that Gutman's paper says to perform - ** in this scenario). - */ - if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){ - int rc2; - RtreeNode *pChild = 0; - i64 iChild = nodeGetRowid(pRtree, pRoot, 0); - rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); - if( rc==SQLITE_OK ){ - rc = removeNode(pRtree, pChild, pRtree->iDepth-1); - } - rc2 = nodeRelease(pRtree, pChild); - if( rc==SQLITE_OK ) rc = rc2; - if( rc==SQLITE_OK ){ - pRtree->iDepth--; - writeInt16(pRoot->zData, pRtree->iDepth); - pRoot->isDirty = 1; - } - } - - /* Re-insert the contents of any underfull nodes removed from the tree. */ - for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ - if( rc==SQLITE_OK ){ - rc = reinsertNodeContent(pRtree, pLeaf); - } - pRtree->pDeleted = pLeaf->pNext; - pRtree->nNodeRef--; - sqlite3_free(pLeaf); - } - - /* Release the reference to the root node. */ - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pRoot); - }else{ - nodeRelease(pRtree, pRoot); - } - - return rc; -} - -/* -** Rounding constants for float->double conversion. -*/ -#define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */ -#define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */ - -#if !defined(SQLITE_RTREE_INT_ONLY) -/* -** Convert an sqlite3_value into an RtreeValue (presumably a float) -** while taking care to round toward negative or positive, respectively. -*/ -static RtreeValue rtreeValueDown(sqlite3_value *v){ - double d = sqlite3_value_double(v); - float f = (float)d; - if( f>d ){ - f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); - } - return f; -} -static RtreeValue rtreeValueUp(sqlite3_value *v){ - double d = sqlite3_value_double(v); - float f = (float)d; - if( fbase.zErrMsg) to an appropriate value and returns -** SQLITE_CONSTRAINT. -** -** Parameter iCol is the index of the leftmost column involved in the -** constraint failure. If it is 0, then the constraint that failed is -** the unique constraint on the id column. Otherwise, it is the rtree -** (c1<=c2) constraint on columns iCol and iCol+1 that has failed. -** -** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT. -*/ -static int rtreeConstraintError(Rtree *pRtree, int iCol){ - sqlite3_stmt *pStmt = 0; - char *zSql; - int rc; - - assert( iCol==0 || iCol%2 ); - zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName); - if( zSql ){ - rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0); - }else{ - rc = SQLITE_NOMEM; - } - sqlite3_free(zSql); - - if( rc==SQLITE_OK ){ - if( iCol==0 ){ - const char *zCol = sqlite3_column_name(pStmt, 0); - pRtree->base.zErrMsg = sqlite3_mprintf( - "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol - ); - }else{ - const char *zCol1 = sqlite3_column_name(pStmt, iCol); - const char *zCol2 = sqlite3_column_name(pStmt, iCol+1); - pRtree->base.zErrMsg = sqlite3_mprintf( - "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2 - ); - } - } - - sqlite3_finalize(pStmt); - return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc); -} - - - -/* -** The xUpdate method for rtree module virtual tables. -*/ -static int rtreeUpdate( - sqlite3_vtab *pVtab, - int nData, - sqlite3_value **aData, - sqlite_int64 *pRowid -){ - Rtree *pRtree = (Rtree *)pVtab; - int rc = SQLITE_OK; - RtreeCell cell; /* New cell to insert if nData>1 */ - int bHaveRowid = 0; /* Set to 1 after new rowid is determined */ - - if( pRtree->nNodeRef ){ - /* Unable to write to the btree while another cursor is reading from it, - ** since the write might do a rebalance which would disrupt the read - ** cursor. */ - return SQLITE_LOCKED_VTAB; - } - rtreeReference(pRtree); - assert(nData>=1); - - cell.iRowid = 0; /* Used only to suppress a compiler warning */ - - /* Constraint handling. A write operation on an r-tree table may return - ** SQLITE_CONSTRAINT for two reasons: - ** - ** 1. A duplicate rowid value, or - ** 2. The supplied data violates the "x2>=x1" constraint. - ** - ** In the first case, if the conflict-handling mode is REPLACE, then - ** the conflicting row can be removed before proceeding. In the second - ** case, SQLITE_CONSTRAINT must be returned regardless of the - ** conflict-handling mode specified by the user. - */ - if( nData>1 ){ - int ii; - int nn = nData - 4; - - if( nn > pRtree->nDim2 ) nn = pRtree->nDim2; - /* Populate the cell.aCoord[] array. The first coordinate is aData[3]. - ** - ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared - ** with "column" that are interpreted as table constraints. - ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5)); - ** This problem was discovered after years of use, so we silently ignore - ** these kinds of misdeclared tables to avoid breaking any legacy. - */ - -#ifndef SQLITE_RTREE_INT_ONLY - if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - for(ii=0; iicell.aCoord[ii+1].f ){ - rc = rtreeConstraintError(pRtree, ii+1); - goto constraint; - } - } - }else -#endif - { - for(ii=0; iicell.aCoord[ii+1].i ){ - rc = rtreeConstraintError(pRtree, ii+1); - goto constraint; - } - } - } - - /* If a rowid value was supplied, check if it is already present in - ** the table. If so, the constraint has failed. */ - if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){ - cell.iRowid = sqlite3_value_int64(aData[2]); - if( sqlite3_value_type(aData[0])==SQLITE_NULL - || sqlite3_value_int64(aData[0])!=cell.iRowid - ){ - int steprc; - sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); - steprc = sqlite3_step(pRtree->pReadRowid); - rc = sqlite3_reset(pRtree->pReadRowid); - if( SQLITE_ROW==steprc ){ - if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ - rc = rtreeDeleteRowid(pRtree, cell.iRowid); - }else{ - rc = rtreeConstraintError(pRtree, 0); - goto constraint; - } - } - } - bHaveRowid = 1; - } - } - - /* If aData[0] is not an SQL NULL value, it is the rowid of a - ** record to delete from the r-tree table. The following block does - ** just that. - */ - if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){ - rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0])); - } - - /* If the aData[] array contains more than one element, elements - ** (aData[2]..aData[argc-1]) contain a new record to insert into - ** the r-tree structure. - */ - if( rc==SQLITE_OK && nData>1 ){ - /* Insert the new record into the r-tree */ - RtreeNode *pLeaf = 0; - - /* Figure out the rowid of the new row. */ - if( bHaveRowid==0 ){ - rc = rtreeNewRowid(pRtree, &cell.iRowid); - } - *pRowid = cell.iRowid; - - if( rc==SQLITE_OK ){ - rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); - } - if( rc==SQLITE_OK ){ - int rc2; - pRtree->iReinsertHeight = -1; - rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); - rc2 = nodeRelease(pRtree, pLeaf); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - if( rc==SQLITE_OK && pRtree->nAux ){ - sqlite3_stmt *pUp = pRtree->pWriteAux; - int jj; - sqlite3_bind_int64(pUp, 1, *pRowid); - for(jj=0; jjnAux; jj++){ - sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]); - } - sqlite3_step(pUp); - rc = sqlite3_reset(pUp); - } - } - -constraint: - rtreeRelease(pRtree); - return rc; -} - -/* -** Called when a transaction starts. -*/ -static int rtreeBeginTransaction(sqlite3_vtab *pVtab){ - Rtree *pRtree = (Rtree *)pVtab; - assert( pRtree->inWrTrans==0 ); - pRtree->inWrTrans++; - return SQLITE_OK; -} - -/* -** Called when a transaction completes (either by COMMIT or ROLLBACK). -** The sqlite3_blob object should be released at this point. -*/ -static int rtreeEndTransaction(sqlite3_vtab *pVtab){ - Rtree *pRtree = (Rtree *)pVtab; - pRtree->inWrTrans = 0; - nodeBlobReset(pRtree); - return SQLITE_OK; -} - -/* -** The xRename method for rtree module virtual tables. -*/ -static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ - Rtree *pRtree = (Rtree *)pVtab; - int rc = SQLITE_NOMEM; - char *zSql = sqlite3_mprintf( - "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" - "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" - "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" - , pRtree->zDb, pRtree->zName, zNewName - , pRtree->zDb, pRtree->zName, zNewName - , pRtree->zDb, pRtree->zName, zNewName - ); - if( zSql ){ - nodeBlobReset(pRtree); - rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); - sqlite3_free(zSql); - } - return rc; -} - -/* -** The xSavepoint method. -** -** This module does not need to do anything to support savepoints. However, -** it uses this hook to close any open blob handle. This is done because a -** DROP TABLE command - which fortunately always opens a savepoint - cannot -** succeed if there are any open blob handles. i.e. if the blob handle were -** not closed here, the following would fail: -** -** BEGIN; -** INSERT INTO rtree... -** DROP TABLE ; -- Would fail with SQLITE_LOCKED -** COMMIT; -*/ -static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){ - Rtree *pRtree = (Rtree *)pVtab; - u8 iwt = pRtree->inWrTrans; - UNUSED_PARAMETER(iSavepoint); - pRtree->inWrTrans = 0; - nodeBlobReset(pRtree); - pRtree->inWrTrans = iwt; - return SQLITE_OK; -} - -/* -** This function populates the pRtree->nRowEst variable with an estimate -** of the number of rows in the virtual table. If possible, this is based -** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST. -*/ -static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){ - const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'"; - char *zSql; - sqlite3_stmt *p; - int rc; - i64 nRow = 0; - - rc = sqlite3_table_column_metadata( - db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0 - ); - if( rc!=SQLITE_OK ){ - pRtree->nRowEst = RTREE_DEFAULT_ROWEST; - return rc==SQLITE_ERROR ? SQLITE_OK : rc; - } - zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0); - if( rc==SQLITE_OK ){ - if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0); - rc = sqlite3_finalize(p); - }else if( rc!=SQLITE_NOMEM ){ - rc = SQLITE_OK; - } - - if( rc==SQLITE_OK ){ - if( nRow==0 ){ - pRtree->nRowEst = RTREE_DEFAULT_ROWEST; - }else{ - pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST); - } - } - sqlite3_free(zSql); - } - - return rc; -} - - -/* -** Return true if zName is the extension on one of the shadow tables used -** by this module. -*/ -static int rtreeShadowName(const char *zName){ - static const char *azName[] = { - "node", "parent", "rowid" - }; - unsigned int i; - for(i=0; idb = db; - - if( isCreate ){ - char *zCreate; - sqlite3_str *p = sqlite3_str_new(db); - int ii; - sqlite3_str_appendf(p, - "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno", - zDb, zPrefix); - for(ii=0; iinAux; ii++){ - sqlite3_str_appendf(p,",a%d",ii); - } - sqlite3_str_appendf(p, - ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);", - zDb, zPrefix); - sqlite3_str_appendf(p, - "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);", - zDb, zPrefix); - sqlite3_str_appendf(p, - "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))", - zDb, zPrefix, pRtree->iNodeSize); - zCreate = sqlite3_str_finish(p); - if( !zCreate ){ - return SQLITE_NOMEM; - } - rc = sqlite3_exec(db, zCreate, 0, 0, 0); - sqlite3_free(zCreate); - if( rc!=SQLITE_OK ){ - return rc; - } - } - - appStmt[0] = &pRtree->pWriteNode; - appStmt[1] = &pRtree->pDeleteNode; - appStmt[2] = &pRtree->pReadRowid; - appStmt[3] = &pRtree->pWriteRowid; - appStmt[4] = &pRtree->pDeleteRowid; - appStmt[5] = &pRtree->pReadParent; - appStmt[6] = &pRtree->pWriteParent; - appStmt[7] = &pRtree->pDeleteParent; - - rc = rtreeQueryStat1(db, pRtree); - for(i=0; inAux==0 ){ - zFormat = azSql[i]; - }else { - /* An UPSERT is very slightly slower than REPLACE, but it is needed - ** if there are auxiliary columns */ - zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)" - "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno"; - } - zSql = sqlite3_mprintf(zFormat, zDb, zPrefix); - if( zSql ){ - rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0); - }else{ - rc = SQLITE_NOMEM; - } - sqlite3_free(zSql); - } - if( pRtree->nAux ){ - pRtree->zReadAuxSql = sqlite3_mprintf( - "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1", - zDb, zPrefix); - if( pRtree->zReadAuxSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - sqlite3_str *p = sqlite3_str_new(db); - int ii; - char *zSql; - sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix); - for(ii=0; iinAux; ii++){ - if( ii ) sqlite3_str_append(p, ",", 1); - if( iinAuxNotNull ){ - sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii); - }else{ - sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2); - } - } - sqlite3_str_appendf(p, " WHERE rowid=?1"); - zSql = sqlite3_str_finish(p); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0); - sqlite3_free(zSql); - } - } - } - - return rc; -} - -/* -** The second argument to this function contains the text of an SQL statement -** that returns a single integer value. The statement is compiled and executed -** using database connection db. If successful, the integer value returned -** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error -** code is returned and the value of *piVal after returning is not defined. -*/ -static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){ - int rc = SQLITE_NOMEM; - if( zSql ){ - sqlite3_stmt *pStmt = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *piVal = sqlite3_column_int(pStmt, 0); - } - rc = sqlite3_finalize(pStmt); - } - } - return rc; -} - -/* -** This function is called from within the xConnect() or xCreate() method to -** determine the node-size used by the rtree table being created or connected -** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned. -** Otherwise, an SQLite error code is returned. -** -** If this function is being called as part of an xConnect(), then the rtree -** table already exists. In this case the node-size is determined by inspecting -** the root node of the tree. -** -** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. -** This ensures that each node is stored on a single database page. If the -** database page-size is so large that more than RTREE_MAXCELLS entries -** would fit in a single node, use a smaller node-size. -*/ -static int getNodeSize( - sqlite3 *db, /* Database handle */ - Rtree *pRtree, /* Rtree handle */ - int isCreate, /* True for xCreate, false for xConnect */ - char **pzErr /* OUT: Error message, if any */ -){ - int rc; - char *zSql; - if( isCreate ){ - int iPageSize = 0; - zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); - rc = getIntFromStmt(db, zSql, &iPageSize); - if( rc==SQLITE_OK ){ - pRtree->iNodeSize = iPageSize-64; - if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)iNodeSize ){ - pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; - } - }else{ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - } - }else{ - zSql = sqlite3_mprintf( - "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", - pRtree->zDb, pRtree->zName - ); - rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); - if( rc!=SQLITE_OK ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - }else if( pRtree->iNodeSize<(512-64) ){ - rc = SQLITE_CORRUPT_VTAB; - RTREE_IS_CORRUPT(pRtree); - *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"", - pRtree->zName); - } - } - - sqlite3_free(zSql); - return rc; -} - -/* -** Return the length of a token -*/ -static int rtreeTokenLength(const char *z){ - int dummy = 0; - return sqlite3GetToken((const unsigned char*)z,&dummy); -} - -/* -** This function is the implementation of both the xConnect and xCreate -** methods of the r-tree virtual table. -** -** argv[0] -> module name -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> column names... -*/ -static int rtreeInit( - sqlite3 *db, /* Database connection */ - void *pAux, /* One of the RTREE_COORD_* constants */ - int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ - sqlite3_vtab **ppVtab, /* OUT: New virtual table */ - char **pzErr, /* OUT: Error message, if any */ - int isCreate /* True for xCreate, false for xConnect */ -){ - int rc = SQLITE_OK; - Rtree *pRtree; - int nDb; /* Length of string argv[1] */ - int nName; /* Length of string argv[2] */ - int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32); - sqlite3_str *pSql; - char *zSql; - int ii = 4; - int iErr; - - const char *aErrMsg[] = { - 0, /* 0 */ - "Wrong number of columns for an rtree table", /* 1 */ - "Too few columns for an rtree table", /* 2 */ - "Too many columns for an rtree table", /* 3 */ - "Auxiliary rtree columns must be last" /* 4 */ - }; - - assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */ - if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){ - *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]); - return SQLITE_ERROR; - } - - sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); - - /* Allocate the sqlite3_vtab structure */ - nDb = (int)strlen(argv[1]); - nName = (int)strlen(argv[2]); - pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2); - if( !pRtree ){ - return SQLITE_NOMEM; - } - memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); - pRtree->nBusy = 1; - pRtree->base.pModule = &rtreeModule; - pRtree->zDb = (char *)&pRtree[1]; - pRtree->zName = &pRtree->zDb[nDb+1]; - pRtree->eCoordType = (u8)eCoordType; - memcpy(pRtree->zDb, argv[1], nDb); - memcpy(pRtree->zName, argv[2], nName); - - - /* Create/Connect to the underlying relational database schema. If - ** that is successful, call sqlite3_declare_vtab() to configure - ** the r-tree table schema. - */ - pSql = sqlite3_str_new(db); - sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT", - rtreeTokenLength(argv[3]), argv[3]); - for(ii=4; iinAux++; - sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1); - }else if( pRtree->nAux>0 ){ - break; - }else{ - static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"}; - pRtree->nDim2++; - sqlite3_str_appendf(pSql, azFormat[eCoordType], - rtreeTokenLength(zArg), zArg); - } - } - sqlite3_str_appendf(pSql, ");"); - zSql = sqlite3_str_finish(pSql); - if( !zSql ){ - rc = SQLITE_NOMEM; - }else if( iinDim = pRtree->nDim2/2; - if( pRtree->nDim<1 ){ - iErr = 2; - }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){ - iErr = 3; - }else if( pRtree->nDim2 % 2 ){ - iErr = 1; - }else{ - iErr = 0; - } - if( iErr ){ - *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); - goto rtreeInit_fail; - } - pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; - - /* Figure out the node size to use. */ - rc = getNodeSize(db, pRtree, isCreate, pzErr); - if( rc ) goto rtreeInit_fail; - rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate); - if( rc ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - goto rtreeInit_fail; - } - - *ppVtab = (sqlite3_vtab *)pRtree; - return SQLITE_OK; - -rtreeInit_fail: - if( rc==SQLITE_OK ) rc = SQLITE_ERROR; - assert( *ppVtab==0 ); - assert( pRtree->nBusy==1 ); - rtreeRelease(pRtree); - return rc; -} - - -/* -** Implementation of a scalar function that decodes r-tree nodes to -** human readable strings. This can be used for debugging and analysis. -** -** The scalar function takes two arguments: (1) the number of dimensions -** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing -** an r-tree node. For a two-dimensional r-tree structure called "rt", to -** deserialize all nodes, a statement like: -** -** SELECT rtreenode(2, data) FROM rt_node; -** -** The human readable string takes the form of a Tcl list with one -** entry for each cell in the r-tree node. Each entry is itself a -** list, containing the 8-byte rowid/pageno followed by the -** *2 coordinates. -*/ -static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ - RtreeNode node; - Rtree tree; - int ii; - int nData; - int errCode; - sqlite3_str *pOut; - - UNUSED_PARAMETER(nArg); - memset(&node, 0, sizeof(RtreeNode)); - memset(&tree, 0, sizeof(Rtree)); - tree.nDim = (u8)sqlite3_value_int(apArg[0]); - if( tree.nDim<1 || tree.nDim>5 ) return; - tree.nDim2 = tree.nDim*2; - tree.nBytesPerCell = 8 + 8 * tree.nDim; - node.zData = (u8 *)sqlite3_value_blob(apArg[1]); - nData = sqlite3_value_bytes(apArg[1]); - if( nData<4 ) return; - if( nData0 ) sqlite3_str_append(pOut, " ", 1); - sqlite3_str_appendf(pOut, "{%lld", cell.iRowid); - for(jj=0; jjrc==SQLITE_OK ) pCheck->rc = rc; -} - -/* -** The second and subsequent arguments to this function are a format string -** and printf style arguments. This function formats the string and attempts -** to compile it as an SQL statement. -** -** If successful, a pointer to the new SQL statement is returned. Otherwise, -** NULL is returned and an error code left in RtreeCheck.rc. -*/ -static sqlite3_stmt *rtreeCheckPrepare( - RtreeCheck *pCheck, /* RtreeCheck object */ - const char *zFmt, ... /* Format string and trailing args */ -){ - va_list ap; - char *z; - sqlite3_stmt *pRet = 0; - - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - - if( pCheck->rc==SQLITE_OK ){ - if( z==0 ){ - pCheck->rc = SQLITE_NOMEM; - }else{ - pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0); - } - } - - sqlite3_free(z); - va_end(ap); - return pRet; -} - -/* -** The second and subsequent arguments to this function are a printf() -** style format string and arguments. This function formats the string and -** appends it to the report being accumuated in pCheck. -*/ -static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){ - va_list ap; - va_start(ap, zFmt); - if( pCheck->rc==SQLITE_OK && pCheck->nErrrc = SQLITE_NOMEM; - }else{ - pCheck->zReport = sqlite3_mprintf("%z%s%z", - pCheck->zReport, (pCheck->zReport ? "\n" : ""), z - ); - if( pCheck->zReport==0 ){ - pCheck->rc = SQLITE_NOMEM; - } - } - pCheck->nErr++; - } - va_end(ap); -} - -/* -** This function is a no-op if there is already an error code stored -** in the RtreeCheck object indicated by the first argument. NULL is -** returned in this case. -** -** Otherwise, the contents of rtree table node iNode are loaded from -** the database and copied into a buffer obtained from sqlite3_malloc(). -** If no error occurs, a pointer to the buffer is returned and (*pnNode) -** is set to the size of the buffer in bytes. -** -** Or, if an error does occur, NULL is returned and an error code left -** in the RtreeCheck object. The final value of *pnNode is undefined in -** this case. -*/ -static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){ - u8 *pRet = 0; /* Return value */ - - if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){ - pCheck->pGetNode = rtreeCheckPrepare(pCheck, - "SELECT data FROM %Q.'%q_node' WHERE nodeno=?", - pCheck->zDb, pCheck->zTab - ); - } - - if( pCheck->rc==SQLITE_OK ){ - sqlite3_bind_int64(pCheck->pGetNode, 1, iNode); - if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){ - int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0); - const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0); - pRet = sqlite3_malloc64(nNode); - if( pRet==0 ){ - pCheck->rc = SQLITE_NOMEM; - }else{ - memcpy(pRet, pNode, nNode); - *pnNode = nNode; - } - } - rtreeCheckReset(pCheck, pCheck->pGetNode); - if( pCheck->rc==SQLITE_OK && pRet==0 ){ - rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode); - } - } - - return pRet; -} - -/* -** This function is used to check that the %_parent (if bLeaf==0) or %_rowid -** (if bLeaf==1) table contains a specified entry. The schemas of the -** two tables are: -** -** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) -** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...) -** -** In both cases, this function checks that there exists an entry with -** IPK value iKey and the second column set to iVal. -** -*/ -static void rtreeCheckMapping( - RtreeCheck *pCheck, /* RtreeCheck object */ - int bLeaf, /* True for a leaf cell, false for interior */ - i64 iKey, /* Key for mapping */ - i64 iVal /* Expected value for mapping */ -){ - int rc; - sqlite3_stmt *pStmt; - const char *azSql[2] = { - "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1", - "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1" - }; - - assert( bLeaf==0 || bLeaf==1 ); - if( pCheck->aCheckMapping[bLeaf]==0 ){ - pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck, - azSql[bLeaf], pCheck->zDb, pCheck->zTab - ); - } - if( pCheck->rc!=SQLITE_OK ) return; - - pStmt = pCheck->aCheckMapping[bLeaf]; - sqlite3_bind_int64(pStmt, 1, iKey); - rc = sqlite3_step(pStmt); - if( rc==SQLITE_DONE ){ - rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table", - iKey, iVal, (bLeaf ? "%_rowid" : "%_parent") - ); - }else if( rc==SQLITE_ROW ){ - i64 ii = sqlite3_column_int64(pStmt, 0); - if( ii!=iVal ){ - rtreeCheckAppendMsg(pCheck, - "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)", - iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal - ); - } - } - rtreeCheckReset(pCheck, pStmt); -} - -/* -** Argument pCell points to an array of coordinates stored on an rtree page. -** This function checks that the coordinates are internally consistent (no -** x1>x2 conditions) and adds an error message to the RtreeCheck object -** if they are not. -** -** Additionally, if pParent is not NULL, then it is assumed to point to -** the array of coordinates on the parent page that bound the page -** containing pCell. In this case it is also verified that the two -** sets of coordinates are mutually consistent and an error message added -** to the RtreeCheck object if they are not. -*/ -static void rtreeCheckCellCoord( - RtreeCheck *pCheck, - i64 iNode, /* Node id to use in error messages */ - int iCell, /* Cell number to use in error messages */ - u8 *pCell, /* Pointer to cell coordinates */ - u8 *pParent /* Pointer to parent coordinates */ -){ - RtreeCoord c1, c2; - RtreeCoord p1, p2; - int i; - - for(i=0; inDim; i++){ - readCoord(&pCell[4*2*i], &c1); - readCoord(&pCell[4*(2*i + 1)], &c2); - - /* printf("%e, %e\n", c1.u.f, c2.u.f); */ - if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){ - rtreeCheckAppendMsg(pCheck, - "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode - ); - } - - if( pParent ){ - readCoord(&pParent[4*2*i], &p1); - readCoord(&pParent[4*(2*i + 1)], &p2); - - if( (pCheck->bInt ? c1.ibInt ? c2.i>p2.i : c2.f>p2.f) - ){ - rtreeCheckAppendMsg(pCheck, - "Dimension %d of cell %d on node %lld is corrupt relative to parent" - , i, iCell, iNode - ); - } - } - } -} - -/* -** Run rtreecheck() checks on node iNode, which is at depth iDepth within -** the r-tree structure. Argument aParent points to the array of coordinates -** that bound node iNode on the parent node. -** -** If any problems are discovered, an error message is appended to the -** report accumulated in the RtreeCheck object. -*/ -static void rtreeCheckNode( - RtreeCheck *pCheck, - int iDepth, /* Depth of iNode (0==leaf) */ - u8 *aParent, /* Buffer containing parent coords */ - i64 iNode /* Node to check */ -){ - u8 *aNode = 0; - int nNode = 0; - - assert( iNode==1 || aParent!=0 ); - assert( pCheck->nDim>0 ); - - aNode = rtreeCheckGetNode(pCheck, iNode, &nNode); - if( aNode ){ - if( nNode<4 ){ - rtreeCheckAppendMsg(pCheck, - "Node %lld is too small (%d bytes)", iNode, nNode - ); - }else{ - int nCell; /* Number of cells on page */ - int i; /* Used to iterate through cells */ - if( aParent==0 ){ - iDepth = readInt16(aNode); - if( iDepth>RTREE_MAX_DEPTH ){ - rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth); - sqlite3_free(aNode); - return; - } - } - nCell = readInt16(&aNode[2]); - if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){ - rtreeCheckAppendMsg(pCheck, - "Node %lld is too small for cell count of %d (%d bytes)", - iNode, nCell, nNode - ); - }else{ - for(i=0; inDim*2*4)]; - i64 iVal = readInt64(pCell); - rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent); - - if( iDepth>0 ){ - rtreeCheckMapping(pCheck, 0, iVal, iNode); - rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal); - pCheck->nNonLeaf++; - }else{ - rtreeCheckMapping(pCheck, 1, iVal, iNode); - pCheck->nLeaf++; - } - } - } - } - sqlite3_free(aNode); - } -} - -/* -** The second argument to this function must be either "_rowid" or -** "_parent". This function checks that the number of entries in the -** %_rowid or %_parent table is exactly nExpect. If not, it adds -** an error message to the report in the RtreeCheck object indicated -** by the first argument. -*/ -static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){ - if( pCheck->rc==SQLITE_OK ){ - sqlite3_stmt *pCount; - pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'", - pCheck->zDb, pCheck->zTab, zTbl - ); - if( pCount ){ - if( sqlite3_step(pCount)==SQLITE_ROW ){ - i64 nActual = sqlite3_column_int64(pCount, 0); - if( nActual!=nExpect ){ - rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table" - " - expected %lld, actual %lld" , zTbl, nExpect, nActual - ); - } - } - pCheck->rc = sqlite3_finalize(pCount); - } - } -} - -/* -** This function does the bulk of the work for the rtree integrity-check. -** It is called by rtreecheck(), which is the SQL function implementation. -*/ -static int rtreeCheckTable( - sqlite3 *db, /* Database handle to access db through */ - const char *zDb, /* Name of db ("main", "temp" etc.) */ - const char *zTab, /* Name of rtree table to check */ - char **pzReport /* OUT: sqlite3_malloc'd report text */ -){ - RtreeCheck check; /* Common context for various routines */ - sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */ - int bEnd = 0; /* True if transaction should be closed */ - int nAux = 0; /* Number of extra columns. */ - - /* Initialize the context object */ - memset(&check, 0, sizeof(check)); - check.db = db; - check.zDb = zDb; - check.zTab = zTab; - - /* If there is not already an open transaction, open one now. This is - ** to ensure that the queries run as part of this integrity-check operate - ** on a consistent snapshot. */ - if( sqlite3_get_autocommit(db) ){ - check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); - bEnd = 1; - } - - /* Find the number of auxiliary columns */ - if( check.rc==SQLITE_OK ){ - pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab); - if( pStmt ){ - nAux = sqlite3_column_count(pStmt) - 2; - sqlite3_finalize(pStmt); - } - check.rc = SQLITE_OK; - } - - /* Find number of dimensions in the rtree table. */ - pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab); - if( pStmt ){ - int rc; - check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2; - if( check.nDim<1 ){ - rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree"); - }else if( SQLITE_ROW==sqlite3_step(pStmt) ){ - check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER); - } - rc = sqlite3_finalize(pStmt); - if( rc!=SQLITE_CORRUPT ) check.rc = rc; - } - - /* Do the actual integrity-check */ - if( check.nDim>=1 ){ - if( check.rc==SQLITE_OK ){ - rtreeCheckNode(&check, 0, 0, 1); - } - rtreeCheckCount(&check, "_rowid", check.nLeaf); - rtreeCheckCount(&check, "_parent", check.nNonLeaf); - } - - /* Finalize SQL statements used by the integrity-check */ - sqlite3_finalize(check.pGetNode); - sqlite3_finalize(check.aCheckMapping[0]); - sqlite3_finalize(check.aCheckMapping[1]); - - /* If one was opened, close the transaction */ - if( bEnd ){ - int rc = sqlite3_exec(db, "END", 0, 0, 0); - if( check.rc==SQLITE_OK ) check.rc = rc; - } - *pzReport = check.zReport; - return check.rc; -} - -/* -** Usage: -** -** rtreecheck(); -** rtreecheck(, ); -** -** Invoking this SQL function runs an integrity-check on the named rtree -** table. The integrity-check verifies the following: -** -** 1. For each cell in the r-tree structure (%_node table), that: -** -** a) for each dimension, (coord1 <= coord2). -** -** b) unless the cell is on the root node, that the cell is bounded -** by the parent cell on the parent node. -** -** c) for leaf nodes, that there is an entry in the %_rowid -** table corresponding to the cell's rowid value that -** points to the correct node. -** -** d) for cells on non-leaf nodes, that there is an entry in the -** %_parent table mapping from the cell's child node to the -** node that it resides on. -** -** 2. That there are the same number of entries in the %_rowid table -** as there are leaf cells in the r-tree structure, and that there -** is a leaf cell that corresponds to each entry in the %_rowid table. -** -** 3. That there are the same number of entries in the %_parent table -** as there are non-leaf cells in the r-tree structure, and that -** there is a non-leaf cell that corresponds to each entry in the -** %_parent table. -*/ -static void rtreecheck( - sqlite3_context *ctx, - int nArg, - sqlite3_value **apArg -){ - if( nArg!=1 && nArg!=2 ){ - sqlite3_result_error(ctx, - "wrong number of arguments to function rtreecheck()", -1 - ); - }else{ - int rc; - char *zReport = 0; - const char *zDb = (const char*)sqlite3_value_text(apArg[0]); - const char *zTab; - if( nArg==1 ){ - zTab = zDb; - zDb = "main"; - }else{ - zTab = (const char*)sqlite3_value_text(apArg[1]); - } - rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport); - if( rc==SQLITE_OK ){ - sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT); - }else{ - sqlite3_result_error_code(ctx, rc); - } - sqlite3_free(zReport); - } -} - -/* Conditionally include the geopoly code */ -#ifdef SQLITE_ENABLE_GEOPOLY -/************** Include geopoly.c in the middle of rtree.c *******************/ -/************** Begin file geopoly.c *****************************************/ -/* -** 2018-05-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 implements an alternative R-Tree virtual table that -** uses polygons to express the boundaries of 2-dimensional objects. -** -** This file is #include-ed onto the end of "rtree.c" so that it has -** access to all of the R-Tree internals. -*/ -/* #include */ - -/* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */ -#ifdef GEOPOLY_ENABLE_DEBUG - static int geo_debug = 0; -# define GEODEBUG(X) if(geo_debug)printf X -#else -# define GEODEBUG(X) -#endif - -#ifndef JSON_NULL /* The following stuff repeats things found in json1 */ -/* -** Versions of isspace(), isalnum() and isdigit() to which it is safe -** to pass signed char values. -*/ -#ifdef sqlite3Isdigit - /* Use the SQLite core versions if this routine is part of the - ** SQLite amalgamation */ -# define safe_isdigit(x) sqlite3Isdigit(x) -# define safe_isalnum(x) sqlite3Isalnum(x) -# define safe_isxdigit(x) sqlite3Isxdigit(x) -#else - /* Use the standard library for separate compilation */ -#include /* amalgamator: keep */ -# define safe_isdigit(x) isdigit((unsigned char)(x)) -# define safe_isalnum(x) isalnum((unsigned char)(x)) -# define safe_isxdigit(x) isxdigit((unsigned char)(x)) -#endif - -/* -** Growing our own isspace() routine this way is twice as fast as -** the library isspace() function. -*/ -static const char geopolyIsSpace[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -}; -#define safe_isspace(x) (geopolyIsSpace[(unsigned char)x]) -#endif /* JSON NULL - back to original code */ - -/* Compiler and version */ -#ifndef GCC_VERSION -#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) -# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) -#else -# define GCC_VERSION 0 -#endif -#endif -#ifndef MSVC_VERSION -#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) -# define MSVC_VERSION _MSC_VER -#else -# define MSVC_VERSION 0 -#endif -#endif - -/* Datatype for coordinates -*/ -typedef float GeoCoord; - -/* -** Internal representation of a polygon. -** -** The polygon consists of a sequence of vertexes. There is a line -** segment between each pair of vertexes, and one final segment from -** the last vertex back to the first. (This differs from the GeoJSON -** standard in which the final vertex is a repeat of the first.) -** -** The polygon follows the right-hand rule. The area to the right of -** each segment is "outside" and the area to the left is "inside". -** -** The on-disk representation consists of a 4-byte header followed by -** the values. The 4-byte header is: -** -** encoding (1 byte) 0=big-endian, 1=little-endian -** nvertex (3 bytes) Number of vertexes as a big-endian integer -** -** Enough space is allocated for 4 coordinates, to work around over-zealous -** warnings coming from some compiler (notably, clang). In reality, the size -** of each GeoPoly memory allocate is adjusted as necessary so that the -** GeoPoly.a[] array at the end is the appropriate size. -*/ -typedef struct GeoPoly GeoPoly; -struct GeoPoly { - int nVertex; /* Number of vertexes */ - unsigned char hdr[4]; /* Header for on-disk representation */ - GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */ -}; - -/* The size of a memory allocation needed for a GeoPoly object sufficient -** to hold N coordinate pairs. -*/ -#define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4)) - -/* Macros to access coordinates of a GeoPoly. -** We have to use these macros, rather than just say p->a[i] in order -** to silence (incorrect) UBSAN warnings if the array index is too large. -*/ -#define GeoX(P,I) (((GeoCoord*)(P)->a)[(I)*2]) -#define GeoY(P,I) (((GeoCoord*)(P)->a)[(I)*2+1]) - - -/* -** State of a parse of a GeoJSON input. -*/ -typedef struct GeoParse GeoParse; -struct GeoParse { - const unsigned char *z; /* Unparsed input */ - int nVertex; /* Number of vertexes in a[] */ - int nAlloc; /* Space allocated to a[] */ - int nErr; /* Number of errors encountered */ - GeoCoord *a; /* Array of vertexes. From sqlite3_malloc64() */ -}; - -/* Do a 4-byte byte swap */ -static void geopolySwab32(unsigned char *a){ - unsigned char t = a[0]; - a[0] = a[3]; - a[3] = t; - t = a[1]; - a[1] = a[2]; - a[2] = t; -} - -/* Skip whitespace. Return the next non-whitespace character. */ -static char geopolySkipSpace(GeoParse *p){ - while( safe_isspace(p->z[0]) ) p->z++; - return p->z[0]; -} - -/* Parse out a number. Write the value into *pVal if pVal!=0. -** return non-zero on success and zero if the next token is not a number. -*/ -static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){ - char c = geopolySkipSpace(p); - const unsigned char *z = p->z; - int j = 0; - int seenDP = 0; - int seenE = 0; - if( c=='-' ){ - j = 1; - c = z[j]; - } - if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0; - for(;; j++){ - c = z[j]; - if( safe_isdigit(c) ) continue; - if( c=='.' ){ - if( z[j-1]=='-' ) return 0; - if( seenDP ) return 0; - seenDP = 1; - continue; - } - if( c=='e' || c=='E' ){ - if( z[j-1]<'0' ) return 0; - if( seenE ) return -1; - seenDP = seenE = 1; - c = z[j+1]; - if( c=='+' || c=='-' ){ - j++; - c = z[j+1]; - } - if( c<'0' || c>'9' ) return 0; - continue; - } - break; - } - if( z[j-1]<'0' ) return 0; - if( pVal ){ -#ifdef SQLITE_AMALGAMATION - /* The sqlite3AtoF() routine is much much faster than atof(), if it - ** is available */ - double r; - (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8); - *pVal = r; -#else - *pVal = (GeoCoord)atof((const char*)p->z); -#endif - } - p->z += j; - return 1; -} - -/* -** If the input is a well-formed JSON array of coordinates with at least -** four coordinates and where each coordinate is itself a two-value array, -** then convert the JSON into a GeoPoly object and return a pointer to -** that object. -** -** If any error occurs, return NULL. -*/ -static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){ - GeoParse s; - int rc = SQLITE_OK; - memset(&s, 0, sizeof(s)); - s.z = z; - if( geopolySkipSpace(&s)=='[' ){ - s.z++; - while( geopolySkipSpace(&s)=='[' ){ - int ii = 0; - char c; - s.z++; - if( s.nVertex>=s.nAlloc ){ - GeoCoord *aNew; - s.nAlloc = s.nAlloc*2 + 16; - aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 ); - if( aNew==0 ){ - rc = SQLITE_NOMEM; - s.nErr++; - break; - } - s.a = aNew; - } - while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){ - ii++; - if( ii==2 ) s.nVertex++; - c = geopolySkipSpace(&s); - s.z++; - if( c==',' ) continue; - if( c==']' && ii>=2 ) break; - s.nErr++; - rc = SQLITE_ERROR; - goto parse_json_err; - } - if( geopolySkipSpace(&s)==',' ){ - s.z++; - continue; - } - break; - } - if( geopolySkipSpace(&s)==']' - && s.nVertex>=4 - && s.a[0]==s.a[s.nVertex*2-2] - && s.a[1]==s.a[s.nVertex*2-1] - && (s.z++, geopolySkipSpace(&s)==0) - ){ - GeoPoly *pOut; - int x = 1; - s.nVertex--; /* Remove the redundant vertex at the end */ - pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) ); - x = 1; - if( pOut==0 ) goto parse_json_err; - pOut->nVertex = s.nVertex; - memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord)); - pOut->hdr[0] = *(unsigned char*)&x; - pOut->hdr[1] = (s.nVertex>>16)&0xff; - pOut->hdr[2] = (s.nVertex>>8)&0xff; - pOut->hdr[3] = s.nVertex&0xff; - sqlite3_free(s.a); - if( pRc ) *pRc = SQLITE_OK; - return pOut; - }else{ - s.nErr++; - rc = SQLITE_ERROR; - } - } -parse_json_err: - if( pRc ) *pRc = rc; - sqlite3_free(s.a); - return 0; -} - -/* -** Given a function parameter, try to interpret it as a polygon, either -** in the binary format or JSON text. Compute a GeoPoly object and -** return a pointer to that object. Or if the input is not a well-formed -** polygon, put an error message in sqlite3_context and return NULL. -*/ -static GeoPoly *geopolyFuncParam( - sqlite3_context *pCtx, /* Context for error messages */ - sqlite3_value *pVal, /* The value to decode */ - int *pRc /* Write error here */ -){ - GeoPoly *p = 0; - int nByte; - if( sqlite3_value_type(pVal)==SQLITE_BLOB - && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord)) - ){ - const unsigned char *a = sqlite3_value_blob(pVal); - int nVertex; - nVertex = (a[1]<<16) + (a[2]<<8) + a[3]; - if( (a[0]==0 || a[0]==1) - && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte - ){ - p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) ); - if( p==0 ){ - if( pRc ) *pRc = SQLITE_NOMEM; - if( pCtx ) sqlite3_result_error_nomem(pCtx); - }else{ - int x = 1; - p->nVertex = nVertex; - memcpy(p->hdr, a, nByte); - if( a[0] != *(unsigned char*)&x ){ - int ii; - for(ii=0; iihdr[0] ^= 1; - } - } - } - if( pRc ) *pRc = SQLITE_OK; - return p; - }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){ - const unsigned char *zJson = sqlite3_value_text(pVal); - if( zJson==0 ){ - if( pRc ) *pRc = SQLITE_NOMEM; - return 0; - } - return geopolyParseJson(zJson, pRc); - }else{ - if( pRc ) *pRc = SQLITE_ERROR; - return 0; - } -} - -/* -** Implementation of the geopoly_blob(X) function. -** -** If the input is a well-formed Geopoly BLOB or JSON string -** then return the BLOB representation of the polygon. Otherwise -** return NULL. -*/ -static void geopolyBlobFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p = geopolyFuncParam(context, argv[0], 0); - if( p ){ - sqlite3_result_blob(context, p->hdr, - 4+8*p->nVertex, SQLITE_TRANSIENT); - sqlite3_free(p); - } -} - -/* -** SQL function: geopoly_json(X) -** -** Interpret X as a polygon and render it as a JSON array -** of coordinates. Or, if X is not a valid polygon, return NULL. -*/ -static void geopolyJsonFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p = geopolyFuncParam(context, argv[0], 0); - if( p ){ - sqlite3 *db = sqlite3_context_db_handle(context); - sqlite3_str *x = sqlite3_str_new(db); - int i; - sqlite3_str_append(x, "[", 1); - for(i=0; inVertex; i++){ - sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i)); - } - sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0)); - sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free); - sqlite3_free(p); - } -} - -/* -** SQL function: geopoly_svg(X, ....) -** -** Interpret X as a polygon and render it as a SVG . -** Additional arguments are added as attributes to the . -*/ -static void geopolySvgFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p; - if( argc<1 ) return; - p = geopolyFuncParam(context, argv[0], 0); - if( p ){ - sqlite3 *db = sqlite3_context_db_handle(context); - sqlite3_str *x = sqlite3_str_new(db); - int i; - char cSep = '\''; - sqlite3_str_appendf(x, ""); - sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free); - sqlite3_free(p); - } -} - -/* -** SQL Function: geopoly_xform(poly, A, B, C, D, E, F) -** -** Transform and/or translate a polygon as follows: -** -** x1 = A*x0 + B*y0 + E -** y1 = C*x0 + D*y0 + F -** -** For a translation: -** -** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset) -** -** Rotate by R around the point (0,0): -** -** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0) -*/ -static void geopolyXformFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p = geopolyFuncParam(context, argv[0], 0); - double A = sqlite3_value_double(argv[1]); - double B = sqlite3_value_double(argv[2]); - double C = sqlite3_value_double(argv[3]); - double D = sqlite3_value_double(argv[4]); - double E = sqlite3_value_double(argv[5]); - double F = sqlite3_value_double(argv[6]); - GeoCoord x1, y1, x0, y0; - int ii; - if( p ){ - for(ii=0; iinVertex; ii++){ - x0 = GeoX(p,ii); - y0 = GeoY(p,ii); - x1 = (GeoCoord)(A*x0 + B*y0 + E); - y1 = (GeoCoord)(C*x0 + D*y0 + F); - GeoX(p,ii) = x1; - GeoY(p,ii) = y1; - } - sqlite3_result_blob(context, p->hdr, - 4+8*p->nVertex, SQLITE_TRANSIENT); - sqlite3_free(p); - } -} - -/* -** Compute the area enclosed by the polygon. -** -** This routine can also be used to detect polygons that rotate in -** the wrong direction. Polygons are suppose to be counter-clockwise (CCW). -** This routine returns a negative value for clockwise (CW) polygons. -*/ -static double geopolyArea(GeoPoly *p){ - double rArea = 0.0; - int ii; - for(ii=0; iinVertex-1; ii++){ - rArea += (GeoX(p,ii) - GeoX(p,ii+1)) /* (x0 - x1) */ - * (GeoY(p,ii) + GeoY(p,ii+1)) /* (y0 + y1) */ - * 0.5; - } - rArea += (GeoX(p,ii) - GeoX(p,0)) /* (xN - x0) */ - * (GeoY(p,ii) + GeoY(p,0)) /* (yN + y0) */ - * 0.5; - return rArea; -} - -/* -** Implementation of the geopoly_area(X) function. -** -** If the input is a well-formed Geopoly BLOB then return the area -** enclosed by the polygon. If the polygon circulates clockwise instead -** of counterclockwise (as it should) then return the negative of the -** enclosed area. Otherwise return NULL. -*/ -static void geopolyAreaFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p = geopolyFuncParam(context, argv[0], 0); - if( p ){ - sqlite3_result_double(context, geopolyArea(p)); - sqlite3_free(p); - } -} - -/* -** Implementation of the geopoly_ccw(X) function. -** -** If the rotation of polygon X is clockwise (incorrect) instead of -** counter-clockwise (the correct winding order according to RFC7946) -** then reverse the order of the vertexes in polygon X. -** -** In other words, this routine returns a CCW polygon regardless of the -** winding order of its input. -** -** Use this routine to sanitize historical inputs that that sometimes -** contain polygons that wind in the wrong direction. -*/ -static void geopolyCcwFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p = geopolyFuncParam(context, argv[0], 0); - if( p ){ - if( geopolyArea(p)<0.0 ){ - int ii, jj; - for(ii=1, jj=p->nVertex-1; iihdr, - 4+8*p->nVertex, SQLITE_TRANSIENT); - sqlite3_free(p); - } -} - -#define GEOPOLY_PI 3.1415926535897932385 - -/* Fast approximation for sine(X) for X between -0.5*pi and 2*pi -*/ -static double geopolySine(double r){ - assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI ); - if( r>=1.5*GEOPOLY_PI ){ - r -= 2.0*GEOPOLY_PI; - } - if( r>=0.5*GEOPOLY_PI ){ - return -geopolySine(r-GEOPOLY_PI); - }else{ - double r2 = r*r; - double r3 = r2*r; - double r5 = r3*r2; - return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5; - } -} - -/* -** Function: geopoly_regular(X,Y,R,N) -** -** Construct a simple, convex, regular polygon centered at X, Y -** with circumradius R and with N sides. -*/ -static void geopolyRegularFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - double x = sqlite3_value_double(argv[0]); - double y = sqlite3_value_double(argv[1]); - double r = sqlite3_value_double(argv[2]); - int n = sqlite3_value_int(argv[3]); - int i; - GeoPoly *p; - - if( n<3 || r<=0.0 ) return; - if( n>1000 ) n = 1000; - p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) ); - if( p==0 ){ - sqlite3_result_error_nomem(context); - return; - } - i = 1; - p->hdr[0] = *(unsigned char*)&i; - p->hdr[1] = 0; - p->hdr[2] = (n>>8)&0xff; - p->hdr[3] = n&0xff; - for(i=0; ihdr, 4+8*n, SQLITE_TRANSIENT); - sqlite3_free(p); -} - -/* -** If pPoly is a polygon, compute its bounding box. Then: -** -** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL -** (2) otherwise, compute a GeoPoly for the bounding box and return the -** new GeoPoly -** -** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from -** the bounding box in aCoord and return a pointer to that GeoPoly. -*/ -static GeoPoly *geopolyBBox( - sqlite3_context *context, /* For recording the error */ - sqlite3_value *pPoly, /* The polygon */ - RtreeCoord *aCoord, /* Results here */ - int *pRc /* Error code here */ -){ - GeoPoly *pOut = 0; - GeoPoly *p; - float mnX, mxX, mnY, mxY; - if( pPoly==0 && aCoord!=0 ){ - p = 0; - mnX = aCoord[0].f; - mxX = aCoord[1].f; - mnY = aCoord[2].f; - mxY = aCoord[3].f; - goto geopolyBboxFill; - }else{ - p = geopolyFuncParam(context, pPoly, pRc); - } - if( p ){ - int ii; - mnX = mxX = GeoX(p,0); - mnY = mxY = GeoY(p,0); - for(ii=1; iinVertex; ii++){ - double r = GeoX(p,ii); - if( rmxX ) mxX = (float)r; - r = GeoY(p,ii); - if( rmxY ) mxY = (float)r; - } - if( pRc ) *pRc = SQLITE_OK; - if( aCoord==0 ){ - geopolyBboxFill: - pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4)); - if( pOut==0 ){ - sqlite3_free(p); - if( context ) sqlite3_result_error_nomem(context); - if( pRc ) *pRc = SQLITE_NOMEM; - return 0; - } - pOut->nVertex = 4; - ii = 1; - pOut->hdr[0] = *(unsigned char*)ⅈ - pOut->hdr[1] = 0; - pOut->hdr[2] = 0; - pOut->hdr[3] = 4; - GeoX(pOut,0) = mnX; - GeoY(pOut,0) = mnY; - GeoX(pOut,1) = mxX; - GeoY(pOut,1) = mnY; - GeoX(pOut,2) = mxX; - GeoY(pOut,2) = mxY; - GeoX(pOut,3) = mnX; - GeoY(pOut,3) = mxY; - }else{ - sqlite3_free(p); - aCoord[0].f = mnX; - aCoord[1].f = mxX; - aCoord[2].f = mnY; - aCoord[3].f = mxY; - } - }else{ - memset(aCoord, 0, sizeof(RtreeCoord)*4); - } - return pOut; -} - -/* -** Implementation of the geopoly_bbox(X) SQL function. -*/ -static void geopolyBBoxFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p = geopolyBBox(context, argv[0], 0, 0); - if( p ){ - sqlite3_result_blob(context, p->hdr, - 4+8*p->nVertex, SQLITE_TRANSIENT); - sqlite3_free(p); - } -} - -/* -** State vector for the geopoly_group_bbox() aggregate function. -*/ -typedef struct GeoBBox GeoBBox; -struct GeoBBox { - int isInit; - RtreeCoord a[4]; -}; - - -/* -** Implementation of the geopoly_group_bbox(X) aggregate SQL function. -*/ -static void geopolyBBoxStep( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - RtreeCoord a[4]; - int rc = SQLITE_OK; - (void)geopolyBBox(context, argv[0], a, &rc); - if( rc==SQLITE_OK ){ - GeoBBox *pBBox; - pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox)); - if( pBBox==0 ) return; - if( pBBox->isInit==0 ){ - pBBox->isInit = 1; - memcpy(pBBox->a, a, sizeof(RtreeCoord)*4); - }else{ - if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0]; - if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1]; - if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2]; - if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3]; - } - } -} -static void geopolyBBoxFinal( - sqlite3_context *context -){ - GeoPoly *p; - GeoBBox *pBBox; - pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0); - if( pBBox==0 ) return; - p = geopolyBBox(context, 0, pBBox->a, 0); - if( p ){ - sqlite3_result_blob(context, p->hdr, - 4+8*p->nVertex, SQLITE_TRANSIENT); - sqlite3_free(p); - } -} - - -/* -** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2). -** Returns: -** -** +2 x0,y0 is on the line segement -** -** +1 x0,y0 is beneath line segment -** -** 0 x0,y0 is not on or beneath the line segment or the line segment -** is vertical and x0,y0 is not on the line segment -** -** The left-most coordinate min(x1,x2) is not considered to be part of -** the line segment for the purposes of this analysis. -*/ -static int pointBeneathLine( - double x0, double y0, - double x1, double y1, - double x2, double y2 -){ - double y; - if( x0==x1 && y0==y1 ) return 2; - if( x1x2 ) return 0; - }else if( x1>x2 ){ - if( x0<=x2 || x0>x1 ) return 0; - }else{ - /* Vertical line segment */ - if( x0!=x1 ) return 0; - if( y0y1 && y0>y2 ) return 0; - return 2; - } - y = y1 + (y2-y1)*(x0-x1)/(x2-x1); - if( y0==y ) return 2; - if( y0nVertex-1; ii++){ - v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii), - GeoX(p1,ii+1),GeoY(p1,ii+1)); - if( v==2 ) break; - cnt += v; - } - if( v!=2 ){ - v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii), - GeoX(p1,0), GeoY(p1,0)); - } - if( v==2 ){ - sqlite3_result_int(context, 1); - }else if( ((v+cnt)&1)==0 ){ - sqlite3_result_int(context, 0); - }else{ - sqlite3_result_int(context, 2); - } - sqlite3_free(p1); -} - -/* Forward declaration */ -static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2); - -/* -** SQL function: geopoly_within(P1,P2) -** -** Return +2 if P1 and P2 are the same polygon -** Return +1 if P2 is contained within P1 -** Return 0 if any part of P2 is on the outside of P1 -** -*/ -static void geopolyWithinFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); - GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0); - if( p1 && p2 ){ - int x = geopolyOverlap(p1, p2); - if( x<0 ){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0); - } - } - sqlite3_free(p1); - sqlite3_free(p2); -} - -/* Objects used by the overlap algorihm. */ -typedef struct GeoEvent GeoEvent; -typedef struct GeoSegment GeoSegment; -typedef struct GeoOverlap GeoOverlap; -struct GeoEvent { - double x; /* X coordinate at which event occurs */ - int eType; /* 0 for ADD, 1 for REMOVE */ - GeoSegment *pSeg; /* The segment to be added or removed */ - GeoEvent *pNext; /* Next event in the sorted list */ -}; -struct GeoSegment { - double C, B; /* y = C*x + B */ - double y; /* Current y value */ - float y0; /* Initial y value */ - unsigned char side; /* 1 for p1, 2 for p2 */ - unsigned int idx; /* Which segment within the side */ - GeoSegment *pNext; /* Next segment in a list sorted by y */ -}; -struct GeoOverlap { - GeoEvent *aEvent; /* Array of all events */ - GeoSegment *aSegment; /* Array of all segments */ - int nEvent; /* Number of events */ - int nSegment; /* Number of segments */ -}; - -/* -** Add a single segment and its associated events. -*/ -static void geopolyAddOneSegment( - GeoOverlap *p, - GeoCoord x0, - GeoCoord y0, - GeoCoord x1, - GeoCoord y1, - unsigned char side, - unsigned int idx -){ - GeoSegment *pSeg; - GeoEvent *pEvent; - if( x0==x1 ) return; /* Ignore vertical segments */ - if( x0>x1 ){ - GeoCoord t = x0; - x0 = x1; - x1 = t; - t = y0; - y0 = y1; - y1 = t; - } - pSeg = p->aSegment + p->nSegment; - p->nSegment++; - pSeg->C = (y1-y0)/(x1-x0); - pSeg->B = y1 - x1*pSeg->C; - pSeg->y0 = y0; - pSeg->side = side; - pSeg->idx = idx; - pEvent = p->aEvent + p->nEvent; - p->nEvent++; - pEvent->x = x0; - pEvent->eType = 0; - pEvent->pSeg = pSeg; - pEvent = p->aEvent + p->nEvent; - p->nEvent++; - pEvent->x = x1; - pEvent->eType = 1; - pEvent->pSeg = pSeg; -} - - - -/* -** Insert all segments and events for polygon pPoly. -*/ -static void geopolyAddSegments( - GeoOverlap *p, /* Add segments to this Overlap object */ - GeoPoly *pPoly, /* Take all segments from this polygon */ - unsigned char side /* The side of pPoly */ -){ - unsigned int i; - GeoCoord *x; - for(i=0; i<(unsigned)pPoly->nVertex-1; i++){ - x = &GeoX(pPoly,i); - geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i); - } - x = &GeoX(pPoly,i); - geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i); -} - -/* -** Merge two lists of sorted events by X coordinate -*/ -static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){ - GeoEvent head, *pLast; - head.pNext = 0; - pLast = &head; - while( pRight && pLeft ){ - if( pRight->x <= pLeft->x ){ - pLast->pNext = pRight; - pLast = pRight; - pRight = pRight->pNext; - }else{ - pLast->pNext = pLeft; - pLast = pLeft; - pLeft = pLeft->pNext; - } - } - pLast->pNext = pRight ? pRight : pLeft; - return head.pNext; -} - -/* -** Sort an array of nEvent event objects into a list. -*/ -static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){ - int mx = 0; - int i, j; - GeoEvent *p; - GeoEvent *a[50]; - for(i=0; ipNext = 0; - for(j=0; j=mx ) mx = j+1; - } - p = 0; - for(i=0; iy - pLeft->y; - if( r==0.0 ) r = pRight->C - pLeft->C; - if( r<0.0 ){ - pLast->pNext = pRight; - pLast = pRight; - pRight = pRight->pNext; - }else{ - pLast->pNext = pLeft; - pLast = pLeft; - pLeft = pLeft->pNext; - } - } - pLast->pNext = pRight ? pRight : pLeft; - return head.pNext; -} - -/* -** Sort a list of GeoSegments in order of increasing Y and in the event of -** a tie, increasing C (slope). -*/ -static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){ - int mx = 0; - int i; - GeoSegment *p; - GeoSegment *a[50]; - while( pList ){ - p = pList; - pList = pList->pNext; - p->pNext = 0; - for(i=0; i=mx ) mx = i+1; - } - p = 0; - for(i=0; inVertex + p2->nVertex + 2; - GeoOverlap *p; - sqlite3_int64 nByte; - GeoEvent *pThisEvent; - double rX; - int rc = 0; - int needSort = 0; - GeoSegment *pActive = 0; - GeoSegment *pSeg; - unsigned char aOverlap[4]; - - nByte = sizeof(GeoEvent)*nVertex*2 - + sizeof(GeoSegment)*nVertex - + sizeof(GeoOverlap); - p = sqlite3_malloc64( nByte ); - if( p==0 ) return -1; - p->aEvent = (GeoEvent*)&p[1]; - p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2]; - p->nEvent = p->nSegment = 0; - geopolyAddSegments(p, p1, 1); - geopolyAddSegments(p, p2, 2); - pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent); - rX = pThisEvent->x==0.0 ? -1.0 : 0.0; - memset(aOverlap, 0, sizeof(aOverlap)); - while( pThisEvent ){ - if( pThisEvent->x!=rX ){ - GeoSegment *pPrev = 0; - int iMask = 0; - GEODEBUG(("Distinct X: %g\n", pThisEvent->x)); - rX = pThisEvent->x; - if( needSort ){ - GEODEBUG(("SORT\n")); - pActive = geopolySortSegmentsByYAndC(pActive); - needSort = 0; - } - for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ - if( pPrev ){ - if( pPrev->y!=pSeg->y ){ - GEODEBUG(("MASK: %d\n", iMask)); - aOverlap[iMask] = 1; - } - } - iMask ^= pSeg->side; - pPrev = pSeg; - } - pPrev = 0; - for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ - double y = pSeg->C*rX + pSeg->B; - GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y)); - pSeg->y = y; - if( pPrev ){ - if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){ - rc = 1; - GEODEBUG(("Crossing: %d.%d and %d.%d\n", - pPrev->side, pPrev->idx, - pSeg->side, pSeg->idx)); - goto geopolyOverlapDone; - }else if( pPrev->y!=pSeg->y ){ - GEODEBUG(("MASK: %d\n", iMask)); - aOverlap[iMask] = 1; - } - } - iMask ^= pSeg->side; - pPrev = pSeg; - } - } - GEODEBUG(("%s %d.%d C=%g B=%g\n", - pThisEvent->eType ? "RM " : "ADD", - pThisEvent->pSeg->side, pThisEvent->pSeg->idx, - pThisEvent->pSeg->C, - pThisEvent->pSeg->B)); - if( pThisEvent->eType==0 ){ - /* Add a segment */ - pSeg = pThisEvent->pSeg; - pSeg->y = pSeg->y0; - pSeg->pNext = pActive; - pActive = pSeg; - needSort = 1; - }else{ - /* Remove a segment */ - if( pActive==pThisEvent->pSeg ){ - pActive = pActive->pNext; - }else{ - for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){ - if( pSeg->pNext==pThisEvent->pSeg ){ - pSeg->pNext = pSeg->pNext->pNext; - break; - } - } - } - } - pThisEvent = pThisEvent->pNext; - } - if( aOverlap[3]==0 ){ - rc = 0; - }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){ - rc = 3; - }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){ - rc = 2; - }else if( aOverlap[1]==0 && aOverlap[2]==0 ){ - rc = 4; - }else{ - rc = 1; - } - -geopolyOverlapDone: - sqlite3_free(p); - return rc; -} - -/* -** SQL function: geopoly_overlap(P1,P2) -** -** Determine whether or not P1 and P2 overlap. Return value: -** -** 0 The two polygons are disjoint -** 1 They overlap -** 2 P1 is completely contained within P2 -** 3 P2 is completely contained within P1 -** 4 P1 and P2 are the same polygon -** NULL Either P1 or P2 or both are not valid polygons -*/ -static void geopolyOverlapFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0); - GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0); - if( p1 && p2 ){ - int x = geopolyOverlap(p1, p2); - if( x<0 ){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_int(context, x); - } - } - sqlite3_free(p1); - sqlite3_free(p2); -} - -/* -** Enable or disable debugging output -*/ -static void geopolyDebugFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ -#ifdef GEOPOLY_ENABLE_DEBUG - geo_debug = sqlite3_value_int(argv[0]); -#endif -} - -/* -** This function is the implementation of both the xConnect and xCreate -** methods of the geopoly virtual table. -** -** argv[0] -> module name -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> column names... -*/ -static int geopolyInit( - sqlite3 *db, /* Database connection */ - void *pAux, /* One of the RTREE_COORD_* constants */ - int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ - sqlite3_vtab **ppVtab, /* OUT: New virtual table */ - char **pzErr, /* OUT: Error message, if any */ - int isCreate /* True for xCreate, false for xConnect */ -){ - int rc = SQLITE_OK; - Rtree *pRtree; - sqlite3_int64 nDb; /* Length of string argv[1] */ - sqlite3_int64 nName; /* Length of string argv[2] */ - sqlite3_str *pSql; - char *zSql; - int ii; - - sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); - - /* Allocate the sqlite3_vtab structure */ - nDb = strlen(argv[1]); - nName = strlen(argv[2]); - pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2); - if( !pRtree ){ - return SQLITE_NOMEM; - } - memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); - pRtree->nBusy = 1; - pRtree->base.pModule = &rtreeModule; - pRtree->zDb = (char *)&pRtree[1]; - pRtree->zName = &pRtree->zDb[nDb+1]; - pRtree->eCoordType = RTREE_COORD_REAL32; - pRtree->nDim = 2; - pRtree->nDim2 = 4; - memcpy(pRtree->zDb, argv[1], nDb); - memcpy(pRtree->zName, argv[2], nName); - - - /* Create/Connect to the underlying relational database schema. If - ** that is successful, call sqlite3_declare_vtab() to configure - ** the r-tree table schema. - */ - pSql = sqlite3_str_new(db); - sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape"); - pRtree->nAux = 1; /* Add one for _shape */ - pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */ - for(ii=3; iinAux++; - sqlite3_str_appendf(pSql, ",%s", argv[ii]); - } - sqlite3_str_appendf(pSql, ");"); - zSql = sqlite3_str_finish(pSql); - if( !zSql ){ - rc = SQLITE_NOMEM; - }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - } - sqlite3_free(zSql); - if( rc ) goto geopolyInit_fail; - pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; - - /* Figure out the node size to use. */ - rc = getNodeSize(db, pRtree, isCreate, pzErr); - if( rc ) goto geopolyInit_fail; - rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate); - if( rc ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - goto geopolyInit_fail; - } - - *ppVtab = (sqlite3_vtab *)pRtree; - return SQLITE_OK; - -geopolyInit_fail: - if( rc==SQLITE_OK ) rc = SQLITE_ERROR; - assert( *ppVtab==0 ); - assert( pRtree->nBusy==1 ); - rtreeRelease(pRtree); - return rc; -} - - -/* -** GEOPOLY virtual table module xCreate method. -*/ -static int geopolyCreate( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1); -} - -/* -** GEOPOLY virtual table module xConnect method. -*/ -static int geopolyConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0); -} - - -/* -** GEOPOLY virtual table module xFilter method. -** -** Query plans: -** -** 1 rowid lookup -** 2 search for objects overlapping the same bounding box -** that contains polygon argv[0] -** 3 search for objects overlapping the same bounding box -** that contains polygon argv[0] -** 4 full table scan -*/ -static int geopolyFilter( - sqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */ - int idxNum, /* Query plan */ - const char *idxStr, /* Not Used */ - int argc, sqlite3_value **argv /* Parameters to the query plan */ -){ - Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; - RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; - RtreeNode *pRoot = 0; - int rc = SQLITE_OK; - int iCell = 0; - - rtreeReference(pRtree); - - /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ - resetCursor(pCsr); - - pCsr->iStrategy = idxNum; - if( idxNum==1 ){ - /* Special case - lookup by rowid. */ - RtreeNode *pLeaf; /* Leaf on which the required cell resides */ - RtreeSearchPoint *p; /* Search point for the leaf */ - i64 iRowid = sqlite3_value_int64(argv[0]); - i64 iNode = 0; - rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); - if( rc==SQLITE_OK && pLeaf!=0 ){ - p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); - assert( p!=0 ); /* Always returns pCsr->sPoint */ - pCsr->aNode[0] = pLeaf; - p->id = iNode; - p->eWithin = PARTLY_WITHIN; - rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); - p->iCell = (u8)iCell; - RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); - }else{ - pCsr->atEOF = 1; - } - }else{ - /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array - ** with the configured constraints. - */ - rc = nodeAcquire(pRtree, 1, 0, &pRoot); - if( rc==SQLITE_OK && idxNum<=3 ){ - RtreeCoord bbox[4]; - RtreeConstraint *p; - assert( argc==1 ); - geopolyBBox(0, argv[0], bbox, &rc); - if( rc ){ - goto geopoly_filter_end; - } - pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4); - pCsr->nConstraint = 4; - if( p==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4); - memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1)); - if( idxNum==2 ){ - /* Overlap query */ - p->op = 'B'; - p->iCoord = 0; - p->u.rValue = bbox[1].f; - p++; - p->op = 'D'; - p->iCoord = 1; - p->u.rValue = bbox[0].f; - p++; - p->op = 'B'; - p->iCoord = 2; - p->u.rValue = bbox[3].f; - p++; - p->op = 'D'; - p->iCoord = 3; - p->u.rValue = bbox[2].f; - }else{ - /* Within query */ - p->op = 'D'; - p->iCoord = 0; - p->u.rValue = bbox[0].f; - p++; - p->op = 'B'; - p->iCoord = 1; - p->u.rValue = bbox[1].f; - p++; - p->op = 'D'; - p->iCoord = 2; - p->u.rValue = bbox[2].f; - p++; - p->op = 'B'; - p->iCoord = 3; - p->u.rValue = bbox[3].f; - } - } - } - if( rc==SQLITE_OK ){ - RtreeSearchPoint *pNew; - pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1)); - if( pNew==0 ){ - rc = SQLITE_NOMEM; - goto geopoly_filter_end; - } - pNew->id = 1; - pNew->iCell = 0; - pNew->eWithin = PARTLY_WITHIN; - assert( pCsr->bPoint==1 ); - pCsr->aNode[0] = pRoot; - pRoot = 0; - RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:"); - rc = rtreeStepToLeaf(pCsr); - } - } - -geopoly_filter_end: - nodeRelease(pRtree, pRoot); - rtreeRelease(pRtree); - return rc; -} - -/* -** Rtree virtual table module xBestIndex method. There are three -** table scan strategies to choose from (in order from most to -** least desirable): -** -** idxNum idxStr Strategy -** ------------------------------------------------ -** 1 "rowid" Direct lookup by rowid. -** 2 "rtree" R-tree overlap query using geopoly_overlap() -** 3 "rtree" R-tree within query using geopoly_within() -** 4 "fullscan" full-table scan. -** ------------------------------------------------ -*/ -static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ - int ii; - int iRowidTerm = -1; - int iFuncTerm = -1; - int idxNum = 0; - - for(ii=0; iinConstraint; ii++){ - struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; - if( !p->usable ) continue; - if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - iRowidTerm = ii; - break; - } - if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){ - /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap() - ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within(). - ** See geopolyFindFunction() */ - iFuncTerm = ii; - idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2; - } - } - - if( iRowidTerm>=0 ){ - pIdxInfo->idxNum = 1; - pIdxInfo->idxStr = "rowid"; - pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1; - pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1; - pIdxInfo->estimatedCost = 30.0; - pIdxInfo->estimatedRows = 1; - pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE; - return SQLITE_OK; - } - if( iFuncTerm>=0 ){ - pIdxInfo->idxNum = idxNum; - pIdxInfo->idxStr = "rtree"; - pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1; - pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0; - pIdxInfo->estimatedCost = 300.0; - pIdxInfo->estimatedRows = 10; - return SQLITE_OK; - } - pIdxInfo->idxNum = 4; - pIdxInfo->idxStr = "fullscan"; - pIdxInfo->estimatedCost = 3000000.0; - pIdxInfo->estimatedRows = 100000; - return SQLITE_OK; -} - - -/* -** GEOPOLY virtual table module xColumn method. -*/ -static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ - Rtree *pRtree = (Rtree *)cur->pVtab; - RtreeCursor *pCsr = (RtreeCursor *)cur; - RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); - int rc = SQLITE_OK; - RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); - - if( rc ) return rc; - if( p==0 ) return SQLITE_OK; - if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK; - if( i<=pRtree->nAux ){ - if( !pCsr->bAuxValid ){ - if( pCsr->pReadAux==0 ){ - rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0, - &pCsr->pReadAux, 0); - if( rc ) return rc; - } - sqlite3_bind_int64(pCsr->pReadAux, 1, - nodeGetRowid(pRtree, pNode, p->iCell)); - rc = sqlite3_step(pCsr->pReadAux); - if( rc==SQLITE_ROW ){ - pCsr->bAuxValid = 1; - }else{ - sqlite3_reset(pCsr->pReadAux); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - return rc; - } - } - sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2)); - } - return SQLITE_OK; -} - - -/* -** The xUpdate method for GEOPOLY module virtual tables. -** -** For DELETE: -** -** argv[0] = the rowid to be deleted -** -** For INSERT: -** -** argv[0] = SQL NULL -** argv[1] = rowid to insert, or an SQL NULL to select automatically -** argv[2] = _shape column -** argv[3] = first application-defined column.... -** -** For UPDATE: -** -** argv[0] = rowid to modify. Never NULL -** argv[1] = rowid after the change. Never NULL -** argv[2] = new value for _shape -** argv[3] = new value for first application-defined column.... -*/ -static int geopolyUpdate( - sqlite3_vtab *pVtab, - int nData, - sqlite3_value **aData, - sqlite_int64 *pRowid -){ - Rtree *pRtree = (Rtree *)pVtab; - int rc = SQLITE_OK; - RtreeCell cell; /* New cell to insert if nData>1 */ - i64 oldRowid; /* The old rowid */ - int oldRowidValid; /* True if oldRowid is valid */ - i64 newRowid; /* The new rowid */ - int newRowidValid; /* True if newRowid is valid */ - int coordChange = 0; /* Change in coordinates */ - - if( pRtree->nNodeRef ){ - /* Unable to write to the btree while another cursor is reading from it, - ** since the write might do a rebalance which would disrupt the read - ** cursor. */ - return SQLITE_LOCKED_VTAB; - } - rtreeReference(pRtree); - assert(nData>=1); - - oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;; - oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0; - newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL; - newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0; - cell.iRowid = newRowid; - - if( nData>1 /* not a DELETE */ - && (!oldRowidValid /* INSERT */ - || !sqlite3_value_nochange(aData[2]) /* UPDATE _shape */ - || oldRowid!=newRowid) /* Rowid change */ - ){ - geopolyBBox(0, aData[2], cell.aCoord, &rc); - if( rc ){ - if( rc==SQLITE_ERROR ){ - pVtab->zErrMsg = - sqlite3_mprintf("_shape does not contain a valid polygon"); - } - goto geopoly_update_end; - } - coordChange = 1; - - /* If a rowid value was supplied, check if it is already present in - ** the table. If so, the constraint has failed. */ - if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){ - int steprc; - sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); - steprc = sqlite3_step(pRtree->pReadRowid); - rc = sqlite3_reset(pRtree->pReadRowid); - if( SQLITE_ROW==steprc ){ - if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ - rc = rtreeDeleteRowid(pRtree, cell.iRowid); - }else{ - rc = rtreeConstraintError(pRtree, 0); - } - } - } - } - - /* If aData[0] is not an SQL NULL value, it is the rowid of a - ** record to delete from the r-tree table. The following block does - ** just that. - */ - if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){ - rc = rtreeDeleteRowid(pRtree, oldRowid); - } - - /* If the aData[] array contains more than one element, elements - ** (aData[2]..aData[argc-1]) contain a new record to insert into - ** the r-tree structure. - */ - if( rc==SQLITE_OK && nData>1 && coordChange ){ - /* Insert the new record into the r-tree */ - RtreeNode *pLeaf = 0; - if( !newRowidValid ){ - rc = rtreeNewRowid(pRtree, &cell.iRowid); - } - *pRowid = cell.iRowid; - if( rc==SQLITE_OK ){ - rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); - } - if( rc==SQLITE_OK ){ - int rc2; - pRtree->iReinsertHeight = -1; - rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); - rc2 = nodeRelease(pRtree, pLeaf); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - - /* Change the data */ - if( rc==SQLITE_OK && nData>1 ){ - sqlite3_stmt *pUp = pRtree->pWriteAux; - int jj; - int nChange = 0; - sqlite3_bind_int64(pUp, 1, cell.iRowid); - assert( pRtree->nAux>=1 ); - if( sqlite3_value_nochange(aData[2]) ){ - sqlite3_bind_null(pUp, 2); - }else{ - GeoPoly *p = 0; - if( sqlite3_value_type(aData[2])==SQLITE_TEXT - && (p = geopolyFuncParam(0, aData[2], &rc))!=0 - && rc==SQLITE_OK - ){ - sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT); - }else{ - sqlite3_bind_value(pUp, 2, aData[2]); - } - sqlite3_free(p); - nChange = 1; - } - for(jj=1; jjnAux; jj++){ - nChange++; - sqlite3_bind_value(pUp, jj+2, aData[jj+2]); - } - if( nChange ){ - sqlite3_step(pUp); - rc = sqlite3_reset(pUp); - } - } - -geopoly_update_end: - rtreeRelease(pRtree); - return rc; -} - -/* -** Report that geopoly_overlap() is an overloaded function suitable -** for use in xBestIndex. -*/ -static int geopolyFindFunction( - sqlite3_vtab *pVtab, - int nArg, - const char *zName, - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), - void **ppArg -){ - if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){ - *pxFunc = geopolyOverlapFunc; - *ppArg = 0; - return SQLITE_INDEX_CONSTRAINT_FUNCTION; - } - if( sqlite3_stricmp(zName, "geopoly_within")==0 ){ - *pxFunc = geopolyWithinFunc; - *ppArg = 0; - return SQLITE_INDEX_CONSTRAINT_FUNCTION+1; - } - return 0; -} - - -static sqlite3_module geopolyModule = { - 3, /* iVersion */ - geopolyCreate, /* xCreate - create a table */ - geopolyConnect, /* xConnect - connect to an existing table */ - geopolyBestIndex, /* xBestIndex - Determine search strategy */ - rtreeDisconnect, /* xDisconnect - Disconnect from a table */ - rtreeDestroy, /* xDestroy - Drop a table */ - rtreeOpen, /* xOpen - open a cursor */ - rtreeClose, /* xClose - close a cursor */ - geopolyFilter, /* xFilter - configure scan constraints */ - rtreeNext, /* xNext - advance a cursor */ - rtreeEof, /* xEof */ - geopolyColumn, /* xColumn - read data */ - rtreeRowid, /* xRowid - read data */ - geopolyUpdate, /* xUpdate - write data */ - rtreeBeginTransaction, /* xBegin - begin transaction */ - rtreeEndTransaction, /* xSync - sync transaction */ - rtreeEndTransaction, /* xCommit - commit transaction */ - rtreeEndTransaction, /* xRollback - rollback transaction */ - geopolyFindFunction, /* xFindFunction - function overloading */ - rtreeRename, /* xRename - rename the table */ - rtreeSavepoint, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - rtreeShadowName /* xShadowName */ -}; - -static int sqlite3_geopoly_init(sqlite3 *db){ - int rc = SQLITE_OK; - static const struct { - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - signed char nArg; - unsigned char bPure; - const char *zName; - } aFunc[] = { - { geopolyAreaFunc, 1, 1, "geopoly_area" }, - { geopolyBlobFunc, 1, 1, "geopoly_blob" }, - { geopolyJsonFunc, 1, 1, "geopoly_json" }, - { geopolySvgFunc, -1, 1, "geopoly_svg" }, - { geopolyWithinFunc, 2, 1, "geopoly_within" }, - { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" }, - { geopolyOverlapFunc, 2, 1, "geopoly_overlap" }, - { geopolyDebugFunc, 1, 0, "geopoly_debug" }, - { geopolyBBoxFunc, 1, 1, "geopoly_bbox" }, - { geopolyXformFunc, 7, 1, "geopoly_xform" }, - { geopolyRegularFunc, 4, 1, "geopoly_regular" }, - { geopolyCcwFunc, 1, 1, "geopoly_ccw" }, - }; - static const struct { - void (*xStep)(sqlite3_context*,int,sqlite3_value**); - void (*xFinal)(sqlite3_context*); - const char *zName; - } aAgg[] = { - { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" }, - }; - int i; - for(i=0; ixDestructor ) pInfo->xDestructor(pInfo->pContext); - sqlite3_free(p); -} - -/* -** This routine frees the BLOB that is returned by geomCallback(). -*/ -static void rtreeMatchArgFree(void *pArg){ - int i; - RtreeMatchArg *p = (RtreeMatchArg*)pArg; - for(i=0; inParam; i++){ - sqlite3_value_free(p->apSqlParam[i]); - } - sqlite3_free(p); -} - -/* -** Each call to sqlite3_rtree_geometry_callback() or -** sqlite3_rtree_query_callback() creates an ordinary SQLite -** scalar function that is implemented by this routine. -** -** All this function does is construct an RtreeMatchArg object that -** contains the geometry-checking callback routines and a list of -** parameters to this function, then return that RtreeMatchArg object -** as a BLOB. -** -** The R-Tree MATCH operator will read the returned BLOB, deserialize -** the RtreeMatchArg object, and use the RtreeMatchArg object to figure -** out which elements of the R-Tree should be returned by the query. -*/ -static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ - RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx); - RtreeMatchArg *pBlob; - sqlite3_int64 nBlob; - int memErr = 0; - - nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue) - + nArg*sizeof(sqlite3_value*); - pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob); - if( !pBlob ){ - sqlite3_result_error_nomem(ctx); - }else{ - int i; - pBlob->iSize = nBlob; - pBlob->cb = pGeomCtx[0]; - pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg]; - pBlob->nParam = nArg; - for(i=0; iapSqlParam[i] = sqlite3_value_dup(aArg[i]); - if( pBlob->apSqlParam[i]==0 ) memErr = 1; -#ifdef SQLITE_RTREE_INT_ONLY - pBlob->aParam[i] = sqlite3_value_int64(aArg[i]); -#else - pBlob->aParam[i] = sqlite3_value_double(aArg[i]); -#endif - } - if( memErr ){ - sqlite3_result_error_nomem(ctx); - rtreeMatchArgFree(pBlob); - }else{ - sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree); - } - } -} - -/* -** Register a new geometry function for use with the r-tree MATCH operator. -*/ -SQLITE_API int sqlite3_rtree_geometry_callback( - sqlite3 *db, /* Register SQL function on this connection */ - const char *zGeom, /* Name of the new SQL function */ - int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */ - void *pContext /* Extra data associated with the callback */ -){ - RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ - - /* Allocate and populate the context object. */ - pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); - if( !pGeomCtx ) return SQLITE_NOMEM; - pGeomCtx->xGeom = xGeom; - pGeomCtx->xQueryFunc = 0; - pGeomCtx->xDestructor = 0; - pGeomCtx->pContext = pContext; - return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, - (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback - ); -} - -/* -** Register a new 2nd-generation geometry function for use with the -** r-tree MATCH operator. -*/ -SQLITE_API int sqlite3_rtree_query_callback( - sqlite3 *db, /* Register SQL function on this connection */ - const char *zQueryFunc, /* Name of new SQL function */ - int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */ - void *pContext, /* Extra data passed into the callback */ - void (*xDestructor)(void*) /* Destructor for the extra data */ -){ - RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ - - /* Allocate and populate the context object. */ - pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); - if( !pGeomCtx ) return SQLITE_NOMEM; - pGeomCtx->xGeom = 0; - pGeomCtx->xQueryFunc = xQueryFunc; - pGeomCtx->xDestructor = xDestructor; - pGeomCtx->pContext = pContext; - return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, - (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback - ); -} - -#if !SQLITE_CORE -#ifdef _WIN32 -__declspec(dllexport) -#endif -SQLITE_API int sqlite3_rtree_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - SQLITE_EXTENSION_INIT2(pApi) - return sqlite3RtreeInit(db); -} -#endif - -#endif - -/************** End of rtree.c ***********************************************/ -/************** Begin file icu.c *********************************************/ -/* -** 2007 May 6 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $ -** -** This file implements an integration between the ICU library -** ("International Components for Unicode", an open-source library -** for handling unicode data) and SQLite. The integration uses -** ICU to provide the following to SQLite: -** -** * An implementation of the SQL regexp() function (and hence REGEXP -** operator) using the ICU uregex_XX() APIs. -** -** * Implementations of the SQL scalar upper() and lower() functions -** for case mapping. -** -** * Integration of ICU and SQLite collation sequences. -** -** * An implementation of the LIKE operator that uses ICU to -** provide case-independent matching. -*/ - -#if !defined(SQLITE_CORE) \ - || defined(SQLITE_ENABLE_ICU) \ - || defined(SQLITE_ENABLE_ICU_COLLATIONS) - -/* Include ICU headers */ -#include -#include -#include -#include - -/* #include */ - -#ifndef SQLITE_CORE -/* #include "sqlite3ext.h" */ - SQLITE_EXTENSION_INIT1 -#else -/* #include "sqlite3.h" */ -#endif - -/* -** This function is called when an ICU function called from within -** the implementation of an SQL scalar function returns an error. -** -** The scalar function context passed as the first argument is -** loaded with an error message based on the following two args. -*/ -static void icuFunctionError( - sqlite3_context *pCtx, /* SQLite scalar function context */ - const char *zName, /* Name of ICU function that failed */ - UErrorCode e /* Error code returned by ICU function */ -){ - char zBuf[128]; - sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e)); - zBuf[127] = '\0'; - sqlite3_result_error(pCtx, zBuf, -1); -} - -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) - -/* -** 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 - -/* -** Version of sqlite3_free() that is always a function, never a macro. -*/ -static void xFree(void *p){ - sqlite3_free(p); -} - -/* -** This lookup table is used to help decode the first byte of -** a multi-byte UTF8 character. It is copied here from SQLite source -** code file utf8.c. -*/ -static const unsigned char icuUtf8Trans1[] = { - 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 SQLITE_ICU_READ_UTF8(zIn, c) \ - c = *(zIn++); \ - if( c>=0xc0 ){ \ - c = icuUtf8Trans1[c-0xc0]; \ - while( (*zIn & 0xc0)==0x80 ){ \ - c = (c<<6) + (0x3f & *(zIn++)); \ - } \ - } - -#define SQLITE_ICU_SKIP_UTF8(zIn) \ - assert( *zIn ); \ - if( *(zIn++)>=0xc0 ){ \ - while( (*zIn & 0xc0)==0x80 ){zIn++;} \ - } - - -/* -** Compare two UTF-8 strings for equality where the first string is -** a "LIKE" expression. Return true (1) if they are the same and -** false (0) if they are different. -*/ -static int icuLikeCompare( - const uint8_t *zPattern, /* LIKE pattern */ - const uint8_t *zString, /* The UTF-8 string to compare against */ - const UChar32 uEsc /* The escape character */ -){ - static const uint32_t MATCH_ONE = (uint32_t)'_'; - static const uint32_t MATCH_ALL = (uint32_t)'%'; - - int prevEscape = 0; /* True if the previous character was uEsc */ - - while( 1 ){ - - /* Read (and consume) the next character from the input pattern. */ - uint32_t uPattern; - SQLITE_ICU_READ_UTF8(zPattern, uPattern); - if( uPattern==0 ) break; - - /* There are now 4 possibilities: - ** - ** 1. uPattern is an unescaped match-all character "%", - ** 2. uPattern is an unescaped match-one character "_", - ** 3. uPattern is an unescaped escape character, or - ** 4. uPattern is to be handled as an ordinary character - */ - if( uPattern==MATCH_ALL && !prevEscape && uPattern!=(uint32_t)uEsc ){ - /* Case 1. */ - uint8_t c; - - /* Skip any MATCH_ALL or MATCH_ONE characters that follow a - ** MATCH_ALL. For each MATCH_ONE, skip one character in the - ** test string. - */ - while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){ - if( c==MATCH_ONE ){ - if( *zString==0 ) return 0; - SQLITE_ICU_SKIP_UTF8(zString); - } - zPattern++; - } - - if( *zPattern==0 ) return 1; - - while( *zString ){ - if( icuLikeCompare(zPattern, zString, uEsc) ){ - return 1; - } - SQLITE_ICU_SKIP_UTF8(zString); - } - return 0; - - }else if( uPattern==MATCH_ONE && !prevEscape && uPattern!=(uint32_t)uEsc ){ - /* Case 2. */ - if( *zString==0 ) return 0; - SQLITE_ICU_SKIP_UTF8(zString); - - }else if( uPattern==(uint32_t)uEsc && !prevEscape ){ - /* Case 3. */ - prevEscape = 1; - - }else{ - /* Case 4. */ - uint32_t uString; - SQLITE_ICU_READ_UTF8(zString, uString); - uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT); - uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT); - if( uString!=uPattern ){ - return 0; - } - prevEscape = 0; - } - } - - return *zString==0; -} - -/* -** Implementation of the like() SQL function. This function implements -** the build-in LIKE operator. The first argument to the function is the -** pattern and the second argument is the string. So, the SQL statements: -** -** A LIKE B -** -** is implemented as like(B, A). If there is an escape character E, -** -** A LIKE B ESCAPE E -** -** is mapped to like(B, A, E). -*/ -static void icuLikeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *zA = sqlite3_value_text(argv[0]); - const unsigned char *zB = sqlite3_value_text(argv[1]); - UChar32 uEsc = 0; - - /* Limit the length of the LIKE or GLOB pattern to avoid problems - ** of deep recursion and N*N behavior in patternCompare(). - */ - if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ - sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); - return; - } - - - if( argc==3 ){ - /* The escape character string must consist of a single UTF-8 character. - ** Otherwise, return an error. - */ - int nE= sqlite3_value_bytes(argv[2]); - const unsigned char *zE = sqlite3_value_text(argv[2]); - int i = 0; - if( zE==0 ) return; - U8_NEXT(zE, i, nE, uEsc); - if( i!=nE){ - sqlite3_result_error(context, - "ESCAPE expression must be a single character", -1); - return; - } - } - - if( zA && zB ){ - sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc)); - } -} - -/* -** Function to delete compiled regexp objects. Registered as -** a destructor function with sqlite3_set_auxdata(). -*/ -static void icuRegexpDelete(void *p){ - URegularExpression *pExpr = (URegularExpression *)p; - uregex_close(pExpr); -} - -/* -** Implementation of SQLite REGEXP operator. This scalar function takes -** two arguments. The first is a regular expression pattern to compile -** the second is a string to match against that pattern. If either -** argument is an SQL NULL, then NULL Is returned. Otherwise, the result -** is 1 if the string matches the pattern, or 0 otherwise. -** -** SQLite maps the regexp() function to the regexp() operator such -** that the following two are equivalent: -** -** zString REGEXP zPattern -** regexp(zPattern, zString) -** -** Uses the following ICU regexp APIs: -** -** uregex_open() -** uregex_matches() -** uregex_close() -*/ -static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){ - UErrorCode status = U_ZERO_ERROR; - URegularExpression *pExpr; - UBool res; - const UChar *zString = sqlite3_value_text16(apArg[1]); - - (void)nArg; /* Unused parameter */ - - /* If the left hand side of the regexp operator is NULL, - ** then the result is also NULL. - */ - if( !zString ){ - return; - } - - pExpr = sqlite3_get_auxdata(p, 0); - if( !pExpr ){ - const UChar *zPattern = sqlite3_value_text16(apArg[0]); - if( !zPattern ){ - return; - } - pExpr = uregex_open(zPattern, -1, 0, 0, &status); - - if( U_SUCCESS(status) ){ - sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete); - }else{ - assert(!pExpr); - icuFunctionError(p, "uregex_open", status); - return; - } - } - - /* Configure the text that the regular expression operates on. */ - uregex_setText(pExpr, zString, -1, &status); - if( !U_SUCCESS(status) ){ - icuFunctionError(p, "uregex_setText", status); - return; - } - - /* Attempt the match */ - res = uregex_matches(pExpr, 0, &status); - if( !U_SUCCESS(status) ){ - icuFunctionError(p, "uregex_matches", status); - return; - } - - /* Set the text that the regular expression operates on to a NULL - ** pointer. This is not really necessary, but it is tidier than - ** leaving the regular expression object configured with an invalid - ** pointer after this function returns. - */ - uregex_setText(pExpr, 0, 0, &status); - - /* Return 1 or 0. */ - sqlite3_result_int(p, res ? 1 : 0); -} - -/* -** Implementations of scalar functions for case mapping - upper() and -** lower(). Function upper() converts its input to upper-case (ABC). -** Function lower() converts to lower-case (abc). -** -** ICU provides two types of case mapping, "general" case mapping and -** "language specific". Refer to ICU documentation for the differences -** between the two. -** -** To utilise "general" case mapping, the upper() or lower() scalar -** functions are invoked with one argument: -** -** upper('ABC') -> 'abc' -** lower('abc') -> 'ABC' -** -** To access ICU "language specific" case mapping, upper() or lower() -** should be invoked with two arguments. The second argument is the name -** of the locale to use. Passing an empty string ("") or SQL NULL value -** as the second argument is the same as invoking the 1 argument version -** of upper() or lower(). -** -** lower('I', 'en_us') -> 'i' -** lower('I', 'tr_tr') -> '\u131' (small dotless i) -** -** http://www.icu-project.org/userguide/posix.html#case_mappings -*/ -static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ - const UChar *zInput; /* Pointer to input string */ - UChar *zOutput = 0; /* Pointer to output buffer */ - int nInput; /* Size of utf-16 input string in bytes */ - int nOut; /* Size of output buffer in bytes */ - int cnt; - int bToUpper; /* True for toupper(), false for tolower() */ - UErrorCode status; - const char *zLocale = 0; - - assert(nArg==1 || nArg==2); - bToUpper = (sqlite3_user_data(p)!=0); - if( nArg==2 ){ - zLocale = (const char *)sqlite3_value_text(apArg[1]); - } - - zInput = sqlite3_value_text16(apArg[0]); - if( !zInput ){ - return; - } - nOut = nInput = sqlite3_value_bytes16(apArg[0]); - if( nOut==0 ){ - sqlite3_result_text16(p, "", 0, SQLITE_STATIC); - return; - } - - for(cnt=0; cnt<2; cnt++){ - UChar *zNew = sqlite3_realloc(zOutput, nOut); - if( zNew==0 ){ - sqlite3_free(zOutput); - sqlite3_result_error_nomem(p); - return; - } - zOutput = zNew; - status = U_ZERO_ERROR; - if( bToUpper ){ - nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); - }else{ - nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); - } - - if( U_SUCCESS(status) ){ - sqlite3_result_text16(p, zOutput, nOut, xFree); - }else if( status==U_BUFFER_OVERFLOW_ERROR ){ - assert( cnt==0 ); - continue; - }else{ - icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status); - } - return; - } - assert( 0 ); /* Unreachable */ -} - -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */ - -/* -** Collation sequence destructor function. The pCtx argument points to -** a UCollator structure previously allocated using ucol_open(). -*/ -static void icuCollationDel(void *pCtx){ - UCollator *p = (UCollator *)pCtx; - ucol_close(p); -} - -/* -** Collation sequence comparison function. The pCtx argument points to -** a UCollator structure previously allocated using ucol_open(). -*/ -static int icuCollationColl( - void *pCtx, - int nLeft, - const void *zLeft, - int nRight, - const void *zRight -){ - UCollationResult res; - UCollator *p = (UCollator *)pCtx; - res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2); - switch( res ){ - case UCOL_LESS: return -1; - case UCOL_GREATER: return +1; - case UCOL_EQUAL: return 0; - } - assert(!"Unexpected return value from ucol_strcoll()"); - return 0; -} - -/* -** Implementation of the scalar function icu_load_collation(). -** -** This scalar function is used to add ICU collation based collation -** types to an SQLite database connection. It is intended to be called -** as follows: -** -** SELECT icu_load_collation(, ); -** -** Where is a string containing an ICU locale identifier (i.e. -** "en_AU", "tr_TR" etc.) and is the name of the -** collation sequence to create. -*/ -static void icuLoadCollation( - sqlite3_context *p, - int nArg, - sqlite3_value **apArg -){ - sqlite3 *db = (sqlite3 *)sqlite3_user_data(p); - UErrorCode status = U_ZERO_ERROR; - const char *zLocale; /* Locale identifier - (eg. "jp_JP") */ - const char *zName; /* SQL Collation sequence name (eg. "japanese") */ - UCollator *pUCollator; /* ICU library collation object */ - int rc; /* Return code from sqlite3_create_collation_x() */ - - assert(nArg==2); - (void)nArg; /* Unused parameter */ - zLocale = (const char *)sqlite3_value_text(apArg[0]); - zName = (const char *)sqlite3_value_text(apArg[1]); - - if( !zLocale || !zName ){ - return; - } - - pUCollator = ucol_open(zLocale, &status); - if( !U_SUCCESS(status) ){ - icuFunctionError(p, "ucol_open", status); - return; - } - assert(p); - - rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, - icuCollationColl, icuCollationDel - ); - if( rc!=SQLITE_OK ){ - ucol_close(pUCollator); - sqlite3_result_error(p, "Error registering collation function", -1); - } -} - -/* -** Register the ICU extension functions with database db. -*/ -SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){ -# define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS) - static const struct IcuScalar { - const char *zName; /* Function name */ - unsigned char nArg; /* Number of arguments */ - unsigned int enc; /* Optimal text encoding */ - unsigned char iContext; /* sqlite3_user_data() context */ - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } scalars[] = { - {"icu_load_collation",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation}, -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) - {"regexp", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS, 0, icuRegexpFunc}, - {"lower", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, - {"lower", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, - {"upper", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, - {"upper", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, - {"lower", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, - {"lower", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16}, - {"upper", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, - {"upper", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16}, - {"like", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc}, - {"like", 3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc}, -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */ - }; - int rc = SQLITE_OK; - int i; - - for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){ - const struct IcuScalar *p = &scalars[i]; - rc = sqlite3_create_function( - db, p->zName, p->nArg, p->enc, - p->iContext ? (void*)db : (void*)0, - p->xFunc, 0, 0 - ); - } - - return rc; -} - -#if !SQLITE_CORE -#ifdef _WIN32 -__declspec(dllexport) -#endif -SQLITE_API int sqlite3_icu_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - SQLITE_EXTENSION_INIT2(pApi) - return sqlite3IcuInit(db); -} -#endif - -#endif - -/************** End of icu.c *************************************************/ -/************** Begin file fts3_icu.c ****************************************/ -/* -** 2007 June 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file implements a tokenizer for fts3 based on the ICU library. -*/ -/* #include "fts3Int.h" */ -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#ifdef SQLITE_ENABLE_ICU - -/* #include */ -/* #include */ -/* #include "fts3_tokenizer.h" */ - -#include -/* #include */ -/* #include */ -#include - -typedef struct IcuTokenizer IcuTokenizer; -typedef struct IcuCursor IcuCursor; - -struct IcuTokenizer { - sqlite3_tokenizer base; - char *zLocale; -}; - -struct IcuCursor { - sqlite3_tokenizer_cursor base; - - UBreakIterator *pIter; /* ICU break-iterator object */ - int nChar; /* Number of UChar elements in pInput */ - UChar *aChar; /* Copy of input using utf-16 encoding */ - int *aOffset; /* Offsets of each character in utf-8 input */ - - int nBuffer; - char *zBuffer; - - int iToken; -}; - -/* -** Create a new tokenizer instance. -*/ -static int icuCreate( - int argc, /* Number of entries in argv[] */ - const char * const *argv, /* Tokenizer creation arguments */ - sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ -){ - IcuTokenizer *p; - int n = 0; - - if( argc>0 ){ - n = strlen(argv[0])+1; - } - p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n); - if( !p ){ - return SQLITE_NOMEM; - } - memset(p, 0, sizeof(IcuTokenizer)); - - if( n ){ - p->zLocale = (char *)&p[1]; - memcpy(p->zLocale, argv[0], n); - } - - *ppTokenizer = (sqlite3_tokenizer *)p; - - return SQLITE_OK; -} - -/* -** Destroy a tokenizer -*/ -static int icuDestroy(sqlite3_tokenizer *pTokenizer){ - IcuTokenizer *p = (IcuTokenizer *)pTokenizer; - sqlite3_free(p); - return SQLITE_OK; -} - -/* -** Prepare to begin tokenizing a particular string. The input -** string to be tokenized is pInput[0..nBytes-1]. A cursor -** used to incrementally tokenize this string is returned in -** *ppCursor. -*/ -static int icuOpen( - sqlite3_tokenizer *pTokenizer, /* The tokenizer */ - const char *zInput, /* Input string */ - int nInput, /* Length of zInput in bytes */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ -){ - IcuTokenizer *p = (IcuTokenizer *)pTokenizer; - IcuCursor *pCsr; - - const int32_t opt = U_FOLD_CASE_DEFAULT; - UErrorCode status = U_ZERO_ERROR; - int nChar; - - UChar32 c; - int iInput = 0; - int iOut = 0; - - *ppCursor = 0; - - if( zInput==0 ){ - nInput = 0; - zInput = ""; - }else if( nInput<0 ){ - nInput = strlen(zInput); - } - nChar = nInput+1; - pCsr = (IcuCursor *)sqlite3_malloc64( - sizeof(IcuCursor) + /* IcuCursor */ - ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */ - (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ - ); - if( !pCsr ){ - return SQLITE_NOMEM; - } - memset(pCsr, 0, sizeof(IcuCursor)); - pCsr->aChar = (UChar *)&pCsr[1]; - pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3]; - - pCsr->aOffset[iOut] = iInput; - U8_NEXT(zInput, iInput, nInput, c); - while( c>0 ){ - int isError = 0; - c = u_foldCase(c, opt); - U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); - if( isError ){ - sqlite3_free(pCsr); - return SQLITE_ERROR; - } - pCsr->aOffset[iOut] = iInput; - - if( iInputpIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); - if( !U_SUCCESS(status) ){ - sqlite3_free(pCsr); - return SQLITE_ERROR; - } - pCsr->nChar = iOut; - - ubrk_first(pCsr->pIter); - *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; - return SQLITE_OK; -} - -/* -** Close a tokenization cursor previously opened by a call to icuOpen(). -*/ -static int icuClose(sqlite3_tokenizer_cursor *pCursor){ - IcuCursor *pCsr = (IcuCursor *)pCursor; - ubrk_close(pCsr->pIter); - sqlite3_free(pCsr->zBuffer); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Extract the next token from a tokenization cursor. -*/ -static int icuNext( - sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ - const char **ppToken, /* OUT: *ppToken is the token text */ - int *pnBytes, /* OUT: Number of bytes in token */ - int *piStartOffset, /* OUT: Starting offset of token */ - int *piEndOffset, /* OUT: Ending offset of token */ - int *piPosition /* OUT: Position integer of token */ -){ - IcuCursor *pCsr = (IcuCursor *)pCursor; - - int iStart = 0; - int iEnd = 0; - int nByte = 0; - - while( iStart==iEnd ){ - UChar32 c; - - iStart = ubrk_current(pCsr->pIter); - iEnd = ubrk_next(pCsr->pIter); - if( iEnd==UBRK_DONE ){ - return SQLITE_DONE; - } - - while( iStartaChar, iWhite, pCsr->nChar, c); - if( u_isspace(c) ){ - iStart = iWhite; - }else{ - break; - } - } - assert(iStart<=iEnd); - } - - do { - UErrorCode status = U_ZERO_ERROR; - if( nByte ){ - char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); - if( !zNew ){ - return SQLITE_NOMEM; - } - pCsr->zBuffer = zNew; - pCsr->nBuffer = nByte; - } - - u_strToUTF8( - pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */ - &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */ - &status /* Output success/failure */ - ); - } while( nByte>pCsr->nBuffer ); - - *ppToken = pCsr->zBuffer; - *pnBytes = nByte; - *piStartOffset = pCsr->aOffset[iStart]; - *piEndOffset = pCsr->aOffset[iEnd]; - *piPosition = pCsr->iToken++; - - return SQLITE_OK; -} - -/* -** The set of routines that implement the simple tokenizer -*/ -static const sqlite3_tokenizer_module icuTokenizerModule = { - 0, /* iVersion */ - icuCreate, /* xCreate */ - icuDestroy, /* xCreate */ - icuOpen, /* xOpen */ - icuClose, /* xClose */ - icuNext, /* xNext */ - 0, /* xLanguageid */ -}; - -/* -** Set *ppModule to point at the implementation of the ICU tokenizer. -*/ -SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( - sqlite3_tokenizer_module const**ppModule -){ - *ppModule = &icuTokenizerModule; -} - -#endif /* defined(SQLITE_ENABLE_ICU) */ -#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ - -/************** End of fts3_icu.c ********************************************/ -/************** Begin file sqlite3rbu.c **************************************/ -/* -** 2014 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. -** -************************************************************************* -** -** -** OVERVIEW -** -** The RBU extension requires that the RBU update be packaged as an -** SQLite database. The tables it expects to find are described in -** sqlite3rbu.h. Essentially, for each table xyz in the target database -** that the user wishes to write to, a corresponding data_xyz table is -** created in the RBU database and populated with one row for each row to -** update, insert or delete from the target table. -** -** The update proceeds in three stages: -** -** 1) The database is updated. The modified database pages are written -** to a *-oal file. A *-oal file is just like a *-wal file, except -** that it is named "-oal" instead of "-wal". -** Because regular SQLite clients do not look for file named -** "-oal", they go on using the original database in -** rollback mode while the *-oal file is being generated. -** -** During this stage RBU does not update the database by writing -** directly to the target tables. Instead it creates "imposter" -** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses -** to update each b-tree individually. All updates required by each -** b-tree are completed before moving on to the next, and all -** updates are done in sorted key order. -** -** 2) The "-oal" file is moved to the equivalent "-wal" -** location using a call to rename(2). Before doing this the RBU -** module takes an EXCLUSIVE lock on the database file, ensuring -** that there are no other active readers. -** -** Once the EXCLUSIVE lock is released, any other database readers -** detect the new *-wal file and read the database in wal mode. At -** this point they see the new version of the database - including -** the updates made as part of the RBU update. -** -** 3) The new *-wal file is checkpointed. This proceeds in the same way -** as a regular database checkpoint, except that a single frame is -** checkpointed each time sqlite3rbu_step() is called. If the RBU -** handle is closed before the entire *-wal file is checkpointed, -** the checkpoint progress is saved in the RBU database and the -** checkpoint can be resumed by another RBU client at some point in -** the future. -** -** POTENTIAL PROBLEMS -** -** The rename() call might not be portable. And RBU is not currently -** syncing the directory after renaming the file. -** -** When state is saved, any commit to the *-oal file and the commit to -** the RBU update database are not atomic. So if the power fails at the -** wrong moment they might get out of sync. As the main database will be -** committed before the RBU update database this will likely either just -** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE -** constraint violations). -** -** If some client does modify the target database mid RBU update, or some -** other error occurs, the RBU extension will keep throwing errors. It's -** not really clear how to get out of this state. The system could just -** by delete the RBU update database and *-oal file and have the device -** download the update again and start over. -** -** At present, for an UPDATE, both the new.* and old.* records are -** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all -** fields are collected. This means we're probably writing a lot more -** data to disk when saving the state of an ongoing update to the RBU -** update database than is strictly necessary. -** -*/ - -/* #include */ -/* #include */ -/* #include */ - -/* #include "sqlite3.h" */ - -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) -/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/ -/************** Begin file sqlite3rbu.h **************************************/ -/* -** 2014 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. -** -************************************************************************* -** -** This file contains the public interface for the RBU extension. -*/ - -/* -** SUMMARY -** -** Writing a transaction containing a large number of operations on -** b-tree indexes that are collectively larger than the available cache -** memory can be very inefficient. -** -** The problem is that in order to update a b-tree, the leaf page (at least) -** containing the entry being inserted or deleted must be modified. If the -** working set of leaves is larger than the available cache memory, then a -** single leaf that is modified more than once as part of the transaction -** may be loaded from or written to the persistent media multiple times. -** Additionally, because the index updates are likely to be applied in -** random order, access to pages within the database is also likely to be in -** random order, which is itself quite inefficient. -** -** One way to improve the situation is to sort the operations on each index -** by index key before applying them to the b-tree. This leads to an IO -** pattern that resembles a single linear scan through the index b-tree, -** and all but guarantees each modified leaf page is loaded and stored -** exactly once. SQLite uses this trick to improve the performance of -** CREATE INDEX commands. This extension allows it to be used to improve -** the performance of large transactions on existing databases. -** -** Additionally, this extension allows the work involved in writing the -** large transaction to be broken down into sub-transactions performed -** sequentially by separate processes. This is useful if the system cannot -** guarantee that a single update process will run for long enough to apply -** the entire update, for example because the update is being applied on a -** mobile device that is frequently rebooted. Even after the writer process -** has committed one or more sub-transactions, other database clients continue -** to read from the original database snapshot. In other words, partially -** applied transactions are not visible to other clients. -** -** "RBU" stands for "Resumable Bulk Update". As in a large database update -** transmitted via a wireless network to a mobile device. A transaction -** applied using this extension is hence refered to as an "RBU update". -** -** -** LIMITATIONS -** -** An "RBU update" transaction is subject to the following limitations: -** -** * The transaction must consist of INSERT, UPDATE and DELETE operations -** only. -** -** * INSERT statements may not use any default values. -** -** * UPDATE and DELETE statements must identify their target rows by -** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY -** KEY fields may not be updated or deleted. If the table being written -** has no PRIMARY KEY, affected rows must be identified by rowid. -** -** * UPDATE statements may not modify PRIMARY KEY columns. -** -** * No triggers will be fired. -** -** * No foreign key violations are detected or reported. -** -** * CHECK constraints are not enforced. -** -** * No constraint handling mode except for "OR ROLLBACK" is supported. -** -** -** PREPARATION -** -** An "RBU update" is stored as a separate SQLite database. A database -** containing an RBU update is an "RBU database". For each table in the -** target database to be updated, the RBU database should contain a table -** named "data_" containing the same set of columns as the -** target table, and one more - "rbu_control". The data_% table should -** have no PRIMARY KEY or UNIQUE constraints, but each column should have -** the same type as the corresponding column in the target database. -** The "rbu_control" column should have no type at all. For example, if -** the target database contains: -** -** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE); -** -** Then the RBU database should contain: -** -** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control); -** -** The order of the columns in the data_% table does not matter. -** -** Instead of a regular table, the RBU database may also contain virtual -** tables or view named using the data_ naming scheme. -** -** Instead of the plain data_ naming scheme, RBU database tables -** may also be named data_, where is any sequence -** of zero or more numeric characters (0-9). This can be significant because -** tables within the RBU database are always processed in order sorted by -** name. By judicious selection of the portion of the names -** of the RBU tables the user can therefore control the order in which they -** are processed. This can be useful, for example, to ensure that "external -** content" FTS4 tables are updated before their underlying content tables. -** -** If the target database table is a virtual table or a table that has no -** PRIMARY KEY declaration, the data_% table must also contain a column -** named "rbu_rowid". This column is mapped to the tables implicit primary -** key column - "rowid". Virtual tables for which the "rowid" column does -** not function like a primary key value cannot be updated using RBU. For -** example, if the target db contains either of the following: -** -** CREATE VIRTUAL TABLE x1 USING fts3(a, b); -** CREATE TABLE x1(a, b) -** -** then the RBU database should contain: -** -** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control); -** -** All non-hidden columns (i.e. all columns matched by "SELECT *") of the -** target table must be present in the input table. For virtual tables, -** hidden columns are optional - they are updated by RBU if present in -** the input table, or not otherwise. For example, to write to an fts4 -** table with a hidden languageid column such as: -** -** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid'); -** -** Either of the following input table schemas may be used: -** -** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control); -** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control); -** -** For each row to INSERT into the target database as part of the RBU -** update, the corresponding data_% table should contain a single record -** with the "rbu_control" column set to contain integer value 0. The -** other columns should be set to the values that make up the new record -** to insert. -** -** If the target database table has an INTEGER PRIMARY KEY, it is not -** possible to insert a NULL value into the IPK column. Attempting to -** do so results in an SQLITE_MISMATCH error. -** -** For each row to DELETE from the target database as part of the RBU -** update, the corresponding data_% table should contain a single record -** with the "rbu_control" column set to contain integer value 1. The -** real primary key values of the row to delete should be stored in the -** corresponding columns of the data_% table. The values stored in the -** other columns are not used. -** -** For each row to UPDATE from the target database as part of the RBU -** update, the corresponding data_% table should contain a single record -** with the "rbu_control" column set to contain a value of type text. -** The real primary key values identifying the row to update should be -** stored in the corresponding columns of the data_% table row, as should -** the new values of all columns being update. The text value in the -** "rbu_control" column must contain the same number of characters as -** there are columns in the target database table, and must consist entirely -** of 'x' and '.' characters (or in some special cases 'd' - see below). For -** each column that is being updated, the corresponding character is set to -** 'x'. For those that remain as they are, the corresponding character of the -** rbu_control value should be set to '.'. For example, given the tables -** above, the update statement: -** -** UPDATE t1 SET c = 'usa' WHERE a = 4; -** -** is represented by the data_t1 row created by: -** -** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x'); -** -** Instead of an 'x' character, characters of the rbu_control value specified -** for UPDATEs may also be set to 'd'. In this case, instead of updating the -** target table with the value stored in the corresponding data_% column, the -** user-defined SQL function "rbu_delta()" is invoked and the result stored in -** the target table column. rbu_delta() is invoked with two arguments - the -** original value currently stored in the target table column and the -** value specified in the data_xxx table. -** -** For example, this row: -** -** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d'); -** -** is similar to an UPDATE statement such as: -** -** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4; -** -** Finally, if an 'f' character appears in place of a 'd' or 's' in an -** ota_control string, the contents of the data_xxx table column is assumed -** to be a "fossil delta" - a patch to be applied to a blob value in the -** format used by the fossil source-code management system. In this case -** the existing value within the target database table must be of type BLOB. -** It is replaced by the result of applying the specified fossil delta to -** itself. -** -** If the target database table is a virtual table or a table with no PRIMARY -** KEY, the rbu_control value should not include a character corresponding -** to the rbu_rowid value. For example, this: -** -** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) -** VALUES(NULL, 'usa', 12, '.x'); -** -** causes a result similar to: -** -** UPDATE ft1 SET b = 'usa' WHERE rowid = 12; -** -** The data_xxx tables themselves should have no PRIMARY KEY declarations. -** However, RBU is more efficient if reading the rows in from each data_xxx -** table in "rowid" order is roughly the same as reading them sorted by -** the PRIMARY KEY of the corresponding target database table. In other -** words, rows should be sorted using the destination table PRIMARY KEY -** fields before they are inserted into the data_xxx tables. -** -** USAGE -** -** The API declared below allows an application to apply an RBU update -** stored on disk to an existing target database. Essentially, the -** application: -** -** 1) Opens an RBU handle using the sqlite3rbu_open() function. -** -** 2) Registers any required virtual table modules with the database -** handle returned by sqlite3rbu_db(). Also, if required, register -** the rbu_delta() implementation. -** -** 3) Calls the sqlite3rbu_step() function one or more times on -** the new handle. Each call to sqlite3rbu_step() performs a single -** b-tree operation, so thousands of calls may be required to apply -** a complete update. -** -** 4) Calls sqlite3rbu_close() to close the RBU update handle. If -** sqlite3rbu_step() has been called enough times to completely -** apply the update to the target database, then the RBU database -** is marked as fully applied. Otherwise, the state of the RBU -** update application is saved in the RBU database for later -** resumption. -** -** See comments below for more detail on APIs. -** -** If an update is only partially applied to the target database by the -** time sqlite3rbu_close() is called, various state information is saved -** within the RBU database. This allows subsequent processes to automatically -** resume the RBU update from where it left off. -** -** To remove all RBU extension state information, returning an RBU database -** to its original contents, it is sufficient to drop all tables that begin -** with the prefix "rbu_" -** -** DATABASE LOCKING -** -** An RBU update may not be applied to a database in WAL mode. Attempting -** to do so is an error (SQLITE_ERROR). -** -** While an RBU handle is open, a SHARED lock may be held on the target -** database file. This means it is possible for other clients to read the -** database, but not to write it. -** -** If an RBU update is started and then suspended before it is completed, -** then an external client writes to the database, then attempting to resume -** the suspended RBU update is also an error (SQLITE_BUSY). -*/ - -#ifndef _SQLITE3RBU_H -#define _SQLITE3RBU_H - -/* #include "sqlite3.h" ** Required for error code definitions ** */ - -#if 0 -extern "C" { -#endif - -typedef struct sqlite3rbu sqlite3rbu; - -/* -** Open an RBU handle. -** -** Argument zTarget is the path to the target database. Argument zRbu is -** the path to the RBU database. Each call to this function must be matched -** by a call to sqlite3rbu_close(). When opening the databases, RBU passes -** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget -** or zRbu begin with "file:", it will be interpreted as an SQLite -** database URI, not a regular file name. -** -** If the zState argument is passed a NULL value, the RBU extension stores -** the current state of the update (how many rows have been updated, which -** indexes are yet to be updated etc.) within the RBU database itself. This -** can be convenient, as it means that the RBU application does not need to -** organize removing a separate state file after the update is concluded. -** Or, if zState is non-NULL, it must be a path to a database file in which -** the RBU extension can store the state of the update. -** -** When resuming an RBU update, the zState argument must be passed the same -** value as when the RBU update was started. -** -** Once the RBU update is finished, the RBU extension does not -** automatically remove any zState database file, even if it created it. -** -** By default, RBU uses the default VFS to access the files on disk. To -** use a VFS other than the default, an SQLite "file:" URI containing a -** "vfs=..." option may be passed as the zTarget option. -** -** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of -** SQLite's built-in VFSs, including the multiplexor VFS. However it does -** not work out of the box with zipvfs. Refer to the comment describing -** the zipvfs_create_vfs() API below for details on using RBU with zipvfs. -*/ -SQLITE_API sqlite3rbu *sqlite3rbu_open( - const char *zTarget, - const char *zRbu, - const char *zState -); - -/* -** Open an RBU handle to perform an RBU vacuum on database file zTarget. -** An RBU vacuum is similar to SQLite's built-in VACUUM command, except -** that it can be suspended and resumed like an RBU update. -** -** The second argument to this function identifies a database in which -** to store the state of the RBU vacuum operation if it is suspended. The -** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum -** operation, the state database should either not exist or be empty -** (contain no tables). If an RBU vacuum is suspended by calling -** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has -** returned SQLITE_DONE, the vacuum state is stored in the state database. -** The vacuum can be resumed by calling this function to open a new RBU -** handle specifying the same target and state databases. -** -** If the second argument passed to this function is NULL, then the -** name of the state database is "-vacuum", where -** is the name of the target database file. In this case, on UNIX, if the -** state database is not already present in the file-system, it is created -** with the same permissions as the target db is made. -** -** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the -** state database ends with "-vactmp". This name is reserved for internal -** use. -** -** This function does not delete the state database after an RBU vacuum -** is completed, even if it created it. However, if the call to -** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents -** of the state tables within the state database are zeroed. This way, -** the next call to sqlite3rbu_vacuum() opens a handle that starts a -** new RBU vacuum operation. -** -** As with sqlite3rbu_open(), Zipvfs users should rever to the comment -** describing the sqlite3rbu_create_vfs() API function below for -** a description of the complications associated with using RBU with -** zipvfs databases. -*/ -SQLITE_API sqlite3rbu *sqlite3rbu_vacuum( - const char *zTarget, - const char *zState -); - -/* -** Configure a limit for the amount of temp space that may be used by -** the RBU handle passed as the first argument. The new limit is specified -** in bytes by the second parameter. If it is positive, the limit is updated. -** If the second parameter to this function is passed zero, then the limit -** is removed entirely. If the second parameter is negative, the limit is -** not modified (this is useful for querying the current limit). -** -** In all cases the returned value is the current limit in bytes (zero -** indicates unlimited). -** -** If the temp space limit is exceeded during operation, an SQLITE_FULL -** error is returned. -*/ -SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64); - -/* -** Return the current amount of temp file space, in bytes, currently used by -** the RBU handle passed as the only argument. -*/ -SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*); - -/* -** Internally, each RBU connection uses a separate SQLite database -** connection to access the target and rbu update databases. This -** API allows the application direct access to these database handles. -** -** The first argument passed to this function must be a valid, open, RBU -** handle. The second argument should be passed zero to access the target -** database handle, or non-zero to access the rbu update database handle. -** Accessing the underlying database handles may be useful in the -** following scenarios: -** -** * If any target tables are virtual tables, it may be necessary to -** call sqlite3_create_module() on the target database handle to -** register the required virtual table implementations. -** -** * If the data_xxx tables in the RBU source database are virtual -** tables, the application may need to call sqlite3_create_module() on -** the rbu update db handle to any required virtual table -** implementations. -** -** * If the application uses the "rbu_delta()" feature described above, -** it must use sqlite3_create_function() or similar to register the -** rbu_delta() implementation with the target database handle. -** -** If an error has occurred, either while opening or stepping the RBU object, -** this function may return NULL. The error code and message may be collected -** when sqlite3rbu_close() is called. -** -** Database handles returned by this function remain valid until the next -** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db(). -*/ -SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu); - -/* -** Do some work towards applying the RBU update to the target db. -** -** Return SQLITE_DONE if the update has been completely applied, or -** SQLITE_OK if no error occurs but there remains work to do to apply -** the RBU update. If an error does occur, some other error code is -** returned. -** -** Once a call to sqlite3rbu_step() has returned a value other than -** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops -** that immediately return the same value. -*/ -SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu); - -/* -** Force RBU to save its state to disk. -** -** If a power failure or application crash occurs during an update, following -** system recovery RBU may resume the update from the point at which the state -** was last saved. In other words, from the most recent successful call to -** sqlite3rbu_close() or this function. -** -** SQLITE_OK is returned if successful, or an SQLite error code otherwise. -*/ -SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu); - -/* -** Close an RBU handle. -** -** If the RBU update has been completely applied, mark the RBU database -** as fully applied. Otherwise, assuming no error has occurred, save the -** current state of the RBU update appliation to the RBU database. -** -** If an error has already occurred as part of an sqlite3rbu_step() -** or sqlite3rbu_open() call, or if one occurs within this function, an -** SQLite error code is returned. Additionally, if pzErrmsg is not NULL, -** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted -** English language error message. It is the responsibility of the caller to -** eventually free any such buffer using sqlite3_free(). -** -** Otherwise, if no error occurs, this function returns SQLITE_OK if the -** update has been partially applied, or SQLITE_DONE if it has been -** completely applied. -*/ -SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg); - -/* -** Return the total number of key-value operations (inserts, deletes or -** updates) that have been performed on the target database since the -** current RBU update was started. -*/ -SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu); - -/* -** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) -** progress indications for the two stages of an RBU update. This API may -** be useful for driving GUI progress indicators and similar. -** -** An RBU update is divided into two stages: -** -** * Stage 1, in which changes are accumulated in an oal/wal file, and -** * Stage 2, in which the contents of the wal file are copied into the -** main database. -** -** The update is visible to non-RBU clients during stage 2. During stage 1 -** non-RBU reader clients may see the original database. -** -** If this API is called during stage 2 of the update, output variable -** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo) -** to a value between 0 and 10000 to indicate the permyriadage progress of -** stage 2. A value of 5000 indicates that stage 2 is half finished, -** 9000 indicates that it is 90% finished, and so on. -** -** If this API is called during stage 1 of the update, output variable -** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The -** value to which (*pnOne) is set depends on whether or not the RBU -** database contains an "rbu_count" table. The rbu_count table, if it -** exists, must contain the same columns as the following: -** -** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID; -** -** There must be one row in the table for each source (data_xxx) table within -** the RBU database. The 'tbl' column should contain the name of the source -** table. The 'cnt' column should contain the number of rows within the -** source table. -** -** If the rbu_count table is present and populated correctly and this -** API is called during stage 1, the *pnOne output variable is set to the -** permyriadage progress of the same stage. If the rbu_count table does -** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count -** table exists but is not correctly populated, the value of the *pnOne -** output variable during stage 1 is undefined. -*/ -SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo); - -/* -** Obtain an indication as to the current stage of an RBU update or vacuum. -** This function always returns one of the SQLITE_RBU_STATE_XXX constants -** defined in this file. Return values should be interpreted as follows: -** -** SQLITE_RBU_STATE_OAL: -** RBU is currently building a *-oal file. The next call to sqlite3rbu_step() -** may either add further data to the *-oal file, or compute data that will -** be added by a subsequent call. -** -** SQLITE_RBU_STATE_MOVE: -** RBU has finished building the *-oal file. The next call to sqlite3rbu_step() -** will move the *-oal file to the equivalent *-wal path. If the current -** operation is an RBU update, then the updated version of the database -** file will become visible to ordinary SQLite clients following the next -** call to sqlite3rbu_step(). -** -** SQLITE_RBU_STATE_CHECKPOINT: -** RBU is currently performing an incremental checkpoint. The next call to -** sqlite3rbu_step() will copy a page of data from the *-wal file into -** the target database file. -** -** SQLITE_RBU_STATE_DONE: -** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step() -** will immediately return SQLITE_DONE. -** -** SQLITE_RBU_STATE_ERROR: -** An error has occurred. Any subsequent calls to sqlite3rbu_step() will -** immediately return the SQLite error code associated with the error. -*/ -#define SQLITE_RBU_STATE_OAL 1 -#define SQLITE_RBU_STATE_MOVE 2 -#define SQLITE_RBU_STATE_CHECKPOINT 3 -#define SQLITE_RBU_STATE_DONE 4 -#define SQLITE_RBU_STATE_ERROR 5 - -SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu); - -/* -** Create an RBU VFS named zName that accesses the underlying file-system -** via existing VFS zParent. Or, if the zParent parameter is passed NULL, -** then the new RBU VFS uses the default system VFS to access the file-system. -** The new object is registered as a non-default VFS with SQLite before -** returning. -** -** Part of the RBU implementation uses a custom VFS object. Usually, this -** object is created and deleted automatically by RBU. -** -** The exception is for applications that also use zipvfs. In this case, -** the custom VFS must be explicitly created by the user before the RBU -** handle is opened. The RBU VFS should be installed so that the zipvfs -** VFS uses the RBU VFS, which in turn uses any other VFS layers in use -** (for example multiplexor) to access the file-system. For example, -** to assemble an RBU enabled VFS stack that uses both zipvfs and -** multiplexor (error checking omitted): -** -** // Create a VFS named "multiplex" (not the default). -** sqlite3_multiplex_initialize(0, 0); -** -** // Create an rbu VFS named "rbu" that uses multiplexor. If the -** // second argument were replaced with NULL, the "rbu" VFS would -** // access the file-system via the system default VFS, bypassing the -** // multiplexor. -** sqlite3rbu_create_vfs("rbu", "multiplex"); -** -** // Create a zipvfs VFS named "zipvfs" that uses rbu. -** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector); -** -** // Make zipvfs the default VFS. -** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1); -** -** Because the default VFS created above includes a RBU functionality, it -** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack -** that does not include the RBU layer results in an error. -** -** The overhead of adding the "rbu" VFS to the system is negligible for -** non-RBU users. There is no harm in an application accessing the -** file-system via "rbu" all the time, even if it only uses RBU functionality -** occasionally. -*/ -SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent); - -/* -** Deregister and destroy an RBU vfs created by an earlier call to -** sqlite3rbu_create_vfs(). -** -** VFS objects are not reference counted. If a VFS object is destroyed -** before all database handles that use it have been closed, the results -** are undefined. -*/ -SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName); - -#if 0 -} /* end of the 'extern "C"' block */ -#endif - -#endif /* _SQLITE3RBU_H */ - -/************** End of sqlite3rbu.h ******************************************/ -/************** Continuing where we left off in sqlite3rbu.c *****************/ - -#if defined(_WIN32_WCE) -/* #include "windows.h" */ -#endif - -/* Maximum number of prepared UPDATE statements held by this module */ -#define SQLITE_RBU_UPDATE_CACHESIZE 16 - -/* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM -** to enable checksum verification. -*/ -#ifndef RBU_ENABLE_DELTA_CKSUM -# define RBU_ENABLE_DELTA_CKSUM 0 -#endif - -/* -** Swap two objects of type TYPE. -*/ -#if !defined(SQLITE_AMALGAMATION) -# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} -#endif - -/* -** The rbu_state table is used to save the state of a partially applied -** update so that it can be resumed later. The table consists of integer -** keys mapped to values as follows: -** -** RBU_STATE_STAGE: -** May be set to integer values 1, 2, 4 or 5. As follows: -** 1: the *-rbu file is currently under construction. -** 2: the *-rbu file has been constructed, but not yet moved -** to the *-wal path. -** 4: the checkpoint is underway. -** 5: the rbu update has been checkpointed. -** -** RBU_STATE_TBL: -** Only valid if STAGE==1. The target database name of the table -** currently being written. -** -** RBU_STATE_IDX: -** Only valid if STAGE==1. The target database name of the index -** currently being written, or NULL if the main table is currently being -** updated. -** -** RBU_STATE_ROW: -** Only valid if STAGE==1. Number of rows already processed for the current -** table/index. -** -** RBU_STATE_PROGRESS: -** Trbul number of sqlite3rbu_step() calls made so far as part of this -** rbu update. -** -** RBU_STATE_CKPT: -** Valid if STAGE==4. The 64-bit checksum associated with the wal-index -** header created by recovering the *-wal file. This is used to detect -** cases when another client appends frames to the *-wal file in the -** middle of an incremental checkpoint (an incremental checkpoint cannot -** be continued if this happens). -** -** RBU_STATE_COOKIE: -** Valid if STAGE==1. The current change-counter cookie value in the -** target db file. -** -** RBU_STATE_OALSZ: -** Valid if STAGE==1. The size in bytes of the *-oal file. -** -** RBU_STATE_DATATBL: -** Only valid if STAGE==1. The RBU database name of the table -** currently being read. -*/ -#define RBU_STATE_STAGE 1 -#define RBU_STATE_TBL 2 -#define RBU_STATE_IDX 3 -#define RBU_STATE_ROW 4 -#define RBU_STATE_PROGRESS 5 -#define RBU_STATE_CKPT 6 -#define RBU_STATE_COOKIE 7 -#define RBU_STATE_OALSZ 8 -#define RBU_STATE_PHASEONESTEP 9 -#define RBU_STATE_DATATBL 10 - -#define RBU_STAGE_OAL 1 -#define RBU_STAGE_MOVE 2 -#define RBU_STAGE_CAPTURE 3 -#define RBU_STAGE_CKPT 4 -#define RBU_STAGE_DONE 5 - - -#define RBU_CREATE_STATE \ - "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)" - -typedef struct RbuFrame RbuFrame; -typedef struct RbuObjIter RbuObjIter; -typedef struct RbuState RbuState; -typedef struct RbuSpan RbuSpan; -typedef struct rbu_vfs rbu_vfs; -typedef struct rbu_file rbu_file; -typedef struct RbuUpdateStmt RbuUpdateStmt; - -#if !defined(SQLITE_AMALGAMATION) -typedef unsigned int u32; -typedef unsigned short u16; -typedef unsigned char u8; -typedef sqlite3_int64 i64; -#endif - -/* -** These values must match the values defined in wal.c for the equivalent -** locks. These are not magic numbers as they are part of the SQLite file -** format. -*/ -#define WAL_LOCK_WRITE 0 -#define WAL_LOCK_CKPT 1 -#define WAL_LOCK_READ0 3 - -#define SQLITE_FCNTL_RBUCNT 5149216 - -/* -** A structure to store values read from the rbu_state table in memory. -*/ -struct RbuState { - int eStage; - char *zTbl; - char *zDataTbl; - char *zIdx; - i64 iWalCksum; - int nRow; - i64 nProgress; - u32 iCookie; - i64 iOalSz; - i64 nPhaseOneStep; -}; - -struct RbuUpdateStmt { - char *zMask; /* Copy of update mask used with pUpdate */ - sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */ - RbuUpdateStmt *pNext; -}; - -struct RbuSpan { - const char *zSpan; - int nSpan; -}; - -/* -** An iterator of this type is used to iterate through all objects in -** the target database that require updating. For each such table, the -** iterator visits, in order: -** -** * the table itself, -** * each index of the table (zero or more points to visit), and -** * a special "cleanup table" state. -** -** abIndexed: -** If the table has no indexes on it, abIndexed is set to NULL. Otherwise, -** it points to an array of flags nTblCol elements in size. The flag is -** set for each column that is either a part of the PK or a part of an -** index. Or clear otherwise. -** -** If there are one or more partial indexes on the table, all fields of -** this array set set to 1. This is because in that case, the module has -** no way to tell which fields will be required to add and remove entries -** from the partial indexes. -** -*/ -struct RbuObjIter { - sqlite3_stmt *pTblIter; /* Iterate through tables */ - sqlite3_stmt *pIdxIter; /* Index iterator */ - int nTblCol; /* Size of azTblCol[] array */ - char **azTblCol; /* Array of unquoted target column names */ - char **azTblType; /* Array of target column types */ - int *aiSrcOrder; /* src table col -> target table col */ - u8 *abTblPk; /* Array of flags, set on target PK columns */ - u8 *abNotNull; /* Array of flags, set on NOT NULL columns */ - u8 *abIndexed; /* Array of flags, set on indexed & PK cols */ - int eType; /* Table type - an RBU_PK_XXX value */ - - /* Output variables. zTbl==0 implies EOF. */ - int bCleanup; /* True in "cleanup" state */ - const char *zTbl; /* Name of target db table */ - const char *zDataTbl; /* Name of rbu db table (or null) */ - const char *zIdx; /* Name of target db index (or null) */ - int iTnum; /* Root page of current object */ - int iPkTnum; /* If eType==EXTERNAL, root of PK index */ - int bUnique; /* Current index is unique */ - int nIndex; /* Number of aux. indexes on table zTbl */ - - /* Statements created by rbuObjIterPrepareAll() */ - int nCol; /* Number of columns in current object */ - sqlite3_stmt *pSelect; /* Source data */ - sqlite3_stmt *pInsert; /* Statement for INSERT operations */ - sqlite3_stmt *pDelete; /* Statement for DELETE ops */ - sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */ - int nIdxCol; - RbuSpan *aIdxCol; - char *zIdxSql; - - /* Last UPDATE used (for PK b-tree updates only), or NULL. */ - RbuUpdateStmt *pRbuUpdate; -}; - -/* -** Values for RbuObjIter.eType -** -** 0: Table does not exist (error) -** 1: Table has an implicit rowid. -** 2: Table has an explicit IPK column. -** 3: Table has an external PK index. -** 4: Table is WITHOUT ROWID. -** 5: Table is a virtual table. -*/ -#define RBU_PK_NOTABLE 0 -#define RBU_PK_NONE 1 -#define RBU_PK_IPK 2 -#define RBU_PK_EXTERNAL 3 -#define RBU_PK_WITHOUT_ROWID 4 -#define RBU_PK_VTAB 5 - - -/* -** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs -** one of the following operations. -*/ -#define RBU_INSERT 1 /* Insert on a main table b-tree */ -#define RBU_DELETE 2 /* Delete a row from a main table b-tree */ -#define RBU_REPLACE 3 /* Delete and then insert a row */ -#define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */ -#define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */ - -#define RBU_UPDATE 6 /* Update a row in a main table b-tree */ - -/* -** A single step of an incremental checkpoint - frame iWalFrame of the wal -** file should be copied to page iDbPage of the database file. -*/ -struct RbuFrame { - u32 iDbPage; - u32 iWalFrame; -}; - -/* -** RBU handle. -** -** nPhaseOneStep: -** If the RBU database contains an rbu_count table, this value is set to -** a running estimate of the number of b-tree operations required to -** finish populating the *-oal file. This allows the sqlite3_bp_progress() -** API to calculate the permyriadage progress of populating the *-oal file -** using the formula: -** -** permyriadage = (10000 * nProgress) / nPhaseOneStep -** -** nPhaseOneStep is initialized to the sum of: -** -** nRow * (nIndex + 1) -** -** for all source tables in the RBU database, where nRow is the number -** of rows in the source table and nIndex the number of indexes on the -** corresponding target database table. -** -** This estimate is accurate if the RBU update consists entirely of -** INSERT operations. However, it is inaccurate if: -** -** * the RBU update contains any UPDATE operations. If the PK specified -** for an UPDATE operation does not exist in the target table, then -** no b-tree operations are required on index b-trees. Or if the -** specified PK does exist, then (nIndex*2) such operations are -** required (one delete and one insert on each index b-tree). -** -** * the RBU update contains any DELETE operations for which the specified -** PK does not exist. In this case no operations are required on index -** b-trees. -** -** * the RBU update contains REPLACE operations. These are similar to -** UPDATE operations. -** -** nPhaseOneStep is updated to account for the conditions above during the -** first pass of each source table. The updated nPhaseOneStep value is -** stored in the rbu_state table if the RBU update is suspended. -*/ -struct sqlite3rbu { - int eStage; /* Value of RBU_STATE_STAGE field */ - sqlite3 *dbMain; /* target database handle */ - sqlite3 *dbRbu; /* rbu database handle */ - char *zTarget; /* Path to target db */ - char *zRbu; /* Path to rbu db */ - char *zState; /* Path to state db (or NULL if zRbu) */ - char zStateDb[5]; /* Db name for state ("stat" or "main") */ - int rc; /* Value returned by last rbu_step() call */ - char *zErrmsg; /* Error message if rc!=SQLITE_OK */ - int nStep; /* Rows processed for current object */ - int nProgress; /* Rows processed for all objects */ - RbuObjIter objiter; /* Iterator for skipping through tbl/idx */ - const char *zVfsName; /* Name of automatically created rbu vfs */ - rbu_file *pTargetFd; /* File handle open on target db */ - int nPagePerSector; /* Pages per sector for pTargetFd */ - i64 iOalSz; - i64 nPhaseOneStep; - - /* The following state variables are used as part of the incremental - ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding - ** function rbuSetupCheckpoint() for details. */ - u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */ - u32 mLock; - int nFrame; /* Entries in aFrame[] array */ - int nFrameAlloc; /* Allocated size of aFrame[] array */ - RbuFrame *aFrame; - int pgsz; - u8 *aBuf; - i64 iWalCksum; - i64 szTemp; /* Current size of all temp files in use */ - i64 szTempLimit; /* Total size limit for temp files */ - - /* Used in RBU vacuum mode only */ - int nRbu; /* Number of RBU VFS in the stack */ - rbu_file *pRbuFd; /* Fd for main db of dbRbu */ -}; - -/* -** An rbu VFS is implemented using an instance of this structure. -** -** Variable pRbu is only non-NULL for automatically created RBU VFS objects. -** It is NULL for RBU VFS objects created explicitly using -** sqlite3rbu_create_vfs(). It is used to track the total amount of temp -** space used by the RBU handle. -*/ -struct rbu_vfs { - sqlite3_vfs base; /* rbu VFS shim methods */ - sqlite3_vfs *pRealVfs; /* Underlying VFS */ - sqlite3_mutex *mutex; /* Mutex to protect pMain */ - sqlite3rbu *pRbu; /* Owner RBU object */ - rbu_file *pMain; /* List of main db files */ - rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */ -}; - -/* -** Each file opened by an rbu VFS is represented by an instance of -** the following structure. -** -** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable -** "sz" is set to the current size of the database file. -*/ -struct rbu_file { - sqlite3_file base; /* sqlite3_file methods */ - sqlite3_file *pReal; /* Underlying file handle */ - rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */ - sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */ - i64 sz; /* Size of file in bytes (temp only) */ - - int openFlags; /* Flags this file was opened with */ - u32 iCookie; /* Cookie value for main db files */ - u8 iWriteVer; /* "write-version" value for main db files */ - u8 bNolock; /* True to fail EXCLUSIVE locks */ - - int nShm; /* Number of entries in apShm[] array */ - char **apShm; /* Array of mmap'd *-shm regions */ - char *zDel; /* Delete this when closing file */ - - const char *zWal; /* Wal filename for this main db file */ - rbu_file *pWalFd; /* Wal file descriptor for this main db */ - rbu_file *pMainNext; /* Next MAIN_DB file */ - rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */ -}; - -/* -** True for an RBU vacuum handle, or false otherwise. -*/ -#define rbuIsVacuum(p) ((p)->zTarget==0) - - -/************************************************************************* -** The following three functions, found below: -** -** rbuDeltaGetInt() -** rbuDeltaChecksum() -** rbuDeltaApply() -** -** are lifted from the fossil source code (http://fossil-scm.org). They -** are used to implement the scalar SQL function rbu_fossil_delta(). -*/ - -/* -** Read bytes from *pz and convert them into a positive integer. When -** finished, leave *pz pointing to the first character past the end of -** the integer. The *pLen parameter holds the length of the string -** in *pz and is decremented once for each character in the integer. -*/ -static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){ - static const signed char zValue[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, - -1, 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, -1, -1, -1, -1, 36, - -1, 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, -1, -1, -1, 63, -1, - }; - unsigned int v = 0; - int c; - unsigned char *z = (unsigned char*)*pz; - unsigned char *zStart = z; - while( (c = zValue[0x7f&*(z++)])>=0 ){ - v = (v<<6) + c; - } - z--; - *pLen -= z - zStart; - *pz = (char*)z; - return v; -} - -#if RBU_ENABLE_DELTA_CKSUM -/* -** Compute a 32-bit checksum on the N-byte buffer. Return the result. -*/ -static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){ - const unsigned char *z = (const unsigned char *)zIn; - unsigned sum0 = 0; - unsigned sum1 = 0; - unsigned sum2 = 0; - unsigned sum3 = 0; - while(N >= 16){ - sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]); - sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]); - sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]); - sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]); - z += 16; - N -= 16; - } - while(N >= 4){ - sum0 += z[0]; - sum1 += z[1]; - sum2 += z[2]; - sum3 += z[3]; - z += 4; - N -= 4; - } - sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24); - switch(N){ - case 3: sum3 += (z[2] << 8); - case 2: sum3 += (z[1] << 16); - case 1: sum3 += (z[0] << 24); - default: ; - } - return sum3; -} -#endif - -/* -** Apply a delta. -** -** The output buffer should be big enough to hold the whole output -** file and a NUL terminator at the end. The delta_output_size() -** routine will determine this size for you. -** -** The delta string should be null-terminated. But the delta string -** may contain embedded NUL characters (if the input and output are -** binary files) so we also have to pass in the length of the delta in -** the lenDelta parameter. -** -** This function returns the size of the output file in bytes (excluding -** the final NUL terminator character). Except, if the delta string is -** malformed or intended for use with a source file other than zSrc, -** then this routine returns -1. -** -** Refer to the delta_create() documentation above for a description -** of the delta file format. -*/ -static int rbuDeltaApply( - const char *zSrc, /* The source or pattern file */ - int lenSrc, /* Length of the source file */ - const char *zDelta, /* Delta to apply to the pattern */ - int lenDelta, /* Length of the delta */ - char *zOut /* Write the output into this preallocated buffer */ -){ - unsigned int limit; - unsigned int total = 0; -#if RBU_ENABLE_DELTA_CKSUM - char *zOrigOut = zOut; -#endif - - limit = rbuDeltaGetInt(&zDelta, &lenDelta); - if( *zDelta!='\n' ){ - /* ERROR: size integer not terminated by "\n" */ - return -1; - } - zDelta++; lenDelta--; - while( *zDelta && lenDelta>0 ){ - unsigned int cnt, ofst; - cnt = rbuDeltaGetInt(&zDelta, &lenDelta); - switch( zDelta[0] ){ - case '@': { - zDelta++; lenDelta--; - ofst = rbuDeltaGetInt(&zDelta, &lenDelta); - if( lenDelta>0 && zDelta[0]!=',' ){ - /* ERROR: copy command not terminated by ',' */ - return -1; - } - zDelta++; lenDelta--; - total += cnt; - if( total>limit ){ - /* ERROR: copy exceeds output file size */ - return -1; - } - if( (int)(ofst+cnt) > lenSrc ){ - /* ERROR: copy extends past end of input */ - return -1; - } - memcpy(zOut, &zSrc[ofst], cnt); - zOut += cnt; - break; - } - case ':': { - zDelta++; lenDelta--; - total += cnt; - if( total>limit ){ - /* ERROR: insert command gives an output larger than predicted */ - return -1; - } - if( (int)cnt>lenDelta ){ - /* ERROR: insert count exceeds size of delta */ - return -1; - } - memcpy(zOut, zDelta, cnt); - zOut += cnt; - zDelta += cnt; - lenDelta -= cnt; - break; - } - case ';': { - zDelta++; lenDelta--; - zOut[0] = 0; -#if RBU_ENABLE_DELTA_CKSUM - if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){ - /* ERROR: bad checksum */ - return -1; - } -#endif - if( total!=limit ){ - /* ERROR: generated size does not match predicted size */ - return -1; - } - return total; - } - default: { - /* ERROR: unknown delta operator */ - return -1; - } - } - } - /* ERROR: unterminated delta */ - return -1; -} - -static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){ - int size; - size = rbuDeltaGetInt(&zDelta, &lenDelta); - if( *zDelta!='\n' ){ - /* ERROR: size integer not terminated by "\n" */ - return -1; - } - return size; -} - -/* -** End of code taken from fossil. -*************************************************************************/ - -/* -** Implementation of SQL scalar function rbu_fossil_delta(). -** -** This function applies a fossil delta patch to a blob. Exactly two -** arguments must be passed to this function. The first is the blob to -** patch and the second the patch to apply. If no error occurs, this -** function returns the patched blob. -*/ -static void rbuFossilDeltaFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *aDelta; - int nDelta; - const char *aOrig; - int nOrig; - - int nOut; - int nOut2; - char *aOut; - - assert( argc==2 ); - - nOrig = sqlite3_value_bytes(argv[0]); - aOrig = (const char*)sqlite3_value_blob(argv[0]); - nDelta = sqlite3_value_bytes(argv[1]); - aDelta = (const char*)sqlite3_value_blob(argv[1]); - - /* Figure out the size of the output */ - nOut = rbuDeltaOutputSize(aDelta, nDelta); - if( nOut<0 ){ - sqlite3_result_error(context, "corrupt fossil delta", -1); - return; - } - - aOut = sqlite3_malloc(nOut+1); - if( aOut==0 ){ - sqlite3_result_error_nomem(context); - }else{ - nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut); - if( nOut2!=nOut ){ - sqlite3_free(aOut); - sqlite3_result_error(context, "corrupt fossil delta", -1); - }else{ - sqlite3_result_blob(context, aOut, nOut, sqlite3_free); - } - } -} - - -/* -** Prepare the SQL statement in buffer zSql against database handle db. -** If successful, set *ppStmt to point to the new statement and return -** SQLITE_OK. -** -** Otherwise, if an error does occur, set *ppStmt to NULL and return -** an SQLite error code. Additionally, set output variable *pzErrmsg to -** point to a buffer containing an error message. It is the responsibility -** of the caller to (eventually) free this buffer using sqlite3_free(). -*/ -static int prepareAndCollectError( - sqlite3 *db, - sqlite3_stmt **ppStmt, - char **pzErrmsg, - const char *zSql -){ - int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); - if( rc!=SQLITE_OK ){ - *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - *ppStmt = 0; - } - return rc; -} - -/* -** Reset the SQL statement passed as the first argument. Return a copy -** of the value returned by sqlite3_reset(). -** -** If an error has occurred, then set *pzErrmsg to point to a buffer -** containing an error message. It is the responsibility of the caller -** to eventually free this buffer using sqlite3_free(). -*/ -static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){ - int rc = sqlite3_reset(pStmt); - if( rc!=SQLITE_OK ){ - *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt))); - } - return rc; -} - -/* -** Unless it is NULL, argument zSql points to a buffer allocated using -** sqlite3_malloc containing an SQL statement. This function prepares the SQL -** statement against database db and frees the buffer. If statement -** compilation is successful, *ppStmt is set to point to the new statement -** handle and SQLITE_OK is returned. -** -** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code -** returned. In this case, *pzErrmsg may also be set to point to an error -** message. It is the responsibility of the caller to free this error message -** buffer using sqlite3_free(). -** -** If argument zSql is NULL, this function assumes that an OOM has occurred. -** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL. -*/ -static int prepareFreeAndCollectError( - sqlite3 *db, - sqlite3_stmt **ppStmt, - char **pzErrmsg, - char *zSql -){ - int rc; - assert( *pzErrmsg==0 ); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - *ppStmt = 0; - }else{ - rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql); - sqlite3_free(zSql); - } - return rc; -} - -/* -** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated -** by an earlier call to rbuObjIterCacheTableInfo(). -*/ -static void rbuObjIterFreeCols(RbuObjIter *pIter){ - int i; - for(i=0; inTblCol; i++){ - sqlite3_free(pIter->azTblCol[i]); - sqlite3_free(pIter->azTblType[i]); - } - sqlite3_free(pIter->azTblCol); - pIter->azTblCol = 0; - pIter->azTblType = 0; - pIter->aiSrcOrder = 0; - pIter->abTblPk = 0; - pIter->abNotNull = 0; - pIter->nTblCol = 0; - pIter->eType = 0; /* Invalid value */ -} - -/* -** Finalize all statements and free all allocations that are specific to -** the current object (table/index pair). -*/ -static void rbuObjIterClearStatements(RbuObjIter *pIter){ - RbuUpdateStmt *pUp; - - sqlite3_finalize(pIter->pSelect); - sqlite3_finalize(pIter->pInsert); - sqlite3_finalize(pIter->pDelete); - sqlite3_finalize(pIter->pTmpInsert); - pUp = pIter->pRbuUpdate; - while( pUp ){ - RbuUpdateStmt *pTmp = pUp->pNext; - sqlite3_finalize(pUp->pUpdate); - sqlite3_free(pUp); - pUp = pTmp; - } - sqlite3_free(pIter->aIdxCol); - sqlite3_free(pIter->zIdxSql); - - pIter->pSelect = 0; - pIter->pInsert = 0; - pIter->pDelete = 0; - pIter->pRbuUpdate = 0; - pIter->pTmpInsert = 0; - pIter->nCol = 0; - pIter->nIdxCol = 0; - pIter->aIdxCol = 0; - pIter->zIdxSql = 0; -} - -/* -** Clean up any resources allocated as part of the iterator object passed -** as the only argument. -*/ -static void rbuObjIterFinalize(RbuObjIter *pIter){ - rbuObjIterClearStatements(pIter); - sqlite3_finalize(pIter->pTblIter); - sqlite3_finalize(pIter->pIdxIter); - rbuObjIterFreeCols(pIter); - memset(pIter, 0, sizeof(RbuObjIter)); -} - -/* -** Advance the iterator to the next position. -** -** If no error occurs, SQLITE_OK is returned and the iterator is left -** pointing to the next entry. Otherwise, an error code and message is -** left in the RBU handle passed as the first argument. A copy of the -** error code is returned. -*/ -static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){ - int rc = p->rc; - if( rc==SQLITE_OK ){ - - /* Free any SQLite statements used while processing the previous object */ - rbuObjIterClearStatements(pIter); - if( pIter->zIdx==0 ){ - rc = sqlite3_exec(p->dbMain, - "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;" - "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;" - "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;" - "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;" - , 0, 0, &p->zErrmsg - ); - } - - if( rc==SQLITE_OK ){ - if( pIter->bCleanup ){ - rbuObjIterFreeCols(pIter); - pIter->bCleanup = 0; - rc = sqlite3_step(pIter->pTblIter); - if( rc!=SQLITE_ROW ){ - rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg); - pIter->zTbl = 0; - }else{ - pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0); - pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1); - rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM; - } - }else{ - if( pIter->zIdx==0 ){ - sqlite3_stmt *pIdx = pIter->pIdxIter; - rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_step(pIter->pIdxIter); - if( rc!=SQLITE_ROW ){ - rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg); - pIter->bCleanup = 1; - pIter->zIdx = 0; - }else{ - pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0); - pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1); - pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2); - rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM; - } - } - } - } - } - - if( rc!=SQLITE_OK ){ - rbuObjIterFinalize(pIter); - p->rc = rc; - } - return rc; -} - - -/* -** The implementation of the rbu_target_name() SQL function. This function -** accepts one or two arguments. The first argument is the name of a table - -** the name of a table in the RBU database. The second, if it is present, is 1 -** for a view or 0 for a table. -** -** For a non-vacuum RBU handle, if the table name matches the pattern: -** -** data[0-9]_ -** -** where is any sequence of 1 or more characters, is returned. -** Otherwise, if the only argument does not match the above pattern, an SQL -** NULL is returned. -** -** "data_t1" -> "t1" -** "data0123_t2" -> "t2" -** "dataAB_t3" -> NULL -** -** For an rbu vacuum handle, a copy of the first argument is returned if -** the second argument is either missing or 0 (not a view). -*/ -static void rbuTargetNameFunc( - sqlite3_context *pCtx, - int argc, - sqlite3_value **argv -){ - sqlite3rbu *p = sqlite3_user_data(pCtx); - const char *zIn; - assert( argc==1 || argc==2 ); - - zIn = (const char*)sqlite3_value_text(argv[0]); - if( zIn ){ - if( rbuIsVacuum(p) ){ - assert( argc==2 || argc==1 ); - if( argc==1 || 0==sqlite3_value_int(argv[1]) ){ - sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC); - } - }else{ - if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){ - int i; - for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++); - if( zIn[i]=='_' && zIn[i+1] ){ - sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC); - } - } - } - } -} - -/* -** Initialize the iterator structure passed as the second argument. -** -** If no error occurs, SQLITE_OK is returned and the iterator is left -** pointing to the first entry. Otherwise, an error code and message is -** left in the RBU handle passed as the first argument. A copy of the -** error code is returned. -*/ -static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){ - int rc; - memset(pIter, 0, sizeof(RbuObjIter)); - - rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, - sqlite3_mprintf( - "SELECT rbu_target_name(name, type='view') AS target, name " - "FROM sqlite_schema " - "WHERE type IN ('table', 'view') AND target IS NOT NULL " - " %s " - "ORDER BY name" - , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : "")); - - if( rc==SQLITE_OK ){ - rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg, - "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' " - " FROM main.sqlite_schema " - " WHERE type='index' AND tbl_name = ?" - ); - } - - pIter->bCleanup = 1; - p->rc = rc; - return rbuObjIterNext(p, pIter); -} - -/* -** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs, -** an error code is stored in the RBU handle passed as the first argument. -** -** If an error has already occurred (p->rc is already set to something other -** than SQLITE_OK), then this function returns NULL without modifying the -** stored error code. In this case it still calls sqlite3_free() on any -** printf() parameters associated with %z conversions. -*/ -static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){ - char *zSql = 0; - va_list ap; - va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); - if( p->rc==SQLITE_OK ){ - if( zSql==0 ) p->rc = SQLITE_NOMEM; - }else{ - sqlite3_free(zSql); - zSql = 0; - } - va_end(ap); - return zSql; -} - -/* -** Argument zFmt is a sqlite3_mprintf() style format string. The trailing -** arguments are the usual subsitution values. This function performs -** the printf() style substitutions and executes the result as an SQL -** statement on the RBU handles database. -** -** If an error occurs, an error code and error message is stored in the -** RBU handle. If an error has already occurred when this function is -** called, it is a no-op. -*/ -static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){ - va_list ap; - char *zSql; - va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); - if( p->rc==SQLITE_OK ){ - if( zSql==0 ){ - p->rc = SQLITE_NOMEM; - }else{ - p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg); - } - } - sqlite3_free(zSql); - va_end(ap); - return p->rc; -} - -/* -** Attempt to allocate and return a pointer to a zeroed block of nByte -** bytes. -** -** If an error (i.e. an OOM condition) occurs, return NULL and leave an -** error code in the rbu handle passed as the first argument. Or, if an -** error has already occurred when this function is called, return NULL -** immediately without attempting the allocation or modifying the stored -** error code. -*/ -static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){ - void *pRet = 0; - if( p->rc==SQLITE_OK ){ - assert( nByte>0 ); - pRet = sqlite3_malloc64(nByte); - if( pRet==0 ){ - p->rc = SQLITE_NOMEM; - }else{ - memset(pRet, 0, nByte); - } - } - return pRet; -} - - -/* -** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that -** there is room for at least nCol elements. If an OOM occurs, store an -** error code in the RBU handle passed as the first argument. -*/ -static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){ - sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol; - char **azNew; - - azNew = (char**)rbuMalloc(p, nByte); - if( azNew ){ - pIter->azTblCol = azNew; - pIter->azTblType = &azNew[nCol]; - pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol]; - pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol]; - pIter->abNotNull = (u8*)&pIter->abTblPk[nCol]; - pIter->abIndexed = (u8*)&pIter->abNotNull[nCol]; - } -} - -/* -** The first argument must be a nul-terminated string. This function -** returns a copy of the string in memory obtained from sqlite3_malloc(). -** It is the responsibility of the caller to eventually free this memory -** using sqlite3_free(). -** -** If an OOM condition is encountered when attempting to allocate memory, -** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise, -** if the allocation succeeds, (*pRc) is left unchanged. -*/ -static char *rbuStrndup(const char *zStr, int *pRc){ - char *zRet = 0; - - if( *pRc==SQLITE_OK ){ - if( zStr ){ - size_t nCopy = strlen(zStr) + 1; - zRet = (char*)sqlite3_malloc64(nCopy); - if( zRet ){ - memcpy(zRet, zStr, nCopy); - }else{ - *pRc = SQLITE_NOMEM; - } - } - } - - return zRet; -} - -/* -** Finalize the statement passed as the second argument. -** -** If the sqlite3_finalize() call indicates that an error occurs, and the -** rbu handle error code is not already set, set the error code and error -** message accordingly. -*/ -static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){ - sqlite3 *db = sqlite3_db_handle(pStmt); - int rc = sqlite3_finalize(pStmt); - if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ - p->rc = rc; - p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - } -} - -/* Determine the type of a table. -** -** peType is of type (int*), a pointer to an output parameter of type -** (int). This call sets the output parameter as follows, depending -** on the type of the table specified by parameters dbName and zTbl. -** -** RBU_PK_NOTABLE: No such table. -** RBU_PK_NONE: Table has an implicit rowid. -** RBU_PK_IPK: Table has an explicit IPK column. -** RBU_PK_EXTERNAL: Table has an external PK index. -** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID. -** RBU_PK_VTAB: Table is a virtual table. -** -** Argument *piPk is also of type (int*), and also points to an output -** parameter. Unless the table has an external primary key index -** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or, -** if the table does have an external primary key index, then *piPk -** is set to the root page number of the primary key index before -** returning. -** -** ALGORITHM: -** -** if( no entry exists in sqlite_schema ){ -** return RBU_PK_NOTABLE -** }else if( sql for the entry starts with "CREATE VIRTUAL" ){ -** return RBU_PK_VTAB -** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){ -** if( the index that is the pk exists in sqlite_schema ){ -** *piPK = rootpage of that index. -** return RBU_PK_EXTERNAL -** }else{ -** return RBU_PK_WITHOUT_ROWID -** } -** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){ -** return RBU_PK_IPK -** }else{ -** return RBU_PK_NONE -** } -*/ -static void rbuTableType( - sqlite3rbu *p, - const char *zTab, - int *peType, - int *piTnum, - int *piPk -){ - /* - ** 0) SELECT count(*) FROM sqlite_schema where name=%Q AND IsVirtual(%Q) - ** 1) PRAGMA index_list = ? - ** 2) SELECT count(*) FROM sqlite_schema where name=%Q - ** 3) PRAGMA table_info = ? - */ - sqlite3_stmt *aStmt[4] = {0, 0, 0, 0}; - - *peType = RBU_PK_NOTABLE; - *piPk = 0; - - assert( p->rc==SQLITE_OK ); - p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, - sqlite3_mprintf( - "SELECT (sql LIKE 'create virtual%%'), rootpage" - " FROM sqlite_schema" - " WHERE name=%Q", zTab - )); - if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){ - /* Either an error, or no such table. */ - goto rbuTableType_end; - } - if( sqlite3_column_int(aStmt[0], 0) ){ - *peType = RBU_PK_VTAB; /* virtual table */ - goto rbuTableType_end; - } - *piTnum = sqlite3_column_int(aStmt[0], 1); - - p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, - sqlite3_mprintf("PRAGMA index_list=%Q",zTab) - ); - if( p->rc ) goto rbuTableType_end; - while( sqlite3_step(aStmt[1])==SQLITE_ROW ){ - const u8 *zOrig = sqlite3_column_text(aStmt[1], 3); - const u8 *zIdx = sqlite3_column_text(aStmt[1], 1); - if( zOrig && zIdx && zOrig[0]=='p' ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, - sqlite3_mprintf( - "SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx - )); - if( p->rc==SQLITE_OK ){ - if( sqlite3_step(aStmt[2])==SQLITE_ROW ){ - *piPk = sqlite3_column_int(aStmt[2], 0); - *peType = RBU_PK_EXTERNAL; - }else{ - *peType = RBU_PK_WITHOUT_ROWID; - } - } - goto rbuTableType_end; - } - } - - p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, - sqlite3_mprintf("PRAGMA table_info=%Q",zTab) - ); - if( p->rc==SQLITE_OK ){ - while( sqlite3_step(aStmt[3])==SQLITE_ROW ){ - if( sqlite3_column_int(aStmt[3],5)>0 ){ - *peType = RBU_PK_IPK; /* explicit IPK column */ - goto rbuTableType_end; - } - } - *peType = RBU_PK_NONE; - } - -rbuTableType_end: { - unsigned int i; - for(i=0; iabIndexed[] array. -*/ -static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){ - sqlite3_stmt *pList = 0; - int bIndex = 0; - - if( p->rc==SQLITE_OK ){ - memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol); - p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) - ); - } - - pIter->nIndex = 0; - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ - const char *zIdx = (const char*)sqlite3_column_text(pList, 1); - int bPartial = sqlite3_column_int(pList, 4); - sqlite3_stmt *pXInfo = 0; - if( zIdx==0 ) break; - if( bPartial ){ - memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol); - } - p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) - ); - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - int iCid = sqlite3_column_int(pXInfo, 1); - if( iCid>=0 ) pIter->abIndexed[iCid] = 1; - if( iCid==-2 ){ - memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol); - } - } - rbuFinalize(p, pXInfo); - bIndex = 1; - pIter->nIndex++; - } - - if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ - /* "PRAGMA index_list" includes the main PK b-tree */ - pIter->nIndex--; - } - - rbuFinalize(p, pList); - if( bIndex==0 ) pIter->abIndexed = 0; -} - - -/* -** If they are not already populated, populate the pIter->azTblCol[], -** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to -** the table (not index) that the iterator currently points to. -** -** Return SQLITE_OK if successful, or an SQLite error code otherwise. If -** an error does occur, an error code and error message are also left in -** the RBU handle. -*/ -static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ - if( pIter->azTblCol==0 ){ - sqlite3_stmt *pStmt = 0; - int nCol = 0; - int i; /* for() loop iterator variable */ - int bRbuRowid = 0; /* If input table has column "rbu_rowid" */ - int iOrder = 0; - int iTnum = 0; - - /* Figure out the type of table this step will deal with. */ - assert( pIter->eType==0 ); - rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum); - if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){ - p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl); - } - if( p->rc ) return p->rc; - if( pIter->zIdx==0 ) pIter->iTnum = iTnum; - - assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK - || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID - || pIter->eType==RBU_PK_VTAB - ); - - /* Populate the azTblCol[] and nTblCol variables based on the columns - ** of the input table. Ignore any input table columns that begin with - ** "rbu_". */ - p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, - sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl) - ); - if( p->rc==SQLITE_OK ){ - nCol = sqlite3_column_count(pStmt); - rbuAllocateIterArrays(p, pIter, nCol); - } - for(i=0; p->rc==SQLITE_OK && irc); - pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol; - pIter->azTblCol[pIter->nTblCol++] = zCopy; - } - else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){ - bRbuRowid = 1; - } - } - sqlite3_finalize(pStmt); - pStmt = 0; - - if( p->rc==SQLITE_OK - && rbuIsVacuum(p)==0 - && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) - ){ - p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf( - "table %q %s rbu_rowid column", pIter->zDataTbl, - (bRbuRowid ? "may not have" : "requires") - ); - } - - /* Check that all non-HIDDEN columns in the destination table are also - ** present in the input table. Populate the abTblPk[], azTblType[] and - ** aiTblOrder[] arrays at the same time. */ - if( p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, - sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl) - ); - } - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zName = (const char*)sqlite3_column_text(pStmt, 1); - if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */ - for(i=iOrder; inTblCol; i++){ - if( 0==strcmp(zName, pIter->azTblCol[i]) ) break; - } - if( i==pIter->nTblCol ){ - p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("column missing from %q: %s", - pIter->zDataTbl, zName - ); - }else{ - int iPk = sqlite3_column_int(pStmt, 5); - int bNotNull = sqlite3_column_int(pStmt, 3); - const char *zType = (const char*)sqlite3_column_text(pStmt, 2); - - if( i!=iOrder ){ - SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]); - SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]); - } - - pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc); - assert( iPk>=0 ); - pIter->abTblPk[iOrder] = (u8)iPk; - pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0); - iOrder++; - } - } - - rbuFinalize(p, pStmt); - rbuObjIterCacheIndexedCols(p, pIter); - assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 ); - assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 ); - } - - return p->rc; -} - -/* -** This function constructs and returns a pointer to a nul-terminated -** string containing some SQL clause or list based on one or more of the -** column names currently stored in the pIter->azTblCol[] array. -*/ -static char *rbuObjIterGetCollist( - sqlite3rbu *p, /* RBU object */ - RbuObjIter *pIter /* Object iterator for column names */ -){ - char *zList = 0; - const char *zSep = ""; - int i; - for(i=0; inTblCol; i++){ - const char *z = pIter->azTblCol[i]; - zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z); - zSep = ", "; - } - return zList; -} - -/* -** Return a comma separated list of the quoted PRIMARY KEY column names, -** in order, for the current table. Before each column name, add the text -** zPre. After each column name, add the zPost text. Use zSeparator as -** the separator text (usually ", "). -*/ -static char *rbuObjIterGetPkList( - sqlite3rbu *p, /* RBU object */ - RbuObjIter *pIter, /* Object iterator for column names */ - const char *zPre, /* Before each quoted column name */ - const char *zSeparator, /* Separator to use between columns */ - const char *zPost /* After each quoted column name */ -){ - int iPk = 1; - char *zRet = 0; - const char *zSep = ""; - while( 1 ){ - int i; - for(i=0; inTblCol; i++){ - if( (int)pIter->abTblPk[i]==iPk ){ - const char *zCol = pIter->azTblCol[i]; - zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost); - zSep = zSeparator; - break; - } - } - if( i==pIter->nTblCol ) break; - iPk++; - } - return zRet; -} - -/* -** This function is called as part of restarting an RBU vacuum within -** stage 1 of the process (while the *-oal file is being built) while -** updating a table (not an index). The table may be a rowid table or -** a WITHOUT ROWID table. It queries the target database to find the -** largest key that has already been written to the target table and -** constructs a WHERE clause that can be used to extract the remaining -** rows from the source table. For a rowid table, the WHERE clause -** is of the form: -** -** "WHERE _rowid_ > ?" -** -** and for WITHOUT ROWID tables: -** -** "WHERE (key1, key2) > (?, ?)" -** -** Instead of "?" placeholders, the actual WHERE clauses created by -** this function contain literal SQL values. -*/ -static char *rbuVacuumTableStart( - sqlite3rbu *p, /* RBU handle */ - RbuObjIter *pIter, /* RBU iterator object */ - int bRowid, /* True for a rowid table */ - const char *zWrite /* Target table name prefix */ -){ - sqlite3_stmt *pMax = 0; - char *zRet = 0; - if( bRowid ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, - sqlite3_mprintf( - "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl - ) - ); - if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ - sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0); - zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax); - } - rbuFinalize(p, pMax); - }else{ - char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC"); - char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")"); - char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", ""); - - if( p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, - sqlite3_mprintf( - "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1", - zSelect, zWrite, pIter->zTbl, zOrder - ) - ); - if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ - const char *zVal = (const char*)sqlite3_column_text(pMax, 0); - zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal); - } - rbuFinalize(p, pMax); - } - - sqlite3_free(zOrder); - sqlite3_free(zSelect); - sqlite3_free(zList); - } - return zRet; -} - -/* -** This function is called as part of restating an RBU vacuum when the -** current operation is writing content to an index. If possible, it -** queries the target index b-tree for the largest key already written to -** it, then composes and returns an expression that can be used in a WHERE -** clause to select the remaining required rows from the source table. -** It is only possible to return such an expression if: -** -** * The index contains no DESC columns, and -** * The last key written to the index before the operation was -** suspended does not contain any NULL values. -** -** The expression is of the form: -** -** (index-field1, index-field2, ...) > (?, ?, ...) -** -** except that the "?" placeholders are replaced with literal values. -** -** If the expression cannot be created, NULL is returned. In this case, -** the caller has to use an OFFSET clause to extract only the required -** rows from the sourct table, just as it does for an RBU update operation. -*/ -char *rbuVacuumIndexStart( - sqlite3rbu *p, /* RBU handle */ - RbuObjIter *pIter /* RBU iterator object */ -){ - char *zOrder = 0; - char *zLhs = 0; - char *zSelect = 0; - char *zVector = 0; - char *zRet = 0; - int bFailed = 0; - const char *zSep = ""; - int iCol = 0; - sqlite3_stmt *pXInfo = 0; - - p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) - ); - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - int iCid = sqlite3_column_int(pXInfo, 1); - const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); - const char *zCol; - if( sqlite3_column_int(pXInfo, 3) ){ - bFailed = 1; - break; - } - - if( iCid<0 ){ - if( pIter->eType==RBU_PK_IPK ){ - int i; - for(i=0; pIter->abTblPk[i]==0; i++); - assert( inTblCol ); - zCol = pIter->azTblCol[i]; - }else{ - zCol = "_rowid_"; - } - }else{ - zCol = pIter->azTblCol[iCid]; - } - - zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q", - zLhs, zSep, zCol, zCollate - ); - zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC", - zOrder, zSep, iCol, zCol, zCollate - ); - zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")", - zSelect, zSep, iCol, zCol - ); - zSep = ", "; - iCol++; - } - rbuFinalize(p, pXInfo); - if( bFailed ) goto index_start_out; - - if( p->rc==SQLITE_OK ){ - sqlite3_stmt *pSel = 0; - - p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg, - sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1", - zSelect, pIter->zTbl, zOrder - ) - ); - if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){ - zSep = ""; - for(iCol=0; iColnCol; iCol++){ - const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol); - if( zQuoted[0]=='N' ){ - bFailed = 1; - break; - } - zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted); - zSep = ", "; - } - - if( !bFailed ){ - zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector); - } - } - rbuFinalize(p, pSel); - } - - index_start_out: - sqlite3_free(zOrder); - sqlite3_free(zSelect); - sqlite3_free(zVector); - sqlite3_free(zLhs); - return zRet; -} - -/* -** This function is used to create a SELECT list (the list of SQL -** expressions that follows a SELECT keyword) for a SELECT statement -** used to read from an data_xxx or rbu_tmp_xxx table while updating the -** index object currently indicated by the iterator object passed as the -** second argument. A "PRAGMA index_xinfo = " statement is used -** to obtain the required information. -** -** If the index is of the following form: -** -** CREATE INDEX i1 ON t1(c, b COLLATE nocase); -** -** and "t1" is a table with an explicit INTEGER PRIMARY KEY column -** "ipk", the returned string is: -** -** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'" -** -** As well as the returned string, three other malloc'd strings are -** returned via output parameters. As follows: -** -** pzImposterCols: ... -** pzImposterPk: ... -** pzWhere: ... -*/ -static char *rbuObjIterGetIndexCols( - sqlite3rbu *p, /* RBU object */ - RbuObjIter *pIter, /* Object iterator for column names */ - char **pzImposterCols, /* OUT: Columns for imposter table */ - char **pzImposterPk, /* OUT: Imposter PK clause */ - char **pzWhere, /* OUT: WHERE clause */ - int *pnBind /* OUT: Trbul number of columns */ -){ - int rc = p->rc; /* Error code */ - int rc2; /* sqlite3_finalize() return code */ - char *zRet = 0; /* String to return */ - char *zImpCols = 0; /* String to return via *pzImposterCols */ - char *zImpPK = 0; /* String to return via *pzImposterPK */ - char *zWhere = 0; /* String to return via *pzWhere */ - int nBind = 0; /* Value to return via *pnBind */ - const char *zCom = ""; /* Set to ", " later on */ - const char *zAnd = ""; /* Set to " AND " later on */ - sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */ - - if( rc==SQLITE_OK ){ - assert( p->zErrmsg==0 ); - rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx) - ); - } - - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - int iCid = sqlite3_column_int(pXInfo, 1); - int bDesc = sqlite3_column_int(pXInfo, 3); - const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); - const char *zCol = 0; - const char *zType; - - if( iCid==-2 ){ - int iSeq = sqlite3_column_int(pXInfo, 0); - zRet = sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom, - pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate - ); - zType = ""; - }else { - if( iCid<0 ){ - /* An integer primary key. If the table has an explicit IPK, use - ** its name. Otherwise, use "rbu_rowid". */ - if( pIter->eType==RBU_PK_IPK ){ - int i; - for(i=0; pIter->abTblPk[i]==0; i++); - assert( inTblCol ); - zCol = pIter->azTblCol[i]; - }else if( rbuIsVacuum(p) ){ - zCol = "_rowid_"; - }else{ - zCol = "rbu_rowid"; - } - zType = "INTEGER"; - }else{ - zCol = pIter->azTblCol[iCid]; - zType = pIter->azTblType[iCid]; - } - zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate); - } - - if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){ - const char *zOrder = (bDesc ? " DESC" : ""); - zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", - zImpPK, zCom, nBind, zCol, zOrder - ); - } - zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", - zImpCols, zCom, nBind, zCol, zType, zCollate - ); - zWhere = sqlite3_mprintf( - "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol - ); - if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM; - zCom = ", "; - zAnd = " AND "; - nBind++; - } - - rc2 = sqlite3_finalize(pXInfo); - if( rc==SQLITE_OK ) rc = rc2; - - if( rc!=SQLITE_OK ){ - sqlite3_free(zRet); - sqlite3_free(zImpCols); - sqlite3_free(zImpPK); - sqlite3_free(zWhere); - zRet = 0; - zImpCols = 0; - zImpPK = 0; - zWhere = 0; - p->rc = rc; - } - - *pzImposterCols = zImpCols; - *pzImposterPk = zImpPK; - *pzWhere = zWhere; - *pnBind = nBind; - return zRet; -} - -/* -** Assuming the current table columns are "a", "b" and "c", and the zObj -** paramter is passed "old", return a string of the form: -** -** "old.a, old.b, old.b" -** -** With the column names escaped. -** -** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append -** the text ", old._rowid_" to the returned value. -*/ -static char *rbuObjIterGetOldlist( - sqlite3rbu *p, - RbuObjIter *pIter, - const char *zObj -){ - char *zList = 0; - if( p->rc==SQLITE_OK && pIter->abIndexed ){ - const char *zS = ""; - int i; - for(i=0; inTblCol; i++){ - if( pIter->abIndexed[i] ){ - const char *zCol = pIter->azTblCol[i]; - zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol); - }else{ - zList = sqlite3_mprintf("%z%sNULL", zList, zS); - } - zS = ", "; - if( zList==0 ){ - p->rc = SQLITE_NOMEM; - break; - } - } - - /* For a table with implicit rowids, append "old._rowid_" to the list. */ - if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ - zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj); - } - } - return zList; -} - -/* -** Return an expression that can be used in a WHERE clause to match the -** primary key of the current table. For example, if the table is: -** -** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c)); -** -** Return the string: -** -** "b = ?1 AND c = ?2" -*/ -static char *rbuObjIterGetWhere( - sqlite3rbu *p, - RbuObjIter *pIter -){ - char *zList = 0; - if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){ - zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1); - }else if( pIter->eType==RBU_PK_EXTERNAL ){ - const char *zSep = ""; - int i; - for(i=0; inTblCol; i++){ - if( pIter->abTblPk[i] ){ - zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1); - zSep = " AND "; - } - } - zList = rbuMPrintf(p, - "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList - ); - - }else{ - const char *zSep = ""; - int i; - for(i=0; inTblCol; i++){ - if( pIter->abTblPk[i] ){ - const char *zCol = pIter->azTblCol[i]; - zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1); - zSep = " AND "; - } - } - } - return zList; -} - -/* -** The SELECT statement iterating through the keys for the current object -** (p->objiter.pSelect) currently points to a valid row. However, there -** is something wrong with the rbu_control value in the rbu_control value -** stored in the (p->nCol+1)'th column. Set the error code and error message -** of the RBU handle to something reflecting this. -*/ -static void rbuBadControlError(sqlite3rbu *p){ - p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("invalid rbu_control value"); -} - - -/* -** Return a nul-terminated string containing the comma separated list of -** assignments that should be included following the "SET" keyword of -** an UPDATE statement used to update the table object that the iterator -** passed as the second argument currently points to if the rbu_control -** column of the data_xxx table entry is set to zMask. -** -** The memory for the returned string is obtained from sqlite3_malloc(). -** It is the responsibility of the caller to eventually free it using -** sqlite3_free(). -** -** If an OOM error is encountered when allocating space for the new -** string, an error code is left in the rbu handle passed as the first -** argument and NULL is returned. Or, if an error has already occurred -** when this function is called, NULL is returned immediately, without -** attempting the allocation or modifying the stored error code. -*/ -static char *rbuObjIterGetSetlist( - sqlite3rbu *p, - RbuObjIter *pIter, - const char *zMask -){ - char *zList = 0; - if( p->rc==SQLITE_OK ){ - int i; - - if( (int)strlen(zMask)!=pIter->nTblCol ){ - rbuBadControlError(p); - }else{ - const char *zSep = ""; - for(i=0; inTblCol; i++){ - char c = zMask[pIter->aiSrcOrder[i]]; - if( c=='x' ){ - zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", - zList, zSep, pIter->azTblCol[i], i+1 - ); - zSep = ", "; - } - else if( c=='d' ){ - zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", - zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 - ); - zSep = ", "; - } - else if( c=='f' ){ - zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", - zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1 - ); - zSep = ", "; - } - } - } - } - return zList; -} - -/* -** Return a nul-terminated string consisting of nByte comma separated -** "?" expressions. For example, if nByte is 3, return a pointer to -** a buffer containing the string "?,?,?". -** -** The memory for the returned string is obtained from sqlite3_malloc(). -** It is the responsibility of the caller to eventually free it using -** sqlite3_free(). -** -** If an OOM error is encountered when allocating space for the new -** string, an error code is left in the rbu handle passed as the first -** argument and NULL is returned. Or, if an error has already occurred -** when this function is called, NULL is returned immediately, without -** attempting the allocation or modifying the stored error code. -*/ -static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){ - char *zRet = 0; - sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1; - - zRet = (char*)rbuMalloc(p, nByte); - if( zRet ){ - int i; - for(i=0; izIdx==0 ); - if( p->rc==SQLITE_OK ){ - const char *zSep = "PRIMARY KEY("; - sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */ - sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = */ - - p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl) - ); - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){ - const char *zOrig = (const char*)sqlite3_column_text(pXList,3); - if( zOrig && strcmp(zOrig, "pk")==0 ){ - const char *zIdx = (const char*)sqlite3_column_text(pXList,1); - if( zIdx ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) - ); - } - break; - } - } - rbuFinalize(p, pXList); - - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - if( sqlite3_column_int(pXInfo, 5) ){ - /* int iCid = sqlite3_column_int(pXInfo, 0); */ - const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2); - const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : ""; - z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc); - zSep = ", "; - } - } - z = rbuMPrintf(p, "%z)", z); - rbuFinalize(p, pXInfo); - } - return z; -} - -/* -** This function creates the second imposter table used when writing to -** a table b-tree where the table has an external primary key. If the -** iterator passed as the second argument does not currently point to -** a table (not index) with an external primary key, this function is a -** no-op. -** -** Assuming the iterator does point to a table with an external PK, this -** function creates a WITHOUT ROWID imposter table named "rbu_imposter2" -** used to access that PK index. For example, if the target table is -** declared as follows: -** -** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c)); -** -** then the imposter table schema is: -** -** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID; -** -*/ -static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){ - if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){ - int tnum = pIter->iPkTnum; /* Root page of PK index */ - sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */ - const char *zIdx = 0; /* Name of PK index */ - sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */ - const char *zComma = ""; - char *zCols = 0; /* Used to build up list of table cols */ - char *zPk = 0; /* Used to build up table PK declaration */ - - /* Figure out the name of the primary key index for the current table. - ** This is needed for the argument to "PRAGMA index_xinfo". Set - ** zIdx to point to a nul-terminated string containing this name. */ - p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, - "SELECT name FROM sqlite_schema WHERE rootpage = ?" - ); - if( p->rc==SQLITE_OK ){ - sqlite3_bind_int(pQuery, 1, tnum); - if( SQLITE_ROW==sqlite3_step(pQuery) ){ - zIdx = (const char*)sqlite3_column_text(pQuery, 0); - } - } - if( zIdx ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg, - sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx) - ); - } - rbuFinalize(p, pQuery); - - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){ - int bKey = sqlite3_column_int(pXInfo, 5); - if( bKey ){ - int iCid = sqlite3_column_int(pXInfo, 1); - int bDesc = sqlite3_column_int(pXInfo, 3); - const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4); - zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma, - iCid, pIter->azTblType[iCid], zCollate - ); - zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":""); - zComma = ", "; - } - } - zCols = rbuMPrintf(p, "%z, id INTEGER", zCols); - rbuFinalize(p, pXInfo); - - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); - rbuMPrintfExec(p, p->dbMain, - "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", - zCols, zPk - ); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); - } -} - -/* -** If an error has already occurred when this function is called, it -** immediately returns zero (without doing any work). Or, if an error -** occurs during the execution of this function, it sets the error code -** in the sqlite3rbu object indicated by the first argument and returns -** zero. -** -** The iterator passed as the second argument is guaranteed to point to -** a table (not an index) when this function is called. This function -** attempts to create any imposter table required to write to the main -** table b-tree of the table before returning. Non-zero is returned if -** an imposter table are created, or zero otherwise. -** -** An imposter table is required in all cases except RBU_PK_VTAB. Only -** virtual tables are written to directly. The imposter table has the -** same schema as the actual target table (less any UNIQUE constraints). -** More precisely, the "same schema" means the same columns, types, -** collation sequences. For tables that do not have an external PRIMARY -** KEY, it also means the same PRIMARY KEY declaration. -*/ -static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){ - if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){ - int tnum = pIter->iTnum; - const char *zComma = ""; - char *zSql = 0; - int iCol; - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); - - for(iCol=0; p->rc==SQLITE_OK && iColnTblCol; iCol++){ - const char *zPk = ""; - const char *zCol = pIter->azTblCol[iCol]; - const char *zColl = 0; - - p->rc = sqlite3_table_column_metadata( - p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0 - ); - - if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){ - /* If the target table column is an "INTEGER PRIMARY KEY", add - ** "PRIMARY KEY" to the imposter table column declaration. */ - zPk = "PRIMARY KEY "; - } - zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s", - zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl, - (pIter->abNotNull[iCol] ? " NOT NULL" : "") - ); - zComma = ", "; - } - - if( pIter->eType==RBU_PK_WITHOUT_ROWID ){ - char *zPk = rbuWithoutRowidPK(p, pIter); - if( zPk ){ - zSql = rbuMPrintf(p, "%z, %z", zSql, zPk); - } - } - - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum); - rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", - pIter->zTbl, zSql, - (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "") - ); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); - } -} - -/* -** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table. -** Specifically a statement of the form: -** -** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...); -** -** The number of bound variables is equal to the number of columns in -** the target table, plus one (for the rbu_control column), plus one more -** (for the rbu_rowid column) if the target table is an implicit IPK or -** virtual table. -*/ -static void rbuObjIterPrepareTmpInsert( - sqlite3rbu *p, - RbuObjIter *pIter, - const char *zCollist, - const char *zRbuRowid -){ - int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE); - char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid); - if( zBind ){ - assert( pIter->pTmpInsert==0 ); - p->rc = prepareFreeAndCollectError( - p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf( - "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", - p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind - )); - } -} - -static void rbuTmpInsertFunc( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - sqlite3rbu *p = sqlite3_user_data(pCtx); - int rc = SQLITE_OK; - int i; - - assert( sqlite3_value_int(apVal[0])!=0 - || p->objiter.eType==RBU_PK_EXTERNAL - || p->objiter.eType==RBU_PK_NONE - ); - if( sqlite3_value_int(apVal[0])!=0 ){ - p->nPhaseOneStep += p->objiter.nIndex; - } - - for(i=0; rc==SQLITE_OK && iobjiter.pTmpInsert, i+1, apVal[i]); - } - if( rc==SQLITE_OK ){ - sqlite3_step(p->objiter.pTmpInsert); - rc = sqlite3_reset(p->objiter.pTmpInsert); - } - - if( rc!=SQLITE_OK ){ - sqlite3_result_error_code(pCtx, rc); - } -} - -static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){ - sqlite3_stmt *pStmt = 0; - int rc = p->rc; - char *zRet = 0; - - assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 ); - - if( rc==SQLITE_OK ){ - rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, - "SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?" - ); - } - if( rc==SQLITE_OK ){ - int rc2; - rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC); - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - char *zSql = (char*)sqlite3_column_text(pStmt, 0); - if( zSql ){ - pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc); - } - if( zSql ){ - int nParen = 0; /* Number of open parenthesis */ - int i; - int iIdxCol = 0; - int nIdxAlloc = 0; - for(i=0; zSql[i]; i++){ - char c = zSql[i]; - - /* If necessary, grow the pIter->aIdxCol[] array */ - if( iIdxCol==nIdxAlloc ){ - RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc( - pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan) - ); - if( aIdxCol==0 ){ - rc = SQLITE_NOMEM; - break; - } - pIter->aIdxCol = aIdxCol; - nIdxAlloc += 16; - } - - if( c=='(' ){ - if( nParen==0 ){ - assert( iIdxCol==0 ); - pIter->aIdxCol[0].zSpan = &zSql[i+1]; - } - nParen++; - } - else if( c==')' ){ - nParen--; - if( nParen==0 ){ - int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan; - pIter->aIdxCol[iIdxCol++].nSpan = nSpan; - i++; - break; - } - }else if( c==',' && nParen==1 ){ - int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan; - pIter->aIdxCol[iIdxCol++].nSpan = nSpan; - pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1]; - }else if( c=='"' || c=='\'' || c=='`' ){ - for(i++; 1; i++){ - if( zSql[i]==c ){ - if( zSql[i+1]!=c ) break; - i++; - } - } - }else if( c=='[' ){ - for(i++; 1; i++){ - if( zSql[i]==']' ) break; - } - }else if( c=='-' && zSql[i+1]=='-' ){ - for(i=i+2; zSql[i] && zSql[i]!='\n'; i++); - if( zSql[i]=='\0' ) break; - }else if( c=='/' && zSql[i+1]=='*' ){ - for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++); - if( zSql[i]=='\0' ) break; - i++; - } - } - if( zSql[i] ){ - zRet = rbuStrndup(&zSql[i], &rc); - } - pIter->nIdxCol = iIdxCol; - } - } - - rc2 = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ) rc = rc2; - } - - p->rc = rc; - return zRet; -} - -/* -** Ensure that the SQLite statement handles required to update the -** target database object currently indicated by the iterator passed -** as the second argument are available. -*/ -static int rbuObjIterPrepareAll( - sqlite3rbu *p, - RbuObjIter *pIter, - int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */ -){ - assert( pIter->bCleanup==0 ); - if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){ - const int tnum = pIter->iTnum; - char *zCollist = 0; /* List of indexed columns */ - char **pz = &p->zErrmsg; - const char *zIdx = pIter->zIdx; - char *zLimit = 0; - - if( nOffset ){ - zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset); - if( !zLimit ) p->rc = SQLITE_NOMEM; - } - - if( zIdx ){ - const char *zTbl = pIter->zTbl; - char *zImposterCols = 0; /* Columns for imposter table */ - char *zImposterPK = 0; /* Primary key declaration for imposter */ - char *zWhere = 0; /* WHERE clause on PK columns */ - char *zBind = 0; - char *zPart = 0; - int nBind = 0; - - assert( pIter->eType!=RBU_PK_VTAB ); - zPart = rbuObjIterGetIndexWhere(p, pIter); - zCollist = rbuObjIterGetIndexCols( - p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind - ); - zBind = rbuObjIterGetBindlist(p, nBind); - - /* Create the imposter table used to write to this index. */ - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum); - rbuMPrintfExec(p, p->dbMain, - "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID", - zTbl, zImposterCols, zImposterPK - ); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0); - - /* Create the statement to insert index entries */ - pIter->nCol = nBind; - if( p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError( - p->dbMain, &pIter->pInsert, &p->zErrmsg, - sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind) - ); - } - - /* And to delete index entries */ - if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError( - p->dbMain, &pIter->pDelete, &p->zErrmsg, - sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere) - ); - } - - /* Create the SELECT statement to read keys in sorted order */ - if( p->rc==SQLITE_OK ){ - char *zSql; - if( rbuIsVacuum(p) ){ - char *zStart = 0; - if( nOffset ){ - zStart = rbuVacuumIndexStart(p, pIter); - if( zStart ){ - sqlite3_free(zLimit); - zLimit = 0; - } - } - - zSql = sqlite3_mprintf( - "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s", - zCollist, - pIter->zDataTbl, - zPart, - (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart, - zCollist, zLimit - ); - sqlite3_free(zStart); - }else - - if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ - zSql = sqlite3_mprintf( - "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s", - zCollist, p->zStateDb, pIter->zDataTbl, - zPart, zCollist, zLimit - ); - }else{ - zSql = sqlite3_mprintf( - "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s " - "UNION ALL " - "SELECT %s, rbu_control FROM '%q' " - "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 " - "ORDER BY %s%s", - zCollist, p->zStateDb, pIter->zDataTbl, zPart, - zCollist, pIter->zDataTbl, - zPart, - (zPart ? "AND" : "WHERE"), - zCollist, zLimit - ); - } - if( p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql); - }else{ - sqlite3_free(zSql); - } - } - - sqlite3_free(zImposterCols); - sqlite3_free(zImposterPK); - sqlite3_free(zWhere); - sqlite3_free(zBind); - sqlite3_free(zPart); - }else{ - int bRbuRowid = (pIter->eType==RBU_PK_VTAB) - ||(pIter->eType==RBU_PK_NONE) - ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)); - const char *zTbl = pIter->zTbl; /* Table this step applies to */ - const char *zWrite; /* Imposter table name */ - - char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid); - char *zWhere = rbuObjIterGetWhere(p, pIter); - char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old"); - char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new"); - - zCollist = rbuObjIterGetCollist(p, pIter); - pIter->nCol = pIter->nTblCol; - - /* Create the imposter table or tables (if required). */ - rbuCreateImposterTable(p, pIter); - rbuCreateImposterTable2(p, pIter); - zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_"); - - /* Create the INSERT statement to write to the target PK b-tree */ - if( p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz, - sqlite3_mprintf( - "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", - zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings - ) - ); - } - - /* Create the DELETE statement to write to the target PK b-tree. - ** Because it only performs INSERT operations, this is not required for - ** an rbu vacuum handle. */ - if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz, - sqlite3_mprintf( - "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere - ) - ); - } - - if( rbuIsVacuum(p)==0 && pIter->abIndexed ){ - const char *zRbuRowid = ""; - if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ - zRbuRowid = ", rbu_rowid"; - } - - /* Create the rbu_tmp_xxx table and the triggers to populate it. */ - rbuMPrintfExec(p, p->dbRbu, - "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS " - "SELECT *%s FROM '%q' WHERE 0;" - , p->zStateDb, pIter->zDataTbl - , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "") - , pIter->zDataTbl - ); - - rbuMPrintfExec(p, p->dbMain, - "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" " - "BEGIN " - " SELECT rbu_tmp_insert(3, %s);" - "END;" - - "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" " - "BEGIN " - " SELECT rbu_tmp_insert(3, %s);" - "END;" - - "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" " - "BEGIN " - " SELECT rbu_tmp_insert(4, %s);" - "END;", - zWrite, zTbl, zOldlist, - zWrite, zTbl, zOldlist, - zWrite, zTbl, zNewlist - ); - - if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ - rbuMPrintfExec(p, p->dbMain, - "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" " - "BEGIN " - " SELECT rbu_tmp_insert(0, %s);" - "END;", - zWrite, zTbl, zNewlist - ); - } - - rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid); - } - - /* Create the SELECT statement to read keys from data_xxx */ - if( p->rc==SQLITE_OK ){ - const char *zRbuRowid = ""; - char *zStart = 0; - char *zOrder = 0; - if( bRbuRowid ){ - zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid"; - } - - if( rbuIsVacuum(p) ){ - if( nOffset ){ - zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite); - if( zStart ){ - sqlite3_free(zLimit); - zLimit = 0; - } - } - if( bRbuRowid ){ - zOrder = rbuMPrintf(p, "_rowid_"); - }else{ - zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", ""); - } - } - - if( p->rc==SQLITE_OK ){ - p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, - sqlite3_mprintf( - "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s", - zCollist, - (rbuIsVacuum(p) ? "0 AS " : ""), - zRbuRowid, - pIter->zDataTbl, (zStart ? zStart : ""), - (zOrder ? "ORDER BY" : ""), zOrder, - zLimit - ) - ); - } - sqlite3_free(zStart); - sqlite3_free(zOrder); - } - - sqlite3_free(zWhere); - sqlite3_free(zOldlist); - sqlite3_free(zNewlist); - sqlite3_free(zBindings); - } - sqlite3_free(zCollist); - sqlite3_free(zLimit); - } - - return p->rc; -} - -/* -** Set output variable *ppStmt to point to an UPDATE statement that may -** be used to update the imposter table for the main table b-tree of the -** table object that pIter currently points to, assuming that the -** rbu_control column of the data_xyz table contains zMask. -** -** If the zMask string does not specify any columns to update, then this -** is not an error. Output variable *ppStmt is set to NULL in this case. -*/ -static int rbuGetUpdateStmt( - sqlite3rbu *p, /* RBU handle */ - RbuObjIter *pIter, /* Object iterator */ - const char *zMask, /* rbu_control value ('x.x.') */ - sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */ -){ - RbuUpdateStmt **pp; - RbuUpdateStmt *pUp = 0; - int nUp = 0; - - /* In case an error occurs */ - *ppStmt = 0; - - /* Search for an existing statement. If one is found, shift it to the front - ** of the LRU queue and return immediately. Otherwise, leave nUp pointing - ** to the number of statements currently in the cache and pUp to the - ** last object in the list. */ - for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){ - pUp = *pp; - if( strcmp(pUp->zMask, zMask)==0 ){ - *pp = pUp->pNext; - pUp->pNext = pIter->pRbuUpdate; - pIter->pRbuUpdate = pUp; - *ppStmt = pUp->pUpdate; - return SQLITE_OK; - } - nUp++; - } - assert( pUp==0 || pUp->pNext==0 ); - - if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){ - for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext)); - *pp = 0; - sqlite3_finalize(pUp->pUpdate); - pUp->pUpdate = 0; - }else{ - pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1); - } - - if( pUp ){ - char *zWhere = rbuObjIterGetWhere(p, pIter); - char *zSet = rbuObjIterGetSetlist(p, pIter, zMask); - char *zUpdate = 0; - - pUp->zMask = (char*)&pUp[1]; - memcpy(pUp->zMask, zMask, pIter->nTblCol); - pUp->pNext = pIter->pRbuUpdate; - pIter->pRbuUpdate = pUp; - - if( zSet ){ - const char *zPrefix = ""; - - if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_"; - zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", - zPrefix, pIter->zTbl, zSet, zWhere - ); - p->rc = prepareFreeAndCollectError( - p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate - ); - *ppStmt = pUp->pUpdate; - } - sqlite3_free(zWhere); - sqlite3_free(zSet); - } - - return p->rc; -} - -static sqlite3 *rbuOpenDbhandle( - sqlite3rbu *p, - const char *zName, - int bUseVfs -){ - sqlite3 *db = 0; - if( p->rc==SQLITE_OK ){ - const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI; - p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0); - if( p->rc ){ - p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - sqlite3_close(db); - db = 0; - } - } - return db; -} - -/* -** Free an RbuState object allocated by rbuLoadState(). -*/ -static void rbuFreeState(RbuState *p){ - if( p ){ - sqlite3_free(p->zTbl); - sqlite3_free(p->zDataTbl); - sqlite3_free(p->zIdx); - sqlite3_free(p); - } -} - -/* -** Allocate an RbuState object and load the contents of the rbu_state -** table into it. Return a pointer to the new object. It is the -** responsibility of the caller to eventually free the object using -** sqlite3_free(). -** -** If an error occurs, leave an error code and message in the rbu handle -** and return NULL. -*/ -static RbuState *rbuLoadState(sqlite3rbu *p){ - RbuState *pRet = 0; - sqlite3_stmt *pStmt = 0; - int rc; - int rc2; - - pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState)); - if( pRet==0 ) return 0; - - rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, - sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb) - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - switch( sqlite3_column_int(pStmt, 0) ){ - case RBU_STATE_STAGE: - pRet->eStage = sqlite3_column_int(pStmt, 1); - if( pRet->eStage!=RBU_STAGE_OAL - && pRet->eStage!=RBU_STAGE_MOVE - && pRet->eStage!=RBU_STAGE_CKPT - ){ - p->rc = SQLITE_CORRUPT; - } - break; - - case RBU_STATE_TBL: - pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); - break; - - case RBU_STATE_IDX: - pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); - break; - - case RBU_STATE_ROW: - pRet->nRow = sqlite3_column_int(pStmt, 1); - break; - - case RBU_STATE_PROGRESS: - pRet->nProgress = sqlite3_column_int64(pStmt, 1); - break; - - case RBU_STATE_CKPT: - pRet->iWalCksum = sqlite3_column_int64(pStmt, 1); - break; - - case RBU_STATE_COOKIE: - pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1); - break; - - case RBU_STATE_OALSZ: - pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1); - break; - - case RBU_STATE_PHASEONESTEP: - pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1); - break; - - case RBU_STATE_DATATBL: - pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc); - break; - - default: - rc = SQLITE_CORRUPT; - break; - } - } - rc2 = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ) rc = rc2; - - p->rc = rc; - return pRet; -} - - -/* -** Open the database handle and attach the RBU database as "rbu". If an -** error occurs, leave an error code and message in the RBU handle. -*/ -static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){ - assert( p->rc || (p->dbMain==0 && p->dbRbu==0) ); - assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 ); - - /* Open the RBU database */ - p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1); - - if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ - sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); - if( p->zState==0 ){ - const char *zFile = sqlite3_db_filename(p->dbRbu, "main"); - p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile); - } - } - - /* If using separate RBU and state databases, attach the state database to - ** the RBU db handle now. */ - if( p->zState ){ - rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState); - memcpy(p->zStateDb, "stat", 4); - }else{ - memcpy(p->zStateDb, "main", 4); - } - -#if 0 - if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ - p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0); - } -#endif - - /* If it has not already been created, create the rbu_state table */ - rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb); - -#if 0 - if( rbuIsVacuum(p) ){ - if( p->rc==SQLITE_OK ){ - int rc2; - int bOk = 0; - sqlite3_stmt *pCnt = 0; - p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg, - "SELECT count(*) FROM stat.sqlite_schema" - ); - if( p->rc==SQLITE_OK - && sqlite3_step(pCnt)==SQLITE_ROW - && 1==sqlite3_column_int(pCnt, 0) - ){ - bOk = 1; - } - rc2 = sqlite3_finalize(pCnt); - if( p->rc==SQLITE_OK ) p->rc = rc2; - - if( p->rc==SQLITE_OK && bOk==0 ){ - p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("invalid state database"); - } - - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0); - } - } - } -#endif - - if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){ - int bOpen = 0; - int rc; - p->nRbu = 0; - p->pRbuFd = 0; - rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p); - if( rc!=SQLITE_NOTFOUND ) p->rc = rc; - if( p->eStage>=RBU_STAGE_MOVE ){ - bOpen = 1; - }else{ - RbuState *pState = rbuLoadState(p); - if( pState ){ - bOpen = (pState->eStage>=RBU_STAGE_MOVE); - rbuFreeState(pState); - } - } - if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1); - } - - p->eStage = 0; - if( p->rc==SQLITE_OK && p->dbMain==0 ){ - if( !rbuIsVacuum(p) ){ - p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1); - }else if( p->pRbuFd->pWalFd ){ - if( pbRetry ){ - p->pRbuFd->bNolock = 0; - sqlite3_close(p->dbRbu); - sqlite3_close(p->dbMain); - p->dbMain = 0; - p->dbRbu = 0; - *pbRetry = 1; - return; - } - p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database"); - }else{ - char *zTarget; - char *zExtra = 0; - if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){ - zExtra = &p->zRbu[5]; - while( *zExtra ){ - if( *zExtra++=='?' ) break; - } - if( *zExtra=='\0' ) zExtra = 0; - } - - zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s", - sqlite3_db_filename(p->dbRbu, "main"), - (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra) - ); - - if( zTarget==0 ){ - p->rc = SQLITE_NOMEM; - return; - } - p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1); - sqlite3_free(zTarget); - } - } - - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_create_function(p->dbMain, - "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0 - ); - } - - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_create_function(p->dbMain, - "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0 - ); - } - - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_create_function(p->dbRbu, - "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0 - ); - } - - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); - } - rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema"); - - /* Mark the database file just opened as an RBU target database. If - ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use. - ** This is an error. */ - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p); - } - - if( p->rc==SQLITE_NOTFOUND ){ - p->rc = SQLITE_ERROR; - p->zErrmsg = sqlite3_mprintf("rbu vfs not found"); - } -} - -/* -** This routine is a copy of the sqlite3FileSuffix3() routine from the core. -** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined. -** -** 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 -*/ -static void rbuFileSuffix3(const char *zBase, char *z){ -#ifdef SQLITE_ENABLE_8_3_NAMES -#if SQLITE_ENABLE_8_3_NAMES<2 - if( sqlite3_uri_boolean(zBase, "8_3_names", 0) ) -#endif - { - int i, sz; - sz = (int)strlen(z)&0xffffff; - for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} - if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4); - } -#endif -} - -/* -** Return the current wal-index header checksum for the target database -** as a 64-bit integer. -** -** The checksum is store in the first page of xShmMap memory as an 8-byte -** blob starting at byte offset 40. -*/ -static i64 rbuShmChecksum(sqlite3rbu *p){ - i64 iRet = 0; - if( p->rc==SQLITE_OK ){ - sqlite3_file *pDb = p->pTargetFd->pReal; - u32 volatile *ptr; - p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr); - if( p->rc==SQLITE_OK ){ - iRet = ((i64)ptr[10] << 32) + ptr[11]; - } - } - return iRet; -} - -/* -** This function is called as part of initializing or reinitializing an -** incremental checkpoint. -** -** It populates the sqlite3rbu.aFrame[] array with the set of -** (wal frame -> db page) copy operations required to checkpoint the -** current wal file, and obtains the set of shm locks required to safely -** perform the copy operations directly on the file-system. -** -** If argument pState is not NULL, then the incremental checkpoint is -** being resumed. In this case, if the checksum of the wal-index-header -** following recovery is not the same as the checksum saved in the RbuState -** object, then the rbu handle is set to DONE state. This occurs if some -** other client appends a transaction to the wal file in the middle of -** an incremental checkpoint. -*/ -static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){ - - /* If pState is NULL, then the wal file may not have been opened and - ** recovered. Running a read-statement here to ensure that doing so - ** does not interfere with the "capture" process below. */ - if( pState==0 ){ - p->eStage = 0; - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_schema", 0, 0, 0); - } - } - - /* Assuming no error has occurred, run a "restart" checkpoint with the - ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following - ** special behaviour in the rbu VFS: - ** - ** * If the exclusive shm WRITER or READ0 lock cannot be obtained, - ** the checkpoint fails with SQLITE_BUSY (normally SQLite would - ** proceed with running a passive checkpoint instead of failing). - ** - ** * Attempts to read from the *-wal file or write to the database file - ** do not perform any IO. Instead, the frame/page combinations that - ** would be read/written are recorded in the sqlite3rbu.aFrame[] - ** array. - ** - ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, - ** READ0 and CHECKPOINT locks taken as part of the checkpoint are - ** no-ops. These locks will not be released until the connection - ** is closed. - ** - ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL - ** error. - ** - ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the - ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[] - ** array populated with a set of (frame -> page) mappings. Because the - ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy - ** data from the wal file into the database file according to the - ** contents of aFrame[]. - */ - if( p->rc==SQLITE_OK ){ - int rc2; - p->eStage = RBU_STAGE_CAPTURE; - rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0); - if( rc2!=SQLITE_INTERNAL ) p->rc = rc2; - } - - if( p->rc==SQLITE_OK && p->nFrame>0 ){ - p->eStage = RBU_STAGE_CKPT; - p->nStep = (pState ? pState->nRow : 0); - p->aBuf = rbuMalloc(p, p->pgsz); - p->iWalCksum = rbuShmChecksum(p); - } - - if( p->rc==SQLITE_OK ){ - if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){ - p->rc = SQLITE_DONE; - p->eStage = RBU_STAGE_DONE; - }else{ - int nSectorSize; - sqlite3_file *pDb = p->pTargetFd->pReal; - sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal; - assert( p->nPagePerSector==0 ); - nSectorSize = pDb->pMethods->xSectorSize(pDb); - if( nSectorSize>p->pgsz ){ - p->nPagePerSector = nSectorSize / p->pgsz; - }else{ - p->nPagePerSector = 1; - } - - /* Call xSync() on the wal file. This causes SQLite to sync the - ** directory in which the target database and the wal file reside, in - ** case it has not been synced since the rename() call in - ** rbuMoveOalFile(). */ - p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL); - } - } -} - -/* -** Called when iAmt bytes are read from offset iOff of the wal file while -** the rbu object is in capture mode. Record the frame number of the frame -** being read in the aFrame[] array. -*/ -static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){ - const u32 mReq = (1<mLock!=mReq ){ - pRbu->rc = SQLITE_BUSY; - return SQLITE_INTERNAL; - } - - pRbu->pgsz = iAmt; - if( pRbu->nFrame==pRbu->nFrameAlloc ){ - int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2; - RbuFrame *aNew; - aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame)); - if( aNew==0 ) return SQLITE_NOMEM; - pRbu->aFrame = aNew; - pRbu->nFrameAlloc = nNew; - } - - iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1; - if( pRbu->iMaxFrame